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

handleEnvOnly.ts

29 lines981 Bytes

1import { is } from 'yuku-ast'
2import { parseExpression } from '@tanstack/router-utils'
3import type { CompilationContext, RewriteCandidate } from './types'
4import type { LookupKind } from './compiler'
5​
6export function handleEnvOnlyFn(
7 candidates: Array<RewriteCandidate>,
8 context: CompilationContext,
9 kind: LookupKind,
10): void {
11 const target = kind === 'ClientOnlyFn' ? 'client' : 'server'
12 const factory = `create${target[0]!.toUpperCase()}${target.slice(1)}OnlyFn`
13 for (const { node } of candidates) {
14 if (context.env === target) {
15 const argument = node.arguments[0]
16 if (!is.Expression(argument)) {
17 throw new Error(`${factory}() must be called with a function!`)
18 }
19 context.replaceNode(node, argument)
20 } else {
21 context.replaceNode(
22 node,
23 parseExpression(
24 `() => { throw new Error(${JSON.stringify(`${factory}() functions can only be called on the ${target}!`)}); }`,
25 ),
26 )
27 }
28 }