@shadow-js/vite 0.3.0 → 1.0.1
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/CHANGELOG.md +18 -0
- package/LICENSE +2 -2
- package/README.md +123 -236
- package/dist/dev/index.d.ts +98 -0
- package/dist/dev/index.js +143 -0
- package/dist/dev/index.js.map +1 -0
- package/dist/dev/mdx.d.ts +95 -0
- package/dist/dev/mdx.js +213 -0
- package/dist/dev/mdx.js.map +1 -0
- package/dist/mdx-env.d.ts +26 -0
- package/dist/prod/index.js +2 -0
- package/dist/prod/index.js.map +1 -0
- package/dist/prod/mdx.js +2 -0
- package/dist/prod/mdx.js.map +1 -0
- package/package.json +68 -45
- package/dist/index.cjs +0 -59
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -63
- package/dist/index.d.ts +0 -63
- package/dist/index.js +0 -57
- package/dist/index.js.map +0 -1
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { CompileError, compile, getBackend, validatePlugins } from "@shadow-js/compiler";
|
|
2
|
+
import { compile as compile$1 } from "@shadow-js/compiler/javascript";
|
|
3
|
+
import * as vite from "vite";
|
|
4
|
+
// src/index.ts
|
|
5
|
+
const DEFAULT_INCLUDE = /\.[cm]?[jt]sx$/;
|
|
6
|
+
const DEFAULT_EXCLUDE = /[\\/]node_modules[\\/]/;
|
|
7
|
+
/**
|
|
8
|
+
* Plain modules the compiler also reads, when they call `useStore`: a single-value `useStore(...)`
|
|
9
|
+
* there becomes the cell path (see the compiler's store-cells pass). Other plain modules are untouched.
|
|
10
|
+
*/
|
|
11
|
+
const PLAIN_MODULE = /\.[cm]?[jt]s$/;
|
|
12
|
+
/**
|
|
13
|
+
* The same pattern without the `g` and `y` flags. `test()` on a global or sticky pattern starts at the `lastIndex` the
|
|
14
|
+
* previous call left, so the same file would match on one call and not on the next.
|
|
15
|
+
*/
|
|
16
|
+
function stateless(pattern) {
|
|
17
|
+
return pattern.global || pattern.sticky ? new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, "")) : pattern;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* True when this Vite transforms with Oxc (Vite 8 and later, and the Rolldown builds of Vite 7); Vite 7 transforms with
|
|
21
|
+
* esbuild. Found by what the module exports: only a Rolldown based Vite exports `rolldownVersion`.
|
|
22
|
+
*/
|
|
23
|
+
const transformsWithOxc = "rolldownVersion" in vite;
|
|
24
|
+
/** The JSX runtime setting, under the key this Vite's transformer reads (`oxc` on Vite 8, `esbuild` on Vite 7). */
|
|
25
|
+
function jsxConfig() {
|
|
26
|
+
return transformsWithOxc ? { oxc: { jsx: {
|
|
27
|
+
runtime: "automatic",
|
|
28
|
+
importSource: "@shadow-js/web"
|
|
29
|
+
} } } : { esbuild: {
|
|
30
|
+
jsx: "automatic",
|
|
31
|
+
jsxImportSource: "@shadow-js/web"
|
|
32
|
+
} };
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Creates the Vite plugin that compiles a ShadowJS app's JSX and `useStore` calls with
|
|
36
|
+
* `@shadow-js/compiler`. Add it to the Vite config of every ShadowJS app: it runs before Vite's own
|
|
37
|
+
* TypeScript and JSX handling, so Vite never sees JSX. SSR builds get the server target. It also
|
|
38
|
+
* sets the ShadowJS JSX import source and dedupes `@shadow-js/core` and `@shadow-js/web`. A compile
|
|
39
|
+
* error is reported to Vite with its file, line and column.
|
|
40
|
+
* @param options Include and exclude filters, the runtime module, the dev, HMR and test switches, and
|
|
41
|
+
* the compiler plugins.
|
|
42
|
+
* @returns A Vite plugin named `shadowjs` that runs with `enforce: "pre"`.
|
|
43
|
+
* @throws {TypeError} When `include` or `exclude` is not a `RegExp`, `moduleName` is not a non-empty string, or `plugins` is
|
|
44
|
+
* not a list of valid compiler plugins (a member without a unique `name` or a `transform` function, for example), naming the
|
|
45
|
+
* option. The `transform` hook rethrows any error that is not a `CompileError`, which points at a compiler bug. A `CompileError` goes through Vite's `this.error`
|
|
46
|
+
* instead, which fails the build with the file and position.
|
|
47
|
+
* @example
|
|
48
|
+
* // vite.config.ts
|
|
49
|
+
* import { shadow } from "@shadow-js/vite"; // the default export is the same function
|
|
50
|
+
* export default { plugins: [shadow()] };
|
|
51
|
+
* @see ShadowPluginOptions
|
|
52
|
+
* @since 1.0.0
|
|
53
|
+
*/
|
|
54
|
+
function shadow(options = {}) {
|
|
55
|
+
for (const name of ["include", "exclude"]) {
|
|
56
|
+
const value = options[name];
|
|
57
|
+
if (value !== void 0 && !(value instanceof RegExp)) throw new TypeError(`shadow(): "${name}" must be a RegExp (got ${typeof value}).`);
|
|
58
|
+
}
|
|
59
|
+
if (options.moduleName !== void 0 && (typeof options.moduleName !== "string" || options.moduleName === "")) throw new TypeError("shadow(): \"moduleName\" must be a non-empty string.");
|
|
60
|
+
if (options.compiler !== void 0 && options.compiler !== "auto" && options.compiler !== "javascript" && options.compiler !== "native") throw new TypeError(`shadow(): "compiler" must be "auto", "javascript" or "native" (got ${JSON.stringify(options.compiler)}).`);
|
|
61
|
+
const plugins = options.plugins === void 0 ? [] : validatePlugins(options.plugins, "shadow(): plugins");
|
|
62
|
+
const mode = options.compiler ?? "auto";
|
|
63
|
+
let verified = mode !== "native";
|
|
64
|
+
const requireNative = () => {
|
|
65
|
+
if (verified) return;
|
|
66
|
+
const backend = getBackend();
|
|
67
|
+
if (backend.name === "javascript") throw new Error(`shadow(): compiler: "native" needs the Rust or WebAssembly implementation of @shadow-js/compiler, and only the TypeScript one is available (${backend.notes.join("; ") || "no reason was recorded"}). Install @shadow-js/compiler with its optional dependencies (do not use --omit=optional), or use compiler: "auto". SHADOW_COMPILER_BACKEND=${process.env["SHADOW_COMPILER_BACKEND"] ?? "auto"}.`);
|
|
68
|
+
verified = true;
|
|
69
|
+
};
|
|
70
|
+
const run = mode === "javascript" ? compile$1 : compile;
|
|
71
|
+
const include = stateless(options.include ?? DEFAULT_INCLUDE);
|
|
72
|
+
const exclude = stateless(options.exclude ?? DEFAULT_EXCLUDE);
|
|
73
|
+
let dev = options.dev ?? false;
|
|
74
|
+
let hot = options.hmr !== false;
|
|
75
|
+
return {
|
|
76
|
+
name: "shadowjs",
|
|
77
|
+
enforce: "pre",
|
|
78
|
+
config(userConfig, env) {
|
|
79
|
+
if (options.dev === void 0) dev = env.command === "serve";
|
|
80
|
+
const testing = env.mode === "test" || process.env["VITEST"] !== void 0;
|
|
81
|
+
if (testing && options.hmr === void 0) hot = false;
|
|
82
|
+
const test = userConfig.test;
|
|
83
|
+
const domTests = testing && (options.domTests ?? (test?.environment === "happy-dom" || test?.environment === "jsdom"));
|
|
84
|
+
return {
|
|
85
|
+
envPrefix: ["VITE_", "DUSK_PUBLIC_"],
|
|
86
|
+
...jsxConfig(),
|
|
87
|
+
resolve: {
|
|
88
|
+
dedupe: ["@shadow-js/core", "@shadow-js/web"],
|
|
89
|
+
...domTests ? { conditions: ["browser"] } : {}
|
|
90
|
+
},
|
|
91
|
+
...domTests ? { test: { server: { deps: { inline: [/@shadow-js\//] } } } } : {},
|
|
92
|
+
optimizeDeps: { exclude: ["@shadow-js/core", "@shadow-js/web"] }
|
|
93
|
+
};
|
|
94
|
+
},
|
|
95
|
+
transform(code, id, transformOptions) {
|
|
96
|
+
if (id.startsWith("\0")) return null;
|
|
97
|
+
const file = id.split("?")[0] ?? id;
|
|
98
|
+
if (exclude.test(file)) return null;
|
|
99
|
+
if (!include.test(file) && !(PLAIN_MODULE.test(file) && code.includes("useStore"))) return null;
|
|
100
|
+
const compileOptions = {
|
|
101
|
+
filename: file,
|
|
102
|
+
generate: transformOptions?.ssr === true ? "ssr" : "dom",
|
|
103
|
+
dev,
|
|
104
|
+
autoReactive: options.autoReactive !== false,
|
|
105
|
+
hmr: dev && hot && transformOptions?.ssr !== true
|
|
106
|
+
};
|
|
107
|
+
if (options.moduleName !== void 0) compileOptions.moduleName = options.moduleName;
|
|
108
|
+
if (plugins.length > 0) compileOptions.plugins = plugins;
|
|
109
|
+
const finish = (context, run) => {
|
|
110
|
+
try {
|
|
111
|
+
const result = run(code, compileOptions);
|
|
112
|
+
for (const diagnostic of result.diagnostics) if (diagnostic.severity === "warning") context.warn(diagnostic.message, {
|
|
113
|
+
line: diagnostic.line,
|
|
114
|
+
column: diagnostic.column
|
|
115
|
+
});
|
|
116
|
+
if (!result.transformed) return null;
|
|
117
|
+
return {
|
|
118
|
+
code: result.code,
|
|
119
|
+
map: result.map
|
|
120
|
+
};
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (error instanceof CompileError) {
|
|
123
|
+
const loc = {
|
|
124
|
+
file,
|
|
125
|
+
line: error.diagnostic.line,
|
|
126
|
+
column: error.diagnostic.column
|
|
127
|
+
};
|
|
128
|
+
return context.error(error.message, loc.line === 0 ? void 0 : {
|
|
129
|
+
line: loc.line,
|
|
130
|
+
column: loc.column
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
requireNative();
|
|
137
|
+
return finish(this, run);
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
export { shadow as default, shadow };
|
|
142
|
+
|
|
143
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["compileWithJavaScript"],"sources":["../../src/index.ts"],"sourcesContent":["import {\n CompileError,\n type CompileOptions,\n type CompileResult,\n type CompilerPlugin,\n compile,\n getBackend,\n validatePlugins,\n} from \"@shadow-js/compiler\";\nimport { compile as compileWithJavaScript } from \"@shadow-js/compiler/javascript\";\nimport type { Plugin } from \"vite\";\nimport * as vite from \"vite\";\n\n/**\n * Options of {@link shadow}. Every member is optional: the defaults compile a ShadowJS app for the\n * browser in `vite dev` and `vite build`, and for the server in SSR builds.\n * @see shadow\n * @since 1.0.0\n */\nexport interface ShadowPluginOptions {\n /**\n * Files to compile, matched against the module id without its query string. Plain `.ts` and `.js`\n * modules are compiled as well when they call `useStore`, whatever this is set to, so a\n * single-value `useStore` there takes the cell path. Files that `exclude` matches are never compiled.\n * @default /\\.[cm]?[jt]sx$/ (every `.jsx` and `.tsx` file)\n * A `g` or `y` flag on the pattern is ignored: the pattern is matched from the start of every id.\n */\n include?: RegExp;\n /**\n * Files to skip. It is checked before `include`, so an excluded file is never compiled.\n * @default /[\\\\/]node_modules[\\\\/]/ (any path with a `node_modules` segment)\n */\n exclude?: RegExp;\n /**\n * Module the compiled code imports its runtime helpers from. The HMR runtime is read from\n * `<moduleName>/hmr`.\n * @default \"@shadow-js/web\" (`\"@shadow-js/web/server\"` for SSR transforms)\n */\n moduleName?: string;\n /**\n * Turn a `const` computed from reactive reads (`const double = count() * 2`) into a live value\n * inside components, so it updates without a function or `useMemo`. Set `false` to keep such\n * constants as written.\n * @default true\n */\n autoReactive?: boolean;\n /**\n * Hot-update top-level components in place during `vite dev`. It applies to the browser build\n * only: SSR transforms never get it. Test runners never hot-update modules unless this is set.\n * @default true in `vite dev`, false under a test runner\n */\n hmr?: boolean;\n /**\n * Development output: component names in the compiled code and the extra runtime checks.\n * Set `true` to get development output in a production build, or `false` to get it out of `vite dev`.\n * @default true for `vite dev` (command `serve`), false for `vite build`\n */\n dev?: boolean;\n /**\n * Run the browser build of ShadowJS under Vitest, instead of the server build that the `node`\n * condition selects. Tests that render on the server (`renderToString`) want `false`.\n * @default true when the Vitest environment is `happy-dom` or `jsdom`, otherwise false\n */\n domTests?: boolean;\n /**\n * Compiler plugins that run in the build on every module this plugin compiles: `\"pre\"` plugins\n * (the default) on the syntax tree before the compiler's own passes, `\"post\"` plugins on the\n * generated code, each group in list order. A plugin can report findings and change the module\n * (strip test attributes, collect translation keys, sort class names); it never reaches the\n * browser. Errors fail the build with the plugin's name and the position in the file; warnings go\n * to Vite's warning log. Only files that `include` matches are compiled, so a plugin sees plain\n * `.ts` modules only when `include` covers them. See `CompilerPlugin` in `@shadow-js/compiler`.\n * @default undefined (no plugins; nothing is added to the build)\n */\n plugins?: readonly CompilerPlugin[];\n /**\n * Which implementation of the compiler runs. `@shadow-js/compiler` holds three of the same compiler: a Rust addon (about ten times\n * faster on large apps), the same Rust code as WebAssembly, and the TypeScript implementation. `\"auto\"` uses the fastest one the\n * machine has. `\"native\"` requires the Rust or the WebAssembly implementation and fails, with the reason, when only TypeScript is\n * available; use it in CI to be sure builds are fast. `\"javascript\"` uses the TypeScript implementation only, for example to compare\n * outputs. The output is identical in every mode. A module compiled with compiler plugins is answered by the TypeScript\n * implementation in every mode. The environment variable `SHADOW_COMPILER_BACKEND` asks for one for the whole process.\n * @default \"auto\"\n */\n compiler?: \"auto\" | \"javascript\" | \"native\";\n}\n\n/** What the transform reports through: the plugin context's `warn` and `error`. */\ninterface TransformPluginContext {\n warn(message: string, position?: { line: number; column: number }): void;\n error(message: string, position?: { line: number; column: number }): never;\n}\n\n/** The part of Vitest's config this plugin reads and contributes. */\ninterface VitestSection {\n environment?: string;\n server?: { deps?: { inline?: Array<string | RegExp> } };\n}\n\nconst DEFAULT_INCLUDE = /\\.[cm]?[jt]sx$/;\nconst DEFAULT_EXCLUDE = /[\\\\/]node_modules[\\\\/]/;\n/**\n * Plain modules the compiler also reads, when they call `useStore`: a single-value `useStore(...)`\n * there becomes the cell path (see the compiler's store-cells pass). Other plain modules are untouched.\n */\nconst PLAIN_MODULE = /\\.[cm]?[jt]s$/;\n\n/**\n * The same pattern without the `g` and `y` flags. `test()` on a global or sticky pattern starts at the `lastIndex` the\n * previous call left, so the same file would match on one call and not on the next.\n */\nfunction stateless(pattern: RegExp): RegExp {\n return pattern.global || pattern.sticky\n ? new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, \"\"))\n : pattern;\n}\n\n/**\n * True when this Vite transforms with Oxc (Vite 8 and later, and the Rolldown builds of Vite 7); Vite 7 transforms with\n * esbuild. Found by what the module exports: only a Rolldown based Vite exports `rolldownVersion`.\n */\nconst transformsWithOxc = \"rolldownVersion\" in vite;\n\n/** The JSX runtime setting, under the key this Vite's transformer reads (`oxc` on Vite 8, `esbuild` on Vite 7). */\nfunction jsxConfig(): Record<string, unknown> {\n return transformsWithOxc\n ? { oxc: { jsx: { runtime: \"automatic\", importSource: \"@shadow-js/web\" } } }\n : { esbuild: { jsx: \"automatic\", jsxImportSource: \"@shadow-js/web\" } };\n}\n\n/**\n * Creates the Vite plugin that compiles a ShadowJS app's JSX and `useStore` calls with\n * `@shadow-js/compiler`. Add it to the Vite config of every ShadowJS app: it runs before Vite's own\n * TypeScript and JSX handling, so Vite never sees JSX. SSR builds get the server target. It also\n * sets the ShadowJS JSX import source and dedupes `@shadow-js/core` and `@shadow-js/web`. A compile\n * error is reported to Vite with its file, line and column.\n * @param options Include and exclude filters, the runtime module, the dev, HMR and test switches, and\n * the compiler plugins.\n * @returns A Vite plugin named `shadowjs` that runs with `enforce: \"pre\"`.\n * @throws {TypeError} When `include` or `exclude` is not a `RegExp`, `moduleName` is not a non-empty string, or `plugins` is\n * not a list of valid compiler plugins (a member without a unique `name` or a `transform` function, for example), naming the\n * option. The `transform` hook rethrows any error that is not a `CompileError`, which points at a compiler bug. A `CompileError` goes through Vite's `this.error`\n * instead, which fails the build with the file and position.\n * @example\n * // vite.config.ts\n * import { shadow } from \"@shadow-js/vite\"; // the default export is the same function\n * export default { plugins: [shadow()] };\n * @see ShadowPluginOptions\n * @since 1.0.0\n */\nexport function shadow(options: ShadowPluginOptions = {}): Plugin {\n for (const name of [\"include\", \"exclude\"] as const) {\n const value = options[name];\n if (value !== undefined && !(value instanceof RegExp)) {\n throw new TypeError(`shadow(): \"${name}\" must be a RegExp (got ${typeof value}).`);\n }\n }\n if (\n options.moduleName !== undefined &&\n (typeof options.moduleName !== \"string\" || options.moduleName === \"\")\n ) {\n throw new TypeError('shadow(): \"moduleName\" must be a non-empty string.');\n }\n if (\n options.compiler !== undefined &&\n options.compiler !== \"auto\" &&\n options.compiler !== \"javascript\" &&\n options.compiler !== \"native\"\n ) {\n throw new TypeError(\n `shadow(): \"compiler\" must be \"auto\", \"javascript\" or \"native\" (got ${JSON.stringify(options.compiler)}).`,\n );\n }\n const plugins =\n options.plugins === undefined ? [] : validatePlugins(options.plugins, \"shadow(): plugins\");\n // `@shadow-js/compiler` chooses its implementation once per process, on the first call. \"native\" asks it which one it chose and refuses\n // the TypeScript one, so a build that must be fast does not quietly become slow.\n const mode = options.compiler ?? \"auto\";\n let verified = mode !== \"native\";\n const requireNative = (): void => {\n if (verified) return;\n const backend = getBackend();\n if (backend.name === \"javascript\") {\n throw new Error(\n `shadow(): compiler: \"native\" needs the Rust or WebAssembly implementation of @shadow-js/compiler, and only the TypeScript one is available (${backend.notes.join(\"; \") || \"no reason was recorded\"}). Install @shadow-js/compiler with its optional dependencies (do not use --omit=optional), or use compiler: \"auto\". SHADOW_COMPILER_BACKEND=${process.env[\"SHADOW_COMPILER_BACKEND\"] ?? \"auto\"}.`,\n );\n }\n verified = true;\n };\n const run = mode === \"javascript\" ? compileWithJavaScript : compile;\n const include = stateless(options.include ?? DEFAULT_INCLUDE);\n const exclude = stateless(options.exclude ?? DEFAULT_EXCLUDE);\n let dev = options.dev ?? false;\n let hot = options.hmr !== false;\n return {\n name: \"shadowjs\",\n enforce: \"pre\",\n config(userConfig, env) {\n if (options.dev === undefined) dev = env.command === \"serve\";\n const testing = env.mode === \"test\" || process.env[\"VITEST\"] !== undefined;\n // Test runners serve modules but never hot update them, unless the caller asked for it.\n if (testing && options.hmr === undefined) hot = false;\n const test = (userConfig as { test?: VitestSection }).test;\n const domTests =\n testing &&\n (options.domTests ?? (test?.environment === \"happy-dom\" || test?.environment === \"jsdom\"));\n return {\n // `DUSK_PUBLIC_*` variables are readable in client code next to Vite's own `VITE_*` (Dusk\n // and the integration packages document `DUSK_PUBLIC_*`).\n envPrefix: [\"VITE_\", \"DUSK_PUBLIC_\"],\n // Dependency scanning and any file this plugin skips are parsed with the ShadowJS JSX\n // runtime types, never React's.\n ...jsxConfig(),\n resolve: {\n dedupe: [\"@shadow-js/core\", \"@shadow-js/web\"],\n // Vitest resolves packages with the `node` condition, which selects the inert server\n // build of ShadowJS; DOM tests need the browser build.\n ...(domTests ? { conditions: [\"browser\"] } : {}),\n },\n // Packages Node would load natively see the `node` condition too, so they go through Vite.\n ...(domTests ? { test: { server: { deps: { inline: [/@shadow-js\\//] } } } } : {}),\n optimizeDeps: { exclude: [\"@shadow-js/core\", \"@shadow-js/web\"] },\n };\n },\n transform(code, id, transformOptions) {\n // A virtual module (Vite's \\0 prefix) belongs to the plugin that made it.\n if (id.startsWith(\"\\0\")) return null;\n const file = id.split(\"?\")[0] ?? id;\n if (exclude.test(file)) return null;\n if (!include.test(file) && !(PLAIN_MODULE.test(file) && code.includes(\"useStore\")))\n return null;\n const compileOptions: CompileOptions = {\n filename: file,\n generate: transformOptions?.ssr === true ? \"ssr\" : \"dom\",\n dev,\n autoReactive: options.autoReactive !== false,\n hmr: dev && hot && transformOptions?.ssr !== true,\n };\n if (options.moduleName !== undefined) compileOptions.moduleName = options.moduleName;\n if (plugins.length > 0) compileOptions.plugins = plugins;\n const finish = (\n context: TransformPluginContext,\n run: typeof compile,\n ): { code: string; map: CompileResult[\"map\"] } | null => {\n try {\n const result = run(code, compileOptions);\n for (const diagnostic of result.diagnostics) {\n if (diagnostic.severity === \"warning\") {\n context.warn(diagnostic.message, {\n line: diagnostic.line,\n column: diagnostic.column,\n });\n }\n }\n if (!result.transformed) return null;\n return { code: result.code, map: result.map };\n } catch (error) {\n if (error instanceof CompileError) {\n const loc = { file, line: error.diagnostic.line, column: error.diagnostic.column };\n return context.error(\n error.message,\n loc.line === 0 ? undefined : { line: loc.line, column: loc.column },\n );\n }\n throw error;\n }\n };\n requireNative();\n return finish(this, run);\n },\n };\n}\n\nexport default shadow;\n"],"mappings":";;;;AAmGA,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;;;;;AAKxB,MAAM,eAAe;;;;;AAMrB,SAAS,UAAU,SAAyB;CAC1C,OAAO,QAAQ,UAAU,QAAQ,SAC7B,IAAI,OAAO,QAAQ,QAAQ,QAAQ,MAAM,QAA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Aa,QAAQ;GAC1E,IAAI,QAAQ,SAAS,GAAG,eAAe,UAAU;GACjD,MAAM,UACJ,SACA,QACuD;IACvD,IAAI;KACF,MAAM,SAAS,IAAI,MAAM,cAAc;KACvC,KAAK,MAAM,cAAc,OAAO,aAC9B,IAAI,WAAW,aAAa,WAC1B,QAAQ,KAAK,WAAW,SAAS;MAC/B,MAAM,WAAW;MACjB,QAAQ,WAAW;KACrB,CAAC;KAGL,IAAI,CAAC,OAAO,aAAa,OAAO;KAChC,OAAO;MAAE,MAAM,OAAO;MAAM,KAAK,OAAO;KAAI;IAC9C,SAAS,OAAO;KACd,IAAI,iBAAiB,cAAc;MACjC,MAAM,MAAM;OAAE;OAAM,MAAM,MAAM,WAAW;OAAM,QAAQ,MAAM,WAAW;MAAO;MACjF,OAAO,QAAQ,MACb,MAAM,SACN,IAAI,SAAS,IAAI,KAAA,IAAY;OAAE,MAAM,IAAI;OAAM,QAAQ,IAAI;MAAO,CACpE;KACF;KACA,MAAM;IACR;GACF;GACA,cAAc;GACd,OAAO,OAAO,MAAM,GAAG;EACzB;CACF;AACF"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { CompilerPlugin } from "@shadow-js/compiler";
|
|
2
|
+
import { Plugin } from "vite";
|
|
3
|
+
/**
|
|
4
|
+
* `shadowMdx()`: a Vite plugin that turns `.mdx` (and `.md`) files into ShadowJS components. MDX is compiled to JSX by
|
|
5
|
+
* `@mdx-js/mdx`, an optional peer, and the JSX goes through the ShadowJS compiler in the same step, so an MDX file needs no
|
|
6
|
+
* other plugin to be compiled. The default export of a module is the component; the `export`s of the file (a `frontmatter`
|
|
7
|
+
* from `remark-mdx-frontmatter`, a `meta` object) are named exports.
|
|
8
|
+
* @packageDocumentation
|
|
9
|
+
*/
|
|
10
|
+
/** The file `@mdx-js/mdx` answers: a `VFile`, whose `value` holds the code. */
|
|
11
|
+
interface MdxOutput {
|
|
12
|
+
readonly value: string | Uint8Array;
|
|
13
|
+
}
|
|
14
|
+
/** What `compile` of `@mdx-js/mdx` accepts (the options this plugin sets, and the lists it hands on). */
|
|
15
|
+
interface MdxCompileOptions {
|
|
16
|
+
readonly jsx: true;
|
|
17
|
+
readonly jsxImportSource: string;
|
|
18
|
+
readonly development: false;
|
|
19
|
+
readonly format: "mdx" | "md";
|
|
20
|
+
readonly remarkPlugins?: readonly unknown[];
|
|
21
|
+
readonly rehypePlugins?: readonly unknown[];
|
|
22
|
+
readonly recmaPlugins?: readonly unknown[];
|
|
23
|
+
readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;
|
|
24
|
+
readonly providerImportSource?: string;
|
|
25
|
+
}
|
|
26
|
+
/** `compile` of `@mdx-js/mdx`, or a function with its shape. @since 1.0.0 */
|
|
27
|
+
export type MdxCompile = (file: {
|
|
28
|
+
readonly value: string;
|
|
29
|
+
readonly path: string;
|
|
30
|
+
}, options: MdxCompileOptions) => Promise<MdxOutput>;
|
|
31
|
+
/** Options of {@link shadowMdx}. @since 1.0.0 */
|
|
32
|
+
export interface ShadowMdxOptions {
|
|
33
|
+
/** Files to compile, matched against the module id without its query string. Default `/\.mdx$/`. Add `.md` to read Markdown files too. */
|
|
34
|
+
readonly include?: RegExp;
|
|
35
|
+
/** Files to skip; checked first. Default: any path with a `node_modules` segment. */
|
|
36
|
+
readonly exclude?: RegExp;
|
|
37
|
+
/** Plugins of the Markdown syntax tree (`remark-frontmatter`, `remark-mdx-frontmatter`, `remark-gfm`, ...), as `@mdx-js/mdx` takes them. */
|
|
38
|
+
readonly remarkPlugins?: readonly unknown[];
|
|
39
|
+
/** Plugins of the HTML syntax tree (`rehype-slug`, `rehype-autolink-headings`, ...). */
|
|
40
|
+
readonly rehypePlugins?: readonly unknown[];
|
|
41
|
+
/** Plugins of the JavaScript syntax tree. They run before the plugin's own pass over the elements. */
|
|
42
|
+
readonly recmaPlugins?: readonly unknown[];
|
|
43
|
+
/**
|
|
44
|
+
* How the elements of Markdown (`h1`, `p`, `a`, `code`, ...) are rendered.
|
|
45
|
+
*
|
|
46
|
+
* - `"overridable"`: each one is looked up in the `components` prop (and the provider), so an app can replace `a` or `h1`
|
|
47
|
+
* for every page. Each looked-up element is rendered by `Dynamic`.
|
|
48
|
+
* - `"static"`: each one is a plain element in the page's template, cloned in one call. The `components` prop still
|
|
49
|
+
* supplies components the file names itself (`<Chart />`) and the `wrapper`, but cannot replace `h1` or `a`.
|
|
50
|
+
*
|
|
51
|
+
* Choose `"static"` for pages that never replace a Markdown element: documentation and blog posts render faster and ship
|
|
52
|
+
* less code.
|
|
53
|
+
* @default "overridable"
|
|
54
|
+
*/
|
|
55
|
+
readonly elements?: "overridable" | "static";
|
|
56
|
+
/** Options of `remark-rehype`. */
|
|
57
|
+
readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;
|
|
58
|
+
/**
|
|
59
|
+
* A module that exports `useMDXComponents`, whose components every MDX file may use without a `components` prop (the
|
|
60
|
+
* way `@mdx-js/react` works for React). Default: none; pass `components` to the file's component instead.
|
|
61
|
+
*/
|
|
62
|
+
readonly providerImportSource?: string;
|
|
63
|
+
/** `@mdx-js/mdx`, by module name, or your own `compile`. Default `"@mdx-js/mdx"`. */
|
|
64
|
+
readonly mdx?: string | MdxCompile;
|
|
65
|
+
/** Compiler plugins that run on the JSX of every MDX file (see `ShadowPluginOptions.plugins`). */
|
|
66
|
+
readonly plugins?: readonly CompilerPlugin[];
|
|
67
|
+
/** Module the compiled code imports its runtime helpers from. Default `"@shadow-js/web"` (`"@shadow-js/web/server"` for SSR). */
|
|
68
|
+
readonly moduleName?: string;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Creates the plugin that compiles MDX to ShadowJS components. It runs before Vite's own handling (`enforce: "pre"`), so Vite
|
|
72
|
+
* never sees MDX or JSX. A file is compiled for the browser, or for the server in an SSR build; a syntax error in the MDX is
|
|
73
|
+
* reported with its file, line and column. Hot updates reload the page: an MDX file has no component state worth keeping.
|
|
74
|
+
*
|
|
75
|
+
* @param options Which files, the remark, rehype and recma plugins, and the MDX compiler.
|
|
76
|
+
* @returns A Vite plugin named `shadowjs-mdx`.
|
|
77
|
+
* @throws TypeError when `include` or `exclude` is not a `RegExp`, or `plugins` is not a list of valid compiler plugins.
|
|
78
|
+
* @example
|
|
79
|
+
* // vite.config.ts
|
|
80
|
+
* import { shadow } from "@shadow-js/vite";
|
|
81
|
+
* import { shadowMdx } from "@shadow-js/vite/mdx";
|
|
82
|
+
* import remarkFrontmatter from "remark-frontmatter";
|
|
83
|
+
* import remarkMdxFrontmatter from "remark-mdx-frontmatter";
|
|
84
|
+
*
|
|
85
|
+
* export default {
|
|
86
|
+
* plugins: [
|
|
87
|
+
* shadowMdx({ remarkPlugins: [remarkFrontmatter, remarkMdxFrontmatter] }),
|
|
88
|
+
* shadow(),
|
|
89
|
+
* ],
|
|
90
|
+
* };
|
|
91
|
+
* @since 1.0.0
|
|
92
|
+
*/
|
|
93
|
+
export declare function shadowMdx(options?: ShadowMdxOptions): Plugin;
|
|
94
|
+
export {};
|
|
95
|
+
//# sourceMappingURL=mdx.d.ts.map
|
package/dist/dev/mdx.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { CompileError, compile, validatePlugins } from "@shadow-js/compiler";
|
|
2
|
+
// src/mdx.ts
|
|
3
|
+
function isNode(value) {
|
|
4
|
+
return typeof value === "object" && value !== null && typeof value.type === "string";
|
|
5
|
+
}
|
|
6
|
+
/** The identifier `@mdx-js/mdx` binds the element lookup table to. */
|
|
7
|
+
const LOOKUP = "_components";
|
|
8
|
+
/** The local name of `Dynamic`: it cannot clash with a name the file exports or imports. */
|
|
9
|
+
const DYNAMIC = "_ShadowDynamic";
|
|
10
|
+
/**
|
|
11
|
+
* Rewrites the elements `@mdx-js/mdx` looks up in its table (`<_components.h1>`): into plain `<h1>` for `"static"`, into
|
|
12
|
+
* `<Dynamic component={_components.h1}>` for `"overridable"`. The lookup yields a string for a default element and a
|
|
13
|
+
* function for an override, and a ShadowJS component tag must be a function.
|
|
14
|
+
*/
|
|
15
|
+
function elementsPlugin(mode) {
|
|
16
|
+
return () => (tree) => {
|
|
17
|
+
let rewritten = 0;
|
|
18
|
+
const pending = [tree];
|
|
19
|
+
while (pending.length > 0) {
|
|
20
|
+
const node = pending.pop();
|
|
21
|
+
if (Array.isArray(node)) {
|
|
22
|
+
for (const child of node) pending.push(child);
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (!isNode(node)) continue;
|
|
26
|
+
if (node.type === "JSXElement") {
|
|
27
|
+
const opening = node["openingElement"];
|
|
28
|
+
const closing = node["closingElement"];
|
|
29
|
+
if (isNode(opening) && lookupName(opening["name"]) !== void 0) {
|
|
30
|
+
const tag = lookupName(opening["name"]);
|
|
31
|
+
if (mode === "static") opening["name"] = identifier(tag);
|
|
32
|
+
else {
|
|
33
|
+
opening["name"] = identifier(DYNAMIC);
|
|
34
|
+
opening["attributes"].unshift({
|
|
35
|
+
type: "JSXAttribute",
|
|
36
|
+
name: identifier("component"),
|
|
37
|
+
value: {
|
|
38
|
+
type: "JSXExpressionContainer",
|
|
39
|
+
expression: {
|
|
40
|
+
type: "MemberExpression",
|
|
41
|
+
object: {
|
|
42
|
+
type: "Identifier",
|
|
43
|
+
name: LOOKUP
|
|
44
|
+
},
|
|
45
|
+
property: {
|
|
46
|
+
type: "Identifier",
|
|
47
|
+
name: tag
|
|
48
|
+
},
|
|
49
|
+
computed: false,
|
|
50
|
+
optional: false
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
rewritten += 1;
|
|
55
|
+
}
|
|
56
|
+
if (isNode(closing)) closing["name"] = identifier(mode === "static" ? tag : DYNAMIC);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
for (const value of Object.values(node)) if (typeof value === "object" && value !== null) pending.push(value);
|
|
60
|
+
}
|
|
61
|
+
if (rewritten > 0) tree["body"].unshift({
|
|
62
|
+
type: "ImportDeclaration",
|
|
63
|
+
specifiers: [{
|
|
64
|
+
type: "ImportSpecifier",
|
|
65
|
+
imported: {
|
|
66
|
+
type: "Identifier",
|
|
67
|
+
name: "Dynamic"
|
|
68
|
+
},
|
|
69
|
+
local: {
|
|
70
|
+
type: "Identifier",
|
|
71
|
+
name: DYNAMIC
|
|
72
|
+
}
|
|
73
|
+
}],
|
|
74
|
+
source: {
|
|
75
|
+
type: "Literal",
|
|
76
|
+
value: "@shadow-js/web",
|
|
77
|
+
raw: "\"@shadow-js/web\""
|
|
78
|
+
},
|
|
79
|
+
attributes: []
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** The element name of `_components.name` as a JSX tag name, otherwise `undefined`. */
|
|
84
|
+
function lookupName(name) {
|
|
85
|
+
if (!isNode(name) || name.type !== "JSXMemberExpression") return void 0;
|
|
86
|
+
const object = name["object"];
|
|
87
|
+
const property = name["property"];
|
|
88
|
+
if (!isNode(object) || object.type !== "JSXIdentifier" || object["name"] !== LOOKUP) return void 0;
|
|
89
|
+
return isNode(property) && typeof property["name"] === "string" ? property["name"] : void 0;
|
|
90
|
+
}
|
|
91
|
+
function identifier(name) {
|
|
92
|
+
return {
|
|
93
|
+
type: "JSXIdentifier",
|
|
94
|
+
name
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
const DEFAULT_INCLUDE = /\.mdx$/;
|
|
98
|
+
const DEFAULT_EXCLUDE = /[\\/]node_modules[\\/]/;
|
|
99
|
+
async function loadMdx(specifier) {
|
|
100
|
+
let loaded;
|
|
101
|
+
try {
|
|
102
|
+
loaded = await import(specifier);
|
|
103
|
+
} catch (cause) {
|
|
104
|
+
throw new Error(`shadowMdx: cannot load "${specifier}". Install it with "npm install --save-dev ${specifier}", or pass your own function as mdx.`, { cause });
|
|
105
|
+
}
|
|
106
|
+
if (typeof loaded.compile !== "function") throw new TypeError(`shadowMdx: the module "${specifier}" has no compile function.`);
|
|
107
|
+
const compileMdx = loaded.compile;
|
|
108
|
+
return (file, options) => Reflect.apply(compileMdx, void 0, [file, options]);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Creates the plugin that compiles MDX to ShadowJS components. It runs before Vite's own handling (`enforce: "pre"`), so Vite
|
|
112
|
+
* never sees MDX or JSX. A file is compiled for the browser, or for the server in an SSR build; a syntax error in the MDX is
|
|
113
|
+
* reported with its file, line and column. Hot updates reload the page: an MDX file has no component state worth keeping.
|
|
114
|
+
*
|
|
115
|
+
* @param options Which files, the remark, rehype and recma plugins, and the MDX compiler.
|
|
116
|
+
* @returns A Vite plugin named `shadowjs-mdx`.
|
|
117
|
+
* @throws TypeError when `include` or `exclude` is not a `RegExp`, or `plugins` is not a list of valid compiler plugins.
|
|
118
|
+
* @example
|
|
119
|
+
* // vite.config.ts
|
|
120
|
+
* import { shadow } from "@shadow-js/vite";
|
|
121
|
+
* import { shadowMdx } from "@shadow-js/vite/mdx";
|
|
122
|
+
* import remarkFrontmatter from "remark-frontmatter";
|
|
123
|
+
* import remarkMdxFrontmatter from "remark-mdx-frontmatter";
|
|
124
|
+
*
|
|
125
|
+
* export default {
|
|
126
|
+
* plugins: [
|
|
127
|
+
* shadowMdx({ remarkPlugins: [remarkFrontmatter, remarkMdxFrontmatter] }),
|
|
128
|
+
* shadow(),
|
|
129
|
+
* ],
|
|
130
|
+
* };
|
|
131
|
+
* @since 1.0.0
|
|
132
|
+
*/
|
|
133
|
+
function shadowMdx(options = {}) {
|
|
134
|
+
for (const name of ["include", "exclude"]) {
|
|
135
|
+
const value = options[name];
|
|
136
|
+
if (value !== void 0 && !(value instanceof RegExp)) throw new TypeError(`shadowMdx(): "${name}" must be a RegExp (got ${typeof value}).`);
|
|
137
|
+
}
|
|
138
|
+
const plugins = options.plugins === void 0 ? [] : validatePlugins(options.plugins, "shadowMdx(): plugins");
|
|
139
|
+
const include = statelessPattern(options.include ?? DEFAULT_INCLUDE);
|
|
140
|
+
const exclude = statelessPattern(options.exclude ?? DEFAULT_EXCLUDE);
|
|
141
|
+
let compileMdx;
|
|
142
|
+
let dev = false;
|
|
143
|
+
return {
|
|
144
|
+
name: "shadowjs-mdx",
|
|
145
|
+
enforce: "pre",
|
|
146
|
+
config(_config, env) {
|
|
147
|
+
dev = env.command === "serve";
|
|
148
|
+
},
|
|
149
|
+
async transform(code, id, transformOptions) {
|
|
150
|
+
const file = id.split("?")[0] ?? id;
|
|
151
|
+
if (id.startsWith("\0") || exclude.test(file) || !include.test(file)) return null;
|
|
152
|
+
compileMdx ??= typeof options.mdx === "function" ? Promise.resolve(options.mdx) : loadMdx(options.mdx ?? "@mdx-js/mdx");
|
|
153
|
+
const mdx = await compileMdx;
|
|
154
|
+
let jsx;
|
|
155
|
+
try {
|
|
156
|
+
const output = await mdx({
|
|
157
|
+
value: code,
|
|
158
|
+
path: file
|
|
159
|
+
}, {
|
|
160
|
+
jsx: true,
|
|
161
|
+
jsxImportSource: options.moduleName ?? "@shadow-js/web",
|
|
162
|
+
development: false,
|
|
163
|
+
format: file.endsWith(".mdx") ? "mdx" : "md",
|
|
164
|
+
...options.remarkPlugins === void 0 ? {} : { remarkPlugins: options.remarkPlugins },
|
|
165
|
+
...options.rehypePlugins === void 0 ? {} : { rehypePlugins: options.rehypePlugins },
|
|
166
|
+
recmaPlugins: [...options.recmaPlugins ?? [], elementsPlugin(options.elements ?? "overridable")],
|
|
167
|
+
...options.remarkRehypeOptions === void 0 ? {} : { remarkRehypeOptions: options.remarkRehypeOptions },
|
|
168
|
+
...options.providerImportSource === void 0 ? {} : { providerImportSource: options.providerImportSource }
|
|
169
|
+
});
|
|
170
|
+
jsx = typeof output.value === "string" ? output.value : Buffer.from(output.value).toString("utf8");
|
|
171
|
+
} catch (error) {
|
|
172
|
+
const found = error;
|
|
173
|
+
const position = typeof found.line === "number" && found.line > 0 ? {
|
|
174
|
+
line: found.line,
|
|
175
|
+
column: Math.max((found.column ?? 1) - 1, 0)
|
|
176
|
+
} : void 0;
|
|
177
|
+
return this.error(found.reason ?? found.message ?? String(error), position);
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
const result = compile(jsx, {
|
|
181
|
+
filename: `${file}.tsx`,
|
|
182
|
+
generate: transformOptions?.ssr === true ? "ssr" : "dom",
|
|
183
|
+
dev,
|
|
184
|
+
autoReactive: true,
|
|
185
|
+
hmr: false,
|
|
186
|
+
...options.moduleName === void 0 ? {} : { moduleName: options.moduleName },
|
|
187
|
+
...plugins.length > 0 ? { plugins } : {}
|
|
188
|
+
});
|
|
189
|
+
for (const diagnostic of result.diagnostics) if (diagnostic.severity === "warning") this.warn(diagnostic.message, {
|
|
190
|
+
line: diagnostic.line,
|
|
191
|
+
column: diagnostic.column
|
|
192
|
+
});
|
|
193
|
+
return {
|
|
194
|
+
code: result.transformed ? result.code : jsx,
|
|
195
|
+
map: result.transformed ? result.map : null
|
|
196
|
+
};
|
|
197
|
+
} catch (error) {
|
|
198
|
+
if (error instanceof CompileError) return this.error(error.message, error.diagnostic.line === 0 ? void 0 : {
|
|
199
|
+
line: error.diagnostic.line,
|
|
200
|
+
column: error.diagnostic.column
|
|
201
|
+
});
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
/** The same pattern without the `g` and `y` flags, so `test()` does not remember where the last call ended. */
|
|
208
|
+
function statelessPattern(pattern) {
|
|
209
|
+
return pattern.global || pattern.sticky ? new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, "")) : pattern;
|
|
210
|
+
}
|
|
211
|
+
export { shadowMdx };
|
|
212
|
+
|
|
213
|
+
//# sourceMappingURL=mdx.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mdx.js","names":[],"sources":["../../src/mdx.ts"],"sourcesContent":["import { CompileError, type CompilerPlugin, compile, validatePlugins } from \"@shadow-js/compiler\";\nimport type { Plugin } from \"vite\";\n\n/**\n * `shadowMdx()`: a Vite plugin that turns `.mdx` (and `.md`) files into ShadowJS components. MDX is compiled to JSX by\n * `@mdx-js/mdx`, an optional peer, and the JSX goes through the ShadowJS compiler in the same step, so an MDX file needs no\n * other plugin to be compiled. The default export of a module is the component; the `export`s of the file (a `frontmatter`\n * from `remark-mdx-frontmatter`, a `meta` object) are named exports.\n * @packageDocumentation\n */\n\n/** The file `@mdx-js/mdx` answers: a `VFile`, whose `value` holds the code. */\ninterface MdxOutput {\n readonly value: string | Uint8Array;\n}\n\n/** What `compile` of `@mdx-js/mdx` accepts (the options this plugin sets, and the lists it hands on). */\ninterface MdxCompileOptions {\n readonly jsx: true;\n readonly jsxImportSource: string;\n readonly development: false;\n readonly format: \"mdx\" | \"md\";\n readonly remarkPlugins?: readonly unknown[];\n readonly rehypePlugins?: readonly unknown[];\n readonly recmaPlugins?: readonly unknown[];\n readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;\n readonly providerImportSource?: string;\n}\n\n/** `compile` of `@mdx-js/mdx`, or a function with its shape. @since 1.0.0 */\nexport type MdxCompile = (\n file: { readonly value: string; readonly path: string },\n options: MdxCompileOptions,\n) => Promise<MdxOutput>;\n\n/** Options of {@link shadowMdx}. @since 1.0.0 */\nexport interface ShadowMdxOptions {\n /** Files to compile, matched against the module id without its query string. Default `/\\.mdx$/`. Add `.md` to read Markdown files too. */\n readonly include?: RegExp;\n /** Files to skip; checked first. Default: any path with a `node_modules` segment. */\n readonly exclude?: RegExp;\n /** Plugins of the Markdown syntax tree (`remark-frontmatter`, `remark-mdx-frontmatter`, `remark-gfm`, ...), as `@mdx-js/mdx` takes them. */\n readonly remarkPlugins?: readonly unknown[];\n /** Plugins of the HTML syntax tree (`rehype-slug`, `rehype-autolink-headings`, ...). */\n readonly rehypePlugins?: readonly unknown[];\n /** Plugins of the JavaScript syntax tree. They run before the plugin's own pass over the elements. */\n readonly recmaPlugins?: readonly unknown[];\n /**\n * How the elements of Markdown (`h1`, `p`, `a`, `code`, ...) are rendered.\n *\n * - `\"overridable\"`: each one is looked up in the `components` prop (and the provider), so an app can replace `a` or `h1`\n * for every page. Each looked-up element is rendered by `Dynamic`.\n * - `\"static\"`: each one is a plain element in the page's template, cloned in one call. The `components` prop still\n * supplies components the file names itself (`<Chart />`) and the `wrapper`, but cannot replace `h1` or `a`.\n *\n * Choose `\"static\"` for pages that never replace a Markdown element: documentation and blog posts render faster and ship\n * less code.\n * @default \"overridable\"\n */\n readonly elements?: \"overridable\" | \"static\";\n /** Options of `remark-rehype`. */\n readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;\n /**\n * A module that exports `useMDXComponents`, whose components every MDX file may use without a `components` prop (the\n * way `@mdx-js/react` works for React). Default: none; pass `components` to the file's component instead.\n */\n readonly providerImportSource?: string;\n /** `@mdx-js/mdx`, by module name, or your own `compile`. Default `\"@mdx-js/mdx\"`. */\n readonly mdx?: string | MdxCompile;\n /** Compiler plugins that run on the JSX of every MDX file (see `ShadowPluginOptions.plugins`). */\n readonly plugins?: readonly CompilerPlugin[];\n /** Module the compiled code imports its runtime helpers from. Default `\"@shadow-js/web\"` (`\"@shadow-js/web/server\"` for SSR). */\n readonly moduleName?: string;\n}\n\n/** A node of the JavaScript syntax tree `@mdx-js/mdx` hands to recma plugins (ESTree with JSX), read structurally. */\ninterface EsNode {\n type: string;\n [key: string]: unknown;\n}\n\nfunction isNode(value: unknown): value is EsNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { type?: unknown }).type === \"string\"\n );\n}\n\n/** The identifier `@mdx-js/mdx` binds the element lookup table to. */\nconst LOOKUP = \"_components\";\n/** The local name of `Dynamic`: it cannot clash with a name the file exports or imports. */\nconst DYNAMIC = \"_ShadowDynamic\";\n\n/**\n * Rewrites the elements `@mdx-js/mdx` looks up in its table (`<_components.h1>`): into plain `<h1>` for `\"static\"`, into\n * `<Dynamic component={_components.h1}>` for `\"overridable\"`. The lookup yields a string for a default element and a\n * function for an override, and a ShadowJS component tag must be a function.\n */\nfunction elementsPlugin(mode: \"overridable\" | \"static\"): () => (tree: EsNode) => void {\n return () => (tree) => {\n let rewritten = 0;\n const pending: unknown[] = [tree];\n while (pending.length > 0) {\n const node = pending.pop();\n if (Array.isArray(node)) {\n for (const child of node) pending.push(child);\n continue;\n }\n if (!isNode(node)) continue;\n if (node.type === \"JSXElement\") {\n const opening = node[\"openingElement\"];\n const closing = node[\"closingElement\"];\n if (isNode(opening) && lookupName(opening[\"name\"]) !== undefined) {\n const tag = lookupName(opening[\"name\"]) as string;\n if (mode === \"static\") {\n opening[\"name\"] = identifier(tag);\n } else {\n opening[\"name\"] = identifier(DYNAMIC);\n const attributes = opening[\"attributes\"] as unknown[];\n attributes.unshift({\n type: \"JSXAttribute\",\n name: identifier(\"component\"),\n value: {\n type: \"JSXExpressionContainer\",\n expression: {\n type: \"MemberExpression\",\n object: { type: \"Identifier\", name: LOOKUP },\n property: { type: \"Identifier\", name: tag },\n computed: false,\n optional: false,\n },\n },\n });\n rewritten += 1;\n }\n if (isNode(closing)) closing[\"name\"] = identifier(mode === \"static\" ? tag : DYNAMIC);\n }\n }\n for (const value of Object.values(node)) {\n if (typeof value === \"object\" && value !== null) pending.push(value);\n }\n }\n if (rewritten > 0) {\n const body = tree[\"body\"] as unknown[];\n body.unshift({\n type: \"ImportDeclaration\",\n specifiers: [\n {\n type: \"ImportSpecifier\",\n imported: { type: \"Identifier\", name: \"Dynamic\" },\n local: { type: \"Identifier\", name: DYNAMIC },\n },\n ],\n source: { type: \"Literal\", value: \"@shadow-js/web\", raw: '\"@shadow-js/web\"' },\n attributes: [],\n });\n }\n };\n}\n\n/** The element name of `_components.name` as a JSX tag name, otherwise `undefined`. */\nfunction lookupName(name: unknown): string | undefined {\n if (!isNode(name) || name.type !== \"JSXMemberExpression\") return undefined;\n const object = name[\"object\"];\n const property = name[\"property\"];\n if (!isNode(object) || object.type !== \"JSXIdentifier\" || object[\"name\"] !== LOOKUP)\n return undefined;\n return isNode(property) && typeof property[\"name\"] === \"string\" ? property[\"name\"] : undefined;\n}\n\nfunction identifier(name: string): EsNode {\n return { type: \"JSXIdentifier\", name };\n}\n\nconst DEFAULT_INCLUDE = /\\.mdx$/;\nconst DEFAULT_EXCLUDE = /[\\\\/]node_modules[\\\\/]/;\n\n/** `@mdx-js/mdx` warns with a position; so do the errors of its parsers. */\ninterface Positioned {\n readonly message?: string;\n readonly line?: number | null;\n readonly column?: number | null;\n readonly reason?: string;\n}\n\nasync function loadMdx(specifier: string): Promise<MdxCompile> {\n let loaded: { compile?: unknown };\n try {\n loaded = (await import(specifier)) as { compile?: unknown };\n } catch (cause) {\n throw new Error(\n `shadowMdx: cannot load \"${specifier}\". Install it with \"npm install --save-dev ${specifier}\", or pass your own function as mdx.`,\n { cause },\n );\n }\n if (typeof loaded.compile !== \"function\") {\n throw new TypeError(`shadowMdx: the module \"${specifier}\" has no compile function.`);\n }\n const compileMdx = loaded.compile;\n return (file, options) =>\n Reflect.apply(compileMdx, undefined, [file, options]) as Promise<MdxOutput>;\n}\n\n/**\n * Creates the plugin that compiles MDX to ShadowJS components. It runs before Vite's own handling (`enforce: \"pre\"`), so Vite\n * never sees MDX or JSX. A file is compiled for the browser, or for the server in an SSR build; a syntax error in the MDX is\n * reported with its file, line and column. Hot updates reload the page: an MDX file has no component state worth keeping.\n *\n * @param options Which files, the remark, rehype and recma plugins, and the MDX compiler.\n * @returns A Vite plugin named `shadowjs-mdx`.\n * @throws TypeError when `include` or `exclude` is not a `RegExp`, or `plugins` is not a list of valid compiler plugins.\n * @example\n * // vite.config.ts\n * import { shadow } from \"@shadow-js/vite\";\n * import { shadowMdx } from \"@shadow-js/vite/mdx\";\n * import remarkFrontmatter from \"remark-frontmatter\";\n * import remarkMdxFrontmatter from \"remark-mdx-frontmatter\";\n *\n * export default {\n * plugins: [\n * shadowMdx({ remarkPlugins: [remarkFrontmatter, remarkMdxFrontmatter] }),\n * shadow(),\n * ],\n * };\n * @since 1.0.0\n */\nexport function shadowMdx(options: ShadowMdxOptions = {}): Plugin {\n for (const name of [\"include\", \"exclude\"] as const) {\n const value = options[name];\n if (value !== undefined && !(value instanceof RegExp)) {\n throw new TypeError(`shadowMdx(): \"${name}\" must be a RegExp (got ${typeof value}).`);\n }\n }\n const plugins =\n options.plugins === undefined ? [] : validatePlugins(options.plugins, \"shadowMdx(): plugins\");\n const include = statelessPattern(options.include ?? DEFAULT_INCLUDE);\n const exclude = statelessPattern(options.exclude ?? DEFAULT_EXCLUDE);\n let compileMdx: Promise<MdxCompile> | undefined;\n let dev = false;\n return {\n name: \"shadowjs-mdx\",\n enforce: \"pre\",\n config(_config, env) {\n dev = env.command === \"serve\";\n },\n async transform(code, id, transformOptions) {\n const file = id.split(\"?\")[0] ?? id;\n if (id.startsWith(\"\\0\") || exclude.test(file) || !include.test(file)) return null;\n compileMdx ??=\n typeof options.mdx === \"function\"\n ? Promise.resolve(options.mdx)\n : loadMdx(options.mdx ?? \"@mdx-js/mdx\");\n const mdx = await compileMdx;\n let jsx: string;\n try {\n const output = await mdx(\n { value: code, path: file },\n {\n jsx: true,\n jsxImportSource: options.moduleName ?? \"@shadow-js/web\",\n development: false,\n format: file.endsWith(\".mdx\") ? \"mdx\" : \"md\",\n ...(options.remarkPlugins === undefined\n ? {}\n : { remarkPlugins: options.remarkPlugins }),\n ...(options.rehypePlugins === undefined\n ? {}\n : { rehypePlugins: options.rehypePlugins }),\n recmaPlugins: [\n ...(options.recmaPlugins ?? []),\n elementsPlugin(options.elements ?? \"overridable\"),\n ],\n ...(options.remarkRehypeOptions === undefined\n ? {}\n : { remarkRehypeOptions: options.remarkRehypeOptions }),\n ...(options.providerImportSource === undefined\n ? {}\n : { providerImportSource: options.providerImportSource }),\n },\n );\n jsx =\n typeof output.value === \"string\"\n ? output.value\n : Buffer.from(output.value).toString(\"utf8\");\n } catch (error) {\n const found = error as Positioned;\n const position =\n typeof found.line === \"number\" && found.line > 0\n ? { line: found.line, column: Math.max((found.column ?? 1) - 1, 0) }\n : undefined;\n return this.error(found.reason ?? found.message ?? String(error), position);\n }\n try {\n const result = compile(jsx, {\n filename: `${file}.tsx`,\n generate: transformOptions?.ssr === true ? \"ssr\" : \"dom\",\n dev,\n autoReactive: true,\n hmr: false,\n ...(options.moduleName === undefined ? {} : { moduleName: options.moduleName }),\n ...(plugins.length > 0 ? { plugins } : {}),\n });\n for (const diagnostic of result.diagnostics) {\n if (diagnostic.severity === \"warning\") {\n this.warn(diagnostic.message, { line: diagnostic.line, column: diagnostic.column });\n }\n }\n return {\n code: result.transformed ? result.code : jsx,\n map: result.transformed ? result.map : null,\n };\n } catch (error) {\n if (error instanceof CompileError) {\n return this.error(\n error.message,\n error.diagnostic.line === 0\n ? undefined\n : { line: error.diagnostic.line, column: error.diagnostic.column },\n );\n }\n throw error;\n }\n },\n };\n}\n\n/** The same pattern without the `g` and `y` flags, so `test()` does not remember where the last call ended. */\nfunction statelessPattern(pattern: RegExp): RegExp {\n return pattern.global || pattern.sticky\n ? new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, \"\"))\n : pattern;\n}\n"],"mappings":";;AAiFA,SAAS,OAAO,OAAiC;CAC/C,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS;AAElD;;AAGA,MAAM,SAAS;;AAEf,MAAM,UAAU;;;;;;AAOhB,SAAS,eAAe,MAA8D;CACpF,cAAc,SAAS;EACrB,IAAI,YAAY;EAChB,MAAM,UAAqB,CAAC,IAAI;EAChC,OAAO,QAAQ,SAAS,GAAG;GACzB,MAAM,OAAO,QAAQ,IAAI;GACzB,IAAI,MAAM,QAAQ,IAAI,GAAG;IACvB,KAAK,MAAM,SAAS,MAAM,QAAQ,KAAK,KAAK;IAC5C;GACF;GACA,IAAI,CAAC,OAAO,IAAI,GAAG;GACnB,IAAI,KAAK,SAAS,cAAc;IAC9B,MAAM,UAAU,KAAK;IACrB,MAAM,UAAU,KAAK;IACrB,IAAI,OAAO,OAAO,KAAK,WAAW,QAAQ,OAAO,MAAM,KAAA,GAAW;KAChE,MAAM,MAAM,WAAW,QAAQ,OAAO;KACtC,IAAI,SAAS,UACX,QAAQ,UAAU,WAAW,GAAG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,WAAW,aAAa,WAC1B,KAAK,KAAK,WAAW,SAAS;KAAE,MAAM,WAAW;KAAM,QAAQ,WAAW;IAAO,CAAC;IAGtF,OAAO;KACL,MAAM,OAAO,cAAc,OAAO,OAAO;KACzC,KAAK,OAAO,cAAc,OAAO,MAAM;IACzC;GACF,SAAS,OAAO;IACd,IAAI,iBAAiB,cACnB,OAAO,KAAK,MACV,MAAM,SACN,MAAM,WAAW,SAAS,IACtB,KAAA,IACA;KAAE,MAAM,MAAM,WAAW;KAAM,QAAQ,MAAM,WAAW;IAAO,CACrE;IAEF,MAAM;GACR;EACF;CACF;AACF;;AAGA,SAAS,iBAAiB,SAAyB;CACjD,OAAO,QAAQ,UAAU,QAAQ,SAC7B,IAAI,OAAO,QAAQ,QAAQ,QAAQ,MAAM,QAAQ,SAAS,EAAE,CAAC,IAC7D;AACN"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types for `import Page from "./page.mdx"`. Add `/// <reference types="@shadow-js/vite/mdx-env" />` to a `.d.ts` file of
|
|
3
|
+
* the app. A named export of one file (a `frontmatter` from `remark-mdx-frontmatter`) is typed by merging a declaration:
|
|
4
|
+
* `declare module "*.mdx" { export const frontmatter: { title: string }; }`.
|
|
5
|
+
*/
|
|
6
|
+
declare module "*.mdx" {
|
|
7
|
+
import type { JSX } from "@shadow-js/web";
|
|
8
|
+
|
|
9
|
+
/** The props of an MDX page: `components` replaces Markdown elements and supplies the tags the file uses. */
|
|
10
|
+
export interface MdxProps {
|
|
11
|
+
readonly components?: Readonly<Record<string, unknown>>;
|
|
12
|
+
readonly [prop: string]: unknown;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const MDXContent: (props: MdxProps) => JSX.Element;
|
|
16
|
+
export default MDXContent;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
declare module "*.md" {
|
|
20
|
+
import type { JSX } from "@shadow-js/web";
|
|
21
|
+
|
|
22
|
+
const MarkdownContent: (props: {
|
|
23
|
+
readonly components?: Readonly<Record<string, unknown>>;
|
|
24
|
+
}) => JSX.Element;
|
|
25
|
+
export default MarkdownContent;
|
|
26
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{CompileError as e,compile as t,getBackend as n,validatePlugins as r}from"@shadow-js/compiler";import{compile as i}from"@shadow-js/compiler/javascript";import*as a from"vite";const o=/\.[cm]?[jt]sx$/,s=/[\\/]node_modules[\\/]/,c=/\.[cm]?[jt]s$/;function l(e){return e.global||e.sticky?new RegExp(e.source,e.flags.replace(/[gy]/g,``)):e}const u=`rolldownVersion`in a;function d(){return u?{oxc:{jsx:{runtime:`automatic`,importSource:`@shadow-js/web`}}}:{esbuild:{jsx:`automatic`,jsxImportSource:`@shadow-js/web`}}}function f(a={}){for(let e of[`include`,`exclude`]){let t=a[e];if(t!==void 0&&!(t instanceof RegExp))throw TypeError(`shadow(): "${e}" must be a RegExp (got ${typeof t}).`)}if(a.moduleName!==void 0&&(typeof a.moduleName!=`string`||a.moduleName===``))throw TypeError(`shadow(): "moduleName" must be a non-empty string.`);if(a.compiler!==void 0&&a.compiler!==`auto`&&a.compiler!==`javascript`&&a.compiler!==`native`)throw TypeError(`shadow(): "compiler" must be "auto", "javascript" or "native" (got ${JSON.stringify(a.compiler)}).`);let u=a.plugins===void 0?[]:r(a.plugins,`shadow(): plugins`),f=a.compiler??`auto`,p=f!==`native`,m=()=>{if(p)return;let e=n();if(e.name===`javascript`)throw Error(`shadow(): compiler: "native" needs the Rust or WebAssembly implementation of @shadow-js/compiler, and only the TypeScript one is available (${e.notes.join(`; `)||`no reason was recorded`}). Install @shadow-js/compiler with its optional dependencies (do not use --omit=optional), or use compiler: "auto". SHADOW_COMPILER_BACKEND=${process.env.SHADOW_COMPILER_BACKEND??`auto`}.`);p=!0},h=f===`javascript`?i:t,g=l(a.include??o),_=l(a.exclude??s),v=a.dev??!1,y=a.hmr!==!1;return{name:`shadowjs`,enforce:`pre`,config(e,t){a.dev===void 0&&(v=t.command===`serve`);let n=t.mode===`test`||process.env.VITEST!==void 0;n&&a.hmr===void 0&&(y=!1);let r=e.test,i=n&&(a.domTests??(r?.environment===`happy-dom`||r?.environment===`jsdom`));return{envPrefix:[`VITE_`,`DUSK_PUBLIC_`],...d(),resolve:{dedupe:[`@shadow-js/core`,`@shadow-js/web`],...i?{conditions:[`browser`]}:{}},...i?{test:{server:{deps:{inline:[/@shadow-js\//]}}}}:{},optimizeDeps:{exclude:[`@shadow-js/core`,`@shadow-js/web`]}}},transform(t,n,r){if(n.startsWith(`\0`))return null;let i=n.split(`?`)[0]??n;if(_.test(i)||!g.test(i)&&!(c.test(i)&&t.includes(`useStore`)))return null;let o={filename:i,generate:r?.ssr===!0?`ssr`:`dom`,dev:v,autoReactive:a.autoReactive!==!1,hmr:v&&y&&r?.ssr!==!0};return a.moduleName!==void 0&&(o.moduleName=a.moduleName),u.length>0&&(o.plugins=u),m(),((n,r)=>{try{let e=r(t,o);for(let t of e.diagnostics)t.severity===`warning`&&n.warn(t.message,{line:t.line,column:t.column});return e.transformed?{code:e.code,map:e.map}:null}catch(t){if(t instanceof e){let e={file:i,line:t.diagnostic.line,column:t.diagnostic.column};return n.error(t.message,e.line===0?void 0:{line:e.line,column:e.column})}throw t}})(this,h)}}}export{f as default,f as shadow};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["compileWithJavaScript","compile$1","vite","DEFAULT_INCLUDE","DEFAULT_EXCLUDE","PLAIN_MODULE","stateless","pattern","transformsWithOxc","jsxConfig","shadow","name","value","options","plugins","validatePlugins","mode","verified","requireNative","backend","getBackend","\"SHADOW_COMPILER_BACKEND\"","run","compile","include","exclude","dev","hot","env","testing","\"VITEST\"","test","userConfig","domTests","id","file","code","compileOptions","transformOptions","result","diagnostic","context","error","CompileError","loc"],"sources":["../../src/index.ts"],"sourcesContent":["import {\n CompileError,\n type CompileOptions,\n type CompileResult,\n type CompilerPlugin,\n compile,\n getBackend,\n validatePlugins,\n} from \"@shadow-js/compiler\";\nimport { compile as compileWithJavaScript } from \"@shadow-js/compiler/javascript\";\nimport type { Plugin } from \"vite\";\nimport * as vite from \"vite\";\n\n/**\n * Options of {@link shadow}. Every member is optional: the defaults compile a ShadowJS app for the\n * browser in `vite dev` and `vite build`, and for the server in SSR builds.\n * @see shadow\n * @since 1.0.0\n */\nexport interface ShadowPluginOptions {\n /**\n * Files to compile, matched against the module id without its query string. Plain `.ts` and `.js`\n * modules are compiled as well when they call `useStore`, whatever this is set to, so a\n * single-value `useStore` there takes the cell path. Files that `exclude` matches are never compiled.\n * @default /\\.[cm]?[jt]sx$/ (every `.jsx` and `.tsx` file)\n * A `g` or `y` flag on the pattern is ignored: the pattern is matched from the start of every id.\n */\n include?: RegExp;\n /**\n * Files to skip. It is checked before `include`, so an excluded file is never compiled.\n * @default /[\\\\/]node_modules[\\\\/]/ (any path with a `node_modules` segment)\n */\n exclude?: RegExp;\n /**\n * Module the compiled code imports its runtime helpers from. The HMR runtime is read from\n * `<moduleName>/hmr`.\n * @default \"@shadow-js/web\" (`\"@shadow-js/web/server\"` for SSR transforms)\n */\n moduleName?: string;\n /**\n * Turn a `const` computed from reactive reads (`const double = count() * 2`) into a live value\n * inside components, so it updates without a function or `useMemo`. Set `false` to keep such\n * constants as written.\n * @default true\n */\n autoReactive?: boolean;\n /**\n * Hot-update top-level components in place during `vite dev`. It applies to the browser build\n * only: SSR transforms never get it. Test runners never hot-update modules unless this is set.\n * @default true in `vite dev`, false under a test runner\n */\n hmr?: boolean;\n /**\n * Development output: component names in the compiled code and the extra runtime checks.\n * Set `true` to get development output in a production build, or `false` to get it out of `vite dev`.\n * @default true for `vite dev` (command `serve`), false for `vite build`\n */\n dev?: boolean;\n /**\n * Run the browser build of ShadowJS under Vitest, instead of the server build that the `node`\n * condition selects. Tests that render on the server (`renderToString`) want `false`.\n * @default true when the Vitest environment is `happy-dom` or `jsdom`, otherwise false\n */\n domTests?: boolean;\n /**\n * Compiler plugins that run in the build on every module this plugin compiles: `\"pre\"` plugins\n * (the default) on the syntax tree before the compiler's own passes, `\"post\"` plugins on the\n * generated code, each group in list order. A plugin can report findings and change the module\n * (strip test attributes, collect translation keys, sort class names); it never reaches the\n * browser. Errors fail the build with the plugin's name and the position in the file; warnings go\n * to Vite's warning log. Only files that `include` matches are compiled, so a plugin sees plain\n * `.ts` modules only when `include` covers them. See `CompilerPlugin` in `@shadow-js/compiler`.\n * @default undefined (no plugins; nothing is added to the build)\n */\n plugins?: readonly CompilerPlugin[];\n /**\n * Which implementation of the compiler runs. `@shadow-js/compiler` holds three of the same compiler: a Rust addon (about ten times\n * faster on large apps), the same Rust code as WebAssembly, and the TypeScript implementation. `\"auto\"` uses the fastest one the\n * machine has. `\"native\"` requires the Rust or the WebAssembly implementation and fails, with the reason, when only TypeScript is\n * available; use it in CI to be sure builds are fast. `\"javascript\"` uses the TypeScript implementation only, for example to compare\n * outputs. The output is identical in every mode. A module compiled with compiler plugins is answered by the TypeScript\n * implementation in every mode. The environment variable `SHADOW_COMPILER_BACKEND` asks for one for the whole process.\n * @default \"auto\"\n */\n compiler?: \"auto\" | \"javascript\" | \"native\";\n}\n\n/** What the transform reports through: the plugin context's `warn` and `error`. */\ninterface TransformPluginContext {\n warn(message: string, position?: { line: number; column: number }): void;\n error(message: string, position?: { line: number; column: number }): never;\n}\n\n/** The part of Vitest's config this plugin reads and contributes. */\ninterface VitestSection {\n environment?: string;\n server?: { deps?: { inline?: Array<string | RegExp> } };\n}\n\nconst DEFAULT_INCLUDE = /\\.[cm]?[jt]sx$/;\nconst DEFAULT_EXCLUDE = /[\\\\/]node_modules[\\\\/]/;\n/**\n * Plain modules the compiler also reads, when they call `useStore`: a single-value `useStore(...)`\n * there becomes the cell path (see the compiler's store-cells pass). Other plain modules are untouched.\n */\nconst PLAIN_MODULE = /\\.[cm]?[jt]s$/;\n\n/**\n * The same pattern without the `g` and `y` flags. `test()` on a global or sticky pattern starts at the `lastIndex` the\n * previous call left, so the same file would match on one call and not on the next.\n */\nfunction stateless(pattern: RegExp): RegExp {\n return pattern.global || pattern.sticky\n ? new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, \"\"))\n : pattern;\n}\n\n/**\n * True when this Vite transforms with Oxc (Vite 8 and later, and the Rolldown builds of Vite 7); Vite 7 transforms with\n * esbuild. Found by what the module exports: only a Rolldown based Vite exports `rolldownVersion`.\n */\nconst transformsWithOxc = \"rolldownVersion\" in vite;\n\n/** The JSX runtime setting, under the key this Vite's transformer reads (`oxc` on Vite 8, `esbuild` on Vite 7). */\nfunction jsxConfig(): Record<string, unknown> {\n return transformsWithOxc\n ? { oxc: { jsx: { runtime: \"automatic\", importSource: \"@shadow-js/web\" } } }\n : { esbuild: { jsx: \"automatic\", jsxImportSource: \"@shadow-js/web\" } };\n}\n\n/**\n * Creates the Vite plugin that compiles a ShadowJS app's JSX and `useStore` calls with\n * `@shadow-js/compiler`. Add it to the Vite config of every ShadowJS app: it runs before Vite's own\n * TypeScript and JSX handling, so Vite never sees JSX. SSR builds get the server target. It also\n * sets the ShadowJS JSX import source and dedupes `@shadow-js/core` and `@shadow-js/web`. A compile\n * error is reported to Vite with its file, line and column.\n * @param options Include and exclude filters, the runtime module, the dev, HMR and test switches, and\n * the compiler plugins.\n * @returns A Vite plugin named `shadowjs` that runs with `enforce: \"pre\"`.\n * @throws {TypeError} When `include` or `exclude` is not a `RegExp`, `moduleName` is not a non-empty string, or `plugins` is\n * not a list of valid compiler plugins (a member without a unique `name` or a `transform` function, for example), naming the\n * option. The `transform` hook rethrows any error that is not a `CompileError`, which points at a compiler bug. A `CompileError` goes through Vite's `this.error`\n * instead, which fails the build with the file and position.\n * @example\n * // vite.config.ts\n * import { shadow } from \"@shadow-js/vite\"; // the default export is the same function\n * export default { plugins: [shadow()] };\n * @see ShadowPluginOptions\n * @since 1.0.0\n */\nexport function shadow(options: ShadowPluginOptions = {}): Plugin {\n for (const name of [\"include\", \"exclude\"] as const) {\n const value = options[name];\n if (value !== undefined && !(value instanceof RegExp)) {\n throw new TypeError(`shadow(): \"${name}\" must be a RegExp (got ${typeof value}).`);\n }\n }\n if (\n options.moduleName !== undefined &&\n (typeof options.moduleName !== \"string\" || options.moduleName === \"\")\n ) {\n throw new TypeError('shadow(): \"moduleName\" must be a non-empty string.');\n }\n if (\n options.compiler !== undefined &&\n options.compiler !== \"auto\" &&\n options.compiler !== \"javascript\" &&\n options.compiler !== \"native\"\n ) {\n throw new TypeError(\n `shadow(): \"compiler\" must be \"auto\", \"javascript\" or \"native\" (got ${JSON.stringify(options.compiler)}).`,\n );\n }\n const plugins =\n options.plugins === undefined ? [] : validatePlugins(options.plugins, \"shadow(): plugins\");\n // `@shadow-js/compiler` chooses its implementation once per process, on the first call. \"native\" asks it which one it chose and refuses\n // the TypeScript one, so a build that must be fast does not quietly become slow.\n const mode = options.compiler ?? \"auto\";\n let verified = mode !== \"native\";\n const requireNative = (): void => {\n if (verified) return;\n const backend = getBackend();\n if (backend.name === \"javascript\") {\n throw new Error(\n `shadow(): compiler: \"native\" needs the Rust or WebAssembly implementation of @shadow-js/compiler, and only the TypeScript one is available (${backend.notes.join(\"; \") || \"no reason was recorded\"}). Install @shadow-js/compiler with its optional dependencies (do not use --omit=optional), or use compiler: \"auto\". SHADOW_COMPILER_BACKEND=${process.env[\"SHADOW_COMPILER_BACKEND\"] ?? \"auto\"}.`,\n );\n }\n verified = true;\n };\n const run = mode === \"javascript\" ? compileWithJavaScript : compile;\n const include = stateless(options.include ?? DEFAULT_INCLUDE);\n const exclude = stateless(options.exclude ?? DEFAULT_EXCLUDE);\n let dev = options.dev ?? false;\n let hot = options.hmr !== false;\n return {\n name: \"shadowjs\",\n enforce: \"pre\",\n config(userConfig, env) {\n if (options.dev === undefined) dev = env.command === \"serve\";\n const testing = env.mode === \"test\" || process.env[\"VITEST\"] !== undefined;\n // Test runners serve modules but never hot update them, unless the caller asked for it.\n if (testing && options.hmr === undefined) hot = false;\n const test = (userConfig as { test?: VitestSection }).test;\n const domTests =\n testing &&\n (options.domTests ?? (test?.environment === \"happy-dom\" || test?.environment === \"jsdom\"));\n return {\n // `DUSK_PUBLIC_*` variables are readable in client code next to Vite's own `VITE_*` (Dusk\n // and the integration packages document `DUSK_PUBLIC_*`).\n envPrefix: [\"VITE_\", \"DUSK_PUBLIC_\"],\n // Dependency scanning and any file this plugin skips are parsed with the ShadowJS JSX\n // runtime types, never React's.\n ...jsxConfig(),\n resolve: {\n dedupe: [\"@shadow-js/core\", \"@shadow-js/web\"],\n // Vitest resolves packages with the `node` condition, which selects the inert server\n // build of ShadowJS; DOM tests need the browser build.\n ...(domTests ? { conditions: [\"browser\"] } : {}),\n },\n // Packages Node would load natively see the `node` condition too, so they go through Vite.\n ...(domTests ? { test: { server: { deps: { inline: [/@shadow-js\\//] } } } } : {}),\n optimizeDeps: { exclude: [\"@shadow-js/core\", \"@shadow-js/web\"] },\n };\n },\n transform(code, id, transformOptions) {\n // A virtual module (Vite's \\0 prefix) belongs to the plugin that made it.\n if (id.startsWith(\"\\0\")) return null;\n const file = id.split(\"?\")[0] ?? id;\n if (exclude.test(file)) return null;\n if (!include.test(file) && !(PLAIN_MODULE.test(file) && code.includes(\"useStore\")))\n return null;\n const compileOptions: CompileOptions = {\n filename: file,\n generate: transformOptions?.ssr === true ? \"ssr\" : \"dom\",\n dev,\n autoReactive: options.autoReactive !== false,\n hmr: dev && hot && transformOptions?.ssr !== true,\n };\n if (options.moduleName !== undefined) compileOptions.moduleName = options.moduleName;\n if (plugins.length > 0) compileOptions.plugins = plugins;\n const finish = (\n context: TransformPluginContext,\n run: typeof compile,\n ): { code: string; map: CompileResult[\"map\"] } | null => {\n try {\n const result = run(code, compileOptions);\n for (const diagnostic of result.diagnostics) {\n if (diagnostic.severity === \"warning\") {\n context.warn(diagnostic.message, {\n line: diagnostic.line,\n column: diagnostic.column,\n });\n }\n }\n if (!result.transformed) return null;\n return { code: result.code, map: result.map };\n } catch (error) {\n if (error instanceof CompileError) {\n const loc = { file, line: error.diagnostic.line, column: error.diagnostic.column };\n return context.error(\n error.message,\n loc.line === 0 ? undefined : { line: loc.line, column: loc.column },\n );\n }\n throw error;\n }\n };\n requireNative();\n return finish(this, run);\n },\n };\n}\n\nexport default shadow;\n"],"mappings":"A,qLAmGA,MAAMG,EAAkB,iBAClBC,EAAkB,yBAKlBC,EAAe,gBAMrB,SAASC,EAAU,EAAyB,CAC1C,OAAOC,EAAQ,QAAUA,EAAQ,OAC7B,IAAI,OAAOA,EAAQ,OAAQA,EAAQ,MAAM,QAAQ,QAAS,EAAE,CAAC,EAC7DA,CACN,CAMA,MAAMC,EAAoB,oBAAqBN,EAG/C,SAASO,GAAqC,CAC5C,OAAOD,EACH,CAAE,IAAK,CAAE,IAAK,CAAE,QAAS,YAAa,aAAc,gBAAiB,CAAE,CAAE,EACzE,CAAE,QAAS,CAAE,IAAK,YAAa,gBAAiB,gBAAiB,CAAE,CACzE,CAsBA,SAAgBE,EAAO,EAA+B,CAAC,EAAW,CAChE,IAAK,IAAMC,IAAQ,CAAC,UAAW,SAAS,EAAY,CAClD,IAAMC,EAAQC,EAAQF,GACtB,GAAIC,IAAU,IAAA,IAAa,EAAEA,aAAiB,QAC5C,MAAU,UAAU,cAAcD,EAAK,0BAA0B,OAAOC,EAAM,GAAG,CAErF,CACA,GACEC,EAAQ,aAAe,IAAA,KACtB,OAAOA,EAAQ,YAAe,UAAYA,EAAQ,aAAe,IAElE,MAAU,UAAU,oDAAoD,EAE1E,GACEA,EAAQ,WAAa,IAAA,IACrBA,EAAQ,WAAa,QACrBA,EAAQ,WAAa,cACrBA,EAAQ,WAAa,SAErB,MAAU,UACR,sEAAsE,KAAK,UAAUA,EAAQ,QAAQ,EAAE,GACzG,EAEF,IAAMC,EACJD,EAAQ,UAAY,IAAA,GAAY,CAAC,EAAIE,EAAgBF,EAAQ,QAAS,mBAAmB,EAGrFG,EAAOH,EAAQ,UAAY,OAC7BI,EAAWD,IAAS,SAClBE,MAA4B,C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CAACX,EAAQ,KAAKW,CAAI,GAAK,EAAE9B,EAAa,KAAK8B,CAAI,GAAKC,EAAK,SAAS,UAAU,GAC9E,OAAO,KACT,IAAMC,EAAiC,CACrC,SAAUF,EACV,SAAUG,GAAkB,MAAQ,GAAO,MAAQ,MACnD,MACA,aAAczB,EAAQ,eAAiB,GACvC,IAAKa,GAAOC,GAAOW,GAAkB,MAAQ,EAC/C,EA+BA,OA9BIzB,EAAQ,aAAe,IAAA,KAAW,EAAe,WAAaA,EAAQ,YACtEC,EAAQ,OAAS,IAAG,EAAe,QAAUA,GA4BjDI,EAAc,IA1BZ,EACA,IACuD,CACvD,GAAI,CACF,IAAMqB,EAASjB,EAAIc,EAAMC,CAAc,EACvC,IAAK,IAAMG,KAAcD,EAAO,YAC1BC,EAAW,WAAa,WAC1BC,EAAQ,KAAKD,EAAW,QAAS,CAC/B,KAAMA,EAAW,KACjB,OAAQA,EAAW,MACrB,CAAC,EAIL,OADKD,EAAO,YACL,CAAE,KAAMA,EAAO,KAAM,IAAKA,EAAO,GAAI,EADZ,IAElC,OAASG,EAAO,CACd,GAAIA,aAAiBC,EAAc,CACjC,IAAMC,EAAM,CAAE,OAAM,KAAMF,EAAM,WAAW,KAAM,OAAQA,EAAM,WAAW,MAAO,EACjF,OAAOD,EAAQ,MACbC,EAAM,QACNE,EAAI,OAAS,EAAI,IAAA,GAAY,CAAE,KAAMA,EAAI,KAAM,OAAQA,EAAI,MAAO,CACpE,CACF,CACA,MAAMF,CACR,CACF,EAEO,CAAO,KAAMpB,CAAG,CACzB,CACF,CACF,C"}
|
package/dist/prod/mdx.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{CompileError as e,compile as t,validatePlugins as n}from"@shadow-js/compiler";function r(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}const i=`_components`,a=`_ShadowDynamic`;function o(e){return()=>t=>{let n=0,o=[t];for(;o.length>0;){let t=o.pop();if(Array.isArray(t))for(let e of t)o.push(e);else if(r(t)){if(t.type===`JSXElement`){let o=t.openingElement,l=t.closingElement;if(r(o)&&s(o.name)!==void 0){let t=s(o.name);e===`static`?o.name=c(t):(o.name=c(a),o.attributes.unshift({type:`JSXAttribute`,name:c(`component`),value:{type:`JSXExpressionContainer`,expression:{type:`MemberExpression`,object:{type:`Identifier`,name:i},property:{type:`Identifier`,name:t},computed:!1,optional:!1}}}),n+=1),r(l)&&(l.name=c(e===`static`?t:a))}}for(let e of Object.values(t))typeof e==`object`&&e&&o.push(e)}}n>0&&t.body.unshift({type:`ImportDeclaration`,specifiers:[{type:`ImportSpecifier`,imported:{type:`Identifier`,name:`Dynamic`},local:{type:`Identifier`,name:a}}],source:{type:`Literal`,value:`@shadow-js/web`,raw:`"@shadow-js/web"`},attributes:[]})}}function s(e){if(!r(e)||e.type!==`JSXMemberExpression`)return;let t=e.object,n=e.property;if(r(t)&&t.type===`JSXIdentifier`&&t.name===i)return r(n)&&typeof n.name==`string`?n.name:void 0}function c(e){return{type:`JSXIdentifier`,name:e}}const l=/\.mdx$/,u=/[\\/]node_modules[\\/]/;async function d(e){let t;try{t=await import(e)}catch(t){throw Error(`shadowMdx: cannot load "${e}". Install it with "npm install --save-dev ${e}", or pass your own function as mdx.`,{cause:t})}if(typeof t.compile!=`function`)throw TypeError(`shadowMdx: the module "${e}" has no compile function.`);let n=t.compile;return(e,t)=>Reflect.apply(n,void 0,[e,t])}function f(r={}){for(let e of[`include`,`exclude`]){let t=r[e];if(t!==void 0&&!(t instanceof RegExp))throw TypeError(`shadowMdx(): "${e}" must be a RegExp (got ${typeof t}).`)}let i=r.plugins===void 0?[]:n(r.plugins,`shadowMdx(): plugins`),a=p(r.include??l),s=p(r.exclude??u),c,f=!1;return{name:`shadowjs-mdx`,enforce:`pre`,config(e,t){f=t.command===`serve`},async transform(n,l,u){let p=l.split(`?`)[0]??l;if(l.startsWith(`\0`)||s.test(p)||!a.test(p))return null;c??=typeof r.mdx==`function`?Promise.resolve(r.mdx):d(r.mdx??`@mdx-js/mdx`);let m=await c,h;try{let e=await m({value:n,path:p},{jsx:!0,jsxImportSource:r.moduleName??`@shadow-js/web`,development:!1,format:p.endsWith(`.mdx`)?`mdx`:`md`,...r.remarkPlugins===void 0?{}:{remarkPlugins:r.remarkPlugins},...r.rehypePlugins===void 0?{}:{rehypePlugins:r.rehypePlugins},recmaPlugins:[...r.recmaPlugins??[],o(r.elements??`overridable`)],...r.remarkRehypeOptions===void 0?{}:{remarkRehypeOptions:r.remarkRehypeOptions},...r.providerImportSource===void 0?{}:{providerImportSource:r.providerImportSource}});h=typeof e.value==`string`?e.value:Buffer.from(e.value).toString(`utf8`)}catch(e){let t=e,n=typeof t.line==`number`&&t.line>0?{line:t.line,column:Math.max((t.column??1)-1,0)}:void 0;return this.error(t.reason??t.message??String(e),n)}try{let e=t(h,{filename:`${p}.tsx`,generate:u?.ssr===!0?`ssr`:`dom`,dev:f,autoReactive:!0,hmr:!1,...r.moduleName===void 0?{}:{moduleName:r.moduleName},...i.length>0?{plugins:i}:{}});for(let t of e.diagnostics)t.severity===`warning`&&this.warn(t.message,{line:t.line,column:t.column});return{code:e.transformed?e.code:h,map:e.transformed?e.map:null}}catch(t){if(t instanceof e)return this.error(t.message,t.diagnostic.line===0?void 0:{line:t.diagnostic.line,column:t.diagnostic.column});throw t}}}}function p(e){return e.global||e.sticky?new RegExp(e.source,e.flags.replace(/[gy]/g,``)):e}export{f as shadowMdx};
|
|
2
|
+
//# sourceMappingURL=mdx.js.map
|