@anievo-id/rbac-evolution-mongoose 0.0.0-stage → 0.3.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.
@@ -0,0 +1,178 @@
1
+ import { RbacAdapter, Permission, FindPermissionsQuery, Id, TeamId, Role, FindRolesQuery, RolePermissionLink, Subject } from '@anievo-id/rbac-evolution';
2
+ import mongoose, { Types, Model, Connection } from 'mongoose';
3
+
4
+ interface PermissionDoc {
5
+ _id: Types.ObjectId;
6
+ name: string;
7
+ guardName: string;
8
+ createdAt: Date;
9
+ updatedAt: Date;
10
+ }
11
+ interface RoleDoc {
12
+ _id: Types.ObjectId;
13
+ name: string;
14
+ guardName: string;
15
+ /** `''` = global (no team). */
16
+ teamId: string;
17
+ createdAt: Date;
18
+ updatedAt: Date;
19
+ }
20
+ interface RoleHasPermissionDoc {
21
+ _id: Types.ObjectId;
22
+ roleId: Types.ObjectId;
23
+ permissionId: Types.ObjectId;
24
+ }
25
+ interface ModelHasRoleDoc {
26
+ _id: Types.ObjectId;
27
+ roleId: Types.ObjectId;
28
+ subjectType: string;
29
+ subjectId: string;
30
+ /** `''` = global (no team). */
31
+ teamId: string;
32
+ }
33
+ interface ModelHasPermissionDoc {
34
+ _id: Types.ObjectId;
35
+ permissionId: Types.ObjectId;
36
+ subjectType: string;
37
+ subjectId: string;
38
+ /** `''` = global (no team). */
39
+ teamId: string;
40
+ }
41
+ /** The five Mongoose models used by the adapter. */
42
+ interface RbacModels {
43
+ Permission: Model<PermissionDoc>;
44
+ Role: Model<RoleDoc>;
45
+ RoleHasPermission: Model<RoleHasPermissionDoc>;
46
+ ModelHasRole: Model<ModelHasRoleDoc>;
47
+ ModelHasPermission: Model<ModelHasPermissionDoc>;
48
+ }
49
+ interface RbacModelOptions {
50
+ /** Connection to register the models on. Default: the default `mongoose.connection`. */
51
+ connection?: Connection;
52
+ /** Prepended to every collection name, e.g. `'rbac_'` → `rbac_permissions`. Default: `''`. */
53
+ prefix?: string;
54
+ }
55
+ interface RbacCollectionNames {
56
+ permissions: string;
57
+ roles: string;
58
+ roleHasPermissions: string;
59
+ modelHasRoles: string;
60
+ modelHasPermissions: string;
61
+ }
62
+ declare const collectionNames: (options?: Pick<RbacModelOptions, "prefix">) => RbacCollectionNames;
63
+ /** Schemas (unregistered). Useful to add plugins or hooks before calling `createRbacModels`. */
64
+ declare function rbacSchemas(): {
65
+ permission: mongoose.Schema<PermissionDoc, mongoose.Model<PermissionDoc, any, any, any, mongoose.Document<unknown, any, PermissionDoc, any, {}> & PermissionDoc & Required<{
66
+ _id: Types.ObjectId;
67
+ }> & {
68
+ __v: number;
69
+ }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, PermissionDoc, mongoose.Document<unknown, {}, mongoose.FlatRecord<PermissionDoc>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<PermissionDoc> & Required<{
70
+ _id: Types.ObjectId;
71
+ }> & {
72
+ __v: number;
73
+ }>;
74
+ role: mongoose.Schema<RoleDoc, mongoose.Model<RoleDoc, any, any, any, mongoose.Document<unknown, any, RoleDoc, any, {}> & RoleDoc & Required<{
75
+ _id: Types.ObjectId;
76
+ }> & {
77
+ __v: number;
78
+ }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, RoleDoc, mongoose.Document<unknown, {}, mongoose.FlatRecord<RoleDoc>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<RoleDoc> & Required<{
79
+ _id: Types.ObjectId;
80
+ }> & {
81
+ __v: number;
82
+ }>;
83
+ roleHasPermission: mongoose.Schema<RoleHasPermissionDoc, mongoose.Model<RoleHasPermissionDoc, any, any, any, mongoose.Document<unknown, any, RoleHasPermissionDoc, any, {}> & RoleHasPermissionDoc & Required<{
84
+ _id: Types.ObjectId;
85
+ }> & {
86
+ __v: number;
87
+ }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, RoleHasPermissionDoc, mongoose.Document<unknown, {}, mongoose.FlatRecord<RoleHasPermissionDoc>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<RoleHasPermissionDoc> & Required<{
88
+ _id: Types.ObjectId;
89
+ }> & {
90
+ __v: number;
91
+ }>;
92
+ modelHasRole: mongoose.Schema<ModelHasRoleDoc, mongoose.Model<ModelHasRoleDoc, any, any, any, mongoose.Document<unknown, any, ModelHasRoleDoc, any, {}> & ModelHasRoleDoc & Required<{
93
+ _id: Types.ObjectId;
94
+ }> & {
95
+ __v: number;
96
+ }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, ModelHasRoleDoc, mongoose.Document<unknown, {}, mongoose.FlatRecord<ModelHasRoleDoc>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<ModelHasRoleDoc> & Required<{
97
+ _id: Types.ObjectId;
98
+ }> & {
99
+ __v: number;
100
+ }>;
101
+ modelHasPermission: mongoose.Schema<ModelHasPermissionDoc, mongoose.Model<ModelHasPermissionDoc, any, any, any, mongoose.Document<unknown, any, ModelHasPermissionDoc, any, {}> & ModelHasPermissionDoc & Required<{
102
+ _id: Types.ObjectId;
103
+ }> & {
104
+ __v: number;
105
+ }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, ModelHasPermissionDoc, mongoose.Document<unknown, {}, mongoose.FlatRecord<ModelHasPermissionDoc>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<ModelHasPermissionDoc> & Required<{
106
+ _id: Types.ObjectId;
107
+ }> & {
108
+ __v: number;
109
+ }>;
110
+ };
111
+ /**
112
+ * Registers (or reuses) the rbac-evolution models on a connection.
113
+ *
114
+ * ```ts
115
+ * const models = createRbacModels() // default connection
116
+ * const models = createRbacModels({ connection: conn, prefix: 'rbac_' })
117
+ * ```
118
+ */
119
+ declare function createRbacModels(options?: RbacModelOptions): RbacModels;
120
+ /**
121
+ * Creates the collections' indexes (unique constraints included). Call it once at deploy/startup when
122
+ * Mongoose `autoIndex` is disabled; with `autoIndex` on (the default) the adapter waits for them itself.
123
+ */
124
+ declare function syncRbacIndexes(models: RbacModels): Promise<void>;
125
+
126
+ /**
127
+ * Mongoose (MongoDB) implementation of `RbacAdapter`.
128
+ * Construct it with `mongooseAdapter(options?)` or `new MongooseRbacAdapter(createRbacModels(...))`.
129
+ */
130
+ declare class MongooseRbacAdapter implements RbacAdapter {
131
+ readonly models: RbacModels;
132
+ private ready;
133
+ constructor(models: RbacModels);
134
+ /** Waits for the models' indexes (unique constraints) once, before the first operation. */
135
+ private init;
136
+ createPermission(data: {
137
+ name: string;
138
+ guardName: string;
139
+ }): Promise<Permission>;
140
+ findPermissions(query?: FindPermissionsQuery): Promise<Permission[]>;
141
+ deletePermission(id: Id): Promise<void>;
142
+ createRole(data: {
143
+ name: string;
144
+ guardName: string;
145
+ teamId: TeamId;
146
+ }): Promise<Role>;
147
+ findRoles(query?: FindRolesQuery): Promise<Role[]>;
148
+ deleteRole(id: Id): Promise<void>;
149
+ getRolePermissionLinks(roleIds: readonly Id[]): Promise<RolePermissionLink[]>;
150
+ attachRolePermissions(roleId: Id, permissionIds: readonly Id[]): Promise<void>;
151
+ detachRolePermissions(roleId: Id, permissionIds?: readonly Id[]): Promise<void>;
152
+ getSubjectRoleIds(subject: Subject, teamId: TeamId): Promise<Id[]>;
153
+ attachSubjectRoles(subject: Subject, roleIds: readonly Id[], teamId: TeamId): Promise<void>;
154
+ detachSubjectRoles(subject: Subject, roleIds: readonly Id[] | undefined, teamId: TeamId): Promise<void>;
155
+ getSubjectPermissionIds(subject: Subject, teamId: TeamId): Promise<Id[]>;
156
+ attachSubjectPermissions(subject: Subject, permissionIds: readonly Id[], teamId: TeamId): Promise<void>;
157
+ detachSubjectPermissions(subject: Subject, permissionIds: readonly Id[] | undefined, teamId: TeamId): Promise<void>;
158
+ getSubjectIdsWithRoles(subjectType: string, roleIds: readonly Id[], teamId: TeamId): Promise<Id[]>;
159
+ getSubjectIdsWithPermissions(subjectType: string, permissionIds: readonly Id[], teamId: TeamId): Promise<Id[]>;
160
+ private static subjectFilter;
161
+ /**
162
+ * Idempotent insert: one upsert per link (`$setOnInsert`), matched on the unique key.
163
+ * A concurrent insert of the same link surfaces as a duplicate-key error, which is ignored.
164
+ */
165
+ private static upsertAll;
166
+ }
167
+ /**
168
+ * Creates a Mongoose-backed `RbacAdapter` (registers the models on the connection if needed).
169
+ *
170
+ * ```ts
171
+ * await mongoose.connect(process.env.MONGO_URL!)
172
+ * const rbac = createRbac({ adapter: mongooseAdapter() })
173
+ * const rbac = createRbac({ adapter: mongooseAdapter({ connection: conn, prefix: 'rbac_' }) })
174
+ * ```
175
+ */
176
+ declare function mongooseAdapter(options?: RbacModelOptions): MongooseRbacAdapter;
177
+
178
+ export { type ModelHasPermissionDoc, type ModelHasRoleDoc, MongooseRbacAdapter, type PermissionDoc, type RbacCollectionNames, type RbacModelOptions, type RbacModels, type RoleDoc, type RoleHasPermissionDoc, collectionNames, createRbacModels, mongooseAdapter, rbacSchemas, syncRbacIndexes };
@@ -0,0 +1,178 @@
1
+ import { RbacAdapter, Permission, FindPermissionsQuery, Id, TeamId, Role, FindRolesQuery, RolePermissionLink, Subject } from '@anievo-id/rbac-evolution';
2
+ import mongoose, { Types, Model, Connection } from 'mongoose';
3
+
4
+ interface PermissionDoc {
5
+ _id: Types.ObjectId;
6
+ name: string;
7
+ guardName: string;
8
+ createdAt: Date;
9
+ updatedAt: Date;
10
+ }
11
+ interface RoleDoc {
12
+ _id: Types.ObjectId;
13
+ name: string;
14
+ guardName: string;
15
+ /** `''` = global (no team). */
16
+ teamId: string;
17
+ createdAt: Date;
18
+ updatedAt: Date;
19
+ }
20
+ interface RoleHasPermissionDoc {
21
+ _id: Types.ObjectId;
22
+ roleId: Types.ObjectId;
23
+ permissionId: Types.ObjectId;
24
+ }
25
+ interface ModelHasRoleDoc {
26
+ _id: Types.ObjectId;
27
+ roleId: Types.ObjectId;
28
+ subjectType: string;
29
+ subjectId: string;
30
+ /** `''` = global (no team). */
31
+ teamId: string;
32
+ }
33
+ interface ModelHasPermissionDoc {
34
+ _id: Types.ObjectId;
35
+ permissionId: Types.ObjectId;
36
+ subjectType: string;
37
+ subjectId: string;
38
+ /** `''` = global (no team). */
39
+ teamId: string;
40
+ }
41
+ /** The five Mongoose models used by the adapter. */
42
+ interface RbacModels {
43
+ Permission: Model<PermissionDoc>;
44
+ Role: Model<RoleDoc>;
45
+ RoleHasPermission: Model<RoleHasPermissionDoc>;
46
+ ModelHasRole: Model<ModelHasRoleDoc>;
47
+ ModelHasPermission: Model<ModelHasPermissionDoc>;
48
+ }
49
+ interface RbacModelOptions {
50
+ /** Connection to register the models on. Default: the default `mongoose.connection`. */
51
+ connection?: Connection;
52
+ /** Prepended to every collection name, e.g. `'rbac_'` → `rbac_permissions`. Default: `''`. */
53
+ prefix?: string;
54
+ }
55
+ interface RbacCollectionNames {
56
+ permissions: string;
57
+ roles: string;
58
+ roleHasPermissions: string;
59
+ modelHasRoles: string;
60
+ modelHasPermissions: string;
61
+ }
62
+ declare const collectionNames: (options?: Pick<RbacModelOptions, "prefix">) => RbacCollectionNames;
63
+ /** Schemas (unregistered). Useful to add plugins or hooks before calling `createRbacModels`. */
64
+ declare function rbacSchemas(): {
65
+ permission: mongoose.Schema<PermissionDoc, mongoose.Model<PermissionDoc, any, any, any, mongoose.Document<unknown, any, PermissionDoc, any, {}> & PermissionDoc & Required<{
66
+ _id: Types.ObjectId;
67
+ }> & {
68
+ __v: number;
69
+ }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, PermissionDoc, mongoose.Document<unknown, {}, mongoose.FlatRecord<PermissionDoc>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<PermissionDoc> & Required<{
70
+ _id: Types.ObjectId;
71
+ }> & {
72
+ __v: number;
73
+ }>;
74
+ role: mongoose.Schema<RoleDoc, mongoose.Model<RoleDoc, any, any, any, mongoose.Document<unknown, any, RoleDoc, any, {}> & RoleDoc & Required<{
75
+ _id: Types.ObjectId;
76
+ }> & {
77
+ __v: number;
78
+ }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, RoleDoc, mongoose.Document<unknown, {}, mongoose.FlatRecord<RoleDoc>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<RoleDoc> & Required<{
79
+ _id: Types.ObjectId;
80
+ }> & {
81
+ __v: number;
82
+ }>;
83
+ roleHasPermission: mongoose.Schema<RoleHasPermissionDoc, mongoose.Model<RoleHasPermissionDoc, any, any, any, mongoose.Document<unknown, any, RoleHasPermissionDoc, any, {}> & RoleHasPermissionDoc & Required<{
84
+ _id: Types.ObjectId;
85
+ }> & {
86
+ __v: number;
87
+ }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, RoleHasPermissionDoc, mongoose.Document<unknown, {}, mongoose.FlatRecord<RoleHasPermissionDoc>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<RoleHasPermissionDoc> & Required<{
88
+ _id: Types.ObjectId;
89
+ }> & {
90
+ __v: number;
91
+ }>;
92
+ modelHasRole: mongoose.Schema<ModelHasRoleDoc, mongoose.Model<ModelHasRoleDoc, any, any, any, mongoose.Document<unknown, any, ModelHasRoleDoc, any, {}> & ModelHasRoleDoc & Required<{
93
+ _id: Types.ObjectId;
94
+ }> & {
95
+ __v: number;
96
+ }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, ModelHasRoleDoc, mongoose.Document<unknown, {}, mongoose.FlatRecord<ModelHasRoleDoc>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<ModelHasRoleDoc> & Required<{
97
+ _id: Types.ObjectId;
98
+ }> & {
99
+ __v: number;
100
+ }>;
101
+ modelHasPermission: mongoose.Schema<ModelHasPermissionDoc, mongoose.Model<ModelHasPermissionDoc, any, any, any, mongoose.Document<unknown, any, ModelHasPermissionDoc, any, {}> & ModelHasPermissionDoc & Required<{
102
+ _id: Types.ObjectId;
103
+ }> & {
104
+ __v: number;
105
+ }, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, ModelHasPermissionDoc, mongoose.Document<unknown, {}, mongoose.FlatRecord<ModelHasPermissionDoc>, {}, mongoose.DefaultSchemaOptions> & mongoose.FlatRecord<ModelHasPermissionDoc> & Required<{
106
+ _id: Types.ObjectId;
107
+ }> & {
108
+ __v: number;
109
+ }>;
110
+ };
111
+ /**
112
+ * Registers (or reuses) the rbac-evolution models on a connection.
113
+ *
114
+ * ```ts
115
+ * const models = createRbacModels() // default connection
116
+ * const models = createRbacModels({ connection: conn, prefix: 'rbac_' })
117
+ * ```
118
+ */
119
+ declare function createRbacModels(options?: RbacModelOptions): RbacModels;
120
+ /**
121
+ * Creates the collections' indexes (unique constraints included). Call it once at deploy/startup when
122
+ * Mongoose `autoIndex` is disabled; with `autoIndex` on (the default) the adapter waits for them itself.
123
+ */
124
+ declare function syncRbacIndexes(models: RbacModels): Promise<void>;
125
+
126
+ /**
127
+ * Mongoose (MongoDB) implementation of `RbacAdapter`.
128
+ * Construct it with `mongooseAdapter(options?)` or `new MongooseRbacAdapter(createRbacModels(...))`.
129
+ */
130
+ declare class MongooseRbacAdapter implements RbacAdapter {
131
+ readonly models: RbacModels;
132
+ private ready;
133
+ constructor(models: RbacModels);
134
+ /** Waits for the models' indexes (unique constraints) once, before the first operation. */
135
+ private init;
136
+ createPermission(data: {
137
+ name: string;
138
+ guardName: string;
139
+ }): Promise<Permission>;
140
+ findPermissions(query?: FindPermissionsQuery): Promise<Permission[]>;
141
+ deletePermission(id: Id): Promise<void>;
142
+ createRole(data: {
143
+ name: string;
144
+ guardName: string;
145
+ teamId: TeamId;
146
+ }): Promise<Role>;
147
+ findRoles(query?: FindRolesQuery): Promise<Role[]>;
148
+ deleteRole(id: Id): Promise<void>;
149
+ getRolePermissionLinks(roleIds: readonly Id[]): Promise<RolePermissionLink[]>;
150
+ attachRolePermissions(roleId: Id, permissionIds: readonly Id[]): Promise<void>;
151
+ detachRolePermissions(roleId: Id, permissionIds?: readonly Id[]): Promise<void>;
152
+ getSubjectRoleIds(subject: Subject, teamId: TeamId): Promise<Id[]>;
153
+ attachSubjectRoles(subject: Subject, roleIds: readonly Id[], teamId: TeamId): Promise<void>;
154
+ detachSubjectRoles(subject: Subject, roleIds: readonly Id[] | undefined, teamId: TeamId): Promise<void>;
155
+ getSubjectPermissionIds(subject: Subject, teamId: TeamId): Promise<Id[]>;
156
+ attachSubjectPermissions(subject: Subject, permissionIds: readonly Id[], teamId: TeamId): Promise<void>;
157
+ detachSubjectPermissions(subject: Subject, permissionIds: readonly Id[] | undefined, teamId: TeamId): Promise<void>;
158
+ getSubjectIdsWithRoles(subjectType: string, roleIds: readonly Id[], teamId: TeamId): Promise<Id[]>;
159
+ getSubjectIdsWithPermissions(subjectType: string, permissionIds: readonly Id[], teamId: TeamId): Promise<Id[]>;
160
+ private static subjectFilter;
161
+ /**
162
+ * Idempotent insert: one upsert per link (`$setOnInsert`), matched on the unique key.
163
+ * A concurrent insert of the same link surfaces as a duplicate-key error, which is ignored.
164
+ */
165
+ private static upsertAll;
166
+ }
167
+ /**
168
+ * Creates a Mongoose-backed `RbacAdapter` (registers the models on the connection if needed).
169
+ *
170
+ * ```ts
171
+ * await mongoose.connect(process.env.MONGO_URL!)
172
+ * const rbac = createRbac({ adapter: mongooseAdapter() })
173
+ * const rbac = createRbac({ adapter: mongooseAdapter({ connection: conn, prefix: 'rbac_' }) })
174
+ * ```
175
+ */
176
+ declare function mongooseAdapter(options?: RbacModelOptions): MongooseRbacAdapter;
177
+
178
+ export { type ModelHasPermissionDoc, type ModelHasRoleDoc, MongooseRbacAdapter, type PermissionDoc, type RbacCollectionNames, type RbacModelOptions, type RbacModels, type RoleDoc, type RoleHasPermissionDoc, collectionNames, createRbacModels, mongooseAdapter, rbacSchemas, syncRbacIndexes };
package/dist/index.js ADDED
@@ -0,0 +1,325 @@
1
+ import mongoose, { Schema, Types } from 'mongoose';
2
+
3
+ // src/adapter.ts
4
+ var collectionNames = (options = {}) => {
5
+ const prefix = options.prefix ?? "";
6
+ return {
7
+ permissions: `${prefix}permissions`,
8
+ roles: `${prefix}roles`,
9
+ roleHasPermissions: `${prefix}role_has_permissions`,
10
+ modelHasRoles: `${prefix}model_has_roles`,
11
+ modelHasPermissions: `${prefix}model_has_permissions`
12
+ };
13
+ };
14
+ var linkOptions = { versionKey: false };
15
+ function rbacSchemas() {
16
+ const permission = new Schema(
17
+ {
18
+ name: { type: String, required: true },
19
+ guardName: { type: String, required: true }
20
+ },
21
+ { timestamps: true, versionKey: false }
22
+ );
23
+ permission.index({ name: 1, guardName: 1 }, { unique: true });
24
+ const role = new Schema(
25
+ {
26
+ name: { type: String, required: true },
27
+ guardName: { type: String, required: true },
28
+ teamId: { type: String, default: "" }
29
+ },
30
+ { timestamps: true, versionKey: false }
31
+ );
32
+ role.index({ name: 1, guardName: 1, teamId: 1 }, { unique: true });
33
+ const roleHasPermission = new Schema(
34
+ {
35
+ roleId: { type: Schema.Types.ObjectId, required: true },
36
+ permissionId: { type: Schema.Types.ObjectId, required: true }
37
+ },
38
+ linkOptions
39
+ );
40
+ roleHasPermission.index({ roleId: 1, permissionId: 1 }, { unique: true });
41
+ roleHasPermission.index({ permissionId: 1 });
42
+ const modelHasRole = new Schema(
43
+ {
44
+ roleId: { type: Schema.Types.ObjectId, required: true },
45
+ subjectType: { type: String, required: true },
46
+ subjectId: { type: String, required: true },
47
+ teamId: { type: String, default: "" }
48
+ },
49
+ linkOptions
50
+ );
51
+ modelHasRole.index({ subjectType: 1, subjectId: 1, teamId: 1, roleId: 1 }, { unique: true });
52
+ modelHasRole.index({ roleId: 1, subjectType: 1, teamId: 1 });
53
+ const modelHasPermission = new Schema(
54
+ {
55
+ permissionId: { type: Schema.Types.ObjectId, required: true },
56
+ subjectType: { type: String, required: true },
57
+ subjectId: { type: String, required: true },
58
+ teamId: { type: String, default: "" }
59
+ },
60
+ linkOptions
61
+ );
62
+ modelHasPermission.index({ subjectType: 1, subjectId: 1, teamId: 1, permissionId: 1 }, { unique: true });
63
+ modelHasPermission.index({ permissionId: 1, subjectType: 1, teamId: 1 });
64
+ return { permission, role, roleHasPermission, modelHasRole, modelHasPermission };
65
+ }
66
+ var register = (connection, collection, schema) => {
67
+ const name = `rbac:${collection}`;
68
+ const existing = connection.models[name];
69
+ return existing ?? connection.model(name, schema, collection);
70
+ };
71
+ function createRbacModels(options = {}) {
72
+ const connection = options.connection ?? mongoose.connection;
73
+ const names = collectionNames(options);
74
+ const schemas = rbacSchemas();
75
+ return {
76
+ Permission: register(connection, names.permissions, schemas.permission),
77
+ Role: register(connection, names.roles, schemas.role),
78
+ RoleHasPermission: register(connection, names.roleHasPermissions, schemas.roleHasPermission),
79
+ ModelHasRole: register(connection, names.modelHasRoles, schemas.modelHasRole),
80
+ ModelHasPermission: register(connection, names.modelHasPermissions, schemas.modelHasPermission)
81
+ };
82
+ }
83
+ async function syncRbacIndexes(models) {
84
+ await Promise.all(Object.values(models).map((model) => model.createIndexes()));
85
+ }
86
+
87
+ // src/adapter.ts
88
+ var GLOBAL_TEAM = "";
89
+ var teamKey = (teamId) => teamId === null ? GLOBAL_TEAM : String(teamId);
90
+ var teamFromKey = (key) => key === void 0 || key === GLOBAL_TEAM ? null : key;
91
+ var OBJECT_ID = /^[0-9a-f]{24}$/i;
92
+ var toObjectId = (id) => {
93
+ const s = String(id);
94
+ return OBJECT_ID.test(s) ? new Types.ObjectId(s) : null;
95
+ };
96
+ var toObjectIds = (ids) => {
97
+ const out = /* @__PURE__ */ new Map();
98
+ for (const id of ids) {
99
+ const oid = toObjectId(id);
100
+ if (oid !== null) out.set(oid.toHexString(), oid);
101
+ }
102
+ return [...out.values()];
103
+ };
104
+ var onlyDuplicates = (error) => {
105
+ const e = error;
106
+ if (e === null || typeof e !== "object") return false;
107
+ const writeErrors = Array.isArray(e.writeErrors) ? e.writeErrors : [];
108
+ if (Array.isArray(e.writeConcernErrors) && e.writeConcernErrors.length > 0) return false;
109
+ if (writeErrors.length > 0) return writeErrors.every((w) => w.code === 11e3);
110
+ return e.code === 11e3;
111
+ };
112
+ var MongooseRbacAdapter = class _MongooseRbacAdapter {
113
+ constructor(models) {
114
+ this.models = models;
115
+ }
116
+ models;
117
+ ready;
118
+ /** Waits for the models' indexes (unique constraints) once, before the first operation. */
119
+ init() {
120
+ this.ready ??= Promise.all(Object.values(this.models).map((model) => model.init()));
121
+ return this.ready;
122
+ }
123
+ // ---------------------------------------------------------------- permissions
124
+ async createPermission(data) {
125
+ await this.init();
126
+ const doc = await this.models.Permission.create({ name: data.name, guardName: data.guardName });
127
+ return { id: doc._id.toHexString(), name: doc.name, guardName: doc.guardName };
128
+ }
129
+ async findPermissions(query = {}) {
130
+ await this.init();
131
+ const filter = {};
132
+ if (query.ids !== void 0) {
133
+ const ids = toObjectIds(query.ids);
134
+ if (ids.length === 0) return [];
135
+ filter._id = { $in: ids };
136
+ }
137
+ if (query.names !== void 0) {
138
+ if (query.names.length === 0) return [];
139
+ filter.name = { $in: [...query.names] };
140
+ }
141
+ if (query.guardName !== void 0) filter.guardName = query.guardName;
142
+ const docs = await this.models.Permission.find(filter, { name: 1, guardName: 1 }).sort({ _id: 1 }).lean();
143
+ return docs.map((d) => ({ id: d._id.toHexString(), name: d.name, guardName: d.guardName }));
144
+ }
145
+ async deletePermission(id) {
146
+ const pid = toObjectId(id);
147
+ if (pid === null) return;
148
+ await this.init();
149
+ await this.models.RoleHasPermission.deleteMany({ permissionId: pid });
150
+ await this.models.ModelHasPermission.deleteMany({ permissionId: pid });
151
+ await this.models.Permission.deleteOne({ _id: pid });
152
+ }
153
+ // ---------------------------------------------------------------------- roles
154
+ async createRole(data) {
155
+ await this.init();
156
+ const doc = await this.models.Role.create({ name: data.name, guardName: data.guardName, teamId: teamKey(data.teamId) });
157
+ return { id: doc._id.toHexString(), name: doc.name, guardName: doc.guardName, teamId: teamFromKey(doc.teamId) };
158
+ }
159
+ async findRoles(query = {}) {
160
+ await this.init();
161
+ const filter = {};
162
+ if (query.ids !== void 0) {
163
+ const ids = toObjectIds(query.ids);
164
+ if (ids.length === 0) return [];
165
+ filter._id = { $in: ids };
166
+ }
167
+ if (query.names !== void 0) {
168
+ if (query.names.length === 0) return [];
169
+ filter.name = { $in: [...query.names] };
170
+ }
171
+ if (query.guardName !== void 0) filter.guardName = query.guardName;
172
+ if (query.teamIds !== void 0) {
173
+ if (query.teamIds.length === 0) return [];
174
+ const teams = [...new Set(query.teamIds.map(teamKey))];
175
+ filter.teamId = teams.includes(GLOBAL_TEAM) ? { $in: [...teams, null] } : { $in: teams };
176
+ }
177
+ const docs = await this.models.Role.find(filter, { name: 1, guardName: 1, teamId: 1 }).sort({ _id: 1 }).lean();
178
+ return docs.map((d) => ({
179
+ id: d._id.toHexString(),
180
+ name: d.name,
181
+ guardName: d.guardName,
182
+ teamId: teamFromKey(d.teamId)
183
+ }));
184
+ }
185
+ async deleteRole(id) {
186
+ const rid = toObjectId(id);
187
+ if (rid === null) return;
188
+ await this.init();
189
+ await this.models.RoleHasPermission.deleteMany({ roleId: rid });
190
+ await this.models.ModelHasRole.deleteMany({ roleId: rid });
191
+ await this.models.Role.deleteOne({ _id: rid });
192
+ }
193
+ // ---------------------------------------------------------- role ↔ permission
194
+ async getRolePermissionLinks(roleIds) {
195
+ const ids = toObjectIds(roleIds);
196
+ if (ids.length === 0) return [];
197
+ await this.init();
198
+ const docs = await this.models.RoleHasPermission.find({ roleId: { $in: ids } }, { roleId: 1, permissionId: 1 }).lean();
199
+ return docs.map((d) => ({ roleId: d.roleId.toHexString(), permissionId: d.permissionId.toHexString() }));
200
+ }
201
+ async attachRolePermissions(roleId, permissionIds) {
202
+ const rid = toObjectId(roleId);
203
+ const ids = toObjectIds(permissionIds);
204
+ if (rid === null || ids.length === 0) return;
205
+ await this.init();
206
+ await _MongooseRbacAdapter.upsertAll(
207
+ this.models.RoleHasPermission,
208
+ ids.map((permissionId) => ({ roleId: rid, permissionId }))
209
+ );
210
+ }
211
+ async detachRolePermissions(roleId, permissionIds) {
212
+ const rid = toObjectId(roleId);
213
+ if (rid === null) return;
214
+ const filter = { roleId: rid };
215
+ if (permissionIds !== void 0) {
216
+ const ids = toObjectIds(permissionIds);
217
+ if (ids.length === 0) return;
218
+ filter.permissionId = { $in: ids };
219
+ }
220
+ await this.init();
221
+ await this.models.RoleHasPermission.deleteMany(filter);
222
+ }
223
+ // ------------------------------------------------------------- subject links
224
+ async getSubjectRoleIds(subject, teamId) {
225
+ await this.init();
226
+ const docs = await this.models.ModelHasRole.find(_MongooseRbacAdapter.subjectFilter(subject, teamId), {
227
+ roleId: 1
228
+ }).lean();
229
+ return docs.map((d) => d.roleId.toHexString());
230
+ }
231
+ async attachSubjectRoles(subject, roleIds, teamId) {
232
+ const ids = toObjectIds(roleIds);
233
+ if (ids.length === 0) return;
234
+ await this.init();
235
+ const base = _MongooseRbacAdapter.subjectFilter(subject, teamId);
236
+ await _MongooseRbacAdapter.upsertAll(
237
+ this.models.ModelHasRole,
238
+ ids.map((roleId) => ({ ...base, roleId }))
239
+ );
240
+ }
241
+ async detachSubjectRoles(subject, roleIds, teamId) {
242
+ const filter = _MongooseRbacAdapter.subjectFilter(subject, teamId);
243
+ if (roleIds !== void 0) {
244
+ const ids = toObjectIds(roleIds);
245
+ if (ids.length === 0) return;
246
+ filter.roleId = { $in: ids };
247
+ }
248
+ await this.init();
249
+ await this.models.ModelHasRole.deleteMany(filter);
250
+ }
251
+ async getSubjectPermissionIds(subject, teamId) {
252
+ await this.init();
253
+ const docs = await this.models.ModelHasPermission.find(_MongooseRbacAdapter.subjectFilter(subject, teamId), {
254
+ permissionId: 1
255
+ }).lean();
256
+ return docs.map((d) => d.permissionId.toHexString());
257
+ }
258
+ async attachSubjectPermissions(subject, permissionIds, teamId) {
259
+ const ids = toObjectIds(permissionIds);
260
+ if (ids.length === 0) return;
261
+ await this.init();
262
+ const base = _MongooseRbacAdapter.subjectFilter(subject, teamId);
263
+ await _MongooseRbacAdapter.upsertAll(
264
+ this.models.ModelHasPermission,
265
+ ids.map((permissionId) => ({ ...base, permissionId }))
266
+ );
267
+ }
268
+ async detachSubjectPermissions(subject, permissionIds, teamId) {
269
+ const filter = _MongooseRbacAdapter.subjectFilter(subject, teamId);
270
+ if (permissionIds !== void 0) {
271
+ const ids = toObjectIds(permissionIds);
272
+ if (ids.length === 0) return;
273
+ filter.permissionId = { $in: ids };
274
+ }
275
+ await this.init();
276
+ await this.models.ModelHasPermission.deleteMany(filter);
277
+ }
278
+ async getSubjectIdsWithRoles(subjectType, roleIds, teamId) {
279
+ const ids = toObjectIds(roleIds);
280
+ if (ids.length === 0) return [];
281
+ await this.init();
282
+ const subjectIds = await this.models.ModelHasRole.distinct("subjectId", {
283
+ subjectType,
284
+ teamId: teamKey(teamId),
285
+ roleId: { $in: ids }
286
+ });
287
+ return subjectIds.map(String);
288
+ }
289
+ async getSubjectIdsWithPermissions(subjectType, permissionIds, teamId) {
290
+ const ids = toObjectIds(permissionIds);
291
+ if (ids.length === 0) return [];
292
+ await this.init();
293
+ const subjectIds = await this.models.ModelHasPermission.distinct("subjectId", {
294
+ subjectType,
295
+ teamId: teamKey(teamId),
296
+ permissionId: { $in: ids }
297
+ });
298
+ return subjectIds.map(String);
299
+ }
300
+ // -------------------------------------------------------------------- helpers
301
+ static subjectFilter(subject, teamId) {
302
+ return { subjectType: subject.type, subjectId: String(subject.id), teamId: teamKey(teamId) };
303
+ }
304
+ /**
305
+ * Idempotent insert: one upsert per link (`$setOnInsert`), matched on the unique key.
306
+ * A concurrent insert of the same link surfaces as a duplicate-key error, which is ignored.
307
+ */
308
+ static async upsertAll(model, docs) {
309
+ try {
310
+ await model.bulkWrite(
311
+ docs.map((doc) => ({ updateOne: { filter: doc, update: { $setOnInsert: doc }, upsert: true } })),
312
+ { ordered: false }
313
+ );
314
+ } catch (error) {
315
+ if (!onlyDuplicates(error)) throw error;
316
+ }
317
+ }
318
+ };
319
+ function mongooseAdapter(options = {}) {
320
+ return new MongooseRbacAdapter(createRbacModels(options));
321
+ }
322
+
323
+ export { MongooseRbacAdapter, collectionNames, createRbacModels, mongooseAdapter, rbacSchemas, syncRbacIndexes };
324
+ //# sourceMappingURL=index.js.map
325
+ //# sourceMappingURL=index.js.map