@tafrahq/wt-tunnel-client 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +166 -2
  3. package/dist/bin.js +15 -0
  4. package/dist/bin.js.map +1 -0
  5. package/dist/cli-commands.js +27 -0
  6. package/dist/cli-commands.js.map +1 -0
  7. package/dist/cli-provision.js +25 -0
  8. package/dist/cli-provision.js.map +1 -0
  9. package/dist/cli-status.js +19 -0
  10. package/dist/cli-status.js.map +1 -0
  11. package/dist/cli-workspace.js +38 -0
  12. package/dist/cli-workspace.js.map +1 -0
  13. package/dist/cli-worktree.js +40 -0
  14. package/dist/cli-worktree.js.map +1 -0
  15. package/dist/cli.js +9 -0
  16. package/dist/cli.js.map +1 -0
  17. package/dist/config.js +70 -0
  18. package/dist/config.js.map +1 -0
  19. package/dist/domain.js +26 -0
  20. package/dist/domain.js.map +1 -0
  21. package/dist/errno.js +6 -0
  22. package/dist/errno.js.map +1 -0
  23. package/dist/errors.js +7 -0
  24. package/dist/errors.js.map +1 -0
  25. package/dist/exec.js +18 -0
  26. package/dist/exec.js.map +1 -0
  27. package/dist/files.js +18 -0
  28. package/dist/files.js.map +1 -0
  29. package/dist/frpc-binary.js +16 -0
  30. package/dist/frpc-binary.js.map +1 -0
  31. package/dist/frpc-config.js +47 -0
  32. package/dist/frpc-config.js.map +1 -0
  33. package/dist/packages/binaries/src/frp.js +45 -0
  34. package/dist/packages/binaries/src/frp.js.map +1 -0
  35. package/dist/packages/binaries/src/install.js +110 -0
  36. package/dist/packages/binaries/src/install.js.map +1 -0
  37. package/dist/packages/contract/src/index.js +12 -0
  38. package/dist/packages/contract/src/index.js.map +1 -0
  39. package/dist/ports.js +121 -0
  40. package/dist/ports.js.map +1 -0
  41. package/dist/processes.js +118 -0
  42. package/dist/processes.js.map +1 -0
  43. package/dist/provision-frpc.js +100 -0
  44. package/dist/provision-frpc.js.map +1 -0
  45. package/dist/provision-ports.js +75 -0
  46. package/dist/provision-ports.js.map +1 -0
  47. package/dist/provision.js +28 -0
  48. package/dist/provision.js.map +1 -0
  49. package/dist/state.js +53 -0
  50. package/dist/state.js.map +1 -0
  51. package/dist/worktree.js +25 -0
  52. package/dist/worktree.js.map +1 -0
  53. package/llms.txt +33 -0
  54. package/package.json +63 -3
  55. package/src/bin.ts +28 -0
  56. package/src/cli-commands.ts +40 -0
  57. package/src/cli-provision.ts +34 -0
  58. package/src/cli-status.ts +29 -0
  59. package/src/cli-workspace.ts +78 -0
  60. package/src/cli-worktree.ts +62 -0
  61. package/src/cli.ts +15 -0
  62. package/src/config.ts +101 -0
  63. package/src/domain.ts +51 -0
  64. package/src/errno.ts +5 -0
  65. package/src/errors.ts +13 -0
  66. package/src/exec.ts +18 -0
  67. package/src/files.ts +20 -0
  68. package/src/frpc-binary.ts +27 -0
  69. package/src/frpc-config.ts +69 -0
  70. package/src/ports.ts +177 -0
  71. package/src/processes.ts +163 -0
  72. package/src/provision-frpc.ts +152 -0
  73. package/src/provision-ports.ts +116 -0
  74. package/src/provision.ts +41 -0
  75. package/src/resource.ts +28 -0
  76. package/src/state.ts +87 -0
  77. package/src/worktree.ts +52 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files.js","names":[],"sources":["../src/files.ts"],"sourcesContent":["import { access, readFile } from 'node:fs/promises';\n\n/** Like `existsSync`: false for any path that cannot be accessed. */\nconst pathExists = async (path: string) => {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n};\n\nconst readTextIfExists = async (file: string): Promise<string | undefined> => {\n if (!(await pathExists(file))) {\n return undefined;\n }\n return readFile(file, 'utf8');\n};\n\nexport { pathExists, readTextIfExists };\n"],"mappings":";;;AAGA,MAAM,aAAa,OAAO,SAAiB;CACzC,IAAI;EACF,MAAM,OAAO,IAAI;EACjB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,mBAAmB,OAAO,SAA8C;CAC5E,IAAI,CAAE,MAAM,WAAW,IAAI,GACzB;CAEF,OAAO,SAAS,MAAM,MAAM;AAC9B"}
