@h3ravel/shared 0.27.7 → 0.28.0

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/index.js CHANGED
@@ -1,94 +1,279 @@
1
+ import chalk from "chalk";
1
2
  import { access } from "fs/promises";
2
3
  import escalade from "escalade/sync";
4
+ import { existsSync } from "fs";
3
5
  import path from "path";
4
- import chalk from "chalk";
5
6
  import autocomplete from "inquirer-autocomplete-standalone";
6
7
  import { confirm, input, password, select } from "@inquirer/prompts";
7
8
  import crypto from "crypto";
8
9
  import preferredPM from "preferred-pm";
9
10
 
10
- //#region src/Utils/EnvParser.ts
11
- var EnvParser = class {
12
- static parse(initial) {
13
- const parsed = { ...initial };
14
- for (const key in parsed) {
15
- const value = parsed[key];
16
- parsed[key] = this.parseValue(value);
11
+ //#region src/Container.ts
12
+ const INTERNAL_METHODS = Symbol("internal_methods");
13
+
14
+ //#endregion
15
+ //#region src/Mixins/MixinSystem.ts
16
+ /**
17
+ * Helper to mix multiple classes into one, this allows extending multiple classes by any single class
18
+ *
19
+ * @param bases
20
+ * @returns
21
+ */
22
+ const mix = (...bases) => {
23
+ class Base {
24
+ constructor(...args) {
25
+ let instance = this;
26
+ for (const constructor of bases) {
27
+ const result = Reflect.construct(constructor, args, new.target);
28
+ if (result && (typeof result === "object" || typeof result === "function")) {
29
+ if (result !== instance) {
30
+ Object.assign(result, instance);
31
+ instance = result;
32
+ }
33
+ }
34
+ }
35
+ return instance;
17
36
  }
18
- return parsed;
19
37
  }
20
- static parseValue(value) {
21
- /**
22
- * Null/undefined stay untouched
23
- */
24
- if (value === null || value === void 0) return value;
25
- /**
26
- * Convert string "true"/"false" to boolean
27
- */
28
- if (value === "true") return true;
29
- if (value === "false") return false;
30
- /**
31
- * Convert string numbers to number
32
- */
33
- if (!isNaN(value) && value.trim() !== "") return Number(value);
34
- /**
35
- * Convert string "null" and "undefined"
36
- */
37
- if (value === "null") return null;
38
- if (value === "undefined") return void 0;
39
- /**
40
- * Otherwise return as-is (string)
41
- */
42
- return value;
38
+ for (let i = 0; i < bases.length; i++) {
39
+ const currentBase = bases[i];
40
+ const nextBase = bases[i + 1];
41
+ Object.getOwnPropertyNames(currentBase.prototype).forEach((prop) => {
42
+ if (prop !== "constructor") Object.defineProperty(Base.prototype, prop, Object.getOwnPropertyDescriptor(currentBase.prototype, prop));
43
+ });
44
+ Object.getOwnPropertyNames(currentBase).forEach((prop) => {
45
+ if (![
46
+ "prototype",
47
+ "name",
48
+ "length"
49
+ ].includes(prop)) Object.defineProperty(Base, prop, Object.getOwnPropertyDescriptor(currentBase, prop));
50
+ });
51
+ if (nextBase) {
52
+ Object.setPrototypeOf(currentBase.prototype, nextBase.prototype);
53
+ Object.setPrototypeOf(currentBase, nextBase);
54
+ }
43
55
  }
56
+ Object.setPrototypeOf(Base.prototype, bases[0].prototype);
57
+ Object.setPrototypeOf(Base, bases[0]);
58
+ return Base;
44
59
  };
45
60
 
46
61
  //#endregion
47
- //#region src/Utils/FileSystem.ts
48
- var FileSystem = class {
49
- static findModulePkg(moduleId, cwd) {
50
- const parts = moduleId.replace(/\\/g, "/").split("/");
51
- let packageName = "";
52
- if (parts.length > 0 && parts[0][0] === "@") packageName += parts.shift() + "/";
53
- packageName += parts.shift();
54
- const packageJson = path.join(cwd ?? process.cwd(), "node_modules", packageName);
55
- const resolved = this.resolveFileUp("package", ["json"], packageJson);
56
- if (!resolved) return;
57
- return path.join(path.dirname(resolved), parts.join("/"));
58
- }
59
- /**
60
- * Check if file exists
61
- *
62
- * @param path
63
- * @returns
64
- */
65
- static async fileExists(path$1) {
66
- try {
67
- await access(path$1);
68
- return true;
69
- } catch {
70
- return false;
62
+ //#region src/Mixins/TraitSystem.ts
63
+ const crcTable = [];
64
+ for (let n = 0; n < 256; n++) {
65
+ let c = n;
66
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
67
+ crcTable[n] = c;
68
+ }
69
+ const crc32 = (str) => {
70
+ let crc = -1;
71
+ for (let i = 0; i < str.length; i++) crc = crc >>> 8 ^ crcTable[(crc ^ str.charCodeAt(i)) & 255];
72
+ return (crc ^ -1) >>> 0;
73
+ };
74
+ const isCons = (fn) => typeof fn === "function" && !!fn.prototype && !!fn.prototype.constructor;
75
+ const isTypeFactory = (fn) => typeof fn === "function" && !fn.prototype && fn.length === 0;
76
+ function trait(...args) {
77
+ const factory = args.length === 2 ? args[1] : args[0];
78
+ const superTraits = args.length === 2 ? args[0] : void 0;
79
+ return {
80
+ id: crc32(factory.toString()),
81
+ symbol: Symbol("trait"),
82
+ factory,
83
+ superTraits
84
+ };
85
+ }
86
+ const extendProperties = (cons, field, value) => Object.defineProperty(cons, field, {
87
+ value,
88
+ enumerable: false,
89
+ writable: false
90
+ });
91
+ const rawTrait = (x) => isTypeFactory(x) ? x() : x;
92
+ const deriveTrait = (trait$, baseClz, derived) => {
93
+ const trait$1 = rawTrait(trait$);
94
+ let clz = baseClz;
95
+ if (!derived.has(trait$1.id)) {
96
+ derived.set(trait$1.id, true);
97
+ if (trait$1.superTraits !== void 0) for (const superTrait of reverseTraitList(trait$1.superTraits)) clz = deriveTrait(superTrait, clz, derived);
98
+ clz = trait$1.factory(clz);
99
+ extendProperties(clz, "id", crc32(trait$1.factory.toString()));
100
+ extendProperties(clz, trait$1.symbol, true);
101
+ }
102
+ return clz;
103
+ };
104
+ const reverseTraitList = (traits) => traits.slice().reverse();
105
+ function use(...traits) {
106
+ if (traits.length === 0) throw new Error("invalid number of parameters (expected one or more traits)");
107
+ let clz;
108
+ let lot;
109
+ const last = traits[traits.length - 1];
110
+ if (isCons(last) && !isTypeFactory(last)) {
111
+ clz = last;
112
+ lot = traits.slice(0, -1);
113
+ } else {
114
+ clz = class ROOT {};
115
+ lot = traits;
116
+ }
117
+ const derived = /* @__PURE__ */ new Map();
118
+ for (const trait$1 of reverseTraitList(lot)) clz = deriveTrait(trait$1, clz, derived);
119
+ return clz;
120
+ }
121
+ function uses(instance, trait$1) {
122
+ if (typeof instance !== "object" || instance === null) return false;
123
+ let obj = instance;
124
+ if (isCons(trait$1) && !isTypeFactory(trait$1)) return instance instanceof trait$1;
125
+ const idTrait = (isTypeFactory(trait$1) ? trait$1() : trait$1)["id"];
126
+ while (obj) {
127
+ if (Object.hasOwn(obj, "constructor")) {
128
+ if ((obj.constructor["id"] ?? 0) === idTrait) return true;
71
129
  }
130
+ obj = Object.getPrototypeOf(obj);
72
131
  }
73
- /**
74
- * Recursively find files starting from given cwd
75
- *
76
- * @param name
77
- * @param extensions
78
- * @param cwd
79
- *
80
- * @returns
81
- */
82
- static resolveFileUp(name, extensions, cwd) {
83
- cwd ??= process.cwd();
84
- return escalade(cwd, (dir, filesNames) => {
85
- if (typeof extensions === "function") return extensions(dir, filesNames);
86
- const candidates = new Set(extensions.map((ext) => `${name}.${ext}`));
87
- for (const filename of filesNames) if (candidates.has(filename)) return filename;
88
- return false;
89
- }) ?? void 0;
132
+ return false;
133
+ }
134
+
135
+ //#endregion
136
+ //#region src/Mixins/UseFinalizable.ts
137
+ /**
138
+ * the central class instance registry
139
+ */
140
+ const registry = new FinalizationRegistry((fn) => {
141
+ if (typeof fn === "function" && !fn.finalized) {
142
+ fn.finalized = true;
143
+ fn();
144
+ }
145
+ });
146
+ /**
147
+ * the API trait "Finalizable<T>"
148
+ */
149
+ const Finalizable = trait((base) => class Finalizable$1 extends base {
150
+ constructor(...args) {
151
+ super(...args);
152
+ const fn1 = this.$finalize;
153
+ if (typeof fn1 !== "function") throw new Error("trait Finalizable requires a $finalize method to be defined");
154
+ const fn2 = () => {
155
+ fn1(this);
156
+ };
157
+ fn2.finalized = false;
158
+ registry.register(this, fn2, this);
159
+ }
160
+ });
161
+
162
+ //#endregion
163
+ //#region src/Mixins/UseMagic.ts
164
+ /**
165
+ * Wraps an object in a Proxy to emulate PHP magic methods.
166
+ *
167
+ * Supported:
168
+ * - __call(method, args)
169
+ * - __get(property)
170
+ * - __set(property, value)
171
+ * - __isset(property)
172
+ * - __unset(property)
173
+ *
174
+ * Called automatically by Magic's constructor.
175
+ *
176
+ * Return in any class constructor to use
177
+ *
178
+ * @param target
179
+ * @returns
180
+ */
181
+ function makeMagic(target) {
182
+ return new Proxy(target, {
183
+ get(obj, prop, receiver) {
184
+ if (typeof prop === "string") {
185
+ if (prop in obj) return Reflect.get(obj, prop, receiver);
186
+ if (obj.__call) return (...args) => obj.__call(prop, args);
187
+ if (obj.__get) return obj.__get(prop);
188
+ }
189
+ },
190
+ set(obj, prop, value) {
191
+ if (typeof prop === "string" && obj.__set) {
192
+ obj.__set(prop, value);
193
+ return true;
194
+ }
195
+ return Reflect.set(obj, prop, value);
196
+ },
197
+ has(obj, prop) {
198
+ if (typeof prop === "string" && obj.__isset) return obj.__isset(prop);
199
+ return Reflect.has(obj, prop);
200
+ },
201
+ deleteProperty(obj, prop) {
202
+ if (typeof prop === "string" && obj.__unset) {
203
+ obj.__unset(prop);
204
+ return true;
205
+ }
206
+ return Reflect.deleteProperty(obj, prop);
207
+ }
208
+ });
209
+ }
210
+ /**
211
+ * Wraps a class constructor in a Proxy to emulate static PHP magic methods.
212
+ *
213
+ * Supported:
214
+ * - __callStatic(method, args)
215
+ * - static __get(property)
216
+ * - static __set(property, value)
217
+ * - static __isset(property)
218
+ * - static __unset(property)
219
+ *
220
+ * @param cls
221
+ * @returns
222
+ */
223
+ function makeStaticMagic(cls) {
224
+ return new Proxy(cls, {
225
+ get(target, prop) {
226
+ if (typeof prop === "string") {
227
+ if (prop in target) return target[prop];
228
+ if (target.__callStatic) return (...args) => target.__callStatic(prop, args);
229
+ if (target.__get) return target.__get(prop);
230
+ }
231
+ },
232
+ set(target, prop, value) {
233
+ if (typeof prop === "string" && target.__set) {
234
+ target.__set(prop, value);
235
+ return true;
236
+ }
237
+ return Reflect.set(target, prop, value);
238
+ },
239
+ has(target, prop) {
240
+ if (typeof prop === "string" && target.__isset) return target.__isset(prop);
241
+ return Reflect.has(target, prop);
242
+ },
243
+ deleteProperty(target, prop) {
244
+ if (typeof prop === "string" && target.__unset) {
245
+ target.__unset(prop);
246
+ return true;
247
+ }
248
+ return Reflect.deleteProperty(target, prop);
249
+ }
250
+ });
251
+ }
252
+ /**
253
+ * Base class that enables PHP-style magic methods automatically.
254
+ *
255
+ * Any subclass may implement:
256
+ * - __call
257
+ * - __get
258
+ * - __set
259
+ * - __isset
260
+ * - __unset
261
+ *
262
+ * The constructor returns a Proxy transparently.
263
+ */
264
+ var Magic = class {
265
+ constructor() {
266
+ return makeMagic(this);
90
267
  }
91
268
  };
269
+ const UseMagic = trait((Base) => {
270
+ return class Magic$1 extends Base {
271
+ constructor(...args) {
272
+ super(...args);
273
+ return makeMagic(this);
274
+ }
275
+ };
276
+ });
92
277
 
93
278
  //#endregion
94
279
  //#region src/Utils/Logger.ts
@@ -166,6 +351,17 @@ var Logger = class Logger {
166
351
  * @returns
167
352
  */
168
353
  static textFormat(txt, color, preserveCol = false) {
354
+ if (txt instanceof Error) {
355
+ const err = txt;
356
+ const code = err.code ?? err.statusCode ? ` (${err.code ?? err.statusCode})` : "";
357
+ const output = [];
358
+ if (err.message) output.push(this.textFormat(`${err.constructor.name}${code}: ${err.message}`, chalk.bgRed, preserveCol));
359
+ if (err.stack) output.push(" " + chalk.white(err.stack.replace(`${err.name}: ${err.message}`, "").trim()));
360
+ return output.join("\n");
361
+ }
362
+ if (Array.isArray(txt)) return txt.map((e) => this.textFormat(e, color, preserveCol)).join("\n");
363
+ if (typeof txt === "object") return this.textFormat(Object.values(txt), color, preserveCol);
364
+ if (typeof txt !== "string") return color(txt);
169
365
  const str = String(txt);
170
366
  if (preserveCol) return str;
171
367
  const [first, ...rest] = str.split(":");
@@ -262,9 +458,129 @@ var Logger = class Logger {
262
458
  if (typeof config === "string") {
263
459
  const conf = [[config, joiner]];
264
460
  return this.parse(conf, "", log, sc);
265
- } else if (config) return this.parse(config, String(joiner), log, sc);
461
+ } else if (Array.isArray(config)) return this.parse(config, String(joiner), log, sc);
462
+ else if (log && !this.shouldSuppressOutput("line")) return console.log(this.textFormat(config, Logger.chalker(["blue"])));
266
463
  return this;
267
464
  });
465
+ /**
466
+ * A simple console like output logger
467
+ *
468
+ * @returns
469
+ */
470
+ static console() {
471
+ return Console;
472
+ }
473
+ };
474
+
475
+ //#endregion
476
+ //#region src/Utils/Console.ts
477
+ var Console = class {
478
+ static log = (...args) => Logger.log(args.map((e) => [e, "white"]));
479
+ static debug = (...args) => Logger.debug(args, false, true);
480
+ static warn = (...args) => args.map((e) => Logger.warn(e, false, true));
481
+ static info = (...args) => args.map((e) => Logger.info(e, false, true));
482
+ static error = (...args) => args.map((e) => Logger.error(e, false), true);
483
+ };
484
+
485
+ //#endregion
486
+ //#region src/Utils/EnvParser.ts
487
+ var EnvParser = class {
488
+ static parse(initial) {
489
+ const parsed = { ...initial };
490
+ for (const key in parsed) {
491
+ const value = parsed[key];
492
+ parsed[key] = this.parseValue(value);
493
+ }
494
+ return parsed;
495
+ }
496
+ static parseValue(value) {
497
+ /**
498
+ * Null/undefined stay untouched
499
+ */
500
+ if (value === null || value === void 0) return value;
501
+ /**
502
+ * Convert string "true"/"false" to boolean
503
+ */
504
+ if (value === "true") return true;
505
+ if (value === "false") return false;
506
+ /**
507
+ * Convert string numbers to number
508
+ */
509
+ if (!isNaN(value) && value.trim() !== "") return Number(value);
510
+ /**
511
+ * Convert string "null" and "undefined"
512
+ */
513
+ if (value === "null") return null;
514
+ if (value === "undefined") return void 0;
515
+ /**
516
+ * Otherwise return as-is (string)
517
+ */
518
+ return value;
519
+ }
520
+ };
521
+
522
+ //#endregion
523
+ //#region src/Utils/FileSystem.ts
524
+ var FileSystem = class {
525
+ static findModulePkg(moduleId, cwd) {
526
+ const parts = moduleId.replace(/\\/g, "/").split("/");
527
+ let packageName = "";
528
+ if (parts.length > 0 && parts[0][0] === "@") packageName += parts.shift() + "/";
529
+ packageName += parts.shift();
530
+ const packageJson = path.join(cwd ?? process.cwd(), "node_modules", packageName);
531
+ const resolved = this.resolveFileUp("package", ["json"], packageJson);
532
+ if (!resolved) return;
533
+ return path.join(path.dirname(resolved), parts.join("/"));
534
+ }
535
+ /**
536
+ * Check if file exists
537
+ *
538
+ * @param path
539
+ * @returns
540
+ */
541
+ static async fileExists(path$1) {
542
+ try {
543
+ await access(path$1);
544
+ return true;
545
+ } catch {
546
+ return false;
547
+ }
548
+ }
549
+ /**
550
+ * Recursively find files starting from given cwd
551
+ *
552
+ * @param name
553
+ * @param extensions
554
+ * @param cwd
555
+ *
556
+ * @returns
557
+ */
558
+ static resolveFileUp(name, extensions, cwd) {
559
+ cwd ??= process.cwd();
560
+ return escalade(cwd, (dir, filesNames) => {
561
+ if (typeof extensions === "function") return extensions(dir, filesNames);
562
+ const candidates = new Set(extensions.map((ext) => `${name}.${ext}`));
563
+ for (const filename of filesNames) if (candidates.has(filename)) return filename;
564
+ return false;
565
+ }) ?? void 0;
566
+ }
567
+ /**
568
+ * Recursively find files starting from given cwd
569
+ *
570
+ * @param name
571
+ * @param extensions
572
+ * @param cwd
573
+ *
574
+ * @returns
575
+ */
576
+ static resolveModulePath(moduleId, pathName, cwd) {
577
+ pathName = Array.isArray(pathName) ? pathName : [pathName];
578
+ const module = this.findModulePkg(moduleId, cwd) ?? "";
579
+ for (const name of pathName) {
580
+ const file = path.join(module, name);
581
+ if (existsSync(file)) return file;
582
+ }
583
+ }
268
584
  };
269
585
 
270
586
  //#endregion
@@ -278,7 +594,8 @@ var PathLoader = class {
278
594
  config: "/src/config",
279
595
  public: "/public",
280
596
  storage: "/storage",
281
- database: "/src/database"
597
+ database: "/src/database",
598
+ commands: "/src/App/Console/Commands/"
282
599
  };
283
600
  /**
284
601
  * Dynamically retrieves a path property from the class.
@@ -307,6 +624,11 @@ var PathLoader = class {
307
624
  if (base && name !== "base") this.paths[name] = path.join(base, path$1);
308
625
  this.paths[name] = path$1;
309
626
  }
627
+ distPath(path$1, skipExt = false) {
628
+ path$1 = path$1.replace("/src/", `/${process.env.DIST_DIR ?? "src"}/`.replace(/([^:]\/)\/+/g, "$1"));
629
+ if (!skipExt) path$1 = path$1.replace(/\.(ts|tsx|mts|cts)$/, ".js");
630
+ return path.normalize(path$1);
631
+ }
310
632
  };
311
633
 
312
634
  //#endregion
@@ -426,7 +748,7 @@ const mainTsconfig = {
426
748
  },
427
749
  target: "es2022",
428
750
  module: "es2022",
429
- moduleResolution: "Node",
751
+ moduleResolution: "bundler",
430
752
  esModuleInterop: true,
431
753
  strict: true,
432
754
  allowJs: true,
@@ -496,5 +818,5 @@ var TaskManager = class {
496
818
  };
497
819
 
498
820
  //#endregion
499
- export { EnvParser, FileSystem, Logger, PathLoader, Prompts, Resolver, TaskManager, baseTsconfig, mainTsconfig, packageJsonScript };
821
+ export { Console, EnvParser, FileSystem, Finalizable, INTERNAL_METHODS, Logger, Magic, PathLoader, Prompts, Resolver, TaskManager, UseMagic, baseTsconfig, crc32, mainTsconfig, makeMagic, makeStaticMagic, mix, packageJsonScript, trait, use, uses };
500
822
  //# sourceMappingURL=index.js.map