@farm.js/islx 0.0.4 → 0.0.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.
@@ -0,0 +1,506 @@
1
+ import { i as transformActions, r as hasModuleDirective, t as ActionCompileError } from "./actions-Eutk6UzT.mjs";
2
+ import { t as ISLAND_STRATEGIES } from "./schedule-CjoybS3b.mjs";
3
+ import { randomBytes } from "node:crypto";
4
+ import path from "node:path";
5
+ import { walk } from "estree-walker";
6
+ import MagicString from "magic-string";
7
+ import { analyze } from "periscopic";
8
+ import { readFile, readdir, writeFile } from "node:fs/promises";
9
+ // src/compiler/client.ts
10
+ /**
11
+ * The `"use client"` compiler. In the server build, every component a `"use client"` module
12
+ * exports renders as an island: its server HTML, and its props for the browser. The browser build
13
+ * keeps the module as it is.
14
+ *
15
+ * A component is an export named in PascalCase (`Chart`, not `COLORS` or `useChart`) that is not
16
+ * a literal value, or the default export. Other exports (hooks, constants, helpers) stay as they
17
+ * are on both sides.
18
+ *
19
+ * When an island hydrates comes from the module's `hydrate` export:
20
+ *
21
+ * export const hydrate = "visible"; // every component in the file
22
+ * export const hydrate = { Chart: "visible", Legend: "idle" }; // per component; others "load"
23
+ */
24
+ const FUNCTION_TYPES = /* @__PURE__ */ new Set([
25
+ "FunctionDeclaration",
26
+ "FunctionExpression",
27
+ "ArrowFunctionExpression"
28
+ ]);
29
+ function isComponentName(name) {
30
+ return /^[A-Z]/.test(name) && /[a-z]/.test(name);
31
+ }
32
+ const VALUE_TYPES = /* @__PURE__ */ new Set([
33
+ "Literal",
34
+ "ArrayExpression",
35
+ "ObjectExpression",
36
+ "TemplateLiteral",
37
+ "UnaryExpression",
38
+ "BinaryExpression"
39
+ ]);
40
+ /** Reads the `hydrate` export: a strategy for every component, or one per component. */
41
+ function readStrategies(program, fail) {
42
+ const byName = /* @__PURE__ */ new Map();
43
+ const check = (value, node) => {
44
+ if (typeof value !== "string" || !ISLAND_STRATEGIES.includes(value)) fail(`hydrate must be one of ${ISLAND_STRATEGIES.map((s) => `"${s}"`).join(", ")}`, node);
45
+ return value;
46
+ };
47
+ for (const node of program.body ?? []) {
48
+ if (node.type !== "ExportNamedDeclaration" || node.declaration?.type !== "VariableDeclaration") continue;
49
+ for (const declarator of node.declaration.declarations ?? []) {
50
+ if (declarator.id?.type !== "Identifier" || declarator.id.name !== "hydrate") continue;
51
+ let init = declarator.init;
52
+ while (init && (init.type === "TSAsExpression" || init.type === "TSSatisfiesExpression")) init = init.expression;
53
+ if (init?.type === "Literal") return {
54
+ all: check(init.value, init),
55
+ byName
56
+ };
57
+ if (init?.type === "ObjectExpression") {
58
+ for (const property of init.properties ?? []) {
59
+ const key = property.key?.type === "Identifier" ? property.key.name : property.key?.value;
60
+ if (property.type !== "Property" || property.computed || typeof key !== "string" || property.value?.type !== "Literal") fail("hydrate must be a string, or an object of strings: { Chart: \"visible\" }", property);
61
+ byName.set(key, check(property.value.value, property.value));
62
+ }
63
+ return { byName };
64
+ }
65
+ fail("hydrate must be written as a literal: \"visible\", or { Chart: \"visible\" }", declarator);
66
+ }
67
+ }
68
+ return { byName };
69
+ }
70
+ /** Wraps a `"use client"` module's components as islands, or returns null for any other module. */
71
+ function transformClientModule(options) {
72
+ const { code, id, root } = options;
73
+ if (!hasModuleDirective(code, options.directive ?? "use client")) return null;
74
+ const file = id.split("?", 1)[0];
75
+ const relative = path.relative(root, file).split(path.sep).join("/");
76
+ const program = options.parse(code);
77
+ const fail = (message, node) => {
78
+ throw new ActionCompileError(message, file, code, node.start);
79
+ };
80
+ const strategies = readStrategies(program, fail);
81
+ const strategyOf = (name) => {
82
+ const configured = options.strategy?.(name);
83
+ if (configured !== void 0 && !ISLAND_STRATEGIES.includes(configured)) throw new Error(`islx: strategy for ${name} must be one of ${ISLAND_STRATEGIES.join(", ")}`);
84
+ return configured ?? strategies.byName.get(name) ?? strategies.all ?? "load";
85
+ };
86
+ const output = new MagicString(code);
87
+ const wrapped = [];
88
+ for (const node of program.body ?? []) if (node.type === "ExportNamedDeclaration" && !node.source && node.exportKind !== "type") {
89
+ const declaration = node.declaration;
90
+ if (declaration) {
91
+ const names = declaration.type === "VariableDeclaration" ? declaration.declarations.flatMap((d) => d.id?.type === "Identifier" && !(d.init && VALUE_TYPES.has(d.init.type)) ? [d.id.name] : []) : declaration.id?.name ? [declaration.id.name] : [];
92
+ const declared = declaration.type === "VariableDeclaration" ? declaration.declarations.length : names.length;
93
+ const components = names.filter(isComponentName);
94
+ if (components.length === 0 || String(declaration.type).startsWith("TS")) continue;
95
+ if (components.length !== declared) fail("Export components and other values in separate statements", declaration);
96
+ output.remove(node.start, declaration.start);
97
+ for (const name of components) wrapped.push({
98
+ local: name,
99
+ exportName: name
100
+ });
101
+ continue;
102
+ }
103
+ const kept = [];
104
+ for (const specifier of node.specifiers ?? []) {
105
+ const exported = specifier.exported?.name ?? specifier.exported?.value;
106
+ const local = specifier.local?.name ?? specifier.local?.value;
107
+ if (specifier.exportKind !== "type" && (isComponentName(exported) || exported === "default")) wrapped.push({
108
+ local,
109
+ exportName: exported
110
+ });
111
+ else kept.push(output.slice(specifier.start, specifier.end));
112
+ }
113
+ output.overwrite(node.start, node.end, kept.length > 0 ? `export { ${kept.join(", ")} };` : "");
114
+ } else if (node.type === "ExportDefaultDeclaration") {
115
+ const declaration = node.declaration;
116
+ if (FUNCTION_TYPES.has(declaration.type) || declaration.type === "ClassDeclaration" || declaration.type === "ClassExpression") {
117
+ if (declaration.id?.name) {
118
+ output.remove(node.start, declaration.start);
119
+ wrapped.push({
120
+ local: declaration.id.name,
121
+ exportName: "default"
122
+ });
123
+ } else {
124
+ output.overwrite(node.start, declaration.start, "const $$islx_default = ");
125
+ wrapped.push({
126
+ local: "$$islx_default",
127
+ exportName: "default"
128
+ });
129
+ }
130
+ } else if (declaration.type === "Identifier" || declaration.type.endsWith("Expression")) {
131
+ output.overwrite(node.start, declaration.start, "const $$islx_default = ");
132
+ if (!code.slice(declaration.end, node.end).includes(";")) output.appendLeft(declaration.end, ";");
133
+ wrapped.push({
134
+ local: "$$islx_default",
135
+ exportName: "default"
136
+ });
137
+ }
138
+ }
139
+ if (wrapped.length === 0) return null;
140
+ const runtime = options.runtime ?? "@farm.js/islx/react";
141
+ const src = options.reference(relative);
142
+ const lines = [...wrapped.map(({ local, exportName }, index) => {
143
+ return `const $$islx_island_${index} = $$islx_island(${local}, ${src}, ${JSON.stringify(exportName)}, ${JSON.stringify(strategyOf(exportName === "default" ? "default" : exportName))});`;
144
+ }), `export { ${wrapped.map(({ exportName }, index) => `$$islx_island_${index} as ${exportName}`).join(", ")} };`];
145
+ const imports = [`import { createIsland as $$islx_island } from ${JSON.stringify(runtime)};`, ...(options.sideEffects ?? []).map((module) => `import ${JSON.stringify(module)};`)];
146
+ output.prepend(`${imports.join("\n")}\n`);
147
+ output.append(`\n${lines.join("\n")}\n`);
148
+ return {
149
+ code: output.toString(),
150
+ map: output.generateMap({
151
+ hires: true,
152
+ source: file
153
+ }),
154
+ islands: wrapped.map(({ exportName }) => ({
155
+ exportName,
156
+ strategy: strategyOf(exportName)
157
+ }))
158
+ };
159
+ }
160
+ // src/vite.ts
161
+ /**
162
+ * @farm.js/islx/vite: islx for Vite 6 and later (the Environment API).
163
+ *
164
+ * import react from "@vitejs/plugin-react";
165
+ * import { islx } from "@farm.js/islx/vite";
166
+ * export default defineConfig({ plugins: [react(), islx()] });
167
+ *
168
+ * - Server environments: `"use client"` components render as islands, `"use server"` exports
169
+ * and inline actions register.
170
+ * - The client environment: `"use server"` modules become references; inline actions are
171
+ * refused; the browser entry hydrates islands.
172
+ * - `vite build` builds the server first, which finds the client components pages use, then the
173
+ * browser with exactly those (plus `clientComponents.include`), each in a chunk of its own that
174
+ * the browser entry imports when an island needs it. An island names its module by its path
175
+ * from the root; the server build learns the entry's URL once the browser build has named it.
176
+ */
177
+ const RUNTIME_ID = "virtual:islx/runtime";
178
+ /** @internal The browser entry, for a framework whose own entry imports it. */
179
+ const ENTRY_ID = "virtual:islx/client-entry";
180
+ const LIBRARY_RUNTIME_ID = "virtual:islx/react-for-libraries";
181
+ const CLIENT_HOOKS_ID = "virtual:islx/hooks-client";
182
+ const SERVER_HOOKS_ID = "virtual:islx/hooks-server";
183
+ const BROWSER_GLOBALS = /* @__PURE__ */ new Set([
184
+ "window",
185
+ "document",
186
+ "location",
187
+ "history",
188
+ "navigator",
189
+ "screen",
190
+ "localStorage",
191
+ "sessionStorage",
192
+ "alert",
193
+ "confirm",
194
+ "prompt",
195
+ "requestAnimationFrame",
196
+ "cancelAnimationFrame",
197
+ "requestIdleCallback",
198
+ "cancelIdleCallback",
199
+ "IntersectionObserver",
200
+ "MutationObserver",
201
+ "ResizeObserver",
202
+ "HTMLElement",
203
+ "Element",
204
+ "Node",
205
+ "CustomEvent",
206
+ "Event",
207
+ "matchMedia",
208
+ "getComputedStyle",
209
+ "innerWidth",
210
+ "innerHeight",
211
+ "scrollX",
212
+ "scrollY",
213
+ "self"
214
+ ]);
215
+ /**
216
+ * The source of a hooks module made from callbacks. Each callback is copied as written, so it
217
+ * must not use anything from where it was written: an outside variable, an import.
218
+ */
219
+ function serializeHooks(hooks, where, parse) {
220
+ const entries = [];
221
+ for (const [name, value] of Object.entries(hooks)) {
222
+ if (value === void 0) continue;
223
+ if (typeof value !== "function") throw new Error(`islx: hooks.${where}.${name} must be a function`);
224
+ const source = Function.prototype.toString.call(value);
225
+ if (source.includes("[native code]")) throw new Error(`islx: hooks.${where}.${name} must be written in the config, not a built-in or bound function`);
226
+ const expression = parse("hook.js", `(${source});`).errors.length === 0;
227
+ entries.push(expression ? `${JSON.stringify(name)}: ${source}` : source);
228
+ }
229
+ const code = `export default {\n${entries.join(",\n")}\n};\n`;
230
+ const program = parse("hooks.js", code);
231
+ const { globals } = analyze(program);
232
+ const outside = [...globals.keys()].filter((name) => where === "client" ? !(name in globalThis) && !BROWSER_GLOBALS.has(name) : BROWSER_GLOBALS.has(name) || !(name in globalThis));
233
+ let imports = false;
234
+ walk(program, { enter(node) {
235
+ if (node.type === "ImportExpression") imports = true;
236
+ } });
237
+ if (outside.length > 0 || imports) {
238
+ const what = imports ? "`import()`" : outside.map((name) => `\`${name}\``).join(", ");
239
+ throw new Error(`islx: hooks.${where} uses ${what}, which does not exist where the hook runs: hooks written in the config are copied into the ${where === "client" ? "browser" : "server"} build as source. Use a global${where === "client" ? " (window.analytics)" : ""}, or put the hooks in a module and pass its path: hooks: { ${where}: "./src/islx.${where}.ts" }.`);
240
+ }
241
+ return code;
242
+ }
243
+ /** Stand for the browser entry's URL, and the files each client module needs, in the server
244
+ * build until the browser build names them. */
245
+ const ENTRY_PLACEHOLDER = "__islx_client_entry_url__";
246
+ const MODULES_PLACEHOLDER = "__islx_client_modules__";
247
+ const SCRIPT = /\.[cm]?[jt]sx?$/;
248
+ async function createParser() {
249
+ const withErrors = (result) => Object.assign(result.program, { errors: result.errors ?? [] });
250
+ const vite = await import("vite");
251
+ if (typeof vite.parseSync === "function") return (file, code) => withErrors(vite.parseSync(file, code));
252
+ try {
253
+ const oxc = await import("oxc-parser");
254
+ return (file, code) => withErrors(oxc.parseSync(file, code));
255
+ } catch {
256
+ throw new Error("@farm.js/islx/vite needs Vite 8, or oxc-parser installed with an older Vite");
257
+ }
258
+ }
259
+ /** A tiny glob matcher: `**`, `*` and `?`, on paths from the root. */
260
+ function globToRegExp(glob) {
261
+ let pattern = "";
262
+ for (let index = 0; index < glob.length; index++) {
263
+ const char = glob[index];
264
+ if (char === "*" && glob[index + 1] === "*") {
265
+ pattern += glob[index + 2] === "/" ? "(?:.*/)?" : ".*";
266
+ index += glob[index + 2] === "/" ? 2 : 1;
267
+ } else if (char === "*") pattern += "[^/]*";
268
+ else if (char === "?") pattern += "[^/]";
269
+ else pattern += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
270
+ }
271
+ return new RegExp(`^${pattern.replace(/^\.\//, "")}$`);
272
+ }
273
+ async function listFiles(root, directory = root) {
274
+ const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
275
+ const files = [];
276
+ for (const entry of entries) {
277
+ if (entry.name === "node_modules" || entry.name.startsWith(".") || entry.name === "dist") continue;
278
+ const full = path.join(directory, entry.name);
279
+ if (entry.isDirectory()) files.push(...await listFiles(root, full));
280
+ else if (SCRIPT.test(entry.name)) files.push(full);
281
+ }
282
+ return files;
283
+ }
284
+ async function listOutput(directory) {
285
+ const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
286
+ const files = [];
287
+ for (const entry of entries) {
288
+ const full = path.join(directory, entry.name);
289
+ if (entry.isDirectory()) files.push(...await listOutput(full));
290
+ else if (/\.[cm]?js$/.test(entry.name)) files.push(full);
291
+ }
292
+ return files;
293
+ }
294
+ const toPosix = (value) => value.split(path.sep).join("/");
295
+ const RESERVED_DIRECTIVES = /* @__PURE__ */ new Set(["use strict", "use asm"]);
296
+ /** The directives to use, refusing ones that would make a file mean two things. */
297
+ function resolveDirectives(directives = {}) {
298
+ const client = directives.client ?? "use client";
299
+ const server = directives.server ?? "use server";
300
+ for (const [kind, value] of [["client", client], ["server", server]]) if (typeof value !== "string" || !/^[\w-]+( [\w-]+)*$/.test(value) || RESERVED_DIRECTIVES.has(value)) throw new Error(`islx: directives.${kind} must be a plain directive such as "use island", not ${JSON.stringify(value)}`);
301
+ if (client === server) throw new Error(`islx: directives.client and directives.server are both ${JSON.stringify(client)}`);
302
+ return {
303
+ client,
304
+ server
305
+ };
306
+ }
307
+ function islx(options = {}, host = {}) {
308
+ const directives = resolveDirectives(options.directives);
309
+ let config;
310
+ let parse;
311
+ let preamble = false;
312
+ const include = (options.clientComponents?.include ?? []).map(globToRegExp);
313
+ const exclude = (options.clientComponents?.exclude ?? []).map(globToRegExp);
314
+ /** Client modules the server build rendered, by path from the root. */
315
+ const discovered = /* @__PURE__ */ new Set();
316
+ /** The browser entry's URL, once the browser build named it. */
317
+ let entryUrl;
318
+ /** The files each client module needs, once the browser build named them. */
319
+ const moduleFiles = {};
320
+ /** Whether the browser build ran first (a framework that orders the build). */
321
+ let clientBuilt = false;
322
+ const buildKey = randomBytes(32).toString("base64url");
323
+ const isServer = (name) => options.serverEnvironments ? options.serverEnvironments.includes(name) : name !== "client";
324
+ const relativeOf = (id) => toPosix(path.relative(config.root, id.split("?", 1)[0]));
325
+ const excluded = (relative) => exclude.some((pattern) => pattern.test(relative));
326
+ const isBuild = () => config.command === "build";
327
+ const clientInputs = async () => {
328
+ const inputs = new Set(discovered);
329
+ if (include.length > 0) for (const file of await listFiles(config.root)) {
330
+ const relative = relativeOf(file);
331
+ if (!include.some((pattern) => pattern.test(relative)) || excluded(relative)) continue;
332
+ if ((await readFile(file, "utf8")).includes("use client")) inputs.add(relative);
333
+ }
334
+ return [...inputs].sort();
335
+ };
336
+ return [
337
+ {
338
+ name: "islx",
339
+ enforce: "pre",
340
+ sharedDuringBuild: true,
341
+ config(user) {
342
+ const clientBuild = user.environments?.client?.build;
343
+ const input = clientBuild?.rollupOptions?.input;
344
+ return {
345
+ builder: user.builder ?? {},
346
+ environments: { client: {
347
+ optimizeDeps: { include: [
348
+ "react",
349
+ "react/jsx-runtime",
350
+ "react/jsx-dev-runtime",
351
+ "react-dom",
352
+ "react-dom/client"
353
+ ] },
354
+ build: {
355
+ outDir: clientBuild?.outDir ?? "dist/client",
356
+ rollupOptions: { input: host.frameworkEntry ? input : {
357
+ ...typeof input === "string" ? { index: input } : Array.isArray(input) ? Object.fromEntries(input.map((entry, index) => [`input${index}`, entry])) : input,
358
+ "islx-entry": ENTRY_ID
359
+ } }
360
+ }
361
+ } }
362
+ };
363
+ },
364
+ async configResolved(resolved) {
365
+ config = resolved;
366
+ parse = await createParser();
367
+ preamble = resolved.plugins.some((plugin) => plugin.name === "vite:react-virtual-preamble");
368
+ },
369
+ resolveId(id) {
370
+ if (id === LIBRARY_RUNTIME_ID) return this.resolve("@farm.js/islx/react", path.join(config.root, "package.json"), { skipSelf: true });
371
+ if (id === RUNTIME_ID || id === "virtual:islx/client-entry" || id === CLIENT_HOOKS_ID || id === SERVER_HOOKS_ID) return `\0${id}`;
372
+ },
373
+ async load(id) {
374
+ if (id === `\0${RUNTIME_ID}`) {
375
+ const entry = host.frameworkEntry ? void 0 : !isBuild() ? `${config.base}@id/__x00__${ENTRY_ID}` : clientBuilt ? entryUrl : ENTRY_PLACEHOLDER;
376
+ const modules = !isBuild() ? "{}" : clientBuilt ? JSON.stringify(moduleFiles) : `JSON.parse(${JSON.stringify(MODULES_PLACEHOLDER)})`;
377
+ return [
378
+ ...host.frameworkRender ? [`import "@farm.js/islx/react/server";`] : [],
379
+ `import { setBuildDefaults, setServerHooks } from "@farm.js/islx/server";`,
380
+ `import hooks from ${JSON.stringify(SERVER_HOOKS_ID)};`,
381
+ `setBuildDefaults({ entry: ${JSON.stringify(entry)}, key: ${JSON.stringify(buildKey)}, modules: ${modules} });`,
382
+ `setServerHooks(hooks);`
383
+ ].join("\n");
384
+ }
385
+ if (id === `\0${CLIENT_HOOKS_ID}` || id === `\0${SERVER_HOOKS_ID}`) {
386
+ const where = id === `\0${CLIENT_HOOKS_ID}` ? "client" : "server";
387
+ const hooks = options.hooks?.[where];
388
+ if (hooks === void 0) return "export default undefined;";
389
+ if (typeof hooks === "string") return `export { default } from ${JSON.stringify(path.resolve(config.root, hooks))};`;
390
+ return serializeHooks(hooks, where, parse);
391
+ }
392
+ if (id === `\0virtual:islx/client-entry`) {
393
+ const load = isBuild() ? `const modules = {\n${(await clientInputs()).map((relative) => ` ${JSON.stringify(relative)}: () => import(${JSON.stringify(path.resolve(config.root, relative))}),`).join("\n")}\n};\nconst load = (src) => modules[src] ? modules[src]() : Promise.reject(new Error("islx: no client module " + src));` : `const root = new URL(${JSON.stringify(`file://${toPosix(config.root)}/`)});\nconst load = (src) => import(/* @vite-ignore */ src.startsWith("../") ? "/@fs" + new URL(src, root).pathname : ${JSON.stringify(config.base)} + src);`;
394
+ return [
395
+ ...preamble && !isBuild() ? [`import "@vitejs/plugin-react/preamble";`] : [],
396
+ `import { createHydrationRuntime, refreshDocument, scheduleHydration, swapDocument } from "@farm.js/islx/react/client";`,
397
+ `import { enhanceForms, setActionNavigator, setClientHooks, startNavigation, navigate } from "@farm.js/islx/client";`,
398
+ `import hooks from ${JSON.stringify(CLIENT_HOOKS_ID)};`,
399
+ `setClientHooks(hooks);`,
400
+ load,
401
+ `const runtime = createHydrationRuntime({ load, schedule: scheduleHydration });`,
402
+ `setActionNavigator({ refresh: () => refreshDocument(runtime), navigate: (href) => navigate(href) });`,
403
+ `enhanceForms();`,
404
+ ...options.navigation === false ? [] : [`startNavigation({ swap: (next) => swapDocument(runtime, next), viewTransition: ${typeof options.navigation === "object" && options.navigation.viewTransition === true} });`],
405
+ `runtime.hydrate(document);`,
406
+ `export { runtime };`
407
+ ].join("\n");
408
+ }
409
+ },
410
+ transform(code, id) {
411
+ if (id.startsWith("\0") || !SCRIPT.test(id.split("?", 1)[0])) return null;
412
+ const library = id.includes("/node_modules/");
413
+ const clientDirective = library ? "use client" : directives.client;
414
+ if (!code.includes(clientDirective) && (library || !code.includes(directives.server))) return null;
415
+ const file = id.split("?", 1)[0];
416
+ const server = isServer(this.environment.name);
417
+ const relative = relativeOf(file);
418
+ const parseFile = (source) => parse(file, source);
419
+ if (server && !excluded(relative)) {
420
+ const island = transformClientModule({
421
+ code,
422
+ id: file,
423
+ root: config.root,
424
+ parse: parseFile,
425
+ reference: (relative) => {
426
+ discovered.add(relative);
427
+ return JSON.stringify(relative);
428
+ },
429
+ sideEffects: [RUNTIME_ID],
430
+ directive: clientDirective,
431
+ ...library ? { runtime: LIBRARY_RUNTIME_ID } : {}
432
+ });
433
+ if (island) {
434
+ if (!library) transformActions({
435
+ code,
436
+ id: file,
437
+ root: config.root,
438
+ environment: "client",
439
+ parse: parseFile,
440
+ directive: directives.server
441
+ });
442
+ return {
443
+ code: island.code,
444
+ map: island.map
445
+ };
446
+ }
447
+ }
448
+ if (library) return null;
449
+ const actions = transformActions({
450
+ code,
451
+ id: file,
452
+ root: config.root,
453
+ environment: server ? "server" : "client",
454
+ parse: parseFile,
455
+ directive: directives.server
456
+ });
457
+ if (!actions) return null;
458
+ return {
459
+ code: server ? `import ${JSON.stringify(RUNTIME_ID)};\n${actions.code}` : actions.code,
460
+ map: server ? null : actions.map
461
+ };
462
+ }
463
+ },
464
+ {
465
+ name: "islx:reload",
466
+ apply: "serve",
467
+ hotUpdate({ file, modules, server }) {
468
+ if (!isServer(this.environment.name) || modules.length === 0) return;
469
+ const client = server.environments.client;
470
+ if (client?.moduleGraph.getModulesByFile(file)?.size) return;
471
+ client?.hot.send({ type: "full-reload" });
472
+ }
473
+ },
474
+ {
475
+ name: "islx:build",
476
+ sharedDuringBuild: true,
477
+ async buildApp(builder) {
478
+ if (host.frameworkBuild) return;
479
+ const servers = Object.values(builder.environments).filter((environment) => isServer(environment.name));
480
+ for (const environment of servers) await builder.build(environment);
481
+ await builder.build(builder.environments.client);
482
+ if (!entryUrl) throw new Error("islx: the browser build did not emit the islx entry");
483
+ for (const environment of servers) {
484
+ const outDir = path.resolve(config.root, environment.config.build.outDir);
485
+ for (const file of await listOutput(outDir)) {
486
+ const source = await readFile(file, "utf8");
487
+ if (!source.includes(ENTRY_PLACEHOLDER) && !source.includes(MODULES_PLACEHOLDER)) continue;
488
+ const modules = JSON.stringify(JSON.stringify(moduleFiles)).slice(1, -1);
489
+ await writeFile(file, source.replaceAll(ENTRY_PLACEHOLDER, entryUrl).replaceAll(MODULES_PLACEHOLDER, modules));
490
+ }
491
+ }
492
+ },
493
+ generateBundle(_options, bundle) {
494
+ if (this.environment.name !== "client") return;
495
+ const url = (fileName) => `${config.base}${fileName}`;
496
+ for (const chunk of Object.values(bundle)) {
497
+ if (chunk.type !== "chunk" || !chunk.facadeModuleId) continue;
498
+ if (chunk.isEntry && chunk.facadeModuleId === `\0virtual:islx/client-entry`) entryUrl = url(chunk.fileName);
499
+ else if (chunk.isDynamicEntry && !chunk.facadeModuleId.startsWith("\0")) moduleFiles[relativeOf(chunk.facadeModuleId)] = [chunk.fileName, ...chunk.imports].map(url);
500
+ }
501
+ clientBuilt = true;
502
+ }
503
+ }
504
+ ];
505
+ }
506
+ export { serializeHooks as i, islx as n, resolveDirectives as r, ENTRY_ID as t };
package/dist/client.d.mts CHANGED
@@ -10,8 +10,24 @@ interface ActionNavigator {
10
10
  /** A client navigation to `href`, as the action's redirect. */
11
11
  navigate?(href: string): Promise<void> | void;
12
12
  }
