blogwright 0.5.0 → 0.6.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": "1a4751543322"
2
+ "hash": "cf96a6a02e97"
3
3
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * `node:dns` adapter for the DnsPort: SOA lookups through the system resolver,
3
+ * retried once against public resolvers when the system resolver fails to
4
+ * answer. A definite negative (the name has no SOA) is an answer, not a
5
+ * failure, and never triggers the fallback.
6
+ */
7
+ import type { DnsPort } from '../ports.js';
8
+ /** The slice of a resolver the adapter uses; both `dns.promises` and a `Resolver` fit. */
9
+ export interface SoaResolver {
10
+ resolveSoa(name: string): Promise<{
11
+ nsname: string;
12
+ hostmaster: string;
13
+ serial: number;
14
+ }>;
15
+ }
16
+ /**
17
+ * Build the port. `system` and `publicResolver` are injectable for tests;
18
+ * `publicResolver` is built lazily so a run that never needs it makes none.
19
+ */
20
+ export declare function createNodeDns(system?: SoaResolver, publicResolver?: () => SoaResolver): DnsPort;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `node:dns` adapter for the DnsPort: SOA lookups through the system resolver,
3
+ * retried once against public resolvers when the system resolver fails to
4
+ * answer. A definite negative (the name has no SOA) is an answer, not a
5
+ * failure, and never triggers the fallback.
6
+ */
7
+ import { promises as dns } from 'node:dns';
8
+ /** Public resolvers tried, in order, when the system resolver cannot answer. */
9
+ const PUBLIC_RESOLVERS = ['1.1.1.1', '8.8.8.8'];
10
+ /** Codes meaning "the resolver answered: this name has no SOA record". */
11
+ const NEGATIVE = new Set(['ENODATA', 'ENOTFOUND', 'NXDOMAIN']);
12
+ function code(err) {
13
+ return typeof err === 'object' && err !== null && 'code' in err
14
+ ? String(err.code)
15
+ : '';
16
+ }
17
+ /**
18
+ * Build the port. `system` and `publicResolver` are injectable for tests;
19
+ * `publicResolver` is built lazily so a run that never needs it makes none.
20
+ */
21
+ export function createNodeDns(system = dns, publicResolver = () => {
22
+ const resolver = new dns.Resolver({ timeout: 3000, tries: 1 });
23
+ resolver.setServers([...PUBLIC_RESOLVERS]);
24
+ return resolver;
25
+ }) {
26
+ async function ask(resolver, name) {
27
+ try {
28
+ const r = await resolver.resolveSoa(name);
29
+ return `${r.nsname} ${r.hostmaster} ${r.serial}`;
30
+ }
31
+ catch (err) {
32
+ if (NEGATIVE.has(code(err)))
33
+ return undefined;
34
+ throw err;
35
+ }
36
+ }
37
+ return {
38
+ async soa(name) {
39
+ try {
40
+ return await ask(system, name);
41
+ }
42
+ catch {
43
+ // The system resolver did not answer; ask the public ones. Their own
44
+ // failure propagates so the caller can tell "no answer" from "no SOA".
45
+ return await ask(publicResolver(), name);
46
+ }
47
+ },
48
+ };
49
+ }
package/dist/cli.js CHANGED
@@ -70,6 +70,10 @@ Options:
70
70
  --force-unlock Replace the environment lock a deploy, rollback, stage,
71
71
  promote or delete left behind when it stopped; only once
72
72
  that command is known to be no longer running
73
+ --prune-aliases With bootstrap: detach attached CloudFront aliases that
74
+ the config does not name. Without it they are reported
75
+ and left attached, so a config edit never drops a
76
+ live hostname.
73
77
  --switch-mode Allow bootstrap to change a bootstrapped stack between
74
78
  static and SSR serving. Without it that cutover is
75
79
  refused, because the distribution moves before a deploy
@@ -281,6 +285,7 @@ export async function main(argv, makeTerminal, makeContext, makeDiscoveryPorts,
281
285
  // form would reject the flag the usage text and docs advertise.
282
286
  'switch-mode': { type: 'boolean', default: false },
283
287
  'force-unlock': { type: 'boolean', default: false },
288
+ 'prune-aliases': { type: 'boolean', default: false },
284
289
  staged: { type: 'boolean', default: false },
285
290
  rebuild: { type: 'boolean', default: false },
286
291
  yes: { type: 'boolean', default: false },
@@ -419,6 +424,7 @@ export async function main(argv, makeTerminal, makeContext, makeDiscoveryPorts,
419
424
  domain: values.domain,
420
425
  endpointOverride: values.endpoint,
421
426
  profile: values.profile,
427
+ pruneAliases: command === 'bootstrap' && values['prune-aliases'],
422
428
  ports: { terminal },
423
429
  });
