@tanstack/start-client-core 1.114.4

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.
@@ -0,0 +1,243 @@
1
+ import { isPlainObject } from '@tanstack/router-core'
2
+
3
+ import invariant from 'tiny-invariant'
4
+
5
+ import { startSerializer } from './serializer'
6
+ import type {
7
+ AnyRouter,
8
+ ControllablePromise,
9
+ DeferredPromiseState,
10
+ MakeRouteMatch,
11
+ Manifest,
12
+ RouteContextOptions,
13
+ } from '@tanstack/router-core'
14
+
15
+ declare global {
16
+ interface Window {
17
+ __TSR_SSR__?: StartSsrGlobal
18
+ }
19
+ }
20
+
21
+ export interface StartSsrGlobal {
22
+ matches: Array<SsrMatch>
23
+ streamedValues: Record<
24
+ string,
25
+ {
26
+ value: any
27
+ parsed: any
28
+ }
29
+ >
30
+ cleanScripts: () => void
31
+ dehydrated?: any
32
+ initMatch: (match: SsrMatch) => void
33
+ resolvePromise: (opts: {
34
+ matchId: string
35
+ id: number
36
+ promiseState: DeferredPromiseState<any>
37
+ }) => void
38
+ injectChunk: (opts: { matchId: string; id: number; chunk: string }) => void
39
+ closeStream: (opts: { matchId: string; id: number }) => void
40
+ }
41
+
42
+ export interface SsrMatch {
43
+ id: string
44
+ __beforeLoadContext: string
45
+ loaderData?: string
46
+ error?: string
47
+ extracted?: Array<ClientExtractedEntry>
48
+ updatedAt: MakeRouteMatch['updatedAt']
49
+ status: MakeRouteMatch['status']
50
+ }
51
+
52
+ export type ClientExtractedEntry =
53
+ | ClientExtractedStream
54
+ | ClientExtractedPromise
55
+
56
+ export interface ClientExtractedPromise extends ClientExtractedBaseEntry {
57
+ type: 'promise'
58
+ value?: ControllablePromise<any>
59
+ }
60
+
61
+ export interface ClientExtractedStream extends ClientExtractedBaseEntry {
62
+ type: 'stream'
63
+ value?: ReadableStream & { controller?: ReadableStreamDefaultController }
64
+ }
65
+
66
+ export interface ClientExtractedBaseEntry {
67
+ type: string
68
+ path: Array<string>
69
+ }
70
+
71
+ export interface ResolvePromiseState {
72
+ matchId: string
73
+ id: number
74
+ promiseState: DeferredPromiseState<any>
75
+ }
76
+
77
+ export interface DehydratedRouter {
78
+ manifest: Manifest | undefined
79
+ dehydratedData: any
80
+ }
81
+
82
+ export function hydrate(router: AnyRouter) {
83
+ invariant(
84
+ window.__TSR_SSR__?.dehydrated,
85
+ 'Expected to find a dehydrated data on window.__TSR_SSR__.dehydrated... but we did not. Please file an issue!',
86
+ )
87
+
88
+ const { manifest, dehydratedData } = startSerializer.parse(
89
+ window.__TSR_SSR__.dehydrated,
90
+ ) as DehydratedRouter
91
+
92
+ router.ssr = {
93
+ manifest,
94
+ serializer: startSerializer,
95
+ }
96
+
97
+ router.clientSsr = {
98
+ getStreamedValue: <T,>(key: string): T | undefined => {
99
+ if (router.isServer) {
100
+ return undefined
101
+ }
102
+
103
+ const streamedValue = window.__TSR_SSR__?.streamedValues[key]
104
+
105
+ if (!streamedValue) {
106
+ return
107
+ }
108
+
109
+ if (!streamedValue.parsed) {
110
+ streamedValue.parsed = router.ssr!.serializer.parse(streamedValue.value)
111
+ }
112
+
113
+ return streamedValue.parsed
114
+ },
115
+ }
116
+
117
+ // Hydrate the router state
118
+ const matches = router.matchRoutes(router.state.location)
119
+ // kick off loading the route chunks
120
+ const routeChunkPromise = Promise.all(
121
+ matches.map((match) => {
122
+ const route = router.looseRoutesById[match.routeId]!
123
+ return router.loadRouteChunk(route)
124
+ }),
125
+ )
126
+ // Right after hydration and before the first render, we need to rehydrate each match
127
+ // First step is to reyhdrate loaderData and __beforeLoadContext
128
+ matches.forEach((match) => {
129
+ const dehydratedMatch = window.__TSR_SSR__!.matches.find(
130
+ (d) => d.id === match.id,
131
+ )
132
+
133
+ if (dehydratedMatch) {
134
+ Object.assign(match, dehydratedMatch)
135
+
136
+ // Handle beforeLoadContext
137
+ if (dehydratedMatch.__beforeLoadContext) {
138
+ match.__beforeLoadContext = router.ssr!.serializer.parse(
139
+ dehydratedMatch.__beforeLoadContext,
140
+ ) as any
141
+ }
142
+
143
+ // Handle loaderData
144
+ if (dehydratedMatch.loaderData) {
145
+ match.loaderData = router.ssr!.serializer.parse(
146
+ dehydratedMatch.loaderData,
147
+ )
148
+ }
149
+
150
+ // Handle error
151
+ if (dehydratedMatch.error) {
152
+ match.error = router.ssr!.serializer.parse(dehydratedMatch.error)
153
+ }
154
+
155
+ // Handle extracted
156
+ ;(match as unknown as SsrMatch).extracted?.forEach((ex) => {
157
+ deepMutableSetByPath(match, ['loaderData', ...ex.path], ex.value)
158
+ })
159
+ } else {
160
+ Object.assign(match, {
161
+ status: 'success',
162
+ updatedAt: Date.now(),
163
+ })
164
+ }
165
+
166
+ return match
167
+ })
168
+
169
+ router.__store.setState((s) => {
170
+ return {
171
+ ...s,
172
+ matches,
173
+ }
174
+ })
175
+
176
+ // Allow the user to handle custom hydration data
177
+ router.options.hydrate?.(dehydratedData)
178
+
179
+ // now that all necessary data is hydrated:
180
+ // 1) fully reconstruct the route context
181
+ // 2) execute `head()` and `scripts()` for each match
182
+ router.state.matches.forEach((match) => {
183
+ const route = router.looseRoutesById[match.routeId]!
184
+
185
+ const parentMatch = router.state.matches[match.index - 1]
186
+ const parentContext = parentMatch?.context ?? router.options.context ?? {}
187
+
188
+ // `context()` was already executed by `matchRoutes`, however route context was not yet fully reconstructed
189
+ // so run it again and merge route context
190
+ const contextFnContext: RouteContextOptions<any, any, any, any> = {
191
+ deps: match.loaderDeps,
192
+ params: match.params,
193
+ context: parentContext,
194
+ location: router.state.location,
195
+ navigate: (opts: any) =>
196
+ router.navigate({ ...opts, _fromLocation: router.state.location }),
197
+ buildLocation: router.buildLocation,
198
+ cause: match.cause,
199
+ abortController: match.abortController,
200
+ preload: false,
201
+ matches,
202
+ }
203
+ match.__routeContext = route.options.context?.(contextFnContext) ?? {}
204
+
205
+ match.context = {
206
+ ...parentContext,
207
+ ...match.__routeContext,
208
+ ...match.__beforeLoadContext,
209
+ }
210
+
211
+ const assetContext = {
212
+ matches: router.state.matches,
213
+ match,
214
+ params: match.params,
215
+ loaderData: match.loaderData,
216
+ }
217
+ const headFnContent = route.options.head?.(assetContext)
218
+
219
+ const scripts = route.options.scripts?.(assetContext)
220
+
221
+ match.meta = headFnContent?.meta
222
+ match.links = headFnContent?.links
223
+ match.headScripts = headFnContent?.scripts
224
+ match.scripts = scripts
225
+ })
226
+
227
+ return routeChunkPromise
228
+ }
229
+
230
+ function deepMutableSetByPath<T>(obj: T, path: Array<string>, value: any) {
231
+ // mutable set by path retaining array and object references
232
+ if (path.length === 1) {
233
+ ;(obj as any)[path[0]!] = value
234
+ }
235
+
236
+ const [key, ...rest] = path
237
+
238
+ if (Array.isArray(obj)) {
239
+ deepMutableSetByPath(obj[Number(key)], rest, value)
240
+ } else if (isPlainObject(obj)) {
241
+ deepMutableSetByPath((obj as any)[key!], rest, value)
242
+ }
243
+ }
@@ -0,0 +1,147 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { startSerializer as tf } from '../serializer'
4
+
5
+ describe('transformer.stringify', () => {
6
+ it('should stringify dates', () => {
7
+ const date = new Date('2021-08-19T20:00:00.000Z')
8
+ expect(tf.stringify(date)).toMatchInlineSnapshot(`
9
+ "{"$date":"2021-08-19T20:00:00.000Z"}"
10
+ `)
11
+ })
12
+
13
+ it('should stringify undefined', () => {
14
+ expect(tf.stringify(undefined)).toMatchInlineSnapshot(`"{"$undefined":0}"`)
15
+ })
16
+
17
+ it('should stringify object foo="bar"', () => {
18
+ expect(tf.stringify({ foo: 'bar' })).toMatchInlineSnapshot(`
19
+ "{"foo":"bar"}"
20
+ `)
21
+ })
22
+
23
+ it('should stringify object foo=undefined', () => {
24
+ expect(tf.stringify({ foo: undefined })).toMatchInlineSnapshot(
25
+ `"{"foo":{"$undefined":0}}"`,
26
+ )
27
+ })
28
+
29
+ it('should stringify object foo=Date', () => {
30
+ const date = new Date('2021-08-19T20:00:00.000Z')
31
+ expect(tf.stringify({ foo: date })).toMatchInlineSnapshot(`
32
+ "{"foo":{"$date":"2021-08-19T20:00:00.000Z"}}"
33
+ `)
34
+ })
35
+
36
+ it('should stringify empty FormData', () => {
37
+ const formData = new FormData()
38
+ expect(tf.stringify(formData)).toMatchInlineSnapshot(`"{"$formData":{}}"`)
39
+ })
40
+
41
+ it('should stringify FormData with key-value pairs of foo="bar",name="Sean"', () => {
42
+ const formData = new FormData()
43
+ formData.append('foo', 'bar')
44
+ formData.append('name', 'Sean')
45
+ expect(tf.stringify(formData)).toMatchInlineSnapshot(
46
+ `"{"$formData":{"foo":"bar","name":"Sean"}}"`,
47
+ )
48
+ })
49
+ it('should stringify FormData with multiple values for the same key', () => {
50
+ const formData = new FormData()
51
+ formData.append('foo', 'bar')
52
+ formData.append('foo', 'baz')
53
+ expect(tf.stringify(formData)).toMatchInlineSnapshot(
54
+ `"{"$formData":{"foo":["bar","baz"]}}"`,
55
+ )
56
+ })
57
+
58
+ it('should stringify bigint', () => {
59
+ const bigint = BigInt('9007199254740992')
60
+ expect(tf.stringify(bigint)).toMatchInlineSnapshot(
61
+ `"{"$bigint":"9007199254740992"}"`,
62
+ )
63
+ })
64
+ it('should stringify object foo=bigint', () => {
65
+ const bigint = BigInt('9007199254740992')
66
+ expect(tf.stringify({ foo: bigint })).toMatchInlineSnapshot(
67
+ `"{"foo":{"$bigint":"9007199254740992"}}"`,
68
+ )
69
+ })
70
+ })
71
+
72
+ describe('transformer.parse', () => {
73
+ it('should parse dates', () => {
74
+ const date = new Date('2021-08-19T20:00:00.000Z')
75
+ const str = tf.stringify(date)
76
+ expect(tf.parse(str)).toEqual(date)
77
+ })
78
+
79
+ it('should parse undefined', () => {
80
+ const str = tf.stringify(undefined)
81
+ expect(tf.parse(str)).toBeUndefined()
82
+ })
83
+
84
+ it('should parse object foo="bar"', () => {
85
+ const obj = { foo: 'bar' }
86
+ const str = tf.stringify(obj)
87
+ expect(tf.parse(str)).toEqual(obj)
88
+ })
89
+
90
+ it('should parse object foo=undefined', () => {
91
+ const obj = { foo: undefined }
92
+ const str = tf.stringify(obj)
93
+ expect(tf.parse(str)).toEqual(obj)
94
+ })
95
+
96
+ it('should parse object foo=Date', () => {
97
+ const date = new Date('2021-08-19T20:00:00.000Z')
98
+ const obj = { foo: date }
99
+ const str = tf.stringify(obj)
100
+ expect(tf.parse(str)).toEqual(obj)
101
+ })
102
+
103
+ it('should parse empty FormData', () => {
104
+ const formData = new FormData()
105
+ const str = tf.stringify(formData)
106
+ const parsed = tf.parse(str) as FormData
107
+ expect(parsed).toBeInstanceOf(FormData)
108
+ expect([...parsed.entries()]).toEqual([])
109
+ })
110
+
111
+ it('should parse FormData with key-value pairs of foo="bar",name="Sean"', () => {
112
+ const formData = new FormData()
113
+ formData.append('foo', 'bar')
114
+ formData.append('name', 'Sean')
115
+ const str = tf.stringify(formData)
116
+ const parsed = tf.parse(str) as FormData
117
+ expect(parsed).toBeInstanceOf(FormData)
118
+ expect([...parsed.entries()]).toEqual([
119
+ ['foo', 'bar'],
120
+ ['name', 'Sean'],
121
+ ])
122
+ })
123
+ it('should parse FormData with multiple values for the same key', () => {
124
+ const formData = new FormData()
125
+ formData.append('foo', 'bar')
126
+ formData.append('foo', 'baz')
127
+ const str = tf.stringify(formData)
128
+ const parsed = tf.parse(str) as FormData
129
+ expect(parsed).toBeInstanceOf(FormData)
130
+ expect([...parsed.entries()]).toEqual([
131
+ ['foo', 'bar'],
132
+ ['foo', 'baz'],
133
+ ])
134
+ })
135
+
136
+ it('should parse bigint', () => {
137
+ const bigint = BigInt('9007199254740992')
138
+ const str = tf.stringify(bigint)
139
+ expect(tf.parse(str)).toEqual(bigint)
140
+ })
141
+ it('should parse object foo=bigint', () => {
142
+ const bigint = BigInt('9007199254740992')
143
+ const obj = { foo: bigint }
144
+ const str = tf.stringify(obj)
145
+ expect(tf.parse(str)).toEqual(obj)
146
+ })
147
+ })