@anievo-id/rbac-evolution-react 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AniEvo-ID
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,148 @@
1
- # Temporary Holding Version
1
+ # @anievo-id/rbac-evolution-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ React bindings for [rbac-evolution](../core): `<RbacProvider>`, `useCan()`, `<Can>`, `<HasRole>`, ... — the React
4
+ counterpart of spatie/laravel-permission's Blade directives (`@can`, `@cannot`, `@role`, `@hasanyrole`, ...).
5
+
6
+ > **UI only.** These helpers show and hide elements based on a snapshot sent to the browser. Anyone can edit
7
+ > client-side state, so they are **not** a security boundary. Always enforce authorization on the server
8
+ > (route handlers, server actions, API) — e.g. with `@anievo-id/rbac-evolution-next` or the core `rbac.for(user).can()`.
9
+
10
+ ```bash
11
+ npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-react
12
+ ```
13
+
14
+ Works with React 18+ and the Next.js App Router (the bundle starts with `'use client'`).
15
+
16
+ ## How it works
17
+
18
+ 1. On the server, take a snapshot of the user's access: `await rbac.for(user).snapshot()` → `{ roles, permissions }`.
19
+ 2. Pass it to `<RbacProvider snapshot={...}>`.
20
+ 3. Check synchronously anywhere below it — no requests, no loading states.
21
+
22
+ ## Next.js App Router
23
+
24
+ ```tsx
25
+ // app/layout.tsx — server component
26
+ import { RbacProvider } from '@anievo-id/rbac-evolution-react'
27
+ import { rbac } from '@/lib/rbac'
28
+ import { auth } from '@/auth'
29
+
30
+ export default async function RootLayout({ children }: { children: React.ReactNode }) {
31
+ const session = await auth()
32
+ const snapshot = session?.user
33
+ ? await rbac.for({ type: 'user', id: session.user.id }).snapshot()
34
+ : null // guest
35
+
36
+ return (
37
+ <html lang="en">
38
+ <body>
39
+ <RbacProvider snapshot={snapshot} wildcard={rbac.wildcard}>
40
+ {children}
41
+ </RbacProvider>
42
+ </body>
43
+ </html>
44
+ )
45
+ }
46
+ ```
47
+
48
+ (With `@anievo-id/rbac-evolution-next` this is just `snapshot={await getSnapshot()}`.)
49
+
50
+ ```tsx
51
+ // app/articles/article-actions.tsx — client component
52
+ 'use client'
53
+
54
+ import { Can, Cannot, HasRole, useCan } from '@anievo-id/rbac-evolution-react'
55
+
56
+ export function ArticleActions() {
57
+ const canPublish = useCan('articles.publish')
58
+
59
+ return (
60
+ <div>
61
+ <Can permission="articles.edit">
62
+ <button>Edit</button>
63
+ </Can>
64
+
65
+ <Can anyOf={['articles.delete', 'articles.archive']} fallback={<span>Read only</span>}>
66
+ <button>Remove</button>
67
+ </Can>
68
+
69
+ <Cannot permission="articles.edit">
70
+ <p>Ask an editor to make changes.</p>
71
+ </Cannot>
72
+
73
+ <HasRole role="admin">
74
+ <a href="/admin">Admin panel</a>
75
+ </HasRole>
76
+
77
+ <button disabled={!canPublish}>Publish</button>
78
+ </div>
79
+ )
80
+ }
81
+ ```
82
+
83
+ ## Other React apps
84
+
85
+ Fetch the snapshot from your API (e.g. `GET /api/me/permissions` returning `rbac.for(user).snapshot()`) and pass it in:
86
+
87
+ ```tsx
88
+ <RbacProvider snapshot={data ?? null}>
89
+ <App />
90
+ </RbacProvider>
91
+ ```
92
+
93
+ ## API
94
+
95
+ ### `<RbacProvider>`
96
+
97
+ | Prop | Type | Description |
98
+ | ----------------- | ------------------------------ | ------------------------------------------------------------------------------ |
99
+ | `snapshot` | `RbacSnapshot \| null` | `{ roles, permissions }` of the current user. `null`/`undefined` = guest. |
100
+ | `wildcard` | `boolean` | Match `articles.*`-style permissions. Use the same value as `createRbac`. |
101
+ | `superAdminRoles` | `string[]` | Users with one of these roles pass every `can` check (not role checks). |
102
+
103
+ Providers can be nested; the nearest one wins.
104
+
105
+ ### Hooks
106
+
107
+ | Hook | Returns `true` when |
108
+ | ------------------------------ | -------------------------------------------------------- |
109
+ | `useCan(permission)` | the user has the permission |
110
+ | `useCannot(permission)` | the user does not have the permission |
111
+ | `useCanAny(...permissions)` | the user has ANY of them (arrays or varargs) |
112
+ | `useCanAll(...permissions)` | the user has ALL of them |
113
+ | `useHasRole(role \| roles[])` | the user has the role / ANY of the roles |
114
+ | `useHasAnyRole(...roles)` | the user has ANY of the roles |
115
+ | `useHasAllRoles(...roles)` | the user has ALL of the roles |
116
+ | `useRbac()` | returns the checker (`can`, `canAny`, `hasRole`, `roles`, `permissions`, ...) |
117
+
118
+ Hooks throw when used outside `<RbacProvider>`.
119
+
120
+ ### Components
121
+
122
+ ```tsx
123
+ <Can permission="a">…</Can> // @can('a')
124
+ <Can anyOf={['a', 'b']}>…</Can> // @canany(['a', 'b'])
125
+ <Can allOf={['a', 'b']}>…</Can> // all of them
126
+ <Cannot permission="a">…</Cannot> // @cannot('a')
127
+ <HasRole role="admin">…</HasRole> // @role('admin')
128
+ <HasRole anyOf={['a', 'b']}>…</HasRole> // @hasanyrole
129
+ <HasRole allOf={['a', 'b']}>…</HasRole> // @hasallroles
130
+ ```
131
+
132
+ All accept `fallback` (rendered when the check fails). TypeScript enforces exactly one condition; at runtime a
133
+ component with no condition renders the fallback (deny by default).
134
+
135
+ ### `createRbacChecker(snapshot, { wildcard?, superAdminRoles? })`
136
+
137
+ The pure checker behind the provider, usable outside React.
138
+
139
+ ## Notes
140
+
141
+ - Name matching is exact (after trimming), like the core. With `wildcard`, matching uses the core's `wildcardImplies`.
142
+ - Snapshots are per guard/team: take the snapshot with the same `guard`/`team` you check on the server.
143
+ - A snapshot is a point-in-time copy. After changing a user's roles, re-render with a fresh snapshot
144
+ (e.g. `router.refresh()` in Next.js).
145
+
146
+ ## License
147
+
148
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,168 @@
1
+ 'use client';
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ Can: () => Can,
25
+ Cannot: () => Cannot,
26
+ HasRole: () => HasRole,
27
+ RbacProvider: () => RbacProvider,
28
+ createRbacChecker: () => createRbacChecker,
29
+ useCan: () => useCan,
30
+ useCanAll: () => useCanAll,
31
+ useCanAny: () => useCanAny,
32
+ useCannot: () => useCannot,
33
+ useHasAllRoles: () => useHasAllRoles,
34
+ useHasAnyRole: () => useHasAnyRole,
35
+ useHasRole: () => useHasRole,
36
+ useRbac: () => useRbac
37
+ });
38
+ module.exports = __toCommonJS(index_exports);
39
+
40
+ // src/checker.ts
41
+ var import_rbac_evolution = require("@anievo-id/rbac-evolution");
42
+ var EMPTY = { roles: [], permissions: [] };
43
+ function flatten(items) {
44
+ const out = [];
45
+ for (const item of items) {
46
+ if (typeof item === "string") out.push(item);
47
+ else out.push(...item);
48
+ }
49
+ return out;
50
+ }
51
+ function safeImplies(granted, required) {
52
+ try {
53
+ return (0, import_rbac_evolution.wildcardImplies)(granted, required);
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
58
+ function createRbacChecker(snapshot, options = {}) {
59
+ const { roles, permissions } = snapshot ?? EMPTY;
60
+ const roleSet = new Set(roles);
61
+ const permissionSet = new Set(permissions);
62
+ const wildcard = options.wildcard ?? false;
63
+ const isSuperAdmin = (options.superAdminRoles ?? []).some((r) => roleSet.has(r));
64
+ const can = (permission) => {
65
+ if (isSuperAdmin) return true;
66
+ const name = permission.trim();
67
+ if (name === "") return false;
68
+ if (permissionSet.has(name)) return true;
69
+ return wildcard && permissions.some((granted) => safeImplies(granted, name));
70
+ };
71
+ const hasOne = (role) => roleSet.has(role.trim());
72
+ return {
73
+ roles,
74
+ permissions,
75
+ isSuperAdmin,
76
+ can,
77
+ cannot: (permission) => !can(permission),
78
+ canAny: (...list) => flatten(list).some(can),
79
+ canAll: (...list) => flatten(list).every(can),
80
+ hasRole: (list) => flatten([list]).some(hasOne),
81
+ hasAnyRole: (...list) => flatten(list).some(hasOne),
82
+ hasAllRoles: (...list) => flatten(list).every(hasOne)
83
+ };
84
+ }
85
+
86
+ // src/context.tsx
87
+ var import_react = require("react");
88
+ var import_jsx_runtime = require("react/jsx-runtime");
89
+ var RbacContext = (0, import_react.createContext)(null);
90
+ RbacContext.displayName = "RbacContext";
91
+ function RbacProvider({ snapshot, wildcard = false, superAdminRoles, children }) {
92
+ const superKey = superAdminRoles?.join("\0") ?? "";
93
+ const checker = (0, import_react.useMemo)(
94
+ () => createRbacChecker(snapshot, superAdminRoles ? { wildcard, superAdminRoles } : { wildcard }),
95
+ // `superKey` keeps inline arrays (`superAdminRoles={['admin']}`) from recomputing every render.
96
+ // eslint-disable-next-line react-hooks/exhaustive-deps
97
+ [snapshot, wildcard, superKey]
98
+ );
99
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RbacContext.Provider, { value: checker, children });
100
+ }
101
+ function useRbac() {
102
+ const checker = (0, import_react.useContext)(RbacContext);
103
+ if (!checker) {
104
+ throw new Error("useRbac() must be used inside <RbacProvider>.");
105
+ }
106
+ return checker;
107
+ }
108
+ function useCan(permission) {
109
+ return useRbac().can(permission);
110
+ }
111
+ function useCannot(permission) {
112
+ return useRbac().cannot(permission);
113
+ }
114
+ function useCanAny(...permissions) {
115
+ return useRbac().canAny(...permissions);
116
+ }
117
+ function useCanAll(...permissions) {
118
+ return useRbac().canAll(...permissions);
119
+ }
120
+ function useHasRole(role) {
121
+ return useRbac().hasRole(role);
122
+ }
123
+ function useHasAnyRole(...roles) {
124
+ return useRbac().hasAnyRole(...roles);
125
+ }
126
+ function useHasAllRoles(...roles) {
127
+ return useRbac().hasAllRoles(...roles);
128
+ }
129
+
130
+ // src/components.tsx
131
+ var import_jsx_runtime2 = require("react/jsx-runtime");
132
+ function checkPermissions(rbac, p) {
133
+ if (p.permission === void 0 && p.anyOf === void 0 && p.allOf === void 0) return false;
134
+ return (p.permission === void 0 || rbac.can(p.permission)) && (p.anyOf === void 0 || rbac.canAny(p.anyOf)) && (p.allOf === void 0 || rbac.canAll(p.allOf));
135
+ }
136
+ function checkRoles(rbac, p) {
137
+ if (p.role === void 0 && p.anyOf === void 0 && p.allOf === void 0) return false;
138
+ return (p.role === void 0 || rbac.hasRole(p.role)) && (p.anyOf === void 0 || rbac.hasAnyRole(p.anyOf)) && (p.allOf === void 0 || rbac.hasAllRoles(p.allOf));
139
+ }
140
+ function Can(props) {
141
+ const allowed = checkPermissions(useRbac(), props);
142
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children: allowed ? props.children : props.fallback });
143
+ }
144
+ function Cannot(props) {
145
+ const allowed = checkPermissions(useRbac(), props);
146
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children: allowed ? props.fallback : props.children });
147
+ }
148
+ function HasRole(props) {
149
+ const allowed = checkRoles(useRbac(), props);
150
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children: allowed ? props.children : props.fallback });
151
+ }
152
+ // Annotate the CommonJS export names for ESM import in node:
153
+ 0 && (module.exports = {
154
+ Can,
155
+ Cannot,
156
+ HasRole,
157
+ RbacProvider,
158
+ createRbacChecker,
159
+ useCan,
160
+ useCanAll,
161
+ useCanAny,
162
+ useCannot,
163
+ useHasAllRoles,
164
+ useHasAnyRole,
165
+ useHasRole,
166
+ useRbac
167
+ });
168
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/checker.ts","../src/context.tsx","../src/components.tsx"],"sourcesContent":["/**\n * @anievo-id/rbac-evolution-react\n *\n * Client-side UI helpers. They only show/hide UI — always enforce authorization on the server.\n */\n\nexport { createRbacChecker } from './checker'\nexport type { RbacChecker, RbacCheckerOptions } from './checker'\n\nexport {\n RbacProvider,\n useCan,\n useCanAll,\n useCanAny,\n useCannot,\n useHasAllRoles,\n useHasAnyRole,\n useHasRole,\n useRbac,\n} from './context'\nexport type { RbacProviderProps } from './context'\n\nexport { Can, Cannot, HasRole } from './components'\nexport type { CannotProps, CanProps, HasRoleProps, PermissionCondition, RoleCondition } from './components'\n","import { wildcardImplies } from '@anievo-id/rbac-evolution'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\n\nexport interface RbacCheckerOptions {\n /** Treat granted permissions as wildcard patterns (`articles.*`). Must match the server's `wildcard` setting. */\n wildcard?: boolean\n /** Roles that pass every permission check (like spatie's `Gate::before` super-admin pattern). */\n superAdminRoles?: readonly string[]\n}\n\n/** Synchronous checks against a {@link RbacSnapshot}. */\nexport interface RbacChecker {\n readonly roles: readonly string[]\n readonly permissions: readonly string[]\n /** `true` if the subject has one of the configured `superAdminRoles`. */\n readonly isSuperAdmin: boolean\n can(permission: string): boolean\n cannot(permission: string): boolean\n /** `true` if ANY of the permissions is granted. `false` for an empty list. */\n canAny(...permissions: Many<string>[]): boolean\n /** `true` if ALL of the permissions are granted. `true` for an empty list. */\n canAll(...permissions: Many<string>[]): boolean\n /** `true` if the subject has the role — or ANY of the roles when given an array. */\n hasRole(roles: Many<string>): boolean\n hasAnyRole(...roles: Many<string>[]): boolean\n hasAllRoles(...roles: Many<string>[]): boolean\n}\n\nconst EMPTY: RbacSnapshot = { roles: [], permissions: [] }\n\nfunction flatten(items: readonly Many<string>[]): string[] {\n const out: string[] = []\n for (const item of items) {\n if (typeof item === 'string') out.push(item)\n else out.push(...item)\n }\n return out\n}\n\nfunction safeImplies(granted: string, required: string): boolean {\n try {\n return wildcardImplies(granted, required)\n } catch {\n return false\n }\n}\n\n/**\n * Builds a pure, synchronous checker for a snapshot (as returned by `rbac.for(user).snapshot()`).\n * Used by `RbacProvider`, but usable on its own too.\n */\nexport function createRbacChecker(\n snapshot: RbacSnapshot | null | undefined,\n options: RbacCheckerOptions = {},\n): RbacChecker {\n const { roles, permissions } = snapshot ?? EMPTY\n const roleSet = new Set(roles)\n const permissionSet = new Set(permissions)\n const wildcard = options.wildcard ?? false\n const isSuperAdmin = (options.superAdminRoles ?? []).some((r) => roleSet.has(r))\n\n const can = (permission: string): boolean => {\n if (isSuperAdmin) return true\n const name = permission.trim()\n if (name === '') return false\n if (permissionSet.has(name)) return true\n return wildcard && permissions.some((granted) => safeImplies(granted, name))\n }\n const hasOne = (role: string): boolean => roleSet.has(role.trim())\n\n return {\n roles,\n permissions,\n isSuperAdmin,\n can,\n cannot: (permission) => !can(permission),\n canAny: (...list) => flatten(list).some(can),\n canAll: (...list) => flatten(list).every(can),\n hasRole: (list) => flatten([list]).some(hasOne),\n hasAnyRole: (...list) => flatten(list).some(hasOne),\n hasAllRoles: (...list) => flatten(list).every(hasOne),\n }\n}\n","import { createContext, useContext, useMemo } from 'react'\nimport type { ReactNode } from 'react'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\nimport { createRbacChecker } from './checker'\nimport type { RbacChecker } from './checker'\n\nconst RbacContext = createContext<RbacChecker | null>(null)\nRbacContext.displayName = 'RbacContext'\n\nexport interface RbacProviderProps {\n /** Roles & permissions of the current user, e.g. from `rbac.for(user).snapshot()` on the server. `null` = guest. */\n snapshot: RbacSnapshot | null | undefined\n /** Enable wildcard matching (`articles.*`). Must match the server's `wildcard` setting. Default: `false`. */\n wildcard?: boolean\n /** Roles that pass every `can` check (super admin). */\n superAdminRoles?: readonly string[]\n children?: ReactNode\n}\n\n/**\n * Provides a user's roles & permissions to `useCan()`, `<Can>`, ...\n *\n * UI only: this hides and shows elements. Always enforce authorization on the server.\n */\nexport function RbacProvider({ snapshot, wildcard = false, superAdminRoles, children }: RbacProviderProps) {\n const superKey = superAdminRoles?.join('\\u0000') ?? ''\n const checker = useMemo(\n () => createRbacChecker(snapshot, superAdminRoles ? { wildcard, superAdminRoles } : { wildcard }),\n // `superKey` keeps inline arrays (`superAdminRoles={['admin']}`) from recomputing every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [snapshot, wildcard, superKey],\n )\n return <RbacContext.Provider value={checker}>{children}</RbacContext.Provider>\n}\n\n/** Returns the checker of the nearest `RbacProvider`. Throws when there is none. */\nexport function useRbac(): RbacChecker {\n const checker = useContext(RbacContext)\n if (!checker) {\n throw new Error('useRbac() must be used inside <RbacProvider>.')\n }\n return checker\n}\n\nexport function useCan(permission: string): boolean {\n return useRbac().can(permission)\n}\n\nexport function useCannot(permission: string): boolean {\n return useRbac().cannot(permission)\n}\n\nexport function useCanAny(...permissions: Many<string>[]): boolean {\n return useRbac().canAny(...permissions)\n}\n\nexport function useCanAll(...permissions: Many<string>[]): boolean {\n return useRbac().canAll(...permissions)\n}\n\n/** `true` if the user has the role — or ANY of the roles when given an array. */\nexport function useHasRole(role: Many<string>): boolean {\n return useRbac().hasRole(role)\n}\n\nexport function useHasAnyRole(...roles: Many<string>[]): boolean {\n return useRbac().hasAnyRole(...roles)\n}\n\nexport function useHasAllRoles(...roles: Many<string>[]): boolean {\n return useRbac().hasAllRoles(...roles)\n}\n","import type { ReactNode } from 'react'\nimport type { RbacChecker } from './checker'\nimport { useRbac } from './context'\n\n/** Exactly one of `permission`, `anyOf` or `allOf`. */\nexport type PermissionCondition =\n | { permission: string; anyOf?: never; allOf?: never }\n | { permission?: never; anyOf: readonly string[]; allOf?: never }\n | { permission?: never; anyOf?: never; allOf: readonly string[] }\n\n/** Exactly one of `role`, `anyOf` or `allOf`. */\nexport type RoleCondition =\n | { role: string; anyOf?: never; allOf?: never }\n | { role?: never; anyOf: readonly string[]; allOf?: never }\n | { role?: never; anyOf?: never; allOf: readonly string[] }\n\ninterface GateProps {\n children?: ReactNode\n /** Rendered when the check fails. Default: nothing. */\n fallback?: ReactNode\n}\n\nexport type CanProps = PermissionCondition & GateProps\nexport type CannotProps = PermissionCondition & GateProps\nexport type HasRoleProps = RoleCondition & GateProps\n\ninterface LooseCondition {\n anyOf?: readonly string[] | undefined\n allOf?: readonly string[] | undefined\n}\n\n// Conditions are ANDed; no condition at all is denied (deny by default, also for untyped JS callers).\nfunction checkPermissions(rbac: RbacChecker, p: LooseCondition & { permission?: string | undefined }): boolean {\n if (p.permission === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.permission === undefined || rbac.can(p.permission)) &&\n (p.anyOf === undefined || rbac.canAny(p.anyOf)) &&\n (p.allOf === undefined || rbac.canAll(p.allOf))\n )\n}\n\nfunction checkRoles(rbac: RbacChecker, p: LooseCondition & { role?: string | undefined }): boolean {\n if (p.role === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.role === undefined || rbac.hasRole(p.role)) &&\n (p.anyOf === undefined || rbac.hasAnyRole(p.anyOf)) &&\n (p.allOf === undefined || rbac.hasAllRoles(p.allOf))\n )\n}\n\n/** Renders `children` if the user has the permission(s) — like spatie's `@can` / `@canany`. */\nexport function Can(props: CanProps) {\n const allowed = checkPermissions(useRbac(), props)\n return <>{allowed ? props.children : props.fallback}</>\n}\n\n/** Renders `children` if the user does NOT have the permission(s) — like spatie's `@cannot`. */\nexport function Cannot(props: CannotProps) {\n const allowed = checkPermissions(useRbac(), props)\n return <>{allowed ? props.fallback : props.children}</>\n}\n\n/** Renders `children` if the user has the role(s) — like spatie's `@role` / `@hasanyrole` / `@hasallroles`. */\nexport function HasRole(props: HasRoleProps) {\n const allowed = checkRoles(useRbac(), props)\n return <>{allowed ? props.children : props.fallback}</>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,4BAAgC;AA4BhC,IAAM,QAAsB,EAAE,OAAO,CAAC,GAAG,aAAa,CAAC,EAAE;AAEzD,SAAS,QAAQ,OAA0C;AACzD,QAAM,MAAgB,CAAC;AACvB,aAAW,QAAQ,OAAO;AACxB,QAAI,OAAO,SAAS,SAAU,KAAI,KAAK,IAAI;AAAA,QACtC,KAAI,KAAK,GAAG,IAAI;AAAA,EACvB;AACA,SAAO;AACT;AAEA,SAAS,YAAY,SAAiB,UAA2B;AAC/D,MAAI;AACF,eAAO,uCAAgB,SAAS,QAAQ;AAAA,EAC1C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,kBACd,UAC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,QAAO;AACnF,UACG,EAAE,SAAS,UAAa,KAAK,QAAQ,EAAE,IAAI,OAC3C,EAAE,UAAU,UAAa,KAAK,WAAW,EAAE,KAAK,OAChD,EAAE,UAAU,UAAa,KAAK,YAAY,EAAE,KAAK;AAEtD;AAGO,SAAS,IAAI,OAAiB;AACnC,QAAM,UAAU,iBAAiB,QAAQ,GAAG,KAAK;AACjD,SAAO,6EAAG,oBAAU,MAAM,WAAW,MAAM,UAAS;AACtD;AAGO,SAAS,OAAO,OAAoB;AACzC,QAAM,UAAU,iBAAiB,QAAQ,GAAG,KAAK;AACjD,SAAO,6EAAG,oBAAU,MAAM,WAAW,MAAM,UAAS;AACtD;AAGO,SAAS,QAAQ,OAAqB;AAC3C,QAAM,UAAU,WAAW,QAAQ,GAAG,KAAK;AAC3C,SAAO,6EAAG,oBAAU,MAAM,WAAW,MAAM,UAAS;AACtD;","names":["import_jsx_runtime"]}
@@ -0,0 +1,103 @@
1
+ import { Many, RbacSnapshot } from '@anievo-id/rbac-evolution';
2
+ import * as react from 'react';
3
+ import { ReactNode } from 'react';
4
+
5
+ interface RbacCheckerOptions {
6
+ /** Treat granted permissions as wildcard patterns (`articles.*`). Must match the server's `wildcard` setting. */
7
+ wildcard?: boolean;
8
+ /** Roles that pass every permission check (like spatie's `Gate::before` super-admin pattern). */
9
+ superAdminRoles?: readonly string[];
10
+ }
11
+ /** Synchronous checks against a {@link RbacSnapshot}. */
12
+ interface RbacChecker {
13
+ readonly roles: readonly string[];
14
+ readonly permissions: readonly string[];
15
+ /** `true` if the subject has one of the configured `superAdminRoles`. */
16
+ readonly isSuperAdmin: boolean;
17
+ can(permission: string): boolean;
18
+ cannot(permission: string): boolean;
19
+ /** `true` if ANY of the permissions is granted. `false` for an empty list. */
20
+ canAny(...permissions: Many<string>[]): boolean;
21
+ /** `true` if ALL of the permissions are granted. `true` for an empty list. */
22
+ canAll(...permissions: Many<string>[]): boolean;
23
+ /** `true` if the subject has the role — or ANY of the roles when given an array. */
24
+ hasRole(roles: Many<string>): boolean;
25
+ hasAnyRole(...roles: Many<string>[]): boolean;
26
+ hasAllRoles(...roles: Many<string>[]): boolean;
27
+ }
28
+ /**
29
+ * Builds a pure, synchronous checker for a snapshot (as returned by `rbac.for(user).snapshot()`).
30
+ * Used by `RbacProvider`, but usable on its own too.
31
+ */
32
+ declare function createRbacChecker(snapshot: RbacSnapshot | null | undefined, options?: RbacCheckerOptions): RbacChecker;
33
+
34
+ interface RbacProviderProps {
35
+ /** Roles & permissions of the current user, e.g. from `rbac.for(user).snapshot()` on the server. `null` = guest. */
36
+ snapshot: RbacSnapshot | null | undefined;
37
+ /** Enable wildcard matching (`articles.*`). Must match the server's `wildcard` setting. Default: `false`. */
38
+ wildcard?: boolean;
39
+ /** Roles that pass every `can` check (super admin). */
40
+ superAdminRoles?: readonly string[];
41
+ children?: ReactNode;
42
+ }
43
+ /**
44
+ * Provides a user's roles & permissions to `useCan()`, `<Can>`, ...
45
+ *
46
+ * UI only: this hides and shows elements. Always enforce authorization on the server.
47
+ */
48
+ declare function RbacProvider({ snapshot, wildcard, superAdminRoles, children }: RbacProviderProps): react.JSX.Element;
49
+ /** Returns the checker of the nearest `RbacProvider`. Throws when there is none. */
50
+ declare function useRbac(): RbacChecker;
51
+ declare function useCan(permission: string): boolean;
52
+ declare function useCannot(permission: string): boolean;
53
+ declare function useCanAny(...permissions: Many<string>[]): boolean;
54
+ declare function useCanAll(...permissions: Many<string>[]): boolean;
55
+ /** `true` if the user has the role — or ANY of the roles when given an array. */
56
+ declare function useHasRole(role: Many<string>): boolean;
57
+ declare function useHasAnyRole(...roles: Many<string>[]): boolean;
58
+ declare function useHasAllRoles(...roles: Many<string>[]): boolean;
59
+
60
+ /** Exactly one of `permission`, `anyOf` or `allOf`. */
61
+ type PermissionCondition = {
62
+ permission: string;
63
+ anyOf?: never;
64
+ allOf?: never;
65
+ } | {
66
+ permission?: never;
67
+ anyOf: readonly string[];
68
+ allOf?: never;
69
+ } | {
70
+ permission?: never;
71
+ anyOf?: never;
72
+ allOf: readonly string[];
73
+ };
74
+ /** Exactly one of `role`, `anyOf` or `allOf`. */
75
+ type RoleCondition = {
76
+ role: string;
77
+ anyOf?: never;
78
+ allOf?: never;
79
+ } | {
80
+ role?: never;
81
+ anyOf: readonly string[];
82
+ allOf?: never;
83
+ } | {
84
+ role?: never;
85
+ anyOf?: never;
86
+ allOf: readonly string[];
87
+ };
88
+ interface GateProps {
89
+ children?: ReactNode;
90
+ /** Rendered when the check fails. Default: nothing. */
91
+ fallback?: ReactNode;
92
+ }
93
+ type CanProps = PermissionCondition & GateProps;
94
+ type CannotProps = PermissionCondition & GateProps;
95
+ type HasRoleProps = RoleCondition & GateProps;
96
+ /** Renders `children` if the user has the permission(s) — like spatie's `@can` / `@canany`. */
97
+ declare function Can(props: CanProps): react.JSX.Element;
98
+ /** Renders `children` if the user does NOT have the permission(s) — like spatie's `@cannot`. */
99
+ declare function Cannot(props: CannotProps): react.JSX.Element;
100
+ /** Renders `children` if the user has the role(s) — like spatie's `@role` / `@hasanyrole` / `@hasallroles`. */
101
+ declare function HasRole(props: HasRoleProps): react.JSX.Element;
102
+
103
+ export { Can, type CanProps, Cannot, type CannotProps, HasRole, type HasRoleProps, type PermissionCondition, type RbacChecker, type RbacCheckerOptions, RbacProvider, type RbacProviderProps, type RoleCondition, createRbacChecker, useCan, useCanAll, useCanAny, useCannot, useHasAllRoles, useHasAnyRole, useHasRole, useRbac };
@@ -0,0 +1,103 @@
1
+ import { Many, RbacSnapshot } from '@anievo-id/rbac-evolution';
2
+ import * as react from 'react';
3
+ import { ReactNode } from 'react';
4
+
5
+ interface RbacCheckerOptions {
6
+ /** Treat granted permissions as wildcard patterns (`articles.*`). Must match the server's `wildcard` setting. */
7
+ wildcard?: boolean;
8
+ /** Roles that pass every permission check (like spatie's `Gate::before` super-admin pattern). */
9
+ superAdminRoles?: readonly string[];
10
+ }
11
+ /** Synchronous checks against a {@link RbacSnapshot}. */
12
+ interface RbacChecker {
13
+ readonly roles: readonly string[];
14
+ readonly permissions: readonly string[];
15
+ /** `true` if the subject has one of the configured `superAdminRoles`. */
16
+ readonly isSuperAdmin: boolean;
17
+ can(permission: string): boolean;
18
+ cannot(permission: string): boolean;
19
+ /** `true` if ANY of the permissions is granted. `false` for an empty list. */
20
+ canAny(...permissions: Many<string>[]): boolean;
21
+ /** `true` if ALL of the permissions are granted. `true` for an empty list. */
22
+ canAll(...permissions: Many<string>[]): boolean;
23
+ /** `true` if the subject has the role — or ANY of the roles when given an array. */
24
+ hasRole(roles: Many<string>): boolean;
25
+ hasAnyRole(...roles: Many<string>[]): boolean;
26
+ hasAllRoles(...roles: Many<string>[]): boolean;
27
+ }
28
+ /**
29
+ * Builds a pure, synchronous checker for a snapshot (as returned by `rbac.for(user).snapshot()`).
30
+ * Used by `RbacProvider`, but usable on its own too.
31
+ */
32
+ declare function createRbacChecker(snapshot: RbacSnapshot | null | undefined, options?: RbacCheckerOptions): RbacChecker;
33
+
34
+ interface RbacProviderProps {
35
+ /** Roles & permissions of the current user, e.g. from `rbac.for(user).snapshot()` on the server. `null` = guest. */
36
+ snapshot: RbacSnapshot | null | undefined;
37
+ /** Enable wildcard matching (`articles.*`). Must match the server's `wildcard` setting. Default: `false`. */
38
+ wildcard?: boolean;
39
+ /** Roles that pass every `can` check (super admin). */
40
+ superAdminRoles?: readonly string[];
41
+ children?: ReactNode;
42
+ }
43
+ /**
44
+ * Provides a user's roles & permissions to `useCan()`, `<Can>`, ...
45
+ *
46
+ * UI only: this hides and shows elements. Always enforce authorization on the server.
47
+ */
48
+ declare function RbacProvider({ snapshot, wildcard, superAdminRoles, children }: RbacProviderProps): react.JSX.Element;
49
+ /** Returns the checker of the nearest `RbacProvider`. Throws when there is none. */
50
+ declare function useRbac(): RbacChecker;
51
+ declare function useCan(permission: string): boolean;
52
+ declare function useCannot(permission: string): boolean;
53
+ declare function useCanAny(...permissions: Many<string>[]): boolean;
54
+ declare function useCanAll(...permissions: Many<string>[]): boolean;
55
+ /** `true` if the user has the role — or ANY of the roles when given an array. */
56
+ declare function useHasRole(role: Many<string>): boolean;
57
+ declare function useHasAnyRole(...roles: Many<string>[]): boolean;
58
+ declare function useHasAllRoles(...roles: Many<string>[]): boolean;
59
+
60
+ /** Exactly one of `permission`, `anyOf` or `allOf`. */
61
+ type PermissionCondition = {
62
+ permission: string;
63
+ anyOf?: never;
64
+ allOf?: never;
65
+ } | {
66
+ permission?: never;
67
+ anyOf: readonly string[];
68
+ allOf?: never;
69
+ } | {
70
+ permission?: never;
71
+ anyOf?: never;
72
+ allOf: readonly string[];
73
+ };
74
+ /** Exactly one of `role`, `anyOf` or `allOf`. */
75
+ type RoleCondition = {
76
+ role: string;
77
+ anyOf?: never;
78
+ allOf?: never;
79
+ } | {
80
+ role?: never;
81
+ anyOf: readonly string[];
82
+ allOf?: never;
83
+ } | {
84
+ role?: never;
85
+ anyOf?: never;
86
+ allOf: readonly string[];
87
+ };
88
+ interface GateProps {
89
+ children?: ReactNode;
90
+ /** Rendered when the check fails. Default: nothing. */
91
+ fallback?: ReactNode;
92
+ }
93
+ type CanProps = PermissionCondition & GateProps;
94
+ type CannotProps = PermissionCondition & GateProps;
95
+ type HasRoleProps = RoleCondition & GateProps;
96
+ /** Renders `children` if the user has the permission(s) — like spatie's `@can` / `@canany`. */
97
+ declare function Can(props: CanProps): react.JSX.Element;
98
+ /** Renders `children` if the user does NOT have the permission(s) — like spatie's `@cannot`. */
99
+ declare function Cannot(props: CannotProps): react.JSX.Element;
100
+ /** Renders `children` if the user has the role(s) — like spatie's `@role` / `@hasanyrole` / `@hasallroles`. */
101
+ declare function HasRole(props: HasRoleProps): react.JSX.Element;
102
+
103
+ export { Can, type CanProps, Cannot, type CannotProps, HasRole, type HasRoleProps, type PermissionCondition, type RbacChecker, type RbacCheckerOptions, RbacProvider, type RbacProviderProps, type RoleCondition, createRbacChecker, useCan, useCanAll, useCanAny, useCannot, useHasAllRoles, useHasAnyRole, useHasRole, useRbac };
package/dist/index.js ADDED
@@ -0,0 +1,130 @@
1
+ 'use client';
2
+
3
+ // src/checker.ts
4
+ import { wildcardImplies } from "@anievo-id/rbac-evolution";
5
+ var EMPTY = { roles: [], permissions: [] };
6
+ function flatten(items) {
7
+ const out = [];
8
+ for (const item of items) {
9
+ if (typeof item === "string") out.push(item);
10
+ else out.push(...item);
11
+ }
12
+ return out;
13
+ }
14
+ function safeImplies(granted, required) {
15
+ try {
16
+ return wildcardImplies(granted, required);
17
+ } catch {
18
+ return false;
19
+ }
20
+ }
21
+ function createRbacChecker(snapshot, options = {}) {
22
+ const { roles, permissions } = snapshot ?? EMPTY;
23
+ const roleSet = new Set(roles);
24
+ const permissionSet = new Set(permissions);
25
+ const wildcard = options.wildcard ?? false;
26
+ const isSuperAdmin = (options.superAdminRoles ?? []).some((r) => roleSet.has(r));
27
+ const can = (permission) => {
28
+ if (isSuperAdmin) return true;
29
+ const name = permission.trim();
30
+ if (name === "") return false;
31
+ if (permissionSet.has(name)) return true;
32
+ return wildcard && permissions.some((granted) => safeImplies(granted, name));
33
+ };
34
+ const hasOne = (role) => roleSet.has(role.trim());
35
+ return {
36
+ roles,
37
+ permissions,
38
+ isSuperAdmin,
39
+ can,
40
+ cannot: (permission) => !can(permission),
41
+ canAny: (...list) => flatten(list).some(can),
42
+ canAll: (...list) => flatten(list).every(can),
43
+ hasRole: (list) => flatten([list]).some(hasOne),
44
+ hasAnyRole: (...list) => flatten(list).some(hasOne),
45
+ hasAllRoles: (...list) => flatten(list).every(hasOne)
46
+ };
47
+ }
48
+
49
+ // src/context.tsx
50
+ import { createContext, useContext, useMemo } from "react";
51
+ import { jsx } from "react/jsx-runtime";
52
+ var RbacContext = createContext(null);
53
+ RbacContext.displayName = "RbacContext";
54
+ function RbacProvider({ snapshot, wildcard = false, superAdminRoles, children }) {
55
+ const superKey = superAdminRoles?.join("\0") ?? "";
56
+ const checker = useMemo(
57
+ () => createRbacChecker(snapshot, superAdminRoles ? { wildcard, superAdminRoles } : { wildcard }),
58
+ // `superKey` keeps inline arrays (`superAdminRoles={['admin']}`) from recomputing every render.
59
+ // eslint-disable-next-line react-hooks/exhaustive-deps
60
+ [snapshot, wildcard, superKey]
61
+ );
62
+ return /* @__PURE__ */ jsx(RbacContext.Provider, { value: checker, children });
63
+ }
64
+ function useRbac() {
65
+ const checker = useContext(RbacContext);
66
+ if (!checker) {
67
+ throw new Error("useRbac() must be used inside <RbacProvider>.");
68
+ }
69
+ return checker;
70
+ }
71
+ function useCan(permission) {
72
+ return useRbac().can(permission);
73
+ }
74
+ function useCannot(permission) {
75
+ return useRbac().cannot(permission);
76
+ }
77
+ function useCanAny(...permissions) {
78
+ return useRbac().canAny(...permissions);
79
+ }
80
+ function useCanAll(...permissions) {
81
+ return useRbac().canAll(...permissions);
82
+ }
83
+ function useHasRole(role) {
84
+ return useRbac().hasRole(role);
85
+ }
86
+ function useHasAnyRole(...roles) {
87
+ return useRbac().hasAnyRole(...roles);
88
+ }
89
+ function useHasAllRoles(...roles) {
90
+ return useRbac().hasAllRoles(...roles);
91
+ }
92
+
93
+ // src/components.tsx
94
+ import { Fragment, jsx as jsx2 } from "react/jsx-runtime";
95
+ function checkPermissions(rbac, p) {
96
+ if (p.permission === void 0 && p.anyOf === void 0 && p.allOf === void 0) return false;
97
+ return (p.permission === void 0 || rbac.can(p.permission)) && (p.anyOf === void 0 || rbac.canAny(p.anyOf)) && (p.allOf === void 0 || rbac.canAll(p.allOf));
98
+ }
99
+ function checkRoles(rbac, p) {
100
+ if (p.role === void 0 && p.anyOf === void 0 && p.allOf === void 0) return false;
101
+ return (p.role === void 0 || rbac.hasRole(p.role)) && (p.anyOf === void 0 || rbac.hasAnyRole(p.anyOf)) && (p.allOf === void 0 || rbac.hasAllRoles(p.allOf));
102
+ }
103
+ function Can(props) {
104
+ const allowed = checkPermissions(useRbac(), props);
105
+ return /* @__PURE__ */ jsx2(Fragment, { children: allowed ? props.children : props.fallback });
106
+ }
107
+ function Cannot(props) {
108
+ const allowed = checkPermissions(useRbac(), props);
109
+ return /* @__PURE__ */ jsx2(Fragment, { children: allowed ? props.fallback : props.children });
110
+ }
111
+ function HasRole(props) {
112
+ const allowed = checkRoles(useRbac(), props);
113
+ return /* @__PURE__ */ jsx2(Fragment, { children: allowed ? props.children : props.fallback });
114
+ }
115
+ export {
116
+ Can,
117
+ Cannot,
118
+ HasRole,
119
+ RbacProvider,
120
+ createRbacChecker,
121
+ useCan,
122
+ useCanAll,
123
+ useCanAny,
124
+ useCannot,
125
+ useHasAllRoles,
126
+ useHasAnyRole,
127
+ useHasRole,
128
+ useRbac
129
+ };
130
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/checker.ts","../src/context.tsx","../src/components.tsx"],"sourcesContent":["import { wildcardImplies } from '@anievo-id/rbac-evolution'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\n\nexport interface RbacCheckerOptions {\n /** Treat granted permissions as wildcard patterns (`articles.*`). Must match the server's `wildcard` setting. */\n wildcard?: boolean\n /** Roles that pass every permission check (like spatie's `Gate::before` super-admin pattern). */\n superAdminRoles?: readonly string[]\n}\n\n/** Synchronous checks against a {@link RbacSnapshot}. */\nexport interface RbacChecker {\n readonly roles: readonly string[]\n readonly permissions: readonly string[]\n /** `true` if the subject has one of the configured `superAdminRoles`. */\n readonly isSuperAdmin: boolean\n can(permission: string): boolean\n cannot(permission: string): boolean\n /** `true` if ANY of the permissions is granted. `false` for an empty list. */\n canAny(...permissions: Many<string>[]): boolean\n /** `true` if ALL of the permissions are granted. `true` for an empty list. */\n canAll(...permissions: Many<string>[]): boolean\n /** `true` if the subject has the role — or ANY of the roles when given an array. */\n hasRole(roles: Many<string>): boolean\n hasAnyRole(...roles: Many<string>[]): boolean\n hasAllRoles(...roles: Many<string>[]): boolean\n}\n\nconst EMPTY: RbacSnapshot = { roles: [], permissions: [] }\n\nfunction flatten(items: readonly Many<string>[]): string[] {\n const out: string[] = []\n for (const item of items) {\n if (typeof item === 'string') out.push(item)\n else out.push(...item)\n }\n return out\n}\n\nfunction safeImplies(granted: string, required: string): boolean {\n try {\n return wildcardImplies(granted, required)\n } catch {\n return false\n }\n}\n\n/**\n * Builds a pure, synchronous checker for a snapshot (as returned by `rbac.for(user).snapshot()`).\n * Used by `RbacProvider`, but usable on its own too.\n */\nexport function createRbacChecker(\n snapshot: RbacSnapshot | null | undefined,\n options: RbacCheckerOptions = {},\n): RbacChecker {\n const { roles, permissions } = snapshot ?? EMPTY\n const roleSet = new Set(roles)\n const permissionSet = new Set(permissions)\n const wildcard = options.wildcard ?? false\n const isSuperAdmin = (options.superAdminRoles ?? []).some((r) => roleSet.has(r))\n\n const can = (permission: string): boolean => {\n if (isSuperAdmin) return true\n const name = permission.trim()\n if (name === '') return false\n if (permissionSet.has(name)) return true\n return wildcard && permissions.some((granted) => safeImplies(granted, name))\n }\n const hasOne = (role: string): boolean => roleSet.has(role.trim())\n\n return {\n roles,\n permissions,\n isSuperAdmin,\n can,\n cannot: (permission) => !can(permission),\n canAny: (...list) => flatten(list).some(can),\n canAll: (...list) => flatten(list).every(can),\n hasRole: (list) => flatten([list]).some(hasOne),\n hasAnyRole: (...list) => flatten(list).some(hasOne),\n hasAllRoles: (...list) => flatten(list).every(hasOne),\n }\n}\n","import { createContext, useContext, useMemo } from 'react'\nimport type { ReactNode } from 'react'\nimport type { Many, RbacSnapshot } from '@anievo-id/rbac-evolution'\nimport { createRbacChecker } from './checker'\nimport type { RbacChecker } from './checker'\n\nconst RbacContext = createContext<RbacChecker | null>(null)\nRbacContext.displayName = 'RbacContext'\n\nexport interface RbacProviderProps {\n /** Roles & permissions of the current user, e.g. from `rbac.for(user).snapshot()` on the server. `null` = guest. */\n snapshot: RbacSnapshot | null | undefined\n /** Enable wildcard matching (`articles.*`). Must match the server's `wildcard` setting. Default: `false`. */\n wildcard?: boolean\n /** Roles that pass every `can` check (super admin). */\n superAdminRoles?: readonly string[]\n children?: ReactNode\n}\n\n/**\n * Provides a user's roles & permissions to `useCan()`, `<Can>`, ...\n *\n * UI only: this hides and shows elements. Always enforce authorization on the server.\n */\nexport function RbacProvider({ snapshot, wildcard = false, superAdminRoles, children }: RbacProviderProps) {\n const superKey = superAdminRoles?.join('\\u0000') ?? ''\n const checker = useMemo(\n () => createRbacChecker(snapshot, superAdminRoles ? { wildcard, superAdminRoles } : { wildcard }),\n // `superKey` keeps inline arrays (`superAdminRoles={['admin']}`) from recomputing every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [snapshot, wildcard, superKey],\n )\n return <RbacContext.Provider value={checker}>{children}</RbacContext.Provider>\n}\n\n/** Returns the checker of the nearest `RbacProvider`. Throws when there is none. */\nexport function useRbac(): RbacChecker {\n const checker = useContext(RbacContext)\n if (!checker) {\n throw new Error('useRbac() must be used inside <RbacProvider>.')\n }\n return checker\n}\n\nexport function useCan(permission: string): boolean {\n return useRbac().can(permission)\n}\n\nexport function useCannot(permission: string): boolean {\n return useRbac().cannot(permission)\n}\n\nexport function useCanAny(...permissions: Many<string>[]): boolean {\n return useRbac().canAny(...permissions)\n}\n\nexport function useCanAll(...permissions: Many<string>[]): boolean {\n return useRbac().canAll(...permissions)\n}\n\n/** `true` if the user has the role — or ANY of the roles when given an array. */\nexport function useHasRole(role: Many<string>): boolean {\n return useRbac().hasRole(role)\n}\n\nexport function useHasAnyRole(...roles: Many<string>[]): boolean {\n return useRbac().hasAnyRole(...roles)\n}\n\nexport function useHasAllRoles(...roles: Many<string>[]): boolean {\n return useRbac().hasAllRoles(...roles)\n}\n","import type { ReactNode } from 'react'\nimport type { RbacChecker } from './checker'\nimport { useRbac } from './context'\n\n/** Exactly one of `permission`, `anyOf` or `allOf`. */\nexport type PermissionCondition =\n | { permission: string; anyOf?: never; allOf?: never }\n | { permission?: never; anyOf: readonly string[]; allOf?: never }\n | { permission?: never; anyOf?: never; allOf: readonly string[] }\n\n/** Exactly one of `role`, `anyOf` or `allOf`. */\nexport type RoleCondition =\n | { role: string; anyOf?: never; allOf?: never }\n | { role?: never; anyOf: readonly string[]; allOf?: never }\n | { role?: never; anyOf?: never; allOf: readonly string[] }\n\ninterface GateProps {\n children?: ReactNode\n /** Rendered when the check fails. Default: nothing. */\n fallback?: ReactNode\n}\n\nexport type CanProps = PermissionCondition & GateProps\nexport type CannotProps = PermissionCondition & GateProps\nexport type HasRoleProps = RoleCondition & GateProps\n\ninterface LooseCondition {\n anyOf?: readonly string[] | undefined\n allOf?: readonly string[] | undefined\n}\n\n// Conditions are ANDed; no condition at all is denied (deny by default, also for untyped JS callers).\nfunction checkPermissions(rbac: RbacChecker, p: LooseCondition & { permission?: string | undefined }): boolean {\n if (p.permission === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.permission === undefined || rbac.can(p.permission)) &&\n (p.anyOf === undefined || rbac.canAny(p.anyOf)) &&\n (p.allOf === undefined || rbac.canAll(p.allOf))\n )\n}\n\nfunction checkRoles(rbac: RbacChecker, p: LooseCondition & { role?: string | undefined }): boolean {\n if (p.role === undefined && p.anyOf === undefined && p.allOf === undefined) return false\n return (\n (p.role === undefined || rbac.hasRole(p.role)) &&\n (p.anyOf === undefined || rbac.hasAnyRole(p.anyOf)) &&\n (p.allOf === undefined || rbac.hasAllRoles(p.allOf))\n )\n}\n\n/** Renders `children` if the user has the permission(s) — like spatie's `@can` / `@canany`. */\nexport function Can(props: CanProps) {\n const allowed = checkPermissions(useRbac(), props)\n return <>{allowed ? props.children : props.fallback}</>\n}\n\n/** Renders `children` if the user does NOT have the permission(s) — like spatie's `@cannot`. */\nexport function Cannot(props: CannotProps) {\n const allowed = checkPermissions(useRbac(), props)\n return <>{allowed ? props.fallback : props.children}</>\n}\n\n/** Renders `children` if the user has the role(s) — like spatie's `@role` / `@hasanyrole` / `@hasallroles`. */\nexport function HasRole(props: HasRoleProps) {\n const allowed = checkRoles(useRbac(), props)\n return <>{allowed ? props.children : props.fallback}</>\n}\n"],"mappings":";;;AAAA,SAAS,uBAAuB;AA4BhC,IAAM,QAAsB,EAAE,OAAO,C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BAAAA,YAAA;AArBT,SAAS,iBAAiB,MAAmB,GAAkE;AAC7G,MAAI,EAAE,eAAe,UAAa,EAAE,UAAU,UAAa,EAAE,UAAU,OAAW,QAAO;AACzF,UACG,EAAE,eAAe,UAAa,KAAK,IAAI,EAAE,UAAU,OACnD,EAAE,UAAU,UAAa,KAAK,OAAO,EAAE,KAAK,OAC5C,EAAE,UAAU,UAAa,KAAK,OAAO,EAAE,KAAK;AAEjD;AAEA,SAAS,WAAW,MAAmB,GAA4D;AACjG,MAAI,EAAE,SAAS,UAAa,EAAE,UAAU,UAAa,EAAE,UAAU,OAAW,QAAO;AACnF,UACG,EAAE,SAAS,UAAa,KAAK,QAAQ,EAAE,IAAI,OAC3C,EAAE,UAAU,UAAa,KAAK,WAAW,EAAE,KAAK,OAChD,EAAE,UAAU,UAAa,KAAK,YAAY,EAAE,KAAK;AAEtD;AAGO,SAAS,IAAI,OAAiB;AACnC,QAAM,UAAU,iBAAiB,QAAQ,GAAG,KAAK;AACjD,SAAO,gBAAAA,KAAA,YAAG,oBAAU,MAAM,WAAW,MAAM,UAAS;AACtD;AAGO,SAAS,OAAO,OAAoB;AACzC,QAAM,UAAU,iBAAiB,QAAQ,GAAG,KAAK;AACjD,SAAO,gBAAAA,KAAA,YAAG,oBAAU,MAAM,WAAW,MAAM,UAAS;AACtD;AAGO,SAAS,QAAQ,OAAqB;AAC3C,QAAM,UAAU,WAAW,QAAQ,GAAG,KAAK;AAC3C,SAAO,gBAAAA,KAAA,YAAG,oBAAU,MAAM,WAAW,MAAM,UAAS;AACtD;","names":["jsx"]}
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "@anievo-id/rbac-evolution-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "React bindings for rbac-evolution: <Can>, useCan(), useRole().",
5
+ "license": "MIT",
6
+ "author": "AniEvo-ID (https://github.com/AniEvo-ID)",
7
+ "homepage": "https://github.com/AniEvo-ID/rbac-evolution/tree/main/packages/react#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/AniEvo-ID/rbac-evolution/issues"
10
+ },
11
+ "type": "module",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/AniEvo-ID/rbac-evolution.git",
15
+ "directory": "packages/react"
16
+ },
17
+ "keywords": [
18
+ "rbac",
19
+ "permissions",
20
+ "roles",
21
+ "authorization",
22
+ "react",
23
+ "hooks"
24
+ ],
25
+ "sideEffects": false,
26
+ "main": "./dist/index.cjs",
27
+ "module": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "import": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/index.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/index.d.cts",
37
+ "default": "./dist/index.cjs"
38
+ }
39
+ },
40
+ "./package.json": "./package.json"
41
+ },
42
+ "files": [
43
+ "dist"
44
+ ],
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "dependencies": {
49
+ "@anievo-id/rbac-evolution": "^0.1.1"
50
+ },
51
+ "peerDependencies": {
52
+ "react": ">=18"
53
+ },
54
+ "devDependencies": {
55
+ "react": "^19.0.0",
56
+ "react-dom": "^19.0.0",
57
+ "@types/react": "^19.0.0",
58
+ "@types/react-dom": "^19.0.0",
59
+ "@testing-library/react": "^16.1.0",
60
+ "jsdom": "^25.0.0",
61
+ "tsup": "^8.3.0",
62
+ "typescript": "^5.7.0",
63
+ "vitest": "^2.1.0"
64
+ },
65
+ "engines": {
66
+ "node": ">=20"
67
+ },
68
+ "scripts": {
69
+ "build": "tsup && node scripts/check-use-client.mjs",
70
+ "dev": "tsup --watch",
71
+ "typecheck": "tsc --noEmit",
72
+ "test": "vitest run --passWithNoTests",
73
+ "clean": "rm -rf dist .turbo"
74
+ }
6
75
  }