@fastify/react 0.5.0 → 1.0.0-beta.1

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 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
+ }
@@ -19,6 +19,7 @@ export default class RouteContext {
19
19
  this.req = req
20
20
  this.reply = reply
21
21
  this.head = {}
22
+ this.actionData = {}
22
23
  this.state = null
23
24
  this.data = route.data
24
25
  this.firstRender = true
@@ -42,6 +43,7 @@ export default class RouteContext {
42
43
 
43
44
  toJSON() {
44
45
  return {
46
+ actionData: this.actionData,
45
47
  state: this.state,
46
48
  data: this.data,
47
49
  layout: this.layout,
package/index.js CHANGED
@@ -1,191 +1,16 @@
1
- // Used to send a readable stream to reply.send()
2
- import { Readable } from 'stream'
1
+ export {
2
+ prepareServer,
3
+ } from './server.js'
3
4
 
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
- // Helpers from the Node.js stream library to
18
- // make it easier to work with renderToPipeableStream()
19
- import {
20
- generateHtmlStream,
21
- onAllReady,
22
- onShellReady,
23
- } from './server/stream.js'
24
-
25
- // Holds the universal route context
26
- import RouteContext from './server/context.js'
27
-
28
- export default {
5
+ export {
29
6
  prepareClient,
30
- createHtmlFunction,
31
- createRenderFunction,
32
- createRouteHandler,
7
+ createErrorHandler,
33
8
  createRoute,
34
- }
35
-
36
- export async function prepareClient({
37
- routes: routesPromise,
38
- context: contextPromise,
39
- ...others
40
- }) {
41
- const context = await contextPromise
42
- const resolvedRoutes = await routesPromise
43
- return { context, routes: resolvedRoutes, ...others }
44
- }
9
+ } from './routing.js'
45
10
 
46
- // The return value of this function gets registered as reply.html()
47
- export function createHtmlFunction(source, scope, config) {
48
- // Templating functions for universal rendering (SSR+CSR)
49
- const [unHeadSource, unFooterSource] = source.split('<!-- element -->')
50
- const unHeadTemplate = createHtmlTemplateFunction(unHeadSource)
51
- const unFooterTemplate = createHtmlTemplateFunction(unFooterSource)
52
- // Templating functions for server-only rendering (SSR only)
53
- const [soHeadSource, soFooterSource] = source
54
- // Unsafe if dealing with user-input, but safe here
55
- // where we control the index.html source
56
- .replace(/<script[^>]+type="module"[^>]+>.*?<\/script>/g, '')
57
- .split('<!-- element -->')
58
- const soHeadTemplate = createHtmlTemplateFunction(soHeadSource)
59
- const soFooterTemplate = createHtmlTemplateFunction(soFooterSource)
60
- // This function gets registered as reply.html()
61
- return function ({ routes, context, body }) {
62
- // Decide which templating functions to use, with and without hydration
63
- const headTemplate = context.serverOnly ? soHeadTemplate : unHeadTemplate
64
- const footerTemplate = context.serverOnly
65
- ? soFooterTemplate
66
- : unFooterTemplate
67
- // Render page-level <head> elements
68
- const head = new Head(context.head).render()
69
- // Create readable stream with prepended and appended chunks
70
- const readable = Readable.from(
71
- generateHtmlStream({
72
- body:
73
- body && (context.streaming ? onShellReady(body) : onAllReady(body)),
74
- head: headTemplate({ ...context, head }),
75
- footer: () =>
76
- footerTemplate({
77
- ...context,
78
- hydration: '',
79
- // Decide whether or not to include the hydration script
80
- ...(!context.serverOnly && {
81
- hydration: `<script>\nwindow.route = ${devalue.uneval(
82
- context.toJSON(),
83
- )}\nwindow.routes = ${devalue.uneval(
84
- routes.toJSON(),
85
- )}\n</script>`,
86
- }),
87
- }),
88
- }),
89
- )
90
- // Send out header and readable stream with full response
91
- this.type('text/html')
92
- this.send(readable)
93
- }
94
- }
95
-
96
- export async function createRenderFunction({ routes, create }) {
97
- // create is exported by client/index.js
98
- return (req) => {
99
- // Create convenience-access routeMap
100
- const routeMap = Object.fromEntries(
101
- routes.toJSON().map((route) => {
102
- return [route.path, route]
103
- }),
104
- )
105
- // Creates main React component with all the SSR context it needs
106
- const app =
107
- !req.route.clientOnly &&
108
- create({
109
- routes,
110
- routeMap,
111
- ctxHydration: req.route,
112
- url: req.url,
113
- })
114
- // Perform SSR, i.e., turn app.instance into an HTML fragment
115
- // The SSR context data is passed along so it can be inlined for hydration
116
- return { routes, context: req.route, body: app }
117
- }
118
- }
119
-
120
- export function createRouteHandler({ client }, scope, config) {
121
- return (req, reply) => {
122
- reply.html(reply.render(req))
123
- return reply
124
- }
125
- }
126
-
127
- export function createRoute(
128
- { client, handler, errorHandler, route },
129
- scope,
130
- config,
131
- ) {
132
- const onRequest = async function onRequest(req, reply) {
133
- req.route = await RouteContext.create(
134
- scope,
135
- req,
136
- reply,
137
- route,
138
- client.context,
139
- )
140
- }
141
- if (route.getData) {
142
- // If getData is provided, register JSON endpoint for it
143
- scope.get(`/-/data${route.path}`, {
144
- onRequest,
145
- async handler(req, reply) {
146
- reply.send(await route.getData(req.route))
147
- },
148
- })
149
- }
150
-
151
- // See https://github.com/fastify/fastify-dx/blob/main/URMA.md
152
- const hasURMAHooks = Boolean(route.getData || route.getMeta || route.onEnter)
153
-
154
- // Extend with route context initialization module
155
- RouteContext.extend(client.context)
11
+ export {
12
+ createRenderFunction,
13
+ createHtmlFunction,
14
+ } from './rendering.js'
156
15
 
157
- scope.route({
158
- url: route.path,
159
- method: ['GET', 'POST', 'PUT', 'DELETE'],
160
- onRequest,
161
- // If either getData or onEnter are provided,
162
- // make sure they run before the SSR route handler
163
- ...(hasURMAHooks && {
164
- async preHandler(req, reply) {
165
- try {
166
- if (route.getData) {
167
- req.route.data = await route.getData(req.route)
168
- }
169
- if (route.getMeta) {
170
- req.route.head = await route.getMeta(req.route)
171
- }
172
- if (route.onEnter) {
173
- if (!req.route.data) {
174
- req.route.data = {}
175
- }
176
- const result = await route.onEnter(req.route)
177
- Object.assign(req.route.data, result)
178
- }
179
- } catch (err) {
180
- if (config.dev) {
181
- console.error(err)
182
- }
183
- req.route.error = err
184
- }
185
- },
186
- }),
187
- handler,
188
- errorHandler,
189
- ...route,
190
- })
191
- }
16
+ export const clientModule = '$app/index.js'
package/package.json CHANGED
@@ -3,43 +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.5.0",
6
+ "version": "1.0.0-beta.1",
7
7
  "files": [
8
- "virtual/create.jsx",
9
- "virtual/root.jsx",
10
- "virtual/layouts.js",
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.jsx",
19
+ "virtual/layouts.js",
13
20
  "virtual/mount.js",
14
21
  "virtual/resource.js",
15
- "virtual/core.jsx",
22
+ "virtual/root.jsx",
16
23
  "virtual/routes.js",
24
+ "client.js",
25
+ "context.js",
17
26
  "index.js",
18
- "plugin.cjs",
19
- "server/context.js",
20
- "server/stream.js"
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.cjs"
35
+ "./plugin": "./plugin/index.js",
36
+ "./client": "./client.js",
37
+ "./server": "./server.js"
26
38
  },
27
39
  "dependencies": {
40
+ "acorn": "^8.14.1",
41
+ "acorn-strip-function": "^1.2.0",
42
+ "acorn-walk": "^8.3.4",
28
43
  "devalue": "latest",
29
44
  "history": "latest",
45
+ "html-rewriter-wasm": "^0.4.1",
30
46
  "minipass": "latest",
31
- "react": "^18.2.0",
32
- "react-dom": "^18.2.0",
33
- "react-router-dom": "latest",
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",
34
52
  "unihead": "latest",
35
- "valtio": "latest"
53
+ "valtio": "latest",
54
+ "youch": "^3.3.4",
55
+ "@fastify/vite": "^8.0.1"
36
56
  },
37
57
  "devDependencies": {
38
- "@biomejs/biome": "^1.5.3"
58
+ "@biomejs/biome": "^1.9.2"
39
59
  },
40
60
  "publishConfig": {
41
61
  "access": "public"
42
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/",
43
76
  "scripts": {
44
77
  "lint": "biome check --apply-unsafe ."
45
78
  }
@@ -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
+ }
@@ -0,0 +1,39 @@
1
+
2
+ export function generateStores(keys) {
3
+ let code = `
4
+ import { useRouteContext } from '@fastify/react/client'
5
+
6
+ function storeGetter (proxy, prop) {
7
+ if (!proxy.context) {
8
+ proxy.context = useRouteContext()
9
+ }
10
+ if (prop === 'state') {
11
+ return proxy.context.state[proxy.key]
12
+ }
13
+ let method
14
+ if (method = proxy.context.actions[proxy.key][prop]) {
15
+ if (!proxy.wrappers[prop]) {
16
+ proxy.wrappers[prop] = (...args) => {
17
+ return method(proxy.context.state, ...args)
18
+ }
19
+ }
20
+ return proxy.wrappers[prop]
21
+ }
22
+ }
23
+ `
24
+ for (const key of keys) {
25
+ code += `
26
+ export const ${key} = new Proxy({
27
+ key: '${key}',
28
+ wrappers: {},
29
+ context: null,
30
+ }, {
31
+ get: storeGetter
32
+ })
33
+ `
34
+ }
35
+ return {
36
+ code,
37
+ map: null
38
+ }
39
+ }