An open-source, self-hosted system for apps built with web technologies.
Release System 0.1.53
zohayrslileh06645b4ae0f4
diff --git a/bun.lock b/bun.lockindex 260ae84..b340c04 100644--- a/bun.lock+++ b/bun.lock@@ -8,8 +8,10 @@"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1","@msgpack/msgpack": "^3.1.3",- "@phreshos/client": "^0.1.29",- "@phreshos/server": "^0.1.32",+ "@the-link/client": "^0.2.0",+ "@the-link/core": "^0.2.0",+ "@the-link/react": "^0.2.0",+ "@the-link/server": "^0.2.0","cfonts": "^3.3.1","get-port": "^7.2.0","gsap": "^3.15.0",@@ -234,14 +236,10 @@"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-nuhZIOLuI6TFQ32I/WnUx+SCPY7SdSKwgnFHydAuoS1+Z4BRcaP+RRJmGzl9lw+0OFF7UmaESf7KQRXaNLHypg=="],- "@phreshos/client": ["@phreshos/[email protected]", "", { "dependencies": { "@msgpack/msgpack": "^3.1.3" }, "peerDependencies": { "@phreshos/core": "^0.1.31" } }, "sha512-3hoA+2XHYN26dW32hNvqBsh9wkiDIfSaFDDzavbsEkystdZADmQbM3KkNDPnGdgzLqKAbvILhbsv5TSwJU20ew=="],-"@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-ilIAUYEeldEgfgdNrANu36eLcKCgh5Usc72PnFSIfBV3jsRxKRKrIEBEcnOHoiwvKMjo5cgBi3mPo8CvYy5LMg=="],"@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "react-aria-components": "^1.20.0" }, "peerDependencies": { "@phreshos/core": "^0.1.31", "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-4ukMLfoP/zWk6tNd+pTmqONka9TakyxzVF+rRCY34fxHu/8KV2KJ+AT6B+oaWtXr/J0/Ay4nXDt2EL5tbcp/eg=="],- "@phreshos/server": ["@phreshos/[email protected]", "", { "dependencies": { "@msgpack/msgpack": "^3.1.3" }, "peerDependencies": { "@phreshos/core": "^0.1.31" } }, "sha512-7yl0lXWEcnvIxGFjo7Wb6y6gc8OHUafKJZkVS2rrJfMH9Mb8Km+Hlj/E295Nzh2EHJ6NU58psemtdmahC7gHvA=="],-"@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=="],"@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-jHC2cnyKz5xU2fhECtFl8OZ83cYNt13GZQD+0uMJ/X3o+ijmd56okHhTUwxVSHPx1IRVIJEZ1/1pPzeLCU6XKA=="],@@ -308,6 +306,14 @@"@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "tailwindcss": "4.3.3" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw=="],+ "@the-link/client": ["@the-link/[email protected]", "", { "dependencies": { "@the-link/core": "^0.2.0", "uuid": "^14.0.1" } }, "sha512-vMuGWKqJb1cCgtHy/w6+H3kN5qkrUFJFGPvBYGV/YvI1LtD/9K5iVxQutTZe1Efks3CwgiV/lbwJXl9FbA/QTg=="],++ "@the-link/core": ["@the-link/[email protected]", "", { "dependencies": { "uuid": "^14.0.1" } }, "sha512-xUbgY24gn1id1uOM194PiWdgJMw8ApF/Ujjs8E7ENN9jEVJzriwGywF171WeFU7o3azj009HUjfvh7crafOGlA=="],++ "@the-link/react": ["@the-link/[email protected]", "", { "peerDependencies": { "@the-link/core": "^0.2.0", "react": "^19.2.0" } }, "sha512-HhWA3s1bWkrzee5IUs122AOvdkL21ckIbqFkg2nsTsBqHuS2XapfxIeZGJw+PVB3za9aC+wSEuTcLKH75WKgVg=="],++ "@the-link/server": ["@the-link/[email protected]", "", { "dependencies": { "@the-link/core": "^0.2.0", "hono": "^4.13.2", "uuid": "^14.0.1" } }, "sha512-UJ4WTxDQ3gb9UKhcPwSiFNQ0FhoEuNUY7xk+qiji72uGKVsT13dzFueEVr4iKnwJ8h39g+phkeFeK+ekVHyvFw=="],+"@types/adm-zip": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q=="],"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg=="],diff --git a/package.json b/package.jsonindex e8c8411..6357ecf 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "phreshos","displayName": "PhreshOS",- "version": "0.1.52",+ "version": "0.1.53","description": "The PhreshOS server, desktop, and authoritative system runtime.","type": "module","private": true,@@ -38,8 +38,10 @@"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1","@msgpack/msgpack": "^3.1.3",- "@phreshos/client": "^0.1.29",- "@phreshos/server": "^0.1.32",+ "@the-link/client": "^0.2.0",+ "@the-link/core": "^0.2.0",+ "@the-link/react": "^0.2.0",+ "@the-link/server": "^0.2.0","cfonts": "^3.3.1","get-port": "^7.2.0","gsap": "^3.15.0",diff --git a/scripts/contracts/process-lifecycle.ts b/scripts/contracts/process-lifecycle.tsindex 1533113..01ad888 100644--- a/scripts/contracts/process-lifecycle.ts+++ b/scripts/contracts/process-lifecycle.ts@@ -1,5 +1,5 @@import assert from "node:assert/strict"-import TheLink from "@libs/the-link/the-link"+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"diff --git a/scripts/contracts/readiness.tsx b/scripts/contracts/readiness.tsxindex 37b701e..c463332 100644--- a/scripts/contracts/readiness.tsx+++ b/scripts/contracts/readiness.tsx@@ -1,7 +1,6 @@import assert from "node:assert/strict"import { renderToStaticMarkup } from "react-dom/server"-import Readiness from "@libs/readiness/main"-import ReadinessState from "@libs/readiness/state"+import Readiness, { ReadinessState } from "@libs/readiness"const startup = ReadinessState.start(["connection", "session", "wallpaper"])diff --git a/source/client/core/application.ts b/source/client/core/application.tsindex d6e7862..4c98566 100644--- a/source/client/core/application.ts+++ b/source/client/core/application.ts@@ -1,4 +1,4 @@-import ClientLink from "@libs/the-link/plugins/client-link/client-link"+import { ClientLink } from "@the-link/client"import { type ProxyOutcome, type ProxyRequest, type ProxyResponse, proxyMediaType } from "@server/core/protocol/proxy"import { storageMediaType, type StorageRequest } from "@server/core/protocol/storage"import { frame, frameBlob, unframe } from "@libs/framing"diff --git a/source/client/core/link-manager/auth-manager/auth-manager.ts b/source/client/core/link-manager/auth-manager/auth-manager.tsindex 51a6620..2f0584d 100644--- a/source/client/core/link-manager/auth-manager/auth-manager.ts+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts@@ -1,9 +1,9 @@import { TransmittedAuthManager } from "@server/core/link-manager/auth-manager/auth-manager"-import { Intercept } from "@libs/the-link/decorators/escript"+import { Intercept } from "@the-link/core/decorators"import ProcessManager from "./process-manager/process-manager"import ProgramManager from "./program-manager/program-manager"import DialogManager from "./dialog-manager"-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"import LinkManager from "../link-manager"import { type PermissionDecision, type PermissionName } from "@phreshos/core"diff --git a/source/client/core/link-manager/auth-manager/dialog-manager.ts b/source/client/core/link-manager/auth-manager/dialog-manager.tsindex f6f8b39..6233993 100644--- a/source/client/core/link-manager/auth-manager/dialog-manager.ts+++ b/source/client/core/link-manager/auth-manager/dialog-manager.ts@@ -1,6 +1,6 @@import { type PermissionChoice, type SystemDialog, type TransmittedDialogManager } from "@server/core/dialog-manager"-import { Publish, Subscribe } from "@libs/the-link/decorators/escript"-import TheLink from "@libs/the-link/the-link"+import { Publish, Subscribe } from "@the-link/core/decorators"+import { TheLink } from "@the-link/core"import AuthManager from "./auth-manager"/** Synchronized desktop counterpart of the authoritative system-dialog queue. */diff --git a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/client/core/link-manager/auth-manager/process-manager/process-manager.tsindex 90620d8..1489f52 100644--- a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts+++ b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts@@ -1,8 +1,8 @@import { TransmittedProcessManager } from "@server/core/link-manager/auth-manager/process-manager/process-manager"import { TransmittedProcess } from "@server/core/link-manager/auth-manager/process-manager/process"import { TransmittedWindow } from "@server/core/link-manager/auth-manager/process-manager/window"-import { Publish, Subscribe } from "@libs/the-link/decorators/escript"-import TheLink from "@libs/the-link/the-link"+import { Publish, Subscribe } from "@the-link/core/decorators"+import { TheLink } from "@the-link/core"import AuthManager from "../auth-manager"import Process from "./process"import ProcessScope from "./process-scope"diff --git a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/client/core/link-manager/auth-manager/program-manager/program-manager.tsindex 3fc8969..86f00a2 100644--- a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts+++ b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts@@ -1,7 +1,7 @@import { TransmittedProgramManager } from "@server/core/link-manager/auth-manager/program-manager/program-manager"import { HostedEntry } from "@server/core/link-manager/auth-manager/program-manager/entry"-import { Publish, Subscribe } from "@libs/the-link/decorators/escript"-import TheLink from "@libs/the-link/the-link"+import { Publish, Subscribe } from "@the-link/core/decorators"+import { TheLink } from "@the-link/core"import AuthManager from "../auth-manager"import Program from "./program"import { type Launch, type ProgramCommandChunk, type ProgramIconSize } from "@phreshos/core"diff --git a/source/client/core/link-manager/link-manager.ts b/source/client/core/link-manager/link-manager.tsindex a24d7b2..0df5712 100644--- a/source/client/core/link-manager/link-manager.ts+++ b/source/client/core/link-manager/link-manager.ts@@ -3,9 +3,9 @@ import { TransmittedLinkManager } from "@server/core/link-manager/link-manager"import { type AuthenticationState } from "@server/core/authentication/authentication"import { type RegistrationResponse } from "@server/core/link-manager/link-manager"import { type Appearance, type DesktopPreferences, type DesktopPreferencesUpdate } from "@phreshos/core"-import { Forward } from "@libs/the-link/decorators/escript"-import TheLink from "@libs/the-link/the-link"-import Property from "@libs/the-link/property"+import { Forward } from "@the-link/core/decorators"+import { TheLink } from "@the-link/core"+import { Property } from "@the-link/core"import Application from "../application"import { v4 as uuidv4 } from "uuid"import { type Outcome, unwrap } from "@server/core/outcome"diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.tsindex 888720d..2e23d49 100644--- a/source/client/view/components/desktop-host/announcements.ts+++ b/source/client/view/components/desktop-host/announcements.ts@@ -1,6 +1,6 @@import { type default as AuthManager } from "@client/core/link-manager/auth-manager/auth-manager"import { type HostedEntry } from "@server/core/link-manager/auth-manager/program-manager/entry"-import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"+import { ReactTunnel } from "@the-link/react"import { useCallback } from "react"import ClientProcessBoundary from "./client-process-boundary"import ClientTraffic from "./client-traffic"diff --git a/source/client/view/components/desktop-host/client-host.ts b/source/client/view/components/desktop-host/client-host.tsindex 6c35f0d..87b25af 100644--- a/source/client/view/components/desktop-host/client-host.ts+++ b/source/client/view/components/desktop-host/client-host.ts@@ -1,4 +1,4 @@-import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"+import { ReactTunnel } from "@the-link/react"import { isPermissionName, type DesktopSize, type DesktopSurfaceSnapshot } from "@phreshos/core"import useAnnouncements from "./announcements"import DesktopPointer from "./pointer"diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.tsindex 3205f19..bd59ed1 100644--- a/source/client/view/components/desktop-host/client-process-boundary.ts+++ b/source/client/view/components/desktop-host/client-process-boundary.ts@@ -1,5 +1,5 @@import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"import host, { TransferredAnswer } from "./host"import { type PointerHost } from "./pointer"import ClientTraffic from "./client-traffic"diff --git a/source/client/view/components/desktop-host/client-traffic.ts b/source/client/view/components/desktop-host/client-traffic.tsindex 5dcc03f..ae3e02b 100644--- a/source/client/view/components/desktop-host/client-traffic.ts+++ b/source/client/view/components/desktop-host/client-traffic.ts@@ -1,4 +1,4 @@-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"/** Desktop-local traffic routed only to subscribed client Process boundaries. */diff --git a/source/client/view/components/desktop-host/pointer.ts b/source/client/view/components/desktop-host/pointer.tsindex 2c11c41..6f8a03b 100644--- a/source/client/view/components/desktop-host/pointer.ts+++ b/source/client/view/components/desktop-host/pointer.ts@@ -1,5 +1,5 @@import { type RefObject } from "react"-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"import { type DesktopPointerPosition, type DesktopPointerSnapshot } from "@phreshos/core"/**diff --git a/source/client/view/components/window-manager/window-manager.ts b/source/client/view/components/window-manager/window-manager.tsindex d9d43b3..545fe76 100644--- a/source/client/view/components/window-manager/window-manager.ts+++ b/source/client/view/components/window-manager/window-manager.ts@@ -1,6 +1,6 @@import ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"import Process from "@client/core/link-manager/auth-manager/process-manager/process"-import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"+import { ReactTunnel } from "@the-link/react"import { Layer } from "@server/core/link-manager/auth-manager/program-manager/config"import { type Position, type Size, type Value } from "@phreshos/core"import { useCallback, useRef, useState } from "react"diff --git a/source/client/view/structure/authentication/authentication.tsx b/source/client/view/structure/authentication/authentication.tsxindex 61b2894..71f4cb8 100644--- a/source/client/view/structure/authentication/authentication.tsx+++ b/source/client/view/structure/authentication/authentication.tsx@@ -10,7 +10,7 @@ import Register from "./register"import { useState, type ReactNode } from "react"import { type AuthenticationState } from "@server/core/authentication/authentication"import { WallpaperStage } from "../desktop/wallpaper/wallpaper"-import { useReady } from "@libs/readiness/main"+import { useReady } from "@libs/readiness"import { useAppearance, useResolveTheme } from "@phreshos/react-ui"export default function () {diff --git a/source/client/view/structure/desktop/desktop.tsx b/source/client/view/structure/desktop/desktop.tsxindex de5278d..f467612 100644--- a/source/client/view/structure/desktop/desktop.tsx+++ b/source/client/view/structure/desktop/desktop.tsx@@ -16,7 +16,7 @@ import ProcessWindow from "./windows/process-window"import useWindows from "../../components/window-manager/window-manager"import { ReadyWallpaper, WallpaperBackground } from "./wallpaper/wallpaper"import Loading from "../../components/loading"-import { useRequirement } from "@libs/readiness/main"+import { useRequirement } from "@libs/readiness"import { useAppearance, useResolveTheme, useTheme } from "@phreshos/react-ui"export default function Workspace() {diff --git a/source/client/view/structure/desktop/programs/programs.ts b/source/client/view/structure/desktop/programs/programs.tsindex 51bb9d0..3eeaa1a 100644--- a/source/client/view/structure/desktop/programs/programs.ts+++ b/source/client/view/structure/desktop/programs/programs.ts@@ -1,4 +1,4 @@-import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"+import { ReactTunnel } from "@the-link/react"import { AuthManagerContext } from "@client/view/contexts"/**diff --git a/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx b/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsxindex 67e296b..d1c4c3a 100644--- a/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx+++ b/source/client/view/structure/desktop/taskbar/system/system-dialogs.tsx@@ -1,5 +1,5 @@import { type PermissionChoice, type PermissionDialog, type ServerCrashDialog } from "@server/core/dialog-manager"-import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"+import { ReactTunnel } from "@the-link/react"import { enterSurface, prepareSurfaceEntrance, restSurface } from "@client/view/appearance/surface-presence"import { useReducedMotion } from "@libs/react-motion"import { useAppearance, useResolveTheme, useScale } from "@phreshos/react-ui"diff --git a/source/client/view/structure/desktop/wallpaper/wallpaper.tsx b/source/client/view/structure/desktop/wallpaper/wallpaper.tsxindex 4f000a3..6d142f6 100644--- a/source/client/view/structure/desktop/wallpaper/wallpaper.tsx+++ b/source/client/view/structure/desktop/wallpaper/wallpaper.tsx@@ -3,7 +3,7 @@ import lightWallpaper from "@/assets/bundled/light-wallpaper.png"import { ApplicationContext } from "@client/view/contexts"import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"import Loading from "@client/view/components/loading"-import { useReady } from "@libs/readiness/main"+import { useReady } from "@libs/readiness"import { useTheme } from "@phreshos/react-ui"type WallpaperSource = Readonly<{diff --git a/source/client/view/structure/structure.tsx b/source/client/view/structure/structure.tsxindex f7f424d..2cf5dae 100644--- a/source/client/view/structure/structure.tsx+++ b/source/client/view/structure/structure.tsx@@ -1,7 +1,7 @@-import ReactTunnel from "@libs/the-link/plugins/react-helper/react-tunnel"-import useProperty from "@libs/the-link/plugins/react-helper/property-hook"+import { ReactTunnel } from "@the-link/react"+import { useProperty } from "@the-link/react"import { TransmittedLinkManager } from "@server/core/link-manager/link-manager"-import SocketLink from "@libs/the-link/plugins/client-link/socket-link"+import { SocketLink } from "@the-link/client"import LinkManager from "@client/core/link-manager/link-manager"import { AppearanceProvider, useResolveTheme } from "@phreshos/react-ui"import Loading from "../components/loading"@@ -11,7 +11,7 @@ import usePromise from "@libs/react-promise"import { useDesktopPreferences } from "../appearance/desktop-preferences"import Authentication from "./authentication/authentication"import { useCallback, useEffect, useState } from "react"-import Readiness, { useReady } from "@libs/readiness/main"+import Readiness, { useReady } from "@libs/readiness"import { standardAppearance, type DesktopPreferencesUpdate } from "@phreshos/core"const startupRequirements = ["connection", "session", "wallpaper"] as constdiff --git a/source/libs/readiness/main.tsx b/source/libs/readiness.tsxsimilarity index 61%rename from source/libs/readiness/main.tsxrename to source/libs/readiness.tsxindex dbc930e..d2d4a86 100644--- a/source/libs/readiness/main.tsx+++ b/source/libs/readiness.tsx@@ -1,6 +1,55 @@-import ReadinessState from "./state"import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"+/** The immutable state beneath a readiness boundary. */+export class ReadinessState {++ public readonly requirements: readonly string[]++ public readonly pending: readonly string[]++ private constructor(requirements: readonly string[], pending: readonly string[]) {++ this.requirements = [...requirements]++ this.pending = [...pending]+ }++ public static start(requirements: readonly string[]) {++ validate(requirements)++ return new ReadinessState(requirements, requirements)+ }++ /** Mark one known requirement ready. Repeated readiness is harmless. */+ public ready(requirement: string) {++ if (!this.requirements.includes(requirement)) throw new Error(`Readiness does not know the requirement "${requirement}"`)++ if (!this.pending.includes(requirement)) return this++ const pending = this.pending.filter(candidate => candidate !== requirement)++ return new ReadinessState(this.requirements, pending)+ }++ /** Add new work or restore one completed requirement. */+ public require(requirement: string) {++ validateRequirement(requirement)++ if (this.pending.includes(requirement)) return this++ const requirements = this.requirements.includes(requirement)+ ? this.requirements+ : [...this.requirements, requirement]++ const restored = new Set([...this.pending, requirement])++ return new ReadinessState(requirements, requirements.filter(candidate => restored.has(candidate)))+ }+}+const ReadinessContext = createContext<ReadinessValue | null>(null)/** Provides one readiness lifecycle to every operation inside the boundary. */@@ -103,6 +152,25 @@ function sameRequirements(left: readonly string[], right: readonly string[]) {return left.length === right.length && left.every((requirement, index) => requirement === right[index])}+function validate(requirements: readonly string[]) {++ const known = new Set<string>()++ for (const requirement of requirements) {++ validateRequirement(requirement)++ if (known.has(requirement)) throw new Error(`Readiness already knows the requirement "${requirement}"`)++ known.add(requirement)+ }+}++function validateRequirement(requirement: string) {++ if (!requirement.trim()) throw new Error("A readiness requirement must have a name")+}+interface ReadinessProps {requirements: readonly string[]diff --git a/source/libs/readiness/state.ts b/source/libs/readiness/state.tsdeleted file mode 100644index 173aa03..0000000--- a/source/libs/readiness/state.ts+++ /dev/null@@ -1,68 +0,0 @@-/** The immutable state beneath a readiness boundary. */-export default class ReadinessState {-- public readonly requirements: readonly string[]-- public readonly pending: readonly string[]-- private constructor(requirements: readonly string[], pending: readonly string[]) {-- this.requirements = [...requirements]-- this.pending = [...pending]- }-- public static start(requirements: readonly string[]) {-- validate(requirements)-- return new ReadinessState(requirements, requirements)- }-- /** Mark one known requirement ready. Repeated readiness is harmless. */- public ready(requirement: string) {-- if (!this.requirements.includes(requirement)) throw new Error(`Readiness does not know the requirement "${requirement}"`)-- if (!this.pending.includes(requirement)) return this-- const pending = this.pending.filter(candidate => candidate !== requirement)-- return new ReadinessState(this.requirements, pending)- }-- /** Add new work or restore one completed requirement. */- public require(requirement: string) {-- validateRequirement(requirement)-- if (this.pending.includes(requirement)) return this-- const requirements = this.requirements.includes(requirement)- ? this.requirements- : [...this.requirements, requirement]-- const restored = new Set([...this.pending, requirement])-- return new ReadinessState(requirements, requirements.filter(candidate => restored.has(candidate)))- }-}--function validate(requirements: readonly string[]) {-- const known = new Set<string>()-- for (const requirement of requirements) {-- validateRequirement(requirement)-- if (known.has(requirement)) throw new Error(`Readiness already knows the requirement "${requirement}"`)-- known.add(requirement)- }-}--function validateRequirement(requirement: string) {-- if (!requirement.trim()) throw new Error("A readiness requirement must have a name")-}diff --git a/source/libs/the-link/codec.ts b/source/libs/the-link/codec.tsdeleted file mode 100644index 4f559d7..0000000--- a/source/libs/the-link/codec.ts+++ /dev/null@@ -1,20 +0,0 @@-export type Bytes = Uint8Array<ArrayBuffer>--export type Serialize = (value: unknown) => Bytes--export type Deserialize = (bytes: Bytes) => unknown--const encoder = new TextEncoder()--const decoder = new TextDecoder("utf-8", { fatal: true })--export const defaultSerialize: Serialize = value => {-- const serialized = JSON.stringify(value)-- if (serialized === undefined) throw new TypeError("The value cannot be serialized as JSON")-- return encoder.encode(serialized)-}--export const defaultDeserialize: Deserialize = bytes => JSON.parse(decoder.decode(bytes))diff --git a/source/libs/the-link/decorators/escript.ts b/source/libs/the-link/decorators/escript.tsdeleted file mode 100644index c629358..0000000--- a/source/libs/the-link/decorators/escript.ts+++ /dev/null@@ -1,158 +0,0 @@-import { Finalizer, Forwarder, Interceptor, Subscriber } from "../tunnel"-import TheLink, { Publisher, TunnelName } from "../the-link"--/**- * Register a method as an interceptor on one of the link tunnels.- *- * Uses the standard ECMAScript decorator context to register the interceptor- * when each instance is initialized.- *- * @param tunnelName Target tunnel for interceptor registration- * @param prefix Event prefix to intercept, or an empty string for all events- * @returns ECMAScript method decorator- */-export function Intercept(tunnelName: TunnelName, prefix: string = "") {-- return function <TargetLink extends TheLink>(interceptor: Interceptor, context: ClassMethodDecoratorContext<TargetLink, Interceptor>) {-- if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)-- context.addInitializer(function () {-- // Select the tunnel from the concrete instance.- const tunnel = tunnelName === "outbound" ? this.$outbound : this.$inbound-- // Bind the method so interceptors preserve instance context.- tunnel.addInterceptor(interceptor.bind(this), prefix)- })- }-}--/**- * Register a method as a subscriber for a tunnel event.- *- * @param event Event identifier to subscribe to- * @param tunnelName Target tunnel for subscription- * @returns ECMAScript method decorator- */-export function Subscribe(event: string, tunnelName: TunnelName = "inbound") {-- return function <TargetLink extends TheLink>(subscriber: Subscriber, context: ClassMethodDecoratorContext<TargetLink, Subscriber>) {-- if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)-- context.addInitializer(function () {-- // Select the tunnel from the concrete instance.- const tunnel = tunnelName === "outbound" ? this.$outbound : this.$inbound-- // Bind the method so subscribers run with the instance as `this`.- tunnel.subscribe(event, subscriber.bind(this))- })- }-}--/**- * Register a method as a forwarder on one of the link tunnels.- *- * @param tunnelName Target tunnel for forwarder registration- * @param fromPrefix Source event prefix to match- * @param toPrefix Destination event prefix to apply- * @returns ECMAScript method decorator- */-export function Forward(tunnelName: TunnelName, fromPrefix: string = "", toPrefix: string = "") {-- return function <TargetLink extends TheLink>(forwarder: Forwarder, context: ClassMethodDecoratorContext<TargetLink, Forwarder>) {-- if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)-- context.addInitializer(function () {-- // Select the tunnel from the concrete instance.- const tunnel = tunnelName === "outbound" ? this.$outbound : this.$inbound-- // Bind the method before registering it as a tunnel forwarder.- tunnel.forwardTo(forwarder.bind(this), fromPrefix, toPrefix)- })- }-}--/**- * Register a method as a finalizer on one of the link tunnels.- *- * @param tunnelName Target tunnel for finalizer registration- * @param prefix Event prefix to finalize, or an empty string for all events- * @returns ECMAScript method decorator- */-export function Finalize(tunnelName: TunnelName, prefix: string = "") {-- return function <TargetLink extends TheLink>(finalizer: Finalizer, context: ClassMethodDecoratorContext<TargetLink, Finalizer>) {-- if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)-- context.addInitializer(function () {-- // Select the tunnel from the concrete instance.- const tunnel = tunnelName === "outbound" ? this.$outbound : this.$inbound-- // Bind the method so finalizers preserve instance context.- tunnel.addFinalizer(finalizer.bind(this), prefix)- })- }-}--/**- * Wrap a method so its return value is published as a tunnel event.- *- * The original method still returns its own result. After it resolves, that- * result is published on the configured tunnel.- *- * @param event Event identifier to publish after method execution- * @param tunnelName Target tunnel for publication- * @returns ECMAScript method decorator- */-export function Publish(event: string, tunnelName: TunnelName = "outbound") {-- return function <TargetLink extends TheLink>(publisher: Publisher, context: ClassMethodDecoratorContext<TargetLink, Publisher>) {-- if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)-- // Replace the decorated method with a publishing wrapper.- return async function (this: TargetLink, ...values: unknown[]) {-- const tunnel = tunnelName === "outbound" ? this.$outbound : this.$inbound-- const result = await publisher.apply(this, values)-- await tunnel.publish(event, result)-- return result- }- }-}--/**- * Combine inbound subscription with outbound publication for one method.- *- * Creates a publishing wrapper, registers that wrapper as the inbound subscriber,- * and returns the wrapper as the decorated method implementation.- *- * @param subscribeEvent Inbound event identifier to subscribe to- * @param publishEvent Optional outbound event identifier, defaults to subscribeEvent- * @returns ECMAScript method decorator- */-export function Connect(subscribeEvent: string, publishEvent?: string) {-- return function <TargetLink extends TheLink>(method: Subscriber & Publisher, context: ClassMethodDecoratorContext<TargetLink, Subscriber & Publisher>) {-- if (context.static) throw new Error(`@${String(context.name)} cannot be used on static methods`)-- // Create one publisher wrapper for both inbound and direct invocation.- const publisher = Publish(publishEvent || subscribeEvent, "outbound")(method, context)-- // Register the publisher wrapper as the inbound subscriber.- Subscribe(subscribeEvent, "inbound")(publisher, context)-- return publisher- }-}\ No newline at end of filediff --git a/source/libs/the-link/plugins/client-link/client-link.ts b/source/libs/the-link/plugins/client-link/client-link.tsdeleted file mode 100644index a533fd6..0000000--- a/source/libs/the-link/plugins/client-link/client-link.ts+++ /dev/null@@ -1,280 +0,0 @@-import Tunnel, { Subscriber } from "../../tunnel"-import { bytesToText, receiveBytes } from "./transport"-import { defaultDeserialize, defaultSerialize } from "../../codec"-import type { Deserialize, Serialize } from "../../codec"-import SocketLink from "./socket-link"-import TheLink from "../../the-link"-import { v4 as uuidv4 } from "uuid"--/**- * Client adapter for TheLink over HTTP publishing and WebSocket subscriptions.- *- * For outbound events, ClientLink forwards the outbound tunnel to the server's- * POST `/publish` endpoint. For subscriptions, it opens a WebSocket connection- * to `/subscribe`, waits for the server's subscribe envelope, then exposes the- * connection as a client-side SocketLink. Recoverable WebSocket closures trigger- * a delayed resubscribe with the original connection payload.- *- * The adapter uses UTF-8 JSON bytes by default, with hooks for custom codecs- * that must match the corresponding ServerLink.- *- * @example- * ```typescript- * const client = new ClientLink("https://api.example.com/events")- *- * const socket = await client.subscribeAsync<{ userId: string }>({ token })- *- * socket.$inbound.subscribe("server:event", handleServerEvent)- * await client.$outbound.publish("client:event", payload)- * ```- */-export default class ClientLink extends TheLink {-- /**- * Internal tunnel for client-side connection lifecycle events.- *- * Publishes `subscribe` when a WebSocket is accepted and `unsubscribe` when- * a tracked socket closes. UUID-scoped `subscribe:<uuid>` and- * `unsubscribe:<uuid>` events are also published so individual async- * subscription calls can resolve or reject their own connection.- */- public readonly $internal: Tunnel = new Tunnel()-- /**- * Server base URL used to construct `/publish` and `/subscribe` endpoints.- */- private readonly url: string-- private serialize: Serialize = defaultSerialize-- private deserialize: Deserialize = defaultDeserialize-- /**- * Active WebSocket-backed SocketLink instances keyed by connection UUID.- */- public readonly sockets: Map<string, SocketLink> = new Map()-- /**- * Initialize a ClientLink for a ServerLink base URL.- *- * @param url Server base URL that exposes `/publish` and `/subscribe`- */- public constructor(url: string) {-- super()-- // Store the server base URL for endpoint construction.- this.url = url-- // Forward outbound tunnel events to the server via HTTP POST.- this.$outbound.forwardTo(this.publishHandler.bind(this))- }-- /**- * Configure the serialization function used for HTTP and WebSocket payloads.- *- * @param serialize Custom function that converts values to bytes- */- public setSerialize(serialize: Serialize) {-- this.serialize = serialize- }-- /**- * Configure the deserialization function used for HTTP and WebSocket payloads.- *- * @param deserialize Custom function that parses values from bytes- */- public setDeserialize(deserialize: Deserialize) {-- this.deserialize = deserialize- }-- /**- * Register a handler for successful WebSocket subscriptions.- *- * @param subscriber Handler invoked with each accepted SocketLink- * @returns Function that removes this subscriber- */- public onSubscribe<Payload>(subscriber: Subscriber<[SocketLink<Payload>]>) {-- return this.$internal.subscribe("subscribe", subscriber)- }-- /**- * Open a WebSocket subscription to the server.- *- * The connection payload is serialized and encoded into the `payload` query parameter.- * When the server responds with a `subscribe` envelope, this client creates a- * SocketLink and publishes it on the internal `subscribe` event plus the- * UUID-scoped `subscribe:<uuid>` event.- *- * @param payload Optional connection payload sent to the server- * @returns Connection UUID used for socket tracking and scoped lifecycle events- */- public subscribe(payload: unknown = undefined) {-- const searchParams = new URLSearchParams()-- // Include caller-provided connection context in the subscribe request.- searchParams.set("payload", bytesToText(this.serialize({ current: payload })))-- const socket = new WebSocket(`${this.url}/subscribe?${searchParams.toString()}`)-- socket.binaryType = "arraybuffer"-- const uuid = uuidv4()-- // Route the server subscribe envelope through the WebSocket message handler.- socket.addEventListener("message", (event) => this.webSocketMessageHandler(event, socket, uuid), { once: true })-- // Ensure SocketLink cleanup and reconnect handling when the WebSocket closes.- socket.addEventListener("close", (event) => this.webSocketCloseHandler(event, payload, uuid))-- return uuid- }-- /**- * Open a WebSocket subscription and resolve with its SocketLink.- *- * Resolves when this subscription's UUID-scoped `subscribe:<uuid>` event is- * published. Rejects if `unsubscribe:<uuid>` is published before the- * subscription succeeds.- *- * @param payload Optional connection payload sent to the server- * @returns SocketLink created from the server subscription response- * @throws Error when the socket closes before subscription completes- */- public async subscribeAsync<Response>(payload: unknown = undefined) {-- return await new Promise<SocketLink<Response>>((resolve, reject) => {-- const socketUuid = this.subscribe(payload)-- const removeSubscribeSubscriber = this.$internal.subscribeOnce(`subscribe:${socketUuid}`, function (socketLink: SocketLink<Response>) {-- removeUnsubscribeSubscriber()-- resolve(socketLink)- })-- const removeUnsubscribeSubscriber = this.$internal.subscribeOnce(`unsubscribe:${socketUuid}`, function (event: CloseEvent) {-- removeSubscribeSubscriber()-- reject(new Error(event.reason))- })- })- }-- /**- * Publish an outbound event to the server through HTTP POST.- *- * Automatically invoked by outbound tunnel forwarding configured in the- * constructor.- *- * @param event Event identifier routed on the server- * @param values Event payload values sent to the server- * @returns Deserialized server handler results- * @throws Error when the server returns a non-successful response- */- private async publishHandler(event: string, ...values: unknown[]) {-- // Send the event envelope to ServerLink's POST /publish endpoint.- const response = await fetch(`${this.url}/publish`, {-- body: this.serialize([event, ...values]),-- method: "POST"- })-- if (!response.ok) throw new Error(await response.text())-- return this.deserialize(new Uint8Array(await response.arrayBuffer()))- }-- /**- * Handle the server's WebSocket subscribe envelope.- *- * A `subscribe` message creates the client-side SocketLink for this- * connection, configures matching serialization, and publishes the internal- * `subscribe` event for application code. It also publishes- * `subscribe:<uuid>` for the specific subscribeAsync() call that opened this- * socket.- *- * @param event WebSocket message containing the serialized subscribe envelope- * @param socket Browser WebSocket instance for this connection- * @param uuid Connection identifier used for socket tracking- */- private async webSocketMessageHandler(event: MessageEvent, socket: WebSocket, uuid: string) {-- const result = this.deserialize(await receiveBytes(event.data)) as { type: string, data: unknown }-- if (result.type === "subscribe") {-- try {-- // Wrap the browser WebSocket in a TheLink-compatible socket adapter.- const socketLink = new SocketLink(socket, result.data)-- socketLink.setSerialize(value => this.serialize(value))-- socketLink.setDeserialize(value => this.deserialize(value))-- this.sockets.set(uuid, socketLink)-- // Notify application code that this subscription is ready.- await this.$internal.publish("subscribe", socketLink)-- await this.$internal.publish(`subscribe:${uuid}`, socketLink)- }-- catch (exception) {-- console.error(exception instanceof Error ? exception.message : "An unknown exception occurred")-- socket.close(1000, exception instanceof Error ? exception.message : "An unknown exception occurred")- }- }- }-- /**- * Clean up a closed WebSocket subscription and reconnect when recoverable.- *- * Publishes the socket-level unsubscribe event before removing the SocketLink- * from the active map, then publishes `unsubscribe:<uuid>` for callers- * waiting on that specific subscription. Recoverable close codes open a new- * subscription with the original payload after a short delay.- *- * @param event Browser WebSocket close event- * @param payload Original connection payload used for reconnect attempts- * @param uuid Connection identifier used to find the SocketLink- */- private async webSocketCloseHandler(event: CloseEvent, payload: unknown, uuid: string) {-- try {-- const socketLink = this.sockets.get(uuid)-- // Notify socket consumers before dropping the tracked connection.- if (socketLink) await socketLink.$internal.publish("unsubscribe", event)-- await this.$internal.publish(`unsubscribe:${uuid}`, event)- }-- finally {-- this.sockets.delete(uuid)-- // Retry transient server or network closures with the original payload.- const reconnectCodes = new Set([1001, 1006, 1011, 1012, 1013, 1014])-- if (reconnectCodes.has(event.code)) {-- await new Promise(resolve => setTimeout(resolve, 1000))-- this.subscribe(payload)- }- }- }-}diff --git a/source/libs/the-link/plugins/client-link/socket-link.ts b/source/libs/the-link/plugins/client-link/socket-link.tsdeleted file mode 100644index e550766..0000000--- a/source/libs/the-link/plugins/client-link/socket-link.ts+++ /dev/null@@ -1,176 +0,0 @@-import TheLink from "../../the-link"-import { receiveBytes } from "./transport"-import { defaultDeserialize, defaultSerialize } from "../../codec"-import type { Deserialize, Serialize } from "../../codec"-import Tunnel from "../../tunnel"--/**- * Client-side WebSocket adapter for a subscribed ServerLink connection.- *- * Wraps one browser WebSocket with TheLink-compatible inbound and outbound- * tunnels. Server messages are routed into the inbound tunnel, while outbound- * tunnel events are serialized and sent back through the WebSocket.- *- * Event messages use a simple `[event, ...values]` envelope.- *- * @example- * ```typescript- * const socket = await client.subscribeAsync()- *- * socket.$inbound.subscribe("server:event", handleServerEvent)- * await socket.$outbound.publish("client:event", payload)- * ```- */-export default class SocketLink<Payload = unknown> extends TheLink {-- /**- * Internal tunnel for this socket's lifecycle events.- *- * Publishes `unsubscribe` when the underlying WebSocket closes.- */- public readonly $internal: Tunnel = new Tunnel()-- /**- * Browser WebSocket used for bidirectional transport.- */- private readonly socket: WebSocket-- /**- * Server response payload supplied during subscription establishment.- */- public readonly payload: Payload-- private serialize: Serialize = defaultSerialize-- private deserialize: Deserialize = defaultDeserialize-- /**- * Initialize a SocketLink for one browser WebSocket subscription.- *- * @param socket Browser WebSocket connected to the server subscription route- * @param payload Server-provided subscription response payload- */- public constructor(socket: WebSocket, payload: Payload) {-- super()-- // Store the raw WebSocket connection for later message delivery.- this.socket = socket-- // Preserve server-provided connection context for application handlers.- this.payload = payload-- // Route server messages and close events through local handlers.- this.socket.addEventListener("message", this.subscribeHandler.bind(this))-- this.socket.addEventListener("close", this.closeHandler.bind(this))-- // Send outbound tunnel events to the server automatically.- this.$outbound.forwardTo(this.publishHandler.bind(this))- }-- /**- * Configure the serialization function used for WebSocket payloads.- *- * @param serialize Custom function that converts values to bytes- */- public setSerialize(serialize: Serialize) {-- this.serialize = serialize- }-- /**- * Configure the deserialization function used for WebSocket payloads.- *- * @param deserialize Custom function that parses values from bytes- */- public setDeserialize(deserialize: Deserialize) {-- this.deserialize = deserialize- }-- /**- * Connect another TheLink instance to this socket until it unsubscribes.- *- * @param theLink Source link whose events should be forwarded- * @param fromPrefix Source event prefix to match- * @param toPrefix Destination event prefix to apply- * @returns Function that manually disconnects forwarding and cleanup- */- public autoJoin(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {-- // Forward matching events from the source link to this socket.- const disconnect = theLink.connectTo(this, fromPrefix, toPrefix)-- // Stop forwarding automatically when the socket closes.- const removeUnsubscribeSubscriber = this.$internal.subscribeOnce("unsubscribe", disconnect)-- return function () {-- // Allow callers to tear down forwarding before socket closure.- disconnect()-- removeUnsubscribeSubscriber()- }- }-- /**- * Close the WebSocket subscription from the client side.- *- * @param code WebSocket close code- * @param reason Close reason sent to the server- */- public unsubscribe(code: number = 1000, reason: string = "Unsubscribed by client") {-- this.socket.close(code, reason)- }-- /**- * Process a server message envelope and route it into the inbound tunnel.- *- * @param event Browser WebSocket message event- */- private async subscribeHandler(event: MessageEvent) {-- const result = this.deserialize(await receiveBytes(event.data)) as { type: string, data: [string, ...unknown[]] }-- if (result.type === "message") {-- // Decode the event payload from the server.- const [eventName, ...values] = result.data-- try {-- // Publish server event through this socket's inbound tunnel.- await this.$inbound.publish(eventName, ...values)- }-- catch (exception) {-- console.error(exception instanceof Error ? exception.message : "An unknown exception occurred")- }- }- }-- /**- * Send an outbound tunnel event to the server.- *- * @param event Event identifier sent to the server- * @param values Event payload values sent to the server- */- private publishHandler(event: string, ...values: unknown[]) {-- // Send the event envelope using the same simple event tuple protocol.- this.socket.send(this.serialize([event, ...values]))- }-- /**- * Publish the socket-level unsubscribe event after WebSocket closure.- *- * @param event Browser WebSocket close event- */- private async closeHandler(event: CloseEvent) {-- await this.$internal.publish("unsubscribe", event.code, event.reason)- }-}diff --git a/source/libs/the-link/plugins/client-link/transport.ts b/source/libs/the-link/plugins/client-link/transport.tsdeleted file mode 100644index 38afc43..0000000--- a/source/libs/the-link/plugins/client-link/transport.ts+++ /dev/null@@ -1,24 +0,0 @@-import type { Bytes } from "../../codec"--export const receiveBytes = async (value: unknown): Promise<Bytes> => {-- if (value instanceof ArrayBuffer) return new Uint8Array(value)-- if (ArrayBuffer.isView(value)) {-- return Uint8Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength))- }-- if (value instanceof Blob) return new Uint8Array(await value.arrayBuffer())-- throw new TypeError("The WebSocket message is not binary")-}--export const bytesToText = (bytes: Bytes) => {-- let binary = ""-- for (const byte of bytes) binary += String.fromCharCode(byte)-- return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "")-}diff --git a/source/libs/the-link/plugins/react-helper/property-hook.ts b/source/libs/the-link/plugins/react-helper/property-hook.tsdeleted file mode 100644index 4e24aa3..0000000--- a/source/libs/the-link/plugins/react-helper/property-hook.ts+++ /dev/null@@ -1,30 +0,0 @@-import Property from "../../property"-import { useCallback, useSyncExternalStore } from "react"--/**- * React hook for reading a Property value reactively.- *- * The Property remains the source of truth. React reads its current snapshot- * and subscribes only for invalidation, so there is no mirrored state that can- * fall out of step between rendering and effect setup.- *- * @param property Property instance to synchronize with React state- * @returns Current property value, updated when the property publishes `change`- *- * @example- * ```typescript- * function ThemeLabel({ theme }: { theme: Property<string> }) {- * const value = useProperty(theme)- *- * return <span>{value}</span>- * }- * ```- */-export default function useProperty<Value>(property: Property<Value>) {-- const subscribe = useCallback((changed: () => void) => property.tunnel.subscribe("change", changed), [property])-- const snapshot = useCallback(() => property.value, [property])-- return useSyncExternalStore(subscribe, snapshot, snapshot)-}diff --git a/source/libs/the-link/plugins/react-helper/react-tunnel.ts b/source/libs/the-link/plugins/react-helper/react-tunnel.tsdeleted file mode 100644index 4ab6cb9..0000000--- a/source/libs/the-link/plugins/react-helper/react-tunnel.ts+++ /dev/null@@ -1,99 +0,0 @@-import { useCallback, useEffect, useMemo, useState } from "react"-import Tunnel, { Subscriber } from "../../tunnel"--/**- * React hook helper for a Tunnel instance.- *- * Provides React-friendly subscription and state helpers around Tunnel events.- * Subscriptions are registered in effects and cleaned up automatically, while- * event payloads can be mirrored into React state for rendering.- *- * @example- * ```typescript- * function StatusView({ tunnel }: { tunnel: Tunnel }) {- * const reactTunnel = ReactTunnel.useFactory(tunnel)- * const status = reactTunnel.useFirstState("status:update", "idle")- *- * return <span>{status}</span>- * }- * ```- */-export default class ReactTunnel {-- /**- * Tunnel instance used by the React hook helpers.- */- public readonly tunnel: Tunnel-- /**- * Initialize a ReactTunnel wrapper around a Tunnel.- *- * @param tunnel Tunnel instance to integrate with React components- */- public constructor(tunnel: Tunnel) {-- // Store the tunnel used by all helper hooks.- this.tunnel = tunnel- }-- /**- * Create a memoized ReactTunnel instance for a Tunnel.- *- * @param tunnel Tunnel instance to wrap- * @returns Stable ReactTunnel wrapper while the Tunnel reference is unchanged- */- public static useFactory(tunnel: Tunnel) {-- return useMemo(() => new ReactTunnel(tunnel), [tunnel])- }-- /**- * Subscribe to a Tunnel event with React lifecycle cleanup.- *- * @param event Event identifier to subscribe to- * @param subscriber Handler invoked when the event is published- */- public useSubscribe(event: string, subscriber: Subscriber) {-- useEffect(() => {-- // Register on mount or when the event/subscriber pair changes.- this.tunnel.subscribe(event, subscriber)-- // Remove the exact subscriber when React cleans up the effect.- return () => this.tunnel.unsubscribe(event, subscriber)-- }, [event, subscriber])- }-- /**- * Mirror a Tunnel event's payload values into React state.- *- * @param event Event identifier used for state updates- * @param defaultResults Initial state values before the event is published- * @returns Latest event payload values- */- public useState<Results extends unknown[]>(event: string, defaultResults: Results): Results {-- const [results, setResults] = useState<Results>(defaultResults)-- // Store each event publication payload as the next React state value.- const subscriber = useCallback((...results: Results) => setResults(results), [])-- this.useSubscribe(event, subscriber)-- return results- }-- /**- * Mirror the first value of a Tunnel event payload into React state.- *- * @param event Event identifier used for state updates- * @param defaultResult Initial value before the event is published- * @returns Latest first event payload value- */- public useFirstState<Result>(event: string, defaultResult: Result): Result {-- return this.useState(event, [defaultResult])[0]- }-}\ No newline at end of filediff --git a/source/libs/the-link/plugins/server-link/server-link.ts b/source/libs/the-link/plugins/server-link/server-link.tsdeleted file mode 100644index 16f9524..0000000--- a/source/libs/the-link/plugins/server-link/server-link.ts+++ /dev/null@@ -1,301 +0,0 @@-import { UpgradeWebSocket, WSContext, WSEvents } from "hono/ws"-import Tunnel, { Subscriber } from "../../tunnel"-import { receiveBytes, textToBytes } from "./transport"-import { defaultDeserialize, defaultSerialize } from "../../codec"-import type { Deserialize, Serialize } from "../../codec"-import { HonoOptions } from "hono/hono-base"-import SocketLink from "./socket-link"-import { BlankEnv } from "hono/types"-import TheLink from "../../the-link"-import { Hono, Context } from "hono"-import { v4 as uuidv4 } from "uuid"--/**- * Hono server adapter for TheLink over HTTP and WebSocket endpoints.- *- * Provides a POST `/publish` endpoint for client-to-server events and an- * optional WebSocket `/subscribe` endpoint for long-lived server-to-client- * communication. Each accepted WebSocket connection gets a dedicated- * SocketLink instance, allowing application code to route events per client.- *- * The adapter uses UTF-8 JSON bytes by default, with hooks for custom codecs- * such as compression, encryption, or type preservation.- *- * Connection lifecycle events:- * - `subscribe`: Published on the internal tunnel when a socket connects- * - `unsubscribe`: Published through the SocketLink when a socket closes- *- * @example- * ```typescript- * const server = new ServerLink()- *- * server.prepareConnection(upgradeWebSocket)- *- * server.onSubscribe((socket) => {- * socket.autoJoin(server)- * })- * ```- */-export default class ServerLink extends TheLink {-- /**- * Internal tunnel for server-only lifecycle events.- *- * Keeps connection coordination separate from application inbound and- * outbound event traffic.- */- public readonly $internal: Tunnel = new Tunnel()-- /**- * Hono application that owns the HTTP and WebSocket routes.- */- public readonly app: Hono-- /**- * Controls whether handler errors are exposed to clients.- *- * Keep disabled in production to avoid leaking internal details.- */- private debugging: boolean = false-- private serialize: Serialize = defaultSerialize-- private deserialize: Deserialize = defaultDeserialize-- /**- * Active WebSocket-backed SocketLink instances keyed by connection UUID.- */- public readonly sockets: Map<string, SocketLink> = new Map()-- /**- * Initialize a ServerLink with an optional Hono configuration object.- *- * @param options Hono application options passed to the underlying app- */- public constructor(options?: HonoOptions<BlankEnv>) {-- super()-- this.app = new Hono(options)- }-- /**- * Register server communication routes on the Hono application.- *- * Always registers the POST `/publish` endpoint. When an Hono WebSocket- * upgrader is provided, also registers GET `/subscribe` for WebSocket- * subscriptions.- *- * @param upgradeWebSocket Optional Hono WebSocket upgrade helper- */- public prepareConnection(upgradeWebSocket?: UpgradeWebSocket) {-- // Configure client-to-server event publication.- this.app.post("/publish", this.publishHandler.bind(this))-- if (upgradeWebSocket) {-- // Configure long-lived client subscriptions when WebSocket support is available.- this.app.get("/subscribe", upgradeWebSocket(this.webSocketHandler.bind(this)))- }- }-- /**- * Enable detailed client-facing error messages.- */- public enableDebugging() {-- this.debugging = true- }-- /**- * Disable detailed client-facing error messages.- */- public disableDebugging() {-- this.debugging = false- }-- /**- * Configure the serialization function used for HTTP and WebSocket payloads.- *- * @param serialize Custom function that converts values to bytes- */- public setSerialize(serialize: Serialize) {-- this.serialize = serialize- }-- /**- * Configure the deserialization function used for HTTP and WebSocket payloads.- *- * @param deserialize Custom function that parses values from bytes- */- public setDeserialize(deserialize: Deserialize) {-- this.deserialize = deserialize- }-- /**- * Register a handler for accepted WebSocket subscriptions.- *- * The subscriber receives the SocketLink created for the connection and can- * attach handlers, join tunnels, or return connection initialization data.- *- * @param subscriber Handler invoked with each new SocketLink- * @returns Function that removes this subscriber- */- public onSubscribe<Payload>(subscriber: Subscriber<[SocketLink<Payload>]>) {-- return this.$internal.subscribe("subscribe", subscriber)- }-- /**- * Process a client POST request and publish it through the inbound tunnel.- *- * @param context Hono request context containing serialized event data- * @returns Serialized event handler results, or a 500 error response- */- private async publishHandler(context: Context) {-- try {-- // Decode the event envelope from the request body.- const bytes = new Uint8Array(await context.req.arrayBuffer())-- const [event, ...values] = this.deserialize(bytes) as [string, ...unknown[]]-- // Route the client event into the server-side inbound tunnel.- const results = await this.$inbound.publish(event, ...values)-- return context.body(this.serialize(results))- }-- catch (exception) {-- console.error(exception instanceof Error ? exception.message : "An unknown exception occurred")-- if (this.debugging) return context.text(exception instanceof Error ? exception.message : "An unknown exception occurred", 500)-- else return context.text("An unknown exception occurred", 500)- }- }-- /**- * Create the Hono WebSocket event handlers for a new subscription request.- *- * @param context Hono request context containing subscription query data- * @returns WebSocket lifecycle callbacks for this connection- */- private webSocketHandler(context: Context): WSEvents {-- const uuid = uuidv4()-- return {-- onOpen: (_event, socket) => this.webSocketOpenHandler(context, socket, uuid),-- onMessage: (event) => this.webSocketMessageHandler(event, uuid),-- onClose: (event) => this.webSocketCloseHandler(event, uuid)- }- }-- /**- * Accept a WebSocket connection and create its SocketLink facade.- *- * Reads the serialized `payload` query parameter, initializes a SocketLink,- * publishes the internal subscribe event, and sends the subscription response- * back to the client.- *- * @param context Hono request context containing subscription payload data- * @param socket Accepted WebSocket context- * @param uuid Connection identifier used for socket tracking- */- private async webSocketOpenHandler(context: Context, socket: WSContext, uuid: string) {-- try {-- // Extract client-provided connection context.- const payload = context.req.query("payload")-- if (payload === undefined) throw new Error("payload is required")-- const parsedPayload = this.deserialize(textToBytes(payload)) as { current: unknown }-- // Wrap the raw WebSocket in TheLink-compatible socket routing.- const socketLink = new SocketLink(socket, parsedPayload.current)-- socketLink.setSerialize(value => this.serialize(value))-- // Let application code initialize the connection before notifying the client.- const response = await this.$internal.publishFirst("subscribe", socketLink)-- this.sockets.set(uuid, socketLink)-- socket.send(this.serialize({ type: "subscribe", data: response }))- }-- catch (exception) {-- console.error(exception instanceof Error ? exception.message : "An unknown exception occurred")-- if (this.debugging) return socket.close(1011, exception instanceof Error ? exception.message : "An unknown exception occurred")-- else return socket.close(1011, "An unknown exception occurred")- }- }-- /**- * Route a WebSocket message through the matching SocketLink inbound tunnel.- *- * @param event WebSocket message containing a serialized event envelope- * @param uuid Connection identifier used to find the SocketLink- */- private async webSocketMessageHandler(event: MessageEvent, uuid: string) {-- const socketLink = this.sockets.get(uuid)-- if (socketLink) {-- // Decode the event payload from the message.- const [eventName, ...values] = this.deserialize(await receiveBytes(event.data)) as [string, ...unknown[]]-- try {-- // Publish client event through this socket's inbound tunnel.- await socketLink.$inbound.publish(eventName, ...values)- }-- catch (exception) {-- console.error(exception instanceof Error ? exception.message : "An unknown exception occurred")- }- }- }-- /**- * Clean up a closed WebSocket connection.- *- * Publishes the socket-level unsubscribe event before removing the connection- * from the active socket map.- *- * @param event WebSocket close event- * @param uuid Connection identifier used to find the SocketLink- */- private async webSocketCloseHandler(event: CloseEvent, uuid: string) {-- try {-- const socketLink = this.sockets.get(uuid)-- // Notify socket consumers before dropping the active connection.- if (socketLink) await socketLink.$internal.publish("unsubscribe", event)- }-- finally {-- this.sockets.delete(uuid)- }- }-}diff --git a/source/libs/the-link/plugins/server-link/socket-link.ts b/source/libs/the-link/plugins/server-link/socket-link.tsdeleted file mode 100644index d12ea67..0000000--- a/source/libs/the-link/plugins/server-link/socket-link.ts+++ /dev/null@@ -1,129 +0,0 @@-import TheLink from "../../the-link"-import { defaultSerialize } from "../../codec"-import type { Serialize } from "../../codec"-import { WSContext } from "hono/ws"-import Tunnel from "../../tunnel"--/**- * Per-connection WebSocket adapter for TheLink server subscriptions.- *- * Wraps a single accepted WebSocket connection with TheLink-compatible inbound- * and outbound tunnels. Server code can use each SocketLink to publish events to- * one client and receive events from that client.- *- * Outbound events are serialized into `{ type: "message", data: [...] }`- * envelopes using a simple `[event, ...values]` event tuple.- *- * @example- * ```typescript- * server.onSubscribe((socket) => {- * socket.autoJoin(server)- * socket.$inbound.subscribe("client:event", handleClientEvent)- * })- * ```- */-export default class SocketLink<Payload = unknown> extends TheLink {-- /**- * Internal tunnel for this socket's lifecycle events.- *- * Currently used to coordinate cleanup when the socket unsubscribes.- */- public readonly $internal: Tunnel = new Tunnel()-- /**- * Accepted WebSocket connection used for bidirectional transport.- */- private readonly socket: WSContext-- /**- * Client payload supplied during subscription establishment.- */- public readonly payload: Payload-- private serialize: Serialize = defaultSerialize-- /**- * Initialize a SocketLink for one accepted WebSocket connection.- *- * The constructor stores the connection payload and forwards all outbound- * tunnel events to the WebSocket publish handler.- *- * @param socket Accepted WebSocket context- * @param payload Client payload supplied during subscription- */- public constructor(socket: WSContext, payload: Payload) {-- super()-- // Store the raw WebSocket connection for later message delivery.- this.socket = socket-- // Preserve caller-provided connection context for application handlers.- this.payload = payload-- // Send outbound tunnel events to this client automatically.- this.$outbound.forwardTo(this.publishHandler.bind(this))- }-- /**- * Configure the serialization function used for WebSocket payloads.- *- * @param serialize Custom function that converts values to bytes- */- public setSerialize(serialize: Serialize) {-- this.serialize = serialize- }-- /**- * Connect another TheLink instance to this socket until it unsubscribes.- *- * Creates a forwarding relationship from the source link to this socket, then- * registers cleanup on this socket's internal `unsubscribe` event.- *- * @param theLink Source link whose events should be forwarded- * @param fromPrefix Source event prefix to match- * @param toPrefix Destination event prefix to apply- * @returns Function that manually disconnects forwarding and cleanup- */- public autoJoin(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {-- // Forward matching events from the source link to this socket.- const disconnect = theLink.connectTo(this, fromPrefix, toPrefix)-- // Stop forwarding automatically when the socket closes.- const removeUnsubscribeSubscriber = this.$internal.subscribeOnce("unsubscribe", disconnect)-- return function () {-- // Allow callers to tear down forwarding before socket closure.- disconnect()-- removeUnsubscribeSubscriber()- }- }-- /**- * Close the WebSocket subscription from the server side.- *- * @param code WebSocket close code- * @param reason Close reason sent to the client- */- public unsubscribe(code: number = 1000, reason: string = "Unsubscribed by server") {-- this.socket.close(code, reason)- }-- /**- * Send an outbound tunnel event to the client.- *- * @param event Event identifier sent to the client- * @param values Event payload values sent to the client- */- private publishHandler(event: string, ...values: unknown[]) {-- // Send the event envelope using the same simple event tuple protocol.- this.socket.send(this.serialize({ type: "message", data: [event, ...values] }))- }-}diff --git a/source/libs/the-link/plugins/server-link/transport.ts b/source/libs/the-link/plugins/server-link/transport.tsdeleted file mode 100644index fa83d00..0000000--- a/source/libs/the-link/plugins/server-link/transport.ts+++ /dev/null@@ -1,24 +0,0 @@-import type { Bytes } from "../../codec"--export const receiveBytes = async (value: unknown): Promise<Bytes> => {-- if (value instanceof ArrayBuffer) return new Uint8Array(value)-- if (ArrayBuffer.isView(value)) {-- return Uint8Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength))- }-- if (value instanceof Blob) return new Uint8Array(await value.arrayBuffer())-- throw new TypeError("The WebSocket message is not binary")-}--export const textToBytes = (value: string): Bytes => {-- const unpadded = value.replaceAll("-", "+").replaceAll("_", "/")-- const binary = atob(unpadded.padEnd(unpadded.length + (4 - unpadded.length % 4) % 4, "="))-- return Uint8Array.from(binary, character => character.charCodeAt(0))-}diff --git a/source/libs/the-link/property.ts b/source/libs/the-link/property.tsdeleted file mode 100644index 854c60c..0000000--- a/source/libs/the-link/property.ts+++ /dev/null@@ -1,219 +0,0 @@-import { v4 as uuidv4 } from "uuid"-import TheLink from "./the-link"-import Tunnel from "./tunnel"--/**- * Reactive property synchronized through a TheLink instance.- *- * A provider owns the property key and source value. Consumers bind to that key- * and receive `property-update:<key>` events through their link. Every Property- * also exposes a local tunnel that publishes `change` whenever its stored value- * changes.- */-export default class Property<Value> {-- /**- * Local notification tunnel for this property's value changes.- */- public readonly tunnel: Tunnel = new Tunnel()-- /**- * Provider or consumer role controlling update propagation.- */- private readonly type: PropertyType-- /**- * Link used to publish and receive cross-instance property updates.- */- private readonly theLink: TheLink-- /**- * Unique property identifier used in the update event namespace.- */- public readonly key: string-- /**- * Current locally stored value.- */- private _value: Value-- /**- * Optional inbound value mapper or validator.- */- private interceptor: PropertyInterceptor<any, Value> | null = null-- /**- * Initialize a property instance and subscribe it to its update namespace.- *- * @param type Provider or consumer role- * @param theLink Link used for cross-instance synchronization- * @param key Property update namespace key- * @param value Initial local value- */- private constructor(type: PropertyType, theLink: TheLink, key: string, value: Value) {-- this.type = type-- this.theLink = theLink-- this.key = key-- this._value = value-- // Receive updates published by connected providers or consumers.- this.theLink.$inbound.subscribe(`property-update:${this.key}`, this.updateHandler.bind(this))- }-- /**- * Create a public provider property with a generated key.- *- * Public providers accept inbound update requests and relay accepted values- * back outbound to synchronize all consumers.- *- * @param theLink Link used for synchronization- * @param value Initial provider value- * @param interceptor Optional inbound value mapper or validator- * @returns Provider property with a generated key- */- public static public<Value>(theLink: TheLink, value: Value, interceptor?: PropertyInterceptor<any, Value>) {-- const property = new this("provider", theLink, uuidv4(), value)-- if (interceptor) property.setInterceptor(interceptor)-- return property- }-- /**- * Create a private provider property with a generated key.- *- * Private providers reject inbound update requests by installing an- * interceptor that always throws.- *- * @param theLink Link used for synchronization- * @param value Initial provider value- * @returns Provider property that rejects consumer update requests- */- public static private<Value>(theLink: TheLink, value: Value) {-- return this.public(theLink, value, function () {-- throw new Error("You cannot request update a private property.")- })- }-- /**- * Create a consumer property bound to an existing provider key.- *- * @param theLink Link used for synchronization- * @param key Provider property key to consume- * @param value Initial local value before the first provider update- * @param interceptor Optional inbound value mapper or validator- * @returns Consumer property bound to the provider key- */- public static consumer<Value>(theLink: TheLink, key: string, value: Value, interceptor?: PropertyInterceptor<any, Value>) {-- const property = new Property("consumer", theLink, key, value)-- if (interceptor) property.setInterceptor(interceptor)-- return property- }-- /**- * Set or clear the inbound value interceptor.- *- * @param interceptor Mapper or validator for inbound values, or null to clear- */- public setInterceptor(interceptor: PropertyInterceptor<any, Value> | null) {-- this.interceptor = interceptor- }-- /**- * Current local property value.- */- public get value() {-- return this._value- }-- /**- * Store a new local value and notify local subscribers.- *- * @param value New local value- */- private async setValue(value: Value) {-- this._value = value-- await this.tunnel.publish("change", value)- }-- /**- * Publish a property update through the link's outbound tunnel.- *- * @param value Value to publish to connected links- */- private async publish(value: Value) {-- await this.theLink.$outbound.publish(`property-update:${this.key}`, value)- }-- /**- * Update this property and propagate the value.- *- * Providers update their local value immediately before publishing. Consumers- * publish the request and rely on the provider's relayed update to settle the- * synchronized value.- *- * @param value New value or requested value- */- public async update(value: Value) {-- if (this.type === "provider") await this.setValue(value)-- await this.publish(value)- }-- /**- * Handle an inbound property update event.- *- * @param value Incoming value from the link inbound tunnel- */- private async updateHandler(value: Value) {-- // Interceptors can transform or reject inbound values.- if (this.interceptor) value = this.interceptor(value)-- await this.setValue(value)-- // Providers relay accepted inbound updates to every connected consumer.- if (this.type === "provider") await this.publish(value)- }-- /**- * Serialize the property as its public key/value shape.- *- * @returns Plain object representation used by JSON.stringify- */- public toJSON() {-- return {-- key: this.key,-- value: this.value- }- }-}--/**- * Property role in the provider/consumer relationship.- */-export type PropertyType = "provider" | "consumer"--/**- * Function applied to inbound property values before local storage.- */-export type PropertyInterceptor<IncomingValue, ProcessedValue> = (incomingValue: IncomingValue) => ProcessedValuediff --git a/source/libs/the-link/the-link.ts b/source/libs/the-link/the-link.tsdeleted file mode 100644index b5acaa1..0000000--- a/source/libs/the-link/the-link.ts+++ /dev/null@@ -1,157 +0,0 @@-import Tunnel from "./tunnel"--/**- * Base link abstraction built from inbound and outbound event tunnels.- *- * TheLink provides a two-tunnel model for bidirectional event flow. Subclasses- * can publish through `$outbound`, receive through `$inbound`, and connect to- * other links through prefix-aware forwarding relationships.- *- * Decorator implementations use `addInitializer()` to register instance setup- * work on the class prototype. The constructor executes those initializers for- * each new instance.- */-export default class TheLink {-- /**- * Events received by this link from other links or adapters.- */- public readonly $inbound: Tunnel = new Tunnel()-- /**- * Events published by this link toward other links or adapters.- */- public readonly $outbound: Tunnel = new Tunnel()-- /**- * Initialize a link and run prototype-registered decorator initializers.- */- public constructor() {-- const initializers: Initializer<typeof this>[] = this.constructor.prototype.$initializers ??= []-- // Decorators register these initializers on the prototype before construction.- for (const initializer of initializers) initializer(this)- }-- /**- * Register a constructor-time initializer on the class prototype.- *- * Intended for decorator implementations only.- *- * @param initializer Function executed for each constructed instance- * @throws Error when called on an already constructed instance- */- public addInitializer(initializer: Initializer<typeof this>) {-- if (this !== this.constructor.prototype) throw new Error("addInitializer() can only be called on the class prototype during decoration, not on constructed instances")-- const initializers: Initializer<typeof this>[] = this.constructor.prototype.$initializers ??= []-- initializers.push(initializer)- }-- /**- * Forward another link's inbound events into this link's inbound tunnel.- *- * @param theLink Source link to subscribe to- * @param fromPrefix Source event prefix to match and strip- * @param toPrefix Destination event prefix to prepend- * @returns Cleanup function that removes this forwarding relationship- */- public subscribeTo(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {-- theLink.$inbound.forwardTo(this.$inbound, fromPrefix, toPrefix)-- return () => this.unsubscribeFrom(theLink, fromPrefix, toPrefix)- }-- /**- * Stop forwarding another link's inbound events into this link.- *- * @param theLink Source link used during subscription- * @param fromPrefix Source prefix used during subscription- * @param toPrefix Destination prefix used during subscription- */- public unsubscribeFrom(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {-- theLink.$inbound.stopForwardingTo(this.$inbound, fromPrefix, toPrefix)- }-- /**- * Forward this link's outbound events into another link's outbound tunnel.- *- * @param theLink Target link to publish to- * @param fromPrefix Source event prefix to match and strip- * @param toPrefix Destination event prefix to prepend- * @returns Cleanup function that removes this forwarding relationship- */- public publishTo(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {-- this.$outbound.forwardTo(theLink.$outbound, fromPrefix, toPrefix)-- return () => this.stopPublishingTo(theLink, fromPrefix, toPrefix)- }-- /**- * Stop forwarding this link's outbound events into another link.- *- * @param theLink Target link used during publication forwarding- * @param fromPrefix Source prefix used during forwarding- * @param toPrefix Destination prefix used during forwarding- */- public stopPublishingTo(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {-- this.$outbound.stopForwardingTo(theLink.$outbound, fromPrefix, toPrefix)- }-- /**- * Connect this link to another link in both directions.- *- * `fromPrefix` applies to events received from the target link. `toPrefix`- * applies to events sent to the target link, with prefixes swapped for the- * outbound side so the relationship is symmetric.- *- * @param theLink Link to connect with- * @param fromPrefix Prefix for events received from the target link- * @param toPrefix Prefix for events sent to the target link- * @returns Cleanup function that disconnects both directions- */- public connectTo(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {-- this.subscribeTo(theLink, fromPrefix, toPrefix)-- this.publishTo(theLink, toPrefix, fromPrefix)-- return () => this.disconnectFrom(theLink, fromPrefix, toPrefix)- }-- /**- * Disconnect a bidirectional relationship created by connectTo().- *- * @param theLink Link to disconnect from- * @param fromPrefix Prefix used for received events- * @param toPrefix Prefix used for sent events- */- public disconnectFrom(theLink: TheLink, fromPrefix: string = "", toPrefix: string = "") {-- this.unsubscribeFrom(theLink, fromPrefix, toPrefix)-- this.stopPublishingTo(theLink, toPrefix, fromPrefix)- }-}--/**- * Constructor-time setup function registered by decorators.- */-export type Initializer<TargetLink extends TheLink> = (instanceLink: TargetLink) => void--/**- * Method shape used by publish-oriented decorators.- */-export type Publisher = (...values: any[]) => Promise<any>--/**- * TheLink tunnel selector used by decorators.- */-export type TunnelName = "outbound" | "inbound"\ No newline at end of filediff --git a/source/libs/the-link/tunnel.ts b/source/libs/the-link/tunnel.tsdeleted file mode 100644index 976e49b..0000000--- a/source/libs/the-link/tunnel.ts+++ /dev/null@@ -1,369 +0,0 @@--/**- * Event tunnel with interceptors, subscribers, forwarders, and finalizers.- *- * A publish call runs through four phases:- * intercept matching prefixes, exact-event subscribers, prefix-based forwarders,- * then result finalizers. Subscribers and forwarders contribute results, while- * interceptors transform payload values and finalizers transform result values.- */-export default class Tunnel {-- /**- * Prefix-matched functions that can transform values before publication.- */- private readonly interceptors: Map<string, Set<Interceptor>> = new Map()-- /**- * Exact event subscribers keyed by event name.- */- private readonly subscribers: Map<string, Set<Subscriber>> = new Map()-- /**- * Forwarding rules keyed by source prefix, then destination prefix.- */- private readonly forwarders: Map<string, Map<string, Set<Forwarder | Tunnel>>> = new Map()-- /**- * Prefix-matched functions that can transform aggregated publish results.- */- private readonly finalizers: Map<string, Set<Finalizer>> = new Map()-- /**- * Register a payload interceptor for events matching a prefix.- *- * @param interceptor Function that can transform publication values- * @param prefix Event prefix to match, or an empty string for all events- * @returns Cleanup function that removes this interceptor- */- public addInterceptor(interceptor: Interceptor, prefix: string = "") {-- if (!this.interceptors.has(prefix)) this.interceptors.set(prefix, new Set())-- this.interceptors.get(prefix)!.add(interceptor)-- return () => this.removeInterceptor(interceptor, prefix)- }-- /**- * Remove a previously registered interceptor.- *- * @param interceptor Interceptor function to remove- * @param prefix Prefix used during registration- */- public removeInterceptor(interceptor: Interceptor, prefix: string = "") {-- const interceptorSet = this.interceptors.get(prefix)-- if (interceptorSet) {-- interceptorSet.delete(interceptor)-- if (interceptorSet.size === 0) this.interceptors.delete(prefix)- }- }-- /**- * Subscribe to an exact event name.- *- * @param event Event identifier to listen for- * @param subscriber Handler invoked when the event is published- * @returns Cleanup function that removes this subscriber- */- public subscribe(event: string, subscriber: Subscriber) {-- if (!this.subscribers.has(event)) this.subscribers.set(event, new Set())-- this.subscribers.get(event)!.add(subscriber)-- return () => this.unsubscribe(event, subscriber)- }-- /**- * Remove a previously registered subscriber.- *- * @param event Event identifier used during registration- * @param subscriber Subscriber function to remove- */- public unsubscribe(event: string, subscriber: Subscriber) {-- const subscriberSet = this.subscribers.get(event)-- if (subscriberSet) {-- subscriberSet.delete(subscriber)-- if (subscriberSet.size === 0) this.subscribers.delete(event)- }- }-- /**- * Subscribe to an event once, then remove the subscriber before it runs.- *- * @param event Event identifier to listen for- * @param subscriber Handler invoked for the first matching publication- * @returns Cleanup function that cancels the pending one-time subscription- */- public subscribeOnce(event: string, subscriber: Subscriber) {-- const removeSubscription = this.subscribe(event, async function (...values) {-- // Remove before invocation so re-entrant publishes do not call it twice.- removeSubscription()-- await subscriber(...values)- })-- return removeSubscription- }-- /**- * Wait for the next publication of an event.- *- * @param event Event identifier to wait for- * @param timeout Maximum wait time in milliseconds- * @returns Event payload values from the next matching publication- * @throws Error when the timeout expires before the event is published- */- public async waitFor<Results extends unknown[]>(event: string, timeout: number = 30_000) {-- return await new Promise<Results>((resolve, reject) => {-- const removeSubscription = this.subscribeOnce(event, function (...values: Results) {-- resolve(values)-- // Cancel timeout work after the awaited event arrives.- if (timer) clearTimeout(timer)- })-- const timer = setTimeout(function () {-- // Remove the one-time subscriber before rejecting on timeout.- removeSubscription()-- reject(new Error(`Event promise timeout ${timeout}ms`))-- }, timeout)- })- }-- /**- * Wait for an event and return only its first payload value.- *- * @param event Event identifier to wait for- * @param timeout Maximum wait time in milliseconds- * @returns First value from the next matching publication- */- public async waitFirst<Result>(event: string, timeout: number = 30_000) {-- const [result] = await this.waitFor<[Result]>(event, timeout)-- return result- }-- /**- * Forward matching events to another Tunnel or a custom forwarder.- *- * Matching removes `fromPrefix` from the source event name, then prepends- * `toPrefix` before forwarding.- *- * @param forwarder Target Tunnel or forwarding function- * @param fromPrefix Source event prefix to match and strip- * @param toPrefix Destination event prefix to prepend- * @returns Cleanup function that removes this forwarding rule- */- public forwardTo(forwarder: Forwarder | Tunnel, fromPrefix: string = "", toPrefix: string = "") {-- if (!this.forwarders.has(fromPrefix)) this.forwarders.set(fromPrefix, new Map())-- const forwardersFrom = this.forwarders.get(fromPrefix)!-- if (!forwardersFrom.has(toPrefix)) forwardersFrom.set(toPrefix, new Set())-- const forwardersTo = forwardersFrom.get(toPrefix)!-- forwardersTo.add(forwarder)-- return () => this.stopForwardingTo(forwarder, fromPrefix, toPrefix)- }-- /**- * Remove a previously registered forwarding rule.- *- * @param forwarder Target Tunnel or forwarding function to remove- * @param fromPrefix Source prefix used during registration- * @param toPrefix Destination prefix used during registration- */- public stopForwardingTo(forwarder: Forwarder | Tunnel, fromPrefix: string = "", toPrefix: string = "") {-- const forwardersFrom = this.forwarders.get(fromPrefix)-- if (!forwardersFrom) return-- const forwardersTo = forwardersFrom.get(toPrefix)-- if (!forwardersTo) return-- forwardersTo.delete(forwarder)-- // Remove now-empty nested maps so stale prefix entries do not accumulate.- if (forwardersTo.size === 0) forwardersFrom.delete(toPrefix)-- if (forwardersFrom.size === 0) this.forwarders.delete(fromPrefix)- }-- /**- * Register a result finalizer for events matching a prefix.- *- * @param finalizer Function that can transform aggregated publish results- * @param prefix Event prefix to match, or an empty string for all events- * @returns Cleanup function that removes this finalizer- */- public addFinalizer(finalizer: Finalizer, prefix: string = "") {-- if (!this.finalizers.has(prefix)) this.finalizers.set(prefix, new Set())-- this.finalizers.get(prefix)!.add(finalizer)-- return () => this.removeFinalizer(finalizer, prefix)- }-- /**- * Remove a previously registered finalizer.- *- * @param finalizer Finalizer function to remove- * @param prefix Prefix used during registration- */- public removeFinalizer(finalizer: Finalizer, prefix: string = "") {-- const finalizerSet = this.finalizers.get(prefix)-- if (finalizerSet) {-- finalizerSet.delete(finalizer)-- if (finalizerSet.size === 0) this.finalizers.delete(prefix)- }- }-- /**- * Publish an event through interceptors, subscribers, forwarders, and finalizers.- *- * @param event Event identifier to publish- * @param values Event payload values- * @returns Aggregated and finalized handler results- */- public async publish<Results extends unknown[]>(event: string, ...values: unknown[]): Promise<Results> {-- let results = []-- // Phase 1: matching interceptors can replace the payload values.- const interceptorGroups = this.interceptors.entries().filter(([prefix]) => event.startsWith(prefix))-- for (const [_prefix, interceptorSet] of interceptorGroups) {-- for (const interceptor of interceptorSet) {-- const transformedValues = await interceptor(...values)-- if (Array.isArray(transformedValues)) values = transformedValues-- // A single non-undefined value becomes the next payload tuple.- else if (transformedValues !== undefined) values = [transformedValues]- }- }-- // Phase 2: exact-event subscribers run with the final payload values.- const subscribers = this.subscribers.get(event) || []-- for (const subscriber of subscribers) {-- const result = await subscriber(...values)-- if (result !== undefined) results.push(result)- }-- // Phase 3: prefix-matched forwarders receive rewritten event names.- const forwardersFrom = this.forwarders.entries().filter(([prefix]) => event.startsWith(prefix))-- for (const [fromPrefix, forwardersTo] of forwardersFrom) {-- for (const [toPrefix, forwarders] of forwardersTo) {-- for (const forwarder of forwarders) {-- if (forwarder instanceof Tunnel) {-- // Tunnel forwarders return arrays that are flattened into this result set.- const result = await forwarder.publish(toPrefix + event.slice(fromPrefix.length), ...values)-- results.push(...result)- }-- else {-- const result = await forwarder(toPrefix + event.slice(fromPrefix.length), ...values)-- if (Array.isArray(result)) results.push(...result)-- // Custom forwarders can return one value or an array of values.- else if (result !== undefined) results.push(result)- }- }- }- }-- // Phase 4: matching finalizers can replace the aggregated result values.- const finalizerGroups = this.finalizers.entries().filter(([prefix]) => event.startsWith(prefix))-- for (const [_prefix, finalizerSet] of finalizerGroups) {-- for (const finalizer of finalizerSet) {-- const transformedResults = await finalizer(...results)-- if (Array.isArray(transformedResults)) results = transformedResults-- // A single non-undefined value becomes the next result tuple.- else if (transformedResults !== undefined) results = [transformedResults]- }- }-- return results as Results- }-- /**- * Publish an event and return only the first result.- *- * @param event Event identifier to publish- * @param values Event payload values- * @returns First value from the aggregated publish results- */- public async publishFirst<Result>(event: string, ...values: unknown[]): Promise<Result> {-- const [result] = await this.publish<[Result]>(event, ...values)-- return result- }-}--/**- * Interceptor function signature for transforming event payload values.- */-export type Interceptor<Values extends unknown[] = any[]> = (...values: Values) => any--/**- * Subscriber function signature for exact event handling.- */-export type Subscriber<Values extends unknown[] = any[]> = (...values: Values) => any--/**- * Forwarder function signature for custom prefix-based routing.- */-export type Forwarder<Values extends unknown[] = any[]> = (forwardedEvent: string, ...values: Values) => any--/**- * Finalizer function signature for transforming aggregated publish results.- */-export type Finalizer<Results extends unknown[] = any[]> = (...results: Results) => any\ No newline at end of filediff --git a/source/server/core/dialog-manager.ts b/source/server/core/dialog-manager.tsindex 9e00e91..af33999 100644--- a/source/server/core/dialog-manager.ts+++ b/source/server/core/dialog-manager.ts@@ -1,6 +1,6 @@-import { Subscribe } from "@libs/the-link/decorators/escript"+import { Subscribe } from "@the-link/core/decorators"import { Transmitted } from "@libs/messagepack"-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"import { randomUUID } from "node:crypto"import { type default as Process } from "./link-manager/auth-manager/process-manager/process"import { type PermissionName } from "@phreshos/core"diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.tsindex 1a5848f..875c741 100644--- a/source/server/core/link-manager/auth-manager/auth-manager.ts+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts@@ -1,10 +1,10 @@-import { Connect, Forward, Intercept, Subscribe } from "@libs/the-link/decorators/escript"+import { Connect, Forward, Intercept, Subscribe } from "@the-link/core/decorators"import UploadManager from "@server/core/upload-manager"import DialogManager from "@server/core/dialog-manager"import ProcessManager from "./process-manager/process-manager"import ProgramManager from "./program-manager/program-manager"import { Transmitted } from "@libs/messagepack"-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"import LinkManager from "../link-manager"import { isPermissionName } from "@phreshos/core"diff --git a/source/server/core/link-manager/auth-manager/process-manager/endpoint-events.ts b/source/server/core/link-manager/auth-manager/process-manager/endpoint-events.tsindex e59ee5e..b2ab06a 100644--- a/source/server/core/link-manager/auth-manager/process-manager/endpoint-events.ts+++ b/source/server/core/link-manager/auth-manager/process-manager/endpoint-events.ts@@ -1,4 +1,4 @@-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"import { type Half } from "./process-traffic"/**diff --git a/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts b/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.tsindex af7599b..df735d0 100644--- a/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts+++ b/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts@@ -1,5 +1,5 @@import { isServiceKey, type ServiceKey } from "@phreshos/core"-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"import type Process from "./process"import type { Half } from "./process-traffic"diff --git a/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts b/source/server/core/link-manager/auth-manager/process-manager/host-traffic.tsindex 9403350..7abba4e 100644--- a/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts+++ b/source/server/core/link-manager/auth-manager/process-manager/host-traffic.ts@@ -1,4 +1,4 @@-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"/** Host announcements routed only into Process boundaries that requested them. */export default class HostTraffic extends TheLink {diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.tsindex 1a46291..00f3466 100644--- a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts+++ b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts@@ -1,10 +1,10 @@-import { Connect, Subscribe } from "@libs/the-link/decorators/escript"+import { Connect, Subscribe } from "@the-link/core/decorators"import { uploadLimit } from "@server/core/upload-manager"import { type Options } from "../program-manager/program-manager"import Program from "../program-manager/program"import { Layer } from "../program-manager/config"import Window, { Position, Size } from "./window"-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"import { Transmitted } from "@libs/messagepack"import AuthManager from "../auth-manager"import Process, { type HostedProcess, type ProcessLaunch } from "./process"diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-traffic.ts b/source/server/core/link-manager/auth-manager/process-manager/process-traffic.tsindex 971891e..afd9c11 100644--- a/source/server/core/link-manager/auth-manager/process-manager/process-traffic.ts+++ b/source/server/core/link-manager/auth-manager/process-manager/process-traffic.ts@@ -1,4 +1,4 @@-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"/*** Application traffic spoken by one Process endpoint.diff --git a/source/server/core/link-manager/auth-manager/process-manager/process.ts b/source/server/core/link-manager/auth-manager/process-manager/process.tsindex 94446e2..aa4fb16 100644--- a/source/server/core/link-manager/auth-manager/process-manager/process.ts+++ b/source/server/core/link-manager/auth-manager/process-manager/process.ts@@ -7,7 +7,7 @@ import HostTraffic from "./host-traffic"import ClientState from "./client-state"import { randomUUID } from "node:crypto"import { type Layer, type PermissionName } from "@phreshos/core"-import Tunnel from "@libs/the-link/tunnel"+import { Tunnel } from "@the-link/core"import type { ServerRuntime } from "./server-runtime"/**diff --git a/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.tsindex 7db9df9..64aa340 100644--- a/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts+++ b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts@@ -1,10 +1,10 @@-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"import ProcessTraffic, { type Half, type TrafficKind } from "./process-traffic"import HostTraffic from "./host-traffic"import EndpointEvents from "./endpoint-events"import EndpointServices, { type ServiceScope } from "./endpoint-services"import type { ServiceKey } from "@phreshos/core"-import Tunnel from "@libs/the-link/tunnel"+import { Tunnel } from "@the-link/core"import messagepack from "@libs/messagepack"import type { ServerRuntime, Stream } from "./server-runtime"diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.tsindex bdd8167..7187f8d 100644--- a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts+++ b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts@@ -1,7 +1,7 @@import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"-import { Connect } from "@libs/the-link/decorators/escript"+import { Connect } from "@the-link/core/decorators"import { randomUUID } from "node:crypto"-import TheLink from "@libs/the-link/the-link"+import { TheLink } from "@the-link/core"import SqliteDatabase from "@libs/sqlite-database"import { Transmitted } from "@libs/messagepack"import FileManager from "@libs/file-manager"diff --git a/source/server/core/link-manager/link-manager.ts b/source/server/core/link-manager/link-manager.tsindex 4557727..65b1a15 100644--- a/source/server/core/link-manager/link-manager.ts+++ b/source/server/core/link-manager/link-manager.ts@@ -1,7 +1,7 @@-import { Forward, Subscribe } from "@libs/the-link/decorators/escript"+import { Forward, Subscribe } from "@the-link/core/decorators"import AuthManager from "./auth-manager/auth-manager"-import TheLink from "@libs/the-link/the-link"-import Property from "@libs/the-link/property"+import { TheLink } from "@the-link/core"+import { Property } from "@the-link/core"import { Transmitted } from "@libs/messagepack"import Application from "../application"import { type Appearance } from "@phreshos/core"diff --git a/source/server/view/link.ts b/source/server/view/link.tsindex a4378f3..44a15ba 100644--- a/source/server/view/link.ts+++ b/source/server/view/link.ts@@ -1,4 +1,4 @@-import ServerLink from "@libs/the-link/plugins/server-link/server-link"+import { ServerLink } from "@the-link/server"import { upgradeWebSocket } from "@hono/node-server"import Application from "@server/core/application"import messagepack from "@libs/messagepack"