@ohos-ports/bun-repl 0.0.0-stage → 2.1.1-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintignore +2 -0
- package/.eslintrc.json +89 -0
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/dist/cli.js +62 -0
- package/dist/colors.js +68 -0
- package/dist/module/repl.js +83 -0
- package/dist/repl.js +945 -0
- package/dist/shims/bun.js +126 -0
- package/dist/shims/inspector-server.js +518 -0
- package/dist/swcrc.js +66 -0
- package/dist/transpiler.js +86 -0
- package/dist/utl/index.d.ts +30 -0
- package/dist/utl/index.js +2760 -0
- package/dist/utl/primordials.js +216 -0
- package/dist/utl/proxy.js +30 -0
- package/package.json +50 -4
- package/scripts/build.mjs +98 -0
- package/src/cli.ts +54 -0
- package/src/colors.ts +73 -0
- package/src/module/repl.ts +77 -0
- package/src/repl.ts +947 -0
- package/src/shims/bun.js +126 -0
- package/src/shims/inspector-server.js +518 -0
- package/src/swcrc.ts +70 -0
- package/src/transpiler.ts +96 -0
- package/src/utl/index.d.ts +117 -0
- package/src/utl/index.js +2760 -0
- package/src/utl/primordials.js +216 -0
- package/src/utl/proxy.js +30 -0
- package/tsconfig.json +99 -0
package/src/repl.ts
ADDED
|
@@ -0,0 +1,947 @@
|
|
|
1
|
+
import type { JSC } from 'bun-devtools';
|
|
2
|
+
import { join, dirname, basename, resolve as pathresolve } from 'node:path';
|
|
3
|
+
import { readFileSync, existsSync, readSync } from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import readline from 'node:readline';
|
|
6
|
+
import { createRequire } from 'node:module';
|
|
7
|
+
import $ from './colors.ts';
|
|
8
|
+
import swcrc from './swcrc.ts';
|
|
9
|
+
import SWCTranspiler from './transpiler.ts';
|
|
10
|
+
import repl from './module/repl.ts';
|
|
11
|
+
import utl, { $Proxy } from './utl/index.js';
|
|
12
|
+
import bun, { serve, write, inspect as bunInspect, inspectorReady } from './shims/bun.js';
|
|
13
|
+
const { exit, cwd } = process;
|
|
14
|
+
// Node port: Bun's `import.meta.require` equivalent — a CJS loader anchored at this module.
|
|
15
|
+
const metaRequire = createRequire(import.meta.url);
|
|
16
|
+
const stdoutWrite = process.stdout.write.bind(process.stdout);
|
|
17
|
+
|
|
18
|
+
/**Safely get an object's property. If an error occurs, just treat it as non-existent. */
|
|
19
|
+
export function SafeGet(obj: any, key: string | number | symbol): any {
|
|
20
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
|
21
|
+
try { return obj?.[key]; } catch { return undefined; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Safely inspect a value, falling down through implementations as they fail. If all inspectors fail, simply return undefined. */
|
|
25
|
+
export function SafeInspect(val: any, opts: utl.InspectOptions = {}): string {
|
|
26
|
+
try {
|
|
27
|
+
try {
|
|
28
|
+
return utl.inspect(val, opts);
|
|
29
|
+
} catch {
|
|
30
|
+
// Bun's native inspect is expected to never fail. Unfortunately it doesn't inspect a lot of values properly,
|
|
31
|
+
// nor does it support the full options object, therefore it's the fallback for now.
|
|
32
|
+
if (opts.depth === null) opts.depth = Infinity;
|
|
33
|
+
if (typeof opts.sorted === 'function') opts.sorted = true;
|
|
34
|
+
return bunInspect(val, opts as utl.InspectOptions & { depth?: number, sorted?: boolean });
|
|
35
|
+
}
|
|
36
|
+
} catch {
|
|
37
|
+
try {
|
|
38
|
+
// In the greatly unexpected event of Bun's native inspect failing,
|
|
39
|
+
// panic back to the primitive method of string coercion.
|
|
40
|
+
console.warn($.yellow+$.dim+'All value inspection methods failed, this should not happen!'+$.reset);
|
|
41
|
+
const str = val + '';
|
|
42
|
+
// If the coercion somehow fails to return a proper string, resort to an empty one.
|
|
43
|
+
return typeof str === 'string' ? str : '';
|
|
44
|
+
} catch {
|
|
45
|
+
// Here's a fun fact about javascript.
|
|
46
|
+
// You can't rely even on string concatenation as a fully reliable string coercion method.
|
|
47
|
+
// Introducing, null prototype objects: `Object.create(null) + ""` = throws TypeError
|
|
48
|
+
return ''; // If this line of code ever runs, something truly catastrophic happened...
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const GLOBAL = globalThis;
|
|
54
|
+
// node port: one-shot global REPL setup guard — Bun exits the process after each
|
|
55
|
+
// single-shot run, but the Node port returns control, so start() may run again.
|
|
56
|
+
let REPL_GLOBALS_READY = false;
|
|
57
|
+
const { Buffer, WebSocket, Map, EvalError, TypeError, Error } = GLOBAL;
|
|
58
|
+
//const Promise: PromiseConstructor<any> = GLOBAL.Promise; // TS bug?
|
|
59
|
+
const { isBuffer } = Buffer;
|
|
60
|
+
const SymbolToStringTag = Symbol.toStringTag;
|
|
61
|
+
const JSONParse = JSON.parse;
|
|
62
|
+
const JSONStringify = JSON.stringify;
|
|
63
|
+
const ObjectAssign = Object.assign;
|
|
64
|
+
const ObjectDefineProperty = Object.defineProperty;
|
|
65
|
+
const ReflectGet = Reflect.get;
|
|
66
|
+
const ReflectSet = Reflect.set;
|
|
67
|
+
const ReflectDeleteProperty = Reflect.deleteProperty;
|
|
68
|
+
const RegExpTest = Function.prototype.call.bind(RegExp.prototype.test) as Primordial<RegExp, 'test'>;
|
|
69
|
+
const RegExpPrototypeSymbolReplace = Function.prototype.call.bind(RegExp.prototype[Symbol.replace]) as Primordial<RegExp, typeof Symbol.replace>;
|
|
70
|
+
const FunctionApply = Function.prototype.call.bind(Function.prototype.apply) as Primordial<Function, 'apply'>;
|
|
71
|
+
const BufferToString = Function.prototype.call.bind(Reflect.get(Buffer.prototype, 'toString') as Buffer['toString']) as Primordial<Buffer, 'toString'>;
|
|
72
|
+
const StringTrim = Function.prototype.call.bind(String.prototype.trim) as Primordial<String, 'trim'>;
|
|
73
|
+
const StringPadStart = Function.prototype.call.bind(String.prototype.padStart) as Primordial<String, 'padStart'>;
|
|
74
|
+
const StringPadEnd = Function.prototype.call.bind(String.prototype.padEnd) as Primordial<String, 'padEnd'>;
|
|
75
|
+
const StringRepeat = Function.prototype.call.bind(String.prototype.repeat) as Primordial<String, 'repeat'>;
|
|
76
|
+
const StringMatchAll = Function.prototype.call.bind(String.prototype.matchAll) as Primordial<String, 'matchAll'>;
|
|
77
|
+
const StringPrototypeSlice = Function.prototype.call.bind(String.prototype.slice) as Primordial<String, 'slice'>;
|
|
78
|
+
const StringPrototypeSplit = Function.prototype.call.bind(String.prototype.split) as Primordial<String, 'split'>;
|
|
79
|
+
const StringPrototypeIncludes = Function.prototype.call.bind(String.prototype.includes) as Primordial<String, 'includes'>;
|
|
80
|
+
const StringReplace = Function.prototype.call.bind(String.prototype.replace) as Primordial<String, 'replace'>;
|
|
81
|
+
const StringPrototypeReplaceAll = Function.prototype.call.bind(String.prototype.replaceAll) as Primordial<String, 'replaceAll'>;
|
|
82
|
+
const ArrayPush = Function.prototype.call.bind(Array.prototype.push) as Primordial<Array<any>, 'push'>;
|
|
83
|
+
const ArrayPrototypePop = Function.prototype.call.bind(Array.prototype.pop) as Primordial<Array<any>, 'pop'>;
|
|
84
|
+
const ArrayPrototypeJoin = Function.prototype.call.bind(Array.prototype.join) as Primordial<Array<any>, 'join'>;
|
|
85
|
+
const ArrayPrototypeFind = Function.prototype.call.bind(Array.prototype.find) as Primordial<Array<any>, 'find'>;
|
|
86
|
+
const ArrayPrototypeFilter = Function.prototype.call.bind(Array.prototype.filter) as Primordial<Array<any>, 'filter'>;
|
|
87
|
+
const MapGet = Function.prototype.call.bind(Map.prototype.get) as Primordial<Map<any, any>, 'get'>;
|
|
88
|
+
const MapSet = Function.prototype.call.bind(Map.prototype.set) as Primordial<Map<any, any>, 'set'>;
|
|
89
|
+
const MapDelete = Function.prototype.call.bind(Map.prototype.delete) as Primordial<Map<any, any>, 'delete'>;
|
|
90
|
+
const console = {
|
|
91
|
+
dir: GLOBAL.console.dir,
|
|
92
|
+
log: GLOBAL.console.log,
|
|
93
|
+
info: GLOBAL.console.info,
|
|
94
|
+
warn: GLOBAL.console.warn,
|
|
95
|
+
error: GLOBAL.console.error,
|
|
96
|
+
debug: GLOBAL.console.debug,
|
|
97
|
+
clear: GLOBAL.console.clear,
|
|
98
|
+
trace: GLOBAL.console.trace,
|
|
99
|
+
assert: GLOBAL.console.assert,
|
|
100
|
+
};
|
|
101
|
+
// Uncomment below for extreme debugging
|
|
102
|
+
//for (const k in console) console[k as keyof typeof console] = GLOBAL.console.trace;
|
|
103
|
+
const IS_DEBUG = process.argv.includes('--debug');
|
|
104
|
+
const debuglog = IS_DEBUG ? (...args: string[]) => (console.debug($.dim+'DEBUG:', ...args, $.reset)) : () => void 0;
|
|
105
|
+
//const SLOPPY_MODE = process.argv.includes('--sloppy');
|
|
106
|
+
const NO_HISTORY = process.env.BUN_REPL_NO_HISTORY || process.argv.includes('--no-history');
|
|
107
|
+
|
|
108
|
+
type Primordial<T, M extends keyof T> = <S extends T>(
|
|
109
|
+
self: S, ...args: Parameters<S[M] extends (...args: any) => any ? S[M] : never>
|
|
110
|
+
) => ReturnType<S[M] extends (...args: any) => any ? S[M] : never>;
|
|
111
|
+
type JSCResponsePromiseCallbacks = {
|
|
112
|
+
resolve: <T extends JSC.ResponseMap[keyof JSC.ResponseMap]>(value: T) => void;
|
|
113
|
+
reject: (reason: {
|
|
114
|
+
code?: string | undefined;
|
|
115
|
+
message: string;
|
|
116
|
+
}) => void;
|
|
117
|
+
};
|
|
118
|
+
type EvalRemoteObject = JSC.Runtime.RemoteObject & { wasRejectedPromise?: boolean; wasThrown?: boolean; };
|
|
119
|
+
type RemoteObjectType = EvalRemoteObject['type'];
|
|
120
|
+
type RemoteObjectSubtype = NonNullable<EvalRemoteObject['subtype']>;
|
|
121
|
+
type TypeofToValueType<T extends RemoteObjectType> =
|
|
122
|
+
T extends 'string' ? { type: T, value: string; } :
|
|
123
|
+
T extends 'number' ? { type: T, value: number, description: string; } :
|
|
124
|
+
T extends 'bigint' ? { type: T, description: string; } :
|
|
125
|
+
T extends 'boolean' ? { type: T, value: boolean; } :
|
|
126
|
+
T extends 'symbol' ? { type: T, objectId: string, className: string, description: string; } :
|
|
127
|
+
T extends 'undefined' ? { type: T; } :
|
|
128
|
+
T extends 'object' ? { type: T, subtype?: RemoteObjectSubtype, objectId: string, className: string, description: string; } :
|
|
129
|
+
T extends 'function' ? { type: T, subtype?: RemoteObjectSubtype, objectId: string, className: string, description: string; } : never;
|
|
130
|
+
type SubtypeofToValueType<T extends RemoteObjectSubtype, BaseObj = { type: 'object', subtype: T, objectId: string, className: string, description: string; }> =
|
|
131
|
+
T extends 'error' ? BaseObj :
|
|
132
|
+
T extends 'array' ? BaseObj & { size: number; } :
|
|
133
|
+
T extends 'null' ? { type: 'object', subtype: T, value: null; } :
|
|
134
|
+
T extends 'regexp' ? BaseObj :
|
|
135
|
+
T extends 'date' ? BaseObj :
|
|
136
|
+
T extends 'map' ? BaseObj & { size: number; } :
|
|
137
|
+
T extends 'set' ? BaseObj & { size: number; } :
|
|
138
|
+
T extends 'weakmap' ? BaseObj & { size: number; } :
|
|
139
|
+
T extends 'weakset' ? BaseObj & { size: number; } :
|
|
140
|
+
T extends 'iterator' ? never /*//!error*/ :
|
|
141
|
+
T extends 'class' ? { type: 'function', subtype: T, objectId: string, className: string, description: string, classPrototype: JSC.Runtime.RemoteObject; } :
|
|
142
|
+
T extends 'proxy' ? BaseObj :
|
|
143
|
+
T extends 'weakref' ? BaseObj : never;
|
|
144
|
+
interface Keypress { sequence: string, name: string, ctrl: boolean, meta: boolean, shift: boolean }
|
|
145
|
+
// Node port: TS `enum` is not supported by Node's strip-only TS loader, so the
|
|
146
|
+
// modifier bitmask enum is expressed as a const object (same semantics).
|
|
147
|
+
const Modifier = {
|
|
148
|
+
NONE : 0b000,
|
|
149
|
+
CTRL : 0b001,
|
|
150
|
+
ALT : 0b010,
|
|
151
|
+
SHIFT : 0b100,
|
|
152
|
+
CTRL_ALT : 0b001 | 0b010,
|
|
153
|
+
CTRL_SHIFT : 0b001 | 0b100,
|
|
154
|
+
ALT_SHIFT : 0b010 | 0b100,
|
|
155
|
+
CTRL_ALT_SHIFT : 0b001 | 0b010 | 0b100,
|
|
156
|
+
} as const;
|
|
157
|
+
|
|
158
|
+
/** Convert a {@link WebSocket.onmessage} `event.data` value to a string. */
|
|
159
|
+
function wsDataToString(data: Parameters<NonNullable<WebSocket['onmessage']>>[0]['data']): string {
|
|
160
|
+
if (data instanceof ArrayBuffer) return new TextDecoder('utf-8').decode(data);
|
|
161
|
+
if (data instanceof Buffer || isBuffer(data)) return BufferToString(data, 'utf-8');
|
|
162
|
+
else return data;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Note: This is a custom REPLServer, not the Node.js node:repl module one.
|
|
166
|
+
class REPLServer extends WebSocket {
|
|
167
|
+
constructor() {
|
|
168
|
+
const server = serve({
|
|
169
|
+
inspector: true,
|
|
170
|
+
development: true,
|
|
171
|
+
port: process.env.BUN_REPL_PORT ?? 0,
|
|
172
|
+
// @ts-expect-error stub
|
|
173
|
+
fetch() {},
|
|
174
|
+
});
|
|
175
|
+
super(`ws://${server.hostname}:${server.port}/bun:inspect`);
|
|
176
|
+
debuglog(`[ws/open] repl server listening on ${$.blueBright}ws://${server.hostname}:${server.port}/bun:inspect`);
|
|
177
|
+
this.onmessage = (event) => {
|
|
178
|
+
try {
|
|
179
|
+
const data = JSONParse(wsDataToString(event.data)) as JSC.Response<keyof JSC.ResponseMap>;
|
|
180
|
+
const { id } = data;
|
|
181
|
+
const promiseRef = MapGet(this.#pendingReqs, id);
|
|
182
|
+
if (promiseRef) {
|
|
183
|
+
MapDelete(this.#pendingReqs, id);
|
|
184
|
+
if ('error' in data) promiseRef.reject(data.error);
|
|
185
|
+
else if ('result' in data) promiseRef.resolve(data.result);
|
|
186
|
+
else throw `Received response with no result or error: ${id}`;
|
|
187
|
+
} else throw `Received message for unknown request ID: ${id}`;
|
|
188
|
+
} catch (err) {
|
|
189
|
+
console.error(`[ws/message] An unexpected error occured:`, err, '\nReceived Data:', event.data);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
this.onclose = () => console.info('[ws/close] disconnected');
|
|
193
|
+
this.onerror = (error) => console.error('[ws/error]', error);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Incrementing current request ID */
|
|
197
|
+
#reqID = 0;
|
|
198
|
+
/** Object ID of the global object */
|
|
199
|
+
#globalObjectID!: string;
|
|
200
|
+
/** Queue of pending requests promises to resolve, mapped by request ID */
|
|
201
|
+
readonly #pendingReqs = new Map<number, JSCResponsePromiseCallbacks>();
|
|
202
|
+
/** Must be awaited before using the REPLServer */
|
|
203
|
+
readonly ready = new Promise<void>(resolve => {
|
|
204
|
+
// It's okay to not use primordials here since this only runs once before users can use the REPL
|
|
205
|
+
this.onopen = () => void this.request('Runtime.enable', {})
|
|
206
|
+
.then(() => this.rawEval('globalThis'))
|
|
207
|
+
.then(({ result }) => {
|
|
208
|
+
this.#globalObjectID = result.objectId!;
|
|
209
|
+
// node port: skip repeated global setup (see REPL_GLOBALS_READY)
|
|
210
|
+
if (REPL_GLOBALS_READY) { resolve(); return; }
|
|
211
|
+
GLOBAL.Proxy = $Proxy;
|
|
212
|
+
Object.defineProperty(GLOBAL, '_', { value: undefined, writable: true, configurable: true }); // node port: configurable for repeated start()
|
|
213
|
+
Object.defineProperty(GLOBAL, '_error', { value: undefined, writable: true, configurable: true }); // node port: configurable for repeated start()
|
|
214
|
+
Object.defineProperty(GLOBAL, 'repl', { value: repl, writable: true, configurable: true }); // node port: configurable for repeated start()
|
|
215
|
+
// import.meta.resolveSync takes a *file* path for the parent.
|
|
216
|
+
// Bun.resolveSync takes a *directory* path for the parent.
|
|
217
|
+
const { resolveSync } = Bun;
|
|
218
|
+
const ArrayIncludes = Function.prototype.call.bind(Array.prototype.includes) as Primordial<Array<any>, 'includes'>;
|
|
219
|
+
const nodePrefixedModules = repl.builtinModules
|
|
220
|
+
.filter(x => x[0] !== '_' && !x.includes(':') && !['undici', 'ws', 'detect-libc', 'bun'].includes(x));
|
|
221
|
+
// eslint-disable-next-line unicorn/prefer-module
|
|
222
|
+
const originalRequire = metaRequire; // node port: ESM has no ambient `require` (Bun did)
|
|
223
|
+
Object.defineProperty(GLOBAL, 'require', { value: function require(moduleID: string) { // node port: descriptor made writable/configurable below so repeated start() works
|
|
224
|
+
if (ArrayIncludes(nodePrefixedModules, moduleID)) moduleID = `node:${moduleID}`;
|
|
225
|
+
if (moduleID === 'node:repl') return repl; // polyfill
|
|
226
|
+
if (moduleID === 'bun') return bun; // workaround
|
|
227
|
+
const here = cwd();
|
|
228
|
+
try {
|
|
229
|
+
moduleID = resolveSync(moduleID, here);
|
|
230
|
+
} catch {
|
|
231
|
+
// TODO: attempt to load the module from the global directory if it's not found in the local directory
|
|
232
|
+
throw {
|
|
233
|
+
name: 'ResolveError',
|
|
234
|
+
message: `Cannot find module "${moduleID}" from "${join(here, swcrc.filename!)}"`,
|
|
235
|
+
specifier: moduleID
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
debuglog((`Importing: ${$.blueBright+moduleID+$.reset}`));
|
|
239
|
+
try {
|
|
240
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
|
241
|
+
return metaRequire(moduleID);
|
|
242
|
+
} catch (e) {
|
|
243
|
+
const err = e as Error;
|
|
244
|
+
if (err instanceof TypeError && StringPrototypeIncludes(err.message, 'require() async module')) {
|
|
245
|
+
err.stack = '';
|
|
246
|
+
}
|
|
247
|
+
throw err;
|
|
248
|
+
}
|
|
249
|
+
}, writable: true, configurable: true }); // node port: Bun exited the process after one shot; the Node port returns, so allow redefinition
|
|
250
|
+
Object.defineProperties(GLOBAL.require, {
|
|
251
|
+
resolve: { value: function resolve(moduleID: string, { paths = ['.'] } = {}) {
|
|
252
|
+
if (paths.length === 0) paths.push('.');
|
|
253
|
+
const base = cwd();
|
|
254
|
+
for (const path of paths) {
|
|
255
|
+
const from = pathresolve(base, path);
|
|
256
|
+
try {
|
|
257
|
+
return resolveSync(moduleID, from);
|
|
258
|
+
} catch { continue; }
|
|
259
|
+
}
|
|
260
|
+
throw {
|
|
261
|
+
name: 'ResolveError',
|
|
262
|
+
message: `Cannot find module "${moduleID}"`,
|
|
263
|
+
specifier: moduleID
|
|
264
|
+
};
|
|
265
|
+
} },
|
|
266
|
+
main: { value: Reflect.get(originalRequire, 'main') as unknown },
|
|
267
|
+
extensions: { value: Reflect.get(originalRequire, 'extensions') as unknown },
|
|
268
|
+
cache: { value: Reflect.get(originalRequire, 'cache') as unknown },
|
|
269
|
+
});
|
|
270
|
+
GLOBAL.require.resolve.paths = function paths() { return []; }; // Bun's polyfill of this function is also like this for now
|
|
271
|
+
const REQUIRE = GLOBAL.require;
|
|
272
|
+
for (const module of nodePrefixedModules) {
|
|
273
|
+
if (module.includes('/')) continue;
|
|
274
|
+
if (['crypto', 'repl', 'process', 'console'].includes(module)) continue;
|
|
275
|
+
const descriptor: PropertyDescriptor & { cached: unknown } = { cached: null };
|
|
276
|
+
const getter = (function (this: typeof descriptor) {
|
|
277
|
+
if (this.cached) return this.cached;
|
|
278
|
+
return this.cached = REQUIRE(module) as unknown;
|
|
279
|
+
}).bind(descriptor);
|
|
280
|
+
descriptor.get = getter;
|
|
281
|
+
Object.defineProperty(GLOBAL, module, descriptor);
|
|
282
|
+
}
|
|
283
|
+
for (const module of repl.builtinModules.filter(x => x.startsWith('bun:'))) {
|
|
284
|
+
if (module.includes('/')) continue;
|
|
285
|
+
if (['bun:main', 'bun:wrap'].includes(module)) continue;
|
|
286
|
+
const descriptor: PropertyDescriptor & { cached: unknown } = { cached: null };
|
|
287
|
+
const getter = (function (this: typeof descriptor) {
|
|
288
|
+
if (this.cached) return this.cached;
|
|
289
|
+
return this.cached = REQUIRE(module) as unknown;
|
|
290
|
+
}).bind(descriptor);
|
|
291
|
+
descriptor.get = getter;
|
|
292
|
+
Object.defineProperty(GLOBAL, module.slice(4), descriptor);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Yes, if someone types a 0xFFFF characters line, they will fill up the buffer.
|
|
296
|
+
// But that's very unlikely to happen, and if it does, it will just cutoff the line.
|
|
297
|
+
// Anyway this just a temporary workaround for https://github.com/oven-sh/bun/issues/5267
|
|
298
|
+
const promptReuseBuffer = Buffer.allocUnsafe(0xFFFF);
|
|
299
|
+
globalThis.prompt = function prompt(question: string = 'Prompt', defaultValue: unknown = null): string | null {
|
|
300
|
+
stdoutWrite(question + ' ');
|
|
301
|
+
let i = -1;
|
|
302
|
+
// eslint-disable-next-line no-constant-condition
|
|
303
|
+
while (true) {
|
|
304
|
+
// This currently relies on https://github.com/oven-sh/bun/issues/5305
|
|
305
|
+
// If that bug is fixed, this will break one way or another.
|
|
306
|
+
const read = readSync(0, promptReuseBuffer, { length: 1, offset: ++i });
|
|
307
|
+
if (read !== 1) {
|
|
308
|
+
if (read === 0) { // This means the buffer got filled up (unlikely, but possible)
|
|
309
|
+
stdoutWrite('\n');
|
|
310
|
+
return BufferToString(promptReuseBuffer, 'utf8', 0, i) || defaultValue as string | null;
|
|
311
|
+
}
|
|
312
|
+
else throw new Error('Unexpected read length'); // This will tell us if the bug is fixed.
|
|
313
|
+
}
|
|
314
|
+
const char = promptReuseBuffer[i];
|
|
315
|
+
if (char === 3) {
|
|
316
|
+
stdoutWrite('^C\n');
|
|
317
|
+
exit(0);
|
|
318
|
+
}
|
|
319
|
+
if (char === 4) {
|
|
320
|
+
stdoutWrite('\n');
|
|
321
|
+
return defaultValue as string | null;
|
|
322
|
+
}
|
|
323
|
+
if (char === 27) {
|
|
324
|
+
stdoutWrite('^[');
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
if (char === 127) {
|
|
328
|
+
i--;
|
|
329
|
+
if (i < 0) continue;
|
|
330
|
+
stdoutWrite('\b \b');
|
|
331
|
+
if (promptReuseBuffer[i] === 27) stdoutWrite('\b \b');
|
|
332
|
+
i--;
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
stdoutWrite(BufferToString(promptReuseBuffer, 'utf8', i, i + 1));
|
|
336
|
+
if (char === 13 || char === 10) {
|
|
337
|
+
stdoutWrite('\n');
|
|
338
|
+
return BufferToString(promptReuseBuffer, 'utf8', 0, i) || defaultValue as string | null;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
Object.defineProperty(GLOBAL, '@@bunReplRuntimeHelpers', {
|
|
343
|
+
value: Object.freeze({
|
|
344
|
+
join, dirname, basename, resolve: pathresolve, getcwd: process.cwd,
|
|
345
|
+
pathToFileURL: Bun.pathToFileURL, fileURLToPath: Bun.fileURLToPath,
|
|
346
|
+
StringStartsWith: Function.prototype.call.bind(String.prototype.startsWith),
|
|
347
|
+
ObjectFreeze: Object.freeze,
|
|
348
|
+
}),
|
|
349
|
+
});
|
|
350
|
+
Object.defineProperty(GLOBAL, 'eval', { value: eval, configurable: false, writable: false }); // used by inlined import.meta trick
|
|
351
|
+
Object.defineProperty(GLOBAL, 'Object', { value: Object, configurable: false, writable: false }); // used by swc
|
|
352
|
+
Object.freeze(Object); // bun's node:events polyfill relies on this
|
|
353
|
+
Object.freeze(Promise); // must preserve .name property
|
|
354
|
+
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
|
355
|
+
Object.freeze(Promise.prototype); // too many possible pitfalls
|
|
356
|
+
//? Workarounds for bug: https://canary.discord.com/channels/876711213126520882/888839314056839309/1120394929164779570
|
|
357
|
+
const TypedArray = Object.getPrototypeOf(Uint8Array) as typeof Uint8Array.prototype;
|
|
358
|
+
const wrapIterator = (iterable: Record<string | symbol, any>, key: string | symbol = Symbol.iterator, name = iterable.name + ' Iterator') => {
|
|
359
|
+
const original = Reflect.get(iterable.prototype, key) as GeneratorFunction;
|
|
360
|
+
Reflect.set(iterable.prototype, key, function (this: typeof iterable, ...argz: any[]) {
|
|
361
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
362
|
+
const thiz = this;
|
|
363
|
+
function* wrappedIter() { yield* FunctionApply(original, thiz, argz) as Generator; }
|
|
364
|
+
return ObjectDefineProperty(wrappedIter(), SymbolToStringTag, { value: name, configurable: true });
|
|
365
|
+
});
|
|
366
|
+
};
|
|
367
|
+
wrapIterator(Array);
|
|
368
|
+
wrapIterator(Array, 'keys');
|
|
369
|
+
wrapIterator(Array, 'values');
|
|
370
|
+
wrapIterator(Array, 'entries');
|
|
371
|
+
wrapIterator(TypedArray, Symbol.iterator, 'Array Iterator');
|
|
372
|
+
wrapIterator(TypedArray, 'entries', 'Array Iterator');
|
|
373
|
+
wrapIterator(TypedArray, 'values', 'Array Iterator');
|
|
374
|
+
wrapIterator(TypedArray, 'keys', 'Array Iterator');
|
|
375
|
+
wrapIterator(String);
|
|
376
|
+
wrapIterator(Map);
|
|
377
|
+
wrapIterator(Map, 'keys');
|
|
378
|
+
wrapIterator(Map, 'values');
|
|
379
|
+
wrapIterator(Map, 'entries');
|
|
380
|
+
wrapIterator(Set);
|
|
381
|
+
wrapIterator(Set, 'keys');
|
|
382
|
+
wrapIterator(Set, 'values');
|
|
383
|
+
wrapIterator(Set, 'entries');
|
|
384
|
+
|
|
385
|
+
REPL_GLOBALS_READY = true;
|
|
386
|
+
resolve();
|
|
387
|
+
});
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
/** Check and assert typeof for a remote object */
|
|
391
|
+
typeof<T extends RemoteObjectType>(v: JSC.Runtime.RemoteObject, expected: T):
|
|
392
|
+
v is Omit<JSC.Runtime.RemoteObject, 'value'> & TypeofToValueType<T> {
|
|
393
|
+
return v.type === expected;
|
|
394
|
+
}
|
|
395
|
+
/** Check and assert subtypeof for a remote object */
|
|
396
|
+
subtypeof<T extends RemoteObjectSubtype>(v: JSC.Runtime.RemoteObject, expected: T):
|
|
397
|
+
v is Omit<JSC.Runtime.RemoteObject, 'value'> & SubtypeofToValueType<T> {
|
|
398
|
+
return v.subtype === expected;
|
|
399
|
+
}
|
|
400
|
+
/** Send a direct request to the inspector */
|
|
401
|
+
request<T extends keyof JSC.RequestMap>(method: T, params: JSC.RequestMap[T]) {
|
|
402
|
+
const req: JSC.Request<T> = { id: ++this.#reqID, method, params };
|
|
403
|
+
const response = new Promise<JSC.ResponseMap[T]>((resolve, reject) => {
|
|
404
|
+
MapSet(this.#pendingReqs, this.#reqID, { resolve: resolve as typeof resolve extends Promise<infer P> ? P : never, reject });
|
|
405
|
+
}).catch(err => { throw ObjectAssign(new Error, err); });
|
|
406
|
+
this.send(JSONStringify(req));
|
|
407
|
+
return response;
|
|
408
|
+
}
|
|
409
|
+
/** Direct shortcut for a `Runtime.evaluate` request */
|
|
410
|
+
async rawEval(code: string): Promise<JSC.Runtime.EvaluateResponse> {
|
|
411
|
+
return this.request('Runtime.evaluate', {
|
|
412
|
+
expression: code,
|
|
413
|
+
generatePreview: true
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
/** Run a snippet of code in the REPL */
|
|
417
|
+
async eval(code: string, topLevelAwaited = false, extraOut?: { errored?: boolean, noPrintError?: boolean }): Promise<string> {
|
|
418
|
+
debuglog(`transpiled code: ${StringTrim(code)}`);
|
|
419
|
+
const { result, wasThrown: thrown } = await this.rawEval(code);
|
|
420
|
+
let remoteObj: EvalRemoteObject = result;
|
|
421
|
+
remoteObj.wasThrown = thrown;
|
|
422
|
+
|
|
423
|
+
if (result.type === 'object') ObjectTypeHandler: {
|
|
424
|
+
if (result.subtype === 'null') break ObjectTypeHandler;
|
|
425
|
+
if (!result.objectId) throw new EvalError(`Received non-null object without objectId: ${JSONStringify(result)}`);
|
|
426
|
+
if (result.className === 'Promise') {
|
|
427
|
+
if (!result.preview) throw new EvalError(`Received Promise object without preview: ${JSONStringify(result)}}`);
|
|
428
|
+
if (topLevelAwaited) {
|
|
429
|
+
const awaited = await this.request('Runtime.awaitPromise', { promiseObjectId: result.objectId, generatePreview: false });
|
|
430
|
+
remoteObj = awaited.result;
|
|
431
|
+
remoteObj.wasThrown = awaited.wasThrown;
|
|
432
|
+
if (remoteObj.type === 'undefined') {
|
|
433
|
+
console.warn(
|
|
434
|
+
$.yellow+$.dim+'[!] REPL top-level await is still very experimental and prone to failing on complex code snippets.\n' +
|
|
435
|
+
' You are seeing this because top-level await usage was detected with undefined as the result, if that was expected, you can ignore this.'+$.reset
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
if (result.preview.properties && ArrayPrototypeFind(result.preview.properties, p => p.name === 'status')?.value === 'rejected') {
|
|
440
|
+
remoteObj.wasRejectedPromise = true;
|
|
441
|
+
}
|
|
442
|
+
break ObjectTypeHandler;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
//! bug workaround, bigints are being passed as undefined to Runtime.callFunctionOn (?)
|
|
447
|
+
if (remoteObj.type === 'bigint') {
|
|
448
|
+
if (!remoteObj.description) throw new EvalError(`Received BigInt value without description: ${JSONStringify(remoteObj)}`);
|
|
449
|
+
const value = BigInt(StringPrototypeSlice(remoteObj.description, 0, -1));
|
|
450
|
+
ReflectSet(GLOBAL, remoteObj.wasThrown ? '_error' : '_', value);
|
|
451
|
+
return (remoteObj.wasThrown ? $.red + 'Uncaught ' + $.reset : '') + SafeInspect(value,
|
|
452
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
|
453
|
+
ReflectGet(GLOBAL, 'repl')?.writer?.options as utl.InspectOptions
|
|
454
|
+
?? { colors: Bun.enableANSIColors, showProxy: true }
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
//! bug workaround, Infinity and NaN are being passed as null to Runtime.callFunctionOn (?)
|
|
458
|
+
// also -0 is being passed as 0
|
|
459
|
+
if (remoteObj.type === 'number') {
|
|
460
|
+
if (!remoteObj.description) throw new EvalError(`Received Number value without description: ${JSONStringify(remoteObj)}`);
|
|
461
|
+
let value = remoteObj.value as number;
|
|
462
|
+
if (remoteObj.description === 'Infinity') value = Infinity;
|
|
463
|
+
else if (remoteObj.description === '-Infinity') value = -Infinity;
|
|
464
|
+
else if (remoteObj.description === 'NaN') value = NaN;
|
|
465
|
+
else if (remoteObj.description === '-0') value = -0;
|
|
466
|
+
ReflectSet(GLOBAL, remoteObj.wasThrown ? '_error' : '_', value);
|
|
467
|
+
return (remoteObj.wasThrown ? $.red + 'Uncaught ' + $.reset : '') + SafeInspect(value,
|
|
468
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
|
469
|
+
ReflectGet(GLOBAL, 'repl')?.writer?.options as utl.InspectOptions
|
|
470
|
+
?? { colors: Bun.enableANSIColors, showProxy: true }
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
const { wasThrown } = remoteObj;
|
|
475
|
+
const REPL_INTERNALS = '@@bunReplInternals';
|
|
476
|
+
ObjectDefineProperty(GLOBAL, REPL_INTERNALS, {
|
|
477
|
+
value: { SafeInspect, SafeGet, StringReplace, bunInspect },
|
|
478
|
+
configurable: true,
|
|
479
|
+
});
|
|
480
|
+
const inspected = await this.request('Runtime.callFunctionOn', {
|
|
481
|
+
objectId: this.#globalObjectID,
|
|
482
|
+
functionDeclaration: `(v) => {
|
|
483
|
+
const { SafeInspect, SafeGet, StringReplace, bunInspect } = this['${REPL_INTERNALS}'];
|
|
484
|
+
if (!${wasThrown!}) this._ = v;
|
|
485
|
+
else this._error = v;
|
|
486
|
+
if (v?.name === 'ResolveError')
|
|
487
|
+
return \`${$.red}ResolveError${$.reset}${$.dim}: ${$.reset}${$.whiteBright}\${StringReplace(
|
|
488
|
+
SafeGet(v, 'message') || \`Failed to resolve import "?" from "?"\`, / ".+" from ".+"$/,
|
|
489
|
+
\` ${$.blueBright}"\${SafeGet(v, 'specifier') ?? '<unresolved>'}"${$.whiteBright} from ${$.cyan+cwd()}/${swcrc.filename!}\`
|
|
490
|
+
)}${$.reset}\`;
|
|
491
|
+
if (${remoteObj.subtype === 'error'}) return bunInspect(v, { colors: ${Bun.enableANSIColors} });
|
|
492
|
+
return SafeInspect(v, this.repl?.writer?.options ?? { colors: ${Bun.enableANSIColors}, showProxy: true });
|
|
493
|
+
}`,
|
|
494
|
+
arguments: [remoteObj],
|
|
495
|
+
});
|
|
496
|
+
ReflectDeleteProperty(GLOBAL, REPL_INTERNALS);
|
|
497
|
+
if (inspected.wasThrown) throw new EvalError(`Failed to inspect object: ${JSONStringify(inspected)}`);
|
|
498
|
+
if (!this.typeof(inspected.result, 'string')) throw new EvalError(`Received non-string inspect result: ${JSONStringify(inspected)}`);
|
|
499
|
+
if (extraOut) {
|
|
500
|
+
if (wasThrown) extraOut.errored = true;
|
|
501
|
+
if (remoteObj.wasRejectedPromise) extraOut.noPrintError = true;
|
|
502
|
+
}
|
|
503
|
+
if (wasThrown && remoteObj.subtype !== 'error') return $.red + 'Uncaught ' + $.reset + inspected.result.value;
|
|
504
|
+
return inspected.result.value;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
async function loadHistoryData(): Promise<{ path: string, lines: string[] }> {
|
|
509
|
+
if (NO_HISTORY) return { path: '', lines: [] };
|
|
510
|
+
let out: { path: string; lines: string[]; } | null;
|
|
511
|
+
if (process.env.XDG_DATA_HOME && (out = await tryLoadHistory(process.env.XDG_DATA_HOME, 'bun'))) return out;
|
|
512
|
+
else if (process.env.BUN_INSTALL && (out = await tryLoadHistory(process.env.BUN_INSTALL))) return out;
|
|
513
|
+
else {
|
|
514
|
+
debuglog('Trying to load history from fallback location at home directory.');
|
|
515
|
+
const homedir = os.homedir();
|
|
516
|
+
return await tryLoadHistory(homedir) ?? { path: join(homedir, '.bun_repl_history'), lines: [] };
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
async function tryLoadHistory(...dir: string[]) {
|
|
520
|
+
const path = join(...dir, '.bun_repl_history');
|
|
521
|
+
try {
|
|
522
|
+
debuglog(`Trying to load REPL history from ${path}`);
|
|
523
|
+
if (!existsSync(path)) {
|
|
524
|
+
debuglog(`History file not found, creating new one at ${path}`);
|
|
525
|
+
await write(path, '\n');
|
|
526
|
+
// BUG: Bun.file doesn't update the file's status after writing to it
|
|
527
|
+
}
|
|
528
|
+
debuglog(`Loading history file from ${path}`);
|
|
529
|
+
return { path, lines: readFileSync(path, 'utf8').split('\n') };
|
|
530
|
+
} catch (err) {
|
|
531
|
+
debuglog(`Failed to load history file from ${path}\nError will be printed below:`);
|
|
532
|
+
if (IS_DEBUG) console.error(err);
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// This only supports the most basic var/let/const declarations
|
|
538
|
+
const JSVarDeclRegex = /(?<keyword>var|let|const)\s+(?<varname>(?:[$_\p{ID_Start}]|\\u[\da-fA-F]{4})(?:[$\u200C\u200D\p{ID_Continue}]|\\u[\da-fA-F]{4})*)/gu;
|
|
539
|
+
|
|
540
|
+
// Wrap the code in an async function if it contains top level await
|
|
541
|
+
// Make sure to return the result of the last expression
|
|
542
|
+
function tryProcessTopLevelAwait(src: string) {
|
|
543
|
+
const lines = StringPrototypeSplit(src, '\n' as unknown as RegExp);
|
|
544
|
+
if (!StringTrim(lines[lines.length - 1])) ArrayPrototypePop(lines);
|
|
545
|
+
lines[lines.length - 1] = 'return ' + lines[lines.length - 1] + ';})();';
|
|
546
|
+
lines[0] = '(async()=>{' + lines[0];
|
|
547
|
+
let hoisted = '';
|
|
548
|
+
const transformed = StringPrototypeReplaceAll(ArrayPrototypeJoin(lines, '\n'), JSVarDeclRegex, (m, _1, _2, idx, str, groups) => {
|
|
549
|
+
const { keyword, varname } = groups as { keyword: string, varname: string };
|
|
550
|
+
hoisted += `${keyword === 'const' ? 'let' : keyword} ${varname};`;
|
|
551
|
+
return varname;
|
|
552
|
+
});
|
|
553
|
+
return hoisted + transformed;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
async function tryGetPackageVersion() {
|
|
557
|
+
try {
|
|
558
|
+
return 'v' + (await import('../package.json')).default.version;
|
|
559
|
+
} catch {
|
|
560
|
+
return $.dim+$.redBright+'failed to retrieve version'+$.reset;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// Regex used for ANSI escape code splitting
|
|
565
|
+
// Adopted from https://github.com/chalk/ansi-regex/blob/HEAD/index.js
|
|
566
|
+
// License: MIT, authors: @sindresorhus, Qix-, arjunmehta and LitoMore
|
|
567
|
+
// Matches all ansi escape code sequences in a string
|
|
568
|
+
const ansiPattern =
|
|
569
|
+
"[\\u001B\\u009B][[\\]()#;?]*" +
|
|
570
|
+
"(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*" +
|
|
571
|
+
"|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)" +
|
|
572
|
+
"|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))";
|
|
573
|
+
const ansi = new RegExp(ansiPattern, "g");
|
|
574
|
+
/** Remove all VT control characters. Use to estimate displayed string width. */
|
|
575
|
+
function stripVTControlCharacters(str: string) {
|
|
576
|
+
return RegExpPrototypeSymbolReplace(ansi, str, '' as unknown as (substring: string, ...args: any[]) => string);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function rlRefresh(rl: readline.Interface) {
|
|
580
|
+
// @ts-expect-error "internal" function
|
|
581
|
+
rl._refreshLine(); // eslint-disable-line @typescript-eslint/no-unsafe-call
|
|
582
|
+
}
|
|
583
|
+
function rlLineInsert(rl: readline.Interface, insert: string, cutoff = 0) {
|
|
584
|
+
const { line, cursor } = rl;
|
|
585
|
+
const middle = cursor - cutoff;
|
|
586
|
+
const lineStart = StringPrototypeSlice(line, 0, middle < 0 ? 0 : middle);
|
|
587
|
+
const lineEnd = StringPrototypeSlice(line, cursor);
|
|
588
|
+
ReflectSet(rl, 'line', lineStart + insert + lineEnd);
|
|
589
|
+
ReflectSet(rl, 'cursor', cursor + insert.length - (middle < 0 ? 0 : cutoff));
|
|
590
|
+
rlRefresh(rl);
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const isMac = process.platform === 'darwin';
|
|
594
|
+
const metaKey = (key: string) => (isMac ? 'Meta+' : 'Alt+') + key + (isMac ? '' : ' ');
|
|
595
|
+
|
|
596
|
+
export default {
|
|
597
|
+
async start(singleshotCode?: string, printSingleshot = false) {
|
|
598
|
+
try {
|
|
599
|
+
debuglog('Debug mode enabled.');
|
|
600
|
+
if (IS_DEBUG) { // while debuglog by itself is handy for simple strings its important to note JS will still evaluate the arguments
|
|
601
|
+
debuglog(
|
|
602
|
+
`REPL version ${await tryGetPackageVersion()} running on Bun v${Bun.version}+${Bun.revision} (${process.platform} ${process.arch})`
|
|
603
|
+
);
|
|
604
|
+
debuglog(`OS Info: ${os.type()} -- ${os.release()} -- ${os.version()}`);
|
|
605
|
+
}
|
|
606
|
+
// Node port: Bun.serve binds its inspector synchronously; the Node shim's
|
|
607
|
+
// HTTP server binds on the next tick, so wait for it before connecting.
|
|
608
|
+
await inspectorReady();
|
|
609
|
+
const repl = new REPLServer();
|
|
610
|
+
await repl.ready;
|
|
611
|
+
debuglog('REPL server initialized.');
|
|
612
|
+
// TODO: How to make Bun transpiler not dead-code-eliminate lone constants like "5"?
|
|
613
|
+
const transpiler = new SWCTranspiler();
|
|
614
|
+
debuglog('Transpiler initialized.');
|
|
615
|
+
/*new Bun.Transpiler({
|
|
616
|
+
target: 'bun',
|
|
617
|
+
loader: 'ts',
|
|
618
|
+
minifyWhitespace: false,
|
|
619
|
+
trimUnusedImports: false,
|
|
620
|
+
treeShaking: false,
|
|
621
|
+
inline: false,
|
|
622
|
+
jsxOptimizationInline: false,
|
|
623
|
+
});*/
|
|
624
|
+
if (singleshotCode) {
|
|
625
|
+
let code: string = singleshotCode;
|
|
626
|
+
try {
|
|
627
|
+
code = transpiler.preprocess(code);
|
|
628
|
+
code = transpiler.transpile(code);
|
|
629
|
+
code = transpiler.postprocess(code);
|
|
630
|
+
} catch (e) {
|
|
631
|
+
const err = e as Error;
|
|
632
|
+
console.error((err?.message ?? 'Unknown transpiler error.').split('\nCaused by:\n')[0].trim());
|
|
633
|
+
return exit(1);
|
|
634
|
+
}
|
|
635
|
+
let hasTLA = false;
|
|
636
|
+
if (StringPrototypeIncludes(code, 'await')) {
|
|
637
|
+
hasTLA = true;
|
|
638
|
+
code = tryProcessTopLevelAwait(code);
|
|
639
|
+
}
|
|
640
|
+
const extraInfo = { errored: false, noPrintError: false };
|
|
641
|
+
const evaled = await repl.eval(/* ts */`${code}`, hasTLA, extraInfo);
|
|
642
|
+
if (!extraInfo.noPrintError) {
|
|
643
|
+
if (extraInfo.errored) console.error(evaled);
|
|
644
|
+
else if (printSingleshot) console.log(evaled);
|
|
645
|
+
} else if (!extraInfo.errored && printSingleshot) console.log(evaled);
|
|
646
|
+
// Node port: release the inspector WebSocket so the process can exit naturally
|
|
647
|
+
// (Bun exited the process here; the port returns control to the caller instead).
|
|
648
|
+
try { repl.close(); } catch { /* already closed */ }
|
|
649
|
+
return evaled;
|
|
650
|
+
}
|
|
651
|
+
const history = await loadHistoryData();
|
|
652
|
+
let historySize = Number(process.env.BUN_REPL_HISTORY_SIZE ?? 1000);
|
|
653
|
+
if (!Number.isSafeInteger(historySize) || historySize < 1) {
|
|
654
|
+
console.warn(
|
|
655
|
+
`[!] Invalid BUN_REPL_HISTORY_SIZE value "${process.env.BUN_REPL_HISTORY_SIZE!}", must be a safe positive integer!\n` +
|
|
656
|
+
` Using the default value of 1000.`
|
|
657
|
+
);
|
|
658
|
+
historySize = 1000;
|
|
659
|
+
}
|
|
660
|
+
if (NO_HISTORY) debuglog('Skipped history file loading due to --no-history flag.');
|
|
661
|
+
else debuglog(`REPL history data loaded: (${history.lines.length} lines) ${history.path}`);
|
|
662
|
+
const sessionHistoryNoErrors: string[] = [];
|
|
663
|
+
|
|
664
|
+
if (!process.stdin.isTTY) {
|
|
665
|
+
console.error('[!] Failed to start REPL interface! Is the command running in an interactive terminal?');
|
|
666
|
+
return exit(1);
|
|
667
|
+
}
|
|
668
|
+
const rl = readline.createInterface({
|
|
669
|
+
input: process.stdin,
|
|
670
|
+
output: process.stdout,
|
|
671
|
+
terminal: true,
|
|
672
|
+
tabSize: 4,
|
|
673
|
+
prompt: process.env.BUN_REPL_PROMPT ?? '> ',
|
|
674
|
+
historySize: historySize,
|
|
675
|
+
history: history.lines,
|
|
676
|
+
// completions currently cause a panic "FilePoll.register failed: 17"
|
|
677
|
+
//completer(line: string) {
|
|
678
|
+
// const completions = ['hello', 'world'];
|
|
679
|
+
// const hits = completions.filter(c => c.startsWith(line));
|
|
680
|
+
// return [hits.length ? hits : completions, line];
|
|
681
|
+
//}
|
|
682
|
+
});
|
|
683
|
+
debuglog('readline interface created.');
|
|
684
|
+
process.on('exit', () => {
|
|
685
|
+
rl.close();
|
|
686
|
+
});
|
|
687
|
+
console.log(`Welcome to Bun v${Bun.version}\nType ".help" for more information.`);
|
|
688
|
+
console.warn(
|
|
689
|
+
`${$.yellow+$.dim}[!] Please note that the REPL implementation is still experimental!\n` +
|
|
690
|
+
` Don't consider it to be representative of the stability or behavior of Bun overall.${$.reset}`);
|
|
691
|
+
//* Only primordials should be used beyond this point!
|
|
692
|
+
const multiline = { enabled: false, lines: [] as string[] };
|
|
693
|
+
const toggleMultiline = () => {
|
|
694
|
+
multiline.enabled = !multiline.enabled;
|
|
695
|
+
multiline.lines = [];
|
|
696
|
+
if (multiline.enabled) {
|
|
697
|
+
rl.setPrompt(`${$.purple}(m)${$.reset} ` + rl.getPrompt());
|
|
698
|
+
console.log(
|
|
699
|
+
StringPadEnd(
|
|
700
|
+
`\r${$.gray}Multi-line mode enabled. End a line with "${$.whiteBright}.${$.gray}" to send.${$.reset}`,
|
|
701
|
+
rl.line.length + rl.getPrompt().length
|
|
702
|
+
) +
|
|
703
|
+
StringRepeat('\n', [...StringMatchAll(rl.line, '\n' as unknown as RegExp)].length)
|
|
704
|
+
);
|
|
705
|
+
}
|
|
706
|
+
else {
|
|
707
|
+
rl.setPrompt(process.env.BUN_REPL_PROMPT ?? '> ');
|
|
708
|
+
console.log(
|
|
709
|
+
StringPadEnd(`\r${$.gray}Multi-line mode disabled.${$.reset}`, rl.line.length + rl.getPrompt().length) +
|
|
710
|
+
StringRepeat('\n', [...StringMatchAll(rl.line, '\n' as unknown as RegExp)].length)
|
|
711
|
+
);
|
|
712
|
+
}
|
|
713
|
+
rlRefresh(rl);
|
|
714
|
+
};
|
|
715
|
+
process.stdin.on('keypress', (char: string, key: Keypress) => {
|
|
716
|
+
let modifier: number = Modifier.NONE;
|
|
717
|
+
if (key.ctrl) modifier |= Modifier.CTRL;
|
|
718
|
+
if (key.meta) modifier |= Modifier.ALT;
|
|
719
|
+
if (key.shift) modifier |= Modifier.SHIFT;
|
|
720
|
+
|
|
721
|
+
if (modifier === Modifier.NONE) {
|
|
722
|
+
if (key.name === 'tab') {
|
|
723
|
+
// refuse to place the tab in preparation for autocompletion
|
|
724
|
+
return rlLineInsert(rl, '', 1);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
else if (modifier === Modifier.SHIFT) switch (key.name) {
|
|
728
|
+
case 'tab': {
|
|
729
|
+
rlLineInsert(rl, ' ');
|
|
730
|
+
} break;
|
|
731
|
+
default: return;
|
|
732
|
+
}
|
|
733
|
+
else if (modifier === Modifier.ALT) switch (key.name) {
|
|
734
|
+
case 'n': {
|
|
735
|
+
if (!multiline.enabled) rlLineInsert(rl, '\n');
|
|
736
|
+
else {
|
|
737
|
+
const { line, cursor } = rl;
|
|
738
|
+
ReflectSet(rl, 'line', StringPrototypeSlice(line, 0, cursor));
|
|
739
|
+
rlRefresh(rl);
|
|
740
|
+
rl.write('\n');
|
|
741
|
+
ReflectSet(rl, 'line', StringPrototypeSlice(line, cursor));
|
|
742
|
+
rlRefresh(rl);
|
|
743
|
+
}
|
|
744
|
+
} break;
|
|
745
|
+
case 'm': {
|
|
746
|
+
toggleMultiline();
|
|
747
|
+
} break;
|
|
748
|
+
default: return;
|
|
749
|
+
}
|
|
750
|
+
else if (modifier === Modifier.CTRL) switch (key.name) {
|
|
751
|
+
default: return;
|
|
752
|
+
}
|
|
753
|
+
else if (modifier === Modifier.ALT_SHIFT) switch (key.name) {
|
|
754
|
+
// TODO: readline.moveCursor is broken ("TypeError: undefined is not a function")
|
|
755
|
+
case 'up': {
|
|
756
|
+
//readline.moveCursor(process.stdin, 0, -1, () => void 0);
|
|
757
|
+
} break;
|
|
758
|
+
case 'down': {
|
|
759
|
+
//readline.moveCursor(process.stdin, 0, 1, () => void 0);
|
|
760
|
+
} break;
|
|
761
|
+
default: return;
|
|
762
|
+
}
|
|
763
|
+
});
|
|
764
|
+
rl.on('SIGINT', () => {
|
|
765
|
+
if (rl.line.length === 0) rl.close();
|
|
766
|
+
else {
|
|
767
|
+
console.log('');
|
|
768
|
+
ReflectSet(rl, 'line', '');
|
|
769
|
+
rl.prompt();
|
|
770
|
+
}
|
|
771
|
+
});
|
|
772
|
+
rl.on('close', () => {
|
|
773
|
+
if (!NO_HISTORY) write(
|
|
774
|
+
history.path,
|
|
775
|
+
ArrayPrototypeJoin(ArrayPrototypeFilter(history.lines, l => l !== '.exit'), '\n')
|
|
776
|
+
).catch(() => console.warn(`[!] Failed to save REPL history to ${history.path}!`));
|
|
777
|
+
console.log(''); // ensure newline
|
|
778
|
+
exit(0);
|
|
779
|
+
});
|
|
780
|
+
rl.on('history', newHistory => {
|
|
781
|
+
history.lines = newHistory;
|
|
782
|
+
});
|
|
783
|
+
rl.on('line', async (line, { loadingFile = false } = {}) => {
|
|
784
|
+
line = StringTrim(line);
|
|
785
|
+
if (!line) return rl.prompt();
|
|
786
|
+
if (
|
|
787
|
+
!loadingFile && (line[0] === '.' && multiline.lines.length === 0 && !RegExpTest(/\d/, line[1]))
|
|
788
|
+
) {
|
|
789
|
+
const replCmd = StringPrototypeSplit(line, /\s+/g);
|
|
790
|
+
switch (replCmd[0]) {
|
|
791
|
+
case '.help': {
|
|
792
|
+
console.log(
|
|
793
|
+
`Commands & keybinds:\n` +
|
|
794
|
+
` .help Show this help message.\n` +
|
|
795
|
+
` .info Print extra REPL information.\n` +
|
|
796
|
+
` .multiline Toggle multi-line mode. ${$.gray}(${metaKey('M').trim()})${$.reset}\n` +
|
|
797
|
+
` .save Save all successful commands evaluated in this REPL session to a file.\n` +
|
|
798
|
+
` .load Load a file into the REPL session. ${$.yellow}(Experimental)${$.reset}\n` +
|
|
799
|
+
` .clear Clear the screen. ${$.gray}(Ctrl+L)${$.reset}\n` +
|
|
800
|
+
` .exit Exit the REPL. ${$.gray}(Ctrl+C / Ctrl+D)${$.reset}\n` +
|
|
801
|
+
`\n` +
|
|
802
|
+
` ${metaKey('N')} Insert a raw newline at cursor position, works even in single-line mode.\n` +
|
|
803
|
+
` ${$.dim}* In multi-line mode, ${$.noDim+$.gray}Enter${$.reset+$.dim} can only append newline to the end of the input.${$.reset}\n` +
|
|
804
|
+
` ${metaKey('M')} Toggle multi-line mode.\n` +
|
|
805
|
+
` Shift+Tab Insert an indent instead of triggering autocompletions (autocomplete not yet implemented).` +
|
|
806
|
+
(!isMac ? '' : (
|
|
807
|
+
`\n\n${$.dim}[?] MacOS users: The ${$.noDim+$.gray}Meta${$.reset+$.dim} key defaults to ${$.noDim+$.gray}Esc${$.reset+$.dim}, ` +
|
|
808
|
+
`but may also be mapped to ${$.noDim+$.gray}Option${$.reset+$.dim} based on your terminal settings.${$.reset}`
|
|
809
|
+
))
|
|
810
|
+
);
|
|
811
|
+
} break;
|
|
812
|
+
case '.info': {
|
|
813
|
+
console.log(
|
|
814
|
+
`Running on Bun v${Bun.version} ${$.gray}(${Bun.revision})${$.reset}\n` +
|
|
815
|
+
` REPL version: ${await tryGetPackageVersion()}\n` +
|
|
816
|
+
` Color mode: ${Bun.enableANSIColors ? `${$.greenBright}Enabled` : 'Disabled'}${$.reset}\n` +
|
|
817
|
+
` Debug mode: ${IS_DEBUG ? `${$.greenBright}Enabled` : $.dim+'Disabled'}${$.reset}`
|
|
818
|
+
);
|
|
819
|
+
} break;
|
|
820
|
+
case '.multiline': {
|
|
821
|
+
toggleMultiline();
|
|
822
|
+
} break;
|
|
823
|
+
case '.load': {
|
|
824
|
+
const filepath = replCmd[1];
|
|
825
|
+
if (!filepath) {
|
|
826
|
+
console.log(`${$.red}Missing argument, usage: ${$.whiteBright}.load <filepath>${$.reset}`);
|
|
827
|
+
break;
|
|
828
|
+
}
|
|
829
|
+
const resolved = pathresolve(filepath);
|
|
830
|
+
try {
|
|
831
|
+
const contents = readFileSync(resolved, 'utf8');
|
|
832
|
+
console.warn(`${$.yellow+$.dim}[!] Loading files into the REPL is experimental and may not work as expected.${$.reset}`);
|
|
833
|
+
rl.emit('line', contents, { loadingFile: true });
|
|
834
|
+
} catch (e) {
|
|
835
|
+
const err = e as Error;
|
|
836
|
+
console.error(`Failed to load file ${$.cyan}${resolved}${$.red}: ${err.message ?? 'Unknown error'}${$.reset}`);
|
|
837
|
+
if (IS_DEBUG) console.error(err);
|
|
838
|
+
break;
|
|
839
|
+
}
|
|
840
|
+
} break;
|
|
841
|
+
case '.save': {
|
|
842
|
+
const filepath = replCmd[1];
|
|
843
|
+
if (!filepath) {
|
|
844
|
+
console.log(`${$.red}Missing argument, usage: ${$.whiteBright}.save <filepath>${$.reset}`);
|
|
845
|
+
break;
|
|
846
|
+
}
|
|
847
|
+
const resolved = pathresolve(filepath);
|
|
848
|
+
const contents = ArrayPrototypeJoin(sessionHistoryNoErrors, '\n');
|
|
849
|
+
try {
|
|
850
|
+
await write(resolved, contents);
|
|
851
|
+
} catch (e) {
|
|
852
|
+
const err = e as Error;
|
|
853
|
+
console.error(`Failed to save REPL session to ${$.cyan}${resolved}${$.red}: ${err.message ?? 'Unknown error'}${$.reset}`);
|
|
854
|
+
if (IS_DEBUG) console.error(err);
|
|
855
|
+
break;
|
|
856
|
+
}
|
|
857
|
+
console.log(`Saved REPL session to: ${$.cyan}${resolved}${$.reset+$.dim} (${contents.length} chars)${$.reset}`);
|
|
858
|
+
} break;
|
|
859
|
+
case '.clear': {
|
|
860
|
+
console.clear();
|
|
861
|
+
} break;
|
|
862
|
+
case '.exit': {
|
|
863
|
+
rl.close();
|
|
864
|
+
} break;
|
|
865
|
+
default: {
|
|
866
|
+
console.log(
|
|
867
|
+
`${$.red}Unknown REPL command "${$.whiteBright}${line}${$.red}", ` +
|
|
868
|
+
`type "${$.whiteBright}.help${$.red}" for more information.${$.reset}`
|
|
869
|
+
);
|
|
870
|
+
} break;
|
|
871
|
+
}
|
|
872
|
+
} else {
|
|
873
|
+
if (multiline.enabled && !loadingFile) {
|
|
874
|
+
if (line[line.length - 1] === '.') {
|
|
875
|
+
ArrayPush(multiline.lines, StringPrototypeSlice(line, 0, -1));
|
|
876
|
+
line = ArrayPrototypeJoin(multiline.lines, '\n');
|
|
877
|
+
multiline.lines = [];
|
|
878
|
+
rl.setPrompt(`${$.purple}(m)${$.reset} ` + (process.env.BUN_REPL_PROMPT ?? '> '));
|
|
879
|
+
//rlRefresh(rl);
|
|
880
|
+
} else {
|
|
881
|
+
ArrayPush(multiline.lines, line);
|
|
882
|
+
const promptLineNo = `${$.dim}${multiline.lines.length + 1} | ${$.reset}`;
|
|
883
|
+
const stripped = stripVTControlCharacters(promptLineNo);
|
|
884
|
+
const padded = StringPadStart(stripped, stripVTControlCharacters(rl.getPrompt()).length);
|
|
885
|
+
rl.setPrompt(StringRepeat(' ', padded.length - stripped.length) + promptLineNo);
|
|
886
|
+
rlRefresh(rl);
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
const backupPrompt = rl.getPrompt();
|
|
891
|
+
if (loadingFile) rl.setPrompt('');
|
|
892
|
+
let code: string = line;
|
|
893
|
+
try {
|
|
894
|
+
if (RegExpTest(/^\s*{/, code) && !RegExpTest(/;\s*$/, code)) code = `(${code})`;
|
|
895
|
+
code = transpiler.preprocess(code);
|
|
896
|
+
code = transpiler.transpile(code);
|
|
897
|
+
code = transpiler.postprocess(code);
|
|
898
|
+
} catch (e) {
|
|
899
|
+
const err = e as Error;
|
|
900
|
+
if (err.stack?.includes('@swc/core') || err.stack?.includes('@ohos-ports/swc-core')) {
|
|
901
|
+
console.error(
|
|
902
|
+
'Internal failure due to global builtins tampering, this is likely not a bug but a temporary limitation of the REPL.\n' +
|
|
903
|
+
'Please do not report this and avoid tampering with the global builtins in the REPL.\n' +
|
|
904
|
+
'If you didn\'t tamper with the global builtins, please report this as a bug.'
|
|
905
|
+
);
|
|
906
|
+
if (IS_DEBUG) console.error(e);
|
|
907
|
+
exit(0);
|
|
908
|
+
}
|
|
909
|
+
console.error(
|
|
910
|
+
StringTrim(StringPrototypeSplit(
|
|
911
|
+
err?.message ?? 'Unknown transpiler error.', '\nCaused by:\n' as unknown as RegExp
|
|
912
|
+
)[0])
|
|
913
|
+
);
|
|
914
|
+
if (IS_DEBUG) console.error(e);
|
|
915
|
+
rl.prompt();
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
let hasTLA = false;
|
|
919
|
+
if (StringPrototypeIncludes(code, 'await')) {
|
|
920
|
+
hasTLA = true;
|
|
921
|
+
code = tryProcessTopLevelAwait(code);
|
|
922
|
+
}
|
|
923
|
+
const extraInfo = { errored: false, noPrintError: false };
|
|
924
|
+
const evaled = await repl.eval(/* ts */`${code}`, hasTLA, extraInfo);
|
|
925
|
+
if (!extraInfo.noPrintError) {
|
|
926
|
+
if (extraInfo.errored) console.error(evaled);
|
|
927
|
+
else {
|
|
928
|
+
console.log(evaled);
|
|
929
|
+
ArrayPush(sessionHistoryNoErrors, line);
|
|
930
|
+
}
|
|
931
|
+
} else if (!extraInfo.errored) {
|
|
932
|
+
console.log(evaled);
|
|
933
|
+
ArrayPush(sessionHistoryNoErrors, line);
|
|
934
|
+
}
|
|
935
|
+
if (loadingFile) rl.setPrompt(backupPrompt);
|
|
936
|
+
}
|
|
937
|
+
rl.prompt();
|
|
938
|
+
});
|
|
939
|
+
debuglog('readline interface event handlers registered.');
|
|
940
|
+
rl.prompt();
|
|
941
|
+
} catch (err) {
|
|
942
|
+
console.error('Internal REPL Error:');
|
|
943
|
+
console.error(err, '\nThis should not happen! Search GitHub issues https://bun.sh/issues or ask for #help in https://bun.sh/discord');
|
|
944
|
+
exit(1);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
};
|