UNPKG

@sveltejs/kit

Version:

SvelteKit is the fastest way to build Svelte apps

79 lines (65 loc) • 2 kB
import { read_implementation, manifest } from '../../server/internal.js'; import { assets } from '#app/paths'; import { base64_decode } from '../../utils.js'; import * as e from '../../../messages/server-errors.js'; /** * Read the contents of an imported asset from the filesystem * @example * ```js * import { read } from '$app/server'; * import somefile from './somefile.txt'; * * const asset = read(somefile); * const text = await asset.text(); * ``` * @param {string} asset * @returns {Response} * @since 2.4.0 */ export function read(asset) { __SVELTEKIT_TRACK__('$app/server:read'); if (!read_implementation) { e.read_implementation_missing(); } // handle inline assets internally const match = /^data:([^;,]+)?(;base64)?,/.exec(asset); if (match) { const type = match[1] ?? 'application/octet-stream'; const data = asset.slice(match[0].length); if (match[2] !== undefined) { const decoded = base64_decode(data); // @ts-ignore passing a Uint8Array to `new Response(...)` is fine return new Response(decoded, { headers: { 'Content-Length': decoded.byteLength.toString(), 'Content-Type': type } }); } const decoded = decodeURIComponent(data); return new Response(decoded, { headers: { 'Content-Length': decoded.length.toString(), 'Content-Type': type } }); } const file = decodeURIComponent( __SVELTEKIT_DEV__ && asset.startsWith(assets + '/@fs') ? asset.slice(assets.length) : asset.slice(assets.length + 1) ); if (file in manifest.server_assets) { const length = manifest.server_assets[file]; const type = manifest.mime_types[file.slice(file.lastIndexOf('.'))]; return new Response(read_implementation(file), { headers: { 'Content-Length': '' + length, 'Content-Type': type } }); } e.read_asset_missing({ file }); } export { getRequestEvent } from '@sveltejs/kit/internal/server'; export { query, prerender, command, form, requested } from './remote/index.js';