@happyvertical/smrt-users 0.70.0 → 0.70.2

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.
@@ -0,0 +1,716 @@
1
+ import { n as getRuntimePermissionRegistrations } from "./permission-registry-PhcdZvKe.js";
2
+ import { ObjectRegistry, SmrtCollection, SmrtObject, field, findManifestEntryByQualifiedName, inheritedCollectionSurface, isEmbeddedDatabase, resolveOperationPermissionAlias, smrt, withEmbeddedWriteTransaction } from "@happyvertical/smrt-core";
3
+ import { getPackageConfig } from "@happyvertical/smrt-config";
4
+ //#region src/models/Permission.ts
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
8
+ enumerable: true,
9
+ configurable: true,
10
+ writable: true,
11
+ value
12
+ }) : obj[key] = value;
13
+ var __decorateClass = (decorators, target, key, kind) => {
14
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
15
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
16
+ if (kind && result) __defProp(target, key, result);
17
+ return result;
18
+ };
19
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
20
+ function parsePermissionSlug(slug) {
21
+ const parts = slug.split(".");
22
+ if (parts.length >= 2 && parts.every(Boolean)) return {
23
+ resource: parts[0],
24
+ action: parts.slice(1).join("."),
25
+ isValid: true
26
+ };
27
+ return {
28
+ resource: slug,
29
+ action: "",
30
+ isValid: false
31
+ };
32
+ }
33
+ function isValidPermissionSlug(slug) {
34
+ return parsePermissionSlug(slug).isValid;
35
+ }
36
+ var Permission = class extends SmrtObject {
37
+ name = "";
38
+ description = "";
39
+ category = "";
40
+ constructor(options = {}) {
41
+ super(options);
42
+ if (options.name !== void 0) this.name = options.name;
43
+ if (options.description !== void 0) this.description = options.description;
44
+ if (options.category !== void 0) this.category = options.category;
45
+ }
46
+ /**
47
+ * Parse the permission slug into resource and action components.
48
+ * @returns Parsed slug with resource, action, and validation status
49
+ */
50
+ parseSlug() {
51
+ return parsePermissionSlug(this.slug ?? "");
52
+ }
53
+ /**
54
+ * Get the resource part of the permission slug
55
+ * e.g., 'articles.create' -> 'articles'
56
+ */
57
+ getResource() {
58
+ return this.parseSlug().resource;
59
+ }
60
+ /**
61
+ * Get the action part of the permission slug
62
+ * e.g., 'articles.create' -> 'create'
63
+ */
64
+ getAction() {
65
+ return this.parseSlug().action;
66
+ }
67
+ /**
68
+ * Check if the permission slug is valid (follows 'resource.action' pattern)
69
+ */
70
+ isValidSlug() {
71
+ return this.parseSlug().isValid;
72
+ }
73
+ };
74
+ __publicField(Permission, "__smrtPackage__", "@happyvertical/smrt-users");
75
+ __decorateClass([field({ description: "The name of an action people can be allowed to perform." })], Permission.prototype, "name", 2);
76
+ __decorateClass([field({ description: "What this permission allows someone to do." })], Permission.prototype, "description", 2);
77
+ __decorateClass([field({ description: "The area of the application this permission belongs to." })], Permission.prototype, "category", 2);
78
+ Permission = __decorateClass([smrt({
79
+ api: { include: ["list", "get"] },
80
+ mcp: { include: ["list", "get"] },
81
+ cli: { include: ["list", "get"] }
82
+ })], Permission);
83
+ //#endregion
84
+ //#region src/collections/PermissionCollection.ts
85
+ var PermissionCollection = class extends SmrtCollection {
86
+ static _itemClass = Permission;
87
+ /**
88
+ * Find permissions by category
89
+ */
90
+ async findByCategory(category) {
91
+ return await this.list({
92
+ where: { category },
93
+ orderBy: "slug ASC"
94
+ });
95
+ }
96
+ /**
97
+ * Find permission by slug
98
+ */
99
+ async findBySlug(slug) {
100
+ const results = await this.list({
101
+ where: { slug },
102
+ limit: 1
103
+ });
104
+ return results.length > 0 ? results[0] : null;
105
+ }
106
+ /**
107
+ * Batch fetch permissions by IDs
108
+ * Returns a Map of id -> Permission for efficient lookup
109
+ */
110
+ async findByIds(ids) {
111
+ if (ids.length === 0) return /* @__PURE__ */ new Map();
112
+ const uniqueIds = [...new Set(ids)];
113
+ const placeholders = uniqueIds.map(() => "?").join(", ");
114
+ const results = await this.query(`SELECT * FROM ${this.tableName} WHERE id IN (${placeholders})`, uniqueIds);
115
+ const map = /* @__PURE__ */ new Map();
116
+ for (const perm of results) if (perm.id) map.set(perm.id, perm);
117
+ return map;
118
+ }
119
+ /**
120
+ * Get all unique categories
121
+ */
122
+ async getCategories() {
123
+ return (await this.query(`SELECT DISTINCT category FROM ${this.tableName} WHERE category != '' ORDER BY category ASC`)).map((r) => r.category);
124
+ }
125
+ /**
126
+ * Find or create a permission by slug
127
+ */
128
+ async findOrCreate(slug, defaults = {}) {
129
+ const existing = await this.findBySlug(slug);
130
+ if (existing) return existing;
131
+ return await this.create({
132
+ slug,
133
+ name: defaults.name ?? slug,
134
+ description: defaults.description ?? "",
135
+ category: defaults.category ?? slug.split(".")[0]
136
+ });
137
+ }
138
+ };
139
+ //#endregion
140
+ //#region src/services/authorization-read-options.ts
141
+ function withoutListBounds(options) {
142
+ return {
143
+ ...options,
144
+ defaultListLimit: void 0,
145
+ maxListLimit: void 0
146
+ };
147
+ }
148
+ async function writeInSeedingBatches(db, items, write) {
149
+ for (let start = 0; start < items.length; start += 50) {
150
+ const batch = items.slice(start, start + 50);
151
+ if (typeof db.transaction !== "function") {
152
+ await write(db, batch);
153
+ continue;
154
+ }
155
+ await withEmbeddedWriteTransaction(db, isEmbeddedDatabase(db), (database) => write(database, batch), true);
156
+ }
157
+ }
158
+ //#endregion
159
+ //#region src/services/PermissionCatalogService.ts
160
+ function toSnakeCase(value) {
161
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase();
162
+ }
163
+ function pluralize(word) {
164
+ if (word.endsWith("y") && !/[aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
165
+ if (word.endsWith("s") || word.endsWith("x") || word.endsWith("z") || word.endsWith("ch") || word.endsWith("sh")) return `${word}es`;
166
+ return `${word}s`;
167
+ }
168
+ function deriveCollectionName(className) {
169
+ return pluralize(toSnakeCase(className));
170
+ }
171
+ function humanizeResource(resource) {
172
+ return resource.replace(/[._-]+/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
173
+ }
174
+ function capitalize(value) {
175
+ return `${value[0]?.toUpperCase() ?? ""}${value.slice(1)}`;
176
+ }
177
+ function defaultPermissionName(slug) {
178
+ const parsed = parsePermissionSlug(slug);
179
+ if (!parsed.isValid) return humanizeResource(slug);
180
+ return `${humanizeResource(parsed.action)} ${humanizeResource(parsed.resource)}`;
181
+ }
182
+ function defaultPermissionDescription(slug) {
183
+ const parsed = parsePermissionSlug(slug);
184
+ if (!parsed.isValid) return `Allows ${slug}`;
185
+ return `Allows ${humanizeResource(parsed.action).toLowerCase()} access for ${humanizeResource(parsed.resource).toLowerCase()}`;
186
+ }
187
+ function normalizeOperationPermissionAction(action) {
188
+ const trimmed = action.trim();
189
+ const lower = trimmed.toLowerCase();
190
+ if (lower === "list" || lower === "get") return "read";
191
+ if (lower === "read" || lower === "create" || lower === "update" || lower === "delete") return lower;
192
+ return trimmed;
193
+ }
194
+ function isConstructorLike(value) {
195
+ return typeof value === "function";
196
+ }
197
+ function isCollectionLike(value) {
198
+ return typeof value === "object" && value !== null && typeof value.getItemClass === "function";
199
+ }
200
+ function resolveConstructor(value) {
201
+ if (isConstructorLike(value)) return value;
202
+ if (isCollectionLike(value)) return value.getItemClass?.();
203
+ if (typeof value === "object" && value !== null) {
204
+ const ctor = value.constructor;
205
+ if (typeof ctor === "function" && ctor.name && ctor.name !== "Object") return ctor;
206
+ }
207
+ }
208
+ function deriveOperationPermissionCollectionName(input) {
209
+ if (typeof input === "string") {
210
+ const collection = input.trim();
211
+ if (!collection) throw new Error("Operation permission collection must not be empty.");
212
+ return collection;
213
+ }
214
+ const ctor = resolveConstructor(input);
215
+ if (!ctor?.name) throw new Error("Operation permission collection must be a collection slug, model class, model instance, or collection instance.");
216
+ const registered = ObjectRegistry.getClassByConstructor(ctor) ?? ObjectRegistry.getClass(ctor.name);
217
+ if (!registered) return deriveCollectionName(ctor.name);
218
+ return resolveCollectionName(registered, manifestEntryFor(registered), (target) => target.collection ?? deriveCollectionName(target.name));
219
+ }
220
+ function deriveOperationPermissionSlug(collection, action) {
221
+ const collectionName = deriveOperationPermissionCollectionName(collection);
222
+ const standard = normalizeOperationPermissionAction(action);
223
+ if ([
224
+ "read",
225
+ "create",
226
+ "update",
227
+ "delete"
228
+ ].includes(standard)) return `${collectionName}.${standard}`;
229
+ const ctor = typeof collection === "string" ? void 0 : resolveConstructor(collection);
230
+ const registered = ctor ? ObjectRegistry.getClassByConstructor(ctor) ?? ObjectRegistry.getClass(ctor.name ?? "") : void 0;
231
+ if (registered) {
232
+ const normalizedAction2 = normalizeOperationPermissionAction(resolveOperationPermissionAlias(manifestEntryFor(registered)?.decoratorConfig ?? registered.config, action)?.action ?? action);
233
+ if (!normalizedAction2) throw new Error("Operation permission action must not be empty.");
234
+ return `${collectionName}.${normalizedAction2}`;
235
+ }
236
+ const actions = /* @__PURE__ */ new Set();
237
+ for (const registered2 of new Set(ObjectRegistry.getAllClasses().values())) {
238
+ const entry = manifestEntryFor(registered2);
239
+ const owner = entry && isCollectionClass(registered2, entry) ? resolveCollectionItemRegistration(registered2, entry) : registered2;
240
+ if (!owner || resolveCatalogCollectionName(owner, manifestEntryFor(owner)) !== collectionName) continue;
241
+ const alias = resolveOperationPermissionAlias(entry?.decoratorConfig ?? registered2.config, action);
242
+ if (alias) {
243
+ actions.add(alias.action);
244
+ continue;
245
+ }
246
+ if (getPublicCustomMethodNames(entry?.methods ? Object.values(entry.methods) : Array.from(registered2.methods.entries()), [
247
+ "list",
248
+ "get",
249
+ "create",
250
+ "update",
251
+ "delete"
252
+ ]).includes(action)) actions.add(action);
253
+ }
254
+ if (actions.size > 1) throw new Error("Ambiguous operation permission alias");
255
+ const normalizedAction = normalizeOperationPermissionAction([...actions][0] ?? action);
256
+ if (!normalizedAction) throw new Error("Operation permission action must not be empty.");
257
+ return `${collectionName}.${normalizedAction}`;
258
+ }
259
+ function manifestEntryFor(registered) {
260
+ return registered.qualifiedName ? findManifestEntryByQualifiedName(registered.qualifiedName) : void 0;
261
+ }
262
+ function registeredStiBase(registered) {
263
+ let base;
264
+ for (let parent = Object.getPrototypeOf(registered.constructor); parent && parent !== Function.prototype; parent = Object.getPrototypeOf(parent)) {
265
+ const ancestor = ObjectRegistry.getClassByConstructor(parent);
266
+ if (ancestor?.config?.tableStrategy === "sti") base = ancestor;
267
+ }
268
+ return base === registered ? void 0 : base;
269
+ }
270
+ function resolveCollectionName(registered, manifestEntry, fallback) {
271
+ const rawCollection = (manifestEntry?.decoratorConfig ?? registered.config)?.collection;
272
+ if (typeof rawCollection === "string" && rawCollection.length > 0) return rawCollection;
273
+ if (manifestEntry?.collection) return manifestEntry.collection;
274
+ const stiBase = registeredStiBase(registered);
275
+ return stiBase ? resolveCollectionName(stiBase, manifestEntryFor(stiBase), fallback) : fallback(registered);
276
+ }
277
+ function resolveCatalogCollectionName(registered, manifestEntry) {
278
+ return resolveCollectionName(registered, manifestEntry, (target) => deriveCollectionName(target.name));
279
+ }
280
+ function packagePrefix(qualifiedName) {
281
+ const separator = qualifiedName?.lastIndexOf(":") ?? -1;
282
+ return qualifiedName && separator > 0 ? qualifiedName.slice(0, separator) : void 0;
283
+ }
284
+ function findCatalogClass(name, nearQualifiedName) {
285
+ if (name.includes(":")) return ObjectRegistry.getClassByQualifiedName(name);
286
+ const prefix = packagePrefix(nearQualifiedName);
287
+ return (prefix ? ObjectRegistry.getClassByQualifiedName(`${prefix}:${name}`) : void 0) ?? ObjectRegistry.getClass(name);
288
+ }
289
+ function collectCatalogAncestry(registered, manifestEntry) {
290
+ const chain = [];
291
+ const seen = /* @__PURE__ */ new Set();
292
+ let current = manifestEntry ? {
293
+ entry: manifestEntry,
294
+ registered
295
+ } : void 0;
296
+ while (current && chain.length < 32) {
297
+ const key = current.registered.qualifiedName ?? current.registered.name;
298
+ if (seen.has(key)) break;
299
+ seen.add(key);
300
+ chain.push(current);
301
+ const parentName = current.entry.extendsQualified || current.entry.extends || void 0;
302
+ if (!parentName || parentName === "SmrtCollection") break;
303
+ const parent = findCatalogClass(parentName, current.registered.qualifiedName);
304
+ const parentEntry = parent?.qualifiedName ? findManifestEntryByQualifiedName(parent.qualifiedName) : void 0;
305
+ current = parent && parentEntry ? {
306
+ entry: parentEntry,
307
+ registered: parent
308
+ } : void 0;
309
+ }
310
+ return chain;
311
+ }
312
+ function isCollectionClass(registered, manifestEntry) {
313
+ return collectCatalogAncestry(registered, manifestEntry).some(({ entry }) => isCollectionManifestEntry(entry));
314
+ }
315
+ function resolveCollectionItemRegistration(registered, manifestEntry) {
316
+ const ancestry = collectCatalogAncestry(registered, manifestEntry);
317
+ for (const { entry, registered: ancestor } of ancestry) {
318
+ const typeArg = entry.extendsTypeArg;
319
+ if (typeof typeArg === "string" && typeArg.length > 0) return findCatalogClass(typeArg, ancestor.qualifiedName);
320
+ }
321
+ for (const { registered: ancestor } of ancestry) {
322
+ if (!ancestor.name.endsWith("Collection")) continue;
323
+ const item = findCatalogClass(ancestor.name.slice(0, -10), ancestor.qualifiedName);
324
+ if (item) return item;
325
+ }
326
+ }
327
+ function getCollectionClassActionDefinitions(registered, manifestEntry, standardActions) {
328
+ if (!manifestEntry) return [];
329
+ const item = resolveCollectionItemRegistration(registered, manifestEntry);
330
+ if (!item) return [];
331
+ const itemEntry = item.qualifiedName ? findManifestEntryByQualifiedName(item.qualifiedName) : void 0;
332
+ if (isCollectionClass(item, itemEntry)) return [];
333
+ const collection = resolveCatalogCollectionName(item, itemEntry);
334
+ const objectConfig = manifestEntry.decoratorConfig ?? registered.config;
335
+ const methodEntries = manifestEntry.methods ? Object.values(manifestEntry.methods) : Array.from(registered.methods.entries());
336
+ const catalogApi = ownCollectionApiConfig(objectConfig?.api, manifestEntry, itemEntry);
337
+ return getPublicCustomMethodNames(methodEntries, standardActions).filter((methodName) => isOperationEnabled(catalogApi, methodName)).map((methodName) => {
338
+ const alias = resolveOperationPermissionAlias(objectConfig, methodName);
339
+ const action = alias?.action ?? methodName;
340
+ const definition = {
341
+ className: item.name,
342
+ collection,
343
+ description: `Allows ${action} on ${humanizeResource(collection).toLowerCase()}`,
344
+ name: `${capitalize(action)} ${humanizeResource(collection)}`,
345
+ qualifiedName: item.qualifiedName,
346
+ slug: `${collection}.${action}`
347
+ };
348
+ addAliasDatabaseBindings(definition, alias, item, itemEntry);
349
+ return definition;
350
+ });
351
+ }
352
+ function ownCollectionApiConfig(apiConfig, collectionEntry, itemEntry) {
353
+ if (apiConfig === void 0 || apiConfig === false || !itemEntry) return apiConfig;
354
+ const inherited = inheritedCollectionSurface("api", itemEntry.decoratorConfig ?? {}, {
355
+ collection: new Set(Object.keys(collectionEntry.methods ?? {})),
356
+ item: new Set(Object.keys(itemEntry.methods ?? {}))
357
+ });
358
+ return inherited !== void 0 && inherited !== false && JSON.stringify(inherited) === JSON.stringify(apiConfig) ? void 0 : apiConfig;
359
+ }
360
+ function addAliasDatabaseBindings(definition, alias, registered, manifestEntry) {
361
+ if (!alias?.databaseActions?.length) return;
362
+ const tableName = manifestEntry?.schema?.tableName ?? registered.schema?.tableName ?? registered.config.tableName;
363
+ if (!tableName) throw new Error("Permission SQL binding requires a table name");
364
+ mergeBindings(definition, {
365
+ slug: definition.slug,
366
+ postgres: { bindings: alias.databaseActions.map((action) => ({
367
+ action,
368
+ tableName,
369
+ ...registered.tenantScopedConfig?.field ? { tenantField: toSnakeCase(registered.tenantScopedConfig.field) } : {}
370
+ })) }
371
+ });
372
+ }
373
+ function isCollectionManifestEntry(objectDef) {
374
+ return objectDef?.extends === "SmrtCollection" || objectDef?.extendsTypeArg !== void 0;
375
+ }
376
+ function isMethodEntryTuple(method) {
377
+ return Array.isArray(method);
378
+ }
379
+ function normalizeMethodCandidate(method) {
380
+ if (isMethodEntryTuple(method)) {
381
+ const [name, definition] = method;
382
+ return {
383
+ ...definition,
384
+ name: definition.name ?? name
385
+ };
386
+ }
387
+ return method;
388
+ }
389
+ function getPublicCustomMethodNames(methodEntries, standardActions) {
390
+ return Array.from(new Set(methodEntries.flatMap((method) => {
391
+ const { isPublic, name } = normalizeMethodCandidate(method);
392
+ if (!name || isPublic !== true || standardActions.includes(name)) return [];
393
+ return [name];
394
+ })));
395
+ }
396
+ function getCustomMethodExposureNames(config, availableCustomMethods) {
397
+ if (!config || config === false) return /* @__PURE__ */ new Set();
398
+ if (config === true || typeof config !== "object") return new Set(availableCustomMethods);
399
+ const rawInclude = config.include;
400
+ const include = Array.isArray(rawInclude) ? [...rawInclude] : void 0;
401
+ const rawExclude = config.exclude;
402
+ const exclude = Array.isArray(rawExclude) ? [...rawExclude] : [];
403
+ if (!include) return new Set(availableCustomMethods.filter((methodName) => !exclude.includes(methodName)));
404
+ const baseMethods = include.filter((methodName) => availableCustomMethods.includes(methodName));
405
+ return new Set(baseMethods.filter((methodName) => !exclude.includes(methodName)));
406
+ }
407
+ var USERS_AUTHORITY_CATALOG_MODELS = new Set([
408
+ "Group",
409
+ "GroupMember",
410
+ "GroupRole",
411
+ "Membership",
412
+ "MembershipOverride",
413
+ "Permission",
414
+ "ResourceGrant",
415
+ "Role",
416
+ "RolePermission",
417
+ "Session",
418
+ "Tenant",
419
+ "TenantIntegration",
420
+ "TenantPermissionOverride",
421
+ "User",
422
+ "UsersMagicLinkToken"
423
+ ].map((className) => `@happyvertical/smrt-users:${className}`));
424
+ function isOperationEnabled(config, action) {
425
+ if (config === false) return false;
426
+ if (config && typeof config === "object") {
427
+ const include = Array.isArray(config.include) ? config.include : void 0;
428
+ const rawExclude = config.exclude;
429
+ const exclude = Array.isArray(rawExclude) ? [...rawExclude] : [];
430
+ if (include && !include.includes(action)) return false;
431
+ if (exclude.includes(action)) return false;
432
+ }
433
+ return true;
434
+ }
435
+ function normalizePostgresAction(action) {
436
+ const normalized = action.toUpperCase();
437
+ if (normalized === "SELECT" || normalized === "INSERT" || normalized === "UPDATE" || normalized === "DELETE") return normalized;
438
+ throw new Error(`Unsupported Postgres permission action '${action}'. Expected SELECT, INSERT, UPDATE, or DELETE.`);
439
+ }
440
+ function normalizeBinding(binding, fallbackPermission) {
441
+ return {
442
+ action: normalizePostgresAction(binding.action),
443
+ permission: binding.permission || fallbackPermission,
444
+ schemaName: binding.schemaName,
445
+ tableName: binding.tableName,
446
+ tenantField: binding.tenantField
447
+ };
448
+ }
449
+ function mergeStringField(fieldName, existing, incoming, slug) {
450
+ const existingValue = existing[fieldName];
451
+ const incomingValue = incoming[fieldName];
452
+ if (!incomingValue) return;
453
+ if (!existingValue) {
454
+ existing[fieldName] = incomingValue;
455
+ return;
456
+ }
457
+ if (existingValue !== incomingValue) throw new Error(`Conflicting permission metadata for '${slug}' field '${fieldName}': '${existingValue}' !== '${incomingValue}'`);
458
+ }
459
+ function mergeBindings(existing, incoming) {
460
+ const existingBindings = existing.postgres?.bindings ?? [];
461
+ const incomingBindings = incoming.postgres?.bindings ?? [];
462
+ if (incomingBindings.length === 0) return;
463
+ const seen = new Set(existingBindings.map((binding) => [
464
+ binding.permission,
465
+ binding.action,
466
+ binding.schemaName ?? "",
467
+ binding.tableName,
468
+ binding.tenantField ?? ""
469
+ ].join("|")));
470
+ const mergedBindings = [...existingBindings];
471
+ for (const binding of incomingBindings) {
472
+ const normalized = normalizeBinding(binding, incoming.slug);
473
+ const key = [
474
+ normalized.permission,
475
+ normalized.action,
476
+ normalized.schemaName ?? "",
477
+ normalized.tableName,
478
+ normalized.tenantField ?? ""
479
+ ].join("|");
480
+ if (!seen.has(key)) {
481
+ seen.add(key);
482
+ mergedBindings.push(normalized);
483
+ }
484
+ }
485
+ existing.postgres = { bindings: mergedBindings };
486
+ }
487
+ function normalizeDefinition(definition, source) {
488
+ if (!definition.slug || !isValidPermissionSlug(definition.slug.trim())) throw new Error(`Invalid permission slug '${definition.slug}'. Expected 'resource.action[.scope...]'.`);
489
+ const slug = definition.slug.trim();
490
+ return {
491
+ category: definition.category ?? parsePermissionSlug(slug).resource,
492
+ className: definition.className,
493
+ collection: definition.collection,
494
+ description: definition.description ?? defaultPermissionDescription(slug),
495
+ name: definition.name ?? defaultPermissionName(slug),
496
+ postgres: definition.postgres?.bindings ? { bindings: definition.postgres.bindings.map((binding) => normalizeBinding(binding, slug)) } : void 0,
497
+ qualifiedName: definition.qualifiedName,
498
+ slug,
499
+ source
500
+ };
501
+ }
502
+ function mergeDefinitionSet(current, incomingDefinitions, source) {
503
+ for (const rawDefinition of incomingDefinitions) {
504
+ const definition = normalizeDefinition(rawDefinition, source);
505
+ const existing = current.get(definition.slug);
506
+ if (!existing) {
507
+ current.set(definition.slug, definition);
508
+ continue;
509
+ }
510
+ mergeStringField("category", existing, definition, definition.slug);
511
+ mergeStringField("className", existing, definition, definition.slug);
512
+ mergeStringField("collection", existing, definition, definition.slug);
513
+ mergeStringField("description", existing, definition, definition.slug);
514
+ mergeStringField("name", existing, definition, definition.slug);
515
+ mergeStringField("qualifiedName", existing, definition, definition.slug);
516
+ mergeBindings(existing, definition);
517
+ }
518
+ }
519
+ function definitionChangesPermission(existing, definition) {
520
+ return (definition.name ?? existing.name) !== existing.name || (definition.description ?? existing.description) !== existing.description || (definition.category ?? existing.category) !== existing.category;
521
+ }
522
+ var PermissionCatalogService = class PermissionCatalogService {
523
+ constructor(options = {}) {
524
+ this.options = options;
525
+ }
526
+ options;
527
+ getUsersConfig() {
528
+ return getPackageConfig("users", {});
529
+ }
530
+ getRuntimePermissionDefinitions() {
531
+ return Array.from(getRuntimePermissionRegistrations().values()).flat();
532
+ }
533
+ getCustomPermissionDefinitions() {
534
+ return this.getUsersConfig().permissions?.custom ?? [];
535
+ }
536
+ getCatalog() {
537
+ const manifestPermissions = this.getManifestPermissionDefinitions();
538
+ const customPermissions = this.getCustomPermissionDefinitions();
539
+ const runtimePermissions = this.getRuntimePermissionDefinitions();
540
+ const merged = /* @__PURE__ */ new Map();
541
+ mergeDefinitionSet(merged, manifestPermissions, "manifest");
542
+ mergeDefinitionSet(merged, customPermissions, "config");
543
+ mergeDefinitionSet(merged, runtimePermissions, "runtime");
544
+ return {
545
+ customPermissions: customPermissions.map((definition) => normalizeDefinition(definition, "config")),
546
+ manifestPermissions: manifestPermissions.map((definition) => normalizeDefinition(definition, "manifest")),
547
+ permissions: Array.from(merged.values()).sort((left, right) => left.slug.localeCompare(right.slug)),
548
+ runtimePermissions: runtimePermissions.map((definition) => normalizeDefinition(definition, "runtime"))
549
+ };
550
+ }
551
+ deriveOperationPermissionSlug(collection, action) {
552
+ return deriveOperationPermissionSlug(collection, action);
553
+ }
554
+ hasPermissionSlug(slug) {
555
+ return this.getCatalog().permissions.some((permission) => permission.slug === slug);
556
+ }
557
+ async syncPermissionCatalog() {
558
+ const catalog = this.getCatalog();
559
+ const permissions = await PermissionCollection.create(withoutListBounds(this.options));
560
+ const created = [];
561
+ const unchanged = [];
562
+ const updated = [];
563
+ const existingBySlug = /* @__PURE__ */ new Map();
564
+ for (const permission of await permissions.list({})) if (typeof permission.slug === "string" && permission.slug.length > 0) existingBySlug.set(permission.slug, permission);
565
+ const pending = catalog.permissions.filter((definition) => {
566
+ const existing = existingBySlug.get(definition.slug);
567
+ if (existing && !definitionChangesPermission(existing, definition)) {
568
+ unchanged.push(definition.slug);
569
+ return false;
570
+ }
571
+ return true;
572
+ });
573
+ await writeInSeedingBatches(permissions.db, pending, async (database, batch) => {
574
+ const batchPermissions = await PermissionCollection.create({
575
+ ...this.options,
576
+ db: database
577
+ });
578
+ for (const definition of batch) {
579
+ const existing = existingBySlug.get(definition.slug) ?? null;
580
+ if (!existing) {
581
+ const permission = await batchPermissions.create({
582
+ category: definition.category ?? parsePermissionSlug(definition.slug).resource,
583
+ description: definition.description ?? "",
584
+ name: definition.name ?? definition.slug,
585
+ slug: definition.slug
586
+ });
587
+ existingBySlug.set(definition.slug, permission);
588
+ created.push(definition.slug);
589
+ continue;
590
+ }
591
+ if (!definitionChangesPermission(existing, definition)) {
592
+ unchanged.push(definition.slug);
593
+ continue;
594
+ }
595
+ existing.name = definition.name ?? existing.name;
596
+ existing.description = definition.description ?? existing.description;
597
+ existing.category = definition.category ?? existing.category;
598
+ await existing.withDatabase(database, (row) => row.save());
599
+ updated.push(definition.slug);
600
+ }
601
+ });
602
+ return {
603
+ catalog,
604
+ created,
605
+ unchanged,
606
+ updated
607
+ };
608
+ }
609
+ getManifestPermissionDefinitions() {
610
+ const standardActions = [
611
+ "list",
612
+ "get",
613
+ "create",
614
+ "update",
615
+ "delete"
616
+ ];
617
+ const definitions = /* @__PURE__ */ new Map();
618
+ const seenRegistrations = /* @__PURE__ */ new Set();
619
+ for (const [, registered] of ObjectRegistry.getAllClasses()) {
620
+ if (seenRegistrations.has(registered)) continue;
621
+ seenRegistrations.add(registered);
622
+ const manifestEntry = registered?.qualifiedName ? findManifestEntryByQualifiedName(registered.qualifiedName) : void 0;
623
+ if (isCollectionClass(registered, manifestEntry)) {
624
+ for (const definition of getCollectionClassActionDefinitions(registered, manifestEntry, standardActions)) {
625
+ const existing = definitions.get(definition.slug);
626
+ if (existing) mergeBindings(existing, definition);
627
+ else definitions.set(definition.slug, definition);
628
+ }
629
+ continue;
630
+ }
631
+ const className = registered.name;
632
+ const qualifiedName = registered.qualifiedName;
633
+ const objectConfig = manifestEntry?.decoratorConfig ?? registered.config;
634
+ const collection = resolveCatalogCollectionName(registered, manifestEntry);
635
+ const registryKey = qualifiedName ?? className;
636
+ const ownsCrud = !ObjectRegistry.getSTIBase(registryKey) || !ObjectRegistry.getInheritanceChain(registryKey).some((ancestor) => {
637
+ const parent = ObjectRegistry.getClass(ancestor);
638
+ return parent && parent !== registered && resolveCatalogCollectionName(parent, manifestEntryFor(parent)) === collection;
639
+ });
640
+ const catalogCliConfig = qualifiedName && USERS_AUTHORITY_CATALOG_MODELS.has(qualifiedName) ? true : objectConfig.cli;
641
+ const readExposed = isOperationEnabled(objectConfig.api, "list") || isOperationEnabled(objectConfig.api, "get") || isOperationEnabled(catalogCliConfig, "list") || isOperationEnabled(catalogCliConfig, "get") || isOperationEnabled(objectConfig.mcp, "list") || isOperationEnabled(objectConfig.mcp, "get");
642
+ if (ownsCrud && readExposed) definitions.set(`${collection}.read`, {
643
+ ...definitions.get(`${collection}.read`),
644
+ className,
645
+ collection,
646
+ qualifiedName,
647
+ slug: `${collection}.read`
648
+ });
649
+ const fieldEntries = manifestEntry?.fields ? Object.entries(manifestEntry.fields) : Array.from((registered.inheritedFields ?? registered.fields).entries());
650
+ for (const [fieldName, fieldDef] of fieldEntries) {
651
+ const field = fieldDef;
652
+ const readPermission = typeof field.readPermission === "string" ? field.readPermission : typeof field._meta?.readPermission === "string" ? field._meta.readPermission : void 0;
653
+ if (!readPermission || definitions.has(readPermission)) continue;
654
+ definitions.set(readPermission, {
655
+ className,
656
+ collection,
657
+ description: `Allows reading ${fieldName} on ${humanizeResource(collection).toLowerCase()}`,
658
+ name: `Read ${humanizeResource(fieldName)} on ${humanizeResource(collection)}`,
659
+ qualifiedName,
660
+ slug: readPermission
661
+ });
662
+ }
663
+ for (const action of [
664
+ "create",
665
+ "update",
666
+ "delete"
667
+ ]) {
668
+ const exposed = isOperationEnabled(objectConfig.api, action) || isOperationEnabled(catalogCliConfig, action) || isOperationEnabled(objectConfig.mcp, action);
669
+ if (!ownsCrud || !exposed) continue;
670
+ definitions.set(`${collection}.${action}`, {
671
+ ...definitions.get(`${collection}.${action}`),
672
+ className,
673
+ collection,
674
+ qualifiedName,
675
+ slug: `${collection}.${action}`
676
+ });
677
+ }
678
+ const publicCustomMethodNames = getPublicCustomMethodNames(manifestEntry?.methods ? Object.values(manifestEntry.methods) : Array.from(registered.methods.entries()), standardActions);
679
+ const customApiMethods = /* @__PURE__ */ new Set();
680
+ const customCliMethods = getCustomMethodExposureNames(catalogCliConfig, publicCustomMethodNames);
681
+ const customMcpMethods = getCustomMethodExposureNames(objectConfig.mcp, publicCustomMethodNames);
682
+ for (const methodName of publicCustomMethodNames) if (isOperationEnabled(objectConfig.api, methodName)) customApiMethods.add(methodName);
683
+ const customMethods = /* @__PURE__ */ new Set([
684
+ ...customApiMethods,
685
+ ...customCliMethods,
686
+ ...customMcpMethods
687
+ ]);
688
+ for (const methodName of customMethods) {
689
+ const alias = resolveOperationPermissionAlias(objectConfig, methodName);
690
+ const permissionAction = alias?.action ?? methodName;
691
+ const slug = `${collection}.${permissionAction}`;
692
+ const definition = definitions.get(slug) ?? {
693
+ className,
694
+ collection,
695
+ qualifiedName,
696
+ slug,
697
+ description: `Allows ${permissionAction} on ${humanizeResource(collection).toLowerCase()}`,
698
+ name: `${capitalize(permissionAction)} ${humanizeResource(collection)}`
699
+ };
700
+ addAliasDatabaseBindings(definition, alias, registered, manifestEntry);
701
+ definitions.set(slug, definition);
702
+ }
703
+ }
704
+ return Array.from(definitions.values()).sort((left, right) => left.slug.localeCompare(right.slug));
705
+ }
706
+ static create(options = {}) {
707
+ return new PermissionCatalogService(options);
708
+ }
709
+ };
710
+ async function syncPermissionCatalog(options = {}) {
711
+ return PermissionCatalogService.create(options).syncPermissionCatalog();
712
+ }
713
+ //#endregion
714
+ export { syncPermissionCatalog as a, PermissionCollection as c, normalizeOperationPermissionAction as i, Permission as l, deriveOperationPermissionCollectionName as n, writeInSeedingBatches as o, deriveOperationPermissionSlug as r, withoutListBounds as s, PermissionCatalogService as t };
715
+
716
+ //# sourceMappingURL=PermissionCatalogService-DcmTn38P.js.map