Skip to content

Commit

Permalink
merge master
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Feb 16, 2023
2 parents 9b71ed9 + 8a950aa commit fe3b7f5
Show file tree
Hide file tree
Showing 76 changed files with 677 additions and 293 deletions.
5 changes: 5 additions & 0 deletions .changeset/bright-lizards-deny.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': minor
---

feat: richer error message for invalid exports
5 changes: 5 additions & 0 deletions .changeset/seven-teachers-tell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

chore: throw more helpful error when encoding uri fails during prerendering
5 changes: 0 additions & 5 deletions .changeset/smooth-shrimps-look.md

This file was deleted.

8 changes: 5 additions & 3 deletions documentation/docs/20-core-concepts/10-routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ Like `+layout.js`, `+layout.server.js` can export [page options](page-options)

## +server

As well as pages, you can define routes with a `+server.js` file (sometimes referred to as an 'API route' or an 'endpoint'), which gives you full control over the response. Your `+server.js` file (or `+server.ts`) exports functions corresponding to HTTP verbs like `GET`, `POST`, `PATCH`, `PUT` and `DELETE` that take a `RequestEvent` argument and return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object.
As well as pages, you can define routes with a `+server.js` file (sometimes referred to as an 'API route' or an 'endpoint'), which gives you full control over the response. Your `+server.js` file (or `+server.ts`) exports functions corresponding to HTTP verbs like `GET`, `POST`, `PATCH`, `PUT`, `DELETE`, and `OPTIONS` that take a `RequestEvent` argument and return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object.

For example we could create an `/api/random-number` route with a `GET` handler:

Expand Down Expand Up @@ -279,9 +279,11 @@ You can use the [`error`](modules#sveltejs-kit-error), [`redirect`](modules#svel
If an error is thrown (either `throw error(...)` or an unexpected error), the response will be a JSON representation of the error or a fallback error page — which can be customised via `src/error.html` — depending on the `Accept` header. The [`+error.svelte`](#error) component will _not_ be rendered in this case. You can read more about error handling [here](errors).
> When creating an `OPTIONS` handler, note that Vite will inject `Access-Control-Allow-Origin` and `Access-Control-Allow-Methods` headers — these will not be present in production unless you add them.
### Receiving data
By exporting `POST`/`PUT`/`PATCH`/`DELETE` handlers, `+server.js` files can be used to create a complete API:
By exporting `POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS` handlers, `+server.js` files can be used to create a complete API:
```svelte
/// file: src/routes/add/+page.svelte
Expand Down Expand Up @@ -327,7 +329,7 @@ export async function POST({ request }) {
`+server.js` files can be placed in the same directory as `+page` files, allowing the same route to be either a page or an API endpoint. To determine which, SvelteKit applies the following rules:
- `PUT`/`PATCH`/`DELETE` requests are always handled by `+server.js` since they do not apply to pages
- `PUT`/`PATCH`/`DELETE`/`OPTIONS` requests are always handled by `+server.js` since they do not apply to pages
- `GET`/`POST` requests are treated as page requests if the `accept` header prioritises `text/html` (in other words, it's a browser page request), else they are handled by `+server.js`
## $types
Expand Down
2 changes: 1 addition & 1 deletion documentation/docs/20-core-concepts/20-load.md
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ export function load({ locals }) {
}
```

> Make sure you're not catching the thrown redirect, which results in a noop.
> Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
In the browser, you can also navigate programmatically outside of a `load` function using [`goto`](modules#$app-navigation-goto) from [`$app.navigation`](modules#$app-navigation).

Expand Down
7 changes: 6 additions & 1 deletion documentation/docs/25-build-and-deploy/40-adapter-node.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@ export default {
// default options are shown
out: 'build',
precompress: false,
envPrefix: ''
envPrefix: '',
polyfill: true
})
}
};
Expand All @@ -140,6 +141,10 @@ Enables precompressing using gzip and brotli for assets and prerendered pages. I

