wikiparser-node 0.9.0 → 0.9.1-b

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.
Files changed (87) hide show
  1. package/bundle/bundle.min.js +38 -0
  2. package/extensions/editor.css +62 -0
  3. package/extensions/editor.js +328 -0
  4. package/extensions/ui.css +119 -0
  5. package/package.json +13 -12
  6. package/README.md +0 -39
  7. package/config/default.json +0 -832
  8. package/config/llwiki.json +0 -630
  9. package/config/moegirl.json +0 -729
  10. package/config/zhwiki.json +0 -1269
  11. package/index.js +0 -333
  12. package/lib/element.js +0 -611
  13. package/lib/node.js +0 -770
  14. package/lib/ranges.js +0 -130
  15. package/lib/text.js +0 -245
  16. package/lib/title.js +0 -83
  17. package/mixin/attributeParent.js +0 -117
  18. package/mixin/fixedToken.js +0 -40
  19. package/mixin/hidden.js +0 -21
  20. package/mixin/singleLine.js +0 -31
  21. package/mixin/sol.js +0 -54
  22. package/parser/brackets.js +0 -126
  23. package/parser/commentAndExt.js +0 -59
  24. package/parser/converter.js +0 -46
  25. package/parser/externalLinks.js +0 -33
  26. package/parser/hrAndDoubleUnderscore.js +0 -38
  27. package/parser/html.js +0 -42
  28. package/parser/links.js +0 -94
  29. package/parser/list.js +0 -59
  30. package/parser/magicLinks.js +0 -41
  31. package/parser/quotes.js +0 -64
  32. package/parser/selector.js +0 -177
  33. package/parser/table.js +0 -114
  34. package/src/arg.js +0 -207
  35. package/src/atom/hidden.js +0 -13
  36. package/src/atom/index.js +0 -43
  37. package/src/attribute.js +0 -470
  38. package/src/attributes.js +0 -453
  39. package/src/charinsert.js +0 -97
  40. package/src/converter.js +0 -176
  41. package/src/converterFlags.js +0 -284
  42. package/src/converterRule.js +0 -256
  43. package/src/extLink.js +0 -180
  44. package/src/gallery.js +0 -149
  45. package/src/hasNowiki/index.js +0 -44
  46. package/src/hasNowiki/pre.js +0 -40
  47. package/src/heading.js +0 -134
  48. package/src/html.js +0 -254
  49. package/src/imageParameter.js +0 -301
  50. package/src/imagemap.js +0 -199
  51. package/src/imagemapLink.js +0 -41
  52. package/src/index.js +0 -936
  53. package/src/link/category.js +0 -44
  54. package/src/link/file.js +0 -287
  55. package/src/link/galleryImage.js +0 -120
  56. package/src/link/index.js +0 -384
  57. package/src/magicLink.js +0 -149
  58. package/src/nested/choose.js +0 -24
  59. package/src/nested/combobox.js +0 -23
  60. package/src/nested/index.js +0 -93
  61. package/src/nested/references.js +0 -23
  62. package/src/nowiki/comment.js +0 -71
  63. package/src/nowiki/dd.js +0 -59
  64. package/src/nowiki/doubleUnderscore.js +0 -56
  65. package/src/nowiki/hr.js +0 -41
  66. package/src/nowiki/index.js +0 -56
  67. package/src/nowiki/list.js +0 -16
  68. package/src/nowiki/noinclude.js +0 -28
  69. package/src/nowiki/quote.js +0 -69
  70. package/src/onlyinclude.js +0 -64
  71. package/src/paramTag/index.js +0 -89
  72. package/src/paramTag/inputbox.js +0 -35
  73. package/src/parameter.js +0 -239
  74. package/src/syntax.js +0 -91
  75. package/src/table/index.js +0 -983
  76. package/src/table/td.js +0 -338
  77. package/src/table/tr.js +0 -319
  78. package/src/tagPair/ext.js +0 -148
  79. package/src/tagPair/include.js +0 -50
  80. package/src/tagPair/index.js +0 -126
  81. package/src/transclude.js +0 -843
  82. package/tool/index.js +0 -1202
  83. package/util/base.js +0 -17
  84. package/util/debug.js +0 -73
  85. package/util/diff.js +0 -76
  86. package/util/lint.js +0 -55
  87. package/util/string.js +0 -126
