// oxlint-disable typescript/no-implied-eval, typescript/no-unsafe-call, no-new-func -- the tests evaluate the emitted code exactly as the client does import { describe, expect, it } from 'vitest' import { DESERIALIZE_FUNCTIONS, serializeFunctions, } from '../../src/node/utils/fnSerialize.js' type AnyFunction = (...args: any[]) => any interface RestoredThemeData { editLink: { pattern: (page: { path: string }) => string } navbar: [ { link: (page: { path: string }) => string; text: string }, { items: { link: (page: { path: string }) => string }[] text: string }, ] } /** * Evaluate a serialized function expression the same way the generated module * exposes it to the client * * 与生成的模块一致地求值序列化后的函数表达式 * * @param source - The serialized function source / 序列化后的函数源码 * @returns The evaluated function / 求值后的函数 */ const evaluateFunction = (source: string): AnyFunction => new Function(`return ${source}`)() as AnyFunction /** * Evaluate the deserializer inlined into the generated module * * 求值内联进生成模块的反序列化器 * * @returns The deserializer / 反序列化器 */ const evaluateDeserializer = (): (( value: unknown, fns: AnyFunction[], ) => any) => new Function(`${DESERIALIZE_FUNCTIONS}\nreturn deserializeFunctions`)() as ( value: unknown, fns: AnyFunction[], ) => any describe(serializeFunctions, () => { it('should replace the function values with placeholders', () => { const fns: string[] = [] const page = { path: '/guide/' } const result = serializeFunctions( { pattern: (payload: typeof page) => `https://example.com${payload.path}`, }, fns, ) expect(result).toStrictEqual({ pattern: '_vp-fn_0' }) expect(fns).toHaveLength(1) expect(fns[0]).toContain('example.com') // the source is wrapped as an expression, so it can be emitted as code expect(fns[0]).toMatch(/^\([\S\s]*\)$/u) expect(evaluateFunction(fns[0])(page)).toBe('https://example.com/guide/') }) it('should rewrite the shorthand method into a function expression', () => { const fns: string[] = [] const page = { path: '/guide/' } const result = serializeFunctions( { pattern(payload: typeof page) { return `https://example.com${payload.path}` }, }, fns, ) expect(result).toStrictEqual({ pattern: '_vp-fn_0' }) // `(pattern(payload) { … })` is not a valid expression expect(fns[0]).toMatch(/^\(function\b/u) expect(evaluateFunction(fns[0])(page)).toBe('https://example.com/guide/') }) it('should rewrite the shorthand async method into an async function', () => { const fns: string[] = [] const page = { path: '/guide/' } const result = serializeFunctions( { // oxlint-disable-next-line typescript/require-await -- the async shorthand is the subject of the test async pattern(payload: typeof page) { return `https://example.com${payload.path}` }, }, fns, ) expect(result).toStrictEqual({ pattern: '_vp-fn_0' }) expect(fns[0]).toMatch(/^\(async function\b/u) return expect(evaluateFunction(fns[0])(page)).resolves.toBe( 'https://example.com/guide/', ) }) it('should rewrite the generator, computed and quoted methods into a function expression', () => { const fns: string[] = [] const page = { path: '/guide/' } const computedKey = 'computed' const methodObject = { *generator(payload: typeof page): Generator { yield payload }, [computedKey](payload: typeof page): string { return `computed${payload.path}` }, quoted(payload: typeof page): string { return `quoted${payload.path}` }, } const result = serializeFunctions(methodObject, fns) expect(result).toStrictEqual({ generator: '_vp-fn_0', computed: '_vp-fn_1', quoted: '_vp-fn_2', }) for (const source of fns) { expect(source).toMatch(/^\(function\b/u) expect(() => evaluateFunction(source)).not.toThrow() } expect( (evaluateFunction(fns[0])(page) as Generator).next().value, ).toStrictEqual(page) expect(evaluateFunction(fns[1])(page)).toBe('computed/guide/') expect(evaluateFunction(fns[2])(page)).toBe('quoted/guide/') }) it('should serialize a Date as an ISO string', () => { const fns: string[] = [] const date = new Date('2026-01-02T03:04:05.678Z') expect(serializeFunctions({ date }, fns)).toStrictEqual({ date: '2026-01-02T03:04:05.678Z', }) expect(fns).toStrictEqual([]) }) it('should skip the keys starting with an underscore', () => { const fns: string[] = [] const result = serializeFunctions( { _internal: (): number => 1, visible: (): number => 2 }, fns, ) expect(result).toStrictEqual({ visible: '_vp-fn_0' }) expect(result).not.toHaveProperty('_internal') expect(fns).toHaveLength(1) }) it('should recurse into the arrays and the nested objects', () => { const fns: string[] = [] const page = { path: '/guide/' } const link = (payload: typeof page): string => payload.path const result = serializeFunctions( { navbar: [{ link, text: 'Guide' }], locales: { '/': { editLink: { pattern: link } } }, }, fns, ) expect(result).toStrictEqual({ navbar: [{ link: '_vp-fn_0', text: 'Guide' }], locales: { '/': { editLink: { pattern: '_vp-fn_1' } } }, }) expect(fns).toHaveLength(2) // same function, different index expect(evaluateFunction(fns[0])(page)).toBe('/guide/') expect(evaluateFunction(fns[1])(page)).toBe('/guide/') }) it('should return the data untouched when it has no function', () => { const fns: string[] = [] const data = { navbar: [{ link: '/guide/', text: 'Guide' }], title: 'My Theme', } expect(serializeFunctions(data, fns)).toStrictEqual(data) expect(fns).toStrictEqual([]) }) it('should keep the primitive values', () => { const fns: string[] = [] expect(serializeFunctions('text', fns)).toBe('text') expect(serializeFunctions(42, fns)).toBe(42) expect(serializeFunctions(null, fns)).toBeNull() expect(serializeFunctions(false, fns)).toBe(false) }) }) describe(DESERIALIZE_FUNCTIONS, () => { it('should not rely on eval or new Function', () => { expect(DESERIALIZE_FUNCTIONS).not.toMatch(/\b(?:eval|new\s+Function)\b/u) }) it('should restore the functions from the collected sources', () => { const fns: string[] = [] const page = { path: '/guide/' } const link = (payload: typeof page): string => `https://example.com${payload.path}` const serialized = serializeFunctions( { editLink: { pattern: link }, navbar: [ { link, text: 'Guide' }, { items: [{ link }], text: 'Group' }, ], }, fns, ) const restored = evaluateDeserializer()( structuredClone(serialized), fns.map((source) => evaluateFunction(source)), ) as RestoredThemeData expect(restored.editLink.pattern).toBeTypeOf('function') expect(restored.editLink.pattern(page)).toBe('https://example.com/guide/') expect(restored.navbar[0].link).toBeTypeOf('function') expect(restored.navbar[0].link(page)).toBe('https://example.com/guide/') expect(restored.navbar[1].text).toBe('Group') expect(restored.navbar[1].items[0].link(page)).toBe( 'https://example.com/guide/', ) }) it('should keep the placeholders that have no matching function', () => { const restored = evaluateDeserializer()( { link: '_vp-fn_9', text: 'Guide' }, [], ) expect(restored).toStrictEqual({ link: '_vp-fn_9', text: 'Guide' }) }) it('should only restore the strings that are exactly a placeholder', () => { const page = { path: '/guide/' } const fns = [ (payload: typeof page): string => `https://example.com${payload.path}`, ] const restored = evaluateDeserializer()( { exact: '_vp-fn_0', trailingChars: '_vp-fn_0x1', prefixOnly: '_vp-fn_', notANumber: '_vp-fn_abc', }, fns, ) as Record expect(restored.exact).toBeTypeOf('function') expect((restored.exact as AnyFunction)(page)).toBe( 'https://example.com/guide/', ) expect(restored.trailingChars).toBe('_vp-fn_0x1') expect(restored.prefixOnly).toBe('_vp-fn_') expect(restored.notANumber).toBe('_vp-fn_abc') }) it('should keep the strings that only look similar to a placeholder', () => { const restored = evaluateDeserializer()({ link: '/_vp-fn/' }, []) expect(restored).toStrictEqual({ link: '/_vp-fn/' }) }) })