Get type links working

pull/8452/head
Puru Vijay 3 years ago
parent 4a288a5e33
commit 6899df23ea

@ -12,4 +12,3 @@
.vercel .vercel
examples-data.js examples-data.js
type-info.js type-info.js
.snippets

@ -206,17 +206,6 @@ const bundled_types = await get_bundled_types();
}); });
} }
{
const module = bundled_types.get('svelte/runtime');
if (!module) throw new Error('Could not find svelte/runtime');
modules.push({
name: 'svelte/runtime',
comment: '',
...get_types(module.code, module.ts_source_file.statements)
});
}
{ {
const module = bundled_types.get('svelte/action'); const module = bundled_types.get('svelte/action');
@ -289,18 +278,6 @@ const bundled_types = await get_bundled_types();
}); });
} }
{
const module = bundled_types.get('svelte/internal');
if (!module) throw new Error('Could not find svelte/internal');
modules.push({
name: 'svelte/internal',
comment: '',
...get_types(module.code, module.ts_source_file.statements)
});
}
// const dir = fileURLToPath( // const dir = fileURLToPath(
// new URL('../../../../packages/kit/types/synthetic', import.meta.url).href // new URL('../../../../packages/kit/types/synthetic', import.meta.url).href
// ); // );

@ -1,19 +1,44 @@
import { createShikiHighlighter, renderCodeToHTML, runTwoSlash } from 'shiki-twoslash'; import { modules } from '$lib/generated/type-info';
import { SHIKI_LANGUAGE_MAP, escape, normalizeSlugify, transform } from '../markdown';
import { replace_placeholders } from './render.js';
// import { parse_route_id } from '../../../../../../packages/kit/src/utils/routing.js';
import { createHash } from 'crypto'; import { createHash } from 'crypto';
import fs from 'fs'; import fs from 'fs';
import MagicString from 'magic-string'; import MagicString from 'magic-string';
import { createShikiHighlighter, renderCodeToHTML, runTwoSlash } from 'shiki-twoslash';
import ts from 'typescript'; import ts from 'typescript';
import { SHIKI_LANGUAGE_MAP, escape, normalizeSlugify, slugify, transform } from '../markdown';
import { replace_placeholders } from './render.js';
const FILE_METADATA_REGEX = /(?:<!---\s*file:\s*(.*?)(?:\s*--->)|\/\/\/\s*file:\s*(.*?)(?:$))/i; const METADATA_REGEX = /(?:<!---\s*([\w-]+):\s*(.*?)\s*--->|\/\/\/\s*([\w-]+):\s*(.*))\n/gm;
const snippet_cache = new URL('../../../../.snippets', import.meta.url).pathname; const snippet_cache = new URL('../../../../node_modules/.snippets', import.meta.url).pathname;
if (!fs.existsSync(snippet_cache)) { if (!fs.existsSync(snippet_cache)) {
fs.mkdirSync(snippet_cache, { recursive: true }); fs.mkdirSync(snippet_cache, { recursive: true });
} }
const type_regex = new RegExp(
`(import\\(&apos;svelte&apos;\\)\\.)?\\b(${modules
.flatMap((module) => module.types)
.map((type) => type.name)
.join('|')})\\b`,
'g'
);
const type_links = new Map();
// const slugs = {
// '@sveltejs/kit': 'public-types'
// };
modules.forEach((module) => {
const slug = slugify(module.name);
module.types.forEach((type) => {
const link = `/docs/${slug}#type-${slugify(type.name)}`;
type_links.set(type.name, link);
});
});
console.log(type_links);
/** /**
* @param {import('./types').DocsData} docs_data * @param {import('./types').DocsData} docs_data
* @param {string} slug * @param {string} slug
@ -39,9 +64,11 @@ export async function get_parsed_docs(docs_data, slug) {
hash.update(source + language + current); hash.update(source + language + current);
const digest = hash.digest().toString('base64').replace(/\//g, '-'); const digest = hash.digest().toString('base64').replace(/\//g, '-');
try {
if (fs.existsSync(`${snippet_cache}/${digest}.html`)) { if (fs.existsSync(`${snippet_cache}/${digest}.html`)) {
return fs.readFileSync(`${snippet_cache}/${digest}.html`, 'utf-8'); return fs.readFileSync(`${snippet_cache}/${digest}.html`, 'utf-8');
} }
} catch {}
/** @type {Record<string, string>} */ /** @type {Record<string, string>} */
const options = {}; const options = {};
@ -89,9 +116,6 @@ export async function get_parsed_docs(docs_data, slug) {
try { try {
const injected = []; const injected = [];
// For the snippets that are not proper JS or TS
// if (!source.includes('import')) injected.push('// @errors: 2552 1005 1109 2304');
if (source.includes('svelte')) { if (source.includes('svelte')) {
injected.push( injected.push(
`// @filename: ambient.d.ts`, `// @filename: ambient.d.ts`,
@ -192,18 +216,21 @@ export async function get_parsed_docs(docs_data, slug) {
html = html.replace(/class=('|")/, `class=$1${version_class} `); html = html.replace(/class=('|")/, `class=$1${version_class} `);
} }
// type_regex.lastIndex = 0; type_regex.lastIndex = 0;
console.log(html);
html = html html = html
// .replace(type_regex, (match, prefix, name) => { .replace(type_regex, (match, prefix, name) => {
// if (options.link === 'false' || name === current) { console.log(2);
// // we don't want e.g. RequestHandler to link to RequestHandler if (options.link === 'false' || name === current) {
// return match; // we don't want e.g. RequestHandler to link to RequestHandler
// } return match;
}
// const link = `<a href="${type_links.get(name)}">${name}</a>`; const link = `<a href="${type_links.get(name)}">${name}</a>`;
// return `${prefix || ''}${link}`; return `${prefix || ''}${link}`;
// }) })
.replace( .replace(
/^(\s+)<span class="token comment">([\s\S]+?)<\/span>\n/gm, /^(\s+)<span class="token comment">([\s\S]+?)<\/span>\n/gm,
(match, intro_whitespace, content) => { (match, intro_whitespace, content) => {
@ -229,11 +256,12 @@ export async function get_parsed_docs(docs_data, slug) {
codespan: (text) => { codespan: (text) => {
return ( return (
'<code>' + '<code>' +
text + text.replace(type_regex, (match, prefix, name) => {
// text.replace(type_regex, (match, prefix, name) => { console.log(prefix);
// const link = `<a href="${type_links.get(name)}">${name}</a>`; console.log(1);
// return `${prefix || ''}${link}`; const link = `<a href="${type_links.get(name)}">${name}</a>`;
// }) + return `${prefix || ''}${link}`;
}) +
'</code>' '</code>'
); );
} }
@ -276,9 +304,16 @@ function parse({ body, code, codespan }) {
headings[level] = normalized; headings[level] = normalized;
headings.length = level; headings.length = level;
const slug = normalizeSlugify(raw); const type_heading_match = /^\[TYPE\]:\s+(.+)/.exec(raw);
const slug = normalizeSlugify(type_heading_match ? `type-${type_heading_match[1]}` : raw);
return `<h${level} id="${slug}">${html}<a href="#${slug}" class="permalink"><span class="visually-hidden">permalink</span></a></h${level}>`; return `<h${level} id="${slug}">${html
.replace(/<\/?code>/g, '')
.replace(
/^\[TYPE\]:\s+(.+)/,
'$1'
)}<a href="#${slug}" class="permalink"><span class="visually-hidden">permalink</span></a></h${level}>`;
}, },
code: (source, language) => code(source, language, current), code: (source, language) => code(source, language, current),
codespan codespan
@ -310,7 +345,7 @@ export function generate_ts_from_js(markdown) {
return match.replace('js', 'original-js') + '\n```generated-ts\n' + ts + '\n```'; return match.replace('js', 'original-js') + '\n```generated-ts\n' + ts + '\n```';
}) })
.replaceAll(/```svelte\n([\s\S]+?)\n```/g, (match, code) => { .replaceAll(/```svelte\n([\s\S]+?)\n```/g, (match, code) => {
if (!FILE_METADATA_REGEX.test(code)) { if (!METADATA_REGEX.test(code)) {
// No named file -> assume that the code is not meant to be shown in two versions // No named file -> assume that the code is not meant to be shown in two versions
return match; return match;
} }

@ -51,14 +51,9 @@ export function replace_placeholders(content) {
return `${module.comment}\n\n${module.types return `${module.comment}\n\n${module.types
.map((t) => { .map((t) => {
let children = t.children.map(stringify).join('\n\n'); let children = t.children.map(stringify).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 markdown = `<div class="ts-block">${fence(t.snippet)}` + children + `</div>`; const markdown = `<div class="ts-block">${fence(t.snippet)}` + children + `</div>`;
return `### ${t.name}\n\n${t.comment}\n\n${markdown}\n\n`; return `### [TYPE]: ${t.name}\n\n${t.comment}\n\n${markdown}\n\n`;
}) })
.join('')}`; .join('')}`;
}) })

Loading…
Cancel
Save