@wiconnect/sdk 0.0.0-stage → 1.0.0-rc.1
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 +43 -0
- package/README.md +35 -2
- package/dist/cjs/client.d.ts +79 -0
- package/dist/cjs/client.js +128 -0
- package/dist/cjs/contract.d.ts +53 -0
- package/dist/cjs/contract.js +76 -0
- package/dist/cjs/enums.d.ts +29 -0
- package/dist/cjs/enums.js +48 -0
- package/dist/cjs/environment.d.ts +6 -0
- package/dist/cjs/environment.js +15 -0
- package/dist/cjs/errors.d.ts +99 -0
- package/dist/cjs/errors.js +144 -0
- package/dist/cjs/index.d.ts +13 -0
- package/dist/cjs/index.js +53 -0
- package/dist/cjs/members.d.ts +61 -0
- package/dist/cjs/members.js +100 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/paging.d.ts +12 -0
- package/dist/cjs/paging.js +35 -0
- package/dist/cjs/presence.d.ts +42 -0
- package/dist/cjs/presence.js +108 -0
- package/dist/cjs/resource.d.ts +17 -0
- package/dist/cjs/resource.js +30 -0
- package/dist/cjs/transport.d.ts +64 -0
- package/dist/cjs/transport.js +332 -0
- package/dist/cjs/types.d.ts +246 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/validate.d.ts +11 -0
- package/dist/cjs/validate.js +67 -0
- package/dist/cjs/version.d.ts +4 -0
- package/dist/cjs/version.js +7 -0
- package/dist/esm/client.d.ts +79 -0
- package/dist/esm/client.js +120 -0
- package/dist/esm/contract.d.ts +53 -0
- package/dist/esm/contract.js +73 -0
- package/dist/esm/enums.d.ts +29 -0
- package/dist/esm/enums.js +45 -0
- package/dist/esm/environment.d.ts +6 -0
- package/dist/esm/environment.js +12 -0
- package/dist/esm/errors.d.ts +99 -0
- package/dist/esm/errors.js +116 -0
- package/dist/esm/index.d.ts +13 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/members.d.ts +61 -0
- package/dist/esm/members.js +96 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/paging.d.ts +12 -0
- package/dist/esm/paging.js +31 -0
- package/dist/esm/presence.d.ts +42 -0
- package/dist/esm/presence.js +104 -0
- package/dist/esm/resource.d.ts +17 -0
- package/dist/esm/resource.js +24 -0
- package/dist/esm/transport.d.ts +64 -0
- package/dist/esm/transport.js +326 -0
- package/dist/esm/types.d.ts +246 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/validate.d.ts +11 -0
- package/dist/esm/validate.js +56 -0
- package/dist/esm/version.d.ts +4 -0
- package/dist/esm/version.js +4 -0
- package/package.json +43 -4
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
// The one place that talks HTTP: timeout, cancellation, retry, idempotency, error mapping, redaction.
|
|
2
|
+
// Contract 3.8 is implemented here and only here, so no endpoint has a rule of its own.
|
|
3
|
+
import { USER_AGENT } from "./version.js";
|
|
4
|
+
import { CONTRACT } from "./contract.js";
|
|
5
|
+
import { AbortedError, AmbiguousPersonError, ApiError, BadRequestError, ConflictError, CredentialInvalidError, EndpointNotAvailableError, ForbiddenError, IdempotencyKeyReuseError, InvalidArgumentError, LocalMembershipDisabledError, MemberExistsError, MemberIdentityInvalidError, NetworkError, NotFoundError, ProtocolError, RateLimitedError, ServerError, TimeoutError, VersionConflictError, VersionRequiredError, WiConnectError, redact, } from "./errors.js";
|
|
6
|
+
import { isObject } from "./validate.js";
|
|
7
|
+
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
8
|
+
const MAX_BODY = 16 * 1024;
|
|
9
|
+
export function checkBaseUrl(raw) {
|
|
10
|
+
if (typeof raw !== "string")
|
|
11
|
+
throw new InvalidArgumentError("baseUrl must be a string such as https://cloud.example.com");
|
|
12
|
+
let u;
|
|
13
|
+
try {
|
|
14
|
+
u = new URL(raw);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
throw new InvalidArgumentError("baseUrl is not a valid URL (expected https://<cloud host>)");
|
|
18
|
+
}
|
|
19
|
+
const loopback = LOOPBACK.has(u.hostname) || u.hostname.endsWith(".localhost");
|
|
20
|
+
if (u.protocol !== "https:" && !(u.protocol === "http:" && loopback))
|
|
21
|
+
throw new InvalidArgumentError("baseUrl must be https (plain http is accepted only for localhost stand-ins)");
|
|
22
|
+
if (u.username || u.password)
|
|
23
|
+
throw new InvalidArgumentError("baseUrl must not contain a user name or password");
|
|
24
|
+
if (u.search || u.hash)
|
|
25
|
+
throw new InvalidArgumentError("baseUrl must not contain a query or fragment: secrets never travel in a URL");
|
|
26
|
+
return u.origin + u.pathname.replace(/\/+$/, "");
|
|
27
|
+
}
|
|
28
|
+
function checkRetry(r) {
|
|
29
|
+
const o = r ?? {};
|
|
30
|
+
const maxRetries = o.maxRetries ?? CONTRACT.limits.maxRetries;
|
|
31
|
+
if (!Number.isInteger(maxRetries) || maxRetries < 0 || maxRetries > 10)
|
|
32
|
+
throw new InvalidArgumentError("retry.maxRetries must be an integer from 0 to 10");
|
|
33
|
+
const baseDelayMs = o.baseDelayMs ?? 250;
|
|
34
|
+
const maxDelayMs = o.maxDelayMs ?? 4000;
|
|
35
|
+
if (!(baseDelayMs > 0) || !(maxDelayMs > 0))
|
|
36
|
+
throw new InvalidArgumentError("retry delays must be positive");
|
|
37
|
+
return { maxRetries, baseDelayMs, maxDelayMs, random: o.random ?? Math.random, sleep: o.sleep ?? defaultSleep };
|
|
38
|
+
}
|
|
39
|
+
function defaultSleep(ms, signal) {
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
if (signal?.aborted)
|
|
42
|
+
return reject(signal.reason);
|
|
43
|
+
const t = setTimeout(() => {
|
|
44
|
+
signal?.removeEventListener("abort", onAbort);
|
|
45
|
+
resolve();
|
|
46
|
+
}, ms);
|
|
47
|
+
const onAbort = () => {
|
|
48
|
+
clearTimeout(t);
|
|
49
|
+
reject(signal?.reason);
|
|
50
|
+
};
|
|
51
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
export function parseRetryAfter(h, now = Date.now()) {
|
|
55
|
+
if (!h)
|
|
56
|
+
return undefined;
|
|
57
|
+
const t = h.trim();
|
|
58
|
+
if (/^\d+$/.test(t))
|
|
59
|
+
return Number(t);
|
|
60
|
+
const d = Date.parse(t);
|
|
61
|
+
if (Number.isNaN(d))
|
|
62
|
+
return undefined;
|
|
63
|
+
return Math.max(0, Math.ceil((d - now) / 1000));
|
|
64
|
+
}
|
|
65
|
+
// Errors raised before an attempt went out: they count as no attempt and leave nothing unknown.
|
|
66
|
+
const notSent = new WeakSet();
|
|
67
|
+
function unsent(e) {
|
|
68
|
+
notSent.add(e);
|
|
69
|
+
return e;
|
|
70
|
+
}
|
|
71
|
+
// Settles with the token, or rejects as soon as the signal aborts; the token function is not waited for after that.
|
|
72
|
+
function untilAborted(get, signal) {
|
|
73
|
+
return new Promise((resolve, reject) => {
|
|
74
|
+
if (signal.aborted)
|
|
75
|
+
return reject(signal.reason);
|
|
76
|
+
const onAbort = () => reject(signal.reason);
|
|
77
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
78
|
+
const done = () => signal.removeEventListener("abort", onAbort);
|
|
79
|
+
Promise.resolve()
|
|
80
|
+
.then(get)
|
|
81
|
+
.then((v) => {
|
|
82
|
+
done();
|
|
83
|
+
resolve(v);
|
|
84
|
+
}, (e) => {
|
|
85
|
+
done();
|
|
86
|
+
reject(e);
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
export class Transport {
|
|
91
|
+
secret;
|
|
92
|
+
origin;
|
|
93
|
+
timeoutMs;
|
|
94
|
+
retry;
|
|
95
|
+
fetchImpl;
|
|
96
|
+
userAgent;
|
|
97
|
+
secrets = new Set();
|
|
98
|
+
constructor(opts, secret) {
|
|
99
|
+
this.secret = secret;
|
|
100
|
+
this.origin = checkBaseUrl(opts.baseUrl);
|
|
101
|
+
this.timeoutMs = opts.timeoutMs ?? CONTRACT.limits.defaultTimeoutMs;
|
|
102
|
+
if (typeof this.timeoutMs !== "number" || !Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0)
|
|
103
|
+
throw new InvalidArgumentError("timeoutMs must be a positive number of milliseconds");
|
|
104
|
+
this.retry = checkRetry(opts.retry);
|
|
105
|
+
this.fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
106
|
+
if (typeof this.fetchImpl !== "function")
|
|
107
|
+
throw new InvalidArgumentError("no fetch available: use Node.js 22 or newer, or pass options.fetch");
|
|
108
|
+
this.userAgent = opts.userAgentSuffix ? `${USER_AGENT} ${opts.userAgentSuffix}` : USER_AGENT;
|
|
109
|
+
}
|
|
110
|
+
async request(spec) {
|
|
111
|
+
const { method } = spec;
|
|
112
|
+
const total = spec.timeoutMs ?? this.timeoutMs;
|
|
113
|
+
if (typeof total !== "number" || !Number.isFinite(total) || total <= 0)
|
|
114
|
+
throw new InvalidArgumentError("timeoutMs must be a positive number of milliseconds");
|
|
115
|
+
const started = Date.now();
|
|
116
|
+
const deadline = started + total;
|
|
117
|
+
const user = spec.signal;
|
|
118
|
+
const canRepeat = method === "GET" || method === "POST"; // POST always carries an Idempotency-Key; PUT/PATCH never repeat // POST always carries an Idempotency-Key
|
|
119
|
+
const stamp = (e, attempts) => {
|
|
120
|
+
e.attempts = attempts;
|
|
121
|
+
if (spec.idempotencyKey)
|
|
122
|
+
e.idempotencyKey = spec.idempotencyKey;
|
|
123
|
+
return e;
|
|
124
|
+
};
|
|
125
|
+
if (user?.aborted)
|
|
126
|
+
throw stamp(new AbortedError("the call was cancelled before it was sent"), 0);
|
|
127
|
+
let body;
|
|
128
|
+
if (spec.body !== undefined) {
|
|
129
|
+
body = JSON.stringify(spec.body);
|
|
130
|
+
if (Buffer.byteLength(body) > MAX_BODY)
|
|
131
|
+
throw new InvalidArgumentError("request body is larger than the 16 KiB the cloud accepts");
|
|
132
|
+
}
|
|
133
|
+
// Sticky across the attempts of this call: once one attempt of a write may have run, a later 401 or 409 only
|
|
134
|
+
// says that attempt was refused, not that the earlier one did nothing (#1320).
|
|
135
|
+
let unknown = false;
|
|
136
|
+
for (let attempt = 0;; attempt++) {
|
|
137
|
+
let err;
|
|
138
|
+
try {
|
|
139
|
+
return await this.once(spec, body, deadline, user);
|
|
140
|
+
}
|
|
141
|
+
catch (e) {
|
|
142
|
+
if (!(e instanceof WiConnectError))
|
|
143
|
+
throw e;
|
|
144
|
+
err = e;
|
|
145
|
+
}
|
|
146
|
+
const sent = !notSent.has(err);
|
|
147
|
+
stamp(err, sent ? attempt + 1 : attempt);
|
|
148
|
+
const write = method !== "GET";
|
|
149
|
+
const status = err.status;
|
|
150
|
+
const isThrottle = err instanceof RateLimitedError;
|
|
151
|
+
const isServer = err instanceof ServerError && (status === 500 || status === 502 || status === 503 || status === 504);
|
|
152
|
+
const isNet = err instanceof NetworkError;
|
|
153
|
+
// Unknown outcome: a write that may have been carried out. 429 means it did not run; 4xx means it was refused;
|
|
154
|
+
// an attempt stopped before it went out ran nothing.
|
|
155
|
+
if (write && sent && (isNet || err instanceof TimeoutError || err instanceof AbortedError || err instanceof ServerError || err instanceof ProtocolError))
|
|
156
|
+
unknown = true;
|
|
157
|
+
err.outcomeUnknown = unknown;
|
|
158
|
+
// Contract 3.8: GET and POST retry network errors, 429 and 500/502/503/504; PUT and PATCH retry only 429.
|
|
159
|
+
const retryable = isThrottle || (canRepeat && (isNet || isServer));
|
|
160
|
+
if (!retryable || attempt >= this.retry.maxRetries)
|
|
161
|
+
throw err;
|
|
162
|
+
const remaining = deadline - Date.now();
|
|
163
|
+
const asked = err.retryAfterSeconds !== undefined && (isThrottle || status === 503) ? err.retryAfterSeconds * 1000 : undefined;
|
|
164
|
+
const cap = Math.min(this.retry.maxDelayMs, this.retry.baseDelayMs * 2 ** attempt);
|
|
165
|
+
const wait = asked ?? Math.floor(this.retry.random() * cap);
|
|
166
|
+
if (wait >= remaining)
|
|
167
|
+
throw err; // never wait past the budget: tell the caller now
|
|
168
|
+
try {
|
|
169
|
+
await this.retry.sleep(wait, user);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// Cancelled while waiting.
|
|
173
|
+
}
|
|
174
|
+
if (user?.aborted) {
|
|
175
|
+
const a = stamp(new AbortedError("the call was cancelled while waiting to retry"), attempt + 1);
|
|
176
|
+
a.outcomeUnknown = unknown; // what the earlier attempts left behind is still what it was
|
|
177
|
+
throw a;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
async once(spec, body, deadline, user) {
|
|
182
|
+
const left = deadline - Date.now();
|
|
183
|
+
if (left <= 0)
|
|
184
|
+
throw unsent(new TimeoutError("the call ran out of time before it could be sent again"));
|
|
185
|
+
if (user?.aborted)
|
|
186
|
+
throw unsent(new AbortedError("the call was cancelled before it was sent"));
|
|
187
|
+
// The timer and the cancel listener are in place before the token is fetched: a token function that is slow
|
|
188
|
+
// (a vault, a refresh) is part of the call, so the total budget and the caller's signal cover it too (#1320).
|
|
189
|
+
const ctl = new AbortController();
|
|
190
|
+
let timedOut = false;
|
|
191
|
+
let cancelled = false;
|
|
192
|
+
const timer = setTimeout(() => {
|
|
193
|
+
timedOut = true;
|
|
194
|
+
ctl.abort();
|
|
195
|
+
}, left);
|
|
196
|
+
const onUser = () => {
|
|
197
|
+
cancelled = true;
|
|
198
|
+
ctl.abort();
|
|
199
|
+
};
|
|
200
|
+
user?.addEventListener("abort", onUser, { once: true });
|
|
201
|
+
try {
|
|
202
|
+
let token;
|
|
203
|
+
try {
|
|
204
|
+
token = await untilAborted(() => this.secret(), ctl.signal);
|
|
205
|
+
}
|
|
206
|
+
catch (e) {
|
|
207
|
+
if (timedOut)
|
|
208
|
+
throw unsent(new TimeoutError("the call ran out of time while waiting for the token function; nothing was sent"));
|
|
209
|
+
if (cancelled)
|
|
210
|
+
throw unsent(new AbortedError("the call was cancelled while waiting for the token function; nothing was sent"));
|
|
211
|
+
throw e;
|
|
212
|
+
}
|
|
213
|
+
this.secrets.add(token);
|
|
214
|
+
const url = new URL(this.origin + spec.path);
|
|
215
|
+
for (const [k, v] of Object.entries(spec.query ?? {}))
|
|
216
|
+
if (v !== undefined)
|
|
217
|
+
url.searchParams.set(k, String(v));
|
|
218
|
+
const headers = { authorization: `Bearer ${token}`, accept: "application/json", "user-agent": this.userAgent };
|
|
219
|
+
if (body !== undefined)
|
|
220
|
+
headers["content-type"] = "application/json";
|
|
221
|
+
if (spec.idempotencyKey)
|
|
222
|
+
headers["idempotency-key"] = spec.idempotencyKey;
|
|
223
|
+
let res;
|
|
224
|
+
let text;
|
|
225
|
+
try {
|
|
226
|
+
res = await this.fetchImpl(url, { method: spec.method, headers, body, signal: ctl.signal, redirect: "manual" });
|
|
227
|
+
text = await res.text();
|
|
228
|
+
}
|
|
229
|
+
catch (e) {
|
|
230
|
+
if (timedOut)
|
|
231
|
+
throw new TimeoutError("the call did not finish within the time allowed and was stopped");
|
|
232
|
+
if (cancelled)
|
|
233
|
+
throw new AbortedError("the call was cancelled");
|
|
234
|
+
const n = new NetworkError("could not reach the WiConnect cloud (no response received)");
|
|
235
|
+
n.reason = redact(String(e?.cause?.code ?? e?.name ?? "error"), this.secrets);
|
|
236
|
+
throw n;
|
|
237
|
+
}
|
|
238
|
+
return this.interpret(res, text, spec);
|
|
239
|
+
}
|
|
240
|
+
finally {
|
|
241
|
+
clearTimeout(timer);
|
|
242
|
+
user?.removeEventListener("abort", onUser);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
interpret(res, text, spec) {
|
|
246
|
+
const requestIdHeader = res.headers.get("x-request-id") || undefined;
|
|
247
|
+
if (res.status >= 300 && res.status < 400)
|
|
248
|
+
throw new ProtocolError(`unexpected redirect (HTTP ${res.status}); the cloud does not redirect API calls`, { status: res.status, requestId: requestIdHeader });
|
|
249
|
+
if (res.status >= 200 && res.status < 300) {
|
|
250
|
+
let data;
|
|
251
|
+
try {
|
|
252
|
+
data = JSON.parse(text);
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
throw new ProtocolError(`the cloud answered HTTP ${res.status} with a body that is not JSON`, { status: res.status, requestId: requestIdHeader });
|
|
256
|
+
}
|
|
257
|
+
return { data: data, status: res.status, headers: res.headers };
|
|
258
|
+
}
|
|
259
|
+
throw this.apiError(res, text, spec, requestIdHeader);
|
|
260
|
+
}
|
|
261
|
+
apiError(res, text, spec, headerId) {
|
|
262
|
+
const status = res.status;
|
|
263
|
+
let parsed;
|
|
264
|
+
try {
|
|
265
|
+
parsed = JSON.parse(text);
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
parsed = undefined;
|
|
269
|
+
}
|
|
270
|
+
const apiBody = isObject(parsed) && typeof parsed.error === "string" ? parsed : undefined;
|
|
271
|
+
const bodyId = apiBody && typeof apiBody.request_id === "string" && apiBody.request_id ? apiBody.request_id : undefined;
|
|
272
|
+
const fields = {
|
|
273
|
+
status,
|
|
274
|
+
requestId: headerId || bodyId,
|
|
275
|
+
retryAfterSeconds: parseRetryAfter(res.headers.get("retry-after")),
|
|
276
|
+
};
|
|
277
|
+
if (!apiBody) {
|
|
278
|
+
if (status === 404) {
|
|
279
|
+
return new EndpointNotAvailableError(`this WiConnect cloud does not offer ${spec.method} ${spec.what ?? spec.path} (HTTP 404 without an API error body). ` +
|
|
280
|
+
`The cloud is probably older than this SDK and does not have this endpoint yet. ` +
|
|
281
|
+
`Ask your WiConnect contact which cloud version you are on, or use an SDK version that matches it.`, fields);
|
|
282
|
+
}
|
|
283
|
+
return this.byStatus(status, undefined, `HTTP ${status}`, fields);
|
|
284
|
+
}
|
|
285
|
+
const code = apiBody.error;
|
|
286
|
+
const said = typeof apiBody.message === "string" ? redact(apiBody.message, this.secrets) : "";
|
|
287
|
+
const e = this.byStatus(status, code, `${code}${said ? `: ${said}` : ""} (HTTP ${status}${fields.requestId ? `, request ${fields.requestId}` : ""})`, { ...fields, code });
|
|
288
|
+
if (e instanceof AmbiguousPersonError && Array.isArray(apiBody.candidates)) {
|
|
289
|
+
e.candidates = apiBody.candidates
|
|
290
|
+
.filter((c) => isObject(c))
|
|
291
|
+
.map((c) => ({ issuer: String(c.issuer ?? ""), id: String(c.id ?? "") }));
|
|
292
|
+
}
|
|
293
|
+
return e;
|
|
294
|
+
}
|
|
295
|
+
byStatus(status, code, message, f) {
|
|
296
|
+
const msg = `WiConnect API error: ${message}`;
|
|
297
|
+
if (status === 400)
|
|
298
|
+
return code === "member_identity_invalid" ? new MemberIdentityInvalidError(msg, f) : new BadRequestError(msg, f);
|
|
299
|
+
if (status === 401)
|
|
300
|
+
return new CredentialInvalidError(msg, f);
|
|
301
|
+
if (status === 403)
|
|
302
|
+
return new ForbiddenError(msg, f);
|
|
303
|
+
if (status === 404)
|
|
304
|
+
return new NotFoundError(msg, f);
|
|
305
|
+
if (status === 409) {
|
|
306
|
+
if (code === "version_conflict")
|
|
307
|
+
return new VersionConflictError(msg, f);
|
|
308
|
+
if (code === "ambiguous_person")
|
|
309
|
+
return new AmbiguousPersonError(msg, f);
|
|
310
|
+
if (code === "local_membership_disabled")
|
|
311
|
+
return new LocalMembershipDisabledError(msg, f);
|
|
312
|
+
if (code === "member_exists")
|
|
313
|
+
return new MemberExistsError(msg, f);
|
|
314
|
+
return new ConflictError(msg, f);
|
|
315
|
+
}
|
|
316
|
+
if (status === 422 && code === "idempotency_key_reuse")
|
|
317
|
+
return new IdempotencyKeyReuseError(msg, f);
|
|
318
|
+
if (status === 428)
|
|
319
|
+
return new VersionRequiredError(msg, f);
|
|
320
|
+
if (status === 429)
|
|
321
|
+
return new RateLimitedError(msg, f);
|
|
322
|
+
if (status >= 500)
|
|
323
|
+
return new ServerError(msg, f);
|
|
324
|
+
return new ApiError(msg, f);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import type { APPLIED_BY, APPLIED_STATES, AUTHORIZED_STATES, CAPABILITIES_ENFORCER_KINDS, CAPABILITY_STATES, CREDENTIAL_STATES, DIAGNOSTICS_ENFORCER_STATES, DISCONNECT_OUTCOMES, ENDED_REASONS, ENFORCER_KINDS, GRANT_STATES, MEMBER_STATES, Open, PRESENCE_INTENTS, PRESENCE_SOURCES, PRESENCE_STATES, REVOCATION_CONFIRMED_BY, REVOCATION_STATES, SCOPES, WAN_SOURCES, WAN_STATES } from "./enums.js";
|
|
2
|
+
export type GrantState = Open<(typeof GRANT_STATES)[number]>;
|
|
3
|
+
export type Scope = Open<(typeof SCOPES)[number]>;
|
|
4
|
+
export type MemberState = Open<(typeof MEMBER_STATES)[number]>;
|
|
5
|
+
export type PresenceIntent = Open<(typeof PRESENCE_INTENTS)[number]>;
|
|
6
|
+
/** `limit` default 50, at most 200. `next_cursor` is opaque; "" on the last page. Never build or parse one. */
|
|
7
|
+
export interface Page<T> {
|
|
8
|
+
items: T[];
|
|
9
|
+
limit: number;
|
|
10
|
+
next_cursor: string;
|
|
11
|
+
}
|
|
12
|
+
export interface Credential {
|
|
13
|
+
id: string;
|
|
14
|
+
name: string;
|
|
15
|
+
organization: string;
|
|
16
|
+
sites: string[];
|
|
17
|
+
scopes: Scope[];
|
|
18
|
+
org_wide: boolean;
|
|
19
|
+
state: Open<(typeof CREDENTIAL_STATES)[number]>;
|
|
20
|
+
created_at: number;
|
|
21
|
+
expires_at: number;
|
|
22
|
+
last_used_at?: number;
|
|
23
|
+
issued_by?: string;
|
|
24
|
+
previous_secret_ends_at?: number;
|
|
25
|
+
version: number;
|
|
26
|
+
}
|
|
27
|
+
export interface Site {
|
|
28
|
+
id: string;
|
|
29
|
+
slug: string;
|
|
30
|
+
display_name: string;
|
|
31
|
+
network_name?: string;
|
|
32
|
+
landing_url?: string;
|
|
33
|
+
theme?: string;
|
|
34
|
+
timezone?: string;
|
|
35
|
+
contact?: string;
|
|
36
|
+
consent: {
|
|
37
|
+
text: string;
|
|
38
|
+
version: number;
|
|
39
|
+
};
|
|
40
|
+
has_logo?: boolean;
|
|
41
|
+
/** Read only. */
|
|
42
|
+
disabled?: boolean;
|
|
43
|
+
/** Read only. */
|
|
44
|
+
grant_scope?: Open<"organization" | "site">;
|
|
45
|
+
created?: number;
|
|
46
|
+
version: number;
|
|
47
|
+
}
|
|
48
|
+
/** One effect layer that is only ever "saved". */
|
|
49
|
+
export interface SavedLayer {
|
|
50
|
+
state: "saved";
|
|
51
|
+
version?: number;
|
|
52
|
+
at: number;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The five effect states, answered separately (contract section 4). Nothing is inferred upward:
|
|
56
|
+
* `applied.state === "confirmed"` means the executor says it carried the decision out, not that the internet works;
|
|
57
|
+
* `observed.wan` is always `unknown` in the first release (`no_wan_evidence_source`).
|
|
58
|
+
*/
|
|
59
|
+
export interface SessionState {
|
|
60
|
+
saved: {
|
|
61
|
+
state: "saved";
|
|
62
|
+
at: number;
|
|
63
|
+
};
|
|
64
|
+
authorized: {
|
|
65
|
+
state: Open<(typeof AUTHORIZED_STATES)[number]>;
|
|
66
|
+
expires_at: number;
|
|
67
|
+
ended_reason?: Open<(typeof ENDED_REASONS)[number]>;
|
|
68
|
+
};
|
|
69
|
+
applied: {
|
|
70
|
+
state: Open<(typeof APPLIED_STATES)[number]>;
|
|
71
|
+
at?: number;
|
|
72
|
+
by?: Open<(typeof APPLIED_BY)[number]>;
|
|
73
|
+
reason?: string;
|
|
74
|
+
};
|
|
75
|
+
observed: {
|
|
76
|
+
presence: {
|
|
77
|
+
state: Open<(typeof PRESENCE_STATES)[number]>;
|
|
78
|
+
at?: number;
|
|
79
|
+
source?: Open<(typeof PRESENCE_SOURCES)[number]>;
|
|
80
|
+
reason?: string;
|
|
81
|
+
};
|
|
82
|
+
wan: {
|
|
83
|
+
state: Open<(typeof WAN_STATES)[number]>;
|
|
84
|
+
at?: number;
|
|
85
|
+
source?: Open<(typeof WAN_SOURCES)[number]>;
|
|
86
|
+
reason: string;
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* What is known about ending a session. `pending` is NOT "disconnected": the executor has not confirmed.
|
|
92
|
+
* `unconfirmed_expired` is "the time ran out", also not a confirmation.
|
|
93
|
+
*/
|
|
94
|
+
export interface Revocation {
|
|
95
|
+
state: Open<(typeof REVOCATION_STATES)[number]>;
|
|
96
|
+
requested_at: number;
|
|
97
|
+
confirmed_at?: number;
|
|
98
|
+
confirmed_by?: Open<(typeof REVOCATION_CONFIRMED_BY)[number]>;
|
|
99
|
+
/** null: no known bound (a gateway that has not been heard from). Never a guess. */
|
|
100
|
+
latest_effect_at?: number | null;
|
|
101
|
+
disconnect?: {
|
|
102
|
+
attempted?: boolean;
|
|
103
|
+
outcome?: Open<(typeof DISCONNECT_OUTCOMES)[number]>;
|
|
104
|
+
};
|
|
105
|
+
request_id?: string;
|
|
106
|
+
}
|
|
107
|
+
export interface Session {
|
|
108
|
+
id: string;
|
|
109
|
+
site_id: string;
|
|
110
|
+
subject: {
|
|
111
|
+
issuer: string;
|
|
112
|
+
subject: string;
|
|
113
|
+
};
|
|
114
|
+
/** Masked: the first three bytes only. No IP. */
|
|
115
|
+
device: {
|
|
116
|
+
mac_masked: string;
|
|
117
|
+
};
|
|
118
|
+
class?: string;
|
|
119
|
+
synthetic?: boolean;
|
|
120
|
+
issued_at: number;
|
|
121
|
+
expires_at: number;
|
|
122
|
+
enforcer: Open<(typeof ENFORCER_KINDS)[number]>;
|
|
123
|
+
grant_state: GrantState;
|
|
124
|
+
state: SessionState;
|
|
125
|
+
revocation?: Revocation | null;
|
|
126
|
+
}
|
|
127
|
+
export interface Capability {
|
|
128
|
+
key: string;
|
|
129
|
+
state: Open<(typeof CAPABILITY_STATES)[number]>;
|
|
130
|
+
value?: number | null;
|
|
131
|
+
reason?: string;
|
|
132
|
+
source?: string;
|
|
133
|
+
reported_at?: number;
|
|
134
|
+
}
|
|
135
|
+
export interface Capabilities {
|
|
136
|
+
site_id: string;
|
|
137
|
+
enforcer: Open<(typeof CAPABILITIES_ENFORCER_KINDS)[number]>;
|
|
138
|
+
items: Capability[];
|
|
139
|
+
}
|
|
140
|
+
export interface Diagnostics {
|
|
141
|
+
site_id: string;
|
|
142
|
+
generated_at: number;
|
|
143
|
+
enforcer: {
|
|
144
|
+
kind: Open<(typeof CAPABILITIES_ENFORCER_KINDS)[number]>;
|
|
145
|
+
state: Open<(typeof DIAGNOSTICS_ENFORCER_STATES)[number]>;
|
|
146
|
+
last_seen?: number;
|
|
147
|
+
};
|
|
148
|
+
/** Gateway sites only. */
|
|
149
|
+
config?: {
|
|
150
|
+
desired_version?: number;
|
|
151
|
+
applied_version?: number;
|
|
152
|
+
applied?: string;
|
|
153
|
+
last_ack_at?: number;
|
|
154
|
+
};
|
|
155
|
+
/** Sites served by their own access points only. */
|
|
156
|
+
native_setup?: {
|
|
157
|
+
checks?: Array<{
|
|
158
|
+
key: string;
|
|
159
|
+
state: string;
|
|
160
|
+
last_seen?: number;
|
|
161
|
+
}>;
|
|
162
|
+
};
|
|
163
|
+
last_identity_test?: {
|
|
164
|
+
id: string;
|
|
165
|
+
status: string;
|
|
166
|
+
at: number;
|
|
167
|
+
} | null;
|
|
168
|
+
observed: {
|
|
169
|
+
wan: {
|
|
170
|
+
state: Open<(typeof WAN_STATES)[number]>;
|
|
171
|
+
at?: number;
|
|
172
|
+
reason: string;
|
|
173
|
+
};
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
export interface Member {
|
|
177
|
+
id: string;
|
|
178
|
+
/** With `subject`, the stable identity. Never an e-mail address or phone number. */
|
|
179
|
+
issuer: string;
|
|
180
|
+
/** Shown case-folded, as the existing member key is. */
|
|
181
|
+
subject: string;
|
|
182
|
+
state: MemberState;
|
|
183
|
+
/** Unix seconds; null or absent for no deadline. */
|
|
184
|
+
expires_at?: number | null;
|
|
185
|
+
created_at: number;
|
|
186
|
+
updated_at: number;
|
|
187
|
+
version: number;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* The answer to a member write. Three different facts, not one "success":
|
|
191
|
+
* `saved` — eligibility was changed in the cloud;
|
|
192
|
+
* `sessions.revocation` — whether this call asked for any session to end (`not_requested`: it did not;
|
|
193
|
+
* ending sessions is `sessions.revoke`, a separate operation with its own answer).
|
|
194
|
+
*/
|
|
195
|
+
export interface MemberSaved {
|
|
196
|
+
member: Member;
|
|
197
|
+
saved: SavedLayer;
|
|
198
|
+
sessions: {
|
|
199
|
+
revocation: Open<"not_requested">;
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
export interface PresenceEntry {
|
|
203
|
+
id: string;
|
|
204
|
+
issuer: string;
|
|
205
|
+
email?: string;
|
|
206
|
+
phone?: string;
|
|
207
|
+
intent?: PresenceIntent;
|
|
208
|
+
online: boolean;
|
|
209
|
+
device: Open<"phone" | "computer" | "unknown">;
|
|
210
|
+
/** Unix seconds: when the venue gateway last saw this person's device. */
|
|
211
|
+
last_seen: number;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Who is here and willing to be known. **An empty `items` is not "the room is empty"**: the list holds only
|
|
215
|
+
* people who were seen in the last 15 minutes AND agreed to be known; a gateway with observation off, an offline
|
|
216
|
+
* gateway, or nobody consenting all give the same empty list.
|
|
217
|
+
*/
|
|
218
|
+
export interface PresenceList {
|
|
219
|
+
items: PresenceEntry[];
|
|
220
|
+
/** How many people are visible in `items`. Not a head count of the room. */
|
|
221
|
+
visibleCount: number;
|
|
222
|
+
/** When this SDK received the answer (ms since epoch). */
|
|
223
|
+
fetchedAt: number;
|
|
224
|
+
/** From Cache-Control: asking more often than this learns nothing new. */
|
|
225
|
+
cacheMaxAgeSeconds?: number;
|
|
226
|
+
/** A reminder that travels with the data. */
|
|
227
|
+
note: string;
|
|
228
|
+
}
|
|
229
|
+
export interface ConsentResult {
|
|
230
|
+
id: string;
|
|
231
|
+
issuer: string;
|
|
232
|
+
consent: boolean;
|
|
233
|
+
intent: PresenceIntent;
|
|
234
|
+
}
|
|
235
|
+
export type PersonRef = {
|
|
236
|
+
id: string;
|
|
237
|
+
issuer?: string;
|
|
238
|
+
} | {
|
|
239
|
+
email: string;
|
|
240
|
+
} | {
|
|
241
|
+
phone: string;
|
|
242
|
+
};
|
|
243
|
+
export interface AmbiguousCandidate {
|
|
244
|
+
issuer: string;
|
|
245
|
+
id: string;
|
|
246
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare function isObject(v: unknown): v is Record<string, unknown>;
|
|
2
|
+
export declare function bad(message: string): never;
|
|
3
|
+
export declare function requireObject(v: unknown, what: string): Record<string, unknown>;
|
|
4
|
+
/** Refuses keys the cloud would reject as unknown (and so catches typos like `emial`). */
|
|
5
|
+
export declare function onlyKeys(o: object, allowed: readonly string[], what: string): void;
|
|
6
|
+
export declare function nonEmptyString(v: unknown, what: string, max?: number): string;
|
|
7
|
+
export declare function limitOf(v: unknown): number | undefined;
|
|
8
|
+
export declare function idempotencyKeyOf(v: unknown): string | undefined;
|
|
9
|
+
/** Unix seconds. A value in milliseconds is the usual mistake, so values beyond year 2100 are refused. */
|
|
10
|
+
export declare function unixSeconds(v: unknown, what: string): number;
|
|
11
|
+
export declare function versionOf(v: unknown): number;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Local argument checks. They mirror what the cloud would answer with 400 (it rejects unknown fields and bad
|
|
2
|
+
// values), so a mistake is reported at once, with the argument's name, and nothing is sent.
|
|
3
|
+
import { CONTRACT } from "./contract.js";
|
|
4
|
+
import { InvalidArgumentError } from "./errors.js";
|
|
5
|
+
export function isObject(v) {
|
|
6
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
7
|
+
}
|
|
8
|
+
export function bad(message) {
|
|
9
|
+
throw new InvalidArgumentError(message);
|
|
10
|
+
}
|
|
11
|
+
export function requireObject(v, what) {
|
|
12
|
+
if (!isObject(v))
|
|
13
|
+
bad(`${what} must be an object`);
|
|
14
|
+
return v;
|
|
15
|
+
}
|
|
16
|
+
/** Refuses keys the cloud would reject as unknown (and so catches typos like `emial`). */
|
|
17
|
+
export function onlyKeys(o, allowed, what) {
|
|
18
|
+
for (const k of Object.keys(o))
|
|
19
|
+
if (!allowed.includes(k))
|
|
20
|
+
bad(`${what}: unknown option "${k}" (allowed: ${allowed.join(", ")})`);
|
|
21
|
+
}
|
|
22
|
+
export function nonEmptyString(v, what, max = 2048) {
|
|
23
|
+
if (typeof v !== "string" || v.trim() === "")
|
|
24
|
+
bad(`${what} must be a non-empty string`);
|
|
25
|
+
if (v.length > max)
|
|
26
|
+
bad(`${what} is longer than ${max} characters`);
|
|
27
|
+
return v;
|
|
28
|
+
}
|
|
29
|
+
export function limitOf(v) {
|
|
30
|
+
if (v === undefined)
|
|
31
|
+
return undefined;
|
|
32
|
+
if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > CONTRACT.limits.pageMax)
|
|
33
|
+
bad(`limit must be an integer from 1 to ${CONTRACT.limits.pageMax}`);
|
|
34
|
+
return v;
|
|
35
|
+
}
|
|
36
|
+
const KEY_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
37
|
+
export function idempotencyKeyOf(v) {
|
|
38
|
+
if (v === undefined)
|
|
39
|
+
return undefined;
|
|
40
|
+
if (typeof v !== "string" || !KEY_RE.test(v))
|
|
41
|
+
bad("idempotencyKey must be 1-64 characters from A-Z a-z 0-9 _ -");
|
|
42
|
+
return v;
|
|
43
|
+
}
|
|
44
|
+
/** Unix seconds. A value in milliseconds is the usual mistake, so values beyond year 2100 are refused. */
|
|
45
|
+
export function unixSeconds(v, what) {
|
|
46
|
+
if (typeof v !== "number" || !Number.isInteger(v) || v < 1)
|
|
47
|
+
bad(`${what} must be a whole number of Unix seconds`);
|
|
48
|
+
if (v > 4_102_444_800)
|
|
49
|
+
bad(`${what} is beyond the year 2100: is it in milliseconds? The cloud uses Unix seconds`);
|
|
50
|
+
return v;
|
|
51
|
+
}
|
|
52
|
+
export function versionOf(v) {
|
|
53
|
+
if (typeof v !== "number" || !Number.isInteger(v) || v < 0)
|
|
54
|
+
bad("version is required: pass the `version` you read (a whole number, 0 or more)");
|
|
55
|
+
return v;
|
|
56
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** The SDK version. `test/packaging.test.mjs` keeps it equal to package.json. */
|
|
2
|
+
export declare const VERSION = "1.0.0-rc.1";
|
|
3
|
+
/** Sent as the User-Agent so the cloud's logs and a support request can tell which SDK called. */
|
|
4
|
+
export declare const USER_AGENT = "wiconnect-sdk-js/1.0.0-rc.1";
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** The SDK version. `test/packaging.test.mjs` keeps it equal to package.json. */
|
|
2
|
+
export const VERSION = "1.0.0-rc.1";
|
|
3
|
+
/** Sent as the User-Agent so the cloud's logs and a support request can tell which SDK called. */
|
|
4
|
+
export const USER_AGENT = `wiconnect-sdk-js/${VERSION}`;
|