bakit 2.0.0-alpha.22 → 2.0.0-alpha.24

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/dist/cli.js CHANGED
@@ -1,14 +1,15 @@
1
1
  import { config } from 'dotenv';
2
2
  import { program } from 'commander';
3
3
  import { fork } from 'child_process';
4
+ import path, { resolve, relative, sep } from 'path';
4
5
  import chokidar from 'chokidar';
5
- import path, { relative, sep } from 'path';
6
- import { pathToFileURL } from 'url';
7
6
 
8
7
  // src/cli/bin.ts
9
8
  function getTopLevelDirectory(path2, entryDir) {
10
9
  return relative(entryDir, path2).split(sep)[0] ?? null;
11
10
  }
11
+
12
+ // src/cli/process/DevProcessManager.ts
12
13
  var DevProcessManager = class {
13
14
  constructor(options) {
14
15
  this.options = options;
@@ -22,7 +23,7 @@ var DevProcessManager = class {
22
23
  if (this.child) return;
23
24
  let entry = path.resolve(this.options.entry);
24
25
  this.child = fork(entry, {
25
- execArgv: ["--import", "bakit/loader/register"],
26
+ execArgv: ["--import", "bakit/register"],
26
27
  stdio: "inherit",
27
28
  env: {
28
29
  ...process.env,
@@ -57,7 +58,7 @@ var DevProcessManager = class {
57
58
  return;
58
59
  let top = getTopLevelDirectory(path2, this.options.rootDir);
59
60
  if (top && this.options.hotDirs.includes(top)) {
60
- this.child.connected && this.child.send({ type: `hmr:${top}`, url: pathToFileURL(path2).href });
61
+ this.child.connected && this.child.send({ type: `hmr:${top}`, path: resolve(path2) });
61
62
  return;
62
63
  }
63
64
  this.scheduleRestart();
@@ -4,10 +4,13 @@ import { Module } from 'module';
4
4
  import { dirname, resolve as resolve$1, basename } from 'path';
5
5
  import { fileURLToPath, pathToFileURL } from 'url';
6
6
 
7
- // src/loader/hooks.ts
8
- var EXTENSIONS = [".js", ".ts"], inDev = false, parentPort, versions, esbuild;
7
+ // src/lib/loader/hooks.ts
8
+ var EXTENSIONS = [".js", ".ts"], parentPort, versions, esbuild;
9
+ function isDevelopment() {
10
+ return process.env.NODE_ENV === "development";
11
+ }
9
12
  async function initialize({ port }) {
10
- inDev = process.env.NODE_ENV === "development", inDev && (parentPort = port, parentPort.on("message", onMessage), versions = /* @__PURE__ */ new Map(), esbuild = await import('esbuild'));
13
+ isDevelopment() && (parentPort = port, parentPort.on("message", onMessage), versions = /* @__PURE__ */ new Map(), esbuild = await import('esbuild'));
11
14
  }
12
15
  async function resolve(specifier, context, nextResolve) {
13
16
  if (shouldSkip(specifier))
@@ -22,7 +25,7 @@ async function resolve(specifier, context, nextResolve) {
22
25
  url = pathToFileURL(absPath).href;
23
26
  }
24
27
  let urlObj = new URL(url);
25
- if (inDev) {
28
+ if (isDevelopment()) {
26
29
  let filePath = fileURLToPath(urlObj), version = createVersion(filePath);
27
30
  urlObj.searchParams.set("hmr", version), parentURL && parentPort && parentPort.postMessage({
28
31
  type: "dependency",
@@ -39,19 +42,22 @@ async function resolve(specifier, context, nextResolve) {
39
42
  async function load(url, context, nextLoad) {
40
43
  if (shouldSkip(url))
41
44
  return nextLoad(url, context);
42
- let cleanURL = url.split("?")[0], filePath = fileURLToPath(cleanURL ?? "");
43
- if (filePath.endsWith(".ts") && esbuild) {
44
- let raw = await readFile(filePath, "utf8");
45
- return {
46
- source: (await esbuild.transform(raw, {
47
- platform: "node",
48
- sourcefile: filePath,
49
- sourcemap: "inline",
50
- loader: "ts"
51
- })).code,
52
- format: "module",
53
- shortCircuit: true
54
- };
45
+ try {
46
+ let cleanURL = url.split("?")[0], filePath = fileURLToPath(cleanURL ?? "");
47
+ if (filePath.endsWith(".ts") && esbuild) {
48
+ let raw = await readFile(filePath, "utf8");
49
+ return {
50
+ source: (await esbuild.transform(raw, {
51
+ platform: "node",
52
+ sourcefile: filePath,
53
+ sourcemap: "inline",
54
+ loader: "ts"
55
+ })).code,
56
+ format: "module",
57
+ shortCircuit: !0
58
+ };
59
+ }
60
+ } catch {
55
61
  }
56
62
  return nextLoad(url, context);
57
63
  }
@@ -69,7 +75,18 @@ function shouldSkip(specifier) {
69
75
  return true;
70
76
  }
71
77
  function onMessage(message) {
72
- message.type === "unload" && versions?.delete(fileURLToPath(message.target));
78
+ let { type, data, id } = message;
79
+ if (type !== "unload") {
80
+ parentPort?.postMessage({
81
+ id,
82
+ data: false
83
+ });
84
+ return;
85
+ }
86
+ versions?.delete(data), parentPort?.postMessage({
87
+ id,
88
+ data: true
89
+ });
73
90
  }
74
91
 
75
92
  export { initialize, load, resolve };
package/dist/index.d.ts CHANGED
@@ -449,6 +449,21 @@ declare function extractSnowflakeId(input: string): string | null;
449
449
 
450
450
  declare function getTopLevelDirectory(path: string, entryDir: string): string | null;
451
451
 
452
+ interface PostMessage<Data> {
453
+ id: number;
454
+ type: string;
455
+ data: Data;
456
+ }
457
+ interface ResponseMessage<Data> {
458
+ id: number;
459
+ error?: string;
460
+ data?: Data;
461
+ }
462
+ declare function $initLoader(): void;
463
+ declare function $postLoaderMessage<Data>(type: string, data: Data, wait?: false): void;
464
+ declare function $postLoaderMessage<Data, Output = unknown>(type: string, data: Data, wait: true): Promise<Output>;
465
+ declare function $unloadFile(path: string): Promise<boolean>;
466
+
452
467
  declare const messageCommandHandler: Listener<Events.MessageCreate>;
453
468
  declare const chatInputCommandHandler: Listener<Events.InteractionCreate>;
454
469
  declare const registerCommandsHandler: Listener<Events.ClientReady>;
@@ -479,4 +494,4 @@ declare function loadConfig(cwd?: string): Promise<ProjectConfig>;
479
494
  */
480
495
  declare function getConfig(): ProjectConfig;
481
496
 
482
- export { type AnyParam, ArgumentError, BakitClient, type BakitClientEvents, BakitError, BaseClientManager, BaseCommandContext, BaseParam, type BaseParamOptions, BaseParamSchema, ChatInputContext, type ChatInputContextSendOptions, Command, type CommandContext, CommandManager, type CommandOptions, type CommandOptionsInput, CommandOptionsSchema, Context, type ContextSendOptions, EVENT_INTENT_MAPPING, type ErrorHookCallback, type GetPrefixFunction, HookOrder, HookState, type InferParamTuple, type InferParamValue, Instance, LifecycleManager, Listener, ListenerManager, type ListenerOptions, ListenerOptionsSchema, type MainHookCallback, MessageContext, type MessageContextSendOptions, type NumberOptions, NumberParam, NumberParamSchema, type ParamResolvedOutputType, ParamUserType, Params, ProjectCacheManager, type ProjectConfig, type ProjectConfigInput, ProjectConfigSchema, type StringOptions, StringParam, StringParamSchema, type UserOptions, UserParam, UserParamSchema, chatInputCommandHandler, defineCommand, defineConfig, defineListener, extractSnowflakeId, getConfig, getTopLevelDirectory, loadConfig, messageCommandHandler, registerCommandsHandler, tokenize, useApp, validateParamsOrder };
497
+ export { $initLoader, $postLoaderMessage, $unloadFile, type AnyParam, ArgumentError, BakitClient, type BakitClientEvents, BakitError, BaseClientManager, BaseCommandContext, BaseParam, type BaseParamOptions, BaseParamSchema, ChatInputContext, type ChatInputContextSendOptions, Command, type CommandContext, CommandManager, type CommandOptions, type CommandOptionsInput, CommandOptionsSchema, Context, type ContextSendOptions, EVENT_INTENT_MAPPING, type ErrorHookCallback, type GetPrefixFunction, HookOrder, HookState, type InferParamTuple, type InferParamValue, Instance, LifecycleManager, Listener, ListenerManager, type ListenerOptions, ListenerOptionsSchema, type MainHookCallback, MessageContext, type MessageContextSendOptions, type NumberOptions, NumberParam, NumberParamSchema, type ParamResolvedOutputType, ParamUserType, Params, type PostMessage, ProjectCacheManager, type ProjectConfig, type ProjectConfigInput, ProjectConfigSchema, type ResponseMessage, type StringOptions, StringParam, StringParamSchema, type UserOptions, UserParam, UserParamSchema, chatInputCommandHandler, defineCommand, defineConfig, defineListener, extractSnowflakeId, getConfig, getTopLevelDirectory, loadConfig, messageCommandHandler, registerCommandsHandler, tokenize, useApp, validateParamsOrder };
package/dist/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { GatewayIntentBits, Events, Client, Collection, IntentsBitField, SlashCommandBuilder, SlashCommandStringOption, SlashCommandNumberOption, SlashCommandUserOption, ChatInputCommandInteraction, Message } from 'discord.js';
2
2
  import { inspect } from 'util';
3
- import { posix, relative, sep, join, dirname } from 'path';
3
+ import { posix, resolve, relative, sep, join, dirname } from 'path';
4
4
  import glob from 'tiny-glob';
5
5
  import z4 from 'zod';
6
+ import { register } from 'module';
7
+ import { MessageChannel } from 'worker_threads';
6
8
  import { pathToFileURL } from 'url';
7
9
  import { existsSync, mkdirSync, rmSync } from 'fs';
8
10
  import { mkdir, writeFile, readFile, rm } from 'fs/promises';
@@ -162,6 +164,35 @@ function extractSnowflakeId(input) {
162
164
  function getTopLevelDirectory(path, entryDir) {
163
165
  return relative(entryDir, path).split(sep)[0] ?? null;
164
166
  }
167
+ var port1, port2, messageId = 0, pending = /* @__PURE__ */ new Map();
168
+ function $initLoader() {
169
+ let channel = new MessageChannel();
170
+ port1 = channel.port1, port2 = channel.port2;
171
+ let hookPath = new URL("./hooks.js", import.meta.url).href;
172
+ register(hookPath, import.meta.url, {
173
+ data: { port: port1 },
174
+ transferList: [port1]
175
+ }), port2.on("message", onMessage), port2.unref();
176
+ }
177
+ function onMessage(message) {
178
+ let { id, error, data } = message, request = pending.get(id);
179
+ request && (pending.delete(id), error ? request.reject(new Error(error)) : request.resolve(data));
180
+ }
181
+ function $postLoaderMessage(type, data, wait = false) {
182
+ let id = messageId++, message = { id, type, data };
183
+ if (!wait) {
184
+ port2?.postMessage(message);
185
+ return;
186
+ }
187
+ return new Promise((resolve4, reject) => {
188
+ if (!port2)
189
+ return reject(new Error("Loader is not initialized"));
190
+ pending.set(id, { resolve: resolve4, reject }), port2.postMessage(message);
191
+ });
192
+ }
193
+ function $unloadFile(path) {
194
+ return $postLoaderMessage("unload", resolve(path), true);
195
+ }
165
196
 
166
197
  // src/core/structures/param/Param.ts
167
198
  var BaseParam = class {
@@ -457,6 +488,7 @@ var CommandManager = class extends BaseClientManager {
457
488
  * @returns The command object if added successfully.
458
489
  */
459
490
  async load(path) {
491
+ path = resolve(path);
460
492
  let command = (await import(pathToFileURL(path).href)).default;
461
493
  if (!command) {
462
494
  console.warn(`[Loader] File has no default export: ${path}`);
@@ -474,12 +506,13 @@ var CommandManager = class extends BaseClientManager {
474
506
  * @returns The command object if unloaded successfully.
475
507
  */
476
508
  async unload(path) {
509
+ path = resolve(path);
477
510
  let command = this.entries.get(path);
478
- if (this.entries.delete(path), (await import('bakit/loader/register')).unload(path), !!command)
511
+ if (this.entries.delete(path), await $unloadFile(path), !!command)
479
512
  return this.remove(command);
480
513
  }
481
514
  async reload(path) {
482
- await this.unload(path);
515
+ path = resolve(path), await this.unload(path);
483
516
  let command = await this.load(path);
484
517
  if (command)
485
518
  return console.log(`[Loader] Reloaded command '${command.options.name}' at '${path}'`), command;
@@ -554,6 +587,7 @@ var ListenerManager = class extends BaseClientManager {
554
587
  * @returns The listener object if added successfully.
555
588
  */
556
589
  async load(path) {
590
+ path = resolve(path);
557
591
  let listener = (await import(pathToFileURL(path).href)).default;
558
592
  if (!listener) {
559
593
  console.warn(`[Loader] File has no default export: ${path}`);
@@ -571,12 +605,13 @@ var ListenerManager = class extends BaseClientManager {
571
605
  * @returns The listener object if unloaded successfully.
572
606
  */
573
607
  async unload(path) {
608
+ path = resolve(path);
574
609
  let listener = this.entries.get(path);
575
- if (this.entries.delete(path), (await import('bakit/loader/register')).unload(path), !!listener)
610
+ if (this.entries.delete(path), await $unloadFile(path), !!listener)
576
611
  return this.remove(listener)?.[0];
577
612
  }
578
613
  async reload(path) {
579
- await this.unload(path);
614
+ path = resolve(path), await this.unload(path);
580
615
  let listener = await this.load(path);
581
616
  if (listener)
582
617
  return console.log(`[Loader] Reloaded listener '${listener.options.name}' at '${path}'`), listener;
@@ -903,16 +938,16 @@ var Instance = class {
903
938
  }
904
939
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
905
940
  async onProcessMessage(message) {
906
- let { type, url } = message;
941
+ let { type, path } = message;
907
942
  if (!type.startsWith("hmr:"))
908
943
  return;
909
944
  let target = type.split(":")[1], { listeners, commands } = this.client.managers;
910
945
  switch (target) {
911
946
  case "listeners":
912
- await listeners.reload(url);
947
+ await listeners.reload(path);
913
948
  break;
914
949
  case "commands":
915
- await commands.reload(url);
950
+ await commands.reload(path);
916
951
  break;
917
952
  }
918
953
  }
@@ -931,4 +966,4 @@ var Params = {
931
966
  user: createFactory(UserParam)
932
967
  };
933
968
 
934
- export { ArgumentError, BakitClient, BakitError, BaseClientManager, BaseCommandContext, BaseParam, BaseParamSchema, ChatInputContext, Command, CommandManager, CommandOptionsSchema, Context, EVENT_INTENT_MAPPING, HookOrder, HookState, Instance, LifecycleManager, Listener, ListenerManager, ListenerOptionsSchema, MessageContext, NumberParam, NumberParamSchema, ParamUserType, Params, ProjectCacheManager, ProjectConfigSchema, StringParam, StringParamSchema, UserParam, UserParamSchema, chatInputCommandHandler, defineCommand, defineConfig, defineListener, extractSnowflakeId, getConfig, getTopLevelDirectory, loadConfig, messageCommandHandler, registerCommandsHandler, tokenize, useApp, validateParamsOrder };
969
+ export { $initLoader, $postLoaderMessage, $unloadFile, ArgumentError, BakitClient, BakitError, BaseClientManager, BaseCommandContext, BaseParam, BaseParamSchema, ChatInputContext, Command, CommandManager, CommandOptionsSchema, Context, EVENT_INTENT_MAPPING, HookOrder, HookState, Instance, LifecycleManager, Listener, ListenerManager, ListenerOptionsSchema, MessageContext, NumberParam, NumberParamSchema, ParamUserType, Params, ProjectCacheManager, ProjectConfigSchema, StringParam, StringParamSchema, UserParam, UserParamSchema, chatInputCommandHandler, defineCommand, defineConfig, defineListener, extractSnowflakeId, getConfig, getTopLevelDirectory, loadConfig, messageCommandHandler, registerCommandsHandler, tokenize, useApp, validateParamsOrder };
@@ -0,0 +1,4 @@
1
+ import { $initLoader } from 'bakit';
2
+
3
+ // src/lib/loader/register.ts
4
+ $initLoader();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bakit",
3
- "version": "2.0.0-alpha.22",
3
+ "version": "2.0.0-alpha.24",
4
4
  "description": "A framework for discord.js",
5
5
  "type": "module",
6
6
  "exports": {
@@ -8,7 +8,7 @@
8
8
  "import": "./dist/index.js",
9
9
  "types": "./dist/index.d.ts"
10
10
  },
11
- "./loader/*": "./dist/loader/*.js"
11
+ "./register": "./dist/register.js"
12
12
  },
13
13
  "scripts": {
14
14
  "build": "tsup",
@@ -1,14 +0,0 @@
1
- import { register } from 'module';
2
- import { MessageChannel } from 'worker_threads';
3
-
4
- // src/loader/register.ts
5
- var { port1, port2 } = new MessageChannel(), hookPath = new URL("./hooks.js", import.meta.url).href;
6
- register(hookPath, import.meta.url, {
7
- data: { port: port1 },
8
- transferList: [port1]
9
- });
10
- function unload(module) {
11
- port2.postMessage({ type: "unload", target: module });
12
- }
13
-
14
- export { unload };