@rathnasgala2/adapter-github-pages 0.1.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.
package/src/rest.js ADDED
@@ -0,0 +1,360 @@
1
+ /**
2
+ * The raw GitHub Pages REST client. Every request line is resolved from the
3
+ * frozen nine-row request-template catalog (`request-catalog.js`) by its
4
+ * exact `(stage, callClass)` pair, never from a caller-supplied URL: a
5
+ * `status_url` parsed out of a create response is retained verbatim as
6
+ * evidence and is never followed (DEC-097 section 6.2).
7
+ *
8
+ * Three properties this module enforces rather than assumes:
9
+ *
10
+ * 1. Every request sends exactly the fixed headers its template declares —
11
+ * including the mandatory `accept-encoding: identity` and
12
+ * `connection: close` — plus exactly one `authorization` credential row.
13
+ * A request that disagrees with its template is refused before dispatch.
14
+ * 2. The `pagesDeploymentId` path segment is chosen *statically by the call
15
+ * class*: the seven ordinary/current rows take the intent's reserved
16
+ * `pagesBuildVersion` and the two `pages-recovery-prior-*` rows take
17
+ * `pagesRecovery.priorPagesBuildVersion`. No provider response and no
18
+ * workflow value can select it.
19
+ * 3. The two recovery-prior rows are forbidden in `normal` mode.
20
+ *
21
+ * The client is deliberately small and explicit: no redirect following, no
22
+ * ambient proxy or cookie state, a bounded response body, and a caller-
23
+ * injectable `fetch` so a conformance fixture can bind the exact same code
24
+ * path to a local fake provider without weakening anything (the canonical
25
+ * origin, the request line and every header are identical either way).
26
+ *
27
+ * @module
28
+ */
29
+
30
+ import { NORMAL_MODE, RECOVERY_MODE } from './constants.js';
31
+ import { callClassIdBinding, requireTemplate } from './request-catalog.js';
32
+
33
+ /** Maximum response body this client will read, in bytes. */
34
+ export const MAXIMUM_RESPONSE_BODY_BYTES = 1048576;
35
+
36
+ /** The exact shape a `pagesBuildVersion` path segment must have. */
37
+ const BUILD_VERSION_PATTERN = /^[0-9a-f]{40}$/u;
38
+
39
+ /**
40
+ * @typedef {Readonly<{
41
+ * status: number,
42
+ * headers: Readonly<Record<string, string>>,
43
+ * body: unknown,
44
+ * rawByteCount: number
45
+ * }>} ProviderResponse
46
+ */
47
+
48
+ /**
49
+ * @typedef {Readonly<{
50
+ * apiOrigin: string,
51
+ * owner: string,
52
+ * repository: string,
53
+ * token: string,
54
+ * mode?: string,
55
+ * pagesBuildVersion?: string,
56
+ * priorPagesBuildVersion?: string,
57
+ * fetch?: typeof globalThis.fetch,
58
+ * requestTemplates: readonly Readonly<Record<string, unknown>>[]
59
+ * }>} RestContext
60
+ */
61
+
62
+ /**
63
+ * Bind the per-activation identities a call class may statically select.
64
+ *
65
+ * @param {RestContext} context the bound REST context
66
+ * @param {{
67
+ * mode?: string,
68
+ * pagesBuildVersion?: string,
69
+ * priorPagesBuildVersion?: string
70
+ * }} identity the identities this attempt is authorized for
71
+ * @returns {RestContext} a new frozen context
72
+ */
73
+ export function bindIdentity(context, identity) {
74
+ return Object.freeze({
75
+ ...context,
76
+ ...(identity.mode === undefined ? {} : { mode: identity.mode }),
77
+ ...(identity.pagesBuildVersion === undefined
78
+ ? {}
79
+ : { pagesBuildVersion: identity.pagesBuildVersion }),
80
+ ...(identity.priorPagesBuildVersion === undefined
81
+ ? {}
82
+ : { priorPagesBuildVersion: identity.priorPagesBuildVersion }),
83
+ });
84
+ }
85
+
86
+ /**
87
+ * Render a catalog template's request target by substituting only the closed
88
+ * placeholder set. An unknown placeholder is a programming error, not a
89
+ * caller-controlled value.
90
+ *
91
+ * @param {string} template the `requestTargetTemplate`
92
+ * @param {Readonly<Record<string, string>>} values placeholder values
93
+ * @returns {string} the rendered request target
94
+ */
95
+ export function renderRequestTarget(template, values) {
96
+ return template.replace(/\{([A-Za-z]+)\}/gu, (_match, key) => {
97
+ const value = values[key];
98
+ if (value === undefined) {
99
+ throw new Error(
100
+ `PAGES_REQUEST_TARGET_PLACEHOLDER_UNBOUND: ${JSON.stringify(key)} has no value`,
101
+ );
102
+ }
103
+ return encodeURIComponent(value);
104
+ });
105
+ }
106
+
107
+ /**
108
+ * Resolve the `pagesDeploymentId` a row's call class statically selects.
109
+ *
110
+ * @param {RestContext} context the bound REST context
111
+ * @param {Readonly<Record<string, unknown>>} template the resolved template
112
+ * @returns {string | undefined} the selected ID, or `undefined` for a row
113
+ * whose request target has no `pagesDeploymentId` variable
114
+ */
115
+ export function selectDeploymentId(context, template) {
116
+ const source = callClassIdBinding(
117
+ String(template.stage),
118
+ String(template.callClass),
119
+ ).pagesDeploymentIdSource;
120
+ if (source === 'none') {
121
+ return undefined;
122
+ }
123
+ const value =
124
+ source === 'recovery-prior-pages-build-version'
125
+ ? context.priorPagesBuildVersion
126
+ : context.pagesBuildVersion;
127
+ const label =
128
+ source === 'recovery-prior-pages-build-version'
129
+ ? 'pagesRecovery.priorPagesBuildVersion'
130
+ : "the intent's pagesBuildVersion";
131
+ if (typeof value !== 'string' || !BUILD_VERSION_PATTERN.test(value)) {
132
+ throw new Error(
133
+ `PAGES_DEPLOYMENT_ID_SOURCE_UNAVAILABLE: ${String(template.stage)}/${String(template.callClass)} statically selects ${label}, which is absent or not 40 lowercase hex characters`,
134
+ );
135
+ }
136
+ return value;
137
+ }
138
+
139
+ /**
140
+ * Refuse a recovery-prior call outside `pages-reconciliation-recovery` mode.
141
+ *
142
+ * @param {RestContext} context the bound REST context
143
+ * @param {Readonly<Record<string, unknown>>} tmpl the resolved template
144
+ * @returns {void}
145
+ */
146
+ export function assertModePermitsCall(context, tmpl) {
147
+ const mode = context.mode ?? NORMAL_MODE;
148
+ const recoveryOnly = callClassIdBinding(
149
+ String(tmpl.stage),
150
+ String(tmpl.callClass),
151
+ ).recoveryOnly;
152
+ if (recoveryOnly && mode !== RECOVERY_MODE) {
153
+ throw new Error(
154
+ `PAGES_RECOVERY_CALL_FORBIDDEN: ${String(tmpl.stage)}/${String(tmpl.callClass)} is admitted only in ${RECOVERY_MODE} mode; ${JSON.stringify(mode)} forbids every recovery-prior call`,
155
+ );
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Build the complete raw header map one cataloged call sends.
161
+ *
162
+ * @param {RestContext} context the bound REST context
163
+ * @param {Readonly<Record<string, unknown>>} tmpl the resolved template
164
+ * @returns {Record<string, string>} the header map, lower-case names
165
+ */
166
+ export function buildHeaders(context, tmpl) {
167
+ /** @type {Record<string, string>} */
168
+ const headers = {};
169
+ for (const fixed of /** @type {{name: string, value: string}[]} */ (
170
+ tmpl.fixedHeaders
171
+ )) {
172
+ headers[fixed.name] = fixed.value;
173
+ }
174
+ for (const credential of /** @type {{name: string, prefix: string}[]} */ (
175
+ tmpl.credentialHeaders
176
+ )) {
177
+ headers[credential.name] = `${credential.prefix}${context.token}`;
178
+ }
179
+ return headers;
180
+ }
181
+
182
+ /**
183
+ * Refuse a request that disagrees with the template it claims to implement.
184
+ *
185
+ * @param {Readonly<Record<string, unknown>>} tmpl the resolved template
186
+ * @param {{
187
+ * method: string,
188
+ * url: string,
189
+ * headers: Readonly<Record<string, string>>,
190
+ * body: string | undefined
191
+ * }} request the request about to be dispatched
192
+ * @returns {void}
193
+ */
194
+ export function assertRequestMatchesTemplate(tmpl, request) {
195
+ if (request.method !== tmpl.method) {
196
+ throw new Error(
197
+ `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: method ${request.method} is not the cataloged ${String(tmpl.method)}`,
198
+ );
199
+ }
200
+ if (!request.url.startsWith(`${String(tmpl.origin)}/`)) {
201
+ throw new Error(
202
+ `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: the request URL is not on the cataloged origin ${String(tmpl.origin)}`,
203
+ );
204
+ }
205
+ if (new URL(request.url).search !== '') {
206
+ throw new Error(
207
+ 'PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: canonicalQueryProfile is "none", so no query component is representable',
208
+ );
209
+ }
210
+ for (const fixed of /** @type {{name: string, value: string}[]} */ (
211
+ tmpl.fixedHeaders
212
+ )) {
213
+ if (request.headers[fixed.name] !== fixed.value) {
214
+ throw new Error(
215
+ `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: fixed header ${JSON.stringify(fixed.name)} is missing or not the cataloged value`,
216
+ );
217
+ }
218
+ }
219
+ const credentialNames = /** @type {{name: string}[]} */ (
220
+ tmpl.credentialHeaders
221
+ ).map((row) => row.name);
222
+ const fixedNames = /** @type {{name: string}[]} */ (tmpl.fixedHeaders).map(
223
+ (row) => row.name,
224
+ );
225
+ const permitted = new Set([...fixedNames, ...credentialNames]);
226
+ for (const name of Object.keys(request.headers)) {
227
+ if (!permitted.has(name)) {
228
+ throw new Error(
229
+ `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: header ${JSON.stringify(name)} is not declared by this template`,
230
+ );
231
+ }
232
+ }
233
+ const expectsBody = tmpl.requestBodyProfile !== 'empty';
234
+ if (expectsBody !== (request.body !== undefined)) {
235
+ throw new Error(
236
+ `PAGES_REQUEST_DISAGREES_WITH_TEMPLATE: requestBodyProfile is ${JSON.stringify(String(tmpl.requestBodyProfile))} but the request ${request.body === undefined ? 'has no' : 'has a'} body`,
237
+ );
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Issue one cataloged provider call.
243
+ *
244
+ * @param {RestContext} context the bound REST context
245
+ * @param {string} stage the lifecycle stage issuing the call
246
+ * @param {string} callClass the catalog `callClass` to issue
247
+ * @param {{
248
+ * bodyText?: string,
249
+ * acceptStatuses: readonly number[]
250
+ * }} options the call options; `bodyText` is already-canonical JCS text,
251
+ * because the create body's byte length is contract-visible
252
+ * @returns {Promise<ProviderResponse>} the parsed, bounded response
253
+ */
254
+ export async function callProvider(context, stage, callClass, options) {
255
+ const tmpl = requireTemplate(context.requestTemplates, stage, callClass);
256
+ assertModePermitsCall(context, tmpl);
257
+ const pagesDeploymentId = selectDeploymentId(context, tmpl);
258
+ const requestTarget = renderRequestTarget(
259
+ /** @type {string} */ (tmpl.requestTargetTemplate),
260
+ {
261
+ owner: context.owner,
262
+ repository: context.repository,
263
+ ...(pagesDeploymentId === undefined ? {} : { pagesDeploymentId }),
264
+ },
265
+ );
266
+ const maximumTargetBytes = /** @type {number} */ (
267
+ tmpl.maximumRequestTargetBytes
268
+ );
269
+ if (Buffer.byteLength(requestTarget, 'utf8') > maximumTargetBytes) {
270
+ throw new Error(
271
+ `PAGES_REQUEST_TARGET_TOO_LONG: ${requestTarget.length} characters exceed the cataloged ${maximumTargetBytes}-byte ceiling`,
272
+ );
273
+ }
274
+
275
+ const headers = buildHeaders(context, tmpl);
276
+ const url = `${context.apiOrigin}${requestTarget}`;
277
+ const method = /** @type {string} */ (tmpl.method);
278
+ assertRequestMatchesTemplate(
279
+ // A fixture binds a local origin; the template equality is checked
280
+ // against the origin this context is actually bound to.
281
+ Object.freeze({ ...tmpl, origin: context.apiOrigin }),
282
+ { method, url, headers, body: options.bodyText },
283
+ );
284
+
285
+ const doFetch = context.fetch ?? globalThis.fetch;
286
+ const response = await doFetch(url, {
287
+ method,
288
+ headers,
289
+ redirect: 'error',
290
+ ...(options.bodyText === undefined ? {} : { body: options.bodyText }),
291
+ });
292
+
293
+ const rawBody = Buffer.from(await response.arrayBuffer());
294
+ if (rawBody.byteLength > MAXIMUM_RESPONSE_BODY_BYTES) {
295
+ throw new Error(
296
+ `PAGES_RESPONSE_BODY_TOO_LARGE: ${rawBody.byteLength} bytes exceed the ${MAXIMUM_RESPONSE_BODY_BYTES}-byte ceiling`,
297
+ );
298
+ }
299
+ if (!options.acceptStatuses.includes(response.status)) {
300
+ throw new Error(
301
+ `PAGES_PROVIDER_STATUS_UNEXPECTED: ${stage}/${callClass} returned HTTP ${response.status}, expected one of ${options.acceptStatuses.join(', ')}`,
302
+ );
303
+ }
304
+
305
+ /** @type {Record<string, string>} */
306
+ const responseHeaders = {};
307
+ response.headers.forEach((value, name) => {
308
+ responseHeaders[name.toLowerCase()] = value;
309
+ });
310
+
311
+ return Object.freeze({
312
+ status: response.status,
313
+ headers: Object.freeze(responseHeaders),
314
+ body:
315
+ rawBody.byteLength === 0 ? null : JSON.parse(rawBody.toString('utf8')),
316
+ rawByteCount: rawBody.byteLength,
317
+ });
318
+ }
319
+
320
+ /**
321
+ * Independently construct the suffix-free poll URL for a deployment, rather
322
+ * than reusing a provider-supplied `status_url` (DEC-097 section 6.2: "The
323
+ * actual polling GET is the distinct suffix-free ... target constructed
324
+ * independently from the pre-authorized ID. Equality between those two URLs
325
+ * is forbidden.").
326
+ *
327
+ * @param {RestContext} context the bound REST context
328
+ * @param {string} pagesDeploymentId the deployment identity
329
+ * @param {string} [stage] the stage whose status row is used
330
+ * @returns {string} the canonical poll URL
331
+ */
332
+ export function buildPollUrl(context, pagesDeploymentId, stage = 'activate') {
333
+ const tmpl = requireTemplate(
334
+ context.requestTemplates,
335
+ stage,
336
+ 'pages-deployment-status',
337
+ );
338
+ return `${context.apiOrigin}${renderRequestTarget(
339
+ /** @type {string} */ (tmpl.requestTargetTemplate),
340
+ {
341
+ owner: context.owner,
342
+ repository: context.repository,
343
+ pagesDeploymentId,
344
+ },
345
+ )}`;
346
+ }
347
+
348
+ /**
349
+ * The exact `status_url` shape a create response is permitted to carry. A
350
+ * response whose `status_url` does not match is retained as evidence with
351
+ * `createResponseStatusUrl` absent rather than trusted. It is never followed
352
+ * and, by construction, never equal to {@link buildPollUrl}'s result.
353
+ *
354
+ * @param {RestContext} context the bound REST context
355
+ * @param {string} pagesDeploymentId the deployment identity
356
+ * @returns {string} the expected `status_url`
357
+ */
358
+ export function expectedStatusUrl(context, pagesDeploymentId) {
359
+ return `${buildPollUrl(context, pagesDeploymentId)}/status`;
360
+ }
package/src/store.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Per-run adapter state, keyed by the physical Pages destination.
3
+ *
4
+ * The GitHub Pages API has no list-deployments operation and no
5
+ * server-side notion of a retained generation, so an honest adapter cannot
6
+ * *discover* what it staged earlier: it can only remember, within the run
7
+ * that staged it, and re-read the public marker for what is actually served
8
+ * now. This module holds exactly that run-scoped memory. Nothing here is
9
+ * durable, nothing here is authority, and `inspectDestination`/`observe`
10
+ * always prefer a live public read over anything recorded here.
11
+ *
12
+ * @module
13
+ */
14
+
15
+ import { domainDigest } from '@rathnasgala2/adapter-protocol';
16
+
17
+ import { DOMAIN_PAGES_DESTINATION } from './constants.js';
18
+
19
+ /**
20
+ * @typedef {Readonly<{
21
+ * stageToken: string,
22
+ * operationId: string,
23
+ * attemptId: string,
24
+ * idempotencyKey: string,
25
+ * generationId: string,
26
+ * artifactId: string,
27
+ * artifactDigest: string,
28
+ * entryPaths: readonly string[],
29
+ * carrierBytes: Buffer,
30
+ * carrierDigest: string,
31
+ * pagesArtifactId: string,
32
+ * pagesArtifactDigest: string,
33
+ * carrierByteCount: number
34
+ * }>} StageRecord
35
+ */
36
+
37
+ /**
38
+ * @typedef {{
39
+ * stages: Map<string, StageRecord>,
40
+ * activations: Map<string, {generationId: string, pagesDeploymentId: string, certifiedAt: string, entryPaths: readonly string[]}>,
41
+ * inFlight: Map<string, string>
42
+ * }} DestinationState
43
+ */
44
+
45
+ /** @type {Map<string, DestinationState>} */
46
+ const STATE = new Map();
47
+
48
+ /**
49
+ * Compute the physical destination mutation key. DEC-097 section 4.3 fixes
50
+ * it as the immutable Pages repository identity: a logical alias, name or
51
+ * URL never creates a second physical fence, so the numeric repository id
52
+ * is preferred and `owner/repository` is only the fallback when the caller
53
+ * has not supplied one.
54
+ *
55
+ * @param {{owner: string, repository: string, repositoryId?: string | number}} destination
56
+ * the destination identity
57
+ * @returns {string} the destination key digest
58
+ */
59
+ export function destinationKey(destination) {
60
+ return domainDigest(DOMAIN_PAGES_DESTINATION, {
61
+ repositoryId:
62
+ destination.repositoryId === undefined
63
+ ? null
64
+ : String(destination.repositoryId),
65
+ owner: destination.owner.toLowerCase(),
66
+ repository: destination.repository.toLowerCase(),
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Get (creating on first use) the run-scoped state for one destination.
72
+ *
73
+ * @param {{owner: string, repository: string, repositoryId?: string | number}} destination
74
+ * the destination identity
75
+ * @returns {DestinationState} the mutable run-scoped state
76
+ */
77
+ export function stateFor(destination) {
78
+ const key = destinationKey(destination);
79
+ const existing = STATE.get(key);
80
+ if (existing !== undefined) {
81
+ return existing;
82
+ }
83
+ /** @type {DestinationState} */
84
+ const created = {
85
+ stages: new Map(),
86
+ activations: new Map(),
87
+ inFlight: new Map(),
88
+ };
89
+ STATE.set(key, created);
90
+ return created;
91
+ }
92
+
93
+ /**
94
+ * Discard all run-scoped state for one destination. Used by a test fixture's
95
+ * teardown so one conformance destination can never leak into the next.
96
+ *
97
+ * @param {{owner: string, repository: string, repositoryId?: string | number}} destination
98
+ * the destination identity
99
+ * @returns {void}
100
+ */
101
+ export function forgetDestination(destination) {
102
+ STATE.delete(destinationKey(destination));
103
+ }