/
provider.ts
96 lines (79 loc) · 2.53 KB
/
provider.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
import { normalize, resolve, dirname } from 'upath'
import { writeJson, mkdirp } from 'fs-extra'
import { parseURL } from 'ufo'
import { hash } from './utils'
import type { ModuleOptions, InputProvider, ImageModuleProvider, ProviderSetup } from './types'
import { ipxSetup } from './ipx'
const BuiltInProviders = [
'cloudinary',
'fastly',
'imagekit',
'imgix',
'ipx',
'prismic',
'sanity',
'static',
'twicpics',
'storyblok',
'vercel'
]
export const providerSetup: Record<string, ProviderSetup> = {
// IPX
ipx: ipxSetup,
static: ipxSetup,
// https://vercel.com/docs/more/adding-your-framework#images
async vercel (_providerOptions, moduleOptions, nuxt) {
const imagesConfig = resolve(nuxt.options.rootDir, '.vercel_build_output/config/images.json')
await mkdirp(dirname(imagesConfig))
await writeJson(imagesConfig, {
domains: moduleOptions.domains.map(domain => parseURL(domain, 'https://').host),
sizes: Array.from(new Set(Object.values(moduleOptions.screens || {})))
})
}
}
export function resolveProviders (nuxt: any, options: ModuleOptions): ImageModuleProvider[] {
const providers: ImageModuleProvider[] = []
for (const key in options) {
if (BuiltInProviders.includes(key)) {
providers.push(resolveProvider(nuxt, key, { provider: key, options: options[key] }))
}
}
for (const key in options.providers) {
providers.push(resolveProvider(nuxt, key, options.providers[key]))
}
return providers
}
export function resolveProvider (nuxt: any, key: string, input: InputProvider): ImageModuleProvider {
if (typeof input === 'string') {
input = { name: input }
}
if (!input.name) {
input.name = key
}
if (!input.provider) {
input.provider = input.name
}
input.provider = BuiltInProviders.includes(input.provider)
? require.resolve('./runtime/providers/' + input.provider)
: nuxt.resolver.resolvePath(input.provider)
const setup = input.setup || providerSetup[input.name]
return <ImageModuleProvider> {
...input,
setup,
runtime: normalize(input.provider!),
importName: `${key}Runtime$${hash(input.provider!, 4)}`,
runtimeOptions: input.options
}
}
export function detectProvider (userInput?: string, isStatic: boolean = false) {
if (process.env.NUXT_IMAGE_PROVIDER) {
return process.env.NUXT_IMAGE_PROVIDER
}
if (userInput && userInput !== 'auto') {
return userInput
}
if (process.env.VERCEL || process.env.VERCEL_ENV || process.env.NOW_BUILDER) {
return 'vercel'
}
return isStatic ? 'static' : 'ipx'
}