@sveltejs/adapter-netlify 1.0.0-next.8 → 1.0.0-next.80

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/README.md CHANGED
@@ -1,18 +1,87 @@
1
1
  # adapter-netlify
2
2
 
3
- Adapter for Svelte apps that creates a Netlify app, using a function for dynamic server rendering. A future version might use a function per route, though it's unclear if that has any real advantages.
3
+ A SvelteKit adapter that creates a Netlify app.
4
4
 
5
- This is very experimental; the adapter API isn't at all fleshed out, and things will definitely change.
5
+ If you're using [adapter-auto](../adapter-auto), you don't need to install this unless you need to specify Netlify-specific options, since it's already included.
6
6
 
7
- ## Configuration
7
+ ## Installation
8
8
 
9
- This adapter expects to find a [netlify.toml](https://docs.netlify.com/configure-builds/file-based-configuration) file in the project root. It will determine where to write static assets and functions to based on the `build.publish` and `build.functions` settings, as per this sample configuration:
9
+ ```bash
10
+ npm i -D @sveltejs/adapter-netlify
11
+ ```
12
+
13
+ You can then configure it inside of `svelte.config.js`:
14
+
15
+ ```js
16
+ import adapter from '@sveltejs/adapter-netlify';
17
+
18
+ export default {
19
+ kit: {
20
+ // default options are shown
21
+ adapter: adapter({
22
+ // if true, will create a Netlify Edge Function rather
23
+ // than using standard Node-based functions
24
+ edge: false,
25
+
26
+ // if true, will split your app into multiple functions
27
+ // instead of creating a single one for the entire app.
28
+ // if `edge` is true, this option cannot be used
29
+ split: false
30
+ })
31
+ }
32
+ };
33
+ ```
34
+
35
+ Then, make sure you have a [netlify.toml](https://docs.netlify.com/configure-builds/file-based-configuration) file in the project root. This will determine where to write static assets based on the `build.publish` settings, as per this sample configuration:
10
36
 
11
37
  ```toml
12
38
  [build]
13
39
  command = "npm run build"
14
- publish = "build/"
15
- functions = "functions/"
40
+ publish = "build"
16
41
  ```
17
42
 
18
- It's recommended that you add the `build` and `functions` folders (or whichever other folders you specify) to your `.gitignore`.
43
+ If the `netlify.toml` file or the `build.publish` value is missing, a default value of `"build"` will be used. Note that if you have set the publish directory in the Netlify UI to something else then you will need to set it in `netlify.toml` too, or use the default value of `"build"`.
44
+
45
+ ### Node version
46
+
47
+ New projects will use Node 16 by default. However, if you're upgrading a project you created a while ago it may be stuck on an older version. See [the Netlify docs](https://docs.netlify.com/configure-builds/manage-dependencies/#node-js-and-javascript) for details on manually specifying Node 16 or newer.
48
+
49
+ ## Netlify Edge Functions (beta)
50
+
51
+ SvelteKit supports the beta release of [Netlify Edge Functions](https://docs.netlify.com/netlify-labs/experimental-features/edge-functions/). If you pass the option `edge: true` to the `adapter` function, server-side rendering will happen in a Deno-based edge function that's deployed close to the site visitor. If set to `false` (the default), the site will deploy to standard Node-based Netlify Functions.
52
+
53
+ ## Netlify alternatives to SvelteKit functionality
54
+
55
+ You may build your app using functionality provided directly by SvelteKit without relying on any Netlify functionality. Using the SvelteKit versions of these features will allow them to be used in dev mode, tested with integration tests, and to work with other adapters should you ever decide to switch away from Netlify. However, in some scenarios you may find it beneficial to use the Netlify versions of these features. One example would be if you're migrating an app that's already hosted on Netlify to SvelteKit.
56
+
57
+ ### Using Netlify Redirect Rules
58
+
59
+ During compilation, redirect rules are automatically appended to your `_redirects` file. (If it doesn't exist yet, it will be created.) That means:
60
+
61
+ - `[[redirects]]` in `netlify.toml` will never match as `_redirects` has a [higher priority](https://docs.netlify.com/routing/redirects/#rule-processing-order). So always put your rules in the [`_redirects` file](https://docs.netlify.com/routing/redirects/#syntax-for-the-redirects-file).
62
+ - `_redirects` shouldn't have any custom "catch all" rules such as `/* /foobar/:splat`. Otherwise the automatically appended rule will never be applied as Netlify is only processing [the first matching rule](https://docs.netlify.com/routing/redirects/#rule-processing-order).
63
+
64
+ ### Using Netlify Forms
65
+
66
+ 1. Create your Netlify HTML form as described [here](https://docs.netlify.com/forms/setup/#html-forms), e.g. as `/routes/contact.svelte`. (Don't forget to add the hidden `form-name` input element!)
67
+ 2. Netlify's build bot parses your HTML files at deploy time, which means your form must be [prerendered](https://kit.svelte.dev/docs/page-options#prerender) as HTML. You can either add `export const prerender = true` to your `contact.svelte` to prerender just that page or set the `kit.prerender.force: true` option to prerender all pages.
68
+ 3. If your Netlify form has a [custom success message](https://docs.netlify.com/forms/setup/#success-messages) like `<form netlify ... action="/success">` then ensure the corresponding `/routes/success.svelte` exists and is prerendered.
69
+
70
+ ### Using Netlify Functions
71
+
72
+ With this adapter, SvelteKit endpoints are hosted as [Netlify Functions](https://docs.netlify.com/functions/overview/). Netlify function handlers have additional context, including [Netlify Identity](https://docs.netlify.com/visitor-access/identity/) information. You can access this context via the `event.platform.context` field inside your hooks and endpoints.
73
+
74
+ Additionally, you can add your own Netlify functions by creating a directory for them and adding the configuration to your `netlify.toml` file. For example:
75
+
76
+ ```toml
77
+ [build]
78
+ command = "npm run build"
79
+ publish = "build"
80
+
81
+ [functions]
82
+ directory = "functions"
83
+ ```
84
+
85
+ ## Changelog
86
+
87
+ [The Changelog for this package is available on GitHub](https://github.com/sveltejs/kit/blob/master/packages/adapter-netlify/CHANGELOG.md).
@@ -0,0 +1,345 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ require('./shims.js');
6
+ var _0SERVER = require('0SERVER');
7
+ require('assert');
8
+ require('net');
9
+ require('http');
10
+ require('stream');
11
+ require('buffer');
12
+ require('util');
13
+ require('querystring');
14
+ require('stream/web');
15
+ require('perf_hooks');
16
+ require('util/types');
17
+ require('events');
18
+ require('tls');
19
+ require('async_hooks');
20
+ require('console');
21
+ require('url');
22
+ require('zlib');
23
+ require('crypto');
24
+
25
+ var setCookie = {exports: {}};
26
+
27
+ var defaultParseOptions = {
28
+ decodeValues: true,
29
+ map: false,
30
+ silent: false,
31
+ };
32
+
33
+ function isNonEmptyString(str) {
34
+ return typeof str === "string" && !!str.trim();
35
+ }
36
+
37
+ function parseString(setCookieValue, options) {
38
+ var parts = setCookieValue.split(";").filter(isNonEmptyString);
39
+ var nameValue = parts.shift().split("=");
40
+ var name = nameValue.shift();
41
+ var value = nameValue.join("="); // everything after the first =, joined by a "=" if there was more than one part
42
+
43
+ options = options
44
+ ? Object.assign({}, defaultParseOptions, options)
45
+ : defaultParseOptions;
46
+
47
+ try {
48
+ value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
49
+ } catch (e) {
50
+ console.error(
51
+ "set-cookie-parser encountered an error while decoding a cookie with value '" +
52
+ value +
53
+ "'. Set options.decodeValues to false to disable this feature.",
54
+ e
55
+ );
56
+ }
57
+
58
+ var cookie = {
59
+ name: name, // grab everything before the first =
60
+ value: value,
61
+ };
62
+
63
+ parts.forEach(function (part) {
64
+ var sides = part.split("=");
65
+ var key = sides.shift().trimLeft().toLowerCase();
66
+ var value = sides.join("=");
67
+ if (key === "expires") {
68
+ cookie.expires = new Date(value);
69
+ } else if (key === "max-age") {
70
+ cookie.maxAge = parseInt(value, 10);
71
+ } else if (key === "secure") {
72
+ cookie.secure = true;
73
+ } else if (key === "httponly") {
74
+ cookie.httpOnly = true;
75
+ } else if (key === "samesite") {
76
+ cookie.sameSite = value;
77
+ } else {
78
+ cookie[key] = value;
79
+ }
80
+ });
81
+
82
+ return cookie;
83
+ }
84
+
85
+ function parse(input, options) {
86
+ options = options
87
+ ? Object.assign({}, defaultParseOptions, options)
88
+ : defaultParseOptions;
89
+
90
+ if (!input) {
91
+ if (!options.map) {
92
+ return [];
93
+ } else {
94
+ return {};
95
+ }
96
+ }
97
+
98
+ if (input.headers && input.headers["set-cookie"]) {
99
+ // fast-path for node.js (which automatically normalizes header names to lower-case
100
+ input = input.headers["set-cookie"];
101
+ } else if (input.headers) {
102
+ // slow-path for other environments - see #25
103
+ var sch =
104
+ input.headers[
105
+ Object.keys(input.headers).find(function (key) {
106
+ return key.toLowerCase() === "set-cookie";
107
+ })
108
+ ];
109
+ // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
110
+ if (!sch && input.headers.cookie && !options.silent) {
111
+ console.warn(
112
+ "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
113
+ );
114
+ }
115
+ input = sch;
116
+ }
117
+ if (!Array.isArray(input)) {
118
+ input = [input];
119
+ }
120
+
121
+ options = options
122
+ ? Object.assign({}, defaultParseOptions, options)
123
+ : defaultParseOptions;
124
+
125
+ if (!options.map) {
126
+ return input.filter(isNonEmptyString).map(function (str) {
127
+ return parseString(str, options);
128
+ });
129
+ } else {
130
+ var cookies = {};
131
+ return input.filter(isNonEmptyString).reduce(function (cookies, str) {
132
+ var cookie = parseString(str, options);
133
+ cookies[cookie.name] = cookie;
134
+ return cookies;
135
+ }, cookies);
136
+ }
137
+ }
138
+
139
+ /*
140
+ Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
141
+ that are within a single set-cookie field-value, such as in the Expires portion.
142
+
143
+ This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
144
+ Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
145
+ React Native's fetch does this for *every* header, including set-cookie.
146
+
147
+ Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
148
+ Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
149
+ */
150
+ function splitCookiesString(cookiesString) {
151
+ if (Array.isArray(cookiesString)) {
152
+ return cookiesString;
153
+ }
154
+ if (typeof cookiesString !== "string") {
155
+ return [];
156
+ }
157
+
158
+ var cookiesStrings = [];
159
+ var pos = 0;
160
+ var start;
161
+ var ch;
162
+ var lastComma;
163
+ var nextStart;
164
+ var cookiesSeparatorFound;
165
+
166
+ function skipWhitespace() {
167
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
168
+ pos += 1;
169
+ }
170
+ return pos < cookiesString.length;
171
+ }
172
+
173
+ function notSpecialChar() {
174
+ ch = cookiesString.charAt(pos);
175
+
176
+ return ch !== "=" && ch !== ";" && ch !== ",";
177
+ }
178
+
179
+ while (pos < cookiesString.length) {
180
+ start = pos;
181
+ cookiesSeparatorFound = false;
182
+
183
+ while (skipWhitespace()) {
184
+ ch = cookiesString.charAt(pos);
185
+ if (ch === ",") {
186
+ // ',' is a cookie separator if we have later first '=', not ';' or ','
187
+ lastComma = pos;
188
+ pos += 1;
189
+
190
+ skipWhitespace();
191
+ nextStart = pos;
192
+
193
+ while (pos < cookiesString.length && notSpecialChar()) {
194
+ pos += 1;
195
+ }
196
+
197
+ // currently special character
198
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
199
+ // we found cookies separator
200
+ cookiesSeparatorFound = true;
201
+ // pos is inside the next cookie, so back up and return it.
202
+ pos = nextStart;
203
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
204
+ start = pos;
205
+ } else {
206
+ // in param ',' or param separator ';',
207
+ // we continue from that comma
208
+ pos = lastComma + 1;
209
+ }
210
+ } else {
211
+ pos += 1;
212
+ }
213
+ }
214
+
215
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
216
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
217
+ }
218
+ }
219
+
220
+ return cookiesStrings;
221
+ }
222
+
223
+ setCookie.exports = parse;
224
+ setCookie.exports.parse = parse;
225
+ setCookie.exports.parseString = parseString;
226
+ var splitCookiesString_1 = setCookie.exports.splitCookiesString = splitCookiesString;
227
+
228
+ /**
229
+ * Splits headers into two categories: single value and multi value
230
+ * @param {Headers} headers
231
+ * @returns {{
232
+ * headers: Record<string, string>,
233
+ * multiValueHeaders: Record<string, string[]>
234
+ * }}
235
+ */
236
+ function split_headers(headers) {
237
+ /** @type {Record<string, string>} */
238
+ const h = {};
239
+
240
+ /** @type {Record<string, string[]>} */
241
+ const m = {};
242
+
243
+ headers.forEach((value, key) => {
244
+ if (key === 'set-cookie') {
245
+ m[key] = splitCookiesString_1(value);
246
+ } else {
247
+ h[key] = value;
248
+ }
249
+ });
250
+
251
+ return {
252
+ headers: h,
253
+ multiValueHeaders: m
254
+ };
255
+ }
256
+
257
+ /**
258
+ * @param {import('@sveltejs/kit').SSRManifest} manifest
259
+ * @returns {import('@netlify/functions').Handler}
260
+ */
261
+ function init(manifest) {
262
+ const server = new _0SERVER.Server(manifest);
263
+
264
+ let init_promise = server.init({
265
+ env: process.env
266
+ });
267
+
268
+ return async (event, context) => {
269
+ if (init_promise !== null) {
270
+ await init_promise;
271
+ init_promise = null;
272
+ }
273
+
274
+ const response = await server.respond(to_request(event), {
275
+ platform: { context },
276
+ getClientAddress() {
277
+ return event.headers['x-nf-client-connection-ip'];
278
+ }
279
+ });
280
+
281
+ const partial_response = {
282
+ statusCode: response.status,
283
+ ...split_headers(response.headers)
284
+ };
285
+
286
+ if (!is_text(response.headers.get('content-type'))) {
287
+ // Function responses should be strings (or undefined), and responses with binary
288
+ // content should be base64 encoded and set isBase64Encoded to true.
289
+ // https://github.com/netlify/functions/blob/main/src/function/response.ts
290
+ return {
291
+ ...partial_response,
292
+ isBase64Encoded: true,
293
+ body: Buffer.from(await response.arrayBuffer()).toString('base64')
294
+ };
295
+ }
296
+
297
+ return {
298
+ ...partial_response,
299
+ body: await response.text()
300
+ };
301
+ };
302
+ }
303
+
304
+ /**
305
+ * @param {import('@netlify/functions').HandlerEvent} event
306
+ * @returns {Request}
307
+ */
308
+ function to_request(event) {
309
+ const { httpMethod, headers, rawUrl, body, isBase64Encoded } = event;
310
+
311
+ /** @type {RequestInit} */
312
+ const init = {
313
+ method: httpMethod,
314
+ headers: new Headers(headers)
315
+ };
316
+
317
+ if (httpMethod !== 'GET' && httpMethod !== 'HEAD') {
318
+ const encoding = isBase64Encoded ? 'base64' : 'utf-8';
319
+ init.body = typeof body === 'string' ? Buffer.from(body, encoding) : body;
320
+ }
321
+
322
+ return new Request(rawUrl, init);
323
+ }
324
+
325
+ const text_types = new Set([
326
+ 'application/xml',
327
+ 'application/json',
328
+ 'application/x-www-form-urlencoded',
329
+ 'multipart/form-data'
330
+ ]);
331
+
332
+ /**
333
+ * Decides how the body should be parsed based on its mime type
334
+ *
335
+ * @param {string | undefined | null} content_type The `content-type` header of a request/response.
336
+ * @returns {boolean}
337
+ */
338
+ function is_text(content_type) {
339
+ if (!content_type) return true; // defaults to json
340
+ const type = content_type.split(';')[0].toLowerCase(); // get the mime type
341
+
342
+ return type.startsWith('text/') || type.endsWith('+xml') || text_types.has(type);
343
+ }
344
+
345
+ exports.init = init;