-
-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathindex.ts
More file actions
256 lines (216 loc) · 8.02 KB
/
index.ts
File metadata and controls
256 lines (216 loc) · 8.02 KB
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
import { defineAddon, defineAddonOptions } from '../../core/index.ts';
import { exports, functions, imports, object, type AstTypes } from '../../core/tooling/js/index.ts';
import { parseJson, parseScript, parseToml } from '../../core/tooling/parsers.ts';
import { fileExists, readFile } from '../../cli/add/utils.ts';
import { sanitizeName } from '../../core/sanitize.ts';
import { resolveCommand } from 'package-manager-detector';
import * as js from '../../core/tooling/js/index.ts';
const adapters = [
{ id: 'auto', package: '@sveltejs/adapter-auto', version: '^7.0.0' },
{ id: 'node', package: '@sveltejs/adapter-node', version: '^5.4.0' },
{ id: 'static', package: '@sveltejs/adapter-static', version: '^3.0.10' },
{ id: 'vercel', package: '@sveltejs/adapter-vercel', version: '^6.2.0' },
{ id: 'cloudflare', package: '@sveltejs/adapter-cloudflare', version: '^7.2.4' },
{ id: 'netlify', package: '@sveltejs/adapter-netlify', version: '^5.2.4' }
] as const;
const options = defineAddonOptions()
.add('adapter', {
type: 'select',
question: 'Which SvelteKit adapter would you like to use?',
default: 'auto',
options: adapters.map((p) => ({ value: p.id, label: p.id, hint: p.package }))
})
.add('cfTarget', {
condition: (options) => options.adapter === 'cloudflare',
type: 'select',
question: 'Are you deploying to Workers (assets) or Pages?',
default: 'workers',
options: [
{ value: 'workers', label: 'Workers', hint: 'Recommended way to deploy to Cloudflare' },
{ value: 'pages', label: 'Pages' }
]
})
.build();
export default defineAddon({
id: 'sveltekit-adapter',
alias: 'adapter',
shortDescription: 'deployment',
homepage: 'https://svelte.dev/docs/kit/adapters',
options,
setup: ({ kit, unsupported }) => {
if (!kit) unsupported('Requires SvelteKit');
},
run: ({ sv, options, files, cwd, packageManager, language }) => {
const adapter = adapters.find((a) => a.id === options.adapter)!;
// removes previously installed adapters
sv.file(files.package, (content) => {
const { data, generateCode } = parseJson(content);
const devDeps = data['devDependencies'];
for (const pkg of Object.keys(devDeps)) {
if (pkg.startsWith('@sveltejs/adapter-')) {
delete devDeps[pkg];
}
}
// in sk 3, we will keep "preview": "vite preview" like any other adapter
if (options.adapter === 'cloudflare') {
if (options.cfTarget === 'workers') {
data.scripts.preview = 'wrangler dev .svelte-kit/cloudflare/_worker.js --port 4173';
} else if (options.cfTarget === 'pages') {
data.scripts.preview = 'wrangler pages dev .svelte-kit/cloudflare --port 4173';
}
}
return generateCode();
});
sv.devDependency(adapter.package, adapter.version);
sv.file(files.svelteConfig, (content) => {
const { ast, comments, generateCode } = parseScript(content);
// finds any existing adapter's import declaration
const importDecls = ast.body.filter((n) => n.type === 'ImportDeclaration');
const adapterImportDecl = importDecls.find(
(importDecl) =>
typeof importDecl.source.value === 'string' &&
importDecl.source.value.startsWith('@sveltejs/adapter-') &&
importDecl.importKind === 'value'
);
let adapterName = 'adapter';
if (adapterImportDecl) {
// replaces the import's source with the new adapter
adapterImportDecl.source.value = adapter.package;
// reset raw value, so that the string is re-generated
adapterImportDecl.source.raw = undefined;
adapterName = adapterImportDecl.specifiers?.find((s) => s.type === 'ImportDefaultSpecifier')
?.local?.name as string;
} else {
imports.addDefault(ast, { from: adapter.package, as: adapterName });
}
const { value: config } = exports.createDefault(ast, { fallback: object.create({}) });
// override the adapter property
object.overrideProperties(config, {
kit: {
adapter: functions.createCall({ name: adapterName, args: [], useIdentifiers: true })
}
});
// reset the comment for non-auto adapters
if (adapter.package !== '@sveltejs/adapter-auto') {
const fallback = object.create({});
const cfgKitValue = object.property(config, { name: 'kit', fallback });
// removes any existing adapter auto comments
comments.remove(
(c) =>
c.loc &&
cfgKitValue.loc &&
c.loc.start.line >= cfgKitValue.loc.start.line &&
c.loc.end.line <= cfgKitValue.loc.end.line
);
}
return generateCode();
});
if (adapter.package === '@sveltejs/adapter-cloudflare') {
sv.devDependency('wrangler', '^4.56.0');
// default to jsonc
const configFormat = fileExists(cwd, 'wrangler.toml') ? 'toml' : 'jsonc';
// Setup Cloudlfare workers/pages config
sv.file(`wrangler.${configFormat}`, (content) => {
const { data, generateCode } =
configFormat === 'jsonc' ? parseJson(content) : parseToml(content);
if (configFormat === 'jsonc') {
data.$schema ??= './node_modules/wrangler/config-schema.json';
}
if (!data.name) {
const pkg = parseJson(readFile(cwd, files.package));
data.name = sanitizeName(pkg.data.name, 'wrangler');
}
data.compatibility_date ??= new Date().toISOString().split('T')[0];
data.compatibility_flags ??= [];
if (
!data.compatibility_flags.includes('nodejs_compat') &&
!data.compatibility_flags.includes('nodejs_als')
) {
data.compatibility_flags.push('nodejs_als');
}
switch (options.cfTarget) {
case 'workers':
data.main = '.svelte-kit/cloudflare/_worker.js';
data.assets ??= {};
data.assets.binding = 'ASSETS';
data.assets.directory = '.svelte-kit/cloudflare';
data.workers_dev = true;
data.preview_urls = true;
break;
case 'pages':
data.pages_build_output_dir = '.svelte-kit/cloudflare';
break;
}
return generateCode();
});
const jsconfig = fileExists(cwd, 'jsconfig.json');
const typeChecked = language === 'ts' || jsconfig;
if (typeChecked) {
// Ignore generated Cloudflare Types
sv.file(files.gitignore, (content) => {
return content.includes('.wrangler') && content.includes('worker-configuration.d.ts')
? content
: `${content.trimEnd()}\n\n# Cloudflare Types\n/worker-configuration.d.ts`;
});
// Setup wrangler types command
sv.file(files.package, (content) => {
const { data, generateCode } = parseJson(content);
data.scripts ??= {};
data.scripts.types = 'wrangler types';
const { command, args } = resolveCommand(packageManager, 'run', ['types'])!;
data.scripts.prepare = data.scripts.prepare
? `${command} ${args.join(' ')} && ${data.scripts.prepare}`
: `${command} ${args.join(' ')}`;
return generateCode();
});
// Add Cloudflare generated types to tsconfig
sv.file(`${jsconfig ? 'jsconfig' : 'tsconfig'}.json`, (content) => {
const { data, generateCode } = parseJson(content);
data.compilerOptions ??= {};
data.compilerOptions.types ??= [];
data.compilerOptions.types.push('./worker-configuration.d.ts');
return generateCode();
});
sv.file('src/app.d.ts', (content) => {
const { ast, generateCode } = parseScript(content);
const platform = js.kit.addGlobalAppInterface(ast, { name: 'Platform' });
if (!platform) {
throw new Error('Failed detecting `platform` interface in `src/app.d.ts`');
}
platform.body.body.push(
createCloudflarePlatformType('env', 'Env'),
createCloudflarePlatformType('ctx', 'ExecutionContext'),
createCloudflarePlatformType('caches', 'CacheStorage'),
createCloudflarePlatformType('cf', 'IncomingRequestCfProperties', true)
);
return generateCode();
});
}
}
}
});
function createCloudflarePlatformType(
name: string,
value: string,
optional = false
): AstTypes.TSInterfaceBody['body'][number] {
return {
type: 'TSPropertySignature',
key: {
type: 'Identifier',
name
},
computed: false,
optional,
typeAnnotation: {
type: 'TSTypeAnnotation',
typeAnnotation: {
type: 'TSTypeReference',
typeName: {
type: 'Identifier',
name: value
}
}
}
};
}