@gibeon/sdk 0.0.0-stage → 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/README.md +83 -2
- package/dist/index.cjs +882 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +179 -0
- package/dist/index.d.ts +179 -0
- package/dist/index.js +863 -0
- package/dist/index.js.map +1 -0
- package/package.json +53 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,863 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var GibeonAuthError = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
constructor(code, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "GibeonAuthError";
|
|
7
|
+
this.code = code;
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
var GibeonApiError = class extends Error {
|
|
11
|
+
status;
|
|
12
|
+
code;
|
|
13
|
+
requestId;
|
|
14
|
+
ids;
|
|
15
|
+
constructor(init) {
|
|
16
|
+
super(init.message);
|
|
17
|
+
this.name = "GibeonApiError";
|
|
18
|
+
this.status = init.status;
|
|
19
|
+
this.code = init.code;
|
|
20
|
+
this.requestId = init.requestId ?? null;
|
|
21
|
+
if (init.ids !== void 0) this.ids = init.ids;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// src/auth.ts
|
|
26
|
+
import { createInterface } from "readline";
|
|
27
|
+
|
|
28
|
+
// src/browser.ts
|
|
29
|
+
import { spawn } from "child_process";
|
|
30
|
+
var OPENABLE_URL = /^https:\/\/app\.gibeon\.io\/oauth\/agent\?cat=[A-Za-z0-9_-]+$/;
|
|
31
|
+
function shouldOpenBrowser(i) {
|
|
32
|
+
if (!i.stdoutIsTTY) return false;
|
|
33
|
+
if (isSet(i.env.CI)) return false;
|
|
34
|
+
if (i.platform === "darwin" || i.platform === "win32") return true;
|
|
35
|
+
if (i.platform === "linux") return isSet(i.env.DISPLAY) || isSet(i.env.WAYLAND_DISPLAY);
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
function browserCommand(platform, url) {
|
|
39
|
+
switch (platform) {
|
|
40
|
+
case "darwin":
|
|
41
|
+
return { command: "open", args: [url] };
|
|
42
|
+
case "win32":
|
|
43
|
+
return { command: "cmd", args: ["/c", "start", '""', url], windowsVerbatimArguments: true };
|
|
44
|
+
case "linux":
|
|
45
|
+
return { command: "xdg-open", args: [url] };
|
|
46
|
+
default:
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function openBrowser(url) {
|
|
51
|
+
if (!OPENABLE_URL.test(url)) return;
|
|
52
|
+
const canOpen = shouldOpenBrowser({
|
|
53
|
+
stdoutIsTTY: process.stdout.isTTY === true,
|
|
54
|
+
env: process.env,
|
|
55
|
+
platform: process.platform
|
|
56
|
+
});
|
|
57
|
+
if (!canOpen) return;
|
|
58
|
+
const cmd = browserCommand(process.platform, url);
|
|
59
|
+
if (cmd === null) return;
|
|
60
|
+
try {
|
|
61
|
+
const child = spawn(cmd.command, cmd.args, {
|
|
62
|
+
detached: true,
|
|
63
|
+
stdio: "ignore",
|
|
64
|
+
// No console window flashes up for cmd on Windows; ignored elsewhere.
|
|
65
|
+
windowsHide: true,
|
|
66
|
+
...cmd.windowsVerbatimArguments === true ? { windowsVerbatimArguments: true } : {}
|
|
67
|
+
});
|
|
68
|
+
child.on("error", () => void 0);
|
|
69
|
+
child.unref();
|
|
70
|
+
} catch {
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function isSet(value) {
|
|
74
|
+
return value !== void 0 && value !== "";
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// src/credentials.ts
|
|
78
|
+
import { randomBytes } from "crypto";
|
|
79
|
+
import {
|
|
80
|
+
chmod,
|
|
81
|
+
link,
|
|
82
|
+
lstat,
|
|
83
|
+
mkdir,
|
|
84
|
+
open,
|
|
85
|
+
readFile,
|
|
86
|
+
rename,
|
|
87
|
+
stat,
|
|
88
|
+
unlink
|
|
89
|
+
} from "fs/promises";
|
|
90
|
+
import { homedir } from "os";
|
|
91
|
+
import { dirname, join, resolve } from "path";
|
|
92
|
+
var LOCK_STALE_MS = 3e4;
|
|
93
|
+
var DEFAULT_POLL_MS = 100;
|
|
94
|
+
function credentialsPath(env = process.env) {
|
|
95
|
+
const fromEnv = env.GIBEON_CREDENTIALS_FILE;
|
|
96
|
+
if (fromEnv !== void 0 && fromEnv !== "") return fromEnv;
|
|
97
|
+
return join(homedir(), ".gibeon", "credentials.json");
|
|
98
|
+
}
|
|
99
|
+
async function readCredentials(path) {
|
|
100
|
+
try {
|
|
101
|
+
if ((await lstat(path)).isSymbolicLink()) return null;
|
|
102
|
+
} catch (err) {
|
|
103
|
+
if (errorCode(err) === "ENOENT") return null;
|
|
104
|
+
throw err;
|
|
105
|
+
}
|
|
106
|
+
let handle;
|
|
107
|
+
try {
|
|
108
|
+
handle = await open(path, "r");
|
|
109
|
+
} catch (err) {
|
|
110
|
+
if (errorCode(err) === "ENOENT") return null;
|
|
111
|
+
throw err;
|
|
112
|
+
}
|
|
113
|
+
let text;
|
|
114
|
+
try {
|
|
115
|
+
const info = await handle.stat();
|
|
116
|
+
if (info.isFile() && !isPrivate(info)) return null;
|
|
117
|
+
text = await handle.readFile("utf8");
|
|
118
|
+
} finally {
|
|
119
|
+
await handle.close();
|
|
120
|
+
}
|
|
121
|
+
let parsed;
|
|
122
|
+
try {
|
|
123
|
+
parsed = JSON.parse(text);
|
|
124
|
+
} catch {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
return toCredentials(parsed);
|
|
128
|
+
}
|
|
129
|
+
async function writeCredentials(path, creds) {
|
|
130
|
+
const dir = dirname(path);
|
|
131
|
+
await mkdir(dir, { recursive: true, mode: 448 });
|
|
132
|
+
await narrowGibeonDir(dir);
|
|
133
|
+
const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
134
|
+
const body = `${JSON.stringify(
|
|
135
|
+
{
|
|
136
|
+
version: 1,
|
|
137
|
+
client_id: creds.client_id,
|
|
138
|
+
email: creds.email,
|
|
139
|
+
access_token: creds.access_token,
|
|
140
|
+
refresh_token: creds.refresh_token,
|
|
141
|
+
expires_at: creds.expires_at
|
|
142
|
+
},
|
|
143
|
+
null,
|
|
144
|
+
2
|
|
145
|
+
)}
|
|
146
|
+
`;
|
|
147
|
+
let created = false;
|
|
148
|
+
try {
|
|
149
|
+
const handle = await open(tmp, "wx", 384);
|
|
150
|
+
created = true;
|
|
151
|
+
try {
|
|
152
|
+
await handle.chmod(384);
|
|
153
|
+
await handle.writeFile(body, "utf8");
|
|
154
|
+
} finally {
|
|
155
|
+
await handle.close();
|
|
156
|
+
}
|
|
157
|
+
await rename(tmp, path);
|
|
158
|
+
} catch (err) {
|
|
159
|
+
if (created) await unlink(tmp).catch(() => void 0);
|
|
160
|
+
throw err;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
async function narrowGibeonDir(dir) {
|
|
164
|
+
const uid = process.getuid?.();
|
|
165
|
+
if (uid === void 0) return;
|
|
166
|
+
if (resolve(dir) !== join(homedir(), ".gibeon")) return;
|
|
167
|
+
const info = await lstat(dir);
|
|
168
|
+
if (!info.isDirectory() || info.uid !== uid) return;
|
|
169
|
+
if ((info.mode & 511) !== 448) await chmod(dir, 448);
|
|
170
|
+
}
|
|
171
|
+
function isPrivate(info) {
|
|
172
|
+
const uid = process.getuid?.();
|
|
173
|
+
if (uid === void 0) return true;
|
|
174
|
+
return info.uid === uid && (info.mode & 63) === 0;
|
|
175
|
+
}
|
|
176
|
+
async function withLock(path, fn, opts) {
|
|
177
|
+
const lock = `${path}.lock`;
|
|
178
|
+
const id = randomBytes(16).toString("hex");
|
|
179
|
+
await acquire(lock, id, opts?.pollMs ?? DEFAULT_POLL_MS);
|
|
180
|
+
try {
|
|
181
|
+
return await fn();
|
|
182
|
+
} finally {
|
|
183
|
+
await release(lock, id);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
async function acquire(lock, id, pollMs) {
|
|
187
|
+
for (; ; ) {
|
|
188
|
+
let handle;
|
|
189
|
+
try {
|
|
190
|
+
handle = await open(lock, "wx");
|
|
191
|
+
} catch (err) {
|
|
192
|
+
if (errorCode(err) !== "EEXIST") throw err;
|
|
193
|
+
let seen;
|
|
194
|
+
try {
|
|
195
|
+
const { ino, mtimeMs } = await stat(lock);
|
|
196
|
+
seen = { ino, mtimeMs };
|
|
197
|
+
} catch (statErr) {
|
|
198
|
+
if (errorCode(statErr) === "ENOENT") continue;
|
|
199
|
+
throw statErr;
|
|
200
|
+
}
|
|
201
|
+
if (Date.now() - seen.mtimeMs > LOCK_STALE_MS && await takeOver(lock, id, seen)) {
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
await delay(pollMs);
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
try {
|
|
209
|
+
await handle.writeFile(id, "utf8");
|
|
210
|
+
} finally {
|
|
211
|
+
await handle.close();
|
|
212
|
+
}
|
|
213
|
+
} catch (err) {
|
|
214
|
+
await unlink(lock).catch(() => void 0);
|
|
215
|
+
throw err;
|
|
216
|
+
}
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async function takeOver(lock, id, seen) {
|
|
221
|
+
const aside = await moveAside(lock, id);
|
|
222
|
+
if (aside === null) return true;
|
|
223
|
+
const moved = await stat(aside);
|
|
224
|
+
if (moved.ino === seen.ino && moved.mtimeMs === seen.mtimeMs) {
|
|
225
|
+
await unlinkIfPresent(aside);
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
await putBack(aside, lock);
|
|
229
|
+
return false;
|
|
230
|
+
}
|
|
231
|
+
async function release(lock, id) {
|
|
232
|
+
if (await readLockId(lock) !== id) return;
|
|
233
|
+
const aside = await moveAside(lock, id);
|
|
234
|
+
if (aside === null) return;
|
|
235
|
+
if (await readFile(aside, "utf8") === id) {
|
|
236
|
+
await unlinkIfPresent(aside);
|
|
237
|
+
} else {
|
|
238
|
+
await putBack(aside, lock);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
async function moveAside(lock, id) {
|
|
242
|
+
const aside = `${lock}.${id}.stale`;
|
|
243
|
+
try {
|
|
244
|
+
await rename(lock, aside);
|
|
245
|
+
} catch (err) {
|
|
246
|
+
if (errorCode(err) === "ENOENT") return null;
|
|
247
|
+
throw err;
|
|
248
|
+
}
|
|
249
|
+
return aside;
|
|
250
|
+
}
|
|
251
|
+
async function putBack(aside, lock) {
|
|
252
|
+
try {
|
|
253
|
+
await link(aside, lock);
|
|
254
|
+
} catch (err) {
|
|
255
|
+
if (errorCode(err) !== "EEXIST") throw err;
|
|
256
|
+
} finally {
|
|
257
|
+
await unlinkIfPresent(aside);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
async function readLockId(lock) {
|
|
261
|
+
try {
|
|
262
|
+
return await readFile(lock, "utf8");
|
|
263
|
+
} catch (err) {
|
|
264
|
+
if (errorCode(err) === "ENOENT") return null;
|
|
265
|
+
throw err;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
async function unlinkIfPresent(path) {
|
|
269
|
+
try {
|
|
270
|
+
await unlink(path);
|
|
271
|
+
} catch (err) {
|
|
272
|
+
if (errorCode(err) !== "ENOENT") throw err;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
function delay(ms) {
|
|
276
|
+
return new Promise((resolve2) => {
|
|
277
|
+
setTimeout(resolve2, ms);
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
function toCredentials(value) {
|
|
281
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
282
|
+
const v = value;
|
|
283
|
+
if (v.version !== 1) return null;
|
|
284
|
+
const { client_id, email, access_token, refresh_token, expires_at } = v;
|
|
285
|
+
if (!isText(client_id) || !isText(email) || !isText(access_token) || !isText(refresh_token)) {
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
if (typeof expires_at !== "number" || !Number.isFinite(expires_at)) return null;
|
|
289
|
+
return { version: 1, client_id, email, access_token, refresh_token, expires_at };
|
|
290
|
+
}
|
|
291
|
+
function isText(value) {
|
|
292
|
+
return typeof value === "string" && value !== "";
|
|
293
|
+
}
|
|
294
|
+
function errorCode(err) {
|
|
295
|
+
return typeof err === "object" && err !== null ? err.code : void 0;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// src/auth.ts
|
|
299
|
+
var REGISTER_URL = "https://cuztuwusnyvfuictgesw.supabase.co/auth/v1/oauth/clients/register";
|
|
300
|
+
var TOKEN_URL = "https://id.gibeon.io/auth/v1/oauth/token";
|
|
301
|
+
var REDIRECT_URI = "https://www.gibeon.io/agent/callback";
|
|
302
|
+
var REFRESH_MARGIN_MS = 6e4;
|
|
303
|
+
var REQUEST_TIMEOUT_MS = 1e4;
|
|
304
|
+
var CLAIM_MAX_EXPIRES_S = 900;
|
|
305
|
+
var POLL_MIN_S = 1;
|
|
306
|
+
var POLL_MAX_S = 60;
|
|
307
|
+
var EMAIL_PROMPT = "Email address of your gibeon.io account: ";
|
|
308
|
+
var EMAIL_REQUIRED = "gibeon.io sign-in needs the email address of your account: pass new Gibeon({ email }) or set GIBEON_EMAIL.";
|
|
309
|
+
var RATE_LIMITED = "Too many sign-in attempts from this network: the limit is 20 per hour. Try again later.";
|
|
310
|
+
var CLAIM_EXPIRED = "The sign-in link expired before it was approved. Run the script again for a new link.";
|
|
311
|
+
var TOKEN_EXPIRED = "The access token from GIBEON_TOKEN or new Gibeon({ token }) was refused: it expired or was revoked. Generate a new one in the CMS (Settings, Connected apps), or leave it out to sign in.";
|
|
312
|
+
var REGISTRATION = {
|
|
313
|
+
client_name: "Gibeon SDK",
|
|
314
|
+
redirect_uris: [REDIRECT_URI],
|
|
315
|
+
token_endpoint_auth_method: "none",
|
|
316
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
317
|
+
response_types: ["code"]
|
|
318
|
+
};
|
|
319
|
+
function createTokenSource(opts, deps = {}) {
|
|
320
|
+
const baseUrl = opts.baseUrl.replace(/\/+$/, "");
|
|
321
|
+
const claimUrl = `${baseUrl}/agent/claim`;
|
|
322
|
+
const now = deps.now ?? Date.now;
|
|
323
|
+
const sleep = deps.sleep ?? delay2;
|
|
324
|
+
const stderr = deps.stderr ?? process.stderr;
|
|
325
|
+
const prompt = deps.prompt ?? promptOnTerminal;
|
|
326
|
+
const open2 = deps.openBrowser ?? openBrowser;
|
|
327
|
+
const onTerminal = () => (deps.stdinIsTTY ?? process.stdin.isTTY === true) && (deps.stdoutIsTTY ?? process.stdout.isTTY === true);
|
|
328
|
+
let inflight = null;
|
|
329
|
+
function share(run) {
|
|
330
|
+
if (inflight !== null) return inflight;
|
|
331
|
+
const pending = run().finally(() => {
|
|
332
|
+
if (inflight === pending) inflight = null;
|
|
333
|
+
});
|
|
334
|
+
inflight = pending;
|
|
335
|
+
return pending;
|
|
336
|
+
}
|
|
337
|
+
function fixedToken() {
|
|
338
|
+
if (opts.token !== void 0 && opts.token !== "") return opts.token;
|
|
339
|
+
const fromEnv = process.env.GIBEON_TOKEN;
|
|
340
|
+
return fromEnv !== void 0 && fromEnv !== "" ? fromEnv : null;
|
|
341
|
+
}
|
|
342
|
+
function namedEmail() {
|
|
343
|
+
for (const value of [opts.email, process.env.GIBEON_EMAIL]) {
|
|
344
|
+
const email = value?.trim() ?? "";
|
|
345
|
+
if (email !== "") return email;
|
|
346
|
+
}
|
|
347
|
+
return null;
|
|
348
|
+
}
|
|
349
|
+
function isFresh(c) {
|
|
350
|
+
return c.expires_at - now() >= REFRESH_MARGIN_MS;
|
|
351
|
+
}
|
|
352
|
+
async function readStored(path) {
|
|
353
|
+
const stored = await readCredentials(path);
|
|
354
|
+
if (stored === null) return null;
|
|
355
|
+
const named = namedEmail();
|
|
356
|
+
if (named !== null && named.toLowerCase() !== stored.email.trim().toLowerCase()) return null;
|
|
357
|
+
return stored;
|
|
358
|
+
}
|
|
359
|
+
async function obtain(refused) {
|
|
360
|
+
const path = credentialsPath();
|
|
361
|
+
const stored = await readStored(path);
|
|
362
|
+
if (stored === null) return signIn(path, null);
|
|
363
|
+
if (stored.access_token !== refused && isFresh(stored)) return stored.access_token;
|
|
364
|
+
return refresh(path, stored, refused ?? stored.access_token);
|
|
365
|
+
}
|
|
366
|
+
async function refresh(path, stored, replaced) {
|
|
367
|
+
const newer = (c) => c.access_token !== replaced && isFresh(c);
|
|
368
|
+
let refreshed = null;
|
|
369
|
+
try {
|
|
370
|
+
refreshed = await withLock(path, async () => {
|
|
371
|
+
const latest = await readStored(path);
|
|
372
|
+
if (latest === null) return null;
|
|
373
|
+
if (newer(latest)) return latest.access_token;
|
|
374
|
+
const tokens = await requestRefresh(latest);
|
|
375
|
+
if (tokens === null) return null;
|
|
376
|
+
await writeCredentials(path, { ...latest, ...tokens });
|
|
377
|
+
return tokens.access_token;
|
|
378
|
+
});
|
|
379
|
+
} catch (err) {
|
|
380
|
+
if (errorCode2(err) !== "ENOENT") throw err;
|
|
381
|
+
}
|
|
382
|
+
if (refreshed !== null) return refreshed;
|
|
383
|
+
const again = await readStored(path);
|
|
384
|
+
if (again !== null && newer(again)) return again.access_token;
|
|
385
|
+
return signIn(path, again ?? stored);
|
|
386
|
+
}
|
|
387
|
+
async function requestRefresh(c) {
|
|
388
|
+
const body = new URLSearchParams({
|
|
389
|
+
grant_type: "refresh_token",
|
|
390
|
+
client_id: c.client_id,
|
|
391
|
+
refresh_token: c.refresh_token
|
|
392
|
+
}).toString();
|
|
393
|
+
let res;
|
|
394
|
+
try {
|
|
395
|
+
res = await fetch(TOKEN_URL, {
|
|
396
|
+
method: "POST",
|
|
397
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
398
|
+
body,
|
|
399
|
+
// A redirect would carry the refresh token to another host.
|
|
400
|
+
redirect: "error",
|
|
401
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
402
|
+
});
|
|
403
|
+
} catch {
|
|
404
|
+
return null;
|
|
405
|
+
}
|
|
406
|
+
const answer = await readJson(res);
|
|
407
|
+
return res.ok ? toTokens(answer) : null;
|
|
408
|
+
}
|
|
409
|
+
async function signIn(path, known) {
|
|
410
|
+
const email = await resolveEmail(known);
|
|
411
|
+
const clientId = known?.client_id ?? await register();
|
|
412
|
+
const claim = await startClaim(clientId, email);
|
|
413
|
+
stderr.write(
|
|
414
|
+
"gibeon.io sign-in: open this link and enter the code to connect this script to your account.\n"
|
|
415
|
+
);
|
|
416
|
+
stderr.write(` ${claim.uri}
|
|
417
|
+
`);
|
|
418
|
+
stderr.write(` Code: ${claim.userCode}
|
|
419
|
+
`);
|
|
420
|
+
stderr.write(
|
|
421
|
+
`Waiting for approval (the link expires in ${Math.round(claim.expiresIn / 60)} minutes).
|
|
422
|
+
`
|
|
423
|
+
);
|
|
424
|
+
open2(claim.uri);
|
|
425
|
+
const tokens = await awaitApproval(claim);
|
|
426
|
+
await writeCredentials(path, { version: 1, client_id: clientId, email, ...tokens });
|
|
427
|
+
stderr.write(`Signed in. The token is stored in ${path}.
|
|
428
|
+
`);
|
|
429
|
+
return tokens.access_token;
|
|
430
|
+
}
|
|
431
|
+
async function resolveEmail(known) {
|
|
432
|
+
const named = namedEmail();
|
|
433
|
+
if (named !== null) return named;
|
|
434
|
+
if (known !== null) return known.email;
|
|
435
|
+
if (onTerminal()) {
|
|
436
|
+
const answer = (await prompt(EMAIL_PROMPT)).trim();
|
|
437
|
+
if (answer !== "") return answer;
|
|
438
|
+
}
|
|
439
|
+
throw new GibeonAuthError("email_required", EMAIL_REQUIRED);
|
|
440
|
+
}
|
|
441
|
+
async function register() {
|
|
442
|
+
const step = "client registration";
|
|
443
|
+
const res = await postJson(REGISTER_URL, REGISTRATION);
|
|
444
|
+
if (res === null) throw noAnswer(step);
|
|
445
|
+
const answer = await readJson(res);
|
|
446
|
+
if (!res.ok || !isRecord(answer) || !isText2(answer.client_id)) {
|
|
447
|
+
throw signInFailed(step, res.status);
|
|
448
|
+
}
|
|
449
|
+
return answer.client_id;
|
|
450
|
+
}
|
|
451
|
+
async function startClaim(clientId, email) {
|
|
452
|
+
const step = "claim start";
|
|
453
|
+
const res = await postJson(claimUrl, { client_id: clientId, email });
|
|
454
|
+
if (res === null) throw noAnswer(step);
|
|
455
|
+
const answer = await readJson(res);
|
|
456
|
+
if (res.status === 429) throw new GibeonAuthError("rate_limited", RATE_LIMITED);
|
|
457
|
+
const claim = res.status === 200 ? toClaim(answer) : null;
|
|
458
|
+
if (claim === null) throw signInFailed(step, res.status);
|
|
459
|
+
return claim;
|
|
460
|
+
}
|
|
461
|
+
async function awaitApproval(claim) {
|
|
462
|
+
const deadline = now() + claim.expiresIn * 1e3;
|
|
463
|
+
const intervalMs = claim.interval * 1e3;
|
|
464
|
+
for (; ; ) {
|
|
465
|
+
await sleep(intervalMs);
|
|
466
|
+
if (now() >= deadline) throw new GibeonAuthError("claim_expired", CLAIM_EXPIRED);
|
|
467
|
+
const res = await postJson(claimUrl, { claim_token: claim.token });
|
|
468
|
+
if (res === null) continue;
|
|
469
|
+
const answer = await readJson(res);
|
|
470
|
+
if (res.status === 202 || res.status >= 500) continue;
|
|
471
|
+
if (res.status === 200) {
|
|
472
|
+
const tokens = toTokens(answer);
|
|
473
|
+
if (tokens === null) throw signInFailed("approval check", res.status);
|
|
474
|
+
return tokens;
|
|
475
|
+
}
|
|
476
|
+
if (res.status === 400 && isRecord(answer) && answer.error === "expired_token") {
|
|
477
|
+
throw new GibeonAuthError("claim_expired", CLAIM_EXPIRED);
|
|
478
|
+
}
|
|
479
|
+
throw signInFailed("approval check", res.status);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
function toTokens(answer) {
|
|
483
|
+
if (!isRecord(answer)) return null;
|
|
484
|
+
const { access_token, refresh_token, expires_in } = answer;
|
|
485
|
+
if (!isText2(access_token) || !isText2(refresh_token)) return null;
|
|
486
|
+
if (typeof expires_in !== "number" || !Number.isFinite(expires_in) || expires_in < 0) return null;
|
|
487
|
+
return { access_token, refresh_token, expires_at: now() + expires_in * 1e3 };
|
|
488
|
+
}
|
|
489
|
+
return {
|
|
490
|
+
getToken() {
|
|
491
|
+
const fixed = fixedToken();
|
|
492
|
+
if (fixed !== null) return Promise.resolve(fixed);
|
|
493
|
+
return share(() => obtain(null));
|
|
494
|
+
},
|
|
495
|
+
async renew(used) {
|
|
496
|
+
if (fixedToken() !== null) throw new GibeonAuthError("token_expired", TOKEN_EXPIRED);
|
|
497
|
+
while (inflight !== null) {
|
|
498
|
+
const token = await inflight;
|
|
499
|
+
if (token !== used) return token;
|
|
500
|
+
}
|
|
501
|
+
return share(() => obtain(used));
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
async function postJson(url, body) {
|
|
506
|
+
try {
|
|
507
|
+
return await fetch(url, {
|
|
508
|
+
method: "POST",
|
|
509
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
510
|
+
body: JSON.stringify(body),
|
|
511
|
+
// A redirect would carry the email or the claim token to another host.
|
|
512
|
+
redirect: "error",
|
|
513
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
514
|
+
});
|
|
515
|
+
} catch {
|
|
516
|
+
return null;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
async function readJson(res) {
|
|
520
|
+
try {
|
|
521
|
+
return await res.json();
|
|
522
|
+
} catch {
|
|
523
|
+
return null;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
function toClaim(answer) {
|
|
527
|
+
if (!isRecord(answer) || !isText2(answer.claim_token) || !isRecord(answer.claim_attempt)) {
|
|
528
|
+
return null;
|
|
529
|
+
}
|
|
530
|
+
const { user_code, verification_uri, expires_in, interval } = answer.claim_attempt;
|
|
531
|
+
if (typeof user_code !== "string" || !/^[0-9]{6}$/.test(user_code)) return null;
|
|
532
|
+
if (!isPrintable(verification_uri)) return null;
|
|
533
|
+
if (!isPositive(expires_in) || !isPositive(interval)) return null;
|
|
534
|
+
return {
|
|
535
|
+
token: answer.claim_token,
|
|
536
|
+
userCode: user_code,
|
|
537
|
+
uri: verification_uri,
|
|
538
|
+
expiresIn: Math.min(expires_in, CLAIM_MAX_EXPIRES_S),
|
|
539
|
+
interval: Math.min(Math.max(interval, POLL_MIN_S), POLL_MAX_S)
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
function signInFailed(step, status) {
|
|
543
|
+
const detail = status >= 200 && status < 300 ? `unexpected answer, HTTP ${status}` : `HTTP ${status}`;
|
|
544
|
+
return new GibeonAuthError("sign_in_failed", `gibeon.io sign-in failed at ${step} (${detail}).`);
|
|
545
|
+
}
|
|
546
|
+
function noAnswer(step) {
|
|
547
|
+
return new GibeonAuthError(
|
|
548
|
+
"sign_in_failed",
|
|
549
|
+
`gibeon.io sign-in failed at ${step} (no answer from the server).`
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
function promptOnTerminal(question) {
|
|
553
|
+
return new Promise((resolve2) => {
|
|
554
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
555
|
+
rl.once("close", () => resolve2(""));
|
|
556
|
+
rl.once("SIGINT", () => {
|
|
557
|
+
rl.close();
|
|
558
|
+
process.kill(process.pid, "SIGINT");
|
|
559
|
+
});
|
|
560
|
+
rl.question(question, (answer) => {
|
|
561
|
+
resolve2(answer);
|
|
562
|
+
rl.close();
|
|
563
|
+
});
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
function delay2(ms) {
|
|
567
|
+
return new Promise((resolve2) => {
|
|
568
|
+
setTimeout(resolve2, ms);
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
function isRecord(value) {
|
|
572
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
573
|
+
}
|
|
574
|
+
function isText2(value) {
|
|
575
|
+
return typeof value === "string" && value !== "";
|
|
576
|
+
}
|
|
577
|
+
function isPrintable(value) {
|
|
578
|
+
return typeof value === "string" && /^[^\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]+$/.test(value);
|
|
579
|
+
}
|
|
580
|
+
function isPositive(value) {
|
|
581
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
582
|
+
}
|
|
583
|
+
function errorCode2(err) {
|
|
584
|
+
return typeof err === "object" && err !== null ? err.code : void 0;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// src/case.ts
|
|
588
|
+
function camel(key) {
|
|
589
|
+
return key.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
590
|
+
}
|
|
591
|
+
function toCamel(value) {
|
|
592
|
+
if (Array.isArray(value)) return value.map((v) => toCamel(v));
|
|
593
|
+
if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
|
|
594
|
+
const out = {};
|
|
595
|
+
for (const [k, v] of Object.entries(value)) out[camel(k)] = toCamel(v);
|
|
596
|
+
return out;
|
|
597
|
+
}
|
|
598
|
+
return value;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// src/http.ts
|
|
602
|
+
var API_TIMEOUT_MS = 6e4;
|
|
603
|
+
var UPLOAD_TIMEOUT_MS = 3e5;
|
|
604
|
+
var Http = class {
|
|
605
|
+
baseUrl;
|
|
606
|
+
tokens;
|
|
607
|
+
constructor(o) {
|
|
608
|
+
this.baseUrl = o.baseUrl.replace(/\/+$/, "");
|
|
609
|
+
this.tokens = o.tokens;
|
|
610
|
+
}
|
|
611
|
+
async json(method, path, body) {
|
|
612
|
+
const headers = { Accept: "application/json" };
|
|
613
|
+
let payload;
|
|
614
|
+
if (body !== void 0) {
|
|
615
|
+
headers["Content-Type"] = "application/json";
|
|
616
|
+
payload = JSON.stringify(body);
|
|
617
|
+
}
|
|
618
|
+
return await this.send(method, path, headers, payload, API_TIMEOUT_MS);
|
|
619
|
+
}
|
|
620
|
+
async put(path, data, contentType) {
|
|
621
|
+
await this.send(
|
|
622
|
+
"PUT",
|
|
623
|
+
path,
|
|
624
|
+
{ Accept: "application/json", "Content-Type": contentType },
|
|
625
|
+
data,
|
|
626
|
+
UPLOAD_TIMEOUT_MS
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
/** One request; a 401 renews the token once and retries once. Each try gets `timeoutMs`. */
|
|
630
|
+
async send(method, path, extra, body, timeoutMs) {
|
|
631
|
+
const used = await this.tokens.getToken();
|
|
632
|
+
let res = await this.once(method, path, used, extra, body, timeoutMs);
|
|
633
|
+
if (res.status === 401) {
|
|
634
|
+
const fresh = await this.tokens.renew(used);
|
|
635
|
+
res = await this.once(method, path, fresh, extra, body, timeoutMs);
|
|
636
|
+
}
|
|
637
|
+
if (!res.ok) throw await toApiError(res);
|
|
638
|
+
if (res.status === 204) return void 0;
|
|
639
|
+
let text;
|
|
640
|
+
try {
|
|
641
|
+
text = await res.text();
|
|
642
|
+
} catch (err) {
|
|
643
|
+
throw isTimeout(err) ? timedOut(timeoutMs) : err;
|
|
644
|
+
}
|
|
645
|
+
if (text === "") return void 0;
|
|
646
|
+
try {
|
|
647
|
+
return JSON.parse(text);
|
|
648
|
+
} catch {
|
|
649
|
+
throw new GibeonApiError({
|
|
650
|
+
status: res.status,
|
|
651
|
+
code: "invalid_json",
|
|
652
|
+
message: "The API sent an answer that is not JSON."
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
async once(method, path, token, extra, body, timeoutMs) {
|
|
657
|
+
const init = {
|
|
658
|
+
method,
|
|
659
|
+
headers: { Authorization: `Bearer ${token}`, ...extra },
|
|
660
|
+
// A redirect would carry the bearer token to another host.
|
|
661
|
+
redirect: "error",
|
|
662
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
663
|
+
};
|
|
664
|
+
if (body !== void 0) init.body = body;
|
|
665
|
+
try {
|
|
666
|
+
return await fetch(`${this.baseUrl}${path}`, init);
|
|
667
|
+
} catch (err) {
|
|
668
|
+
throw isTimeout(err) ? timedOut(timeoutMs) : err;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
function isTimeout(err) {
|
|
673
|
+
return typeof err === "object" && err !== null && err.name === "TimeoutError";
|
|
674
|
+
}
|
|
675
|
+
function timedOut(timeoutMs) {
|
|
676
|
+
return new GibeonApiError({
|
|
677
|
+
status: 0,
|
|
678
|
+
code: "timeout",
|
|
679
|
+
message: `The API did not answer within ${timeoutMs / 1e3} seconds.`
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
async function toApiError(res) {
|
|
683
|
+
const header = res.headers.get("X-Request-Id");
|
|
684
|
+
try {
|
|
685
|
+
const parsed = JSON.parse(await res.text());
|
|
686
|
+
const e = parsed.error;
|
|
687
|
+
if (e && typeof e.code === "string" && typeof e.message === "string") {
|
|
688
|
+
return new GibeonApiError({
|
|
689
|
+
status: res.status,
|
|
690
|
+
code: e.code,
|
|
691
|
+
message: e.message,
|
|
692
|
+
requestId: typeof e.request_id === "string" ? e.request_id : header
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
} catch {
|
|
696
|
+
}
|
|
697
|
+
return new GibeonApiError({
|
|
698
|
+
status: res.status,
|
|
699
|
+
code: "http_error",
|
|
700
|
+
message: `HTTP ${res.status}`,
|
|
701
|
+
requestId: header
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// src/client.ts
|
|
706
|
+
var DEFAULT_BASE_URL = "https://api.gibeon.io";
|
|
707
|
+
var BASE_URL_SCHEME = "new Gibeon({ baseUrl }) needs an https URL, or http on localhost or 127.0.0.1.";
|
|
708
|
+
var BASE_URL_STORE = "A baseUrl other than api.gibeon.io needs GIBEON_CREDENTIALS_FILE or a token, so its sign-in never replaces the tokens of api.gibeon.io: set GIBEON_CREDENTIALS_FILE to a file of its own, or pass new Gibeon({ token }) or set GIBEON_TOKEN.";
|
|
709
|
+
var enc = encodeURIComponent;
|
|
710
|
+
function checkBaseUrl(baseUrl, token) {
|
|
711
|
+
let url;
|
|
712
|
+
try {
|
|
713
|
+
url = new URL(baseUrl);
|
|
714
|
+
} catch {
|
|
715
|
+
throw new TypeError(BASE_URL_SCHEME);
|
|
716
|
+
}
|
|
717
|
+
const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
|
|
718
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
|
|
719
|
+
throw new TypeError(BASE_URL_SCHEME);
|
|
720
|
+
}
|
|
721
|
+
if (baseUrl === DEFAULT_BASE_URL) return;
|
|
722
|
+
const env = process.env;
|
|
723
|
+
if (isSet2(token) || isSet2(env.GIBEON_TOKEN) || isSet2(env.GIBEON_CREDENTIALS_FILE)) return;
|
|
724
|
+
throw new TypeError(BASE_URL_STORE);
|
|
725
|
+
}
|
|
726
|
+
function isSet2(value) {
|
|
727
|
+
return value !== void 0 && value !== "";
|
|
728
|
+
}
|
|
729
|
+
function assetTypeOf(mimeType) {
|
|
730
|
+
if (mimeType.startsWith("image/")) return "image";
|
|
731
|
+
if (mimeType === "application/pdf") return "pdf";
|
|
732
|
+
if (mimeType === "text/html") return "html";
|
|
733
|
+
throw new TypeError(
|
|
734
|
+
`assets.upload takes an image, a PDF or an HTML file, not "${mimeType}" (mimeType image/*, application/pdf or text/html)`
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
var Gibeon = class {
|
|
738
|
+
http;
|
|
739
|
+
screens;
|
|
740
|
+
playlists;
|
|
741
|
+
assets;
|
|
742
|
+
constructor(options = {}) {
|
|
743
|
+
const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
744
|
+
checkBaseUrl(baseUrl, options.token);
|
|
745
|
+
const tokens = createTokenSource({ email: options.email, token: options.token, baseUrl });
|
|
746
|
+
const http = new Http({ baseUrl, tokens });
|
|
747
|
+
this.http = http;
|
|
748
|
+
const getScreen = async (id) => {
|
|
749
|
+
if (id === "") throw new TypeError("screens.get needs a screen id");
|
|
750
|
+
return toCamel((await http.json("GET", `/v1/players/${enc(id)}`)).data);
|
|
751
|
+
};
|
|
752
|
+
const publishOne = async (id) => toCamel(
|
|
753
|
+
(await http.json("POST", `/v1/players/${enc(id)}/publish`)).data
|
|
754
|
+
);
|
|
755
|
+
const publishAll = async () => toCamel((await http.json("POST", "/v1/players/publish")).data);
|
|
756
|
+
function publish(id) {
|
|
757
|
+
return id === void 0 ? publishAll() : publishOne(id);
|
|
758
|
+
}
|
|
759
|
+
this.screens = {
|
|
760
|
+
list: async () => toCamel((await http.json("GET", "/v1/players")).data),
|
|
761
|
+
get: getScreen,
|
|
762
|
+
create: async (name, opts) => {
|
|
763
|
+
const wanted = name.trim();
|
|
764
|
+
if (wanted === "") throw new TypeError("screens.create needs a name that is not blank");
|
|
765
|
+
const content = [
|
|
766
|
+
["playlist_id", opts.playlistId],
|
|
767
|
+
["sequence_id", opts.sequenceId],
|
|
768
|
+
["planning_id", opts.planningId]
|
|
769
|
+
];
|
|
770
|
+
const given = content.filter(([, v]) => v !== void 0);
|
|
771
|
+
if (given.length !== 1) {
|
|
772
|
+
throw new TypeError("screens.create needs exactly one of playlistId, sequenceId, planningId");
|
|
773
|
+
}
|
|
774
|
+
const [field, id] = given[0];
|
|
775
|
+
const all = (await http.json(
|
|
776
|
+
"GET",
|
|
777
|
+
"/v1/players"
|
|
778
|
+
)).data;
|
|
779
|
+
const matches = all.filter((p) => p.play_url !== null && p.name === wanted);
|
|
780
|
+
if (matches.length >= 2) {
|
|
781
|
+
const ids = matches.map((m) => m.id);
|
|
782
|
+
throw new GibeonApiError({
|
|
783
|
+
status: 409,
|
|
784
|
+
code: "ambiguous_name",
|
|
785
|
+
message: `${matches.length} screens are named "${wanted}": ${ids.join(", ")}. Rename all but one, or call screens.update(id, ...) with the id you mean.`,
|
|
786
|
+
ids
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
if (matches.length === 1) {
|
|
790
|
+
const target = matches[0].id;
|
|
791
|
+
const patch = {};
|
|
792
|
+
for (const [key] of content) patch[key] = key === field ? id : null;
|
|
793
|
+
if (opts.location !== void 0) patch.location = opts.location;
|
|
794
|
+
const patched = await http.json(
|
|
795
|
+
"PATCH",
|
|
796
|
+
`/v1/players/${enc(target)}`,
|
|
797
|
+
patch
|
|
798
|
+
);
|
|
799
|
+
if (patched.publish_required === true) await publishOne(target);
|
|
800
|
+
return toCamel(patched.data);
|
|
801
|
+
}
|
|
802
|
+
const body = { name: wanted, [field]: id };
|
|
803
|
+
if (opts.orientation !== void 0) body.orientation = opts.orientation;
|
|
804
|
+
if (opts.location !== void 0) body.location = opts.location;
|
|
805
|
+
return toCamel((await http.json("POST", "/v1/players", body)).data);
|
|
806
|
+
},
|
|
807
|
+
update: async (id, patch) => {
|
|
808
|
+
const map = [
|
|
809
|
+
["name", "name"],
|
|
810
|
+
["location", "location"],
|
|
811
|
+
["playlistId", "playlist_id"],
|
|
812
|
+
["sequenceId", "sequence_id"],
|
|
813
|
+
["planningId", "planning_id"],
|
|
814
|
+
["groupId", "group_id"],
|
|
815
|
+
["volume", "volume"],
|
|
816
|
+
["isActive", "is_active"],
|
|
817
|
+
["hideWatermark", "hide_watermark"]
|
|
818
|
+
];
|
|
819
|
+
const body = {};
|
|
820
|
+
for (const [from, to] of map) if (patch[from] !== void 0) body[to] = patch[from];
|
|
821
|
+
const res = await http.json(
|
|
822
|
+
"PATCH",
|
|
823
|
+
`/v1/players/${enc(id)}`,
|
|
824
|
+
body
|
|
825
|
+
);
|
|
826
|
+
return { ...toCamel(res.data), publishRequired: res.publish_required };
|
|
827
|
+
},
|
|
828
|
+
publish
|
|
829
|
+
};
|
|
830
|
+
this.playlists = {
|
|
831
|
+
list: async () => toCamel((await http.json("GET", "/v1/playlists")).data),
|
|
832
|
+
get: async (id) => toCamel((await http.json("GET", `/v1/playlists/${enc(id)}`)).data),
|
|
833
|
+
create: async (input) => toCamel((await http.json("POST", "/v1/playlists", input)).data),
|
|
834
|
+
addItem: async (playlistId, item) => toCamel(
|
|
835
|
+
(await http.json("POST", `/v1/playlists/${enc(playlistId)}/items`, item)).data
|
|
836
|
+
)
|
|
837
|
+
};
|
|
838
|
+
this.assets = {
|
|
839
|
+
upload: async ({ name, data, mimeType }) => {
|
|
840
|
+
const assetType = assetTypeOf(mimeType);
|
|
841
|
+
const created = await http.json("POST", "/v1/assets", {
|
|
842
|
+
name,
|
|
843
|
+
asset_type: assetType,
|
|
844
|
+
mime_type: mimeType,
|
|
845
|
+
file_size: data.byteLength
|
|
846
|
+
});
|
|
847
|
+
const id = created.data.id;
|
|
848
|
+
await http.put(`/v1/assets/${enc(id)}/upload`, data, mimeType);
|
|
849
|
+
return toCamel((await http.json("GET", `/v1/assets/${enc(id)}`)).data);
|
|
850
|
+
}
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
async request(method, path, body) {
|
|
854
|
+
if (!path.startsWith("/")) throw new TypeError('request path must start with "/"');
|
|
855
|
+
return this.http.json(method, path, body);
|
|
856
|
+
}
|
|
857
|
+
};
|
|
858
|
+
export {
|
|
859
|
+
Gibeon,
|
|
860
|
+
GibeonApiError,
|
|
861
|
+
GibeonAuthError
|
|
862
|
+
};
|
|
863
|
+
//# sourceMappingURL=index.js.map
|