Skip to content

Commit

Permalink
Merge branch 'main' into cleanup-scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy committed Aug 20, 2024
2 parents db887d8 + b558424 commit 07097a5
Show file tree
Hide file tree
Showing 25 changed files with 159 additions and 23 deletions.
5 changes: 5 additions & 0 deletions .changeset/long-months-burn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Changes messages logged when using unsupported, deprecated, or experimental adapter features for clarity
5 changes: 5 additions & 0 deletions .changeset/odd-donuts-impress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes the path returned by `injectTypes`
7 changes: 7 additions & 0 deletions .changeset/smooth-melons-cough.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astrojs/vercel': patch
---

Prevent race condition with Node 18

Using Node 18 there can be a race condition where polyfill for the `crypto` global is not applied in time. This change ensures the polyfills run first.
5 changes: 5 additions & 0 deletions .changeset/tiny-lamps-lick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes an error thrown by `astro sync` when an `astro:env` virtual module is imported inside the Content Collections config
6 changes: 6 additions & 0 deletions .changeset/weak-masks-do.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'astro': patch
'@astrojs/db': patch
---

Disables the WebSocket server when creating a Vite server for loading config files
31 changes: 21 additions & 10 deletions examples/middleware/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,27 @@ const validation = defineMiddleware(async (context, next) => {
} else if (context.request.url.endsWith('/api/login')) {
const response = await next();
// the login endpoint will return to us a JSON with username and password
const data = await response.json();
// we naively check if username and password are equals to some string
if (data.username === 'astro' && data.password === 'astro') {
// we store the token somewhere outside of locals because the `locals` object is attached to the request
// and when doing a redirect, we lose that information
loginInfo.token = 'loggedIn';
loginInfo.currentTime = new Date().getTime();
return context.redirect('/admin');
}
}
if (response.headers.get('content-type') === 'application/json') {
const data = await response.json();
// we naively check if username and password are equals to some string
if (data.username === 'astro' && data.password === 'astro') {
// we store the token somewhere outside of locals because the `locals` object is attached to the request
// and when doing a redirect, we lose that information
loginInfo.token = 'loggedIn';
loginInfo.currentTime = new Date().getTime();
return context.redirect('/admin');
}
}
return response;
} else if (context.request.url.endsWith('/api/logout')) {
const response = await next();
if (response.ok) {
loginInfo.token = undefined;
loginInfo.currentTime = undefined;
return context.redirect('/login');
}
return response;
}
return next();
});

Expand Down
5 changes: 5 additions & 0 deletions examples/middleware/src/pages/admin.astro
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
---
import Layout from '../layouts/Layout.astro';
import Card from '../components/Card.astro';
const user = Astro.locals.user;
---

<Layout title="Welcome back!!">
<main>
<h1>Welcome back <span class="text-gradient">{user.name} {user.surname}</span></h1>
{}
<ul role="list" class="link-card-grid">
<Card href="/api/logout" title="Logout" body="Logout now" />
</ul>
</main>
</Layout>

Expand Down
21 changes: 21 additions & 0 deletions examples/middleware/src/pages/api/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { APIRoute, APIContext } from "astro";

export const POST: APIRoute = async (context: APIContext) => {
try {
const data = await context.request.formData();
return new Response(
JSON.stringify({
username: data.get("username"),
password: data.get("password"),
}),
{
headers: { "Content-Type": "application/json" },
}
);
} catch (e) {
if (e instanceof Error) {
console.error(e.message);
}
}
return new Response(null, { status: 400 });
};
5 changes: 5 additions & 0 deletions examples/middleware/src/pages/api/logout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { APIRoute, APIContext } from "astro";

