@codeworksh/cli 0.1.0-dev.20261007133227 → 0.1.0-dev.20261012131434
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/README.md +5 -5
- package/{acp-DK_xXx9y.mjs → acp-BHv2HR2W.mjs} +5 -5
- package/acp-BHv2HR2W.mjs.map +1 -0
- package/{add-B9gIgFb3.mjs → add-DlwSE-gO.mjs} +4 -4
- package/{add-B9gIgFb3.mjs.map → add-DlwSE-gO.mjs.map} +1 -1
- package/{catalog-D5BxyTfH.mjs → catalog-BDSnGfE_.mjs} +2 -2
- package/{catalog-D5BxyTfH.mjs.map → catalog-BDSnGfE_.mjs.map} +1 -1
- package/{check-B9PJ6rn_.mjs → check-CpZTFCDq.mjs} +4 -4
- package/{check-B9PJ6rn_.mjs.map → check-CpZTFCDq.mjs.map} +1 -1
- package/{entries-CzgqHfKQ.mjs → entries-8LFGwy4n.mjs} +3 -3
- package/{entries-CzgqHfKQ.mjs.map → entries-8LFGwy4n.mjs.map} +1 -1
- package/{error-C9ACQhhu.mjs → error-CzUxh0Q9.mjs} +23 -3
- package/error-CzUxh0Q9.mjs.map +1 -0
- package/identity-B3FOHqbf.mjs +89 -0
- package/identity-B3FOHqbf.mjs.map +1 -0
- package/index.mjs +26 -19
- package/index.mjs.map +1 -1
- package/{install-Cw6h6IRB.mjs → install-CNWMNyaf.mjs} +4 -4
- package/{install-Cw6h6IRB.mjs.map → install-CNWMNyaf.mjs.map} +1 -1
- package/{link-B7iVolAn.mjs → link-oTpS3aUc.mjs} +3 -3
- package/{link-B7iVolAn.mjs.map → link-oTpS3aUc.mjs.map} +1 -1
- package/{list-BAonMfru.mjs → list-CmHTTB8Z.mjs} +4 -4
- package/{list-BAonMfru.mjs.map → list-CmHTTB8Z.mjs.map} +1 -1
- package/{list-3hYMW1Wo.mjs → list-DhdnHHJ5.mjs} +4 -4
- package/{list-3hYMW1Wo.mjs.map → list-DhdnHHJ5.mjs.map} +1 -1
- package/{login-CXelgTth.mjs → login-DPJbdjAY.mjs} +4 -4
- package/{login-CXelgTth.mjs.map → login-DPJbdjAY.mjs.map} +1 -1
- package/{logout-DrQQPxEW.mjs → logout-CL5CN_af.mjs} +4 -4
- package/{logout-DrQQPxEW.mjs.map → logout-CL5CN_af.mjs.map} +1 -1
- package/package.json +4 -3
- package/{providers-DksUoT4Z.mjs → providers-Dg8UlU_O.mjs} +4 -4
- package/{providers-DksUoT4Z.mjs.map → providers-Dg8UlU_O.mjs.map} +1 -1
- package/{refresh-DPBpboO0.mjs → refresh-OsgI6DYK.mjs} +4 -4
- package/{refresh-DPBpboO0.mjs.map → refresh-OsgI6DYK.mjs.map} +1 -1
- package/{refresh-CHBg5ya9.mjs → refresh-TK948P0j.mjs} +4 -4
- package/{refresh-CHBg5ya9.mjs.map → refresh-TK948P0j.mjs.map} +1 -1
- package/{reload-DDsh7kFG.mjs → reload-_hDmESKE.mjs} +3 -3
- package/{reload-DDsh7kFG.mjs.map → reload-_hDmESKE.mjs.map} +1 -1
- package/{remove-__JfeHO-.mjs → remove-DjBJe09T.mjs} +4 -4
- package/{remove-__JfeHO-.mjs.map → remove-DjBJe09T.mjs.map} +1 -1
- package/restart-CqAQCig7.mjs +21 -0
- package/restart-CqAQCig7.mjs.map +1 -0
- package/{run-D47jXr5Q.mjs → run-BpiW8Wxp.mjs} +3 -3
- package/{run-D47jXr5Q.mjs.map → run-BpiW8Wxp.mjs.map} +1 -1
- package/{runtime-D4zyJPrh.mjs → runtime-CIBm_3RX.mjs} +44 -5
- package/runtime-CIBm_3RX.mjs.map +1 -0
- package/{serve-gOODO9pv.mjs → serve-RFw_BCHm.mjs} +52 -19
- package/serve-RFw_BCHm.mjs.map +1 -0
- package/service-7_FrDOGJ.mjs +222 -0
- package/service-7_FrDOGJ.mjs.map +1 -0
- package/{settings-DDkmAxW5.mjs → settings-BM_gw7Fm.mjs} +2 -2
- package/{settings-DDkmAxW5.mjs.map → settings-BM_gw7Fm.mjs.map} +1 -1
- package/{shared-DFB2--6V.mjs → shared-DjyUhNsi.mjs} +3 -3
- package/{shared-DFB2--6V.mjs.map → shared-DjyUhNsi.mjs.map} +1 -1
- package/start-DcvqAhc4.mjs +20 -0
- package/start-DcvqAhc4.mjs.map +1 -0
- package/status-9o_2AAAv.mjs +14 -0
- package/status-9o_2AAAv.mjs.map +1 -0
- package/{status-BNc5JZ1C.mjs → status-BTCqpq7x.mjs} +4 -4
- package/{status-BNc5JZ1C.mjs.map → status-BTCqpq7x.mjs.map} +1 -1
- package/stop-De_XWxXw.mjs +13 -0
- package/stop-De_XWxXw.mjs.map +1 -0
- package/tui-B5RAnvTr.mjs +76 -0
- package/tui-B5RAnvTr.mjs.map +1 -0
- package/{update-CaW7oDOl.mjs → update-6Fn2_4fJ.mjs} +4 -4
- package/{update-CaW7oDOl.mjs.map → update-6Fn2_4fJ.mjs.map} +1 -1
- package/acp-DK_xXx9y.mjs.map +0 -1
- package/error-C9ACQhhu.mjs.map +0 -1
- package/runtime-D4zyJPrh.mjs.map +0 -1
- package/serve-gOODO9pv.mjs.map +0 -1
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { f as layer, p as make } from "./error-CzUxh0Q9.mjs";
|
|
2
|
+
import { a as file, i as command, n as current, o as infoJson, s as log } from "./identity-B3FOHqbf.mjs";
|
|
3
|
+
import { Effect, FileSystem, Layer, Option, Ref, Schedule, Schema } from "effect";
|
|
4
|
+
import { Global } from "@codeworksh/harness/effect";
|
|
5
|
+
import { ChildProcess, ChildProcessSpawner } from "effect/process";
|
|
6
|
+
//#region src/server/health.ts
|
|
7
|
+
/**
|
|
8
|
+
* One `server.info` call, with the answer normalized to `undefined` for every
|
|
9
|
+
* way a server can fail to answer: unreachable, slow, or speaking a different
|
|
10
|
+
* protocol. A health check that throws where it should say "no" would make
|
|
11
|
+
* every caller wrap it in a catch.
|
|
12
|
+
*/
|
|
13
|
+
const probe = (url) => Effect.gen(function* () {
|
|
14
|
+
const context = yield* Layer.build(layer(url)).pipe(Effect.orElseSucceed(() => void 0));
|
|
15
|
+
if (context === void 0) return void 0;
|
|
16
|
+
return yield* Effect.gen(function* () {
|
|
17
|
+
return yield* (yield* make)["server.info"]({}).pipe(Effect.timeout("1 second"));
|
|
18
|
+
}).pipe(Effect.provideContext(context), Effect.orElseSucceed(() => void 0));
|
|
19
|
+
}).pipe(Effect.scoped);
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/server/discovery.ts
|
|
22
|
+
/** A managed server could not be produced, in the words the CLI prints. */
|
|
23
|
+
var ServerStartError = class extends Schema.TaggedError()("Discovery.ServerStartError", { message: Schema.String }) {};
|
|
24
|
+
const START_TIMEOUT = "20 seconds";
|
|
25
|
+
const RACE_GRACE = "2 seconds";
|
|
26
|
+
const STOP_TIMEOUT = "5 seconds";
|
|
27
|
+
const decode = Schema.decodeUnknownEffect(infoJson);
|
|
28
|
+
const read = (path) => Effect.gen(function* () {
|
|
29
|
+
const text = yield* (yield* FileSystem.FileSystem).readFileString(path).pipe(Effect.option);
|
|
30
|
+
if (Option.isNone(text)) return void 0;
|
|
31
|
+
return yield* decode(text.value).pipe(Effect.option, Effect.map(Option.getOrUndefined));
|
|
32
|
+
});
|
|
33
|
+
const remove = (path) => Effect.gen(function* () {
|
|
34
|
+
yield* (yield* FileSystem.FileSystem).remove(path);
|
|
35
|
+
}).pipe(Effect.ignore);
|
|
36
|
+
/** Whether `pid` is a running process. EPERM means it exists but belongs to someone else. */
|
|
37
|
+
const alive = (pid) => Effect.try({
|
|
38
|
+
try: () => process.kill(pid, 0),
|
|
39
|
+
catch: (error) => error.code
|
|
40
|
+
}).pipe(Effect.as(true), Effect.catch((code) => Effect.succeed(code === "EPERM")));
|
|
41
|
+
/** Whether `pid` exits within `timeout`. */
|
|
42
|
+
const exits = (pid, timeout) => alive(pid).pipe(Effect.repeat({
|
|
43
|
+
while: (running) => running,
|
|
44
|
+
schedule: Schedule.spaced("50 millis")
|
|
45
|
+
}), Effect.timeoutOption(timeout), Effect.map(Option.isSome));
|
|
46
|
+
/**
|
|
47
|
+
* The registered server, with `live` set when the process answering its endpoint
|
|
48
|
+
* is the one that registered. The file is a hint, never proof: a different server
|
|
49
|
+
* on a reused port must not pass for it.
|
|
50
|
+
*/
|
|
51
|
+
const registered = (path) => Effect.gen(function* () {
|
|
52
|
+
const info = yield* read(path);
|
|
53
|
+
if (info === void 0) return void 0;
|
|
54
|
+
const live = yield* probe(info.url);
|
|
55
|
+
return {
|
|
56
|
+
info,
|
|
57
|
+
live: live?.pid === info.pid ? live : void 0
|
|
58
|
+
};
|
|
59
|
+
});
|
|
60
|
+
const endpoint = (info) => ({
|
|
61
|
+
url: info.url,
|
|
62
|
+
pid: info.pid,
|
|
63
|
+
port: info.port
|
|
64
|
+
});
|
|
65
|
+
/** The running server registered for `home`, with the build it reports. */
|
|
66
|
+
const discover = (home) => registered(file(home)).pipe(Effect.map((found) => found?.live === void 0 ? void 0 : {
|
|
67
|
+
...endpoint(found.info),
|
|
68
|
+
version: found.live.version
|
|
69
|
+
}));
|
|
70
|
+
/**
|
|
71
|
+
* Stop the server registered for `home`, returning it, or undefined when none
|
|
72
|
+
* answers. Only a server that confirms it is the registrant is signalled: a pid
|
|
73
|
+
* on file may since have been reused by an unrelated process.
|
|
74
|
+
*/
|
|
75
|
+
const stop = (home) => Effect.gen(function* () {
|
|
76
|
+
const path = file(home);
|
|
77
|
+
const found = yield* registered(path);
|
|
78
|
+
if (found === void 0) return void 0;
|
|
79
|
+
if (found.live === void 0) {
|
|
80
|
+
if (!(yield* alive(found.info.pid))) yield* remove(path);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
yield* terminate(path, found.info.pid);
|
|
84
|
+
return endpoint(found.info);
|
|
85
|
+
});
|
|
86
|
+
/**
|
|
87
|
+
* Ensure a healthy local server for `home`: reuse the registered one, replace it
|
|
88
|
+
* when `replace` is set and it runs a different build, or start a background one.
|
|
89
|
+
*
|
|
90
|
+
* The background server is detached and outlives this caller, so the next
|
|
91
|
+
* invocation reuses it. When two callers race, only the contender that binds the
|
|
92
|
+
* port registers; the loser exits and both adopt the winner, because a caller
|
|
93
|
+
* only ever believes a registration it can confirm over the wire.
|
|
94
|
+
*/
|
|
95
|
+
const ensure = (options) => Effect.gen(function* () {
|
|
96
|
+
const path = file(options.home);
|
|
97
|
+
const found = yield* registered(path);
|
|
98
|
+
if (found?.live !== void 0) {
|
|
99
|
+
if (!options.replace || found.live.version === current.version) return endpoint(found.info);
|
|
100
|
+
yield* Effect.sync(() => options.onStart?.("version-mismatch"));
|
|
101
|
+
yield* terminate(path, found.info.pid);
|
|
102
|
+
} else {
|
|
103
|
+
if (found !== void 0 && !(yield* alive(found.info.pid))) yield* remove(path);
|
|
104
|
+
yield* Effect.sync(() => options.onStart?.("missing"));
|
|
105
|
+
}
|
|
106
|
+
return yield* start(path, options);
|
|
107
|
+
});
|
|
108
|
+
/** The registered server once it answers, polled every 200ms for up to `timeout`. */
|
|
109
|
+
const ready = (path, timeout, pending) => Effect.gen(function* () {
|
|
110
|
+
const next = yield* registered(path);
|
|
111
|
+
if (next?.live !== void 0) return Option.some(endpoint(next.info));
|
|
112
|
+
return (yield* pending) || next !== void 0 && (yield* alive(next.info.pid)) ? Option.none() : yield* Effect.fail("exited");
|
|
113
|
+
}).pipe(Effect.repeat({
|
|
114
|
+
until: Option.isSome,
|
|
115
|
+
schedule: Schedule.spaced("200 millis")
|
|
116
|
+
}), Effect.timeoutOption(timeout), Effect.map(Option.flatten), Effect.orElseSucceed(() => Option.none()));
|
|
117
|
+
/**
|
|
118
|
+
* Start a background server and wait for it to register, quoting the reason
|
|
119
|
+
* from its log when it cannot.
|
|
120
|
+
*
|
|
121
|
+
* The contender stays tied to this scope until it is the server adopted: a
|
|
122
|
+
* timeout, an interrupt, or another caller winning the race stops it rather than
|
|
123
|
+
* leaving an unmanaged server behind.
|
|
124
|
+
*/
|
|
125
|
+
const start = (path, options) => Effect.gen(function* () {
|
|
126
|
+
const contender = yield* spawn(options);
|
|
127
|
+
const won = yield* ready(path, START_TIMEOUT, contender.isRunning.pipe(Effect.orElseSucceed(() => false)));
|
|
128
|
+
const server = Option.isSome(won) ? won : yield* ready(path, RACE_GRACE, Effect.succeed(true));
|
|
129
|
+
if (Option.isSome(server)) {
|
|
130
|
+
if (server.value.pid === contender.pid) yield* contender.unref.pipe(Effect.asVoid);
|
|
131
|
+
return server.value;
|
|
132
|
+
}
|
|
133
|
+
const log$1 = log(options.log);
|
|
134
|
+
const reason = yield* lastLine(log$1);
|
|
135
|
+
return yield* new ServerStartError({ message: [
|
|
136
|
+
`could not start a CodeWork server on ${options.host}:${options.port}`,
|
|
137
|
+
...reason === void 0 ? [] : [`reason: ${reason}`],
|
|
138
|
+
`log: ${log$1}`,
|
|
139
|
+
"hint: pass --port to use another port, or point `codework tui --server` at a running server"
|
|
140
|
+
].join("\n") });
|
|
141
|
+
}).pipe(Effect.scoped);
|
|
142
|
+
/**
|
|
143
|
+
* Keep the session's server running for as long as the caller lives.
|
|
144
|
+
*
|
|
145
|
+
* The TUI only reconnects; it cannot start a server. If the one it uses goes
|
|
146
|
+
* away, this brings one back on the same port so the reconnect lands. It never
|
|
147
|
+
* replaces a running server: another invocation may have just upgraded it.
|
|
148
|
+
*/
|
|
149
|
+
const keepAlive = (initial, options) => Effect.gen(function* () {
|
|
150
|
+
const current = yield* Ref.make(initial);
|
|
151
|
+
yield* Effect.gen(function* () {
|
|
152
|
+
const server = yield* Ref.get(current);
|
|
153
|
+
if (yield* alive(server.pid)) return;
|
|
154
|
+
const next = yield* ensure({
|
|
155
|
+
...options,
|
|
156
|
+
port: server.port,
|
|
157
|
+
replace: false
|
|
158
|
+
}).pipe(Effect.orElseSucceed(() => server));
|
|
159
|
+
yield* Ref.set(current, next);
|
|
160
|
+
}).pipe(Effect.repeat(Schedule.spaced("1 second")));
|
|
161
|
+
});
|
|
162
|
+
/** Ask `pid` to shut down, escalating to SIGKILL, and retire its registration. */
|
|
163
|
+
const terminate = (path, pid) => Effect.gen(function* () {
|
|
164
|
+
const signal = (name) => Effect.try(() => process.kill(pid, name)).pipe(Effect.ignore);
|
|
165
|
+
yield* signal("SIGTERM");
|
|
166
|
+
if (!(yield* exits(pid, STOP_TIMEOUT))) {
|
|
167
|
+
yield* signal("SIGKILL");
|
|
168
|
+
yield* exits(pid, STOP_TIMEOUT);
|
|
169
|
+
}
|
|
170
|
+
if ((yield* read(path))?.pid === pid) yield* remove(path);
|
|
171
|
+
});
|
|
172
|
+
const lastLine = (path) => Effect.gen(function* () {
|
|
173
|
+
return (yield* (yield* FileSystem.FileSystem).readFileString(path).pipe(Effect.orElseSucceed(() => ""))).split("\n").map((line) => line.trim()).findLast((line) => line.length > 0);
|
|
174
|
+
});
|
|
175
|
+
/**
|
|
176
|
+
* Spawn `codework serve --service` detached, inheriting this environment so it
|
|
177
|
+
* resolves the same home, catalog and credentials. It writes its own log, so no
|
|
178
|
+
* stdio is tied to this short-lived caller. It stays referenced, and so stopped
|
|
179
|
+
* with the scope, until `start` adopts it.
|
|
180
|
+
*/
|
|
181
|
+
const spawn = (options) => Effect.gen(function* () {
|
|
182
|
+
const [file, ...base] = command();
|
|
183
|
+
if (file === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("could not resolve the codework entrypoint"));
|
|
184
|
+
return yield* (yield* ChildProcessSpawner.ChildProcessSpawner).spawn(ChildProcess.make(file, [
|
|
185
|
+
...base,
|
|
186
|
+
...options.args,
|
|
187
|
+
"serve",
|
|
188
|
+
"--service",
|
|
189
|
+
"--host",
|
|
190
|
+
options.host,
|
|
191
|
+
"--port",
|
|
192
|
+
String(options.port)
|
|
193
|
+
], {
|
|
194
|
+
detached: true,
|
|
195
|
+
stdin: "ignore",
|
|
196
|
+
stdout: "ignore",
|
|
197
|
+
stderr: "ignore"
|
|
198
|
+
}));
|
|
199
|
+
});
|
|
200
|
+
//#endregion
|
|
201
|
+
//#region src/cli/service.ts
|
|
202
|
+
/** The CodeWork home the shared flags name, resolved the way the harness resolves it. */
|
|
203
|
+
const home = (shared) => Global.resolve(Option.isSome(shared.home) ? { home: shared.home.value } : {});
|
|
204
|
+
/**
|
|
205
|
+
* How `tui` and `service` find or start the background server: the home whose
|
|
206
|
+
* `service.json` names it, and the server-owned flags it is started with, in the
|
|
207
|
+
* order `serve` parses them.
|
|
208
|
+
*/
|
|
209
|
+
const options = (shared, server) => home(shared).pipe(Effect.map((paths) => ({
|
|
210
|
+
home: paths.home,
|
|
211
|
+
log: paths.log,
|
|
212
|
+
...server,
|
|
213
|
+
args: [
|
|
214
|
+
...Option.isSome(shared.home) ? ["--home", shared.home.value] : [],
|
|
215
|
+
...Option.isSome(shared.database) ? ["--database", shared.database.value] : [],
|
|
216
|
+
...Option.isSome(shared.userConfigDir) ? ["--user-config-dir", shared.userConfigDir.value] : []
|
|
217
|
+
]
|
|
218
|
+
})));
|
|
219
|
+
//#endregion
|
|
220
|
+
export { keepAlive as a, ensure as i, options as n, stop as o, discover as r, probe as s, home as t };
|
|
221
|
+
|
|
222
|
+
//# sourceMappingURL=service-7_FrDOGJ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-7_FrDOGJ.mjs","names":["Client.layer","Client.make","Registration.infoJson","Health.probe","Registration.file","log","Registration.log","Registration.command"],"sources":["../../src/server/health.ts","../../src/server/discovery.ts","../../src/cli/service.ts"],"sourcesContent":["import { Effect, Layer } from \"effect\";\nimport { Client } from \"./client.ts\";\n\n/**\n * One `server.info` call, with the answer normalized to `undefined` for every\n * way a server can fail to answer: unreachable, slow, or speaking a different\n * protocol. A health check that throws where it should say \"no\" would make\n * every caller wrap it in a catch.\n */\nexport const probe = (url: string) =>\n\tEffect.gen(function* () {\n\t\tconst context = yield* Layer.build(Client.layer(url)).pipe(Effect.orElseSucceed(() => undefined));\n\t\tif (context === undefined) return undefined;\n\t\treturn yield* Effect.gen(function* () {\n\t\t\tconst rpc = yield* Client.make;\n\t\t\treturn yield* rpc[\"server.info\"]({}).pipe(Effect.timeout(\"1 second\"));\n\t\t}).pipe(\n\t\t\tEffect.provideContext(context),\n\t\t\tEffect.orElseSucceed(() => undefined),\n\t\t);\n\t}).pipe(Effect.scoped);\n\nexport * as Health from \"./health.ts\";\n","import { type Duration, Effect, FileSystem, Option, Ref, Schedule, Schema } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\nimport { Health } from \"./health.ts\";\nimport { Identity } from \"./identity.ts\";\nimport { Registration } from \"./registration.ts\";\n\n/** A server a client can connect to, and the process and port behind it. */\nexport interface Endpoint {\n\treadonly url: string;\n\treadonly pid: number;\n\treadonly port: number;\n}\n\n/** A managed server could not be produced, in the words the CLI prints. */\nexport class ServerStartError extends Schema.TaggedError<ServerStartError>()(\"Discovery.ServerStartError\", {\n\tmessage: Schema.String,\n}) {}\n\nexport interface Options {\n\t/** The CodeWork home whose `service.json` names the server. */\n\treadonly home: string;\n\t/** The home's log directory, where a background server writes `server.log`. */\n\treadonly log: string;\n\treadonly host: string;\n\treadonly port: number;\n\t/** Server-owned flags placed before `serve`. */\n\treadonly args: ReadonlyArray<string>;\n}\n\nconst START_TIMEOUT = \"20 seconds\";\nconst RACE_GRACE = \"2 seconds\";\nconst STOP_TIMEOUT = \"5 seconds\";\n\nconst decode = Schema.decodeUnknownEffect(Registration.infoJson);\n\nconst read = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tconst text = yield* fs.readFileString(path).pipe(Effect.option);\n\t\tif (Option.isNone(text)) return undefined;\n\t\treturn yield* decode(text.value).pipe(Effect.option, Effect.map(Option.getOrUndefined));\n\t});\n\nconst remove = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tyield* fs.remove(path);\n\t}).pipe(Effect.ignore);\n\n/** Whether `pid` is a running process. EPERM means it exists but belongs to someone else. */\nconst alive = (pid: number) =>\n\tEffect.try({ try: () => process.kill(pid, 0), catch: (error) => (error as NodeJS.ErrnoException).code }).pipe(\n\t\tEffect.as(true),\n\t\tEffect.catch((code) => Effect.succeed(code === \"EPERM\")),\n\t);\n\n/** Whether `pid` exits within `timeout`. */\nconst exits = (pid: number, timeout: typeof STOP_TIMEOUT) =>\n\talive(pid).pipe(\n\t\tEffect.repeat({ while: (running) => running, schedule: Schedule.spaced(\"50 millis\") }),\n\t\tEffect.timeoutOption(timeout),\n\t\tEffect.map(Option.isSome),\n\t);\n\n/**\n * The registered server, with `live` set when the process answering its endpoint\n * is the one that registered. The file is a hint, never proof: a different server\n * on a reused port must not pass for it.\n */\nconst registered = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst info = yield* read(path);\n\t\tif (info === undefined) return undefined;\n\t\tconst live = yield* Health.probe(info.url);\n\t\treturn { info, live: live?.pid === info.pid ? live : undefined };\n\t});\n\nconst endpoint = (info: Registration.Info): Endpoint => ({ url: info.url, pid: info.pid, port: info.port });\n\n/** The running server registered for `home`, with the build it reports. */\nexport const discover = (home: string) =>\n\tregistered(Registration.file(home)).pipe(\n\t\tEffect.map((found) =>\n\t\t\tfound?.live === undefined ? undefined : { ...endpoint(found.info), version: found.live.version },\n\t\t),\n\t);\n\n/**\n * Stop the server registered for `home`, returning it, or undefined when none\n * answers. Only a server that confirms it is the registrant is signalled: a pid\n * on file may since have been reused by an unrelated process.\n */\nexport const stop = (home: string) =>\n\tEffect.gen(function* () {\n\t\tconst path = Registration.file(home);\n\t\tconst found = yield* registered(path);\n\t\tif (found === undefined) return undefined;\n\t\tif (found.live === undefined) {\n\t\t\tif (!(yield* alive(found.info.pid))) yield* remove(path);\n\t\t\treturn undefined;\n\t\t}\n\t\tyield* terminate(path, found.info.pid);\n\t\treturn endpoint(found.info);\n\t});\n\n/**\n * Ensure a healthy local server for `home`: reuse the registered one, replace it\n * when `replace` is set and it runs a different build, or start a background one.\n *\n * The background server is detached and outlives this caller, so the next\n * invocation reuses it. When two callers race, only the contender that binds the\n * port registers; the loser exits and both adopt the winner, because a caller\n * only ever believes a registration it can confirm over the wire.\n */\nexport const ensure = (\n\toptions: Options & {\n\t\treadonly replace: boolean;\n\t\treadonly onStart?: (reason: \"missing\" | \"version-mismatch\") => void;\n\t},\n) =>\n\tEffect.gen(function* () {\n\t\tconst path = Registration.file(options.home);\n\t\tconst found = yield* registered(path);\n\t\tif (found?.live !== undefined) {\n\t\t\tif (!options.replace || found.live.version === Identity.current.version) return endpoint(found.info);\n\t\t\tyield* Effect.sync(() => options.onStart?.(\"version-mismatch\"));\n\t\t\tyield* terminate(path, found.info.pid);\n\t\t} else {\n\t\t\t// A file nothing answers for, left by a crash, must not mislead the next caller.\n\t\t\tif (found !== undefined && !(yield* alive(found.info.pid))) yield* remove(path);\n\t\t\tyield* Effect.sync(() => options.onStart?.(\"missing\"));\n\t\t}\n\t\treturn yield* start(path, options);\n\t});\n\n/** The registered server once it answers, polled every 200ms for up to `timeout`. */\nconst ready = (path: string, timeout: Duration.Input, pending: Effect.Effect<boolean>) =>\n\tEffect.gen(function* () {\n\t\tconst next = yield* registered(path);\n\t\tif (next?.live !== undefined) return Option.some(endpoint(next.info));\n\t\t// A live registrant that does not answer yet is another caller's server starting up.\n\t\tconst waiting = (yield* pending) || (next !== undefined && (yield* alive(next.info.pid)));\n\t\treturn waiting ? Option.none() : yield* Effect.fail(\"exited\" as const);\n\t}).pipe(\n\t\tEffect.repeat({ until: Option.isSome, schedule: Schedule.spaced(\"200 millis\") }),\n\t\tEffect.timeoutOption(timeout),\n\t\tEffect.map(Option.flatten),\n\t\tEffect.orElseSucceed(() => Option.none<Endpoint>()),\n\t);\n\n/**\n * Start a background server and wait for it to register, quoting the reason\n * from its log when it cannot.\n *\n * The contender stays tied to this scope until it is the server adopted: a\n * timeout, an interrupt, or another caller winning the race stops it rather than\n * leaving an unmanaged server behind.\n */\nconst start = (path: string, options: Options) =>\n\tEffect.gen(function* () {\n\t\tconst contender = yield* spawn(options);\n\t\tconst won = yield* ready(path, START_TIMEOUT, contender.isRunning.pipe(Effect.orElseSucceed(() => false)));\n\t\t// A contender that lost the bind race exits before the winner may have filed its\n\t\t// registration; give the winner a moment before calling the start a failure.\n\t\tconst server = Option.isSome(won) ? won : yield* ready(path, RACE_GRACE, Effect.succeed(true));\n\t\tif (Option.isSome(server)) {\n\t\t\tif (server.value.pid === contender.pid) yield* contender.unref.pipe(Effect.asVoid);\n\t\t\treturn server.value;\n\t\t}\n\n\t\tconst log = Registration.log(options.log);\n\t\tconst reason = yield* lastLine(log);\n\t\treturn yield* new ServerStartError({\n\t\t\tmessage: [\n\t\t\t\t`could not start a CodeWork server on ${options.host}:${options.port}`,\n\t\t\t\t...(reason === undefined ? [] : [`reason: ${reason}`]),\n\t\t\t\t`log: ${log}`,\n\t\t\t\t\"hint: pass --port to use another port, or point `codework tui --server` at a running server\",\n\t\t\t].join(\"\\n\"),\n\t\t});\n\t}).pipe(Effect.scoped);\n\n/**\n * Keep the session's server running for as long as the caller lives.\n *\n * The TUI only reconnects; it cannot start a server. If the one it uses goes\n * away, this brings one back on the same port so the reconnect lands. It never\n * replaces a running server: another invocation may have just upgraded it.\n */\nexport const keepAlive = (initial: Endpoint, options: Options) =>\n\tEffect.gen(function* () {\n\t\tconst current = yield* Ref.make(initial);\n\t\tyield* Effect.gen(function* () {\n\t\t\tconst server = yield* Ref.get(current);\n\t\t\tif (yield* alive(server.pid)) return;\n\t\t\tconst next = yield* ensure({ ...options, port: server.port, replace: false }).pipe(\n\t\t\t\tEffect.orElseSucceed(() => server),\n\t\t\t);\n\t\t\tyield* Ref.set(current, next);\n\t\t}).pipe(Effect.repeat(Schedule.spaced(\"1 second\")));\n\t});\n\n/** Ask `pid` to shut down, escalating to SIGKILL, and retire its registration. */\nconst terminate = (path: string, pid: number) =>\n\tEffect.gen(function* () {\n\t\tconst signal = (name: NodeJS.Signals) => Effect.try(() => process.kill(pid, name)).pipe(Effect.ignore);\n\t\tyield* signal(\"SIGTERM\");\n\t\tif (!(yield* exits(pid, STOP_TIMEOUT))) {\n\t\t\tyield* signal(\"SIGKILL\");\n\t\t\tyield* exits(pid, STOP_TIMEOUT);\n\t\t}\n\t\t// A server removes its own file on a clean exit; this covers the SIGKILL path.\n\t\tconst info = yield* read(path);\n\t\tif (info?.pid === pid) yield* remove(path);\n\t});\n\nconst lastLine = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tconst text = yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => \"\"));\n\t\treturn text\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trim())\n\t\t\t.findLast((line) => line.length > 0);\n\t});\n\n/**\n * Spawn `codework serve --service` detached, inheriting this environment so it\n * resolves the same home, catalog and credentials. It writes its own log, so no\n * stdio is tied to this short-lived caller. It stays referenced, and so stopped\n * with the scope, until `start` adopts it.\n */\nconst spawn = (options: Options) =>\n\tEffect.gen(function* () {\n\t\tconst [file, ...base] = Registration.command();\n\t\tif (file === undefined) return yield* Effect.die(new Error(\"could not resolve the codework entrypoint\"));\n\t\tconst spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\t\tconst handle = yield* spawner.spawn(\n\t\t\tChildProcess.make(\n\t\t\t\tfile,\n\t\t\t\t[...base, ...options.args, \"serve\", \"--service\", \"--host\", options.host, \"--port\", String(options.port)],\n\t\t\t\t{ detached: true, stdin: \"ignore\", stdout: \"ignore\", stderr: \"ignore\" },\n\t\t\t),\n\t\t);\n\t\treturn handle;\n\t});\n\nexport * as Discovery from \"./discovery.ts\";\n","import { Global } from \"@codeworksh/harness/effect\";\nimport { Effect, Option } from \"effect\";\nimport type { Discovery } from \"../server/discovery.ts\";\n\ninterface Shared {\n\treadonly userConfigDir: Option.Option<string>;\n\treadonly home: Option.Option<string>;\n\treadonly database: Option.Option<string>;\n}\n\n/** The CodeWork home the shared flags name, resolved the way the harness resolves it. */\nexport const home = (shared: Shared) => Global.resolve(Option.isSome(shared.home) ? { home: shared.home.value } : {});\n\n/**\n * How `tui` and `service` find or start the background server: the home whose\n * `service.json` names it, and the server-owned flags it is started with, in the\n * order `serve` parses them.\n */\nexport const options = (shared: Shared, server: { readonly host: string; readonly port: number }) =>\n\thome(shared).pipe(\n\t\tEffect.map((paths): Discovery.Options => ({\n\t\t\thome: paths.home,\n\t\t\tlog: paths.log,\n\t\t\t...server,\n\t\t\targs: [\n\t\t\t\t...(Option.isSome(shared.home) ? [\"--home\", shared.home.value] : []),\n\t\t\t\t...(Option.isSome(shared.database) ? [\"--database\", shared.database.value] : []),\n\t\t\t\t...(Option.isSome(shared.userConfigDir) ? [\"--user-config-dir\", shared.userConfigDir.value] : []),\n\t\t\t],\n\t\t})),\n\t);\n\nexport * as Service from \"./service.ts\";\n"],"mappings":";;;;;;;;;;;;AASA,MAAa,SAAS,QACrB,OAAO,IAAI,aAAa;CACvB,MAAM,UAAU,OAAO,MAAM,MAAMA,MAAa,GAAG,CAAC,CAAC,CAAC,KAAK,OAAO,oBAAoB,KAAA,CAAS,CAAC;CAChG,IAAI,YAAY,KAAA,GAAW,OAAO,KAAA;CAClC,OAAO,OAAO,OAAO,IAAI,aAAa;EAErC,OAAO,QAAO,OADKC,KAAAA,CACD,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,UAAU,CAAC;CACrE,CAAC,CAAC,CAAC,KACF,OAAO,eAAe,OAAO,GAC7B,OAAO,oBAAoB,KAAA,CAAS,CACrC;AACD,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM;;;;ACNtB,IAAa,mBAAb,cAAsC,OAAO,YAA8B,CAAC,CAAC,8BAA8B,EAC1G,SAAS,OAAO,OACjB,CAAC,CAAC,CAAC,CAAC;AAaJ,MAAM,gBAAgB;AACtB,MAAM,aAAa;AACnB,MAAM,eAAe;AAErB,MAAM,SAAS,OAAO,oBAAoBC,QAAqB;AAE/D,MAAM,QAAQ,SACb,OAAO,IAAI,aAAa;CAEvB,MAAM,OAAO,QAAO,OADF,WAAW,WAAA,CACN,eAAe,IAAI,CAAC,CAAC,KAAK,OAAO,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AC;;;;AC1OF,MAAa,QAAQ,WAAmB,OAAO,QAAQ,OAAO,OAAO,OAAO,IAAI,IAAI,EAAE,MAAM,OAAO,KAAK,MAAM,IAAI,CAAC,CAAC;;;;;;AAOpH,MAAa,WAAW,QAAgB,WACvC,KAAK,MAAM,CAAC,CAAC,KACZ,OAAO,KAAK,WAA8B;CACzC,MAAM,MAAM;CACZ,KAAK,MAAM;CACX,GAAG;CACH,MAAM;EACL,GAAI,OAAO,OAAO,OAAO,IAAI,IAAI,CAAC,UAAU,OAAO,KAAK,KAAK,IAAI,CAAC;EAClE,GAAI,OAAO,OAAO,OAAO,QAAQ,IAAI,CAAC,cAAc,OAAO,SAAS,KAAK,IAAI,CAAC;EAC9E,GAAI,OAAO,OAAO,OAAO,aAAa,IAAI,CAAC,qBAAqB,OAAO,cAAc,KAAK,IAAI,CAAC;CAChG;AACD,EAAE,CACH"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as InvalidInputError } from "./error-
|
|
1
|
+
import { t as InvalidInputError } from "./error-CzUxh0Q9.mjs";
|
|
2
2
|
import { Effect, FileSystem, Option, Path } from "effect";
|
|
3
3
|
import { Global, Plugin, Settings } from "@codeworksh/harness/effect";
|
|
4
4
|
import { applyEdits, modify, parse } from "jsonc-parser";
|
|
@@ -218,4 +218,4 @@ const resolveTarget = Effect.fn("CLI.plugin.resolveTarget")(function* (shared, g
|
|
|
218
218
|
//#endregion
|
|
219
219
|
export { resolveTarget as a, withPluginsLock as c, readPlugins as i, writePlugins as l, matches as n, spellings as o, matching as r, userLayer as s, identify as t, written as u };
|
|
220
220
|
|
|
221
|
-
//# sourceMappingURL=settings-
|
|
221
|
+
//# sourceMappingURL=settings-BM_gw7Fm.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-DDkmAxW5.mjs","names":["parseJsonc"],"sources":["../../src/cli/cmd/handlers/plugin/settings.ts"],"sourcesContent":["import { Global, Plugin, Settings } from \"@codeworksh/harness/effect\";\nimport { Effect, FileSystem, Option, Path } from \"effect\";\nimport { applyEdits, modify, parse as parseJsonc, type ParseError } from \"jsonc-parser\";\nimport { InvalidInputError } from \"../../../error.ts\";\n\n/**\n * Reading and rewriting the `plugins` array of one settings file.\n *\n * Edits go through `jsonc-parser`, so a hand-written file keeps its comments, key order and\n * formatting: a plugin added by the CLI must not reformat a file its owner maintains. The write\n * is a temp file renamed over the original, so an interrupted run leaves the previous settings\n * intact rather than a half-written document.\n */\n\nexport interface Shared {\n\treadonly userConfigDir: Option.Option<string>;\n\treadonly home: Option.Option<string>;\n}\n\n/**\n * The user layer a command reads and writes: `--user-config-dir` when given -- a hard override of\n * the home's settings file -- resolved, like every app-level flag, against the directory the\n * command runs in (`hostCwd`), never against a linked session's `hostDir`.\n */\nexport const userLayer = (shared: Shared, hostCwd: string) =>\n\tOption.isNone(shared.userConfigDir)\n\t\t? {}\n\t\t: { userConfigDir: Settings.userConfigDir(shared.userConfigDir.value, hostCwd) };\n\nexport interface Target {\n\treadonly path: string;\n\t/** Set when this command had to create the project directory, so the caller can say so. */\n\treadonly created?: string;\n\t/** The project this file belongs to, which a local entry is written relative to. */\n\treadonly root?: string;\n}\n\n/** The module an entry names: a bare loader string, or the `package` of a config object. */\nconst moduleOf = (entry: unknown): string | undefined => {\n\tif (typeof entry === \"string\") return entry;\n\tif (typeof entry !== \"object\" || entry === null) return undefined;\n\tconst { package: located } = entry as { package?: unknown };\n\treturn typeof located === \"string\" ? located : undefined;\n};\n\n/** The plugin ID an entry configures, if it names one. */\nconst idOf = (entry: unknown): string | undefined => {\n\tif (typeof entry !== \"object\" || entry === null) return undefined;\n\tconst { plugin } = entry as { plugin?: unknown };\n\treturn typeof plugin === \"string\" ? plugin : undefined;\n};\n\n/**\n * Every spelling a reference answers to, without touching the filesystem.\n *\n * `canonical` drops a version suffix and resolves a relative path against the file that declared\n * it, so `@acme/x@1.2.0` and `@acme/x` are one name. The literal string is kept alongside it\n * because a plugin ID is not a module reference and survives `canonical` unchanged.\n */\nconst aliases = (reference: string, directory: string): Effect.Effect<ReadonlyArray<string>> =>\n\tPlugin.canonical(reference, directory).pipe(\n\t\tEffect.map((canonical) => [reference, canonical] as ReadonlyArray<string>),\n\t\t// A reference that does not parse still answers to itself: a plugin ID is not a module\n\t\t// reference, and it has to keep matching an entry that names it.\n\t\tEffect.orElseSucceed(() => [reference] as ReadonlyArray<string>),\n\t);\n\n/** Every spelling `reference` answers to, computed once for a whole command. */\nexport const spellings = (reference: string, directory: string): Effect.Effect<ReadonlySet<string>> =>\n\tEffect.map(aliases(reference, directory), (found) => new Set(found));\n\nexport interface Entry {\n\treadonly value: unknown;\n\treadonly answers: ReadonlySet<string>;\n\treadonly loads: boolean;\n}\n\n/**\n * What each configured entry answers to.\n *\n * Comparing the string as written is not enough. `plugin add @acme/x@1.2.0` records a version the\n * user will not repeat when removing it, and one plugin can be named three ways: by package, by\n * path, or by the ID it declares -- a `{ \"plugin\": \"<id>\" }` configuration object sits next to the\n * module entry that loaded it, and removing the plugin has to take both.\n *\n * The declared ID is only knowable by importing the module, so it is read from what is already\n * installed: `resolveCached` reads a published package out of the harness cache and never runs an\n * installer, so editing a settings file cannot fetch anything. An entry that does not resolve --\n * uninstalled, moved, or broken -- keeps the names it was written with rather than failing the\n * command, because an unusable plugin is exactly the one a user is trying to remove.\n */\nexport const identify = Effect.fn(\"CLI.plugin.identify\")(function* (\n\tplugins: ReadonlyArray<unknown>,\n\tfile: string,\n\tcache: string,\n) {\n\tconst nodePath = yield* Path.Path;\n\tconst directory = nodePath.dirname(file);\n\tconst entries: Entry[] = [];\n\tfor (const value of plugins) {\n\t\tconst answers = new Set<string>();\n\t\tconst id = idOf(value);\n\t\tif (id !== undefined) answers.add(id);\n\t\tconst module = moduleOf(value);\n\t\tif (module !== undefined) {\n\t\t\tfor (const alias of yield* aliases(module, directory)) answers.add(alias);\n\t\t\tconst declared = yield* Plugin.inspect(module, {\n\t\t\t\tcache,\n\t\t\t\thostDir: directory,\n\t\t\t\tfile,\n\t\t\t\tinstall: Plugin.resolveCached,\n\t\t\t}).pipe(Effect.option);\n\t\t\tif (Option.isSome(declared)) {\n\t\t\t\tanswers.add(declared.value.id);\n\t\t\t\tif (declared.value.name !== undefined) answers.add(declared.value.name);\n\t\t\t}\n\t\t}\n\t\tentries.push({ value, answers, loads: typeof value === \"string\" });\n\t}\n\treturn entries as ReadonlyArray<Entry>;\n});\n\n/**\n * What a local reference should be *written* as, which is rarely what was typed.\n *\n * A relative path on the command line is relative to the command's host directory; in a settings file it is relative to\n * that file's own directory. Those differ the moment the command runs anywhere but the directory\n * holding the file, and writing the string verbatim produces a silently wrong entry:\n *\n * ```\n * $ cd ~/workspace/app/packages/fubar\n * $ codework plugin add ./plugins/x.ts # means packages/fubar/plugins/x.ts\n * → the project is ~/workspace/app, so the entry lands in app/.codework/settings.jsonc\n * → written verbatim, the harness loads app/.codework/plugins/x.ts ← a different file\n * ```\n *\n * With both ends inside one project the entry is written relative to the file, which is portable\n * to any checkout of that repository and therefore worth committing. Otherwise -- a `-g` write\n * into `<home>`, a `--user-config-dir` elsewhere, or a target outside the project -- relative\n * would be a lie, and an absolute path means the same thing read from anywhere.\n *\n * A package spec is returned untouched: it names no location.\n */\nexport const written = Effect.fn(\"CLI.plugin.written\")(function* (\n\treference: string,\n\tinput: { readonly hostDir: string; readonly file: string; readonly root: string | undefined },\n) {\n\tconst nodePath = yield* Path.Path;\n\tconst target = yield* Plugin.parse(reference, input.hostDir).pipe(Effect.option);\n\tif (Option.isNone(target) || target.value.kind !== \"local\") return reference;\n\n\tconst absolute = target.value.path;\n\tconst inside = (root: string, path: string) => path === root || path.startsWith(`${root}${nodePath.sep}`);\n\tif (input.root !== undefined && inside(input.root, input.file) && inside(input.root, absolute)) {\n\t\tconst relative = nodePath.relative(nodePath.dirname(input.file), absolute);\n\t\treturn relative.startsWith(\"..\") ? relative : `./${relative}`;\n\t}\n\treturn absolute;\n});\n\n/** `reference` selects `entry` when any spelling of one is a spelling of the other. */\nexport const matches = (entry: Entry, spelled: ReadonlySet<string>) =>\n\t[...spelled].some((alias) => entry.answers.has(alias));\n\n/** Every entry connected to a reference through a package spelling or declared plugin ID. */\nexport const matching = (entries: ReadonlyArray<Entry>, spelled: ReadonlySet<string>) => {\n\tconst answers = new Set(spelled);\n\tconst found = new Set<Entry>();\n\tfor (;;) {\n\t\tconst next = entries.filter(\n\t\t\t(entry) => !found.has(entry) && [...entry.answers].some((answer) => answers.has(answer)),\n\t\t);\n\t\tif (next.length === 0) return found as ReadonlySet<Entry>;\n\t\tfor (const entry of next) {\n\t\t\tfound.add(entry);\n\t\t\tfor (const answer of entry.answers) answers.add(answer);\n\t\t}\n\t}\n};\n\nexport const readPlugins = Effect.fn(\"CLI.plugin.readPlugins\")(function* (path: string) {\n\tconst fs = yield* FileSystem.FileSystem;\n\tconst exists = yield* fs.exists(path);\n\tconst source = exists ? yield* fs.readFileString(path) : \"{}\";\n\tconst errors: ParseError[] = [];\n\tconst document: unknown = parseJsonc(source, errors, { allowTrailingComma: true });\n\tif (errors.length > 0 || typeof document !== \"object\" || document === null || Array.isArray(document)) {\n\t\treturn yield* new InvalidInputError({ message: `${path} is not a valid settings file` });\n\t}\n\tconst plugins = (document as { plugins?: unknown }).plugins;\n\tif (plugins !== undefined && !Array.isArray(plugins)) {\n\t\treturn yield* new InvalidInputError({ message: `${path}: \"plugins\" must be an array` });\n\t}\n\treturn { source, plugins: (plugins ?? []) as ReadonlyArray<unknown> };\n});\n\nexport const writePlugins = Effect.fn(\"CLI.plugin.writePlugins\")(function* (\n\tpath: string,\n\tsource: string,\n\tplugins: ReadonlyArray<unknown>,\n) {\n\tconst fs = yield* FileSystem.FileSystem;\n\tconst nodePath = yield* Path.Path;\n\tconst edited = applyEdits(\n\t\tsource,\n\t\tmodify(source, [\"plugins\"], plugins, { formattingOptions: { tabSize: 2, insertSpaces: false } }),\n\t);\n\tconst directory = nodePath.dirname(path);\n\tyield* fs.makeDirectory(directory, { recursive: true });\n\tconst mode = (yield* fs.exists(path)) ? (yield* fs.stat(path)).mode & 0o777 : 0o600;\n\tconst temporary = yield* fs.makeTempFile({ directory, prefix: `.${nodePath.basename(path)}.`, suffix: \".tmp\" });\n\tyield* fs\n\t\t.writeFileString(temporary, edited.endsWith(\"\\n\") ? edited : `${edited}\\n`)\n\t\t.pipe(\n\t\t\tEffect.andThen(fs.chmod(temporary, mode)),\n\t\t\tEffect.andThen(fs.rename(temporary, path)),\n\t\t\tEffect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)),\n\t\t);\n});\n\n/**\n * Serialize one settings read-modify-rename across CLI processes.\n *\n * The install or inspection that precedes an edit stays outside this scope; only the local edit is\n * locked, so unrelated downloads do not wait behind one another.\n */\nexport const withPluginsLock = <A, E, R>(path: string, edit: Effect.Effect<A, E, R>) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tconst nodePath = yield* Path.Path;\n\t\tyield* fs.makeDirectory(nodePath.dirname(path), { recursive: true });\n\t\tyield* Plugin.settingsLock(\n\t\t\t`${path}.lock`,\n\t\t\t() => new InvalidInputError({ message: `timed out waiting to edit ${path}` }),\n\t\t);\n\t\treturn yield* edit;\n\t}).pipe(Effect.scoped);\n\n/**\n * Which file the edit lands in.\n *\n * A plugin belongs to a project by default — it is part of how that repository is worked on, so\n * the entry belongs in a file the repository can commit. `--global` writes the user settings file\n * instead, the way `npm -g` installs outside a package: `<--home>/settings.jsonc`, or the\n * `--user-config-dir` one that replaces it.\n *\n * The project is found the way the harness finds it: the nearest ancestor holding a `.codework`\n * directory, so a command run from `packages/app` edits the repository's own file rather than\n * creating a second one beside it. When no ancestor has one, the project begins here -- the\n * directory is created and the caller is told, because that decision changes where every future\n * plugin entry lands, and a mistyped `cd` is the way it goes wrong.\n *\n * There is nothing to warn about between layers: plugin entries from every layer accumulate, so a\n * user-wide entry still applies inside a project that declares its own.\n */\nexport const resolveTarget = Effect.fn(\"CLI.plugin.resolveTarget\")(function* (\n\tshared: Shared,\n\tglobal: boolean,\n\t/**\n\t * Where to discover the project from, when it is not the shell's directory.\n\t *\n\t * A session's host directory is the only other honest answer: it is a declared host path. The\n\t * session's *space* is not, and neither is its project -- a `Project` is env-independent by\n\t * design, so it has no host directory to offer.\n\t */\n\tfrom?: string,\n\t/** Only `plugin add` may establish a project marker when no project exists yet. */\n\tcreate = true,\n) {\n\tconst fs = yield* FileSystem.FileSystem;\n\tconst nodePath = yield* Path.Path;\n\tconst hostCwd = nodePath.resolve(\".\");\n\t// The linked session's host directory, or -- with none -- the one the command runs in.\n\tconst hostDir = from ?? hostCwd;\n\tconst home = yield* Global.resolve(Option.isNone(shared.home) ? {} : { home: shared.home.value });\n\tconst root = global ? undefined : yield* Settings.projectRoot(hostDir, home.home);\n\t// `paths` is ordered lowest priority first: the user layer, then the project.\n\tconst groups = Settings.paths({\n\t\thome: home.home,\n\t\t...(root === undefined ? {} : { root }),\n\t\t...userLayer(shared, hostCwd),\n\t});\n\tconst chosen = global ? 0 : 1;\n\t// An empty group is the project layer saying there is no project above this directory. Then\n\t// this directory becomes one -- reported, not silent, because the marker shadows any outer\n\t// project from now on, so a `.codework/` created by a mistyped `cd` is worth spotting at once.\n\tconst found = groups[chosen] ?? [];\n\tif (found.length > 0) {\n\t\tconst existing = yield* Effect.findFirst(found, (candidate) => fs.exists(candidate));\n\t\treturn {\n\t\t\tpath: Option.getOrElse(existing, () => found[0]!),\n\t\t\t...(root === undefined ? {} : { root }),\n\t\t} satisfies Target;\n\t}\n\tconst marker = nodePath.join(hostDir, \".codework\");\n\t// `created` is reported either way: with `create` unset the marker is named, not made, so a\n\t// caller can say what its write is about to establish without establishing it early.\n\tif (!create)\n\t\treturn { path: nodePath.join(marker, \"settings.jsonc\"), created: marker, root: hostDir } satisfies Target;\n\tyield* fs.makeDirectory(marker, { recursive: true });\n\treturn { path: nodePath.join(marker, \"settings.jsonc\"), created: marker, root: hostDir } satisfies Target;\n});\n"],"mappings":";;;;;;;;;;AAwBA,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AAC;CAChG,MAAM,OAAO,SAAS,KAAA,IAAY,OAAO,SAAS,YAAY,SAAS,KAAK,IAAI;CAWhF,MAAM,QATS,SAAS,MAAM;EAC7B,MAAM,KAAK;EACX,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK;EACrC,GAAG,UAAU,QAAQ,OAAO;CAC7B,CAKmB,CAAC,CAJL,SAAS,IAAI,MAII,CAAC;CACjC,IAAI,MAAM,SAAS,GAAG;EACrB,MAAM,WAAW,OAAO,OAAO,UAAU,QAAQ,cAAc,GAAG,OAAO,SAAS,CAAC;EACnF,OAAO;GACN,MAAM,OAAO,UAAU,gBAAgB,MAAM,EAAG;GAChD,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK;EACtC;CACD;CACA,MAAM,SAAS,SAAS,KAAK,SAAS,WAAW;CAGjD,IAAI,CAAC,QACJ,OAAO;EAAE,MAAM,SAAS,KAAK,QAAQ,gBAAgB;EAAG,SAAS;EAAQ,MAAM;CAAQ;CACxF,OAAO,GAAG,cAAc,QAAQ,EAAE,WAAW,KAAK,CAAC;CACnD,OAAO;EAAE,MAAM,SAAS,KAAK,QAAQ,gBAAgB;EAAG,SAAS;EAAQ,MAAM;CAAQ;AACxF,CAAC"}
|
|
1
|
+
{"version":3,"file":"settings-BM_gw7Fm.mjs","names":["parseJsonc"],"sources":["../../src/cli/cmd/handlers/plugin/settings.ts"],"sourcesContent":["import { Global, Plugin, Settings } from \"@codeworksh/harness/effect\";\nimport { Effect, FileSystem, Option, Path } from \"effect\";\nimport { applyEdits, modify, parse as parseJsonc, type ParseError } from \"jsonc-parser\";\nimport { InvalidInputError } from \"../../../error.ts\";\n\n/**\n * Reading and rewriting the `plugins` array of one settings file.\n *\n * Edits go through `jsonc-parser`, so a hand-written file keeps its comments, key order and\n * formatting: a plugin added by the CLI must not reformat a file its owner maintains. The write\n * is a temp file renamed over the original, so an interrupted run leaves the previous settings\n * intact rather than a half-written document.\n */\n\nexport interface Shared {\n\treadonly userConfigDir: Option.Option<string>;\n\treadonly home: Option.Option<string>;\n}\n\n/**\n * The user layer a command reads and writes: `--user-config-dir` when given -- a hard override of\n * the home's settings file -- resolved, like every app-level flag, against the directory the\n * command runs in (`hostCwd`), never against a linked session's `hostDir`.\n */\nexport const userLayer = (shared: Shared, hostCwd: string) =>\n\tOption.isNone(shared.userConfigDir)\n\t\t? {}\n\t\t: { userConfigDir: Settings.userConfigDir(shared.userConfigDir.value, hostCwd) };\n\nexport interface Target {\n\treadonly path: string;\n\t/** Set when this command had to create the project directory, so the caller can say so. */\n\treadonly created?: string;\n\t/** The project this file belongs to, which a local entry is written relative to. */\n\treadonly root?: string;\n}\n\n/** The module an entry names: a bare loader string, or the `package` of a config object. */\nconst moduleOf = (entry: unknown): string | undefined => {\n\tif (typeof entry === \"string\") return entry;\n\tif (typeof entry !== \"object\" || entry === null) return undefined;\n\tconst { package: located } = entry as { package?: unknown };\n\treturn typeof located === \"string\" ? located : undefined;\n};\n\n/** The plugin ID an entry configures, if it names one. */\nconst idOf = (entry: unknown): string | undefined => {\n\tif (typeof entry !== \"object\" || entry === null) return undefined;\n\tconst { plugin } = entry as { plugin?: unknown };\n\treturn typeof plugin === \"string\" ? plugin : undefined;\n};\n\n/**\n * Every spelling a reference answers to, without touching the filesystem.\n *\n * `canonical` drops a version suffix and resolves a relative path against the file that declared\n * it, so `@acme/x@1.2.0` and `@acme/x` are one name. The literal string is kept alongside it\n * because a plugin ID is not a module reference and survives `canonical` unchanged.\n */\nconst aliases = (reference: string, directory: string): Effect.Effect<ReadonlyArray<string>> =>\n\tPlugin.canonical(reference, directory).pipe(\n\t\tEffect.map((canonical) => [reference, canonical] as ReadonlyArray<string>),\n\t\t// A reference that does not parse still answers to itself: a plugin ID is not a module\n\t\t// reference, and it has to keep matching an entry that names it.\n\t\tEffect.orElseSucceed(() => [reference] as ReadonlyArray<string>),\n\t);\n\n/** Every spelling `reference` answers to, computed once for a whole command. */\nexport const spellings = (reference: string, directory: string): Effect.Effect<ReadonlySet<string>> =>\n\tEffect.map(aliases(reference, directory), (found) => new Set(found));\n\nexport interface Entry {\n\treadonly value: unknown;\n\treadonly answers: ReadonlySet<string>;\n\treadonly loads: boolean;\n}\n\n/**\n * What each configured entry answers to.\n *\n * Comparing the string as written is not enough. `plugin add @acme/x@1.2.0` records a version the\n * user will not repeat when removing it, and one plugin can be named three ways: by package, by\n * path, or by the ID it declares -- a `{ \"plugin\": \"<id>\" }` configuration object sits next to the\n * module entry that loaded it, and removing the plugin has to take both.\n *\n * The declared ID is only knowable by importing the module, so it is read from what is already\n * installed: `resolveCached` reads a published package out of the harness cache and never runs an\n * installer, so editing a settings file cannot fetch anything. An entry that does not resolve --\n * uninstalled, moved, or broken -- keeps the names it was written with rather than failing the\n * command, because an unusable plugin is exactly the one a user is trying to remove.\n */\nexport const identify = Effect.fn(\"CLI.plugin.identify\")(function* (\n\tplugins: ReadonlyArray<unknown>,\n\tfile: string,\n\tcache: string,\n) {\n\tconst nodePath = yield* Path.Path;\n\tconst directory = nodePath.dirname(file);\n\tconst entries: Entry[] = [];\n\tfor (const value of plugins) {\n\t\tconst answers = new Set<string>();\n\t\tconst id = idOf(value);\n\t\tif (id !== undefined) answers.add(id);\n\t\tconst module = moduleOf(value);\n\t\tif (module !== undefined) {\n\t\t\tfor (const alias of yield* aliases(module, directory)) answers.add(alias);\n\t\t\tconst declared = yield* Plugin.inspect(module, {\n\t\t\t\tcache,\n\t\t\t\thostDir: directory,\n\t\t\t\tfile,\n\t\t\t\tinstall: Plugin.resolveCached,\n\t\t\t}).pipe(Effect.option);\n\t\t\tif (Option.isSome(declared)) {\n\t\t\t\tanswers.add(declared.value.id);\n\t\t\t\tif (declared.value.name !== undefined) answers.add(declared.value.name);\n\t\t\t}\n\t\t}\n\t\tentries.push({ value, answers, loads: typeof value === \"string\" });\n\t}\n\treturn entries as ReadonlyArray<Entry>;\n});\n\n/**\n * What a local reference should be *written* as, which is rarely what was typed.\n *\n * A relative path on the command line is relative to the command's host directory; in a settings file it is relative to\n * that file's own directory. Those differ the moment the command runs anywhere but the directory\n * holding the file, and writing the string verbatim produces a silently wrong entry:\n *\n * ```\n * $ cd ~/workspace/app/packages/fubar\n * $ codework plugin add ./plugins/x.ts # means packages/fubar/plugins/x.ts\n * → the project is ~/workspace/app, so the entry lands in app/.codework/settings.jsonc\n * → written verbatim, the harness loads app/.codework/plugins/x.ts ← a different file\n * ```\n *\n * With both ends inside one project the entry is written relative to the file, which is portable\n * to any checkout of that repository and therefore worth committing. Otherwise -- a `-g` write\n * into `<home>`, a `--user-config-dir` elsewhere, or a target outside the project -- relative\n * would be a lie, and an absolute path means the same thing read from anywhere.\n *\n * A package spec is returned untouched: it names no location.\n */\nexport const written = Effect.fn(\"CLI.plugin.written\")(function* (\n\treference: string,\n\tinput: { readonly hostDir: string; readonly file: string; readonly root: string | undefined },\n) {\n\tconst nodePath = yield* Path.Path;\n\tconst target = yield* Plugin.parse(reference, input.hostDir).pipe(Effect.option);\n\tif (Option.isNone(target) || target.value.kind !== \"local\") return reference;\n\n\tconst absolute = target.value.path;\n\tconst inside = (root: string, path: string) => path === root || path.startsWith(`${root}${nodePath.sep}`);\n\tif (input.root !== undefined && inside(input.root, input.file) && inside(input.root, absolute)) {\n\t\tconst relative = nodePath.relative(nodePath.dirname(input.file), absolute);\n\t\treturn relative.startsWith(\"..\") ? relative : `./${relative}`;\n\t}\n\treturn absolute;\n});\n\n/** `reference` selects `entry` when any spelling of one is a spelling of the other. */\nexport const matches = (entry: Entry, spelled: ReadonlySet<string>) =>\n\t[...spelled].some((alias) => entry.answers.has(alias));\n\n/** Every entry connected to a reference through a package spelling or declared plugin ID. */\nexport const matching = (entries: ReadonlyArray<Entry>, spelled: ReadonlySet<string>) => {\n\tconst answers = new Set(spelled);\n\tconst found = new Set<Entry>();\n\tfor (;;) {\n\t\tconst next = entries.filter(\n\t\t\t(entry) => !found.has(entry) && [...entry.answers].some((answer) => answers.has(answer)),\n\t\t);\n\t\tif (next.length === 0) return found as ReadonlySet<Entry>;\n\t\tfor (const entry of next) {\n\t\t\tfound.add(entry);\n\t\t\tfor (const answer of entry.answers) answers.add(answer);\n\t\t}\n\t}\n};\n\nexport const readPlugins = Effect.fn(\"CLI.plugin.readPlugins\")(function* (path: string) {\n\tconst fs = yield* FileSystem.FileSystem;\n\tconst exists = yield* fs.exists(path);\n\tconst source = exists ? yield* fs.readFileString(path) : \"{}\";\n\tconst errors: ParseError[] = [];\n\tconst document: unknown = parseJsonc(source, errors, { allowTrailingComma: true });\n\tif (errors.length > 0 || typeof document !== \"object\" || document === null || Array.isArray(document)) {\n\t\treturn yield* new InvalidInputError({ message: `${path} is not a valid settings file` });\n\t}\n\tconst plugins = (document as { plugins?: unknown }).plugins;\n\tif (plugins !== undefined && !Array.isArray(plugins)) {\n\t\treturn yield* new InvalidInputError({ message: `${path}: \"plugins\" must be an array` });\n\t}\n\treturn { source, plugins: (plugins ?? []) as ReadonlyArray<unknown> };\n});\n\nexport const writePlugins = Effect.fn(\"CLI.plugin.writePlugins\")(function* (\n\tpath: string,\n\tsource: string,\n\tplugins: ReadonlyArray<unknown>,\n) {\n\tconst fs = yield* FileSystem.FileSystem;\n\tconst nodePath = yield* Path.Path;\n\tconst edited = applyEdits(\n\t\tsource,\n\t\tmodify(source, [\"plugins\"], plugins, { formattingOptions: { tabSize: 2, insertSpaces: false } }),\n\t);\n\tconst directory = nodePath.dirname(path);\n\tyield* fs.makeDirectory(directory, { recursive: true });\n\tconst mode = (yield* fs.exists(path)) ? (yield* fs.stat(path)).mode & 0o777 : 0o600;\n\tconst temporary = yield* fs.makeTempFile({ directory, prefix: `.${nodePath.basename(path)}.`, suffix: \".tmp\" });\n\tyield* fs\n\t\t.writeFileString(temporary, edited.endsWith(\"\\n\") ? edited : `${edited}\\n`)\n\t\t.pipe(\n\t\t\tEffect.andThen(fs.chmod(temporary, mode)),\n\t\t\tEffect.andThen(fs.rename(temporary, path)),\n\t\t\tEffect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)),\n\t\t);\n});\n\n/**\n * Serialize one settings read-modify-rename across CLI processes.\n *\n * The install or inspection that precedes an edit stays outside this scope; only the local edit is\n * locked, so unrelated downloads do not wait behind one another.\n */\nexport const withPluginsLock = <A, E, R>(path: string, edit: Effect.Effect<A, E, R>) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tconst nodePath = yield* Path.Path;\n\t\tyield* fs.makeDirectory(nodePath.dirname(path), { recursive: true });\n\t\tyield* Plugin.settingsLock(\n\t\t\t`${path}.lock`,\n\t\t\t() => new InvalidInputError({ message: `timed out waiting to edit ${path}` }),\n\t\t);\n\t\treturn yield* edit;\n\t}).pipe(Effect.scoped);\n\n/**\n * Which file the edit lands in.\n *\n * A plugin belongs to a project by default — it is part of how that repository is worked on, so\n * the entry belongs in a file the repository can commit. `--global` writes the user settings file\n * instead, the way `npm -g` installs outside a package: `<--home>/settings.jsonc`, or the\n * `--user-config-dir` one that replaces it.\n *\n * The project is found the way the harness finds it: the nearest ancestor holding a `.codework`\n * directory, so a command run from `packages/app` edits the repository's own file rather than\n * creating a second one beside it. When no ancestor has one, the project begins here -- the\n * directory is created and the caller is told, because that decision changes where every future\n * plugin entry lands, and a mistyped `cd` is the way it goes wrong.\n *\n * There is nothing to warn about between layers: plugin entries from every layer accumulate, so a\n * user-wide entry still applies inside a project that declares its own.\n */\nexport const resolveTarget = Effect.fn(\"CLI.plugin.resolveTarget\")(function* (\n\tshared: Shared,\n\tglobal: boolean,\n\t/**\n\t * Where to discover the project from, when it is not the shell's directory.\n\t *\n\t * A session's host directory is the only other honest answer: it is a declared host path. The\n\t * session's *space* is not, and neither is its project -- a `Project` is env-independent by\n\t * design, so it has no host directory to offer.\n\t */\n\tfrom?: string,\n\t/** Only `plugin add` may establish a project marker when no project exists yet. */\n\tcreate = true,\n) {\n\tconst fs = yield* FileSystem.FileSystem;\n\tconst nodePath = yield* Path.Path;\n\tconst hostCwd = nodePath.resolve(\".\");\n\t// The linked session's host directory, or -- with none -- the one the command runs in.\n\tconst hostDir = from ?? hostCwd;\n\tconst home = yield* Global.resolve(Option.isNone(shared.home) ? {} : { home: shared.home.value });\n\tconst root = global ? undefined : yield* Settings.projectRoot(hostDir, home.home);\n\t// `paths` is ordered lowest priority first: the user layer, then the project.\n\tconst groups = Settings.paths({\n\t\thome: home.home,\n\t\t...(root === undefined ? {} : { root }),\n\t\t...userLayer(shared, hostCwd),\n\t});\n\tconst chosen = global ? 0 : 1;\n\t// An empty group is the project layer saying there is no project above this directory. Then\n\t// this directory becomes one -- reported, not silent, because the marker shadows any outer\n\t// project from now on, so a `.codework/` created by a mistyped `cd` is worth spotting at once.\n\tconst found = groups[chosen] ?? [];\n\tif (found.length > 0) {\n\t\tconst existing = yield* Effect.findFirst(found, (candidate) => fs.exists(candidate));\n\t\treturn {\n\t\t\tpath: Option.getOrElse(existing, () => found[0]!),\n\t\t\t...(root === undefined ? {} : { root }),\n\t\t} satisfies Target;\n\t}\n\tconst marker = nodePath.join(hostDir, \".codework\");\n\t// `created` is reported either way: with `create` unset the marker is named, not made, so a\n\t// caller can say what its write is about to establish without establishing it early.\n\tif (!create)\n\t\treturn { path: nodePath.join(marker, \"settings.jsonc\"), created: marker, root: hostDir } satisfies Target;\n\tyield* fs.makeDirectory(marker, { recursive: true });\n\treturn { path: nodePath.join(marker, \"settings.jsonc\"), created: marker, root: hostDir } satisfies Target;\n});\n"],"mappings":";;;;;;;;;;AAwBA,MAAa,aAAa,QAAgB,YACzC,OAAO,OAAO,OAAO,aAAa,IAC/B,CAAC,IACD,EAAE,eAAe,SAAS,cAAc,OAAO,cAAc,OAAO,OAAO,EAAE;;AAWjF,MAAM,YAAY,UAAuC;CACxD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,KAAA;CACxD,MAAM,EAAE,SAAS,YAAY;CAC7B,OAAO,OAAO,YAAY,WAAW,UAAU,KAAA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O,OAAO,UAAU,QAAQ,cAAc,GAAG,OAAO,SAAS,CAAC;EACnF,OAAO;GACN,MAAM,OAAO,UAAU,gBAAgB,MAAM,EAAG;GAChD,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK;EACtC;CACD;CACA,MAAM,SAAS,SAAS,KAAK,SAAS,WAAW;CAGjD,IAAI,CAAC,QACJ,OAAO;EAAE,MAAM,SAAS,KAAK,QAAQ,gBAAgB;EAAG,SAAS;EAAQ,MAAM;CAAQ;CACxF,OAAO,GAAG,cAAc,QAAQ,EAAE,WAAW,KAAK,CAAC;CACnD,OAAO;EAAE,MAAM,SAAS,KAAK,QAAQ,gBAAgB;EAAG,SAAS;EAAQ,MAAM;CAAQ;AACxF,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { i as Cmd } from "./runtime-
|
|
2
|
-
import { f as layer, n as OAuthError, t as InvalidInputError } from "./error-
|
|
1
|
+
import { i as Cmd } from "./runtime-CIBm_3RX.mjs";
|
|
2
|
+
import { f as layer, n as OAuthError, t as InvalidInputError } from "./error-CzUxh0Q9.mjs";
|
|
3
3
|
import { Effect, Option, Path } from "effect";
|
|
4
4
|
import { Global } from "@codeworksh/harness/effect";
|
|
5
5
|
import { checkOAuthProvider, oauthProviderLabel, summarizeGitHubCopilot, summarizeOpenAICodex } from "@codeworksh/aikit/oauth/summary";
|
|
@@ -113,4 +113,4 @@ const withServer = (url, program) => program.pipe(Effect.provide(layer(url)), Ef
|
|
|
113
113
|
//#endregion
|
|
114
114
|
export { oauthProviderLabel as a, makeOps as i, attempt as n, selectProvider as o, localOps as r, withServer as s, assertServerScope as t };
|
|
115
115
|
|
|
116
|
-
//# sourceMappingURL=shared-
|
|
116
|
+
//# sourceMappingURL=shared-DjyUhNsi.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-
|
|
1
|
+
{"version":3,"file":"shared-DjyUhNsi.mjs","names":["Client.layer"],"sources":["../../src/cli/cmd/handlers/auth/shared.ts"],"sourcesContent":["/* @effect-diagnostics nodeBuiltinImport:off -- OAuth login opens the system browser. */\n/* @effect-diagnostics globalDate:off -- Stored expiry timestamps are rendered for the user. */\n/* oxlint-disable effecttsgo/async-function -- Aikit OAuth callbacks require Promise-returning functions. */\nimport {\n\tGitHubCopilotOAuthClient,\n\tJsonGitHubCopilotAuthStorage,\n\ttype GitHubCopilotAuthStorage,\n} from \"@codeworksh/aikit/oauth/github/copilot\";\nimport {\n\tJsonOpenAICodexAuthStorage,\n\tOpenAICodexOAuthClient,\n\ttype OpenAICodexAuthStorage,\n} from \"@codeworksh/aikit/oauth/openai/codex\";\nimport { openBrowser, promptLine } from \"@codeworksh/aikit/oauth/interactive\";\nimport {\n\tcheckOAuthProvider,\n\toauthProviderLabel,\n\tsummarizeGitHubCopilot,\n\tsummarizeOpenAICodex,\n\ttype OAuthSummary,\n} from \"@codeworksh/aikit/oauth/summary\";\nimport { Global } from \"@codeworksh/harness/effect\";\nimport { Effect, Option, Path } from \"effect\";\nimport { Client } from \"../../../../server/client.ts\";\nimport type { Contract } from \"../../../../server/contract.ts\";\nimport { InvalidInputError, OAuthError } from \"../../../error.ts\";\nimport { Cmd } from \"../../cmd.ts\";\n\nexport type Provider = Contract.OAuthProvider;\n\n// The wire shape and aikit's summary are the same record.\nexport type Summary = Contract.OAuthInfo & OAuthSummary;\n\nconst announce = (\n\tinfo: { url: string; userCode?: string | undefined; instructions?: string | undefined },\n\tbrowser: boolean,\n): void => {\n\tprocess.stderr.write(\n\t\t`${info.instructions ?? \"Complete authentication in your browser.\"}\\n${\n\t\t\tinfo.userCode === undefined ? \"\" : `Enter code: ${info.userCode}\\n`\n\t\t}${info.url}\\n`,\n\t);\n\tif (browser) {\n\t\tvoid openBrowser(info.url, (error) => void process.stderr.write(`Failed to open browser: ${error.message}\\n`));\n\t}\n};\n\nexport interface LoginOptions {\n\treadonly browser: boolean;\n\treadonly device: boolean;\n\treadonly enterprise: Option.Option<string>;\n\treadonly enableModels: boolean;\n}\n\nexport interface Ops {\n\treadonly path: string;\n\treadonly login: (options: LoginOptions) => Promise<{ wire: Contract.OAuthCredentials; summary: Summary }>;\n\treadonly stored: () => Promise<Summary | undefined>;\n\treadonly refreshed: () => Promise<Summary | undefined>;\n\treadonly logout: () => Promise<void>;\n}\n\n/** Holds nothing: a server's credentials live on the server, not on this disk. */\nconst transient: OpenAICodexAuthStorage & GitHubCopilotAuthStorage = {\n\tget: async () => undefined,\n\tset: async () => {},\n\tclear: async () => {},\n};\n\nconst codexOps = (storage: OpenAICodexAuthStorage, path: string): Ops => {\n\tconst client = new OpenAICodexOAuthClient({ storage });\n\treturn {\n\t\tpath,\n\t\tlogin: async (options) => {\n\t\t\tconst credentials = await client.login({\n\t\t\t\tdevice: options.device,\n\t\t\t\tonAuth: (info) => announce(info, options.browser),\n\t\t\t\tonProgress: (message) => void process.stderr.write(`${message}\\n`),\n\t\t\t\tonPrompt: (prompt) => promptLine(prompt.message),\n\t\t\t});\n\t\t\treturn { wire: { provider: \"openai-codex\", ...credentials }, summary: summarizeOpenAICodex(credentials) };\n\t\t},\n\t\tstored: async () => {\n\t\t\tconst credentials = await storage.get();\n\t\t\treturn credentials && summarizeOpenAICodex(credentials);\n\t\t},\n\t\trefreshed: async () => {\n\t\t\tconst credentials = await client.getCredentials();\n\t\t\treturn credentials && summarizeOpenAICodex(credentials);\n\t\t},\n\t\tlogout: () => client.logout(),\n\t};\n};\n\nconst copilotOps = (storage: GitHubCopilotAuthStorage, path: string): Ops => {\n\tconst client = new GitHubCopilotOAuthClient({ storage });\n\tconst read = async () => {\n\t\tconst credentials = await storage.get();\n\t\treturn credentials && summarizeGitHubCopilot(credentials);\n\t};\n\treturn {\n\t\tpath,\n\t\tlogin: async (options) => {\n\t\t\tconst credentials = await client.login({\n\t\t\t\t...(Option.isSome(options.enterprise) && { enterpriseUrl: options.enterprise.value }),\n\t\t\t\tenableModels: options.enableModels,\n\t\t\t\tonAuth: (info) => announce(info, options.browser),\n\t\t\t\tonProgress: (message) => void process.stderr.write(`${message}\\n`),\n\t\t\t});\n\t\t\treturn { wire: { provider: \"github-copilot\", ...credentials }, summary: summarizeGitHubCopilot(credentials) };\n\t\t},\n\t\tstored: read,\n\t\t// GitHub OAuth tokens never expire, so there is nothing to refresh.\n\t\trefreshed: read,\n\t\tlogout: () => client.logout(),\n\t};\n};\n\nexport const makeOps = (provider: Provider, options: { path?: string | undefined; persist?: boolean } = {}): Ops => {\n\tconst file = options.path === undefined ? {} : { path: options.path };\n\tif (provider === \"openai-codex\") {\n\t\tconst storage = options.persist === false ? undefined : new JsonOpenAICodexAuthStorage(file);\n\t\treturn codexOps(storage ?? transient, storage?.path ?? \"\");\n\t}\n\tconst storage = options.persist === false ? undefined : new JsonGitHubCopilotAuthStorage(file);\n\treturn copilotOps(storage ?? transient, storage?.path ?? \"\");\n};\n\nexport const attempt = <A>(message: string, run: () => Promise<A>) =>\n\tEffect.tryPromise({ try: run, catch: (cause) => new OAuthError({ message, cause }) });\n\n/** The provider named by the two mutually exclusive flags. */\nexport const selectProvider = (flags: {\n\treadonly openaiCodex: boolean;\n\treadonly githubCopilot: boolean;\n}): Effect.Effect<Provider, InvalidInputError> => {\n\tconst checked = checkOAuthProvider(flags);\n\treturn checked.ok\n\t\t? Effect.succeed(checked.provider)\n\t\t: Effect.fail(new InvalidInputError({ message: checked.message }));\n};\n\n/** Reject the local-credential flags when the credentials live on a server. */\nexport const assertServerScope = (authFile: Option.Option<string>) =>\n\tEffect.gen(function* () {\n\t\tconst shared = yield* Cmd.spec;\n\t\tif (Option.isSome(authFile) || Option.isSome(shared.home)) {\n\t\t\treturn yield* new InvalidInputError({\n\t\t\t\tmessage: \"--auth-file and --home belong on codework serve when using --server\",\n\t\t\t});\n\t\t}\n\t});\n\n/** Credential operations against this machine's auth.json. */\nexport const localOps = (provider: Provider, authFile: Option.Option<string>) =>\n\tEffect.gen(function* () {\n\t\tconst shared = yield* Cmd.spec;\n\t\tconst path = yield* Path.Path;\n\t\tconst file = Option.isSome(authFile)\n\t\t\t? authFile.value\n\t\t\t: Option.isSome(shared.home)\n\t\t\t\t? path.join((yield* Global.resolve({ home: shared.home.value })).home, \"aikit\", \"auth.json\")\n\t\t\t\t: undefined;\n\t\treturn makeOps(provider, file === undefined ? {} : { path: file });\n\t});\n\n/** Run an effect against the RPC server at `url`, discharging the client. */\nexport const withServer = <A, E, R>(url: string, program: Effect.Effect<A, E, R>) =>\n\tprogram.pipe(Effect.provide(Client.layer(url)), Effect.scoped);\n\nexport { Client, oauthProviderLabel };\n"],"mappings":";;;;;;;;;AAiCA,MAAM,YACL,MACA,YACU;CACV,QAAQ,OAAO,MACd,GAAG,KAAK,gBAAgB,2CAA2C,IAClE,KAAK,aAAa,KAAA,IAAY,KAAK,eAAe,KAAK,SAAS,MAC9D,KAAK,IAAI,GACb;CACA,IAAI,SACH,YAAiB,KAAK,MAAM,UAAU,KAAK,QAAQ,OAAO,MAAM,2BAA2B,MAAM,QAAQ,GAAG,CAAC;AAE/G;;AAkBA,MAAM,YAA+D;CACpE,KAAK,YAAY,KAAA;CACjB,KAAK,YAAY,CAAC;CAClB,OAAO,YAAY,CAAC;AACrB;AAEA,MAAM,YAAY,SAAiC,SAAsB;CACxE,MAAM,SAAS,IAAI,uBAAuB,EAAE,QAAQ,CAAC;CACrD,OAAO;EACN;EACA,OAAO,OAAO,YAAY;GACzB,MAAM,cAAc,MAAM,OAAO,MAAM;IACtC,QAAQ,QAAQ;IAChB,SAAS,SAAS,SAAS,MAAM,QAAQ,OAAO;IAChD,aAAa,YAAY,KAAK,QAAQ,OAAO,MAAM,GAAG,QAAQ,GAAG;IACjE,WAAW,WAAW,WAAW,OAAO,OAAO;GAChD,CAAC;GACD,OAAO;IAAE,MAAM;KAAE,UAAU;KAAgB,GAAG;IAAY;IAAG,SAAS,qBAAqB,WAAW;GAAE;EACzG;EACA,QAAQ,YAAY;GACnB,MAAM,cAAc,MAAM,QAAQ,IAAI;GACtC,OAAO,eA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KAAK;CAAK,QAAQ,UAAU,IAAI,WAAW;EAAE;EAAS;CAAM,CAAC;AAAE,CAAC;;AAGrF,MAAa,kBAAkB,UAGmB;CACjD,MAAM,UAAU,mBAAmB,KAAK;CACxC,OAAO,QAAQ,KACZ,OAAO,QAAQ,QAAQ,QAAQ,IAC/B,OAAO,KAAK,IAAI,kBAAkB,EAAE,SAAS,QAAQ,QAAQ,CAAC,CAAC;AACnE;;AAGA,MAAa,qBAAqB,aACjC,OAAO,IAAI,aAAa;CACvB,MAAM,SAAS,OAAO,IAAI;CAC1B,IAAI,OAAO,OAAO,QAAQ,KAAK,OAAO,OAAO,OAAO,IAAI,GACvD,OAAO,OAAO,IAAI,kBAAkB,EACnC,SAAS,sEACV,CAAC;AAEH,CAAC;;AAGF,MAAa,YAAY,UAAoB,aAC5C,OAAO,IAAI,aAAa;CACvB,MAAM,SAAS,OAAO,IAAI;CAC1B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,OAAO,OAAO,OAAO,QAAQ,IAChC,SAAS,QACT,OAAO,OAAO,OAAO,IAAI,IACxB,KAAK,MAAM,OAAO,OAAO,QAAQ,EAAE,MAAM,OAAO,KAAK,MAAM,CAAC,EAAA,CAAG,MAAM,SAAS,WAAW,IACzF,KAAA;CACJ,OAAO,QAAQ,UAAU,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,KAAK,CAAC;AAClE,CAAC;;AAGF,MAAa,cAAuB,KAAa,YAChD,QAAQ,KAAK,OAAO,QAAQA,MAAa,GAAG,CAAC,GAAG,OAAO,MAAM"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { i as Cmd, t as handler } from "./runtime-CIBm_3RX.mjs";
|
|
2
|
+
import { d as writeOut, i as reportFailure } from "./error-CzUxh0Q9.mjs";
|
|
3
|
+
import { i as ensure, n as options } from "./service-7_FrDOGJ.mjs";
|
|
4
|
+
import { Effect } from "effect";
|
|
5
|
+
//#region src/cli/cmd/handlers/service/start.ts
|
|
6
|
+
var start_default = handler(Cmd.commands.service.commands.start, Effect.fn("CLI.service.start")(function* ({ host, port }) {
|
|
7
|
+
const options$1 = yield* options(yield* Cmd.spec, {
|
|
8
|
+
host,
|
|
9
|
+
port
|
|
10
|
+
});
|
|
11
|
+
const server = yield* ensure({
|
|
12
|
+
...options$1,
|
|
13
|
+
replace: true
|
|
14
|
+
});
|
|
15
|
+
yield* writeOut(`${server.url}\n`);
|
|
16
|
+
}, Effect.catch(reportFailure)));
|
|
17
|
+
//#endregion
|
|
18
|
+
export { start_default as default };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=start-DcvqAhc4.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"start-DcvqAhc4.mjs","names":["Runtime.handler","options","Service.options","Discovery.ensure"],"sources":["../../src/cli/cmd/handlers/service/start.ts"],"sourcesContent":["import { Effect } from \"effect\";\nimport { Runtime } from \"../../../../framework/runtime.ts\";\nimport { Discovery } from \"../../../../server/discovery.ts\";\nimport { reportFailure } from \"../../../error.ts\";\nimport { writeOut } from \"../../../output.ts\";\nimport { Service } from \"../../../service.ts\";\nimport { Cmd } from \"../../cmd.ts\";\n\nexport default Runtime.handler(\n\tCmd.commands.service.commands.start,\n\tEffect.fn(\"CLI.service.start\")(function* ({ host, port }) {\n\t\tconst options = yield* Service.options(yield* Cmd.spec, { host, port });\n\t\tconst server = yield* Discovery.ensure({ ...options, replace: true });\n\t\tyield* writeOut(`${server.url}\\n`);\n\t}, Effect.catch(reportFailure)),\n);\n"],"mappings":";;;;;AAQA,IAAA,gBAAeA,QACd,IAAI,SAAS,QAAQ,SAAS,OAC9B,OAAO,GAAG,mBAAmB,CAAC,CAAC,WAAW,EAAE,MAAM,QAAQ;CACzD,MAAMC,YAAU,OAAOC,QAAgB,OAAO,IAAI,MAAM;EAAE;EAAM;CAAK,CAAC;CACtE,MAAM,SAAS,OAAOC,OAAiB;EAAE,GAAGF;EAAS,SAAS;CAAK,CAAC;CACpE,OAAO,SAAS,GAAG,OAAO,IAAI,GAAG;AAClC,GAAG,OAAO,MAAM,aAAa,CAAC,CAC/B"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { i as Cmd, t as handler } from "./runtime-CIBm_3RX.mjs";
|
|
2
|
+
import { d as writeOut, i as reportFailure } from "./error-CzUxh0Q9.mjs";
|
|
3
|
+
import { r as discover, t as home } from "./service-7_FrDOGJ.mjs";
|
|
4
|
+
import { Effect } from "effect";
|
|
5
|
+
//#region src/cli/cmd/handlers/service/status.ts
|
|
6
|
+
var status_default = handler(Cmd.commands.service.commands.status, Effect.fn("CLI.service.status")(function* () {
|
|
7
|
+
const paths = yield* home(yield* Cmd.spec);
|
|
8
|
+
const server = yield* discover(paths.home);
|
|
9
|
+
yield* writeOut(`${server?.url ?? "stopped"}\n`);
|
|
10
|
+
}, Effect.catch(reportFailure)));
|
|
11
|
+
//#endregion
|
|
12
|
+
export { status_default as default };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=status-9o_2AAAv.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"status-9o_2AAAv.mjs","names":["Runtime.handler","Service.home","Discovery.discover"],"sources":["../../src/cli/cmd/handlers/service/status.ts"],"sourcesContent":["import { Effect } from \"effect\";\nimport { Runtime } from \"../../../../framework/runtime.ts\";\nimport { Discovery } from \"../../../../server/discovery.ts\";\nimport { reportFailure } from \"../../../error.ts\";\nimport { writeOut } from \"../../../output.ts\";\nimport { Service } from \"../../../service.ts\";\nimport { Cmd } from \"../../cmd.ts\";\n\nexport default Runtime.handler(\n\tCmd.commands.service.commands.status,\n\tEffect.fn(\"CLI.service.status\")(function* () {\n\t\tconst paths = yield* Service.home(yield* Cmd.spec);\n\t\tconst server = yield* Discovery.discover(paths.home);\n\t\tyield* writeOut(`${server?.url ?? \"stopped\"}\\n`);\n\t}, Effect.catch(reportFailure)),\n);\n"],"mappings":";;;;;AAQA,IAAA,iBAAeA,QACd,IAAI,SAAS,QAAQ,SAAS,QAC9B,OAAO,GAAG,oBAAoB,CAAC,CAAC,aAAa;CAC5C,MAAM,QAAQ,OAAOC,KAAa,OAAO,IAAI,IAAI;CACjD,MAAM,SAAS,OAAOC,SAAmB,MAAM,IAAI;CACnD,OAAO,SAAS,GAAG,QAAQ,OAAO,UAAU,GAAG;AAChD,GAAG,OAAO,MAAM,aAAa,CAAC,CAC/B"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { i as Cmd, t as handler } from "./runtime-
|
|
2
|
-
import { d as writeOut, i as reportFailure, n as OAuthError, p as make } from "./error-
|
|
3
|
-
import { a as oauthProviderLabel, n as attempt, o as selectProvider, r as localOps, s as withServer, t as assertServerScope } from "./shared-
|
|
1
|
+
import { i as Cmd, t as handler } from "./runtime-CIBm_3RX.mjs";
|
|
2
|
+
import { d as writeOut, i as reportFailure, n as OAuthError, p as make } from "./error-CzUxh0Q9.mjs";
|
|
3
|
+
import { a as oauthProviderLabel, n as attempt, o as selectProvider, r as localOps, s as withServer, t as assertServerScope } from "./shared-DjyUhNsi.mjs";
|
|
4
4
|
import { Effect, Option } from "effect";
|
|
5
5
|
import { formatOAuthSummary, oauthNotice } from "@codeworksh/aikit/oauth/summary";
|
|
6
6
|
//#region src/cli/cmd/handlers/auth/status.ts
|
|
@@ -28,4 +28,4 @@ var status_default = handler(Cmd.commands.auth.commands.status, Effect.fn("CLI.a
|
|
|
28
28
|
//#endregion
|
|
29
29
|
export { status_default as default };
|
|
30
30
|
|
|
31
|
-
//# sourceMappingURL=status-
|
|
31
|
+
//# sourceMappingURL=status-BTCqpq7x.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"status-
|
|
1
|
+
{"version":3,"file":"status-BTCqpq7x.mjs","names":["Runtime.handler","Client.make"],"sources":["../../src/cli/cmd/handlers/auth/status.ts"],"sourcesContent":["import { formatOAuthSummary, oauthNotice } from \"@codeworksh/aikit/oauth/summary\";\nimport { Effect, Option } from \"effect\";\nimport { Runtime } from \"../../../../framework/runtime.ts\";\nimport { OAuthError, reportFailure } from \"../../../error.ts\";\nimport { writeOut } from \"../../../output.ts\";\nimport { Cmd } from \"../../cmd.ts\";\nimport {\n\tassertServerScope,\n\tattempt,\n\tClient,\n\tlocalOps,\n\toauthProviderLabel,\n\tselectProvider,\n\twithServer,\n} from \"./shared.ts\";\n\nexport default Runtime.handler(\n\tCmd.commands.auth.commands.status,\n\tEffect.fn(\"CLI.auth.status\")(function* ({ server, openaiCodex, githubCopilot, authFile, json }) {\n\t\tconst program = Effect.gen(function* () {\n\t\t\tconst provider = yield* selectProvider({ openaiCodex, githubCopilot });\n\t\t\tconst name = oauthProviderLabel(provider);\n\n\t\t\tif (Option.isSome(server)) {\n\t\t\t\tyield* assertServerScope(authFile);\n\t\t\t\treturn yield* withServer(\n\t\t\t\t\tserver.value,\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst rpc = yield* Client.make;\n\t\t\t\t\t\tconst info = yield* rpc[\"auth.status\"]({ provider });\n\t\t\t\t\t\tif (info === null) {\n\t\t\t\t\t\t\treturn yield* new OAuthError({ message: oauthNotice(\"missing\", provider, \"the server\") });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tyield* writeOut(formatOAuthSummary(info, { json }));\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst ops = yield* localOps(provider, authFile);\n\t\t\tconst summary = yield* attempt(`failed to read ${name} credentials`, () => ops.stored());\n\t\t\tif (summary === undefined) {\n\t\t\t\treturn yield* new OAuthError({ message: oauthNotice(\"missing\", provider, ops.path) });\n\t\t\t}\n\t\t\tyield* writeOut(formatOAuthSummary(summary, { json }));\n\t\t});\n\n\t\treturn yield* program.pipe(Effect.catch(reportFailure));\n\t}),\n);\n"],"mappings":";;;;;;AAgBA,IAAA,iBAAeA,QACd,IAAI,SAAS,KAAK,SAAS,QAC3B,OAAO,GAAG,iBAAiB,CAAC,CAAC,WAAW,EAAE,QAAQ,aAAa,eAAe,UAAU,QAAQ;CA4B/F,OAAO,OA3BS,OAAO,IAAI,aAAa;EACvC,MAAM,WAAW,OAAO,eAAe;GAAE;GAAa;EAAc,CAAC;EACrE,MAAM,OAAO,mBAAmB,QAAQ;EAExC,IAAI,OAAO,OAAO,MAAM,GAAG;GAC1B,OAAO,kBAAkB,QAAQ;GACjC,OAAO,OAAO,WACb,OAAO,OACP,OAAO,IAAI,aAAa;IAEvB,MAAM,OAAO,QAAO,OADDC,KAAAA,CACK,cAAc,CAAC,EAAE,SAAS,CAAC;IACnD,IAAI,SAAS,MACZ,OAAO,OAAO,IAAI,WAAW,EAAE,SAAS,YAAY,WAAW,UAAU,YAAY,EAAE,CAAC;IAEzF,OAAO,SAAS,mBAAmB,MAAM,EAAE,KAAK,CAAC,CAAC;GACnD,CAAC,CACF;EACD;EAEA,MAAM,MAAM,OAAO,SAAS,UAAU,QAAQ;EAC9C,MAAM,UAAU,OAAO,QAAQ,kBAAkB,KAAK,qBAAqB,IAAI,OAAO,CAAC;EACvF,IAAI,YAAY,KAAA,GACf,OAAO,OAAO,IAAI,WAAW,EAAE,SAAS,YAAY,WAAW,UAAU,IAAI,IAAI,EAAE,CAAC;EAErF,OAAO,SAAS,mBAAmB,SAAS,EAAE,KAAK,CAAC,CAAC;CACtD,CAEoB,CAAC,CAAC,KAAK,OAAO,MAAM,aAAa,CAAC;AACvD,CAAC,CACF"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { i as Cmd, t as handler } from "./runtime-CIBm_3RX.mjs";
|
|
2
|
+
import { i as reportFailure } from "./error-CzUxh0Q9.mjs";
|
|
3
|
+
import { o as stop, t as home } from "./service-7_FrDOGJ.mjs";
|
|
4
|
+
import { Effect } from "effect";
|
|
5
|
+
//#region src/cli/cmd/handlers/service/stop.ts
|
|
6
|
+
var stop_default = handler(Cmd.commands.service.commands.stop, Effect.fn("CLI.service.stop")(function* () {
|
|
7
|
+
const paths = yield* home(yield* Cmd.spec);
|
|
8
|
+
yield* stop(paths.home);
|
|
9
|
+
}, Effect.catch(reportFailure)));
|
|
10
|
+
//#endregion
|
|
11
|
+
export { stop_default as default };
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=stop-De_XWxXw.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stop-De_XWxXw.mjs","names":["Runtime.handler","Service.home","Discovery.stop"],"sources":["../../src/cli/cmd/handlers/service/stop.ts"],"sourcesContent":["import { Effect } from \"effect\";\nimport { Runtime } from \"../../../../framework/runtime.ts\";\nimport { Discovery } from \"../../../../server/discovery.ts\";\nimport { reportFailure } from \"../../../error.ts\";\nimport { Service } from \"../../../service.ts\";\nimport { Cmd } from \"../../cmd.ts\";\n\nexport default Runtime.handler(\n\tCmd.commands.service.commands.stop,\n\tEffect.fn(\"CLI.service.stop\")(function* () {\n\t\tconst paths = yield* Service.home(yield* Cmd.spec);\n\t\tyield* Discovery.stop(paths.home);\n\t}, Effect.catch(reportFailure)),\n);\n"],"mappings":";;;;;AAOA,IAAA,eAAeA,QACd,IAAI,SAAS,QAAQ,SAAS,MAC9B,OAAO,GAAG,kBAAkB,CAAC,CAAC,aAAa;CAC1C,MAAM,QAAQ,OAAOC,KAAa,OAAO,IAAI,IAAI;CACjD,OAAOC,KAAe,MAAM,IAAI;AACjC,GAAG,OAAO,MAAM,aAAa,CAAC,CAC/B"}
|
package/tui-B5RAnvTr.mjs
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { i as Cmd, t as handler } from "./runtime-CIBm_3RX.mjs";
|
|
2
|
+
import { r as renderError, t as InvalidInputError, u as writeError } from "./error-CzUxh0Q9.mjs";
|
|
3
|
+
import { n as current } from "./identity-B3FOHqbf.mjs";
|
|
4
|
+
import { a as keepAlive, i as ensure, n as options, s as probe } from "./service-7_FrDOGJ.mjs";
|
|
5
|
+
import { Effect, Option } from "effect";
|
|
6
|
+
import { ChildProcess, ChildProcessSpawner } from "effect/process";
|
|
7
|
+
//#region src/cli/cmd/handlers/tui.ts
|
|
8
|
+
/**
|
|
9
|
+
* Adopt a server the user started, only if it answers `server.info`: the UI must
|
|
10
|
+
* never launch against an endpoint that is not a CodeWork server. A different
|
|
11
|
+
* build is allowed, with a warning, because the user chose it.
|
|
12
|
+
*/
|
|
13
|
+
const attach = (url) => Effect.gen(function* () {
|
|
14
|
+
const info = yield* probe(url);
|
|
15
|
+
if (info === void 0) return yield* new InvalidInputError({ message: `no CodeWork server answered at ${url}` });
|
|
16
|
+
if (info.version !== current.version) yield* Effect.sync(() => process.stderr.write(`warning: server at ${url} runs ${info.version}; this client is ${current.version}\n`));
|
|
17
|
+
return url;
|
|
18
|
+
});
|
|
19
|
+
/** Start or reuse the local server, and keep it up while the TUI runs. */
|
|
20
|
+
const managed = (options) => Effect.gen(function* () {
|
|
21
|
+
const resolved = yield* ensure({
|
|
22
|
+
...options,
|
|
23
|
+
replace: true,
|
|
24
|
+
onStart: (reason) => void process.stderr.write(reason === "version-mismatch" ? "Restarting CodeWork server (version mismatch)...\n" : `Starting CodeWork server on ${options.host}:${options.port}...\n`)
|
|
25
|
+
});
|
|
26
|
+
yield* keepAlive(resolved, options).pipe(Effect.forkScoped);
|
|
27
|
+
return resolved.url;
|
|
28
|
+
});
|
|
29
|
+
/**
|
|
30
|
+
* Run the TUI in the foreground, on this terminal, for as long as this command
|
|
31
|
+
* runs. It stays in this process group (`detached: false`) so it keeps the
|
|
32
|
+
* terminal; stdio is inherited because it draws and reads raw keys itself. The
|
|
33
|
+
* scope is what ties their lifetimes: when this command is interrupted (SIGINT,
|
|
34
|
+
* SIGTERM), closing it terminates the TUI rather than leaving it on the screen.
|
|
35
|
+
*/
|
|
36
|
+
const run = (binary, args, env) => Effect.gen(function* () {
|
|
37
|
+
return yield* (yield* (yield* ChildProcessSpawner.ChildProcessSpawner).spawn(ChildProcess.make(binary, [...args], {
|
|
38
|
+
env,
|
|
39
|
+
extendEnv: true,
|
|
40
|
+
detached: false,
|
|
41
|
+
stdin: "inherit",
|
|
42
|
+
stdout: "inherit",
|
|
43
|
+
stderr: "inherit"
|
|
44
|
+
}))).exitCode.pipe(Effect.orElseSucceed(() => 1));
|
|
45
|
+
}).pipe(Effect.scoped);
|
|
46
|
+
var tui_default = handler(Cmd.commands.tui, Effect.fn("CLI.tui")(function* ({ server, host, port, args }) {
|
|
47
|
+
const shared = yield* Cmd.spec;
|
|
48
|
+
const code = yield* Effect.gen(function* () {
|
|
49
|
+
if (Option.isSome(server) && [
|
|
50
|
+
shared.home,
|
|
51
|
+
shared.database,
|
|
52
|
+
shared.userConfigDir
|
|
53
|
+
].some(Option.isSome)) return yield* new InvalidInputError({ message: "--home, --database, and --user-config-dir belong on codework serve when using --server" });
|
|
54
|
+
const options$1 = yield* options(shared, {
|
|
55
|
+
host,
|
|
56
|
+
port
|
|
57
|
+
});
|
|
58
|
+
const url = yield* Option.isSome(server) ? attach(server.value) : managed(options$1);
|
|
59
|
+
const launcher = yield* Effect.promise(() => import("@codeworksh/tui"));
|
|
60
|
+
const binary = yield* Effect.try({
|
|
61
|
+
try: () => launcher.resolveBinary(),
|
|
62
|
+
catch: (error) => new InvalidInputError({ message: error.message })
|
|
63
|
+
});
|
|
64
|
+
return yield* run(binary, args, {
|
|
65
|
+
[launcher.ENV_SERVER]: url,
|
|
66
|
+
CODEWORK_HOME_DIR: options$1.home
|
|
67
|
+
});
|
|
68
|
+
}).pipe(Effect.scoped, Effect.catch((error) => writeError(renderError(error)).pipe(Effect.as(1))));
|
|
69
|
+
yield* Effect.sync(() => {
|
|
70
|
+
process.exitCode = code;
|
|
71
|
+
});
|
|
72
|
+
}));
|
|
73
|
+
//#endregion
|
|
74
|
+
export { tui_default as default };
|
|
75
|
+
|
|
76
|
+
//# sourceMappingURL=tui-B5RAnvTr.mjs.map
|