13
+ /** A call of a server action, as an interceptor sees it. */
14
+ interface ActionCall {
15
+ id: string;
16
+ /** The export (or inline function) name, when known. */
17
+ name?: string;
18
+ /** The arguments, after any bound with `.bind`. */
19
+ args: readonly unknown[];
20
+ }
21
+ /**
22
+ * Wraps every server action call: call `next` to make the request, and return what the caller
23
+ * gets. A framework uses it to unwrap what its own server side adds to a result (cache
24
+ * invalidations, a query's cache entry) or to turn a returned error back into one it throws.
25
+ */
26
+ type ActionInterceptor = (call: ActionCall, next: () => Promise<unknown>) => Promise<unknown>;
13
27
  /** Connects actions to the framework's router. */
14
28
  declare function setActionNavigator(navigator: ActionNavigator): void;
29
+ /** Installs the framework's interceptor for server action calls (one; a later call replaces it). */
30
+ declare function setActionInterceptor(interceptor: ActionInterceptor | undefined): void;
15
31
  /** Decodes an action in a result or props: `{"$":"a","v":id,"b"?:sealed}`. */
16
32
  declare function decodeActionReference(object: Record<string, unknown>): AnyFunction | undefined;
17
33
  /** The function that calls a server action; one per id and sealed values, so props keep identity. */
