@mark1russell7/text 0.0.9 → 0.0.11

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @mark1russell7/text
2
2
 
3
- Plain text helpers in seven groups: the escapes of a text for five targets, the English word forms and a word search. The other four groups are the text of a thrown value, the removal of secrets, lengths with cuts and padding, and marked parts.
3
+ Plain text helpers in nine groups: the escapes of a text for five targets, the English word forms and a word search. The next three groups are the order of texts, the text of a thrown value and the removal of secrets. The last three are lengths with cuts and padding, marked parts and a scan of HTML.
4
4
 
5
5
  ```sh
6
6
  pnpm add @mark1russell7/text
@@ -38,6 +38,19 @@ countOf(1024, "site"); // "1,024 sites"
38
38
  countOf(3, "match", "matches"); // "3 matches"
39
39
  ```
40
40
 
41
+ `listOf(parts, options?)` joins the parts into an English list. A comma goes between the parts, and the conjunction goes before the last part. The option `conjunction` sets the word, and its default is "and". With the option `serialComma`, a comma also goes before the conjunction in a list of three parts or more.
42
+
43
+ The entry `@mark1russell7/text/english` has `listOf` and `countOf`. The root entry has only `countOf`, to keep its size.
44
+
45
+ ```ts
46
+ import { listOf } from "@mark1russell7/text/english";
47
+
48
+ listOf([]); // ""
49
+ listOf(["a", "b"]); // "a and b"
50
+ listOf(["a", "b", "c"]); // "a, b and c"
51
+ listOf(["a", "b", "c"], { conjunction: "or", serialComma: true }); // "a, b, or c"
52
+ ```
53
+
41
54
  ## A word search
42
55
 
43
56
  `wordSearch(query)` gives a test of a text. A text agrees when it has each word of the search, in any order and in any case. A word can be a part of a longer word.
@@ -211,6 +224,27 @@ The parts obey these rules:
211
224
  - Two ranges that touch stay two parts. Two ranges that overlap become one part.
212
225
  - An empty range, an empty `find` and an empty text give no part with `hit`.
213
226
 
227
+ ## A scan of HTML
228
+
229
+ The entry `@mark1russell7/text/html` scans HTML for its text and its start tags, with no DOM. A check of a page uses it, for example for the text that a reader with no script gets, or for a `link` with `rel="icon"`.
230
+
231
+ - `scanHtml(html, options)` gives `text` and `elements`. Each element has its name in lower case, its attributes and the index of its `<`.
232
+ - The content of each element of `skip` gives no text and no element. The default `HTML_SKIP` is `script`, `style` and `template`.
233
+ - A comment, a tag, a doctype and a processing instruction each give one space, so two words in two elements stay two words.
234
+ - The content of a title or a text area is text with no tags.
235
+ - The scan is linear in the length of the HTML.
236
+
237
+ ```ts
238
+ import { scanHtml } from "@mark1russell7/text/html";
239
+
240
+ const { text, elements } = scanHtml('<h1>Title</h1><script>draw()</script><link rel="icon" href="/favicon.svg">');
241
+ text.replace(/\s+/g, " ").trim(); // "Title"
242
+ elements.some((element) => element.name === "link" && element.attributes["rel"] === "icon"); // true
243
+
244
+ // The text of the body for a reader with no script:
245
+ scanHtml("<html><head><title>T</title></head><body><noscript>On</noscript>Body</body></html>", { skip: ["head", "script", "style", "template", "noscript"] }).text; // " Body "
246
+ ```
247
+
214
248
  ## The copies that this package replaces
215
249
 
216
250
  The tests run 58 copies of these functions from other repositories of the owner. Each copy comes from a list of the duplication atlas, at a pinned commit. The file `test/copies.json` has each copy, and `test/differences.ts` has each difference from the function of this package, with its reason. A copy that is not in the list gives the same output on each of the 1000 test strings.
@@ -224,6 +258,7 @@ The tests also examine 18 copies of a cut with a mark, from a later list of the
224
258
  - `escapeMarkdown` does not change spaces. Four spaces at the start of a line make a code block.
225
259
  - `wordSearch` keeps accents, so "cafe" does not find "café".
226
260
  - `countOf` knows no irregular plural. Give the plural noun for each noun that does not add "s".
261
+ - `listOf` does not change the parts. A part with a comma makes a list that a reader cannot split again.
227
262
  - `errorMessage` gives only the message. It does not add the name of the error, its `cause` or its stack.
228
263
  - `redactSecrets` removes only the forms in its table. A secret in a JSON string with escapes, or in a different encoding, stays.
229
264
  - `findSecretShapes` knows only the shapes in its table. A token directly after a letter or a digit is not a match. A token of a service that is not in the table stays.
@@ -231,3 +266,7 @@ The tests also examine 18 copies of a cut with a mark, from a later list of the
231
266
  - In `pad`, a grapheme of the fill can join the text or the next copy of the fill. A combining mark and a lone regional indicator do this. Then the result has fewer graphemes than the width.
232
267
  - `partsAt` counts in code units, as `String.prototype.slice` does. A range can cut a surrogate pair or a grapheme.
233
268
  - The three functions count units, not the width on a screen. A wide character, for example 日, is one unit, as a narrow character is.