package/src/index.js DELETED
@@ -1,936 +0,0 @@
1
- 'use strict';
2
-
3
- /*
4
- * PHP解析器的步骤:
5
- * -1. 替换签名和`{{subst:}}`,参见Parser::preSaveTransform;这在revision中不可能保留,可以跳过
6
- * 0. 移除特定字符`\0`和`\x7F`,参见Parser::parse
7
- * 1. 注释/扩展标签('<'相关),参见Preprocessor_Hash::buildDomTreeArrayFromText和Sanitizer::decodeTagAttributes
8
- * 2. 模板/模板变量/标题,注意rightmost法则,以及`-{`和`[[`可以破坏`{{`或`{{{`语法,
9
- * 参见Preprocessor_Hash::buildDomTreeArrayFromText
10
- * 3. HTML标签(允许不匹配),参见Sanitizer::internalRemoveHtmlTags
11
- * 4. 表格,参见Parser::handleTables
12
- * 5. 水平线和状态开关,参见Parser::internalParse
13
- * 6. 内链,含文件和分类,参见Parser::handleInternalLinks2
14
- * 7. `'`,参见Parser::doQuotes
15
- * 8. 外链,参见Parser::handleExternalLinks
16
- * 9. ISBN、RFC(未来将废弃,不予支持)和自由外链,参见Parser::handleMagicLinks
17
- * 10. 段落和列表,参见BlockLevelPass::execute
18
- * 11. 转换,参见LanguageConverter::recursiveConvertTopLevel
19
- */
20
-
21
- /*
22
- * \0\d+.\x7F标记Token:
23
- * e: ExtToken
24
- * a: AttributeToken
25
- * c: CommentToken、NoIncludeToken和IncludeToken
26
- * !: `{{!}}`专用
27
- * {: `{{(!}}`专用
28
- * }: `{{!)}}`专用
29
- * -: `{{!-}}`专用
30
- * +: `{{!!}}`专用
31
- * ~: `{{=}}`专用
32
- * s: `{{{|subst:}}}`
33
- * m: `{{fullurl:}}`、`{{canonicalurl:}}`或`{{filepath:}}`
34
- * t: ArgToken或TranscludeToken
35
- * h: HeadingToken
36
- * x: HtmlToken
37
- * b: TableToken
38
- * r: HrToken
39
- * u: DoubleUnderscoreToken
40
- * l: LinkToken
41
- * q: QuoteToken
42
- * w: ExtLinkToken
43
- * d: ListToken
44
- * v: ConverterToken
45
- */
46
-
47
- const {text} = require('../util/string'),
48
- {externalUse} = require('../util/debug'),
49
- assert = require('assert/strict'),
50
- Ranges = require('../lib/ranges'),
51
- Parser = require('..'),
52
- AstElement = require('../lib/element'),
53
- AstText = require('../lib/text');
54
- const {MAX_STAGE, aliases} = Parser;
55
-
56
- /**
57
- * 所有节点的基类
58
- * @classdesc `{childNodes: ...(AstText|Token)}`
59
- */
60
- class Token extends AstElement {
61
- type = 'root';
62
- #stage = 0; // 解析阶段,参见顶部注释。只对plain Token有意义。
63
- #config;
64
- // 这个数组起两个作用:1. 数组中的Token会在build时替换`/\0\d+.\x7F/`标记;2. 数组中的Token会依次执行parseOnce和build方法。
65
- #accum;
66
- /** @type {boolean} */ #include;
67
- /** @type {Record<string, Ranges>} */ #acceptable;
68
- #protectedChildren = new Ranges();
69
-
70
- /**
71
- * 将维基语法替换为占位符
72
- * @param {number} n 解析阶段
73
- * @param {boolean} include 是否嵌入
74
- */
75
- #parseOnce = (n = this.#stage, include = false) => {
76
- if (n < this.#stage || !this.isPlain() || this.length === 0) {
77
- return this;
78
- }
79
- switch (n) {
80
- case 0:
81
- if (this.type === 'root') {
82
- this.#accum.shift();
83
- }
84
- this.#include = Boolean(include);
85
- this.#parseCommentAndExt(include);
86
- break;
87
- case 1:
88
- this.#parseBrackets();
89
- break;
90
- case 2:
91
- this.#parseHtml();
92
- break;
93
- case 3:
94
- this.#parseTable();
95
- break;
96
- case 4:
97
- this.#parseHrAndDoubleUndescore();
98
- break;
99
- case 5:
100
- this.#parseLinks();
101
- break;
102
- case 6:
103
- this.#parseQuotes();
104
- break;
105
-
106
- case 7:
107
- this.#parseExternalLinks();
108
- break;
109
- case 8:
110
- this.#parseMagicLinks();
111
- break;
112
- case 9:
113
- this.#parseList();
114
- break;
115
- case 10:
116
- this.#parseConverter();
117
- // no default
118
- }
119
- if (this.type === 'root') {
120
- for (const token of this.#accum) {
121
- token.getAttribute('parseOnce')(n, include);
122
- }
123
- }
124
- this.#stage++;
125
- return this;
126
- };
127
-
128
- /**
129
- * 重建wikitext
130
- * @template {string} T
131
- * @param {string} str 半解析的字符串
132
- * @param {T} type 返回类型
133
- * @complexity `n`
134
- * @returns {T extends 'string|text' ? string : (Token|AstText)[]}
135
- */
136
- #buildFromStr = (str, type) => {
137
- const nodes = str.split(/[\0\x7F]/u).map((s, i) => {
138
- if (i % 2 === 0) {
139
- return new AstText(s);
140
- } else if (isNaN(s.at(-1))) {
141
- return this.#accum[Number(s.slice(0, -1))];
142
- }
143
- throw new Error(`解析错误!未正确标记的 Token:${s}`);
144
- });
145
- if (type === 'string') {
146
- return nodes.map(String).join('');
147
- } else if (type === 'text') {
148
- return text(nodes);
149
- }
150
- return nodes;
151
- };
152
-
153
- /**
154
- * 将占位符替换为子Token
155
- * @complexity `n`
156
- */
157
- #build = () => {
158
- this.#stage = MAX_STAGE;
159
- const {length, firstChild} = this,
160
- str = String(firstChild);
161
- if (length === 1 && firstChild.type === 'text' && str.includes('\0')) {
162
- this.replaceChildren(...this.#buildFromStr(str));
163
- this.normalize();
164
- if (this.type === 'root') {
165
- for (const token of this.#accum) {
166
- token.getAttribute('build')();
167
- }
168
- }
169
- }
170
- };
171
-
172
- /**
173
- * 保护部分子节点不被移除
174
- * @param {...string|number|Range} args 子节点范围
175
- */
176
- #protectChildren = (...args) => {
177
- this.#protectedChildren.push(...new Ranges(args));
178
- };
179
-
180
- /** 所有图片,包括图库 */
181
- get images() {
182
- return this.querySelectorAll('file, gallery-image, imagemap-image');
183
- }
184
-
185
- /** 所有内链、外链和自由外链 */
186
- get links() {
187
- return this.querySelectorAll('link, ext-link, free-ext-link, image-parameter#link');
188
- }
189
-
190
- /** 所有模板和模块 */
191
- get embeds() {
192
- return this.querySelectorAll('template, magic-word#invoke');
193
- }
194
-
195
- /**
196
- * @param {string} wikitext wikitext
197
- * @param {accum} accum
198
- * @param {acceptable} acceptable 可接受的子节点设置
199
- */
200
- constructor(wikitext, config = Parser.getConfig(), halfParsed = false, accum = [], acceptable = undefined) {
201
- super();
202
- if (typeof wikitext === 'string') {
203
- this.insertAt(halfParsed ? wikitext : wikitext.replace(/[\0\x7F]/gu, ''));
204
- }
205
- this.#config = config;
206
- this.#accum = accum;
207
- this.setAttribute('acceptable', acceptable);
208
- accum.push(this);
209
- }
210
-
211
- /**
212
- * @override
213
- * @template {string} T
214
- * @param {T} key 属性键
215
- * @returns {TokenAttribute<T>}
216
- */
217
- getAttribute(key) {
218
- switch (key) {
219
- case 'config':
220
- return structuredClone(this.#config);
221
- case 'accum':
222
- return this.#accum;
223
- case 'parseOnce':
224
- return this.#parseOnce;
225
- case 'buildFromStr':
226
- return this.#buildFromStr;
227
- case 'build':
228
- return this.#build;
229
- case 'include': {
230
- if (this.#include !== undefined) {
231
- return this.#include;
232
- }
233
- const root = this.getRootNode();
234
- if (root.type === 'root' && root !== this) {
235
- return root.getAttribute('include');
236
- }
237
- const includeToken = root.querySelector('include');
238
- if (includeToken) {
239
- return includeToken.name === 'noinclude';
240
- }
241
- const noincludeToken = root.querySelector('noinclude');
242
- return Boolean(noincludeToken) && !/^<\/?noinclude(?:\s[^>]*)?\/?>$/iu.test(String(noincludeToken));
243
- }
244
- case 'stage':
245
- return this.#stage;
246
- case 'acceptable':
247
- return this.#acceptable ? {...this.#acceptable} : undefined;
248
- case 'protectChildren':
249
- return this.#protectChildren;
250
- case 'protectedChildren':
251
- return new Ranges(this.#protectedChildren);
252
- default:
253
- return super.getAttribute(key);
254
- }
255
- }
256
-
257
- /**
258
- * @override
259
- * @template {string} T
260
- * @param {T} key 属性键
261
- * @param {TokenAttribute<T>} value 属性值
262
- */
263
- setAttribute(key, value) {
264
- switch (key) {
265
- case 'stage':
266
- if (this.#stage === 0 && this.type === 'root') {
267
- this.#accum.shift();
268
- }
269
- this.#stage = value;
270
- return this;
271
- case 'acceptable': {
272
- const /** @type {acceptable} */ acceptable = {};
273
- if (value) {
274
- for (const [k, v] of Object.entries(value)) {
275
- if (k.startsWith('Stage-')) {
276
- for (let i = 0; i <= Number(k.slice(6)); i++) {
277
- for (const type of aliases[i]) {
278
- acceptable[type] = new Ranges(v);
279
- }
280
- }
281
- } else if (k[0] === '!') { // `!`项必须放在最后
282
- delete acceptable[k.slice(1)];
283
- } else {
284
- acceptable[k] = new Ranges(v);
285
- }
286
- }
287
- }
288
- this.#acceptable = value && acceptable;
289
- return this;
290
- }
291
- default:
292
- return super.setAttribute(key, value);
293
- }
294
- }
295
-
296
- /** 是否是普通节点 */
297
- isPlain() {
298
- return this.constructor === Token;
299
- }
300
-
301
- /**
302
- * @override
303
- * @template {string|Token} T
304
- * @param {T} token 待插入的子节点
305
- * @param {number} i 插入位置
306
- * @complexity `n`
307
- * @returns {T extends Token ? Token : AstText}
308
- * @throws `RangeError` 不可插入的子节点
309
- */
310
- insertAt(token, i = this.length) {
311
- if (typeof token === 'string') {
312
- token = new AstText(token);
313
- }
314
- if (!Parser.running && this.#acceptable) {
315
- const acceptableIndices = Object.fromEntries(
316
- Object.entries(this.#acceptable)
317
- .map(([str, ranges]) => [str, ranges.applyTo(this.length + 1)]),
318
- ),
319
- nodesAfter = this.childNodes.slice(i),
320
- {constructor: {name: insertedName}} = token,
321
- k = i < 0 ? i + this.length : i;
322
- if (!acceptableIndices[insertedName].includes(k)) {
323
- throw new RangeError(`${this.constructor.name} 的第 ${k} 个子节点不能为 ${insertedName}!`);
324
- } else if (nodesAfter.some(({constructor: {name}}, j) => !acceptableIndices[name].includes(k + j + 1))) {
325
- throw new Error(`${this.constructor.name} 插入新的第 ${k} 个子节点会破坏规定的顺序!`);
326
- }
327
- }
328
- super.insertAt(token, i);
329
- if (token.type === 'root') {
330
- token.type = 'plain';
331
- }
332
- return token;
333
- }
334
-
335
- /**
336
- * 规范化页面标题
337
- * @param {string} title 标题(含或不含命名空间前缀)
338
- * @param {number} defaultNs 命名空间
339
- * @param {boolean} decode 是否需要解码
340
- * @param {boolean} selfLink 是否允许selfLink
341
- */
342
- normalizeTitle(title, defaultNs = 0, halfParsed = false, decode = false, selfLink = false) {
343
- return Parser.normalizeTitle(title, defaultNs, this.#include, this.#config, halfParsed, decode, selfLink);
344
- }
345
-
346
- /**
347
- * @override
348
- * @param {number} i 移除位置
349
- * @returns {Token}
350
- * @complexity `n`
351
- * @throws `Error` 不可移除的子节点
352
- */
353
- removeAt(i) {
354
- if (!Number.isInteger(i)) {
355
- this.typeError('removeAt', 'Number');
356
- }
357
- const iPos = i < 0 ? i + this.length : i;
358
- if (!Parser.running) {
359
- const protectedIndices = this.#protectedChildren.applyTo(this.childNodes);
360
- if (protectedIndices.includes(iPos)) {
361
- throw new Error(`${this.constructor.name} 的第 ${i} 个子节点不可移除!`);
362
- } else if (this.#acceptable) {
363
- const acceptableIndices = Object.fromEntries(
364
- Object.entries(this.#acceptable)
365
- .map(([str, ranges]) => [str, ranges.applyTo(this.length - 1)]),
366
- ),
367
- nodesAfter = i === -1 ? [] : this.childNodes.slice(i + 1);
368
- if (nodesAfter.some(({constructor: {name}}, j) => !acceptableIndices[name].includes(i + j))) {
369
- throw new Error(`移除 ${this.constructor.name} 的第 ${i} 个子节点会破坏规定的顺序!`);
370
- }
371
- }
372
- }
373
- return super.removeAt(i);
374
- }
375
-
376
- /**
377
- * 替换为同类节点
378
- * @param {Token} token 待替换的节点
379
- * @complexity `n`
380
- * @throws `Error` 不存在父节点
381
- * @throws `Error` 待替换的节点具有不同属性
382
- */
383
- safeReplaceWith(token) {
384
- const {parentNode} = this;
385
- if (!parentNode) {
386
- throw new Error('不存在父节点!');
387
- } else if (token.constructor !== this.constructor) {
388
- this.typeError('safeReplaceWith', this.constructor.name);
389
- }
390
- try {
391
- assert.deepEqual(token.getAttribute('acceptable'), this.#acceptable);
392
- } catch (e) {
393
- if (e instanceof assert.AssertionError) {
394
- throw new Error(`待替换的 ${this.constructor.name} 带有不同的 #acceptable 属性!`);
395
- }
396
- throw e;
397
- }
398
- const i = parentNode.childNodes.indexOf(this);
399
- super.removeAt.call(parentNode, i);
400
- super.insertAt.call(parentNode, token, i);
401
- if (token.type === 'root') {
402
- token.type = 'plain';
403
- }
404
- const e = new Event('replace', {bubbles: true});
405
- token.dispatchEvent(e, {position: i, oldToken: this, newToken: token});
406
- }
407
-
408
- /**
409
- * 创建HTML注释
410
- * @param {string} data 注释内容
411
- */
412
- createComment(data = '') {
413
- if (typeof data === 'string') {
414
- const CommentToken = require('./nowiki/comment');
415
- const config = this.getAttribute('config');
416
- return Parser.run(() => new CommentToken(data.replaceAll('-->', '--&gt;'), true, config));
417
- }
418
- return this.typeError('createComment', 'String');
419
- }
420
-
421
- /**
422
- * 创建标签
423
- * @param {string} tagName 标签名
424
- * @param {{selfClosing: boolean, closing: boolean}} options 选项
425
- * @throws `RangeError` 非法的标签名
426
- */
427
- createElement(tagName, {selfClosing, closing} = {}) {
428
- if (typeof tagName !== 'string') {
429
- this.typeError('createElement', 'String');
430
- }
431
- const config = this.getAttribute('config'),
432
- include = this.getAttribute('include');
433
- if (tagName === (include ? 'noinclude' : 'includeonly')) {
434
- const IncludeToken = require('./tagPair/include');
435
- return Parser.run(
436
- () => new IncludeToken(tagName, '', undefined, selfClosing ? undefined : tagName, config),
437
- );
438
- } else if (config.ext.includes(tagName)) {
439
- const ExtToken = require('./tagPair/ext');
440
- return Parser.run(() => new ExtToken(tagName, '', '', selfClosing ? undefined : '', config));
441
- } else if (config.html.flat().includes(tagName)) {
442
- const HtmlToken = require('./html');
443
- return Parser.run(() => new HtmlToken(tagName, '', closing, selfClosing, config));
444
- }
445
- throw new RangeError(`非法的标签名!${tagName}`);
446
- }
447
-
448
- /**
449
- * 创建纯文本节点
450
- * @param {string} data 文本内容
451
- */
452
- createTextNode(data = '') {
453
- return typeof data === 'string' ? new AstText(data) : this.typeError('createComment', 'String');
454
- }
455
-
456
- /**
457
- * 找到给定位置所在的节点
458
- * @param {number} index 位置
459
- */
460
- caretPositionFromIndex(index) {
461
- if (index === undefined) {
462
- return undefined;
463
- } else if (!Number.isInteger(index)) {
464
- this.typeError('caretPositionFromIndex', 'Number');
465
- }
466
- const {length} = String(this);
467
- if (index > length || index < -length) {
468
- return undefined;
469
- } else if (index < 0) {
470
- index += length;
471
- }
472
- let child = this, // eslint-disable-line unicorn/no-this-assignment
473
- acc = 0,
474
- start = 0;
475
- while (child.type !== 'text') {
476
- const {childNodes} = child;
477
- acc += child.getPadding();
478
- for (let i = 0; acc <= index && i < childNodes.length; i++) {
479
- const cur = childNodes[i],
480
- {length: l} = String(cur);
481
- acc += l;
482
- if (acc >= index) {
483
- child = cur;
484
- acc -= l;
485
- start = acc;
486
- break;
487
- }
488
- acc += child.getGaps(i);
489
- }
490
- if (child.childNodes === childNodes) {
491
- return {offsetNode: child, offset: index - start};
492
- }
493
- }
494
- return {offsetNode: child, offset: index - start};
495
- }
496
-
497
- /**
498
- * 找到给定位置所在的节点
499
- * @param {number} x 列数
500
- * @param {number} y 行数
501
- */
502
- caretPositionFromPoint(x, y) {
503
- return this.caretPositionFromIndex(this.indexFromPos(y, x));
504
- }
505
-
506
- /**
507
- * 找到给定位置所在的最外层节点
508
- * @param {number} index 位置
509
- * @throws `Error` 不是根节点
510
- */
511
- elementFromIndex(index) {
512
- if (index === undefined) {
513
- return undefined;
514
- } else if (!Number.isInteger(index)) {
515
- this.typeError('elementFromIndex', 'Number');
516
- } else if (this.type !== 'root') {
517
- throw new Error('elementFromIndex方法只可用于根节点!');
518
- }
519
- const {length} = String(this);
520
- if (index > length || index < -length) {
521
- return undefined;
522
- } else if (index < 0) {
523
- index += length;
524
- }
525
- const {childNodes} = this;
526
- let acc = 0,
527
- i = 0;
528
- for (; acc < index && i < childNodes.length; i++) {
529
- const {length: l} = String(childNodes[i]);
530
- acc += l;
531
- }
532
- return childNodes[i && i - 1];
533
- }
534
-
535
- /**
536
- * 找到给定位置所在的最外层节点
537
- * @param {number} x 列数
538
- * @param {number} y 行数
539
- */
540
- elementFromPoint(x, y) {
541
- return this.elementFromIndex(this.indexFromPos(y, x));
542
- }
543
-
544
- /**
545
- * 找到给定位置所在的所有节点
546
- * @param {number} index 位置
547
- */
548
- elementsFromIndex(index) {
549
- const offsetNode = this.caretPositionFromIndex(index)?.offsetNode;
550
- return offsetNode && [...offsetNode.getAncestors().reverse(), offsetNode];
551
- }
552
-
553
- /**
554
- * 找到给定位置所在的所有节点
555
- * @param {number} x 列数
556
- * @param {number} y 行数
557
- */
558
- elementsFromPoint(x, y) {
559
- return this.elementsFromIndex(this.indexFromPos(y, x));
560
- }
561
-
562
- /**
563
- * 判断标题是否是跨维基链接
564
- * @param {string} title 标题
565
- */
566
- isInterwiki(title) {
567
- return Parser.isInterwiki(title, this.#config);
568
- }
569
-
570
- /**
571
- * 深拷贝所有子节点
572
- * @complexity `n`
573
- * @returns {(AstText|Token)[]}
574
- */
575
- cloneChildNodes() {
576
- return this.childNodes.map(child => child.cloneNode());
577
- }
578
-
579
- /**
580
- * 深拷贝节点
581
- * @complexity `n`
582
- * @throws `Error` 未定义复制方法
583
- */
584
- cloneNode() {
585
- if (this.constructor !== Token) {
586
- throw new Error(`未定义 ${this.constructor.name} 的复制方法!`);
587
- }
588
- const cloned = this.cloneChildNodes();
589
- return Parser.run(() => {
590
- const token = new Token(undefined, this.#config, false, [], this.#acceptable);
591
- token.type = this.type;
592
- token.append(...cloned);
593
- token.getAttribute('protectChildren')(...this.#protectedChildren);
594
- return token;
595
- });
596
- }
597
-
598
- /**
599
- * 获取全部章节
600
- * @complexity `n`
601
- */
602
- sections() {
603
- if (this.type !== 'root') {
604
- return undefined;
605
- }
606
- const {childNodes} = this,
607
- headings = [...childNodes.entries()].filter(([, {type}]) => type === 'heading')
608
- .map(([i, {name}]) => [i, Number(name)]),
609
- lastHeading = [-1, -1, -1, -1, -1, -1],
610
- /** @type {(AstText|Token)[][]} */ sections = new Array(headings.length);
611
- for (let i = 0; i < headings.length; i++) {
612
- const [index, level] = headings[i];
613
- for (let j = level; j < 6; j++) {
614
- const last = lastHeading[j];
615
- if (last >= 0) {
616
- sections[last] = childNodes.slice(headings[last][0], index);
617
- }
618
- lastHeading[j] = j === level ? i : -1;
619
- }
620
- }
621
- for (const last of lastHeading) {
622
- if (last >= 0) {
623
- sections[last] = childNodes.slice(headings[last][0]);
624
- }
625
- }
626
- sections.unshift(childNodes.slice(0, headings[0]?.[0]));
627
- return sections;
628
- }
629
-
630
- /**
631
- * 获取指定章节
632
- * @param {number} n 章节序号
633
- * @complexity `n`
634
- */
635
- section(n) {
636
- return Number.isInteger(n) ? this.sections()?.[n] : this.typeError('section', 'Number');
637
- }
638
-
639
- /**
640
- * 获取指定的外层HTML标签
641
- * @param {string|undefined} tag HTML标签名
642
- * @returns {[Token, Token]}
643
- * @complexity `n`
644
- * @throws `RangeError` 非法的标签或空标签
645
- */
646
- findEnclosingHtml(tag) {
647
- if (tag !== undefined && typeof tag !== 'string') {
648
- this.typeError('findEnclosingHtml', 'String');
649
- }
650
- tag = tag?.toLowerCase();
651
- if (tag !== undefined && !this.#config.html.slice(0, 2).flat().includes(tag)) {
652
- throw new RangeError(`非法的标签或空标签:${tag}`);
653
- }
654
- const {parentNode} = this;
655
- if (!parentNode) {
656
- return undefined;
657
- }
658
- const {childNodes} = parentNode,
659
- index = childNodes.indexOf(this);
660
- let i;
661
- for (i = index - 1; i >= 0; i--) {
662
- const {type, name, selfClosing, closing} = childNodes[i];
663
- if (type === 'html' && (!tag || name === tag) && selfClosing === false && closing === false) {
664
- break;
665
- }
666
- }
667
- if (i === -1) {
668
- return parentNode.findEnclosingHtml(tag);
669
- }
670
- const opening = childNodes[i];
671
- for (i = index + 1; i < childNodes.length; i++) {
672
- const {type, name, selfClosing, closing} = childNodes[i];
673
- if (type === 'html' && name === opening.name && selfClosing === false && closing === true) {
674
- break;
675
- }
676
- }
677
- return i === childNodes.length
678
- ? parentNode.findEnclosingHtml(tag)
679
- : [opening, childNodes[i]];
680
- }
681
-
682
- /**
683
- * 获取全部分类
684
- * @complexity `n`
685
- */
686
- getCategories() {
687
- return this.querySelectorAll('category').map(({name, sortkey}) => [name, sortkey]);
688
- }
689
-
690
- /**
691
- * 重新解析单引号
692
- * @throws `Error` 不接受QuoteToken作为子节点
693
- */
694
- redoQuotes() {
695
- const acceptable = this.getAttribute('acceptable');
696
- if (acceptable && !acceptable.QuoteToken?.some(
697
- range => typeof range !== 'number' && range.start === 0 && range.end === Infinity && range.step === 1,
698
- )) {
699
- throw new Error(`${this.constructor.name} 不接受 QuoteToken 作为子节点!`);
700
- }
701
- for (const quote of this.childNodes) {
702
- if (quote.type === 'quote') {
703
- quote.replaceWith(String(quote));
704
- }
705
- }
706
- this.normalize();
707
- /** @type {[number, AstText][]} */
708
- const textNodes = [...this.childNodes.entries()].filter(([, {type}]) => type === 'text'),
709
- indices = textNodes.map(([i]) => this.getRelativeIndex(i)),
710
- token = Parser.run(() => {
711
- const root = new Token(text(textNodes.map(([, str]) => str)), this.getAttribute('config'));
712
- return root.setAttribute('stage', 6).parse(7);
713
- });
714
- for (const quote of [...token.childNodes].reverse()) {
715
- if (quote.type === 'quote') {
716
- const index = quote.getRelativeIndex(),
717
- n = indices.findLastIndex(textIndex => textIndex <= index);
718
- this.childNodes[n].splitText(index - indices[n]);
719
- this.childNodes[n + 1].splitText(Number(quote.name));
720
- this.removeAt(n + 1);
721
- this.insertAt(quote, n + 1);
722
- }
723
- }
724
- this.normalize();
725
- }
726
-
727
- /** 解析部分魔术字 */
728
- solveConst() {
729
- const ArgToken = require('./arg'),
730
- ParameterToken = require('./parameter');
731
- const targets = this.querySelectorAll('magic-word, arg'),
732
- magicWords = new Set(['if', 'ifeq', 'switch']);
733
- for (let i = targets.length - 1; i >= 0; i--) {
734
- const /** @type {ArgToken} */ target = targets[i],
735
- {type, name, default: argDefault, childNodes, length} = target;
736
- if (type === 'arg' || type === 'magic-word' && magicWords.has(name)) {
737
- let replace = '';
738
- if (type === 'arg') {
739
- replace = argDefault === false ? String(target) : argDefault;
740
- } else if (name === 'if' && !childNodes[1].querySelector('magic-word, template')) {
741
- replace = String(childNodes[String(childNodes[1] ?? '').trim() ? 2 : 3] ?? '').trim();
742
- } else if (name === 'ifeq'
743
- && !childNodes.slice(1, 3).some(child => child.querySelector('magic-word, template'))
744
- ) {
745
- replace = String(childNodes[
746
- String(childNodes[1] ?? '').trim() === String(childNodes[2] ?? '') ? 3 : 4
747
- ] ?? '').trim();
748
- } else if (name === 'switch' && !childNodes[1].querySelector('magic-word, template')) {
749
- const key = String(childNodes[1] ?? '').trim();
750
- let defaultVal = '',
751
- found = false,
752
- transclusion = false,
753
- j = 2;
754
- for (; j < length; j++) {
755
- const /** @type {ParameterToken} */ {anon, name: option, value, firstChild} = childNodes[j];
756
- transclusion = firstChild.querySelector('magic-word, template');
757
- if (anon) {
758
- if (j === length - 1) {
759
- defaultVal = value;
760
- } else if (transclusion) {
761
- break;
762
- } else {
763
- found ||= key === value;
764
- }
765
- } else if (transclusion) {
766
- break;
767
- } else if (found || option === key) {
768
- replace = value;
769
- break;
770
- } else if (option.toLowerCase() === '#default') {
771
- defaultVal = value;
772
- }
773
- if (j === length - 1) {
774
- replace = defaultVal;
775
- }
776
- }
777
- if (transclusion) {
778
- continue;
779
- }
780
- } else {
781
- continue;
782
- }
783
- target.replaceWith(replace);
784
- }
785
- }
786
- }
787
-
788
- /** 生成部分Token的`name`属性 */
789
- afterBuild() {
790
- if (!Parser.debugging && externalUse('afterBuild')) {
791
- this.debugOnly('afterBuild');
792
- } else if (this.type === 'root') {
793
- for (const token of this.#accum) {
794
- token.afterBuild();
795
- }
796
- }
797
- }
798
-
799
- /**
800
- * 解析、重构、生成部分Token的`name`属性
801
- * @param {number} n 最大解析层级
802
- * @param {boolean} include 是否嵌入
803
- */
804
- parse(n = MAX_STAGE, include = false) {
805
- if (!Number.isInteger(n)) {
806
- this.typeError('parse', 'Number');
807
- }
808
- while (this.#stage < n) {
809
- this.#parseOnce(this.#stage, include);
810
- }
811
- if (n) {
812
- this.#build();
813
- this.afterBuild();
814
- }
815
- return this;
816
- }
817
-
818
- /**
819
- * 解析HTML注释和扩展标签
820
- * @param {boolean} includeOnly 是否嵌入
821
- */
822
- #parseCommentAndExt(includeOnly) {
823
- const parseCommentAndExt = require('../parser/commentAndExt');
824
- this.setText(parseCommentAndExt(String(this.firstChild), this.#config, this.#accum, includeOnly));
825
- }
826
-
827
- /** 解析花括号 */
828
- #parseBrackets() {
829
- const parseBrackets = require('../parser/brackets');
830
- const str = this.type === 'root' ? String(this.firstChild) : `\0${String(this.firstChild)}`,
831
- parsed = parseBrackets(str, this.#config, this.#accum);
832
- this.setText(this.type === 'root' ? parsed : parsed.slice(1));
833
- }
834
-
835
- /** 解析HTML标签 */
836
- #parseHtml() {
837
- if (this.#config.excludes.includes('html')) {
838
- return;
839
- }
840
- const parseHtml = require('../parser/html');
841
- this.setText(parseHtml(String(this.firstChild), this.#config, this.#accum));
842
- }
843
-
844
- /** 解析表格 */
845
- #parseTable() {
846
- if (this.#config.excludes.includes('table')) {
847
- return;
848
- }
849
- const parseTable = require('../parser/table'),
850
- TableToken = require('./table');
851
- this.setText(parseTable(this, this.#config, this.#accum));
852
- for (const table of this.#accum) {
853
- if (table instanceof TableToken && table.type !== 'td') {
854
- table.normalize();
855
- const {childNodes: [, child]} = table;
856
- if (typeof child === 'string' && child.includes('\0')) {
857
- table.removeAt(1);
858
- const inner = new Token(child, this.#config, true, this.#accum);
859
- table.insertAt(inner, 1);
860
- inner.setAttribute('stage', 4);
861
- }
862
- }
863
- }
864
- }
865
-
866
- /** 解析\<hr\>和状态开关 */
867
- #parseHrAndDoubleUndescore() {
868
- if (this.#config.excludes.includes('hr')) {
869
- return;
870
- }
871
- const parseHrAndDoubleUnderscore = require('../parser/hrAndDoubleUnderscore');
872
- this.setText(parseHrAndDoubleUnderscore(this, this.#config, this.#accum));
873
- }
874
-
875
- /** 解析内部链接 */
876
- #parseLinks() {
877
- const parseLinks = require('../parser/links');
878
- this.setText(parseLinks(String(this.firstChild), this.#config, this.#accum));
879
- }
880
-
881
- /** 解析单引号 */
882
- #parseQuotes() {
883
- if (this.#config.excludes.includes('quote')) {
884
- return;
885
- }
886
- const parseQuotes = require('../parser/quotes');
887
- const lines = String(this.firstChild).split('\n');
888
- for (let i = 0; i < lines.length; i++) {
889
- lines[i] = parseQuotes(lines[i], this.#config, this.#accum);
890
- }
891
- this.setText(lines.join('\n'));
892
- }
893
-
894
- /** 解析外部链接 */
895
- #parseExternalLinks() {
896
- if (this.#config.excludes.includes('extLink')) {
897
- return;
898
- }
899
- const parseExternalLinks = require('../parser/externalLinks');
900
- this.setText(parseExternalLinks(String(this.firstChild), this.#config, this.#accum));
901
- }
902
-
903
- /** 解析自由外链 */
904
- #parseMagicLinks() {
905
- if (this.#config.excludes.includes('magicLink')) {
906
- return;
907
- }
908
- const parseMagicLinks = require('../parser/magicLinks');
909
- this.setText(parseMagicLinks(String(this.firstChild), this.#config, this.#accum));
910
- }
911
-
912
- /** 解析列表 */
913
- #parseList() {
914
- if (this.#config.excludes.includes('list')) {
915
- return;
916
- }
917
- const parseList = require('../parser/list');
918
- const lines = String(this.firstChild).split('\n');
919
- let i = this.type === 'root' || this.type === 'ext-inner' && this.name === 'poem' ? 0 : 1;
920
- for (; i < lines.length; i++) {
921
- lines[i] = parseList(lines[i], this.#config, this.#accum);
922
- }
923
- this.setText(lines.join('\n'));
924
- }
925
-
926
- /** 解析语言变体转换 */
927
- #parseConverter() {
928
- if (this.#config.variants?.length > 0) {
929
- const parseConverter = require('../parser/converter');
930
- this.setText(parseConverter(String(this.firstChild), this.#config, this.#accum));
931
- }
932
- }
933
- }
934
-
935
- Parser.classes.Token = __filename;
936
- module.exports = Token;