chalker 1.3.0 → 2.0.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/LICENSE CHANGED
@@ -1,11 +1,201 @@
1
- Licensed under the Apache License, Version 2.0 (the "License");
2
- you may not use this file except in compliance with the License.
3
- You may obtain a copy of the License at
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
4
 
5
- http://www.apache.org/licenses/LICENSE-2.0
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
6
 
7
- Unless required by applicable law or agreed to in writing, software
8
- distributed under the License is distributed on an "AS IS" BASIS,
9
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
- See the License for the specific language governing permissions and
11
- limitations under the License.
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2019 Joel Chen
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,5 +1,4 @@
1
- [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url]
2
- [![Dependency Status][daviddm-image]][daviddm-url] [![devDependency Status][daviddm-dev-image]][daviddm-dev-url]
1
+ [![NPM version][npm-image]][npm-url]
3
2
 
4
3
  # chalker
5
4
 
@@ -8,7 +7,7 @@ Set ansi colors in strings using `<>` markers and [chalk] or [ansi-colors].
8
7
  # Usage
9
8
 
10
9
  ```js
11
- const chalker = require("chalker");
10
+ import chalker from "chalker";
12
11
 
13
12
  console.log(chalker("<red.bgGreen>Red on Green Text</>"));
14
13
 
@@ -110,7 +109,7 @@ chalker(str, [chalkInstance]);
110
109
 
111
110
  - `str` - String with chalker color markers
112
111
  - `chalkInstance` - Optional custom instance of [chalk].
113
- - ie: created from `new chalk.constructor({level: 2})`
112
+ - ie: created from `new chalk.Instance({level: 2})`
114
113
 
115
114
  **Returns:** A string with terminal/ansi color codes
116
115
 
@@ -119,12 +118,21 @@ chalker(str, [chalkInstance]);
119
118
  ### `chalker.CHALK`
120
119
 
121
120
  ```js
122
- chalker.CHALK = require("ansi-colors");
121
+ import ansiColors from "ansi-colors";
122
+ chalker.CHALK = ansiColors;
123
123
  ```
124
124
 
125
125
  Set the default colors library. By default, `chalker` loads `chalk` first and falls back to
126
126
  [ansi-colors].
127
127
 
128
+ > `chalker` is published as an ESM-only package (`"type": "module"`). It can still be loaded
129
+ > from CommonJS with `require("chalker")` on Node >=22.12, but since `require()` of an ESM
130
+ > module returns the module's namespace object, you need to access `.default`:
131
+ >
132
+ > ```js
133
+ > const chalker = require("chalker").default;
134
+ > ```
135
+
128
136
  ### `chalker.remove`
129
137
 
130
138
  ```js
@@ -160,11 +168,5 @@ Licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses
160
168
  [ansi-colors]: https://www.npmjs.com/package/ansi-colors
161
169
  [chalk]: https://www.npmjs.com/package/chalk
162
170
  [chalk advanced colors]: https://github.com/chalk/chalk#256-and-truecolor-color-support
163
- [travis-image]: https://travis-ci.org/jchip/chalker.svg?branch=master
164
- [travis-url]: https://travis-ci.org/jchip/chalker
165
171
  [npm-image]: https://badge.fury.io/js/chalker.svg
166
172
  [npm-url]: https://npmjs.org/package/chalker
