Skip to content
Draft
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
7 changes: 7 additions & 0 deletions .changeset/sveltekit-version-before-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@aws-cdk-blocks/hosting": patch
"@aws-cdk-blocks/core": patch
"@aws-cdk-blocks/create-blocks-app": patch
---

A SvelteKit 3 project (what `npx sv create` scaffolds) is now refused before any build runs. `Hosting` checks the installed `@sveltejs/kit` before it runs `buildCommand`, and `UnsupportedSvelteKitVersionError` names the SvelteKit 2 versions to pin (`@sveltejs/kit@^2`, `@sveltejs/adapter-node@^5`, `@sveltejs/vite-plugin-svelte@^5`, `vite@^6`). `create-blocks-app .` stops before it writes anything in a SvelteKit 3 project and prints the same versions. The Hosting README now states the supported range: SvelteKit 2 (`>=2.0.0 <3.0.0`). The new `assertFrameworkSupported(framework, projectDir)` from `@aws-cdk-blocks/hosting/adapters` runs these build-free checks.
2 changes: 1 addition & 1 deletion packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ new Hosting(stack, 'Web', {

The `framework` option selects the frontend type: `'spa' | 'static' | 'nextjs'`. When omitted, the framework is auto-detected by reading your app's OWN `package.json` (not `node_modules`): a `next` dependency → `nextjs`; otherwise `spa`; and `static` when there is no `package.json`. Set `framework: 'spa'` explicitly to override auto-detection — e.g. when a stray `next` dependency would otherwise trigger an unwanted Next.js/OpenNext build. Full reference lives in the source JSDoc.

`buildCommand` runs during synth, with `BLOCKS_API_URL` set to the backend the frontend talks to, and then the framework adapter runs its own build (OpenNext, Nitro, Astro, SvelteKit). Two synths skip both:
`buildCommand` runs during synth, with `BLOCKS_API_URL` set to the backend the frontend talks to, and then the framework adapter runs its own build (OpenNext, Nitro, Astro, SvelteKit). Before `buildCommand` runs, `Hosting` refuses a framework version its adapter doesn't support, so a deploy doesn't wait for a build that is then rejected: SvelteKit 3 fails with `UnsupportedSvelteKitVersionError` (Hosting supports SvelteKit 2; see the `@aws-cdk-blocks/hosting` README). Two synths skip both:

- **Destroy.** `npm run destroy` and `npm run sandbox:destroy` don't deploy the frontend, so `Hosting` reuses the build output already on disk instead of building. It builds only when there is no output, for example on a fresh clone. Each framework adapter checks the output it deploys: a Next.js destroy reuses the `.open-next/` output of an earlier deploy, and with only `.next/` (after a plain `next build`) OpenNext still builds, because the synth needs its output. An exported `BLOCKS_SKIP_FRONTEND_BUILD=1` doesn't apply to a destroy.
- **A deploy you ask to run on the existing build.** Set `BLOCKS_SKIP_FRONTEND_BUILD=1`, for example `BLOCKS_SKIP_FRONTEND_BUILD=1 npm run deploy`, to deploy what is already in the build output directory. Nothing is built, and a missing build output (the output directory, or the output the framework adapter deploys, such as Next.js's `.open-next/`) fails the synth with a message naming the variable. The build bakes in `BLOCKS_API_URL`, so only reuse a build made for the same backend; a deploy never reuses one on its own.
Expand Down
51 changes: 51 additions & 0 deletions packages/core/src/hosting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2265,7 +2265,7 @@
([id, r]) => r.Type === 'AWS::CloudFormation::CustomResource' && /RouteStoreKeys/.test(id),
);
assert.ok(kvKeys, 'expected a RouteStoreKeys custom resource');
const entries = JSON.parse(kvKeys![1].Properties.Entries);

Check warning on line 2268 in packages/core/src/hosting.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
const meta = JSON.parse(entries.meta);
return meta.bp as string;
};
Expand Down Expand Up @@ -4473,6 +4473,57 @@
});
});

