@fedify/init 2.5.0-dev.2687 → 2.5.0-dev.2726

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.
@@ -1,4 +1,4 @@
1
1
  //#region deno.json
2
- var version = "2.5.0-dev.2687+924da5ce";
2
+ var version = "2.5.0-dev.2726+da549263";
3
3
  //#endregion
4
4
  export { version };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/init",
3
- "version": "2.5.0-dev.2687+924da5ce",
3
+ "version": "2.5.0-dev.2726+da549263",
4
4
  "description": "Project initializer for Fedify",
5
5
  "keywords": [
6
6
  "fedify",
@@ -42,7 +42,20 @@
42
42
  "files": [
43
43
  "dist/",
44
44
  "package.json",
45
- "README.md"
45
+ "README.md",
46
+ "!dist/**/*.test.{js,cjs,mjs,ts,cts,mts}",
47
+ "!dist/**/*.test.d.{ts,cts,mts}",
48
+ "!dist/**/*.test.*.map",
49
+ "!dist/**/*.bench.{js,cjs,mjs,ts,cts,mts}",
50
+ "!dist/**/*.bench.d.{ts,cts,mts}",
51
+ "!dist/**/*.bench.*.map",
52
+ "!dist/**/*.snap",
53
+ "!dist/**/__snapshots__/**",
54
+ "!dist/**/__fixtures__/**",
55
+ "!dist/**/test/**",
56
+ "!dist/**/tests/**",
57
+ "!dist/**/testdata/**",
58
+ "!dist/**/fixtures/**"
46
59
  ],
47
60
  "dependencies": {
48
61
  "@david/dax": "npm:dax@^0.46.1",
@@ -1,6 +0,0 @@
1
- import { TestInitCommand } from "../command.js";
2
-
3
- //#region src/test/action.d.ts
4
- declare function runTestInit(options: TestInitCommand): Promise<boolean>;
5
- //#endregion
6
- export { runTestInit as default };
@@ -1,22 +0,0 @@
1
- import { checkRequiredDbs } from "./db.js";
2
- import { fillEmptyOptions } from "./fill.js";
3
- import runTests from "./run.js";
4
- import { emptyTestDir, genRunId, genTestDirPrefix, logTestDir } from "./utils.js";
5
- //#region src/test/action.ts
6
- async function runTestInit(options) {
7
- const runId = genRunId();
8
- const data = fillEmptyOptions({
9
- ...options,
10
- runId,
11
- testDirPrefix: genTestDirPrefix({ runId })
12
- });
13
- await emptyTestDir(data);
14
- await checkRequiredDbs(data);
15
- logTestDir(data);
16
- let success = true;
17
- if (data.dryRun) success = await runTests(true)(data) && success;
18
- if (data.hydRun) success = await runTests(false)(data) && success;
19
- return success;
20
- }
21
- //#endregion
22
- export { runTestInit as default };
@@ -1,14 +0,0 @@
1
- //#region src/test/cancel.ts
2
- /** An OS request to stop the initializer matrix after cleaning up its server. */
3
- var TestInterruptedError = class extends Error {
4
- signal;
5
- exitCode;
6
- constructor(signal) {
7
- super(`Initializer tests interrupted by ${signal}`);
8
- this.signal = signal;
9
- this.name = "TestInterruptedError";
10
- this.exitCode = signal === "SIGINT" ? 130 : 143;
11
- }
12
- };
13
- //#endregion
14
- export { TestInterruptedError };
@@ -1,137 +0,0 @@
1
- import pm_default from "../json/pm.js";
2
- import { printErrorMessage, printMessage, product } from "../utils.js";
3
- import { getBuildCommand, kvStores, messageQueues } from "../lib.js";
4
- import webFrameworks from "../webframeworks/mod.js";
5
- import { nodeExecutable } from "./node.js";
6
- import { filter, isEmpty, pipe, toArray } from "@fxts/core";
7
- import process from "node:process";
8
- import $ from "@david/dax";
9
- import { appendFile, lstat, mkdir, readFile, stat, symlink } from "node:fs/promises";
10
- import { dirname, join as join$1, resolve, sep } from "node:path";
11
- import { values } from "@optique/core";
12
- //#region src/test/create.ts
13
- const BANNED_PMS = ["bun", "yarn"];
14
- const createTestApp = (testDirPrefix, dry) => async (options) => {
15
- if (!dry && options[1] === "deno") await ensureDenoWorkspaceCache();
16
- const testDir = join$1(testDirPrefix, ...options);
17
- const vals = values(testDir.split(sep).slice(-4));
18
- const result = await $`${toArray(genInitCommand(testDir, dry, options))}`.cwd(join$1(import.meta.dirname, "..", "..")).env("FEDIFY_TEST_MODE", "true").stdin("null").stdout("piped").stderr("piped").noThrow().spawn();
19
- await saveOutputs(testDir, result);
20
- if (result.code === 0) {
21
- if (!dry && (!await validateDevToolScripts(testDir, options) || !await validateFrameworkBuild(testDir, options))) {
22
- printMessage` Fail: ${vals}`;
23
- printMessage` Check out these files for more details: \
24
- ${join$1(testDir, "out.txt")} and \
25
- ${join$1(testDir, "err.txt")}\n`;
26
- return "";
27
- }
28
- printMessage` Pass: ${vals}`;
29
- return testDir;
30
- }
31
- printMessage` Fail: ${vals}`;
32
- printMessage` Check out these files for more details: \
33
- ${join$1(testDir, "out.txt")} and \
34
- ${join$1(testDir, "err.txt")}\n`;
35
- return "";
36
- };
37
- function* genInitCommand(testDir, dry, [webFramework, packageManager, kvStore, messageQueue]) {
38
- yield nodeExecutable;
39
- yield "--experimental-transform-types";
40
- yield "src/test/execute.ts";
41
- yield "init";
42
- yield testDir;
43
- yield "-w";
44
- yield webFramework;
45
- yield "-p";
46
- yield packageManager;
47
- yield "-k";
48
- yield kvStore;
49
- yield "-m";
50
- yield messageQueue;
51
- if (dry) yield "--dry-run";
52
- }
53
- const generateTestCases = ({ webFramework, packageManager, kvStore, messageQueue }) => {
54
- const pms = filterPackageManager(packageManager);
55
- exitIfCasesEmpty([
56
- webFramework,
57
- pms,
58
- kvStore,
59
- messageQueue
60
- ]);
61
- return product(webFramework, pms, kvStore, messageQueue);
62
- };
63
- const filterPackageManager = (pm) => pipe(pm, filter((pm) => BANNED_PMS.includes(pm) ? printErrorMessage`${pm_default[pm]["label"]} is not \
64
- supported in test mode yet because ${pm_default[pm]["label"]} don't \
65
- support local file dependencies properly.` : true), toArray);
66
- const exitIfCasesEmpty = (cases) => {
67
- if (cases.some(isEmpty)) {
68
- printErrorMessage`No test cases to run. Exiting.`;
69
- process.exit(1);
70
- }
71
- };
72
- const saveOutputs = async (dirPath, { stdout, stderr }) => {
73
- await mkdir(dirPath, { recursive: true });
74
- if (stdout) await appendFile(join$1(dirPath, "out.txt"), stdout + "\n", "utf8");
75
- if (stderr) await appendFile(join$1(dirPath, "err.txt"), stderr + "\n", "utf8");
76
- };
77
- async function validateDevToolScripts(dir, options) {
78
- const [_, packageManager] = options;
79
- if (packageManager === "deno") return true;
80
- if (!await hasInstalledNodeDependencies(dir)) return true;
81
- for (const script of [
82
- "format",
83
- "format:check",
84
- "lint"
85
- ]) {
86
- const result = await $`${[
87
- packageManager,
88
- "run",
89
- script
90
- ]}`.cwd(dir).stdin("null").stdout("piped").stderr("piped").noThrow().spawn();
91
- await saveOutputs(dir, result);
92
- if (result.code !== 0) printMessage` Warning: ${script} failed, continuing anyway.`;
93
- }
94
- return true;
95
- }
96
- async function hasInstalledNodeDependencies(dir) {
97
- try {
98
- return (await stat(join$1(dir, "node_modules"))).isDirectory();
99
- } catch {
100
- return false;
101
- }
102
- }
103
- async function validateFrameworkBuild(dir, options) {
104
- const [webFramework, packageManager] = options;
105
- if (webFramework !== "astro") return true;
106
- if (packageManager === "deno") await linkDenoWorkspacePackages(dir);
107
- const result = await $`${getBuildCommand(packageManager)}`.cwd(dir).stdin("null").stdout("piped").stderr("piped").noThrow().spawn();
108
- await saveOutputs(dir, result);
109
- return result.code === 0;
110
- }
111
- async function linkDenoWorkspacePackages(dir) {
112
- const config = JSON.parse(await readFile(join$1(dir, "deno.json"), "utf8"));
113
- for (const link of config.links ?? []) {
114
- const packageDir = resolve(dir, link);
115
- const target = join$1(dir, "node_modules", ...JSON.parse(await readFile(join$1(packageDir, "package.json"), "utf8")).name.split("/"));
116
- await mkdir(dirname(target), { recursive: true });
117
- try {
118
- await lstat(target);
119
- } catch {
120
- await symlink(packageDir, target, "junction");
121
- }
122
- }
123
- }
124
- function filterOptions(options) {
125
- const [wf, pm, kv, mq] = options;
126
- return [
127
- webFrameworks[wf].packageManagers,
128
- kvStores[kv].packageManagers,
129
- messageQueues[mq].packageManagers
130
- ].every((pms) => pms.includes(pm));
131
- }
132
- let denoWorkspaceCache;
133
- function ensureDenoWorkspaceCache() {
134
- return denoWorkspaceCache ??= $`mise run deno:cache`.cwd(join$1(import.meta.dirname, "..", "..", "..", "..")).stdin("null").spawn();
135
- }
136
- //#endregion
137
- export { createTestApp as default, filterOptions, genInitCommand, generateTestCases };
package/dist/test/db.js DELETED
@@ -1,49 +0,0 @@
1
- import { DB_TO_CHECK } from "../const.js";
2
- import { printErrorMessage, printMessage } from "../utils.js";
3
- import db_to_check_default from "../json/db-to-check.js";
4
- import { concat, filter, pipe, toArray, uniq } from "@fxts/core";
5
- import { createConnection } from "node:net";
6
- //#region src/test/db.ts
7
- /**
8
- * Checks if a given port is open by attempting a raw TCP connection to
9
- * localhost at that port. This works reliably for non-HTTP services like
10
- * Redis, PostgreSQL, or AMQP.
11
- * @param port The port number to check.
12
- * @param timeout The timeout in milliseconds. Defaults to 3000.
13
- * @returns A promise that resolves to true if the port is open, else false.
14
- */
15
- function isPortOpen(port, timeout = 3e3) {
16
- return new Promise((resolve) => {
17
- const socket = createConnection({
18
- port,
19
- host: "localhost"
20
- });
21
- socket.setTimeout(timeout);
22
- socket.once("connect", () => {
23
- socket.destroy();
24
- resolve(true);
25
- });
26
- socket.once("timeout", () => {
27
- socket.destroy();
28
- resolve(false);
29
- });
30
- socket.once("error", () => {
31
- socket.destroy();
32
- resolve(false);
33
- });
34
- });
35
- }
36
- const getRequiredDbs = ({ kvStore, messageQueue }) => pipe(kvStore, concat(messageQueue), uniq, filter((db) => DB_TO_CHECK.includes(db)), toArray);
37
- async function checkRequiredDbs(options) {
38
- const dbs = Array.from(getRequiredDbs(options));
39
- if (dbs.length === 0) return;
40
- printMessage`Checking required databases...`;
41
- for (const db of dbs) {
42
- const info = db_to_check_default[db];
43
- const port = String(info.defaultPort);
44
- if (await isPortOpen(info.defaultPort)) printMessage` ${info.name} is running on port ${port}.`;
45
- else printErrorMessage`${info.name} is not running on port ${port}. Tests requiring ${info.name} may fail. Install: ${info.documentation}`;
46
- }
47
- }
48
- //#endregion
49
- export { checkRequiredDbs };
package/dist/test/fill.js DELETED
@@ -1,27 +0,0 @@
1
- import { KV_STORE, MESSAGE_QUEUE, PACKAGE_MANAGER, WEB_FRAMEWORK } from "../const.js";
2
- import { isEmpty, omit, pipe } from "@fxts/core";
3
- //#region src/test/fill.ts
4
- const fillEmptyOptions = (options) => pipe(options, fillWebFramework, fillPackageManager, fillKVStore, fillMessageQueue, fillRunMode);
5
- const fillOption = (key, allValues) => (options) => ({
6
- ...options,
7
- [key]: isEmpty(options[key]) ? allValues : options[key].filter((i) => allValues.includes(i))
8
- });
9
- const fillWebFramework = fillOption("webFramework", WEB_FRAMEWORK);
10
- const fillPackageManager = fillOption("packageManager", PACKAGE_MANAGER);
11
- const fillKVStore = fillOption("kvStore", KV_STORE);
12
- const fillMessageQueue = fillOption("messageQueue", MESSAGE_QUEUE);
13
- const fillRunMode = (options) => pipe(options, (options) => "noHydRun" in options ? {
14
- ...omit(["noHydRun"], options),
15
- hydRun: !options.noHydRun
16
- } : {
17
- ...options,
18
- hydRun: true
19
- }, (options) => "noDryRun" in options ? {
20
- ...omit(["noDryRun"], options),
21
- dryRun: !options.noDryRun
22
- } : {
23
- ...options,
24
- dryRun: true
25
- });
26
- //#endregion
27
- export { fillEmptyOptions };
@@ -1,123 +0,0 @@
1
- import { printErrorMessage, printMessage } from "../utils.js";
2
- import { getDevCommand, kvStores, messageQueues, packageManagers } from "../lib.js";
3
- import webFrameworks from "../webframeworks/mod.js";
4
- import { nodeExecutable } from "./node.js";
5
- import { TestInterruptedError } from "./cancel.js";
6
- import { replacePortInApp, reservePort } from "./port.js";
7
- import { STARTUP_TIMEOUT, serverClosure, waitForServer } from "./server.js";
8
- import { join } from "@fxts/core";
9
- import $ from "@david/dax";
10
- import { join as join$1, sep } from "node:path";
11
- import { values } from "@optique/core";
12
- import { fileURLToPath } from "node:url";
13
- //#region src/test/lookup.ts
14
- const HANDLE = "john";
15
- const BANNED_LOOKUP_REASONS = {
16
- "next,*,*,*": "Next.js doesn't support remote packages",
17
- "solidstart,deno,*,*": "Error occurred while loading submodules in Deno",
18
- "astro,deno,*,*": "Astro doesn't support remote packages in Deno",
19
- "nuxt,deno,*,*": "Nuxt doesn't support remote packages in Deno",
20
- "sveltekit,deno,*,*": "SvelteKit doesn't support remote packages in Deno"
21
- };
22
- const BANNED_LOOKUP_CASES = Object.keys(BANNED_LOOKUP_REASONS).map((key) => key.split(","));
23
- /**
24
- * Run servers for all generated apps and test them with the lookup command.
25
- *
26
- * @param dirs - Array of paths to generated app directories
27
- */
28
- async function runServerAndLookupUser(dirs, test = testApp) {
29
- const valid = dirs.filter(Boolean).filter(isTestable);
30
- printSkippedCases(dirs);
31
- if (valid.length === 0) printErrorMessage`\nNo directories to lookup test.`;
32
- printMessage``;
33
- printMessage`Lookup Test start for ${String(valid.length)} app(s)!`;
34
- const results = await Array.fromAsync(valid, test);
35
- const successCount = results.filter(Boolean).length;
36
- const failCount = results.length - successCount;
37
- printMessage`Lookup Test Results:
38
- Total: ${String(results.length)}
39
- Passed: ${String(successCount)}
40
- Failed: ${String(failCount)}\n\n`;
41
- printFailedCases(valid, results);
42
- return valid.length > 0 && results.every(Boolean);
43
- }
44
- const parseLookupCase = (dir) => dir.split(sep).slice(-4);
45
- const matchesLookupCasePattern = (target) => (pattern) => pattern.every((value, index) => value === "*" || value === target[index]);
46
- const isTestable = (dir) => !BANNED_LOOKUP_CASES.some(matchesLookupCasePattern(parseLookupCase(dir)));
47
- function printSkippedCases(dirs) {
48
- const matchedPatterns = new Set(dirs.filter(Boolean).flatMap((dir) => BANNED_LOOKUP_CASES.filter(matchesLookupCasePattern(parseLookupCase(dir))).map(join(","))));
49
- if (matchedPatterns.size > 0) {
50
- printMessage``;
51
- printMessage`Skipped the following lookup cases due to known issues:`;
52
- }
53
- for (const key of matchedPatterns) {
54
- const reason = BANNED_LOOKUP_REASONS[key] ?? "unknown reason";
55
- printMessage` - ${values(Array.from(getLabels(key.split(","))))}: ${reason}`;
56
- }
57
- }
58
- function* getLabels([wf, pm, kv, mq]) {
59
- if (wf !== "*") yield webFrameworks[wf].label;
60
- if (pm !== "*") yield packageManagers[pm].label;
61
- if (kv !== "*") yield kvStores[kv].label;
62
- if (mq !== "*") yield messageQueues[mq].label;
63
- }
64
- function printFailedCases(valid, results) {
65
- if (results.every(Boolean)) return;
66
- printMessage`Failed cases:`;
67
- for (let i = 0; i < results.length; i++) if (!results[i]) {
68
- const dir = valid[i];
69
- printMessage` - ${values(parseLookupCase(dir))}: ${dir}`;
70
- }
71
- }
72
- /**
73
- * Run the dev server and test with lookup command.
74
- */
75
- async function testApp(dir) {
76
- const [wf, pm, kv, mq] = parseLookupCase(dir);
77
- printMessage` Testing ${values([
78
- wf,
79
- pm,
80
- kv,
81
- mq
82
- ])}...`;
83
- const defaultPort = webFrameworks[wf].defaultPort;
84
- const { port, release } = await reservePort();
85
- await replacePortInApp(dir, wf, defaultPort, port);
86
- printMessage` Using port ${String(port)}`;
87
- const result = await serverClosure(dir, getDevCommand(pm), port, (port, signal) => sendLookup(port, void 0, signal), release).catch((error) => {
88
- if (error instanceof TestInterruptedError) throw error;
89
- return false;
90
- });
91
- printMessage` Lookup ${result ? "successful" : "failed"} for ${values([
92
- wf,
93
- pm,
94
- kv,
95
- mq
96
- ])}!`;
97
- if (!result) printMessage` Check out these files for more details: \
98
- ${join$1(dir, "out.txt")} and \
99
- ${join$1(dir, "err.txt")}\n`;
100
- printMessage`\n`;
101
- return result;
102
- }
103
- async function sendLookup(port, cliEntry = fileURLToPath(new URL("../../../cli/dist/mod.js", import.meta.url)), signal) {
104
- const serverUrl = `http://localhost:${port}`;
105
- const lookupTarget = `${serverUrl}/users/${HANDLE}`;
106
- printMessage` Waiting for server to start at ${serverUrl}...`;
107
- if (!await waitForServer(serverUrl, 1e4, signal)) {
108
- printErrorMessage`Server did not start within ${String(STARTUP_TIMEOUT)}ms`;
109
- return false;
110
- }
111
- printMessage` Server is ready. Running lookup command...`;
112
- try {
113
- let command = $`${nodeExecutable} ${cliEntry} lookup ${lookupTarget} -p`.stdin("null").stdout("piped").stderr("piped").noThrow();
114
- if (signal != null) command = command.signal(signal);
115
- const res = await command.spawn();
116
- return res.code === 0 && res.stdout.includes(`id: URL '${lookupTarget}',`);
117
- } catch (error) {
118
- if (error instanceof Error) printErrorMessage`${error.message}`;
119
- }
120
- return false;
121
- }
122
- //#endregion
123
- export { runServerAndLookupUser as default, isTestable, matchesLookupCasePattern, parseLookupCase, sendLookup };
@@ -1,6 +0,0 @@
1
- import runTestInit from "./action.js";
2
-
3
- //#region src/test/mod.d.ts
4
- declare function main(action?: typeof runTestInit): Promise<void>;
5
- //#endregion
6
- export { main };
package/dist/test/mod.js DELETED
@@ -1,22 +0,0 @@
1
- import { testInitCommand } from "../command.js";
2
- import { isMain } from "../scripts/tooling_main.js";
3
- import { TestInterruptedError } from "./cancel.js";
4
- import runTestInit from "./action.js";
5
- import process from "node:process";
6
- import { run } from "@optique/run";
7
- //#region src/test/mod.ts
8
- async function main(action = runTestInit) {
9
- const result = run(testInitCommand, {
10
- programName: "fedify-test-init",
11
- help: "both"
12
- });
13
- try {
14
- process.exitCode = await action(result) ? 0 : 1;
15
- } catch (error) {
16
- if (!(error instanceof TestInterruptedError)) throw error;
17
- process.exitCode = error.exitCode;
18
- }
19
- }
20
- if (isMain(import.meta.url)) await main();
21
- //#endregion
22
- export { main };
package/dist/test/node.js DELETED
@@ -1,6 +0,0 @@
1
- import process from "node:process";
2
- //#region src/test/node.ts
3
- /** Select Node.js even when a compatibility test imports the harness in Deno. */
4
- const nodeExecutable = process.versions.deno != null || process.versions.bun != null ? "node" : process.execPath;
5
- //#endregion
6
- export { nodeExecutable };
package/dist/test/port.js DELETED
@@ -1,151 +0,0 @@
1
- import { printErrorMessage, printMessage } from "../utils.js";
2
- import process from "node:process";
3
- import { readFile, writeFile } from "node:fs/promises";
4
- import { join } from "node:path";
5
- import { execFile } from "node:child_process";
6
- import { createConnection, createServer } from "node:net";
7
- //#region src/test/port.ts
8
- /**
9
- * Check if a port is currently in use by attempting a TCP connection.
10
- */
11
- function isPortInUse(port, timeout = 1e3) {
12
- return new Promise((resolve) => {
13
- const socket = createConnection({
14
- port,
15
- host: "localhost"
16
- });
17
- socket.setTimeout(timeout);
18
- socket.once("connect", () => {
19
- socket.destroy();
20
- resolve(true);
21
- });
22
- socket.once("timeout", () => {
23
- socket.destroy();
24
- resolve(false);
25
- });
26
- socket.once("error", () => {
27
- socket.destroy();
28
- resolve(false);
29
- });
30
- });
31
- }
32
- /**
33
- * Poll until the port is free or timeout is reached.
34
- * Returns true if the port was released, false if still occupied.
35
- */
36
- async function waitForPortRelease(port, timeout = 5e3) {
37
- const start = Date.now();
38
- while (Date.now() - start < timeout) {
39
- if (!await isPortInUse(port)) return true;
40
- await new Promise((r) => setTimeout(r, 500));
41
- }
42
- return false;
43
- }
44
- /** Attempt to stop remaining listeners using the platform's process tools. */
45
- async function killProcessOnPort(port) {
46
- const windows = process.platform === "win32";
47
- try {
48
- const output = await new Promise((resolve, reject) => {
49
- execFile(windows ? "netstat" : "lsof", windows ? [
50
- "-ano",
51
- "-p",
52
- "tcp"
53
- ] : [
54
- "-t",
55
- `-i:${port}`,
56
- "-sTCP:LISTEN"
57
- ], {
58
- timeout: 1e3,
59
- windowsHide: true
60
- }, (error, stdout) => error ? reject(error) : resolve(stdout));
61
- });
62
- const pids = windows ? parseWindowsListeners(output, port) : output.trim().split(/\s+/).filter((pid) => /^\d+$/.test(pid));
63
- for (const pid of new Set(pids)) if (windows) await new Promise((resolve) => {
64
- execFile("taskkill", [
65
- "/pid",
66
- pid,
67
- "/t",
68
- "/f"
69
- ], {
70
- timeout: 1e3,
71
- windowsHide: true
72
- }, () => resolve());
73
- });
74
- else try {
75
- process.kill(Number(pid), "SIGKILL");
76
- } catch {}
77
- } catch {}
78
- }
79
- function parseWindowsListeners(output, port) {
80
- return output.split(/\r?\n/).flatMap((line) => {
81
- const [protocol, localAddress, , state, pid] = line.trim().split(/\s+/);
82
- return protocol === "TCP" && localAddress?.endsWith(`:${port}`) && state === "LISTENING" && /^\d+$/.test(pid) ? [pid] : [];
83
- });
84
- }
85
- /**
86
- * Reserve a free port by binding to port 0 and letting the OS assign one.
87
- * The socket is held until the returned `release` function is called,
88
- * eliminating the race window between discovery and actual use.
89
- */
90
- function reservePort() {
91
- return new Promise((resolve, reject) => {
92
- const server = createServer();
93
- server.listen(0, () => {
94
- const addr = server.address();
95
- if (addr == null || typeof addr === "string") {
96
- server.close();
97
- reject(/* @__PURE__ */ new Error("Failed to get port from server"));
98
- return;
99
- }
100
- resolve({
101
- port: addr.port,
102
- release: () => new Promise((r) => server.close(() => r()))
103
- });
104
- });
105
- server.on("error", reject);
106
- });
107
- }
108
- const ENTRY_FILES = {
109
- "bare-bones": "src/main.ts",
110
- express: "src/index.ts",
111
- hono: "src/index.ts",
112
- elysia: "src/index.ts"
113
- };
114
- const WF_READ_PORT_FROM_ENV = /* @__PURE__ */ new Set([
115
- "nuxt",
116
- "nitro",
117
- "solidstart"
118
- ]);
119
- /**
120
- * Replace the hardcoded default port with `newPort` in the generated test
121
- * app's source files. Strategy varies by framework.
122
- */
123
- async function replacePortInApp(dir, wf, defaultPort, newPort) {
124
- if (WF_READ_PORT_FROM_ENV.has(wf)) return;
125
- if (defaultPort === newPort) return;
126
- const entryFile = ENTRY_FILES[wf];
127
- if (entryFile) {
128
- const filePath = join(dir, entryFile);
129
- await writeFile(filePath, (await readFile(filePath, "utf8")).replaceAll(String(defaultPort), String(newPort)));
130
- return;
131
- }
132
- if (wf === "astro" || wf === "sveltekit") {
133
- const configPath = join(dir, wf === "astro" ? "astro.config.ts" : "vite.config.ts");
134
- await writeFile(configPath, (await readFile(configPath, "utf8")).replace("defineConfig({", `defineConfig({\n server: { port: ${newPort} },`));
135
- return;
136
- }
137
- printErrorMessage`Unknown framework ${wf}—cannot replace port.`;
138
- }
139
- /**
140
- * Ensure a port is fully released after killing a server process.
141
- * If the port is still occupied after waiting, force-kill the holder.
142
- */
143
- async function ensurePortReleased(port) {
144
- if (!await waitForPortRelease(port, 5e3)) {
145
- printMessage` Port ${String(port)} still in use—force-killing...`;
146
- await killProcessOnPort(port);
147
- if (!await waitForPortRelease(port, 3e3)) throw new Error(`Port ${port} is still in use after server cleanup`);
148
- }
149
- }
150
- //#endregion
151
- export { ensurePortReleased, isPortInUse, killProcessOnPort, parseWindowsListeners, replacePortInApp, reservePort, waitForPortRelease };
package/dist/test/run.js DELETED
@@ -1,25 +0,0 @@
1
- import { printMessage } from "../utils.js";
2
- import createTestApp, { filterOptions, generateTestCases } from "./create.js";
3
- import runServerAndLookupUser from "./lookup.js";
4
- import { join } from "node:path";
5
- import { optionNames } from "@optique/core";
6
- //#region src/test/run.ts
7
- const runTests = (dry, runners) => async ({ testDirPrefix, dryRun, hydRun, ...options }) => {
8
- printMessage`\n
9
- Init ${dry ? "Dry" : "Hyd"} Test start!
10
- Options: ${optionNames([
11
- "Web Framework",
12
- "Package Manager",
13
- "KV Store",
14
- "Message Queue"
15
- ])}`;
16
- const create = runners?.create ?? createTestApp(join(testDirPrefix, getMid(dryRun, hydRun, dry)), dry);
17
- const dirs = [];
18
- for (const testCase of generateTestCases(options)) if (filterOptions(testCase)) dirs.push(await create(testCase));
19
- const generated = dirs.length > 0 && dirs.every(Boolean);
20
- const lookup = dry ? true : await (runners?.lookup ?? runServerAndLookupUser)(dirs);
21
- return generated && lookup;
22
- };
23
- const getMid = (dryRun, hydRun, dry) => dryRun === hydRun ? dry ? "dry" : "hyd" : "";
24
- //#endregion
25
- export { runTests as default };
@@ -1,185 +0,0 @@
1
- import { __toESM } from "../_virtual/_rolldown/runtime.js";
2
- import { printErrorMessage } from "../utils.js";
3
- import { TestInterruptedError } from "./cancel.js";
4
- import { ensurePortReleased } from "./port.js";
5
- import { require_cross_spawn } from "../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js";
6
- import process from "node:process";
7
- import { createWriteStream } from "node:fs";
8
- import { join } from "node:path";
9
- import { execFile } from "node:child_process";
10
- import { finished } from "node:stream/promises";
11
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
12
- //#region src/test/server.ts
13
- var import_cross_spawn = /* @__PURE__ */ __toESM(require_cross_spawn(), 1);
14
- const STARTUP_TIMEOUT = 1e4;
15
- /** Wait for the generated application to respond successfully. */
16
- async function waitForServer(url, timeout = STARTUP_TIMEOUT, signal) {
17
- const startTime = Date.now();
18
- while (Date.now() - startTime < timeout) {
19
- signal?.throwIfAborted();
20
- try {
21
- const timeoutSignal = AbortSignal.timeout(1e3);
22
- const response = await fetch(url, { signal: signal == null ? timeoutSignal : AbortSignal.any([signal, timeoutSignal]) });
23
- const ok = response.ok;
24
- await response.body?.cancel();
25
- if (ok) return true;
26
- } catch {}
27
- await setTimeout$1(500, void 0, { signal });
28
- }
29
- return false;
30
- }
31
- /** Run a generated application's server and always stop its process tree. */
32
- async function serverClosure(dir, cmd, defaultPort, callback, releasePort, signal) {
33
- await releasePort?.();
34
- signal?.throwIfAborted();
35
- const command = typeof cmd === "string" ? cmd.split(" ") : cmd;
36
- const child = (0, import_cross_spawn.default)(command[0], [...command.slice(1)], {
37
- cwd: dir,
38
- env: {
39
- ...process.env,
40
- PORT: String(defaultPort)
41
- },
42
- stdio: [
43
- "ignore",
44
- "pipe",
45
- "pipe"
46
- ],
47
- detached: process.platform !== "win32"
48
- });
49
- const outFile = createWriteStream(join(dir, "out.txt"), { flags: "a" });
50
- const errFile = createWriteStream(join(dir, "err.txt"), { flags: "a" });
51
- const filesDone = Promise.all([finished(outFile), finished(errFile)]);
52
- filesDone.catch(() => {});
53
- child.stdout.pipe(outFile, { end: false });
54
- child.stderr.pipe(errFile, { end: false });
55
- let rejectFailure;
56
- const failure = new Promise((_, reject) => rejectFailure = reject);
57
- failure.catch(() => {});
58
- const closed = new Promise((resolve) => child.once("close", () => resolve()));
59
- child.once("error", (error) => rejectFailure(error));
60
- child.once("exit", (code, exitSignal) => {
61
- rejectFailure(/* @__PURE__ */ new Error(`Server exited (${exitSignal ?? code})`));
62
- });
63
- outFile.once("error", (error) => rejectFailure(error));
64
- errFile.once("error", (error) => rejectFailure(error));
65
- const onAbort = () => rejectFailure(signal?.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("Server test aborted"));
66
- const onInterrupt = () => rejectFailure(new TestInterruptedError("SIGINT"));
67
- const onTerminate = () => rejectFailure(new TestInterruptedError("SIGTERM"));
68
- signal?.addEventListener("abort", onAbort, { once: true });
69
- process.once("SIGINT", onInterrupt);
70
- process.once("SIGTERM", onTerminate);
71
- if (signal?.aborted) onAbort();
72
- let port = defaultPort;
73
- const detection = detectPort(child);
74
- let operationError;
75
- let failed = false;
76
- let result;
77
- const shutdown = new AbortController();
78
- try {
79
- port = await Promise.race([detection.result.catch((error) => {
80
- printErrorMessage`Failed to determine server port: ${error.message}`;
81
- printErrorMessage`Use default port ${String(defaultPort)} for lookup.`;
82
- return defaultPort;
83
- }), failure]);
84
- result = await Promise.race([callback(port, shutdown.signal), failure]);
85
- } catch (error) {
86
- operationError = error;
87
- failed = true;
88
- } finally {
89
- shutdown.abort(/* @__PURE__ */ new Error("Server test finished"));
90
- detection.stop();
91
- signal?.removeEventListener("abort", onAbort);
92
- process.removeListener("SIGINT", onInterrupt);
93
- process.removeListener("SIGTERM", onTerminate);
94
- try {
95
- await stopProcessTree(child, closed);
96
- } catch (error) {
97
- if (!failed) operationError = error;
98
- failed = true;
99
- printErrorMessage`Failed to stop server: ${String(error)}`;
100
- } finally {
101
- child.stdout.destroy();
102
- child.stderr.destroy();
103
- outFile.end();
104
- errFile.end();
105
- }
106
- try {
107
- await filesDone;
108
- if (child.pid != null) await ensurePortReleased(port);
109
- } catch (error) {
110
- if (!failed) operationError = error;
111
- failed = true;
112
- printErrorMessage`Failed to clean up server: ${String(error)}`;
113
- }
114
- }
115
- if (failed) throw operationError;
116
- return result;
117
- }
118
- function detectPort(child) {
119
- let output = "";
120
- let timer;
121
- let onData;
122
- const stop = () => {
123
- clearTimeout(timer);
124
- child.stdout.removeListener("data", onData);
125
- child.stderr.removeListener("data", onData);
126
- };
127
- return {
128
- result: new Promise((resolve, reject) => {
129
- timer = setTimeout(() => {
130
- stop();
131
- reject(/* @__PURE__ */ new Error("Timeout: Could not determine port from server output"));
132
- }, STARTUP_TIMEOUT);
133
- onData = (chunk) => {
134
- output += chunk.toString("utf8");
135
- for (const pattern of [
136
- /listening on.*:(\d+)/i,
137
- /server.*:(\d+)/i,
138
- /port\s*:?\s*(\d+)/i,
139
- /https?:\/\/[^:]+:(\d+)/i
140
- ]) {
141
- const match = pattern.exec(output);
142
- const port = Number(match?.[1]);
143
- if (port > 0 && port < 65536) {
144
- stop();
145
- resolve(port);
146
- break;
147
- }
148
- }
149
- };
150
- child.stdout.on("data", onData);
151
- child.stderr.on("data", onData);
152
- }),
153
- stop
154
- };
155
- }
156
- async function stopProcessTree(child, closed) {
157
- if (child.pid == null) return;
158
- if (process.platform === "win32") await new Promise((resolve) => {
159
- execFile("taskkill", [
160
- "/pid",
161
- String(child.pid),
162
- "/t",
163
- "/f"
164
- ], {
165
- timeout: 1e3,
166
- windowsHide: true
167
- }, () => resolve());
168
- });
169
- else {
170
- const kill = (signal) => {
171
- try {
172
- process.kill(-child.pid, signal);
173
- } catch (error) {
174
- if (error.code !== "ESRCH") throw error;
175
- }
176
- };
177
- kill("SIGTERM");
178
- await Promise.race([closed, setTimeout$1(1e3)]);
179
- kill("SIGKILL");
180
- }
181
- child.kill("SIGKILL");
182
- await Promise.race([closed, setTimeout$1(1e3)]);
183
- }
184
- //#endregion
185
- export { STARTUP_TIMEOUT, serverClosure, waitForServer };
@@ -1,13 +0,0 @@
1
- import { printMessage } from "../utils.js";
2
- import { rm } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { tmpdir } from "node:os";
5
- //#region src/test/utils.ts
6
- const genRunId = () => `${Date.now()}-${Math.random().toString(36).slice(2)}`;
7
- const genTestDirPrefix = ({ runId }) => join(tmpdir(), "fedify-init", runId);
8
- const emptyTestDir = ({ testDirPrefix }) => rm(testDirPrefix, { recursive: true }).catch(() => {});
9
- const logTestDir = ({ runId, testDirPrefix }) => printMessage`Test running with
10
- Run ID: ${runId}
11
- Path: ${testDirPrefix}`;
12
- //#endregion
13
- export { emptyTestDir, genRunId, genTestDirPrefix, logTestDir };