@@ -55,4 +71,4 @@ declare const INTERACTION_EVENT = "f:island-interaction";
55
71
  declare const REPLAYABLE_SELECTOR = "button,[role=\"button\"],input[type=\"button\"],input[type=\"submit\"],input[type=\"reset\"]";
56
72
  /** The inline script's source (no `<script>` tag): pass it to the page's head or bootstrap. */
57
73
  declare const PREHYDRATION_SCRIPT: string;
58
- export { type ActionNavigator, type ClientHookEvent, type ClientHookEvents, type ClientHooks, INTERACTION_EVENT, NAVIGATION_RENDER, type NavigateOptions, type NavigationOptions, PENDING_INTERACTIONS, PREHYDRATION_SCRIPT, REPLAYABLE_SELECTOR, type ValueStore, createServerReference, createValueStore, decodeActionReference, defineClientHooks, enhanceForms, getValueStore, hookEventName, navigate, setActionNavigator, setClientHooks, startNavigation, valueHeaders };
74
+ export { type ActionCall, type ActionInterceptor, type ActionNavigator, type ClientHookEvent, type ClientHookEvents, type ClientHooks, INTERACTION_EVENT, NAVIGATION_RENDER, type NavigateOptions, type NavigationOptions, PENDING_INTERACTIONS, PREHYDRATION_SCRIPT, REPLAYABLE_SELECTOR, type ValueStore, createServerReference, createValueStore, decodeActionReference, defineClientHooks, enhanceForms, getValueStore, hookEventName, navigate, setActionInterceptor, setActionNavigator, setClientHooks, startNavigation, valueHeaders };
package/dist/client.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as emit, c as createValueStore, i as defineClientHooks, l as getValueStore, n as decodeActionReference, o as hookEventName, r as setActionNavigator, s as setClientHooks, t as createServerReference, u as valueHeaders } from "./_chunks/actions-8RQfrM-p.mjs";
1
+ import { a as defineClientHooks, c as setClientHooks, d as valueHeaders, i as setActionNavigator, l as createValueStore, n as decodeActionReference, o as emit, r as setActionInterceptor, s as hookEventName, t as createServerReference, u as getValueStore } from "./_chunks/actions-C-IwUCKU.mjs";
2
2
  import { C as RENDER_HEADER, I as readPostedAction, L as stripRuntimeFields } from "./_chunks/wire-QEQWBr5s.mjs";
