|
| 1 | +import type { EntryFiles } from '../../src/types'; |
| 2 | +import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'; |
| 3 | +import { tmpdir } from 'node:os'; |
| 4 | +import { dirname, join } from 'node:path'; |
| 5 | +import { describe, expect, it } from 'vitest'; |
| 6 | +import { computeIntegrity, integrityFromDisk, referencedFileNames } from '../../src/core/integrity'; |
| 7 | + |
| 8 | +describe('computeIntegrity', () => { |
| 9 | + it('formats a single algorithm as `<algo>-<base64>`', () => { |
| 10 | + expect(computeIntegrity('reprise', ['sha384'])).toBe( |
| 11 | + 'sha384-faAamSmmStfxJQ9skVshC6f5CFqO35HWc37M47/RU370OJxAaGp/EDpOhEtMqHU6' |
| 12 | + ); |
| 13 | + expect(computeIntegrity('reprise', ['sha256'])).toBe('sha256-9HI/4mqcitIofBrwxywRV2OTHrfkKZSVAdGtr3AidrQ='); |
| 14 | + }); |
| 15 | + |
| 16 | + it('joins multiple algorithms with a space, in the given order', () => { |
| 17 | + expect(computeIntegrity('reprise', ['sha256', 'sha512'])).toBe( |
| 18 | + 'sha256-9HI/4mqcitIofBrwxywRV2OTHrfkKZSVAdGtr3AidrQ= sha512-lMCBX5XJ7xq9zWMR7zg7rQXzt0U1v/qX3vtUkCDkrBvOULn+UWCMFvf0hTGqKr+GMj+gTY5zzqQhISiHJlMDXg==' |
| 19 | + ); |
| 20 | + }); |
| 21 | + |
| 22 | + it('hashes raw bytes (Uint8Array) the same as the equivalent string', () => { |
| 23 | + expect(computeIntegrity(new TextEncoder().encode('reprise'), ['sha256'])).toBe( |
| 24 | + computeIntegrity('reprise', ['sha256']) |
| 25 | + ); |
| 26 | + }); |
| 27 | +}); |
| 28 | + |
| 29 | +describe('referencedFileNames', () => { |
| 30 | + it('collects js/css/preload/dynamic across entries, deduped in first-seen order', () => { |
| 31 | + const entryPoints: Record<string, EntryFiles> = { |
| 32 | + app: { js: ['app.js'], css: ['app.css'], preload: ['vendor.js'], dynamic: ['lazy.js'] }, |
| 33 | + admin: { js: ['admin.js'], css: [], preload: ['vendor.js'], dynamic: [] }, |
| 34 | + }; |
| 35 | + expect(referencedFileNames(entryPoints)).toEqual(['app.js', 'app.css', 'vendor.js', 'lazy.js', 'admin.js']); |
| 36 | + }); |
| 37 | +}); |
| 38 | + |
| 39 | +describe('integrityFromDisk', () => { |
| 40 | + it('hashes each named file (including nested paths) read from the output directory', () => { |
| 41 | + const dir = mkdtempSync(join(tmpdir(), 'reprise-sri-')); |
| 42 | + writeFileSync(join(dir, 'app.js'), 'reprise'); |
| 43 | + mkdirSync(dirname(join(dir, 'static/js/vendor.js')), { recursive: true }); |
| 44 | + writeFileSync(join(dir, 'static/js/vendor.js'), 'reprise'); |
| 45 | + |
| 46 | + expect(integrityFromDisk(['app.js', 'static/js/vendor.js'], dir, ['sha384'])).toEqual({ |
| 47 | + 'app.js': 'sha384-faAamSmmStfxJQ9skVshC6f5CFqO35HWc37M47/RU370OJxAaGp/EDpOhEtMqHU6', |
| 48 | + 'static/js/vendor.js': 'sha384-faAamSmmStfxJQ9skVshC6f5CFqO35HWc37M47/RU370OJxAaGp/EDpOhEtMqHU6', |
| 49 | + }); |
| 50 | + }); |
| 51 | +}); |
0 commit comments