167
- [daviddm-image]: https://david-dm.org/jchip/chalker/status.svg
168
- [daviddm-url]: https://david-dm.org/jchip/chalker
169
- [daviddm-dev-image]: https://david-dm.org/jchip/chalker/dev-status.svg
170
- [daviddm-dev-url]: https://david-dm.org/jchip/chalker?type=dev
@@ -0,0 +1,4 @@
1
+ export type { ChalkerFn } from "./core.ts";
2
+ export { makeChalker } from "./core.ts";
3
+ declare const _default: import("./core.ts").ChalkerFn;
4
+ export default _default;
@@ -0,0 +1,14 @@
1
+ import colors from "ansi-colors";
2
+ import { makeChalker } from "./core.js";
3
+ export { makeChalker } from "./core.js";
4
+ //
5
+ // Static entry: colors come from a hard `import` of ansi-colors.
6
+ //
7
+ // The ansi-colors counterpart of `chalker/chalk` - same trade: no top-level await, no
8
+ // runtime-computed specifier, so bundlers resolve it and CJS consumers are not blocked by an
9
+ // async module. See `./chalk.ts` for the longer rationale.
10
+ //
11
+ // `ansi-colors` is a peer dependency. Importing this entry without it installed is a resolve
12
+ // error at import time, which is the intended, explicit failure.
13
+ //
14
+ export default makeChalker(colors);
@@ -0,0 +1,4 @@
1
+ export type { ChalkerFn } from "./core.ts";
2
+ export { makeChalker } from "./core.ts";
3
+ declare const _default: import("./core.ts").ChalkerFn;
4
+ export default _default;
package/dist/chalk.js ADDED
@@ -0,0 +1,18 @@
1
+ import chalk from "chalk";
2
+ import { makeChalker } from "./core.js";
3
+ export { makeChalker } from "./core.js";
4
+ //
5
+ // Static entry: colors come from a hard `import` of chalk.
6
+ //
7
+ // Use this when you know chalk is there. Compared to the default entry it has no top-level
8
+ // await and no runtime-computed specifier, which means:
9
+ //
10
+ // - a bundler resolves chalk statically and inlines it, instead of leaving a dynamic
11
+ // `import()` that fails at runtime when nothing installed chalk next to the bundle
12
+ // - a consumer that already imports chalk itself shares that exact module instance, so there
13
+ // is one chalk with one color-support state rather than two
14
+ //
15
+ // `chalk` is a peer dependency. Importing this entry without it installed is a resolve error
16
+ // at import time, which is the intended, explicit failure.
17
+ //
18
+ export default makeChalker(chalk);
package/dist/core.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ type AnyColors = any;
2
+ export type ChalkerFn = {
3
+ (s?: string | readonly string[] | null, ...args: unknown[]): string;
4
+ remove: (s: string, keepHtml?: boolean) => string;
5
+ decodeHtml: (s: string) => string;
6
+ CHALK: AnyColors;
7
+ };
8
+ /**
9
+ * Build a chalker bound to a specific colors module.
10
+ *
11
+ * Each entry point calls this with the colors it obtained, so no two entries share mutable
12
+ * state: `.CHALK` belongs to the returned instance and can be reassigned on it alone.
13
+ *
14
+ * @param colors - a chalk or ansi-colors module (namespace or default export, either works)
15
+ * @returns the chalker function
16
+ */
17
+ export declare function makeChalker(colors: AnyColors): ChalkerFn;
18
+ export {};
package/dist/core.js ADDED
@@ -0,0 +1,256 @@
1
+ import assert from "node:assert";
2
+ import colorConvert from "color-convert";
3
+ function deQuote(str, marker) {
4
+ const q = str[0];
5
+ if (q === `'` || q === `"` || q === "`") {
6
+ // remove enclosing quotes ', ", or ` if they are present
7
+ assert(str.endsWith(q), `chalk ${marker} param must be enclosed with matching quote ${q}`);
8
+ str = str.substr(1, str.length - 2);
9
+ }
10
+ return str;
11
+ }
12
+ // https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
13
+ // https://en.wikipedia.org/wiki/Universal_Coded_Character_Set
14
+ const htmlEntities = {
15
+ [`&quot;`]: `"`,
16
+ [`&amp;`]: "&",
17
+ [`&apos;`]: "'",
18
+ [`&lt;`]: "<",
19
+ [`&gt;`]: ">",
20
+ [`&nbsp;`]: "\xa0",
21
+ [`&copy;`]: "\xa9",
22
+ [`&reg;`]: "\xae"
23
+ };
24
+ function normalizeColors(colorsModule) {
25
+ const colors = colorsModule &&
26
+ colorsModule.default &&
27
+ (typeof colorsModule.default === "function" || typeof colorsModule.default === "object")
28
+ ? colorsModule.default
29
+ : colorsModule;
30
+ return addAnsiColorsCompat(colors);
31
+ }
32
+ function addAnsiColorsCompat(colors) {
33
+ if (!colors || typeof colors.alias !== "function" || typeof colors.rgb === "function") {
34
+ return colors;
35
+ }
36
+ colors.rgb = function (r, g, b) {
37
+ return this[defineAnsiColor(colors, "rgb", [r, g, b])];
38
+ };
39
+ colors.bgRgb = function (r, g, b) {
40
+ return this[defineAnsiColor(colors, "bgRgb", [r, g, b], true)];
41
+ };
42
+ colors.hex = function (value) {
43
+ return this.rgb.apply(this, colorConvert.hex.rgb(value));
44
+ };
45
+ colors.bgHex = function (value) {
46
+ return this.bgRgb.apply(this, colorConvert.hex.rgb(value));
47
+ };
48
+ return colors;
49
+ }
50
+ function defineAnsiColor(colors, name, values, bg) {
51
+ const styleName = `chalker_${name}_${values.join("_")}`;
52
+ if (!colors.styles[styleName]) {
53
+ const prefix = bg ? 48 : 38;
54
+ const close = bg ? 49 : 39;
55
+ colors.alias(styleName, (text) => `\u001b[${prefix};2;${values.join(";")}m${text}\u001b[${close}m`);
56
+ }
57
+ return styleName;
58
+ }
59
+ function convertColorModel(name, values) {
60
+ const bg = name.startsWith("bg");
61
+ const model = bg ? name[2].toLowerCase() + name.substring(3) : name;
62
+ const rgb = model === "keyword"
63
+ ? colorConvert.keyword.rgb(String(values[0]).toLowerCase())
64
+ : colorConvert[model] && colorConvert[model].rgb.apply(colorConvert[model], values);
65
+ assert(rgb, `unknown color ${values[0]}`);
66
+ return { name: bg ? "bgRgb" : "rgb", values: rgb };
67
+ }
68
+ function applyChalkMethod(chalkInstance, name, values) {
69
+ if (typeof chalkInstance[name] === "function") {
70
+ return chalkInstance[name].apply(chalkInstance, values);
71
+ }
72
+ if (name === "keyword" ||
73
+ name === "bgKeyword" ||
74
+ name === "hsl" ||
75
+ name === "bgHsl" ||
76
+ name === "hsv" ||
77
+ name === "bgHsv" ||
78
+ name === "hwb" ||
79
+ name === "bgHwb") {
80
+ const converted = convertColorModel(name, values);
81
+ return chalkInstance[converted.name].apply(chalkInstance, converted.values);
82
+ }
83
+ throw new TypeError(`${name} is not a chalk function`);
84
+ }
85
+ function decodeHtml(str) {
86
+ return str.replace(/&[\w#]+;/g, m => {
87
+ if (Object.prototype.hasOwnProperty.call(htmlEntities, m))
88
+ return htmlEntities[m];
89
+ if (m.startsWith("&#x")) {
90
+ const s = m.substring(3, m.length - 1);
91
+ const p = parseInt(s, 16);
92
+ return String.fromCodePoint(p);
93
+ }
94
+ if (m.startsWith("&#")) {
95
+ const s = m.substring(2, m.length - 1);
96
+ const p = parseInt(s, 10);
97
+ return String.fromCodePoint(p);
98
+ }
99
+ return m;
100
+ });
101
+ }
102
+ function applyChalkMarkers(markers, text, userChalk) {
103
+ const chalkify = markers
104
+ .trim()
105
+ .split(".")
106
+ .reduce((a, marker) => {
107
+ marker = marker.trim();
108
+ if (a[marker]) {
109
+ // a basic color found
110
+ return a[marker];
111
+ }
112
+ else if (marker.startsWith("#")) {
113
+ // a hex value
114
+ return a.hex(marker);
115
+ }
116
+ else if ((marker[2] === "#" || marker[3] === "#") && marker.startsWith("bg")) {
117
+ // a bgHex value, `bg#`, `bg-#`, `bg #`
118
+ // no need to extract only the #HHHHHH part since chalk seems to deal with
119
+ // the value in the form of text#HHHHHH
120
+ return a.bgHex(marker);
121
+ }
122
+ const openIx = marker.indexOf("(");
123
+ if (openIx >= 0) {
124
+ // apply other advanced colors when ( is found
125
+ const closeIx = marker.lastIndexOf(")");
126
+ assert(closeIx > openIx, `marker ${marker} missing matching ()`);
127
+ // extract name if there're something before (
128
+ let name = openIx > 0 && marker.substring(0, openIx).trim();
129
+ // extract values within ()
130
+ let values = marker.substring(openIx + 1, closeIx).trim();
131
+ if (values.indexOf(",") >= 0) {
132
+ // extract rgb/hsl/hsv/hwb values like (255, 10, 20)
133
+ values = values.split(",").map(x => parseInt(x.trim(), 10));
134
+ // default no name to rgb, and bg to bgRgb
135
+ if (!name)
136
+ name = "rgb";
137
+ else if (name === "bg")
138
+ name = "bgRgb";
139
+ }
140
+ else {
141
+ // extract a string (with or without quotes) to use for keyword
142
+ values = [deQuote(values.trim(), marker)];
143
+ // default no name to keyword, and bg to bgKeyword
144
+ if (!name)
145
+ name = "keyword";
146
+ else if (name === "bg")
147
+ name = "bgKeyword";
148
+ }
149
+ try {
150
+ a = applyChalkMethod(a, name, values);
151
+ }
152
+ catch (err) {
153
+ throw new Error(`marker ${marker} is invalid: calling chalk.${name} failed with: ${err.message}`);
154
+ }
155
+ }
156
+ else {
157
+ // if not found as a basic color, then try with chalk.keyword or chalk.bgKeyword
158
+ try {
159
+ const kw = deQuote(marker, marker);
160
+ if (kw.startsWith("bg-") || kw.startsWith("bg ")) {
161
+ a = applyChalkMethod(a, "bgKeyword", [kw.substring(3)]);
162
+ }
163
+ else {
164
+ a = applyChalkMethod(a, "keyword", [kw]);
165
+ }
166
+ }
167
+ catch (err) {
168
+ throw new Error(`marker ${marker} is not found and invalid as a keyword`);
169
+ }
170
+ }
171
+ assert(a, `marker ${marker} is invalid`);
172
+ return a;
173
+ }, userChalk);
174
+ assert(typeof chalkify === "function", `final chalk value is not a function after applying ${markers}`);
175
+ return chalkify(text);
176
+ }
177
+ // remove the color marker like <red>text</> from strings
178
+ function remove(s, keepHtml) {
179
+ const r = s.replace(/<[^>]*>/g, "").trim();
180
+ return keepHtml ? r : decodeHtml(r);
181
+ }
182
+ function format(s, instance, userChalk) {
183
+ // read CHALK off the instance at call time - it is public and settable
184
+ userChalk = normalizeColors(userChalk || instance.CHALK);
185
+ // skip applying ansi colors if chalk says color support is off
186
+ if (userChalk.supportsColor === false) {
187
+ return remove(s);
188
+ }
189
+ const tks = s && s.match(/(<[^>]+>|[^<>]+)/g);
190
+ // empty string "" result in null from match
191
+ // but other strings w/o matches gets ['original-string']
192
+ if (!tks)
193
+ return s || "";
194
+ const colorized = tks.reduceRight((a, e, ix) => {
195
+ const lvl = a[a.length - 1];
196
+ // text
197
+ if (e[0] !== "<") {
198
+ lvl.s = e + lvl.s;
199
+ return a;
200
+ }
201
+ // close marker
202
+ if (e[1] === "/") {
203
+ a.push({ mk: e.substring(2, e.length - 1), ix, s: "" });
204
+ return a;
205
+ }
206
+ // open marker
207
+ // markers balance check
208
+ if (a.length === 1) {
209
+ const partial = tks.slice(0, ix).join("") + `[${tks[ix]}]` + (tks.length > ix + 1 ? "..." : "");
210
+ throw new Error(`unbalanced open/close markers: ${partial}`);
211
+ }
212
+ // markers match check
213
+ const mk = e.substring(1, e.length - 1);
214
+ if (lvl.mk && mk !== lvl.mk) {
215
+ const partial = tks.slice(0, ix).join("") +
216
+ `[** ${tks[ix]} **]` +
217
+ tks.slice(ix + 1, lvl.ix).join("") +
218
+ `[** ${tks[lvl.ix]} **]`;
219
+ throw new Error(`mismatch markers: ${partial}`);
220
+ }
221
+ // apply marker and update result at previous level
222
+ const t = applyChalkMarkers(mk, lvl.s, userChalk);
223
+ a.pop();
224
+ const nl = a.length - 1;
225
+ a[nl].s = t + a[nl].s;
226
+ return a;
227
+ }, [{ s: "" }]);
228
+ return decodeHtml(colorized[0].s);
229
+ }
230
+ /**
231
+ * Build a chalker bound to a specific colors module.
232
+ *
233
+ * Each entry point calls this with the colors it obtained, so no two entries share mutable
234
+ * state: `.CHALK` belongs to the returned instance and can be reassigned on it alone.
235
+ *
236
+ * @param colors - a chalk or ansi-colors module (namespace or default export, either works)
237
+ * @returns the chalker function
238
+ */
239
+ export function makeChalker(colors) {
240
+ const chalker = ((s, ...args) => {
241
+ if (Array.isArray(s)) {
242
+ // template string tagging
243
+ let c = "";
244
+ let ix;
245
+ for (ix = 0; ix < args.length; ix++) {
246
+ c = c + s[ix] + String(args[ix]);
247
+ }
248
+ return format(c + s[ix], chalker);
249
+ }
250
+ return format(s, chalker, args[0]);
251
+ });
252
+ chalker.remove = remove;
253
+ chalker.decodeHtml = decodeHtml;
254
+ chalker.CHALK = normalizeColors(colors);
255
+ return chalker;
256
+ }
@@ -0,0 +1,4 @@
1
+ export type { ChalkerFn } from "./core.ts";
2
+ export { makeChalker } from "./core.ts";
3
+ declare const _default: import("./core.ts").ChalkerFn;
4
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,40 @@
1
+ import { makeOptionalImport } from "optional-import";
2
+ import { makeChalker } from "./core.js";
3
+ export { makeChalker } from "./core.js";
4
+ //
5
+ // The auto-detecting entry: take whichever of chalk / ansi-colors is installed.
6
+ //
7
+ // This is the historical default and stays the default. It costs a top-level await, which is
8
+ // what makes this entry unusable from `require()` (ERR_REQUIRE_ASYNC_MODULE) and what forces a
9
+ // bundler to leave the color module external -- the specifier is only known at runtime.
10
+ //
11
+ // If you know which colors module you have, import a static entry instead and pay neither cost:
12
+ //
13
+ // import ck from "chalker/chalk";
14
+ // import ck from "chalker/ansi-colors";
15
+ //
16
+ // optional import from this module's own context, used to optionally load
17
+ // chalk/ansi-colors without failing the whole module load when neither is installed.
18
+ //
19
+ // `import()` reaches both CJS and ESM, so this covers ESM-only chalk 5/6 as well as
20
+ // CJS-only ansi-colors -- `createRequire` could only ever load the latter.
21
+ const optionalImport = makeOptionalImport(import.meta);
22
+ async function loadColors() {
23
+ let colors = (await optionalImport("chalk")) || (await optionalImport("ansi-colors"));
24
+ if (!colors) {
25
+ // just go for chalk and let its module-not-found error propagate
26
+ colors = await optionalImport("chalk", {
27
+ notFound: err => {
28
+ throw err;
29
+ }
30
+ });
31
+ }
32
+ return colors;
33
+ }
34
+ // top-level await: consumers that statically import chalker have their own evaluation
35
+ // deferred until this settles, so the very first format call already has colors loaded.
36
+ //
37
+ // This is what makes this entry unusable from `require()` -- ERR_REQUIRE_ASYNC_MODULE. That is
38
+ // deliberate as of 2.0; loading ESM-only chalk cannot be done synchronously, so CJS consumers
39
+ // must use `await import("chalker")` -- or one of the static entries, which have no await.
40
+ export default makeChalker(await loadColors());
package/package.json CHANGED
@@ -1,16 +1,48 @@
1
1
  {
2
2
  "name": "chalker",
3
- "version": "1.3.0",
3
+ "version": "2.0.0",
4
4
  "description": "Set ansi colors in strings using XML and chalk",
5
- "main": "lib/index.js",
5
+ "type": "module",
6
+ "types": "./dist/index.d.ts",
7
+ "main": "./dist/index.js",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./chalk": {
14
+ "types": "./dist/chalk.d.ts",
15
+ "default": "./dist/chalk.js"
16
+ },
17
+ "./ansi-colors": {
18
+ "types": "./dist/ansi-colors.d.ts",
19
+ "default": "./dist/ansi-colors.js"
20
+ },
21
+ "./core": {
22
+ "types": "./dist/core.d.ts",
23
+ "default": "./dist/core.js"
24
+ },
25
+ "./package.json": "./package.json"
26
+ },
27
+ "sideEffects": false,
28
+ "engines": {
29
+ "node": ">=22.12.0"
30
+ },
31
+ "homepage": "https://github.com/jchip/fynjs/tree/main/packages/chalker",
32
+ "bugs": {
33
+ "url": "https://github.com/jchip/fynjs/issues"
34
+ },
6
35
  "repository": {
7
36
  "type": "git",
8
- "url": "https://github.com/jchip/chalker.git"
37
+ "url": "git+https://github.com/jchip/fynjs.git",
38
+ "directory": "packages/chalker"
9
39
  },
