Skip to content

Commit 2c5c171

Browse files
authored
Merge pull request #119 from hkbertoson/astro-upgrade
Astro V5 Upgrade
2 parents 28b5330 + e5a7b61 commit 2c5c171

18 files changed

+1164
-1458
lines changed

.changeset/early-kiwis-impress.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"astro-turnstile": major
3+
---
4+
5+
Upgrade to Astro V5

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,6 @@
1616
},
1717
"devDependencies": {
1818
"@biomejs/biome": "1.9.2",
19-
"@changesets/cli": "^2.27.8"
19+
"@changesets/cli": "^2.27.10"
2020
}
2121
}

package/lib/components/TurnstileForm.astro

+2-4
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ const siteUrl = Astro.site;
4949
<script>
5050
// Get the form element
5151
const form = document.getElementById(
52-
'at-turnstile-captcha-form',
52+
'at-turnstile-captcha-form'
5353
) as HTMLFormElement;
5454

5555
const turnstileConfig = form.dataset;
@@ -67,9 +67,7 @@ const siteUrl = Astro.site;
6767
if (typeof value === 'string') {
6868
urlEncodedFormData.append(key, value);
6969
} else {
70-
console.warn(
71-
`Invalid form data value for key: ${key}, Skipping...`,
72-
);
70+
console.warn(`Invalid form data value for key: ${key}, Skipping...`);
7371
}
7472
});
7573

package/package.json

+4-4
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,11 @@
3838
"scripts": {},
3939
"type": "module",
4040
"peerDependencies": {
41-
"astro": ">=4.14"
41+
"astro": ">=5.0.2"
4242
},
4343
"dependencies": {
44-
"@matthiesenxyz/astrodtsbuilder": "^0.1.2",
45-
"astro-integration-kit": "^0.16.1",
46-
"vite": "^5.4.4"
44+
"@matthiesenxyz/astrodtsbuilder": "^0.2.0",
45+
"astro-integration-kit": "^0.17.0",
46+
"vite": "^6.0.2"
4747
}
4848
}

package/src/env.d.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
/// <reference types="../../playground/src/env.d.ts" />
1+
/// <reference types="../../.astro/types.d.ts" />

package/src/integration.ts

+75-64
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,36 @@ import {
22
addVirtualImports,
33
createResolver,
44
defineIntegration,
5-
} from "astro-integration-kit";
6-
import { envField } from "astro/config";
7-
import { AstroError } from "astro/errors";
8-
import { loadEnv } from "vite";
9-
import { name } from "../package.json";
10-
import { AstroTurnstileOptionsSchema as optionsSchema } from "./schema.ts";
11-
import { ErrorMessages, envDefaults, loggerStrings } from "./strings.ts";
12-
import Dts from "./stubs.ts";
5+
} from 'astro-integration-kit';
6+
import {envField} from 'astro/config';
7+
import {AstroError} from 'astro/errors';
8+
import {loadEnv} from 'vite';
9+
import {name} from '../package.json';
10+
import {AstroTurnstileOptionsSchema as optionsSchema} from './schema.ts';
11+
import {
12+
ErrorMessages,
13+
envDefaults,
14+
loggerStrings,
15+
svgIcons,
16+
} from './strings.ts';
17+
import Dts from './stubs.ts';
1318

1419
// Load the Turnstile environment variables for the Server runtime and Verification
1520
// that the environment variables are NOT set to Turnstile demo values during build.
16-
const env = loadEnv("TURNSTILE_", process.cwd());
21+
const env = loadEnv('TURNSTILE_', process.cwd());
1722