3
3
  import { i as REPLAYABLE_SELECTOR, n as PENDING_INTERACTIONS, r as PREHYDRATION_SCRIPT, t as INTERACTION_EVENT } from "./_chunks/prehydration-B1GLTLdk.mjs";
4
4
  // src/client/forms.ts
@@ -194,4 +194,4 @@ function navigate(href, options = {}) {
194
194
  else location.assign(href);
195
195
  return Promise.resolve();
196
196
  }
197
- export { INTERACTION_EVENT, NAVIGATION_RENDER, PENDING_INTERACTIONS, PREHYDRATION_SCRIPT, REPLAYABLE_SELECTOR, createServerReference, createValueStore, decodeActionReference, defineClientHooks, enhanceForms, getValueStore, hookEventName, navigate, setActionNavigator, setClientHooks, startNavigation, valueHeaders };
197
+ export { INTERACTION_EVENT, NAVIGATION_RENDER, PENDING_INTERACTIONS, PREHYDRATION_SCRIPT, REPLAYABLE_SELECTOR, createServerReference, createValueStore, decodeActionReference, defineClientHooks, enhanceForms, getValueStore, hookEventName, navigate, setActionInterceptor, setActionNavigator, setClientHooks, startNavigation, valueHeaders };
@@ -1,7 +1,8 @@
1
- import { a as emit, l as getValueStore, t as createServerReference, u as valueHeaders } from "../_chunks/actions-8RQfrM-p.mjs";
1
+ import { d as valueHeaders, o as emit, t as createServerReference, u as getValueStore } from "../_chunks/actions-C-IwUCKU.mjs";
2
2
  import { i as decodeTagged, n as NOT_A_VALUE, r as decode, u as setOwn } from "../_chunks/codec-C8to-RQW.mjs";
