@sveltejs/adapter-netlify 7.0.0-next.10 → 7.0.0-next.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/files/edge.js CHANGED
@@ -1,7 +1,4 @@
1
- import { Server } from '0SERVER';
2
- import { manifest } from 'MANIFEST';
3
-
4
- const server = new Server(manifest);
1
+ import { server } from '0SERVER';
5
2
 
6
3
  /**
7
4
  * We don't know the origin until we receive a request, but
@@ -1,14 +1,11 @@
1
- import { Server } from '0SERVER';
2
1
  import { createReadableStream } from '@sveltejs/kit/node';
3
2
  import process from 'node:process';
4
3
 
5
4
  /**
6
- * @param {import('@sveltejs/kit').SSRManifest} manifest
5
+ * @param {import('@sveltejs/kit').Server} server
7
6
  * @returns {(request: Request, context: import('@netlify/types').Context) => Promise<Response>}
8
7
  */
9
- export function init(manifest) {
10
- const server = new Server(manifest);
11
-
8
+ export function init(server) {
12
9
  /** @type {Promise<void> | null} */
13
10
  let init_promise = server.init({
14
11
  env: process.env,
package/index.js CHANGED
@@ -1,9 +1,12 @@
1
+ /** @import { Builder, RouteDefinition } from '@sveltejs/kit' */
2
+ /** @import { TomlTable } from 'smol-toml' */
3
+ import crypto from 'node:crypto';
1
4
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
- import { join, posix } from 'node:path';
3
- import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
4
7
  import { builtinModules } from 'node:module';
5
8
  import process from 'node:process';
6
- import toml from '@iarna/toml';
9
+ import { parse } from 'smol-toml';
7
10
  import { build } from 'rolldown';
8
11
  import { matches, get_publish_directory, s } from './utils.js';
9
12
 
@@ -11,7 +14,7 @@ import { matches, get_publish_directory, s } from './utils.js';
11
14
  * @typedef {{
12
15
  * build?: { publish?: string }
13
16
  * functions?: { node_bundler?: 'zisi' | 'esbuild' }
14
- * } & toml.JsonMap} NetlifyConfig
17
+ * } & TomlTable} NetlifyConfig
15
18
  */
16
19
 
17
20
  const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf-8'));
@@ -84,11 +87,18 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
84
87
  builder.writeClient(publish_dir);
85
88
  builder.writePrerendered(publish_dir);
86
89
 
87
- // Copy user's custom _headers file if it exists
90
+ // Copy user's _headers file if it exists
88
91
  if (existsSync('_headers')) {
92
+ builder.log.minor('Copying user custom headers...');
89
93
  builder.copy('_headers', join(publish, '_headers'));
90
94
  }
91
95
 
96
+ // Copy user's _redirects file if it exists
97
+ if (existsSync('_redirects')) {
98
+ builder.log.minor('Copying user redirects...');
99
+ builder.copy('_redirects', join(publish, '_redirects'));
100
+ }
101
+
92
102
  builder.log.minor('Writing Netlify config...');
93
103
  write_frameworks_config({ builder });
94
104
 
@@ -99,7 +109,7 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
99
109
 
100
110
  await generate_edge_functions({ builder });
101
111
  } else {
102
- generate_serverless_functions({ builder, split, publish });
112
+ generate_serverless_functions(builder, split);
103
113
  }
104
114
  },
105
115
 
@@ -111,27 +121,23 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
111
121
  }
112
122
 
113
123
  /**
114
- * @param { object } params
115
- * @param {import('@sveltejs/kit').Builder} params.builder
116
- * @param { string } params.publish
117
- * @param { boolean } params.split
124
+ * @param {Builder} builder
125
+ * @param {boolean} split
118
126
  */