10
40
  "scripts": {
11
- "test": "xrun --serial test:unit test:demo",
41
+ "build": "rm -rf dist && tsc -p tsconfig.json",
42
+ "test": "npm run test:unit && npm run test:demo",
43
+ "ci:check": "tsc --noEmit -p tsconfig.json && npm test",
12
44
  "test:unit": "vitest run",
13
- "test:demo": "xrun --serial test:demo:legacy-cjs test:demo:ansi-colors-cjs test:demo:cjs-dynamic-import test:demo:esm-default test:demo:esm-namespace test:demo:esm-create-require test:demo:esm-named-export-probe",
45
+ "test:demo": "npm run test:demo:legacy-cjs && npm run test:demo:ansi-colors-cjs && npm run test:demo:cjs-dynamic-import && npm run test:demo:esm-default && npm run test:demo:esm-namespace && npm run test:demo:esm-create-require && npm run test:demo:esm-named-export-probe",
14
46
  "test:demo:legacy-cjs": "cd demo/legacy-cjs && fyn install && fyn test",
15
47
  "test:demo:ansi-colors-cjs": "cd demo/ansi-colors-cjs && fyn install && fyn test",
16
48
  "test:demo:cjs-dynamic-import": "cd demo/cjs-dynamic-import && fyn install && fyn test",
@@ -18,10 +50,12 @@
18
50
  "test:demo:esm-namespace": "cd demo/esm-namespace && fyn install && fyn test",
19
51
  "test:demo:esm-create-require": "cd demo/esm-create-require && fyn install && fyn test",
20
52
  "test:demo:esm-named-export-probe": "cd demo/esm-named-export-probe && fyn install && fyn test",
21
- "coverage": "vitest run --coverage"
53
+ "coverage": "vitest run --coverage",
54
+ "prepublishOnly": "npm run build",
55
+ "postpack": "publish-util-postpack"
22
56
  },
