@shadow-js/vite 0.3.0 → 1.0.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mdx.js","names":["isNode","value","LOOKUP","DYNAMIC","elementsPlugin","rewritten","pending","tree","node","child","opening","\"openingElement\"","closing","\"closingElement\"","lookupName","\"name\"","tag","mode","identifier","\"attributes\"","\"body\"","name","object","\"object\"","property","\"property\"","DEFAULT_INCLUDE","DEFAULT_EXCLUDE","loadMdx","loaded","specifier","cause","compileMdx","file","options","shadowMdx","plugins","validatePlugins","include","statelessPattern","exclude","dev","env","id","mdx","jsx","output","code","error","found","position","result","compile","transformOptions","diagnostic","CompileError","pattern"],"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"],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  "name": "@shadow-js/vite",
3
- "version": "0.3.0",
4
- "description": "Vite plugin for ShadowJS (JSX + transforms via SWC)",
5
- "author": "Jehaad AL-Johani",
6
- "homepage": "https://github.com/shadowjs-dev/shadow#readme",
7
- "repository": {
8
- "type": "git",
9
- "url": "https://github.com/shadowjs-dev/shadow.git",
10
- "directory": "packages/vite"
11
- },
12
- "bugs": {
13
- "url": "https://github.com/shadowjs-dev/shadow/issues"
14
- },
15
- "keywords": [
16
- "shadowjs",
17
- "vite",
18
- "plugin",
19
- "jsx",
20
- "swc"
21
- ],
22
- "engines": {
23
- "node": ">=20"
24
- },
3
+ "version": "1.0.0",
4
+ "description": "A Vite plugin that compiles your JSX, builds for server rendering and sets up Vitest",
25
5
  "license": "MIT",
26
6
  "type": "module",
27
7
  "sideEffects": false,
