@rathnasgala2/adapter-github-pages 0.1.1 → 0.1.3

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.
package/CHANGELOG.md CHANGED
@@ -8,8 +8,69 @@ and this project adheres to
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.1.3] - 2026-10-23
12
+
13
+ ### Fixed
14
+
15
+ - The shipped TypeScript declarations (`types/`) are regenerated from `src/`.
16
+ The 0.1.2 package shipped the `observe` CDN wait and the transport error
17
+ policy in `src/` but declarations that predated them, so a TypeScript consumer
18
+ saw no `now` clock on the destination, no `cacheControl` on a public read and
19
+ no `entries` on the staged and certified records. The declarations now carry
20
+ `PagesDestination.now`, the `ObserveProgress` type, `readServedGeneration`,
21
+ `maxAgeSeconds` and the `cacheControl` and `entries` members. There is no
22
+ runtime change from 0.1.2.
23
+
24
+ ## [0.1.2] - 2026-10-23
25
+
26
+ ### Added
27
+
28
+ - `destination.verificationBaseUrl` (optional, https): the origin that is
29
+ serving right now. Every public read used for verification (marker reads,
30
+ `inspectDestination`, `preflight`, `activate`'s fence read, `observe` and the
31
+ route reads) uses it when present and `publicBaseUrl` otherwise, joined the
32
+ same way. A redirect there is still `PAGES_PUBLIC_REDIRECT`.
33
+
11
34
  ### Fixed
12
35
 
36
+ - `observe` no longer reports a freshly activated generation as unverified
37
+ because the Pages CDN still serves the previous one. GitHub Pages serves
38
+ `cache-control: max-age=600` and its CDN ignores query strings and request
39
+ cache headers, so cache-busting is impossible. `observe` now re-observes the
40
+ marker and every staged route with a backoff (5 s doubling to 30 s) until the
41
+ marker and the artifact digest match, for at most the served `max-age`
42
+ (default 600 s, capped at 900 s) plus a 60 s margin, and then reports the last
43
+ observation's findings. A redirect (`PAGES_PUBLIC_REDIRECT`) and a generation
44
+ this run never staged still fail at once without waiting. The destination
45
+ accepts an optional `now` clock beside `sleep` for tests.
46
+
47
+ The waiting is bounded in requests too. The first pass reads the marker and
48
+ every staged route. Later passes re-read the marker only until it matches,
49
+ plus a rotating sample of at most 20 still-unmatched routes; once the marker
50
+ and the sample match, the remaining unmatched routes are read in the same
51
+ pass. Routes that matched are kept, and a site of 50 routes or fewer re-reads
52
+ what matched in earlier passes once more before reporting success. The digest
53
+ is computed over the whole coherent set. The request count is about passes x
54
+ (20 + 1) + 2 x routes; there is no request cap that can end the wait early.
55
+ Transient transport errors (ECONNRESET, ETIMEDOUT, ECONNREFUSED, EPIPE,
56
+ EAI_AGAIN, the undici socket and timeout codes, TimeoutError) are retried
57
+ within the deadline and reported as findings (`verified: false`) if they
58
+ persist, and the same code on three consecutive passes stops the wait.
59
+ Name-resolution, certificate and TLS errors, a body over the ceiling and
60
+ programming errors still throw at once. The declared `managedExecutionBudget`
61
+ stays at the schema maximum of 1500 seconds, below the true worst case (1500 s
62
+ activation poll plus up to 960 s of observe waiting).
63
+
64
+ - A redirecting public origin no longer throws out of the lifecycle. A site
65
+ whose repository still carried the `github.io` base after moving to a custom
66
+ domain made the public read's `redirect: 'error'` fetch throw (production
67
+ incident 2026-10-21), so the run died without a journal. `readPublic` now
68
+ returns `{status: 'redirect', toHost, location}` (the `Location` is read with
69
+ one extra credential-free `redirect: 'manual'` request, still followed
70
+ nowhere, bounded to ten seconds, body cancelled, http(s) targets only, and
71
+ only undici's exact refused-redirect error counts); `inspectDestination` and
72
+ `observe` carry `failure: {code: 'PAGES_PUBLIC_REDIRECT', toHost, location}`
73
+ and a `PAGES_PUBLIC_REDIRECT:` finding, and `preflight` refuses with it.
13
74
  - Accept GitHub's `deployment_queued` Pages deployment status as temporary (keep
14
75
  polling). It is in GitHub's REST reference but was missing from the accepted
15
76
  vocabulary, so a real publish on 2026-10-06 stopped with
package/README.md CHANGED
@@ -49,6 +49,9 @@ them as the weakest true claim rather than hiding them:
49
49
  - it never mints a `pagesReconciliationRecovery` record, a run-attempt gap proof
50
50
  or a tombstone: it validates the server-minted record and refuses a malformed
51
51
  one;
52
+ - it never follows a redirect from the public origin and never serves or
53
+ configures a custom domain (`configuration.customDomains: false`): a redirect
54
+ is reported, not followed (see "A redirecting public origin");
52
55
  - it declares `providerInventoryAssurance: none` and never claims complete
53
56
  deployed inventory; and
54
57
  - it declares `cacheInvalidation: none` and has no purge authority.
@@ -174,7 +177,8 @@ release the destination fence.
174
177
  repositoryId,
175
178
  repositoryOwnerId,
176
179
  apiOrigin, // https origin; defaults to https://api.github.com
177
- publicBaseUrl, // https origin of the activated Pages site
180
+ publicBaseUrl, // https base the artifact was built for
181
+ verificationBaseUrl, // optional https base serving right now; verification reads use it
178
182
  token, // caller-supplied installation token
179
183
  oidcToken, // caller-supplied Pages OIDC JWT (or pass per-activate)
180
184
  oidcClaims, // its expected ref/sha/run/job_workflow bindings
@@ -195,6 +199,45 @@ untars the carrier this adapter produced, and serves the result from a separate
195
199
  public origin. `test/carrier.test.js` holds the codec goldens. What none of that
196
200
  can prove is the live GitHub Pages deployment API itself; that is backlog W4-16.
197
201
 