If you need to change the name of the environment variables used to configure the deployment (for example, to deconflict with environment variables you don't control), you can specify a prefix:

### polyfill

Controlls whether your build will load polyfills for missing modules. It defaults to `true`, and should only be disabled when using Node 18.11 or greater.

```js
envPrefix: 'MY_CUSTOM_';
```
Expand Down
5 changes: 4 additions & 1 deletion documentation/docs/30-advanced/40-service-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ The following example caches the built app and any files in `static` eagerly, an

```js
// @errors: 2339
/// <reference types="@sveltejs/kit" />
import { build, files, version } from '$service-worker';

// Create a unique cache name for this deployment
Expand Down Expand Up @@ -108,21 +109,23 @@ navigator.serviceWorker.register('/service-worker.js', {
Setting up proper types for service workers requires some manual setup. Inside your `service-worker.js`, add the following to the top of your file:

```original-js
/// <reference types="@sveltejs/kit" />
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" />
const sw = /** @type {ServiceWorkerGlobalScope} */ (/** @type {unknown} */ (self));
```
```generated-ts
/// <reference types="@sveltejs/kit" />
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" />
const sw = self as unknown as ServiceWorkerGlobalScope;
```

This disables access to DOM typings like `HTMLElement` which are not available inside a service worker and instantiates the correct globals. The reassignment of `self` to `sw` allows you to type cast it in the process (there are a couple of ways to do this, but the easiest that requires no additional files). Use `sw` instead of `self` in the rest of the file.
This disables access to DOM typings like `HTMLElement` which are not available inside a service worker and instantiates the correct globals. The reassignment of `self` to `sw` allows you to type cast it in the process (there are a couple of ways to do this, but the easiest that requires no additional files). Use `sw` instead of `self` in the rest of the file. The reference to the SvelteKit types ensures that the `$service-worker` import has proper type definitions.

## Other solutions

Expand Down
5 changes: 3 additions & 2 deletions documentation/docs/30-advanced/65-snapshots.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ To do this, export a `snapshot` object with `capture` and `restore` methods from
</script>
<form method="POST">
<textarea bind:value={comment} />
<label for="comment">Comment</label>
<textarea id="comment" bind:value={comment} />
<button>Post comment</button>
</form>
```
Expand All @@ -30,4 +31,4 @@ When you navigate away from this page, the `capture` function is called immediat

The data must be serializable as JSON so that it can be persisted to `sessionStorage`. This allows the state to be restored when the page is reloaded, or when the user navigates back from a different site.

> Avoid returning very large objects from `capture` — once captured, objects will be retained in memory for the duration of the session, and in extreme cases may be too large to persist to `sessionStorage`.
> Avoid returning very large objects from `capture` — once captured, objects will be retained in memory for the duration of the session, and in extreme cases may be too large to persist to `sessionStorage`.
11 changes: 11 additions & 0 deletions packages/adapter-cloudflare/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
# @sveltejs/adapter-cloudflare

## 2.0.2

### Patch Changes

- fix: exclude `_headers` and `_redirects` files from Cloudflare Pages static request list ([#9042](https://github.com/sveltejs/kit/pull/9042))

- fix: remove redundant cloudflare worker static asset serving ([#9040](https://github.com/sveltejs/kit/pull/9040))

- Updated dependencies [[`19c0e62a`](https://github.com/sveltejs/kit/commit/19c0e62a6bd281e656061b453973c35fa2dd9d3d)]:
- @sveltejs/kit@1.5.7

## 2.0.1

### Patch Changes
Expand Down
20 changes: 15 additions & 5 deletions packages/adapter-cloudflare/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { writeFileSync } from 'fs';
import { posix } from 'path';
import { fileURLToPath } from 'url';
import { writeFileSync } from 'node:fs';
import { posix } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as esbuild from 'esbuild';

/** @type {import('.').default} */
Expand Down Expand Up @@ -70,7 +70,14 @@ function get_routes_json(builder, assets) {
const exclude = [
`/${builder.config.kit.appDir}/*`,
...assets
.filter((file) => !file.startsWith(`${builder.config.kit.appDir}/`))
.filter(
(file) =>
!(
file.startsWith(`${builder.config.kit.appDir}/`) ||
file === '_headers' ||
file === '_redirects'
)
)
.map((file) => `/${file}`)
];

Expand Down Expand Up @@ -111,9 +118,12 @@ function get_routes_json(builder, assets) {
function generate_headers(app_dir) {
return `
# === START AUTOGENERATED SVELTE IMMUTABLE HEADERS ===
/${app_dir}/*
X-Robots-Tag: noindex
Cache-Control: no-cache
/${app_dir}/immutable/*
! Cache-Control
Cache-Control: public, immutable, max-age=31536000
X-Robots-Tag: noindex
# === END AUTOGENERATED SVELTE IMMUTABLE HEADERS ===
`.trimEnd();
}
2 changes: 1 addition & 1 deletion packages/adapter-cloudflare/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@sveltejs/adapter-cloudflare",
"version": "2.0.1",
"version": "2.0.2",
"repository": {
"type": "git",
"url": "https://github.com/sveltejs/kit",
Expand Down
82 changes: 29 additions & 53 deletions packages/adapter-cloudflare/src/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import * as Cache from 'worktop/cfw.cache';

const server = new Server(manifest);

const app_path = `/${manifest.appPath}/`;

/** @type {import('worktop/cfw').Module.Worker<{ ASSETS: import('worktop/cfw.durable').Durable.Object }>} */
const worker = {
async fetch(req, env, context) {
Expand All @@ -17,64 +15,42 @@ const worker = {
if (res) return res;

let { pathname } = new URL(req.url);
try {
pathname = decodeURIComponent(pathname);
} catch {
// ignore invalid URI
}

// generated files
if (pathname.startsWith(app_path)) {
res = await env.ASSETS.fetch(req);
if (!res.ok) return res;
const stripped_pathname = pathname.replace(/\/$/, '');

const cache_control = pathname.startsWith(app_path + 'immutable/')
? 'public, immutable, max-age=31536000'
: 'no-cache';
// prerendered pages and /static files
let is_static_asset = false;
const filename = stripped_pathname.substring(1);
if (filename) {
is_static_asset =
manifest.assets.has(filename) || manifest.assets.has(filename + '/index.html');
}

res = new Response(res.body, {
const location = pathname.at(-1) === '/' ? stripped_pathname : pathname + '/';

if (is_static_asset || prerendered.has(pathname)) {
res = await env.ASSETS.fetch(req);
} else if (location && prerendered.has(location)) {
res = new Response('', {
status: 308,
headers: {
// include original headers, minus cache-control which
// is overridden, and etag which is no longer useful
'cache-control': cache_control,
'content-type': res.headers.get('content-type'),
'x-robots-tag': 'noindex'
location
}
});
} else {
// prerendered pages and /static files

try {
pathname = decodeURIComponent(pathname);
} catch {
// ignore invalid URI
}

const stripped_pathname = pathname.replace(/\/$/, '');

let is_static_asset = false;
const filename = stripped_pathname.substring(1);
if (filename) {
is_static_asset =
manifest.assets.has(filename) || manifest.assets.has(filename + '/index.html');
}

const counterpart_route = pathname.at(-1) === '/' ? stripped_pathname : pathname + '/';

if (is_static_asset || prerendered.has(pathname)) {
res = await env.ASSETS.fetch(req);
} else if (counterpart_route && prerendered.has(counterpart_route)) {
res = new Response('', {
status: 308,
headers: {
location: counterpart_route
}
});
} else {
// dynamically-generated pages
res = await server.respond(req, {
// @ts-ignore
platform: { env, context, caches },
getClientAddress() {
return req.headers.get('cf-connecting-ip');
}
});
}
// dynamically-generated pages
res = await server.respond(req, {
// @ts-ignore
platform: { env, context, caches },
getClientAddress() {
return req.headers.get('cf-connecting-ip');
}
});
}

// Writes to Cache only if allowed & specified
Expand Down
20 changes: 20 additions & 0 deletions packages/adapter-netlify/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
# @sveltejs/adapter-netlify

## 2.0.4

### Patch Changes

- fix: Root route data endpoint redirect when using split routes ([#9006](https://github.com/sveltejs/kit/pull/9006))

- Updated dependencies [[`74cfa8d5`](https://github.com/sveltejs/kit/commit/74cfa8d5f1f13f81759e20e90f4ff86a4f96040d), [`bfa2b6ec`](https://github.com/sveltejs/kit/commit/bfa2b6ec88a6d522d87c924d7c466c01e142e66e)]:
- @sveltejs/kit@1.5.6

## 2.0.3

### Patch Changes

- chore: simplify functions-internal cleanup ([#8953](https://github.com/sveltejs/kit/pull/8953))

- fix: correctly compare routes when generating split functions ([#8952](https://github.com/sveltejs/kit/pull/8952))

- Updated dependencies [[`0abb8ebf`](https://github.com/sveltejs/kit/commit/0abb8ebffc6121f81c2bbfa0a0f68866d4cc1627), [`bef54f63`](https://github.com/sveltejs/kit/commit/bef54f63d2315066d30e8f1bcf471ddf2bd72c35), [`51cd6e64`](https://github.com/sveltejs/kit/commit/51cd6e643178e3a113fc2c3e8a63755bcbfe902d), [`930c8e4e`](https://github.com/sveltejs/kit/commit/930c8e4ee2e3046ed1b622777dafa23029a19fe5), [`ee8066fc`](https://github.com/sveltejs/kit/commit/ee8066fcb29ed1e7e3ab513cabb7997e38c984f2), [`49d2ec62`](https://github.com/sveltejs/kit/commit/49d2ec62e6385694f11701bf2fa411d07449344c), [`eb943565`](https://github.com/sveltejs/kit/commit/eb943565a4324dbed3da5a581924ca91a24366de)]:
- @sveltejs/kit@1.5.3

## 2.0.2

### Patch Changes
Expand Down
Loading

0 comments on commit fe3b7f5

Please sign in to comment.