28
- "main": "dist/index.cjs",
29
- "module": "dist/index.js",
30
- "types": "dist/index.d.ts",
31
- "exports": {
32
- ".": {
33
- "types": "./dist/index.d.ts",
34
- "import": "./dist/index.js",
35
- "require": "./dist/index.cjs"
36
- }
8
+ "engines": {
9
+ "node": ">=22.12.0"
37
10
  },
38
11
  "files": [
39
12
  "dist",
40
13
  "README.md",
41
- "LICENSE"
14
+ "CHANGELOG.md"
42
15
  ],
16
+ "publishConfig": {
17
+ "access": "public",
18
+ "provenance": true
19
+ },
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/dev/index.d.ts",
23
+ "development": "./dist/dev/index.js",
24
+ "default": "./dist/prod/index.js"
25
+ },
26
+ "./mdx": {
27
+ "types": "./dist/dev/mdx.d.ts",
28
+ "development": "./dist/dev/mdx.js",
29
+ "default": "./dist/prod/mdx.js"
30
+ },
31
+ "./mdx-env": {
32
+ "types": "./dist/mdx-env.d.ts"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
43
36
  "scripts": {
44
- "build": "tsup",
45
- "dev": "tsup --watch",
46
- "typecheck": "tsc -p tsconfig.json --noEmit"
37
+ "build": "tsdown --config-loader native && node scripts/copy-types.mjs",
38
+ "typecheck": "tsc -p tsconfig.json"
47
39
  },
48
40
  "dependencies": {
49
- "@shadow-js/compiler": "^0.2.0"
41
+ "@shadow-js/compiler": "1.0.0"
50
42
  },
51
43
  "peerDependencies": {
52
- "@swc/core": "^1.3.96",
53
- "@shadow-js/core": "^0.1.0",
54
- "vite": "^5.1.4"
44
+ "vite": "^7.0.0 || ^8.0.0",
45
+ "@mdx-js/mdx": "^3.0.0",
46
+ "@shadow-js/web": "^1.0.0"
47
+ },
48
+ "peerDependenciesMeta": {
49
+ "vite": {
50
+ "optional": true
51
+ },
52
+ "@mdx-js/mdx": {
53
+ "optional": true
54
+ },
55
+ "@shadow-js/web": {
56
+ "optional": true
57
+ }
55
58
  },
56
59
  "devDependencies": {
57
- "@swc/core": "^1.13.3",
58
- "@types/node": "^22.5.4",
59
- "tsup": "^8.1.0",
60
- "typescript": "^5.5.4"
60
+ "@biomejs/biome": "2.5.15",
61
+ "@mdx-js/mdx": "3.1.1",
62
+ "@shadow-js/core": "*",
63
+ "@shadow-js/web": "*",
64
+ "@types/node": "^24.0.0",
65
+ "fast-check": "^4.10.2",
66
+ "happy-dom": "^21.0.3",
67
+ "remark-frontmatter": "5.0.0",
68
+ "remark-gfm": "4.0.1",
69
+ "remark-mdx-frontmatter": "6.0.0",
70
+ "tsdown": "0.23.0",
71
+ "typescript": "7.0.2",
72
+ "vite": "8.3.3",
73
+ "vitest": "5.0.3"
61
74
  },
62
- "publishConfig": {
63
- "access": "public"
75
+ "homepage": "https://shadowjs.net/guides/vite/",
76
+ "keywords": [
77
+ "shadowjs",
78
+ "vite"
79
+ ],
80
+ "repository": {
81
+ "type": "git",
82
+ "url": "git+https://github.com/shadowjs-dev/shadow.git",
83
+ "directory": "packages/vite"
84
+ },
85
+ "bugs": {
86
+ "url": "https://github.com/shadowjs-dev/shadow/issues"
64
87
  }
65
88
  }
package/dist/index.cjs DELETED
@@ -1,59 +0,0 @@
1
- 'use strict';
2
-
3
- var compiler = require('@shadow-js/compiler');
4
- var core = require('@swc/core');
5
-
6
- // src/index.ts
7
- function shadow() {
8
- return {
9
- name: "@shadow-js/vite",
10
- enforce: "pre",
11
- // Prevent esbuild from also transforming JSX to avoid double transforms.
12
- config() {
13
- return {
14
- esbuild: {
15
- jsx: "preserve"
16
- }
17
- };
18
- },
19
- async transform(code, id) {
20
- if (!/\.(tsx|jsx)$/.test(id)) return null;
21
- if (id.includes("node_modules")) return null;
22
- let transformedCode;
23
- try {
24
- transformedCode = compiler.transformSource(code);
25
- } catch (e) {
26
- const msg = e instanceof Error ? e.message : String(e);
27
- throw new Error(`ShadowJS (vite): compiler failed for ${id}: ${msg}`);
28
- }
29
- try {
30
- const result = await core.transform(transformedCode, {
31
- filename: id,
32
- jsc: {
33
- parser: { syntax: "typescript", tsx: true },
34
- transform: {
35
- react: {
36
- runtime: "automatic",
37
- importSource: "@shadow-js/core"
38
- }
39
- },
40
- target: "es2022"
41
- },
42
- module: { type: "es6" },
43
- sourceMaps: true
44
- });
45
- return {
46
- code: result.code,
47
- map: result.map ?? null
48
- };
49
- } catch (e) {
50
- const msg = e instanceof Error ? e.message : String(e);
51
- throw new Error(`ShadowJS (vite): SWC failed for ${id}: ${msg}`);
52
- }
53
- }
54
- };
55
- }
56
-
57
- module.exports = shadow;
58
- //# sourceMappingURL=index.cjs.map
59
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["transformSource","swcTransform"],"mappings":";;;;;;AA8De,SAAR,MAAA,GAAwC;AAC7C,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,iBAAA;AAAA,IACN,OAAA,EAAS,KAAA;AAAA;AAAA,IAGT,MAAA,GAAS;AACP,MAAA,OAAO;AAAA,QACL,OAAA,EAAS;AAAA,UACP,GAAA,EAAK;AAAA;AACP,OACF;AAAA,IACF,CAAA;AAAA,IAEA,MAAM,SAAA,CAAU,IAAA,EAAM,EAAA,EAAI;AAExB,MAAA,IAAI,CAAC,cAAA,CA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;AAAA,IACF;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import type { PluginOption } from \"vite\";\nimport { transformSource } from \"@shadow-js/compiler\";\nimport { transform as swcTransform } from \"@swc/core\";\n\n/**\n * Shadow Vite Plugin\n *\n * This plugin integrates Shadow with Vite to provide seamless development experience.\n * It handles the complete transformation pipeline from TSX/JSX source code to\n * Shadow-compatible JavaScript with reactive expressions.\n *\n * Plugin Pipeline:\n * 1. **Shadow Compiler**: Applies JSX transformations to inject reactive functions\n * 2. **SWC Transformation**: Converts TypeScript/JSX to JavaScript with proper imports\n * 3. **JSX Runtime Injection**: Automatically imports Shadow's JSX runtime functions\n * 4. **Source Map Generation**: Preserves debugging capabilities\n *\n * Features:\n * - **Selective Processing**: Only transforms user code (excludes node_modules)\n * - **TypeScript Support**: Full TypeScript and TSX compilation\n * - **Hot Module Replacement**: Compatible with Vite's HMR system\n * - **Error Handling**: Provides clear error messages for compilation failures\n * - **Performance**: Uses fast SWC compiler for optimal build speeds\n *\n * The plugin automatically configures Vite to preserve JSX for SWC processing\n * instead of using esbuild's JSX transform, ensuring compatibility with Shadow's\n * reactive programming model.\n *\n * @returns Vite PluginOption instance for Shadow integration\n *\n * @example\n * ```typescript\n * // vite.config.ts\n * import { defineConfig } from \"vite\";\n * import shadow from \"@shadow-js/vite\";\n *\n * export default defineConfig({\n * plugins: [shadow()]\n * })\n * ```\n *\n * @example\n * ```typescript\n * // Your component file (App.tsx)\n * import { useStore, Show } from \"@shadow-js/core\";\n *\n * function App() {\n * const [count, setCount] = useStore(0)\n *\n * return (\n * <div>\n * <button onClick={() => setCount((c) => c + 1)}>\n * Increment\n * </button>\n * <Show when={count() > 0}>\n * <div>Count: {count()}</div>\n * </Show>\n * </div>\n * )\n * }\n * ```\n */\nexport default function shadow(): PluginOption {\n return {\n name: \"@shadow-js/vite\",\n enforce: \"pre\",\n\n // Prevent esbuild from also transforming JSX to avoid double transforms.\n config() {\n return {\n esbuild: {\n jsx: \"preserve\",\n },\n };\n },\n\n async transform(code, id) {\n // Only TSX/JSX user files\n if (!/\\.(tsx|jsx)$/.test(id)) return null;\n if (id.includes(\"node_modules\")) return null;\n\n // 1) Apply Shadow compiler transforms on source text\n let transformedCode: string;\n try {\n transformedCode = transformSource(code);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n throw new Error(`ShadowJS (vite): compiler failed for ${id}: ${msg}`);\n }\n\n // 2) Use SWC to handle TS/JSX -> JS and inject jsx runtime imports\n try {\n const result = await swcTransform(transformedCode, {\n filename: id,\n jsc: {\n parser: { syntax: \"typescript\", tsx: true },\n transform: {\n react: {\n runtime: \"automatic\",\n importSource: \"@shadow-js/core\",\n },\n },\n target: \"es2022\",\n },\n module: { type: \"es6\" },\n sourceMaps: true,\n });\n\n return {\n code: result.code,\n map: result.map ?? null,\n };\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n throw new Error(`ShadowJS (vite): SWC failed for ${id}: ${msg}`);\n }\n },\n } satisfies PluginOption;\n}\n"]}
package/dist/index.d.cts DELETED
@@ -1,63 +0,0 @@
1
- import { PluginOption } from 'vite';
2
-
3
- /**
4
- * Shadow Vite Plugin
5
- *
6
- * This plugin integrates Shadow with Vite to provide seamless development experience.
7
- * It handles the complete transformation pipeline from TSX/JSX source code to
8
- * Shadow-compatible JavaScript with reactive expressions.
9
- *
10
- * Plugin Pipeline:
11
- * 1. **Shadow Compiler**: Applies JSX transformations to inject reactive functions
12
- * 2. **SWC Transformation**: Converts TypeScript/JSX to JavaScript with proper imports
13
- * 3. **JSX Runtime Injection**: Automatically imports Shadow's JSX runtime functions
14
- * 4. **Source Map Generation**: Preserves debugging capabilities
15
- *
16
- * Features:
17
- * - **Selective Processing**: Only transforms user code (excludes node_modules)
18
- * - **TypeScript Support**: Full TypeScript and TSX compilation
19
- * - **Hot Module Replacement**: Compatible with Vite's HMR system
20
- * - **Error Handling**: Provides clear error messages for compilation failures
21
- * - **Performance**: Uses fast SWC compiler for optimal build speeds
22
- *
23
- * The plugin automatically configures Vite to preserve JSX for SWC processing
24
- * instead of using esbuild's JSX transform, ensuring compatibility with Shadow's
25
- * reactive programming model.
26
- *
27
- * @returns Vite PluginOption instance for Shadow integration
28
- *
29
- * @example
30
- * ```typescript
31
- * // vite.config.ts
32
- * import { defineConfig } from "vite";
33
- * import shadow from "@shadow-js/vite";
34
- *
35
- * export default defineConfig({
36
- * plugins: [shadow()]
37
- * })
38
- * ```
39
- *
40
- * @example
41
- * ```typescript
42
- * // Your component file (App.tsx)
43
- * import { useStore, Show } from "@shadow-js/core";
44
- *
45
- * function App() {
46
- * const [count, setCount] = useStore(0)
47
- *
48
- * return (
49
- * <div>
50
- * <button onClick={() => setCount((c) => c + 1)}>
51
- * Increment
52
- * </button>
53
- * <Show when={count() > 0}>
54
- * <div>Count: {count()}</div>
55
- * </Show>
56
- * </div>
57
- * )
58
- * }
59
- * ```
60
- */
61
- declare function shadow(): PluginOption;
62
-
63
- export { shadow as default };
package/dist/index.d.ts DELETED
@@ -1,63 +0,0 @@
1
- import { PluginOption } from 'vite';
2
-
3
- /**
4
- * Shadow Vite Plugin
5
- *
6
- * This plugin integrates Shadow with Vite to provide seamless development experience.
7
- * It handles the complete transformation pipeline from TSX/JSX source code to
8
- * Shadow-compatible JavaScript with reactive expressions.
9
- *
10
- * Plugin Pipeline:
11
- * 1. **Shadow Compiler**: Applies JSX transformations to inject reactive functions
12
- * 2. **SWC Transformation**: Converts TypeScript/JSX to JavaScript with proper imports
13
- * 3. **JSX Runtime Injection**: Automatically imports Shadow's JSX runtime functions
14
- * 4. **Source Map Generation**: Preserves debugging capabilities
15
- *
16
- * Features:
17
- * - **Selective Processing**: Only transforms user code (excludes node_modules)
18
- * - **TypeScript Support**: Full TypeScript and TSX compilation
19
- * - **Hot Module Replacement**: Compatible with Vite's HMR system
20
- * - **Error Handling**: Provides clear error messages for compilation failures
21
- * - **Performance**: Uses fast SWC compiler for optimal build speeds
22
- *
23
- * The plugin automatically configures Vite to preserve JSX for SWC processing
24
- * instead of using esbuild's JSX transform, ensuring compatibility with Shadow's
25
- * reactive programming model.
26
- *
27
- * @returns Vite PluginOption instance for Shadow integration
28
- *
29
- * @example
30
- * ```typescript
31
- * // vite.config.ts
32
- * import { defineConfig } from "vite";
33
- * import shadow from "@shadow-js/vite";
34
- *
35
- * export default defineConfig({
36
- * plugins: [shadow()]
37
- * })
38
- * ```
39
- *
40
- * @example
41
- * ```typescript
42
- * // Your component file (App.tsx)
43
- * import { useStore, Show } from "@shadow-js/core";
44
- *
45
- * function App() {
46
- * const [count, setCount] = useStore(0)
47
- *
48
- * return (
49
- * <div>
50
- * <button onClick={() => setCount((c) => c + 1)}>
51
- * Increment
52
- * </button>
53
- * <Show when={count() > 0}>
54
- * <div>Count: {count()}</div>
55
- * </Show>
56
- * </div>
57
- * )
58
- * }
59
- * ```
60
- */
61
- declare function shadow(): PluginOption;
62
-
63
- export { shadow as default };
package/dist/index.js DELETED
@@ -1,57 +0,0 @@
1
- import { transformSource } from '@shadow-js/compiler';
2
- import { transform } from '@swc/core';
3
-
4
- // src/index.ts
5
- function shadow() {
6
- return {
7
- name: "@shadow-js/vite",
8
- enforce: "pre",
9
- // Prevent esbuild from also transforming JSX to avoid double transforms.
10
- config() {
11
- return {
12
- esbuild: {
13
- jsx: "preserve"
14
- }
15
- };
16
- },
17
- async transform(code, id) {
18
- if (!/\.(tsx|jsx)$/.test(id)) return null;
19
- if (id.includes("node_modules")) return null;
20
- let transformedCode;
21
- try {
22
- transformedCode = transformSource(code);
23
- } catch (e) {
24
- const msg = e instanceof Error ? e.message : String(e);
25
- throw new Error(`ShadowJS (vite): compiler failed for ${id}: ${msg}`);
26
- }
27
- try {
28
- const result = await transform(transformedCode, {
29
- filename: id,
30
- jsc: {
31
- parser: { syntax: "typescript", tsx: true },
32
- transform: {
33
- react: {
34
- runtime: "automatic",
35
- importSource: "@shadow-js/core"
36
- }
37
- },
38
- target: "es2022"
39
- },
40
- module: { type: "es6" },
41
- sourceMaps: true
42
- });
43
- return {
44
- code: result.code,
45
- map: result.map ?? null
46
- };
47
- } catch (e) {
48
- const msg = e instanceof Error ? e.message : String(e);
49
- throw new Error(`ShadowJS (vite): SWC failed for ${id}: ${msg}`);
50
- }
51
- }
52
- };
53
- }
54
-
55
- export { shadow as default };
56
- //# sourceMappingURL=index.js.map
57
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["swcTransform"],"mappings":";;;;AA8De,SAAR,MAAA,GAAwC;AAC7C,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,iBAAA;AAAA,IACN,OAAA,EAAS,KAAA;AAAA;AAAA,IAGT,MAAA,GAAS;AACP,MAAA,OAAO;AAAA,QACL,OAAA,EAAS;AAAA,UACP,GAAA,EAAK;AAAA;AACP,OACF;AAAA,IACF,CAAA;AAAA,IAEA,MAAM,SAAA,CAAU,IAAA,EAAM,EAAA,EAAI;AAExB,MAAA,IAAI,CAAC,cAAA,CAAe,IAAA,CAAK,EAAE,GAAG,OAAO,IAAA;AACrC,MAAA,IAAI,EAAA,CAAG,QAAA,CAAS,cAAc,CAAA,EAAG,OAAO,IAAA;AAGxC,MAAA,IAAI,eAAA;AACJ,MAAA,IAAI;AACF,QAAA,eAAA,GAAkB,gBAAgB,IAAI,CAAA;AAAA,MACxC,SAAS,CAAA,EAAG;AACV,QAAA,MAAM,MAAM,CAAA,YAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU,OAAO,CAAC,CAAA;AACrD,QAAA,MAAM,IAAI,KAAA,CAAM,CAAA,qCAAA,EAAwC,EAAE,CAAA,EAAA,EAAK,GAAG,CAAA,CAAE,CAAA;AAAA,MACtE;AAGA,MAAA,IAAI;AACF,QAAA,MAAM,MAAA,GAAS,MAAMA,SAAA,CAAa,eAAA,EAAiB;AAAA,UACjD,QAAA,EAAU,EAAA;AAAA,UACV,GAAA,EAAK;AAAA,YACH,MAAA,EAAQ,EAAE,MAAA,EAAQ,YAAA,EAAc,KAAK,IAAA,EAAK;AAAA,YAC1C,SAAA,EAAW;AAAA,cACT,KAAA,EAAO;AAAA,gBACL,OAAA,EAAS,WAAA;AAAA,gBACT,YAAA,EAAc;AAAA;AAChB,aACF;AAAA,YACA,MAAA,EAAQ;AAAA,WACV;AAAA,UACA,MAAA,EAAQ,EAAE,IAAA,EAAM,KAAA,EAAM;AAAA,UACtB,UAAA,EAAY;AAAA,SACb,CAAA;AAED,QAAA,OAAO;AAAA,UACL,MAAM,MAAA,CAAO,IAAA;AAAA,UACb,GAAA,EAAK,OAAO,GAAA,IAAO;AAAA,SACrB;AAAA,MACF,SAAS,CAAA,EAAG;AACV,QAAA,MAAM,MAAM,CAAA,YAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU,OAAO,CAAC,CAAA;AACrD,QAAA,MAAM,IAAI,KAAA,CAAM,CAAA,gCAAA,EAAmC,EAAE,CAAA,EAAA,EAAK,GAAG,CAAA,CAAE,CAAA;AAAA,MACjE;AAAA,IACF;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import type { PluginOption } from \"vite\";\nimport { transformSource } from \"@shadow-js/compiler\";\nimport { transform as swcTransform } from \"@swc/core\";\n\n/**\n * Shadow Vite Plugin\n *\n * This plugin integrates Shadow with Vite to provide seamless development experience.\n * It handles the complete transformation pipeline from TSX/JSX source code to\n * Shadow-compatible JavaScript with reactive expressions.\n *\n * Plugin Pipeline:\n * 1. **Shadow Compiler**: Applies JSX transformations to inject reactive functions\n * 2. **SWC Transformation**: Converts TypeScript/JSX to JavaScript with proper imports\n * 3. **JSX Runtime Injection**: Automatically imports Shadow's JSX runtime functions\n * 4. **Source Map Generation**: Preserves debugging capabilities\n *\n * Features:\n * - **Selective Processing**: Only transforms user code (excludes node_modules)\n * - **TypeScript Support**: Full TypeScript and TSX compilation\n * - **Hot Module Replacement**: Compatible with Vite's HMR system\n * - **Error Handling**: Provides clear error messages for compilation failures\n * - **Performance**: Uses fast SWC compiler for optimal build speeds\n *\n * The plugin automatically configures Vite to preserve JSX for SWC processing\n * instead of using esbuild's JSX transform, ensuring compatibility with Shadow's\n * reactive programming model.\n *\n * @returns Vite PluginOption instance for Shadow integration\n *\n * @example\n * ```typescript\n * // vite.config.ts\n * import { defineConfig } from \"vite\";\n * import shadow from \"@shadow-js/vite\";\n *\n * export default defineConfig({\n * plugins: [shadow()]\n * })\n * ```\n *\n * @example\n * ```typescript\n * // Your component file (App.tsx)\n * import { useStore, Show } from \"@shadow-js/core\";\n *\n * function App() {\n * const [count, setCount] = useStore(0)\n *\n * return (\n * <div>\n * <button onClick={() => setCount((c) => c + 1)}>\n * Increment\n * </button>\n * <Show when={count() > 0}>\n * <div>Count: {count()}</div>\n * </Show>\n * </div>\n * )\n * }\n * ```\n */\nexport default function shadow(): PluginOption {\n return {\n name: \"@shadow-js/vite\",\n enforce: \"pre\",\n\n // Prevent esbuild from also transforming JSX to avoid double transforms.\n config() {\n return {\n esbuild: {\n jsx: \"preserve\",\n },\n };\n },\n\n async transform(code, id) {\n // Only TSX/JSX user files\n if (!/\\.(tsx|jsx)$/.test(id)) return null;\n if (id.includes(\"node_modules\")) return null;\n\n // 1) Apply Shadow compiler transforms on source text\n let transformedCode: string;\n try {\n transformedCode = transformSource(code);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n throw new Error(`ShadowJS (vite): compiler failed for ${id}: ${msg}`);\n }\n\n // 2) Use SWC to handle TS/JSX -> JS and inject jsx runtime imports\n try {\n const result = await swcTransform(transformedCode, {\n filename: id,\n jsc: {\n parser: { syntax: \"typescript\", tsx: true },\n transform: {\n react: {\n runtime: \"automatic\",\n importSource: \"@shadow-js/core\",\n },\n },\n target: \"es2022\",\n },\n module: { type: \"es6\" },\n sourceMaps: true,\n });\n\n return {\n code: result.code,\n map: result.map ?? null,\n };\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n throw new Error(`ShadowJS (vite): SWC failed for ${id}: ${msg}`);\n }\n },\n } satisfies PluginOption;\n}\n"]}