Skip to content

feat: Vite environment API #14008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 19 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@
"svelte-preprocess",
"unix-dgram",
"workerd"
]
],
"overrides": {
"esm-env": "github:benmccann/esm-env#bcbddbc&path:packages/esm-env"
}
}
}
2 changes: 1 addition & 1 deletion packages/adapter-auto/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"devDependencies": {
"@sveltejs/kit": "workspace:^",
"@sveltejs/vite-plugin-svelte": "catalog:",
"@types/node": "^18.19.119",
"@types/node": "catalog:",
"typescript": "^5.3.3",
"vitest": "catalog:"
},
Expand Down
74 changes: 37 additions & 37 deletions packages/adapter-cloudflare/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { VERSION } from '@sveltejs/kit';
import { copyFileSync, existsSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { VERSION } from '@sveltejs/kit';
import { unstable_readConfig } from 'wrangler';
import { is_building_for_cloudflare_pages, validate_worker_settings } from './utils.js';
import { getPlatformProxy, unstable_readConfig } from 'wrangler';

const name = '@sveltejs/adapter-cloudflare';
const [kit_major, kit_minor] = VERSION.split('.');
Expand Down Expand Up @@ -132,41 +132,6 @@ export default function (options = {}) {
);
}
},
emulate() {
// we want to invoke `getPlatformProxy` only once, but await it only when it is accessed.
// If we would await it here, it would hang indefinitely because the platform proxy only resolves once a request happens
const get_emulated = async () => {
const proxy = await getPlatformProxy(options.platformProxy);
const platform = /** @type {App.Platform} */ ({
env: proxy.env,
ctx: proxy.ctx,
context: proxy.ctx, // deprecated in favor of ctx
caches: proxy.caches,
cf: proxy.cf
});
/** @type {Record<string, any>} */
const env = {};
const prerender_platform = /** @type {App.Platform} */ (/** @type {unknown} */ ({ env }));
for (const key in proxy.env) {
Object.defineProperty(env, key, {
get: () => {
throw new Error(`Cannot access platform.env.${key} in a prerenderable route`);
}
});
}
return { platform, prerender_platform };
};

/** @type {{ platform: App.Platform, prerender_platform: App.Platform }} */
let emulated;

return {
platform: async ({ prerender }) => {
emulated ??= await get_emulated();
return prerender ? emulated.prerender_platform : emulated.platform;
}
};
},
supports: {
read: ({ route }) => {
// TODO bump peer dep in next adapter major to simplify this
Expand All @@ -179,6 +144,41 @@ export default function (options = {}) {
return true;
}
}
// emulate() {
// // we want to invoke `getPlatformProxy` only once, but await it only when it is accessed.
// // If we would await it here, it would hang indefinitely because the platform proxy only resolves once a request happens
// const get_emulated = async () => {
// const proxy = await getPlatformProxy(options.platformProxy);
// const platform = /** @type {App.Platform} */ ({
// env: proxy.env,
// ctx: proxy.ctx,
// context: proxy.ctx, // deprecated in favor of ctx
// caches: proxy.caches,
// cf: proxy.cf
// });
// /** @type {Record<string, any>} */
// const env = {};
// const prerender_platform = /** @type {App.Platform} */ (/** @type {unknown} */ ({ env }));
// for (const key in proxy.env) {
// Object.defineProperty(env, key, {
// get: () => {
// throw new Error(`Cannot access platform.env.${key} in a prerenderable route`);
// }
// });
// }
// return { platform, prerender_platform };
// };

// /** @type {{ platform: App.Platform, prerender_platform: App.Platform }} */
// let emulated;

// return {
// platform: async ({ prerender }) => {
// emulated ??= await get_emulated();
// return prerender ? emulated.prerender_platform : emulated.platform;
// }
// };
// }
};
}

Expand Down
11 changes: 11 additions & 0 deletions packages/adapter-cloudflare/internal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,14 @@ declare module 'MANIFEST' {
export const app_path: string;
export const base_path: string;
}

