@zyro-sec/util 0.0.0-stage → 1.0.1

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.
Files changed (79) hide show
  1. package/docs/layer-node.md +155 -0
  2. package/package.json +68 -4
  3. package/script/build.ts +9 -0
  4. package/script/pack.ts +5 -0
  5. package/src/abort.test.ts +16 -0
  6. package/src/abort.ts +9 -0
  7. package/src/activity-calendar.test.ts +136 -0
  8. package/src/activity-calendar.ts +50 -0
  9. package/src/artifact.test.ts +29 -0
  10. package/src/artifact.ts +95 -0
  11. package/src/base64.test.ts +12 -0
  12. package/src/base64.ts +29 -0
  13. package/src/binary.test.ts +19 -0
  14. package/src/binary.ts +30 -0
  15. package/src/bom.test.ts +21 -0
  16. package/src/bom.ts +46 -0
  17. package/src/cross-spawn-spawner.ts +694 -0
  18. package/src/duration.ts +22 -0
  19. package/src/effect/app-node-platform.ts +40 -0
  20. package/src/effect/app-node.ts +14 -0
  21. package/src/effect/layer-node.ts +360 -0
  22. package/src/effect-flock.ts +313 -0
  23. package/src/encode.test.ts +32 -0
  24. package/src/encode.ts +39 -0
  25. package/src/execute-output.test.ts +36 -0
  26. package/src/execute-output.ts +23 -0
  27. package/src/flock.ts +346 -0
  28. package/src/fs-util.ts +271 -0
  29. package/src/glob.ts +38 -0
  30. package/src/global-roots.ts +19 -0
  31. package/src/global-roots.workerd.ts +16 -0
  32. package/src/global.ts +88 -0
  33. package/src/hash.ts +11 -0
  34. package/src/heap-snapshot.ts +44 -0
  35. package/src/no-timeout-fetch.test.ts +33 -0
  36. package/src/no-timeout-fetch.ts +5 -0
  37. package/src/npm-config.ts +41 -0
  38. package/src/npm.ts +557 -0
  39. package/src/observability/logging.ts +179 -0
  40. package/src/observability/otlp.ts +109 -0
  41. package/src/observability/shared.ts +8 -0
  42. package/src/observability.ts +60 -0
  43. package/src/open.test.ts +16 -0
  44. package/src/open.ts +12 -0
  45. package/src/patch.ts +382 -0
  46. package/src/path.test.ts +89 -0
  47. package/src/path.ts +149 -0
  48. package/src/process-signal.test.ts +38 -0
  49. package/src/process-signal.ts +23 -0
  50. package/src/process.ts +270 -0
  51. package/src/qr.ts +323 -0
  52. package/src/record.ts +3 -0
  53. package/src/retry.test.ts +87 -0
  54. package/src/retry.ts +51 -0
  55. package/src/runtime/import.bun.ts +10 -0
  56. package/src/runtime/import.node.ts +61 -0
  57. package/src/runtime/import.workerd.ts +9 -0
  58. package/src/runtime-import.ts +1 -0
  59. package/src/session-mention.test.ts +19 -0
  60. package/src/session-mention.ts +24 -0
  61. package/src/session-title-fallback.ts +36 -0
  62. package/src/session-turn.test.ts +131 -0
  63. package/src/session-turn.ts +82 -0
  64. package/src/teardown.ts +19 -0
  65. package/src/text-boundary.test.ts +39 -0
  66. package/src/text-boundary.ts +36 -0
  67. package/src/uuid.test.ts +80 -0
  68. package/src/uuid.ts +15 -0
  69. package/test/fixtures/qr.json +625 -0
  70. package/test/glob.test.ts +11 -0
  71. package/test/global-roots.test.ts +62 -0
  72. package/test/global.test.ts +99 -0
  73. package/test/observability-otlp.test.ts +45 -0
  74. package/test/qr.test.ts +113 -0
  75. package/test/session-title-fallback.test.ts +49 -0
  76. package/tsconfig.build.json +12 -0
  77. package/tsconfig.dist.json +10 -0
  78. package/tsconfig.json +14 -0
  79. package/README.md +0 -3
