mirror of
https://github.com/oven-sh/bun
synced 2026-02-02 23:18:47 +00:00
Compare commits
5 Commits
claude/sql
...
dave/node_
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e665b7dae | ||
|
|
9f63d55efc | ||
|
|
c2d1389dbc | ||
|
|
87067e528d | ||
|
|
cf9eff9d5d |
@@ -198,7 +198,6 @@ const ServerEntryPoint = bun.bundler.ServerEntryPoint;
|
||||
const js_printer = bun.js_printer;
|
||||
const js_parser = bun.js_parser;
|
||||
const js_ast = bun.JSAst;
|
||||
const NodeFallbackModules = @import("../../node_fallbacks.zig");
|
||||
const ImportKind = ast.ImportKind;
|
||||
const Analytics = @import("../../analytics/analytics_thread.zig");
|
||||
const ZigString = bun.JSC.ZigString;
|
||||
|
||||
@@ -25,7 +25,6 @@ const ServerEntryPoint = bun.bundler.ServerEntryPoint;
|
||||
const js_printer = bun.js_printer;
|
||||
const js_parser = bun.js_parser;
|
||||
const js_ast = bun.JSAst;
|
||||
const NodeFallbackModules = @import("../../node_fallbacks.zig");
|
||||
const ImportKind = ast.ImportKind;
|
||||
const Analytics = @import("../../analytics/analytics_thread.zig");
|
||||
const ZigString = bun.JSC.ZigString;
|
||||
|
||||
@@ -25,7 +25,6 @@ const ServerEntryPoint = bun.bundler.ServerEntryPoint;
|
||||
const js_printer = bun.js_printer;
|
||||
const js_parser = bun.js_parser;
|
||||
const js_ast = bun.JSAst;
|
||||
const NodeFallbackModules = @import("../../node_fallbacks.zig");
|
||||
const ImportKind = ast.ImportKind;
|
||||
const Analytics = @import("../../analytics/analytics_thread.zig");
|
||||
const ZigString = bun.JSC.ZigString;
|
||||
|
||||
@@ -31,7 +31,7 @@ const ServerEntryPoint = bun.bundler.ServerEntryPoint;
|
||||
const js_printer = bun.js_printer;
|
||||
const js_parser = bun.js_parser;
|
||||
const js_ast = bun.JSAst;
|
||||
const NodeFallbackModules = @import("../node_fallbacks.zig");
|
||||
const node_fallbacks = @import("../node_fallbacks.zig");
|
||||
const ImportKind = ast.ImportKind;
|
||||
const Analytics = @import("../analytics/analytics_thread.zig");
|
||||
const ZigString = bun.JSC.ZigString;
|
||||
@@ -2082,7 +2082,7 @@ pub const VirtualMachine = struct {
|
||||
ret.result = null;
|
||||
ret.path = specifier;
|
||||
return;
|
||||
} else if (strings.hasPrefixComptime(specifier, "/bun-vfs/node_modules/")) {
|
||||
} else if (strings.hasPrefixComptime(specifier, node_fallbacks.prefix)) {
|
||||
ret.result = null;
|
||||
ret.path = specifier;
|
||||
return;
|
||||
|
||||
@@ -30,7 +30,7 @@ const ServerEntryPoint = bun.bundler.ServerEntryPoint;
|
||||
const js_printer = bun.js_printer;
|
||||
const js_parser = bun.js_parser;
|
||||
const js_ast = bun.JSAst;
|
||||
const NodeFallbackModules = @import("../node_fallbacks.zig");
|
||||
const node_fallbacks = @import("../node_fallbacks.zig");
|
||||
const ImportKind = ast.ImportKind;
|
||||
const Analytics = @import("../analytics/analytics_thread.zig");
|
||||
const ZigString = bun.JSC.ZigString;
|
||||
@@ -485,8 +485,7 @@ pub const RuntimeTranspilerStore = struct {
|
||||
else => {},
|
||||
}
|
||||
|
||||
// this should be a cheap lookup because 24 bytes == 8 * 3 so it's read 3 machine words
|
||||
const is_node_override = strings.hasPrefixComptime(specifier, "/bun-vfs/node_modules/");
|
||||
const is_node_override = strings.hasPrefixComptime(specifier, node_fallbacks.prefix);
|
||||
|
||||
const macro_remappings = if (vm.macro_mode or !vm.has_any_macro_remappings or is_node_override)
|
||||
MacroRemap{}
|
||||
@@ -539,7 +538,7 @@ pub const RuntimeTranspilerStore = struct {
|
||||
}
|
||||
|
||||
if (is_node_override) {
|
||||
if (NodeFallbackModules.contentsFromPath(specifier)) |code| {
|
||||
if (node_fallbacks.contentsFromPath(specifier)) |code| {
|
||||
const fallback_path = Fs.Path.initWithNamespace(specifier, "node");
|
||||
fallback_source = logger.Source{ .path = fallback_path, .contents = code, .key_path = fallback_path };
|
||||
parse_options.virtual_source = &fallback_source;
|
||||
@@ -1659,7 +1658,7 @@ pub const ModuleLoader = struct {
|
||||
}
|
||||
|
||||
// this should be a cheap lookup because 24 bytes == 8 * 3 so it's read 3 machine words
|
||||
const is_node_override = strings.hasPrefixComptime(specifier, "/bun-vfs/node_modules/");
|
||||
const is_node_override = strings.hasPrefixComptime(specifier, node_fallbacks.prefix);
|
||||
|
||||
const macro_remappings = if (jsc_vm.macro_mode or !jsc_vm.has_any_macro_remappings or is_node_override)
|
||||
MacroRemap{}
|
||||
@@ -1707,7 +1706,7 @@ pub const ModuleLoader = struct {
|
||||
}
|
||||
|
||||
if (is_node_override) {
|
||||
if (NodeFallbackModules.contentsFromPath(specifier)) |code| {
|
||||
if (node_fallbacks.contentsFromPath(specifier)) |code| {
|
||||
const fallback_path = Fs.Path.initWithNamespace(specifier, "node");
|
||||
fallback_source = logger.Source{ .path = fallback_path, .contents = code, .key_path = fallback_path };
|
||||
parse_options.virtual_source = &fallback_source;
|
||||
|
||||
@@ -42,7 +42,7 @@ const isPackagePath = _resolver.isPackagePath;
|
||||
const Css = @import("css_scanner.zig");
|
||||
const DotEnv = @import("./env_loader.zig");
|
||||
const Lock = @import("./lock.zig").Lock;
|
||||
const NodeFallbackModules = @import("./node_fallbacks.zig");
|
||||
const node_fallbacks = @import("./node_fallbacks.zig");
|
||||
const CacheEntry = @import("./cache.zig").FsCacheEntry;
|
||||
const Analytics = @import("./analytics/analytics_thread.zig");
|
||||
const URL = @import("./url.zig").URL;
|
||||
@@ -1326,7 +1326,7 @@ pub const Bundler = struct {
|
||||
}
|
||||
|
||||
if (strings.eqlComptime(path.namespace, "node")) {
|
||||
if (NodeFallbackModules.contentsFromPath(path.text)) |code| {
|
||||
if (node_fallbacks.contentsFromPath(path.text)) |code| {
|
||||
break :brk logger.Source.initPathString(path.text, code);
|
||||
}
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ const DebugLogs = _resolver.DebugLogs;
|
||||
const Router = @import("../router.zig");
|
||||
const isPackagePath = _resolver.isPackagePath;
|
||||
const Lock = @import("../lock.zig").Lock;
|
||||
const NodeFallbackModules = @import("../node_fallbacks.zig");
|
||||
const node_fallbacks = @import("../node_fallbacks.zig");
|
||||
const CacheEntry = @import("../cache.zig").Fs.Entry;
|
||||
const Analytics = @import("../analytics/analytics_thread.zig");
|
||||
const URL = @import("../url.zig").URL;
|
||||
@@ -2777,7 +2777,7 @@ pub const ParseTask = struct {
|
||||
|
||||
if (strings.eqlComptime(file_path.namespace, "node"))
|
||||
break :brk CacheEntry{
|
||||
.contents = NodeFallbackModules.contentsFromPath(file_path.text) orelse "",
|
||||
.contents = node_fallbacks.contentsFromPath(file_path.text) orelse "",
|
||||
};
|
||||
|
||||
break :brk resolver.caches.fs.readFileWithAllocator(
|
||||
@@ -2874,6 +2874,7 @@ pub const ParseTask = struct {
|
||||
opts.features.minify_syntax = bundler.options.minify_syntax;
|
||||
opts.features.minify_identifiers = bundler.options.minify_identifiers;
|
||||
opts.features.emit_decorator_metadata = bundler.options.emit_decorator_metadata;
|
||||
opts.target = bundler.options.target;
|
||||
|
||||
opts.tree_shaking = if (source.index.isRuntime()) true else bundler.options.tree_shaking;
|
||||
opts.module_type = task.module_type;
|
||||
@@ -10430,19 +10431,27 @@ pub const LinkerContext = struct {
|
||||
},
|
||||
) catch unreachable;
|
||||
}
|
||||
} else if (c.resolver.opts.target == .browser and JSC.HardcodedModule.Aliases.has(next_source.path.pretty, .browser)) {
|
||||
} else if (c.resolver.opts.target == .browser and bun.strings.hasPrefixComptime(next_source.path.text, node_fallbacks.prefix)) {
|
||||
// Remove the "browser polyfill" text which is appended to all of these
|
||||
const path_len = std.mem.indexOfScalar(u8, next_source.path.pretty, ' ') orelse
|
||||
next_source.path.pretty.len;
|
||||
const path = next_source.path.pretty[0..path_len];
|
||||
|
||||
c.log.addRangeErrorFmtWithNote(
|
||||
source,
|
||||
r,
|
||||
c.allocator,
|
||||
|
||||
"Browser polyfill for module \"{s}\" doesn't have a matching export named \"{s}\"",
|
||||
.{
|
||||
next_source.path.pretty,
|
||||
named_import.alias.?,
|
||||
},
|
||||
"Bun's bundler defaults to browser builds instead of node or bun builds. If you want to use node or bun builds, you can set the target to \"node\" or \"bun\" in the bundler options.",
|
||||
.{},
|
||||
r,
|
||||
.{ path, named_import.alias.? },
|
||||
|
||||
"Bun's bundler defaults to browser builds. To bundle for Bun or Node.js, pass {s}",
|
||||
.{switch (bun.CLI.Cli.cmd == .BuildCommand) {
|
||||
true => "'--target=bun' or '--target=node'",
|
||||
false => "'target: \"bun\"' or 'target: \"node\"",
|
||||
}},
|
||||
|
||||
Logger.Range.None,
|
||||
) catch unreachable;
|
||||
} else {
|
||||
c.log.addRangeErrorFmt(
|
||||
@@ -10463,7 +10472,6 @@ pub const LinkerContext = struct {
|
||||
result = .{ .kind = .probably_typescript_type };
|
||||
},
|
||||
.found => {
|
||||
|
||||
// If there are multiple ambiguous results due to use of "export * from"
|
||||
// statements, trace them all to see if they point to different things.
|
||||
for (potentially_ambiguous_export_star_refs) |*ambiguous_tracker| {
|
||||
|
||||
10
src/fs.zig
10
src/fs.zig
@@ -1851,16 +1851,6 @@ pub const Path = struct {
|
||||
};
|
||||
}
|
||||
|
||||
pub fn initWithNamespaceVirtual(comptime text: string, comptime namespace: string, comptime package: string) Path {
|
||||
return Path{
|
||||
.pretty = comptime "node:" ++ package,
|
||||
.is_symlink = true,
|
||||
.text = text,
|
||||
.namespace = namespace,
|
||||
.name = PathName.init(text),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn isBefore(a: *Path, b: Path) bool {
|
||||
return a.namespace > b.namespace ||
|
||||
(a.namespace == b.namespace and (a.text < b.text ||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Reimplementation of https://nodejs.org/api/events.html
|
||||
|
||||
// Reference: https://github.com/nodejs/node/blob/main/lib/events.js
|
||||
// @ts-nocheck TODO: fix type checking of this
|
||||
|
||||
const { throwNotImplemented } = require("internal/shared");
|
||||
|
||||
const SymbolFor = Symbol.for;
|
||||
@@ -519,7 +520,7 @@ function validateBoolean(value, name) {
|
||||
if (typeof value !== "boolean") throw ERR_INVALID_ARG_TYPE(name, "boolean", value);
|
||||
}
|
||||
|
||||
let AsyncResource = null;
|
||||
let AsyncResource: null | typeof import("node:async_hooks").AsyncResource = null;
|
||||
|
||||
function getMaxListeners(emitterOrTarget) {
|
||||
// TODO: apparently EventTarget in Node can have a max number of listeners?
|
||||
@@ -565,7 +566,7 @@ class EventEmitterAsyncResource extends EventEmitter {
|
||||
var { captureRejections = false, triggerAsyncId, name = new.target.name, requireManualDestroy } = options || {};
|
||||
super({ captureRejections });
|
||||
this.triggerAsyncId = triggerAsyncId ?? 0;
|
||||
this.asyncResource = new AsyncResource(name, { triggerAsyncId, requireManualDestroy });
|
||||
this.asyncResource = new AsyncResource!(name, { triggerAsyncId, requireManualDestroy });
|
||||
}
|
||||
|
||||
emit(...args) {
|
||||
|
||||
@@ -5537,6 +5537,9 @@ pub const Expr = struct {
|
||||
/// Expressions that can be moved are those that do not have side
|
||||
/// effects on their own. This is used to determine what can be moved
|
||||
/// outside of a module wrapper (__esm/__commonJS).
|
||||
///
|
||||
/// TODO: this should be replaced with js_parser canBeRemovedIfUnused
|
||||
/// since it is just code duplication of that.
|
||||
pub fn canBeMoved(data: Expr.Data) bool {
|
||||
return switch (data) {
|
||||
.e_class => |class| class.canBeMoved(),
|
||||
@@ -5548,7 +5551,7 @@ pub const Expr = struct {
|
||||
.e_boolean,
|
||||
.e_null,
|
||||
.e_undefined,
|
||||
// .e_reg_exp,
|
||||
.e_reg_exp,
|
||||
.e_big_int,
|
||||
.e_string,
|
||||
.e_inlined_enum,
|
||||
@@ -5556,10 +5559,41 @@ pub const Expr = struct {
|
||||
.e_utf8_string,
|
||||
=> true,
|
||||
|
||||
// Treat pure call and construct expressions as movable
|
||||
// since @__PURE__ implies that there are no side effects.
|
||||
// We will need to check the arguments for movability.
|
||||
inline .e_new, .e_call => |call| {
|
||||
if (call.can_be_unwrapped_if_unused) {
|
||||
for (call.args.slice()) |arg| {
|
||||
if (!arg.data.canBeMoved())
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
.e_template => |template| template.parts.len == 0,
|
||||
|
||||
.e_array => |array| array.was_originally_macro,
|
||||
.e_object => |object| object.was_originally_macro,
|
||||
.e_array => |array| {
|
||||
if (array.was_originally_macro)
|
||||
return true;
|
||||
|
||||
// Treat arrays with movable values as movable too
|
||||
for (array.slice()) |item| {
|
||||
if (!item.canBeMoved())
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
.e_object => |object| {
|
||||
if (object.was_originally_macro)
|
||||
return true;
|
||||
|
||||
// TODO: Treat objects with movable keys and values as movable too
|
||||
return false;
|
||||
},
|
||||
|
||||
// TODO: experiment with allowing some e_binary, e_unary, e_if as movable
|
||||
|
||||
|
||||
@@ -76,7 +76,6 @@ pub const StringHashMap = bun.StringHashMap;
|
||||
pub const AutoHashMap = std.AutoHashMap;
|
||||
const StringHashMapUnmanaged = bun.StringHashMapUnmanaged;
|
||||
const ObjectPool = @import("./pool.zig").ObjectPool;
|
||||
const NodeFallbackModules = @import("./node_fallbacks.zig");
|
||||
|
||||
const DeferredImportNamespace = struct {
|
||||
namespace: LocRef,
|
||||
@@ -502,6 +501,51 @@ pub fn locAfterOp(e: E.Binary) logger.Loc {
|
||||
}
|
||||
const ExportsStringName = "exports";
|
||||
|
||||
// If this is one of a few specific built-ins, make the default value refer to
|
||||
// the *namespace* instead of the default export. This allows dot properties to
|
||||
// note property accesses on this to make tree shaking more effective. We can
|
||||
// only enable it on built-in modules that have a default export that is
|
||||
//
|
||||
// Bun's browser polyfills are specially designed to take advantage of this
|
||||
// optimization to make bundles smaller.
|
||||
//
|
||||
// import path from 'node:path'
|
||||
// -->
|
||||
// import * as path from 'node:path'
|
||||
//
|
||||
// For example, bundling this code only includes a dependency on `function join`
|
||||
// and not on the entire module.
|
||||
//
|
||||
// import path from 'node:path'
|
||||
// console.log(path.join);
|
||||
//
|
||||
const rewrite_default_to_star_map = bun.ComptimeStringMap(void, kvs: {
|
||||
const node_builtins = .{
|
||||
"buffer",
|
||||
"constants",
|
||||
"constants",
|
||||
"crypto",
|
||||
"domain",
|
||||
"http",
|
||||
"https",
|
||||
"path",
|
||||
"sys",
|
||||
"util",
|
||||
"net",
|
||||
"os",
|
||||
"punycode",
|
||||
"querystring",
|
||||
};
|
||||
var kvs: [node_builtins.len * 2]struct { []const u8, void } = undefined;
|
||||
var i = 0;
|
||||
for (node_builtins) |pkg| {
|
||||
kvs[i] = .{ pkg, {} };
|
||||
kvs[i + 1] = .{ "node:" ++ pkg, {} };
|
||||
i += 2;
|
||||
}
|
||||
break :kvs kvs;
|
||||
});
|
||||
|
||||
const TransposeState = struct {
|
||||
is_await_target: bool = false,
|
||||
is_then_catch_target: bool = false,
|
||||
@@ -3100,6 +3144,8 @@ pub const Parser = struct {
|
||||
|
||||
transform_only: bool = false,
|
||||
|
||||
target: options.Target = .bun,
|
||||
|
||||
pub fn hashForRuntimeTranspiler(this: *const Options, hasher: *std.hash.Wyhash, did_use_jsx: bool) void {
|
||||
bun.assert(!this.bundle);
|
||||
|
||||
@@ -9140,6 +9186,11 @@ fn NewParser_(
|
||||
stmt.import_record_index = p.addImportRecord(.stmt, path.loc, path.text);
|
||||
p.import_records.items[stmt.import_record_index].was_originally_bare_import = was_originally_bare_import;
|
||||
|
||||
// See the comment on `rewrite_default_to_star_map`
|
||||
const should_rewrite_default_to_star = p.options.bundle and
|
||||
p.options.target == .browser and
|
||||
rewrite_default_to_star_map.has(path.text);
|
||||
|
||||
if (stmt.star_name_loc) |star| {
|
||||
const name = p.loadNameFromRef(stmt.namespace_ref);
|
||||
|
||||
@@ -9151,11 +9202,38 @@ fn NewParser_(
|
||||
.import_record_index = stmt.import_record_index,
|
||||
}) catch unreachable;
|
||||
}
|
||||
} else {
|
||||
|
||||
if (should_rewrite_default_to_star) {
|
||||
if (stmt.default_name) |default| {
|
||||
// Alias the namespace and the default import without using a new symbol
|
||||
const default_name = p.loadNameFromRef(default.ref.?);
|
||||
_ = try p.insertSymbolIntoCurrentScope(
|
||||
.import,
|
||||
default.loc,
|
||||
stmt.namespace_ref,
|
||||
default_name,
|
||||
false,
|
||||
);
|
||||
stmt.default_name = null;
|
||||
}
|
||||
}
|
||||
} else init_namespace_ref: {
|
||||
if (should_rewrite_default_to_star) {
|
||||
if (stmt.default_name) |default| {
|
||||
// Create a namespace ref as the default
|
||||
const default_name = p.loadNameFromRef(default.ref.?);
|
||||
const ref = try p.declareSymbol(.import, default.loc, default_name);
|
||||
stmt.namespace_ref = ref;
|
||||
stmt.star_name_loc = default.loc;
|
||||
stmt.default_name = null;
|
||||
break :init_namespace_ref;
|
||||
}
|
||||
}
|
||||
|
||||
var path_name = fs.PathName.init(strings.append(p.allocator, "import_", path.text) catch unreachable);
|
||||
const name = try path_name.nonUniqueNameString(p.allocator);
|
||||
stmt.namespace_ref = try p.newSymbol(.other, name);
|
||||
var scope: *Scope = p.current_scope;
|
||||
const scope: *Scope = p.current_scope;
|
||||
try scope.generated.push(p.allocator, stmt.namespace_ref);
|
||||
}
|
||||
|
||||
@@ -12672,7 +12750,6 @@ fn NewParser_(
|
||||
// p.checkForNonBMPCodePoint(loc, name)
|
||||
|
||||
if (comptime !is_generated) {
|
||||
|
||||
// Forbid declaring a symbol with a reserved word in strict mode
|
||||
if (p.isStrictMode() and name.ptr != arguments_str.ptr and js_lexer.StrictModeReservedWords.has(name)) {
|
||||
try p.markStrictModeFeature(.reserved_word, js_lexer.rangeOfIdentifier(p.source, loc), name);
|
||||
@@ -12680,8 +12757,12 @@ fn NewParser_(
|
||||
}
|
||||
|
||||
// Allocate a new symbol
|
||||
var ref = try p.newSymbol(kind, name);
|
||||
const ref = try p.newSymbol(kind, name);
|
||||
return p.insertSymbolIntoCurrentScope(kind, loc, ref, name, is_generated);
|
||||
}
|
||||
|
||||
fn insertSymbolIntoCurrentScope(p: *P, kind: Symbol.Kind, loc: logger.Loc, ref: Ref, name: string, comptime is_generated: bool) !Ref {
|
||||
var ref_to_use = ref;
|
||||
const scope = p.current_scope;
|
||||
const entry = try scope.members.getOrPut(p.allocator, name);
|
||||
if (entry.found_existing) {
|
||||
@@ -12696,7 +12777,7 @@ fn NewParser_(
|
||||
},
|
||||
|
||||
.keep_existing => {
|
||||
ref = existing.ref;
|
||||
ref_to_use = existing.ref;
|
||||
},
|
||||
|
||||
.replace_with_new => {
|
||||
@@ -12709,12 +12790,12 @@ fn NewParser_(
|
||||
},
|
||||
|
||||
.become_private_get_set_pair => {
|
||||
ref = existing.ref;
|
||||
ref_to_use = existing.ref;
|
||||
symbol.kind = .private_get_set_pair;
|
||||
},
|
||||
|
||||
.become_private_static_get_set_pair => {
|
||||
ref = existing.ref;
|
||||
ref_to_use = existing.ref;
|
||||
symbol.kind = .private_static_get_set_pair;
|
||||
},
|
||||
|
||||
@@ -12725,9 +12806,9 @@ fn NewParser_(
|
||||
}
|
||||
}
|
||||
entry.key_ptr.* = name;
|
||||
entry.value_ptr.* = js_ast.Scope.Member{ .ref = ref, .loc = loc };
|
||||
entry.value_ptr.* = js_ast.Scope.Member{ .ref = ref_to_use, .loc = loc };
|
||||
if (comptime is_generated) {
|
||||
try p.module_scope.generated.push(p.allocator, ref);
|
||||
try p.module_scope.generated.push(p.allocator, ref_to_use);
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
@@ -20758,7 +20839,7 @@ fn NewParser_(
|
||||
{
|
||||
p.emitted_namespace_vars.putNoClobber(allocator, name_ref, {}) catch bun.outOfMemory();
|
||||
|
||||
var decls = allocator.alloc(G.Decl, 1) catch bun.outOfMemory();
|
||||
const decls = allocator.alloc(G.Decl, 1) catch bun.outOfMemory();
|
||||
decls[0] = G.Decl{ .binding = p.b(B.Identifier{ .ref = name_ref }, name_loc) };
|
||||
|
||||
if (p.enclosing_namespace_arg_ref == null) {
|
||||
|
||||
@@ -65,8 +65,8 @@ const ascii_only_always_on_unless_minifying = true;
|
||||
fn formatUnsignedIntegerBetween(comptime len: u16, buf: *[len]u8, val: u64) void {
|
||||
comptime var i: u16 = len;
|
||||
var remainder = val;
|
||||
// Write out the number from the end to the front
|
||||
|
||||
// Write out the number from the end to the front
|
||||
inline while (i > 0) {
|
||||
comptime i -= 1;
|
||||
buf[comptime i] = @as(u8, @intCast((remainder % 10))) + '0';
|
||||
@@ -536,6 +536,8 @@ pub const Options = struct {
|
||||
minify_whitespace: bool = false,
|
||||
minify_identifiers: bool = false,
|
||||
minify_syntax: bool = false,
|
||||
print_dce_annotations: bool = true,
|
||||
|
||||
transform_only: bool = false,
|
||||
inline_require_and_import_errors: bool = true,
|
||||
has_run_symbol_renamer: bool = false,
|
||||
@@ -544,7 +546,7 @@ pub const Options = struct {
|
||||
|
||||
module_type: options.OutputFormat = .preserve,
|
||||
|
||||
/// Used for cross-module inlining of import items when bundling
|
||||
// /// Used for cross-module inlining of import items when bundling
|
||||
// const_values: Ast.ConstValuesMap = .{},
|
||||
ts_enums: Ast.TsEnumsMap = .{},
|
||||
|
||||
@@ -2146,8 +2148,10 @@ fn NewPrinter(
|
||||
return;
|
||||
}
|
||||
|
||||
// noop for now
|
||||
pub inline fn printPure(_: *Printer) void {}
|
||||
pub inline fn printPure(p: *Printer) void {
|
||||
if (Environment.allow_assert) assert(p.options.print_dce_annotations);
|
||||
p.print("/* @__PURE__ */");
|
||||
}
|
||||
|
||||
pub fn printQuotedUTF8(p: *Printer, str: string, allow_backtick: bool) void {
|
||||
const quote = if (comptime !is_json)
|
||||
@@ -2353,7 +2357,7 @@ fn NewPrinter(
|
||||
}
|
||||
},
|
||||
.e_new => |e| {
|
||||
const has_pure_comment = e.can_be_unwrapped_if_unused;
|
||||
const has_pure_comment = e.can_be_unwrapped_if_unused and p.options.print_dce_annotations;
|
||||
const wrap = level.gte(.call) or (has_pure_comment and level.gte(.postfix));
|
||||
|
||||
if (wrap) {
|
||||
@@ -2403,7 +2407,7 @@ fn NewPrinter(
|
||||
wrap = true;
|
||||
}
|
||||
|
||||
const has_pure_comment = e.can_be_unwrapped_if_unused;
|
||||
const has_pure_comment = e.can_be_unwrapped_if_unused and p.options.print_dce_annotations;
|
||||
if (has_pure_comment and level.gte(.postfix)) {
|
||||
wrap = true;
|
||||
}
|
||||
|
||||
@@ -1 +1,22 @@
|
||||
export * from "assert";
|
||||
import assert from "assert";
|
||||
export const AssertionError = assert.AssertionError;
|
||||
export const CallTracker = assert.CallTracker;
|
||||
export const deepEqual = assert.deepEqual;
|
||||
export const deepStrictEqual = assert.deepStrictEqual;
|
||||
export const doesNotMatch = assert.doesNotMatch;
|
||||
export const doesNotReject = assert.doesNotReject;
|
||||
export const doesNotThrow = assert.doesNotThrow;
|
||||
export const equal = assert.equal;
|
||||
export const fail = assert.fail;
|
||||
export const ifError = assert.ifError;
|
||||
export const match = assert.match;
|
||||
export const notDeepEqual = assert.notDeepEqual;
|
||||
export const notDeepStrictEqual = assert.notDeepStrictEqual;
|
||||
export const notEqual = assert.notEqual;
|
||||
export const notStrictEqual = assert.notStrictEqual;
|
||||
export const ok = assert.ok;
|
||||
export const rejects = assert.rejects;
|
||||
export const strict = assert.strict;
|
||||
export const strictEqual = assert.strictEqual;
|
||||
export const throws = assert.throws;
|
||||
export default assert;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1 +1,208 @@
|
||||
export * from "constants-browserify";
|
||||
// equivalent to browserify constants module, converted to an ES module
|
||||
export const O_RDONLY = 0;
|
||||
export const O_WRONLY = 1;
|
||||
export const O_RDWR = 2;
|
||||
export const S_IFMT = 61440;
|
||||
export const S_IFREG = 32768;
|
||||
export const S_IFDIR = 16384;
|
||||
export const S_IFCHR = 8192;
|
||||
export const S_IFBLK = 24576;
|
||||
export const S_IFIFO = 4096;
|
||||
export const S_IFLNK = 40960;
|
||||
export const S_IFSOCK = 49152;
|
||||
export const O_CREAT = 512;
|
||||
export const O_EXCL = 2048;
|
||||
export const O_NOCTTY = 131072;
|
||||
export const O_TRUNC = 1024;
|
||||
export const O_APPEND = 8;
|
||||
export const O_DIRECTORY = 1048576;
|
||||
export const O_NOFOLLOW = 256;
|
||||
export const O_SYNC = 128;
|
||||
export const O_SYMLINK = 2097152;
|
||||
export const O_NONBLOCK = 4;
|
||||
export const S_IRWXU = 448;
|
||||
export const S_IRUSR = 256;
|
||||
export const S_IWUSR = 128;
|
||||
export const S_IXUSR = 64;
|
||||
export const S_IRWXG = 56;
|
||||
export const S_IRGRP = 32;
|
||||
export const S_IWGRP = 16;
|
||||
export const S_IXGRP = 8;
|
||||
export const S_IRWXO = 7;
|
||||
export const S_IROTH = 4;
|
||||
export const S_IWOTH = 2;
|
||||
export const S_IXOTH = 1;
|
||||
export const E2BIG = 7;
|
||||
export const EACCES = 13;
|
||||
export const EADDRINUSE = 48;
|
||||
export const EADDRNOTAVAIL = 49;
|
||||
export const EAFNOSUPPORT = 47;
|
||||
export const EAGAIN = 35;
|
||||
export const EALREADY = 37;
|
||||
export const EBADF = 9;
|
||||
export const EBADMSG = 94;
|
||||
export const EBUSY = 16;
|
||||
export const ECANCELED = 89;
|
||||
export const ECHILD = 10;
|
||||
export const ECONNABORTED = 53;
|
||||
export const ECONNREFUSED = 61;
|
||||
export const ECONNRESET = 54;
|
||||
export const EDEADLK = 11;
|
||||
export const EDESTADDRREQ = 39;
|
||||
export const EDOM = 33;
|
||||
export const EDQUOT = 69;
|
||||
export const EEXIST = 17;
|
||||
export const EFAULT = 14;
|
||||
export const EFBIG = 27;
|
||||
export const EHOSTUNREACH = 65;
|
||||
export const EIDRM = 90;
|
||||
export const EILSEQ = 92;
|
||||
export const EINPROGRESS = 36;
|
||||
export const EINTR = 4;
|
||||
export const EINVAL = 22;
|
||||
export const EIO = 5;
|
||||
export const EISCONN = 56;
|
||||
export const EISDIR = 21;
|
||||
export const ELOOP = 62;
|
||||
export const EMFILE = 24;
|
||||
export const EMLINK = 31;
|
||||
export const EMSGSIZE = 40;
|
||||
export const EMULTIHOP = 95;
|
||||
export const ENAMETOOLONG = 63;
|
||||
export const ENETDOWN = 50;
|
||||
export const ENETRESET = 52;
|
||||
export const ENETUNREACH = 51;
|
||||
export const ENFILE = 23;
|
||||
export const ENOBUFS = 55;
|
||||
export const ENODATA = 96;
|
||||
export const ENODEV = 19;
|
||||
export const ENOENT = 2;
|
||||
export const ENOEXEC = 8;
|
||||
export const ENOLCK = 77;
|
||||
export const ENOLINK = 97;
|
||||
export const ENOMEM = 12;
|
||||
export const ENOMSG = 91;
|
||||
export const ENOPROTOOPT = 42;
|
||||
export const ENOSPC = 28;
|
||||
export const ENOSR = 98;
|
||||
export const ENOSTR = 99;
|
||||
export const ENOSYS = 78;
|
||||
export const ENOTCONN = 57;
|
||||
export const ENOTDIR = 20;
|
||||
export const ENOTEMPTY = 66;
|
||||
export const ENOTSOCK = 38;
|
||||
export const ENOTSUP = 45;
|
||||
export const ENOTTY = 25;
|
||||
export const ENXIO = 6;
|
||||
export const EOPNOTSUPP = 102;
|
||||
export const EOVERFLOW = 84;
|
||||
export const EPERM = 1;
|
||||
export const EPIPE = 32;
|
||||
export const EPROTO = 100;
|
||||
export const EPROTONOSUPPORT = 43;
|
||||
export const EPROTOTYPE = 41;
|
||||
export const ERANGE = 34;
|
||||
export const EROFS = 30;
|
||||
export const ESPIPE = 29;
|
||||
export const ESRCH = 3;
|
||||
export const ESTALE = 70;
|
||||
export const ETIME = 101;
|
||||
export const ETIMEDOUT = 60;
|
||||
export const ETXTBSY = 26;
|
||||
export const EWOULDBLOCK = 35;
|
||||
export const EXDEV = 18;
|
||||
export const SIGHUP = 1;
|
||||
export const SIGINT = 2;
|
||||
export const SIGQUIT = 3;
|
||||
export const SIGILL = 4;
|
||||
export const SIGTRAP = 5;
|
||||
export const SIGABRT = 6;
|
||||
export const SIGIOT = 6;
|
||||
export const SIGBUS = 10;
|
||||
export const SIGFPE = 8;
|
||||
export const SIGKILL = 9;
|
||||
export const SIGUSR1 = 30;
|
||||
export const SIGSEGV = 11;
|
||||
export const SIGUSR2 = 31;
|
||||
export const SIGPIPE = 13;
|
||||
export const SIGALRM = 14;
|
||||
export const SIGTERM = 15;
|
||||
export const SIGCHLD = 20;
|
||||
export const SIGCONT = 19;
|
||||
export const SIGSTOP = 17;
|
||||
export const SIGTSTP = 18;
|
||||
export const SIGTTIN = 21;
|
||||
export const SIGTTOU = 22;
|
||||
export const SIGURG = 16;
|
||||
export const SIGXCPU = 24;
|
||||
export const SIGXFSZ = 25;
|
||||
export const SIGVTALRM = 26;
|
||||
export const SIGPROF = 27;
|
||||
export const SIGWINCH = 28;
|
||||
export const SIGIO = 23;
|
||||
export const SIGSYS = 12;
|
||||
export const SSL_OP_ALL = 2147486719;
|
||||
export const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = 262144;
|
||||
export const SSL_OP_CIPHER_SERVER_PREFERENCE = 4194304;
|
||||
export const SSL_OP_CISCO_ANYCONNECT = 32768;
|
||||
export const SSL_OP_COOKIE_EXCHANGE = 8192;
|
||||
export const SSL_OP_CRYPTOPRO_TLSEXT_BUG = 2147483648;
|
||||
export const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS = 2048;
|
||||
export const SSL_OP_EPHEMERAL_RSA = 0;
|
||||
export const SSL_OP_LEGACY_SERVER_CONNECT = 4;
|
||||
export const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER = 32;
|
||||
export const SSL_OP_MICROSOFT_SESS_ID_BUG = 1;
|
||||
export const SSL_OP_MSIE_SSLV2_RSA_PADDING = 0;
|
||||
export const SSL_OP_NETSCAPE_CA_DN_BUG = 536870912;
|
||||
export const SSL_OP_NETSCAPE_CHALLENGE_BUG = 2;
|
||||
export const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = 1073741824;
|
||||
export const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = 8;
|
||||
export const SSL_OP_NO_COMPRESSION = 131072;
|
||||
export const SSL_OP_NO_QUERY_MTU = 4096;
|
||||
export const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = 65536;
|
||||
export const SSL_OP_NO_SSLv2 = 16777216;
|
||||
export const SSL_OP_NO_SSLv3 = 33554432;
|
||||
export const SSL_OP_NO_TICKET = 16384;
|
||||
export const SSL_OP_NO_TLSv1 = 67108864;
|
||||
export const SSL_OP_NO_TLSv1_1 = 268435456;
|
||||
export const SSL_OP_NO_TLSv1_2 = 134217728;
|
||||
export const SSL_OP_PKCS1_CHECK_1 = 0;
|
||||
export const SSL_OP_PKCS1_CHECK_2 = 0;
|
||||
export const SSL_OP_SINGLE_DH_USE = 1048576;
|
||||
export const SSL_OP_SINGLE_ECDH_USE = 524288;
|
||||
export const SSL_OP_SSLEAY_080_CLIENT_DH_BUG = 128;
|
||||
export const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG = 0;
|
||||
export const SSL_OP_TLS_BLOCK_PADDING_BUG = 512;
|
||||
export const SSL_OP_TLS_D5_BUG = 256;
|
||||
export const SSL_OP_TLS_ROLLBACK_BUG = 8388608;
|
||||
export const ENGINE_METHOD_DSA = 2;
|
||||
export const ENGINE_METHOD_DH = 4;
|
||||
export const ENGINE_METHOD_RAND = 8;
|
||||
export const ENGINE_METHOD_ECDH = 16;
|
||||
export const ENGINE_METHOD_ECDSA = 32;
|
||||
export const ENGINE_METHOD_CIPHERS = 64;
|
||||
export const ENGINE_METHOD_DIGESTS = 128;
|
||||
export const ENGINE_METHOD_STORE = 256;
|
||||
export const ENGINE_METHOD_PKEY_METHS = 512;
|
||||
export const ENGINE_METHOD_PKEY_ASN1_METHS = 1024;
|
||||
export const ENGINE_METHOD_ALL = 65535;
|
||||
export const ENGINE_METHOD_NONE = 0;
|
||||
export const DH_CHECK_P_NOT_SAFE_PRIME = 2;
|
||||
export const DH_CHECK_P_NOT_PRIME = 1;
|
||||
export const DH_UNABLE_TO_CHECK_GENERATOR = 4;
|
||||
export const DH_NOT_SUITABLE_GENERATOR = 8;
|
||||
export const NPN_ENABLED = 1;
|
||||
export const RSA_PKCS1_PADDING = 1;
|
||||
export const RSA_SSLV23_PADDING = 2;
|
||||
export const RSA_NO_PADDING = 3;
|
||||
export const RSA_PKCS1_OAEP_PADDING = 4;
|
||||
export const RSA_X931_PADDING = 5;
|
||||
export const RSA_PKCS1_PSS_PADDING = 6;
|
||||
export const POINT_CONVERSION_COMPRESSED = 2;
|
||||
export const POINT_CONVERSION_UNCOMPRESSED = 4;
|
||||
export const POINT_CONVERSION_HYBRID = 6;
|
||||
export const F_OK = 0;
|
||||
export const R_OK = 4;
|
||||
export const W_OK = 2;
|
||||
export const X_OK = 1;
|
||||
export const UV_UDP_REUSEADDR = 4;
|
||||
|
||||
@@ -1,5 +1,44 @@
|
||||
export * from "crypto-browserify";
|
||||
import * as cryptoBrowserify from "crypto-browserify";
|
||||
import cryptoBrowserify from "crypto-browserify";
|
||||
|
||||
export const prng = cryptoBrowserify.prng;
|
||||
export const pseudoRandomBytes = cryptoBrowserify.pseudoRandomBytes;
|
||||
export const rng = cryptoBrowserify.rng;
|
||||
export const randomBytes = cryptoBrowserify.randomBytes;
|
||||
export const Hash = cryptoBrowserify.Hash;
|
||||
export const createHash = cryptoBrowserify.createHash;
|
||||
export const Hmac = cryptoBrowserify.Hmac;
|
||||
export const createHmac = cryptoBrowserify.createHmac;
|
||||
export const getHashes = cryptoBrowserify.getHashes;
|
||||
export const pbkdf2 = cryptoBrowserify.pbkdf2;
|
||||
export const pbkdf2Sync = cryptoBrowserify.pbkdf2Sync;
|
||||
export const Cipher = cryptoBrowserify.Cipher;
|
||||
export const createCipher = cryptoBrowserify.createCipher;
|
||||
export const Cipheriv = cryptoBrowserify.Cipheriv;
|
||||
export const createCipheriv = cryptoBrowserify.createCipheriv;
|
||||
export const Decipher = cryptoBrowserify.Decipher;
|
||||
export const createDecipher = cryptoBrowserify.createDecipher;
|
||||
export const Decipheriv = cryptoBrowserify.Decipheriv;
|
||||
export const createDecipheriv = cryptoBrowserify.createDecipheriv;
|
||||
export const getCiphers = cryptoBrowserify.getCiphers;
|
||||
export const listCiphers = cryptoBrowserify.listCiphers;
|
||||
export const DiffieHellmanGroup = cryptoBrowserify.DiffieHellmanGroup;
|
||||
export const createDiffieHellmanGroup = cryptoBrowserify.createDiffieHellmanGroup;
|
||||
export const getDiffieHellman = cryptoBrowserify.getDiffieHellman;
|
||||
export const createDiffieHellman = cryptoBrowserify.createDiffieHellman;
|
||||
export const DiffieHellman = cryptoBrowserify.DiffieHellman;
|
||||
export const createSign = cryptoBrowserify.createSign;
|
||||
export const Sign = cryptoBrowserify.Sign;
|
||||
export const createVerify = cryptoBrowserify.createVerify;
|
||||
export const Verify = cryptoBrowserify.Verify;
|
||||
export const createECDH = cryptoBrowserify.createECDH;
|
||||
export const publicEncrypt = cryptoBrowserify.publicEncrypt;
|
||||
export const privateEncrypt = cryptoBrowserify.privateEncrypt;
|
||||
export const publicDecrypt = cryptoBrowserify.publicDecrypt;
|
||||
export const privateDecrypt = cryptoBrowserify.privateDecrypt;
|
||||
export const randomFill = cryptoBrowserify.randomFill;
|
||||
export const randomFillSync = cryptoBrowserify.randomFillSync;
|
||||
export const createCredentials = cryptoBrowserify.createCredentials;
|
||||
export const constants = cryptoBrowserify.constants;
|
||||
|
||||
export var DEFAULT_ENCODING = "buffer";
|
||||
|
||||
@@ -12,7 +51,7 @@ export const randomUUID = () => {
|
||||
return crypto.randomUUID();
|
||||
};
|
||||
|
||||
const harcoded_curves = [
|
||||
const hardcoded_curves = [
|
||||
"p192",
|
||||
"p224",
|
||||
"p256",
|
||||
@@ -30,7 +69,7 @@ const harcoded_curves = [
|
||||
];
|
||||
|
||||
export function getCurves() {
|
||||
return harcoded_curves;
|
||||
return hardcoded_curves;
|
||||
}
|
||||
|
||||
export const timingSafeEqual =
|
||||
@@ -101,14 +140,3 @@ if (timingSafeEqual) {
|
||||
}
|
||||
|
||||
export const webcrypto = crypto;
|
||||
|
||||
export default {
|
||||
...cryptoBrowserify,
|
||||
getRandomValues,
|
||||
randomUUID,
|
||||
timingSafeEqual,
|
||||
scryptSync,
|
||||
scrypt,
|
||||
webcrypto,
|
||||
getCurves,
|
||||
};
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
import domain from "domain-browser";
|
||||
export default domain;
|
||||
export var { create, createDomain } = domain;
|
||||
|
||||
@@ -1,483 +1,535 @@
|
||||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
// NOTE: THIS IS A BROWSER POLYFILL - Bun's actual node:* modules are in src/js/node
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the
|
||||
// "Software"), to deal in the Software without restriction, including
|
||||
// without limitation the rights to use, copy, modify, merge, publish,
|
||||
// distribute, sublicense, and/or sell copies of the Software, and to permit
|
||||
// persons to whom the Software is furnished to do so, subject to the
|
||||
// following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included
|
||||
// in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
||||
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
// TODO: This file is copy pasted from that, and should be generated from that,
|
||||
// in a way that excludes async_hooks related functions. Those will never be
|
||||
// available in the browser. Also, Node.js has some addition hooks to allow
|
||||
// these functions to take secret data out of EventTarget. those cannot be
|
||||
// included here either.
|
||||
|
||||
"use strict";
|
||||
const SymbolFor = Symbol.for;
|
||||
|
||||
var R = typeof Reflect === "object" ? Reflect : null;
|
||||
var ReflectApply =
|
||||
R && typeof R.apply === "function"
|
||||
? R.apply
|
||||
: function ReflectApply(target, receiver, args) {
|
||||
return Function.prototype.apply.call(target, receiver, args);
|
||||
};
|
||||
const kCapture = Symbol("kCapture");
|
||||
const kErrorMonitor = SymbolFor("events.errorMonitor");
|
||||
const kMaxEventTargetListeners = Symbol("events.maxEventTargetListeners");
|
||||
const kMaxEventTargetListenersWarned = Symbol("events.maxEventTargetListenersWarned");
|
||||
const kRejection = SymbolFor("nodejs.rejection");
|
||||
const captureRejectionSymbol = SymbolFor("nodejs.rejection");
|
||||
const ArrayPrototypeSlice = Array.prototype.slice;
|
||||
|
||||
var ReflectOwnKeys;
|
||||
if (R && typeof R.ownKeys === "function") {
|
||||
ReflectOwnKeys = R.ownKeys;
|
||||
} else if (Object.getOwnPropertySymbols) {
|
||||
ReflectOwnKeys = function ReflectOwnKeys(target) {
|
||||
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
|
||||
};
|
||||
} else {
|
||||
ReflectOwnKeys = function ReflectOwnKeys(target) {
|
||||
return Object.getOwnPropertyNames(target);
|
||||
};
|
||||
}
|
||||
|
||||
function ProcessEmitWarning(warning) {
|
||||
if (console && console.warn) console.warn(warning);
|
||||
}
|
||||
|
||||
var NumberIsNaN =
|
||||
Number.isNaN ||
|
||||
function NumberIsNaN(value) {
|
||||
return value !== value;
|
||||
};
|
||||
|
||||
function EventEmitter() {
|
||||
EventEmitter.init.call(this);
|
||||
}
|
||||
|
||||
// Backwards-compat with node 0.10.x
|
||||
EventEmitter.EventEmitter = EventEmitter;
|
||||
|
||||
EventEmitter.prototype._events = undefined;
|
||||
EventEmitter.prototype._eventsCount = 0;
|
||||
EventEmitter.prototype._maxListeners = undefined;
|
||||
|
||||
// By default EventEmitters will print a warning if more than 10 listeners are
|
||||
// added to it. This is a useful default which helps finding memory leaks.
|
||||
var defaultMaxListeners = 10;
|
||||
|
||||
function checkListener(listener) {
|
||||
if (typeof listener !== "function") {
|
||||
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(EventEmitter, "defaultMaxListeners", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return defaultMaxListeners;
|
||||
},
|
||||
set: function (arg) {
|
||||
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) {
|
||||
throw new RangeError(
|
||||
'The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + ".",
|
||||
);
|
||||
}
|
||||
defaultMaxListeners = arg;
|
||||
},
|
||||
});
|
||||
|
||||
EventEmitter.init = function () {
|
||||
if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) {
|
||||
this._events = Object.create(null);
|
||||
// EventEmitter must be a standard function because some old code will do weird tricks like `EventEmitter.$apply(this)`.
|
||||
const EventEmitter = function EventEmitter(opts) {
|
||||
if (this._events === undefined || this._events === this.__proto__._events) {
|
||||
this._events = { __proto__: null };
|
||||
this._eventsCount = 0;
|
||||
}
|
||||
|
||||
this._maxListeners = this._maxListeners || undefined;
|
||||
};
|
||||
|
||||
// Obviously not all Emitters should be limited to 10. This function allows
|
||||
// that to be increased. Set to zero for unlimited.
|
||||
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
|
||||
if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) {
|
||||
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + ".");
|
||||
this._maxListeners ??= undefined;
|
||||
if ((this[kCapture] = opts?.captureRejections ? Boolean(opts?.captureRejections) : EventEmitterPrototype[kCapture])) {
|
||||
this.emit = emitWithRejectionCapture;
|
||||
}
|
||||
};
|
||||
const EventEmitterPrototype = (EventEmitter.prototype = {});
|
||||
|
||||
EventEmitterPrototype._events = undefined;
|
||||
EventEmitterPrototype._eventsCount = 0;
|
||||
EventEmitterPrototype._maxListeners = undefined;
|
||||
EventEmitterPrototype.setMaxListeners = function setMaxListeners(n) {
|
||||
validateNumber(n, "setMaxListeners", 0);
|
||||
this._maxListeners = n;
|
||||
return this;
|
||||
};
|
||||
|
||||
function _getMaxListeners(that) {
|
||||
if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners;
|
||||
return that._maxListeners;
|
||||
}
|
||||
EventEmitterPrototype.constructor = EventEmitter;
|
||||
|
||||
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
|
||||
return _getMaxListeners(this);
|
||||
EventEmitterPrototype.getMaxListeners = function getMaxListeners() {
|
||||
return this?._maxListeners ?? defaultMaxListeners;
|
||||
};
|
||||
|
||||
EventEmitter.prototype.emit = function emit(type) {
|
||||
var args = [];
|
||||
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
|
||||
var doError = type === "error";
|
||||
|
||||
var events = this._events;
|
||||
if (events !== undefined) doError = doError && events.error === undefined;
|
||||
else if (!doError) return false;
|
||||
|
||||
// If there is no 'error' event listener then throw.
|
||||
if (doError) {
|
||||
var er;
|
||||
if (args.length > 0) er = args[0];
|
||||
if (er instanceof Error) {
|
||||
// Note: The comments on the `throw` lines are intentional, they show
|
||||
// up in Node's output if this results in an unhandled exception.
|
||||
throw er; // Unhandled 'error' event
|
||||
function emitError(emitter, args) {
|
||||
var { _events: events } = emitter;
|
||||
args[0] ??= new Error("Unhandled error.");
|
||||
if (!events) throw args[0];
|
||||
var errorMonitor = events[kErrorMonitor];
|
||||
if (errorMonitor) {
|
||||
for (var handler of ArrayPrototypeSlice.$call(errorMonitor)) {
|
||||
handler.$apply(emitter, args);
|
||||
}
|
||||
// At least give some kind of context to the user
|
||||
var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
|
||||
err.context = er;
|
||||
throw err; // Unhandled 'error' event
|
||||
}
|
||||
|
||||
var handler = events[type];
|
||||
|
||||
if (handler === undefined) return false;
|
||||
|
||||
if (typeof handler === "function") {
|
||||
ReflectApply(handler, this, args);
|
||||
} else {
|
||||
var len = handler.length;
|
||||
var listeners = arrayClone(handler, len);
|
||||
for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args);
|
||||
var handlers = events.error;
|
||||
if (!handlers) throw args[0];
|
||||
for (var handler of ArrayPrototypeSlice.$call(handlers)) {
|
||||
handler.$apply(emitter, args);
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
function _addListener(target, type, listener, prepend) {
|
||||
var m;
|
||||
var events;
|
||||
var existing;
|
||||
|
||||
checkListener(listener);
|
||||
|
||||
events = target._events;
|
||||
if (events === undefined) {
|
||||
events = target._events = Object.create(null);
|
||||
target._eventsCount = 0;
|
||||
} else {
|
||||
// To avoid recursion in the case that type === "newListener"! Before
|
||||
// adding it to the listeners, first emit "newListener".
|
||||
if (events.newListener !== undefined) {
|
||||
target.emit("newListener", type, listener.listener ? listener.listener : listener);
|
||||
|
||||
// Re-assign `events` because a newListener handler could have caused the
|
||||
// this._events to be assigned to a new object
|
||||
events = target._events;
|
||||
}
|
||||
existing = events[type];
|
||||
}
|
||||
|
||||
if (existing === undefined) {
|
||||
// Optimize the case of one listener. Don't need the extra array object.
|
||||
existing = events[type] = listener;
|
||||
++target._eventsCount;
|
||||
} else {
|
||||
if (typeof existing === "function") {
|
||||
// Adding the second element, need to change to array.
|
||||
existing = events[type] = prepend ? [listener, existing] : [existing, listener];
|
||||
// If we've already got an array, just append.
|
||||
} else if (prepend) {
|
||||
existing.unshift(listener);
|
||||
} else {
|
||||
existing.push(listener);
|
||||
}
|
||||
|
||||
// Check for listener leak
|
||||
m = _getMaxListeners(target);
|
||||
if (m > 0 && existing.length > m && !existing.warned) {
|
||||
existing.warned = true;
|
||||
// No error code for this since it is a Warning
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
var w = new Error(
|
||||
"Possible EventEmitter memory leak detected. " +
|
||||
existing.length +
|
||||
" " +
|
||||
String(type) +
|
||||
" listeners " +
|
||||
"added. Use emitter.setMaxListeners() to " +
|
||||
"increase limit",
|
||||
);
|
||||
w.name = "MaxListenersExceededWarning";
|
||||
w.emitter = target;
|
||||
w.type = type;
|
||||
w.count = existing.length;
|
||||
ProcessEmitWarning(w);
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
EventEmitter.prototype.addListener = function addListener(type, listener) {
|
||||
return _addListener(this, type, listener, false);
|
||||
};
|
||||
|
||||
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
|
||||
|
||||
EventEmitter.prototype.prependListener = function prependListener(type, listener) {
|
||||
return _addListener(this, type, listener, true);
|
||||
};
|
||||
|
||||
function onceWrapper() {
|
||||
if (!this.fired) {
|
||||
this.target.removeListener(this.type, this.wrapFn);
|
||||
this.fired = true;
|
||||
if (arguments.length === 0) return this.listener.call(this.target);
|
||||
return this.listener.apply(this.target, arguments);
|
||||
}
|
||||
}
|
||||
|
||||
function _onceWrap(target, type, listener) {
|
||||
var state = {
|
||||
fired: false,
|
||||
wrapFn: undefined,
|
||||
target: target,
|
||||
type: type,
|
||||
listener: listener,
|
||||
};
|
||||
var wrapped = onceWrapper.bind(state);
|
||||
wrapped.listener = listener;
|
||||
state.wrapFn = wrapped;
|
||||
return wrapped;
|
||||
}
|
||||
|
||||
EventEmitter.prototype.once = function once(type, listener) {
|
||||
checkListener(listener);
|
||||
this.on(type, _onceWrap(this, type, listener));
|
||||
return this;
|
||||
};
|
||||
|
||||
EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) {
|
||||
checkListener(listener);
|
||||
this.prependListener(type, _onceWrap(this, type, listener));
|
||||
return this;
|
||||
};
|
||||
|
||||
// Emits a 'removeListener' event if and only if the listener was removed.
|
||||
EventEmitter.prototype.removeListener = function removeListener(type, listener) {
|
||||
var list, events, position, i, originalListener;
|
||||
|
||||
checkListener(listener);
|
||||
|
||||
events = this._events;
|
||||
if (events === undefined) return this;
|
||||
|
||||
list = events[type];
|
||||
if (list === undefined) return this;
|
||||
|
||||
if (list === listener || list.listener === listener) {
|
||||
if (--this._eventsCount === 0) this._events = Object.create(null);
|
||||
else {
|
||||
delete events[type];
|
||||
if (events.removeListener) this.emit("removeListener", type, list.listener || listener);
|
||||
}
|
||||
} else if (typeof list !== "function") {
|
||||
position = -1;
|
||||
|
||||
for (i = list.length - 1; i >= 0; i--) {
|
||||
if (list[i] === listener || list[i].listener === listener) {
|
||||
originalListener = list[i].listener;
|
||||
position = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (position < 0) return this;
|
||||
|
||||
if (position === 0) list.shift();
|
||||
else {
|
||||
spliceOne(list, position);
|
||||
}
|
||||
|
||||
if (list.length === 1) events[type] = list[0];
|
||||
|
||||
if (events.removeListener !== undefined) this.emit("removeListener", type, originalListener || listener);
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
|
||||
|
||||
EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) {
|
||||
var listeners, events, i;
|
||||
|
||||
events = this._events;
|
||||
if (events === undefined) return this;
|
||||
|
||||
// not listening for removeListener, no need to emit
|
||||
if (events.removeListener === undefined) {
|
||||
if (arguments.length === 0) {
|
||||
this._events = Object.create(null);
|
||||
this._eventsCount = 0;
|
||||
} else if (events[type] !== undefined) {
|
||||
if (--this._eventsCount === 0) this._events = Object.create(null);
|
||||
else delete events[type];
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
// emit removeListener for all listeners on all events
|
||||
if (arguments.length === 0) {
|
||||
var keys = Object.keys(events);
|
||||
var key;
|
||||
for (i = 0; i < keys.length; ++i) {
|
||||
key = keys[i];
|
||||
if (key === "removeListener") continue;
|
||||
this.removeAllListeners(key);
|
||||
}
|
||||
this.removeAllListeners("removeListener");
|
||||
this._events = Object.create(null);
|
||||
this._eventsCount = 0;
|
||||
return this;
|
||||
}
|
||||
|
||||
listeners = events[type];
|
||||
|
||||
if (typeof listeners === "function") {
|
||||
this.removeListener(type, listeners);
|
||||
} else if (listeners !== undefined) {
|
||||
// LIFO order
|
||||
for (i = listeners.length - 1; i >= 0; i--) {
|
||||
this.removeListener(type, listeners[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
function _listeners(target, type, unwrap) {
|
||||
var events = target._events;
|
||||
|
||||
if (events === undefined) return [];
|
||||
|
||||
var evlistener = events[type];
|
||||
if (evlistener === undefined) return [];
|
||||
|
||||
if (typeof evlistener === "function") return unwrap ? [evlistener.listener || evlistener] : [evlistener];
|
||||
|
||||
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
|
||||
}
|
||||
|
||||
EventEmitter.prototype.listeners = function listeners(type) {
|
||||
return _listeners(this, type, true);
|
||||
};
|
||||
|
||||
EventEmitter.prototype.rawListeners = function rawListeners(type) {
|
||||
return _listeners(this, type, false);
|
||||
};
|
||||
|
||||
EventEmitter.listenerCount = function (emitter, type) {
|
||||
if (typeof emitter.listenerCount === "function") {
|
||||
return emitter.listenerCount(type);
|
||||
} else {
|
||||
return listenerCount.call(emitter, type);
|
||||
}
|
||||
};
|
||||
|
||||
EventEmitter.prototype.listenerCount = listenerCount;
|
||||
function listenerCount(type) {
|
||||
var events = this._events;
|
||||
|
||||
if (events !== undefined) {
|
||||
var evlistener = events[type];
|
||||
|
||||
if (typeof evlistener === "function") {
|
||||
return 1;
|
||||
} else if (evlistener !== undefined) {
|
||||
return evlistener.length;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
EventEmitter.prototype.eventNames = function eventNames() {
|
||||
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
|
||||
};
|
||||
|
||||
function arrayClone(arr, n) {
|
||||
var copy = new Array(n);
|
||||
for (var i = 0; i < n; ++i) copy[i] = arr[i];
|
||||
return copy;
|
||||
}
|
||||
|
||||
function spliceOne(list, index) {
|
||||
for (; index + 1 < list.length; index++) list[index] = list[index + 1];
|
||||
list.pop();
|
||||
}
|
||||
|
||||
function unwrapListeners(arr) {
|
||||
var ret = new Array(arr.length);
|
||||
for (var i = 0; i < ret.length; ++i) {
|
||||
ret[i] = arr[i].listener || arr[i];
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
function once(emitter, name) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
function errorListener(err) {
|
||||
emitter.removeListener(name, resolver);
|
||||
reject(err);
|
||||
}
|
||||
|
||||
function resolver() {
|
||||
if (typeof emitter.removeListener === "function") {
|
||||
emitter.removeListener("error", errorListener);
|
||||
}
|
||||
resolve([].slice.call(arguments));
|
||||
}
|
||||
|
||||
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
|
||||
if (name !== "error") {
|
||||
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
|
||||
}
|
||||
function addCatch(emitter, promise, type, args) {
|
||||
promise.then(undefined, function (err) {
|
||||
// The callback is called with nextTick to avoid a follow-up rejection from this promise.
|
||||
process.nextTick(emitUnhandledRejectionOrErr, emitter, err, type, args);
|
||||
});
|
||||
}
|
||||
|
||||
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
|
||||
if (typeof emitter.on === "function") {
|
||||
eventTargetAgnosticAddListener(emitter, "error", handler, flags);
|
||||
function emitUnhandledRejectionOrErr(emitter, err, type, args) {
|
||||
if (typeof emitter[kRejection] === "function") {
|
||||
emitter[kRejection](err, type, ...args);
|
||||
} else {
|
||||
// If the error handler throws, it is not catchable and it will end up in 'uncaughtException'.
|
||||
// We restore the previous value of kCapture in case the uncaughtException is present
|
||||
// and the exception is handled.
|
||||
try {
|
||||
emitter[kCapture] = false;
|
||||
emitter.emit("error", err);
|
||||
} finally {
|
||||
emitter[kCapture] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const emitWithoutRejectionCapture = function emit(type, ...args) {
|
||||
if (type === "error") {
|
||||
return emitError(this, args);
|
||||
}
|
||||
var { _events: events } = this;
|
||||
if (events === undefined) return false;
|
||||
var handlers = events[type];
|
||||
if (handlers === undefined) return false;
|
||||
// Clone handlers array if necessary since handlers can be added/removed during the loop.
|
||||
// Cloning is skipped for performance reasons in the case of exactly one attached handler
|
||||
// since array length changes have no side-effects in a for-loop of length 1.
|
||||
const maybeClonedHandlers = handlers.length > 1 ? handlers.slice() : handlers;
|
||||
for (let i = 0, { length } = maybeClonedHandlers; i < length; i++) {
|
||||
const handler = maybeClonedHandlers[i];
|
||||
// For performance reasons Function.call(...) is used whenever possible.
|
||||
switch (args.length) {
|
||||
case 0:
|
||||
handler.$call(this);
|
||||
break;
|
||||
case 1:
|
||||
handler.$call(this, args[0]);
|
||||
break;
|
||||
case 2:
|
||||
handler.$call(this, args[0], args[1]);
|
||||
break;
|
||||
case 3:
|
||||
handler.$call(this, args[0], args[1], args[2]);
|
||||
break;
|
||||
default:
|
||||
handler.$apply(this, args);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const emitWithRejectionCapture = function emit(type, ...args) {
|
||||
if (type === "error") {
|
||||
return emitError(this, args);
|
||||
}
|
||||
var { _events: events } = this;
|
||||
if (events === undefined) return false;
|
||||
var handlers = events[type];
|
||||
if (handlers === undefined) return false;
|
||||
// Clone handlers array if necessary since handlers can be added/removed during the loop.
|
||||
// Cloning is skipped for performance reasons in the case of exactly one attached handler
|
||||
// since array length changes have no side-effects in a for-loop of length 1.
|
||||
const maybeClonedHandlers = handlers.length > 1 ? handlers.slice() : handlers;
|
||||
for (let i = 0, { length } = maybeClonedHandlers; i < length; i++) {
|
||||
const handler = maybeClonedHandlers[i];
|
||||
let result;
|
||||
// For performance reasons Function.call(...) is used whenever possible.
|
||||
switch (args.length) {
|
||||
case 0:
|
||||
result = handler.$call(this);
|
||||
break;
|
||||
case 1:
|
||||
result = handler.$call(this, args[0]);
|
||||
break;
|
||||
case 2:
|
||||
result = handler.$call(this, args[0], args[1]);
|
||||
break;
|
||||
case 3:
|
||||
result = handler.$call(this, args[0], args[1], args[2]);
|
||||
break;
|
||||
default:
|
||||
result = handler.$apply(this, args);
|
||||
break;
|
||||
}
|
||||
if (result !== undefined && $isPromise(result)) {
|
||||
addCatch(this, result, type, args);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
EventEmitterPrototype.emit = emitWithoutRejectionCapture;
|
||||
|
||||
EventEmitterPrototype.addListener = function addListener(type, fn) {
|
||||
checkListener(fn);
|
||||
var events = this._events;
|
||||
if (!events) {
|
||||
events = this._events = { __proto__: null };
|
||||
this._eventsCount = 0;
|
||||
} else if (events.newListener) {
|
||||
this.emit("newListener", type, fn.listener ?? fn);
|
||||
}
|
||||
var handlers = events[type];
|
||||
if (!handlers) {
|
||||
events[type] = [fn];
|
||||
this._eventsCount++;
|
||||
} else {
|
||||
handlers.push(fn);
|
||||
var m = this._maxListeners ?? defaultMaxListeners;
|
||||
if (m > 0 && handlers.length > m && !handlers.warned) {
|
||||
overflowWarning(this, type, handlers);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
EventEmitterPrototype.on = EventEmitterPrototype.addListener;
|
||||
|
||||
EventEmitterPrototype.prependListener = function prependListener(type, fn) {
|
||||
checkListener(fn);
|
||||
var events = this._events;
|
||||
if (!events) {
|
||||
events = this._events = { __proto__: null };
|
||||
this._eventsCount = 0;
|
||||
} else if (events.newListener) {
|
||||
this.emit("newListener", type, fn.listener ?? fn);
|
||||
}
|
||||
var handlers = events[type];
|
||||
if (!handlers) {
|
||||
events[type] = [fn];
|
||||
this._eventsCount++;
|
||||
} else {
|
||||
handlers.unshift(fn);
|
||||
var m = this._maxListeners ?? defaultMaxListeners;
|
||||
if (m > 0 && handlers.length > m && !handlers.warned) {
|
||||
overflowWarning(this, type, handlers);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
function overflowWarning(emitter, type, handlers) {
|
||||
handlers.warned = true;
|
||||
const warn = new Error(
|
||||
`Possible EventEmitter memory leak detected. ${handlers.length} ${String(type)} listeners ` +
|
||||
`added to [${emitter.constructor.name}]. Use emitter.setMaxListeners() to increase limit`,
|
||||
);
|
||||
warn.name = "MaxListenersExceededWarning";
|
||||
warn.emitter = emitter;
|
||||
warn.type = type;
|
||||
warn.count = handlers.length;
|
||||
process.emitWarning(warn);
|
||||
}
|
||||
|
||||
function onceWrapper(type, listener, ...args) {
|
||||
this.removeListener(type, listener);
|
||||
listener.$apply(this, args);
|
||||
}
|
||||
|
||||
EventEmitterPrototype.once = function once(type, fn) {
|
||||
checkListener(fn);
|
||||
const bound = onceWrapper.bind(this, type, fn);
|
||||
bound.listener = fn;
|
||||
this.addListener(type, bound);
|
||||
return this;
|
||||
};
|
||||
|
||||
EventEmitterPrototype.prependOnceListener = function prependOnceListener(type, fn) {
|
||||
checkListener(fn);
|
||||
const bound = onceWrapper.bind(this, type, fn);
|
||||
bound.listener = fn;
|
||||
this.prependListener(type, bound);
|
||||
return this;
|
||||
};
|
||||
|
||||
EventEmitterPrototype.removeListener = function removeListener(type, fn) {
|
||||
checkListener(fn);
|
||||
var { _events: events } = this;
|
||||
if (!events) return this;
|
||||
var handlers = events[type];
|
||||
if (!handlers) return this;
|
||||
var length = handlers.length;
|
||||
let position = -1;
|
||||
for (let i = length - 1; i >= 0; i--) {
|
||||
if (handlers[i] === fn || handlers[i].listener === fn) {
|
||||
position = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (position < 0) return this;
|
||||
if (position === 0) {
|
||||
handlers.shift();
|
||||
} else {
|
||||
handlers.splice(position, 1);
|
||||
}
|
||||
if (handlers.length === 0) {
|
||||
delete events[type];
|
||||
this._eventsCount--;
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
EventEmitterPrototype.off = EventEmitterPrototype.removeListener;
|
||||
|
||||
EventEmitterPrototype.removeAllListeners = function removeAllListeners(type) {
|
||||
var { _events: events } = this;
|
||||
if (type && events) {
|
||||
if (events[type]) {
|
||||
delete events[type];
|
||||
this._eventsCount--;
|
||||
}
|
||||
} else {
|
||||
this._events = { __proto__: null };
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
EventEmitterPrototype.listeners = function listeners(type) {
|
||||
var { _events: events } = this;
|
||||
if (!events) return [];
|
||||
var handlers = events[type];
|
||||
if (!handlers) return [];
|
||||
return handlers.map(x => x.listener ?? x);
|
||||
};
|
||||
|
||||
EventEmitterPrototype.rawListeners = function rawListeners(type) {
|
||||
var { _events } = this;
|
||||
if (!_events) return [];
|
||||
var handlers = _events[type];
|
||||
if (!handlers) return [];
|
||||
return handlers.slice();
|
||||
};
|
||||
|
||||
EventEmitterPrototype.listenerCount = function listenerCount(type) {
|
||||
var { _events: events } = this;
|
||||
if (!events) return 0;
|
||||
return events[type]?.length ?? 0;
|
||||
};
|
||||
|
||||
EventEmitterPrototype.eventNames = function eventNames() {
|
||||
return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
|
||||
};
|
||||
|
||||
EventEmitterPrototype[kCapture] = false;
|
||||
|
||||
function once(emitter, type, options) {
|
||||
var signal = options?.signal;
|
||||
validateAbortSignal(signal, "options.signal");
|
||||
if (signal?.aborted) {
|
||||
throw new AbortError(undefined, { cause: signal?.reason });
|
||||
}
|
||||
const { resolve, reject, promise } = $newPromiseCapability(Promise);
|
||||
const errorListener = err => {
|
||||
emitter.removeListener(type, resolver);
|
||||
if (signal != null) {
|
||||
eventTargetAgnosticRemoveListener(signal, "abort", abortListener);
|
||||
}
|
||||
reject(err);
|
||||
};
|
||||
const resolver = (...args) => {
|
||||
if (typeof emitter.removeListener === "function") {
|
||||
emitter.removeListener("error", errorListener);
|
||||
}
|
||||
if (signal != null) {
|
||||
eventTargetAgnosticRemoveListener(signal, "abort", abortListener);
|
||||
}
|
||||
resolve(args);
|
||||
};
|
||||
eventTargetAgnosticAddListener(emitter, type, resolver, { once: true });
|
||||
if (type !== "error" && typeof emitter.once === "function") {
|
||||
// EventTarget does not have `error` event semantics like Node
|
||||
// EventEmitters, we listen to `error` events only on EventEmitters.
|
||||
emitter.once("error", errorListener);
|
||||
}
|
||||
function abortListener() {
|
||||
eventTargetAgnosticRemoveListener(emitter, type, resolver);
|
||||
eventTargetAgnosticRemoveListener(emitter, "error", errorListener);
|
||||
reject(new AbortError(undefined, { cause: signal?.reason }));
|
||||
}
|
||||
if (signal != null) {
|
||||
eventTargetAgnosticAddListener(signal, "abort", abortListener, { once: true });
|
||||
}
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
function getEventListeners(emitter, type) {
|
||||
return emitter.listeners(type);
|
||||
}
|
||||
|
||||
function setMaxListeners(n, ...eventTargets) {
|
||||
validateNumber(n, "setMaxListeners", 0);
|
||||
var length;
|
||||
if (eventTargets && (length = eventTargets.length)) {
|
||||
for (let i = 0; i < length; i++) {
|
||||
eventTargets[i].setMaxListeners(n);
|
||||
}
|
||||
} else {
|
||||
defaultMaxListeners = n;
|
||||
}
|
||||
}
|
||||
|
||||
function listenerCount(emitter, type) {
|
||||
return emitter.listenerCount(type);
|
||||
}
|
||||
|
||||
function eventTargetAgnosticRemoveListener(emitter, name, listener, flags) {
|
||||
if (typeof emitter.removeListener === "function") {
|
||||
emitter.removeListener(name, listener);
|
||||
} else {
|
||||
emitter.removeEventListener(name, listener, flags);
|
||||
}
|
||||
}
|
||||
|
||||
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
|
||||
if (typeof emitter.on === "function") {
|
||||
if (flags.once) {
|
||||
emitter.once(name, listener);
|
||||
} else {
|
||||
emitter.on(name, listener);
|
||||
}
|
||||
} else if (typeof emitter.addEventListener === "function") {
|
||||
// EventTarget does not have `error` event semantics like Node
|
||||
// EventEmitters, we do not listen for `error` events here.
|
||||
emitter.addEventListener(name, function wrapListener(arg) {
|
||||
// IE does not have builtin `{ once: true }` support so we
|
||||
// have to do it manually.
|
||||
if (flags.once) {
|
||||
emitter.removeEventListener(name, wrapListener);
|
||||
}
|
||||
listener(arg);
|
||||
});
|
||||
if (flags.once) emitter.once(name, listener);
|
||||
else emitter.on(name, listener);
|
||||
} else {
|
||||
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
|
||||
emitter.addEventListener(name, listener, flags);
|
||||
}
|
||||
}
|
||||
|
||||
class AbortError extends Error {
|
||||
constructor(message = "The operation was aborted", options = undefined) {
|
||||
if (options !== undefined && typeof options !== "object") {
|
||||
throw ERR_INVALID_ARG_TYPE("options", "Object", options);
|
||||
}
|
||||
super(message, options);
|
||||
this.code = "ABORT_ERR";
|
||||
this.name = "AbortError";
|
||||
}
|
||||
}
|
||||
|
||||
function ERR_INVALID_ARG_TYPE(name, type, value) {
|
||||
const err = new TypeError(`The "${name}" argument must be of type ${type}. Received ${value}`);
|
||||
err.code = "ERR_INVALID_ARG_TYPE";
|
||||
return err;
|
||||
}
|
||||
|
||||
function ERR_OUT_OF_RANGE(name, range, value) {
|
||||
const err = new RangeError(`The "${name}" argument is out of range. It must be ${range}. Received ${value}`);
|
||||
err.code = "ERR_OUT_OF_RANGE";
|
||||
return err;
|
||||
}
|
||||
|
||||
function validateAbortSignal(signal, name) {
|
||||
if (signal !== undefined && (signal === null || typeof signal !== "object" || !("aborted" in signal))) {
|
||||
throw ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal);
|
||||
}
|
||||
}
|
||||
|
||||
function validateNumber(value, name, min, max) {
|
||||
if (typeof value !== "number") throw ERR_INVALID_ARG_TYPE(name, "number", value);
|
||||
if (
|
||||
(min != null && value < min) ||
|
||||
(max != null && value > max) ||
|
||||
((min != null || max != null) && Number.isNaN(value))
|
||||
) {
|
||||
throw ERR_OUT_OF_RANGE(
|
||||
name,
|
||||
`${min != null ? `>= ${min}` : ""}${min != null && max != null ? " && " : ""}${max != null ? `<= ${max}` : ""}`,
|
||||
value,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function checkListener(listener) {
|
||||
if (typeof listener !== "function") {
|
||||
throw new TypeError("The listener must be a function");
|
||||
}
|
||||
}
|
||||
|
||||
function validateBoolean(value, name) {
|
||||
if (typeof value !== "boolean") throw ERR_INVALID_ARG_TYPE(name, "boolean", value);
|
||||
}
|
||||
|
||||
function getMaxListeners(emitterOrTarget) {
|
||||
return emitterOrTarget?._maxListeners ?? defaultMaxListeners;
|
||||
}
|
||||
|
||||
// Copy-pasta from Node.js source code
|
||||
function addAbortListener(signal, listener) {
|
||||
if (signal === undefined) {
|
||||
throw ERR_INVALID_ARG_TYPE("signal", "AbortSignal", signal);
|
||||
}
|
||||
|
||||
validateAbortSignal(signal, "signal");
|
||||
if (typeof listener !== "function") {
|
||||
throw ERR_INVALID_ARG_TYPE("listener", "function", listener);
|
||||
}
|
||||
|
||||
let removeEventListener;
|
||||
if (signal.aborted) {
|
||||
queueMicrotask(() => listener());
|
||||
} else {
|
||||
signal.addEventListener("abort", listener, { __proto__: null, once: true });
|
||||
removeEventListener = () => {
|
||||
signal.removeEventListener("abort", listener);
|
||||
};
|
||||
}
|
||||
return {
|
||||
__proto__: null,
|
||||
[Symbol.dispose]() {
|
||||
removeEventListener?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
Object.defineProperties(EventEmitter, {
|
||||
captureRejections: {
|
||||
get() {
|
||||
return EventEmitterPrototype[kCapture];
|
||||
},
|
||||
set(value) {
|
||||
validateBoolean(value, "EventEmitter.captureRejections");
|
||||
|
||||
EventEmitterPrototype[kCapture] = value;
|
||||
},
|
||||
enumerable: true,
|
||||
},
|
||||
defaultMaxListeners: {
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
return defaultMaxListeners;
|
||||
},
|
||||
set: arg => {
|
||||
validateNumber(arg, "defaultMaxListeners", 0);
|
||||
defaultMaxListeners = arg;
|
||||
},
|
||||
},
|
||||
kMaxEventTargetListeners: {
|
||||
value: kMaxEventTargetListeners,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false,
|
||||
},
|
||||
kMaxEventTargetListenersWarned: {
|
||||
value: kMaxEventTargetListenersWarned,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false,
|
||||
},
|
||||
});
|
||||
Object.assign(EventEmitter, {
|
||||
once,
|
||||
// on,
|
||||
getEventListeners,
|
||||
getMaxListeners,
|
||||
setMaxListeners,
|
||||
EventEmitter,
|
||||
usingDomains: false,
|
||||
captureRejectionSymbol,
|
||||
errorMonitor: kErrorMonitor,
|
||||
addAbortListener,
|
||||
init: EventEmitter,
|
||||
listenerCount,
|
||||
});
|
||||
|
||||
export default EventEmitter;
|
||||
export { once };
|
||||
export { EventEmitter };
|
||||
export var prototype = EventEmitter.prototype;
|
||||
|
||||
@@ -1,13 +1,2 @@
|
||||
import http from "stream-http";
|
||||
export default http;
|
||||
export var {
|
||||
//
|
||||
request,
|
||||
get,
|
||||
ClientRequest,
|
||||
IncomingMessage,
|
||||
Agent,
|
||||
globalAgent,
|
||||
STATUS_CODES,
|
||||
METHODS,
|
||||
} = http;
|
||||
export var { request, get, ClientRequest, IncomingMessage, Agent, globalAgent, STATUS_CODES, METHODS } = http;
|
||||
|
||||
@@ -1,2 +1,19 @@
|
||||
export * from "https-browserify";
|
||||
export * as default from "https-browserify";
|
||||
import * as https from "https-browserify";
|
||||
export var {
|
||||
Agent,
|
||||
ClientRequest,
|
||||
IncomingMessage,
|
||||
METHODS,
|
||||
OutgoingMessage,
|
||||
STATUS_CODES,
|
||||
Server,
|
||||
ServerResponse,
|
||||
createServer,
|
||||
get,
|
||||
globalAgent,
|
||||
maxHeaderSize,
|
||||
request,
|
||||
setMaxIdleHTTPParsers,
|
||||
validateHeaderName,
|
||||
validateHeaderValue,
|
||||
} = https;
|
||||
|
||||
@@ -22,11 +22,11 @@
|
||||
// IPv4 Segment
|
||||
const v4Seg = "(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])";
|
||||
const v4Str = `(?:${v4Seg}\\.){3}${v4Seg}`;
|
||||
const IPv4Reg = new RegExp(`^${v4Str}$`);
|
||||
const IPv4Reg = /* @__PURE__ */ new RegExp(`^${v4Str}$`);
|
||||
|
||||
// IPv6 Segment
|
||||
const v6Seg = "(?:[0-9a-fA-F]{1,4})";
|
||||
const IPv6Reg = new RegExp(
|
||||
const IPv6Reg = /* @__PURE__ */ new RegExp(
|
||||
"^(?:" +
|
||||
`(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
|
||||
`(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
|
||||
@@ -52,9 +52,3 @@ export function isIP(s) {
|
||||
if (isIPv6(s)) return 6;
|
||||
return 0;
|
||||
}
|
||||
|
||||
export default {
|
||||
isIP,
|
||||
isIPv4,
|
||||
isIPv6,
|
||||
};
|
||||
|
||||
@@ -1,20 +1,64 @@
|
||||
import os from "os-browserify/browser";
|
||||
export default os;
|
||||
export var {
|
||||
endianness,
|
||||
hostname,
|
||||
loadavg,
|
||||
uptime,
|
||||
freemem,
|
||||
totalmem,
|
||||
cpus,
|
||||
type,
|
||||
release,
|
||||
arch,
|
||||
platform,
|
||||
tmpdir,
|
||||
EOL,
|
||||
homedir,
|
||||
networkInterfaces,
|
||||
getNetworkInterfaces,
|
||||
} = os;
|
||||
export const endianness = function () {
|
||||
return "LE";
|
||||
};
|
||||
|
||||
export const hostname = function () {
|
||||
if (typeof location !== "undefined") {
|
||||
return location.hostname;
|
||||
} else return "";
|
||||
};
|
||||
|
||||
export const loadavg = function () {
|
||||
return [];
|
||||
};
|
||||
|
||||
export const uptime = function () {
|
||||
return 0;
|
||||
};
|
||||
|
||||
export const freemem = function () {
|
||||
return Number.MAX_VALUE;
|
||||
};
|
||||
|
||||
export const totalmem = function () {
|
||||
return Number.MAX_VALUE;
|
||||
};
|
||||
|
||||
export const cpus = function () {
|
||||
return [];
|
||||
};
|
||||
|
||||
export const type = function () {
|
||||
return "Browser";
|
||||
};
|
||||
|
||||
export const release = function () {
|
||||
if (typeof navigator !== "undefined") {
|
||||
return navigator.appVersion;
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
export const getNetworkInterfaces = function () {
|
||||
return {};
|
||||
};
|
||||
export const networkInterfaces = getNetworkInterfaces;
|
||||
|
||||
export const arch = function () {
|
||||
return "javascript";
|
||||
};
|
||||
|
||||
export const platform = function () {
|
||||
return "browser";
|
||||
};
|
||||
|
||||
export const tmpdir = function () {
|
||||
return "/tmp";
|
||||
};
|
||||
export const tmpDir = tmpdir;
|
||||
|
||||
export const EOL = "\n";
|
||||
|
||||
export const homedir = function () {
|
||||
return "/";
|
||||
};
|
||||
|
||||
@@ -6,33 +6,33 @@
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"build-gen": "bash -c 'esbuild --bundle *.js --outdir=bun --format=esm --platform=browser --external:buffer --external:stream --external:util --external:util/ --external:assert'",
|
||||
"build": "bash -c 'esbuild --bundle *.js --outdir=out --format=esm --minify --platform=browser'"
|
||||
"build": "bash -c 'esbuild --bundle *.js --outdir=out --format=esm --minify-syntax --platform=browser --external:node:buffer --external:node:timers/promises'"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"assert": "^2.0.0",
|
||||
"assert": "^2.1.0",
|
||||
"browserify-zlib": "^0.2.0",
|
||||
"buffer": "^6.0.3",
|
||||
"console-browserify": "^1.2.0",
|
||||
"constants-browserify": "^1.0.0",
|
||||
"crypto-browserify": "^3.12.0",
|
||||
"domain-browser": "^4.22.0",
|
||||
"esbuild": "^0.14.10",
|
||||
"domain-browser": "^4.23.0",
|
||||
"esbuild": "^0.14.54",
|
||||
"events": "^3.3.0",
|
||||
"https-browserify": "^1.0.0",
|
||||
"os-browserify": "^0.3.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"process": "^0.11.10",
|
||||
"punycode": "^2.1.1",
|
||||
"punycode": "^2.3.1",
|
||||
"querystring-es3": "^1.0.0-0",
|
||||
"readable-stream": "^4.1.0",
|
||||
"readable-stream": "^4.5.2",
|
||||
"stream-http": "^3.2.0",
|
||||
"string_decoder": "^1.3.0",
|
||||
"timers-browserify": "^2.0.12",
|
||||
"tty-browserify": "^0.0.1",
|
||||
"url": "^0.11.0",
|
||||
"util": "^0.12.4",
|
||||
"url": "^0.11.4",
|
||||
"util": "^0.12.5",
|
||||
"vm-browserify": "^1.1.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +1,530 @@
|
||||
export * from "path-browserify";
|
||||
export * as default from "path-browserify";
|
||||
// 'path' module extracted from Node.js v8.11.1 (only the posix part)
|
||||
// transplited with Babel
|
||||
|
||||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the
|
||||
// "Software"), to deal in the Software without restriction, including
|
||||
// without limitation the rights to use, copy, modify, merge, publish,
|
||||
// distribute, sublicense, and/or sell copies of the Software, and to permit
|
||||
// persons to whom the Software is furnished to do so, subject to the
|
||||
// following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included
|
||||
// in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
||||
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
"use strict";
|
||||
|
||||
function assertPath(path) {
|
||||
if (typeof path !== "string") {
|
||||
throw new TypeError("Path must be a string. Received " + JSON.stringify(path));
|
||||
}
|
||||
}
|
||||
|
||||
// Resolves . and .. elements in a path with directory names
|
||||
function normalizeStringPosix(path, allowAboveRoot) {
|
||||
var res = "";
|
||||
var lastSegmentLength = 0;
|
||||
var lastSlash = -1;
|
||||
var dots = 0;
|
||||
var code;
|
||||
for (var i = 0; i <= path.length; ++i) {
|
||||
if (i < path.length) code = path.charCodeAt(i);
|
||||
else if (code === 47 /*/*/) break;
|
||||
else code = 47 /*/*/;
|
||||
if (code === 47 /*/*/) {
|
||||
if (lastSlash === i - 1 || dots === 1) {
|
||||
// NOOP
|
||||
} else if (lastSlash !== i - 1 && dots === 2) {
|
||||
if (
|
||||
res.length < 2 ||
|
||||
lastSegmentLength !== 2 ||
|
||||
res.charCodeAt(res.length - 1) !== 46 /*.*/ ||
|
||||
res.charCodeAt(res.length - 2) !== 46 /*.*/
|
||||
) {
|
||||
if (res.length > 2) {
|
||||
var lastSlashIndex = res.lastIndexOf("/");
|
||||
if (lastSlashIndex !== res.length - 1) {
|
||||
if (lastSlashIndex === -1) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
} else {
|
||||
res = res.slice(0, lastSlashIndex);
|
||||
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
||||
}
|
||||
lastSlash = i;
|
||||
dots = 0;
|
||||
continue;
|
||||
}
|
||||
} else if (res.length === 2 || res.length === 1) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
lastSlash = i;
|
||||
dots = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (allowAboveRoot) {
|
||||
if (res.length > 0) res += "/..";
|
||||
else res = "..";
|
||||
lastSegmentLength = 2;
|
||||
}
|
||||
} else {
|
||||
if (res.length > 0) res += "/" + path.slice(lastSlash + 1, i);
|
||||
else res = path.slice(lastSlash + 1, i);
|
||||
lastSegmentLength = i - lastSlash - 1;
|
||||
}
|
||||
lastSlash = i;
|
||||
dots = 0;
|
||||
} else if (code === 46 /*.*/ && dots !== -1) {
|
||||
++dots;
|
||||
} else {
|
||||
dots = -1;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
function _format(sep, pathObject) {
|
||||
var dir = pathObject.dir || pathObject.root;
|
||||
var base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
|
||||
if (!dir) {
|
||||
return base;
|
||||
}
|
||||
if (dir === pathObject.root) {
|
||||
return dir + base;
|
||||
}
|
||||
return dir + sep + base;
|
||||
}
|
||||
|
||||
// path.resolve([from ...], to)
|
||||
export function resolve() {
|
||||
var resolvedPath = "";
|
||||
var resolvedAbsolute = false;
|
||||
var cwd;
|
||||
|
||||
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
|
||||
var path;
|
||||
if (i >= 0) path = arguments[i];
|
||||
else {
|
||||
if (cwd === undefined) cwd = process.cwd();
|
||||
path = cwd;
|
||||
}
|
||||
|
||||
assertPath(path);
|
||||
|
||||
// Skip empty entries
|
||||
if (path.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
resolvedPath = path + "/" + resolvedPath;
|
||||
resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;
|
||||
}
|
||||
|
||||
// At this point the path should be resolved to a full absolute path, but
|
||||
// handle relative paths to be safe (might happen when process.cwd() fails)
|
||||
|
||||
// Normalize the path
|
||||
resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
|
||||
|
||||
if (resolvedAbsolute) {
|
||||
if (resolvedPath.length > 0) return "/" + resolvedPath;
|
||||
else return "/";
|
||||
} else if (resolvedPath.length > 0) {
|
||||
return resolvedPath;
|
||||
} else {
|
||||
return ".";
|
||||
}
|
||||
}
|
||||
|
||||
export function normalize(path) {
|
||||
assertPath(path);
|
||||
|
||||
if (path.length === 0) return ".";
|
||||
|
||||
var isAbsolute = path.charCodeAt(0) === 47; /*/*/
|
||||
var trailingSeparator = path.charCodeAt(path.length - 1) === 47; /*/*/
|
||||
|
||||
// Normalize the path
|
||||
path = normalizeStringPosix(path, !isAbsolute);
|
||||
|
||||
if (path.length === 0 && !isAbsolute) path = ".";
|
||||
if (path.length > 0 && trailingSeparator) path += "/";
|
||||
|
||||
if (isAbsolute) return "/" + path;
|
||||
return path;
|
||||
}
|
||||
|
||||
export function isAbsolute(path) {
|
||||
assertPath(path);
|
||||
return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;
|
||||
}
|
||||
|
||||
export function join() {
|
||||
if (arguments.length === 0) return ".";
|
||||
var joined;
|
||||
for (var i = 0; i < arguments.length; ++i) {
|
||||
var arg = arguments[i];
|
||||
assertPath(arg);
|
||||
if (arg.length > 0) {
|
||||
if (joined === undefined) joined = arg;
|
||||
else joined += "/" + arg;
|
||||
}
|
||||
}
|
||||
if (joined === undefined) return ".";
|
||||
return normalize(joined);
|
||||
}
|
||||
|
||||
export function relative(from, to) {
|
||||
assertPath(from);
|
||||
assertPath(to);
|
||||
|
||||
if (from === to) return "";
|
||||
|
||||
from = resolve(from);
|
||||
to = resolve(to);
|
||||
|
||||
if (from === to) return "";
|
||||
|
||||
// Trim any leading backslashes
|
||||
var fromStart = 1;
|
||||
for (; fromStart < from.length; ++fromStart) {
|
||||
if (from.charCodeAt(fromStart) !== 47 /*/*/) break;
|
||||
}
|
||||
var fromEnd = from.length;
|
||||
var fromLen = fromEnd - fromStart;
|
||||
|
||||
// Trim any leading backslashes
|
||||
var toStart = 1;
|
||||
for (; toStart < to.length; ++toStart) {
|
||||
if (to.charCodeAt(toStart) !== 47 /*/*/) break;
|
||||
}
|
||||
var toEnd = to.length;
|
||||
var toLen = toEnd - toStart;
|
||||
|
||||
// Compare paths to find the longest common path from root
|
||||
var length = fromLen < toLen ? fromLen : toLen;
|
||||
var lastCommonSep = -1;
|
||||
var i = 0;
|
||||
for (; i <= length; ++i) {
|
||||
if (i === length) {
|
||||
if (toLen > length) {
|
||||
if (to.charCodeAt(toStart + i) === 47 /*/*/) {
|
||||
// We get here if `from` is the exact base path for `to`.
|
||||
// For example: from='/foo/bar'; to='/foo/bar/baz'
|
||||
return to.slice(toStart + i + 1);
|
||||
} else if (i === 0) {
|
||||
// We get here if `from` is the root
|
||||
// For example: from='/'; to='/foo'
|
||||
return to.slice(toStart + i);
|
||||
}
|
||||
} else if (fromLen > length) {
|
||||
if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
|
||||
// We get here if `to` is the exact base path for `from`.
|
||||
// For example: from='/foo/bar/baz'; to='/foo/bar'
|
||||
lastCommonSep = i;
|
||||
} else if (i === 0) {
|
||||
// We get here if `to` is the root.
|
||||
// For example: from='/foo'; to='/'
|
||||
lastCommonSep = 0;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
var fromCode = from.charCodeAt(fromStart + i);
|
||||
var toCode = to.charCodeAt(toStart + i);
|
||||
if (fromCode !== toCode) break;
|
||||
else if (fromCode === 47 /*/*/) lastCommonSep = i;
|
||||
}
|
||||
|
||||
var out = "";
|
||||
// Generate the relative path based on the path difference between `to`
|
||||
// and `from`
|
||||
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
|
||||
if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
|
||||
if (out.length === 0) out += "..";
|
||||
else out += "/..";
|
||||
}
|
||||
}
|
||||
|
||||
// Lastly, append the rest of the destination (`to`) path that comes after
|
||||
// the common path parts
|
||||
if (out.length > 0) return out + to.slice(toStart + lastCommonSep);
|
||||
else {
|
||||
toStart += lastCommonSep;
|
||||
if (to.charCodeAt(toStart) === 47 /*/*/) ++toStart;
|
||||
return to.slice(toStart);
|
||||
}
|
||||
}
|
||||
|
||||
export function _makeLong(path) {
|
||||
return path;
|
||||
}
|
||||
|
||||
export function dirname(path) {
|
||||
assertPath(path);
|
||||
if (path.length === 0) return ".";
|
||||
var code = path.charCodeAt(0);
|
||||
var hasRoot = code === 47; /*/*/
|
||||
var end = -1;
|
||||
var matchedSlash = true;
|
||||
for (var i = path.length - 1; i >= 1; --i) {
|
||||
code = path.charCodeAt(i);
|
||||
if (code === 47 /*/*/) {
|
||||
if (!matchedSlash) {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// We saw the first non-path separator
|
||||
matchedSlash = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (end === -1) return hasRoot ? "/" : ".";
|
||||
if (hasRoot && end === 1) return "//";
|
||||
return path.slice(0, end);
|
||||
}
|
||||
|
||||
export function basename(path, ext) {
|
||||
if (ext !== undefined && typeof ext !== "string") throw new TypeError('"ext" argument must be a string');
|
||||
assertPath(path);
|
||||
|
||||
var start = 0;
|
||||
var end = -1;
|
||||
var matchedSlash = true;
|
||||
var i;
|
||||
|
||||
if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
|
||||
if (ext.length === path.length && ext === path) return "";
|
||||
var extIdx = ext.length - 1;
|
||||
var firstNonSlashEnd = -1;
|
||||
for (i = path.length - 1; i >= 0; --i) {
|
||||
var code = path.charCodeAt(i);
|
||||
if (code === 47 /*/*/) {
|
||||
// If we reached a path separator that was not part of a set of path
|
||||
// separators at the end of the string, stop now
|
||||
if (!matchedSlash) {
|
||||
start = i + 1;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (firstNonSlashEnd === -1) {
|
||||
// We saw the first non-path separator, remember this index in case
|
||||
// we need it if the extension ends up not matching
|
||||
matchedSlash = false;
|
||||
firstNonSlashEnd = i + 1;
|
||||
}
|
||||
if (extIdx >= 0) {
|
||||
// Try to match the explicit extension
|
||||
if (code === ext.charCodeAt(extIdx)) {
|
||||
if (--extIdx === -1) {
|
||||
// We matched the extension, so mark this as the end of our path
|
||||
// component
|
||||
end = i;
|
||||
}
|
||||
} else {
|
||||
// Extension does not match, so our result is the entire path
|
||||
// component
|
||||
extIdx = -1;
|
||||
end = firstNonSlashEnd;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (start === end) end = firstNonSlashEnd;
|
||||
else if (end === -1) end = path.length;
|
||||
return path.slice(start, end);
|
||||
} else {
|
||||
for (i = path.length - 1; i >= 0; --i) {
|
||||
if (path.charCodeAt(i) === 47 /*/*/) {
|
||||
// If we reached a path separator that was not part of a set of path
|
||||
// separators at the end of the string, stop now
|
||||
if (!matchedSlash) {
|
||||
start = i + 1;
|
||||
break;
|
||||
}
|
||||
} else if (end === -1) {
|
||||
// We saw the first non-path separator, mark this as the end of our
|
||||
// path component
|
||||
matchedSlash = false;
|
||||
end = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (end === -1) return "";
|
||||
return path.slice(start, end);
|
||||
}
|
||||
}
|
||||
|
||||
export function extname(path) {
|
||||
assertPath(path);
|
||||
var startDot = -1;
|
||||
var startPart = 0;
|
||||
var end = -1;
|
||||
var matchedSlash = true;
|
||||
// Track the state of characters (if any) we see before our first dot and
|
||||
// after any path separator we find
|
||||
var preDotState = 0;
|
||||
for (var i = path.length - 1; i >= 0; --i) {
|
||||
var code = path.charCodeAt(i);
|
||||
if (code === 47 /*/*/) {
|
||||
// If we reached a path separator that was not part of a set of path
|
||||
// separators at the end of the string, stop now
|
||||
if (!matchedSlash) {
|
||||
startPart = i + 1;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (end === -1) {
|
||||
// We saw the first non-path separator, mark this as the end of our
|
||||
// extension
|
||||
matchedSlash = false;
|
||||
end = i + 1;
|
||||
}
|
||||
if (code === 46 /*.*/) {
|
||||
// If this is our first dot, mark it as the start of our extension
|
||||
if (startDot === -1) startDot = i;
|
||||
else if (preDotState !== 1) preDotState = 1;
|
||||
} else if (startDot !== -1) {
|
||||
// We saw a non-dot and non-path separator before our dot, so we should
|
||||
// have a good chance at having a non-empty extension
|
||||
preDotState = -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
startDot === -1 ||
|
||||
end === -1 ||
|
||||
// We saw a non-dot character immediately before the dot
|
||||
preDotState === 0 ||
|
||||
// The (right-most) trimmed path component is exactly '..'
|
||||
(preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
|
||||
) {
|
||||
return "";
|
||||
}
|
||||
return path.slice(startDot, end);
|
||||
}
|
||||
|
||||
export function format(pathObject) {
|
||||
if (pathObject === null || typeof pathObject !== "object") {
|
||||
throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
|
||||
}
|
||||
return _format("/", pathObject);
|
||||
}
|
||||
|
||||
export function parse(path) {
|
||||
assertPath(path);
|
||||
|
||||
var ret = { root: "", dir: "", base: "", ext: "", name: "" };
|
||||
if (path.length === 0) return ret;
|
||||
var code = path.charCodeAt(0);
|
||||
var isAbsolute = code === 47; /*/*/
|
||||
var start;
|
||||
if (isAbsolute) {
|
||||
ret.root = "/";
|
||||
start = 1;
|
||||
} else {
|
||||
start = 0;
|
||||
}
|
||||
var startDot = -1;
|
||||
var startPart = 0;
|
||||
var end = -1;
|
||||
var matchedSlash = true;
|
||||
var i = path.length - 1;
|
||||
|
||||
// Track the state of characters (if any) we see before our first dot and
|
||||
// after any path separator we find
|
||||
var preDotState = 0;
|
||||
|
||||
// Get non-dir info
|
||||
for (; i >= start; --i) {
|
||||
code = path.charCodeAt(i);
|
||||
if (code === 47 /*/*/) {
|
||||
// If we reached a path separator that was not part of a set of path
|
||||
// separators at the end of the string, stop now
|
||||
if (!matchedSlash) {
|
||||
startPart = i + 1;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (end === -1) {
|
||||
// We saw the first non-path separator, mark this as the end of our
|
||||
// extension
|
||||
matchedSlash = false;
|
||||
end = i + 1;
|
||||
}
|
||||
if (code === 46 /*.*/) {
|
||||
// If this is our first dot, mark it as the start of our extension
|
||||
if (startDot === -1) startDot = i;
|
||||
else if (preDotState !== 1) preDotState = 1;
|
||||
} else if (startDot !== -1) {
|
||||
// We saw a non-dot and non-path separator before our dot, so we should
|
||||
// have a good chance at having a non-empty extension
|
||||
preDotState = -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
startDot === -1 ||
|
||||
end === -1 ||
|
||||
// We saw a non-dot character immediately before the dot
|
||||
preDotState === 0 ||
|
||||
// The (right-most) trimmed path component is exactly '..'
|
||||
(preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
|
||||
) {
|
||||
if (end !== -1) {
|
||||
if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);
|
||||
else ret.base = ret.name = path.slice(startPart, end);
|
||||
}
|
||||
} else {
|
||||
if (startPart === 0 && isAbsolute) {
|
||||
ret.name = path.slice(1, startDot);
|
||||
ret.base = path.slice(1, end);
|
||||
} else {
|
||||
ret.name = path.slice(startPart, startDot);
|
||||
ret.base = path.slice(startPart, end);
|
||||
}
|
||||
ret.ext = path.slice(startDot, end);
|
||||
}
|
||||
|
||||
if (startPart > 0) ret.dir = path.slice(0, startPart - 1);
|
||||
else if (isAbsolute) ret.dir = "/";
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
export const sep = "/";
|
||||
export const delimiter = ":";
|
||||
|
||||
// Use an IIFE to allow for tree-shaking
|
||||
export const posix = /* @__PURE__ */ (p => ((p.posix = p), p))({
|
||||
resolve,
|
||||
normalize,
|
||||
isAbsolute,
|
||||
join,
|
||||
relative,
|
||||
_makeLong,
|
||||
dirname,
|
||||
basename,
|
||||
extname,
|
||||
format,
|
||||
parse,
|
||||
sep,
|
||||
delimiter,
|
||||
win32: null,
|
||||
posix: null,
|
||||
});
|
||||
|
||||
@@ -1,2 +1,96 @@
|
||||
export * from "process/browser";
|
||||
export * as default from "process/browser";
|
||||
// shim for using process in browser
|
||||
var queue = [];
|
||||
var draining = false;
|
||||
var currentQueue;
|
||||
var queueIndex = -1;
|
||||
|
||||
function cleanUpNextTick() {
|
||||
if (!draining || !currentQueue) {
|
||||
return;
|
||||
}
|
||||
draining = false;
|
||||
if (currentQueue.length) {
|
||||
queue = currentQueue.concat(queue);
|
||||
} else {
|
||||
queueIndex = -1;
|
||||
}
|
||||
if (queue.length) {
|
||||
drainQueue();
|
||||
}
|
||||
}
|
||||
|
||||
function drainQueue() {
|
||||
if (draining) {
|
||||
return;
|
||||
}
|
||||
var timeout = setTimeout(cleanUpNextTick, 0);
|
||||
draining = true;
|
||||
var len = queue.length;
|
||||
while (len) {
|
||||
currentQueue = queue;
|
||||
queue = [];
|
||||
while (++queueIndex < len) {
|
||||
if (currentQueue) {
|
||||
var item = currentQueue[queueIndex];
|
||||
item.fun.apply(null, item.array);
|
||||
}
|
||||
}
|
||||
queueIndex = -1;
|
||||
len = queue.length;
|
||||
}
|
||||
currentQueue = null;
|
||||
draining = false;
|
||||
clearTimeout(timeout, 0);
|
||||
}
|
||||
|
||||
export function nextTick(fun) {
|
||||
var args = new Array(arguments.length - 1);
|
||||
if (arguments.length > 1) {
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
args[i - 1] = arguments[i];
|
||||
}
|
||||
}
|
||||
queue.push({ fun, args });
|
||||
if (queue.length === 1 && !draining) {
|
||||
setTimeout(drainQueue, 0);
|
||||
}
|
||||
}
|
||||
|
||||
export const title = "browser";
|
||||
export const browser = true;
|
||||
export const env = {};
|
||||
export const argv = [];
|
||||
export const version = ""; // empty string to avoid regexp issues
|
||||
export const versions = {};
|
||||
|
||||
function noop() {}
|
||||
|
||||
export const on = noop;
|
||||
export const addListener = noop;
|
||||
export const once = noop;
|
||||
export const off = noop;
|
||||
export const removeListener = noop;
|
||||
export const removeAllListeners = noop;
|
||||
export const emit = noop;
|
||||
export const prependListener = noop;
|
||||
export const prependOnceListener = noop;
|
||||
|
||||
export const listeners = function (name) {
|
||||
return [];
|
||||
};
|
||||
|
||||
export const binding = function (name) {
|
||||
throw new Error("process.binding is not supported in browser polyfill");
|
||||
};
|
||||
|
||||
export const cwd = function () {
|
||||
return "/";
|
||||
};
|
||||
|
||||
export const chdir = function (dir) {
|
||||
throw new Error("process.chdir is not supported in browser polyfill");
|
||||
};
|
||||
|
||||
export const umask = function () {
|
||||
return 0;
|
||||
};
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export { unescapeBuffer, unescape, escape, stringify, encode, parse, decode } from "querystring-es3";
|
||||
export { default } from "querystring-es3";
|
||||
import querystring from "querystring-es3";
|
||||
export var { unescapeBuffer, unescape, escape, stringify, encode, parse, decode } = querystring;
|
||||
|
||||
@@ -1,2 +1,26 @@
|
||||
export * from "readable-stream";
|
||||
export * as default from "readable-stream";
|
||||
import stream from "readable-stream";
|
||||
|
||||
export const ReadableState = stream.ReadableState;
|
||||
export const _fromList = stream._fromList;
|
||||
export const from = stream.from;
|
||||
export const fromWeb = stream.fromWeb;
|
||||
export const toWeb = stream.toWeb;
|
||||
export const wrap = stream.wrap;
|
||||
export const _uint8ArrayToBuffer = stream._uint8ArrayToBuffer;
|
||||
export const _isUint8Array = stream._isUint8Array;
|
||||
export const isDisturbed = stream.isDisturbed;
|
||||
export const isErrored = stream.isErrored;
|
||||
export const isReadable = stream.isReadable;
|
||||
export const Readable = stream.Readable;
|
||||
export const Writable = stream.Writable;
|
||||
export const Duplex = stream.Duplex;
|
||||
export const Transform = stream.Transform;
|
||||
export const PassThrough = stream.PassThrough;
|
||||
export const addAbortSignal = stream.addAbortSignal;
|
||||
export const finished = stream.finished;
|
||||
export const destroy = stream.destroy;
|
||||
export const pipeline = stream.pipeline;
|
||||
export const compose = stream.compose;
|
||||
export const Stream = stream.Stream;
|
||||
|
||||
export default stream;
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
// TODO: This depends on a separate buffer polyfill
|
||||
export { StringDecoder, StringDecoder as default } from "string_decoder";
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
export * from "util";
|
||||
export * as default from "util";
|
||||
@@ -1,2 +1,9 @@
|
||||
export * from "timers-browserify";
|
||||
export * as default from "timers-browserify";
|
||||
// Hardcoded module "node:timers"
|
||||
export const setTimeout = globalThis.setTimeout;
|
||||
export const clearTimeout = globalThis.clearTimeout;
|
||||
export const setInterval = globalThis.setInterval;
|
||||
export const setImmediate = globalThis.setImmediate;
|
||||
export const clearInterval = globalThis.clearInterval;
|
||||
export const clearImmediate = globalThis.clearImmediate;
|
||||
export const _unrefActive = () => {};
|
||||
export * as promises from "node:timers/promises";
|
||||
|
||||
238
src/node-fallbacks/timers.promises.js
Normal file
238
src/node-fallbacks/timers.promises.js
Normal file
@@ -0,0 +1,238 @@
|
||||
// Hardcoded module "node:timers/promises"
|
||||
// https://github.com/niksy/isomorphic-timers-promises/blob/master/index.js
|
||||
const symbolAsyncIterator = /* @__PURE__ */ Symbol.asyncIterator;
|
||||
|
||||
class ERR_INVALID_ARG_TYPE extends Error {
|
||||
constructor(name, expected, actual) {
|
||||
super(`${name} must be ${expected}, ${typeof actual} given`);
|
||||
this.code = "ERR_INVALID_ARG_TYPE";
|
||||
}
|
||||
}
|
||||
|
||||
class AbortError extends Error {
|
||||
constructor() {
|
||||
super("The operation was aborted");
|
||||
this.code = "ABORT_ERR";
|
||||
}
|
||||
}
|
||||
|
||||
function validateObject(object, name) {
|
||||
if (object === null || typeof object !== "object") {
|
||||
throw new ERR_INVALID_ARG_TYPE(name, "Object", object);
|
||||
}
|
||||
}
|
||||
|
||||
function validateBoolean(value, name) {
|
||||
if (typeof value !== "boolean") {
|
||||
throw new ERR_INVALID_ARG_TYPE(name, "boolean", value);
|
||||
}
|
||||
}
|
||||
|
||||
function validateAbortSignal(signal, name) {
|
||||
if (typeof signal !== "undefined" && (signal === null || typeof signal !== "object" || !("aborted" in signal))) {
|
||||
throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal);
|
||||
}
|
||||
}
|
||||
|
||||
function asyncIterator({ next: nextFunction, return: returnFunction }) {
|
||||
const result = {};
|
||||
if (typeof nextFunction === "function") {
|
||||
result.next = nextFunction;
|
||||
}
|
||||
if (typeof returnFunction === "function") {
|
||||
result.return = returnFunction;
|
||||
}
|
||||
result[symbolAsyncIterator] = function () {
|
||||
return this;
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function setTimeoutPromise(after = 1, value, options = {}) {
|
||||
const arguments_ = [].concat(value ?? []);
|
||||
try {
|
||||
validateObject(options, "options");
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
const { signal, ref: reference = true } = options;
|
||||
try {
|
||||
validateAbortSignal(signal, "options.signal");
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
try {
|
||||
validateBoolean(reference, "options.ref");
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
return Promise.reject(new AbortError());
|
||||
}
|
||||
let onCancel;
|
||||
const returnValue = new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => resolve(value), after, ...arguments_);
|
||||
if (!reference) {
|
||||
timeout?.unref?.();
|
||||
}
|
||||
if (signal) {
|
||||
onCancel = () => {
|
||||
clearTimeout(timeout);
|
||||
reject(new AbortError());
|
||||
};
|
||||
signal.addEventListener("abort", onCancel);
|
||||
}
|
||||
});
|
||||
return typeof onCancel !== "undefined"
|
||||
? returnValue.finally(() => signal.removeEventListener("abort", onCancel))
|
||||
: returnValue;
|
||||
}
|
||||
|
||||
function setImmediatePromise(value, options = {}) {
|
||||
try {
|
||||
validateObject(options, "options");
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
const { signal, ref: reference = true } = options;
|
||||
try {
|
||||
validateAbortSignal(signal, "options.signal");
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
try {
|
||||
validateBoolean(reference, "options.ref");
|
||||
} catch (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
return Promise.reject(new AbortError());
|
||||
}
|
||||
let onCancel;
|
||||
const returnValue = new Promise((resolve, reject) => {
|
||||
const immediate = setImmediate(() => resolve(value));
|
||||
if (!reference) {
|
||||
immediate?.unref?.();
|
||||
}
|
||||
if (signal) {
|
||||
onCancel = () => {
|
||||
clearImmediate(immediate);
|
||||
reject(new AbortError());
|
||||
};
|
||||
signal.addEventListener("abort", onCancel);
|
||||
}
|
||||
});
|
||||
return typeof onCancel !== "undefined"
|
||||
? returnValue.finally(() => signal.removeEventListener("abort", onCancel))
|
||||
: returnValue;
|
||||
}
|
||||
|
||||
function setIntervalPromise(after = 1, value, options = {}) {
|
||||
/* eslint-disable no-undefined, no-unreachable-loop, no-loop-func */
|
||||
try {
|
||||
validateObject(options, "options");
|
||||
} catch (error) {
|
||||
return asyncIterator({
|
||||
next: function () {
|
||||
return Promise.reject(error);
|
||||
},
|
||||
});
|
||||
}
|
||||
const { signal, ref: reference = true } = options;
|
||||
try {
|
||||
validateAbortSignal(signal, "options.signal");
|
||||
} catch (error) {
|
||||
return asyncIterator({
|
||||
next: function () {
|
||||
return Promise.reject(error);
|
||||
},
|
||||
});
|
||||
}
|
||||
try {
|
||||
validateBoolean(reference, "options.ref");
|
||||
} catch (error) {
|
||||
return asyncIterator({
|
||||
next: function () {
|
||||
return Promise.reject(error);
|
||||
},
|
||||
});
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
return asyncIterator({
|
||||
next: function () {
|
||||
return Promise.reject(new AbortError());
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let onCancel, interval;
|
||||
|
||||
try {
|
||||
let notYielded = 0;
|
||||
let callback;
|
||||
interval = setInterval(() => {
|
||||
notYielded++;
|
||||
if (callback) {
|
||||
callback();
|
||||
callback = undefined;
|
||||
}
|
||||
}, after);
|
||||
if (!reference) {
|
||||
interval?.unref?.();
|
||||
}
|
||||
if (signal) {
|
||||
onCancel = () => {
|
||||
clearInterval(interval);
|
||||
if (callback) {
|
||||
callback();
|
||||
callback = undefined;
|
||||
}
|
||||
};
|
||||
signal.addEventListener("abort", onCancel);
|
||||
}
|
||||
|
||||
return asyncIterator({
|
||||
next: function () {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!signal?.aborted) {
|
||||
if (notYielded === 0) {
|
||||
callback = resolve;
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
} else if (notYielded === 0) {
|
||||
reject(new AbortError());
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
}).then(() => {
|
||||
if (notYielded > 0) {
|
||||
notYielded = notYielded - 1;
|
||||
return { done: false, value: value };
|
||||
}
|
||||
return { done: true };
|
||||
});
|
||||
},
|
||||
return: function () {
|
||||
clearInterval(interval);
|
||||
signal?.removeEventListener("abort", onCancel);
|
||||
return Promise.resolve({});
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return asyncIterator({
|
||||
next: function () {
|
||||
clearInterval(interval);
|
||||
signal?.removeEventListener("abort", onCancel);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { setTimeoutPromise as setTimeout, setImmediatePromise as setImmediate, setIntervalPromise as setInterval };
|
||||
|
||||
export const scheduler = {
|
||||
wait: (delay, options) => setTimeoutPromise(delay, undefined, options),
|
||||
yield: setImmediatePromise,
|
||||
};
|
||||
@@ -6,4 +6,3 @@ function ReadStream() {
|
||||
throw new Error("tty.ReadStream is not implemented for browsers");
|
||||
}
|
||||
export { isatty, ReadStream, WriteStream };
|
||||
export default { isatty, ReadStream, WriteStream };
|
||||
|
||||
@@ -20,7 +20,8 @@
|
||||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
"use strict";
|
||||
const { URL, URLSearchParams } = globalThis;
|
||||
const URL = /* @__PURE__ */ globalThis.URL;
|
||||
const URLSearchParams = /* @__PURE__ */ globalThis.URLSearchParams;
|
||||
|
||||
function util_isString(arg) {
|
||||
return typeof arg === "string";
|
||||
@@ -34,9 +35,6 @@ function util_isNull(arg) {
|
||||
function util_isNullOrUndefined(arg) {
|
||||
return arg == null;
|
||||
}
|
||||
function util_isUndefined(arg) {
|
||||
return arg === void 0;
|
||||
}
|
||||
|
||||
function Url() {
|
||||
this.protocol = null;
|
||||
|
||||
@@ -1,7 +1,949 @@
|
||||
export * from "util";
|
||||
// NOTE: THIS IS A BROWSER POLYFILL - Bun's actual node:* modules are in src/js/node
|
||||
//
|
||||
// This file is derived from https://www.npmjs.com/package/util v0.12.5,
|
||||
// converted into an Tree-shaking ES Module.
|
||||
|
||||
const TextEncoder = globalThis.TextEncoder;
|
||||
const TextDecoder = globalThis.TextDecoder;
|
||||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the
|
||||
// "Software"), to deal in the Software without restriction, including
|
||||
// without limitation the rights to use, copy, modify, merge, publish,
|
||||
// distribute, sublicense, and/or sell copies of the Software, and to permit
|
||||
// persons to whom the Software is furnished to do so, subject to the
|
||||
// following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included
|
||||
// in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
||||
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
export { TextEncoder, TextDecoder };
|
||||
export default { TextEncoder, TextDecoder };
|
||||
var formatRegExp = /%[sdj%]/g;
|
||||
export function format(f, ...args) {
|
||||
if (!isString(f)) {
|
||||
var objects = [f];
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
objects.push(inspect(args[i]));
|
||||
}
|
||||
return objects.join(" ");
|
||||
}
|
||||
|
||||
var i = 0;
|
||||
var len = args.length;
|
||||
var str = String(f).replace(formatRegExp, function (x) {
|
||||
if (x === "%%") return "%";
|
||||
if (i >= len) return x;
|
||||
switch (x) {
|
||||
case "%s":
|
||||
return String(args[i++]);
|
||||
case "%d":
|
||||
return Number(args[i++]);
|
||||
case "%j":
|
||||
try {
|
||||
return JSON.stringify(args[i++]);
|
||||
} catch (_) {
|
||||
return "[Circular]";
|
||||
}
|
||||
default:
|
||||
return x;
|
||||
}
|
||||
});
|
||||
for (var x = args[i]; i < len; x = args[++i]) {
|
||||
if (isNull(x) || !isObject(x)) {
|
||||
str += " " + x;
|
||||
} else {
|
||||
str += " " + inspect(x);
|
||||
}
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
// Mark that a method should not be used.
|
||||
// Returns a modified function which warns once by default.
|
||||
// If --no-deprecation is set, then it is a no-op.
|
||||
export function deprecate(fn, msg) {
|
||||
if (typeof process === "undefined" || process?.noDeprecation === true) {
|
||||
return fn;
|
||||
}
|
||||
|
||||
var warned = false;
|
||||
function deprecated(...args) {
|
||||
if (!warned) {
|
||||
if (process.throwDeprecation) {
|
||||
throw new Error(msg);
|
||||
} else if (process.traceDeprecation) {
|
||||
console.trace(msg);
|
||||
} else {
|
||||
console.error(msg);
|
||||
}
|
||||
warned = true;
|
||||
}
|
||||
return fn.apply(this, ...args);
|
||||
}
|
||||
|
||||
return deprecated;
|
||||
}
|
||||
|
||||
// This function has been edited to be tree-shakable and minifiable
|
||||
export const debuglog = /* @__PURE__ */ ((debugs = {}, debugEnvRegex = {}, debugEnv) => (
|
||||
((debugEnv = typeof process !== "undefined" && process.env.NODE_DEBUG) &&
|
||||
(debugEnv = debugEnv
|
||||
.replace(/[|\\{}()[\]^$+?.]/g, "\\$&")
|
||||
.replace(/\*/g, ".*")
|
||||
.replace(/,/g, "$|^")
|
||||
.toUpperCase()),
|
||||
(debugEnvRegex = new RegExp("^" + debugEnv + "$", "i"))),
|
||||
set => {
|
||||
set = set.toUpperCase();
|
||||
if (!debugs[set]) {
|
||||
if (debugEnvRegex.test(set)) {
|
||||
debugs[set] = function (...args) {
|
||||
console.error("%s: %s", set, pid, format.apply(null, ...args));
|
||||
};
|
||||
} else {
|
||||
debugs[set] = function () {};
|
||||
}
|
||||
}
|
||||
return debugs[set];
|
||||
}
|
||||
))();
|
||||
|
||||
/**
|
||||
* Echos the value of a value. Tries to print the value out
|
||||
* in the best way possible given the different types.
|
||||
*
|
||||
* @param {Object} obj The object to print out.
|
||||
* @param {Object} opts Optional options object that alters the output.
|
||||
*/
|
||||
/* legacy: obj, showHidden, depth, colors*/
|
||||
export const inspect = /* @__PURE__ */ (i =>
|
||||
(
|
||||
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
|
||||
(i.colors = {
|
||||
"bold": [1, 22],
|
||||
"italic": [3, 23],
|
||||
"underline": [4, 24],
|
||||
"inverse": [7, 27],
|
||||
"white": [37, 39],
|
||||
"grey": [90, 39],
|
||||
"black": [30, 39],
|
||||
"blue": [34, 39],
|
||||
"cyan": [36, 39],
|
||||
"green": [32, 39],
|
||||
"magenta": [35, 39],
|
||||
"red": [31, 39],
|
||||
"yellow": [33, 39],
|
||||
}),
|
||||
// Don't use 'blue' not visible on cmd.exe
|
||||
(i.styles = {
|
||||
"special": "cyan",
|
||||
"number": "yellow",
|
||||
"boolean": "yellow",
|
||||
"undefined": "grey",
|
||||
"null": "bold",
|
||||
"string": "green",
|
||||
"date": "magenta",
|
||||
// "name": intentionally not styling
|
||||
"regexp": "red",
|
||||
}),
|
||||
(i.custom = Symbol.for("nodejs.util.inspect.custom")),
|
||||
i
|
||||
))(function inspect(obj, opts, ...rest) {
|
||||
// default options
|
||||
var ctx = {
|
||||
seen: [],
|
||||
stylize: stylizeNoColor,
|
||||
};
|
||||
// legacy...
|
||||
if (rest.length >= 1) ctx.depth = rest[0];
|
||||
if (rest.length >= 2) ctx.colors = rest[1];
|
||||
if (isBoolean(opts)) {
|
||||
// legacy...
|
||||
ctx.showHidden = opts;
|
||||
} else if (opts) {
|
||||
// got an "options" object
|
||||
_extend(ctx, opts);
|
||||
}
|
||||
// set default options
|
||||
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
|
||||
if (isUndefined(ctx.depth)) ctx.depth = 2;
|
||||
if (isUndefined(ctx.colors)) ctx.colors = false;
|
||||
if (ctx.colors) ctx.stylize = stylizeWithColor;
|
||||
return formatValue(ctx, obj, ctx.depth);
|
||||
});
|
||||
|
||||
function stylizeWithColor(str, styleType) {
|
||||
var style = inspect.styles[styleType];
|
||||
|
||||
if (style) {
|
||||
return "\u001b[" + inspect.colors[style][0] + "m" + str + "\u001b[" + inspect.colors[style][1] + "m";
|
||||
} else {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
function stylizeNoColor(str, styleType) {
|
||||
return str;
|
||||
}
|
||||
|
||||
function arrayToHash(array) {
|
||||
var hash = {};
|
||||
|
||||
array.forEach(function (val, idx) {
|
||||
hash[val] = true;
|
||||
});
|
||||
|
||||
return hash;
|
||||
}
|
||||
|
||||
function formatValue(ctx, value, recurseTimes) {
|
||||
// Provide a hook for user-specified inspect functions.
|
||||
// Check that value is an object with an inspect function on it
|
||||
if (
|
||||
ctx.customInspect &&
|
||||
value &&
|
||||
isFunction(value.inspect) &&
|
||||
// Filter out the util module, it's inspect function is special
|
||||
value.inspect !== inspect &&
|
||||
// Also filter out any prototype objects using the circular check.
|
||||
!(value.constructor && value.constructor.prototype === value)
|
||||
) {
|
||||
var ret = value.inspect(recurseTimes, ctx);
|
||||
if (!isString(ret)) {
|
||||
ret = formatValue(ctx, ret, recurseTimes);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
// Primitive types cannot have properties
|
||||
var primitive = formatPrimitive(ctx, value);
|
||||
if (primitive) {
|
||||
return primitive;
|
||||
}
|
||||
|
||||
// Look up the keys of the object.
|
||||
var keys = Object.keys(value);
|
||||
var visibleKeys = arrayToHash(keys);
|
||||
|
||||
if (ctx.showHidden) {
|
||||
keys = Object.getOwnPropertyNames(value);
|
||||
}
|
||||
|
||||
// IE doesn't make error fields non-enumerable
|
||||
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
|
||||
if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) {
|
||||
return formatError(value);
|
||||
}
|
||||
|
||||
// Some type of object without properties can be shortcutted.
|
||||
if (keys.length === 0) {
|
||||
if (isFunction(value)) {
|
||||
var name = value.name ? ": " + value.name : "";
|
||||
return ctx.stylize("[Function" + name + "]", "special");
|
||||
}
|
||||
if (isRegExp(value)) {
|
||||
return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
|
||||
}
|
||||
if (isDate(value)) {
|
||||
return ctx.stylize(Date.prototype.toString.call(value), "date");
|
||||
}
|
||||
if (isError(value)) {
|
||||
return formatError(value);
|
||||
}
|
||||
}
|
||||
|
||||
var base = "",
|
||||
array = false,
|
||||
braces = ["{", "}"];
|
||||
|
||||
// Make Array say that they are Array
|
||||
if (isArray(value)) {
|
||||
array = true;
|
||||
braces = ["[", "]"];
|
||||
}
|
||||
|
||||
// Make functions say that they are functions
|
||||
if (isFunction(value)) {
|
||||
var n = value.name ? ": " + value.name : "";
|
||||
base = " [Function" + n + "]";
|
||||
}
|
||||
|
||||
// Make RegExps say that they are RegExps
|
||||
if (isRegExp(value)) {
|
||||
base = " " + RegExp.prototype.toString.call(value);
|
||||
}
|
||||
|
||||
// Make dates with properties first say the date
|
||||
if (isDate(value)) {
|
||||
base = " " + Date.prototype.toUTCString.call(value);
|
||||
}
|
||||
|
||||
// Make error with message first say the error
|
||||
if (isError(value)) {
|
||||
base = " " + formatError(value);
|
||||
}
|
||||
|
||||
if (keys.length === 0 && (!array || value.length == 0)) {
|
||||
return braces[0] + base + braces[1];
|
||||
}
|
||||
|
||||
if (recurseTimes < 0) {
|
||||
if (isRegExp(value)) {
|
||||
return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
|
||||
} else {
|
||||
return ctx.stylize("[Object]", "special");
|
||||
}
|
||||
}
|
||||
|
||||
ctx.seen.push(value);
|
||||
|
||||
var output;
|
||||
if (array) {
|
||||
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
|
||||
} else {
|
||||
output = keys.map(function (key) {
|
||||
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
|
||||
});
|
||||
}
|
||||
|
||||
ctx.seen.pop();
|
||||
|
||||
return reduceToSingleString(output, base, braces);
|
||||
}
|
||||
|
||||
function formatPrimitive(ctx, value) {
|
||||
if (isUndefined(value)) return ctx.stylize("undefined", "undefined");
|
||||
if (isString(value)) {
|
||||
var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'";
|
||||
return ctx.stylize(simple, "string");
|
||||
}
|
||||
if (isNumber(value)) return ctx.stylize("" + value, "number");
|
||||
if (isBoolean(value)) return ctx.stylize("" + value, "boolean");
|
||||
// For some reason typeof null is "object", so special case here.
|
||||
if (isNull(value)) return ctx.stylize("null", "null");
|
||||
}
|
||||
|
||||
function formatError(value) {
|
||||
return "[" + Error.prototype.toString.call(value) + "]";
|
||||
}
|
||||
|
||||
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
|
||||
var output = [];
|
||||
for (var i = 0, l = value.length; i < l; ++i) {
|
||||
if (hasOwnProperty(value, String(i))) {
|
||||
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
|
||||
} else {
|
||||
output.push("");
|
||||
}
|
||||
}
|
||||
keys.forEach(function (key) {
|
||||
if (!key.match(/^\d+$/)) {
|
||||
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
|
||||
}
|
||||
});
|
||||
return output;
|
||||
}
|
||||
|
||||
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
|
||||
var name, str, desc;
|
||||
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
|
||||
if (desc.get) {
|
||||
if (desc.set) {
|
||||
str = ctx.stylize("[Getter/Setter]", "special");
|
||||
} else {
|
||||
str = ctx.stylize("[Getter]", "special");
|
||||
}
|
||||
} else {
|
||||
if (desc.set) {
|
||||
str = ctx.stylize("[Setter]", "special");
|
||||
}
|
||||
}
|
||||
if (!hasOwnProperty(visibleKeys, key)) {
|
||||
name = "[" + key + "]";
|
||||
}
|
||||
if (!str) {
|
||||
if (ctx.seen.indexOf(desc.value) < 0) {
|
||||
if (isNull(recurseTimes)) {
|
||||
str = formatValue(ctx, desc.value, null);
|
||||
} else {
|
||||
str = formatValue(ctx, desc.value, recurseTimes - 1);
|
||||
}
|
||||
if (str.indexOf("\n") > -1) {
|
||||
if (array) {
|
||||
str = str
|
||||
.split("\n")
|
||||
.map(function (line) {
|
||||
return " " + line;
|
||||
})
|
||||
.join("\n")
|
||||
.slice(2);
|
||||
} else {
|
||||
str =
|
||||
"\n" +
|
||||
str
|
||||
.split("\n")
|
||||
.map(function (line) {
|
||||
return " " + line;
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
str = ctx.stylize("[Circular]", "special");
|
||||
}
|
||||
}
|
||||
if (isUndefined(name)) {
|
||||
if (array && key.match(/^\d+$/)) {
|
||||
return str;
|
||||
}
|
||||
name = JSON.stringify("" + key);
|
||||
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
|
||||
name = name.slice(1, -1);
|
||||
name = ctx.stylize(name, "name");
|
||||
} else {
|
||||
name = name
|
||||
.replace(/'/g, "\\'")
|
||||
.replace(/\\"/g, '"')
|
||||
.replace(/(^"|"$)/g, "'");
|
||||
name = ctx.stylize(name, "string");
|
||||
}
|
||||
}
|
||||
|
||||
return name + ": " + str;
|
||||
}
|
||||
|
||||
function reduceToSingleString(output, base, braces) {
|
||||
var numLinesEst = 0;
|
||||
var length = output.reduce(function (prev, cur) {
|
||||
numLinesEst++;
|
||||
if (cur.indexOf("\n") >= 0) numLinesEst++;
|
||||
return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1;
|
||||
}, 0);
|
||||
|
||||
if (length > 60) {
|
||||
return braces[0] + (base === "" ? "" : base + "\n ") + " " + output.join(",\n ") + " " + braces[1];
|
||||
}
|
||||
|
||||
return braces[0] + base + " " + output.join(", ") + " " + braces[1];
|
||||
}
|
||||
|
||||
// NOTE: These type checking functions intentionally don't use `instanceof`
|
||||
// because it is fragile and can be easily faked with `Object.create()`.
|
||||
export const types = /* @__PURE__ */ () => {
|
||||
// var toStr = Object.prototype.toString;
|
||||
// var fnToStr = Function.prototype.toString;
|
||||
// function isArgumentsObject(value) {
|
||||
// if (hasToStringTag && value && typeof value === "object" && Symbol.toStringTag in value) {
|
||||
// return false;
|
||||
// }
|
||||
// return toStr.apply(value) === "[object Arguments]";
|
||||
// }
|
||||
// var isFnRegex = /^\s*(?:function)?\*/;
|
||||
// var getProto = Object.getPrototypeOf;
|
||||
// var GeneratorFunction;
|
||||
// function isGeneratorFunction(fn) {
|
||||
// if (typeof fn !== "function") {
|
||||
// return false;
|
||||
// }
|
||||
// if (isFnRegex.test(fnToStr.call(fn))) {
|
||||
// return true;
|
||||
// }
|
||||
// if (typeof GeneratorFunction === "undefined") {
|
||||
// var generatorFunc;
|
||||
// try {
|
||||
// generatorFunc = Function("return function*() {}")();
|
||||
// } catch (e) {}
|
||||
// GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false;
|
||||
// }
|
||||
// return getProto(fn) === GeneratorFunction;
|
||||
// }
|
||||
// // var whichTypedArray = require("which-typed-array");
|
||||
// // var isTypedArray = require("is-typed-array");
|
||||
// function uncurryThis(f) {
|
||||
// return f.call.bind(f);
|
||||
// }
|
||||
// var BigIntSupported = typeof BigInt !== "undefined";
|
||||
// var SymbolSupported = typeof Symbol !== "undefined";
|
||||
// var ObjectToString = uncurryThis(Object.prototype.toString);
|
||||
// var numberValue = uncurryThis(Number.prototype.valueOf);
|
||||
// var stringValue = uncurryThis(String.prototype.valueOf);
|
||||
// var booleanValue = uncurryThis(Boolean.prototype.valueOf);
|
||||
// if (BigIntSupported) {
|
||||
// var bigIntValue = uncurryThis(BigInt.prototype.valueOf);
|
||||
// }
|
||||
// if (SymbolSupported) {
|
||||
// var symbolValue = uncurryThis(Symbol.prototype.valueOf);
|
||||
// }
|
||||
// function checkBoxedPrimitive(value, prototypeValueOf) {
|
||||
// if (typeof value !== "object") {
|
||||
// return false;
|
||||
// }
|
||||
// try {
|
||||
// prototypeValueOf(value);
|
||||
// return true;
|
||||
// } catch (e) {
|
||||
// return false;
|
||||
// }
|
||||
// }
|
||||
// exports.isArgumentsObject = isArgumentsObject;
|
||||
// exports.isGeneratorFunction = isGeneratorFunction;
|
||||
// exports.isTypedArray = isTypedArray;
|
||||
// // Taken from here and modified for better browser support
|
||||
// // https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js
|
||||
// function isPromise(input) {
|
||||
// return (
|
||||
// (typeof Promise !== "undefined" && input instanceof Promise) ||
|
||||
// (input !== null &&
|
||||
// typeof input === "object" &&
|
||||
// typeof input.then === "function" &&
|
||||
// typeof input.catch === "function")
|
||||
// );
|
||||
// }
|
||||
// exports.isPromise = isPromise;
|
||||
// function isArrayBufferView(value) {
|
||||
// if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
|
||||
// return ArrayBuffer.isView(value);
|
||||
// }
|
||||
// return isTypedArray(value) || isDataView(value);
|
||||
// }
|
||||
// exports.isArrayBufferView = isArrayBufferView;
|
||||
// function isUint8Array(value) {
|
||||
// return whichTypedArray(value) === "Uint8Array";
|
||||
// }
|
||||
// exports.isUint8Array = isUint8Array;
|
||||
// function isUint8ClampedArray(value) {
|
||||
// return whichTypedArray(value) === "Uint8ClampedArray";
|
||||
// }
|
||||
// exports.isUint8ClampedArray = isUint8ClampedArray;
|
||||
// function isUint16Array(value) {
|
||||
// return whichTypedArray(value) === "Uint16Array";
|
||||
// }
|
||||
// exports.isUint16Array = isUint16Array;
|
||||
// function isUint32Array(value) {
|
||||
// return whichTypedArray(value) === "Uint32Array";
|
||||
// }
|
||||
// exports.isUint32Array = isUint32Array;
|
||||
// function isInt8Array(value) {
|
||||
// return whichTypedArray(value) === "Int8Array";
|
||||
// }
|
||||
// exports.isInt8Array = isInt8Array;
|
||||
// function isInt16Array(value) {
|
||||
// return whichTypedArray(value) === "Int16Array";
|
||||
// }
|
||||
// exports.isInt16Array = isInt16Array;
|
||||
// function isInt32Array(value) {
|
||||
// return whichTypedArray(value) === "Int32Array";
|
||||
// }
|
||||
// exports.isInt32Array = isInt32Array;
|
||||
// function isFloat32Array(value) {
|
||||
// return whichTypedArray(value) === "Float32Array";
|
||||
// }
|
||||
// exports.isFloat32Array = isFloat32Array;
|
||||
// function isFloat64Array(value) {
|
||||
// return whichTypedArray(value) === "Float64Array";
|
||||
// }
|
||||
// exports.isFloat64Array = isFloat64Array;
|
||||
// function isBigInt64Array(value) {
|
||||
// return whichTypedArray(value) === "BigInt64Array";
|
||||
// }
|
||||
// exports.isBigInt64Array = isBigInt64Array;
|
||||
// function isBigUint64Array(value) {
|
||||
// return whichTypedArray(value) === "BigUint64Array";
|
||||
// }
|
||||
// exports.isBigUint64Array = isBigUint64Array;
|
||||
// function isMapToString(value) {
|
||||
// return ObjectToString(value) === "[object Map]";
|
||||
// }
|
||||
// isMapToString.working = typeof Map !== "undefined" && isMapToString(new Map());
|
||||
// function isMap(value) {
|
||||
// if (typeof Map === "undefined") {
|
||||
// return false;
|
||||
// }
|
||||
// return isMapToString.working ? isMapToString(value) : value instanceof Map;
|
||||
// }
|
||||
// exports.isMap = isMap;
|
||||
// function isSetToString(value) {
|
||||
// return ObjectToString(value) === "[object Set]";
|
||||
// }
|
||||
// isSetToString.working = typeof Set !== "undefined" && isSetToString(new Set());
|
||||
// function isSet(value) {
|
||||
// if (typeof Set === "undefined") {
|
||||
// return false;
|
||||
// }
|
||||
// return isSetToString.working ? isSetToString(value) : value instanceof Set;
|
||||
// }
|
||||
// exports.isSet = isSet;
|
||||
// function isWeakMapToString(value) {
|
||||
// return ObjectToString(value) === "[object WeakMap]";
|
||||
// }
|
||||
// isWeakMapToString.working = typeof WeakMap !== "undefined" && isWeakMapToString(new WeakMap());
|
||||
// function isWeakMap(value) {
|
||||
// if (typeof WeakMap === "undefined") {
|
||||
// return false;
|
||||
// }
|
||||
// return isWeakMapToString.working ? isWeakMapToString(value) : value instanceof WeakMap;
|
||||
// }
|
||||
// exports.isWeakMap = isWeakMap;
|
||||
// function isWeakSetToString(value) {
|
||||
// return ObjectToString(value) === "[object WeakSet]";
|
||||
// }
|
||||
// isWeakSetToString.working = typeof WeakSet !== "undefined" && isWeakSetToString(new WeakSet());
|
||||
// function isWeakSet(value) {
|
||||
// return isWeakSetToString(value);
|
||||
// }
|
||||
// exports.isWeakSet = isWeakSet;
|
||||
// function isArrayBufferToString(value) {
|
||||
// return ObjectToString(value) === "[object ArrayBuffer]";
|
||||
// }
|
||||
// isArrayBufferToString.working = typeof ArrayBuffer !== "undefined" && isArrayBufferToString(new ArrayBuffer());
|
||||
// function isArrayBuffer(value) {
|
||||
// if (typeof ArrayBuffer === "undefined") {
|
||||
// return false;
|
||||
// }
|
||||
// return isArrayBufferToString.working ? isArrayBufferToString(value) : value instanceof ArrayBuffer;
|
||||
// }
|
||||
// exports.isArrayBuffer = isArrayBuffer;
|
||||
// function isDataViewToString(value) {
|
||||
// return ObjectToString(value) === "[object DataView]";
|
||||
// }
|
||||
// isDataViewToString.working =
|
||||
// typeof ArrayBuffer !== "undefined" &&
|
||||
// typeof DataView !== "undefined" &&
|
||||
// isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1));
|
||||
// function isDataView(value) {
|
||||
// if (typeof DataView === "undefined") {
|
||||
// return false;
|
||||
// }
|
||||
// return isDataViewToString.working ? isDataViewToString(value) : value instanceof DataView;
|
||||
// }
|
||||
// exports.isDataView = isDataView;
|
||||
// // Store a copy of SharedArrayBuffer in case it's deleted elsewhere
|
||||
// var SharedArrayBufferCopy = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : undefined;
|
||||
// function isSharedArrayBufferToString(value) {
|
||||
// return ObjectToString(value) === "[object SharedArrayBuffer]";
|
||||
// }
|
||||
// function isSharedArrayBuffer(value) {
|
||||
// if (typeof SharedArrayBufferCopy === "undefined") {
|
||||
// return false;
|
||||
// }
|
||||
// if (typeof isSharedArrayBufferToString.working === "undefined") {
|
||||
// isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy());
|
||||
// }
|
||||
// return isSharedArrayBufferToString.working
|
||||
// ? isSharedArrayBufferToString(value)
|
||||
// : value instanceof SharedArrayBufferCopy;
|
||||
// }
|
||||
// exports.isSharedArrayBuffer = isSharedArrayBuffer;
|
||||
// function isAsyncFunction(value) {
|
||||
// return ObjectToString(value) === "[object AsyncFunction]";
|
||||
// }
|
||||
// exports.isAsyncFunction = isAsyncFunction;
|
||||
// function isMapIterator(value) {
|
||||
// return ObjectToString(value) === "[object Map Iterator]";
|
||||
// }
|
||||
// exports.isMapIterator = isMapIterator;
|
||||
// function isSetIterator(value) {
|
||||
// return ObjectToString(value) === "[object Set Iterator]";
|
||||
// }
|
||||
// exports.isSetIterator = isSetIterator;
|
||||
// function isGeneratorObject(value) {
|
||||
// return ObjectToString(value) === "[object Generator]";
|
||||
// }
|
||||
// exports.isGeneratorObject = isGeneratorObject;
|
||||
// function isWebAssemblyCompiledModule(value) {
|
||||
// return ObjectToString(value) === "[object WebAssembly.Module]";
|
||||
// }
|
||||
// exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;
|
||||
// function isNumberObject(value) {
|
||||
// return checkBoxedPrimitive(value, numberValue);
|
||||
// }
|
||||
// exports.isNumberObject = isNumberObject;
|
||||
// function isStringObject(value) {
|
||||
// return checkBoxedPrimitive(value, stringValue);
|
||||
// }
|
||||
// exports.isStringObject = isStringObject;
|
||||
// function isBooleanObject(value) {
|
||||
// return checkBoxedPrimitive(value, booleanValue);
|
||||
// }
|
||||
// exports.isBooleanObject = isBooleanObject;
|
||||
// function isBigIntObject(value) {
|
||||
// return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);
|
||||
// }
|
||||
// exports.isBigIntObject = isBigIntObject;
|
||||
// function isSymbolObject(value) {
|
||||
// return SymbolSupported && checkBoxedPrimitive(value, symbolValue);
|
||||
// }
|
||||
// exports.isSymbolObject = isSymbolObject;
|
||||
// function isBoxedPrimitive(value) {
|
||||
// return (
|
||||
// isNumberObject(value) ||
|
||||
// isStringObject(value) ||
|
||||
// isBooleanObject(value) ||
|
||||
// isBigIntObject(value) ||
|
||||
// isSymbolObject(value)
|
||||
// );
|
||||
// }
|
||||
// exports.isBoxedPrimitive = isBoxedPrimitive;
|
||||
// function isAnyArrayBuffer(value) {
|
||||
// return typeof Uint8Array !== "undefined" && (isArrayBuffer(value) || isSharedArrayBuffer(value));
|
||||
// }
|
||||
// exports.isAnyArrayBuffer = isAnyArrayBuffer;
|
||||
// ["isProxy", "isExternal", "isModuleNamespaceObject"].forEach(function (method) {
|
||||
// Object.defineProperty(exports, method, {
|
||||
// enumerable: false,
|
||||
// value: function () {
|
||||
// throw new Error(method + " is not supported in userland");
|
||||
// },
|
||||
// });
|
||||
// });
|
||||
// exports.types.isRegExp = isRegExp;
|
||||
// exports.types.isDate = isDate;
|
||||
// exports.types.isNativeError = isError;
|
||||
};
|
||||
|
||||
export function isArray(ar) {
|
||||
return Array.isArray(ar);
|
||||
}
|
||||
|
||||
export function isBoolean(arg) {
|
||||
return typeof arg === "boolean";
|
||||
}
|
||||
|
||||
export function isNull(arg) {
|
||||
return arg === null;
|
||||
}
|
||||
|
||||
export function isNullOrUndefined(arg) {
|
||||
return arg == null;
|
||||
}
|
||||
|
||||
export function isNumber(arg) {
|
||||
return typeof arg === "number";
|
||||
}
|
||||
|
||||
export function isString(arg) {
|
||||
return typeof arg === "string";
|
||||
}
|
||||
|
||||
export function isSymbol(arg) {
|
||||
return typeof arg === "symbol";
|
||||
}
|
||||
|
||||
export function isUndefined(arg) {
|
||||
return arg === void 0;
|
||||
}
|
||||
|
||||
export function isRegExp(re) {
|
||||
return isObject(re) && objectToString(re) === "[object RegExp]";
|
||||
}
|
||||
|
||||
export function isObject(arg) {
|
||||
return typeof arg === "object" && arg !== null;
|
||||
}
|
||||
|
||||
export function isDate(d) {
|
||||
return isObject(d) && objectToString(d) === "[object Date]";
|
||||
}
|
||||
|
||||
export function isError(e) {
|
||||
return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error);
|
||||
}
|
||||
|
||||
export function isFunction(arg) {
|
||||
return typeof arg === "function";
|
||||
}
|
||||
|
||||
export function isPrimitive(arg) {
|
||||
return (
|
||||
arg === null ||
|
||||
typeof arg === "boolean" ||
|
||||
typeof arg === "number" ||
|
||||
typeof arg === "string" ||
|
||||
typeof arg === "symbol" || // ES6 symbol
|
||||
typeof arg === "undefined"
|
||||
);
|
||||
}
|
||||
|
||||
// Compatibility with the buffer polyfill:
|
||||
export function isBuffer(arg) {
|
||||
return arg instanceof Buffer;
|
||||
}
|
||||
|
||||
function objectToString(o) {
|
||||
return Object.prototype.toString.call(o);
|
||||
}
|
||||
|
||||
function pad(n) {
|
||||
return n < 10 ? "0" + n.toString(10) : n.toString(10);
|
||||
}
|
||||
|
||||
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
|
||||
// 26 Feb 16:19:34
|
||||
function timestamp() {
|
||||
var d = new Date();
|
||||
var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(":");
|
||||
return [d.getDate(), months[d.getMonth()], time].join(" ");
|
||||
}
|
||||
|
||||
// log is just a thin wrapper to console.log that prepends a timestamp
|
||||
export function log(...args) {
|
||||
console.log("%s - %s", timestamp(), format.apply(null, args));
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit the prototype methods from one constructor into another.
|
||||
*
|
||||
* The Function.prototype.inherits from lang.js rewritten as a standalone
|
||||
* function (not on Function.prototype). NOTE: If this file is to be loaded
|
||||
* during bootstrapping this function needs to be rewritten using some native
|
||||
* functions as prototype setup using normal JavaScript does not work as
|
||||
* expected during bootstrapping (see mirror.js in r114903).
|
||||
*
|
||||
* @param {function} ctor Constructor function which needs to inherit the
|
||||
* prototype.
|
||||
* @param {function} superCtor Constructor function to inherit prototype from.
|
||||
*/
|
||||
export function inherits(ctor, superCtor) {
|
||||
if (superCtor) {
|
||||
ctor.super_ = superCtor;
|
||||
ctor.prototype = Object.create(superCtor.prototype, {
|
||||
constructor: {
|
||||
value: ctor,
|
||||
enumerable: false,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function _extend(origin, add) {
|
||||
// Don't do anything if add isn't an object
|
||||
if (!add || !isObject(add)) return origin;
|
||||
|
||||
var keys = Object.keys(add);
|
||||
var i = keys.length;
|
||||
while (i--) {
|
||||
origin[keys[i]] = add[keys[i]];
|
||||
}
|
||||
return origin;
|
||||
}
|
||||
|
||||
function hasOwnProperty(obj, prop) {
|
||||
return Object.prototype.hasOwnProperty.call(obj, prop);
|
||||
}
|
||||
|
||||
export const promisify = /* @__PURE__ */ (x => ((x.custom = Symbol.for("nodejs.util.promisify.custom")), x))(
|
||||
function promisify(original) {
|
||||
if (typeof original !== "function") throw new TypeError('The "original" argument must be of type Function');
|
||||
|
||||
if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
|
||||
var fn = original[kCustomPromisifiedSymbol];
|
||||
|
||||
if (typeof fn !== "function") {
|
||||
throw new TypeError('The "nodejs.util.promisify.custom" argument must be of type Function');
|
||||
}
|
||||
|
||||
Object.defineProperty(fn, kCustomPromisifiedSymbol, {
|
||||
value: fn,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
configurable: true,
|
||||
});
|
||||
return fn;
|
||||
}
|
||||
|
||||
function fn(...args) {
|
||||
var promiseResolve, promiseReject;
|
||||
var promise = new Promise(function (resolve, reject) {
|
||||
promiseResolve = resolve;
|
||||
promiseReject = reject;
|
||||
});
|
||||
|
||||
args.push(function (err, value) {
|
||||
if (err) {
|
||||
promiseReject(err);
|
||||
} else {
|
||||
promiseResolve(value);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
original.apply(this, args);
|
||||
} catch (err) {
|
||||
promiseReject(err);
|
||||
}
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
|
||||
|
||||
if (kCustomPromisifiedSymbol)
|
||||
Object.defineProperty(fn, kCustomPromisifiedSymbol, {
|
||||
value: fn,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
configurable: true,
|
||||
});
|
||||
return Object.defineProperties(fn, Object.getOwnPropertyDescriptors(original));
|
||||
},
|
||||
);
|
||||
|
||||
export function callbackifyOnRejected(reason, cb) {
|
||||
// `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
|
||||
// Because `null` is a special error value in callbacks which means "no error
|
||||
// occurred", we error-wrap so the callback consumer can distinguish between
|
||||
// "the promise rejected with null" or "the promise fulfilled with undefined".
|
||||
if (!reason) {
|
||||
var newReason = new Error("Promise was rejected with a falsy value");
|
||||
newReason.reason = reason;
|
||||
reason = newReason;
|
||||
}
|
||||
return cb(reason);
|
||||
}
|
||||
|
||||
export function callbackify(original) {
|
||||
if (typeof original !== "function") {
|
||||
throw new TypeError('The "original" argument must be of type Function');
|
||||
}
|
||||
|
||||
// We DO NOT return the promise as it gives the user a false sense that
|
||||
// the promise is actually somehow related to the callback's execution
|
||||
// and that the callback throwing will reject the promise.
|
||||
function callbackified(...args) {
|
||||
var maybeCb = args.pop();
|
||||
if (typeof maybeCb !== "function") {
|
||||
throw new TypeError("The last argument must be of type Function");
|
||||
}
|
||||
var self = this;
|
||||
var cb = function (...args) {
|
||||
return maybeCb.apply(self, ...args);
|
||||
};
|
||||
// In true node style we process the callback on `nextTick` with all the
|
||||
// implications (stack, `uncaughtException`, `async_hooks`)
|
||||
original.apply(this, args).then(
|
||||
function (ret) {
|
||||
process.nextTick(cb.bind(null, null, ret));
|
||||
},
|
||||
function (rej) {
|
||||
process.nextTick(callbackifyOnRejected.bind(null, rej, cb));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
|
||||
Object.defineProperties(callbackified, Object.getOwnPropertyDescriptors(original));
|
||||
|
||||
return callbackified;
|
||||
}
|
||||
|
||||
export const TextEncoder = /* @__PURE__ */ globalThis.TextEncoder;
|
||||
export const TextDecoder = /* @__PURE__ */ globalThis.TextDecoder;
|
||||
|
||||
126
src/node-fallbacks/vendor/base64-js.js
vendored
Normal file
126
src/node-fallbacks/vendor/base64-js.js
vendored
Normal file
@@ -0,0 +1,126 @@
|
||||
// Vendored version of https://www.npmjs.com/package/base64-js version 1.5.1
|
||||
// Converted manually to an ES module for higher tree-shaking compatibility
|
||||
"use strict";
|
||||
|
||||
var lookup = [];
|
||||
var revLookup = [];
|
||||
|
||||
var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
for (var i = 0, len = code.length; i < len; ++i) {
|
||||
lookup[i] = code[i];
|
||||
revLookup[code.charCodeAt(i)] = i;
|
||||
}
|
||||
|
||||
// Support decoding URL-safe base64 strings, as Node.js does.
|
||||
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
|
||||
revLookup["-".charCodeAt(0)] = 62;
|
||||
revLookup["_".charCodeAt(0)] = 63;
|
||||
|
||||
function getLens(b64) {
|
||||
var len = b64.length;
|
||||
|
||||
if (len % 4 > 0) {
|
||||
throw new Error("Invalid string. Length must be a multiple of 4");
|
||||
}
|
||||
|
||||
// Trim off extra bytes after placeholder bytes are found
|
||||
// See: https://github.com/beatgammit/base64-js/issues/42
|
||||
var validLen = b64.indexOf("=");
|
||||
if (validLen === -1) validLen = len;
|
||||
|
||||
var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4);
|
||||
|
||||
return [validLen, placeHoldersLen];
|
||||
}
|
||||
|
||||
// base64 is 4/3 + up to two characters of the original data
|
||||
function byteLength(b64) {
|
||||
var lens = getLens(b64);
|
||||
var validLen = lens[0];
|
||||
var placeHoldersLen = lens[1];
|
||||
return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;
|
||||
}
|
||||
|
||||
function _byteLength(validLen, placeHoldersLen) {
|
||||
return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;
|
||||
}
|
||||
|
||||
export function toByteArray(b64) {
|
||||
var tmp;
|
||||
var lens = getLens(b64);
|
||||
var validLen = lens[0];
|
||||
var placeHoldersLen = lens[1];
|
||||
|
||||
var arr = new Uint8Array(_byteLength(validLen, placeHoldersLen));
|
||||
|
||||
var curByte = 0;
|
||||
|
||||
// if there are placeholders, only get up to the last complete 4 chars
|
||||
var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
|
||||
|
||||
var i;
|
||||
for (i = 0; i < len; i += 4) {
|
||||
tmp =
|
||||
(revLookup[b64.charCodeAt(i)] << 18) |
|
||||
(revLookup[b64.charCodeAt(i + 1)] << 12) |
|
||||
(revLookup[b64.charCodeAt(i + 2)] << 6) |
|
||||
revLookup[b64.charCodeAt(i + 3)];
|
||||
arr[curByte++] = (tmp >> 16) & 0xff;
|
||||
arr[curByte++] = (tmp >> 8) & 0xff;
|
||||
arr[curByte++] = tmp & 0xff;
|
||||
}
|
||||
|
||||
if (placeHoldersLen === 2) {
|
||||
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
|
||||
arr[curByte++] = tmp & 0xff;
|
||||
}
|
||||
|
||||
if (placeHoldersLen === 1) {
|
||||
tmp =
|
||||
(revLookup[b64.charCodeAt(i)] << 10) |
|
||||
(revLookup[b64.charCodeAt(i + 1)] << 4) |
|
||||
(revLookup[b64.charCodeAt(i + 2)] >> 2);
|
||||
arr[curByte++] = (tmp >> 8) & 0xff;
|
||||
arr[curByte++] = tmp & 0xff;
|
||||
}
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
function tripletToBase64(num) {
|
||||
return lookup[(num >> 18) & 0x3f] + lookup[(num >> 12) & 0x3f] + lookup[(num >> 6) & 0x3f] + lookup[num & 0x3f];
|
||||
}
|
||||
|
||||
function encodeChunk(uint8, start, end) {
|
||||
var tmp;
|
||||
var output = [];
|
||||
for (var i = start; i < end; i += 3) {
|
||||
tmp = ((uint8[i] << 16) & 0xff0000) + ((uint8[i + 1] << 8) & 0xff00) + (uint8[i + 2] & 0xff);
|
||||
output.push(tripletToBase64(tmp));
|
||||
}
|
||||
return output.join("");
|
||||
}
|
||||
|
||||
export function fromByteArray(uint8) {
|
||||
var tmp;
|
||||
var len = uint8.length;
|
||||
var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
|
||||
var parts = [];
|
||||
var maxChunkLength = 16383; // must be multiple of 3
|
||||
|
||||
// go through the array every three bytes, we'll deal with trailing stuff later
|
||||
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
|
||||
parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
|
||||
}
|
||||
|
||||
// pad the end with zeros, but make sure to not forget the extra bytes
|
||||
if (extraBytes === 1) {
|
||||
tmp = uint8[len - 1];
|
||||
parts.push(lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3f] + "==");
|
||||
} else if (extraBytes === 2) {
|
||||
tmp = (uint8[len - 2] << 8) + uint8[len - 1];
|
||||
parts.push(lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3f] + lookup[(tmp << 2) & 0x3f] + "=");
|
||||
}
|
||||
|
||||
return parts.join("");
|
||||
}
|
||||
85
src/node-fallbacks/vendor/ieee754.js
vendored
Normal file
85
src/node-fallbacks/vendor/ieee754.js
vendored
Normal file
@@ -0,0 +1,85 @@
|
||||
/* ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
||||
export function read(buffer, offset, isLE, mLen, nBytes) {
|
||||
var e, m;
|
||||
var eLen = nBytes * 8 - mLen - 1;
|
||||
var eMax = (1 << eLen) - 1;
|
||||
var eBias = eMax >> 1;
|
||||
var nBits = -7;
|
||||
var i = isLE ? nBytes - 1 : 0;
|
||||
var d = isLE ? -1 : 1;
|
||||
var s = buffer[offset + i];
|
||||
|
||||
i += d;
|
||||
|
||||
e = s & ((1 << -nBits) - 1);
|
||||
s >>= -nBits;
|
||||
nBits += eLen;
|
||||
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
|
||||
|
||||
m = e & ((1 << -nBits) - 1);
|
||||
e >>= -nBits;
|
||||
nBits += mLen;
|
||||
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
|
||||
|
||||
if (e === 0) {
|
||||
e = 1 - eBias;
|
||||
} else if (e === eMax) {
|
||||
return m ? NaN : (s ? -1 : 1) * Infinity;
|
||||
} else {
|
||||
m = m + Math.pow(2, mLen);
|
||||
e = e - eBias;
|
||||
}
|
||||
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
|
||||
}
|
||||
|
||||
export function write(buffer, value, offset, isLE, mLen, nBytes) {
|
||||
var e, m, c;
|
||||
var eLen = nBytes * 8 - mLen - 1;
|
||||
var eMax = (1 << eLen) - 1;
|
||||
var eBias = eMax >> 1;
|
||||
var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
|
||||
var i = isLE ? 0 : nBytes - 1;
|
||||
var d = isLE ? 1 : -1;
|
||||
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
|
||||
|
||||
value = Math.abs(value);
|
||||
|
||||
if (isNaN(value) || value === Infinity) {
|
||||
m = isNaN(value) ? 1 : 0;
|
||||
e = eMax;
|
||||
} else {
|
||||
e = Math.floor(Math.log(value) / Math.LN2);
|
||||
if (value * (c = Math.pow(2, -e)) < 1) {
|
||||
e--;
|
||||
c *= 2;
|
||||
}
|
||||
if (e + eBias >= 1) {
|
||||
value += rt / c;
|
||||
} else {
|
||||
value += rt * Math.pow(2, 1 - eBias);
|
||||
}
|
||||
if (value * c >= 2) {
|
||||
e++;
|
||||
c /= 2;
|
||||
}
|
||||
|
||||
if (e + eBias >= eMax) {
|
||||
m = 0;
|
||||
e = eMax;
|
||||
} else if (e + eBias >= 1) {
|
||||
m = (value * c - 1) * Math.pow(2, mLen);
|
||||
e = e + eBias;
|
||||
} else {
|
||||
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
|
||||
e = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
|
||||
|
||||
e = (e << mLen) | m;
|
||||
eLen += mLen;
|
||||
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
|
||||
|
||||
buffer[offset + i - d] |= s * 128;
|
||||
}
|
||||
@@ -1,436 +1,93 @@
|
||||
//! When bundling with --target=browser, we want to allow using some of the
|
||||
//! `node:*` builtins. The implementations of these polyfills are in
|
||||
//! `./src/node_fallbacks`, with this file being the glue to add them to the
|
||||
//! resolver.
|
||||
const std = @import("std");
|
||||
const string = @import("./string_types.zig").string;
|
||||
const bun = @import("root").bun;
|
||||
|
||||
const PackageJSON = @import("./resolver/package_json.zig").PackageJSON;
|
||||
const logger = bun.logger;
|
||||
const Fs = @import("./fs.zig");
|
||||
const bun = @import("root").bun;
|
||||
|
||||
const assert_code: string = @embedFile("./node-fallbacks/out/assert.js");
|
||||
const buffer_code: string = @embedFile("./node-fallbacks/out/buffer.js");
|
||||
const console_code: string = @embedFile("./node-fallbacks/out/console.js");
|
||||
const constants_code: string = @embedFile("./node-fallbacks/out/constants.js");
|
||||
const crypto_code: string = @embedFile("./node-fallbacks/out/crypto.js");
|
||||
const domain_code: string = @embedFile("./node-fallbacks/out/domain.js");
|
||||
const events_code: string = @embedFile("./node-fallbacks/out/events.js");
|
||||
const http_code: string = @embedFile("./node-fallbacks/out/http.js");
|
||||
const https_code: string = @embedFile("./node-fallbacks/out/https.js");
|
||||
const net_code: string = @embedFile("./node-fallbacks/out/net.js");
|
||||
const os_code: string = @embedFile("./node-fallbacks/out/os.js");
|
||||
const path_code: string = @embedFile("./node-fallbacks/out/path.js");
|
||||
const process_code: string = @embedFile("./node-fallbacks/out/process.js");
|
||||
const punycode_code: string = @embedFile("./node-fallbacks/out/punycode.js");
|
||||
const querystring_code: string = @embedFile("./node-fallbacks/out/querystring.js");
|
||||
const stream_code: string = @embedFile("./node-fallbacks/out/stream.js");
|
||||
const string_decoder_code: string = @embedFile("./node-fallbacks/out/string_decoder.js");
|
||||
const sys_code: string = @embedFile("./node-fallbacks/out/sys.js");
|
||||
const timers_code: string = @embedFile("./node-fallbacks/out/timers.js");
|
||||
const tty_code: string = @embedFile("./node-fallbacks/out/tty.js");
|
||||
const url_code: string = @embedFile("./node-fallbacks/out/url.js");
|
||||
const util_code: string = @embedFile("./node-fallbacks/out/util.js");
|
||||
const zlib_code: string = @embedFile("./node-fallbacks/out/zlib.js");
|
||||
pub const prefix = "/bun-vfs$$/node_modules/";
|
||||
|
||||
const assert_import_path = "/bun-vfs/node_modules/assert/index.js";
|
||||
const buffer_import_path = "/bun-vfs/node_modules/buffer/index.js";
|
||||
const console_import_path = "/bun-vfs/node_modules/console/index.js";
|
||||
const constants_import_path = "/bun-vfs/node_modules/constants/index.js";
|
||||
const crypto_import_path = "/bun-vfs/node_modules/crypto/index.js";
|
||||
const domain_import_path = "/bun-vfs/node_modules/domain/index.js";
|
||||
const events_import_path = "/bun-vfs/node_modules/events/index.js";
|
||||
const http_import_path = "/bun-vfs/node_modules/http/index.js";
|
||||
const https_import_path = "/bun-vfs/node_modules/https/index.js";
|
||||
const net_import_path = "/bun-vfs/node_modules/net/index.js";
|
||||
const os_import_path = "/bun-vfs/node_modules/os/index.js";
|
||||
const path_import_path = "/bun-vfs/node_modules/path/index.js";
|
||||
const process_import_path = "/bun-vfs/node_modules/process/index.js";
|
||||
const punycode_import_path = "/bun-vfs/node_modules/punycode/index.js";
|
||||
const querystring_import_path = "/bun-vfs/node_modules/querystring/index.js";
|
||||
const stream_import_path = "/bun-vfs/node_modules/stream/index.js";
|
||||
const string_decoder_import_path = "/bun-vfs/node_modules/string_decoder/index.js";
|
||||
const sys_import_path = "/bun-vfs/node_modules/sys/index.js";
|
||||
const timers_import_path = "/bun-vfs/node_modules/timers/index.js";
|
||||
const tty_import_path = "/bun-vfs/node_modules/tty/index.js";
|
||||
const url_import_path = "/bun-vfs/node_modules/url/index.js";
|
||||
const util_import_path = "/bun-vfs/node_modules/util/index.js";
|
||||
const zlib_import_path = "/bun-vfs/node_modules/zlib/index.js";
|
||||
comptime {
|
||||
// Ensure that checking for the prefix should be a cheap lookup (bun.strings.hasPrefixComptime)
|
||||
// because 24 bytes == 8 * 3 --> read and compare three u64s
|
||||
bun.assert(prefix.len % 8 == 0);
|
||||
}
|
||||
|
||||
const assert_package_json = PackageJSON{
|
||||
.name = "assert",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("assert@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/assert/package.json", ""),
|
||||
};
|
||||
const buffer_package_json = PackageJSON{
|
||||
.name = "buffer",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("buffer@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/buffer/package.json", ""),
|
||||
};
|
||||
const console_package_json = PackageJSON{
|
||||
.name = "console",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("console@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/console/package.json", ""),
|
||||
};
|
||||
const constants_package_json = PackageJSON{
|
||||
.name = "constants",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("constants@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/constants/package.json", ""),
|
||||
};
|
||||
const crypto_package_json = PackageJSON{
|
||||
.name = "crypto",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("crypto@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/crypto/package.json", ""),
|
||||
};
|
||||
const domain_package_json = PackageJSON{
|
||||
.name = "domain",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("domain@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/domain/package.json", ""),
|
||||
};
|
||||
const events_package_json = PackageJSON{
|
||||
.name = "events",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("events@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/events/package.json", ""),
|
||||
};
|
||||
const http_package_json = PackageJSON{
|
||||
.name = "http",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("http@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/http/package.json", ""),
|
||||
};
|
||||
const https_package_json = PackageJSON{
|
||||
.name = "https",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("https@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/https/package.json", ""),
|
||||
};
|
||||
const net_package_json = PackageJSON{
|
||||
.name = "net",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("net@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/net/package.json", ""),
|
||||
};
|
||||
const os_package_json = PackageJSON{
|
||||
.name = "os",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("os@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/os/package.json", ""),
|
||||
};
|
||||
const path_package_json = PackageJSON{
|
||||
.name = "path",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("path@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/path/package.json", ""),
|
||||
};
|
||||
const process_package_json = PackageJSON{
|
||||
.name = "process",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("process@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/process/package.json", ""),
|
||||
};
|
||||
const punycode_package_json = PackageJSON{
|
||||
.name = "punycode",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("punycode@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/punycode/package.json", ""),
|
||||
};
|
||||
const querystring_package_json = PackageJSON{
|
||||
.name = "querystring",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("querystring@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/querystring/package.json", ""),
|
||||
};
|
||||
const stream_package_json = PackageJSON{
|
||||
.name = "stream",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("stream@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/stream/package.json", ""),
|
||||
};
|
||||
const string_decoder_package_json = PackageJSON{
|
||||
.name = "string_decoder",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = brk: {
|
||||
@setEvalBranchQuota(9999);
|
||||
break :brk @as(u32, @truncate(bun.hash("string_decoder@0.0.0-polyfill")));
|
||||
},
|
||||
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/string_decoder/package.json", ""),
|
||||
};
|
||||
|
||||
const sys_package_json = PackageJSON{
|
||||
.name = "sys",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("sys@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/sys/package.json", ""),
|
||||
};
|
||||
const timers_package_json = PackageJSON{
|
||||
.name = "timers",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("timers@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/timers/package.json", ""),
|
||||
};
|
||||
const tty_package_json = PackageJSON{
|
||||
.name = "tty",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("tty@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/tty/package.json", ""),
|
||||
};
|
||||
const url_package_json = PackageJSON{
|
||||
.name = "url",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("url@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/url/package.json", ""),
|
||||
};
|
||||
const util_package_json = PackageJSON{
|
||||
.name = "util",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("util@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/util/package.json", ""),
|
||||
};
|
||||
const zlib_package_json = PackageJSON{
|
||||
.name = "zlib",
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = @as(u32, @truncate(bun.hash("zlib@0.0.0-polyfill"))),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString("/bun-vfs/node_modules/zlib/package.json", ""),
|
||||
};
|
||||
|
||||
pub const FallbackModule = struct {
|
||||
pub const Module = struct {
|
||||
path: Fs.Path,
|
||||
code: string,
|
||||
code: []const u8,
|
||||
package_json: *const PackageJSON,
|
||||
|
||||
pub const assert = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(assert_import_path, "node", "assert"),
|
||||
.code = assert_code,
|
||||
.package_json = &assert_package_json,
|
||||
};
|
||||
pub const buffer = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(buffer_import_path, "node", "buffer"),
|
||||
.code = buffer_code,
|
||||
.package_json = &buffer_package_json,
|
||||
};
|
||||
pub const console = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(console_import_path, "node", "console"),
|
||||
.code = console_code,
|
||||
.package_json = &console_package_json,
|
||||
};
|
||||
pub const constants = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(constants_import_path, "node", "constants"),
|
||||
.code = constants_code,
|
||||
.package_json = &constants_package_json,
|
||||
};
|
||||
pub const crypto = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(crypto_import_path, "node", "crypto"),
|
||||
.code = crypto_code,
|
||||
.package_json = &crypto_package_json,
|
||||
};
|
||||
pub const domain = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(domain_import_path, "node", "domain"),
|
||||
.code = domain_code,
|
||||
.package_json = &domain_package_json,
|
||||
};
|
||||
pub const events = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(events_import_path, "node", "events"),
|
||||
.code = events_code,
|
||||
.package_json = &events_package_json,
|
||||
};
|
||||
pub const http = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(http_import_path, "node", "http"),
|
||||
.code = http_code,
|
||||
.package_json = &http_package_json,
|
||||
};
|
||||
pub const https = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(https_import_path, "node", "https"),
|
||||
.code = https_code,
|
||||
.package_json = &https_package_json,
|
||||
};
|
||||
pub const net = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(net_import_path, "node", "net"),
|
||||
.code = net_code,
|
||||
.package_json = &net_package_json,
|
||||
};
|
||||
pub const os = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(os_import_path, "node", "os"),
|
||||
.code = os_code,
|
||||
.package_json = &os_package_json,
|
||||
};
|
||||
pub const path = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(path_import_path, "node", "path"),
|
||||
.code = path_code,
|
||||
.package_json = &path_package_json,
|
||||
};
|
||||
pub const process = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(process_import_path, "node", "process"),
|
||||
.code = process_code,
|
||||
.package_json = &process_package_json,
|
||||
};
|
||||
pub const punycode = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(punycode_import_path, "node", "punycode"),
|
||||
.code = punycode_code,
|
||||
.package_json = &punycode_package_json,
|
||||
};
|
||||
pub const querystring = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(querystring_import_path, "node", "querystring"),
|
||||
.code = querystring_code,
|
||||
.package_json = &querystring_package_json,
|
||||
};
|
||||
pub const stream = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(stream_import_path, "node", "stream"),
|
||||
.code = stream_code,
|
||||
.package_json = &stream_package_json,
|
||||
};
|
||||
pub const string_decoder = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(string_decoder_import_path, "node", "string_decoder"),
|
||||
.code = string_decoder_code,
|
||||
.package_json = &string_decoder_package_json,
|
||||
};
|
||||
pub const sys = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(sys_import_path, "node", "sys"),
|
||||
.code = sys_code,
|
||||
.package_json = &sys_package_json,
|
||||
};
|
||||
pub const timers = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(timers_import_path, "node", "timers"),
|
||||
.code = timers_code,
|
||||
.package_json = &timers_package_json,
|
||||
};
|
||||
pub const tty = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(tty_import_path, "node", "tty"),
|
||||
.code = tty_code,
|
||||
.package_json = &tty_package_json,
|
||||
};
|
||||
pub const url = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(url_import_path, "node", "url"),
|
||||
.code = url_code,
|
||||
.package_json = &url_package_json,
|
||||
};
|
||||
pub const util = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(util_import_path, "node", "util"),
|
||||
.code = util_code,
|
||||
.package_json = &util_package_json,
|
||||
};
|
||||
pub const zlib = FallbackModule{
|
||||
.path = Fs.Path.initWithNamespaceVirtual(zlib_import_path, "node", "zlib"),
|
||||
.code = zlib_code,
|
||||
.package_json = &zlib_package_json,
|
||||
};
|
||||
};
|
||||
|
||||
pub const Map = bun.ComptimeStringMap(FallbackModule, .{
|
||||
.{ "assert", FallbackModule.assert },
|
||||
.{ "buffer", FallbackModule.buffer },
|
||||
.{ "console", FallbackModule.console },
|
||||
.{ "constants", FallbackModule.constants },
|
||||
.{ "crypto", FallbackModule.crypto },
|
||||
.{ "domain", FallbackModule.domain },
|
||||
.{ "events", FallbackModule.events },
|
||||
.{ "http", FallbackModule.http },
|
||||
.{ "https", FallbackModule.https },
|
||||
.{ "net", FallbackModule.net },
|
||||
.{ "os", FallbackModule.os },
|
||||
.{ "path", FallbackModule.path },
|
||||
.{ "process", FallbackModule.process },
|
||||
.{ "punycode", FallbackModule.punycode },
|
||||
.{ "querystring", FallbackModule.querystring },
|
||||
.{ "stream", FallbackModule.stream },
|
||||
.{ "string_decoder", FallbackModule.string_decoder },
|
||||
.{ "sys", FallbackModule.sys },
|
||||
.{ "timers", FallbackModule.timers },
|
||||
.{ "tty", FallbackModule.tty },
|
||||
.{ "url", FallbackModule.url },
|
||||
.{ "util", FallbackModule.util },
|
||||
.{ "zlib", FallbackModule.zlib },
|
||||
});
|
||||
pub fn contentsFromPath(path: []const u8) ?[]const u8 {
|
||||
if (bun.Environment.allow_assert)
|
||||
bun.assert(bun.strings.hasPrefixComptime(path, prefix));
|
||||
|
||||
pub fn contentsFromPath(path: string) ?string {
|
||||
@setCold(true);
|
||||
var module_name = path["/bun-vfs/node_modules/".len..];
|
||||
|
||||
if (module_name[0] == '@') {
|
||||
var end = std.mem.indexOfScalar(u8, module_name, '/').? + 1;
|
||||
end += std.mem.indexOfScalar(u8, module_name[end..], '/').?;
|
||||
|
||||
module_name = module_name[0..end];
|
||||
} else {
|
||||
module_name = module_name[0..std.mem.indexOfScalar(u8, module_name, '/').?];
|
||||
}
|
||||
var module_name = path[prefix.len..];
|
||||
module_name = module_name[0 .. std.mem.indexOfScalar(u8, module_name, '/') orelse module_name.len];
|
||||
|
||||
if (Map.get(module_name)) |mod| {
|
||||
return mod.code;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
pub const buffer_fallback_import_name: string = "node:buffer";
|
||||
pub const Map = bun.ComptimeStringMap(Module, .{
|
||||
.{ "assert", nodeFallback("assert", @embedFile("./node-fallbacks/out/assert.js")) },
|
||||
.{ "buffer", nodeFallback("buffer", @embedFile("./node-fallbacks/out/buffer.js")) },
|
||||
.{ "console", nodeFallback("console", @embedFile("./node-fallbacks/out/console.js")) },
|
||||
.{ "constants", nodeFallback("constants", @embedFile("./node-fallbacks/out/constants.js")) },
|
||||
.{ "crypto", nodeFallback("crypto", @embedFile("./node-fallbacks/out/crypto.js")) },
|
||||
.{ "domain", nodeFallback("domain", @embedFile("./node-fallbacks/out/domain.js")) },
|
||||
.{ "events", nodeFallback("events", @embedFile("./node-fallbacks/out/events.js")) },
|
||||
.{ "http", nodeFallback("http", @embedFile("./node-fallbacks/out/http.js")) },
|
||||
.{ "https", nodeFallback("https", @embedFile("./node-fallbacks/out/https.js")) },
|
||||
.{ "net", nodeFallback("net", @embedFile("./node-fallbacks/out/net.js")) },
|
||||
.{ "os", nodeFallback("os", @embedFile("./node-fallbacks/out/os.js")) },
|
||||
.{ "path", nodeFallback("path", @embedFile("./node-fallbacks/out/path.js")) },
|
||||
.{ "process", nodeFallback("process", @embedFile("./node-fallbacks/out/process.js")) },
|
||||
.{ "punycode", nodeFallback("punycode", @embedFile("./node-fallbacks/out/punycode.js")) },
|
||||
.{ "querystring", nodeFallback("querystring", @embedFile("./node-fallbacks/out/querystring.js")) },
|
||||
.{ "stream", nodeFallback("stream", @embedFile("./node-fallbacks/out/stream.js")) },
|
||||
.{ "string_decoder", nodeFallback("string", @embedFile("./node-fallbacks/out/string_decoder.js")) },
|
||||
.{ "timers", nodeFallback("timers", @embedFile("./node-fallbacks/out/timers.js")) },
|
||||
.{ "timers/promises", nodeFallback("timers/promises", @embedFile("./node-fallbacks/out/timers.promises.js")) },
|
||||
.{ "tty", nodeFallback("tty", @embedFile("./node-fallbacks/out/tty.js")) },
|
||||
.{ "url", nodeFallback("url", @embedFile("./node-fallbacks/out/url.js")) },
|
||||
.{ "util", nodeFallback("util", @embedFile("./node-fallbacks/out/util.js")) },
|
||||
.{ "zlib", nodeFallback("zlib", @embedFile("./node-fallbacks/out/zlib.js")) },
|
||||
|
||||
// sys is an alias of util
|
||||
.{ "sys", nodeFallback("util", @embedFile("./node-fallbacks/out/util.js")) },
|
||||
});
|
||||
|
||||
fn nodeFallback(comptime name: []const u8, comptime code: []const u8) Module {
|
||||
const path_text = prefix ++ name ++ "/index.js";
|
||||
|
||||
@setEvalBranchQuota(100_000);
|
||||
|
||||
return comptime .{
|
||||
.path = .{
|
||||
.pretty = "node:" ++ name ++ " browser polyfill",
|
||||
.is_symlink = true,
|
||||
.text = path_text,
|
||||
.namespace = "node",
|
||||
.name = Fs.PathName.init(path_text),
|
||||
},
|
||||
.package_json = &.{
|
||||
.name = name,
|
||||
.version = "0.0.0-polyfill",
|
||||
.module_type = .esm,
|
||||
.hash = bun.hash32(name ++ "@0.0.0-polyfill"),
|
||||
.main_fields = undefined,
|
||||
.browser_map = undefined,
|
||||
.source = logger.Source.initPathString(prefix ++ name ++ "/package.json", ""),
|
||||
},
|
||||
.code = code,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ const CacheSet = cache.Set;
|
||||
const DataURL = @import("./data_url.zig").DataURL;
|
||||
pub const DirInfo = @import("./dir_info.zig");
|
||||
const ResolvePath = @import("./resolve_path.zig");
|
||||
const NodeFallbackModules = @import("../node_fallbacks.zig");
|
||||
const node_fallbacks = @import("../node_fallbacks.zig");
|
||||
const Mutex = @import("../lock.zig").Lock;
|
||||
const StringBoolMap = bun.StringHashMap(bool);
|
||||
const FileDescriptorType = bun.FileDescriptor;
|
||||
@@ -1348,7 +1348,7 @@ pub const Resolver = struct {
|
||||
const had_node_prefix = strings.hasPrefixComptime(import_path, "node:");
|
||||
const import_path_without_node_prefix = if (had_node_prefix) import_path["node:".len..] else import_path;
|
||||
|
||||
if (NodeFallbackModules.Map.get(import_path_without_node_prefix)) |*fallback_module| {
|
||||
if (node_fallbacks.Map.get(import_path_without_node_prefix)) |*fallback_module| {
|
||||
result.path_pair.primary = fallback_module.path;
|
||||
result.module_type = .cjs;
|
||||
result.package_json = @as(*PackageJSON, @ptrFromInt(@intFromPtr(fallback_module.package_json)));
|
||||
|
||||
@@ -32,6 +32,7 @@ describe("bundler", () => {
|
||||
"string_decoder": "polyfill",
|
||||
"sys": "polyfill",
|
||||
"timers": "polyfill",
|
||||
"timers/promises": "polyfill",
|
||||
"tls": "no-op",
|
||||
"tty": "polyfill",
|
||||
"url": "polyfill",
|
||||
@@ -70,6 +71,55 @@ describe("bundler", () => {
|
||||
stdout: "function\nfunction\nfalse",
|
||||
},
|
||||
});
|
||||
const utilTreeShaking = itBundled("browser/NodeUtilTreeShaking", {
|
||||
files: {
|
||||
"/entry.js": /* js */ `
|
||||
import { TextEncoder } from "node:util";
|
||||
console.log(TextEncoder);
|
||||
`,
|
||||
},
|
||||
target: "browser",
|
||||
minifySyntax: true,
|
||||
minifyWhitespace: true,
|
||||
minifyIdentifiers: true,
|
||||
expectExactFilesize: {
|
||||
// TODO: After a release with https://github.com/oven-sh/bun/pull/12808/files
|
||||
// we can change node_fallbacks to use this and it will half this size
|
||||
"/out.js": 60,
|
||||
},
|
||||
});
|
||||
// Special rewriting is done in the parser for these polyfills, these three
|
||||
// test different cases are unique code paths in the parser.
|
||||
itBundled("browser/NodeUtilDefaultTreeShaking", {
|
||||
...utilTreeShaking.options,
|
||||
files: {
|
||||
"/entry.js": /* js */ `
|
||||
import util from "node:util";
|
||||
console.log(util.TextEncoder);
|
||||
`,
|
||||
},
|
||||
});
|
||||
itBundled("browser/NodeUtilStarTreeShaking", {
|
||||
...utilTreeShaking.options,
|
||||
files: {
|
||||
"/entry.js": /* js */ `
|
||||
import * as util from "node:util";
|
||||
console.log(util.TextEncoder);
|
||||
`,
|
||||
},
|
||||
});
|
||||
itBundled("browser/NodeUtilDefaultAndStarTreeShaking", {
|
||||
...utilTreeShaking.options,
|
||||
files: {
|
||||
"/entry.js": /* js */ `
|
||||
import util2, * as util from "node:util";
|
||||
console.log(util.TextEncoder, util2.TextEncoder);
|
||||
`,
|
||||
},
|
||||
expectExactFilesize: {
|
||||
"/out.js": 62,
|
||||
},
|
||||
});
|
||||
// TODO: use nodePolyfillList to generate the code in here.
|
||||
const NodePolyfills = itBundled("browser/NodePolyfills", {
|
||||
files: {
|
||||
@@ -102,6 +152,7 @@ describe("bundler", () => {
|
||||
import * as string_decoder from "node:string_decoder";
|
||||
import * as sys from "node:sys";
|
||||
import * as timers from "node:timers";
|
||||
import * as timers_promises from "node:timers/promises";
|
||||
import * as tls from "node:tls";
|
||||
import * as tty from "node:tty";
|
||||
import * as url from "node:url";
|
||||
@@ -113,41 +164,42 @@ describe("bundler", () => {
|
||||
if (typeof obj === 'function') obj = obj()
|
||||
return Object.keys(obj).length === 0 ? 'no-op' : 'polyfill'
|
||||
}
|
||||
console.log('assert :', scan(assert))
|
||||
console.log('buffer :', scan(buffer))
|
||||
console.log('child_process :', scan(child_process))
|
||||
console.log('cluster :', scan(cluster))
|
||||
console.log('console :', console2 === console ? 'equal' : 'polyfill')
|
||||
console.log('constants :', scan(constants))
|
||||
console.log('crypto :', scan(crypto))
|
||||
console.log('dgram :', scan(dgram))
|
||||
console.log('dns :', scan(dns))
|
||||
console.log('domain :', scan(domain))
|
||||
console.log('events :', scan(events))
|
||||
console.log('fs :', scan(fs))
|
||||
console.log('http :', scan(http))
|
||||
console.log('https :', scan(https))
|
||||
console.log('module :', scan(module2))
|
||||
console.log('net :', scan(net))
|
||||
console.log('os :', scan(os))
|
||||
console.log('path :', scan(path))
|
||||
console.log('perf_hooks :', scan(perf_hooks))
|
||||
console.log('process :', scan(process))
|
||||
console.log('punycode :', scan(punycode))
|
||||
console.log('querystring :', scan(querystring))
|
||||
console.log('readline :', scan(readline))
|
||||
console.log('repl :', scan(repl))
|
||||
console.log('stream :', scan(stream))
|
||||
console.log('string_decoder :', scan(string_decoder))
|
||||
console.log('sys :', scan(sys))
|
||||
console.log('timers :', scan(timers))
|
||||
console.log('tls :', scan(tls))
|
||||
console.log('tty :', scan(tty))
|
||||
console.log('url :', scan(url))
|
||||
console.log('util :', scan(util))
|
||||
console.log('v8 :', scan(v8))
|
||||
console.log('vm :', scan(vm))
|
||||
console.log('zlib :', scan(zlib))
|
||||
console.log('assert :', scan(assert))
|
||||
console.log('buffer :', scan(buffer))
|
||||
console.log('child_process :', scan(child_process))
|
||||
console.log('cluster :', scan(cluster))
|
||||
console.log('console :', console2 === console ? 'equal' : 'polyfill')
|
||||
console.log('constants :', scan(constants))
|
||||
console.log('crypto :', scan(crypto))
|
||||
console.log('dgram :', scan(dgram))
|
||||
console.log('dns :', scan(dns))
|
||||
console.log('domain :', scan(domain))
|
||||
console.log('events :', scan(events))
|
||||
console.log('fs :', scan(fs))
|
||||
console.log('http :', scan(http))
|
||||
console.log('https :', scan(https))
|
||||
console.log('module :', scan(module2))
|
||||
console.log('net :', scan(net))
|
||||
console.log('os :', scan(os))
|
||||
console.log('path :', scan(path))
|
||||
console.log('perf_hooks :', scan(perf_hooks))
|
||||
console.log('process :', scan(process))
|
||||
console.log('punycode :', scan(punycode))
|
||||
console.log('querystring :', scan(querystring))
|
||||
console.log('readline :', scan(readline))
|
||||
console.log('repl :', scan(repl))
|
||||
console.log('stream :', scan(stream))
|
||||
console.log('string_decoder :', scan(string_decoder))
|
||||
console.log('sys :', scan(sys))
|
||||
console.log('timers :', scan(timers))
|
||||
console.log('timers/promises :', scan(timers_promises))
|
||||
console.log('tls :', scan(tls))
|
||||
console.log('tty :', scan(tty))
|
||||
console.log('url :', scan(url))
|
||||
console.log('util :', scan(util))
|
||||
console.log('v8 :', scan(v8))
|
||||
console.log('vm :', scan(vm))
|
||||
console.log('zlib :', scan(zlib))
|
||||
`,
|
||||
},
|
||||
target: "browser",
|
||||
@@ -159,41 +211,42 @@ describe("bundler", () => {
|
||||
},
|
||||
run: {
|
||||
stdout: `
|
||||
assert : polyfill
|
||||
buffer : polyfill
|
||||
child_process : no-op
|
||||
cluster : no-op
|
||||
console : polyfill
|
||||
constants : polyfill
|
||||
crypto : polyfill
|
||||
dgram : no-op
|
||||
dns : no-op
|
||||
domain : polyfill
|
||||
events : polyfill
|
||||
fs : no-op
|
||||
http : polyfill
|
||||
https : polyfill
|
||||
module : no-op
|
||||
net : polyfill
|
||||
os : polyfill
|
||||
path : polyfill
|
||||
perf_hooks : no-op
|
||||
process : polyfill
|
||||
punycode : polyfill
|
||||
querystring : polyfill
|
||||
readline : no-op
|
||||
repl : no-op
|
||||
stream : polyfill
|
||||
string_decoder : polyfill
|
||||
sys : polyfill
|
||||
timers : polyfill
|
||||
tls : no-op
|
||||
tty : polyfill
|
||||
url : polyfill
|
||||
util : polyfill
|
||||
v8 : no-op
|
||||
vm : no-op
|
||||
zlib : polyfill
|
||||
assert : polyfill
|
||||
buffer : polyfill
|
||||
child_process : no-op
|
||||
cluster : no-op
|
||||
console : polyfill
|
||||
constants : polyfill
|
||||
crypto : polyfill
|
||||
dgram : no-op
|
||||
dns : no-op
|
||||
domain : polyfill
|
||||
events : polyfill
|
||||
fs : no-op
|
||||
http : polyfill
|
||||
https : polyfill
|
||||
module : no-op
|
||||
net : polyfill
|
||||
os : polyfill
|
||||
path : polyfill
|
||||
perf_hooks : no-op
|
||||
process : polyfill
|
||||
punycode : polyfill
|
||||
querystring : polyfill
|
||||
readline : no-op
|
||||
repl : no-op
|
||||
stream : polyfill
|
||||
string_decoder : polyfill
|
||||
sys : polyfill
|
||||
timers : polyfill
|
||||
timers/promises : polyfill
|
||||
tls : no-op
|
||||
tty : polyfill
|
||||
url : polyfill
|
||||
util : polyfill
|
||||
v8 : no-op
|
||||
vm : no-op
|
||||
zlib : polyfill
|
||||
`,
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user