wikiparser-node 0.10.0 → 0.11.0-m

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 (155) hide show
  1. package/README.md +44 -32
  2. package/config/.schema.json +1 -8
  3. package/config/default.json +1 -2
  4. package/config/llwiki.json +1 -36
  5. package/config/moegirl.json +1 -45
  6. package/config/zhwiki.json +1 -467
  7. package/dist/index.d.ts +110 -0
  8. package/dist/lib/element.d.ts +48 -0
  9. package/dist/lib/node.d.ts +108 -0
  10. package/dist/lib/text.d.ts +30 -0
  11. package/dist/lib/title.d.ts +15 -0
  12. package/dist/mixin/hidden.d.ts +8 -0
  13. package/dist/parser/brackets.d.ts +12 -0
  14. package/dist/parser/commentAndExt.d.ts +8 -0
  15. package/dist/parser/converter.d.ts +7 -0
  16. package/dist/parser/externalLinks.d.ts +7 -0
  17. package/dist/parser/hrAndDoubleUnderscore.d.ts +11 -0
  18. package/dist/parser/html.d.ts +7 -0
  19. package/dist/parser/links.d.ts +7 -0
  20. package/dist/parser/list.d.ts +7 -0
  21. package/dist/parser/magicLinks.d.ts +7 -0
  22. package/dist/parser/quotes.d.ts +7 -0
  23. package/dist/parser/table.d.ts +11 -0
  24. package/dist/src/arg.d.ts +25 -0
  25. package/dist/src/atom/hidden.d.ts +5 -0
  26. package/dist/src/atom/index.d.ts +14 -0
  27. package/dist/src/attribute.d.ts +42 -0
  28. package/dist/src/attributes.d.ts +33 -0
  29. package/dist/src/converter.d.ts +29 -0
  30. package/dist/src/converterFlags.d.ts +27 -0
  31. package/dist/src/converterRule.d.ts +29 -0
  32. package/dist/src/extLink.d.ts +22 -0
  33. package/dist/src/gallery.d.ts +19 -0
  34. package/dist/src/hasNowiki/index.d.ts +14 -0
  35. package/dist/src/hasNowiki/pre.d.ts +13 -0
  36. package/dist/src/heading.d.ts +24 -0
  37. package/dist/src/html.d.ts +33 -0
  38. package/dist/src/imageParameter.d.ts +23 -0
  39. package/dist/src/imagemap.d.ts +26 -0
  40. package/dist/src/imagemapLink.d.ts +16 -0
  41. package/dist/src/index.d.ts +53 -0
  42. package/dist/src/link/category.d.ts +8 -0
  43. package/dist/src/link/file.d.ts +27 -0
  44. package/dist/src/link/galleryImage.d.ts +15 -0
  45. package/dist/src/link/index.d.ts +29 -0
  46. package/dist/src/magicLink.d.ts +14 -0
  47. package/dist/src/nested/choose.d.ts +13 -0
  48. package/dist/src/nested/combobox.d.ts +13 -0
  49. package/dist/src/nested/index.d.ts +20 -0
  50. package/dist/src/nested/references.d.ts +13 -0
  51. package/dist/src/nowiki/comment.d.ts +19 -0
  52. package/dist/src/nowiki/dd.d.ts +8 -0
  53. package/dist/src/nowiki/doubleUnderscore.d.ts +12 -0
  54. package/dist/src/nowiki/hr.d.ts +13 -0
  55. package/dist/src/nowiki/index.d.ts +18 -0
  56. package/dist/src/nowiki/list.d.ts +8 -0
  57. package/dist/src/nowiki/noinclude.d.ts +8 -0
  58. package/dist/src/nowiki/quote.d.ts +20 -0
  59. package/dist/src/onlyinclude.d.ts +17 -0
  60. package/dist/src/paramTag/index.d.ts +24 -0
  61. package/dist/src/paramTag/inputbox.d.ts +8 -0
  62. package/dist/src/parameter.d.ts +28 -0
  63. package/dist/src/syntax.d.ts +15 -0
  64. package/dist/src/table/index.d.ts +16 -0
  65. package/dist/src/table/td.d.ts +39 -0
  66. package/dist/src/table/tr.d.ts +17 -0
  67. package/dist/src/tagPair/ext.d.ts +17 -0
  68. package/dist/src/tagPair/include.d.ts +16 -0
  69. package/dist/src/tagPair/index.d.ts +28 -0
  70. package/dist/src/transclude.d.ts +75 -0
  71. package/dist/util/lint.d.ts +28 -0
  72. package/dist/util/string.d.ts +31 -0
  73. package/i18n/zh-hans.json +1 -1
  74. package/i18n/zh-hant.json +1 -1
  75. package/index.js +5 -257
  76. package/lib/element.js +7 -482
  77. package/lib/node.js +11 -540
  78. package/lib/text.js +3 -96
  79. package/lib/title.js +1 -28
  80. package/mixin/hidden.js +0 -3
  81. package/package.json +11 -5
  82. package/parser/brackets.js +3 -2
  83. package/parser/commentAndExt.js +8 -6
  84. package/parser/converter.js +1 -2
  85. package/parser/externalLinks.js +1 -2
  86. package/parser/hrAndDoubleUnderscore.js +1 -2
  87. package/parser/html.js +1 -2
  88. package/parser/links.js +5 -6
  89. package/parser/list.js +1 -2
  90. package/parser/magicLinks.js +1 -2
  91. package/parser/quotes.js +1 -2
  92. package/parser/table.js +1 -2
  93. package/src/arg.js +4 -118
  94. package/src/atom/hidden.js +0 -2
  95. package/src/atom/index.js +1 -18
  96. package/src/attribute.js +6 -190
  97. package/src/attributes.js +5 -308
  98. package/src/converter.js +3 -109
  99. package/src/converterFlags.js +1 -188
  100. package/src/converterRule.js +2 -184
  101. package/src/extLink.js +2 -122
  102. package/src/gallery.js +2 -56
  103. package/src/hasNowiki/index.js +1 -13
  104. package/src/hasNowiki/pre.js +1 -13
  105. package/src/heading.js +4 -55
  106. package/src/html.js +5 -120
  107. package/src/imageParameter.js +3 -165
  108. package/src/imagemap.js +3 -62
  109. package/src/imagemapLink.js +2 -14
  110. package/src/index.js +9 -530
  111. package/src/link/category.js +1 -32
  112. package/src/link/file.js +3 -158
  113. package/src/link/galleryImage.js +3 -61
  114. package/src/link/index.js +4 -273
  115. package/src/magicLink.js +6 -87
  116. package/src/nested/choose.js +1 -2
  117. package/src/nested/combobox.js +1 -2
  118. package/src/nested/index.js +8 -32
  119. package/src/nested/references.js +1 -2
  120. package/src/nowiki/comment.js +2 -26
  121. package/src/nowiki/dd.js +1 -47
  122. package/src/nowiki/doubleUnderscore.js +1 -31
  123. package/src/nowiki/hr.js +2 -21
  124. package/src/nowiki/index.js +2 -24
  125. package/src/nowiki/list.js +2 -5
  126. package/src/nowiki/noinclude.js +0 -14
  127. package/src/nowiki/quote.js +2 -16
  128. package/src/onlyinclude.js +2 -27
  129. package/src/paramTag/index.js +2 -25
  130. package/src/paramTag/inputbox.js +2 -5
  131. package/src/parameter.js +6 -148
  132. package/src/syntax.js +1 -69
  133. package/src/table/index.js +2 -939
  134. package/src/table/td.js +6 -226
  135. package/src/table/tr.js +3 -248
  136. package/src/tagPair/ext.js +4 -23
  137. package/src/tagPair/include.js +1 -25
  138. package/src/tagPair/index.js +3 -52
  139. package/src/transclude.js +6 -513
  140. package/typings/api.d.ts +9 -0
  141. package/typings/index.d.ts +51 -0
  142. package/typings/node.d.ts +16 -0
  143. package/typings/parser.d.ts +5 -0
  144. package/typings/token.d.ts +28 -0
  145. package/util/lint.js +2 -0
  146. package/util/string.js +0 -51
  147. package/lib/ranges.js +0 -130
  148. package/mixin/attributeParent.js +0 -117
  149. package/mixin/fixedToken.js +0 -40
  150. package/mixin/singleLine.js +0 -31
  151. package/mixin/sol.js +0 -54
  152. package/parser/selector.js +0 -177
  153. package/src/charinsert.js +0 -97
  154. package/tool/index.js +0 -1202
  155. package/util/debug.js +0 -73
