blogwright 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
1
  {
2
- "hash": "cf96a6a02e97"
2
+ "hash": "0dbb8d92ec61"
3
3
  }
package/dist/commands.js CHANGED
@@ -6,7 +6,7 @@ import { applyGraph, destroyGraph } from './graph.js';
6
6
  import { forgetLiveRelease, markLiveReleasePublishing, recordLiveRelease, } from './live-release.js';
7
7
  import { assertEnvUnlocked, withEnvLock } from './lock.js';
8
8
  import { clearRunningMicrovms } from './microvms.js';
9
- import { buildNodes, reconcileBuilderImage, reconcileResponseHeadersOnDeploy } from './nodes.js';
9
+ import { buildNodes, reconcileBuilderImage, reconcileResponseHeadersOnDeploy, reconcileRouterFunction, } from './nodes.js';
10
10
  import { describeInvalidation, formatDuration, logStatusEntries, historyHasRevisions, historyStatus, historyTime, NO_REVISION, renderHistoryTable, renderSummary, } from './render.js';
11
11
  import { rollbackToStagedRelease, runAfterPublish } from './releases.js';
12
12
  import { buildRepoZip, COMMIT_FILE, listRepoFiles } from './repo.js';
@@ -292,6 +292,8 @@ async function deployLocked(ctx, opts, { cwd, hash, startedAt }) {
292
292
  artifact = await recordDeployArtifact(ctx, hash, artifactKey);
293
293
  await noteLiveRelease(ctx, artifact, 'deploy');
294
294
  }
295
+ // The content is live, so a redirect to a new page never answers before the page exists.
296
+ const router = await reconcileRouterFunction(ctx);
295
297
  // The site is live - plugins' post-deploy steps (the pds sync, for one) run now.
296
298
  await opts.afterDeploy(ctx);
297
299
  const url = siteBaseUrl(ctx);
@@ -303,10 +305,22 @@ async function deployLocked(ctx, opts, { cwd, hash, startedAt }) {
303
305
  : hash,
304
306
  },
305
307
  { label: 'environment', value: ctx.env },
306
- { label: 'source', value: `${fileCount} files, ${(zipBytes / 1024).toFixed(0)} KiB` },
308
+ {
309
+ label: 'source',
310
+ value: `${fileCount} files, ${(zipBytes / 1024).toFixed(0)} KiB`,
311
+ },
307
312
  { label: 'build', value: formatDuration(manifest.durationMs) },
308
313
  ...(artifact ? [{ label: 'release', value: describeRelease(artifact) }] : []),
309
314
  { label: 'invalidated', value: describeInvalidation(invalidation) },
315
+ ...(router.status === 'not-bootstrapped' ||
316
+ (router.redirects === 0 && router.status === 'unchanged')
317
+ ? []
318
+ : [
319
+ {
320
+ label: 'redirects',
321
+ value: `${router.redirects} (router function ${router.status})`,
322
+ },
323
+ ]),
310
324
  ...(url ? [{ label: 'site', value: colors.cyan(url) }] : []),
311
325
  ];
312
326
  for (const line of renderSummary('deploy summary', rows, ctx.ports.terminal.isInteractive)) {
@@ -455,7 +469,9 @@ export async function previewDeploy(ctx, id, opts = {}) {
455
469
  ctx.logger.info(colors.bold(`Preview deploy ${id} (${hash})`));
456
470
  const files = await listRepoFiles(ctx.ports, cwd, ctx.config.sourceIgnore, ctx.config.sourceInclude);
457
471
  ctx.logger.step(`zipping ${files.length} files`);
458
- const zip = await buildRepoZip(ctx.ports.fs, cwd, files, { [COMMIT_FILE]: hash });
472
+ const zip = await buildRepoZip(ctx.ports.fs, cwd, files, {
473
+ [COMMIT_FILE]: hash,
474
+ });
459
475
  const sourceKey = `build/${hash}.zip`;
460
476
  await ctx.clients.s3.putObject(ctx.names.bucket, sourceKey, zip, 'application/zip');
461
477
  // Rebuild the shared preview builder image if the agent bundle changed (no-op when
@@ -627,12 +643,20 @@ export async function readNodeStatus(nodes, ctx) {
627
643
  exists = await node.read(ctx);
628
644
  }
629
645
  catch (err) {
630
- entries.push({ title: node.title, state: 'error', detail: err.message });
646
+ entries.push({
647
+ title: node.title,
648
+ state: 'error',
649
+ detail: err.message,
650
+ });
631
651
  continue;
632
652
  }
633
653
  const outputs = ctx.state.resources[node.id];
634
654
  const detail = outputs ? JSON.stringify(outputs) : undefined;
635
- entries.push({ title: node.title, state: exists ? 'present' : 'missing', detail });
655
+ entries.push({
656
+ title: node.title,
657
+ state: exists ? 'present' : 'missing',
658
+ detail,
659
+ });
636
660
  }
637
661
  return entries;
638
662
  }