1823
export const astroTurnstile = defineIntegration({
1924
name,
2025
optionsSchema,
2126
setup({
2227
name,
2328
options,
24-
options: { endpointPath, verbose, disableClientScript, disableDevToolbar },
29+
options: {endpointPath, verbose, disableClientScript, disableDevToolbar},
2530
}) {
26-
const { resolve } = createResolver(import.meta.url);
31+
const {resolve} = createResolver(import.meta.url);
2732
return {
2833
hooks: {
29-
"astro:config:setup": (params) => {
34+
'astro:config:setup': (params) => {
3035
// Destructure the params object
3136
const {
3237
logger,
@@ -45,30 +50,25 @@ export const astroTurnstile = defineIntegration({
4550
// environment variables and Set the 'checkOrigin' security option to true
4651
verbose && logger.info(loggerStrings.updateConfig);
4752
updateConfig({
48-
security: {
49-
checkOrigin: true,
50-
},
51-
experimental: {
52-
env: {
53-
validateSecrets: true,
54-
schema: {
55-
TURNSTILE_SECRET_KEY: envField.string({
56-
access: "secret",
57-
context: "server",
58-
optional: false,
59-
// The default value is only usable in 'dev'/'preview' and should be replaced with the actual secret key.
60-
// See https://developers.cloudflare.com/turnstile/troubleshooting/testing/#dummy-sitekeys-and-secret-keys for more information.
61-
default: envDefaults.secretKey(command),
62-
}),
63-
TURNSTILE_SITE_KEY: envField.string({
64-
access: "public",
65-
context: "client",
66-
optional: false,
67-
// The default value is only usable in 'dev'/'preview' and should be replaced with the actual secret key.
68-
// See https://developers.cloudflare.com/turnstile/troubleshooting/testing/#dummy-sitekeys-and-secret-keys for more information.
69-
default: envDefaults.siteKey(command),
70-
}),
71-
},
53+
env: {
54+
validateSecrets: true,
55+
schema: {
56+
TURNSTILE_SECRET_KEY: envField.string({
57+
access: 'secret',
58+
context: 'server',
59+
optional: false,
60+
// The default value is only usable in 'dev'/'preview' and should be replaced with the actual secret key.
61+
// See https://developers.cloudflare.com/turnstile/troubleshooting/testing/#dummy-sitekeys-and-secret-keys for more information.
62+
default: envDefaults.secretKey(command),
63+
}),
64+
TURNSTILE_SITE_KEY: envField.string({
65+
access: 'public',
66+
context: 'client',
67+
optional: false,
68+
// The default value is only usable in 'dev'/'preview' and should be replaced with the actual secret key.
69+
// See https://developers.cloudflare.com/turnstile/troubleshooting/testing/#dummy-sitekeys-and-secret-keys for more information.
70+
default: envDefaults.siteKey(command),
71+
}),
7272
},
7373
},
7474
});
@@ -85,15 +85,15 @@ export const astroTurnstile = defineIntegration({
8585
}
8686

8787
// If environment variables are set to Turnstile demo values during build, error
88-
if (command === "build") {
88+
if (command === 'build') {
8989
// Check TURNSTILE_SECRET_KEY
9090
if (env.TURNSTILE_SECRET_KEY) {
9191
checkKeys({
9292
key: env.TURNSTILE_SECRET_KEY,
9393
knownKeys: [
94-
"1x0000000000000000000000000000000AA",
95-
"2x0000000000000000000000000000000AA",
96-
"3x0000000000000000000000000000000AA",
94+
'1x0000000000000000000000000000000AA',
95+
'2x0000000000000000000000000000000AA',
96+
'3x0000000000000000000000000000000AA',
9797
],
9898
error: ErrorMessages.demoSecret,
9999
});
@@ -104,11 +104,11 @@ export const astroTurnstile = defineIntegration({
104104
checkKeys({
105105
key: env.TURNSTILE_SITE_KEY,
106106
knownKeys: [
107-
"1x00000000000000000000AA",
108-
"1x00000000000000000000BB",
109-
"2x00000000000000000000AB",
110-
"2x00000000000000000000BB",
111-
"3x00000000000000000000FF",
107+
'1x00000000000000000000AA',
108+
'1x00000000000000000000BB',
109+
'2x00000000000000000000AB',
110+
'2x00000000000000000000BB',
111+
'3x00000000000000000000FF',
112112
],
113113
error: ErrorMessages.demoSiteKey,
114114
});
@@ -123,13 +123,24 @@ export const astroTurnstile = defineIntegration({
123123
// Inject the required Turnstile client-side script if not disabled
124124
if (!disableClientScript) {
125125
verbose && logger.info(loggerStrings.injectScript);
126-
injectScript("page", `import '${name}/client'`);
126+
injectScript('page', `import '${name}/client'`);
127127
}
128128

129+
/*
130+
131+
name: 'Astro Turnstile',
132+
id: 'astro-turnstile-dev-toolbar',
133+
icon: svgIcons.turnstile,
134+
*/
129135
// Add Development Toolbar App for Astro Turnstile testing
130136
if (!disableDevToolbar) {
131137
verbose && logger.info(loggerStrings.addDevToolbarApp);
132-
addDevToolbarApp(resolve("toolbar.ts"));
138+
addDevToolbarApp({
139+
name: 'Astro Turnstile',
140+
id: 'astro-turnstile-dev-toolbar',
141+
icon: svgIcons.turnstile,
142+
entrypoint: resolve('./toolbar.ts'),
143+
});
133144
}
134145

135146
// Inject the required Turnstile server-side route
@@ -145,60 +156,60 @@ export const astroTurnstile = defineIntegration({
145156
addVirtualImports(params, {
146157
name,
147158
imports: {
148-
"virtual:astro-turnstile/config": `export default ${JSON.stringify(
149-
options,
159+
'virtual:astro-turnstile/config': `export default ${JSON.stringify(
160+
options
150161
)}`,
151-
"astro-turnstile:components/TurnstileWidget": `import Widget from '${name}/components/TurnstileWidget'; export default Widget;`,
152-
"astro-turnstile:components/TurnstileForm": `import Form from '${name}/components/TurnstileForm'; export default Form;`,
162+
'astro-turnstile:components/TurnstileWidget': `import Widget from '${name}/components/TurnstileWidget'; export default Widget;`,
163+
'astro-turnstile:components/TurnstileForm': `import Form from '${name}/components/TurnstileForm'; export default Form;`,
153164
},
154165
});
155166

156167
// Log completion message
157168
verbose && logger.info(loggerStrings.setupComplete);
158169
},
159-
"astro:config:done": ({ injectTypes, logger }) => {
170+
'astro:config:done': ({injectTypes, logger}) => {
160171
// Inject the required Turnstile types for the Astro config and components
161172
verbose && logger.info(loggerStrings.injectTypes);
162173
injectTypes(Dts.config);
163174
injectTypes(Dts.components);
164175
},
165-
"astro:server:setup": async ({ toolbar, logger }) => {
176+
'astro:server:setup': async ({toolbar, logger}) => {
166177
// Add a Server Event Listener for the 'sendverify' event from the Astro Dev Toolbar app
167178
if (!disableDevToolbar) {
168179
verbose &&
169-
logger.info("Adding Server Event Listener Dev Toolbar App...");
170-
toolbar.on("sendverify", async (data: { key: string }) => {
180+
logger.info('Adding Server Event Listener Dev Toolbar App...');
181+
toolbar.on('sendverify', async (data: {key: string}) => {
171182
const formData = new FormData();
172183

173184
// Get the Turnstile site token from the environment variables
174185
// or use a dummy token for testing
175186
const siteToken =
176-
env.TURNSTILE_SITE_KEY || "1x00000000000000000000AA";
187+
env.TURNSTILE_SITE_KEY || '1x00000000000000000000AA';
177188

178189
// Add the secret key and token to the form data
179-
formData.append("secret", data.key);
180-
formData.append("response", siteToken);
190+
formData.append('secret', data.key);
191+
formData.append('response', siteToken);
181192

182193
// Send the token to the Turnstile API for verification
183194
try {
184195
const response = await fetch(
185-
"https://challenges.cloudflare.com/turnstile/v0/siteverify",
196+
'https://challenges.cloudflare.com/turnstile/v0/siteverify',
186197
{
187-
method: "POST",
198+
method: 'POST',
188199
body: formData,
189200
headers: {
190-
"content-type": "application/x-www-form-urlencoded",
201+
'content-type': 'application/x-www-form-urlencoded',
191202
},
192-
},
203+
}
193204
);
194205

195206
// Send the verification response back to the Astro Dev Toolbar app
196-
toolbar.send("verifyresponse", {
207+
toolbar.send('verifyresponse', {
197208
success: response.ok,
198209
});
199210
} catch (error) {
200211
// Send the verification response back to the Astro Dev Toolbar app
201-
toolbar.send("verifyresponse", { success: false });
212+
toolbar.send('verifyresponse', {success: false});
202213
}
203214
});
204215
}

package/src/strings.ts

+28-16
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,47 @@
11
export const loggerStrings = {
2-
setup: "Turnstile integration setup...",
2+
setup: 'Turnstile integration setup...',
33
configSiteMissing: `Astro Config Error: 'site' is not defined, it is recommended to define 'site' in your Astro config. (https://docs.astro.build/en/reference/configuration-reference/#site)\nFalling back to 'window.location.origin'.`,
4-
updateConfig: "Updating Astro config with Turnstile environment variables...",
5-
injectScript: "Injecting Turnstile client script...",
4+
updateConfig: 'Updating Astro config with Turnstile environment variables...',
5+
injectScript: 'Injecting Turnstile client script...',
66
injectRoute: (value: string) => `Injecting Turnstile route at ${value}...`,
7-
virtualImports: "Adding Virtual Import modules...",
8-
setupComplete: "Turnstile integration setup complete.",
9-
addDevToolbarApp: "Adding Turnstile Dev Toolbar App for testing...",
10-
injectTypes: "Injecting Turnstile types...",
7+
virtualImports: 'Adding Virtual Import modules...',
8+
setupComplete: 'Turnstile integration setup complete.',
9+
addDevToolbarApp: 'Adding Turnstile Dev Toolbar App for testing...',
10+
injectTypes: 'Injecting Turnstile types...',
1111
};
1212

1313
export const ErrorMessages = {
1414
demoSecret:
15-
"Turnstile Secret Key is set to a demo value. Please replace it with a valid secret key.",
15+
'Turnstile Secret Key is set to a demo value. Please replace it with a valid secret key.',
1616
demoSiteKey:
17-
"Turnstile Site Key is set to a demo value. Please replace it with a valid site key.",
17+
'Turnstile Site Key is set to a demo value. Please replace it with a valid site key.',
1818
};
1919

20-
type astroHooks = import("astro").HookParameters<"astro:config:setup">;
20+
type astroHooks = import('astro').HookParameters<'astro:config:setup'>;
2121

2222
export const envDefaults = {
23-
secretKey: (command: astroHooks["command"]): string | undefined => {
24-
if (command === "dev" || command === "preview") {
25-
return "1x0000000000000000000000000000000AA";
23+
secretKey: (command: astroHooks['command']): string | undefined => {
24+
if (command === 'dev' || command === 'preview') {
25+
return '1x0000000000000000000000000000000AA';
2626
}
2727
return undefined;
2828
},
29-
siteKey: (command: astroHooks["command"]): string | undefined => {
30-
if (command === "dev" || command === "preview") {
31-
return "1x00000000000000000000AA";
29+
siteKey: (command: astroHooks['command']): string | undefined => {
30+
if (command === 'dev' || command === 'preview') {
31+
return '1x00000000000000000000AA';
3232
}
3333
return undefined;
3434
},
3535
};
36+
// Define the SVG icons for the toolbar app
37+
export const svgIcons = {
38+
turnstile: `<svg width="1em" height="1em" viewBox="0 0 54 54" data-icon="turnstile"><symbol id="ai:local:turnstile"><path fill="#e07800" d="M27.315 7.261a19.45 19.45 0 0 0-13.518 4.917l1.23-6.743-3.193-.582-2.162 11.836 11.84 2.16.582-3.193-6.08-1.11a16.173 16.173 0 1 1-4.982 8.064l-3.142-.824A19.478 19.478 0 1 0 27.315 7.261Z"></path><path fill="#e07800" fill-rule="evenodd" d="M38.847 21.919 35.928 19 24.477 30.452 19.923 25.9 17 28.822l7.483 7.484 2.923-2.923-.011-.012L38.847 21.92Z" clip-rule="evenodd"></path></symbol><use xlink:href="#ai:local:turnstile"></use></svg>`,
39+
close: `<svg xmlns="http://www.w3.org/2000/svg" width="2rem" height="2rem" viewBox="0 0 32 32"><path fill="#e07800" d="M16 2C8.2 2 2 8.2 2 16s6.2 14 14 14s14-6.2 14-14S23.8 2 16 2m5.4 21L16 17.6L10.6 23L9 21.4l5.4-5.4L9 10.6L10.6 9l5.4 5.4L21.4 9l1.6 1.6l-5.4 5.4l5.4 5.4z"/></svg>`,
40+
};
41+
42+
// Define the raw HTML elements for the app window
43+
export const windowHtmlElements = {
44+
button: `<button type="submit" style="margin-top: 1rem; padding: 0.5rem 1rem; border: none; background-color: #e07800; color: black; cursor: pointer; border-radius: 0.25rem; margin-bottom: 0;">Test Turnstile Integration</button>`,
45+
successBanner: `<div style="margin-top: 0; padding: 0.5rem 1rem; border: none; background-color: green; color: black; cursor: pointer; border-radius: 0.25rem; text-align: center; width: 520px; position: absolute; bottom: 0.5rem;">Token Verification Successful</div>`,
46+
errorBanner: `<div style="margin-top: 0; padding: 0.5rem 1rem; border: none; background-color: red; color: white; cursor: pointer; border-radius: 0.25rem;" text-align: center; width: 520px; position: absolute; bottom: 0.5rem;">"Unable to verify token"</div>`,
47+
};

0 commit comments

Comments
 (0)