export const GET: APIRoute = async (_: APIContext) => {
return new Response(null, { status: 200 });
};
2 changes: 1 addition & 1 deletion examples/middleware/src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import Card from '../components/Card.astro';
</p>
{}
<ul role="list" class="link-card-grid">
<Card href="/login" title="Login" body="Try the login" />
<Card href="/login" title="Login" body="Try the login with astro/astro" />
</ul>
</main>
</Layout>
Expand Down
1 change: 1 addition & 0 deletions examples/middleware/src/pages/login.astro
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ if (status === 301) {
<p class="instructions">
To get started, open the directory <code>src/pages</code> in your project.<br />
<strong>Code Challenge:</strong> Tweak the "Welcome to Astro" message above.
<strong>Login with:</strong> Username: <code>astro</code> Password: <code>astro</code>
</p>
{redirectMessage}
<form action="/api/login" method="POST">
Expand Down
6 changes: 5 additions & 1 deletion packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2275,6 +2275,10 @@ export interface AstroUserConfig {
* export const collections = { blog, dogs };
* ```
*
* :::note
* Loaders will not automatically [exclude files prefaced with an `_`](/en/guides/routing/#excluding-pages). Use a regular expression such as `pattern: '**\/[^_]*.md` in your loader to ignore these files.
* :::
*
* #### Querying and rendering with the Content Layer API
*
* The collection can be [queried in the same way as content collections](/en/guides/content-collections/#querying-collections):
Expand Down Expand Up @@ -2356,7 +2360,7 @@ export interface AstroUserConfig {
* const blog = defineCollection({
* // For content layer you no longer define a `type`
* type: 'content',
* loader: glob({ pattern: "**\/*.md", base: "./src/data/blog" }),
* loader: glob({ pattern: '**\/[^_]*.md', base: "./src/data/blog" }),
* schema: z.object({
* title: z.string(),
* description: z.string(),
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/config/vite-load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { debug } from '../logger/core.js';
async function createViteServer(root: string, fs: typeof fsType): Promise<ViteDevServer> {
const viteServer = await createServer({
configFile: false,
server: { middlewareMode: true, hmr: false, watch: null },
server: { middlewareMode: true, hmr: false, watch: null, ws: false },
optimizeDeps: { noDiscovery: true },
clearScreen: false,
appType: 'custom',
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/sync/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ async function syncContentCollections(
const tempViteServer = await createServer(
await createVite(
{
server: { middlewareMode: true, hmr: false, watch: null },
server: { middlewareMode: true, hmr: false, watch: null, ws: false },
optimizeDeps: { noDiscovery: true },
ssr: { external: [] },
logLevel: 'silent',
Expand Down
7 changes: 5 additions & 2 deletions packages/astro/src/env/vite-plugin-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function astroEnv({
fs,
sync,
}: AstroEnvVirtualModPluginParams): Plugin | undefined {
if (!settings.config.experimental.env || sync) {
if (!settings.config.experimental.env) {
return;
}
const schema = settings.config.experimental.env.schema ?? {};
Expand All @@ -57,6 +57,7 @@ export function astroEnv({
schema,
loadedEnv,
validateSecrets: settings.config.experimental.env?.validateSecrets ?? false,
sync,
});

templates = {
Expand Down Expand Up @@ -100,10 +101,12 @@ function validatePublicVariables({
schema,
loadedEnv,
validateSecrets,
sync,
}: {
schema: EnvSchema;
loadedEnv: Record<string, string>;
validateSecrets: boolean;
sync: boolean;
}) {
const valid: Array<{ key: string; value: any; type: string; context: 'server' | 'client' }> = [];
const invalid: Array<InvalidVariable> = [];
Expand All @@ -125,7 +128,7 @@ function validatePublicVariables({
}
}

if (invalid.length > 0) {
if (invalid.length > 0 && !sync) {
throw new AstroError({
...AstroErrorData.EnvInvalidVariables,
message: AstroErrorData.EnvInvalidVariables.message(invalidVariablesToError(invalid)),
Expand Down
9 changes: 6 additions & 3 deletions packages/astro/src/integrations/features-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,20 +124,23 @@ function validateSupportKind(
}

function featureIsUnsupported(adapterName: string, logger: Logger, featureName: string) {
logger.error('config', `The feature "${featureName}" is not supported (used by ${adapterName}).`);
logger.error(
'config',
`The adapter ${adapterName} doesn't currently support the feature "${featureName}".`,
);
}

function featureIsExperimental(adapterName: string, logger: Logger, featureName: string) {
logger.warn(
'config',
`The feature "${featureName}" is experimental and subject to change (used by ${adapterName}).`,
`The adapter ${adapterName} provides experimental support for "${featureName}". You may experience issues or breaking changes until this feature is fully supported by the adapter.`,
);
}

function featureIsDeprecated(adapterName: string, logger: Logger, featureName: string) {
logger.warn(
'config',
`The feature "${featureName}" is deprecated and will be removed in the future (used by ${adapterName}).`,
`The adapter ${adapterName} has deprecated its support for "${featureName}", and future compatibility is not guaranteed. The adapter may completely remove support for this feature without warning.`,
);
}

Expand Down
4 changes: 3 additions & 1 deletion packages/astro/src/integrations/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,9 @@ export async function runHookConfigDone({
content: injectedType.content,
});

return new URL(normalizedFilename, settings.config.root);
// It must be relative to dotAstroDir here and not inside normalizeInjectedTypeFilename
// because injectedTypes are handled relatively to the dotAstroDir already
return new URL(normalizedFilename, settings.dotAstroDir);
},
logger: getLogger(integration, logger),
}),
Expand Down
10 changes: 10 additions & 0 deletions packages/astro/test/astro-sync.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,16 @@ describe('astro sync', () => {
assert.fail();
}
});
it('Does not throw if a virtual module is imported in content/config.ts', async () => {
try {
await fixture.load('./fixtures/astro-env-content-collections/');
fixture.clean();
await fixture.whenSyncing();
assert.ok(true);
} catch {
assert.fail();
}
});
});

describe('astro:actions', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { defineConfig, envField } from 'astro/config';

// https://astro.build/config
export default defineConfig({
experimental: {
env: {
schema: {
FOO: envField.string({ context: "client", access: "public", optional: true, default: "ABC" }),
}
}
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "@test/astro-env-content-collections",
"version": "0.0.0",
"private": true,
"dependencies": {
"astro": "workspace:*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { defineCollection, z } from "astro:content";
import { FOO } from "astro:env/client"

console.log({ FOO })

export const collections = {
foo: defineCollection({
type: "data",
schema: z.object({
title: z.string()
})
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "astro/tsconfigs/base"
}
2 changes: 1 addition & 1 deletion packages/db/src/core/integration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ async function executeSeedFile({
async function getTempViteServer({ viteConfig }: { viteConfig: UserConfig }) {
const tempViteServer = await createServer(
mergeConfig(viteConfig, {
server: { middlewareMode: true, hmr: false, watch: null },
server: { middlewareMode: true, hmr: false, watch: null, ws: false },
optimizeDeps: { noDiscovery: true },
ssr: { external: [] },
logLevel: 'silent',
Expand Down
5 changes: 3 additions & 2 deletions packages/integrations/vercel/src/serverless/entrypoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ import {
ASTRO_PATH_PARAM,
} from './adapter.js';

// Run polyfills immediately so any dependent code can use the globals
applyPolyfills();

// Won't throw if the virtual module is not available because it's not supported in
// the users's astro version or if astro:env is not enabled in the project
await import('astro/env/setup')
.then((mod) => mod.setGetEnv((key) => process.env[key]))
.catch(() => {});

applyPolyfills();

export const createExports = (
manifest: SSRManifest,
{ middlewareSecret, skewProtection }: { middlewareSecret: string; skewProtection: boolean },
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 07097a5

Please sign in to comment.