mirror of
https://github.com/oven-sh/bun
synced 2026-02-02 15:08:46 +00:00
bun run prettier (#14153)
Co-authored-by: Electroid <Electroid@users.noreply.github.com>
This commit is contained in:
1
.github/actions/setup-bun/action.yml
vendored
1
.github/actions/setup-bun/action.yml
vendored
@@ -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}
|
||||
|
||||
8
.github/workflows/clang-format.yml
vendored
8
.github/workflows/clang-format.yml
vendored
@@ -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"
|
||||
|
||||
46
.github/workflows/prettier-format.yml
vendored
Normal file
46
.github/workflows/prettier-format.yml
vendored
Normal file
@@ -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`"
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
15
package.json
15
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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<number> {
|
||||
const server = createServer();
|
||||
|
||||
@@ -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}!`);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 = `<div class='error'><h1>oh no, a client side error happened:</h1><pre><code>${e?.message ? `${e?.name ?? (e?.constructor?.name) ?? 'Error'}: ${e.message}\n` : JSON.stringify(e)}${e?.message ? e?.stack : ''}</code></pre></div>`;
|
||||
console.error(e);
|
||||
root.innerHTML = `<div class='error'><h1>oh no, a client side error happened:</h1><pre><code>${e?.message ? `${e?.name ?? e?.constructor?.name ?? "Error"}: ${e.message}\n` : JSON.stringify(e)}${e?.message ? e?.stack : ""}</code></pre></div>`;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as runtimeHelpers from '../runtime.bun.js';
|
||||
import * as runtimeHelpers from "../runtime.bun.js";
|
||||
|
||||
const registry = new Map<Id, HotModule>()
|
||||
const registry = new Map<Id, HotModule>();
|
||||
|
||||
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, '<HMR runtime> importSync')
|
||||
runtimeHelpers.__name(HotModule.prototype.require, '<HMR runtime> require')
|
||||
runtimeHelpers.__name(loadModule, '<HMR runtime> loadModule')
|
||||
runtimeHelpers.__name(HotModule.prototype.importSync, "<HMR runtime> importSync");
|
||||
runtimeHelpers.__name(HotModule.prototype.require, "<HMR runtime> require");
|
||||
runtimeHelpers.__name(loadModule, "<HMR runtime> loadModule");
|
||||
|
||||
6
src/kit/hmr-runtime-types.d.ts
vendored
6
src/kit/hmr-runtime-types.d.ts
vendored
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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 {};
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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!" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user