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

fix(actions): better runtime check for invalid usages #12402

Merged
merged 2 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
14 changes: 14 additions & 0 deletions .changeset/dull-lemons-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'astro': patch
---

Fixes a case where Astro allowed to call an action without using `Astro.callAction`. This is now invalid, and Astro will show a proper error.

```diff
---
import { actions } from "astro:actions";

-const result = actions.getUser({ userId: 123 });
+const result = Astro.callAction(actions.getUser, { userId: 123 });
---
```
3 changes: 2 additions & 1 deletion packages/astro/src/actions/runtime/virtual/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ export function defineAction<
: getJsonServerHandler(handler, inputSchema);

async function safeServerHandler(this: ActionAPIContext, unparsedInput: unknown) {
if (typeof this === 'function') {
// The ActionAPIContext should always contain the `params` property
if (typeof this === 'function' || !('params' in this)) {
ematipico marked this conversation as resolved.
Show resolved Hide resolved
throw new AstroError(ActionCalledFromServerError);
}
return callSafely(() => serverHandler(unparsedInput, this));
Expand Down
6 changes: 6 additions & 0 deletions packages/astro/test/actions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ describe('Astro Actions', () => {
assert.equal(data, 'Hello, ben!');
}
});

it('Should fail when calling an action without using Astro.callAction', async () => {
const res = await fixture.fetch('/invalid/');
const text = await res.text();
assert.match(text, /ActionCalledFromServerError/);
ematipico marked this conversation as resolved.
Show resolved Hide resolved
});
});

describe('build', () => {
Expand Down
6 changes: 6 additions & 0 deletions packages/astro/test/fixtures/actions/src/pages/invalid.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
import { actions } from "astro:actions";

// this is invalid, it should fail
const result = await actions.imageUploadInChunks();
---
Loading