269
+ - `scanHtml` does not make a tree. It does not close an element with no end tag, and it does not move an element as a browser does.
270
+ - `scanHtml` keeps the character references of the text and of each attribute value. Thus `&amp;` stays as five characters.
271
+ - In `scanHtml`, a comment or a skipped element with no end is text. A browser hides the rest of the page in that case.
272
+ - In `scanHtml`, a tag in a word also gives a space. Thus `a<b>c</b>` gives the text `a c `.
@@ -0,0 +1,32 @@
1
+ /**
2
+ * This module has the English word forms: a count with a noun, and a list of parts. It is the entry
3
+ * `@mark1russell7/text/english`. The root entry has only `countOf`.
4
+ */
5
+ /**
6
+ * This function gives a count with a noun, for example "1 site" or "1,024 sites". Only the count 1 takes the singular
7
+ * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most
8
+ * three decimal places.
9
+ *
10
+ * @param count - The number of things.
11
+ * @param noun - The singular noun.
12
+ * @param plural - The plural noun. The default is the singular noun with the letter "s" at the end.
13
+ * @returns The count, a space and the noun.
14
+ */
15
+ export declare function countOf(count: number, noun: string, plural?: string): string;
16
+ /** The options of `listOf`. */
17
+ export interface ListOptions {
18
+ /** The word before the last part. The default is "and". */
19
+ readonly conjunction?: string;
20
+ /** With true, a comma also goes before the conjunction in a list of three parts or more. The default is false. */
21
+ readonly serialComma?: boolean;
22
+ }
23
+ /**
24
+ * This function joins the parts into an English list, for example "a", "a and b" or "a, b and c". A comma and a space go
25
+ * between the parts, and the conjunction goes before the last part. No part gives an empty text. The parts do not change.
26
+ *
27
+ * @param parts - The parts of the list, in their order.
28
+ * @param options - The conjunction and the serial comma.
29
+ * @returns The list as one text.
30
+ */
31
+ export declare function listOf(parts: readonly string[], options?: ListOptions): string;
32
+ //# sourceMappingURL=english.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"english.d.ts","names":[],"sources":["../src/english.ts"],"mappings":";;;;;;;;;;;;;;wBAegB,QAAQ,eAAe,cAAc;;iBAKpC;;WAEN;;WAEA;;;;;;;;;;wBAWK,OAAO,0BAA0B,UAAS"}
@@ -0,0 +1,35 @@
1
+ // src/english.ts
2
+ /**
3
+ * This module has the English word forms: a count with a noun, and a list of parts. It is the entry
4
+ * `@mark1russell7/text/english`. The root entry has only `countOf`.
5
+ */
6
+ /**
7
+ * This function gives a count with a noun, for example "1 site" or "1,024 sites". Only the count 1 takes the singular
8
+ * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most
9
+ * three decimal places.
10
+ *
11
+ * @param count - The number of things.
12
+ * @param noun - The singular noun.
13
+ * @param plural - The plural noun. The default is the singular noun with the letter "s" at the end.
14
+ * @returns The count, a space and the noun.
15
+ */
16
+ function countOf(count, noun, plural = `${noun}s`) {
17
+ return `${count.toLocaleString("en")} ${count === 1 ? noun : plural}`;
18
+ }
19
+ /**
20
+ * This function joins the parts into an English list, for example "a", "a and b" or "a, b and c". A comma and a space go
21
+ * between the parts, and the conjunction goes before the last part. No part gives an empty text. The parts do not change.
22
+ *
23
+ * @param parts - The parts of the list, in their order.
24
+ * @param options - The conjunction and the serial comma.
25
+ * @returns The list as one text.
26
+ */
27
+ function listOf(parts, options = {}) {
28
+ const { conjunction = "and", serialComma = false } = options;
29
+ if (parts.length < 2) return parts[0] ?? "";
30
+ const comma = serialComma && parts.length > 2 ? "," : "";
31
+ return `${parts.slice(0, -1).join(", ")}${comma} ${conjunction} ${parts[parts.length - 1]}`;
32
+ }
33
+ export { countOf, listOf };
34
+
35
+ //# sourceMappingURL=english.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"english.js","names":[],"sources":["../src/english.ts"],"sourcesContent":["/**\n * This module has the English word forms: a count with a noun, and a list of parts. It is the entry\n * `@mark1russell7/text/english`. The root entry has only `countOf`.\n */\n\n/**\n * This function gives a count with a noun, for example \"1 site\" or \"1,024 sites\". Only the count 1 takes the singular\n * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most\n * three decimal places.\n *\n * @param count - The number of things.\n * @param noun - The singular noun.\n * @param plural - The plural noun. The default is the singular noun with the letter \"s\" at the end.\n * @returns The count, a space and the noun.\n */\nexport function countOf(count: number, noun: string, plural = `${noun}s`): string {\n return `${count.toLocaleString(\"en\")} ${count === 1 ? noun : plural}`;\n}\n\n/** The options of `listOf`. */\nexport interface ListOptions {\n /** The word before the last part. The default is \"and\". */\n readonly conjunction?: string;\n /** With true, a comma also goes before the conjunction in a list of three parts or more. The default is false. */\n readonly serialComma?: boolean;\n}\n\n/**\n * This function joins the parts into an English list, for example \"a\", \"a and b\" or \"a, b and c\". A comma and a space go\n * between the parts, and the conjunction goes before the last part. No part gives an empty text. The parts do not change.\n *\n * @param parts - The parts of the list, in their order.\n * @param options - The conjunction and the serial comma.\n * @returns The list as one text.\n */\nexport function listOf(parts: readonly string[], options: ListOptions = {}): string {\n const { conjunction = \"and\", serialComma = false } = options;\n if (parts.length < 2) return parts[0] ?? \"\";\n const comma = serialComma && parts.length > 2 ? \",\" : \"\";\n return `${parts.slice(0, -1).join(\", \")}${comma} ${conjunction} ${parts[parts.length - 1]}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,SAAgB,QAAQ,OAAe,MAAc,SAAS,GAAG,KAAK,IAAY;CAChF,OAAO,GAAG,MAAM,eAAe,IAAI,EAAE,GAAG,UAAU,IAAI,OAAO;AAC/D;;;;;;;;;AAkBA,SAAgB,OAAO,OAA0B,UAAuB,CAAC,GAAW;CAClF,MAAM,EAAE,cAAc,OAAO,cAAc,UAAU;CACrD,IAAI,MAAM,SAAS,GAAG,OAAO,MAAM,MAAM;CACzC,MAAM,QAAQ,eAAe,MAAM,SAAS,IAAI,MAAM;CACtD,OAAO,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,IAAI,MAAM,GAAG,YAAY,GAAG,MAAM,MAAM,SAAS;AACzF"}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * This module scans HTML for its text and its start tags, with no DOM. A check of a page reads the text that a reader with
3
+ * no script gets. It also reads the elements of the page, for example an `h1` or a `link` with `rel="icon"`. The scan is
4
+ * linear in the length of the HTML. Thus a page with many starts of a comment and no end does not stop it.
5
+ */
6
+ /** A start tag that the scan found. */
7
+ export interface HtmlElement {
8
+ /** The name of the element, in lower case. */
9
+ readonly name: string;
10
+ /**
11
+ * The attributes of the start tag. Each name is in lower case. A value has no quotes, and its character references stay
12
+ * as in the HTML. An attribute with no value has an empty value. When a tag has a name two times, the first value counts.
13
+ */
14
+ readonly attributes: Readonly<Record<string, string>>;
15
+ /** The index of the "<" of the start tag in the HTML, in UTF-16 code units. */
16
+ readonly start: number;
17
+ }
18
+ /** The result of a scan of HTML. */
19
+ export interface HtmlScan {
20
+ /**
21
+ * The text of the HTML outside the tags, the comments and the skipped elements. Each tag, comment and skipped element
22
+ * gives one space, so two words in two elements stay two words. The white space and the character references stay as in the HTML.
23
+ */
24
+ readonly text: string;
25
+ /** The start tags outside the comments and the skipped elements, in the order of the HTML. The start tag of a skipped element is in the list. */
26
+ readonly elements: readonly HtmlElement[];
27
+ }
28
+ /** The options of `scanHtml`. */
29
+ export interface HtmlScanOptions {
30
+ /** The names of the elements whose content gives no text and no element. The default is `HTML_SKIP`. */
31
+ readonly skip?: readonly string[];
32
+ }
33
+ /** The elements that the scan skips by default. A script and a style hold code, not text, and a template is not on the page. */
34
+ export declare const HTML_SKIP: readonly string[];
35
+ /**
36
+ * This function scans HTML for its text and its start tags, from the left to the right, in one pass.
37
+ *
38
+ * - A comment, a tag, a doctype and a processing instruction give no text. Each gives one space.
39
+ * - The content of an element of `skip`, to its end tag, gives no text and no element.
40
+ * - The content of a script, a style, a title or a text area that the scan does not skip is text with no tags.
41
+ * - A "<" starts a tag only before a letter, "/", "!" or "?", as in HTML. Each other "<" is text, as in `1 < 2`.
42
+ * - A comment or a skipped element with no end is text, and the scan continues in it. A tag with no ">" ends the scan,
43
+ * and the rest of the HTML is text.
44
+ *
45
+ * @param html - The HTML, a document or a part of one.
46
+ * @param options - The elements to skip. The default is `HTML_SKIP`.
47
+ * @returns The text and the start tags.
48
+ */
49
+ export declare function scanHtml(html: string, options?: HtmlScanOptions): HtmlScan;
50
+ //# sourceMappingURL=html.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"html.d.ts","names":[],"sources":["../src/html.ts"],"mappings":";;;;;;iBAOiB;;WAEN;;;;;WAKA,YAAY,SAAS;;WAErB;;;iBAIM;;;;;WAKN;;WAEA,mBAAmB;;;iBAIb;;WAEN;;;qBAIE;;;;;;;;;;;;;;;wBAqGG,SAAS,cAAc,UAAS,kBAAuB"}
package/build/html.js ADDED
@@ -0,0 +1,162 @@
1
+ // src/html.ts
2
+ /** The elements that the scan skips by default. A script and a style hold code, not text, and a template is not on the page. */
3
+ const HTML_SKIP = Object.freeze([
4
+ "script",
5
+ "style",
6
+ "template"
7
+ ]);
8
+ /**
9
+ * The elements whose content has no tags. A "<" in a script, a title or a text area does not start a tag. The content of
10
+ * such an element that the scan does not skip is text.
11
+ */
12
+ const RAW_TEXT = [
13
+ "script",
14
+ "style",
15
+ "title",
16
+ "textarea",
17
+ "xmp",
18
+ "iframe",
19
+ "noembed",
20
+ "noframes"
21
+ ];
22
+ /** This function tells if a character is white space in HTML: space, tab, line feed, form feed or carriage return. */
23
+ const isSpace = (char) => char === " " || char === " " || char === "\n" || char === "\f" || char === "\r";
24
+ /** This function tells if a character ends the name of a tag: white space, "/", ">" or the end of the HTML. */
25
+ const endsName = (char) => char === "" || char === "/" || char === ">" || isSpace(char);
26
+ /**
27
+ * This function gives a search in a source. A text that is not after a position is not after a later position either. Thus
28
+ * the search keeps each failure and does not do it again, and a scan with many searches stays linear.
29
+ */
30
+ function searchIn(source) {
31
+ const missing = /* @__PURE__ */ new Map();
32
+ return (needle, from) => {
33
+ const least = missing.get(needle);
34
+ if (least !== void 0 && from >= least) return -1;
35
+ const index = source.indexOf(needle, from);
36
+ if (index === -1) missing.set(needle, from);
37
+ return index;
38
+ };
39
+ }
40
+ /** This function reads the start tag at `lt`. It gives undefined for a tag with no ">" after it. */
41
+ function readTag(html, lower, lt) {
42
+ let at = lt + 1;
43
+ while (!endsName(lower.charAt(at))) at += 1;
44
+ const name = lower.slice(lt + 1, at);
45
+ const attributes = /* @__PURE__ */ new Map();
46
+ while (at < lower.length) {
47
+ const char = lower.charAt(at);
48
+ if (char === ">") return {
49
+ element: {
50
+ name,
51
+ attributes: Object.fromEntries(attributes),
52
+ start: lt
53
+ },
54
+ end: at + 1
55
+ };
56
+ if (char === "/" || isSpace(char)) {
57
+ at += 1;
58
+ continue;
59
+ }
60
+ const from = at;
61
+ at += 1;
62
+ while (!endsName(lower.charAt(at)) && lower.charAt(at) !== "=") at += 1;
63
+ const key = lower.slice(from, at);
64
+ let value = "";
65
+ let next = at;
66
+ while (isSpace(lower.charAt(next))) next += 1;
67
+ if (lower.charAt(next) === "=") {
68
+ next += 1;
69
+ while (isSpace(lower.charAt(next))) next += 1;
70
+ const quote = lower.charAt(next);
71
+ if (quote === "\"" || quote === "'") {
72
+ const close = lower.indexOf(quote, next + 1);
73
+ if (close === -1) return void 0;
74
+ value = html.slice(next + 1, close);
75
+ at = close + 1;
76
+ } else {
77
+ at = next;
78
+ while (at < lower.length && lower.charAt(at) !== ">" && !isSpace(lower.charAt(at))) at += 1;
79
+ value = html.slice(next, at);
80
+ }
81
+ }
82
+ if (!attributes.has(key)) attributes.set(key, value);
83
+ }
84
+ }
85
+ /**
86
+ * This function gives the start and the end of the end tag of `name` at or after `from`, or undefined. The name of the end
87
+ * tag ends at white space, "/" or ">", and the tag ends at the next ">".
88
+ */
89
+ function endTagOf(lower, name, from, search) {
90
+ const needle = `</${name}`;
91
+ for (let start = search(needle, from); start !== -1; start = search(needle, start + 1)) {
92
+ if (!endsName(lower.charAt(start + needle.length)) || lower.charAt(start + needle.length) === "") continue;
93
+ const gt = search(">", start + needle.length);
94
+ return gt === -1 ? void 0 : {
95
+ start,
96
+ end: gt + 1
97
+ };
98
+ }
99
+ }
100
+ /**
101
+ * This function scans HTML for its text and its start tags, from the left to the right, in one pass.
102
+ *
103
+ * - A comment, a tag, a doctype and a processing instruction give no text. Each gives one space.
104
+ * - The content of an element of `skip`, to its end tag, gives no text and no element.
105
+ * - The content of a script, a style, a title or a text area that the scan does not skip is text with no tags.
106
+ * - A "<" starts a tag only before a letter, "/", "!" or "?", as in HTML. Each other "<" is text, as in `1 < 2`.
107
+ * - A comment or a skipped element with no end is text, and the scan continues in it. A tag with no ">" ends the scan,
108
+ * and the rest of the HTML is text.
109
+ *
110
+ * @param html - The HTML, a document or a part of one.
111
+ * @param options - The elements to skip. The default is `HTML_SKIP`.
112
+ * @returns The text and the start tags.
113
+ */
114
+ function scanHtml(html, options = {}) {
115
+ const skip = new Set((options.skip ?? HTML_SKIP).map((name) => name.toLowerCase()));
116
+ const lower = html.replace(/[A-Z]+/g, (upper) => upper.toLowerCase());
117
+ const search = searchIn(lower);
118
+ const unclosed = /* @__PURE__ */ new Set();
119
+ const parts = [];
120
+ const elements = [];
121
+ let at = 0;
122
+ for (let lt = search("<", 0); lt !== -1; lt = search("<", Math.max(at, lt + 1))) {
123
+ const next = lower.charAt(lt + 1);
124
+ let end;
125
+ if (lower.startsWith("<!--", lt)) {
126
+ const close = search("-->", lt + 2);
127
+ if (close === -1) continue;
128
+ end = close + 3;
129
+ } else if (next === "/" || next === "!" || next === "?") {
130
+ const gt = search(">", lt + 2);
131
+ if (gt === -1) break;
132
+ end = gt + 1;
133
+ } else if (next >= "a" && next <= "z") {
134
+ const tag = readTag(html, lower, lt);
135
+ if (tag === void 0) break;
136
+ elements.push(tag.element);
137
+ end = tag.end;
138
+ const { name } = tag.element;
139
+ const skipped = skip.has(name);
140
+ if ((skipped || RAW_TEXT.includes(name)) && !unclosed.has(name)) {
141
+ const close = endTagOf(lower, name, end, search);
142
+ if (close === void 0) unclosed.add(name);
143
+ else {
144
+ parts.push(html.slice(at, lt), " ");
145
+ if (!skipped) parts.push(html.slice(end, close.start), " ");
146
+ at = close.end;
147
+ continue;
148
+ }
149
+ }
150
+ } else continue;
151
+ parts.push(html.slice(at, lt), " ");
152
+ at = end;
153
+ }
154
+ parts.push(html.slice(at));
155
+ return {
156
+ text: parts.join(""),
157
+ elements
158
+ };
159
+ }
160
+ export { HTML_SKIP, scanHtml };
161
+
162
+ //# sourceMappingURL=html.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"html.js","names":[],"sources":["../src/html.ts"],"sourcesContent":["/**\n * This module scans HTML for its text and its start tags, with no DOM. A check of a page reads the text that a reader with\n * no script gets. It also reads the elements of the page, for example an `h1` or a `link` with `rel=\"icon\"`. The scan is\n * linear in the length of the HTML. Thus a page with many starts of a comment and no end does not stop it.\n */\n\n/** A start tag that the scan found. */\nexport interface HtmlElement {\n /** The name of the element, in lower case. */\n readonly name: string;\n /**\n * The attributes of the start tag. Each name is in lower case. A value has no quotes, and its character references stay\n * as in the HTML. An attribute with no value has an empty value. When a tag has a name two times, the first value counts.\n */\n readonly attributes: Readonly<Record<string, string>>;\n /** The index of the \"<\" of the start tag in the HTML, in UTF-16 code units. */\n readonly start: number;\n}\n\n/** The result of a scan of HTML. */\nexport interface HtmlScan {\n /**\n * The text of the HTML outside the tags, the comments and the skipped elements. Each tag, comment and skipped element\n * gives one space, so two words in two elements stay two words. The white space and the character references stay as in the HTML.\n */\n readonly text: string;\n /** The start tags outside the comments and the skipped elements, in the order of the HTML. The start tag of a skipped element is in the list. */\n readonly elements: readonly HtmlElement[];\n}\n\n/** The options of `scanHtml`. */\nexport interface HtmlScanOptions {\n /** The names of the elements whose content gives no text and no element. The default is `HTML_SKIP`. */\n readonly skip?: readonly string[];\n}\n\n/** The elements that the scan skips by default. A script and a style hold code, not text, and a template is not on the page. */\nexport const HTML_SKIP: readonly string[] = Object.freeze([\"script\", \"style\", \"template\"]);\n\n/**\n * The elements whose content has no tags. A \"<\" in a script, a title or a text area does not start a tag. The content of\n * such an element that the scan does not skip is text.\n */\nconst RAW_TEXT: readonly string[] = [\"script\", \"style\", \"title\", \"textarea\", \"xmp\", \"iframe\", \"noembed\", \"noframes\"];\n\n/** This function tells if a character is white space in HTML: space, tab, line feed, form feed or carriage return. */\nconst isSpace = (char: string): boolean => char === \" \" || char === \"\\t\" || char === \"\\n\" || char === \"\\f\" || char === \"\\r\";\n\n/** This function tells if a character ends the name of a tag: white space, \"/\", \">\" or the end of the HTML. */\nconst endsName = (char: string): boolean => char === \"\" || char === \"/\" || char === \">\" || isSpace(char);\n\n/** A search for the first index of a text at or after a position, or -1. */\ntype Search = (needle: string, from: number) => number;\n\n/**\n * This function gives a search in a source. A text that is not after a position is not after a later position either. Thus\n * the search keeps each failure and does not do it again, and a scan with many searches stays linear.\n */\nfunction searchIn(source: string): Search {\n const missing = new Map<string, number>();\n return (needle, from) => {\n const least = missing.get(needle);\n if (least !== undefined && from >= least) return -1;\n const index = source.indexOf(needle, from);\n if (index === -1) missing.set(needle, from);\n return index;\n };\n}\n\n/** This function reads the start tag at `lt`. It gives undefined for a tag with no \">\" after it. */\nfunction readTag(html: string, lower: string, lt: number): { element: HtmlElement; end: number } | undefined {\n let at = lt + 1;\n while (!endsName(lower.charAt(at))) at += 1;\n const name = lower.slice(lt + 1, at);\n const attributes = new Map<string, string>();\n while (at < lower.length) {\n const char = lower.charAt(at);\n if (char === \">\") return { element: { name, attributes: Object.fromEntries(attributes), start: lt }, end: at + 1 };\n if (char === \"/\" || isSpace(char)) {\n at += 1;\n continue;\n }\n // A name of an attribute ends at white space, \"/\", \">\" or \"=\". A \"=\" at its start is a part of the name.\n const from = at;\n at += 1;\n while (!endsName(lower.charAt(at)) && lower.charAt(at) !== \"=\") at += 1;\n const key = lower.slice(from, at);\n let value = \"\";\n let next = at;\n while (isSpace(lower.charAt(next))) next += 1;\n if (lower.charAt(next) === \"=\") {\n next += 1;\n while (isSpace(lower.charAt(next))) next += 1;\n const quote = lower.charAt(next);\n if (quote === '\"' || quote === \"'\") {\n const close = lower.indexOf(quote, next + 1);\n if (close === -1) return undefined;\n value = html.slice(next + 1, close);\n at = close + 1;\n } else {\n at = next;\n while (at < lower.length && lower.charAt(at) !== \">\" && !isSpace(lower.charAt(at))) at += 1;\n value = html.slice(next, at);\n }\n }\n if (!attributes.has(key)) attributes.set(key, value);\n }\n return undefined;\n}\n\n/**\n * This function gives the start and the end of the end tag of `name` at or after `from`, or undefined. The name of the end\n * tag ends at white space, \"/\" or \">\", and the tag ends at the next \">\".\n */\nfunction endTagOf(lower: string, name: string, from: number, search: Search): { start: number; end: number } | undefined {\n const needle = `</${name}`;\n for (let start = search(needle, from); start !== -1; start = search(needle, start + 1)) {\n if (!endsName(lower.charAt(start + needle.length)) || lower.charAt(start + needle.length) === \"\") continue;\n const gt = search(\">\", start + needle.length);\n return gt === -1 ? undefined : { start, end: gt + 1 };\n }\n return undefined;\n}\n\n/**\n * This function scans HTML for its text and its start tags, from the left to the right, in one pass.\n *\n * - A comment, a tag, a doctype and a processing instruction give no text. Each gives one space.\n * - The content of an element of `skip`, to its end tag, gives no text and no element.\n * - The content of a script, a style, a title or a text area that the scan does not skip is text with no tags.\n * - A \"<\" starts a tag only before a letter, \"/\", \"!\" or \"?\", as in HTML. Each other \"<\" is text, as in `1 < 2`.\n * - A comment or a skipped element with no end is text, and the scan continues in it. A tag with no \">\" ends the scan,\n * and the rest of the HTML is text.\n *\n * @param html - The HTML, a document or a part of one.\n * @param options - The elements to skip. The default is `HTML_SKIP`.\n * @returns The text and the start tags.\n */\nexport function scanHtml(html: string, options: HtmlScanOptions = {}): HtmlScan {\n const skip = new Set((options.skip ?? HTML_SKIP).map((name) => name.toLowerCase()));\n // Only A to Z go to lower case, so each index of the copy is an index of the HTML.\n const lower = html.replace(/[A-Z]+/g, (upper) => upper.toLowerCase());\n const search = searchIn(lower);\n const unclosed = new Set<string>();\n const parts: string[] = [];\n const elements: HtmlElement[] = [];\n let at = 0;\n for (let lt = search(\"<\", 0); lt !== -1; lt = search(\"<\", Math.max(at, lt + 1))) {\n const next = lower.charAt(lt + 1);\n let end: number;\n if (lower.startsWith(\"<!--\", lt)) {\n // A comment can end at once: `<!-->` and `<!--->` are comments.\n const close = search(\"-->\", lt + 2);\n if (close === -1) continue;\n end = close + 3;\n } else if (next === \"/\" || next === \"!\" || next === \"?\") {\n const gt = search(\">\", lt + 2);\n if (gt === -1) break;\n end = gt + 1;\n } else if (next >= \"a\" && next <= \"z\") {\n const tag = readTag(html, lower, lt);\n if (tag === undefined) break;\n elements.push(tag.element);\n end = tag.end;\n const { name } = tag.element;\n const skipped = skip.has(name);\n if ((skipped || RAW_TEXT.includes(name)) && !unclosed.has(name)) {\n const close = endTagOf(lower, name, end, search);\n if (close === undefined) unclosed.add(name);\n else {\n parts.push(html.slice(at, lt), \" \");\n if (!skipped) parts.push(html.slice(end, close.start), \" \");\n at = close.end;\n continue;\n }\n }\n } else continue;\n parts.push(html.slice(at, lt), \" \");\n at = end;\n }\n parts.push(html.slice(at));\n return { text: parts.join(\"\"), elements };\n}\n"],"mappings":"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"}
package/build/index.d.ts CHANGED
@@ -2,22 +2,9 @@
2
2
  * The entry of `@mark1russell7/text`: plain text helpers. The first group is the escapes for HTML, attributes, regular
