@yaks/process 0.0.0-stage → 0.2.36

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 (111) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +249 -2
  3. package/_dist/clock.d.ts +5 -0
  4. package/_dist/clock.d.ts.map +1 -0
  5. package/_dist/command.d.ts +43 -0
  6. package/_dist/command.d.ts.map +1 -0
  7. package/_dist/comp.d.ts +49 -0
  8. package/_dist/comp.d.ts.map +1 -0
  9. package/_dist/env.d.ts +8 -0
  10. package/_dist/env.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +3 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/http.d.ts +11 -0
  14. package/_dist/http.d.ts.map +1 -0
  15. package/_dist/isolate.d.ts +11 -0
  16. package/_dist/isolate.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +49 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/modules.d.ts +31 -0
  20. package/_dist/modules.d.ts.map +1 -0
  21. package/_dist/platform.d.ts +7 -0
  22. package/_dist/platform.d.ts.map +1 -0
  23. package/_dist/plugin.d.ts +15 -0
  24. package/_dist/plugin.d.ts.map +1 -0
  25. package/_dist/run.d.ts +219 -0
  26. package/_dist/run.d.ts.map +1 -0
  27. package/_dist/self.d.ts +32 -0
  28. package/_dist/self.d.ts.map +1 -0
  29. package/_dist/socket.d.ts +11 -0
  30. package/_dist/socket.d.ts.map +1 -0
  31. package/_dist/store.d.ts +22 -0
  32. package/_dist/store.d.ts.map +1 -0
  33. package/_dist/system.d.ts +64 -0
  34. package/_dist/system.d.ts.map +1 -0
  35. package/_dist/trash.d.ts +6 -0
  36. package/_dist/trash.d.ts.map +1 -0
  37. package/_dist/views.d.ts +4 -0
  38. package/_dist/views.d.ts.map +1 -0
  39. package/_dist/vocab.d.ts +8 -0
  40. package/_dist/vocab.d.ts.map +1 -0
  41. package/_dist/wind.d.ts +35 -0
  42. package/_dist/wind.d.ts.map +1 -0
  43. package/clock.js +11 -0
  44. package/clock.js.map +1 -0
  45. package/clock.ts +11 -0
  46. package/command.js +172 -0
  47. package/command.js.map +1 -0
  48. package/command.ts +215 -0
  49. package/comp.js +54 -0
  50. package/comp.js.map +1 -0
  51. package/comp.ts +123 -0
  52. package/deno.json +1 -0
  53. package/detached.js +60 -0
  54. package/detached.js.map +1 -0
  55. package/detached.ts +92 -0
  56. package/detached_worker.ts +22 -0
  57. package/env.js +13 -0
  58. package/env.js.map +1 -0
  59. package/env.ts +24 -0
  60. package/graph.js +7 -0
  61. package/graph.js.map +1 -0
  62. package/graph.ts +8 -0
  63. package/http.js +158 -0
  64. package/http.js.map +1 -0
  65. package/http.ts +184 -0
  66. package/isolate.js +41 -0
  67. package/isolate.js.map +1 -0
  68. package/isolate.ts +52 -0
  69. package/mod.js +49 -0
  70. package/mod.js.map +1 -0
  71. package/mod.ts +50 -0
  72. package/modules.js +41 -0
  73. package/modules.js.map +1 -0
  74. package/modules.ts +69 -0
  75. package/package.json +81 -4
  76. package/platform.js +9 -0
  77. package/platform.js.map +1 -0
  78. package/platform.ts +9 -0
  79. package/plugin.js +27 -0
  80. package/plugin.js.map +1 -0
  81. package/plugin.ts +28 -0
  82. package/run.js +899 -0
  83. package/run.js.map +1 -0
  84. package/run.ts +1139 -0
  85. package/self.js +93 -0
  86. package/self.js.map +1 -0
  87. package/self.ts +144 -0
  88. package/socket.js +38 -0
  89. package/socket.js.map +1 -0
  90. package/socket.ts +49 -0
  91. package/store.js +30 -0
  92. package/store.js.map +1 -0
  93. package/store.ts +50 -0
  94. package/system.js +161 -0
  95. package/system.js.map +1 -0
  96. package/system.ts +216 -0
  97. package/testing.ts +39 -0
  98. package/tidy.ts +28 -0
  99. package/trash.js +117 -0
  100. package/trash.js.map +1 -0
  101. package/trash.ts +117 -0
  102. package/views.js +28 -0
  103. package/views.js.map +1 -0
  104. package/views.ts +30 -0
  105. package/vocab.js +16 -0
  106. package/vocab.js.map +1 -0
  107. package/vocab.json +154 -0
  108. package/vocab.ts +18 -0
  109. package/wind.js +88 -0
  110. package/wind.js.map +1 -0
  111. package/wind.ts +114 -0
