@mediaviz/react-native-sdk 1.9.0-dev.116
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/LICENSE +21 -0
- package/dist/react.cjs +404 -0
- package/dist/react.d.cts +48 -0
- package/dist/react.d.ts +48 -0
- package/dist/react.esm.js +400 -0
- package/dist/sdk.cjs +3032 -0
- package/dist/sdk.d.cts +650 -0
- package/dist/sdk.d.ts +650 -0
- package/dist/sdk.esm.d.ts +650 -0
- package/dist/sdk.esm.js +2986 -0
- package/package.json +60 -0
package/dist/sdk.cjs
ADDED
|
@@ -0,0 +1,3032 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
function getDefaultExportFromCjs (x) {
|
|
4
|
+
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
var base64;
|
|
8
|
+
var hasRequiredBase64;
|
|
9
|
+
|
|
10
|
+
function requireBase64 () {
|
|
11
|
+
if (hasRequiredBase64) return base64;
|
|
12
|
+
hasRequiredBase64 = 1;
|
|
13
|
+
|
|
14
|
+
// Base64URL codec, used by PKCE (encode) and JWT payload decoding (decode).
|
|
15
|
+
// Hand-rolled rather than delegating to atob/btoa, Buffer, or TextDecoder:
|
|
16
|
+
// none of those is present on every target runtime — React Native's Hermes has
|
|
17
|
+
// no Buffer and does not guarantee atob — and the alphabet here is URL-safe and
|
|
18
|
+
// unpadded, which the standard helpers do not produce.
|
|
19
|
+
|
|
20
|
+
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {Uint8Array} bytes
|
|
24
|
+
* @returns {string} unpadded base64url
|
|
25
|
+
*/
|
|
26
|
+
function base64urlEncode(bytes) {
|
|
27
|
+
let result = '';
|
|
28
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
29
|
+
const b0 = bytes[i];
|
|
30
|
+
const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
|
|
31
|
+
const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
|
|
32
|
+
result += ALPHABET[b0 >> 2];
|
|
33
|
+
result += ALPHABET[((b0 & 3) << 4) | (b1 >> 4)];
|
|
34
|
+
if (i + 1 < bytes.length) result += ALPHABET[((b1 & 0xf) << 2) | (b2 >> 6)];
|
|
35
|
+
if (i + 2 < bytes.length) result += ALPHABET[b2 & 0x3f];
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Decodes base64url or standard base64, padded or not.
|
|
42
|
+
* @param {string} str
|
|
43
|
+
* @returns {Uint8Array}
|
|
44
|
+
*/
|
|
45
|
+
function base64urlDecode(str) {
|
|
46
|
+
const clean = String(str).replace(/=+$/, '');
|
|
47
|
+
const out = new Uint8Array((clean.length * 3) >> 2);
|
|
48
|
+
let acc = 0;
|
|
49
|
+
let bits = 0;
|
|
50
|
+
let i = 0;
|
|
51
|
+
for (const ch of clean) {
|
|
52
|
+
const value = decodeChar(ch);
|
|
53
|
+
if (value < 0) throw new TypeError(`Invalid base64url character: ${JSON.stringify(ch)}`);
|
|
54
|
+
acc = (acc << 6) | value;
|
|
55
|
+
bits += 6;
|
|
56
|
+
if (bits >= 8) {
|
|
57
|
+
bits -= 8;
|
|
58
|
+
out[i++] = (acc >> bits) & 0xff;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return out.subarray(0, i);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @param {Uint8Array} bytes
|
|
66
|
+
* @returns {string}
|
|
67
|
+
*/
|
|
68
|
+
function utf8Decode(bytes) {
|
|
69
|
+
let out = '';
|
|
70
|
+
let i = 0;
|
|
71
|
+
while (i < bytes.length) {
|
|
72
|
+
const b0 = bytes[i++];
|
|
73
|
+
let codePoint;
|
|
74
|
+
if (b0 < 0x80) codePoint = b0;
|
|
75
|
+
else if ((b0 & 0xe0) === 0xc0) codePoint = ((b0 & 0x1f) << 6) | (bytes[i++] & 0x3f);
|
|
76
|
+
else if ((b0 & 0xf0) === 0xe0)
|
|
77
|
+
codePoint = ((b0 & 0x0f) << 12) | ((bytes[i++] & 0x3f) << 6) | (bytes[i++] & 0x3f);
|
|
78
|
+
else
|
|
79
|
+
codePoint =
|
|
80
|
+
((b0 & 0x07) << 18) | ((bytes[i++] & 0x3f) << 12) | ((bytes[i++] & 0x3f) << 6) | (bytes[i++] & 0x3f);
|
|
81
|
+
out += String.fromCodePoint(codePoint);
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// helpers
|
|
87
|
+
function decodeChar(ch) {
|
|
88
|
+
// '+' and '/' map onto the URL-safe alphabet's '-' and '_' slots, so standard
|
|
89
|
+
// base64 decodes through the same table.
|
|
90
|
+
if (ch === '+') return 62;
|
|
91
|
+
if (ch === '/') return 63;
|
|
92
|
+
return ALPHABET.indexOf(ch);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
base64 = { base64urlEncode, base64urlDecode, utf8Decode };
|
|
96
|
+
return base64;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
var crypto$1;
|
|
100
|
+
var hasRequiredCrypto$1;
|
|
101
|
+
|
|
102
|
+
function requireCrypto$1 () {
|
|
103
|
+
if (hasRequiredCrypto$1) return crypto$1;
|
|
104
|
+
hasRequiredCrypto$1 = 1;
|
|
105
|
+
|
|
106
|
+
// Crypto seam for PKCE.
|
|
107
|
+
//
|
|
108
|
+
// Defaults to WebCrypto, which covers browsers and Node >= 18. React Native's
|
|
109
|
+
// Hermes runtime provides neither half of what PKCE needs: there is no
|
|
110
|
+
// SubtleCrypto at all (so no SHA-256), and no crypto.getRandomValues without a
|
|
111
|
+
// polyfill. Hosts on such runtimes call configureCrypto() once at startup with
|
|
112
|
+
// native-backed equivalents (expo-crypto, react-native-quick-crypto).
|
|
113
|
+
|
|
114
|
+
/** @typedef {{getRandomValues: (bytes: Uint8Array) => Uint8Array, sha256: (bytes: Uint8Array) => Promise<Uint8Array>}} CryptoProvider */
|
|
115
|
+
|
|
116
|
+
let _provider = null;
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Installs a crypto provider, replacing the WebCrypto default.
|
|
120
|
+
* @param {CryptoProvider} provider
|
|
121
|
+
*/
|
|
122
|
+
function configureCrypto(provider) {
|
|
123
|
+
if (!provider || typeof provider.getRandomValues !== 'function' || typeof provider.sha256 !== 'function') {
|
|
124
|
+
throw new TypeError(
|
|
125
|
+
'configureCrypto requires { getRandomValues(bytes) => bytes, sha256(bytes) => Promise<Uint8Array> }'
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
_provider = provider;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Restores the WebCrypto default. Primarily for tests. */
|
|
132
|
+
function resetCrypto() {
|
|
133
|
+
_provider = null;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* @returns {CryptoProvider}
|
|
138
|
+
*/
|
|
139
|
+
function getCrypto() {
|
|
140
|
+
return _provider ?? webCryptoProvider();
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// helpers
|
|
144
|
+
function webCryptoProvider() {
|
|
145
|
+
const wc = globalThis.crypto;
|
|
146
|
+
// Named explicitly rather than letting a property access blow up deep inside
|
|
147
|
+
// PKCE: on React Native the failure is a missing polyfill, and the message
|
|
148
|
+
// has to say so.
|
|
149
|
+
if (!wc || typeof wc.getRandomValues !== 'function' || !wc.subtle) {
|
|
150
|
+
throw new Error(
|
|
151
|
+
'No WebCrypto available in this runtime. On React Native (or any host without ' +
|
|
152
|
+
'SubtleCrypto), call configureCrypto({ getRandomValues, sha256 }) before using PKCE.'
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
getRandomValues: (bytes) => wc.getRandomValues(bytes),
|
|
157
|
+
sha256: async (bytes) => new Uint8Array(await wc.subtle.digest('SHA-256', bytes)),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
crypto$1 = { configureCrypto, resetCrypto, getCrypto };
|
|
162
|
+
return crypto$1;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
var pkce;
|
|
166
|
+
var hasRequiredPkce;
|
|
167
|
+
|
|
168
|
+
function requirePkce () {
|
|
169
|
+
if (hasRequiredPkce) return pkce;
|
|
170
|
+
hasRequiredPkce = 1;
|
|
171
|
+
|
|
172
|
+
const { base64urlEncode } = requireBase64();
|
|
173
|
+
const { getCrypto } = requireCrypto$1();
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Generates a 64-character PKCE code verifier from [A-Za-z0-9-._~].
|
|
177
|
+
* @returns {string}
|
|
178
|
+
*/
|
|
179
|
+
function generateCodeVerifier() {
|
|
180
|
+
const bytes = new Uint8Array(48);
|
|
181
|
+
getCrypto().getRandomValues(bytes);
|
|
182
|
+
return base64urlEncode(bytes).slice(0, 64);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Computes Base64URL(SHA256(verifier)) with no padding.
|
|
187
|
+
* @param {string} verifier
|
|
188
|
+
* @returns {Promise<string>}
|
|
189
|
+
*/
|
|
190
|
+
async function generateCodeChallenge(verifier) {
|
|
191
|
+
const hash = await getCrypto().sha256(asciiEncode(verifier));
|
|
192
|
+
return base64urlEncode(hash);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Generates a cryptographically random 32-char hex state value.
|
|
197
|
+
* @returns {string}
|
|
198
|
+
*/
|
|
199
|
+
function generateState() {
|
|
200
|
+
const bytes = new Uint8Array(16);
|
|
201
|
+
getCrypto().getRandomValues(bytes);
|
|
202
|
+
return Array.from(bytes).map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// helpers
|
|
206
|
+
|
|
207
|
+
// The RFC 7636 §4.1 verifier alphabet is ASCII-only, so a byte-per-char encode
|
|
208
|
+
// is exact and keeps TextEncoder — absent on some React Native versions — off
|
|
209
|
+
// the PKCE path entirely. A non-ASCII verifier is invalid input, not something
|
|
210
|
+
// to silently re-encode.
|
|
211
|
+
function asciiEncode(str) {
|
|
212
|
+
const out = new Uint8Array(str.length);
|
|
213
|
+
for (let i = 0; i < str.length; i++) {
|
|
214
|
+
const code = str.charCodeAt(i);
|
|
215
|
+
if (code > 0x7f) throw new TypeError('PKCE code_verifier must be ASCII (RFC 7636 §4.1)');
|
|
216
|
+
out[i] = code;
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
pkce = { generateCodeVerifier, generateCodeChallenge, generateState };
|
|
222
|
+
return pkce;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
var errors;
|
|
226
|
+
var hasRequiredErrors;
|
|
227
|
+
|
|
228
|
+
function requireErrors () {
|
|
229
|
+
if (hasRequiredErrors) return errors;
|
|
230
|
+
hasRequiredErrors = 1;
|
|
231
|
+
|
|
232
|
+
class OAuthError extends Error {
|
|
233
|
+
/**
|
|
234
|
+
* @param {string} code - RFC 6749 error code
|
|
235
|
+
* @param {string} description - Human-readable description
|
|
236
|
+
* @param {number} httpStatus - HTTP status code
|
|
237
|
+
* @param {unknown} [body] - Raw response body (parsed JSON when available)
|
|
238
|
+
*/
|
|
239
|
+
constructor(code, description, httpStatus, body = null) {
|
|
240
|
+
super(description);
|
|
241
|
+
this.name = 'OAuthError';
|
|
242
|
+
this.code = code;
|
|
243
|
+
this.description = description;
|
|
244
|
+
this.httpStatus = httpStatus;
|
|
245
|
+
this.body = body;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* @param {number} status
|
|
250
|
+
* @param {unknown} body
|
|
251
|
+
* @returns {OAuthError}
|
|
252
|
+
*/
|
|
253
|
+
static fromResponse(status, body) {
|
|
254
|
+
// FastAPI wraps HTTPException payloads in a `detail` envelope, so an OAuth
|
|
255
|
+
// error arrives as { detail: { error, error_description } }. Unwrap it
|
|
256
|
+
// before falling back, or every server-side OAuth error reads as server_error.
|
|
257
|
+
const payload =
|
|
258
|
+
body && typeof body === 'object' && typeof body.error !== 'string' && body.detail
|
|
259
|
+
? body.detail
|
|
260
|
+
: body;
|
|
261
|
+
if (payload && typeof payload === 'object' && typeof payload.error === 'string') {
|
|
262
|
+
return new OAuthError(payload.error, payload.error_description ?? '', status, body);
|
|
263
|
+
}
|
|
264
|
+
return new OAuthError('server_error', 'Unexpected server response', status, body);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
errors = { OAuthError };
|
|
269
|
+
return errors;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
var http;
|
|
273
|
+
var hasRequiredHttp;
|
|
274
|
+
|
|
275
|
+
function requireHttp () {
|
|
276
|
+
if (hasRequiredHttp) return http;
|
|
277
|
+
hasRequiredHttp = 1;
|
|
278
|
+
|
|
279
|
+
const { OAuthError } = requireErrors();
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* @param {string} url
|
|
283
|
+
* @param {Record<string, string>} params
|
|
284
|
+
* @param {Record<string, string>} [headers]
|
|
285
|
+
* @returns {Promise<unknown>}
|
|
286
|
+
*/
|
|
287
|
+
async function postForm(url, params, headers = {}) {
|
|
288
|
+
const body = new URLSearchParams(params).toString();
|
|
289
|
+
const response = await fetch(url, {
|
|
290
|
+
method: 'POST',
|
|
291
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...headers },
|
|
292
|
+
body,
|
|
293
|
+
});
|
|
294
|
+
const json = await response.json();
|
|
295
|
+
if (!response.ok) throw OAuthError.fromResponse(response.status, json);
|
|
296
|
+
return json;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* @param {string} url
|
|
301
|
+
* @param {Record<string, string>} [headers]
|
|
302
|
+
* @returns {Promise<unknown>}
|
|
303
|
+
*/
|
|
304
|
+
async function getJson(url, headers = {}) {
|
|
305
|
+
const response = await fetch(url, { headers });
|
|
306
|
+
const json = await response.json();
|
|
307
|
+
if (!response.ok) throw OAuthError.fromResponse(response.status, json);
|
|
308
|
+
return json;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* @param {string} url
|
|
313
|
+
* @param {object} body
|
|
314
|
+
* @param {Record<string, string>} [headers]
|
|
315
|
+
* @returns {Promise<unknown>}
|
|
316
|
+
*/
|
|
317
|
+
async function postJson(url, body, headers = {}) {
|
|
318
|
+
const response = await fetch(url, {
|
|
319
|
+
method: 'POST',
|
|
320
|
+
headers: { 'Content-Type': 'application/json', ...headers },
|
|
321
|
+
body: JSON.stringify(body),
|
|
322
|
+
});
|
|
323
|
+
const json = await response.json();
|
|
324
|
+
if (!response.ok) throw OAuthError.fromResponse(response.status, json);
|
|
325
|
+
return json;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
http = { postForm, getJson, postJson };
|
|
329
|
+
return http;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
var client;
|
|
333
|
+
var hasRequiredClient;
|
|
334
|
+
|
|
335
|
+
function requireClient () {
|
|
336
|
+
if (hasRequiredClient) return client;
|
|
337
|
+
hasRequiredClient = 1;
|
|
338
|
+
|
|
339
|
+
const { generateCodeVerifier, generateCodeChallenge, generateState } = requirePkce();
|
|
340
|
+
const { postForm, postJson } = requireHttp();
|
|
341
|
+
const { base64urlDecode, utf8Decode } = requireBase64();
|
|
342
|
+
const { OAuthError } = requireErrors();
|
|
343
|
+
|
|
344
|
+
// In-flight dedup key for client_credentials re-mints (no refresh_token to key on).
|
|
345
|
+
const CLIENT_CREDENTIALS_KEY = Symbol('client_credentials');
|
|
346
|
+
|
|
347
|
+
class OAuthClient {
|
|
348
|
+
/**
|
|
349
|
+
* @param {import('./types').OAuthClientConfig} config
|
|
350
|
+
*/
|
|
351
|
+
constructor(config) {
|
|
352
|
+
this._config = config;
|
|
353
|
+
this._inFlightRefreshes = new Map();
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* @param {import('./types').ClientRegistrationRequest} params
|
|
358
|
+
* @returns {Promise<import('./types').ClientRegistrationResponse>}
|
|
359
|
+
*/
|
|
360
|
+
static async registerClient(params) {
|
|
361
|
+
const baseUrl = params.baseUrl.replace(/\/+$/, '');
|
|
362
|
+
const body = {
|
|
363
|
+
client_name: params.clientName,
|
|
364
|
+
client_type: params.clientType,
|
|
365
|
+
redirect_uris: params.redirectUris,
|
|
366
|
+
is_first_party: params.isFirstParty,
|
|
367
|
+
};
|
|
368
|
+
// grant_types/company_id are required to provision a confidential
|
|
369
|
+
// client_credentials (machine-to-machine) client; omitted bodies keep the
|
|
370
|
+
// legacy public/authorization_code shape. The endpoint is admin-gated, so a
|
|
371
|
+
// bearer token must be supplied for the request to authenticate.
|
|
372
|
+
if (params.grantTypes !== undefined) body.grant_types = params.grantTypes;
|
|
373
|
+
if (params.companyId !== undefined) body.company_id = params.companyId;
|
|
374
|
+
const headers = params.accessToken
|
|
375
|
+
? { Authorization: `Bearer ${params.accessToken}` }
|
|
376
|
+
: {};
|
|
377
|
+
return postJson(`${baseUrl}/oauth/clients`, body, headers);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* @param {string} [state]
|
|
382
|
+
* @returns {import('./types').AuthorizationUrlResult}
|
|
383
|
+
*/
|
|
384
|
+
async generateAuthorizationUrl(state) {
|
|
385
|
+
const codeVerifier = generateCodeVerifier();
|
|
386
|
+
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
|
387
|
+
const resolvedState = state ?? generateState();
|
|
388
|
+
|
|
389
|
+
const params = new URLSearchParams({
|
|
390
|
+
response_type: 'code',
|
|
391
|
+
client_id: this._config.clientId,
|
|
392
|
+
redirect_uri: this._config.redirectUri,
|
|
393
|
+
state: resolvedState,
|
|
394
|
+
code_challenge: codeChallenge,
|
|
395
|
+
code_challenge_method: 'S256',
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
return {
|
|
399
|
+
url: `${this._config.baseUrl}/oauth/authorize?${params}`,
|
|
400
|
+
state: resolvedState,
|
|
401
|
+
code_verifier: codeVerifier,
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* @param {string} code
|
|
407
|
+
* @param {string} codeVerifier
|
|
408
|
+
* @param {string} [redirectUri]
|
|
409
|
+
* @returns {Promise<import('./types').TokenResponse>}
|
|
410
|
+
*/
|
|
411
|
+
async exchangeCode(code, codeVerifier, redirectUri) {
|
|
412
|
+
return postForm(`${this._config.baseUrl}/oauth/token`, {
|
|
413
|
+
grant_type: 'authorization_code',
|
|
414
|
+
code,
|
|
415
|
+
code_verifier: codeVerifier,
|
|
416
|
+
redirect_uri: redirectUri ?? this._config.redirectUri,
|
|
417
|
+
...this._clientAuth(),
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* RFC 6749 §4.4 — machine-to-machine token exchange. No user login.
|
|
423
|
+
* Returned TokenResponse has no refresh_token.
|
|
424
|
+
* @returns {Promise<import('./types').TokenResponse>}
|
|
425
|
+
*/
|
|
426
|
+
async getClientCredentialsToken() {
|
|
427
|
+
return postForm(`${this._config.baseUrl}/oauth/token`, {
|
|
428
|
+
grant_type: 'client_credentials',
|
|
429
|
+
...this._clientAuth(),
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* @param {string} refreshToken
|
|
435
|
+
* @returns {Promise<import('./types').TokenResponse>}
|
|
436
|
+
*/
|
|
437
|
+
async refreshAccessToken(refreshToken) {
|
|
438
|
+
return postForm(`${this._config.baseUrl}/oauth/token`, {
|
|
439
|
+
grant_type: 'refresh_token',
|
|
440
|
+
refresh_token: refreshToken,
|
|
441
|
+
...this._clientAuth(),
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* @param {string} token
|
|
447
|
+
* @param {string} [tokenTypeHint]
|
|
448
|
+
* @returns {Promise<void>}
|
|
449
|
+
*/
|
|
450
|
+
async revokeToken(token, tokenTypeHint) {
|
|
451
|
+
const params = { token, ...this._clientAuth() };
|
|
452
|
+
if (tokenTypeHint) params.token_type_hint = tokenTypeHint;
|
|
453
|
+
await postForm(`${this._config.baseUrl}/oauth/revoke`, params);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Makes an authenticated request with 401-intercept-and-retry.
|
|
458
|
+
*
|
|
459
|
+
* `onRefreshSuccess` fires synchronously the moment the rotated tokens are received,
|
|
460
|
+
* BEFORE the retry. The server has already deleted the old refresh token by then;
|
|
461
|
+
* if the retry throws, the new tokens would otherwise be lost in this call frame.
|
|
462
|
+
* Long-lived callers MUST persist via this callback — not from the resolved value —
|
|
463
|
+
* to stay in sync with single-use refresh-token rotation (RFC 6749 §6).
|
|
464
|
+
*
|
|
465
|
+
* @param {string} url
|
|
466
|
+
* @param {string} method
|
|
467
|
+
* @param {string} accessToken
|
|
468
|
+
* @param {string} refreshToken
|
|
469
|
+
* @param {object} [body]
|
|
470
|
+
* @param {(newTokens: import('./types').TokenResponse) => void} [onRefreshSuccess]
|
|
471
|
+
* @returns {Promise<import('./types').AuthenticatedResponse>}
|
|
472
|
+
*/
|
|
473
|
+
async request(url, method, accessToken, refreshToken, body, onRefreshSuccess) {
|
|
474
|
+
const buildOptions = (token) => {
|
|
475
|
+
const headers = { Authorization: `Bearer ${token}` };
|
|
476
|
+
const options = { method, headers };
|
|
477
|
+
if (body != null) {
|
|
478
|
+
headers['Content-Type'] = 'application/json';
|
|
479
|
+
options.body = JSON.stringify(body);
|
|
480
|
+
}
|
|
481
|
+
return options;
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
const firstResponse = await fetch(`${this._config.baseUrl}${url}`, buildOptions(accessToken));
|
|
485
|
+
|
|
486
|
+
if (firstResponse.status !== 401) {
|
|
487
|
+
const json = await firstResponse.json();
|
|
488
|
+
if (!firstResponse.ok) throw OAuthError.fromResponse(firstResponse.status, json);
|
|
489
|
+
return { data: json, updatedTokens: null };
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// 401: re-authenticate, then retry once.
|
|
493
|
+
// - User sessions (refresh_token present) use the refresh_token grant. The server
|
|
494
|
+
// rotates the token one-time, so concurrent callers share one in-flight call
|
|
495
|
+
// (a second rotation would get invalid_grant).
|
|
496
|
+
// - Machine-to-machine sessions (no refresh_token, client_secret configured) re-mint
|
|
497
|
+
// via client_credentials, which issues no refresh token to rotate (RFC 6749 §4.4).
|
|
498
|
+
// - With neither a refresh_token nor a client_secret there is nothing to retry with.
|
|
499
|
+
if (!refreshToken && !this._config.clientSecret) {
|
|
500
|
+
throw OAuthError.fromResponse(401, await firstResponse.json());
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const reauthKey = refreshToken || CLIENT_CREDENTIALS_KEY;
|
|
504
|
+
let pending = this._inFlightRefreshes.get(reauthKey);
|
|
505
|
+
if (!pending) {
|
|
506
|
+
const reauth = refreshToken
|
|
507
|
+
? this.refreshAccessToken(refreshToken)
|
|
508
|
+
: this.getClientCredentialsToken();
|
|
509
|
+
pending = reauth.finally(() => {
|
|
510
|
+
this._inFlightRefreshes.delete(reauthKey);
|
|
511
|
+
});
|
|
512
|
+
this._inFlightRefreshes.set(reauthKey, pending);
|
|
513
|
+
}
|
|
514
|
+
const newTokens = await pending;
|
|
515
|
+
|
|
516
|
+
if (onRefreshSuccess) onRefreshSuccess(newTokens);
|
|
517
|
+
|
|
518
|
+
const retryResponse = await fetch(`${this._config.baseUrl}${url}`, buildOptions(newTokens.access_token));
|
|
519
|
+
const retryJson = await retryResponse.json();
|
|
520
|
+
if (!retryResponse.ok) throw OAuthError.fromResponse(retryResponse.status, retryJson);
|
|
521
|
+
return { data: retryJson, updatedTokens: newTokens };
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Decodes a JWT access token payload without verifying the signature.
|
|
526
|
+
* @param {string} accessToken
|
|
527
|
+
* @returns {import('./types').TokenPayload}
|
|
528
|
+
*/
|
|
529
|
+
decodeAccessToken(accessToken) {
|
|
530
|
+
const segment = accessToken.split('.')[1];
|
|
531
|
+
if (!segment) throw new OAuthError('invalid_token', 'Malformed JWT', 400);
|
|
532
|
+
return JSON.parse(utf8Decode(base64urlDecode(segment)));
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Client-authentication params for a token-endpoint request.
|
|
537
|
+
*
|
|
538
|
+
* A public client (mobile, SPA) holds no secret, and the authorization server
|
|
539
|
+
* rejects the request outright if one is present, so the key is omitted
|
|
540
|
+
* entirely rather than sent empty. Passing it through unconditionally
|
|
541
|
+
* serializes `undefined` into the form body as that literal string.
|
|
542
|
+
* @returns {Record<string, string>}
|
|
543
|
+
*/
|
|
544
|
+
_clientAuth() {
|
|
545
|
+
const params = { client_id: this._config.clientId };
|
|
546
|
+
if (this._config.clientSecret) params.client_secret = this._config.clientSecret;
|
|
547
|
+
return params;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
client = { OAuthClient };
|
|
552
|
+
return client;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* @typedef {Object} OAuthClientConfig
|
|
557
|
+
* @property {string} baseUrl - Base URL of the OAuth server
|
|
558
|
+
* @property {string} clientId - Registered client_id
|
|
559
|
+
* @property {string} clientSecret - Registered client_secret
|
|
560
|
+
* @property {string} redirectUri - Registered redirect URI
|
|
561
|
+
*/
|
|
562
|
+
|
|
563
|
+
var types;
|
|
564
|
+
var hasRequiredTypes;
|
|
565
|
+
|
|
566
|
+
function requireTypes () {
|
|
567
|
+
if (hasRequiredTypes) return types;
|
|
568
|
+
hasRequiredTypes = 1;
|
|
569
|
+
/**
|
|
570
|
+
* @typedef {Object} TokenResponse
|
|
571
|
+
* @property {string} access_token - Signed JWT access token
|
|
572
|
+
* @property {string} token_type - Always "bearer"
|
|
573
|
+
* @property {number} expires_in - Seconds until access token expires
|
|
574
|
+
* @property {string} refresh_token - Opaque refresh token
|
|
575
|
+
*/
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* @typedef {Object} TokenPayload
|
|
579
|
+
* @property {string} user_id - ID of the authenticated user
|
|
580
|
+
* @property {string} client_id - ID of the OAuth client
|
|
581
|
+
* @property {string} jti - Unique token ID
|
|
582
|
+
* @property {number} iat - Issued-at timestamp (Unix seconds)
|
|
583
|
+
* @property {number} exp - Expiry timestamp (Unix seconds)
|
|
584
|
+
*/
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* @typedef {Object} AuthorizationUrlResult
|
|
588
|
+
* @property {string} url - Full authorization URL
|
|
589
|
+
* @property {string} state - CSRF state value; persist between redirect and callback
|
|
590
|
+
* @property {string} code_verifier - PKCE verifier; persist between redirect and callback
|
|
591
|
+
*/
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* @typedef {Object} AuthenticatedResponse
|
|
595
|
+
* @property {Object} data - Parsed JSON response body from resource server
|
|
596
|
+
* @property {TokenResponse|null} updatedTokens - Non-null only when token refresh occurred
|
|
597
|
+
*/
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* @typedef {Object} ClientRegistrationRequest
|
|
601
|
+
* @property {string} baseUrl - Base URL of the OAuth server
|
|
602
|
+
* @property {string} clientName - Human-readable client name
|
|
603
|
+
* @property {string} clientType - "public" or "confidential"
|
|
604
|
+
* @property {string[]} redirectUris - HTTPS redirect URIs
|
|
605
|
+
* @property {boolean} isFirstParty - Whether this is a first-party client
|
|
606
|
+
* @property {string[]} [grantTypes] - Allowed grants, e.g. ["client_credentials"]; required for machine-to-machine clients
|
|
607
|
+
* @property {number} [companyId] - Company to bind the client to; required for the client_credentials grant
|
|
608
|
+
* @property {string} [accessToken] - Admin bearer token; the registration endpoint is authorization-gated
|
|
609
|
+
*/
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* @typedef {Object} ClientRegistrationResponse
|
|
613
|
+
* @property {string} client_id - Assigned client ID
|
|
614
|
+
* @property {string} client_name - Registered client name
|
|
615
|
+
* @property {string} client_type - "public" or "confidential"
|
|
616
|
+
* @property {string[]} redirect_uris - Registered redirect URIs
|
|
617
|
+
* @property {string} [client_secret] - Only present for confidential clients
|
|
618
|
+
*/
|
|
619
|
+
|
|
620
|
+
const OAuthErrorCode = Object.freeze({
|
|
621
|
+
INVALID_REQUEST: 'invalid_request',
|
|
622
|
+
INVALID_CLIENT: 'invalid_client',
|
|
623
|
+
INVALID_GRANT: 'invalid_grant',
|
|
624
|
+
UNAUTHORIZED_CLIENT: 'unauthorized_client',
|
|
625
|
+
UNSUPPORTED_GRANT_TYPE: 'unsupported_grant_type',
|
|
626
|
+
ACCESS_DENIED: 'access_denied',
|
|
627
|
+
SERVER_ERROR: 'server_error',
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
types = { OAuthErrorCode };
|
|
631
|
+
return types;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
var src$2;
|
|
635
|
+
var hasRequiredSrc$2;
|
|
636
|
+
|
|
637
|
+
function requireSrc$2 () {
|
|
638
|
+
if (hasRequiredSrc$2) return src$2;
|
|
639
|
+
hasRequiredSrc$2 = 1;
|
|
640
|
+
|
|
641
|
+
const { OAuthClient } = requireClient();
|
|
642
|
+
const { OAuthError } = requireErrors();
|
|
643
|
+
const { OAuthErrorCode } = requireTypes();
|
|
644
|
+
const { configureCrypto } = requireCrypto$1();
|
|
645
|
+
|
|
646
|
+
src$2 = { OAuthClient, OAuthError, OAuthErrorCode, configureCrypto };
|
|
647
|
+
return src$2;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
var srcExports$2 = requireSrc$2();
|
|
651
|
+
var _oauth = /*@__PURE__*/getDefaultExportFromCjs(srcExports$2);
|
|
652
|
+
|
|
653
|
+
// Auto-generated — do not edit
|
|
654
|
+
const { OAuthClient, OAuthError, OAuthErrorCode, configureCrypto } = _oauth;
|
|
655
|
+
|
|
656
|
+
var signing;
|
|
657
|
+
var hasRequiredSigning;
|
|
658
|
+
|
|
659
|
+
function requireSigning () {
|
|
660
|
+
if (hasRequiredSigning) return signing;
|
|
661
|
+
hasRequiredSigning = 1;
|
|
662
|
+
|
|
663
|
+
// HMAC scheme shared with the MediaViz producer: X-Signature = 'sha256=' +
|
|
664
|
+
// hex(HMAC-SHA256(secret, `${X-Timestamp}.` + rawBody)). The signing string is
|
|
665
|
+
// the timestamp joined to the *raw request body bytes* — never re-serialized
|
|
666
|
+
// JSON. Verification accepts the current and (during rotation) previous
|
|
667
|
+
// secret, rejects timestamps outside the skew window, and compares digests in
|
|
668
|
+
// constant time. Web Crypto only, so the same code runs in Node >= 18 and
|
|
669
|
+
// browsers.
|
|
670
|
+
|
|
671
|
+
// Built on first use, not at import. These functions are a server-side concern
|
|
672
|
+
// (only the endpoint receiving a push verifies a signature), but the module is
|
|
673
|
+
// bundled into every SDK including React Native — and constructing this at
|
|
674
|
+
// module scope made merely importing the SDK crash on any runtime without a
|
|
675
|
+
// TextEncoder global.
|
|
676
|
+
let _encoderInstance = null;
|
|
677
|
+
function _encode(text) {
|
|
678
|
+
if (!_encoderInstance) _encoderInstance = new TextEncoder();
|
|
679
|
+
return _encoderInstance.encode(text);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
async function signWebhookPayload(secret, timestamp, rawBody) {
|
|
683
|
+
const key = await globalThis.crypto.subtle.importKey(
|
|
684
|
+
'raw', _encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
685
|
+
const payload = _concat(_encode(`${timestamp}.`), toBytes(rawBody));
|
|
686
|
+
const digest = await globalThis.crypto.subtle.sign('HMAC', key, payload);
|
|
687
|
+
return 'sha256=' + _hex(new Uint8Array(digest));
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
async function verifyWebhookSignature(secretCurrent, secretPrevious, headers, rawBody, options = {}) {
|
|
691
|
+
const h = lowerHeaders(headers);
|
|
692
|
+
const timestamp = h['x-timestamp'];
|
|
693
|
+
const signature = h['x-signature'];
|
|
694
|
+
if (!timestamp || !signature) return false;
|
|
695
|
+
if (!/^-?\d+$/.test(String(timestamp))) return false;
|
|
696
|
+
const skewToleranceS = options.skewToleranceS ?? 300;
|
|
697
|
+
const now = options.now ?? Math.floor(Date.now() / 1000);
|
|
698
|
+
if (Math.abs(now - Number(timestamp)) > skewToleranceS) return false;
|
|
699
|
+
for (const secret of [secretCurrent, secretPrevious]) {
|
|
700
|
+
if (!secret) continue;
|
|
701
|
+
const expected = await signWebhookPayload(secret, String(timestamp), rawBody);
|
|
702
|
+
if (_constantTimeEqual(expected, String(signature))) return true;
|
|
703
|
+
}
|
|
704
|
+
return false;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// helpers
|
|
708
|
+
function toBytes(rawBody) {
|
|
709
|
+
if (typeof rawBody === 'string') return _encode(rawBody);
|
|
710
|
+
if (rawBody instanceof Uint8Array) return rawBody;
|
|
711
|
+
if (rawBody instanceof ArrayBuffer) return new Uint8Array(rawBody);
|
|
712
|
+
throw new TypeError('rawBody must be a string, Uint8Array, or ArrayBuffer');
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
function lowerHeaders(headers) {
|
|
716
|
+
const out = {};
|
|
717
|
+
const entries = typeof headers?.entries === 'function' ? headers.entries() : Object.entries(headers ?? {});
|
|
718
|
+
for (const [k, v] of entries) out[String(k).toLowerCase()] = v;
|
|
719
|
+
return out;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function _concat(a, b) {
|
|
723
|
+
const out = new Uint8Array(a.length + b.length);
|
|
724
|
+
out.set(a, 0);
|
|
725
|
+
out.set(b, a.length);
|
|
726
|
+
return out;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function _hex(bytes) {
|
|
730
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function _constantTimeEqual(a, b) {
|
|
734
|
+
if (a.length !== b.length) return false;
|
|
735
|
+
let diff = 0;
|
|
736
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
737
|
+
return diff === 0;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
signing = { signWebhookPayload, verifyWebhookSignature, toBytes, lowerHeaders };
|
|
741
|
+
return signing;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
var store;
|
|
745
|
+
var hasRequiredStore;
|
|
746
|
+
|
|
747
|
+
function requireStore () {
|
|
748
|
+
if (hasRequiredStore) return store;
|
|
749
|
+
hasRequiredStore = 1;
|
|
750
|
+
|
|
751
|
+
// Persistence seam for the webhook consumer: dedupe ledger, signing secrets,
|
|
752
|
+
// and pull cursors. The default in-memory store suits a single long-lived
|
|
753
|
+
// process (worker, dev server); multi-process consumers supply an object with
|
|
754
|
+
// the same shape backed by Redis or a database.
|
|
755
|
+
|
|
756
|
+
const MAX_SEEN_ENTRIES = 100000;
|
|
757
|
+
|
|
758
|
+
class InMemoryWebhookStore {
|
|
759
|
+
constructor() {
|
|
760
|
+
this._seen = new Map(); // eventId -> expiresAt (ms)
|
|
761
|
+
this._secrets = new Map(); // subscriptionId -> {current, previous, previousExpiresAt}
|
|
762
|
+
this._cursors = new Map(); // subscriptionId -> cursor
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
markSeen(eventId, ttlS) {
|
|
766
|
+
const now = Date.now();
|
|
767
|
+
const expiresAt = this._seen.get(eventId);
|
|
768
|
+
if (expiresAt !== undefined && expiresAt > now) return false;
|
|
769
|
+
this._seen.delete(eventId);
|
|
770
|
+
this._seen.set(eventId, now + ttlS * 1000);
|
|
771
|
+
this._prune(now);
|
|
772
|
+
return true;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
unmarkSeen(eventId) {
|
|
776
|
+
this._seen.delete(eventId);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
saveSecret(subscriptionId, secret) {
|
|
780
|
+
this._secrets.set(subscriptionId, { current: secret, previous: null, previousExpiresAt: 0 });
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
rotateSecret(subscriptionId, newSecret, windowS) {
|
|
784
|
+
const entry = this._secrets.get(subscriptionId);
|
|
785
|
+
this._secrets.set(subscriptionId, {
|
|
786
|
+
current: newSecret,
|
|
787
|
+
previous: entry?.current ?? null,
|
|
788
|
+
previousExpiresAt: Date.now() + windowS * 1000,
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
getSecrets(subscriptionId) {
|
|
793
|
+
const entry = this._secrets.get(subscriptionId);
|
|
794
|
+
if (!entry) return [null, null];
|
|
795
|
+
const previous = entry.previous && entry.previousExpiresAt > Date.now() ? entry.previous : null;
|
|
796
|
+
return [entry.current, previous];
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
getCursor(subscriptionId) {
|
|
800
|
+
return this._cursors.get(subscriptionId) ?? null;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
setCursor(subscriptionId, cursor) {
|
|
804
|
+
this._cursors.set(subscriptionId, cursor);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
_prune(now) {
|
|
808
|
+
if (this._seen.size <= MAX_SEEN_ENTRIES) return;
|
|
809
|
+
for (const [id, expiresAt] of this._seen) {
|
|
810
|
+
if (expiresAt <= now) this._seen.delete(id);
|
|
811
|
+
if (this._seen.size <= MAX_SEEN_ENTRIES) return;
|
|
812
|
+
}
|
|
813
|
+
// still over the cap: evict oldest insertions
|
|
814
|
+
for (const id of this._seen.keys()) {
|
|
815
|
+
this._seen.delete(id);
|
|
816
|
+
if (this._seen.size <= MAX_SEEN_ENTRIES) return;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
store = { InMemoryWebhookStore };
|
|
822
|
+
return store;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
var consumer;
|
|
826
|
+
var hasRequiredConsumer;
|
|
827
|
+
|
|
828
|
+
function requireConsumer () {
|
|
829
|
+
if (hasRequiredConsumer) return consumer;
|
|
830
|
+
hasRequiredConsumer = 1;
|
|
831
|
+
|
|
832
|
+
const { verifyWebhookSignature, toBytes, lowerHeaders } = requireSigning();
|
|
833
|
+
const { InMemoryWebhookStore } = requireStore();
|
|
834
|
+
|
|
835
|
+
// Photo columns each producer model writes — used to select a model's results
|
|
836
|
+
// out of a fetched PhotoDisplay. Mirrors the producer vocabulary; personhood is
|
|
837
|
+
// predicate-based and writes no columns.
|
|
838
|
+
const WEBHOOK_MODEL_COLUMNS = {
|
|
839
|
+
blur: ['blur_value'],
|
|
840
|
+
colors: ['main_color_palette', 'color_averages', 'hue_values', 'light_values', 'saturation_values'],
|
|
841
|
+
face_recognition: ['number_of_faces', 'bounding_boxes_from_faces_model'],
|
|
842
|
+
image_classification: ['labels_from_classifications_model', 'feature_extraction_output'],
|
|
843
|
+
image_comparison: ['average_hash'],
|
|
844
|
+
image_describe: ['topic'],
|
|
845
|
+
ocr: ['ocr_output'],
|
|
846
|
+
similarity: ['similar_photo_ids_high', 'similar_photo_ids_medium', 'similar_photo_ids_low'],
|
|
847
|
+
evidence: ['evidence_score', 'aesthetic_score', 'face_score', 'content_score', 'similarity_set_ranking'],
|
|
848
|
+
personhood: [],
|
|
849
|
+
};
|
|
850
|
+
|
|
851
|
+
const WEBHOOK_OUTCOME_MODELS = {
|
|
852
|
+
curation: ['blur', 'colors', 'face_recognition', 'image_classification', 'image_comparison', 'similarity', 'evidence'],
|
|
853
|
+
similarity: ['image_classification', 'image_comparison', 'similarity'],
|
|
854
|
+
persons: ['face_recognition', 'personhood'],
|
|
855
|
+
};
|
|
856
|
+
|
|
857
|
+
// Client-side counterpart of the MediaViz webhook producer, giving photo-by-photo
|
|
858
|
+
// progress as a project upload is analyzed.
|
|
859
|
+
//
|
|
860
|
+
// Receiver half (no auth needed): classify inbound POSTs, echo the subscription
|
|
861
|
+
// verification challenge, verify signed `target.completed` deliveries (HMAC +
|
|
862
|
+
// timestamp skew), dedupe on event_id, and dispatch each new event to a single
|
|
863
|
+
// onEvent callback. `handleRequest` is framework-agnostic glue — adapt it to
|
|
864
|
+
// express/lambda/etc. in a few lines by feeding it the raw body and headers.
|
|
865
|
+
//
|
|
866
|
+
// API half (requires an authenticated client): subscription lifecycle
|
|
867
|
+
// orchestration — register/confirm/rotate store the signing secret the moment
|
|
868
|
+
// the producer issues it — plus history pulls that share the push dedupe
|
|
869
|
+
// ledger, and out-of-band result fetches (webhooks carry a pointer, never the
|
|
870
|
+
// result itself).
|
|
871
|
+
class WebhookConsumer {
|
|
872
|
+
constructor(ctx, subscriptionApi, options = {}) {
|
|
873
|
+
this._ctx = ctx;
|
|
874
|
+
this._api = subscriptionApi;
|
|
875
|
+
this.store = options.store ?? new InMemoryWebhookStore();
|
|
876
|
+
this.skewToleranceS = options.skewToleranceS ?? 300;
|
|
877
|
+
this.rotationWindowS = options.rotationWindowS ?? 86400;
|
|
878
|
+
this.dedupeTtlS = options.dedupeTtlS ?? 604800;
|
|
879
|
+
this.pageLimit = options.pageLimit ?? 100;
|
|
880
|
+
this._onEvent = options.onEvent ?? null;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
// ── receiver half ─────────────────────────────────────────────────────────
|
|
884
|
+
|
|
885
|
+
onEvent(fn) {
|
|
886
|
+
this._onEvent = fn;
|
|
887
|
+
return fn;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
useStore(store) {
|
|
891
|
+
this.store = store;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
classifyMessage(body) {
|
|
895
|
+
const type = body?.event_type;
|
|
896
|
+
if (type === 'subscription.verification') return 'verification';
|
|
897
|
+
if (type === 'target.completed') return 'delivery';
|
|
898
|
+
return 'unknown';
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
handleChallenge(body) {
|
|
902
|
+
return { challenge: body.challenge };
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
async handleDelivery(headers, rawBody) {
|
|
906
|
+
let event;
|
|
907
|
+
try {
|
|
908
|
+
event = this._parseDelivery(rawBody);
|
|
909
|
+
} catch {
|
|
910
|
+
return 'bad_signature';
|
|
911
|
+
}
|
|
912
|
+
const [current, previous] = this.store.getSecrets(String(event.subscription_id));
|
|
913
|
+
const ok = await verifyWebhookSignature(current, previous, headers, rawBody, { skewToleranceS: this.skewToleranceS });
|
|
914
|
+
if (!ok) return 'bad_signature';
|
|
915
|
+
return this._dispatch(event);
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
async handleRequest(headers, rawBody) {
|
|
919
|
+
let body;
|
|
920
|
+
try {
|
|
921
|
+
body = JSON.parse(_text(rawBody));
|
|
922
|
+
} catch {
|
|
923
|
+
return { status: 400, body: { detail: 'invalid JSON' } };
|
|
924
|
+
}
|
|
925
|
+
switch (this.classifyMessage(body)) {
|
|
926
|
+
case 'verification':
|
|
927
|
+
return { status: 200, body: this.handleChallenge(body) };
|
|
928
|
+
case 'delivery': {
|
|
929
|
+
const ack = await this.handleDelivery(lowerHeaders(headers), rawBody);
|
|
930
|
+
if (ack === 'bad_signature') return { status: 401, body: { detail: 'bad signature' } };
|
|
931
|
+
return { status: 200, body: { status: ack } };
|
|
932
|
+
}
|
|
933
|
+
default:
|
|
934
|
+
return { status: 400, body: { detail: 'unrecognized event_type' } };
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
// ── API half ──────────────────────────────────────────────────────────────
|
|
939
|
+
|
|
940
|
+
async register(projectTableName, callbackUrl, targets) {
|
|
941
|
+
const res = await this._api.createSubscription(projectTableName, callbackUrl, targets);
|
|
942
|
+
this._saveSecretFrom(res);
|
|
943
|
+
return res;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
async confirm(subscriptionId) {
|
|
947
|
+
const res = await this._api.verifySubscription(subscriptionId);
|
|
948
|
+
this._saveSecretFrom(res);
|
|
949
|
+
return res;
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
async rotateSecret(subscriptionId) {
|
|
953
|
+
const res = await this._api.rotateSubscriptionSecret(subscriptionId);
|
|
954
|
+
this.store.rotateSecret(String(subscriptionId), res.signing_secret, this.rotationWindowS);
|
|
955
|
+
return res.signing_secret;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
async updateCallback(subscriptionId, callbackUrl) {
|
|
959
|
+
// A callback change resets the subscription to pending_verification and
|
|
960
|
+
// pauses push until the new URL passes the challenge — confirm right away.
|
|
961
|
+
await this._api.updateSubscription(subscriptionId, { callbackUrl });
|
|
962
|
+
return this.confirm(subscriptionId);
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
async disable(subscriptionId) {
|
|
966
|
+
return this._api.deleteSubscription(subscriptionId);
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
async listSubscriptions() {
|
|
970
|
+
return this._api.listSubscriptions();
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
async pullEvents(subscriptionId, { since, limit } = {}) {
|
|
974
|
+
return this._api.listSubscriptionEvents(subscriptionId, { since, limit: limit ?? this.pageLimit });
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
async reconcile(subscriptionId, projectTableName) {
|
|
978
|
+
const id = String(subscriptionId);
|
|
979
|
+
let cursor = this.store.getCursor(id);
|
|
980
|
+
let pulled = 0;
|
|
981
|
+
let dispatched = 0;
|
|
982
|
+
for (;;) {
|
|
983
|
+
const page = await this._api.listSubscriptionEvents(id, { since: cursor ?? undefined, limit: this.pageLimit });
|
|
984
|
+
const events = page?.events ?? [];
|
|
985
|
+
pulled += events.length;
|
|
986
|
+
for (const ev of events) {
|
|
987
|
+
const ack = await this._dispatch({
|
|
988
|
+
event_id: ev.event_id,
|
|
989
|
+
event_type: 'target.completed',
|
|
990
|
+
schema_version: '1',
|
|
991
|
+
subscription_id: id,
|
|
992
|
+
project_table_name: projectTableName,
|
|
993
|
+
photo_id: ev.photo_id,
|
|
994
|
+
target: ev.target,
|
|
995
|
+
completed_at: ev.completed_at,
|
|
996
|
+
result_location: this._ctx.baseUrl + _photoPath(projectTableName, ev.photo_id),
|
|
997
|
+
});
|
|
998
|
+
if (ack === 'handled') dispatched += 1;
|
|
999
|
+
}
|
|
1000
|
+
if (page?.next_cursor && page.next_cursor !== cursor) {
|
|
1001
|
+
cursor = page.next_cursor;
|
|
1002
|
+
this.store.setCursor(id, cursor);
|
|
1003
|
+
}
|
|
1004
|
+
if (!events.length || events.length < this.pageLimit) break;
|
|
1005
|
+
}
|
|
1006
|
+
return { pulled, dispatched };
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
async fetchResult(event) {
|
|
1010
|
+
this._ctx.requireTokens();
|
|
1011
|
+
const path = _photoPath(event.project_table_name, event.photo_id);
|
|
1012
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1013
|
+
return { photo: data, selected: selectResultColumns(data, event.target) };
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
saveSecret(subscriptionId, secret) {
|
|
1017
|
+
this.store.saveSecret(String(subscriptionId), secret);
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
// ── internal ──────────────────────────────────────────────────────────────
|
|
1021
|
+
|
|
1022
|
+
_saveSecretFrom(res) {
|
|
1023
|
+
if (res?.signing_secret && res?.subscription_id != null) {
|
|
1024
|
+
this.store.saveSecret(String(res.subscription_id), res.signing_secret);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
_parseDelivery(rawBody) {
|
|
1029
|
+
const event = JSON.parse(_text(rawBody));
|
|
1030
|
+
for (const key of ['event_id', 'subscription_id', 'target']) {
|
|
1031
|
+
if (typeof event?.[key] !== 'string' || !event[key]) throw new Error(`missing ${key}`);
|
|
1032
|
+
}
|
|
1033
|
+
if (!Number.isInteger(event.photo_id)) throw new Error('photo_id must be an integer');
|
|
1034
|
+
return event;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
async _dispatch(event) {
|
|
1038
|
+
if (!this.store.markSeen(String(event.event_id), this.dedupeTtlS)) return 'duplicate';
|
|
1039
|
+
if (this._onEvent) {
|
|
1040
|
+
try {
|
|
1041
|
+
await this._onEvent(event);
|
|
1042
|
+
} catch (e) {
|
|
1043
|
+
// release the dedupe claim so the producer's retry redelivers
|
|
1044
|
+
this.store.unmarkSeen(String(event.event_id));
|
|
1045
|
+
throw e;
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
return 'handled';
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// helpers
|
|
1053
|
+
function selectResultColumns(photo, target) {
|
|
1054
|
+
if (target === 'all') return null;
|
|
1055
|
+
const sep = String(target).indexOf(':');
|
|
1056
|
+
const kind = sep === -1 ? String(target) : String(target).slice(0, sep);
|
|
1057
|
+
const name = sep === -1 ? '' : String(target).slice(sep + 1);
|
|
1058
|
+
let columns;
|
|
1059
|
+
if (kind === 'model') {
|
|
1060
|
+
columns = WEBHOOK_MODEL_COLUMNS[name];
|
|
1061
|
+
if (!columns) throw new Error(`unknown model '${name}'`);
|
|
1062
|
+
} else if (kind === 'outcome') {
|
|
1063
|
+
const models = WEBHOOK_OUTCOME_MODELS[name];
|
|
1064
|
+
if (!models) throw new Error(`unknown outcome '${name}'`);
|
|
1065
|
+
columns = [...new Set(models.flatMap((m) => WEBHOOK_MODEL_COLUMNS[m]))];
|
|
1066
|
+
} else {
|
|
1067
|
+
throw new Error(`unknown target grammar '${target}' (expected 'model:<name>', 'outcome:<name>', or 'all')`);
|
|
1068
|
+
}
|
|
1069
|
+
const selected = {};
|
|
1070
|
+
for (const c of columns) selected[c] = photo?.[c] ?? null;
|
|
1071
|
+
return selected;
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
function _photoPath(projectTableName, photoId) {
|
|
1075
|
+
return `/api/v1/photos/${encodeURIComponent(projectTableName)}/${encodeURIComponent(String(photoId))}`;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
function _text(rawBody) {
|
|
1079
|
+
return typeof rawBody === 'string' ? rawBody : new TextDecoder().decode(toBytes(rawBody));
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
consumer = { WebhookConsumer, selectResultColumns, WEBHOOK_MODEL_COLUMNS, WEBHOOK_OUTCOME_MODELS };
|
|
1083
|
+
return consumer;
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
var src$1;
|
|
1087
|
+
var hasRequiredSrc$1;
|
|
1088
|
+
|
|
1089
|
+
function requireSrc$1 () {
|
|
1090
|
+
if (hasRequiredSrc$1) return src$1;
|
|
1091
|
+
hasRequiredSrc$1 = 1;
|
|
1092
|
+
|
|
1093
|
+
const { WebhookConsumer, selectResultColumns, WEBHOOK_MODEL_COLUMNS, WEBHOOK_OUTCOME_MODELS } = requireConsumer();
|
|
1094
|
+
const { InMemoryWebhookStore } = requireStore();
|
|
1095
|
+
const { signWebhookPayload, verifyWebhookSignature } = requireSigning();
|
|
1096
|
+
|
|
1097
|
+
src$1 = { WebhookConsumer, InMemoryWebhookStore, signWebhookPayload, verifyWebhookSignature, selectResultColumns, WEBHOOK_MODEL_COLUMNS, WEBHOOK_OUTCOME_MODELS };
|
|
1098
|
+
return src$1;
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
var srcExports$1 = requireSrc$1();
|
|
1102
|
+
var _webhooks = /*@__PURE__*/getDefaultExportFromCjs(srcExports$1);
|
|
1103
|
+
|
|
1104
|
+
// Auto-generated — do not edit
|
|
1105
|
+
const { WebhookConsumer, InMemoryWebhookStore, signWebhookPayload, verifyWebhookSignature, selectResultColumns, WEBHOOK_MODEL_COLUMNS, WEBHOOK_OUTCOME_MODELS } = _webhooks;
|
|
1106
|
+
|
|
1107
|
+
class AiModelCredits {
|
|
1108
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1109
|
+
|
|
1110
|
+
async getModelCreditRelationship(modelName) {
|
|
1111
|
+
this._ctx.requireTokens();
|
|
1112
|
+
const path = `/api/v1/model_credit/${encodeURIComponent(modelName)}`;
|
|
1113
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1114
|
+
return data;
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
class Admin {
|
|
1119
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1120
|
+
|
|
1121
|
+
async getCategoryLabels(category) {
|
|
1122
|
+
this._ctx.requireTokens();
|
|
1123
|
+
const path = `/api/v1/admin/category_labels/${encodeURIComponent(category)}`;
|
|
1124
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1125
|
+
return data;
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
class Company {
|
|
1130
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1131
|
+
|
|
1132
|
+
async getCompanyById(companyId) {
|
|
1133
|
+
this._ctx.requireTokens();
|
|
1134
|
+
const path = `/api/v1/company/${encodeURIComponent(companyId)}`;
|
|
1135
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1136
|
+
return data;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
async confirmCompanyCreditBalance(companyId, { photoCount, modelsList } = {}) {
|
|
1140
|
+
this._ctx.requireTokens();
|
|
1141
|
+
let path = `/api/v1/company/credit_balance/${encodeURIComponent(companyId)}`;
|
|
1142
|
+
const query = new URLSearchParams();
|
|
1143
|
+
if (photoCount !== undefined) (Array.isArray(photoCount) ? photoCount : [photoCount]).forEach(v => query.append('photo_count', v));
|
|
1144
|
+
if (modelsList !== undefined) (Array.isArray(modelsList) ? modelsList : [modelsList]).forEach(v => query.append('models_list', v));
|
|
1145
|
+
const qs = query.toString();
|
|
1146
|
+
if (qs) path += '?' + qs;
|
|
1147
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1148
|
+
return data;
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
function stripUndef$8(o) { const r = {}; for (const k in o) if (o[k] !== undefined) r[k] = o[k]; return r; }
|
|
1153
|
+
|
|
1154
|
+
class CuratedAlbums {
|
|
1155
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1156
|
+
|
|
1157
|
+
async createCuratedAlbum(projectTableName, name, description = undefined, confidenceValue = undefined) {
|
|
1158
|
+
this._ctx.requireTokens();
|
|
1159
|
+
const path = `/api/v1/curated_album/project/${encodeURIComponent(projectTableName)}`;
|
|
1160
|
+
const body = stripUndef$8({
|
|
1161
|
+
name: name,
|
|
1162
|
+
description: description,
|
|
1163
|
+
confidence_value: confidenceValue,
|
|
1164
|
+
});
|
|
1165
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
1166
|
+
return data;
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
async getAllProjectCuratedAlbums(projectTableName) {
|
|
1170
|
+
this._ctx.requireTokens();
|
|
1171
|
+
const path = `/api/v1/curated_album/project/${encodeURIComponent(projectTableName)}`;
|
|
1172
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1173
|
+
return data;
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
async getCuratedAlbumPhotos(albumId, { ascOrDesc, lastId, limit, confidenceValue } = {}) {
|
|
1177
|
+
this._ctx.requireTokens();
|
|
1178
|
+
let path = `/api/v1/curated_album/photos/${encodeURIComponent(albumId)}/`;
|
|
1179
|
+
const query = new URLSearchParams();
|
|
1180
|
+
if (ascOrDesc !== undefined) (Array.isArray(ascOrDesc) ? ascOrDesc : [ascOrDesc]).forEach(v => query.append('asc_or_desc', v));
|
|
1181
|
+
if (lastId !== undefined) (Array.isArray(lastId) ? lastId : [lastId]).forEach(v => query.append('last_id', v));
|
|
1182
|
+
if (limit !== undefined) (Array.isArray(limit) ? limit : [limit]).forEach(v => query.append('limit', v));
|
|
1183
|
+
if (confidenceValue !== undefined) (Array.isArray(confidenceValue) ? confidenceValue : [confidenceValue]).forEach(v => query.append('confidence_value', v));
|
|
1184
|
+
const qs = query.toString();
|
|
1185
|
+
if (qs) path += '?' + qs;
|
|
1186
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1187
|
+
return data;
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
async getCuratedAlbumPhotosRanked(albumId, { ascOrDesc, lastId, limit, confidenceValue } = {}) {
|
|
1191
|
+
this._ctx.requireTokens();
|
|
1192
|
+
let path = `/api/v1/curated_album/photos/ranked/${encodeURIComponent(albumId)}/`;
|
|
1193
|
+
const query = new URLSearchParams();
|
|
1194
|
+
if (ascOrDesc !== undefined) (Array.isArray(ascOrDesc) ? ascOrDesc : [ascOrDesc]).forEach(v => query.append('asc_or_desc', v));
|
|
1195
|
+
if (lastId !== undefined) (Array.isArray(lastId) ? lastId : [lastId]).forEach(v => query.append('last_id', v));
|
|
1196
|
+
if (limit !== undefined) (Array.isArray(limit) ? limit : [limit]).forEach(v => query.append('limit', v));
|
|
1197
|
+
if (confidenceValue !== undefined) (Array.isArray(confidenceValue) ? confidenceValue : [confidenceValue]).forEach(v => query.append('confidence_value', v));
|
|
1198
|
+
const qs = query.toString();
|
|
1199
|
+
if (qs) path += '?' + qs;
|
|
1200
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1201
|
+
return data;
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
async getCuratedAlbumById(albumId) {
|
|
1205
|
+
this._ctx.requireTokens();
|
|
1206
|
+
const path = `/api/v1/curated_album/${encodeURIComponent(albumId)}`;
|
|
1207
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1208
|
+
return data;
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
async updateCuratedAlbum(albumId, { name, description, confidenceValue } = {}) {
|
|
1212
|
+
this._ctx.requireTokens();
|
|
1213
|
+
const path = `/api/v1/curated_album/${encodeURIComponent(albumId)}`;
|
|
1214
|
+
const body = stripUndef$8({
|
|
1215
|
+
name: name,
|
|
1216
|
+
description: description,
|
|
1217
|
+
confidence_value: confidenceValue,
|
|
1218
|
+
});
|
|
1219
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
1220
|
+
return data;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
async deleteCuratedAlbum(albumId) {
|
|
1224
|
+
this._ctx.requireTokens();
|
|
1225
|
+
const path = `/api/v1/curated_album/${encodeURIComponent(albumId)}`;
|
|
1226
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1227
|
+
return data;
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
async convertCuratedAlbumToCustom(albumId) {
|
|
1231
|
+
this._ctx.requireTokens();
|
|
1232
|
+
const path = `/api/v1/curated_album/${encodeURIComponent(albumId)}/convert`;
|
|
1233
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1234
|
+
return data;
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
function stripUndef$7(o) { const r = {}; for (const k in o) if (o[k] !== undefined) r[k] = o[k]; return r; }
|
|
1239
|
+
|
|
1240
|
+
class CustomAlbums {
|
|
1241
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1242
|
+
|
|
1243
|
+
async getCustomAlbumDetailById(customAlbumId) {
|
|
1244
|
+
this._ctx.requireTokens();
|
|
1245
|
+
const path = `/api/v1/custom_album/${encodeURIComponent(customAlbumId)}`;
|
|
1246
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1247
|
+
return data;
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
async getAllProjectCustomAlbums(projectTableName) {
|
|
1251
|
+
this._ctx.requireTokens();
|
|
1252
|
+
const path = `/api/v1/custom_album/project/${encodeURIComponent(projectTableName)}`;
|
|
1253
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1254
|
+
return data;
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
async getCustomAlbumPhotosById(customAlbumId, { ascOrDesc, lastId, limit } = {}) {
|
|
1258
|
+
this._ctx.requireTokens();
|
|
1259
|
+
let path = `/api/v1/custom_album/photos/${encodeURIComponent(customAlbumId)}/`;
|
|
1260
|
+
const query = new URLSearchParams();
|
|
1261
|
+
if (ascOrDesc !== undefined) (Array.isArray(ascOrDesc) ? ascOrDesc : [ascOrDesc]).forEach(v => query.append('asc_or_desc', v));
|
|
1262
|
+
if (lastId !== undefined) (Array.isArray(lastId) ? lastId : [lastId]).forEach(v => query.append('last_id', v));
|
|
1263
|
+
if (limit !== undefined) (Array.isArray(limit) ? limit : [limit]).forEach(v => query.append('limit', v));
|
|
1264
|
+
const qs = query.toString();
|
|
1265
|
+
if (qs) path += '?' + qs;
|
|
1266
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1267
|
+
return data;
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
async getRankedCustomAlbumById(customAlbumId, { ascOrDesc, lastId, limit } = {}) {
|
|
1271
|
+
this._ctx.requireTokens();
|
|
1272
|
+
let path = `/api/v1/custom_album/photos/ranked/${encodeURIComponent(customAlbumId)}/`;
|
|
1273
|
+
const query = new URLSearchParams();
|
|
1274
|
+
if (ascOrDesc !== undefined) (Array.isArray(ascOrDesc) ? ascOrDesc : [ascOrDesc]).forEach(v => query.append('asc_or_desc', v));
|
|
1275
|
+
if (lastId !== undefined) (Array.isArray(lastId) ? lastId : [lastId]).forEach(v => query.append('last_id', v));
|
|
1276
|
+
if (limit !== undefined) (Array.isArray(limit) ? limit : [limit]).forEach(v => query.append('limit', v));
|
|
1277
|
+
const qs = query.toString();
|
|
1278
|
+
if (qs) path += '?' + qs;
|
|
1279
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1280
|
+
return data;
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
async createProjectCustomAlbum(projectTableName, { name, description, photoIdInclusionList, photoIdRemovalList } = {}) {
|
|
1284
|
+
this._ctx.requireTokens();
|
|
1285
|
+
const path = `/api/v1/custom_album/project/${encodeURIComponent(projectTableName)}`;
|
|
1286
|
+
const body = stripUndef$7({
|
|
1287
|
+
name: name,
|
|
1288
|
+
description: description,
|
|
1289
|
+
photo_id_inclusion_list: photoIdInclusionList,
|
|
1290
|
+
photo_id_removal_list: photoIdRemovalList,
|
|
1291
|
+
});
|
|
1292
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
1293
|
+
return data;
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
async updateCustomAlbum(albumId, { name, description, photoIdInclusionList, photoIdRemovalList } = {}) {
|
|
1297
|
+
this._ctx.requireTokens();
|
|
1298
|
+
const path = `/api/v1/custom_album/${encodeURIComponent(albumId)}`;
|
|
1299
|
+
const body = stripUndef$7({
|
|
1300
|
+
name: name,
|
|
1301
|
+
description: description,
|
|
1302
|
+
photo_id_inclusion_list: photoIdInclusionList,
|
|
1303
|
+
photo_id_removal_list: photoIdRemovalList,
|
|
1304
|
+
});
|
|
1305
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
1306
|
+
return data;
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
async deleteCustomAlbum(albumId) {
|
|
1310
|
+
this._ctx.requireTokens();
|
|
1311
|
+
const path = `/api/v1/custom_album/${encodeURIComponent(albumId)}`;
|
|
1312
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1313
|
+
return data;
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
// Auto-generated — do not edit
|
|
1318
|
+
|
|
1319
|
+
class ApiError extends Error {
|
|
1320
|
+
constructor(message, status, requestId, body) {
|
|
1321
|
+
super(message);
|
|
1322
|
+
this.name = 'ApiError';
|
|
1323
|
+
this.status = status;
|
|
1324
|
+
this.requestId = requestId;
|
|
1325
|
+
this.body = body;
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
class ValidationError extends ApiError {
|
|
1330
|
+
constructor(body, status, requestId) {
|
|
1331
|
+
const detail = body.detail ?? [];
|
|
1332
|
+
const message = Array.isArray(detail)
|
|
1333
|
+
? detail.map(d => `${d.loc.join('.')}: ${d.msg}`).join('; ')
|
|
1334
|
+
: String(detail);
|
|
1335
|
+
super(message, status, requestId, body);
|
|
1336
|
+
this.name = 'ValidationError';
|
|
1337
|
+
this.fieldErrors = Array.isArray(detail)
|
|
1338
|
+
? detail.map(d => ({ loc: d.loc, msg: d.msg, type: d.type }))
|
|
1339
|
+
: [];
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
class NotFoundError extends ApiError {
|
|
1344
|
+
constructor(body, status, requestId) {
|
|
1345
|
+
super(body.detail ?? 'Resource not found', status, requestId, body);
|
|
1346
|
+
this.name = 'NotFoundError';
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
class RateLimitError extends ApiError {
|
|
1351
|
+
constructor(body, status, requestId, headers) {
|
|
1352
|
+
super(body.detail ?? 'Rate limited', status, requestId, body);
|
|
1353
|
+
this.name = 'RateLimitError';
|
|
1354
|
+
this.retryAfter = parseInt(headers.get('retry-after') ?? '', 10) || null;
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
class ServerError extends ApiError {
|
|
1359
|
+
constructor(body, status, requestId) {
|
|
1360
|
+
super(body.detail ?? 'Internal server error', status, requestId, body);
|
|
1361
|
+
this.name = 'ServerError';
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
async function handleResponse(response) {
|
|
1366
|
+
const requestId = response.headers.get('x-request-id');
|
|
1367
|
+
|
|
1368
|
+
if (response.ok) {
|
|
1369
|
+
return response.status === 204 ? null : response.json();
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
let body;
|
|
1373
|
+
try {
|
|
1374
|
+
body = await response.json();
|
|
1375
|
+
} catch {
|
|
1376
|
+
body = { detail: response.statusText };
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
switch (response.status) {
|
|
1380
|
+
case 422:
|
|
1381
|
+
throw new ValidationError(body, response.status, requestId);
|
|
1382
|
+
case 404:
|
|
1383
|
+
throw new NotFoundError(body, response.status, requestId);
|
|
1384
|
+
case 429:
|
|
1385
|
+
throw new RateLimitError(body, response.status, requestId, response.headers);
|
|
1386
|
+
default:
|
|
1387
|
+
if (response.status >= 500) {
|
|
1388
|
+
throw new ServerError(body, response.status, requestId);
|
|
1389
|
+
}
|
|
1390
|
+
throw new ApiError(
|
|
1391
|
+
body.detail ?? 'Unknown error',
|
|
1392
|
+
response.status,
|
|
1393
|
+
requestId,
|
|
1394
|
+
body
|
|
1395
|
+
);
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
function stripUndef$6(o) { const r = {}; for (const k in o) if (o[k] !== undefined) r[k] = o[k]; return r; }
|
|
1400
|
+
|
|
1401
|
+
class EmailTokens {
|
|
1402
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1403
|
+
|
|
1404
|
+
async requestEmailVerification({ email } = {}) {
|
|
1405
|
+
let path = `/api/v1/request-email-verification`;
|
|
1406
|
+
const query = new URLSearchParams();
|
|
1407
|
+
if (email !== undefined) (Array.isArray(email) ? email : [email]).forEach(v => query.append('email', v));
|
|
1408
|
+
const qs = query.toString();
|
|
1409
|
+
if (qs) path += '?' + qs;
|
|
1410
|
+
const resp = await fetch(this._ctx.baseUrl + path, { method: 'POST' });
|
|
1411
|
+
return handleResponse(resp);
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
async verifyEmail(token) {
|
|
1415
|
+
const resp = await fetch(this._ctx.baseUrl + `/api/v1/verify-email/${encodeURIComponent(token)}`, { method: 'POST' });
|
|
1416
|
+
return handleResponse(resp);
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
async requestPasswordReset({ email } = {}) {
|
|
1420
|
+
let path = `/api/v1/request-password-reset`;
|
|
1421
|
+
const query = new URLSearchParams();
|
|
1422
|
+
if (email !== undefined) (Array.isArray(email) ? email : [email]).forEach(v => query.append('email', v));
|
|
1423
|
+
const qs = query.toString();
|
|
1424
|
+
if (qs) path += '?' + qs;
|
|
1425
|
+
const resp = await fetch(this._ctx.baseUrl + path, { method: 'POST' });
|
|
1426
|
+
return handleResponse(resp);
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
async validateToken(token) {
|
|
1430
|
+
const body = stripUndef$6({
|
|
1431
|
+
token: token,
|
|
1432
|
+
});
|
|
1433
|
+
const resp = await fetch(this._ctx.baseUrl + `/api/v1/validate-token`, {
|
|
1434
|
+
method: 'POST',
|
|
1435
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1436
|
+
body: JSON.stringify(body),
|
|
1437
|
+
});
|
|
1438
|
+
return handleResponse(resp);
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
async resetPassword(token, newPassword) {
|
|
1442
|
+
const body = stripUndef$6({
|
|
1443
|
+
token: token,
|
|
1444
|
+
new_password: newPassword,
|
|
1445
|
+
});
|
|
1446
|
+
const resp = await fetch(this._ctx.baseUrl + `/api/v1/reset-password`, {
|
|
1447
|
+
method: 'POST',
|
|
1448
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1449
|
+
body: JSON.stringify(body),
|
|
1450
|
+
});
|
|
1451
|
+
return handleResponse(resp);
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
async deleteUserEmailTokens(userId) {
|
|
1455
|
+
this._ctx.requireTokens();
|
|
1456
|
+
const path = `/api/v1/admin/email_tokens/by_user/${encodeURIComponent(userId)}`;
|
|
1457
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1458
|
+
return data;
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
class Health {
|
|
1463
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1464
|
+
|
|
1465
|
+
async healthCheck() {
|
|
1466
|
+
const resp = await fetch(this._ctx.baseUrl + `/api/v1/health/`, { method: 'GET' });
|
|
1467
|
+
return handleResponse(resp);
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
async livenessCheck() {
|
|
1471
|
+
const resp = await fetch(this._ctx.baseUrl + `/api/v1/health/live/`, { method: 'GET' });
|
|
1472
|
+
return handleResponse(resp);
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
async readinessCheck() {
|
|
1476
|
+
const resp = await fetch(this._ctx.baseUrl + `/api/v1/health/ready`, { method: 'GET' });
|
|
1477
|
+
return handleResponse(resp);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
function stripUndef$5(o) { const r = {}; for (const k in o) if (o[k] !== undefined) r[k] = o[k]; return r; }
|
|
1482
|
+
|
|
1483
|
+
class Keywords {
|
|
1484
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1485
|
+
|
|
1486
|
+
async createKeywordFilteringList(name, projectList = undefined) {
|
|
1487
|
+
this._ctx.requireTokens();
|
|
1488
|
+
const path = `/api/v1/keyword/`;
|
|
1489
|
+
const body = stripUndef$5({
|
|
1490
|
+
name: name,
|
|
1491
|
+
project_list: projectList,
|
|
1492
|
+
});
|
|
1493
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
1494
|
+
return data;
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
async getUserKeywordFilteringLists() {
|
|
1498
|
+
this._ctx.requireTokens();
|
|
1499
|
+
const path = `/api/v1/keyword/user`;
|
|
1500
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1501
|
+
return data;
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
async getCompanyKeywordLists(companyId) {
|
|
1505
|
+
this._ctx.requireTokens();
|
|
1506
|
+
const path = `/api/v1/keyword/company/${encodeURIComponent(companyId)}`;
|
|
1507
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1508
|
+
return data;
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
async getKeywordFilteringListAndProjectsById(keywordListId) {
|
|
1512
|
+
this._ctx.requireTokens();
|
|
1513
|
+
const path = `/api/v1/keyword/${encodeURIComponent(keywordListId)}`;
|
|
1514
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1515
|
+
return data;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
async getKeywordFilteringListById(keywordListId) {
|
|
1519
|
+
this._ctx.requireTokens();
|
|
1520
|
+
const path = `/api/v1/keyword/list/${encodeURIComponent(keywordListId)}`;
|
|
1521
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1522
|
+
return data;
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
async getExistingKeywordFilteringListByProject(projectTableName) {
|
|
1526
|
+
this._ctx.requireTokens();
|
|
1527
|
+
const path = `/api/v1/keyword/project/${encodeURIComponent(projectTableName)}`;
|
|
1528
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1529
|
+
return data;
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
async getDefaultKeywordFilteringListByProject(projectTableName) {
|
|
1533
|
+
this._ctx.requireTokens();
|
|
1534
|
+
const path = `/api/v1/keyword/project/${encodeURIComponent(projectTableName)}/default`;
|
|
1535
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1536
|
+
return data;
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
async updateKeywordFilteringListLabels(keywordListId, listKeywordsToInclude, listKeywordsToExclude) {
|
|
1540
|
+
this._ctx.requireTokens();
|
|
1541
|
+
const path = `/api/v1/keyword/${encodeURIComponent(keywordListId)}`;
|
|
1542
|
+
const body = stripUndef$5({
|
|
1543
|
+
list_keywords_to_include: listKeywordsToInclude,
|
|
1544
|
+
list_keywords_to_exclude: listKeywordsToExclude,
|
|
1545
|
+
});
|
|
1546
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
1547
|
+
return data;
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
async updateKeywordFilteringListDetails(keywordListId, { name, projectList } = {}) {
|
|
1551
|
+
this._ctx.requireTokens();
|
|
1552
|
+
const path = `/api/v1/keyword/details/${encodeURIComponent(keywordListId)}`;
|
|
1553
|
+
const body = stripUndef$5({
|
|
1554
|
+
name: name,
|
|
1555
|
+
project_list: projectList,
|
|
1556
|
+
});
|
|
1557
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
1558
|
+
return data;
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
async addProjectsToKeywordFilteringList(keywordListId, { projectIds } = {}) {
|
|
1562
|
+
this._ctx.requireTokens();
|
|
1563
|
+
let path = `/api/v1/keyword/${encodeURIComponent(keywordListId)}/projects`;
|
|
1564
|
+
const query = new URLSearchParams();
|
|
1565
|
+
if (projectIds !== undefined) (Array.isArray(projectIds) ? projectIds : [projectIds]).forEach(v => query.append('project_ids', v));
|
|
1566
|
+
const qs = query.toString();
|
|
1567
|
+
if (qs) path += '?' + qs;
|
|
1568
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1569
|
+
return data;
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
async addCompanyToKeywordFilteringList(keywordListId, { companyId } = {}) {
|
|
1573
|
+
this._ctx.requireTokens();
|
|
1574
|
+
let path = `/api/v1/keyword/${encodeURIComponent(keywordListId)}/company`;
|
|
1575
|
+
const query = new URLSearchParams();
|
|
1576
|
+
if (companyId !== undefined) (Array.isArray(companyId) ? companyId : [companyId]).forEach(v => query.append('company_id', v));
|
|
1577
|
+
const qs = query.toString();
|
|
1578
|
+
if (qs) path += '?' + qs;
|
|
1579
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1580
|
+
return data;
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
async requestKeywordListExport(keywordListId) {
|
|
1584
|
+
this._ctx.requireTokens();
|
|
1585
|
+
const path = `/api/v1/keyword/export/${encodeURIComponent(keywordListId)}`;
|
|
1586
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1587
|
+
return data;
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
async requestKeywordListExportStatus(keywordListId) {
|
|
1591
|
+
this._ctx.requireTokens();
|
|
1592
|
+
const path = `/api/v1/keyword/export_status/${encodeURIComponent(keywordListId)}`;
|
|
1593
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1594
|
+
return data;
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
async getKeywordsAndIds() {
|
|
1598
|
+
this._ctx.requireTokens();
|
|
1599
|
+
const path = `/api/v1/keyword/all_keywords/id/label`;
|
|
1600
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1601
|
+
return data;
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
async removeProjectsFromKeywordFilteringList(keywordListId, { projectIds } = {}) {
|
|
1605
|
+
this._ctx.requireTokens();
|
|
1606
|
+
let path = `/api/v1/keyword/${encodeURIComponent(keywordListId)}/projects`;
|
|
1607
|
+
const query = new URLSearchParams();
|
|
1608
|
+
if (projectIds !== undefined) (Array.isArray(projectIds) ? projectIds : [projectIds]).forEach(v => query.append('project_ids', v));
|
|
1609
|
+
const qs = query.toString();
|
|
1610
|
+
if (qs) path += '?' + qs;
|
|
1611
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1612
|
+
return data;
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
async removeCompanyFromKeywordFilteringList(keywordListId, { companyId } = {}) {
|
|
1616
|
+
this._ctx.requireTokens();
|
|
1617
|
+
let path = `/api/v1/keyword/${encodeURIComponent(keywordListId)}/company`;
|
|
1618
|
+
const query = new URLSearchParams();
|
|
1619
|
+
if (companyId !== undefined) (Array.isArray(companyId) ? companyId : [companyId]).forEach(v => query.append('company_id', v));
|
|
1620
|
+
const qs = query.toString();
|
|
1621
|
+
if (qs) path += '?' + qs;
|
|
1622
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1623
|
+
return data;
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
async deleteKeywordFilteringListById(keywordListId) {
|
|
1627
|
+
this._ctx.requireTokens();
|
|
1628
|
+
const path = `/api/v1/keyword/${encodeURIComponent(keywordListId)}`;
|
|
1629
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1630
|
+
return data;
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
class Media {
|
|
1635
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1636
|
+
|
|
1637
|
+
async getProjectAccessQuery(projectTableName) {
|
|
1638
|
+
this._ctx.requireTokens();
|
|
1639
|
+
const path = `/api/v1/media/project/${encodeURIComponent(projectTableName)}/access_query`;
|
|
1640
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1641
|
+
return data;
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
class OauthAuthorization {
|
|
1646
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1647
|
+
|
|
1648
|
+
async authorize({ responseType, clientId, redirectUri, state, codeChallenge, codeChallengeMethod } = {}) {
|
|
1649
|
+
let path = `/oauth/authorize`;
|
|
1650
|
+
const query = new URLSearchParams();
|
|
1651
|
+
if (responseType !== undefined) (Array.isArray(responseType) ? responseType : [responseType]).forEach(v => query.append('response_type', v));
|
|
1652
|
+
if (clientId !== undefined) (Array.isArray(clientId) ? clientId : [clientId]).forEach(v => query.append('client_id', v));
|
|
1653
|
+
if (redirectUri !== undefined) (Array.isArray(redirectUri) ? redirectUri : [redirectUri]).forEach(v => query.append('redirect_uri', v));
|
|
1654
|
+
if (state !== undefined) (Array.isArray(state) ? state : [state]).forEach(v => query.append('state', v));
|
|
1655
|
+
if (codeChallenge !== undefined) (Array.isArray(codeChallenge) ? codeChallenge : [codeChallenge]).forEach(v => query.append('code_challenge', v));
|
|
1656
|
+
if (codeChallengeMethod !== undefined) (Array.isArray(codeChallengeMethod) ? codeChallengeMethod : [codeChallengeMethod]).forEach(v => query.append('code_challenge_method', v));
|
|
1657
|
+
const qs = query.toString();
|
|
1658
|
+
if (qs) path += '?' + qs;
|
|
1659
|
+
const resp = await fetch(this._ctx.baseUrl + path, { method: 'GET' });
|
|
1660
|
+
return handleResponse(resp);
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
async getConsent(sessionId) {
|
|
1664
|
+
const resp = await fetch(this._ctx.baseUrl + `/oauth/consent/${encodeURIComponent(sessionId)}`, { method: 'GET' });
|
|
1665
|
+
return handleResponse(resp);
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
async postApproveConsent(sessionId, { restartUrl }) {
|
|
1669
|
+
const resp = await fetch(this._ctx.baseUrl + `/oauth/consent/${encodeURIComponent(sessionId)}/approve`, {
|
|
1670
|
+
method: 'POST',
|
|
1671
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
1672
|
+
body: new URLSearchParams({ restart_url: restartUrl }).toString(),
|
|
1673
|
+
});
|
|
1674
|
+
return handleResponse(resp);
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
async postDenyConsent(sessionId, { restartUrl }) {
|
|
1678
|
+
const resp = await fetch(this._ctx.baseUrl + `/oauth/consent/${encodeURIComponent(sessionId)}/deny`, {
|
|
1679
|
+
method: 'POST',
|
|
1680
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
1681
|
+
body: new URLSearchParams({ restart_url: restartUrl }).toString(),
|
|
1682
|
+
});
|
|
1683
|
+
return handleResponse(resp);
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
async getSwitchUser(sessionId, { restartUrl } = {}) {
|
|
1687
|
+
let path = `/oauth/consent/${encodeURIComponent(sessionId)}/switch-user`;
|
|
1688
|
+
const query = new URLSearchParams();
|
|
1689
|
+
if (restartUrl !== undefined) (Array.isArray(restartUrl) ? restartUrl : [restartUrl]).forEach(v => query.append('restart_url', v));
|
|
1690
|
+
const qs = query.toString();
|
|
1691
|
+
if (qs) path += '?' + qs;
|
|
1692
|
+
const resp = await fetch(this._ctx.baseUrl + path, { method: 'GET' });
|
|
1693
|
+
return handleResponse(resp);
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1697
|
+
class OauthToken {
|
|
1698
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1699
|
+
|
|
1700
|
+
async token({ grantType, code, redirectUri, clientId, codeVerifier, refreshToken, clientSecret }) {
|
|
1701
|
+
const resp = await fetch(this._ctx.baseUrl + `/oauth/token`, {
|
|
1702
|
+
method: 'POST',
|
|
1703
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
1704
|
+
body: new URLSearchParams({ grant_type: grantType, code, redirect_uri: redirectUri, client_id: clientId, code_verifier: codeVerifier, refresh_token: refreshToken, client_secret: clientSecret }).toString(),
|
|
1705
|
+
});
|
|
1706
|
+
return handleResponse(resp);
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
async adminRevokeUserTokens(userId) {
|
|
1710
|
+
this._ctx.requireTokens();
|
|
1711
|
+
const path = `/oauth/admin/users/${encodeURIComponent(userId)}/revoke-tokens`;
|
|
1712
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1713
|
+
return data;
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
async revoke({ token, tokenTypeHint, clientId }) {
|
|
1717
|
+
const resp = await fetch(this._ctx.baseUrl + `/oauth/revoke`, {
|
|
1718
|
+
method: 'POST',
|
|
1719
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
1720
|
+
body: new URLSearchParams({ token, token_type_hint: tokenTypeHint, client_id: clientId }).toString(),
|
|
1721
|
+
});
|
|
1722
|
+
return handleResponse(resp);
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
class OauthLogin {
|
|
1727
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1728
|
+
|
|
1729
|
+
async getLogin({ next } = {}) {
|
|
1730
|
+
let path = `/api/v1/oauth/login`;
|
|
1731
|
+
const query = new URLSearchParams();
|
|
1732
|
+
if (next !== undefined) (Array.isArray(next) ? next : [next]).forEach(v => query.append('next', v));
|
|
1733
|
+
const qs = query.toString();
|
|
1734
|
+
if (qs) path += '?' + qs;
|
|
1735
|
+
const resp = await fetch(this._ctx.baseUrl + path, { method: 'GET' });
|
|
1736
|
+
return handleResponse(resp);
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
async postLogin({ email, password, next }) {
|
|
1740
|
+
const resp = await fetch(this._ctx.baseUrl + `/api/v1/oauth/login`, {
|
|
1741
|
+
method: 'POST',
|
|
1742
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
1743
|
+
body: new URLSearchParams({ email, password, next }).toString(),
|
|
1744
|
+
});
|
|
1745
|
+
return handleResponse(resp);
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
class Person {
|
|
1750
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1751
|
+
|
|
1752
|
+
async updatePerson(projectTableName, personId, { personName } = {}) {
|
|
1753
|
+
this._ctx.requireTokens();
|
|
1754
|
+
let path = `/api/v1/person/${encodeURIComponent(projectTableName)}/${encodeURIComponent(personId)}`;
|
|
1755
|
+
const query = new URLSearchParams();
|
|
1756
|
+
if (personName !== undefined) (Array.isArray(personName) ? personName : [personName]).forEach(v => query.append('person_name', v));
|
|
1757
|
+
const qs = query.toString();
|
|
1758
|
+
if (qs) path += '?' + qs;
|
|
1759
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1760
|
+
return data;
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
async removePersonName(projectTableName, personId) {
|
|
1764
|
+
this._ctx.requireTokens();
|
|
1765
|
+
const path = `/api/v1/person/${encodeURIComponent(projectTableName)}/remove_name/${encodeURIComponent(personId)}`;
|
|
1766
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1767
|
+
return data;
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
async combinePersons(projectTableName, destinationPersonId, oldPersonId) {
|
|
1771
|
+
this._ctx.requireTokens();
|
|
1772
|
+
const path = `/api/v1/person/${encodeURIComponent(projectTableName)}/combine/${encodeURIComponent(destinationPersonId)}/${encodeURIComponent(oldPersonId)}`;
|
|
1773
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1774
|
+
return data;
|
|
1775
|
+
}
|
|
1776
|
+
|
|
1777
|
+
async splitPersons(projectTableName, id, { newName, destinationPersonId } = {}) {
|
|
1778
|
+
this._ctx.requireTokens();
|
|
1779
|
+
let path = `/api/v1/person/${encodeURIComponent(projectTableName)}/split/${encodeURIComponent(id)}/`;
|
|
1780
|
+
const query = new URLSearchParams();
|
|
1781
|
+
if (newName !== undefined) (Array.isArray(newName) ? newName : [newName]).forEach(v => query.append('new_name', v));
|
|
1782
|
+
if (destinationPersonId !== undefined) (Array.isArray(destinationPersonId) ? destinationPersonId : [destinationPersonId]).forEach(v => query.append('destination_person_id', v));
|
|
1783
|
+
const qs = query.toString();
|
|
1784
|
+
if (qs) path += '?' + qs;
|
|
1785
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1786
|
+
return data;
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
async getAllPersonsFromProject(projectTableName) {
|
|
1790
|
+
this._ctx.requireTokens();
|
|
1791
|
+
const path = `/api/v1/person/${encodeURIComponent(projectTableName)}/`;
|
|
1792
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1793
|
+
return data;
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
async getAllPersonNamesFromProject(projectTableName) {
|
|
1797
|
+
this._ctx.requireTokens();
|
|
1798
|
+
const path = `/api/v1/person/${encodeURIComponent(projectTableName)}/names`;
|
|
1799
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1800
|
+
return data;
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
async getPhotoIdsByPersons(projectTableName, { personId } = {}) {
|
|
1804
|
+
this._ctx.requireTokens();
|
|
1805
|
+
let path = `/api/v1/person/${encodeURIComponent(projectTableName)}/photos`;
|
|
1806
|
+
const query = new URLSearchParams();
|
|
1807
|
+
if (personId !== undefined) (Array.isArray(personId) ? personId : [personId]).forEach(v => query.append('person_id', v));
|
|
1808
|
+
const qs = query.toString();
|
|
1809
|
+
if (qs) path += '?' + qs;
|
|
1810
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1811
|
+
return data;
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
async getAllPersonsFromPhoto(projectTableName, photoId) {
|
|
1815
|
+
this._ctx.requireTokens();
|
|
1816
|
+
const path = `/api/v1/person/${encodeURIComponent(projectTableName)}/photo/${encodeURIComponent(photoId)}`;
|
|
1817
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1818
|
+
return data;
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
async removePerson(projectTableName, personId) {
|
|
1822
|
+
this._ctx.requireTokens();
|
|
1823
|
+
const path = `/api/v1/person/${encodeURIComponent(projectTableName)}/${encodeURIComponent(personId)}`;
|
|
1824
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1825
|
+
return data;
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
function stripUndef$4(o) { const r = {}; for (const k in o) if (o[k] !== undefined) r[k] = o[k]; return r; }
|
|
1830
|
+
|
|
1831
|
+
class Projects {
|
|
1832
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
1833
|
+
|
|
1834
|
+
async createProjectAndRun(name, type, private_ = undefined, description = undefined, directory = undefined, photoUploadVector = undefined, thumbnail = undefined, runName = undefined, { outcomes, models } = {}) {
|
|
1835
|
+
this._ctx.requireTokens();
|
|
1836
|
+
let path = `/api/v1/project_outcome/`;
|
|
1837
|
+
const query = new URLSearchParams();
|
|
1838
|
+
if (outcomes !== undefined) (Array.isArray(outcomes) ? outcomes : [outcomes]).forEach(v => query.append('outcomes', v));
|
|
1839
|
+
if (models !== undefined) (Array.isArray(models) ? models : [models]).forEach(v => query.append('models', v));
|
|
1840
|
+
const qs = query.toString();
|
|
1841
|
+
if (qs) path += '?' + qs;
|
|
1842
|
+
const body = stripUndef$4({
|
|
1843
|
+
name: name,
|
|
1844
|
+
private: private_,
|
|
1845
|
+
type: type,
|
|
1846
|
+
description: description,
|
|
1847
|
+
directory: directory,
|
|
1848
|
+
photo_upload_vector: photoUploadVector,
|
|
1849
|
+
thumbnail: thumbnail,
|
|
1850
|
+
run_name: runName,
|
|
1851
|
+
});
|
|
1852
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
1853
|
+
return data;
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
async markProjectUploadComplete(projectTableName, { skippedFileCount } = {}) {
|
|
1857
|
+
this._ctx.requireTokens();
|
|
1858
|
+
let path = `/api/v1/project/${encodeURIComponent(projectTableName)}/upload_complete/`;
|
|
1859
|
+
const query = new URLSearchParams();
|
|
1860
|
+
if (skippedFileCount !== undefined) (Array.isArray(skippedFileCount) ? skippedFileCount : [skippedFileCount]).forEach(v => query.append('skipped_file_count', v));
|
|
1861
|
+
const qs = query.toString();
|
|
1862
|
+
if (qs) path += '?' + qs;
|
|
1863
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1864
|
+
return data;
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
async checkProjectStatus(projectTableName) {
|
|
1868
|
+
this._ctx.requireTokens();
|
|
1869
|
+
const path = `/api/v1/project/status/${encodeURIComponent(projectTableName)}`;
|
|
1870
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1871
|
+
return data;
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
async getProjectPrelimModelRequestTemplate(projectTableName) {
|
|
1875
|
+
this._ctx.requireTokens();
|
|
1876
|
+
const path = `/api/v1/project_outcome/${encodeURIComponent(projectTableName)}`;
|
|
1877
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1878
|
+
return data;
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
async getUserProjects() {
|
|
1882
|
+
this._ctx.requireTokens();
|
|
1883
|
+
const path = `/api/v1/projects/user`;
|
|
1884
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1885
|
+
return data;
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
async getAdminProjects() {
|
|
1889
|
+
this._ctx.requireTokens();
|
|
1890
|
+
const path = `/api/v1/projects/admin`;
|
|
1891
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1892
|
+
return data;
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
async getProjectById(projectId) {
|
|
1896
|
+
this._ctx.requireTokens();
|
|
1897
|
+
const path = `/api/v1/projects/${encodeURIComponent(projectId)}`;
|
|
1898
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1899
|
+
return data;
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
async getProjectByDirectory(directory) {
|
|
1903
|
+
this._ctx.requireTokens();
|
|
1904
|
+
const path = `/api/v1/projects/directory/${encodeURIComponent(directory)}`;
|
|
1905
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1906
|
+
return data;
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
async updateProject(projectId, { private: private_, type, description, directory, name, thumbnail } = {}) {
|
|
1910
|
+
this._ctx.requireTokens();
|
|
1911
|
+
const path = `/api/v1/projects/${encodeURIComponent(projectId)}`;
|
|
1912
|
+
const body = stripUndef$4({
|
|
1913
|
+
private: private_,
|
|
1914
|
+
type: type,
|
|
1915
|
+
description: description,
|
|
1916
|
+
directory: directory,
|
|
1917
|
+
name: name,
|
|
1918
|
+
thumbnail: thumbnail,
|
|
1919
|
+
});
|
|
1920
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
1921
|
+
return data;
|
|
1922
|
+
}
|
|
1923
|
+
|
|
1924
|
+
async updateProjectPhotoCount(tableName, { filesFailedCount } = {}) {
|
|
1925
|
+
this._ctx.requireTokens();
|
|
1926
|
+
let path = `/api/v1/projects_photos/${encodeURIComponent(tableName)}/`;
|
|
1927
|
+
const query = new URLSearchParams();
|
|
1928
|
+
if (filesFailedCount !== undefined) (Array.isArray(filesFailedCount) ? filesFailedCount : [filesFailedCount]).forEach(v => query.append('files_failed_count', v));
|
|
1929
|
+
const qs = query.toString();
|
|
1930
|
+
if (qs) path += '?' + qs;
|
|
1931
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1932
|
+
return data;
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
async updateProjectCreateUploadReport(tableName, { filesFailedCount } = {}) {
|
|
1936
|
+
this._ctx.requireTokens();
|
|
1937
|
+
let path = `/api/v1/project_upload_report/${encodeURIComponent(tableName)}/`;
|
|
1938
|
+
const query = new URLSearchParams();
|
|
1939
|
+
if (filesFailedCount !== undefined) (Array.isArray(filesFailedCount) ? filesFailedCount : [filesFailedCount]).forEach(v => query.append('files_failed_count', v));
|
|
1940
|
+
const qs = query.toString();
|
|
1941
|
+
if (qs) path += '?' + qs;
|
|
1942
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1943
|
+
return data;
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
async requestProjectSimilarityQueue(projectTableName, level) {
|
|
1947
|
+
this._ctx.requireTokens();
|
|
1948
|
+
const path = `/api/v1/projects_similarity_queue/${encodeURIComponent(projectTableName)}/level/${encodeURIComponent(level)}`;
|
|
1949
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1950
|
+
return data;
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
async requestProjectEvidenceQueue(projectTableName) {
|
|
1954
|
+
this._ctx.requireTokens();
|
|
1955
|
+
const path = `/api/v1/projects_evidence_queue/${encodeURIComponent(projectTableName)}`;
|
|
1956
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1957
|
+
return data;
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
async requestProjectPersonhoodQueue(projectTableName) {
|
|
1961
|
+
this._ctx.requireTokens();
|
|
1962
|
+
const path = `/api/v1/projects_personhood_queue/${encodeURIComponent(projectTableName)}`;
|
|
1963
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1964
|
+
return data;
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
async requestInsightsQueue(analysisLevel, identifier) {
|
|
1968
|
+
this._ctx.requireTokens();
|
|
1969
|
+
const path = `/api/v1/insights_queue/analysis_level/${encodeURIComponent(analysisLevel)}/identifier/${encodeURIComponent(identifier)}`;
|
|
1970
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1971
|
+
return data;
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
async requestProjectExport(projectTableName) {
|
|
1975
|
+
this._ctx.requireTokens();
|
|
1976
|
+
const path = `/api/v1/projects_export/${encodeURIComponent(projectTableName)}`;
|
|
1977
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1978
|
+
return data;
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
async getProjectProcessStatus(projectTableName, modelName) {
|
|
1982
|
+
this._ctx.requireTokens();
|
|
1983
|
+
const path = `/api/v1/projects/${encodeURIComponent(projectTableName)}/process_status/${encodeURIComponent(modelName)}`;
|
|
1984
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
1985
|
+
return data;
|
|
1986
|
+
}
|
|
1987
|
+
|
|
1988
|
+
async addProjectEvent(projectTableName, event, detail = undefined) {
|
|
1989
|
+
this._ctx.requireTokens();
|
|
1990
|
+
const path = `/api/v1/projects/${encodeURIComponent(projectTableName)}/event`;
|
|
1991
|
+
const body = stripUndef$4({
|
|
1992
|
+
event: event,
|
|
1993
|
+
detail: detail,
|
|
1994
|
+
});
|
|
1995
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
1996
|
+
return data;
|
|
1997
|
+
}
|
|
1998
|
+
|
|
1999
|
+
async deleteProject(projectId) {
|
|
2000
|
+
this._ctx.requireTokens();
|
|
2001
|
+
const path = `/api/v1/projects/${encodeURIComponent(projectId)}`;
|
|
2002
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2003
|
+
return data;
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
|
|
2007
|
+
class Photoupload {
|
|
2008
|
+
constructor(ctx) { this._ctx = ctx; this._caches = {}; }
|
|
2009
|
+
|
|
2010
|
+
async uploadPhotoToMediaviz(fileContent, filePath, mimetype, companyId, userId, projectTableName, blur, colors, faceRecognition, imageClassification, imageComparison, imageDescribe, ocr, judgment, { clientSideId, format, size, sourceResolutionX, sourceResolutionY, dateTaken, latitude, longitude } = {}) {
|
|
2011
|
+
this._ctx.requireTokens();
|
|
2012
|
+
const baseUrl = this._ctx.requireHost('photoUpload');
|
|
2013
|
+
const headers = {
|
|
2014
|
+
'Content-Type': 'application/json',
|
|
2015
|
+
'Authorization': `Bearer ${this._ctx.accessToken}`,
|
|
2016
|
+
};
|
|
2017
|
+
const resp = await fetch(baseUrl + `/photo_upload`, {
|
|
2018
|
+
method: 'POST',
|
|
2019
|
+
headers,
|
|
2020
|
+
body: JSON.stringify({ file_content: fileContent, file_path: filePath, mimetype, company_id: companyId, user_id: userId, project_table_name: projectTableName, blur, colors, face_recognition: faceRecognition, image_classification: imageClassification, image_comparison: imageComparison, image_describe: imageDescribe, ocr, judgment, client_side_id: clientSideId, format, size, source_resolution_x: sourceResolutionX, source_resolution_y: sourceResolutionY, date_taken: dateTaken, latitude, longitude }),
|
|
2021
|
+
});
|
|
2022
|
+
return handleResponse(resp);
|
|
2023
|
+
}
|
|
2024
|
+
|
|
2025
|
+
async uploadPhoto(companyId, userId, projectTableName, photo) {
|
|
2026
|
+
this._ctx.requireTokens();
|
|
2027
|
+
|
|
2028
|
+
if (!this._caches['_get_template']) this._caches['_get_template'] = new Map();
|
|
2029
|
+
const _cacheKey_get_template = `upload_template:${projectTableName}`;
|
|
2030
|
+
let template = this._caches['_get_template'].get(_cacheKey_get_template);
|
|
2031
|
+
if (template === undefined) {
|
|
2032
|
+
template = (await this._ctx.client.request(`/api/v1/project_outcome/${encodeURIComponent(projectTableName)}`, 'GET', this._ctx.accessToken, this._ctx.refreshToken)).data;
|
|
2033
|
+
this._caches['_get_template'].set(_cacheKey_get_template, template);
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
const upload_result = await this.uploadPhotoToMediaviz(photo.fileContent, photo.filePath, photo.mimetype, companyId, userId, projectTableName, (((template?.body?.['blur'] ?? template?.headers?.['x-blur']) === true || (template?.body?.['blur'] ?? template?.headers?.['x-blur']) === 'true') ? 'true' : undefined), (((template?.body?.['colors'] ?? template?.headers?.['x-colors']) === true || (template?.body?.['colors'] ?? template?.headers?.['x-colors']) === 'true') ? 'true' : undefined), (((template?.body?.['face_recognition'] ?? template?.headers?.['x-face-recognition']) === true || (template?.body?.['face_recognition'] ?? template?.headers?.['x-face-recognition']) === 'true') ? 'true' : undefined), (((template?.body?.['image_classification'] ?? template?.headers?.['x-image-classification']) === true || (template?.body?.['image_classification'] ?? template?.headers?.['x-image-classification']) === 'true') ? 'true' : undefined), (((template?.body?.['image_comparison'] ?? template?.headers?.['x-image-comparison']) === true || (template?.body?.['image_comparison'] ?? template?.headers?.['x-image-comparison']) === 'true') ? 'true' : undefined), (((template?.body?.['image_describe'] ?? template?.headers?.['x-image-describe']) === true || (template?.body?.['image_describe'] ?? template?.headers?.['x-image-describe']) === 'true') ? 'true' : undefined), (((template?.body?.['ocr'] ?? template?.headers?.['x-ocr']) === true || (template?.body?.['ocr'] ?? template?.headers?.['x-ocr']) === 'true') ? 'true' : undefined), (((template?.body?.['judgment'] ?? template?.headers?.['x-judgment']) === true || (template?.body?.['judgment'] ?? template?.headers?.['x-judgment']) === 'true') ? 'true' : undefined), { clientSideId: photo.clientSideId, format: photo.format, size: photo.size, sourceResolutionX: photo.sourceResolutionX, sourceResolutionY: photo.sourceResolutionY, dateTaken: photo.dateTaken, latitude: photo.latitude, longitude: photo.longitude });
|
|
2037
|
+
|
|
2038
|
+
return upload_result;
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
function stripUndef$3(o) { const r = {}; for (const k in o) if (o[k] !== undefined) r[k] = o[k]; return r; }
|
|
2043
|
+
|
|
2044
|
+
class Photos {
|
|
2045
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
2046
|
+
|
|
2047
|
+
async getPhotoFromProject(tableName, photoId, { keywordListId } = {}) {
|
|
2048
|
+
this._ctx.requireTokens();
|
|
2049
|
+
let path = `/api/v1/photos/${encodeURIComponent(tableName)}/${encodeURIComponent(photoId)}`;
|
|
2050
|
+
const query = new URLSearchParams();
|
|
2051
|
+
if (keywordListId !== undefined) (Array.isArray(keywordListId) ? keywordListId : [keywordListId]).forEach(v => query.append('keyword_list_id', v));
|
|
2052
|
+
const qs = query.toString();
|
|
2053
|
+
if (qs) path += '?' + qs;
|
|
2054
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2055
|
+
return data;
|
|
2056
|
+
}
|
|
2057
|
+
|
|
2058
|
+
async getPhotoFaceDetailsFromProject(tableName, photoId) {
|
|
2059
|
+
this._ctx.requireTokens();
|
|
2060
|
+
const path = `/api/v1/photos/face_details/${encodeURIComponent(tableName)}/${encodeURIComponent(photoId)}`;
|
|
2061
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2062
|
+
return data;
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
async getProjectPhotoIdsByTableName(tableName, { ascOrDesc, lastId, limit, includeAll, startDate, endDate, noDateTaken } = {}) {
|
|
2066
|
+
this._ctx.requireTokens();
|
|
2067
|
+
let path = `/api/v1/photos/${encodeURIComponent(tableName)}/`;
|
|
2068
|
+
const query = new URLSearchParams();
|
|
2069
|
+
if (ascOrDesc !== undefined) (Array.isArray(ascOrDesc) ? ascOrDesc : [ascOrDesc]).forEach(v => query.append('asc_or_desc', v));
|
|
2070
|
+
if (lastId !== undefined) (Array.isArray(lastId) ? lastId : [lastId]).forEach(v => query.append('last_id', v));
|
|
2071
|
+
if (limit !== undefined) (Array.isArray(limit) ? limit : [limit]).forEach(v => query.append('limit', v));
|
|
2072
|
+
if (includeAll !== undefined) (Array.isArray(includeAll) ? includeAll : [includeAll]).forEach(v => query.append('include_all', v));
|
|
2073
|
+
if (startDate !== undefined) (Array.isArray(startDate) ? startDate : [startDate]).forEach(v => query.append('start_date', v));
|
|
2074
|
+
if (endDate !== undefined) (Array.isArray(endDate) ? endDate : [endDate]).forEach(v => query.append('end_date', v));
|
|
2075
|
+
if (noDateTaken !== undefined) (Array.isArray(noDateTaken) ? noDateTaken : [noDateTaken]).forEach(v => query.append('no_date_taken', v));
|
|
2076
|
+
const qs = query.toString();
|
|
2077
|
+
if (qs) path += '?' + qs;
|
|
2078
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2079
|
+
return data;
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
async getRankedProjectPhotoIdsByTableName(tableName, { ascOrDesc, lastId, limit, startDate, endDate, noDateTaken } = {}) {
|
|
2083
|
+
this._ctx.requireTokens();
|
|
2084
|
+
let path = `/api/v1/photos/ranked/${encodeURIComponent(tableName)}/`;
|
|
2085
|
+
const query = new URLSearchParams();
|
|
2086
|
+
if (ascOrDesc !== undefined) (Array.isArray(ascOrDesc) ? ascOrDesc : [ascOrDesc]).forEach(v => query.append('asc_or_desc', v));
|
|
2087
|
+
if (lastId !== undefined) (Array.isArray(lastId) ? lastId : [lastId]).forEach(v => query.append('last_id', v));
|
|
2088
|
+
if (limit !== undefined) (Array.isArray(limit) ? limit : [limit]).forEach(v => query.append('limit', v));
|
|
2089
|
+
if (startDate !== undefined) (Array.isArray(startDate) ? startDate : [startDate]).forEach(v => query.append('start_date', v));
|
|
2090
|
+
if (endDate !== undefined) (Array.isArray(endDate) ? endDate : [endDate]).forEach(v => query.append('end_date', v));
|
|
2091
|
+
if (noDateTaken !== undefined) (Array.isArray(noDateTaken) ? noDateTaken : [noDateTaken]).forEach(v => query.append('no_date_taken', v));
|
|
2092
|
+
const qs = query.toString();
|
|
2093
|
+
if (qs) path += '?' + qs;
|
|
2094
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2095
|
+
return data;
|
|
2096
|
+
}
|
|
2097
|
+
|
|
2098
|
+
async getProjectMonthYearsWithPhotos(tableName) {
|
|
2099
|
+
this._ctx.requireTokens();
|
|
2100
|
+
const path = `/api/v1/photo_month_years/${encodeURIComponent(tableName)}`;
|
|
2101
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2102
|
+
return data;
|
|
2103
|
+
}
|
|
2104
|
+
|
|
2105
|
+
async updatePhotoInProject(tableName, photoId, { filePath, title, description, tags } = {}) {
|
|
2106
|
+
this._ctx.requireTokens();
|
|
2107
|
+
const path = `/api/v1/photos_update/${encodeURIComponent(tableName)}/id/${encodeURIComponent(photoId)}`;
|
|
2108
|
+
const body = stripUndef$3({
|
|
2109
|
+
file_path: filePath,
|
|
2110
|
+
title: title,
|
|
2111
|
+
description: description,
|
|
2112
|
+
tags: tags,
|
|
2113
|
+
});
|
|
2114
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
2115
|
+
return data;
|
|
2116
|
+
}
|
|
2117
|
+
|
|
2118
|
+
async updatePhotoRanking(tableName, photoId, newCategory) {
|
|
2119
|
+
this._ctx.requireTokens();
|
|
2120
|
+
const path = `/api/v1/photos_update/${encodeURIComponent(tableName)}/id/${encodeURIComponent(photoId)}/rank/${encodeURIComponent(newCategory)}`;
|
|
2121
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2122
|
+
return data;
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
async deletePhotoFromProject(tableName, { photoIds } = {}) {
|
|
2126
|
+
this._ctx.requireTokens();
|
|
2127
|
+
let path = `/api/v1/photos/${encodeURIComponent(tableName)}/delete/`;
|
|
2128
|
+
const query = new URLSearchParams();
|
|
2129
|
+
if (photoIds !== undefined) (Array.isArray(photoIds) ? photoIds : [photoIds]).forEach(v => query.append('photo_ids', v));
|
|
2130
|
+
const qs = query.toString();
|
|
2131
|
+
if (qs) path += '?' + qs;
|
|
2132
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2133
|
+
return data;
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
function stripUndef$2(o) { const r = {}; for (const k in o) if (o[k] !== undefined) r[k] = o[k]; return r; }
|
|
2138
|
+
|
|
2139
|
+
class Search {
|
|
2140
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
2141
|
+
|
|
2142
|
+
async searchProjectPhotos(projectTableName, { andParams, andStringParams, orParams, orStringParams, notParams, notStringParams, dateMin, dateMax, dateNullAnd, dateNullOr, dateOrder, customAlbumId, bestOfSimilarSetsOnly, curatedAlbumId, splitByTier } = {}) {
|
|
2143
|
+
this._ctx.requireTokens();
|
|
2144
|
+
let path = `/api/v1/search/${encodeURIComponent(projectTableName)}/`;
|
|
2145
|
+
const query = new URLSearchParams();
|
|
2146
|
+
if (andParams !== undefined) (Array.isArray(andParams) ? andParams : [andParams]).forEach(v => query.append('and_params', v));
|
|
2147
|
+
if (andStringParams !== undefined) (Array.isArray(andStringParams) ? andStringParams : [andStringParams]).forEach(v => query.append('and_string_params', v));
|
|
2148
|
+
if (orParams !== undefined) (Array.isArray(orParams) ? orParams : [orParams]).forEach(v => query.append('or_params', v));
|
|
2149
|
+
if (orStringParams !== undefined) (Array.isArray(orStringParams) ? orStringParams : [orStringParams]).forEach(v => query.append('or_string_params', v));
|
|
2150
|
+
if (notParams !== undefined) (Array.isArray(notParams) ? notParams : [notParams]).forEach(v => query.append('not_params', v));
|
|
2151
|
+
if (notStringParams !== undefined) (Array.isArray(notStringParams) ? notStringParams : [notStringParams]).forEach(v => query.append('not_string_params', v));
|
|
2152
|
+
if (dateMin !== undefined) (Array.isArray(dateMin) ? dateMin : [dateMin]).forEach(v => query.append('date_min', v));
|
|
2153
|
+
if (dateMax !== undefined) (Array.isArray(dateMax) ? dateMax : [dateMax]).forEach(v => query.append('date_max', v));
|
|
2154
|
+
if (dateNullAnd !== undefined) (Array.isArray(dateNullAnd) ? dateNullAnd : [dateNullAnd]).forEach(v => query.append('date_null_and', v));
|
|
2155
|
+
if (dateNullOr !== undefined) (Array.isArray(dateNullOr) ? dateNullOr : [dateNullOr]).forEach(v => query.append('date_null_or', v));
|
|
2156
|
+
if (dateOrder !== undefined) (Array.isArray(dateOrder) ? dateOrder : [dateOrder]).forEach(v => query.append('date_order', v));
|
|
2157
|
+
if (customAlbumId !== undefined) (Array.isArray(customAlbumId) ? customAlbumId : [customAlbumId]).forEach(v => query.append('custom_album_id', v));
|
|
2158
|
+
if (bestOfSimilarSetsOnly !== undefined) (Array.isArray(bestOfSimilarSetsOnly) ? bestOfSimilarSetsOnly : [bestOfSimilarSetsOnly]).forEach(v => query.append('best_of_similar_sets_only', v));
|
|
2159
|
+
if (curatedAlbumId !== undefined) (Array.isArray(curatedAlbumId) ? curatedAlbumId : [curatedAlbumId]).forEach(v => query.append('curated_album_id', v));
|
|
2160
|
+
if (splitByTier !== undefined) (Array.isArray(splitByTier) ? splitByTier : [splitByTier]).forEach(v => query.append('split_by_tier', v));
|
|
2161
|
+
const qs = query.toString();
|
|
2162
|
+
if (qs) path += '?' + qs;
|
|
2163
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2164
|
+
return data;
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
async searchProjectPhotosParametrized(projectTableName, { andSearchText, orSearchText, notSearchText, city, country, state, albums, dateMin, dateMax, dateNullAnd, dateNullOr, ascOrDesc, bestOfSimilarSetsOnly, splitByTier, lastId, limit } = {}) {
|
|
2168
|
+
this._ctx.requireTokens();
|
|
2169
|
+
let path = `/api/v1/search/parametrized/${encodeURIComponent(projectTableName)}/`;
|
|
2170
|
+
const query = new URLSearchParams();
|
|
2171
|
+
if (andSearchText !== undefined) (Array.isArray(andSearchText) ? andSearchText : [andSearchText]).forEach(v => query.append('and_search_text', v));
|
|
2172
|
+
if (orSearchText !== undefined) (Array.isArray(orSearchText) ? orSearchText : [orSearchText]).forEach(v => query.append('or_search_text', v));
|
|
2173
|
+
if (notSearchText !== undefined) (Array.isArray(notSearchText) ? notSearchText : [notSearchText]).forEach(v => query.append('not_search_text', v));
|
|
2174
|
+
if (city !== undefined) (Array.isArray(city) ? city : [city]).forEach(v => query.append('city', v));
|
|
2175
|
+
if (country !== undefined) (Array.isArray(country) ? country : [country]).forEach(v => query.append('country', v));
|
|
2176
|
+
if (state !== undefined) (Array.isArray(state) ? state : [state]).forEach(v => query.append('state', v));
|
|
2177
|
+
if (albums !== undefined) (Array.isArray(albums) ? albums : [albums]).forEach(v => query.append('albums', v));
|
|
2178
|
+
if (dateMin !== undefined) (Array.isArray(dateMin) ? dateMin : [dateMin]).forEach(v => query.append('date_min', v));
|
|
2179
|
+
if (dateMax !== undefined) (Array.isArray(dateMax) ? dateMax : [dateMax]).forEach(v => query.append('date_max', v));
|
|
2180
|
+
if (dateNullAnd !== undefined) (Array.isArray(dateNullAnd) ? dateNullAnd : [dateNullAnd]).forEach(v => query.append('date_null_and', v));
|
|
2181
|
+
if (dateNullOr !== undefined) (Array.isArray(dateNullOr) ? dateNullOr : [dateNullOr]).forEach(v => query.append('date_null_or', v));
|
|
2182
|
+
if (ascOrDesc !== undefined) (Array.isArray(ascOrDesc) ? ascOrDesc : [ascOrDesc]).forEach(v => query.append('asc_or_desc', v));
|
|
2183
|
+
if (bestOfSimilarSetsOnly !== undefined) (Array.isArray(bestOfSimilarSetsOnly) ? bestOfSimilarSetsOnly : [bestOfSimilarSetsOnly]).forEach(v => query.append('best_of_similar_sets_only', v));
|
|
2184
|
+
if (splitByTier !== undefined) (Array.isArray(splitByTier) ? splitByTier : [splitByTier]).forEach(v => query.append('split_by_tier', v));
|
|
2185
|
+
if (lastId !== undefined) (Array.isArray(lastId) ? lastId : [lastId]).forEach(v => query.append('last_id', v));
|
|
2186
|
+
if (limit !== undefined) (Array.isArray(limit) ? limit : [limit]).forEach(v => query.append('limit', v));
|
|
2187
|
+
const qs = query.toString();
|
|
2188
|
+
if (qs) path += '?' + qs;
|
|
2189
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2190
|
+
return data;
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
async recallProjectPhotos(projectTableName, { ascOrDesc, bestOfSimilarSetsOnly, lastId, limit } = {}) {
|
|
2194
|
+
this._ctx.requireTokens();
|
|
2195
|
+
let path = `/api/v1/search/recall/${encodeURIComponent(projectTableName)}/`;
|
|
2196
|
+
const query = new URLSearchParams();
|
|
2197
|
+
if (ascOrDesc !== undefined) (Array.isArray(ascOrDesc) ? ascOrDesc : [ascOrDesc]).forEach(v => query.append('asc_or_desc', v));
|
|
2198
|
+
if (bestOfSimilarSetsOnly !== undefined) (Array.isArray(bestOfSimilarSetsOnly) ? bestOfSimilarSetsOnly : [bestOfSimilarSetsOnly]).forEach(v => query.append('best_of_similar_sets_only', v));
|
|
2199
|
+
if (lastId !== undefined) (Array.isArray(lastId) ? lastId : [lastId]).forEach(v => query.append('last_id', v));
|
|
2200
|
+
if (limit !== undefined) (Array.isArray(limit) ? limit : [limit]).forEach(v => query.append('limit', v));
|
|
2201
|
+
const qs = query.toString();
|
|
2202
|
+
if (qs) path += '?' + qs;
|
|
2203
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2204
|
+
return data;
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
async searchProjectPhotosNaturalLanguage(projectTableName, searchText, size = undefined, { minCosine, labelMinCosine, labelTopK, labelDelta, bestOfSimilarSetsOnly, splitByTier } = {}) {
|
|
2208
|
+
this._ctx.requireTokens();
|
|
2209
|
+
let path = `/api/v1/search/natural_language/${encodeURIComponent(projectTableName)}/`;
|
|
2210
|
+
const query = new URLSearchParams();
|
|
2211
|
+
if (minCosine !== undefined) (Array.isArray(minCosine) ? minCosine : [minCosine]).forEach(v => query.append('min_cosine', v));
|
|
2212
|
+
if (labelMinCosine !== undefined) (Array.isArray(labelMinCosine) ? labelMinCosine : [labelMinCosine]).forEach(v => query.append('label_min_cosine', v));
|
|
2213
|
+
if (labelTopK !== undefined) (Array.isArray(labelTopK) ? labelTopK : [labelTopK]).forEach(v => query.append('label_top_k', v));
|
|
2214
|
+
if (labelDelta !== undefined) (Array.isArray(labelDelta) ? labelDelta : [labelDelta]).forEach(v => query.append('label_delta', v));
|
|
2215
|
+
if (bestOfSimilarSetsOnly !== undefined) (Array.isArray(bestOfSimilarSetsOnly) ? bestOfSimilarSetsOnly : [bestOfSimilarSetsOnly]).forEach(v => query.append('best_of_similar_sets_only', v));
|
|
2216
|
+
if (splitByTier !== undefined) (Array.isArray(splitByTier) ? splitByTier : [splitByTier]).forEach(v => query.append('split_by_tier', v));
|
|
2217
|
+
const qs = query.toString();
|
|
2218
|
+
if (qs) path += '?' + qs;
|
|
2219
|
+
const body = stripUndef$2({
|
|
2220
|
+
search_text: searchText,
|
|
2221
|
+
size: size,
|
|
2222
|
+
});
|
|
2223
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
2224
|
+
return data;
|
|
2225
|
+
}
|
|
2226
|
+
|
|
2227
|
+
async getProjectSavedSearches(projectTableName) {
|
|
2228
|
+
this._ctx.requireTokens();
|
|
2229
|
+
const path = `/api/v1/search/saved/${encodeURIComponent(projectTableName)}/`;
|
|
2230
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2231
|
+
return data;
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
async getSavedSearchById(searchId) {
|
|
2235
|
+
this._ctx.requireTokens();
|
|
2236
|
+
const path = `/api/v1/search/${encodeURIComponent(searchId)}`;
|
|
2237
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2238
|
+
return data;
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
async saveProjectPhotosSearch(projectTableName, { searchName, andParams, andStringParams, orParams, orStringParams, notParams, notStringParams, dateMin, dateMax, dateNullAnd, dateNullOr, dateOrder, customAlbumId, bestOfSimilarSetsOnly, curatedAlbumId, splitByTier } = {}) {
|
|
2242
|
+
this._ctx.requireTokens();
|
|
2243
|
+
let path = `/api/v1/search/${encodeURIComponent(projectTableName)}/`;
|
|
2244
|
+
const query = new URLSearchParams();
|
|
2245
|
+
if (searchName !== undefined) (Array.isArray(searchName) ? searchName : [searchName]).forEach(v => query.append('search_name', v));
|
|
2246
|
+
if (andParams !== undefined) (Array.isArray(andParams) ? andParams : [andParams]).forEach(v => query.append('and_params', v));
|
|
2247
|
+
if (andStringParams !== undefined) (Array.isArray(andStringParams) ? andStringParams : [andStringParams]).forEach(v => query.append('and_string_params', v));
|
|
2248
|
+
if (orParams !== undefined) (Array.isArray(orParams) ? orParams : [orParams]).forEach(v => query.append('or_params', v));
|
|
2249
|
+
if (orStringParams !== undefined) (Array.isArray(orStringParams) ? orStringParams : [orStringParams]).forEach(v => query.append('or_string_params', v));
|
|
2250
|
+
if (notParams !== undefined) (Array.isArray(notParams) ? notParams : [notParams]).forEach(v => query.append('not_params', v));
|
|
2251
|
+
if (notStringParams !== undefined) (Array.isArray(notStringParams) ? notStringParams : [notStringParams]).forEach(v => query.append('not_string_params', v));
|
|
2252
|
+
if (dateMin !== undefined) (Array.isArray(dateMin) ? dateMin : [dateMin]).forEach(v => query.append('date_min', v));
|
|
2253
|
+
if (dateMax !== undefined) (Array.isArray(dateMax) ? dateMax : [dateMax]).forEach(v => query.append('date_max', v));
|
|
2254
|
+
if (dateNullAnd !== undefined) (Array.isArray(dateNullAnd) ? dateNullAnd : [dateNullAnd]).forEach(v => query.append('date_null_and', v));
|
|
2255
|
+
if (dateNullOr !== undefined) (Array.isArray(dateNullOr) ? dateNullOr : [dateNullOr]).forEach(v => query.append('date_null_or', v));
|
|
2256
|
+
if (dateOrder !== undefined) (Array.isArray(dateOrder) ? dateOrder : [dateOrder]).forEach(v => query.append('date_order', v));
|
|
2257
|
+
if (customAlbumId !== undefined) (Array.isArray(customAlbumId) ? customAlbumId : [customAlbumId]).forEach(v => query.append('custom_album_id', v));
|
|
2258
|
+
if (bestOfSimilarSetsOnly !== undefined) (Array.isArray(bestOfSimilarSetsOnly) ? bestOfSimilarSetsOnly : [bestOfSimilarSetsOnly]).forEach(v => query.append('best_of_similar_sets_only', v));
|
|
2259
|
+
if (curatedAlbumId !== undefined) (Array.isArray(curatedAlbumId) ? curatedAlbumId : [curatedAlbumId]).forEach(v => query.append('curated_album_id', v));
|
|
2260
|
+
if (splitByTier !== undefined) (Array.isArray(splitByTier) ? splitByTier : [splitByTier]).forEach(v => query.append('split_by_tier', v));
|
|
2261
|
+
const qs = query.toString();
|
|
2262
|
+
if (qs) path += '?' + qs;
|
|
2263
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2264
|
+
return data;
|
|
2265
|
+
}
|
|
2266
|
+
|
|
2267
|
+
async deleteSavedSearchById(searchId) {
|
|
2268
|
+
this._ctx.requireTokens();
|
|
2269
|
+
const path = `/api/v1/search/${encodeURIComponent(searchId)}`;
|
|
2270
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2271
|
+
return data;
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
|
|
2275
|
+
function stripUndef$1(o) { const r = {}; for (const k in o) if (o[k] !== undefined) r[k] = o[k]; return r; }
|
|
2276
|
+
|
|
2277
|
+
class Subscription {
|
|
2278
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
2279
|
+
|
|
2280
|
+
async createSubscription(projectTableName, callbackUrl, targets) {
|
|
2281
|
+
this._ctx.requireTokens();
|
|
2282
|
+
const path = `/api/v1/subscriptions`;
|
|
2283
|
+
const body = stripUndef$1({
|
|
2284
|
+
project_table_name: projectTableName,
|
|
2285
|
+
callback_url: callbackUrl,
|
|
2286
|
+
targets: targets,
|
|
2287
|
+
});
|
|
2288
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
2289
|
+
return data;
|
|
2290
|
+
}
|
|
2291
|
+
|
|
2292
|
+
async verifySubscription(subscriptionId) {
|
|
2293
|
+
this._ctx.requireTokens();
|
|
2294
|
+
const path = `/api/v1/subscriptions/${encodeURIComponent(subscriptionId)}/verify`;
|
|
2295
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2296
|
+
return data;
|
|
2297
|
+
}
|
|
2298
|
+
|
|
2299
|
+
async listSubscriptions() {
|
|
2300
|
+
this._ctx.requireTokens();
|
|
2301
|
+
const path = `/api/v1/subscriptions`;
|
|
2302
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2303
|
+
return data;
|
|
2304
|
+
}
|
|
2305
|
+
|
|
2306
|
+
async listSubscriptionEvents(subscriptionId, { since, limit } = {}) {
|
|
2307
|
+
this._ctx.requireTokens();
|
|
2308
|
+
let path = `/api/v1/subscriptions/${encodeURIComponent(subscriptionId)}/events`;
|
|
2309
|
+
const query = new URLSearchParams();
|
|
2310
|
+
if (since !== undefined) (Array.isArray(since) ? since : [since]).forEach(v => query.append('since', v));
|
|
2311
|
+
if (limit !== undefined) (Array.isArray(limit) ? limit : [limit]).forEach(v => query.append('limit', v));
|
|
2312
|
+
const qs = query.toString();
|
|
2313
|
+
if (qs) path += '?' + qs;
|
|
2314
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2315
|
+
return data;
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
async updateSubscription(subscriptionId, { callbackUrl, targets } = {}) {
|
|
2319
|
+
this._ctx.requireTokens();
|
|
2320
|
+
const path = `/api/v1/subscriptions/${encodeURIComponent(subscriptionId)}`;
|
|
2321
|
+
const body = stripUndef$1({
|
|
2322
|
+
callback_url: callbackUrl,
|
|
2323
|
+
targets: targets,
|
|
2324
|
+
});
|
|
2325
|
+
const { data } = await this._ctx.client.request(path, 'PATCH', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
2326
|
+
return data;
|
|
2327
|
+
}
|
|
2328
|
+
|
|
2329
|
+
async deleteSubscription(subscriptionId) {
|
|
2330
|
+
this._ctx.requireTokens();
|
|
2331
|
+
const path = `/api/v1/subscriptions/${encodeURIComponent(subscriptionId)}`;
|
|
2332
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2333
|
+
return data;
|
|
2334
|
+
}
|
|
2335
|
+
|
|
2336
|
+
async rotateSubscriptionSecret(subscriptionId) {
|
|
2337
|
+
this._ctx.requireTokens();
|
|
2338
|
+
const path = `/api/v1/subscriptions/${encodeURIComponent(subscriptionId)}/rotate_secret`;
|
|
2339
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2340
|
+
return data;
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
function stripUndef(o) { const r = {}; for (const k in o) if (o[k] !== undefined) r[k] = o[k]; return r; }
|
|
2345
|
+
|
|
2346
|
+
class Users {
|
|
2347
|
+
constructor(ctx) { this._ctx = ctx; }
|
|
2348
|
+
|
|
2349
|
+
async createUser(name, email, accountType, companyId = undefined, profilePicture = undefined, paymentPlanType = undefined) {
|
|
2350
|
+
this._ctx.requireTokens();
|
|
2351
|
+
const path = `/api/v1/users/`;
|
|
2352
|
+
const body = stripUndef({
|
|
2353
|
+
name: name,
|
|
2354
|
+
email: email,
|
|
2355
|
+
company_id: companyId,
|
|
2356
|
+
profile_picture: profilePicture,
|
|
2357
|
+
payment_plan_type: paymentPlanType,
|
|
2358
|
+
account_type: accountType,
|
|
2359
|
+
});
|
|
2360
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
2361
|
+
return data;
|
|
2362
|
+
}
|
|
2363
|
+
|
|
2364
|
+
async createUserAndCompany(name, email, password, companyId = undefined, profilePicture = undefined, paymentPlanType = undefined, companyName = undefined, credits = undefined, { inviteToken } = {}) {
|
|
2365
|
+
let path = `/api/v1/users/new_company/`;
|
|
2366
|
+
const query = new URLSearchParams();
|
|
2367
|
+
if (inviteToken !== undefined) (Array.isArray(inviteToken) ? inviteToken : [inviteToken]).forEach(v => query.append('invite_token', v));
|
|
2368
|
+
const qs = query.toString();
|
|
2369
|
+
if (qs) path += '?' + qs;
|
|
2370
|
+
const body = stripUndef({
|
|
2371
|
+
name: name,
|
|
2372
|
+
email: email,
|
|
2373
|
+
company_id: companyId,
|
|
2374
|
+
profile_picture: profilePicture,
|
|
2375
|
+
payment_plan_type: paymentPlanType,
|
|
2376
|
+
password: password,
|
|
2377
|
+
company_name: companyName,
|
|
2378
|
+
credits: credits,
|
|
2379
|
+
});
|
|
2380
|
+
const resp = await fetch(this._ctx.baseUrl + path, {
|
|
2381
|
+
method: 'POST',
|
|
2382
|
+
headers: { 'Content-Type': 'application/json' },
|
|
2383
|
+
body: JSON.stringify(body),
|
|
2384
|
+
});
|
|
2385
|
+
return handleResponse(resp);
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
async changePassword(oldPassword, newPassword) {
|
|
2389
|
+
this._ctx.requireTokens();
|
|
2390
|
+
const path = `/api/v1/user/change_password`;
|
|
2391
|
+
const body = stripUndef({
|
|
2392
|
+
old_password: oldPassword,
|
|
2393
|
+
new_password: newPassword,
|
|
2394
|
+
});
|
|
2395
|
+
const { data } = await this._ctx.client.request(path, 'POST', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
2396
|
+
return data;
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
async getUserId() {
|
|
2400
|
+
this._ctx.requireTokens();
|
|
2401
|
+
const path = `/api/v1/users`;
|
|
2402
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2403
|
+
return data;
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
async getUser(userId) {
|
|
2407
|
+
this._ctx.requireTokens();
|
|
2408
|
+
const path = `/api/v1/users/${encodeURIComponent(userId)}`;
|
|
2409
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2410
|
+
return data;
|
|
2411
|
+
}
|
|
2412
|
+
|
|
2413
|
+
async getAllUsersByCompany(companyId) {
|
|
2414
|
+
this._ctx.requireTokens();
|
|
2415
|
+
const path = `/api/v1/users/company/${encodeURIComponent(companyId)}`;
|
|
2416
|
+
const { data } = await this._ctx.client.request(path, 'GET', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2417
|
+
return data;
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
async updateUser(userId, { name, email, password, companyId, accountType, profilePicture, location, phoneNumber, birthday } = {}) {
|
|
2421
|
+
this._ctx.requireTokens();
|
|
2422
|
+
const path = `/api/v1/users/${encodeURIComponent(userId)}`;
|
|
2423
|
+
const body = stripUndef({
|
|
2424
|
+
name: name,
|
|
2425
|
+
email: email,
|
|
2426
|
+
password: password,
|
|
2427
|
+
company_id: companyId,
|
|
2428
|
+
account_type: accountType,
|
|
2429
|
+
profile_picture: profilePicture,
|
|
2430
|
+
location: location,
|
|
2431
|
+
phone_number: phoneNumber,
|
|
2432
|
+
birthday: birthday,
|
|
2433
|
+
});
|
|
2434
|
+
const { data } = await this._ctx.client.request(path, 'PUT', this._ctx.accessToken, this._ctx.refreshToken, body);
|
|
2435
|
+
return data;
|
|
2436
|
+
}
|
|
2437
|
+
|
|
2438
|
+
async deleteUser(userId, { newCompanyOwnerId } = {}) {
|
|
2439
|
+
this._ctx.requireTokens();
|
|
2440
|
+
let path = `/api/v1/users/delete/${encodeURIComponent(userId)}`;
|
|
2441
|
+
const query = new URLSearchParams();
|
|
2442
|
+
if (newCompanyOwnerId !== undefined) (Array.isArray(newCompanyOwnerId) ? newCompanyOwnerId : [newCompanyOwnerId]).forEach(v => query.append('new_company_owner_id', v));
|
|
2443
|
+
const qs = query.toString();
|
|
2444
|
+
if (qs) path += '?' + qs;
|
|
2445
|
+
const { data } = await this._ctx.client.request(path, 'DELETE', this._ctx.accessToken, this._ctx.refreshToken);
|
|
2446
|
+
return data;
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
// Auto-generated — do not edit
|
|
2451
|
+
|
|
2452
|
+
function _env(key) {
|
|
2453
|
+
if (typeof process !== 'undefined' && process.env) return process.env[key];
|
|
2454
|
+
return undefined;
|
|
2455
|
+
}
|
|
2456
|
+
|
|
2457
|
+
class _Context {
|
|
2458
|
+
constructor(mv) { this._mv = mv; }
|
|
2459
|
+
get client() { return this._mv._oauthClient; }
|
|
2460
|
+
get accessToken() { return this._mv._accessToken; }
|
|
2461
|
+
get refreshToken() { return this._mv._refreshToken; }
|
|
2462
|
+
get baseUrl() { return this._mv._config.baseUrl; }
|
|
2463
|
+
get hosts() { return this._mv._hosts; }
|
|
2464
|
+
get utils() { return this._mv.utils; }
|
|
2465
|
+
requireHost(key) {
|
|
2466
|
+
const url = this._mv._hosts[key];
|
|
2467
|
+
if (!url) throw new Error(`Host '${key}' not configured. Pass hosts.${key} in MediaViz constructor or set the corresponding env var.`);
|
|
2468
|
+
return url;
|
|
2469
|
+
}
|
|
2470
|
+
requireTokens() {
|
|
2471
|
+
if (!this._mv._accessToken) throw new Error('Not authenticated. Call authenticate(), handleCallback(), or setTokens() first.');
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
|
|
2475
|
+
class _TokenTrackingClient {
|
|
2476
|
+
constructor(mv, inner) { this._mv = mv; this._inner = inner; }
|
|
2477
|
+
async request(url, method, accessToken, refreshToken, body) {
|
|
2478
|
+
const onRefreshSuccess = (newTokens) => {
|
|
2479
|
+
this._mv._accessToken = newTokens.access_token;
|
|
2480
|
+
this._mv._refreshToken = newTokens.refresh_token;
|
|
2481
|
+
if (this._mv._onTokenRefresh) this._mv._onTokenRefresh(newTokens);
|
|
2482
|
+
};
|
|
2483
|
+
return this._inner.request(url, method, accessToken, refreshToken, body, onRefreshSuccess);
|
|
2484
|
+
}
|
|
2485
|
+
}
|
|
2486
|
+
|
|
2487
|
+
class _Utils {
|
|
2488
|
+
constructor(mv) { this._mv = mv; }
|
|
2489
|
+
async getMediaAccessQuery(projectTableName) {
|
|
2490
|
+
if (!this._mv._accessToken) throw new Error('Not authenticated. Call authenticate(), handleCallback(), or setTokens() first.');
|
|
2491
|
+
// Memo lives on the _Utils instance, so it is scoped to one MediaViz client
|
|
2492
|
+
// (one authenticated user) — keying on project alone cannot leak across users.
|
|
2493
|
+
if (!this._mediaQueryMemo) this._mediaQueryMemo = new Map();
|
|
2494
|
+
const _nowSec = Date.now() / 1000;
|
|
2495
|
+
const _memo = this._mediaQueryMemo.get(projectTableName);
|
|
2496
|
+
// Re-mint 60s early: an <img> load that starts just before expiry must not race
|
|
2497
|
+
// the policy going stale and 403 mid-flight.
|
|
2498
|
+
if (_memo && _memo.expiresEpoch - 60 > _nowSec) return _memo.result;
|
|
2499
|
+
|
|
2500
|
+
// Through the generated endpoint method, not a bare fetch: this inherits the
|
|
2501
|
+
// oauth client's 401-refresh-and-retry. Errors propagate — without a query
|
|
2502
|
+
// string there is nothing to render.
|
|
2503
|
+
const _result = await this._mv.media.getProjectAccessQuery(projectTableName);
|
|
2504
|
+
|
|
2505
|
+
const _expiresEpoch = Date.parse(_result.expires_at) / 1000;
|
|
2506
|
+
// Skip the memo on an unparseable expiry rather than cache something that can
|
|
2507
|
+
// never be invalidated.
|
|
2508
|
+
if (!Number.isNaN(_expiresEpoch)) {
|
|
2509
|
+
this._mediaQueryMemo.set(projectTableName, { expiresEpoch: _expiresEpoch, result: _result });
|
|
2510
|
+
}
|
|
2511
|
+
return _result;
|
|
2512
|
+
}
|
|
2513
|
+
async authorizeMediaUrl(photoUrl, projectTableName) {
|
|
2514
|
+
if (!this._mv._accessToken) throw new Error('Not authenticated. Call authenticate(), handleCallback(), or setTokens() first.');
|
|
2515
|
+
// Memoized upstream, so calling this once per tile in a grid still costs one
|
|
2516
|
+
// round trip for the whole project.
|
|
2517
|
+
const _access = await this.getMediaAccessQuery(projectTableName);
|
|
2518
|
+
|
|
2519
|
+
// Already signed: return untouched. Appending a second policy yields duplicate
|
|
2520
|
+
// Policy/Signature params and an opaque 403 at the edge, and the caller almost
|
|
2521
|
+
// certainly passed a URL this function already authorized.
|
|
2522
|
+
//
|
|
2523
|
+
// Keyed on Key-Pair-Id, not Policy: the query-string params are Policy /
|
|
2524
|
+
// Signature / Key-Pair-Id (NOT the CloudFront-* spelling the cookie path used),
|
|
2525
|
+
// and 'Policy' alone is generic enough to collide with an unrelated param.
|
|
2526
|
+
if (/[?&]Key-Pair-Id=/.test(photoUrl)) return photoUrl;
|
|
2527
|
+
|
|
2528
|
+
return photoUrl + (photoUrl.includes('?') ? '&' : '?') + _access.query_string;
|
|
2529
|
+
}
|
|
2530
|
+
}
|
|
2531
|
+
|
|
2532
|
+
class MediaViz {
|
|
2533
|
+
constructor(config = {}) {
|
|
2534
|
+
this._config = {
|
|
2535
|
+
clientId: config.clientId ?? _env('MEDIAVIZ_CLIENT_ID'),
|
|
2536
|
+
clientSecret: config.clientSecret ?? _env('MEDIAVIZ_CLIENT_SECRET'),
|
|
2537
|
+
baseUrl: config.baseUrl ?? _env('MEDIAVIZ_BASE_URL') ?? 'https://api.mediaviz.ai',
|
|
2538
|
+
redirectUri: config.redirectUri ?? _env('MEDIAVIZ_REDIRECT_URI'),
|
|
2539
|
+
};
|
|
2540
|
+
this._hosts = {
|
|
2541
|
+
photoUpload: config.hosts?.photoUpload ?? _env('MEDIAVIZ_PHOTO_UPLOAD_URL'),
|
|
2542
|
+
...(config.hosts || {}),
|
|
2543
|
+
};
|
|
2544
|
+
this._accessToken = config.accessToken ?? null;
|
|
2545
|
+
this._refreshToken = config.refreshToken ?? null;
|
|
2546
|
+
this._onTokenRefresh = config.onTokenRefresh ?? null;
|
|
2547
|
+
|
|
2548
|
+
const _inner = new OAuthClient({
|
|
2549
|
+
clientId: this._config.clientId,
|
|
2550
|
+
clientSecret: this._config.clientSecret,
|
|
2551
|
+
baseUrl: this._config.baseUrl,
|
|
2552
|
+
redirectUri: this._config.redirectUri,
|
|
2553
|
+
});
|
|
2554
|
+
this._oauthClient = new _TokenTrackingClient(this, _inner);
|
|
2555
|
+
|
|
2556
|
+
const _ctx = new _Context(this);
|
|
2557
|
+
this.aiModelCredits = new AiModelCredits(_ctx);
|
|
2558
|
+
this.admin = new Admin(_ctx);
|
|
2559
|
+
this.company = new Company(_ctx);
|
|
2560
|
+
this.curatedAlbums = new CuratedAlbums(_ctx);
|
|
2561
|
+
this.customAlbums = new CustomAlbums(_ctx);
|
|
2562
|
+
this.emailTokens = new EmailTokens(_ctx);
|
|
2563
|
+
this.health = new Health(_ctx);
|
|
2564
|
+
this.keywords = new Keywords(_ctx);
|
|
2565
|
+
this.media = new Media(_ctx);
|
|
2566
|
+
this.oAuthAuthorization = new OauthAuthorization(_ctx);
|
|
2567
|
+
this.oAuthToken = new OauthToken(_ctx);
|
|
2568
|
+
this.oauthLogin = new OauthLogin(_ctx);
|
|
2569
|
+
this.person = new Person(_ctx);
|
|
2570
|
+
this.photoUpload = new Photoupload(_ctx);
|
|
2571
|
+
this.photos = new Photos(_ctx);
|
|
2572
|
+
this.projects = new Projects(_ctx);
|
|
2573
|
+
this.search = new Search(_ctx);
|
|
2574
|
+
this.subscription = new Subscription(_ctx);
|
|
2575
|
+
this.users = new Users(_ctx);
|
|
2576
|
+
this.webhooks = new WebhookConsumer(_ctx, this.subscription);
|
|
2577
|
+
this.utils = new _Utils(this);
|
|
2578
|
+
}
|
|
2579
|
+
|
|
2580
|
+
async authenticate() {
|
|
2581
|
+
const tokens = await this._oauthClient._inner.getClientCredentialsToken();
|
|
2582
|
+
this._accessToken = tokens.access_token;
|
|
2583
|
+
this._refreshToken = tokens.refresh_token ?? null;
|
|
2584
|
+
return tokens;
|
|
2585
|
+
}
|
|
2586
|
+
|
|
2587
|
+
async getAuthorizationUrl(state) {
|
|
2588
|
+
return this._oauthClient._inner.generateAuthorizationUrl(state);
|
|
2589
|
+
}
|
|
2590
|
+
|
|
2591
|
+
async handleCallback(code, codeVerifier) {
|
|
2592
|
+
const tokens = await this._oauthClient._inner.exchangeCode(code, codeVerifier);
|
|
2593
|
+
this._accessToken = tokens.access_token;
|
|
2594
|
+
this._refreshToken = tokens.refresh_token;
|
|
2595
|
+
return tokens;
|
|
2596
|
+
}
|
|
2597
|
+
|
|
2598
|
+
setTokens(accessToken, refreshToken) {
|
|
2599
|
+
this._accessToken = accessToken;
|
|
2600
|
+
this._refreshToken = refreshToken;
|
|
2601
|
+
}
|
|
2602
|
+
|
|
2603
|
+
get accessToken() { return this._accessToken; }
|
|
2604
|
+
get refreshToken() { return this._refreshToken; }
|
|
2605
|
+
}
|
|
2606
|
+
|
|
2607
|
+
var crypto;
|
|
2608
|
+
var hasRequiredCrypto;
|
|
2609
|
+
|
|
2610
|
+
function requireCrypto () {
|
|
2611
|
+
if (hasRequiredCrypto) return crypto;
|
|
2612
|
+
hasRequiredCrypto = 1;
|
|
2613
|
+
|
|
2614
|
+
// PKCE crypto for Hermes, which ships no SubtleCrypto and no
|
|
2615
|
+
// crypto.getRandomValues. The native implementation is injected rather than
|
|
2616
|
+
// required here: expo-crypto and react-native-quick-crypto are alternatives,
|
|
2617
|
+
// neither is a hard dependency, and a static require of one would break Metro
|
|
2618
|
+
// for apps that installed the other.
|
|
2619
|
+
|
|
2620
|
+
/**
|
|
2621
|
+
* Builds a provider for the OAuth SDK's configureCrypto().
|
|
2622
|
+
* @param {{getRandomValues: (bytes: Uint8Array) => unknown, digest: (bytes: Uint8Array) => unknown}} impl
|
|
2623
|
+
*/
|
|
2624
|
+
function createCryptoProvider(impl) {
|
|
2625
|
+
const { getRandomValues, digest } = impl ?? {};
|
|
2626
|
+
if (typeof getRandomValues !== 'function') {
|
|
2627
|
+
throw new TypeError('createCryptoProvider requires getRandomValues(bytes)');
|
|
2628
|
+
}
|
|
2629
|
+
if (typeof digest !== 'function') {
|
|
2630
|
+
throw new TypeError('createCryptoProvider requires digest(bytes) => SHA-256 bytes');
|
|
2631
|
+
}
|
|
2632
|
+
return {
|
|
2633
|
+
// expo-crypto fills in place and returns undefined; quick-crypto returns the
|
|
2634
|
+
// array. Normalising here means callers never have to care which they have.
|
|
2635
|
+
getRandomValues: (bytes) => {
|
|
2636
|
+
const filled = getRandomValues(bytes);
|
|
2637
|
+
return filled instanceof Uint8Array ? filled : bytes;
|
|
2638
|
+
},
|
|
2639
|
+
sha256: async (bytes) => toBytes(await digest(bytes)),
|
|
2640
|
+
};
|
|
2641
|
+
}
|
|
2642
|
+
|
|
2643
|
+
// helpers
|
|
2644
|
+
function toBytes(digest) {
|
|
2645
|
+
if (digest instanceof Uint8Array) return digest;
|
|
2646
|
+
if (digest instanceof ArrayBuffer) return new Uint8Array(digest);
|
|
2647
|
+
if (ArrayBuffer.isView(digest)) return new Uint8Array(digest.buffer, digest.byteOffset, digest.byteLength);
|
|
2648
|
+
if (Array.isArray(digest)) return Uint8Array.from(digest);
|
|
2649
|
+
throw new TypeError('digest must resolve to a Uint8Array, ArrayBuffer, typed array, or byte array');
|
|
2650
|
+
}
|
|
2651
|
+
|
|
2652
|
+
crypto = { createCryptoProvider };
|
|
2653
|
+
return crypto;
|
|
2654
|
+
}
|
|
2655
|
+
|
|
2656
|
+
var storage;
|
|
2657
|
+
var hasRequiredStorage;
|
|
2658
|
+
|
|
2659
|
+
function requireStorage () {
|
|
2660
|
+
if (hasRequiredStorage) return storage;
|
|
2661
|
+
hasRequiredStorage = 1;
|
|
2662
|
+
|
|
2663
|
+
// Token persistence.
|
|
2664
|
+
//
|
|
2665
|
+
// Access and refresh tokens are kept under separate keys because
|
|
2666
|
+
// expo-secure-store caps a single value at 2048 bytes and two JWTs in one blob
|
|
2667
|
+
// can cross that. Keychain has no such cap, so it stores one JSON entry.
|
|
2668
|
+
|
|
2669
|
+
const ACCESS_KEY = 'mediaviz.accessToken';
|
|
2670
|
+
const REFRESH_KEY = 'mediaviz.refreshToken';
|
|
2671
|
+
|
|
2672
|
+
/** Non-persistent default. Tokens are lost when the app is killed. */
|
|
2673
|
+
class MemoryTokenStore {
|
|
2674
|
+
constructor() {
|
|
2675
|
+
this._tokens = { accessToken: null, refreshToken: null };
|
|
2676
|
+
}
|
|
2677
|
+
|
|
2678
|
+
async load() {
|
|
2679
|
+
return { ...this._tokens };
|
|
2680
|
+
}
|
|
2681
|
+
|
|
2682
|
+
async save(tokens) {
|
|
2683
|
+
this._tokens = normalize(tokens);
|
|
2684
|
+
}
|
|
2685
|
+
|
|
2686
|
+
async clear() {
|
|
2687
|
+
this._tokens = { accessToken: null, refreshToken: null };
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
|
|
2691
|
+
/**
|
|
2692
|
+
* Backed by expo-secure-store (Keychain on iOS, Keystore on Android).
|
|
2693
|
+
* @param {{getItemAsync: Function, setItemAsync: Function, deleteItemAsync: Function}} SecureStore
|
|
2694
|
+
*/
|
|
2695
|
+
function createSecureTokenStore(SecureStore, options = {}) {
|
|
2696
|
+
requireMethods(SecureStore, ['getItemAsync', 'setItemAsync', 'deleteItemAsync'], 'expo-secure-store');
|
|
2697
|
+
const accessKey = options.accessKey ?? ACCESS_KEY;
|
|
2698
|
+
const refreshKey = options.refreshKey ?? REFRESH_KEY;
|
|
2699
|
+
const opts = options.secureStoreOptions;
|
|
2700
|
+
return {
|
|
2701
|
+
async load() {
|
|
2702
|
+
const [accessToken, refreshToken] = await Promise.all([
|
|
2703
|
+
SecureStore.getItemAsync(accessKey, opts),
|
|
2704
|
+
SecureStore.getItemAsync(refreshKey, opts),
|
|
2705
|
+
]);
|
|
2706
|
+
return { accessToken: accessToken ?? null, refreshToken: refreshToken ?? null };
|
|
2707
|
+
},
|
|
2708
|
+
async save(tokens) {
|
|
2709
|
+
const { accessToken, refreshToken } = normalize(tokens);
|
|
2710
|
+
await Promise.all([
|
|
2711
|
+
writeOrDelete(SecureStore, accessKey, accessToken, opts),
|
|
2712
|
+
writeOrDelete(SecureStore, refreshKey, refreshToken, opts),
|
|
2713
|
+
]);
|
|
2714
|
+
},
|
|
2715
|
+
async clear() {
|
|
2716
|
+
await Promise.all([
|
|
2717
|
+
SecureStore.deleteItemAsync(accessKey, opts),
|
|
2718
|
+
SecureStore.deleteItemAsync(refreshKey, opts),
|
|
2719
|
+
]);
|
|
2720
|
+
},
|
|
2721
|
+
};
|
|
2722
|
+
}
|
|
2723
|
+
|
|
2724
|
+
/**
|
|
2725
|
+
* Backed by react-native-keychain.
|
|
2726
|
+
* @param {{getGenericPassword: Function, setGenericPassword: Function, resetGenericPassword: Function}} Keychain
|
|
2727
|
+
*/
|
|
2728
|
+
function createKeychainTokenStore(Keychain, options = {}) {
|
|
2729
|
+
requireMethods(Keychain, ['getGenericPassword', 'setGenericPassword', 'resetGenericPassword'], 'react-native-keychain');
|
|
2730
|
+
const opts = { service: options.service ?? 'ai.mediaviz.tokens', ...options.keychainOptions };
|
|
2731
|
+
return {
|
|
2732
|
+
async load() {
|
|
2733
|
+
const entry = await Keychain.getGenericPassword(opts);
|
|
2734
|
+
if (!entry || !entry.password) return { accessToken: null, refreshToken: null };
|
|
2735
|
+
return normalize(JSON.parse(entry.password));
|
|
2736
|
+
},
|
|
2737
|
+
async save(tokens) {
|
|
2738
|
+
await Keychain.setGenericPassword('mediaviz', JSON.stringify(normalize(tokens)), opts);
|
|
2739
|
+
},
|
|
2740
|
+
async clear() {
|
|
2741
|
+
await Keychain.resetGenericPassword(opts);
|
|
2742
|
+
},
|
|
2743
|
+
};
|
|
2744
|
+
}
|
|
2745
|
+
|
|
2746
|
+
// helpers
|
|
2747
|
+
function normalize(tokens) {
|
|
2748
|
+
// The OAuth client emits snake_case (access_token); MediaViz getters emit
|
|
2749
|
+
// camelCase. Both reach this store, so both are accepted.
|
|
2750
|
+
const t = tokens ?? {};
|
|
2751
|
+
return {
|
|
2752
|
+
accessToken: t.accessToken ?? t.access_token ?? null,
|
|
2753
|
+
refreshToken: t.refreshToken ?? t.refresh_token ?? null,
|
|
2754
|
+
};
|
|
2755
|
+
}
|
|
2756
|
+
|
|
2757
|
+
function writeOrDelete(SecureStore, key, value, opts) {
|
|
2758
|
+
// A null token must erase the key, not persist the string "null".
|
|
2759
|
+
return value ? SecureStore.setItemAsync(key, value, opts) : SecureStore.deleteItemAsync(key, opts);
|
|
2760
|
+
}
|
|
2761
|
+
|
|
2762
|
+
function requireMethods(mod, names, label) {
|
|
2763
|
+
for (const name of names) {
|
|
2764
|
+
if (typeof mod?.[name] !== 'function') {
|
|
2765
|
+
throw new TypeError(`Expected the ${label} module; it has no ${name}()`);
|
|
2766
|
+
}
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2769
|
+
|
|
2770
|
+
storage = { MemoryTokenStore, createSecureTokenStore, createKeychainTokenStore };
|
|
2771
|
+
return storage;
|
|
2772
|
+
}
|
|
2773
|
+
|
|
2774
|
+
var authSession;
|
|
2775
|
+
var hasRequiredAuthSession;
|
|
2776
|
+
|
|
2777
|
+
function requireAuthSession () {
|
|
2778
|
+
if (hasRequiredAuthSession) return authSession;
|
|
2779
|
+
hasRequiredAuthSession = 1;
|
|
2780
|
+
|
|
2781
|
+
// Authorization Code + PKCE on device.
|
|
2782
|
+
//
|
|
2783
|
+
// The app injects openAuthSession (expo-web-browser's openAuthSessionAsync, or
|
|
2784
|
+
// anything with the same contract), keeping this file free of native
|
|
2785
|
+
// dependencies. The verifier never leaves this function, so there is nothing to
|
|
2786
|
+
// persist across the redirect the way a web app must.
|
|
2787
|
+
|
|
2788
|
+
class AuthSessionError extends Error {
|
|
2789
|
+
constructor(code, message) {
|
|
2790
|
+
super(message);
|
|
2791
|
+
this.name = 'AuthSessionError';
|
|
2792
|
+
this.code = code;
|
|
2793
|
+
}
|
|
2794
|
+
}
|
|
2795
|
+
|
|
2796
|
+
/**
|
|
2797
|
+
* Runs the full interactive login and leaves *mv* authenticated.
|
|
2798
|
+
* @param {object} mv - a MediaViz client
|
|
2799
|
+
* @param {{openAuthSession: Function, redirectUri: string, state?: string, sessionOptions?: object}} options
|
|
2800
|
+
* @returns {Promise<object>} the token response
|
|
2801
|
+
*/
|
|
2802
|
+
async function startAuthSession(mv, options) {
|
|
2803
|
+
const { openAuthSession, redirectUri, state: requestedState, sessionOptions } = options ?? {};
|
|
2804
|
+
if (typeof openAuthSession !== 'function') {
|
|
2805
|
+
throw new TypeError('startAuthSession requires openAuthSession(url, redirectUri, options)');
|
|
2806
|
+
}
|
|
2807
|
+
if (!redirectUri) {
|
|
2808
|
+
throw new TypeError('startAuthSession requires redirectUri');
|
|
2809
|
+
}
|
|
2810
|
+
|
|
2811
|
+
const { url, state, code_verifier: codeVerifier } = await mv.getAuthorizationUrl(requestedState);
|
|
2812
|
+
const result = await openAuthSession(url, redirectUri, sessionOptions);
|
|
2813
|
+
|
|
2814
|
+
const type = result?.type;
|
|
2815
|
+
if (type === 'cancel' || type === 'dismiss') {
|
|
2816
|
+
throw new AuthSessionError('cancelled', 'The user dismissed the sign-in screen.');
|
|
2817
|
+
}
|
|
2818
|
+
if (type !== 'success' || !result?.url) {
|
|
2819
|
+
throw new AuthSessionError('failed', `Sign-in did not complete (result type: ${type ?? 'none'}).`);
|
|
2820
|
+
}
|
|
2821
|
+
|
|
2822
|
+
const params = parseRedirectUrl(result.url);
|
|
2823
|
+
if (params.error) {
|
|
2824
|
+
throw new AuthSessionError(params.error, params.error_description ?? `Authorization failed: ${params.error}`);
|
|
2825
|
+
}
|
|
2826
|
+
// Rejecting a mismatched state is the CSRF defence the whole flow rests on —
|
|
2827
|
+
// it must fail closed, including when the server returns no state at all.
|
|
2828
|
+
if (params.state !== state) {
|
|
2829
|
+
throw new AuthSessionError('state_mismatch', 'Authorization state did not match the request; discarding the response.');
|
|
2830
|
+
}
|
|
2831
|
+
if (!params.code) {
|
|
2832
|
+
throw new AuthSessionError('no_code', 'Authorization redirect carried no code.');
|
|
2833
|
+
}
|
|
2834
|
+
|
|
2835
|
+
return mv.handleCallback(params.code, codeVerifier);
|
|
2836
|
+
}
|
|
2837
|
+
|
|
2838
|
+
/**
|
|
2839
|
+
* Extracts query and fragment params from a redirect URL.
|
|
2840
|
+
*
|
|
2841
|
+
* Hand-rolled because React Native's URL polyfill mis-parses custom schemes
|
|
2842
|
+
* (mediaviz://callback) — the very shape every native redirect URI takes.
|
|
2843
|
+
* @param {string} url
|
|
2844
|
+
* @returns {Record<string, string>}
|
|
2845
|
+
*/
|
|
2846
|
+
function parseRedirectUrl(url) {
|
|
2847
|
+
const out = {};
|
|
2848
|
+
const text = String(url ?? '');
|
|
2849
|
+
const queryStart = text.indexOf('?');
|
|
2850
|
+
const hashStart = text.indexOf('#');
|
|
2851
|
+
if (queryStart !== -1) {
|
|
2852
|
+
const end = hashStart > queryStart ? hashStart : text.length;
|
|
2853
|
+
assign(out, text.slice(queryStart + 1, end));
|
|
2854
|
+
}
|
|
2855
|
+
if (hashStart !== -1) assign(out, text.slice(hashStart + 1));
|
|
2856
|
+
return out;
|
|
2857
|
+
}
|
|
2858
|
+
|
|
2859
|
+
// helpers
|
|
2860
|
+
function assign(out, segment) {
|
|
2861
|
+
for (const pair of segment.split('&')) {
|
|
2862
|
+
if (!pair) continue;
|
|
2863
|
+
const eq = pair.indexOf('=');
|
|
2864
|
+
const key = decode(eq === -1 ? pair : pair.slice(0, eq));
|
|
2865
|
+
if (!key) continue;
|
|
2866
|
+
out[key] = eq === -1 ? '' : decode(pair.slice(eq + 1));
|
|
2867
|
+
}
|
|
2868
|
+
}
|
|
2869
|
+
|
|
2870
|
+
function decode(value) {
|
|
2871
|
+
try {
|
|
2872
|
+
return decodeURIComponent(value.replace(/\+/g, ' '));
|
|
2873
|
+
} catch {
|
|
2874
|
+
// A malformed escape must not take down the whole redirect parse; the
|
|
2875
|
+
// caller's state/code checks still reject anything unusable.
|
|
2876
|
+
return value;
|
|
2877
|
+
}
|
|
2878
|
+
}
|
|
2879
|
+
|
|
2880
|
+
authSession = { startAuthSession, parseRedirectUrl, AuthSessionError };
|
|
2881
|
+
return authSession;
|
|
2882
|
+
}
|
|
2883
|
+
|
|
2884
|
+
var session;
|
|
2885
|
+
var hasRequiredSession;
|
|
2886
|
+
|
|
2887
|
+
function requireSession () {
|
|
2888
|
+
if (hasRequiredSession) return session;
|
|
2889
|
+
hasRequiredSession = 1;
|
|
2890
|
+
|
|
2891
|
+
// The authenticated-session lifecycle, independent of React.
|
|
2892
|
+
//
|
|
2893
|
+
// Everything stateful about being signed in — rehydrating persisted tokens,
|
|
2894
|
+
// keeping the store in step with refresh-token rotation, running the
|
|
2895
|
+
// interactive login, clearing on sign-out — lives here so it can be driven and
|
|
2896
|
+
// tested without a renderer. react.js is a thin binding over this.
|
|
2897
|
+
//
|
|
2898
|
+
// The MediaViz class is injected because this module is copied *into* the
|
|
2899
|
+
// generated package: it cannot name its own host, and MediaViz.js is ESM while
|
|
2900
|
+
// this file is CommonJS.
|
|
2901
|
+
|
|
2902
|
+
const { MemoryTokenStore } = requireStorage();
|
|
2903
|
+
const { startAuthSession } = requireAuthSession();
|
|
2904
|
+
|
|
2905
|
+
/**
|
|
2906
|
+
* @param {{MediaViz: Function, config?: object, store?: object, openAuthSession?: Function, onTokens?: Function}} options
|
|
2907
|
+
*/
|
|
2908
|
+
function createSession(options) {
|
|
2909
|
+
const { MediaViz, config, store, openAuthSession, onTokens } = options ?? {};
|
|
2910
|
+
if (typeof MediaViz !== 'function') throw new TypeError('createSession requires the MediaViz class');
|
|
2911
|
+
|
|
2912
|
+
const tokenStore = store ?? new MemoryTokenStore();
|
|
2913
|
+
const emit = (tokens) => {
|
|
2914
|
+
if (onTokens) onTokens(tokens ?? null);
|
|
2915
|
+
};
|
|
2916
|
+
|
|
2917
|
+
const client = new MediaViz({
|
|
2918
|
+
...config,
|
|
2919
|
+
onTokenRefresh: (tokens) => {
|
|
2920
|
+
emit(tokens);
|
|
2921
|
+
// Fire-and-forget: the refresh already succeeded and the retry is waiting
|
|
2922
|
+
// on this callback, so awaiting the write would stall the request. A
|
|
2923
|
+
// failed write is not worth failing the call over — the next refresh
|
|
2924
|
+
// rewrites it.
|
|
2925
|
+
Promise.resolve(tokenStore.save(tokens)).catch(() => {});
|
|
2926
|
+
},
|
|
2927
|
+
});
|
|
2928
|
+
|
|
2929
|
+
return {
|
|
2930
|
+
client,
|
|
2931
|
+
store: tokenStore,
|
|
2932
|
+
|
|
2933
|
+
/** Loads persisted tokens into the client. Returns them, or null if none. */
|
|
2934
|
+
async restore() {
|
|
2935
|
+
const tokens = await tokenStore.load().catch(() => null);
|
|
2936
|
+
if (!tokens || !tokens.accessToken) return null;
|
|
2937
|
+
client.setTokens(tokens.accessToken, tokens.refreshToken ?? null);
|
|
2938
|
+
emit(tokens);
|
|
2939
|
+
return tokens;
|
|
2940
|
+
},
|
|
2941
|
+
|
|
2942
|
+
async signIn(overrides = {}) {
|
|
2943
|
+
const tokens = await startAuthSession(client, {
|
|
2944
|
+
openAuthSession: overrides.openAuthSession ?? openAuthSession,
|
|
2945
|
+
redirectUri: overrides.redirectUri ?? config?.redirectUri,
|
|
2946
|
+
state: overrides.state,
|
|
2947
|
+
sessionOptions: overrides.sessionOptions,
|
|
2948
|
+
});
|
|
2949
|
+
await tokenStore.save(tokens);
|
|
2950
|
+
emit(tokens);
|
|
2951
|
+
return tokens;
|
|
2952
|
+
},
|
|
2953
|
+
|
|
2954
|
+
async signOut() {
|
|
2955
|
+
client.setTokens(null, null);
|
|
2956
|
+
emit(null);
|
|
2957
|
+
await tokenStore.clear();
|
|
2958
|
+
},
|
|
2959
|
+
};
|
|
2960
|
+
}
|
|
2961
|
+
|
|
2962
|
+
session = { createSession };
|
|
2963
|
+
return session;
|
|
2964
|
+
}
|
|
2965
|
+
|
|
2966
|
+
var src;
|
|
2967
|
+
var hasRequiredSrc;
|
|
2968
|
+
|
|
2969
|
+
function requireSrc () {
|
|
2970
|
+
if (hasRequiredSrc) return src;
|
|
2971
|
+
hasRequiredSrc = 1;
|
|
2972
|
+
|
|
2973
|
+
const { createCryptoProvider } = requireCrypto();
|
|
2974
|
+
const { MemoryTokenStore, createSecureTokenStore, createKeychainTokenStore } = requireStorage();
|
|
2975
|
+
const { startAuthSession, parseRedirectUrl, AuthSessionError } = requireAuthSession();
|
|
2976
|
+
const { createSession } = requireSession();
|
|
2977
|
+
|
|
2978
|
+
src = { createCryptoProvider, MemoryTokenStore, createSecureTokenStore, createKeychainTokenStore, startAuthSession, parseRedirectUrl, AuthSessionError, createSession };
|
|
2979
|
+
return src;
|
|
2980
|
+
}
|
|
2981
|
+
|
|
2982
|
+
var srcExports = requireSrc();
|
|
2983
|
+
var _react_native = /*@__PURE__*/getDefaultExportFromCjs(srcExports);
|
|
2984
|
+
|
|
2985
|
+
// Auto-generated — do not edit
|
|
2986
|
+
const { createCryptoProvider, MemoryTokenStore, createSecureTokenStore, createKeychainTokenStore, startAuthSession, parseRedirectUrl, AuthSessionError, createSession } = _react_native;
|
|
2987
|
+
|
|
2988
|
+
exports.Admin = Admin;
|
|
2989
|
+
exports.AiModelCredits = AiModelCredits;
|
|
2990
|
+
exports.ApiError = ApiError;
|
|
2991
|
+
exports.AuthSessionError = AuthSessionError;
|
|
2992
|
+
exports.Company = Company;
|
|
2993
|
+
exports.CuratedAlbums = CuratedAlbums;
|
|
2994
|
+
exports.CustomAlbums = CustomAlbums;
|
|
2995
|
+
exports.EmailTokens = EmailTokens;
|
|
2996
|
+
exports.Health = Health;
|
|
2997
|
+
exports.InMemoryWebhookStore = InMemoryWebhookStore;
|
|
2998
|
+
exports.Keywords = Keywords;
|
|
2999
|
+
exports.Media = Media;
|
|
3000
|
+
exports.MediaViz = MediaViz;
|
|
3001
|
+
exports.MemoryTokenStore = MemoryTokenStore;
|
|
3002
|
+
exports.NotFoundError = NotFoundError;
|
|
3003
|
+
exports.OAuthClient = OAuthClient;
|
|
3004
|
+
exports.OAuthError = OAuthError;
|
|
3005
|
+
exports.OAuthErrorCode = OAuthErrorCode;
|
|
3006
|
+
exports.OauthAuthorization = OauthAuthorization;
|
|
3007
|
+
exports.OauthLogin = OauthLogin;
|
|
3008
|
+
exports.OauthToken = OauthToken;
|
|
3009
|
+
exports.Person = Person;
|
|
3010
|
+
exports.Photos = Photos;
|
|
3011
|
+
exports.Photoupload = Photoupload;
|
|
3012
|
+
exports.Projects = Projects;
|
|
3013
|
+
exports.RateLimitError = RateLimitError;
|
|
3014
|
+
exports.Search = Search;
|
|
3015
|
+
exports.ServerError = ServerError;
|
|
3016
|
+
exports.Subscription = Subscription;
|
|
3017
|
+
exports.Users = Users;
|
|
3018
|
+
exports.ValidationError = ValidationError;
|
|
3019
|
+
exports.WEBHOOK_MODEL_COLUMNS = WEBHOOK_MODEL_COLUMNS;
|
|
3020
|
+
exports.WEBHOOK_OUTCOME_MODELS = WEBHOOK_OUTCOME_MODELS;
|
|
3021
|
+
exports.WebhookConsumer = WebhookConsumer;
|
|
3022
|
+
exports.configureCrypto = configureCrypto;
|
|
3023
|
+
exports.createCryptoProvider = createCryptoProvider;
|
|
3024
|
+
exports.createKeychainTokenStore = createKeychainTokenStore;
|
|
3025
|
+
exports.createSecureTokenStore = createSecureTokenStore;
|
|
3026
|
+
exports.createSession = createSession;
|
|
3027
|
+
exports.handleResponse = handleResponse;
|
|
3028
|
+
exports.parseRedirectUrl = parseRedirectUrl;
|
|
3029
|
+
exports.selectResultColumns = selectResultColumns;
|
|
3030
|
+
exports.signWebhookPayload = signWebhookPayload;
|
|
3031
|
+
exports.startAuthSession = startAuthSession;
|
|
3032
|
+
exports.verifyWebhookSignature = verifyWebhookSignature;
|