3
3
  * expressions, Markdown and GitHub Actions workflow commands. The other groups are the English word forms, a word
4
4
  * search and the text of a thrown value. The entry `@mark1russell7/text/redact` removes secrets from a text, and the entry
5
- * `@mark1russell7/text/order` has two orders of texts.
5
+ * `@mark1russell7/text/order` has two orders of texts. The entry `@mark1russell7/text/english` adds the list join `listOf`.
6
6
  */
7
- /**
8
- * This module has the English word forms.
9
- */
10
- /**
11
- * This function gives a count with a noun, for example "1 site" or "1,024 sites". Only the count 1 takes the singular
12
- * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most
13
- * three decimal places.
14
- *
15
- * @param count - The number of things.
16
- * @param noun - The singular noun.
17
- * @param plural - The plural noun. The default is the singular noun with the letter "s" at the end.
18
- * @returns The count, a space and the noun.
19
- */
20
- export declare function countOf(count: number, noun: string, plural?: string): string;
7
+ import { countOf } from "./english.js";
21
8
  /**
22
9
  * This module has the text of a thrown value.
23
10
  */
@@ -117,4 +104,5 @@ export declare function searchKey(text: string): string;
117
104
  * @returns The test of a text.
118
105
  */
119
106
  export declare function wordSearch(query: string): (text: string) => boolean;