119
- function generate_serverless_functions({ builder, publish, split }) {
127
+ function generate_serverless_functions(builder, split) {
120
128
  // https://docs.netlify.com/build/frameworks/frameworks-api/#netlifyv1functions
121
129
  mkdirSync(netlify_framework_serverless_path, { recursive: true });
122
130
 
123
131
  builder.writeServer('.netlify/v1/server');
124
132
 
125
- const replace = {
126
- '0SERVER': './server/index.js' // digit prefix prevents CJS build from using this as a variable name, which would also get replaced
127
- };
128
-
129
- builder.copy(files, '.netlify/v1', { replace, filter: (file) => !file.endsWith('edge.js') });
133
+ builder.copy(`${files}/serverless.js`, '.netlify/v1/serverless.js');
130
134
 
131
135
  builder.log.minor('Generating serverless functions...');
132
136
 
133
137
  if (split) {
134
138
  const seen = new Set();
139
+ let index = 0;
140
+ const uuid = crypto.randomUUID();
135
141
 
136
142
  for (let i = 0; i < builder.routes.length; i++) {
137
143
  const route = builder.routes[i];
@@ -144,12 +150,13 @@ function generate_serverless_functions({ builder, publish, split }) {
144
150
 
145
151
  // The parts should conform to URLPattern syntax
146
152
  // https://docs.netlify.com/build/functions/get-started/?fn-language=ts&data-tab=TypeScript#route-requests
147
- for (const segment of route.segments) {
153
+ for (const [i, segment] of route.segments.entries()) {
148
154
  if (segment.rest) {
149
155
  parts.push('*');
150
156
  } else if (segment.dynamic) {
151
157
  // URLPattern requires params to start with letters
152
- parts.push(`:param${parts.length}`);
158
+ const optional = /^\[\[.+\]\]$/.test(segment.content) ? '?' : '';
159
+ parts.push(`:param${i}${optional}`);
153
160
  } else {
154
161
  parts.push(segment.content);
155
162
  }
@@ -157,14 +164,16 @@ function generate_serverless_functions({ builder, publish, split }) {
157
164
 
158
165
  // Netlify handles trailing slashes for us, so we don't need to include them in the pattern
159
166
  const pattern = `/${parts.join('/')}`;
160
- const name =
161
- FUNCTION_PREFIX + (parts.join('-').replace(/[:.]/g, '_').replace('*', '__rest') || 'index');
162
167
 
163
168
  // skip routes with identical patterns, they were already folded into another function
164
169
  if (seen.has(pattern)) continue;
165
170
 
171
+ // the route itself is human readable via the `name` config export,
172
+ // so the function file can just use an index
173
+ const name = `${FUNCTION_PREFIX}${index++}`;
174
+
166
175
  const patterns = [pattern, `${pattern === '/' ? '' : pattern}/__data.json`];
167
- patterns.forEach((p) => seen.add(p));
176
+ patterns.forEach((pattern) => seen.add(pattern));
168
177
 
169
178
  // figure out which lower priority routes should be considered fallbacks
170
179
  for (let j = i + 1; j < builder.routes.length; j += 1) {
@@ -176,38 +185,37 @@ function generate_serverless_functions({ builder, publish, split }) {
176
185
  }
177
186
  }
178
187
 
179
- generate_serverless_function({
188
+ generate_serverless_function(
180
189
  builder,
181
190
  routes,
182
191
  patterns,
183
192
  name,
184
- type: 'split'
185
- });
193
+ `SvelteKit ${route.id}`,
194
+ 'split',
195
+ undefined,
196
+ uuid
197
+ );
186
198
  }
187
199
 
188
- generate_serverless_function({
200
+ generate_serverless_function(
189
201
  builder,
190
- routes: [],
191
- patterns: ['/*'],
192
- name: `${FUNCTION_PREFIX}catch-all`,
193
- type: 'catch-all',
194
- exclude: Array.from(seen)
195
- });
202
+ [],
203
+ ['/*'],
204
+ `${FUNCTION_PREFIX}catch-all`,
205
+ 'SvelteKit catch-all',
206
+ 'catch-all',
207
+ Array.from(seen),
208
+ uuid
209
+ );
196
210
  } else {
197
- generate_serverless_function({
211
+ generate_serverless_function(
198
212
  builder,
199
- routes: undefined,
200
- patterns: ['/*'],
201
- name: `${FUNCTION_PREFIX}render`,
202
- type: 'singular'
203
- });
204
- }
205
-
206
- // Copy user's custom _redirects file if it exists
207
- if (existsSync('_redirects')) {
208
- builder.log.minor('Copying user redirects...');
209
- const redirects_file = join(publish, '_redirects');
210
- builder.copy('_redirects', redirects_file);
213
+ undefined,
214
+ ['/*'],
215
+ `${FUNCTION_PREFIX}render`,
216
+ 'SvelteKit server',
217
+ 'singular'
218
+ );
211
219
  }
212
220
  }
213
221
 
@@ -218,7 +226,7 @@ function get_netlify_config() {
218
226
  if (!existsSync('netlify.toml')) return null;
219
227
 
220
228
  try {
221
- return toml.parse(readFileSync('netlify.toml', 'utf-8'));
229
+ return parse(readFileSync('netlify.toml', 'utf-8'));
222
230
  } catch (err) {
223
231
  if (err instanceof Error) {
224
232
  throw new Error(`Failed to parse netlify.toml: ${err.message}`, { cause: err });
@@ -253,31 +261,44 @@ function write_frameworks_config({ builder }) {
253
261
  /** @typedef {'singular' | 'split' | 'catch-all'} ServerlessFunctionType */
254
262
 
255
263
  /**
256
- *
257
- * @param {{
258
- * builder: import('@sveltejs/kit').Builder,
259
- * routes: import('@sveltejs/kit').RouteDefinition[] | undefined,
260
- * patterns: string[],
261
- * name: string,
262
- * type: ServerlessFunctionType,
263
- * exclude?: string[]
264
- * }} opts
264
+ * @param {Builder} builder
265
+ * @param {RouteDefinition[] | undefined} routes
266
+ * @param {string[]} patterns
267
+ * @param {string} name
268
+ * @param {string} display_name
269
+ * @param {ServerlessFunctionType} type
270
+ * @param {string[]} [exclude]
271
+ * @param {string} [uuid]
265
272
  */
266
- function generate_serverless_function({ builder, routes, patterns, name, type, exclude }) {
267
- const manifest = builder.generateManifest({
268
- relativePath: '../server',
269
- routes
273
+ function generate_serverless_function(
274
+ builder,
275
+ routes,
276
+ patterns,
277
+ name,
278
+ display_name,
279
+ type,
280
+ exclude,
281
+ uuid
282
+ ) {
283
+ builder.generateServerInstance(`.netlify/v1/server-${name}.js`, {
284
+ routes,
285
+ serverDirectory: '.netlify/v1/server'
270
286
  });
271
287
 
272
- const fn = generate_serverless_function_module(manifest, type);
273
- const config = generate_config_export(name, patterns, exclude);
288
+ const fn = generate_serverless_function_module(name, type, uuid);
289
+ const config = generate_config_export(patterns, display_name, exclude);
274
290
 
275
291
  if (builder.hasServerInstrumentationFile()) {
276
292
  writeFileSync(`${netlify_framework_serverless_path}/${name}.mjs`, fn);
293
+ const initializer = builder.createInstrumentationInitializer({
294
+ outputDirectory: netlify_framework_serverless_path,
295
+ serverDirectory: '.netlify/v1/server'
296
+ });
277
297
  builder.instrument({
278
298
  entrypoint: `${netlify_framework_serverless_path}/${name}.mjs`,
279
299
  instrumentation: '.netlify/v1/server/instrumentation.server.js',
280
300
  start: `.netlify/v1/server/${name}.start.mjs`,
301
+ initializer,
281
302
  module: {
282
303
  generateText: generate_traced_module(config)
283
304
  }
@@ -288,29 +309,33 @@ function generate_serverless_function({ builder, routes, patterns, name, type, e
288
309
  }
289
310
 
290
311
  /**
291
- * @param {string} manifest
312
+ * @param {string} name
292
313
  * @param {ServerlessFunctionType} type
314
+ * @param {string} [uuid]
293
315
  * @returns {string}
294
316
  */
295
- function generate_serverless_function_module(manifest, type) {
296
- if (type === 'catch-all') {
317
+ function generate_serverless_function_module(name, type, uuid) {
318
+ const original_pathname_header = `const original_pathname_header = \`x-sveltekit-original-pathname-${uuid}\``;
319
+
320
+ if (type === 'catch-all' && uuid) {
297
321
  // Netlify encodes the response body but `fetch` automatically decodes it.
298
322
  // So, we need to remove the `content-encoding` header to allow Netlify
299
323
  // to correctly re-encode it on the way out.
300
324
  return `\
301
325
  import { applyReroute } from '@sveltejs/kit/adapter';
302
326
  import { init } from '../serverless.js';
327
+ import { server } from '../server-${name}.js';
303
328
 
304
- const original_url_header = \`x-sveltekit-original-url-\${process.env.NETLIFY_FUNCTIONS_TOKEN}\`
329
+ ${original_pathname_header}
305
330
 
306
- const respond = init(${manifest});
331
+ const respond = init(server);
307
332
 
308
333
  export default async (request, context) => {
309
334
  const catch_all_response = await respond(request, context);
310
335
 
311
336
  return await applyReroute(catch_all_response, async (url) => {
312
337
  const rerouted_request = new Request(url, request);
313
- rerouted_request.headers.set(original_url_header, request.url);
338
+ rerouted_request.headers.set(original_pathname_header, new URL(request.url).pathname);
314
339
 
315
340
  const rerouted_response = await fetch(rerouted_request);
316
341
 
@@ -326,19 +351,21 @@ export default async (request, context) => {
326
351
  `;
327
352
  }
328
353
 
329
- if (type === 'split') {
354
+ if (type === 'split' && uuid) {
330
355
  return `\
331
356
  import { init } from '../serverless.js';
357
+ import { server } from '../server-${name}.js';
332
358
 
333
- const original_url_header = \`x-sveltekit-original-url-\${process.env.NETLIFY_FUNCTIONS_TOKEN}\`
359
+ ${original_pathname_header}
334
360
 
335
- const respond = init(${manifest});
361
+ const respond = init(server);
336
362
 
337
363
  export default async (request, context) => {
338
- if (request.headers.has(original_url_header)) {
339
- const original_url = request.headers.get(original_url_header);
340
- request = new Request(original_url, request);
341
- request.headers.delete(original_url_header);
364
+ if (request.headers.has(original_pathname_header)) {
365
+ const url = new URL(request.url);
366
+ url.pathname = request.headers.get(original_pathname_header);
367
+ request = new Request(url, request);
368
+ request.headers.delete(original_pathname_header);
342
369
  }
343
370
 
344
371
  return await respond(request, context);
@@ -348,26 +375,25 @@ export default async (request, context) => {
348
375
 
349
376
  return `\
350
377
  import { init } from '../serverless.js';
378
+ import { server } from '../server-${name}.js';
351
379
 
352
- export default init(${manifest});
380
+ export default init(server);
353
381
  `;
354
382
  }
355
383
 
356
384
  const generator_string = `@sveltejs/adapter-netlify@${adapter_version}`;
357
385
 
358
386
  /**
359
- * @param {string} name The name that shows up in the logs & metrics functions list
360
387
  * @param {string[]} patterns
388
+ * @param {string} display_name The name that shows up in the logs & metrics functions list
361
389
  * @param {string[]} [exclude]
362
390
  * @returns {string}
363
391
  */
364
- function generate_config_export(name, patterns, exclude = []) {
365
- // TODO: add a human friendly name for the function https://docs.netlify.com/build/frameworks/frameworks-api/#configuration-options-2
366
-
392
+ function generate_config_export(patterns, display_name, exclude = []) {
367
393
  // https://docs.netlify.com/build/frameworks/frameworks-api/#configuration-options-2
368
394
  return `\
369
395
  export const config = {
370
- name: ${JSON.stringify(name)},
396
+ name: ${JSON.stringify(display_name)},
371
397
  generator: '${generator_string}',
372
398
  path: [${patterns.map(s).join(', ')}],
373
399
  excludedPath: [${['/.netlify/*', ...exclude].map(s).join(', ')}],
@@ -378,19 +404,25 @@ export const config = {
378
404
 
379
405
  /**
380
406
  * @param {string} config
381
- * @returns {(opts: { instrumentation: string; start: string }) => string}
407
+ * @returns {(opts: { instrumentation: string; start: string; initializer: string }) => string}
382
408
  */
383
409
  function generate_traced_module(config) {
384
- return ({ instrumentation, start }) => {
410
+ return ({ instrumentation, start, initializer }) => {
385
411
  return `\
386
- import '../server/${instrumentation}';
387
- const { default: _0 } = await import('../server/${start}');
412
+ import ${JSON.stringify(to_import_specifier(initializer))};
413
+ import ${JSON.stringify(to_import_specifier(instrumentation))};
414
+ const { default: _0 } = await import(${JSON.stringify(to_import_specifier(start))});
388
415
  export { _0 as default };
389
416
 
390
417
  ${config}`;
391
418
  };
392
419
  }
393
420
 
421
+ /** @param {string} path */
422
+ function to_import_specifier(path) {
423
+ return path.startsWith('.') ? path : `./${path}`;
424
+ }
425
+
394
426
  /** @satisfies {import('rolldown').BuildOptions} */
395
427
  const rolldown_config = {
396
428
  platform: 'browser',
@@ -422,23 +454,14 @@ async function generate_edge_functions({ builder }) {
422
454
  mkdirSync('.netlify/v1/edge-functions', { recursive: true });
423
455
 
424
456
  builder.log.minor('Generating Edge Function...');
425
- const relativePath = posix.relative(tmp, builder.getServerDirectory());
426
457
 
427
458
  builder.copy(`${files}/edge.js`, `${tmp}/entry.js`, {
428
459
  replace: {
429
- '0SERVER': `${relativePath}/index.js`,
430
- MANIFEST: './manifest.js'
460
+ '0SERVER': `./server.js`
431
461
  }
432
462
  });
433
463
 
434
- const manifest = builder.generateManifest({
435
- relativePath
436
- });
437
-
438
- writeFileSync(`${tmp}/manifest.js`, `export const manifest = ${manifest};\n`);
439
-
440
- /** @type {{ assets: Set<string> }} */
441
- const { assets } = (await import(pathToFileURL(`${tmp}/manifest.js`).href)).manifest;
464
+ builder.generateServerInstance(`${tmp}/server.js`);
442
465
 
443
466
  const path = '/*';
444
467
  // We only need to specify paths without the trailing slash because
@@ -449,7 +472,7 @@ async function generate_edge_functions({ builder }) {
449
472
  `/${builder.getAppPath()}/version.json`,
450
473
  // the base root and `trailingSlash: 'always'` pages are recorded with a trailing slash
451
474
  ...builder.prerendered.paths.map((path) => (path === '/' ? path : path.replace(/\/$/, ''))),
452
- ...Array.from(assets).flatMap((asset) => {
475
+ ...Array.from(builder.manifest.assets).flatMap(({ path: asset }) => {
453
476
  if (asset.endsWith('/index.html')) {
454
477
  const dir = asset.replace(/\/index\.html$/, '');
455
478
  return [`${builder.config.paths.base}/${asset}`, `${builder.config.paths.base}/${dir}`];
@@ -460,34 +483,30 @@ async function generate_edge_functions({ builder }) {
460
483
  '/.netlify/*'
461
484
  ];
462
485
 
463
- await Promise.all([
464
- build({
465
- ...rolldown_config,
466
- input: `${tmp}/entry.js`,
467
- output: {
468
- ...rolldown_config.output,
469
- file: `${netlify_framework_edge_path}/${FUNCTION_PREFIX}render.js`
470
- }
471
- }),
472
- builder.hasServerInstrumentationFile() &&
473
- build({
474
- ...rolldown_config,
475
- input: `${builder.getServerDirectory()}/instrumentation.server.js`,
476
- output: {
477
- ...rolldown_config.output,
478
- file: `${netlify_framework_edge_path}/${FUNCTION_PREFIX}instrumentation.server.js`
479
- }
480
- })
481
- ]);
482
-
483
486
  if (builder.hasServerInstrumentationFile()) {
487
+ const initializer = builder.createInstrumentationInitializer({
488
+ outputDirectory: tmp,
489
+ environment: 'export default Deno.env.toObject();\n'
490
+ });
491
+ writeFileSync(`${tmp}/instrumented-entry.js`, `export { default } from './entry.js';\n`);
484
492
  builder.instrument({
485
- entrypoint: `${netlify_framework_edge_path}/${FUNCTION_PREFIX}render.js`,
486
- instrumentation: `${netlify_framework_edge_path}/${FUNCTION_PREFIX}instrumentation.server.js`,
487
- start: `${netlify_framework_edge_path}/${FUNCTION_PREFIX}start.js`
493
+ entrypoint: `${tmp}/instrumented-entry.js`,
494
+ instrumentation: `${builder.getServerDirectory()}/instrumentation.server.js`,
495
+ initializer
488
496
  });
489
497
  }
490
498
 
499
+ await build({
500
+ ...rolldown_config,
501
+ input: builder.hasServerInstrumentationFile()
502
+ ? `${tmp}/instrumented-entry.js`
503
+ : `${tmp}/entry.js`,
504
+ output: {
505
+ ...rolldown_config.output,
506
+ file: `${netlify_framework_edge_path}/${FUNCTION_PREFIX}render.js`
507
+ }
508
+ });
509
+
491
510
  add_edge_function_config({ builder, path, excluded_paths });
492
511
  }
493
512
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sveltejs/adapter-netlify",
3
- "version": "7.0.0-next.10",
3
+ "version": "7.0.0-next.11",
4
4
  "description": "A SvelteKit adapter that creates a Netlify app",
5
5
  "keywords": [
6
6
  "adapter",
@@ -34,27 +34,27 @@
34
34
  "ambient.d.ts"
35
35
  ],
36
36
  "dependencies": {
37
- "@iarna/toml": "^2.2.5",
38
37
  "@netlify/types": "^2.8.0",
39
- "rolldown": "^1.2.3"
38
+ "rolldown": "^1.2.3",
39
+ "smol-toml": "^1.8.0"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@netlify/edge-functions": "^3.0.8",
43
+ "@sveltejs/kit": "^3.0.0-next.27",
43
44
  "@types/deno": "^2.7.0",
44
45
  "@types/node": "^22.19.19",
45
46
  "typescript": "^7.0.2",
46
- "vitest": "^4.1.10",
47
- "@sveltejs/kit": "^3.0.0-next.25"
47
+ "vitest": "^4.1.10"
48
48
  },
49
49
  "peerDependencies": {
50
- "@sveltejs/kit": "^2.31.0"
50
+ "@sveltejs/kit": "^3.0.0-next.0"
51
51
  },
52
52
  "scripts": {
53
53
  "check": "tsc && tsc --project files/tsconfig.json",
54
54
  "lint": "oxfmt --check .",
55
55
  "format": "oxfmt --write .",
56
56
  "test:unit": "vitest run",
57
- "test:build": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" build",
57
+ "test:build": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:build",
58
58
  "test": "pnpm test:unit && pnpm test:build"
59
59
  }
60
60
  }