package/system.ts ADDED
@@ -0,0 +1,216 @@
1
+ // This program's operating-system boundary. Callers do not depend on its runtime.
2
+ import process from 'node:process'
3
+ import { cpus, hostname as host, loadavg, release, uptime } from 'node:os'
4
+ import { format, inspect } from 'node:util'
5
+ import { readSync, writeSync } from 'node:fs'
6
+ import { Readable, Writable } from 'node:stream'
7
+ import { pathToFileURL } from 'node:url'
8
+ import { constants } from 'node:os'
9
+ export { type Env, env } from './env.js'
10
+ export { build, os } from './platform.js'
11
+
12
+ export { cpus, format, inspect, loadavg }
13
+ export {
14
+ clearInterval,
15
+ clearTimeout,
16
+ setInterval,
17
+ setTimeout,
18
+ } from 'node:timers'
19
+ export type Signal = NodeJS.Signals
20
+ export type {
21
+ ChildProcess,
22
+ CommandOptions,
23
+ CommandOutput,
24
+ CommandStatus,
25
+ } from './command.ts'
26
+ export let args: string[] = process.argv.slice(2)
27
+ export let pid = process.pid
28
+ export let ppid = process.ppid
29
+ export let cwd = (): string => process.cwd()
30
+ export let execPath = (): string => process.execPath
31
+ // Deno names a module run from a URL (`deno run jsr:…`) only as
32
+ // `Deno.mainModule`: its `process.argv[1]` is a placeholder file.
33
+ let deno = (globalThis as { Deno?: { mainModule: string } }).Deno
34
+ export let mainModule: string = deno?.mainModule ??
35
+ (process.argv[1] ? pathToFileURL(process.argv[1]).href : '')
36
+
37
+ // Deno tells a main module whose top-level await rejected as an unhandled
38
+ // rejection, the same way it tells a promise nobody held. Importing the main
39
+ // module after it failed rejects with that same reason; an import made while
40
+ // it still runs says nothing of how it ends, so each question imports anew. A
41
+ // Worker has no `Deno.mainModule`, and its `argv[1]` names the main thread's
42
+ // module, so a Worker never imports it.
43
+ let NONE = Symbol('none')
44
+
45
+ /** Whether `reason`, met as an unhandled rejection, is the main module's own
46
+ * failure (a top-level await that rejected) rather than a promise nobody
47
+ * held. Answers within `ms`. */
48
+ export let mainFailed = async (reason: unknown, ms = 50): Promise<boolean> => {
49
+ if (!deno?.mainModule) return false
50
+ let timer: ReturnType<typeof setTimeout> | undefined
51
+ let failure = await Promise.race([
52
+ import(deno.mainModule).then(() => NONE, (failure) => failure),
53
+ new Promise((done) => timer = setTimeout(done, ms, NONE)),
54
+ ])
55
+ clearTimeout(timer)
56
+ return failure !== NONE && failure === reason
57
+ }
58
+ export let version = { ...process.versions }
59
+ export let runtimeName = process.versions.deno ? 'deno' : 'node'
60
+ export let runtimeVersion = process.versions.deno ?? process.versions.node
61
+ export let osRelease = release
62
+ export let uid = (): number | null => process.getuid?.() ?? null
63
+ /** When this machine last started, in milliseconds since the epoch. */
64
+ export let booted = (): number => Date.now() - uptime() * 1000
65
+ /** What this machine calls itself. */
66
+ export let hostname = (): string => host()
67
+ export let exit = (code?: number): never => process.exit(code)
68
+ export let setExitCode = (code: number): void => {
69
+ process.exitCode = code
70
+ }
71
+ export let kill = (pid: number, signal: Signal | number = 'SIGTERM'): void => {
72
+ process.kill(pid, signal)
73
+ }
74
+ /** The parent's IPC channel closing, including before this listener starts.
75
+ * The channel is separate from stdin and is not inherited by grandchildren. */
76
+ export let disconnected = (
77
+ source: {
78
+ connected?: boolean
79
+ once: (event: 'disconnect', listener: () => void) => unknown
80
+ } = process,
81
+ ): Promise<void> =>
82
+ new Promise((resolve) =>
83
+ source.connected ? source.once('disconnect', resolve) : resolve()
84
+ )
85
+ export let addSignalListener = (signal: Signal, fn: () => void): void => {
86
+ process.on(signal, fn)
87
+ }
88
+ export let removeSignalListener = (signal: Signal, fn: () => void): void => {
89
+ process.off(signal, fn)
90
+ }
91
+ export let cpuUsage = process.cpuUsage
92
+ export let memoryUsage = (): NodeJS.MemoryUsage => process.memoryUsage()
93
+
94
+ // glibc keeps what a process frees resident, for its next allocations: a test
95
+ // runtime that closed hundreds of databases still held 280 MB of their pages.
96
+ // `malloc_trim` gives it back. Deno alone opens a library, and only glibc's
97
+ // libc has the call (musl's and macOS's do not), so elsewhere `trim` does
98
+ // nothing.
99
+ type Trims = { symbols: { malloc_trim: (pad: bigint) => number } }
100
+ let trims: Trims | null | undefined
101
+ let libc = (): Trims | null => {
102
+ let deno = (globalThis as unknown as {
103
+ Deno?: { dlopen: (path: string, symbols: object) => Trims }
104
+ }).Deno
105
+ if (!deno || process.platform != 'linux') return null
106
+ try {
107
+ return deno.dlopen('libc.so.6', {
108
+ malloc_trim: { parameters: ['usize'], result: 'i32' },
109
+ })
110
+ } catch {
111
+ // A libc that is not glibc's.
112
+ return null
113
+ }
114
+ }
115
+
116
+ /** Gives the memory this process freed back to the system, where it can. */
117
+ export let trim = (): void => {
118
+ ;(trims === undefined ? trims = libc() : trims)?.symbols.malloc_trim(0n)
119
+ }
120
+ export let signalCode = (signal: Signal | null): number =>
121
+ signal ? 128 + (constants.signals[signal] ?? 0) : 1
122
+ export let unrefTimer = (timer: unknown): void => {
123
+ if (
124
+ timer && typeof timer == 'object' && 'unref' in timer &&
125
+ typeof timer.unref == 'function'
126
+ ) timer.unref()
127
+ }
128
+ export type Input = {
129
+ isTerminal: () => boolean
130
+ setRaw: (raw: boolean, options?: { cbreak?: boolean }) => void
131
+ readable: ReadableStream<Uint8Array<ArrayBuffer>>
132
+ read: (buffer: Uint8Array, signal?: AbortSignal) => Promise<number | null>
133
+ readSync: (buffer: Uint8Array) => number | null
134
+ }
135
+ export type Output = {
136
+ isTerminal: () => boolean
137
+ writeSync: (buffer: Uint8Array) => number
138
+ write: (buffer: Uint8Array) => Promise<number>
139
+ writable: WritableStream<Uint8Array>
140
+ }
141
+ let input: ReadableStream<Uint8Array<ArrayBuffer>> | undefined
142
+ export let stdin: Input = {
143
+ isTerminal: () => !!process.stdin.isTTY,
144
+ setRaw: (raw: boolean, _options?: { cbreak?: boolean }) => {
145
+ process.stdin.setRawMode(raw)
146
+ },
147
+ get readable(): ReadableStream<Uint8Array<ArrayBuffer>> {
148
+ return input ??= Readable.toWeb(process.stdin) as ReadableStream<
149
+ Uint8Array<ArrayBuffer>
150
+ >
151
+ },
152
+ read: async (buffer, signal): Promise<number | null> => {
153
+ signal?.throwIfAborted()
154
+ let stream = process.stdin
155
+ let chunk: Buffer | null = stream.read(buffer.length)
156
+ if (!chunk) {
157
+ if (stream.readableEnded) return null
158
+ await new Promise<void>((resolve, reject) => {
159
+ let clear = () => {
160
+ stream.off('readable', ready)
161
+ stream.off('error', failed)
162
+ stream.off('end', ready)
163
+ signal?.removeEventListener('abort', aborted)
164
+ }
165
+ let ready = () => {
166
+ clear()
167
+ resolve()
168
+ }
169
+ let failed = (error: Error) => {
170
+ clear()
171
+ reject(error)
172
+ }
173
+ let aborted = () => {
174
+ clear()
175
+ reject(signal?.reason)
176
+ }
177
+ stream.once('readable', ready)
178
+ stream.once('error', failed)
179
+ stream.once('end', ready)
180
+ signal?.addEventListener('abort', aborted, { once: true })
181
+ })
182
+ signal?.throwIfAborted()
183
+ chunk = stream.read(buffer.length) ?? stream.read()
184
+ }
185
+ if (!chunk) return null
186
+ let count = Math.min(buffer.length, chunk.length)
187
+ buffer.set(chunk.subarray(0, count))
188
+ if (chunk.length > count) stream.unshift(chunk.subarray(count))
189
+ return count
190
+ },
191
+ readSync: (buffer: Uint8Array) =>
192
+ readSync(0, buffer, 0, buffer.length, null) || null,
193
+ }
194
+ let output = (
195
+ stream: typeof process.stdout | typeof process.stderr,
196
+ fd: number,
197
+ ): Output => ({
198
+ isTerminal: () => !!stream.isTTY,
199
+ writeSync: (buffer: Uint8Array) => writeSync(fd, buffer),
200
+ write: (buffer: Uint8Array): Promise<number> =>
201
+ new Promise((resolve, reject) => {
202
+ stream.write(
203
+ buffer,
204
+ (error) => error ? reject(error) : resolve(buffer.length),
205
+ )
206
+ }),
207
+ get writable(): WritableStream<Uint8Array> {
208
+ return Writable.toWeb(stream)
209
+ },
210
+ })
211
+ export let stdout: Output = output(process.stdout, 1)
212
+ export let stderr: Output = output(process.stderr, 2)
213
+ export let consoleSize = (): { columns: number; rows: number } => ({
214
+ columns: process.stdout.columns ?? 80,
215
+ rows: process.stdout.rows ?? 24,
216
+ })
package/testing.ts ADDED
@@ -0,0 +1,39 @@
1
+ // Shared test fixtures (not part of the published package — see deno.json).
2
+ //
3
+ // The store is @yaks/ram: a Map holding the bundles, with the same `apply()`
4
+ // and the same query grammar as a database, so a test needs no file and no
5
+ // schema. The vocabulary is this package's loaded beside @yaks/session's,
6
+ // because a service's `stop` is that package's component.
7
+
8
+ import { loadVocab, type Vocab } from 'jsr:@yaks/vocab@0.2.36'
9
+ import { type Graph, graph } from 'jsr:@yaks/graph@0.2.36'
10
+ import { ram } from 'jsr:@yaks/ram@0.2.36'
11
+ import { modelDoc } from 'jsr:@yaks/model@0.2.36'
12
+ import { sessionDoc } from 'jsr:@yaks/session@0.2.36'
13
+ import { toolsDoc } from 'jsr:@yaks/tools@0.2.36/vocab'
14
+ import { processDoc } from './comp.ts'
15
+ import { processes } from './plugin.ts'
16
+
17
+ /** This package's components, plus the session components a service's stop
18
+ * uses. */
19
+ export let host: Vocab = loadVocab([processDoc, sessionDoc, toolsDoc, modelDoc])
20
+
21
+ /** A graph over an empty store, with the process plugin on it. */
22
+ export let tracked = (): Graph =>
23
+ graph({ storage: ram(host), vocab: host, plugins: [processes()] })
24
+
25
+ /** Wait for a condition by polling it, never by guessing a duration. The
26
+ * timeout is only there so a failure fails instead of hanging. */
27
+ export let until = async <T>(
28
+ fact: () => T | Promise<T>,
29
+ label = 'it',
30
+ timeout = 5000,
31
+ ): Promise<T> => {
32
+ let deadline = Date.now() + timeout
33
+ while (true) {
34
+ let v = await fact()
35
+ if (v) return v
36
+ if (Date.now() >= deadline) throw new Error(`until: timed out on ${label}`)
37
+ await new Promise((go) => setTimeout(go, 5))
38
+ }
39
+ }
package/tidy.ts ADDED
@@ -0,0 +1,28 @@
1
+ // Machines share the process-file directory, even when each lend creates a new
2
+ // machine. Keep both the hourly throttle and in-flight sweep at that boundary.
3
+
4
+ import { resolve } from 'node:path/posix'
5
+ import { type Opts, paths, sweep } from './run.ts'
6
+ import type { Store } from './store.ts'
7
+
8
+ let HOUR = 60 * 60 * 1000
9
+ let DAY = 24 * HOUR
10
+
11
+ export let tidier = (run = sweep, now = Date.now) => {
12
+ let directories = new Map<string, { at: number; pending: boolean }>()
13
+ return (processes: Store, opts: Opts): void => {
14
+ let dir = resolve(paths('', opts).code, '..')
15
+ let prior = directories.get(dir)
16
+ if (prior && (prior.pending || now() - prior.at < HOUR)) return
17
+ let state = { at: now(), pending: true }
18
+ directories.set(dir, state)
19
+ run(DAY, { ...opts, dir }, processes)
20
+ .catch((e) => console.error('process sweep failed:', e))
21
+ .finally(() => {
22
+ state.at = now()
23
+ state.pending = false
24
+ })
25
+ }
26
+ }
27
+
28
+ export let tidy = tidier()
package/trash.js ADDED
@@ -0,0 +1,117 @@
1
+ // Recoverable filesystem removal at the host boundary. Each record keeps its
2
+ // original path and bytes; callers decide when data enters trash, never when
3
+ // time alone destroys it. Temporary source directories use durable trash too.
4
+ import * as fs from 'node:fs/promises';
5
+ import { constants } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { dirname, join, resolve } from 'node:path';
8
+ let missing = (error)=>error.code == 'ENOENT';
9
+ let transfer = async (from, to)=>{
10
+ try {
11
+ await fs.rename(from, to);
12
+ } catch (error) {
13
+ if (error.code != 'EXDEV') throw error;
14
+ await fs.cp(from, to, {
15
+ recursive: true,
16
+ preserveTimestamps: true,
17
+ dereference: false,
18
+ verbatimSymlinks: true,
19
+ errorOnExist: true,
20
+ force: false
21
+ });
22
+ await fs.rm(from, {
23
+ recursive: true
24
+ });
25
+ }
26
+ };
27
+ let copy = async (from, to, mode)=>{
28
+ await using input = await fs.open(from, 'r');
29
+ await using output = await fs.open(to, 'wx', mode);
30
+ let buffer = new Uint8Array(64 * 1024);
31
+ for(;;){
32
+ let { bytesRead } = await input.read(buffer);
33
+ if (!bytesRead) break;
34
+ for(let at = 0; at < bytesRead;){
35
+ let { bytesWritten } = await output.write(buffer, at, bytesRead - at);
36
+ at += bytesWritten;
37
+ }
38
+ }
39
+ };
40
+ // Each destination is claimed by an exclusive filesystem operation. A name
41
+ // becoming occupied between attempts cannot be overwritten by restoration.
42
+ let recover = async (from, to)=>{
43
+ let info = await fs.lstat(from);
44
+ if (info.isSymbolicLink()) await fs.symlink(await fs.readlink(from), to);
45
+ else if (info.isDirectory()) {
46
+ await fs.mkdir(to, {
47
+ mode: info.mode
48
+ });
49
+ await fs.cp(from, to, {
50
+ recursive: true,
51
+ preserveTimestamps: true,
52
+ dereference: false,
53
+ verbatimSymlinks: true,
54
+ errorOnExist: true,
55
+ force: false,
56
+ mode: constants.COPYFILE_EXCL
57
+ });
58
+ } else await copy(from, to, info.mode);
59
+ await fs.rm(from, {
60
+ recursive: true
61
+ });
62
+ };
63
+ /** Move a file or directory into private trash. Missing sources do nothing.
64
+ * `root` defaults to `~/.yak/trash/files`; a persistent store can keep its own
65
+ * trash beside its data. The returned record holds `source.json` and `data`. */ export let trash = async (path, root = join(homedir(), '.yak/trash/files'))=>{
66
+ path = resolve(path);
67
+ try {
68
+ await fs.lstat(path);
69
+ } catch (error) {
70
+ if (missing(error)) return undefined;
71
+ throw error;
72
+ }
73
+ let record = join(root, crypto.randomUUID());
74
+ await fs.mkdir(record, {
75
+ recursive: true,
76
+ mode: 0o700
77
+ });
78
+ await fs.writeFile(join(record, 'source.json'), JSON.stringify({
79
+ path,
80
+ at: Date.now()
81
+ }) + '\n', {
82
+ mode: 0o600,
83
+ flag: 'wx'
84
+ });
85
+ let to = join(record, 'data');
86
+ try {
87
+ await transfer(path, to);
88
+ } catch (error) {
89
+ if (missing(error)) return undefined;
90
+ throw error;
91
+ }
92
+ return record;
93
+ };
94
+ /** Restore a record, retaining a free name when its original path is taken.
95
+ * The answer is the restored path, so a caller can say where it went. */ export let restore = async (record)=>{
96
+ let source = JSON.parse(await fs.readFile(join(record, 'source.json'), 'utf8'));
97
+ let to = source.path;
98
+ await fs.mkdir(dirname(to), {
99
+ recursive: true
100
+ });
101
+ for(;;){
102
+ try {
103
+ await recover(join(record, 'data'), to);
104
+ break;
105
+ } catch (error) {
106
+ if (error.code != 'EEXIST') throw error;
107
+ to = `${source.path}.restored-${crypto.randomUUID()}`;
108
+ }
109
+ }
110
+ await fs.writeFile(join(record, 'restored.json'), JSON.stringify({
111
+ path: to
112
+ }) + '\n', {
113
+ mode: 0o600
114
+ });
115
+ return to;
116
+ };
117
+ //# sourceMappingURL=trash.js.map
package/trash.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trash.js","sources":["./trash.ts"],"names":[],"mappings":"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"}
package/trash.ts ADDED
@@ -0,0 +1,117 @@
1
+ // Recoverable filesystem removal at the host boundary. Each record keeps its
2
+ // original path and bytes; callers decide when data enters trash, never when
3
+ // time alone destroys it. Temporary source directories use durable trash too.
4
+ import * as fs from 'node:fs/promises'
5
+ import { constants } from 'node:fs'
6
+ import { homedir } from 'node:os'
7
+ import { dirname, join, resolve } from 'node:path'
8
+
9
+ let missing = (error: unknown) =>
10
+ (error as NodeJS.ErrnoException).code == 'ENOENT'
11
+
12
+ let transfer = async (from: string, to: string) => {
13
+ try {
14
+ await fs.rename(from, to)
15
+ } catch (error) {
16
+ if ((error as NodeJS.ErrnoException).code != 'EXDEV') throw error
17
+ await fs.cp(from, to, {
18
+ recursive: true,
19
+ preserveTimestamps: true,
20
+ dereference: false,
21
+ verbatimSymlinks: true,
22
+ errorOnExist: true,
23
+ force: false,
24
+ })
25
+ await fs.rm(from, { recursive: true })
26
+ }
27
+ }
28
+
29
+ let copy = async (from: string, to: string, mode: number) => {
30
+ await using input = await fs.open(from, 'r')
31
+ await using output = await fs.open(to, 'wx', mode)
32
+ let buffer = new Uint8Array(64 * 1024)
33
+ for (;;) {
34
+ let { bytesRead } = await input.read(buffer)
35
+ if (!bytesRead) break
36
+ for (let at = 0; at < bytesRead;) {
37
+ let { bytesWritten } = await output.write(buffer, at, bytesRead - at)
38
+ at += bytesWritten
39
+ }
40
+ }
41
+ }
42
+
43
+ // Each destination is claimed by an exclusive filesystem operation. A name
44
+ // becoming occupied between attempts cannot be overwritten by restoration.
45
+ let recover = async (from: string, to: string) => {
46
+ let info = await fs.lstat(from)
47
+ if (info.isSymbolicLink()) await fs.symlink(await fs.readlink(from), to)
48
+ else if (info.isDirectory()) {
49
+ await fs.mkdir(to, { mode: info.mode })
50
+ await fs.cp(from, to, {
51
+ recursive: true,
52
+ preserveTimestamps: true,
53
+ dereference: false,
54
+ verbatimSymlinks: true,
55
+ errorOnExist: true,
56
+ force: false,
57
+ mode: constants.COPYFILE_EXCL,
58
+ })
59
+ } else await copy(from, to, info.mode)
60
+ await fs.rm(from, { recursive: true })
61
+ }
62
+
63
+ /** Move a file or directory into private trash. Missing sources do nothing.
64
+ * `root` defaults to `~/.yak/trash/files`; a persistent store can keep its own
65
+ * trash beside its data. The returned record holds `source.json` and `data`. */
66
+ export let trash = async (
67
+ path: string,
68
+ root: string = join(homedir(), '.yak/trash/files'),
69
+ ): Promise<string | undefined> => {
70
+ path = resolve(path)
71
+ try {
72
+ await fs.lstat(path)
73
+ } catch (error) {
74
+ if (missing(error)) return undefined
75
+ throw error
76
+ }
77
+ let record = join(root, crypto.randomUUID())
78
+ await fs.mkdir(record, { recursive: true, mode: 0o700 })
79
+ await fs.writeFile(
80
+ join(record, 'source.json'),
81
+ JSON.stringify({ path, at: Date.now() }) + '\n',
82
+ { mode: 0o600, flag: 'wx' },
83
+ )
84
+ let to = join(record, 'data')
85
+ try {
86
+ await transfer(path, to)
87
+ } catch (error) {
88
+ if (missing(error)) return undefined
89
+ throw error
90
+ }
91
+ return record
92
+ }
93
+
94
+ /** Restore a record, retaining a free name when its original path is taken.
95
+ * The answer is the restored path, so a caller can say where it went. */
96
+ export let restore = async (record: string): Promise<string> => {
97
+ let source = JSON.parse(
98
+ await fs.readFile(join(record, 'source.json'), 'utf8'),
99
+ ) as { path: string }
100
+ let to = source.path
101
+ await fs.mkdir(dirname(to), { recursive: true })
102
+ for (;;) {
103
+ try {
104
+ await recover(join(record, 'data'), to)
105
+ break
106
+ } catch (error) {
107
+ if ((error as NodeJS.ErrnoException).code != 'EEXIST') throw error
108
+ to = `${source.path}.restored-${crypto.randomUUID()}`
109
+ }
110
+ }
111
+ await fs.writeFile(
112
+ join(record, 'restored.json'),
113
+ JSON.stringify({ path: to }) + '\n',
114
+ { mode: 0o600 },
115
+ )
116
+ return to
117
+ }
package/views.js ADDED
@@ -0,0 +1,28 @@
1
+ // How a process reads, in every interface: as the command it runs, the words a
2
+ // person typed to start it — `yak task new Buy the cake` — rather than its id.
3
+ // Its options stop the name: `yak serve --share --ready /run/…` reads as
4
+ // `yak serve`, and the whole line rides the tooltip. A process is what signs
5
+ // the writes it makes (./self.ts), so this is the name a write's author reads
6
+ // as wherever one is named. A portable @yaks/render renderer, so a terminal
7
+ // prints it and a browser mounts it.
8
+ import { parse } from "@yaks/query/core";
9
+ import { define } from "@yaks/render";
10
+ import { PROCESS } from "./comp.js";
11
+ /** A command's words before its first option. */ export let named = (command)=>{
12
+ let words = command.split(' ');
13
+ let first = words.findIndex((w, i)=>i > 0 && w.startsWith('-'));
14
+ return (first < 0 ? words : words.slice(0, first)).join(' ');
15
+ };
16
+ /** `Title` for a process that knows its command. */ export let views = define([
17
+ {
18
+ view: 'Title',
19
+ match: parse(`.${PROCESS}.command`),
20
+ render: (b, h)=>{
21
+ let command = String(b[PROCESS].command);
22
+ return h('span', {
23
+ title: command
24
+ }, named(command));
25
+ }
26
+ }
27
+ ]);
28
+ //# sourceMappingURL=views.js.map
package/views.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"views.js","sources":["./views.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,+EAA+E;AAC/E,yEAAyE;AACzE,6EAA6E;AAC7E,8EAA8E;AAC9E,4EAA4E;AAC5E,qCAAqC;AAErC,SAAS,KAAK,gCAAqC;AACnD,SAAS,MAAM,4BAAgD;AAC/D,SAAS,OAAO,oBAAmB;AAEnC,+CAA+C,GAC/C,OAAO,IAAI,QAAQ,CAAC;EAClB,IAAI,QAAQ,QAAQ,KAAK,CAAC;EAC1B,IAAI,QAAQ,MAAM,SAAS,CAAC,CAAC,GAAG,IAAM,IAAI,KAAK,EAAE,UAAU,CAAC;EAC5D,OAAO,CAAC,QAAQ,IAAI,QAAQ,MAAM,KAAK,CAAC,GAAG,MAAM,EAAE,IAAI,CAAC;AAC1D,EAAC;AAED,kDAAkD,GAClD,OAAO,IAAI,QAAkB,OAAO;EAClC;IACE,MAAM;IACN,OAAO,MAAM,CAAC,CAAC,EAAE,QAAQ,QAAQ,CAAC;IAClC,QAAQ,CAAC,GAAG;MACV,IAAI,UAAU,OAAO,AAAC,CAAC,CAAC,QAAQ,CAAyB,OAAO;MAChE,OAAO,EAAE,QAAQ;QAAE,OAAO;MAAQ,GAAG,MAAM;IAC7C;EACF;CACD,EAAC"}
package/views.ts ADDED
@@ -0,0 +1,30 @@
1
+ // How a process reads, in every interface: as the command it runs, the words a
2
+ // person typed to start it — `yak task new Buy the cake` — rather than its id.
3
+ // Its options stop the name: `yak serve --share --ready /run/…` reads as
4
+ // `yak serve`, and the whole line rides the tooltip. A process is what signs
5
+ // the writes it makes (./self.ts), so this is the name a write's author reads
6
+ // as wherever one is named. A portable @yaks/render renderer, so a terminal
7
+ // prints it and a browser mounts it.
8
+
9
+ import { parse } from '@yaks/query/core'
10
+ import { define, type Registry } from '@yaks/render'
11
+ import { PROCESS } from './comp.js'
12
+
13
+ /** A command's words before its first option. */
14
+ export let named = (command: string): string => {
15
+ let words = command.split(' ')
16
+ let first = words.findIndex((w, i) => i > 0 && w.startsWith('-'))
17
+ return (first < 0 ? words : words.slice(0, first)).join(' ')
18
+ }
19
+
20
+ /** `Title` for a process that knows its command. */
21
+ export let views: Registry = define([
22
+ {
23
+ view: 'Title',
24
+ match: parse(`.${PROCESS}.command`),
25
+ render: (b, h) => {
26
+ let command = String((b[PROCESS] as { command: string }).command)
27
+ return h('span', { title: command }, named(command))
28
+ },
29
+ },
30
+ ])
package/vocab.js ADDED
@@ -0,0 +1,16 @@
1
+ // The process components and nothing else, exported as `@yaks/process/vocab`
2
+ // for a caller that only needs to know the shape of the data. It imports no
3
+ // storage, no SQL and no runtime code, so a browser tab loading this
4
+ // vocabulary loads nothing else.
5
+ import { processDoc } from "./comp.js";
6
+ import manifest from './package.json' with {
7
+ type: 'json'
8
+ };
9
+ export { processDoc };
10
+ export { EXIT, PROCESS, RUNTIME, SERVICE } from "./comp.js";
11
+ /** What this package is: its manifest's description, the one place it is
12
+ * written, which a host stamps on each document here. */ export let description = manifest.description;
13
+ /** Every vocabulary document this plugin declares. */ export let docs = [
14
+ processDoc
15
+ ];
16
+ //# sourceMappingURL=vocab.js.map
package/vocab.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vocab.js","sources":["./vocab.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,4EAA4E;AAC5E,qEAAqE;AACrE,iCAAiC;AAGjC,SAAS,UAAU,oBAAmB;AACtC,OAAO,cAAc,sBAAsB;EAAE,MAAM;AAAO,EAAC;AAE3D,SAAS,UAAU,GAAE;AACrB,SAAS,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,oBAAmB;AAE3D;uDACuD,GACvD,OAAO,IAAI,cAAsB,SAAS,WAAW,CAAA;AAErD,oDAAoD,GACpD,OAAO,IAAI,OAAmB;EAAC;CAAW,CAAA"}