rwsdk 1.0.0-alpha.2 → 1.0.0-alpha.20

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 (158) hide show
  1. package/dist/lib/e2e/browser.d.mts +10 -0
  2. package/dist/lib/e2e/browser.mjs +124 -0
  3. package/dist/lib/e2e/dev.d.mts +8 -0
  4. package/dist/lib/e2e/dev.mjs +242 -0
  5. package/dist/lib/e2e/environment.d.mts +14 -0
  6. package/dist/lib/e2e/environment.mjs +266 -0
  7. package/dist/lib/e2e/index.d.mts +8 -0
  8. package/dist/lib/e2e/index.mjs +8 -0
  9. package/dist/lib/e2e/poll.d.mts +8 -0
  10. package/dist/lib/e2e/poll.mjs +31 -0
  11. package/dist/lib/e2e/release.d.mts +56 -0
  12. package/dist/lib/e2e/release.mjs +559 -0
  13. package/dist/lib/e2e/retry.d.mts +4 -0
  14. package/dist/lib/e2e/retry.mjs +16 -0
  15. package/dist/lib/e2e/setup.d.mts +2 -0
  16. package/dist/lib/e2e/setup.mjs +1 -0
  17. package/dist/lib/e2e/tarball.d.mts +14 -0
  18. package/dist/lib/e2e/tarball.mjs +99 -0
  19. package/dist/lib/e2e/testHarness.d.mts +132 -0
  20. package/dist/lib/e2e/testHarness.mjs +437 -0
  21. package/dist/lib/e2e/types.d.mts +32 -0
  22. package/dist/lib/getShortName.mjs +6 -1
  23. package/dist/lib/getShortName.test.d.mts +1 -0
  24. package/dist/lib/getShortName.test.mjs +25 -0
  25. package/dist/lib/hasPkgScript.d.mts +4 -1
  26. package/dist/lib/hasPkgScript.mjs +9 -6
  27. package/dist/lib/hasPkgScript.test.d.mts +1 -0
  28. package/dist/lib/hasPkgScript.test.mjs +33 -0
  29. package/dist/lib/jsonUtils.mjs +3 -0
  30. package/dist/lib/jsonUtils.test.d.mts +1 -0
  31. package/dist/lib/jsonUtils.test.mjs +90 -0
  32. package/dist/lib/normalizeModulePath.d.mts +5 -0
  33. package/dist/lib/normalizeModulePath.mjs +1 -1
  34. package/dist/lib/normalizeModulePath.test.d.mts +1 -0
  35. package/dist/lib/{normalizeModulePath.test.js → normalizeModulePath.test.mjs} +20 -1
  36. package/dist/lib/smokeTests/browser.mjs +3 -94
  37. package/dist/lib/smokeTests/development.mjs +2 -223
  38. package/dist/lib/smokeTests/environment.d.mts +4 -11
  39. package/dist/lib/smokeTests/environment.mjs +10 -158
  40. package/dist/lib/smokeTests/release.d.mts +2 -49
  41. package/dist/lib/smokeTests/release.mjs +3 -503
  42. package/dist/llms/rules/middleware.d.ts +1 -1
  43. package/dist/llms/rules/middleware.js +4 -4
  44. package/dist/runtime/entries/worker.d.ts +0 -1
  45. package/dist/runtime/entries/worker.js +0 -1
  46. package/dist/runtime/lib/auth/session.d.ts +2 -2
  47. package/dist/runtime/lib/auth/session.js +4 -4
  48. package/dist/runtime/lib/memoizeOnId.test.d.ts +1 -0
  49. package/dist/runtime/lib/memoizeOnId.test.js +49 -0
  50. package/dist/runtime/lib/realtime/protocol.test.d.ts +1 -0
  51. package/dist/runtime/lib/realtime/protocol.test.js +107 -0
  52. package/dist/runtime/lib/realtime/shared.test.d.ts +1 -0
  53. package/dist/runtime/lib/realtime/shared.test.js +18 -0
  54. package/dist/runtime/lib/realtime/validateUpgradeRequest.test.d.ts +1 -0
  55. package/dist/runtime/lib/realtime/validateUpgradeRequest.test.js +66 -0
  56. package/dist/runtime/lib/realtime/worker.d.ts +1 -1
  57. package/dist/runtime/lib/router.js +40 -22
  58. package/dist/runtime/lib/router.test.js +590 -2
  59. package/dist/runtime/lib/rwContext.d.ts +22 -0
  60. package/dist/runtime/lib/rwContext.js +1 -0
  61. package/dist/runtime/lib/stitchDocumentAndAppStreams.d.ts +18 -0
  62. package/dist/runtime/lib/stitchDocumentAndAppStreams.js +143 -0
  63. package/dist/runtime/lib/turnstile/verifyTurnstileToken.d.ts +2 -1
  64. package/dist/runtime/lib/turnstile/verifyTurnstileToken.js +6 -6
  65. package/dist/runtime/lib/turnstile/verifyTurnstileToken.test.d.ts +1 -0
  66. package/dist/runtime/lib/turnstile/verifyTurnstileToken.test.js +49 -0
  67. package/dist/runtime/register/worker.d.ts +1 -1
  68. package/dist/runtime/register/worker.js +33 -21
  69. package/dist/runtime/render/assembleDocument.d.ts +6 -0
  70. package/dist/runtime/render/assembleDocument.js +22 -0
  71. package/dist/runtime/render/createThenableFromReadableStream.d.ts +1 -0
  72. package/dist/runtime/render/createThenableFromReadableStream.js +9 -0
  73. package/dist/runtime/render/normalizeActionResult.d.ts +1 -0
  74. package/dist/runtime/render/normalizeActionResult.js +43 -0
  75. package/dist/runtime/render/preloads.d.ts +2 -2
  76. package/dist/runtime/render/preloads.js +2 -3
  77. package/dist/runtime/render/{renderRscThenableToHtmlStream.d.ts → renderDocumentHtmlStream.d.ts} +3 -3
  78. package/dist/runtime/render/renderDocumentHtmlStream.js +39 -0
  79. package/dist/runtime/render/renderHtmlStream.d.ts +7 -0
  80. package/dist/runtime/render/renderHtmlStream.js +31 -0
  81. package/dist/runtime/render/renderToRscStream.d.ts +5 -3
  82. package/dist/runtime/render/renderToRscStream.js +12 -41
  83. package/dist/runtime/render/renderToStream.d.ts +2 -1
  84. package/dist/runtime/render/renderToStream.js +15 -8
  85. package/dist/runtime/render/stylesheets.d.ts +2 -2
  86. package/dist/runtime/render/stylesheets.js +2 -3
  87. package/dist/runtime/requestInfo/types.d.ts +0 -2
  88. package/dist/runtime/requestInfo/worker.js +1 -9
  89. package/dist/runtime/ssrBridge.d.ts +2 -1
  90. package/dist/runtime/ssrBridge.js +2 -1
  91. package/dist/runtime/worker.d.ts +1 -0
  92. package/dist/runtime/worker.js +11 -14
  93. package/dist/scripts/debug-sync.mjs +102 -133
  94. package/dist/vite/buildApp.d.mts +2 -1
  95. package/dist/vite/buildApp.mjs +9 -5
  96. package/dist/vite/checkIsUsingPrisma.d.mts +4 -0
  97. package/dist/vite/checkIsUsingPrisma.mjs +2 -2
  98. package/dist/vite/checkIsUsingPrisma.test.d.mts +1 -0
  99. package/dist/vite/checkIsUsingPrisma.test.mjs +30 -0
  100. package/dist/vite/configPlugin.mjs +54 -14
  101. package/dist/vite/createDirectiveLookupPlugin.d.mts +9 -0
  102. package/dist/vite/createDirectiveLookupPlugin.mjs +33 -29
  103. package/dist/vite/createDirectiveLookupPlugin.test.d.mts +1 -0
  104. package/dist/vite/createDirectiveLookupPlugin.test.mjs +40 -0
  105. package/dist/vite/directiveModulesDevPlugin.d.mts +4 -1
  106. package/dist/vite/directiveModulesDevPlugin.mjs +6 -5
  107. package/dist/vite/directiveModulesDevPlugin.test.d.mts +1 -0
  108. package/dist/vite/directiveModulesDevPlugin.test.mjs +59 -0
  109. package/dist/vite/directivesPlugin.d.mts +1 -0
  110. package/dist/vite/directivesPlugin.mjs +1 -1
  111. package/dist/vite/directivesPlugin.test.d.mts +1 -0
  112. package/dist/vite/directivesPlugin.test.mjs +24 -0
  113. package/dist/vite/ensureAliasArray.test.d.mts +1 -0
  114. package/dist/vite/ensureAliasArray.test.mjs +71 -0
  115. package/dist/vite/findSpecifiers.mjs +2 -1
  116. package/dist/vite/findSpecifiers.test.d.mts +1 -0
  117. package/dist/vite/findSpecifiers.test.mjs +202 -0
  118. package/dist/vite/findSsrSpecifiers.test.d.mts +1 -0
  119. package/dist/vite/findSsrSpecifiers.test.mjs +99 -0
  120. package/dist/vite/hasDirective.d.mts +6 -3
  121. package/dist/vite/hasDirective.mjs +43 -27
  122. package/dist/vite/hasDirective.test.d.mts +1 -0
  123. package/dist/vite/hasDirective.test.mjs +107 -0
  124. package/dist/vite/isJsFile.test.d.mts +1 -0
  125. package/dist/vite/isJsFile.test.mjs +38 -0
  126. package/dist/vite/{reactConditionsResolverPlugin.d.mts → knownDepsResolverPlugin.d.mts} +2 -2
  127. package/dist/vite/{reactConditionsResolverPlugin.mjs → knownDepsResolverPlugin.mjs} +28 -23
  128. package/dist/vite/linkerPlugin.d.mts +8 -0
  129. package/dist/vite/linkerPlugin.mjs +30 -22
  130. package/dist/vite/linkerPlugin.test.d.mts +1 -0
  131. package/dist/vite/linkerPlugin.test.mjs +41 -0
  132. package/dist/vite/miniflareHMRPlugin.d.mts +5 -0
  133. package/dist/vite/miniflareHMRPlugin.mjs +2 -2
  134. package/dist/vite/miniflareHMRPlugin.test.d.mts +1 -0
  135. package/dist/vite/miniflareHMRPlugin.test.mjs +42 -0
  136. package/dist/vite/redwoodPlugin.d.mts +9 -0
  137. package/dist/vite/redwoodPlugin.mjs +29 -5
  138. package/dist/vite/redwoodPlugin.test.d.mts +1 -0
  139. package/dist/vite/redwoodPlugin.test.mjs +34 -0
  140. package/dist/vite/resolveForcedPaths.d.mts +4 -0
  141. package/dist/vite/resolveForcedPaths.mjs +9 -0
  142. package/dist/vite/runDirectivesScan.d.mts +22 -1
  143. package/dist/vite/runDirectivesScan.mjs +105 -58
  144. package/dist/vite/runDirectivesScan.test.d.mts +1 -0
  145. package/dist/vite/runDirectivesScan.test.mjs +73 -0
  146. package/dist/vite/ssrBridgePlugin.mjs +8 -1
  147. package/dist/vite/transformClientComponents.mjs +6 -4
  148. package/dist/vite/transformClientComponents.test.mjs +116 -58
  149. package/dist/vite/transformServerFunctions.d.mts +1 -1
  150. package/dist/vite/transformServerFunctions.mjs +1 -1
  151. package/dist/vite/transformServerFunctions.test.mjs +3 -3
  152. package/package.json +56 -47
  153. package/dist/runtime/imports/resolveSSRValue.d.ts +0 -1
  154. package/dist/runtime/imports/resolveSSRValue.js +0 -8
  155. package/dist/runtime/render/renderRscThenableToHtmlStream.js +0 -54
  156. package/dist/runtime/render/transformRscToHtmlStream.d.ts +0 -8
  157. package/dist/runtime/render/transformRscToHtmlStream.js +0 -19
  158. /package/dist/lib/{normalizeModulePath.test.d.ts → e2e/types.mjs} +0 -0