// An unsupported framework version is refused before `buildCommand` runs, so
// the user doesn't wait for a full build that the adapter then rejects.
describe('Hosting — unsupported framework version', () => {
let tmpDir: string;
// Records that it ran, then writes the adapter-node output a real build would.
const BUILD = `node -e "const f=require('fs');f.writeFileSync('built.txt','1');f.mkdirSync('build',{recursive:true})"`;

beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bb-hosting-kit3-'));
fs.writeFileSync(
path.join(tmpDir, 'package.json'),
JSON.stringify({ name: 'kit3', devDependencies: { '@sveltejs/kit': '^3.2.0' } }),
);
const kitDir = path.join(tmpDir, 'node_modules', '@sveltejs', 'kit');
fs.mkdirSync(kitDir, { recursive: true });
fs.writeFileSync(path.join(kitDir, 'package.json'), JSON.stringify({ name: '@sveltejs/kit', version: '3.3.1' }));
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});

it('refuses SvelteKit 3 before running buildCommand', () => {
const stack = new Stack(new App(), 'Kit3Stack');
assert.throws(
() =>
new Hosting(stack, 'Hosting', {
root: tmpDir,
api: MOCK_API,
framework: 'sveltekit',
buildCommand: BUILD,
buildOutputDir: 'build',
}),
(err: Error) => {
assert.ok(err instanceof HostingError, 'expected a HostingError');
assert.strictEqual(err.code, 'UnsupportedSvelteKitVersionError');
return true;
},
);
assert.ok(!fs.existsSync(path.join(tmpDir, 'built.txt')), 'buildCommand should not run');
});

it('refuses a detected SvelteKit 3 project the same way', () => {
const stack = new Stack(new App(), 'Kit3DetectStack');
assert.throws(
() => new Hosting(stack, 'Hosting', { root: tmpDir, api: MOCK_API, buildCommand: BUILD }),
/UnsupportedSvelteKitVersionError|SvelteKit 3\.3\.1/,
);
assert.ok(!fs.existsSync(path.join(tmpDir, 'built.txt')), 'buildCommand should not run');
});
});