3
3
  import { F as getTag, f as FORM_STATE_SCRIPT_TYPE, h as ISLAND_ELEMENT, m as HYDRATED_ATTRIBUTE, w as SLOT_ELEMENT, x as PROPS_SCRIPT_TYPE, y as PROMISE_SCRIPT_TYPE } from "../_chunks/wire-QEQWBr5s.mjs";
4
- import { d as isolateIslands, h as withinClientRoot, i as createServerTreeLayout, n as PAYLOAD_ONLY_ATTRIBUTE, o as updateServerTrees, r as createServerTreeElement, u as getContexts } from "../_chunks/tree-opIpaCke.mjs";
4
+ import { i as getContexts, o as isolateIslands, u as withinClientRoot } from "../_chunks/island-DVOr-OUw.mjs";
5
+ import { i as createServerTreeLayout, n as PAYLOAD_ONLY_ATTRIBUTE, o as updateServerTrees, r as createServerTreeElement } from "../_chunks/tree-C47p6khN.mjs";
5
6
  import { n as isIslandStrategy, r as scheduleHydration, t as ISLAND_STRATEGIES } from "../_chunks/schedule-CjoybS3b.mjs";
6
7
  import * as React from "react";
7
8
  import { hydrateRoot } from "react-dom/client";
@@ -1,9 +1,11 @@
1
1
  import { a as encode } from "../_chunks/codec-C8to-RQW.mjs";
