-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathmodule.ts
244 lines (227 loc) · 8.26 KB
/
module.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
import {
addBuildPlugin,
addComponentsDir,
addImports,
addPluginTemplate,
createResolver,
defineNuxtModule,
hasNuxtModule,
} from '@nuxt/kit'
import { readPackageJSON } from 'pkg-types'
import type { FetchOptions } from 'ofetch'
import { setupDevToolsUI } from './devtools'
import { NuxtScriptBundleTransformer } from './plugins/transform'
import { setupPublicAssetStrategy } from './assets'
import { logger } from './logger'
import { extendTypes, installNuxtModule } from './kit'
import { registry } from './registry'
import type {
NuxtConfigScriptRegistry,
NuxtUseScriptInput,
NuxtUseScriptOptionsSerializable,
RegistryScript,
RegistryScripts,
} from './runtime/types'
import { NuxtScriptsCheckScripts } from './plugins/check-scripts'
import { templatePlugin } from './templates'
export interface ModuleOptions {
/**
* The registry of supported third-party scripts. Loads the scripts in globally using the default script options.
*/
registry?: NuxtConfigScriptRegistry
/**
* Default options for scripts.
*/
defaultScriptOptions?: NuxtUseScriptOptionsSerializable
/**
* Register scripts that should be loaded globally on all pages.
*/
globals?: Record<string, NuxtUseScriptInput | [NuxtUseScriptInput, NuxtUseScriptOptionsSerializable]>
/** Configure the way scripts assets are exposed */
assets?: {
/**
* The baseURL where scripts files are served.
* @default '/_scripts/'
*/
prefix?: string
/**
* Scripts assets are exposed as public assets as part of the build.
*
* TODO Make configurable in future.
*/
strategy?: 'public'
/**
* Fallback to src if bundle fails to load.
* The default behavior is to stop the bundling process if a script fails to be downloaded.
* @default false
*/
fallbackOnSrcOnBundleFail?: boolean
/**
* Configure the fetch options used for downloading scripts.
*/
fetchOptions?: FetchOptions
}
/**
* Whether the module is enabled.
*
* @default true
*/
enabled: boolean
/**
* Enables debug mode.
*
* @false false
*/
debug: boolean
}
export interface ModuleHooks {
'scripts:registry': (registry: RegistryScripts) => void | Promise<void>
}
export default defineNuxtModule<ModuleOptions>({
meta: {
name: '@nuxt/scripts',
configKey: 'scripts',
compatibility: {
nuxt: '>=3.16',
bridge: false,
},
},
defaults: {
defaultScriptOptions: {
trigger: 'onNuxtReady',
},
assets: {
fetchOptions: {
retry: 3, // Specifies the number of retry attempts for failed fetches.
retryDelay: 2000, // Specifies the delay (in milliseconds) between retry attempts.
timeout: 15_000, // Configures the maximum time (in milliseconds) allowed for each fetch attempt.
},
},
enabled: true,
debug: false,
},
async setup(config, nuxt) {
const { resolvePath } = createResolver(import.meta.url)
const { version, name } = await readPackageJSON(await resolvePath('../package.json'))
nuxt.options.alias['#nuxt-scripts-validator'] = await resolvePath(`./runtime/validation/${(nuxt.options.dev || nuxt.options._prepare) ? 'valibot' : 'mock'}`)
nuxt.options.alias['#nuxt-scripts'] = await resolvePath('./runtime')
logger.level = (config.debug || nuxt.options.debug) ? 4 : 3
if (!config.enabled) {
// TODO fallback to useHead?
logger.debug('The module is disabled, skipping setup.')
return
}
// couldn't be found for some reason, assume compatibility
const { version: unheadVersion } = await readPackageJSON('@unhead/vue', {
from: nuxt.options.modulesDir,
}).catch(() => ({ version: null }))
if (unheadVersion?.startsWith('1')) {
logger.error(`Nuxt Scripts requires Unhead >= 2, you are using v${unheadVersion}. Please run \`nuxi upgrade --clean\` to upgrade...`)
}
nuxt.options.runtimeConfig['nuxt-scripts'] = { version }
nuxt.options.runtimeConfig.public['nuxt-scripts'] = {
// expose for devtools
version: nuxt.options.dev ? version : undefined,
defaultScriptOptions: config.defaultScriptOptions,
}
const composables = [
'useScript',
'useScriptEventPage',
'useScriptTriggerConsent',
'useScriptTriggerElement',
]
for (const composable of composables) {
addImports({
priority: 2,
name: composable,
as: composable,
from: await resolvePath(`./runtime/composables/${composable}`),
})
}
addComponentsDir({
path: await resolvePath('./runtime/components'),
})
const scripts = await registry(resolvePath) as (RegistryScript & { _importRegistered?: boolean })[]
for (const script of scripts) {
if (script.import?.name) {
addImports({ priority: 2, ...script.import })
script._importRegistered = true
}
}
nuxt.hooks.hook('modules:done', async () => {
const registryScripts = [...scripts]
// @ts-expect-error nuxi prepare is broken to generate these types, possibly because of the runtime path
await nuxt.hooks.callHook('scripts:registry', registryScripts)
for (const script of registryScripts) {
if (script.import?.name && !script._importRegistered) {
addImports({ priority: 3, ...script.import })
}
}
// compare the registryScripts to the original registry to find new scripts
const registryScriptsWithImport = registryScripts.filter(i => !!i.import?.name) as Required<RegistryScript>[]
const newScripts = registryScriptsWithImport.filter(i => !scripts.some(r => r.import?.name === i.import.name))
// augment types to support the integrations registry
extendTypes(name!, async ({ typesPath }) => {
let types = `
declare module '#app' {
interface NuxtApp {
$scripts: Record<${[...Object.keys(config.globals || {}), ...Object.keys(config.registry || {})].map(k => `'${k}'`).concat(['string']).join(' | ')}, (import('#nuxt-scripts/types').UseScriptContext<any>)>
_scripts: Record<string, (import('#nuxt-scripts/types').UseScriptContext<any>)>
}
interface RuntimeNuxtHooks {
'scripts:updated': (ctx: { scripts: Record<string, (import('#nuxt-scripts/types').UseScriptContext<any>)> }) => void | Promise<void>
}
}
`
if (newScripts.length) {
types = `${types}
declare module '#nuxt-scripts/types' {
type NuxtUseScriptOptions = Omit<import('${typesPath}').NuxtUseScriptOptions, 'use' | 'beforeInit'>
interface ScriptRegistry {
${newScripts.map((i) => {
const key = i.import?.name.replace('useScript', '')
const keyLcFirst = key.substring(0, 1).toLowerCase() + key.substring(1)
return ` ${keyLcFirst}?: import('${i.import?.from}').${key}Input | [import('${i.import?.from}').${key}Input, NuxtUseScriptOptions]`
}).join('\n')}
}
}`
return types
}
return types
})
if (Object.keys(config.globals || {}).length || Object.keys(config.registry || {}).length) {
// create a virtual plugin
addPluginTemplate({
filename: `modules/${name!.replace('/', '-')}/plugin.mjs`,
getContents() {
return templatePlugin(config, registryScriptsWithImport)
},
})
}
const { renderedScript } = setupPublicAssetStrategy(config.assets)
const moduleInstallPromises: Map<string, () => Promise<boolean> | undefined> = new Map()
addBuildPlugin(NuxtScriptsCheckScripts(), {
dev: true,
})
addBuildPlugin(NuxtScriptBundleTransformer({
scripts: registryScriptsWithImport,
defaultBundle: config.defaultScriptOptions?.bundle,
moduleDetected(module) {
if (nuxt.options.dev && module !== '@nuxt/scripts' && !moduleInstallPromises.has(module) && !hasNuxtModule(module))
moduleInstallPromises.set(module, () => installNuxtModule(module))
},
assetsBaseURL: config.assets?.prefix,
fallbackOnSrcOnBundleFail: config.assets?.fallbackOnSrcOnBundleFail,
fetchOptions: config.assets?.fetchOptions,
renderedScript,
}))
nuxt.hooks.hook('build:done', async () => {
const initPromise = Array.from(moduleInstallPromises.values())
for (const p of initPromise)
await p?.()
})
})
if (nuxt.options.dev)
setupDevToolsUI(config, resolvePath)
},
})