@kiln-js/vite-plugin 0.1.5 → 0.1.6

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/README.md ADDED
@@ -0,0 +1,42 @@
1
+ # @kiln-js/vite-plugin
2
+
3
+ [![npm](https://img.shields.io/npm/v/%40kiln-js%2Fvite-plugin)](https://www.npmjs.com/package/@kiln-js/vite-plugin)
4
+ [![license](https://img.shields.io/npm/l/%40kiln-js%2Fvite-plugin)](LICENSE)
5
+
6
+ Part of the Kiln framework.
7
+
8
+ Part of [Kiln](https://github.com/kiln-js/kiln), a file-based server-side rendering framework for React and Vite.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ bun add -d @kiln-js/vite-plugin
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ```ts
19
+ import { defineConfig } from "vite";
20
+ import { kiln } from "@kiln-js/vite-plugin";
21
+
22
+ export default defineConfig({
23
+ plugins: [...kiln({ pagesDir: "app/pages", apiDir: "app/api" })],
24
+ });
25
+ ```
26
+
27
+ ## What it provides
28
+
29
+ The route table (`virtual:kiln-routes`), the `<kiln:title>` rewrite, the entry prelude, and the server-only import guard.
30
+ The Kiln CLI calls `kiln()` for you, so add it yourself only when you run Vite without the CLI.
31
+
32
+ ## Documentation
33
+
34
+ See the [Kiln repository](https://github.com/kiln-js/kiln) for the full API reference and guides.
35
+
36
+ ## Development
37
+
38
+ This repository is generated from the Kiln monorepo. Make changes there, then run `scripts/publish-repo.ps1` to publish them here. Report issues in this repository, and send pull requests to the monorepo.
39
+
40
+ ## License
41
+
42
+ MIT
package/dist/index.d.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import type { PluginOption } from "vite";
2
- export interface KilnPlugin {
2
+ export interface KilnPluginSpec {
3
3
  name: string;
4
4
  vite?: () => PluginOption[];
5
5
  }
6
- export interface KilnConfig {
7
- plugins?: KilnPlugin[];
8
- }
9
6
  export interface KilnOptions {
10
7
  pagesDir?: string;
11
8
  apiDir?: string;
9
+ appDir?: string;
10
+ plugins?: KilnPluginSpec[];
12
11
  }
13
- export declare function defineConfig<T extends KilnConfig>(config: T): T;
12
+ export declare function rewriteTitleTags(code: string): string;
13
+ export declare function stripServerCode(code: string, parse: (c: string) => any): string | null;
14
+ export declare function islandCode(code: string, parse: (c: string) => any, islandId: string): string | null;
14
15
  export declare function kiln(opts?: KilnOptions): PluginOption[];
package/dist/index.js CHANGED
@@ -1,75 +1,277 @@
1
- // src/index.ts
1
+ // packages/vite-plugin/src/index.ts
2
+ import fs from "node:fs";
2
3
  import path from "node:path";
3
4
  import react from "@vitejs/plugin-react";
4
- import { scanRoutes, scanApi } from "@kiln-js/core/scan";
5
+ import { scanRoutes, scanApi, scanSpecials } from "@kiln-js/core/scan";
5
6
  var VIRTUAL = "virtual:kiln-routes";
6
- var RESOLVED = "\x00" + VIRTUAL;
7
+ var VIRTUAL_ISLANDS = "virtual:kiln-islands";
8
+ var RESOLVED = "\0" + VIRTUAL;
9
+ var RESOLVED_ISLANDS = "\0" + VIRTUAL_ISLANDS;
7
10
  var SERVER_FILE = /\.server(\.[jt]sx?)?$/;
8
11
  var ENTRY_FILE = /[\\/](app|\.kiln)[\\/](client|server)\.(tsx|ts|jsx|js)$/;
9
- var PRELUDE = `import __kilnRoutes, { api as __kilnApi } from "${VIRTUAL}";
12
+ var ISLAND_DIRECTIVE = /^\s*(?:\/\/[^\n]*\n\s*)*(["'])use island\1/;
13
+ var SERVER_EXPORTS = /* @__PURE__ */ new Set(["loader", "action", "revalidate"]);
14
+ var PRELUDE = `import __kilnRoutes, { api as __kilnApi, specials as __kilnSpecials } from "${VIRTUAL}";
15
+ import __kilnIslands from "${VIRTUAL_ISLANDS}";
10
16
  globalThis.__KILN_ROUTES__ = __kilnRoutes;
11
17
  globalThis.__KILN_API__ = __kilnApi;
18
+ globalThis.__KILN_SPECIALS__ = __kilnSpecials;
19
+ globalThis.__KILN_ISLANDS__ = __kilnIslands;
12
20
  `;
13
21
  var TITLE_IMPORT = `import { Title as KilnTitle } from "@kiln-js/core";
14
22
  `;
15
23
  var norm = (p) => p.replace(/\\/g, "/");
16
- function defineConfig(config) {
17
- return config;
24
+ function rewriteTitleTags(code) {
25
+ const n = code.length;
26
+ let out = "";
27
+ let i = 0;
28
+ const isStart = (k) => {
29
+ const c = code[k];
30
+ if (c === '"' || c === "'" || c === "`") return true;
31
+ return c === "/" && (code[k + 1] === "/" || code[k + 1] === "*");
32
+ };
33
+ while (i < n) {
34
+ let j = i;
35
+ while (j < n && !isStart(j)) j++;
36
+ out += code.slice(i, j).replace(/<(\/?)kiln:title\b/g, "<$1KilnTitle");
37
+ i = j;
38
+ if (i >= n) break;
39
+ const c = code[i];
40
+ let end;
41
+ if (c === "/" && code[i + 1] === "/") {
42
+ end = code.indexOf("\n", i);
43
+ if (end === -1) end = n;
44
+ } else if (c === "/" && code[i + 1] === "*") {
45
+ end = code.indexOf("*/", i + 2);
46
+ end = end === -1 ? n : end + 2;
47
+ } else if (c === "`") {
48
+ end = i + 1;
49
+ while (end < n && code[end] !== "`") end += code[end] === "\\" ? 2 : 1;
50
+ end = Math.min(end + 1, n);
51
+ } else {
52
+ end = i + 1;
53
+ while (end < n && code[end] !== c && code[end] !== "\n") end += code[end] === "\\" ? 2 : 1;
54
+ if (end < n && code[end] === c) end += 1;
55
+ }
56
+ out += code.slice(i, end);
57
+ i = end;
58
+ }
59
+ return out;
60
+ }
61
+ function declaredNames(decl) {
62
+ if (decl.type === "FunctionDeclaration") return decl.id ? [decl.id.name] : [];
63
+ if (decl.type === "VariableDeclaration") {
64
+ return decl.declarations.flatMap((d) => d.id.type === "Identifier" ? [d.id.name] : []);
65
+ }
66
+ return [];
67
+ }
68
+ function collectIdentifiers(nodes) {
69
+ const names = /* @__PURE__ */ new Set();
70
+ const visit = (node) => {
71
+ if (!node || typeof node !== "object") return;
72
+ if (Array.isArray(node)) {
73
+ node.forEach(visit);
74
+ return;
75
+ }
76
+ if (node.type === "Identifier") names.add(node.name);
77
+ for (const key of Object.keys(node)) {
78
+ if (key === "type" || key === "start" || key === "end" || key === "loc") continue;
79
+ visit(node[key]);
80
+ }
81
+ };
82
+ nodes.forEach(visit);
83
+ return names;
84
+ }
85
+ function applyEdits(code, edits) {
86
+ let out = code;
87
+ for (const e of [...edits].sort((a, b) => b.start - a.start)) {
88
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
89
+ }
90
+ return out;
91
+ }
92
+ function rebuildImport(node, used) {
93
+ const specifiers = node.specifiers;
94
+ if (specifiers.length === 0) return null;
95
+ const keep = specifiers.filter((s) => used.has(s.local.name));
96
+ if (keep.length === specifiers.length) return null;
97
+ if (keep.length === 0) return "";
98
+ const parts = [];
99
+ const def = keep.find((s) => s.type === "ImportDefaultSpecifier");
100
+ const ns = keep.find((s) => s.type === "ImportNamespaceSpecifier");
101
+ const named = keep.filter((s) => s.type === "ImportSpecifier");
102
+ if (def) parts.push(def.local.name);
103
+ if (ns) parts.push(`* as ${ns.local.name}`);
104
+ if (named.length) {
105
+ const list = named.map((s) => {
106
+ const imported = s.imported.name ?? s.imported.value;
107
+ return imported === s.local.name ? imported : `${imported} as ${s.local.name}`;
108
+ });
109
+ parts.push(`{ ${list.join(", ")} }`);
110
+ }
111
+ return `import ${parts.join(", ")} from ${JSON.stringify(node.source.value)};`;
112
+ }
113
+ function stripServerCode(code, parse) {
114
+ const program = parse(code);
115
+ const edits = [];
116
+ for (const node of program.body) {
117
+ if (node.type !== "ExportNamedDeclaration" || !node.declaration) continue;
118
+ if (declaredNames(node.declaration).some((n) => SERVER_EXPORTS.has(n))) {
119
+ edits.push({ start: node.start, end: node.end, text: "" });
120
+ }
121
+ }
122
+ if (edits.length === 0) return null;
123
+ const stripped = applyEdits(code, edits);
124
+ const next = parse(stripped);
125
+ const used = collectIdentifiers(next.body.filter((n) => n.type !== "ImportDeclaration"));
126
+ const importEdits = [];
127
+ for (const node of next.body) {
128
+ if (node.type !== "ImportDeclaration") continue;
129
+ const text = rebuildImport(node, used);
130
+ if (text !== null) importEdits.push({ start: node.start, end: node.end, text });
131
+ }
132
+ return applyEdits(stripped, importEdits);
133
+ }
134
+ function islandCode(code, parse, islandId2) {
135
+ const program = parse(code);
136
+ const def = program.body.find((n) => n.type === "ExportDefaultDeclaration");
137
+ if (!def) return null;
138
+ const decl = def.declaration;
139
+ let raw;
140
+ const edits = [];
141
+ if (decl.type === "FunctionDeclaration" && decl.id) {
142
+ raw = decl.id.name;
143
+ edits.push({ start: def.start, end: decl.start, text: "" });
144
+ } else if (decl.type === "Identifier") {
145
+ raw = decl.name;
146
+ edits.push({ start: def.start, end: def.end, text: "" });
147
+ } else {
148
+ raw = "__KilnIslandRaw";
149
+ edits.push({ start: def.start, end: decl.start, text: `const ${raw} = ` });
150
+ }
151
+ return applyEdits(code, edits) + `
152
+ import { island as __kilnIsland } from "@kiln-js/core";
153
+ export const __kilnRaw = ${raw};
154
+ export default __kilnIsland(${JSON.stringify(islandId2)}, ${raw});
155
+ `;
156
+ }
157
+ function sourceFiles(dir, out = []) {
158
+ if (!fs.existsSync(dir)) return out;
159
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
160
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist") continue;
161
+ const full = path.join(dir, entry.name);
162
+ if (entry.isDirectory()) sourceFiles(full, out);
163
+ else if (/\.[jt]sx?$/.test(entry.name) && !SERVER_FILE.test(entry.name)) out.push(full);
164
+ }
165
+ return out;
18
166
  }
19
- function routesPlugin(pagesDir, apiDir) {
167
+ var islandId = (file) => norm(path.relative(process.cwd(), file));
168
+ function islandFiles(appDir) {
169
+ return sourceFiles(appDir).filter((f) => ISLAND_DIRECTIVE.test(fs.readFileSync(f, "utf8")));
170
+ }
171
+ function postPlugin(pagesDir, appDir) {
172
+ const pagesPrefix = norm(pagesDir) + "/";
173
+ const appPrefix = norm(appDir) + "/";
174
+ return {
175
+ name: "kiln:compile-server-split",
176
+ enforce: "post",
177
+ transform(code, rawId, options) {
178
+ const file = norm(rawId.split("?")[0]);
179
+ if (!/\.[jt]sx?$/.test(file) || file.includes("/node_modules/")) return;
180
+ const parse = (c) => this.parse(c);
181
+ let out = code;
182
+ let changed = false;
183
+ if (!options?.ssr && file.startsWith(pagesPrefix) && !SERVER_FILE.test(file) && /\b(loader|action|revalidate)\b/.test(out)) {
184
+ const next = stripServerCode(out, parse);
185
+ if (next !== null) {
186
+ out = next;
187
+ changed = true;
188
+ }
189
+ }
190
+ if (file.startsWith(appPrefix) && !SERVER_FILE.test(file)) {
191
+ let isIsland = false;
192
+ try {
193
+ isIsland = ISLAND_DIRECTIVE.test(fs.readFileSync(file, "utf8"));
194
+ } catch {
195
+ isIsland = false;
196
+ }
197
+ if (isIsland) {
198
+ const next = islandCode(out, parse, islandId(file));
199
+ if (next !== null) {
200
+ out = next;
201
+ changed = true;
202
+ }
203
+ }
204
+ }
205
+ return changed ? { code: out, map: null } : void 0;
206
+ }
207
+ };
208
+ }
209
+ var specialEntry = (r) => `{ pattern: ${JSON.stringify(r.pattern)}, load: () => import(${JSON.stringify(r.file)}), layouts: [${r.layouts.map((f) => `() => import(${JSON.stringify(f)})`).join(", ")}] }`;
210
+ function routesPlugin(pagesDir, apiDir, appDir) {
20
211
  const pagesPrefix = norm(pagesDir) + "/";
21
212
  const apiPrefix = norm(apiDir) + "/";
22
213
  return {
23
214
  name: "kiln:routes",
215
+ // Runs before Vite compiles JSX, so <kiln:title> is still visible.
24
216
  enforce: "pre",
25
217
  resolveId(source, _importer, options) {
26
- if (source === VIRTUAL)
27
- return RESOLVED;
218
+ if (source === VIRTUAL) return RESOLVED;
219
+ if (source === VIRTUAL_ISLANDS) return RESOLVED_ISLANDS;
28
220
  if (!options?.ssr && SERVER_FILE.test(source)) {
29
221
  this.error(`"${source}" is server-only and cannot be imported by client code.`);
30
222
  }
31
223
  },
32
224
  load(id, options) {
33
- if (id !== RESOLVED)
34
- return;
35
225
  const ssr = !!options?.ssr;
226
+ if (id === RESOLVED_ISLANDS) {
227
+ if (ssr) return "export default {};\n";
228
+ const entries = islandFiles(appDir).map(
229
+ (f) => `${JSON.stringify(islandId(f))}: () => import(${JSON.stringify(norm(f))}).then((m) => ({ default: m.__kilnRaw }))`
230
+ );
231
+ return `export default {
232
+ ${entries.join(",\n ")}
233
+ };
234
+ `;
235
+ }
236
+ if (id !== RESOLVED) return;
36
237
  const pages = scanRoutes(pagesDir).map((r) => {
37
238
  const importable = ssr ? r.mode !== "client" : r.mode !== "server";
38
239
  const load = importable ? `() => import(${JSON.stringify(r.file)})` : "null";
39
240
  const layouts = r.layouts.map((f) => `() => import(${JSON.stringify(f)})`);
40
241
  return `{ pattern: ${JSON.stringify(r.pattern)}, mode: ${JSON.stringify(r.mode)}, load: ${load}, layouts: [${layouts.join(", ")}] }`;
41
242
  });
42
- const apis = ssr ? scanApi(apiDir).map((r) => `{ pattern: ${JSON.stringify(r.pattern)}, load: () => import(${JSON.stringify(r.file)}) }`) : [];
243
+ const apis = ssr ? scanApi(apiDir).map(
244
+ (r) => `{ pattern: ${JSON.stringify(r.pattern)}, load: () => import(${JSON.stringify(r.file)}) }`
245
+ ) : [];
246
+ const specials = ssr ? `{ errors: [${scanSpecials(pagesDir, "_error").map(specialEntry).join(", ")}], notFounds: [${scanSpecials(pagesDir, "_not-found").map(specialEntry).join(", ")}] }` : `{ errors: [], notFounds: [] }`;
43
247
  return `export default [
44
- ${pages.join(`,
45
- `)}
248
+ ${pages.join(",\n ")}
46
249
  ];
47
250
 
48
251
  export const api = [
49
- ${apis.join(`,
50
- `)}
252
+ ${apis.join(",\n ")}
51
253
  ];
254
+
255
+ export const specials = ${specials};
52
256
  `;
53
257
  },
54
258
  transform(code, rawId) {
55
- const id = rawId.split("?")[0];
56
- const file = norm(id);
57
- if (file.startsWith(pagesPrefix) && /\.(tsx|jsx)$/.test(file) && code.includes("<kiln:title")) {
58
- const rewritten = code.replace(/<kiln:title>/g, "<KilnTitle>").replace(/<\/kiln:title>/g, "</KilnTitle>");
59
- return { code: TITLE_IMPORT + rewritten, map: null };
60
- }
61
- if (ENTRY_FILE.test(file)) {
62
- return { code: PRELUDE + code, map: null };
259
+ const file = norm(rawId.split("?")[0]);
260
+ const isMarkdownModule = file.endsWith(".kiln-md.tsx");
261
+ if (!isMarkdownModule && file.startsWith(pagesPrefix) && /\.(tsx|jsx)$/.test(file) && code.includes("<kiln:title")) {
262
+ const rewritten = rewriteTitleTags(code);
263
+ if (rewritten !== code) return { code: TITLE_IMPORT + rewritten, map: null };
63
264
  }
265
+ if (ENTRY_FILE.test(file)) return { code: PRELUDE + code, map: null };
64
266
  },
65
267
  configureServer(server) {
66
268
  const onChange = (file) => {
67
269
  const f = norm(file);
68
- if (!f.startsWith(pagesPrefix) && !f.startsWith(apiPrefix))
69
- return;
70
- const mod = server.moduleGraph.getModuleById(RESOLVED);
71
- if (mod)
72
- server.moduleGraph.invalidateModule(mod);
270
+ if (!f.startsWith(pagesPrefix) && !f.startsWith(apiPrefix) && !f.startsWith(norm(appDir) + "/")) return;
271
+ for (const id of [RESOLVED, RESOLVED_ISLANDS]) {
272
+ const mod = server.moduleGraph.getModuleById(id);
273
+ if (mod) server.moduleGraph.invalidateModule(mod);
274
+ }
73
275
  server.ws.send({ type: "full-reload" });
74
276
  };
75
277
  server.watcher.on("add", onChange);
@@ -80,9 +282,13 @@ export const api = [
80
282
  function kiln(opts = {}) {
81
283
  const pagesDir = path.resolve(opts.pagesDir ?? "app/pages");
82
284
  const apiDir = path.resolve(opts.apiDir ?? "app/api");
83
- return [react(), routesPlugin(pagesDir, apiDir)];
285
+ const appDir = path.resolve(opts.appDir ?? "app");
286
+ const extra = (opts.plugins ?? []).flatMap((p) => p.vite?.() ?? []);
287
+ return [react(), routesPlugin(pagesDir, apiDir, appDir), postPlugin(pagesDir, appDir), ...extra];
84
288
  }
85
289
  export {
86
- defineConfig,
87
- kiln
290
+ islandCode,
291
+ kiln,
292
+ rewriteTitleTags,
293
+ stripServerCode
88
294
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kiln-js/vite-plugin",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -16,7 +16,7 @@
16
16
  "typecheck": "tsc -p tsconfig.json --noEmit"
17
17
  },
18
18
  "dependencies": {
19
- "@kiln-js/core": "^0.1.4",
19
+ "@kiln-js/core": "^0.1.5",
20
20
  "@vitejs/plugin-react": "^4.3.0"
21
21
  },
22
22
  "peerDependencies": {