@sigrix-io/gatehouse 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.
@@ -0,0 +1,248 @@
1
+ /* The four verbs over `fetch`, and nothing else.
2
+ *
3
+ * Holds no knowledge of any marketplace: the base URL is a constructor
4
+ * argument, so the same client serves a proxy on this origin and a runner on
5
+ * loopback. Every request it makes goes to that base and to the protocol's own
6
+ * path prefix — a test asserts exactly that, because a font, an icon CDN or a
7
+ * "check for updates" call would each be a second origin this page reaches.
8
+ *
9
+ * **`stream` is read with a body reader, never `EventSource`.** That API
10
+ * cannot POST, and it reconnects on its own — which SPEC 4.5 names as the way
11
+ * a client spends someone's money twice, since a reopened stream is a new run.
12
+ * There is deliberately no retry loop around the reader either.
13
+ *
14
+ * **A disconnect is a cancel** (SPEC 4.5), so Stop is an `AbortController` and
15
+ * not a verb: the protocol has four and will not grow a fifth.
16
+ */
17
+ (function (global) {
18
+ const root = global || (typeof window !== 'undefined' ? window : {});
19
+
20
+ const PATH_PREFIX = '/postern/v0';
21
+ const JSON_MEDIA_TYPE = 'application/json';
22
+
23
+ /* A refusal the runner stated in SPEC 2.1's envelope, carried whole so the
24
+ * caller can show `message` verbatim and add its own next move. `code` may
25
+ * be one this client has never heard of: 2.1 requires a client to treat an
26
+ * unrecognised code as a generic failure of its status class rather than
27
+ * reject the response, so nothing here validates it against a list. */
28
+ class PosternRefusal extends Error {
29
+ constructor(status, code, message, detail) {
30
+ super(message || 'The runner refused this request.');
31
+ this.name = 'PosternRefusal';
32
+ this.status = status;
33
+ this.code = code || '';
34
+ this.detail = detail === undefined ? null : detail;
35
+ }
36
+ }
37
+
38
+ /* A failure that is not a refusal: the runner was unreachable, or answered
39
+ * something that is not the envelope. Kept distinct because the two want
40
+ * different copy — one is the agent's operator to fix, the other is the
41
+ * network. */
42
+ class PosternUnreachable extends Error {
43
+ constructor(message, cause) {
44
+ super(message);
45
+ this.name = 'PosternUnreachable';
46
+ this.cause = cause || null;
47
+ }
48
+ }
49
+
50
+ function joinUrl(baseUrl, verb) {
51
+ return String(baseUrl).replace(/\/+$/, '') + PATH_PREFIX + verb;
52
+ }
53
+
54
+ async function readEnvelope(response) {
55
+ /* A non-2xx body is the envelope (SPEC 2.1) — including for paths and
56
+ * methods the runner does not implement. A body that is not JSON means
57
+ * something other than a runner is answering this URL, which is worth
58
+ * saying rather than reporting as an empty refusal. */
59
+ let payload = null;
60
+ try {
61
+ payload = await response.json();
62
+ } catch (err) {
63
+ throw new PosternUnreachable(
64
+ 'The runner answered ' + response.status + ' with something that is not JSON. ' +
65
+ 'Check that this address is a runner and not a proxy or sign-in page.',
66
+ err
67
+ );
68
+ }
69
+ const error = payload && typeof payload === 'object' ? payload.error : null;
70
+ if (!error || typeof error !== 'object') {
71
+ throw new PosternUnreachable(
72
+ 'The runner answered ' + response.status + ' without the error envelope this protocol requires.'
73
+ );
74
+ }
75
+ return new PosternRefusal(response.status, error.code, error.message, error.detail);
76
+ }
77
+
78
+ /* One SSE frame per `\n\n`, each carrying an `event:` name and a `data:`
79
+ * JSON line. Written as a stateful splitter rather than a per-chunk parse
80
+ * because a frame can arrive split across reads — the case that only shows
81
+ * up against a real network and never against a stubbed one. */
82
+ function createFrameParser() {
83
+ let buffer = '';
84
+ return function push(chunk) {
85
+ buffer += chunk;
86
+ const frames = [];
87
+ let boundary = buffer.indexOf('\n\n');
88
+ while (boundary !== -1) {
89
+ const raw = buffer.slice(0, boundary);
90
+ buffer = buffer.slice(boundary + 2);
91
+ const frame = parseFrame(raw);
92
+ if (frame) frames.push(frame);
93
+ boundary = buffer.indexOf('\n\n');
94
+ }
95
+ return frames;
96
+ };
97
+ }
98
+
99
+ function parseFrame(raw) {
100
+ let name = '';
101
+ const dataLines = [];
102
+ raw.split('\n').forEach(line => {
103
+ if (line.startsWith('event:')) name = line.slice(6).trim();
104
+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).trim());
105
+ /* A comment line (`:`) is a keep-alive. A proxy sends them to hold the
106
+ * connection open through an idle-timeout, so they are expected traffic
107
+ * rather than a malformed frame. */
108
+ });
109
+ if (!name || !dataLines.length) return null;
110
+ try {
111
+ return { name, payload: JSON.parse(dataLines.join('\n')) };
112
+ } catch (err) {
113
+ /* A frame this client cannot parse is skipped rather than thrown: the
114
+ * stream owes exactly one ending, and an unreadable frame in the middle
115
+ * is not it. */
116
+ return null;
117
+ }
118
+ }
119
+
120
+ class PosternClient {
121
+ constructor(baseUrl, options) {
122
+ if (!baseUrl) throw new Error('PosternClient needs a base URL.');
123
+ const settings = options || {};
124
+ this.baseUrl = String(baseUrl).replace(/\/+$/, '');
125
+ this._fetch = settings.fetchImpl || (root.fetch ? root.fetch.bind(root) : null);
126
+ /* Extra headers the embedder needs — a proxy's CSRF token, say. The
127
+ * client sets none of its own beyond the media type the protocol
128
+ * requires, because a header it invented would be one more thing a
129
+ * runner has to be configured to admit through its preflight. */
130
+ this._headers = settings.headers || {};
131
+ if (!this._fetch) throw new Error('PosternClient needs a fetch implementation.');
132
+ }
133
+
134
+ url(verb) {
135
+ return joinUrl(this.baseUrl, verb);
136
+ }
137
+
138
+ async _get(verb) {
139
+ let response;
140
+ try {
141
+ response = await this._fetch(this.url(verb), {
142
+ method: 'GET',
143
+ headers: Object.assign({ Accept: JSON_MEDIA_TYPE }, this._headers),
144
+ });
145
+ } catch (err) {
146
+ throw new PosternUnreachable('Could not reach the runner at ' + this.baseUrl + '.', err);
147
+ }
148
+ if (!response.ok) throw await readEnvelope(response);
149
+ return response.json();
150
+ }
151
+
152
+ describe() {
153
+ return this._get('/describe');
154
+ }
155
+
156
+ status() {
157
+ return this._get('/status');
158
+ }
159
+
160
+ _postInit(inputs, options) {
161
+ const settings = options || {};
162
+ const headers = Object.assign(
163
+ { 'Content-Type': JSON_MEDIA_TYPE, Accept: JSON_MEDIA_TYPE },
164
+ this._headers
165
+ );
166
+ /* SPEC 4.2: the same key with the same inputs is a replay; with
167
+ * different inputs it is a 409. The caller owns that decision, so the
168
+ * key is only sent when it hands one over. */
169
+ if (settings.idempotencyKey) headers['Idempotency-Key'] = settings.idempotencyKey;
170
+ return {
171
+ method: 'POST',
172
+ headers,
173
+ /* The media type above is what makes a browser preflight this request
174
+ * (SPEC 2.3). A runner refuses any other, before reading the body. */
175
+ body: JSON.stringify({ inputs: inputs || {} }),
176
+ signal: settings.signal,
177
+ };
178
+ }
179
+
180
+ async run(inputs, options) {
181
+ let response;
182
+ try {
183
+ response = await this._fetch(this.url('/run'), this._postInit(inputs, options));
184
+ } catch (err) {
185
+ if (err && err.name === 'AbortError') throw err;
186
+ throw new PosternUnreachable('Could not reach the runner at ' + this.baseUrl + '.', err);
187
+ }
188
+ if (!response.ok) throw await readEnvelope(response);
189
+ return response.json();
190
+ }
191
+
192
+ /* Yields each event to `onEvent` as it arrives. Resolves when the stream
193
+ * ends; rejects on a refusal raised before the first byte, which is the
194
+ * only point a status code is still available — past it SPEC 4.5 requires
195
+ * the failure to arrive as an `error` event instead, and this returns
196
+ * normally so the caller renders that event rather than a thrown one. */
197
+ async stream(inputs, options) {
198
+ const settings = options || {};
199
+ const onEvent = settings.onEvent || function () {};
200
+ let response;
201
+ try {
202
+ response = await this._fetch(this.url('/stream'), this._postInit(inputs, settings));
203
+ } catch (err) {
204
+ if (err && err.name === 'AbortError') throw err;
205
+ throw new PosternUnreachable('Could not reach the runner at ' + this.baseUrl + '.', err);
206
+ }
207
+ if (!response.ok) throw await readEnvelope(response);
208
+ if (!response.body || typeof response.body.getReader !== 'function') {
209
+ throw new PosternUnreachable('This browser cannot read a streamed response body.');
210
+ }
211
+
212
+ const reader = response.body.getReader();
213
+ const decoder = new TextDecoder();
214
+ const push = createFrameParser();
215
+ try {
216
+ for (;;) {
217
+ const chunk = await reader.read();
218
+ if (chunk.done) break;
219
+ push(decoder.decode(chunk.value, { stream: true })).forEach(onEvent);
220
+ }
221
+ /* Whatever the last read left mid-buffer. A conforming runner ends on
222
+ * a frame boundary, so this is ordinarily empty. */
223
+ push('\n\n').forEach(onEvent);
224
+ } finally {
225
+ /* Releasing the lock lets an abort actually close the socket, which is
226
+ * what makes Stop a cancel rather than a client that stopped looking. */
227
+ try {
228
+ reader.releaseLock();
229
+ } catch (err) {
230
+ /* Already released by the abort. */
231
+ }
232
+ }
233
+ }
234
+ }
235
+
236
+ root.Gatehouse = Object.assign({}, root.Gatehouse, {
237
+ PATH_PREFIX,
238
+ PosternClient,
239
+ PosternRefusal,
240
+ PosternUnreachable,
241
+ });
242
+
243
+ /* `SigrixRun` is the name this package was born under, inside one host. It
244
+ * is kept pointing at the same object so that host keeps working across the
245
+ * extraction, and because a global is the one part of a browser package a
246
+ * consumer cannot alias for itself. Deprecated; removed at 1.0. */
247
+ root.SigrixRun = root.Gatehouse;
248
+ })(typeof window !== 'undefined' ? window : globalThis);
@@ -0,0 +1,143 @@
1
+ /* What to add to a refusal the runner already worded.
2
+ *
3
+ * `error.message` is shown verbatim in every case — SPEC 2.1 says it SHOULD be
4
+ * safe to show a user, and rewriting it here would replace what the runner
5
+ * knows with what this client guessed. What this adds is only the next move,
6
+ * which is the part a message written by a runner cannot supply: it does not
7
+ * know what the page is offering.
8
+ *
9
+ * The unknown arm is a MUST rather than a courtesy. A client that recognised
10
+ * only the codes in the table would turn every code added in a later minor
11
+ * release into a breaking change for its own users, so an unrecognised code
12
+ * degrades to its HTTP status class and still shows the message.
13
+ */
14
+ (function (global) {
15
+ const root = global || (typeof window !== 'undefined' ? window : {});
16
+
17
+ function text(value) {
18
+ return value === null || value === undefined ? '' : String(value);
19
+ }
20
+
21
+ /* `context` carries what the page knows and the refusal does not: the
22
+ * credentials `describe` declared, the level `status` reported, the state it
23
+ * was in when the request went out, and the run id if one had been issued. */
24
+ function guidance(refusal, context) {
25
+ const ctx = context || {};
26
+ const status = refusal && typeof refusal.status === 'number' ? refusal.status : 0;
27
+ const code = text(refusal && refusal.code);
28
+ const detail = refusal && refusal.detail ? refusal.detail : {};
29
+
30
+ if (code === 'bad_request') {
31
+ return {
32
+ nextMove: 'Check the highlighted field and try again.',
33
+ /* The runner names the offending key in `detail.key` where it can, so
34
+ * the form can point at it rather than making the buyer re-read a
35
+ * sentence to find out which field it meant. */
36
+ highlightKey: text(detail && detail.key),
37
+ canRetry: false,
38
+ };
39
+ }
40
+
41
+ if (code === 'missing_credential') {
42
+ const names = Array.isArray(detail && detail.missing) ? detail.missing.map(text) : [];
43
+ const declared = Array.isArray(ctx.credentials) ? ctx.credentials : [];
44
+ const rows = names.map(function (env) {
45
+ const known = declared.find(entry => entry && entry.env === env) || {};
46
+ return { env, purpose: text(known.purpose), signupUrl: text(known.signupUrl) };
47
+ });
48
+ return {
49
+ nextMove: 'Add it to the runner’s own .env file and start the runner again — it is not a field on this page.',
50
+ credentials: rows,
51
+ canRetry: false,
52
+ };
53
+ }
54
+
55
+ if (code === 'not_entitled') {
56
+ return {
57
+ /* The same sentence the entitlement banner uses, and for the same
58
+ * reason: SPEC 5.5 does not let the runner tell a refund from a
59
+ * withdrawal from a mistyped token, so neither may this. */
60
+ nextMove: 'Your access to this agent has ended or could not be confirmed. Check with the place you bought it.',
61
+ canRetry: false,
62
+ };
63
+ }
64
+
65
+ if (code === 'unavailable') {
66
+ const inFlight = text(ctx.state) === 'running' ||
67
+ (typeof ctx.maxConcurrentRuns === 'number' && ctx.maxConcurrentRuns === 1 && ctx.runInFlight === true);
68
+ return {
69
+ nextMove: inFlight
70
+ ? 'Another run is in flight on this runner. Wait for it to finish and try again.'
71
+ : 'The runner is not ready yet. Try again in a moment.',
72
+ canRetry: true,
73
+ };
74
+ }
75
+
76
+ if (code === 'run_timeout') {
77
+ const bound = detail && typeof detail.max_run_seconds === 'number' ? detail.max_run_seconds : null;
78
+ return {
79
+ nextMove:
80
+ (bound === null ? 'This run passed the runner’s limit and was stopped.' :
81
+ 'This run passed the runner’s limit of ' + bound + ' seconds and was stopped.') +
82
+ ' Try again with less to do, or use a runner started with a longer limit.',
83
+ canRetry: true,
84
+ };
85
+ }
86
+
87
+ if (code === 'not_implemented') {
88
+ const level = typeof ctx.level === 'number' ? ctx.level : null;
89
+ return {
90
+ nextMove:
91
+ (level === null ? 'This runner does not implement that verb.' :
92
+ 'This runner reports conformance level ' + level + ', which does not include that verb.') +
93
+ ' Retrying will not help.',
94
+ canRetry: false,
95
+ };
96
+ }
97
+
98
+ if (code === 'agent_error') {
99
+ const runId = text(ctx.runId);
100
+ return {
101
+ nextMove: 'The agent ran and failed.' + (runId ? ' Quote run ' + runId + ' when reporting it.' : ''),
102
+ canRetry: true,
103
+ };
104
+ }
105
+
106
+ if (code === 'unauthorized') {
107
+ /* On a hosted run the runner that refused is the platform's own proxy,
108
+ * and what failed is the buyer's sign-in. Its message says what
109
+ * to do, and "whoever deployed it" would be the platform. */
110
+ if (ctx.hosted === true) {
111
+ return { nextMove: '', canRetry: false };
112
+ }
113
+ /* Added to SPEC 2.1 alongside the runner's own inbound authentication:
114
+ * a runner bound off-machine requires a credential this page did not
115
+ * present. Said in terms of the runner rather than of any one host,
116
+ * because the scheme is the deployment's and not the protocol's. */
117
+ return {
118
+ nextMove: 'This runner requires an authorization token that was not presented. Whoever deployed it can supply one.',
119
+ canRetry: false,
120
+ };
121
+ }
122
+
123
+ /* Unrecognised: the status class, and nothing invented. Note a runner has
124
+ * no `withdrawn` and no distributor `not_found` to give (SPEC 2.1 marks
125
+ * both distributor-side), so there is deliberately no copy for them — one
126
+ * arriving here lands in this arm, which is the honest answer. */
127
+ if (status >= 500) {
128
+ return { nextMove: 'The runner reported a failure. Trying again may help.', canRetry: true };
129
+ }
130
+ if (status >= 400) {
131
+ return { nextMove: 'The runner refused this request, and nothing ran.', canRetry: false };
132
+ }
133
+ return { nextMove: '', canRetry: false };
134
+ }
135
+
136
+ root.Gatehouse = Object.assign({}, root.Gatehouse, { refusalGuidance: guidance });
137
+
138
+ /* `SigrixRun` is the name this package was born under, inside one host. It
139
+ * is kept pointing at the same object so that host keeps working across the
140
+ * extraction, and because a global is the one part of a browser package a
141
+ * consumer cannot alias for itself. Deprecated; removed at 1.0. */
142
+ root.SigrixRun = root.Gatehouse;
143
+ })(typeof window !== 'undefined' ? window : globalThis);