2
2
  import { f as FORM_STATE_SCRIPT_TYPE } from "../_chunks/wire-QEQWBr5s.mjs";
3
3
  import { r as PREHYDRATION_SCRIPT } from "../_chunks/prehydration-B1GLTLdk.mjs";
4
- import { g as escapeScriptJson, h as addressValues, i as encodeActionReference, v as parseHeldValues, y as selectValuesToSend } from "../_chunks/actions-CtLpJPEB.mjs";
4
+ import { i as encodeActionReference } from "../_chunks/actions-BuS5jDi0.mjs";
5
5
  import { t as getBuildDefaults } from "../_chunks/build-COIcs7wm.mjs";
6
- import { a as renderServerTree, c as createIsland, d as isolateIslands, f as runtimeTagged, h as withinClientRoot, l as getClientReference, m as setRenderStateResolver, n as PAYLOAD_ONLY_ATTRIBUTE, p as setIslandServerHook, s as IslandsProvider, t as Outlet, u as getContexts } from "../_chunks/tree-opIpaCke.mjs";
6
+ import { a as parseHeldValues, n as addressValues, o as selectValuesToSend, r as escapeScriptJson } from "../_chunks/values-37UIzxM0.mjs";
7
+ import { c as setIslandServerHook, i as getContexts, l as setRenderStateResolver, n as createIsland, o as isolateIslands, r as getClientReference, s as runtimeTagged, t as IslandsProvider, u as withinClientRoot } from "../_chunks/island-DVOr-OUw.mjs";
8
+ import { a as renderServerTree, n as PAYLOAD_ONLY_ATTRIBUTE, t as Outlet } from "../_chunks/tree-C47p6khN.mjs";
7
9
  import * as React from "react";
