Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

transformAssets.test.ts

607 lines16.6 KB

1import { describe, expect, it, vi } from 'vitest'
2import {
3 buildManifest,
4 resolveTransformAssetsConfig,
5 transformManifestAssets,
6} from '../src/transformAssetUrls'
7import type { ServerManifest } from '@tanstack/router-core'
8​
9describe('transformAssets', () => {
10 it('supports string shorthand', async () => {
11 const config = resolveTransformAssetsConfig('https://cdn.example.com')
12​
13 expect(config.type).toBe('transform')
14 if (config.type !== 'transform') {
15 throw new Error('expected transform config')
16 }
17​
18 expect(
19 config.transformFn({
20 kind: 'script',
21 url: '/assets/app.js',
22 }),
23 ).toEqual({ href: 'https://cdn.example.com/assets/app.js' })
24 })
25​
26 it('supports object return values with crossOrigin', async () => {
27 const manifest = await transformManifestAssets(
28 {
29 routes: {
30 __root__: {
31 preloads: ['/assets/app.js'],
32 css: ['/assets/app.css'],
33 scripts: [
34 {
35 attrs: {
36 type: 'module',
37 async: true,
38 src: '/assets/entry.js',
39 },
40 },
41 ],
42 },
43 },
44 },
45 (context) => {
46 if (context.kind === 'script') {
47 return {
48 href: `https://cdn.example.com${context.url}`,
49 crossOrigin: 'anonymous',
50 }
51 }
52​
53 return { href: `https://cdn.example.com${context.url}` }
54 },
55 { clone: true },
56 )
57​
58 expect(manifest.routes.__root__?.preloads).toEqual([
59 {
60 href: 'https://cdn.example.com/assets/app.js',
61 crossOrigin: 'anonymous',
62 },
63 ])
64 expect(manifest.routes.__root__?.css?.[0]).toBe(
65 'https://cdn.example.com/assets/app.css',
66 )
67 expect(manifest.routes.__root__?.scripts?.[0]).toEqual({
68 attrs: {
69 type: 'module',
70 async: true,
71 src: 'https://cdn.example.com/assets/entry.js',
72 crossOrigin: 'anonymous',
73 },
74 })
75 })
76​
77 it('preserves string preload format when transform returns no crossOrigin', async () => {
78 const manifest = await transformManifestAssets(
79 {
80 routes: {
81 __root__: {
82 preloads: ['/assets/app.js'],
83 },
84 },
85 },
86 ({ url }) => ({ href: `https://cdn.example.com${url}` }),
87 { clone: true },
88 )
89​
90 expect(manifest.routes.__root__?.preloads?.[0]).toBe(
91 'https://cdn.example.com/assets/app.js',
92 )
93 })
94​
95 it('passes script context for manifest preloads and scripts', async () => {
96 const transformFn = vi.fn(({ url }) => ({
97 href: `https://cdn.example.com${url}`,
98 }))
99​
100 await transformManifestAssets(
101 {
102 scriptFormat: 'iife',
103 routes: {
104 __root__: {
105 preloads: ['/assets/app.js'],
106 scripts: [{ attrs: { src: '/assets/entry.js' } }],
107 },
108 },
109 },
110 transformFn,
111 )
112​
113 expect(transformFn.mock.calls).toEqual([
114 [{ kind: 'script', url: '/assets/app.js' }],
115 [{ kind: 'script', url: '/assets/entry.js' }],
116 ])
117 })
118​
119 it('reuses transformed URLs for matching preload and script tags', async () => {
120 let signature = 0
121 const transformFn = vi.fn(({ url }) => ({
122 href: `https://cdn.example.com${url}?sig=${++signature}`,
123 }))
124​
125 const manifest = await transformManifestAssets(
126 {
127 routes: {
128 __root__: {
129 preloads: ['/assets/entry.js'],
130 scripts: [
131 {
132 attrs: {
133 type: 'module',
134 async: true,
135 src: '/assets/entry.js',
136 },
137 },
138 ],
139 },
140 },
141 },
142 transformFn,
143 )
144​
145 const preload = manifest.routes.__root__?.preloads?.[0]
146 const script = manifest.routes.__root__?.scripts?.[0]
147 expect(preload).toBe(script?.attrs?.src)
148 expect(transformFn.mock.calls).toEqual([
149 [{ kind: 'script', url: '/assets/entry.js' }],
150 ])
151 })
152​
153 it('keeps root route boot scripts before an iife client entry', async () => {
154 const transformFn = vi.fn(({ url }) => ({
155 href: `https://cdn.example.com${url}`,
156 }))
157​
158 const manifest = await transformManifestAssets(
159 {
160 scriptFormat: 'iife',
161 routes: {
162 __root__: {
163 preloads: ['/assets/runtime.js', '/assets/entry.js'],
164 scripts: [
165 { attrs: { src: '/assets/runtime.js' } },
166 { attrs: { src: '/assets/entry.js' } },
167 ],
168 },
169 },
170 },
171 transformFn,
172 )
173​
174 expect(manifest.routes.__root__?.preloads).toEqual([
175 'https://cdn.example.com/assets/runtime.js',
176 'https://cdn.example.com/assets/entry.js',
177 ])
178 expect(manifest.routes.__root__?.scripts).toEqual([
179 { attrs: { src: 'https://cdn.example.com/assets/runtime.js' } },
180 { attrs: { src: 'https://cdn.example.com/assets/entry.js' } },
181 ])
182 expect(transformFn.mock.calls).toEqual([
183 [{ kind: 'script', url: '/assets/runtime.js' }],
184 [{ kind: 'script', url: '/assets/entry.js' }],
185 ])
186 })
187​
188 it('does not mutate the source manifest', async () => {
189 const source: ServerManifest = {
190 routes: {
191 __root__: {
192 preloads: ['/assets/app.js'],
193 css: ['/assets/app.css'],
194 },
195 },
196 }
197​
198 const manifest = await transformManifestAssets(source, ({ url }) => ({
199 href: `https://cdn.example.com${url}`,
200 }))
201​
202 expect(manifest.routes.__root__?.preloads?.[0]).toBe(
203 'https://cdn.example.com/assets/app.js',
204 )
205 expect(source.routes.__root__?.preloads?.[0]).toBe('/assets/app.js')
206 expect(source.routes.__root__?.css?.[0]).toBe('/assets/app.css')
207 })
208​
209 it('transforms manifest stylesheet links', async () => {
210 const transformFn = vi.fn(({ url }) => ({
211 href: `https://cdn.example.com${url}`,
212 }))
213​
214 const manifest = await transformManifestAssets(
215 {
216 routes: {
217 __root__: {
218 preloads: [],
219 css: ['/assets/app.css'],
220 },
221 },
222 },
223 transformFn,
224 { clone: true },
225 )
226​
227 expect(transformFn).toHaveBeenCalledWith({
228 kind: 'stylesheet',
229 url: '/assets/app.css',
230 })
231 expect(manifest.routes.__root__?.css).toEqual([
232 'https://cdn.example.com/assets/app.css',
233 ])
234 expect(manifest.routes.__root__?.scripts).toBeUndefined()
235 })
236​
237 it('transforms existing manifest route script src values', async () => {
238 const manifest = await transformManifestAssets(
239 {
240 routes: {
241 __root__: {
242 scripts: [
243 {
244 attrs: {
245 src: '/assets/route-script.js',
246 type: 'module',
247 },
248 },
249 ],
250 },
251 },
252 },
253 ({ url }) => ({ href: `https://cdn.example.com${url}` }),
254 { clone: true },
255 )
256​
257 expect(manifest.routes.__root__?.scripts?.[0]).toEqual({
258 attrs: {
259 src: 'https://cdn.example.com/assets/route-script.js',
260 type: 'module',
261 },
262 })
263 })
264​
265 it('transforms CSS URLs inside inlined stylesheet templates with css-url context', async () => {
266 const transformFn = vi.fn((context) => {
267 if (context.kind === 'css-url') {
268 return `https://cdn.example.com${context.url}`
269 }
270​
271 return context.url
272 })
273​
274 const manifest = await transformManifestAssets(
275 {
276 inlineCss: {
277 styles: {
278 '/assets/app.css':
279 '@font-face{src:url(/assets/font.woff2)}.card{background:url(/images/bg.png)}.icon{background:url(data:image/svg+xml,foo)}',
280 },
281 templates: {
282 '/assets/app.css': {
283 strings: [
284 '@font-face{src:url("',
285 '")}.card{background:url("',
286 '")}.icon{background:url(data:image/svg+xml,foo)}',
287 ],
288 urls: ['/assets/font.woff2', '/images/bg.png'],
289 },
290 },
291 },
292 routes: {
293 __root__: {
294 css: ['/assets/app.css'],
295 },
296 },
297 },
298 transformFn,
299 )
300​
301 expect(manifest.inlineCss?.styles['/assets/app.css']).toBe(
302 '@font-face{src:url("https://cdn.example.com/assets/font.woff2")}.card{background:url("https://cdn.example.com/images/bg.png")}.icon{background:url(data:image/svg+xml,foo)}',
303 )
304 expect(transformFn).toHaveBeenCalledWith({
305 kind: 'css-url',
306 url: '/assets/font.woff2',
307 stylesheetHref: '/assets/app.css',
308 })
309 expect(transformFn).toHaveBeenCalledWith({
310 kind: 'css-url',
311 url: '/images/bg.png',
312 stylesheetHref: '/assets/app.css',
313 })
314 expect(transformFn).not.toHaveBeenCalledWith({
315 kind: 'css-url',
316 url: 'data:image/svg+xml,foo',
317 stylesheetHref: '/assets/app.css',
318 })
319 })
320​
321 it('leaves inlined CSS URLs unchanged when template metadata is absent', async () => {
322 const transformFn = vi.fn((context) => {
323 if (context.kind === 'css-url') {
324 return `https://cdn.example.com${context.url}`
325 }
326​
327 return context.url
328 })
329​
330 const manifest = await transformManifestAssets(
331 {
332 inlineCss: {
333 styles: {
334 '/assets/app.css': '.card{background:url(/images/bg.png)}',
335 },
336 },
337 routes: {},
338 },
339 transformFn,
340 )
341​
342 expect(manifest.inlineCss?.styles['/assets/app.css']).toBe(
343 '.card{background:url(/images/bg.png)}',
344 )
345 expect(transformFn).not.toHaveBeenCalledWith(
346 expect.objectContaining({ kind: 'css-url' }),
347 )
348 })
349​
350 it('does not transform stylesheet link hrefs when inline CSS is enabled', async () => {
351 const transformFn = vi.fn((context) => {
352 if (context.kind === 'stylesheet') {
353 return `https://cdn.example.com${context.url}`
354 }
355​
356 return context.url
357 })
358​
359 const manifest = await transformManifestAssets(
360 {
361 inlineCss: {
362 styles: {
363 '/assets/app.css': '.root{color:red}',
364 },
365 },
366 routes: {
367 __root__: {
368 css: ['/assets/app.css'],
369 },
370 },
371 },
372 transformFn,
373 )
374​
375 expect(manifest.routes.__root__?.css?.[0]).toBe('/assets/app.css')
376 expect(transformFn).not.toHaveBeenCalledWith({
377 kind: 'stylesheet',
378 url: '/assets/app.css',
379 })
380 })
381​
382 it('preserves inline CSS style order when template transforms resolve out of order', async () => {
383 const resolvers = new Map<string, (value: string) => void>()
384 const transformFn = vi.fn((context) => {
385 if (context.kind !== 'css-url') {
386 return context.url
387 }
388​
389 return new Promise<string>((resolve) => {
390 resolvers.set(context.url, resolve)
391 })
392 })
393​
394 const manifestPromise = transformManifestAssets(
395 {
396 inlineCss: {
397 styles: {
398 '/assets/a.css': '.a{background:url(/assets/a.png)}',
399 '/assets/b.css': '.b{background:url(/assets/b.png)}',
400 },
401 templates: {
402 '/assets/a.css': {
403 strings: ['.a{background:url("', '")}'],
404 urls: ['/assets/a.png'],
405 },
406 '/assets/b.css': {
407 strings: ['.b{background:url("', '")}'],
408 urls: ['/assets/b.png'],
409 },
410 },
411 },
412 routes: {},
413 },
414 transformFn,
415 )
416​
417 await vi.waitFor(() => {
418 expect(resolvers.size).toBe(2)
419 })
420​
421 resolvers.get('/assets/b.png')!('https://cdn.example.com/assets/b.png')
422 resolvers.get('/assets/a.png')!('https://cdn.example.com/assets/a.png')
423​
424 const manifest = await manifestPromise
425​
426 expect(Object.keys(manifest.inlineCss!.styles)).toEqual([
427 '/assets/a.css',
428 '/assets/b.css',
429 ])
430 expect(manifest.inlineCss?.styles['/assets/a.css']).toBe(
431 '.a{background:url("https://cdn.example.com/assets/a.png")}',
432 )
433 expect(manifest.inlineCss?.styles['/assets/b.css']).toBe(
434 '.b{background:url("https://cdn.example.com/assets/b.png")}',
435 )
436 })
437​
438 it('clones inline CSS when building a manifest without transforms', () => {
439 const source: ServerManifest = {
440 inlineCss: {
441 styles: {
442 '/assets/app.css': '.app{color:red}',
443 },
444 templates: {
445 '/assets/app.css': {
446 strings: ['.app{background:url("', '")}'],
447 urls: ['/assets/bg.png'],
448 },
449 },
450 },
451 routes: {
452 __root__: {},
453 },
454 }
455​
456 const manifest = buildManifest(source)
457 manifest.inlineCss!.styles['/assets/app.css'] = '.mutated{}'
458 manifest.inlineCss!.templates!['/assets/app.css']!.urls[0] =
459 '/assets/mutated.png'
460​
461 expect(source.inlineCss!.styles['/assets/app.css']).toBe('.app{color:red}')
462 expect(source.inlineCss!.templates!['/assets/app.css']!.urls[0]).toBe(
463 '/assets/bg.png',
464 )
465 })
466​
467 describe('object shorthand', () => {
468 it('supports { prefix } - same as string shorthand', () => {
469 const config = resolveTransformAssetsConfig({
470 prefix: 'https://cdn.example.com',
471 })
472​
473 expect(config.type).toBe('transform')
474 expect(config.cache).toBe(true)
475 if (config.type !== 'transform') throw new Error('expected transform')
476​
477 expect(
478 config.transformFn({
479 kind: 'script',
480 url: '/assets/app.js',
481 }),
482 ).toEqual({ href: 'https://cdn.example.com/assets/app.js' })
483 })
484​
485 it('supports { prefix, crossOrigin: string } - uniform crossOrigin', () => {
486 const config = resolveTransformAssetsConfig({
487 prefix: 'https://cdn.example.com',
488 crossOrigin: 'anonymous',
489 })
490​
491 if (config.type !== 'transform') throw new Error('expected transform')
492​
493 expect(
494 config.transformFn({
495 kind: 'script',
496 url: '/assets/app.js',
497 }),
498 ).toEqual({
499 href: 'https://cdn.example.com/assets/app.js',
500 crossOrigin: 'anonymous',
501 })
502​
503 expect(
504 config.transformFn({ kind: 'stylesheet', url: '/assets/app.css' }),
505 ).toEqual({
506 href: 'https://cdn.example.com/assets/app.css',
507 crossOrigin: 'anonymous',
508 })
509​
510 expect(
511 config.transformFn({
512 kind: 'css-url',
513 url: '/assets/font.woff2',
514 stylesheetHref: '/assets/app.css',
515 }),
516 ).toEqual({
517 href: 'https://cdn.example.com/assets/font.woff2',
518 })
519 })
520​
521 it('supports { prefix, crossOrigin: per-kind } - different crossOrigin per kind', () => {
522 const config = resolveTransformAssetsConfig({
523 prefix: 'https://cdn.example.com',
524 crossOrigin: {
525 script: 'anonymous',
526 stylesheet: 'use-credentials',
527 },
528 })
529​
530 if (config.type !== 'transform') throw new Error('expected transform')
531​
532 expect(
533 config.transformFn({
534 kind: 'script',
535 url: '/assets/app.js',
536 }),
537 ).toEqual({
538 href: 'https://cdn.example.com/assets/app.js',
539 crossOrigin: 'anonymous',
540 })
541​
542 expect(
543 config.transformFn({ kind: 'stylesheet', url: '/assets/app.css' }),
544 ).toEqual({
545 href: 'https://cdn.example.com/assets/app.css',
546 crossOrigin: 'use-credentials',
547 })
548 })
549​
550 it('supports empty-string prefix shorthand', () => {
551 const config = resolveTransformAssetsConfig('')
552​
553 if (config.type !== 'transform') throw new Error('expected transform')
554​
555 expect(
556 config.transformFn({
557 kind: 'script',
558 url: '/assets/app.js',
559 }),
560 ).toEqual({ href: '/assets/app.js' })
561 })
562​
563 it('applies object shorthand crossOrigin to manifest stylesheets, preloads, and scripts', async () => {
564 const config = resolveTransformAssetsConfig({
565 prefix: 'https://cdn.example.com',
566 crossOrigin: {
567 script: 'anonymous',
568 stylesheet: 'use-credentials',
569 },
570 })
571​
572 if (config.type !== 'transform') throw new Error('expected transform')
573​
574 const manifest = await transformManifestAssets(
575 {
576 routes: {
577 __root__: {
578 preloads: ['/assets/app.js'],
579 css: ['/assets/app.css'],
580 scripts: [{ attrs: { src: '/assets/entry.js' } }],
581 },
582 },
583 },
584 config.transformFn,
585 { clone: true },
586 )
587​
588 expect(manifest.routes.__root__?.preloads).toEqual([
589 {
590 href: 'https://cdn.example.com/assets/app.js',
591 crossOrigin: 'anonymous',
592 },
593 ])
594​
595 expect(manifest.routes.__root__?.css?.[0]).toEqual({
596 href: 'https://cdn.example.com/assets/app.css',
597 crossOrigin: 'use-credentials',
598 })
599 expect(manifest.routes.__root__?.scripts?.[0]).toEqual({
600 attrs: {
601 src: 'https://cdn.example.com/assets/entry.js',
602 crossOrigin: 'anonymous',
603 },
604 })
605 })
606 })
607})