-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnode-api-test.mjs
More file actions
731 lines (662 loc) · 29.7 KB
/
Copy pathnode-api-test.mjs
File metadata and controls
731 lines (662 loc) · 29.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
import * as mds from '../packages/mds/dist/node.js';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
await mds.init();
console.log(`Backend: ${mds.getBackend()}`);
const tests = [];
let passed = 0;
let failed = 0;
function test(name, fn) {
tests.push({ name, fn });
}
function assert(condition, msg) {
if (!condition) throw new Error(`Assertion failed: ${msg}`);
}
// ─── Test: compile simple string ─────────────────────────────────
test('compile simple string', () => {
const result = mds.compile('---\nname: World\n---\nHello {{name}}!\n');
assert(result.kind === 'markdown', `expected kind==='markdown', got ${result.kind}`);
assert(result.output.includes('Hello World!'), 'should interpolate variable');
assert(result.warnings.length === 0, 'should have no warnings');
assert(result.dependencies.length === 0, 'string compile has no deps');
});
// ─── Test: compile with runtime vars ─────────────────────────────
test('compile with vars override', () => {
const result = mds.compile('---\nenv: dev\n---\nEnv: {{env}}\n', {
vars: { env: 'production' },
});
assert(result.output.includes('Env: production'), 'vars should override frontmatter');
});
// ─── Test: compile file with imports ─────────────────────────────
test('compileFile with imports', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'ai-agent/system-prompt.mds'),
);
assert(result.output.includes('DataBot'), 'should contain agent name');
assert(result.output.includes('Safety Guidelines'), 'should include imported guardrails');
assert(result.dependencies.length === 3, `expected 3 deps, got ${result.dependencies.length}`);
});
// ─── Test: compileFile with vars ─────────────────────────────────
test('compileFile with vars', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'edge-cases/08_runtime_vars.mds'),
{ vars: { is_production: true, is_development: false, debug: true } },
);
assert(result.output.includes('Debug Mode Enabled'), 'debug should be enabled via vars');
assert(result.output.includes('Production Checklist'), 'should show production section');
assert(!result.output.includes('Development Notes'), 'should NOT show dev section');
});
// ─── Test: check valid file ──────────────────────────────────────
test('check valid file', async () => {
const result = await mds.checkFile(
resolve(__dirname, 'ai-agent/multi-turn-prompt.mds'),
);
assert(result.warnings.length === 0, 'should have no warnings');
});
// ─── Test: error handling with isMdsError ────────────────────────
test('error handling', () => {
try {
mds.compile('Hello {{undefined_var}}!');
assert(false, 'should have thrown');
} catch (err) {
assert(mds.isMdsError(err), 'should be MDS error');
assert(err.code === 'mds::undefined_var', `expected mds::undefined_var, got ${err.code}`);
}
});
// ─── Test: complex template with nested data ─────────────────────
test('complex nested data', () => {
const source = `---
users:
- name: Alice
active: true
- name: Bob
active: false
---
@for user in users:
@if user.active:
- {{user.name}} (active)
@end
@end
`;
const result = mds.compile(source);
assert(result.output.includes('Alice (active)'), 'should include active user');
const body = result.output.split('---\n').slice(2).join('---\n');
assert(!body.includes('Bob'), 'body should exclude inactive user');
});
// ─── Test: function definition and call ──────────────────────────
test('function definition and call', () => {
const source = `---
---
@define greet(name, role):
Hello {{name}}, you are a {{role}}!
@end
{{greet("Alice", "developer")}}
`;
const result = mds.compile(source);
assert(result.output.includes('Hello Alice, you are a developer!'), 'should expand function');
});
// ─── Test: code block passthrough ────────────────────────────────
test('code block passthrough', () => {
const source = '---\nlang: Python\n---\n\n```python\nx = {\"key\": \"value\"}\n```\n\nLanguage: {{lang}}\n';
const result = mds.compile(source);
assert(result.output.includes('{"key": "value"}'), 'braces in code block should be literal');
assert(result.output.includes('Language: Python'), 'var outside code block should interpolate');
});
// ─── Test: escaped braces ────────────────────────────────────────
test('escaped braces', () => {
// In the new engine: {x} is literal text; {{x}} interpolates; \{{ is a literal {{
const source = '---\nname: test\n---\nLiteral: {name} Interpolated: {{name}}\n';
const result = mds.compile(source);
assert(result.output.includes('Literal: {name}'), 'single braces are literal text');
assert(result.output.includes('Interpolated: test'), 'double braces interpolate the variable');
});
// ─── Test: empty array loop ──────────────────────────────────────
test('empty array loop', () => {
const source = '---\nitems: []\n---\nBefore\n@for item in items:\n{{item}}\n@end\nAfter\n';
const result = mds.compile(source);
assert(result.output.includes('Before'), 'should have content before loop');
assert(result.output.includes('After'), 'should have content after loop');
assert(!result.output.includes('undefined'), 'should not have undefined');
});
// ─── Test: built-in string functions ─────────────────────────
test('built-in string functions', () => {
const result = mds.compile(`---
name: " hello world "
greeting: "Hello, World!"
---
UPPER: {{upper(name)}}
LOWER: {{lower(greeting)}}
TRIM: [{{trim(name)}}]
REPLACE: {{replace(greeting, "World", "MDS")}}
STARTS: {{starts_with(greeting, "Hello")}}
ENDS: {{ends_with(greeting, "World!")}}
CONTAINS: {{contains(greeting, "World")}}
SLICE: [{{slice(greeting, 0, 5)}}]
`);
assert(result.output.includes('UPPER: HELLO WORLD'), 'upper should work');
assert(result.output.includes('LOWER: hello, world!'), 'lower should work');
assert(result.output.includes('TRIM: [hello world]'), 'trim should work');
assert(result.output.includes('REPLACE: Hello, MDS!'), 'replace should work');
assert(result.output.includes('STARTS: true'), 'starts_with should return true');
assert(result.output.includes('ENDS: true'), 'ends_with should return true');
assert(result.output.includes('CONTAINS: true'), 'contains should return true');
assert(result.output.includes('SLICE: [Hello]'), 'slice should work');
});
// ─── Test: built-in array functions ─────────────────────────
test('built-in array functions', () => {
const result = mds.compile(`---
fruits:
- banana
- apple
- cherry
- apple
csv: "red,green,blue"
---
SPLIT: {{split(csv, ",")}}
JOIN: {{join(fruits, " | ")}}
LENGTH: {{length(fruits)}}
FIRST: {{first(fruits)}}
LAST: {{last(fruits)}}
SORT: {{sort(fruits)}}
UNIQUE: {{unique(fruits)}}
REVERSE: {{reverse(fruits)}}
`);
assert(result.output.includes('SPLIT: red, green, blue'), 'split should work');
assert(result.output.includes('JOIN: banana | apple | cherry | apple'), 'join should work');
assert(result.output.includes('LENGTH: 4'), 'length should work');
assert(result.output.includes('FIRST: banana'), 'first should work');
assert(result.output.includes('LAST: apple'), 'last should work');
assert(result.output.includes('SORT: apple, apple, banana, cherry'), 'sort should work');
assert(result.output.includes('UNIQUE: banana, apple, cherry'), 'unique should work');
assert(result.output.includes('REVERSE: apple, cherry, apple, banana'), 'reverse should work');
});
// ─── Test: type conversion builtins ─────────────────────────
test('type conversion builtins', () => {
const result = mds.compile(`---
num: 42
flag: true
nothing: null
numeric_str: "123"
---
S_NUM: [{{string(num)}}]
S_BOOL: [{{string(flag)}}]
S_NULL: [{{string(nothing)}}]
N_STR: {{number(numeric_str)}}
N_BOOL: {{number(flag)}}
N_NULL: {{number(nothing)}}
`);
assert(result.output.includes('S_NUM: [42]'), 'string(num) should work');
assert(result.output.includes('S_BOOL: [true]'), 'string(bool) should work');
assert(result.output.includes('S_NULL: []'), 'string(null) should be empty');
assert(result.output.includes('N_STR: 123'), 'number(str) should work');
assert(result.output.includes('N_BOOL: 1'), 'number(true) should be 1');
assert(result.output.includes('N_NULL: 0'), 'number(null) should be 0');
});
// ─── Test: default function arguments ───────────────────────
test('default function arguments', () => {
const result = mds.compile(`---
---
@define greet(name, greeting = "Hello"):
{{greeting}}, {{name}}!
@end
@define badge(label, color = "blue", size = 3):
[{{color}}:{{label}}:{{size}}]
@end
DEFAULTS: {{greet("Alice")}}
OVERRIDE: {{greet("Bob", "Hey")}}
BADGE_DEF: {{badge("v2")}}
BADGE_PART: {{badge("v2", "green")}}
BADGE_FULL: {{badge("v2", "red", 5)}}
`);
assert(result.output.includes('DEFAULTS: Hello, Alice!'), 'default arg should apply');
assert(result.output.includes('OVERRIDE: Hey, Bob!'), 'explicit arg should override');
assert(result.output.includes('BADGE_DEF: [blue:v2:3]'), 'all defaults should apply');
assert(result.output.includes('BADGE_PART: [green:v2:3]'), 'partial override should work');
assert(result.output.includes('BADGE_FULL: [red:v2:5]'), 'full override should work');
});
// ─── Test: default arg types (number, bool, null) ───────────
test('default arg types', () => {
const result = mds.compile(`---
---
@define show_num(val = 42):
num:{{val}}
@end
@define show_bool(val = true):
bool:{{val}}
@end
@define show_null(val = null):
@if val:
has_val
@else:
null_val
@end
@end
{{show_num()}}
{{show_bool()}}
{{show_null()}}
{{show_null("override")}}
`);
assert(result.output.includes('num:42'), 'default number arg should work');
assert(result.output.includes('bool:true'), 'default bool arg should work');
assert(result.output.includes('null_val'), 'default null arg should be falsy');
assert(result.output.includes('has_val'), 'overridden null default should be truthy');
});
// ─── Test: logical AND operator ─────────────────────────────
test('logical AND operator', () => {
const result = mds.compile(`---
a: true
b: true
c: false
---
@if a && b:
BOTH_TRUE
@end
@if a && c:
SHOULD_NOT_APPEAR
@else:
AND_FALSE
@end
`);
assert(result.output.includes('BOTH_TRUE'), 'AND with both true should render');
assert(!result.output.includes('SHOULD_NOT_APPEAR'), 'AND with one false should not render');
assert(result.output.includes('AND_FALSE'), 'AND false branch should render');
});
// ─── Test: logical OR operator ──────────────────────────────
test('logical OR operator', () => {
const result = mds.compile(`---
a: true
b: false
c: false
---
@if a || b:
OR_TRUE
@end
@if b || c:
SHOULD_NOT_APPEAR
@else:
OR_FALSE
@end
`);
assert(result.output.includes('OR_TRUE'), 'OR with one true should render');
assert(!result.output.includes('SHOULD_NOT_APPEAR'), 'OR with both false should not render');
assert(result.output.includes('OR_FALSE'), 'OR false branch should render');
});
// ─── Test: operator precedence (AND binds tighter) ──────────
test('operator precedence', () => {
const result = mds.compile(`---
a: true
b: false
c: false
---
@if b && c || a:
PREC_PASS
@end
@if a || b && c:
PREC_PASS2
@end
`);
assert(result.output.includes('PREC_PASS'), '(false && false) || true should be true');
assert(result.output.includes('PREC_PASS2'), 'true || (false && false) should be true');
});
// ─── Test: chaining built-in functions ──────────────────────
test('chaining builtins', () => {
const result = mds.compile(`---
---
CHAIN1: {{upper(trim(" hello "))}}
CHAIN2: {{join(sort(split("cherry,apple,banana", ",")), " < ")}}
CHAIN3: {{upper(replace("hello world", "world", "mds"))}}
CHAIN4: {{reverse(slice("abcdefgh", 2, 6))}}
CHAIN5: {{length(split("a,b,c,d,e", ","))}}
CHAIN6: {{first(reverse(split("a,b,c", ",")))}}
`);
assert(result.output.includes('CHAIN1: HELLO'), 'upper(trim()) should chain');
assert(result.output.includes('CHAIN2: apple < banana < cherry'), 'sort(split()) should chain');
assert(result.output.includes('CHAIN3: HELLO MDS'), 'upper(replace()) should chain');
assert(result.output.includes('CHAIN4: fedc'), 'reverse(slice()) should chain');
assert(result.output.includes('CHAIN5: 5'), 'length(split()) should chain');
assert(result.output.includes('CHAIN6: c'), 'first(reverse(split())) should chain');
});
// ─── Test: builtins with logical operators ──────────────────
test('builtins with logical operators in same template', () => {
const result = mds.compile(`---
admin: true
active: true
name: "Alice"
---
@define user_line(user_name, role = "member"):
@if admin && active:
{{upper(user_name)}}: {{role}}
@end
@end
{{user_line(name)}}
{{user_line("Bob", "admin")}}
`);
assert(result.output.includes('ALICE: member'), 'default arg + logical + builtin should work');
assert(result.output.includes('BOB: admin'), 'explicit arg should override default');
});
// ─── Test: compileFile with v0.2.0 edge-case templates ──────
test('compileFile: builtin string functions', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'edge-cases/16_builtin_string_functions.mds'),
);
assert(result.output.includes('UPPER: HELLO WORLD'), 'upper via file');
assert(result.output.includes('TRIM: [hello world]'), 'trim via file');
assert(result.output.includes('REPLACE: Hello, MDS!'), 'replace via file');
});
test('compileFile: default arguments', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'edge-cases/19_default_arguments.mds'),
);
assert(result.output.includes('Hello, Alice!'), 'default arg via file');
assert(result.output.includes('Hey, Bob!'), 'override arg via file');
assert(result.output.includes('[blue:v0.2.0:3]'), 'multi-default via file');
});
test('compileFile: logical operators', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'edge-cases/20_logical_operators.mds'),
);
assert(!result.output.includes('FAIL'), 'no FAIL lines in logical operators template');
const passCount = (result.output.match(/PASS/g) || []).length;
assert(passCount >= 10, `expected >=10 PASS lines, got ${passCount}`);
});
test('compileFile: chaining builtins', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'edge-cases/21_chaining_builtins.mds'),
);
assert(result.output.includes('TYPESCRIPT'), 'chain upper(trim(first(split()))) via file');
assert(result.output.includes('apple < banana < cherry'), 'chain sort+join via file');
assert(result.output.includes('HELLO MDS'), 'chain replace+upper via file');
});
test('compileFile: combined v2 features', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'edge-cases/22_combined_v2_features.mds'),
);
assert(result.output.includes('[ADMIN] ALICE'), 'combined: user badge with logical+builtin');
assert(result.output.includes('go, python, rust, typescript'), 'combined: unique+sort+join');
assert(result.output.includes('Tag count: 4'), 'combined: length(unique())');
assert(result.output.includes('Account suspended: charlie'), 'combined: inactive branch');
});
// ─── Tests: expression directives (issue #74) ───────────────────
test('expression @if: function call truthy', () => {
const result = mds.compile(`---
tags:
- rust
- go
---
@if contains(tags, "rust"):
yes
@else:
no
@end
`);
assert(result.output.includes('yes'), '@if contains() should be truthy');
});
test('expression @if: negated function call', () => {
const result = mds.compile(`---
name: alice
---
@if !starts_with(name, "z"):
yes
@else:
no
@end
`);
assert(result.output.includes('yes'), '@if !starts_with() should be truthy for non-z name');
});
test('expression @if: comparison with expression on both sides', () => {
const result = mds.compile(`---
a: Alice
b: ALICE
---
@if lower(a) == lower(b):
match
@else:
no-match
@end
`);
assert(result.output.includes('match'), '@if lower(a)==lower(b) should match');
});
test('expression @for: function call iterable', () => {
const result = mds.compile(`---
csv: "x,y,z"
---
@for item in split(csv, ","):
- {{item}}
@end
`);
assert(result.output.includes('- x'), '@for split iterable should produce x');
assert(result.output.includes('- y'), '@for split iterable should produce y');
assert(result.output.includes('- z'), '@for split iterable should produce z');
});
test('expression @for: nested calls (sort+unique)', () => {
const result = mds.compile(`---
tags:
- b
- a
- b
---
@for t in sort(unique(tags)):
- {{t}}
@end
`);
const lines = result.output.split('\n').filter(l => l.startsWith('- '));
assert(lines.length === 2, `should have 2 unique items, got ${lines.length}`);
assert(result.output.includes('- a'), 'sorted unique should include a');
assert(result.output.includes('- b'), 'sorted unique should include b');
});
test('expression @if: logical AND with function calls', () => {
const result = mds.compile(`---
text: grunge
---
@if contains(text, "g") && contains(text, "r"):
yes
@else:
no
@end
`);
assert(result.output.includes('yes'), '@if && with calls should work');
});
test('expression @if: error cases (undefined function)', () => {
try {
mds.compile('@if notabuiltin(x):\nyes\n@end\n');
assert(false, 'should have thrown');
} catch {
// expected
}
});
test('compileFile: expression directives', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'edge-cases/23_expression_directives.mds'),
);
assert(result.output.includes('Has rust tag'), 'expression @if contains should work');
assert(result.output.includes('Admin access granted'), 'expression @if lower==admin should work');
assert(result.output.includes('- a'), '@for split iterable should work');
assert(result.output.includes('- go'), '@for sort(unique) should produce sorted results');
});
test('compileFile: colon in string args', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'edge-cases/24_colon_in_string_args.mds'),
);
assert(result.output.includes('Path contains usr:local'), 'colon in string arg for @if');
assert(result.output.includes('- usr'), '@for with colon separator should work');
});
// ─── Tests: frontmatter imports (issue #75) ────────────────────
test('compileFile: frontmatter imports (alias, selective, merge)', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'edge-cases/25_frontmatter_imports.mds'),
);
assert(result.output.includes('**Frontmatter Imports**'), 'alias import: fmt.bold should work');
assert(result.output.includes('`Frontmatter Imports`'), 'alias import: fmt.badge should work');
assert(result.output.includes('Safety Guidelines'), 'selective import: safety_rules should work');
assert(result.output.includes('professional'), 'selective import: tone_professional should work');
assert(result.output.includes('MDS Templates'), 'merge import: teacher should work');
assert(result.dependencies.length >= 3, `expected >=3 deps, got ${result.dependencies.length}`);
});
test('frontmatter imports: inline alias', () => {
const lib = `@define greet(x):\nHello {{x}}!\n@end\n@export greet\n`;
const main = `---\ntype: mds\nimports:\n - path: ./lib.mds\n as: lib\n---\n{{lib.greet("World")}}\n`;
try {
const result = mds.compile(main);
assert(false, 'inline frontmatter imports need file-based resolution');
} catch {
// frontmatter imports require file resolution — expected to fail with compile()
}
});
test('frontmatter imports: compile() rejects scalar imports key', () => {
try {
mds.compile(`---\nimports: some_value\nname: test\n---\nHello {{name}}\n`);
assert(false, 'should throw — compile() treats source as MDS, so imports is reserved');
} catch (err) {
assert(mds.isMdsError(err), 'should be MDS error');
assert(err.code === 'mds::import', `expected mds::import, got ${err.code}`);
}
});
// ─── Tests: intrinsic output kind (discriminated union) ──────────
test('kind: markdown template returns kind==="markdown"', () => {
const result = mds.compile('---\nname: World\n---\nHello {{name}}!\n');
assert(result.kind === 'markdown', `expected kind==='markdown', got ${result.kind}`);
assert(typeof result.output === 'string', 'markdown result must have string output');
assert(!('messages' in result), 'markdown result must not have messages field');
});
test('kind: compile() result has kind on every markdown call', () => {
const result = mds.compile('No frontmatter, just text.\n');
assert(result.kind === 'markdown', `expected kind==='markdown', got ${result.kind}`);
assert(result.output.includes('No frontmatter'), 'output should contain text');
});
test('kind: messages template returns kind==="messages"', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'ai-agent/chat-messages.mds'),
);
assert(result.kind === 'messages', `expected kind==='messages', got ${result.kind}`);
assert(Array.isArray(result.messages), 'messages result must have array messages');
assert(!('output' in result), 'messages result must not have output field');
assert(result.messages.length > 0, 'chat-messages.mds should produce at least one message');
const first = result.messages[0];
assert(typeof first.role === 'string' && first.role.length > 0, 'each message must have a non-empty role');
assert(typeof first.content === 'string', 'each message must have string content');
});
test('kind: messages array elements are {role, content} objects', async () => {
const result = await mds.compileFile(
resolve(__dirname, 'ai-agent/chat-messages.mds'),
);
assert(result.kind === 'messages', 'must be messages kind');
for (const msg of result.messages) {
assert(typeof msg.role === 'string', `role must be string, got ${typeof msg.role}`);
assert(typeof msg.content === 'string', `content must be string, got ${typeof msg.content}`);
assert(Object.keys(msg).sort().join(',') === 'content,role', `message must only have role+content keys`);
}
});
test('kind: mixed content throws mds::mixed_content', () => {
// Loose top-level prose alongside @message is a hard compile error.
const source = 'This is loose prose.\n@message user:\nHello!\n@end\n';
try {
mds.compile(source);
assert(false, 'should have thrown mds::mixed_content');
} catch (err) {
assert(mds.isMdsError(err), `expected MDS error, got ${err}`);
assert(
err.code === 'mds::mixed_content',
`expected mds::mixed_content, got ${err.code}`,
);
}
});
test('kind: messages template with zero messages emits empty array', () => {
// A messages template where all @message blocks are gated by a falsy @if produces [].
// Detection is static: the @message block is seen by the parser, so kind==='messages'.
const source = '---\nenabled: false\n---\n@if enabled:\n@message user:\nSkipped.\n@end\n@end\n';
const result = mds.compile(source);
assert(result.kind === 'messages', `expected kind==='messages', got ${result.kind}`);
assert(Array.isArray(result.messages), 'should have messages array');
assert(result.messages.length === 0, `expected 0 messages, got ${result.messages.length}`);
});
// ─── Tests: lint API (v0.4.0) ────────────────────────────────────
test('lint: canonical shape + unused-variable finding', () => {
const result = mds.lint('---\nused: yes\nnever_used: 1\n---\n# Doc\n\nValue: {{used}}\n');
assert(result.version === 1, `lint result version must be 1, got ${result.version}`);
assert(Array.isArray(result.files), 'lint result must have files array');
assert(result.truncated === false, 'lint result truncated must be false');
assert(result.files.length === 1, `expected 1 file with findings, got ${result.files.length}`);
assert(result.files[0].file === 'input.mds', `string-source lint file key must be input.mds, got ${result.files[0].file}`);
const diag = result.files[0].diagnostics.find((d) => d.rule === 'unused-variable');
assert(diag, 'should report unused-variable for never_used');
assert(diag.severity === 'warn', `unused-variable severity must be warn, got ${diag.severity}`);
assert(diag.message.includes('never_used'), 'diagnostic message should name the variable');
assert(typeof diag.fixable === 'boolean', 'diagnostic must have boolean fixable');
assert(diag.span && typeof diag.span.offset === 'number', 'diagnostic should carry a span');
});
test('lintVirtual: duplicate-import finding across a 2-module map', () => {
const result = mds.lintVirtual(
{
'main.mds': '@import "./lib.mds"\n@import "./lib.mds"\n\n# Main\n',
'lib.mds': '## Lib\n',
},
'main.mds',
);
assert(result.version === 1 && result.truncated === false, 'canonical lint envelope');
assert(result.files[0].file === 'main.mds', `file key must be the caller entry name, got ${result.files[0].file}`);
const diag = result.files[0].diagnostics.find((d) => d.rule === 'duplicate-import');
assert(diag, 'should report duplicate-import');
assert(diag.severity === 'error', `duplicate-import severity must be error, got ${diag.severity}`);
assert(diag.fixable === true, 'duplicate-import must be auto-fixable');
});
test('lintFile: canonical shape on a real template', async () => {
const result = await mds.lintFile(
resolve(__dirname, 'prompt-library/personas.mds'),
);
assert(result.version === 1, `lint result version must be 1, got ${result.version}`);
assert(Array.isArray(result.files), 'lintFile result must have files array');
assert(result.truncated === false, 'lintFile result truncated must be false');
for (const f of result.files) {
assert(typeof f.file === 'string' && Array.isArray(f.diagnostics), 'each file entry has file + diagnostics');
}
});
// ─── Tests: source maps (v0.4.0) ─────────────────────────────────
test('compile with sourceMap: version 3 + mappings', () => {
const source = '---\nname: Mapper\n---\n# Hello {{name}}\n\nLine two.\n';
const result = mds.compile(source, { sourceMap: true });
assert(result.kind === 'markdown', 'sourceMap test template is markdown-kind');
assert(result.sourceMap, 'result.sourceMap must be present when sourceMap: true');
assert(result.sourceMap.version === 3, `sourceMap version must be 3, got ${result.sourceMap.version}`);
assert(typeof result.sourceMap.mappings === 'string' && result.sourceMap.mappings.length > 0, 'mappings must be a non-empty string');
assert(Array.isArray(result.sourceMap.sources) && result.sourceMap.sources.length === 1, 'sources must list the single string-source entry');
assert(Array.isArray(result.sourceMap.names), 'names must be an array');
assert(!('sourcesContent' in result.sourceMap), 'sourcesContent must be absent unless requested');
});
test('compile with sourceMap + sourcesContent embeds the source', () => {
const source = '---\nname: Mapper\n---\n# Hello {{name}}\n';
const result = mds.compile(source, { sourceMap: true, sourcesContent: true });
assert(Array.isArray(result.sourceMap.sourcesContent), 'sourcesContent must be present when requested');
assert(result.sourceMap.sourcesContent[0] === source, 'sourcesContent[0] must be the exact original source');
});
test('sourcesContent without sourceMap throws mds::invalid_options', () => {
try {
mds.compile('# Hi\n', { sourcesContent: true });
assert(false, 'should have thrown mds::invalid_options');
} catch (err) {
assert(mds.isMdsError(err), `expected MDS error, got ${err}`);
assert(err.code === 'mds::invalid_options', `expected mds::invalid_options, got ${err.code}`);
}
});
test('messages template: sourceMap degrades to a warning', () => {
const source = '@message user:\nHello!\n@end\n';
const result = mds.compile(source, { sourceMap: true });
assert(result.kind === 'messages', `expected kind==='messages', got ${result.kind}`);
assert(!('sourceMap' in result), 'messages result must not carry a sourceMap');
assert(result.warnings.length > 0, 'requesting a sourceMap on a messages template must surface a warning');
assert(result.warnings.some((w) => w.includes('not supported')), 'warning should explain sourceMap is unsupported for messages templates');
});
// ─── Run all tests ───────────────────────────────────────────────
console.log(`\nRunning ${tests.length} tests...\n`);
for (const { name, fn } of tests) {
try {
await fn();
passed++;
console.log(` PASS ${name}`);
} catch (err) {
failed++;
console.log(` FAIL ${name}: ${err.message}`);
}
}
console.log(`\n${passed} passed, ${failed} failed out of ${tests.length} tests`);
if (failed > 0) process.exit(1);