// A deploy synthesizes with `NODE_OPTIONS=--conditions=cdk`. `buildCommand`
// must run without that condition, so a build that loads `@aws-cdk-blocks/*`
// doesn't get their CDK constructs, but with the user's other NODE_OPTIONS.
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/hosting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import type { DeployManifest, FrameworkType, KindStoreOptions, RouteBehavior } from '@aws-cdk-blocks/hosting/constructs';
import {
appBuildEnv,
assertFrameworkSupported,
detectFramework,
type FrameworkAdapterFn,
getAdapter,
Expand Down Expand Up @@ -1192,6 +1193,11 @@
// still reports the framework it was deploying.
writeFrameworkSink(framework);

// Refuse an unsupported framework version (e.g. SvelteKit 3) before the
// build below, so the user doesn't wait for a build the adapter rejects.
// A custom adapter owns its own checks.
if (!props.customAdapter) assertFrameworkSupported(framework, root);

// ── 2. Optionally run the build ──────────────────────────────
// A destroy reuses an existing build, and `BLOCKS_SKIP_FRONTEND_BUILD=1`
// makes a deploy reuse it (see common/frontend-build.ts). The adapter gets
Expand Down Expand Up @@ -1226,7 +1232,7 @@
stdio: 'inherit',
env: buildEnv,
});
} catch (error) {

Check warning on line 1235 in packages/core/src/hosting.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/correctness/noUnusedVariables

This variable error is unused.
throw new Error(
`Frontend build failed: ${props.buildCommand}\n` +
`Ensure the build command is correct and all dependencies are installed.`,
Expand Down
2 changes: 2 additions & 0 deletions packages/create-blocks-app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ This writes `cdk-blocks/tsconfig.json`, a TypeScript project that checks the bac

In an npm workspaces monorepo, the app's `cdk-blocks/` folder has to be a workspace of the monorepo root too: npm installs the app's dependencies at the root and does not read the app's own `"workspaces": ["cdk-blocks"]`. When the app is a workspace of an enclosing root that does not list `<app>/cdk-blocks`, `create-blocks-app` stops before it writes anything and prints the `"workspaces"` entry to add; add it and run the command again.

A SvelteKit project must be on SvelteKit 2 (`@sveltejs/kit` `>=2.0.0 <3.0.0`), which the Hosting construct deploys. SvelteKit 3, which `npx sv create` scaffolds today, is not supported yet: `create-blocks-app` stops before it writes anything and prints the SvelteKit 2 versions to pin (`npm install -D @sveltejs/kit@^2 @sveltejs/adapter-node@^5 @sveltejs/vite-plugin-svelte@^5 vite@^6`, with the SvelteKit config in `svelte.config.js`). It reads the installed `@sveltejs/kit` when `node_modules` has it, and the lowest version of the `package.json` range otherwise. Support for SvelteKit 3 is tracked in [#984](https://github.com/aws/cdk-blocks/issues/984).

It also adds to your `.gitignore` (or creates one): the AWS CDK Blocks build and local-data paths, secret and key-material patterns such as `.env` and `*.pem`, and `node_modules` unless a line such as `node_modules`, `node_modules/` or `/node_modules` already ignores it. A `.gitignore` that un-ignores it (`!node_modules`) is left as it is. Lines you already have are kept, and the CLI prints the ones it adds.

### Add Blocks to an Amplify Gen 2 Project
Expand Down
42 changes: 42 additions & 0 deletions packages/create-blocks-app/src/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@
// The Node client resolves BLOCKS_API_URL before it reads .cdk-blocks-sandbox/config.json. A test that
// left the choice to that file sent its sign-ups and writes to the stack a deploy had just recorded.
const templatesDir = join(__dirname, '..', 'templates');
const pin = 'process.env.BLOCKS_API_URL = `${testUrl ?? `http://localhost:${serverPort}`}/cdk-blocks/api`;';

Check warning on line 339 in packages/create-blocks-app/src/cli.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/suspicious/noTemplateCurlyInString

Unexpected template string placeholder.
const problems: string[] = [];
for (const entry of readdirSync(templatesDir, { withFileTypes: true })) {
const testPath = join(templatesDir, entry.name, 'test', 'e2e.test.ts');
Expand Down Expand Up @@ -788,7 +788,7 @@
const suffix = parts.pop();
const namepart = parts.join('-');
assert.ok(namepart.length <= 16, `name portion "${namepart}" should be at most 16 chars`);
assert.strictEqual(suffix!.length, 6, 'random suffix should be 6 chars');

Check warning on line 791 in packages/create-blocks-app/src/cli.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
assert.match(config.stackId, /^[a-z][a-z0-9-]*$/i, 'stackId must be CDK/CFN-safe');
} finally {
rmSync(tmpDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
Expand Down Expand Up @@ -887,7 +887,7 @@
const config = JSON.parse(readFileSync(join(tmpDir, '.cdk-blocks', 'config.json'), 'utf-8'));
assert.ok(config.stackId, '.cdk-blocks/config.json should have a stackId');
assert.match(config.stackId, /^[a-z][a-z0-9-]*$/i, 'stackId must be CDK/CFN-safe');
assert.strictEqual(config.stackId.split('-').pop()!.length, 6, 'suffix should be 6 chars');

Check warning on line 890 in packages/create-blocks-app/src/cli.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
// The bare template's commented examples import zod, so a fresh app must depend on it
// at the template's range (read from the template — dependency bumps change it).
const templateZod = JSON.parse(readFileSync(join(__dirname, '../templates/bare/package.json'), 'utf-8')).dependencies?.zod;
Expand Down Expand Up @@ -1044,6 +1044,48 @@
}
});

it('refuses an existing SvelteKit 3 project before it writes anything', () => {
// Hosting deploys SvelteKit 2 only; `npx sv create` scaffolds SvelteKit 3.
const tmpDir = mkdtempSync(join(tmpdir(), 'create-blocks-app-kit3-'));
const pkg = JSON.stringify({ name: 'my-svelte-app', version: '0.0.1', devDependencies: { '@sveltejs/kit': '^3.2.0', vite: '^8.0.0' } });
writeFileSync(join(tmpDir, 'package.json'), pkg);
try {
const result = run(['.', '-y', '--skip-install'], tmpDir);
assert.strictEqual(result.exitCode, 1, result.stdout);
assert.match(result.stderr, /SvelteKit 3 is not supported yet/);
assert.ok(result.stderr.includes('@sveltejs/kit@^2 @sveltejs/adapter-node@^5 @sveltejs/vite-plugin-svelte@^5 vite@^6'), result.stderr);
assert.ok(result.stderr.includes('https://github.com/aws/cdk-blocks/issues/984'), result.stderr);
assert.match(result.stderr, /Nothing was written/);
assert.strictEqual(readFileSync(join(tmpDir, 'package.json'), 'utf-8'), pkg);
assert.deepStrictEqual(readdirSync(tmpDir), ['package.json'], 'nothing is written');
} finally {
rmSync(tmpDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
}
});

it('reads the installed SvelteKit version over the package.json range', () => {
const tmpDir = mkdtempSync(join(tmpdir(), 'create-blocks-app-kit-installed-'));
const kitDir = join(tmpDir, 'node_modules', '@sveltejs', 'kit');
mkdirSync(kitDir, { recursive: true });
try {
// A non-semver range: the installed 3.x decides.
writeFileSync(join(tmpDir, 'package.json'), JSON.stringify({ name: 'kit-latest', devDependencies: { '@sveltejs/kit': 'latest' } }));
writeFileSync(join(kitDir, 'package.json'), JSON.stringify({ name: '@sveltejs/kit', version: '3.3.1' }));
const refused = run(['.', '-y', '--skip-install'], tmpDir);
assert.strictEqual(refused.exitCode, 1, refused.stdout);
assert.match(refused.stderr, /SvelteKit 3 is not supported yet \(installed: 3\.3\.1\)/);
assert.ok(!existsSync(join(tmpDir, 'cdk-blocks')));

// SvelteKit 2 installed: the backend is added as usual.
writeFileSync(join(kitDir, 'package.json'), JSON.stringify({ name: '@sveltejs/kit', version: '2.70.3' }));
const added = run(['.', '-y', '--skip-install'], tmpDir);
assert.strictEqual(added.exitCode, 0, added.stderr);
assert.ok(existsSync(join(tmpDir, 'cdk-blocks', 'index.ts')));
} finally {
rmSync(tmpDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
}
});

it('gives an Amplify app without Next.js the default template\'s backend tsconfig', () => {
const tmpDir = join(__dirname, '../.test-amplify-tsconfig');
mkdirSync(join(tmpDir, 'amplify'), { recursive: true });
Expand Down Expand Up @@ -1195,7 +1237,7 @@
assert.strictEqual(result.exitCode, 0);
assert.match(result.stdout, /AWS CDK Blocks app created/);
assert.doesNotMatch(result.stdout, /Installing dependencies/);
assert.match(result.stdout, /\n npm install\n/);

Check warning on line 1240 in packages/create-blocks-app/src/cli.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/complexity/noAdjacentSpacesInRegex

This regular expression contains unclear uses of consecutive spaces.
assert.strictEqual(existsSync(join(targetDir, 'node_modules')), false);
} finally {
rmSync(tmpDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
Expand Down Expand Up @@ -1378,9 +1420,9 @@
// AGENTS.md shared-resource overlay.
const written = new Map<string, string>(); // written name -> source (template or overlay)
written.set('AGENTS.md', 'shared resource overlay (resources/AGENTS.md)');
for (const entry of readdirSync(templatesDir!, { withFileTypes: true })) {

Check warning on line 1423 in packages/create-blocks-app/src/cli.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
if (!entry.isDirectory()) continue;
for (const name of readdirSync(join(templatesDir!, entry.name))) {

Check warning on line 1425 in packages/create-blocks-app/src/cli.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
const writtenName = name === 'gitignore' ? '.gitignore' : name;
if (!written.has(writtenName)) written.set(writtenName, `template "${entry.name}"`);
}
Expand Down
38 changes: 38 additions & 0 deletions packages/create-blocks-app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
const collected = new Set<string>();
const queue: string[] = [...seedPkgNames];
while (queue.length > 0) {
const name = queue.shift()!;

Check warning on line 72 in packages/create-blocks-app/src/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
if (collected.has(name) || !monorepoPkgs.has(name)) continue;
collected.add(name);
const pkgName = blocksPackageDir(name);
Expand Down Expand Up @@ -232,7 +232,7 @@
let patterns: string[] = [];
let excluded: string[] = [];
for (const entry of workspaces) {
const bangs = /^!*/.exec(entry)![0].length;

Check warning on line 235 in packages/create-blocks-app/src/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/noNonNullAssertion

Forbidden non-null assertion.
const pattern = entry.slice(bangs).replace(/^\.?\/+/, '');
if (bangs % 2 === 1) {
excluded.push(pattern);
Expand Down Expand Up @@ -1083,10 +1083,48 @@
return Object.keys(kept).length > 0 ? { dev: kept } : undefined;
}

/**
* The major version of the project's `@sveltejs/kit`: the installed one when
* `node_modules` has it, else the lowest major its `package.json` range allows
* (`^3.2.0` is 3). `undefined` when the project doesn't use SvelteKit, or the
* range names no version (`latest`, `workspace:*`).
*/
async function svelteKitMajor(targetDir: string, pkg: PackageDeps): Promise<{ major: number; installed?: string } | undefined> {
const installed: unknown = await readFile(join(targetDir, 'node_modules', '@sveltejs', 'kit', 'package.json'), 'utf-8')
.then((text) => JSON.parse(text).version, () => undefined);
if (typeof installed === 'string' && /^\d+\./.test(installed)) {
return { major: Number.parseInt(installed, 10), installed };
}
const range = pkg.devDependencies?.['@sveltejs/kit'] ?? pkg.dependencies?.['@sveltejs/kit'];
const match = typeof range === 'string' ? /^\s*(?:[~^]|>=?|=)?\s*v?(\d+)/.exec(range) : null;
return match ? { major: Number.parseInt(match[1], 10) } : undefined;
}

/**
* Stops before anything is written when the project uses a SvelteKit version
* the Hosting construct can't deploy (SvelteKit 3, which `npx sv create`
* scaffolds). Synth would refuse it too, so adding the backend now would only
* leave the project half set up. Prints the versions to pin instead.
*/
async function refuseUnsupportedSvelteKit(targetDir: string): Promise<void> {
const pkg: PackageDeps = JSON.parse(await readFile(join(targetDir, 'package.json'), 'utf-8'));
const kit = await svelteKitMajor(targetDir, pkg);
if (!kit || kit.major < 3) return;
console.error(`Error: SvelteKit ${kit.major} is not supported yet${kit.installed ? ` (installed: ${kit.installed})` : ''}.`);
console.error('AWS CDK Blocks Hosting deploys SvelteKit 2 (@sveltejs/kit >=2.0.0 <3.0.0) with');
console.error('@sveltejs/adapter-node 5 and the SvelteKit config in svelte.config.js.');
console.error('');
console.error('Pin the SvelteKit 2 toolchain, move the config back to svelte.config.js, then run this command again:');
console.error(' npm install -D @sveltejs/kit@^2 @sveltejs/adapter-node@^5 @sveltejs/vite-plugin-svelte@^5 vite@^6');
console.error('SvelteKit 3 support is tracked in https://github.com/aws/cdk-blocks/issues/984. Nothing was written.');
process.exit(1);
}

async function integrateWithExistingProject(targetDir: string, templateName = 'default', skipConfirm = false, skipInstall = false) {
if (templateName === 'amplify') {
throw new Error('The amplify template requires an existing Amplify Gen 2 project (amplify/backend.ts).');
}
await refuseUnsupportedSvelteKit(targetDir);
const workspaceRoot = await enclosingWorkspaceRoot(targetDir);
console.log('\n🔍 Detected existing project (package.json found)\n');
console.log('This will add an AWS CDK Blocks backend to your project:');
Expand Down Expand Up @@ -1156,9 +1194,9 @@
devDeps: {
'aws-cdk-lib': tplDevDeps['aws-cdk-lib'] || '2.257.0',
'aws-cdk': tplDevDeps['aws-cdk'] || '^2.1147.0',
'constructs': tplDevDeps['constructs'] || '^10.6.0',

Check notice on line 1197 in packages/create-blocks-app/src/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/complexity/useLiteralKeys

The computed expression can be simplified without the use of a string literal.
'tsx': tplDevDeps['tsx'] || '^4.7.0',

Check notice on line 1198 in packages/create-blocks-app/src/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/complexity/useLiteralKeys

The computed expression can be simplified without the use of a string literal.
'esbuild': tplDevDeps['esbuild'] || '^0.27.1',

Check notice on line 1199 in packages/create-blocks-app/src/index.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/complexity/useLiteralKeys

The computed expression can be simplified without the use of a string literal.
'@types/node': tplDevDeps['@types/node'] || '^22.12.0',
},
scripts: { ...tasks, 'dev:server': tasks.dev },
Expand Down
20 changes: 19 additions & 1 deletion packages/hosting/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ new HostingConstruct(stack, 'Hosting', { manifest });
| `nextjsAdapter` | `{ projectDir, configPath?, skipBuild? }` | A Next.js app, built with OpenNext. `configPath` is a custom `open-next.config.ts`, relative to `projectDir`. |
| `nuxtAdapter`, `nitroAdapter` | `{ projectDir, preset?, buildCommand?, skipBuild? }` | A Nuxt app, or another Nitro app. `preset` overrides the Nitro preset. |
| `astroAdapter` | `{ projectDir, buildCommand?, skipBuild?, bodySizeLimit? }` | An Astro app. `bodySizeLimit` is the largest request body in bytes (default 20 MB). |
| `sveltekitAdapter` | `{ projectDir, buildCommand?, skipBuild?, bodySizeLimit? }` | A SvelteKit app. `bodySizeLimit` as for Astro. |
| `sveltekitAdapter` | `{ projectDir, buildCommand?, skipBuild?, bodySizeLimit? }` | A SvelteKit 2 app (see [SvelteKit: the supported version](#sveltekit-the-supported-version)). `bodySizeLimit` as for Astro. |
| `spaAdapter` | `projectDir, { buildOutputDir?, spaFallback? }` | An already built single-page app in `dist/`, `build/` or `out/`. `spaFallback: false` declares a multi-page static site. |

`skipBuild: true` reuses an existing build output.
Expand Down Expand Up @@ -625,6 +625,23 @@ const blocksStack = await BlocksStack.create(app, stackName, {
- `npm run destroy` passes no stack selection, so the CDK CLI refuses to
destroy an app with more than one top-level stack.

## SvelteKit: the supported version

The SvelteKit adapter supports **SvelteKit 2 only**: `@sveltejs/kit`
`>=2.0.0 <3.0.0`, built with `@sveltejs/adapter-node` 5, with the SvelteKit
config in `svelte.config.js`.

- SvelteKit 3, which `npx sv create` scaffolds today, is not supported yet.
Synth refuses it with `UnsupportedSvelteKitVersionError` before it runs the
app's build. Support is tracked in
[#984](https://github.com/aws/cdk-blocks/issues/984).
- To deploy a project scaffolded with SvelteKit 3, pin the SvelteKit 2
toolchain and move the SvelteKit config back to `svelte.config.js`:

```bash
npm install -D @sveltejs/kit@^2 @sveltejs/adapter-node@^5 @sveltejs/vite-plugin-svelte@^5 vite@^6
```

## SSR compute: Lambda or Lambda Web Functions

By default the SSR server runs on a Lambda function behind an API Gateway REST
Expand Down Expand Up @@ -1332,6 +1349,7 @@ synth. `error.name` and `error.code` hold the name in the table, and
| `UnsupportedComputeFrontDoorError` | `compute.type: 'web-function'` behind a door other than CloudFront. |
| `UnsupportedFrontDoorError` | `frontDoor` is not a front door, `'none'` is set for an app with a server, or a custom door fails the wiring check. |
| `UnsupportedFrontDoorSettingError` | The door kind doesn't implement a setting. |
| `UnsupportedSvelteKitVersionError` | The installed `@sveltejs/kit` is not SvelteKit 2 (`>=2.0.0 <3.0.0`). Thrown before the app's build runs. |
| `UnsupportedRoutePatternError` | ALB: one pattern has more than six wildcards. API Gateway: a backend route has a wildcard other than one trailing `/*`. |
| `WafRegionError` | A CloudFront-scoped WAF is enabled in a known region outside us-east-1 and region validation isn't skipped. |
| `WebFunctionPolicyAlreadySetError` | `allowCloudFrontInvoke()` was called twice on the same Web Function. |
Expand Down
41 changes: 41 additions & 0 deletions packages/hosting/src/adapters/adapters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@

import { afterEach, beforeEach, describe, it } from 'node:test';
import assert from 'node:assert';
import * as fs from 'fs';

Check notice on line 6 in packages/hosting/src/adapters/adapters.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/useNodejsImportProtocol

A Node.js builtin module should be imported with the node: protocol.
import * as path from 'path';

Check notice on line 7 in packages/hosting/src/adapters/adapters.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/useNodejsImportProtocol

A Node.js builtin module should be imported with the node: protocol.
import * as os from 'os';

Check notice on line 8 in packages/hosting/src/adapters/adapters.test.ts

View workflow job for this annotation

GitHub Actions / Local Build and Checks

lint/style/useNodejsImportProtocol

A Node.js builtin module should be imported with the node: protocol.
import {
assertFrameworkSupported,
detectFramework,
getAdapter,
readProjectDeps,
Expand Down Expand Up @@ -270,3 +271,43 @@
);
});
});

void describe('assertFrameworkSupported', () => {
let tmp: string;
beforeEach(() => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'adapters-supported-'));
});
afterEach(() => {
fs.rmSync(tmp, { recursive: true, force: true });
});

void it('refuses SvelteKit 3 without building anything', () => {
writePackageJson(tmp, { devDependencies: { '@sveltejs/kit': '^3.2.0' } });
installFakePackage(tmp, '@sveltejs/kit', '3.3.1');
assert.throws(
() => assertFrameworkSupported('sveltekit', tmp),
(error: Error) => {
assert.strictEqual(error.name, 'UnsupportedSvelteKitVersionError');
assert.match(error.message, /3\.3\.1/);
return true;
},
);
assert.deepStrictEqual(
fs.readdirSync(tmp).sort(),
['node_modules', 'package.json'],
'the check writes nothing into the project',
);
});

void it('accepts SvelteKit 2', () => {
writePackageJson(tmp, { devDependencies: { '@sveltejs/kit': '^2.15.0' } });
installFakePackage(tmp, '@sveltejs/kit', '2.15.0');
assert.doesNotThrow(() => assertFrameworkSupported('sveltekit', tmp));
});

void it('does nothing for a framework without a version check', () => {
writePackageJson(tmp, { dependencies: { react: '^18.0.0' } });
assert.doesNotThrow(() => assertFrameworkSupported('spa', tmp));
assert.doesNotThrow(() => assertFrameworkSupported('static', tmp));
});
});
Loading
Loading