From 117e1b38836543d333ee230c2b718f17eb28a0c2 Mon Sep 17 00:00:00 2001 From: Ashcon Partovi Date: Tue, 24 Sep 2024 22:46:18 -0700 Subject: [PATCH] `bun run prettier` (#14153) Co-authored-by: Electroid --- .github/actions/setup-bun/action.yml | 1 + .github/workflows/clang-format.yml | 8 +- .github/workflows/prettier-format.yml | 46 ++++ .prettierrc-ci | 31 --- package.json | 15 +- .../src/debugger/adapter.ts | 8 +- packages/bun-vscode/example/hello.ts | 6 +- packages/bun-vscode/scripts/dev.mjs | 11 +- packages/bun-vscode/src/features/debug.ts | 10 +- src/codegen/kit-codegen.ts | 199 +++++++++--------- src/js/internal/debugger.ts | 10 +- src/kit/client/overlay.ts | 29 +-- src/kit/hmr-module.ts | 22 +- src/kit/hmr-runtime-types.d.ts | 6 +- src/kit/hmr-runtime.ts | 43 ++-- src/kit/macros.ts | 6 +- test/bundler/bundler_kit_dev.test.ts | 38 ++-- test/bundler/bundler_loader.test.ts | 4 +- test/bundler/expectBundled.ts | 16 +- test/bundler/transpiler/transpiler.test.js | 2 +- test/cli/install/bun-install.test.ts | 2 +- test/cli/install/bun-lockb.test.ts | 11 +- test/js/bun/http/proxy.test.ts | 4 +- test/js/bun/spawn/bun-ipc-inherit.test.ts | 6 +- test/js/bun/test/jest-extended.test.js | 12 +- test/js/node/http/node-http.test.ts | 2 +- test/js/node/net/node-net.test.ts | 13 +- test/js/node/tls/node-tls-namedpipes.test.ts | 12 +- test/regression/issue/14029.test.ts | 4 +- 29 files changed, 306 insertions(+), 271 deletions(-) create mode 100644 .github/workflows/prettier-format.yml delete mode 100644 .prettierrc-ci diff --git a/.github/actions/setup-bun/action.yml b/.github/actions/setup-bun/action.yml index 25424ce666..0e6e6103c8 100644 --- a/.github/actions/setup-bun/action.yml +++ b/.github/actions/setup-bun/action.yml @@ -47,4 +47,5 @@ runs: mkdir -p ${{ runner.temp }}/.bun/bin mv ${target}/bun* ${{ runner.temp }}/.bun/bin/ chmod +x ${{ runner.temp }}/.bun/bin/* + ln -fs ${{ runner.temp }}/.bun/bin/bun ${{ runner.temp }}/.bun/bin/bunx echo "${{ runner.temp }}/.bun/bin" >> ${GITHUB_PATH} diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 0bbeae1f96..be3b7bf313 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -13,8 +13,12 @@ on: - "package.json" - "scripts/**" - "cmake/**" - - "src/**/*.{c,cpp,h,hpp}" - - "packages/**/*.{c,cpp,h,hpp}" + - "src/**/*.c" + - "src/**/*.cpp" + - "src/**/*.h" + - "packages/**/*.c" + - "packages/**/*.cpp" + - "packages/**/*.h" env: BUN_VERSION: "1.1.27" diff --git a/.github/workflows/prettier-format.yml b/.github/workflows/prettier-format.yml new file mode 100644 index 0000000000..718c6fb5c5 --- /dev/null +++ b/.github/workflows/prettier-format.yml @@ -0,0 +1,46 @@ +name: prettier-format + +permissions: + contents: write + +on: + workflow_call: + workflow_dispatch: + pull_request: + paths: + - ".github/workflows/prettier-format.yml" + - "package.json" + - "scripts/**" + - "**.yml" + - "**.json" + - "**.js" + - "**.jsx" + - "**.ts" + - "**.tsx" + - "**.mjs" + - "**.cjs" + +env: + BUN_VERSION: "1.1.27" + +jobs: + prettier-format: + name: prettier-format + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup Bun + uses: ./.github/actions/setup-bun + with: + bun-version: ${{ env.BUN_VERSION }} + - name: Setup Dependencies + run: | + bun install + - name: Format + run: | + bun run prettier:extra + - name: Commit + uses: stefanzweifel/git-auto-commit-action@v5 + with: + commit_message: "`bun run prettier:extra`" diff --git a/.prettierrc-ci b/.prettierrc-ci deleted file mode 100644 index b9cd5bacb7..0000000000 --- a/.prettierrc-ci +++ /dev/null @@ -1,31 +0,0 @@ -{ - "arrowParens": "avoid", - "printWidth": 120, - "trailingComma": "all", - "useTabs": false, - "quoteProps": "preserve", - "plugins": [ - "prettier-plugin-organize-imports" - ], - "overrides": [ - { - "files": [ - ".vscode/*.json" - ], - "options": { - "parser": "jsonc", - "quoteProps": "preserve", - "singleQuote": false, - "trailingComma": "all" - } - }, - { - "files": [ - "*.md" - ], - "options": { - "printWidth": 80 - } - } - ] -} diff --git a/package.json b/package.json index c7292681e6..12022404c5 100644 --- a/package.json +++ b/package.json @@ -42,16 +42,16 @@ "build:debug-zig-release": "cmake . -DCMAKE_BUILD_TYPE=Release -DZIG_OPTIMIZE=Debug -GNinja -Bbuild-debug-zig-release && ninja -Cbuild-debug-zig-release", "bump": "bun ./scripts/bump.ts", "typecheck": "tsc --noEmit && cd test && bun run typecheck", - "fmt": "prettier --config=.prettierrc-ci --write --cache './{.vscode,src,test,bench,packages/{bun-types,bun-inspector-*,bun-vscode,bun-debug-adapter-protocol}}/**/*.{mjs,ts,tsx,js,jsx}'", + "fmt": "bun run prettier", "fmt:cpp": "bun run clang-format", - "fmt:zig": "bun run zig:fmt", + "fmt:zig": "bun run zig-format", "lint": "eslint './**/*.d.ts' --cache", "lint:fix": "eslint './**/*.d.ts' --cache --fix", - "test": "node scripts/runner.node.mjs ./build/bun-debug", - "test:release": "node scripts/runner.node.mjs ./build-release/bun", + "test": "node scripts/runner.node.mjs --exec-path ./build/debug/bun-debug", + "test:release": "node scripts/runner.node.mjs --exec-path ./build/release/bun", "banned": "bun packages/bun-internal-test/src/linter.ts", "zig": "vendor/zig/zig.exe", - "zig:fmt": "bun run zig fmt src/*.zig src/*/*.zig src/*/*/*.zig src/*/*/*/*.zig", + "zig:fmt": "bun run zig-format", "zig:check": "bun run zig build check --summary new", "zig:check-all": "bun run zig build check-all --summary new", "zig:check-windows": "bun run zig build check-windows --summary new", @@ -59,6 +59,9 @@ "clang-format": "bun run cmake --target clang-format", "clang-format:check": "bun run cmake --target clang-format-check", "zig-format": "bun run cmake --target zig-format", - "zig-format:check": "bun run cmake --target zig-format-check" + "zig-format:check": "bun run cmake --target zig-format-check", + "prettier": "prettier --config=.prettierrc --write --cache './{.vscode,src,test,bench,packages/{bun-types,bun-inspector-*,bun-vscode,bun-debug-adapter-protocol}}/**/*.{mjs,ts,tsx,js,jsx}'", + "prettier:check": "bun run prettier --check", + "prettier:extra": "bun run prettier --plugin=prettier-plugin-organize-imports" } } diff --git a/packages/bun-debug-adapter-protocol/src/debugger/adapter.ts b/packages/bun-debug-adapter-protocol/src/debugger/adapter.ts index ddf5a9ff25..677db5e41c 100644 --- a/packages/bun-debug-adapter-protocol/src/debugger/adapter.ts +++ b/packages/bun-debug-adapter-protocol/src/debugger/adapter.ts @@ -2,13 +2,13 @@ import type { InspectorEventMap } from "../../../bun-inspector-protocol/src/insp import type { JSC } from "../../../bun-inspector-protocol/src/protocol"; import type { DAP } from "../protocol"; // @ts-ignore -import { spawn, ChildProcess } from "node:child_process"; +import { ChildProcess, spawn } from "node:child_process"; import { EventEmitter } from "node:events"; -import { WebSocketInspector, remoteObjectToString } from "../../../bun-inspector-protocol/index"; +import { AddressInfo, createServer } from "node:net"; +import * as path from "node:path"; +import { remoteObjectToString, WebSocketInspector } from "../../../bun-inspector-protocol/index"; import { randomUnixPath, TCPSocketSignal, UnixSignal } from "./signal"; import { Location, SourceMap } from "./sourcemap"; -import { createServer, AddressInfo } from "node:net"; -import * as path from "node:path"; export async function getAvailablePort(): Promise { const server = createServer(); diff --git a/packages/bun-vscode/example/hello.ts b/packages/bun-vscode/example/hello.ts index ccd2773908..ee960a9c69 100644 --- a/packages/bun-vscode/example/hello.ts +++ b/packages/bun-vscode/example/hello.ts @@ -2,8 +2,6 @@ type OS = "Windows"; Bun.serve({ fetch(req: Request) { - return new Response( - `Hello, ${"Windows" as OS}!` - ); - } + return new Response(`Hello, ${"Windows" as OS}!`); + }, }); diff --git a/packages/bun-vscode/scripts/dev.mjs b/packages/bun-vscode/scripts/dev.mjs index 33fe719583..c648256fda 100644 --- a/packages/bun-vscode/scripts/dev.mjs +++ b/packages/bun-vscode/scripts/dev.mjs @@ -1,21 +1,24 @@ import { defineConfig } from "@vscode/test-cli"; -import { dirname, join } from "node:path"; import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; const workspacePath = dirname(import.meta.dirname); const vscodePath = join(workspacePath, ".vscode-test"); const vscodeTestPath = join(vscodePath, "launch.test.js"); -if(!existsSync(vscodeTestPath)) { +if (!existsSync(vscodeTestPath)) { mkdirSync(vscodePath, { recursive: true }); - writeFileSync(vscodeTestPath, `// Generated by ${import.meta.filename} + writeFileSync( + vscodeTestPath, + `// Generated by ${import.meta.filename} // A test that intentionally waits forever and does nothing, // so you can debug and test the VSCode extension in a clean environment. suite("VSCode extension", function () { this.timeout(Number.MAX_SAFE_INTEGER); test("wait forever", (done) => {}); }); -`); +`, + ); } export default defineConfig({ diff --git a/packages/bun-vscode/src/features/debug.ts b/packages/bun-vscode/src/features/debug.ts index c6fc47f0c4..2dd68c8695 100644 --- a/packages/bun-vscode/src/features/debug.ts +++ b/packages/bun-vscode/src/features/debug.ts @@ -1,8 +1,14 @@ import { DebugSession } from "@vscode/debugadapter"; import { tmpdir } from "node:os"; import * as vscode from "vscode"; -import { DAP, TCPSocketSignal } from "../../../bun-debug-adapter-protocol"; -import { DebugAdapter, getAvailablePort, UnixSignal, getRandomId } from "../../../bun-debug-adapter-protocol"; +import { + DAP, + DebugAdapter, + getAvailablePort, + getRandomId, + TCPSocketSignal, + UnixSignal, +} from "../../../bun-debug-adapter-protocol"; export const DEBUG_CONFIGURATION: vscode.DebugConfiguration = { type: "bun", diff --git a/src/codegen/kit-codegen.ts b/src/codegen/kit-codegen.ts index e6ec16d40a..d3bb39f2da 100644 --- a/src/codegen/kit-codegen.ts +++ b/src/codegen/kit-codegen.ts @@ -1,120 +1,122 @@ -import { join, basename } from 'node:path'; -import { writeFileSync, existsSync } from 'node:fs'; -import assert from 'node:assert'; +import assert from "node:assert"; +import { existsSync, writeFileSync } from "node:fs"; +import { basename, join } from "node:path"; // arg parsing const options = {}; for (const arg of process.argv.slice(2)) { - if(!arg.startsWith('--')) { - console.error('Unknown argument ' + arg); + if (!arg.startsWith("--")) { + console.error("Unknown argument " + arg); process.exit(1); } - const split = arg.split('='); - const value = split[1] || 'true'; + const split = arg.split("="); + const value = split[1] || "true"; options[split[0].slice(2)] = value; } let { codegen_root, debug } = options as any; -if (!codegen_root) {console.error('Missing --codegen_root=...'); process.exit(1);} -if (debug === 'false' || debug === '0' || debug == 'OFF') debug = false; +if (!codegen_root) { + console.error("Missing --codegen_root=..."); + process.exit(1); +} +if (debug === "false" || debug === "0" || debug == "OFF") debug = false; -const kit_dir = join(import.meta.dirname, '../kit'); +const kit_dir = join(import.meta.dirname, "../kit"); process.chdir(kit_dir); // to make bun build predictable in development -const results = await Promise.allSettled(['client', 'server'].map(async mode => { - let result = await Bun.build({ - entrypoints: [join(kit_dir, 'hmr-runtime.ts')], - define: { - mode: JSON.stringify(mode), - IS_BUN_DEVELOPMENT: String(!!debug), - }, - minify: { - syntax: true, - } - }); - if(!result.success) throw new AggregateError(result.logs); - assert(result.outputs.length === 1, 'must bundle to a single file'); - // @ts-ignore - let code = await result.outputs[0].text(); +const results = await Promise.allSettled( + ["client", "server"].map(async mode => { + let result = await Bun.build({ + entrypoints: [join(kit_dir, "hmr-runtime.ts")], + define: { + mode: JSON.stringify(mode), + IS_BUN_DEVELOPMENT: String(!!debug), + }, + minify: { + syntax: true, + }, + }); + if (!result.success) throw new AggregateError(result.logs); + assert(result.outputs.length === 1, "must bundle to a single file"); + // @ts-ignore + let code = await result.outputs[0].text(); - // A second pass is used to convert global variables into parameters, while - // allowing for renaming to properly function when minification is enabled. - const in_names = [ - 'input_graph', - 'config', - mode === 'server' && 'server_fetch_function' - ].filter(Boolean); - const combined_source = ` + // A second pass is used to convert global variables into parameters, while + // allowing for renaming to properly function when minification is enabled. + const in_names = ["input_graph", "config", mode === "server" && "server_fetch_function"].filter(Boolean); + const combined_source = ` __marker__; - let ${in_names.join(',')}; - __marker__(${in_names.join(',')}); + let ${in_names.join(",")}; + __marker__(${in_names.join(",")}); ${code}; `; - const generated_entrypoint = join(kit_dir, `.runtime-${mode}.generated.ts`); - - writeFileSync(generated_entrypoint, combined_source); - using _ = {[Symbol.dispose] : () => { - try { - rmSync(generated_entrypoint); - } catch {} - }}; + const generated_entrypoint = join(kit_dir, `.runtime-${mode}.generated.ts`); - result = await Bun.build({ - entrypoints: [generated_entrypoint], - minify: { - syntax: true, - whitespace: !debug, - identifiers: !debug, + writeFileSync(generated_entrypoint, combined_source); + using _ = { + [Symbol.dispose]: () => { + try { + rmSync(generated_entrypoint); + } catch {} + }, + }; + + result = await Bun.build({ + entrypoints: [generated_entrypoint], + minify: { + syntax: true, + whitespace: !debug, + identifiers: !debug, + }, + }); + if (!result.success) throw new AggregateError(result.logs); + assert(result.outputs.length === 1, "must bundle to a single file"); + // @ts-ignore + code = await result.outputs[0].text(); + + let names: string = ""; + code = code + .replace(/(\n?)\s*__marker__.*__marker__\((.+?)\);\s*/s, (_, n, captured) => { + names = captured; + return n; + }) + .replace(`// ${basename(generated_entrypoint)}`, "") + .trim(); + assert(names, "missing name"); + + if (debug) { + code = "\n " + code.replace(/\n/g, "\n ") + "\n"; } - }); - if(!result.success) throw new AggregateError(result.logs); - assert(result.outputs.length === 1, 'must bundle to a single file'); - // @ts-ignore - code = await result.outputs[0].text(); - - let names: string = ''; - code = code - .replace(/(\n?)\s*__marker__.*__marker__\((.+?)\);\s*/s, (_, n, captured) => { - names = captured; - return n; - }) - .replace(`// ${basename(generated_entrypoint)}`, '') - .trim(); - assert(names, 'missing name'); - if (debug) { - code = '\n ' + code.replace(/\n/g, '\n ') + '\n'; - } + if (code[code.length - 1] === ";") code = code.slice(0, -1); - if (code[code.length - 1] === ';') code = code.slice(0, -1); + if (mode === "server") { + const server_fetch_function = names.split(",")[2].trim(); + code = debug ? `${code} return ${server_fetch_function};\n` : `${code};return ${server_fetch_function};`; + } - if (mode === 'server') { - const server_fetch_function = names.split(',')[2].trim(); - code = debug - ? `${code} return ${server_fetch_function};\n` - : `${code};return ${server_fetch_function};` - } + code = debug ? `((${names}) => {${code}})({\n` : `((${names})=>{${code}})({`; - code = debug - ? `((${names}) => {${code}})({\n` - : `((${names})=>{${code}})({`; + if (mode === "server") { + code = `export default await ${code}`; + } - if (mode === 'server') { - code = `export default await ${code}`; - } - - writeFileSync(join(codegen_root, `kit.${mode}.js`), code); -})); + writeFileSync(join(codegen_root, `kit.${mode}.js`), code); + }), +); // print failures in a de-duplicated fashion. -interface Err { kind: 'client' | 'server' | 'both', err: any } +interface Err { + kind: "client" | "server" | "both"; + err: any; +} const failed = [ - { kind: 'client', result: results[0] }, - { kind: 'server', result: results[1] }, + { kind: "client", result: results[0] }, + { kind: "server", result: results[1] }, ] - .filter(x => x.result.status === 'rejected') + .filter(x => x.result.status === "rejected") .map(x => ({ kind: x.kind, err: x.result.reason })) as Err[]; -if(failed.length > 0) { +if (failed.length > 0) { const flattened_errors: Err[] = []; for (const { kind, err } of failed) { if (err instanceof AggregateError) { @@ -122,31 +124,30 @@ if(failed.length > 0) { } flattened_errors.push({ kind, err }); } - for(let i = 0; i < flattened_errors.length; i++) { + for (let i = 0; i < flattened_errors.length; i++) { const x = flattened_errors[i]; if (!x.err?.message) continue; for (const other of flattened_errors.slice(0, i)) { - if(other.err?.message === x.err.message || other.err.stack === x.err.stack) { - other.kind = 'both'; + if (other.err?.message === x.err.message || other.err.stack === x.err.stack) { + other.kind = "both"; flattened_errors.splice(i, 1); i -= 1; continue; } } } - let current = ''; - for(const { kind, err } of flattened_errors) { - if(kind !== current) { - const map = { both: 'runtime', client: 'client runtime', server: 'server runtime' } + let current = ""; + for (const { kind, err } of flattened_errors) { + if (kind !== current) { + const map = { both: "runtime", client: "client runtime", server: "server runtime" }; console.error(`Errors while bundling Kit ${map[kind]}:`); } console.error(err); } process.exit(1); } else { - console.log('-> kit.client.js, kit.server.js'); + console.log("-> kit.client.js, kit.server.js"); - const empty_file = join(codegen_root, 'kit_empty_file'); - if (!existsSync(empty_file)) - writeFileSync(empty_file, 'this is used to fulfill a cmake dependency'); + const empty_file = join(codegen_root, "kit_empty_file"); + if (!existsSync(empty_file)) writeFileSync(empty_file, "this is used to fulfill a cmake dependency"); } diff --git a/src/js/internal/debugger.ts b/src/js/internal/debugger.ts index cf79349cd3..567e2fa384 100644 --- a/src/js/internal/debugger.ts +++ b/src/js/internal/debugger.ts @@ -1,12 +1,4 @@ -import type { - ServerWebSocket, - Socket, - SocketHandler, - TCPSocketConnectOptions, - UnixSocketOptions, - WebSocketHandler, - Server as WebSocketServer, -} from "bun"; +import type { ServerWebSocket, Socket, SocketHandler, WebSocketHandler, Server as WebSocketServer } from "bun"; export default function ( executionContextId: string, diff --git a/src/kit/client/overlay.ts b/src/kit/client/overlay.ts index 9ada1d768d..d90319e583 100644 --- a/src/kit/client/overlay.ts +++ b/src/kit/client/overlay.ts @@ -1,27 +1,30 @@ -import { css } from '../macros' with { type: 'macro' }; +import { css } from "../macros" with { type: "macro" }; // Create a root element to contain all our our DOM nodes. var root!: HTMLElement; var mount; -if (mode === 'client') { +if (mode === "client") { mount = function mount() { - const wrap = document.createElement('bun-hmr'); - wrap.setAttribute('style', 'position:absolute;display:block;top:0;left:0;width:100%;height:100%;background:transparent'); - const shadow = wrap.attachShadow({ mode: 'open' }); - + const wrap = document.createElement("bun-hmr"); + wrap.setAttribute( + "style", + "position:absolute;display:block;top:0;left:0;width:100%;height:100%;background:transparent", + ); + const shadow = wrap.attachShadow({ mode: "open" }); + const sheet = new CSSStyleSheet(); - sheet.replace(css('client/overlay.css', IS_BUN_DEVELOPMENT)); - shadow.adoptedStyleSheets = [ sheet ]; - - root = document.createElement('main'); + sheet.replace(css("client/overlay.css", IS_BUN_DEVELOPMENT)); + shadow.adoptedStyleSheets = [sheet]; + + root = document.createElement("main"); shadow.appendChild(root); document.body.appendChild(wrap); - } + }; } export function showErrorOverlay(e) { mount(); - console.error(e); - root.innerHTML = `

oh no, a client side error happened:

${e?.message ? `${e?.name ?? (e?.constructor?.name) ?? 'Error'}: ${e.message}\n` : JSON.stringify(e)}${e?.message ? e?.stack : ''}
`; + console.error(e); + root.innerHTML = `

oh no, a client side error happened:

${e?.message ? `${e?.name ?? e?.constructor?.name ?? "Error"}: ${e.message}\n` : JSON.stringify(e)}${e?.message ? e?.stack : ""}
`; } diff --git a/src/kit/hmr-module.ts b/src/kit/hmr-module.ts index 440e1998cf..e21e80688c 100644 --- a/src/kit/hmr-module.ts +++ b/src/kit/hmr-module.ts @@ -1,6 +1,6 @@ -import * as runtimeHelpers from '../runtime.bun.js'; +import * as runtimeHelpers from "../runtime.bun.js"; -const registry = new Map() +const registry = new Map(); export type ModuleLoadFunction = (module: HotModule) => void; export type ExportsCallbackFunction = (new_exports: any) => void; @@ -8,7 +8,7 @@ export type ExportsCallbackFunction = (new_exports: any) => void; /** * This object is passed as the CommonJS "module", but has a bunch of * non-standard properties that are used for implementing hot-module - * reloading. It is unacceptable to depend + * reloading. It is unacceptable to depend */ export class HotModule { exports: any = {}; @@ -26,13 +26,11 @@ export class HotModule { importSync(id: Id, onReload: null | ExportsCallbackFunction) { const module = loadModule(id); const { exports, __esModule } = module; - return __esModule - ? exports - : module._ext_exports ??= { ...exports, default: exports }; + return __esModule ? exports : (module._ext_exports ??= { ...exports, default: exports }); } importMeta() { - return this._import_meta ??= initImportMeta(this); + return (this._import_meta ??= initImportMeta(this)); } } @@ -54,12 +52,14 @@ export function loadModule(key: Id): HotModule { registry.set(key, module); const load = input_graph[key]; if (!load) { - throw new Error(`Failed to load bundled module '${key}'. This is not a dynamic import, and therefore is a bug in Bun`); + throw new Error( + `Failed to load bundled module '${key}'. This is not a dynamic import, and therefore is a bug in Bun`, + ); } load(module); return module; } -runtimeHelpers.__name(HotModule.prototype.importSync, ' importSync') -runtimeHelpers.__name(HotModule.prototype.require, ' require') -runtimeHelpers.__name(loadModule, ' loadModule') +runtimeHelpers.__name(HotModule.prototype.importSync, " importSync"); +runtimeHelpers.__name(HotModule.prototype.require, " require"); +runtimeHelpers.__name(loadModule, " loadModule"); diff --git a/src/kit/hmr-runtime-types.d.ts b/src/kit/hmr-runtime-types.d.ts index 1a830ed220..f80f1d3cde 100644 --- a/src/kit/hmr-runtime-types.d.ts +++ b/src/kit/hmr-runtime-types.d.ts @@ -22,13 +22,13 @@ declare const config: Config; * The runtime is bundled for server and client, which influences * how hmr connection should be established, as well if there is * a window to visually display errors with. -*/ -declare const mode: 'client' | 'server'; + */ +declare const mode: "client" | "server"; /* What should be `export default`'d */ declare var server_fetch_function: any; -/* +/* * If you are running a debug build of Bun. These debug builds should provide * helpful information to someone working on the bundler itself. */ diff --git a/src/kit/hmr-runtime.ts b/src/kit/hmr-runtime.ts index fe7ba48d26..2b6b4f8d76 100644 --- a/src/kit/hmr-runtime.ts +++ b/src/kit/hmr-runtime.ts @@ -1,15 +1,17 @@ // This file is the entrypoint to the hot-module-reloading runtime // In the browser, this uses a WebSocket to communicate with the bundler. // On the server, communication is facilitated using a secret global. -import { loadModule } from './hmr-module'; -import { showErrorOverlay } from './client/overlay'; +import { showErrorOverlay } from "./client/overlay"; +import { loadModule } from "./hmr-module"; -if (typeof IS_BUN_DEVELOPMENT !== 'boolean') { throw new Error('DCE is configured incorrectly') } +if (typeof IS_BUN_DEVELOPMENT !== "boolean") { + throw new Error("DCE is configured incorrectly"); +} // Initialize client-side features. -if (mode === 'client') { +if (mode === "client") { const { refresh } = config; - if(refresh) { + if (refresh) { const runtime = loadModule(refresh).exports; runtime.injectIntoGlobalHook(window); } @@ -18,29 +20,28 @@ if (mode === 'client') { // Load the entry point module try { const main = loadModule(config.main); - - // export it on the server side - if (mode === 'server') - server_fetch_function = main.exports.default; - if (mode === 'client') { - const ws = new WebSocket('/_bun/hmr'); - ws.onopen = (ev) => { + // export it on the server side + if (mode === "server") server_fetch_function = main.exports.default; + + if (mode === "client") { + const ws = new WebSocket("/_bun/hmr"); + ws.onopen = ev => { console.log(ev); - } - ws.onmessage = (ev) => { + }; + ws.onmessage = ev => { console.log(ev); - } - ws.onclose = (ev) => { + }; + ws.onclose = ev => { console.log(ev); - } - ws.onerror = (ev) => { + }; + ws.onerror = ev => { console.log(ev); - } + }; } } catch (e) { - if (mode !== 'client') throw e; + if (mode !== "client") throw e; showErrorOverlay(e); } -export {} +export {}; diff --git a/src/kit/macros.ts b/src/kit/macros.ts index dd3f2aa8de..13299608a7 100644 --- a/src/kit/macros.ts +++ b/src/kit/macros.ts @@ -1,8 +1,8 @@ -import { readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; export function css(file: string, is_development: boolean): string { - const contents = readFileSync(resolve(import.meta.dir, file), 'utf-8'); + const contents = readFileSync(resolve(import.meta.dir, file), "utf-8"); if (!is_development) { // TODO: minify return contents; diff --git a/test/bundler/bundler_kit_dev.test.ts b/test/bundler/bundler_kit_dev.test.ts index 753a33c671..7a978eb4c3 100644 --- a/test/bundler/bundler_kit_dev.test.ts +++ b/test/bundler/bundler_kit_dev.test.ts @@ -1,39 +1,39 @@ +import { describe } from "bun:test"; import { itBundled } from "./expectBundled"; -import { describe, expect } from "bun:test"; describe("bundler", async () => { - itBundled('kit_dev/HelloWorld', { + itBundled("kit_dev/HelloWorld", { files: { - '/a.js': `console.log("Hello, world!")`, + "/a.js": `console.log("Hello, world!")`, }, - format: 'internal_kit_dev', - target: 'bun', - run: { stdout: 'Hello, world!' }, + format: "internal_kit_dev", + target: "bun", + run: { stdout: "Hello, world!" }, onAfterBundle(api) { // `importSync` is one of the functions the runtime includes. // it is on a property access so it will not be mangled - api.expectFile('out.js').toContain('importSync'); + api.expectFile("out.js").toContain("importSync"); }, }); - itBundled('kit_dev/SimpleCommonJS', { + itBundled("kit_dev/SimpleCommonJS", { files: { - '/a.js': `console.log(require('./b').message)`, - '/b.js': `module.exports = { message: "Hello, world!" }`, + "/a.js": `console.log(require('./b').message)`, + "/b.js": `module.exports = { message: "Hello, world!" }`, }, - format: 'internal_kit_dev', - target: 'bun', - run: { stdout: 'Hello, world!' }, + format: "internal_kit_dev", + target: "bun", + run: { stdout: "Hello, world!" }, }); - itBundled('kit_dev/SimpleESM', { + itBundled("kit_dev/SimpleESM", { files: { - '/a.js': ` + "/a.js": ` import message from './b'; console.log(message); `, - '/b.js': `export default "Hello, world!"`, + "/b.js": `export default "Hello, world!"`, }, - format: 'internal_kit_dev', - target: 'bun', - run: { stdout: 'Hello, world!' }, + format: "internal_kit_dev", + target: "bun", + run: { stdout: "Hello, world!" }, }); }); diff --git a/test/bundler/bundler_loader.test.ts b/test/bundler/bundler_loader.test.ts index 19bd68893f..c6f1e3ce3c 100644 --- a/test/bundler/bundler_loader.test.ts +++ b/test/bundler/bundler_loader.test.ts @@ -1,8 +1,8 @@ import { fileURLToPath } from "bun"; import { describe } from "bun:test"; -import { itBundled } from "./expectBundled"; -import { join } from "path"; import fs from "node:fs"; +import { join } from "path"; +import { itBundled } from "./expectBundled"; describe("bundler", async () => { for (let target of ["bun", "node"] as const) { diff --git a/test/bundler/expectBundled.ts b/test/bundler/expectBundled.ts index 558e211237..d1177a8102 100644 --- a/test/bundler/expectBundled.ts +++ b/test/bundler/expectBundled.ts @@ -479,7 +479,7 @@ function expectBundled( if (bundling === false && entryPoints.length > 1) { throw new Error("bundling:false only supports a single entry point"); } - if (!ESBUILD && (format === "cjs" || format === 'iife')) { + if (!ESBUILD && (format === "cjs" || format === "iife")) { throw new Error(`format ${format} not implemented in bun build`); } if (!ESBUILD && metafile) { @@ -880,12 +880,14 @@ function expectBundled( // Check for warnings if (!ESBUILD) { const warningText = stderr!.toUnixString(); - const allWarnings = warnParser(warningText).map(([error, source]) => { - if(!source) return; - const [_str2, fullFilename, line, col] = source.match(/bun-build-tests[\/\\](.*):(\d+):(\d+)/)!; - const file = fullFilename.slice(id.length + path.basename(tempDirectory).length + 1).replaceAll("\\", "/"); - return { error, file, line, col }; - }).filter(Boolean); + const allWarnings = warnParser(warningText) + .map(([error, source]) => { + if (!source) return; + const [_str2, fullFilename, line, col] = source.match(/bun-build-tests[\/\\](.*):(\d+):(\d+)/)!; + const file = fullFilename.slice(id.length + path.basename(tempDirectory).length + 1).replaceAll("\\", "/"); + return { error, file, line, col }; + }) + .filter(Boolean); const expectedWarnings = bundleWarnings ? Object.entries(bundleWarnings).flatMap(([file, v]) => v.map(error => ({ file, error }))) : null; diff --git a/test/bundler/transpiler/transpiler.test.js b/test/bundler/transpiler/transpiler.test.js index 8e8fd6afe4..33d91f5794 100644 --- a/test/bundler/transpiler/transpiler.test.js +++ b/test/bundler/transpiler/transpiler.test.js @@ -103,7 +103,7 @@ describe("Bun.Transpiler", () => { it("doesn't hang indefinitely #2746", () => { // this test passes by not hanging expect(() => { - console.log('1'); + console.log("1"); const y = transpiler.transformSync(` class Test { test() { diff --git a/test/cli/install/bun-install.test.ts b/test/cli/install/bun-install.test.ts index ef179f327a..591f03fc5c 100644 --- a/test/cli/install/bun-install.test.ts +++ b/test/cli/install/bun-install.test.ts @@ -1,6 +1,5 @@ import { file, listen, Socket, spawn } from "bun"; import { - jest, afterAll, afterEach, beforeAll, @@ -8,6 +7,7 @@ import { describe, expect, it, + jest, setDefaultTimeout, test, } from "bun:test"; diff --git a/test/cli/install/bun-lockb.test.ts b/test/cli/install/bun-lockb.test.ts index 86ea34672f..b97bc1759a 100644 --- a/test/cli/install/bun-lockb.test.ts +++ b/test/cli/install/bun-lockb.test.ts @@ -1,9 +1,8 @@ -import { file, listen, Socket, spawn } from "bun"; -import { tmpdirSync } from "harness"; -import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, setDefaultTimeout, test } from "bun:test"; -import { access, mkdir, readlink, rm, writeFile, copyFile } from "fs/promises"; -import { bunEnv, bunExe, bunEnv as env, tempDirWithFiles, toBeValidBin, toBeWorkspaceLink, toHaveBins } from "harness"; -import { join, sep } from "path"; +import { spawn } from "bun"; +import { expect, it } from "bun:test"; +import { access, copyFile, writeFile } from "fs/promises"; +import { bunExe, bunEnv as env, tmpdirSync } from "harness"; +import { join } from "path"; it("should not print anything to stderr when running bun.lockb", async () => { const package_dir = tmpdirSync(); diff --git a/test/js/bun/http/proxy.test.ts b/test/js/bun/http/proxy.test.ts index b952e8bc68..1b6953c70e 100644 --- a/test/js/bun/http/proxy.test.ts +++ b/test/js/bun/http/proxy.test.ts @@ -1,11 +1,11 @@ +import axios from "axios"; import type { Server } from "bun"; import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { tls as tlsCert } from "harness"; +import { HttpsProxyAgent } from "https-proxy-agent"; import { once } from "node:events"; import net from "node:net"; import tls from "node:tls"; -import axios from "axios"; -import { HttpsProxyAgent } from "https-proxy-agent"; async function createProxyServer(is_tls: boolean) { const serverArgs = []; if (is_tls) { diff --git a/test/js/bun/spawn/bun-ipc-inherit.test.ts b/test/js/bun/spawn/bun-ipc-inherit.test.ts index 1cbd1247ed..1c62c53de9 100644 --- a/test/js/bun/spawn/bun-ipc-inherit.test.ts +++ b/test/js/bun/spawn/bun-ipc-inherit.test.ts @@ -1,7 +1,7 @@ -import { spawn, spawnSync, env } from "bun"; -import fs from "node:fs/promises"; -import { describe, expect, it } from "bun:test"; +import { spawn } from "bun"; +import { expect, it } from "bun:test"; import { bunExe, isWindows } from "harness"; +import fs from "node:fs/promises"; import path from "path"; it.todoIf(isWindows)("spawning a bun package script should inherit the ipc fd", async () => { diff --git a/test/js/bun/test/jest-extended.test.js b/test/js/bun/test/jest-extended.test.js index 815a645045..7602122aaa 100644 --- a/test/js/bun/test/jest-extended.test.js +++ b/test/js/bun/test/jest-extended.test.js @@ -177,9 +177,17 @@ describe("jest-extended", () => { // Test errors // @ts-expect-error - expect(() => expect(1).toSatisfy(() => { throw new Error("Bun!") })).toThrow("predicate threw an exception"); + expect(() => + expect(1).toSatisfy(() => { + throw new Error("Bun!"); + }), + ).toThrow("predicate threw an exception"); // @ts-expect-error - expect(() => expect(1).not.toSatisfy(() => { throw new Error("Bun!") })).toThrow("predicate threw an exception"); + expect(() => + expect(1).not.toSatisfy(() => { + throw new Error("Bun!"); + }), + ).toThrow("predicate threw an exception"); }); // Array diff --git a/test/js/node/http/node-http.test.ts b/test/js/node/http/node-http.test.ts index c79b392fe0..a3f4e2f767 100644 --- a/test/js/node/http/node-http.test.ts +++ b/test/js/node/http/node-http.test.ts @@ -162,7 +162,7 @@ describe("node:http", () => { const server = http.createServer(() => {}); const random_port = randomPort(); server.listen(random_port); - await once(server, 'listening'); + await once(server, "listening"); const { port } = server.address(); expect(port).toEqual(random_port); server.close(); diff --git a/test/js/node/net/node-net.test.ts b/test/js/node/net/node-net.test.ts index 928f5f994b..9e4aa7ffc2 100644 --- a/test/js/node/net/node-net.test.ts +++ b/test/js/node/net/node-net.test.ts @@ -1,11 +1,10 @@ -import { Socket as _BunSocket, resolve, TCPSocketListener } from "bun"; -import { describe, expect, it } from "bun:test"; -import { bunEnv, bunExe, tmpdirSync, isWindows, expectMaxObjectTypeCount } from "harness"; -import { connect, createServer, createConnection, isIP, isIPv4, isIPv6, Server, Socket, Stream } from "node:net"; -import { join } from "node:path"; -import { once } from "node:events"; -import { randomUUID } from "node:crypto"; +import { Socket as _BunSocket, TCPSocketListener } from "bun"; import { heapStats } from "bun:jsc"; +import { describe, expect, it } from "bun:test"; +import { bunEnv, bunExe, expectMaxObjectTypeCount, isWindows, tmpdirSync } from "harness"; +import { randomUUID } from "node:crypto"; +import { connect, createConnection, createServer, isIP, isIPv4, isIPv6, Server, Socket, Stream } from "node:net"; +import { join } from "node:path"; const socket_domain = tmpdirSync(); diff --git a/test/js/node/tls/node-tls-namedpipes.test.ts b/test/js/node/tls/node-tls-namedpipes.test.ts index 0277e4ed33..586e0f81cb 100644 --- a/test/js/node/tls/node-tls-namedpipes.test.ts +++ b/test/js/node/tls/node-tls-namedpipes.test.ts @@ -1,10 +1,10 @@ -import { expect, it } from "bun:test"; -import { tls, isWindows, expectMaxObjectTypeCount } from "harness"; -import { connect, createServer } from "node:tls"; -import net from "node:net"; -import { once } from "node:events"; -import { randomUUID } from "node:crypto"; import { heapStats } from "bun:jsc"; +import { expect, it } from "bun:test"; +import { expectMaxObjectTypeCount, isWindows, tls } from "harness"; +import { randomUUID } from "node:crypto"; +import { once } from "node:events"; +import net from "node:net"; +import { connect, createServer } from "node:tls"; it.if(isWindows)("should work with named pipes and tls", async () => { async function test(pipe_name: string) { diff --git a/test/regression/issue/14029.test.ts b/test/regression/issue/14029.test.ts index 476b5df918..bf7841ca47 100644 --- a/test/regression/issue/14029.test.ts +++ b/test/regression/issue/14029.test.ts @@ -1,6 +1,6 @@ -import { test, expect } from "bun:test"; +import { expect, test } from "bun:test"; +import { bunEnv, bunExe, tmpdirSync } from "harness"; import { join } from "path"; -import { tmpdirSync, bunExe, bunEnv } from "harness"; test("snapshots will recognize existing entries", async () => { const testDir = tmpdirSync();