@qaecy/cue-sdk 0.0.5 → 0.0.8

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/cue-y-t8nSnt.js DELETED
@@ -1,353 +0,0 @@
1
- import { initializeApp as D } from "firebase/app";
2
- import { getAuth as S, connectAuthEmulator as C, signInWithEmailAndPassword as T, GoogleAuthProvider as P, OAuthProvider as U, signInWithPopup as O, signInWithCustomToken as j, signOut as v, onAuthStateChanged as N, fetchSignInMethodsForEmail as K, linkWithPopup as R, unlink as $, reauthenticateWithCredential as f, EmailAuthProvider as m, updatePassword as q, linkWithCredential as H, verifyBeforeUpdateEmail as x, sendEmailVerification as L } from "firebase/auth";
3
- import { getFirestore as b, connectFirestoreEmulator as A, doc as _, collection as n, getDoc as y, setDoc as g, getDocs as h, query as l, where as d, serverTimestamp as F, increment as W, addDoc as z, deleteDoc as B, limit as J } from "firebase/firestore";
4
- const M = "microsoft.com";
5
- class V {
6
- _auth;
7
- _endpoints;
8
- constructor(t, e = !1, r) {
9
- this._auth = S(t), this._endpoints = r, e && C(this._auth, r.authEmulatorUrl, {
10
- disableWarnings: !0
11
- });
12
- }
13
- async signIn(t, e) {
14
- if (t === "password") {
15
- if (!e)
16
- throw new Error("credentials are required for password sign-in");
17
- return (await T(
18
- this._auth,
19
- e.email,
20
- e.password
21
- )).user;
22
- }
23
- const r = t === "google" ? new P() : new U(M);
24
- return (await O(this._auth, r)).user;
25
- }
26
- /** Sign in with a Cue API key */
27
- async signInWithApiKey(t, e) {
28
- const r = await fetch(this._endpoints.tokenUrl, {
29
- method: "GET",
30
- headers: {
31
- "x-project-id": e,
32
- "cue-api-key": t
33
- }
34
- });
35
- if (!r.ok)
36
- throw new Error(`Failed to fetch custom token: ${r.statusText}`);
37
- const { token: s } = await r.json();
38
- return (await j(this._auth, s)).user;
39
- }
40
- /** Sign out the current user */
41
- async signOut() {
42
- await v(this._auth);
43
- }
44
- /** Currently signed-in user, or null if not authenticated */
45
- get currentUser() {
46
- return this._auth.currentUser;
47
- }
48
- /** Subscribe to authentication state changes. Returns an unsubscribe function. */
49
- onAuthStateChanged(t) {
50
- return N(this._auth, t);
51
- }
52
- /** Get the Firebase ID token for the current user, or null if not authenticated */
53
- async getToken(t = !1) {
54
- const e = this._auth.currentUser;
55
- return e ? e.getIdToken(t) : null;
56
- }
57
- /** Raw Firebase Auth instance, for advanced use cases */
58
- get firebaseAuth() {
59
- return this._auth;
60
- }
61
- }
62
- const G = "/assistant/search", Q = "/triplestore/query", Y = "/data-views/admin/consumption/units";
63
- class X {
64
- constructor(t, e, r, s) {
65
- this._auth = t, this._gatewayUrl = e, this.projects = r, this.sync = s;
66
- }
67
- _auth;
68
- _gatewayUrl;
69
- projects;
70
- sync;
71
- async _authHeaders() {
72
- return this.getAuthHeaders();
73
- }
74
- /**
75
- * Returns standard authentication headers for the current user.
76
- * Useful when calling Cue-backed services directly (e.g. the GIS proxy).
77
- */
78
- async getAuthHeaders() {
79
- const t = await this._auth.getToken();
80
- if (!t) throw new Error("Not authenticated. Call cue.auth.signIn() first.");
81
- return {
82
- Authorization: `Bearer ${t}`,
83
- "Content-Type": "application/json"
84
- };
85
- }
86
- /**
87
- * Search project documents using natural language.
88
- * The user must be authenticated before calling this.
89
- */
90
- async search(t) {
91
- const e = await this._authHeaders(), r = await fetch(`${this._gatewayUrl}${G}`, {
92
- method: "POST",
93
- headers: e,
94
- body: JSON.stringify({
95
- term: t.term,
96
- projectId: t.projectId,
97
- categories: t.categories ?? []
98
- })
99
- });
100
- if (!r.ok)
101
- throw new Error(`Search request failed: ${r.status} ${r.statusText}`);
102
- return r.json();
103
- }
104
- /**
105
- * Execute a SPARQL query against the project's triplestore.
106
- * The user must be authenticated before calling this.
107
- */
108
- async sparql(t, e) {
109
- const r = await this._authHeaders(), s = await fetch(`${this._gatewayUrl}${Q}`, {
110
- method: "POST",
111
- headers: r,
112
- body: JSON.stringify({ query: t, projectId: e })
113
- });
114
- if (!s.ok)
115
- throw new Error(`SPARQL query failed: ${s.status} ${s.statusText}`);
116
- return s.json();
117
- }
118
- async getConsumption(t) {
119
- const e = await this._authHeaders(), r = await fetch(`${this._gatewayUrl}${Y}`, {
120
- headers: { ...e, "x-project-id": t }
121
- });
122
- if (!r.ok)
123
- throw new Error(`Failed to fetch consumption: ${r.status} ${r.statusText}`);
124
- return r.json();
125
- }
126
- }
127
- const w = "projects";
128
- class Z {
129
- constructor(t, e, r = !1, s) {
130
- if (this._auth = t, this._db = b(e), r) {
131
- const a = s?.firestoreEmulatorHost ?? "localhost", i = s?.firestoreEmulatorPort ?? 8080;
132
- A(this._db, a, i);
133
- }
134
- }
135
- _auth;
136
- _db;
137
- _requireUser() {
138
- const t = this._auth.currentUser;
139
- if (!t) throw new Error("Not authenticated. Call cue.auth.signIn() first.");
140
- return t.uid;
141
- }
142
- /**
143
- * Create a new project. The authenticated user is automatically set as admin, syncer, and member.
144
- * Throws if a project with the given ID already exists.
145
- */
146
- async createProject(t) {
147
- const e = this._requireUser(), r = t.id ?? crypto.randomUUID(), s = (/* @__PURE__ */ new Date()).toISOString(), a = { views: [], chatDisabled: !1 }, i = _(n(this._db, w), r);
148
- if ((await y(i)).exists())
149
- throw new Error(`Project with ID "${r}" already exists.`);
150
- const u = {
151
- id: r,
152
- name: t.name,
153
- organizationID: t.organizationID,
154
- created: s,
155
- lastSync: null,
156
- isPublic: !1,
157
- members: [e],
158
- syncers: [e],
159
- admins: [e],
160
- alternativeIDs: [r],
161
- projectSettings: a
162
- };
163
- return await g(i, u), u;
164
- }
165
- /**
166
- * List all projects where the authenticated user appears in the members, syncers, or admins array.
167
- * Runs three parallel Firestore queries and deduplicates by project ID.
168
- */
169
- async listProjects() {
170
- const t = this._requireUser(), e = n(this._db, w), [r, s, a] = await Promise.all([
171
- h(l(e, d("members", "array-contains", t))),
172
- h(l(e, d("syncers", "array-contains", t))),
173
- h(l(e, d("admins", "array-contains", t)))
174
- ]), i = /* @__PURE__ */ new Set(), o = [];
175
- for (const u of [r, s, a])
176
- for (const k of u.docs) {
177
- const p = k.data();
178
- i.has(p.id) || (i.add(p.id), o.push(p));
179
- }
180
- return o;
181
- }
182
- /** Fetch a single project by ID. Returns null if not found. */
183
- async getProject(t) {
184
- const e = _(n(this._db, w), t), r = await y(e);
185
- return r.exists() ? r.data() : null;
186
- }
187
- /**
188
- * Atomically increments `unitsConsumed` on the top-level `clientSync/{projectId}`
189
- * document, creating it if it doesn't exist. Intended for pre-flight checks.
190
- */
191
- async incrementUnitsConsumed(t, e, r) {
192
- if (e <= 0) return;
193
- const s = _(this._db, "clientSync", t);
194
- await g(s, {
195
- unitsConsumed: W(e),
196
- lastUpdated: F(),
197
- lastUserId: r
198
- }, { merge: !0 });
199
- }
200
- }
201
- const E = "apiKeys";
202
- class tt {
203
- constructor(t, e, r, s, a) {
204
- this._auth = t, this._db = b(e), r && A(this._db, s, a);
205
- }
206
- _auth;
207
- _db;
208
- _apiKeyDocRef;
209
- /** Whether the current user has an active API key. */
210
- async hasAPIKey() {
211
- const t = this._auth.currentUser?.uid;
212
- return t ? this._checkIfUserHasAPIKey(t) : !1;
213
- }
214
- /** Returns the sign-in methods registered for the current user's email. */
215
- async getSignInMethods() {
216
- const t = this._auth.currentUser;
217
- if (!t?.email) throw new Error("User has no e-mail");
218
- return K(this._auth.firebaseAuth, t.email);
219
- }
220
- /** Builds a human-readable label from a Firebase UserInfo provider entry. */
221
- buildProviderLabel(t) {
222
- return t.displayName && t.email ? `${t.displayName} (${t.email})` : t.displayName ?? t.email ?? "-";
223
- }
224
- /** Returns SSO accounts linked to the current user (excludes password). */
225
- getSSOAccounts() {
226
- const t = this._auth.currentUser;
227
- return t ? t.providerData.filter((e) => e.providerId !== "password").map((e) => ({ id: e.providerId, label: this.buildProviderLabel(e) })) : [];
228
- }
229
- /** Links a Google or Microsoft provider to the current account via popup. Returns the new provider label. */
230
- async linkProvider(t) {
231
- const e = this._requireUser(), r = t === "google.com" ? new P() : new U(t), a = (await R(e, r)).user.providerData.find(
232
- (i) => i.providerId === t
233
- );
234
- return a ? this.buildProviderLabel(a) : "-";
235
- }
236
- /** Unlinks a provider from the current account. */
237
- async unlinkProvider(t) {
238
- await $(this._requireUser(), t);
239
- }
240
- /** Changes the password. Reauthenticates first. */
241
- async updatePassword(t, e) {
242
- const r = this._requireUser();
243
- if (!r.email) throw new Error("User has no e-mail");
244
- await f(
245
- r,
246
- m.credential(r.email, t)
247
- ), await q(r, e);
248
- }
249
- /** Adds (sets) a password for an account that currently only uses SSO. */
250
- async addPassword(t) {
251
- const e = this._requireUser();
252
- if (!e.email) throw new Error("User has no e-mail");
253
- await H(e, m.credential(e.email, t));
254
- }
255
- /** Requests an e-mail change. Sends a verification e-mail to the new address. */
256
- async updateEmail(t, e) {
257
- const r = this._requireUser();
258
- if (!r.email) throw new Error("User e-mail not available");
259
- await f(
260
- r,
261
- m.credential(r.email, e)
262
- ), await x(r, t), await L(r);
263
- }
264
- /** Creates a new API key for the current user. */
265
- async createAPIKey(t) {
266
- const e = this._auth.currentUser?.uid;
267
- if (!e) throw new Error("User not authenticated");
268
- const r = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", a = { key: `cue-${Array.from(globalThis.crypto.getRandomValues(new Uint8Array(150)), (o) => r[o & 63]).join("")}`, uid: e, expiration: t }, i = n(this._db, E);
269
- return this._apiKeyDocRef = await z(i, a), a;
270
- }
271
- /** Revokes the current user's API key. */
272
- async revokeAPIKey() {
273
- if (!this._apiKeyDocRef) throw new Error("No API key document reference");
274
- await B(this._apiKeyDocRef), this._apiKeyDocRef = void 0;
275
- }
276
- /** Fetches the current user's existing API key. */
277
- async requestAPIKey() {
278
- if (!this._apiKeyDocRef) throw new Error("No API key document reference");
279
- const t = (await y(this._apiKeyDocRef)).data();
280
- return { key: t.key, expiration: t.expiration };
281
- }
282
- async _checkIfUserHasAPIKey(t) {
283
- const e = n(this._db, E), r = l(e, d("uid", "==", t), J(1)), s = await h(r);
284
- return s.empty || (this._apiKeyDocRef = s.docs[0].ref), !s.empty;
285
- }
286
- _requireUser() {
287
- const t = this._auth.currentUser;
288
- if (!t) throw new Error("Not authenticated");
289
- return t;
290
- }
291
- }
292
- const I = "qaecy-mvp-406413", et = "734737865998", rt = {
293
- production: {
294
- gatewayUrl: "https://accessors-api-gateway-ueyeemwf2a-oa.a.run.app",
295
- tokenUrl: "https://accessors-api-gateway-ueyeemwf2a-oa.a.run.app/token",
296
- authEmulatorUrl: "http://localhost:9099",
297
- storageEmulatorHost: "localhost",
298
- storageEmulatorPort: 9199,
299
- firestoreEmulatorHost: "localhost",
300
- firestoreEmulatorPort: 8080
301
- },
302
- emulator: {
303
- gatewayUrl: "http://localhost:8093",
304
- tokenUrl: "http://localhost:8093/token",
305
- authEmulatorUrl: "http://localhost:9099",
306
- storageEmulatorHost: "localhost",
307
- storageEmulatorPort: 9199,
308
- firestoreEmulatorHost: "localhost",
309
- firestoreEmulatorPort: 8080
310
- }
311
- };
312
- class ot {
313
- auth;
314
- api;
315
- profile;
316
- _app;
317
- _endpoints;
318
- _isEmulator;
319
- constructor(t) {
320
- const e = t.environment ?? "production";
321
- this._endpoints = { ...rt[e], ...t.endpoints }, this._isEmulator = e === "emulator", this._app = D({
322
- apiKey: t.apiKey,
323
- appId: t.appId,
324
- measurementId: t.measurementId,
325
- authDomain: `${I}.firebaseapp.com`,
326
- projectId: I,
327
- messagingSenderId: et
328
- }), this.auth = new V(this._app, this._isEmulator, this._endpoints);
329
- const r = new Z(this.auth, this._app, this._isEmulator, this._endpoints);
330
- this.api = this._buildApi(r), this.profile = new tt(
331
- this.auth,
332
- this._app,
333
- this._isEmulator,
334
- this._endpoints.firestoreEmulatorHost,
335
- this._endpoints.firestoreEmulatorPort
336
- );
337
- }
338
- /** Override in subclasses to provide a custom CueApi (e.g. with sync). */
339
- _buildApi(t) {
340
- return new X(this.auth, this._endpoints.gatewayUrl, t);
341
- }
342
- /** Convenience: get the current user's Firebase ID token */
343
- getToken(t = !1) {
344
- return this.auth.getToken(t);
345
- }
346
- }
347
- export {
348
- ot as C,
349
- X as a,
350
- V as b,
351
- tt as c,
352
- Z as d
353
- };