package/src/index.js CHANGED
@@ -1,5 +1,10 @@
1
1
  'use strict';
2
2
 
3
+ /**
4
+ * @template T
5
+ * @typedef {import('../typings/node').TokenAttribute<T>} TokenAttribute
6
+ */
7
+
3
8
  // PHP解析器的步骤:
4
9
  // -1. 替换签名和`{{subst:}}`,参见Parser::preSaveTransform;这在revision中不可能保留,可以跳过
5
10
  // 0. 移除特定字符`\0`和`\x7F`,参见Parser::parse
@@ -41,13 +46,10 @@
41
46
  // v: ConverterToken
42
47
 
43
48
  const {text} = require('../util/string'),
44
- {externalUse} = require('../util/debug'),
45
- assert = require('assert/strict'),
46
- Ranges = require('../lib/ranges'),
47
49
  Parser = require('..'),
48
50
  AstElement = require('../lib/element'),
49
51
  AstText = require('../lib/text');
50
- const {MAX_STAGE, aliases} = Parser;
52
+ const {MAX_STAGE} = Parser;
51
53
 
52
54
  /**
53
55
  * 所有节点的基类
@@ -60,8 +62,6 @@ class Token extends AstElement {
60
62
  // 这个数组起两个作用:1. 数组中的Token会在build时替换`/\0\d+.\x7F/`标记;2. 数组中的Token会依次执行parseOnce和build方法。
61
63
  #accum;
62
64
  /** @type {boolean} */ #include;
