diff --git a/scripts/build/codegen.ts b/scripts/build/codegen.ts index 32810f500d15..7aa6c2238db7 100644 --- a/scripts/build/codegen.ts +++ b/scripts/build/codegen.ts @@ -588,7 +588,6 @@ function emitGeneratedClasses({ n, cfg, sources, o, dirStamp }: Ctx): void { resolve(cfg.codegenDir, "ZigGeneratedClasses+DOMClientIsoSubspaces.h"), resolve(cfg.codegenDir, "ZigGeneratedClasses+DOMIsoSubspaces.h"), resolve(cfg.codegenDir, "ZigGeneratedClasses+lazyStructureImpl.h"), - resolve(cfg.codegenDir, "ZigGeneratedClasses.lut.txt"), // Rust sibling: include!()'d by src/runtime/generated_classes.rs. Must be // a declared output so the cargo edge (which lists this in rustInputs) // re-invokes when generate-classes.ts changes — cargo doesn't track @@ -612,7 +611,6 @@ function emitGeneratedClasses({ n, cfg, sources, o, dirStamp }: Ctx): void { o.rustInputs.push(...outputs); o.cppSources.push(outputs[1]!); // .cpp o.cppHeaders.push(outputs[0]!, outputs[2]!, outputs[3]!, outputs[4]!, outputs[5]!); // .h files - // .lut.txt is consumed by emitObjectLuts below } function emitHostExports({ n, cfg, sources, o, dirStamp }: Ctx): void { @@ -944,8 +942,7 @@ function emitObjectLuts({ n, cfg, o, dirStamp }: Ctx): void { const script = resolve(cfg.cwd, "src", "codegen", "create-hash-table.ts"); const perlScript = resolve(cfg.cwd, "src", "codegen", "create_hash_table"); - // (source, output) pairs. ZigGeneratedClasses.lut.txt is special: it's - // GENERATED by emitGeneratedClasses, so it's in codegenDir not src/. + // (source, output) pairs. const pairs: [src: string, out: string][] = [ [resolve(cfg.cwd, "src/jsc/bindings/BunObject.cpp"), resolve(cfg.codegenDir, "BunObject.lut.h")], [resolve(cfg.cwd, "src/jsc/bindings/ZigGlobalObject.lut.txt"), resolve(cfg.codegenDir, "ZigGlobalObject.lut.h")], @@ -969,7 +966,6 @@ function emitObjectLuts({ n, cfg, o, dirStamp }: Ctx): void { resolve(cfg.codegenDir, "ProcessBindingHTTPParser.lut.h"), ], [resolve(cfg.cwd, "src/jsc/modules/NodeModuleModule.cpp"), resolve(cfg.codegenDir, "NodeModuleModule.lut.h")], - [resolve(cfg.codegenDir, "ZigGeneratedClasses.lut.txt"), resolve(cfg.codegenDir, "ZigGeneratedClasses.lut.h")], [resolve(cfg.cwd, "src/jsc/bindings/webcore/JSEvent.cpp"), resolve(cfg.codegenDir, "JSEvent.lut.h")], ]; diff --git a/scripts/build/config.ts b/scripts/build/config.ts index 9588df924a1f..a2d5cb4c7528 100644 --- a/scripts/build/config.ts +++ b/scripts/build/config.ts @@ -311,14 +311,8 @@ export interface Config { * undefined on native Windows builds (VS dev shell supplies the SDK). */ winsysroot: string | undefined; - /** Android NDK root. undefined when abi != "android". */ - androidNdk: string | undefined; - /** Android API level (the N in `__ANDROID_API__=N`). undefined when abi != "android". */ - androidApiLevel: number | undefined; /** NDK compiler-rt/libunwind dir: `/toolchains/llvm/prebuilt//lib/clang//lib/linux`. */ androidNdkRuntimeDir: string | undefined; - /** FreeBSD release version targeted (e.g. "14.3"). undefined when os != "freebsd". */ - freebsdVersion: string | undefined; // ─── Versioning ─── /** Bun's own version (from package.json). */ @@ -1280,10 +1274,7 @@ export function resolveConfig(partial: PartialConfig, toolchain: Toolchain): Con crossTarget, sysroot, winsysroot, - androidNdk, - androidApiLevel, androidNdkRuntimeDir, - freebsdVersion, version, revision, nodejsVersion, diff --git a/scripts/build/depVersionsHeader.ts b/scripts/build/depVersionsHeader.ts index 810601198df9..bbeed206b600 100644 --- a/scripts/build/depVersionsHeader.ts +++ b/scripts/build/depVersionsHeader.ts @@ -64,8 +64,6 @@ function computeVersions(cfg: Config): [string, string][] { } // ─── Non-dep versions ─── - versions.push(["BUN_VERSION", cfg.version]); - versions.push(["NODEJS_COMPAT_VERSION", cfg.nodejsVersion]); // UWS/USOCKETS are vendored at packages/bun-usockets — the bun commit // IS their version. versions.push(["UWS", cfg.revision]); diff --git a/scripts/build/deps/libjpeg-turbo.ts b/scripts/build/deps/libjpeg-turbo.ts index 4f3efcb1a011..2ad324776026 100644 --- a/scripts/build/deps/libjpeg-turbo.ts +++ b/scripts/build/deps/libjpeg-turbo.ts @@ -70,7 +70,6 @@ const cmakedefine = (truthy: boolean): [string, string] => ["#cmakedefine", trut export const libjpegTurbo: Dependency = { name: "libjpeg-turbo", - versionMacro: "LIBJPEG_TURBO", source: () => ({ kind: "github-archive", diff --git a/scripts/build/deps/libspng.ts b/scripts/build/deps/libspng.ts index df6c6040689c..0f664524baf2 100644 --- a/scripts/build/deps/libspng.ts +++ b/scripts/build/deps/libspng.ts @@ -16,7 +16,6 @@ const LIBSPNG_COMMIT = "fb768002d4288590083a476af628e51c3f1d47cd"; // v0.7.4 export const libspng: Dependency = { name: "libspng", - versionMacro: "LIBSPNG", source: () => ({ kind: "github-archive", diff --git a/scripts/build/deps/libwebp.ts b/scripts/build/deps/libwebp.ts index 8c185c0069f9..762034f19c8f 100644 --- a/scripts/build/deps/libwebp.ts +++ b/scripts/build/deps/libwebp.ts @@ -113,7 +113,6 @@ function simd(path: string, x64: boolean) { export const libwebp: Dependency = { name: "libwebp", - versionMacro: "LIBWEBP", source: () => ({ kind: "github-archive", diff --git a/scripts/build/deps/lsqpack.ts b/scripts/build/deps/lsqpack.ts index c944a4fe8f31..519553351b9c 100644 --- a/scripts/build/deps/lsqpack.ts +++ b/scripts/build/deps/lsqpack.ts @@ -11,7 +11,6 @@ const LSQPACK_COMMIT = "1e9c5b8e59f8161c54f168a570c8bfdc59ded0c3"; export const lsqpack: Dependency = { name: "lsqpack", - versionMacro: "LSQPACK", source: () => ({ kind: "github-archive", diff --git a/scripts/build/deps/lsquic.ts b/scripts/build/deps/lsquic.ts index 177bb94b2917..becb1d0aa9e9 100644 --- a/scripts/build/deps/lsquic.ts +++ b/scripts/build/deps/lsquic.ts @@ -93,7 +93,6 @@ const liblsquic: string[] = [ export const lsquic: Dependency = { name: "lsquic", - versionMacro: "LSQUIC", source: () => ({ kind: "github-archive", diff --git a/scripts/build/flags.ts b/scripts/build/flags.ts index da67305be6ee..4e4fd4cb7678 100644 --- a/scripts/build/flags.ts +++ b/scripts/build/flags.ts @@ -725,7 +725,6 @@ export const defines: Flag[] = [ flag: [ "_HAS_EXCEPTIONS=0", "LIBUS_USE_OPENSSL=1", - "LIBUS_USE_BORINGSSL=1", "STATICALLY_LINKED_WITH_JavaScriptCore=1", "BUILDING_WITH_CMAKE=1", "JSC_OBJC_API_ENABLED=0", diff --git a/scripts/build/unified.ts b/scripts/build/unified.ts index 6ea8a8e00ab7..ec4deb12d4b7 100644 --- a/scripts/build/unified.ts +++ b/scripts/build/unified.ts @@ -91,7 +91,6 @@ const noUnify: readonly string[] = [ "src/jsc/bindings/webcrypto/CryptoAlgorithmAES_KW.cpp", "src/jsc/bindings/webcrypto/CryptoAlgorithmECDSA.cpp", "src/jsc/bindings/webcrypto/CryptoAlgorithmHMAC.cpp", - "src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5.cpp", "src/jsc/bindings/webcrypto/CryptoAlgorithmRSASSA_PKCS1_v1_5.cpp", "src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_OAEP.cpp", "src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_PSS.cpp", diff --git a/scripts/glob-sources.ts b/scripts/glob-sources.ts index 74becfbccb68..804d38c72f51 100644 --- a/scripts/glob-sources.ts +++ b/scripts/glob-sources.ts @@ -102,7 +102,6 @@ const patterns = { "src/jsc/bindings/webcore/streams/*.cpp", "src/jsc/bindings/sqlite/*.cpp", "src/jsc/bindings/webcrypto/*.cpp", - "src/jsc/bindings/webcrypto/*/*.cpp", "src/jsc/bindings/node/*.cpp", "src/jsc/bindings/node/crypto/*.cpp", "src/jsc/bindings/node/http/*.cpp", @@ -121,7 +120,6 @@ const patterns = { paths: [ "packages/bun-usockets/src/*.c", "packages/bun-usockets/src/eventing/*.c", - "packages/bun-usockets/src/internal/*.c", "packages/bun-usockets/src/crypto/*.c", "src/jsc/bindings/uv-posix-polyfills.c", "src/jsc/bindings/uv-posix-stubs.c", diff --git a/scripts/runner.node.mjs b/scripts/runner.node.mjs index 313ee1f6e95c..0a66229ce10c 100755 --- a/scripts/runner.node.mjs +++ b/scripts/runner.node.mjs @@ -2913,38 +2913,6 @@ function uploadArtifactsToBuildKite(glob) { }); } -/** - * @param {string} [glob] - * @param {string} [step] - */ -function listArtifactsFromBuildKite(glob, step) { - const args = [ - "artifact", - "search", - "--no-color", - "--allow-empty-results", - "--include-retried-jobs", - "--format", - "%p\n", - glob || "*", - ]; - if (step) { - args.push("--step", step); - } - const { error, status, signal, stdout, stderr } = spawnSync("buildkite-agent", args, { - stdio: ["ignore", "ignore", "ignore"], - encoding: "utf-8", - timeout: spawnTimeout, - cwd, - }); - if (status === 0) { - return stdout?.split("\n").map(line => line.trim()) || []; - } - const cause = error ?? signal ?? `code ${status}`; - console.warn("Failed to list artifacts from BuildKite:", cause, stderr); - return []; -} - /** * @param {string} name * @param {string} value @@ -2990,14 +2958,6 @@ function stripAnsi(string) { return string.replace(/\u001b\[\d+m/g, ""); } -/** - * @param {string} string - * @returns {string} - */ -function escapeGitHubAction(string) { - return string.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A"); -} - /** * @param {string} string * @returns {string} diff --git a/scripts/utils.mjs b/scripts/utils.mjs index 335c181c8987..713e8ecb6d9e 100755 --- a/scripts/utils.mjs +++ b/scripts/utils.mjs @@ -27,7 +27,6 @@ export const isLinux = process.platform === "linux" || isAndroid; export const isFreeBSD = process.platform === "freebsd"; export const isPosix = isMacOS || isLinux || isFreeBSD; -export const isArm64 = process.arch === "arm64"; export const isX64 = process.arch === "x64"; /** @@ -561,32 +560,6 @@ export function getRepository(cwd) { } } -/** - * @returns {string | undefined} - */ -export function getPullRequestRepository() { - if (isBuildkite) { - const repository = getEnv("BUILDKITE_PULL_REQUEST_REPO", false); - if (repository) { - return parseGitRepository(repository); - } - } -} - -/** - * @param {string} [cwd] - * @returns {string | undefined} - */ -export function getRepositoryOwner(cwd) { - const repository = getRepository(cwd); - if (repository) { - const [owner] = repository.split("/"); - if (owner) { - return owner; - } - } -} - /** * @param {string} [cwd] * @returns {string | undefined} @@ -1072,51 +1045,6 @@ export function which(command, options = {}) { } } -/** - * @typedef {object} GitRef - * @property {string} [repository] - * @property {string} [commit] - */ - -/** - * @param {string} [cwd] - * @param {string | GitRef} [base] - * @param {string | GitRef} [head] - * @returns {Promise} - */ -export async function getChangedFiles(cwd, base, head) { - const repository = getRepository(cwd); - head ||= getCommit(cwd); - base ||= `${head}^1`; - - const url = new URL(`repos/${repository}/compare/${base}...${head}`, getGithubApiUrl()); - const { error, body } = await curl(url, { json: true }); - - if (error) { - console.warn("Failed to list changed files:", error); - return; - } - - const { files } = body; - return files.filter(({ status }) => !/removed|unchanged/i.test(status)).map(({ filename }) => filename); -} - -/** - * @param {string} filename - * @returns {boolean} - */ -export function isDocumentation(filename) { - if (/^(docs|bench|examples|misctools|\.vscode)/.test(filename)) { - return true; - } - - if (!/^(src|test|vendor)/.test(filename) && /\.(md|txt)$/.test(filename)) { - return true; - } - - return false; -} - /** * @returns {string | undefined} */ @@ -1211,91 +1139,6 @@ export function getBootstrapVersion(os) { return 0; } -/** - * @typedef {object} BuildArtifact - * @property {string} [job] - * @property {string} filename - * @property {string} url - */ - -/** - * @returns {Promise} - */ -export async function getBuildArtifacts() { - const buildId = await getBuildkiteBuildNumber(); - if (buildId) { - return getBuildkiteArtifacts(buildId); - } -} - -/** - * @returns {Promise} - */ -export async function getBuildkiteBuildNumber() { - if (isBuildkite) { - const number = parseInt(getEnv("BUILDKITE_BUILD_NUMBER", false)); - if (!isNaN(number)) { - return number; - } - } - - const repository = getRepository(); - const commit = getCommit(); - if (!repository || !commit) { - return; - } - - const url = new URL(`repos/${repository}/commits/${commit}/statuses`, getGithubApiUrl()); - const { status, error, body } = await curl(url, { json: true }); - if (status === 404) { - return; - } - if (error) { - throw error; - } - - for (const { target_url: url } of body) { - const { hostname, pathname } = new URL(url); - if (hostname === "buildkite.com") { - const buildId = parseInt(pathname.split("/").pop()); - if (!isNaN(buildId)) { - return buildId; - } - } - } -} - -/** - * @param {string} buildId - * @returns {Promise} - */ -export async function getBuildkiteArtifacts(buildId) { - const orgId = getEnv("BUILDKITE_ORGANIZATION_SLUG", false) || "bun"; - const pipelineId = getEnv("BUILDKITE_PIPELINE_SLUG", false) || "bun"; - const { jobs } = await curlSafe(`https://buildkite.com/${orgId}/${pipelineId}/builds/${buildId}.json`, { - json: true, - }); - - const artifacts = await Promise.all( - jobs.map(async ({ id: jobId, step_key: jobKey }) => { - const artifacts = await curlSafe( - `https://buildkite.com/organizations/${orgId}/pipelines/${pipelineId}/builds/${buildId}/jobs/${jobId}/artifacts`, - { json: true }, - ); - - return artifacts.map(({ path, url }) => { - return { - job: jobKey, - filename: path, - url: new URL(url, "https://buildkite.com/").toString(), - }; - }); - }), - ); - - return artifacts.flat(); -} - /** * @param {string} [filename] * @param {number} [line] @@ -1394,25 +1237,6 @@ export function stripAnsi(string) { return string.replace(/\u001b\[[0-9;]*[a-zA-Z]/g, ""); } -/** - * @param {string} string - * @returns {string} - */ -export function escapeYaml(string) { - if (/[:"{}[\],&*#?|\-<>=!%@`]/.test(string)) { - return `"${string.replace(/"/g, '\\"')}"`; - } - return string; -} - -/** - * @param {string} string - * @returns {string} - */ -export function escapeGitHubAction(string) { - return string.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A"); -} - /** * @param {string} string * @returns {string} @@ -1528,17 +1352,6 @@ export function parseBoolean(value) { } } -/** - * @param {string} value - * @returns {number | undefined} - */ -export function parseNumber(value) { - const number = Number(value); - if (!isNaN(number)) { - return number; - } -} - /** * @param {string} string * @returns {"darwin" | "linux" | "windows" | "freebsd"} @@ -1668,174 +1481,6 @@ export function getAbiVersion() { } } -/** - * @typedef {object} Target - * @property {"darwin" | "linux" | "windows"} os - * @property {"x64" | "aarch64"} arch - * @property {"musl"} [abi] - * @property {boolean} [baseline] - * @property {boolean} profile - * @property {string} label - */ - -/** - * @param {string} string - * @returns {Target} - */ -export function parseTarget(string) { - const os = parseOs(string); - const arch = parseArch(string); - const abi = os === "linux" && string.includes("-musl") ? "musl" : undefined; - const baseline = arch === "x64" ? string.includes("-baseline") : undefined; - const profile = string.includes("-profile"); - - let label = `${os}-${arch}`; - if (abi) { - label += `-${abi}`; - } - if (baseline) { - label += "-baseline"; - } - if (profile) { - label += "-profile"; - } - - return { label, os, arch, abi, baseline, profile }; -} - -/** - * @param {string} target - * @param {string} [release] - * @returns {Promise} - */ -export async function getTargetDownloadUrl(target, release) { - const { label, os, arch, abi, baseline } = parseTarget(target); - const baseUrl = "https://pub-5e11e972747a44bf9aaf9394f185a982.r2.dev/releases/"; - const filename = `bun-${label}.zip`; - - const exists = async url => { - const { status } = await curl(url, { method: "HEAD" }); - return status !== 404; - }; - - if (!release || /^(stable|latest|canary)$/i.test(release)) { - const tag = release === "canary" ? "canary" : "latest"; - const url = new URL(`${tag}/${filename}`, baseUrl); - if (await exists(url)) { - return url; - } - } - - if (/^(bun-v|v)?(\d+\.\d+\.\d+)$/i.test(release)) { - const [, major, minor, patch] = /(\d+)\.(\d+)\.(\d+)/i.exec(release); - const url = new URL(`bun-v${major}.${minor}.${patch}/${filename}`, baseUrl); - if (await exists(url)) { - return url; - } - } - - if (/^https?:\/\//i.test(release) && (await exists(release))) { - return new URL(release); - } - - if (release.length === 40 && /^[0-9a-f]{40}$/i.test(release)) { - const releaseUrl = new URL(`${release}/${filename}`, baseUrl); - if (await exists(releaseUrl)) { - return releaseUrl; - } - - const canaryUrl = new URL(`${release}-canary/${filename}`, baseUrl); - if (await exists(canaryUrl)) { - return canaryUrl; - } - - const statusUrl = new URL(`repos/oven-sh/bun/commits/${release}/status`, getGithubApiUrl()); - const { error, body } = await curl(statusUrl, { json: true }); - if (error) { - throw new Error(`Failed to fetch commit status: ${release}`, { cause: error }); - } - - const { statuses } = body; - const buildUrls = new Set(); - for (const { target_url: url } of statuses) { - const { hostname, origin, pathname } = new URL(url); - if (hostname === "buildkite.com") { - buildUrls.add(`${origin}${pathname}.json`); - } - } - - const buildkiteUrl = new URL("https://buildkite.com/"); - for (const url of buildUrls) { - const { status, error, body } = await curl(url, { json: true }); - if (status === 404) { - continue; - } - if (error) { - throw new Error(`Failed to fetch build: ${url}`, { cause: error }); - } - - const { jobs } = body; - const job = jobs.find( - ({ step_key: key }) => - key && - key.includes("build-bun") && - key.includes(os) && - key.includes(arch) && - (!baseline || key.includes("baseline")) && - (!abi || key.includes(abi)), - ); - if (!job) { - continue; - } - - const { base_path: jobPath } = job; - const artifactsUrl = new URL(`${jobPath}/artifacts`, buildkiteUrl); - { - const { error, body } = await curl(artifactsUrl, { json: true }); - if (error) { - continue; - } - - for (const { url, file_name: name } of body) { - if (name === filename) { - return new URL(url, artifactsUrl); - } - } - } - } - } - - throw new Error(`Failed to find release: ${release}`); -} - -/** - * @param {string} target - * @param {string} [release] - * @returns {Promise} - */ -export async function downloadTarget(target, release) { - const url = await getTargetDownloadUrl(target, release); - const { error, body } = await curl(url, { arrayBuffer: true }); - if (error) { - throw new Error(`Failed to download target: ${target} at ${release}`, { cause: error }); - } - - const tmpPath = mkdtempSync(join(tmpdir(), "bun-download-")); - const zipPath = join(tmpPath, "bun.zip"); - - writeFileSync(zipPath, new Uint8Array(body)); - const unzipPath = await unzip(zipPath, tmpPath); - - for (const entry of readdirSync(unzipPath, { recursive: true, encoding: "utf-8" })) { - const exePath = join(unzipPath, entry); - if (/bun(?:\.exe)?$/i.test(entry)) { - return exePath; - } - } - - throw new Error(`Failed to find bun executable: ${unzipPath}`); -} - /** * @returns {string} */ @@ -1932,30 +1577,6 @@ export function getUsernameForDistro(distro) { throw new Error(`Unsupported distro: ${distro}`); } -/** - * @typedef {object} User - * @property {string} username - * @property {number} uid - * @property {number} gid - */ - -/** - * @param {string} username - * @returns {Promise} - */ -export async function getUser(username) { - if (isWindows) { - throw new Error("TODO: Windows"); - } - - const [uid, gid] = await Promise.all([ - spawnSafe(["id", "-u", username]).then(({ stdout }) => parseInt(stdout.trim())), - spawnSafe(["id", "-g", username]).then(({ stdout }) => parseInt(stdout.trim())), - ]); - - return { username, uid, gid }; -} - /** * @returns {string | undefined} */ diff --git a/src/cares_sys/c_ares.rs b/src/cares_sys/c_ares.rs index c0292e7433fa..58390891bd72 100644 --- a/src/cares_sys/c_ares.rs +++ b/src/cares_sys/c_ares.rs @@ -628,15 +628,6 @@ pub trait AddrInfoHandler: Sized { impl AddrInfo { // toJSArray alias deleted — lives in bun_runtime::dns_jsc. - #[inline] - pub fn name(&self) -> &[u8] { - if self.name_.is_null() { - return b""; - } - // SAFETY: name_ is a NUL-terminated string allocated by c-ares. - unsafe { core::ffi::CStr::from_ptr(self.name_) }.to_bytes() - } - // Consumers walk `cnames_` / `node` pointer chains directly. pub(crate) unsafe extern "C" fn callback_wrapper( diff --git a/src/codegen/bundle-functions.ts b/src/codegen/bundle-functions.ts index 8271698ae037..b98c60532043 100644 --- a/src/codegen/bundle-functions.ts +++ b/src/codegen/bundle-functions.ts @@ -79,11 +79,7 @@ interface ParsedBuiltin { interface BundledBuiltin { name: string; directives: Record; - isGetter: boolean; constructAbility: string; - constructKind: string; - isLinkTimeConstant: boolean; - intrinsic: string; overriddenName: string; source: string; params: string[]; @@ -193,9 +189,6 @@ async function processFileSplit(filename: string): Promise<{ functions: BundledB } if (name === "constructor") { directives.ConstructAbility = "CanConstruct"; - } else if (name === "nakedConstructor") { - directives.ConstructAbility = "CanConstruct"; - directives.ConstructKind = "Naked"; } else { directives[name] = value; } @@ -328,15 +321,13 @@ $$capture_start$$(${fn.async ? "async " : ""}${ let usesAssert = output.includes("$assert"); const captured = output.match(/\$\$capture_start\$\$([\s\S]+)\.\$\$capture_end\$\$/)![1]; const finalReplacement = - (fn.directives.sloppy - ? captured - : captured.replace( - /function\s*\(.*?\)\s*{/, - '$&"use strict";' + - (usesDebug ? createLogClientJS("BUILTINS", fn.name) : "") + - (usesAssert ? createAssertClientJS(fn.name) : ""), - ) - ) + captured + .replace( + /function\s*\(.*?\)\s*{/, + '$&"use strict";' + + (usesDebug ? createLogClientJS("BUILTINS", fn.name) : "") + + (usesAssert ? createAssertClientJS(fn.name) : ""), + ) .replace(/^\((async )?function\(/, "($1function (") .replace(/__intrinsic__/g, "@") .replace(/__no_intrinsic__/g, "") + "\n"; @@ -354,11 +345,7 @@ $$capture_start$$(${fn.async ? "async " : ""}${ // Async functions automatically get Private visibility because the parser // upgrades them when they use await (see Parser.cpp parseFunctionBody) visibility: fn.directives.visibility ?? (fn.directives.linkTimeConstant || fn.async ? "Private" : "Public"), - isGetter: !!fn.directives.getter, constructAbility: fn.directives.ConstructAbility ?? "CannotConstruct", - constructKind: fn.directives.ConstructKind ?? "None", - isLinkTimeConstant: !!fn.directives.linkTimeConstant, - intrinsic: fn.directives.intrinsic ?? "NoIntrinsic", // Not known yet. sourceOffset: 0, @@ -622,7 +609,7 @@ JSBuiltinInternalFunctions::JSBuiltinInternalFunctions(JSC::VM& vm) : m_vm(vm) #define WEBCORE_BUILTIN_${basename.toUpperCase()}_${fn.name.toUpperCase()} 1 static constexpr JSC::ConstructAbility s_${name}ConstructAbility = JSC::ConstructAbility::${fn.constructAbility}; static constexpr JSC::InlineAttribute s_${name}InlineAttribute = JSC::InlineAttribute::${fn.directives.alwaysInline ? "Always" : "None"}; - static constexpr JSC::ConstructorKind s_${name}ConstructorKind = JSC::ConstructorKind::${fn.constructKind}; + static constexpr JSC::ConstructorKind s_${name}ConstructorKind = JSC::ConstructorKind::None; static constexpr JSC::ImplementationVisibility s_${name}ImplementationVisibility = JSC::ImplementationVisibility::${fn.visibility}; `; diff --git a/src/codegen/bundle-modules.ts b/src/codegen/bundle-modules.ts index 92d7d60d11eb..324dd673fdaf 100644 --- a/src/codegen/bundle-modules.ts +++ b/src/codegen/bundle-modules.ts @@ -42,7 +42,7 @@ const JS_DIR = path.join(CMAKE_BUILD_ROOT, "js"); const t = new Bun.Transpiler({ loader: "tsx" }); let start = performance.now(); -const silent = process.env.BUN_SILENT === "1" || process.env.CLAUDECODE; +const silent = process.env.CLAUDECODE; function markVerbose(log: string) { const now = performance.now(); console.log(`${log} (${(now - start).toFixed(0)}ms)`); diff --git a/src/codegen/class-definitions.ts b/src/codegen/class-definitions.ts index 7d4d45885d5b..ea29ef30242f 100644 --- a/src/codegen/class-definitions.ts +++ b/src/codegen/class-definitions.ts @@ -39,11 +39,6 @@ export type Field = } & PropertyAttribute) | { value: string } | ({ setter: string; this?: boolean } & PropertyAttribute) - | ({ - accessor: { getter: string; setter: string }; - cache?: true | string; - this?: boolean; - } & PropertyAttribute) | ({ fn: string; @@ -201,10 +196,6 @@ export class ClassDefinition { * properties and methods on the prototype. */ proto: Record; - /** - * Properties and methods attached to the instance itself. - */ - own: Record; values?: string[]; /** * When true, the class will accept a MarkedArgumentBuffer* to create a @@ -243,40 +234,19 @@ export class ClassDefinition { memoryCost?: boolean; hasPendingActivity?: boolean; isEventEmitter?: boolean; - supportsObjectCreate?: boolean; - - custom?: Record; configurable?: boolean; enumerable?: boolean; structuredClone?: { transferable: boolean; tag: number; storable: boolean }; inspectCustom?: boolean; - callbacks?: Record; - constructor(options: Partial) { this.name = options.name ?? ""; this.klass = options.klass ?? {}; this.proto = options.proto ?? {}; - this.own = options.own ?? {}; Object.assign(this, options); } - - hasOwnProperties() { - for (const key in this.own) { - return true; - } - - return false; - } -} - -export interface CustomField { - header?: string; - extraHeaderIncludes?: string[]; - impl?: string; - type?: string; } /** @@ -287,7 +257,6 @@ export function define( { klass = {}, proto = {}, - own = {}, values = [], overridesToJS = false, estimatedSize = false, @@ -314,7 +283,6 @@ export function define( estimatedSize, structuredClone, values, - own: own || {}, klass: Object.fromEntries( Object.entries(klass) .sort(([a], [b]) => a.localeCompare(b)) diff --git a/src/codegen/cppbind.ts b/src/codegen/cppbind.ts index dedf0324512b..23000c669fe6 100644 --- a/src/codegen/cppbind.ts +++ b/src/codegen/cppbind.ts @@ -901,9 +901,6 @@ async function renderError(position: Srcloc, message: string, label: string, col console.error(`\x1b[m${" ".repeat(Bun.stringWidth(before))}${color}^${"~".repeat(Math.max(length - 1, 0))}\x1b[m`); } -type Cfg = { - dstDir: string; -}; async function readFileOrEmpty(file: string): Promise { try { const fileContents = await Bun.file(file).text(); diff --git a/src/codegen/generate-classes.ts b/src/codegen/generate-classes.ts index 2bdc56702971..d5af9a2e4696 100644 --- a/src/codegen/generate-classes.ts +++ b/src/codegen/generate-classes.ts @@ -5,10 +5,6 @@ import jsclasses from "./../jsc/bindings/js_classes"; import { InvalidThisBehavior, type ClassDefinition, type Field } from "./class-definitions"; import { writeIfNotChanged } from "./helpers"; -if (process.env.BUN_SILENT === "1") { - console.log = () => {}; -} - const files = process.argv.slice(2); const outBase = files.pop(); let externs = ""; @@ -143,7 +139,7 @@ JSC_DEFINE_JIT_OPERATION(${DOMJITName( } function zigExportName(to: Map, symbolName: (name: string) => string, prop) { - var { defaultValue, getter, setter, accessor, fn, DOMJIT, cache } = prop; + var { getter, setter, fn, DOMJIT, cache } = prop; const exportNames = { getter: "", setter: "", @@ -151,11 +147,6 @@ function zigExportName(to: Map, symbolName: (name: string) => st DOMJIT: "", }; - if (accessor) { - getter = accessor.getter; - setter = accessor.setter; - } - if (getter && !to.get(getter)) { to.set(getter, (exportNames.getter = symbolName(getter))); } @@ -180,16 +171,12 @@ function propRow( prop: Field, isWrapped = true, defaultPropertyAttributes, - supportsObjectCreate = false, disableDom, ) { var { - defaultValue, getter, setter, fn, - accessor, - fn, length = 0, cache, DOMJIT, @@ -209,11 +196,6 @@ function propRow( extraPropertyAttributes += " | PropertyAttribute::DontDelete"; } - if (accessor) { - getter = accessor.getter; - setter = accessor.setter; - } - var symbol = symbolName(typeName, name); if (isWrapped) { @@ -262,16 +244,11 @@ function propRow( { "${name}"_s, static_cast(JSC::PropertyAttribute::CustomAccessor${disableDom ? "" : "| JSC::PropertyAttribute::DOMAttribute"}${extraPropertyAttributes}), NoIntrinsic, { HashTableValue::GetterSetterType, ${getter}, ${setter} } } `.trim(); - } else if (defaultValue) { - } else if (getter && !supportsObjectCreate && !writable) { + } else if (getter && !writable) { return `{ "${name}"_s, static_cast(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor${disableDom ? "" : "| JSC::PropertyAttribute::DOMAttribute"}${extraPropertyAttributes}), NoIntrinsic, { HashTableValue::GetterSetterType, ${getter}, 0 } } `.trim(); - } else if (getter && !supportsObjectCreate && writable) { + } else if (getter && writable) { return `{ "${name}"_s, static_cast(JSC::PropertyAttribute::CustomAccessor${disableDom ? "" : "| JSC::PropertyAttribute::DOMAttribute"}${extraPropertyAttributes}), NoIntrinsic, { HashTableValue::GetterSetterType, ${getter}, ${setter} } } -`.trim(); - } else if (getter && supportsObjectCreate) { - setter = getter.replace("Get", "Set"); - return `{ "${name}"_s, static_cast(JSC::PropertyAttribute::CustomAccessor ${extraPropertyAttributes}), NoIntrinsic, { HashTableValue::GetterSetterType, &${getter}, &${setter} } } `.trim(); } else if (setter) { return `{ "${name}"_s, static_cast(JSC::PropertyAttribute::CustomAccessor${disableDom ? "" : "| JSC::PropertyAttribute::DOMAttribute"}${extraPropertyAttributes}), NoIntrinsic, { HashTableValue::GetterSetterType, 0, ${setter} } } @@ -299,18 +276,7 @@ export function generateHashTable(nameToUse, symbolName, typeName, obj, props = if ("privateSymbol" in props[name] || "internal" in props[name] || "value" in props[name]) continue; if (name.startsWith("@@")) continue; - rows.push( - propRow( - symbolName, - typeName, - name, - props[name], - wrapped, - defaultPropertyAttributes, - obj.supportsObjectCreate || false, - !!obj.forBind, - ), - ); + rows.push(propRow(symbolName, typeName, name, props[name], wrapped, defaultPropertyAttributes, !!obj.forBind)); } if (rows.length === 0) { @@ -321,45 +287,6 @@ export function generateHashTable(nameToUse, symbolName, typeName, obj, props = `; } -export function generateHashTableComment(nameToUse, symbolName, obj, props = {}, wrapped) { - const rows = []; - let defaultPropertyAttributes = undefined; - - if ("enumerable" in obj) { - defaultPropertyAttributes ||= {}; - defaultPropertyAttributes.enumerable = obj.enumerable; - } - - if ("configurable" in obj) { - defaultPropertyAttributes ||= {}; - defaultPropertyAttributes.configurable = obj.configurable; - } - - for (const name in props) { - if (name.startsWith("@@")) continue; - externs += ` -extern JSC_CALLCONV JSC::EncodedJSValue JSC_HOST_CALL_ATTRIBUTES ${protoSymbolName( - obj.name, - props[name], - )}(void* ptr, JSC::JSGlobalObject*); -namespace WebCore { -static JSC::JSValue construct${symbolName(name)}PropertyCallback(JSC::VM &vm, JSC::JSObject* initialThisObject); -} - `; - rows.push(`${name} WebCore::construct${symbolName(name)}PropertyCallback PropertyCallback`); - } - - if (rows.length === 0) { - return ""; - } - - return ` -@begin ${nameToUse}Table -${rows.join("\n")} -@end -`; -} - function generatePrototype(typeName, obj) { const proto = prototypeName(typeName); const { proto: protoFields } = obj; @@ -459,7 +386,7 @@ JSC_DECLARE_CUSTOM_GETTER(js${typeName}Constructor); } return ` -${renderDecls(protoSymbolName, typeName, protoFields, obj.supportsObjectCreate || false)} +${renderDecls(protoSymbolName, typeName, protoFields)} STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(${proto}, ${proto}::Base); ${generateHashTable( @@ -587,7 +514,7 @@ function generateConstructorImpl(typeName, obj: ClassDefinition) { return ( ` -${renderStaticDecls(classSymbolName, typeName, fields, obj.supportsObjectCreate || false)} +${renderStaticDecls(classSymbolName, typeName, fields)} ${hashTable} void ${name}::finishCreation(VM& vm, JSC::JSGlobalObject* globalObject, ${prototypeName(typeName)}* prototype) @@ -756,78 +683,15 @@ function renderCachedFieldsHeader(typeName, klass, proto, values) { return rows.join("\n"); } -function renderCallbacksHeader(typeName, callbacks: Record) { - const rows: string[] = []; - for (const name in callbacks) { - rows.push(`mutable WriteBarrier m_callback_${name};`); - } - - return rows.join("\n"); -} - -function renderCallbacksCppImpl(typeName, callbacks: Record) { - const rows: string[] = []; - if (Object.keys(callbacks).length === 0) return ""; - for (const name in callbacks) { - rows.push( - ` - extern JSC_CALLCONV JSC::EncodedJSValue ${symbolName(typeName, "_callback_get_" + name)}(JSC::EncodedJSValue encodedThisValue) { - auto* thisObject = uncheckedDowncast<${className(typeName)}>(JSValue::decode(encodedThisValue)); - return JSValue::encode(thisObject->m_callback_${name}.get()); - } - - extern JSC_CALLCONV void ${symbolName(typeName, "_callback_set_" + name)}(JSC::EncodedJSValue encodedThisValue, JSC::EncodedJSValue encodedCallback) { - auto* thisObject = uncheckedDowncast<${className(typeName)}>(JSValue::decode(encodedThisValue)); - JSValue callback = JSValue::decode(encodedCallback); -#if ASSERT_ENABLED - if (!callback.isEmpty()) { - ASSERT(callback.isObject()); - ASSERT(callback.isCallable()); - } -#endif - if (callback.isEmpty()) { - thisObject->m_callback_${name}.clear(); - } else { - thisObject->m_callback_${name}.set(thisObject->vm(), thisObject, callback.getObject()); - } - } - `, - ); - } - - rows.push(` - extern JSC_CALLCONV void ${symbolName(typeName, "_setAllCallbacks")}(JSC::EncodedJSValue encodedThisValue, ${Object.keys( - callbacks, - ) - .map((_, i) => `JSC::EncodedJSValue encodedCallback${i}`) - .join(", ")}) { - auto* thisObject = uncheckedDowncast<${className(typeName)}>(JSValue::decode(encodedThisValue)); - ${Object.keys(callbacks) - .map( - (name, i) => ` - JSValue callback${i} = JSValue::decode(encodedCallback${i}); - if (!callback${i}.isEmpty()) { - thisObject->m_callback_${name}.set(thisObject->vm(), thisObject, callback${i}.getObject()); - } - `, - ) - .join("\n")} - } - -`); - - return rows.map(a => a.trim()).join("\n"); -} - -function renderDecls(symbolName, typeName, proto, supportsObjectCreate = false) { +function renderDecls(symbolName, typeName, proto) { const rows = []; for (const name in proto) { - if ("getter" in proto[name] || ("accessor" in proto[name] && proto[name].getter)) { + if ("getter" in proto[name]) { externs += `extern JSC_CALLCONV JSC::EncodedJSValue JSC_HOST_CALL_ATTRIBUTES ${symbolName( typeName, - proto[name].getter || proto[name].accessor.getter, + proto[name].getter, )}(void* ptr,${ !!proto[name].this ? " JSC::EncodedJSValue thisValue, " : "" } JSC::JSGlobalObject* lexicalGlobalObject);` + "\n"; @@ -839,15 +703,11 @@ function renderDecls(symbolName, typeName, proto, supportsObjectCreate = false) `.trim(), "\n", ); - - if (supportsObjectCreate && !("setter" in proto[name])) { - rows.push("\n" + `static JSC_DECLARE_CUSTOM_SETTER(${symbolName(typeName, name)}SetterWrap);` + "\n"); - } } - if ("setter" in proto[name] || ("accessor" in proto[name] && proto[name].setter)) { + if ("setter" in proto[name]) { externs += - `extern JSC_CALLCONV bool JSC_HOST_CALL_ATTRIBUTES ${symbolName(typeName, proto[name].setter || proto[name].accessor.setter)}(void* ptr,${ + `extern JSC_CALLCONV bool JSC_HOST_CALL_ATTRIBUTES ${symbolName(typeName, proto[name].setter)}(void* ptr,${ !!proto[name].this ? " JSC::EncodedJSValue thisValue, " : "" } JSC::JSGlobalObject* lexicalGlobalObject, JSC::EncodedJSValue value);` + "\n"; rows.push( @@ -895,24 +755,16 @@ function renderDecls(symbolName, typeName, proto, supportsObjectCreate = false) return rows.map(a => a.trim()).join("\n"); } -function renderStaticDecls(symbolName, typeName, fields, supportsObjectCreate = false) { +function renderStaticDecls(symbolName, typeName, fields) { const rows = []; for (const name in fields) { - if ("getter" in fields[name] || ("accessor" in fields[name] && fields[name].getter)) { - externs += - `extern JSC_CALLCONV JSC_DECLARE_CUSTOM_GETTER(${symbolName( - typeName, - fields[name].getter || fields[name].accessor.getter, - )});` + "\n"; + if ("getter" in fields[name]) { + externs += `extern JSC_CALLCONV JSC_DECLARE_CUSTOM_GETTER(${symbolName(typeName, fields[name].getter)});` + "\n"; } - if ("setter" in fields[name] || ("accessor" in fields[name] && fields[name].setter)) { - externs += - `extern JSC_CALLCONV JSC_DECLARE_CUSTOM_SETTER(${symbolName( - typeName, - fields[name].setter || fields[name].accessor.setter, - )});` + "\n"; + if ("setter" in fields[name]) { + externs += `extern JSC_CALLCONV JSC_DECLARE_CUSTOM_SETTER(${symbolName(typeName, fields[name].setter)});` + "\n"; } if ("fn" in fields[name]) { @@ -952,8 +804,6 @@ function renderFieldsImpl( ) { const rows: string[] = []; - const supportsObjectCreate = obj.supportsObjectCreate || false; - if (obj.construct) { rows.push( ` @@ -979,9 +829,8 @@ JSC_DEFINE_CUSTOM_GETTER(js${typeName}Constructor, (JSGlobalObject * lexicalGlob if ("cache" in proto[name] || proto[name]?.internal) { const cacheName = typeof proto[name].cache === "string" ? `m_${proto[name].cache}` : `m_${name}`; if ("cache" in proto[name]) { - if (!supportsObjectCreate) { - rows.push( - ` + rows.push( + ` JSC_DEFINE_CUSTOM_GETTER(${symbolName(typeName, name)}GetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue encodedThisValue, PropertyName attributeName)) { auto& vm = JSC::getVM(lexicalGlobalObject); @@ -1021,10 +870,10 @@ JSC_DEFINE_CUSTOM_GETTER(${symbolName(typeName, name)}GetterWrap, (JSGlobalObjec #endif RELEASE_AND_RETURN(throwScope, JSValue::encode(result)); }`.trim(), - ); - if (proto[name].writable) { - rows.push( - ` + ); + if (proto[name].writable) { + rows.push( + ` JSC_DEFINE_CUSTOM_SETTER(${symbolName(typeName, name)}SetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue encodedThisValue, EncodedJSValue encodedValue, PropertyName attributeName)) { auto& vm = JSC::getVM(lexicalGlobalObject); @@ -1038,47 +887,12 @@ JSC_DEFINE_CUSTOM_SETTER(${symbolName(typeName, name)}SetterWrap, (JSGlobalObjec thisObject->${cacheName}.set(vm, thisObject, JSValue::decode(encodedValue)); RELEASE_AND_RETURN(throwScope, true); }`.trim(), - ); - } - } else { - rows.push( - ` -JSC_DEFINE_CUSTOM_GETTER(${symbolName(typeName, name)}GetterWrap, (JSGlobalObject * globalObject, EncodedJSValue encodedThisValue, PropertyName attributeName)) -{ - auto& vm = JSC::getVM(globalObject); - auto throwScope = DECLARE_THROW_SCOPE(vm); - ${className(typeName)}* thisObject = dynamicDowncast<${className(typeName)}>(JSValue::decode(encodedThisValue)); - if (!thisObject) [[unlikely]] { - return JSValue::encode(jsUndefined()); - } - - JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject); - - if (JSValue cachedValue = thisObject->${cacheName}.get()) - return JSValue::encode(cachedValue); - - JSC::JSValue result = JSC::JSValue::decode( - ${symbolName(typeName, proto[name].getter)}(thisObject->wrapped(),${ - proto[name].this!! ? " thisValue, " : "" - } globalObject) - ); - RETURN_IF_EXCEPTION(throwScope, {}); - thisObject->${cacheName}.set(vm, thisObject, result); -#if ASSERT_ENABLED - if (!result.isEmpty() && result.isCell()) { - JSC::Integrity::auditCellFully(vm, result.asCell()); - } -#endif - RELEASE_AND_RETURN(throwScope, JSValue::encode(result)); -} -`.trim(), ); } } rows.push(writeBarrier(symbolName, typeName, name, cacheName)); - } else if ("getter" in proto[name] || ("accessor" in proto[name] && proto[name].getter)) { - if (!supportsObjectCreate) { - rows.push(` + } else if ("getter" in proto[name]) { + rows.push(` JSC_DEFINE_CUSTOM_GETTER(${symbolName(typeName, name)}GetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue encodedThisValue, PropertyName attributeName)) { auto& vm = JSC::getVM(lexicalGlobalObject); @@ -1099,35 +913,9 @@ JSC_DEFINE_CUSTOM_GETTER(${symbolName(typeName, name)}GetterWrap, (JSGlobalObjec RELEASE_AND_RETURN(throwScope, result); } `); - } else { - rows.push(` -JSC_DEFINE_CUSTOM_GETTER(${symbolName(typeName, name)}GetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue encodedThisValue, PropertyName attributeName)) -{ - auto& vm = JSC::getVM(lexicalGlobalObject); - Zig::GlobalObject *globalObject = reinterpret_cast(lexicalGlobalObject); - auto throwScope = DECLARE_THROW_SCOPE(vm); - ${className(typeName)}* thisObject = dynamicDowncast<${className(typeName)}>(JSValue::decode(encodedThisValue)); - if (!thisObject) [[unlikely]] { - return JSValue::encode(jsUndefined()); - } - JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject); - JSC::EncodedJSValue result = ${symbolName(typeName, proto[name].getter)}(thisObject->wrapped(),${ - !!proto[name].this ? " encodedThisValue, " : "" - } globalObject); - RETURN_IF_EXCEPTION(throwScope, {}); -#if ASSERT_ENABLED - JSValue decodedValue = JSValue::decode(result); - if (!decodedValue.isEmpty() && decodedValue.isCell()) { - JSC::Integrity::auditCellFully(vm, decodedValue.asCell()); - } -#endif - RELEASE_AND_RETURN(throwScope, result); -} - `); - } } - if ("setter" in proto[name] || ("accessor" in proto[name] && proto[name].setter)) { + if ("setter" in proto[name]) { rows.push( ` JSC_DEFINE_CUSTOM_SETTER(${symbolName(typeName, name)}SetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue encodedThisValue, EncodedJSValue encodedValue, PropertyName attributeName)) @@ -1140,31 +928,13 @@ JSC_DEFINE_CUSTOM_SETTER(${symbolName(typeName, name)}SetterWrap, (JSGlobalObjec return false; } JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject); - bool result = ${symbolName(typeName, proto[name].setter || proto[name].accessor.setter)}(thisObject->wrapped(),${ + bool result = ${symbolName(typeName, proto[name].setter)}(thisObject->wrapped(),${ !!proto[name].this ? " encodedThisValue, " : "" } lexicalGlobalObject, encodedValue); RELEASE_AND_RETURN(throwScope, result); } `, ); - } else if (supportsObjectCreate) { - rows.push( - ` -JSC_DEFINE_CUSTOM_SETTER(${symbolName(typeName, name)}SetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue encodedThisValue, EncodedJSValue encodedValue, PropertyName attributeName)) -{ - auto& vm = JSC::getVM(lexicalGlobalObject); - auto throwScope = DECLARE_THROW_SCOPE(vm); - JSValue thisValue = JSValue::decode(encodedThisValue); - if (!thisValue.isObject()) { - return false; - } - - JSObject *thisObject = asObject(thisValue); - thisObject->putDirect(vm, attributeName, JSValue::decode(encodedValue), 0); - return true; -} - `, - ); } if ("fn" in proto[name]) { @@ -1277,18 +1047,11 @@ function allCachedValues(obj: ClassDefinition) { } } - for (const name in obj.callbacks ?? {}) { - values.push([name, `m_callback_${name}`]); - } - return values; } -var extraIncludes = []; function generateClassHeader(typeName, obj: ClassDefinition) { - var { klass, proto, JSType = "ObjectType", values = [], callbacks = {}, zigOnly = false } = obj; - - if (zigOnly) return ""; + var { klass, proto, JSType = "ObjectType", values = [] } = obj; const name = className(typeName); @@ -1307,11 +1070,9 @@ function generateClassHeader(typeName, obj: ClassDefinition) { values.length || obj.estimatedSize || obj.valuesArray || - Object.keys(callbacks).length || [...Object.values(klass), ...Object.values(proto)].find(a => a.cache === true) ? "DECLARE_VISIT_CHILDREN;\n" : ""; - const sizeEstimator = "static size_t estimatedSize(JSCell* cell, VM& vm);"; var weakOwner = ""; var weakInit = ``; @@ -1355,7 +1116,7 @@ function generateClassHeader(typeName, obj: ClassDefinition) { class ${name}${final ? " final" : ""} : public JSC::JSDestructibleObject { public: using Base = JSC::JSDestructibleObject; - static constexpr unsigned StructureFlags = Base::StructureFlags${obj.hasOwnProperties() ? ` | HasStaticPropertyTable` : ""}; + static constexpr unsigned StructureFlags = Base::StructureFlags; static ${name}* create(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::Structure* structure, void* ctx); ${obj.valuesArray ? `static ${name}* create(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::Structure* structure, void* ctx, WTF::FixedVector>&& jsvalueArray);` : ""} ${obj.valuesArray && obj.values && obj.values.length > 0 ? `static ${name}* create(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::Structure* structure, void* ctx${obj.values.map(v => `, JSC::JSValue ${v}`).join("")});` : ""} @@ -1449,20 +1210,7 @@ function generateClassHeader(typeName, obj: ClassDefinition) { void finishCreation(JSC::VM&); - ${Object.entries(obj.custom ?? {}) - .map(([fieldName, field]) => { - if (field.extraHeaderIncludes?.length ?? 0) { - extraIncludes.push(...field.extraHeaderIncludes); - } - - var str = ""; - if (field.header) { - str += `#include "${field.header}";` + "\n"; - } - str += `${field.type} ${fieldName};`; - return str; - }) - .join("\n")} + ${domJITTypeCheckFields(proto, klass)} @@ -1471,7 +1219,7 @@ function generateClassHeader(typeName, obj: ClassDefinition) { ${DECLARE_VISIT_CHILDREN} ${renderCachedFieldsHeader(typeName, klass, proto, values)} - ${callbacks ? renderCallbacksHeader(typeName, obj.callbacks) : ""} + ${obj.valuesArray ? "WTF::FixedVector> jsvalueArray;" : ""} }; `.trim(); @@ -1495,30 +1243,17 @@ function domJITTypeCheckFields(proto, klass) { } function generateClassImpl(typeName, obj: ClassDefinition) { - const { - klass: fields, - finalize, - proto, - construct, - estimatedSize, - hasPendingActivity = false, - callbacks = {}, - own, - } = obj; + const { klass: fields, finalize, proto, construct, estimatedSize, hasPendingActivity = false } = obj; const name = className(typeName); // analyzeHeap reports these as named property edges (see allCachedValues); appendHidden // marks for GC without emitting a duplicate anonymous internal edge. klass caches are // marked but never reported, which is moot: no setter is generated, so they stay empty. - let DEFINE_VISIT_CHILDREN_LIST = [...Object.entries(fields), ...Object.entries(proto)] + const DEFINE_VISIT_CHILDREN_LIST = [...Object.entries(fields), ...Object.entries(proto)] .filter(([name, { cache = false }]) => cache === true) .map(([name]) => `visitor.appendHidden(thisObject->m_${name});`) .join("\n"); - for (const name in callbacks) { - DEFINE_VISIT_CHILDREN_LIST += "\n" + ` visitor.appendHidden(thisObject->m_callback_${name});`; - } - const values = (obj.values || []) .map(val => { return `visitor.appendHidden(thisObject->m_${val});`; @@ -1574,19 +1309,11 @@ visitor.reportExtraMemoryVisited(size); DEFINE_VISIT_CHILDREN(${name}); -${renderCallbacksCppImpl(typeName, callbacks)} - `.trim(); } var output = ``; - for (let { impl } of Object.values(obj.custom ?? {})) { - if (impl) { - output += `#include "${impl}";` + "\n"; - } - } - if (hasPendingActivity) { externs += `extern JSC_CALLCONV bool JSC_HOST_CALL_ATTRIBUTES ${symbolName(typeName, "hasPendingActivity")}(void* ptr);` + @@ -1598,22 +1325,6 @@ ${renderCallbacksCppImpl(typeName, callbacks)} `; } - if (obj.hasOwnProperties()) { - output += Object.entries(own) - .map( - ([name, getterName]) => ` -static JSC::JSValue construct${symbolName(obj.name, name)}PropertyCallback(JSC::VM &vm, JSC::JSObject* initialThisObject) { - auto scope = DECLARE_THROW_SCOPE(vm); - Bun::JS${obj.name}* thisObject = uncheckedDowncast(initialThisObject); - JSC::EncodedJSValue result = ${protoSymbolName(obj.name, getterName)}(thisObject->wrapped(), thisObject->globalObject()); - RETURN_IF_EXCEPTION(scope, {}); - return JSC::JSValue::decode(result); -} - `, - ) - .join("\n"); - } - if (finalize) { output += ` ${name}::~${name}() @@ -1670,7 +1381,7 @@ void ${name}::destroy(JSCell* cell) static_cast<${name}*>(cell)->${name}::~${name}(); } -const ClassInfo ${name}::s_info = { "${typeName}"_s, &Base::s_info, ${obj.hasOwnProperties() ? `&${typeName}Table` : "nullptr"}, nullptr, CREATE_METHOD_TABLE(${name}) }; +const ClassInfo ${name}::s_info = { "${typeName}"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(${name}) }; void ${name}::finishCreation(VM& vm) { @@ -1899,22 +1610,8 @@ function generateHeader(typeName, obj) { return "\n" + fields.join("\n").trim(); } -let lutTextFile = ` -/* Source for ZigGeneratedClasses.lut.h -`; -function generateOwnProperties(typeName, symbolName, obj, props = {}, wrapped) { - lutTextFile += ` -${generateHashTableComment(typeName, symbolName, obj, props, wrapped)} -`; -} - function generateImpl(typeName, obj: ClassDefinition) { - if (obj.zigOnly) return ""; - const proto = obj.proto; - if (obj?.hasOwnProperties?.()) { - generateOwnProperties(typeName, name => symbolName(typeName, name), obj, obj.own); - } return [ (obj.final ?? true) ? generatePrototypeHeader(typeName, true) : null, !obj.noConstructor ? generateConstructorHeader(typeName).trim() + "\n" : null, @@ -2177,7 +1874,6 @@ function generateRust( { klass = {}, proto = {}, - own = {}, construct, constructNeedsThis = false, finalize, @@ -2193,11 +1889,6 @@ function generateRust( sharedThis = true, } = {} as ClassDefinition, ) { - proto = { - ...Object.fromEntries(Object.entries(own || {}).map(([name, getterName]) => [name, { getter: getterName }])), - ...proto, - }; - const gc_fields = Object.entries({ ...proto, ...Object.fromEntries((values || []).map(a => [a, { internal: true }])), @@ -2302,17 +1993,15 @@ function generateRust( const seen = new Map(); const exportNames = name => zigExportName(seen, n => protoSymbolName(typeName, n), proto[name]); for (const name in proto) { - const { getter, setter, accessor, fn, this: thisValue = false, passThis, DOMJIT } = proto[name]; + const { getter, setter, fn, this: thisValue = false, passThis, DOMJIT } = proto[name]; const names = exportNames(name); - const g = accessor ? accessor.getter : getter; - const s = accessor ? accessor.setter : setter; if (thisValue && !sharedThis && (names.getter || names.setter)) { throw new Error(`${typeName}.${name}: \`this: true\` accessors require \`sharedThis: true\``); } if (names.getter) { - const id = rustSnakeIdent(g); + const id = rustSnakeIdent(getter); thunk( names.getter, `(this: ${recv}, ${thisValue ? "this_value: JSValue, " : ""}global: &JSGlobalObject) -> JSValue`, @@ -2323,7 +2012,7 @@ function generateRust( } if (names.setter) { - const id = rustSnakeIdent(s); + const id = rustSnakeIdent(setter); thunk( names.setter, `(this: ${recv}, ${thisValue ? "this_value: JSValue, " : ""}global: &JSGlobalObject, value: JSValue) -> bool`, @@ -2362,13 +2051,11 @@ function generateRust( const seen = new Map(); const exportNames = name => zigExportName(seen, n => classSymbolName(typeName, n), klass[name]); for (const name in klass) { - const { getter, setter, accessor, fn, DOMJIT } = klass[name]; + const { getter, setter, fn, DOMJIT } = klass[name]; const names = exportNames(name); - const g = accessor ? accessor.getter : getter; - const s = accessor ? accessor.setter : setter; if (names.getter) { - const id = rustSnakeIdent(g); + const id = rustSnakeIdent(getter); thunk( names.getter, `(global: &JSGlobalObject, this_value: JSValue, prop: PropertyName) -> JSValue`, @@ -2377,7 +2064,7 @@ function generateRust( } if (names.setter) { - const id = rustSnakeIdent(s); + const id = rustSnakeIdent(setter); thunk( names.setter, `(global: &JSGlobalObject, this_value: JSValue, value: JSValue, prop: PropertyName) -> bool`, @@ -2562,9 +2249,7 @@ pub type WriteBytesFn = unsafe extern "C" fn(*mut c_void, *const u8, u32); pub struct PropertyName(pub *const c_void); `; -function generateLazyClassStructureHeader(typeName, { klass = {}, proto = {}, zigOnly = false }) { - if (zigOnly) return ""; - +function generateLazyClassStructureHeader(typeName, { klass = {}, proto = {} }) { return ` JSC::Structure* ${className(typeName)}Structure() const { return m_${className(typeName)}.getInitializedOnMainThread(this); } JSC::JSObject* ${className(typeName)}Constructor() const { return m_${className(typeName)}.constructorInitializedOnMainThread(this); } @@ -2573,9 +2258,7 @@ function generateLazyClassStructureHeader(typeName, { klass = {}, proto = {}, zi `.trim(); } -function generateLazyClassStructureImpl(typeName, { klass = {}, proto = {}, noConstructor = false, zigOnly = false }) { - if (zigOnly) return ""; - +function generateLazyClassStructureImpl(typeName, { klass = {}, proto = {}, noConstructor = false }) { return ` m_${className(typeName)}.initLater( [](LazyClassStructure::Initializer& init) { @@ -2668,7 +2351,6 @@ namespace WebCore { using namespace JSC; using namespace Zig; -#include "ZigGeneratedClasses.lut.h" `; @@ -2779,15 +2461,13 @@ classes.sort((a, b) => (a.name < b.name ? -1 : 1)); // sort all the prototype keys and klass keys for (const obj of classes) { - let { klass = {}, proto = {}, own = {} } = obj; + let { klass = {}, proto = {} } = obj; klass = Object.fromEntries(Object.entries(klass).sort(([a], [b]) => a.localeCompare(b))); proto = Object.fromEntries(Object.entries(proto).sort(([a], [b]) => a.localeCompare(b))); - own = Object.fromEntries(Object.entries(own).sort(([a], [b]) => a.localeCompare(b))); obj.klass = klass; obj.proto = proto; - obj.own = own; } const GENERATED_CLASSES_FOOTER = ` @@ -2891,12 +2571,11 @@ function writeCppSerializers() { ); } -if (!process.env.ONLY_ZIG) { +// ── C++ output: ZigGeneratedClasses.{h,cpp,+*.h} and the .d.ts twin ──────── +{ const allHeaders = classes.map(a => generateHeader(a.name, a)); await writeIfNotChanged(`${outBase}/ZigGeneratedClasses.h`, [ - GENERATED_CLASSES_HEADER[0], - ...[...new Set(extraIncludes.map(a => `#include "${a}";` + "\n"))], - GENERATED_CLASSES_HEADER[1], + ...GENERATED_CLASSES_HEADER, ...allHeaders, GENERATED_CLASSES_FOOTER, ]); @@ -2913,13 +2592,6 @@ if (!process.env.ONLY_ZIG) { isTransferableCppImpl(), ]); - if (lutTextFile.length) { - lutTextFile += ` -/* -`; - await writeIfNotChanged(`${outBase}/ZigGeneratedClasses.lut.txt`, [lutTextFile]); - } - await writeIfNotChanged( `${outBase}/ZigGeneratedClasses+lazyStructureHeader.h`, classes.map(a => generateLazyClassStructureHeader(a.name, a)).join("\n"), @@ -3001,24 +2673,6 @@ function getPropertySignatureWithComment( } else if ("builtin" in propDef) { commentLines.push(`* C++ builtin name: \`${propDef.builtin}\``); } - } else if ("accessor" in propDef) { - signature = `${tsPropName}: unknown;`; // Read-write accessor - commentLines.push(` zig ⚡ \`${propDef.accessor.getter}\``); - commentLines.push( - ` Look for a getter like this: - * \`\`\`zig - * fn ${propDef.accessor.getter}(this: *${classDef.name}, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { ... } - * \`\`\``, - ); - commentLines.push( - ` Look for a setter like this: - * \`\`\`zig - * fn ${propDef.accessor.setter}(this: *${classDef.name}, globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!void - * \`\`\``, - ); - if (propDef.cache) { - commentLines.push(` Cached value ${typeof propDef.cache === "string" ? `via m_${propDef.cache}` : ""}`); - } } else if ("getter" in propDef) { signature = `${tsPropName}: unknown;`; // Getter, possibly with setter isReadOnly = !propDef.writable; // Mark readonly if only getter or explicitly not writable @@ -3063,15 +2717,12 @@ export function generateBuiltinTypes(classes: ClassDefinition[]): string { const typeDeclarations: string[] = []; for (const classDef of classes) { - // Skip classes marked as zigOnly, as they shouldn't have JS/TS counterparts - if ((classDef as any).zigOnly) continue; - const instanceMembers: string[] = []; const staticMembers: string[] = []; const constructorInterfaceName = `${classDef.name}Constructor`; const staticsInterfaceName = `${classDef.name}Statics`; - // --- Process Instance Members (proto, own, values) --- + // --- Process Instance Members (proto, values) --- for (const [propName, propDef] of Object.entries(classDef.proto || {})) { const result = getPropertySignatureWithComment(propName, propDef, classDef); if (result) { @@ -3080,10 +2731,6 @@ export function generateBuiltinTypes(classes: ClassDefinition[]): string { } } - for (const [propName, zigFieldName] of Object.entries(classDef.own || {})) { - instanceMembers.push(` readonly ${propName}: any;`); - } - // --- Process Static Members (klass) --- for (const [propName, propDef] of Object.entries(classDef.klass || {})) { const result = getPropertySignatureWithComment(propName, propDef, classDef); diff --git a/src/codegen/generate-host-exports.ts b/src/codegen/generate-host-exports.ts index 49f7eb25f138..75d92f123389 100644 --- a/src/codegen/generate-host-exports.ts +++ b/src/codegen/generate-host-exports.ts @@ -45,8 +45,6 @@ import { existsSync, readFileSync } from "fs"; import path from "path"; import { readdirRecursive, writeIfNotChanged } from "./helpers"; -if (process.env.BUN_SILENT === "1") console.log = () => {}; - const argv = process.argv.slice(2); const outBase = argv.pop(); if (!outBase) { diff --git a/src/codegen/generate-jssink.ts b/src/codegen/generate-jssink.ts index d11702be1be4..ce4e38066b4a 100644 --- a/src/codegen/generate-jssink.ts +++ b/src/codegen/generate-jssink.ts @@ -19,14 +19,12 @@ function names(name) { controllerName: `Readable${name}Controller`, prototypeName: `JS${name}Prototype`, controllerPrototypeName: `JSReadable${name}ControllerPrototype`, - writableStreamSourcePrototype: `JSWritableStreamSource${name}Prototype`, - writableStreamName: `JSWritableStreamSource${name}`, }; } function header() { function classTemplate(name) { - const { constructor, className, controller, writableStreamName } = names(name); + const { constructor, className, controller } = names(name); return `class ${constructor} final : public JSC::InternalFunction { public: @@ -312,18 +310,7 @@ const ClassInfo JSReadableSinkControllerBase::s_info = { "ReadableSinkController var templ = head; for (let name of classes) { - const { - className, - controller, - prototypeName, - controllerName, - controllerPrototypeName, - constructor, - writableStreamName, - writableStreamSourcePrototype, - } = names(name); - const protopad = `${controller}__close`.length; - const padding = `${name}__doClose`.length; + const { className, controller, prototypeName, controllerName, controllerPrototypeName, constructor } = names(name); templ += ` void ${className}::ref() { diff --git a/src/codegen/replacements.ts b/src/codegen/replacements.ts index af31730db055..ad089c28e00e 100644 --- a/src/codegen/replacements.ts +++ b/src/codegen/replacements.ts @@ -8,7 +8,6 @@ import { registerNativeCall } from "./generate-js2native"; export const replacements: ReplacementRule[] = [ { from: /\bthrow new TypeError\b/g, to: "$throwTypeError" }, { from: /\bthrow new RangeError\b/g, to: "$throwRangeError" }, - { from: /\bthrow new OutOfMemoryError\b/g, to: "$throwOutOfMemoryError" }, { from: /\bnew TypeError\b/g, to: "$makeTypeError" }, { from: /\bexport\s*default/g, to: "$exports =" }, ]; @@ -169,7 +168,6 @@ export interface ReplacementRule { from: RegExp; to?: string; toRaw?: string; - global?: boolean; } export const function_replacements = [ diff --git a/src/css/css_modules.rs b/src/css/css_modules.rs index c342a548d35e..314c1e569e9e 100644 --- a/src/css/css_modules.rs +++ b/src/css/css_modules.rs @@ -411,16 +411,6 @@ pub struct CssModuleExport<'a> { /// /// See [CssModuleExport](CssModuleExport). pub enum CssModuleReference<'a> { - /// A local reference. - Local { - /// The local (compiled) name for the reference. - name: &'a [u8], - }, - /// A global reference. - Global { - /// The referenced global name. - name: &'a [u8], - }, /// A reference to an export in a different file. Dependency { /// The name to reference within the dependency. @@ -432,27 +422,6 @@ pub enum CssModuleReference<'a> { }, } -impl<'a> CssModuleReference<'a> { - pub fn eql(&self, other: &Self) -> bool { - match (self, other) { - (Self::Local { name: a }, Self::Local { name: b }) => a == b, - (Self::Global { name: a }, Self::Global { name: b }) => a == b, - // .dependency => |v| bun.strings.eql(v.name, other.dependency.name) and bun.strings.eql(v.specifier, other.dependency.specifier), - ( - Self::Dependency { - name: an, - specifier: asp, - }, - Self::Dependency { - name: bn, - specifier: bsp, - }, - ) => an == bn && asp == bsp, - _ => false, - } - } -} - /// LAYERING: canonical implementation lives in `bun_base64::wyhash_url_safe` /// (a leaf crate) so `bun_bundler::LinkerContext::mangle_local_css` can call /// the *same* hasher without depending on `bun_css`. Re-export here so diff --git a/src/js/builtins.d.ts b/src/js/builtins.d.ts index 7d43df169845..8c65bffa7a64 100644 --- a/src/js/builtins.d.ts +++ b/src/js/builtins.d.ts @@ -49,14 +49,8 @@ declare var $overriddenName: string; declare var $linkTimeConstant: never; /** Assign to this directly above a function declaration (like a decorator) to set visibility */ declare var $visibility: "Public" | "Private" | "PrivateRecursive"; -/** ??? */ -declare var $nakedConstructor: never; -/** Assign to this directly above a function declaration (like a decorator) to set intrinsic */ -declare var $intrinsic: string; /** Assign to this directly above a function declaration (like a decorator) to make it a constructor. */ declare var $constructor; -/** Place this directly above a function declaration (like a decorator) to NOT include "use strict" */ -declare var $sloppy; /** Place this directly above a function declaration (like a decorator) to always inline the function */ declare var $alwaysInline; @@ -202,11 +196,6 @@ declare function $throwTypeError(message: string): never; * @deprecated */ declare function $throwRangeError(message: string): never; -/** - * **NOTE** - use `throw new OutOfMemoryError()` instead. it compiles to the same builtin - * @deprecated - */ -declare function $throwOutOfMemoryError(): never; declare function $putByIdDirect(obj: any, key: PropertyKey, value: any): void; /** @@ -471,10 +460,6 @@ declare interface AddEventListenerOptions { $kResistStopPropagation?: boolean; } -declare class OutOfMemoryError { - constructor(); -} - // Provided by the C++ Web Streams implementation. declare class ReadableByteStreamController { private constructor(); diff --git a/src/js/internal-for-testing.ts b/src/js/internal-for-testing.ts index 9b1fed3e91d9..2b343abce6a3 100644 --- a/src/js/internal-for-testing.ts +++ b/src/js/internal-for-testing.ts @@ -541,14 +541,6 @@ export function getWebStreamState(stream: ReadableStream | WritableStream): { } } -export const fs = require("node:fs/promises").$data; - -export const fsStreamInternals = { - writeStreamFastPath(str) { - return str[require("internal/fs/streams").kWriteStreamFastPath]; - }, -}; - export const arrayBufferViewHasBuffer = $newCppFunction( "InternalForTesting.cpp", "jsFunction_arrayBufferViewHasBuffer", @@ -564,7 +556,6 @@ export const timerInternals = { export const dgramInternals = { newRawSocketFd: $newRustFunction("udp_socket.rs", "jsDgramNewSocketFd", 2), closeRawFd: $newRustFunction("udp_socket.rs", "jsDgramCloseFd", 1), - isFdAdopted: $newRustFunction("udp_socket.rs", "jsDgramIsFdAdopted", 1), }; export const decodeURIComponentSIMD = $newCppFunction( diff --git a/src/js/internal/http.ts b/src/js/internal/http.ts index 96dee383fc92..19c94ee3fe6c 100644 --- a/src/js/internal/http.ts +++ b/src/js/internal/http.ts @@ -1,26 +1,9 @@ const { isIPv4 } = require("internal/net/isIP"); -const { - getHeader, - setHeader, - Headers, - assignHeaders: assignHeadersFast, - setRequestTimeout, - headersTuple, - webRequestOrResponseHasBodyValue, - setServerCustomOptions, - setServerAppFlags, - getCompleteWebRequestOrResponseBodyValueAsArrayBuffer, - drainMicrotasks, - setServerIdleTimeout, -} = $cpp("NodeHTTP.cpp", "createNodeHTTPInternalBinding") as { - getHeader: (headers: Headers, name: string) => string | undefined; - setHeader: (headers: Headers, name: string, value: string) => void; - Headers: (typeof globalThis)["Headers"]; - assignHeaders: (object: any, req: Request, headersTuple: any) => boolean; - setRequestTimeout: (req: Request, timeout: number) => boolean; - headersTuple: any; - webRequestOrResponseHasBodyValue: (arg: any) => boolean; +const { setServerCustomOptions, setServerAppFlags, drainMicrotasks, setServerIdleTimeout } = $cpp( + "NodeHTTP.cpp", + "createNodeHTTPInternalBinding", +) as { setServerCustomOptions: ( server: any, requireHostHeader: boolean, @@ -37,14 +20,12 @@ const { lenientHttpFlags: number, httpAllowHalfOpen: boolean, ) => void; - getCompleteWebRequestOrResponseBodyValueAsArrayBuffer: (arg: any) => ArrayBuffer | undefined; drainMicrotasks: () => void; setServerIdleTimeout: (server: any, timeout: number) => void; }; const getRawKeys = $newCppFunction("JSFetchHeaders.cpp", "jsFetchHeaders_getRawKeys", 0); -const kDeprecatedReplySymbol = Symbol("deprecatedReply"); const kBodyChunks = Symbol("bodyChunks"); const kPath = Symbol("path"); const kPort = Symbol("port"); @@ -73,12 +54,8 @@ const headerStateSymbol = Symbol("headerState"); const kEmitState = Symbol("emitState"); const bodyStreamSymbol = Symbol("bodyStream"); -const controllerSymbol = Symbol("controller"); -const runSymbol = Symbol("run"); -const deferredSymbol = Symbol("deferred"); const eofInProgress = Symbol("eofInProgress"); const fakeSocketSymbol = Symbol("fakeSocket"); -const firstWriteSymbol = Symbol("firstWrite"); const headersSymbol = Symbol("headers"); const isTlsSymbol = Symbol("is_tls"); const kHandle = Symbol("handle"); @@ -99,8 +76,6 @@ const kPendingCallbacks = Symbol("pendingCallbacks"); const kRequest = Symbol("request"); const kCloseCallback = Symbol("closeCallback"); -const kEmptyObject = Object.freeze(Object.create(null)); - export const enum ClientRequestEmitState { socket = 1, prefinish = 2, @@ -157,20 +132,6 @@ function emitErrorNextTickIfErrorListener(self, err, cb) { } } -// TODO: make this more robust. -function isAbortError(err) { - return err?.name === "AbortError"; -} - -// This lets us skip some URL parsing -let isNextIncomingMessageHTTPS = false; -function getIsNextIncomingMessageHTTPS() { - return isNextIncomingMessageHTTPS; -} -function setIsNextIncomingMessageHTTPS(value) { - isNextIncomingMessageHTTPS = value; -} - function callCloseCallback(self) { if (self[kCloseCallback]) { self[kCloseCallback](); @@ -590,16 +551,12 @@ function filterEnvForProxies(env) { } export { - Headers, METHODS, STATUS_CODES, abortedSymbol, - assignHeadersFast, bodyStreamSymbol, callCloseCallback, checkShouldUseProxy, - controllerSymbol, - deferredSymbol, drainMicrotasks, emitCloseNT, emitCloseNTAndComplete, @@ -608,26 +565,18 @@ export { eofInProgress, fakeSocketSymbol, filterEnvForProxies, - firstWriteSymbol, - getCompleteWebRequestOrResponseBodyValueAsArrayBuffer, - getHeader, - getIsNextIncomingMessageHTTPS, getMaxHTTPHeaderSize, getRawKeys, hasServerResponseFinished, headerStateSymbol, headersSymbol, - headersTuple, - isAbortError, isTlsSymbol, kAbortController, kAgent, kBodyChunks, kClearTimeout, kCloseCallback, - kDeprecatedReplySymbol, kEmitState, - kEmptyObject, kFetchRequest, kHandle, kHost, @@ -661,12 +610,8 @@ export { parseProxyConfigFromEnv, parseProxyUrl, reqSymbol, - runSymbol, serverSymbol, - setHeader, - setIsNextIncomingMessageHTTPS, setMaxHTTPHeaderSize, - setRequestTimeout, setServerAppFlags, setServerCustomOptions, setServerIdleTimeout, @@ -678,5 +623,4 @@ export { utcDate, validateMsecs, webRequestOrResponse, - webRequestOrResponseHasBodyValue, }; diff --git a/src/js/internal/readline/interface.js b/src/js/internal/readline/interface.js index 29c878e4fd6e..e9b1ae6f6bc6 100644 --- a/src/js/internal/readline/interface.js +++ b/src/js/internal/readline/interface.js @@ -22,7 +22,6 @@ const { MathMaxApply, NumberIsFinite, ObjectDefineProperty, - ObjectSetPrototypeOf, RegExpPrototypeExec, SafeStringIterator, StringPrototypeCodePointAt, diff --git a/src/js/internal/repl/node-primordials.js b/src/js/internal/repl/node-primordials.js index a380c2b0d145..01e81adc2d39 100644 --- a/src/js/internal/repl/node-primordials.js +++ b/src/js/internal/repl/node-primordials.js @@ -117,7 +117,6 @@ export default { ObjectGetOwnPropertyNames: Object.getOwnPropertyNames, ObjectGetPrototypeOf: Object.getPrototypeOf, ObjectKeys: Object.keys, - ObjectSetPrototypeOf: Object.setPrototypeOf, Promise, PromisePrototypeThen: (p, onFulfilled, onRejected) => PromisePrototypeThenFn.$call(p, onFulfilled, onRejected), PromiseReject: v => PromiseRejectFn.$call(Promise, v), diff --git a/src/js/node/wasi.ts b/src/js/node/wasi.ts index 2f952a86120e..b4b9fa47a609 100644 --- a/src/js/node/wasi.ts +++ b/src/js/node/wasi.ts @@ -401,11 +401,6 @@ var require_constants = __commonJS({ // node_modules/wasi-js/dist/wasi.js var require_wasi = __commonJS({ "node_modules/wasi-js/dist/wasi.js"(exports) { - var __importDefault = - (exports && exports.__importDefault) || - function (mod) { - return mod && mod.__esModule ? mod : { default: mod }; - }; let fs; Object.defineProperty(exports, "__esModule", { value: true }); var SC_OPEN_MAX = 32768; diff --git a/src/js/private.d.ts b/src/js/private.d.ts index 106355dcb997..ee6260fea979 100644 --- a/src/js/private.d.ts +++ b/src/js/private.d.ts @@ -141,21 +141,6 @@ declare module "bun" { var fetch: typeof globalThis.fetch; } -/** - * `JSC::JSModuleLoader` - */ -declare var Loader: { - registry: Map; - - parseModule(key: string, sourceCodeObject: JSCSourceCodeObject): Promise | LoaderModule; - linkAndEvaluateModule(resolvedSpecifier: string, unknown: any); - getModuleNamespaceObject(module: LoaderModule): any; - requestedModules(module: LoaderModule): string[]; - dependencyKeysIfEvaluated(specifier: string): string[]; - resolve(specifier: string, referrer: string): string; - ensureRegistered(key: string): LoaderEntry; -}; - interface LoaderEntry { key: string; state: number; diff --git a/src/jsc/bindings/AsymmetricKeyValue.cpp b/src/jsc/bindings/AsymmetricKeyValue.cpp index 17ef96f1678c..10374c6ef62a 100644 --- a/src/jsc/bindings/AsymmetricKeyValue.cpp +++ b/src/jsc/bindings/AsymmetricKeyValue.cpp @@ -22,59 +22,13 @@ // IN THE SOFTWARE. #include "root.h" -#include "ErrorCode.h" -#include "BunCommonStrings.h" -#include "JavaScriptCore/JSArrayBufferView.h" -#include "JavaScriptCore/JSCJSValue.h" -#include "JavaScriptCore/JSCast.h" #include "ZigGlobalObject.h" -#include "webcrypto/JSCryptoKey.h" -#include "webcrypto/JSSubtleCrypto.h" #include "webcrypto/CryptoKeyAKP.h" #include "webcrypto/CryptoKeyOKP.h" #include "webcrypto/CryptoKeyEC.h" #include "webcrypto/CryptoKeyRSA.h" -#include "webcrypto/CryptoKeyAES.h" -#include "webcrypto/CryptoKeyHMAC.h" -#include "webcrypto/CryptoKeyRaw.h" -#include "webcrypto/CryptoKeyUsage.h" -#include "webcrypto/JsonWebKey.h" -#include "webcrypto/JSJsonWebKey.h" -#include "JavaScriptCore/JSObject.h" -#include "JavaScriptCore/ObjectConstructor.h" -#include "headers-handwritten.h" #include -#include -#include -#include -#include -#include "JSBuffer.h" -#include "CryptoAlgorithmHMAC.h" -#include "CryptoAlgorithmEd25519.h" -#include "CryptoAlgorithmRSA_OAEP.h" -#include "CryptoAlgorithmRSA_PSS.h" -#include "CryptoAlgorithmRSASSA_PKCS1_v1_5.h" -#include "CryptoAlgorithmECDSA.h" -#include "CryptoAlgorithmEcdsaParams.h" -#include "CryptoAlgorithmRsaOaepParams.h" -#include "CryptoAlgorithmRsaPssParams.h" -#include "CryptoAlgorithmRegistry.h" -#include "wtf/ForbidHeapAllocation.h" -#include "wtf/Noncopyable.h" -#include "ncrypto.h" #include "AsymmetricKeyValue.h" -using namespace JSC; -using namespace Bun; -using JSGlobalObject = JSC::JSGlobalObject; -using Exception = JSC::Exception; -using JSValue = JSC::JSValue; -using JSString = JSC::JSString; -using JSModuleLoader = JSC::JSModuleLoader; -using JSModuleRecord = JSC::JSModuleRecord; -using Identifier = JSC::Identifier; -using SourceOrigin = JSC::SourceOrigin; -using JSObject = JSC::JSObject; -using JSNonFinalObject = JSC::JSNonFinalObject; namespace WebCore { diff --git a/src/jsc/bindings/NodeHTTP.cpp b/src/jsc/bindings/NodeHTTP.cpp index 367d067c759c..e2ced9fe1603 100644 --- a/src/jsc/bindings/NodeHTTP.cpp +++ b/src/jsc/bindings/NodeHTTP.cpp @@ -6,13 +6,10 @@ #include "BunClientData.h" #include -#include #include #include #include -#include "wtf/URL.h" #include "JSFetchHeaders.h" -#include "JSDOMExceptionHandling.h" #include #include #include "ZigGeneratedClasses.h" @@ -21,7 +18,6 @@ #include "ZigGeneratedClasses.h" #include #include -#include #include "JSSocketAddressDTO.h" #include "node/JSNodeHTTPServerSocket.h" #include "node/JSNodeHTTPServerSocketPrototype.h" @@ -31,143 +27,12 @@ using namespace JSC; using namespace WebCore; BUN_DECLARE_HOST_FUNCTION(Bun__drainMicrotasksFromJS); -BUN_DECLARE_HOST_FUNCTION(jsFunctionRequestOrResponseHasBodyValue); -BUN_DECLARE_HOST_FUNCTION(jsFunctionGetCompleteRequestOrResponseBodyValueAsArrayBuffer); -extern "C" uWS::HttpRequest* Request__getUWSRequest(void*); -extern "C" void Request__setInternalEventCallback(void*, EncodedJSValue, JSC::JSGlobalObject*); -extern "C" void Request__setTimeout(void*, EncodedJSValue, JSC::JSGlobalObject*); -extern "C" bool NodeHTTPResponse__setTimeout(void*, EncodedJSValue, JSC::JSGlobalObject*); extern "C" void Server__setIdleTimeout(EncodedJSValue, EncodedJSValue, JSC::JSGlobalObject*); extern "C" EncodedJSValue Server__setAppFlags(JSC::JSGlobalObject*, EncodedJSValue, bool require_host_header, bool use_strict_method_validation, uint8_t lenient_http_flags, bool http_allow_half_open); extern "C" EncodedJSValue Server__setOnClientError(JSC::JSGlobalObject*, EncodedJSValue, EncodedJSValue); extern "C" EncodedJSValue Server__setOnConnection(JSC::JSGlobalObject*, EncodedJSValue, EncodedJSValue); extern "C" EncodedJSValue Server__setMaxHTTPHeaderSize(JSC::JSGlobalObject*, EncodedJSValue, uint64_t); -static EncodedJSValue assignHeadersFromFetchHeaders(FetchHeaders& impl, JSObject* prototype, JSObject* objectValue, JSC::InternalFieldTuple* tuple, JSC::JSGlobalObject* globalObject, JSC::VM& vm) -{ - auto scope = DECLARE_THROW_SCOPE(vm); - uint32_t size = std::min(impl.sizeAfterJoiningSetCookieHeader(), static_cast(JSFinalObject::maxInlineCapacity)); - JSC::JSArray* array = constructEmptyArray(globalObject, nullptr, impl.size() * 2); - RETURN_IF_EXCEPTION(scope, {}); - JSC::JSObject* obj = JSC::constructEmptyObject(globalObject, prototype, size); - RETURN_IF_EXCEPTION(scope, {}); - - unsigned arrayI = 0; - - auto& internal = impl.internalHeaders(); - { - auto& vec = internal.commonHeaders(); - for (const auto& it : vec) { - const auto& name = it.key; - const auto& value = it.value; - const auto impl = WTF::httpHeaderNameStringImpl(name); - JSString* jsValue = jsString(vm, value); - obj->putDirect(vm, Identifier::fromString(vm, impl), jsValue, 0); - array->putDirectIndex(globalObject, arrayI++, jsString(vm, impl)); - array->putDirectIndex(globalObject, arrayI++, jsValue); - RETURN_IF_EXCEPTION(scope, {}); - } - } - - { - const auto& values = internal.getSetCookieHeaders(); - - size_t count = values.size(); - - if (count > 0) { - JSC::JSArray* setCookies = constructEmptyArray(globalObject, nullptr, count); - RETURN_IF_EXCEPTION(scope, {}); - const auto setCookieHeaderString = WTF::httpHeaderNameStringImpl(HTTPHeaderName::SetCookie); - - JSString* setCookie = jsString(vm, setCookieHeaderString); - - for (size_t i = 0; i < count; ++i) { - auto* out = jsString(vm, values[i]); - array->putDirectIndex(globalObject, arrayI++, setCookie); - array->putDirectIndex(globalObject, arrayI++, out); - setCookies->putDirectIndex(globalObject, i, out); - RETURN_IF_EXCEPTION(scope, {}); - } - - RETURN_IF_EXCEPTION(scope, {}); - obj->putDirect(vm, JSC::Identifier::fromString(vm, setCookieHeaderString), setCookies, 0); - } - } - - { - const auto& vec = internal.uncommonHeaders(); - for (const auto& it : vec) { - const auto& name = it.key; - const auto& value = it.value; - auto* jsValue = jsString(vm, value); - obj->putDirect(vm, Identifier::fromString(vm, name.convertToASCIILowercase()), jsValue, 0); - array->putDirectIndex(globalObject, arrayI++, jsString(vm, name)); - array->putDirectIndex(globalObject, arrayI++, jsValue); - } - } - - tuple->putInternalField(vm, 0, obj); - tuple->putInternalField(vm, 1, array); - - return JSValue::encode(tuple); -} - -enum class RequestHeaderKind : uint8_t { - Joinable, - Singleton, - Cookie, - SetCookie, -}; - -static RequestHeaderKind requestHeaderKind(WebCore::HTTPHeaderName name) -{ - switch (name) { - case WebCore::HTTPHeaderName::SetCookie: - return RequestHeaderKind::SetCookie; - case WebCore::HTTPHeaderName::Cookie: - return RequestHeaderKind::Cookie; - case WebCore::HTTPHeaderName::Age: - case WebCore::HTTPHeaderName::Authorization: - case WebCore::HTTPHeaderName::ContentLength: - case WebCore::HTTPHeaderName::ContentType: - case WebCore::HTTPHeaderName::ETag: - case WebCore::HTTPHeaderName::Expires: - case WebCore::HTTPHeaderName::Host: - case WebCore::HTTPHeaderName::IfModifiedSince: - case WebCore::HTTPHeaderName::IfUnmodifiedSince: - case WebCore::HTTPHeaderName::LastModified: - case WebCore::HTTPHeaderName::Location: - case WebCore::HTTPHeaderName::ProxyAuthorization: - case WebCore::HTTPHeaderName::Referer: - case WebCore::HTTPHeaderName::UserAgent: - return RequestHeaderKind::Singleton; - default: - return RequestHeaderKind::Joinable; - } -} - -static RequestHeaderKind requestHeaderKind(const WTF::String& lowercasedName) -{ - if (lowercasedName == "from"_s || lowercasedName == "max-forwards"_s || lowercasedName == "retry-after"_s || lowercasedName == "server"_s) - return RequestHeaderKind::Singleton; - return RequestHeaderKind::Joinable; -} - -// Builds the value for a duplicated, non-singleton request header: the -// existing value, the kind's separator, and the new value as one flat -// string — never a rope. -static JSString* joinedRequestHeaderValue(JSC::JSGlobalObject* globalObject, JSC::VM& vm, JSString* existing, RequestHeaderKind kind, const WTF::String& value) -{ - auto scope = DECLARE_THROW_SCOPE(vm); - auto existingValue = existing->value(globalObject); - RETURN_IF_EXCEPTION(scope, nullptr); - String merged = tryMakeString(existingValue.data, kind == RequestHeaderKind::Cookie ? "; "_s : ", "_s, value); - if (merged.isNull()) [[unlikely]] { - throwOutOfMemoryError(globalObject, scope); - return nullptr; - } - return jsString(vm, merged); -} // Bit layout must stay in sync with kDispatchBits* in src/js/node/_http_server.ts. static constexpr uint32_t kDispatchConnClose = 1 << 0; static constexpr uint32_t kDispatchConnUpgrade = 1 << 1; @@ -388,212 +253,6 @@ extern "C" void Bun__NodeHTTP__acknowledgeThrowScope(JSC::JSGlobalObject* global // onto the native response so takeRawHeaders can materialize them on demand. extern "C" void NodeHTTPResponse__adoptRawRequestHeaders(void* nodeHttpResponse, const uint8_t* data, size_t length); -// This is an 8% speedup. -static EncodedJSValue assignHeadersFromUWebSockets(uWS::HttpRequest* request, JSObject* prototype, JSObject* objectValue, JSC::InternalFieldTuple* tuple, JSC::JSGlobalObject* globalObject, JSC::VM& vm) -{ - auto scope = DECLARE_THROW_SCOPE(vm); - auto& builtinNames = WebCore::builtinNames(vm); - - { - std::string_view fullURLStdStr = request->getFullUrl(); - String fullURL = String::fromUTF8ReplacingInvalidSequences({ reinterpret_cast(fullURLStdStr.data()), fullURLStdStr.length() }); - PutPropertySlot slot(objectValue, false); - objectValue->put(objectValue, globalObject, builtinNames.urlPublicName(), jsString(vm, WTF::move(fullURL)), slot); - RETURN_IF_EXCEPTION(scope, {}); - } - - { - PutPropertySlot slot(objectValue, false); - std::string_view methodView = request->getMethod(); - WTF::String methodString; - switch (methodView.length()) { - case 3: { - if (methodView == std::string_view("get", 3)) { - methodString = "GET"_s; - break; - } - if (methodView == std::string_view("put", 3)) { - methodString = "PUT"_s; - break; - } - - break; - } - case 4: { - if (methodView == std::string_view("post", 4)) { - methodString = "POST"_s; - break; - } - if (methodView == std::string_view("head", 4)) { - methodString = "HEAD"_s; - break; - } - - if (methodView == std::string_view("copy", 4)) { - methodString = "COPY"_s; - break; - } - } - - case 5: { - if (methodView == std::string_view("patch", 5)) { - methodString = "PATCH"_s; - break; - } - if (methodView == std::string_view("merge", 5)) { - methodString = "MERGE"_s; - break; - } - if (methodView == std::string_view("trace", 5)) { - methodString = "TRACE"_s; - break; - } - if (methodView == std::string_view("fetch", 5)) { - methodString = "FETCH"_s; - break; - } - if (methodView == std::string_view("purge", 5)) { - methodString = "PURGE"_s; - break; - } - - break; - } - - case 6: { - if (methodView == std::string_view("delete", 6)) { - methodString = "DELETE"_s; - break; - } - - break; - } - - case 7: { - if (methodView == std::string_view("connect", 7)) { - methodString = "CONNECT"_s; - break; - } - if (methodView == std::string_view("options", 7)) { - methodString = "OPTIONS"_s; - break; - } - - break; - } - } - - if (methodString.isNull()) { - methodString = String::fromUTF8ReplacingInvalidSequences({ reinterpret_cast(methodView.data()), methodView.length() }); - } - objectValue->put(objectValue, globalObject, builtinNames.methodPublicName(), jsString(vm, methodString), slot); - RETURN_IF_EXCEPTION(scope, {}); - } - - size_t size = 0; - for (auto it = request->begin(); it != request->end(); ++it) { - size++; - } - - JSC::JSObject* headersObject = JSC::constructEmptyObject(globalObject, prototype, std::min(size, static_cast(JSFinalObject::maxInlineCapacity))); - RETURN_IF_EXCEPTION(scope, {}); - JSC::JSArray* array = constructEmptyArray(globalObject, nullptr, size * 2); - RETURN_IF_EXCEPTION(scope, {}); - JSC::JSArray* setCookiesHeaderArray = nullptr; - JSC::JSString* setCookiesHeaderString = nullptr; - - unsigned i = 0; - - for (auto it = request->begin(); it != request->end(); ++it) { - auto pair = *it; - StringView nameView = StringView(std::span { reinterpret_cast(pair.first.data()), pair.first.length() }); - std::span data; - auto value = String::tryCreateUninitialized(pair.second.length(), data); - if (value.isNull()) [[unlikely]] { - throwOutOfMemoryError(globalObject, scope); - return {}; - } - if (pair.second.length() > 0) - memcpy(data.data(), pair.second.data(), pair.second.length()); - - HTTPHeaderName name; - WTF::String nameString; - WTF::String lowercasedNameString; - bool knownHeader = WebCore::findHTTPHeaderName(nameView, name); - bool isSetCookie = false; - - if (knownHeader) { - lowercasedNameString = WTF::httpHeaderNameStringImpl(name); - // rawHeaders keeps the wire casing; reuse the canonical string - // only when the client already sent it lowercased. - nameString = nameView == StringView(lowercasedNameString) ? lowercasedNameString : nameView.toString(); - isSetCookie = name == WebCore::HTTPHeaderName::SetCookie; - } else { - nameString = nameView.toString(); - lowercasedNameString = nameString.convertToASCIILowercase(); - } - - JSString* jsValue = jsString(vm, value); - - if (isSetCookie) { - if (!setCookiesHeaderArray) { - setCookiesHeaderArray = constructEmptyArray(globalObject, nullptr); - RETURN_IF_EXCEPTION(scope, {}); - setCookiesHeaderString = jsString(vm, nameString); - headersObject->putDirect(vm, Identifier::fromString(vm, lowercasedNameString), setCookiesHeaderArray, 0); - RETURN_IF_EXCEPTION(scope, {}); - } - array->putDirectIndex(globalObject, i++, setCookiesHeaderString); - array->putDirectIndex(globalObject, i++, jsValue); - setCookiesHeaderArray->push(globalObject, jsValue); - RETURN_IF_EXCEPTION(scope, {}); - - } else { - Identifier nameIdentifier = Identifier::fromString(vm, lowercasedNameString); - if (std::optional index = parseIndex(nameIdentifier)) [[unlikely]] { - // Index-shaped names store through the indexed path. A numeric - // name is never a known header name, so duplicates comma-join. - JSValue existing = headersObject->getDirectIndex(globalObject, index.value()); - RETURN_IF_EXCEPTION(scope, {}); - JSValue valueToPut = jsValue; - if (existing) [[unlikely]] { - valueToPut = joinedRequestHeaderValue(globalObject, vm, asString(existing), RequestHeaderKind::Joinable, value); - RETURN_IF_EXCEPTION(scope, {}); - } - headersObject->putDirectIndex(globalObject, index.value(), valueToPut); - } else { - // Locate the property the same way putDirect's replace path - // would, before storing anything: on a duplicate the first - // value is still intact at the returned offset. - PropertyOffset offset = headersObject->getDirectOffset(vm, nameIdentifier); - if (offset != invalidOffset) [[unlikely]] { - // Duplicate header name, Node's rules: singleton headers - // keep the first value (nothing to store), Cookie joins - // with "; ", everything else joins with ", ". - RequestHeaderKind kind = knownHeader ? requestHeaderKind(name) : requestHeaderKind(lowercasedNameString); - if (kind != RequestHeaderKind::Singleton) { - JSString* merged = joinedRequestHeaderValue(globalObject, vm, asString(headersObject->getDirect(offset)), kind, value); - RETURN_IF_EXCEPTION(scope, {}); - headersObject->structure()->didReplaceProperty(offset); - headersObject->putDirectOffset(vm, offset, merged); - } - } else { - headersObject->putDirect(vm, nameIdentifier, jsValue, 0); - } - } - RETURN_IF_EXCEPTION(scope, {}); - array->putDirectIndex(globalObject, i++, jsString(vm, nameString)); - array->putDirectIndex(globalObject, i++, jsValue); - RETURN_IF_EXCEPTION(scope, {}); - } - } - - tuple->putInternalField(vm, 0, headersObject); - tuple->putInternalField(vm, 1, array); - - return JSValue::encode(tuple); -} - template static void assignOnNodeJSCompat(uWS::TemplatedApp* app) { @@ -1142,112 +801,6 @@ extern "C" EncodedJSValue NodeHTTPServer__onRequest_https( nodeHttpResponsePtr); } -JSC_DEFINE_HOST_FUNCTION(jsHTTPAssignHeaders, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - auto& vm = JSC::getVM(globalObject); - auto scope = DECLARE_THROW_SCOPE(vm); - - // This is an internal binding. - JSValue requestValue = callFrame->uncheckedArgument(0); - JSObject* objectValue = callFrame->uncheckedArgument(1).getObject(); - JSC::InternalFieldTuple* tuple = uncheckedDowncast(callFrame->uncheckedArgument(2)); - ASSERT(callFrame->argumentCount() == 3); - - JSValue headersValue = JSValue(); - JSValue urlValue = JSValue(); - if (auto* jsRequest = dynamicDowncast(requestValue)) { - if (uWS::HttpRequest* request = Request__getUWSRequest(jsRequest->wrapped())) { - return assignHeadersFromUWebSockets(request, globalObject->objectPrototype(), objectValue, tuple, globalObject, vm); - } - - if (jsRequest->m_headers) { - headersValue = jsRequest->m_headers.get(); - } - - if (jsRequest->m_url) { - urlValue = jsRequest->m_url.get(); - } - } - - if (requestValue.isObject()) { - if (!headersValue) { - headersValue = requestValue.getObject()->getIfPropertyExists(globalObject, WebCore::builtinNames(vm).headersPublicName()); - RETURN_IF_EXCEPTION(scope, {}); - } - - if (!urlValue) { - urlValue = requestValue.getObject()->getIfPropertyExists(globalObject, WebCore::builtinNames(vm).urlPublicName()); - RETURN_IF_EXCEPTION(scope, {}); - } - - if (headersValue) { - if (auto* headers = dynamicDowncast(headersValue)) { - FetchHeaders& impl = headers->wrapped(); - if (urlValue) { - if (urlValue.isString()) { - String url = urlValue.toWTFString(globalObject); - RETURN_IF_EXCEPTION(scope, {}); - if (url.startsWith("https://"_s) || url.startsWith("http://"_s) || url.startsWith("file://"_s)) { - WTF::URL urlObj = WTF::URL({}, url); - if (urlObj.isValid()) { - urlValue = jsString(vm, makeString(urlObj.path(), urlObj.query().isEmpty() ? emptyString() : urlObj.queryWithLeadingQuestionMark())); - } - } - } else { - urlValue = jsEmptyString(vm); - } - PutPropertySlot slot(objectValue, false); - objectValue->put(objectValue, globalObject, WebCore::builtinNames(vm).urlPublicName(), urlValue, slot); - RETURN_IF_EXCEPTION(scope, {}); - } - - RELEASE_AND_RETURN(scope, assignHeadersFromFetchHeaders(impl, globalObject->objectPrototype(), objectValue, tuple, globalObject, vm)); - } - } - } - - return JSValue::encode(jsNull()); -} - -JSC_DEFINE_HOST_FUNCTION(jsHTTPAssignEventCallback, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - auto& vm = JSC::getVM(globalObject); - auto scope = DECLARE_THROW_SCOPE(vm); - - // This is an internal binding. - JSValue requestValue = callFrame->uncheckedArgument(0); - JSValue callback = callFrame->uncheckedArgument(1); - - ASSERT(callFrame->argumentCount() == 2); - - if (auto* jsRequest = dynamicDowncast(requestValue)) { - Request__setInternalEventCallback(jsRequest->wrapped(), JSValue::encode(callback), globalObject); - } - - return JSValue::encode(jsNull()); -} - -JSC_DEFINE_HOST_FUNCTION(jsHTTPSetTimeout, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - auto& vm = JSC::getVM(globalObject); - auto scope = DECLARE_THROW_SCOPE(vm); - - // This is an internal binding. - JSValue requestValue = callFrame->uncheckedArgument(0); - JSValue seconds = callFrame->uncheckedArgument(1); - - ASSERT(callFrame->argumentCount() == 2); - - if (auto* jsRequest = dynamicDowncast(requestValue)) { - Request__setTimeout(jsRequest->wrapped(), JSValue::encode(seconds), globalObject); - } - - if (auto* nodeHttpResponse = dynamicDowncast(requestValue)) { - NodeHTTPResponse__setTimeout(nodeHttpResponse->wrapped(), JSValue::encode(seconds), globalObject); - } - - return JSValue::encode(jsUndefined()); -} JSC_DEFINE_HOST_FUNCTION(jsHTTPSetServerIdleTimeout, (JSGlobalObject * globalObject, CallFrame* callFrame)) { auto& vm = JSC::getVM(globalObject); @@ -1325,154 +878,10 @@ JSC_DEFINE_HOST_FUNCTION(jsHTTPSetAppFlags, (JSGlobalObject * globalObject, Call return JSValue::encode(jsUndefined()); } -JSC_DEFINE_HOST_FUNCTION(jsHTTPGetHeader, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - auto& vm = JSC::getVM(globalObject); - auto scope = DECLARE_THROW_SCOPE(vm); - - JSValue headersValue = callFrame->argument(0); - - if (auto* headers = dynamicDowncast(headersValue)) { - JSValue nameValue = callFrame->argument(1); - if (nameValue.isString()) { - FetchHeaders* impl = &headers->wrapped(); - JSString* nameString = nameValue.toString(globalObject); - RETURN_IF_EXCEPTION(scope, {}); - const auto name = nameString->view(globalObject); - RETURN_IF_EXCEPTION(scope, {}); - - // Resolve the name to its known header enum once. A known name then - // takes the HTTPHeaderName fast path (HTTPHeaderMap::get) and skips - // the isValidHTTPToken scan plus the second findHTTPHeaderName - // lookup that FetchHeaders::get(StringView) would otherwise perform. - WebCore::HTTPHeaderName headerName; - if (WebCore::findHTTPHeaderName(name, headerName)) { - if (headerName == WebCore::HTTPHeaderName::SetCookie) { - // Node's getHeader returns undefined for an absent header; - // Headers.getSetCookie()'s empty array is only correct once - // at least one Set-Cookie value exists. - if (impl->getSetCookieHeaders().isEmpty()) { - return JSValue::encode(jsUndefined()); - } - RELEASE_AND_RETURN(scope, fetchHeadersGetSetCookie(globalObject, vm, impl)); - } - - String value = impl->fastGet(headerName); - if (value.isEmpty()) { - return JSValue::encode(jsUndefined()); - } - - return JSC::JSValue::encode(jsString(vm, value)); - } - - WebCore::ExceptionOr res = impl->get(name); - if (res.hasException()) { - WebCore::propagateException(globalObject, scope, res.releaseException()); - RELEASE_AND_RETURN(scope, {}); - } - - String value = res.returnValue(); - if (value.isEmpty()) { - return JSValue::encode(jsUndefined()); - } - - return JSC::JSValue::encode(jsString(vm, value)); - } - } - - return JSValue::encode(jsUndefined()); -} - -JSC_DEFINE_HOST_FUNCTION(jsHTTPSetHeader, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - auto& vm = JSC::getVM(globalObject); - auto scope = DECLARE_THROW_SCOPE(vm); - - JSValue headersValue = callFrame->argument(0); - JSValue nameValue = callFrame->argument(1); - JSValue valueValue = callFrame->argument(2); - - if (auto* headers = dynamicDowncast(headersValue)) { - - if (nameValue.isString()) { - String name = nameValue.toWTFString(globalObject); - RETURN_IF_EXCEPTION(scope, {}); - - FetchHeaders* impl = &headers->wrapped(); - - if (valueValue.isUndefined()) - return JSValue::encode(jsUndefined()); - - // Resolve the header name to its known enum once. Known names then - // take the HTTPHeaderName overload of FetchHeaders::set, which skips - // the isValidHTTPToken scan (an enum name is a valid token by - // construction) and the second findHTTPHeaderName lookup that - // HTTPHeaderMap::set(const String&, ...) would otherwise perform. - WebCore::HTTPHeaderName headerName; - const bool isKnownHeaderName = WebCore::findHTTPHeaderName(StringView(name), headerName); - const auto setHeader = [&](const String& value) { - if (isKnownHeaderName) - impl->set(headerName, value); - else - impl->set(name, value); - }; - - // Note: isArray() accepts Proxy->Array, but jsDynamicCast returns null for Proxy. - // Fall through to the single-value path in that case. - if (auto* array = dynamicDowncast(valueValue)) { - unsigned length = array->length(); - if (length > 0) { - JSValue item = array->getIndex(globalObject, 0); - RETURN_IF_EXCEPTION(scope, {}); - auto value = item.toWTFString(globalObject); - RETURN_IF_EXCEPTION(scope, {}); - setHeader(value); - RETURN_IF_EXCEPTION(scope, {}); - } - for (unsigned i = 1; i < length; ++i) { - JSValue value = array->getIndex(globalObject, i); - RETURN_IF_EXCEPTION(scope, {}); - auto string = value.toWTFString(globalObject); - RETURN_IF_EXCEPTION(scope, {}); - impl->append(name, string); - RETURN_IF_EXCEPTION(scope, {}); - } - RELEASE_AND_RETURN(scope, JSValue::encode(jsUndefined())); - return JSValue::encode(jsUndefined()); - } - - auto value = valueValue.toWTFString(globalObject); - RETURN_IF_EXCEPTION(scope, {}); - setHeader(value); - RETURN_IF_EXCEPTION(scope, {}); - return JSValue::encode(jsUndefined()); - } - } - - return JSValue::encode(jsUndefined()); -} - JSValue createNodeHTTPInternalBinding(Zig::GlobalObject* globalObject) { auto* obj = constructEmptyObject(globalObject); VM& vm = globalObject->vm(); - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "setHeader"_s)), - JSC::JSFunction::create(vm, globalObject, 3, "setHeader"_s, jsHTTPSetHeader, ImplementationVisibility::Public), 0); - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "getHeader"_s)), - JSC::JSFunction::create(vm, globalObject, 2, "getHeader"_s, jsHTTPGetHeader, ImplementationVisibility::Public), 0); - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "assignHeaders"_s)), - JSC::JSFunction::create(vm, globalObject, 2, "assignHeaders"_s, jsHTTPAssignHeaders, ImplementationVisibility::Public), 0); - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "assignEventCallback"_s)), - JSC::JSFunction::create(vm, globalObject, 2, "assignEventCallback"_s, jsHTTPAssignEventCallback, ImplementationVisibility::Public), 0); - - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "setRequestTimeout"_s)), - JSC::JSFunction::create(vm, globalObject, 2, "setRequestTimeout"_s, jsHTTPSetTimeout, ImplementationVisibility::Public), 0); - obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "setServerIdleTimeout"_s)), JSC::JSFunction::create(vm, globalObject, 2, "setServerIdleTimeout"_s, jsHTTPSetServerIdleTimeout, ImplementationVisibility::Public), 0); @@ -1483,28 +892,6 @@ JSValue createNodeHTTPInternalBinding(Zig::GlobalObject* globalObject) obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "setServerAppFlags"_s)), JSC::JSFunction::create(vm, globalObject, 5, "setServerAppFlags"_s, jsHTTPSetAppFlags, ImplementationVisibility::Public), 0); - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "Response"_s)), - globalObject->JSResponseConstructor(), 0); - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "Request"_s)), - globalObject->JSRequestConstructor(), 0); - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "Blob"_s)), - globalObject->JSBlobConstructor(), 0); - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "Headers"_s)), - WebCore::JSFetchHeaders::getConstructor(vm, globalObject), 0); - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "headersTuple"_s)), - JSC::InternalFieldTuple::create(vm, globalObject->m_internalFieldTupleStructure.get()), 0); - obj->putDirectNativeFunction( - vm, globalObject, JSC::PropertyName(JSC::Identifier::fromString(vm, "webRequestOrResponseHasBodyValue"_s)), - 1, jsFunctionRequestOrResponseHasBodyValue, ImplementationVisibility::Public, Intrinsic::NoIntrinsic, 0); - - obj->putDirectNativeFunction( - vm, globalObject, JSC::PropertyName(JSC::Identifier::fromString(vm, "getCompleteWebRequestOrResponseBodyValueAsArrayBuffer"_s)), - 1, jsFunctionGetCompleteRequestOrResponseBodyValueAsArrayBuffer, ImplementationVisibility::Public, Intrinsic::NoIntrinsic, 0); obj->putDirectNativeFunction( vm, globalObject, JSC::PropertyName(JSC::Identifier::fromString(vm, "drainMicrotasks"_s)), 0, Bun__drainMicrotasksFromJS, ImplementationVisibility::Public, Intrinsic::NoIntrinsic, 0); diff --git a/src/jsc/bindings/NodeHTTP.h b/src/jsc/bindings/NodeHTTP.h index 8035cc216c84..b5f82d099f20 100644 --- a/src/jsc/bindings/NodeHTTP.h +++ b/src/jsc/bindings/NodeHTTP.h @@ -2,10 +2,6 @@ namespace Bun { -JSC_DECLARE_HOST_FUNCTION(jsHTTPAssignHeaders); -JSC_DECLARE_HOST_FUNCTION(jsHTTPGetHeader); -JSC_DECLARE_HOST_FUNCTION(jsHTTPSetHeader); - JSC::Structure* createNodeHTTPServerSocketStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject); JSC::JSValue createNodeHTTPInternalBinding(Zig::GlobalObject*); diff --git a/src/jsc/bindings/node/crypto/node_crypto_binding.cpp b/src/jsc/bindings/node/crypto/node_crypto_binding.cpp index e8c2d019dad4..b8117600afdb 100644 --- a/src/jsc/bindings/node/crypto/node_crypto_binding.cpp +++ b/src/jsc/bindings/node/crypto/node_crypto_binding.cpp @@ -4,17 +4,6 @@ #include "JavaScriptCore/JSCJSValue.h" #include "JavaScriptCore/JSCast.h" #include "ZigGlobalObject.h" -#include "webcrypto/JSCryptoKey.h" -#include "webcrypto/JSSubtleCrypto.h" -#include "webcrypto/CryptoKeyOKP.h" -#include "webcrypto/CryptoKeyEC.h" -#include "webcrypto/CryptoKeyRSA.h" -#include "webcrypto/CryptoKeyAES.h" -#include "webcrypto/CryptoKeyHMAC.h" -#include "webcrypto/CryptoKeyRaw.h" -#include "webcrypto/CryptoKeyUsage.h" -#include "webcrypto/JsonWebKey.h" -#include "webcrypto/JSJsonWebKey.h" #include "JavaScriptCore/JSObject.h" #include "JavaScriptCore/ObjectConstructor.h" #include "headers-handwritten.h" @@ -24,16 +13,6 @@ #include #include #include "JSBuffer.h" -#include "CryptoAlgorithmHMAC.h" -#include "CryptoAlgorithmEd25519.h" -#include "CryptoAlgorithmRSA_OAEP.h" -#include "CryptoAlgorithmRSA_PSS.h" -#include "CryptoAlgorithmRSASSA_PKCS1_v1_5.h" -#include "CryptoAlgorithmECDSA.h" -#include "CryptoAlgorithmEcdsaParams.h" -#include "CryptoAlgorithmRsaOaepParams.h" -#include "CryptoAlgorithmRsaPssParams.h" -#include "CryptoAlgorithmRegistry.h" #include "wtf/ForbidHeapAllocation.h" #include "wtf/Noncopyable.h" #include "ncrypto.h" diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithm.h b/src/jsc/bindings/webcrypto/CryptoAlgorithm.h index 8a3130e16fd3..b8334c71eb04 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithm.h +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithm.h @@ -60,7 +60,6 @@ class CryptoAlgorithm : public ThreadSafeRefCounted { using KeyOrKeyPairCallback = Function; // FIXME: https://bugs.webkit.org/show_bug.cgi?id=169395 using VectorCallback = Function&)>; - using VoidCallback = Function; using ExceptionCallback = Function; using KeyDataCallback = Function; // sharedKey, ciphertext diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmECDSAOpenSSL.cpp b/src/jsc/bindings/webcrypto/CryptoAlgorithmECDSAOpenSSL.cpp index 28acc21e5740..76cedbd0b409 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmECDSAOpenSSL.cpp +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithmECDSAOpenSSL.cpp @@ -56,80 +56,45 @@ ExceptionOr> CryptoAlgorithmECDSA::platformSign(const CryptoAlgo if (!sig) return Exception { OperationError }; - if (parameters.encoding == CryptoAlgorithmECDSAEncoding::DER) { - int derSigLength = i2d_ECDSA_SIG(sig.get(), nullptr); - if (derSigLength <= 0) - return Exception { OperationError }; - Vector signature(derSigLength); - uint8_t* p = signature.begin(); - if (i2d_ECDSA_SIG(sig.get(), &p) != derSigLength) - return Exception { OperationError }; - return signature; - } else { - - const BIGNUM* r; - const BIGNUM* s; - ECDSA_SIG_get0(sig.get(), &r, &s); - - // Concatenate r and s, expanding r and s to keySizeInBytes. - Vector signature = convertToBytesExpand(r, keySizeInBytes); - signature.appendVector(convertToBytesExpand(s, keySizeInBytes)); - return signature; - } + const BIGNUM* r; + const BIGNUM* s; + ECDSA_SIG_get0(sig.get(), &r, &s); + + // Concatenate r and s, expanding r and s to keySizeInBytes. + Vector signature = convertToBytesExpand(r, keySizeInBytes); + signature.appendVector(convertToBytesExpand(s, keySizeInBytes)); + return signature; } ExceptionOr CryptoAlgorithmECDSA::platformVerify(const CryptoAlgorithmEcdsaParams& parameters, const CryptoKeyEC& key, const Vector& signature, const Vector& data) { - if (parameters.encoding == CryptoAlgorithmECDSAEncoding::DER) { - const uint8_t* p = signature.begin(); - - auto sig = ECDSASigPtr(d2i_ECDSA_SIG(nullptr, &p, signature.size())); - if (!sig) - return Exception { OperationError }; - - const EVP_MD* md = digestAlgorithm(parameters.hashIdentifier); - if (!md) - return Exception { NotSupportedError }; - - std::optional> digest = calculateDigest(md, data); - if (!digest) - return Exception { OperationError }; - - EC_KEY* ecKey = EVP_PKEY_get0_EC_KEY(key.platformKey()); - if (!ecKey) - return Exception { OperationError }; - - int ret = ECDSA_do_verify(digest->begin(), digest->size(), sig.get(), ecKey); - return ret == 1; - } else { - size_t keySizeInBytes = (key.keySizeInBits() + 7) / 8; + size_t keySizeInBytes = (key.keySizeInBits() + 7) / 8; - // Bail if the signature size isn't double the key size (i.e. concatenated r and s components). - if (signature.size() != keySizeInBytes * 2) - return false; + // Bail if the signature size isn't double the key size (i.e. concatenated r and s components). + if (signature.size() != keySizeInBytes * 2) + return false; - auto sig = ECDSASigPtr(ECDSA_SIG_new()); - auto r = BN_bin2bn(signature.begin(), keySizeInBytes, nullptr); - auto s = BN_bin2bn(signature.begin() + keySizeInBytes, keySizeInBytes, nullptr); + auto sig = ECDSASigPtr(ECDSA_SIG_new()); + auto r = BN_bin2bn(signature.begin(), keySizeInBytes, nullptr); + auto s = BN_bin2bn(signature.begin() + keySizeInBytes, keySizeInBytes, nullptr); - if (!ECDSA_SIG_set0(sig.get(), r, s)) - return Exception { OperationError }; + if (!ECDSA_SIG_set0(sig.get(), r, s)) + return Exception { OperationError }; - const EVP_MD* md = digestAlgorithm(parameters.hashIdentifier); - if (!md) - return Exception { NotSupportedError }; + const EVP_MD* md = digestAlgorithm(parameters.hashIdentifier); + if (!md) + return Exception { NotSupportedError }; - std::optional> digest = calculateDigest(md, data); - if (!digest) - return Exception { OperationError }; + std::optional> digest = calculateDigest(md, data); + if (!digest) + return Exception { OperationError }; - EC_KEY* ecKey = EVP_PKEY_get0_EC_KEY(key.platformKey()); - if (!ecKey) - return Exception { OperationError }; + EC_KEY* ecKey = EVP_PKEY_get0_EC_KEY(key.platformKey()); + if (!ecKey) + return Exception { OperationError }; - int ret = ECDSA_do_verify(digest->begin(), digest->size(), sig.get(), ecKey); - return ret == 1; - } + int ret = ECDSA_do_verify(digest->begin(), digest->size(), sig.get(), ecKey); + return ret == 1; } } // namespace WebCore diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmEcdsaParams.h b/src/jsc/bindings/webcrypto/CryptoAlgorithmEcdsaParams.h index 18155fdb2d71..b7bee180df56 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmEcdsaParams.h +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithmEcdsaParams.h @@ -34,17 +34,11 @@ namespace WebCore { -enum CryptoAlgorithmECDSAEncoding { - IeeeP1363, - DER, -}; class CryptoAlgorithmEcdsaParams final : public CryptoAlgorithmParameters { public: // FIXME: Consider merging hash and hashIdentifier. std::variant, String> hash; CryptoAlgorithmIdentifier hashIdentifier; - // WebCrypto default is IeeeP1363. - CryptoAlgorithmECDSAEncoding encoding { CryptoAlgorithmECDSAEncoding::IeeeP1363 }; Class parametersClass() const final { return Class::EcdsaParams; } @@ -53,7 +47,6 @@ class CryptoAlgorithmEcdsaParams final : public CryptoAlgorithmParameters { CryptoAlgorithmEcdsaParams result; result.identifier = identifier; result.hashIdentifier = hashIdentifier; - result.encoding = encoding; return result; } }; diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmMlDsaParams.h b/src/jsc/bindings/webcrypto/CryptoAlgorithmMlDsaParams.h index 11b14cd081b3..8c840e283b9f 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmMlDsaParams.h +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithmMlDsaParams.h @@ -54,15 +54,6 @@ class CryptoAlgorithmMlDsaParams final : public CryptoAlgorithmParameters { return m_contextVector; } - CryptoAlgorithmMlDsaParams isolatedCopy() const - { - CryptoAlgorithmMlDsaParams result; - result.identifier = identifier; - result.m_contextVector = contextVector(); - - return result; - } - private: mutable Vector m_contextVector; }; diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5.cpp b/src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5.cpp index 13a66470b072..b69f6cceb374 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5.cpp +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5.cpp @@ -28,15 +28,8 @@ #if ENABLE(WEB_CRYPTO) -#include "CryptoAlgorithmRsaKeyGenParams.h" -#include "CryptoKeyPair.h" -#include "CryptoKeyRSA.h" -#include - namespace WebCore { -static constexpr auto ALG = "RSA1_5"_s; - Ref CryptoAlgorithmRSAES_PKCS1_v1_5::create() { return adoptRef(*new CryptoAlgorithmRSAES_PKCS1_v1_5); @@ -47,148 +40,6 @@ CryptoAlgorithmIdentifier CryptoAlgorithmRSAES_PKCS1_v1_5::identifier() const return s_identifier; } -void CryptoAlgorithmRSAES_PKCS1_v1_5::encrypt(const CryptoAlgorithmParameters&, Ref&& key, Vector&& plainText, VectorCallback&& callback, ExceptionCallback&& exceptionCallback, ScriptExecutionContext& context, WorkQueue& workQueue) -{ - if (key->type() != CryptoKeyType::Public) { - exceptionCallback(InvalidAccessError, ""_s); - return; - } - - dispatchOperationInWorkQueue(workQueue, context, WTF::move(callback), WTF::move(exceptionCallback), - [key = WTF::move(key), plainText = WTF::move(plainText)] { - return platformEncrypt(downcast(key.get()), plainText); - }); -} - -void CryptoAlgorithmRSAES_PKCS1_v1_5::decrypt(const CryptoAlgorithmParameters&, Ref&& key, Vector&& cipherText, VectorCallback&& callback, ExceptionCallback&& exceptionCallback, ScriptExecutionContext& context, WorkQueue& workQueue) -{ - if (key->type() != CryptoKeyType::Private) { - exceptionCallback(InvalidAccessError, ""_s); - return; - } - - dispatchOperationInWorkQueue(workQueue, context, WTF::move(callback), WTF::move(exceptionCallback), - [key = WTF::move(key), cipherText = WTF::move(cipherText)] { - return platformDecrypt(downcast(key.get()), cipherText); - }); -} - -void CryptoAlgorithmRSAES_PKCS1_v1_5::generateKey(const CryptoAlgorithmParameters& parameters, bool extractable, CryptoKeyUsageBitmap usages, KeyOrKeyPairCallback&& callback, ExceptionCallback&& exceptionCallback, ScriptExecutionContext& context) -{ - const auto& rsaParameters = downcast(parameters); - - if (usages & (CryptoKeyUsageSign | CryptoKeyUsageVerify | CryptoKeyUsageDeriveKey | CryptoKeyUsageDeriveBits | CryptoKeyUsageWrapKey | CryptoKeyUsageUnwrapKey | CryptoKeyUsageKemMask)) { - exceptionCallback(SyntaxError, "Unsupported key usage for a RSA key"_s); - return; - } - - auto keyPairCallback = [capturedCallback = WTF::move(callback)](CryptoKeyPair&& pair) { - pair.publicKey->setUsagesBitmap(pair.publicKey->usagesBitmap() & CryptoKeyUsageEncrypt); - pair.privateKey->setUsagesBitmap(pair.privateKey->usagesBitmap() & CryptoKeyUsageDecrypt); - capturedCallback(WTF::move(pair)); - }; - auto failureCallback = [capturedCallback = WTF::move(exceptionCallback)]() { - capturedCallback(OperationError, ""_s); - }; - // Notice: CryptoAlgorithmIdentifier::SHA_1 is just a placeholder. It should not have any effect. - CryptoKeyRSA::generatePair(CryptoAlgorithmIdentifier::RSAES_PKCS1_v1_5, CryptoAlgorithmIdentifier::SHA_1, false, rsaParameters.modulusLength, rsaParameters.publicExponentVector(), extractable, usages, WTF::move(keyPairCallback), WTF::move(failureCallback), &context); -} - -void CryptoAlgorithmRSAES_PKCS1_v1_5::importKey(CryptoKeyFormat format, KeyData&& data, const CryptoAlgorithmParameters& parameters, bool extractable, CryptoKeyUsageBitmap usages, KeyCallback&& callback, ExceptionCallback&& exceptionCallback) -{ - RefPtr result; - bool keyTypeMismatch = false; - switch (format) { - case CryptoKeyFormat::Jwk: { - JsonWebKey key = WTF::move(std::get(data)); - if (usages && ((!key.d.isNull() && (usages ^ CryptoKeyUsageDecrypt)) || (key.d.isNull() && (usages ^ CryptoKeyUsageEncrypt)))) { - exceptionCallback(SyntaxError, "Unsupported key usage for an RSAES-PKCS1-v1_5 key"_s); - return; - } - if (usages && !key.use.isNull() && key.use != "enc"_s) { - exceptionCallback(DataError, "Invalid JWK \"use\" Parameter"_s); - return; - } - if (!key.alg.isNull() && key.alg != ALG) { - exceptionCallback(DataError, "JWK \"alg\" does not match the requested algorithm"_s); - return; - } - result = CryptoKeyRSA::importJwk(parameters.identifier, std::nullopt, WTF::move(key), extractable, usages); - break; - } - case CryptoKeyFormat::Spki: { - if (usages && (usages ^ CryptoKeyUsageEncrypt)) { - exceptionCallback(SyntaxError, "Unsupported key usage for an RSAES-PKCS1-v1_5 key"_s); - return; - } - result = CryptoKeyRSA::importSpki(parameters.identifier, std::nullopt, WTF::move(std::get>(data)), extractable, usages, &keyTypeMismatch); - break; - } - case CryptoKeyFormat::Pkcs8: { - if (usages && (usages ^ CryptoKeyUsageDecrypt)) { - exceptionCallback(SyntaxError, "Unsupported key usage for an RSAES-PKCS1-v1_5 key"_s); - return; - } - result = CryptoKeyRSA::importPkcs8(parameters.identifier, std::nullopt, WTF::move(std::get>(data)), extractable, usages, &keyTypeMismatch); - break; - } - default: - // Only raw reaches here: raw-secret/raw-public alias to raw and - // raw-seed is rejected by aliasImportKeyFormat before dispatch. - exceptionCallback(NotSupportedError, "Unable to import RSAES-PKCS1-v1_5 using raw format"_s); - return; - } - if (!result) { - exceptionCallback(DataError, keyTypeMismatch ? "Invalid key type"_s : "Invalid keyData"_s); - return; - } - - callback(*result); -} - -void CryptoAlgorithmRSAES_PKCS1_v1_5::exportKey(CryptoKeyFormat format, Ref&& key, KeyDataCallback&& callback, ExceptionCallback&& exceptionCallback) -{ - const auto& rsaKey = downcast(key.get()); - - if (!rsaKey.keySizeInBits()) { - exceptionCallback(OperationError, ""_s); - return; - } - - KeyData result; - switch (format) { - case CryptoKeyFormat::Jwk: { - JsonWebKey jwk = rsaKey.exportJwk(); - jwk.alg = String(ALG); - result = WTF::move(jwk); - break; - } - case CryptoKeyFormat::Spki: { - auto spki = rsaKey.exportSpki(); - if (spki.hasException()) { - exceptionCallback(spki.releaseException().code(), ""_s); - return; - } - result = spki.releaseReturnValue(); - break; - } - case CryptoKeyFormat::Pkcs8: { - auto pkcs8 = rsaKey.exportPkcs8(); - if (pkcs8.hasException()) { - exceptionCallback(pkcs8.releaseException().code(), ""_s); - return; - } - result = pkcs8.releaseReturnValue(); - break; - } - default: - exceptionCallback(NotSupportedError, ""_s); - return; - } - - callback(format, WTF::move(result)); -} - } #endif // ENABLE(WEB_CRYPTO) diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5.h b/src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5.h index d21e6c1ee286..de7637f244a3 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5.h +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5.h @@ -31,8 +31,8 @@ namespace WebCore { -class CryptoKeyRSA; - +// Registered so the algorithm name resolves; SubtleCrypto rejects every RSAES +// operation as deprecated while normalizing parameters, so nothing else is needed. class CryptoAlgorithmRSAES_PKCS1_v1_5 final : public CryptoAlgorithm { public: static constexpr ASCIILiteral s_name = "RSAES-PKCS1-v1_5"_s; @@ -42,15 +42,6 @@ class CryptoAlgorithmRSAES_PKCS1_v1_5 final : public CryptoAlgorithm { private: CryptoAlgorithmRSAES_PKCS1_v1_5() = default; CryptoAlgorithmIdentifier identifier() const final; - - void encrypt(const CryptoAlgorithmParameters&, Ref&&, Vector&&, VectorCallback&&, ExceptionCallback&&, ScriptExecutionContext&, WorkQueue&) final; - void decrypt(const CryptoAlgorithmParameters&, Ref&&, Vector&&, VectorCallback&&, ExceptionCallback&&, ScriptExecutionContext&, WorkQueue&) final; - void generateKey(const CryptoAlgorithmParameters&, bool extractable, CryptoKeyUsageBitmap, KeyOrKeyPairCallback&&, ExceptionCallback&&, ScriptExecutionContext&) final; - void importKey(CryptoKeyFormat, KeyData&&, const CryptoAlgorithmParameters&, bool extractable, CryptoKeyUsageBitmap, KeyCallback&&, ExceptionCallback&&) final; - void exportKey(CryptoKeyFormat, Ref&&, KeyDataCallback&&, ExceptionCallback&&) final; - - static ExceptionOr> platformEncrypt(const CryptoKeyRSA&, const Vector&); - static ExceptionOr> platformDecrypt(const CryptoKeyRSA&, const Vector&); }; } // namespace WebCore diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5OpenSSL.cpp b/src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5OpenSSL.cpp deleted file mode 100644 index 7f9f947a8bd9..000000000000 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSAES_PKCS1_v1_5OpenSSL.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2021 Sony Interactive Entertainment Inc. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "CryptoAlgorithmRSAES_PKCS1_v1_5.h" - -#if ENABLE(WEB_CRYPTO) - -#include "CryptoKeyRSA.h" -#include "OpenSSLUtilities.h" - -namespace WebCore { - -ExceptionOr> CryptoAlgorithmRSAES_PKCS1_v1_5::platformEncrypt(const CryptoKeyRSA& key, const Vector& plainText) -{ - auto ctx = EvpPKeyCtxPtr(EVP_PKEY_CTX_new(key.platformKey(), nullptr)); - if (!ctx) - return Exception { OperationError }; - - if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) - return Exception { OperationError }; - - if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING) <= 0) - return Exception { OperationError }; - - size_t cipherTextLen; - if (EVP_PKEY_encrypt(ctx.get(), nullptr, &cipherTextLen, plainText.begin(), plainText.size()) <= 0) - return Exception { OperationError }; - - Vector cipherText(cipherTextLen); - if (EVP_PKEY_encrypt(ctx.get(), cipherText.begin(), &cipherTextLen, plainText.begin(), plainText.size()) <= 0) - return Exception { OperationError }; - cipherText.shrink(cipherTextLen); - - return cipherText; -} - -ExceptionOr> CryptoAlgorithmRSAES_PKCS1_v1_5::platformDecrypt(const CryptoKeyRSA& key, const Vector& cipherText) -{ - auto ctx = EvpPKeyCtxPtr(EVP_PKEY_CTX_new(key.platformKey(), nullptr)); - if (!ctx) - return Exception { OperationError }; - - if (EVP_PKEY_decrypt_init(ctx.get()) <= 0) - return Exception { OperationError }; - - if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PADDING) <= 0) - return Exception { OperationError }; - - size_t plainTextLen; - if (EVP_PKEY_decrypt(ctx.get(), nullptr, &plainTextLen, cipherText.begin(), cipherText.size()) <= 0) - return Exception { OperationError }; - - Vector plainText(plainTextLen); - if (EVP_PKEY_decrypt(ctx.get(), plainText.begin(), &plainTextLen, cipherText.begin(), cipherText.size()) <= 0) - return Exception { OperationError }; - plainText.shrink(plainTextLen); - - return plainText; -} - -} // namespace WebCore - -#endif // ENABLE(WEB_CRYPTO) diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_OAEP.h b/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_OAEP.h index 582e3e44041a..dba7ea9d5d72 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_OAEP.h +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_OAEP.h @@ -40,9 +40,6 @@ class CryptoAlgorithmRSA_OAEP final : public CryptoAlgorithm { static constexpr CryptoAlgorithmIdentifier s_identifier = CryptoAlgorithmIdentifier::RSA_OAEP; static Ref create(); - static ExceptionOr> platformEncryptWithHash(const CryptoAlgorithmRsaOaepParams&, const CryptoKeyRSA&, const Vector&, CryptoAlgorithmIdentifier hashIdentifier); - static ExceptionOr> platformDecryptWithHash(const CryptoAlgorithmRsaOaepParams&, const CryptoKeyRSA&, const Vector&, CryptoAlgorithmIdentifier hashIdentifier); - private: CryptoAlgorithmRSA_OAEP() = default; CryptoAlgorithmIdentifier identifier() const final; diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_OAEPOpenSSL.cpp b/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_OAEPOpenSSL.cpp index d9ed3dc77b93..0402211e1b38 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_OAEPOpenSSL.cpp +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_OAEPOpenSSL.cpp @@ -37,11 +37,6 @@ namespace WebCore { ExceptionOr> CryptoAlgorithmRSA_OAEP::platformEncrypt(const CryptoAlgorithmRsaOaepParams& parameters, const CryptoKeyRSA& key, const Vector& plainText) -{ - return CryptoAlgorithmRSA_OAEP::platformEncryptWithHash(parameters, key, plainText, key.hashAlgorithmIdentifier()); -} - -ExceptionOr> CryptoAlgorithmRSA_OAEP::platformEncryptWithHash(const CryptoAlgorithmRsaOaepParams& parameters, const CryptoKeyRSA& key, const Vector& plainText, CryptoAlgorithmIdentifier hashIdentifier) { auto ctx = EvpPKeyCtxPtr(EVP_PKEY_CTX_new(key.platformKey(), nullptr)); if (!ctx) @@ -50,25 +45,18 @@ ExceptionOr> CryptoAlgorithmRSA_OAEP::platformEncryptWithHash(co if (EVP_PKEY_encrypt_init(ctx.get()) <= 0) return Exception { OperationError }; - auto padding = parameters.padding; - if (padding == 0) { - padding = RSA_PKCS1_OAEP_PADDING; - } - - if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0) + if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING) <= 0) return Exception { OperationError }; - if (padding == RSA_PKCS1_OAEP_PADDING) { - const EVP_MD* md = digestAlgorithm(hashIdentifier); - if (!md) - return Exception { NotSupportedError }; + const EVP_MD* md = digestAlgorithm(key.hashAlgorithmIdentifier()); + if (!md) + return Exception { NotSupportedError }; - if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md) <= 0) - return Exception { OperationError }; + if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md) <= 0) + return Exception { OperationError }; - if (EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), md) <= 0) - return Exception { OperationError }; - } + if (EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), md) <= 0) + return Exception { OperationError }; if (!parameters.labelVector().isEmpty()) { size_t labelSize = parameters.labelVector().size(); @@ -94,11 +82,6 @@ ExceptionOr> CryptoAlgorithmRSA_OAEP::platformEncryptWithHash(co } ExceptionOr> CryptoAlgorithmRSA_OAEP::platformDecrypt(const CryptoAlgorithmRsaOaepParams& parameters, const CryptoKeyRSA& key, const Vector& cipherText) -{ - return CryptoAlgorithmRSA_OAEP::platformDecryptWithHash(parameters, key, cipherText, key.hashAlgorithmIdentifier()); -} - -ExceptionOr> CryptoAlgorithmRSA_OAEP::platformDecryptWithHash(const CryptoAlgorithmRsaOaepParams& parameters, const CryptoKeyRSA& key, const Vector& cipherText, CryptoAlgorithmIdentifier hashIdentifier) { auto ctx = EvpPKeyCtxPtr(EVP_PKEY_CTX_new(key.platformKey(), nullptr)); if (!ctx) @@ -107,25 +90,18 @@ ExceptionOr> CryptoAlgorithmRSA_OAEP::platformDecryptWithHash(co if (EVP_PKEY_decrypt_init(ctx.get()) <= 0) return Exception { OperationError }; - auto padding = parameters.padding; - if (padding == 0) { - padding = RSA_PKCS1_OAEP_PADDING; - } - - if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0) + if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING) <= 0) return Exception { OperationError }; - if (padding == RSA_PKCS1_OAEP_PADDING) { - const EVP_MD* md = digestAlgorithm(hashIdentifier); - if (!md) - return Exception { NotSupportedError }; + const EVP_MD* md = digestAlgorithm(key.hashAlgorithmIdentifier()); + if (!md) + return Exception { NotSupportedError }; - if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md) <= 0) - return Exception { OperationError }; + if (EVP_PKEY_CTX_set_rsa_oaep_md(ctx.get(), md) <= 0) + return Exception { OperationError }; - if (EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), md) <= 0) - return Exception { OperationError }; - } + if (EVP_PKEY_CTX_set_rsa_mgf1_md(ctx.get(), md) <= 0) + return Exception { OperationError }; if (!parameters.labelVector().isEmpty()) { size_t labelSize = parameters.labelVector().size(); diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_PSSOpenSSL.cpp b/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_PSSOpenSSL.cpp index 4d85f5cec458..933217204086 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_PSSOpenSSL.cpp +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithmRSA_PSSOpenSSL.cpp @@ -36,10 +36,6 @@ namespace WebCore { static ExceptionOr> signWithMD(const CryptoAlgorithmRsaPssParams& parameters, const CryptoKeyRSA& key, const Vector& data, const EVP_MD* md) { - auto padding = parameters.padding; - if (padding == 0) { - padding = RSA_PKCS1_PSS_PADDING; - } std::optional> digest = calculateDigest(md, data); if (!digest) return Exception { OperationError }; @@ -51,13 +47,11 @@ static ExceptionOr> signWithMD(const CryptoAlgorithmRsaPssParams if (EVP_PKEY_sign_init(ctx.get()) <= 0) return Exception { OperationError }; - if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0) + if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PSS_PADDING) <= 0) return Exception { OperationError }; - if (padding == RSA_PKCS1_PSS_PADDING) { - if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx.get(), parameters.saltLength) <= 0) - return Exception { OperationError }; - } + if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx.get(), parameters.saltLength) <= 0) + return Exception { OperationError }; if (EVP_PKEY_CTX_set_signature_md(ctx.get(), md) <= 0) return Exception { OperationError }; @@ -92,11 +86,6 @@ ExceptionOr> CryptoAlgorithmRSA_PSS::platformSign(const CryptoAl static ExceptionOr verifyWithMD(const CryptoAlgorithmRsaPssParams& parameters, const CryptoKeyRSA& key, const Vector& signature, const Vector& data, const EVP_MD* md) { - auto padding = parameters.padding; - if (padding == 0) { - padding = RSA_PKCS1_PSS_PADDING; - } - auto ctx = EvpPKeyCtxPtr(EVP_PKEY_CTX_new(key.platformKey(), nullptr)); if (!ctx) return Exception { OperationError }; @@ -104,13 +93,11 @@ static ExceptionOr verifyWithMD(const CryptoAlgorithmRsaPssParams& paramet if (EVP_PKEY_verify_init(ctx.get()) <= 0) return Exception { OperationError }; - if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), padding) <= 0) + if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_PSS_PADDING) <= 0) return Exception { OperationError }; - if (padding == RSA_PKCS1_PSS_PADDING) { - if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx.get(), parameters.saltLength) <= 0) - return Exception { OperationError }; - } + if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx.get(), parameters.saltLength) <= 0) + return Exception { OperationError }; if (EVP_PKEY_CTX_set_signature_md(ctx.get(), md) <= 0) return Exception { OperationError }; diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmRsaOaepParams.h b/src/jsc/bindings/webcrypto/CryptoAlgorithmRsaOaepParams.h index 40874a066f4c..24e86e92cd53 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmRsaOaepParams.h +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithmRsaOaepParams.h @@ -37,7 +37,6 @@ class CryptoAlgorithmRsaOaepParams final : public CryptoAlgorithmParameters { public: // Use labelVector() instead of label. The label will be gone once labelVector() is called. mutable std::optional label; - size_t padding = 0; // 0 represents the default value of the API Class parametersClass() const final { return Class::RsaOaepParams; } diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmRsaPssParams.h b/src/jsc/bindings/webcrypto/CryptoAlgorithmRsaPssParams.h index a1cda97d5fd0..412f4ce0534e 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmRsaPssParams.h +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithmRsaPssParams.h @@ -34,7 +34,6 @@ namespace WebCore { class CryptoAlgorithmRsaPssParams final : public CryptoAlgorithmParameters { public: size_t saltLength; - size_t padding = 0; // 0 = default Class parametersClass() const final { return Class::RsaPssParams; } @@ -43,7 +42,6 @@ class CryptoAlgorithmRsaPssParams final : public CryptoAlgorithmParameters { CryptoAlgorithmRsaPssParams result; result.identifier = identifier; result.saltLength = saltLength; - result.padding = padding; return result; } diff --git a/src/jsc/bindings/webcrypto/CryptoAlgorithmX25519.cpp b/src/jsc/bindings/webcrypto/CryptoAlgorithmX25519.cpp index 38394a934aab..3242a5efa41e 100644 --- a/src/jsc/bindings/webcrypto/CryptoAlgorithmX25519.cpp +++ b/src/jsc/bindings/webcrypto/CryptoAlgorithmX25519.cpp @@ -25,7 +25,6 @@ #include "CryptoAlgorithmX25519Params.h" #include "CryptoKeyOKP.h" #include "ScriptExecutionContext.h" -#include "CryptoDigest.h" #include #include diff --git a/src/jsc/bindings/webcrypto/CryptoKey.cpp b/src/jsc/bindings/webcrypto/CryptoKey.cpp index ea48b80720b6..c453b50f0562 100644 --- a/src/jsc/bindings/webcrypto/CryptoKey.cpp +++ b/src/jsc/bindings/webcrypto/CryptoKey.cpp @@ -28,14 +28,8 @@ #if ENABLE(WEB_CRYPTO) -#include "CryptoAlgorithmRegistry.h" #include "WebCoreOpaqueRoot.h" -#include #include -#include -#include "CryptoKeyRSA.h" -#include "CryptoKeyEC.h" -#include "CryptoKeyHMAC.h" namespace WebCore { CryptoKey::CryptoKey(CryptoAlgorithmIdentifier algorithmIdentifier, Type type, bool extractable, CryptoKeyUsageBitmap usages) diff --git a/src/jsc/bindings/webcrypto/JSJsonWebKey.cpp b/src/jsc/bindings/webcrypto/JSJsonWebKey.cpp index da4f70e40cca..4a5ff2739661 100644 --- a/src/jsc/bindings/webcrypto/JSJsonWebKey.cpp +++ b/src/jsc/bindings/webcrypto/JSJsonWebKey.cpp @@ -274,7 +274,7 @@ template<> JsonWebKey convertDictionary(JSGlobalObject& lexicalGloba return result; } -JSC::JSObject* convertDictionaryToJS(JSC::JSGlobalObject& lexicalGlobalObject, JSDOMGlobalObject& globalObject, const JsonWebKey& dictionary, bool ignoreExtAndKeyOps) +JSC::JSObject* convertDictionaryToJS(JSC::JSGlobalObject& lexicalGlobalObject, JSDOMGlobalObject& globalObject, const JsonWebKey& dictionary) { auto& vm = JSC::getVM(&lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); @@ -311,7 +311,7 @@ JSC::JSObject* convertDictionaryToJS(JSC::JSGlobalObject& lexicalGlobalObject, J RETURN_IF_EXCEPTION(throwScope, {}); result->putDirect(vm, JSC::Identifier::fromString(vm, "e"_s), eValue); } - if (!ignoreExtAndKeyOps && !IDLBoolean::isNullValue(dictionary.ext)) { + if (!IDLBoolean::isNullValue(dictionary.ext)) { auto extValue = toJS(lexicalGlobalObject, throwScope, IDLBoolean::extractValueFromNullable(dictionary.ext)); RETURN_IF_EXCEPTION(throwScope, {}); result->putDirect(vm, JSC::Identifier::fromString(vm, "ext"_s), extValue); @@ -321,7 +321,7 @@ JSC::JSObject* convertDictionaryToJS(JSC::JSGlobalObject& lexicalGlobalObject, J RETURN_IF_EXCEPTION(throwScope, {}); result->putDirect(vm, JSC::Identifier::fromString(vm, "k"_s), kValue); } - if (!ignoreExtAndKeyOps && !IDLSequence>::isNullValue(dictionary.key_ops)) { + if (!IDLSequence>::isNullValue(dictionary.key_ops)) { auto key_opsValue = toJS>>(lexicalGlobalObject, globalObject, throwScope, IDLSequence>::extractValueFromNullable(dictionary.key_ops)); RETURN_IF_EXCEPTION(throwScope, {}); result->putDirect(vm, JSC::Identifier::fromString(vm, "key_ops"_s), key_opsValue); diff --git a/src/jsc/bindings/webcrypto/JSJsonWebKey.h b/src/jsc/bindings/webcrypto/JSJsonWebKey.h index c1b287c4dd37..07e7960bedfe 100644 --- a/src/jsc/bindings/webcrypto/JSJsonWebKey.h +++ b/src/jsc/bindings/webcrypto/JSJsonWebKey.h @@ -29,7 +29,7 @@ namespace WebCore { template<> JsonWebKey convertDictionary(JSC::JSGlobalObject&, JSC::JSValue); -JSC::JSObject* convertDictionaryToJS(JSC::JSGlobalObject&, JSDOMGlobalObject&, const JsonWebKey&, bool ignoreExtAndKeyOps = false); +JSC::JSObject* convertDictionaryToJS(JSC::JSGlobalObject&, JSDOMGlobalObject&, const JsonWebKey&); } // namespace WebCore diff --git a/src/jsc/bindings/webcrypto/JSRsaKeyGenParams.cpp b/src/jsc/bindings/webcrypto/JSRsaKeyGenParams.cpp deleted file mode 100644 index 5e81569b562e..000000000000 --- a/src/jsc/bindings/webcrypto/JSRsaKeyGenParams.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - This file is part of the WebKit open source project. - This file has been generated by generate-bindings.pl. DO NOT MODIFY! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "config.h" - -#if ENABLE(WEB_CRYPTO) - -#include "JSRsaKeyGenParams.h" - -#include "JSDOMConvertBufferSource.h" -#include "JSDOMConvertNumbers.h" -#include "JSDOMConvertStrings.h" -#include - -namespace WebCore { -using namespace JSC; - -#if ENABLE(WEB_CRYPTO) - -template<> CryptoAlgorithmRsaKeyGenParams convertDictionary(JSGlobalObject& lexicalGlobalObject, JSValue value) -{ - auto& vm = JSC::getVM(&lexicalGlobalObject); - auto throwScope = DECLARE_THROW_SCOPE(vm); - bool isNullOrUndefined = value.isUndefinedOrNull(); - auto* object = isNullOrUndefined ? nullptr : value.getObject(); - if (!isNullOrUndefined && !object) [[unlikely]] { - throwTypeError(&lexicalGlobalObject, throwScope); - return {}; - } - CryptoAlgorithmRsaKeyGenParams result; - JSValue nameValue; - if (isNullOrUndefined) - nameValue = jsUndefined(); - else { - nameValue = object->get(&lexicalGlobalObject, vm.propertyNames->name); - RETURN_IF_EXCEPTION(throwScope, {}); - } - if (!nameValue.isUndefined()) { - result.name = convert(lexicalGlobalObject, nameValue); - RETURN_IF_EXCEPTION(throwScope, {}); - } else { - throwRequiredMemberTypeError(lexicalGlobalObject, throwScope, "name"_s, "RsaKeyGenParams"_s, "DOMString"_s); - return {}; - } - JSValue modulusLengthValue; - if (isNullOrUndefined) - modulusLengthValue = jsUndefined(); - else { - modulusLengthValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "modulusLength"_s)); - RETURN_IF_EXCEPTION(throwScope, {}); - } - if (!modulusLengthValue.isUndefined()) { - result.modulusLength = convert>(lexicalGlobalObject, modulusLengthValue); - RETURN_IF_EXCEPTION(throwScope, {}); - } else { - throwRequiredMemberTypeError(lexicalGlobalObject, throwScope, "modulusLength"_s, "RsaKeyGenParams"_s, "unsigned long"_s); - return {}; - } - JSValue publicExponentValue; - if (isNullOrUndefined) - publicExponentValue = jsUndefined(); - else { - publicExponentValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "publicExponent"_s)); - RETURN_IF_EXCEPTION(throwScope, {}); - } - if (!publicExponentValue.isUndefined()) { - result.publicExponent = convert(lexicalGlobalObject, publicExponentValue); - RETURN_IF_EXCEPTION(throwScope, {}); - } else { - throwRequiredMemberTypeError(lexicalGlobalObject, throwScope, "publicExponent"_s, "RsaKeyGenParams"_s, "Uint8Array"_s); - return {}; - } - return result; -} - -#endif - -} // namespace WebCore - -#endif // ENABLE(WEB_CRYPTO) diff --git a/src/jsc/bindings/webcrypto/JSRsaKeyGenParams.h b/src/jsc/bindings/webcrypto/JSRsaKeyGenParams.h deleted file mode 100644 index 5ed39bcff2d3..000000000000 --- a/src/jsc/bindings/webcrypto/JSRsaKeyGenParams.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - This file is part of the WebKit open source project. - This file has been generated by generate-bindings.pl. DO NOT MODIFY! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#pragma once - -#if ENABLE(WEB_CRYPTO) - -#include "CryptoAlgorithmRsaKeyGenParams.h" -#include "JSDOMConvertDictionary.h" - -namespace WebCore { - -template<> CryptoAlgorithmRsaKeyGenParams convertDictionary(JSC::JSGlobalObject&, JSC::JSValue); - -} // namespace WebCore - -#endif // ENABLE(WEB_CRYPTO) diff --git a/src/jsc/bindings/webcrypto/SubtleCrypto.cpp b/src/jsc/bindings/webcrypto/SubtleCrypto.cpp index 0fbeb2dc3167..6345449e9a02 100644 --- a/src/jsc/bindings/webcrypto/SubtleCrypto.cpp +++ b/src/jsc/bindings/webcrypto/SubtleCrypto.cpp @@ -66,7 +66,6 @@ #include #include "JSRsaHashedImportParams.h" #include "JSRsaHashedKeyGenParams.h" -#include "JSRsaKeyGenParams.h" #include "JSRsaOaepParams.h" #include "JSRsaPssParams.h" #include @@ -108,22 +107,6 @@ static ExceptionOr toHashIdentifier(JSGlobalObject& s return digestParams.returnValue()->identifier; } -static bool isRSAESPKCSWebCryptoDeprecated(JSGlobalObject& state) -{ - return true; - // auto& globalObject = *uncheckedDowncast(&state); - // auto* context = globalObject.scriptExecutionContext(); - // return context && context->settingsValues().deprecateRSAESPKCSWebCryptoEnabled; -} - -static bool isSafeCurvesEnabled(JSGlobalObject& state) -{ - return true; - // auto& globalObject = *uncheckedDowncast(&state); - // auto* context = globalObject.scriptExecutionContext(); - // return context && context->settingsValues().webCryptoSafeCurvesEnabled; -} - // The lazy *Vector() accessors on the parameter classes copy these dictionary members into // Vector with no size check, and exceeding the Vector capacity cap CRASH()es in // allocateBuffer. Validate them while normalizing so an oversized member rejects instead. @@ -168,19 +151,13 @@ static ExceptionOr> normalizeCryptoAl if (!identifier) [[unlikely]] return Exception { NotSupportedError, "Unrecognized algorithm name"_s }; - if (*identifier == CryptoAlgorithmIdentifier::Ed25519 && !isSafeCurvesEnabled(state)) - return Exception { NotSupportedError, "Unrecognized algorithm name"_s }; - std::unique_ptr result; switch (operation) { case Operations::Encrypt: case Operations::Decrypt: switch (*identifier) { case CryptoAlgorithmIdentifier::RSAES_PKCS1_v1_5: - if (isRSAESPKCSWebCryptoDeprecated(state)) - return Exception { NotSupportedError, "RSAES-PKCS1-v1_5 support is deprecated"_s }; - result = makeUnique(params); - break; + return Exception { NotSupportedError, "RSAES-PKCS1-v1_5 support is deprecated"_s }; case CryptoAlgorithmIdentifier::RSA_OAEP: { auto params = convertDictionary(state, value.get()); RETURN_IF_EXCEPTION(scope, Exception { ExistingExceptionError }); @@ -282,16 +259,8 @@ static ExceptionOr> normalizeCryptoAl break; case Operations::GenerateKey: switch (*identifier) { - case CryptoAlgorithmIdentifier::RSAES_PKCS1_v1_5: { - if (isRSAESPKCSWebCryptoDeprecated(state)) - return Exception { NotSupportedError, "RSAES-PKCS1-v1_5 support is deprecated"_s }; - auto params = convertDictionary(state, value.get()); - RETURN_IF_EXCEPTION(scope, Exception { ExistingExceptionError }); - if (!isAcceptableVectorSource(params.publicExponent)) - return Exception { OperationError, "Input data is too large"_s }; - result = makeUnique(params); - break; - } + case CryptoAlgorithmIdentifier::RSAES_PKCS1_v1_5: + return Exception { NotSupportedError, "RSAES-PKCS1-v1_5 support is deprecated"_s }; case CryptoAlgorithmIdentifier::RSASSA_PKCS1_v1_5: case CryptoAlgorithmIdentifier::RSA_PSS: case CryptoAlgorithmIdentifier::RSA_OAEP: { @@ -414,10 +383,7 @@ static ExceptionOr> normalizeCryptoAl case Operations::ImportKey: switch (*identifier) { case CryptoAlgorithmIdentifier::RSAES_PKCS1_v1_5: - if (isRSAESPKCSWebCryptoDeprecated(state)) - return Exception { NotSupportedError, "RSAES-PKCS1-v1_5 support is deprecated"_s }; - result = makeUnique(params); - break; + return Exception { NotSupportedError, "RSAES-PKCS1-v1_5 support is deprecated"_s }; case CryptoAlgorithmIdentifier::RSASSA_PKCS1_v1_5: case CryptoAlgorithmIdentifier::RSA_PSS: case CryptoAlgorithmIdentifier::RSA_OAEP: { @@ -681,11 +647,9 @@ static std::optional> copyToVector(BufferSource&& data, Ref { std::span { data.data(), data.length() } }; } -static bool isSupportedExportKey(JSGlobalObject& state, CryptoAlgorithmIdentifier identifier) +static bool isSupportedExportKey(CryptoAlgorithmIdentifier identifier) { switch (identifier) { - case CryptoAlgorithmIdentifier::RSAES_PKCS1_v1_5: - return !isRSAESPKCSWebCryptoDeprecated(state); case CryptoAlgorithmIdentifier::RSASSA_PKCS1_v1_5: case CryptoAlgorithmIdentifier::RSA_PSS: case CryptoAlgorithmIdentifier::RSA_OAEP: @@ -794,10 +758,6 @@ static std::unique_ptr crossThreadCopyImportParams(co } } -void SubtleCrypto::addAuthenticatedEncryptionWarningIfNecessary(CryptoAlgorithmIdentifier algorithmIdentifier) -{ -} - // MARK: - Exposed functions. void SubtleCrypto::encrypt(JSC::JSGlobalObject& state, AlgorithmIdentifier&& algorithmIdentifier, CryptoKey& key, BufferSource&& dataBufferSource, Ref&& promise) @@ -805,8 +765,6 @@ void SubtleCrypto::encrypt(JSC::JSGlobalObject& state, AlgorithmIdentifier&& alg auto& vm = state.vm(); auto scope = DECLARE_THROW_SCOPE(vm); - addAuthenticatedEncryptionWarningIfNecessary(key.algorithmIdentifier()); - auto paramsOrException = normalizeCryptoAlgorithmParameters(state, WTF::move(algorithmIdentifier), Operations::Encrypt); RETURN_IF_EXCEPTION(scope, void()); if (paramsOrException.hasException()) { @@ -851,8 +809,6 @@ void SubtleCrypto::decrypt(JSC::JSGlobalObject& state, AlgorithmIdentifier&& alg auto& vm = state.vm(); auto scope = DECLARE_THROW_SCOPE(vm); - addAuthenticatedEncryptionWarningIfNecessary(key.algorithmIdentifier()); - auto paramsOrException = normalizeCryptoAlgorithmParameters(state, WTF::move(algorithmIdentifier), Operations::Decrypt); RETURN_IF_EXCEPTION(scope, void()); if (paramsOrException.hasException()) { @@ -1337,7 +1293,7 @@ void SubtleCrypto::importKey(JSC::JSGlobalObject& state, KeyFormat format, KeyDa void SubtleCrypto::exportKey(KeyFormat format, CryptoKey& key, Ref&& promise) { - if (!isSupportedExportKey(*promise->globalObject(), key.algorithmIdentifier())) { + if (!isSupportedExportKey(key.algorithmIdentifier())) { promise->reject(Exception { NotSupportedError }); return; } @@ -1419,7 +1375,7 @@ void SubtleCrypto::wrapKey(JSC::JSGlobalObject& state, KeyFormat format, CryptoK return; } - if (!isSupportedExportKey(state, key.algorithmIdentifier())) { + if (!isSupportedExportKey(key.algorithmIdentifier())) { promise->reject(Exception { NotSupportedError }); return; } @@ -2067,7 +2023,7 @@ bool SubtleCrypto::supports(JSC::JSGlobalObject& state, const String& operation, operationKind = Operations::Decapsulate; else if (op == "exportKey"_s) { auto params = normalize(algorithm, Operations::ImportKey); - return params && isSupportedExportKey(state, params->identifier); + return params && isSupportedExportKey(params->identifier); } else return false; diff --git a/src/jsc/bindings/webcrypto/SubtleCrypto.h b/src/jsc/bindings/webcrypto/SubtleCrypto.h index 450cf1a2bad1..511a43385d52 100644 --- a/src/jsc/bindings/webcrypto/SubtleCrypto.h +++ b/src/jsc/bindings/webcrypto/SubtleCrypto.h @@ -56,8 +56,6 @@ class CryptoAlgorithmParameters; class CryptoKey; class DeferredPromise; -enum class CryptoAlgorithmIdentifier : uint8_t; - class SubtleCrypto : public ContextDestructionObserver, public RefCounted { public: // ContextDestructionObserver. @@ -103,7 +101,6 @@ class SubtleCrypto : public ContextDestructionObserver, public RefCounted getPromise(DeferredPromise*, WeakPtr); Ref m_workQueue; diff --git a/src/libuv_sys/libuv.rs b/src/libuv_sys/libuv.rs index 661755032621..17f19a46b62b 100644 --- a/src/libuv_sys/libuv.rs +++ b/src/libuv_sys/libuv.rs @@ -60,9 +60,7 @@ pub use bun_windows_sys::{ LARGE_INTEGER, LONG, OVERLAPPED, SHORT, ULONG, ULONG_PTR, WCHAR, WORD, }; // Kept local — NOT re-exported from `bun_windows_sys`: -// • CHAR: libuv wants u8, `bun_windows_sys::CHAR` is c_char (i8 on MSVC). -// • NTSTATUS: libuv wants plain i32, `bun_windows_sys::NTSTATUS` is a newtype. -pub type CHAR = u8; +// libuv wants plain i32, `bun_windows_sys::NTSTATUS` is a newtype. pub type NTSTATUS = i32; /// Win32 `SOCKET` is `UINT_PTR` (an integer), not a pointer. A raw-pointer type would give /// `Option` an unwanted niche (None ↔ 0 collides with socket 0) and @@ -530,24 +528,6 @@ impl Loop { log!("dec"); self.active_handles = self.active_handles.saturating_sub(1); } - /// `ref`/`unref` aliases for `inc`/`dec`. - #[inline] - pub fn ref_(&mut self) { - self.inc(); - } - #[inline] - pub fn unref(&mut self) { - self.dec(); - } - #[inline] - pub fn unref_count(&mut self, count: i32) { - log!("unrefCount({})", count); - // A bare `count as u32` would silently wrap a - // negative to ~4 billion and zero out `active_handles`: - // assert in debug, clamp in release so we never wrap. - debug_assert!(count >= 0, "unref_count: count must be non-negative"); - self.active_handles = self.active_handles.saturating_sub(count.max(0) as u32); - } #[inline] pub fn stop(&mut self) { log!("stop"); @@ -564,23 +544,6 @@ impl Loop { // SAFETY: self is a live loop. let _ = unsafe { uv_run(self, RunMode::Default) }; } - #[inline] - pub fn run(&mut self) { - // SAFETY: self is a live loop. - let _ = unsafe { uv_run(self, RunMode::Default) }; - } - /// Signature matches the uSockets loop's so callers need no `cfg`. Both args are ignored: - /// libuv derives its own deadline, and the Windows park hook is driven from `us_loop_run` - /// (libuv.c), which reuses libuv's already-refreshed clock via `uv_now`. - #[inline] - pub fn tick_with_timeout(&mut self, _: i64, _now_ns: u64) { - // SAFETY: self is a live loop. - let _ = unsafe { uv_run(self, RunMode::NoWait) }; - } - #[inline] - pub fn wakeup(&mut self) { - self.wq_async.send(); - } } /// `Loop::close_thread_loop` diagnostics: which handles keep the worker's loop busy. @@ -983,17 +946,6 @@ pub struct uv_write_t { pub wait_handle: HANDLE, } impl uv_write_t { - /// Thin wrapper over `uv_write` for a single buffer. - #[inline] - pub fn write_raw( - &mut self, - stream: *mut uv_stream_t, - input: &uv_buf_t, - cb: uv_write_cb, - ) -> ReturnCode { - // SAFETY: caller initialized `self`; `stream` is a live stream handle. - unsafe { uv_write(self, stream, input, 1, cb) } - } /// Context-aware `uv_write`. Stores `context` in `req.data`; /// the trampoline recovers it and dispatches to `on_write` as a plain Rust /// `&mut`. Generic monomorphisation gives one `extern "C"` thunk per ``. @@ -1003,8 +955,7 @@ impl uv_write_t { /// (fn-ptr ↔ integer is well-defined; fn-ptr ↔ data-ptr is not — Miri /// rejects the latter), and (b) returns the raw [`ReturnCode`]; callers /// apply `.to_error(Tag::write)` themselves. The `bun.sys.syslog` line is - /// emitted via this crate's `[uv]` log scope. The null-callback path is - /// [`write_raw`]. + /// emitted via this crate's `[uv]` log scope. #[inline] pub fn write( &mut self, @@ -1112,7 +1063,6 @@ pub struct uv_tcp_t { pub delayed_error: c_int, tcp: tcp_u, } -pub type Tcp = uv_tcp_t; // ────────────────────────────────────────────────────────────────────────── // `uv_udp_t`. @@ -1400,7 +1350,6 @@ pub struct uv_tty_t { pub handle: HANDLE, tty: tty_u, } -pub type Tty = uv_tty_t; impl uv_tty_t { #[inline] pub fn init(&mut self, loop_: *mut Loop, file: uv_file) -> ReturnCode { @@ -1461,7 +1410,6 @@ pub struct uv_poll_t { pub mask_events_2: u8, pub events: u8, } -pub type Poll = uv_poll_t; // ────────────────────────────────────────────────────────────────────────── // `Timer` (`uv_timer_t`). @@ -1483,7 +1431,6 @@ pub struct Timer { pub start_id: u64, pub timer_cb: uv_timer_cb, } -pub type uv_timer_t = Timer; impl Timer { #[inline] pub fn init(&mut self, loop_: *mut Loop) { @@ -1588,14 +1535,6 @@ pub struct uv_async_t { pub async_cb: uv_async_cb, pub async_sent: u8, } -pub type Async = uv_async_t; -impl uv_async_t { - #[inline] - pub fn send(&mut self) { - // SAFETY: async was `init`ed. - let _ = unsafe { uv_async_send(self) }; - } -} // ────────────────────────────────────────────────────────────────────────── // `Process` (`uv_process_t`) + spawn options. @@ -1644,11 +1583,6 @@ impl Process { // SAFETY: process was spawned. unsafe { uv_process_kill(self, signum) } } - #[inline] - pub fn get_pid(&self) -> c_int { - // SAFETY: process was spawned. - unsafe { uv_process_get_pid(self) } - } } #[repr(C)] @@ -1846,18 +1780,10 @@ pub struct uv_stat_t { pub birthtim: uv_timespec_t, } impl uv_stat_t { - #[inline] - pub fn atime(&self) -> uv_timespec_t { - self.atim - } #[inline] pub fn mtime(&self) -> uv_timespec_t { self.mtim } - #[inline] - pub fn ctime(&self) -> uv_timespec_t { - self.ctim - } // Un-prefixed accessors so cross-platform code that pattern-matches on // POSIX `stat.mode`/`stat.size` can call // through without `cfg` arms. @@ -2308,10 +2234,6 @@ impl ReturnCode { ReturnCode(0) } #[inline] - pub const fn from_raw(v: c_int) -> ReturnCode { - ReturnCode(v) - } - #[inline] pub const fn int(self) -> c_int { self.0 } @@ -2370,10 +2292,6 @@ impl fmt::Display for ReturnCode { #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct ReturnCodeI64(pub(crate) i64); impl ReturnCodeI64 { - #[inline] - pub const fn init(i: i64) -> ReturnCodeI64 { - ReturnCodeI64(i) - } #[inline] pub const fn int(self) -> i64 { self.0 @@ -2813,7 +2731,6 @@ unsafe extern "C" { pub fn uv_idle_init(loop_: *mut Loop, idle: *mut uv_idle_t) -> c_int; pub fn uv_idle_start(idle: *mut uv_idle_t, cb: uv_idle_cb) -> c_int; pub fn uv_idle_stop(idle: *mut uv_idle_t) -> c_int; - pub fn uv_async_send(async_: *mut uv_async_t) -> c_int; // timer pub fn uv_timer_init(loop_: *mut Loop, handle: *mut Timer) -> c_int; @@ -2839,7 +2756,6 @@ unsafe extern "C" { options: *const uv_process_options_t, ) -> ReturnCode; pub fn uv_process_kill(handle: *mut Process, signum: c_int) -> ReturnCode; - pub fn uv_process_get_pid(handle: *const Process) -> uv_pid_t; // misc pub fn uv_uptime(uptime: *mut f64) -> c_int; diff --git a/src/runtime/bake/bake.bind.ts b/src/runtime/bake/bake.bind.ts deleted file mode 100644 index 7a28653d34e6..000000000000 --- a/src/runtime/bake/bake.bind.ts +++ /dev/null @@ -1,9 +0,0 @@ -// import { t } from "bindgen"; - -// export const ReactFastRefresh = t.dictionary({ -// importSource: t.UTF8String, -// }); - -// export const FrameworkConfig = t.dictionary({ -// reactFastRefresh: t.oneOf(t.boolean, ReactFastRefresh).default(false), -// }); diff --git a/src/runtime/server/AnyRequestContext.rs b/src/runtime/server/AnyRequestContext.rs index e50a24ca256e..96d62cef1346 100644 --- a/src/runtime/server/AnyRequestContext.rs +++ b/src/runtime/server/AnyRequestContext.rs @@ -176,10 +176,6 @@ impl AnyRequestContext { dispatch!(self, (), |_T, ctx| ctx.set_cookies(cookie_map)) } - pub(crate) fn enable_timeout_events(self) { - dispatch!(self, (), |_T, ctx| ctx.set_timeout_handler()) - } - pub(crate) fn get_remote_socket_info(self) -> Option { dispatch!(self, None, |_T, ctx| ctx.get_remote_socket_info()) } diff --git a/src/runtime/server/NodeHTTPResponse.rs b/src/runtime/server/NodeHTTPResponse.rs index aa8cfd2873cc..bfcf97a09630 100644 --- a/src/runtime/server/NodeHTTPResponse.rs +++ b/src/runtime/server/NodeHTTPResponse.rs @@ -2803,31 +2803,3 @@ pub(crate) unsafe extern "C" fn NodeHTTPResponse__createForJS( unsafe { *node_response_ptr = response }; js_this } - -impl NodeHTTPResponse { - #[uws::uws_callback(export = "NodeHTTPResponse__setTimeout")] - pub(crate) fn ffi_set_timeout(&self, seconds: JSValue, global_this: &JSGlobalObject) -> bool { - if !seconds.is_number() { - let _: jsc::JsError = - global_this.throw_invalid_argument_type_value(b"timeout", b"number", seconds); - return false; - } - - let flags = self.flags.get(); - let Some(raw) = self.raw_response.get() else { - return false; - }; - if flags.contains(Flags::REQUEST_HAS_COMPLETED) - || flags.contains(Flags::SOCKET_CLOSED) - || flags.contains(Flags::UPGRADED) - { - return false; - } - - // ECMAScript ToUint32 — same bit pattern as - // ToInt32 reinterpreted as unsigned (negative inputs wrap, e.g. -1 → u32::MAX). - let secs = (seconds.to_int32() as c_uint).min(255) as u8; - raw.timeout(secs); - true - } -} diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 2d90373a54a1..0e337adb45d5 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -9,7 +9,7 @@ use bun_http_types::Method::Method; use bun_jsc::JsCell; use bun_uws::{self as uws, WebSocketUpgradeContext}; -use crate::server::jsc::{self, JSGlobalObject, JSValue, JsResult, VirtualMachine}; +use crate::server::jsc::{self, JSGlobalObject, JSValue, JsResult}; use crate::server::{RangeRequest, ServerLike}; use crate::webcore::{ self as WebCore, AbortSignal, AnyBlob, ByteStream, CookieMap, CookieMapRef, FetchHeaders, @@ -341,8 +341,8 @@ fn as_response(value: JSValue) -> Option<*mut Response> { // ─── sibling-subtree shims ─────────────────────────────────────────────────── // These forward to methods that exist in webcore/ but are currently inside -// impl blocks that fail to compile (codegen gc-slot stubs, opaque AbortSignal, -// duplicate InternalJSEventCallback). Adapt on this side per phase-d rules. +// impl blocks that fail to compile (codegen gc-slot stubs, opaque AbortSignal). +// Adapt on this side per phase-d rules. mod shim { use super::*; @@ -387,22 +387,6 @@ mod shim { signal.pending_activity_unref(); signal.unref(); } - #[inline] - pub(super) fn iec_trigger( - cb: &bun_jsc::JsCell, - ev: request::EventType, - g: &JSGlobalObject, - ) -> JsResult { - cb.with_mut(|cb| cb.trigger(ev, g)) - } - #[inline] - pub(super) fn iec_deinit(cb: &bun_jsc::JsCell) { - cb.with_mut(|cb| cb.deinit()) - } - #[inline] - pub(super) fn iec_has_callback(cb: &bun_jsc::JsCell) -> bool { - cb.get().has_callback() - } /// `Blob::is_s3()` / `Blob::needs_to_read_file()` have duplicate impls /// (E0034); inline the body here. #[inline] @@ -680,17 +664,6 @@ where )); } - pub(crate) fn set_timeout_handler(&self) { - if self.flags.has_timeout_handler() { - return; - } - if let Some(resp) = self.resp.get() { - self.flags.set_has_timeout_handler(true); - // SAFETY: FFI handle valid while resp is Some - resp.on_timeout(|this, resp| Self::on_timeout(this, resp), self.as_ctx_ptr()); - } - } - pub(crate) fn on_resolve(_global: &JSGlobalObject, callframe: &CallFrame) -> JsResult { ctx_log!("onResolve"); @@ -1218,7 +1191,6 @@ where if self.resp.take().is_some() { self.flags.set_is_waiting_for_request_body(false); self.flags.set_has_abort_handler(false); - self.flags.set_has_timeout_handler(false); self.request_body_buf.set(Vec::new()); self.end_request_streaming_and_drain(); self.deref(); @@ -1347,40 +1319,6 @@ where ctx_log!("create ({:p})", this.as_ptr()); } - fn on_timeout(this: *mut Self, _resp: uws::AnyResponse) { - let pinned = RequestContextRef::pin(this); - let this = pinned.ctx(); - debug_assert!(this.resp.get().is_some()); - debug_assert!(this.server.get().is_some()); - - let any_js_calls = core::cell::Cell::new(false); - let server = this.server(); - let _ = server.vm(); - let global_this = server.global_this(); - // This is a task in the event loop. - // If we called into JavaScript, we must drain the microtask queue. - scopeguard::defer! { - if any_js_calls.get() { - VirtualMachine::get().as_mut().drain_microtasks(); - } - } - - if let Some(request) = this.request_mut() { - match shim::iec_trigger( - &request.internal_event_callback, - request::EventType::Timeout, - global_this, - ) { - Ok(called) => any_js_calls.set(called), - // This uWS callback is the landing frame for what it threw. - Err(err) => { - any_js_calls.set(true); - crate::dispatch::fold(Err(err)); - } - } - } - } - fn on_abort(this: *mut Self, resp: uws::AnyResponse) { ctx_log!("onAbort"); let pinned = RequestContextRef::pin(this); @@ -1424,20 +1362,6 @@ where if let Some(request) = this.request_mut() { request.request_context = AnyRequestContext::NULL; - match shim::iec_trigger( - &request.internal_event_callback, - request::EventType::Abort, - global_this, - ) { - Ok(called) => any_js_calls.set(called), - // This uWS callback is the landing frame for what it threw. - Err(err) => { - any_js_calls.set(true); - crate::dispatch::fold(Err(err)); - } - } - // we can already clean this strong refs - shim::iec_deinit(&request.internal_event_callback); this.request_weakref.with_mut(|w| w.deref()); } // if signal is not aborted, abort the signal @@ -1527,8 +1451,6 @@ where if let Some(request) = self.request_mut() { request.request_context = AnyRequestContext::NULL; - // we can already clean this strong refs - shim::iec_deinit(&request.internal_event_callback); self.request_weakref.with_mut(|w| w.deref()); } @@ -1914,10 +1836,6 @@ where self.flags.set_is_waiting_for_request_body(false); resp.clear_on_data(); } - if self.flags.has_timeout_handler() { - resp.clear_timeout(); - self.flags.set_has_timeout_handler(false); - } let server = self.server(); FileResponseStream::start(&file_response_stream::StartOptions { @@ -2378,10 +2296,6 @@ where resp.clear_aborted(); self.flags.set_has_abort_handler(false); } - if self.flags.has_timeout_handler() { - resp.clear_timeout(); - self.flags.set_has_timeout_handler(false); - } } } @@ -4371,16 +4285,7 @@ where if let Some(resp) = self.resp.get() { // SAFETY: FFI handle resp.timeout(seconds.min(255) as u8); - if seconds > 0 { - // we only set the timeout callback if we wanna the timeout event to be triggered - // the connection will be closed so the abort handler will be called after the timeout - if let Some(req) = self.request_mut() { - if shim::iec_has_callback(&req.internal_event_callback) { - self.set_timeout_handler(); - } - } - } else { - // if the timeout is 0, we don't need to trigger the timeout event + if seconds == 0 { // SAFETY: FFI handle resp.clear_timeout(); } @@ -4598,7 +4503,6 @@ bitflags::bitflags! { const HAS_MARKED_COMPLETE = 1 << 0; const HAS_MARKED_PENDING = 1 << 1; const HAS_ABORT_HANDLER = 1 << 2; - const HAS_TIMEOUT_HANDLER = 1 << 3; const HAS_SENDFILE_CTX = 1 << 4; const HAS_CALLED_ERROR_HANDLER = 1 << 5; const NEEDS_CONTENT_LENGTH = 1 << 6; @@ -4653,11 +4557,6 @@ impl Flags { HAS_MARKED_PENDING ); flag_accessor!(has_abort_handler, set_has_abort_handler, HAS_ABORT_HANDLER); - flag_accessor!( - has_timeout_handler, - set_has_timeout_handler, - HAS_TIMEOUT_HANDLER - ); flag_accessor!(has_sendfile_ctx, set_has_sendfile_ctx, HAS_SENDFILE_CTX); flag_accessor!( has_called_error_handler, diff --git a/src/runtime/webcore/Body.rs b/src/runtime/webcore/Body.rs index 199858791101..a4998b2bbd6e 100644 --- a/src/runtime/webcore/Body.rs +++ b/src/runtime/webcore/Body.rs @@ -702,20 +702,6 @@ impl Value { } impl Value { - // We may not have all the data yet - // So we can't know for sure if it's empty or not - // We CAN know that it is definitely empty. - pub(crate) fn is_definitely_empty(&self) -> bool { - match self { - Value::Null => true, - Value::Used | Value::Empty => true, - Value::InternalBlob(b) => b.slice_const().is_empty(), - Value::Blob(b) => b.size.get() == 0, - Value::WTFStringImpl(s) => wtf_impl(s).length() == 0, - Value::Error(_) | Value::Locked(_) => false, - } - } - pub(crate) fn to_blob_if_possible(&mut self) { if let Value::WTFStringImpl(str) = *self { if let Some(bytes) = wtf_impl(&str).to_utf8_if_needed() { diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index e6d55c7d1163..66fa423c8351 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -1,7 +1,6 @@ //! https://developer.mozilla.org/en-US/docs/Web/API/Request use core::cell::Cell; -use core::ffi::c_uint; use core::ptr::NonNull; use std::borrow::Cow; @@ -14,7 +13,7 @@ use crate::webcore::BlobExt as _; use crate::webcore::blob::ZigStringBlobExt as _; use crate::webcore::body::{self, BodyHiveHandle, BodyMixin, Value as BodyValue}; use crate::webcore::jsc::{ - self as jsc, CallFrame, HTTPHeaderName, JSGlobalObject, JSValue, JsError, JsRef, JsResult, + CallFrame, HTTPHeaderName, JSGlobalObject, JSValue, JsError, JsRef, JsResult, }; use crate::webcore::{AbortSignal, Blob, CookieMap, FetchHeaders, ReadableStream, Response}; use bun_alloc::AllocError; @@ -32,7 +31,6 @@ use bun_jsc::AbortSignalRef; use bun_jsc::StringJsc as _; use bun_jsc::generated::JSRequest as js_gen; use bun_ptr::weak_ptr::WeakPtrData; -use bun_uws as uws; use core::mem::ManuallyDrop; impl bun_ptr::weak_ptr::HasWeakPtrData for Request { @@ -104,7 +102,6 @@ pub struct Request { pub(crate) weak_ptr_data: WeakPtrData, // We must report a consistent value for this reported_estimated_size: Cell, - pub(crate) internal_event_callback: JsCell, } // A `#[repr(C)]` 4-byte struct for direct @@ -388,36 +385,6 @@ impl Request { .set_cookies(cookie_map.map(|c| std::ptr::from_ref::(c).cast_mut())); } - /// C++ treats the returned pointer as borrowed for the request handler's lifetime. - #[bun_uws::uws_callback(export = "Request__getUWSRequest", no_catch)] - pub fn ffi_get_uws_request(&self) -> *mut uws::Request { - self.request_context - .get_request() - .unwrap_or(core::ptr::null_mut()) - } - - #[bun_uws::uws_callback(export = "Request__setInternalEventCallback")] - pub fn ffi_set_internal_event_callback(&self, callback: JSValue, global_this: &JSGlobalObject) { - self.internal_event_callback - .set(InternalJSEventCallback::init(callback, global_this)); - // we always have the abort event but we need to enable the timeout event as well in case of `node:http`.Server.setTimeout is set - self.request_context.enable_timeout_events(); - } - - #[bun_uws::uws_callback(export = "Request__setTimeout")] - pub fn ffi_set_timeout(&self, seconds: JSValue, global_this: &JSGlobalObject) { - if !seconds.is_number() { - let _ = global_this.throw(format_args!( - "Failed to set timeout: The provided value is not of type 'number'." - )); - return; - } - - // `JSValue.toU32` clamps via JS ToUint32 rules, - // not signed wrap-then-reinterpret like `to_int32() as c_uint` would do. - self.set_timeout(seconds.to_u32() as c_uint); - } - /// `BunRequest.prototype.clone` (the `Bun.serve` `routes:` subclass) goes /// through `JSBunRequest::clone` -> here, not through [`Self::do_clone`], /// so it needs the same fetch-spec step-1 usability check. @@ -449,10 +416,6 @@ impl Request { } } -// NOTE: `EventType` and `impl InternalJSEventCallback` are defined once below -// (near the struct decl); the duplicate block that used to live here was -// removed to resolve E0034 ambiguity. - impl Request { /// TODO: do we need this? pub(crate) fn init2( @@ -472,7 +435,6 @@ impl Request { request_context: AnyRequestContext::NULL, weak_ptr_data: WeakPtrData::EMPTY, reported_estimated_size: Cell::new(0), - internal_event_callback: JsCell::new(InternalJSEventCallback::default()), } } @@ -758,9 +720,6 @@ impl Request { // AbortSignalRef::Drop unrefs the C++ handle. self.signal.set(None); - // internal_event_callback.deinit() → Drop on Strong inside; explicit take to match timing - self.internal_event_callback - .set(InternalJSEventCallback::default()); } pub fn finalize(self: Box) { @@ -776,7 +735,7 @@ impl Request { // Hot path: no outstanding weak refs. Reclaim and drop the whole // allocation in one shot — `Box::from_raw`'s drop runs // `drop_in_place` over every field (headers / url / signal / - // js_ref / internal_event_callback) once, without the 4× `Cell::set` + // js_ref) once, without the `Cell::set` // read-write-drop round-trips the old `finalize_without_deinit()` // call performed here before re-dropping the (now-empty) fields. // SAFETY: `this` is the live Box-allocated payload. @@ -1044,7 +1003,6 @@ impl Request { request_context: AnyRequestContext::NULL, weak_ptr_data: WeakPtrData::EMPTY, reported_estimated_size: Cell::new(0), - internal_event_callback: JsCell::new(InternalJSEventCallback::default()), }; // A scopeguard cannot capture `&mut req` while the // fn body also uses it. Cleanup is invoked at each early-return site via `bail!`. @@ -1580,8 +1538,8 @@ impl Request { }; // `ptr::write` is a raw bit-overwrite — no destructors run on the old - // `*req`, so Drop impls on `JsRef` / `strong::Optional` don't fire on - // the caller's sentinel. + // `*req`, so the Drop impl on `JsRef` doesn't fire on the caller's + // sentinel. // The old `req.body` hive ref is intentionally NOT unref'd here: // `clone()` seeds it with a dangling sentinel, and `construct_into` // releases its seed via the ptr-equality arm of its `cleanup`. @@ -1603,7 +1561,6 @@ impl Request { request_context: AnyRequestContext::NULL, weak_ptr_data: WeakPtrData::EMPTY, reported_estimated_size: Cell::new(0), - internal_event_callback: JsCell::new(InternalJSEventCallback::default()), }, ); } @@ -1636,59 +1593,11 @@ impl Request { request_context: AnyRequestContext::NULL, weak_ptr_data: WeakPtrData::EMPTY, reported_estimated_size: Cell::new(0), - internal_event_callback: JsCell::new(InternalJSEventCallback::default()), }); // Box drops on the error path automatically self.clone_into(&mut req, global_this, false)?; Ok(req) } - - pub(crate) fn set_timeout(&self, seconds: c_uint) { - let _ = self.request_context.set_timeout(seconds); - } -} - -#[derive(Default)] -pub struct InternalJSEventCallback { - pub(crate) function: jsc::strong::Optional, // jsc.Strong.Optional → bun_jsc::Strong -} - -/// Re-export of `NodeHTTPResponse.AbortEvent`. -pub(crate) type EventType = crate::server::node_http_response::AbortEvent; - -impl InternalJSEventCallback { - pub(crate) fn init(function: JSValue, global_this: &JSGlobalObject) -> InternalJSEventCallback { - InternalJSEventCallback { - function: jsc::strong::Optional::create(function, global_this), - } - } - - pub(crate) fn has_callback(&self) -> bool { - self.function.has() - } - - pub(crate) fn deinit(&mut self) { - self.function.deinit(); - } - - /// Fire the internal event callback (node:http's per-request timeout / - /// abort hook). `Ok(true)`: it ran; `Err`: it ran and threw, for the - /// response callback that fired it to fold. - pub(crate) fn trigger( - &mut self, - event_type: EventType, - global_this: &JSGlobalObject, - ) -> JsResult { - let Some(callback) = self.function.get() else { - return Ok(false); - }; - callback.call( - global_this, - JSValue::UNDEFINED, - &[JSValue::js_number(event_type as i32 as f64)], - )?; - Ok(true) - } } impl Request { @@ -1713,7 +1622,6 @@ impl Request { request_context, weak_ptr_data: WeakPtrData::EMPTY, reported_estimated_size: Cell::new(0), - internal_event_callback: JsCell::new(InternalJSEventCallback::default()), } } } diff --git a/src/runtime/webcore/Response.rs b/src/runtime/webcore/Response.rs index 72f171585728..6ce8498377ea 100644 --- a/src/runtime/webcore/Response.rs +++ b/src/runtime/webcore/Response.rs @@ -6,7 +6,6 @@ use core::ptr::NonNull; use bun_jsc::JsCell; use bun_jsc::{AbortSignal, AbortSignalRef, GlobalRef}; -use crate::webcore::BlobExt as _; use crate::webcore::jsc::{ BuiltinName, CallFrame, HTTPHeaderName, JSGlobalObject, JSType, JSValue, JsError, JsRef, JsResult, StringJsc as _, @@ -551,84 +550,6 @@ impl Response { } } -mod _jsc_host_fns { - use super::*; - - #[unsafe(export_name = "jsFunctionRequestOrResponseHasBodyValue")] - #[bun_jsc::host_call] - fn js_function_request_or_response_has_body_value( - _global: *mut JSGlobalObject, - callframe: &CallFrame, - ) -> JSValue { - let [this_value] = callframe.arguments_as_array::<1>(); - if this_value.is_empty_or_undefined_or_null() { - return JSValue::FALSE; - } - - if let Some(response) = this_value.as_class_ref::() { - return JSValue::from(!response.body.get().value.get().is_definitely_empty()); - } else if let Some(request) = this_value.as_class_ref::() { - return JSValue::from(!request.get_body_value().is_definitely_empty()); - } - - JSValue::FALSE - } - - #[unsafe(export_name = "jsFunctionGetCompleteRequestOrResponseBodyValueAsArrayBuffer")] - #[bun_jsc::host_call] - fn js_function_get_complete_request_or_response_body_value_as_array_buffer( - global_object: *mut JSGlobalObject, - callframe: *mut CallFrame, - ) -> JSValue { - // S008: `JSGlobalObject`/`CallFrame` are `opaque_ffi!` ZST handles — - // safe `*mut → &` via `opaque_deref` (JSC guarantees non-null/live). - let (global_object, callframe) = ( - bun_opaque::opaque_deref(global_object), - bun_opaque::opaque_deref(callframe), - ); - let [this_value] = callframe.arguments_as_array::<1>(); - if this_value.is_empty_or_undefined_or_null() { - return JSValue::UNDEFINED; - } - - let body: &mut BodyValue = 'brk: { - if let Some(response) = this_value.as_class_ref::() { - // R-2: `get_body_value` projects `&mut` via `JsCell`. - break 'brk response.get_body_value(); - } else if let Some(request) = this_value.as_class_ref::() { - break 'brk request.get_body_value(); - } - - return JSValue::UNDEFINED; - }; - - // Get the body if it's available synchronously. - match body { - BodyValue::Used | BodyValue::Empty | BodyValue::Null => JSValue::UNDEFINED, - BodyValue::Blob(blob) => { - if blob.needs_to_read_file() { - return JSValue::UNDEFINED; - } - let result = - match blob.to_array_buffer(global_object, crate::webcore::Lifetime::Transfer) { - Ok(v) => v, - Err(_) => JSValue::ZERO, - }; - *body = BodyValue::Used; - result - } - BodyValue::WTFStringImpl(_) | BodyValue::InternalBlob(_) => { - let mut any_blob = body.use_as_any_blob(); - match any_blob.to_array_buffer_transfer(global_object) { - Ok(v) => v, - Err(_) => JSValue::ZERO, - } - } - BodyValue::Error(_) | BodyValue::Locked(_) => JSValue::UNDEFINED, - } - } -} // mod _jsc_host_fns - impl Response { pub(crate) fn get_fetch_headers(&self) -> Option<&FetchHeaders> { self.init.get().headers.as_deref() diff --git a/src/sys/lib.rs b/src/sys/lib.rs index e563f9bb54b8..4a1c4833770e 100644 --- a/src/sys/lib.rs +++ b/src/sys/lib.rs @@ -4431,8 +4431,6 @@ mod windows_impl { Err(Error::new(E::ENOTSUP, Tag::munmap)) } pub type FcntlInt = isize; - pub const MSG_DONTWAIT: i32 = 0; - pub const SEND_FLAGS_NONBLOCK: i32 = 0; } #[cfg(windows)] pub use windows_impl::*; diff --git a/src/sys/windows/mod.rs b/src/sys/windows/mod.rs index 13427b1c5445..0842f2391503 100644 --- a/src/sys/windows/mod.rs +++ b/src/sys/windows/mod.rs @@ -227,21 +227,10 @@ pub(crate) fn filetime_to_timespec(filetime: i64) -> bun_libuv_sys::uv_timespec_ pub const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX; pub const NT_OBJECT_PREFIX: [u16; 4] = [b'\\' as u16, b'?' as u16, b'?' as u16, b'\\' as u16]; -pub const NT_UNC_OBJECT_PREFIX: [u16; 8] = [ - b'\\' as u16, - b'?' as u16, - b'?' as u16, - b'\\' as u16, - b'U' as u16, - b'N' as u16, - b'C' as u16, - b'\\' as u16, -]; pub(crate) const LONG_PATH_PREFIX: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]; pub(crate) const NT_OBJECT_PREFIX_U8: [u8; 4] = *b"\\??\\"; -pub const NT_UNC_OBJECT_PREFIX_U8: [u8; 8] = *b"\\??\\UNC\\"; pub const LONG_PATH_PREFIX_U8: [u8; 4] = *b"\\\\?\\"; #[cfg(windows)] diff --git a/test/js/node/fs/fs-leak.test.js b/test/js/node/fs/fs-leak.test.js index 276f549d5fce..228d6d5a95f3 100644 --- a/test/js/node/fs/fs-leak.test.js +++ b/test/js/node/fs/fs-leak.test.js @@ -2,7 +2,6 @@ const { expect, test } = require("bun:test"); const fs = require("fs"); const { tmpdir, devNull } = require("os"); -const { fsStreamInternals } = require("bun:internal-for-testing"); function getMaxFd() { const dev_null = fs.openSync(devNull, "r");