@briklab/lib 1.1.10 → 1.2.0-test

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.
@@ -1,15 +1,459 @@
1
- var a=function(i,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?i!==t||!n:!t.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(i):n?n.value:t.get(i)},T=function(i,t,e,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?i!==t||!r:!t.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(i,e):r?r.value=e:t.set(i,e),e},u,m,w,v,C,y,_,I;import f from"../jstc/index.js";import b,{StyleSheet as k}from"../stylesheet/index.js";import L from"../color/index.js";import{warner as c}from"../warner/index.js";f.addCustomHandler("NodeJS Process",i=>i&&typeof i=="object"&&typeof i.pid=="number"&&typeof i.cwd=="function"&&typeof i.exit=="function");class p{constructor(t){if(u.add(this),m.set(this,[]),w.set(this,[]),C.set(this,void 0),y.set(this,class extends S{constructor(e){super(e),this.setName="CLI"}}),!f.for([t]).check(["NodeJS Process"]))throw a(this,u,"m",_).call(this,"Invalid First Argument!","You must pass a valid NodeJS process (imported from node:process) while constructing a CLI Class!");T(this,C,t,"f")}command(t){f.for([t]).check(["string"])||(a(this,u,"m",I).call(this,"Invalid First Argument!","CLI.option expects a string as the first argument.","Using String(given argument) as fallback."),t=String(t));let e=new p.Command(t),n=a(this,m,"f").findIndex(r=>r.name===t);return n!==-1?a(this,m,"f")[n]=e:a(this,m,"f").push(e),e}on(t,e){if(!f.for([t,e]).check(["string","function"]))throw a(this,u,"m",_).call(this,"Arguments in CLI.on are invalid!","The first argument must be a string, and the second argument must be a function.");t.toLowerCase()==="command"?a(this,w,"f").push(e):a(this,u,"m",I).call(this,"Invalid event in CLI.on","Please enter a valid event from CLI.ValidEvents (array)")}run(){let{options:t,commandArgs:e,command:n,failed:r}=a(this,u,"m",v).call(this);if(!r){for(let o=0;o<a(this,w,"f").length;o++)a(this,w,"f")[o]({options:t,commandArgs:e,command:n});c.flush()}}}m=new WeakMap,w=new WeakMap,C=new WeakMap,y=new WeakMap,u=new WeakSet,v=function(){let[,,...t]=a(this,C,"f").argv;if(t.length===0)return{options:[],command:"",commandArgs:[],failed:!0};let e=a(this,m,"f").find(s=>s.name===t[0]);if(!e)return{options:[],command:"",commandArgs:[],failed:!0};let n=[];const r=t.slice(1);for(let s=0;s<r.length;s++){let l=r[s];if(l.startsWith("--"))break;n.push(l)}let o=r.slice(n.length),d=[];for(let s=0;s<o.length;s++){const l=o[s];if(!l.startsWith("--"))continue;const h=[];for(let g=s+1;g<o.length&&!o[g].startsWith("--");g++)h.push(o[g]);d.push({option:l,arguments:h})}return{options:d,commandArgs:n,command:e,failed:!1}},_=function(t,e){return new(a(this,y,"f"))(`${t}
2
- Hint: ${e}`)},I=function(t,e,n){c.warn({message:`[Class CLI] ${t}
3
- Hint: ${e}
4
- ${n}`})};class S extends Error{constructor(t){super(t),this.name="[] @briklab/lib/cli-john",Error.captureStackTrace(this,S)}set setName(t){this.name=`[${t}] @briklab/lib/cli-john`}}(function(i){var t,e,n,r;i.ValidEvents=["command"];class o{constructor(s){return t.add(this),e.set(this,void 0),r.set(this,[]),T(this,e,s,"f"),this}get name(){return a(this,e,"f")}get metadata(){return{options:a(this,r,"f").map(l=>l.metadata),name:this.name}}option(s){f.for([s]).check(["string"])||(a(this,t,"m",n).call(this,"First argument is invalid!","The first argument must be a string","Using String(argument) as fallback"),s=String(s));let l=new i.Command.Option(s),h=a(this,r,"f").findIndex(g=>g.name===s);return h!==-1?a(this,r,"f")[h]=l:a(this,r,"f").push(l),l}}e=new WeakMap,r=new WeakMap,t=new WeakSet,n=function(s,l,h){c.warn({message:`[Class CLI.Command] ${s}
5
- Hint: ${l}
6
- ${h}`})},i.Command=o})(p||(p={})),(function(i){var t;(function(e){var n;class r{get metadata(){return{name:`${a(this,n,"f")}`}}constructor(d){return n.set(this,void 0),T(this,n,d,"f"),this}get name(){return a(this,n,"f")}}n=new WeakMap,e.Option=r})(t=i.Command||(i.Command={}))})(p||(p={})),f.addCustomHandler("Utilities Tag Config",i=>i&&typeof i=="object"&&typeof i.tag=="string"&&typeof i.showErrorInTag=="boolean"&&typeof i.paddingLeft=="number"&&typeof i.paddingRight=="number"&&(typeof i.styleName=="string"||i.styleName===void 0));class E{constructor(){this.styleSheet=new k,this.tags={},this.addTag("error",{tag:"ERROR",showErrorInTag:!1,paddingLeft:0,paddingRight:0}),this.addTag("warning",{tag:"WARNING",showErrorInTag:!0,paddingLeft:0,paddingRight:0}),this.addTag("info",{tag:"INFO",showErrorInTag:!0,paddingLeft:0,paddingRight:0}),this.setTagStyle("error",new b({color:"red",fontWeight:"bold"})),this.setTagStyle("warning",new b({color:"orange",fontWeight:"bold"})),this.setTagStyle("info",new b({color:"blue"}))}addTag(t,e={}){f.for([t,e]).check(["string","object"])||(c.warn({message:`[UtilitiesClass.addTag] @briklab/lib/cli-john: Invalid Arguments!
7
- Hint: The first argument must be a string, and the second argument must be a object.
8
- Using String(argument1) and {} as fallback.`}),t=String(t),e={});const n={tag:t.toUpperCase(),showErrorInTag:!1,paddingLeft:0,paddingRight:0,styleName:"",...e};return f.for([n]).check(["Utilities Tag Config"])?(this.tags[t]=n,this):(c.warn({message:`[UtilitiesClass.addTag] @briklab/lib/cli-john: Invalid tag config passed for "${t}"
9
- Hint: The config must be in format {tag?: string, showErrorInTag?:boolean, paddingLeft?:number, paddingRight?:number, styleName?:string}`}),c.warn({message:JSON.stringify(n,null,2)}),this)}setTagStyle(t,e){if((typeof t!="string"||!(e instanceof b))&&(c.warn({message:`[UtilitiesClass.setTagStyle] @briklab/lib/cli-john: Invalid arguments!
10
- Hint: The first argument must be a string and the second argument must be a instance of InlineStyle
11
- Using String(firstArgument) and new InlineStyle({}) as fallback`}),t=String(t),e=new b({})),!this.tags[t])return c.warn({message:`[UtilitiesClass.setTagStyle] @briklab/lib/cli-john: Tag "${t}" does not exist!
12
- Hint: Use a valid tag that you have defined or use "error"|"warn"|"info"`}),this;const n=`${t} Tag Color`;return this.styleSheet.set(n,e),this.tags[t].styleName=n,this}log(t,...e){f.for([t]).check(["string"])||(c.warn({message:`[UtilitiesClass.log] @briklab/lib/cli-john: Invalid Arguments!
13
- Hint: The first argument must be a string
14
- Using String(argument1) as fallback`}),t=String(t)),(!e||e.length===0)&&(e=[""]);const n=this.tags[t];if(!n){c.warn({message:`[UtilitiesClass.log] @briklab/lib/cli-john: Tag "${t}" does not exist!
15
- Hint: Use a valid tag that you have defined or use "error"|"warn"|"info"`}),console.log(...e);return}const r=this.styleSheet.get(n.styleName),o=r?.text??"",d=" ".repeat(n.paddingLeft),s=" ".repeat(n.paddingRight);if(typeof process<"u"&&typeof process.stdout<"u"&&!!process.stdout.isTTY){const h=r?.ansi??"",g=L.RESET;n.showErrorInTag?console.log("["+h+d+n.tag+s+g+"]:",...e):console.log(h+"["+d+n.tag+s+"]"+g+":",...e)}else n.showErrorInTag?console.log(`[%c${d}${n.tag}${s}%c]:`,o,...e):console.log(`%c[${d}${n.tag}${s}]%c:`,o,...e)}error(...t){return(!t||t.length===0)&&(t=[""]),this.log("error",...t),this}warning(...t){return(!t||t.length===0)&&(t=[""]),this.log("warning",...t),this}info(...t){return(!t||t.length===0)&&(t=[""]),this.log("info",...t),this}}const P=new E;export{p as CLI,P as Utilities};
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * # CLI John
5
+ *
6
+ * **CLI John** is a **Node.js CLI framework** designed to create **fully functional CLIs** quickly.
7
+ * It hooks into a given NodeJS process, automatically listens for commands, parses arguments,
8
+ * and allows beautiful console messages. Its design is **modular**, using Commands and Options as sub-classes.
9
+ *
10
+ * ## Features
11
+ * - Auto-listening to commands
12
+ * - Command parsing
13
+ * - Beautiful console messages
14
+ * - One CLI per file
15
+ * - Add your file to `bin` in package.json CLI works seamlessly
16
+ * - Event-driven command handling
17
+ *
18
+ * ## Usage
19
+ * ```ts
20
+ * import { CLI as CLI } from "@briklab/lib/cli-john"
21
+ * import * as process from "node:process"
22
+ *
23
+ * const cli = new CLI(process);
24
+ *
25
+ * const cmd = cli.command("myCommand");
26
+ * const opt = cmd.option("force");
27
+ *
28
+ * cmd.on("run", ({commandArgs}) => {
29
+ * CJ.notice("Hey, this is my CLI!");
30
+ * CJ.message("Do you like it?");
31
+ * CJ.error("Invalid args:", ...commandArgs.map(a => a.name));
32
+ * });
33
+ *
34
+ * cli.run();
35
+ * ```
36
+ *
37
+ * ## Limitations
38
+ * - Only **one CLI per file** is allowed (CLI enforces this)
39
+ * - CLI file must be manually added to `bin` in package.json
40
+ *
41
+ * ## Hierarchy
42
+ * ```
43
+ * CLI
44
+ * ├─ Command
45
+ * │ └─ Option
46
+ * └─ CLIErrors
47
+ * ```
48
+ *
49
+ * ## Error Handling
50
+ * - All errors are instances of `CLIErrors`
51
+ * - Dynamic names allow easy identification of which part of the CLI threw the error
52
+ *
53
+ * @module cli-john
54
+ */
55
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
56
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
57
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
58
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
59
+ };
60
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
61
+ if (kind === "m") throw new TypeError("Private method is not writable");
62
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
63
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
64
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
65
+ };
66
+ var _CLI_instances, _CLI_commands, _CLI_onCmdFunctions, _CLI_figureOutCommand, _CLI_process, _CLI_ErrorClass, _CLI_createErr, _CLI_createWarn;
67
+ // -------------------------------------------------------------------------------------------------------
68
+ //#region Defination of custom JSTC handler
69
+ import JSTC from "../jstc/index.js";
70
+ import InlineStyle, { StyleSheet } from "../stylesheet/index.js";
71
+ import Color from "../color/index.js";
72
+ import { warner } from "../warner/index.js";
73
+ JSTC.addCustomHandler("NodeJS Process", (p) => {
74
+ return (p &&
75
+ typeof p === "object" &&
76
+ typeof p.pid === "number" &&
77
+ typeof p.cwd === "function" &&
78
+ typeof p.exit === "function");
79
+ });
80
+ //#endregion
81
+ // -------------------------------------------------------------------------------------------------------
82
+ //#region The Main Class
83
+ /**
84
+ * # CLI
85
+ * @classdesc The main class for **CLI**.
86
+ * @example
87
+ * import * as process from "node:process"
88
+ * import {CLI} from "@briklab/lib/cli-john"
89
+ * const cli = new CLI(process)
90
+ * cli.run()
91
+ */
92
+ export class CLI {
93
+ /**
94
+ * ## CLI: Constructor
95
+ * @param {NodeJS.Process} process - **The main process**
96
+ * @constructor
97
+ * @constructs CLI
98
+ * @example
99
+ * import * as process from "node:process"
100
+ * import {CLI} from "@briklab/lib/cli-john"
101
+ * const cli = new CLI(process)
102
+ * cli.run()
103
+ */
104
+ constructor(process) {
105
+ _CLI_instances.add(this);
106
+ _CLI_commands.set(this, []);
107
+ _CLI_onCmdFunctions.set(this, []);
108
+ _CLI_process.set(this, void 0);
109
+ _CLI_ErrorClass.set(this, class extends CLIErrors {
110
+ constructor(message) {
111
+ super(message);
112
+ this.setName = "CLI";
113
+ }
114
+ });
115
+ if (!JSTC.for([process]).check(["NodeJS Process"])) {
116
+ throw __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_createErr).call(this, "Invalid First Argument!", "You must pass a valid NodeJS process (imported from node:process) while constructing a CLI Class!");
117
+ }
118
+ __classPrivateFieldSet(this, _CLI_process, process, "f");
119
+ }
120
+ /**
121
+ * ### CLI.command
122
+ * create a new command in a CLI.
123
+ *
124
+ * @param {string} name
125
+ */
126
+ command(name) {
127
+ if (!JSTC.for([name]).check(["string"])) {
128
+ __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_createWarn).call(this, "Invalid First Argument!", "CLI.option expects a string as the first argument.", "Using String(given argument) as fallback.");
129
+ name = String(name);
130
+ }
131
+ let c = new CLI.Command(name);
132
+ let f = __classPrivateFieldGet(this, _CLI_commands, "f").findIndex((a) => a.name === name);
133
+ if (f !== -1)
134
+ __classPrivateFieldGet(this, _CLI_commands, "f")[f] = c;
135
+ else
136
+ __classPrivateFieldGet(this, _CLI_commands, "f").push(c);
137
+ return c;
138
+ }
139
+ on(event, func) {
140
+ if (!JSTC.for([event, func]).check(["string", "function"]))
141
+ throw __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_createErr).call(this, "Arguments in CLI.on are invalid!", "The first argument must be a string, and the second argument must be a function.");
142
+ switch (event.toLowerCase()) {
143
+ case "command":
144
+ __classPrivateFieldGet(this, _CLI_onCmdFunctions, "f").push(func);
145
+ break;
146
+ default:
147
+ __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_createWarn).call(this, "Invalid event in CLI.on", "Please enter a valid event from CLI.ValidEvents (array)");
148
+ }
149
+ }
150
+ run() {
151
+ let { options, commandArgs, command, failed } = __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_figureOutCommand).call(this);
152
+ if (failed)
153
+ return;
154
+ for (let i = 0; i < __classPrivateFieldGet(this, _CLI_onCmdFunctions, "f").length; i++) {
155
+ __classPrivateFieldGet(this, _CLI_onCmdFunctions, "f")[i]({ options, commandArgs, command });
156
+ }
157
+ warner.flush();
158
+ }
159
+ }
160
+ _CLI_commands = new WeakMap(), _CLI_onCmdFunctions = new WeakMap(), _CLI_process = new WeakMap(), _CLI_ErrorClass = new WeakMap(), _CLI_instances = new WeakSet(), _CLI_figureOutCommand = function _CLI_figureOutCommand() {
161
+ // for eg. we have nodepath filepath cli build
162
+ let [, , ...commands] = __classPrivateFieldGet(this, _CLI_process, "f").argv; // now its cli build. clear
163
+ if (commands.length === 0)
164
+ return { options: [], command: "", commandArgs: [], failed: true };
165
+ let command = __classPrivateFieldGet(this, _CLI_commands, "f").find((a) => a.name === commands[0]); // find the command
166
+ if (!command)
167
+ return { options: [], command: "", commandArgs: [], failed: true }; // command not found?
168
+ let commandArgs = [];
169
+ const args = commands.slice(1);
170
+ for (let i = 0; i < args.length; i++) {
171
+ let arg = args[i];
172
+ if (arg.startsWith("--"))
173
+ break;
174
+ commandArgs.push(arg);
175
+ }
176
+ let leftover = args.slice(commandArgs.length); // args = [1,2,3]; command args = [1,2] command args length is 2, therefore .slice(2) results in [3]
177
+ let options = [];
178
+ for (let i = 0; i < leftover.length; i++) {
179
+ const opt = leftover[i];
180
+ if (!opt.startsWith("--"))
181
+ continue;
182
+ const values = [];
183
+ for (let j = i + 1; j < leftover.length; j++) {
184
+ if (leftover[j].startsWith("--"))
185
+ break;
186
+ values.push(leftover[j]);
187
+ }
188
+ options.push({ option: opt, arguments: values });
189
+ }
190
+ return {
191
+ options,
192
+ commandArgs,
193
+ command,
194
+ failed: false,
195
+ };
196
+ }, _CLI_createErr = function _CLI_createErr(message, hint) {
197
+ return new (__classPrivateFieldGet(this, _CLI_ErrorClass, "f"))(`${message}
198
+ Hint: ${hint}`);
199
+ }, _CLI_createWarn = function _CLI_createWarn(message, hint, otherMessage) {
200
+ warner.warn({ message: `[Class CLI] ${message}
201
+ Hint: ${hint}
202
+ ${otherMessage}` });
203
+ return;
204
+ };
205
+ //#endregion
206
+ // -------------------------------------------------------------------------------------------------------
207
+ //#region Error Class
208
+ class CLIErrors extends Error {
209
+ constructor(message) {
210
+ super(message);
211
+ this.name = `[] @briklab/lib/cli-john`;
212
+ Error.captureStackTrace(this, CLIErrors);
213
+ }
214
+ set setName(name) {
215
+ this.name = `[${name}] @briklab/lib/cli-john`;
216
+ }
217
+ }
218
+ (function (CLI) {
219
+ var _Command_instances, _Command_name, _Command_createWarn, _Command_options;
220
+ CLI.ValidEvents = ["command"];
221
+ /**
222
+ * ## CLI.Command
223
+ * A command in a CLI Command
224
+ */
225
+ class Command {
226
+ /**
227
+ * ### Command Constructor
228
+ * @param name The name of the command
229
+ * @constructor
230
+ */
231
+ constructor(name) {
232
+ _Command_instances.add(this);
233
+ _Command_name.set(this, void 0);
234
+ _Command_options.set(this, []);
235
+ __classPrivateFieldSet(this, _Command_name, name, "f");
236
+ return this;
237
+ }
238
+ /**
239
+ * The name of the Command
240
+ * @returns {string}
241
+ */
242
+ get name() {
243
+ return __classPrivateFieldGet(this, _Command_name, "f");
244
+ }
245
+ /**
246
+ * the metadata of the Command
247
+ * @returns {object}
248
+ */
249
+ get metadata() {
250
+ let metadata = {
251
+ options: __classPrivateFieldGet(this, _Command_options, "f").map((a) => a.metadata),
252
+ name: this.name,
253
+ };
254
+ return metadata;
255
+ }
256
+ option(name) {
257
+ if (!JSTC.for([name]).check(["string"])) {
258
+ __classPrivateFieldGet(this, _Command_instances, "m", _Command_createWarn).call(this, "First argument is invalid!", "The first argument must be a string", "Using String(argument) as fallback");
259
+ name = String(name);
260
+ }
261
+ let o = new CLI.Command.Option(name);
262
+ let f = __classPrivateFieldGet(this, _Command_options, "f").findIndex((a) => a.name === name);
263
+ if (f !== -1)
264
+ __classPrivateFieldGet(this, _Command_options, "f")[f] = o;
265
+ else
266
+ __classPrivateFieldGet(this, _Command_options, "f").push(o);
267
+ return o;
268
+ }
269
+ }
270
+ _Command_name = new WeakMap(), _Command_options = new WeakMap(), _Command_instances = new WeakSet(), _Command_createWarn = function _Command_createWarn(message, hint, otherMessage) {
271
+ warner.warn({ message: `[Class CLI.Command] ${message}
272
+ Hint: ${hint}
273
+ ${otherMessage}` });
274
+ return;
275
+ };
276
+ CLI.Command = Command;
277
+ })(CLI || (CLI = {}));
278
+ //#endregion
279
+ // -------------------------------------------------------------------------------------------------------
280
+ //#region CLI.Command.Option
281
+ (function (CLI) {
282
+ var Command;
283
+ (function (Command) {
284
+ var _Option_name;
285
+ /**
286
+ * ## CLI.Command.Option
287
+ * A option for a CLI.Command
288
+ */
289
+ class Option {
290
+ get metadata() {
291
+ let metadata = {
292
+ name: `${__classPrivateFieldGet(this, _Option_name, "f")}`, // <-- Templates TO NOT reference the actual variable
293
+ };
294
+ return metadata;
295
+ }
296
+ constructor(name) {
297
+ _Option_name.set(this, void 0);
298
+ __classPrivateFieldSet(this, _Option_name, name, "f");
299
+ return this;
300
+ }
301
+ get name() {
302
+ return __classPrivateFieldGet(this, _Option_name, "f");
303
+ }
304
+ }
305
+ _Option_name = new WeakMap();
306
+ Command.Option = Option;
307
+ })(Command = CLI.Command || (CLI.Command = {}));
308
+ })(CLI || (CLI = {}));
309
+ //#endregion
310
+ // -------------------------------------------------------------------------------------------------------
311
+ //#region CLI Utilities
312
+ JSTC.addCustomHandler("Utilities Tag Config", (p) => {
313
+ return (p &&
314
+ typeof p === "object" &&
315
+ typeof p.tag === "string" &&
316
+ typeof p.showErrorInTag === "boolean" &&
317
+ typeof p.paddingLeft === "number" &&
318
+ typeof p.paddingRight === "number" &&
319
+ (typeof p.styleName === "string" || p.styleName === undefined));
320
+ });
321
+ class UtilitiesClass {
322
+ constructor() {
323
+ this.styleSheet = new StyleSheet();
324
+ this.tags = {};
325
+ this.addTag("error", {
326
+ tag: "ERROR",
327
+ showErrorInTag: false,
328
+ paddingLeft: 0,
329
+ paddingRight: 0,
330
+ });
331
+ this.addTag("warning", {
332
+ tag: "WARNING",
333
+ showErrorInTag: true,
334
+ paddingLeft: 0,
335
+ paddingRight: 0,
336
+ });
337
+ this.addTag("info", {
338
+ tag: "INFO",
339
+ showErrorInTag: true,
340
+ paddingLeft: 0,
341
+ paddingRight: 0,
342
+ });
343
+ this.setTagStyle("error", new InlineStyle({ color: "red", fontWeight: "bold" }));
344
+ this.setTagStyle("warning", new InlineStyle({ color: "orange", fontWeight: "bold" }));
345
+ this.setTagStyle("info", new InlineStyle({ color: "blue" }));
346
+ }
347
+ /** Add a new tag */
348
+ addTag(name, config = {}) {
349
+ if (!JSTC.for([name, config]).check(["string", "object"])) {
350
+ warner.warn({ message: `[UtilitiesClass.addTag] @briklab/lib/cli-john: Invalid Arguments!
351
+ Hint: The first argument must be a string, and the second argument must be a object.
352
+ Using String(argument1) and {} as fallback.` });
353
+ name = String(name);
354
+ config = {};
355
+ }
356
+ const fullConfig = {
357
+ tag: name.toUpperCase(),
358
+ showErrorInTag: false,
359
+ paddingLeft: 0,
360
+ paddingRight: 0,
361
+ styleName: "",
362
+ ...config,
363
+ };
364
+ if (!JSTC.for([fullConfig]).check(["Utilities Tag Config"])) {
365
+ warner.warn({ message: `[UtilitiesClass.addTag] @briklab/lib/cli-john: Invalid tag config passed for "${name}"
366
+ Hint: The config must be in format {tag?: string, showErrorInTag?:boolean, paddingLeft?:number, paddingRight?:number, styleName?:string}` });
367
+ warner.warn({ message: JSON.stringify(fullConfig, null, 2) });
368
+ return this;
369
+ }
370
+ this.tags[name] = fullConfig;
371
+ return this;
372
+ }
373
+ /** Set style for a tag */
374
+ setTagStyle(tagName, style) {
375
+ if (typeof tagName !== "string" || !(style instanceof InlineStyle)) {
376
+ warner.warn({ message: `[UtilitiesClass.setTagStyle] @briklab/lib/cli-john: Invalid arguments!
377
+ Hint: The first argument must be a string and the second argument must be a instance of InlineStyle
378
+ Using String(firstArgument) and new InlineStyle({}) as fallback` });
379
+ tagName = String(tagName);
380
+ style = new InlineStyle({});
381
+ }
382
+ if (!this.tags[tagName]) {
383
+ warner.warn({ message: `[UtilitiesClass.setTagStyle] @briklab/lib/cli-john: Tag "${tagName}" does not exist!
384
+ Hint: Use a valid tag that you have defined or use "error"|"warn"|"info"` });
385
+ return this;
386
+ }
387
+ const styleName = `${tagName} Tag Color`;
388
+ this.styleSheet.set(styleName, style);
389
+ this.tags[tagName].styleName = styleName;
390
+ return this;
391
+ }
392
+ log(tagName, ...messages) {
393
+ if (!JSTC.for([tagName]).check(["string"])) {
394
+ warner.warn({ message: `[UtilitiesClass.log] @briklab/lib/cli-john: Invalid Arguments!
395
+ Hint: The first argument must be a string
396
+ Using String(argument1) as fallback` });
397
+ tagName = String(tagName);
398
+ }
399
+ if (!messages || messages.length === 0)
400
+ messages = [""];
401
+ const tag = this.tags[tagName];
402
+ if (!tag) {
403
+ warner.warn({ message: `[UtilitiesClass.log] @briklab/lib/cli-john: Tag "${tagName}" does not exist!
404
+ Hint: Use a valid tag that you have defined or use "error"|"warn"|"info"` });
405
+ console.log(...messages);
406
+ return;
407
+ }
408
+ const inlineStyle = this.styleSheet.get(tag.styleName);
409
+ const style = inlineStyle?.text ?? "";
410
+ const leftPad = " ".repeat(tag.paddingLeft);
411
+ const rightPad = " ".repeat(tag.paddingRight);
412
+ const isNodeTTY = typeof process !== "undefined" &&
413
+ typeof process.stdout !== "undefined" &&
414
+ Boolean(process.stdout.isTTY);
415
+ if (isNodeTTY) {
416
+ const ansi = inlineStyle?.ansi ?? "";
417
+ const reset = Color.RESET;
418
+ if (tag.showErrorInTag) {
419
+ console.log("[" + ansi + leftPad + tag.tag + rightPad + reset + "]:", ...messages);
420
+ }
421
+ else {
422
+ console.log(ansi + "[" + leftPad + tag.tag + rightPad + "]" + reset + ":", ...messages);
423
+ }
424
+ }
425
+ else {
426
+ if (tag.showErrorInTag) {
427
+ console.log(`[%c${leftPad}${tag.tag}${rightPad}%c]:`, style, ...messages);
428
+ }
429
+ else {
430
+ console.log(`%c[${leftPad}${tag.tag}${rightPad}]%c:`, style, ...messages);
431
+ }
432
+ }
433
+ }
434
+ error(...msg) {
435
+ if (!msg || msg.length === 0)
436
+ msg = [""];
437
+ this.log("error", ...msg);
438
+ return this;
439
+ }
440
+ warning(...msg) {
441
+ if (!msg || msg.length === 0)
442
+ msg = [""];
443
+ this.log("warning", ...msg);
444
+ return this;
445
+ }
446
+ info(...msg) {
447
+ if (!msg || msg.length === 0)
448
+ msg = [""];
449
+ this.log("info", ...msg);
450
+ return this;
451
+ }
452
+ }
453
+ export const Utilities = new UtilitiesClass();
454
+ //#endregion
455
+ // -------------------------------------------------------------------------------------------------------
456
+ //#region TODO
457
+ // TODO: Wire Options to Commands
458
+ // TODO: Create metadata getter-s in both commands and options
459
+ //#endregion
@@ -1,7 +1,205 @@
1
- var h=function(o,s,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof s=="function"?o!==s||!i:!s.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(o):i?i.value:s.get(o)},a,u,m,f,x,d,$;import{warner as _}from"../warner/index.js";const w={red:"#ff0000",blue:"#0000ff",green:"#00ff00",yellow:"#ffff00",orange:"#ffa500",black:"#000000",white:"#ffffff",gray:"#808080"};class c{constructor(s){if(a.add(this),this.r=0,this.g=0,this.b=0,this.a=1,typeof s=="string")h(this,a,"m",x).call(this,s);else if("r"in s&&"g"in s&&"b"in s)this.r=h(this,a,"m",m).call(this,s.r),this.g=h(this,a,"m",m).call(this,s.g),this.b=h(this,a,"m",m).call(this,s.b),this.a=s.a??1;else if("h"in s&&"s"in s&&"l"in s){const{r:t,g:i,b:r}=h(this,a,"m",d).call(this,s.h,s.s,s.l);this.r=t,this.g=i,this.b=r,this.a=s.a??1}else _.warn({message:`[Color.constructor] Invalid first argument!
2
- Hint: The first argument must be a valid color array
3
- Using black as fallback.`})}hex(){return`#${h(this,a,"m",f).call(this,this.r)}${h(this,a,"m",f).call(this,this.g)}${h(this,a,"m",f).call(this,this.b)}`}rgb(){return`rgb(${this.r}, ${this.g}, ${this.b})`}rgba(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}hsl(){const{h:s,s:t,l:i}=h(this,a,"m",$).call(this,this.r,this.g,this.b);return`hsl(${s}, ${t}%, ${i}%)`}hsla(){const{h:s,s:t,l:i}=h(this,a,"m",$).call(this,this.r,this.g,this.b);return`hsla(${s}, ${t}%, ${i}%, ${this.a})`}css(){return this.a===1?this.hex():this.rgba()}ansiTruecolor(){return`\x1B[38;2;${this.r};${this.g};${this.b}m`}ansiTruecolorBg(){return`\x1B[48;2;${this.r};${this.g};${this.b}m`}ansi256(){return`\x1B[38;5;${h(this,a,"m",u).call(this,this.r,this.g,this.b)}m`}ansi256Bg(){return`\x1B[48;5;${h(this,a,"m",u).call(this,this.r,this.g,this.b)}m`}wrapAnsi(s,t={}){const i=!!t.use256,r=t.background?i?this.ansi256Bg():this.ansiTruecolorBg():i?this.ansi256():this.ansiTruecolor();return`${`${t.bold?c.BOLD:""}${t.underline?c.UNDERLINE:""}`}${r}${s}${c.RESET}`}}a=new WeakSet,u=function(s,t,i){if(s===t&&t===i)return s<8?16:s>248?231:Math.round((s-8)/247*24)+232;const r=g=>Math.round(g/255*5),n=r(s),e=r(t),l=r(i);return 16+36*n+6*e+l},m=function(s){return Math.max(0,Math.min(255,s))},f=function(s){return s.toString(16).padStart(2,"0")},x=function(s){if(s=s.trim().toLowerCase(),w[s]&&(s=w[s]),s.startsWith("#")){const t=s.slice(1);t.length===3?(this.r=parseInt(t[0]+t[0],16),this.g=parseInt(t[1]+t[1],16),this.b=parseInt(t[2]+t[2],16)):t.length===6?(this.r=parseInt(t.slice(0,2),16),this.g=parseInt(t.slice(2,4),16),this.b=parseInt(t.slice(4,6),16)):_.warn({message:`[Color class] @briklab/lib/color: Invalid hex!
4
- Hint: You must pass a valid hex color string!
5
- Using black as fallback.`})}else if(s.startsWith("rgb")){const t=s.match(/[\d.]+/g)?.map(Number);t&&t.length>=3&&([this.r,this.g,this.b]=t,this.a=t[3]??1)}else if(s.startsWith("hsl")){const t=s.match(/[\d.]+/g)?.map(Number);if(t&&t.length>=3){const{r:i,g:r,b:n}=h(this,a,"m",d).call(this,t[0],t[1],t[2]);this.r=i,this.g=r,this.b=n,this.a=t[3]??1}}else _.warn({message:`[Color class] @briklab/lib/color: Unknown color string "${s}"!
6
- Hint: The argument must be a valid color string!
7
- Using black as fallback.`})},d=function(s,t,i){t/=100,i/=100;const r=l=>(l+s/30)%12,n=t*Math.min(i,1-i),e=l=>i-n*Math.max(-1,Math.min(r(l)-3,Math.min(9-r(l),1)));return{r:Math.round(e(0)*255),g:Math.round(e(8)*255),b:Math.round(e(4)*255)}},$=function(s,t,i){s/=255,t/=255,i/=255;const r=Math.max(s,t,i),n=Math.min(s,t,i);let e=0,l=0,g=(r+n)/2;if(r!==n){const b=r-n;switch(l=g>.5?b/(2-r-n):b/(r+n),r){case s:e=(t-i)/b+(t<i?6:0);break;case t:e=(i-s)/b+2;break;case i:e=(s-t)/b+4;break}e*=60}return{h:Math.round(e),s:Math.round(l*100),l:Math.round(g*100)}},c.RESET="\x1B[0m",c.BOLD="\x1B[1m",c.UNDERLINE="\x1B[4m";var M=c;export{M as default};
1
+ /**
2
+ * Easy way to use colors
3
+ */
4
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
5
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
6
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
7
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
8
+ };
9
+ var _Color_instances, _Color_rgbToAnsi256Index, _Color_clamp, _Color_toHex, _Color_parseString, _Color_hslToRgb, _Color_rgbToHsl;
10
+ import { warner } from "../warner/index.js";
11
+ const NAMED_COLORS = {
12
+ red: "#ff0000",
13
+ blue: "#0000ff",
14
+ green: "#00ff00",
15
+ yellow: "#ffff00",
16
+ orange: "#ffa500",
17
+ black: "#000000",
18
+ white: "#ffffff",
19
+ gray: "#808080",
20
+ };
21
+ class Color {
22
+ constructor(input) {
23
+ _Color_instances.add(this);
24
+ this.r = 0;
25
+ this.g = 0;
26
+ this.b = 0;
27
+ this.a = 1;
28
+ if (typeof input === "string") {
29
+ __classPrivateFieldGet(this, _Color_instances, "m", _Color_parseString).call(this, input);
30
+ }
31
+ else if ("r" in input && "g" in input && "b" in input) {
32
+ this.r = __classPrivateFieldGet(this, _Color_instances, "m", _Color_clamp).call(this, input.r);
33
+ this.g = __classPrivateFieldGet(this, _Color_instances, "m", _Color_clamp).call(this, input.g);
34
+ this.b = __classPrivateFieldGet(this, _Color_instances, "m", _Color_clamp).call(this, input.b);
35
+ this.a = input.a ?? 1;
36
+ }
37
+ else if ("h" in input && "s" in input && "l" in input) {
38
+ const { r, g, b } = __classPrivateFieldGet(this, _Color_instances, "m", _Color_hslToRgb).call(this, input.h, input.s, input.l);
39
+ this.r = r;
40
+ this.g = g;
41
+ this.b = b;
42
+ this.a = input.a ?? 1;
43
+ }
44
+ else {
45
+ warner.warn({ message: `[Color.constructor] Invalid first argument!
46
+ Hint: The first argument must be a valid color array
47
+ Using black as fallback.` });
48
+ }
49
+ }
50
+ // -----------------------
51
+ // Public Methods
52
+ // -----------------------
53
+ hex() {
54
+ return `#${__classPrivateFieldGet(this, _Color_instances, "m", _Color_toHex).call(this, this.r)}${__classPrivateFieldGet(this, _Color_instances, "m", _Color_toHex).call(this, this.g)}${__classPrivateFieldGet(this, _Color_instances, "m", _Color_toHex).call(this, this.b)}`;
55
+ }
56
+ rgb() {
57
+ return `rgb(${this.r}, ${this.g}, ${this.b})`;
58
+ }
59
+ rgba() {
60
+ return `rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`;
61
+ }
62
+ hsl() {
63
+ const { h, s, l } = __classPrivateFieldGet(this, _Color_instances, "m", _Color_rgbToHsl).call(this, this.r, this.g, this.b);
64
+ return `hsl(${h}, ${s}%, ${l}%)`;
65
+ }
66
+ hsla() {
67
+ const { h, s, l } = __classPrivateFieldGet(this, _Color_instances, "m", _Color_rgbToHsl).call(this, this.r, this.g, this.b);
68
+ return `hsla(${h}, ${s}%, ${l}%, ${this.a})`;
69
+ }
70
+ css() {
71
+ return this.a === 1 ? this.hex() : this.rgba();
72
+ }
73
+ /** Return a 24-bit (truecolor) ANSI sequence for this color (foreground) */
74
+ ansiTruecolor() {
75
+ return `\x1b[38;2;${this.r};${this.g};${this.b}m`;
76
+ }
77
+ /** Return a 24-bit (truecolor) ANSI sequence for background */
78
+ ansiTruecolorBg() {
79
+ return `\x1b[48;2;${this.r};${this.g};${this.b}m`;
80
+ }
81
+ /** Return a 256-color ANSI sequence for this color (foreground) */
82
+ ansi256() {
83
+ const idx = __classPrivateFieldGet(this, _Color_instances, "m", _Color_rgbToAnsi256Index).call(this, this.r, this.g, this.b);
84
+ return `\x1b[38;5;${idx}m`;
85
+ }
86
+ /** Return a 256-color ANSI sequence for background */
87
+ ansi256Bg() {
88
+ const idx = __classPrivateFieldGet(this, _Color_instances, "m", _Color_rgbToAnsi256Index).call(this, this.r, this.g, this.b);
89
+ return `\x1b[48;5;${idx}m`;
90
+ }
91
+ /** Wrap text with this color (truecolor by default). Options: {background?: boolean, use256?: boolean, bold?: boolean, underline?: boolean} */
92
+ wrapAnsi(text, opts = {}) {
93
+ const use256 = Boolean(opts.use256);
94
+ const seq = opts.background
95
+ ? use256
96
+ ? this.ansi256Bg()
97
+ : this.ansiTruecolorBg()
98
+ : use256
99
+ ? this.ansi256()
100
+ : this.ansiTruecolor();
101
+ const mods = `${opts.bold ? Color.BOLD : ""}${opts.underline ? Color.UNDERLINE : ""}`;
102
+ return `${mods}${seq}${text}${Color.RESET}`;
103
+ }
104
+ }
105
+ _Color_instances = new WeakSet(), _Color_rgbToAnsi256Index = function _Color_rgbToAnsi256Index(r, g, b) {
106
+ // grayscale range
107
+ if (r === g && g === b) {
108
+ if (r < 8)
109
+ return 16;
110
+ if (r > 248)
111
+ return 231;
112
+ return Math.round(((r - 8) / 247) * 24) + 232;
113
+ }
114
+ const to6 = (v) => Math.round((v / 255) * 5);
115
+ const ri = to6(r);
116
+ const gi = to6(g);
117
+ const bi = to6(b);
118
+ return 16 + 36 * ri + 6 * gi + bi;
119
+ }, _Color_clamp = function _Color_clamp(value) {
120
+ return Math.max(0, Math.min(255, value));
121
+ }, _Color_toHex = function _Color_toHex(value) {
122
+ return value.toString(16).padStart(2, "0");
123
+ }, _Color_parseString = function _Color_parseString(str) {
124
+ str = str.trim().toLowerCase();
125
+ if (NAMED_COLORS[str]) {
126
+ str = NAMED_COLORS[str];
127
+ }
128
+ if (str.startsWith("#")) {
129
+ const hex = str.slice(1);
130
+ if (hex.length === 3) {
131
+ this.r = parseInt(hex[0] + hex[0], 16);
132
+ this.g = parseInt(hex[1] + hex[1], 16);
133
+ this.b = parseInt(hex[2] + hex[2], 16);
134
+ }
135
+ else if (hex.length === 6) {
136
+ this.r = parseInt(hex.slice(0, 2), 16);
137
+ this.g = parseInt(hex.slice(2, 4), 16);
138
+ this.b = parseInt(hex.slice(4, 6), 16);
139
+ }
140
+ else {
141
+ warner.warn({ message: `[Color class] @briklab/lib/color: Invalid hex!
142
+ Hint: You must pass a valid hex color string!
143
+ Using black as fallback.` });
144
+ }
145
+ }
146
+ else if (str.startsWith("rgb")) {
147
+ const vals = str.match(/[\d.]+/g)?.map(Number);
148
+ if (vals && vals.length >= 3) {
149
+ [this.r, this.g, this.b] = vals;
150
+ this.a = vals[3] ?? 1;
151
+ }
152
+ }
153
+ else if (str.startsWith("hsl")) {
154
+ const vals = str.match(/[\d.]+/g)?.map(Number);
155
+ if (vals && vals.length >= 3) {
156
+ const { r, g, b } = __classPrivateFieldGet(this, _Color_instances, "m", _Color_hslToRgb).call(this, vals[0], vals[1], vals[2]);
157
+ this.r = r;
158
+ this.g = g;
159
+ this.b = b;
160
+ this.a = vals[3] ?? 1;
161
+ }
162
+ }
163
+ else {
164
+ warner.warn({ message: `[Color class] @briklab/lib/color: Unknown color string "${str}"!
165
+ Hint: The argument must be a valid color string!
166
+ Using black as fallback.` });
167
+ }
168
+ }, _Color_hslToRgb = function _Color_hslToRgb(h, s, l) {
169
+ s /= 100;
170
+ l /= 100;
171
+ const k = (n) => (n + h / 30) % 12;
172
+ const a = s * Math.min(l, 1 - l);
173
+ const f = (n) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
174
+ return { r: Math.round(f(0) * 255), g: Math.round(f(8) * 255), b: Math.round(f(4) * 255) };
175
+ }, _Color_rgbToHsl = function _Color_rgbToHsl(r, g, b) {
176
+ r /= 255;
177
+ g /= 255;
178
+ b /= 255;
179
+ const max = Math.max(r, g, b), min = Math.min(r, g, b);
180
+ let h = 0, s = 0, l = (max + min) / 2;
181
+ if (max !== min) {
182
+ const d = max - min;
183
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
184
+ switch (max) {
185
+ case r:
186
+ h = (g - b) / d + (g < b ? 6 : 0);
187
+ break;
188
+ case g:
189
+ h = (b - r) / d + 2;
190
+ break;
191
+ case b:
192
+ h = (r - g) / d + 4;
193
+ break;
194
+ }
195
+ h *= 60;
196
+ }
197
+ return { h: Math.round(h), s: Math.round(s * 100), l: Math.round(l * 100) };
198
+ };
199
+ /**
200
+ * ANSI / Terminal color helpers
201
+ */
202
+ Color.RESET = "\x1b[0m";
203
+ Color.BOLD = "\x1b[1m";
204
+ Color.UNDERLINE = "\x1b[4m";
205
+ export default Color;
@@ -1,5 +1,97 @@
1
- var c=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},i;import{warner as u}from"../warner/index.js";class g{constructor(){i.set(this,{Array:e=>Array.isArray(e),"string[]":e=>Array.isArray(e)&&e.every(t=>typeof t=="string")})}for(e){return Array.isArray(e)||(u.warn({message:`[JSTC.for] @briklab/lib/jstc: Invalid first argument!
2
- Hint: The first argument must be a array.
3
- Using [givenValue] as fallback`}),e=[e]),{check:t=>{if(e.length<t.length)return!1;for(let r=0;r<t.length;r++){const o=e[r],f=t[r],y=Array.isArray(f)?f:[f];let s=!1;for(const l of y){const d=typeof l=="string"?l.split("|"):[l];for(const a of d)if(typeof a=="function"){if(o instanceof a){s=!0;break}}else if(typeof a=="string"&&c(this,i,"f")[a]){if(c(this,i,"f")[a](o)){s=!0;break}}else if(typeof o===a){s=!0;break}if(s)break}if(!s)return!1}return!0}}}addCustomHandler(e,t){typeof e=="string"&&typeof t=="function"||(u.warn({message:`[JSTC.addCustomHandler] @briklab/lib/jstc: Invalid Arguments!
4
- Hint: The first argument must be a string, and the second argument must be a function
5
- Using String(argument1) and ()=>false as fallbacks`}),e=String(e),t=()=>!1),c(this,i,"f")[e]=t}}i=new WeakMap;const p=new g;var m=p;export{g as JSTypeChecker,m as default};
1
+ /**
2
+ * # JSTC
3
+ * @packageDocumentation
4
+ * Runtime JS Type Checker
5
+ * @module JSTC
6
+ */
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _JSTypeChecker___CustomHandler;
13
+ import { warner } from "../warner/index.js";
14
+ /**
15
+ * # JSTypeChecker
16
+ * A JS Type Checker. Add type checking to your javascript files as well
17
+ */
18
+ export class JSTypeChecker {
19
+ constructor() {
20
+ _JSTypeChecker___CustomHandler.set(this, {
21
+ Array: (value) => Array.isArray(value),
22
+ "string[]": (value) => Array.isArray(value) && value.every((v) => typeof v === "string"),
23
+ });
24
+ }
25
+ /**
26
+ * ### JSTypeChecker.for
27
+ * check if specific arguments are of a specific type, class, etc.
28
+ * @param {unknown[]} args
29
+ */
30
+ for(args) {
31
+ if (!Array.isArray(args)) {
32
+ warner.warn({ message: `[JSTC.for] @briklab/lib/jstc: Invalid first argument!
33
+ Hint: The first argument must be a array.
34
+ Using [givenValue] as fallback` });
35
+ args = [args];
36
+ }
37
+ return {
38
+ /**
39
+ * ### JSTypeChecker.for().check
40
+ * Check the given arguments with corresponding given types
41
+ */
42
+ check: (types) => {
43
+ if (args.length < types.length)
44
+ return false;
45
+ for (let i = 0; i < types.length; i++) {
46
+ const value = args[i];
47
+ const expected = types[i];
48
+ const expectedTypes = Array.isArray(expected) ? expected : [expected];
49
+ let matched = false;
50
+ for (const tRaw of expectedTypes) {
51
+ const unionTypes = typeof tRaw === "string" ? tRaw.split("|") : [tRaw];
52
+ for (const t of unionTypes) {
53
+ if (typeof t === "function") {
54
+ if (value instanceof t) {
55
+ matched = true;
56
+ break;
57
+ }
58
+ }
59
+ else if (typeof t === "string" && __classPrivateFieldGet(this, _JSTypeChecker___CustomHandler, "f")[t]) {
60
+ if (__classPrivateFieldGet(this, _JSTypeChecker___CustomHandler, "f")[t](value)) {
61
+ matched = true;
62
+ break;
63
+ }
64
+ }
65
+ else if (typeof value === t) {
66
+ matched = true;
67
+ break;
68
+ }
69
+ }
70
+ if (matched)
71
+ break;
72
+ }
73
+ if (!matched)
74
+ return false;
75
+ }
76
+ return true;
77
+ },
78
+ };
79
+ }
80
+ /**
81
+ * ### JSTypeChecker.addCustomHandler
82
+ * Create a custom handler for checking types.
83
+ */
84
+ addCustomHandler(name, handler) {
85
+ if (!(typeof name === "string" && typeof handler === "function")) {
86
+ warner.warn({ message: `[JSTC.addCustomHandler] @briklab/lib/jstc: Invalid Arguments!
87
+ Hint: The first argument must be a string, and the second argument must be a function
88
+ Using String(argument1) and ()=>false as fallbacks` });
89
+ name = String(name);
90
+ handler = () => false;
91
+ }
92
+ __classPrivateFieldGet(this, _JSTypeChecker___CustomHandler, "f")[name] = handler;
93
+ }
94
+ }
95
+ _JSTypeChecker___CustomHandler = new WeakMap();
96
+ const JSTC = new JSTypeChecker();
97
+ export default JSTC;
@@ -1,14 +1,251 @@
1
- var u=function(l,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?l!==e||!i:!e.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(l,t):i?i.value=t:e.set(l,t),t},o=function(l,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?l!==e||!n:!e.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(l):n?n.value:e.get(l)},y,f,p,m,h,g;import d from"../jstc/index.js";import{warner as s}from"../warner/index.js";import{CSSStyleDeclaration as w}from"cssom";import S from"../color/index.js";class v{constructor(e){y.add(this),f.set(this,void 0),h.set(this,void 0),d.for([e]).check(["object|undefined"])||(s.warn({message:`[InlineStyle class] @briklab/lib/stylesheet: Invalid first argument!
2
- Hint: The first argument must be a valid style object or not be given!
3
- Using {"imeMode":${e}} as fallback`}),e={imeMode:`${e}`}),u(this,h,e,"f"),u(this,f,new w,"f")}generate(){let e=o(this,f,"f"),t=o(this,h,"f"),n=Object.keys(t),i=Object.values(t);for(let r=0;r<n.length;r++){const c=n[r];let a=i[r];if(a==null){s.warn({message:`[InlineStyle.generate] @briklab/lib/stylesheet: Skipping property "${c}" with ${String(a)} value. Hint: avoid null/undefined style values.`});continue}typeof a!="string"&&(s.warn({message:`[InlineStyle.generate] @briklab/lib/stylesheet: Non-string style value for "${c}" (type=${typeof a}). Coercing to string.`}),a=String(a)),e.setProperty(c,a)}return e.cssText}get text(){return this.generate()}get ansi(){const e=o(this,h,"f")||{};let t=[];(e["font-weight"]==="bold"||e.fontWeight==="bold")&&t.push(S.BOLD),(e["text-decoration"]||e.textDecoration||"").includes("underline")&&t.push(S.UNDERLINE);const n=e.color||e.color;if(n)try{const r=new S(String(n));t.push(r.ansiTruecolor())}catch{s.warn({message:`[InlineStyle.ansi] @briklab/lib/stylesheet: Invalid color value "${String(n)}" \u2014 ignoring. Hint: use a valid hex, rgb(), hsl() or named color.`})}const i=e["background-color"]||e.backgroundColor;if(i)try{const r=new S(String(i));t.push(r.ansiTruecolorBg())}catch{s.warn({message:`[InlineStyle.ansi] @briklab/lib/stylesheet: Invalid background-color value "${String(i)}" \u2014 ignoring. Hint: use a valid hex, rgb(), hsl() or named color.`})}return t.join("")}addStyleWithObject(e){return d.for([e]).check(["object"])?(u(this,h,{...o(this,h,"f"),...e},"f"),this.generate(),this):(s.warn({message:`[InlineStyle.addStyleWithObject] @briklab/lib/stylesheet: Invalid first argument!
4
- Hint: expected a plain object with CSS properties. Received: ${String(e)}
5
- Returned with no operations.`}),this)}addStyleWithInlineCSS(e){if(!d.for([e]).check(["string"]))return s.warn({message:`[InlineStyle.addStyleWithInlineCSS] @briklab/lib/stylesheet: Invalid first argument!
6
- Hint: The first argument must be a valid inline css string!
7
- Returned with no operations.`}),this;let t=new w;t.cssText=o(this,y,"m",m).call(this,e);let n={};for(let i=0;i<t.length;i++){const r=t[i],c=t.getPropertyValue(r);n[r]=c}return this.addStyleWithObject(n),this}removeStyle(e){if(!d.for([e]).check(["string[]|string"]))return s.warn({message:`[InlineStyle.removeStyle] @briklab/lib/stylesheet: Invalid first argument!
8
- Hint: expected a string or array of strings. Returned with no operations. Received: ${String(e)}`}),this;typeof e=="string"&&(e=[e]);for(let t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"){s.warn({message:`[InlineStyle.removeStyle] @briklab/lib/stylesheet: Ignoring non-string style name at index ${t}: ${String(n)}`});continue}delete o(this,h,"f")[n]}return this}applyTo(e){return d.for([e]).check(["object"])?!e||typeof e.style!="object"?(s.warn({message:"[InlineStyle.applyTo] @briklab/lib/stylesheet: Given object does not look like an HTMLElement (missing .style). No operation was performed."}),this):(e.style.cssText=this.generate(),this):(s.warn({message:`[InlineStyle.applyTo] @briklab/lib/stylesheet: Invalid first argument!
9
- Hint: expected an HTMLElement. No operation was performed.`}),this)}}f=new WeakMap,h=new WeakMap,y=new WeakSet,p=function(e){return e.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)},m=function(e){const t=String(e).split(";");let n="";for(let i=0;i<t.length;i++){const r=t[i].trim();if(!r)continue;const c=r.split(":");if(c.length<2){s.warn({message:`[InlineStyle.#convertKeysToValidCSS] @briklab/lib/stylesheet: Skipping malformed rule: "${r}". Hint: expected "property: value" pairs separated by ";"`});continue}const a=c[0].trim(),b=c.slice(1).join(":").trim();if(!a||!b){s.warn({message:`[InlineStyle.#convertKeysToValidCSS] @briklab/lib/stylesheet: Skipping empty property or value in rule: "${r}".`});continue}n+=`${o(this,y,"m",p).call(this,a)}:${b};`}return n};var $=v;class H{constructor(){g.set(this,void 0),u(this,g,{},"f")}set(e,t){return d.for([e,t]).check(["string","object"])?t instanceof v?(o(this,g,"f")[e]=t,this):(s.warn({message:`[StyleSheet.set] @briklab/lib/stylesheet: Provided style is not an InlineStyle instance!
10
- Hint: create the style with new InlineStyle({...}). Received: ${String(t)}. Returned with no operations.`}),this):(s.warn({message:`[StyleSheet.set] @briklab/lib/stylesheet: Invalid arguments!
11
- Hint: call .set("ruleName", new InlineStyle({...})). Received name=${String(e)}, style=${String(t)}. Returned with no operations.`}),this)}get(e){if(!d.for([e]).check(["string"])){s.warn({message:`[StyleSheet.get] @briklab/lib/stylesheet: Invalid argument!
12
- Hint: name must be a string. Received: ${String(e)}. Returned undefined.`});return}return o(this,g,"f")[e]}remove(e){return d.for([e]).check(["string"])?(delete o(this,g,"f")[e],this):(s.warn({message:`[StyleSheet.remove] @briklab/lib/stylesheet: Invalid argument!
13
- Hint: name must be a string. Received: ${String(e)}. No-op.`}),this)}generate(){let e="";for(const t in o(this,g,"f")){const n=o(this,g,"f")[t];n&&(e+=`${t} { ${n.text} }
14
- `)}return e.trim()}toString(){return this.generate()}}g=new WeakMap;export{H as StyleSheet,$ as default};
1
+ /**
2
+ * # @briklab/lib/stylesheet
3
+ * Create inline styles in JS/TS
4
+ */
5
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
6
+ if (kind === "m") throw new TypeError("Private method is not writable");
7
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
8
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
9
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
10
+ };
11
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
12
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
13
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
14
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
15
+ };
16
+ var _InlineStyle_instances, _InlineStyle_cssStyleDec, _InlineStyle_convertFieldToHyphenCase, _InlineStyle_convertKeysToValidCSS, _InlineStyle_styleObject, _StyleSheet_styles;
17
+ import JSTC from "../jstc/index.js";
18
+ import { warner } from "../warner/index.js";
19
+ import { CSSStyleDeclaration as UUIII } from "cssom";
20
+ import Color from "../color/index.js";
21
+ /**
22
+ * # InlineStyle
23
+ * @classdesc Create a CSS Inline style.
24
+ * @class
25
+ */
26
+ class InlineStyle {
27
+ /**
28
+ * ## constructor
29
+ * construct a InlineStyle
30
+ */
31
+ constructor(styleObject) {
32
+ _InlineStyle_instances.add(this);
33
+ _InlineStyle_cssStyleDec.set(this, void 0);
34
+ _InlineStyle_styleObject.set(this, void 0);
35
+ if (!JSTC.for([styleObject]).check(["object|undefined"])) {
36
+ warner.warn({ message: `[InlineStyle class] @briklab/lib/stylesheet: Invalid first argument!
37
+ Hint: The first argument must be a valid style object or not be given!
38
+ Using {"imeMode":${styleObject}} as fallback` });
39
+ styleObject = { imeMode: `${styleObject}` };
40
+ }
41
+ __classPrivateFieldSet(this, _InlineStyle_styleObject, styleObject, "f");
42
+ __classPrivateFieldSet(this, _InlineStyle_cssStyleDec, new UUIII(), "f");
43
+ }
44
+ generate() {
45
+ let a = __classPrivateFieldGet(this, _InlineStyle_cssStyleDec, "f");
46
+ let b = __classPrivateFieldGet(this, _InlineStyle_styleObject, "f");
47
+ let c = Object.keys(b);
48
+ let d = Object.values(b);
49
+ for (let i = 0; i < c.length; i++) {
50
+ const prop = c[i];
51
+ let val = d[i];
52
+ if (val == null) {
53
+ warner.warn({ message: `[InlineStyle.generate] @briklab/lib/stylesheet: Skipping property "${prop}" with ${String(val)} value. Hint: avoid null/undefined style values.` });
54
+ continue;
55
+ }
56
+ if (typeof val !== "string") {
57
+ warner.warn({ message: `[InlineStyle.generate] @briklab/lib/stylesheet: Non-string style value for "${prop}" (type=${typeof val}). Coercing to string.` });
58
+ val = String(val);
59
+ }
60
+ a.setProperty(prop, val);
61
+ }
62
+ return a.cssText;
63
+ }
64
+ get text() {
65
+ return this.generate();
66
+ }
67
+ get ansi() {
68
+ const s = __classPrivateFieldGet(this, _InlineStyle_styleObject, "f") || {};
69
+ let parts = [];
70
+ if (s["font-weight"] === "bold" || s.fontWeight === "bold")
71
+ parts.push(Color.BOLD);
72
+ if ((s["text-decoration"] || s.textDecoration || "").includes("underline"))
73
+ parts.push(Color.UNDERLINE);
74
+ const colorVal = s.color || s["color"];
75
+ if (colorVal) {
76
+ try {
77
+ const c = new Color(String(colorVal));
78
+ parts.push(c.ansiTruecolor());
79
+ }
80
+ catch (e) {
81
+ warner.warn({ message: `[InlineStyle.ansi] @briklab/lib/stylesheet: Invalid color value "${String(colorVal)}" — ignoring. Hint: use a valid hex, rgb(), hsl() or named color.` });
82
+ }
83
+ }
84
+ const bgVal = s["background-color"] || s.backgroundColor;
85
+ if (bgVal) {
86
+ try {
87
+ const c = new Color(String(bgVal));
88
+ parts.push(c.ansiTruecolorBg());
89
+ }
90
+ catch (e) {
91
+ warner.warn({ message: `[InlineStyle.ansi] @briklab/lib/stylesheet: Invalid background-color value "${String(bgVal)}" — ignoring. Hint: use a valid hex, rgb(), hsl() or named color.` });
92
+ }
93
+ }
94
+ return parts.join("");
95
+ }
96
+ addStyleWithObject(styleObject) {
97
+ if (!JSTC.for([styleObject]).check(["object"])) {
98
+ warner.warn({ message: `[InlineStyle.addStyleWithObject] @briklab/lib/stylesheet: Invalid first argument!\n` +
99
+ `Hint: expected a plain object with CSS properties. Received: ${String(styleObject)}\n` +
100
+ `Returned with no operations.` });
101
+ return this;
102
+ }
103
+ __classPrivateFieldSet(this, _InlineStyle_styleObject, { ...__classPrivateFieldGet(this, _InlineStyle_styleObject, "f"), ...styleObject }, "f");
104
+ this.generate();
105
+ return this;
106
+ }
107
+ addStyleWithInlineCSS(inlineCSS) {
108
+ if (!JSTC.for([inlineCSS]).check(["string"])) {
109
+ warner.warn({ message: `[InlineStyle.addStyleWithInlineCSS] @briklab/lib/stylesheet: Invalid first argument!
110
+ Hint: The first argument must be a valid inline css string!
111
+ Returned with no operations.` });
112
+ return this;
113
+ }
114
+ let s = new UUIII();
115
+ s.cssText = __classPrivateFieldGet(this, _InlineStyle_instances, "m", _InlineStyle_convertKeysToValidCSS).call(this, inlineCSS);
116
+ let o = {};
117
+ for (let i = 0; i < s.length; i++) {
118
+ const a = s[i];
119
+ const v = s.getPropertyValue(a);
120
+ o[a] = v;
121
+ }
122
+ this.addStyleWithObject(o);
123
+ return this;
124
+ }
125
+ removeStyle(styles) {
126
+ if (!JSTC.for([styles]).check(["string[]|string"])) {
127
+ warner.warn({ message: `[InlineStyle.removeStyle] @briklab/lib/stylesheet: Invalid first argument!\n` +
128
+ `Hint: expected a string or array of strings. Returned with no operations. Received: ${String(styles)}` });
129
+ return this;
130
+ }
131
+ if (typeof styles === "string") {
132
+ styles = [styles];
133
+ }
134
+ for (let i = 0; i < styles.length; i++) {
135
+ const prop = styles[i];
136
+ if (typeof prop !== "string") {
137
+ warner.warn({ message: `[InlineStyle.removeStyle] @briklab/lib/stylesheet: Ignoring non-string style name at index ${i}: ${String(prop)}` });
138
+ continue;
139
+ }
140
+ delete __classPrivateFieldGet(this, _InlineStyle_styleObject, "f")[prop];
141
+ }
142
+ return this;
143
+ }
144
+ applyTo(element) {
145
+ if (!JSTC.for([element]).check(["object"])) {
146
+ warner.warn({ message: `[InlineStyle.applyTo] @briklab/lib/stylesheet: Invalid first argument!\n` +
147
+ `Hint: expected an HTMLElement. No operation was performed.` });
148
+ return this;
149
+ }
150
+ if (!element || typeof element.style !== "object") {
151
+ warner.warn({ message: `[InlineStyle.applyTo] @briklab/lib/stylesheet: Given object does not look like an HTMLElement (missing .style). No operation was performed.` });
152
+ return this;
153
+ }
154
+ element.style.cssText = this.generate();
155
+ return this;
156
+ }
157
+ }
158
+ _InlineStyle_cssStyleDec = new WeakMap(), _InlineStyle_styleObject = new WeakMap(), _InlineStyle_instances = new WeakSet(), _InlineStyle_convertFieldToHyphenCase = function _InlineStyle_convertFieldToHyphenCase(string) {
159
+ return string.replace(/([A-Z])/g, (match) => `-${match.toLowerCase()}`);
160
+ }, _InlineStyle_convertKeysToValidCSS = function _InlineStyle_convertKeysToValidCSS(string) {
161
+ const parts = String(string).split(";");
162
+ let out = "";
163
+ for (let i = 0; i < parts.length; i++) {
164
+ const raw = parts[i].trim();
165
+ if (!raw)
166
+ continue;
167
+ const kv = raw.split(":");
168
+ if (kv.length < 2) {
169
+ warner.warn({ message: `[InlineStyle.#convertKeysToValidCSS] @briklab/lib/stylesheet: Skipping malformed rule: "${raw}". ` +
170
+ `Hint: expected "property: value" pairs separated by ";"` });
171
+ continue;
172
+ }
173
+ const k = kv[0].trim();
174
+ const v = kv.slice(1).join(":").trim();
175
+ if (!k || !v) {
176
+ warner.warn({ message: `[InlineStyle.#convertKeysToValidCSS] @briklab/lib/stylesheet: Skipping empty property or value in rule: "${raw}".` });
177
+ continue;
178
+ }
179
+ out += `${__classPrivateFieldGet(this, _InlineStyle_instances, "m", _InlineStyle_convertFieldToHyphenCase).call(this, k)}:${v};`;
180
+ }
181
+ return out;
182
+ };
183
+ export default InlineStyle;
184
+ export class StyleSheet {
185
+ constructor() {
186
+ _StyleSheet_styles.set(this, void 0);
187
+ __classPrivateFieldSet(this, _StyleSheet_styles, {}, "f");
188
+ }
189
+ /**
190
+ * Add or update a rule in the stylesheet.
191
+ * @param name The rule name or selector (string).
192
+ * @param style An InlineStyle instance.
193
+ */
194
+ set(name, style) {
195
+ if (!JSTC.for([name, style]).check(["string", "object"])) {
196
+ warner.warn({ message: `[StyleSheet.set] @briklab/lib/stylesheet: Invalid arguments!\n` +
197
+ `Hint: call .set("ruleName", new InlineStyle({...})). Received name=${String(name)}, style=${String(style)}. Returned with no operations.` });
198
+ return this;
199
+ }
200
+ if (!(style instanceof InlineStyle)) {
201
+ warner.warn({ message: `[StyleSheet.set] @briklab/lib/stylesheet: Provided style is not an InlineStyle instance!\n` +
202
+ `Hint: create the style with new InlineStyle({...}). Received: ${String(style)}. Returned with no operations.` });
203
+ return this;
204
+ }
205
+ __classPrivateFieldGet(this, _StyleSheet_styles, "f")[name] = style;
206
+ return this;
207
+ }
208
+ /**
209
+ * Get a rule by name.
210
+ */
211
+ get(name) {
212
+ if (!JSTC.for([name]).check(["string"])) {
213
+ warner.warn({ message: `[StyleSheet.get] @briklab/lib/stylesheet: Invalid argument!\n` +
214
+ `Hint: name must be a string. Received: ${String(name)}. Returned undefined.` });
215
+ return undefined;
216
+ }
217
+ return __classPrivateFieldGet(this, _StyleSheet_styles, "f")[name];
218
+ }
219
+ /**
220
+ * Remove a rule by name.
221
+ */
222
+ remove(name) {
223
+ if (!JSTC.for([name]).check(["string"])) {
224
+ warner.warn({ message: `[StyleSheet.remove] @briklab/lib/stylesheet: Invalid argument!\n` +
225
+ `Hint: name must be a string. Received: ${String(name)}. No-op.` });
226
+ return this;
227
+ }
228
+ delete __classPrivateFieldGet(this, _StyleSheet_styles, "f")[name];
229
+ return this;
230
+ }
231
+ /**
232
+ * Generate CSS text for the whole stylesheet.
233
+ */
234
+ generate() {
235
+ let css = "";
236
+ for (const key in __classPrivateFieldGet(this, _StyleSheet_styles, "f")) {
237
+ const style = __classPrivateFieldGet(this, _StyleSheet_styles, "f")[key];
238
+ if (style) {
239
+ css += `${key} { ${style.text} }\n`;
240
+ }
241
+ }
242
+ return css.trim();
243
+ }
244
+ /**
245
+ * Export as a string for inline style usage or injection.
246
+ */
247
+ toString() {
248
+ return this.generate();
249
+ }
250
+ }
251
+ _StyleSheet_styles = new WeakMap();
@@ -1,4 +1,169 @@
1
- var g=function(e,t,a,s,o){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?o.call(e,a):o?o.value=a:t.set(e,a),a},n=function(e,t,a,s){if(a==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return a==="m"?s:a==="a"?s.call(e):s?s.value:t.get(e)},l,i,r,d,y,m;import u from"../jstc/index.js";const W=typeof window<"u"&&typeof window?.console<"u",_=typeof process<"u"&&!!process.stdout,c={label:"\x1B[35m",tag:"\x1B[36m",msg:"\x1B[0m",hint:"\x1B[2m",reset:"\x1B[0m",bold:"\x1B[1m"};u.addCustomHandler("WarnerOptions",e=>e&&typeof e=="object"&&(typeof e.level=="string"&&"silent summary full".split(" ").includes(e.level)||!e.level)&&(typeof e.maxWarnings=="number"||!e.maxWarnings)&&(typeof e.onWarn=="function"||!e.onWarn)&&(typeof e.onSummary=="function"||!e.onSummary)&&(typeof e.packageName=="string"||!e.packageName)),u.addCustomHandler("Warning",e=>e&&typeof e.message=="string"&&(typeof e.source=="string"||!e.source)&&(typeof e.hint=="string"||!e.hint)&&(typeof e.instantlyWarn=="boolean"||!e.instantlyWarn)&&(typeof e.tag=="string"||!e.tag)&&(typeof e.documentation=="string"||!e.documentation));class ${constructor(t={}){l.add(this),i.set(this,[]),r.set(this,{}),t.level=t.level??"summary",t.maxWarnings=Number(t.maxWarnings??20),t.onWarn=t.onWarn??(()=>{}),t.onSummary=t.onSummary??(()=>{}),t.packageName=t.packageName??"",g(this,r,t,"f")}get warnings(){return n(this,i,"f")}setLevel(t){["silent","summary","full"].includes(t)&&(n(this,r,"f").level=t)}setPackageName(t){n(this,r,"f").packageName=String(t)}clear(){g(this,i,[],"f")}count(){return n(this,i,"f").length}warn(t){if(u.for([t]).check(["Warning"])){n(this,r,"f").maxWarnings&&n(this,i,"f").length<n(this,r,"f").maxWarnings&&n(this,i,"f").push(t);try{n(this,r,"f").onWarn?.(t)}catch{}if(t.instantlyWarn){n(this,l,"m",m).call(this,t);return}n(this,r,"f").level==="full"&&n(this,l,"m",m).call(this,t),n(this,r,"f").level}}finalize(){this.flush()}flush(){if(n(this,r,"f").level==="full"&&n(this,i,"f").forEach(t=>n(this,l,"m",m).call(this,t)),n(this,r,"f").level==="summary"){try{n(this,r,"f").onSummary?.(n(this,i,"f").length,[...n(this,i,"f")])}catch{}const t=n(this,i,"f").length,a=n(this,r,"f").maxWarnings;console.log(W?`${a&&t>a?`${a}+`:String(t)} warnings collected`:`${t} warnings collected`)}}}i=new WeakMap,r=new WeakMap,l=new WeakSet,d=function(t){const a=[],s=n(this,r,"f").packageName?`${n(this,r,"f").packageName}: `:"",f=`${t.tag?`[${t.tag}] `:t.source?`[${t.source}] `:""}${s}${t.message}`;return a.push(f,"background:#222;color:#fff;padding:2px 6px;border-radius:4px;font-weight:700;"),t.hint&&a.push(`
2
- Hint: ${t.hint}`,"color:#888;font-style:italic;"),t.documentation&&a.push(`
3
- Documentation: ${t.documentation}`,"color:#0af;font-weight:600;"),a},y=function(t){const a=[],s=t.tag?`${c.tag}[${t.tag}]${c.reset} `:t.source?`${c.tag}[${t.source}]${c.reset} `:"",o=n(this,r,"f").packageName?`${c.label}${n(this,r,"f").packageName}${c.reset}: `:"";return a.push(`${s}${o}${c.bold}${t.message}${c.reset}`),t.hint&&a.push(`${c.hint}Hint: ${t.hint}${c.reset}`),t.documentation&&a.push(`Documentation: ${t.documentation}`),a.join(`
4
- `)},m=function(t){if(W){const a=n(this,l,"m",d).call(this,t);let s="%c"+a[0];const o=[a[1]];let f="";for(let h=2;h<a.length;h+=2)f+="%c"+a[h-1],o.push(a[h]);f&&(s+=f),console.warn(s,...o);return}if(_){console.warn(n(this,l,"m",y).call(this,t));return}console.warn(`${n(this,r,"f").packageName?n(this,r,"f").packageName+": ":""}${t.message}`)};var b=$;const x=new $({level:"summary"});export{b as default,x as warner};
1
+ /**
2
+ * Warning collector for briklab modules
3
+ */
4
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
5
+ if (kind === "m") throw new TypeError("Private method is not writable");
6
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
7
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
8
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
9
+ };
10
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
11
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
12
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
13
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
14
+ };
15
+ var _Warner_instances, _Warner_warnings, _Warner_options, _Warner_formatForBrowser, _Warner_formatForNode, _Warner_print;
16
+ import JSTC from "../jstc/index.js";
17
+ const IS_BROWSER = typeof window !== "undefined" && typeof window?.console !== "undefined";
18
+ const IS_NODE = typeof process !== "undefined" && !!process.stdout;
19
+ const NODE_STYLES = {
20
+ label: "\x1b[35m",
21
+ tag: "\x1b[36m",
22
+ msg: "\x1b[0m",
23
+ hint: "\x1b[2m",
24
+ reset: "\x1b[0m",
25
+ bold: "\x1b[1m",
26
+ };
27
+ JSTC.addCustomHandler("WarnerOptions", (p) => {
28
+ return (p &&
29
+ typeof p === "object" &&
30
+ ((typeof p.level === "string" && "silent summary full".split(" ").includes(p.level)) || !(p.level)) &&
31
+ (typeof p.maxWarnings === "number" || !(p.maxWarnings)) &&
32
+ (typeof p.onWarn === "function" || !(p.onWarn)) &&
33
+ (typeof p.onSummary === "function" || !(p.onSummary)) &&
34
+ (typeof p.packageName === "string" || !(p.packageName)));
35
+ });
36
+ JSTC.addCustomHandler("Warning", (p) => {
37
+ return (p &&
38
+ typeof p.message === "string" &&
39
+ (typeof p.source === "string" || !p.source) &&
40
+ (typeof p.hint === "string" || !p.hint) &&
41
+ (typeof p.instantlyWarn === "boolean" || !p.instantlyWarn) &&
42
+ (typeof p.tag === "string" || !p.tag) &&
43
+ (typeof p.documentation === "string" || !p.documentation));
44
+ });
45
+ /**
46
+ * A Warner instance
47
+ */
48
+ class Warner {
49
+ constructor(options = {}) {
50
+ _Warner_instances.add(this);
51
+ _Warner_warnings.set(this, []);
52
+ _Warner_options.set(this, {});
53
+ options.level = options.level ?? "summary";
54
+ options.maxWarnings = Number(options.maxWarnings ?? 20);
55
+ options.onWarn = options.onWarn ?? (() => { });
56
+ options.onSummary = options.onSummary ?? (() => { });
57
+ options.packageName = options.packageName ?? "";
58
+ __classPrivateFieldSet(this, _Warner_options, options, "f");
59
+ }
60
+ get warnings() {
61
+ return __classPrivateFieldGet(this, _Warner_warnings, "f");
62
+ }
63
+ setLevel(level) {
64
+ if (["silent", "summary", "full"].includes(level))
65
+ __classPrivateFieldGet(this, _Warner_options, "f").level = level;
66
+ }
67
+ setPackageName(name) {
68
+ __classPrivateFieldGet(this, _Warner_options, "f").packageName = String(name);
69
+ }
70
+ clear() {
71
+ __classPrivateFieldSet(this, _Warner_warnings, [], "f");
72
+ }
73
+ count() {
74
+ return __classPrivateFieldGet(this, _Warner_warnings, "f").length;
75
+ }
76
+ warn(warning) {
77
+ if (!JSTC.for([warning]).check(["Warning"]))
78
+ return;
79
+ if (__classPrivateFieldGet(this, _Warner_options, "f").maxWarnings && __classPrivateFieldGet(this, _Warner_warnings, "f").length < __classPrivateFieldGet(this, _Warner_options, "f").maxWarnings) {
80
+ __classPrivateFieldGet(this, _Warner_warnings, "f").push(warning);
81
+ }
82
+ try {
83
+ __classPrivateFieldGet(this, _Warner_options, "f").onWarn?.(warning);
84
+ }
85
+ catch (e) {
86
+ }
87
+ if (warning.instantlyWarn) {
88
+ __classPrivateFieldGet(this, _Warner_instances, "m", _Warner_print).call(this, warning);
89
+ return;
90
+ }
91
+ if (__classPrivateFieldGet(this, _Warner_options, "f").level === "full")
92
+ __classPrivateFieldGet(this, _Warner_instances, "m", _Warner_print).call(this, warning);
93
+ if (__classPrivateFieldGet(this, _Warner_options, "f").level === "summary") {
94
+ }
95
+ }
96
+ /**
97
+ * Finalize all warnings and log summary if needed
98
+ */
99
+ finalize() {
100
+ this.flush();
101
+ }
102
+ flush() {
103
+ if (__classPrivateFieldGet(this, _Warner_options, "f").level === "full") {
104
+ __classPrivateFieldGet(this, _Warner_warnings, "f").forEach((w) => __classPrivateFieldGet(this, _Warner_instances, "m", _Warner_print).call(this, w));
105
+ }
106
+ if (__classPrivateFieldGet(this, _Warner_options, "f").level === "summary") {
107
+ try {
108
+ __classPrivateFieldGet(this, _Warner_options, "f").onSummary?.(__classPrivateFieldGet(this, _Warner_warnings, "f").length, [...__classPrivateFieldGet(this, _Warner_warnings, "f")]);
109
+ }
110
+ catch (e) { }
111
+ const count = __classPrivateFieldGet(this, _Warner_warnings, "f").length;
112
+ const max = __classPrivateFieldGet(this, _Warner_options, "f").maxWarnings;
113
+ if (IS_BROWSER) {
114
+ console.log(`${max ? (count > max ? `${max}+` : String(count)) : String(count)} warnings collected`);
115
+ }
116
+ else {
117
+ console.log(`${count} warnings collected`);
118
+ }
119
+ }
120
+ }
121
+ }
122
+ _Warner_warnings = new WeakMap(), _Warner_options = new WeakMap(), _Warner_instances = new WeakSet(), _Warner_formatForBrowser = function _Warner_formatForBrowser(w) {
123
+ const lines = [];
124
+ const label = __classPrivateFieldGet(this, _Warner_options, "f").packageName ? `${__classPrivateFieldGet(this, _Warner_options, "f").packageName}: ` : "";
125
+ const tagOrSource = w.tag ? `[${w.tag}] ` : w.source ? `[${w.source}] ` : "";
126
+ const header = `${tagOrSource}${label}${w.message}`;
127
+ const cssHeader = "background:#222;color:#fff;padding:2px 6px;border-radius:4px;font-weight:700;";
128
+ lines.push(header, cssHeader);
129
+ if (w.hint) {
130
+ lines.push(`\nHint: ${w.hint}`, "color:#888;font-style:italic;");
131
+ }
132
+ if (w.documentation) {
133
+ lines.push(`\nDocumentation: ${w.documentation}`, "color:#0af;font-weight:600;");
134
+ }
135
+ return lines;
136
+ }, _Warner_formatForNode = function _Warner_formatForNode(w) {
137
+ const parts = [];
138
+ const t = w.tag ? `${NODE_STYLES.tag}[${w.tag}]${NODE_STYLES.reset} ` : w.source ? `${NODE_STYLES.tag}[${w.source}]${NODE_STYLES.reset} ` : "";
139
+ const pkg = __classPrivateFieldGet(this, _Warner_options, "f").packageName ? `${NODE_STYLES.label}${__classPrivateFieldGet(this, _Warner_options, "f").packageName}${NODE_STYLES.reset}: ` : "";
140
+ parts.push(`${t}${pkg}${NODE_STYLES.bold}${w.message}${NODE_STYLES.reset}`);
141
+ if (w.hint)
142
+ parts.push(`${NODE_STYLES.hint}Hint: ${w.hint}${NODE_STYLES.reset}`);
143
+ if (w.documentation)
144
+ parts.push(`Documentation: ${w.documentation}`);
145
+ return parts.join("\n");
146
+ }, _Warner_print = function _Warner_print(w) {
147
+ if (IS_BROWSER) {
148
+ const args = __classPrivateFieldGet(this, _Warner_instances, "m", _Warner_formatForBrowser).call(this, w);
149
+ let fmt = "%c" + args[0];
150
+ const cssArgs = [args[1]];
151
+ let extraFmt = "";
152
+ for (let i = 2; i < args.length; i += 2) {
153
+ extraFmt += "%c" + args[i - 1];
154
+ cssArgs.push(args[i]);
155
+ }
156
+ if (extraFmt)
157
+ fmt += extraFmt;
158
+ console.warn(fmt, ...cssArgs);
159
+ return;
160
+ }
161
+ if (IS_NODE) {
162
+ console.warn(__classPrivateFieldGet(this, _Warner_instances, "m", _Warner_formatForNode).call(this, w));
163
+ return;
164
+ }
165
+ console.warn(`${__classPrivateFieldGet(this, _Warner_options, "f").packageName ? __classPrivateFieldGet(this, _Warner_options, "f").packageName + ': ' : ''}${w.message}`);
166
+ };
167
+ export default Warner;
168
+ export const warner = new Warner({ level: "summary" });
169
+ // TODO: complete this warner bro
package/package.json CHANGED
@@ -34,7 +34,7 @@
34
34
  "repository": {
35
35
  "url": "https://github.com/EkaanshPC/briklab-stdlib"
36
36
  },
37
- "version": "1.1.10",
37
+ "version": "1.2.0-test",
38
38
  "devDependencies": {
39
39
  "@types/cssom": "^0.4.3",
40
40
  "@types/node": "^25.1.0",
@@ -71,8 +71,7 @@
71
71
  "cssom": "^0.5.0"
72
72
  },
73
73
  "scripts": {
74
- "build": "tsc && pnpm minify",
75
- "minify": "node build.js",
74
+ "build": "tsc",
76
75
  "test:smoke": "pnpm run build && node ./test-dist.js"
77
76
  }
78
77
  }