63
- /** @type {Record<string, Ranges>} */ #acceptable;
64
- #protectedChildren = new Ranges();
65
65
 
66
66
  /**
67
67
  * 将维基语法替换为占位符
@@ -165,33 +165,9 @@ class Token extends AstElement {
165
165
  }
166
166
  };
167
167
 
168
- /**
169
- * 保护部分子节点不被移除
170
- * @param {...string|number|Range} args 子节点范围
171
- */
172
- #protectChildren = (...args) => {
173
- this.#protectedChildren.push(...new Ranges(args));
174
- };
175
-
176
- /** 所有图片,包括图库 */
177
- get images() {
178
- return this.querySelectorAll('file, gallery-image, imagemap-image');
179
- }
180
-
181
- /** 所有内链、外链和自由外链 */
182
- get links() {
183
- return this.querySelectorAll('link, ext-link, free-ext-link, image-parameter#link');
184
- }
185
-
186
- /** 所有模板和模块 */
187
- get embeds() {
188
- return this.querySelectorAll('template, magic-word#invoke');
189
- }
190
-
191
168
  /**
192
169
  * @param {string} wikitext wikitext
193
- * @param {accum} accum
194
- * @param {acceptable} acceptable 可接受的子节点设置
170
+ * @param {import('../typings/token').accum} accum
195
171
  */
196
172
  constructor(wikitext, config = Parser.getConfig(), halfParsed = false, accum = [], acceptable = undefined) {
197
173
  super();
@@ -200,7 +176,6 @@ class Token extends AstElement {
200
176
  }
201
177
  this.#config = config;
202
178
  this.#accum = accum;
203
- this.setAttribute('acceptable', acceptable);
204
179
  accum.push(this);
205
180
  }
206
181
 
@@ -230,21 +205,8 @@ class Token extends AstElement {
230
205
  if (root.type === 'root' && root !== this) {
231
206
  return root.getAttribute('include');
232
207
  }
233
- const includeToken = root.querySelector('include');
234
- if (includeToken) {
235
- return includeToken.name === 'noinclude';
236
- }
237
- const noincludeToken = root.querySelector('noinclude');
238
- return Boolean(noincludeToken) && !/^<\/?noinclude(?:\s[^>]*)?\/?>$/iu.test(String(noincludeToken));
208
+ return false;
239
209
  }
240
- case 'stage':
241
- return this.#stage;
242
- case 'acceptable':
243
- return this.#acceptable ? {...this.#acceptable} : undefined;
244
- case 'protectChildren':
245
- return this.#protectChildren;
246
- case 'protectedChildren':
247
- return new Ranges(this.#protectedChildren);
248
210
  default:
249
211
  return super.getAttribute(key);
250
212
  }
@@ -264,26 +226,6 @@ class Token extends AstElement {
264
226
  }
265
227
  this.#stage = value;
266
228
  return this;
