Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(nuxt): add @since annotations to exported composables #25086

Merged
merged 26 commits into from
Jan 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
d8e3d4f
docs: annotate `useRequestURL`
luc122c Jan 6, 2024
116f635
docs: annotate async composables
luc122c Jan 6, 2024
6d1e88e
docs: annotate chunk reload
luc122c Jan 6, 2024
5020aee
docs: annotate cookies
luc122c Jan 6, 2024
c83cddd
docs: annotate `defineNuxtComponent`
luc122c Jan 6, 2024
86ee6cf
docs: annotate error composables
luc122c Jan 7, 2024
4988d5f
docs: make annotations single-line
luc122c Jan 7, 2024
5e261a0
docs: annotate `useFetch` and `useLazyFetch`
luc122c Jan 7, 2024
4bb7dd8
docs: annotate `useHydration`
luc122c Jan 7, 2024
ca3a688
docs: annotate `useLoadingIndicator`
luc122c Jan 7, 2024
7ce4f51
docs: annotate `getAppManifest` and `getRouteRules`
luc122c Jan 7, 2024
4f46f3c
docs: annotate `callOnce`
luc122c Jan 7, 2024
f55cced
Merge branch 'main' into docs/add-since
luc122c Jan 18, 2024
86bf317
docs: annotate payload composables
luc122c Jan 18, 2024
ca34cf5
Merge branch 'docs/add-since' of https://github.com/luc122c/nuxt into…
luc122c Jan 18, 2024
9840a29
docs: annotate preload composables
luc122c Jan 18, 2024
72ee8d1
Merge commit 'dab2188d58e2dcb03a900ac6626a21589df21356' into docs/add…
luc122c Jan 18, 2024
8ef3fa1
docs: annotate `onNuxtReady` composable
luc122c Jan 18, 2024
191d245
docs: update `useNuxtData` annotation
luc122c Jan 18, 2024
a9cdcf0
docs: annotate state composables
luc122c Jan 18, 2024
a1ac58b
docs: annotate ssr composables
luc122c Jan 18, 2024
b0bcf75
docs: annotate router composables
luc122c Jan 18, 2024
fd33d2d
docs: revert formatting changes in `asyncData`
luc122c Jan 18, 2024
2c2ff95
docs: fix line ending
luc122c Jan 19, 2024
7f4cd32
docs: revert style changes in `fetch`
luc122c Jan 19, 2024
092c154
Merge branch 'main' into docs/add-since
luc122c Jan 19, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/nuxt/src/app/composables/asyncContext.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// @ts-expect-error withAsyncContext is internal API
import { getCurrentInstance, withAsyncContext as withVueAsyncContext } from 'vue'

/** @since 3.8.0 */
export function withAsyncContext (fn: () => PromiseLike<unknown>) {
return withVueAsyncContext(() => {
const nuxtApp = getCurrentInstance()?.appContext.app.$nuxt
Expand Down
5 changes: 5 additions & 0 deletions packages/nuxt/src/app/composables/asyncData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ const isDefer = (dedupe?: boolean | 'cancel' | 'defer') => dedupe === 'defer' ||
/**
* Provides access to data that resolves asynchronously in an SSR-friendly composable.
* See {@link https://nuxt.com/docs/api/composables/use-async-data}
* @since 3.0.0
* @param handler An asynchronous function that must return a truthy value (for example, it should not be `undefined` or `null`) or the request may be duplicated on the client side.
* @param options customize the behavior of useAsyncData
*/
Expand Down Expand Up @@ -378,6 +379,7 @@ export function useAsyncData<

return asyncDataPromise as AsyncData<PickFrom<DataT, PickKeys>, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>)>
}
/** @since 3.0.0 */
export function useLazyAsyncData<
ResT,
DataE = Error,
Expand Down Expand Up @@ -441,6 +443,7 @@ export function useLazyAsyncData<
return useAsyncData(key, handler, { ...options, lazy: true }, null)
}

