Skip to content
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
1 change: 1 addition & 0 deletions packages/void/src/cli/cf-build-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { WORKER_CONDITIONS } from './worker-conditions.ts';
export interface CfBuildOutput {
directory: string;
assetsDirectory?: string;
forwardAssetRedirects?: boolean;
activeSecrets?: {
versionId: string;
bindings: ReadonlyArray<{ name: string; type: 'secret_text' | 'secret_key' }>;
Expand Down
21 changes: 15 additions & 6 deletions packages/void/src/cli/cf-version-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1005,12 +1005,15 @@ async function ensureContainerApplications(options: {
}
}

function readAssetHeaders(output: CfBuildOutput): string | undefined {
function readAssetRuleFile(
output: CfBuildOutput,
name: '_headers' | '_redirects',
): string | undefined {
if (!output.assetsDirectory) {
return undefined;
}
try {
return readFileSync(join(getWorkerAssetsDir(output.directory), '_headers'), 'utf8');
return readFileSync(join(getWorkerAssetsDir(output.directory), name), 'utf8');
} catch (cause) {
if (cause instanceof Error && 'code' in cause && cause.code === 'ENOENT') {
return undefined;
Expand Down Expand Up @@ -1251,12 +1254,18 @@ export async function uploadPinnedCloudflareVersion(options: {
).toString('base64'),
});
}
const assetHeaders = readAssetHeaders(options.output);
if (assetHeaders !== undefined) {
for (const name of ['_headers', '_redirects'] as const) {
if (name === '_redirects' && !options.output.forwardAssetRedirects) {
continue;
}
const content = readAssetRuleFile(options.output, name);
if (content === undefined) {
continue;
}
modules.push({
name: '_headers',
name,
content_type: 'text/plain',
content_base64: Buffer.from(assetHeaders).toString('base64'),
content_base64: Buffer.from(content).toString('base64'),
});
}
await preflightWorkflowExports({
Expand Down
26 changes: 18 additions & 8 deletions packages/void/src/cli/deploy-cloudflare-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,14 +337,24 @@ export async function buildCloudflareWorker(input: {
const generatedConfigPath = (
deps.resolveGeneratedConfigPath ?? resolveGeneratedDeployConfigPathDefault
)(root);
const prepareBuildOutput = () =>
frameworkPreset?.cloudflareArtifact === 'worker-output'
? prepareCfFrameworkBuildOutput({
projectRoot: root,
configPath: generatedConfigPath,
accountId,
})
: prepareCfBuildOutput(dirname(generatedConfigPath), accountId, undefined, root);
const prepareBuildOutput = async () => {
const output =
frameworkPreset?.cloudflareArtifact === 'worker-output'
? await prepareCfFrameworkBuildOutput({
projectRoot: root,
configPath: generatedConfigPath,
accountId,
})
: await prepareCfBuildOutput(dirname(generatedConfigPath), accountId, undefined, root);
if (
output &&
frameworkPreset !== undefined &&
(voidConfig.inference?.appType ?? 'framework') === 'framework'
) {
output.forwardAssetRedirects = true;
}
return output;
};
if (usesCf) {
// Validate the exact upload format before changing a remote database or secret.
const preflight = await prepareBuildOutput();
Expand Down
48 changes: 27 additions & 21 deletions packages/void/test/unit/cf-version-runner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -779,15 +779,18 @@ it.each(
],
['user-authored', authoredAssetHeaders],
['empty', ''],
['custom ignore negation', authoredAssetHeaders],
['framework redirects', authoredAssetHeaders],
['plain Worker redirects', authoredAssetHeaders],
['missing', undefined],
] as const
).flatMap(([kind, headers]) =>
[false, true].map((workerFirst) => ({ kind, headers, workerFirst })),
),
)(
'uploads generated and user-authored _headers files with pinned secrets ($kind, worker-first=$workerFirst)',
'uploads asset routing files with pinned secrets ($kind, worker-first=$workerFirst)',
async ({ kind, headers, workerFirst }) => {
const forwardAssetRedirects = kind === 'framework redirects';
const redirects = '/old /new 302\n';
const runWorkerFirst = workerFirst ? ['/**', '!/assets/*'] : undefined;
const prepared = await output({
secrets: { required: ['AUTH_SECRET'] },
Expand All @@ -799,18 +802,18 @@ it.each(
},
});
try {
if (forwardAssetRedirects) {
prepared.forwardAssetRedirects = true;
}
if (headers !== undefined) {
writeFileSync(join(getWorkerAssetsDir(prepared.directory), '_headers'), headers);
}
if (kind === 'custom ignore negation') {
if (forwardAssetRedirects || kind === 'plain Worker redirects') {
writeFileSync(
join(getWorkerAssetsDir(prepared.directory), '.assetsignore'),
'private.txt\n!/_headers\n!/_redirects\n!/.assetsignore\n',
);
writeFileSync(
join(getWorkerAssetsDir(prepared.directory), '_redirects'),
'/old /new 302\n',
);
writeFileSync(join(getWorkerAssetsDir(prepared.directory), '_redirects'), redirects);
}
await pinActiveWorkerSecrets({
output: prepared,
Expand Down Expand Up @@ -863,20 +866,23 @@ it.each(
...(runWorkerFirst === undefined ? {} : { run_worker_first: runWorkerFirst }),
},
});
const modules = (body.modules as Array<{ name: string }>).filter(({ name }) =>
['_headers', '_redirects', '.assetsignore'].includes(name),
);
expect(modules).toEqual(
headers !== undefined
? [
{
name: '_headers',
content_type: 'text/plain',
content_base64: Buffer.from(headers).toString('base64'),
},
]
: [],
);
const modules = (
body.modules as Array<{ name: string; content_type: string; content_base64: string }>
)
.filter(({ name }) => ['_headers', '_redirects', '.assetsignore'].includes(name))
.map(({ name, content_type, content_base64 }) => ({
name,
content_type,
content: Buffer.from(content_base64, 'base64').toString('utf8'),
}));
expect(modules).toEqual([
...(headers === undefined
? []
: [{ name: '_headers', content_type: 'text/plain', content: headers }]),
...(forwardAssetRedirects
? [{ name: '_redirects', content_type: 'text/plain', content: redirects }]
: []),
]);
} finally {
await prepared.dispose();
}
Expand Down
46 changes: 46 additions & 0 deletions packages/void/test/unit/cloudflare-deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1217,6 +1217,52 @@ it('reaches the native Worker build for VitePress with a configured Void backend
}
});

it.each([undefined, 'void'] as const)(
'selects Versions API asset redirects with a vinext dependency and appType %s',
async (appType) => {
const config = { name: 'site', account_id: 'personal', compatibility_date: '2026-02-24' };
const root = makeProject({
'package.json': JSON.stringify({ name: 'site', dependencies: { void: '*', vinext: '*' } }),
'void.config.ts': `export default ${JSON.stringify({
inference: { appType, build: 'node build.mjs' },
cloudflare: config,
})};`,
'dist/ssr/wrangler.json': JSON.stringify({ ...config, main: 'index.js' }),
'dist/ssr/index.js': 'export default { fetch: () => new Response("hello") };',
});
const [cloudflareDeployHelpers, cfVersionRunner] = await Promise.all([
import('../../src/cli/deploy-cloudflare-helpers.ts'),
import('../../src/cli/cf-version-runner.ts'),
]);
const connect = cloudflareDeployHelpers.connectCloudflareDeployAccount;
const connectAccount = vi
.spyOn(cloudflareDeployHelpers, 'connectCloudflareDeployAccount')
.mockImplementation(async (options) => {
const connection = await connect(options);
return connection && { ...connection, usesCf: true, cfUploaderIsPinned: () => true };
});
const pinSecrets = vi.spyOn(cfVersionRunner, 'createActiveSecretPinner');
const { deps } = harness({
activateVersion: async () => ({
ok: true,
versionId: '22222222-2222-4222-8222-222222222222',
previewUrl: 'https://site.example.com',
previousVersionId: null,
}),
});
try {
await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps);
expect(pinSecrets).toHaveBeenCalledOnce();
expect(pinSecrets.mock.calls[0][0].output?.forwardAssetRedirects).toBe(
appType === undefined ? true : undefined,
);
} finally {
pinSecrets.mockRestore();
connectAccount.mockRestore();
}
},
);

describe('existing Cloudflare site handoff', () => {
const existing = {
versionId: 'original',
Expand Down