Open History to see the last commit
1import fs from 'node:fs/promises'
2import path from 'node:path'
3import {
4 createMiddleware,
5 defaultSerovalDeserializerPlugins,
6 getDefaultSerovalPlugins,
7 getSerovalPlugins,
8} from '@tanstack/start-client-core'
9import { fromJSON, toJSONAsync } from 'seroval'
10β
11type StaticCachedResult = {
12 result: any
13 context: any
14}
15β
16/**
17 * This is a simple hash function for generating a hash from a string to make the filenames shorter.
18 *
19 * It is not cryptographically secure (as its using SHA-1) and should not be used for any security purposes.
20 *
21 * It is only used to generate a hash for the static cache filenames.
22 *
23 * @param message - The input string to hash.
24 * @returns A promise that resolves to the SHA-1 hash of the input string in hexadecimal format.
25 *
26 * @example
27 * ```typescript
28 * const hash = await sha1Hash("hello");
29 * console.log(hash); // Outputs the SHA-1 hash of "hello" -> "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"
30 * ```
31 */
32async function sha1Hash(message: string): Promise<string> {
33 // Encode the string as UTF-8
34 const msgBuffer = new TextEncoder().encode(message)
35β
36 // Hash the message
37 const hashBuffer = await crypto.subtle.digest('SHA-1', msgBuffer)
38β
39 // Convert the ArrayBuffer to a string
40 const hashArray = Array.from(new Uint8Array(hashBuffer))
41 const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
42 return hashHex
43}
44β
45const getStaticCacheUrl = async (opts: {
46 functionId: string
47 hash: string
48}) => {
49 const filename = await sha1Hash(`${opts.functionId}__${opts.hash}`)
50 return `/__tsr/staticServerFnCache/${filename}.json`
51}
52β
53const jsonToFilenameSafeString = (json: any) => {
54 // Custom replacer to sort keys
55 const sortedKeysReplacer = (key: string, value: any) =>
56 value && typeof value === 'object' && !Array.isArray(value)
57 ? Object.keys(value)
58 .sort()
59 .reduce((acc: any, curr: string) => {
60 acc[curr] = value[curr]
61 return acc
62 }, {})
63 : value
64β
65 // Convert JSON to string with sorted keys
66 const jsonString = JSON.stringify(json ?? '', sortedKeysReplacer)
67β
68 // Replace characters invalid in filenames
69 return jsonString
70 .replace(/[/\\?%*:|"<>]/g, '-') // Replace invalid characters with a dash
71 .replace(/\s+/g, '_') // Optionally replace whitespace with underscores
72}
73β
74async function addItemToCache({
75 functionId,
76 data,
77 response,
78}: {
79 functionId: string
80 data: any
81 response: StaticCachedResult
82}): Promise<void> {
83 const hash = jsonToFilenameSafeString(data)
84 const url = await getStaticCacheUrl({ functionId, hash })
85 const clientUrl = process.env.TSS_CLIENT_OUTPUT_DIR!
86 const filePath = path.join(clientUrl, url)
87β
88 // Ensure the directory exists
89 await fs.mkdir(path.dirname(filePath), { recursive: true })
90β
91 // Store the result with fs
92 const stringifiedResult = JSON.stringify(
93 await toJSONAsync(
94 {
95 result: response.result,
96 context: response.context.sendContext,
97 },
98 { plugins: getDefaultSerovalPlugins() },
99 ),
100 )
101 await fs.writeFile(filePath, stringifiedResult, 'utf-8')
102}
103β
104const fetchItem = async ({
105 data,
106 functionId,
107}: {
108 data: any
109 functionId: string
110}) => {
111 const hash = jsonToFilenameSafeString(data)
112 const url = await getStaticCacheUrl({ functionId, hash })
113β
114 return fetch(url, {
115 method: 'GET',
116 })
117 .then((r) => r.json())
118 .then((d) =>
119 fromJSON<any>(d, {
120 // Cached responses may carry RawStream nodes.
121 plugins: getSerovalPlugins(defaultSerovalDeserializerPlugins),
122 }),
123 )
124}
125β
126export const staticFunctionMiddleware = createMiddleware({ type: 'function' })
127 .client(async (ctx) => {
128 if (
129 process.env.NODE_ENV === 'production' &&
130 // do not run this during SSR on the server
131 typeof document !== 'undefined'
132 ) {
133 const response = await fetchItem({
134 functionId: ctx.serverFnMeta.id,
135 data: ctx.data,
136 })
137β
138 if (response) {
139 return {
140 result: response.result,
141 context: { ...(ctx as any).context, ...response.context },
142 } as any
143 }
144 }
145 return ctx.next()
146 })
147 .server(async (ctx) => {
148 const response = await ctx.next()
149 if (
150 process.env.NODE_ENV === 'production' &&
151 process.env.TSS_CLIENT_OUTPUT_DIR
152 ) {
153 await addItemToCache({
154 functionId: ctx.serverFnMeta.id,
155 response: { result: (response as any).result, context: ctx },
156 data: ctx.data,
157 })
158 }
159β
160 return response
161 })