8
10
  // src/react/server.ts
9
11
  /**
package/dist/react.mjs CHANGED
@@ -1 +1,3 @@
1
- export { s as IslandsProvider, t as Outlet, c as createIsland, d as isolateIslands, a as renderServerTree, h as withinClientRoot } from "./_chunks/tree-opIpaCke.mjs";
1
+ import { n as createIsland, o as isolateIslands, t as IslandsProvider, u as withinClientRoot } from "./_chunks/island-DVOr-OUw.mjs";
2
+ import { a as renderServerTree, t as Outlet } from "./_chunks/tree-C47p6khN.mjs";
3
+ export { IslandsProvider, Outlet, createIsland, isolateIslands, renderServerTree, withinClientRoot };
package/dist/server.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { _ as hashValue, a as getActionReference, c as resolveAction, d as generateActionKey, f as sealBound, g as escapeScriptJson, h as addressValues, i as encodeActionReference, l as SealError, m as VALUE_MIN_LENGTH, n as configureActionKeys, o as registerInlineAction, p as unsealBound, r as decodeActionReference, s as registerServerReference, t as bindInlineAction, u as createActionKeys, v as parseHeldValues, y as selectValuesToSend } from "./_chunks/actions-CtLpJPEB.mjs";
1
+ import { a as parseHeldValues, i as hashValue, n as addressValues, o as selectValuesToSend, r as escapeScriptJson, t as VALUE_MIN_LENGTH } from "./_chunks/values-37UIzxM0.mjs";
2
+ import { a as getActionReference, c as resolveAction, d as generateActionKey, f as sealBound, i as encodeActionReference, l as SealError, n as configureActionKeys, o as registerInlineAction, p as unsealBound, r as decodeActionReference, s as registerServerReference, t as bindInlineAction, u as createActionKeys } from "./_chunks/actions-BuS5jDi0.mjs";
2
3
  import { a as encode, r as decode } from "./_chunks/codec-C8to-RQW.mjs";
3
4
  import { I as readPostedAction, L as stripRuntimeFields, N as attachmentField, n as ACTION_KEY_FIELD, o as BOUND_FIELD, r as ACTION_STALE_HEADER, s as CALL_FIELD, t as ACTION_HEADER } from "./_chunks/wire-QEQWBr5s.mjs";
4
5
  import { n as setBuildDefaults, t as getBuildDefaults } from "./_chunks/build-COIcs7wm.mjs";
@@ -0,0 +1,11 @@
1
+ import { HandlerCallback } from "@tanstack/react-router/ssr/server";
2
+ import { AnyRouter } from "@tanstack/react-router";
3
+
4
+ // src/tanstack-start/server.d.ts
5
+
6
+ /**
7
+ * Renders the page with its islands: values the browser holds stay out, and a navigation (an
8
+ * `F-Render` request) gets the whole page in one piece, as islx's browser runtime swaps it in.
9
+ */
10
+ declare const islandsHandler: HandlerCallback<AnyRouter>;
11
+ export { islandsHandler };