@@ -0,0 +1,16 @@
1
+ import { WtTunnelError } from "./errors.js";
2
+ import { cacheHome, pinnedBinary } from "./packages/binaries/src/install.js";
3
+ import { frpPin } from "./packages/binaries/src/frp.js";
4
+ import { Effect } from "effect";
5
+ import { join } from "node:path";
6
+ // src/frpc-binary.ts
7
+ const pin = frpPin("frpc");
8
+ /** `WT_TUNNEL_FRPC`, else the cached frpc, downloaded on first use. */
9
+ const frpcBinary = Effect.suspend(() => {
10
+ const override = process.env.WT_TUNNEL_FRPC;
11
+ if (override !== void 0 && override !== "") return Effect.succeed(override);
12
+ return pinnedBinary(pin, join(cacheHome(), "wt-tunnel", "frp", pin.version, "frpc")).pipe(Effect.mapError(({ message }) => new WtTunnelError({ message: `${message} Set WT_TUNNEL_FRPC to an frpc ${pin.version} binary instead.` })));
13
+ });
14
+ export { frpcBinary };
15
+
16
+ //# sourceMappingURL=frpc-binary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frpc-binary.js","names":[],"sources":["../src/frpc-binary.ts"],"sourcesContent":["import { join } from 'node:path';\n\nimport { cacheHome, pinnedBinary } from '@tafrahq/wt-tunnel-binaries';\nimport { frpPin } from '@tafrahq/wt-tunnel-binaries/frp';\nimport { Effect } from 'effect';\n\nimport { WtTunnelError } from './errors.ts';\n\nconst pin = frpPin('frpc');\n\n/** `WT_TUNNEL_FRPC`, else the cached frpc, downloaded on first use. */\nconst frpcBinary = Effect.suspend(() => {\n const override = process.env.WT_TUNNEL_FRPC;\n if (override !== undefined && override !== '') {\n return Effect.succeed(override);\n }\n return pinnedBinary(pin, join(cacheHome(), 'wt-tunnel', 'frp', pin.version, 'frpc')).pipe(\n Effect.mapError(\n ({ message }: { readonly message: string }) =>\n new WtTunnelError({\n message: `${message} Set WT_TUNNEL_FRPC to an frpc ${pin.version} binary instead.`,\n }),\n ),\n );\n});\n\nexport { frpcBinary };\n"],"mappings":";;;;;;AAQA,MAAM,MAAM,OAAO,MAAM;;AAGzB,MAAM,aAAa,OAAO,cAAc;CACtC,MAAM,WAAW,QAAQ,IAAI;CAC7B,IAAI,aAAa,KAAA,KAAa,aAAa,IACzC,OAAO,OAAO,QAAQ,QAAQ;CAEhC,OAAO,aAAa,KAAK,KAAK,UAAU,GAAG,aAAa,OAAO,IAAI,SAAS,MAAM,CAAC,CAAC,CAAC,KACnF,OAAO,UACJ,EAAE,cACD,IAAI,cAAc,EAChB,SAAS,GAAG,QAAQ,iCAAiC,IAAI,QAAQ,kBACnE,CAAC,CACL,CACF;AACF,CAAC"}
@@ -0,0 +1,47 @@
1
+ import "./packages/contract/src/index.js";
2
+ import { WtTunnelError } from "./errors.js";
3
+ import { Effect, Redacted } from "effect";
4
+ // src/frpc-config.ts
5
+ const tokenEnv = "WT_TUNNEL_SERVER_TOKEN";
6
+ /** `host:port` of frps, with an IPv6 address in brackets as in a URL. */
7
+ const serverEndpoint = (server) => {
8
+ return `${server.host.includes(":") ? `[${server.host}]` : server.host}:${server.port ?? 7e3}`;
9
+ };
10
+ /** JSON's string escapes are valid in TOML basic strings. */
11
+ const tomlString = (value) => JSON.stringify(value);
12
+ const proxyLines = ({ app, hostname, port }) => [
13
+ "",
14
+ "[[proxies]]",
15
+ `name = ${tomlString(app)}`,
16
+ "type = \"http\"",
17
+ "localIP = \"127.0.0.1\"",
18
+ `localPort = ${port}`,
19
+ `customDomains = [${tomlString(hostname)}]`
20
+ ];
21
+ /**
22
+ * The config of a worktree's frpc. The token is a frp template that frpc fills in from its
23
+ * environment when it reads the file, so the token is never written down.
24
+ */
25
+ const renderFrpcConfig = (server, worktree, apps) => [
26
+ "# Written by wt-tunnel-client up.",
27
+ `serverAddr = ${tomlString(server.host)}`,
28
+ `serverPort = ${server.port ?? 7e3}`,
29
+ `user = ${tomlString(`${worktree.project}.${worktree.name}`)}`,
30
+ "loginFailExit = true",
31
+ "auth.method = \"token\"",
32
+ `auth.token = "{{ .Envs.${tokenEnv} }}"`,
33
+ "transport.tls.enable = true",
34
+ "log.to = \"console\"",
35
+ "log.disablePrintColor = true",
36
+ ...apps.flatMap((app) => proxyLines(app)),
37
+ ""
38
+ ].join("\n");
39
+ const serverToken = Effect.suspend(() => {
40
+ const token = process.env[tokenEnv];
41
+ return token === void 0 || token === "" ? Effect.fail(new WtTunnelError({ message: `Set ${tokenEnv} to the tunnel server's token (tunnelToken in its config).` })) : Effect.succeed(Redacted.make(token));
42
+ });
43
+ /** The environment that hands the token to frpc. */
44
+ const tokenEnvironment = (token) => ({ [tokenEnv]: Redacted.value(token) });
45
+ export { renderFrpcConfig, serverEndpoint, serverToken, tokenEnvironment };
46
+
47
+ //# sourceMappingURL=frpc-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frpc-config.js","names":[],"sources":["../src/frpc-config.ts"],"sourcesContent":["import { tunnelPort } from '@tafrahq/wt-tunnel-contract';\nimport { Effect, Redacted } from 'effect';\n\nimport type { ServerConfig } from './config.ts';\nimport { WtTunnelError } from './errors.ts';\nimport type { RoutedApp } from './provision-ports.ts';\nimport type { Worktree } from './worktree.ts';\n\nconst tokenEnv = 'WT_TUNNEL_SERVER_TOKEN';\n\n/** `host:port` of frps, with an IPv6 address in brackets as in a URL. */\nconst serverEndpoint = (server: ServerConfig) => {\n const host = server.host.includes(':') ? `[${server.host}]` : server.host;\n return `${host}:${server.port ?? tunnelPort}`;\n};\n\n/** JSON's string escapes are valid in TOML basic strings. */\nconst tomlString = (value: string) => JSON.stringify(value);\n\nconst proxyLines = ({ app, hostname, port }: RoutedApp) => [\n '',\n '[[proxies]]',\n `name = ${tomlString(app)}`,\n 'type = \"http\"',\n 'localIP = \"127.0.0.1\"',\n `localPort = ${port}`,\n `customDomains = [${tomlString(hostname)}]`,\n];\n\n/**\n * The config of a worktree's frpc. The token is a frp template that frpc fills in from its\n * environment when it reads the file, so the token is never written down.\n */\nconst renderFrpcConfig = (\n server: ServerConfig,\n worktree: Pick<Worktree, 'name' | 'project'>,\n apps: readonly RoutedApp[],\n) =>\n [\n '# Written by wt-tunnel-client up.',\n `serverAddr = ${tomlString(server.host)}`,\n `serverPort = ${server.port ?? tunnelPort}`,\n // The server names each proxy `<user>.<name>`. DNS labels hold no dot, so no two apps share one.\n `user = ${tomlString(`${worktree.project}.${worktree.name}`)}`,\n 'loginFailExit = true',\n 'auth.method = \"token\"',\n `auth.token = \"{{ .Envs.${tokenEnv} }}\"`,\n 'transport.tls.enable = true',\n 'log.to = \"console\"',\n 'log.disablePrintColor = true',\n ...apps.flatMap((app) => proxyLines(app)),\n '',\n ].join('\\n');\n\nconst serverToken = Effect.suspend(() => {\n const token = process.env[tokenEnv];\n return token === undefined || token === ''\n ? Effect.fail(\n new WtTunnelError({\n message: `Set ${tokenEnv} to the tunnel server's token (tunnelToken in its config).`,\n }),\n )\n : Effect.succeed(Redacted.make(token));\n});\n\n/** The environment that hands the token to frpc. */\nconst tokenEnvironment = (token: Redacted.Redacted) => ({ [tokenEnv]: Redacted.value(token) });\n\nexport { renderFrpcConfig, serverEndpoint, serverToken, tokenEnvironment };\n"],"mappings":";;;;AAQA,MAAM,WAAW;;AAGjB,MAAM,kBAAkB,WAAyB;CAE/C,OAAO,GADM,OAAO,KAAK,SAAS,GAAG,IAAI,IAAI,OAAO,KAAK,KAAK,OAAO,KACtD,GAAG,OAAO,QAAA;AAC3B;;AAGA,MAAM,cAAc,UAAkB,KAAK,UAAU,KAAK;AAE1D,MAAM,cAAc,EAAE,KAAK,UAAU,WAAsB;CACzD;CACA;CACA,UAAU,WAAW,GAAG;CACxB;CACA;CACA,eAAe;CACf,oBAAoB,WAAW,QAAQ,EAAE;AAC3C;;;;;AAMA,MAAM,oBACJ,QACA,UACA,SAEA;CACE;CACA,gBAAgB,WAAW,OAAO,IAAI;CACtC,gBAAgB,OAAO,QAAA;CAEvB,UAAU,WAAW,GAAG,SAAS,QAAQ,GAAG,SAAS,MAAM;CAC3D;CACA;CACA,0BAA0B,SAAS;CACnC;CACA;CACA;CACA,GAAG,KAAK,SAAS,QAAQ,WAAW,GAAG,CAAC;CACxC;AACF,CAAC,CAAC,KAAK,IAAI;AAEb,MAAM,cAAc,OAAO,cAAc;CACvC,MAAM,QAAQ,QAAQ,IAAI;CAC1B,OAAO,UAAU,KAAA,KAAa,UAAU,KACpC,OAAO,KACL,IAAI,cAAc,EAChB,SAAS,OAAO,SAAS,4DAC3B,CAAC,CACH,IACA,OAAO,QAAQ,SAAS,KAAK,KAAK,CAAC;AACzC,CAAC;;AAGD,MAAM,oBAAoB,WAA8B,GAAG,WAAW,SAAS,MAAM,KAAK,EAAE"}
@@ -0,0 +1,45 @@
1
+ // ../../packages/binaries/src/frp.ts
2
+ const frpVersion = "0.71.1";
3
+ /** Node's `process.arch` names to Go's, which frp's release names use. */
4
+ const goArch = {
5
+ arm64: "arm64",
6
+ x64: "amd64"
7
+ };
8
+ /** From the release's frp_sha256_checksums.txt. A tarball that does not match is never unpacked. */
9
+ const frpTarballs = [
10
+ [
11
+ "darwin",
12
+ "x64",
13
+ "8acb59b6fb998cc8d209d1373d90bf70fa5ec3efeb4dfbc7bda6ce3abd78cb45"
14
+ ],
15
+ [
16
+ "darwin",
17
+ "arm64",
18
+ "d15d0324b99e14619c9aa46e37f6db588c06a09be4bc6f7948890b6b61077842"
19
+ ],
20
+ [
21
+ "linux",
22
+ "x64",
23
+ "1d9875210972a5d1a62b2dc4c48df45ab0af05d3ca1b5e494a014428259df803"
24
+ ],
25
+ [
26
+ "linux",
27
+ "arm64",
28
+ "8edf590b0c396fa42f9c147121a76af83cfc2002b08f5aef0ea1008c43482019"
29
+ ]
30
+ ];
31
+ /**
32
+ * One frp tarball holds both frpc and frps, so the client's frpc and the server's frps come from
33
+ * one pinned release.
34
+ */
35
+ const frpPin = (name) => ({
36
+ name,
37
+ tarballs: Object.fromEntries(frpTarballs.map(([platform, arch, sha256]) => [`${platform}-${arch}`, {
38
+ sha256,
39
+ url: `https://github.com/fatedier/frp/releases/download/v${frpVersion}/frp_${frpVersion}_${platform}_${goArch[arch]}.tar.gz`
40
+ }])),
41
+ version: frpVersion
42
+ });
43
+ export { frpPin };
44
+
45
+ //# sourceMappingURL=frp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frp.js","names":[],"sources":["../../../../../../packages/binaries/src/frp.ts"],"sourcesContent":["import type { Pin } from './install.ts';\n\nconst frpVersion = '0.71.1';\n\n/** Node's `process.arch` names to Go's, which frp's release names use. */\nconst goArch = { arm64: 'arm64', x64: 'amd64' } as const;\n\n/** From the release's frp_sha256_checksums.txt. A tarball that does not match is never unpacked. */\nconst frpTarballs = [\n ['darwin', 'x64', '8acb59b6fb998cc8d209d1373d90bf70fa5ec3efeb4dfbc7bda6ce3abd78cb45'],\n ['darwin', 'arm64', 'd15d0324b99e14619c9aa46e37f6db588c06a09be4bc6f7948890b6b61077842'],\n ['linux', 'x64', '1d9875210972a5d1a62b2dc4c48df45ab0af05d3ca1b5e494a014428259df803'],\n ['linux', 'arm64', '8edf590b0c396fa42f9c147121a76af83cfc2002b08f5aef0ea1008c43482019'],\n] as const;\n\n/**\n * One frp tarball holds both frpc and frps, so the client's frpc and the server's frps come from\n * one pinned release.\n */\nconst frpPin = (name: 'frpc' | 'frps'): Pin => ({\n name,\n tarballs: Object.fromEntries(\n frpTarballs.map(([platform, arch, sha256]) => [\n `${platform}-${arch}`,\n {\n sha256,\n url: `https://github.com/fatedier/frp/releases/download/v${frpVersion}/frp_${frpVersion}_${platform}_${goArch[arch]}.tar.gz`,\n },\n ]),\n ),\n version: frpVersion,\n});\n\nexport { frpPin };\n"],"mappings":";AAEA,MAAM,aAAa;;AAGnB,MAAM,SAAS;CAAE,OAAO;CAAS,KAAK;AAAQ;;AAG9C,MAAM,cAAc;CAClB;EAAC;EAAU;EAAO;CAAkE;CACpF;EAAC;EAAU;EAAS;CAAkE;CACtF;EAAC;EAAS;EAAO;CAAkE;CACnF;EAAC;EAAS;EAAS;CAAkE;AACvF;;;;;AAMA,MAAM,UAAU,UAAgC;CAC9C;CACA,UAAU,OAAO,YACf,YAAY,KAAK,CAAC,UAAU,MAAM,YAAY,CAC5C,GAAG,SAAS,GAAG,QACf;EACE;EACA,KAAK,sDAAsD,WAAW,OAAO,WAAW,GAAG,SAAS,GAAG,OAAO,MAAM;CACtH,CACF,CAAC,CACH;CACA,SAAS;AACX"}
@@ -0,0 +1,110 @@
1
+ import { Console, Effect, Schema } from "effect";
2
+ import { access, chmod, mkdir, rename, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { homedir } from "node:os";
5
+ import { createHash } from "node:crypto";
6
+ import { promisify } from "node:util";
7
+ import { gunzip } from "node:zlib";
8
+ // ../../packages/binaries/src/install.ts
9
+ const { TaggedError: taggedErrorClass } = Schema;
10
+ var InstallError = class extends taggedErrorClass()("InstallError", { message: Schema.String }) {};
11
+ const executableMode = 493;
12
+ const tarBlock = 512;
13
+ const tarName = {
14
+ end: 100,
15
+ start: 0
16
+ };
17
+ const tarSize = {
18
+ end: 136,
19
+ start: 124
20
+ };
21
+ const tarType = {
22
+ end: 157,
23
+ start: 156
24
+ };
25
+ const octal = 8;
26
+ /** Old tar writes NUL, ustar writes '0', for a regular file. */
27
+ const regularFileTypes = /* @__PURE__ */ new Set(["0", "\0"]);
28
+ /** A header block's fields; undefined for the zero block that ends the archive. */
29
+ const tarHeader = (block) => {
30
+ const path = block.toString("utf8", tarName.start, tarName.end).replace(/\0.*$/su, "");
31
+ const size = Number.parseInt(block.toString("ascii", tarSize.start, tarSize.end).trim(), octal);
32
+ if (path === "" || Number.isNaN(size)) return;
33
+ return {
34
+ path,
35
+ regularFile: regularFileTypes.has(block.toString("ascii", tarType.start, tarType.end)),
36
+ size
37
+ };
38
+ };
39
+ /**
40
+ * The bytes of the regular file named `name` (in any directory) in a tar archive. Reading the one
41
+ * entry in process means nothing in the archive decides which paths get written.
42
+ */
43
+ const tarEntry = (archive, name) => {
44
+ let offset = 0;
45
+ while (offset + tarBlock <= archive.length) {
46
+ const header = tarHeader(archive.subarray(offset, offset + tarBlock));
47
+ if (header === void 0) return;
48
+ const data = offset + tarBlock;
49
+ if (header.regularFile && basename(header.path) === name) return archive.subarray(data, data + header.size);
50
+ offset = data + Math.ceil(header.size / tarBlock) * tarBlock;
51
+ }
52
+ };
53
+ const fetchBytes = async (url) => {
54
+ const response = await fetch(url);
55
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
56
+ return new Uint8Array(await response.arrayBuffer());
57
+ };
58
+ const installFailed = (pin, message) => new InstallError({ message: `Could not install ${pin.name}: ${message}` });
59
+ /** The rename is atomic, so a concurrent install sees no file or a complete one. */
60
+ const placeExecutable = async (destination, bytes) => {
61
+ await mkdir(dirname(destination), { recursive: true });
62
+ const temp = `${destination}.${process.pid}.tmp`;
63
+ await writeFile(temp, bytes);
64
+ await chmod(temp, executableMode);
65
+ await rename(temp, destination);
66
+ };
67
+ const verifiedDownload = (pin, tarball, download) => Effect.gen(function* downloadThenHash() {
68
+ yield* Console.log(`Downloading ${pin.name} ${pin.version} from ${tarball.url}`);
69
+ const bytes = yield* Effect.tryPromise({
70
+ catch: (cause) => installFailed(pin, `${tarball.url}: ${String(cause)}`),
71
+ try: () => download(tarball.url)
72
+ });
73
+ const actual = createHash("sha256").update(bytes).digest("hex");
74
+ if (actual !== tarball.sha256) return yield* installFailed(pin, `${tarball.url} has SHA-256 ${actual}, expected ${tarball.sha256}. Nothing was installed.`);
75
+ return bytes;
76
+ });
77
+ /** Downloads the tarball, checks its SHA-256, and moves only the pinned executable into place. */
78
+ const installTarballEntry = (pin, { destination, download, tarball }) => Effect.gen(function* downloadVerifyExtract() {
79
+ const bytes = yield* verifiedDownload(pin, tarball, download);
80
+ const archive = yield* Effect.promise(() => promisify(gunzip)(bytes));
81
+ const executable = tarEntry(archive, pin.name);
82
+ if (executable === void 0) return yield* installFailed(pin, `${tarball.url} holds no ${pin.name}.`);
83
+ yield* Effect.promise(() => placeExecutable(destination, executable));
84
+ return destination;
85
+ });
86
+ const tarballFor = (pin, platform, arch) => pin.tarballs[`${platform}-${arch}`];
87
+ /** The user's cache directory: `$XDG_CACHE_HOME`, else the platform's usual place. */
88
+ const cacheHome = () => process.env.XDG_CACHE_HOME ?? (process.platform === "darwin" ? join(homedir(), "Library", "Caches") : join(homedir(), ".cache"));
89
+ const exists = (path) => Effect.promise(async () => {
90
+ try {
91
+ await access(path);
92
+ return true;
93
+ } catch {
94
+ return false;
95
+ }
96
+ });
97
+ /** The executable at `destination`, downloaded there on first use. */
98
+ const pinnedBinary = (pin, destination) => Effect.gen(function* cachedOrDownload() {
99
+ if (yield* exists(destination)) return destination;
100
+ const tarball = tarballFor(pin, process.platform, process.arch);
101
+ if (tarball === void 0) return yield* installFailed(pin, `no pinned ${pin.version} build for ${process.platform} ${process.arch}.`);
102
+ return yield* installTarballEntry(pin, {
103
+ destination,
104
+ download: fetchBytes,
105
+ tarball
106
+ });
107
+ });
108
+ export { InstallError, cacheHome, installTarballEntry, pinnedBinary, tarballFor };
109
+
110
+ //# sourceMappingURL=install.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"install.js","names":[],"sources":["../../../../../../packages/binaries/src/install.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { access, chmod, mkdir, rename, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { gunzip } from 'node:zlib';\n\nimport { Console, Effect, Schema } from 'effect';\n\n/*\n * The alias stops `unicorn/throw-new-error` from reading this class factory, whose name ends in\n * `Error`, as an error thrown without `new`.\n */\nconst { TaggedError: taggedErrorClass } = Schema;\n\nclass InstallError extends taggedErrorClass<InstallError>()('InstallError', {\n message: Schema.String,\n}) {}\n\n/** A release tarball and the SHA-256 it must have. */\ninterface Tarball {\n readonly sha256: string;\n readonly url: string;\n}\n\n/** One executable at one version, with a tarball per `<process.platform>-<process.arch>`. */\ninterface Pin {\n readonly name: string;\n readonly tarballs: Readonly<Partial<Record<string, Tarball>>>;\n readonly version: string;\n}\n\nconst executableMode = 0o755;\n\nconst tarBlock = 512;\nconst tarName = { end: 100, start: 0 } as const;\nconst tarSize = { end: 136, start: 124 } as const;\nconst tarType = { end: 157, start: 156 } as const;\nconst octal = 8;\n/** Old tar writes NUL, ustar writes '0', for a regular file. */\nconst regularFileTypes: ReadonlySet<string> = new Set(['0', '\\0']);\n\n/** A header block's fields; undefined for the zero block that ends the archive. */\nconst tarHeader = (\n block: Buffer,\n): { readonly path: string; readonly regularFile: boolean; readonly size: number } | undefined => {\n const path = block.toString('utf8', tarName.start, tarName.end).replace(/\\0.*$/su, '');\n const size = Number.parseInt(block.toString('ascii', tarSize.start, tarSize.end).trim(), octal);\n if (path === '' || Number.isNaN(size)) {\n return undefined;\n }\n const regularFile = regularFileTypes.has(block.toString('ascii', tarType.start, tarType.end));\n return { path, regularFile, size };\n};\n\n/**\n * The bytes of the regular file named `name` (in any directory) in a tar archive. Reading the one\n * entry in process means nothing in the archive decides which paths get written.\n */\nconst tarEntry = (archive: Buffer, name: string): Buffer | undefined => {\n let offset = 0;\n while (offset + tarBlock <= archive.length) {\n const header = tarHeader(archive.subarray(offset, offset + tarBlock));\n if (header === undefined) {\n return undefined;\n }\n const data = offset + tarBlock;\n if (header.regularFile && basename(header.path) === name) {\n return archive.subarray(data, data + header.size);\n }\n offset = data + Math.ceil(header.size / tarBlock) * tarBlock;\n }\n return undefined;\n};\n\ntype FetchBytes = (url: string) => Promise<Uint8Array>;\n\nconst fetchBytes: FetchBytes = async (url) => {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n return new Uint8Array(await response.arrayBuffer());\n};\n\nconst installFailed = (pin: Pin, message: string) =>\n new InstallError({ message: `Could not install ${pin.name}: ${message}` });\n\n/** The rename is atomic, so a concurrent install sees no file or a complete one. */\nconst placeExecutable = async (destination: string, bytes: Buffer) => {\n await mkdir(dirname(destination), { recursive: true });\n const temp = `${destination}.${process.pid}.tmp`;\n await writeFile(temp, bytes);\n await chmod(temp, executableMode);\n await rename(temp, destination);\n};\n\nconst verifiedDownload = (pin: Pin, tarball: Tarball, download: FetchBytes) =>\n Effect.gen(function* downloadThenHash() {\n yield* Console.log(`Downloading ${pin.name} ${pin.version} from ${tarball.url}`);\n const bytes = yield* Effect.tryPromise({\n catch: (cause) => installFailed(pin, `${tarball.url}: ${String(cause)}`),\n try: () => download(tarball.url),\n });\n const actual = createHash('sha256').update(bytes).digest('hex');\n if (actual !== tarball.sha256) {\n return yield* installFailed(\n pin,\n `${tarball.url} has SHA-256 ${actual}, expected ${tarball.sha256}. Nothing was installed.`,\n );\n }\n return bytes;\n });\n\n/** Where to install from and to. */\ninterface Install {\n readonly destination: string;\n readonly download: FetchBytes;\n readonly tarball: Tarball;\n}\n\n/** Downloads the tarball, checks its SHA-256, and moves only the pinned executable into place. */\nconst installTarballEntry = (pin: Pin, { destination, download, tarball }: Install) =>\n Effect.gen(function* downloadVerifyExtract() {\n const bytes = yield* verifiedDownload(pin, tarball, download);\n const archive = yield* Effect.promise(() => promisify(gunzip)(bytes));\n const executable = tarEntry(archive, pin.name);\n if (executable === undefined) {\n return yield* installFailed(pin, `${tarball.url} holds no ${pin.name}.`);\n }\n yield* Effect.promise(() => placeExecutable(destination, executable));\n return destination;\n });\n\nconst tarballFor = (pin: Pin, platform: string, arch: string) =>\n pin.tarballs[`${platform}-${arch}`];\n\n/** The user's cache directory: `$XDG_CACHE_HOME`, else the platform's usual place. */\nconst cacheHome = () =>\n process.env.XDG_CACHE_HOME ??\n (process.platform === 'darwin'\n ? join(homedir(), 'Library', 'Caches')\n : join(homedir(), '.cache'));\n\nconst exists = (path: string) =>\n Effect.promise(async () => {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n });\n\n/** The executable at `destination`, downloaded there on first use. */\nconst pinnedBinary = (pin: Pin, destination: string) =>\n Effect.gen(function* cachedOrDownload() {\n if (yield* exists(destination)) {\n return destination;\n }\n const tarball = tarballFor(pin, process.platform, process.arch);\n if (tarball === undefined) {\n return yield* installFailed(\n pin,\n `no pinned ${pin.version} build for ${process.platform} ${process.arch}.`,\n );\n }\n return yield* installTarballEntry(pin, { destination, download: fetchBytes, tarball });\n });\n\nexport { cacheHome, InstallError, installTarballEntry, pinnedBinary, tarballFor };\nexport type { FetchBytes, Install, Pin, Tarball };\n"],"mappings":";;;;;;;;AAaA,MAAM,EAAE,aAAa,qBAAqB;AAE1C,IAAM,eAAN,cAA2B,iBAA+B,CAAC,CAAC,gBAAgB,EAC1E,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;AAeJ,MAAM,iBAAiB;AAEvB,MAAM,WAAW;AACjB,MAAM,UAAU;CAAE,KAAK;CAAK,OAAO;AAAE;AACrC,MAAM,UAAU;CAAE,KAAK;CAAK,OAAO;AAAI;AACvC,MAAM,UAAU;CAAE,KAAK;CAAK,OAAO;AAAI;AACvC,MAAM,QAAQ;;AAEd,MAAM,mCAAwC,IAAI,IAAI,CAAC,KAAK,IAAI,CAAC;;AAGjE,MAAM,aACJ,UACgG;CAChG,MAAM,OAAO,MAAM,SAAS,QAAQ,QAAQ,OAAO,QAAQ,GAAG,CAAC,CAAC,QAAQ,WAAW,EAAE;CACrF,MAAM,OAAO,OAAO,SAAS,MAAM,SAAS,SAAS,QAAQ,OAAO,QAAQ,GAAG,CAAC,CAAC,KAAK,GAAG,KAAK;CAC9F,IAAI,SAAS,MAAM,OAAO,MAAM,IAAI,GAClC;CAGF,OAAO;EAAE;EAAM,aADK,iBAAiB,IAAI,MAAM,SAAS,SAAS,QAAQ,OAAO,QAAQ,GAAG,CAClE;EAAG;CAAK;AACnC;;;;;AAMA,MAAM,YAAY,SAAiB,SAAqC;CACtE,IAAI,SAAS;CACb,OAAO,SAAS,YAAY,QAAQ,QAAQ;EAC1C,MAAM,SAAS,UAAU,QAAQ,SAAS,QAAQ,SAAS,QAAQ,CAAC;EACpE,IAAI,WAAW,KAA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dev domains, the sign-in host and every dev
5
+ * host. The CLI accepts a domain only if the server could serve it.
6
+ */
7
+ const Hostname = Schema.String.check(Schema.isPattern(/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u)).pipe(Schema.brand("Hostname"));
8
+ /** The port frps listens on for frpc, and the CLI's default `server.port`. */
9
+ const tunnelPort = 7e3;
10
+ export { Hostname, tunnelPort };
11
+
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../../../packages/contract/src/index.ts"],"sourcesContent":["import { Schema } from 'effect';\n\nconst dnsName =\n /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;\n\n/**\n * A lowercase DNS name with at least two labels: the dev domains, the sign-in host and every dev\n * host. The CLI accepts a domain only if the server could serve it.\n */\nconst Hostname = Schema.String.check(Schema.isPattern(dnsName)).pipe(Schema.brand('Hostname'));\ntype Hostname = typeof Hostname.Type;\n\n/** The port frps listens on for frpc, and the CLI's default `server.port`. */\nconst tunnelPort = 7000;\n\nexport { Hostname, tunnelPort };\n"],"mappings":";;;;;;AASA,MAAM,WAAW,OAAO,OAAO,MAAM,OAAO,UAAU,iGAAO,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM,UAAU,CAAC;;AAI7F,MAAM,aAAa"}
package/dist/ports.js ADDED
@@ -0,0 +1,121 @@
1
+ import { Port } from "./domain.js";
2
+ import { errorCode } from "./errno.js";
3
+ import { pathExists } from "./files.js";
4
+ import { Effect, Schema } from "effect";
5
+ import { mkdir, readFile, readdir, unlink, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { createServer } from "node:net";
8
+ import { homedir } from "node:os";
9
+ // src/ports.ts
10
+ /**
11
+ * Below Linux's ephemeral range (32768-60999), so the kernel never hands these ports to outgoing
12
+ * connections.
13
+ */
14
+ const portRange = {
15
+ first: 2e4,
16
+ last: 29999
17
+ };
18
+ /** How many ports `portRange` holds, both ends included. */
19
+ const portCount = 1e4;
20
+ /** A stale claim is deleted once and the create retried; a second loss means someone else won. */
21
+ const claimAttempts = 2;
22
+ const loopback = "127.0.0.1";
23
+ /** The part of an owner's state.json that says which ports it still uses. */
24
+ const PortsByApp = Schema.Record(Schema.String, Schema.Number);
25
+ const OwnerState = Schema.fromJsonString(Schema.Struct({ ports: Schema.optionalKey(PortsByApp) }));
26
+ /**
27
+ * One file per reserved port, shared by every worktree of every repo for this user. The file holds
28
+ * the owning worktree's directory. Only files, no daemon.
29
+ */
30
+ const reservationsDir = () => {
31
+ const base = process.env.WT_TUNNEL_STATE_DIR ?? join(process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "wt-tunnel");
32
+ return join(base, "ports");
33
+ };
34
+ /** Exclusive create is the lock: of two worktrees claiming one port, exactly one wins. */
35
+ const createExclusive = async (file, owner) => {
36
+ try {
37
+ await writeFile(file, owner, { flag: "wx" });
38
+ return true;
39
+ } catch (error) {
40
+ if (errorCode(error) !== "EEXIST") throw error;
41
+ return false;
42
+ }
43
+ };
44
+ /**
45
+ * A claim whose owner directory is gone, or whose owner's state no longer lists the port, is left
46
+ * over from a worktree deleted without `remove`.
47
+ */
48
+ const isStale = (owner, port) => Effect.gen(function* ownerStillUsesPort() {
49
+ if (!(yield* Effect.promise(() => pathExists(owner)))) return true;
50
+ return yield* Effect.tryPromise(() => readFile(join(owner, ".wt-tunnel", "state.json"), "utf8")).pipe(Effect.flatMap(Schema.decodeUnknownEffect(OwnerState)), Effect.map((state) => !Object.values(state.ports ?? {}).includes(port)), Effect.orElseSucceed(() => false));
51
+ });
52
+ const readOwner = (file) => Effect.promise(() => readFile(file, "utf8"));
53
+ const attemptClaim = (file, port, owner) => Effect.gen(function* createOrInspect() {
54
+ if (yield* Effect.promise(() => createExclusive(file, owner))) return { _tag: "claimed" };
55
+ const current = yield* readOwner(file);
56
+ if (current === owner) return { _tag: "ours" };
57
+ if (!(yield* isStale(current, port))) return {
58
+ _tag: "taken",
59
+ owner: current
60
+ };
61
+ yield* Effect.promise(() => unlink(file));
62
+ return { _tag: "staleRemoved" };
63
+ });
64
+ const claim = (dir, port, owner) => Effect.gen(function* claimPortFile() {
65
+ yield* Effect.promise(() => mkdir(dir, { recursive: true }));
66
+ const file = join(dir, String(port));
67
+ for (let attempt = 0; attempt < claimAttempts; attempt++) {
68
+ const result = yield* attemptClaim(file, port, owner);
69
+ if (result._tag !== "staleRemoved") return result;
70
+ }
71
+ return {
72
+ _tag: "taken",
73
+ owner: yield* readOwner(file)
74
+ };
75
+ });
76
+ const unlinkIfOwned = async (file, owner) => {
77
+ try {
78
+ if (await readFile(file, "utf8") === owner) await unlink(file);
79
+ } catch {}
80
+ };
81
+ /** Releases this owner's claims, except the ports it still uses. */
82
+ const release = (dir, owner, keep = []) => Effect.gen(function* releaseOwnedFiles() {
83
+ if (!(yield* Effect.promise(() => pathExists(dir)))) return;
84
+ for (const name of yield* Effect.promise(() => readdir(dir))) if (!keep.includes(Number(name))) yield* Effect.promise(() => unlinkIfOwned(join(dir, name), owner));
85
+ });
86
+ const isListening = (port) => Effect.callback((resume) => {
87
+ const server = createServer();
88
+ server.once("error", () => {
89
+ resume(Effect.succeed(true));
90
+ });
91
+ server.listen(port, loopback, () => {
92
+ server.close(() => {
93
+ resume(Effect.succeed(false));
94
+ });
95
+ });
96
+ });
97
+ /** Claims `port` unless another worktree holds it or some program already listens on it. */
98
+ const reserveIfFree = (dir, owner, port) => Effect.gen(function* claimUnlessBusy() {
99
+ const result = yield* claim(dir, port, owner);
100
+ if (result._tag === "taken") return false;
101
+ if (result._tag === "claimed" && (yield* isListening(port))) {
102
+ yield* Effect.promise(() => unlink(join(dir, String(port))));
103
+ return false;
104
+ }
105
+ return true;
106
+ });
107
+ /**
108
+ * Reserves a port nobody has claimed and nothing is listening on, starting from a random point in
109
+ * the range so concurrent worktrees rarely contend.
110
+ */
111
+ const allocate = (dir, owner, avoid) => Effect.gen(function* firstFreePort() {
112
+ const start = Math.floor(Math.random() * portCount);
113
+ for (let index = 0; index < portCount; index++) {
114
+ const port = portRange.first + (start + index) % portCount;
115
+ if (!avoid.includes(port) && (yield* reserveIfFree(dir, owner, port))) return Port.make(port);
116
+ }
117
+ return yield* Effect.die(/* @__PURE__ */ new Error(`every port in ${portRange.first}-${portRange.last} is reserved`));
118
+ });
119
+ export { allocate, claim, portRange, release, reservationsDir };
120
+
121
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ports.js","names":[],"sources":["../src/ports.ts"],"sourcesContent":["import { mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises';\nimport { createServer } from 'node:net';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nimport { Effect, Schema } from 'effect';\n\nimport { Port } from './domain.ts';\nimport { errorCode } from './errno.ts';\nimport { pathExists } from './files.ts';\n\n/**\n * Below Linux's ephemeral range (32768-60999), so the kernel never hands these ports to outgoing\n * connections.\n */\nconst portRange = { first: 20_000, last: 29_999 } as const;\n/** How many ports `portRange` holds, both ends included. */\nconst portCount = 10_000;\n/** A stale claim is deleted once and the create retried; a second loss means someone else won. */\nconst claimAttempts = 2;\nconst loopback = '127.0.0.1';\n\ntype Claim =\n | { readonly _tag: 'claimed' }\n | { readonly _tag: 'ours' }\n | { readonly _tag: 'taken'; readonly owner: string };\n\n/** One claim attempt either settles the claim or deletes a stale one so the next can retry. */\ntype Attempt = Claim | { readonly _tag: 'staleRemoved' };\n\n/** The part of an owner's state.json that says which ports it still uses. */\nconst PortsByApp = Schema.Record(Schema.String, Schema.Number);\nconst OwnerState = Schema.fromJsonString(Schema.Struct({ ports: Schema.optionalKey(PortsByApp) }));\n\n/**\n * One file per reserved port, shared by every worktree of every repo for this user. The file holds\n * the owning worktree's directory. Only files, no daemon.\n */\nconst reservationsDir = () => {\n const base =\n process.env.WT_TUNNEL_STATE_DIR ??\n join(process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), 'wt-tunnel');\n return join(base, 'ports');\n};\n\n/** Exclusive create is the lock: of two worktrees claiming one port, exactly one wins. */\nconst createExclusive = async (file: string, owner: string) => {\n try {\n await writeFile(file, owner, { flag: 'wx' });\n return true;\n } catch (error) {\n if (errorCode(error) !== 'EEXIST') {\n throw error;\n }\n return false;\n }\n};\n\n/**\n * A claim whose owner directory is gone, or whose owner's state no longer lists the port, is left\n * over from a worktree deleted without `remove`.\n */\nconst isStale = (owner: string, port: number) =>\n Effect.gen(function* ownerStillUsesPort() {\n if (!(yield* Effect.promise(() => pathExists(owner)))) {\n return true;\n }\n return yield* Effect.tryPromise(() =>\n readFile(join(owner, '.wt-tunnel', 'state.json'), 'utf8'),\n ).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(OwnerState)),\n Effect.map((state) => !Object.values(state.ports ?? {}).includes(port)),\n // No readable state yet: the owner may be mid-add, so keep its claim.\n Effect.orElseSucceed(() => false),\n );\n });\n\nconst readOwner = (file: string) => Effect.promise(() => readFile(file, 'utf8'));\n\nconst attemptClaim = (file: string, port: number, owner: string): Effect.Effect<Attempt> =>\n Effect.gen(function* createOrInspect() {\n if (yield* Effect.promise(() => createExclusive(file, owner))) {\n return { _tag: 'claimed' };\n }\n const current = yield* readOwner(file);\n if (current === owner) {\n return { _tag: 'ours' };\n }\n if (!(yield* isStale(current, port))) {\n return { _tag: 'taken', owner: current };\n }\n yield* Effect.promise(() => unlink(file));\n return { _tag: 'staleRemoved' };\n });\n\nconst claim = (dir: string, port: number, owner: string): Effect.Effect<Claim> =>\n Effect.gen(function* claimPortFile() {\n yield* Effect.promise(() => mkdir(dir, { recursive: true }));\n const file = join(dir, String(port));\n for (let attempt = 0; attempt < claimAttempts; attempt++) {\n const result = yield* attemptClaim(file, port, owner);\n if (result._tag !== 'staleRemoved') {\n return result;\n }\n }\n return { _tag: 'taken', owner: yield* readOwner(file) };\n });\n\nconst unlinkIfOwned = async (file: string, owner: string) => {\n try {\n if ((await readFile(file, 'utf8')) === owner) {\n await unlink(file);\n }\n } catch {\n // Released concurrently.\n }\n};\n\n/** Releases this owner's claims, except the ports it still uses. */\nconst release = (dir: string, owner: string, keep: readonly number[] = []) =>\n Effect.gen(function* releaseOwnedFiles() {\n if (!(yield* Effect.promise(() => pathExists(dir)))) {\n return;\n }\n for (const name of yield* Effect.promise(() => readdir(dir))) {\n if (!keep.includes(Number(name))) {\n yield* Effect.promise(() => unlinkIfOwned(join(dir, name), owner));\n }\n }\n });\n\nconst isListening = (port: number) =>\n Effect.callback<boolean>((resume) => {\n const server = createServer();\n server.once('error', () => {\n resume(Effect.succeed(true));\n });\n server.listen(port, loopback, () => {\n server.close(() => {\n resume(Effect.succeed(false));\n });\n });\n });\n\n/** Claims `port` unless another worktree holds it or some program already listens on it. */\nconst reserveIfFree = (dir: string, owner: string, port: number) =>\n Effect.gen(function* claimUnlessBusy() {\n const result = yield* claim(dir, port, owner);\n if (result._tag === 'taken') {\n return false;\n }\n if (result._tag === 'claimed' && (yield* isListening(port))) {\n yield* Effect.promise(() => unlink(join(dir, String(port))));\n return false;\n }\n return true;\n });\n\n/**\n * Reserves a port nobody has claimed and nothing is listening on, starting from a random point in\n * the range so concurrent worktrees rarely contend.\n */\nconst allocate = (dir: string, owner: string, avoid: readonly number[]) =>\n Effect.gen(function* firstFreePort() {\n const start = Math.floor(Math.random() * portCount);\n for (let index = 0; index < portCount; index++) {\n const port = portRange.first + ((start + index) % portCount);\n if (!avoid.includes(port) && (yield* reserveIfFree(dir, owner, port))) {\n return Port.make(port);\n }\n }\n return yield* Effect.die(\n new Error(`every port in ${portRange.first}-${portRange.last} is reserved`),\n );\n });\n\nexport { allocate, claim, portRange, release, reservationsDir };\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAM,YAAY;CAAE,OAAO;CAAQ,MAAM;AAAO;;AAEhD,MAAM,YAAY;;AAElB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B;EAClC,OAAO,YAAY;GACjB,OAAO,OAAO,QAAQ,KAAK,CAAC;EAC9B,CAAC;CACH,CAAC;AACH,CAAC;;AAGH,MAAM,iBAAiB,KAAa,OAAe,SACjD,OAAO,IAAI,UAAU,kBAAkB;CACrC,MAAM,SAAS,OAAO,MAAM,KAAK,MAAM,KAAK;CAC5C,IAAI,OAAO,SAAS,SAClB,OAAO;CAET,IAAI,OAAO,SAAS,cAAc,OAAO,YAAY,IAAI,IAAI;EAC3D,OAAO,OAAO,cAAc,OAAO,KAAK,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC;EAC3D,OAAO;CACT;CACA,OAAO;AACT,CAAC;;;;;AAMH,MAAM,YAAY,KAAa,OAAe,UAC5C,OAAO,IAAI,UAAU,gBAAgB;CACnC,MAAM,QAAQ,KAAK,MAAM,KAAK,OAAO,IAAI,SAAS;CAClD,KAAK,IAAI,QAAQ,GAAG,QAAQ,WAAW,SAAS;EAC9C,MAAM,OAAO,UAAU,SAAU,QAAQ,SAAS;EAClD,IAAI,CAAC,MAAM,SAAS,IAAI,MAAM,OAAO,cAAc,KAAK,OAAO,IAAI,IACjE,OAAO,KAAK,KAAK,IAAI;CAEzB;CACA,OAAO,OAAO,OAAO,oBACnB,IAAI,MAAM,iBAAiB,UAAU,MAAM,GAAG,UAAU,KAAK,aAAa,CAC5E;AACF,CAAC"}
@@ -0,0 +1,118 @@
1
+ import { WtTunnelError } from "./errors.js";
2
+ import { errorCode } from "./errno.js";
3
+ import { readTextIfExists } from "./files.js";
4
+ import { execFileText } from "./exec.js";
5
+ import { Effect } from "effect";
6
+ import { open, rm, writeFile } from "node:fs/promises";
7
+ import { join } from "node:path";
8
+ import { spawn } from "node:child_process";
9
+ // src/processes.ts
10
+ /** Signal 0 checks that a process exists without touching it. */
11
+ const probeSignal = 0;
12
+ const firstPid = 1;
13
+ /** How long a fresh process must survive before it counts as started. */
14
+ const startupGrace = "1500 millis";
15
+ const stopPollInterval = "100 millis";
16
+ const stopPolls = 50;
17
+ const pidFile = (stateDir, name) => join(stateDir, `${name}.pid`);
18
+ const processLogFile = (stateDir, name) => join(stateDir, `${name}.log`);
19
+ const alive = (pid) => {
20
+ try {
21
+ process.kill(pid, probeSignal);
22
+ return true;
23
+ } catch (error) {
24
+ return errorCode(error) === "EPERM";
25
+ }
26
+ };
27
+ /**
28
+ * A pid file can outlive its process and the pid can be reused, so a pid only counts as ours while
29
+ * its argv still mentions this worktree's state dir.
30
+ */
31
+ const ownedBy = (pid, stateDir) => execFileText("ps", [
32
+ "-o",
33
+ "args=",
34
+ "-p",
35
+ String(pid)
36
+ ]).pipe(Effect.map((args) => args.includes(stateDir)), Effect.orElseSucceed(() => false));
37
+ const processStatus = (stateDir, name) => Effect.gen(function* readPidFile() {
38
+ const text = yield* Effect.promise(() => readTextIfExists(pidFile(stateDir, name)));
39
+ if (text === void 0) return { _tag: "stopped" };
40
+ const pid = Number(text.trim());
41
+ if (Number.isInteger(pid) && pid >= firstPid && alive(pid) && (yield* ownedBy(pid, stateDir))) return {
42
+ _tag: "running",
43
+ pid
44
+ };
45
+ return {
46
+ _tag: "stale",
47
+ pid
48
+ };
49
+ });
50
+ const tail = (file) => Effect.promise(() => readTextIfExists(file)).pipe(Effect.map((text) => (text ?? "").trimEnd().split("\n").slice(-15).join("\n")));
51
+ const failedToStart = (name) => (cause) => new WtTunnelError({ message: `Failed to start ${name}: ${String(cause)}` });
52
+ /** Spawn failures throw synchronously, as Node reports a missing command. */
53
+ const spawnDetached = (spec, logFd) => {
54
+ const child = spawn(spec.command, [...spec.args], {
55
+ detached: true,
56
+ env: {
57
+ ...process.env,
58
+ ...spec.env
59
+ },
60
+ stdio: [
61
+ "ignore",
62
+ logFd,
63
+ logFd
64
+ ]
65
+ });
66
+ child.unref();
67
+ if (child.pid === void 0) throw new Error(`could not spawn ${spec.command}`);
68
+ return child.pid;
69
+ };
70
+ /**
71
+ * Starts the process with its output appended to `log`. The child holds its own copy of the log
72
+ * descriptor, so ours is closed without waiting.
73
+ */
74
+ const spawnLogging = (spec, log) => Effect.gen(function* openLogThenSpawn() {
75
+ const handle = yield* Effect.tryPromise({
76
+ catch: failedToStart(spec.name),
77
+ try: () => open(log, "a")
78
+ });
79
+ return yield* Effect.try({
80
+ catch: failedToStart(spec.name),
81
+ try: () => spawnDetached(spec, handle.fd)
82
+ }).pipe(Effect.ensuring(Effect.sync(() => {
83
+ handle.close();
84
+ })));
85
+ });
86
+ /** Fails with the log's last lines when the process dies within the startup grace period. */
87
+ const survivesStartup = (stateDir, name, pid) => Effect.gen(function* waitThenCheck() {
88
+ yield* Effect.sleep(startupGrace);
89
+ if (!alive(pid)) {
90
+ yield* Effect.promise(() => rm(pidFile(stateDir, name), { force: true }));
91
+ const log = processLogFile(stateDir, name);
92
+ yield* new WtTunnelError({ message: `${name} exited right after starting. Last log lines (${log}):\n${yield* tail(log)}` });
93
+ }
94
+ });
95
+ const startProcess = (stateDir, spec) => Effect.gen(function* spawnUnlessRunning() {
96
+ const current = yield* processStatus(stateDir, spec.name);
97
+ if (current._tag === "running") return current.pid;
98
+ const log = processLogFile(stateDir, spec.name);
99
+ const pid = yield* spawnLogging(spec, log);
100
+ yield* Effect.promise(() => writeFile(pidFile(stateDir, spec.name), `${pid}\n`));
101
+ yield* survivesStartup(stateDir, spec.name, pid);
102
+ return pid;
103
+ });
104
+ /** SIGTERM, then SIGKILL if the process is still alive after the polls. */
105
+ const terminate = (pid) => Effect.gen(function* termThenKill() {
106
+ process.kill(pid, "SIGTERM");
107
+ for (let poll = 0; poll < stopPolls && alive(pid); poll++) yield* Effect.sleep(stopPollInterval);
108
+ if (alive(pid)) process.kill(pid, "SIGKILL");
109
+ });
110
+ const stopProcess = (stateDir, name) => Effect.gen(function* terminateAndForget() {
111
+ const current = yield* processStatus(stateDir, name);
112
+ if (current._tag === "running") yield* terminate(current.pid);
113
+ yield* Effect.promise(() => rm(pidFile(stateDir, name), { force: true }));
114
+ return current;
115
+ });
116
+ export { processLogFile, processStatus, startProcess, stopProcess };
117
+
118
+ //# sourceMappingURL=processes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"processes.js","names":[],"sources":["../src/processes.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { open, rm, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { Effect } from 'effect';\n\nimport { errorCode } from './errno.ts';\nimport { WtTunnelError } from './errors.ts';\nimport { execFileText } from './exec.ts';\nimport { readTextIfExists } from './files.ts';\n\n/** Signal 0 checks that a process exists without touching it. */\nconst probeSignal = 0;\nconst firstPid = 1;\nconst logTailLines = 15;\n/** How long a fresh process must survive before it counts as started. */\nconst startupGrace = '1500 millis';\nconst stopPollInterval = '100 millis';\nconst stopPolls = 50;\n\ninterface ProcessSpec {\n readonly args: readonly string[];\n readonly command: string;\n readonly env?: Readonly<Record<string, string>>;\n readonly name: 'frpc';\n}\n\ntype ProcessName = ProcessSpec['name'];\n\ntype ProcessStatus =\n | { readonly _tag: 'running'; readonly pid: number }\n | { readonly _tag: 'stopped' }\n | { readonly _tag: 'stale'; readonly pid: number };\n\nconst pidFile = (stateDir: string, name: ProcessName) => join(stateDir, `${name}.pid`);\nconst processLogFile = (stateDir: string, name: ProcessName) => join(stateDir, `${name}.log`);\n\nconst alive = (pid: number) => {\n try {\n process.kill(pid, probeSignal);\n return true;\n } catch (error) {\n return errorCode(error) === 'EPERM';\n }\n};\n\n/**\n * A pid file can outlive its process and the pid can be reused, so a pid only counts as ours while\n * its argv still mentions this worktree's state dir.\n */\nconst ownedBy = (pid: number, stateDir: string) =>\n execFileText('ps', ['-o', 'args=', '-p', String(pid)]).pipe(\n Effect.map((args) => args.includes(stateDir)),\n Effect.orElseSucceed(() => false),\n );\n\nconst processStatus = (stateDir: string, name: ProcessName): Effect.Effect<ProcessStatus> =>\n Effect.gen(function* readPidFile() {\n const text = yield* Effect.promise(() => readTextIfExists(pidFile(stateDir, name)));\n if (text === undefined) {\n return { _tag: 'stopped' };\n }\n const pid = Number(text.trim());\n if (Number.isInteger(pid) && pid >= firstPid && alive(pid) && (yield* ownedBy(pid, stateDir))) {\n return { _tag: 'running', pid };\n }\n return { _tag: 'stale', pid };\n });\n\nconst tail = (file: string) =>\n Effect.promise(() => readTextIfExists(file)).pipe(\n Effect.map((text) => (text ?? '').trimEnd().split('\\n').slice(-logTailLines).join('\\n')),\n );\n\nconst failedToStart = (name: ProcessName) => (cause: unknown) =>\n new WtTunnelError({ message: `Failed to start ${name}: ${String(cause)}` });\n\n/** Spawn failures throw synchronously, as Node reports a missing command. */\nconst spawnDetached = (spec: ProcessSpec, logFd: number) => {\n const child = spawn(spec.command, [...spec.args], {\n detached: true,\n env: { ...process.env, ...spec.env },\n stdio: ['ignore', logFd, logFd],\n });\n child.unref();\n if (child.pid === undefined) {\n throw new Error(`could not spawn ${spec.command}`);\n }\n return child.pid;\n};\n\n/**\n * Starts the process with its output appended to `log`. The child holds its own copy of the log\n * descriptor, so ours is closed without waiting.\n */\nconst spawnLogging = (spec: ProcessSpec, log: string) =>\n Effect.gen(function* openLogThenSpawn() {\n const handle = yield* Effect.tryPromise({\n catch: failedToStart(spec.name),\n try: () => open(log, 'a'),\n });\n return yield* Effect.try({\n catch: failedToStart(spec.name),\n try: () => spawnDetached(spec, handle.fd),\n }).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n void handle.close();\n }),\n ),\n );\n });\n\n/** Fails with the log's last lines when the process dies within the startup grace period. */\nconst survivesStartup = (stateDir: string, name: ProcessName, pid: number) =>\n Effect.gen(function* waitThenCheck() {\n yield* Effect.sleep(startupGrace);\n if (!alive(pid)) {\n yield* Effect.promise(() => rm(pidFile(stateDir, name), { force: true }));\n const log = processLogFile(stateDir, name);\n yield* new WtTunnelError({\n message: `${name} exited right after starting. Last log lines (${log}):\\n${yield* tail(log)}`,\n });\n }\n });\n\nconst startProcess = (stateDir: string, spec: ProcessSpec) =>\n Effect.gen(function* spawnUnlessRunning() {\n const current = yield* processStatus(stateDir, spec.name);\n if (current._tag === 'running') {\n return current.pid;\n }\n const log = processLogFile(stateDir, spec.name);\n const pid = yield* spawnLogging(spec, log);\n yield* Effect.promise(() => writeFile(pidFile(stateDir, spec.name), `${pid}\\n`));\n yield* survivesStartup(stateDir, spec.name, pid);\n return pid;\n });\n\n/** SIGTERM, then SIGKILL if the process is still alive after the polls. */\nconst terminate = (pid: number) =>\n Effect.gen(function* termThenKill() {\n process.kill(pid, 'SIGTERM');\n for (let poll = 0; poll < stopPolls && alive(pid); poll++) {\n yield* Effect.sleep(stopPollInterval);\n }\n if (alive(pid)) {\n process.kill(pid, 'SIGKILL');\n }\n });\n\nconst stopProcess = (stateDir: string, name: ProcessName) =>\n Effect.gen(function* terminateAndForget() {\n const current = yield* processStatus(stateDir, name);\n if (current._tag === 'running') {\n yield* terminate(current.pid);\n }\n yield* Effect.promise(() => rm(pidFile(stateDir, name), { force: true }));\n return current;\n });\n\nexport { processLogFile, processStatus, startProcess, stopProcess };\nexport type { ProcessName, ProcessSpec };\n"],"mappings":";;;;;;;;;;AAYA,MAAM,cAAc;AACpB,MAAM,WAAW;;AAGjB,MAAM,eAAe;AACrB,MAAM,mBAAmB;AACzB,MAAM,YAAY;AAgBlB,MAAM,WAAW,UAAkB,SAAsB,KAAK,UAAU,GAAG,KAAK,KAAK;AACrF,MAAM,kBAAkB,UAAkB,SAAsB,KAAK,UAAU,GAAG,KAAK,KAAK;AAE5F,MAAM,SAAS,QAAgB;CAC7B,IAAI;EACF,QAAQ,KAAK,KAAK,WAAW;EAC7B,OAAO;CACT,SAAS,OAAO;EACd,OAAO,UAAU,KAAK,MAAM;CAC9B;AACF;;;;;AAMA,MAAM,WAAW,KAAa,aAC5B,aAAa,MAAM;CAAC;CAAM;CAAS;CAAM,OAAO,GAAG;AAAC,CAAC,CAAC,CAAC,KACrD,OAAO,KAAK,SAAS,KAAK,SAAS,QAAQ,CAAC,GAC5C,OAAO,oBAAoB,KAAK,CAClC;AAEF,MAAM,iBAAiB,UAAkB,SACvC,OAAO,IAAI,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