diff --git a/deno.lock b/deno.lock index 9df02b7f..a60b0181 100644 --- a/deno.lock +++ b/deno.lock @@ -81,10 +81,12 @@ "npm:feed@^5.1.0": "5.1.0", "npm:fflate@~0.8.2": "0.8.2", "npm:github-slugger@2": "2.0.0", + "npm:ioredis@^5.7.0": "5.7.0", "npm:linkedom@~0.18.10": "0.18.12", "npm:marked-mangle@^1.1.9": "1.1.11_marked@15.0.12", "npm:marked@^15.0.11": "15.0.12", "npm:mime-db@^1.54.0": "1.54.0", + "npm:pg@^8.16.3": "8.16.3", "npm:postcss@8.5.6": "8.5.6", "npm:postcss@^8.5.6": "8.5.6", "npm:preact-render-to-string@^6.5.11": "6.6.1_preact@10.27.1", @@ -1044,6 +1046,9 @@ "os": ["win32"], "cpu": ["x64"] }, + "@ioredis/commands@1.3.1": { + "integrity": "sha512-bYtU8avhGIcje3IhvF9aSjsa5URMZBHnwKtOvXsT4sfYy9gppW11gLPT/9oNqlJZD47yPKveQFTAFWpHjKvUoQ==" + }, "@isaacs/balanced-match@4.0.1": { "integrity": "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==" }, @@ -1607,6 +1612,9 @@ "wrap-ansi@7.0.0" ] }, + "cluster-key-slot@1.1.2": { + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==" + }, "code-block-writer@13.0.3": { "integrity": "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg==" }, @@ -1757,6 +1765,9 @@ "define-lazy-prop@3.0.0": { "integrity": "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==" }, + "denque@2.1.0": { + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==" + }, "detect-libc@2.0.4": { "integrity": "sha512-3UDv+G9CsCKO1WKMGw9fwq/SWJYbI0c5Y7LU1AXYoDdbhE2AHQ6N6Nb34sG8Fj7T5APy8qXDCKuuIHd1BR0tVA==" }, @@ -1974,6 +1985,20 @@ "entities@6.0.1" ] }, + "ioredis@5.7.0": { + "integrity": "sha512-NUcA93i1lukyXU+riqEyPtSEkyFq8tX90uL659J+qpCZ3rEdViB/APC58oAhIh3+bJln2hzdlZbBZsGNrlsR8g==", + "dependencies": [ + "@ioredis/commands", + "cluster-key-slot", + "debug", + "denque", + "lodash.defaults", + "lodash.isarguments", + "redis-errors", + "redis-parser", + "standard-as-callback" + ] + }, "is-binary-path@2.1.0": { "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", "dependencies": [ @@ -2143,6 +2168,12 @@ "uhyphen" ] }, + "lodash.defaults@4.2.0": { + "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==" + }, + "lodash.isarguments@3.1.0": { + "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==" + }, "lodash.memoize@4.1.2": { "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==" }, @@ -2302,6 +2333,53 @@ "perfect-debounce@2.0.0": { "integrity": "sha512-fkEH/OBiKrqqI/yIgjR92lMfs2K8105zt/VT6+7eTjNwisrsh47CeIED9z58zI7DfKdH3uHAn25ziRZn3kgAow==" }, + "pg-cloudflare@1.2.7": { + "integrity": "sha512-YgCtzMH0ptvZJslLM1ffsY4EuGaU0cx4XSdXLRFae8bPP4dS5xL1tNB3k2o/N64cHJpwU7dxKli/nZ2lUa5fLg==" + }, + "pg-connection-string@2.9.1": { + "integrity": "sha512-nkc6NpDcvPVpZXxrreI/FOtX3XemeLl8E0qFr6F2Lrm/I8WOnaWNhIPK2Z7OHpw7gh5XJThi6j6ppgNoaT1w4w==" + }, + "pg-int8@1.0.1": { + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==" + }, + "pg-pool@3.10.1_pg@8.16.3": { + "integrity": "sha512-Tu8jMlcX+9d8+QVzKIvM/uJtp07PKr82IUOYEphaWcoBhIYkoHpLXN3qO59nAI11ripznDsEzEv8nUxBVWajGg==", + "dependencies": [ + "pg" + ] + }, + "pg-protocol@1.10.3": { + "integrity": "sha512-6DIBgBQaTKDJyxnXaLiLR8wBpQQcGWuAESkRBX/t6OwA8YsqP+iVSiond2EDy6Y/dsGk8rh/jtax3js5NeV7JQ==" + }, + "pg-types@2.2.0": { + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "dependencies": [ + "pg-int8", + "postgres-array", + "postgres-bytea", + "postgres-date", + "postgres-interval" + ] + }, + "pg@8.16.3": { + "integrity": "sha512-enxc1h0jA/aq5oSDMvqyW3q89ra6XIIDZgCX9vkMrnz5DFTw/Ny3Li2lFQ+pt3L6MCgm/5o2o8HW9hiJji+xvw==", + "dependencies": [ + "pg-connection-string", + "pg-pool", + "pg-protocol", + "pg-types", + "pgpass" + ], + "optionalDependencies": [ + "pg-cloudflare" + ] + }, + "pgpass@1.0.5": { + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "dependencies": [ + "split2" + ] + }, "picocolors@1.1.1": { "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" }, @@ -2570,6 +2648,21 @@ "source-map-js" ] }, + "postgres-array@2.0.0": { + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==" + }, + "postgres-bytea@1.0.0": { + "integrity": "sha512-xy3pmLuQqRBZBXDULy7KbaitYqLcmxigw14Q5sj8QBVLqEwXfeybIKVWiqAXTlcvdvb0+xkOtDbfQMOf4lST1w==" + }, + "postgres-date@1.0.7": { + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==" + }, + "postgres-interval@1.2.0": { + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "dependencies": [ + "xtend" + ] + }, "preact-render-to-string@6.6.1_preact@10.27.1": { "integrity": "sha512-IIMfXRjmbSP9QmG18WJLQa4Z4yx3J0VC9QN5q9z2XYlWSzFlJ+bSm/AyLyyV/YFwjof1OXFX2Mz6Ao60LXudJg==", "dependencies": [ @@ -2597,6 +2690,15 @@ "picomatch@2.3.1" ] }, + "redis-errors@1.2.0": { + "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==" + }, + "redis-parser@3.0.0": { + "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", + "dependencies": [ + "redis-errors" + ] + }, "require-directory@2.1.1": { "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==" }, @@ -2699,6 +2801,12 @@ "source-map@0.7.6": { "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==" }, + "split2@4.2.0": { + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==" + }, + "standard-as-callback@2.1.0": { + "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==" + }, "string-width@4.2.3": { "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dependencies": [ @@ -3007,6 +3115,9 @@ ], "bin": true }, + "xtend@4.0.2": { + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==" + }, "y18n@5.0.8": { "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==" }, @@ -3174,7 +3285,9 @@ "npm:@types/babel__core@^7.20.5", "npm:@types/node@^24.1.0", "npm:feed@^5.1.0", + "npm:ioredis@^5.7.0", "npm:mime-db@^1.54.0", + "npm:pg@^8.16.3", "npm:preact@^10.26.9", "npm:rollup-plugin-visualizer@^6.0.3", "npm:vite-plugin-inspect@^11.3.2", diff --git a/packages/fresh/src/dev/update_check_test.ts b/packages/fresh/src/dev/update_check_test.ts index 09e14cc3..e522f60a 100644 --- a/packages/fresh/src/dev/update_check_test.ts +++ b/packages/fresh/src/dev/update_check_test.ts @@ -5,6 +5,7 @@ import { expect } from "@std/expect"; import { withTmpDir } from "../test_utils.ts"; import type { CheckFile } from "./update_check.ts"; import { WEEK } from "../constants.ts"; +import { retry } from "@std/async/retry"; const CURRENT_VERSION = denoJson.version; @@ -333,49 +334,51 @@ Deno.test("doesn't show update if last_shown + interval >= today", async () => { Deno.test( "shows update if last_shown + interval < today", async () => { - await using tmp = await withTmpDir(); + await retry(async () => { + await using tmp = await withTmpDir(); - const yesterday = new Date(); - yesterday.setDate(yesterday.getDate() - 1); + const yesterday = new Date(); + yesterday.setDate(yesterday.getDate() - 1); - const checkFile: CheckFile = { - current_version: "1.2.0", - latest_version: "99.999.99", - last_checked: new Date().toISOString(), - last_shown: yesterday.toISOString(), - }; + const checkFile: CheckFile = { + current_version: "1.2.0", + latest_version: "99.999.99", + last_checked: new Date().toISOString(), + last_shown: yesterday.toISOString(), + }; - await Deno.writeTextFile( - path.join(tmp.dir, "latest.json"), - JSON.stringify(checkFile, null, 2), - ); - - const out = await new Deno.Command(Deno.execPath(), { - args: [ - "run", - "-A", - path.join(cwd, "../../tests/fixture_update_check/mod.ts"), - ], - cwd, - env: { - CI: "false", - TEST_HOME: tmp.dir, - CURRENT_VERSION: CURRENT_VERSION, - LATEST_VERSION: "99999.9999.0", - }, - stderr: "piped", - stdout: "piped", - }).output(); - - const { stdout } = getStdOutput(out); - expect(stdout).toMatch(/Fresh .* is available/); - - const checkFileAfter = JSON.parse( - await Deno.readTextFile( + await Deno.writeTextFile( path.join(tmp.dir, "latest.json"), - ), - ); + JSON.stringify(checkFile, null, 2), + ); - expect(checkFileAfter.last_shown).not.toEqual(yesterday.toISOString()); + const out = await new Deno.Command(Deno.execPath(), { + args: [ + "run", + "-A", + path.join(cwd, "../../tests/fixture_update_check/mod.ts"), + ], + cwd, + env: { + CI: "false", + TEST_HOME: tmp.dir, + CURRENT_VERSION: CURRENT_VERSION, + LATEST_VERSION: "99999.9999.0", + }, + stderr: "piped", + stdout: "piped", + }).output(); + + const { stdout } = getStdOutput(out); + expect(stdout).toMatch(/Fresh .* is available/); + + const checkFileAfter = JSON.parse( + await Deno.readTextFile( + path.join(tmp.dir, "latest.json"), + ), + ); + + expect(checkFileAfter.last_shown).not.toEqual(yesterday.toISOString()); + }, { maxAttempts: 5 }); }, ); diff --git a/packages/plugin-vite/demo/routes/tests/ioredis.tsx b/packages/plugin-vite/demo/routes/tests/ioredis.tsx new file mode 100644 index 00000000..1b1ba601 --- /dev/null +++ b/packages/plugin-vite/demo/routes/tests/ioredis.tsx @@ -0,0 +1,7 @@ +import * as ioredis from "ioredis"; + +export default function Page() { + // deno-lint-ignore no-console + console.log(ioredis); + return

ioredis

; +} diff --git a/packages/plugin-vite/demo/routes/tests/pg.tsx b/packages/plugin-vite/demo/routes/tests/pg.tsx new file mode 100644 index 00000000..fa3c1b15 --- /dev/null +++ b/packages/plugin-vite/demo/routes/tests/pg.tsx @@ -0,0 +1,7 @@ +import * as pg from "pg"; + +export default function Page() { + // deno-lint-ignore no-console + console.log(pg); + return

pg

; +} diff --git a/packages/plugin-vite/deno.json b/packages/plugin-vite/deno.json index 6b4282d2..2949736d 100644 --- a/packages/plugin-vite/deno.json +++ b/packages/plugin-vite/deno.json @@ -31,7 +31,9 @@ "@types/node": "npm:@types/node@^24.1.0", "feed": "npm:feed@^5.1.0", "fresh": "jsr:@fresh/core@^2.0.0-alpha.60", + "ioredis": "npm:ioredis@^5.7.0", "mime-db": "npm:mime-db@^1.54.0", + "pg": "npm:pg@^8.16.3", "preact": "npm:preact@^10.26.9", "rollup-plugin-visualizer": "npm:rollup-plugin-visualizer@^6.0.3", "vite": "npm:vite@^7.1.4", diff --git a/packages/plugin-vite/src/plugins/patches.ts b/packages/plugin-vite/src/plugins/patches.ts index 76315a86..a9036015 100644 --- a/packages/plugin-vite/src/plugins/patches.ts +++ b/packages/plugin-vite/src/plugins/patches.ts @@ -7,6 +7,7 @@ import { inlineEnvVarsPlugin } from "./patches/inline_env_vars.ts"; import { removePolyfills } from "./patches/remove_polyfills.ts"; import { JS_REG, JSX_REG } from "../utils.ts"; import { denoGlobal } from "./patches/deno_global.ts"; +import { codeEvalPlugin } from "./patches/code_eval.ts"; export function patches(): Plugin { let isDev = false; @@ -33,13 +34,14 @@ export function patches(): Plugin { }]); } + const env = isDev ? "development" : "production"; + const plugins: babel.PluginItem[] = [ + codeEvalPlugin(options?.ssr ? "ssr" : "client", env), cjsPlugin, removePolyfills, jsxComments, - inlineEnvVarsPlugin( - isDev ? "development" : "production", - ), + inlineEnvVarsPlugin(env, Deno.env.toObject()), ]; if (!options?.ssr) { diff --git a/packages/plugin-vite/src/plugins/patches/code_eval.ts b/packages/plugin-vite/src/plugins/patches/code_eval.ts new file mode 100644 index 00000000..445e3451 --- /dev/null +++ b/packages/plugin-vite/src/plugins/patches/code_eval.ts @@ -0,0 +1,284 @@ +import type { PluginObj, PluginPass, types } from "@babel/core"; + +const APPLY_PG_QUIRKS = "applyPgQuirks"; + +export function codeEvalPlugin( + env: "ssr" | "client", + mode: string, +) { + return ( + { types: t }: { types: typeof types }, + ): PluginObj => { + return { + name: "fresh-remove-polyfills", + visitor: { + IfStatement: { + enter(path, state) { + const res = evaluateExpr(t, env, mode, path.node.test, state); + // Could not evaluate + if (res === null) return; + if (res) { + if (t.isBlockStatement(path.node.consequent)) { + path.replaceWithMultiple(path.node.consequent.body); + } else { + path.replaceWith(path.node.consequent); + } + } else if (path.node.alternate) { + if (t.isBlockStatement(path.node.alternate)) { + path.replaceWithMultiple(path.node.alternate.body); + } else { + path.replaceWith(path.node.alternate); + } + } else { + path.remove(); + } + }, + }, + CallExpression: { + enter(path) { + if ( + t.isMemberExpression(path.node.callee) && + t.isIdentifier(path.node.callee.object) && + t.isIdentifier(path.node.callee.property) && + path.node.callee.object.name === "Object" && + path.node.callee.property.name === "defineProperty" && + path.node.arguments.length >= 2 + ) { + const args = path.node.arguments; + + if ( + t.isIdentifier(args[0]) && args[0].name === "exports" || + t.isMemberExpression(args[0]) && + t.isIdentifier(args[0].object) && + t.isIdentifier(args[0].property) && + args[0].object.name === "module" && + args[0].property.name === "exports" && + t.isStringLiteral(args[1]) && args[1].value === "native" + ) { + path.remove(); + } + } + }, + }, + }, + }; + }; +} + +function evaluateExpr( + t: typeof types, + env: "client" | "ssr", + mode: string, + node: types.Node, + state: PluginPass, +): boolean | null { + if (t.isLogicalExpression(node)) { + const left = evaluateExpr(t, env, mode, node.left, state); + if (left === null) return null; + if (left && node.operator === "||") return true; + + const right = evaluateExpr(t, env, mode, node.right, state); + if (right === null) return null; + + switch (node.operator) { + case "||": + return left || right; + case "&&": + return left && right; + case "??": + return left ?? right; + default: + return false; + } + } else if (t.isBinaryExpression(node)) { + // Check: typeof process == "undefined" + // Check: typeof process === "undefined" + // Check: typeof process != "undefined" + // Check: typeof process !== "undefined" + if ( + t.isUnaryExpression(node.left) && node.left.operator === "typeof" && + t.isIdentifier(node.left.argument) && + node.left.argument.name === "process" && t.isStringLiteral(node.right) && + node.right.value === "undefined" + ) { + if (node.operator === "==" || node.operator === "===") { + return env !== "ssr"; + } else if (node.operator === "!=" || node.operator === "!==") { + return env === "ssr"; + } + } else if ( + // Workaround for npm:pg + // Check: typeof process.env.NODE_PG_FORCE_NATIVE !== "undefined" + t.isUnaryExpression(node.left) && + t.isMemberExpression(node.left.argument) && + t.isMemberExpression(node.left.argument.object) && + t.isIdentifier(node.left.argument.object.object) && + node.left.argument.object.object.name === "process" && + t.isIdentifier(node.left.argument.object.property) && + node.left.argument.object.property.name === "env" && + t.isIdentifier(node.left.argument.property) && + node.left.argument.property.name === "NODE_PG_FORCE_NATIVE" && + t.isStringLiteral(node.right) + ) { + state.set(APPLY_PG_QUIRKS, true); + const left = typeof Deno.env.get("NODE_PG_FORCE_NATIVE"); + const right = node.right.value; + + const result = applyBinExpr(left, right, node); + if (result !== null) return result; + } else if ( + // Check: process.env.NODE_ENV == "production" + // Check: process.env.NODE_ENV === "production" + // Check: process.env.NODE_ENV != "production" + // Check: process.env.NODE_ENV !== "production" + // Check: process.env.NODE_ENV == "development" + // Check: process.env.NODE_ENV === "development" + // Check: process.env.NODE_ENV != "development" + // Check: process.env.NODE_ENV !== "development" + t.isMemberExpression(node.left) && + t.isMemberExpression(node.left.object) && + t.isIdentifier(node.left.object.object) && + node.left.object.object.name === "process" && + t.isIdentifier(node.left.object.property) && + node.left.object.property.name === "env" && + t.isIdentifier(node.left.property) && + node.left.property.name === "NODE_ENV" && + t.isStringLiteral(node.right) + ) { + const value = node.right.value; + + const result = applyBinExpr(mode, value, node); + if (result !== null) return result; + } else if ( + // Check: process.foo === "bar" + env === "ssr" && t.isMemberExpression(node.left) && + t.isIdentifier(node.left.object) && node.left.object.name === "process" && + t.isIdentifier(node.left.property) && + !PROCESS_PROPERTIES.has(node.left.property.name) + ) { + return false; + } + + return null; + } else if ( + t.isMemberExpression(node) && t.isIdentifier(node.object) && + node.object.name === "process" && t.isIdentifier(node.property) + ) { + return PROCESS_PROPERTIES.has(node.property.name); + } else if (t.isIdentifier(node) && node.name === "useLegacyCrypto") { + return false; + } + + return null; +} + +function applyBinExpr( + left: unknown, + right: unknown, + node: types.BinaryExpression, +): boolean | null { + switch (node.operator) { + case "==": + return left == right; + case "===": + return left === right; + case "!=": + return left != right; + case "!==": + return left !== right; + case "+": + case "-": + case "/": + case "%": + case "*": + case "**": + case "&": + case "|": + case ">>": + case ">>>": + case "<<": + case "^": + case "in": + case "instanceof": + case ">": + case "<": + case ">=": + case "<=": + case "|>": + break; + } + return null; +} + +const PROCESS_PROPERTIES = new Set([ + "abort", + "allowedNodeEnvironmentFlags", + "arch", + "argv", + "argv0", + "availableMemory", + "channel", + "chdir", + "config", + "connected", + "constrainedMemory", + "cpuUsage", + "cwd", + "debugPort", + "disconnect", + "dlopen", + "emitWarning", + "env", + "execArgv", + "execPath", + "execve", + "exit", + "exitCode", + "features", + "finalization", + "getActiveResourcesInfo", + "getBuiltinModule", + "getegid", + "geteuid", + "getgid", + "getgroups", + "getuid", + "hasUncaughtExceptionCaptureCallback", + "hrtime", + "initgroups", + "kill", + "loadEnvFile", + "mainModule", + "memoryUsage", + "nextTick", + "noDeprecation", + "permission", + "pid", + "platform", + "ppid", + "ref", + "release", + "report", + "resourceUsage", + "send", + "setegid", + "seteuid", + "setgid", + "setgroups", + "setuid", + "setSourceMapsEnabled", + "setUncaughtExceptionCaptureCallback", + "sourceMapsEnabled", + "stderr", + "stdin", + "stdout", + "throwDeprecation", + "threadCpuUsage", + "title", + "traceDeprecation", + "umask", + "unref", + "uptime", + "version", + "versions", +]); diff --git a/packages/plugin-vite/src/plugins/patches/code_eval_test.ts b/packages/plugin-vite/src/plugins/patches/code_eval_test.ts new file mode 100644 index 00000000..36f6db7c --- /dev/null +++ b/packages/plugin-vite/src/plugins/patches/code_eval_test.ts @@ -0,0 +1,138 @@ +import { expect } from "@std/expect/expect"; +import * as babel from "@babel/core"; +import { codeEvalPlugin } from "./code_eval.ts"; + +function runTest( + options: { + input: string; + expected: string; + env: "client" | "ssr"; + mode: "development" | "production"; + }, +) { + const res = babel.transformSync(options.input, { + filename: "foo.js", + babelrc: false, + plugins: [codeEvalPlugin(options.env, options.mode)], + }); + + const output = res?.code ?? ""; + expect(output).toEqual(options.expected); +} + +Deno.test("code eval - resolve runtime conditional detection", () => { + runTest({ + env: "client", + mode: "development", + input: + `if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +}`, + expected: `module.exports = require('./browser.js');`, + }); + + runTest({ + env: "client", + mode: "development", + input: `if (typeof process !== 'undefined') { + module.exports = require('./node.js'); +} else { + module.exports = require('./browser.js'); +}`, + expected: `module.exports = require('./browser.js');`, + }); + + runTest({ + env: "ssr", + mode: "development", + input: `if (typeof process === 'undefined') { + module.exports = require('./browser.js'); + } else { + module.exports = require('./node.js'); + }`, + expected: `module.exports = require('./node.js');`, + }); + + runTest({ + env: "ssr", + mode: "development", + input: `if (typeof process !== 'undefined') { + module.exports = require('./node.js'); +} else { + module.exports = require('./browser.js'); +}`, + expected: `module.exports = require('./node.js');`, + }); +}); + +Deno.test("code eval - resolve process.env.NODE_ENV", () => { + runTest({ + env: "client", + mode: "development", + input: `if (process.env.NODE_ENV === 'production') { + module.exports = require('./cjs/react.production.js'); +} else { + module.exports = require('./cjs/react.development.js'); +}`, + expected: `module.exports = require('./cjs/react.development.js');`, + }); + + runTest({ + env: "client", + mode: "production", + input: `if (process.env.NODE_ENV === 'production') { + module.exports = require('./cjs/react.production.js'); +} else { + module.exports = require('./cjs/react.development.js'); +}`, + expected: `module.exports = require('./cjs/react.production.js');`, + }); +}); + +Deno.test("code eval - npm:debug", () => { + runTest({ + env: "ssr", + mode: "development", + input: + `if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +}`, + expected: `module.exports = require('./node.js');`, + }); +}); + +Deno.test("code eval - npm:pg", () => { + runTest({ + env: "ssr", + mode: "development", + input: `if (typeof process.env.NODE_PG_FORCE_NATIVE !== "undefined") { + module.exports = require('./native.js'); +} else { + module.exports = require('./normal.js'); +}`, + expected: `module.exports = require('./normal.js');`, + }); +}); + +Deno.test("code eval - npm:pg #2", () => { + runTest({ + env: "ssr", + mode: "development", + input: + `const useLegacyCrypto = parseInt(process.versions && process.versions.node && process.versions.node.split('.')[0]) < 15 +if (useLegacyCrypto) { + // We are on an old version of Node.js that requires legacy crypto utilities. + module.exports = require('./utils-legacy') +} else { + module.exports = require('./utils-webcrypto') +} +`, + expected: + `const useLegacyCrypto = parseInt(process.versions && process.versions.node && process.versions.node.split('.')[0]) < 15; +module.exports = require('./utils-webcrypto');`, + }); +}); diff --git a/packages/plugin-vite/src/plugins/patches/commonjs.ts b/packages/plugin-vite/src/plugins/patches/commonjs.ts index 607256db..29c44836 100644 --- a/packages/plugin-vite/src/plugins/patches/commonjs.ts +++ b/packages/plugin-vite/src/plugins/patches/commonjs.ts @@ -1,4 +1,4 @@ -import type { PluginObj, types } from "@babel/core"; +import type { NodePath, PluginObj, types } from "@babel/core"; export function cjsPlugin( { types: t }: { types: typeof types }, @@ -9,6 +9,7 @@ export function cjsPlugin( const EXPORTED = "exported"; const EXPORTED_NAMESPACES = "exported_namespaces"; const ALIASED = "aliased"; + const NEEDS_REQUIRE_IMPORT = "needsRequireImport"; return { name: "fresh-cjs-esm", @@ -37,6 +38,40 @@ export function cjsPlugin( const exported = state.get(EXPORTED); const exportedNs = state.get(EXPORTED_NAMESPACES); + const needsRequireImport = state.get(NEEDS_REQUIRE_IMPORT); + + if (needsRequireImport) { + // Inject: + // ```ts + // import { createRequire } from "node:module"; + // const require = createRequire(import.meta.url); + // ``` + const id = t.identifier("createRequire"); + path.unshiftContainer( + "body", + t.variableDeclaration("const", [ + t.variableDeclarator( + t.identifier("require"), + t.callExpression(t.identifier("createRequire"), [ + t.memberExpression( + t.metaProperty( + t.identifier("import"), + t.identifier("meta"), + ), + t.identifier("url"), + ), + ]), + ), + ]), + ); + path.unshiftContainer( + "body", + t.importDeclaration( + [t.importSpecifier(id, id)], + t.stringLiteral("node:module"), + ), + ); + } const mappedNs: string[] = []; @@ -224,30 +259,53 @@ export function cjsPlugin( const mods = state.get(REQUIRE_CALLS) ?? []; state.set(REQUIRE_CALLS, mods); - mods.push({ - id, - specifier: t.cloneNode(path.node.arguments[0], true), - }); + if (t.isStringLiteral(path.node.arguments[0])) { + // Check if we can hoist it or if we need to keep it. + let canImport = true; + let parent: NodePath | null = path.parentPath; + while (parent !== null) { + if ( + t.isTryStatement(parent.node) || t.isIfStatement(parent.node) || + t.isConditionalExpression(parent.node) + ) { + canImport = false; + break; + } + parent = parent.parentPath; + } - if ( - path.parentPath?.isVariableDeclarator() && - path.parentPath?.get("id").isIdentifier() || - path.parentPath?.isCallExpression() - ) { - path.replaceWith( - t.logicalExpression( - "??", - t.memberExpression( + if (!canImport) { + state.set(NEEDS_REQUIRE_IMPORT, true); + return; + } + + mods.push({ + id, + specifier: t.cloneNode(path.node.arguments[0], true), + }); + + if ( + path.parentPath?.isVariableDeclarator() && + path.parentPath?.get("id").isIdentifier() || + path.parentPath?.isCallExpression() + ) { + path.replaceWith( + t.logicalExpression( + "??", + t.memberExpression( + t.cloneNode(id, true), + t.identifier("default"), + ), t.cloneNode(id, true), - t.identifier("default"), ), - t.cloneNode(id, true), - ), - ); - return; - } + ); + return; + } - path.replaceWith(t.cloneNode(id, true)); + path.replaceWith(t.cloneNode(id, true)); + } else { + state.set(NEEDS_REQUIRE_IMPORT, true); + } } else if ( t.isMemberExpression(path.node.callee) && t.isIdentifier(path.node.callee.object) && @@ -283,6 +341,24 @@ export function cjsPlugin( }, ExpressionStatement: { enter(path, state) { + // Check: Object.defineProperty(module.exports) "__esModule" ...) + // Check: Object.defineProperty(exports) "__esModule" ...) + if ( + t.isCallExpression(path.node.expression) && + t.isMemberExpression(path.node.expression.callee) && + t.isIdentifier(path.node.expression.callee.object) && + t.isIdentifier(path.node.expression.callee.property) && + path.node.expression.callee.object.name === "Object" && + path.node.expression.callee.property.name === "defineProperty" && + path.node.expression.arguments.length >= 2 && + t.isStringLiteral(path.node.expression.arguments[1]) && + path.node.expression.arguments[1].value === "__esModule" + ) { + state.set(HAS_ES_MODULE, true); + path.remove(); + return; + } + if ( t.isExpressionStatement(path.node) && t.isCallExpression(path.node.expression) && @@ -312,6 +388,92 @@ export function cjsPlugin( const alias = path.node.expression.callee.params[0].name; state.set(ALIASED, alias); } + } else if ( + // Check: Object.defineProperty(exports, "foo", { enumerable: true, get: function () { return foo; } }); + t.isCallExpression(path.node.expression) && + t.isMemberExpression(path.node.expression.callee) && + t.isIdentifier(path.node.expression.callee.object) && + path.node.expression.callee.object.name === "Object" && + t.isIdentifier(path.node.expression.callee.property) && + path.node.expression.callee.property.name === "defineProperty" && + path.node.expression.arguments.length >= 2 && + t.isIdentifier(path.node.expression.arguments[0]) && + path.node.expression.arguments[0].name === "exports" && + t.isStringLiteral(path.node.expression.arguments[1]) && + t.isObjectExpression(path.node.expression.arguments[2]) + ) { + const exported = path.node.expression.arguments[1].value; + const obj = path.node.expression.arguments[2]; + for (let i = 0; i < obj.properties.length; i++) { + const prop = obj.properties[i]; + + if ( + t.isObjectProperty(prop) && t.isIdentifier(prop.key) && + prop.key.name === "get" && t.isFunctionExpression(prop.value) && + t.isBlockStatement(prop.value.body) && + prop.value.body.body.length === 1 && + t.isReturnStatement(prop.value.body.body[0]) + ) { + const expr = prop.value.body.body[0].argument; + if (expr !== null && expr !== undefined) { + path.replaceWith( + t.assignmentExpression( + "=", + t.memberExpression( + t.identifier("exports"), + t.identifier(exported), + ), + t.cloneNode(expr, true), + ), + ); + } + } else if ( + t.isObjectMethod(prop) && t.isIdentifier(prop.key) && + prop.key.name === "get" && t.isBlockStatement(prop.body) && + prop.body.body.length === 1 && + t.isReturnStatement(prop.body.body[0]) + ) { + const expr = prop.body.body[0].argument; + if (expr !== null && expr !== undefined) { + path.replaceWith( + t.assignmentExpression( + "=", + t.memberExpression( + t.identifier("exports"), + t.identifier(exported), + ), + t.cloneNode(expr, true), + ), + ); + } + } + } + } else { + let depth = 0; + let current = path.node.expression; + + while ( + t.isAssignmentExpression(current) && + t.isMemberExpression(current.left) && + t.isIdentifier(current.left.object) && + current.left.object.name === "exports" + ) { + if ( + t.isUnaryExpression(current.right) && + current.right.operator === "void" && + t.isNumericLiteral(current.right.argument) && + current.right.argument.value === 0 + ) { + if (depth > 0) { + path.remove(); + } + + break; + } + + depth++; + current = current.right; + } } }, exit(path, state) { diff --git a/packages/plugin-vite/src/plugins/patches/commonjs_test.ts b/packages/plugin-vite/src/plugins/patches/commonjs_test.ts index 3a984fe8..84b8e080 100644 --- a/packages/plugin-vite/src/plugins/patches/commonjs_test.ts +++ b/packages/plugin-vite/src/plugins/patches/commonjs_test.ts @@ -26,6 +26,8 @@ Object.defineProperty(module, "exports", { const DEFAULT_EXPORT = `const _default = exports.default ?? exports;`; const DEFAULT_EXPORT_END = `export default _default;`; +const IMPORT_REQUIRE = `import { createRequire } from "node:module"; +const require = createRequire(import.meta.url);`; Deno.test("commonjs - module.exports default", () => { runTest({ @@ -239,14 +241,11 @@ Deno.test("commonjs - cleared exports", () => { exports.foo = exports.bar = void 0; exports.foo = 'foo'`, expected: `${INIT} -exports.foo = exports.bar = void 0; exports.foo = 'foo'; var _foo = exports.foo; -var _bar = exports.bar; -export { _foo as foo, _bar as bar }; +export { _foo as foo }; ${DEFAULT_EXPORT} _default.foo = _foo; -_default.bar = _bar; ${DEFAULT_EXPORT_END}`, }); }); @@ -258,12 +257,7 @@ Object.defineProperty(exports, "foo", { enumerable: true, get: function () { ret expected: `${INIT} import * as _mod from "./bar"; var utils_1 = _mod.default ?? _mod; -Object.defineProperty(exports, "foo", { - enumerable: true, - get: function () { - return utils_1.foo; - } -}); +exports.foo = utils_1.foo; var _foo = exports.foo; export { _foo as foo }; ${DEFAULT_EXPORT} @@ -279,12 +273,7 @@ Object.defineProperty(exports, "foo", { enumerable: true, get() { return utils_1 expected: `${INIT} import * as _mod from "./bar"; var utils_1 = _mod.default ?? _mod; -Object.defineProperty(exports, "foo", { - enumerable: true, - get() { - return utils_1.foo; - } -}); +exports.foo = utils_1.foo; var _foo = exports.foo; export { _foo as foo }; ${DEFAULT_EXPORT} @@ -471,3 +460,76 @@ _default.foo = _foo; ${DEFAULT_EXPORT_END}`, }); }); + +Deno.test("commonjs - require non-analyzable arg", () => { + runTest({ + input: `const pkg = require(path.join(basedir, "package.json"))`, + expected: `import { createRequire } from "node:module"; +const require = createRequire(import.meta.url); +const pkg = require(path.join(basedir, "package.json"));`, + }); +}); + +Deno.test("commonjs - require lazy import", () => { + runTest({ + input: `if (typeof process.env.NODE_PG_FORCE_NATIVE !== 'undefined') { + module.exports = new PG(require('./native')) +} else { + module.exports = new PG(Client) + + // lazy require native module...the native module may not have installed + Object.defineProperty(module.exports, 'native', { + configurable: true, + enumerable: false, + get() { + let native = null + try { + native = new PG(require('./native')) + } catch (err) { + if (err.code !== 'MODULE_NOT_FOUND') { + throw err + } + } + + // overwrite module.exports.native so that getter is never called again + Object.defineProperty(module.exports, 'native', { + value: native, + }) + + return native + }, + }) +}`, + expected: `${INIT} +${IMPORT_REQUIRE} +if (typeof process.env.NODE_PG_FORCE_NATIVE !== 'undefined') { + module.exports = new PG(require('./native')); +} else { + module.exports = new PG(Client); + + // lazy require native module...the native module may not have installed + Object.defineProperty(module.exports, 'native', { + configurable: true, + enumerable: false, + get() { + let native = null; + try { + native = new PG(require('./native')); + } catch (err) { + if (err.code !== 'MODULE_NOT_FOUND') { + throw err; + } + } + + // overwrite module.exports.native so that getter is never called again + Object.defineProperty(module.exports, 'native', { + value: native + }); + return native; + } + }); +} +${DEFAULT_EXPORT} +${DEFAULT_EXPORT_END}`, + }); +}); diff --git a/packages/plugin-vite/src/plugins/patches/inline_env_vars.ts b/packages/plugin-vite/src/plugins/patches/inline_env_vars.ts index dbe7175a..820247d1 100644 --- a/packages/plugin-vite/src/plugins/patches/inline_env_vars.ts +++ b/packages/plugin-vite/src/plugins/patches/inline_env_vars.ts @@ -1,14 +1,14 @@ import type { NodePath, PluginObj, types } from "@babel/core"; -export function inlineEnvVarsPlugin(mode: string) { +export function inlineEnvVarsPlugin(mode: string, env: Record) { const allowed = new Map(); - for (const [name, value] of Object.entries(Deno.env.toObject())) { + for (const [name, value] of Object.entries(env)) { if (name.startsWith("FRESH_PUBLIC_")) { allowed.set(name, value); } } - allowed.set("NODE_ENV", Deno.env.get("NODE_ENV") ?? mode); + allowed.set("NODE_ENV", mode); return ( { types: t }: { types: typeof types }, diff --git a/packages/plugin-vite/src/plugins/patches/inline_env_vars_test.ts b/packages/plugin-vite/src/plugins/patches/inline_env_vars_test.ts index 4365308a..424fb250 100644 --- a/packages/plugin-vite/src/plugins/patches/inline_env_vars_test.ts +++ b/packages/plugin-vite/src/plugins/patches/inline_env_vars_test.ts @@ -1,27 +1,27 @@ import { expect } from "@std/expect/expect"; import * as babel from "@babel/core"; import { inlineEnvVarsPlugin } from "./inline_env_vars.ts"; -import { usingEnv } from "../../../tests/test_utils.ts"; -function runTest(options: { input: string; expected: string; mode?: string }) { +function runTest( + options: { + input: string; + expected: string; + mode?: string; + env?: Record; + }, +) { const res = babel.transformSync(options.input, { filename: "foo.js", babelrc: false, - plugins: [inlineEnvVarsPlugin(options.mode ?? "development")], + plugins: [ + inlineEnvVarsPlugin(options.mode ?? "development", options.env ?? {}), + ], }); const output = res?.code ?? ""; expect(output).toEqual(options.expected); } -Deno.test("env vars - inline NODE_ENV", () => { - using _ = usingEnv("NODE_ENV", "foobar"); - runTest({ - input: `() => process.env.NODE_ENV`, - expected: `() => "foobar";`, - }); -}); - Deno.test("env vars - inline NODE_ENV mode", () => { runTest({ input: `() => process.env.NODE_ENV`, @@ -31,49 +31,49 @@ Deno.test("env vars - inline NODE_ENV mode", () => { }); Deno.test("env vars - inline custom process.env.*", () => { - using _ = usingEnv("FRESH_PUBLIC_FOO", "a"); runTest({ input: `() => process.env.FRESH_PUBLIC_FOO`, expected: `() => "a";`, + env: { + FRESH_PUBLIC_FOO: "a", + }, }); }); Deno.test("env vars - inline Deno.env.get()", () => { - using _ = usingEnv("FRESH_PUBLIC_FOO", "b"); runTest({ input: `() => Deno.env.get("FRESH_PUBLIC_FOO")`, expected: `() => "b";`, + env: { + FRESH_PUBLIC_FOO: "b", + }, }); }); Deno.test("env vars - inline Deno.env.get(NODE_ENV)", () => { - using _ = usingEnv("NODE_ENV", "c"); runTest({ input: `() => Deno.env.get("NODE_ENV")`, expected: `() => "c";`, - }); -}); - -Deno.test("env vars - inline Deno.env.get(NODE_ENV) mode", () => { - runTest({ - input: `() => Deno.env.get("NODE_ENV")`, - expected: `() => "test";`, - mode: "test", + mode: "c", }); }); Deno.test("env vars - inline const _ = Deno.env.get()", () => { - using _ = usingEnv("FRESH_PUBLIC_FOO", "test"); runTest({ input: `const deno = Deno.env.get("FRESH_PUBLIC_FOO");`, expected: `const deno = "test";`, + env: { + FRESH_PUBLIC_FOO: "test", + }, }); }); Deno.test("env vars - inline import.meta.env.FRESH_PUBLIC_FOO", () => { - using _ = usingEnv("FRESH_PUBLIC_FOO", "test"); runTest({ input: `() => import.meta.env.FRESH_PUBLIC_FOO;`, expected: `() => "test";`, + env: { + FRESH_PUBLIC_FOO: "test", + }, }); }); diff --git a/packages/plugin-vite/src/plugins/shims.ts b/packages/plugin-vite/src/plugins/shims.ts new file mode 100644 index 00000000..11e64d00 --- /dev/null +++ b/packages/plugin-vite/src/plugins/shims.ts @@ -0,0 +1,34 @@ +import type { Plugin } from "vite"; +import * as path from "@std/path"; + +const SHIMS: Record = { + "object.entries": path.join( + import.meta.dirname!, + "shims", + "object.entries", + "index.ts", + ), + "supports-color": path.join( + import.meta.dirname!, + "shims", + "supports-color", + "index.ts", + ), +}; + +export function shims(): Plugin { + return { + name: "fresh:shims", + resolveId: { + filter: { + id: /(object\.entries|supports-color)/, + }, + handler(id) { + const resolved = SHIMS[id]; + if (resolved !== undefined) { + return resolved; + } + }, + }, + }; +} diff --git a/packages/plugin-vite/src/plugins/shims/object.entries/index.ts b/packages/plugin-vite/src/plugins/shims/object.entries/index.ts new file mode 100644 index 00000000..10ba82df --- /dev/null +++ b/packages/plugin-vite/src/plugins/shims/object.entries/index.ts @@ -0,0 +1,4 @@ +// deno-lint-ignore no-explicit-any +export default function entries(obj: any) { + return Object.entries(obj); +} diff --git a/packages/plugin-vite/src/plugins/shims/supports-color/index.ts b/packages/plugin-vite/src/plugins/shims/supports-color/index.ts new file mode 100644 index 00000000..260b6897 --- /dev/null +++ b/packages/plugin-vite/src/plugins/shims/supports-color/index.ts @@ -0,0 +1,30 @@ +export interface ColorSupport { + level: 1 | 2 | 3; + hasBasic: boolean; + has256: boolean; + has16m: boolean; +} + +function toLevel(depth: number): 1 | 2 | 3 { + if (depth === 1) return 1; + if (depth === 8) return 2; + if (depth === 24) return 3; + return 1; +} + +function toSupport(depth: number): ColorSupport { + const level = toLevel(depth); + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +export default { + // deno-lint-ignore no-process-global + stdout: toSupport(process.stdout.getColorDepth()), + // deno-lint-ignore no-process-global + stderr: toSupport(process.stderr.getColorDepth()), +}; diff --git a/packages/plugin-vite/tests/dev_server_test.ts b/packages/plugin-vite/tests/dev_server_test.ts index 91e8d671..130ac700 100644 --- a/packages/plugin-vite/tests/dev_server_test.ts +++ b/packages/plugin-vite/tests/dev_server_test.ts @@ -6,20 +6,22 @@ import { FIXTURE_DIR, launchDevServer, prepareDevServer, + spawnDevServer, updateFile, withDevServer, } from "./test_utils.ts"; const tmp = await prepareDevServer(DEMO_DIR); +const demoServer = await spawnDevServer(tmp.dir, { + FRESH_PUBLIC_FOO: "foobar", +}); Deno.test({ name: "vite dev - launches", fn: async () => { - await launchDevServer(tmp.dir, async (address) => { - const res = await fetch(`${address}/tests/it_works`); - const text = await res.text(); - expect(text).toContain("it works"); - }); + const res = await fetch(`${demoServer.address()}/tests/it_works`); + const text = await res.text(); + expect(text).toContain("it works"); }, sanitizeResources: false, sanitizeOps: false, @@ -28,11 +30,9 @@ Deno.test({ Deno.test({ name: "vite dev - serves static files", fn: async () => { - await launchDevServer(tmp.dir, async (address) => { - const res = await fetch(`${address}/test_static/foo.txt`); - const text = await res.text(); - expect(text).toContain("it works"); - }); + const res = await fetch(`${demoServer.address()}/test_static/foo.txt`); + const text = await res.text(); + expect(text).toContain("it works"); }, sanitizeResources: false, sanitizeOps: false, @@ -41,16 +41,14 @@ Deno.test({ Deno.test({ name: "vite dev - loads islands", fn: async () => { - await launchDevServer(tmp.dir, async (address) => { - await withBrowser(async (page) => { - await page.goto(`${address}/tests/island_hooks`, { - waitUntil: "networkidle2", - }); - await waitForText(page, "button", "count: 0"); - - await page.locator("button").click(); - await waitForText(page, "button", "count: 1"); + await withBrowser(async (page) => { + await page.goto(`${demoServer.address()}/tests/island_hooks`, { + waitUntil: "networkidle2", }); + await waitForText(page, "button", "count: 0"); + + await page.locator("button").click(); + await waitForText(page, "button", "count: 1"); }); }, sanitizeResources: false, @@ -103,30 +101,28 @@ Deno.test({ name: "vite dev - can apply HMR to islands (hooks)", ignore: true, // Test is very flaky fn: async () => { - await launchDevServer(tmp.dir, async (address, dir) => { - await withBrowser(async (page) => { - await page.goto(`${address}/tests/island_hooks`, { - waitUntil: "networkidle2", - }); - await waitForText(page, "button", "count: 0"); - await page.locator("button").click(); - await waitForText(page, "button", "count: 1"); - - const island = path.join( - dir, - "islands", - "tests", - "CounterHooks.tsx", - ); - await using _ = await updateFile( - island, - (text) => text.replace("count:", "hmr:"), - ); - - await waitForText(page, "button", "hmr: 1"); - await page.locator("button").click(); - await waitForText(page, "button", "hmr: 2"); + await withBrowser(async (page) => { + await page.goto(`${demoServer.address()}/tests/island_hooks`, { + waitUntil: "networkidle2", }); + await waitForText(page, "button", "count: 0"); + await page.locator("button").click(); + await waitForText(page, "button", "count: 1"); + + const island = path.join( + demoServer.dir, + "islands", + "tests", + "CounterHooks.tsx", + ); + await using _ = await updateFile( + island, + (text) => text.replace("count:", "hmr:"), + ); + + await waitForText(page, "button", "hmr: 1"); + await page.locator("button").click(); + await waitForText(page, "button", "hmr: 2"); }); }, sanitizeResources: false, @@ -136,13 +132,11 @@ Deno.test({ Deno.test({ name: "vite dev - can import json in npm package", fn: async () => { - await launchDevServer(tmp.dir, async (address) => { - await withBrowser(async (page) => { - await page.goto(`${address}/tests/mime`, { - waitUntil: "networkidle2", - }); - await page.locator(".ready").wait(); + await withBrowser(async (page) => { + await page.goto(`${demoServer.address()}/tests/mime`, { + waitUntil: "networkidle2", }); + await page.locator(".ready").wait(); }); }, sanitizeResources: false, @@ -152,21 +146,19 @@ Deno.test({ Deno.test({ name: "vite dev - inline env vars", fn: async () => { - await launchDevServer(tmp.dir, async (address) => { - await withBrowser(async (page) => { - await page.goto(`${address}/tests/env`, { - waitUntil: "networkidle2", - }); - await page.locator(".ready").wait(); - - const res = await page.locator("pre").evaluate((el) => - // deno-lint-ignore no-explicit-any - (el as any).textContent ?? "" - ); - - expect(JSON.parse(res)).toEqual({ deno: "foobar", nodeEnv: "foobar" }); + await withBrowser(async (page) => { + await page.goto(`${demoServer.address()}/tests/env`, { + waitUntil: "networkidle2", }); - }, { FRESH_PUBLIC_FOO: "foobar" }); + await page.locator(".ready").wait(); + + const res = await page.locator("pre").evaluate((el) => + // deno-lint-ignore no-explicit-any + (el as any).textContent ?? "" + ); + + expect(JSON.parse(res)).toEqual({ deno: "foobar", nodeEnv: "foobar" }); + }); }, sanitizeResources: false, sanitizeOps: false, @@ -175,19 +167,17 @@ Deno.test({ Deno.test({ name: "vite dev - serves imported assets", fn: async () => { - await launchDevServer(DEMO_DIR, async (address) => { - // Vite has an internal allowlist that is refreshed when - // pathnames are requested. It will discover valid static - // files imported in JS once it encounters them. Therefore - // we must request the URL that ultimately imports the - // asset first for it to work. - let res = await fetch(`${address}/tests/assets`); - await res.body?.cancel(); + // Vite has an internal allowlist that is refreshed when + // pathnames are requested. It will discover valid static + // files imported in JS once it encounters them. Therefore + // we must request the URL that ultimately imports the + // asset first for it to work. + let res = await fetch(`${demoServer.address()}/tests/assets`); + await res.body?.cancel(); - res = await fetch(`${address}/assets/deno-logo.png`); - expect(res.status).toEqual(200); - expect(res.headers.get("Content-Type")).toEqual("image/png"); - }); + res = await fetch(`${demoServer.address()}/assets/deno-logo.png`); + expect(res.status).toEqual(200); + expect(res.headers.get("Content-Type")).toEqual("image/png"); }, sanitizeResources: false, sanitizeOps: false, @@ -232,19 +222,17 @@ Deno.test({ Deno.test({ name: "vite dev - partial island", fn: async () => { - await launchDevServer(tmp.dir, async (address) => { - await withBrowser(async (page) => { - await page.goto(`${address}/tests/partial`, { - waitUntil: "networkidle2", - }); - - await page.locator(".ready").wait(); - await page.locator("a").click(); - await page.locator(".counter-hooks").wait(); - - await page.locator(".counter-hooks button").click(); - await waitForText(page, ".counter-hooks button", "count: 1"); + await withBrowser(async (page) => { + await page.goto(`${demoServer.address()}/tests/partial`, { + waitUntil: "networkidle2", }); + + await page.locator(".ready").wait(); + await page.locator("a").click(); + await page.locator(".counter-hooks").wait(); + + await page.locator(".counter-hooks button").click(); + await waitForText(page, ".counter-hooks button", "count: 1"); }); }, sanitizeResources: false, @@ -254,11 +242,9 @@ Deno.test({ Deno.test({ name: "vite dev - json from jsr dependency", fn: async () => { - await launchDevServer(tmp.dir, async (address) => { - const res = await fetch(`${address}/tests/dep_json`); - const json = await res.json(); - expect(json.name).toEqual("@marvinh-test/import-json"); - }); + const res = await fetch(`${demoServer.address()}/tests/dep_json`); + const json = await res.json(); + expect(json.name).toEqual("@marvinh-test/import-json"); }, sanitizeResources: false, sanitizeOps: false, @@ -267,11 +253,9 @@ Deno.test({ Deno.test({ name: "vite dev - import node:*", fn: async () => { - await launchDevServer(tmp.dir, async (address) => { - const res = await fetch(`${address}/tests/feed`); - await res.body?.cancel(); - expect(res.status).toEqual(200); - }); + const res = await fetch(`${demoServer.address()}/tests/feed`); + await res.body?.cancel(); + expect(res.status).toEqual(200); }, sanitizeResources: false, sanitizeOps: false, @@ -280,18 +264,16 @@ Deno.test({ Deno.test({ name: "vite dev - island css modules", fn: async () => { - await launchDevServer(tmp.dir, async (address) => { - await withBrowser(async (page) => { - await page.goto(`${address}/tests/css_modules`, { - waitUntil: "networkidle2", - }); - - const color = await page - .locator("h1") - // deno-lint-ignore no-explicit-any - .evaluate((el) => window.getComputedStyle(el as any).color); - expect(color).toEqual("rgb(255, 0, 0)"); + await withBrowser(async (page) => { + await page.goto(`${demoServer.address()}/tests/css_modules`, { + waitUntil: "networkidle2", }); + + const color = await page + .locator("h1") + // deno-lint-ignore no-explicit-any + .evaluate((el) => window.getComputedStyle(el as any).color); + expect(color).toEqual("rgb(255, 0, 0)"); }); }, sanitizeResources: false, @@ -341,11 +323,23 @@ Deno.test({ Deno.test({ name: "vite dev - allow routes looking like static paths", fn: async () => { - await launchDevServer(tmp.dir, async (address) => { - const res = await fetch(`${address}/tests/api/@marvinh@infosec.exchange`); - const text = await res.text(); - expect(text).toEqual("ok"); - }); + const res = await fetch( + `${demoServer.address()}/tests/api/@marvinh@infosec.exchange`, + ); + const text = await res.text(); + expect(text).toEqual("ok"); + }, + sanitizeOps: false, + sanitizeResources: false, +}); + +// issue: https://github.com/denoland/fresh/issues/3323 +Deno.test({ + name: "vite dev - npm:pg", + fn: async () => { + const res = await fetch(`${demoServer.address()}/tests/pg`); + const text = await res.text(); + expect(text).toContain("

pg

"); }, sanitizeOps: false, sanitizeResources: false, diff --git a/packages/plugin-vite/tests/test_utils.ts b/packages/plugin-vite/tests/test_utils.ts index ff3602df..461d3883 100644 --- a/packages/plugin-vite/tests/test_utils.ts +++ b/packages/plugin-vite/tests/test_utils.ts @@ -86,6 +86,42 @@ export async function launchDevServer( ); } +export async function spawnDevServer( + dir: string, + env: Record = {}, +) { + const boot = Promise.withResolvers(); + const p = Promise.withResolvers(); + + let serverAddress = ""; + + const server = withChildProcessServer( + { + cwd: dir, + args: ["run", "-A", "--cached-only", "npm:vite", "--port", "0"], + env, + }, + async (address) => { + serverAddress = address; + boot.resolve(); + await p.promise; + }, + ); + + await boot.promise; + + return { + dir, + promise: server, + address: () => { + return serverAddress; + }, + async [Symbol.asyncDispose]() { + await p.resolve(); + }, + }; +} + export async function withDevServer( fixtureDir: string, fn: (address: string, dir: string) => void | Promise,