mirror of
https://github.com/Start9Labs/start-os.git
synced 2026-03-26 18:31:52 +00:00
* docs: update preferred external port design in TODO * docs: add user-controlled public/private and port forward mapping to design * docs: overhaul interfaces page design with view/manage split and per-address controls * docs: move address enable/disable to overflow menu, add SSL indicator, defer UI placement decisions * chore: remove tor from startos core Tor is being moved from a built-in OS feature to a service. This removes the Arti-based Tor client, onion address management, hidden service creation, and all related code from the core backend, frontend, and SDK. - Delete core/src/net/tor/ module (~2060 lines) - Remove OnionAddress, TorSecretKey, TorController from all consumers - Remove HostnameInfo::Onion and HostAddress::Onion variants - Remove onion CRUD RPC endpoints and tor subcommand - Remove tor key handling from account and backup/restore - Remove ~12 tor-related Cargo dependencies (arti-client, torut, etc.) - Remove tor UI components, API methods, mock data, and routes - Remove OnionHostname and tor patterns/regexes from SDK - Add v0_4_0_alpha_20 database migration to strip onion data - Bump version to 0.4.0-alpha.20 * chore: flatten HostnameInfo from enum to struct HostnameInfo only had one variant (Ip) after removing Tor. Flatten it into a plain struct with fields gateway, public, hostname. Remove all kind === 'ip' type guards and narrowing across SDK, frontend, and container runtime. Update DB migration to strip the kind field. * chore: format RPCSpec.md markdown table * docs: update TODO.md with DerivedAddressInfo design, remove completed tor task * feat: implement preferred port allocation and per-address enable/disable - Add AvailablePorts::try_alloc() with SSL tracking (BTreeMap<u16, bool>) - Add DerivedAddressInfo on BindInfo with private_disabled/public_enabled/possible sets - Add Bindings wrapper with Map impl for patchdb indexed access - Flatten HostAddress from single-variant enum to struct - Replace set-gateway-enabled RPC with set-address-enabled - Remove hostname_info from Host; computed addresses now in BindInfo.addresses.possible - Compute possible addresses inline in NetServiceData::update() - Update DB migration, SDK types, frontend, and container-runtime * feat: replace InterfaceFilter with ForwardRequirements, add WildcardListener, complete alpha.20 bump - Replace DynInterfaceFilter with ForwardRequirements for per-IP forward precision with source-subnet iptables filtering for private forwards - Add WildcardListener (binds [::]:port) to replace the per-gateway NetworkInterfaceListener/SelfContainedNetworkInterfaceListener/ UpgradableListener infrastructure - Update forward-port script with src_subnet and excluded_src env vars - Remove unused filter types and listener infrastructure from gateway.rs - Add availablePorts migration (IdPool -> BTreeMap<u16, bool>) to alpha.20 - Complete version bump to 0.4.0-alpha.20 in SDK and web * outbound gateway support (#3120) * Multiple (#3111) * fix alerts i18n, fix status display, better, remove usb media, hide shutdown for install complete * trigger chnage detection for localize pipe and round out implementing localize pipe for consistency even though not needed * Fix PackageInfoShort to handle LocaleString on releaseNotes (#3112) * Fix PackageInfoShort to handle LocaleString on releaseNotes * fix: filter by target_version in get_matching_models and pass otherVersions from install * chore: add exver documentation for ai agents * frontend plus some be types --------- Co-authored-by: Aiden McClelland <3732071+dr-bonez@users.noreply.github.com> * feat: replace SourceFilter with IpNet, add policy routing, remove MASQUERADE * build ts types and fix i18n * fix license display in marketplace * wip refactor * chore: update ts bindings for preferred port design * feat: refactor NetService to watch DB and reconcile network state - NetService sync task now uses PatchDB DbWatch instead of being called directly after DB mutations - Read gateways from DB instead of network interface context when updating host addresses - gateway sync updates all host addresses in the DB - Add Watch<u64> channel for callers to wait on sync completion - Fix ts-rs codegen bug with #[ts(skip)] on flattened Plugin field - Update SDK getServiceInterface.ts for new HostnameInfo shape - Remove unnecessary HTTPS redirect in static_server.rs - Fix tunnel/api.rs to filter for WAN IPv4 address * re-arrange (#3123) * new service interfacee page * feat: add mdns hostname metadata variant and fix vhost routing - Add HostnameMetadata::Mdns variant to distinguish mDNS from private domains - Mark mDNS addresses as private (public: false) since mDNS is local-only - Fall back to null SNI entry when hostname not found in vhost mapping - Simplify public detection in ProxyTarget filter - Pass hostname to update_addresses for mDNS domain name generation * looking good * feat: add port_forwards field to Host for tracking gateway forwarding rules * update bindings for API types, add ARCHITECTURE (#3124) * update binding for API types, add ARCHITECTURE * translations * fix: add CONNMARK restore-mark to mangle OUTPUT chain The CONNMARK --restore-mark rule was only in PREROUTING, which handles forwarded packets. Locally-bound listeners (e.g. vhost) generate replies through the OUTPUT chain, where the fwmark was never restored. This caused response packets to route via the default table instead of back through the originating interface. * chore: reserialize db on equal version, update bindings and docs - Run de/ser roundtrip in pre_init even when db version matches, ensuring all #[serde(default)] fields are populated before any typed access - Add patchdb.md documentation for TypedDbWatch patterns - Update TS bindings for CheckPortParams, CheckPortRes, ifconfigUrl - Update CLAUDE.md docs with patchdb and component-level references * fix: include public gateways for IP-based addresses in vhost targets The server hostname vhost construction only collected private IPs, always setting public to empty. Public IP addresses (Ipv4/Ipv6 metadata with public=true) were never added to the vhost target's public gateway set, causing the vhost filter to reject public traffic for IP-based addresses. * fix: add TLS handshake timeout and fix accept loop deadlock Two issues in TlsListener::poll_accept: 1. No timeout on TLS handshakes: LazyConfigAcceptor waits indefinitely for ClientHello. Attackers that complete TCP handshake but never send TLS data create zombie futures in `in_progress` that never complete. Fix: wrap the entire handshake in tokio::time::timeout(15s). 2. Missing waker on new-connection pending path: when a TCP connection is accepted and the TLS handshake is pending, poll_accept returned Pending without calling wake_by_ref(). Since the TcpListener returned Ready (not Pending), no waker was registered for it. With edge- triggered epoll and no other wakeup source, the task sleeps forever and remaining connections in the kernel accept queue are never drained. Fix: add cx.waker().wake_by_ref() so the task immediately re-polls and continues draining the accept queue. * fix: switch BackgroundJobRunner from Vec to FuturesUnordered BackgroundJobRunner stored active jobs in a Vec<BoxFuture> and polled ALL of them on every wakeup — O(n) per poll. Since this runs in the same tokio::select! as the WebServer accept loop, polling overhead from active connections directly delayed acceptance of new connections. FuturesUnordered only polls woken futures — O(woken) instead of O(n). * chore: update bindings and use typed params for outbound gateway API * feat: per-service and default outbound gateway routing Add set-outbound-gateway RPC for packages and set-default-outbound RPC for the server, with policy routing enforcement via ip rules. Fix connmark restore to skip packets with existing fwmarks, add bridge subnet routes to per-interface tables, and fix squashfs path in update-image-local.sh. * refactor: manifest wraps PackageMetadata, move dependency_metadata to PackageVersionInfo Manifest now embeds PackageMetadata via #[serde(flatten)] instead of duplicating ~14 fields. icon and dependency_metadata moved from PackageMetadata to PackageVersionInfo since they are registry-enrichment data loaded from the S9PK archive. merge_with now returns errors on metadata/icon/dependency_metadata mismatches instead of silently ignoring them. * fix: replace .status() with .invoke() for iptables/ip commands Using .status() leaks stderr directly to system logs, causing noisy iptables error messages. Switch all networking CLI invocations to use .invoke() which captures stderr properly. For check-then-act patterns (iptables -C), use .invoke().await.is_err() instead of .status().await.map_or(false, |s| s.success()). * feat: add check-dns gateway endpoint and fix per-interface routing tables Add a `check-dns` RPC endpoint that verifies whether a gateway's DNS is properly configured for private domain resolution. Uses a three-tier check: direct match (DNS == server IP), TXT challenge probe (DNS on LAN), or failure (DNS off-subnet). Fix per-interface routing tables to clone all non-default routes from the main table instead of only the interface's own subnets. This preserves LAN reachability when the priority-75 catch-all overrides default routing. Filter out status-only flags (linkdown, dead) that are invalid for `ip route add`. * refactor: rename manifest metadata fields and improve error display Rename wrapperRepo→packageRepo, marketingSite→marketingUrl, docsUrl→docsUrls (array), remove supportSite. Add display_src/display_dbg helpers to Error. Fix DepInfo description type to LocaleString. Update web UI, SDK bindings, tests, and fixtures to match. Clean up cli_attach error handling and remove dead commented code. * chore: bump sdk version to 0.4.0-beta.49 * chore: add createTask decoupling TODO * chore: add TODO to clear service error state on install/update * round out dns check, dns server check, port forward check, and gateway port forwards * chore: add TODOs for URL plugins, NAT hairpinning, and start-tunnel OTA updates * version instead of os query param * interface row clickable again, bu now with a chevron! * feat: implement URL plugins with table/row actions and prefill support - Add URL plugin effects (register, export_url, clear_urls) in core - Add PluginHostnameInfo, HostnameMetadata::Plugin, and plugin registration types - Implement plugin URL table in web UI with tableAction button and rowAction overflow menus - Thread urlPluginMetadata (packageId, hostId, interfaceId, internalPort) as prefill to actions - Add prefill support to PackageActionData so metadata passes through form dialogs - Add i18n translations for plugin error messages - Clean up plugin URLs on package uninstall * feat: split row_actions into remove_action and overflow_actions for URL plugins * touch up URL plugins table * show table even when no addresses * feat: NAT hairpinning, DNS static servers, clear service error on install - Add POSTROUTING MASQUERADE rules for container and host hairpin NAT - Allow bridge subnet containers to reach private forwards via LAN IPs - Pass bridge_subnet env var from forward.rs to forward-port script - Use DB-configured static DNS servers in resolver with DB watcher - Fall back to resolv.conf servers when no static servers configured - Clear service error state when install/update completes successfully - Remove completed TODO items * feat: builder-style InputSpec API, prefill plumbing, and port forward fix - Add addKey() and add() builder methods to InputSpec with InputSpecTools - Move OuterType to last generic param on Value, List, and all dynamic methods - Plumb prefill through getActionInput end-to-end (core → container-runtime → SDK) - Filter port_forwards to enabled addresses only - Bump SDK to 0.4.0-beta.50 * fix: propagate host locale into LXC containers and write locale.conf * chore: remove completed URL plugins TODO * feat: OTA updates for start-tunnel via apt repository (untested) - Add apt repo publish script (build/apt/publish-deb.sh) for S3-hosted repo - Add apt source config and GPG key placeholder (apt/) - Add tunnel.update.check and tunnel.update.apply RPC endpoints - Wire up update API in tunnel frontend (api service + mock) - Uses systemd-run --scope to survive service restart during update * fix: publish script dpkg-name, s3cfg fallback, and --reinstall for apply * chore: replace OTA updates TODO with UI TODO for MattDHill * feat: add getOutboundGateway effect and simplify VersionGraph init/uninit Add getOutboundGateway effect across core, container-runtime, and SDK to let services query their effective outbound gateway with callback support. Remove preInstall/uninstall hooks from VersionGraph as they are no longer needed. * frontend start-tunnel updates * chore: remove completed TODO * feat: tor hidden service key migration * chore: migrate from ts-matches to zod across all TypeScript packages * feat(core): allow setting server hostname * send prefill for tasks and hide operations to hidden fields * fix(core): preserve plugin URLs across binding updates BindInfo::update was replacing addresses with a new DerivedAddressInfo that cleared the available set, wiping plugin-exported URLs whenever bind() was called. Also simplify update_addresses plugin preservation to use retain in place rather than collecting into a separate set. * minor cleanup from patch-db audit * clean up prefill flow * frontend support for setting and changing hostname * feat(core): refactor hostname to ServerHostnameInfo with name/hostname pair - Rename Hostname to ServerHostnameInfo, add name + hostname fields - Add set_hostname_rpc for changing hostname at runtime - Migrate alpha_20: generate serverInfo.name from hostname, delete ui.name - Extract gateway.rs helpers to fix rustfmt nesting depth issue - Add i18n key for hostname validation error - Update SDK bindings * add comments to everything potentially consumer facing (#3127) * add comments to everything potentially consumer facing * rework smtp --------- Co-authored-by: Aiden McClelland <3732071+dr-bonez@users.noreply.github.com> * implement server name * setup changes * clean up copy around addresses table * feat: add zod-deep-partial, partialValidator on InputSpec, and z.deepPartial re-export * fix: header color in zoom (#3128) * fix: merge version ranges when adding existing package signer (#3125) * fix: merge version ranges when adding existing package signer Previously, add_package_signer unconditionally inserted the new version range, overwriting any existing authorization for that signer. Now it OR-merges the new range with the existing one, so running signer add multiple times accumulates permissions rather than replacing them. * add --merge flag to registry package signer add Default behavior remains overwrite. When --merge is passed, the new version range is OR-merged with the existing one, allowing admins to accumulate permissions incrementally. * add missing attribute to TS type * make merge optional * upsert instead of insert * VersionRange::None on upsert * fix: header color in zoom --------- Co-authored-by: Dominion5254 <musashidisciple@proton.me> * update snake and add about this server to system general * chore: bump sdk to beta.53, wrap z.deepPartial with passthrough * reset instead of reset defaults * action failure show dialog * chore: bump sdk to beta.54, add device-info RPC, improve SDK abort handling and InputSpec filtering - Bump SDK version to 0.4.0-beta.54 - Add `server.device-info` RPC endpoint and `s9pk select` CLI command - Extract `HardwareRequirements::is_compatible()` method, reuse in registry filtering - Add `AbortedError` class with `muteUnhandled` flag, replace generic abort errors - Handle unhandled promise rejections in container-runtime with mute support - Improve `InputSpec.filter()` with `keepByDefault` param and boolean filter values - Accept readonly tuples in `CommandType` and `splitCommand` - Remove `sync_host` calls from host API handlers (binding/address changes) - Filter mDNS hostnames by secure gateway availability - Derive mDNS enabled state from LAN IPs in web UI - Add "Open UI" action to address table, disable mDNS toggle - Hide debug details in service error component - Update rpc-toolkit docs for no-params handlers * fix: add --no-nvram to efi grub-install to preserve built-in boot order * update snake * diable actions when in error state * chore: split out nvidia variant * misc bugfixes * create manage-release script (untested) * fix: preserve z namespace types for sdk consumers * sdk version bump * new checkPort types * multiple bugs and better port forward ux * fix link * chore: todos and formatting * fix build --------- Co-authored-by: Matt Hill <MattDHill@users.noreply.github.com> Co-authored-by: Matt Hill <mattnine@protonmail.com> Co-authored-by: Alex Inkin <alexander@inkin.ru> Co-authored-by: Dominion5254 <musashidisciple@proton.me>
689 lines
20 KiB
TypeScript
689 lines
20 KiB
TypeScript
import { z } from 'zod'
|
|
import * as YAML from 'yaml'
|
|
import * as TOML from '@iarna/toml'
|
|
import * as INI from 'ini'
|
|
import * as T from '../../../base/lib/types'
|
|
import * as fs from 'node:fs/promises'
|
|
import { AbortedError, asError, deepEqual } from '../../../base/lib/util'
|
|
import { DropGenerator, DropPromise } from '../../../base/lib/util/Drop'
|
|
import { PathBase } from './Volume'
|
|
|
|
const previousPath = /(.+?)\/([^/]*)$/
|
|
|
|
const exists = (path: string) =>
|
|
fs.access(path).then(
|
|
() => true,
|
|
() => false,
|
|
)
|
|
|
|
async function onCreated(path: string) {
|
|
if (path === '/') return
|
|
if (!path.startsWith('/')) path = `${process.cwd()}/${path}`
|
|
if (await exists(path)) {
|
|
return
|
|
}
|
|
const split = path.split('/')
|
|
const filename = split.pop()
|
|
const parent = split.join('/')
|
|
await onCreated(parent)
|
|
const ctrl = new AbortController()
|
|
const watch = fs.watch(parent, { persistent: false, signal: ctrl.signal })
|
|
if (await exists(path)) {
|
|
ctrl.abort()
|
|
return
|
|
}
|
|
if (
|
|
await fs.access(path).then(
|
|
() => true,
|
|
() => false,
|
|
)
|
|
) {
|
|
ctrl.abort()
|
|
return
|
|
}
|
|
for await (let event of watch) {
|
|
if (event.filename === filename) {
|
|
ctrl.abort('finished')
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
function fileMerge(...args: any[]): any {
|
|
let res = args.shift()
|
|
for (const arg of args) {
|
|
if (res === arg) continue
|
|
else if (
|
|
res &&
|
|
arg &&
|
|
typeof res === 'object' &&
|
|
typeof arg === 'object' &&
|
|
!Array.isArray(res) &&
|
|
!Array.isArray(arg)
|
|
) {
|
|
for (const key of Object.keys(arg)) {
|
|
res[key] = fileMerge(res[key], arg[key])
|
|
}
|
|
} else res = arg
|
|
}
|
|
return res
|
|
}
|
|
|
|
function filterUndefined<A>(a: A): A {
|
|
if (a && typeof a === 'object') {
|
|
if (Array.isArray(a)) {
|
|
return a.map(filterUndefined) as A
|
|
}
|
|
return Object.entries(a).reduce<Record<string, any>>((acc, [k, v]) => {
|
|
if (v !== undefined) {
|
|
acc[k] = filterUndefined(v)
|
|
}
|
|
return acc
|
|
}, {}) as A
|
|
}
|
|
return a
|
|
}
|
|
|
|
/**
|
|
* Bidirectional transformers for converting between the raw file format and
|
|
* the application-level data type. Used with FileHelper factory methods.
|
|
*
|
|
* @typeParam Raw - The native type the file format parses to (e.g. `Record<string, unknown>` for JSON)
|
|
* @typeParam Transformed - The application-level type after transformation
|
|
*/
|
|
export type Transformers<
|
|
Raw = unknown,
|
|
Transformed = unknown,
|
|
Validated extends Transformed = Transformed,
|
|
> = {
|
|
/** Transform raw parsed data into the application type */
|
|
onRead: (value: Raw) => Transformed
|
|
/** Transform application data back into the raw format for writing */
|
|
onWrite: (value: Validated) => Raw
|
|
}
|
|
|
|
type ToPath = string | { base: PathBase; subpath: string }
|
|
function toPath(path: ToPath): string {
|
|
if (typeof path === 'string') {
|
|
return path
|
|
}
|
|
return path.base.subpath(path.subpath)
|
|
}
|
|
|
|
type Validator<_T, U> = z.ZodType<U>
|
|
|
|
type ReadType<A> = {
|
|
once: () => Promise<A | null>
|
|
const: (effects: T.Effects) => Promise<A | null>
|
|
watch: (
|
|
effects: T.Effects,
|
|
abort?: AbortSignal,
|
|
) => AsyncGenerator<A | null, never, unknown>
|
|
onChange: (
|
|
effects: T.Effects,
|
|
callback: (
|
|
value: A | null,
|
|
error?: Error,
|
|
) => { cancel: boolean } | Promise<{ cancel: boolean }>,
|
|
) => void
|
|
waitFor: (
|
|
effects: T.Effects,
|
|
pred: (value: A | null) => boolean,
|
|
) => Promise<A | null>
|
|
}
|
|
|
|
/**
|
|
* @description Use this class to read/write an underlying configuration file belonging to the upstream service.
|
|
*
|
|
* These type definitions should reflect the underlying file as closely as possible. For example, if the service does not require a particular value, it should be marked as optional(), even if your package requires it.
|
|
*
|
|
* It is recommended to use onMismatch() whenever possible. This provides an escape hatch in case the user edits the file manually and accidentally sets a value to an unsupported type.
|
|
*
|
|
* Officially supported file types are json, yaml, and toml. Other files types can use "raw"
|
|
*
|
|
* Choose between officially supported file formats (), or a custom format (raw).
|
|
*
|
|
* @example
|
|
* Below are a few examples
|
|
*
|
|
* ```
|
|
* import { matches, FileHelper } from '@start9labs/start-sdk'
|
|
* const { arrayOf, boolean, literal, literals, object, natural, string } = matches
|
|
*
|
|
* export const jsonFile = FileHelper.json('./inputSpec.json', object({
|
|
* passwords: arrayOf(string).onMismatch([])
|
|
* type: literals('private', 'public').optional().onMismatch(undefined)
|
|
* }))
|
|
*
|
|
* export const tomlFile = FileHelper.toml('./inputSpec.toml', object({
|
|
* url: literal('https://start9.com').onMismatch('https://start9.com')
|
|
* public: boolean.onMismatch(true)
|
|
* }))
|
|
*
|
|
* export const yamlFile = FileHelper.yaml('./inputSpec.yml', object({
|
|
* name: string.optional().onMismatch(undefined)
|
|
* age: natural.optional().onMismatch(undefined)
|
|
* }))
|
|
*
|
|
* export const bitcoinConfFile = FileHelper.raw(
|
|
* './service.conf',
|
|
* (obj: CustomType) => customConvertObjToFormattedString(obj),
|
|
* (str) => customParseStringToTypedObj(str),
|
|
* )
|
|
* ```
|
|
*/
|
|
export class FileHelper<A> {
|
|
private consts: [
|
|
() => void,
|
|
any,
|
|
(a: any) => any,
|
|
(left: any, right: any) => any,
|
|
][] = []
|
|
protected constructor(
|
|
readonly path: string,
|
|
readonly writeData: (dataIn: A) => string,
|
|
readonly readData: (stringValue: string) => unknown,
|
|
readonly validate: (value: unknown) => A,
|
|
) {}
|
|
|
|
private async writeFileRaw(data: string): Promise<null> {
|
|
const parent = previousPath.exec(this.path)
|
|
if (parent) {
|
|
await fs.mkdir(parent[1], { recursive: true })
|
|
}
|
|
|
|
await fs.writeFile(this.path, data)
|
|
|
|
return null
|
|
}
|
|
|
|
/**
|
|
* Accepts structured data and overwrites the existing file on disk.
|
|
*/
|
|
private async writeFile(data: A): Promise<null> {
|
|
return await this.writeFileRaw(this.writeData(data))
|
|
}
|
|
|
|
private async readFileRaw(): Promise<string | null> {
|
|
if (!(await exists(this.path))) {
|
|
return null
|
|
}
|
|
return await fs.readFile(this.path).then((data) => data.toString('utf-8'))
|
|
}
|
|
|
|
private async readFile(): Promise<unknown> {
|
|
const raw = await this.readFileRaw()
|
|
if (raw === null) {
|
|
return raw
|
|
}
|
|
return this.readData(raw)
|
|
}
|
|
|
|
/**
|
|
* Reads the file from disk and converts it to structured data.
|
|
*/
|
|
private async readOnce<B>(map: (value: A) => B): Promise<B | null> {
|
|
const data = await this.readFile()
|
|
if (!data) return null
|
|
return map(this.validate(data))
|
|
}
|
|
|
|
private async readConst<B>(
|
|
effects: T.Effects,
|
|
map: (value: A) => B,
|
|
eq: (left: B | null | undefined, right: B | null) => boolean,
|
|
): Promise<B | null> {
|
|
const watch = this.readWatch(effects, map, eq)
|
|
const res = await watch.next()
|
|
if (effects.constRetry) {
|
|
const record: (typeof this.consts)[number] = [
|
|
effects.constRetry,
|
|
res.value,
|
|
map,
|
|
eq,
|
|
]
|
|
this.consts.push(record)
|
|
watch
|
|
.next()
|
|
.then(() => {
|
|
this.consts = this.consts.filter((r) => r !== record)
|
|
effects.constRetry && effects.constRetry()
|
|
})
|
|
.catch()
|
|
}
|
|
return res.value
|
|
}
|
|
|
|
private async *readWatch<B>(
|
|
effects: T.Effects,
|
|
map: (value: A) => B,
|
|
eq: (left: B | null | undefined, right: B | null) => boolean,
|
|
abort?: AbortSignal,
|
|
) {
|
|
let prev: { value: B | null } | null = null
|
|
while (effects.isInContext && !abort?.aborted) {
|
|
if (await exists(this.path)) {
|
|
const ctrl = new AbortController()
|
|
abort?.addEventListener('abort', () => ctrl.abort())
|
|
const watch = fs.watch(this.path, {
|
|
persistent: false,
|
|
signal: ctrl.signal,
|
|
})
|
|
const newRes = await this.readOnce(map)
|
|
const listen = Promise.resolve()
|
|
.then(async () => {
|
|
for await (const _ of watch) {
|
|
ctrl.abort()
|
|
return null
|
|
}
|
|
})
|
|
.catch((e) => console.error(asError(e)))
|
|
if (!prev || !eq(prev.value, newRes)) {
|
|
console.error('yielding', JSON.stringify({ prev: prev, newRes }))
|
|
yield newRes
|
|
}
|
|
prev = { value: newRes }
|
|
await listen
|
|
} else {
|
|
yield null
|
|
await onCreated(this.path).catch((e) => console.error(asError(e)))
|
|
}
|
|
}
|
|
return new Promise<never>((_, rej) => rej(new AbortedError()))
|
|
}
|
|
|
|
private readOnChange<B>(
|
|
effects: T.Effects,
|
|
callback: (
|
|
value: B | null,
|
|
error?: Error,
|
|
) => { cancel: boolean } | Promise<{ cancel: boolean }>,
|
|
map: (value: A) => B,
|
|
eq: (left: B | null | undefined, right: B | null) => boolean,
|
|
) {
|
|
;(async () => {
|
|
const ctrl = new AbortController()
|
|
for await (const value of this.readWatch(effects, map, eq, ctrl.signal)) {
|
|
try {
|
|
const res = await callback(value)
|
|
if (res.cancel) ctrl.abort()
|
|
} catch (e) {
|
|
console.error(
|
|
'callback function threw an error @ FileHelper.read.onChange',
|
|
e,
|
|
)
|
|
}
|
|
}
|
|
})()
|
|
.catch((e) => callback(null, e))
|
|
.catch((e) =>
|
|
console.error(
|
|
'callback function threw an error @ FileHelper.read.onChange',
|
|
e,
|
|
),
|
|
)
|
|
}
|
|
|
|
private readWaitFor<B>(
|
|
effects: T.Effects,
|
|
pred: (value: B | null, error?: Error) => boolean,
|
|
map: (value: A) => B,
|
|
): Promise<B | null> {
|
|
const ctrl = new AbortController()
|
|
return DropPromise.of(
|
|
Promise.resolve().then(async () => {
|
|
const watch = this.readWatch(effects, map, (_) => false, ctrl.signal)
|
|
while (true) {
|
|
try {
|
|
const res = await watch.next()
|
|
if (pred(res.value)) {
|
|
ctrl.abort()
|
|
return res.value
|
|
}
|
|
if (res.done) {
|
|
break
|
|
}
|
|
} catch (e) {
|
|
if (pred(null, e as Error)) {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
ctrl.abort()
|
|
return null
|
|
}),
|
|
() => ctrl.abort(),
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Create a reactive reader for this file.
|
|
*
|
|
* Returns an object with multiple read strategies:
|
|
* - `once()` - Read the file once and return the parsed value
|
|
* - `const(effects)` - Read once but re-read when the file changes (for use with constRetry)
|
|
* - `watch(effects)` - Async generator yielding new values on each file change
|
|
* - `onChange(effects, callback)` - Fire a callback on each file change
|
|
* - `waitFor(effects, predicate)` - Block until the file value satisfies a predicate
|
|
*
|
|
* @param map - Optional transform function applied after validation
|
|
* @param eq - Optional equality function to deduplicate watch emissions
|
|
*/
|
|
read(): ReadType<A>
|
|
read<B>(
|
|
map: (value: A) => B,
|
|
eq?: (left: B | null | undefined, right: B | null) => boolean,
|
|
): ReadType<B>
|
|
read(
|
|
map?: (value: A) => any,
|
|
eq?: (left: any, right: any) => boolean,
|
|
): ReadType<any> {
|
|
map = map ?? ((a: A) => a)
|
|
eq = eq ?? deepEqual
|
|
return {
|
|
once: () => this.readOnce(map),
|
|
const: (effects: T.Effects) => this.readConst(effects, map, eq),
|
|
watch: (effects: T.Effects, abort?: AbortSignal) => {
|
|
const ctrl = new AbortController()
|
|
abort?.addEventListener('abort', () => ctrl.abort())
|
|
return DropGenerator.of(
|
|
this.readWatch(effects, map, eq, ctrl.signal),
|
|
() => ctrl.abort(),
|
|
)
|
|
},
|
|
onChange: (
|
|
effects: T.Effects,
|
|
callback: (
|
|
value: A | null,
|
|
error?: Error,
|
|
) => { cancel: boolean } | Promise<{ cancel: boolean }>,
|
|
) => this.readOnChange(effects, callback, map, eq),
|
|
waitFor: (effects: T.Effects, pred: (value: A | null) => boolean) =>
|
|
this.readWaitFor(effects, pred, map),
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Accepts full structured data and overwrites the existing file on disk if it exists.
|
|
*/
|
|
async write(
|
|
effects: T.Effects,
|
|
data: T.AllowReadonly<A> | A,
|
|
options: { allowWriteAfterConst?: boolean } = {},
|
|
) {
|
|
const newData = this.validate(data)
|
|
await this.writeFile(newData)
|
|
if (!options.allowWriteAfterConst && effects.constRetry) {
|
|
const records = this.consts.filter(([c]) => c === effects.constRetry)
|
|
for (const record of records) {
|
|
const [_, prev, map, eq] = record
|
|
if (!eq(prev, map(newData))) {
|
|
throw new Error(`Canceled: write after const: ${this.path}`)
|
|
}
|
|
}
|
|
}
|
|
return null
|
|
}
|
|
|
|
/**
|
|
* Accepts partial structured data and performs a merge with the existing file on disk.
|
|
*/
|
|
async merge(
|
|
effects: T.Effects,
|
|
data: T.AllowReadonly<T.DeepPartial<A>>,
|
|
options: { allowWriteAfterConst?: boolean } = {},
|
|
) {
|
|
const fileDataRaw = await this.readFileRaw()
|
|
let fileData: any = fileDataRaw === null ? null : this.readData(fileDataRaw)
|
|
try {
|
|
fileData = this.validate(fileData)
|
|
} catch (_) {}
|
|
const mergeData = this.validate(fileMerge({}, fileData, data))
|
|
const toWrite = this.writeData(mergeData)
|
|
if (toWrite !== fileDataRaw) {
|
|
this.writeFile(mergeData)
|
|
if (!options.allowWriteAfterConst && effects.constRetry) {
|
|
const records = this.consts.filter(([c]) => c === effects.constRetry)
|
|
for (const record of records) {
|
|
const [_, prev, map, eq] = record
|
|
if (!eq(prev, map(mergeData))) {
|
|
throw new Error(`Canceled: write after const: ${this.path}`)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return null
|
|
}
|
|
|
|
/**
|
|
* We wanted to be able to have a fileHelper, and just modify the path later in time.
|
|
* Like one behavior of another dependency or something similar.
|
|
*/
|
|
withPath(path: ToPath) {
|
|
return new FileHelper<A>(
|
|
toPath(path),
|
|
this.writeData,
|
|
this.readData,
|
|
this.validate,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Create a File Helper for an arbitrary file type.
|
|
*
|
|
* Provide custom functions for translating data to/from the file format.
|
|
*/
|
|
static raw<A>(
|
|
path: ToPath,
|
|
toFile: (dataIn: A) => string,
|
|
fromFile: (rawData: string) => unknown,
|
|
validate: (data: unknown) => A,
|
|
) {
|
|
return new FileHelper<A>(toPath(path), toFile, fromFile, validate)
|
|
}
|
|
|
|
private static rawTransformed<A extends Transformed, Raw, Transformed>(
|
|
path: ToPath,
|
|
toFile: (dataIn: Raw) => string,
|
|
fromFile: (rawData: string) => Raw,
|
|
validate: (data: Transformed) => A,
|
|
transformers: Transformers<Raw, Transformed, A> | undefined,
|
|
) {
|
|
return FileHelper.raw<A>(
|
|
path,
|
|
(inData) => {
|
|
if (transformers) {
|
|
return toFile(transformers.onWrite(inData))
|
|
}
|
|
return toFile(inData as any as Raw)
|
|
},
|
|
(fileData) => {
|
|
if (transformers) {
|
|
return transformers.onRead(fromFile(fileData))
|
|
}
|
|
return fromFile(fileData)
|
|
},
|
|
validate as (a: unknown) => A,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Create a File Helper for a text file
|
|
*/
|
|
static string(path: ToPath): FileHelper<string>
|
|
static string<A extends string>(
|
|
path: ToPath,
|
|
shape: Validator<string, A>,
|
|
): FileHelper<A>
|
|
static string<A extends Transformed, Transformed = string>(
|
|
path: ToPath,
|
|
shape: Validator<Transformed, A>,
|
|
transformers: Transformers<string, Transformed, A>,
|
|
): FileHelper<A>
|
|
static string<A extends Transformed, Transformed = string>(
|
|
path: ToPath,
|
|
shape?: Validator<Transformed, A>,
|
|
transformers?: Transformers<string, Transformed, A>,
|
|
) {
|
|
return FileHelper.rawTransformed<A, string, Transformed>(
|
|
path,
|
|
(inData) => inData,
|
|
(inString) => inString,
|
|
(data) =>
|
|
(shape || (z.string() as unknown as Validator<Transformed, A>)).parse(
|
|
data,
|
|
),
|
|
transformers,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Create a File Helper for a .json file.
|
|
*/
|
|
static json<A>(path: ToPath, shape: Validator<unknown, A>): FileHelper<A>
|
|
static json<A extends Transformed, Transformed = unknown>(
|
|
path: ToPath,
|
|
shape: Validator<unknown, A>,
|
|
transformers: Transformers<unknown, Transformed, A>,
|
|
): FileHelper<A>
|
|
static json<A extends Transformed, Transformed = unknown>(
|
|
path: ToPath,
|
|
shape: Validator<unknown, A>,
|
|
transformers?: Transformers<unknown, Transformed, A>,
|
|
) {
|
|
return FileHelper.rawTransformed(
|
|
path,
|
|
(inData) => JSON.stringify(inData, null, 2),
|
|
(inString) => JSON.parse(inString),
|
|
(data) => shape.parse(data),
|
|
transformers,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Create a File Helper for a .yaml file
|
|
*/
|
|
static yaml<A extends Record<string, unknown>>(
|
|
path: ToPath,
|
|
shape: Validator<Record<string, unknown>, A>,
|
|
): FileHelper<A>
|
|
static yaml<A extends Transformed, Transformed = Record<string, unknown>>(
|
|
path: ToPath,
|
|
shape: Validator<Transformed, A>,
|
|
transformers: Transformers<Record<string, unknown>, Transformed, A>,
|
|
): FileHelper<A>
|
|
static yaml<A extends Transformed, Transformed = Record<string, unknown>>(
|
|
path: ToPath,
|
|
shape: Validator<Transformed, A>,
|
|
transformers?: Transformers<Record<string, unknown>, Transformed, A>,
|
|
) {
|
|
return FileHelper.rawTransformed<A, Record<string, unknown>, Transformed>(
|
|
path,
|
|
(inData) => YAML.stringify(inData, null, 2),
|
|
(inString) => YAML.parse(inString),
|
|
(data) => shape.parse(data),
|
|
transformers,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Create a File Helper for a .toml file
|
|
*/
|
|
static toml<A extends Record<string, unknown>>(
|
|
path: ToPath,
|
|
shape: Validator<Record<string, unknown>, A>,
|
|
): FileHelper<A>
|
|
static toml<A extends Transformed, Transformed = Record<string, unknown>>(
|
|
path: ToPath,
|
|
shape: Validator<Transformed, A>,
|
|
transformers: Transformers<Record<string, unknown>, Transformed, A>,
|
|
): FileHelper<A>
|
|
static toml<A extends Transformed, Transformed = Record<string, unknown>>(
|
|
path: ToPath,
|
|
shape: Validator<Transformed, A>,
|
|
transformers?: Transformers<Record<string, unknown>, Transformed, A>,
|
|
) {
|
|
return FileHelper.rawTransformed<A, Record<string, unknown>, Transformed>(
|
|
path,
|
|
(inData) => TOML.stringify(inData as TOML.JsonMap),
|
|
(inString) => TOML.parse(inString),
|
|
(data) => shape.parse(data),
|
|
transformers,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Create a File Helper for a .ini file.
|
|
*
|
|
* Supports optional encode/decode options and custom transformers.
|
|
*/
|
|
static ini<A extends Record<string, unknown>>(
|
|
path: ToPath,
|
|
shape: Validator<Record<string, unknown>, A>,
|
|
options?: INI.EncodeOptions & INI.DecodeOptions,
|
|
): FileHelper<A>
|
|
static ini<A extends Transformed, Transformed = Record<string, unknown>>(
|
|
path: ToPath,
|
|
shape: Validator<Transformed, A>,
|
|
options: INI.EncodeOptions & INI.DecodeOptions,
|
|
transformers: Transformers<Record<string, unknown>, Transformed, A>,
|
|
): FileHelper<A>
|
|
static ini<A extends Transformed, Transformed = Record<string, unknown>>(
|
|
path: ToPath,
|
|
shape: Validator<Transformed, A>,
|
|
options?: INI.EncodeOptions & INI.DecodeOptions,
|
|
transformers?: Transformers<Record<string, unknown>, Transformed, A>,
|
|
): FileHelper<A> {
|
|
return FileHelper.rawTransformed<A, Record<string, unknown>, Transformed>(
|
|
path,
|
|
(inData) => INI.stringify(filterUndefined(inData), options),
|
|
(inString) => INI.parse(inString, options),
|
|
(data) => shape.parse(data),
|
|
transformers,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Create a File Helper for a .env file (KEY=VALUE format, one per line).
|
|
*
|
|
* Lines starting with `#` are treated as comments and ignored on read.
|
|
*/
|
|
static env<A extends Record<string, string>>(
|
|
path: ToPath,
|
|
shape: Validator<Record<string, string>, A>,
|
|
): FileHelper<A>
|
|
static env<A extends Transformed, Transformed = Record<string, string>>(
|
|
path: ToPath,
|
|
shape: Validator<Transformed, A>,
|
|
transformers: Transformers<Record<string, string>, Transformed, A>,
|
|
): FileHelper<A>
|
|
static env<A extends Transformed, Transformed = Record<string, string>>(
|
|
path: ToPath,
|
|
shape: Validator<Transformed, A>,
|
|
transformers?: Transformers<Record<string, string>, Transformed, A>,
|
|
) {
|
|
return FileHelper.rawTransformed<A, Record<string, string>, Transformed>(
|
|
path,
|
|
(inData) =>
|
|
Object.entries(inData)
|
|
.map(([k, v]) => `${k}=${v}`)
|
|
.join('\n'),
|
|
(inString) =>
|
|
Object.fromEntries(
|
|
inString
|
|
.split('\n')
|
|
.map((line) => line.trim())
|
|
.filter((line) => !line.startsWith('#') && line.includes('='))
|
|
.map((line) => {
|
|
const pos = line.indexOf('=')
|
|
return [line.slice(0, pos), line.slice(pos + 1)]
|
|
}),
|
|
),
|
|
(data) => shape.parse(data),
|
|
transformers,
|
|
)
|
|
}
|
|
}
|
|
|
|
export default FileHelper
|