package/src/flock.ts ADDED
@@ -0,0 +1,346 @@
1
+ import path from "path"
2
+ import os from "os"
3
+ import { randomBytes, randomUUID } from "crypto"
4
+ import { mkdir, readFile, rm, stat, utimes, writeFile } from "fs/promises"
5
+ import { Hash } from "./hash.js"
6
+
7
+ export type FlockGlobal = {
8
+ state: string
9
+ }
10
+
11
+ export namespace Flock {
12
+ let global: FlockGlobal | undefined
13
+
14
+ export function setGlobal(g: FlockGlobal) {
15
+ global = g
16
+ }
17
+
18
+ const root = () => {
19
+ if (!global) throw new Error("Flock global not set")
20
+ return path.join(global.state, "locks")
21
+ }
22
+
23
+ // Defaults for callers that do not provide timing options.
24
+ const defaultOpts = {
25
+ staleMs: 60_000,
26
+ timeoutMs: 5 * 60_000,
27
+ baseDelayMs: 100,
28
+ maxDelayMs: 2_000,
29
+ }
30
+
31
+ export interface WaitEvent {
32
+ key: string
33
+ attempt: number
34
+ delay: number
35
+ waited: number
36
+ }
37
+
38
+ export type Wait = (input: WaitEvent) => void | Promise<void>
39
+
40
+ export interface Options {
41
+ dir?: string
42
+ signal?: AbortSignal
43
+ staleMs?: number
44
+ timeoutMs?: number
45
+ baseDelayMs?: number
46
+ maxDelayMs?: number
47
+ onWait?: Wait
48
+ }
49
+
50
+ type Opts = {
51
+ staleMs: number
52
+ timeoutMs: number
53
+ baseDelayMs: number
54
+ maxDelayMs: number
55
+ }
56
+
57
+ type Owned = {
58
+ acquired: true
59
+ startHeartbeat: (intervalMs?: number) => void
60
+ release: () => Promise<void>
61
+ }
62
+
63
+ export interface Lease {
64
+ release: () => Promise<void>
65
+ [Symbol.asyncDispose]: () => Promise<void>
66
+ }
67
+
68
+ function code(err: unknown) {
69
+ if (typeof err !== "object" || err === null || !("code" in err)) return
70
+ const value = err.code
71
+ if (typeof value !== "string") return
72
+ return value
73
+ }
74
+
75
+ function sleep(ms: number, signal?: AbortSignal) {
76
+ return new Promise<void>((resolve, reject) => {
77
+ if (signal?.aborted) {
78
+ reject(signal.reason ?? new Error("Aborted"))
79
+ return
80
+ }
81
+
82
+ let timer: NodeJS.Timeout | undefined
83
+
84
+ const done = () => {
85
+ signal?.removeEventListener("abort", abort)
86
+ resolve()
87
+ }
88
+
89
+ const abort = () => {
90
+ if (timer) {
91
+ clearTimeout(timer)
92
+ }
93
+ signal?.removeEventListener("abort", abort)
94
+ reject(signal?.reason ?? new Error("Aborted"))
95
+ }
96
+
97
+ signal?.addEventListener("abort", abort, { once: true })
98
+ timer = setTimeout(done, ms)
99
+ })
100
+ }
101
+
102
+ function jitter(ms: number) {
103
+ const j = Math.floor(ms * 0.3)
104
+ const d = Math.floor(Math.random() * (2 * j + 1)) - j
105
+ return Math.max(0, ms + d)
106
+ }
107
+
108
+ function mono() {
109
+ return performance.now()
110
+ }
111
+
112
+ function wall() {
113
+ return performance.timeOrigin + mono()
114
+ }
115
+
116
+ async function stats(file: string) {
117
+ try {
118
+ return await stat(file)
119
+ } catch (err) {
120
+ const errCode = code(err)
121
+ if (errCode === "ENOENT" || errCode === "ENOTDIR") return
122
+ throw err
123
+ }
124
+ }
125
+
126
+ async function stale(lockDir: string, heartbeatPath: string, metaPath: string, staleMs: number) {
127
+ // Stale detection allows automatic recovery after crashed owners.
128
+ const now = wall()
129
+ const heartbeat = await stats(heartbeatPath)
130
+ if (heartbeat) {
131
+ return now - heartbeat.mtimeMs > staleMs
132
+ }
133
+
134
+ const meta = await stats(metaPath)
135
+ if (meta) {
136
+ return now - meta.mtimeMs > staleMs
137
+ }
138
+
139
+ const dir = await stats(lockDir)
140
+ if (!dir) {
141
+ return false
142
+ }
143
+
144
+ return now - dir.mtimeMs > staleMs
145
+ }
146
+
147
+ async function tryAcquireLockDir(lockDir: string, opts: Opts): Promise<Owned | { acquired: false }> {
148
+ const token = randomUUID?.() ?? randomBytes(16).toString("hex")
149
+ const metaPath = path.join(lockDir, "meta.json")
150
+ const heartbeatPath = path.join(lockDir, "heartbeat")
151
+
152
+ try {
153
+ await mkdir(lockDir, { mode: 0o700 })
154
+ } catch (err) {
155
+ if (code(err) !== "EEXIST") {
156
+ throw err
157
+ }
158
+
159
+ if (!(await stale(lockDir, heartbeatPath, metaPath, opts.staleMs))) {
160
+ return { acquired: false }
161
+ }
162
+
163
+ const breakerPath = lockDir + ".breaker"
164
+ try {
165
+ await mkdir(breakerPath, { mode: 0o700 })
166
+ } catch (claimErr) {
167
+ const errCode = code(claimErr)
168
+ if (errCode === "EEXIST") {
169
+ const breaker = await stats(breakerPath)
170
+ if (breaker && wall() - breaker.mtimeMs > opts.staleMs) {
171
+ await rm(breakerPath, { recursive: true, force: true }).catch(() => undefined)
172
+ }
173
+ return { acquired: false }
174
+ }
175
+
176
+ if (errCode === "ENOENT" || errCode === "ENOTDIR") {
177
+ return { acquired: false }
178
+ }
179
+
180
+ throw claimErr
181
+ }
182
+
183
+ try {
184
+ // Breaker ownership ensures only one contender performs stale cleanup.
185
+ if (!(await stale(lockDir, heartbeatPath, metaPath, opts.staleMs))) {
186
+ return { acquired: false }
187
+ }
188
+
189
+ await rm(lockDir, { recursive: true, force: true })
190
+
191
+ try {
192
+ await mkdir(lockDir, { mode: 0o700 })
193
+ } catch (retryErr) {
194
+ const errCode = code(retryErr)
195
+ if (errCode === "EEXIST" || errCode === "ENOTEMPTY") {
196
+ return { acquired: false }
197
+ }
198
+ throw retryErr
199
+ }
200
+ } finally {
201
+ await rm(breakerPath, { recursive: true, force: true }).catch(() => undefined)
202
+ }
203
+ }
204
+
205
+ const meta = {
206
+ token,
207
+ pid: process.pid,
208
+ hostname: os.hostname(),
209
+ createdAt: new Date().toISOString(),
210
+ }
211
+
212
+ await writeFile(heartbeatPath, "", { flag: "wx" }).catch(async () => {
213
+ await rm(lockDir, { recursive: true, force: true })
214
+ throw new Error("Lock acquired but heartbeat already existed (possible compromise).")
215
+ })
216
+
217
+ await writeFile(metaPath, JSON.stringify(meta, null, 2), { flag: "wx" }).catch(async () => {
218
+ await rm(lockDir, { recursive: true, force: true })
219
+ throw new Error("Lock acquired but meta.json already existed (possible compromise).")
220
+ })
221
+
222
+ let timer: NodeJS.Timeout | undefined
223
+
224
+ const startHeartbeat = (intervalMs = Math.max(100, Math.floor(opts.staleMs / 3))) => {
225
+ if (timer) return
226
+ // Heartbeat prevents long critical sections from being evicted as stale.
227
+ timer = setInterval(() => {
228
+ const t = new Date()
229
+ void utimes(heartbeatPath, t, t).catch(() => undefined)
230
+ }, intervalMs)
231
+ timer.unref?.()
232
+ }
233
+
234
+ const release = async () => {
235
+ if (timer) {
236
+ clearInterval(timer)
237
+ timer = undefined
238
+ }
239
+
240
+ const current = await readFile(metaPath, "utf8")
241
+ .then((raw) => {
242
+ const parsed = JSON.parse(raw)
243
+ if (!parsed || typeof parsed !== "object") return {}
244
+ return {
245
+ token: "token" in parsed && typeof parsed.token === "string" ? parsed.token : undefined,
246
+ }
247
+ })
248
+ .catch((err) => {
249
+ const errCode = code(err)
250
+ if (errCode === "ENOENT" || errCode === "ENOTDIR") {
251
+ throw new Error("Refusing to release: lock is compromised (metadata missing).")
252
+ }
253
+ if (err instanceof SyntaxError) {
254
+ throw new Error("Refusing to release: lock is compromised (metadata invalid).")
255
+ }
256
+ throw err
257
+ })
258
+ // Token check prevents deleting a lock that was re-acquired by another process.
259
+ if (current.token !== token) {
260
+ throw new Error("Refusing to release: lock token mismatch (not the owner).")
261
+ }
262
+
263
+ await rm(lockDir, { recursive: true, force: true })
264
+ }
265
+
266
+ return {
267
+ acquired: true,
268
+ startHeartbeat,
269
+ release,
270
+ }
271
+ }
272
+
273
+ async function acquireLockDir(
274
+ lockDir: string,
275
+ input: { key: string; onWait?: Wait; signal?: AbortSignal },
276
+ opts: Opts,
277
+ ) {
278
+ const stop = mono() + opts.timeoutMs
279
+ let attempt = 0
280
+ let waited = 0
281
+ let delay = opts.baseDelayMs
282
+
283
+ while (true) {
284
+ input.signal?.throwIfAborted()
285
+
286
+ const res = await tryAcquireLockDir(lockDir, opts)
287
+ if (res.acquired) {
288
+ return res
289
+ }
290
+
291
+ if (mono() > stop) {
292
+ throw new Error(`Timed out waiting for lock: ${input.key}`)
293
+ }
294
+
295
+ attempt += 1
296
+ const ms = jitter(delay)
297
+ await input.onWait?.({
298
+ key: input.key,
299
+ attempt,
300
+ delay: ms,
301
+ waited,
302
+ })
303
+ await sleep(ms, input.signal)
304
+ waited += ms
305
+ delay = Math.min(opts.maxDelayMs, Math.floor(delay * 1.7))
306
+ }
307
+ }
308
+
309
+ export async function acquire(key: string, input: Options = {}): Promise<Lease> {
310
+ input.signal?.throwIfAborted()
311
+ const cfg: Opts = {
312
+ staleMs: input.staleMs ?? defaultOpts.staleMs,
313
+ timeoutMs: input.timeoutMs ?? defaultOpts.timeoutMs,
314
+ baseDelayMs: input.baseDelayMs ?? defaultOpts.baseDelayMs,
315
+ maxDelayMs: input.maxDelayMs ?? defaultOpts.maxDelayMs,
316
+ }
317
+ const dir = input.dir ?? root()
318
+
319
+ await mkdir(dir, { recursive: true })
320
+ const lockfile = path.join(dir, Hash.fast(key) + ".lock")
321
+ const lock = await acquireLockDir(
322
+ lockfile,
323
+ {
324
+ key,
325
+ onWait: input.onWait,
326
+ signal: input.signal,
327
+ },
328
+ cfg,
329
+ )
330
+ lock.startHeartbeat()
331
+
332
+ const release = () => lock.release()
333
+ return {
334
+ release,
335
+ [Symbol.asyncDispose]() {
336
+ return release()
337
+ },
338
+ }
339
+ }
340
+
341
+ export async function withLock<T>(key: string, fn: () => Promise<T>, input: Options = {}) {
342
+ await using _ = await acquire(key, input)
343
+ input.signal?.throwIfAborted()
344
+ return await fn()
345
+ }
346
+ }
package/src/fs-util.ts ADDED
@@ -0,0 +1,271 @@
1
+ import path, { dirname, join, type PlatformPath } from "path"
2
+ import { realpathSync } from "fs"
3
+ import { lookup } from "mime-types"
4
+ import { Context, Effect, FileSystem, Layer, Schema } from "effect"
5
+ import type { PlatformError } from "effect/PlatformError"
6
+ import { Glob } from "./glob.js"
7
+ import { makeGlobalNode } from "./effect/app-node.js"
8
+ import { filesystem } from "./effect/app-node-platform.js"
9
+ import { sameDirectory } from "./path.js"
10
+
11
+ export namespace FSUtil {
12
+ export class FileSystemError extends Schema.TaggedError<FileSystemError>()("FileSystemError", {
13
+ method: Schema.String,
14
+ cause: Schema.optional(Schema.Defect()),
15
+ }) {
16
+ override get message() {
17
+ const detail = this.cause instanceof Error ? this.cause.message : this.cause && String(this.cause)
18
+ return `Filesystem operation failed: ${this.method}${detail ? `: ${detail}` : ""}`
19
+ }
20
+ }
21
+
22
+ export type Error = PlatformError | FileSystemError
23
+
24
+ export interface UpOptions {
25
+ readonly targets: string[]
26
+ readonly start: string
27
+ readonly stop?: string
28
+ readonly mode?: "all" | "first"
29
+ /** Only match regular files or directories (following symlinks). By default any existing path matches. */
30
+ readonly type?: "file" | "directory"
31
+ }
32
+
33
+ export interface Interface extends FileSystem.FileSystem {
34
+ readonly isDir: (path: string) => Effect.Effect<boolean>
35
+ readonly isFile: (path: string) => Effect.Effect<boolean>
36
+ readonly existsSafe: (path: string) => Effect.Effect<boolean>
37
+ readonly readFileStringSafe: (path: string) => Effect.Effect<string | undefined, Error>
38
+ readonly readJson: (path: string) => Effect.Effect<unknown, Error>
39
+ readonly writeJson: (path: string, data: unknown, mode?: number) => Effect.Effect<void, Error>
40
+ readonly ensureDir: (path: string) => Effect.Effect<void, Error>
41
+ readonly writeWithDirs: (path: string, content: string | Uint8Array, mode?: number) => Effect.Effect<void, Error>
42
+ readonly resolve: (path: string) => Effect.Effect<string>
43
+ readonly findUp: (target: string, start: string, stop?: string) => Effect.Effect<string[], Error>
44
+ readonly up: (options: UpOptions) => Effect.Effect<string[], Error>
45
+ readonly globUp: (pattern: string, start: string, stop?: string) => Effect.Effect<string[], Error>
46
+ readonly scan: (pattern: string, options?: Glob.Options) => Effect.Effect<string[], Error>
47
+ readonly globMatch: (pattern: string, filepath: string) => boolean
48
+ }
49
+
50
+ export class Service extends Context.Service<Service, Interface>()("@zyro-sec/FSUtil") {}
51
+
52
+ // Exported so simulation can wrap this layer and override the methods that
53
+ // bypass the injected FileSystem (scan, globUp).
54
+ export const layer = Layer.effect(
55
+ Service,
56
+ Effect.gen(function* () {
57
+ const fs = yield* FileSystem.FileSystem
58
+
59
+ const existsSafe = Effect.fn("FileSystem.existsSafe")(function* (path: string) {
60
+ return yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false))
61
+ })
62
+
63
+ const readFileStringSafe = Effect.fn("FileSystem.readFileStringSafe")(function* (path: string) {
64
+ return yield* fs.readFileString(path).pipe(
65
+ Effect.catchIf(
66
+ (error) => error.reason._tag === "NotFound" || isAccessDenied(error),
67
+ () => Effect.undefined,
68
+ ),
69
+ )
70
+ })
71
+
72
+ const isDir = Effect.fn("FileSystem.isDir")(function* (path: string) {
73
+ const info = yield* fs.stat(path).pipe(Effect.catch(() => Effect.void))
74
+ return info?.type === "Directory"
75
+ })
76
+
77
+ const isFile = Effect.fn("FileSystem.isFile")(function* (path: string) {
78
+ const info = yield* fs.stat(path).pipe(Effect.catch(() => Effect.void))
79
+ return info?.type === "File"
80
+ })
81
+
82
+ const resolve = Effect.fnUntraced(function* (input: string) {
83
+ const resolved = path.resolve(windowsPath(input))
84
+ // Sandboxes deny reads outside granted paths; canonicalize what we can see.
85
+ return yield* fs.realPath(resolved).pipe(
86
+ Effect.map((real) =>
87
+ process.platform === "win32" && real.toLowerCase() === resolved.toLowerCase() ? resolved : real,
88
+ ),
89
+ Effect.catchIf(
90
+ (error) => error.reason._tag === "NotFound" || isAccessDenied(error),
91
+ () => Effect.succeed(resolved),
92
+ ),
93
+ Effect.orDie,
94
+ )
95
+ })
96
+
97
+ const readJson = Effect.fn("FileSystem.readJson")(function* (path: string) {
98
+ const text = yield* fs.readFileString(path)
99
+ return yield* Effect.try({
100
+ try: () => JSON.parse(text),
101
+ catch: (cause) => new FileSystemError({ method: "readJson", cause }),
102
+ })
103
+ })
104
+
105
+ const writeJson = Effect.fn("FileSystem.writeJson")(function* (path: string, data: unknown, mode?: number) {
106
+ const content = JSON.stringify(data, null, 2)
107
+ yield* fs.writeFileString(path, content)
108
+ if (mode) yield* fs.chmod(path, mode)
109
+ })
110
+
111
+ const ensureDir = Effect.fn("FileSystem.ensureDir")(function* (path: string) {
112
+ yield* fs.makeDirectory(path, { recursive: true }).pipe(
113
+ // Bun on Windows can throw EEXIST here despite recursive mode.
114
+ // https://github.com/oven-sh/bun/issues/21901
115
+ Effect.catchIf(
116
+ (error) => error.reason._tag === "AlreadyExists",
117
+ (error) => isDir(path).pipe(Effect.flatMap((exists) => (exists ? Effect.void : Effect.fail(error)))),
118
+ ),
119
+ )
120
+ })
121
+
122
+ const writeWithDirs = Effect.fn("FileSystem.writeWithDirs")(function* (
123
+ path: string,
124
+ content: string | Uint8Array,
125
+ mode?: number,
126
+ ) {
127
+ const write = typeof content === "string" ? fs.writeFileString(path, content) : fs.writeFile(path, content)
128
+
129
+ yield* write.pipe(
130
+ Effect.catchIf(
131
+ (e) => e.reason._tag === "NotFound",
132
+ () =>
133
+ Effect.gen(function* () {
134
+ yield* fs.makeDirectory(dirname(path), { recursive: true })
135
+ yield* write
136
+ }),
137
+ ),
138
+ )
139
+ if (mode) yield* fs.chmod(path, mode)
140
+ })
141
+
142
+ const scan = Effect.fn("FileSystem.scan")(function* (pattern: string, options?: Glob.Options) {
143
+ return yield* Effect.tryPromise({
144
+ try: () => Glob.scan(pattern, options),
145
+ catch: (cause) => new FileSystemError({ method: "glob", cause }),
146
+ })
147
+ })
148
+
149
+ const up = Effect.fn("FileSystem.up")(function* (options: UpOptions) {
150
+ const result: string[] = []
151
+ let current = options.start
152
+ while (true) {
153
+ for (const target of options.targets) {
154
+ const search = join(current, target)
155
+ const found =
156
+ options.type === "file"
157
+ ? yield* isFile(search)
158
+ : options.type === "directory"
159
+ ? yield* isDir(search)
160
+ : yield* fs.exists(search)
161
+ if (found) {
162
+ result.push(search)
163
+ if (options.mode === "first") return result
164
+ }
165
+ }
166
+ if (options.stop && sameDirectory(options.stop, current)) break
167
+ const parent = dirname(current)
168
+ if (parent === current) break
169
+ current = parent
170
+ }
171
+ return result
172
+ })
173
+
174
+ const findUp = Effect.fn("FileSystem.findUp")((target: string, start: string, stop?: string) =>
175
+ up({ targets: [target], start, stop }),
176
+ )
177
+
178
+ const globUp = Effect.fn("FileSystem.globUp")(function* (pattern: string, start: string, stop?: string) {
179
+ const result: string[] = []
180
+ let current = start
181
+ while (true) {
182
+ const matches = yield* scan(pattern, { cwd: current, absolute: true, include: "file", dot: true }).pipe(
183
+ Effect.orElseSucceed(() => [] as string[]),
184
+ )
185
+ result.push(...matches)
186
+ if (stop && sameDirectory(stop, current)) break
187
+ const parent = dirname(current)
188
+ if (parent === current) break
189
+ current = parent
190
+ }
191
+ return result
192
+ })
193
+
194
+ return Service.of({
195
+ ...fs,
196
+ existsSafe,
197
+ readFileStringSafe,
198
+ isDir,
199
+ isFile,
200
+ resolve,
201
+ readJson,
202
+ writeJson,
203
+ ensureDir,
204
+ writeWithDirs,
205
+ findUp,
206
+ up,
207
+ globUp,
208
+ scan,
209
+ globMatch: Glob.match,
210
+ })
211
+ }),
212
+ )
213
+
214
+ export const node = makeGlobalNode({ service: Service, layer: layer, deps: [filesystem] })
215
+
216
+ /** Permission denial, including macOS sandbox and privacy denials that surface as Unknown with an EPERM cause. */
217
+ export function isAccessDenied(error: PlatformError) {
218
+ if (error.reason._tag === "PermissionDenied") return true
219
+ const cause = error.reason.cause
220
+ return (
221
+ error.reason._tag === "Unknown" && cause instanceof globalThis.Error && "code" in cause && cause.code === "EPERM"
222
+ )
223
+ }
224
+
225
+ // Pure helpers that don't need Effect (path manipulation, sync operations)
226
+ export function mimeType(p: string): string {
227
+ return lookup(p) || "application/octet-stream"
228
+ }
229
+
230
+ export function normalizePath(p: string): string {
231
+ if (process.platform !== "win32") return p
232
+ const resolved = path.resolve(windowsPath(p))
233
+ try {
234
+ return realpathSync.native(resolved)
235
+ } catch {
236
+ return resolved
237
+ }
238
+ }
239
+
240
+ export function resolve(p: string): string {
241
+ const resolved = path.resolve(windowsPath(p))
242
+ try {
243
+ return normalizePath(realpathSync(resolved))
244
+ } catch (e: any) {
245
+ if (["ENOENT", "ENOTDIR", "EPERM", "EACCES"].includes(e?.code)) return normalizePath(resolved)
246
+ throw e
247
+ }
248
+ }
249
+
250
+ export function windowsPath(p: string): string {
251
+ if (process.platform !== "win32") return p
252
+ return p
253
+ .replace(/^\/([a-zA-Z]):(?:[\\/]|$)/, (_, drive) => `${drive.toUpperCase()}:/`)
254
+ .replace(/^\/([a-zA-Z])(?:\/|$)/, (_, drive) => `${drive.toUpperCase()}:/`)
255
+ .replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/, (_, drive) => `${drive.toUpperCase()}:/`)
256
+ .replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/, (_, drive) => `${drive.toUpperCase()}:/`)
257
+ }
258
+
259
+ export const ignoredDirectories = ["node_modules", ".git", ".venv", "venv", "__pycache__"]
260
+
261
+ export const ignoreGlobs = [...ignoredDirectories, `**/{${ignoredDirectories.join(",")}}/**`]
262
+
263
+ export function overlaps(a: string, b: string) {
264
+ return contains(a, b) || contains(b, a)
265
+ }
266
+
267
+ export function contains(parent: string, child: string, platform: PlatformPath = path) {
268
+ const result = platform.relative(parent, child)
269
+ return result === "" || (!platform.isAbsolute(result) && result !== ".." && !result.startsWith(`..${platform.sep}`))
270
+ }
271
+ }
package/src/glob.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { glob, type GlobOptionsWithFileTypesFalse } from "glob"
2
+ import { Minimatch, minimatch } from "minimatch"
3
+
4
+ export namespace Glob {
5
+ export interface Options {
6
+ cwd?: string
7
+ absolute?: boolean
8
+ include?: "file" | "all"
9
+ dot?: boolean
10
+ symlink?: boolean
11
+ ignore?: string[]
12
+ }
13
+
14
+ function toGlobOptions(options: Options): GlobOptionsWithFileTypesFalse {
15
+ return {
16
+ cwd: options.cwd,
17
+ absolute: options.absolute,
18
+ dot: options.dot,
19
+ follow: options.symlink ?? false,
20
+ nodir: options.include !== "all",
21
+ ignore: options.ignore,
22
+ }
23
+ }
24
+
25
+ export async function scan(pattern: string, options: Options = {}): Promise<string[]> {
26
+ return glob(pattern, toGlobOptions(options))
27
+ }
28
+
29
+ export function match(pattern: string, filepath: string, options: { dot?: boolean } = {}): boolean {
30
+ return minimatch(filepath, pattern, { dot: options.dot ?? true })
31
+ }
32
+
33
+ /** `match` for one pattern, compiled on first use and reused for every later path. */
34
+ export function matcher(pattern: string, options: { dot?: boolean } = {}): (filepath: string) => boolean {
35
+ let compiled: Minimatch | undefined
36
+ return (filepath) => (compiled ??= new Minimatch(pattern, { dot: options.dot ?? true })).match(filepath)
37
+ }
38
+ }
@@ -0,0 +1,19 @@
1
+ import os from "os"
2
+ import path from "path"
3
+
4
+ const home = os.homedir()
5
+ const data = process.env.XDG_DATA_HOME || (home ? path.join(home, ".local", "share") : undefined)
6
+ const cache = process.env.XDG_CACHE_HOME || (home ? path.join(home, ".cache") : undefined)
7
+ const config = process.env.XDG_CONFIG_HOME || (home ? path.join(home, ".config") : undefined)
8
+ const state = process.env.XDG_STATE_HOME || (home ? path.join(home, ".local", "state") : undefined)
9
+
10
+ /** The XDG base directories that root Zyro Sec's global paths. */
11
+ export function roots(app: string) {
12
+ return {
13
+ data: path.join(data!, app),
14
+ cache: path.join(cache!, app),
15
+ config: path.join(config!, app),
16
+ state: path.join(state!, app),
17
+ tmp: path.join(os.tmpdir(), app),
18
+ }
19
+ }
@@ -0,0 +1,16 @@
1
+ import os from "os"
2
+ import path from "path"
3
+
4
+ // workerd has no home directory or XDG base dirs and only tmp is writable, so
5
+ // every global path roots under one directory there. Nothing durable lives in
6
+ // these: on workerd the database is on Durable Object storage.
7
+ export function roots(app: string) {
8
+ const root = path.join(os.tmpdir(), app)
9
+ return {
10
+ data: path.join(root, "data"),
11
+ cache: path.join(root, "cache"),
12
+ config: path.join(root, "config"),
13
+ state: path.join(root, "state"),
14
+ tmp: path.join(root, "tmp"),
15
+ }
16
+ }