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

_setup.ts

59 lines1.9 KB

1import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
2import { basename, dirname, join } from 'node:path'
3import { fileURLToPath } from 'node:url'
4import { transformSync } from 'esbuild'
5import { compile as compileToReact } from '@tsrx/react'
6​
7const directory = dirname(fileURLToPath(import.meta.url))
8const fixtureDirectory = join(directory, '../_fixtures')
9const cacheDirectory = join(directory, '.react-cache')
10const fixtureNames = ['cached-diff.tsrx', 'async-diff.tsrx']
11​
12function hashString(value: string): string {
13 let hash = 5381
14 for (let index = 0; index < value.length; index++) {
15 hash = ((hash << 5) + hash + value.charCodeAt(index)) | 0
16 }
17 return Math.abs(hash).toString(36)
19​
20function compileFixture(sourcePath: string): void {
21 const source = readFileSync(sourcePath, 'utf8')
22 const compiled = compileToReact(source, sourcePath)
23 if (compiled.errors.length) {
24 throw new Error(`React compilation failed for ${sourcePath}`)
25 }
26​
27 const transformed = transformSync(compiled.code, {
28 loader: 'tsx',
29 jsx: 'automatic',
30 jsxImportSource: 'react',
31 target: 'esnext',
32 format: 'esm',
33 sourcefile: sourcePath,
34 })
35 const rewritten = transformed.code
36 .replace(
37 /from\s+["']@tanstack\/octane-query(\/[^"']*)?["']/g,
38 (_match, subpath) => `from "@tanstack/react-query${subpath || ''}"`,
39 )
40 .replace(/from\s+["']octane["']/g, 'from "react"')
41 const slug = basename(sourcePath).replace(/\.tsrx$/, '')
42 const outputPath = join(
43 cacheDirectory,
44 `${slug}-${hashString(sourcePath)}.js`,
45 )
46 writeFileSync(outputPath, rewritten)
48​
49export function setup(): void {
50 rmSync(cacheDirectory, { force: true, recursive: true })
51 mkdirSync(cacheDirectory, { recursive: true })
52 for (const fixtureName of fixtureNames) {
53 compileFixture(join(fixtureDirectory, fixtureName))
54 }
56​
57export function teardown(): void {
58 rmSync(cacheDirectory, { force: true, recursive: true })