Skip to content

Commit a5ef636

Browse files
committed
fix: polyfill require function
1 parent 544a68a commit a5ef636

File tree

4 files changed

+41
-11
lines changed

4 files changed

+41
-11
lines changed

packages/commandkit/bin/build.mjs

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// @ts-check
22

3-
import { appendFile } from 'node:fs/promises';
3+
import { readFile, writeFile } from 'node:fs/promises';
44
import { join } from 'node:path';
55
import { build } from 'tsup';
66
import { Colors, erase, findCommandKitConfig, panic, write } from './common.mjs';
@@ -14,6 +14,7 @@ export async function bootstrapProductionBuild(config) {
1414
antiCrash = true,
1515
src,
1616
main,
17+
requirePolyfill: polyfillRequire,
1718
} = await findCommandKitConfig(config);
1819

1920
const status = ora('Creating optimized production build...\n').start();
@@ -39,7 +40,7 @@ export async function bootstrapProductionBuild(config) {
3940
entry: [src, '!dist', '!.commandkit', `!${outDir}`],
4041
});
4142

42-
await injectShims(outDir, main, antiCrash);
43+
await injectShims(outDir, main, antiCrash, polyfillRequire);
4344

4445
status.succeed(
4546
Colors.green(`Build completed in ${(performance.now() - start).toFixed(2)}ms!`),
@@ -55,14 +56,33 @@ export async function bootstrapProductionBuild(config) {
5556
}
5657
}
5758

58-
async function injectShims(outDir, main, antiCrash) {
59+
export async function injectShims(outDir, main, antiCrash, polyfillRequire) {
5960
const path = join(process.cwd(), outDir, main);
6061

62+
const head = ['\n\n;await (async()=>{', " 'use strict';"].join('\n');
63+
const tail = '\n})();';
64+
const requireScript = polyfillRequire
65+
? [
66+
'// --- CommandKit require() polyfill ---',
67+
' if (typeof require === "undefined") {',
68+
' const { createRequire } = await import("node:module");',
69+
' const __require = createRequire(import.meta.url);',
70+
' Object.defineProperty(globalThis, "require", {',
71+
' value: (id) => {',
72+
' return __require(id);',
73+
' },',
74+
' configurable: true,',
75+
' enumerable: false,',
76+
' writable: true,',
77+
' });',
78+
' }',
79+
'// --- CommandKit require() polyfill ---',
80+
].join('\n')
81+
: '';
82+
6183
const antiCrashScript = antiCrash
6284
? [
63-
'\n\n// --- CommandKit Anti-Crash Monitor ---',
64-
';(()=>{',
65-
" 'use strict';",
85+
'// --- CommandKit Anti-Crash Monitor ---',
6686
" // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process",
6787
' // instead of using it as a means to resume operation.',
6888
' // But it exists here due to compatibility reasons with discord bot ecosystem.',
@@ -75,12 +95,12 @@ async function injectShims(outDir, main, antiCrash) {
7595
' process.on(e2, (r) => {',
7696
' l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));',
7797
' });',
78-
'})();',
79-
'// --- CommandKit Anti-Crash Monitor ---\n',
98+
'// --- CommandKit Anti-Crash Monitor ---',
8099
].join('\n')
81100
: '';
82101

83-
const finalScript = [antiCrashScript].join('\n');
102+
const contents = await readFile(path, 'utf-8');
103+
const finalScript = [head, requireScript, antiCrashScript, tail, '\n\n', contents].join('\n');
84104

85-
return appendFile(path, finalScript);
105+
return writeFile(path, finalScript);
86106
}

packages/commandkit/bin/development.mjs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { Colors, erase, findCommandKitConfig, panic, write } from './common.mjs'
66
import { parseEnv } from './parse-env.mjs';
77
import child_process from 'node:child_process';
88
import ora from 'ora';
9+
import { injectShims } from './build.mjs';
910

1011
const RESTARTING_MSG_PATTERN = /^Restarting '|".+'|"\n?$/;
1112
const FAILED_RUNNING_PATTERN = /^Failed running '.+'|"\n?$/;
@@ -19,6 +20,7 @@ export async function bootstrapDevelopmentServer(opts) {
1920
envExtra = true,
2021
clearRestartLogs = true,
2122
outDir,
23+
requirePolyfill,
2224
} = await findCommandKitConfig(opts.config);
2325

2426
if (!src) {
@@ -61,6 +63,8 @@ export async function bootstrapDevelopmentServer(opts) {
6163
watch: watchMode,
6264
});
6365

66+
await injectShims('.commandkit', main, false, requirePolyfill);
67+
6468
status.succeed(
6569
Colors.green(`Dev server started in ${(performance.now() - start).toFixed(2)}ms!\n`),
6670
);

packages/commandkit/src/config.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@ export interface CommandKitConfig {
3939
* Whether or not to include anti-crash handler in production. Defaults to `true`.
4040
*/
4141
antiCrash: boolean;
42+
/**
43+
* Whether or not to polyfill `require` function. Defaults to `true`.
44+
*/
45+
requirePolyfill: boolean;
4246
}
4347

4448
let globalConfig: Partial<CommandKitConfig> = {
@@ -50,6 +54,7 @@ let globalConfig: Partial<CommandKitConfig> = {
5054
sourcemap: false,
5155
nodeOptions: [],
5256
antiCrash: true,
57+
requirePolyfill: true,
5358
};
5459

5560
export function getConfig(): CommandKitConfig {

packages/commandkit/tests/src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { CommandKit } from '../../src/index';
22
import { Client } from 'discord.js';
3-
import 'dotenv/config';
3+
4+
require('dotenv/config');
45

56
const client = new Client({
67
intents: ['Guilds', 'GuildMembers', 'GuildMessages', 'MessageContent'],

0 commit comments

Comments
 (0)