forked from solidjs/solid-start
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
392 lines (373 loc) · 13.5 KB
/
Copy pathindex.ts
File metadata and controls
392 lines (373 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import { defu } from "defu";
import { globSync } from "node:fs";
import { basename, extname, isAbsolute, join } from "node:path";
import type { PluginOption } from "vite";
import solid, { type Options as SolidOptions } from "vite-plugin-solid";
import { type ServerFunctionsOptions, serverFunctionsPlugin } from "../directives/index.ts";
import { appRootAlias } from "./app-root-alias.ts";
import { boundaryModules } from "./boundary-modules.ts";
import { DEFAULT_EXTENSIONS, VIRTUAL_MODULES, VITE_ENVIRONMENTS } from "./constants.ts";
import { devServer } from "./dev-server.ts";
import { envPlugin, type EnvPluginOptions } from "./env.ts";
import { SolidStartClientFileRouter, SolidStartServerFileRouter } from "./fs-router.ts";
import { fsRoutes } from "./fs-routes/index.ts";
import type { BaseFileSystemRouter } from "./fs-routes/router.ts";
import { sanitizeChunkFileName, toPickId } from "./fs-routes/tree-shake.ts";
import lazy from "./lazy.ts";
import { manifest } from "./manifest.ts";
import { parseIdQuery } from "./utils.ts";
/**
* Configuration options for SolidStart. (previously in `app.config.ts`)
*
* @see https://docs.solidjs.com/solid-start/v2/migrating-from-v1#move-framework-configuration-into-viteconfigts
*/
export interface SolidStartOptions {
/**
* Path to the root of the application (where `app.tsx` / `app.jsx` lives).
*
* @default "./src"
*/
appRoot?: string;
/**
* Options forwarded to `vite-plugin-solid`.
*
* @see https://github.com/solidjs/vite-plugin-solid#api
*/
solid?: Partial<SolidOptions>;
/**
* Enable or disable server-side rendering.
*
* - `true` — SSR (default)
* - `false` — client-side rendering only (SPA mode)
*
* @default true
*/
ssr?: boolean;
/**
* Show the SolidStart development overlay (error overlay, etc.) in development.
*
* @default true
*/
devOverlay?: boolean;
/**
* Experimental features.
*/
experimental?: {
/**
* Enable islands architecture mode.
*
* Currently fixed to `false` (not yet fully supported).
*
* @default false
*/
islands?: false;
};
/**
* Directory containing file-system routes, relative to {@link appRoot}.
*
* @default "./routes"
*/
routeDir?: string;
/**
* File extensions that should be treated as routes.
*
* @default ["js", "jsx", "ts", "tsx"]
*/
extensions?: string[];
/**
* Path to an optional middleware module.
*
* The module should export a middleware created with `createMiddleware`
* from `@solidjs/start/middleware`.
*
* @example "src/middleware/index.ts"
*/
middleware?: string;
/**
* Serialization settings for server-function / action payloads
* that cross the server-client boundary.
*/
serialization?: {
/**
* The serialization mode to use for server functions/actions.
*
* - `"js"` — Uses a custom binary format (Seroval) that is more efficient
* than JSON, but requires a custom deserializer (with `eval()`) on the client.
* A strong CSP that blocks `eval()` will prevent this mode from working.
* - `"json"` — Uses JSON for serialization. Less efficient / larger payloads,
* but can be deserialized with `JSON.parse` on the client and is CSP-friendly.
*
* @default "json"
*/
mode?: "js" | "json";
/**
* Path to a module whose default export is an array of custom Seroval
* plugins, used to serialize values Seroval doesn't understand natively
* (ORM id types, decimals, `Temporal`, and other custom classes).
*
* Build plugins with `createPlugin` from `seroval`. The module is bundled
* into both the client and the server so that both ends of a server
* function agree on the format, so it must not import server-only code.
*
* SolidStart's built-in plugins take precedence: Seroval uses the first
* plugin whose `test()` passes, and these are appended after the built-ins.
*
* A plugin's `deserialize` rebuilds the value under {@link mode} `"json"`.
* `serialize` is only used by `mode: "js"`, where the payload is evaluated
* on the client and may therefore reference globals only, not the plugin
* module's own imports.
*
* Only applies to server-function and action payloads. The SSR hydration
* payload is serialized by `solid-js/web` and is unaffected.
*
* @example "src/seroval-plugins.ts"
*/
plugins?: string;
};
/**
* Configures plugin behavior per build environment
*/
env?: EnvPluginOptions;
/**
* Options controlling which files are processed as server functions
* (inclusion / exclusion filters for the `"use server"` transform) and how
* their ids are generated.
*/
serverFunctions?: Pick<ServerFunctionsOptions, "filter" | "readableIds">;
}
const absolute = (path: string, root: string) =>
path ? (isAbsolute(path) ? path : join(root, path)) : path;
export function solidStart(options?: SolidStartOptions): Array<PluginOption> {
const start = defu(options ?? {}, {
appRoot: "./src",
routeDir: "./routes",
ssr: true,
devOverlay: true,
experimental: {
islands: false,
},
solid: {},
extensions: [],
} satisfies SolidStartOptions);
const extensions = [...DEFAULT_EXTENSIONS, ...(start.extensions || [])];
const routeDir = join(start.appRoot, start.routeDir);
const root = process.cwd();
const appEntryPath = globSync(join(root, start.appRoot, "app.{j,t}sx"))[0];
if (!appEntryPath) {
throw new Error(`Could not find an app jsx/tsx entry in ${start.appRoot}.`);
}
const entryExtension = extname(appEntryPath);
const handlers = {
client: `${start.appRoot}/entry-client${entryExtension}`,
server: `${start.appRoot}/entry-server${entryExtension}`,
};
return [
// TODO (Alexis): check if the comment below is still relevant
//
// Must be placed after fsRoutes, as treeShake will remove the
// server fn exports added in by this plugin
serverFunctionsPlugin({
manifest: VIRTUAL_MODULES.serverFnManifest,
runtime: {
server: "@solidjs/start/fns/server",
client: "@solidjs/start/fns/client",
},
filter: options?.serverFunctions?.filter,
readableIds: options?.serverFunctions?.readableIds,
}),
{
name: "solid-start:config",
enforce: "pre",
configEnvironment(name) {
return {
resolve: {
// remove when https://github.com/solidjs/vite-plugin-solid/pull/228 is released
externalConditions: ["solid", "node"],
},
};
},
async config(config, env) {
const clientInput = [handlers.client];
const clientEntryUrl =
env.command === "serve" && config.experimental?.bundledDev
? `assets/${basename(handlers.client, entryExtension)}.js`
: handlers.client;
if (env.command === "build") {
const clientRouter: BaseFileSystemRouter = (globalThis as any).ROUTERS.client;
for (const route of await clientRouter.getRoutes()) {
for (const [key, value] of Object.entries(route)) {
if (value && key.startsWith("$") && !key.startsWith("$$")) {
clientInput.push(toPickId((value as any).src, (value as any).pick));
}
}
}
}
return {
appType: "custom",
build: {
assetsDir: "_build/assets",
rollupOptions: {
output: {
// Keeps route chunks named after their file rather than after
// the `?pick=...` id that addresses them. See toPickId.
sanitizeFileName: sanitizeChunkFileName,
},
},
},
optimizeDeps: {
// Suppress TS errors from Vite 7 types when configuring Vite 8's Rolldown
...({
rolldownOptions: {
transform: {
jsx: "react",
},
},
} as any),
},
environments: {
[VITE_ENVIRONMENTS.client]: {
consumer: "client",
build: {
write: true,
manifest: true,
outDir: "dist/client",
rollupOptions: {
input: clientInput,
treeshake: true,
preserveEntrySignatures: "exports-only",
},
},
},
[VITE_ENVIRONMENTS.server]: {
consumer: "server",
build: {
ssr: true,
write: true,
manifest: true,
copyPublicDir: false,
rollupOptions: {
input: handlers.server,
},
outDir: "dist/server",
commonjsOptions: {
include: [/node_modules/],
},
},
},
},
resolve: {
alias: {
"@solidjs/start/server/entry": handlers.server,
...(!start.ssr
? {
"@solidjs/start/server": "@solidjs/start/server/spa",
"@solidjs/start/client": "@solidjs/start/client/spa",
}
: {}),
},
// Depending on the package manager and dependency structure Vite externalizes @solidjs/start
// This makes sure that @solidjs/start goes through the Vite build process
//
// h3 and cookie-es must be bundled as well: if they stay external, the server build
// emits bare imports that nitro later re-resolves from the project root, where package
// managers like yarn may have hoisted the older major versions required by nitropack
// and unstorage (h3 v1 / cookie-es v1) instead of the versions @solidjs/start needs
// (see https://github.com/solidjs/solid-start/issues/2101
// and https://github.com/solidjs/solid-start/issues/2178)
noExternal: ["@solidjs/start", "h3", "cookie-es"],
},
define: {
"import.meta.env.MANIFEST": `globalThis.MANIFEST`,
"import.meta.env.START_SSR": JSON.stringify(start.ssr),
// Use JSON.stringify so backslashes on Windows are escaped and
// esbuild receives a valid JS string literal for the define value
"import.meta.env.START_APP_ENTRY": JSON.stringify(appEntryPath),
"import.meta.env.START_CLIENT_ENTRY": JSON.stringify(handlers.client),
"import.meta.env.START_CLIENT_ENTRY_URL": JSON.stringify(clientEntryUrl),
"import.meta.env.START_DEV_OVERLAY": JSON.stringify(start.devOverlay),
"import.meta.env.SERVER_BASE_URL": JSON.stringify(
(config.server as { baseURL?: string } | undefined)?.baseURL ?? "",
),
"import.meta.env.SEROVAL_MODE": JSON.stringify(start.serialization?.mode || "json"),
},
builder: {
sharedPlugins: true,
async buildApp(builder) {
const client = builder.environments[VITE_ENVIRONMENTS.client];
const server = builder.environments[VITE_ENVIRONMENTS.server];
if (!client) throw new Error("Client environment not found");
if (!server) throw new Error("SSR environment not found");
if (!client.isBuilt) await builder.build(client);
if (!server.isBuilt) await builder.build(server);
},
},
};
},
},
appRootAlias(root, start.appRoot),
manifest(start),
fsRoutes({
routers: {
client: new SolidStartClientFileRouter({
dir: absolute(routeDir, root),
extensions,
}),
ssr: new SolidStartServerFileRouter({
dir: absolute(routeDir, root),
extensions,
dataOnly: !start.ssr,
}),
},
}),
lazy(),
envPlugin(options?.env),
boundaryModules(),
{
name: "solid-start:boundary-modules",
enforce: "pre",
resolveId(id, importer, { ssr }) {
if (id === "server-only") {
if (!ssr) this.error(`Attempt to import 'server-only' in a client module: ${importer}`);
} else if (id === "client-only") {
if (ssr) this.error(`Attempt to import 'client-only' in a server module: ${importer}`);
} else {
return null;
}
return "\0solid-start:boundary-modules:id";
},
load(id) {
if (id === "\0solid-start:boundary-modules:id") return "export {}";
},
},
{
name: "solid-start:virtual-modules",
async resolveId(id) {
const { filename, query } = parseIdQuery(id);
let base;
if (filename === VIRTUAL_MODULES.clientEntry) base = handlers.client;
if (filename === VIRTUAL_MODULES.serverEntry) base = handlers.server;
if (filename === VIRTUAL_MODULES.app) base = appEntryPath;
if (base) {
let id = (await this.resolve(base))?.id;
if (!id) return;
if (query.size > 0) id += `?${query.toString()}`;
return id;
}
},
},
{
name: "solid-start:capture-client-bundle",
enforce: "post",
generateBundle(options, bundle) {
globalThis.START_CLIENT_BUNDLE = bundle;
(globalThis as any).START_CLIENT_OUT_DIR = options.dir;
},
},
devServer(handlers.server),
solid({
...start.solid,
ssr: true,
extensions: extensions.map(ext => `.${ext}`),
}),
];
}