@farm.js/core 0.1.0-beta.14 → 0.1.0-beta.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/route-manager.cjs.map +1 -1
- package/dist/api/route-manager.mjs +2 -2
- package/dist/api/runtime.cjs.map +1 -1
- package/dist/api/runtime.mjs +1 -1
- package/dist/api.cjs +18 -10
- package/dist/api.cjs.map +1 -1
- package/dist/api.mjs +3 -3
- package/dist/{chunk-B232I2GP.mjs → chunk-3HIVDX7J.mjs} +12 -1
- package/dist/chunk-3HIVDX7J.mjs.map +1 -0
- package/dist/{chunk-JDEOUK5V.mjs → chunk-6YXKHAFU.mjs} +3 -3
- package/dist/{chunk-VUL55IAX.mjs → chunk-AN3PQVKH.mjs} +14 -16
- package/dist/{chunk-VUL55IAX.mjs.map → chunk-AN3PQVKH.mjs.map} +1 -1
- package/dist/{chunk-Z5CQMP54.mjs → chunk-ARRYKOI5.mjs} +2 -2
- package/dist/{chunk-KLA67WKG.mjs → chunk-B3FFOIWS.mjs} +2 -2
- package/dist/{chunk-ARCGE2VT.mjs → chunk-BWJC5ZOD.mjs} +2 -2
- package/dist/{chunk-ARCGE2VT.mjs.map → chunk-BWJC5ZOD.mjs.map} +1 -1
- package/dist/{chunk-PFE6GMNE.mjs → chunk-HMRFYJK6.mjs} +19 -11
- package/dist/chunk-HMRFYJK6.mjs.map +1 -0
- package/dist/{chunk-32W4QEJP.mjs → chunk-KFTGPFRD.mjs} +1 -1
- package/dist/chunk-KFTGPFRD.mjs.map +1 -0
- package/dist/{chunk-PNFQQSRA.mjs → chunk-OSWV5IJB.mjs} +114 -35
- package/dist/chunk-OSWV5IJB.mjs.map +1 -0
- package/dist/{chunk-OPHK6OJN.mjs → chunk-SLDBGSC3.mjs} +2 -2
- package/dist/{chunk-L2PE36GQ.mjs → chunk-T2KL7VEL.mjs} +3 -3
- package/dist/{chunk-WDU6QXNK.mjs → chunk-UCYWGN2P.mjs} +1 -1
- package/dist/chunk-UCYWGN2P.mjs.map +1 -0
- package/dist/{chunk-65A7QIKI.mjs → chunk-UMVLB3PN.mjs} +3 -3
- package/dist/chunk-UMVLB3PN.mjs.map +1 -0
- package/dist/{chunk-VY2UYN5R.mjs → chunk-VPCFICID.mjs} +82 -3
- package/dist/chunk-VPCFICID.mjs.map +1 -0
- package/dist/{chunk-H3TE3LOV.mjs → chunk-XMFTIVJH.mjs} +2 -2
- package/dist/{chunk-UB5UOSHB.mjs → chunk-ZVMV3THA.mjs} +71 -2
- package/dist/chunk-ZVMV3THA.mjs.map +1 -0
- package/dist/client.cjs.map +1 -1
- package/dist/client.mjs +3 -3
- package/dist/deployment.cjs +12 -0
- package/dist/deployment.cjs.map +1 -1
- package/dist/deployment.mjs +3 -1
- package/dist/{devtools-GAZ7F3KL.mjs → devtools-E4YNCY5J.mjs} +4 -4
- package/dist/docs.cjs.map +1 -1
- package/dist/docs.mjs +4 -4
- package/dist/index.cjs +306 -52
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +28 -16
- package/dist/index.mjs.map +1 -1
- package/dist/internal/build-runtime.cjs +133 -40
- package/dist/internal/build-runtime.cjs.map +1 -1
- package/dist/internal/build-runtime.mjs +11 -11
- package/dist/internal/config-runtime.cjs.map +1 -1
- package/dist/internal/config-runtime.mjs +3 -3
- package/dist/navigation.cjs.map +1 -1
- package/dist/navigation.mjs +3 -3
- package/dist/plugin.cjs +115 -28
- package/dist/plugin.cjs.map +1 -1
- package/dist/plugin.mjs +8 -8
- package/dist/server-action-security.cjs +23 -1
- package/dist/server-action-security.cjs.map +1 -1
- package/dist/server-action-security.mjs +1 -1
- package/dist/server-fn-client.cjs.map +1 -1
- package/dist/server-fn-client.mjs +1 -1
- package/dist/server-fn.cjs +140 -3
- package/dist/server-fn.cjs.map +1 -1
- package/dist/server-fn.mjs +14 -3
- package/dist/server-query.cjs +99 -1
- package/dist/server-query.cjs.map +1 -1
- package/dist/server-query.mjs +3 -3
- package/dist/server.cjs +234 -31
- package/dist/server.cjs.map +1 -1
- package/dist/server.mjs +11 -11
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.mjs +3 -3
- package/dist/version.cjs +1 -1
- package/dist/version.cjs.map +1 -1
- package/dist/version.mjs +1 -1
- package/dist/vite.cjs +116 -29
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.mjs +8 -8
- package/package.json +1 -1
- package/dist/chunk-32W4QEJP.mjs.map +0 -1
- package/dist/chunk-65A7QIKI.mjs.map +0 -1
- package/dist/chunk-B232I2GP.mjs.map +0 -1
- package/dist/chunk-PFE6GMNE.mjs.map +0 -1
- package/dist/chunk-PNFQQSRA.mjs.map +0 -1
- package/dist/chunk-UB5UOSHB.mjs.map +0 -1
- package/dist/chunk-VY2UYN5R.mjs.map +0 -1
- package/dist/chunk-WDU6QXNK.mjs.map +0 -1
- /package/dist/{chunk-JDEOUK5V.mjs.map → chunk-6YXKHAFU.mjs.map} +0 -0
- /package/dist/{chunk-Z5CQMP54.mjs.map → chunk-ARRYKOI5.mjs.map} +0 -0
- /package/dist/{chunk-KLA67WKG.mjs.map → chunk-B3FFOIWS.mjs.map} +0 -0
- /package/dist/{chunk-OPHK6OJN.mjs.map → chunk-SLDBGSC3.mjs.map} +0 -0
- /package/dist/{chunk-L2PE36GQ.mjs.map → chunk-T2KL7VEL.mjs.map} +0 -0
- /package/dist/{chunk-H3TE3LOV.mjs.map → chunk-XMFTIVJH.mjs.map} +0 -0
- /package/dist/{devtools-GAZ7F3KL.mjs.map → devtools-E4YNCY5J.mjs.map} +0 -0
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
} from "./chunk-V7RBCSDJ.mjs";
|
|
5
5
|
import {
|
|
6
6
|
resolveDocsConfig
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-T2KL7VEL.mjs";
|
|
8
8
|
import {
|
|
9
9
|
resolveFarmDocsFontAssets,
|
|
10
10
|
toFarmDocsPublicFontAssets
|
|
@@ -4002,4 +4002,4 @@ export {
|
|
|
4002
4002
|
createDocsAPI,
|
|
4003
4003
|
createFarmDocsAPIHandler
|
|
4004
4004
|
};
|
|
4005
|
-
//# sourceMappingURL=chunk-
|
|
4005
|
+
//# sourceMappingURL=chunk-SLDBGSC3.mjs.map
|
|
@@ -26,7 +26,7 @@ import {
|
|
|
26
26
|
} from "./chunk-GY2STC2S.mjs";
|
|
27
27
|
import {
|
|
28
28
|
resolveServerActionsConfig
|
|
29
|
-
} from "./chunk-
|
|
29
|
+
} from "./chunk-ZVMV3THA.mjs";
|
|
30
30
|
import {
|
|
31
31
|
resolveMdxConfig
|
|
32
32
|
} from "./chunk-ZVWA4ZQ3.mjs";
|
|
@@ -47,7 +47,7 @@ import {
|
|
|
47
47
|
} from "./chunk-FQYDHKKU.mjs";
|
|
48
48
|
import {
|
|
49
49
|
normalizeFarmDeploymentId
|
|
50
|
-
} from "./chunk-
|
|
50
|
+
} from "./chunk-3HIVDX7J.mjs";
|
|
51
51
|
import {
|
|
52
52
|
__name
|
|
53
53
|
} from "./chunk-CGILA3WO.mjs";
|
|
@@ -484,4 +484,4 @@ export {
|
|
|
484
484
|
resolveConfig,
|
|
485
485
|
loadConfig
|
|
486
486
|
};
|
|
487
|
-
//# sourceMappingURL=chunk-
|
|
487
|
+
//# sourceMappingURL=chunk-T2KL7VEL.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mutation-client.ts","../src/fetcher-client.tsx","../src/store.ts","../src/client/link.tsx"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport { isAPIRouteRef, type APIResult, type ClientOptions } from \"./api/client\";\n\nexport type MutationStatus = \"idle\" | \"pending\" | \"success\" | \"error\";\n\nexport type AnyMutationTarget = (...args: any[]) => Promise<any>;\n\nexport type InferMutationVariables<TTarget extends AnyMutationTarget> =\n Parameters<TTarget> extends [] ? undefined : Parameters<TTarget>[0];\n\nexport type InferMutationData<TTarget extends AnyMutationTarget> = TTarget extends {\n readonly __farmRouteData: infer TData;\n}\n ? TData\n : Awaited<ReturnType<TTarget>>;\n\nexport type InferMutationError<TTarget extends AnyMutationTarget> = TTarget extends {\n readonly __farmServerFnError: infer TError;\n}\n ? TError\n : TTarget extends (...args: any[]) => Promise<APIResult<any, infer TError>>\n ? TError\n : Error;\n\nexport type MutationOptimisticContext<TVariables, TData> = {\n variables: TVariables | undefined;\n current: TData | null;\n};\n\nexport type UseMutationOptions<TVariables, TData, TError = Error> = {\n initialData?: TData | null;\n resetOnMutate?: boolean;\n optimistic?: (context: MutationOptimisticContext<TVariables, TData>) => TData | null | undefined;\n rollbackOnError?: boolean;\n /**\n * Options forwarded to generated `api.route.method` clients.\n * Server functions ignore this field.\n */\n request?: ClientOptions<TData, TError>;\n onSuccess?: (data: TData, variables: TVariables | undefined) => void;\n onError?: (error: TError, variables: TVariables | undefined) => void;\n onSettled?: (data: TData | null, error: TError | null, variables: TVariables | undefined) => void;\n};\n\ntype MutationInput<TTarget extends AnyMutationTarget> = InferMutationVariables<TTarget>;\n\ntype MutationData<TTarget extends AnyMutationTarget> = InferMutationData<TTarget>;\n\ntype MutationError<TTarget extends AnyMutationTarget> = InferMutationError<TTarget>;\n\nexport type MutationAsync<TTarget extends AnyMutationTarget, TData = MutationData<TTarget>> =\n [] extends Parameters<TTarget>\n ? (variables?: MutationInput<TTarget>) => Promise<TData>\n : (variables: MutationInput<TTarget>) => Promise<TData>;\n\nexport type MutationTrigger<TTarget extends AnyMutationTarget> =\n [] extends Parameters<TTarget>\n ? (variables?: MutationInput<TTarget>) => void\n : (variables: MutationInput<TTarget>) => void;\n\nexport type UseMutationReturn<\n TTarget extends AnyMutationTarget,\n TData = MutationData<TTarget>,\n TError = MutationError<TTarget>,\n> = {\n pending: boolean;\n status: MutationStatus;\n data: TData | null;\n error: TError | null;\n variables: MutationInput<TTarget> | undefined;\n mutate: MutationTrigger<TTarget>;\n mutateAsync: MutationAsync<TTarget, TData>;\n reset: () => void;\n};\n\ntype MutationState<TVariables, TData, TError> = {\n pendingCount: number;\n status: MutationStatus;\n data: TData | null;\n error: TError | null;\n variables: TVariables | undefined;\n};\n\n/**\n * Track a generated API route mutation or a Farm server function with one\n * React lifecycle.\n *\n * API routes keep using their existing fetch transport and request options.\n * Server functions keep using their configured server-function transport.\n */\nexport function useMutation<TTarget extends AnyMutationTarget>(\n target: TTarget,\n options: UseMutationOptions<\n MutationInput<TTarget>,\n MutationData<TTarget>,\n MutationError<TTarget>\n > = {},\n): UseMutationReturn<TTarget> {\n type TVariables = MutationInput<TTarget>;\n type TData = MutationData<TTarget>;\n type TError = MutationError<TTarget>;\n\n const initialData = options.initialData ?? null;\n const optionsRef = useRef(options);\n const targetRef = useRef(target);\n const requestIdRef = useRef(0);\n const initialState: MutationState<TVariables, TData, TError> = {\n pendingCount: 0,\n status: \"idle\",\n data: initialData,\n error: null,\n variables: undefined,\n };\n const stateRef = useRef(initialState);\n const [state, setState] = useState<MutationState<TVariables, TData, TError>>(initialState);\n\n optionsRef.current = options;\n targetRef.current = target;\n\n const setMutationState = useCallback(\n (\n value:\n | MutationState<TVariables, TData, TError>\n | ((\n current: MutationState<TVariables, TData, TError>,\n ) => MutationState<TVariables, TData, TError>),\n ) => {\n setState((current) => {\n const next = typeof value === \"function\" ? value(current) : value;\n stateRef.current = next;\n return next;\n });\n },\n [],\n );\n\n const mutateAsync = useCallback(\n async (variables?: TVariables) => {\n const requestId = ++requestIdRef.current;\n const currentOptions = optionsRef.current;\n const previousData = stateRef.current.data;\n const optimisticData = currentOptions.optimistic?.({\n variables,\n current: previousData,\n });\n const hasOptimisticData = optimisticData !== undefined;\n\n setMutationState((current) => ({\n pendingCount: current.pendingCount + 1,\n status: \"pending\",\n data: hasOptimisticData\n ? optimisticData\n : currentOptions.resetOnMutate === false\n ? current.data\n : null,\n error: null,\n variables,\n }));\n\n try {\n const mutationTarget = targetRef.current;\n const rawResult = isAPIRouteRef(mutationTarget)\n ? await mutationTarget(variables, currentOptions.request)\n : await mutationTarget(variables);\n const data = unwrapMutationResult<TData, TError>(rawResult, isAPIRouteRef(mutationTarget));\n const isLatestRequest = requestId === requestIdRef.current;\n\n setMutationState((current) => {\n const pendingCount = Math.max(0, current.pendingCount - 1);\n if (!isLatestRequest) {\n return {\n ...current,\n pendingCount,\n status: pendingCount > 0 ? \"pending\" : current.status,\n };\n }\n\n return {\n pendingCount,\n status: \"success\",\n data,\n error: null,\n variables,\n };\n });\n\n if (isLatestRequest) {\n currentOptions.onSuccess?.(data, variables);\n currentOptions.onSettled?.(data, null, variables);\n }\n\n return data;\n } catch (cause) {\n const error = normalizeMutationError(cause) as TError;\n const isLatestRequest = requestId === requestIdRef.current;\n\n setMutationState((current) => {\n const pendingCount = Math.max(0, current.pendingCount - 1);\n if (!isLatestRequest) {\n return {\n ...current,\n pendingCount,\n status: pendingCount > 0 ? \"pending\" : current.status,\n };\n }\n\n return {\n pendingCount,\n status: \"error\",\n data:\n hasOptimisticData && currentOptions.rollbackOnError\n ? previousData\n : currentOptions.resetOnMutate === false\n ? current.data\n : null,\n error,\n variables,\n };\n });\n\n if (isLatestRequest) {\n currentOptions.onError?.(error, variables);\n currentOptions.onSettled?.(null, error, variables);\n }\n\n throw error;\n }\n },\n [setMutationState],\n ) as MutationAsync<TTarget, TData>;\n\n const mutate = useCallback(\n (variables?: TVariables) => {\n void mutateAsync(variables as never).catch(() => {});\n },\n [mutateAsync],\n ) as MutationTrigger<TTarget>;\n\n const reset = useCallback(() => {\n requestIdRef.current += 1;\n setMutationState({\n pendingCount: 0,\n status: \"idle\",\n data: optionsRef.current.initialData ?? null,\n error: null,\n variables: undefined,\n });\n }, [setMutationState]);\n\n return useMemo(\n () => ({\n pending: state.pendingCount > 0,\n status: state.status,\n data: state.data,\n error: state.error,\n variables: state.variables,\n mutate,\n mutateAsync,\n reset,\n }),\n [\n mutate,\n mutateAsync,\n reset,\n state.data,\n state.error,\n state.pendingCount,\n state.status,\n state.variables,\n ],\n );\n}\n\nfunction unwrapMutationResult<TData, TError>(result: unknown, apiRoute: boolean): TData {\n if (!apiRoute) return result as TData;\n\n const apiResult = result as APIResult<TData, TError>;\n if (apiResult.error) {\n throw apiResult.error;\n }\n\n return apiResult.data as TData;\n}\n\nfunction normalizeMutationError(error: unknown): Error {\n if (error instanceof Error) return error;\n\n const normalized = new Error(typeof error === \"string\" ? error : \"Mutation failed\");\n (normalized as Error & { cause?: unknown }).cause = error;\n return normalized;\n}\n","\"use client\";\n\nimport {\n createElement,\n useCallback,\n useMemo,\n useRef,\n useState,\n type ComponentType,\n type FormEvent,\n type FormHTMLAttributes,\n} from \"react\";\nimport { getAPIRouteRefMetadata, isAPIRouteRef } from \"./api/client\";\nimport {\n useMutation,\n type AnyMutationTarget,\n type InferMutationData,\n type InferMutationError,\n type InferMutationVariables,\n type MutationStatus,\n type UseMutationOptions,\n} from \"./mutation-client\";\n\nexport type FetcherState = \"idle\" | \"submitting\";\n\nexport type FetcherFormDataContext = {\n form: HTMLFormElement | null;\n submitter: HTMLElement | null;\n};\n\nexport type UseFetcherOptions<TTarget extends AnyMutationTarget> = UseMutationOptions<\n InferMutationVariables<TTarget>,\n InferMutationData<TTarget>,\n InferMutationError<TTarget>\n> & {\n /**\n * Convert browser FormData into the target's typed variables.\n *\n * Generated API routes default to `{ body: Object.fromEntries(formData) }`\n * (or `{ query: ... }` for GET/HEAD). Server functions receive FormData\n * directly so their input schema remains authoritative.\n */\n mapFormData?: (\n formData: FormData,\n context: FetcherFormDataContext,\n ) => InferMutationVariables<TTarget>;\n};\n\nexport type FetcherFormProps = Omit<FormHTMLAttributes<HTMLFormElement>, \"action\" | \"onSubmit\"> & {\n /**\n * Override the native form fallback. By default server functions remain the\n * action and generated GET/POST API routes use their real URL.\n */\n action?: string | ((formData: FormData) => void | Promise<void>);\n onSubmit?: (event: FormEvent<HTMLFormElement>) => void;\n};\n\ntype FetcherInput<TTarget extends AnyMutationTarget> = InferMutationVariables<TTarget> | FormData;\n\nexport type FetcherSubmitAsync<TTarget extends AnyMutationTarget> =\n [] extends Parameters<TTarget>\n ? (input?: FetcherInput<TTarget>) => Promise<InferMutationData<TTarget>>\n : (input: FetcherInput<TTarget>) => Promise<InferMutationData<TTarget>>;\n\nexport type FetcherSubmit<TTarget extends AnyMutationTarget> =\n [] extends Parameters<TTarget>\n ? (input?: FetcherInput<TTarget>) => void\n : (input: FetcherInput<TTarget>) => void;\n\nexport type UseFetcherReturn<TTarget extends AnyMutationTarget> = {\n state: FetcherState;\n status: MutationStatus;\n pending: boolean;\n data: InferMutationData<TTarget> | null;\n error: InferMutationError<TTarget> | null;\n variables: InferMutationVariables<TTarget> | undefined;\n formData: FormData | null;\n submit: FetcherSubmit<TTarget>;\n submitAsync: FetcherSubmitAsync<TTarget>;\n Form: ComponentType<FetcherFormProps>;\n reset: () => void;\n};\n\nconst formDataContexts = new WeakMap<FormData, FetcherFormDataContext>();\n\n/**\n * Run a typed server function or generated API operation without navigating.\n *\n * `fetcher.Form` progressively keeps a server function as the native form\n * action, while hydration intercepts submissions into this fetcher lifecycle.\n */\nexport function useFetcher<TTarget extends AnyMutationTarget>(\n target: TTarget,\n options: UseFetcherOptions<TTarget> = {},\n): UseFetcherReturn<TTarget> {\n const targetRef = useRef(target);\n const optionsRef = useRef(options);\n const submissionIdRef = useRef(0);\n const [formData, setFormData] = useState<FormData | null>(null);\n const mutation = useMutation(target, options);\n\n targetRef.current = target;\n optionsRef.current = options;\n\n const submitAsync = useCallback(\n async (input?: FetcherInput<TTarget>) => {\n const submissionId = ++submissionIdRef.current;\n const submittedFormData = isFormData(input) ? input : null;\n setFormData(submittedFormData);\n\n try {\n const variables = submittedFormData\n ? mapFetcherFormData(targetRef.current, submittedFormData, optionsRef.current)\n : input;\n return await mutation.mutateAsync(variables as InferMutationVariables<TTarget>);\n } finally {\n if (submissionId === submissionIdRef.current) {\n setFormData(null);\n }\n }\n },\n [mutation.mutateAsync],\n ) as FetcherSubmitAsync<TTarget>;\n\n const submit = useCallback(\n (input?: FetcherInput<TTarget>) => {\n void submitAsync(input as never).catch(() => {});\n },\n [submitAsync],\n ) as FetcherSubmit<TTarget>;\n\n const Form = useMemo(() => {\n const FetcherForm = ({ action, method, encType, onSubmit, ...props }: FetcherFormProps) => {\n const targetValue = targetRef.current;\n const metadata = getAPIRouteRefMetadata(targetValue);\n const nativeAction = action ?? resolveFetcherFormAction(targetValue, metadata);\n const nativeMethod =\n method ??\n (metadata && (metadata.method === \"GET\" || metadata.method === \"POST\")\n ? metadata.method.toLowerCase()\n : metadata\n ? \"post\"\n : undefined);\n const functionAction = typeof nativeAction === \"function\";\n\n const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n onSubmit?.(event);\n if (event.defaultPrevented) return;\n\n event.preventDefault();\n const submitter = getSubmitter(event);\n const nextFormData = createSubmitterFormData(event.currentTarget, submitter);\n formDataContexts.set(nextFormData, {\n form: event.currentTarget,\n submitter,\n });\n void submitAsync(nextFormData as never).catch(() => {});\n };\n\n return createElement(\"form\", {\n ...props,\n action: nativeAction as FormHTMLAttributes<HTMLFormElement>[\"action\"],\n method: functionAction ? undefined : nativeMethod,\n encType: functionAction ? undefined : encType,\n onSubmit: handleSubmit,\n });\n };\n\n FetcherForm.displayName = \"FetcherForm\";\n return FetcherForm;\n }, [submitAsync]);\n\n const reset = useCallback(() => {\n submissionIdRef.current += 1;\n setFormData(null);\n mutation.reset();\n }, [mutation.reset]);\n\n return useMemo(\n () => ({\n state: mutation.pending ? \"submitting\" : \"idle\",\n status: mutation.status,\n pending: mutation.pending,\n data: mutation.data,\n error: mutation.error,\n variables: mutation.variables,\n formData,\n submit,\n submitAsync,\n Form,\n reset,\n }),\n [\n Form,\n formData,\n mutation.data,\n mutation.error,\n mutation.pending,\n mutation.status,\n mutation.variables,\n reset,\n submit,\n submitAsync,\n ],\n );\n}\n\nfunction mapFetcherFormData<TTarget extends AnyMutationTarget>(\n target: TTarget,\n formData: FormData,\n options: UseFetcherOptions<TTarget>,\n): InferMutationVariables<TTarget> | FormData {\n const context = formDataContexts.get(formData) ?? { form: null, submitter: null };\n if (options.mapFormData) {\n return options.mapFormData(formData, context);\n }\n if (!isAPIRouteRef(target)) {\n return formData;\n }\n\n const values = formDataToObject(formData);\n const method = getAPIRouteRefMetadata(target)?.method;\n return (\n method === \"GET\" || method === \"HEAD\" ? { query: values } : { body: values }\n ) as InferMutationVariables<TTarget>;\n}\n\nfunction resolveFetcherFormAction(\n target: AnyMutationTarget,\n metadata: ReturnType<typeof getAPIRouteRefMetadata>,\n): string | AnyMutationTarget | undefined {\n if (!metadata) return isProgressiveFormAction(target) ? target : undefined;\n if (metadata.sameOrigin) return metadata.path;\n\n return new URL(metadata.path, metadata.baseURL).href;\n}\n\nfunction formDataToObject(\n formData: FormData,\n): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n const output: Record<string, FormDataEntryValue | FormDataEntryValue[]> = Object.create(null);\n for (const [key, value] of formData.entries()) {\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue;\n const current = output[key];\n if (current === undefined) {\n output[key] = value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n output[key] = [current, value];\n }\n }\n return output;\n}\n\nfunction createSubmitterFormData(form: HTMLFormElement, submitter: HTMLElement | null): FormData {\n try {\n return new FormData(form, submitter as HTMLElement | undefined);\n } catch {\n const formData = new FormData(form);\n const candidate = submitter as\n | (HTMLElement & { disabled?: boolean; name?: string; value?: string })\n | null;\n if (candidate && !candidate.disabled && candidate.name) {\n formData.append(candidate.name, candidate.value ?? \"\");\n }\n return formData;\n }\n}\n\nfunction getSubmitter(event: FormEvent<HTMLFormElement>): HTMLElement | null {\n const nativeEvent = event.nativeEvent as SubmitEvent;\n return nativeEvent.submitter instanceof HTMLElement ? nativeEvent.submitter : null;\n}\n\nfunction isProgressiveFormAction(target: AnyMutationTarget): boolean {\n const candidate = target as AnyMutationTarget & {\n __farmServerFn?: unknown;\n $$FORM_ACTION?: unknown;\n $$typeof?: unknown;\n };\n return (\n candidate.__farmServerFn === true ||\n typeof candidate.$$FORM_ACTION === \"function\" ||\n candidate.$$typeof === Symbol.for(\"react.server.reference\")\n );\n}\n\nfunction isFormData(value: unknown): value is FormData {\n if (!value || typeof value !== \"object\") return false;\n return (\n (typeof FormData !== \"undefined\" && value instanceof FormData) ||\n (Object.prototype.toString.call(value) === \"[object FormData]\" &&\n typeof (value as { entries?: unknown }).entries === \"function\")\n );\n}\n","import { useSyncExternalStore } from \"react\";\n\nexport type StoreState = Record<string, any>;\nexport type StoreValueUpdater<T> = T | ((previous: T) => T);\nexport type StorePatch<T extends StoreState> = Partial<T> | ((state: T) => Partial<T>);\nexport type StoreListener<T extends StoreState> = (state: T, previousState: T) => void;\nexport type StoreKeyListener<T extends StoreState, K extends keyof T> = (\n value: T[K],\n previousValue: T[K],\n) => void;\nexport type StoreKeysListener<T extends StoreState, K extends keyof T> = (\n value: Pick<T, K>,\n previousValue: Pick<T, K>,\n) => void;\n\ntype StoreSubscription<T extends StoreState> = {\n keys: readonly (keyof T)[] | null;\n notify: (state: T, previousState: T) => void;\n};\n\ntype ReservedStoreKey = \"use\" | \"get\" | \"set\" | \"replace\" | \"reset\" | \"subscribe\";\n\ntype FieldAccessor<T extends StoreState, K extends keyof T> = {\n (): T[K];\n get(): T[K];\n set(value: StoreValueUpdater<T[K]>): T[K];\n subscribe(listener: StoreKeyListener<T, K>): () => void;\n};\n\nexport type StoreFields<T extends StoreState> = {\n [K in keyof T]: FieldAccessor<T, K>;\n};\n\nexport interface StoreApi<T extends StoreState> {\n use(): T;\n use<K extends keyof T>(key: K): T[K];\n use<K extends keyof T>(keys: readonly K[]): Pick<T, K>;\n get(): T;\n get<K extends keyof T>(key: K): T[K];\n set<K extends keyof T>(key: K, value: StoreValueUpdater<T[K]>): T[K];\n set(patch: StorePatch<T>): T;\n replace(nextState: T | ((state: T) => T)): T;\n reset(): T;\n subscribe(listener: StoreListener<T>): () => void;\n subscribe<K extends keyof T>(key: K, listener: StoreKeyListener<T, K>): () => void;\n subscribe<K extends keyof T>(keys: readonly K[], listener: StoreKeysListener<T, K>): () => void;\n}\n\nexport type Store<T extends StoreState, TMethods extends Record<string, any> = {}> = StoreApi<T> &\n StoreFields<T> &\n TMethods;\n\nconst RESERVED_STORE_KEYS = new Set<ReservedStoreKey>([\n \"use\",\n \"get\",\n \"set\",\n \"replace\",\n \"reset\",\n \"subscribe\",\n]);\n\nfunction cloneState<T extends StoreState>(state: T): T {\n return { ...state };\n}\n\nfunction pickState<T extends StoreState, K extends keyof T>(\n state: T,\n keys: readonly K[],\n): Pick<T, K> {\n const slice = {} as Pick<T, K>;\n\n for (const key of keys) {\n slice[key] = state[key];\n }\n\n return slice;\n}\n\nfunction getChangedKeys<T extends StoreState>(state: T, previousState: T): (keyof T)[] {\n const keys = new Set<keyof T>([\n ...(Object.keys(state) as (keyof T)[]),\n ...(Object.keys(previousState) as (keyof T)[]),\n ]);\n\n return [...keys].filter((key) => !Object.is(state[key], previousState[key]));\n}\n\nfunction normalizeKeys<T extends StoreState, K extends keyof T>(keys: readonly K[]): readonly K[] {\n return Array.from(new Set(keys));\n}\n\nfunction resolveValue<T>(value: StoreValueUpdater<T>, previousValue: T): T {\n return typeof value === \"function\" ? (value as (previousValue: T) => T)(previousValue) : value;\n}\n\nfunction isStoreKey(value: unknown): value is string | number | symbol {\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"symbol\";\n}\n\nexport function createStore<T extends StoreState, TMethods extends Record<string, any> = {}>(\n initialState: T,\n extend?: (store: Store<T>) => TMethods,\n): Store<T, TMethods> {\n const initialSnapshot = cloneState(initialState);\n let state = cloneState(initialState);\n const subscriptions = new Set<StoreSubscription<T>>();\n\n const addSubscription = (\n keys: readonly (keyof T)[] | null,\n notify: (state: T, previousState: T) => void,\n ) => {\n const subscription: StoreSubscription<T> = { keys, notify };\n subscriptions.add(subscription);\n return () => {\n subscriptions.delete(subscription);\n };\n };\n\n const emit = (nextState: T, previousState: T) => {\n const changedKeys = getChangedKeys(nextState, previousState);\n\n if (changedKeys.length === 0) {\n return;\n }\n\n const changedKeySet = new Set(changedKeys);\n\n for (const subscription of subscriptions) {\n if (subscription.keys === null || subscription.keys.some((key) => changedKeySet.has(key))) {\n subscription.notify(nextState, previousState);\n }\n }\n };\n\n const getState = (key?: keyof T) => {\n return key === undefined ? state : state[key];\n };\n\n const replaceState = (nextState: T | ((state: T) => T)) => {\n const previousState = state;\n const resolvedState =\n typeof nextState === \"function\" ? (nextState as (state: T) => T)(previousState) : nextState;\n state = resolvedState;\n emit(state, previousState);\n return state;\n };\n\n const setState = (keyOrPatch: keyof T | StorePatch<T>, value?: StoreValueUpdater<T[keyof T]>) => {\n const previousState = state;\n let nextState: T;\n\n if (isStoreKey(keyOrPatch)) {\n const key = keyOrPatch as keyof T;\n const nextValue = resolveValue(value as StoreValueUpdater<T[keyof T]>, previousState[key]);\n\n if (Object.is(previousState[key], nextValue)) {\n return nextValue;\n }\n\n nextState = {\n ...previousState,\n [key]: nextValue,\n };\n state = nextState;\n emit(nextState, previousState);\n return nextValue;\n }\n\n const patch: Partial<T> =\n typeof keyOrPatch === \"function\"\n ? (keyOrPatch as (state: T) => Partial<T>)(previousState)\n : (keyOrPatch as Partial<T>);\n\n nextState = {\n ...previousState,\n ...patch,\n };\n state = nextState;\n emit(nextState, previousState);\n return nextState;\n };\n\n const subscribeState = (\n keyOrListener: keyof T | readonly (keyof T)[] | StoreListener<T>,\n listener?: StoreKeyListener<T, keyof T> | StoreKeysListener<T, keyof T>,\n ) => {\n if (typeof keyOrListener === \"function\") {\n return addSubscription(null, (nextState, previousState) => {\n (keyOrListener as StoreListener<T>)(nextState, previousState);\n });\n }\n\n if (Array.isArray(keyOrListener)) {\n const keys = normalizeKeys(keyOrListener);\n return addSubscription(keys, (nextState, previousState) => {\n (listener as StoreKeysListener<T, keyof T>)(\n pickState(nextState, keys),\n pickState(previousState, keys),\n );\n });\n }\n\n const key = keyOrListener as keyof T;\n return addSubscription([key], (nextState, previousState) => {\n (listener as StoreKeyListener<T, keyof T>)(nextState[key], previousState[key]);\n });\n };\n\n const useStateValue = <K extends keyof T>(keyOrKeys?: K | readonly K[]) => {\n if (Array.isArray(keyOrKeys)) {\n const keys = normalizeKeys(keyOrKeys);\n let lastState = state;\n let lastSlice = pickState(state, keys);\n const getSnapshot = () => {\n if (lastState !== state) {\n lastState = state;\n lastSlice = pickState(state, keys);\n }\n\n return lastSlice;\n };\n\n return useSyncExternalStore(\n (notify) => addSubscription(keys, () => notify()),\n getSnapshot,\n getSnapshot,\n );\n }\n\n if (typeof keyOrKeys === \"string\") {\n return useSyncExternalStore(\n (notify) => addSubscription([keyOrKeys], () => notify()),\n () => state[keyOrKeys],\n () => state[keyOrKeys],\n );\n }\n\n return useSyncExternalStore(\n (notify) => addSubscription(null, () => notify()),\n () => state,\n () => state,\n );\n };\n\n const store = {\n use: useStateValue,\n get: getState,\n set: setState,\n replace: replaceState,\n reset: () => replaceState(cloneState(initialSnapshot)),\n subscribe: subscribeState,\n } as Store<T>;\n\n for (const key of Object.keys(initialSnapshot) as (keyof T)[]) {\n if (RESERVED_STORE_KEYS.has(key as ReservedStoreKey)) {\n throw new Error(\n `createStore does not allow the reserved key \"${String(key)}\" in the initial state.`,\n );\n }\n\n const field = (() => useStateValue(key)) as FieldAccessor<T, typeof key>;\n field.get = () => state[key];\n field.set = (value) => setState(key, value) as T[typeof key];\n field.subscribe = (listener) => subscribeState(key, listener as StoreKeyListener<T, keyof T>);\n\n Object.defineProperty(store, key, {\n configurable: false,\n enumerable: true,\n value: field,\n writable: false,\n });\n }\n\n if (extend) {\n const methods = extend(store);\n\n for (const [name, method] of Object.entries(methods)) {\n if (name in store) {\n throw new Error(\n `createStore cannot attach the method \"${name}\" because it already exists.`,\n );\n }\n\n Object.defineProperty(store, name, {\n configurable: false,\n enumerable: true,\n value: method,\n writable: false,\n });\n }\n }\n\n return store as Store<T, TMethods>;\n}\n","\"use client\";\n\nimport type React from \"react\";\nimport { forwardRef, useEffect, useRef, useCallback, type AnchorHTMLAttributes } from \"react\";\nimport {\n buildFarmRoutePath,\n type FarmRouterBuildOptions,\n type FarmRouterPathParam,\n type FarmRouterPathParams,\n} from \"../router\";\nimport type { FarmViewTransitionMode } from \"./spa-router\";\nimport { isFarmLocaleChangeHref, localizeActiveFarmHref } from \"../i18n/client-runtime\";\nimport type { FarmI18nLocale } from \"../i18n/types\";\n\n/**\n * Prefetch strategy (TanStack Router–style):\n * - \"intent\": prefetch on hover and touchstart (with prefetchDelay)\n * - \"viewport\": prefetch when link enters viewport (IntersectionObserver)\n * - \"render\": prefetch as soon as the link is mounted\n * - \"none\" | false: no prefetch\n */\nexport type PrefetchBehavior = false | \"intent\" | \"viewport\" | \"render\" | \"none\";\n\n/** @internal Legacy prefetch mode for backward compatibility */\ntype PrefetchLegacy = boolean | \"hover\" | \"viewport\" | \"none\";\n\n/**\n * Augment this interface via the generated farm.d.ts so Link href is typed\n * without passing a generic. Defaults to string when not augmented.\n */\nexport interface LinkDefaultRoute {}\n\nexport type DefaultRoutePath = LinkDefaultRoute extends { _: infer TRoute extends string }\n ? TRoute\n : string;\n\nexport type DefaultRoutePattern = LinkDefaultRoute extends {\n pattern: infer TRoute extends string;\n}\n ? TRoute\n : DefaultRoutePath;\n\nexport type DefaultRouteHref = DefaultRoutePath | DefaultRoutePattern;\n\nexport type RouteHref<TRoute extends string> =\n | TRoute\n | `${TRoute}?${string}`\n | `${TRoute}#${string}`\n | `${TRoute}?${string}#${string}`;\n\n/** A generated route with params already filled into its pathname. */\nexport type ResolvedRouteHref = RouteHref<DefaultRoutePath>;\n\nexport type RouteParamValue = Exclude<FarmRouterPathParam, null | undefined>;\nexport type RouteOptionalParamValue = FarmRouterPathParam;\nexport type RouteParams<TRoute extends string> = string extends TRoute\n ? FarmRouterPathParams\n : ExtractRouteParams<StripRouteSuffix<TRoute>>;\n\n/** External URLs; these are never type-checked as routes. */\nexport type ExternalHref =\n | `http://${string}`\n | `https://${string}`\n | `//${string}`\n | `mailto:${string}`;\n\ntype StripRouteSuffix<TRoute extends string> = TRoute extends `${infer Path}?${string}`\n ? StripRouteSuffix<Path>\n : TRoute extends `${infer Path}#${string}`\n ? StripRouteSuffix<Path>\n : TRoute;\n\ntype ExtractRouteParams<TRoute extends string> = Simplify<\n ExtractOptionalCatchAllParams<TRoute> &\n ExtractCatchAllParams<TRoute> &\n ExtractDynamicParams<TRoute>\n>;\n\ntype ExtractOptionalCatchAllParams<TRoute extends string> =\n TRoute extends `${string}[[...${infer Param}]]${infer Rest}`\n ? { [Key in Param]?: RouteOptionalParamValue } & ExtractOptionalCatchAllParams<Rest>\n : {};\n\ntype ExtractCatchAllParams<TRoute extends string> =\n TRoute extends `${string}[...${infer Param}]${infer Rest}`\n ? Param extends `[...${string}`\n ? ExtractCatchAllParams<Rest>\n : { [Key in Param]: RouteParamValue } & ExtractCatchAllParams<Rest>\n : {};\n\ntype ExtractDynamicParams<TRoute extends string> =\n TRoute extends `${string}[${infer Param}]${infer Rest}`\n ? Param extends `...${string}` | `[...${string}`\n ? ExtractDynamicParams<Rest>\n : { [Key in Param]: RouteParamValue } & ExtractDynamicParams<Rest>\n : {};\n\ntype Simplify<T> = { [Key in keyof T]: T[Key] } & {};\n\ntype HasRouteParams<TRoute extends string> = keyof RouteParams<TRoute> extends never ? false : true;\n\ntype RoutesWithRequiredParams<TRoute extends string> = TRoute extends string\n ? HasRouteParams<TRoute> extends true\n ? TRoute\n : never\n : never;\n\ntype LinkRouteParamsProps<TRoute extends string> = string extends TRoute\n ? { params?: FarmRouterPathParams }\n : HasRouteParams<TRoute> extends true\n ? { params: RouteParams<TRoute> }\n : { params?: FarmRouterPathParams };\n\ntype LinkRouteTargetProps<TRoute extends string> = [RoutesWithRequiredParams<TRoute>] extends [\n never,\n]\n ? {\n /** Internal route path with all params already resolved. */\n href: RouteHref<TRoute>;\n params?: FarmRouterPathParams;\n }\n : TRoute extends string\n ? {\n /** Internal route path or route pattern. */\n href: RouteHref<TRoute>;\n } & LinkRouteParamsProps<TRoute>\n : never;\n\ntype LinkExternalTargetProps = {\n /** External URL; these are never type-checked as app routes. */\n href: ExternalHref;\n params?: never;\n};\n\ntype LinkTargetProps<TRoute extends string> =\n | LinkExternalTargetProps\n | LinkRouteTargetProps<TRoute>;\n\nexport type LinkProps<TRoute extends string = DefaultRouteHref> = Omit<\n AnchorHTMLAttributes<HTMLAnchorElement>,\n \"href\"\n> &\n LinkTargetProps<TRoute> & {\n /**\n * When to prefetch. TanStack-style: \"intent\" (hover+touch), \"viewport\", \"render\", or \"none\".\n * Legacy: true (intent+viewport), \"hover\" (intent), \"viewport\", false/\"none\".\n */\n prefetch?: PrefetchBehavior | PrefetchLegacy;\n /** Search params appended after route params are resolved. */\n query?: FarmRouterBuildOptions[\"query\"];\n /** Hash appended after route params and search params are resolved. */\n hash?: string;\n /** Add a trailing slash to the generated internal href. */\n trailingSlash?: boolean;\n /** Delay in ms before intent-based prefetch (hover/touch). Default 50. */\n prefetchDelay?: number;\n /** Replace current history entry instead of pushing */\n replace?: boolean;\n /** Scroll to top after navigation (default: true) */\n scroll?: boolean;\n /** Wrap this SPA navigation in a browser View Transition when supported. */\n viewTransition?: FarmViewTransitionMode;\n /** Preserve the active locale by default, or navigate using this locale. */\n locale?: FarmI18nLocale;\n };\n\nfunction isModifierEvent(e: React.MouseEvent): boolean {\n return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);\n}\n\nfunction isExternalUrl(href: string): boolean {\n return href.startsWith(\"http://\") || href.startsWith(\"https://\") || href.startsWith(\"//\");\n}\n\nfunction getRouter(): {\n prefetch(href: string): Promise<void>;\n observeForPrefetch(el: HTMLAnchorElement): void;\n unobserveForPrefetch(el: HTMLAnchorElement): void;\n navigate(\n href: string,\n opts: { replace?: boolean; scroll?: boolean; viewTransition?: FarmViewTransitionMode },\n ): void;\n} | null {\n if (typeof window !== \"undefined\" && (window as any).__FARM_SPA_ROUTER__) {\n return (window as any).__FARM_SPA_ROUTER__;\n }\n return null;\n}\n\nfunction normalizePrefetch(prefetch: LinkProps[\"prefetch\"]): {\n intent: boolean;\n viewport: boolean;\n render: boolean;\n} {\n if (prefetch === false || prefetch === \"none\") {\n return { intent: false, viewport: false, render: false };\n }\n if (prefetch === true) {\n return { intent: true, viewport: true, render: false };\n }\n if (prefetch === \"hover\") {\n return { intent: true, viewport: false, render: false };\n }\n if (prefetch === \"intent\") {\n return { intent: true, viewport: false, render: false };\n }\n if (prefetch === \"viewport\") {\n return { intent: false, viewport: true, render: false };\n }\n if (prefetch === \"render\") {\n return { intent: false, viewport: false, render: true };\n }\n return { intent: false, viewport: false, render: false };\n}\n\nfunction LinkInner<TRoute extends string = DefaultRouteHref>(\n {\n href,\n params,\n query,\n hash,\n trailingSlash,\n prefetch = true,\n prefetchDelay = 50,\n replace = false,\n scroll = true,\n viewTransition = false,\n locale,\n onClick,\n target,\n onMouseEnter,\n onMouseLeave,\n onFocus,\n onBlur,\n onTouchStart,\n ...props\n }: LinkProps<TRoute>,\n ref: React.ForwardedRef<HTMLAnchorElement>,\n) {\n const elementRef = useRef<HTMLAnchorElement | null>(null);\n const intentTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const hasPrefetched = useRef(false);\n\n const { intent, viewport, render } = normalizePrefetch(prefetch);\n const baseHref = resolveLinkHref(href, params, {\n query,\n hash,\n trailingSlash,\n });\n const resolvedHref = localizeActiveFarmHref(baseHref, locale);\n const isExternal = isExternalUrl(resolvedHref);\n\n const doPrefetch = useCallback(() => {\n if (isExternal || hasPrefetched.current) return;\n const router = getRouter();\n if (!router) return;\n hasPrefetched.current = true;\n router.prefetch(resolvedHref);\n }, [resolvedHref, isExternal]);\n\n useEffect(() => {\n hasPrefetched.current = false;\n }, [resolvedHref]);\n\n useEffect(() => {\n const element = elementRef.current;\n if (!element || isExternal) return;\n\n const router = getRouter();\n if (!router) return;\n\n if (viewport) {\n router.observeForPrefetch(element);\n return () => router.unobserveForPrefetch(element);\n }\n }, [resolvedHref, viewport, isExternal]);\n\n useEffect(() => {\n if (!render || isExternal) return;\n\n let cancelled = false;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const tryRenderPrefetch = () => {\n if (cancelled || hasPrefetched.current) return;\n\n const router = getRouter();\n if (!router) {\n timeoutId = setTimeout(tryRenderPrefetch, 30);\n return;\n }\n\n hasPrefetched.current = true;\n router.prefetch(resolvedHref);\n };\n\n tryRenderPrefetch();\n\n return () => {\n cancelled = true;\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n };\n }, [render, isExternal, resolvedHref]);\n\n useEffect(() => {\n return () => {\n if (intentTimeoutRef.current) {\n clearTimeout(intentTimeoutRef.current);\n intentTimeoutRef.current = null;\n }\n };\n }, []);\n\n const cancelIntent = useCallback(() => {\n if (intentTimeoutRef.current) {\n clearTimeout(intentTimeoutRef.current);\n intentTimeoutRef.current = null;\n }\n }, []);\n\n const scheduleIntentPrefetch = useCallback(() => {\n if (isExternal || !intent || hasPrefetched.current) return;\n cancelIntent();\n intentTimeoutRef.current = setTimeout(() => {\n intentTimeoutRef.current = null;\n doPrefetch();\n }, prefetchDelay);\n }, [intent, isExternal, prefetchDelay, doPrefetch, cancelIntent]);\n\n const handleMouseEnter = useCallback(\n (event: React.MouseEvent<HTMLAnchorElement>) => {\n onMouseEnter?.(event);\n scheduleIntentPrefetch();\n },\n [onMouseEnter, scheduleIntentPrefetch],\n );\n\n const handleMouseLeave = useCallback(\n (event: React.MouseEvent<HTMLAnchorElement>) => {\n onMouseLeave?.(event);\n cancelIntent();\n },\n [onMouseLeave, cancelIntent],\n );\n\n const handleTouchStart = useCallback(\n (event: React.TouchEvent<HTMLAnchorElement>) => {\n onTouchStart?.(event);\n scheduleIntentPrefetch();\n },\n [onTouchStart, scheduleIntentPrefetch],\n );\n\n const handleFocus = useCallback(\n (event: React.FocusEvent<HTMLAnchorElement>) => {\n onFocus?.(event);\n scheduleIntentPrefetch();\n },\n [onFocus, scheduleIntentPrefetch],\n );\n\n const handleBlur = useCallback(\n (event: React.FocusEvent<HTMLAnchorElement>) => {\n onBlur?.(event);\n cancelIntent();\n },\n [onBlur, cancelIntent],\n );\n\n const handleClick = useCallback(\n (event: React.MouseEvent<HTMLAnchorElement>) => {\n onClick?.(event);\n if (event.defaultPrevented) return;\n if (isExternal) return;\n if (target && target !== \"_self\") return;\n if (isModifierEvent(event)) return;\n if (event.button !== 0) return;\n\n if (typeof window !== \"undefined\") {\n event.preventDefault();\n if (isFarmLocaleChangeHref(resolvedHref)) {\n window.location.assign(resolvedHref);\n return;\n }\n const router = getRouter();\n if (router) {\n router.navigate(resolvedHref, { replace, scroll, viewTransition });\n } else {\n if (replace) window.location.replace(resolvedHref);\n else window.location.href = resolvedHref;\n }\n }\n },\n [resolvedHref, replace, scroll, viewTransition, target, isExternal, onClick],\n );\n\n const setRefs = useCallback(\n (node: HTMLAnchorElement | null) => {\n elementRef.current = node;\n if (typeof ref === \"function\") ref(node);\n else if (ref) (ref as React.MutableRefObject<HTMLAnchorElement | null>).current = node;\n },\n [ref],\n );\n\n return (\n <a\n ref={setRefs}\n href={resolvedHref}\n target={target}\n onClick={handleClick}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onFocus={handleFocus}\n onBlur={handleBlur}\n onTouchStart={handleTouchStart}\n {...props}\n data-farm-link=\"\"\n data-replace={replace ? \"\" : undefined}\n data-no-scroll={!scroll ? \"\" : undefined}\n data-view-transition={\n viewTransition === \"auto\" ? \"auto\" : viewTransition ? \"true\" : undefined\n }\n />\n );\n}\n\nconst LinkWithRef = forwardRef(LinkInner);\nLinkWithRef.displayName = \"Link\";\n\ntype LinkComponentType = <TRoute extends string = DefaultRouteHref>(\n props: LinkProps<TRoute> & { ref?: React.ForwardedRef<HTMLAnchorElement> },\n) => React.ReactElement;\n\nexport const Link = LinkWithRef as unknown as LinkComponentType;\n\nfunction resolveLinkHref(\n href: string,\n params: FarmRouterPathParams | undefined,\n options: FarmRouterBuildOptions,\n) {\n if (isExternalUrl(href)) return href;\n\n const { pathname, query, hash } = splitInternalHref(href);\n\n const resolvedHref = buildFarmRoutePath(pathname, params, {\n query: mergeQueryParams(query, options.query),\n hash: options.hash ?? hash,\n trailingSlash: options.trailingSlash,\n });\n\n return applyPreservedSearchParams(resolvedHref);\n}\n\nfunction splitInternalHref(href: string) {\n try {\n const url = new URL(href, \"http://farm.local\");\n return {\n pathname: url.pathname || \"/\",\n query: url.searchParams,\n hash: url.hash ? url.hash.slice(1) : undefined,\n };\n } catch {\n const [withoutHash, rawHash] = href.split(\"#\", 2);\n const [pathname, rawQuery] = withoutHash.split(\"?\", 2);\n return {\n pathname: pathname || \"/\",\n query: new URLSearchParams(rawQuery || \"\"),\n hash: rawHash,\n };\n }\n}\n\nfunction mergeQueryParams(\n current: URLSearchParams,\n next: FarmRouterBuildOptions[\"query\"],\n): URLSearchParams | undefined {\n const merged = new URLSearchParams(current);\n\n if (next instanceof URLSearchParams) {\n for (const [key, value] of next.entries()) {\n merged.append(key, value);\n }\n } else if (next) {\n for (const [key, value] of Object.entries(next)) {\n const values = Array.isArray(value) ? value : [value];\n for (const item of values) {\n if (item == null) continue;\n merged.append(key, String(item));\n }\n }\n }\n\n return merged.toString() ? merged : undefined;\n}\n\nfunction applyPreservedSearchParams(href: string): string {\n if (typeof window === \"undefined\") return href;\n\n const manifest = (window as any).__FARM_MANIFEST__;\n const routes =\n manifest?.routes && typeof manifest.routes === \"object\" ? Object.values(manifest.routes) : [];\n if (routes.length === 0) return href;\n\n const url = new URL(href, window.location.origin);\n const route = routes.find((candidate: any) => matchManifestRoute(url.pathname, candidate));\n const preserve = Array.isArray((route as any)?.search?.preserve)\n ? ((route as any).search.preserve as string[])\n : [];\n if (preserve.length === 0) return href;\n\n const current = new URLSearchParams(window.location.search);\n let changed = false;\n\n for (const key of preserve) {\n if (url.searchParams.has(key) || !current.has(key)) continue;\n for (const value of current.getAll(key)) {\n url.searchParams.append(key, value);\n changed = true;\n }\n }\n\n if (!changed) return href;\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\nfunction matchManifestRoute(pathname: string, route: any): boolean {\n if (!route || !Array.isArray(route.segments)) return false;\n const routeSegments = route.segments;\n const normalized = pathname === \"/\" ? \"\" : pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n const pathSegments = normalized ? normalized.split(\"/\") : [];\n const hasCatchAll = routeSegments.some((segment: any) => segment.isCatchAll);\n\n if (!hasCatchAll && pathSegments.length !== routeSegments.length) {\n return false;\n }\n\n for (let index = 0; index < routeSegments.length; index++) {\n const routeSegment = routeSegments[index];\n const pathSegment = pathSegments[index];\n\n if (routeSegment.isCatchAll) {\n return true;\n }\n\n if (pathSegment === undefined) {\n if (routeSegment.isOptional) continue;\n return false;\n }\n\n if (!routeSegment.isDynamic && routeSegment.segment !== pathSegment) {\n return false;\n }\n }\n\n return pathSegments.length === routeSegments.length || hasCatchAll;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAEA,SAAS,aAAa,SAAS,QAAQ,gBAAgB;AA0FhD,SAAS,YACd,QACA,UAII,CAAC,GACuB;AAK5B,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,aAAa,OAAO,OAAO;AACjC,QAAM,YAAY,OAAO,MAAM;AAC/B,QAAM,eAAe,OAAO,CAAC;AAC7B,QAAM,eAAyD;AAAA,IAC7D,cAAc;AAAA,IACd,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,OAAO;AAAA,IACP,WAAW;AAAA,EACb;AACA,QAAM,WAAW,OAAO,YAAY;AACpC,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAmD,YAAY;AAEzF,aAAW,UAAU;AACrB,YAAU,UAAU;AAEpB,QAAM,mBAAmB;AAAA,IACvB,CACE,UAKG;AACH,eAAS,CAAC,YAAY;AACpB,cAAM,OAAO,OAAO,UAAU,aAAa,MAAM,OAAO,IAAI;AAC5D,iBAAS,UAAU;AACnB,eAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,IACA,CAAC;AAAA,EACH;AAEA,QAAM,cAAc;AAAA,IAClB,OAA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;AAEA,QAAI,gBAAgB,QAAW;AAC7B,UAAI,aAAa,WAAY;AAC7B,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,aAAa,aAAa,aAAa,YAAY,aAAa;AACnE,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,aAAa,WAAW,cAAc,UAAU;AACzD;AA9BS;","names":["useCallback","useMemo","useRef","useState","useRef","useState","useCallback","useMemo","replaceState","useRef","useCallback","prefetch","useRef","useCallback"]}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
2
|
_parseServerFnSchema,
|
|
3
3
|
createServerFn
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-VPCFICID.mjs";
|
|
5
5
|
import {
|
|
6
6
|
createFarmServerQueryResult
|
|
7
7
|
} from "./chunk-SCFX4UTD.mjs";
|
|
8
8
|
import {
|
|
9
9
|
getServerActionExecutionContext
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-ZVMV3THA.mjs";
|
|
11
11
|
import {
|
|
12
12
|
createFarmCacheKey,
|
|
13
13
|
createRouteDataCacheKey,
|
|
@@ -139,4 +139,4 @@ export {
|
|
|
139
139
|
FARM_SERVER_QUERY_SYMBOL,
|
|
140
140
|
createServerQuery
|
|
141
141
|
};
|
|
142
|
-
//# sourceMappingURL=chunk-
|
|
142
|
+
//# sourceMappingURL=chunk-UMVLB3PN.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server-query.ts"],"sourcesContent":["import {\n createFarmCacheKey,\n createRouteDataCacheKey,\n createRouteDataCacheTag,\n getFarmDataCache,\n type RouteDataCacheKey,\n} from \"./cache\";\nimport { getServerActionExecutionContext } from \"./server-action-security\";\nimport {\n createServerFn,\n type AnyServerFnMiddleware,\n type InferServerFnSchemaInput,\n type InferServerFnSchemaOutput,\n type ServerFn,\n type ServerFnContext,\n type ServerFnHandler,\n type ServerFnHandlerContext,\n type ServerFnMiddlewareContext,\n type ServerFnSchema,\n _parseServerFnSchema,\n} from \"./server-fn\";\nimport { createFarmServerQueryResult, type FarmServerQueryResult } from \"./server-query-protocol\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type ServerQueryStaleTime = number | false | `${number}${\"ms\" | \"s\" | \"m\" | \"h\"}`;\n\nexport type ServerQueryKey<TInput, TContext extends object = {}> = (\n context: ServerFnContext<TInput, TContext>,\n) => MaybePromise<RouteDataCacheKey>;\n\nexport type ServerQueryOptions<\n TSchema extends ServerFnSchema | undefined,\n TResult,\n TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n> = {\n input?: TSchema;\n output?: undefined;\n middleware?: TMiddlewares;\n key: ServerQueryKey<\n TSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TSchema> : unknown,\n ServerFnMiddlewareContext<TMiddlewares>\n >;\n /** Milliseconds, a duration string such as \"30s\", or false for no expiry. */\n staleTime?: ServerQueryStaleTime;\n handler: ServerFnHandler<\n TSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TSchema> : unknown,\n TResult,\n ServerFnMiddlewareContext<TMiddlewares>\n >;\n};\n\nexport type ServerQueryOutputOptions<\n TInputSchema extends ServerFnSchema | undefined,\n TOutputSchema extends ServerFnSchema,\n TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n> = {\n input?: TInputSchema;\n output: TOutputSchema;\n middleware?: TMiddlewares;\n key: ServerQueryKey<\n TInputSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TInputSchema> : unknown,\n ServerFnMiddlewareContext<TMiddlewares>\n >;\n /** Milliseconds, a duration string such as \"30s\", or false for no expiry. */\n staleTime?: ServerQueryStaleTime;\n handler: ServerFnHandler<\n TInputSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TInputSchema> : unknown,\n unknown,\n ServerFnMiddlewareContext<TMiddlewares>\n >;\n};\n\nexport type ServerQuery<TInput, TResult> = ([unknown] extends [TInput]\n ? (input?: TInput) => Promise<TResult>\n : (input: TInput) => Promise<TResult>) & {\n readonly __farmServerQuery: true;\n readonly __farmServerQueryInput?: unknown;\n readonly __farmServerQueryOutput?: unknown;\n};\n\nexport const FARM_SERVER_QUERY_SYMBOL = Symbol.for(\"farm.server-query\");\n\ntype AnyServerQueryOptions = {\n input?: ServerFnSchema;\n output?: ServerFnSchema;\n middleware?: readonly AnyServerFnMiddleware[];\n key: ServerQueryKey<any, any>;\n staleTime?: ServerQueryStaleTime;\n handler: ServerFnHandler<any, any, any>;\n};\n\nconst requestInflight = new WeakMap<Request, Map<string, Promise<unknown>>>();\nconst detachedInflight = new Map<string, Promise<unknown>>();\n\nexport function createServerQuery<\n TInputSchema extends ServerFnSchema,\n TOutputSchema extends ServerFnSchema,\n const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n>(\n options: ServerQueryOutputOptions<TInputSchema, TOutputSchema, TMiddlewares>,\n): ServerQuery<\n InferServerFnSchemaInput<TInputSchema>,\n Awaited<InferServerFnSchemaOutput<TOutputSchema>>\n>;\nexport function createServerQuery<\n TOutputSchema extends ServerFnSchema,\n const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n>(\n options: ServerQueryOutputOptions<undefined, TOutputSchema, TMiddlewares>,\n): ServerQuery<unknown, Awaited<InferServerFnSchemaOutput<TOutputSchema>>>;\nexport function createServerQuery<\n TSchema extends ServerFnSchema,\n TResult,\n const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n>(\n options: ServerQueryOptions<TSchema, TResult, TMiddlewares>,\n): ServerQuery<InferServerFnSchemaInput<TSchema>, Awaited<TResult>>;\nexport function createServerQuery<\n TResult,\n const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n>(\n options: ServerQueryOptions<undefined, TResult, TMiddlewares>,\n): ServerQuery<unknown, Awaited<TResult>>;\nexport function createServerQuery(options: AnyServerQueryOptions): ServerQuery<unknown, unknown> {\n if (!options || typeof options.handler !== \"function\") {\n throw new TypeError(\"createServerQuery requires a handler function\");\n }\n if (typeof options.key !== \"function\") {\n throw new TypeError(\"createServerQuery requires a key function\");\n }\n\n const staleTime = normalizeServerQueryStaleTime(options.staleTime);\n const execute = (\n createServerFn as (options: any) => ServerFn<unknown, FarmServerQueryResult<any>>\n )({\n input: options.input,\n middleware: options.middleware,\n handler: async (context: ServerFnHandlerContext<any, any>) => {\n const routeKey = await options.key(context);\n assertServerQueryKey(routeKey);\n\n const clientKey = createRouteDataCacheKey(routeKey);\n const cacheKey = createFarmCacheKey([\"route-data\", routeKey]);\n const producer = async () => {\n const value = await options.handler(context);\n return _parseServerFnSchema(options.output, value, \"output\", \"createServerQuery\");\n };\n\n let data: unknown;\n let updatedAt: number;\n\n if (staleTime === 0) {\n data = await dedupeServerQueryRequest(cacheKey, context.request, producer);\n updatedAt = Date.now();\n } else {\n const cache = getFarmDataCache();\n data = await cache.getOrSet(cacheKey, producer, {\n tags: [createRouteDataCacheTag(routeKey)],\n revalidate: staleTime === false ? false : Math.max(1, Math.ceil(staleTime / 1000)),\n });\n updatedAt =\n (await cache.getEntryAsync(cacheKey, { allowStale: true }))?.createdAt ?? Date.now();\n }\n\n return createFarmServerQueryResult(data, {\n key: clientKey,\n staleTime,\n updatedAt,\n });\n },\n });\n\n const query = async (input?: unknown) => {\n const result = await execute(input);\n return getServerActionExecutionContext() ? result : result.data;\n };\n\n Object.defineProperties(query, {\n [FARM_SERVER_QUERY_SYMBOL]: {\n value: true,\n enumerable: false,\n },\n __farmServerQuery: {\n value: true,\n enumerable: false,\n },\n __farmServerQueryInput: {\n value: options.input,\n enumerable: false,\n },\n __farmServerQueryOutput: {\n value: options.output,\n enumerable: false,\n },\n });\n\n return query as ServerQuery<unknown, unknown>;\n}\n\nasync function dedupeServerQueryRequest<TData>(\n key: string,\n request: Request | undefined,\n producer: () => Promise<TData>,\n): Promise<TData> {\n let inflight: Map<string, Promise<unknown>>;\n if (request) {\n inflight = requestInflight.get(request) ?? new Map();\n requestInflight.set(request, inflight);\n } else {\n inflight = detachedInflight;\n }\n\n const existing = inflight.get(key) as Promise<TData> | undefined;\n if (existing) return existing;\n\n const promise = Promise.resolve().then(producer);\n inflight.set(key, promise);\n\n try {\n return await promise;\n } finally {\n inflight.delete(key);\n }\n}\n\nfunction normalizeServerQueryStaleTime(value: ServerQueryStaleTime | undefined): number | false {\n if (value === false) return false;\n if (value === undefined) return 0;\n\n if (typeof value === \"number\") {\n if (!Number.isFinite(value) || value < 0) {\n throw new TypeError(\"createServerQuery staleTime must be a non-negative duration\");\n }\n return value;\n }\n\n const match = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)$/);\n if (!match) {\n throw new TypeError('createServerQuery staleTime must look like \"250ms\", \"30s\", \"5m\", or \"1h\"');\n }\n\n const amount = Number(match[1]);\n const unit = match[2];\n const multiplier = unit === \"ms\" ? 1 : unit === \"s\" ? 1000 : unit === \"m\" ? 60_000 : 3_600_000;\n return amount * multiplier;\n}\n\nfunction assertServerQueryKey(key: unknown): asserts key is RouteDataCacheKey {\n if (typeof key === \"string\") {\n if (key.trim().length > 0) return;\n } else if (Array.isArray(key)) {\n return;\n }\n\n throw new TypeError(\"createServerQuery key must return a non-empty string or an array\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiFO,IAAM,2BAA2B,uBAAO,IAAI,mBAAmB;AAWtE,IAAM,kBAAkB,oBAAI,QAAgD;AAC5E,IAAM,mBAAmB,oBAAI,IAA8B;AA+BpD,SAAS,kBAAkB,SAA+D;AAC/F,MAAI,CAAC,WAAW,OAAO,QAAQ,YAAY,YAAY;AACrD,UAAM,IAAI,UAAU,+CAA+C;AAAA,EACrE;AACA,MAAI,OAAO,QAAQ,QAAQ,YAAY;AACrC,UAAM,IAAI,UAAU,2CAA2C;AAAA,EACjE;AAEA,QAAM,YAAY,8BAA8B,QAAQ,SAAS;AACjE,QAAM,UACJ,eACA;AAAA,IACA,OAAO,QAAQ;AAAA,IACf,YAAY,QAAQ;AAAA,IACpB,SAAS,8BAAO,YAA8C;AAC5D,YAAM,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AAC7B;AAAA,EACF;AAEA,QAAM,IAAI,UAAU,kEAAkE;AACxF;AARS;","names":[]}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
|
+
ServerFnFailure,
|
|
2
3
|
getServerActionExecutionContext,
|
|
3
4
|
getServerActionSignal
|
|
4
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-ZVMV3THA.mjs";
|
|
5
6
|
import {
|
|
6
7
|
_resolveCurrentRequest
|
|
7
8
|
} from "./chunk-LM2YNO4U.mjs";
|
|
@@ -35,6 +36,8 @@ function createServerFn(options) {
|
|
|
35
36
|
throw new TypeError("createServerFn requires a handler function");
|
|
36
37
|
}
|
|
37
38
|
const middleware = resolveServerFnMiddleware(options.middleware);
|
|
39
|
+
const errors = normalizeServerFnErrors(options.errors);
|
|
40
|
+
const error = createServerFnErrorHandler(errors);
|
|
38
41
|
const serverFn = /* @__PURE__ */ __name(async (value) => {
|
|
39
42
|
const formData = isFormData(value) ? value : void 0;
|
|
40
43
|
const rawInput = formData ? formDataToObject(formData) : value;
|
|
@@ -52,7 +55,7 @@ function createServerFn(options) {
|
|
|
52
55
|
let resolvedContext = Object.freeze(/* @__PURE__ */ Object.create(null));
|
|
53
56
|
const result = await runServerFnMiddleware(middleware, handlerContext, async (context) => {
|
|
54
57
|
resolvedContext = context.context;
|
|
55
|
-
return options.handler(context);
|
|
58
|
+
return options.handler({ ...context, error });
|
|
56
59
|
});
|
|
57
60
|
const parsedResult = await _parseServerFnSchema(options.output, result, "output");
|
|
58
61
|
if (options.invalidates) {
|
|
@@ -82,6 +85,10 @@ function createServerFn(options) {
|
|
|
82
85
|
value: options.output,
|
|
83
86
|
enumerable: false
|
|
84
87
|
},
|
|
88
|
+
__farmServerFnError: {
|
|
89
|
+
value: void 0,
|
|
90
|
+
enumerable: false
|
|
91
|
+
},
|
|
85
92
|
__farmServerFnMiddleware: {
|
|
86
93
|
value: middleware,
|
|
87
94
|
enumerable: false
|
|
@@ -120,6 +127,78 @@ async function runServerFnMiddleware(middleware, handlerContext, handler) {
|
|
|
120
127
|
return dispatch(0, Object.freeze(/* @__PURE__ */ Object.create(null)));
|
|
121
128
|
}
|
|
122
129
|
__name(runServerFnMiddleware, "runServerFnMiddleware");
|
|
130
|
+
function normalizeServerFnErrors(definitions) {
|
|
131
|
+
if (definitions === void 0) return Object.freeze({});
|
|
132
|
+
if (!isPlainServerFnObject(definitions)) {
|
|
133
|
+
throw new TypeError("createServerFn errors must be an object");
|
|
134
|
+
}
|
|
135
|
+
const normalized = /* @__PURE__ */ Object.create(null);
|
|
136
|
+
for (const [code, definition] of Object.entries(definitions)) {
|
|
137
|
+
if (!code.trim()) {
|
|
138
|
+
throw new TypeError("Server function error codes cannot be empty");
|
|
139
|
+
}
|
|
140
|
+
if (!definition || typeof definition !== "object") {
|
|
141
|
+
throw new TypeError(`Server function error "${code}" must be an object`);
|
|
142
|
+
}
|
|
143
|
+
if (!Number.isInteger(definition.status) || definition.status < 400 || definition.status > 599) {
|
|
144
|
+
throw new TypeError(
|
|
145
|
+
`Server function error "${code}" status must be an integer between 400 and 599`
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
if (!definition.data || typeof definition.data.parse !== "function" && typeof definition.data.safeParse !== "function") {
|
|
149
|
+
throw new TypeError(
|
|
150
|
+
`Server function error "${code}" data must provide synchronous parse() or safeParse()`
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
if (definition.message !== void 0 && typeof definition.message !== "string") {
|
|
154
|
+
throw new TypeError(`Server function error "${code}" message must be a string`);
|
|
155
|
+
}
|
|
156
|
+
normalized[code] = Object.freeze({ ...definition });
|
|
157
|
+
}
|
|
158
|
+
return Object.freeze(normalized);
|
|
159
|
+
}
|
|
160
|
+
__name(normalizeServerFnErrors, "normalizeServerFnErrors");
|
|
161
|
+
function createServerFnErrorHandler(definitions) {
|
|
162
|
+
return ((code, data) => {
|
|
163
|
+
const definition = definitions[code];
|
|
164
|
+
if (!definition) {
|
|
165
|
+
throw new TypeError(`Server function error "${code}" is not declared`);
|
|
166
|
+
}
|
|
167
|
+
const parsed = parseServerFnFailureData(code, definition.data, data);
|
|
168
|
+
throw new ServerFnFailure(code, parsed, {
|
|
169
|
+
status: definition.status,
|
|
170
|
+
message: definition.message ?? "Server function failed"
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
__name(createServerFnErrorHandler, "createServerFnErrorHandler");
|
|
175
|
+
function parseServerFnFailureData(code, schema, value) {
|
|
176
|
+
if (typeof schema.safeParse === "function") {
|
|
177
|
+
const result2 = schema.safeParse(value);
|
|
178
|
+
if (isPromiseLike(result2)) {
|
|
179
|
+
throw new TypeError(`Server function error "${code}" data schema must parse synchronously`);
|
|
180
|
+
}
|
|
181
|
+
return unwrapSafeParseResult(result2);
|
|
182
|
+
}
|
|
183
|
+
const result = schema.parse(value);
|
|
184
|
+
if (isPromiseLike(result)) {
|
|
185
|
+
throw new TypeError(`Server function error "${code}" data schema must parse synchronously`);
|
|
186
|
+
}
|
|
187
|
+
return result;
|
|
188
|
+
}
|
|
189
|
+
__name(parseServerFnFailureData, "parseServerFnFailureData");
|
|
190
|
+
function isPlainServerFnObject(value) {
|
|
191
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
192
|
+
const prototype = Object.getPrototypeOf(value);
|
|
193
|
+
return prototype === Object.prototype || prototype === null;
|
|
194
|
+
}
|
|
195
|
+
__name(isPlainServerFnObject, "isPlainServerFnObject");
|
|
196
|
+
function isPromiseLike(value) {
|
|
197
|
+
return Boolean(
|
|
198
|
+
value && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function"
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
__name(isPromiseLike, "isPromiseLike");
|
|
123
202
|
function resolveServerFnMiddleware(middleware) {
|
|
124
203
|
const resolved = [];
|
|
125
204
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -221,4 +300,4 @@ export {
|
|
|
221
300
|
createServerFn,
|
|
222
301
|
_parseServerFnSchema
|
|
223
302
|
};
|
|
224
|
-
//# sourceMappingURL=chunk-
|
|
303
|
+
//# sourceMappingURL=chunk-VPCFICID.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server-fn.ts"],"sourcesContent":["import { getServerActionExecutionContext, getServerActionSignal } from \"./server-action-security\";\nimport { _resolveCurrentRequest } from \"./server/request-bridge\";\nimport { applyFarmCacheInvalidationTargets, type FarmCacheInvalidationTarget } from \"./cache\";\nimport { ServerActionError, ServerFnFailure } from \"./server-fn-error\";\n\nexport {\n FARM_SERVER_FN_FAILURE_SYMBOL,\n ServerActionError,\n ServerFnFailure,\n createServerFnTransportError,\n isServerFnFailure,\n} from \"./server-fn-error\";\nexport type { SerializedServerFnFailure } from \"./server-fn-error\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n// Generic schema type that works with Zod v3/v4 and similar validator APIs.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ServerFnSchema = {\n _input?: any;\n _output?: any;\n parse?: (data: unknown) => any;\n parseAsync?: (data: unknown) => Promise<any>;\n safeParse?: (data: unknown) => any;\n safeParseAsync?: (data: unknown) => Promise<any>;\n};\n\nexport type InferServerFnSchemaInput<T> = T extends { _input: infer I } ? I : unknown;\nexport type InferServerFnSchemaOutput<T> = T extends { _output: infer O }\n ? O\n : T extends { parse: (data: unknown) => infer R }\n ? R\n : unknown;\n\nexport type ServerFnErrorSchema = ServerFnSchema &\n ({ parse: (data: unknown) => unknown } | { safeParse: (data: unknown) => unknown });\n\nexport type ServerFnErrorDefinition<\n TSchema extends ServerFnErrorSchema = ServerFnErrorSchema,\n TStatus extends number = number,\n> = {\n status: TStatus;\n /** Schema for the public error payload exposed to callers. */\n data: TSchema;\n /** Public message safe to expose to callers. */\n message?: string;\n};\n\nexport type ServerFnErrorDefinitions = Record<\n string,\n ServerFnErrorDefinition<ServerFnErrorSchema, number>\n>;\n\nexport type ServerFnDeclaredError<TErrors extends ServerFnErrorDefinitions> = {\n [TCode in keyof TErrors]: ServerFnFailure<\n TCode & string,\n InferServerFnSchemaOutput<TErrors[TCode][\"data\"]>,\n TErrors[TCode][\"status\"]\n >;\n}[keyof TErrors];\n\nexport type ServerFnError<TErrors extends ServerFnErrorDefinitions> = keyof TErrors extends never\n ? Error\n : ServerActionError | ServerFnDeclaredError<TErrors>;\n\nexport type ServerFnErrorHandler<TErrors extends ServerFnErrorDefinitions> = <\n TCode extends keyof TErrors & string,\n>(\n code: TCode,\n data: InferServerFnSchemaInput<TErrors[TCode][\"data\"]>,\n) => never;\n\nexport type ServerFnFormInput = FormData;\n\ntype Simplify<T> = { [TKey in keyof T]: T[TKey] } & {};\ntype AssignContext<TCurrent extends object, TNext extends object> = Simplify<\n Omit<TCurrent, keyof TNext> & TNext\n>;\ntype MiddlewareContext<TMiddleware> =\n TMiddleware extends ServerFnMiddleware<infer TContext> ? TContext : {};\n\nexport type ServerFnMiddlewareContext<\n TMiddlewares extends readonly AnyServerFnMiddleware[],\n TContext extends object = {},\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n ? TMiddleware extends AnyServerFnMiddleware\n ? TRest extends readonly AnyServerFnMiddleware[]\n ? ServerFnMiddlewareContext<TRest, AssignContext<TContext, MiddlewareContext<TMiddleware>>>\n : TContext\n : TContext\n : number extends TMiddlewares[\"length\"]\n ? Simplify<TContext & MiddlewareContext<TMiddlewares[number]>>\n : Simplify<TContext>;\n\ndeclare const SERVER_FN_MIDDLEWARE_CONTEXT: unique symbol;\n\nexport type ServerFnMiddlewareContinuation<TContext extends object = {}> = {\n readonly [SERVER_FN_MIDDLEWARE_CONTEXT]: TContext;\n};\n\nexport type ServerFnMiddlewareNext = <TContext extends object = {}>(options?: {\n context?: TContext;\n}) => Promise<ServerFnMiddlewareContinuation<TContext>>;\n\nexport type ServerFnContext<TInput, TContext extends object = {}> = {\n input: TInput;\n rawInput: unknown;\n formData?: FormData;\n /** The action request when invoked across the network. Undefined for direct server calls. */\n request?: Request;\n /** Aborts when the underlying action request is cancelled. */\n signal: AbortSignal;\n /** Context produced by this server function's middleware chain. */\n context: Readonly<TContext>;\n};\n\nexport type ServerFnHandlerContext<\n TInput,\n TContext extends object = {},\n TErrors extends ServerFnErrorDefinitions = {},\n> = ServerFnContext<TInput, TContext> & {\n /** Return a declared, validated error from this server function. */\n error: ServerFnErrorHandler<TErrors>;\n};\n\nexport type ServerFnHandler<\n TInput,\n TResult,\n TContext extends object = {},\n TErrors extends ServerFnErrorDefinitions = {},\n> = (ctx: ServerFnHandlerContext<TInput, TContext, TErrors>) => MaybePromise<TResult>;\n\nexport type ServerFnInvalidationContext<\n TInput,\n TResult,\n TContext extends object = {},\n> = ServerFnContext<TInput, TContext> & {\n /** Parsed value returned by the successful server function. */\n result: TResult;\n};\n\nexport type ServerFnInvalidations<TInput, TResult, TContext extends object = {}> =\n | readonly FarmCacheInvalidationTarget[]\n | ((\n context: ServerFnInvalidationContext<TInput, TResult, TContext>,\n ) => readonly FarmCacheInvalidationTarget[] | Promise<readonly FarmCacheInvalidationTarget[]>);\n\nexport type ServerFnMiddlewareHandlerContext<TContext extends object = {}> = ServerFnContext<\n unknown,\n TContext\n> & {\n next: ServerFnMiddlewareNext;\n};\n\nexport type ServerFnMiddlewareHandler<\n TContext extends object = {},\n TProvidedContext extends object = {},\n> = (\n ctx: ServerFnMiddlewareHandlerContext<TContext>,\n) => MaybePromise<ServerFnMiddlewareContinuation<TProvidedContext>>;\n\nexport type ServerFnMiddleware<TContext extends object = {}> = {\n readonly __farmServerFnMiddleware: true;\n readonly __farmServerFnMiddlewareContext?: TContext;\n readonly middleware: readonly AnyServerFnMiddleware[];\n readonly handler: ServerFnMiddlewareHandler<any, any>;\n};\n\nexport type AnyServerFnMiddleware = ServerFnMiddleware<any>;\n\nexport type ServerFnMiddlewareOptions<\n TMiddlewares extends readonly AnyServerFnMiddleware[],\n TProvidedContext extends object,\n> = {\n middleware?: TMiddlewares;\n handler: ServerFnMiddlewareHandler<ServerFnMiddlewareContext<TMiddlewares>, TProvidedContext>;\n};\n\nexport type ServerFnOptions<\n TSchema extends ServerFnSchema | undefined,\n TResult,\n TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n TErrors extends ServerFnErrorDefinitions = {},\n> = {\n input?: TSchema;\n output?: undefined;\n middleware?: TMiddlewares;\n errors?: TErrors;\n invalidates?: ServerFnInvalidations<\n TSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TSchema> : unknown,\n Awaited<TResult>,\n ServerFnMiddlewareContext<TMiddlewares>\n >;\n handler: ServerFnHandler<\n TSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TSchema> : unknown,\n TResult,\n ServerFnMiddlewareContext<TMiddlewares>,\n TErrors\n >;\n};\n\nexport type ServerFnOutputOptions<\n TInputSchema extends ServerFnSchema | undefined,\n TOutputSchema extends ServerFnSchema,\n TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n TErrors extends ServerFnErrorDefinitions = {},\n> = {\n input?: TInputSchema;\n output: TOutputSchema;\n middleware?: TMiddlewares;\n errors?: TErrors;\n invalidates?: ServerFnInvalidations<\n TInputSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TInputSchema> : unknown,\n Awaited<InferServerFnSchemaOutput<TOutputSchema>>,\n ServerFnMiddlewareContext<TMiddlewares>\n >;\n handler: ServerFnHandler<\n TInputSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TInputSchema> : unknown,\n unknown,\n ServerFnMiddlewareContext<TMiddlewares>,\n TErrors\n >;\n};\n\nexport type ServerFn<TInput, TResult, TError extends Error = Error> = ([unknown] extends [TInput]\n ? (input?: TInput | FormData) => Promise<TResult>\n : (input: TInput | FormData) => Promise<TResult>) & {\n readonly __farmServerFn: true;\n readonly __farmServerFnInput?: unknown;\n readonly __farmServerFnOutput?: unknown;\n readonly __farmServerFnError: TError;\n};\n\nexport type InferServerFnError<TServerFn> =\n TServerFn extends ServerFn<any, any, infer TError> ? TError : Error;\n\nexport const FARM_SERVER_FN_SYMBOL = Symbol.for(\"farm.server-fn\");\n\nconst UNSAFE_FORM_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport function createServerMiddleware<\n const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n TProvidedContext extends object = {},\n>(\n options: ServerFnMiddlewareOptions<TMiddlewares, TProvidedContext>,\n): ServerFnMiddleware<AssignContext<ServerFnMiddlewareContext<TMiddlewares>, TProvidedContext>>;\nexport function createServerMiddleware(options: {\n middleware?: readonly AnyServerFnMiddleware[];\n handler: ServerFnMiddlewareHandler<any, any>;\n}): ServerFnMiddleware<any> {\n if (!options || typeof options.handler !== \"function\") {\n throw new TypeError(\"createServerMiddleware requires a handler function\");\n }\n\n const middleware = Object.freeze([...(options.middleware ?? [])]);\n for (const entry of middleware) {\n assertServerFnMiddleware(entry);\n }\n\n return Object.freeze({\n __farmServerFnMiddleware: true as const,\n middleware,\n handler: options.handler,\n });\n}\n\nexport function createServerFn<\n TInputSchema extends ServerFnSchema,\n TOutputSchema extends ServerFnSchema,\n const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n const TErrors extends ServerFnErrorDefinitions = {},\n>(\n options: ServerFnOutputOptions<TInputSchema, TOutputSchema, TMiddlewares, TErrors>,\n): ServerFn<\n InferServerFnSchemaInput<TInputSchema>,\n Awaited<InferServerFnSchemaOutput<TOutputSchema>>,\n ServerFnError<TErrors>\n>;\nexport function createServerFn<\n TOutputSchema extends ServerFnSchema,\n const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n const TErrors extends ServerFnErrorDefinitions = {},\n>(\n options: ServerFnOutputOptions<undefined, TOutputSchema, TMiddlewares, TErrors>,\n): ServerFn<unknown, Awaited<InferServerFnSchemaOutput<TOutputSchema>>, ServerFnError<TErrors>>;\nexport function createServerFn<\n TSchema extends ServerFnSchema,\n TResult,\n const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n const TErrors extends ServerFnErrorDefinitions = {},\n>(\n options: ServerFnOptions<TSchema, TResult, TMiddlewares, TErrors>,\n): ServerFn<InferServerFnSchemaInput<TSchema>, Awaited<TResult>, ServerFnError<TErrors>>;\nexport function createServerFn<\n TResult,\n const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n const TErrors extends ServerFnErrorDefinitions = {},\n>(\n options: ServerFnOptions<undefined, TResult, TMiddlewares, TErrors>,\n): ServerFn<unknown, Awaited<TResult>, ServerFnError<TErrors>>;\nexport function createServerFn(options: {\n input?: ServerFnSchema;\n output?: ServerFnSchema;\n middleware?: readonly AnyServerFnMiddleware[];\n errors?: ServerFnErrorDefinitions;\n invalidates?: ServerFnInvalidations<any, any, any>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: ServerFnHandler<any, any, any, any>;\n}) {\n if (!options || typeof options.handler !== \"function\") {\n throw new TypeError(\"createServerFn requires a handler function\");\n }\n\n const middleware = resolveServerFnMiddleware(options.middleware);\n const errors = normalizeServerFnErrors(options.errors);\n const error = createServerFnErrorHandler(errors);\n const serverFn = async (value: unknown) => {\n const formData = isFormData(value) ? value : undefined;\n const rawInput = formData ? formDataToObject(formData) : value;\n const input = await _parseServerFnSchema(options.input, rawInput, \"input\");\n const executionContext = getServerActionExecutionContext();\n const request = executionContext?.request ?? _resolveCurrentRequest();\n const signal = executionContext?.signal ?? request?.signal ?? getServerActionSignal();\n const handlerContext = {\n input,\n rawInput,\n formData,\n request,\n signal,\n };\n let resolvedContext: Readonly<object> = Object.freeze(Object.create(null));\n const result = await runServerFnMiddleware(middleware, handlerContext, async (context) => {\n resolvedContext = context.context;\n return options.handler({ ...context, error });\n });\n const parsedResult = await _parseServerFnSchema(options.output, result, \"output\");\n\n if (options.invalidates) {\n const declaration =\n typeof options.invalidates === \"function\"\n ? await options.invalidates({\n ...handlerContext,\n context: resolvedContext,\n result: parsedResult,\n })\n : options.invalidates;\n await applyFarmCacheInvalidationTargets(declaration);\n }\n\n return parsedResult;\n };\n\n Object.defineProperties(serverFn, {\n [FARM_SERVER_FN_SYMBOL]: {\n value: true,\n enumerable: false,\n },\n __farmServerFn: {\n value: true,\n enumerable: false,\n },\n __farmServerFnInput: {\n value: options.input,\n enumerable: false,\n },\n __farmServerFnOutput: {\n value: options.output,\n enumerable: false,\n },\n __farmServerFnError: {\n value: undefined,\n enumerable: false,\n },\n __farmServerFnMiddleware: {\n value: middleware,\n enumerable: false,\n },\n __farmServerFnInvalidates: {\n value: options.invalidates,\n enumerable: false,\n },\n });\n\n return serverFn as ServerFn<unknown, unknown, Error>;\n}\n\ntype ServerFnBaseContext = Omit<ServerFnContext<unknown, {}>, \"context\">;\n\nasync function runServerFnMiddleware(\n middleware: readonly AnyServerFnMiddleware[],\n handlerContext: ServerFnBaseContext,\n handler: (context: ServerFnContext<any, any>) => MaybePromise<unknown>,\n) {\n const dispatch = async (index: number, context: Readonly<object>): Promise<unknown> => {\n const current = middleware[index];\n if (!current) {\n return handler({ ...handlerContext, context });\n }\n\n let nextCalled = false;\n const result = await current.handler({\n ...handlerContext,\n context,\n next: async (nextOptions) => {\n if (nextCalled) {\n throw new Error(\"Server function middleware next() can only be called once\");\n }\n nextCalled = true;\n\n return dispatch(index + 1, mergeServerFnContext(context, nextOptions?.context)) as Promise<\n ServerFnMiddlewareContinuation<any>\n >;\n },\n });\n\n if (!nextCalled) {\n throw new Error(\"Server function middleware must call next()\");\n }\n\n return result;\n };\n\n return dispatch(0, Object.freeze(Object.create(null)));\n}\n\nfunction normalizeServerFnErrors(\n definitions: ServerFnErrorDefinitions | undefined,\n): Readonly<ServerFnErrorDefinitions> {\n if (definitions === undefined) return Object.freeze({});\n if (!isPlainServerFnObject(definitions)) {\n throw new TypeError(\"createServerFn errors must be an object\");\n }\n\n const normalized: ServerFnErrorDefinitions = Object.create(null);\n for (const [code, definition] of Object.entries(definitions)) {\n if (!code.trim()) {\n throw new TypeError(\"Server function error codes cannot be empty\");\n }\n if (!definition || typeof definition !== \"object\") {\n throw new TypeError(`Server function error \"${code}\" must be an object`);\n }\n if (\n !Number.isInteger(definition.status) ||\n definition.status < 400 ||\n definition.status > 599\n ) {\n throw new TypeError(\n `Server function error \"${code}\" status must be an integer between 400 and 599`,\n );\n }\n if (\n !definition.data ||\n (typeof definition.data.parse !== \"function\" &&\n typeof definition.data.safeParse !== \"function\")\n ) {\n throw new TypeError(\n `Server function error \"${code}\" data must provide synchronous parse() or safeParse()`,\n );\n }\n if (definition.message !== undefined && typeof definition.message !== \"string\") {\n throw new TypeError(`Server function error \"${code}\" message must be a string`);\n }\n\n normalized[code] = Object.freeze({ ...definition });\n }\n\n return Object.freeze(normalized);\n}\n\nfunction createServerFnErrorHandler(\n definitions: Readonly<ServerFnErrorDefinitions>,\n): ServerFnErrorHandler<ServerFnErrorDefinitions> {\n return ((code: string, data: unknown): never => {\n const definition = definitions[code];\n if (!definition) {\n throw new TypeError(`Server function error \"${code}\" is not declared`);\n }\n\n const parsed = parseServerFnFailureData(code, definition.data, data);\n throw new ServerFnFailure(code, parsed, {\n status: definition.status,\n message: definition.message ?? \"Server function failed\",\n });\n }) as ServerFnErrorHandler<ServerFnErrorDefinitions>;\n}\n\nfunction parseServerFnFailureData(code: string, schema: ServerFnSchema, value: unknown) {\n if (typeof schema.safeParse === \"function\") {\n const result = schema.safeParse(value);\n if (isPromiseLike(result)) {\n throw new TypeError(`Server function error \"${code}\" data schema must parse synchronously`);\n }\n return unwrapSafeParseResult(result);\n }\n\n const result = schema.parse!(value);\n if (isPromiseLike(result)) {\n throw new TypeError(`Server function error \"${code}\" data schema must parse synchronously`);\n }\n return result;\n}\n\nfunction isPlainServerFnObject(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return Boolean(\n value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n \"then\" in value &&\n typeof (value as PromiseLike<unknown>).then === \"function\",\n );\n}\n\nfunction resolveServerFnMiddleware(\n middleware: readonly AnyServerFnMiddleware[] | undefined,\n): readonly AnyServerFnMiddleware[] {\n const resolved: AnyServerFnMiddleware[] = [];\n const seen = new Set<AnyServerFnMiddleware>();\n const visiting = new Set<AnyServerFnMiddleware>();\n\n const visit = (entry: AnyServerFnMiddleware) => {\n assertServerFnMiddleware(entry);\n if (seen.has(entry)) return;\n if (visiting.has(entry)) {\n throw new Error(\"Server function middleware dependencies cannot contain a cycle\");\n }\n\n visiting.add(entry);\n for (const dependency of entry.middleware) {\n visit(dependency);\n }\n visiting.delete(entry);\n seen.add(entry);\n resolved.push(entry);\n };\n\n for (const entry of middleware ?? []) {\n visit(entry);\n }\n\n return Object.freeze(resolved);\n}\n\nfunction assertServerFnMiddleware(value: unknown): asserts value is AnyServerFnMiddleware {\n if (\n !value ||\n typeof value !== \"object\" ||\n (value as { __farmServerFnMiddleware?: unknown }).__farmServerFnMiddleware !== true ||\n typeof (value as { handler?: unknown }).handler !== \"function\" ||\n !Array.isArray((value as { middleware?: unknown }).middleware)\n ) {\n throw new TypeError(\"createServerFn middleware must be created with createServerMiddleware\");\n }\n}\n\nfunction mergeServerFnContext(current: Readonly<object>, added: object | undefined) {\n if (\n added !== undefined &&\n (added === null || typeof added !== \"object\" || Array.isArray(added))\n ) {\n throw new TypeError(\"Server function middleware context must be an object\");\n }\n\n return Object.freeze(Object.assign(Object.create(null), current, added));\n}\n\nexport async function _parseServerFnSchema(\n schema: ServerFnSchema | undefined,\n value: unknown,\n contract: \"input\" | \"output\",\n owner = \"createServerFn\",\n) {\n if (!schema) return value;\n\n if (typeof schema.safeParseAsync === \"function\") {\n const result = await schema.safeParseAsync(value);\n return unwrapSafeParseResult(result);\n }\n\n if (typeof schema.safeParse === \"function\") {\n const result = schema.safeParse(value);\n return unwrapSafeParseResult(await result);\n }\n\n if (typeof schema.parseAsync === \"function\") {\n return schema.parseAsync(value);\n }\n\n if (typeof schema.parse === \"function\") {\n return schema.parse(value);\n }\n\n throw new TypeError(`${owner} ${contract} must provide parse, parseAsync, or safeParse`);\n}\n\nfunction unwrapSafeParseResult(result: unknown) {\n if (\n result &&\n typeof result === \"object\" &&\n \"success\" in result &&\n (result as { success: boolean }).success === false\n ) {\n throw (result as { error?: unknown }).error;\n }\n\n if (\n result &&\n typeof result === \"object\" &&\n \"success\" in result &&\n (result as { success: boolean }).success === true\n ) {\n return (result as unknown as { data: unknown }).data;\n }\n\n return result;\n}\n\nfunction formDataToObject(formData: FormData) {\n const output: Record<string, FormDataEntryValue | FormDataEntryValue[]> = Object.create(null);\n\n for (const [key, value] of formData.entries()) {\n if (!isSafeFormKey(key)) continue;\n\n const existing = output[key];\n if (existing === undefined) {\n output[key] = value;\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n output[key] = [existing, value];\n }\n }\n\n return output;\n}\n\nfunction isSafeFormKey(key: string) {\n return !key.startsWith(\"$ACTION_\") && !UNSAFE_FORM_KEYS.has(key);\n}\n\nfunction isFormData(value: unknown): value is FormData {\n if (!value || typeof value !== \"object\") return false;\n\n if (typeof FormData !== \"undefined\" && value instanceof FormData) {\n return true;\n }\n\n return (\n Object.prototype.toString.call(value) === \"[object FormData]\" &&\n typeof (value as { entries?: unknown }).entries === \"function\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4OO,IAAM,wBAAwB,uBAAO,IAAI,gBAAgB;AAEhE,IAAM,mBAAmB,oBAAI,IAAI,CAAC,aAAa,eAAe,WAAW,CAAC;AAQnE,SAAS,uBAAuB,SAGX;AAC1B,MAAI,CAAC,WAAW,OAAO,QAAQ,YAAY,YAAY;AACrD,UAAM,IAAI,UAAU,oDAAoD;AAAA,EAC1E;AAEA,QAAM,aAAa,OAAO,OAAO,CAAC,GAAI,QAAQ,cAAc,CAAC,CAAE,CAAC;AAChE,aAAW,SAAS,YAAY;AAC9B,6BAAyB,KAAK;AAAA,EAChC;AAEA,SAAO,OAAO,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O,WAAW,YAClB,aAAa,UACZ,OAAgC,YAAY,OAC7C;AACA,UAAO,OAA+B;AAAA,EACxC;AAEA,MACE,UACA,OAAO,WAAW,YAClB,aAAa,UACZ,OAAgC,YAAY,MAC7C;AACA,WAAQ,OAAwC;AAAA,EAClD;AAEA,SAAO;AACT;AApBS;AAsBT,SAAS,iBAAiB,UAAoB;AAC5C,QAAM,SAAoE,uBAAO,OAAO,IAAI;AAE5F,aAAW,CAAC,KAAK,KAAK,KAAK,SAAS,QAAQ,GAAG;AAC7C,QAAI,CAAC,cAAc,GAAG,EAAG;AAEzB,UAAM,WAAW,OAAO,GAAG;AAC3B,QAAI,aAAa,QAAW;AAC1B,aAAO,GAAG,IAAI;AAAA,IAChB,WAAW,MAAM,QAAQ,QAAQ,GAAG;AAClC,eAAS,KAAK,KAAK;AAAA,IACrB,OAAO;AACL,aAAO,GAAG,IAAI,CAAC,UAAU,KAAK;AAAA,IAChC;AAAA,EACF;AAEA,SAAO;AACT;AAjBS;AAmBT,SAAS,cAAc,KAAa;AAClC,SAAO,CAAC,IAAI,WAAW,UAAU,KAAK,CAAC,iBAAiB,IAAI,GAAG;AACjE;AAFS;AAIT,SAAS,WAAW,OAAmC;AACrD,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,MAAI,OAAO,aAAa,eAAe,iBAAiB,UAAU;AAChE,WAAO;AAAA,EACT;AAEA,SACE,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM,uBAC1C,OAAQ,MAAgC,YAAY;AAExD;AAXS;","names":["result"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useRouter
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-B3FFOIWS.mjs";
|
|
4
4
|
import {
|
|
5
5
|
__name
|
|
6
6
|
} from "./chunk-CGILA3WO.mjs";
|
|
@@ -38,4 +38,4 @@ export {
|
|
|
38
38
|
usePathname,
|
|
39
39
|
useSearchParams
|
|
40
40
|
};
|
|
41
|
-
//# sourceMappingURL=chunk-
|
|
41
|
+
//# sourceMappingURL=chunk-XMFTIVJH.mjs.map
|
|
@@ -8,6 +8,68 @@ import {
|
|
|
8
8
|
|
|
9
9
|
// src/server-action-security.ts
|
|
10
10
|
import { AsyncLocalStorage } from "async_hooks";
|
|
11
|
+
|
|
12
|
+
// src/server-fn-error.ts
|
|
13
|
+
var FARM_SERVER_FN_FAILURE_SYMBOL = /* @__PURE__ */ Symbol.for("farm.server-fn.failure");
|
|
14
|
+
var _ServerFnFailure = class _ServerFnFailure extends Error {
|
|
15
|
+
constructor(code, data, options) {
|
|
16
|
+
super(options.message);
|
|
17
|
+
this.name = "ServerFnFailure";
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.data = data;
|
|
20
|
+
this.status = options.status;
|
|
21
|
+
Object.defineProperty(this, FARM_SERVER_FN_FAILURE_SYMBOL, {
|
|
22
|
+
value: true,
|
|
23
|
+
enumerable: false
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
__name(_ServerFnFailure, "ServerFnFailure");
|
|
28
|
+
var ServerFnFailure = _ServerFnFailure;
|
|
29
|
+
var _ServerActionError = class _ServerActionError extends Error {
|
|
30
|
+
constructor(message = "Server function failed") {
|
|
31
|
+
super(message);
|
|
32
|
+
this.name = "ServerActionError";
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
__name(_ServerActionError, "ServerActionError");
|
|
36
|
+
var ServerActionError = _ServerActionError;
|
|
37
|
+
function isServerFnFailure(value) {
|
|
38
|
+
if (!value || typeof value !== "object") return false;
|
|
39
|
+
const candidate = value;
|
|
40
|
+
return candidate[FARM_SERVER_FN_FAILURE_SYMBOL] === true && candidate.name === "ServerFnFailure" && typeof candidate.code === "string" && Number.isInteger(candidate.status) && (candidate.status ?? 0) >= 400 && (candidate.status ?? 0) <= 599;
|
|
41
|
+
}
|
|
42
|
+
__name(isServerFnFailure, "isServerFnFailure");
|
|
43
|
+
function serializeServerFnFailure(value) {
|
|
44
|
+
if (!isServerFnFailure(value)) return null;
|
|
45
|
+
return {
|
|
46
|
+
name: "ServerFnFailure",
|
|
47
|
+
message: value.message,
|
|
48
|
+
code: value.code,
|
|
49
|
+
status: value.status,
|
|
50
|
+
data: value.data
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
__name(serializeServerFnFailure, "serializeServerFnFailure");
|
|
54
|
+
function createServerFnTransportError(value) {
|
|
55
|
+
if (isSerializedServerFnFailure(value)) {
|
|
56
|
+
return new ServerFnFailure(value.code, value.data, {
|
|
57
|
+
status: value.status,
|
|
58
|
+
message: value.message
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
const message = value && typeof value === "object" && "message" in value && typeof value.message === "string" ? value.message : "Server function failed";
|
|
62
|
+
return new ServerActionError(message);
|
|
63
|
+
}
|
|
64
|
+
__name(createServerFnTransportError, "createServerFnTransportError");
|
|
65
|
+
function isSerializedServerFnFailure(value) {
|
|
66
|
+
if (!value || typeof value !== "object") return false;
|
|
67
|
+
const candidate = value;
|
|
68
|
+
return candidate.name === "ServerFnFailure" && typeof candidate.message === "string" && typeof candidate.code === "string" && Number.isInteger(candidate.status) && (candidate.status ?? 0) >= 400 && (candidate.status ?? 0) <= 599 && "data" in candidate;
|
|
69
|
+
}
|
|
70
|
+
__name(isSerializedServerFnFailure, "isSerializedServerFnFailure");
|
|
71
|
+
|
|
72
|
+
// src/server-action-security.ts
|
|
11
73
|
var DEFAULT_SERVER_ACTION_BODY_SIZE_LIMIT = 1e6;
|
|
12
74
|
var _ServerActionRequestError = class _ServerActionRequestError extends Error {
|
|
13
75
|
constructor(code, status, message) {
|
|
@@ -120,7 +182,9 @@ function createServerActionRequestErrorResponse(error) {
|
|
|
120
182
|
});
|
|
121
183
|
}
|
|
122
184
|
__name(createServerActionRequestErrorResponse, "createServerActionRequestErrorResponse");
|
|
123
|
-
function sanitizeServerActionError(
|
|
185
|
+
function sanitizeServerActionError(error) {
|
|
186
|
+
const declaredFailure = serializeServerFnFailure(error);
|
|
187
|
+
if (declaredFailure) return declaredFailure;
|
|
124
188
|
return {
|
|
125
189
|
name: "ServerActionError",
|
|
126
190
|
message: "Server function failed"
|
|
@@ -443,6 +507,11 @@ function throwIfAborted(signal) {
|
|
|
443
507
|
__name(throwIfAborted, "throwIfAborted");
|
|
444
508
|
|
|
445
509
|
export {
|
|
510
|
+
FARM_SERVER_FN_FAILURE_SYMBOL,
|
|
511
|
+
ServerFnFailure,
|
|
512
|
+
ServerActionError,
|
|
513
|
+
isServerFnFailure,
|
|
514
|
+
createServerFnTransportError,
|
|
446
515
|
DEFAULT_SERVER_ACTION_BODY_SIZE_LIMIT,
|
|
447
516
|
ServerActionRequestError,
|
|
448
517
|
resolveServerActionsConfig,
|
|
@@ -455,4 +524,4 @@ export {
|
|
|
455
524
|
getServerActionSignal,
|
|
456
525
|
getServerActionInvalidations
|
|
457
526
|
};
|
|
458
|
-
//# sourceMappingURL=chunk-
|
|
527
|
+
//# sourceMappingURL=chunk-ZVMV3THA.mjs.map
|