@fastify/react 0.6.0 → 1.0.0-beta.2
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/LICENSE +21 -0
- package/client.js +44 -0
- package/index.js +11 -244
- package/package.json +45 -15
- package/plugin/index.js +102 -0
- package/plugin/parsers.js +42 -0
- package/plugin/parsers.test.js +28 -0
- package/plugin/preload.js +75 -0
- package/plugin/stores.js +39 -0
- package/plugin/virtual.js +100 -0
- package/rendering.js +139 -0
- package/routing.js +142 -0
- package/server.js +129 -0
- package/templating.js +51 -0
- package/virtual/core.jsx +6 -17
- package/virtual/create.jsx +1 -1
- package/virtual/index.js +7 -0
- package/virtual/layouts.js +1 -1
- package/virtual/mount.js +31 -28
- package/virtual/root.jsx +1 -1
- package/virtual/routes.js +1 -123
- package/plugin.cjs +0 -115
- package/server/stream.js +0 -56
- /package/{server/context.js → context.js} +0 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021-present Jonas Galvez
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/client.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createContext, useContext, lazy } from 'react'
|
|
2
|
+
import { useSnapshot } from 'valtio'
|
|
3
|
+
|
|
4
|
+
export const RouteContext = createContext({})
|
|
5
|
+
export const isServer = typeof window === 'undefined' && typeof process === 'object'
|
|
6
|
+
|
|
7
|
+
export function useRouteContext() {
|
|
8
|
+
const routeContext = useContext(RouteContext)
|
|
9
|
+
if (routeContext.state) {
|
|
10
|
+
routeContext.snapshot = isServer
|
|
11
|
+
? routeContext.state ?? {}
|
|
12
|
+
: useSnapshot(routeContext.state ?? {})
|
|
13
|
+
}
|
|
14
|
+
return routeContext
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function hydrateRoutes (fromInput) {
|
|
18
|
+
let from = fromInput
|
|
19
|
+
if (Array.isArray(from)) {
|
|
20
|
+
from = Object.fromEntries(
|
|
21
|
+
from.map((route) => [route.path, route]),
|
|
22
|
+
)
|
|
23
|
+
}
|
|
24
|
+
return window.routes.map((route) => {
|
|
25
|
+
route.loader = memoImport(from[route.id])
|
|
26
|
+
route.component = lazy(() => route.loader())
|
|
27
|
+
return route
|
|
28
|
+
})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function memoImport (func) {
|
|
32
|
+
// Otherwise we get a ReferenceError, but since this function
|
|
33
|
+
// is only ran once for each route, there's no overhead
|
|
34
|
+
const kFuncExecuted = Symbol('kFuncExecuted')
|
|
35
|
+
const kFuncValue = Symbol('kFuncValue')
|
|
36
|
+
func[kFuncExecuted] = false
|
|
37
|
+
return async () => {
|
|
38
|
+
if (!func[kFuncExecuted]) {
|
|
39
|
+
func[kFuncValue] = await func()
|
|
40
|
+
func[kFuncExecuted] = true
|
|
41
|
+
}
|
|
42
|
+
return func[kFuncValue]
|
|
43
|
+
}
|
|
44
|
+
}
|
package/index.js
CHANGED
|
@@ -1,249 +1,16 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
// fastify-vite's minimal HTML templating function,
|
|
5
|
-
// which extracts interpolation variables from comments
|
|
6
|
-
// and returns a function with the generated code
|
|
7
|
-
import { createHtmlTemplateFunction } from '@fastify/vite/utils'
|
|
8
|
-
|
|
9
|
-
// Used to safely serialize JavaScript into
|
|
10
|
-
// <script> tags, preventing a few types of attack
|
|
11
|
-
import * as devalue from 'devalue'
|
|
12
|
-
|
|
13
|
-
// Small SSR-ready library used to generate
|
|
14
|
-
// <title>, <meta> and <link> elements
|
|
15
|
-
import Head from 'unihead'
|
|
16
|
-
|
|
17
|
-
// Used for removing <script> tags when serverOnly is enabled
|
|
18
|
-
import { HTMLRewriter } from 'html-rewriter-wasm'
|
|
19
|
-
|
|
20
|
-
// Helpers from the Node.js stream library to
|
|
21
|
-
// make it easier to work with renderToPipeableStream()
|
|
22
|
-
import {
|
|
23
|
-
generateHtmlStream,
|
|
24
|
-
onAllReady,
|
|
25
|
-
onShellReady,
|
|
26
|
-
} from './server/stream.js'
|
|
27
|
-
|
|
28
|
-
// Holds the universal route context
|
|
29
|
-
import RouteContext from './server/context.js'
|
|
1
|
+
export {
|
|
2
|
+
prepareServer,
|
|
3
|
+
} from './server.js'
|
|
30
4
|
|
|
31
|
-
export
|
|
5
|
+
export {
|
|
32
6
|
prepareClient,
|
|
33
|
-
|
|
34
|
-
createHtmlFunction,
|
|
35
|
-
createRenderFunction,
|
|
36
|
-
createRouteHandler,
|
|
7
|
+
createErrorHandler,
|
|
37
8
|
createRoute,
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
async function prepareClient({
|
|
41
|
-
routes: routesPromise,
|
|
42
|
-
context: contextPromise,
|
|
43
|
-
...others
|
|
44
|
-
}) {
|
|
45
|
-
const context = await contextPromise
|
|
46
|
-
const resolvedRoutes = await routesPromise
|
|
47
|
-
return { context, routes: resolvedRoutes, ...others }
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// The return value of this function gets registered as reply.html()
|
|
51
|
-
async function createHtmlFunction(source, scope, config) {
|
|
52
|
-
// Templating functions for universal rendering (SSR+CSR)
|
|
53
|
-
const [unHeadSource, unFooterSource] = source.split('<!-- element -->')
|
|
54
|
-
const unHeadTemplate = createHtmlTemplateFunction(unHeadSource)
|
|
55
|
-
const unFooterTemplate = createHtmlTemplateFunction(unFooterSource)
|
|
56
|
-
// Templating functions for server-only rendering (SSR only)
|
|
57
|
-
const [soHeadSource, soFooterSource] = (await removeModules(source)).split(
|
|
58
|
-
'<!-- element -->',
|
|
59
|
-
)
|
|
60
|
-
const soHeadTemplate = createHtmlTemplateFunction(soHeadSource)
|
|
61
|
-
const soFooterTemplate = createHtmlTemplateFunction(soFooterSource)
|
|
62
|
-
// This function gets registered as reply.html()
|
|
63
|
-
return function ({ routes, context, body }) {
|
|
64
|
-
// Decide which templating functions to use, with and without hydration
|
|
65
|
-
const headTemplate = context.serverOnly ? soHeadTemplate : unHeadTemplate
|
|
66
|
-
const footerTemplate = context.serverOnly
|
|
67
|
-
? soFooterTemplate
|
|
68
|
-
: unFooterTemplate
|
|
69
|
-
// Render page-level <head> elements
|
|
70
|
-
const head = new Head(context.head).render()
|
|
71
|
-
// Create readable stream with prepended and appended chunks
|
|
72
|
-
const readable = Readable.from(
|
|
73
|
-
generateHtmlStream({
|
|
74
|
-
body:
|
|
75
|
-
body && (context.streaming ? onShellReady(body) : onAllReady(body)),
|
|
76
|
-
head: headTemplate({ ...context, head }),
|
|
77
|
-
footer: () =>
|
|
78
|
-
footerTemplate({
|
|
79
|
-
...context,
|
|
80
|
-
hydration: '',
|
|
81
|
-
// Decide whether or not to include the hydration script
|
|
82
|
-
...(!context.serverOnly && {
|
|
83
|
-
hydration: `<script>\nwindow.route = ${devalue.uneval(
|
|
84
|
-
context.toJSON(),
|
|
85
|
-
)}\nwindow.routes = ${devalue.uneval(
|
|
86
|
-
routes.toJSON(),
|
|
87
|
-
)}\n</script>`,
|
|
88
|
-
}),
|
|
89
|
-
}),
|
|
90
|
-
}),
|
|
91
|
-
)
|
|
92
|
-
// Send out header and readable stream with full response
|
|
93
|
-
this.type('text/html')
|
|
94
|
-
this.send(readable)
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
async function createRenderFunction({ routes, create }) {
|
|
99
|
-
// create is exported by client/index.js
|
|
100
|
-
return (req) => {
|
|
101
|
-
// Create convenience-access routeMap
|
|
102
|
-
const routeMap = Object.fromEntries(
|
|
103
|
-
routes.toJSON().map((route) => {
|
|
104
|
-
return [route.path, route]
|
|
105
|
-
}),
|
|
106
|
-
)
|
|
107
|
-
// Creates main React component with all the SSR context it needs
|
|
108
|
-
const app =
|
|
109
|
-
!req.route.clientOnly &&
|
|
110
|
-
create({
|
|
111
|
-
routes,
|
|
112
|
-
routeMap,
|
|
113
|
-
ctxHydration: req.route,
|
|
114
|
-
url: req.url,
|
|
115
|
-
})
|
|
116
|
-
// Perform SSR, i.e., turn app.instance into an HTML fragment
|
|
117
|
-
// The SSR context data is passed along so it can be inlined for hydration
|
|
118
|
-
return { routes, context: req.route, body: app }
|
|
119
|
-
}
|
|
120
|
-
}
|
|
9
|
+
} from './routing.js'
|
|
121
10
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
function prepareServer(server) {
|
|
130
|
-
let url
|
|
131
|
-
server.decorate('serverURL', { getter: () => url })
|
|
132
|
-
server.addHook('onListen', () => {
|
|
133
|
-
const { port, address, family } = server.server.address()
|
|
134
|
-
const protocol = server.https ? 'https' : 'http'
|
|
135
|
-
if (family === 'IPv6') {
|
|
136
|
-
url = `${protocol}://[${address}]:${port}`
|
|
137
|
-
} else {
|
|
138
|
-
url = `${protocol}://${address}:${port}`
|
|
139
|
-
}
|
|
140
|
-
})
|
|
141
|
-
server.decorateRequest('fetchMap', null)
|
|
142
|
-
server.addHook('onRequest', (req, _, done) => {
|
|
143
|
-
req.fetchMap = new Map()
|
|
144
|
-
done()
|
|
145
|
-
})
|
|
146
|
-
server.addHook('onResponse', (req, _, done) => {
|
|
147
|
-
req.fetchMap = undefined
|
|
148
|
-
done()
|
|
149
|
-
})
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
export async function createRoute(
|
|
153
|
-
{ client, handler, errorHandler, route },
|
|
154
|
-
scope,
|
|
155
|
-
config,
|
|
156
|
-
) {
|
|
157
|
-
const onRequest = async function onRequest(req, reply) {
|
|
158
|
-
req.route = await RouteContext.create(
|
|
159
|
-
scope,
|
|
160
|
-
req,
|
|
161
|
-
reply,
|
|
162
|
-
route,
|
|
163
|
-
client.context,
|
|
164
|
-
)
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
if (route.configure) {
|
|
168
|
-
await route.configure(scope)
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
if (route.getData) {
|
|
172
|
-
// If getData is provided, register JSON endpoint for it
|
|
173
|
-
scope.get(`/-/data${route.path}`, {
|
|
174
|
-
onRequest,
|
|
175
|
-
async handler(req, reply) {
|
|
176
|
-
reply.send(await route.getData(req.route))
|
|
177
|
-
},
|
|
178
|
-
})
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// See https://github.com/fastify/fastify-dx/blob/main/URMA.md
|
|
182
|
-
const hasURMAHooks = Boolean(route.getData || route.getMeta || route.onEnter)
|
|
183
|
-
|
|
184
|
-
// Extend with route context initialization module
|
|
185
|
-
RouteContext.extend(client.context)
|
|
186
|
-
|
|
187
|
-
scope.route({
|
|
188
|
-
url: route.path,
|
|
189
|
-
method: ['GET', 'POST', 'PUT', 'DELETE'],
|
|
190
|
-
onRequest,
|
|
191
|
-
// If either getData or onEnter are provided,
|
|
192
|
-
// make sure they run before the SSR route handler
|
|
193
|
-
...(hasURMAHooks && {
|
|
194
|
-
async preHandler(req, reply) {
|
|
195
|
-
try {
|
|
196
|
-
if (route.getData) {
|
|
197
|
-
req.route.data = await route.getData(req.route)
|
|
198
|
-
}
|
|
199
|
-
if (route.getMeta) {
|
|
200
|
-
req.route.head = await route.getMeta(req.route)
|
|
201
|
-
}
|
|
202
|
-
if (route.onEnter) {
|
|
203
|
-
if (!req.route.data) {
|
|
204
|
-
req.route.data = {}
|
|
205
|
-
}
|
|
206
|
-
const result = await route.onEnter(req.route)
|
|
207
|
-
Object.assign(req.route.data, result)
|
|
208
|
-
}
|
|
209
|
-
} catch (err) {
|
|
210
|
-
if (config.dev) {
|
|
211
|
-
console.error(err)
|
|
212
|
-
}
|
|
213
|
-
req.route.error = err
|
|
214
|
-
}
|
|
215
|
-
},
|
|
216
|
-
}),
|
|
217
|
-
handler,
|
|
218
|
-
errorHandler,
|
|
219
|
-
...route,
|
|
220
|
-
})
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
async function removeModules(html) {
|
|
224
|
-
const decoder = new TextDecoder()
|
|
225
|
-
|
|
226
|
-
let output = ''
|
|
227
|
-
const rewriter = new HTMLRewriter((outputChunk) => {
|
|
228
|
-
output += decoder.decode(outputChunk)
|
|
229
|
-
})
|
|
230
|
-
|
|
231
|
-
rewriter.on('script', {
|
|
232
|
-
element(element) {
|
|
233
|
-
for (const [attr, value] of element.attributes) {
|
|
234
|
-
if (attr === 'type' && value === 'module') {
|
|
235
|
-
element.replace('')
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
},
|
|
239
|
-
})
|
|
11
|
+
export {
|
|
12
|
+
createRenderFunction,
|
|
13
|
+
createHtmlFunction,
|
|
14
|
+
} from './rendering.js'
|
|
240
15
|
|
|
241
|
-
|
|
242
|
-
const encoder = new TextEncoder()
|
|
243
|
-
await rewriter.write(encoder.encode(html))
|
|
244
|
-
await rewriter.end()
|
|
245
|
-
return output
|
|
246
|
-
} finally {
|
|
247
|
-
rewriter.free()
|
|
248
|
-
}
|
|
249
|
-
}
|
|
16
|
+
export const clientModule = '$app/index.js'
|
package/package.json
CHANGED
|
@@ -3,46 +3,76 @@
|
|
|
3
3
|
"main": "index.js",
|
|
4
4
|
"name": "@fastify/react",
|
|
5
5
|
"description": "The official @fastify/vite renderer for React",
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "1.0.0-beta.2",
|
|
7
7
|
"files": [
|
|
8
|
-
"
|
|
9
|
-
"
|
|
10
|
-
"
|
|
8
|
+
"plugin/index.js",
|
|
9
|
+
"plugin/parsers.js",
|
|
10
|
+
"plugin/parsers.test.js",
|
|
11
|
+
"plugin/preload.js",
|
|
12
|
+
"plugin/stores.js",
|
|
13
|
+
"plugin/virtual.js",
|
|
11
14
|
"virtual/layouts/default.jsx",
|
|
12
15
|
"virtual/context.js",
|
|
16
|
+
"virtual/core.jsx",
|
|
17
|
+
"virtual/create.jsx",
|
|
18
|
+
"virtual/index.js",
|
|
19
|
+
"virtual/layouts.js",
|
|
13
20
|
"virtual/mount.js",
|
|
14
21
|
"virtual/resource.js",
|
|
15
|
-
"virtual/
|
|
22
|
+
"virtual/root.jsx",
|
|
16
23
|
"virtual/routes.js",
|
|
24
|
+
"client.js",
|
|
25
|
+
"context.js",
|
|
17
26
|
"index.js",
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"server
|
|
27
|
+
"rendering.js",
|
|
28
|
+
"routing.js",
|
|
29
|
+
"server.js",
|
|
30
|
+
"templating.js"
|
|
21
31
|
],
|
|
22
32
|
"license": "MIT",
|
|
23
33
|
"exports": {
|
|
24
34
|
".": "./index.js",
|
|
25
|
-
"./plugin": "./plugin.
|
|
35
|
+
"./plugin": "./plugin/index.js",
|
|
36
|
+
"./client": "./client.js",
|
|
37
|
+
"./server": "./server.js"
|
|
26
38
|
},
|
|
27
39
|
"dependencies": {
|
|
28
|
-
"
|
|
40
|
+
"acorn": "^8.14.1",
|
|
29
41
|
"acorn-strip-function": "^1.2.0",
|
|
42
|
+
"acorn-walk": "^8.3.4",
|
|
30
43
|
"devalue": "latest",
|
|
31
44
|
"history": "latest",
|
|
32
45
|
"html-rewriter-wasm": "^0.4.1",
|
|
33
46
|
"minipass": "latest",
|
|
34
|
-
"
|
|
35
|
-
"react
|
|
36
|
-
"react-
|
|
47
|
+
"mlly": "^1.7.4",
|
|
48
|
+
"react": "^19.1.0",
|
|
49
|
+
"react-dom": "^19.1.0",
|
|
50
|
+
"react-router": "^7.5.0",
|
|
51
|
+
"react-router-dom": "^7.5.0",
|
|
37
52
|
"unihead": "latest",
|
|
38
|
-
"valtio": "latest"
|
|
53
|
+
"valtio": "latest",
|
|
54
|
+
"youch": "^3.3.4",
|
|
55
|
+
"@fastify/vite": "^8.0.1"
|
|
39
56
|
},
|
|
40
57
|
"devDependencies": {
|
|
41
|
-
"@biomejs/biome": "^1.
|
|
58
|
+
"@biomejs/biome": "^1.9.2"
|
|
42
59
|
},
|
|
43
60
|
"publishConfig": {
|
|
44
61
|
"access": "public"
|
|
45
62
|
},
|
|
63
|
+
"repository": {
|
|
64
|
+
"type": "git",
|
|
65
|
+
"url": "git+https://github.com/fastify/fastify-vite.git"
|
|
66
|
+
},
|
|
67
|
+
"keywords": [
|
|
68
|
+
"fastify",
|
|
69
|
+
"vite",
|
|
70
|
+
"react"
|
|
71
|
+
],
|
|
72
|
+
"bugs": {
|
|
73
|
+
"url": "https://github.com/fastify/fastify-vite/issues"
|
|
74
|
+
},
|
|
75
|
+
"homepage": "https://fastify-vite.dev/react/",
|
|
46
76
|
"scripts": {
|
|
47
77
|
"lint": "biome check --apply-unsafe ."
|
|
48
78
|
}
|
package/plugin/index.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { readFileSync, existsSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import viteFastify from '@fastify/vite/plugin'
|
|
4
|
+
import {
|
|
5
|
+
prefix,
|
|
6
|
+
resolveId,
|
|
7
|
+
loadSource,
|
|
8
|
+
loadVirtualModule,
|
|
9
|
+
createPlaceholderExports
|
|
10
|
+
} from './virtual.js'
|
|
11
|
+
import { closeBundle } from './preload.js'
|
|
12
|
+
import { parseStateKeys } from './parsers.js'
|
|
13
|
+
import { generateStores } from './stores.js'
|
|
14
|
+
|
|
15
|
+
export default function viteFastifyVue () {
|
|
16
|
+
const context = {
|
|
17
|
+
root: null,
|
|
18
|
+
}
|
|
19
|
+
return [viteFastify({
|
|
20
|
+
clientModule: '$app/index.js'
|
|
21
|
+
}), {
|
|
22
|
+
name: 'vite-plugin-fastify-react',
|
|
23
|
+
config,
|
|
24
|
+
configResolved: configResolved.bind(context),
|
|
25
|
+
resolveId: resolveId.bind(context),
|
|
26
|
+
async load (id) {
|
|
27
|
+
if (id.includes('?server') && !context.resolvedConfig.build.ssr) {
|
|
28
|
+
const source = loadSource(id)
|
|
29
|
+
return createPlaceholderExports(source)
|
|
30
|
+
}
|
|
31
|
+
if (id.includes('?client') && context.resolvedConfig.build.ssr) {
|
|
32
|
+
const source = loadSource(id)
|
|
33
|
+
return createPlaceholderExports(source)
|
|
34
|
+
}
|
|
35
|
+
if (prefix.test(id)) {
|
|
36
|
+
const [, virtual] = id.split(prefix)
|
|
37
|
+
if (virtual) {
|
|
38
|
+
if (virtual === 'stores') {
|
|
39
|
+
const contextPath = join(context.root, 'context.js')
|
|
40
|
+
if (existsSync(contextPath)) {
|
|
41
|
+
const keys = parseStateKeys(readFileSync(contextPath, 'utf8'))
|
|
42
|
+
return generateStores(keys)
|
|
43
|
+
}
|
|
44
|
+
return
|
|
45
|
+
}
|
|
46
|
+
return loadVirtualModule(virtual)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
transformIndexHtml: {
|
|
51
|
+
order: 'post',
|
|
52
|
+
handler: transformIndexHtml.bind(context)
|
|
53
|
+
},
|
|
54
|
+
closeBundle: closeBundle.bind(context),
|
|
55
|
+
}]
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function transformIndexHtml (html, { bundle }) {
|
|
59
|
+
if (!bundle) {
|
|
60
|
+
return
|
|
61
|
+
}
|
|
62
|
+
this.indexHtml = html
|
|
63
|
+
this.resolvedBundle = bundle
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function configResolved (config) {
|
|
67
|
+
this.resolvedConfig = config
|
|
68
|
+
this.root = config.root
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function config (config, { command }) {
|
|
72
|
+
if (command === 'build') {
|
|
73
|
+
if (!config.build) {
|
|
74
|
+
config.build = {}
|
|
75
|
+
}
|
|
76
|
+
if (!config.build.rollupOptions) {
|
|
77
|
+
config.build.rollupOptions = {}
|
|
78
|
+
}
|
|
79
|
+
config.build.rollupOptions.onwarn = onwarn
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function onwarn (warning, rollupWarn) {
|
|
84
|
+
if (
|
|
85
|
+
!(
|
|
86
|
+
warning.code == 'MISSING_EXPORT' &&
|
|
87
|
+
warning.message?.includes?.('"scrollBehavior" is not exported')
|
|
88
|
+
)
|
|
89
|
+
&&
|
|
90
|
+
!(
|
|
91
|
+
warning.code == 'PLUGIN_WARNING' &&
|
|
92
|
+
warning.message?.includes?.('dynamic import will not move module into another chunk')
|
|
93
|
+
)
|
|
94
|
+
&&
|
|
95
|
+
!(
|
|
96
|
+
warning.code == 'UNUSED_EXTERNAL_IMPORT' &&
|
|
97
|
+
warning.exporter === 'vue'
|
|
98
|
+
)
|
|
99
|
+
) {
|
|
100
|
+
rollupWarn(warning)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import * as acorn from 'acorn'
|
|
2
|
+
import * as walk from 'acorn-walk'
|
|
3
|
+
|
|
4
|
+
export function parseStateKeys (code) {
|
|
5
|
+
const ast = acorn.parse(code, { sourceType: 'module', ecmaVersion: 2020 })
|
|
6
|
+
|
|
7
|
+
let objectKeys = []
|
|
8
|
+
|
|
9
|
+
walk.simple(ast, {
|
|
10
|
+
ExportNamedDeclaration(node) {
|
|
11
|
+
if (node.declaration.type === 'FunctionDeclaration') {
|
|
12
|
+
for (const subNode of node.declaration.body.body) {
|
|
13
|
+
if (subNode.type === 'ReturnStatement' && subNode.argument.type === 'ObjectExpression') {
|
|
14
|
+
objectKeys = extractObjectKeys(subNode.argument)
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
} else if (node.declaration.type === 'VariableDeclaration') {
|
|
18
|
+
for (const subNode of node.declaration.declarations) {
|
|
19
|
+
if (
|
|
20
|
+
subNode.type === 'VariableDeclarator' &&
|
|
21
|
+
subNode.init.type === 'ArrowFunctionExpression' &&
|
|
22
|
+
subNode.init.body.type === 'ObjectExpression'
|
|
23
|
+
) {
|
|
24
|
+
objectKeys = extractObjectKeys(subNode.init.body)
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
return objectKeys
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function extractObjectKeys(node) {
|
|
35
|
+
const keys = []
|
|
36
|
+
for (const prop of node.properties) {
|
|
37
|
+
if (prop.key && prop.key.type === 'Identifier') {
|
|
38
|
+
keys.push(prop.key.name)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return keys
|
|
42
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert'
|
|
3
|
+
|
|
4
|
+
test('parseStateKeys', (t) => {
|
|
5
|
+
const a = `export function state () {
|
|
6
|
+
return {
|
|
7
|
+
user: {
|
|
8
|
+
authenticated: false,
|
|
9
|
+
},
|
|
10
|
+
todoList: null,
|
|
11
|
+
}
|
|
12
|
+
}`
|
|
13
|
+
assert.equal(['user', 'todoList'], parseStateKeys(a))
|
|
14
|
+
|
|
15
|
+
const b = `export const state = () => ({
|
|
16
|
+
user: {
|
|
17
|
+
authenticated: false,
|
|
18
|
+
},
|
|
19
|
+
todoList: null,
|
|
20
|
+
})
|
|
21
|
+
if (1) {
|
|
22
|
+
const state = () => {
|
|
23
|
+
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
`;
|
|
27
|
+
assert.equal(['user', 'todoList'], parseStateKeys(b))
|
|
28
|
+
})
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { writeFileSync, mkdirSync, existsSync } from 'node:fs'
|
|
2
|
+
import { join, parse as parsePath } from 'node:path'
|
|
3
|
+
import { HTMLRewriter } from 'html-rewriter-wasm'
|
|
4
|
+
|
|
5
|
+
const imageFile = /\.((png)|(jpg)|(svg)|(webp)|(gif))$/
|
|
6
|
+
|
|
7
|
+
export async function closeBundle() {
|
|
8
|
+
if (!this.resolvedConfig.build.ssr) {
|
|
9
|
+
const distDir = join(this.root, this.resolvedConfig.build.outDir)
|
|
10
|
+
const pages = Object.fromEntries(
|
|
11
|
+
Object.entries(this.resolvedBundle ?? {})
|
|
12
|
+
.filter(([id, meta]) => {
|
|
13
|
+
if (meta.facadeModuleId?.includes('/pages/')) {
|
|
14
|
+
meta.htmlPath = meta.facadeModuleId.replace(/.*pages\/(.*)\.jsx$/, 'html/$1.html')
|
|
15
|
+
return true
|
|
16
|
+
}
|
|
17
|
+
})
|
|
18
|
+
)
|
|
19
|
+
for (const page of Object.values(pages)) {
|
|
20
|
+
const jsImports = page.imports
|
|
21
|
+
const cssImports = page.viteMetadata.importedCss
|
|
22
|
+
const images = page.moduleIds.filter(_ => imageFile.test(_))
|
|
23
|
+
let imagePreloads = '\n'
|
|
24
|
+
for (let image of images) {
|
|
25
|
+
image = image.slice(this.root.length + 1)
|
|
26
|
+
imagePreloads += ` <link rel="preload" as="image" href="${this.resolvedConfig.base}${image}">\n`
|
|
27
|
+
}
|
|
28
|
+
let cssPreloads = ''
|
|
29
|
+
for (const css of cssImports) {
|
|
30
|
+
cssPreloads += ` <link rel="preload" as="style" href="${this.resolvedConfig.base}${css}">\n`
|
|
31
|
+
}
|
|
32
|
+
let jsPreloads = ''
|
|
33
|
+
for (const js of jsImports) {
|
|
34
|
+
jsPreloads += ` <link rel="modulepreload" href="${this.resolvedConfig.base}${js}">\n`
|
|
35
|
+
}
|
|
36
|
+
const pageHtml = await appendHead(
|
|
37
|
+
this.indexHtml,
|
|
38
|
+
imagePreloads,
|
|
39
|
+
cssPreloads,
|
|
40
|
+
jsPreloads
|
|
41
|
+
)
|
|
42
|
+
writeHtml(page, pageHtml, distDir)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function appendHead (html, ...tags) {
|
|
48
|
+
const encoder = new TextEncoder()
|
|
49
|
+
const decoder = new TextDecoder()
|
|
50
|
+
let output = ''
|
|
51
|
+
const rewriter = new HTMLRewriter((outputChunk) => {
|
|
52
|
+
output += decoder.decode(outputChunk)
|
|
53
|
+
})
|
|
54
|
+
rewriter.on('head', {
|
|
55
|
+
element(element) {
|
|
56
|
+
element.prepend(tags.join('\n '), { html: true })
|
|
57
|
+
},
|
|
58
|
+
})
|
|
59
|
+
try {
|
|
60
|
+
await rewriter.write(encoder.encode(html))
|
|
61
|
+
await rewriter.end()
|
|
62
|
+
return output
|
|
63
|
+
} finally {
|
|
64
|
+
rewriter.free()
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function writeHtml(page, pageHtml, distDir) {
|
|
69
|
+
const { dir, base } = parsePath(page.htmlPath)
|
|
70
|
+
const htmlDir = join(distDir, dir)
|
|
71
|
+
if (!existsSync(htmlDir)) {
|
|
72
|
+
mkdirSync(htmlDir, { recursive: true })
|
|
73
|
+
}
|
|
74
|
+
writeFileSync(join(htmlDir, base), pageHtml)
|
|
75
|
+
}
|