/** @since 3.1.0 */
export function useNuxtData<DataT = any> (key: string): { data: Ref<DataT | null> } {
const nuxt = useNuxtApp()

Expand All @@ -454,6 +457,7 @@ export function useNuxtData<DataT = any> (key: string): { data: Ref<DataT | null
}
}

/** @since 3.0.0 */
export async function refreshNuxtData (keys?: string | string[]): Promise<void> {
if (import.meta.server) {
return Promise.resolve()
Expand All @@ -465,6 +469,7 @@ export async function refreshNuxtData (keys?: string | string[]): Promise<void>
await useNuxtApp().hooks.callHookParallel('app:data:refresh', _keys)
}

/** @since 3.0.0 */
export function clearNuxtData (keys?: string | string[] | ((key: string) => boolean)): void {
const nuxtApp = useNuxtApp()
const _allKeys = Object.keys(nuxtApp.payload.data)
Expand Down
1 change: 1 addition & 0 deletions packages/nuxt/src/app/composables/chunk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export interface ReloadNuxtAppOptions {
path?: string
}

/** @since 3.3.0 */
export function reloadNuxtApp (options: ReloadNuxtAppOptions = {}) {
if (import.meta.server) { return }
const path = options.path || window.location.pathname
Expand Down
1 change: 1 addition & 0 deletions packages/nuxt/src/app/composables/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ async function runLegacyAsyncData (res: Record<string, any> | Promise<Record<str
}
}

/** @since 3.0.0 */
/*@__NO_SIDE_EFFECTS__*/
export const defineNuxtComponent: typeof defineComponent =
function defineNuxtComponent (...args: any[]): any {
Expand Down
1 change: 1 addition & 0 deletions packages/nuxt/src/app/composables/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const CookieDefaults = {
encode: val => encodeURIComponent(typeof val === 'string' ? val : JSON.stringify(val))
} satisfies CookieOptions<any>

/** @since 3.0.0 */
export function useCookie<T = string | null | undefined> (name: string, _opts?: CookieOptions<T> & { readonly?: false }): CookieRef<T>
export function useCookie<T = string | null | undefined> (name: string, _opts: CookieOptions<T> & { readonly: true }): Readonly<CookieRef<T>>
export function useCookie<T = string | null | undefined> (name: string, _opts?: CookieOptions<T>): CookieRef<T> {
Expand Down
5 changes: 5 additions & 0 deletions packages/nuxt/src/app/composables/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import { useRouter } from './router'

export const NUXT_ERROR_SIGNATURE = '__nuxt_error'

/** @since 3.0.0 */
export const useError = () => toRef(useNuxtApp().payload, 'error')

export interface NuxtError<DataT = unknown> extends H3Error<DataT> {}

/** @since 3.0.0 */
export const showError = <DataT = unknown>(
error: string | Error | Partial<NuxtError<DataT>>
) => {
Expand All @@ -31,6 +33,7 @@ export const showError = <DataT = unknown>(
return nuxtError
}

/** @since 3.0.0 */
export const clearError = async (options: { redirect?: string } = {}) => {
const nuxtApp = useNuxtApp()
const error = useError()
Expand All @@ -44,12 +47,14 @@ export const clearError = async (options: { redirect?: string } = {}) => {
error.value = null
}

/** @since 3.0.0 */
export const isNuxtError = <DataT = unknown>(
error?: string | object
): error is NuxtError<DataT> => (
!!error && typeof error === 'object' && NUXT_ERROR_SIGNATURE in error
)

/** @since 3.0.0 */
export const createError = <DataT = unknown>(
error: string | Partial<NuxtError<DataT>>
) => {
Expand Down
2 changes: 2 additions & 0 deletions packages/nuxt/src/app/composables/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export interface UseFetchOptions<
/**
* Fetch data from an API endpoint with an SSR-friendly composable.
* See {@link https://nuxt.com/docs/api/composables/use-fetch}
* @since 3.0.0
* @param request The URL to fetch
* @param opts extends $fetch options and useAsyncData options
*/
Expand Down Expand Up @@ -184,6 +185,7 @@ export function useFetch<
return asyncData
}

/** @since 3.0.0 */
export function useLazyFetch<
ResT = void,
ErrorT = FetchError,
Expand Down
1 change: 1 addition & 0 deletions packages/nuxt/src/app/composables/hydrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { NuxtPayload } from '../nuxt'
* @param key a unique key to identify the data in the Nuxt payload
* @param get a function that returns the value to set the initial data
* @param set a function that will receive the data on the client-side
* @since 3.0.0
*/
export const useHydration = <K extends keyof NuxtPayload, T = NuxtPayload[K]> (key: K, get: () => T, set: (value: T) => void) => {
const nuxt = useNuxtApp()
Expand Down
1 change: 1 addition & 0 deletions packages/nuxt/src/app/composables/loading-indicator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ function createLoadingIndicator (opts: Partial<LoadingIndicatorOpts> = {}) {

/**
* composable to handle the loading state of the page
* @since 3.9.0
*/
export function useLoadingIndicator (opts: Partial<LoadingIndicatorOpts> = {}): Omit<LoadingIndicator, '_cleanup'> {
const nuxtApp = useNuxtApp()
Expand Down
2 changes: 2 additions & 0 deletions packages/nuxt/src/app/composables/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,15 @@ function fetchManifest () {
return manifest
}

/** @since 3.7.4 */
export function getAppManifest (): Promise<NuxtAppManifest> {
if (!isAppManifestEnabled) {
throw new Error('[nuxt] app manifest should be enabled with `experimental.appManifest`')
}
return manifest || fetchManifest()
}

/** @since 3.7.4 */
export async function getRouteRules (url: string) {
await getAppManifest()
return defu({} as Record<string, any>, ...matcher.matchAll(url).reverse())
Expand Down
1 change: 1 addition & 0 deletions packages/nuxt/src/app/composables/once.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useNuxtApp } from '../nuxt'
* @param key a unique key ensuring the function can be properly de-duplicated across requests
* @param fn a function to call
* @see https://nuxt.com/docs/api/utils/call-once
* @since 3.9.0
*/
export function callOnce (key?: string, fn?: (() => any | Promise<any>)): Promise<void>
export function callOnce (fn?: (() => any | Promise<any>)): Promise<void>
Expand Down
8 changes: 6 additions & 2 deletions packages/nuxt/src/app/composables/payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ interface LoadPayloadOptions {
hash?: string
}

/** @since 3.0.0 */
export function loadPayload (url: string, opts: LoadPayloadOptions = {}): Record<string, any> | Promise<Record<string, any>> | null {
if (import.meta.server || !payloadExtraction) { return null }
const payloadURL = _getPayloadURL(url, opts)
Expand All @@ -37,7 +38,7 @@ export function loadPayload (url: string, opts: LoadPayloadOptions = {}): Record
})
return cache[payloadURL]
}

/** @since 3.0.0 */
export function preloadPayload (url: string, opts: LoadPayloadOptions = {}) {
const payloadURL = _getPayloadURL(url, opts)
useHead({
Expand Down Expand Up @@ -75,7 +76,7 @@ async function _importPayload (payloadURL: string) {
}
return null
}

/** @since 3.0.0 */
export async function isPrerendered (url = useRoute().path) {
// Note: Alternative for server is checking x-nitro-prerender header
if (!appManifest) { return !!useNuxtApp().payload.prerenderedAt }
Expand All @@ -89,6 +90,7 @@ export async function isPrerendered (url = useRoute().path) {
}

let payloadCache: any = null
/** @since 3.4.0 */
export async function getNuxtClientPayload () {
if (import.meta.server) {
return
Expand Down Expand Up @@ -121,6 +123,7 @@ export async function parsePayload (payload: string) {

/**
* This is an experimental function for configuring passing rich data from server -> client.
* @since 3.4.0
*/
export function definePayloadReducer (
name: string,
Expand All @@ -135,6 +138,7 @@ export function definePayloadReducer (
* This is an experimental function for configuring passing rich data from server -> client.
*
* This function _must_ be called in a Nuxt plugin that is `unshift`ed to the beginning of the Nuxt plugins array.
* @since 3.4.0
*/
export function definePayloadReviver (
name: string,
Expand Down
3 changes: 3 additions & 0 deletions packages/nuxt/src/app/composables/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { useRouter } from './router'
/**
* Preload a component or components that have been globally registered.
* @param components Pascal-cased name or names of components to prefetch
* @since 3.0.0
*/
export const preloadComponents = async (components: string | string[]) => {
if (import.meta.server) { return }
Expand All @@ -19,6 +20,7 @@ export const preloadComponents = async (components: string | string[]) => {
/**
* Prefetch a component or components that have been globally registered.
* @param components Pascal-cased name or names of components to prefetch
* @since 3.0.0
*/
export const prefetchComponents = (components: string | string[]) => {
// TODO
Expand All @@ -33,6 +35,7 @@ function _loadAsyncComponent (component: Component) {
}
}

/** @since 3.0.0 */
export async function preloadRouteComponents (to: RouteLocationRaw, router: Router & { _routePreloaded?: Set<string>; _preloadPromises?: Array<Promise<any>> } = useRouter()): Promise<void> {
if (import.meta.server) { return }

Expand Down
1 change: 1 addition & 0 deletions packages/nuxt/src/app/composables/ready.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useNuxtApp } from '../nuxt'
import { requestIdleCallback } from '../compat/idle-callback'

/** @since 3.1.0 */
export const onNuxtReady = (callback: () => any) => {
if (import.meta.server) { return }

Expand Down
14 changes: 13 additions & 1 deletion packages/nuxt/src/app/composables/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ import { PageRouteSymbol } from '../components/injections'
import type { NuxtError } from './error'
import { createError, showError } from './error'

/** @since 3.0.0 */
export const useRouter: typeof _useRouter = () => {
return useNuxtApp()?.$router as Router
}

/** @since 3.0.0 */
export const useRoute: typeof _useRoute = () => {
if (import.meta.dev && isProcessingMiddleware()) {
console.warn('[nuxt] Calling `useRoute` within middleware may lead to misleading results. Instead, use the (to, from) arguments passed to the middleware to access the new and old routes.')
Expand All @@ -26,6 +28,7 @@ export const useRoute: typeof _useRoute = () => {
return useNuxtApp()._route
}

/** @since 3.0.0 */
export const onBeforeRouteLeave = (guard: NavigationGuard) => {
const unsubscribe = useRouter().beforeEach((to, from, next) => {
if (to === from) { return }
Expand All @@ -34,6 +37,7 @@ export const onBeforeRouteLeave = (guard: NavigationGuard) => {
onScopeDispose(unsubscribe)
}

/** @since 3.0.0 */
export const onBeforeRouteUpdate = (guard: NavigationGuard) => {
const unsubscribe = useRouter().beforeEach(guard)
onScopeDispose(unsubscribe)
Expand All @@ -43,6 +47,7 @@ export interface RouteMiddleware {
(to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard>
}

/** @since 3.0.0 */
/*@__NO_SIDE_EFFECTS__*/
export function defineNuxtRouteMiddleware (middleware: RouteMiddleware) {
return middleware
Expand All @@ -57,6 +62,7 @@ interface AddRouteMiddleware {
(middleware: RouteMiddleware): void
}

/** @since 3.0.0 */
export const addRouteMiddleware: AddRouteMiddleware = (name: string | RouteMiddleware, middleware?: RouteMiddleware, options: AddRouteMiddlewareOptions = {}) => {
const nuxtApp = useNuxtApp()
const global = options.global || typeof name !== 'string'
Expand All @@ -72,6 +78,7 @@ export const addRouteMiddleware: AddRouteMiddleware = (name: string | RouteMiddl
}
}

/** @since 3.0.0 */
const isProcessingMiddleware = () => {
try {
if (useNuxtApp()._processingMiddleware) {
Expand Down Expand Up @@ -109,6 +116,7 @@ export interface NavigateToOptions {
open?: OpenOptions
}

/** @since 3.0.0 */
export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions): Promise<void | NavigationFailure | false> | false | void | RouteLocationRaw => {
if (!to) {
to = '/'
Expand Down Expand Up @@ -206,7 +214,10 @@ export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: Na
return options?.replace ? router.replace(to) : router.push(to)
}

/** This will abort navigation within a Nuxt route middleware handler. */
/**
* This will abort navigation within a Nuxt route middleware handler.
* @since 3.0.0
*/
export const abortNavigation = (err?: string | Partial<NuxtError>) => {
if (import.meta.dev && !isProcessingMiddleware()) {
throw new Error('abortNavigation() is only usable inside a route middleware handler.')
Expand All @@ -223,6 +234,7 @@ export const abortNavigation = (err?: string | Partial<NuxtError>) => {
throw err
}

/** @since 3.0.0 */
export const setPageLayout = (layout: unknown extends PageMeta['layout'] ? string : PageMeta['layout']) => {
const nuxtApp = useNuxtApp()
if (import.meta.server) {
Expand Down
6 changes: 6 additions & 0 deletions packages/nuxt/src/app/composables/ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import type { NuxtApp } from '../nuxt'
import { useNuxtApp } from '../nuxt'
import { toArray } from '../utils'

/** @since 3.0.0 */
export function useRequestEvent (nuxtApp: NuxtApp = useNuxtApp()): H3Event {
return nuxtApp.ssrContext?.event as H3Event
}

/** @since 3.0.0 */
export function useRequestHeaders<K extends string = string> (include: K[]): { [key in Lowercase<K>]?: string }
export function useRequestHeaders (): Readonly<Record<string, string>>
export function useRequestHeaders (include?: any[]) {
Expand All @@ -26,19 +28,22 @@ export function useRequestHeaders (include?: any[]) {
return headers
}

/** @since 3.9.0 */
export function useRequestHeader(header: string) {
if (import.meta.client) { return undefined }
const event = useRequestEvent()
return event ? getRequestHeader(event, header) : undefined
}

/** @since 3.2.0 */
export function useRequestFetch (): typeof global.$fetch {
if (import.meta.client) {
return globalThis.$fetch
}
return useRequestEvent()?.$fetch as typeof globalThis.$fetch || globalThis.$fetch
}

/** @since 3.0.0 */
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When a function has multiple overloads, does each one need it's own annotation? I see that the last overload has a @deprecated annotation which does not affect the first.
Also, what about the case where a new overload is added in a newer version, can that have it's own @since annotation?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm happy to stick with just one for now.

export function setResponseStatus (event: H3Event, code?: number, message?: string): void
/** @deprecated Pass `event` as first option. */
export function setResponseStatus (code: number, message?: string): void
Expand All @@ -50,6 +55,7 @@ export function setResponseStatus (arg1: H3Event | number | undefined, arg2?: nu
return _setResponseStatus(useRequestEvent(), arg1, arg2 as string | undefined)
}

/** @since 3.8.0 */
export function prerenderRoutes (path: string | string[]) {
if (!import.meta.server || !import.meta.prerender) { return }

Expand Down
2 changes: 2 additions & 0 deletions packages/nuxt/src/app/composables/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { toArray } from '../utils'
const useStateKeyPrefix = '$s'
/**
* Create a global reactive ref that will be hydrated but not shared across ssr requests
* @since 3.0.0
* @param key a unique key ensuring that data fetching can be properly de-duplicated across requests
* @param init a function that provides initial value for the state when it's not initiated
*/
Expand Down Expand Up @@ -37,6 +38,7 @@ export function useState <T> (...args: any): Ref<T> {
return state
}

/** @since 3.6.0 */
export function clearNuxtState (
keys?: string | string[] | ((key: string) => boolean)
): void {
Expand Down
1 change: 1 addition & 0 deletions packages/nuxt/src/app/composables/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { joinURL } from 'ufo'
import { useRuntimeConfig } from '../nuxt'
import { useRequestEvent } from './ssr'

/** @since 3.5.0 */
export function useRequestURL () {
if (import.meta.server) {
const url = getRequestURL(useRequestEvent())
Expand Down