This repository has been archived by the owner on Apr 6, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
nuxt.ts
313 lines (269 loc) · 9.12 KB
/
nuxt.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/* eslint-disable no-use-before-define */
import { getCurrentInstance, reactive, Ref } from 'vue'
import type { App, onErrorCaptured, VNode } from 'vue'
import { createHooks, Hookable } from 'hookable'
import type { RuntimeConfig, AppConfigInput } from '@nuxt/schema'
import { getContext } from 'unctx'
import type { SSRContext } from 'vue-bundle-renderer/runtime'
import type { H3Event } from 'h3'
const nuxtAppCtx = getContext<NuxtApp>('nuxt-app')
type NuxtMeta = {
htmlAttrs?: string
headAttrs?: string
bodyAttrs?: string
headTags?: string
bodyScriptsPrepend?: string
bodyScripts?: string
}
type HookResult = Promise<void> | void
type AppRenderedContext = { ssrContext: NuxtApp['ssrContext'] }
export interface RuntimeNuxtHooks {
'app:created': (app: App<Element>) => HookResult
'app:beforeMount': (app: App<Element>) => HookResult
'app:mounted': (app: App<Element>) => HookResult
'app:rendered': (ctx: AppRenderedContext) => HookResult
'app:redirected': () => HookResult
'app:suspense:resolve': (Component?: VNode) => HookResult
'app:error': (err: any) => HookResult
'app:error:cleared': (options: { redirect?: string }) => HookResult
'app:data:refresh': (keys?: string[]) => HookResult
'link:prefetch': (link: string) => HookResult
'page:start': (Component?: VNode) => HookResult
'page:finish': (Component?: VNode) => HookResult
'page:transition:finish': (Component?: VNode) => HookResult
'vue:setup': () => void
'vue:error': (...args: Parameters<Parameters<typeof onErrorCaptured>[0]>) => HookResult
}
export interface NuxtSSRContext extends SSRContext {
url: string
event: H3Event
runtimeConfig: RuntimeConfig
noSSR: boolean
/** whether we are rendering an SSR error */
error?: boolean
nuxt: _NuxtApp
payload: _NuxtApp['payload']
teleports?: Record<string, string>
renderMeta?: () => Promise<NuxtMeta> | NuxtMeta
}
interface _NuxtApp {
vueApp: App<Element>
globalName: string
hooks: Hookable<RuntimeNuxtHooks>
hook: _NuxtApp['hooks']['hook']
callHook: _NuxtApp['hooks']['callHook']
[key: string]: any
_asyncDataPromises: Record<string, Promise<any> | undefined>
_asyncData: Record<string, {
data: Ref<any>
pending: Ref<boolean>
error: Ref<any>
} | undefined>
isHydrating?: boolean
deferHydration: () => () => void | Promise<void>
ssrContext?: NuxtSSRContext
payload: {
serverRendered?: boolean
prerenderedAt?: number
data: Record<string, any>
state: Record<string, any>
rendered?: Function
error?: Error | {
url: string
statusCode: string
statusMessage: string
message: string
description: string
data?: any
} | null
[key: string]: any
}
provide: (name: string, value: any) => void
}
export interface NuxtApp extends _NuxtApp {}
export const NuxtPluginIndicator = '__nuxt_plugin'
export interface Plugin<Injections extends Record<string, any> = Record<string, any>> {
(nuxt: _NuxtApp): Promise<void> | Promise<{ provide?: Injections }> | void | { provide?: Injections }
[NuxtPluginIndicator]?: true
}
export interface CreateOptions {
vueApp: NuxtApp['vueApp']
ssrContext?: NuxtApp['ssrContext']
globalName?: NuxtApp['globalName']
}
export function createNuxtApp (options: CreateOptions) {
let hydratingCount = 0
const nuxtApp: NuxtApp = {
provide: undefined,
globalName: 'nuxt',
payload: reactive({
data: {},
state: {},
_errors: {},
...(process.client ? window.__NUXT__ : { serverRendered: true })
}),
isHydrating: process.client,
deferHydration () {
if (!nuxtApp.isHydrating) { return () => {} }
hydratingCount++
let called = false
return () => {
if (called) { return }
called = true
hydratingCount--
if (hydratingCount === 0) {
nuxtApp.isHydrating = false
return nuxtApp.callHook('app:suspense:resolve')
}
}
},
_asyncDataPromises: {},
_asyncData: {},
...options
} as any as NuxtApp
nuxtApp.hooks = createHooks<RuntimeNuxtHooks>()
nuxtApp.hook = nuxtApp.hooks.hook
nuxtApp.callHook = nuxtApp.hooks.callHook
nuxtApp.provide = (name: string, value: any) => {
const $name = '$' + name
defineGetter(nuxtApp, $name, value)
defineGetter(nuxtApp.vueApp.config.globalProperties, $name, value)
}
// Inject $nuxt
defineGetter(nuxtApp.vueApp, '$nuxt', nuxtApp)
defineGetter(nuxtApp.vueApp.config.globalProperties, '$nuxt', nuxtApp)
if (process.server) {
// Expose nuxt to the renderContext
if (nuxtApp.ssrContext) {
nuxtApp.ssrContext.nuxt = nuxtApp
}
// Expose to server renderer to create window.__NUXT__
nuxtApp.ssrContext = nuxtApp.ssrContext || {} as any
if (nuxtApp.ssrContext!.payload) {
Object.assign(nuxtApp.payload, nuxtApp.ssrContext!.payload)
}
nuxtApp.ssrContext!.payload = nuxtApp.payload
// Expose client runtime-config to the payload
nuxtApp.payload.config = {
public: options.ssrContext!.runtimeConfig.public,
app: options.ssrContext!.runtimeConfig.app
}
}
// Expose runtime config
const runtimeConfig = process.server
? options.ssrContext!.runtimeConfig
: reactive(nuxtApp.payload.config)
// Backward compatibility following #4254
const compatibilityConfig = new Proxy(runtimeConfig, {
get (target, prop) {
if (prop === 'public') {
return target.public
}
return target[prop] ?? target.public[prop]
},
set (target, prop, value) {
if (process.server || prop === 'public' || prop === 'app') {
return false // Throws TypeError
}
target[prop] = value
target.public[prop] = value
return true
}
})
nuxtApp.provide('config', compatibilityConfig)
return nuxtApp
}
export async function applyPlugin (nuxtApp: NuxtApp, plugin: Plugin) {
if (typeof plugin !== 'function') { return }
const { provide } = await callWithNuxt(nuxtApp, plugin, [nuxtApp]) || {}
if (provide && typeof provide === 'object') {
for (const key in provide) {
nuxtApp.provide(key, provide[key])
}
}
}
export async function applyPlugins (nuxtApp: NuxtApp, plugins: Plugin[]) {
for (const plugin of plugins) {
await applyPlugin(nuxtApp, plugin)
}
}
export function normalizePlugins (_plugins: Plugin[]) {
const unwrappedPlugins: Plugin[] = []
const legacyInjectPlugins: Plugin[] = []
const invalidPlugins: Plugin[] = []
const plugins = _plugins.map((plugin) => {
if (typeof plugin !== 'function') {
invalidPlugins.push(plugin)
return null
}
if (plugin.length > 1) {
legacyInjectPlugins.push(plugin)
// Allow usage without wrapper but warn
// TODO: Skip invalid in next releases
// @ts-ignore
return (nuxtApp: NuxtApp) => plugin(nuxtApp, nuxtApp.provide)
// return null
}
if (!isNuxtPlugin(plugin)) {
unwrappedPlugins.push(plugin)
// Allow usage without wrapper but warn
}
return plugin
}).filter(Boolean)
if (process.dev && legacyInjectPlugins.length) {
console.warn('[warn] [nuxt] You are using a plugin with legacy Nuxt 2 format (context, inject) which is likely to be broken. In the future they will be ignored:', legacyInjectPlugins.map(p => p.name || p).join(','))
}
if (process.dev && invalidPlugins.length) {
console.warn('[warn] [nuxt] Some plugins are not exposing a function and skipped:', invalidPlugins)
}
if (process.dev && unwrappedPlugins.length) {
console.warn('[warn] [nuxt] You are using a plugin that has not been wrapped in `defineNuxtPlugin`. It is advised to wrap your plugins as in the future this may enable enhancements:', unwrappedPlugins.map(p => p.name || p).join(','))
}
return plugins as Plugin[]
}
export function defineNuxtPlugin<T extends Record<string, any>> (plugin: Plugin<T>) {
plugin[NuxtPluginIndicator] = true
return plugin
}
export function isNuxtPlugin (plugin: unknown) {
return typeof plugin === 'function' && NuxtPluginIndicator in plugin
}
/**
* Ensures that the setup function passed in has access to the Nuxt instance via `useNuxt`.
*
* @param nuxt A Nuxt instance
* @param setup The function to call
*/
export function callWithNuxt<T extends (...args: any[]) => any> (nuxt: NuxtApp | _NuxtApp, setup: T, args?: Parameters<T>) {
const fn = () => args ? setup(...args as Parameters<T>) : setup()
if (process.server) {
return nuxtAppCtx.callAsync<ReturnType<T>>(nuxt, fn)
} else {
// In client side we could assume nuxt app is singleton
nuxtAppCtx.set(nuxt)
return fn()
}
}
/**
* Returns the current Nuxt instance.
*/
export function useNuxtApp () {
const nuxtAppInstance = nuxtAppCtx.tryUse()
if (!nuxtAppInstance) {
const vm = getCurrentInstance()
if (!vm) {
throw new Error('nuxt instance unavailable')
}
return vm.appContext.app.$nuxt as NuxtApp
}
return nuxtAppInstance
}
export function useRuntimeConfig (): RuntimeConfig {
return useNuxtApp().$config
}
function defineGetter<K extends string | number | symbol, V> (obj: Record<K, V>, key: K, val: V) {
Object.defineProperty(obj, key, { get: () => val })
}
export function defineAppConfig<C extends AppConfigInput> (config: C): C {
return config
}