@lepistabioinformatics/mycelium-sdk 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,711 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ AccountMetaKeySchema: () => AccountMetaKeySchema,
24
+ DEFAULT_CONNECTION_STRING_KEY: () => DEFAULT_CONNECTION_STRING_KEY,
25
+ DEFAULT_EMAIL_KEY: () => DEFAULT_EMAIL_KEY,
26
+ DEFAULT_MYCELIUM_ROLE_KEY: () => DEFAULT_MYCELIUM_ROLE_KEY,
27
+ DEFAULT_PROFILE_KEY: () => DEFAULT_PROFILE_KEY,
28
+ DEFAULT_REQUEST_ID_KEY: () => DEFAULT_REQUEST_ID_KEY,
29
+ DEFAULT_SCOPE_KEY: () => DEFAULT_SCOPE_KEY,
30
+ DEFAULT_TENANT_ID_KEY: () => DEFAULT_TENANT_ID_KEY,
31
+ InsufficientLicensesError: () => InsufficientLicensesError,
32
+ InsufficientPrivilegesError: () => InsufficientPrivilegesError,
33
+ LicensedResourceSchema: () => LicensedResourceSchema,
34
+ LicensedResourcesSchema: () => LicensedResourcesSchema,
35
+ MyceliumError: () => MyceliumError,
36
+ OwnerSchema: () => OwnerSchema,
37
+ Permission: () => Permission,
38
+ PermissionSchema: () => PermissionSchema,
39
+ Profile: () => Profile,
40
+ ProfileDecodingError: () => ProfileDecodingError,
41
+ ProfileMetaSchema: () => ProfileMetaSchema,
42
+ ProfileSchema: () => ProfileSchema,
43
+ TenantOwnershipSchema: () => TenantOwnershipSchema,
44
+ TenantsOwnershipSchema: () => TenantsOwnershipSchema,
45
+ VerboseStatusSchema: () => VerboseStatusSchema,
46
+ compressAndEncodeProfileToBase64: () => compressAndEncodeProfileToBase64,
47
+ decodeAndDecompressProfileFromBase64: () => decodeAndDecompressProfileFromBase64,
48
+ licensedResourceFromUrlString: () => licensedResourceFromUrlString,
49
+ permissionFromInt: () => permissionFromInt,
50
+ permissionToInt: () => permissionToInt,
51
+ safeDecodeAndDecompressProfileFromBase64: () => safeDecodeAndDecompressProfileFromBase64,
52
+ tenantOwnershipFromUrlString: () => tenantOwnershipFromUrlString,
53
+ toLicensesVector: () => toLicensesVector,
54
+ toOwnershipVector: () => toOwnershipVector
55
+ });
56
+ module.exports = __toCommonJS(src_exports);
57
+
58
+ // src/errors.ts
59
+ var MyceliumError = class extends Error {
60
+ code;
61
+ expTrue;
62
+ constructor(message, code, expTrue = false) {
63
+ super(message);
64
+ this.name = "MyceliumError";
65
+ this.code = code;
66
+ this.expTrue = expTrue;
67
+ }
68
+ };
69
+ var InsufficientPrivilegesError = class extends MyceliumError {
70
+ filteringState;
71
+ constructor(message, filteringState = []) {
72
+ super(message, "MYC00019", true);
73
+ this.name = "InsufficientPrivilegesError";
74
+ this.filteringState = filteringState;
75
+ }
76
+ };
77
+ var InsufficientLicensesError = class extends MyceliumError {
78
+ constructor(message = "Insufficient licenses to perform these action") {
79
+ super(message, "MYC00019", true);
80
+ this.name = "InsufficientLicensesError";
81
+ }
82
+ };
83
+ var ProfileDecodingError = class extends MyceliumError {
84
+ constructor(message) {
85
+ super(message, "MYC00020", false);
86
+ this.name = "ProfileDecodingError";
87
+ }
88
+ };
89
+
90
+ // src/settings.ts
91
+ var DEFAULT_PROFILE_KEY = "x-mycelium-profile";
92
+ var DEFAULT_EMAIL_KEY = "x-mycelium-email";
93
+ var DEFAULT_SCOPE_KEY = "x-mycelium-scope";
94
+ var DEFAULT_MYCELIUM_ROLE_KEY = "x-mycelium-role";
95
+ var DEFAULT_REQUEST_ID_KEY = "x-mycelium-request-id";
96
+ var DEFAULT_CONNECTION_STRING_KEY = "x-mycelium-connection-string";
97
+ var DEFAULT_TENANT_ID_KEY = "x-mycelium-tenant-id";
98
+
99
+ // src/models/permission.ts
100
+ var import_zod = require("zod");
101
+ var Permission = {
102
+ READ: 0,
103
+ WRITE: 1
104
+ };
105
+ var PermissionSchema = import_zod.z.union([
106
+ import_zod.z.literal(0),
107
+ import_zod.z.literal(1)
108
+ ]);
109
+ function permissionToInt(permission) {
110
+ return permission;
111
+ }
112
+ function permissionFromInt(value) {
113
+ if (value === Permission.READ || value === Permission.WRITE) {
114
+ return value;
115
+ }
116
+ throw new Error(`Invalid permission code: ${value}`);
117
+ }
118
+
119
+ // src/models/verboseStatus.ts
120
+ var import_zod2 = require("zod");
121
+ var VerboseStatusSchema = import_zod2.z.enum([
122
+ "unverified",
123
+ "verified",
124
+ "inactive",
125
+ "archived",
126
+ "deleted",
127
+ "unknown"
128
+ ]);
129
+
130
+ // src/models/accountMetaKey.ts
131
+ var import_zod3 = require("zod");
132
+ var KNOWN_KEYS = [
133
+ "phone_number",
134
+ "telegram_user",
135
+ "whatsapp_user",
136
+ "locale"
137
+ ];
138
+ var AccountMetaKeySchema = import_zod3.z.string().refine(
139
+ (value) => KNOWN_KEYS.includes(value) || value.startsWith("custom:"),
140
+ {
141
+ message: "must be one of phone_number, telegram_user, whatsapp_user, locale, or a custom:<key> string"
142
+ }
143
+ );
144
+ var ProfileMetaSchema = import_zod3.z.record(AccountMetaKeySchema, import_zod3.z.string());
145
+
146
+ // src/models/owner.ts
147
+ var import_zod4 = require("zod");
148
+ var OwnerSchema = import_zod4.z.object({
149
+ id: import_zod4.z.string().uuid(),
150
+ email: import_zod4.z.string(),
151
+ firstName: import_zod4.z.string().optional(),
152
+ lastName: import_zod4.z.string().optional(),
153
+ username: import_zod4.z.string().optional(),
154
+ isPrincipal: import_zod4.z.boolean()
155
+ });
156
+
157
+ // src/models/licensedResource.ts
158
+ var import_zod5 = require("zod");
159
+ var LicensedResourceSchema = import_zod5.z.object({
160
+ accId: import_zod5.z.string().uuid(),
161
+ sysAcc: import_zod5.z.boolean(),
162
+ tenantId: import_zod5.z.string().uuid(),
163
+ accName: import_zod5.z.string(),
164
+ role: import_zod5.z.string(),
165
+ roleId: import_zod5.z.string().uuid(),
166
+ perm: PermissionSchema,
167
+ verified: import_zod5.z.boolean(),
168
+ permitFlags: import_zod5.z.array(import_zod5.z.string()).optional(),
169
+ denyFlags: import_zod5.z.array(import_zod5.z.string()).optional()
170
+ });
171
+ function licensedResourceFromUrlString(value) {
172
+ let url;
173
+ try {
174
+ url = new URL(value, "http://placeholder.local");
175
+ } catch {
176
+ throw new Error(`Invalid licensed resource URL string: ${value}`);
177
+ }
178
+ const segments = url.pathname.split("/").filter(Boolean);
179
+ if (segments.length !== 6 || segments[0] !== "t" || segments[2] !== "a" || segments[4] !== "r") {
180
+ throw new Error(`Invalid path format in licensed resource URL: ${value}`);
181
+ }
182
+ const tenantId = segments[1];
183
+ const accId = segments[3];
184
+ const roleId = segments[5];
185
+ const pParam = url.searchParams.get("p");
186
+ if (pParam === null) {
187
+ throw new Error(`Parameter 'p' not found in: ${value}`);
188
+ }
189
+ const sepIndex = pParam.lastIndexOf(":");
190
+ if (sepIndex === -1) {
191
+ throw new Error(`Invalid 'p' parameter format in: ${value}`);
192
+ }
193
+ const role = pParam.slice(0, sepIndex);
194
+ const perm = permissionFromInt(Number.parseInt(pParam.slice(sepIndex + 1), 10));
195
+ const sParam = url.searchParams.get("s");
196
+ const vParam = url.searchParams.get("v");
197
+ const nParam = url.searchParams.get("n");
198
+ if (sParam === null || vParam === null || nParam === null) {
199
+ throw new Error(`Missing 's'/'v'/'n' parameter in: ${value}`);
200
+ }
201
+ if (sParam !== "0" && sParam !== "1") {
202
+ throw new Error(`Invalid 's' parameter value in: ${value}`);
203
+ }
204
+ if (vParam !== "0" && vParam !== "1") {
205
+ throw new Error(`Invalid 'v' parameter value in: ${value}`);
206
+ }
207
+ const accName = Buffer.from(nParam, "base64").toString("utf-8");
208
+ const pfParam = url.searchParams.get("pf");
209
+ const dfParam = url.searchParams.get("df");
210
+ return LicensedResourceSchema.parse({
211
+ accId,
212
+ sysAcc: sParam === "1",
213
+ tenantId,
214
+ accName,
215
+ role,
216
+ roleId,
217
+ perm,
218
+ verified: vParam === "1",
219
+ permitFlags: pfParam ? pfParam.split(",") : void 0,
220
+ denyFlags: dfParam ? dfParam.split(",") : void 0
221
+ });
222
+ }
223
+
224
+ // src/models/licensedResources.ts
225
+ var import_zod6 = require("zod");
226
+ function tagRecordsOrUrls(raw) {
227
+ if (raw && typeof raw === "object") {
228
+ const obj = raw;
229
+ const hasRecords = "records" in obj;
230
+ const hasUrls = "urls" in obj;
231
+ if (hasRecords && !hasUrls) {
232
+ return { kind: "records", records: obj.records };
233
+ }
234
+ if (hasUrls && !hasRecords) {
235
+ return { kind: "urls", urls: obj.urls };
236
+ }
237
+ }
238
+ return raw;
239
+ }
240
+ var LicensedResourcesSchema = import_zod6.z.preprocess(
241
+ tagRecordsOrUrls,
242
+ import_zod6.z.discriminatedUnion("kind", [
243
+ import_zod6.z.object({
244
+ kind: import_zod6.z.literal("records"),
245
+ records: import_zod6.z.array(LicensedResourceSchema)
246
+ }),
247
+ import_zod6.z.object({
248
+ kind: import_zod6.z.literal("urls"),
249
+ urls: import_zod6.z.array(import_zod6.z.string())
250
+ })
251
+ ])
252
+ );
253
+ function toLicensesVector(lr) {
254
+ if (!lr) return [];
255
+ if (lr.kind === "records") return lr.records;
256
+ return lr.urls.map(licensedResourceFromUrlString);
257
+ }
258
+
259
+ // src/models/tenantOwnership.ts
260
+ var import_zod7 = require("zod");
261
+ var TenantOwnershipSchema = import_zod7.z.object({
262
+ id: import_zod7.z.string().uuid(),
263
+ name: import_zod7.z.string(),
264
+ since: import_zod7.z.coerce.date()
265
+ });
266
+ function reinsertUuidHyphens(noHyphens) {
267
+ if (!/^[0-9a-fA-F]{32}$/.test(noHyphens)) {
268
+ throw new Error(`Invalid unhyphenated UUID: ${noHyphens}`);
269
+ }
270
+ return [
271
+ noHyphens.slice(0, 8),
272
+ noHyphens.slice(8, 12),
273
+ noHyphens.slice(12, 16),
274
+ noHyphens.slice(16, 20),
275
+ noHyphens.slice(20, 32)
276
+ ].join("-");
277
+ }
278
+ function tenantOwnershipFromUrlString(value) {
279
+ let url;
280
+ try {
281
+ url = new URL(value, "http://placeholder.local");
282
+ } catch {
283
+ throw new Error(`Invalid tenant ownership URL string: ${value}`);
284
+ }
285
+ const segments = url.pathname.split("/").filter(Boolean);
286
+ if (segments.length !== 2 || segments[0] !== "tid") {
287
+ throw new Error(`Invalid path format in tenant ownership URL: ${value}`);
288
+ }
289
+ const id = reinsertUuidHyphens(segments[1]);
290
+ const since = url.searchParams.get("since");
291
+ const nameEncoded = url.searchParams.get("name");
292
+ if (since === null || nameEncoded === null) {
293
+ throw new Error(`Missing 'since'/'name' parameter in: ${value}`);
294
+ }
295
+ const name = Buffer.from(nameEncoded, "base64").toString("utf-8");
296
+ return TenantOwnershipSchema.parse({ id, name, since });
297
+ }
298
+
299
+ // src/models/tenantsOwnership.ts
300
+ var import_zod8 = require("zod");
301
+ function tagRecordsOrUrls2(raw) {
302
+ if (raw && typeof raw === "object") {
303
+ const obj = raw;
304
+ const hasRecords = "records" in obj;
305
+ const hasUrls = "urls" in obj;
306
+ if (hasRecords && !hasUrls) {
307
+ return { kind: "records", records: obj.records };
308
+ }
309
+ if (hasUrls && !hasRecords) {
310
+ return { kind: "urls", urls: obj.urls };
311
+ }
312
+ }
313
+ return raw;
314
+ }
315
+ var TenantsOwnershipSchema = import_zod8.z.preprocess(
316
+ tagRecordsOrUrls2,
317
+ import_zod8.z.discriminatedUnion("kind", [
318
+ import_zod8.z.object({
319
+ kind: import_zod8.z.literal("records"),
320
+ records: import_zod8.z.array(TenantOwnershipSchema)
321
+ }),
322
+ import_zod8.z.object({
323
+ kind: import_zod8.z.literal("urls"),
324
+ urls: import_zod8.z.array(import_zod8.z.string())
325
+ })
326
+ ])
327
+ );
328
+ function toOwnershipVector(to) {
329
+ if (!to) return [];
330
+ if (to.kind === "records") return to.records;
331
+ return to.urls.map(tenantOwnershipFromUrlString);
332
+ }
333
+
334
+ // src/models/profile.ts
335
+ var import_zod9 = require("zod");
336
+ var ProfileSchema = import_zod9.z.object({
337
+ owners: import_zod9.z.array(OwnerSchema).default([]),
338
+ accId: import_zod9.z.string().uuid(),
339
+ isSubscription: import_zod9.z.boolean(),
340
+ isStaff: import_zod9.z.boolean(),
341
+ isManager: import_zod9.z.boolean().default(false),
342
+ ownerIsActive: import_zod9.z.boolean(),
343
+ accountIsActive: import_zod9.z.boolean(),
344
+ accountWasApproved: import_zod9.z.boolean(),
345
+ accountWasArchived: import_zod9.z.boolean(),
346
+ accountWasDeleted: import_zod9.z.boolean(),
347
+ verboseStatus: VerboseStatusSchema.optional(),
348
+ licensedResources: LicensedResourcesSchema.optional(),
349
+ tenantsOwnership: TenantsOwnershipSchema.optional(),
350
+ meta: ProfileMetaSchema.optional(),
351
+ filteringState: import_zod9.z.array(import_zod9.z.string()).optional()
352
+ });
353
+ function appendState(current, entry) {
354
+ const state = current ?? [];
355
+ return [...state, `${state.length + 1}:${entry}`];
356
+ }
357
+ var Profile = class _Profile {
358
+ data;
359
+ constructor(data) {
360
+ this.data = data;
361
+ }
362
+ static fromValidated(data) {
363
+ return new _Profile(data);
364
+ }
365
+ get accId() {
366
+ return this.data.accId;
367
+ }
368
+ get owners() {
369
+ return this.data.owners;
370
+ }
371
+ get isStaff() {
372
+ return this.data.isStaff;
373
+ }
374
+ get isManager() {
375
+ return this.data.isManager;
376
+ }
377
+ get licensedResources() {
378
+ return this.data.licensedResources;
379
+ }
380
+ get tenantsOwnership() {
381
+ return this.data.tenantsOwnership;
382
+ }
383
+ get filteringState() {
384
+ return this.data.filteringState;
385
+ }
386
+ withData(partial) {
387
+ return new _Profile({ ...this.data, ...partial });
388
+ }
389
+ filterLicensedResources(predicate) {
390
+ const records = toLicensesVector(this.data.licensedResources).filter(
391
+ predicate
392
+ );
393
+ return records.length === 0 ? void 0 : { kind: "records", records };
394
+ }
395
+ withPermission(permission) {
396
+ if (!this.data.licensedResources) return this;
397
+ const licensedResources = this.filterLicensedResources(
398
+ (r) => permissionToInt(r.perm) >= permissionToInt(permission)
399
+ );
400
+ return this.withData({
401
+ licensedResources,
402
+ filteringState: appendState(
403
+ this.data.filteringState,
404
+ `permission:${permissionToInt(permission)}`
405
+ )
406
+ });
407
+ }
408
+ withReadAccess() {
409
+ return this.withPermission(Permission.READ);
410
+ }
411
+ withWriteAccess() {
412
+ return this.withPermission(Permission.WRITE);
413
+ }
414
+ onTenant(tenantId) {
415
+ const licensedResources = this.filterLicensedResources(
416
+ (r) => r.tenantId === tenantId
417
+ );
418
+ return this.withData({
419
+ licensedResources,
420
+ filteringState: appendState(
421
+ this.data.filteringState,
422
+ `tenantId:${tenantId}`
423
+ )
424
+ });
425
+ }
426
+ withRoles(roles) {
427
+ const licensedResources = this.filterLicensedResources(
428
+ (r) => roles.includes(r.role)
429
+ );
430
+ return this.withData({
431
+ licensedResources,
432
+ filteringState: appendState(
433
+ this.data.filteringState,
434
+ `role:${roles.join(",")}`
435
+ )
436
+ });
437
+ }
438
+ onAccount(accountId) {
439
+ const licensedResources = this.filterLicensedResources(
440
+ (r) => r.accId === accountId
441
+ );
442
+ return this.withData({
443
+ licensedResources,
444
+ filteringState: appendState(
445
+ this.data.filteringState,
446
+ `accountId:${accountId}`
447
+ )
448
+ });
449
+ }
450
+ hasPermitFlags(flags) {
451
+ const licensedResources = this.filterLicensedResources((r) => {
452
+ if (!r.permitFlags) return false;
453
+ return flags.every((f) => r.permitFlags?.includes(f));
454
+ });
455
+ return this.withData({
456
+ licensedResources,
457
+ filteringState: appendState(
458
+ this.data.filteringState,
459
+ `permittedFlags:${flags.join(",")}`
460
+ )
461
+ });
462
+ }
463
+ hasNotDenyFlags(flags) {
464
+ const licensedResources = this.filterLicensedResources((r) => {
465
+ if (!r.denyFlags) return true;
466
+ return !flags.some((f) => r.denyFlags?.includes(f));
467
+ });
468
+ return this.withData({
469
+ licensedResources,
470
+ filteringState: appendState(
471
+ this.data.filteringState,
472
+ `deniedFlags:${flags.join(",")}`
473
+ )
474
+ });
475
+ }
476
+ onTenantAsManager(tenantId, permission) {
477
+ const profile = this.onTenant(tenantId).withPermission(permission).withRoles(["tenant-manager"]);
478
+ return profile.withData({
479
+ filteringState: appendState(profile.data.filteringState, `isTenantManager:true`)
480
+ });
481
+ }
482
+ withSystemAccountsAccess() {
483
+ const licensedResources = this.filterLicensedResources((r) => r.sysAcc);
484
+ return this.withData({
485
+ licensedResources,
486
+ filteringState: appendState(
487
+ this.data.filteringState,
488
+ `isAccStd:true`
489
+ )
490
+ });
491
+ }
492
+ withTenantOwnershipOrError(tenantId) {
493
+ const tenants = toOwnershipVector(this.data.tenantsOwnership);
494
+ if (tenants.some((t) => t.id === tenantId)) {
495
+ return this.withData({
496
+ filteringState: appendState(
497
+ this.data.filteringState,
498
+ `tenantOwnership:${tenantId}`
499
+ )
500
+ });
501
+ }
502
+ throw new InsufficientPrivilegesError(
503
+ `Insufficient privileges to perform these action (no tenant ownership): ${(this.data.filteringState ?? []).join(", ")}`,
504
+ this.data.filteringState
505
+ );
506
+ }
507
+ hasAdminPrivileges() {
508
+ return this.data.isStaff || this.data.isManager;
509
+ }
510
+ hasAdminPrivilegesOrError() {
511
+ if (!this.hasAdminPrivileges()) {
512
+ throw new InsufficientPrivilegesError(
513
+ "Current account has no administration privileges",
514
+ this.data.filteringState
515
+ );
516
+ }
517
+ }
518
+ getIdsOrError() {
519
+ const ids = toLicensesVector(this.data.licensedResources).map(
520
+ (r) => r.accId
521
+ );
522
+ if (ids.length === 0 && !this.hasAdminPrivileges()) {
523
+ throw new InsufficientPrivilegesError(
524
+ `Insufficient privileges to perform these action (no ids): ${(this.data.filteringState ?? []).join(", ")}`,
525
+ this.data.filteringState
526
+ );
527
+ }
528
+ return ids;
529
+ }
530
+ getTenantWidePermissionOrError(tenantId, permission) {
531
+ if (this.data.isStaff) {
532
+ return { kind: "HasStaffPrivileges" };
533
+ }
534
+ if (this.data.isManager) {
535
+ return { kind: "HasManagerPrivileges" };
536
+ }
537
+ const tenants = toOwnershipVector(this.data.tenantsOwnership);
538
+ if (tenants.some((t) => t.id === tenantId)) {
539
+ return { kind: "HasTenantWidePrivileges", tenantId };
540
+ }
541
+ try {
542
+ this.onTenantAsManager(tenantId, permission).getIdsOrError();
543
+ return { kind: "HasTenantWidePrivileges", tenantId };
544
+ } catch {
545
+ }
546
+ throw new InsufficientPrivilegesError(
547
+ `Insufficient privileges to perform these action (no tenant wide permission): ${(this.data.filteringState ?? []).join(", ")}`,
548
+ this.data.filteringState
549
+ );
550
+ }
551
+ getRelatedAccountsOrTenantWidePermissionOrError(tenantId, permission) {
552
+ try {
553
+ return this.getTenantWidePermissionOrError(tenantId, permission);
554
+ } catch {
555
+ return this.getRelatedAccountOrError();
556
+ }
557
+ }
558
+ getRelatedAccountOrError() {
559
+ if (this.data.isStaff) {
560
+ return { kind: "HasStaffPrivileges" };
561
+ }
562
+ if (this.data.isManager) {
563
+ return { kind: "HasManagerPrivileges" };
564
+ }
565
+ if (this.data.licensedResources) {
566
+ const records = toLicensesVector(this.data.licensedResources);
567
+ if (records.length === 0) {
568
+ throw new InsufficientLicensesError();
569
+ }
570
+ return {
571
+ kind: "AllowedAccounts",
572
+ accounts: records.map((r) => r.accId)
573
+ };
574
+ }
575
+ throw new InsufficientPrivilegesError(
576
+ `Insufficient privileges to perform these action (no accounts): ${(this.data.filteringState ?? []).join(", ")}`,
577
+ this.data.filteringState
578
+ );
579
+ }
580
+ getOwnersIds() {
581
+ return this.data.owners.map((o) => o.id);
582
+ }
583
+ profileString() {
584
+ return `profile/${this.data.accId}`;
585
+ }
586
+ profileRedacted() {
587
+ const redactedEmails = this.data.owners.map((o) => redactEmail(o.email));
588
+ return `profile/${this.data.accId} owners: [${redactedEmails.join(", ")}]`;
589
+ }
590
+ };
591
+ function redactEmail(email) {
592
+ const [local, domain] = email.split("@");
593
+ if (!domain || !local) return email;
594
+ const visible = local.slice(0, 1);
595
+ return `${visible}${"*".repeat(Math.max(local.length - 1, 1))}@${domain}`;
596
+ }
597
+
598
+ // src/functions/decodeAndDecompressProfileFromBase64.ts
599
+ var import_node_zlib = require("zlib");
600
+ function decodeAndDecompressProfileFromBase64(input, opts = {}) {
601
+ const strict = opts.strict ?? true;
602
+ if (typeof input === "string" && input.length === 0 || Buffer.isBuffer(input) && input.length === 0) {
603
+ throw new ProfileDecodingError("Profile input is empty");
604
+ }
605
+ const inputBytes = Buffer.isBuffer(input) ? input : Buffer.from(input, "utf-8");
606
+ const base64Text = inputBytes.toString("utf-8");
607
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64Text) || base64Text.length % 4 !== 0) {
608
+ throw new ProfileDecodingError(
609
+ `Failed to decode base64 profile: not valid base64`
610
+ );
611
+ }
612
+ let decoded;
613
+ try {
614
+ decoded = Buffer.from(base64Text, "base64");
615
+ } catch (cause) {
616
+ throw new ProfileDecodingError(`Failed to decode base64 profile: ${cause}`);
617
+ }
618
+ let decompressed;
619
+ try {
620
+ decompressed = (0, import_node_zlib.zstdDecompressSync)(decoded);
621
+ } catch (cause) {
622
+ if (strict) {
623
+ throw new ProfileDecodingError(
624
+ `Failed to decompress zstd profile: ${cause}`
625
+ );
626
+ }
627
+ decompressed = decoded;
628
+ }
629
+ let profileString;
630
+ try {
631
+ profileString = decompressed.toString("utf-8");
632
+ } catch (cause) {
633
+ throw new ProfileDecodingError(
634
+ `Failed to convert decompressed profile to string: ${cause}`
635
+ );
636
+ }
637
+ let profileJson;
638
+ try {
639
+ profileJson = JSON.parse(profileString);
640
+ } catch (cause) {
641
+ throw new ProfileDecodingError(`Failed to deserialize profile: ${cause}`);
642
+ }
643
+ const result = ProfileSchema.safeParse(profileJson);
644
+ if (!result.success) {
645
+ throw new ProfileDecodingError(
646
+ `Failed to deserialize profile: ${formatZodError(result.error)}`
647
+ );
648
+ }
649
+ return Profile.fromValidated(result.data);
650
+ }
651
+ function safeDecodeAndDecompressProfileFromBase64(input, opts = {}) {
652
+ try {
653
+ const profile = decodeAndDecompressProfileFromBase64(input, opts);
654
+ return { success: true, profile };
655
+ } catch (error) {
656
+ if (error instanceof ProfileDecodingError) {
657
+ return { success: false, error };
658
+ }
659
+ return {
660
+ success: false,
661
+ error: new ProfileDecodingError(String(error))
662
+ };
663
+ }
664
+ }
665
+ function compressAndEncodeProfileToBase64(profile) {
666
+ const json = JSON.stringify(profile.data);
667
+ const compressed = (0, import_node_zlib.zstdCompressSync)(Buffer.from(json, "utf-8"));
668
+ return compressed.toString("base64");
669
+ }
670
+ function formatZodError(error) {
671
+ return error.issues.map((issue) => {
672
+ const path = issue.path.length > 0 ? issue.path.join(".") : "(root)";
673
+ return `field '${path}' ${issue.message}`;
674
+ }).join("; ");
675
+ }
676
+ // Annotate the CommonJS export names for ESM import in node:
677
+ 0 && (module.exports = {
678
+ AccountMetaKeySchema,
679
+ DEFAULT_CONNECTION_STRING_KEY,
680
+ DEFAULT_EMAIL_KEY,
681
+ DEFAULT_MYCELIUM_ROLE_KEY,
682
+ DEFAULT_PROFILE_KEY,
683
+ DEFAULT_REQUEST_ID_KEY,
684
+ DEFAULT_SCOPE_KEY,
685
+ DEFAULT_TENANT_ID_KEY,
686
+ InsufficientLicensesError,
687
+ InsufficientPrivilegesError,
688
+ LicensedResourceSchema,
689
+ LicensedResourcesSchema,
690
+ MyceliumError,
691
+ OwnerSchema,
692
+ Permission,
693
+ PermissionSchema,
694
+ Profile,
695
+ ProfileDecodingError,
696
+ ProfileMetaSchema,
697
+ ProfileSchema,
698
+ TenantOwnershipSchema,
699
+ TenantsOwnershipSchema,
700
+ VerboseStatusSchema,
701
+ compressAndEncodeProfileToBase64,
702
+ decodeAndDecompressProfileFromBase64,
703
+ licensedResourceFromUrlString,
704
+ permissionFromInt,
705
+ permissionToInt,
706
+ safeDecodeAndDecompressProfileFromBase64,
707
+ tenantOwnershipFromUrlString,
708
+ toLicensesVector,
709
+ toOwnershipVector
710
+ });
711
+ //# sourceMappingURL=index.cjs.map