declare module '__sveltekit/vite-environment' {
// eslint-disable-next-line no-duplicate-imports
import { SSRManifest } from '@sveltejs/kit';

export const manifest: SSRManifest;
export const env: Record<string, string>;
export const remote_address: string | undefined;
export const base_path: string;
export const prerendered: Set<string>;
}
6 changes: 5 additions & 1 deletion packages/adapter-cloudflare/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,17 @@
"types": "./index.d.ts",
"import": "./index.js"
},
"./worker": {
"import": "./worker.js"
},
"./package.json": "./package.json"
},
"types": "index.d.ts",
"files": [
"files",
"index.js",
"utils.js",
"worker.js",
"index.d.ts",
"ambient.d.ts"
],
Expand All @@ -50,7 +54,7 @@
"devDependencies": {
"@playwright/test": "catalog:",
"@sveltejs/kit": "workspace:^",
"@types/node": "^18.19.119",
"@types/node": "catalog:",
"esbuild": "^0.25.4",
"typescript": "^5.3.3",
"vitest": "catalog:"
Expand Down
4 changes: 3 additions & 1 deletion packages/adapter-cloudflare/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@
"moduleResolution": "node16",
"baseUrl": ".",
"paths": {
"@sveltejs/kit": ["../kit/types/index"]
"@sveltejs/kit": ["../kit/types/index.d.ts"],
"@sveltejs/kit/internal/server": ["../kit/src/runtime/server/index.js"]
},
// taken from the Cloudflare Workers TypeScript template https://github.com/cloudflare/workers-sdk/blob/main/packages/create-cloudflare/templates/hello-world/ts/tsconfig.json
"lib": ["es2021"],
"types": ["@cloudflare/workers-types"]
},
"include": [
"index.js",
"worker.js",
"utils.js",
"utils.spec.js",
"test/utils.js",
Expand Down
103 changes: 103 additions & 0 deletions packages/adapter-cloudflare/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { Server } from '@sveltejs/kit/internal/server';
// TODO: use prod variables when building
// TODO: fix kit virtual module type issues when this file is consumed by an app
import { version } from '__sveltekit/environment';
import {
manifest,
env,
remote_address,
base_path,
prerendered
} from '__sveltekit/vite-environment';
import * as Cache from 'worktop/cfw.cache';

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

const immutable = `${app_path}/immutable/`;
const version_file = `${app_path}/version.json`;

const server = new Server(manifest);

await server.init({ env });

/**
* @param {Request} request
* @param {{ ASSETS: { fetch: typeof fetch } }} env
* @param {import('@cloudflare/workers-types').ExecutionContext} ctx
* @returns {Promise<Response>}
*/
export async function handleRequest(request, env, ctx) {
// skip cache if "cache-control: no-cache" in request
let pragma = request.headers.get('cache-control') || '';
let res = !pragma.includes('no-cache') && (await Cache.lookup(request));
if (res) return res;

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

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

// files in /static, the service worker, and Vite imported server assets
let is_static_asset = false;
const filename = stripped_pathname.slice(base_path.length + 1);
if (filename) {
is_static_asset =
manifest.assets.has(filename) ||
manifest.assets.has(filename + '/index.html') ||
filename in manifest._.server_assets ||
filename + '/index.html' in manifest._.server_assets;
}

let location = pathname.at(-1) === '/' ? stripped_pathname : pathname + '/';

// TODO: we should only return the version var in dev because the version file is not written to disk
if (pathname === version_file) {
res = new Response(version);
// TODO: only in production
// }
// else if (
// is_static_asset ||
// prerendered.has(pathname) ||
// pathname === version_file ||
// pathname.startsWith(immutable)
// ) {
// res = await env.ASSETS.fetch(request);
} else if (location && prerendered.has(location)) {
// trailing slash redirect for prerendered pages
if (search) location += search;
res = new Response('', {
status: 308,
headers: {
location
}
});
} else {
// dynamically-generated pages
res = await server.respond(request, {
platform: {
env,
ctx,
context: ctx, // deprecated in favor of ctx
// @ts-expect-error webworker types from worktop are not compatible with Cloudflare Workers types
caches,
// @ts-expect-error the type is correct but ts is confused because platform.cf uses the type from index.ts while req.cf uses the type from index.d.ts
cf: request.cf
},
getClientAddress() {
if (remote_address) return remote_address;
throw new Error('Could not determine clientAddress');
// TODO: use the header in prod
// return request.headers.get('cf-connecting-ip');
}
});
}

// write to `Cache` only if response is not an error,
// let `Cache.save` handle the Cache-Control and Vary headers
pragma = res.headers.get('cache-control') || '';
return pragma && res.status < 400 ? Cache.save(request, res, ctx) : res;
}
2 changes: 1 addition & 1 deletion packages/adapter-netlify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"@rollup/plugin-node-resolve": "^16.0.0",
"@sveltejs/kit": "workspace:^",
"@sveltejs/vite-plugin-svelte": "catalog:",
"@types/node": "^18.19.119",
"@types/node": "catalog:",
"@types/set-cookie-parser": "^2.4.7",
"rollup": "^4.14.2",
"typescript": "^5.3.3",
Expand Down
2 changes: 1 addition & 1 deletion packages/adapter-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"@polka/url": "^1.0.0-next.28",
"@sveltejs/kit": "workspace:^",
"@sveltejs/vite-plugin-svelte": "catalog:",
"@types/node": "^18.19.119",
"@types/node": "catalog:",
"polka": "^1.0.0-next.28",
"sirv": "^3.0.0",
"typescript": "^5.3.3",
Expand Down
2 changes: 1 addition & 1 deletion packages/adapter-static/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"@playwright/test": "catalog:",
"@sveltejs/kit": "workspace:^",
"@sveltejs/vite-plugin-svelte": "catalog:",
"@types/node": "^18.19.119",
"@types/node": "catalog:",
"sirv": "^3.0.0",
"svelte": "^5.35.5",
"typescript": "^5.3.3",
Expand Down
2 changes: 1 addition & 1 deletion packages/adapter-vercel/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"devDependencies": {
"@sveltejs/kit": "workspace:^",
"@sveltejs/vite-plugin-svelte": "catalog:",
"@types/node": "^18.19.119",
"@types/node": "catalog:",
"typescript": "^5.3.3",
"vitest": "catalog:"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/enhanced-img/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "catalog:",
"@types/estree": "^1.0.5",
"@types/node": "^18.19.119",
"@types/node": "catalog:",
"rollup": "^4.27.4",
"svelte": "^5.35.5",
"typescript": "^5.6.3",
Expand Down
8 changes: 6 additions & 2 deletions packages/kit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"@playwright/test": "catalog:",
"@sveltejs/vite-plugin-svelte": "catalog:",
"@types/connect": "^3.4.38",
"@types/node": "^18.19.119",
"@types/node": "catalog:",
"@types/set-cookie-parser": "^2.4.7",
"dts-buddy": "^0.6.1",
"rollup": "^4.14.2",
Expand All @@ -48,7 +48,7 @@
"peerDependencies": {
"@sveltejs/vite-plugin-svelte": "^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0",
"svelte": "^4.0.0 || ^5.0.0-next.0",
"vite": "^5.0.3 || ^6.0.0 || ^7.0.0-beta.0"
"vite": "^7.0.0-beta.0"
},
"bin": {
"svelte-kit": "svelte-kit.js"
Expand Down Expand Up @@ -87,6 +87,10 @@
"types": "./types/index.d.ts",
"import": "./src/exports/internal/index.js"
},
"./internal/server": {
"types": "./types/index.d.ts",
"import": "./src/runtime/server/index.js"
},
"./node": {
"types": "./types/index.d.ts",
"import": "./src/exports/node/index.js"
Expand Down
8 changes: 4 additions & 4 deletions packages/kit/src/exports/vite/build/build_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,21 @@ import { create_node_analyser } from '../static_analysis/index.js';
* @param {import('types').ManifestData} manifest_data
* @param {import('vite').Manifest} server_manifest
* @param {import('vite').Manifest | null} client_manifest
* @param {import('vite').Rollup.OutputBundle | null} server_bundle
* @param {import('vite').Rollup.RollupOutput['output'] | null} server_chunks
* @param {import('vite').Rollup.RollupOutput['output'] | null} client_chunks
* @param {import('types').RecursiveRequired<import('types').ValidatedConfig['kit']['output']>} output_config
* @param {Map<string, { page_options: Record<string, any> | null, children: string[] }>} static_exports
*/
export async function build_server_nodes(out, kit, manifest_data, server_manifest, client_manifest, server_bundle, client_chunks, output_config, static_exports) {
export async function build_server_nodes(out, kit, manifest_data, server_manifest, client_manifest, server_chunks, client_chunks, output_config, static_exports) {
mkdirp(`${out}/server/nodes`);
mkdirp(`${out}/server/stylesheets`);

/** @type {Map<string, string>} */
const stylesheets_to_inline = new Map();

if (server_bundle && client_chunks && kit.inlineStyleThreshold > 0) {
if (server_chunks && client_chunks && kit.inlineStyleThreshold > 0) {
const client = get_stylesheets(client_chunks);
const server = get_stylesheets(Object.values(server_bundle));
const server = get_stylesheets(server_chunks);

// map server stylesheet name to the client stylesheet name
for (const [id, client_stylesheet] of client.stylesheets_used) {
Expand Down
Loading
Loading