package/dist/context.d.ts CHANGED
@@ -65,7 +65,12 @@ export declare function deriveAppTag(config: Pick<OpsConfig, 'app'>, domain: str
65
65
  * primary to be aliases of, must not repeat it, and a preview stack serves one
66
66
  * wildcard host so it takes neither `aliases` nor `redirectToPrimary`.
67
67
  */
68
- export declare function assertDomainSettings(config: Pick<OpsConfig, 'aliases' | 'redirectToPrimary'> & Partial<Pick<OpsConfig, 'manageDns'>>, domain: string | undefined, preview: boolean): void;
68
+ export declare function assertDomainSettings(config: Pick<OpsConfig, 'aliases' | 'redirectToPrimary'> & Partial<Pick<OpsConfig, 'manageDns' | 'redirects'>>, domain: string | undefined, preview: boolean): void;
69
+ /**
70
+ * The compiled router source depends on the effective domain and on `ssr`, so
71
+ * its size is checked here, before any AWS call.
72
+ */
73
+ export declare function assertRouterFits(config: OpsConfig, domain: string | undefined): void;
69
74
  export interface ContextOptions {
70
75
  env: string;
71
76
  configPath?: string | undefined;
package/dist/context.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { ROUTER_CODE_LIMIT, routerCodeFits, ssrRouterCode, staticRouterCode, } from './router-function.js';
1
2
  import { readFile } from 'node:fs/promises';
2
3
  import { homedir } from 'node:os';
3
4
  import { basename, join, relative, resolve } from 'node:path';
@@ -25,6 +26,9 @@ export function deriveAppTag(config, domain, repoRoot) {
25
26
  * wildcard host so it takes neither `aliases` nor `redirectToPrimary`.
26
27
  */
27
28
  export function assertDomainSettings(config, domain, preview) {
29
+ if (preview && (config.redirects?.length ?? 0) > 0) {
30
+ throw new Error('config.redirects is not valid for a preview environment: the preview host router does not apply redirects');
31
+ }
28
32
  if (preview && (config.aliases.length > 0 || config.redirectToPrimary || config.manageDns)) {
29
33
  throw new Error('config.aliases, config.redirectToPrimary and config.manageDns are not valid for a preview environment: ' +
30
34
  'the preview stack serves one wildcard host');
@@ -36,6 +40,25 @@ export function assertDomainSettings(config, domain, preview) {
36
40
  throw new Error(`config.aliases must not repeat the primary domain ("${domain}")`);
37
41
  }
38
42
  }
43
+ /**
44
+ * The compiled router source depends on the effective domain and on `ssr`, so
45
+ * its size is checked here, before any AWS call.
46
+ */
47
+ export function assertRouterFits(config, domain) {
48
+ if (config.redirects.length === 0)
49
+ return;
50
+ const alias = config.redirectToPrimary && domain && config.aliases.length > 0
51
+ ? { primary: domain, aliases: config.aliases }
52
+ : undefined;
53
+ const code = config.ssr
54
+ ? ssrRouterCode(alias, config.redirects)
55
+ : staticRouterCode(alias, config.redirects);
56
+ if (!routerCodeFits(code)) {
57
+ throw new Error(`config.redirects compiles to a ${Buffer.byteLength(code, 'utf8')}-byte router function, ` +
58
+ `over the CloudFront Function limit of ${ROUTER_CODE_LIMIT} bytes (${config.redirects.length} ` +
59
+ 'entries); shorten the map or move redirects to the application');
60
+ }
61
+ }
39
62
  /**
40
63
  * The real adapter for every port not supplied in `overrides`. Shared by
41
64
  * `createContext` and the pre-context paths (`whoami`, `init`) through
@@ -183,6 +206,8 @@ export async function createContext(opts) {
183
206
  });
184
207
  const domain = opts.domain ?? config.domain;
185
208
  assertDomainSettings(config, domain, Boolean(opts.preview));
209
+ if (!opts.preview)
210
+ assertRouterFits(config, domain);
186
211
  const session = await resolveAwsSession({
187
212
  region: config.region,
188
213
  endpointOverride: opts.endpointOverride,
package/dist/nodes.d.ts CHANGED
@@ -48,6 +48,17 @@ export declare function placeholderPackageZip(): Uint8Array;
48
48
  * the record bootstrap keeps, so the deploy role needs no distribution read.
49
49
  */
50
50
  export declare function reconcileResponseHeadersOnDeploy(ctx: OpsContext): Promise<void>;
51
+ /** True when an SSR distribution needs the viewer-request router attached. */
52
+ export declare function ssrNeedsRouter(ctx: OpsContext): boolean;
53
+ /**
54
+ * Deploy-time half of the router function: republish the source when the
55
+ * config now produces different code than the recorded `codeHash`, never
56
+ * touching the distribution. Returns what happened, for the deploy summary.
57
+ */
58
+ export declare function reconcileRouterFunction(ctx: OpsContext): Promise<{
59
+ status: 'republished' | 'unchanged' | 'not-bootstrapped';
60
+ redirects: number;
61
+ }>;
51
62
  /**
52
63
  * The workflow's OIDC subject claim, scoped per environment to match how each one
53
64
  * deploys: previews from any PR ref; staging from pushes to main; production from the
package/dist/nodes.js CHANGED
@@ -173,8 +173,16 @@ async function applyBuildRolePolicy(ctx) {
173
173
  await ctx.clients.iam.putRolePolicy(ctx.names.buildRole, 'build', {
174
174
  Version: '2012-10-17',
175
175
  Statement: [
176
- { Effect: 'Allow', Action: ['s3:GetObject'], Resource: `arn:aws:s3:::${ctx.names.bucket}/*` },
177
- { Effect: 'Allow', Action: ['s3:ListBucket'], Resource: `arn:aws:s3:::${ctx.names.bucket}` },
176
+ {
177
+ Effect: 'Allow',
178
+ Action: ['s3:GetObject'],
179
+ Resource: `arn:aws:s3:::${ctx.names.bucket}/*`,
180
+ },
181
+ {
182
+ Effect: 'Allow',
183
+ Action: ['s3:ListBucket'],
184
+ Resource: `arn:aws:s3:::${ctx.names.bucket}`,
185
+ },
178
186
  {
179
187
  // s3:PutObjectTagging is required even though the tags ride on the PUT
180
188
  // itself (x-amz-tagging header) - AWS checks it as a distinct action, and
@@ -314,7 +322,10 @@ async function imageInput(ctx) {
314
322
  // Bucket + region for the agent, which polls s3://<bucket>/build/pending.json and
315
323
  // resolves credentials from IMDS (→ the build role identity). Hookless: hooks are
316
324
  // delivered over TLS which the agent can't satisfy, and are unnecessary here.
317
- environmentVariables: { BUILD_BUCKET: ctx.names.bucket, BUILD_REGION: ctx.config.region },
325
+ environmentVariables: {
326
+ BUILD_BUCKET: ctx.names.bucket,
327
+ BUILD_REGION: ctx.config.region,
328
+ },
318
329
  // Arm64 in every environment, so what the build compiles or installs matches
319
330
  // the Web Function runtime (and `ARM_64` is the API's only value). Sent on
320
331
  // create AND update, because `imageBody` emits it either way.
@@ -820,7 +831,10 @@ function desiredResponseHeadersPolicyId(ctx) {
820
831
  function recordResponseHeadersPolicyAttached(ctx, distributionId) {
821
832
  const policyId = desiredResponseHeadersPolicyId(ctx);
822
833
  if (policyId !== undefined) {
823
- recordResponseHeadersPolicy(ctx, { id: policyId, attachedTo: distributionId });
834
+ recordResponseHeadersPolicy(ctx, {
835
+ id: policyId,
836
+ attachedTo: distributionId,
837
+ });
824
838
  }
825
839
  }
826
840
  /**
@@ -1196,7 +1210,9 @@ function webFunctionNode() {
1196
1210
  timeoutSeconds: config.timeoutSeconds,
1197
1211
  maxConcurrencyPerEnvironment: config.maxConcurrencyPerEnvironment,
1198
1212
  environmentVariables: { NODE_ENV: 'production', ...config.env },
1199
- telemetryConfig: { loggingConfig: { logGroup: ctx.names.webLogGroup } },
1213
+ telemetryConfig: {
1214
+ loggingConfig: { logGroup: ctx.names.webLogGroup },
1215
+ },
1200
1216
  },
1201
1217
  },
1202
1218
  endpointConfig: {
@@ -1254,7 +1270,11 @@ function webFunctionPolicyStatement(ctx) {
1254
1270
  Principal: { Service: 'cloudfront.amazonaws.com' },
1255
1271
  Action: 'lambda:InvokeWebFunctionEndpoint',
1256
1272
  Resource: String(output(ctx, 'web-function').endpointArn),
1257
- Condition: { ArnLike: { 'AWS:SourceArn': String(output(ctx, 'cloudfront-distribution').arn) } },
1273
+ Condition: {
1274
+ ArnLike: {
1275
+ 'AWS:SourceArn': String(output(ctx, 'cloudfront-distribution').arn),
1276
+ },
1277
+ },
1258
1278
  };
1259
1279
  }
1260
1280
  function webFunctionPolicyNode() {
@@ -1330,6 +1350,77 @@ function aliasRedirect(ctx) {
1330
1350
  return undefined;
1331
1351
  return { primary: ctx.domain, aliases };
1332
1352
  }
1353
+ /**
1354
+ * The source of the production/staging router function this environment
1355
+ * should run: path redirects, then the alias host check, then (static only)
1356
+ * the directory-index rewrite.
1357
+ */
1358
+ function productionRouterCode(ctx) {
1359
+ const redirect = aliasRedirect(ctx);
1360
+ const paths = ctx.config.redirects;
1361
+ if (ctx.config.ssr && ssrNeedsRouter(ctx))
1362
+ return ssrRouterCode(redirect, paths);
1363
+ return staticRouterCode(redirect, paths);
1364
+ }
1365
+ /** True when an SSR distribution needs the viewer-request router attached. */
1366
+ export function ssrNeedsRouter(ctx) {
1367
+ return Boolean(aliasRedirect(ctx)) || ctx.config.redirects.length > 0;
1368
+ }
1369
+ /** Whether the viewer-request router is associated for this mode. */
1370
+ function routerAttached(ctx, mode, preview) {
1371
+ return preview || mode === 'static' || ssrNeedsRouter(ctx);
1372
+ }
1373
+ const ROUTER_COMMENT = (ctx) => `${ctx.config.siteName} ${ctx.env} directory-index router`;
1374
+ /**
1375
+ * Deploy-time half of the router function: republish the source when the
1376
+ * config now produces different code than the recorded `codeHash`, never
1377
+ * touching the distribution. Returns what happened, for the deploy summary.
1378
+ */
1379
+ export async function reconcileRouterFunction(ctx) {
1380
+ const redirects = ctx.config.redirects.length;
1381
+ const out = output(ctx, 'cloudfront-function');
1382
+ const bootstrap = `blogwright bootstrap ${ctx.env}`;
1383
+ if (typeof out.arn !== 'string') {
1384
+ ctx.logger.warn(`no router function exists yet, so redirects are not live; run \`${bootstrap}\` to create it`);
1385
+ return { status: 'not-bootstrapped', redirects };
1386
+ }
1387
+ if (ctx.config.ssr && !ssrNeedsRouter(ctx)) {
1388
+ // The config no longer needs the router, but the distribution may still run
1389
+ // it; publishing the static rewrite there would break the application's
1390
+ // routes. Leave the code to the bootstrap, which detaches it first.
1391
+ if (output(ctx, 'cloudfront-distribution').routerAttached === true) {
1392
+ ctx.logger.warn(`the router function is still associated with the distribution; run \`${bootstrap}\` to detach it`);
1393
+ }
1394
+ return { status: 'unchanged', redirects };
1395
+ }
1396
+ const code = productionRouterCode(ctx);
1397
+ const hash = routerCodeHash(code);
1398
+ if (ctx.config.ssr) {
1399
+ const attached = output(ctx, 'cloudfront-distribution').routerAttached === true;
1400
+ if (ssrNeedsRouter(ctx) && !attached) {
1401
+ ctx.logger.warn(`the router function is not associated with the distribution, so redirects are not live; ` +
1402
+ `run \`${bootstrap}\` to attach it`);
1403
+ }
1404
+ }
1405
+ if (out.codeHash === hash)
1406
+ return { status: 'unchanged', redirects };
1407
+ if (out.codeHash === undefined && code === staticRouterCode()) {
1408
+ return { status: 'unchanged', redirects };
1409
+ }
1410
+ try {
1411
+ await ctx.clients.cloudfront.ensureFunction(`${ctx.names.prefix}-router`, code, ROUTER_COMMENT(ctx));
1412
+ }
1413
+ catch (err) {
1414
+ if (err instanceof AwsError && /AccessDenied|not authorized/i.test(err.message)) {
1415
+ throw new Error(`the deploy role may not publish the router function; run \`${bootstrap}\` to update it: ${err.message}`, { cause: err });
1416
+ }
1417
+ throw new Error(`the site is live but the router function failed to publish; run \`${bootstrap}\` to retry: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
1418
+ }
1419
+ out.codeHash = hash;
1420
+ await ctx.save();
1421
+ ctx.logger.ok('CloudFront routing function republished');
1422
+ return { status: 'republished', redirects };
1423
+ }
1333
1424
  /**
1334
1425
  * CloudFront viewer-request function. Preview stacks route a subdomain to its S3 prefix
1335
1426
  * (and resolve index documents); staging/production just resolve directory URLs to their
@@ -1345,10 +1436,7 @@ function routerFunctionNode(preview) {
1345
1436
  function desiredCode(ctx) {
1346
1437
  if (preview)
1347
1438
  return PREVIEW_FUNCTION_CODE;
1348
- const redirect = aliasRedirect(ctx);
1349
- if (ctx.config.ssr && redirect)
1350
- return ssrRouterCode(redirect);
1351
- return staticRouterCode(redirect);
1439
+ return productionRouterCode(ctx);
1352
1440
  }
1353
1441
  function comment(ctx) {
1354
1442
  return `${ctx.config.siteName} ${ctx.env} ${preview ? 'preview host router' : 'directory-index router'}`;
@@ -1436,7 +1524,7 @@ function distributionShape(ctx, mode, preview) {
1436
1524
  const config = ssrConfig(ctx);
1437
1525
  // Aliases must redirect on every path, static or dynamic, so the function
1438
1526
  // is on each behavior; without a redirect nothing is attached.
1439
- const functionArn = !preview && aliasRedirect(ctx) ? String(output(ctx, 'cloudfront-function').arn) : undefined;
1527
+ const functionArn = !preview && ssrNeedsRouter(ctx) ? String(output(ctx, 'cloudfront-function').arn) : undefined;
1440
1528
  return {
1441
1529
  ...shared,
1442
1530
  // The app answers `/`; a root object would only intercept it.
@@ -1607,6 +1695,7 @@ function distributionNode(options) {
1607
1695
  // The mode the live distribution was left serving, so a later bootstrap can
1608
1696
  // tell a routine re-run from a serving cutover.
1609
1697
  out.mode = servingMode(ctx);
1698
+ out.routerAttached = routerAttached(ctx, servingMode(ctx), preview);
1610
1699
  await ctx.clients.cloudfront.tagResource(dist.arn, ctx.tags);
1611
1700
  ctx.logger.info(` CloudFront domain: ${dist.domainName}`);
1612
1701
  // Production routing records are the site-dns node's (next in the graph);
@@ -1627,6 +1716,7 @@ function distributionNode(options) {
1627
1716
  if (configured === 'ssr' || (recorded !== undefined && recorded !== configured)) {
1628
1717
  const changed = await ctx.clients.cloudfront.reconcileDistribution(id, distributionShape(ctx, configured, preview));
1629
1718
  out.mode = configured;
1719
+ out.routerAttached = routerAttached(ctx, configured, preview);
1630
1720
  recordResponseHeadersPolicyAttached(ctx, id);
1631
1721
  if (changed) {
1632
1722
  ctx.logger.ok(`reconciled the distribution for ${configured} serving`);
@@ -1979,7 +2069,11 @@ export function oidcRolePolicyStatements(ctx) {
1979
2069
  Resource: `arn:aws:s3:::${ctx.names.bucket}/*`,
1980
2070
  },
1981
2071
  ...promoteTaggingStatements(ctx),
1982
- { Effect: 'Allow', Action: ['s3:ListBucket'], Resource: `arn:aws:s3:::${ctx.names.bucket}` },
2072
+ {
2073
+ Effect: 'Allow',
2074
+ Action: ['s3:ListBucket'],
2075
+ Resource: `arn:aws:s3:::${ctx.names.bucket}`,
2076
+ },
1983
2077
  {
1984
2078
  Effect: 'Allow',
1985
2079
  Action: [
@@ -2022,6 +2116,16 @@ export function oidcRolePolicyStatements(ctx) {
2022
2116
  Action: ['cloudfront:CreateInvalidation'],
2023
2117
  Resource: String(output(ctx, 'cloudfront-distribution').arn),
2024
2118
  });
2119
+ // Deploys republish the router function's code (`reconcileRouterFunction`).
2120
+ statements.push({
2121
+ Effect: 'Allow',
2122
+ Action: [
2123
+ 'cloudfront:DescribeFunction',
2124
+ 'cloudfront:UpdateFunction',
2125
+ 'cloudfront:PublishFunction',
2126
+ ],
2127
+ Resource: `arn:aws:cloudfront::${ctx.accountId}:function/${ctx.names.prefix}-router`,
2128
+ });
2025
2129
  // Deploys converge the response headers in place - this one policy only,
2026
2130
  // never the distribution (`reconcileResponseHeadersOnDeploy`).
2027
2131
  const policyId = recordedResponseHeadersPolicyId(ctx);
@@ -2052,7 +2156,9 @@ async function applyOidcRole(ctx, roleName) {
2052
2156
  Action: 'sts:AssumeRoleWithWebIdentity',
2053
2157
  Condition: {
2054
2158
  StringEquals: { [`${GITHUB_OIDC_URL}:aud`]: 'sts.amazonaws.com' },
2055
- StringLike: { [`${GITHUB_OIDC_URL}:sub`]: oidcSubClaim(repo, ctx.env, ctx.preview) },
2159
+ StringLike: {
2160
+ [`${GITHUB_OIDC_URL}:sub`]: oidcSubClaim(repo, ctx.env, ctx.preview),
2161
+ },
2056
2162
  },
2057
2163
  },
2058
2164
  ],
@@ -1,3 +1,8 @@
1
+ import { type PathRedirect } from 'blogwright-core';
2
+ /** CloudFront Function source limit, in bytes. */
3
+ export declare const ROUTER_CODE_LIMIT = 10240;
4
+ /** True when the compiled router source fits the CloudFront Function limit. */
5
+ export declare function routerCodeFits(code: string): boolean;
1
6
  /** Hosts whose requests redirect, and the host they redirect to. */
2
7
  export interface AliasRedirect {
3
8
  /** The canonical host (`OpsConfig.domain`); the redirect target. */
@@ -12,13 +17,13 @@ export interface AliasRedirect {
12
17
  * type, so the alias redirect is folded into this function rather than being a
13
18
  * second one.
14
19
  */
15
- export declare function staticRouterCode(redirect?: AliasRedirect): string;
20
+ export declare function staticRouterCode(redirect?: AliasRedirect, paths?: readonly PathRedirect[]): string;
16
21
  /**
17
22
  * Source of the viewer-request function an SSR distribution runs when
18
23
  * `redirectToPrimary` is set. The application owns its own routing, so unlike
19
24
  * the static router there is no directory-index rewrite: alias hosts get the
20
25
  * `301` and every other request passes through untouched.
21
26
  */
22
- export declare function ssrRouterCode(redirect: AliasRedirect): string;
27
+ export declare function ssrRouterCode(redirect: AliasRedirect | undefined, paths?: readonly PathRedirect[]): string;
23
28
  /** Stable fingerprint of a function's source, recorded in state to detect a change. */
24
29
  export declare function routerCodeHash(code: string): string;
@@ -1,4 +1,11 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { isPrefixRedirect, normalizeRedirectFrom } from 'blogwright-core';
3
+ /** CloudFront Function source limit, in bytes. */
4
+ export const ROUTER_CODE_LIMIT = 10_240;
5
+ /** True when the compiled router source fits the CloudFront Function limit. */
6
+ export function routerCodeFits(code) {
7
+ return Buffer.byteLength(code, 'utf8') <= ROUTER_CODE_LIMIT;
8
+ }
2
9
  /**
3
10
  * The directory-index rewrite every static-mode request goes through. The
4
11
  * S3 origin is the private REST endpoint (via OAC), which - unlike an S3
@@ -17,17 +24,9 @@ const INDEX_REWRITE = ` var uri = request.uri;
17
24
  * primary. It reads `request.uri` before the rewrite touches it, so the
18
25
  * redirect target is the URL the viewer asked for, not the origin key.
19
26
  */
20
- function redirectBlock(redirect) {
21
- return ` var host = request.headers.host ? request.headers.host.value.toLowerCase() : '';
22
- if (${JSON.stringify([...redirect.aliases])}.indexOf(host) !== -1) {
23
- var parts = [];
24
- var query = request.querystring;
25
- for (var key in query) {
26
- var entries = query[key].multiValue || [query[key]];
27
- for (var i = 0; i < entries.length; i++) {
28
- parts.push(entries[i].value === '' ? key : key + '=' + entries[i].value);
29
- }
30
- }
27
+ function redirectBlock(redirect, declareHost = true) {
28
+ return `${declareHost ? HOST_LINE : ''} if (${JSON.stringify([...redirect.aliases])}.indexOf(host) !== -1) {
29
+ ${queryParts(' ')}
31
30
  return {
32
31
  statusCode: 301,
33
32
  statusDescription: 'Moved Permanently',
@@ -38,6 +37,85 @@ function redirectBlock(redirect) {
38
37
  }
39
38
  `;
40
39
  }
40
+ const HOST_LINE = ` var host = request.headers.host ? request.headers.host.value.toLowerCase() : '';
41
+ `;
42
+ /** Rebuilds the request's query string into `parts`; shared by both redirect blocks. */
43
+ function queryParts(indent) {
44
+ return [
45
+ 'var parts = [];',
46
+ 'var query = request.querystring;',
47
+ 'for (var key in query) {',
48
+ ' var entries = query[key].multiValue || [query[key]];',
49
+ ' for (var i = 0; i < entries.length; i++) {',
50
+ " parts.push(entries[i].value === '' ? key : key + '=' + entries[i].value);",
51
+ ' }',
52
+ '}',
53
+ ]
54
+ .map((line) => indent + line)
55
+ .join('\n');
56
+ }
57
+ /**
58
+ * Path-redirect check that runs ahead of the alias host check and the rewrite.
59
+ * Exact matches are one object lookup; prefix matches are an array walked
60
+ * longest-first. For an alias request (when `redirectToPrimary` applies) a
61
+ * relative target is made absolute on the primary, so the request reaches the
62
+ * final URL in one hop.
63
+ */
64
+ function pathRedirectsBlock(paths, alias) {
65
+ const exact = {};
66
+ const prefixes = [];
67
+ for (const r of paths) {
68
+ const from = normalizeRedirectFrom(r.from);
69
+ const status = r.status ?? 301;
70
+ if (isPrefixRedirect(from))
71
+ prefixes.push([from.slice(0, -2), r.to, status]);
72
+ else
73
+ exact[from] = [r.to, status];
74
+ }
75
+ prefixes.sort((a, b) => b[0].length - a[0].length);
76
+ const aliasCheck = alias ? `${JSON.stringify([...alias.aliases])}.indexOf(host) !== -1` : 'false';
77
+ const primary = alias ? JSON.stringify(alias.primary) : '""';
78
+ return `${alias ? HOST_LINE : ''} var uri = request.uri;
79
+ var key = uri.length > 1 && uri.charAt(uri.length - 1) === '/' ? uri.slice(0, -1) : uri;
80
+ var exact = ${JSON.stringify(exact)};
81
+ var prefixes = ${JSON.stringify(prefixes)};
82
+ var to = null;
83
+ var status = 301;
84
+ if (exact.hasOwnProperty(key)) {
85
+ to = exact[key][0];
86
+ status = exact[key][1];
87
+ } else {
88
+ for (var p = 0; p < prefixes.length; p++) {
89
+ var base = prefixes[p][0];
90
+ if (key === base || key.indexOf(base + '/') === 0) {
91
+ to = prefixes[p][1].split(':splat').join(uri.length > base.length ? uri.slice(base.length + 1) : '');
92
+ status = prefixes[p][2];
93
+ // A splat that begins with slashes (\`/old//evil.com\`) must not turn a
94
+ // relative target into a protocol-relative one (\`//evil.com\`).
95
+ if (to.charAt(0) === '/') { to = '/' + to.replace(/^[\\/\\\\]+/, ''); }
96
+ break;
97
+ }
98
+ }
99
+ }
100
+ if (to !== null) {
101
+ ${queryParts(' ')}
102
+ if (to.charAt(0) === '/' && ${aliasCheck}) { to = 'https://' + ${primary} + to; }
103
+ if (parts.length) { to += (to.indexOf('?') === -1 ? '?' : '&') + parts.join('&'); }
104
+ return {
105
+ statusCode: status,
106
+ statusDescription: { 301: 'Moved Permanently', 302: 'Found', 307: 'Temporary Redirect', 308: 'Permanent Redirect' }[status],
107
+ headers: { location: { value: to } }
108
+ };
109
+ }
110
+ `;
111
+ }
112
+ /** The redirect checks that precede the rewrite: path redirects, then the alias host check. */
113
+ function checks(redirect, paths) {
114
+ const alias = redirect && redirect.aliases.length > 0 ? redirect : undefined;
115
+ if (paths.length > 0)
116
+ return pathRedirectsBlock(paths, alias) + (alias ? redirectBlock(alias, false) : '');
117
+ return alias ? redirectBlock(alias) : '';
118
+ }
41
119
  /**
42
120
  * Source of the production/staging CloudFront viewer-request function. With no
43
121
  * `redirect` it is the directory-index rewrite alone, byte-for-byte what every
@@ -45,8 +123,8 @@ function redirectBlock(redirect) {
45
123
  * type, so the alias redirect is folded into this function rather than being a
46
124
  * second one.
47
125
  */
48
- export function staticRouterCode(redirect) {
49
- const block = redirect && redirect.aliases.length > 0 ? redirectBlock(redirect) : '';
126
+ export function staticRouterCode(redirect, paths = []) {
127
+ const block = checks(redirect, paths);
50
128
  return `function handler(event) {
51
129
  var request = event.request;
52
130
  ${block}${INDEX_REWRITE}
@@ -58,8 +136,8 @@ ${block}${INDEX_REWRITE}
58
136
  * the static router there is no directory-index rewrite: alias hosts get the
59
137
  * `301` and every other request passes through untouched.
60
138
  */
61
- export function ssrRouterCode(redirect) {
62
- const block = redirect.aliases.length > 0 ? redirectBlock(redirect) : '';
139
+ export function ssrRouterCode(redirect, paths = []) {
140
+ const block = checks(redirect, paths);
63
141
  return `function handler(event) {
64
142
  var request = event.request;
65
143
  ${block} return request;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blogwright",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "blogwright": "./dist/bin.js",
@@ -17,12 +17,12 @@
17
17
  }
18
18
  },
19
19
  "dependencies": {
20
- "blogwright-core": "0.6.0"
20
+ "blogwright-core": "0.7.0"
21
21
  },
22
22
  "devDependencies": {
23
23
  "@types/node": "^26.6.5",
24
24
  "blogwright-build-agent": "0.1.0",
25
- "blogwright-pds": "0.6.0",
25
+ "blogwright-pds": "0.7.0",
26
26
  "fflate": "^0.8.3",
27
27
  "oxlint": "^1.90.0",
28
28
  "typescript": "^6.0.3",