107
+ export { countOf };
120
108
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/english.ts","../src/error.ts","../src/escape.ts","../src/search.ts"],"mappings":";;;;;;;;;;;;;;;;;;;wBAcgB,QAAQ,eAAe,cAAc;;;;;;;;;;;;;;;;;;wBCIrC,aAAa;;;;;;;;wBCHb,WAAW;;;;;;;;wBAWX,gBAAgB;;;;;;;;;wBAYhB,aAAa;;;;;;;;;;;;wBAeb,eAAe;;;;;;;;wBAWf,mBAAmB;;;;;;;;wBAWnB,uBAAuB;;;;;;;;;;;;;;;;;wBCnDvB,UAAU;;;;;;;;;;;wBAcV,WAAW,iBAAiB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/error.ts","../src/escape.ts","../src/search.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;wBAkBgB,aAAa;;;;;;;;wBCHb,WAAW;;;;;;;;wBAWX,gBAAgB;;;;;;;;;wBAYhB,aAAa;;;;;;;;;;;;wBAeb,eAAe;;;;;;;;wBAWf,mBAAmB;;;;;;;;wBAWnB,uBAAuB;;;;;;;;;;;;;;;;;wBCnDvB,UAAU;;;;;;;;;;;wBAcV,WAAW,iBAAiB"}
package/build/index.js CHANGED
@@ -1,21 +1,5 @@
1
+ import { countOf } from "./english.js";
1
2
  import { a as escapeWorkflowData, i as escapeRegExp, n as escapeHtml, o as escapeWorkflowProperty, r as escapeMarkdown, t as escapeAttribute } from "./escape-vfOeIxac.js";