202
+ ## The origin the public reads go to
203
+
204
+ The artifact is built for `publicBaseUrl` (the publication's canonical base),
205
+ but the origin that answers over HTTPS right now can differ: the `github.io`
206
+ project path before the Pages CNAME is set, the custom base once the custom
207
+ domain serves. A destination may name it as `verificationBaseUrl`; every public
208
+ read used for verification (the marker read behind `inspectDestination`,
209
+ `preflight`, `activate`'s fence read and `observe`, and the route reads) uses it
210
+ when present and `publicBaseUrl` otherwise. Artifact-relative paths are joined
211
+ to either the same way, so the marker of an artifact built for a root base is
212
+ found at `<project path>/.well-known/gala-generation.json` while the project
213
+ path serves. It must be an https URL. A redirect at the verification origin is
214
+ still `PAGES_PUBLIC_REDIRECT`.
215
+
216
+ ## A redirecting public origin
217
+
218
+ The adapter declares `customDomains: false`, but a site's `publicBaseUrl` can
219
+ still name a host the site has moved away from (a custom domain attached to the
220
+ Pages site while the repository keeps the `github.io` base), and the origin then
221
+ answers `301`/`302`/`307`/`308`. The public reads keep `redirect: 'error'` and
222
+ follow nothing; a redirect is classified instead of thrown:
223
+
224
+ - `readPublic` returns `{status: 'redirect', toHost, location}`. A refused
225
+ redirect exposes no `Location`, so the same credential-free URL is asked once
226
+ more with `redirect: 'manual'` to read it (still followed nowhere); `toHost`
227
+ and `location` are `null` when none could be read, when the probe takes more
228
+ than ten seconds, or when `Location` is not an http(s) URL; the probe's body
229
+ is cancelled unread. Only undici's exact refused-redirect failure (`TypeError`
230
+ whose cause is `unexpected redirect`) is a redirect; any other fetch error
231
+ still throws.
232
+ - `inspectDestination` and `observe` report the generation as unknown (never a
233
+ throw), add a finding that starts `PAGES_PUBLIC_REDIRECT:` and carry
234
+ `failure: {code: 'PAGES_PUBLIC_REDIRECT', toHost, location}`. `preflight`
235
+ refuses with the same finding, so the kernel stops before staging.
236
+ - The remedy is the base URL: set it to the redirect target and publish again.
237
+
238
+ This is a result, not a `PagesAdapterError`: a redirecting origin is a
239
+ destination fact the kernel journals, not an adapter defect.
240
+
198
241
  ## Errors
199
242
 
200
243
  Every refusal this package raises is a `PagesAdapterError` (`src/errors.js`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rathnasgala2/adapter-github-pages",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Managed GitHub Pages deployment adapter: deterministic uncompressed ustar Pages carrier, raw Pages deployment REST catalog, bounded status polling and credential-free public verification.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
package/src/capability.js CHANGED
@@ -157,6 +157,9 @@ export function describeCapabilities(context) {
157
157
  configuration: {
158
158
  redirects: false,
159
159
  headers: false,
160
+ // No custom-domain configuration or serving. A base URL that names a
161
+ // host the site has since moved away from is reported by the public
162
+ // reads as `PAGES_PUBLIC_REDIRECT`, never followed or configured.
160
163
  customDomains: false,
161
164
  notFoundBehavior: ROW.notFoundBehavior,
162
165
  immutableCaching: false,
@@ -199,6 +202,9 @@ export function describeCapabilities(context) {
199
202
  DOMAIN_PAGES_CREDENTIAL_EGRESS,
200
203
  CREDENTIAL_EGRESS_PROFILE,
201
204
  ),
205
+ // The schema caps providerExecutionSeconds and totalSeconds at 1500, so
206
+ // the true worst case (1500 s activation poll plus up to 960 s of
207
+ // observe waiting) cannot be declared here.
202
208
  managedExecutionBudget: {
203
209
  verifiedHandoffSeconds: 120,
204
210
  pagesCarrierConstructionSeconds: 300,
package/src/index.js CHANGED
@@ -49,7 +49,7 @@ import {
49
49
  } from './deployment.js';
50
50
  import { decodeCarrier, encodeCarrier } from './carrier.js';
51
51
  import { buildValidatedMarker, parsePublicMarker } from './marker.js';
52
- import { readPublic } from './public-read.js';
52
+ import { maxAgeSeconds, readPublic } from './public-read.js';
53
53
  import { requireOidcExpectation } from './oidc.js';
54
54
  import {
55
55
  resolvePriorAttempt,
@@ -111,11 +111,13 @@ export {
111
111
  * oidcToken?: string,
112
112
  * oidcClaims?: import('./oidc.js').PagesOidcExpectation,
113
113
  * publicBaseUrl: string,
114
+ * verificationBaseUrl?: string,
114
115
  * token: string,
115
116
  * publishCarrier: (input: {bytes: Buffer, generationId: string, carrierDigest: string}) => Promise<{pagesArtifactId: string | number, artifactDigest?: string, byteCount?: number}>,
116
117
  * fetch?: typeof globalThis.fetch,
117
118
  * publicFetch?: typeof globalThis.fetch,
118
119
  * sleep?: (seconds: number) => Promise<void>,
120
+ * now?: () => number,
119
121
  * runId?: string,
120
122
  * runAttempt?: number,
121
123
  * headSha?: string
@@ -156,6 +158,14 @@ function restContextFor(destination) {
156
158
  if (!destination.publicBaseUrl.startsWith('https://')) {
157
159
  throw new TypeError('destination.publicBaseUrl must be an https origin');
158
160
  }
161
+ if (
162
+ destination.verificationBaseUrl !== undefined &&
163
+ !destination.verificationBaseUrl.startsWith('https://')
164
+ ) {
165
+ throw new TypeError(
166
+ 'destination.verificationBaseUrl must be an https origin',
167
+ );
168
+ }
159
169
  if (typeof destination.publishCarrier !== 'function') {
160
170
  throw new TypeError(
161
171
  'destination.publishCarrier is required: adapter-github-pages never uploads an Actions artifact itself (DEC-097 section 2.3 makes direct carrier upload workflow-owned)',
@@ -172,13 +182,20 @@ function restContextFor(destination) {
172
182
  }
173
183
 
174
184
  /**
185
+ * The public context every verification read uses: the marker read, the
186
+ * route reads and the inspection. The origin that is serving right now
187
+ * (`verificationBaseUrl`: the `github.io` project path before the Pages CNAME
188
+ * is set, the custom base once the custom domain serves) when the destination
189
+ * names one, else `publicBaseUrl`. Artifact-relative paths are joined to it
190
+ * the same way under either.
191
+ *
175
192
  * @param {PagesDestination} destination the destination
176
193
  * @returns {import('./public-read.js').PublicContext} the public context
177
194
  */
178
195
  function publicContextFor(destination) {
179
196
  const injected = destination.publicFetch ?? destination.fetch;
180
197
  return Object.freeze({
181
- publicBaseUrl: destination.publicBaseUrl,
198
+ publicBaseUrl: destination.verificationBaseUrl ?? destination.publicBaseUrl,
182
199
  ...(injected === undefined ? {} : { fetch: injected }),
183
200
  });
184
201
  }
@@ -194,12 +211,49 @@ export async function describeCapabilities(destination) {
194
211
  return Promise.resolve(buildCapabilities({ apiOrigin: context.apiOrigin }));
195
212
  }
196
213
 
214
+ /**
215
+ * The classified failure the adapter reports when the public origin answers
216
+ * with a redirect instead of the route: the destination's `publicBaseUrl` no
217
+ * longer names the host that serves the site (typically a custom domain was
218
+ * attached while the repository still carries the `github.io` base). The
219
+ * adapter follows no redirect, so it cannot tell what the origin serves.
220
+ *
221
+ * @typedef {Readonly<{
222
+ * code: 'PAGES_PUBLIC_REDIRECT',
223
+ * toHost: string | null,
224
+ * location: string | null
225
+ * }>} PublicRedirectFailure
226
+ */
227
+
228
+ /**
229
+ * @param {{toHost?: string | null, location?: string | null}} redirect a
230
+ * `'redirect'` public read
231
+ * @returns {PublicRedirectFailure} the classified failure
232
+ */
233
+ function publicRedirectFailure(redirect) {
234
+ return Object.freeze({
235
+ code: /** @type {const} */ ('PAGES_PUBLIC_REDIRECT'),
236
+ toHost: redirect.toHost ?? null,
237
+ location: redirect.location ?? null,
238
+ });
239
+ }
240
+
241
+ /**
242
+ * @param {PublicRedirectFailure} failure the classified failure
243
+ * @returns {string} the finding that states it
244
+ */
245
+ function publicRedirectFinding(failure) {
246
+ return `${failure.code}: the public origin answered with a redirect to ${failure.toHost ?? 'a target it did not name as an http(s) URL'} instead of serving the route; the site's base URL no longer names the host that serves it, so set the base URL to the redirect target and publish again`;
247
+ }
248
+
197
249
  /**
198
250
  * Read the generation identity the public origin currently serves, or
199
- * `null` when nothing has ever been activated.
251
+ * `null` when nothing has ever been activated. A redirecting origin is
252
+ * reported as the `PAGES_PUBLIC_REDIRECT` failure with the generation
253
+ * unknown, never thrown.
200
254
  *
201
255
  * @param {PagesDestination} destination the bound destination
202
- * @returns {Promise<{generationId: string | null, artifactDigest: string | null, findings: string[]}>}
256
+ * @returns {Promise<{generationId: string | null, artifactDigest: string | null, findings: string[], cacheControl?: string | null | undefined, failure?: PublicRedirectFailure}>}
203
257
  * the observed public generation
204
258
  */
205
259
  async function readServedGeneration(destination) {
@@ -207,13 +261,28 @@ async function readServedGeneration(destination) {
207
261
  publicContextFor(destination),
208
262
  GENERATION_MARKER_PATH,
209
263
  );
264
+ if (observation.status === 'redirect') {
265
+ const failure = publicRedirectFailure(observation);
266
+ return {
267
+ generationId: null,
268
+ artifactDigest: null,
269
+ findings: [publicRedirectFinding(failure)],
270
+ failure,
271
+ };
272
+ }
210
273
  if (observation.status === 404) {
211
- return { generationId: null, artifactDigest: null, findings: [] };
274
+ return {
275
+ generationId: null,
276
+ artifactDigest: null,
277
+ findings: [],
278
+ cacheControl: observation.cacheControl,
279
+ };
212
280
  }
213
281
  if (observation.status !== 200 || observation.bytes === null) {
214
282
  return {
215
283
  generationId: null,
216
284
  artifactDigest: null,
285
+ cacheControl: observation.cacheControl,
217
286
  findings: [
218
287
  `public generation marker read returned HTTP ${observation.status}; the served generation is unknown, not absent`,
219
288
  ],
@@ -225,12 +294,14 @@ async function readServedGeneration(destination) {
225
294
  generationId: null,
226
295
  artifactDigest: null,
227
296
  findings: parsed.findings,
297
+ cacheControl: observation.cacheControl,
228
298
  };
229
299
  }
230
300
  return {
231
301
  generationId: String(parsed.marker.generationId),
232
302
  artifactDigest: String(parsed.marker.artifactDigest),
233
303
  findings: [],
304
+ cacheControl: observation.cacheControl,
234
305
  };
235
306
  }
236
307
 
@@ -244,7 +315,8 @@ async function readServedGeneration(destination) {
244
315
  * retainedHistory: readonly Readonly<Record<string, unknown>>[],
245
316
  * releaseGenerationsOnDisk: readonly string[],
246
317
  * providerSiteObserved: boolean,
247
- * findings: readonly string[]
318
+ * findings: readonly string[],
319
+ * failure?: PublicRedirectFailure
248
320
  * }>>} the inspection result
249
321
  */
250
322
  export async function inspectDestination(destination) {
@@ -277,6 +349,7 @@ export async function inspectDestination(destination) {
277
349
  ),
278
350
  providerSiteObserved,
279
351
  findings: Object.freeze(findings),
352
+ ...(served.failure === undefined ? {} : { failure: served.failure }),
280
353
  });
281
354
  }
282
355
 
@@ -448,6 +521,9 @@ export async function stage(input) {
448
521
  artifactId: input.artifactId,
449
522
  artifactDigest: input.artifactDigest,
450
523
  entryPaths: Object.freeze(input.files.map((file) => file.path)),
524
+ entries: Object.freeze(
525
+ input.files.map((file) => projectEntry(file.path, file.bytes)),
526
+ ),
451
527
  carrierBytes,
452
528
  carrierDigest,
453
529
  pagesArtifactId,
@@ -627,6 +703,8 @@ export async function activate(input) {
627
703
  certifiedAt: new Date().toISOString(),
628
704
  entryPaths:
629
705
  state.stages.get(input.stageToken)?.entryPaths ?? Object.freeze([]),
706
+ entries:
707
+ state.stages.get(input.stageToken)?.entries ?? Object.freeze([]),
630
708
  });
631
709
  return Object.freeze({
632
710
  decision: /** @type {'activate'} */ ('activate'),
@@ -756,6 +834,7 @@ export async function activate(input) {
756
834
  // staged carrier so `cleanupStaged` can discard the carrier without
757
835
  // taking `observe`'s ability to verify the live generation with it.
758
836
  entryPaths: record.entryPaths,
837
+ entries: record.entries,
759
838
  });
760
839
 
761
840
  return Object.freeze({
@@ -790,14 +869,415 @@ export async function activate(input) {
790
869
  * currentGenerationId: string | null,
791
870
  * markerValid: boolean,
792
871
  * claimsCompleteInventory: false,
793
- * findings: readonly string[]
872
+ * findings: readonly string[],
873
+ * failure?: PublicRedirectFailure
794
874
  * }>>} the observation result
795
875
  */
796
876
  export async function observe(input) {
797
877
  restContextFor(input.destination);
878
+ const sleep = input.destination.sleep ?? defaultSleep;
879
+ const clock = input.destination.now ?? Date.now;
880
+ const startedAt = clock();
881
+ let slept = 0;
882
+ let delay = OBSERVE_FIRST_DELAY_SECONDS;
883
+ /** @type {ObserveProgress} */
884
+ const progress = {
885
+ matched: new Map(),
886
+ matchedPass: new Map(),
887
+ latest: new Map(),
888
+ statuses: new Map(),
889
+ served: null,
890
+ markerPass: -1,
891
+ pass: 0,
892
+ cursor: 0,
893
+ confirmed: false,
894
+ errorCode: null,
895
+ errorStreak: 0,
896
+ };
897
+ let attempt = await observeOnce(input, progress);
898
+ let deadline = observeDeadlineSeconds(attempt.maxAgeSeconds);
899
+ for (;;) {
900
+ const result = { ...attempt };
901
+ const retryable = attempt.retryable;
902
+ // @ts-expect-error the retry hints are internal and never returned
903
+ delete result.retryable;
904
+ // @ts-expect-error the retry hints are internal and never returned
905
+ delete result.maxAgeSeconds;
906
+ if (result.verified || !retryable) {
907
+ return Object.freeze(result);
908
+ }
909
+ deadline = Math.max(
910
+ deadline,
911
+ observeDeadlineSeconds(attempt.maxAgeSeconds),
912
+ );
913
+ const elapsed = Math.max(slept, (clock() - startedAt) / 1000);
914
+ const wait = Math.min(delay, deadline - elapsed);
915
+ if (wait <= 0) {
916
+ return Object.freeze(result);
917
+ }
918
+ await sleep(wait);
919
+ slept += wait;
920
+ delay = Math.min(delay * 2, OBSERVE_MAXIMUM_DELAY_SECONDS);
921
+ attempt = await observeOnce(input, progress);
922
+ }
923
+ }
924
+
925
+ /** First wait between observations, doubling up to the maximum. */
926
+ const OBSERVE_FIRST_DELAY_SECONDS = 5;
927
+ /** Longest wait between two observations. */
928
+ const OBSERVE_MAXIMUM_DELAY_SECONDS = 30;
929
+ /** Lifetime assumed when the origin declares no `max-age`. */
930
+ const OBSERVE_DEFAULT_MAX_AGE_SECONDS = 600;
931
+ /** Longest declared `max-age` that is waited out. */
932
+ const OBSERVE_MAXIMUM_MAX_AGE_SECONDS = 900;
933
+ /** Margin added to the cache lifetime. */
934
+ const OBSERVE_MARGIN_SECONDS = 60;
935
+
936
+ /**
937
+ * How long a stale public read may keep disagreeing: the CDN lifetime plus a
938
+ * margin.
939
+ *
940
+ * @param {number | null} declared the largest `max-age` seen, if any
941
+ * @returns {number} the deadline in seconds since the first observation
942
+ */
943
+ function observeDeadlineSeconds(declared) {
944
+ const lifetime = Math.min(
945
+ declared ?? OBSERVE_DEFAULT_MAX_AGE_SECONDS,
946
+ OBSERVE_MAXIMUM_MAX_AGE_SECONDS,
947
+ );
948
+ return Math.max(lifetime, 0) + OBSERVE_MARGIN_SECONDS;
949
+ }
950
+
951
+ /**
952
+ * @param {number} seconds seconds to wait
953
+ * @returns {Promise<void>} resolves after the wait
954
+ */
955
+ function defaultSleep(seconds) {
956
+ return new Promise((resolve) => {
957
+ setTimeout(resolve, seconds * 1000);
958
+ });
959
+ }
960
+
961
+ /**
962
+ * What `observe` keeps between passes so a retry reads only what is still
963
+ * wrong: the routes whose bytes already match the staged entry, the latest
964
+ * bytes of the others, and the marker read until it matches.
965
+ *
966
+ * @typedef {{
967
+ * matched: Map<string, import('./artifact-projection.js').ArtifactEntry>,
968
+ * matchedPass: Map<string, number>,
969
+ * latest: Map<string, import('./artifact-projection.js').ArtifactEntry>,
970
+ * statuses: Map<string, number>,
971
+ * served: Awaited<ReturnType<typeof readServedGeneration>> | null,
972
+ * markerPass: number,
973
+ * pass: number,
974
+ * cursor: number,
975
+ * confirmed: boolean,
976
+ * errorCode: string | null,
977
+ * errorStreak: number
978
+ * }} ObserveProgress
979
+ */
980
+
981
+ /**
982
+ * Stale routes re-read per pass after the first. A pass reads at most this
983
+ * many plus the marker until the sample matches; the request count is about
984
+ * passes x (K + 1) + 2 x routes, with no cap that can fire inside a CDN
985
+ * lifetime.
986
+ */
987
+ const OBSERVE_SAMPLE_ROUTES = 20;
988
+ /** Largest site whose early matches are confirmed again before success. */
989
+ const OBSERVE_CONFIRM_MAXIMUM_ROUTES = 50;
990
+ /** Consecutive passes failing with one transient code before giving up. */
991
+ const OBSERVE_TRANSIENT_STREAK = 3;
992
+ /** Most unmatched routes named individually in the findings. */
993
+ const OBSERVE_FINDINGS_NAMED = 10;
994
+
995
+ const TRANSIENT_CODES = new Set([
996
+ 'ECONNRESET',
997
+ 'ETIMEDOUT',
998
+ 'ECONNREFUSED',
999
+ 'EPIPE',
1000
+ 'EAI_AGAIN',
1001
+ 'UND_ERR_SOCKET',
1002
+ 'UND_ERR_CONNECT_TIMEOUT',
1003
+ 'UND_ERR_HEADERS_TIMEOUT',
1004
+ 'UND_ERR_BODY_TIMEOUT',
1005
+ ]);
1006
+
1007
+ /**
1008
+ * @param {string} code a network error code
1009
+ * @returns {boolean} whether it is a certificate, TLS or name-resolution
1010
+ * failure that waiting cannot cure
1011
+ */
1012
+ function isFatalCode(code) {
1013
+ return (
1014
+ code === 'ENOTFOUND' ||
1015
+ code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' ||
1016
+ code === 'DEPTH_ZERO_SELF_SIGNED_CERT' ||
1017
+ code.startsWith('CERT_') ||
1018
+ code.startsWith('ERR_TLS_') ||
1019
+ code.startsWith('ERR_SSL_')
1020
+ );
1021
+ }
1022
+
1023
+ /**
1024
+ * Every error code carried by a thrown fetch failure, its cause and the
1025
+ * causes' aggregated errors.
1026
+ *
1027
+ * @param {unknown} error the thrown value
1028
+ * @returns {string[]} the codes found
1029
+ */
1030
+ function errorCodes(error) {
1031
+ /** @type {string[]} */
1032
+ const codes = [];
1033
+ /** @type {unknown[]} */
1034
+ const queue = [error];
1035
+ for (let depth = 0; queue.length > 0 && depth < 16; depth += 1) {
1036
+ const current = /** @type {any} */ (queue.shift());
1037
+ if (current === null || typeof current !== 'object') {
1038
+ continue;
1039
+ }
1040
+ if (typeof current.code === 'string') {
1041
+ codes.push(current.code);
1042
+ }
1043
+ queue.push(current.cause);
1044
+ if (Array.isArray(current.errors)) {
1045
+ queue.push(...current.errors);
1046
+ }
1047
+ }
1048
+ return codes;
1049
+ }
1050
+
1051
+ /**
1052
+ * Classify a failed public read. Only transient transport failures are
1053
+ * waited out; typed adapter errors, name-resolution, certificate and TLS
1054
+ * failures and programming errors fail fast.
1055
+ *
1056
+ * @param {unknown} error the thrown value
1057
+ * @returns {string | null} the transient code, or null when it must throw
1058
+ */
1059
+ function transientCode(error) {
1060
+ if (error instanceof PagesAdapterError) {
1061
+ return null;
1062
+ }
1063
+ const codes = errorCodes(error);
1064
+ if (codes.some(isFatalCode)) {
1065
+ return null;
1066
+ }
1067
+ const code = codes.find((candidate) => TRANSIENT_CODES.has(candidate));
1068
+ if (code !== undefined) {
1069
+ return code;
1070
+ }
1071
+ if (error instanceof Error && error.name === 'TimeoutError') {
1072
+ return 'TimeoutError';
1073
+ }
1074
+ return null;
1075
+ }
1076
+
1077
+ /**
1078
+ * @param {unknown} error the thrown value
1079
+ * @returns {string} a short, single-line description
1080
+ */
1081
+ function describeReadError(error) {
1082
+ const text = error instanceof Error ? error.message : String(error);
1083
+ return text.replaceAll(/\s+/gu, ' ').slice(0, 200);
1084
+ }
1085
+
1086
+ /**
1087
+ * One observation pass. `retryable` is false for hard failures (a redirect,
1088
+ * a generation this run never staged, a repeating transport failure), which
1089
+ * no waiting can change. The first pass reads the marker and every route.
1090
+ * Later passes read the marker until it matches and a rotating sample of the
1091
+ * still-unmatched routes; once the sample and the marker match, the rest of
1092
+ * the unmatched routes are read in the same pass. Before success a small
1093
+ * site re-reads what matched in earlier passes. The digest is computed over
1094
+ * the whole coherent set.
1095
+ *
1096
+ * @param {Parameters<typeof observe>[0]} input the observe input
1097
+ * @param {ObserveProgress} progress what earlier passes learned
1098
+ * @returns {Promise<Awaited<ReturnType<typeof observe>> & {retryable: boolean, maxAgeSeconds: number | null}>}
1099
+ * the observation and its retry hints
1100
+ */
1101
+ async function observeOnce(input, progress) {
798
1102
  const state = stateFor(input.destination);
799
- const served = await readServedGeneration(input.destination);
1103
+ const staged =
1104
+ state.activations.get(input.generationId) ??
1105
+ [...state.stages.values()].find(
1106
+ (candidate) => candidate.generationId === input.generationId,
1107
+ );
1108
+ const entryPaths = staged?.entryPaths;
1109
+ const pass = progress.pass;
1110
+ progress.pass += 1;
1111
+ /** @type {{text: string, code: string}[]} */
1112
+ const readErrors = [];
1113
+ /** @type {number | null} */
1114
+ let seenMaxAge = null;
1115
+ /** @type {PublicRedirectFailure | undefined} */
1116
+ let failure;
1117
+
1118
+ const markerMatches = () =>
1119
+ progress.served !== null &&
1120
+ progress.served.generationId === input.generationId &&
1121
+ progress.served.artifactDigest === input.expectedArtifactDigest;
1122
+
1123
+ const readMarker = async () => {
1124
+ try {
1125
+ progress.served = await readServedGeneration(input.destination);
1126
+ progress.markerPass = pass;
1127
+ } catch (error) {
1128
+ const code = transientCode(error);
1129
+ if (code === null) {
1130
+ throw error;
1131
+ }
1132
+ readErrors.push({
1133
+ text: `${GENERATION_MARKER_PATH}: ${describeReadError(error)}`,
1134
+ code,
1135
+ });
1136
+ progress.served ??= {
1137
+ generationId: null,
1138
+ artifactDigest: null,
1139
+ findings: [],
1140
+ };
1141
+ }
1142
+ if (progress.served.failure !== undefined) {
1143
+ failure = progress.served.failure;
1144
+ }
1145
+ const age = maxAgeSeconds(progress.served.cacheControl);
1146
+ if (age !== null && age > (seenMaxAge ?? -1)) {
1147
+ seenMaxAge = age;
1148
+ }
1149
+ };
800
1150
 
1151
+ if (!markerMatches()) {
1152
+ await readMarker();
1153
+ }
1154
+
1155
+ /** @type {string | undefined} */
1156
+ let redirectedRoute;
1157
+ if (failure === undefined && entryPaths !== undefined) {
1158
+ const publicContext = publicContextFor(input.destination);
1159
+ const expectedByPath = new Map(
1160
+ (staged?.entries ?? []).map((entry) => [entry.path, entry]),
1161
+ );
1162
+ /**
1163
+ * @param {string} entryPath the route
1164
+ * @returns {Promise<boolean>} false when the origin redirects
1165
+ */
1166
+ const readRoute = async (entryPath) => {
1167
+ /** @type {Awaited<ReturnType<typeof readPublic>>} */
1168
+ let read;
1169
+ try {
1170
+ read = await readPublic(publicContext, entryPath);
1171
+ } catch (error) {
1172
+ const code = transientCode(error);
1173
+ if (code === null) {
1174
+ throw error;
1175
+ }
1176
+ readErrors.push({
1177
+ text: `${entryPath}: ${describeReadError(error)}`,
1178
+ code,
1179
+ });
1180
+ return true;
1181
+ }
1182
+ const age = maxAgeSeconds(read.cacheControl);
1183
+ if (age !== null && age > (seenMaxAge ?? -1)) {
1184
+ seenMaxAge = age;
1185
+ }
1186
+ if (read.status === 'redirect') {
1187
+ failure = publicRedirectFailure(read);
1188
+ redirectedRoute = entryPath;
1189
+ return false;
1190
+ }
1191
+ if (read.status !== 200 || read.bytes === null) {
1192
+ progress.latest.delete(entryPath);
1193
+ progress.matched.delete(entryPath);
1194
+ progress.statuses.set(entryPath, read.status);
1195
+ return true;
1196
+ }
1197
+ progress.statuses.delete(entryPath);
1198
+ const entry = projectEntry(entryPath, read.bytes);
1199
+ const expected = expectedByPath.get(entryPath);
1200
+ if (
1201
+ expected !== undefined &&
1202
+ expected.sha256 === entry.sha256 &&
1203
+ expected.byteLength === entry.byteLength
1204
+ ) {
1205
+ progress.matched.set(entryPath, entry);
1206
+ progress.matchedPass.set(entryPath, pass);
1207
+ progress.latest.delete(entryPath);
1208
+ } else {
1209
+ progress.matched.delete(entryPath);
1210
+ progress.latest.set(entryPath, entry);
1211
+ }
1212
+ return true;
1213
+ };
1214
+
1215
+ const unmatched = entryPaths.filter(
1216
+ (entryPath) => !progress.matched.has(entryPath),
1217
+ );
1218
+ /** @type {string[]} */
1219
+ let sample = unmatched;
1220
+ if (pass > 0 && unmatched.length > OBSERVE_SAMPLE_ROUTES) {
1221
+ const start = progress.cursor % unmatched.length;
1222
+ sample = [];
1223
+ for (let offset = 0; offset < OBSERVE_SAMPLE_ROUTES; offset += 1) {
1224
+ sample.push(
1225
+ /** @type {string} */ (
1226
+ unmatched[(start + offset) % unmatched.length]
1227
+ ),
1228
+ );
1229
+ }
1230
+ progress.cursor += OBSERVE_SAMPLE_ROUTES;
1231
+ }
1232
+ let redirected = false;
1233
+ for (const entryPath of sample) {
1234
+ if (!(await readRoute(entryPath))) {
1235
+ redirected = true;
1236
+ break;
1237
+ }
1238
+ }
1239
+ if (
1240
+ !redirected &&
1241
+ sample.length < unmatched.length &&
1242
+ markerMatches() &&
1243
+ sample.every((entryPath) => progress.matched.has(entryPath))
1244
+ ) {
1245
+ const sampled = new Set(sample);
1246
+ for (const entryPath of unmatched) {
1247
+ if (!sampled.has(entryPath) && !(await readRoute(entryPath))) {
1248
+ redirected = true;
1249
+ break;
1250
+ }
1251
+ }
1252
+ }
1253
+ if (
1254
+ !redirected &&
1255
+ !progress.confirmed &&
1256
+ pass > 0 &&
1257
+ entryPaths.length <= OBSERVE_CONFIRM_MAXIMUM_ROUTES &&
1258
+ readErrors.length === 0 &&
1259
+ markerMatches() &&
1260
+ entryPaths.every((entryPath) => progress.matched.has(entryPath))
1261
+ ) {
1262
+ // About to succeed: re-read what matched only in earlier passes.
1263
+ progress.confirmed = true;
1264
+ if (progress.markerPass < pass) {
1265
+ await readMarker();
1266
+ }
1267
+ for (const entryPath of entryPaths) {
1268
+ if (
1269
+ (progress.matchedPass.get(entryPath) ?? pass) < pass &&
1270
+ !(await readRoute(entryPath))
1271
+ ) {
1272
+ break;
1273
+ }
1274
+ }
1275
+ }
1276
+ }
1277
+
1278
+ const served = /** @type {NonNullable<typeof progress.served>} */ (
1279
+ progress.served
1280
+ );
801
1281
  /** @type {string[]} */
802
1282
  const findings = [...served.findings];
803
1283
  if (served.generationId !== input.generationId) {
@@ -805,43 +1285,82 @@ export async function observe(input) {
805
1285
  `the public marker names generation ${JSON.stringify(served.generationId)}, not the observed generation ${JSON.stringify(input.generationId)}`,
806
1286
  );
807
1287
  }
808
- const markerValid =
809
- served.generationId === input.generationId &&
810
- served.artifactDigest === input.expectedArtifactDigest;
1288
+ const markerValid = markerMatches();
811
1289
  if (!markerValid) {
812
1290
  findings.push(
813
1291
  'the public generation marker is missing, invalid or disagrees with the expected identity',
814
1292
  );
815
1293
  }
816
1294
 
817
- const activation = state.activations.get(input.generationId);
818
- const entryPaths =
819
- activation?.entryPaths ??
820
- [...state.stages.values()].find(
821
- (candidate) => candidate.generationId === input.generationId,
822
- )?.entryPaths;
1295
+ let retryable = true;
823
1296
  /** @type {string | null} */
824
1297
  let observedArtifactDigest = null;
825
- if (entryPaths === undefined) {
1298
+ if (failure !== undefined) {
1299
+ // The origin redirects, so every route would redirect too: say so once
1300
+ // instead of asking for each of them.
1301
+ retryable = false;
1302
+ if (redirectedRoute !== undefined) {
1303
+ findings.push(`${redirectedRoute}: ${publicRedirectFinding(failure)}`);
1304
+ }
1305
+ } else if (entryPaths === undefined) {
1306
+ retryable = false;
826
1307
  findings.push(
827
1308
  'this run did not stage the observed generation, so its route inventory cannot be verified here',
828
1309
  );
829
1310
  } else {
830
- const publicContext = publicContextFor(input.destination);
831
- /** @type {import('./artifact-projection.js').ArtifactEntry[]} */
832
- const entries = [];
833
- for (const entryPath of entryPaths) {
834
- const read = await readPublic(publicContext, entryPath);
835
- if (read.status !== 200 || read.bytes === null) {
836
- findings.push(`${entryPath}: public read returned HTTP ${read.status}`);
837
- continue;
1311
+ const unmatchedNow = entryPaths.filter(
1312
+ (entryPath) => !progress.matched.has(entryPath),
1313
+ );
1314
+ for (const entryPath of unmatchedNow.slice(0, OBSERVE_FINDINGS_NAMED)) {
1315
+ const status = progress.statuses.get(entryPath);
1316
+ if (status !== undefined) {
1317
+ findings.push(`${entryPath}: public read returned HTTP ${status}`);
1318
+ } else if (progress.latest.has(entryPath)) {
1319
+ findings.push(`${entryPath}: bytes do not yet match the staged entry`);
1320
+ } else if (
1321
+ !readErrors.some((error) => error.text.startsWith(`${entryPath}: `))
1322
+ ) {
1323
+ findings.push(`${entryPath}: not yet read`);
838
1324
  }
839
- entries.push(projectEntry(entryPath, read.bytes));
840
1325
  }
841
- observedArtifactDigest = digestEntries(entries);
842
- if (observedArtifactDigest !== input.expectedArtifactDigest) {
1326
+ if (unmatchedNow.length > OBSERVE_FINDINGS_NAMED) {
1327
+ findings.push(
1328
+ `${unmatchedNow.length - OBSERVE_FINDINGS_NAMED} more routes do not yet match the staged entries`,
1329
+ );
1330
+ }
1331
+ for (const readError of readErrors) {
1332
+ findings.push(`public read failed: ${readError.text}`);
1333
+ }
1334
+ const coherent = [
1335
+ ...progress.matched.values(),
1336
+ ...progress.latest.values(),
1337
+ ];
1338
+ if (coherent.length === entryPaths.length) {
1339
+ observedArtifactDigest = digestEntries(coherent);
1340
+ if (observedArtifactDigest !== input.expectedArtifactDigest) {
1341
+ findings.push(
1342
+ `the publicly observed artifact digest ${observedArtifactDigest} disagrees with the expected ${input.expectedArtifactDigest}`,
1343
+ );
1344
+ }
1345
+ }
1346
+ if (unmatchedNow.length === 0 && markerValid) {
1347
+ // Every route matches its staged entry and the marker matches, yet
1348
+ // the digest disagrees: no further reading can change that.
1349
+ retryable = false;
1350
+ }
1351
+ const code = readErrors[0]?.code ?? null;
1352
+ if (code === null) {
1353
+ progress.errorStreak = 0;
1354
+ } else if (code === progress.errorCode) {
1355
+ progress.errorStreak += 1;
1356
+ } else {
1357
+ progress.errorStreak = 1;
1358
+ }
1359
+ progress.errorCode = code;
1360
+ if (progress.errorStreak >= OBSERVE_TRANSIENT_STREAK) {
1361
+ retryable = false;
843
1362
  findings.push(
844
- `the publicly observed artifact digest ${observedArtifactDigest} disagrees with the expected ${input.expectedArtifactDigest}`,
1363
+ `the public read failed with ${code} on ${progress.errorStreak} consecutive passes; giving up`,
845
1364
  );
846
1365
  }
847
1366
  }
@@ -853,6 +1372,9 @@ export async function observe(input) {
853
1372
  markerValid,
854
1373
  claimsCompleteInventory: /** @type {false} */ (false),
855
1374
  findings: Object.freeze(findings),
1375
+ ...(failure === undefined ? {} : { failure }),
1376
+ retryable,
1377
+ maxAgeSeconds: seenMaxAge,
856
1378
  });
857
1379
  }
858
1380
 
@@ -6,6 +6,13 @@
6
6
  * profile declares zero credentials on the public origin), follow no
7
7
  * redirect, and read a bounded body.
8
8
  *
9
+ * A redirect is an answer, not a crash: the public base URL a site carries
10
+ * can name a host the site has since moved away from (a custom domain on the
11
+ * Pages site, a base URL still on `github.io`), and the origin then answers
12
+ * 301/302/307/308. The read classifies that as `status: 'redirect'` with the
13
+ * target host, so the adapter can refuse with `PAGES_PUBLIC_REDIRECT` instead
14
+ * of throwing out of the lifecycle.
15
+ *
9
16
  * @module
10
17
  */
11
18
 
@@ -34,23 +41,111 @@ export function publicUrlFor(publicBaseUrl, artifactRelativePath) {
34
41
  return `${base}/${artifactRelativePath}`;
35
42
  }
36
43
 
44
+ /**
45
+ * The `max-age` a `Cache-Control` header declares, in seconds.
46
+ *
47
+ * @param {string | null | undefined} cacheControl the header value
48
+ * @returns {number | null} the lifetime, `null` when none is declared
49
+ */
50
+ export function maxAgeSeconds(cacheControl) {
51
+ const match = /(?:^|[\s,])max-age=(\d+)/iu.exec(cacheControl ?? '');
52
+ return match === null ? null : Number(match[1]);
53
+ }
54
+
55
+ /** How long the redirect-target probe may take before the target is unknown. */
56
+ const REDIRECT_PROBE_TIMEOUT_MS = 10_000;
57
+
58
+ /**
59
+ * Whether a failed fetch failed because the origin answered with a redirect
60
+ * the fetch was told not to follow (`redirect: 'error'`). Undici reports it
61
+ * as a `TypeError('fetch failed')` whose `cause` is an `Error` with the exact
62
+ * message `unexpected redirect` (it carries no `code`); no other failure
63
+ * matches.
64
+ *
65
+ * @param {unknown} error the thrown value
66
+ * @returns {boolean} whether it is the refused-redirect failure
67
+ */
68
+ function isRefusedRedirect(error) {
69
+ return (
70
+ error instanceof TypeError &&
71
+ /** @type {{message?: unknown} | undefined} */ (error.cause)?.message ===
72
+ 'unexpected redirect'
73
+ );
74
+ }
75
+
76
+ /**
77
+ * Learn where a refused redirect pointed. A fetch that refused to follow
78
+ * exposes no `Location`, so the same credential-free URL is asked once more
79
+ * with `redirect: 'manual'`, which hands back the 3xx response itself and
80
+ * still follows nothing. The probe is bounded to ten seconds and its body is
81
+ * cancelled unread. Any failure here, and any `Location` that is not an
82
+ * absolute-or-relative http(s) URL, leaves the target unknown; it never hides
83
+ * the redirect.
84
+ *
85
+ * @param {typeof globalThis.fetch} doFetch the fetch implementation
86
+ * @param {string} url the requested public URL
87
+ * @returns {Promise<{toHost: string | null, location: string | null}>} the
88
+ * redirect target, `null` where it could not be read
89
+ */
90
+ async function redirectTarget(doFetch, url) {
91
+ const unknown = { toHost: null, location: null };
92
+ try {
93
+ const response = await doFetch(url, {
94
+ method: 'GET',
95
+ redirect: 'manual',
96
+ cache: 'no-store',
97
+ signal: AbortSignal.timeout(REDIRECT_PROBE_TIMEOUT_MS),
98
+ });
99
+ await response.body?.cancel().catch(() => undefined);
100
+ const header = response.headers.get('location');
101
+ if (header === null) {
102
+ return unknown;
103
+ }
104
+ const target = new URL(header, url);
105
+ if (target.protocol !== 'https:' && target.protocol !== 'http:') {
106
+ return unknown;
107
+ }
108
+ return { toHost: target.host, location: target.href };
109
+ } catch {
110
+ return unknown;
111
+ }
112
+ }
113
+
37
114
  /**
38
115
  * Read one public route.
39
116
  *
40
117
  * @param {PublicContext} context the public-origin context
41
118
  * @param {string} artifactRelativePath the artifact-relative POSIX path
42
- * @returns {Promise<{status: number, bytes: Buffer | null, etag: string | null}>}
43
- * the bounded observation; `bytes` is `null` for any non-`200` status
119
+ * @returns {Promise<{status: number | 'redirect', bytes: Buffer | null, etag: string | null, cacheControl?: string | null | undefined, toHost?: string | null, location?: string | null}>}
120
+ * the bounded observation; `bytes` is `null` for any non-`200` status. A
121
+ * `'redirect'` status carries the `toHost` and absolute `location` the
122
+ * origin named (`null` when it named none that could be read).
44
123
  */
45
124
  export async function readPublic(context, artifactRelativePath) {
46
125
  const doFetch = context.fetch ?? globalThis.fetch;
47
- const response = await doFetch(
48
- publicUrlFor(context.publicBaseUrl, artifactRelativePath),
49
- { method: 'GET', redirect: 'error', cache: 'no-store' },
50
- );
126
+ const url = publicUrlFor(context.publicBaseUrl, artifactRelativePath);
127
+ let response;
128
+ try {
129
+ response = await doFetch(url, {
130
+ method: 'GET',
131
+ redirect: 'error',
132
+ cache: 'no-store',
133
+ });
134
+ } catch (error) {
135
+ if (!isRefusedRedirect(error)) {
136
+ throw error;
137
+ }
138
+ return {
139
+ status: 'redirect',
140
+ bytes: null,
141
+ etag: null,
142
+ ...(await redirectTarget(doFetch, url)),
143
+ };
144
+ }
51
145
  const etag = response.headers.get('etag');
146
+ const cacheControl = response.headers.get('cache-control');
52
147
  if (response.status !== 200) {
53
- return { status: response.status, bytes: null, etag };
148
+ return { status: response.status, bytes: null, etag, cacheControl };
54
149
  }
55
150
  const bytes = Buffer.from(await response.arrayBuffer());
56
151
  if (bytes.byteLength > MAXIMUM_PUBLIC_BODY_BYTES) {
@@ -59,5 +154,5 @@ export async function readPublic(context, artifactRelativePath) {
59
154
  `${artifactRelativePath} returned ${bytes.byteLength} bytes`,
60
155
  );
61
156
  }
62
- return { status: 200, bytes, etag };
157
+ return { status: 200, bytes, etag, cacheControl };
63
158
  }
package/src/store.js CHANGED
@@ -26,6 +26,7 @@ import { DOMAIN_PAGES_DESTINATION } from './constants.js';
26
26
  * artifactId: string,
27
27
  * artifactDigest: string,
28
28
  * entryPaths: readonly string[],
29
+ * entries: readonly import('./artifact-projection.js').ArtifactEntry[],
29
30
  * carrierBytes: Buffer,
30
31
  * carrierDigest: string,
31
32
  * pagesArtifactId: string,
@@ -37,7 +38,7 @@ import { DOMAIN_PAGES_DESTINATION } from './constants.js';
37
38
  /**
38
39
  * @typedef {{
39
40
  * stages: Map<string, StageRecord>,
40
- * activations: Map<string, {generationId: string, pagesDeploymentId: string, certifiedAt: string, entryPaths: readonly string[]}>,
41
+ * activations: Map<string, {generationId: string, pagesDeploymentId: string, certifiedAt: string, entryPaths: readonly string[], entries: readonly import('./artifact-projection.js').ArtifactEntry[]}>,
41
42
  * inFlight: Map<string, string>
42
43
  * }} DestinationState
43
44
  */
package/types/index.d.ts CHANGED
@@ -15,7 +15,8 @@ export function describeCapabilities(destination: PagesDestination): Promise<Rea
15
15
  * retainedHistory: readonly Readonly<Record<string, unknown>>[],
16
16
  * releaseGenerationsOnDisk: readonly string[],
17
17
  * providerSiteObserved: boolean,
18
- * findings: readonly string[]
18
+ * findings: readonly string[],
19
+ * failure?: PublicRedirectFailure
19
20
  * }>>} the inspection result
20
21
  */
21
22
  export function inspectDestination(destination: PagesDestination): Promise<Readonly<{
@@ -24,6 +25,7 @@ export function inspectDestination(destination: PagesDestination): Promise<Reado
24
25
  releaseGenerationsOnDisk: readonly string[];
25
26
  providerSiteObserved: boolean;
26
27
  findings: readonly string[];
28
+ failure?: PublicRedirectFailure;
27
29
  }>>;
28
30
  /**
29
31
  * `preflight`: check every declared route against the portable path rules
@@ -175,7 +177,8 @@ export function activate(input: {
175
177
  * currentGenerationId: string | null,
176
178
  * markerValid: boolean,
177
179
  * claimsCompleteInventory: false,
178
- * findings: readonly string[]
180
+ * findings: readonly string[],
181
+ * failure?: PublicRedirectFailure
179
182
  * }>>} the observation result
180
183
  */
181
184
  export function observe(input: {
@@ -189,6 +192,7 @@ export function observe(input: {
189
192
  markerValid: boolean;
190
193
  claimsCompleteInventory: false;
191
194
  findings: readonly string[];
195
+ failure?: PublicRedirectFailure;
192
196
  }>>;
193
197
  /**
194
198
  * `cleanupStaged`: drop this operation's staged carrier from run-scoped
@@ -261,6 +265,18 @@ export const PACKAGE_STATUS: Readonly<{
261
265
  implemented: true;
262
266
  implementingTask: "S4-T04";
263
267
  }>;
268
+ /**
269
+ * The classified failure the adapter reports when the public origin answers
270
+ * with a redirect instead of the route: the destination's `publicBaseUrl` no
271
+ * longer names the host that serves the site (typically a custom domain was
272
+ * attached while the repository still carries the `github.io` base). The
273
+ * adapter follows no redirect, so it cannot tell what the origin serves.
274
+ */
275
+ export type PublicRedirectFailure = Readonly<{
276
+ code: "PAGES_PUBLIC_REDIRECT";
277
+ toHost: string | null;
278
+ location: string | null;
279
+ }>;
264
280
  export type PagesDestination = Readonly<{
265
281
  owner: string;
266
282
  repository: string;
@@ -270,6 +286,7 @@ export type PagesDestination = Readonly<{
270
286
  oidcToken?: string;
271
287
  oidcClaims?: import("./oidc.js").PagesOidcExpectation;
272
288
  publicBaseUrl: string;
289
+ verificationBaseUrl?: string;
273
290
  token: string;
274
291
  publishCarrier: (input: {
275
292
  bytes: Buffer;
@@ -283,6 +300,7 @@ export type PagesDestination = Readonly<{
283
300
  fetch?: typeof globalThis.fetch;
284
301
  publicFetch?: typeof globalThis.fetch;
285
302
  sleep?: (seconds: number) => Promise<void>;
303
+ now?: () => number;
286
304
  runId?: string;
287
305
  runAttempt?: number;
288
306
  headSha?: string;
@@ -291,6 +309,41 @@ export type StagedFile = Readonly<{
291
309
  path: string;
292
310
  bytes: Buffer;
293
311
  }>;
312
+ /**
313
+ * What `observe` keeps between passes so a retry reads only what is still
314
+ * wrong: the routes whose bytes already match the staged entry, the latest
315
+ * bytes of the others, and the marker read until it matches.
316
+ */
317
+ export type ObserveProgress = {
318
+ matched: Map<string, import("./artifact-projection.js").ArtifactEntry>;
319
+ matchedPass: Map<string, number>;
320
+ latest: Map<string, import("./artifact-projection.js").ArtifactEntry>;
321
+ statuses: Map<string, number>;
322
+ served: Awaited<ReturnType<typeof readServedGeneration>> | null;
323
+ markerPass: number;
324
+ pass: number;
325
+ cursor: number;
326
+ confirmed: boolean;
327
+ errorCode: string | null;
328
+ errorStreak: number;
329
+ };
330
+ /**
331
+ * Read the generation identity the public origin currently serves, or
332
+ * `null` when nothing has ever been activated. A redirecting origin is
333
+ * reported as the `PAGES_PUBLIC_REDIRECT` failure with the generation
334
+ * unknown, never thrown.
335
+ *
336
+ * @param {PagesDestination} destination the bound destination
337
+ * @returns {Promise<{generationId: string | null, artifactDigest: string | null, findings: string[], cacheControl?: string | null | undefined, failure?: PublicRedirectFailure}>}
338
+ * the observed public generation
339
+ */
340
+ declare function readServedGeneration(destination: PagesDestination): Promise<{
341
+ generationId: string | null;
342
+ artifactDigest: string | null;
343
+ findings: string[];
344
+ cacheControl?: string | null | undefined;
345
+ failure?: PublicRedirectFailure;
346
+ }>;
294
347
  export { EXPECT_NOTHING_SERVED, fenceFor, generateUuidV7 } from "@rathnasgala2/adapter-protocol";
295
348
  export { decodeCarrier, encodeCarrier } from "./carrier.js";
296
349
  export { GENERATION_MARKER_PATH, ADAPTER_VERSION, NORMAL_MODE, RECOVERY_MODE } from "./constants.js";
@@ -12,18 +12,30 @@
12
12
  * @returns {string} the absolute public URL
13
13
  */
14
14
  export function publicUrlFor(publicBaseUrl: string, artifactRelativePath: string): string;
15
+ /**
16
+ * The `max-age` a `Cache-Control` header declares, in seconds.
17
+ *
18
+ * @param {string | null | undefined} cacheControl the header value
19
+ * @returns {number | null} the lifetime, `null` when none is declared
20
+ */
21
+ export function maxAgeSeconds(cacheControl: string | null | undefined): number | null;
15
22
  /**
16
23
  * Read one public route.
17
24
  *
18
25
  * @param {PublicContext} context the public-origin context
19
26
  * @param {string} artifactRelativePath the artifact-relative POSIX path
20
- * @returns {Promise<{status: number, bytes: Buffer | null, etag: string | null}>}
21
- * the bounded observation; `bytes` is `null` for any non-`200` status
27
+ * @returns {Promise<{status: number | 'redirect', bytes: Buffer | null, etag: string | null, cacheControl?: string | null | undefined, toHost?: string | null, location?: string | null}>}
28
+ * the bounded observation; `bytes` is `null` for any non-`200` status. A
29
+ * `'redirect'` status carries the `toHost` and absolute `location` the
30
+ * origin named (`null` when it named none that could be read).
22
31
  */
23
32
  export function readPublic(context: PublicContext, artifactRelativePath: string): Promise<{
24
- status: number;
33
+ status: number | "redirect";
25
34
  bytes: Buffer | null;
26
35
  etag: string | null;
36
+ cacheControl?: string | null | undefined;
37
+ toHost?: string | null;
38
+ location?: string | null;
27
39
  }>;
28
40
  /** Maximum bytes any single public read will accept. */
29
41
  export const MAXIMUM_PUBLIC_BODY_BYTES: 33554432;
package/types/store.d.ts CHANGED
@@ -48,6 +48,7 @@ export type StageRecord = Readonly<{
48
48
  artifactId: string;
49
49
  artifactDigest: string;
50
50
  entryPaths: readonly string[];
51
+ entries: readonly import("./artifact-projection.js").ArtifactEntry[];
51
52
  carrierBytes: Buffer;
52
53
  carrierDigest: string;
53
54
  pagesArtifactId: string;
@@ -61,6 +62,7 @@ export type DestinationState = {
61
62
  pagesDeploymentId: string;
62
63
  certifiedAt: string;
63
64
  entryPaths: readonly string[];
65
+ entries: readonly import("./artifact-projection.js").ArtifactEntry[];
64
66
  }>;
65
67
  inFlight: Map<string, string>;
66
68
  };