-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
index.ts
309 lines (279 loc) · 9.37 KB
/
index.ts
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
import type { Plugin, UserConfig } from 'vite';
import type { QwikCityPlugin } from '@builder.io/qwik-city/vite';
import type { QwikVitePlugin } from '@builder.io/qwik/optimizer';
import type {
StaticGenerateOptions,
StaticGenerateRenderOptions,
} from '@builder.io/qwik-city/static';
import type { BuildRoute } from '../../../buildtime/types';
import fs from 'node:fs';
import { basename, dirname, join, resolve } from 'node:path';
import { postBuild } from './post-build';
/**
* @public
*/
export function viteAdapter(opts: ViteAdapterPluginOptions) {
let qwikCityPlugin: QwikCityPlugin | null = null;
let qwikVitePlugin: QwikVitePlugin | null = null;
let serverOutDir: string | null = null;
let renderModulePath: string | null = null;
let qwikCityPlanModulePath: string | null = null;
let isSsrBuild = false;
let format = 'esm';
const outputEntries: string[] = [];
const plugin: Plugin = {
name: `vite-plugin-qwik-city-${opts.name}`,
enforce: 'post',
apply: 'build',
config(config) {
if (typeof opts.config === 'function') {
config = opts.config(config);
}
config.define = {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production'),
...config.define,
};
return config;
},
configResolved(config) {
isSsrBuild = !!config.build.ssr;
if (isSsrBuild) {
qwikCityPlugin = config.plugins.find(
(p) => p.name === 'vite-plugin-qwik-city'
) as QwikCityPlugin;
if (!qwikCityPlugin) {
throw new Error('Missing vite-plugin-qwik-city');
}
qwikVitePlugin = config.plugins.find(
(p) => p.name === 'vite-plugin-qwik'
) as QwikVitePlugin;
if (!qwikVitePlugin) {
throw new Error('Missing vite-plugin-qwik');
}
serverOutDir = config.build.outDir;
if (config.build?.ssr !== true) {
throw new Error(
`"build.ssr" must be set to "true" in order to use the "${opts.name}" adapter.`
);
}
if (!config.build?.rollupOptions?.input) {
throw new Error(
`"build.rollupOptions.input" must be set in order to use the "${opts.name}" adapter.`
);
}
if (config.ssr?.format === 'cjs') {
format = 'cjs';
}
}
},
generateBundle(_, bundles) {
if (isSsrBuild) {
outputEntries.length = 0;
for (const fileName in bundles) {
const chunk = bundles[fileName];
if (chunk.type === 'chunk' && chunk.isEntry) {
outputEntries.push(fileName);
if (chunk.name === 'entry.ssr') {
renderModulePath = join(serverOutDir!, fileName);
} else if (chunk.name === '@qwik-city-plan') {
qwikCityPlanModulePath = join(serverOutDir!, fileName);
}
}
}
if (!renderModulePath) {
throw new Error(
'Unable to find "entry.ssr" entry point. Did you forget to add it to "build.rollupOptions.input"?'
);
}
if (!qwikCityPlanModulePath) {
throw new Error(
'Unable to find "@qwik-city-plan" entry point. Did you forget to add it to "build.rollupOptions.input"?'
);
}
}
},
closeBundle: {
sequential: true,
async handler() {
if (
isSsrBuild &&
opts.ssg !== null &&
serverOutDir &&
qwikCityPlugin?.api &&
qwikVitePlugin?.api
) {
const staticPaths: string[] = opts.staticPaths || [];
const routes = qwikCityPlugin.api.getRoutes();
const basePathname = qwikCityPlugin.api.getBasePathname();
const clientOutDir = qwikVitePlugin.api.getClientOutDir()!;
const clientPublicOutDir = qwikVitePlugin.api.getClientPublicOutDir()!;
const rootDir = qwikVitePlugin.api.getRootDir() ?? undefined;
if (renderModulePath && qwikCityPlanModulePath && clientOutDir && clientPublicOutDir) {
let ssgOrigin = opts.ssg?.origin ?? opts.origin;
if (!ssgOrigin) {
ssgOrigin = `https://yoursite.qwik.builder.io`;
}
if (
ssgOrigin.length > 0 &&
!ssgOrigin.startsWith('https://') &&
!ssgOrigin.startsWith('http://')
) {
ssgOrigin = `https://${ssgOrigin}`;
}
try {
ssgOrigin = new URL(ssgOrigin).origin;
} catch (e) {
this.warn(
`Invalid "origin" option: "${ssgOrigin}". Using default origin: "https://yoursite.qwik.builder.io"`
);
ssgOrigin = `https://yoursite.qwik.builder.io`;
}
const staticGenerate = await import('../../../static');
const generateOpts: StaticGenerateOptions = {
maxWorkers: opts.maxWorkers,
basePathname,
outDir: clientPublicOutDir,
rootDir,
...opts.ssg,
origin: ssgOrigin,
renderModulePath,
qwikCityPlanModulePath,
};
const staticGenerateResult = await staticGenerate.generate(generateOpts);
if (staticGenerateResult.errors > 0) {
const err = new Error(
`Error while running SSG from "${opts.name}" adapter. At least one path failed to render.`
);
err.stack = undefined;
this.error(err);
}
staticPaths.push(...staticGenerateResult.staticPaths);
const { staticPathsCode, notFoundPathsCode } = await postBuild(
clientPublicOutDir,
basePathname,
staticPaths,
format,
!!opts.cleanStaticGenerated
);
await Promise.all([
fs.promises.writeFile(join(serverOutDir, RESOLVED_STATIC_PATHS_ID), staticPathsCode),
fs.promises.writeFile(
join(serverOutDir, RESOLVED_NOT_FOUND_PATHS_ID),
notFoundPathsCode
),
]);
if (typeof opts.generate === 'function') {
await opts.generate({
outputEntries,
serverOutDir,
clientOutDir,
clientPublicOutDir,
basePathname,
routes,
warn: (message) => this.warn(message),
error: (message) => this.error(message),
});
}
}
}
},
},
};
return plugin;
}
/**
* @public
*/
export function getParentDir(startDir: string, dirName: string) {
const root = resolve('/');
let dir = startDir;
for (let i = 0; i < 20; i++) {
dir = dirname(dir);
if (basename(dir) === dirName) {
return dir;
}
if (dir === root) {
break;
}
}
throw new Error(`Unable to find "${dirName}" directory from "${startDir}"`);
}
/**
* @public
*/
interface ViteAdapterPluginOptions {
name: string;
origin: string;
staticPaths?: string[];
ssg?: AdapterSSGOptions | null;
cleanStaticGenerated?: boolean;
maxWorkers?: number;
config?: (config: UserConfig) => UserConfig;
generate?: (generateOpts: {
outputEntries: string[];
clientOutDir: string;
clientPublicOutDir: string;
serverOutDir: string;
basePathname: string;
routes: BuildRoute[];
warn: (message: string) => void;
error: (message: string) => void;
}) => Promise<void>;
}
/**
* @public
*/
export interface ServerAdapterOptions {
/**
* Options the adapter should use when running Static Site Generation (SSG).
* Defaults the `filter` to "auto" which will attempt to automatically decides if
* a page can be statically generated and does not have dynamic data, or if it the page
* should instead be rendered on the server (SSR). Setting to `null` will prevent any
* pages from being statically generated.
*/
ssg?: AdapterSSGOptions | null;
}
/**
* @public
*/
export interface AdapterSSGOptions extends Omit<StaticGenerateRenderOptions, 'outDir' | 'origin'> {
/**
* Defines routes that should be static generated. Accepts wildcard behavior.
*/
include: string[];
/**
* Defines routes that should not be static generated. Accepts wildcard behavior. `exclude` always
* take priority over `include`.
*/
exclude?: string[];
/**
* The URL `origin`, which is a combination of the scheme (protocol) and hostname (domain).
* For example, `https://qwik.builder.io` has the protocol `https://` and domain `qwik.builder.io`.
* However, the `origin` does not include a `pathname`.
*
* The `origin` is used to provide a full URL during Static Site Generation (SSG), and to
* simulate a complete URL rather than just the `pathname`. For example, in order to
* render a correct canonical tag URL or URLs within the `sitemap.xml`, the `origin` must
* be provided too.
*
* If the site also starts with a pathname other than `/`, please use the `basePathname`
* option in the Qwik City config options.
*/
origin?: string;
}
/**
* @public
*/
export const STATIC_PATHS_ID = '@qwik-city-static-paths';
/**
* @public
*/
export const RESOLVED_STATIC_PATHS_ID = `${STATIC_PATHS_ID}.js`;
/**
* @public
*/
export const NOT_FOUND_PATHS_ID = '@qwik-city-not-found-paths';
/**
* @public
*/
export const RESOLVED_NOT_FOUND_PATHS_ID = `${NOT_FOUND_PATHS_ID}.js`;