267
- case 'acceptable': {
268
- const /** @type {acceptable} */ acceptable = {};
269
- if (value) {
270
- for (const [k, v] of Object.entries(value)) {
271
- if (k.startsWith('Stage-')) {
272
- for (let i = 0; i <= Number(k.slice(6)); i++) {
273
- for (const type of aliases[i]) {
274
- acceptable[type] = new Ranges(v);
275
- }
276
- }
277
- } else if (k[0] === '!') { // `!`项必须放在最后
278
- delete acceptable[k.slice(1)];
279
- } else {
280
- acceptable[k] = new Ranges(v);
281
- }
282
- }
283
- }
284
- this.#acceptable = value && acceptable;
285
- return this;
286
- }
287
229
  default:
288
230
  return super.setAttribute(key, value);
289
231
  }
@@ -301,26 +243,11 @@ class Token extends AstElement {
301
243
  * @param {number} i 插入位置
302
244
  * @complexity `n`
303
245
  * @returns {T extends Token ? Token : AstText}
304
- * @throws `RangeError` 不可插入的子节点
305
246
  */
306
247
  insertAt(token, i = this.length) {
307
248
  if (typeof token === 'string') {
308
249
  token = new AstText(token);
309
250
  }
310
- if (!Parser.running && this.#acceptable) {
311
- const acceptableIndices = Object.fromEntries(
312
- Object.entries(this.#acceptable)
313
- .map(([str, ranges]) => [str, ranges.applyTo(this.length + 1)]),
314
- ),
315
- nodesAfter = this.childNodes.slice(i),
316
- {constructor: {name: insertedName}} = token,
317
- k = i < 0 ? i + this.length : i;
318
- if (!acceptableIndices[insertedName].includes(k)) {
319
- throw new RangeError(`${this.constructor.name} 的第 ${k} 个子节点不能为 ${insertedName}!`);
320
- } else if (nodesAfter.some(({constructor: {name}}, j) => !acceptableIndices[name].includes(k + j + 1))) {
321
- throw new Error(`${this.constructor.name} 插入新的第 ${k} 个子节点会破坏规定的顺序!`);
322
- }
323
- }
324
251
  super.insertAt(token, i);
325
252
  if (token.type === 'root') {
326
253
  token.type = 'plain';
@@ -339,453 +266,9 @@ class Token extends AstElement {
339
266
  return Parser.normalizeTitle(title, defaultNs, this.#include, this.#config, halfParsed, decode, selfLink);
340
267
  }
341
268
 
342
- /**
343
- * @override
344
- * @param {number} i 移除位置
345
- * @returns {Token}
346
- * @complexity `n`
347
- * @throws `Error` 不可移除的子节点
348
- */
349
- removeAt(i) {
350
- if (!Number.isInteger(i)) {
351
- this.typeError('removeAt', 'Number');
352
- }
353
- const iPos = i < 0 ? i + this.length : i;
354
- if (!Parser.running) {
355
- const protectedIndices = this.#protectedChildren.applyTo(this.childNodes);
356
- if (protectedIndices.includes(iPos)) {
357
- throw new Error(`${this.constructor.name} 的第 ${i} 个子节点不可移除!`);
358
- } else if (this.#acceptable) {
359
- const acceptableIndices = Object.fromEntries(
360
- Object.entries(this.#acceptable)
361
- .map(([str, ranges]) => [str, ranges.applyTo(this.length - 1)]),
362
- ),
363
- nodesAfter = i === -1 ? [] : this.childNodes.slice(i + 1);
364
- if (nodesAfter.some(({constructor: {name}}, j) => !acceptableIndices[name].includes(i + j))) {
365
- throw new Error(`移除 ${this.constructor.name} 的第 ${i} 个子节点会破坏规定的顺序!`);
366
- }
367
- }
368
- }
369
- return super.removeAt(i);
370
- }
371
-
372
- /**
373
- * 替换为同类节点
374
- * @param {Token} token 待替换的节点
375
- * @complexity `n`
376
- * @throws `Error` 不存在父节点
377
- * @throws `Error` 待替换的节点具有不同属性
378
- */
379
- safeReplaceWith(token) {
380
- const {parentNode} = this;
381
- if (!parentNode) {
382
- throw new Error('不存在父节点!');
383
- } else if (token.constructor !== this.constructor) {
384
- this.typeError('safeReplaceWith', this.constructor.name);
385
- }
386
- try {
387
- assert.deepEqual(token.getAttribute('acceptable'), this.#acceptable);
388
- } catch (e) {
389
- if (e instanceof assert.AssertionError) {
390
- throw new Error(`待替换的 ${this.constructor.name} 带有不同的 #acceptable 属性!`);
391
- }
392
- throw e;
393
- }
394
- const i = parentNode.childNodes.indexOf(this);
395
- super.removeAt.call(parentNode, i);
396
- super.insertAt.call(parentNode, token, i);
397
- if (token.type === 'root') {
398
- token.type = 'plain';
399
- }
400
- const e = new Event('replace', {bubbles: true});
401
- token.dispatchEvent(e, {position: i, oldToken: this, newToken: token});
402
- }
403
-
404
- /**
405
- * 创建HTML注释
406
- * @param {string} data 注释内容
407
- */
408
- createComment(data = '') {
409
- if (typeof data === 'string') {
410
- const CommentToken = require('./nowiki/comment');
411
- const config = this.getAttribute('config');
412
- return Parser.run(() => new CommentToken(data.replaceAll('-->', '--&gt;'), true, config));
413
- }
414
- return this.typeError('createComment', 'String');
415
- }
416
-
417
- /**
418
- * 创建标签
419
- * @param {string} tagName 标签名
420
- * @param {{selfClosing: boolean, closing: boolean}} options 选项
421
- * @throws `RangeError` 非法的标签名
422
- */
423
- createElement(tagName, {selfClosing, closing} = {}) {
424
- if (typeof tagName !== 'string') {
425
- this.typeError('createElement', 'String');
426
- }
427
- const config = this.getAttribute('config'),
428
- include = this.getAttribute('include');
429
- if (tagName === (include ? 'noinclude' : 'includeonly')) {
430
- const IncludeToken = require('./tagPair/include');
431
- return Parser.run(
432
- () => new IncludeToken(tagName, '', undefined, selfClosing ? undefined : tagName, config),
433
- );
434
- } else if (config.ext.includes(tagName)) {
435
- const ExtToken = require('./tagPair/ext');
436
- return Parser.run(() => new ExtToken(tagName, '', '', selfClosing ? undefined : '', config));
437
- } else if (config.html.flat().includes(tagName)) {
438
- const HtmlToken = require('./html');
439
- return Parser.run(() => new HtmlToken(tagName, '', closing, selfClosing, config));
440
- }
441
- throw new RangeError(`非法的标签名!${tagName}`);
442
- }
443
-
444
- /**
445
- * 创建纯文本节点
446
- * @param {string} data 文本内容
447
- */
448
- createTextNode(data = '') {
449
- return typeof data === 'string' ? new AstText(data) : this.typeError('createComment', 'String');
450
- }
451
-
452
- /**
453
- * 找到给定位置所在的节点
454
- * @param {number} index 位置
455
- */
456
- caretPositionFromIndex(index) {
457
- if (index === undefined) {
458
- return undefined;
459
- } else if (!Number.isInteger(index)) {
460
- this.typeError('caretPositionFromIndex', 'Number');
461
- }
462
- const {length} = String(this);
463
- if (index > length || index < -length) {
464
- return undefined;
465
- } else if (index < 0) {
466
- index += length;
467
- }
468
- let child = this, // eslint-disable-line unicorn/no-this-assignment
469
- acc = 0,
470
- start = 0;
471
- while (child.type !== 'text') {
472
- const {childNodes} = child;
473
- acc += child.getPadding();
474
- for (let i = 0; acc <= index && i < childNodes.length; i++) {
475
- const cur = childNodes[i],
476
- {length: l} = String(cur);
477
- acc += l;
478
- if (acc >= index) {
479
- child = cur;
480
- acc -= l;
481
- start = acc;
482
- break;
483
- }
484
- acc += child.getGaps(i);
485
- }
486
- if (child.childNodes === childNodes) {
487
- return {offsetNode: child, offset: index - start};
488
- }
489
- }
490
- return {offsetNode: child, offset: index - start};
491
- }
492
-
493
- /**
494
- * 找到给定位置所在的节点
495
- * @param {number} x 列数
496
- * @param {number} y 行数
497
- */
498
- caretPositionFromPoint(x, y) {
499
- return this.caretPositionFromIndex(this.indexFromPos(y, x));
500
- }
501
-
502
- /**
503
- * 找到给定位置所在的最外层节点
504
- * @param {number} index 位置
505
- * @throws `Error` 不是根节点
506
- */
507
- elementFromIndex(index) {
508
- if (index === undefined) {
509
- return undefined;
510
- } else if (!Number.isInteger(index)) {
511
- this.typeError('elementFromIndex', 'Number');
512
- } else if (this.type !== 'root') {
513
- throw new Error('elementFromIndex方法只可用于根节点!');
514
- }
515
- const {length} = String(this);
516
- if (index > length || index < -length) {
517
- return undefined;
518
- } else if (index < 0) {
519
- index += length;
520
- }
521
- const {childNodes} = this;
522
- let acc = 0,
523
- i = 0;
524
- for (; acc < index && i < childNodes.length; i++) {
525
- const {length: l} = String(childNodes[i]);
526
- acc += l;
527
- }
528
- return childNodes[i && i - 1];
529
- }
530
-
531
- /**
532
- * 找到给定位置所在的最外层节点
533
- * @param {number} x 列数
534
- * @param {number} y 行数
535
- */
536
- elementFromPoint(x, y) {
537
- return this.elementFromIndex(this.indexFromPos(y, x));
538
- }
539
-
540
- /**
541
- * 找到给定位置所在的所有节点
542
- * @param {number} index 位置
543
- */
544
- elementsFromIndex(index) {
545
- const offsetNode = this.caretPositionFromIndex(index)?.offsetNode;
546
- return offsetNode && [...offsetNode.getAncestors().reverse(), offsetNode];
547
- }
548
-
549
- /**
550
- * 找到给定位置所在的所有节点
551
- * @param {number} x 列数
552
- * @param {number} y 行数
553
- */
554
- elementsFromPoint(x, y) {
555
- return this.elementsFromIndex(this.indexFromPos(y, x));
556
- }
557
-
558
- /**
559
- * 判断标题是否是跨维基链接
560
- * @param {string} title 标题
561
- */
562
- isInterwiki(title) {
563
- return Parser.isInterwiki(title, this.#config);
564
- }
565
-
566
- /**
567
- * 深拷贝所有子节点
568
- * @complexity `n`
569
- * @returns {(AstText|Token)[]}
570
- */
571
- cloneChildNodes() {
572
- return this.childNodes.map(child => child.cloneNode());
573
- }
574
-
575
- /**
576
- * 深拷贝节点
577
- * @complexity `n`
578
- * @throws `Error` 未定义复制方法
579
- */
580
- cloneNode() {
581
- if (this.constructor !== Token) {
582
- throw new Error(`未定义 ${this.constructor.name} 的复制方法!`);
583
- }
584
- const cloned = this.cloneChildNodes();
585
- return Parser.run(() => {
586
- const token = new Token(undefined, this.#config, false, [], this.#acceptable);
587
- token.type = this.type;
588
- token.append(...cloned);
589
- token.getAttribute('protectChildren')(...this.#protectedChildren);
590
- return token;
591
- });
592
- }
593
-
594
- /**
595
- * 获取全部章节
596
- * @complexity `n`
597
- */
598
- sections() {
599
- if (this.type !== 'root') {
600
- return undefined;
601
- }
602
- const {childNodes} = this,
603
- headings = [...childNodes.entries()].filter(([, {type}]) => type === 'heading')
604
- .map(([i, {name}]) => [i, Number(name)]),
605
- lastHeading = [-1, -1, -1, -1, -1, -1],
606
- /** @type {(AstText|Token)[][]} */ sections = new Array(headings.length);
607
- for (let i = 0; i < headings.length; i++) {
608
- const [index, level] = headings[i];
609
- for (let j = level; j < 6; j++) {
610
- const last = lastHeading[j];
611
- if (last >= 0) {
612
- sections[last] = childNodes.slice(headings[last][0], index);
613
- }
614
- lastHeading[j] = j === level ? i : -1;
615
- }
616
- }
617
- for (const last of lastHeading) {
618
- if (last >= 0) {
619
- sections[last] = childNodes.slice(headings[last][0]);
620
- }
621
- }
622
- sections.unshift(childNodes.slice(0, headings[0]?.[0]));
623
- return sections;
624
- }
625
-
626
- /**
627
- * 获取指定章节
628
- * @param {number} n 章节序号
629
- * @complexity `n`
630
- */
631
- section(n) {
632
- return Number.isInteger(n) ? this.sections()?.[n] : this.typeError('section', 'Number');
633
- }
634
-
635
- /**
636
- * 获取指定的外层HTML标签
637
- * @param {string|undefined} tag HTML标签名
638
- * @returns {[Token, Token]}
639
- * @complexity `n`
640
- * @throws `RangeError` 非法的标签或空标签
641
- */
642
- findEnclosingHtml(tag) {
643
- if (tag !== undefined && typeof tag !== 'string') {
644
- this.typeError('findEnclosingHtml', 'String');
645
- }
646
- tag = tag?.toLowerCase();
647
- if (tag !== undefined && !this.#config.html.slice(0, 2).flat().includes(tag)) {
648
- throw new RangeError(`非法的标签或空标签:${tag}`);
649
- }
650
- const {parentNode} = this;
651
- if (!parentNode) {
652
- return undefined;
653
- }
654
- const {childNodes} = parentNode,
655
- index = childNodes.indexOf(this);
656
- let i;
657
- for (i = index - 1; i >= 0; i--) {
658
- const {type, name, selfClosing, closing} = childNodes[i];
659
- if (type === 'html' && (!tag || name === tag) && selfClosing === false && closing === false) {
660
- break;
661
- }
662
- }
663
- if (i === -1) {
664
- return parentNode.findEnclosingHtml(tag);
665
- }
666
- const opening = childNodes[i];
667
- for (i = index + 1; i < childNodes.length; i++) {
668
- const {type, name, selfClosing, closing} = childNodes[i];
669
- if (type === 'html' && name === opening.name && selfClosing === false && closing === true) {
670
- break;
671
- }
672
- }
673
- return i === childNodes.length
674
- ? parentNode.findEnclosingHtml(tag)
675
- : [opening, childNodes[i]];
676
- }
677
-
678
- /**
679
- * 获取全部分类
680
- * @complexity `n`
681
- */
682
- getCategories() {
683
- return this.querySelectorAll('category').map(({name, sortkey}) => [name, sortkey]);
684
- }
685
-
686
- /**
687
- * 重新解析单引号
688
- * @throws `Error` 不接受QuoteToken作为子节点
689
- */
690
- redoQuotes() {
691
- const acceptable = this.getAttribute('acceptable');
692
- if (acceptable && !acceptable.QuoteToken?.some(
693
- range => typeof range !== 'number' && range.start === 0 && range.end === Infinity && range.step === 1,
694
- )) {
695
- throw new Error(`${this.constructor.name} 不接受 QuoteToken 作为子节点!`);
696
- }
697
- for (const quote of this.childNodes) {
698
- if (quote.type === 'quote') {
699
- quote.replaceWith(String(quote));
700
- }
701
- }
702
- this.normalize();
703
- /** @type {[number, AstText][]} */
704
- const textNodes = [...this.childNodes.entries()].filter(([, {type}]) => type === 'text'),
705
- indices = textNodes.map(([i]) => this.getRelativeIndex(i)),
706
- token = Parser.run(() => {
707
- const root = new Token(text(textNodes.map(([, str]) => str)), this.getAttribute('config'));
708
- return root.setAttribute('stage', 6).parse(7);
709
- });
710
- for (const quote of [...token.childNodes].reverse()) {
711
- if (quote.type === 'quote') {
712
- const index = quote.getRelativeIndex(),
713
- n = indices.findLastIndex(textIndex => textIndex <= index);
714
- this.childNodes[n].splitText(index - indices[n]);
715
- this.childNodes[n + 1].splitText(Number(quote.name));
716
- this.removeAt(n + 1);
717
- this.insertAt(quote, n + 1);
718
- }
719
- }
720
- this.normalize();
721
- }
722
-
723
- /** 解析部分魔术字 */
724
- solveConst() {
725
- const ArgToken = require('./arg'),
726
- ParameterToken = require('./parameter');
727
- const targets = this.querySelectorAll('magic-word, arg'),
728
- magicWords = new Set(['if', 'ifeq', 'switch']);
729
- for (let i = targets.length - 1; i >= 0; i--) {
730
- const /** @type {ArgToken} */ target = targets[i],
731
- {type, name, default: argDefault, childNodes, length} = target;
732
- if (type === 'arg' || type === 'magic-word' && magicWords.has(name)) {
733
- let replace = '';
734
- if (type === 'arg') {
735
- replace = argDefault === false ? String(target) : argDefault;
736
- } else if (name === 'if' && !childNodes[1].querySelector('magic-word, template')) {
737
- replace = String(childNodes[String(childNodes[1] ?? '').trim() ? 2 : 3] ?? '').trim();
738
- } else if (name === 'ifeq'
739
- && !childNodes.slice(1, 3).some(child => child.querySelector('magic-word, template'))
740
- ) {
741
- replace = String(childNodes[
742
- String(childNodes[1] ?? '').trim() === String(childNodes[2] ?? '') ? 3 : 4
743
- ] ?? '').trim();
744
- } else if (name === 'switch' && !childNodes[1].querySelector('magic-word, template')) {
745
- const key = String(childNodes[1] ?? '').trim();
746
- let defaultVal = '',
747
- found = false,
748
- transclusion = false,
749
- j = 2;
750
- for (; j < length; j++) {
751
- const /** @type {ParameterToken} */ {anon, name: option, value, firstChild} = childNodes[j];
752
- transclusion = firstChild.querySelector('magic-word, template');
753
- if (anon) {
754
- if (j === length - 1) {
755
- defaultVal = value;
756
- } else if (transclusion) {
757
- break;
758
- } else {
759
- found ||= key === value;
760
- }
761
- } else if (transclusion) {
762
- break;
763
- } else if (found || option === key) {
764
- replace = value;
765
- break;
766
- } else if (option.toLowerCase() === '#default') {
767
- defaultVal = value;
768
- }
769
- if (j === length - 1) {
770
- replace = defaultVal;
771
- }
772
- }
773
- if (transclusion) {
774
- continue;
775
- }
776
- } else {
777
- continue;
778
- }
779
- target.replaceWith(replace);
780
- }
781
- }
782
- }
783
-
784
269
  /** 生成部分Token的`name`属性 */
785
270
  afterBuild() {
786
- if (!Parser.debugging && externalUse('afterBuild')) {
787
- this.debugOnly('afterBuild');
788
- } else if (this.type === 'root') {
271
+ if (this.type === 'root') {
789
272
  for (const token of this.#accum) {
790
273
  token.afterBuild();
791
274
  }
@@ -798,9 +281,6 @@ class Token extends AstElement {
798
281
  * @param {boolean} include 是否嵌入
799
282
  */
800
283
  parse(n = MAX_STAGE, include = false) {
801
- if (!Number.isInteger(n)) {
802
- this.typeError('parse', 'Number');
803
- }
804
284
  while (this.#stage < n) {
805
285
  this.#parseOnce(this.#stage, include);
806
286
  }
@@ -928,5 +408,4 @@ class Token extends AstElement {
928
408
  }
929
409
  }
930
410
 
931
- Parser.classes.Token = __filename;
932
411
  module.exports = Token;
@@ -1,8 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const {decodeHtml} = require('../../util/string'),
4
- Parser = require('../..'),
5
- LinkToken = require('.');
3
+ const LinkToken = require('.');
6
4
 
7
5
  /**
8
6
  * 分类
@@ -10,35 +8,6 @@ const {decodeHtml} = require('../../util/string'),
10
8
  */
11
9
  class CategoryToken extends LinkToken {
12
10
  type = 'category';
13
-
14
- /** 分类排序关键字 */
15
- get sortkey() {
16
- return decodeHtml(this.childNodes[1]?.text());
17
- }
18
-
19
- set sortkey(text) {
20
- this.setSortkey(text);
21
- }
22
-
23
- /**
24
- * @param {string} link 分类名
25
- * @param {string|undefined} text 排序关键字
26
- * @param {accum} accum
27
- * @param {string} delimiter `|`
28
- */
29
- constructor(link, text, config = Parser.getConfig(), accum = [], delimiter = '|') {
30
- super(link, text, config, accum, delimiter);
31
- this.seal(['selfLink', 'interwiki', 'setLangLink', 'setFragment', 'asSelfLink', 'pipeTrick'], true);
32
- }
33
-
34
- /**
35
- * 设置排序关键字
36
- * @param {string} text 排序关键字
37
- */
38
- setSortkey(text) {
39
- this.setLinkText(text);
40
- }
41
11
  }
42
12
 
43
- Parser.classes.CategoryToken = __filename;
44
13
  module.exports = CategoryToken;