424
430
  switch (command) {
package/dist/context.d.ts CHANGED
@@ -7,6 +7,12 @@ export interface OpsContext {
7
7
  domain: string | undefined;
8
8
  /** True for the shared preview stack (host-routed, per-PR prefixes). */
9
9
  preview: boolean;
10
+ /**
11
+ * `bootstrap --prune-aliases`: detach attached aliases that config does not
12
+ * name. False for every other run, so a reconcile never drops a live
13
+ * hostname as a side effect.
14
+ */
15
+ pruneAliases: boolean;
10
16
  config: OpsConfig;
11
17
  /**
12
18
  * The environment's config file exactly as parsed, before `OpsConfig`'s
@@ -53,12 +59,21 @@ export interface OpsContext {
53
59
  * trace back to the project from a billing or resource listing.
54
60
  */
55
61
  export declare function deriveAppTag(config: Pick<OpsConfig, 'app'>, domain: string | undefined, repoRoot: string): string;
62
+ /**
63
+ * The multi-domain rules that depend on the effective domain (`--domain` can
64
+ * supply or override the config file's) or on the stack: aliases need a
65
+ * primary to be aliases of, must not repeat it, and a preview stack serves one
66
+ * wildcard host so it takes neither `aliases` nor `redirectToPrimary`.
67
+ */
68
+ export declare function assertDomainSettings(config: Pick<OpsConfig, 'aliases' | 'redirectToPrimary'> & Partial<Pick<OpsConfig, 'manageDns'>>, domain: string | undefined, preview: boolean): void;
56
69
  export interface ContextOptions {
57
70
  env: string;
58
71
  configPath?: string | undefined;
59
72
  domain?: string | undefined;
60
73
  endpointOverride?: string | undefined;
61
74
  preview?: boolean | undefined;
75
+ /** `--prune-aliases`; see {@link OpsContext.pruneAliases}. */
76
+ pruneAliases?: boolean | undefined;
62
77
  /** `--profile`: the first row of AWS profile resolution. */
63
78
  profile?: string | undefined;
64
79
  /** The environment AWS resolution reads; defaults to `process.env`. */
package/dist/context.js CHANGED
@@ -4,6 +4,7 @@ import { basename, join, relative, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { createNodeFileSystem, createNodeTerminal, deriveNames, findRepoRoot, parseConfigDocument, StateStore, } from 'blogwright-core';
6
6
  import { createFetchPing } from './adapters/fetch-ping.js';
7
+ import { createNodeDns } from './adapters/node-dns.js';
7
8
  import { createNodeModuleLoader } from './adapters/node-module-loader.js';
8
9
  import { createProcessAwsLogin } from './adapters/process-aws-login.js';
9
10
  import { createProcessVcs } from './adapters/process-vcs.js';
@@ -17,6 +18,24 @@ import { createLogger } from './logger.js';
17
18
  export function deriveAppTag(config, domain, repoRoot) {
18
19
  return config.app ?? domain ?? basename(repoRoot);
19
20
  }
21
+ /**
22
+ * The multi-domain rules that depend on the effective domain (`--domain` can
23
+ * supply or override the config file's) or on the stack: aliases need a
24
+ * primary to be aliases of, must not repeat it, and a preview stack serves one
25
+ * wildcard host so it takes neither `aliases` nor `redirectToPrimary`.
26
+ */
27
+ export function assertDomainSettings(config, domain, preview) {
28
+ if (preview && (config.aliases.length > 0 || config.redirectToPrimary || config.manageDns)) {
29
+ throw new Error('config.aliases, config.redirectToPrimary and config.manageDns are not valid for a preview environment: ' +
30
+ 'the preview stack serves one wildcard host');
31
+ }
32
+ if (config.aliases.length > 0 && !domain) {
33
+ throw new Error('config.aliases requires a primary domain (config.domain or --domain)');
34
+ }
35
+ if (domain && config.aliases.includes(domain)) {
36
+ throw new Error(`config.aliases must not repeat the primary domain ("${domain}")`);
37
+ }
38
+ }
20
39
  /**
21
40
  * The real adapter for every port not supplied in `overrides`. Shared by
22
41
  * `createContext` and the pre-context paths (`whoami`, `init`) through
@@ -30,6 +49,7 @@ function createPorts(overrides = {}) {
30
49
  ping: overrides.ping ?? createFetchPing(),
31
50
  loader: overrides.loader ?? createNodeModuleLoader(),
32
51
  awsLogin: overrides.awsLogin ?? createProcessAwsLogin(),
52
+ dns: overrides.dns ?? createNodeDns(),
33
53
  };
34
54
  }
35
55
  /** The operator's machine as AWS resolution sees it, from `process` and `os`. */
@@ -162,6 +182,7 @@ export async function createContext(opts) {
162
182
  configPath: opts.configPath,
163
183
  });
164
184
  const domain = opts.domain ?? config.domain;
185
+ assertDomainSettings(config, domain, Boolean(opts.preview));
165
186
  const session = await resolveAwsSession({
166
187
  region: config.region,
167
188
  endpointOverride: opts.endpointOverride,
@@ -184,6 +205,7 @@ export async function createContext(opts) {
184
205
  env: opts.env,
185
206
  domain,
186
207
  preview: opts.preview ?? false,
208
+ pruneAliases: opts.pruneAliases ?? false,
187
209
  config,
188
210
  configDocument,
189
211
  names,
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The hostnames a production environment serves and the questions asked about
3
+ * them: which set the certificate and distribution should carry, which
4
+ * attached aliases config does not name, which DNS zone a host sits in, and
5
+ * whether it is that zone's apex.
6
+ */
7
+ import type { AwsClients } from 'blogwright-core';
8
+ import type { OpsContext } from './context.js';
9
+ import type { DnsPort } from './ports.js';
10
+ /** The primary then the configured aliases; empty when no domain is configured. */
11
+ export declare function configuredHostnames(ctx: Pick<OpsContext, 'domain' | 'config'>): string[];
12
+ /**
13
+ * The hostnames this run should serve: `configuredHostnames` plus any alias
14
+ * already attached to the distribution that config does not name. Those are
15
+ * kept (and kept on the certificate) so editing config never drops a live
16
+ * host; `--prune-aliases` leaves them out. Reports each such alias once.
17
+ */
18
+ export declare function desiredHostnames(ctx: OpsContext): Promise<string[]>;
19
+ /** What the nodes after the certificate should treat as the site's hostnames. */
20
+ export declare function siteHostnames(ctx: OpsContext): string[];
21
+ /** The names the recorded certificate was requested for; a pre-aliases certificate covers the primary. */
22
+ export declare function recordedDomains(ctx: OpsContext): string[];
23
+ export declare function sameSet(a: readonly string[], b: readonly string[]): boolean;
24
+ /**
25
+ * ACM idempotency token (`\w+`, at most 32): stable for one site, environment
26
+ * and name set, so a retry of the same request reuses the certificate while a
27
+ * changed set requests a new one.
28
+ */
29
+ export declare function certificateToken(siteName: string, env: string, names: readonly string[]): string;
30
+ /**
31
+ * The apex of the DNS zone `host` lives in, found by asking DNS: walk from the
32
+ * host up through its parents and take the highest name that answers with the
33
+ * same SOA as the first that does. Resolvers follow a CNAME when asked for SOA,
34
+ * so `www` aliased to an apex answers with the apex's record - requiring the
35
+ * run of identical records to end at the real apex handles that, and handles
36
+ * multi-label suffixes such as `example.co.uk` without a suffix list.
37
+ * `undefined` when nothing answers or no resolver could be reached.
38
+ */
39
+ export declare function findZoneApex(dns: DnsPort, host: string): Promise<string | undefined>;
40
+ /** The Route 53 hosted zone holding `host`, trying the host and then each parent. */
41
+ export declare function findHostedZone(route53: Pick<AwsClients['route53'], 'hostedZoneId'>, host: string): Promise<{
42
+ zoneId: string;
43
+ zone: string;
44
+ } | undefined>;
45
+ /** One printed routing instruction for a host that blogwright does not manage DNS for. */
46
+ export declare function routingGuidance(dns: DnsPort, host: string, target: string): Promise<string>;
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The hostnames a production environment serves and the questions asked about
3
+ * them: which set the certificate and distribution should carry, which
4
+ * attached aliases config does not name, which DNS zone a host sits in, and
5
+ * whether it is that zone's apex.
6
+ */
7
+ import { createHash } from 'node:crypto';
8
+ /** The primary then the configured aliases; empty when no domain is configured. */
9
+ export function configuredHostnames(ctx) {
10
+ return ctx.domain ? [ctx.domain, ...ctx.config.aliases] : [];
11
+ }
12
+ /** Per-run desired set, so the certificate and distribution nodes agree and drift is reported once. */
13
+ const desiredCache = new WeakMap();
14
+ /**
15
+ * The hostnames this run should serve: `configuredHostnames` plus any alias
16
+ * already attached to the distribution that config does not name. Those are
17
+ * kept (and kept on the certificate) so editing config never drops a live
18
+ * host; `--prune-aliases` leaves them out. Reports each such alias once.
19
+ */
20
+ export async function desiredHostnames(ctx) {
21
+ const cached = desiredCache.get(ctx);
22
+ if (cached)
23
+ return cached;
24
+ const configured = configuredHostnames(ctx);
25
+ let desired = configured;
26
+ const id = ctx.state.resources['cloudfront-distribution']?.id;
27
+ if (ctx.domain && typeof id === 'string') {
28
+ const live = await ctx.clients.cloudfront.getDistributionAliases(id);
29
+ const undeclared = (live?.aliases ?? []).filter((a) => !configured.includes(a)).sort();
30
+ if (undeclared.length > 0 && ctx.pruneAliases) {
31
+ ctx.logger.warn(`detaching aliases not in config: ${undeclared.join(', ')}`);
32
+ }
33
+ else if (undeclared.length > 0) {
34
+ for (const alias of undeclared) {
35
+ ctx.logger.warn(`${alias} is attached to the distribution but not named in config; leaving it ` +
36
+ 'attached (run bootstrap --prune-aliases to detach it)');
37
+ }
38
+ desired = [...configured, ...undeclared];
39
+ }
40
+ }
41
+ desiredCache.set(ctx, desired);
42
+ return desired;
43
+ }
44
+ /** What the nodes after the certificate should treat as the site's hostnames. */
45
+ export function siteHostnames(ctx) {
46
+ return desiredCache.get(ctx) ?? configuredHostnames(ctx);
47
+ }
48
+ /** The names the recorded certificate was requested for; a pre-aliases certificate covers the primary. */
49
+ export function recordedDomains(ctx) {
50
+ const recorded = ctx.state.resources['acm-certificate']?.domains;
51
+ if (Array.isArray(recorded))
52
+ return recorded;
53
+ return ctx.domain ? [ctx.domain] : [];
54
+ }
55
+ export function sameSet(a, b) {
56
+ return a.length === b.length && [...a].sort().every((name, i) => name === [...b].sort()[i]);
57
+ }
58
+ /**
59
+ * ACM idempotency token (`\w+`, at most 32): stable for one site, environment
60
+ * and name set, so a retry of the same request reuses the certificate while a
61
+ * changed set requests a new one.
62
+ */
63
+ export function certificateToken(siteName, env, names) {
64
+ return createHash('sha256')
65
+ .update(`${siteName}\n${env}\n${[...names].sort().join(',')}`)
66
+ .digest('hex')
67
+ .slice(0, 32);
68
+ }
69
+ /**
70
+ * The apex of the DNS zone `host` lives in, found by asking DNS: walk from the
71
+ * host up through its parents and take the highest name that answers with the
72
+ * same SOA as the first that does. Resolvers follow a CNAME when asked for SOA,
73
+ * so `www` aliased to an apex answers with the apex's record - requiring the
74
+ * run of identical records to end at the real apex handles that, and handles
75
+ * multi-label suffixes such as `example.co.uk` without a suffix list.
76
+ * `undefined` when nothing answers or no resolver could be reached.
77
+ */
78
+ export async function findZoneApex(dns, host) {
79
+ const labels = host.split('.');
80
+ let apex;
81
+ try {
82
+ for (let i = 0; i < labels.length - 1; i++) {
83
+ const name = labels.slice(i).join('.');
84
+ const soa = await dns.soa(name);
85
+ if (apex === undefined) {
86
+ if (soa !== undefined)
87
+ apex = { name, soa };
88
+ }
89
+ else if (soa === apex.soa) {
90
+ apex = { name, soa };
91
+ }
92
+ else {
93
+ break;
94
+ }
95
+ }
96
+ }
97
+ catch {
98
+ return undefined;
99
+ }
100
+ return apex?.name;
101
+ }
102
+ /** The Route 53 hosted zone holding `host`, trying the host and then each parent. */
103
+ export async function findHostedZone(route53, host) {
104
+ const labels = host.split('.');
105
+ for (let i = 0; i < labels.length - 1; i++) {
106
+ const zone = labels.slice(i).join('.');
107
+ const zoneId = await route53.hostedZoneId(zone);
108
+ if (zoneId)
109
+ return { zoneId, zone };
110
+ }
111
+ return undefined;
112
+ }
113
+ /** One printed routing instruction for a host that blogwright does not manage DNS for. */
114
+ export async function routingGuidance(dns, host, target) {
115
+ const apex = await findZoneApex(dns, host);
116
+ if (apex === undefined) {
117
+ return (`${host} CNAME -> ${target} (if ${host} is a zone apex use ALIAS/ANAME, or A and AAAA ` +
118
+ 'alias records, instead; its zone could not be looked up)');
119
+ }
120
+ if (apex === host) {
121
+ return (`${host} ALIAS/ANAME -> ${target} (or A and AAAA alias records where the DNS host ` +
122
+ 'cannot flatten a CNAME at the apex)');
123
+ }
124
+ return `${host} CNAME -> ${target}`;
125
+ }
package/dist/nodes.js CHANGED
@@ -1,5 +1,8 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { ALL_VIEWER_EXCEPT_HOST_HEADER, AwsError, CACHING_DISABLED, CACHING_OPTIMIZED, CLOUDFRONT_ALIAS_ZONE_ID, CONTENT_SECURITY_POLICY_DEFAULT_QUOTA, CUSTOM_RESPONSE_HEADERS_DEFAULT_QUOTA, MICROVM_CPU_ARCHITECTURE, pollUntil, REPRODUCIBLE_ZIP_MTIME, STAGED_RELEASES_PREFIX, createZip, textTag, WEB_FUNCTION_RUNTIME, withRetry, } from 'blogwright-core';
2
3
  import { packageAndUploadAgent } from './agent-package.js';
4
+ import { certificateToken, desiredHostnames, findHostedZone, recordedDomains, routingGuidance, sameSet, siteHostnames, } from './domains.js';
5
+ import { routerCodeHash, ssrRouterCode, staticRouterCode, } from './router-function.js';
3
6
  /** Lambda-managed MicroVM base image (Amazon Linux 2023) for the primary region. */
4
7
  function microvmBaseImageArn(region) {
5
8
  return `arn:aws:lambda:${region}:aws:microvm-image:al2023-1`;
@@ -429,7 +432,16 @@ function microvmImageNode() {
429
432
  },
430
433
  };
431
434
  }
432
- /** ACM certificate (us-east-1) - only present when a custom domain is configured. */
435
+ /**
436
+ * ACM certificate (us-east-1) - only present when a custom domain is configured.
437
+ *
438
+ * Production carries one certificate for every hostname the site serves (the
439
+ * primary as `DomainName`, the rest as subject alternative names), because a
440
+ * distribution takes a single viewer certificate. ACM cannot change the names
441
+ * on an issued certificate, so a changed name set requests a replacement; the
442
+ * old certificate stays attached and is retired by `retirePreviousCertificate`
443
+ * once the distribution carries the new one. Previews keep one wildcard name.
444
+ */
433
445
  function certificateNode() {
434
446
  return {
435
447
  id: 'acm-certificate',
@@ -441,6 +453,10 @@ function certificateNode() {
441
453
  const arn = output(ctx, 'acm-certificate').arn;
442
454
  if (typeof arn !== 'string')
443
455
  return false;
456
+ // A name set that no longer matches needs a replacement, which `create` does.
457
+ if (!ctx.preview && !sameSet(recordedDomains(ctx), await desiredHostnames(ctx))) {
458
+ return false;
459
+ }
444
460
  try {
445
461
  const status = await ctx.clients.acm.describeCertificate(arn);
446
462
  return status.status === 'ISSUED';
@@ -456,15 +472,15 @@ function certificateNode() {
456
472
  const domain = ctx.domain;
457
473
  if (!domain)
458
474
  throw new Error('certificate node requires a domain');
475
+ const out = output(ctx, 'acm-certificate');
459
476
  // Previews are served at <pr-id>.<domain>, so the cert must be wildcard.
460
- const certDomain = ctx.preview ? `*.${domain}` : domain;
461
- let arn = output(ctx, 'acm-certificate').arn;
462
- if (!arn) {
463
- // ACM idempotency token must match \w+ (no dashes).
464
- const token = `${ctx.config.siteName}${ctx.env}`.replace(/\W/g, '');
465
- arn = await ctx.clients.acm.requestCertificate(certDomain, token, ctx.tags);
466
- output(ctx, 'acm-certificate').arn = arn;
467
- await ctx.save();
477
+ const names = ctx.preview ? [`*.${domain}`] : await desiredHostnames(ctx);
478
+ let arn = out.arn;
479
+ if (arn && !ctx.preview && !sameSet(recordedDomains(ctx), names)) {
480
+ arn = await replaceCertificate(ctx, arn, names);
481
+ }
482
+ else if (!arn) {
483
+ arn = await requestCertificate(ctx, names);
468
484
  }
469
485
  let initial = await ctx.clients.acm.describeCertificate(arn);
470
486
  if (initial.status === 'PENDING_VALIDATION' && initial.validation.length === 0) {
@@ -493,11 +509,7 @@ function certificateNode() {
493
509
  ctx.logger.step('created ACM validation records in Route53; waiting for ISSUED…');
494
510
  }
495
511
  else {
496
- ctx.logger.warn('Add these DNS records at your registrar to validate the certificate:');
497
- for (const r of initial.validation) {
498
- ctx.logger.info(` ${r.type} ${r.name} -> ${r.value}`);
499
- }
500
- ctx.logger.step('waiting for certificate to be ISSUED (Ctrl-C to background)…');
512
+ await validateProduction(ctx, initial.validation);
501
513
  }
502
514
  }
503
515
  const settled = await pollUntil(() => ctx.clients.acm.describeCertificate(arn), (s) => s.status === 'ISSUED' || s.status === 'FAILED', { intervalMs: 15_000, timeoutMs: 30 * 60_000 });
@@ -506,12 +518,130 @@ function certificateNode() {
506
518
  }
507
519
  },
508
520
  async delete(ctx) {
509
- const arn = output(ctx, 'acm-certificate').arn;
510
- if (typeof arn === 'string')
511
- await ctx.clients.acm.deleteCertificate(arn);
521
+ const out = output(ctx, 'acm-certificate');
522
+ for (const arn of [out.arn, out.previousArn]) {
523
+ if (typeof arn === 'string')
524
+ await ctx.clients.acm.deleteCertificate(arn);
525
+ }
512
526
  },
513
527
  };
514
528
  }
529
+ /**
530
+ * Request a certificate for `names` (the first is its subject) and record it.
531
+ * `previousArn`, when given, is recorded in the same save as the new ARN, so
532
+ * state never names a superseded certificate that a failed request left
533
+ * without a replacement.
534
+ */
535
+ async function requestCertificate(ctx, names, previousArn) {
536
+ const [subject, ...alternatives] = names;
537
+ if (!subject)
538
+ throw new Error('certificate node requires a domain');
539
+ const out = output(ctx, 'acm-certificate');
540
+ // ACM idempotency token must match \w+ (no dashes) and fit 32 characters.
541
+ const token = ctx.preview
542
+ ? `${ctx.config.siteName}${ctx.env}`.replace(/\W/g, '')
543
+ : certificateToken(ctx.config.siteName, ctx.env, names);
544
+ const arn = await ctx.clients.acm.requestCertificate(subject, token, ctx.tags, alternatives);
545
+ if (previousArn !== undefined)
546
+ out.previousArn = previousArn;
547
+ out.arn = arn;
548
+ out.domains = ctx.preview ? names : [...names].sort();
549
+ await ctx.save();
550
+ return arn;
551
+ }
552
+ /**
553
+ * Swap the recorded certificate for one covering `names`. The certificate the
554
+ * distribution may still be serving is remembered as `previousArn`. When the
555
+ * recorded certificate is not the one attached, it never served and is
556
+ * dropped; when it is attached (an earlier swap finished but ACM refused to
557
+ * delete its predecessor), it becomes the one to retire and the older
558
+ * predecessor is deleted now, since nothing serves it.
559
+ */
560
+ async function replaceCertificate(ctx, current, names) {
561
+ const out = output(ctx, 'acm-certificate');
562
+ ctx.logger.info(` certificate names changed; requesting a replacement for ${names.join(', ')}`);
563
+ const earlier = typeof out.previousArn === 'string' ? out.previousArn : undefined;
564
+ if (earlier === undefined)
565
+ return requestCertificate(ctx, names, current);
566
+ const distributionId = output(ctx, 'cloudfront-distribution').id;
567
+ const live = typeof distributionId === 'string'
568
+ ? await ctx.clients.cloudfront.getDistributionAliases(distributionId)
569
+ : undefined;
570
+ const stale = live?.certificateArn === current ? earlier : current;
571
+ try {
572
+ await ctx.clients.acm.deleteCertificate(stale);
573
+ }
574
+ catch (err) {
575
+ ctx.logger.warn(`could not delete the superseded certificate ${stale}: ${String(err)}`);
576
+ }
577
+ return requestCertificate(ctx, names, stale === current ? earlier : current);
578
+ }
579
+ /**
580
+ * Production DNS validation. With `manageDns` the records whose zone is in the
581
+ * account's Route 53 are created; every other still-pending record is printed,
582
+ * grouped by hostname. A record ACM already marks validated is skipped (the
583
+ * validation CNAME is per hostname, so an apex validated by an earlier
584
+ * certificate needs nothing new).
585
+ */
586
+ async function validateProduction(ctx, records) {
587
+ const pending = new Map();
588
+ for (const r of records) {
589
+ if (r.status !== 'SUCCESS')
590
+ pending.set(`${r.type} ${r.name}`, r);
591
+ }
592
+ const unmanaged = [];
593
+ for (const r of pending.values()) {
594
+ const zone = ctx.config.manageDns
595
+ ? await findHostedZone(ctx.clients.route53, r.domain ?? r.name)
596
+ : undefined;
597
+ if (zone) {
598
+ await ctx.clients.route53.upsertRecord(zone.zoneId, {
599
+ name: r.name,
600
+ type: r.type,
601
+ value: r.value,
602
+ });
603
+ ctx.logger.info(` ${r.domain ?? r.name}: validation record created in Route 53`);
604
+ }
605
+ else {
606
+ unmanaged.push(r);
607
+ }
608
+ }
609
+ if (unmanaged.length > 0) {
610
+ ctx.logger.warn('Add these DNS records at your registrar to validate the certificate:');
611
+ for (const r of unmanaged) {
612
+ ctx.logger.info(` ${r.domain ?? r.name}: ${r.type} ${r.name} -> ${r.value}`);
613
+ }
614
+ ctx.logger.step('waiting for certificate to be ISSUED (Ctrl-C to background)…');
615
+ }
616
+ else {
617
+ ctx.logger.step(pending.size > 0
618
+ ? 'created ACM validation records in Route53; waiting for ISSUED…'
619
+ : 'no validation records pending; waiting for ISSUED…');
620
+ }
621
+ }
622
+ /**
623
+ * Delete the certificate a replacement superseded, once the distribution
624
+ * carries the current one. ACM refuses to delete a certificate CloudFront still
625
+ * references (its update is eventually consistent), so a refusal is kept in
626
+ * state and retried on the next run instead of failing the bootstrap.
627
+ */
628
+ async function retirePreviousCertificate(ctx, distributionId) {
629
+ const out = output(ctx, 'acm-certificate');
630
+ const previous = out.previousArn;
631
+ if (typeof previous !== 'string' || previous === out.arn)
632
+ return;
633
+ const live = await ctx.clients.cloudfront.getDistributionAliases(distributionId);
634
+ if (live?.certificateArn !== out.arn)
635
+ return;
636
+ try {
637
+ await ctx.clients.acm.deleteCertificate(previous);
638
+ Reflect.deleteProperty(out, 'previousArn');
639
+ ctx.logger.ok('superseded certificate deleted');
640
+ }
641
+ catch (err) {
642
+ ctx.logger.warn(`superseded certificate not deleted yet (${String(err)}); it will be retried on the next bootstrap`);
643
+ }
644
+ }
515
645
  /** CloudFront Origin Access Control granting the distribution private read on S3. */
516
646
  function oacNode() {
517
647
  return {
@@ -1191,26 +1321,38 @@ const PREVIEW_FUNCTION_CODE = `function handler(event) {
1191
1321
  return request;
1192
1322
  }`;
1193
1323
  /**
1194
- * CloudFront Function (viewer-request) for staging/production: resolve a directory URL
1195
- * to its index document (`/projects/` → `/projects/index.html`). Required because the S3
1196
- * origin is the private REST endpoint (via OAC), which - unlike an S3 website endpoint -
1197
- * does no index-document resolution, so `DefaultRootObject` only covers the apex. The
1198
- * `/site` origin path is applied by the distribution, so this function must not add it.
1324
+ * The alias redirect this environment runs, or undefined when none applies:
1325
+ * `redirectToPrimary` needs a primary domain and at least one alias.
1199
1326
  */
1200
- const STATIC_ROUTER_CODE = `function handler(event) {
1201
- var request = event.request;
1202
- var uri = request.uri;
1203
- if (uri.endsWith('/')) { uri += 'index.html'; }
1204
- else if (uri.lastIndexOf('.') < uri.lastIndexOf('/')) { uri += '/index.html'; }
1205
- request.uri = uri;
1206
- return request;
1207
- }`;
1327
+ function aliasRedirect(ctx) {
1328
+ const { aliases, redirectToPrimary } = ctx.config;
1329
+ if (!redirectToPrimary || !ctx.domain || aliases.length === 0)
1330
+ return undefined;
1331
+ return { primary: ctx.domain, aliases };
1332
+ }
1208
1333
  /**
1209
1334
  * CloudFront viewer-request function. Preview stacks route a subdomain to its S3 prefix
1210
1335
  * (and resolve index documents); staging/production just resolve directory URLs to their
1211
1336
  * index document. Both are needed because the OAC/REST S3 origin does no index resolution.
1212
1337
  */
1213
1338
  function routerFunctionNode(preview) {
1339
+ /**
1340
+ * The source this environment should run. Staging/production resolve
1341
+ * directory URLs and, with `redirectToPrimary`, also 301 alias hosts to the
1342
+ * primary. SSR sites run the redirect alone, since the application owns its
1343
+ * routing; without a redirect the SSR function is unattached.
1344
+ */
1345
+ function desiredCode(ctx) {
1346
+ if (preview)
1347
+ return PREVIEW_FUNCTION_CODE;
1348
+ const redirect = aliasRedirect(ctx);
1349
+ if (ctx.config.ssr && redirect)
1350
+ return ssrRouterCode(redirect);
1351
+ return staticRouterCode(redirect);
1352
+ }
1353
+ function comment(ctx) {
1354
+ return `${ctx.config.siteName} ${ctx.env} ${preview ? 'preview host router' : 'directory-index router'}`;
1355
+ }
1214
1356
  return {
1215
1357
  id: 'cloudfront-function',
1216
1358
  dependsOn: [],
@@ -1219,13 +1361,28 @@ function routerFunctionNode(preview) {
1219
1361
  return typeof output(ctx, 'cloudfront-function').arn === 'string';
1220
1362
  },
1221
1363
  async create(ctx) {
1222
- const arn = await ctx.clients.cloudfront.ensureFunction(`${ctx.names.prefix}-router`, preview ? PREVIEW_FUNCTION_CODE : STATIC_ROUTER_CODE, `${ctx.config.siteName} ${ctx.env} ${preview ? 'preview host router' : 'directory-index router'}`);
1223
- output(ctx, 'cloudfront-function').arn = arn;
1364
+ const code = desiredCode(ctx);
1365
+ const out = output(ctx, 'cloudfront-function');
1366
+ out.arn = await ctx.clients.cloudfront.ensureFunction(`${ctx.names.prefix}-router`, code, comment(ctx));
1367
+ out.codeHash = routerCodeHash(code);
1224
1368
  },
1225
- async update() {
1226
- // The router code is static; leave the already-published function as-is (updating +
1227
- // re-publishing hits CloudFront's ETag/stage preconditions). To change the router,
1228
- // delete the function (teardown) and re-bootstrap.
1369
+ async update(ctx) {
1370
+ // Preview code is static. Production code varies with the alias redirect, so
1371
+ // republish when the source differs from the one last published. A site
1372
+ // bootstrapped before the hash was recorded, and still on the plain
1373
+ // directory-index router, is left alone: republishing it would change nothing.
1374
+ if (preview)
1375
+ return;
1376
+ const code = desiredCode(ctx);
1377
+ const hash = routerCodeHash(code);
1378
+ const out = output(ctx, 'cloudfront-function');
1379
+ if (out.codeHash === hash)
1380
+ return;
1381
+ if (out.codeHash === undefined && code === staticRouterCode())
1382
+ return;
1383
+ await ctx.clients.cloudfront.ensureFunction(`${ctx.names.prefix}-router`, code, comment(ctx));
1384
+ out.codeHash = hash;
1385
+ ctx.logger.ok('CloudFront routing function republished');
1229
1386
  },
1230
1387
  async delete(ctx) {
1231
1388
  await ctx.clients.cloudfront.deleteFunction(`${ctx.names.prefix}-router`);
@@ -1271,12 +1428,15 @@ function distributionShape(ctx, mode, preview) {
1271
1428
  const shared = {
1272
1429
  callerReference: `${ctx.names.prefix}-${ctx.accountId}`,
1273
1430
  comment: `${ctx.config.siteName} ${ctx.env}`,
1274
- aliases: ctx.domain ? [preview ? `*.${ctx.domain}` : ctx.domain] : [],
1431
+ aliases: ctx.domain ? (preview ? [`*.${ctx.domain}`] : siteHostnames(ctx)) : [],
1275
1432
  acmCertificateArn: ctx.domain ? String(output(ctx, 'acm-certificate').arn) : undefined,
1276
1433
  };
1277
1434
  const responseHeadersPolicyId = desiredResponseHeadersPolicyId(ctx);
1278
1435
  if (mode === 'ssr') {
1279
1436
  const config = ssrConfig(ctx);
1437
+ // Aliases must redirect on every path, static or dynamic, so the function
1438
+ // is on each behavior; without a redirect nothing is attached.
1439
+ const functionArn = !preview && aliasRedirect(ctx) ? String(output(ctx, 'cloudfront-function').arn) : undefined;
1280
1440
  return {
1281
1441
  ...shared,
1282
1442
  // The app answers `/`; a root object would only intercept it.
@@ -1298,6 +1458,7 @@ function distributionShape(ctx, mode, preview) {
1298
1458
  cachePolicyId: String(output(ctx, 'web-cache-policy').id),
1299
1459
  originRequestPolicyId: ALL_VIEWER_EXCEPT_HOST_HEADER,
1300
1460
  allowedMethods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'POST', 'PATCH', 'DELETE'],
1461
+ ...(functionArn ? { functionArn } : {}),
1301
1462
  responseHeadersPolicyId,
1302
1463
  },
1303
1464
  // The static paths carry the headers too: they are the same site's responses.
@@ -1305,6 +1466,7 @@ function distributionShape(ctx, mode, preview) {
1305
1466
  pathPattern,
1306
1467
  targetOriginId: 's3-site',
1307
1468
  cachePolicyId: CACHING_OPTIMIZED,
1469
+ ...(functionArn ? { functionArn } : {}),
1308
1470
  responseHeadersPolicyId,
1309
1471
  })),
1310
1472
  // No custom error responses: the application owns 404s, and error
@@ -1366,19 +1528,13 @@ async function reconcileStaticAliases(ctx, distributionId, preview) {
1366
1528
  ctx.logger.ok('no domain configured - existing aliases left as-is');
1367
1529
  return;
1368
1530
  }
1369
- const alias = preview ? `*.${ctx.domain}` : ctx.domain;
1531
+ // Production: the configured names plus any attached alias config does not
1532
+ // name (kept unless `--prune-aliases`); the certificate node computed the same
1533
+ // set, so the certificate covers whatever is attached.
1534
+ const aliases = preview ? [`*.${ctx.domain}`] : siteHostnames(ctx);
1370
1535
  const certArn = String(output(ctx, 'acm-certificate').arn);
1371
- const changed = await ctx.clients.cloudfront.setDistributionAliases(distributionId, [alias], certArn);
1372
- if (changed) {
1373
- ctx.logger.ok(`attached ${alias} to the distribution`);
1374
- const domainName = output(ctx, 'cloudfront-distribution').domainName;
1375
- if (typeof domainName === 'string') {
1376
- ctx.logger.info(` point ${alias} (CNAME/ALIAS) at ${domainName}`);
1377
- }
1378
- }
1379
- else {
1380
- ctx.logger.ok('aliases up to date');
1381
- }
1536
+ const changed = await ctx.clients.cloudfront.setDistributionAliases(distributionId, aliases, certArn);
1537
+ ctx.logger.ok(changed ? `aliases set to ${aliases.join(', ')}` : 'aliases up to date');
1382
1538
  }
1383
1539
  /** The CloudFront distribution. Preview stacks use a host-routing function + no caching. */
1384
1540
  function distributionNode(options) {
@@ -1453,11 +1609,8 @@ function distributionNode(options) {
1453
1609
  out.mode = servingMode(ctx);
1454
1610
  await ctx.clients.cloudfront.tagResource(dist.arn, ctx.tags);
1455
1611
  ctx.logger.info(` CloudFront domain: ${dist.domainName}`);
1456
- if (ctx.domain && !preview) {
1457
- // Preview stacks create the wildcard record themselves (preview-dns
1458
- // node, next in the graph); only the main site may be DNS'd elsewhere.
1459
- ctx.logger.info(` point ${ctx.domain} (CNAME/ALIAS) at ${dist.domainName}`);
1460
- }
1612
+ // Production routing records are the site-dns node's (next in the graph);
1613
+ // preview stacks create their wildcard record in the preview-dns node.
1461
1614
  },
1462
1615
  async update(ctx) {
1463
1616
  const id = output(ctx, 'cloudfront-distribution').id;
@@ -1477,18 +1630,18 @@ function distributionNode(options) {
1477
1630
  recordResponseHeadersPolicyAttached(ctx, id);
1478
1631
  if (changed) {
1479
1632
  ctx.logger.ok(`reconciled the distribution for ${configured} serving`);
1480
- const domainName = out.domainName;
1481
- if (ctx.domain && !preview && typeof domainName === 'string') {
1482
- ctx.logger.info(` point ${ctx.domain} (CNAME/ALIAS) at ${domainName}`);
1483
- }
1484
1633
  }
1485
1634
  else {
1486
1635
  ctx.logger.ok(`distribution already matches ${configured} serving`);
1487
1636
  }
1637
+ if (!preview)
1638
+ await retirePreviousCertificate(ctx, id);
1488
1639
  return;
1489
1640
  }
1490
1641
  await reconcileStaticAliases(ctx, id, preview);
1491
1642
  await attachResponseHeadersPolicy(ctx, id);
1643
+ if (!preview)
1644
+ await retirePreviousCertificate(ctx, id);
1492
1645
  },
1493
1646
  async delete(ctx) {
1494
1647
  const id = output(ctx, 'cloudfront-distribution').id;
@@ -1992,6 +2145,121 @@ function previewDnsNode() {
1992
2145
  },
1993
2146
  };
1994
2147
  }
2148
+ /**
2149
+ * Routing for the production hostnames: the records that point each name at
2150
+ * the distribution. With `manageDns`, hosts whose hosted zone is in the
2151
+ * account's Route 53 get A and AAAA alias records (recorded in state so a
2152
+ * teardown or a prune removes them); every other host is printed, as an
2153
+ * apex or a sub-domain according to what DNS says its zone is. Guidance is
2154
+ * printed when it changes, not on every run.
2155
+ */
2156
+ function siteDnsNode() {
2157
+ const TYPES = ['A', 'AAAA'];
2158
+ async function reconcile(ctx) {
2159
+ const target = output(ctx, 'cloudfront-distribution').domainName;
2160
+ if (typeof target !== 'string')
2161
+ return;
2162
+ const out = output(ctx, 'site-dns');
2163
+ const hosts = siteHostnames(ctx);
2164
+ const previousHosts = Array.isArray(out.hosts) ? out.hosts : [];
2165
+ const previousZones = Array.isArray(out.zoneIds) ? out.zoneIds : [];
2166
+ const managedHosts = [];
2167
+ const managedZones = [];
2168
+ const guidance = [];
2169
+ for (const host of hosts) {
2170
+ const zone = ctx.config.manageDns
2171
+ ? await findHostedZone(ctx.clients.route53, host)
2172
+ : undefined;
2173
+ if (zone) {
2174
+ try {
2175
+ for (const type of TYPES) {
2176
+ await ctx.clients.route53.upsertRecord(zone.zoneId, {
2177
+ name: host,
2178
+ type,
2179
+ value: target,
2180
+ aliasZoneId: CLOUDFRONT_ALIAS_ZONE_ID,
2181
+ });
2182
+ }
2183
+ managedHosts.push(host);
2184
+ managedZones.push(zone.zoneId);
2185
+ ctx.logger.info(` ${host} -> ${target} (Route 53 alias)`);
2186
+ continue;
2187
+ }
2188
+ catch (err) {
2189
+ // A CNAME already at the name is the usual cause; fall back to guidance.
2190
+ ctx.logger.warn(`could not write Route 53 records for ${host}: ${String(err)}`);
2191
+ }
2192
+ }
2193
+ guidance.push(await routingGuidance(ctx.ports.dns, host, target));
2194
+ }
2195
+ // Records this node wrote for a host that is no longer served.
2196
+ for (const [i, host] of previousHosts.entries()) {
2197
+ const zoneId = previousZones[i];
2198
+ if (hosts.includes(host) || zoneId === undefined)
2199
+ continue;
2200
+ for (const type of TYPES) {
2201
+ await ctx.clients.route53.deleteRecord(zoneId, {
2202
+ name: host,
2203
+ type,
2204
+ value: target,
2205
+ aliasZoneId: CLOUDFRONT_ALIAS_ZONE_ID,
2206
+ });
2207
+ }
2208
+ }
2209
+ // A host still served but not written this run (manageDns turned off, or a
2210
+ // write that fell back to guidance) keeps its record of what was written,
2211
+ // so a later prune or teardown still removes the records.
2212
+ for (const [i, host] of previousHosts.entries()) {
2213
+ const zoneId = previousZones[i];
2214
+ if (zoneId === undefined || !hosts.includes(host) || managedHosts.includes(host))
2215
+ continue;
2216
+ managedHosts.push(host);
2217
+ managedZones.push(zoneId);
2218
+ }
2219
+ out.hosts = managedHosts;
2220
+ out.zoneIds = managedZones;
2221
+ const signature = createHash('sha256')
2222
+ .update([target, ...hosts, ...guidance].join('\n'))
2223
+ .digest('hex');
2224
+ if (guidance.length > 0 && out.signature !== signature) {
2225
+ ctx.logger.warn(`Point these hostnames at ${target}:`);
2226
+ for (const line of guidance)
2227
+ ctx.logger.info(` ${line}`);
2228
+ }
2229
+ out.signature = signature;
2230
+ }
2231
+ return {
2232
+ id: 'site-dns',
2233
+ dependsOn: ['cloudfront-distribution'],
2234
+ title: 'Site DNS routing',
2235
+ async read(ctx) {
2236
+ return typeof output(ctx, 'site-dns').signature === 'string';
2237
+ },
2238
+ create: reconcile,
2239
+ update: reconcile,
2240
+ async delete(ctx) {
2241
+ const out = output(ctx, 'site-dns');
2242
+ const target = output(ctx, 'cloudfront-distribution').domainName;
2243
+ const hosts = Array.isArray(out.hosts) ? out.hosts : [];
2244
+ const zones = Array.isArray(out.zoneIds) ? out.zoneIds : [];
2245
+ if (typeof target !== 'string')
2246
+ return;
2247
+ for (const [i, host] of hosts.entries()) {
2248
+ const zoneId = zones[i];
2249
+ if (zoneId === undefined)
2250
+ continue;
2251
+ for (const type of TYPES) {
2252
+ await ctx.clients.route53.deleteRecord(zoneId, {
2253
+ name: host,
2254
+ type,
2255
+ value: target,
2256
+ aliasZoneId: CLOUDFRONT_ALIAS_ZONE_ID,
2257
+ });
2258
+ }
2259
+ }
2260
+ },
2261
+ };
2262
+ }
1995
2263
  /** Build the full node set for the current context (production or preview stack). */
1996
2264
  export function buildNodes(ctx) {
1997
2265
  const hasDomain = Boolean(ctx.domain);
@@ -2023,6 +2291,8 @@ export function buildNodes(ctx) {
2023
2291
  nodes.push(webFunctionPolicyNode());
2024
2292
  if (hasDomain)
2025
2293
  nodes.push(certificateNode());
2294
+ if (hasDomain && !ctx.preview)
2295
+ nodes.push(siteDnsNode());
2026
2296
  if (ctx.preview) {
2027
2297
  nodes.push(previewDnsNode(), githubOidcRoleNode(true, false));
2028
2298
  }
package/dist/ports.d.ts CHANGED
@@ -124,6 +124,20 @@ export interface AwsLogin {
124
124
  run(args: readonly string[]): Promise<AwsLoginResult>;
125
125
  }
126
126
  /** The ports domain code reaches side effects through; adapters are wired in createContext. */
127
+ /**
128
+ * DNS questions the multi-domain bootstrap asks. The real adapter queries the
129
+ * system resolver and falls back to public ones; it throws only when no
130
+ * resolver could answer at all.
131
+ */
132
+ export interface DnsPort {
133
+ /**
134
+ * An opaque fingerprint of the SOA record `name` answers with, or
135
+ * `undefined` when it has none. A resolver follows a CNAME when asked for
136
+ * SOA, so `www` aliased to an apex answers with the apex's record; callers
137
+ * compare fingerprints rather than treating any answer as "this is a zone".
138
+ */
139
+ soa(name: string): Promise<string | undefined>;
140
+ }
127
141
  export interface Ports {
128
142
  fs: FileSystem;
129
143
  vcs: Vcs;
@@ -131,4 +145,5 @@ export interface Ports {
131
145
  ping: PingBuilder;
132
146
  loader: ModuleLoader;
133
147
  awsLogin: AwsLogin;
148
+ dns: DnsPort;
134
149
  }
@@ -0,0 +1,24 @@
1
+ /** Hosts whose requests redirect, and the host they redirect to. */
2
+ export interface AliasRedirect {
3
+ /** The canonical host (`OpsConfig.domain`); the redirect target. */
4
+ primary: string;
5
+ /** Hosts that answer with a `301` to `primary`. */
6
+ aliases: readonly string[];
7
+ }
8
+ /**
9
+ * Source of the production/staging CloudFront viewer-request function. With no
10
+ * `redirect` it is the directory-index rewrite alone, byte-for-byte what every
11
+ * existing site already runs. A distribution allows one function per event
12
+ * type, so the alias redirect is folded into this function rather than being a
13
+ * second one.
14
+ */
15
+ export declare function staticRouterCode(redirect?: AliasRedirect): string;
16
+ /**
17
+ * Source of the viewer-request function an SSR distribution runs when
18
+ * `redirectToPrimary` is set. The application owns its own routing, so unlike
19
+ * the static router there is no directory-index rewrite: alias hosts get the
20
+ * `301` and every other request passes through untouched.
21
+ */
22
+ export declare function ssrRouterCode(redirect: AliasRedirect): string;
23
+ /** Stable fingerprint of a function's source, recorded in state to detect a change. */
24
+ export declare function routerCodeHash(code: string): string;
@@ -0,0 +1,71 @@
1
+ import { createHash } from 'node:crypto';
2
+ /**
3
+ * The directory-index rewrite every static-mode request goes through. The
4
+ * S3 origin is the private REST endpoint (via OAC), which - unlike an S3
5
+ * website endpoint - does no index-document resolution, so `/projects/`
6
+ * becomes `/projects/index.html` here. The `/site` origin path is applied by
7
+ * the distribution, so this must not add it.
8
+ */
9
+ const INDEX_REWRITE = ` var uri = request.uri;
10
+ if (uri.endsWith('/')) { uri += 'index.html'; }
11
+ else if (uri.lastIndexOf('.') < uri.lastIndexOf('/')) { uri += '/index.html'; }
12
+ request.uri = uri;
13
+ return request;`;
14
+ /**
15
+ * Host check that runs ahead of the rewrite when `redirectToPrimary` is set:
16
+ * a request for an alias answers `301` to the same path and query on the
17
+ * primary. It reads `request.uri` before the rewrite touches it, so the
18
+ * redirect target is the URL the viewer asked for, not the origin key.
19
+ */
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
+ }
31
+ return {
32
+ statusCode: 301,
33
+ statusDescription: 'Moved Permanently',
34
+ headers: {
35
+ location: { value: 'https://' + ${JSON.stringify(redirect.primary)} + request.uri + (parts.length ? '?' + parts.join('&') : '') }
36
+ }
37
+ };
38
+ }
39
+ `;
40
+ }
41
+ /**
42
+ * Source of the production/staging CloudFront viewer-request function. With no
43
+ * `redirect` it is the directory-index rewrite alone, byte-for-byte what every
44
+ * existing site already runs. A distribution allows one function per event
45
+ * type, so the alias redirect is folded into this function rather than being a
46
+ * second one.
47
+ */
48
+ export function staticRouterCode(redirect) {
49
+ const block = redirect && redirect.aliases.length > 0 ? redirectBlock(redirect) : '';
50
+ return `function handler(event) {
51
+ var request = event.request;
52
+ ${block}${INDEX_REWRITE}
53
+ }`;
54
+ }
55
+ /**
56
+ * Source of the viewer-request function an SSR distribution runs when
57
+ * `redirectToPrimary` is set. The application owns its own routing, so unlike
58
+ * the static router there is no directory-index rewrite: alias hosts get the
59
+ * `301` and every other request passes through untouched.
60
+ */
61
+ export function ssrRouterCode(redirect) {
62
+ const block = redirect.aliases.length > 0 ? redirectBlock(redirect) : '';
63
+ return `function handler(event) {
64
+ var request = event.request;
65
+ ${block} return request;
66
+ }`;
67
+ }
68
+ /** Stable fingerprint of a function's source, recorded in state to detect a change. */
69
+ export function routerCodeHash(code) {
70
+ return createHash('sha256').update(code).digest('hex');
71
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blogwright",
3
- "version": "0.5.0",
3
+ "version": "0.6.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.5.0"
20
+ "blogwright-core": "0.6.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.5.0",
25
+ "blogwright-pds": "0.6.0",
26
26
  "fflate": "^0.8.3",
27
27
  "oxlint": "^1.90.0",
28
28
  "typescript": "^6.0.3",