Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: update cloudflare preset with unenv v2 #3088

Merged
merged 6 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@
"ultrahtml": "^1.5.3",
"uncrypto": "^0.1.3",
"unctx": "^2.4.1",
"unenv": "2.0.0-rc.4",
"unenv": "2.0.0-rc.6",
"unimport": "^4.0.0",
"unplugin-utils": "^0.2.3",
"unstorage": "^1.14.4",
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 19 additions & 5 deletions src/presets/cloudflare/unenv/preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,15 @@ export const nodeCompatModules = [
];

// Modules implemented via a mix of workerd APIs and polyfills
export const hybridNodeCompatModules = ["async_hooks", "crypto", "util"];
export const hybridNodeCompatModules = [
"async_hooks",
"console",
"crypto",
"module",
"perf_hooks",
"process",
"util",
];

const presetRuntimeDir = fileURLToPath(new URL("runtime/", import.meta.url));
const resolvePresetRuntime = (m: string) => join(presetRuntimeDir, `${m}.mjs`);
Expand Down Expand Up @@ -68,8 +76,7 @@ export const unenvCfPreset: Preset = {
"node-mock-http/_polyfill/buffer": "node:buffer",
},
inject: {
// process: "TODO",
// console: "TODO",
process: resolvePresetRuntime("process"),
Buffer: ["node:buffer", "Buffer"],
"global.Buffer": ["node:buffer", "Buffer"],
"globalThis.Buffer": ["node:buffer", "Buffer"],
Expand All @@ -80,10 +87,17 @@ export const hybridNodePlugin: Plugin = {
name: "nitro:cloudflare:hybrid-node-compat",
resolveId(id) {
if (id.startsWith("cloudflare:")) {
return { id, external: true };
return { id, external: true, moduleSideEffects: false };
}
if (id.startsWith("#workerd/node:")) {
return { id: id.slice("#workerd/".length), external: true };
return {
id: id.slice("#workerd/".length),
external: true,
moduleSideEffects: false,
};
}
if (id.startsWith(presetRuntimeDir)) {
return { id, moduleSideEffects: false };
}
},
};
5 changes: 3 additions & 2 deletions src/presets/cloudflare/unenv/runtime/async_hooks.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// https://github.com/cloudflare/workerd/blob/main/src/node/async_hooks.ts
// https://github.com/cloudflare/workers-sdk/blob/main/packages/unenv-preset/src/runtime/node/async_hooks/index.ts

import workerdAsyncHooks from "#workerd/node:async_hooks";
Expand All @@ -21,11 +22,11 @@ export {
export const { AsyncLocalStorage, AsyncResource } = workerdAsyncHooks;

export default {
AsyncLocalStorage,
AsyncResource,
asyncWrapProviders,
createHook,
executionAsyncId,
executionAsyncResource,
triggerAsyncId,
AsyncLocalStorage,
AsyncResource,
};
71 changes: 71 additions & 0 deletions src/presets/cloudflare/unenv/runtime/console.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// https://github.com/cloudflare/workers-sdk/blob/main/packages/unenv-preset/src/runtime/node/console/index.ts

import workerdConsole from "#workerd/node:console";

import {
Console,
_ignoreErrors,
_stderr,
_stderrErrorHandler,
_stdout,
_stdoutErrorHandler,
_times,
} from "unenv/node/console";

export {
Console,
_ignoreErrors,
_stderr,
_stderrErrorHandler,
_stdout,
_stdoutErrorHandler,
_times,
} from "unenv/node/console";

export const {
assert,
clear,
context,
count,
countReset,
createTask,
debug,
dir,
dirxml,
error,
group,
groupCollapsed,
groupEnd,
info,
log,
profile,
profileEnd,
table,
time,
timeEnd,
timeLog,
timeStamp,
trace,
warn,
} = workerdConsole;

const consolePolyfill = {
Console,
_ignoreErrors,
_stderr,
_stderrErrorHandler,
_stdout,
_stdoutErrorHandler,
_times,
};

const consoleModule = /*@__PURE__*/ new Proxy(workerdConsole, {
get(target, prop) {
if (Reflect.has(target, prop)) {
return Reflect.get(target, prop);
}
return Reflect.get(consolePolyfill, prop);
},
});

export default consoleModule;
4 changes: 2 additions & 2 deletions src/presets/cloudflare/unenv/runtime/crypto.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// https://github.com/cloudflare/workerd/blob/main/src/node/crypto.ts
// https://github.com/cloudflare/workers-sdk/blob/main/packages/unenv-preset/src/runtime/node/crypto/index.ts

import workerdCrypto from "#workerd/node:crypto";
Expand Down Expand Up @@ -100,6 +101,7 @@ export const {
setFips,
subtle,
timingSafeEqual,
fips,
} = workerdCrypto;

export const getRandomValues = workerdCrypto.getRandomValues.bind(
Expand All @@ -113,8 +115,6 @@ export const webcrypto = {
subtle,
};

const fips = workerdCrypto.fips;

export default {
Certificate,
Cipher,
Expand Down
110 changes: 110 additions & 0 deletions src/presets/cloudflare/unenv/runtime/module.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// https://github.com/cloudflare/workerd/blob/main/src/node/module.ts
// https://github.com/cloudflare/workers-sdk/blob/main/packages/unenv-preset/src/runtime/node/module/index.ts

import workerdModule from "#workerd/node:module";

import { notImplemented } from "unenv/_internal/utils";

import {
constants,
enableCompileCache,
findSourceMap,
getCompileCacheDir,
globalPaths,
Module,
register,
runMain,
SourceMap,
syncBuiltinESMExports,
wrap,
flushCompileCache,
stripTypeScriptTypes,
wrapper,
_readPackage,
_stat,
_cache,
_debug,
_extensions,
_findPath,
_initPaths,
_load,
_nodeModulePaths,
_pathCache,
_preloadModules,
_resolveFilename,
_resolveLookupPaths,
} from "unenv/node/module";

export {
Module,
SourceMap,
constants,
enableCompileCache,
findSourceMap,
getCompileCacheDir,
globalPaths,
register,
runMain,
syncBuiltinESMExports,
wrap,
flushCompileCache,
stripTypeScriptTypes,
wrapper,
_cache,
_extensions,
_debug,
_pathCache,
_findPath,
_initPaths,
_load,
_nodeModulePaths,
_preloadModules,
_resolveFilename,
_resolveLookupPaths,
_readPackage,
_stat,
} from "unenv/node/module";

export const { builtinModules, isBuiltin } = workerdModule;

export const createRequire = (file) => {
return Object.assign(workerdModule.createRequire(file), {
resolve: Object.assign(notImplemented("module.require.resolve"), {
paths: notImplemented("module.require.resolve.paths"),
}),
cache: Object.create(null),
extensions: _extensions,
main: undefined,
});
};

export default {
Module,
SourceMap,
builtinModules,
enableCompileCache,
constants,
createRequire,
findSourceMap,
getCompileCacheDir,
globalPaths,
isBuiltin,
register,
runMain,
syncBuiltinESMExports,
wrap,
flushCompileCache,
stripTypeScriptTypes,
wrapper,
_cache,
_extensions,
_debug,
_pathCache,
_findPath,
_initPaths,
_load,
_nodeModulePaths,
_preloadModules,
_resolveFilename,
_resolveLookupPaths,
};
76 changes: 76 additions & 0 deletions src/presets/cloudflare/unenv/runtime/perf_hooks.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// https://github.com/unjs/unenv/blob/main/src/runtime/node/perf_hooks.ts

import {
constants,
createHistogram,
monitorEventLoopDelay,
Performance,
PerformanceEntry,
PerformanceMark,
PerformanceMeasure,
PerformanceObserver,
PerformanceObserverEntryList,
PerformanceResourceTiming,
performance as unenvPerformance,
} from "unenv/node/perf_hooks";

export {
Performance,
PerformanceEntry,
PerformanceMark,
PerformanceMeasure,
PerformanceObserverEntryList,
PerformanceObserver,
PerformanceResourceTiming,
constants,
createHistogram,
monitorEventLoopDelay,
} from "unenv/node/perf_hooks";

const workerdGlobalPerformance = globalThis["perf" + "ormance"];

export const performance = /*@__PURE__*/ Object.assign(
workerdGlobalPerformance,
{
addEventListener: unenvPerformance.addEventListener.bind(unenvPerformance),
clearMarks: unenvPerformance.clearMarks.bind(unenvPerformance),
clearMeasures: unenvPerformance.clearMeasures.bind(unenvPerformance),
clearResourceTimings:
unenvPerformance.clearResourceTimings.bind(unenvPerformance),
dispatchEvent: unenvPerformance.dispatchEvent.bind(unenvPerformance),
eventLoopUtilization:
unenvPerformance.eventLoopUtilization.bind(unenvPerformance),
getEntries: unenvPerformance.getEntries.bind(unenvPerformance),
getEntriesByName: unenvPerformance.getEntriesByName.bind(unenvPerformance),
getEntriesByType: unenvPerformance.getEntriesByType.bind(unenvPerformance),
mark: unenvPerformance.mark.bind(unenvPerformance),
markResourceTiming:
unenvPerformance.markResourceTiming.bind(unenvPerformance),
measure: unenvPerformance.measure.bind(unenvPerformance),
nodeTiming: { ...unenvPerformance.nodeTiming },
onresourcetimingbufferfull:
typeof unenvPerformance.onresourcetimingbufferfull === "function"
? unenvPerformance.onresourcetimingbufferfull.bind(unenvPerformance)
: unenvPerformance.onresourcetimingbufferfull,
removeEventListener:
unenvPerformance.removeEventListener.bind(unenvPerformance),
setResourceTimingBufferSize:
unenvPerformance.setResourceTimingBufferSize.bind(unenvPerformance),
timerify: unenvPerformance.timerify.bind(unenvPerformance),
toJSON: unenvPerformance.toJSON.bind(unenvPerformance),
}
);

export default {
Performance,
PerformanceEntry,
PerformanceMark,
PerformanceMeasure,
PerformanceObserverEntryList,
PerformanceObserver,
PerformanceResourceTiming,
constants,
createHistogram,
monitorEventLoopDelay,
performance,
};
Loading
Loading