23
57
  "files": [
24
- "lib"
58
+ "dist"
25
59
  ],
26
60
  "keywords": [
27
61
  "string",
@@ -37,7 +71,7 @@
37
71
  "license": "Apache-2.0",
38
72
  "dependencies": {
39
73
  "color-convert": "^2.0.1",
40
- "optional-require": "^1.1.8"
74
+ "optional-import": "^1.0.1"
41
75
  },
42
76
  "peerDependencies": {
43
77
  "ansi-colors": ">=4",
@@ -50,17 +84,5 @@
50
84
  "chalk": {
51
85
  "optional": true
52
86
  }
53
- },
54
- "devDependencies": {
55
- "@vitest/coverage-v8": "4.1.5",
56
- "@xarc/run": "^2.3.0",
57
- "ansi-colors": "^4.1.3",
58
- "chalk": "^4.1.2",
59
- "prettier": "^2.0.2",
60
- "vitest": "4.1.5"
61
- },
62
- "prettier": {
63
- "printWidth": 100,
64
- "trailingComma": "none"
65
87
  }
66
88
  }
package/lib/index.js DELETED
@@ -1,347 +0,0 @@
1
- "use strict";
2
-
3
- /* eslint-disable complexity, max-statements, no-magic-numbers, prefer-template, prefer-spread */
4
-
5
- const assert = require("assert");
6
- const optionalRequire = require("optional-require")(require);
7
- const colorConvert = require("color-convert");
8
- const chalk = loadColors();
9
-
10
- //
11
- // convert color markers in a string to terminal/ansi color codes with chalk
12
- // color marker format is "<red>red text</red><blue.bold>blue bold text</blue.bold>"
13
- // the end marker can simply be "</>" also
14
- // the marker is converted to chalk methods directly, for example:
15
- // - chalk.red is called for "<red>"
16
- // - chalk.blue.bold is called for "<blue.bold>"
17
- //
18
- // More advanced colors can be applied with:
19
- //
20
- // <(r,g,b)>, <rgb(255,10,20)>
21
- // <bg(r,g,b)>, <bgRgb(255,10,20)>
22
- // <#FF0000>, <bg#0000FF>, <hex(#FF0000)>, <bgHex(#0000FF)>
23
- // <(orange)>, <keyword(orange)>, <keyword('orange')>,
24
- // <keyword("orange")>, <keyword(`orange`)>
25
- // <bg(orange)>, <bgKeyword(orange)>, <bgKeyword('orange')>,
26
- // <bgKeyword("orange")>, <bgKeyword(`orange`)>
27
- // <hsl(32,100,50)>, <hsv(32,100,100)>, <hwb(32,0,50)>
28
- //
29
- // any thing that's not found as a basic color is tried using chalk.keyword
30
- //
31
- // <orange>, <'orange'>, <"orange">, <`orange`>
32
- //
33
- // If it's prefixed with `"bg-"` or `"bg "` then it's tried using chalk.bgKeyword
34
- //
35
- // <bg-orange>, <bg orange>
36
- //
37
- // These can be comined with . in any order as long as they work with chalk
38
- //
39
- // ie: <#FF0000.bg#0000FF.orange.keyword()>
40
- //
41
-
42
- function deQuote(str, marker) {
43
- const q = str[0];
44
- if (q === `'` || q === `"` || q === "`") {
45
- // remove enclosing quotes ', ", or ` if they are present
46
- assert(str.endsWith(q), `chalk ${marker} param must be enclosed with matching quote ${q}`);
47
- str = str.substr(1, str.length - 2);
48
- }
49
-
50
- return str;
51
- }
52
-
53
- // https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
54
- // https://en.wikipedia.org/wiki/Universal_Coded_Character_Set
55
-
56
- const htmlEntities = {
57
- [`&quot;`]: `"`,
58
- [`&amp;`]: "&",
59
- [`&apos;`]: "'",
60
- [`&lt;`]: "<",
61
- [`&gt;`]: ">",
62
- [`&nbsp;`]: "\xa0",
63
- [`&copy;`]: "\xa9",
64
- [`&reg;`]: "\xae"
65
- };
66
-
67
- function loadColors() {
68
- const colors = optionalRequire("chalk") || optionalRequire("ansi-colors");
69
-
70
- if (!colors) {
71
- throw new Error("chalker requires either chalk or ansi-colors to be installed");
72
- }
73
-
74
- return normalizeColors(colors);
75
- }
76
-
77
- function normalizeColors(colorsModule) {
78
- const colors =
79
- colorsModule &&
80
- colorsModule.default &&
81
- (typeof colorsModule.default === "function" || typeof colorsModule.default === "object")
82
- ? colorsModule.default
83
- : colorsModule;
84
-
85
- return addAnsiColorsCompat(colors);
86
- }
87
-
88
- function addAnsiColorsCompat(colors) {
89
- if (!colors || typeof colors.alias !== "function" || typeof colors.rgb === "function") {
90
- return colors;
91
- }
92
-
93
- colors.rgb = function (r, g, b) {
94
- return this[defineAnsiColor(colors, "rgb", [r, g, b])];
95
- };
96
- colors.bgRgb = function (r, g, b) {
97
- return this[defineAnsiColor(colors, "bgRgb", [r, g, b], true)];
98
- };
99
- colors.hex = function (value) {
100
- return this.rgb.apply(this, colorConvert.hex.rgb(value));
101
- };
102
- colors.bgHex = function (value) {
103
- return this.bgRgb.apply(this, colorConvert.hex.rgb(value));
104
- };
105
-
106
- return colors;
107
- }
108
-
109
- function defineAnsiColor(colors, name, values, bg) {
110
- const styleName = `chalker_${name}_${values.join("_")}`;
111
-
112
- if (!colors.styles[styleName]) {
113
- const prefix = bg ? 48 : 38;
114
- const close = bg ? 49 : 39;
115
- colors.alias(
116
- styleName,
117
- (text) => `\u001b[${prefix};2;${values.join(";")}m${text}\u001b[${close}m`
118
- );
119
- }
120
-
121
- return styleName;
122
- }
123
-
124
- function convertColorModel(name, values) {
125
- const bg = name.startsWith("bg");
126
- const model = bg ? name[2].toLowerCase() + name.substring(3) : name;
127
- const rgb =
128
- model === "keyword"
129
- ? colorConvert.keyword.rgb(String(values[0]).toLowerCase())
130
- : colorConvert[model] && colorConvert[model].rgb.apply(colorConvert[model], values);
131
-
132
- assert(rgb, `unknown color ${values[0]}`);
133
-
134
- return { name: bg ? "bgRgb" : "rgb", values: rgb };
135
- }
136
-
137
- function applyChalkMethod(chalkInstance, name, values) {
138
- if (typeof chalkInstance[name] === "function") {
139
- return chalkInstance[name].apply(chalkInstance, values);
140
- }
141
-
142
- if (
143
- name === "keyword" ||
144
- name === "bgKeyword" ||
145
- name === "hsl" ||
146
- name === "bgHsl" ||
147
- name === "hsv" ||
148
- name === "bgHsv" ||
149
- name === "hwb" ||
150
- name === "bgHwb"
151
- ) {
152
- const converted = convertColorModel(name, values);
153
- return chalkInstance[converted.name].apply(chalkInstance, converted.values);
154
- }
155
-
156
- throw new TypeError(`${name} is not a chalk function`);
157
- }
158
-
159
- function decodeHtml(str) {
160
- return str.replace(/&[\w#]+;/g, (m) => {
161
- if (htmlEntities.hasOwnProperty(m)) return htmlEntities[m];
162
- if (m.startsWith("&#x")) {
163
- const s = m.substring(3, m.length - 1);
164
- const p = parseInt(s, 16);
165
- return String.fromCodePoint(p);
166
- }
167
- if (m.startsWith("&#")) {
168
- const s = m.substring(2, m.length - 1);
169
- const p = parseInt(s, 10);
170
- return String.fromCodePoint(p);
171
- }
172
- return m;
173
- });
174
- }
175
-
176
- function applyChalkMarkers(markers, text, userChalk) {
177
- const chalkify = markers
178
- .trim()
179
- .split(".")
180
- .reduce((a, marker) => {
181
- marker = marker.trim();
182
-
183
- if (a[marker]) {
184
- // a basic color found
185
- return a[marker];
186
- } else if (marker.startsWith("#")) {
187
- // a hex value
188
- return a.hex(marker);
189
- } else if ((marker[2] === "#" || marker[3] === "#") && marker.startsWith("bg")) {
190
- // a bgHex value, `bg#`, `bg-#`, `bg #`
191
- // no need to extract only the #HHHHHH part since chalk seems to deal with
192
- // the value in the form of text#HHHHHH
193
- return a.bgHex(marker);
194
- }
195
-
196
- const openIx = marker.indexOf("(");
197
- if (openIx >= 0) {
198
- // apply other advanced colors when ( is found
199
- const closeIx = marker.lastIndexOf(")");
200
- assert(closeIx > openIx, `marker ${marker} missing matching ()`);
201
-
202
- // extract name if there're something before (
203
- let name = openIx > 0 && marker.substring(0, openIx).trim();
204
-
205
- // extract values within ()
206
- let values = marker.substring(openIx + 1, closeIx).trim();
207
- if (values.indexOf(",") >= 0) {
208
- // extract rgb/hsl/hsv/hwb values like (255, 10, 20)
209
- values = values.split(",").map((x) => parseInt(x.trim(), 10));
210
-
211
- // default no name to rgb, and bg to bgRgb
212
- if (!name) name = "rgb";
213
- else if (name === "bg") name = "bgRgb";
214
- } else {
215
- // extract a string (with or without quotes) to use for keyword
216
- values = [deQuote(values.trim(), marker)];
217
-
218
- // default no name to keyword, and bg to bgKeyword
219
- if (!name) name = "keyword";
220
- else if (name === "bg") name = "bgKeyword";
221
- }
222
-
223
- try {
224
- a = applyChalkMethod(a, name, values);
225
- } catch (err) {
226
- throw new Error(
227
- `marker ${marker} is invalid: calling chalk.${name} failed with: ${err.message}`
228
- );
229
- }
230
- } else {
231
- // if not found as a basic color, then try with chalk.keyword or chalk.bgKeyword
232
- try {
233
- const kw = deQuote(marker, marker);
234
- if (kw.startsWith("bg-") || kw.startsWith("bg ")) {
235
- a = applyChalkMethod(a, "bgKeyword", [kw.substring(3)]);
236
- } else {
237
- a = applyChalkMethod(a, "keyword", [kw]);
238
- }
239
- } catch (err) {
240
- throw new Error(`marker ${marker} is not found and invalid as a keyword`);
241
- }
242
- }
243
-
244
- assert(a, `marker ${marker} is invalid`);
245
-
246
- return a;
247
- }, userChalk);
248
-
249
- assert(
250
- typeof chalkify === "function",
251
- `final chalk value is not a function after applying ${markers}`
252
- );
253
-
254
- return chalkify(text);
255
- }
256
-
257
- // remove the color marker like <red>text</> from strings
258
- function remove(s, keepHtml) {
259
- const r = s.replace(/<[^>]*>/g, "").trim();
260
- return keepHtml ? r : decodeHtml(r);
261
- }
262
-
263
- function format(s, userChalk) {
264
- userChalk = normalizeColors(userChalk || chalker.CHALK);
265
-
266
- // skip applying ansi colors if chalk says color support is off
267
- if (userChalk.supportsColor === false) {
268
- return remove(s);
269
- }
270
-
271
- const tks = s && s.match(/(<[^>]+>|[^<>]+)/g);
272
-
273
- // empty string "" result in null from match
274
- // but other strings w/o matches gets ['original-string']
275
- if (!tks) return s || "";
276
-
277
- const colorized = tks.reduceRight(
278
- (a, e, ix) => {
279
- const lvl = a[a.length - 1];
280
-
281
- // text
282
- if (e[0] !== "<") {
283
- lvl.s = e + lvl.s;
284
- return a;
285
- }
286
-
287
- // close marker
288
- if (e[1] === "/") {
289
- a.push({ mk: e.substring(2, e.length - 1), ix, s: "" });
290
- return a;
291
- }
292
-
293
- // open marker
294
-
295
- // markers balance check
296
- if (a.length === 1) {
297
- const partial =
298
- tks.slice(0, ix).join("") + `[${tks[ix]}]` + (tks.length > ix + 1 ? "..." : "");
299
- throw new Error(`unbalanced open/close markers: ${partial}`);
300
- }
301
-
302
- // markers match check
303
- const mk = e.substring(1, e.length - 1);
304
- if (lvl.mk && mk !== lvl.mk) {
305
- const partial =
306
- tks.slice(0, ix).join("") +
307
- `[** ${tks[ix]} **]` +
308
- tks.slice(ix + 1, lvl.ix).join("") +
309
- `[** ${tks[lvl.ix]} **]`;
310
- throw new Error(`mismatch markers: ${partial}`);
311
- }
312
-
313
- // apply marker and update result at previous level
314
- const t = applyChalkMarkers(mk, lvl.s, userChalk);
315
- a.pop();
316
- const nl = a.length - 1;
317
- a[nl].s = t + a[nl].s;
318
-
319
- return a;
320
- },
321
- [{ s: "" }]
322
- );
323
-
324
- return decodeHtml(colorized[0].s);
325
- }
326
-
327
- function chalker(s, ...args) {
328
- if (Array.isArray(s)) {
329
- // template string tagging
330
- let c = "";
331
- let ix;
332
- for (ix = 0; ix < args.length; ix++) {
333
- c = c + s[ix] + args[ix];
334
- }
335
- return format(c + s[ix]);
336
- }
337
-
338
- return format(s, ...args);
339
- }
340
-
341
- chalker.remove = remove;
342
-
343
- chalker.decodeHtml = decodeHtml;
344
-
345
- chalker.CHALK = chalk;
346
-
347
- module.exports = chalker;