-
Notifications
You must be signed in to change notification settings - Fork 62
/
renderer.js
1087 lines (923 loc) · 30.2 KB
/
renderer.js
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import MagicString from 'magic-string';
import { createHash } from 'node:crypto';
import { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import ts from 'typescript';
import { SHIKI_LANGUAGE_MAP, escape, normalizeSlugify, transform } from './utils.js';
/**
* @typedef {Record<MetadataKeys, string | boolean | number | null>} SnippetOptions
* @typedef {(filename: string, content: string, language: string, options: SnippetOptions) => string} TwoslashBanner
* @typedef {'file' | 'link' | 'copy'} MetadataKeys
*/
// Supports js, svelte, yaml files
const METADATA_REGEX =
/(?:<!---\s*|\/\/\/\s*|###\s*)(?<key>file|link|copy):\s*(?<value>.*?)(?:\s*--->|$)\n/gm;
/** @type {Map<string, string>} */
const CACHE_MAP = new Map();
/** @type {import('shiki-twoslash')} */
let twoslash_module;
/** @type {import('prettier')} */
let prettier_module;
/**
* A super markdown renderer function. Renders svelte and kit docs specific specific markdown code to html.
*
* - Syntax Highlighting -> shikiJS with `css-variables` theme.
* - TS hover snippets -> shiki-twoslash. JS and TS code snippets(other than d.ts) are run through twoslash.
* - JS -> TS conversion -> JS snippets starting with `/// file: some_file.js` are converted to TS if possible. Same for Svelte snippets starting with `<!--- file: some_file.svelte --->`. Notice there's an additional dash(-) to the opening and closing comment tag.
* - Type links -> Type names are converted to links to the type's documentation page.
* - Snippet caching -> To avoid slowing down initial page render time, code snippets are cached in the nearest `node_modules/.snippets` folder. This is done by hashing the code snippet with SHA256 algo and storing the final rendered output in a file named the hash.
*
* ## Special syntax
*
* ### file
*
* Provided as a comment at top of a code snippet. If inside a JS code snippet, expects a triple slash comment as the first line(/// file:)
*
* ````md
* ```js
* /// file: some_file.js
* const a = 1;
* ```
* ````
*
* ---
*
* For svelte snippets, we use HTML comments, with an additional dash at the opening and end
*
* ````md
* ```svelte
* <!--- file: some_file.svelte --->
* <script>
* const a = 1;
* </script>
*
* Hello {a}
* ```
* ````
*
* ---
*
* ### link
*
* Provided at the top. Should be under `file:` if present.
*
* This doesn't allow the imported members from `svelte/*` or `@sveltejs/kit` to be linked, as in they are not wrapped with an `<a href="#type-onmount"></a>`.
*
* ````md
* ```js
* /// file: some_file.js
* /// link: false
* import { onMount } from 'svelte';
*
* onMount(() => {
* console.log('mounted');
* });
* ```
* ````
*
* ---
*
* ### copy
*
* Explicitly specify whether the code snippet should have a copy button on it.
* By default, snippets with a `file` flag will get a copy button.
* Passing `copy: false` will take higher precedence
*
* ````md
* ```js
* /// file: some_file.js
* /// copy: false
* const a = 1;
*
* console.log(a);
* ```
* ````
*
* @param {string} filename
* @param {string} body
* @param {object} options
* @param {TwoslashBanner} [options.twoslashBanner] - A function that returns a string to be prepended to the code snippet before running the code with twoslash. Helps in adding imports from svelte or sveltekit or whichever modules are being globally referenced in all or most code snippets.
* @param {import('.').Modules} [options.modules] Module info generated from type-gen script. Used to create type links and type information blocks
* @param {boolean} [options.cacheCodeSnippets] Whether to cache code snippets or not. Defaults to true.
* @param {Parameters<typeof create_type_links>['1']} [options.resolveTypeLinks] Resolve types into its slugs(used on the page itself).
*/
export async function render_content_markdown(
filename,
body,
{ twoslashBanner, modules = [], cacheCodeSnippets = true, resolveTypeLinks } = {}
) {
twoslash_module ??= await import('shiki-twoslash');
prettier_module ??= await import('prettier');
const highlighter = await twoslash_module.createShikiHighlighter({ theme: 'css-variables' });
const { type_links, type_regex } = create_type_links(modules, resolveTypeLinks);
const SNIPPET_CACHE = await create_snippet_cache(cacheCodeSnippets);
return parse({
body: await generate_ts_from_js(await replace_export_type_placeholders(body, modules)),
type_links,
code: (source, language, current) => {
const cached_snippet = SNIPPET_CACHE.get(source + language + current);
if (cached_snippet.code) return cached_snippet.code;
/** @type {SnippetOptions} */
const options = { file: null, link: null, copy: true };
source = collect_options(source, options);
source = adjust_tab_indentation(source, language);
let version_class = '';
if (/^generated-(ts|svelte)$/.test(language)) {
language = language.replace('generated-', '');
version_class = 'ts-version';
} else if (/^original-(js|svelte)$/.test(language)) {
language = language.replace('original-', '');
version_class = 'js-version';
}
let html = syntax_highlight({
filename,
highlighter,
language,
source,
twoslashBanner,
options
});
if (options.file) {
html = `<div class="code-block"><span class="filename">${options.file}</span>${html}</div>`;
}
if (options.copy) {
html = html.replace(/class=('|")/, `class=$1copy-code-block `);
}
if (version_class) {
html = html.replace(/class=('|")/, `class=$1${version_class} `);
}
if (type_regex) {
type_regex.lastIndex = 0;
html = html.replace(type_regex, (match, prefix, name, pos, str) => {
const char_after = str.slice(pos + match.length, pos + match.length + 1);
if (!options.link || name === current || /(\$|\d|\w)/.test(char_after)) {
// we don't want e.g. RequestHandler to link to RequestHandler
return match;
}
const link = type_links?.get(name)
? `<a href="${type_links.get(name)?.relativeURL}">${name}</a>`
: '';
return `${prefix || ''}${link}`;
});
}
html = indent_multiline_comments(html);
html = html.replace(/\/\*…\*\//g, '…');
// Save everything locally now
SNIPPET_CACHE.save(cached_snippet?.uid, html);
return html;
},
codespan: (text) => {
return (
'<code>' +
(type_regex
? text.replace(type_regex, (_, prefix, name) => {
const link = type_links?.get(name)
? `<a href="${type_links.get(name)?.relativeURL}">${name}</a>`
: '';
return `${prefix || ''}${link}`;
})
: text) +
'</code>'
);
}
});
}
/**
* @param {{
* body: string;
* type_links: Map<string, { relativeURL: string; slug: string; page: string}> | null;
* code: (source: string, language: string, current: string) => string;
* codespan: (source: string) => string;
* }} opts
*/
async function parse({ body, code, codespan }) {
/** @type {string[]} */
const headings = [];
// this is a bit hacky, but it allows us to prevent type declarations
// from linking to themselves
let current = '';
/** @type {string} */
const content = await transform(body, {
heading(html, level, raw) {
const title = html
.replace(/<\/?code>/g, '')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
current = title;
const normalized = normalizeSlugify(raw);
headings[level - 1] = normalized;
headings.length = level;
const slug = headings.filter(Boolean).join('-');
return `<h${level} id="${slug}">${html.replace(
/<\/?code>/g,
''
)}<a href="#${slug}" class="permalink"><span class="visually-hidden">permalink</span></a></h${level}>`;
},
code: (source, language) => code(source, language ?? 'js', current),
codespan
});
return content;
}
/**
* Pre-render step. Takes in all the code snippets, and replaces them with TS snippets if possible
* May replace the language labels (```js) to custom labels(```generated-ts, ```original-js, ```generated-svelte,```original-svelte)
* @param {string} markdown
*/
async function generate_ts_from_js(markdown) {
markdown = await async_replace(markdown, /```js\n([\s\S]+?)\n```/g, async ([match, code]) => {
if (!code.includes('/// file:')) {
// No named file -> assume that the code is not meant to be shown in two versions
return match;
}
if (code.includes('/// file: svelte.config.js')) {
// svelte.config.js has no TS equivalent
return match;
}
const ts = await convert_to_ts(code);
if (!ts) {
// No changes -> don't show TS version
return match;
}
return match.replace('js', 'original-js') + '\n```generated-ts\n' + ts + '```';
});
markdown = await async_replace(markdown, /```svelte\n([\s\S]+?)\n```/g, async ([match, code]) => {
METADATA_REGEX.lastIndex = 0;
if (!METADATA_REGEX.test(code)) {
// No named file -> assume that the code is not meant to be shown in two versions
return match;
}
// Assumption: no context="module" blocks
const script = code.match(/<script>([\s\S]+?)<\/script>/);
if (!script) return match;
const [outer, inner] = script;
const ts = await convert_to_ts(inner, '\t', '\n');
if (!ts) {
// No changes -> don't show TS version
return match;
}
return (
match.replace('svelte', 'original-svelte') +
'\n```generated-svelte\n' +
code.replace(outer, `<script lang="ts">\n\t${ts.trim()}\n</script>`) +
'\n```'
);
});
return markdown;
}
/** @param {ts.Node} node */
function get_jsdoc(node) {
const { jsDoc } = /** @type {{ jsDoc?: ts.JSDoc[] }} */ (/** @type {*} */ (node));
return jsDoc;
}
/**
* Transforms a JS code block into a TS code block by turning JSDoc into type annotations.
* Due to pragmatism only the cases currently used in the docs are implemented.
* @param {string} js_code
* @param {string} [indent]
* @param {string} [offset]
*/
export async function convert_to_ts(js_code, indent = '', offset = '') {
js_code = js_code
.replaceAll('// @filename: index.js', '// @filename: index.ts')
.replace(/(\/\/\/ .+?\.)js/, '$1ts')
// *\/ appears in some JsDoc comments in d.ts files due to the JSDoc-in-JSDoc problem
.replace(/\*\\\//g, '*/');
const ast = ts.createSourceFile(
'filename.ts',
js_code,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS
);
const code = new MagicString(js_code);
const imports = new Map();
/**
* @param {import('typescript').Node} node
*/
async function walk(node) {
const jsdoc = get_jsdoc(node);
if (jsdoc) {
for (const comment of jsdoc) {
let modified = false;
let count = 0;
for (const tag of comment.tags ?? []) {
if (ts.isJSDocTypeTag(tag)) {
const [name, generics] = await get_type_info(tag);
if (ts.isFunctionDeclaration(node)) {
const is_export = node.modifiers?.some(
(modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword
)
? 'export '
: '';
const is_async = node.modifiers?.some(
(modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword
);
const type = generics !== undefined ? `${name}<${generics}>` : name;
if (node.name && node.body) {
code.overwrite(
node.getStart(),
node.name.getEnd(),
`${is_export ? 'export ' : ''}const ${node.name.getText()}: ${type} = (${
is_async ? 'async ' : ''
}`
);
code.appendLeft(node.body.getStart(), '=> ');
code.appendLeft(node.body.getEnd(), ')');
modified = true;
}
} else if (
ts.isVariableStatement(node) &&
node.declarationList.declarations.length === 1
) {
const variable_statement = node.declarationList.declarations[0];
if (variable_statement.name.getText() === 'actions') {
code.appendLeft(variable_statement.getEnd(), ` satisfies ${name}`);
} else {
code.appendLeft(
variable_statement.name.getEnd(),
`: ${name}${generics ? `<${generics}>` : ''}`
);
}
modified = true;
} else {
throw new Error('Unhandled @type JsDoc->TS conversion: ' + js_code);
}
} else if (ts.isJSDocParameterTag(tag) && ts.isFunctionDeclaration(node)) {
const sanitised_param = tag
.getFullText()
.replace(/\s+/g, '')
.replace(/(^\*|\*$)/g, '');
const [, param_type] = /@param{(.+)}(.+)/.exec(sanitised_param) ?? [];
let param_count = 0;
for (const param of node.parameters) {
if (count !== param_count) {
param_count++;
continue;
}
code.appendLeft(param.getEnd(), `:${param_type}`);
param_count++;
}
modified = true;
}
count++;
}
if (modified) {
code.overwrite(comment.getStart(), comment.getEnd(), '');
}
}
}
for (const child_node of node.getChildren()) {
await walk(child_node);
}
}
await walk(ast);
if (imports.size) {
const import_statements = Array.from(imports.entries())
.map(([from, names]) => {
return `${indent}import type { ${Array.from(names).join(', ')} } from '${from}';`;
})
.join('\n');
const idxOfLastImport = [...ast.statements]
.reverse()
.find((statement) => ts.isImportDeclaration(statement))
?.getEnd();
const insertion_point = Math.max(
idxOfLastImport ? idxOfLastImport + 1 : 0,
js_code.includes('---cut---')
? js_code.indexOf('\n', js_code.indexOf('---cut---')) + 1
: js_code.includes('/// file:')
? js_code.indexOf('\n', js_code.indexOf('/// file:')) + 1
: 0
);
code.appendLeft(insertion_point, offset + import_statements + '\n');
}
let transformed = await prettier_module.format(code.toString(), {
printWidth: 100,
parser: 'typescript',
useTabs: true,
singleQuote: true
});
// Indent transformed's each line by 2
transformed = transformed
.split('\n')
.map((line) => indent.repeat(1) + line)
.join('\n');
return transformed === js_code ? undefined : transformed.replace(/\n\s*\n\s*\n/g, '\n\n');
/** @param {ts.JSDocTypeTag | ts.JSDocParameterTag} tag */
async function get_type_info(tag) {
const type_text = tag.typeExpression?.getText();
let name = type_text?.slice(1, -1); // remove { }
const single_line_name = (
await prettier_module.format(name ?? '', {
printWidth: 1000,
parser: 'typescript',
semi: false,
singleQuote: true
})
).replace('\n', '');
const import_match = /import\('(.+?)'\)\.(\w+)(?:<(.+)>)?$/s.exec(single_line_name);
if (import_match) {
const [, from, _name, generics] = import_match;
name = _name;
const existing = imports.get(from);
if (existing) {
existing.add(name);
} else {
imports.set(from, new Set([name]));
}
if (generics !== undefined) {
return [
name,
generics
.replaceAll('*', '') // get rid of JSDoc asterisks
.replace(' }>', '}>') // unindent closing brace
];
}
}
return [name];
}
}
/**
* Replace module/export information placeholders in the docs.
* @param {string} content
* @param {import('.').Modules} modules
*/
export async function replace_export_type_placeholders(content, modules) {
const REGEXES = {
EXPANDED_TYPES: /> EXPANDED_TYPES: (.+?)#(.+)$/gm,
TYPES: /> TYPES: (.+?)(?:#(.+))?$/gm,
EXPORT_SNIPPET: /> EXPORT_SNIPPET: (.+?)#(.+)?$/gm,
MODULES: /> MODULES/g, //! /g is VERY IMPORTANT, OR WILL CAUSE INFINITE LOOP
EXPORTS: /> EXPORTS: (.+)/
};
if (!modules || modules.length === 0) {
return content
.replace(REGEXES.EXPANDED_TYPES, '')
.replace(REGEXES.TYPES, '')
.replace(REGEXES.EXPORT_SNIPPET, '')
.replace(REGEXES.MODULES, '')
.replace(REGEXES.EXPORTS, '');
}
content = await async_replace(content, REGEXES.EXPANDED_TYPES, async ([_, name, id]) => {
const module = modules.find((module) => module.name === name);
if (!module) throw new Error(`Could not find module ${name}`);
if (!module.types) return '';
const type = module.types.find((t) => t.name === id);
if (!type) return '';
return (
type.comment +
type.children
?.map((child) => {
let section = `### ${child.name}`;
if (child.bullets) {
section += `\n\n<div class="ts-block-property-bullets">\n\n${child.bullets.join(
'\n'
)}\n\n</div>`;
}
section += `\n\n${child.comment}`;
if (child.children) {
section += `\n\n<div class="ts-block-property-children">\n\n${child.children
.map((v) => stringify(v))
.join('\n')}\n\n</div>`;
}
return section;
})
.join('\n\n')
);
});
content = await async_replace(content, REGEXES.TYPES, async ([_, name, id]) => {
const module = modules.find((module) => module.name === name);
if (!module) throw new Error(`Could not find module ${name}`);
if (!module.types) return '';
if (id) {
const type = module.types.find((t) => t.name === id);
if (!type) return '';
return (
`<div class="ts-block">${fence(type.snippet, 'dts')}` +
type.children?.map((v) => stringify(v)).join('\n\n') +
`</div>`
);
}
return `${module.comment}\n\n${(
await Promise.all(
module.types.map(async (t) => {
let children = t.children?.map((val) => stringify(val, 'dts')).join('\n\n');
if (t.name === 'Config' || t.name === 'KitConfig') {
// special case — we want these to be on a separate page
children =
'<div class="ts-block-property-details">\n\nSee the [configuration reference](/docs/configuration) for details.</div>';
}
const deprecated = t.deprecated
? ` <blockquote class="tag deprecated">${await transform(t.deprecated)}</blockquote>`
: '';
const markdown = `<div class="ts-block">${fence(t.snippet, 'dts')}` + children + `</div>`;
return `### ${t.name}\n\n${deprecated}\n\n${t.comment ?? ''}\n\n${markdown}\n\n`;
})
)
).join('')}`;
});
content = await async_replace(content, REGEXES.EXPORT_SNIPPET, async ([_, name, id]) => {
const module = modules.find((module) => module.name === name);
if (!module) throw new Error(`Could not find module ${name} for EXPORT_SNIPPET clause`);
if (!id) {
throw new Error(`id is required for module ${name}`);
}
const exported = module.exports?.filter((t) => t.name === id);
return (
exported
?.map((exportVal) => `<div class="ts-block">${fence(exportVal.snippet, 'dts')}</div>`)
.join('\n\n') ?? ''
);
});
content = await async_replace(content, REGEXES.MODULES, async () => {
return modules
.map((module) => {
if (!module.exports) return;
if (module.exports.length === 0 && !module.exempt) return '';
let import_block = '';
if (module.exports.length > 0) {
// deduplication is necessary for now, because of `error()` overload
const exports = Array.from(new Set(module.exports?.map((x) => x.name)));
let declaration = `import { ${exports.join(', ')} } from '${module.name}';`;
if (declaration.length > 80) {
declaration = `import {\n\t${exports.join(',\n\t')}\n} from '${module.name}';`;
}
import_block = fence(declaration, 'js');
}
return `## ${module.name}\n\n${import_block}\n\n${module.comment}\n\n${module.exports
.map((type) => {
const markdown =
`<div class="ts-block">${fence(type.snippet)}` +
type.children?.map((v) => stringify(v)).join('\n\n') +
`</div>`;
return `### ${type.name}\n\n${type.comment}\n\n${markdown}`;
})
.join('\n\n')}`;
})
.join('\n\n');
});
content = await async_replace(content, REGEXES.EXPORTS, async ([_, name]) => {
const module = modules.find((module) => module.name === name);
if (!module) throw new Error(`Could not find module ${name} for EXPORTS: clause`);
if (!module.exports) return '';
if (module.exports.length === 0 && !module.exempt) return '';
let import_block = '';
if (module.exports.length > 0) {
// deduplication is necessary for now, because of `error()` overload
const exports = Array.from(new Set(module.exports.map((x) => x.name)));
let declaration = `import { ${exports.join(', ')} } from '${module.name}';`;
if (declaration.length > 80) {
declaration = `import {\n\t${exports.join(',\n\t')}\n} from '${module.name}';`;
}
import_block = fence(declaration, 'js');
}
return `${import_block}\n\n${module.comment}\n\n${module.exports
.map((type) => {
const markdown =
`<div class="ts-block">${fence(type.snippet, 'dts')}` +
type.children?.map((val) => stringify(val, 'dts')).join('\n\n') +
`</div>`;
return `### ${type.name}\n\n${type.comment}\n\n${markdown}`;
})
.join('\n\n')}`;
});
return content;
}
/**
* @param {string} code
* @param {keyof typeof import('./utils').SHIKI_LANGUAGE_MAP} lang
*/
function fence(code, lang = 'ts') {
return (
'\n\n```' +
lang +
'\n' +
(['js', 'ts'].includes(lang) ? '// @noErrors\n' : '') +
code +
'\n```\n\n'
);
}
/**
* Helper function for {@link replace_export_type_placeholders}. Renders specifiv members to their markdown/html representation.
* @param {import('.').ModuleChild} member
* @param {keyof typeof import('./utils.js').SHIKI_LANGUAGE_MAP} [lang]
* @returns {string}
*/
function stringify(member, lang = 'ts') {
if (!member) return '';
const bullet_block =
(member.bullets?.length ?? 0) > 0
? `\n\n<div class="ts-block-property-bullets">\n\n${member.bullets?.join('\n')}</div>`
: '';
const child_block =
(member.children?.length ?? 0) > 0
? `\n\n<div class="ts-block-property-children">${member.children
?.map((val) => stringify(val, lang))
.join('\n')}</div>`
: '';
return (
`<div class="ts-block-property">${fence(member.snippet, lang)}` +
`<div class="ts-block-property-details">\n\n` +
bullet_block +
'\n\n' +
member.comment
.replace(/\/\/\/ type: (.+)/g, '/** @type {$1} */')
.replace(/^( )+/gm, (match, spaces) => {
return '\t'.repeat(match.length / 2);
}) +
child_block +
'\n</div></div>'
);
}
/**
* @param {string} start_path
* @return {Promise<string | null>}
*/
async function find_nearest_node_modules(start_path) {
try {
if (await stat(path.join(start_path, 'node_modules'))) {
return path.resolve(start_path, 'node_modules');
}
} catch {
const parentDir = path.dirname(start_path);
if (start_path === parentDir) return null;
return find_nearest_node_modules(parentDir);
}
return null;
}
/**
* Utility function to work with code snippet caching.
*
* @example
*
* ```js
* const SNIPPETS_CACHE = create_snippet_cache(true);
*
* const { uid, code } = SNIPPETS_CACHE.get(source);
*
* // Later to save the code to the cache
* SNIPPETS_CACHE.save(uid, processed_code);
* ```
*
* @param {boolean} should
*/
async function create_snippet_cache(should) {
const snippet_cache = (await find_nearest_node_modules(import.meta.url)) + '/.snippets';
// No local cache exists yet
if (!CACHE_MAP.size && should) {
try {
await mkdir(snippet_cache, { recursive: true });
} catch {}
// Read all the cache files and populate the CACHE_MAP
try {
const files = await readdir(snippet_cache);
const file_contents = await Promise.all(
files.map(async (file) => ({
file,
content: await readFile(`${snippet_cache}/${file}`, 'utf-8')
}))
);
for (const { file, content } of file_contents) {
const uid = file.replace(/\.html$/, '');
CACHE_MAP.set(uid, content);
}
} catch {}
}
/** @param {string} source */
function get(source) {
if (!should) return { uid: null, code: null };
const hash = createHash('sha256');
hash.update(source);
const digest = hash.digest().toString('base64').replace(/\//g, '-');
try {
return {
uid: digest,
code: CACHE_MAP.get(digest)
};
} catch {}
return { uid: digest, code: null };
}
/**
* @param {string | null} uid
* @param {string} content
*/
function save(uid, content) {
if (!should || !uid) return;
CACHE_MAP.set(uid, content);
writeFile(`${snippet_cache}/${uid}.html`, content);
}
return { get, save };
}
/**
* @param {import('.').Modules | undefined} modules
* @param {((module_name: string, type_name: string) => { slug: string; page: string; }) | undefined} resolve_link
* @returns {{ type_regex: RegExp | null, type_links: Map<string, { slug: string; page: string; relativeURL: string }> | null }}
*/
function create_type_links(modules, resolve_link) {
if (!modules || modules.length === 0 || !resolve_link)
return { type_regex: null, type_links: null };
const type_regex = new RegExp(
`(import\\('(?:svelte|@sveltejs\\/kit)'\\)\\.)?\\b(${modules
.flatMap((module) => module.types)
.map((type) => type?.name)
.join('|')})\\b`,
'g'
);
/** @type {Map<string, { slug: string; page: string; relativeURL: string; }>} */
const type_links = new Map();
for (const module of modules) {
if (!module || !module.name) continue;
for (const type of module.types ?? []) {
const link = resolve_link(module.name, type.name);
type_links.set(type.name, { ...link, relativeURL: link.page + '#' + link.slug });
}
}
return { type_regex, type_links };
}
/**
* @param {string} source
* @param {SnippetOptions} options
*/
function collect_options(source, options) {
METADATA_REGEX.lastIndex = 0;
let copy_value = 'true';
source = source.replace(METADATA_REGEX, (_, key, value) => {
if (key === 'copy') {
copy_value = value;
}
options[/** @type {MetadataKeys} */ (key)] = value;
return '';
});
options.link = options.link === 'true';
options.copy = copy_value === 'true' || (options.file && copy_value !== 'false');
return source;
}
/**
* @param {string} source
* @param {string} language
*/
function adjust_tab_indentation(source, language) {
return (
source
// TODO: what exactly is going on here? The regex finds spaces and replaces them with spaces again?
.replace(/^([\-\+])?((?: )+)/gm, (match, prefix = '', spaces) => {
if ((prefix && language !== 'diff') || language === 'yaml') return match;
// for no good reason at all, marked replaces tabs with spaces
let i = 0;
let tabs = '';
for (; i < spaces.length; i += 4) {
tabs += '\t';
}
tabs += ' '.repeat(i % 4);
return prefix + tabs;
})
.replace(/\*\\\//g, '*/')
);
}
/** @param {string} html */
function replace_blank_lines(html) {
// preserve blank lines in output (maybe there's a more correct way to do this?)
return html.replaceAll(/<div class='line'>( )?<\/div>/g, '<div class="line">\n</div>');
}
/**
* @param {{
* source: string,
* filename: string,
* language: string,
* highlighter: ReturnType<import('shiki-twoslash').createShikiHighlighter>
* twoslashBanner?: TwoslashBanner
* options: SnippetOptions
* }} param0
*/
function syntax_highlight({ source, filename, language, highlighter, twoslashBanner, options }) {
let html = '';
if (/^(dts|yaml|yml)/.test(language)) {
html = replace_blank_lines(
twoslash_module.renderCodeToHTML(
source,
language === 'dts' ? 'ts' : language,
{ twoslash: false },
{ themeName: 'css-variables' },
highlighter
)
);
} else if (/^(js|ts)/.test(language)) {
try {
const banner = twoslashBanner?.(filename, source, language, options);
if (banner) {
if (source.includes('// @filename:')) {
source = source.replace('// @filename:', `${banner}\n\n// @filename:`);
} else {
source = source.replace(
/^(?!\/\/ @)/m,
`${banner}\n\n// @filename: index.${language}\n` + ` // ---cut---\n`
);
}
}
const twoslash = twoslash_module.runTwoSlash(source, language, {
defaultCompilerOptions: {
allowJs: true,
checkJs: true,
target: ts.ScriptTarget.ES2022,
types: ['svelte', '@sveltejs/kit']
}
});
html = twoslash_module.renderCodeToHTML(
twoslash.code,
'ts',
{ twoslash: true },
// @ts-ignore Why shiki-twoslash requires a theme name?
{},
highlighter,
twoslash
);
} catch (e) {
console.error(`Error compiling snippet in ${filename}`);
// @ts-ignore
console.error(e.code);
throw e;
}
// we need to be able to inject the LSP attributes as HTML, not text, so we
// turn < into &lt;
html = html.replace(
/<data-lsp lsp='([^']*)'([^>]*)>(\w+)<\/data-lsp>/g,
(_, lsp, attrs, name) => {
if (!lsp) return name;
return `<data-lsp lsp='${lsp.replace(/&/g, '&')}'${attrs}>${name}</data-lsp>`;
}
);