functype-os 2.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ConfigResolver-p4Th3EPd.d.ts → ConfigResolver-DNUfcdRT.d.ts} +1 -1
- package/dist/{Env-eeHQ5oLF.d.ts → Env-DSWZuC61.d.ts} +1 -1
- package/dist/{Fs-BkxuVfog.d.ts → Fs-ZlDyYVKg.d.ts} +1 -1
- package/dist/{Layered-plQosjhw.d.ts → Layered-BJ8y5af3.d.ts} +1 -1
- package/dist/{PathExpander-Czw7TQBj.d.ts → PathExpander-C3o94nlr.d.ts} +1 -1
- package/dist/{Process-BqMq_szA.d.ts → Process-CkyuPYhy.d.ts} +1 -1
- package/dist/{ProcessEnvSource-2Kv8VieC.d.ts → ProcessEnvSource-CVw35NQr.d.ts} +1 -1
- package/dist/{StaticSource-BgPzc1hx.d.ts → StaticSource-Xm7KjkoX.d.ts} +1 -1
- package/dist/{bootDiagnostics-CbmGG6s_.d.ts → bootDiagnostics-DJhhGVlw.d.ts} +1 -1
- package/dist/config/ConfigResolver.d.ts +1 -1
- package/dist/config/ConfigResolver.js +1 -1
- package/dist/config/ConfigResolver.js.map +1 -1
- package/dist/config/ConfigSource.d.ts +1 -1
- package/dist/config/Layered.d.ts +1 -1
- package/dist/config/Layered.js.map +1 -1
- package/dist/config/ProcessEnvSource.d.ts +1 -1
- package/dist/config/ProcessEnvSource.js.map +1 -1
- package/dist/config/StaticSource.d.ts +1 -1
- package/dist/config/StaticSource.js.map +1 -1
- package/dist/config/bootDiagnostics.d.ts +1 -1
- package/dist/config/bootDiagnostics.js +1 -1
- package/dist/config/bootDiagnostics.js.map +1 -1
- package/dist/config/colors.js.map +1 -1
- package/dist/config/consoleBootLogger.d.ts +1 -1
- package/dist/config/consoleBootLogger.js.map +1 -1
- package/dist/config/index.d.ts +8 -8
- package/dist/config/mask.d.ts +1 -1
- package/dist/config/mask.js.map +1 -1
- package/dist/env/Env.d.ts +1 -1
- package/dist/env/Env.js +1 -1
- package/dist/env/Env.js.map +1 -1
- package/dist/env/index.d.ts +1 -1
- package/dist/errors/errors.d.ts +1 -1
- package/dist/errors/errors.js.map +1 -1
- package/dist/errors/index.d.ts +1 -1
- package/dist/fs/Fs.d.ts +1 -1
- package/dist/fs/Fs.js +1 -1
- package/dist/fs/Fs.js.map +1 -1
- package/dist/fs/index.d.ts +1 -1
- package/dist/index.d.ts +7 -7
- package/dist/path/PathExpander.d.ts +1 -1
- package/dist/path/PathExpander.js +1 -1
- package/dist/path/PathExpander.js.map +1 -1
- package/dist/path/index.d.ts +1 -1
- package/dist/platform/Platform.d.ts +1 -1
- package/dist/platform/Platform.js +1 -1
- package/dist/platform/Platform.js.map +1 -1
- package/dist/platform/index.d.ts +1 -1
- package/dist/process/Process.d.ts +1 -1
- package/dist/process/Process.js +1 -1
- package/dist/process/Process.js.map +1 -1
- package/dist/process/index.d.ts +1 -1
- package/package.json +3 -3
- /package/dist/{ConfigSource-D8Fi6vaG.d.ts → ConfigSource-DYg8zRVS.d.ts} +0 -0
- /package/dist/{Platform-CxcnVBOy.d.ts → Platform-Drtg2_HB.d.ts} +0 -0
- /package/dist/{consoleBootLogger-Mp3WmMYH.d.ts → consoleBootLogger-EaUJmtmz.d.ts} +0 -0
- /package/dist/{errors-BIVj3Unk.d.ts → errors-CZA32bA8.d.ts} +0 -0
- /package/dist/{mask-O-SEN-kZ.d.ts → mask-D42mrBYN.d.ts} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as EnvError } from "./errors-BIVj3Unk.js";
|
|
2
1
|
import { Either, List, Option } from "functype";
|
|
2
|
+
import { n as EnvError } from "./errors-CZA32bA8.js";
|
|
3
3
|
declare const EnvConstructor: (name: string) => Option<string>;
|
|
4
4
|
declare const EnvCompanion: {
|
|
5
5
|
get: (name: string) => Option<string>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as PathError } from "./errors-BIVj3Unk.js";
|
|
2
1
|
import { Either } from "functype";
|
|
2
|
+
import { a as PathError } from "./errors-CZA32bA8.js";
|
|
3
3
|
declare const expandTilde: (p: string) => string;
|
|
4
4
|
declare const expandVars: (p: string) => Either<PathError, string>;
|
|
5
5
|
declare const expandPath: (p: string) => Either<PathError, string>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as ConfigResolver } from "../ConfigResolver-
|
|
1
|
+
import { t as ConfigResolver } from "../ConfigResolver-DNUfcdRT.js";
|
|
2
2
|
export { ConfigResolver };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{IO as e,Left as t,List as n,Option as r,Right as i}from"functype";import{ConfigError as a}from"../errors/errors.js";import{Fs as o}from"../fs/Fs.js";import{expandPath as s}from"../path/PathExpander.js";const c=e=>s(e).fold(()=>r(void 0),e=>r(e)),l=t=>t.headOption().fold(()=>e.succeed(r(void 0)),n=>o.exists(n).flatMap(i=>i?e.succeed(r(n)):l(t.tail()))),u=e=>n(e.flatMap(e=>c(e).toArray())),d={resolve:e=>l(u(e.candidates)),resolveRequired:t=>d.resolve(t).flatMap(n=>n.fold(()=>e.fail(a(t.candidates)),t=>e.succeed(t))),resolveAll:t=>e.forEach(u(t.candidates).toArray(),e=>o.exists(e).map(t=>t?[e]:[])).map(e=>n(e.flat())),resolveSync:e=>u(e.candidates).find(o.existsSync),resolveRequiredSync:e=>d.resolveSync(e).fold(()=>t(a(e.candidates)),e=>i(e)),resolveAllSync:e=>u(e.candidates).filter(o.existsSync)};export{d as ConfigResolver};
|
|
2
2
|
//# sourceMappingURL=ConfigResolver.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConfigResolver.js","names":["ConfigErrorConstructor","
|
|
1
|
+
{"version":3,"file":"ConfigResolver.js","names":["ConfigErrorConstructor","IO","Left","List","Option","Right","ConfigError","Fs","expandPath","tryExpandPath","candidate","v","findFirstExisting","candidates","head","found","presentPaths","c","ConfigResolver","options","path","perPath"],"sources":["../../src/config/ConfigResolver.ts"],"sourcesContent":["import type { Either } from \"functype\"\nimport { IO, Left, List, Option, Right } from \"functype\"\n\nimport type { ConfigError } from \"../errors/errors\"\nimport { ConfigError as ConfigErrorConstructor } from \"../errors/errors\"\nimport { Fs } from \"../fs/Fs\"\nimport { expandPath } from \"../path/PathExpander\"\n\nconst tryExpandPath = (candidate: string): Option<string> => {\n const result = expandPath(candidate)\n return result.fold(\n () => Option<string>(undefined),\n (v) => Option(v),\n )\n}\n\n// Checks candidates in order and stops at the first that exists.\nconst findFirstExisting = (candidates: List<string>): IO<never, never, Option<string>> =>\n candidates.headOption().fold(\n () => IO.succeed(Option<string>(undefined)),\n (head) =>\n Fs.exists(head).flatMap((found) => (found ? IO.succeed(Option(head)) : findFirstExisting(candidates.tail()))),\n )\n\n// Expand each candidate; drop entries whose env variables didn't resolve.\nconst presentPaths = (candidates: readonly string[]): List<string> =>\n List<string>(candidates.flatMap((c) => tryExpandPath(c).toArray()))\n\nexport const ConfigResolver = {\n // Async methods — return a lazy IO; nothing touches the filesystem until `.run()`\n\n resolve: (options: { readonly candidates: readonly string[] }): IO<never, never, Option<string>> =>\n findFirstExisting(presentPaths(options.candidates)),\n\n resolveRequired: (options: { readonly candidates: readonly string[] }): IO<never, ConfigError, string> =>\n ConfigResolver.resolve(options).flatMap((found) =>\n found.fold<IO<never, ConfigError, string>>(\n () => IO.fail(ConfigErrorConstructor(options.candidates)),\n (path) => IO.succeed(path),\n ),\n ),\n\n // Checks paths one at a time, in order. They're a handful of config candidates, so this\n // costs nothing measurable and keeps the result order stable.\n resolveAll: (options: { readonly candidates: readonly string[] }): IO<never, never, List<string>> =>\n IO.forEach(presentPaths(options.candidates).toArray(), (path) =>\n Fs.exists(path).map((found) => (found ? [path] : [])),\n ).map((perPath) => List<string>(perPath.flat())),\n\n // Sync methods — return Either<ConfigError, T>\n\n resolveSync: (options: { readonly candidates: readonly string[] }): Option<string> =>\n presentPaths(options.candidates).find(Fs.existsSync),\n\n resolveRequiredSync: (options: { readonly candidates: readonly string[] }): Either<ConfigError, string> => {\n const result = ConfigResolver.resolveSync(options)\n return result.fold(\n () => Left(ConfigErrorConstructor(options.candidates)),\n (v) => Right(v),\n )\n },\n\n resolveAllSync: (options: { readonly candidates: readonly string[] }): List<string> =>\n presentPaths(options.candidates).filter(Fs.existsSync),\n}\n"],"mappings":"A,iNAQA,MAAMS,EAAiBC,GACNF,EAAWE,CACd,CAAC,CAAC,SACNN,EAAe,IAAA,EAAS,EAC7BO,GAAMP,EAAOO,CAAC,CACjB,EAIIC,EAAqBC,GACzBA,EAAW,WAAW,CAAC,CAAC,SAChBZ,EAAG,QAAQG,EAAe,IAAA,EAAS,CAAC,EACzCU,GACCP,EAAG,OAAOO,CAAI,CAAC,CAAC,QAASC,GAAWA,EAAQd,EAAG,QAAQG,EAAOU,CAAI,CAAC,EAAIF,EAAkBC,EAAW,KAAK,CAAC,CAAE,CAChH,EAGIG,EAAgBH,GACpBV,EAAaU,EAAW,QAASI,GAAMR,EAAcQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAEvDC,EAAiB,CAG5B,QAAUC,GACRP,EAAkBI,EAAaG,EAAQ,UAAU,CAAC,EAEpD,gBAAkBA,GAChBD,EAAe,QAAQC,CAAO,CAAC,CAAC,QAASJ,GACvCA,EAAM,SACEd,EAAG,KAAKD,EAAuBmB,EAAQ,UAAU,CAAC,EACvDC,GAASnB,EAAG,QAAQmB,CAAI,CAC3B,CACF,EAIF,WAAaD,GACXlB,EAAG,QAAQe,EAAaG,EAAQ,UAAU,CAAC,CAAC,QAAQ,EAAIC,GACtDb,EAAG,OAAOa,CAAI,CAAC,CAAC,IAAKL,GAAWA,EAAQ,CAACK,CAAI,EAAI,CAAC,CAAE,CACtD,CAAC,CAAC,IAAKC,GAAYlB,EAAakB,EAAQ,KAAK,CAAC,CAAC,EAIjD,YAAcF,GACZH,EAAaG,EAAQ,UAAU,CAAC,CAAC,KAAKZ,EAAG,UAAU,EAErD,oBAAsBY,GACLD,EAAe,YAAYC,CAC9B,CAAC,CAAC,SACNjB,EAAKF,EAAuBmB,EAAQ,UAAU,CAAC,EACpDR,GAAMN,EAAMM,CAAC,CAChB,EAGF,eAAiBQ,GACfH,EAAaG,EAAQ,UAAU,CAAC,CAAC,OAAOZ,EAAG,UAAU,CACzD,E"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as ConfigSource } from "../ConfigSource-
|
|
1
|
+
import { t as ConfigSource } from "../ConfigSource-DYg8zRVS.js";
|
|
2
2
|
export { ConfigSource };
|
package/dist/config/Layered.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as Layered } from "../Layered-
|
|
1
|
+
import { t as Layered } from "../Layered-BJ8y5af3.js";
|
|
2
2
|
export { Layered };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Layered.js","names":["OptionCtor","Layered","sources","s","
|
|
1
|
+
{"version":3,"file":"Layered.js","names":["OptionCtor","Option","Layered","sources","s","key","acc","source"],"sources":["../../src/config/Layered.ts"],"sourcesContent":["import type { Option } from \"functype\"\nimport { Option as OptionCtor } from \"functype\"\n\nimport type { ConfigSource } from \"./ConfigSource\"\n\n/**\n * First-wins composition over N `ConfigSource`s.\n *\n * Lookup walks the sources in order and returns the first `Some(value)` it\n * finds. Falls through to the next source when one returns `None`. The\n * composed source's `name` reflects the resolution chain\n * (e.g. `\"process.env > infisical > defaults\"`) so `bootDiagnostics` can echo\n * it in its header.\n *\n * Sensitivity (which keys to mask) is declared at diagnostics time, not at\n * source time — a `Layered([env, vault])` is structurally identical to any\n * other `ConfigSource`.\n *\n * @example\n * ```ts\n * const config = Layered([\n * ProcessEnvSource(),\n * await InfisicalSource({ token, env, projectId }),\n * StaticSource({ ENV: \"local\" }, \"defaults\"),\n * ])\n * // config.name === \"process.env > infisical > defaults\"\n * ```\n */\nexport const Layered = (sources: readonly ConfigSource[]): ConfigSource => ({\n name: sources.map((s) => s.name).join(\" > \"),\n get: (key) =>\n sources.reduce<Option<string>>(\n (acc, source) =>\n acc.fold(\n () => source.get(key),\n () => acc,\n ),\n OptionCtor<string>(undefined),\n ),\n})\n"],"mappings":"A,kCA4BA,MAAaE,EAAWC,IAAoD,CAC1E,KAAMA,EAAQ,IAAKC,GAAMA,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,EAC3C,IAAMC,GACJF,EAAQ,QACLG,EAAKC,IACJD,EAAI,SACIC,EAAO,IAAIF,CAAG,MACdC,CACR,EACFN,EAAmB,IAAA,EAAS,CAC9B,CACJ,G"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as ProcessEnvSource } from "../ProcessEnvSource-
|
|
1
|
+
import { t as ProcessEnvSource } from "../ProcessEnvSource-CVw35NQr.js";
|
|
2
2
|
export { ProcessEnvSource };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProcessEnvSource.js","names":["
|
|
1
|
+
{"version":3,"file":"ProcessEnvSource.js","names":["Env","ProcessEnvSource","key"],"sources":["../../src/config/ProcessEnvSource.ts"],"sourcesContent":["import { Env } from \"../env/Env\"\nimport type { ConfigSource } from \"./ConfigSource\"\n\n/**\n * Built-in `ConfigSource` backed by `process.env` via the existing `Env` wrapper.\n *\n * Use as the first layer of a `Layered` chain so env vars override vault and\n * default values:\n *\n * ```ts\n * const config = Layered([ProcessEnvSource(), await InfisicalSource(...), StaticSource(defaults)])\n * ```\n */\nexport const ProcessEnvSource = (): ConfigSource => ({\n name: \"process.env\",\n get: (key) => Env(key),\n})\n"],"mappings":"A,oCAaA,MAAaC,OAAwC,CACnD,KAAM,cACN,IAAMC,GAAQF,EAAIE,CAAG,CACvB,G"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as StaticSource } from "../StaticSource-
|
|
1
|
+
import { t as StaticSource } from "../StaticSource-Xm7KjkoX.js";
|
|
2
2
|
export { StaticSource };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StaticSource.js","names":["
|
|
1
|
+
{"version":3,"file":"StaticSource.js","names":["Option","StaticSource","entries","name","key"],"sources":["../../src/config/StaticSource.ts"],"sourcesContent":["import { Option } from \"functype\"\n\nimport type { ConfigSource } from \"./ConfigSource\"\n\n/**\n * Built-in `ConfigSource` backed by an in-memory map.\n *\n * Useful for default values, test fixtures, or any static config layer that\n * doesn't need an external lookup. The `name` argument defaults to `\"static\"`\n * but should be set when composing multiple static sources for clearer\n * diagnostics output.\n *\n * @example\n * ```ts\n * const defaults = StaticSource({ ENV: \"local\", PORT: \"3000\" }, \"defaults\")\n * const config = Layered([ProcessEnvSource(), defaults])\n * ```\n */\nexport const StaticSource = (entries: Readonly<Record<string, string>>, name = \"static\"): ConfigSource => ({\n name,\n get: (key) => Option(entries[key]),\n})\n"],"mappings":"A,kCAkBA,MAAaC,GAAgBC,EAA2CC,EAAO,YAA4B,CACzGA,OACA,IAAMC,GAAQJ,EAAOE,EAAQE,EAAI,CACnC,G"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as MissingKey, r as bootDiagnostics, t as BootDiagnosticsOptions } from "../bootDiagnostics-
|
|
1
|
+
import { n as MissingKey, r as bootDiagnostics, t as BootDiagnosticsOptions } from "../bootDiagnostics-DJhhGVlw.js";
|
|
2
2
|
export { BootDiagnosticsOptions, MissingKey, bootDiagnostics };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Left as e,List as t,Right as n}from"functype";import{blue as r,green as i,magenta as a,red as o,yellow as s}from"./colors.js";import{consoleBootLogger as c}from"./consoleBootLogger.js";import{maskValue as l}from"./mask.js";const u=u=>{let d=u.logger??c,f=u.required??[],p=u.sensitive??[],m=u.public??[];d.info(`${r(`📦`)} Boot diagnostics: ${u.serviceName??`service`}`),d.info(` source: ${u.source.name}`);let h=f.filter(e=>u.source.get(e).isEmpty);if(p.length>0&&(d.info(s(`🔐 Sensitive:`)),p.forEach(e=>{let t=u.source.get(e).fold(()=>o(`NOT_LOADED`),e=>l(e));d.info(` ${e.padEnd(28)} ${t}`)})),m.length>0&&(d.info(i(`⚙️ Public:`)),m.forEach(e=>{let t=u.source.get(e).fold(()=>o(`NOT_LOADED`),e=>e);d.info(` ${e.padEnd(28)} ${t}`)})),u.hostEnv!==void 0&&u.vaultEnvKey!==void 0){let e=u.source.get(u.vaultEnvKey),{hostEnv:t}=u,{vaultEnvKey:n}=u;e.fold(()=>{d.warn(`Vault env key '${n}' not present — skipping mismatch check`)},e=>{e===t?d.info(`${a(`🌍`)} Environment: ${t} (host) ↔ ${e} (vault) ${i(`✓`)}`):d.error(`${a(`🌍`)} Environment MISMATCH: host=${t} vault=${e}`,{hostEnv:t,vaultEnv:e})})}if(h.length===0)return d.info(i(`✅ All required keys present`)),n(void 0);d.error(o(`❌ Missing required keys (${h.length}):`)),h.forEach(e=>d.error(` ${e}`));let g=t(h.map(e=>({key:e,required:!0})));return u.failOn===`missing`&&process.exit(1),e(g)};export{u as bootDiagnostics};
|
|
2
2
|
//# sourceMappingURL=bootDiagnostics.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bootDiagnostics.js","names":["
|
|
1
|
+
{"version":3,"file":"bootDiagnostics.js","names":["Left","List","Right","blue","green","magenta","red","yellow","consoleBootLogger","maskValue","bootDiagnostics","opts","logger","required","sensitive","publicKeys","missing","k","key","display","v","vaultEnv","hostEnv","vaultEnvKey","missingList"],"sources":["../../src/config/bootDiagnostics.ts"],"sourcesContent":["import type { Either, List as ListType, Logger } from \"functype\"\nimport { Left, List, Right } from \"functype\"\n\nimport { blue, green, magenta, red, yellow } from \"./colors\"\nimport type { ConfigSource } from \"./ConfigSource\"\nimport { consoleBootLogger } from \"./consoleBootLogger\"\nimport { maskValue } from \"./mask\"\n\nexport interface MissingKey {\n readonly key: string\n readonly required: boolean\n}\n\nexport interface BootDiagnosticsOptions {\n /** The composed `ConfigSource` to inspect. */\n readonly source: ConfigSource\n /** Keys that MUST be present. Missing required keys produce a `Left`. */\n readonly required?: readonly string[]\n /** Keys to log with masked values (via {@link maskValue}). */\n readonly sensitive?: readonly string[]\n /** Keys to log with raw values. */\n readonly public?: readonly string[]\n /**\n * If provided with `vaultEnvKey`, compares the host environment string\n * (e.g. `process.env.NODE_ENV`) against the value at `vaultEnvKey` in the\n * source. Logs `✓` on match, an error-level message on mismatch.\n */\n readonly hostEnv?: string\n readonly vaultEnvKey?: string\n /**\n * `\"missing\"` triggers `process.exit(1)` after logging when any required key\n * is missing. `\"never\"` (default) returns `Left(missing)` and lets the caller\n * decide. Set to `\"missing\"` in production / staging boot paths to guarantee\n * fail-fast on misconfiguration.\n */\n readonly failOn?: \"missing\" | \"never\"\n /**\n * Logger to use. Defaults to {@link consoleBootLogger}. Any value satisfying\n * the core `Logger` interface from `functype` — including `DirectLogger`\n * from `functype-log/direct` — works without an adapter.\n */\n readonly logger?: Logger\n /** Service identifier shown in the diagnostics header. */\n readonly serviceName?: string\n}\n\n/**\n * Log a standardized boot diagnostics block and verify required-key presence.\n *\n * The block always emits, regardless of outcome — operational visibility (\"did\n * the deploy pick up my config?\") is the point. Sensitive keys are masked;\n * public keys are logged verbatim. An optional host-vs-vault env-mismatch\n * check catches the common deploy footgun where the host's `NODE_ENV` and the\n * vault's `ENV` (or equivalent) diverge.\n *\n * Returns `Either<List<MissingKey>, void>` so non-fatal callers can inspect\n * the result. Setting `failOn: \"missing\"` short-circuits to `process.exit(1)`\n * for production guards.\n *\n * @example\n * ```ts\n * const result = bootDiagnostics({\n * serviceName: \"cq-api\",\n * source: Layered([ProcessEnvSource(), await InfisicalSource(...)]),\n * required: [\"SUPABASE_URL\", \"SUPABASE_KEY\", \"OPENAI_API_KEY\"],\n * sensitive: [\"SUPABASE_URL\", \"SUPABASE_KEY\", \"OPENAI_API_KEY\"],\n * public: [\"ENV\", \"ENABLE_CHAT\"],\n * hostEnv: process.env.NODE_ENV ?? \"local\",\n * vaultEnvKey: \"ENV\",\n * failOn: process.env.NODE_ENV === \"production\" ? \"missing\" : \"never\",\n * })\n * ```\n */\nexport const bootDiagnostics = (opts: BootDiagnosticsOptions): Either<ListType<MissingKey>, void> => {\n const logger = opts.logger ?? consoleBootLogger\n const required = opts.required ?? []\n const sensitive = opts.sensitive ?? []\n const publicKeys = opts.public ?? []\n\n logger.info(`${blue(\"📦\")} Boot diagnostics: ${opts.serviceName ?? \"service\"}`)\n logger.info(` source: ${opts.source.name}`)\n\n const missing = required.filter((k) => opts.source.get(k).isEmpty)\n\n if (sensitive.length > 0) {\n logger.info(yellow(\"🔐 Sensitive:\"))\n sensitive.forEach((key) => {\n const value = opts.source.get(key)\n const display = value.fold(\n () => red(\"NOT_LOADED\"),\n (v) => maskValue(v),\n )\n logger.info(` ${key.padEnd(28)} ${display}`)\n })\n }\n\n if (publicKeys.length > 0) {\n logger.info(green(\"⚙️ Public:\"))\n publicKeys.forEach((key) => {\n const value = opts.source.get(key)\n const display = value.fold(\n () => red(\"NOT_LOADED\"),\n (v) => v,\n )\n logger.info(` ${key.padEnd(28)} ${display}`)\n })\n }\n\n if (opts.hostEnv !== undefined && opts.vaultEnvKey !== undefined) {\n const vaultEnv = opts.source.get(opts.vaultEnvKey)\n const { hostEnv } = opts\n const { vaultEnvKey } = opts\n vaultEnv.fold(\n () => {\n logger.warn(`Vault env key '${vaultEnvKey}' not present — skipping mismatch check`)\n return undefined\n },\n (v) => {\n if (v === hostEnv) {\n logger.info(`${magenta(\"🌍\")} Environment: ${hostEnv} (host) ↔ ${v} (vault) ${green(\"✓\")}`)\n } else {\n logger.error(`${magenta(\"🌍\")} Environment MISMATCH: host=${hostEnv} vault=${v}`, {\n hostEnv,\n vaultEnv: v,\n })\n }\n return undefined\n },\n )\n }\n\n if (missing.length === 0) {\n logger.info(green(\"✅ All required keys present\"))\n return Right<ListType<MissingKey>, void>(undefined)\n }\n\n logger.error(red(`❌ Missing required keys (${missing.length}):`))\n missing.forEach((key) => logger.error(` ${key}`))\n\n const missingList = List(missing.map((key): MissingKey => ({ key, required: true })))\n\n if (opts.failOn === \"missing\") {\n process.exit(1)\n }\n return Left<ListType<MissingKey>, void>(missingList)\n}\n"],"mappings":"A,sOAyEA,MAAaU,EAAmBC,GAAqE,CACnG,IAAMC,EAASD,EAAK,QAAUH,EACxBK,EAAWF,EAAK,UAAY,CAAC,EAC7BG,EAAYH,EAAK,WAAa,CAAC,EAC/BI,EAAaJ,EAAK,QAAU,CAAC,EAEnCC,EAAO,KAAK,GAAGT,EAAK,IAAI,EAAE,qBAAqBQ,EAAK,aAAe,WAAW,EAC9EC,EAAO,KAAK,cAAcD,EAAK,OAAO,MAAM,EAE5C,IAAMK,EAAUH,EAAS,OAAQI,GAAMN,EAAK,OAAO,IAAIM,CAAC,CAAC,CAAC,OAAO,EA0BjE,GAxBIH,EAAU,OAAS,IACrBF,EAAO,KAAKL,EAAO,eAAe,CAAC,EACnCO,EAAU,QAASI,GAAQ,CAEzB,IAAMC,EADQR,EAAK,OAAO,IAAIO,CACV,CAAC,CAAC,SACdZ,EAAI,YAAY,EACrBc,GAAMX,EAAUW,CAAC,CACpB,EACAR,EAAO,KAAK,MAAMM,EAAI,OAAO,EAAE,EAAE,GAAGC,GAAS,CAC/C,CAAC,GAGCJ,EAAW,OAAS,IACtBH,EAAO,KAAKR,EAAM,aAAa,CAAC,EAChCW,EAAW,QAASG,GAAQ,CAE1B,IAAMC,EADQR,EAAK,OAAO,IAAIO,CACV,CAAC,CAAC,SACdZ,EAAI,YAAY,EACrBc,GAAMA,CACT,EACAR,EAAO,KAAK,MAAMM,EAAI,OAAO,EAAE,EAAE,GAAGC,GAAS,CAC/C,CAAC,GAGCR,EAAK,UAAY,IAAA,IAAaA,EAAK,cAAgB,IAAA,GAAW,CAChE,IAAMU,EAAWV,EAAK,OAAO,IAAIA,EAAK,WAAW,EAC3C,CAAEW,WAAYX,EACd,CAAEY,eAAgBZ,EACxBU,EAAS,SACD,CACJT,EAAO,KAAK,kBAAkBW,EAAY,wCAAwC,CAEpF,EACCH,GAAM,CACDA,IAAME,EACRV,EAAO,KAAK,GAAGP,EAAQ,IAAI,EAAE,gBAAgBiB,EAAQ,YAAYF,EAAE,WAAWhB,EAAM,GAAG,GAAG,EAE1FQ,EAAO,MAAM,GAAGP,EAAQ,IAAI,EAAE,8BAA8BiB,EAAQ,SAASF,IAAK,CAChFE,UACA,SAAUF,CACZ,CAAC,CAGL,CACF,CACF,CAEA,GAAIJ,EAAQ,SAAW,EAErB,OADAJ,EAAO,KAAKR,EAAM,6BAA6B,CAAC,EACzCF,EAAkC,IAAA,EAAS,EAGpDU,EAAO,MAAMN,EAAI,4BAA4BU,EAAQ,OAAO,GAAG,CAAC,EAChEA,EAAQ,QAASE,GAAQN,EAAO,MAAM,MAAMM,GAAK,CAAC,EAElD,IAAMM,EAAcvB,EAAKe,EAAQ,IAAKE,IAAqB,CAAEA,MAAK,SAAU,EAAK,EAAE,CAAC,EAKpF,OAHIP,EAAK,SAAW,WAClB,QAAQ,KAAK,CAAC,EAETX,EAAiCwB,CAAW,CACrD,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"colors.js","names":["shouldColor","wrap","code","s","red","green","yellow","blue","magenta","cyan","gray"],"sources":["../../src/config/colors.ts"],"sourcesContent":["/**\n * Internal raw-ANSI color helpers for boot diagnostics output.\n *\n * Respects established conventions:\n * - `NO_COLOR=1` (any value) → output uncolored, regardless of TTY. See\n * https://no-color.org/.\n * - `FORCE_COLOR=1` (any value) → output colored, regardless of TTY. Useful\n * for CI logs that pipe stdout but want the colors preserved.\n * - Default: color when `process.stdout.isTTY`, plain otherwise.\n *\n * Zero deps. ANSI escape codes haven't changed since 1979.\n *\n * @internal — not re-exported from the package barrel.\n */\n\nconst shouldColor = (): boolean => {\n if (process.env.NO_COLOR !== undefined) return false\n if (process.env.FORCE_COLOR !== undefined) return true\n return process.stdout.isTTY\n}\n\nconst wrap =\n (code: string) =>\n (s: string): string =>\n shouldColor() ? `\\x1b[${code}m${s}\\x1b[0m` : s\n\nexport const red = wrap(\"31\")\nexport const green = wrap(\"32\")\nexport const yellow = wrap(\"33\")\nexport const blue = wrap(\"34\")\nexport const magenta = wrap(\"35\")\nexport const cyan = wrap(\"36\")\nexport const gray = wrap(\"90\")\n"],"mappings":"AAeA,MAAMA,MACA,QAAQ,IAAI,WAAa,IAAA,GACzB,QAAQ,IAAI,cAAgB,IAAA,IACzB,QAAQ,OAAO,MAFyB,GAK3CC,
|
|
1
|
+
{"version":3,"file":"colors.js","names":["shouldColor","wrap","code","s","red","green","yellow","blue","magenta","cyan","gray"],"sources":["../../src/config/colors.ts"],"sourcesContent":["/**\n * Internal raw-ANSI color helpers for boot diagnostics output.\n *\n * Respects established conventions:\n * - `NO_COLOR=1` (any value) → output uncolored, regardless of TTY. See\n * https://no-color.org/.\n * - `FORCE_COLOR=1` (any value) → output colored, regardless of TTY. Useful\n * for CI logs that pipe stdout but want the colors preserved.\n * - Default: color when `process.stdout.isTTY`, plain otherwise.\n *\n * Zero deps. ANSI escape codes haven't changed since 1979.\n *\n * @internal — not re-exported from the package barrel.\n */\n\nconst shouldColor = (): boolean => {\n if (process.env.NO_COLOR !== undefined) return false\n if (process.env.FORCE_COLOR !== undefined) return true\n return process.stdout.isTTY\n}\n\nconst wrap =\n (code: string) =>\n (s: string): string =>\n shouldColor() ? `\\x1b[${code}m${s}\\x1b[0m` : s\n\nexport const red = wrap(\"31\")\nexport const green = wrap(\"32\")\nexport const yellow = wrap(\"33\")\nexport const blue = wrap(\"34\")\nexport const magenta = wrap(\"35\")\nexport const cyan = wrap(\"36\")\nexport const gray = wrap(\"90\")\n"],"mappings":"AAeA,MAAMA,MACA,QAAQ,IAAI,WAAa,IAAA,GACzB,QAAQ,IAAI,cAAgB,IAAA,IACzB,QAAQ,OAAO,MAFyB,GAK3CC,EACHC,GACAC,GACCH,EAAY,EAAI,QAAQE,EAAK,GAAGC,EAAE,SAAWA,EAEpCC,EAAMH,EAAK,IAAI,EACfI,EAAQJ,EAAK,IAAI,EACjBK,EAASL,EAAK,IAAI,EAClBM,EAAON,EAAK,IAAI,EAChBO,EAAUP,EAAK,IAAI,EACnBQ,EAAOR,EAAK,IAAI,EAChBS,EAAOT,EAAK,IAAI,E"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as consoleBootLogger } from "../consoleBootLogger-
|
|
1
|
+
import { t as consoleBootLogger } from "../consoleBootLogger-EaUJmtmz.js";
|
|
2
2
|
export { consoleBootLogger };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"consoleBootLogger.js","names":["
|
|
1
|
+
{"version":3,"file":"consoleBootLogger.js","names":["gray","red","yellow","stamp","consoleBootLogger","msg","meta"],"sources":["../../src/config/consoleBootLogger.ts"],"sourcesContent":["import type { Logger } from \"functype\"\n\nimport { gray, red, yellow } from \"./colors\"\n\nconst stamp = (): string => new Date().toISOString()\n\n/**\n * Default `Logger` impl for boot diagnostics — zero-dep, raw ANSI colors,\n * NO_COLOR / FORCE_COLOR / isTTY-respecting.\n *\n * All 4 methods of core `Logger` are present (debug included). For consumers\n * already using `functype-log`, pass `createDirectConsoleLogger()` from\n * `functype-log/direct` directly — its `DirectLogger` structurally satisfies\n * core `Logger` (no adapter required).\n *\n * @example\n * ```ts\n * import { bootDiagnostics, consoleBootLogger } from \"functype-os/config\"\n *\n * await bootDiagnostics({ source, required, logger: consoleBootLogger })\n * // (logger defaults to consoleBootLogger anyway — passed explicitly here\n * // to show the swap point for `createDirectConsoleLogger()` etc.)\n * ```\n */\nexport const consoleBootLogger: Logger = {\n debug: (msg, meta) => console.debug(`${gray(stamp())} ${gray(\"DEBUG\")} ${msg}`, meta ?? \"\"),\n info: (msg, meta) => console.log(`${gray(stamp())} ${msg}`, meta ?? \"\"),\n warn: (msg, meta) => console.warn(`${gray(stamp())} ${yellow(\"WARN\")} ${msg}`, meta ?? \"\"),\n error: (msg, meta) => console.error(`${gray(stamp())} ${red(\"ERROR\")} ${msg}`, meta ?? \"\"),\n}\n"],"mappings":"A,wDAIA,MAAMG,uBAAsB,IAAI,KAAK,EAAA,CAAE,YAAY,EAoBtCC,EAA4B,CACvC,OAAQC,EAAKC,IAAS,QAAQ,MAAM,GAAGN,EAAKG,EAAM,CAAC,EAAE,GAAGH,EAAK,OAAO,EAAE,GAAGK,IAAOC,GAAQ,EAAE,EAC1F,MAAOD,EAAKC,IAAS,QAAQ,IAAI,GAAGN,EAAKG,EAAM,CAAC,EAAE,GAAGE,IAAOC,GAAQ,EAAE,EACtE,MAAOD,EAAKC,IAAS,QAAQ,KAAK,GAAGN,EAAKG,EAAM,CAAC,EAAE,GAAGD,EAAO,MAAM,EAAE,GAAGG,IAAOC,GAAQ,EAAE,EACzF,OAAQD,EAAKC,IAAS,QAAQ,MAAM,GAAGN,EAAKG,EAAM,CAAC,EAAE,GAAGF,EAAI,OAAO,EAAE,GAAGI,IAAOC,GAAQ,EAAE,CAC3F,E"}
|
package/dist/config/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { n as MissingKey, r as bootDiagnostics, t as BootDiagnosticsOptions } from "../bootDiagnostics-
|
|
2
|
-
import { t as ConfigResolver } from "../ConfigResolver-
|
|
3
|
-
import { t as ConfigSource } from "../ConfigSource-
|
|
4
|
-
import { t as consoleBootLogger } from "../consoleBootLogger-
|
|
5
|
-
import { t as Layered } from "../Layered-
|
|
6
|
-
import { t as maskValue } from "../mask-
|
|
7
|
-
import { t as ProcessEnvSource } from "../ProcessEnvSource-
|
|
8
|
-
import { t as StaticSource } from "../StaticSource-
|
|
1
|
+
import { n as MissingKey, r as bootDiagnostics, t as BootDiagnosticsOptions } from "../bootDiagnostics-DJhhGVlw.js";
|
|
2
|
+
import { t as ConfigResolver } from "../ConfigResolver-DNUfcdRT.js";
|
|
3
|
+
import { t as ConfigSource } from "../ConfigSource-DYg8zRVS.js";
|
|
4
|
+
import { t as consoleBootLogger } from "../consoleBootLogger-EaUJmtmz.js";
|
|
5
|
+
import { t as Layered } from "../Layered-BJ8y5af3.js";
|
|
6
|
+
import { t as maskValue } from "../mask-D42mrBYN.js";
|
|
7
|
+
import { t as ProcessEnvSource } from "../ProcessEnvSource-CVw35NQr.js";
|
|
8
|
+
import { t as StaticSource } from "../StaticSource-Xm7KjkoX.js";
|
|
9
9
|
export { type BootDiagnosticsOptions, ConfigResolver, type ConfigSource, Layered, type MissingKey, ProcessEnvSource, StaticSource, bootDiagnostics, consoleBootLogger, maskValue };
|
package/dist/config/mask.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as maskValue } from "../mask-
|
|
1
|
+
import { t as maskValue } from "../mask-D42mrBYN.js";
|
|
2
2
|
export { maskValue };
|
package/dist/config/mask.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mask.js","names":["maskValue","value"],"sources":["../../src/config/mask.ts"],"sourcesContent":["/**\n * Mask a sensitive value for display in boot diagnostics or logs.\n *\n * - Values ≤ 8 characters become `****` (no leakage of length or characters).\n * - Longer values become `ab****yz` — first two and last two characters\n * preserved so an operator can confirm which secret loaded without\n * exposing the bulk of it.\n *\n * Exported from `functype-os/config` for ad-hoc masking outside\n * `bootDiagnostics`.\n *\n * @example\n * ```ts\n * maskValue(\"short\") // \"****\"\n * maskValue(\"supersecretvalue\") // \"su****ue\"\n * ```\n */\nexport const maskValue = (value: string): string => {\n if (value.length <= 8) return \"****\"\n return `${value.slice(0, 2)}****${value.slice(-2)}`\n}\n"],"mappings":"AAiBA,MAAaA,
|
|
1
|
+
{"version":3,"file":"mask.js","names":["maskValue","value"],"sources":["../../src/config/mask.ts"],"sourcesContent":["/**\n * Mask a sensitive value for display in boot diagnostics or logs.\n *\n * - Values ≤ 8 characters become `****` (no leakage of length or characters).\n * - Longer values become `ab****yz` — first two and last two characters\n * preserved so an operator can confirm which secret loaded without\n * exposing the bulk of it.\n *\n * Exported from `functype-os/config` for ad-hoc masking outside\n * `bootDiagnostics`.\n *\n * @example\n * ```ts\n * maskValue(\"short\") // \"****\"\n * maskValue(\"supersecretvalue\") // \"su****ue\"\n * ```\n */\nexport const maskValue = (value: string): string => {\n if (value.length <= 8) return \"****\"\n return `${value.slice(0, 2)}****${value.slice(-2)}`\n}\n"],"mappings":"AAiBA,MAAaA,EAAaC,GACpBA,EAAM,QAAU,EAAU,OACvB,GAAGA,EAAM,MAAM,EAAG,CAAC,EAAE,MAAMA,EAAM,MAAM,EAAE,I"}
|
package/dist/env/Env.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as Env } from "../Env-
|
|
1
|
+
import { t as Env } from "../Env-DSWZuC61.js";
|
|
2
2
|
export { Env };
|
package/dist/env/Env.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Left as e,List as t,Option as n,Right as r,Try as i}from"functype";import{EnvError as a}from"../errors/errors.js";const o=Object.assign(e=>n(process.env[e]),{get:e=>n(process.env[e]),getRequired:e=>n(process.env[e]).toEither(a(e)),getOrDefault:(e,t)=>process.env[e]??t,has:e=>process.env[e]!==void 0,entries:()=>{let e=Object.entries(process.env).filter(e=>e[1]!==void 0).map(([e,t])=>[e,t]);return t(e)},parse:(t,o)=>n(process.env[t]).fold(()=>e(a(t)),n=>i(()=>o(n)).toEither(e=>a(t,`Failed to parse '${t}': ${e instanceof Error?e.message:String(e)}`)).flatMap(i=>typeof i==`number`&&isNaN(i)?e(a(t,`Cannot parse '${n}' as number for '${t}'`)):r(i)))});export{o as Env};
|
|
2
2
|
//# sourceMappingURL=Env.js.map
|
package/dist/env/Env.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Env.js","names":["
|
|
1
|
+
{"version":3,"file":"Env.js","names":["Left","List","Option","Right","Try","EnvError","Env","name","defaultValue","pairs","entry","k","v","parser","value","error","p"],"sources":["../../src/env/Env.ts"],"sourcesContent":["import type { Either } from \"functype\"\nimport { Left, List, Option, Right, Try } from \"functype\"\n\nimport { EnvError } from \"../errors/errors\"\n\nconst EnvConstructor = (name: string): Option<string> => Option(process.env[name])\n\nconst EnvCompanion = {\n get: (name: string): Option<string> => Option(process.env[name]),\n\n getRequired: (name: string): Either<EnvError, string> => Option(process.env[name]).toEither(EnvError(name)),\n\n getOrDefault: (name: string, defaultValue: string): string => process.env[name] ?? defaultValue,\n\n has: (name: string): boolean => process.env[name] !== undefined,\n\n entries: (): List<readonly [string, string]> => {\n const pairs: ReadonlyArray<readonly [string, string]> = Object.entries(process.env)\n .filter((entry): entry is [string, string] => entry[1] !== undefined)\n .map(([k, v]) => [k, v] as const)\n return List(pairs)\n },\n\n parse: <T>(name: string, parser: (value: string) => T): Either<EnvError, T> =>\n Option(process.env[name]).fold<Either<EnvError, T>>(\n () => Left(EnvError(name)),\n (value) =>\n Try(() => parser(value))\n .toEither((error) =>\n EnvError(name, `Failed to parse '${name}': ${error instanceof Error ? error.message : String(error)}`),\n )\n .flatMap((p) =>\n typeof p === \"number\" && isNaN(p)\n ? Left(EnvError(name, `Cannot parse '${value}' as number for '${name}'`))\n : Right(p),\n ),\n ),\n}\n\nexport const Env: typeof EnvConstructor & typeof EnvCompanion = Object.assign(EnvConstructor, EnvCompanion)\n"],"mappings":"A,yHAuCA,MAAaM,EAAmD,OAAO,OAlC/CC,GAAiCL,EAAO,QAAQ,IAAIK,EAAK,EAkCa,CA/B5F,IAAMA,GAAiCL,EAAO,QAAQ,IAAIK,EAAK,EAE/D,YAAcA,GAA2CL,EAAO,QAAQ,IAAIK,EAAK,CAAC,CAAC,SAASF,EAASE,CAAI,CAAC,EAE1G,cAAeA,EAAcC,IAAiC,QAAQ,IAAID,IAASC,EAEnF,IAAMD,GAA0B,QAAQ,IAAIA,KAAU,IAAA,GAEtD,YAAgD,CAC9C,IAAME,EAAkD,OAAO,QAAQ,QAAQ,GAAG,CAAC,CAChF,OAAQC,GAAqCA,EAAM,KAAO,IAAA,EAAS,CAAC,CACpE,KAAK,CAACC,EAAGC,KAAO,CAACD,EAAGC,CAAC,CAAU,EAClC,OAAOX,EAAKQ,CAAK,CACnB,EAEA,OAAWF,EAAcM,IACvBX,EAAO,QAAQ,IAAIK,EAAK,CAAC,CAAC,SAClBP,EAAKK,EAASE,CAAI,CAAC,EACxBO,GACCV,MAAUS,EAAOC,CAAK,CAAC,CAAC,CACrB,SAAUC,GACTV,EAASE,EAAM,oBAAoBA,EAAK,KAAKQ,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,GAAG,CACvG,CAAC,CACA,QAASC,GACR,OAAOA,GAAM,UAAY,MAAMA,CAAC,EAC5BhB,EAAKK,EAASE,EAAM,iBAAiBO,EAAM,mBAAmBP,EAAK,EAAE,CAAC,EACtEJ,EAAMa,CAAC,CACb,CACN,CAG0F,CAAY,E"}
|
package/dist/env/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as Env } from "../Env-
|
|
1
|
+
import { t as Env } from "../Env-DSWZuC61.js";
|
|
2
2
|
export { Env };
|
package/dist/errors/errors.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as PathError, i as OsError, n as EnvError, o as ProcessError, r as FsError, t as ConfigError } from "../errors-
|
|
1
|
+
import { a as PathError, i as OsError, n as EnvError, o as ProcessError, r as FsError, t as ConfigError } from "../errors-CZA32bA8.js";
|
|
2
2
|
export { ConfigError, EnvError, FsError, OsError, PathError, ProcessError };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":["EnvError","
|
|
1
|
+
{"version":3,"file":"errors.js","names":["EnvError","variable","message","PathError","path","reason","FsError","operation","cause","ConfigError","candidates","ProcessError","command","exitCode","stderr"],"sources":["../../src/errors/errors.ts"],"sourcesContent":["import type { Option } from \"functype\"\n\nexport type EnvError = {\n readonly _tag: \"EnvError\"\n readonly variable: string\n readonly message: string\n}\n\nexport type PathError = {\n readonly _tag: \"PathError\"\n readonly path: string\n readonly reason: \"unresolved_variable\" | \"invalid_path\"\n readonly message: string\n}\n\nexport type FsError = {\n readonly _tag: \"FsError\"\n readonly path: string\n readonly operation: string\n readonly cause: Error\n readonly message: string\n}\n\nexport type ConfigError = {\n readonly _tag: \"ConfigError\"\n readonly candidates: readonly string[]\n readonly message: string\n}\n\nexport type ProcessError = {\n readonly _tag: \"ProcessError\"\n readonly command: string\n readonly exitCode: Option<number>\n readonly stderr: string\n readonly message: string\n}\n\nexport type OsError = EnvError | PathError | FsError | ConfigError | ProcessError\n\nexport const EnvError = (variable: string, message?: string): EnvError => ({\n _tag: \"EnvError\",\n variable,\n message: message ?? `Environment variable '${variable}' is not set`,\n})\n\nexport const PathError = (path: string, reason: PathError[\"reason\"], message?: string): PathError => ({\n _tag: \"PathError\",\n path,\n reason,\n message:\n message ?? (reason === \"unresolved_variable\" ? `Unresolved variable in path: ${path}` : `Invalid path: ${path}`),\n})\n\nexport const FsError = (path: string, operation: string, cause: Error): FsError => ({\n _tag: \"FsError\",\n path,\n operation,\n cause,\n message: `${operation} failed for '${path}': ${cause.message}`,\n})\n\nexport const ConfigError = (candidates: readonly string[], message?: string): ConfigError => ({\n _tag: \"ConfigError\",\n candidates,\n message: message ?? `No config file found among candidates: ${candidates.join(\", \")}`,\n})\n\nexport const ProcessError = (\n command: string,\n exitCode: Option<number>,\n stderr: string,\n message?: string,\n): ProcessError => ({\n _tag: \"ProcessError\",\n command,\n exitCode,\n stderr,\n message: message ?? `Command '${command}' failed (exit ${exitCode.fold(() => \"?\", String)}): ${stderr}`,\n})\n"],"mappings":"AAuCA,MAAaA,GAAYC,EAAkBC,KAAgC,CACzE,KAAM,WACND,WACA,QAASC,GAAW,yBAAyBD,EAAS,aACxD,GAEaE,GAAaC,EAAcC,EAA6BH,KAAiC,CACpG,KAAM,YACNE,OACAC,SACA,QACEH,IAAYG,IAAW,sBAAwB,gCAAgCD,IAAS,iBAAiBA,IAC7G,GAEaE,GAAWF,EAAcG,EAAmBC,KAA2B,CAClF,KAAM,UACNJ,OACAG,YACAC,QACA,QAAS,GAAGD,EAAU,eAAeH,EAAK,KAAKI,EAAM,SACvD,GAEaC,GAAeC,EAA+BR,KAAmC,CAC5F,KAAM,cACNQ,aACA,QAASR,GAAW,0CAA0CQ,EAAW,KAAK,IAAI,GACpF,GAEaC,GACXC,EACAC,EACAC,EACAZ,KACkB,CAClB,KAAM,eACNU,UACAC,WACAC,SACA,QAASZ,GAAW,YAAYU,EAAQ,iBAAiBC,EAAS,SAAW,IAAK,MAAM,EAAE,KAAKC,GACjG,G"}
|
package/dist/errors/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as PathError, i as OsError, n as EnvError, o as ProcessError, r as FsError, t as ConfigError } from "../errors-
|
|
1
|
+
import { a as PathError, i as OsError, n as EnvError, o as ProcessError, r as FsError, t as ConfigError } from "../errors-CZA32bA8.js";
|
|
2
2
|
export { ConfigError, EnvError, FsError, type OsError, PathError, ProcessError };
|
package/dist/fs/Fs.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as Fs, t as FileInfo } from "../Fs-
|
|
1
|
+
import { n as Fs, t as FileInfo } from "../Fs-ZlDyYVKg.js";
|
|
2
2
|
export { FileInfo, Fs };
|
package/dist/fs/Fs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{IO as e,Left as t,List as n,Option as r,Right as i,Try as a}from"functype";import*as o from"node:fs";import*as s from"node:fs/promises";import{FsError as c}from"../errors/errors.js";const l=e=>({size:e.size,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),createdAt:e.birthtime,modifiedAt:e.mtime,accessedAt:e.atime,permissions:e.mode}),u=(e,t,n)=>c(e,t,n instanceof Error?n:Error(String(n))),d=[`/proc/`,`/sys/`,`/dev/`],f=e=>d.some(t=>e.startsWith(t)),p=(e,t)=>{let n=t.replace(/[\\^$+?.()|[\]{}]/g,`\\$&`).replace(/\*\*\//g,`{{GLOBSTAR}}`).replace(/\*\*/g,`{{GLOBSTAR}}`).replace(/\*/g,`[^/]*`).replace(/\{\{GLOBSTAR\}\}/g,`(?:.*/)?`);return RegExp(`^${n}$`).test(e)},m=(t,n,r)=>e.tryPromise({try:r,catch:e=>u(t,n,e)}),h=e=>e instanceof Error&&`code`in e&&e.code===`ENOENT`,g=(e,t,n)=>a(n).toEither(n=>u(e,t,n)),_={exists:t=>e.async(()=>s.access(t)).fold(()=>!1,()=>!0),readFile:(e,t=`utf8`)=>m(e,`readFile`,()=>s.readFile(e,{encoding:t})),readFileOpt:(n,a=`utf8`)=>e.async(()=>s.readFile(n,{encoding:a})).fold(e=>h(e)?i(r(void 0)):t(u(n,`readFile`,e)),e=>i(r(e))).flatMap(t=>e.fromEither(t)),stat:e=>m(e,`stat`,()=>s.stat(e).then(l)),copyFile:(e,t)=>m(e,`copyFile`,()=>s.copyFile(e,t)),rename:(e,t)=>m(e,`rename`,()=>s.rename(e,t)),readdir:e=>m(e,`readdir`,()=>s.readdir(e).then(e=>n(e))),glob:(e,t)=>m(e,`glob`,()=>s.readdir(e,{recursive:!0,encoding:`utf8`})).map(e=>n(e.filter(e=>p(e,t)))),writeFile:(e,t,n=`utf8`)=>m(e,`writeFile`,()=>s.writeFile(e,t,{encoding:n})),appendFile:(e,t,n=`utf8`)=>m(e,`appendFile`,()=>s.appendFile(e,t,{encoding:n})),mkdir:(t,n)=>n?.recursive&&f(t)?e.fail(u(t,`mkdir`,/* @__PURE__ */ Error(`recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)`))):m(t,`mkdir`,()=>s.mkdir(t,n).then(()=>void 0)),unlink:e=>m(e,`unlink`,()=>s.unlink(e)),existsSync:e=>a(()=>o.accessSync(e)).isSuccess(),readFileSync:(e,t=`utf8`)=>g(e,`readFileSync`,()=>o.readFileSync(e,{encoding:t})),readFileOptSync:(e,n=`utf8`)=>a(()=>o.readFileSync(e,{encoding:n})).fold(n=>h(n)?i(r(void 0)):t(u(e,`readFileOptSync`,n)),e=>i(r(e))),statSync:e=>g(e,`statSync`,()=>l(o.statSync(e))),copyFileSync:(e,t)=>g(e,`copyFileSync`,()=>o.copyFileSync(e,t)),renameSync:(e,t)=>g(e,`renameSync`,()=>o.renameSync(e,t)),readdirSync:e=>g(e,`readdirSync`,()=>n(o.readdirSync(e))),writeFileSync:(e,t,n=`utf8`)=>g(e,`writeFileSync`,()=>o.writeFileSync(e,t,{encoding:n})),appendFileSync:(e,t,n=`utf8`)=>g(e,`appendFileSync`,()=>o.appendFileSync(e,t,{encoding:n})),mkdirSync:(e,n)=>n?.recursive&&f(e)?t(u(e,`mkdirSync`,/* @__PURE__ */ Error(`recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)`))):g(e,`mkdirSync`,()=>{o.mkdirSync(e,n)}),unlinkSync:e=>g(e,`unlinkSync`,()=>o.unlinkSync(e))};export{_ as Fs};
|
|
2
2
|
//# sourceMappingURL=Fs.js.map
|
package/dist/fs/Fs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Fs.js","names":["fsSync","fs","toFileInfo","stats","toFsError","FsError","p","op","error","MAGIC_FS_PREFIXES","isMagicFsPath","prefix","matchGlob","regex","pattern","filePath","liftAsync","IO","thunk","err","isNotFound","liftSync","Try","Fs","Right","Option","Left","data","result","src","dest","oldPath","newPath","List","entries","dir","entry","options"],"sources":["../../src/fs/Fs.ts"],"sourcesContent":["import * as fsSync from \"node:fs\"\nimport * as fs from \"node:fs/promises\"\n\nimport type { Either } from \"functype\"\nimport { IO, Left, List, Option, Right, Try } from \"functype\"\n\nimport { FsError } from \"../errors/errors\"\n\nexport type FileInfo = {\n readonly size: number\n readonly isFile: boolean\n readonly isDirectory: boolean\n readonly isSymbolicLink: boolean\n readonly createdAt: Date\n readonly modifiedAt: Date\n readonly accessedAt: Date\n readonly permissions: number\n}\n\nconst toFileInfo = (stats: fsSync.Stats): FileInfo => ({\n size: stats.size,\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n isSymbolicLink: stats.isSymbolicLink(),\n createdAt: stats.birthtime,\n modifiedAt: stats.mtime,\n accessedAt: stats.atime,\n permissions: stats.mode,\n})\n\nconst toFsError = (p: string, op: string, error: unknown): FsError =>\n FsError(p, op, error instanceof Error ? error : new Error(String(error)))\n\n/**\n * Linux magic filesystems where recursive mkdir can hang indefinitely against\n * unwritable subpaths (libuv quirk; macOS errors immediately instead).\n * Refusing recursive mkdir under these prefixes keeps `mkdir({ recursive: true })`\n * fast-failing and predictable across platforms. See issue #135.\n */\nconst MAGIC_FS_PREFIXES: ReadonlyArray<string> = [\"/proc/\", \"/sys/\", \"/dev/\"]\n\nconst isMagicFsPath = (p: string): boolean => MAGIC_FS_PREFIXES.some((prefix) => p.startsWith(prefix))\n\nconst matchGlob = (filePath: string, pattern: string): boolean => {\n // Escape every regex metachar EXCEPT '*' first, so the subsequent\n // '*' transformations are the only special characters in the output.\n // Order matters: backslashes must be escaped before any '\\\\' insertion below.\n const escaped = pattern.replace(/[\\\\^$+?.()|[\\]{}]/g, \"\\\\$&\")\n const regex = escaped\n .replace(/\\*\\*\\//g, \"{{GLOBSTAR}}\")\n .replace(/\\*\\*/g, \"{{GLOBSTAR}}\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, \"(?:.*/)?\")\n return new RegExp(`^${regex}$`).test(filePath)\n}\n\n// Async helper: lift a Promise-returning thunk into a lazy IO, mapping rejections to\n// FsError. Nothing touches the filesystem until the IO runs. The interpreter awaits the\n// thunk inside its own try, so a synchronous throw from inside it (e.g. a bad encoding\n// argument) fails the same way a rejection does — same FsError, no unhandled rejection.\nconst liftAsync = <T>(p: string, op: string, thunk: () => Promise<T>): IO<never, FsError, T> =>\n IO.tryPromise({ try: thunk, catch: (err) => toFsError(p, op, err) })\n\nconst isNotFound = (err: unknown): boolean => err instanceof Error && \"code\" in err && err.code === \"ENOENT\"\n\n// Sync helper: run a thunk via Try and convert to Either<FsError, T>.\nconst liftSync = <T>(p: string, op: string, thunk: () => T): Either<FsError, T> =>\n Try(thunk).toEither((err) => toFsError(p, op, err))\n\nexport const Fs = {\n // Async methods — return a lazy IO<never, FsError, T>; nothing runs until `.run()`\n\n exists: (p: string): IO<never, never, boolean> =>\n IO.async(() => fs.access(p)).fold(\n () => false,\n () => true,\n ),\n\n readFile: (p: string, encoding: BufferEncoding = \"utf8\"): IO<never, FsError, string> =>\n liftAsync(p, \"readFile\", () => fs.readFile(p, { encoding })),\n\n readFileOpt: (p: string, encoding: BufferEncoding = \"utf8\"): IO<never, FsError, Option<string>> =>\n IO.async(() => fs.readFile(p, { encoding }))\n .fold(\n (err): Either<FsError, Option<string>> =>\n isNotFound(err) ? Right(Option<string>(undefined)) : Left(toFsError(p, \"readFile\", err)),\n (data): Either<FsError, Option<string>> => Right(Option(data)),\n )\n .flatMap((result) => IO.fromEither(result)),\n\n stat: (p: string): IO<never, FsError, FileInfo> => liftAsync(p, \"stat\", () => fs.stat(p).then(toFileInfo)),\n\n copyFile: (src: string, dest: string): IO<never, FsError, void> =>\n liftAsync(src, \"copyFile\", () => fs.copyFile(src, dest)),\n\n rename: (oldPath: string, newPath: string): IO<never, FsError, void> =>\n liftAsync(oldPath, \"rename\", () => fs.rename(oldPath, newPath)),\n\n readdir: (p: string): IO<never, FsError, List<string>> =>\n liftAsync(p, \"readdir\", () => fs.readdir(p).then((entries) => List<string>(entries))),\n\n glob: (dir: string, pattern: string): IO<never, FsError, List<string>> =>\n liftAsync(dir, \"glob\", () => fs.readdir(dir, { recursive: true, encoding: \"utf8\" })).map((entries) =>\n List<string>(entries.filter((entry) => matchGlob(entry, pattern))),\n ),\n\n writeFile: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): IO<never, FsError, void> =>\n liftAsync(p, \"writeFile\", () => fs.writeFile(p, data, { encoding })),\n\n appendFile: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): IO<never, FsError, void> =>\n liftAsync(p, \"appendFile\", () => fs.appendFile(p, data, { encoding })),\n\n mkdir: (p: string, options?: { recursive?: boolean }): IO<never, FsError, void> =>\n options?.recursive && isMagicFsPath(p)\n ? IO.fail(\n toFsError(p, \"mkdir\", new Error(\"recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)\")),\n )\n : liftAsync(p, \"mkdir\", () => fs.mkdir(p, options).then(() => undefined)),\n\n unlink: (p: string): IO<never, FsError, void> => liftAsync(p, \"unlink\", () => fs.unlink(p)),\n\n // Sync methods — return Either<FsError, T>\n\n existsSync: (p: string): boolean => Try(() => fsSync.accessSync(p)).isSuccess(),\n\n readFileSync: (p: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, string> =>\n liftSync(p, \"readFileSync\", () => fsSync.readFileSync(p, { encoding })),\n\n readFileOptSync: (p: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, Option<string>> => {\n const tryResult = Try(() => fsSync.readFileSync(p, { encoding }))\n return tryResult.fold<Either<FsError, Option<string>>>(\n (err) => (isNotFound(err) ? Right(Option<string>(undefined)) : Left(toFsError(p, \"readFileOptSync\", err))),\n (data) => Right(Option(data)),\n )\n },\n\n statSync: (p: string): Either<FsError, FileInfo> => liftSync(p, \"statSync\", () => toFileInfo(fsSync.statSync(p))),\n\n copyFileSync: (src: string, dest: string): Either<FsError, void> =>\n liftSync(src, \"copyFileSync\", () => fsSync.copyFileSync(src, dest)),\n\n renameSync: (oldPath: string, newPath: string): Either<FsError, void> =>\n liftSync(oldPath, \"renameSync\", () => fsSync.renameSync(oldPath, newPath)),\n\n readdirSync: (p: string): Either<FsError, List<string>> =>\n liftSync(p, \"readdirSync\", () => List(fsSync.readdirSync(p))),\n\n writeFileSync: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, void> =>\n liftSync(p, \"writeFileSync\", () => fsSync.writeFileSync(p, data, { encoding })),\n\n appendFileSync: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, void> =>\n liftSync(p, \"appendFileSync\", () => fsSync.appendFileSync(p, data, { encoding })),\n\n mkdirSync: (p: string, options?: { recursive?: boolean }): Either<FsError, void> => {\n if (options?.recursive && isMagicFsPath(p)) {\n return Left(\n toFsError(p, \"mkdirSync\", new Error(\"recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)\")),\n )\n }\n return liftSync(p, \"mkdirSync\", () => {\n fsSync.mkdirSync(p, options)\n })\n },\n\n unlinkSync: (p: string): Either<FsError, void> => liftSync(p, \"unlinkSync\", () => fsSync.unlinkSync(p)),\n}\n"],"mappings":"A,6LAmBA,MAAME,EAAc,IAAmC,CACrD,KAAMC,EAAM,KACZ,OAAQA,EAAM,OAAO,EACrB,YAAaA,EAAM,YAAY,EAC/B,eAAgBA,EAAM,eAAe,EACrC,UAAWA,EAAM,UACjB,WAAYA,EAAM,MAClB,WAAYA,EAAM,MAClB,YAAaA,EAAM,IACrB,GAEMC,GAAa,EAAW,EAAY,IACxCC,EAAQC,EAAGC,EAAIC,aAAiB,MAAQA,EAAY,MAAM,OAAOA,CAAK,CAAC,CAAC,EAQpEC,EAA2C,CAAC,SAAU,QAAS,OAAO,EAEtEC,EAAiB,GAAuBD,EAAkB,KAAM,GAAWH,EAAE,WAAWK,CAAM,CAAC,EAE/FC,GAAa,EAAkB,IAA6B,CAKhE,IAAMC,EADUC,EAAQ,QAAQ,qBAAsB,MAClC,CAAC,CAClB,QAAQ,UAAW,cAAc,CAAC,CAClC,QAAQ,QAAS,cAAc,CAAC,CAChC,QAAQ,MAAO,OAAO,CAAC,CACvB,QAAQ,oBAAqB,UAAU,EAC1C,OAAW,OAAO,IAAID,EAAM,EAAE,CAAC,CAAC,KAAKE,CAAQ,CAC/C,EAMMC,GAAgB,EAAW,EAAY,IAC3CC,EAAG,WAAW,CAAE,IAAKC,EAAO,MAAQ,GAAQd,EAAUE,EAAGC,EAAIY,CAAG,CAAE,CAAC,EAE/DC,EAAc,GAA0BD,aAAe,OAAS,SAAUA,GAAOA,EAAI,OAAS,SAG9FE,GAAe,EAAW,EAAY,IAC1CC,E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,EAAc,EAA2B,SAClEe,EAASf,EAAG,oBAAuBN,EAAO,cAAcM,EAAGqB,EAAM,CAAE,UAAS,CAAC,CAAC,EAEhF,gBAAiB,EAAW,EAAc,EAA2B,SACnEN,EAASf,EAAG,qBAAwBN,EAAO,eAAeM,EAAGqB,EAAM,CAAE,UAAS,CAAC,CAAC,EAElF,WAAY,EAAW,IACjBU,GAAS,WAAa3B,EAAcJ,CAAC,EAChCoB,EACLtB,EAAUE,EAAG,YAAa,gBAAI,MAAM,yEAAyE,CAAC,CAChH,EAEKe,EAASf,EAAG,gBAAmB,CACpCN,EAAO,UAAUM,EAAG+B,CAAO,CAC7B,CAAC,EAGH,WAAa,GAAqChB,EAASf,EAAG,iBAAoBN,EAAO,WAAWM,CAAC,CAAC,CACxG,E"}
|
|
1
|
+
{"version":3,"file":"Fs.js","names":["IO","Left","List","Option","Right","Try","fsSync","fs","FsError","toFileInfo","stats","toFsError","p","op","error","MAGIC_FS_PREFIXES","isMagicFsPath","prefix","matchGlob","filePath","pattern","regex","liftAsync","thunk","err","isNotFound","liftSync","Fs","encoding","data","result","src","dest","oldPath","newPath","entries","dir","entry","options"],"sources":["../../src/fs/Fs.ts"],"sourcesContent":["import * as fsSync from \"node:fs\"\nimport * as fs from \"node:fs/promises\"\n\nimport type { Either } from \"functype\"\nimport { IO, Left, List, Option, Right, Try } from \"functype\"\n\nimport { FsError } from \"../errors/errors\"\n\nexport type FileInfo = {\n readonly size: number\n readonly isFile: boolean\n readonly isDirectory: boolean\n readonly isSymbolicLink: boolean\n readonly createdAt: Date\n readonly modifiedAt: Date\n readonly accessedAt: Date\n readonly permissions: number\n}\n\nconst toFileInfo = (stats: fsSync.Stats): FileInfo => ({\n size: stats.size,\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n isSymbolicLink: stats.isSymbolicLink(),\n createdAt: stats.birthtime,\n modifiedAt: stats.mtime,\n accessedAt: stats.atime,\n permissions: stats.mode,\n})\n\nconst toFsError = (p: string, op: string, error: unknown): FsError =>\n FsError(p, op, error instanceof Error ? error : new Error(String(error)))\n\n/**\n * Linux magic filesystems where recursive mkdir can hang indefinitely against\n * unwritable subpaths (libuv quirk; macOS errors immediately instead).\n * Refusing recursive mkdir under these prefixes keeps `mkdir({ recursive: true })`\n * fast-failing and predictable across platforms. See issue #135.\n */\nconst MAGIC_FS_PREFIXES: ReadonlyArray<string> = [\"/proc/\", \"/sys/\", \"/dev/\"]\n\nconst isMagicFsPath = (p: string): boolean => MAGIC_FS_PREFIXES.some((prefix) => p.startsWith(prefix))\n\nconst matchGlob = (filePath: string, pattern: string): boolean => {\n // Escape every regex metachar EXCEPT '*' first, so the subsequent\n // '*' transformations are the only special characters in the output.\n // Order matters: backslashes must be escaped before any '\\\\' insertion below.\n const escaped = pattern.replace(/[\\\\^$+?.()|[\\]{}]/g, \"\\\\$&\")\n const regex = escaped\n .replace(/\\*\\*\\//g, \"{{GLOBSTAR}}\")\n .replace(/\\*\\*/g, \"{{GLOBSTAR}}\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, \"(?:.*/)?\")\n return new RegExp(`^${regex}$`).test(filePath)\n}\n\n// Async helper: lift a Promise-returning thunk into a lazy IO, mapping rejections to\n// FsError. Nothing touches the filesystem until the IO runs. The interpreter awaits the\n// thunk inside its own try, so a synchronous throw from inside it (e.g. a bad encoding\n// argument) fails the same way a rejection does — same FsError, no unhandled rejection.\nconst liftAsync = <T>(p: string, op: string, thunk: () => Promise<T>): IO<never, FsError, T> =>\n IO.tryPromise({ try: thunk, catch: (err) => toFsError(p, op, err) })\n\nconst isNotFound = (err: unknown): boolean => err instanceof Error && \"code\" in err && err.code === \"ENOENT\"\n\n// Sync helper: run a thunk via Try and convert to Either<FsError, T>.\nconst liftSync = <T>(p: string, op: string, thunk: () => T): Either<FsError, T> =>\n Try(thunk).toEither((err) => toFsError(p, op, err))\n\nexport const Fs = {\n // Async methods — return a lazy IO<never, FsError, T>; nothing runs until `.run()`\n\n exists: (p: string): IO<never, never, boolean> =>\n IO.async(() => fs.access(p)).fold(\n () => false,\n () => true,\n ),\n\n readFile: (p: string, encoding: BufferEncoding = \"utf8\"): IO<never, FsError, string> =>\n liftAsync(p, \"readFile\", () => fs.readFile(p, { encoding })),\n\n readFileOpt: (p: string, encoding: BufferEncoding = \"utf8\"): IO<never, FsError, Option<string>> =>\n IO.async(() => fs.readFile(p, { encoding }))\n .fold(\n (err): Either<FsError, Option<string>> =>\n isNotFound(err) ? Right(Option<string>(undefined)) : Left(toFsError(p, \"readFile\", err)),\n (data): Either<FsError, Option<string>> => Right(Option(data)),\n )\n .flatMap((result) => IO.fromEither(result)),\n\n stat: (p: string): IO<never, FsError, FileInfo> => liftAsync(p, \"stat\", () => fs.stat(p).then(toFileInfo)),\n\n copyFile: (src: string, dest: string): IO<never, FsError, void> =>\n liftAsync(src, \"copyFile\", () => fs.copyFile(src, dest)),\n\n rename: (oldPath: string, newPath: string): IO<never, FsError, void> =>\n liftAsync(oldPath, \"rename\", () => fs.rename(oldPath, newPath)),\n\n readdir: (p: string): IO<never, FsError, List<string>> =>\n liftAsync(p, \"readdir\", () => fs.readdir(p).then((entries) => List<string>(entries))),\n\n glob: (dir: string, pattern: string): IO<never, FsError, List<string>> =>\n liftAsync(dir, \"glob\", () => fs.readdir(dir, { recursive: true, encoding: \"utf8\" })).map((entries) =>\n List<string>(entries.filter((entry) => matchGlob(entry, pattern))),\n ),\n\n writeFile: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): IO<never, FsError, void> =>\n liftAsync(p, \"writeFile\", () => fs.writeFile(p, data, { encoding })),\n\n appendFile: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): IO<never, FsError, void> =>\n liftAsync(p, \"appendFile\", () => fs.appendFile(p, data, { encoding })),\n\n mkdir: (p: string, options?: { recursive?: boolean }): IO<never, FsError, void> =>\n options?.recursive && isMagicFsPath(p)\n ? IO.fail(\n toFsError(p, \"mkdir\", new Error(\"recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)\")),\n )\n : liftAsync(p, \"mkdir\", () => fs.mkdir(p, options).then(() => undefined)),\n\n unlink: (p: string): IO<never, FsError, void> => liftAsync(p, \"unlink\", () => fs.unlink(p)),\n\n // Sync methods — return Either<FsError, T>\n\n existsSync: (p: string): boolean => Try(() => fsSync.accessSync(p)).isSuccess(),\n\n readFileSync: (p: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, string> =>\n liftSync(p, \"readFileSync\", () => fsSync.readFileSync(p, { encoding })),\n\n readFileOptSync: (p: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, Option<string>> => {\n const tryResult = Try(() => fsSync.readFileSync(p, { encoding }))\n return tryResult.fold<Either<FsError, Option<string>>>(\n (err) => (isNotFound(err) ? Right(Option<string>(undefined)) : Left(toFsError(p, \"readFileOptSync\", err))),\n (data) => Right(Option(data)),\n )\n },\n\n statSync: (p: string): Either<FsError, FileInfo> => liftSync(p, \"statSync\", () => toFileInfo(fsSync.statSync(p))),\n\n copyFileSync: (src: string, dest: string): Either<FsError, void> =>\n liftSync(src, \"copyFileSync\", () => fsSync.copyFileSync(src, dest)),\n\n renameSync: (oldPath: string, newPath: string): Either<FsError, void> =>\n liftSync(oldPath, \"renameSync\", () => fsSync.renameSync(oldPath, newPath)),\n\n readdirSync: (p: string): Either<FsError, List<string>> =>\n liftSync(p, \"readdirSync\", () => List(fsSync.readdirSync(p))),\n\n writeFileSync: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, void> =>\n liftSync(p, \"writeFileSync\", () => fsSync.writeFileSync(p, data, { encoding })),\n\n appendFileSync: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, void> =>\n liftSync(p, \"appendFileSync\", () => fsSync.appendFileSync(p, data, { encoding })),\n\n mkdirSync: (p: string, options?: { recursive?: boolean }): Either<FsError, void> => {\n if (options?.recursive && isMagicFsPath(p)) {\n return Left(\n toFsError(p, \"mkdirSync\", new Error(\"recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)\")),\n )\n }\n return liftSync(p, \"mkdirSync\", () => {\n fsSync.mkdirSync(p, options)\n })\n },\n\n unlinkSync: (p: string): Either<FsError, void> => liftSync(p, \"unlinkSync\", () => fsSync.unlinkSync(p)),\n}\n"],"mappings":"A,6LAmBA,MAAMS,EAAcC,IAAmC,CACrD,KAAMA,EAAM,KACZ,OAAQA,EAAM,OAAO,EACrB,YAAaA,EAAM,YAAY,EAC/B,eAAgBA,EAAM,eAAe,EACrC,UAAWA,EAAM,UACjB,WAAYA,EAAM,MAClB,WAAYA,EAAM,MAClB,YAAaA,EAAM,IACrB,GAEMC,GAAaC,EAAWC,EAAYC,IACxCN,EAAQI,EAAGC,EAAIC,aAAiB,MAAQA,EAAY,MAAM,OAAOA,CAAK,CAAC,CAAC,EAQpEC,EAA2C,CAAC,SAAU,QAAS,OAAO,EAEtEC,EAAiBJ,GAAuBG,EAAkB,KAAME,GAAWL,EAAE,WAAWK,CAAM,CAAC,EAE/FC,GAAaC,EAAkBC,IAA6B,CAKhE,IAAMC,EADUD,EAAQ,QAAQ,qBAAsB,MAClC,CAAC,CAClB,QAAQ,UAAW,cAAc,CAAC,CAClC,QAAQ,QAAS,cAAc,CAAC,CAChC,QAAQ,MAAO,OAAO,CAAC,CACvB,QAAQ,oBAAqB,UAAU,EAC1C,OAAW,OAAO,IAAIC,EAAM,EAAE,CAAC,CAAC,KAAKF,CAAQ,CAC/C,EAMMG,GAAgBV,EAAWC,EAAYU,IAC3CvB,EAAG,WAAW,CAAE,IAAKuB,EAAO,MAAQC,GAAQb,EAAUC,EAAGC,EAAIW,CAAG,CAAE,CAAC,EAE/DC,EAAcD,GAA0BA,aAAe,OAAS,SAAUA,GAAOA,EAAI,OAAS,SAG9FE,GAAed,EAAWC,EAAYU,IAC1ClB,EAAIkB,CAAK,CAAC,CAAC,SAAUC,GAAQb,EAAUC,EAAGC,EAAIW,CAAG,CAAC,EAEvCG,EAAK,CAGhB,OAASf,GACPZ,E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BAAuBN,EAAO,cAAcM,EAAGiB,EAAM,CAAED,UAAS,CAAC,CAAC,EAEhF,gBAAiBhB,EAAWiB,EAAcD,EAA2B,SACnEF,EAASd,EAAG,qBAAwBN,EAAO,eAAeM,EAAGiB,EAAM,CAAED,UAAS,CAAC,CAAC,EAElF,WAAYhB,EAAW0B,IACjBA,GAAS,WAAatB,EAAcJ,CAAC,EAChCX,EACLU,EAAUC,EAAG,YAAa,gBAAI,MAAM,yEAAyE,CAAC,CAChH,EAEKc,EAASd,EAAG,gBAAmB,CACpCN,EAAO,UAAUM,EAAG0B,CAAO,CAC7B,CAAC,EAGH,WAAa1B,GAAqCc,EAASd,EAAG,iBAAoBN,EAAO,WAAWM,CAAC,CAAC,CACxG,E"}
|
package/dist/fs/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as Fs, t as FileInfo } from "../Fs-
|
|
1
|
+
import { n as Fs, t as FileInfo } from "../Fs-ZlDyYVKg.js";
|
|
2
2
|
export { type FileInfo, Fs };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import { a as PathError, i as OsError, n as EnvError, o as ProcessError, r as FsError, t as ConfigError } from "./errors-
|
|
2
|
-
import { t as ConfigResolver } from "./ConfigResolver-
|
|
1
|
+
import { a as PathError, i as OsError, n as EnvError, o as ProcessError, r as FsError, t as ConfigError } from "./errors-CZA32bA8.js";
|
|
2
|
+
import { t as ConfigResolver } from "./ConfigResolver-DNUfcdRT.js";
|
|
3
3
|
import "./config/index.js";
|
|
4
|
-
import { t as Env } from "./Env-
|
|
4
|
+
import { t as Env } from "./Env-DSWZuC61.js";
|
|
5
5
|
import "./env/index.js";
|
|
6
6
|
import "./errors/index.js";
|
|
7
|
-
import { n as Fs, t as FileInfo } from "./Fs-
|
|
7
|
+
import { n as Fs, t as FileInfo } from "./Fs-ZlDyYVKg.js";
|
|
8
8
|
import "./fs/index.js";
|
|
9
|
-
import { i as expandVars, n as expandPath, r as expandTilde, t as Path } from "./PathExpander-
|
|
9
|
+
import { i as expandVars, n as expandPath, r as expandTilde, t as Path } from "./PathExpander-C3o94nlr.js";
|
|
10
10
|
import "./path/index.js";
|
|
11
|
-
import { i as UserInfo, n as CloudStorageDir, r as Platform, t as CloudProvider } from "./Platform-
|
|
11
|
+
import { i as UserInfo, n as CloudStorageDir, r as Platform, t as CloudProvider } from "./Platform-Drtg2_HB.js";
|
|
12
12
|
import "./platform/index.js";
|
|
13
|
-
import { n as Process, t as ExecResult } from "./Process-
|
|
13
|
+
import { n as Process, t as ExecResult } from "./Process-CkyuPYhy.js";
|
|
14
14
|
import "./process/index.js";
|
|
15
15
|
export { type CloudProvider, type CloudStorageDir, ConfigError, ConfigResolver, Env, EnvError, type ExecResult, type FileInfo, Fs, FsError, type OsError, Path, PathError, Platform, Process, ProcessError, type UserInfo, expandPath, expandTilde, expandVars };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as expandVars, n as expandPath, r as expandTilde, t as Path } from "../PathExpander-
|
|
1
|
+
import { i as expandVars, n as expandPath, r as expandTilde, t as Path } from "../PathExpander-C3o94nlr.js";
|
|
2
2
|
export { Path, expandPath, expandTilde, expandVars };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Left as e,Option as t,Right as n}from"functype";import*as r from"node:os";import*as i from"node:path";import{PathError as a}from"../errors/errors.js";const o=e=>e===`~`?r.homedir():e.startsWith(`~/`)||e.startsWith(`~\\`)?i.join(r.homedir(),e.slice(2)):e,s=/\$(?:\{([^}$]+)\}|([A-Za-z_][A-Za-z0-9_]*))/g,c=(e,n)=>t(e).orElse(()=>t(n)).getOrElse(()=>``),l=t=>{let r=Array.from(t.matchAll(s),e=>c(e[1],e[2])).filter(e=>process.env[e]===void 0);return r.length>0?e(a(t,`unresolved_variable`,`Unresolved variables: ${r.join(`, `)}`)):n(t.replace(s,(e,t,n)=>process.env[c(t,n)]??e))},u=e=>l(o(e)).map(e=>i.resolve(e)),d={expand:u,expandTilde:o,expandVars:l,join:(...e)=>i.join(...e),resolve:(...e)=>i.resolve(...e),dirname:e=>i.dirname(e),basename:(e,t)=>i.basename(e,t),extname:e=>i.extname(e),isAbsolute:e=>i.isAbsolute(e)};export{d as Path,u as expandPath,o as expandTilde,l as expandVars};
|
|
2
2
|
//# sourceMappingURL=PathExpander.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PathExpander.js","names":["os","nodePath","expandTilde","p","VAR_PATTERN","varNameOf","
|
|
1
|
+
{"version":3,"file":"PathExpander.js","names":["Left","Option","Right","os","nodePath","PathError","expandTilde","p","VAR_PATTERN","varNameOf","braced","bare","expandVars","unresolvedVars","match","varName","expandPath","expanded","Path","segments","suffix"],"sources":["../../src/path/PathExpander.ts"],"sourcesContent":["import * as os from \"node:os\"\nimport * as nodePath from \"node:path\"\n\nimport type { Either } from \"functype\"\nimport { Left, Option, Right } from \"functype\"\n\nimport { PathError } from \"../errors/errors\"\n\nexport const expandTilde = (p: string): string => {\n if (p === \"~\") return os.homedir()\n if (p.startsWith(\"~/\") || p.startsWith(\"~\\\\\")) return nodePath.join(os.homedir(), p.slice(2))\n return p\n}\n\n// Factor out the leading `$` and forbid `$` inside `${...}` so the engine\n// can't backtrack catastrophically on inputs like `${{${{${{...` (CodeQL\n// js/polynomial-redos).\nconst VAR_PATTERN = /\\$(?:\\{([^}$]+)\\}|([A-Za-z_][A-Za-z0-9_]*))/g\n\n/** `NAME` from `${NAME}` (first capture) or `$NAME` (second). */\nconst varNameOf = (braced: string | undefined, bare: string | undefined): string =>\n Option(braced)\n .orElse(() => Option(bare))\n .getOrElse(() => \"\")\n\nexport const expandVars = (p: string): Either<PathError, string> => {\n const unresolvedVars = Array.from(p.matchAll(VAR_PATTERN), (match) => varNameOf(match[1], match[2])).filter(\n (varName) => process.env[varName] === undefined,\n )\n\n if (unresolvedVars.length > 0) {\n return Left(PathError(p, \"unresolved_variable\", `Unresolved variables: ${unresolvedVars.join(\", \")}`))\n }\n\n return Right(\n p.replace(\n VAR_PATTERN,\n (match: string, braced: string | undefined, bare: string | undefined) =>\n process.env[varNameOf(braced, bare)] ?? match,\n ),\n )\n}\n\nexport const expandPath = (p: string): Either<PathError, string> =>\n expandVars(expandTilde(p)).map((expanded) => nodePath.resolve(expanded))\n\nexport const Path = {\n expand: expandPath,\n expandTilde,\n expandVars,\n join: (...segments: string[]): string => nodePath.join(...segments),\n resolve: (...segments: string[]): string => nodePath.resolve(...segments),\n dirname: (p: string): string => nodePath.dirname(p),\n basename: (p: string, suffix?: string): string => nodePath.basename(p, suffix),\n extname: (p: string): string => nodePath.extname(p),\n isAbsolute: (p: string): boolean => nodePath.isAbsolute(p),\n}\n"],"mappings":"A,6JAQA,MAAaM,EAAeC,GACtBA,IAAM,IAAYJ,EAAG,QAAQ,EAC7BI,EAAE,WAAW,IAAI,GAAKA,EAAE,WAAW,KAAK,EAAUH,EAAS,KAAKD,EAAG,QAAQ,EAAGI,EAAE,MAAM,CAAC,CAAC,EACrFA,EAMHC,EAAc,+CAGdC,GAAaC,EAA4BC,IAC7CV,EAAOS,CAAM,CAAC,CACX,WAAaT,EAAOU,CAAI,CAAC,CAAC,CAC1B,cAAgB,EAAE,EAEVC,EAAcL,GAAyC,CAClE,IAAMM,EAAiB,MAAM,KAAKN,EAAE,SAASC,CAAW,EAAIM,GAAUL,EAAUK,EAAM,GAAIA,EAAM,EAAE,CAAC,CAAC,CAAC,OAClGC,GAAY,QAAQ,IAAIA,KAAa,IAAA,EACxC,EAMA,OAJIF,EAAe,OAAS,EACnBb,EAAKK,EAAUE,EAAG,sBAAuB,yBAAyBM,EAAe,KAAK,IAAI,GAAG,CAAC,EAGhGX,EACLK,EAAE,QACAC,GACCM,EAAeJ,EAA4BC,IAC1C,QAAQ,IAAIF,EAAUC,EAAQC,CAAI,IAAMG,CAC5C,CACF,CACF,EAEaE,EAAcT,GACzBK,EAAWN,EAAYC,CAAC,CAAC,CAAC,CAAC,IAAKU,GAAab,EAAS,QAAQa,CAAQ,CAAC,EAE5DC,EAAO,CAClB,OAAQF,EACRV,cACAM,aACA,MAAO,GAAGO,IAA+Bf,EAAS,KAAK,GAAGe,CAAQ,EAClE,SAAU,GAAGA,IAA+Bf,EAAS,QAAQ,GAAGe,CAAQ,EACxE,QAAUZ,GAAsBH,EAAS,QAAQG,CAAC,EAClD,UAAWA,EAAWa,IAA4BhB,EAAS,SAASG,EAAGa,CAAM,EAC7E,QAAUb,GAAsBH,EAAS,QAAQG,CAAC,EAClD,WAAaA,GAAuBH,EAAS,WAAWG,CAAC,CAC3D,E"}
|
package/dist/path/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as expandVars, n as expandPath, r as expandTilde, t as Path } from "../PathExpander-
|
|
1
|
+
import { i as expandVars, n as expandPath, r as expandTilde, t as Path } from "../PathExpander-C3o94nlr.js";
|
|
2
2
|
export { Path, expandPath, expandTilde, expandVars };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as UserInfo, n as CloudStorageDir, r as Platform, t as CloudProvider } from "../Platform-
|
|
1
|
+
import { i as UserInfo, n as CloudStorageDir, r as Platform, t as CloudProvider } from "../Platform-Drtg2_HB.js";
|
|
2
2
|
export { CloudProvider, CloudStorageDir, Platform, UserInfo };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{execSync as e}from"node:child_process";import*as t from"node:fs";import*as n from"node:os";import*as r from"node:path";import{List as i,Option as a,Set as o,Try as s}from"functype";const c=()=>s(()=>t.statSync(`/.dockerenv`)).isSuccess(),l=()=>s(()=>t.readFileSync(`/proc/self/cgroup`,`utf8`)).map(e=>e.includes(`docker`)).toEither(()=>!1).fold(()=>!1,e=>e),u=e=>{let t={};return()=>(`value`in t||(t.value=e()),t.value)},d=u(()=>c()||l()),f=u(()=>s(()=>t.readFileSync(`/proc/self/cgroup`,`utf8`)).map(e=>e.includes(`kube`)).fold(()=>!1,e=>e)),p=u(()=>s(()=>t.readFileSync(`/proc/version`,`utf8`)).map(e=>e.includes(`Microsoft`)||e.includes(`WSL`)).fold(()=>!1,e=>e)),m=u(()=>process.env.CI!==void 0||process.env.GITHUB_ACTIONS!==void 0||process.env.GITLAB_CI!==void 0||process.env.CIRCLECI!==void 0||process.env.JENKINS_URL!==void 0||process.env.TRAVIS!==void 0||process.env.BUILDKITE!==void 0),h=o.of(`all users`,`default`,`default user`,`public`),g=e=>{let t=e.toLowerCase();return!!(h.contains(t)||t.startsWith(`defaultuser`)||t.startsWith(`desktop.`)||t.startsWith(`wsiaccount`))},_=e=>s(()=>t.statSync(e).isDirectory()).fold(()=>!1,e=>e),v=e=>s(()=>t.readdirSync(e)).map(t=>t.filter(t=>!g(t)&&_(r.join(e,t)))).toOption(),y=(t,n)=>{let r=s(()=>e(`cmd.exe /c echo %USERPROFILE%`,{timeout:3e3,encoding:`utf8`}).trim()).toOption().flatMap(e=>{let t=e.match(/^([A-Za-z]):\\(.*)$/);if(!t)return a(void 0);let n=`/mnt/${t[1].toLowerCase()}/${t[2].replace(/\\/g,`/`)}`;return _(n)?a(n):a(void 0)}).getOrElse(()=>n);return a(r)},b=u(()=>{if(!p())return a(void 0);let e=`/mnt/c/Users`;return v(e).fold(()=>a(void 0),t=>t.length===1?a(r.join(e,t[0])):t.length>1?y(e,r.join(e,t[0])):a(void 0))}),x=e=>e===`OneDrive`||e.startsWith(`OneDrive `)||e.startsWith(`OneDrive-`)?a({provider:`onedrive`,label:e}):a(e===`Google Drive`?{provider:`gdrive`,label:e}:e===`Dropbox`?{provider:`dropbox`,label:e}:void 0),S=e=>s(()=>t.readdirSync(e)).map(t=>t.flatMap(t=>{let n=r.join(e,t);return x(t).fold(()=>[],e=>_(n)?[{provider:e.provider,path:n,label:e.label}]:[])})).fold(()=>[],e=>e),C=e=>{let n=r.join(e,`Library`,`CloudStorage`);return s(()=>t.readdirSync(n)).map(e=>e.flatMap(e=>{let t=r.join(n,e);return _(t)?e.startsWith(`OneDrive`)?[{provider:`onedrive`,path:t,label:e}]:e.startsWith(`GoogleDrive`)?[{provider:`gdrive`,path:t,label:e}]:[]:[]})).fold(()=>[],e=>e)},w=e=>{let t=r.join(e,`Library`,`Mobile Documents`,`com~apple~CloudDocs`);return _(t)?[{provider:`icloud`,path:t,label:`iCloud Drive`}]:[]},T=e=>[...S(e),...C(e),...w(e)],E={os:()=>process.platform,arch:()=>process.arch,homeDir:()=>n.homedir(),tmpDir:()=>n.tmpdir(),hostname:()=>n.hostname(),eol:()=>n.EOL,pathSep:()=>r.sep,isWindows:()=>process.platform===`win32`,isMac:()=>process.platform===`darwin`,isLinux:()=>process.platform===`linux`,userInfo:()=>s(()=>n.userInfo()).map(e=>({username:e.username,uid:e.uid,gid:e.gid,shell:a(e.shell),homedir:e.homedir})).toOption(),isDocker:()=>d(),isKubernetes:()=>f(),isWSL:()=>p(),isCI:()=>m(),isContainer:()=>E.isDocker()||E.isKubernetes(),windowsHomeDir:()=>b(),homeDirs:()=>{let e=n.homedir(),t=E.windowsHomeDir().fold(()=>[],t=>t===e?[]:[t]);return i([e,...t])},cloudStorageDirs:e=>{if(e!==void 0)return i(T(e));let t=E.homeDirs().toArray().flatMap(e=>[...T(e)]).reduce((e,t)=>e.seen.includes(t.path)?e:{seen:[...e.seen,t.path],results:[...e.results,t]},{seen:[],results:[]});return i(t.results)}};export{E as Platform};
|
|
2
2
|
//# sourceMappingURL=Platform.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Platform.js","names":["fs","os","path","hasDockerEnv","Try","hasDockerCGroup","contents","matched","memo","cache","fn","cachedIsDocker","cachedIsKube","cachedIsWSL","version","cachedIsCI","\"CI\"","\"GITHUB_ACTIONS\"","\"GITLAB_CI\"","\"CIRCLECI\"","\"JENKINS_URL\"","\"TRAVIS\"","\"BUILDKITE\"","SYSTEM_ACCOUNTS","Set","isSystemAccount","lower","name","isDirectory","p","isDir","readRealUsers","usersDir","entries","resolveViaCmdExe","parsed","execSync","match","raw","Option","wslPath","fallback","cachedWindowsHome","realUsers","detectCloudProvider","scanDirectChildren","home","fullPath","detection","results","scanMacCloudStorage","cloudStoragePath","scanMacICloud","icloudPath","scanCloudStorageDirs","Platform","info","primary","windowsHome","h","List","deduped","acc","dir"],"sources":["../../src/platform/Platform.ts"],"sourcesContent":["import { execSync } from \"node:child_process\"\nimport * as fs from \"node:fs\"\nimport * as os from \"node:os\"\nimport * as path from \"node:path\"\n\nimport { List, Option, Set, Try } from \"functype\"\n\nexport type UserInfo = {\n readonly username: string\n readonly uid: number\n readonly gid: number\n readonly shell: Option<string>\n readonly homedir: string\n}\n\nexport type CloudProvider = \"onedrive\" | \"gdrive\" | \"dropbox\" | \"icloud\"\n\nexport type CloudStorageDir = {\n readonly provider: CloudProvider\n readonly path: string\n readonly label: string\n}\n\nconst hasDockerEnv = (): boolean => Try(() => fs.statSync(\"/.dockerenv\")).isSuccess()\n\nconst hasDockerCGroup = (): boolean =>\n Try(() => fs.readFileSync(\"/proc/self/cgroup\", \"utf8\"))\n .map((contents) => contents.includes(\"docker\"))\n .toEither((): boolean => false)\n .fold(\n () => false,\n (matched) => matched,\n )\n\nconst memo = <T>(fn: () => T): (() => T) => {\n const cache: { value?: T } = {}\n return () => {\n if (!(\"value\" in cache)) {\n cache.value = fn()\n }\n return cache.value as T\n }\n}\n\nconst cachedIsDocker = memo(() => hasDockerEnv() || hasDockerCGroup())\nconst cachedIsKube = memo(() =>\n Try(() => fs.readFileSync(\"/proc/self/cgroup\", \"utf8\"))\n .map((contents) => contents.includes(\"kube\"))\n .fold(\n () => false,\n (matched) => matched,\n ),\n)\nconst cachedIsWSL = memo(() =>\n Try(() => fs.readFileSync(\"/proc/version\", \"utf8\"))\n .map((version) => version.includes(\"Microsoft\") || version.includes(\"WSL\"))\n .fold(\n () => false,\n (matched) => matched,\n ),\n)\nconst cachedIsCI = memo(\n () =>\n process.env[\"CI\"] !== undefined ||\n process.env[\"GITHUB_ACTIONS\"] !== undefined ||\n process.env[\"GITLAB_CI\"] !== undefined ||\n process.env[\"CIRCLECI\"] !== undefined ||\n process.env[\"JENKINS_URL\"] !== undefined ||\n process.env[\"TRAVIS\"] !== undefined ||\n process.env[\"BUILDKITE\"] !== undefined,\n)\n\nconst SYSTEM_ACCOUNTS = Set.of(\"all users\", \"default\", \"default user\", \"public\")\n\nconst isSystemAccount = (name: string): boolean => {\n const lower = name.toLowerCase()\n if (SYSTEM_ACCOUNTS.contains(lower)) return true\n if (lower.startsWith(\"defaultuser\") || lower.startsWith(\"desktop.\") || lower.startsWith(\"wsiaccount\")) return true\n return false\n}\n\nconst isDirectory = (p: string): boolean =>\n Try(() => fs.statSync(p).isDirectory()).fold(\n () => false,\n (isDir) => isDir,\n )\n\nconst readRealUsers = (usersDir: string): Option<readonly string[]> => {\n const filterRealUsers = (entries: readonly string[]): readonly string[] =>\n entries.filter((name) => !isSystemAccount(name) && isDirectory(path.join(usersDir, name)))\n return Try(() => fs.readdirSync(usersDir))\n .map(filterRealUsers)\n .toOption()\n}\n\nconst resolveViaCmdExe = (usersDir: string, fallback: string): Option<string> => {\n // Convert Windows path C:\\Users\\foo → /mnt/c/Users/foo if it's a directory;\n // returns None for unparseable output or non-existent directories.\n const parseCmdOutput = (raw: string): Option<string> => {\n const match = raw.match(/^([A-Za-z]):\\\\(.*)$/)\n if (!match) return Option<string>(undefined)\n const drive = (match[1] as string).toLowerCase()\n const rest = (match[2] as string).replace(/\\\\/g, \"/\")\n const wslPath = `/mnt/${drive}/${rest}`\n return isDirectory(wslPath) ? Option(wslPath) : Option<string>(undefined)\n }\n const parsed = Try(() => execSync(\"cmd.exe /c echo %USERPROFILE%\", { timeout: 3000, encoding: \"utf8\" }).trim())\n .toOption()\n .flatMap(parseCmdOutput)\n .getOrElse(() => fallback)\n return Option(parsed)\n}\n\nconst resolveWindowsHome = (): Option<string> => {\n if (!cachedIsWSL()) return Option<string>(undefined)\n\n const usersDir = \"/mnt/c/Users\"\n return readRealUsers(usersDir).fold<Option<string>>(\n () => Option<string>(undefined),\n (realUsers) => {\n if (realUsers.length === 1) return Option(path.join(usersDir, realUsers[0] as string))\n if (realUsers.length > 1) return resolveViaCmdExe(usersDir, path.join(usersDir, realUsers[0] as string))\n return Option<string>(undefined)\n },\n )\n}\n\nconst cachedWindowsHome = memo(resolveWindowsHome)\n\ntype CloudDetection = { readonly provider: CloudProvider; readonly label: string }\n\nconst detectCloudProvider = (name: string): Option<CloudDetection> => {\n if (name === \"OneDrive\" || name.startsWith(\"OneDrive \") || name.startsWith(\"OneDrive-\")) {\n return Option({ provider: \"onedrive\" as const, label: name })\n }\n if (name === \"Google Drive\") return Option({ provider: \"gdrive\" as const, label: name })\n if (name === \"Dropbox\") return Option({ provider: \"dropbox\" as const, label: name })\n return Option<CloudDetection>(undefined)\n}\n\nconst scanDirectChildren = (home: string): readonly CloudStorageDir[] =>\n Try(() => fs.readdirSync(home))\n .map((entries) =>\n entries.flatMap((name): ReadonlyArray<CloudStorageDir> => {\n const fullPath = path.join(home, name)\n return detectCloudProvider(name).fold<ReadonlyArray<CloudStorageDir>>(\n () => [],\n (detection) =>\n isDirectory(fullPath) ? [{ provider: detection.provider, path: fullPath, label: detection.label }] : [],\n )\n }),\n )\n .fold<readonly CloudStorageDir[]>(\n () => [],\n (results) => results,\n )\n\nconst scanMacCloudStorage = (home: string): readonly CloudStorageDir[] => {\n const cloudStoragePath = path.join(home, \"Library\", \"CloudStorage\")\n return Try(() => fs.readdirSync(cloudStoragePath))\n .map((entries) =>\n entries.flatMap((name): ReadonlyArray<CloudStorageDir> => {\n const fullPath = path.join(cloudStoragePath, name)\n if (!isDirectory(fullPath)) return []\n if (name.startsWith(\"OneDrive\")) return [{ provider: \"onedrive\", path: fullPath, label: name }]\n if (name.startsWith(\"GoogleDrive\")) return [{ provider: \"gdrive\", path: fullPath, label: name }]\n return []\n }),\n )\n .fold<readonly CloudStorageDir[]>(\n () => [],\n (results) => results,\n )\n}\n\nconst scanMacICloud = (home: string): readonly CloudStorageDir[] => {\n const icloudPath = path.join(home, \"Library\", \"Mobile Documents\", \"com~apple~CloudDocs\")\n return isDirectory(icloudPath) ? [{ provider: \"icloud\", path: icloudPath, label: \"iCloud Drive\" }] : []\n}\n\nconst scanCloudStorageDirs = (home: string): readonly CloudStorageDir[] => [\n ...scanDirectChildren(home),\n ...scanMacCloudStorage(home),\n ...scanMacICloud(home),\n]\n\nexport const Platform = {\n os: (): \"darwin\" | \"linux\" | \"win32\" | string => process.platform,\n arch: (): string => process.arch,\n homeDir: (): string => os.homedir(),\n tmpDir: (): string => os.tmpdir(),\n hostname: (): string => os.hostname(),\n eol: (): string => os.EOL,\n pathSep: (): string => path.sep,\n\n isWindows: (): boolean => process.platform === \"win32\",\n isMac: (): boolean => process.platform === \"darwin\",\n isLinux: (): boolean => process.platform === \"linux\",\n\n userInfo: (): Option<UserInfo> => {\n const toUserInfo = (info: os.UserInfo<string>): UserInfo => ({\n username: info.username,\n uid: info.uid,\n gid: info.gid,\n shell: Option(info.shell),\n homedir: info.homedir,\n })\n return Try(() => os.userInfo())\n .map(toUserInfo)\n .toOption()\n },\n\n isDocker: (): boolean => cachedIsDocker(),\n isKubernetes: (): boolean => cachedIsKube(),\n isWSL: (): boolean => cachedIsWSL(),\n isCI: (): boolean => cachedIsCI(),\n\n isContainer: (): boolean => Platform.isDocker() || Platform.isKubernetes(),\n\n windowsHomeDir: (): Option<string> => cachedWindowsHome(),\n\n homeDirs: (): List<string> => {\n const primary = os.homedir()\n const windowsHome = Platform.windowsHomeDir().fold<readonly string[]>(\n () => [],\n (h) => (h !== primary ? [h] : []),\n )\n return List<string>([primary, ...windowsHome])\n },\n\n cloudStorageDirs: (home?: string): List<CloudStorageDir> => {\n if (home !== undefined) return List(scanCloudStorageDirs(home))\n const allDirs = Platform.homeDirs()\n .toArray()\n .flatMap((h) => [...scanCloudStorageDirs(h)])\n // Deduplicate by path, first-wins\n const deduped = allDirs.reduce<{\n readonly seen: ReadonlyArray<string>\n readonly results: ReadonlyArray<CloudStorageDir>\n }>(\n (acc, dir) =>\n acc.seen.includes(dir.path) ? acc : { seen: [...acc.seen, dir.path], results: [...acc.results, dir] },\n { seen: [], results: [] },\n )\n return List(deduped.results)\n },\n}\n"],"mappings":"A,4LAuBA,MAAMG,MAA8BC,MAAUJ,EAAG,SAAS,aAAa,CAAC,CAAC,CAAC,UAAU,EAE9EK,MACJD,MAAUJ,EAAG,aAAa,oBAAqB,MAAM,CAAC,CAAC,CACpD,IAAK,GAAaM,EAAS,SAAS,QAAQ,CAAC,CAAC,CAC9C,aAAwB,EAAK,CAAC,CAC9B,SACO,GACL,GAAYC,CACf,EAEEC,EAAW,GAA2B,CAC1C,IAAMC,EAAuB,CAAC,EAC9B,WACQ,UAAWA,IACf,EAAM,MAAQC,EAAG,GAEZD,EAAM,MAEjB,EAEME,EAAiBH,MAAWL,EAAa,GAAKE,EAAgB,CAAC,EAC/DO,EAAeJ,MACnBJ,MAAUJ,EAAG,aAAa,oBAAqB,MAAM,CAAC,CAAC,CACpD,IAAK,GAAaM,EAAS,SAAS,MAAM,CAAC,CAAC,CAC5C,SACO,GACL,GAAYC,CACf,CACJ,EACMM,EAAcL,MAClBJ,MAAUJ,EAAG,aAAa,gBAAiB,MAAM,CAAC,CAAC,CAChD,IAAK,GAAYc,EAAQ,SAAS,WAAW,GAAKA,EAAQ,SAAS,KAAK,CAAC,CAAC,CAC1E,SACO,GACL,GAAYP,CACf,CACJ,EACMQ,EAAaP,MAEf,QAAQ,IAAIQ,KAAU,IAAA,IACtB,QAAQ,IAAIC,iBAAsB,IAAA,IAClC,QAAQ,IAAIC,YAAiB,IAAA,IAC7B,QAAQ,IAAIC,WAAgB,IAAA,IAC5B,QAAQ,IAAIC,cAAmB,IAAA,IAC/B,QAAQ,IAAIC,SAAc,IAAA,IAC1B,QAAQ,IAAIC,YAAiB,IAAA,EACjC,EAEMC,EAAkBC,EAAI,GAAG,YAAa,UAAW,eAAgB,QAAQ,EAEzEC,EAAmB,GA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AC/C,EAEA,iBAAmB,GAAyC,CAC1D,GAAIZ,IAAS,IAAA,GAAW,OAAOc,EAAKN,EAAqBR,CAAI,CAAC,EAK9D,IAAMe,EAJUN,EAAS,SAAS,CAAC,CAChC,QAAQ,CAAC,CACT,QAAS,GAAM,CAAC,GAAGD,EAAqBK,CAAC,CAAC,CAEvB,CAAC,CAAC,QAIrB,EAAK,IACJG,EAAI,KAAK,SAASC,EAAI,IAAI,EAAID,EAAM,CAAE,KAAM,CAAC,GAAGA,EAAI,KAAMC,EAAI,IAAI,EAAG,QAAS,CAAC,GAAGD,EAAI,QAASC,CAAG,CAAE,EACtG,CAAE,KAAM,CAAC,EAAG,QAAS,CAAC,CAAE,CAC1B,EACA,OAAOH,EAAKC,EAAQ,OAAO,CAC7B,CACF,E"}
|
|
1
|
+
{"version":3,"file":"Platform.js","names":["execSync","fs","os","path","List","Option","Set","Try","hasDockerEnv","hasDockerCGroup","contents","matched","memo","fn","cache","cachedIsDocker","cachedIsKube","cachedIsWSL","version","cachedIsCI","\"CI\"","\"GITHUB_ACTIONS\"","\"GITLAB_CI\"","\"CIRCLECI\"","\"JENKINS_URL\"","\"TRAVIS\"","\"BUILDKITE\"","SYSTEM_ACCOUNTS","isSystemAccount","name","lower","isDirectory","p","isDir","readRealUsers","usersDir","entries","resolveViaCmdExe","fallback","parsed","raw","match","wslPath","cachedWindowsHome","realUsers","detectCloudProvider","scanDirectChildren","home","fullPath","detection","results","scanMacCloudStorage","cloudStoragePath","scanMacICloud","icloudPath","scanCloudStorageDirs","Platform","info","primary","windowsHome","h","deduped","acc","dir"],"sources":["../../src/platform/Platform.ts"],"sourcesContent":["import { execSync } from \"node:child_process\"\nimport * as fs from \"node:fs\"\nimport * as os from \"node:os\"\nimport * as path from \"node:path\"\n\nimport { List, Option, Set, Try } from \"functype\"\n\nexport type UserInfo = {\n readonly username: string\n readonly uid: number\n readonly gid: number\n readonly shell: Option<string>\n readonly homedir: string\n}\n\nexport type CloudProvider = \"onedrive\" | \"gdrive\" | \"dropbox\" | \"icloud\"\n\nexport type CloudStorageDir = {\n readonly provider: CloudProvider\n readonly path: string\n readonly label: string\n}\n\nconst hasDockerEnv = (): boolean => Try(() => fs.statSync(\"/.dockerenv\")).isSuccess()\n\nconst hasDockerCGroup = (): boolean =>\n Try(() => fs.readFileSync(\"/proc/self/cgroup\", \"utf8\"))\n .map((contents) => contents.includes(\"docker\"))\n .toEither((): boolean => false)\n .fold(\n () => false,\n (matched) => matched,\n )\n\nconst memo = <T>(fn: () => T): (() => T) => {\n const cache: { value?: T } = {}\n return () => {\n if (!(\"value\" in cache)) {\n cache.value = fn()\n }\n return cache.value as T\n }\n}\n\nconst cachedIsDocker = memo(() => hasDockerEnv() || hasDockerCGroup())\nconst cachedIsKube = memo(() =>\n Try(() => fs.readFileSync(\"/proc/self/cgroup\", \"utf8\"))\n .map((contents) => contents.includes(\"kube\"))\n .fold(\n () => false,\n (matched) => matched,\n ),\n)\nconst cachedIsWSL = memo(() =>\n Try(() => fs.readFileSync(\"/proc/version\", \"utf8\"))\n .map((version) => version.includes(\"Microsoft\") || version.includes(\"WSL\"))\n .fold(\n () => false,\n (matched) => matched,\n ),\n)\nconst cachedIsCI = memo(\n () =>\n process.env[\"CI\"] !== undefined ||\n process.env[\"GITHUB_ACTIONS\"] !== undefined ||\n process.env[\"GITLAB_CI\"] !== undefined ||\n process.env[\"CIRCLECI\"] !== undefined ||\n process.env[\"JENKINS_URL\"] !== undefined ||\n process.env[\"TRAVIS\"] !== undefined ||\n process.env[\"BUILDKITE\"] !== undefined,\n)\n\nconst SYSTEM_ACCOUNTS = Set.of(\"all users\", \"default\", \"default user\", \"public\")\n\nconst isSystemAccount = (name: string): boolean => {\n const lower = name.toLowerCase()\n if (SYSTEM_ACCOUNTS.contains(lower)) return true\n if (lower.startsWith(\"defaultuser\") || lower.startsWith(\"desktop.\") || lower.startsWith(\"wsiaccount\")) return true\n return false\n}\n\nconst isDirectory = (p: string): boolean =>\n Try(() => fs.statSync(p).isDirectory()).fold(\n () => false,\n (isDir) => isDir,\n )\n\nconst readRealUsers = (usersDir: string): Option<readonly string[]> => {\n const filterRealUsers = (entries: readonly string[]): readonly string[] =>\n entries.filter((name) => !isSystemAccount(name) && isDirectory(path.join(usersDir, name)))\n return Try(() => fs.readdirSync(usersDir))\n .map(filterRealUsers)\n .toOption()\n}\n\nconst resolveViaCmdExe = (usersDir: string, fallback: string): Option<string> => {\n // Convert Windows path C:\\Users\\foo → /mnt/c/Users/foo if it's a directory;\n // returns None for unparseable output or non-existent directories.\n const parseCmdOutput = (raw: string): Option<string> => {\n const match = raw.match(/^([A-Za-z]):\\\\(.*)$/)\n if (!match) return Option<string>(undefined)\n const drive = (match[1] as string).toLowerCase()\n const rest = (match[2] as string).replace(/\\\\/g, \"/\")\n const wslPath = `/mnt/${drive}/${rest}`\n return isDirectory(wslPath) ? Option(wslPath) : Option<string>(undefined)\n }\n const parsed = Try(() => execSync(\"cmd.exe /c echo %USERPROFILE%\", { timeout: 3000, encoding: \"utf8\" }).trim())\n .toOption()\n .flatMap(parseCmdOutput)\n .getOrElse(() => fallback)\n return Option(parsed)\n}\n\nconst resolveWindowsHome = (): Option<string> => {\n if (!cachedIsWSL()) return Option<string>(undefined)\n\n const usersDir = \"/mnt/c/Users\"\n return readRealUsers(usersDir).fold<Option<string>>(\n () => Option<string>(undefined),\n (realUsers) => {\n if (realUsers.length === 1) return Option(path.join(usersDir, realUsers[0] as string))\n if (realUsers.length > 1) return resolveViaCmdExe(usersDir, path.join(usersDir, realUsers[0] as string))\n return Option<string>(undefined)\n },\n )\n}\n\nconst cachedWindowsHome = memo(resolveWindowsHome)\n\ntype CloudDetection = { readonly provider: CloudProvider; readonly label: string }\n\nconst detectCloudProvider = (name: string): Option<CloudDetection> => {\n if (name === \"OneDrive\" || name.startsWith(\"OneDrive \") || name.startsWith(\"OneDrive-\")) {\n return Option({ provider: \"onedrive\" as const, label: name })\n }\n if (name === \"Google Drive\") return Option({ provider: \"gdrive\" as const, label: name })\n if (name === \"Dropbox\") return Option({ provider: \"dropbox\" as const, label: name })\n return Option<CloudDetection>(undefined)\n}\n\nconst scanDirectChildren = (home: string): readonly CloudStorageDir[] =>\n Try(() => fs.readdirSync(home))\n .map((entries) =>\n entries.flatMap((name): ReadonlyArray<CloudStorageDir> => {\n const fullPath = path.join(home, name)\n return detectCloudProvider(name).fold<ReadonlyArray<CloudStorageDir>>(\n () => [],\n (detection) =>\n isDirectory(fullPath) ? [{ provider: detection.provider, path: fullPath, label: detection.label }] : [],\n )\n }),\n )\n .fold<readonly CloudStorageDir[]>(\n () => [],\n (results) => results,\n )\n\nconst scanMacCloudStorage = (home: string): readonly CloudStorageDir[] => {\n const cloudStoragePath = path.join(home, \"Library\", \"CloudStorage\")\n return Try(() => fs.readdirSync(cloudStoragePath))\n .map((entries) =>\n entries.flatMap((name): ReadonlyArray<CloudStorageDir> => {\n const fullPath = path.join(cloudStoragePath, name)\n if (!isDirectory(fullPath)) return []\n if (name.startsWith(\"OneDrive\")) return [{ provider: \"onedrive\", path: fullPath, label: name }]\n if (name.startsWith(\"GoogleDrive\")) return [{ provider: \"gdrive\", path: fullPath, label: name }]\n return []\n }),\n )\n .fold<readonly CloudStorageDir[]>(\n () => [],\n (results) => results,\n )\n}\n\nconst scanMacICloud = (home: string): readonly CloudStorageDir[] => {\n const icloudPath = path.join(home, \"Library\", \"Mobile Documents\", \"com~apple~CloudDocs\")\n return isDirectory(icloudPath) ? [{ provider: \"icloud\", path: icloudPath, label: \"iCloud Drive\" }] : []\n}\n\nconst scanCloudStorageDirs = (home: string): readonly CloudStorageDir[] => [\n ...scanDirectChildren(home),\n ...scanMacCloudStorage(home),\n ...scanMacICloud(home),\n]\n\nexport const Platform = {\n os: (): \"darwin\" | \"linux\" | \"win32\" | string => process.platform,\n arch: (): string => process.arch,\n homeDir: (): string => os.homedir(),\n tmpDir: (): string => os.tmpdir(),\n hostname: (): string => os.hostname(),\n eol: (): string => os.EOL,\n pathSep: (): string => path.sep,\n\n isWindows: (): boolean => process.platform === \"win32\",\n isMac: (): boolean => process.platform === \"darwin\",\n isLinux: (): boolean => process.platform === \"linux\",\n\n userInfo: (): Option<UserInfo> => {\n const toUserInfo = (info: os.UserInfo<string>): UserInfo => ({\n username: info.username,\n uid: info.uid,\n gid: info.gid,\n shell: Option(info.shell),\n homedir: info.homedir,\n })\n return Try(() => os.userInfo())\n .map(toUserInfo)\n .toOption()\n },\n\n isDocker: (): boolean => cachedIsDocker(),\n isKubernetes: (): boolean => cachedIsKube(),\n isWSL: (): boolean => cachedIsWSL(),\n isCI: (): boolean => cachedIsCI(),\n\n isContainer: (): boolean => Platform.isDocker() || Platform.isKubernetes(),\n\n windowsHomeDir: (): Option<string> => cachedWindowsHome(),\n\n homeDirs: (): List<string> => {\n const primary = os.homedir()\n const windowsHome = Platform.windowsHomeDir().fold<readonly string[]>(\n () => [],\n (h) => (h !== primary ? [h] : []),\n )\n return List<string>([primary, ...windowsHome])\n },\n\n cloudStorageDirs: (home?: string): List<CloudStorageDir> => {\n if (home !== undefined) return List(scanCloudStorageDirs(home))\n const allDirs = Platform.homeDirs()\n .toArray()\n .flatMap((h) => [...scanCloudStorageDirs(h)])\n // Deduplicate by path, first-wins\n const deduped = allDirs.reduce<{\n readonly seen: ReadonlyArray<string>\n readonly results: ReadonlyArray<CloudStorageDir>\n }>(\n (acc, dir) =>\n acc.seen.includes(dir.path) ? acc : { seen: [...acc.seen, dir.path], results: [...acc.results, dir] },\n { seen: [], results: [] },\n )\n return List(deduped.results)\n },\n}\n"],"mappings":"A,4LAuBA,MAAMQ,MAA8BD,MAAUN,EAAG,SAAS,aAAa,CAAC,CAAC,CAAC,UAAU,EAE9EQ,MACJF,MAAUN,EAAG,aAAa,oBAAqB,MAAM,CAAC,CAAC,CACpD,IAAKS,GAAaA,EAAS,SAAS,QAAQ,CAAC,CAAC,CAC9C,aAAwB,EAAK,CAAC,CAC9B,SACO,GACLC,GAAYA,CACf,EAEEC,EAAWC,GAA2B,CAC1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QAASC,CAAG,CAAE,EACtG,CAAE,KAAM,CAAC,EAAG,QAAS,CAAC,CAAE,CAC1B,EACA,OAAO3D,EAAKyD,EAAQ,OAAO,CAC7B,CACF,E"}
|
package/dist/platform/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as UserInfo, n as CloudStorageDir, r as Platform, t as CloudProvider } from "../Platform-
|
|
1
|
+
import { i as UserInfo, n as CloudStorageDir, r as Platform, t as CloudProvider } from "../Platform-Drtg2_HB.js";
|
|
2
2
|
export { type CloudProvider, type CloudStorageDir, Platform, type UserInfo };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as Process, t as ExecResult } from "../Process-
|
|
1
|
+
import { n as Process, t as ExecResult } from "../Process-CkyuPYhy.js";
|
|
2
2
|
export { ExecResult, Process };
|
package/dist/process/Process.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{exec as e,execSync as t}from"node:child_process";import{IO as n,Left as r,Option as i,Right as a,Try as o}from"functype";import{ProcessError as s}from"../errors/errors.js";const c={exec:(t,o)=>n.fromPromiseEither(()=>new Promise(n=>{e(t,{timeout:o?.timeout,cwd:o?.cwd},(e,o,c)=>{if(e){let a=i(typeof e.code==`number`?e.code:void 0);n(r(s(t,a,String(c))))}else n(a({stdout:String(o),stderr:String(c),exitCode:0}))})}),e=>s(t,i(void 0),``,e instanceof Error?e.message:String(e))),execSync:(e,n)=>o(()=>t(e,{timeout:n?.timeout,cwd:n?.cwd,encoding:`utf8`,stdio:[`pipe`,`pipe`,`pipe`]})).toEither(t=>{if(t instanceof Error&&`status`in t&&`stderr`in t){let n=t;return s(e,i(n.status),String(n.stderr))}return s(e,i(void 0),``,t instanceof Error?t.message:String(t))}).map(e=>({stdout:String(e),stderr:``,exitCode:0}))};export{c as Process};
|
|
2
2
|
//# sourceMappingURL=Process.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Process.js","names":["nodeExecSync","
|
|
1
|
+
{"version":3,"file":"Process.js","names":["execCb","nodeExecSync","exec","execSync","IO","Left","Option","Right","Try","ProcessError","Process","command","options","resolve","error","stdout","stderr","exitCode","execError"],"sources":["../../src/process/Process.ts"],"sourcesContent":["import { exec as execCb, execSync as nodeExecSync } from \"node:child_process\"\n\nimport type { Either } from \"functype\"\nimport { IO, Left, Option, Right, Try } from \"functype\"\n\nimport { ProcessError } from \"../errors/errors\"\n\nexport type ExecResult = {\n readonly stdout: string\n readonly stderr: string\n readonly exitCode: number\n}\n\nexport const Process = {\n // Lazy: the command doesn't start until the IO runs.\n exec: (command: string, options?: { timeout?: number; cwd?: string }): IO<never, ProcessError, ExecResult> =>\n IO.fromPromiseEither(\n () =>\n new Promise<Either<ProcessError, ExecResult>>((resolve) => {\n execCb(command, { timeout: options?.timeout, cwd: options?.cwd }, (error, stdout, stderr) => {\n if (error) {\n // exec callback error has `code` as exit code (number) — distinct from Node errno `code` (string)\n const exitCode = Option(typeof error.code === \"number\" ? error.code : undefined)\n resolve(Left(ProcessError(command, exitCode, String(stderr))))\n } else {\n resolve(Right({ stdout: String(stdout), stderr: String(stderr), exitCode: 0 }))\n }\n })\n }),\n // exec can throw before the command starts, e.g. on a NUL byte in it. That's a failure of this\n // command, so it stays a typed Left, as in execSync, rather than a defect that rejects run().\n (error) =>\n ProcessError(command, Option<number>(undefined), \"\", error instanceof Error ? error.message : String(error)),\n ),\n\n execSync: (command: string, options?: { timeout?: number; cwd?: string }): Either<ProcessError, ExecResult> => {\n const buildProcessError = (error: unknown): ProcessError => {\n if (error instanceof Error && \"status\" in error && \"stderr\" in error) {\n const execError = error as Error & { status: number; stderr: string }\n return ProcessError(command, Option(execError.status), String(execError.stderr))\n }\n return ProcessError(\n command,\n Option<number>(undefined),\n \"\",\n error instanceof Error ? error.message : String(error),\n )\n }\n return Try(() =>\n nodeExecSync(command, {\n timeout: options?.timeout,\n cwd: options?.cwd,\n encoding: \"utf8\",\n stdio: [\"pipe\",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I,SAAU,CAAE,EAAE,CAExF,E"}
|
package/dist/process/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as Process, t as ExecResult } from "../Process-
|
|
1
|
+
import { n as Process, t as ExecResult } from "../Process-CkyuPYhy.js";
|
|
2
2
|
export { type ExecResult, Process };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "functype-os",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "Functional OS utilities using functype data structures — env vars, path expansion, file ops, platform detection",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"functype",
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@types/node": "^24.19.2",
|
|
30
30
|
"eslint-config-prettier": "^10.1.8",
|
|
31
|
-
"functype": "^2.
|
|
32
|
-
"ts-builds": "^
|
|
31
|
+
"functype": "^2.2.0",
|
|
32
|
+
"ts-builds": "^5.0.0",
|
|
33
33
|
"tsdown": "^0.23.7",
|
|
34
34
|
"vitest": "^5.1.0"
|
|
35
35
|
},
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|