@the_dissidents/libemmm 0.0.8 → 0.0.9

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/dist/index.mjs DELETED
@@ -1,3366 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/interface.ts
8
- var MessageSeverity = /* @__PURE__ */ ((MessageSeverity2) => {
9
- MessageSeverity2[MessageSeverity2["Info"] = 0] = "Info";
10
- MessageSeverity2[MessageSeverity2["Warning"] = 1] = "Warning";
11
- MessageSeverity2[MessageSeverity2["Error"] = 2] = "Error";
12
- return MessageSeverity2;
13
- })(MessageSeverity || {});
14
- var NodeType = /* @__PURE__ */ ((NodeType2) => {
15
- NodeType2[NodeType2["Root"] = 0] = "Root";
16
- NodeType2[NodeType2["Paragraph"] = 1] = "Paragraph";
17
- NodeType2[NodeType2["Preformatted"] = 2] = "Preformatted";
18
- NodeType2[NodeType2["Text"] = 3] = "Text";
19
- NodeType2[NodeType2["Escaped"] = 4] = "Escaped";
20
- NodeType2[NodeType2["SystemModifier"] = 5] = "SystemModifier";
21
- NodeType2[NodeType2["InlineModifier"] = 6] = "InlineModifier";
22
- NodeType2[NodeType2["BlockModifier"] = 7] = "BlockModifier";
23
- NodeType2[NodeType2["Interpolation"] = 8] = "Interpolation";
24
- return NodeType2;
25
- })(NodeType || {});
26
- var ModifierSlotType = /* @__PURE__ */ ((ModifierSlotType2) => {
27
- ModifierSlotType2[ModifierSlotType2["Normal"] = 0] = "Normal";
28
- ModifierSlotType2[ModifierSlotType2["Preformatted"] = 1] = "Preformatted";
29
- ModifierSlotType2[ModifierSlotType2["None"] = 2] = "None";
30
- return ModifierSlotType2;
31
- })(ModifierSlotType || {});
32
- var ModifierBase = class {
33
- constructor(name, slotType = 0 /* Normal */, args) {
34
- this.name = name;
35
- this.slotType = slotType;
36
- if (args) Object.assign(this, args);
37
- }
38
- /**
39
- * Common values: heading, emphasis, keyword, highlight, commentary, comment, link, quote
40
- */
41
- roleHint;
42
- /**
43
- * If true, any modifier encountered inside it will *not* be expanded *during parse-content*,
44
- * *unless* that modifier is `alwaysTryExpand`. In the vast majority of cases, you shouldn't
45
- * be using this.
46
- */
47
- delayContentExpansion = false;
48
- /**
49
- * If true, such a modifier will always be expanded whenever it is encountered, *even if*
50
- * it is contained in a modifier with `delayContentExpansion`. In the vast majority of cases,
51
- * you shouldn't be using this.
52
- */
53
- alwaysTryExpand = false;
54
- /** Called before the modifier's content is parsed.
55
- * @param immediate False when the node is inside a `delayContentExpansion` modifier, but it is `alwaysTryExpand`; otherwise true.
56
- */
57
- beforeParseContent;
58
- /** Called after the modifier's content is parsed.
59
- * @param immediate False when the node is inside a `delayContentExpansion` modifier, but it is `alwaysTryExpand`; otherwise true.
60
- */
61
- afterParseContent;
62
- /** Called before reparsing of the expansion.
63
- * @param immediate False when the node is inside a `delayContentExpansion` modifier, but it is `alwaysTryExpand`; otherwise true.*/
64
- beforeProcessExpansion;
65
- /** Called before reparsing of the expansion.
66
- * @param immediate False when the node is inside a `delayContentExpansion` modifier, but it is `alwaysTryExpand`; otherwise true.*/
67
- afterProcessExpansion;
68
- /**
69
- * @param immediate False when the node is inside a `delayContentExpansion` modifier, but it is `alwaysTryExpand`; otherwise true.
70
- */
71
- prepareExpand;
72
- /**
73
- * @param immediate False when the node is inside a `delayContentExpansion` modifier, but it is `alwaysTryExpand`; otherwise true.
74
- */
75
- expand;
76
- };
77
- var BlockModifierDefinition = class extends ModifierBase {
78
- };
79
- var InlineModifierDefinition = class extends ModifierBase {
80
- };
81
- var SystemModifierDefinition = class extends ModifierBase {
82
- };
83
- var ArgumentInterpolatorDefinition = class {
84
- constructor(name, postfix, args) {
85
- this.name = name;
86
- this.postfix = postfix;
87
- if (args) Object.assign(this, args);
88
- }
89
- alwaysTryExpand = false;
90
- expand;
91
- };
92
-
93
- // src/util.ts
94
- var NameManager = class _NameManager {
95
- array = [];
96
- data = /* @__PURE__ */ new Map();
97
- constructor(from) {
98
- if (from === void 0) return;
99
- if (from instanceof _NameManager) {
100
- this.array = [...from.array];
101
- this.data = new Map(from.data);
102
- } else {
103
- const array = [...from];
104
- assert((from instanceof Set ? from : new Set(array)).size == array.length);
105
- this.array = array.map((x) => ({ k: x.name, v: x }));
106
- this.array.sort((a, b) => b.k.length - a.k.length);
107
- this.data = new Map(array.map((x) => [x.name, x]));
108
- }
109
- }
110
- toArray() {
111
- return this.array.map(({ v }) => v);
112
- }
113
- toSet() {
114
- return new Set(this.toArray());
115
- }
116
- get(name) {
117
- return this.data.get(name);
118
- }
119
- has(name) {
120
- return this.data.has(name);
121
- }
122
- remove(name) {
123
- let i = this.data.get(name);
124
- assert(i !== void 0);
125
- this.data.delete(name);
126
- this.array.splice(this.array.findIndex((x) => x.k == name), 1);
127
- }
128
- add(...elems) {
129
- for (const elem of elems) {
130
- assert(!this.has(elem.name));
131
- this.data.set(elem.name, elem);
132
- const len = elem.name.length;
133
- let i = 0;
134
- while (i < this.array.length && this.array[i].k.length > len) i++;
135
- this.array.splice(i, 0, { k: elem.name, v: elem });
136
- }
137
- }
138
- find(predicate) {
139
- const result = this.array.find((x) => predicate(x.v));
140
- return result ? result.v : void 0;
141
- }
142
- };
143
- function assert(x) {
144
- if (!!!x) {
145
- let error = new Error("assertion failed");
146
- console.log(error.stack);
147
- throw error;
148
- }
149
- }
150
- var cloneArgument = (arg, options) => ({
151
- location: clonePosition(arg.location, options),
152
- content: arg.content.map((ent) => {
153
- switch (ent.type) {
154
- case 3 /* Text */:
155
- case 4 /* Escaped */:
156
- return structuredClone(ent);
157
- case 8 /* Interpolation */:
158
- return {
159
- type: ent.type,
160
- location: clonePosition(arg.location, options),
161
- definition: ent.definition,
162
- argument: cloneArgument(ent.argument, options),
163
- expansion: ent.expansion
164
- };
165
- default:
166
- return debug.never(ent);
167
- }
168
- })
169
- });
170
- function clonePosition(pos, options) {
171
- let base = options.newLocation ?? pos;
172
- return {
173
- start: base.start,
174
- end: base.end,
175
- actualEnd: base.actualEnd,
176
- original: options.newLocation ? pos : pos.original,
177
- source: base.source
178
- };
179
- }
180
- function cloneNode(node, options = {}) {
181
- switch (node.type) {
182
- case 7 /* BlockModifier */:
183
- case 6 /* InlineModifier */:
184
- case 5 /* SystemModifier */:
185
- return {
186
- location: clonePosition(node.location, options),
187
- type: node.type,
188
- mod: node.mod,
189
- state: options.withState ? node.state : void 0,
190
- head: structuredClone(node.head),
191
- arguments: node.arguments.map((x) => cloneArgument(x, options)),
192
- content: node.content.map((x) => cloneNode(x, options)),
193
- expansion: node.expansion ? cloneNodes(node.expansion, options) : void 0
194
- };
195
- case 0 /* Root */:
196
- return {
197
- type: node.type,
198
- source: node.source,
199
- content: node.content.map((x) => cloneNode(x, options))
200
- };
201
- case 1 /* Paragraph */:
202
- return {
203
- type: node.type,
204
- location: clonePosition(node.location, options),
205
- content: node.content.map((x) => cloneNode(x, options))
206
- };
207
- case 2 /* Preformatted */:
208
- case 3 /* Text */:
209
- case 4 /* Escaped */:
210
- return structuredClone(node);
211
- default:
212
- return debug.never(node);
213
- }
214
- }
215
- function cloneNodes(nodes, options = {}) {
216
- return nodes.map((x) => cloneNode(x, options));
217
- }
218
- function stripNode(...nodes) {
219
- return nodes.flatMap((node) => {
220
- switch (node.type) {
221
- case 2 /* Preformatted */:
222
- case 3 /* Text */:
223
- case 4 /* Escaped */:
224
- return [node];
225
- case 7 /* BlockModifier */:
226
- case 6 /* InlineModifier */:
227
- if (node.expansion !== void 0)
228
- return node.expansion.flatMap((x) => stripNode(x));
229
- // else fallthrough!
230
- case 1 /* Paragraph */:
231
- case 0 /* Root */:
232
- node.content = node.content.flatMap((x) => stripNode(x));
233
- return [node];
234
- case 5 /* SystemModifier */:
235
- return [];
236
- default:
237
- return debug.never(node);
238
- }
239
- });
240
- }
241
-
242
- // src/debug.ts
243
- var DebugLevel = /* @__PURE__ */ ((DebugLevel3) => {
244
- DebugLevel3[DebugLevel3["Trace"] = 0] = "Trace";
245
- DebugLevel3[DebugLevel3["Info"] = 1] = "Info";
246
- DebugLevel3[DebugLevel3["Warning"] = 2] = "Warning";
247
- DebugLevel3[DebugLevel3["Error"] = 3] = "Error";
248
- DebugLevel3[DebugLevel3["None"] = 4] = "None";
249
- return DebugLevel3;
250
- })(DebugLevel || {});
251
- var debug = {
252
- level: 1 /* Info */,
253
- trace(arg0, ...args) {
254
- if (this.level > 0 /* Trace */) return;
255
- if (typeof arg0 == "function") arg0 = arg0();
256
- console.info("TRACE", arg0, ...args);
257
- },
258
- info(arg0, ...args) {
259
- if (this.level > 1 /* Info */) return;
260
- if (typeof arg0 == "function") arg0 = arg0();
261
- console.info(" INFO", arg0, ...args);
262
- },
263
- warning(arg0, ...args) {
264
- if (this.level > 2 /* Warning */) return;
265
- if (typeof arg0 == "function") arg0 = arg0();
266
- console.warn(" WARN", arg0, ...args);
267
- },
268
- error(arg0, ...args) {
269
- if (this.level > 3 /* Error */) return;
270
- if (typeof arg0 == "function") arg0 = arg0();
271
- console.error("ERROR", arg0, ...args);
272
- },
273
- never(_) {
274
- assert(false);
275
- }
276
- };
277
-
278
- // src/source.ts
279
- var StringSource = class {
280
- constructor(d, src) {
281
- this.src = src;
282
- this.name = d.name;
283
- this.lineMap = [0];
284
- [...src].forEach((x, i) => {
285
- if (x == "\n") this.lineMap.push(i + 1);
286
- });
287
- this.nLines = this.lineMap.length;
288
- this.lineMap.push(Infinity);
289
- }
290
- name;
291
- nLines;
292
- lineMap;
293
- getRowCol(pos) {
294
- let line = -1, linepos = 0;
295
- for (let i = 1; i < this.lineMap.length; i++) {
296
- if (this.lineMap[i] > pos) {
297
- line = i - 1;
298
- linepos = this.lineMap[i - 1];
299
- break;
300
- }
301
- }
302
- return [line, pos - linepos];
303
- }
304
- getRowStart(n) {
305
- assert(n >= 0);
306
- if (n >= this.lineMap.length) return Infinity;
307
- return this.lineMap[n];
308
- }
309
- getRow(n) {
310
- const start = this.getRowStart(n);
311
- const end = this.getRowStart(n + 1);
312
- if (start === Infinity) return void 0;
313
- return this.src.substring(start, end - 1);
314
- }
315
- };
316
-
317
- // src/scanner.ts
318
- var SimpleScanner = class {
319
- constructor(src, sourceDesc = { name: "<input>" }) {
320
- this.src = src;
321
- this.source = new StringSource(sourceDesc, src);
322
- }
323
- source;
324
- pos = 0;
325
- position() {
326
- return this.pos;
327
- }
328
- isEOF() {
329
- return this.pos >= this.src.length;
330
- }
331
- peek(str) {
332
- assert(str !== "");
333
- let next = this.pos + str.length;
334
- if (next > this.src.length) return false;
335
- return this.src.slice(this.pos, this.pos + str.length) == str;
336
- }
337
- acceptChar() {
338
- if (this.isEOF()) throw new RangeError("EOF");
339
- let char = this.src[this.pos];
340
- this.pos++;
341
- return char;
342
- }
343
- accept(str) {
344
- if (!this.peek(str)) return false;
345
- this.pos += str.length;
346
- return true;
347
- }
348
- acceptWhitespaceChar() {
349
- if (this.isEOF()) return null;
350
- let char = this.src[this.pos];
351
- if (!" ".includes(char)) return null;
352
- this.pos++;
353
- return char;
354
- }
355
- };
356
-
357
- // src/debug-print.ts
358
- var debugPrint = {
359
- blockModifier: (x) => `[.${x.name}] (${ModifierSlotType[x.slotType]})`,
360
- inlineModifier: (x) => `[/${x.name}] (${ModifierSlotType[x.slotType]})`,
361
- inlineShorthand: (x) => x.name + x.parts.map((x2, i) => ` .. <arg${i}> .. ${x2}`).join("") + (x.mod.slotType == 2 /* None */ ? "" : ` .. <slot> .. ${x.postfix ?? "<no postfix>"}`),
362
- blockShorthand: (x) => x.name + x.parts.map((x2, i) => ` .. <arg${i}> .. ${x2}`).join("") + (x.mod.slotType == 2 /* None */ ? "" : ` .. <slot> .. ${x.postfix ?? "<no postfix>"}`),
363
- argument: (arg) => arg.content.map(debugPrintArgEntity).join(""),
364
- node: (...nodes) => nodes.map((x) => debugPrintNode(x)).join("\n"),
365
- message: debugPrintMsg,
366
- range: debugPrintRange,
367
- document: debugDumpDocument
368
- };
369
- function debugPrintArgEntity(node) {
370
- switch (node.type) {
371
- case 3 /* Text */:
372
- return node.content;
373
- case 4 /* Escaped */:
374
- return `<Escaped:${node.content}>`;
375
- case 8 /* Interpolation */:
376
- return `<Interp:${node.definition.name}-${node.definition.postfix}:${debugPrint.argument(node.argument)}${node.expansion ? `=${node.expansion}` : ""}>`;
377
- default:
378
- return debug.never(node);
379
- }
380
- }
381
- function debugPrintNode(node, prefix = "") {
382
- function debugPrintNodes(content, prefix2 = "") {
383
- let dumps = content.map((x) => debugPrintNode(x, prefix2 + " ")).filter((x) => x.length > 0);
384
- if (dumps.length == 0) return "";
385
- return dumps.map((x) => `${prefix2} ${x}`).join("\n");
386
- }
387
- let result = `<${NodeType[node.type]}@${node.location.start}`;
388
- switch (node.type) {
389
- case 1 /* Paragraph */:
390
- const content = debugPrintNodes(node.content, prefix);
391
- if (content.length > 0)
392
- result += `>
393
- ${content}
394
- ${prefix}</${NodeType[node.type]}@${node.location.end}>`;
395
- else result += `-${node.location.end} />`;
396
- break;
397
- case 4 /* Escaped */:
398
- result += `>
399
- ${prefix} ${node.content}
400
- ${prefix}</${NodeType[node.type]}@${node.location.end}>`;
401
- break;
402
- case 2 /* Preformatted */:
403
- result += `>
404
- ${prefix} ${node.content.text}
405
- ${prefix}</${NodeType[node.type]}@${node.location.end}>`;
406
- break;
407
- case 6 /* InlineModifier */:
408
- case 7 /* BlockModifier */:
409
- case 5 /* SystemModifier */:
410
- const args = node.arguments.map((x, i) => `
411
- ${prefix} (${i})@${x.location.start}-${x.location.end}=${debugPrint.argument(x)}`).join("");
412
- if (node.content.length > 0) {
413
- result += ` id=${node.mod.name}${args}>
414
- ` + debugPrintNodes(node.content, prefix) + `
415
- ${prefix}</${NodeType[node.type]}@${node.location.end}>`;
416
- } else result += `-${node.location.end} id=${node.mod.name}${args} />`;
417
- if (node.expansion) {
418
- const content2 = debugPrintNodes(node.expansion, prefix);
419
- if (content2.length > 0)
420
- result += `
421
- ${prefix}<expansion>
422
- ${content2}
423
- ${prefix}</expansion>`;
424
- else if (node.type != 5 /* SystemModifier */)
425
- result += `
426
- ${prefix}<expansion />`;
427
- }
428
- break;
429
- case 3 /* Text */:
430
- return node.content;
431
- default:
432
- return debug.never(node);
433
- }
434
- return result;
435
- }
436
- function debugPrintRange(loc, context = 1) {
437
- const isSingleCharacter = loc.start == loc.end;
438
- let [sr, sc] = loc.source.getRowCol(loc.start);
439
- let [er, ec] = loc.source.getRowCol(loc.actualEnd ?? loc.end);
440
- const rowWidth = Math.max((sr + 1).toString().length, (er + 1).toString().length);
441
- const startLine = Math.max(0, sr - context);
442
- const endLine = Math.min(loc.source.nLines - 1, er + context);
443
- let lines = [];
444
- for (let i = startLine; i <= endLine; i++) {
445
- const line = loc.source.getRow(i);
446
- lines.push((i + 1).toString().padStart(rowWidth) + " | " + line);
447
- if (i >= sr && i <= er) {
448
- const startPos = i == sr ? sc : 0;
449
- const endPos = i == er ? ec : line.length;
450
- lines.push(
451
- " ".repeat(rowWidth) + " | " + " ".repeat(startPos) + (isSingleCharacter ? "^" : "~".repeat(endPos - startPos + 1))
452
- );
453
- }
454
- }
455
- return lines.join("\n");
456
- }
457
- function debugPrintMsg(m) {
458
- const poss = (loc2) => {
459
- const [r1, c1] = loc2.source.getRowCol(loc2.start);
460
- if (loc2.start == loc2.end) return `l${r1 + 1}c${c1 + 1}`;
461
- const [r2, c2] = loc2.source.getRowCol(loc2.end);
462
- return `l${r1 + 1}c${c1 + 1}-l${r2 + 1}c${c2 + 1}`;
463
- };
464
- let loc = m.location;
465
- let result = `at ${poss(loc)}: ${MessageSeverity[m.severity]}[${m.code}]: ${m.info}`;
466
- while (loc = loc.original) {
467
- let d = loc.source !== m.location.source ? `(in ${loc.source.name}) ` : "";
468
- result += `
469
- ---> original at: ${d}${poss(loc)}`;
470
- }
471
- return result;
472
- }
473
- function debugDumpDocument(doc) {
474
- let root = debugPrint.node(...doc.root.content);
475
- let msgs = doc.messages.map((x) => debugPrintRange(x.location) + "\n" + debugPrintMsg(x)).join("\n");
476
- if (msgs.length > 0) msgs += "\n";
477
- return `Document: ${doc.root.source.name}
478
- ${msgs}${root}`;
479
- }
480
-
481
- // src/messages.ts
482
- var messages_exports = {};
483
- __export(messages_exports, {
484
- ArgumentCountMismatchMessage: () => ArgumentCountMismatchMessage,
485
- CannotExpandArgumentMessage: () => CannotExpandArgumentMessage,
486
- CannotUseModuleInSelfMessage: () => CannotUseModuleInSelfMessage,
487
- EitherNormalOrPreMessage: () => EitherNormalOrPreMessage,
488
- EntityNotAllowedMessage: () => EntityNotAllowedMessage,
489
- ExpectedMessage: () => ExpectedMessage,
490
- InvalidArgumentMessage: () => InvalidArgumentMessage,
491
- MultipleBlocksNotPermittedMessage: () => MultipleBlocksNotPermittedMessage,
492
- NameAlreadyDefinedMessage: () => NameAlreadyDefinedMessage,
493
- NewBlockShouldBeOnNewlineMessage: () => NewBlockShouldBeOnNewlineMessage,
494
- NoNestedModuleMessage: () => NoNestedModuleMessage,
495
- OnlySimpleParagraphsPermittedMessage: () => OnlySimpleParagraphsPermittedMessage,
496
- OverwriteDefinitionsMessage: () => OverwriteDefinitionsMessage,
497
- OverwriteSpecialVariableMessage: () => OverwriteSpecialVariableMessage,
498
- ReachedRecursionLimitMessage: () => ReachedRecursionLimitMessage,
499
- ShouldBeOnNewlineMessage: () => ShouldBeOnNewlineMessage,
500
- SlotUsedOutsideDefinitionMessage: () => SlotUsedOutsideDefinitionMessage,
501
- UnclosedInlineModifierMessage: () => UnclosedInlineModifierMessage,
502
- UndefinedVariableMessage: () => UndefinedVariableMessage,
503
- UnknownModifierMessage: () => UnknownModifierMessage,
504
- UnnecessaryNewlineMessage: () => UnnecessaryNewlineMessage
505
- });
506
- var AddThingMessage = class {
507
- constructor(code, severity, location, info) {
508
- this.code = code;
509
- this.severity = severity;
510
- this.location = location;
511
- this.info = info;
512
- }
513
- // get fixes(): readonly FixSuggestion[] {
514
- // let [start, what, fixstr] = [this.location.start, this.what, this.fixstr];
515
- // return [{
516
- // get info() { return fixstr; },
517
- // apply(src: string, cursor: number) {
518
- // let newCursor = (cursor < start)
519
- // ? cursor
520
- // : cursor + what.length;
521
- // return [src.substring(0, start) + what + src.substring(start), newCursor];
522
- // }
523
- // }];
524
- // }
525
- };
526
- var RemoveThingMessage = class {
527
- constructor(code, severity, location, info) {
528
- this.code = code;
529
- this.severity = severity;
530
- this.location = location;
531
- this.info = info;
532
- }
533
- // get fixes(): readonly FixSuggestion[] {
534
- // let [start, end, fixstr] = [this.start, this.end, this.fixstr];
535
- // return [{
536
- // get info() { return fixstr; },
537
- // apply(src: string, cursor: number) {
538
- // let newCursor = (cursor < end && cursor >= start)
539
- // ? start
540
- // : cursor; // Removing text, cursor shouldn't shift if it's outside the removed range
541
- // return [src.substring(0, start) + src.substring(end), newCursor];
542
- // }
543
- // }];
544
- // }
545
- };
546
- var ExpectedMessage = class {
547
- constructor(location, what) {
548
- this.location = location;
549
- this.what = what;
550
- assert(location.end == location.start);
551
- }
552
- code = 1;
553
- severity = 2 /* Error */;
554
- get info() {
555
- return `expected '${this.what}'`;
556
- }
557
- };
558
- var UnknownModifierMessage = class {
559
- constructor(location, what) {
560
- this.location = location;
561
- this.what = what;
562
- }
563
- code = 2;
564
- severity = 2 /* Error */;
565
- get info() {
566
- return `unknown modifier '${this.what}'`;
567
- }
568
- // get fixes(): readonly FixSuggestion[] {
569
- // let [start, end] = [this.start, this.end];
570
- // return [{
571
- // get info() { return 'this is not a modifier -- escape it'; },
572
- // apply(src: string, cursor: number) {
573
- // let newCursor = (cursor < start)
574
- // ? cursor
575
- // : cursor + 1;
576
- // return [src.substring(0, start) + '\\' + src.substring(start), newCursor];
577
- // }
578
- // }];
579
- // }
580
- };
581
- var UnclosedInlineModifierMessage = class {
582
- constructor(location, what) {
583
- this.location = location;
584
- this.what = what;
585
- assert(location.end == location.start);
586
- }
587
- code = 3;
588
- severity = 2 /* Error */;
589
- get info() {
590
- return `unclosed inline modifier ${this.what}'`;
591
- }
592
- };
593
- var ArgumentCountMismatchMessage = class {
594
- constructor(location, min, max) {
595
- this.location = location;
596
- if (min !== void 0) {
597
- if (max == min) this.msg = `: ${min} expected`;
598
- else if (max !== void 0) this.msg = `: ${min} to ${max} expected`;
599
- else this.msg = `: at least ${min} expected`;
600
- } else {
601
- if (max !== void 0) this.msg = `: at most ${max} expected`;
602
- }
603
- }
604
- msg = "";
605
- code = 4;
606
- severity = 2 /* Error */;
607
- get info() {
608
- return `argument count mismatch` + this.msg;
609
- }
610
- };
611
- var CannotExpandArgumentMessage = class {
612
- constructor(location, what) {
613
- this.location = location;
614
- this.what = what;
615
- }
616
- code = 5;
617
- severity = 2 /* Error */;
618
- get info() {
619
- return `failed to expand argument` + (this.what === void 0 ? "" : `: ${this.what}`);
620
- }
621
- };
622
- var InvalidArgumentMessage = class {
623
- constructor(location, what) {
624
- this.location = location;
625
- this.what = what;
626
- }
627
- code = 6;
628
- severity = 2 /* Error */;
629
- get info() {
630
- return `invalid argument` + (this.what === void 0 ? "" : `: ${this.what}`);
631
- }
632
- };
633
- var EntityNotAllowedMessage = class {
634
- constructor(location, what) {
635
- this.location = location;
636
- this.what = what;
637
- }
638
- code = 7;
639
- severity = 2 /* Error */;
640
- get info() {
641
- return "This entity is not allowed here" + (this.what ? `: ${this.what}` : "");
642
- }
643
- };
644
- var ReachedRecursionLimitMessage = class {
645
- constructor(location, limit, what) {
646
- this.location = location;
647
- this.limit = limit;
648
- this.what = what;
649
- }
650
- code = 8;
651
- severity = 2 /* Error */;
652
- get info() {
653
- return `Reached recursion limit ${this.limit} when expanding ${this.what}`;
654
- }
655
- };
656
- var SlotUsedOutsideDefinitionMessage = class {
657
- constructor(location) {
658
- this.location = location;
659
- }
660
- code = 9;
661
- severity = 2 /* Error */;
662
- get info() {
663
- return `slot used outside a definition`;
664
- }
665
- };
666
- var NoNestedModuleMessage = class {
667
- constructor(location) {
668
- this.location = location;
669
- }
670
- code = 10;
671
- severity = 2 /* Error */;
672
- get info() {
673
- return `nested module definitions not allowed`;
674
- }
675
- };
676
- var CannotUseModuleInSelfMessage = class {
677
- constructor(location) {
678
- this.location = location;
679
- }
680
- code = 11;
681
- severity = 2 /* Error */;
682
- get info() {
683
- return `cannot use the same module inside its definition`;
684
- }
685
- };
686
- var EitherNormalOrPreMessage = class {
687
- constructor(location) {
688
- this.location = location;
689
- }
690
- code = 12;
691
- severity = 2 /* Error */;
692
- get info() {
693
- return `a definition cannot be at once normal and preformatted`;
694
- }
695
- };
696
- var MultipleBlocksNotPermittedMessage = class {
697
- constructor(location) {
698
- this.location = location;
699
- }
700
- code = 13;
701
- severity = 2 /* Error */;
702
- get info() {
703
- return `multiple blocks are not permitted here`;
704
- }
705
- };
706
- var OnlySimpleParagraphsPermittedMessage = class {
707
- constructor(location) {
708
- this.location = location;
709
- }
710
- code = 14;
711
- severity = 2 /* Error */;
712
- get info() {
713
- return `Only simple paragraphs are permitted here`;
714
- }
715
- };
716
- var UnnecessaryNewlineMessage = class extends RemoveThingMessage {
717
- constructor(location) {
718
- super(
719
- 1,
720
- 1 /* Warning */,
721
- location,
722
- "more than one newlines have the same effect as one"
723
- );
724
- }
725
- };
726
- var NewBlockShouldBeOnNewlineMessage = class extends AddThingMessage {
727
- constructor(location) {
728
- super(
729
- 2,
730
- 1 /* Warning */,
731
- location,
732
- "a new block should begin in a new line to avoid confusion"
733
- );
734
- }
735
- };
736
- var ShouldBeOnNewlineMessage = class extends AddThingMessage {
737
- constructor(location) {
738
- super(
739
- 3,
740
- 1 /* Warning */,
741
- location,
742
- "the following should begin in a new line to avoid confusion"
743
- );
744
- }
745
- };
746
- var NameAlreadyDefinedMessage = class {
747
- constructor(location, what) {
748
- this.location = location;
749
- this.what = what;
750
- }
751
- code = 4;
752
- severity = 1 /* Warning */;
753
- get info() {
754
- return `name is already defined, will overwrite: ${this.what}`;
755
- }
756
- };
757
- var UndefinedVariableMessage = class {
758
- constructor(location, what) {
759
- this.location = location;
760
- this.what = what;
761
- }
762
- code = 5;
763
- severity = 1 /* Warning */;
764
- get info() {
765
- return `variable is undefined, will expand to empty string: ${this.what}`;
766
- }
767
- };
768
- var OverwriteDefinitionsMessage = class {
769
- constructor(location, what) {
770
- this.location = location;
771
- this.what = what;
772
- }
773
- code = 6;
774
- severity = 1 /* Warning */;
775
- get info() {
776
- return `using this module will overwrite: ${this.what}`;
777
- }
778
- };
779
- var OverwriteSpecialVariableMessage = class {
780
- constructor(location, varname, previous) {
781
- this.location = location;
782
- this.varname = varname;
783
- this.previous = previous;
784
- }
785
- code = 6;
786
- severity = 1 /* Warning */;
787
- get info() {
788
- return `${this.varname} is already defined (as "${this.previous}"), will be overwritten`;
789
- }
790
- };
791
-
792
- // src/parser-config.ts
793
- var ParseContext = class {
794
- constructor(config2, variables = /* @__PURE__ */ new Map()) {
795
- this.config = config2;
796
- this.variables = variables;
797
- config2.initializers.forEach((x) => x(this));
798
- }
799
- data = {};
800
- init(key, obj) {
801
- assert(!(key in this.data));
802
- this.data[key] = obj;
803
- }
804
- set(key, obj) {
805
- assert(key in this.data);
806
- this.data[key] = obj;
807
- }
808
- get(key) {
809
- assert(key in this.data);
810
- return this.data[key];
811
- }
812
- };
813
- var Document = class _Document {
814
- constructor(root, context, messages) {
815
- this.root = root;
816
- this.context = context;
817
- this.messages = messages;
818
- }
819
- toStripped() {
820
- let doc = new _Document(
821
- stripNode(cloneNode(this.root, { withState: true }))[0],
822
- this.context,
823
- this.messages
824
- );
825
- return doc;
826
- }
827
- /**
828
- * Performs a depth-first walk of the node tree.
829
- */
830
- walk(callback) {
831
- let nodes = this.root.content;
832
- let node;
833
- while (node = nodes.shift()) {
834
- const result = callback(node);
835
- if (result == "break") break;
836
- if (result == "skip") continue;
837
- if ("arguments" in node)
838
- nodes.push(...node.arguments.flatMap((x) => x.content));
839
- if ("content" in node && Array.isArray(node.content))
840
- nodes.push(...node.content);
841
- }
842
- }
843
- /**
844
- * Gets all nodes that covers the given position, from outermost to innermost (essentially a path).
845
- */
846
- resolvePosition(pos) {
847
- const result = [];
848
- let nodes = this.root.content;
849
- let node;
850
- while (node = nodes.shift()) {
851
- if (node.location.start <= pos && (node.location.actualEnd ?? node.location.end) >= pos) {
852
- result.push(node);
853
- nodes = [];
854
- if ("arguments" in node)
855
- nodes.push(...node.arguments.flatMap((x) => x.content));
856
- if ("content" in node && Array.isArray(node.content))
857
- nodes.push(...node.content);
858
- }
859
- }
860
- return result;
861
- }
862
- };
863
- var Configuration = class _Configuration {
864
- initializers = [];
865
- blockModifiers = new NameManager();
866
- inlineModifiers = new NameManager();
867
- systemModifiers = new NameManager();
868
- argumentInterpolators = new NameManager();
869
- blockShorthands = new NameManager();
870
- inlineShorthands = new NameManager();
871
- reparseDepthLimit = 10;
872
- static from(from) {
873
- let config2 = new _Configuration();
874
- config2.initializers = [...from.initializers];
875
- config2.reparseDepthLimit = from.reparseDepthLimit;
876
- config2.blockModifiers = new NameManager(from.blockModifiers);
877
- config2.inlineModifiers = new NameManager(from.inlineModifiers);
878
- config2.systemModifiers = new NameManager(from.systemModifiers);
879
- config2.argumentInterpolators = new NameManager(from.argumentInterpolators);
880
- config2.blockShorthands = new NameManager(from.blockShorthands);
881
- config2.inlineShorthands = new NameManager(from.inlineShorthands);
882
- return config2;
883
- }
884
- };
885
-
886
- // src/parser.ts
887
- var GROUP_BEGIN = ":--";
888
- var GROUP_END = "--:";
889
- var MODIFIER_BLOCK_OPEN = "[.";
890
- var MODIFIER_CLOSE_SIGN = "]";
891
- var MODIFIER_END_SIGN = ";";
892
- var MODIFIER_INLINE_OPEN = "[/";
893
- var MODIFIER_INLINE_END_TAG = "[;]";
894
- var MODIFIER_SYSTEM_OPEN = "[-";
895
- var UnknownModifier = {
896
- [7 /* BlockModifier */]: new BlockModifierDefinition("UNKNOWN", 0 /* Normal */),
897
- [6 /* InlineModifier */]: new InlineModifierDefinition("UNKNOWN", 0 /* Normal */),
898
- [5 /* SystemModifier */]: new SystemModifierDefinition("UNKNOWN", 0 /* Normal */)
899
- };
900
- var EmitEnvironment = class {
901
- constructor(scanner) {
902
- this.scanner = scanner;
903
- this.root = { type: 0 /* Root */, source: scanner.source, content: [] };
904
- }
905
- root;
906
- messages = [];
907
- blockStack = [];
908
- inlineStack = [];
909
- message(...m) {
910
- for (let msg of m) {
911
- this.messages.push(msg);
912
- debug.trace("issued msg", msg.code, msg.info);
913
- }
914
- }
915
- addBlockNode(n) {
916
- (this.blockStack.at(-1) ?? this.root).content.push(n);
917
- return n;
918
- }
919
- addInlineNode(n) {
920
- assert(this.inlineStack.length > 0);
921
- this.inlineStack.at(-1).content.push(n);
922
- return n;
923
- }
924
- addString(str) {
925
- assert(this.inlineStack.length > 0);
926
- const content = this.inlineStack.at(-1).content;
927
- const last = content.at(-1);
928
- if (last?.type == 3 /* Text */) {
929
- last.content += str;
930
- last.location.end = this.scanner.position();
931
- } else content.push({
932
- type: 3 /* Text */,
933
- location: {
934
- source: this.scanner.source,
935
- start: this.scanner.position() - str.length,
936
- end: this.scanner.position()
937
- },
938
- content: str
939
- });
940
- }
941
- startBlock(block) {
942
- this.addBlockNode(block);
943
- this.blockStack.push(block);
944
- }
945
- endBlock() {
946
- assert(this.blockStack.length > 0);
947
- const node = this.blockStack.pop();
948
- node.location.end = this.scanner.position();
949
- }
950
- startInline(n) {
951
- if (n.type == 1 /* Paragraph */) this.addBlockNode(n);
952
- else this.addInlineNode(n);
953
- this.inlineStack.push(n);
954
- }
955
- endInline() {
956
- assert(this.inlineStack.length > 0);
957
- const node = this.inlineStack.pop();
958
- node.location.end = this.scanner.position();
959
- }
960
- };
961
- var Parser = class {
962
- constructor(scanner, cxt) {
963
- this.scanner = scanner;
964
- this.cxt = cxt;
965
- this.emit = new EmitEnvironment(scanner);
966
- }
967
- emit;
968
- delayDepth = 0;
969
- groupDepth = 0;
970
- #loc(to) {
971
- return {
972
- source: this.scanner.source,
973
- start: this.scanner.position(),
974
- end: to ?? this.scanner.position()
975
- };
976
- }
977
- #locFrom(from, to) {
978
- return {
979
- source: this.scanner.source,
980
- start: from,
981
- end: to ?? this.scanner.position()
982
- };
983
- }
984
- /* istanbul ignore next -- @preserve */
985
- #defs(type) {
986
- switch (type) {
987
- case 5 /* SystemModifier */:
988
- return this.cxt.config.systemModifiers;
989
- case 6 /* InlineModifier */:
990
- return this.cxt.config.inlineModifiers;
991
- case 7 /* BlockModifier */:
992
- return this.cxt.config.blockModifiers;
993
- default:
994
- return debug.never(type);
995
- }
996
- }
997
- #reparse(nodes, depth) {
998
- if (depth > this.cxt.config.reparseDepthLimit) return false;
999
- let ok = true;
1000
- for (const node of nodes) {
1001
- switch (node.type) {
1002
- case 2 /* Preformatted */:
1003
- case 3 /* Text */:
1004
- case 4 /* Escaped */:
1005
- continue;
1006
- case 1 /* Paragraph */:
1007
- ok = this.#reparse(node.content, depth + 1) && ok;
1008
- continue;
1009
- case 7 /* BlockModifier */:
1010
- case 6 /* InlineModifier */:
1011
- case 5 /* SystemModifier */:
1012
- ok = this.#expand(node, depth + 1) && ok;
1013
- continue;
1014
- default:
1015
- debug.never(node);
1016
- }
1017
- }
1018
- return ok;
1019
- }
1020
- #expandArgument(arg) {
1021
- if (arg.expansion !== void 0)
1022
- return arg.expansion;
1023
- let result = "";
1024
- const immediate = this.delayDepth == 0;
1025
- for (const e of arg.content) {
1026
- switch (e.type) {
1027
- case 3 /* Text */:
1028
- case 4 /* Escaped */:
1029
- result += e.content;
1030
- break;
1031
- case 8 /* Interpolation */:
1032
- if (e.expansion === void 0) {
1033
- const inner = this.#expandArgument(e.argument);
1034
- if (inner === void 0 || e.definition.expand === void 0 || !immediate && !e.definition.alwaysTryExpand)
1035
- return void 0;
1036
- e.expansion = e.definition.expand(inner, this.cxt, immediate);
1037
- if (e.expansion === void 0)
1038
- return void 0;
1039
- }
1040
- result += e.expansion;
1041
- break;
1042
- default:
1043
- debug.never(e);
1044
- }
1045
- }
1046
- arg.expansion = result;
1047
- return result;
1048
- }
1049
- #expandArguments(node) {
1050
- for (const arg of node.arguments) {
1051
- this.#expandArgument(arg);
1052
- }
1053
- }
1054
- #expand(node, depth = 0) {
1055
- if (node.expansion !== void 0) {
1056
- debug.trace("already expanded, skipping:", node.mod.name);
1057
- return true;
1058
- }
1059
- if (depth > 0) {
1060
- this.#expandArguments(node);
1061
- }
1062
- if (this.delayDepth > 0 && !node.mod.alwaysTryExpand) {
1063
- debug.trace("delaying expansion of", node.mod.name);
1064
- return true;
1065
- }
1066
- const immediate = this.delayDepth == 0;
1067
- if (depth > 0) {
1068
- if (node.mod.beforeParseContent)
1069
- this.emit.message(...node.mod.beforeParseContent(node, this.cxt, immediate));
1070
- if (node.content.length > 0) {
1071
- if (node.mod.delayContentExpansion) this.delayDepth++;
1072
- this.#reparse(node.content, depth);
1073
- if (node.mod.delayContentExpansion) this.delayDepth--;
1074
- }
1075
- if (node.mod.afterParseContent)
1076
- this.emit.message(...node.mod.afterParseContent(node, this.cxt, immediate));
1077
- }
1078
- if (node.mod.prepareExpand)
1079
- this.emit.message(...node.mod.prepareExpand(node, this.cxt, immediate));
1080
- if (node.mod.expand) {
1081
- node.expansion = node.mod.expand(node, this.cxt, immediate);
1082
- if (!node.expansion) {
1083
- return true;
1084
- }
1085
- debug.trace(`${this.delayDepth > 0 ? "early " : ""}expanding:`, node.mod.name);
1086
- if (node.expansion.length > 0)
1087
- debug.trace(() => "-->\n" + debugPrint.node(...node.expansion));
1088
- }
1089
- const expansion = node.expansion ?? node.content;
1090
- if (expansion.length == 0) return true;
1091
- if (node.mod.beforeProcessExpansion)
1092
- this.emit.message(...node.mod.beforeProcessExpansion(node, this.cxt, immediate));
1093
- let ok = this.#reparse(expansion, depth);
1094
- if (node.mod.afterProcessExpansion)
1095
- this.emit.message(...node.mod.afterProcessExpansion(node, this.cxt, immediate));
1096
- if (!ok && depth == 0) {
1097
- const limit = this.cxt.config.reparseDepthLimit;
1098
- this.emit.message(
1099
- new ReachedRecursionLimitMessage(node.location, limit, node.mod.name)
1100
- );
1101
- }
1102
- return ok;
1103
- }
1104
- parse() {
1105
- this.DOCUMENT();
1106
- return new Document(this.emit.root, this.cxt, this.emit.messages);
1107
- }
1108
- WHITESPACES() {
1109
- while (this.scanner.acceptWhitespaceChar() !== null) {
1110
- }
1111
- }
1112
- WHITESPACES_OR_NEWLINES() {
1113
- while (this.scanner.acceptWhitespaceChar() !== null || this.scanner.accept("\n")) {
1114
- }
1115
- }
1116
- SHOULD_BE_A_NEWLINE() {
1117
- this.WHITESPACES();
1118
- if (!this.scanner.accept("\n")) this.emit.message(
1119
- new ShouldBeOnNewlineMessage(this.#loc())
1120
- );
1121
- }
1122
- // TODO: this is awkward and doesn't emit messages in the most appropriate way
1123
- WARN_IF_MORE_NEWLINES_THAN(n) {
1124
- let nlines = 0;
1125
- const start = this.scanner.position();
1126
- while (true) {
1127
- if (this.scanner.accept("\n")) {
1128
- nlines++;
1129
- continue;
1130
- }
1131
- if (this.scanner.acceptWhitespaceChar() == null) break;
1132
- }
1133
- const end = this.scanner.position();
1134
- if (nlines > n) this.emit.message(
1135
- new UnnecessaryNewlineMessage(this.#locFrom(start, end))
1136
- );
1137
- }
1138
- DOCUMENT() {
1139
- this.WHITESPACES_OR_NEWLINES();
1140
- while (!this.scanner.isEOF()) {
1141
- this.BLOCK_ENTITY();
1142
- this.WHITESPACES_OR_NEWLINES();
1143
- }
1144
- }
1145
- BLOCK_ENTITY() {
1146
- assert(!this.scanner.isEOF());
1147
- if (this.scanner.peek(MODIFIER_BLOCK_OPEN)) {
1148
- this.MODIFIER(7 /* BlockModifier */);
1149
- return;
1150
- }
1151
- if (this.scanner.peek(MODIFIER_SYSTEM_OPEN)) {
1152
- this.MODIFIER(5 /* SystemModifier */);
1153
- return;
1154
- }
1155
- const short = this.cxt.config.blockShorthands.find((x) => this.scanner.accept(x.name));
1156
- if (short) return this.SHORTHAND(7 /* BlockModifier */, short);
1157
- this.MAYBE_GROUPED_PARAGRAPH();
1158
- }
1159
- MODIFIER(type) {
1160
- const posStart = this.scanner.position();
1161
- assert(this.scanner.accept({
1162
- [7 /* BlockModifier */]: MODIFIER_BLOCK_OPEN,
1163
- [5 /* SystemModifier */]: MODIFIER_SYSTEM_OPEN,
1164
- [6 /* InlineModifier */]: MODIFIER_INLINE_OPEN
1165
- }[type]));
1166
- const result = this.#defs(type).find((x) => this.scanner.accept(x.name));
1167
- const mod = result ?? UnknownModifier[type];
1168
- if (result === void 0) {
1169
- let name = "";
1170
- while (!this.scanner.isEOF() && !this.scanner.acceptWhitespaceChar() && !this.scanner.peek(MODIFIER_CLOSE_SIGN) && !this.scanner.peek(MODIFIER_END_SIGN)) {
1171
- if (this.scanner.accept("\\")) {
1172
- if (this.scanner.isEOF()) break;
1173
- }
1174
- name += this.scanner.acceptChar();
1175
- }
1176
- this.emit.message(
1177
- new UnknownModifierMessage(this.#locFrom(posStart), name)
1178
- );
1179
- }
1180
- const args = this.ARGUMENTS();
1181
- debug.trace(`PARSE ${NodeType[type]}:`, mod.name);
1182
- const endsign = this.scanner.accept(MODIFIER_END_SIGN);
1183
- const flagMarker = mod.slotType == 2 /* None */;
1184
- if (!this.scanner.accept(MODIFIER_CLOSE_SIGN))
1185
- this.emit.message(
1186
- new ExpectedMessage(this.#loc(), MODIFIER_CLOSE_SIGN)
1187
- );
1188
- const headEnd = this.scanner.position();
1189
- const node = {
1190
- type,
1191
- mod,
1192
- head: this.#locFrom(posStart, headEnd),
1193
- location: this.#locFrom(posStart, headEnd),
1194
- arguments: args,
1195
- content: [],
1196
- expansion: void 0
1197
- };
1198
- const isMarker = flagMarker || endsign;
1199
- return this.MODIFIER_BODY(type, node, MODIFIER_INLINE_END_TAG, isMarker);
1200
- }
1201
- // also handles "grouped" (delimited) pre-paragraphs
1202
- PRE_PARAGRAPH() {
1203
- assert(!this.scanner.isEOF());
1204
- const posStart = this.scanner.position();
1205
- const grouped = this.scanner.accept(GROUP_BEGIN);
1206
- if (grouped) this.SHOULD_BE_A_NEWLINE();
1207
- const posContentStart = this.scanner.position();
1208
- let posContentEnd = this.scanner.position();
1209
- let paragraphEnd = void 0;
1210
- let string = "";
1211
- while (!this.scanner.isEOF()) {
1212
- if (this.scanner.accept("\n")) {
1213
- let white = "\n";
1214
- let char;
1215
- while ((char = this.scanner.acceptWhitespaceChar()) !== null)
1216
- white += char;
1217
- if (grouped && this.scanner.accept(GROUP_END)) {
1218
- paragraphEnd = this.scanner.position();
1219
- if (!this.scanner.isEOF()) {
1220
- this.SHOULD_BE_A_NEWLINE();
1221
- this.WARN_IF_MORE_NEWLINES_THAN(1);
1222
- }
1223
- break;
1224
- }
1225
- if (!grouped && this.scanner.accept("\n")) {
1226
- paragraphEnd = this.scanner.position() - 1;
1227
- if (!this.scanner.isEOF())
1228
- this.WARN_IF_MORE_NEWLINES_THAN(0);
1229
- break;
1230
- }
1231
- if (this.scanner.isEOF()) {
1232
- if (grouped) this.emit.message(
1233
- new ExpectedMessage(this.#loc(), GROUP_END)
1234
- );
1235
- break;
1236
- }
1237
- string += white;
1238
- } else {
1239
- string += this.scanner.acceptChar();
1240
- }
1241
- posContentEnd = this.scanner.position();
1242
- }
1243
- const node = {
1244
- type: 2 /* Preformatted */,
1245
- location: this.#locFrom(posStart, paragraphEnd ?? posContentEnd),
1246
- content: {
1247
- start: posContentStart,
1248
- end: posContentEnd,
1249
- text: string
1250
- }
1251
- };
1252
- this.emit.addBlockNode(node);
1253
- }
1254
- MAYBE_GROUPED_PARAGRAPH() {
1255
- assert(!this.scanner.isEOF());
1256
- if (this.scanner.accept(GROUP_BEGIN)) {
1257
- this.groupDepth++;
1258
- this.SHOULD_BE_A_NEWLINE();
1259
- this.WARN_IF_MORE_NEWLINES_THAN(1);
1260
- while (!this.scanner.isEOF()) {
1261
- if (this.scanner.accept(GROUP_END)) {
1262
- if (!this.scanner.isEOF()) {
1263
- this.SHOULD_BE_A_NEWLINE();
1264
- this.WARN_IF_MORE_NEWLINES_THAN(1);
1265
- }
1266
- this.groupDepth--;
1267
- return;
1268
- }
1269
- this.BLOCK_ENTITY();
1270
- this.WARN_IF_MORE_NEWLINES_THAN(1);
1271
- }
1272
- this.emit.message(
1273
- new ExpectedMessage(this.#loc(), GROUP_END)
1274
- );
1275
- } else {
1276
- this.PARAGRAPH();
1277
- }
1278
- }
1279
- #trimNode(node) {
1280
- if (node.content.length == 0) return;
1281
- let first = node.content[0];
1282
- let last = node.content.at(-1);
1283
- if (first.type == 3 /* Text */)
1284
- first.content = first.content.trimStart();
1285
- if (last.type == 3 /* Text */)
1286
- last.content = last.content.trimEnd();
1287
- }
1288
- PARAGRAPH() {
1289
- assert(!this.scanner.isEOF());
1290
- const node = {
1291
- type: 1 /* Paragraph */,
1292
- location: this.#loc(),
1293
- content: []
1294
- };
1295
- this.emit.startInline(node);
1296
- while (!this.scanner.isEOF() && this.INLINE_ENTITY()) {
1297
- }
1298
- this.emit.endInline();
1299
- const last = node.content.at(-1);
1300
- node.location.actualEnd = last?.location.actualEnd ?? last?.location.end;
1301
- this.#trimNode(node);
1302
- }
1303
- // returns false if breaking out of paragraph
1304
- SHORTHAND(type, d) {
1305
- const posStart = this.scanner.position() - d.name.length;
1306
- let args = [];
1307
- for (const part of d.parts) {
1308
- let [arg, ok] = this.ARGUMENT_CONTENT(part, ["\n\n"]);
1309
- if (!ok) {
1310
- this.emit.message(new ExpectedMessage(this.#loc(), part));
1311
- return false;
1312
- }
1313
- args.push(arg);
1314
- }
1315
- const headEnd = this.scanner.position();
1316
- const node = {
1317
- type,
1318
- mod: d.mod,
1319
- head: this.#locFrom(posStart, headEnd),
1320
- location: this.#locFrom(posStart, headEnd),
1321
- arguments: args,
1322
- content: [],
1323
- expansion: void 0
1324
- };
1325
- const isMarker = node.mod.slotType == 2 /* None */;
1326
- return this.MODIFIER_BODY(type, node, d.postfix, isMarker);
1327
- }
1328
- MODIFIER_BODY(type, node, postfix, isMarker) {
1329
- this.#expandArguments(node);
1330
- const immediate = this.delayDepth == 0;
1331
- if (node.mod.beforeParseContent)
1332
- this.emit.message(...node.mod.beforeParseContent(node, this.cxt, immediate));
1333
- if (node.mod.delayContentExpansion) this.delayDepth++;
1334
- let ok = true;
1335
- if (isMarker) {
1336
- if (!this.scanner.isEOF() && type == 7 /* BlockModifier */) {
1337
- this.SHOULD_BE_A_NEWLINE();
1338
- this.WARN_IF_MORE_NEWLINES_THAN(1);
1339
- }
1340
- if (type === 6 /* InlineModifier */) this.emit.addInlineNode(node);
1341
- else this.emit.addBlockNode(node);
1342
- } else if (type == 6 /* InlineModifier */) {
1343
- node = node;
1344
- this.emit.startInline(node);
1345
- const pre = node.mod.slotType == 1 /* Preformatted */;
1346
- const entity = pre ? this.PREFORMATTED_INLINE_ENTITY.bind(this) : this.INLINE_ENTITY.bind(this);
1347
- while (true) {
1348
- if (postfix && this.scanner.accept(postfix)) break;
1349
- if (this.scanner.isEOF() || !(ok = entity())) {
1350
- if (postfix) this.emit.message(
1351
- new ExpectedMessage(this.#loc(), postfix)
1352
- );
1353
- break;
1354
- }
1355
- }
1356
- this.emit.endInline();
1357
- if (!pre && node.content.length > 0) {
1358
- this.#trimNode(node);
1359
- }
1360
- } else {
1361
- this.emit.startBlock(node);
1362
- this.WARN_IF_MORE_NEWLINES_THAN(1);
1363
- if (!this.scanner.isEOF()) {
1364
- if (node.mod.slotType == 1 /* Preformatted */)
1365
- this.PRE_PARAGRAPH();
1366
- else
1367
- this.BLOCK_ENTITY();
1368
- }
1369
- this.emit.endBlock();
1370
- }
1371
- const last = node.content.at(-1);
1372
- node.location.actualEnd = last?.location.actualEnd ?? last?.location.end;
1373
- if (node.mod.delayContentExpansion) this.delayDepth--;
1374
- if (node.mod.afterParseContent)
1375
- this.emit.message(...node.mod.afterParseContent(node, this.cxt, immediate));
1376
- this.#expand(node);
1377
- return ok;
1378
- }
1379
- // returns false if breaking out of paragraph
1380
- INLINE_ENTITY() {
1381
- assert(!this.scanner.isEOF());
1382
- if (this.scanner.peek(MODIFIER_INLINE_OPEN))
1383
- return this.MODIFIER(6 /* InlineModifier */);
1384
- if (this.scanner.peek(MODIFIER_SYSTEM_OPEN))
1385
- return false;
1386
- if (this.scanner.peek(MODIFIER_BLOCK_OPEN)) {
1387
- this.SHOULD_BE_A_NEWLINE();
1388
- return false;
1389
- }
1390
- const short = this.cxt.config.inlineShorthands.find((x) => this.scanner.accept(x.name));
1391
- if (short) return this.SHORTHAND(6 /* InlineModifier */, short);
1392
- if (this.scanner.accept("\\")) {
1393
- if (this.scanner.isEOF()) {
1394
- this.emit.addString("\\");
1395
- return true;
1396
- }
1397
- const start = this.scanner.position();
1398
- const node = {
1399
- type: 4 /* Escaped */,
1400
- content: this.scanner.acceptChar(),
1401
- location: this.#locFrom(start - 1)
1402
- };
1403
- this.emit.addInlineNode(node);
1404
- return true;
1405
- }
1406
- return this.PREFORMATTED_INLINE_ENTITY();
1407
- }
1408
- // returns false if breaking out of paragraph
1409
- PREFORMATTED_INLINE_ENTITY() {
1410
- assert(!this.scanner.isEOF());
1411
- if (this.scanner.accept("\n")) {
1412
- this.WHITESPACES();
1413
- if (this.scanner.peek(MODIFIER_BLOCK_OPEN) || this.scanner.peek(MODIFIER_SYSTEM_OPEN) || this.cxt.config.blockShorthands.find((x) => this.scanner.peek(x.name)) || this.scanner.peek(GROUP_END) && this.groupDepth > 0 || this.scanner.isEOF()) return false;
1414
- if (this.scanner.accept("\n")) {
1415
- this.WARN_IF_MORE_NEWLINES_THAN(0);
1416
- return false;
1417
- }
1418
- this.emit.addString("\n");
1419
- return true;
1420
- }
1421
- this.emit.addString(this.scanner.acceptChar());
1422
- return true;
1423
- }
1424
- // returns argument and isOk
1425
- ARGUMENT_CONTENT(end = void 0, close = [MODIFIER_END_SIGN, MODIFIER_CLOSE_SIGN]) {
1426
- let ok = true;
1427
- const content = [];
1428
- const posStart = this.scanner.position();
1429
- let posEnd = this.scanner.position();
1430
- const emitString = (s) => {
1431
- const last = content.at(-1);
1432
- if (last?.type == 3 /* Text */) {
1433
- last.content += s;
1434
- last.location.end += s.length;
1435
- } else {
1436
- const end2 = this.scanner.position();
1437
- content.push({
1438
- type: 3 /* Text */,
1439
- location: this.#locFrom(end2 - s.length),
1440
- content: s
1441
- });
1442
- }
1443
- };
1444
- while (true) {
1445
- if (end && this.scanner.accept(end))
1446
- break;
1447
- if (end === void 0 && this.scanner.accept(":"))
1448
- break;
1449
- if (close.find((x) => this.scanner.peek(x)) || this.scanner.isEOF()) {
1450
- ok = false;
1451
- break;
1452
- }
1453
- if (this.scanner.accept("\\")) {
1454
- posEnd = this.scanner.position();
1455
- if (this.scanner.isEOF()) {
1456
- emitString("\\");
1457
- ok = false;
1458
- break;
1459
- }
1460
- content.push({
1461
- type: 4 /* Escaped */,
1462
- content: this.scanner.acceptChar(),
1463
- location: this.#locFrom(posEnd - 1)
1464
- });
1465
- continue;
1466
- }
1467
- const beforeInterp = this.scanner.position();
1468
- const result = this.cxt.config.argumentInterpolators.find(
1469
- (x) => this.scanner.accept(x.name)
1470
- );
1471
- if (result !== void 0) {
1472
- const [inner, ok2] = this.ARGUMENT_CONTENT(result.postfix);
1473
- posEnd = this.scanner.position();
1474
- content.push({
1475
- type: 8 /* Interpolation */,
1476
- definition: result,
1477
- argument: inner,
1478
- location: this.#locFrom(beforeInterp)
1479
- });
1480
- if (!ok2) {
1481
- this.emit.message(new ExpectedMessage(this.#loc(), result.postfix));
1482
- ok = false;
1483
- break;
1484
- }
1485
- } else {
1486
- emitString(this.scanner.acceptChar());
1487
- posEnd = this.scanner.position();
1488
- }
1489
- }
1490
- return [{
1491
- location: this.#locFrom(posStart, posEnd),
1492
- content
1493
- }, ok];
1494
- }
1495
- ARGUMENTS() {
1496
- const firstSemicolon = this.scanner.accept(":");
1497
- if (!firstSemicolon) this.WHITESPACES_OR_NEWLINES();
1498
- const list = [];
1499
- let end = false;
1500
- while (!end) {
1501
- const [arg, ok] = this.ARGUMENT_CONTENT();
1502
- if (!ok) {
1503
- end = true;
1504
- if (list.length == 0 && arg.content.length == 0 && !firstSemicolon)
1505
- break;
1506
- }
1507
- list.push(arg);
1508
- }
1509
- return list;
1510
- }
1511
- };
1512
- function parse(scanner, cxt) {
1513
- return new Parser(scanner, cxt).parse();
1514
- }
1515
-
1516
- // src/renderer.ts
1517
- var RenderContext = class {
1518
- constructor(config2, parsedDocument, state) {
1519
- this.config = config2;
1520
- this.parsedDocument = parsedDocument;
1521
- this.state = state;
1522
- }
1523
- renderEntity(node) {
1524
- switch (node.type) {
1525
- case 1 /* Paragraph */:
1526
- return this.config.paragraphRenderer?.(node, this);
1527
- case 2 /* Preformatted */:
1528
- case 3 /* Text */:
1529
- case 4 /* Escaped */:
1530
- return this.config.textRenderer?.(node, this);
1531
- case 6 /* InlineModifier */:
1532
- let ir = this.config.inlineRenderers.get(node.mod);
1533
- if (ir) return ir(node, this);
1534
- return this.config.undefinedInlineRenderer?.(node, this);
1535
- case 7 /* BlockModifier */:
1536
- let br = this.config.blockRenderers.get(node.mod);
1537
- if (br) return br(node, this);
1538
- return this.config.undefinedBlockRenderer?.(node, this);
1539
- case 5 /* SystemModifier */:
1540
- return void 0;
1541
- default:
1542
- return debug.never(node);
1543
- }
1544
- }
1545
- };
1546
- var RenderConfiguration = class _RenderConfiguration {
1547
- constructor(options, postprocessor) {
1548
- this.options = options;
1549
- this.postprocessor = postprocessor;
1550
- }
1551
- paragraphRenderer;
1552
- textRenderer;
1553
- undefinedBlockRenderer;
1554
- undefinedInlineRenderer;
1555
- blockRenderers = /* @__PURE__ */ new Map();
1556
- inlineRenderers = /* @__PURE__ */ new Map();
1557
- render(doc, state) {
1558
- let cxt = new RenderContext(this, doc, state);
1559
- let results = doc.toStripped().root.content.map((x) => cxt.renderEntity(x)).filter((x) => x !== void 0);
1560
- return this.postprocessor(results, cxt);
1561
- }
1562
- addBlockRenderer(...rs) {
1563
- rs.forEach(([x, y]) => this.blockRenderers.set(x, y));
1564
- }
1565
- addInlineRenderer(...rs) {
1566
- rs.forEach(([x, y]) => this.inlineRenderers.set(x, y));
1567
- }
1568
- static from(from) {
1569
- let config2 = new _RenderConfiguration(from.options, from.postprocessor);
1570
- config2.paragraphRenderer = from.paragraphRenderer;
1571
- config2.textRenderer = from.textRenderer;
1572
- config2.undefinedBlockRenderer = from.undefinedBlockRenderer;
1573
- config2.undefinedInlineRenderer = from.undefinedInlineRenderer;
1574
- config2.inlineRenderers = new Map(from.inlineRenderers);
1575
- config2.blockRenderers = new Map(from.blockRenderers);
1576
- return config2;
1577
- }
1578
- };
1579
-
1580
- // src/modifier-helper.ts
1581
- var modifier_helper_exports = {};
1582
- __export(modifier_helper_exports, {
1583
- checkArgumentLength: () => checkArgumentLength,
1584
- checkArguments: () => checkArguments,
1585
- onlyPermitPlaintextParagraph: () => onlyPermitPlaintextParagraph,
1586
- onlyPermitSimpleParagraphs: () => onlyPermitSimpleParagraphs,
1587
- onlyPermitSingleBlock: () => onlyPermitSingleBlock
1588
- });
1589
- function checkArgumentLength(node, min, max = min) {
1590
- if (min !== void 0 && node.arguments.length < min || max !== void 0 && node.arguments.length > max) {
1591
- return [new ArgumentCountMismatchMessage({
1592
- source: node.location.source,
1593
- start: node.head.start,
1594
- end: node.head.end
1595
- }, min, max)];
1596
- }
1597
- return null;
1598
- }
1599
- function checkArguments(node, min, max = min) {
1600
- const arg = node.arguments.find((x) => x.expansion === void 0);
1601
- if (arg !== void 0) {
1602
- return [new CannotExpandArgumentMessage(arg.location)];
1603
- }
1604
- return checkArgumentLength(node, min, max);
1605
- }
1606
- function onlyPermitPlaintextParagraph(node) {
1607
- function checkInline(ents) {
1608
- let result = "";
1609
- for (const ent of ents) {
1610
- switch (ent.type) {
1611
- case 3 /* Text */:
1612
- case 4 /* Escaped */:
1613
- result += ent.content;
1614
- break;
1615
- case 5 /* SystemModifier */:
1616
- break;
1617
- case 6 /* InlineModifier */:
1618
- if (!ent.expansion) return [new EntityNotAllowedMessage(
1619
- ent.location,
1620
- "it does not expand to plain text"
1621
- )];
1622
- let checkInner = checkInline(ent.expansion);
1623
- if (Array.isArray(checkInner)) return checkInner;
1624
- result += checkInner;
1625
- break;
1626
- default:
1627
- return debug.never(ent);
1628
- }
1629
- }
1630
- return result;
1631
- }
1632
- function checkContent(ents) {
1633
- if (ents.length == 0) return "";
1634
- else if (ents.length > 1) {
1635
- let last = ents.at(-1).location;
1636
- return [new MultipleBlocksNotPermittedMessage({
1637
- source: last.source,
1638
- start: ents[1].location.start,
1639
- end: last.actualEnd ?? last.end
1640
- })];
1641
- }
1642
- return check(ents[0]);
1643
- }
1644
- function check(ent) {
1645
- if (ent.type == 7 /* BlockModifier */) {
1646
- if (!ent.expansion) return [new EntityNotAllowedMessage(
1647
- ent.location,
1648
- "it does not expand to plain text"
1649
- )];
1650
- return checkContent(ent.expansion);
1651
- } else if (ent.type == 2 /* Preformatted */) {
1652
- return ent.content.text;
1653
- } else if (ent.type !== 1 /* Paragraph */) {
1654
- return [new OnlySimpleParagraphsPermittedMessage(ent.location)];
1655
- }
1656
- return checkInline(ent.content);
1657
- }
1658
- return checkContent(node.content);
1659
- }
1660
- function onlyPermitSimpleParagraphs(node) {
1661
- function check(nodes) {
1662
- for (let ent of nodes) {
1663
- if (ent.type == 7 /* BlockModifier */ && ent.expansion !== void 0) {
1664
- const cs = check(ent.expansion);
1665
- if (cs) return cs;
1666
- } else if (ent.type !== 1 /* Paragraph */) {
1667
- return [new OnlySimpleParagraphsPermittedMessage(ent.location)];
1668
- }
1669
- }
1670
- return null;
1671
- }
1672
- return check(node.content);
1673
- }
1674
- function onlyPermitSingleBlock(node) {
1675
- function check(nodes) {
1676
- if (nodes.length > 1) {
1677
- let last = nodes.at(-1).location;
1678
- return [new MultipleBlocksNotPermittedMessage({
1679
- source: last.source,
1680
- start: nodes[1].location.start,
1681
- end: last.actualEnd ?? last.end
1682
- })];
1683
- } else if (nodes.length == 1 && nodes[0].type === 7 /* BlockModifier */ && nodes[0].expansion !== void 0) {
1684
- return check(nodes[0].expansion);
1685
- }
1686
- return null;
1687
- }
1688
- return check(node.content);
1689
- }
1690
-
1691
- // src/builtin/internal.ts
1692
- var builtins = Symbol();
1693
- function initParseContext(cxt) {
1694
- cxt.init(builtins, {
1695
- blockSlotDelayedStack: [],
1696
- inlineSlotDelayedStack: [],
1697
- blockInstantiationData: [],
1698
- inlineInstantiationData: [],
1699
- modules: /* @__PURE__ */ new Map(),
1700
- usedModules: /* @__PURE__ */ new Set(),
1701
- insideModule: void 0
1702
- });
1703
- }
1704
- function customModifier(type, name, signature, content) {
1705
- debug.info(`created custom ${NodeType[type]}:`, name);
1706
- debug.info("args:", signature.args, `with ${signature.slotName === void 0 ? "no slot" : signature.slotName == "" ? "empty slot name" : "slot name: " + signature.slotName}`);
1707
- debug.trace(() => "content is\n" + debugPrint.node(...content));
1708
- const flag = signature.slotName === void 0 ? 2 /* None */ : signature.preformatted ? 1 /* Preformatted */ : 0 /* Normal */;
1709
- const mod = type == 7 /* BlockModifier */ ? new BlockModifierDefinition(name, flag) : new InlineModifierDefinition(name, flag);
1710
- const isInline = type == 6 /* InlineModifier */;
1711
- if (content.length == 1 && (content[0].type == 7 /* BlockModifier */ || content[0].type == 6 /* InlineModifier */))
1712
- mod.roleHint = content[0].mod.roleHint;
1713
- mod.delayContentExpansion = true;
1714
- mod.prepareExpand = (node, cxt) => {
1715
- let check = checkArguments(node, signature.args.length);
1716
- if (check) return check;
1717
- node.state = {
1718
- ok: true,
1719
- args: new Map(node.arguments.map((x, i) => [signature.args[i], x.expansion]))
1720
- };
1721
- return [];
1722
- };
1723
- mod.expand = (node) => {
1724
- if (!node.state?.ok) return [];
1725
- const contentClone = cloneNodes(content, { newLocation: node.location });
1726
- return contentClone;
1727
- };
1728
- mod.beforeProcessExpansion = (node, cxt) => {
1729
- if (!node.state?.ok) return [];
1730
- const store = cxt.get(builtins);
1731
- const data = isInline ? store.inlineInstantiationData : store.blockInstantiationData;
1732
- data.push({
1733
- slotName: signature.slotName,
1734
- mod,
1735
- args: node.state.args,
1736
- slotContent: node.content
1737
- });
1738
- debug.trace(`pushed ${NodeType[type]} slot data for`, name);
1739
- debug.trace(
1740
- `... slotName:`,
1741
- signature.slotName === "" ? "<unnamed>" : signature.slotName === void 0 ? "<no slot>" : `'${signature.slotName}'`
1742
- );
1743
- debug.trace(`... args:`, "{" + [...node.state.args].map(([a, b]) => `${a} => ${b}`).join(", ") + "}");
1744
- return [];
1745
- };
1746
- mod.afterProcessExpansion = (node, cxt) => {
1747
- if (!node.state?.ok) return [];
1748
- const store = cxt.get(builtins);
1749
- const data = isInline ? store.inlineInstantiationData : store.blockInstantiationData;
1750
- data.pop();
1751
- debug.trace(`popped ${NodeType[type]} slot data for`, name);
1752
- return [];
1753
- };
1754
- return mod;
1755
- }
1756
- function makeInlineDefinition(node, msgs) {
1757
- let lastIsParagraph = false;
1758
- let concat = [];
1759
- for (const n of node.content) {
1760
- switch (n.type) {
1761
- case 1 /* Paragraph */:
1762
- if (!lastIsParagraph) {
1763
- lastIsParagraph = true;
1764
- concat.push(...n.content);
1765
- continue;
1766
- }
1767
- case 2 /* Preformatted */:
1768
- case 7 /* BlockModifier */:
1769
- msgs.push(new EntityNotAllowedMessage(n.location));
1770
- break;
1771
- case 5 /* SystemModifier */:
1772
- lastIsParagraph = false;
1773
- concat.push(n);
1774
- break;
1775
- default:
1776
- debug.never(n);
1777
- }
1778
- }
1779
- return concat;
1780
- }
1781
-
1782
- // src/builtin/define-modifier.ts
1783
- function parseDefineArguments(node, stack) {
1784
- const check = checkArgumentLength(node, 1, Infinity);
1785
- if (check) return check;
1786
- const msgs = [];
1787
- const name = node.arguments[0];
1788
- const nameValue = name.expansion;
1789
- if (nameValue === "" || nameValue?.includes("\n")) return [
1790
- new InvalidArgumentMessage(name.location, nameValue)
1791
- ];
1792
- let slotName = "";
1793
- if (node.arguments.length > 1) {
1794
- const last = node.arguments.at(-1);
1795
- if (last.expansion) {
1796
- const match = /^\((.*)\)$/.exec(last.expansion);
1797
- slotName = match ? match[1] : "";
1798
- } else msgs.push(
1799
- new InvalidArgumentMessage(last.location)
1800
- );
1801
- }
1802
- const args = node.arguments.slice(1, slotName !== "" ? node.arguments.length - 1 : void 0).map((x) => {
1803
- if (!x.expansion) msgs.push(
1804
- new InvalidArgumentMessage(x.location)
1805
- );
1806
- return x.expansion ?? "";
1807
- });
1808
- let signature = { slotName, args, preformatted: void 0 };
1809
- node.state = { name: nameValue, signature, msgs };
1810
- stack.push(signature);
1811
- return void 0;
1812
- }
1813
- var DefineBlockMod = new SystemModifierDefinition(
1814
- "define-block",
1815
- 0 /* Normal */,
1816
- {
1817
- // .define-block:name:args...[:(slot-id)]
1818
- delayContentExpansion: true,
1819
- alwaysTryExpand: true,
1820
- beforeParseContent(node, cxt) {
1821
- const store = cxt.get(builtins);
1822
- const check = parseDefineArguments(node, store.blockSlotDelayedStack);
1823
- if (check) return check;
1824
- debug.trace("entering block definition:", node.state.name);
1825
- return [];
1826
- },
1827
- afterParseContent(node, cxt) {
1828
- if (!node.state) return [];
1829
- const store = cxt.get(builtins);
1830
- const pop = store.blockSlotDelayedStack.pop();
1831
- assert(pop === node.state.signature);
1832
- debug.trace("leaving block definition", node.state.name);
1833
- return [];
1834
- },
1835
- prepareExpand(node, cxt, immediate) {
1836
- if (!immediate || !node.state) return [];
1837
- const arg = node.arguments[0];
1838
- const msgs = node.state.msgs;
1839
- if (!node.state.name)
1840
- msgs.push(new InvalidArgumentMessage(arg.location));
1841
- else if (cxt.config.blockModifiers.has(node.state.name))
1842
- msgs.push(new NameAlreadyDefinedMessage(arg.location, node.state.name));
1843
- return msgs;
1844
- },
1845
- expand(node, cxt, immediate) {
1846
- if (!immediate) return void 0;
1847
- if (node.state?.name) {
1848
- if (cxt.config.blockModifiers.has(node.state.name))
1849
- cxt.config.blockModifiers.remove(node.state.name);
1850
- cxt.config.blockModifiers.add(customModifier(
1851
- 7 /* BlockModifier */,
1852
- node.state.name,
1853
- node.state.signature,
1854
- node.content
1855
- ));
1856
- }
1857
- return [];
1858
- }
1859
- }
1860
- );
1861
- var DefineInlineMod = new SystemModifierDefinition(
1862
- "define-inline",
1863
- 0 /* Normal */,
1864
- {
1865
- // .define-inline name:args...[:(slot-id)]
1866
- delayContentExpansion: true,
1867
- alwaysTryExpand: true,
1868
- beforeParseContent(node, cxt) {
1869
- const store = cxt.get(builtins);
1870
- const check = parseDefineArguments(node, store.inlineSlotDelayedStack);
1871
- if (check) return check;
1872
- debug.trace("entering inline definition:", node.state.name);
1873
- return [];
1874
- },
1875
- afterParseContent(node, cxt) {
1876
- if (!node.state) return [];
1877
- const store = cxt.get(builtins);
1878
- const pop = store.inlineSlotDelayedStack.pop();
1879
- assert(pop === node.state.signature);
1880
- debug.trace("leaving inline definition", node.state.name);
1881
- return [];
1882
- },
1883
- prepareExpand(node, cxt, immediate) {
1884
- if (!immediate || !node.state) return [];
1885
- const arg = node.arguments[0];
1886
- if (!node.state.name)
1887
- return [new InvalidArgumentMessage(arg.location)];
1888
- const msgs = node.state.msgs;
1889
- if (cxt.config.inlineModifiers.has(node.state.name))
1890
- msgs.push(new NameAlreadyDefinedMessage(arg.location, node.state.name));
1891
- node.state.definition = makeInlineDefinition(node, msgs);
1892
- return msgs;
1893
- },
1894
- expand(node, cxt, immediate) {
1895
- if (!immediate) return void 0;
1896
- if (node.state?.name) {
1897
- if (cxt.config.inlineModifiers.has(node.state.name))
1898
- cxt.config.inlineModifiers.remove(node.state.name);
1899
- cxt.config.inlineModifiers.add(
1900
- customModifier(
1901
- 6 /* InlineModifier */,
1902
- node.state.name,
1903
- node.state.signature,
1904
- node.state.definition
1905
- )
1906
- );
1907
- }
1908
- return [];
1909
- }
1910
- }
1911
- );
1912
-
1913
- // src/builtin/define-shorthand.ts
1914
- function parseDefineArguments2(type, node, stack) {
1915
- const check = checkArguments(node, 1, Infinity);
1916
- if (check) return check;
1917
- const msgs = [];
1918
- const name = node.arguments[0];
1919
- const nameValue = name.expansion;
1920
- if (nameValue === "" || nameValue?.includes("\n")) return [
1921
- new InvalidArgumentMessage(name.location, nameValue)
1922
- ];
1923
- let slotName = void 0;
1924
- let parts = [];
1925
- let postfix = void 0;
1926
- let i = 1;
1927
- while (i < node.arguments.length) {
1928
- const arg = node.arguments[i];
1929
- const match = /^\((.*)\)$/.exec(arg.expansion);
1930
- if (match) {
1931
- slotName = match[1];
1932
- i++;
1933
- if (type == 6 /* InlineModifier */) {
1934
- if (i < node.arguments.length) {
1935
- if (node.arguments[i].expansion === "") {
1936
- msgs.push(new InvalidArgumentMessage(
1937
- node.arguments[i].location,
1938
- "postfix"
1939
- ));
1940
- } else {
1941
- postfix = node.arguments[i].expansion;
1942
- i++;
1943
- }
1944
- } else msgs.push(
1945
- new ArgumentCountMismatchMessage(node.location)
1946
- );
1947
- }
1948
- break;
1949
- }
1950
- i++;
1951
- if (i < node.arguments.length) {
1952
- const id = arg.expansion;
1953
- if (id === "") {
1954
- return [new InvalidArgumentMessage(arg.location, "id")];
1955
- }
1956
- const part = node.arguments[i].expansion;
1957
- if (part === "") {
1958
- return [new InvalidArgumentMessage(
1959
- node.arguments[i].location,
1960
- "part"
1961
- )];
1962
- }
1963
- parts.push([id, part]);
1964
- i++;
1965
- } else {
1966
- msgs.push(new ArgumentCountMismatchMessage(node.location));
1967
- break;
1968
- }
1969
- }
1970
- if (i == node.arguments.length - 1) {
1971
- const last = node.arguments[i];
1972
- if (last.expansion !== "") msgs.push(
1973
- new InvalidArgumentMessage(last.location, "(must be empty)")
1974
- );
1975
- } else if (i < node.arguments.length - 1)
1976
- msgs.push(new ArgumentCountMismatchMessage(node.location));
1977
- let signature = { slotName, args: parts.map((x) => x[0]), preformatted: void 0 };
1978
- node.state = { name: nameValue, signature, parts, postfix, msgs };
1979
- stack.push(signature);
1980
- return [];
1981
- }
1982
- var DefineBlockShorthandMod = new SystemModifierDefinition(
1983
- "block-shorthand",
1984
- 0 /* Normal */,
1985
- {
1986
- // -inline-shorthand prefix:arg1:part1:arg2:part2...:(slot):postfix:
1987
- delayContentExpansion: true,
1988
- alwaysTryExpand: true,
1989
- beforeParseContent(node, cxt) {
1990
- const store = cxt.get(builtins);
1991
- const check = parseDefineArguments2(
1992
- 7 /* BlockModifier */,
1993
- node,
1994
- store.blockSlotDelayedStack
1995
- );
1996
- if (check) return check;
1997
- debug.trace("entering block shorthand definition", node.state.name);
1998
- return [];
1999
- },
2000
- afterParseContent(node, cxt) {
2001
- if (!node.state) return [];
2002
- const store = cxt.get(builtins);
2003
- const pop = store.blockSlotDelayedStack.pop();
2004
- assert(pop === node.state.signature);
2005
- debug.trace("leaving inline shorthand definition", node.state.name);
2006
- return [];
2007
- },
2008
- prepareExpand(node, cxt, immediate) {
2009
- if (!immediate || !node.state) return [];
2010
- const arg = node.arguments[0];
2011
- if (!node.state)
2012
- return [new InvalidArgumentMessage(arg.location)];
2013
- const msgs = node.state.msgs;
2014
- if (cxt.config.blockShorthands.has(node.state.name))
2015
- msgs.push(new NameAlreadyDefinedMessage(arg.location, node.state.name));
2016
- return msgs;
2017
- },
2018
- expand(node, cxt, immediate) {
2019
- if (!immediate || !node.state) return void 0;
2020
- const name = "<block shorthand>";
2021
- const parts = node.state.parts.map((x) => x[1]);
2022
- const mod = customModifier(
2023
- 7 /* BlockModifier */,
2024
- name,
2025
- node.state.signature,
2026
- node.content
2027
- );
2028
- const shorthand = {
2029
- name: node.state.name,
2030
- postfix: node.state.postfix,
2031
- mod,
2032
- parts
2033
- };
2034
- if (cxt.config.blockShorthands.has(node.state.name))
2035
- cxt.config.blockShorthands.remove(node.state.name);
2036
- cxt.config.blockShorthands.add(shorthand);
2037
- debug.info(() => "created block shorthand: " + debugPrint.blockShorthand(shorthand));
2038
- return [];
2039
- }
2040
- }
2041
- );
2042
- var DefineInlineShorthandMod = new SystemModifierDefinition(
2043
- "inline-shorthand",
2044
- 0 /* Normal */,
2045
- {
2046
- // -inline-shorthand prefix:arg1:part1:arg2:part2...:(slot):postfix:
2047
- delayContentExpansion: true,
2048
- alwaysTryExpand: true,
2049
- beforeParseContent(node, cxt) {
2050
- const store = cxt.get(builtins);
2051
- const check = parseDefineArguments2(
2052
- 6 /* InlineModifier */,
2053
- node,
2054
- store.inlineSlotDelayedStack
2055
- );
2056
- if (check) return check;
2057
- debug.trace("entering inline shorthand definition", node.state.name);
2058
- return [];
2059
- },
2060
- afterParseContent(node, cxt) {
2061
- if (!node.state) return [];
2062
- const store = cxt.get(builtins);
2063
- const pop = store.inlineSlotDelayedStack.pop();
2064
- assert(pop === node.state.signature);
2065
- debug.trace("leaving inline shorthand definition", node.state.name);
2066
- return [];
2067
- },
2068
- prepareExpand(node, cxt, immediate) {
2069
- if (!immediate || !node.state) return [];
2070
- const arg = node.arguments[0];
2071
- if (!node.state)
2072
- return [new InvalidArgumentMessage(arg.location)];
2073
- const msgs = node.state.msgs;
2074
- if (cxt.config.inlineShorthands.has(node.state.name))
2075
- msgs.push(new NameAlreadyDefinedMessage(arg.location, node.state.name));
2076
- node.state.definition = makeInlineDefinition(node, msgs);
2077
- return msgs;
2078
- },
2079
- expand(node, cxt, immediate) {
2080
- if (!immediate || !node.state) return void 0;
2081
- const name = "<inline shorthand>";
2082
- const parts = node.state.parts.map((x) => x[1]);
2083
- const mod = customModifier(
2084
- 6 /* InlineModifier */,
2085
- name,
2086
- node.state.signature,
2087
- node.state.definition
2088
- );
2089
- const shorthand = {
2090
- name: node.state.name,
2091
- postfix: node.state.postfix,
2092
- mod,
2093
- parts
2094
- };
2095
- if (cxt.config.inlineShorthands.has(node.state.name))
2096
- cxt.config.inlineShorthands.remove(node.state.name);
2097
- cxt.config.inlineShorthands.add(shorthand);
2098
- debug.info(() => "created inline shorthand: " + debugPrint.inlineShorthand(shorthand));
2099
- return [];
2100
- }
2101
- }
2102
- );
2103
-
2104
- // src/builtin/misc.ts
2105
- var RawBlockMod = new BlockModifierDefinition(
2106
- "raw",
2107
- 1 /* Preformatted */,
2108
- {
2109
- expand(node) {
2110
- return node.content;
2111
- }
2112
- }
2113
- );
2114
-
2115
- // src/builtin/module.ts
2116
- function getDefs(cxt) {
2117
- const data = cxt.get(builtins);
2118
- return {
2119
- usedModules: new Set(data.usedModules),
2120
- blocks: cxt.config.blockModifiers.toSet(),
2121
- inlines: cxt.config.inlineModifiers.toSet(),
2122
- inlineShorthands: cxt.config.inlineShorthands.toSet(),
2123
- blockShorthands: cxt.config.blockShorthands.toSet()
2124
- };
2125
- }
2126
- function applyDefs(cxt, defs) {
2127
- const data = cxt.get(builtins);
2128
- data.usedModules = new Set(defs.usedModules);
2129
- cxt.config.blockModifiers = new NameManager(defs.blocks);
2130
- cxt.config.inlineModifiers = new NameManager(defs.inlines);
2131
- cxt.config.inlineShorthands = new NameManager(defs.inlineShorthands);
2132
- cxt.config.blockShorthands = new NameManager(defs.blockShorthands);
2133
- }
2134
- function add(snew, sold, transform) {
2135
- let newNames = new Set([...snew].map((x) => x.name));
2136
- let out = new Set(snew);
2137
- let overlap = [];
2138
- for (const x of sold) {
2139
- if (newNames.has(x.name))
2140
- overlap.push(x);
2141
- else
2142
- out.add(x);
2143
- }
2144
- return [out, overlap.map(transform).join(", ")];
2145
- }
2146
- function diffDef(cnew, cold) {
2147
- return {
2148
- usedModules: cnew.usedModules.difference(cold.usedModules),
2149
- blocks: cnew.blocks.difference(cold.blocks),
2150
- inlines: cnew.inlines.difference(cold.inlines),
2151
- inlineShorthands: cnew.inlineShorthands.difference(cold.inlineShorthands),
2152
- blockShorthands: cnew.blockShorthands.difference(cold.blockShorthands)
2153
- };
2154
- }
2155
- function addDef(cnew, cold) {
2156
- let [blocks, s1] = add(cnew.blocks, cold.blocks, debugPrint.blockModifier);
2157
- let [inlines, s2] = add(cnew.inlines, cold.inlines, debugPrint.inlineModifier);
2158
- let [inlineShorthands, s3] = add(cnew.inlineShorthands, cold.inlineShorthands, debugPrint.inlineShorthand);
2159
- let [blockShorthands, s4] = add(cnew.blockShorthands, cold.blockShorthands, debugPrint.blockShorthand);
2160
- return [
2161
- {
2162
- usedModules: cnew.usedModules.union(cold.usedModules),
2163
- blocks,
2164
- inlines,
2165
- inlineShorthands,
2166
- blockShorthands
2167
- },
2168
- (s1 ? s1 + "; " : "") + (s2 ? s2 + "; " : "") + (s3 ? "inline shorthand " + s3 + "; " : "") + (s4 ? "block shorthand " + s4 : "")
2169
- ];
2170
- }
2171
- var ModuleMod = new BlockModifierDefinition(
2172
- "module",
2173
- 0 /* Normal */,
2174
- {
2175
- expand(node) {
2176
- return [];
2177
- },
2178
- beforeParseContent(node, cxt) {
2179
- const check = checkArguments(node, 1);
2180
- if (check) return check;
2181
- const data = cxt.get(builtins);
2182
- const name = node.arguments[0].expansion;
2183
- const defs = getDefs(cxt);
2184
- if (data.insideModule !== void 0) {
2185
- return [new NoNestedModuleMessage(node.head)];
2186
- }
2187
- let msgs = [];
2188
- node.state = { name, defs };
2189
- data.insideModule = name;
2190
- if (data.modules.has(name)) {
2191
- const [added, msg] = addDef(defs, data.modules.get(name));
2192
- if (msg) msgs.push(
2193
- new OverwriteDefinitionsMessage(node.head, msg)
2194
- );
2195
- applyDefs(cxt, added);
2196
- debug.trace("entering defs for module", name, "(earlier data loaded)");
2197
- } else {
2198
- debug.trace("entering defs for module", name);
2199
- }
2200
- return msgs;
2201
- },
2202
- afterParseContent(node, cxt) {
2203
- if (!node.state) return [];
2204
- const data = cxt.get(builtins);
2205
- data.insideModule = void 0;
2206
- data.modules.set(
2207
- node.state.name,
2208
- diffDef(getDefs(cxt), node.state.defs)
2209
- );
2210
- applyDefs(cxt, node.state.defs);
2211
- debug.trace("exiting defs for module", node.state.name);
2212
- return [];
2213
- }
2214
- }
2215
- );
2216
- var UseSystemMod = new SystemModifierDefinition(
2217
- "use",
2218
- 2 /* None */,
2219
- {
2220
- prepareExpand(node, cxt) {
2221
- const check = checkArguments(node, 1);
2222
- if (check) return check;
2223
- const data = cxt.get(builtins);
2224
- const name = node.arguments[0];
2225
- if (!data.modules.has(name.expansion))
2226
- return [new InvalidArgumentMessage(name.location)];
2227
- if (data.insideModule === name.expansion)
2228
- return [new CannotUseModuleInSelfMessage(name.location)];
2229
- const [added, msg] = addDef(data.modules.get(name.expansion), getDefs(cxt));
2230
- node.state = added;
2231
- if (msg)
2232
- return [new OverwriteDefinitionsMessage(node.head, msg)];
2233
- return [];
2234
- },
2235
- expand(node, cxt) {
2236
- if (node.state)
2237
- applyDefs(cxt, node.state);
2238
- return [];
2239
- }
2240
- }
2241
- );
2242
- var UseBlockMod = new BlockModifierDefinition(
2243
- "use",
2244
- 0 /* Normal */,
2245
- {
2246
- beforeParseContent(node, cxt) {
2247
- const check = checkArguments(node, 1);
2248
- if (check) return check;
2249
- const data = cxt.get(builtins);
2250
- const name = node.arguments[0];
2251
- if (!data.modules.has(name.expansion))
2252
- return [new InvalidArgumentMessage(name.location)];
2253
- if (data.insideModule === name.expansion)
2254
- return [new CannotUseModuleInSelfMessage(name.location)];
2255
- const old = getDefs(cxt);
2256
- const [added, msg] = addDef(data.modules.get(name.expansion), old);
2257
- applyDefs(cxt, added);
2258
- node.state = { old };
2259
- if (msg)
2260
- return [new OverwriteDefinitionsMessage(node.head, msg)];
2261
- return [];
2262
- },
2263
- afterParseContent(node, cxt) {
2264
- if (node.state)
2265
- applyDefs(cxt, node.state.old);
2266
- return [];
2267
- },
2268
- expand(node) {
2269
- return node.content;
2270
- }
2271
- }
2272
- );
2273
-
2274
- // src/builtin/slot.ts
2275
- function slotModifier(name, type, preformatted, inject) {
2276
- const mod = type == 7 /* BlockModifier */ ? new BlockModifierDefinition(name, 2 /* None */) : new InlineModifierDefinition(name, 2 /* None */);
2277
- const isInline = type == 6 /* InlineModifier */;
2278
- mod.alwaysTryExpand = true;
2279
- mod.prepareExpand = (node, cxt, immediate) => {
2280
- if (node.state) return [];
2281
- function processSignature(s) {
2282
- if (s.preformatted === void 0) {
2283
- s.preformatted = preformatted;
2284
- debug.trace("set preformatted to ", preformatted);
2285
- } else if (s.preformatted !== preformatted) {
2286
- return [new EitherNormalOrPreMessage(node.location)];
2287
- }
2288
- return [];
2289
- }
2290
- const check = inject ? checkArguments(node, 1, 2) : checkArguments(node, 0, 1);
2291
- if (check) {
2292
- node.state = { ok: false };
2293
- return check;
2294
- }
2295
- const msgs = (() => {
2296
- const store = cxt.get(builtins);
2297
- const data = isInline ? store.inlineInstantiationData : store.blockInstantiationData;
2298
- const stack = isInline ? store.inlineSlotDelayedStack : store.blockSlotDelayedStack;
2299
- if (data.length == 0 && stack.length == 0) {
2300
- node.state = { ok: false };
2301
- return [new SlotUsedOutsideDefinitionMessage(node.location)];
2302
- }
2303
- if (node.arguments.length == (inject ? 1 : 0)) {
2304
- let signature2 = stack.at(-1);
2305
- if (signature2) return processSignature(signature2);
2306
- node.state = { ok: true, data: data.at(-1), index: data.length - 1 };
2307
- return;
2308
- }
2309
- const id = node.arguments[0].expansion;
2310
- let signature = stack.find((x) => x.slotName == id);
2311
- if (signature) return processSignature(signature);
2312
- for (let i = data.length - 1; i >= 0; i--) if (data[i].slotName === id) {
2313
- node.state = { ok: true, data: data[i], index: i };
2314
- return;
2315
- }
2316
- if (immediate) {
2317
- node.state = { ok: false };
2318
- const arg = node.arguments[0];
2319
- return [new InvalidArgumentMessage(arg.location, id)];
2320
- }
2321
- })();
2322
- if (inject) {
2323
- const arg = node.arguments.at(-1);
2324
- const modName = arg.expansion;
2325
- const mod2 = (isInline ? cxt.config.inlineModifiers : cxt.config.blockModifiers).get(modName);
2326
- if (!mod2) {
2327
- node.state = { ok: false };
2328
- return [new UnknownModifierMessage(arg.location, modName)];
2329
- }
2330
- if (node.state?.ok)
2331
- node.state.injectMod = mod2;
2332
- }
2333
- if (msgs) return msgs;
2334
- return [];
2335
- };
2336
- mod.expand = (node, cxt) => {
2337
- if (!node.state) return void 0;
2338
- if (!node.state.ok) return [];
2339
- let cloned = cloneNodes(node.state.data.slotContent);
2340
- if (inject) {
2341
- const mod2 = node.state.injectMod;
2342
- const modNode = {
2343
- type,
2344
- mod: mod2,
2345
- location: node.location,
2346
- head: node.head,
2347
- arguments: [],
2348
- // TODO: enable injecting args
2349
- content: cloned
2350
- };
2351
- return [modNode];
2352
- } else return cloned;
2353
- };
2354
- mod.beforeProcessExpansion = (node, cxt) => {
2355
- if (!node.state?.ok) return [];
2356
- const store = cxt.get(builtins);
2357
- debug.trace("temporarily removed slot data for", node.state.data.mod.name);
2358
- const data = isInline ? store.inlineInstantiationData : store.blockInstantiationData;
2359
- data.splice(node.state.index, 1);
2360
- return [];
2361
- };
2362
- mod.afterProcessExpansion = (node, cxt) => {
2363
- if (!node.state?.ok) return [];
2364
- const store = cxt.get(builtins);
2365
- debug.trace("reinstated slot data for", node.state.data.mod.name);
2366
- const data = isInline ? store.inlineInstantiationData : store.blockInstantiationData;
2367
- data.splice(node.state.index, 0, node.state.data);
2368
- return [];
2369
- };
2370
- return mod;
2371
- }
2372
- var SlotBlockMod = slotModifier("slot", 7 /* BlockModifier */, false, false);
2373
- var SlotInlineMod = slotModifier("slot", 6 /* InlineModifier */, false, false);
2374
- var PreSlotBlockMod = slotModifier("pre-slot", 7 /* BlockModifier */, true, false);
2375
- var PreSlotInlineMod = slotModifier("pre-slot", 6 /* InlineModifier */, true, false);
2376
- var InjectPreSlotBlockMod = slotModifier(
2377
- "inject-pre-slot",
2378
- 7 /* BlockModifier */,
2379
- true,
2380
- true
2381
- );
2382
- var InjectPreSlotInlineMod = slotModifier(
2383
- "inject-pre-slot",
2384
- 6 /* InlineModifier */,
2385
- true,
2386
- true
2387
- );
2388
-
2389
- // src/builtin/var.ts
2390
- function resolveId(id, cxt) {
2391
- const store = cxt.get(builtins);
2392
- if (store.inlineSlotDelayedStack.find((x) => x.args.includes(id)) || store.blockSlotDelayedStack.find((x) => x.args.includes(id))) {
2393
- debug.trace("delaying the yet unknown argument", id);
2394
- return void 0;
2395
- }
2396
- let value = void 0;
2397
- for (let i = store.inlineInstantiationData.length - 1; i >= 0; i--) {
2398
- const data = store.inlineInstantiationData[i];
2399
- if ((value = data.args.get(id)) !== void 0)
2400
- break;
2401
- }
2402
- for (let i = store.blockInstantiationData.length - 1; i >= 0; i--) {
2403
- const data = store.blockInstantiationData[i];
2404
- if ((value = data.args.get(id)) !== void 0)
2405
- break;
2406
- }
2407
- if (value === void 0)
2408
- value = cxt.variables.get(id);
2409
- return value;
2410
- }
2411
- var ifdefBody = (x) => ({
2412
- prepareExpand(node, cxt) {
2413
- const check = checkArguments(node, 1);
2414
- if (check) return check;
2415
- const arg = node.arguments[0];
2416
- const id = arg.expansion;
2417
- if (id == "") return [new InvalidArgumentMessage(arg.location)];
2418
- const value = resolveId(id, cxt);
2419
- node.state = value !== void 0;
2420
- return [];
2421
- },
2422
- expand(node) {
2423
- return node.state == x ? node.content : [];
2424
- }
2425
- });
2426
- var ifdefBlock = (name, x) => new BlockModifierDefinition(name, 0 /* Normal */, ifdefBody(x));
2427
- var ifdefInline = (name, x) => new InlineModifierDefinition(name, 0 /* Normal */, ifdefBody(x));
2428
- var IfdefBlockMod = ifdefBlock("ifdef", true);
2429
- var IfndefBlockMod = ifdefBlock("ifndef", false);
2430
- var IfdefInlineMod = ifdefInline("ifdef", true);
2431
- var IfndefInlineMod = ifdefInline("ifndef", false);
2432
- var GetVarInlineMod = new InlineModifierDefinition(
2433
- "$",
2434
- 2 /* None */,
2435
- {
2436
- alwaysTryExpand: true,
2437
- // .$:id
2438
- prepareExpand(node, cxt, immediate) {
2439
- const check = checkArguments(node, 1);
2440
- if (check)
2441
- return immediate ? check : [];
2442
- const arg = node.arguments[0];
2443
- const id = arg.expansion;
2444
- if (id == "")
2445
- return immediate ? [new InvalidArgumentMessage(arg.location)] : [];
2446
- const value = resolveId(id, cxt);
2447
- if (value === void 0)
2448
- return immediate ? [new UndefinedVariableMessage(arg.location, id)] : [];
2449
- node.state = { value };
2450
- return [];
2451
- },
2452
- expand(node, _, immediate) {
2453
- if (!node.state) return immediate ? [] : void 0;
2454
- return [{ type: 3 /* Text */, content: node.state.value, location: node.location }];
2455
- }
2456
- }
2457
- );
2458
- var PrintInlineMod = new InlineModifierDefinition(
2459
- "print",
2460
- 2 /* None */,
2461
- {
2462
- // .print:args...
2463
- prepareExpand(node) {
2464
- const check = checkArguments(node);
2465
- if (check) return check;
2466
- node.state = { value: node.arguments.map((x) => x.expansion).join("") };
2467
- return [];
2468
- },
2469
- expand(node) {
2470
- if (!node.state) return [];
2471
- return [{ type: 3 /* Text */, content: node.state.value, location: node.location }];
2472
- }
2473
- }
2474
- );
2475
- var GetVarInterpolator = new ArgumentInterpolatorDefinition(
2476
- "$(",
2477
- ")",
2478
- {
2479
- alwaysTryExpand: true,
2480
- expand(content, cxt) {
2481
- const result = resolveId(content, cxt);
2482
- if (result !== void 0) debug.trace(`$(${content}) --> ${result}`);
2483
- return result;
2484
- }
2485
- }
2486
- );
2487
- var VarMod = new SystemModifierDefinition("var", 2 /* None */, {
2488
- // .var id:value
2489
- prepareExpand(node, cxt) {
2490
- const check = checkArguments(node, 2);
2491
- if (check) return check;
2492
- const arg = node.arguments[0];
2493
- const id = arg.expansion;
2494
- if (id == "")
2495
- return [new InvalidArgumentMessage(arg.location)];
2496
- node.state = {
2497
- id,
2498
- value: node.arguments[1].expansion
2499
- };
2500
- return [];
2501
- },
2502
- expand(node, cxt) {
2503
- if (node.state) {
2504
- cxt.variables.set(node.state.id, node.state.value);
2505
- debug.trace("set variable", node.state.id, "=", node.state.value);
2506
- }
2507
- return [];
2508
- }
2509
- });
2510
-
2511
- // src/builtin/builtin.ts
2512
- var builtin = new Configuration();
2513
- builtin.initializers = [initParseContext];
2514
- builtin.systemModifiers.add(
2515
- DefineBlockMod,
2516
- DefineInlineMod,
2517
- DefineBlockShorthandMod,
2518
- DefineInlineShorthandMod,
2519
- VarMod,
2520
- UseSystemMod
2521
- );
2522
- builtin.blockModifiers.add(
2523
- SlotBlockMod,
2524
- PreSlotBlockMod,
2525
- InjectPreSlotBlockMod,
2526
- ModuleMod,
2527
- UseBlockMod,
2528
- IfdefBlockMod,
2529
- IfndefBlockMod,
2530
- RawBlockMod
2531
- );
2532
- builtin.inlineModifiers.add(
2533
- SlotInlineMod,
2534
- PreSlotInlineMod,
2535
- InjectPreSlotInlineMod,
2536
- GetVarInlineMod,
2537
- PrintInlineMod,
2538
- IfdefInlineMod,
2539
- IfndefInlineMod
2540
- );
2541
- builtin.argumentInterpolators.add(GetVarInterpolator);
2542
- var BuiltinConfiguration = Object.freeze(builtin);
2543
-
2544
- // src/default/bullets.tsx
2545
- import { jsx } from "minimal-jsx-runtime/jsx-runtime";
2546
- var bulletItemBlock = new BlockModifierDefinition(
2547
- "bullet-item",
2548
- 0 /* Normal */,
2549
- { roleHint: void 0 }
2550
- );
2551
- var orderedListItemBlock = new BlockModifierDefinition(
2552
- "ordered-item",
2553
- 0 /* Normal */,
2554
- {
2555
- roleHint: void 0,
2556
- prepareExpand(node) {
2557
- let msgs = checkArguments(node, 0, 1);
2558
- if (msgs) return msgs;
2559
- let arg = node.arguments[0];
2560
- let num = Number.parseInt(arg.expansion);
2561
- if (isNaN(num)) return [
2562
- new InvalidArgumentMessage(arg.location, "should be a number")
2563
- ];
2564
- node.state = num;
2565
- return [];
2566
- }
2567
- }
2568
- );
2569
- var subItemBlock = new BlockModifierDefinition(
2570
- "subitem",
2571
- 0 /* Normal */,
2572
- { roleHint: void 0 }
2573
- );
2574
- var BulletBlocks = [bulletItemBlock, orderedListItemBlock, subItemBlock];
2575
- var BulletBlockRenderersHTML = [
2576
- [
2577
- bulletItemBlock,
2578
- (node, cxt) => /* @__PURE__ */ jsx("li", { children: cxt.state.render(node.content, cxt) })
2579
- ],
2580
- [
2581
- subItemBlock,
2582
- (node, cxt) => /* @__PURE__ */ jsx("div", { class: "subitem", children: cxt.state.render(node.content, cxt) })
2583
- ],
2584
- [
2585
- orderedListItemBlock,
2586
- (node, cxt) => node.state === void 0 ? cxt.state.invalidBlock(node, "bad format") : /* @__PURE__ */ jsx("li", { value: node.state, children: cxt.state.render(node.content, cxt) })
2587
- ]
2588
- ];
2589
-
2590
- // src/default/headings.tsx
2591
- import { jsx as jsx2 } from "minimal-jsx-runtime/jsx-runtime";
2592
- var headings = Symbol();
2593
- function initHeadings(cxt) {
2594
- cxt.init(headings, {
2595
- path: []
2596
- });
2597
- }
2598
- function setHeading(cxt, data) {
2599
- const path = cxt.get(headings).path;
2600
- while (path.length > 0 && path.at(-1).level >= data.level)
2601
- path.pop();
2602
- path.push(data);
2603
- return [];
2604
- }
2605
- function currentHeadingLevel(cxt) {
2606
- return cxt.get(headings).path.at(-1)?.level;
2607
- }
2608
- function currentExplicitHeadingLevel(cxt) {
2609
- return cxt.get(headings).path.findLast((x) => !x.implicit)?.level;
2610
- }
2611
- var headingBlock = new BlockModifierDefinition(
2612
- "heading",
2613
- 0 /* Normal */,
2614
- {
2615
- roleHint: "heading",
2616
- prepareExpand(node, cxt) {
2617
- let msgs = checkArguments(node, 0, 1);
2618
- if (msgs) return msgs;
2619
- msgs = onlyPermitSingleBlock(node);
2620
- if (msgs) return msgs;
2621
- msgs = onlyPermitSimpleParagraphs(node);
2622
- if (msgs) return msgs;
2623
- node.state = { name: void 0, level: currentHeadingLevel(cxt) ?? 1 };
2624
- if (node.arguments.length == 1) {
2625
- const arg = node.arguments[0];
2626
- const level = Number.parseInt(arg.expansion);
2627
- if (isNaN(level) || level < 1 || level > 6)
2628
- msgs = [new InvalidArgumentMessage(
2629
- arg.location,
2630
- "should be a number between 1 and 6"
2631
- )];
2632
- else node.state.level = level;
2633
- }
2634
- setHeading(cxt, node.state);
2635
- return msgs ?? [];
2636
- }
2637
- }
2638
- );
2639
- var implicitHeadingBlock = new BlockModifierDefinition(
2640
- "implicit-heading",
2641
- 2 /* None */,
2642
- {
2643
- roleHint: "heading",
2644
- prepareExpand(node, cxt) {
2645
- let msgs = checkArguments(node, 0, 1);
2646
- if (msgs) return msgs;
2647
- node.state = {
2648
- name: void 0,
2649
- implicit: true,
2650
- level: (currentExplicitHeadingLevel(cxt) ?? 0) + 1
2651
- };
2652
- if (node.arguments.length == 1) {
2653
- const arg = node.arguments[0];
2654
- const level = Number.parseInt(arg.expansion);
2655
- if (isNaN(level) || level < 1 || level > 6)
2656
- msgs = [new InvalidArgumentMessage(
2657
- arg.location,
2658
- "should be a number between 1 and 6"
2659
- )];
2660
- else node.state.level = level;
2661
- }
2662
- setHeading(cxt, node.state);
2663
- return msgs ?? [];
2664
- }
2665
- }
2666
- );
2667
- var numberedHeadingBlock = new BlockModifierDefinition(
2668
- "numbered-heading",
2669
- 0 /* Normal */,
2670
- {
2671
- roleHint: "heading",
2672
- prepareExpand(node, cxt) {
2673
- let msgs = checkArguments(node, 1);
2674
- if (msgs) return msgs;
2675
- msgs = onlyPermitSingleBlock(node);
2676
- if (msgs) return msgs;
2677
- msgs = onlyPermitSimpleParagraphs(node);
2678
- if (msgs) return msgs;
2679
- node.state = { name: void 0, level: currentHeadingLevel(cxt) ?? 1 };
2680
- const arg = node.arguments[0];
2681
- const split = arg.expansion.trim().split(".").filter((x) => x.length > 0);
2682
- if (split.length == 0 || split.length > 6)
2683
- msgs = [new InvalidArgumentMessage(
2684
- arg.location,
2685
- "should be a number between 1 and 6"
2686
- )];
2687
- else node.state = { name: split.join("."), level: split.length };
2688
- setHeading(cxt, node.state);
2689
- return msgs ?? [];
2690
- }
2691
- }
2692
- );
2693
- var HeadingBlocks = [headingBlock, implicitHeadingBlock, numberedHeadingBlock];
2694
- var HeadingBlockRenderersHTML = [
2695
- [headingBlock, (node, cxt) => {
2696
- if (node.state !== void 0) {
2697
- const tag = "h" + node.state.level;
2698
- const para = node.content[0];
2699
- const element = document.createElement(tag);
2700
- element.appendChild(cxt.state.render(para.content, cxt));
2701
- return element;
2702
- }
2703
- return cxt.state.invalidBlock(node, "Bad format");
2704
- }],
2705
- [implicitHeadingBlock, (node, cxt) => {
2706
- if (node.state !== void 0) {
2707
- const tag = "h" + node.state.level;
2708
- const element = document.createElement(tag);
2709
- element.className = "implicit";
2710
- return element;
2711
- }
2712
- return cxt.state.invalidBlock(node, "Bad format");
2713
- }],
2714
- [numberedHeadingBlock, (node, cxt) => {
2715
- if (node.state !== void 0) {
2716
- const tag = "h" + node.state.level;
2717
- const para = node.content[0];
2718
- const element = document.createElement(tag);
2719
- element.appendChild(/* @__PURE__ */ jsx2("span", { class: "heading-number", children: node.state.name }));
2720
- element.appendChild(cxt.state.render(para.content, cxt));
2721
- return element;
2722
- }
2723
- return cxt.state.invalidBlock(node, "Bad format");
2724
- }]
2725
- ];
2726
-
2727
- // src/default/notes.tsx
2728
- import { jsx as jsx3, jsxs } from "minimal-jsx-runtime/jsx-runtime";
2729
- var notes = Symbol();
2730
- function initNotes(cxt) {
2731
- cxt.init(notes, {
2732
- systems: /* @__PURE__ */ new Map(),
2733
- defaultSystem: {
2734
- position: "preserve",
2735
- autonumber: false
2736
- },
2737
- definitions: [],
2738
- currentId: 0
2739
- });
2740
- }
2741
- function getSystem(cxt, name) {
2742
- const defs = cxt.get(notes);
2743
- let system;
2744
- if (name) {
2745
- if (!defs.systems.has(name)) {
2746
- system = { ...defs.defaultSystem };
2747
- defs.systems.set(name, system);
2748
- } else {
2749
- system = defs.systems.get(name);
2750
- }
2751
- } else {
2752
- system = defs.defaultSystem;
2753
- }
2754
- return system;
2755
- }
2756
- var notePositionSystem = new SystemModifierDefinition(
2757
- "note-position",
2758
- 2 /* None */,
2759
- {
2760
- prepareExpand(node, cxt, immediate) {
2761
- let msgs = checkArguments(node, 1, 2);
2762
- if (msgs) return msgs;
2763
- const type = node.arguments[0].expansion.trim();
2764
- if (type != "global" && type != "preserve")
2765
- return [new InvalidArgumentMessage(
2766
- node.arguments[0].location,
2767
- "should be `preserve` or `global`"
2768
- )];
2769
- const name = node.arguments.at(1)?.expansion.trim();
2770
- getSystem(cxt, name).position = type;
2771
- return [];
2772
- }
2773
- }
2774
- );
2775
- var noteRenumberingSystem = new SystemModifierDefinition(
2776
- "note-renumbering",
2777
- 2 /* None */,
2778
- {
2779
- prepareExpand(node, cxt, immediate) {
2780
- let msgs = checkArguments(node, 1, 2);
2781
- if (msgs) return msgs;
2782
- const type = node.arguments[0].expansion.trim();
2783
- if (type != "on" && type != "off")
2784
- return [new InvalidArgumentMessage(
2785
- node.arguments[0].location,
2786
- "should be `preserve` or `global`"
2787
- )];
2788
- const name = node.arguments.at(1)?.expansion.trim();
2789
- getSystem(cxt, name).autonumber = type == "on";
2790
- return [];
2791
- }
2792
- }
2793
- );
2794
- var noteMarkerInline = new InlineModifierDefinition(
2795
- "note",
2796
- 2 /* None */,
2797
- {
2798
- roleHint: "link",
2799
- prepareExpand(node) {
2800
- let msgs = checkArguments(node, 1);
2801
- if (msgs) return msgs;
2802
- node.state = node.arguments[0].expansion;
2803
- return [];
2804
- }
2805
- }
2806
- );
2807
- var noteInline = new InlineModifierDefinition(
2808
- "note-inline",
2809
- 0 /* Normal */,
2810
- {
2811
- roleHint: "quote",
2812
- prepareExpand(node) {
2813
- let msgs = checkArguments(node, 0, 1);
2814
- if (msgs) return msgs;
2815
- node.state = node.arguments.at(0)?.expansion?.trim() ?? "";
2816
- return [];
2817
- },
2818
- afterProcessExpansion(node, cxt) {
2819
- if (node.state !== void 0) {
2820
- const defs = cxt.get(notes);
2821
- defs.definitions.push({
2822
- system: "",
2823
- id: defs.currentId,
2824
- name: node.state,
2825
- location: node.location,
2826
- content: [{
2827
- type: 1 /* Paragraph */,
2828
- location: {
2829
- source: node.location.source,
2830
- start: node.head.end,
2831
- end: node.location.actualEnd ?? node.location.end
2832
- },
2833
- content: node.content
2834
- }]
2835
- });
2836
- defs.currentId++;
2837
- }
2838
- return [];
2839
- }
2840
- }
2841
- );
2842
- var noteBlock = new BlockModifierDefinition(
2843
- "note",
2844
- 0 /* Normal */,
2845
- {
2846
- roleHint: "quote",
2847
- prepareExpand(node, cxt) {
2848
- let msgs = checkArguments(node, 1, 2);
2849
- if (msgs) return msgs;
2850
- const name = node.arguments[0].expansion.trim();
2851
- const system = node.arguments.at(1)?.expansion.trim() ?? "";
2852
- const content = stripNode(...node.content);
2853
- debug.trace(`add note: system=<${""}> name=${node.state} @${node.location.start}`);
2854
- debug.trace(`-->
2855
- `, debugPrint.node(...content));
2856
- const defs = cxt.get(notes);
2857
- const entry = {
2858
- id: defs.currentId,
2859
- system,
2860
- name,
2861
- location: node.location,
2862
- content
2863
- };
2864
- defs.currentId++;
2865
- defs.definitions.push(entry);
2866
- node.state = entry;
2867
- return [];
2868
- }
2869
- }
2870
- );
2871
- var NoteBlocks = [noteBlock];
2872
- var NoteInlines = [noteInline, noteMarkerInline];
2873
- var NoteSystems = [notePositionSystem, noteRenumberingSystem];
2874
- function makeNoteHTML(def, cxt) {
2875
- return /* @__PURE__ */ jsxs("section", { class: "note", id: `note-id-${def.id}`, children: [
2876
- /* @__PURE__ */ jsx3("div", { class: "note-name", children: /* @__PURE__ */ jsx3("p", { children: /* @__PURE__ */ jsx3("a", { href: `#notemarker-id-${def.id}`, children: def.name }) }) }),
2877
- /* @__PURE__ */ jsx3("div", { class: "note-content", children: cxt.state.render(def.content, cxt) })
2878
- ] });
2879
- }
2880
- var NoteInlineRenderersHTML = [
2881
- [noteMarkerInline, (node, cxt) => {
2882
- if (node.state === void 0)
2883
- return cxt.state.invalidInline(node, "bad format");
2884
- const defs = cxt.parsedDocument.context.get(notes).definitions;
2885
- const note = defs.findIndex((x) => (
2886
- /*x.position >= node.start &&*/
2887
- x.name == node.state
2888
- ));
2889
- return /* @__PURE__ */ jsx3("sup", { class: "note", id: `notemarker-id-${note}`, children: note < 0 ? `Not found: ${node.state}` : /* @__PURE__ */ jsx3("a", { href: `#note-id-${note}`, children: node.state }) });
2890
- }]
2891
- ];
2892
- var NoteBlockRenderersHTML = [
2893
- [noteBlock, (node, cxt) => {
2894
- if (node.state === void 0)
2895
- return cxt.state.invalidBlock(node, "bad format");
2896
- const defs = cxt.parsedDocument.context.get(notes);
2897
- const system = defs.systems.get(node.state.system) ?? defs.defaultSystem;
2898
- if (system.position != "preserve") return [];
2899
- return makeNoteHTML(node.state, cxt);
2900
- }]
2901
- ];
2902
- var NotesFooterPlugin = (cxt) => {
2903
- const defs = cxt.parsedDocument.context.get(notes);
2904
- const items = cxt.parsedDocument.context.get(notes).definitions.filter((x) => (defs.systems.get(x.system) ?? defs.defaultSystem).position == "global");
2905
- if (items.length == 0) return void 0;
2906
- return [
2907
- /* @__PURE__ */ jsx3("hr", {}),
2908
- /* @__PURE__ */ jsx3("section", { class: "notes-global", children: items.map((x) => makeNoteHTML(x, cxt)) })
2909
- ];
2910
- };
2911
-
2912
- // src/default/code.tsx
2913
- import { jsx as jsx4 } from "minimal-jsx-runtime/jsx-runtime";
2914
- var CodeBlock = new BlockModifierDefinition(
2915
- "code",
2916
- 1 /* Preformatted */,
2917
- { roleHint: "code" }
2918
- );
2919
- var CodeInline = new InlineModifierDefinition(
2920
- "code",
2921
- 1 /* Preformatted */,
2922
- { roleHint: "code" }
2923
- );
2924
- var CodeBlockRendererHTML = [
2925
- CodeBlock,
2926
- (node, cxt) => /* @__PURE__ */ jsx4("pre", { children: /* @__PURE__ */ jsx4("code", { children: cxt.state.render(node.content, cxt) }) })
2927
- ];
2928
- var CodeInlineRendererHTML = [
2929
- CodeInline,
2930
- (node, cxt) => /* @__PURE__ */ jsx4("span", { children: /* @__PURE__ */ jsx4("code", { children: cxt.state.render(node.content, cxt) }) })
2931
- ];
2932
-
2933
- // src/default/quotes.tsx
2934
- import { jsx as jsx5 } from "minimal-jsx-runtime/jsx-runtime";
2935
- var quoteBlock = new BlockModifierDefinition(
2936
- "quote",
2937
- 0 /* Normal */,
2938
- { roleHint: "quote" }
2939
- );
2940
- var epitaphBlock = new BlockModifierDefinition(
2941
- "epitaph",
2942
- 0 /* Normal */,
2943
- { roleHint: "quote" }
2944
- );
2945
- var calloutBlock = new BlockModifierDefinition(
2946
- "callout",
2947
- 0 /* Normal */,
2948
- { roleHint: "quote" }
2949
- );
2950
- var detailBlock = new BlockModifierDefinition(
2951
- "detail",
2952
- 0 /* Normal */,
2953
- { roleHint: "quote" }
2954
- );
2955
- var attributionBlock = new BlockModifierDefinition(
2956
- "by",
2957
- 0 /* Normal */,
2958
- {
2959
- roleHint: "quote",
2960
- prepareExpand(node) {
2961
- let msgs = onlyPermitSingleBlock(node);
2962
- if (msgs) return msgs;
2963
- msgs = onlyPermitSimpleParagraphs(node);
2964
- if (msgs) return msgs;
2965
- node.state = true;
2966
- return [];
2967
- }
2968
- }
2969
- );
2970
- var QuoteBlocks = [quoteBlock, epitaphBlock, calloutBlock, detailBlock, attributionBlock];
2971
- var QuoteBlockRenderersHTML = [
2972
- [
2973
- quoteBlock,
2974
- (node, cxt) => /* @__PURE__ */ jsx5("blockquote", { children: cxt.state.render(node.content, cxt) })
2975
- ],
2976
- [
2977
- epitaphBlock,
2978
- (node, cxt) => /* @__PURE__ */ jsx5("blockquote", { class: "epitaph", children: cxt.state.render(node.content, cxt) })
2979
- ],
2980
- [
2981
- detailBlock,
2982
- (node, cxt) => /* @__PURE__ */ jsx5("div", { class: "detail", children: cxt.state.render(node.content, cxt) })
2983
- ],
2984
- [
2985
- calloutBlock,
2986
- (node, cxt) => /* @__PURE__ */ jsx5("aside", { children: cxt.state.render(node.content, cxt) })
2987
- ],
2988
- [attributionBlock, (node, cxt) => {
2989
- if (!node.state)
2990
- return cxt.state.invalidBlock(node, "bad format");
2991
- let para = node.content[0];
2992
- return /* @__PURE__ */ jsx5("p", { class: "attribution", children: cxt.state.render(para.content, cxt) });
2993
- }]
2994
- ];
2995
-
2996
- // src/default/inline-styles.tsx
2997
- import { jsx as jsx6 } from "minimal-jsx-runtime/jsx-runtime";
2998
- var emphasisInline = new InlineModifierDefinition(
2999
- "emphasis",
3000
- 0 /* Normal */,
3001
- { roleHint: "emphasis" }
3002
- );
3003
- var keywordInline = new InlineModifierDefinition(
3004
- "keyword",
3005
- 0 /* Normal */,
3006
- { roleHint: "keyword" }
3007
- );
3008
- var highlightInline = new InlineModifierDefinition(
3009
- "highlight",
3010
- 0 /* Normal */,
3011
- { roleHint: "highlight" }
3012
- );
3013
- var commentaryInline = new InlineModifierDefinition(
3014
- "commentary",
3015
- 0 /* Normal */,
3016
- { roleHint: "commentary" }
3017
- );
3018
- var sequenceInline = new InlineModifierDefinition(
3019
- "seq",
3020
- 0 /* Normal */,
3021
- { roleHint: "commentary" }
3022
- );
3023
- var InlineStyles = [emphasisInline, keywordInline, highlightInline, commentaryInline, sequenceInline];
3024
- var InlineStyleRenderersHTML = [
3025
- [
3026
- emphasisInline,
3027
- (node, cxt) => /* @__PURE__ */ jsx6("em", { children: cxt.state.render(node.content, cxt) })
3028
- ],
3029
- [
3030
- keywordInline,
3031
- (node, cxt) => /* @__PURE__ */ jsx6("b", { children: cxt.state.render(node.content, cxt) })
3032
- ],
3033
- [
3034
- highlightInline,
3035
- (node, cxt) => /* @__PURE__ */ jsx6("mark", { children: cxt.state.render(node.content, cxt) })
3036
- ],
3037
- [
3038
- commentaryInline,
3039
- (node, cxt) => /* @__PURE__ */ jsx6("span", { class: "commentary", children: cxt.state.render(node.content, cxt) })
3040
- ],
3041
- [
3042
- sequenceInline,
3043
- (node, cxt) => /* @__PURE__ */ jsx6("span", { class: "seq", children: cxt.state.render(node.content, cxt) })
3044
- ]
3045
- ];
3046
-
3047
- // src/default/misc.tsx
3048
- import { jsx as jsx7, jsxs as jsxs2 } from "minimal-jsx-runtime/jsx-runtime";
3049
- var rubyInline = new InlineModifierDefinition(
3050
- "ruby",
3051
- 0 /* Normal */,
3052
- {
3053
- roleHint: void 0,
3054
- prepareExpand(node) {
3055
- let msgs = checkArguments(node, 1);
3056
- if (msgs) return msgs;
3057
- node.state = node.arguments[0].expansion;
3058
- return [];
3059
- }
3060
- }
3061
- );
3062
- var linkInline = new InlineModifierDefinition(
3063
- "link",
3064
- 0 /* Normal */,
3065
- {
3066
- roleHint: "link",
3067
- prepareExpand(node) {
3068
- let msgs = checkArguments(node, 1);
3069
- if (msgs) return msgs;
3070
- node.state = node.arguments[0].expansion;
3071
- return [];
3072
- }
3073
- }
3074
- );
3075
- var styleBlock = new BlockModifierDefinition(
3076
- "style",
3077
- 0 /* Normal */,
3078
- {
3079
- prepareExpand(node) {
3080
- let msgs = checkArguments(node, 1);
3081
- if (msgs) return msgs;
3082
- node.state = node.arguments[0].expansion;
3083
- return [];
3084
- }
3085
- }
3086
- );
3087
- var breakBlock = new BlockModifierDefinition(
3088
- "break",
3089
- 2 /* None */
3090
- );
3091
- var linkBlock = new BlockModifierDefinition(
3092
- "link",
3093
- 0 /* Normal */,
3094
- {
3095
- roleHint: "link",
3096
- prepareExpand(node) {
3097
- let msgs = checkArguments(node, 1);
3098
- if (msgs) return msgs;
3099
- node.state = node.arguments[0].expansion;
3100
- return [];
3101
- }
3102
- }
3103
- );
3104
- var imageBlock = new BlockModifierDefinition(
3105
- "image",
3106
- 0 /* Normal */,
3107
- {
3108
- roleHint: "link",
3109
- prepareExpand(node) {
3110
- let msgs = checkArguments(node, 1, 2);
3111
- if (msgs) return msgs;
3112
- msgs = onlyPermitSingleBlock(node);
3113
- if (msgs) return msgs;
3114
- msgs = onlyPermitSimpleParagraphs(node);
3115
- if (msgs) return msgs;
3116
- node.state = node.arguments.map((x) => x.expansion).join(":");
3117
- return [];
3118
- }
3119
- }
3120
- );
3121
- var MiscInlines = [rubyInline, linkInline];
3122
- var MiscBlocks = [styleBlock, breakBlock, linkBlock, imageBlock];
3123
- var MiscInlineRenderersHTML = [
3124
- [
3125
- rubyInline,
3126
- (node, cxt) => node.state === void 0 ? cxt.state.invalidInline(node, "bad format") : /* @__PURE__ */ jsxs2("ruby", { children: [
3127
- cxt.state.render(node.content, cxt),
3128
- /* @__PURE__ */ jsx7("rt", { children: node.state })
3129
- ] })
3130
- ],
3131
- [
3132
- linkInline,
3133
- (node, cxt) => node.state === void 0 ? cxt.state.invalidInline(node, "bad format") : /* @__PURE__ */ jsx7("a", { href: encodeURI(node.state), children: cxt.state.render(node.content, cxt) })
3134
- ]
3135
- ];
3136
- var MiscBlockRenderersHTML = [
3137
- [
3138
- styleBlock,
3139
- (node, cxt) => node.state === void 0 ? cxt.state.invalidBlock(node, "bad format") : /* @__PURE__ */ jsx7("div", { class: `emmmstyle-${node.state}`, style: "display:contents", children: cxt.state.render(node.content, cxt) })
3140
- ],
3141
- [breakBlock, () => /* @__PURE__ */ jsx7("hr", {})],
3142
- [
3143
- linkBlock,
3144
- (node, cxt) => {
3145
- if (node.state === void 0)
3146
- return cxt.state.invalidBlock(node, "bad format");
3147
- const content = cxt.state.render(node.content, cxt);
3148
- return /* @__PURE__ */ jsx7("a", { href: encodeURI(node.state), children: content.childElementCount > 0 ? content : node.state });
3149
- }
3150
- ],
3151
- [imageBlock, (node, cxt) => {
3152
- if (node.state === void 0)
3153
- return cxt.state.invalidBlock(node, "bad format");
3154
- let transformed;
3155
- try {
3156
- transformed = cxt.config.options.transformAsset(node.state);
3157
- } catch {
3158
- return cxt.state.invalidBlock(node, "unable to transform asset");
3159
- }
3160
- return /* @__PURE__ */ jsxs2("figure", { children: [
3161
- transformed ? /* @__PURE__ */ jsx7("img", { src: transformed, "data-original-src": node.state }) : /* @__PURE__ */ jsx7("img", { src: node.state }),
3162
- node.content.length > 0 ? /* @__PURE__ */ jsx7("figcaption", { children: cxt.state.render(node.content[0].content, cxt) }) : []
3163
- ] });
3164
- }]
3165
- ];
3166
-
3167
- // src/default/vars.ts
3168
- function createWrapper(name, varname) {
3169
- varname = varname ?? name.toUpperCase();
3170
- return new SystemModifierDefinition(name, 0 /* Normal */, {
3171
- delayContentExpansion: true,
3172
- afterProcessExpansion(node, cxt) {
3173
- let msgs = checkArguments(node, 0);
3174
- if (msgs) return msgs;
3175
- const result = onlyPermitPlaintextParagraph(node);
3176
- if (typeof result !== "string") return result;
3177
- const previous = cxt.variables.get(varname);
3178
- if (previous)
3179
- msgs = [new OverwriteSpecialVariableMessage(node.head, varname, previous)];
3180
- cxt.variables.set(varname, result);
3181
- debug.trace(varname, "->", result);
3182
- return msgs ?? [];
3183
- }
3184
- });
3185
- }
3186
- var VarWrappers = [
3187
- createWrapper("title"),
3188
- createWrapper("subtitle"),
3189
- createWrapper("author"),
3190
- createWrapper("translator"),
3191
- createWrapper("proofreader"),
3192
- createWrapper("typeset-by"),
3193
- createWrapper("cover-by"),
3194
- createWrapper("cover-img"),
3195
- createWrapper("orig-title"),
3196
- createWrapper("orig-link"),
3197
- createWrapper("theme-color")
3198
- ];
3199
-
3200
- // src/default/default.ts
3201
- var config = Configuration.from(BuiltinConfiguration);
3202
- config.initializers.push(initNotes, initHeadings);
3203
- config.blockModifiers.add(
3204
- ...HeadingBlocks,
3205
- ...BulletBlocks,
3206
- CodeBlock,
3207
- ...QuoteBlocks,
3208
- ...MiscBlocks,
3209
- ...NoteBlocks
3210
- );
3211
- config.inlineModifiers.add(
3212
- CodeInline,
3213
- ...InlineStyles,
3214
- ...MiscInlines,
3215
- ...NoteInlines
3216
- );
3217
- config.systemModifiers.add(
3218
- ...VarWrappers,
3219
- ...NoteSystems
3220
- );
3221
- var DefaultConfiguration = Object.freeze(config);
3222
-
3223
- // src/default/html-renderer.tsx
3224
- import { jsx as jsx8, jsxs as jsxs3 } from "minimal-jsx-runtime/jsx-runtime";
3225
- var HTMLRenderState = class {
3226
- title = "";
3227
- stylesheet = "";
3228
- // FIXME: very unsafe!
3229
- cssVariables = /* @__PURE__ */ new Map();
3230
- invalidBlock(node, msg) {
3231
- let name = NodeType[node.type];
3232
- if (node.type === 7 /* BlockModifier */)
3233
- name += ` (${node.mod.name})`;
3234
- return /* @__PURE__ */ jsxs3("details", { class: "invalid", children: [
3235
- /* @__PURE__ */ jsxs3("summary", { children: [
3236
- "Invalid ",
3237
- name
3238
- ] }),
3239
- /* @__PURE__ */ jsx8("i", { children: msg })
3240
- ] });
3241
- }
3242
- invalidInline(node, msg) {
3243
- let name = NodeType[node.type];
3244
- if (node.type === 6 /* InlineModifier */)
3245
- name += ` (${node.mod.name})`;
3246
- return /* @__PURE__ */ jsxs3("span", { class: "invalid", children: [
3247
- "Invalid ",
3248
- name,
3249
- ": ",
3250
- /* @__PURE__ */ jsx8("i", { children: msg })
3251
- ] });
3252
- }
3253
- render(elems, cxt) {
3254
- let fragment = new DocumentFragment();
3255
- elems.map((x) => cxt.renderEntity(x)).filter((x) => x !== void 0).flat().forEach((x) => fragment.appendChild(x));
3256
- return fragment;
3257
- }
3258
- };
3259
- var htmlConfig = new RenderConfiguration(
3260
- {
3261
- headPlugins: [],
3262
- headerPlugins: [],
3263
- footerPlugins: [NotesFooterPlugin],
3264
- postprocessPlugins: [],
3265
- transformAsset: () => void 0
3266
- // postprocessPlugins: [],
3267
- },
3268
- (results, cxt) => {
3269
- let styles = cxt.state.stylesheet.replaceAll(
3270
- /var\(--(.*?)\)/g,
3271
- (m, c) => cxt.state.cssVariables.get(c) ?? m
3272
- );
3273
- let doc = document.implementation.createHTMLDocument(cxt.state.title);
3274
- doc.head.append(
3275
- /* @__PURE__ */ jsx8("meta", { charset: "UTF-8" }),
3276
- /* @__PURE__ */ jsx8("style", { children: styles }),
3277
- ...cxt.config.options.headPlugins.map((x) => x(cxt)).filter((x) => x !== void 0).flat()
3278
- );
3279
- doc.body.append(
3280
- /* @__PURE__ */ jsx8("section", { class: "article-container", children: /* @__PURE__ */ jsxs3("section", { class: "article-body", children: [
3281
- cxt.config.options.headerPlugins.map((x) => x(cxt)).filter((x) => x !== void 0),
3282
- results,
3283
- cxt.config.options.footerPlugins.map((x) => x(cxt)).filter((x) => x !== void 0)
3284
- ] }) })
3285
- );
3286
- for (const p of cxt.config.options.postprocessPlugins) {
3287
- p(cxt, doc);
3288
- }
3289
- return doc;
3290
- }
3291
- );
3292
- htmlConfig.paragraphRenderer = (node, cxt) => /* @__PURE__ */ jsx8("p", { children: node.content.map((x) => cxt.renderEntity(x)).filter((x) => x !== void 0) });
3293
- htmlConfig.textRenderer = (node, cxt) => {
3294
- switch (node.type) {
3295
- case 2 /* Preformatted */:
3296
- return new Text(node.content.text);
3297
- case 3 /* Text */:
3298
- case 4 /* Escaped */:
3299
- const split = node.content.split("\n");
3300
- const result = [];
3301
- for (let i = 0; i < split.length; i++) {
3302
- result.push(new Text(split[i]));
3303
- if (i < split.length - 1)
3304
- result.push(/* @__PURE__ */ jsx8("br", {}));
3305
- }
3306
- console.log(result);
3307
- return result;
3308
- default:
3309
- return debug.never(node);
3310
- }
3311
- };
3312
- htmlConfig.undefinedBlockRenderer = (node, cxt) => {
3313
- return cxt.state.invalidBlock(node, `No renderer defined for ${node.mod.name}`);
3314
- };
3315
- htmlConfig.undefinedInlineRenderer = (node, cxt) => {
3316
- return cxt.state.invalidInline(node, `No renderer defined for ${node.mod.name}`);
3317
- };
3318
- htmlConfig.addBlockRenderer(
3319
- ...HeadingBlockRenderersHTML,
3320
- ...BulletBlockRenderersHTML,
3321
- CodeBlockRendererHTML,
3322
- ...QuoteBlockRenderersHTML,
3323
- ...MiscBlockRenderersHTML,
3324
- ...NoteBlockRenderersHTML
3325
- );
3326
- htmlConfig.addInlineRenderer(
3327
- CodeInlineRendererHTML,
3328
- ...InlineStyleRenderersHTML,
3329
- ...MiscInlineRenderersHTML,
3330
- ...NoteInlineRenderersHTML
3331
- );
3332
- var HTMLRenderConfiguration = htmlConfig;
3333
-
3334
- // src/index.ts
3335
- var emmmVersion = "0.0.6";
3336
- function setDebugLevel(level) {
3337
- debug.level = level;
3338
- }
3339
- export {
3340
- ArgumentInterpolatorDefinition,
3341
- BlockModifierDefinition,
3342
- BuiltinConfiguration,
3343
- Configuration,
3344
- DebugLevel,
3345
- DefaultConfiguration,
3346
- Document,
3347
- HTMLRenderConfiguration,
3348
- HTMLRenderState,
3349
- InlineModifierDefinition,
3350
- MessageSeverity,
3351
- ModifierSlotType,
3352
- NodeType,
3353
- ParseContext,
3354
- RenderConfiguration,
3355
- RenderContext,
3356
- SimpleScanner,
3357
- StringSource,
3358
- SystemModifierDefinition,
3359
- debugPrint,
3360
- emmmVersion,
3361
- modifier_helper_exports as helper,
3362
- messages_exports as messages,
3363
- parse,
3364
- setDebugLevel
3365
- };
3366
- //# sourceMappingURL=index.mjs.map