2
- // src/english.ts
3
- /**
4
- * This module has the English word forms.
5
- */
6
- /**
7
- * This function gives a count with a noun, for example "1 site" or "1,024 sites". Only the count 1 takes the singular
8
- * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most
9
- * three decimal places.
10
- *
11
- * @param count - The number of things.
12
- * @param noun - The singular noun.
13
- * @param plural - The plural noun. The default is the singular noun with the letter "s" at the end.
14
- * @returns The count, a space and the noun.
15
- */
16
- function countOf(count, noun, plural = `${noun}s`) {
17
- return `${count.toLocaleString("en")} ${count === 1 ? noun : plural}`;
18
- }
19
3
  // src/error.ts
20
4
  /**
21
5
  * This module has the text of a thrown value.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/english.ts","../src/error.ts","../src/search.ts"],"sourcesContent":["/**\n * This module has the English word forms.\n */\n\n/**\n * This function gives a count with a noun, for example \"1 site\" or \"1,024 sites\". Only the count 1 takes the singular\n * noun. Each other count takes the plural noun, also 0 and -1. The count has the digit groups of English and at most\n * three decimal places.\n *\n * @param count - The number of things.\n * @param noun - The singular noun.\n * @param plural - The plural noun. The default is the singular noun with the letter \"s\" at the end.\n * @returns The count, a space and the noun.\n */\nexport function countOf(count: number, noun: string, plural = `${noun}s`): string {\n return `${count.toLocaleString(\"en\")} ${count === 1 ? noun : plural}`;\n}\n","/**\n * This module has the text of a thrown value.\n */\n\n/**\n * This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.\n *\n * - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error\n * from another realm (a `vm` context or an `iframe`) also gives its message.\n * - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of\n * `Object.prototype.toString` finds an `Error` of each realm.\n * - Each other value gives `String(value)`.\n * - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.\n * - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.\n *\n * @param error - The thrown value. It can be any value.\n * @returns The text of the value.\n */\nexport function errorMessage(error: unknown): string {\n try {\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n const message: unknown = error.message;\n if (typeof message === \"string\") return message;\n if (Object.prototype.toString.call(error) === \"[object Error]\") return String(message);\n }\n return String(error);\n } catch {\n // String() throws for an object with no prototype, for a toString that throws and for a message getter that throws.\n try {\n return Object.prototype.toString.call(error);\n } catch {\n // A revoked Proxy throws also here. The operator typeof never throws.\n return `[${typeof error}]`;\n }\n }\n}\n","/**\n * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,\n * in any order. The case of the letters is not significant.\n */\n\n/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */\nconst FINAL_SIGMA = /ς/gu;\n\n/**\n * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:\n *\n * 1. It applies the Unicode normalization NFKC. Thus the ligature \"fi\" agrees with \"fi\", and full-width letters agree\n * with ASCII letters.\n * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus \"ß\", \"ẞ\" and \"SS\" give\n * \"ss\".\n * 3. It changes the small final sigma \"ς\" to \"σ\", as Unicode case folding does.\n * 4. It applies NFKC again.\n *\n * The steps use no rules of a locale. Thus the Turkish \"İ\" gives \"i\" with a combining dot above (U+0307), and the\n * Turkish \"ı\" gives \"i\". The key of a key is the same key. Accents stay, so \"é\" does not agree with \"e\".\n *\n * @param text - The plain text.\n * @returns The search key of the text.\n */\nexport function searchKey(text: string): string {\n return text.normalize(\"NFKC\").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, \"σ\").normalize(\"NFKC\");\n}\n\n/**\n * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits\n * the key into words at each run of white space, the class `\\s` of a regular expression.\n *\n * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the\n * search \"art\" finds \"Party\". A search with no words agrees with each text.\n *\n * @param query - The search, as a person types it.\n * @returns The test of a text.\n */\nexport function wordSearch(query: string): (text: string) => boolean {\n const words = searchKey(query)\n .split(/\\s+/u)\n .filter((word) => word !== \"\");\n return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAgB,QAAQ,OAAe,MAAc,SAAS,GAAG,KAAK,IAAY;CAChF,OAAO,GAAG,MAAM,eAAe,IAAI,EAAE,GAAG,UAAU,IAAI,OAAO;AAC/D;;;;;;;;;;;;;;;;;;;ACEA,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa,OAAO;GACrE,MAAM,UAAmB,MAAM;GAC/B,IAAI,OAAO,YAAY,UAAU,OAAO;GACxC,IAAI,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM,kBAAkB,OAAO,OAAO,OAAO;EACvF;EACA,OAAO,OAAO,KAAK;CACrB,QAAQ;EAEN,IAAI;GACF,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK;EAC7C,QAAQ;GAEN,OAAO,IAAI,OAAO,MAAM;EAC1B;CACF;AACF;;;;;;;AC7BA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAkBpB,SAAgB,UAAU,MAAsB;CAC9C,OAAO,KAAK,UAAU,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,aAAa,GAAG,CAAC,CAAC,UAAU,MAAM;AACpH;;;;;;;;;;;AAYA,SAAgB,WAAW,OAA0C;CACnE,MAAM,QAAQ,UAAU,KAAK,CAAC,CAC3B,MAAM,MAAM,CAAC,CACb,QAAQ,SAAS,SAAS,EAAE;CAC/B,QAAQ,SAAS,MAAM,WAAW,KAAK,MAAM,OAAO,SAAS,UAAU,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC;AAC7F"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/error.ts","../src/search.ts"],"sourcesContent":["/**\n * This module has the text of a thrown value.\n */\n\n/**\n * This function gives the text of a thrown value, for a log line or a message on a screen. It does not throw.\n *\n * - An object with a `message` text gives that text. The check reads the field, not `instanceof Error`, so an error\n * from another realm (a `vm` context or an `iframe`) also gives its message.\n * - An `Error` with a `message` that is not a text gives `String(message)`. The brand check of\n * `Object.prototype.toString` finds an `Error` of each realm.\n * - Each other value gives `String(value)`.\n * - When `String` throws, the function gives the tag of `Object.prototype.toString`, for example `[object Object]`.\n * - A revoked `Proxy` gives its `typeof` in brackets: `[object]`.\n *\n * @param error - The thrown value. It can be any value.\n * @returns The text of the value.\n */\nexport function errorMessage(error: unknown): string {\n try {\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n const message: unknown = error.message;\n if (typeof message === \"string\") return message;\n if (Object.prototype.toString.call(error) === \"[object Error]\") return String(message);\n }\n return String(error);\n } catch {\n // String() throws for an object with no prototype, for a toString that throws and for a message getter that throws.\n try {\n return Object.prototype.toString.call(error);\n } catch {\n // A revoked Proxy throws also here. The operator typeof never throws.\n return `[${typeof error}]`;\n }\n }\n}\n","/**\n * This module has a word search of plain text. A text agrees with a search when the text has each word of the search,\n * in any order. The case of the letters is not significant.\n */\n\n/** The small final sigma. Unicode case folding changes it to the small sigma, so a word agrees in each position. */\nconst FINAL_SIGMA = /ς/gu;\n\n/**\n * This function gives the search key of a text. `wordSearch` compares the keys of texts. The function does these steps:\n *\n * 1. It applies the Unicode normalization NFKC. Thus the ligature \"fi\" agrees with \"fi\", and full-width letters agree\n * with ASCII letters.\n * 2. It applies the full lower case, then the full upper case, then the full lower case. Thus \"ß\", \"ẞ\" and \"SS\" give\n * \"ss\".\n * 3. It changes the small final sigma \"ς\" to \"σ\", as Unicode case folding does.\n * 4. It applies NFKC again.\n *\n * The steps use no rules of a locale. Thus the Turkish \"İ\" gives \"i\" with a combining dot above (U+0307), and the\n * Turkish \"ı\" gives \"i\". The key of a key is the same key. Accents stay, so \"é\" does not agree with \"e\".\n *\n * @param text - The plain text.\n * @returns The search key of the text.\n */\nexport function searchKey(text: string): string {\n return text.normalize(\"NFKC\").toLowerCase().toUpperCase().toLowerCase().replace(FINAL_SIGMA, \"σ\").normalize(\"NFKC\");\n}\n\n/**\n * This function gives the test of a search. The function makes the key of the search with `searchKey`. Then it splits\n * the key into words at each run of white space, the class `\\s` of a regular expression.\n *\n * The test tells if the key of a text contains each word, in any order. A word can be a part of a longer word, so the\n * search \"art\" finds \"Party\". A search with no words agrees with each text.\n *\n * @param query - The search, as a person types it.\n * @returns The test of a text.\n */\nexport function wordSearch(query: string): (text: string) => boolean {\n const words = searchKey(query)\n .split(/\\s+/u)\n .filter((word) => word !== \"\");\n return (text) => words.length === 0 || words.every((word) => searchKey(text).includes(word));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkBA,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa,OAAO;GACrE,MAAM,UAAmB,MAAM;GAC/B,IAAI,OAAO,YAAY,UAAU,OAAO;GACxC,IAAI,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM,kBAAkB,OAAO,OAAO,OAAO;EACvF;EACA,OAAO,OAAO,KAAK;CACrB,QAAQ;EAEN,IAAI;GACF,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK;EAC7C,QAAQ;GAEN,OAAO,IAAI,OAAO,MAAM;EAC1B;CACF;AACF;;;;;;;AC7BA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAkBpB,SAAgB,UAAU,MAAsB;CAC9C,OAAO,KAAK,UAAU,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,aAAa,GAAG,CAAC,CAAC,UAAU,MAAM;AACpH;;;;;;;;;;;AAYA,SAAgB,WAAW,OAA0C;CACnE,MAAM,QAAQ,UAAU,KAAK,CAAC,CAC3B,MAAM,MAAM,CAAC,CACb,QAAQ,SAAS,SAAS,EAAE;CAC/B,QAAQ,SAAS,MAAM,WAAW,KAAK,MAAM,OAAO,SAAS,UAAU,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC;AAC7F"}
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/text",
4
- "version": "0.0.9",
5
- "description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf), a word search (wordSearch), the text of a thrown value (errorMessage), the orders of texts by code units and by code points (compareCodeUnits, compareCodePoints), the removal of secrets (redactSecrets) and the shapes of tokens (findSecretShapes, redactSecretShapes, findSecretShapesInValue), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad), and the marked parts of a text (partsAt, partsOf).",
4
+ "version": "0.0.11",
5
+ "description": "Plain text helpers: the escapes for HTML, attributes, patterns, Markdown and workflow commands, English word forms (countOf, listOf), a word search (wordSearch), the text of a thrown value (errorMessage), the orders of texts by code units and by code points (compareCodeUnits, compareCodePoints), the removal of secrets (redactSecrets) and the shapes of tokens (findSecretShapes, redactSecretShapes, findSecretShapesInValue), and lengths in code units, code points and graphemes with truncation and padding (textLength, truncate, pad), the marked parts of a text (partsAt, partsOf), and a scan of HTML for its text and its start tags (scanHtml).",
6
6
  "keywords": [
7
7
  "text",
8
8
  "escape",
@@ -56,6 +56,14 @@
56
56
  "types": "./build/order.d.ts",
57
57
  "default": "./build/order.js"
58
58
  },
59
+ "./html": {
60
+ "types": "./build/html.d.ts",
61
+ "default": "./build/html.js"
62
+ },
63
+ "./english": {
64
+ "types": "./build/english.d.ts",
65
+ "default": "./build/english.js"
66
+ },
59
67
  "./package.json": "./package.json"
60
68
  },
61
69
  "files": [
package/src/english.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  /**
2
- * This module has the English word forms.
2
+ * This module has the English word forms: a count with a noun, and a list of parts. It is the entry
3
+ * `@mark1russell7/text/english`. The root entry has only `countOf`.
3
4
  */
4
5
 
5
6
  /**
@@ -15,3 +16,26 @@
15
16
  export function countOf(count: number, noun: string, plural = `${noun}s`): string {
16
17
  return `${count.toLocaleString("en")} ${count === 1 ? noun : plural}`;
17
18
  }
19
+
20
+ /** The options of `listOf`. */
21
+ export interface ListOptions {
22
+ /** The word before the last part. The default is "and". */
23
+ readonly conjunction?: string;
24
+ /** With true, a comma also goes before the conjunction in a list of three parts or more. The default is false. */
25
+ readonly serialComma?: boolean;
26
+ }
27
+
28
+ /**
29
+ * This function joins the parts into an English list, for example "a", "a and b" or "a, b and c". A comma and a space go
30
+ * between the parts, and the conjunction goes before the last part. No part gives an empty text. The parts do not change.
31
+ *
32
+ * @param parts - The parts of the list, in their order.
33
+ * @param options - The conjunction and the serial comma.
34
+ * @returns The list as one text.
35
+ */
36
+ export function listOf(parts: readonly string[], options: ListOptions = {}): string {
37
+ const { conjunction = "and", serialComma = false } = options;
38
+ if (parts.length < 2) return parts[0] ?? "";
39
+ const comma = serialComma && parts.length > 2 ? "," : "";
40
+ return `${parts.slice(0, -1).join(", ")}${comma} ${conjunction} ${parts[parts.length - 1]}`;
41
+ }
package/src/html.ts ADDED
@@ -0,0 +1,183 @@
1
+ /**
2
+ * This module scans HTML for its text and its start tags, with no DOM. A check of a page reads the text that a reader with
3
+ * no script gets. It also reads the elements of the page, for example an `h1` or a `link` with `rel="icon"`. The scan is
4
+ * linear in the length of the HTML. Thus a page with many starts of a comment and no end does not stop it.
5
+ */
6
+
7
+ /** A start tag that the scan found. */
8
+ export interface HtmlElement {
9
+ /** The name of the element, in lower case. */
10
+ readonly name: string;
11
+ /**
12
+ * The attributes of the start tag. Each name is in lower case. A value has no quotes, and its character references stay
13
+ * as in the HTML. An attribute with no value has an empty value. When a tag has a name two times, the first value counts.
14
+ */
15
+ readonly attributes: Readonly<Record<string, string>>;
16
+ /** The index of the "<" of the start tag in the HTML, in UTF-16 code units. */
17
+ readonly start: number;
18
+ }
19
+
20
+ /** The result of a scan of HTML. */
21
+ export interface HtmlScan {
22
+ /**
23
+ * The text of the HTML outside the tags, the comments and the skipped elements. Each tag, comment and skipped element
24
+ * gives one space, so two words in two elements stay two words. The white space and the character references stay as in the HTML.
25
+ */
26
+ readonly text: string;
27
+ /** The start tags outside the comments and the skipped elements, in the order of the HTML. The start tag of a skipped element is in the list. */
28
+ readonly elements: readonly HtmlElement[];
29
+ }
30
+
31
+ /** The options of `scanHtml`. */
32
+ export interface HtmlScanOptions {
33
+ /** The names of the elements whose content gives no text and no element. The default is `HTML_SKIP`. */
34
+ readonly skip?: readonly string[];
35
+ }
36
+
37
+ /** The elements that the scan skips by default. A script and a style hold code, not text, and a template is not on the page. */
38
+ export const HTML_SKIP: readonly string[] = Object.freeze(["script", "style", "template"]);
39
+
40
+ /**
41
+ * The elements whose content has no tags. A "<" in a script, a title or a text area does not start a tag. The content of
42
+ * such an element that the scan does not skip is text.
43
+ */
44
+ const RAW_TEXT: readonly string[] = ["script", "style", "title", "textarea", "xmp", "iframe", "noembed", "noframes"];
45
+
46
+ /** This function tells if a character is white space in HTML: space, tab, line feed, form feed or carriage return. */
47
+ const isSpace = (char: string): boolean => char === " " || char === "\t" || char === "\n" || char === "\f" || char === "\r";
48
+
49
+ /** This function tells if a character ends the name of a tag: white space, "/", ">" or the end of the HTML. */
50
+ const endsName = (char: string): boolean => char === "" || char === "/" || char === ">" || isSpace(char);
51
+
52
+ /** A search for the first index of a text at or after a position, or -1. */
53
+ type Search = (needle: string, from: number) => number;
54
+
55
+ /**
56
+ * This function gives a search in a source. A text that is not after a position is not after a later position either. Thus
57
+ * the search keeps each failure and does not do it again, and a scan with many searches stays linear.
58
+ */
59
+ function searchIn(source: string): Search {
60
+ const missing = new Map<string, number>();
61
+ return (needle, from) => {
62
+ const least = missing.get(needle);
63
+ if (least !== undefined && from >= least) return -1;
64
+ const index = source.indexOf(needle, from);
65
+ if (index === -1) missing.set(needle, from);
66
+ return index;
67
+ };
68
+ }
69
+
70
+ /** This function reads the start tag at `lt`. It gives undefined for a tag with no ">" after it. */
71
+ function readTag(html: string, lower: string, lt: number): { element: HtmlElement; end: number } | undefined {
72
+ let at = lt + 1;
73
+ while (!endsName(lower.charAt(at))) at += 1;
74
+ const name = lower.slice(lt + 1, at);
75
+ const attributes = new Map<string, string>();
76
+ while (at < lower.length) {
77
+ const char = lower.charAt(at);
78
+ if (char === ">") return { element: { name, attributes: Object.fromEntries(attributes), start: lt }, end: at + 1 };
79
+ if (char === "/" || isSpace(char)) {
80
+ at += 1;
81
+ continue;
82
+ }
83
+ // A name of an attribute ends at white space, "/", ">" or "=". A "=" at its start is a part of the name.
84
+ const from = at;
85
+ at += 1;
86
+ while (!endsName(lower.charAt(at)) && lower.charAt(at) !== "=") at += 1;
87
+ const key = lower.slice(from, at);
88
+ let value = "";
89
+ let next = at;
90
+ while (isSpace(lower.charAt(next))) next += 1;
91
+ if (lower.charAt(next) === "=") {
92
+ next += 1;
93
+ while (isSpace(lower.charAt(next))) next += 1;
94
+ const quote = lower.charAt(next);
95
+ if (quote === '"' || quote === "'") {
96
+ const close = lower.indexOf(quote, next + 1);
97
+ if (close === -1) return undefined;
98
+ value = html.slice(next + 1, close);
99
+ at = close + 1;
100
+ } else {
101
+ at = next;
102
+ while (at < lower.length && lower.charAt(at) !== ">" && !isSpace(lower.charAt(at))) at += 1;
103
+ value = html.slice(next, at);
104
+ }
105
+ }
106
+ if (!attributes.has(key)) attributes.set(key, value);
107
+ }
108
+ return undefined;
109
+ }
110
+
111
+ /**
112
+ * This function gives the start and the end of the end tag of `name` at or after `from`, or undefined. The name of the end
113
+ * tag ends at white space, "/" or ">", and the tag ends at the next ">".
114
+ */
115
+ function endTagOf(lower: string, name: string, from: number, search: Search): { start: number; end: number } | undefined {
116
+ const needle = `</${name}`;
117
+ for (let start = search(needle, from); start !== -1; start = search(needle, start + 1)) {
118
+ if (!endsName(lower.charAt(start + needle.length)) || lower.charAt(start + needle.length) === "") continue;
119
+ const gt = search(">", start + needle.length);
120
+ return gt === -1 ? undefined : { start, end: gt + 1 };
121
+ }
122
+ return undefined;
123
+ }
124
+
125
+ /**
126
+ * This function scans HTML for its text and its start tags, from the left to the right, in one pass.
127
+ *
128
+ * - A comment, a tag, a doctype and a processing instruction give no text. Each gives one space.
129
+ * - The content of an element of `skip`, to its end tag, gives no text and no element.
130
+ * - The content of a script, a style, a title or a text area that the scan does not skip is text with no tags.
131
+ * - A "<" starts a tag only before a letter, "/", "!" or "?", as in HTML. Each other "<" is text, as in `1 < 2`.
132
+ * - A comment or a skipped element with no end is text, and the scan continues in it. A tag with no ">" ends the scan,
133
+ * and the rest of the HTML is text.
134
+ *
135
+ * @param html - The HTML, a document or a part of one.
136
+ * @param options - The elements to skip. The default is `HTML_SKIP`.
137
+ * @returns The text and the start tags.
138
+ */
139
+ export function scanHtml(html: string, options: HtmlScanOptions = {}): HtmlScan {
140
+ const skip = new Set((options.skip ?? HTML_SKIP).map((name) => name.toLowerCase()));
141
+ // Only A to Z go to lower case, so each index of the copy is an index of the HTML.
142
+ const lower = html.replace(/[A-Z]+/g, (upper) => upper.toLowerCase());
143
+ const search = searchIn(lower);
144
+ const unclosed = new Set<string>();
145
+ const parts: string[] = [];
146
+ const elements: HtmlElement[] = [];
147
+ let at = 0;
148
+ for (let lt = search("<", 0); lt !== -1; lt = search("<", Math.max(at, lt + 1))) {
149
+ const next = lower.charAt(lt + 1);
150
+ let end: number;
151
+ if (lower.startsWith("<!--", lt)) {
152
+ // A comment can end at once: `<!-->` and `<!--->` are comments.
153
+ const close = search("-->", lt + 2);
154
+ if (close === -1) continue;
155
+ end = close + 3;
156
+ } else if (next === "/" || next === "!" || next === "?") {
157
+ const gt = search(">", lt + 2);
158
+ if (gt === -1) break;
159
+ end = gt + 1;
160
+ } else if (next >= "a" && next <= "z") {
161
+ const tag = readTag(html, lower, lt);
162
+ if (tag === undefined) break;
163
+ elements.push(tag.element);
164
+ end = tag.end;
165
+ const { name } = tag.element;
166
+ const skipped = skip.has(name);
167
+ if ((skipped || RAW_TEXT.includes(name)) && !unclosed.has(name)) {
168
+ const close = endTagOf(lower, name, end, search);
169
+ if (close === undefined) unclosed.add(name);
170
+ else {
171
+ parts.push(html.slice(at, lt), " ");
172
+ if (!skipped) parts.push(html.slice(end, close.start), " ");
173
+ at = close.end;
174
+ continue;
175
+ }
176
+ }
177
+ } else continue;
178
+ parts.push(html.slice(at, lt), " ");
179
+ at = end;
180
+ }
181
+ parts.push(html.slice(at));
182
+ return { text: parts.join(""), elements };
183
+ }
package/src/index.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * The entry of `@mark1russell7/text`: plain text helpers. The first group is the escapes for HTML, attributes, regular
3
3
  * expressions, Markdown and GitHub Actions workflow commands. The other groups are the English word forms, a word
4
4
  * search and the text of a thrown value. The entry `@mark1russell7/text/redact` removes secrets from a text, and the entry
5
- * `@mark1russell7/text/order` has two orders of texts.
5
+ * `@mark1russell7/text/order` has two orders of texts. The entry `@mark1russell7/text/english` adds the list join `listOf`.
6
6
  */
7
7
  export { countOf } from "./english.ts";
8
8
  export { errorMessage } from "./error.ts";