@@ -0,0 +1,10 @@
1
+ import { SmokeTestOptions } from "./types.mjs";
2
+ import type { Browser } from "puppeteer-core";
3
+ /**
4
+ * Launch a browser instance
5
+ */
6
+ export declare function launchBrowser(browserPath?: string, headless?: boolean): Promise<Browser>;
7
+ /**
8
+ * Get the browser executable path
9
+ */
10
+ export declare function getBrowserPath(testOptions?: SmokeTestOptions): Promise<string>;
@@ -0,0 +1,124 @@
1
+ import * as os from "os";
2
+ import { join } from "path";
3
+ import { pathExists } from "fs-extra";
4
+ import debug from "debug";
5
+ import { mkdirp } from "fs-extra";
6
+ import { install, resolveBuildId, computeExecutablePath, detectBrowserPlatform, Browser as PuppeteerBrowser, } from "@puppeteer/browsers";
7
+ import puppeteer from "puppeteer-core";
8
+ const log = debug("rwsdk:e2e:browser");
9
+ /**
10
+ * Launch a browser instance
11
+ */
12
+ export async function launchBrowser(browserPath, headless = true) {
13
+ // Get browser path if not provided
14
+ if (!browserPath) {
15
+ log("Getting browser executable path");
16
+ browserPath = await getBrowserPath({ headless });
17
+ }
18
+ console.log(`🚀 Launching browser from ${browserPath} (headless: ${headless})`);
19
+ log("Starting browser with puppeteer");
20
+ return await puppeteer.launch({
21
+ executablePath: browserPath,
22
+ headless,
23
+ args: ["--no-sandbox", "--disable-setuid-sandbox"],
24
+ });
25
+ }
26
+ /**
27
+ * Get the browser executable path
28
+ */
29
+ export async function getBrowserPath(testOptions) {
30
+ console.log("Finding Chrome executable...");
31
+ // First try using environment variable if set
32
+ if (process.env.CHROME_PATH) {
33
+ console.log(`Using Chrome from environment variable: ${process.env.CHROME_PATH}`);
34
+ return process.env.CHROME_PATH;
35
+ }
36
+ // Detect platform
37
+ log("Detecting platform");
38
+ const platform = detectBrowserPlatform();
39
+ if (!platform) {
40
+ log("ERROR: Failed to detect browser platform");
41
+ throw new Error("Failed to detect browser platform");
42
+ }
43
+ log("Detected platform: %s", platform);
44
+ // Define a consistent cache directory path in system temp folder
45
+ const rwCacheDir = join(os.tmpdir(), "redwoodjs-smoke-test-cache");
46
+ await mkdirp(rwCacheDir);
47
+ log("Using cache directory: %s", rwCacheDir);
48
+ // Determine browser type based on headless option
49
+ const browser = testOptions?.headless === false
50
+ ? PuppeteerBrowser.CHROME
51
+ : PuppeteerBrowser.CHROMEHEADLESSSHELL;
52
+ log(`Using browser type: ${browser}`);
53
+ // Resolve the buildId for the stable Chrome version - do this once
54
+ log("Resolving Chrome buildId for stable channel");
55
+ const buildId = await resolveBuildId(browser, platform, "stable");
56
+ log("Resolved buildId: %s", buildId);
57
+ // Create installation options - use them consistently
58
+ const installOptions = {
59
+ browser,
60
+ platform,
61
+ cacheDir: rwCacheDir,
62
+ buildId,
63
+ unpack: true,
64
+ };
65
+ try {
66
+ // Try to compute the path first (this will check if it's installed)
67
+ log("Attempting to find existing Chrome installation");
68
+ const path = computeExecutablePath(installOptions);
69
+ if (await pathExists(path)) {
70
+ console.log(`Found existing Chrome at: ${path}`);
71
+ return path;
72
+ }
73
+ else {
74
+ throw new Error("Chrome not found at: " + path);
75
+ }
76
+ }
77
+ catch (error) {
78
+ // If path computation fails, install Chrome
79
+ console.log("No Chrome installation found. Installing Chrome...");
80
+ // Add better error handling for the install step
81
+ try {
82
+ console.log("Downloading Chrome (this may take a few minutes)...");
83
+ const attempts = 10;
84
+ let installError;
85
+ for (let i = 0; i < attempts; i++) {
86
+ try {
87
+ await install(installOptions);
88
+ installError = null; // Reset error on success
89
+ break; // Exit loop on success
90
+ }
91
+ catch (e) {
92
+ installError = e;
93
+ console.log(`Attempt ${i + 1}/${attempts} failed. Retrying in 1 second...`);
94
+ // Wait for 1 second before retrying
95
+ await new Promise((resolve) => setTimeout(resolve, 1000));
96
+ }
97
+ }
98
+ if (installError) {
99
+ throw installError;
100
+ }
101
+ console.log("✅ Chrome installation completed successfully");
102
+ // Now compute the path for the installed browser
103
+ const path = computeExecutablePath(installOptions);
104
+ console.log(`Installed and using Chrome at: ${path}`);
105
+ return path;
106
+ }
107
+ catch (installError) {
108
+ // Provide more detailed error about the browser download failure
109
+ log("ERROR: Failed to download/install Chrome: %O", installError);
110
+ console.error(`❌ Failed to download/install Chrome browser.`);
111
+ console.error(`This is likely a network issue or the browser download URL is unavailable.`);
112
+ console.error(`Error details: ${installError instanceof Error ? installError.message : String(installError)}`);
113
+ // For debug builds, show the full error stack if available
114
+ if (installError instanceof Error && installError.stack) {
115
+ log("Error stack: %s", installError.stack);
116
+ }
117
+ console.log("\nPossible solutions:");
118
+ console.log("1. Check your internet connection");
119
+ console.log("2. Set CHROME_PATH environment variable to an existing Chrome installation");
120
+ console.log("3. Install Chrome manually and run the tests again");
121
+ throw new Error(`Failed to install Chrome browser: ${installError instanceof Error ? installError.message : String(installError)}`);
122
+ }
123
+ }
124
+ }
@@ -0,0 +1,8 @@
1
+ import { PackageManager } from "./types.mjs";
2
+ /**
3
+ * Run the local development server and return the URL
4
+ */
5
+ export declare function runDevServer(packageManager?: PackageManager, cwd?: string): Promise<{
6
+ url: string;
7
+ stopDev: () => Promise<void>;
8
+ }>;
@@ -0,0 +1,242 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ import debug from "debug";
3
+ import { $ } from "../../lib/$.mjs";
4
+ import { poll } from "./poll.mjs";
5
+ const DEV_SERVER_CHECK_TIMEOUT = process.env.RWSDK_DEV_SERVER_CHECK_TIMEOUT
6
+ ? parseInt(process.env.RWSDK_DEV_SERVER_CHECK_TIMEOUT, 10)
7
+ : 5 * 60 * 1000;
8
+ const log = debug("rwsdk:e2e:dev");
9
+ /**
10
+ * Run the local development server and return the URL
11
+ */
12
+ export async function runDevServer(packageManager = "pnpm", cwd) {
13
+ console.log("🚀 Starting development server...");
14
+ // Function to stop the dev server - defined early so we can use it in error handling
15
+ let devProcess = null;
16
+ let isErrorExpected = false;
17
+ const stopDev = async () => {
18
+ isErrorExpected = true;
19
+ if (!devProcess || !devProcess.pid) {
20
+ log("No dev process to stop or PID is missing");
21
+ return;
22
+ }
23
+ console.log("Stopping development server...");
24
+ try {
25
+ // Send a regular termination signal to the entire process group first
26
+ process.kill(-devProcess.pid, "SIGTERM");
27
+ }
28
+ catch (e) {
29
+ log("Could not send SIGTERM to dev server process group: %O", e);
30
+ }
31
+ // Wait for the process to terminate with a timeout
32
+ const terminationTimeout = 5000; // 5 seconds
33
+ const processExitPromise = devProcess.catch(() => {
34
+ // We expect this promise to reject when the process is killed,
35
+ // so we catch and ignore the error.
36
+ });
37
+ const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(undefined), terminationTimeout));
38
+ await Promise.race([processExitPromise, timeoutPromise]);
39
+ // Check if the process is still alive. We can't reliably check exitCode
40
+ // on a detached process, so we try sending a signal 0, which errors
41
+ // if the process doesn't exist.
42
+ let isAlive = true;
43
+ try {
44
+ // Sending signal 0 doesn't kill the process, but checks if it exists
45
+ process.kill(-devProcess.pid, 0);
46
+ }
47
+ catch (e) {
48
+ isAlive = false;
49
+ }
50
+ // If not terminated within timeout, force kill the entire process group
51
+ if (isAlive) {
52
+ log("Dev server process did not terminate within timeout, force killing with SIGKILL");
53
+ console.log("⚠️ Development server not responding after 5 seconds timeout, force killing...");
54
+ try {
55
+ process.kill(-devProcess.pid, "SIGKILL");
56
+ }
57
+ catch (e) {
58
+ log("Could not send SIGKILL to dev server process group: %O", e);
59
+ }
60
+ }
61
+ console.log("Development server stopped");
62
+ };
63
+ try {
64
+ // Check if we're in CI mode
65
+ const inCIMode = process.env.CI === "true" || process.env.CI === "1";
66
+ // Start dev server with stdout pipe to capture URL
67
+ // Create environment variables object
68
+ const env = {
69
+ ...process.env,
70
+ NODE_ENV: "development",
71
+ };
72
+ // Disable colors when running in CI mode to make URL parsing more reliable
73
+ if (inCIMode) {
74
+ log("Running in CI mode, disabling colors for dev server output");
75
+ env.NO_COLOR = "1";
76
+ env.FORCE_COLOR = "0";
77
+ }
78
+ // Map package manager names to actual commands
79
+ const getPackageManagerCommand = (pm) => {
80
+ switch (pm) {
81
+ case "yarn-classic":
82
+ return "yarn";
83
+ default:
84
+ return pm;
85
+ }
86
+ };
87
+ const pm = getPackageManagerCommand(packageManager);
88
+ // Use the provided cwd if available
89
+ devProcess = $({
90
+ all: true,
91
+ detached: true, // Run in a new process group so we can kill the entire group
92
+ cleanup: false, // Don't auto-kill on exit
93
+ cwd: cwd || process.cwd(), // Use provided directory or current directory
94
+ env, // Pass the updated environment variables
95
+ stdio: "pipe", // Ensure streams are piped
96
+ }) `${pm} run dev`;
97
+ devProcess.catch((error) => {
98
+ if (!isErrorExpected) {
99
+ // Don't re-throw. The error will be handled gracefully by the polling
100
+ // logic in `waitForUrl`, which will detect that the process has exited.
101
+ // Re-throwing here would cause an unhandled promise rejection.
102
+ log("Dev server process exited unexpectedly:", error.shortMessage);
103
+ }
104
+ });
105
+ log("Development server process spawned in directory: %s", cwd || process.cwd());
106
+ // Store chunks to parse the URL
107
+ let url = "";
108
+ let allOutput = "";
109
+ // Listen for all output to get the URL
110
+ const handleOutput = (data, source) => {
111
+ const output = data.toString();
112
+ console.log(output);
113
+ allOutput += output; // Accumulate all output
114
+ log("Received output from %s: %s", source, output.replace(/\n/g, "\\n"));
115
+ if (!url) {
116
+ // Multiple patterns to catch different package manager outputs
117
+ const patterns = [
118
+ // Standard Vite output: "Local: http://localhost:5173/"
119
+ /Local:\s*(?:\u001b\[\d+m)?(https?:\/\/localhost:\d+)/i,
120
+ // Alternative Vite output: "➜ Local: http://localhost:5173/"
121
+ /[➜→]\s*Local:\s*(?:\u001b\[\d+m)?(https?:\/\/localhost:\d+)/i,
122
+ // Unicode-safe arrow pattern
123
+ /[\u27A1\u2192\u279C]\s*Local:\s*(?:\u001b\[\d+m)?(https?:\/\/localhost:\d+)/i,
124
+ // Direct URL pattern: "http://localhost:5173"
125
+ /(https?:\/\/localhost:\d+)/i,
126
+ // Port-only pattern: "localhost:5173"
127
+ /localhost:(\d+)/i,
128
+ // Server ready messages
129
+ /server.*ready.*localhost:(\d+)/i,
130
+ /dev server.*localhost:(\d+)/i,
131
+ ];
132
+ for (const pattern of patterns) {
133
+ const match = output.match(pattern);
134
+ log("Testing pattern %s against output: %s", pattern.source, output.replace(/\n/g, "\\n"));
135
+ if (match) {
136
+ log("Pattern matched: %s, groups: %o", pattern.source, match);
137
+ if (match[1] && match[1].startsWith("http")) {
138
+ url = match[1];
139
+ log("Found development server URL with pattern %s: %s", pattern.source, url);
140
+ break;
141
+ }
142
+ else if (match[1] && /^\d+$/.test(match[1])) {
143
+ url = `http://localhost:${match[1]}`;
144
+ log("Found development server URL with port pattern %s: %s", pattern.source, url);
145
+ break;
146
+ }
147
+ }
148
+ }
149
+ // Log potential matches for debugging
150
+ if (!url &&
151
+ (output.includes("localhost") ||
152
+ output.includes("Local") ||
153
+ output.includes("server"))) {
154
+ log("Potential URL pattern found but not matched: %s", output.trim());
155
+ }
156
+ }
157
+ };
158
+ // Listen to all possible output streams
159
+ log("Setting up stream listeners. Available streams: all=%s, stdout=%s, stderr=%s", !!devProcess.all, !!devProcess.stdout, !!devProcess.stderr);
160
+ devProcess.all?.on("data", (data) => handleOutput(data, "all"));
161
+ devProcess.stdout?.on("data", (data) => handleOutput(data, "stdout"));
162
+ devProcess.stderr?.on("data", (data) => handleOutput(data, "stderr"));
163
+ // Also try listening to the raw process output
164
+ if (devProcess.child) {
165
+ log("Setting up child process stream listeners");
166
+ devProcess.child.stdout?.on("data", (data) => handleOutput(data, "child.stdout"));
167
+ devProcess.child.stderr?.on("data", (data) => handleOutput(data, "child.stderr"));
168
+ }
169
+ // Wait for URL with timeout
170
+ const waitForUrl = async () => {
171
+ const start = Date.now();
172
+ const timeout = 60000; // 60 seconds
173
+ while (Date.now() - start < timeout) {
174
+ if (url) {
175
+ return url;
176
+ }
177
+ // Fallback: check accumulated output if stream listeners aren't working
178
+ if (!url && allOutput) {
179
+ log("Checking accumulated output for URL patterns: %s", allOutput.replace(/\n/g, "\\n"));
180
+ const patterns = [
181
+ /Local:\s*(?:\u001b\[\d+m)?(https?:\/\/localhost:\d+)/i,
182
+ /[➜→]\s*Local:\s*(?:\u001b\[\d+m)?(https?:\/\/localhost:\d+)/i,
183
+ /[\u27A1\u2192\u279C]\s*Local:\s*(?:\u001b\[\d+m)?(https?:\/\/localhost:\d+)/i,
184
+ /(https?:\/\/localhost:\d+)/i,
185
+ /localhost:(\d+)/i,
186
+ ];
187
+ for (const pattern of patterns) {
188
+ const match = allOutput.match(pattern);
189
+ if (match) {
190
+ if (match[1] && match[1].startsWith("http")) {
191
+ url = match[1];
192
+ log("Found URL in accumulated output with pattern %s: %s", pattern.source, url);
193
+ return url;
194
+ }
195
+ else if (match[1] && /^\d+$/.test(match[1])) {
196
+ url = `http://localhost:${match[1]}`;
197
+ log("Found URL in accumulated output with port pattern %s: %s", pattern.source, url);
198
+ return url;
199
+ }
200
+ }
201
+ }
202
+ }
203
+ // Check if the process is still running
204
+ if (devProcess.exitCode !== null) {
205
+ log("ERROR: Development server process exited with code %d. Final output: %s", devProcess.exitCode, allOutput);
206
+ throw new Error(`Development server process exited with code ${devProcess.exitCode}`);
207
+ }
208
+ await sleep(500); // Check every 500ms
209
+ }
210
+ log("ERROR: Timed out waiting for dev server URL. Final accumulated output: %s", allOutput);
211
+ throw new Error("Timed out waiting for dev server URL");
212
+ };
213
+ // Wait for the URL
214
+ const serverUrl = await waitForUrl();
215
+ console.log(`✅ Development server started at ${serverUrl}`);
216
+ // Poll the URL to ensure it's live before proceeding
217
+ await poll(async () => {
218
+ try {
219
+ const response = await fetch(serverUrl, {
220
+ signal: AbortSignal.timeout(1000),
221
+ });
222
+ // We consider any response (even 4xx or 5xx) as success,
223
+ // as it means the worker is routable.
224
+ return response.status > 0;
225
+ }
226
+ catch (e) {
227
+ return false;
228
+ }
229
+ }, {
230
+ timeout: DEV_SERVER_CHECK_TIMEOUT,
231
+ });
232
+ return { url: serverUrl, stopDev };
233
+ }
234
+ catch (error) {
235
+ // Make sure to try to stop the server on error
236
+ log("Error during dev server startup: %O", error);
237
+ await stopDev().catch((e) => {
238
+ log("Failed to stop dev server during error handling: %O", e);
239
+ });
240
+ throw error;
241
+ }
242
+ }
@@ -0,0 +1,14 @@
1
+ import tmp from "tmp-promise";
2
+ import { SmokeTestOptions, TestResources, PackageManager } from "./types.mjs";
3
+ /**
4
+ * Sets up the test environment, preparing any resources needed for testing
5
+ */
6
+ export declare function setupTestEnvironment(options?: SmokeTestOptions): Promise<TestResources>;
7
+ /**
8
+ * Copy project to a temporary directory with a unique name
9
+ */
10
+ export declare function copyProjectToTempDir(projectDir: string, resourceUniqueKey: string, packageManager?: PackageManager, monorepoRoot?: string): Promise<{
11
+ tempDir: tmp.DirectoryResult;
12
+ targetDir: string;
13
+ workerName: string;
14
+ }>;
@@ -0,0 +1,266 @@
1
+ import { join } from "path";
2
+ import debug from "debug";
3
+ import { pathExists, copy } from "fs-extra";
4
+ import * as fs from "node:fs";
5
+ import tmp from "tmp-promise";
6
+ import ignore from "ignore";
7
+ import { relative, basename, resolve } from "path";
8
+ import { uniqueNamesGenerator, adjectives, animals, } from "unique-names-generator";
9
+ import { createHash } from "crypto";
10
+ import { $ } from "../../lib/$.mjs";
11
+ import { ROOT_DIR } from "../constants.mjs";
12
+ import path from "node:path";
13
+ import os from "os";
14
+ import { retry } from "./retry.mjs";
15
+ const log = debug("rwsdk:e2e:environment");
16
+ const createSdkTarball = async () => {
17
+ const packResult = await $({ cwd: ROOT_DIR, stdio: "pipe" }) `npm pack`;
18
+ const tarballName = packResult.stdout?.trim();
19
+ const tarballPath = path.join(ROOT_DIR, tarballName);
20
+ log(`📦 Created tarball: ${tarballPath}`);
21
+ const cleanupTarball = async () => {
22
+ if (fs.existsSync(tarballPath)) {
23
+ log(`🧹 Cleaning up tarball: ${tarballPath}`);
24
+ await fs.promises.rm(tarballPath, { force: true });
25
+ }
26
+ };
27
+ return { tarballPath, cleanupTarball };
28
+ };
29
+ const setTarballDependency = async (targetDir, tarballName) => {
30
+ const filePath = join(targetDir, "package.json");
31
+ const packageJson = await fs.promises.readFile(filePath, "utf-8");
32
+ const packageJsonContent = JSON.parse(packageJson);
33
+ packageJsonContent.dependencies.rwsdk = `file:${tarballName}`;
34
+ await fs.promises.writeFile(filePath, JSON.stringify(packageJsonContent, null, 2));
35
+ };
36
+ /**
37
+ * Sets up the test environment, preparing any resources needed for testing
38
+ */
39
+ export async function setupTestEnvironment(options = {}) {
40
+ log("Setting up test environment with options: %O", options);
41
+ // Generate a resource unique key for this test run right at the start
42
+ const uniqueNameSuffix = uniqueNamesGenerator({
43
+ dictionaries: [adjectives, animals],
44
+ separator: "-",
45
+ length: 2,
46
+ style: "lowerCase",
47
+ });
48
+ // Create a short unique hash based on the timestamp
49
+ const hash = createHash("md5")
50
+ .update(Date.now().toString())
51
+ .digest("hex")
52
+ .substring(0, 8);
53
+ // Create a resource unique key even if we're not copying a project
54
+ const resourceUniqueKey = `${uniqueNameSuffix}-${hash}`;
55
+ const resources = {
56
+ tempDirCleanup: undefined,
57
+ workerName: undefined,
58
+ originalCwd: process.cwd(),
59
+ targetDir: undefined,
60
+ workerCreatedDuringTest: false,
61
+ stopDev: undefined,
62
+ resourceUniqueKey, // Set at initialization
63
+ };
64
+ log("Current working directory: %s", resources.originalCwd);
65
+ try {
66
+ // If a project dir is specified, copy it to a temp dir with a unique name
67
+ if (options.projectDir) {
68
+ log("Project directory specified: %s", options.projectDir);
69
+ const { tempDir, targetDir, workerName } = await copyProjectToTempDir(options.projectDir, resourceUniqueKey, // Pass in the existing resourceUniqueKey
70
+ options.packageManager);
71
+ // Store cleanup function
72
+ resources.tempDirCleanup = tempDir.cleanup;
73
+ resources.workerName = workerName;
74
+ resources.targetDir = targetDir;
75
+ log("Target directory: %s", targetDir);
76
+ }
77
+ else {
78
+ log("No project directory specified, using current directory");
79
+ // When no project dir is specified, we'll use the current directory
80
+ resources.targetDir = resources.originalCwd;
81
+ }
82
+ return resources;
83
+ }
84
+ catch (error) {
85
+ log("Error during test environment setup: %O", error);
86
+ throw error;
87
+ }
88
+ }
89
+ /**
90
+ * Copy project to a temporary directory with a unique name
91
+ */
92
+ export async function copyProjectToTempDir(projectDir, resourceUniqueKey, packageManager, monorepoRoot) {
93
+ const { tarballPath, cleanupTarball } = await createSdkTarball();
94
+ try {
95
+ log("Creating temporary directory for project");
96
+ // Create a temporary directory
97
+ const tempDir = await tmp.dir({ unsafeCleanup: true });
98
+ // Determine the source directory to copy from
99
+ const sourceDir = monorepoRoot || projectDir;
100
+ // Create unique project directory name
101
+ const originalDirName = basename(sourceDir);
102
+ const workerName = `${originalDirName}-test-${resourceUniqueKey}`;
103
+ const tempCopyRoot = resolve(tempDir.path, workerName);
104
+ // If it's a monorepo, the targetDir for commands is a subdirectory
105
+ const targetDir = monorepoRoot
106
+ ? resolve(tempCopyRoot, relative(monorepoRoot, projectDir))
107
+ : tempCopyRoot;
108
+ console.log(`Copying project from ${sourceDir} to ${tempCopyRoot}`);
109
+ // Read project's .gitignore if it exists
110
+ let ig = ignore();
111
+ const gitignorePath = join(sourceDir, ".gitignore");
112
+ if (await pathExists(gitignorePath)) {
113
+ log("Found .gitignore file at %s", gitignorePath);
114
+ const gitignoreContent = await fs.promises.readFile(gitignorePath, "utf-8");
115
+ ig = ig.add(gitignoreContent);
116
+ }
117
+ else {
118
+ log("No .gitignore found, using default ignore patterns");
119
+ // Add default ignores if no .gitignore exists
120
+ ig = ig.add([
121
+ "node_modules",
122
+ ".git",
123
+ "dist",
124
+ "build",
125
+ ".DS_Store",
126
+ "coverage",
127
+ ".cache",
128
+ ".wrangler",
129
+ ".env",
130
+ ].join("\n"));
131
+ }
132
+ // Copy the project directory, respecting .gitignore
133
+ log("Starting copy process with ignored patterns");
134
+ await copy(sourceDir, tempCopyRoot, {
135
+ filter: (src) => {
136
+ // Get path relative to project directory
137
+ const relativePath = relative(sourceDir, src);
138
+ if (!relativePath)
139
+ return true; // Include the root directory
140
+ // Check against ignore patterns
141
+ const result = !ig.ignores(relativePath);
142
+ return result;
143
+ },
144
+ });
145
+ log("Project copy completed successfully");
146
+ // Copy the SDK tarball into the target directory
147
+ const tarballFilename = basename(tarballPath);
148
+ const tempTarballPath = join(targetDir, tarballFilename);
149
+ await fs.promises.copyFile(tarballPath, tempTarballPath);
150
+ if (monorepoRoot) {
151
+ log("⚙️ Configuring monorepo workspace...");
152
+ const rwsdkWsPath = join(tempCopyRoot, "rwsdk-workspace.json");
153
+ if (await pathExists(rwsdkWsPath)) {
154
+ const rwsdkWs = JSON.parse(await fs.promises.readFile(rwsdkWsPath, "utf-8"));
155
+ const workspaces = rwsdkWs.workspaces;
156
+ if (packageManager === "pnpm") {
157
+ const pnpmWsPath = join(tempCopyRoot, "pnpm-workspace.yaml");
158
+ const pnpmWsConfig = `packages:\n${workspaces.map((w) => ` - '${w}'`).join("\n")}\n`;
159
+ await fs.promises.writeFile(pnpmWsPath, pnpmWsConfig);
160
+ log("Created pnpm-workspace.yaml");
161
+ }
162
+ else {
163
+ // For npm and yarn, add a workspaces property to package.json
164
+ const pkgJsonPath = join(tempCopyRoot, "package.json");
165
+ const pkgJson = JSON.parse(await fs.promises.readFile(pkgJsonPath, "utf-8"));
166
+ pkgJson.workspaces = workspaces;
167
+ await fs.promises.writeFile(pkgJsonPath, JSON.stringify(pkgJson, null, 2));
168
+ log("Added workspaces to package.json");
169
+ }
170
+ }
171
+ }
172
+ // Configure temp project to not use frozen lockfile
173
+ log("⚙️ Configuring temp project to not use frozen lockfile...");
174
+ const npmrcPath = join(targetDir, ".npmrc");
175
+ await fs.promises.writeFile(npmrcPath, "frozen-lockfile=false\n");
176
+ // For yarn, create .yarnrc.yml to disable PnP and allow lockfile changes
177
+ if (packageManager === "yarn") {
178
+ const yarnrcPath = join(targetDir, ".yarnrc.yml");
179
+ const yarnCacheDir = path.join(os.tmpdir(), "yarn-cache");
180
+ await fs.promises.mkdir(yarnCacheDir, { recursive: true });
181
+ const yarnConfig = [
182
+ // todo(justinvdm, 23-09-23): Support yarn pnpm
183
+ "nodeLinker: node-modules",
184
+ "enableImmutableInstalls: false",
185
+ `cacheFolder: "${yarnCacheDir}"`,
186
+ ].join("\n");
187
+ await fs.promises.writeFile(yarnrcPath, yarnConfig);
188
+ log("Created .yarnrc.yml to allow lockfile changes for yarn");
189
+ }
190
+ await setTarballDependency(targetDir, tarballFilename);
191
+ // Install dependencies in the target directory
192
+ const installDir = monorepoRoot ? tempCopyRoot : targetDir;
193
+ await retry(() => installDependencies(installDir, packageManager), {
194
+ retries: 3,
195
+ delay: 1000,
196
+ });
197
+ // Return the environment details
198
+ return { tempDir, targetDir, workerName };
199
+ }
200
+ finally {
201
+ await cleanupTarball();
202
+ }
203
+ }
204
+ async function installDependencies(targetDir, packageManager = "pnpm") {
205
+ console.log(`📦 Installing project dependencies in ${targetDir} using ${packageManager}...`);
206
+ try {
207
+ // Clean up any pre-existing node_modules and lockfiles
208
+ log("Cleaning up pre-existing node_modules and lockfiles...");
209
+ await Promise.all([
210
+ fs.promises.rm(join(targetDir, "node_modules"), {
211
+ recursive: true,
212
+ force: true,
213
+ }),
214
+ fs.promises.rm(join(targetDir, "pnpm-lock.yaml"), { force: true }),
215
+ fs.promises.rm(join(targetDir, "yarn.lock"), { force: true }),
216
+ fs.promises.rm(join(targetDir, "package-lock.json"), { force: true }),
217
+ ]);
218
+ log("Cleanup complete.");
219
+ if (packageManager.startsWith("yarn")) {
220
+ log(`Enabling corepack...`);
221
+ await $("corepack", ["enable"], { cwd: targetDir, stdio: "pipe" });
222
+ if (packageManager === "yarn") {
223
+ log(`Preparing yarn@stable with corepack...`);
224
+ await $("corepack", ["prepare", "yarn@stable", "--activate"], {
225
+ cwd: targetDir,
226
+ stdio: "pipe",
227
+ });
228
+ }
229
+ else if (packageManager === "yarn-classic") {
230
+ log(`Preparing yarn@1.22.19 with corepack...`);
231
+ await $("corepack", ["prepare", "yarn@1.22.19", "--activate"], {
232
+ cwd: targetDir,
233
+ stdio: "pipe",
234
+ });
235
+ }
236
+ }
237
+ const npmCacheDir = path.join(os.tmpdir(), "npm-cache");
238
+ await fs.promises.mkdir(npmCacheDir, { recursive: true });
239
+ const installCommand = {
240
+ pnpm: ["pnpm", "install"],
241
+ npm: ["npm", "install", "--cache", npmCacheDir],
242
+ yarn: ["yarn", "install"],
243
+ "yarn-classic": ["yarn"],
244
+ }[packageManager];
245
+ // Run install command in the target directory
246
+ log(`Running ${installCommand.join(" ")}`);
247
+ const [command, ...args] = installCommand;
248
+ const result = await $(command, args, {
249
+ cwd: targetDir,
250
+ stdio: "pipe", // Capture output
251
+ env: {
252
+ YARN_ENABLE_HARDENED_MODE: "0",
253
+ },
254
+ });
255
+ console.log("✅ Dependencies installed successfully");
256
+ // Log installation details at debug level
257
+ if (result.stdout) {
258
+ log(`${packageManager} install output: %s`, result.stdout);
259
+ }
260
+ }
261
+ catch (error) {
262
+ log("ERROR: Failed to install dependencies: %O", error);
263
+ console.error(`❌ Failed to install dependencies: ${error instanceof Error ? error.message : String(error)}`);
264
+ throw new Error(`Failed to install project dependencies. Please ensure the project can be installed with ${packageManager}.`);
265
+ }
266
+ }
@@ -0,0 +1,8 @@
1
+ export * from "./testHarness.mjs";
2
+ export * from "./tarball.mjs";
3
+ export * from "./environment.mjs";
4
+ export * from "./dev.mjs";
5
+ export * from "./browser.mjs";
6
+ export * from "./release.mjs";
7
+ export * from "./types.mjs";
8
+ export * from "./poll.mjs";