Skip to content
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

Refactor runtime #4201

Merged
merged 4 commits into from
Aug 8, 2022
Merged
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: 5 additions & 0 deletions .changeset/shy-dogs-return.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Adds warning in dev when using client: directive on Astro component
54 changes: 54 additions & 0 deletions packages/astro/src/runtime/server/astro-global.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { AstroGlobalPartial } from '../../@types/astro';

// process.env.PACKAGE_VERSION is injected when we build and publish the astro package.
const ASTRO_VERSION = process.env.PACKAGE_VERSION ?? 'development';

/** Create the Astro.fetchContent() runtime function. */
function createDeprecatedFetchContentFn() {
return () => {
throw new Error('Deprecated: Astro.fetchContent() has been replaced with Astro.glob().');
};
}

/** Create the Astro.glob() runtime function. */
function createAstroGlobFn() {
const globHandler = (importMetaGlobResult: Record<string, any>, globValue: () => any) => {
let allEntries = [...Object.values(importMetaGlobResult)];
if (allEntries.length === 0) {
throw new Error(`Astro.glob(${JSON.stringify(globValue())}) - no matches found.`);
}
// Map over the `import()` promises, calling to load them.
return Promise.all(allEntries.map((fn) => fn()));
};
// Cast the return type because the argument that the user sees (string) is different from the argument
// that the runtime sees post-compiler (Record<string, Module>).
return globHandler as unknown as AstroGlobalPartial['glob'];
}

// This is used to create the top-level Astro global; the one that you can use
// Inside of getStaticPaths.
export function createAstro(
filePathname: string,
_site: string | undefined,
projectRootStr: string
): AstroGlobalPartial {
const site = _site ? new URL(_site) : undefined;
const referenceURL = new URL(filePathname, `http://localhost`);
const projectRoot = new URL(projectRootStr);
return {
site,
generator: `Astro v${ASTRO_VERSION}`,
fetchContent: createDeprecatedFetchContentFn(),
glob: createAstroGlobFn(),
// INVESTIGATE is there a use-case for multi args?
resolve(...segments: string[]) {
let resolved = segments.reduce((u, segment) => new URL(segment, u), referenceURL).pathname;
// When inside of project root, remove the leading path so you are
// left with only `/src/images/tower.png`
if (resolved.startsWith(projectRoot.pathname)) {
resolved = '/' + resolved.slice(projectRoot.pathname.length);
}
return resolved;
},
};
}
74 changes: 74 additions & 0 deletions packages/astro/src/runtime/server/endpoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@

import type {
APIContext,
EndpointHandler,
Params
} from '../../@types/astro';

function getHandlerFromModule(mod: EndpointHandler, method: string) {
// If there was an exact match on `method`, return that function.
if (mod[method]) {
return mod[method];
}
// Handle `del` instead of `delete`, since `delete` is a reserved word in JS.
if (method === 'delete' && mod['del']) {
return mod['del'];
}
// If a single `all` handler was used, return that function.
if (mod['all']) {
return mod['all'];
}
// Otherwise, no handler found.
return undefined;
}

/** Renders an endpoint request to completion, returning the body. */
export async function renderEndpoint(mod: EndpointHandler, request: Request, params: Params) {
const chosenMethod = request.method?.toLowerCase();
const handler = getHandlerFromModule(mod, chosenMethod);
if (!handler || typeof handler !== 'function') {
throw new Error(
`Endpoint handler not found! Expected an exported function for "${chosenMethod}"`
);
}

if (handler.length > 1) {
// eslint-disable-next-line no-console
console.warn(`
API routes with 2 arguments have been deprecated. Instead they take a single argument in the form of:

export function get({ params, request }) {
//...
}

Update your code to remove this warning.`);
}

const context = {
request,
params,
};

const proxy = new Proxy(context, {
get(target, prop) {
if (prop in target) {
return Reflect.get(target, prop);
} else if (prop in params) {
// eslint-disable-next-line no-console
console.warn(`
API routes no longer pass params as the first argument. Instead an object containing a params property is provided in the form of:

export function get({ params }) {
// ...
}

Update your code to remove this warning.`);
return Reflect.get(params, prop);
} else {
return undefined;
}
},
}) as APIContext & Params;

return handler.call(mod, proxy, request);
}
10 changes: 5 additions & 5 deletions packages/astro/src/runtime/server/hydration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import { escapeHTML } from './escape.js';
import { serializeProps } from './serialize.js';
import { serializeListValue } from './util.js';

const HydrationDirectives = ['load', 'idle', 'media', 'visible', 'only'];
const HydrationDirectivesRaw = ['load', 'idle', 'media', 'visible', 'only'];
const HydrationDirectives = new Set(HydrationDirectivesRaw);
export const HydrationDirectiveProps = new Set(HydrationDirectivesRaw.map(n => `client:${n}`));

export interface HydrationMetadata {
directive: string;
Expand Down Expand Up @@ -68,11 +70,9 @@ export function extractDirectives(inputProps: Record<string | number, any>): Ext
extracted.hydration.value = value;

// throw an error if an invalid hydration directive was provided
if (HydrationDirectives.indexOf(extracted.hydration.directive) < 0) {
if (!HydrationDirectives.has(extracted.hydration.directive)) {
throw new Error(
`Error: invalid hydration directive "${key}". Supported hydration methods: ${HydrationDirectives.map(
(d) => `"client:${d}"`
).join(', ')}`
`Error: invalid hydration directive "${key}". Supported hydration methods: ${Array.from(HydrationDirectiveProps).join(', ')}`
);
}

Expand Down
Loading