shiki-codegen 1.27.0

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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Pine Wu
4
+ Copyright (c) 2023 Anthony Fu <https://github.com/antfu>
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # @shikijs/codegen
2
+
3
+ Codegen for fine-grained Shiki bundles.
4
+
5
+ [Documentation](https://shiki.style/packages/codegen)
6
+
7
+ ## License
8
+
9
+ MIT
package/bin.mjs ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import('./dist/cli.mjs')
package/dist/cli.d.mts ADDED
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/cli.mjs ADDED
@@ -0,0 +1,33 @@
1
+ import fs from 'node:fs/promises';
2
+ import { resolve, dirname } from 'node:path';
3
+ import { cac } from 'cac';
4
+ import { codegen } from './index.mjs';
5
+ import 'shiki/bundle/full';
6
+
7
+ const cli = cac("shiki-codegen");
8
+ cli.command("[path]", "Generate shiki bundle module").option("--themes <themes>", "Themes to include").option("--langs <langs>", "Languages to include").option("--engine <engine>", "Engine to use", { default: "javascript" }).option("--precompiled", "Use precompiled languages", { default: false }).option("--shorthands", "Generate shorthands", { default: true }).option("--format", "Use prettier to format", { default: true }).action(async (path, options) => {
9
+ const output = resolve(path || "shiki.bundle.ts");
10
+ const langs = (Array.isArray(options.langs) ? options.langs.join(",") : options.langs || "").split(",").map((lang) => lang.trim()).filter(Boolean);
11
+ const themes = (Array.isArray(options.themes) ? options.themes.join(",") : options.themes || "").split(",").map((theme) => theme.trim()).filter(Boolean);
12
+ const isTypeScript = !!output.match(/\.[cm]?ts$/i);
13
+ if (!themes.length) {
14
+ throw new Error("No themes specified, use --themes=theme-name to specify themes");
15
+ }
16
+ if (!langs.length) {
17
+ throw new Error("No langs specified, use --langs=lang-name to specify langs");
18
+ }
19
+ const { code } = await codegen({
20
+ langs,
21
+ themes,
22
+ engine: options.engine,
23
+ precompiled: options.precompiled,
24
+ shorthands: options.shorthands,
25
+ format: options.format,
26
+ typescript: isTypeScript
27
+ });
28
+ await fs.mkdir(dirname(output), { recursive: true });
29
+ await fs.writeFile(output, code, "utf-8");
30
+ console.log(`Generated bundle to ${output}`);
31
+ });
32
+ cli.help();
33
+ cli.parse();
@@ -0,0 +1,50 @@
1
+ import { Options } from 'prettier';
2
+ import { BundledLanguage, BundledTheme } from 'shiki';
3
+
4
+ interface ShikiCodegenOptions {
5
+ /**
6
+ * The header to add to the generated code.
7
+ *
8
+ * @default '/* Generate by @shikijs/codegen *\/'
9
+ */
10
+ header?: string;
11
+ /**
12
+ * The languages to bundle.
13
+ */
14
+ langs: readonly BundledLanguage[];
15
+ /**
16
+ * The themes to bundle.
17
+ */
18
+ themes: readonly BundledTheme[];
19
+ /**
20
+ * The engine to use for syntax highlighting.
21
+ */
22
+ engine: 'oniguruma' | 'javascript' | 'javascript-raw';
23
+ /**
24
+ * Use precompiled grammars.
25
+ * Only available when `engine` is set to `javascript` or `javascript-raw`.
26
+ */
27
+ precompiled?: boolean;
28
+ /**
29
+ * Whether to generate TypeScript code.
30
+ *
31
+ * @default true
32
+ */
33
+ typescript?: boolean;
34
+ /**
35
+ * Generate shorthands for the highlighter.
36
+ *
37
+ * @default true
38
+ */
39
+ shorthands?: boolean;
40
+ /**
41
+ * Use Prettier to format the generated code.
42
+ */
43
+ format?: boolean | Options;
44
+ }
45
+ interface ShikiCodegenResult {
46
+ code: string;
47
+ }
48
+ declare function codegen(options: ShikiCodegenOptions): Promise<ShikiCodegenResult>;
49
+
50
+ export { type ShikiCodegenOptions, type ShikiCodegenResult, codegen };
@@ -0,0 +1,50 @@
1
+ import { Options } from 'prettier';
2
+ import { BundledLanguage, BundledTheme } from 'shiki';
3
+
4
+ interface ShikiCodegenOptions {
5
+ /**
6
+ * The header to add to the generated code.
7
+ *
8
+ * @default '/* Generate by @shikijs/codegen *\/'
9
+ */
10
+ header?: string;
11
+ /**
12
+ * The languages to bundle.
13
+ */
14
+ langs: readonly BundledLanguage[];
15
+ /**
16
+ * The themes to bundle.
17
+ */
18
+ themes: readonly BundledTheme[];
19
+ /**
20
+ * The engine to use for syntax highlighting.
21
+ */
22
+ engine: 'oniguruma' | 'javascript' | 'javascript-raw';
23
+ /**
24
+ * Use precompiled grammars.
25
+ * Only available when `engine` is set to `javascript` or `javascript-raw`.
26
+ */
27
+ precompiled?: boolean;
28
+ /**
29
+ * Whether to generate TypeScript code.
30
+ *
31
+ * @default true
32
+ */
33
+ typescript?: boolean;
34
+ /**
35
+ * Generate shorthands for the highlighter.
36
+ *
37
+ * @default true
38
+ */
39
+ shorthands?: boolean;
40
+ /**
41
+ * Use Prettier to format the generated code.
42
+ */
43
+ format?: boolean | Options;
44
+ }
45
+ interface ShikiCodegenResult {
46
+ code: string;
47
+ }
48
+ declare function codegen(options: ShikiCodegenOptions): Promise<ShikiCodegenResult>;
49
+
50
+ export { type ShikiCodegenOptions, type ShikiCodegenResult, codegen };
package/dist/index.mjs ADDED
@@ -0,0 +1,152 @@
1
+ import { bundledLanguagesInfo, bundledThemesInfo } from 'shiki/bundle/full';
2
+
3
+ async function codegen(options) {
4
+ const {
5
+ header = "/* Generate by @shikijs/codegen */",
6
+ typescript = true,
7
+ precompiled = false,
8
+ format: _format = true,
9
+ shorthands = true
10
+ } = options;
11
+ const ts = (code2) => typescript ? code2 : "";
12
+ if (precompiled && options.engine !== "javascript" && options.engine !== "javascript-raw")
13
+ throw new Error("Precompiled grammars are only available when using the JavaScript engine");
14
+ const langs = options.langs.map((lang) => {
15
+ const info = bundledLanguagesInfo.find((i) => i.id === lang || i.aliases?.includes(lang));
16
+ if (!info)
17
+ throw new Error(`Language ${lang} not found`);
18
+ return info;
19
+ });
20
+ const themes = options.themes.map((theme) => {
21
+ const info = bundledThemesInfo.find((i) => i.id === theme);
22
+ if (!info)
23
+ throw new Error(`Theme ${theme} not found`);
24
+ return info;
25
+ });
26
+ const langsCode = `{
27
+ ${langs.flatMap((lang) => {
28
+ const ids = [lang.id, ...lang.aliases || []];
29
+ return ids.map((id) => {
30
+ return `${JSON.stringify(id)}: () => import('@shikijs/${precompiled ? "langs-precompiled" : "langs"}/${lang.id}'),
31
+ `;
32
+ });
33
+ }).join("")}}`;
34
+ const themesCode = `{
35
+ ${themes.map((theme) => {
36
+ return `${JSON.stringify(theme.id)}: () => import('@shikijs/themes/${theme.id}'),
37
+ `;
38
+ }).join("")}}`;
39
+ const typeImports = {
40
+ "@shikijs/types": ["HighlighterGeneric", "DynamicImportThemeRegistration", "DynamicImportLanguageRegistration"]
41
+ };
42
+ const imports = {
43
+ "@shikijs/core": ["createdBundledHighlighter"]
44
+ };
45
+ const lines = [
46
+ ""
47
+ ];
48
+ const exports = [];
49
+ const typeExports = [];
50
+ if (typescript) {
51
+ lines.push(
52
+ "",
53
+ `type BundledLanguage = ${langs.flatMap((lang) => [lang.id, ...lang.aliases || []]).map((lang) => `'${lang}'`).join(" | ")}`,
54
+ `type BundledTheme = ${themes.map((theme) => `'${theme.id}'`).join(" | ")}`,
55
+ `type Highlighter = HighlighterGeneric<BundledLanguage, BundledTheme>`,
56
+ ""
57
+ );
58
+ typeExports.push("BundledLanguage", "BundledTheme", "Highlighter");
59
+ }
60
+ lines.push(
61
+ "",
62
+ `const bundledLanguages = ${langsCode}${ts(" as Record<BundledLanguage, DynamicImportLanguageRegistration>")}`,
63
+ "",
64
+ `const bundledThemes = ${themesCode}${ts(" as Record<BundledTheme, DynamicImportThemeRegistration>")}`,
65
+ ""
66
+ );
67
+ exports.push("bundledLanguages", "bundledThemes");
68
+ let engine;
69
+ if (options.engine === "javascript") {
70
+ imports["@shikijs/engine-javascript"] = ["createJavaScriptRegexEngine"];
71
+ engine = "createJavaScriptRegexEngine()";
72
+ } else if (options.engine === "javascript-raw") {
73
+ imports["@shikijs/engine-javascript/raw"] = ["createJavaScriptRawEngine"];
74
+ engine = "createJavaScriptRawEngine()";
75
+ } else {
76
+ imports["@shikijs/engine-oniguruma"] = ["createOnigurumaEngine"];
77
+ engine = "createOnigurumaEngine(import('shiki/wasm'))";
78
+ }
79
+ lines.push(
80
+ "",
81
+ `const createHighlighter = /* @__PURE__ */ createdBundledHighlighter${ts("<BundledLanguage, BundledTheme>")}({`,
82
+ ` langs: bundledLanguages,`,
83
+ ` themes: bundledThemes,`,
84
+ ` engine: () => ${engine}`,
85
+ `})`
86
+ );
87
+ exports.push("createHighlighter");
88
+ if (shorthands) {
89
+ imports["@shikijs/core"].push("createSingletonShorthands");
90
+ const shorthandFunctions = [
91
+ "codeToHtml",
92
+ "codeToHast",
93
+ "codeToTokensBase",
94
+ "codeToTokens",
95
+ "codeToTokensWithThemes",
96
+ "getSingletonHighlighter",
97
+ "getLastGrammarState"
98
+ ];
99
+ lines.push(
100
+ "",
101
+ `const { ${shorthandFunctions.join(", ")} } = /* @__PURE__ */ createSingletonShorthands${ts("<BundledLanguage,BundledTheme>")}(createHighlighter)`
102
+ );
103
+ exports.push(
104
+ ...shorthandFunctions
105
+ );
106
+ }
107
+ lines.unshift(
108
+ Object.entries(imports).map(
109
+ ([module, imports2]) => {
110
+ return `import { ${imports2.sort().join(", ")} } from '${module}'`;
111
+ }
112
+ ).join("\n")
113
+ );
114
+ if (typescript) {
115
+ lines.unshift(
116
+ Object.entries(typeImports).map(
117
+ ([module, types]) => {
118
+ return `import type { ${types.sort().join(", ")} } from '${module}'`;
119
+ }
120
+ ).join("\n")
121
+ );
122
+ }
123
+ lines.push(
124
+ "",
125
+ `export { ${exports.sort().join(", ")} }`
126
+ );
127
+ if (typescript) {
128
+ lines.push(
129
+ `export type { ${typeExports.sort().join(", ")} }`
130
+ );
131
+ }
132
+ lines.unshift(header);
133
+ let code = lines.join("\n");
134
+ if (_format) {
135
+ const { format } = await import('prettier');
136
+ const prettierOptions = {
137
+ parser: typescript ? "typescript" : "babel",
138
+ semi: false,
139
+ tabWidth: 2,
140
+ useTabs: false,
141
+ singleQuote: true,
142
+ trailingComma: "all",
143
+ ..._format === true ? {} : _format
144
+ };
145
+ code = await format(code, prettierOptions);
146
+ }
147
+ return {
148
+ code
149
+ };
150
+ }
151
+
152
+ export { codegen };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "shiki-codegen",
3
+ "type": "module",
4
+ "version": "1.27.0",
5
+ "description": "Codegen for fine-grained Shiki bundles.",
6
+ "author": "Anthony Fu <anthonyfu117@hotmail.com>",
7
+ "license": "MIT",
8
+ "homepage": "https://github.com/shikijs/shiki#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/shikijs/shiki.git",
12
+ "directory": "packages/codegen"
13
+ },
14
+ "bugs": "https://github.com/shikijs/shiki/issues",
15
+ "keywords": [
16
+ "shiki",
17
+ "codegen"
18
+ ],
19
+ "sideEffects": false,
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.mts",
23
+ "default": "./dist/index.mjs"
24
+ },
25
+ "./cli": {
26
+ "types": "./dist/cli.d.mts",
27
+ "default": "./dist/cli.mjs"
28
+ }
29
+ },
30
+ "main": "./dist/index.mjs",
31
+ "module": "./dist/index.mjs",
32
+ "types": "./dist/index.d.mts",
33
+ "bin": {
34
+ "shiki-codegen": "bin.mjs"
35
+ },
36
+ "files": [
37
+ "bin.mjs",
38
+ "dist"
39
+ ],
40
+ "dependencies": {
41
+ "cac": "^6.7.14",
42
+ "prettier": "^3.4.2",
43
+ "shiki": "1.27.0"
44
+ },
45
+ "scripts": {
46
+ "build": "unbuild",
47
+ "dev": "unbuild --stub",
48
+ "test": "vitest"
49
+ }
50
+ }