wikiparser-node 0.9.0 → 0.9.2-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/transclude.js DELETED
@@ -1,843 +0,0 @@
1
- 'use strict';
2
-
3
- const {removeComment, escapeRegExp, text, noWrap, print, decodeHtml} = require('../util/string'),
4
- {externalUse} = require('../util/debug'),
5
- {generateForChild} = require('../util/lint'),
6
- Parser = require('..'),
7
- Token = require('.'),
8
- ParameterToken = require('./parameter'),
9
- AtomToken = require('./atom'),
10
- SyntaxToken = require('./syntax');
11
-
12
- /**
13
- * 模板或魔术字
14
- * @classdesc `{childNodes: [AtomToken|SyntaxToken, ...ParameterToken]}`
15
- */
16
- class TranscludeToken extends Token {
17
- type = 'template';
18
- modifier = '';
19
- /** @type {Record<string, Set<ParameterToken>>} */ #args = {};
20
- /** @type {Set<string>} */ #keys = new Set();
21
- #fragment;
22
- #valid = true;
23
- #raw = false;
24
-
25
- /** 是否存在重复参数 */
26
- get duplication() {
27
- return this.isTemplate() && Boolean(this.hasDuplicatedArgs());
28
- }
29
-
30
- /**
31
- * 设置引用修饰符
32
- * @param {string} modifier 引用修饰符
33
- * @complexity `n`
34
- */
35
- setModifier(modifier = '') {
36
- if (typeof modifier !== 'string') {
37
- this.typeError('setModifier', 'String');
38
- }
39
- const {parserFunction: [,, raw, subst]} = this.getAttribute('config'),
40
- lcModifier = removeComment(modifier).trim();
41
- if (modifier && !lcModifier.endsWith(':')) {
42
- return false;
43
- }
44
- const magicWord = lcModifier.slice(0, -1).toLowerCase(),
45
- isRaw = raw.includes(magicWord),
46
- isSubst = subst.includes(magicWord);
47
- if (this.#raw && isRaw || !this.#raw && (isSubst || modifier === '')
48
- || (Parser.running || this.length > 1) && (isRaw || isSubst || modifier === '')
49
- ) {
50
- this.setAttribute('modifier', modifier);
51
- this.#raw = isRaw;
52
- return Boolean(modifier);
53
- }
54
- return false;
55
- }
56
-
57
- /**
58
- * @param {string} title 模板标题或魔术字
59
- * @param {[string, string|undefined][]} parts 参数各部分
60
- * @param {accum} accum
61
- * @complexity `n`
62
- * @throws `SyntaxError` 非法的模板名称
63
- */
64
- constructor(title, parts, config = Parser.getConfig(), accum = []) {
65
- super(undefined, config, true, accum, {
66
- AtomToken: 0, SyntaxToken: 0, ParameterToken: '1:',
67
- });
68
- this.seal('modifier');
69
- const {parserFunction: [insensitive, sensitive]} = config,
70
- argSubst = /^(?:\s|\0\d+c\x7F)*\0\d+s\x7F/u.exec(title)?.[0];
71
- if (argSubst) {
72
- this.setAttribute('modifier', argSubst);
73
- title = title.slice(argSubst.length);
74
- } else if (title.includes(':')) {
75
- const [modifier, ...arg] = title.split(':'),
76
- [mt] = /^(?:\s|\0\d+c\x7F)*/u.exec(arg[0] ?? '');
77
- if (this.setModifier(`${modifier}:${mt}`)) {
78
- title = arg.join(':').slice(mt.length);
79
- }
80
- }
81
- if (title.includes(':') || parts.length === 0 && !this.#raw) {
82
- const [magicWord, ...arg] = title.split(':'),
83
- cleaned = removeComment(magicWord),
84
- name = cleaned[arg.length > 0 ? 'trimStart' : 'trim'](),
85
- isSensitive = sensitive.includes(name),
86
- canonicalCame = insensitive[name.toLowerCase()];
87
- if (isSensitive || canonicalCame) {
88
- this.setAttribute('name', canonicalCame || name.toLowerCase()).type = 'magic-word';
89
- const pattern = new RegExp(`^\\s*${name}\\s*$`, isSensitive ? 'u' : 'iu'),
90
- token = new SyntaxToken(magicWord, pattern, 'magic-word-name', config, accum, {
91
- 'Stage-1': ':', '!ExtToken': '',
92
- });
93
- this.insertAt(token);
94
- if (arg.length > 0) {
95
- parts.unshift([arg.join(':')]);
96
- }
97
- if (this.name === 'invoke') {
98
- this.setAttribute('acceptable', {SyntaxToken: 0, AtomToken: '1:3', ParameterToken: '3:'});
99
- for (let i = 0; i < 2; i++) {
100
- const part = parts.shift();
101
- if (!part) {
102
- break;
103
- }
104
- const invoke = new AtomToken(part.join('='), `invoke-${
105
- i ? 'function' : 'module'
106
- }`, config, accum, {
107
- 'Stage-1': ':', '!ExtToken': '',
108
- });
109
- this.insertAt(invoke);
110
- }
111
- this.getAttribute('protectChildren')('1:3');
112
- }
113
- }
114
- }
115
- if (this.type === 'template') {
116
- const name = removeComment(decodeHtml(title)).split('#')[0].trim();
117
- if (!name || /\0\d+[eh!+-]\x7F|[<>[\]{}\n]|%[\da-f]{2}/u.test(name)) {
118
- accum.pop();
119
- throw new SyntaxError(`非法的模板名称:${noWrap(name)}`);
120
- }
121
- const token = new AtomToken(title, 'template-name', config, accum, {
122
- 'Stage-2': ':', '!HeadingToken': '',
123
- });
124
- this.insertAt(token);
125
- }
126
- const templateLike = this.isTemplate();
127
- let i = 1;
128
- for (let j = 0; j < parts.length; j++) {
129
- const part = parts[j];
130
- if (!templateLike && !(this.name === 'switch' && j > 0)) {
131
- part[0] = part.join('=');
132
- part.length = 1;
133
- }
134
- if (part.length === 1) {
135
- part.unshift(i);
136
- i++;
137
- }
138
- this.insertAt(new ParameterToken(...part, config, accum));
139
- }
140
- this.getAttribute('protectChildren')(0);
141
- }
142
-
143
- /** @override */
144
- afterBuild() {
145
- if (this.modifier.includes('\0')) {
146
- this.setAttribute('modifier', this.getAttribute('buildFromStr')(this.modifier, 'string'));
147
- }
148
- if (this.isTemplate()) {
149
- const isTemplate = this.type === 'template',
150
- titleObj = this.normalizeTitle(this.childNodes[isTemplate ? 0 : 1].text(), isTemplate ? 10 : 828);
151
- this.setAttribute(isTemplate ? 'name' : 'module', titleObj.title);
152
- this.#fragment = titleObj.fragment;
153
- this.#valid = titleObj.valid;
154
-
155
- /**
156
- * 当事件bubble到`parameter`时,将`oldKey`和`newKey`保存进AstEventData。
157
- * 当继续bubble到`template`时,处理并删除`oldKey`和`newKey`。
158
- * @type {AstListener}
159
- */
160
- const transcludeListener = (e, data) => {
161
- const {prevTarget} = e,
162
- {oldKey, newKey} = data ?? {};
163
- if (typeof oldKey === 'string') {
164
- delete data.oldKey;
165
- delete data.newKey;
166
- }
167
- if (prevTarget === this.firstChild && isTemplate
168
- || prevTarget === this.childNodes[1] && !isTemplate && this.name === 'invoke'
169
- ) {
170
- const name = prevTarget.text(),
171
- {title, fragment, valid} = this.normalizeTitle(name, 10);
172
- this.setAttribute(isTemplate ? 'name' : 'module', title);
173
- this.#fragment = fragment;
174
- this.#valid = valid;
175
- } else if (oldKey !== newKey && prevTarget instanceof ParameterToken) {
176
- const oldArgs = this.getArgs(oldKey, false, false);
177
- oldArgs.delete(prevTarget);
178
- this.getArgs(newKey, false, false).add(prevTarget);
179
- this.#keys.add(newKey);
180
- if (oldArgs.size === 0) {
181
- this.#keys.delete(oldKey);
182
- }
183
- }
184
- };
185
- this.addEventListener(['remove', 'insert', 'replace', 'text'], transcludeListener);
186
- }
187
- }
188
-
189
- /**
190
- * @override
191
- * @param {string} selector
192
- */
193
- toString(selector) {
194
- if (selector && this.matches(selector)) {
195
- return '';
196
- }
197
- const {childNodes, firstChild, modifier} = this;
198
- return `{{${modifier}${
199
- this.type === 'magic-word'
200
- ? `${String(firstChild)}${childNodes.length > 1 ? ':' : ''}${childNodes.slice(1).map(String).join('|')}`
201
- : super.toString(selector, '|')
202
- }}}`;
203
- }
204
-
205
- /**
206
- * @override
207
- * @returns {string}
208
- * @complexity `n`
209
- */
210
- text() {
211
- const {childNodes, firstChild, modifier, type, name} = this;
212
- return type === 'magic-word' && name === 'vardefine'
213
- ? ''
214
- : `{{${modifier}${
215
- this.type === 'magic-word'
216
- ? `${firstChild.text()}${childNodes.length > 1 ? ':' : ''}${text(childNodes.slice(1), '|')}`
217
- : super.text('|')
218
- }}}`;
219
- }
220
-
221
- /** @override */
222
- getPadding() {
223
- return this.modifier.length + 2;
224
- }
225
-
226
- /** @override */
227
- getGaps() {
228
- return 1;
229
- }
230
-
231
- /** @override */
232
- print() {
233
- const {childNodes, firstChild, modifier} = this;
234
- return `<span class="wpb-${this.type}">{{${modifier}${
235
- this.type === 'magic-word'
236
- ? `${firstChild.print()}${childNodes.length > 1 ? ':' : ''}${print(childNodes.slice(1), {sep: '|'})}`
237
- : print(childNodes, {sep: '|'})
238
- }}}</span>`;
239
- }
240
-
241
- /**
242
- * @override
243
- * @param {number} start 起始位置
244
- */
245
- lint(start = this.getAbsoluteIndex()) {
246
- const errors = super.lint(start),
247
- {type, childNodes} = this;
248
- let rect;
249
- if (!this.isTemplate()) {
250
- return errors;
251
- } else if (this.#fragment !== undefined) {
252
- rect = {start, ...this.getRootNode().posFromIndex(start)};
253
- errors.push(generateForChild(childNodes[type === 'template' ? 0 : 1], rect, 'useless fragment'));
254
- }
255
- if (!this.#valid) {
256
- rect = {start, ...this.getRootNode().posFromIndex(start)};
257
- errors.push(generateForChild(childNodes[1], rect, 'illegal module name'));
258
- }
259
- const duplicatedArgs = this.getDuplicatedArgs();
260
- if (duplicatedArgs.length > 0) {
261
- rect ||= {start, ...this.getRootNode().posFromIndex(start)};
262
- errors.push(...duplicatedArgs.flatMap(([, args]) => args).map(
263
- arg => generateForChild(arg, rect, 'duplicated parameter'),
264
- ));
265
- }
266
- return errors;
267
- }
268
-
269
- /** 是否是模板 */
270
- isTemplate() {
271
- return this.type === 'template' || this.type === 'magic-word' && this.name === 'invoke';
272
- }
273
-
274
- /**
275
- * 处理匿名参数更改
276
- * @param {number|ParameterToken} addedToken 新增的参数
277
- * @complexity `n`
278
- */
279
- #handleAnonArgChange(addedToken) {
280
- const args = this.getAnonArgs(),
281
- added = typeof addedToken !== 'number',
282
- maxAnon = String(args.length + (added ? 0 : 1));
283
- if (added) {
284
- this.#keys.add(maxAnon);
285
- } else if (!this.hasArg(maxAnon, true)) {
286
- this.#keys.delete(maxAnon);
287
- }
288
- const j = added ? args.indexOf(addedToken) : addedToken - 1;
289
- for (let i = j; i < args.length; i++) {
290
- const token = args[i],
291
- {name} = token,
292
- newName = String(i + 1);
293
- if (name !== newName) {
294
- this.getArgs(newName, false, false).add(token.setAttribute('name', newName));
295
- if (name) {
296
- this.getArgs(name, false, false).delete(token);
297
- }
298
- }
299
- }
300
- }
301
-
302
- /**
303
- * @override
304
- * @param {ParameterToken} token 待插入的子节点
305
- * @param {number} i 插入位置
306
- * @complexity `n`
307
- */
308
- insertAt(token, i = this.length) {
309
- super.insertAt(token, i);
310
- if (token.anon) {
311
- this.#handleAnonArgChange(token);
312
- } else if (token.name) {
313
- this.getArgs(token.name, false, false).add(token);
314
- this.#keys.add(token.name);
315
- }
316
- return token;
317
- }
318
-
319
- /**
320
- * 获取所有参数
321
- * @returns {ParameterToken[]}
322
- * @complexity `n`
323
- */
324
- getAllArgs() {
325
- return this.childNodes.filter(child => child instanceof ParameterToken);
326
- }
327
-
328
- /**
329
- * 获取匿名参数
330
- * @complexity `n`
331
- */
332
- getAnonArgs() {
333
- return this.getAllArgs().filter(({anon}) => anon);
334
- }
335
-
336
- /**
337
- * 获取指定参数
338
- * @param {string|number} key 参数名
339
- * @param {boolean} exact 是否匹配匿名性
340
- * @param {boolean} copy 是否返回一个备份
341
- * @complexity `n`
342
- */
343
- getArgs(key, exact, copy = true) {
344
- if (typeof key !== 'string' && typeof key !== 'number') {
345
- this.typeError('getArgs', 'String', 'Number');
346
- }
347
- copy ||= !Parser.debugging && externalUse('getArgs');
348
- const keyStr = String(key).replace(/^[ \t\n\0\v]+|(?<=[^ \t\n\0\v])[ \t\n\0\v]+$/gu, '');
349
- let args;
350
- if (Object.hasOwn(this.#args, keyStr)) {
351
- args = this.#args[keyStr];
352
- } else {
353
- args = new Set(this.getAllArgs().filter(({name}) => keyStr === name));
354
- this.#args[keyStr] = args;
355
- }
356
- if (exact && !isNaN(keyStr)) {
357
- args = new Set([...args].filter(({anon}) => typeof key === 'number' === anon));
358
- } else if (copy) {
359
- args = new Set(args);
360
- }
361
- return args;
362
- }
363
-
364
- /**
365
- * 获取重名参数
366
- * @complexity `n`
367
- * @returns {[string, ParameterToken[]][]}
368
- * @throws `Error` 仅用于模板
369
- */
370
- getDuplicatedArgs() {
371
- if (this.isTemplate()) {
372
- return Object.entries(this.#args).filter(([, {size}]) => size > 1)
373
- .map(([key, args]) => [key, [...args]]);
374
- }
375
- throw new Error(`${this.constructor.name}.getDuplicatedArgs 方法仅供模板使用!`);
376
- }
377
-
378
- /**
379
- * 对特定魔术字获取可能的取值
380
- * @this {ParameterToken}}
381
- * @throws `Error` 不是可接受的魔术字
382
- */
383
- getPossibleValues() {
384
- const {type, name, childNodes, constructor: {name: cName}} = this;
385
- if (type === 'template') {
386
- throw new Error(`${cName}.getPossibleValues 方法仅供特定魔术字使用!`);
387
- }
388
- let start;
389
- switch (name) {
390
- case 'if':
391
- case 'ifexist':
392
- case 'ifexpr':
393
- case 'iferror':
394
- start = 2;
395
- break;
396
- case 'ifeq':
397
- start = 3;
398
- break;
399
- default:
400
- throw new Error(`${cName}.getPossibleValues 方法仅供特定魔术字使用!`);
401
- }
402
- const /** @type {Token[]} */ queue = childNodes.slice(start, start + 2).map(({childNodes: [, value]}) => value);
403
- for (let i = 0; i < queue.length;) {
404
- /** @type {Token[] & {0: TranscludeToken}} */
405
- const {length, 0: first} = queue[i].childNodes.filter(child => child.text().trim());
406
- if (length === 0) {
407
- queue.splice(i, 1);
408
- } else if (length > 1 || first.type !== 'magic-word') {
409
- i++;
410
- } else {
411
- try {
412
- const possibleValues = first.getPossibleValues();
413
- queue.splice(i, 1, ...possibleValues);
414
- i += possibleValues.length;
415
- } catch {
416
- i++;
417
- }
418
- }
419
- }
420
- return queue;
421
- }
422
-
423
- /** @override */
424
- cloneNode() {
425
- const [first, ...cloned] = this.cloneChildNodes(),
426
- config = this.getAttribute('config');
427
- return Parser.run(() => {
428
- const token = new TranscludeToken(this.type === 'template' ? '' : first.text(), [], config);
429
- if (this.#raw) {
430
- token.setModifier(this.modifier);
431
- } else {
432
- token.setAttribute('modifier', this.modifier);
433
- }
434
- token.firstChild.safeReplaceWith(first);
435
- token.afterBuild();
436
- token.append(...cloned);
437
- return token;
438
- });
439
- }
440
-
441
- /** 替换引用 */
442
- subst() {
443
- this.setModifier('subst:');
444
- }
445
-
446
- /** 安全的替换引用 */
447
- safesubst() {
448
- this.setModifier('safesubst:');
449
- }
450
-
451
- /**
452
- * @override
453
- * @param {PropertyKey} key 属性键
454
- */
455
- hasAttribute(key) {
456
- return key === 'keys' || super.hasAttribute(key);
457
- }
458
-
459
- /**
460
- * @override
461
- * @template {string} T
462
- * @param {T} key 属性键
463
- * @returns {TokenAttribute<T>}
464
- */
465
- getAttribute(key) {
466
- if (key === 'args') {
467
- return {...this.#args};
468
- } else if (key === 'keys') {
469
- return !Parser.debugging && externalUse('getAttribute') ? new Set(this.#keys) : this.#keys;
470
- }
471
- return super.getAttribute(key);
472
- }
473
-
474
- /**
475
- * @override
476
- * @param {number} i 移除位置
477
- * @complexity `n`
478
- */
479
- removeAt(i) {
480
- const /** @type {ParameterToken} */ token = super.removeAt(i);
481
- if (token.anon) {
482
- this.#handleAnonArgChange(Number(token.name));
483
- } else {
484
- const args = this.getArgs(token.name, false, false);
485
- args.delete(token);
486
- if (args.size === 0) {
487
- this.#keys.delete(token.name);
488
- }
489
- }
490
- return token;
491
- }
492
-
493
- /**
494
- * 是否具有某参数
495
- * @param {string|number} key 参数名
496
- * @param {boolean} exact 是否匹配匿名性
497
- * @complexity `n`
498
- */
499
- hasArg(key, exact) {
500
- return this.getArgs(key, exact, false).size > 0;
501
- }
502
-
503
- /**
504
- * 获取生效的指定参数
505
- * @param {string|number} key 参数名
506
- * @param {boolean} exact 是否匹配匿名性
507
- * @complexity `n`
508
- */
509
- getArg(key, exact) {
510
- return [...this.getArgs(key, exact, false)].sort((a, b) => a.compareDocumentPosition(b)).at(-1);
511
- }
512
-
513
- /**
514
- * 移除指定参数
515
- * @param {string|number} key 参数名
516
- * @param {boolean} exact 是否匹配匿名性
517
- * @complexity `n`
518
- */
519
- removeArg(key, exact) {
520
- Parser.run(() => {
521
- for (const token of this.getArgs(key, exact, false)) {
522
- this.removeChild(token);
523
- }
524
- });
525
- }
526
-
527
- /**
528
- * 获取所有参数名
529
- * @complexity `n`
530
- */
531
- getKeys() {
532
- const args = this.getAllArgs();
533
- if (this.#keys.size === 0 && args.length > 0) {
534
- for (const {name} of args) {
535
- this.#keys.add(name);
536
- }
537
- }
538
- return [...this.#keys];
539
- }
540
-
541
- /**
542
- * 获取参数值
543
- * @param {string|number} key 参数名
544
- * @complexity `n`
545
- */
546
- getValues(key) {
547
- return [...this.getArgs(key, false, false)].map(token => token.getValue());
548
- }
549
-
550
- /**
551
- * 获取生效的参数值
552
- * @template {string|number|undefined} T
553
- * @param {T} key 参数名
554
- * @returns {T extends undefined ? Record<string, string> : string}
555
- * @complexity `n`
556
- */
557
- getValue(key) {
558
- return key === undefined
559
- ? Object.fromEntries(this.getKeys().map(k => [k, this.getValue(k)]))
560
- : this.getArg(key)?.getValue();
561
- }
562
-
563
- /**
564
- * 插入匿名参数
565
- * @param {string} val 参数值
566
- * @returns {ParameterToken}
567
- * @complexity `n`
568
- * @throws `SyntaxError` 非法的匿名参数
569
- */
570
- newAnonArg(val) {
571
- val = String(val);
572
- const templateLike = this.isTemplate(),
573
- wikitext = `{{${templateLike ? ':T|' : 'lc:'}${val}}}`,
574
- root = Parser.parse(wikitext, this.getAttribute('include'), 2, this.getAttribute('config')),
575
- {length, firstChild: transclude} = root,
576
- /** @type {Token & {lastChild: ParameterToken}} */
577
- {type, name, length: transcludeLength, lastChild} = transclude,
578
- targetType = templateLike ? 'template' : 'magic-word',
579
- targetName = templateLike ? 'T' : 'lc';
580
- if (length === 1 && type === targetType && name === targetName && transcludeLength === 2 && lastChild.anon) {
581
- return this.insertAt(lastChild);
582
- }
583
- throw new SyntaxError(`非法的匿名参数:${noWrap(val)}`);
584
- }
585
-
586
- /**
587
- * 设置参数值
588
- * @param {string} key 参数名
589
- * @param {string} value 参数值
590
- * @complexity `n`
591
- * @throws `Error` 仅用于模板
592
- * @throws `SyntaxError` 非法的命名参数
593
- */
594
- setValue(key, value) {
595
- if (typeof key !== 'string') {
596
- this.typeError('setValue', 'String');
597
- } else if (!this.isTemplate()) {
598
- throw new Error(`${this.constructor.name}.setValue 方法仅供模板使用!`);
599
- }
600
- const token = this.getArg(key);
601
- value = String(value);
602
- if (token) {
603
- token.setValue(value);
604
- return;
605
- }
606
- const wikitext = `{{:T|${key}=${value}}}`,
607
- root = Parser.parse(wikitext, this.getAttribute('include'), 2, this.getAttribute('config')),
608
- {length, firstChild: template} = root,
609
- {type, name, length: templateLength, lastChild: parameter} = template;
610
- if (length !== 1 || type !== 'template' || name !== 'T' || templateLength !== 2 || parameter.name !== key) {
611
- throw new SyntaxError(`非法的命名参数:${key}=${noWrap(value)}`);
612
- }
613
- this.insertAt(parameter);
614
- }
615
-
616
- /**
617
- * 将匿名参数改写为命名参数
618
- * @complexity `n`
619
- * @throws `Error` 仅用于模板
620
- */
621
- anonToNamed() {
622
- if (!this.isTemplate()) {
623
- throw new Error(`${this.constructor.name}.anonToNamed 方法仅供模板使用!`);
624
- }
625
- for (const token of this.getAnonArgs()) {
626
- token.firstChild.replaceChildren(token.name);
627
- }
628
- }
629
-
630
- /**
631
- * 替换模板名
632
- * @param {string} title 模板名
633
- * @throws `Error` 仅用于模板
634
- * @throws `SyntaxError` 非法的模板名称
635
- */
636
- replaceTemplate(title) {
637
- if (this.type === 'magic-word') {
638
- throw new Error(`${this.constructor.name}.replaceTemplate 方法仅用于更换模板!`);
639
- } else if (typeof title !== 'string') {
640
- this.typeError('replaceTemplate', 'String');
641
- }
642
- const root = Parser.parse(`{{${title}}}`, this.getAttribute('include'), 2, this.getAttribute('config')),
643
- {length, firstChild: template} = root;
644
- if (length !== 1 || template.type !== 'template' || template.length !== 1) {
645
- throw new SyntaxError(`非法的模板名称:${title}`);
646
- }
647
- this.firstChild.replaceChildren(...template.firstChild.childNodes);
648
- }
649
-
650
- /**
651
- * 替换模块名
652
- * @param {string} title 模块名
653
- * @throws `Error` 仅用于模块
654
- * @throws `SyntaxError` 非法的模块名称
655
- */
656
- replaceModule(title) {
657
- if (this.type !== 'magic-word' || this.name !== 'invoke') {
658
- throw new Error(`${this.constructor.name}.replaceModule 方法仅用于更换模块!`);
659
- } else if (typeof title !== 'string') {
660
- this.typeError('replaceModule', 'String');
661
- }
662
- const root = Parser.parse(`{{#invoke:${title}}}`, this.getAttribute('include'), 2, this.getAttribute('config')),
663
- {length, firstChild: invoke} = root,
664
- {type, name, length: invokeLength, lastChild} = invoke;
665
- if (length !== 1 || type !== 'magic-word' || name !== 'invoke' || invokeLength !== 2) {
666
- throw new SyntaxError(`非法的模块名称:${title}`);
667
- } else if (this.length > 1) {
668
- this.childNodes[1].replaceChildren(...lastChild.childNodes);
669
- } else {
670
- invoke.destroy(true);
671
- this.insertAt(lastChild);
672
- }
673
- }
674
-
675
- /**
676
- * 替换模块函数
677
- * @param {string} func 模块函数名
678
- * @throws `Error` 仅用于模块
679
- * @throws `Error` 尚未指定模块名称
680
- * @throws `SyntaxError` 非法的模块函数名
681
- */
682
- replaceFunction(func) {
683
- if (this.type !== 'magic-word' || this.name !== 'invoke') {
684
- throw new Error(`${this.constructor.name}.replaceModule 方法仅用于更换模块!`);
685
- } else if (typeof func !== 'string') {
686
- this.typeError('replaceFunction', 'String');
687
- } else if (this.length < 2) {
688
- throw new Error('尚未指定模块名称!');
689
- }
690
- const root = Parser.parse(
691
- `{{#invoke:M|${func}}}`, this.getAttribute('include'), 2, this.getAttribute('config'),
692
- ),
693
- {length, firstChild: invoke} = root,
694
- {type, name, length: invokeLength, lastChild} = invoke;
695
- if (length !== 1 || type !== 'magic-word' || name !== 'invoke' || invokeLength !== 3) {
696
- throw new SyntaxError(`非法的模块函数名:${func}`);
697
- } else if (this.length > 2) {
698
- this.childNodes[2].replaceChildren(...lastChild.childNodes);
699
- } else {
700
- invoke.destroy(true);
701
- this.insertAt(lastChild);
702
- }
703
- }
704
-
705
- /**
706
- * 是否存在重名参数
707
- * @complexity `n`
708
- * @throws `Error` 仅用于模板
709
- */
710
- hasDuplicatedArgs() {
711
- if (this.isTemplate()) {
712
- return this.getAllArgs().length - this.getKeys().length;
713
- }
714
- throw new Error(`${this.constructor.name}.hasDuplicatedArgs 方法仅供模板使用!`);
715
- }
716
-
717
- /**
718
- * 修复重名参数:
719
- * `aggressive = false`时只移除空参数和全同参数,优先保留匿名参数,否则将所有匿名参数更改为命名。
720
- * `aggressive = true`时还会尝试处理连续的以数字编号的参数。
721
- * @param {boolean} aggressive 是否使用有更大风险的修复手段
722
- * @complexity `n²`
723
- */
724
- fixDuplication(aggressive) {
725
- if (!this.hasDuplicatedArgs()) {
726
- return [];
727
- }
728
- const /** @type {string[]} */ duplicatedKeys = [];
729
- let {length: anonCount} = this.getAnonArgs();
730
- for (const [key, args] of this.getDuplicatedArgs()) {
731
- if (args.length <= 1) {
732
- continue;
733
- }
734
- const /** @type {Record<string, ParameterToken[]>} */ values = {};
735
- for (const arg of args) {
736
- const val = arg.getValue().trim();
737
- if (Object.hasOwn(values, val)) {
738
- values[val].push(arg);
739
- } else {
740
- values[val] = [arg];
741
- }
742
- }
743
- let noMoreAnon = anonCount === 0 || isNaN(key);
744
- const emptyArgs = values[''] ?? [],
745
- duplicatedArgs = Object.entries(values).filter(([val, {length}]) => val && length > 1)
746
- .flatMap(([, curArgs]) => {
747
- const anonIndex = noMoreAnon ? -1 : curArgs.findIndex(({anon}) => anon);
748
- if (anonIndex !== -1) {
749
- noMoreAnon = true;
750
- }
751
- curArgs.splice(anonIndex, 1);
752
- return curArgs;
753
- }),
754
- badArgs = [...emptyArgs, ...duplicatedArgs],
755
- index = noMoreAnon ? -1 : emptyArgs.findIndex(({anon}) => anon);
756
- if (badArgs.length === args.length) {
757
- badArgs.splice(index, 1);
758
- } else if (index !== -1) {
759
- this.anonToNamed();
760
- anonCount = 0;
761
- }
762
- for (const arg of badArgs) {
763
- arg.remove();
764
- }
765
- let remaining = args.length - badArgs.length;
766
- if (remaining === 1) {
767
- continue;
768
- } else if (aggressive && (anonCount ? /\D\d+$/u : /(?:^|\D)\d+$/u).test(key)) {
769
- let /** @type {number} */ last;
770
- const str = key.slice(0, -/(?<!\d)\d+$/u.exec(key)[0].length),
771
- regex = new RegExp(`^${escapeRegExp(str)}\\d+$`, 'u'),
772
- series = this.getAllArgs().filter(({name}) => regex.test(name)),
773
- ordered = series.every(({name}, i) => {
774
- const j = Number(name.slice(str.length)),
775
- cmp = j <= i + 1 && (i === 0 || j >= last || name === key);
776
- last = j;
777
- return cmp;
778
- });
779
- if (ordered) {
780
- for (let i = 0; i < series.length; i++) {
781
- const name = `${str}${i + 1}`,
782
- arg = series[i];
783
- if (arg.name !== name) {
784
- if (arg.name === key) {
785
- remaining--;
786
- }
787
- arg.rename(name, true);
788
- }
789
- }
790
- }
791
- }
792
- if (remaining > 1) {
793
- Parser.error(`${this.type === 'template'
794
- ? this.name
795
- : this.normalizeTitle(this.childNodes[1]?.text() ?? '', 828).title
796
- } 还留有 ${remaining} 个重复的 ${key} 参数:${[...this.getArgs(key)].map(arg => {
797
- const {top, left} = arg.getBoundingClientRect();
798
- return `第 ${top} 行第 ${left} 列`;
799
- }).join('、')}`);
800
- duplicatedKeys.push(key);
801
- continue;
802
- }
803
- }
804
- return duplicatedKeys;
805
- }
806
-
807
- /**
808
- * 转义模板内的表格
809
- * @returns {TranscludeToken}
810
- * @complexity `n`
811
- * @throws `Error` 转义失败
812
- */
813
- escapeTables() {
814
- const count = this.hasDuplicatedArgs();
815
- if (!/\n[^\S\n]*(?::+\s*)?\{\|[^\n]*\n\s*(?:\S[^\n]*\n\s*)*\|\}/u.test(this.text()) || !count) {
816
- return this;
817
- }
818
- const stripped = String(this).slice(2, -2),
819
- include = this.getAttribute('include'),
820
- config = this.getAttribute('config'),
821
- parsed = Parser.parse(stripped, include, 4, config);
822
- const TableToken = require('./table');
823
- for (const table of parsed.childNodes) {
824
- if (table instanceof TableToken) {
825
- table.escape();
826
- }
827
- }
828
- const {firstChild, childNodes} = Parser.parse(`{{${String(parsed)}}}`, include, 2, config);
829
- if (childNodes.length !== 1 || !(firstChild instanceof TranscludeToken)) {
830
- throw new Error('转义表格失败!');
831
- }
832
- const newCount = firstChild.hasDuplicatedArgs();
833
- if (newCount === count) {
834
- return this;
835
- }
836
- Parser.info(`共修复了 ${count - newCount} 个重复参数。`);
837
- this.safeReplaceWith(firstChild);
838
- return firstChild;
839
- }
840
- }
841
-
842
- Parser.classes.TranscludeToken = __filename;
843
- module.exports = TranscludeToken;