role-permission-engine 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +139 -0
- package/LICENSE +21 -0
- package/README.md +682 -0
- package/dist/index.cjs.js +2558 -0
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.esm.js +2548 -0
- package/dist/index.esm.js.map +1 -0
- package/dist/utils.cjs.js +389 -0
- package/dist/utils.cjs.js.map +1 -0
- package/dist/utils.esm.js +385 -0
- package/dist/utils.esm.js.map +1 -0
- package/package.json +106 -0
- package/types/index.d.ts +229 -0
- package/types/utils.d.ts +40 -0
|
@@ -0,0 +1,2548 @@
|
|
|
1
|
+
import require$$0, { createContext, useMemo, useContext } from 'react';
|
|
2
|
+
|
|
3
|
+
var jsxRuntime = {exports: {}};
|
|
4
|
+
|
|
5
|
+
var reactJsxRuntime_production_min = {};
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @license React
|
|
9
|
+
* react-jsx-runtime.production.min.js
|
|
10
|
+
*
|
|
11
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
12
|
+
*
|
|
13
|
+
* This source code is licensed under the MIT license found in the
|
|
14
|
+
* LICENSE file in the root directory of this source tree.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
var hasRequiredReactJsxRuntime_production_min;
|
|
18
|
+
|
|
19
|
+
function requireReactJsxRuntime_production_min () {
|
|
20
|
+
if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
|
|
21
|
+
hasRequiredReactJsxRuntime_production_min = 1;
|
|
22
|
+
var f=require$$0,k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:true,ref:true,__self:true,__source:true};
|
|
23
|
+
function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a) void 0===d[b]&&(d[b]=a[b]);return {$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}reactJsxRuntime_production_min.Fragment=l;reactJsxRuntime_production_min.jsx=q;reactJsxRuntime_production_min.jsxs=q;
|
|
24
|
+
return reactJsxRuntime_production_min;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
var reactJsxRuntime_development = {};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @license React
|
|
31
|
+
* react-jsx-runtime.development.js
|
|
32
|
+
*
|
|
33
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
34
|
+
*
|
|
35
|
+
* This source code is licensed under the MIT license found in the
|
|
36
|
+
* LICENSE file in the root directory of this source tree.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
var hasRequiredReactJsxRuntime_development;
|
|
40
|
+
|
|
41
|
+
function requireReactJsxRuntime_development () {
|
|
42
|
+
if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
|
|
43
|
+
hasRequiredReactJsxRuntime_development = 1;
|
|
44
|
+
|
|
45
|
+
if (process.env.NODE_ENV !== "production") {
|
|
46
|
+
(function() {
|
|
47
|
+
|
|
48
|
+
var React = require$$0;
|
|
49
|
+
|
|
50
|
+
// ATTENTION
|
|
51
|
+
// When adding new symbols to this file,
|
|
52
|
+
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
|
|
53
|
+
// The Symbol used to tag the ReactElement-like types.
|
|
54
|
+
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
|
|
55
|
+
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
|
|
56
|
+
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
|
|
57
|
+
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
|
|
58
|
+
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
|
|
59
|
+
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
|
|
60
|
+
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
|
|
61
|
+
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
|
|
62
|
+
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
|
|
63
|
+
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
|
|
64
|
+
var REACT_MEMO_TYPE = Symbol.for('react.memo');
|
|
65
|
+
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
|
|
66
|
+
var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
|
|
67
|
+
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
|
|
68
|
+
var FAUX_ITERATOR_SYMBOL = '@@iterator';
|
|
69
|
+
function getIteratorFn(maybeIterable) {
|
|
70
|
+
if (maybeIterable === null || typeof maybeIterable !== 'object') {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
|
|
75
|
+
|
|
76
|
+
if (typeof maybeIterator === 'function') {
|
|
77
|
+
return maybeIterator;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
|
|
84
|
+
|
|
85
|
+
function error(format) {
|
|
86
|
+
{
|
|
87
|
+
{
|
|
88
|
+
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
|
|
89
|
+
args[_key2 - 1] = arguments[_key2];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
printWarning('error', format, args);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function printWarning(level, format, args) {
|
|
98
|
+
// When changing this logic, you might want to also
|
|
99
|
+
// update consoleWithStackDev.www.js as well.
|
|
100
|
+
{
|
|
101
|
+
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
|
|
102
|
+
var stack = ReactDebugCurrentFrame.getStackAddendum();
|
|
103
|
+
|
|
104
|
+
if (stack !== '') {
|
|
105
|
+
format += '%s';
|
|
106
|
+
args = args.concat([stack]);
|
|
107
|
+
} // eslint-disable-next-line react-internal/safe-string-coercion
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
var argsWithFormat = args.map(function (item) {
|
|
111
|
+
return String(item);
|
|
112
|
+
}); // Careful: RN currently depends on this prefix
|
|
113
|
+
|
|
114
|
+
argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
|
|
115
|
+
// breaks IE9: https://github.com/facebook/react/issues/13610
|
|
116
|
+
// eslint-disable-next-line react-internal/no-production-logging
|
|
117
|
+
|
|
118
|
+
Function.prototype.apply.call(console[level], console, argsWithFormat);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// -----------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
var enableScopeAPI = false; // Experimental Create Event Handle API.
|
|
125
|
+
var enableCacheElement = false;
|
|
126
|
+
var enableTransitionTracing = false; // No known bugs, but needs performance testing
|
|
127
|
+
|
|
128
|
+
var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
|
|
129
|
+
// stuff. Intended to enable React core members to more easily debug scheduling
|
|
130
|
+
// issues in DEV builds.
|
|
131
|
+
|
|
132
|
+
var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
|
|
133
|
+
|
|
134
|
+
var REACT_MODULE_REFERENCE;
|
|
135
|
+
|
|
136
|
+
{
|
|
137
|
+
REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function isValidElementType(type) {
|
|
141
|
+
if (typeof type === 'string' || typeof type === 'function') {
|
|
142
|
+
return true;
|
|
143
|
+
} // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (typeof type === 'object' && type !== null) {
|
|
151
|
+
if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
|
|
152
|
+
// types supported by any Flight configuration anywhere since
|
|
153
|
+
// we don't know which Flight build this will end up being used
|
|
154
|
+
// with.
|
|
155
|
+
type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
|
|
156
|
+
return true;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function getWrappedName(outerType, innerType, wrapperName) {
|
|
164
|
+
var displayName = outerType.displayName;
|
|
165
|
+
|
|
166
|
+
if (displayName) {
|
|
167
|
+
return displayName;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
var functionName = innerType.displayName || innerType.name || '';
|
|
171
|
+
return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
|
|
172
|
+
} // Keep in sync with react-reconciler/getComponentNameFromFiber
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
function getContextName(type) {
|
|
176
|
+
return type.displayName || 'Context';
|
|
177
|
+
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
function getComponentNameFromType(type) {
|
|
181
|
+
if (type == null) {
|
|
182
|
+
// Host root, text node or just invalid type.
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
{
|
|
187
|
+
if (typeof type.tag === 'number') {
|
|
188
|
+
error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (typeof type === 'function') {
|
|
193
|
+
return type.displayName || type.name || null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (typeof type === 'string') {
|
|
197
|
+
return type;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
switch (type) {
|
|
201
|
+
case REACT_FRAGMENT_TYPE:
|
|
202
|
+
return 'Fragment';
|
|
203
|
+
|
|
204
|
+
case REACT_PORTAL_TYPE:
|
|
205
|
+
return 'Portal';
|
|
206
|
+
|
|
207
|
+
case REACT_PROFILER_TYPE:
|
|
208
|
+
return 'Profiler';
|
|
209
|
+
|
|
210
|
+
case REACT_STRICT_MODE_TYPE:
|
|
211
|
+
return 'StrictMode';
|
|
212
|
+
|
|
213
|
+
case REACT_SUSPENSE_TYPE:
|
|
214
|
+
return 'Suspense';
|
|
215
|
+
|
|
216
|
+
case REACT_SUSPENSE_LIST_TYPE:
|
|
217
|
+
return 'SuspenseList';
|
|
218
|
+
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (typeof type === 'object') {
|
|
222
|
+
switch (type.$$typeof) {
|
|
223
|
+
case REACT_CONTEXT_TYPE:
|
|
224
|
+
var context = type;
|
|
225
|
+
return getContextName(context) + '.Consumer';
|
|
226
|
+
|
|
227
|
+
case REACT_PROVIDER_TYPE:
|
|
228
|
+
var provider = type;
|
|
229
|
+
return getContextName(provider._context) + '.Provider';
|
|
230
|
+
|
|
231
|
+
case REACT_FORWARD_REF_TYPE:
|
|
232
|
+
return getWrappedName(type, type.render, 'ForwardRef');
|
|
233
|
+
|
|
234
|
+
case REACT_MEMO_TYPE:
|
|
235
|
+
var outerName = type.displayName || null;
|
|
236
|
+
|
|
237
|
+
if (outerName !== null) {
|
|
238
|
+
return outerName;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return getComponentNameFromType(type.type) || 'Memo';
|
|
242
|
+
|
|
243
|
+
case REACT_LAZY_TYPE:
|
|
244
|
+
{
|
|
245
|
+
var lazyComponent = type;
|
|
246
|
+
var payload = lazyComponent._payload;
|
|
247
|
+
var init = lazyComponent._init;
|
|
248
|
+
|
|
249
|
+
try {
|
|
250
|
+
return getComponentNameFromType(init(payload));
|
|
251
|
+
} catch (x) {
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// eslint-disable-next-line no-fallthrough
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
var assign = Object.assign;
|
|
264
|
+
|
|
265
|
+
// Helpers to patch console.logs to avoid logging during side-effect free
|
|
266
|
+
// replaying on render function. This currently only patches the object
|
|
267
|
+
// lazily which won't cover if the log function was extracted eagerly.
|
|
268
|
+
// We could also eagerly patch the method.
|
|
269
|
+
var disabledDepth = 0;
|
|
270
|
+
var prevLog;
|
|
271
|
+
var prevInfo;
|
|
272
|
+
var prevWarn;
|
|
273
|
+
var prevError;
|
|
274
|
+
var prevGroup;
|
|
275
|
+
var prevGroupCollapsed;
|
|
276
|
+
var prevGroupEnd;
|
|
277
|
+
|
|
278
|
+
function disabledLog() {}
|
|
279
|
+
|
|
280
|
+
disabledLog.__reactDisabledLog = true;
|
|
281
|
+
function disableLogs() {
|
|
282
|
+
{
|
|
283
|
+
if (disabledDepth === 0) {
|
|
284
|
+
/* eslint-disable react-internal/no-production-logging */
|
|
285
|
+
prevLog = console.log;
|
|
286
|
+
prevInfo = console.info;
|
|
287
|
+
prevWarn = console.warn;
|
|
288
|
+
prevError = console.error;
|
|
289
|
+
prevGroup = console.group;
|
|
290
|
+
prevGroupCollapsed = console.groupCollapsed;
|
|
291
|
+
prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
|
|
292
|
+
|
|
293
|
+
var props = {
|
|
294
|
+
configurable: true,
|
|
295
|
+
enumerable: true,
|
|
296
|
+
value: disabledLog,
|
|
297
|
+
writable: true
|
|
298
|
+
}; // $FlowFixMe Flow thinks console is immutable.
|
|
299
|
+
|
|
300
|
+
Object.defineProperties(console, {
|
|
301
|
+
info: props,
|
|
302
|
+
log: props,
|
|
303
|
+
warn: props,
|
|
304
|
+
error: props,
|
|
305
|
+
group: props,
|
|
306
|
+
groupCollapsed: props,
|
|
307
|
+
groupEnd: props
|
|
308
|
+
});
|
|
309
|
+
/* eslint-enable react-internal/no-production-logging */
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
disabledDepth++;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
function reenableLogs() {
|
|
316
|
+
{
|
|
317
|
+
disabledDepth--;
|
|
318
|
+
|
|
319
|
+
if (disabledDepth === 0) {
|
|
320
|
+
/* eslint-disable react-internal/no-production-logging */
|
|
321
|
+
var props = {
|
|
322
|
+
configurable: true,
|
|
323
|
+
enumerable: true,
|
|
324
|
+
writable: true
|
|
325
|
+
}; // $FlowFixMe Flow thinks console is immutable.
|
|
326
|
+
|
|
327
|
+
Object.defineProperties(console, {
|
|
328
|
+
log: assign({}, props, {
|
|
329
|
+
value: prevLog
|
|
330
|
+
}),
|
|
331
|
+
info: assign({}, props, {
|
|
332
|
+
value: prevInfo
|
|
333
|
+
}),
|
|
334
|
+
warn: assign({}, props, {
|
|
335
|
+
value: prevWarn
|
|
336
|
+
}),
|
|
337
|
+
error: assign({}, props, {
|
|
338
|
+
value: prevError
|
|
339
|
+
}),
|
|
340
|
+
group: assign({}, props, {
|
|
341
|
+
value: prevGroup
|
|
342
|
+
}),
|
|
343
|
+
groupCollapsed: assign({}, props, {
|
|
344
|
+
value: prevGroupCollapsed
|
|
345
|
+
}),
|
|
346
|
+
groupEnd: assign({}, props, {
|
|
347
|
+
value: prevGroupEnd
|
|
348
|
+
})
|
|
349
|
+
});
|
|
350
|
+
/* eslint-enable react-internal/no-production-logging */
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (disabledDepth < 0) {
|
|
354
|
+
error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
|
|
360
|
+
var prefix;
|
|
361
|
+
function describeBuiltInComponentFrame(name, source, ownerFn) {
|
|
362
|
+
{
|
|
363
|
+
if (prefix === undefined) {
|
|
364
|
+
// Extract the VM specific prefix used by each line.
|
|
365
|
+
try {
|
|
366
|
+
throw Error();
|
|
367
|
+
} catch (x) {
|
|
368
|
+
var match = x.stack.trim().match(/\n( *(at )?)/);
|
|
369
|
+
prefix = match && match[1] || '';
|
|
370
|
+
}
|
|
371
|
+
} // We use the prefix to ensure our stacks line up with native stack frames.
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
return '\n' + prefix + name;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
var reentry = false;
|
|
378
|
+
var componentFrameCache;
|
|
379
|
+
|
|
380
|
+
{
|
|
381
|
+
var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
|
|
382
|
+
componentFrameCache = new PossiblyWeakMap();
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function describeNativeComponentFrame(fn, construct) {
|
|
386
|
+
// If something asked for a stack inside a fake render, it should get ignored.
|
|
387
|
+
if ( !fn || reentry) {
|
|
388
|
+
return '';
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
{
|
|
392
|
+
var frame = componentFrameCache.get(fn);
|
|
393
|
+
|
|
394
|
+
if (frame !== undefined) {
|
|
395
|
+
return frame;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
var control;
|
|
400
|
+
reentry = true;
|
|
401
|
+
var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
|
|
402
|
+
|
|
403
|
+
Error.prepareStackTrace = undefined;
|
|
404
|
+
var previousDispatcher;
|
|
405
|
+
|
|
406
|
+
{
|
|
407
|
+
previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
|
|
408
|
+
// for warnings.
|
|
409
|
+
|
|
410
|
+
ReactCurrentDispatcher.current = null;
|
|
411
|
+
disableLogs();
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
try {
|
|
415
|
+
// This should throw.
|
|
416
|
+
if (construct) {
|
|
417
|
+
// Something should be setting the props in the constructor.
|
|
418
|
+
var Fake = function () {
|
|
419
|
+
throw Error();
|
|
420
|
+
}; // $FlowFixMe
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
Object.defineProperty(Fake.prototype, 'props', {
|
|
424
|
+
set: function () {
|
|
425
|
+
// We use a throwing setter instead of frozen or non-writable props
|
|
426
|
+
// because that won't throw in a non-strict mode function.
|
|
427
|
+
throw Error();
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
if (typeof Reflect === 'object' && Reflect.construct) {
|
|
432
|
+
// We construct a different control for this case to include any extra
|
|
433
|
+
// frames added by the construct call.
|
|
434
|
+
try {
|
|
435
|
+
Reflect.construct(Fake, []);
|
|
436
|
+
} catch (x) {
|
|
437
|
+
control = x;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
Reflect.construct(fn, [], Fake);
|
|
441
|
+
} else {
|
|
442
|
+
try {
|
|
443
|
+
Fake.call();
|
|
444
|
+
} catch (x) {
|
|
445
|
+
control = x;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
fn.call(Fake.prototype);
|
|
449
|
+
}
|
|
450
|
+
} else {
|
|
451
|
+
try {
|
|
452
|
+
throw Error();
|
|
453
|
+
} catch (x) {
|
|
454
|
+
control = x;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
fn();
|
|
458
|
+
}
|
|
459
|
+
} catch (sample) {
|
|
460
|
+
// This is inlined manually because closure doesn't do it for us.
|
|
461
|
+
if (sample && control && typeof sample.stack === 'string') {
|
|
462
|
+
// This extracts the first frame from the sample that isn't also in the control.
|
|
463
|
+
// Skipping one frame that we assume is the frame that calls the two.
|
|
464
|
+
var sampleLines = sample.stack.split('\n');
|
|
465
|
+
var controlLines = control.stack.split('\n');
|
|
466
|
+
var s = sampleLines.length - 1;
|
|
467
|
+
var c = controlLines.length - 1;
|
|
468
|
+
|
|
469
|
+
while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
|
|
470
|
+
// We expect at least one stack frame to be shared.
|
|
471
|
+
// Typically this will be the root most one. However, stack frames may be
|
|
472
|
+
// cut off due to maximum stack limits. In this case, one maybe cut off
|
|
473
|
+
// earlier than the other. We assume that the sample is longer or the same
|
|
474
|
+
// and there for cut off earlier. So we should find the root most frame in
|
|
475
|
+
// the sample somewhere in the control.
|
|
476
|
+
c--;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
for (; s >= 1 && c >= 0; s--, c--) {
|
|
480
|
+
// Next we find the first one that isn't the same which should be the
|
|
481
|
+
// frame that called our sample function and the control.
|
|
482
|
+
if (sampleLines[s] !== controlLines[c]) {
|
|
483
|
+
// In V8, the first line is describing the message but other VMs don't.
|
|
484
|
+
// If we're about to return the first line, and the control is also on the same
|
|
485
|
+
// line, that's a pretty good indicator that our sample threw at same line as
|
|
486
|
+
// the control. I.e. before we entered the sample frame. So we ignore this result.
|
|
487
|
+
// This can happen if you passed a class to function component, or non-function.
|
|
488
|
+
if (s !== 1 || c !== 1) {
|
|
489
|
+
do {
|
|
490
|
+
s--;
|
|
491
|
+
c--; // We may still have similar intermediate frames from the construct call.
|
|
492
|
+
// The next one that isn't the same should be our match though.
|
|
493
|
+
|
|
494
|
+
if (c < 0 || sampleLines[s] !== controlLines[c]) {
|
|
495
|
+
// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
|
|
496
|
+
var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
|
|
497
|
+
// but we have a user-provided "displayName"
|
|
498
|
+
// splice it in to make the stack more readable.
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
if (fn.displayName && _frame.includes('<anonymous>')) {
|
|
502
|
+
_frame = _frame.replace('<anonymous>', fn.displayName);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
{
|
|
506
|
+
if (typeof fn === 'function') {
|
|
507
|
+
componentFrameCache.set(fn, _frame);
|
|
508
|
+
}
|
|
509
|
+
} // Return the line we found.
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
return _frame;
|
|
513
|
+
}
|
|
514
|
+
} while (s >= 1 && c >= 0);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
break;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
} finally {
|
|
522
|
+
reentry = false;
|
|
523
|
+
|
|
524
|
+
{
|
|
525
|
+
ReactCurrentDispatcher.current = previousDispatcher;
|
|
526
|
+
reenableLogs();
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
Error.prepareStackTrace = previousPrepareStackTrace;
|
|
530
|
+
} // Fallback to just using the name if we couldn't make it throw.
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
var name = fn ? fn.displayName || fn.name : '';
|
|
534
|
+
var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
|
|
535
|
+
|
|
536
|
+
{
|
|
537
|
+
if (typeof fn === 'function') {
|
|
538
|
+
componentFrameCache.set(fn, syntheticFrame);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
return syntheticFrame;
|
|
543
|
+
}
|
|
544
|
+
function describeFunctionComponentFrame(fn, source, ownerFn) {
|
|
545
|
+
{
|
|
546
|
+
return describeNativeComponentFrame(fn, false);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function shouldConstruct(Component) {
|
|
551
|
+
var prototype = Component.prototype;
|
|
552
|
+
return !!(prototype && prototype.isReactComponent);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
|
|
556
|
+
|
|
557
|
+
if (type == null) {
|
|
558
|
+
return '';
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
if (typeof type === 'function') {
|
|
562
|
+
{
|
|
563
|
+
return describeNativeComponentFrame(type, shouldConstruct(type));
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
if (typeof type === 'string') {
|
|
568
|
+
return describeBuiltInComponentFrame(type);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
switch (type) {
|
|
572
|
+
case REACT_SUSPENSE_TYPE:
|
|
573
|
+
return describeBuiltInComponentFrame('Suspense');
|
|
574
|
+
|
|
575
|
+
case REACT_SUSPENSE_LIST_TYPE:
|
|
576
|
+
return describeBuiltInComponentFrame('SuspenseList');
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
if (typeof type === 'object') {
|
|
580
|
+
switch (type.$$typeof) {
|
|
581
|
+
case REACT_FORWARD_REF_TYPE:
|
|
582
|
+
return describeFunctionComponentFrame(type.render);
|
|
583
|
+
|
|
584
|
+
case REACT_MEMO_TYPE:
|
|
585
|
+
// Memo may contain any component type so we recursively resolve it.
|
|
586
|
+
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
|
|
587
|
+
|
|
588
|
+
case REACT_LAZY_TYPE:
|
|
589
|
+
{
|
|
590
|
+
var lazyComponent = type;
|
|
591
|
+
var payload = lazyComponent._payload;
|
|
592
|
+
var init = lazyComponent._init;
|
|
593
|
+
|
|
594
|
+
try {
|
|
595
|
+
// Lazy may contain any component type so we recursively resolve it.
|
|
596
|
+
return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
|
|
597
|
+
} catch (x) {}
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
return '';
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
var hasOwnProperty = Object.prototype.hasOwnProperty;
|
|
606
|
+
|
|
607
|
+
var loggedTypeFailures = {};
|
|
608
|
+
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
|
|
609
|
+
|
|
610
|
+
function setCurrentlyValidatingElement(element) {
|
|
611
|
+
{
|
|
612
|
+
if (element) {
|
|
613
|
+
var owner = element._owner;
|
|
614
|
+
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
|
|
615
|
+
ReactDebugCurrentFrame.setExtraStackFrame(stack);
|
|
616
|
+
} else {
|
|
617
|
+
ReactDebugCurrentFrame.setExtraStackFrame(null);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
function checkPropTypes(typeSpecs, values, location, componentName, element) {
|
|
623
|
+
{
|
|
624
|
+
// $FlowFixMe This is okay but Flow doesn't know it.
|
|
625
|
+
var has = Function.call.bind(hasOwnProperty);
|
|
626
|
+
|
|
627
|
+
for (var typeSpecName in typeSpecs) {
|
|
628
|
+
if (has(typeSpecs, typeSpecName)) {
|
|
629
|
+
var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
|
|
630
|
+
// fail the render phase where it didn't fail before. So we log it.
|
|
631
|
+
// After these have been cleaned up, we'll let them throw.
|
|
632
|
+
|
|
633
|
+
try {
|
|
634
|
+
// This is intentionally an invariant that gets caught. It's the same
|
|
635
|
+
// behavior as without this statement except with a better message.
|
|
636
|
+
if (typeof typeSpecs[typeSpecName] !== 'function') {
|
|
637
|
+
// eslint-disable-next-line react-internal/prod-error-codes
|
|
638
|
+
var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
|
|
639
|
+
err.name = 'Invariant Violation';
|
|
640
|
+
throw err;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
|
|
644
|
+
} catch (ex) {
|
|
645
|
+
error$1 = ex;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
if (error$1 && !(error$1 instanceof Error)) {
|
|
649
|
+
setCurrentlyValidatingElement(element);
|
|
650
|
+
|
|
651
|
+
error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
|
|
652
|
+
|
|
653
|
+
setCurrentlyValidatingElement(null);
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
|
|
657
|
+
// Only monitor this failure once because there tends to be a lot of the
|
|
658
|
+
// same error.
|
|
659
|
+
loggedTypeFailures[error$1.message] = true;
|
|
660
|
+
setCurrentlyValidatingElement(element);
|
|
661
|
+
|
|
662
|
+
error('Failed %s type: %s', location, error$1.message);
|
|
663
|
+
|
|
664
|
+
setCurrentlyValidatingElement(null);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
|
|
672
|
+
|
|
673
|
+
function isArray(a) {
|
|
674
|
+
return isArrayImpl(a);
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/*
|
|
678
|
+
* The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
|
|
679
|
+
* and Temporal.* types. See https://github.com/facebook/react/pull/22064.
|
|
680
|
+
*
|
|
681
|
+
* The functions in this module will throw an easier-to-understand,
|
|
682
|
+
* easier-to-debug exception with a clear errors message message explaining the
|
|
683
|
+
* problem. (Instead of a confusing exception thrown inside the implementation
|
|
684
|
+
* of the `value` object).
|
|
685
|
+
*/
|
|
686
|
+
// $FlowFixMe only called in DEV, so void return is not possible.
|
|
687
|
+
function typeName(value) {
|
|
688
|
+
{
|
|
689
|
+
// toStringTag is needed for namespaced types like Temporal.Instant
|
|
690
|
+
var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
|
|
691
|
+
var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
|
|
692
|
+
return type;
|
|
693
|
+
}
|
|
694
|
+
} // $FlowFixMe only called in DEV, so void return is not possible.
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
function willCoercionThrow(value) {
|
|
698
|
+
{
|
|
699
|
+
try {
|
|
700
|
+
testStringCoercion(value);
|
|
701
|
+
return false;
|
|
702
|
+
} catch (e) {
|
|
703
|
+
return true;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
function testStringCoercion(value) {
|
|
709
|
+
// If you ended up here by following an exception call stack, here's what's
|
|
710
|
+
// happened: you supplied an object or symbol value to React (as a prop, key,
|
|
711
|
+
// DOM attribute, CSS property, string ref, etc.) and when React tried to
|
|
712
|
+
// coerce it to a string using `'' + value`, an exception was thrown.
|
|
713
|
+
//
|
|
714
|
+
// The most common types that will cause this exception are `Symbol` instances
|
|
715
|
+
// and Temporal objects like `Temporal.Instant`. But any object that has a
|
|
716
|
+
// `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
|
|
717
|
+
// exception. (Library authors do this to prevent users from using built-in
|
|
718
|
+
// numeric operators like `+` or comparison operators like `>=` because custom
|
|
719
|
+
// methods are needed to perform accurate arithmetic or comparison.)
|
|
720
|
+
//
|
|
721
|
+
// To fix the problem, coerce this object or symbol value to a string before
|
|
722
|
+
// passing it to React. The most reliable way is usually `String(value)`.
|
|
723
|
+
//
|
|
724
|
+
// To find which value is throwing, check the browser or debugger console.
|
|
725
|
+
// Before this exception was thrown, there should be `console.error` output
|
|
726
|
+
// that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
|
|
727
|
+
// problem and how that type was used: key, atrribute, input value prop, etc.
|
|
728
|
+
// In most cases, this console output also shows the component and its
|
|
729
|
+
// ancestor components where the exception happened.
|
|
730
|
+
//
|
|
731
|
+
// eslint-disable-next-line react-internal/safe-string-coercion
|
|
732
|
+
return '' + value;
|
|
733
|
+
}
|
|
734
|
+
function checkKeyStringCoercion(value) {
|
|
735
|
+
{
|
|
736
|
+
if (willCoercionThrow(value)) {
|
|
737
|
+
error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
|
|
738
|
+
|
|
739
|
+
return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
|
|
745
|
+
var RESERVED_PROPS = {
|
|
746
|
+
key: true,
|
|
747
|
+
ref: true,
|
|
748
|
+
__self: true,
|
|
749
|
+
__source: true
|
|
750
|
+
};
|
|
751
|
+
var specialPropKeyWarningShown;
|
|
752
|
+
var specialPropRefWarningShown;
|
|
753
|
+
|
|
754
|
+
function hasValidRef(config) {
|
|
755
|
+
{
|
|
756
|
+
if (hasOwnProperty.call(config, 'ref')) {
|
|
757
|
+
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
|
|
758
|
+
|
|
759
|
+
if (getter && getter.isReactWarning) {
|
|
760
|
+
return false;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
return config.ref !== undefined;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
function hasValidKey(config) {
|
|
769
|
+
{
|
|
770
|
+
if (hasOwnProperty.call(config, 'key')) {
|
|
771
|
+
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
|
|
772
|
+
|
|
773
|
+
if (getter && getter.isReactWarning) {
|
|
774
|
+
return false;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
return config.key !== undefined;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
function warnIfStringRefCannotBeAutoConverted(config, self) {
|
|
783
|
+
{
|
|
784
|
+
if (typeof config.ref === 'string' && ReactCurrentOwner.current && self) ;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
function defineKeyPropWarningGetter(props, displayName) {
|
|
789
|
+
{
|
|
790
|
+
var warnAboutAccessingKey = function () {
|
|
791
|
+
if (!specialPropKeyWarningShown) {
|
|
792
|
+
specialPropKeyWarningShown = true;
|
|
793
|
+
|
|
794
|
+
error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
|
|
798
|
+
warnAboutAccessingKey.isReactWarning = true;
|
|
799
|
+
Object.defineProperty(props, 'key', {
|
|
800
|
+
get: warnAboutAccessingKey,
|
|
801
|
+
configurable: true
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
function defineRefPropWarningGetter(props, displayName) {
|
|
807
|
+
{
|
|
808
|
+
var warnAboutAccessingRef = function () {
|
|
809
|
+
if (!specialPropRefWarningShown) {
|
|
810
|
+
specialPropRefWarningShown = true;
|
|
811
|
+
|
|
812
|
+
error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
|
|
816
|
+
warnAboutAccessingRef.isReactWarning = true;
|
|
817
|
+
Object.defineProperty(props, 'ref', {
|
|
818
|
+
get: warnAboutAccessingRef,
|
|
819
|
+
configurable: true
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
/**
|
|
824
|
+
* Factory method to create a new React element. This no longer adheres to
|
|
825
|
+
* the class pattern, so do not use new to call it. Also, instanceof check
|
|
826
|
+
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
|
|
827
|
+
* if something is a React Element.
|
|
828
|
+
*
|
|
829
|
+
* @param {*} type
|
|
830
|
+
* @param {*} props
|
|
831
|
+
* @param {*} key
|
|
832
|
+
* @param {string|object} ref
|
|
833
|
+
* @param {*} owner
|
|
834
|
+
* @param {*} self A *temporary* helper to detect places where `this` is
|
|
835
|
+
* different from the `owner` when React.createElement is called, so that we
|
|
836
|
+
* can warn. We want to get rid of owner and replace string `ref`s with arrow
|
|
837
|
+
* functions, and as long as `this` and owner are the same, there will be no
|
|
838
|
+
* change in behavior.
|
|
839
|
+
* @param {*} source An annotation object (added by a transpiler or otherwise)
|
|
840
|
+
* indicating filename, line number, and/or other information.
|
|
841
|
+
* @internal
|
|
842
|
+
*/
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
var ReactElement = function (type, key, ref, self, source, owner, props) {
|
|
846
|
+
var element = {
|
|
847
|
+
// This tag allows us to uniquely identify this as a React Element
|
|
848
|
+
$$typeof: REACT_ELEMENT_TYPE,
|
|
849
|
+
// Built-in properties that belong on the element
|
|
850
|
+
type: type,
|
|
851
|
+
key: key,
|
|
852
|
+
ref: ref,
|
|
853
|
+
props: props,
|
|
854
|
+
// Record the component responsible for creating this element.
|
|
855
|
+
_owner: owner
|
|
856
|
+
};
|
|
857
|
+
|
|
858
|
+
{
|
|
859
|
+
// The validation flag is currently mutative. We put it on
|
|
860
|
+
// an external backing store so that we can freeze the whole object.
|
|
861
|
+
// This can be replaced with a WeakMap once they are implemented in
|
|
862
|
+
// commonly used development environments.
|
|
863
|
+
element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
|
|
864
|
+
// the validation flag non-enumerable (where possible, which should
|
|
865
|
+
// include every environment we run tests in), so the test framework
|
|
866
|
+
// ignores it.
|
|
867
|
+
|
|
868
|
+
Object.defineProperty(element._store, 'validated', {
|
|
869
|
+
configurable: false,
|
|
870
|
+
enumerable: false,
|
|
871
|
+
writable: true,
|
|
872
|
+
value: false
|
|
873
|
+
}); // self and source are DEV only properties.
|
|
874
|
+
|
|
875
|
+
Object.defineProperty(element, '_self', {
|
|
876
|
+
configurable: false,
|
|
877
|
+
enumerable: false,
|
|
878
|
+
writable: false,
|
|
879
|
+
value: self
|
|
880
|
+
}); // Two elements created in two different places should be considered
|
|
881
|
+
// equal for testing purposes and therefore we hide it from enumeration.
|
|
882
|
+
|
|
883
|
+
Object.defineProperty(element, '_source', {
|
|
884
|
+
configurable: false,
|
|
885
|
+
enumerable: false,
|
|
886
|
+
writable: false,
|
|
887
|
+
value: source
|
|
888
|
+
});
|
|
889
|
+
|
|
890
|
+
if (Object.freeze) {
|
|
891
|
+
Object.freeze(element.props);
|
|
892
|
+
Object.freeze(element);
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
return element;
|
|
897
|
+
};
|
|
898
|
+
/**
|
|
899
|
+
* https://github.com/reactjs/rfcs/pull/107
|
|
900
|
+
* @param {*} type
|
|
901
|
+
* @param {object} props
|
|
902
|
+
* @param {string} key
|
|
903
|
+
*/
|
|
904
|
+
|
|
905
|
+
function jsxDEV(type, config, maybeKey, source, self) {
|
|
906
|
+
{
|
|
907
|
+
var propName; // Reserved names are extracted
|
|
908
|
+
|
|
909
|
+
var props = {};
|
|
910
|
+
var key = null;
|
|
911
|
+
var ref = null; // Currently, key can be spread in as a prop. This causes a potential
|
|
912
|
+
// issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
|
|
913
|
+
// or <div key="Hi" {...props} /> ). We want to deprecate key spread,
|
|
914
|
+
// but as an intermediary step, we will use jsxDEV for everything except
|
|
915
|
+
// <div {...props} key="Hi" />, because we aren't currently able to tell if
|
|
916
|
+
// key is explicitly declared to be undefined or not.
|
|
917
|
+
|
|
918
|
+
if (maybeKey !== undefined) {
|
|
919
|
+
{
|
|
920
|
+
checkKeyStringCoercion(maybeKey);
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
key = '' + maybeKey;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
if (hasValidKey(config)) {
|
|
927
|
+
{
|
|
928
|
+
checkKeyStringCoercion(config.key);
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
key = '' + config.key;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
if (hasValidRef(config)) {
|
|
935
|
+
ref = config.ref;
|
|
936
|
+
warnIfStringRefCannotBeAutoConverted(config, self);
|
|
937
|
+
} // Remaining properties are added to a new props object
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
for (propName in config) {
|
|
941
|
+
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
|
|
942
|
+
props[propName] = config[propName];
|
|
943
|
+
}
|
|
944
|
+
} // Resolve default props
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
if (type && type.defaultProps) {
|
|
948
|
+
var defaultProps = type.defaultProps;
|
|
949
|
+
|
|
950
|
+
for (propName in defaultProps) {
|
|
951
|
+
if (props[propName] === undefined) {
|
|
952
|
+
props[propName] = defaultProps[propName];
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
if (key || ref) {
|
|
958
|
+
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
|
|
959
|
+
|
|
960
|
+
if (key) {
|
|
961
|
+
defineKeyPropWarningGetter(props, displayName);
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
if (ref) {
|
|
965
|
+
defineRefPropWarningGetter(props, displayName);
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
|
|
974
|
+
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
|
|
975
|
+
|
|
976
|
+
function setCurrentlyValidatingElement$1(element) {
|
|
977
|
+
{
|
|
978
|
+
if (element) {
|
|
979
|
+
var owner = element._owner;
|
|
980
|
+
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
|
|
981
|
+
ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
|
|
982
|
+
} else {
|
|
983
|
+
ReactDebugCurrentFrame$1.setExtraStackFrame(null);
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
var propTypesMisspellWarningShown;
|
|
989
|
+
|
|
990
|
+
{
|
|
991
|
+
propTypesMisspellWarningShown = false;
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Verifies the object is a ReactElement.
|
|
995
|
+
* See https://reactjs.org/docs/react-api.html#isvalidelement
|
|
996
|
+
* @param {?object} object
|
|
997
|
+
* @return {boolean} True if `object` is a ReactElement.
|
|
998
|
+
* @final
|
|
999
|
+
*/
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
function isValidElement(object) {
|
|
1003
|
+
{
|
|
1004
|
+
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
function getDeclarationErrorAddendum() {
|
|
1009
|
+
{
|
|
1010
|
+
if (ReactCurrentOwner$1.current) {
|
|
1011
|
+
var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
|
|
1012
|
+
|
|
1013
|
+
if (name) {
|
|
1014
|
+
return '\n\nCheck the render method of `' + name + '`.';
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
return '';
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
function getSourceInfoErrorAddendum(source) {
|
|
1023
|
+
{
|
|
1024
|
+
|
|
1025
|
+
return '';
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* Warn if there's no key explicitly set on dynamic arrays of children or
|
|
1030
|
+
* object keys are not valid. This allows us to keep track of children between
|
|
1031
|
+
* updates.
|
|
1032
|
+
*/
|
|
1033
|
+
|
|
1034
|
+
|
|
1035
|
+
var ownerHasKeyUseWarning = {};
|
|
1036
|
+
|
|
1037
|
+
function getCurrentComponentErrorInfo(parentType) {
|
|
1038
|
+
{
|
|
1039
|
+
var info = getDeclarationErrorAddendum();
|
|
1040
|
+
|
|
1041
|
+
if (!info) {
|
|
1042
|
+
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
|
|
1043
|
+
|
|
1044
|
+
if (parentName) {
|
|
1045
|
+
info = "\n\nCheck the top-level render call using <" + parentName + ">.";
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
return info;
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Warn if the element doesn't have an explicit key assigned to it.
|
|
1054
|
+
* This element is in an array. The array could grow and shrink or be
|
|
1055
|
+
* reordered. All children that haven't already been validated are required to
|
|
1056
|
+
* have a "key" property assigned to it. Error statuses are cached so a warning
|
|
1057
|
+
* will only be shown once.
|
|
1058
|
+
*
|
|
1059
|
+
* @internal
|
|
1060
|
+
* @param {ReactElement} element Element that requires a key.
|
|
1061
|
+
* @param {*} parentType element's parent's type.
|
|
1062
|
+
*/
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
function validateExplicitKey(element, parentType) {
|
|
1066
|
+
{
|
|
1067
|
+
if (!element._store || element._store.validated || element.key != null) {
|
|
1068
|
+
return;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
element._store.validated = true;
|
|
1072
|
+
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
|
|
1073
|
+
|
|
1074
|
+
if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
|
|
1079
|
+
// property, it may be the creator of the child that's responsible for
|
|
1080
|
+
// assigning it a key.
|
|
1081
|
+
|
|
1082
|
+
var childOwner = '';
|
|
1083
|
+
|
|
1084
|
+
if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
|
|
1085
|
+
// Give the component that originally created this child.
|
|
1086
|
+
childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
setCurrentlyValidatingElement$1(element);
|
|
1090
|
+
|
|
1091
|
+
error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
|
|
1092
|
+
|
|
1093
|
+
setCurrentlyValidatingElement$1(null);
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
/**
|
|
1097
|
+
* Ensure that every element either is passed in a static location, in an
|
|
1098
|
+
* array with an explicit keys property defined, or in an object literal
|
|
1099
|
+
* with valid key property.
|
|
1100
|
+
*
|
|
1101
|
+
* @internal
|
|
1102
|
+
* @param {ReactNode} node Statically passed child of any type.
|
|
1103
|
+
* @param {*} parentType node's parent's type.
|
|
1104
|
+
*/
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
function validateChildKeys(node, parentType) {
|
|
1108
|
+
{
|
|
1109
|
+
if (typeof node !== 'object') {
|
|
1110
|
+
return;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
if (isArray(node)) {
|
|
1114
|
+
for (var i = 0; i < node.length; i++) {
|
|
1115
|
+
var child = node[i];
|
|
1116
|
+
|
|
1117
|
+
if (isValidElement(child)) {
|
|
1118
|
+
validateExplicitKey(child, parentType);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
} else if (isValidElement(node)) {
|
|
1122
|
+
// This element was passed in a valid location.
|
|
1123
|
+
if (node._store) {
|
|
1124
|
+
node._store.validated = true;
|
|
1125
|
+
}
|
|
1126
|
+
} else if (node) {
|
|
1127
|
+
var iteratorFn = getIteratorFn(node);
|
|
1128
|
+
|
|
1129
|
+
if (typeof iteratorFn === 'function') {
|
|
1130
|
+
// Entry iterators used to provide implicit keys,
|
|
1131
|
+
// but now we print a separate warning for them later.
|
|
1132
|
+
if (iteratorFn !== node.entries) {
|
|
1133
|
+
var iterator = iteratorFn.call(node);
|
|
1134
|
+
var step;
|
|
1135
|
+
|
|
1136
|
+
while (!(step = iterator.next()).done) {
|
|
1137
|
+
if (isValidElement(step.value)) {
|
|
1138
|
+
validateExplicitKey(step.value, parentType);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
/**
|
|
1147
|
+
* Given an element, validate that its props follow the propTypes definition,
|
|
1148
|
+
* provided by the type.
|
|
1149
|
+
*
|
|
1150
|
+
* @param {ReactElement} element
|
|
1151
|
+
*/
|
|
1152
|
+
|
|
1153
|
+
|
|
1154
|
+
function validatePropTypes(element) {
|
|
1155
|
+
{
|
|
1156
|
+
var type = element.type;
|
|
1157
|
+
|
|
1158
|
+
if (type === null || type === undefined || typeof type === 'string') {
|
|
1159
|
+
return;
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
var propTypes;
|
|
1163
|
+
|
|
1164
|
+
if (typeof type === 'function') {
|
|
1165
|
+
propTypes = type.propTypes;
|
|
1166
|
+
} else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
|
|
1167
|
+
// Inner props are checked in the reconciler.
|
|
1168
|
+
type.$$typeof === REACT_MEMO_TYPE)) {
|
|
1169
|
+
propTypes = type.propTypes;
|
|
1170
|
+
} else {
|
|
1171
|
+
return;
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
if (propTypes) {
|
|
1175
|
+
// Intentionally inside to avoid triggering lazy initializers:
|
|
1176
|
+
var name = getComponentNameFromType(type);
|
|
1177
|
+
checkPropTypes(propTypes, element.props, 'prop', name, element);
|
|
1178
|
+
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
|
|
1179
|
+
propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
|
|
1180
|
+
|
|
1181
|
+
var _name = getComponentNameFromType(type);
|
|
1182
|
+
|
|
1183
|
+
error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
|
|
1187
|
+
error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Given a fragment, validate that it can only be provided with fragment props
|
|
1193
|
+
* @param {ReactElement} fragment
|
|
1194
|
+
*/
|
|
1195
|
+
|
|
1196
|
+
|
|
1197
|
+
function validateFragmentProps(fragment) {
|
|
1198
|
+
{
|
|
1199
|
+
var keys = Object.keys(fragment.props);
|
|
1200
|
+
|
|
1201
|
+
for (var i = 0; i < keys.length; i++) {
|
|
1202
|
+
var key = keys[i];
|
|
1203
|
+
|
|
1204
|
+
if (key !== 'children' && key !== 'key') {
|
|
1205
|
+
setCurrentlyValidatingElement$1(fragment);
|
|
1206
|
+
|
|
1207
|
+
error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
|
|
1208
|
+
|
|
1209
|
+
setCurrentlyValidatingElement$1(null);
|
|
1210
|
+
break;
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
if (fragment.ref !== null) {
|
|
1215
|
+
setCurrentlyValidatingElement$1(fragment);
|
|
1216
|
+
|
|
1217
|
+
error('Invalid attribute `ref` supplied to `React.Fragment`.');
|
|
1218
|
+
|
|
1219
|
+
setCurrentlyValidatingElement$1(null);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
var didWarnAboutKeySpread = {};
|
|
1225
|
+
function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
|
|
1226
|
+
{
|
|
1227
|
+
var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
|
|
1228
|
+
// succeed and there will likely be errors in render.
|
|
1229
|
+
|
|
1230
|
+
if (!validType) {
|
|
1231
|
+
var info = '';
|
|
1232
|
+
|
|
1233
|
+
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
|
|
1234
|
+
info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
var sourceInfo = getSourceInfoErrorAddendum();
|
|
1238
|
+
|
|
1239
|
+
if (sourceInfo) {
|
|
1240
|
+
info += sourceInfo;
|
|
1241
|
+
} else {
|
|
1242
|
+
info += getDeclarationErrorAddendum();
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
var typeString;
|
|
1246
|
+
|
|
1247
|
+
if (type === null) {
|
|
1248
|
+
typeString = 'null';
|
|
1249
|
+
} else if (isArray(type)) {
|
|
1250
|
+
typeString = 'array';
|
|
1251
|
+
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
|
|
1252
|
+
typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
|
|
1253
|
+
info = ' Did you accidentally export a JSX literal instead of a component?';
|
|
1254
|
+
} else {
|
|
1255
|
+
typeString = typeof type;
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
|
|
1262
|
+
// TODO: Drop this when these are no longer allowed as the type argument.
|
|
1263
|
+
|
|
1264
|
+
if (element == null) {
|
|
1265
|
+
return element;
|
|
1266
|
+
} // Skip key warning if the type isn't valid since our key validation logic
|
|
1267
|
+
// doesn't expect a non-string/function type and can throw confusing errors.
|
|
1268
|
+
// We don't want exception behavior to differ between dev and prod.
|
|
1269
|
+
// (Rendering will throw with a helpful message and as soon as the type is
|
|
1270
|
+
// fixed, the key warnings will appear.)
|
|
1271
|
+
|
|
1272
|
+
|
|
1273
|
+
if (validType) {
|
|
1274
|
+
var children = props.children;
|
|
1275
|
+
|
|
1276
|
+
if (children !== undefined) {
|
|
1277
|
+
if (isStaticChildren) {
|
|
1278
|
+
if (isArray(children)) {
|
|
1279
|
+
for (var i = 0; i < children.length; i++) {
|
|
1280
|
+
validateChildKeys(children[i], type);
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
if (Object.freeze) {
|
|
1284
|
+
Object.freeze(children);
|
|
1285
|
+
}
|
|
1286
|
+
} else {
|
|
1287
|
+
error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');
|
|
1288
|
+
}
|
|
1289
|
+
} else {
|
|
1290
|
+
validateChildKeys(children, type);
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
{
|
|
1296
|
+
if (hasOwnProperty.call(props, 'key')) {
|
|
1297
|
+
var componentName = getComponentNameFromType(type);
|
|
1298
|
+
var keys = Object.keys(props).filter(function (k) {
|
|
1299
|
+
return k !== 'key';
|
|
1300
|
+
});
|
|
1301
|
+
var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';
|
|
1302
|
+
|
|
1303
|
+
if (!didWarnAboutKeySpread[componentName + beforeExample]) {
|
|
1304
|
+
var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';
|
|
1305
|
+
|
|
1306
|
+
error('A props object containing a "key" prop is being spread into JSX:\n' + ' let props = %s;\n' + ' <%s {...props} />\n' + 'React keys must be passed directly to JSX without using spread:\n' + ' let props = %s;\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);
|
|
1307
|
+
|
|
1308
|
+
didWarnAboutKeySpread[componentName + beforeExample] = true;
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
if (type === REACT_FRAGMENT_TYPE) {
|
|
1314
|
+
validateFragmentProps(element);
|
|
1315
|
+
} else {
|
|
1316
|
+
validatePropTypes(element);
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
return element;
|
|
1320
|
+
}
|
|
1321
|
+
} // These two functions exist to still get child warnings in dev
|
|
1322
|
+
// even with the prod transform. This means that jsxDEV is purely
|
|
1323
|
+
// opt-in behavior for better messages but that we won't stop
|
|
1324
|
+
// giving you warnings if you use production apis.
|
|
1325
|
+
|
|
1326
|
+
function jsxWithValidationStatic(type, props, key) {
|
|
1327
|
+
{
|
|
1328
|
+
return jsxWithValidation(type, props, key, true);
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
function jsxWithValidationDynamic(type, props, key) {
|
|
1332
|
+
{
|
|
1333
|
+
return jsxWithValidation(type, props, key, false);
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.
|
|
1338
|
+
// for now we can ship identical prod functions
|
|
1339
|
+
|
|
1340
|
+
var jsxs = jsxWithValidationStatic ;
|
|
1341
|
+
|
|
1342
|
+
reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
|
|
1343
|
+
reactJsxRuntime_development.jsx = jsx;
|
|
1344
|
+
reactJsxRuntime_development.jsxs = jsxs;
|
|
1345
|
+
})();
|
|
1346
|
+
}
|
|
1347
|
+
return reactJsxRuntime_development;
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
if (process.env.NODE_ENV === 'production') {
|
|
1351
|
+
jsxRuntime.exports = requireReactJsxRuntime_production_min();
|
|
1352
|
+
} else {
|
|
1353
|
+
jsxRuntime.exports = requireReactJsxRuntime_development();
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
var jsxRuntimeExports = jsxRuntime.exports;
|
|
1357
|
+
|
|
1358
|
+
/**
|
|
1359
|
+
* @fileoverview React context for providing permission state throughout the component tree.
|
|
1360
|
+
*
|
|
1361
|
+
* Wrap your application (or a sub-tree) with `PermissionProvider` to make
|
|
1362
|
+
* the current user's roles, permissions, and identity available to all
|
|
1363
|
+
* child components via `usePermissionContext()`.
|
|
1364
|
+
*
|
|
1365
|
+
* @module context/PermissionContext
|
|
1366
|
+
*/
|
|
1367
|
+
|
|
1368
|
+
const PermissionContext = /*#__PURE__*/createContext(/** @type {PermissionContextValue} */{
|
|
1369
|
+
roles: [],
|
|
1370
|
+
permissions: [],
|
|
1371
|
+
user: null,
|
|
1372
|
+
isAuthenticated: false,
|
|
1373
|
+
isLoading: false
|
|
1374
|
+
});
|
|
1375
|
+
PermissionContext.displayName = 'PermissionContext';
|
|
1376
|
+
|
|
1377
|
+
// ─── Provider ─────────────────────────────────────────────────────────────────
|
|
1378
|
+
|
|
1379
|
+
/**
|
|
1380
|
+
* Provides permission state to the entire React subtree below it.
|
|
1381
|
+
*
|
|
1382
|
+
* Place this **once** near the root of your application (or around any
|
|
1383
|
+
* subtree that needs access control). Every `BlockRoute`, `PermissionGate`,
|
|
1384
|
+
* and `usePermission` call inside will automatically read from it.
|
|
1385
|
+
*
|
|
1386
|
+
* The provider is **memoized** — it only re-renders children when one of
|
|
1387
|
+
* its props actually changes (roles, permissions, user, isAuthenticated, isLoading).
|
|
1388
|
+
*
|
|
1389
|
+
* @param {PermissionProviderProps} props - See {@link PermissionProviderProps} for full details.
|
|
1390
|
+
* @returns {React.ReactElement}
|
|
1391
|
+
*
|
|
1392
|
+
* @example <caption>Basic setup at app root</caption>
|
|
1393
|
+
* import { PermissionProvider } from 'role-permission-engine';
|
|
1394
|
+
* import { BrowserRouter } from 'react-router-dom';
|
|
1395
|
+
*
|
|
1396
|
+
* function App() {
|
|
1397
|
+
* const { user } = useAuth(); // your own auth hook
|
|
1398
|
+
*
|
|
1399
|
+
* return (
|
|
1400
|
+
* <PermissionProvider
|
|
1401
|
+
* roles={user?.roles ?? []} // e.g. ['admin', 'editor']
|
|
1402
|
+
* permissions={user?.permissions ?? []} // e.g. ['read:users', 'write:posts']
|
|
1403
|
+
* user={user} // raw user object (any shape)
|
|
1404
|
+
* isAuthenticated={!!user} // true when signed in
|
|
1405
|
+
* isLoading={false} // set true while fetching session
|
|
1406
|
+
* >
|
|
1407
|
+
* <BrowserRouter>
|
|
1408
|
+
* <AppRoutes />
|
|
1409
|
+
* </BrowserRouter>
|
|
1410
|
+
* </PermissionProvider>
|
|
1411
|
+
* );
|
|
1412
|
+
* }
|
|
1413
|
+
*
|
|
1414
|
+
* @example <caption>With async auth — using isLoading to avoid premature redirects</caption>
|
|
1415
|
+
* import { useState, useEffect } from 'react';
|
|
1416
|
+
*
|
|
1417
|
+
* function App() {
|
|
1418
|
+
* const [authState, setAuthState] = useState({ user: null, isLoading: true });
|
|
1419
|
+
*
|
|
1420
|
+
* useEffect(() => {
|
|
1421
|
+
* fetchCurrentUser()
|
|
1422
|
+
* .then(user => setAuthState({ user, isLoading: false }))
|
|
1423
|
+
* .catch(() => setAuthState({ user: null, isLoading: false }));
|
|
1424
|
+
* }, []);
|
|
1425
|
+
*
|
|
1426
|
+
* return (
|
|
1427
|
+
* <PermissionProvider
|
|
1428
|
+
* roles={authState.user?.roles ?? []}
|
|
1429
|
+
* permissions={authState.user?.permissions ?? []}
|
|
1430
|
+
* user={authState.user}
|
|
1431
|
+
* isAuthenticated={!!authState.user}
|
|
1432
|
+
* isLoading={authState.isLoading} // <-- prevents flash of /unauthorized
|
|
1433
|
+
* >
|
|
1434
|
+
* <BrowserRouter><AppRoutes /></BrowserRouter>
|
|
1435
|
+
* </PermissionProvider>
|
|
1436
|
+
* );
|
|
1437
|
+
* }
|
|
1438
|
+
*/
|
|
1439
|
+
function PermissionProvider({
|
|
1440
|
+
roles = [],
|
|
1441
|
+
permissions = [],
|
|
1442
|
+
user = null,
|
|
1443
|
+
isAuthenticated = false,
|
|
1444
|
+
isLoading = false,
|
|
1445
|
+
children
|
|
1446
|
+
}) {
|
|
1447
|
+
const value = useMemo(() => ({
|
|
1448
|
+
roles,
|
|
1449
|
+
permissions,
|
|
1450
|
+
user,
|
|
1451
|
+
isAuthenticated,
|
|
1452
|
+
isLoading
|
|
1453
|
+
}), [roles, permissions, user, isAuthenticated, isLoading]);
|
|
1454
|
+
return /*#__PURE__*/jsxRuntimeExports.jsx(PermissionContext.Provider, {
|
|
1455
|
+
value: value,
|
|
1456
|
+
children: children
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
// ─── Hook ─────────────────────────────────────────────────────────────────────
|
|
1461
|
+
|
|
1462
|
+
/**
|
|
1463
|
+
* Hook that returns the raw value from the nearest {@link PermissionProvider}.
|
|
1464
|
+
*
|
|
1465
|
+
* Use this when you need direct access to the user's roles, permissions,
|
|
1466
|
+
* user object, or auth flags — without running an access check.
|
|
1467
|
+
* For running actual permission checks, prefer `usePermission()`.
|
|
1468
|
+
*
|
|
1469
|
+
* @returns {PermissionContextValue}
|
|
1470
|
+
* An object with the following fields:
|
|
1471
|
+
*
|
|
1472
|
+
* | Field | Type | Description |
|
|
1473
|
+
* |-------------------|-------------|------------------------------------------------|
|
|
1474
|
+
* | `roles` | `string[]` | The user's current roles |
|
|
1475
|
+
* | `permissions` | `string[]` | The user's current permissions |
|
|
1476
|
+
* | `user` | `object\|null` | The raw user object passed to the provider |
|
|
1477
|
+
* | `isAuthenticated` | `boolean` | Whether the user is signed in |
|
|
1478
|
+
* | `isLoading` | `boolean` | Whether auth state is still resolving |
|
|
1479
|
+
*
|
|
1480
|
+
* @throws {Error}
|
|
1481
|
+
* Throws if called outside of a `<PermissionProvider>`. Check the tree
|
|
1482
|
+
* to ensure a provider wraps the component using this hook.
|
|
1483
|
+
*
|
|
1484
|
+
* @example <caption>Read user info for display purposes</caption>
|
|
1485
|
+
* import { usePermissionContext } from 'role-permission-engine';
|
|
1486
|
+
*
|
|
1487
|
+
* function UserBadge() {
|
|
1488
|
+
* const { user, roles, isAuthenticated, isLoading } = usePermissionContext();
|
|
1489
|
+
*
|
|
1490
|
+
* if (isLoading) return <span>Loading...</span>;
|
|
1491
|
+
* if (!isAuthenticated) return <span>Guest</span>;
|
|
1492
|
+
* return <span>{user?.name} — {roles.join(', ')}</span>;
|
|
1493
|
+
* }
|
|
1494
|
+
*
|
|
1495
|
+
* @example <caption>Conditional render based on auth state</caption>
|
|
1496
|
+
* function NavBar() {
|
|
1497
|
+
* const { isAuthenticated } = usePermissionContext();
|
|
1498
|
+
*
|
|
1499
|
+
* return (
|
|
1500
|
+
* <nav>
|
|
1501
|
+
* <Logo />
|
|
1502
|
+
* {isAuthenticated ? <UserMenu /> : <LoginButton />}
|
|
1503
|
+
* </nav>
|
|
1504
|
+
* );
|
|
1505
|
+
* }
|
|
1506
|
+
*/
|
|
1507
|
+
function usePermissionContext() {
|
|
1508
|
+
const ctx = useContext(PermissionContext);
|
|
1509
|
+
if (!ctx) {
|
|
1510
|
+
throw new Error('[role-permission-engine] usePermissionContext must be used inside a <PermissionProvider>.');
|
|
1511
|
+
}
|
|
1512
|
+
return ctx;
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
/**
|
|
1516
|
+
* @fileoverview Core permission-checking utility functions.
|
|
1517
|
+
*
|
|
1518
|
+
* These are pure, framework-agnostic functions that form the heart of
|
|
1519
|
+
* the role-permission-engine. They have zero side effects and can be
|
|
1520
|
+
* used independently of any React component.
|
|
1521
|
+
*
|
|
1522
|
+
* @module utils/checkPermission
|
|
1523
|
+
*/
|
|
1524
|
+
|
|
1525
|
+
// ─── Type Definitions ────────────────────────────────────────────────────────
|
|
1526
|
+
|
|
1527
|
+
/**
|
|
1528
|
+
* The logical operator used when evaluating multiple roles or permissions.
|
|
1529
|
+
*
|
|
1530
|
+
* - `"any"` – The user must satisfy **at least one** of the required items (OR logic).
|
|
1531
|
+
* - `"all"` – The user must satisfy **every** required item (AND logic).
|
|
1532
|
+
*
|
|
1533
|
+
* @typedef {"any" | "all"} LogicOperator
|
|
1534
|
+
*/
|
|
1535
|
+
|
|
1536
|
+
/**
|
|
1537
|
+
* A single role string, e.g. `"admin"`, `"editor"`, `"viewer"`.
|
|
1538
|
+
*
|
|
1539
|
+
* @typedef {string} Role
|
|
1540
|
+
*/
|
|
1541
|
+
|
|
1542
|
+
/**
|
|
1543
|
+
* A single permission string, typically in `"action:resource"` format,
|
|
1544
|
+
* e.g. `"read:users"`, `"write:posts"`, `"delete:*"`.
|
|
1545
|
+
*
|
|
1546
|
+
* @typedef {string} Permission
|
|
1547
|
+
*/
|
|
1548
|
+
|
|
1549
|
+
/**
|
|
1550
|
+
* The result returned by permission-check functions.
|
|
1551
|
+
*
|
|
1552
|
+
* @typedef {Object} PermissionResult
|
|
1553
|
+
* @property {boolean} allowed - Whether the user is allowed access.
|
|
1554
|
+
* @property {string} reason - A human-readable explanation of the result.
|
|
1555
|
+
*/
|
|
1556
|
+
|
|
1557
|
+
// ─── Role Checking ────────────────────────────────────────────────────────────
|
|
1558
|
+
|
|
1559
|
+
/**
|
|
1560
|
+
* Checks whether a user's roles satisfy the required roles using
|
|
1561
|
+
* the specified logic operator.
|
|
1562
|
+
*
|
|
1563
|
+
* This is a **pure utility** — it accepts any string as a role.
|
|
1564
|
+
* You define what roles mean in your own application. Examples:
|
|
1565
|
+
* `"admin"`, `"manager"`, `"superuser"`, `"read-only"`, `"tenant-owner"`, etc.
|
|
1566
|
+
*
|
|
1567
|
+
* @param {string[]} userRoles
|
|
1568
|
+
* Array of role strings currently assigned to the user.
|
|
1569
|
+
* - Comparison is **case-insensitive** and **trims whitespace**.
|
|
1570
|
+
* - Example: `['Admin', ' editor ']` is treated as `['admin', 'editor']`.
|
|
1571
|
+
* - Pass an empty array `[]` when the user has no roles.
|
|
1572
|
+
*
|
|
1573
|
+
* @param {string[]} requiredRoles
|
|
1574
|
+
* Array of role strings required to pass this check.
|
|
1575
|
+
* - If this array is **empty** (`[]`) or not provided, the check
|
|
1576
|
+
* is skipped and `allowed: true` is returned immediately.
|
|
1577
|
+
* - Example: `['admin', 'superuser']`
|
|
1578
|
+
*
|
|
1579
|
+
* @param {"any" | "all"} [logic="any"]
|
|
1580
|
+
* Controls how multiple `requiredRoles` are evaluated.
|
|
1581
|
+
*
|
|
1582
|
+
* | Value | Alias | Behaviour | Example |
|
|
1583
|
+
* |---------|-------|-----------------------------------------------------|----------------------------------------------|
|
|
1584
|
+
* | `"any"` | OR | User needs **at least one** of the required roles | `required: ['admin','editor']` → admin **or** editor is enough |
|
|
1585
|
+
* | `"all"` | AND | User needs **every single** required role | `required: ['admin','editor']` → must have **both** |
|
|
1586
|
+
*
|
|
1587
|
+
* **Default:** `"any"` (OR logic).
|
|
1588
|
+
*
|
|
1589
|
+
* ```js
|
|
1590
|
+
* // Default — no third argument needed for OR logic
|
|
1591
|
+
* hasRole(['editor'], ['admin', 'editor']);
|
|
1592
|
+
* // same as:
|
|
1593
|
+
* hasRole(['editor'], ['admin', 'editor'], 'any');
|
|
1594
|
+
* ```
|
|
1595
|
+
*
|
|
1596
|
+
* @returns {PermissionResult}
|
|
1597
|
+
* `{ allowed: boolean, reason: string }`
|
|
1598
|
+
*
|
|
1599
|
+
* @example <caption>OR logic (default) — user has at least one required role</caption>
|
|
1600
|
+
* hasRole(['editor'], ['admin', 'editor']);
|
|
1601
|
+
* // => { allowed: true, reason: 'User has at least one required role.' }
|
|
1602
|
+
*
|
|
1603
|
+
* @example <caption>OR logic — user has none of the required roles</caption>
|
|
1604
|
+
* hasRole(['viewer'], ['admin', 'editor'], 'any');
|
|
1605
|
+
* // => { allowed: false, reason: 'User does not have any of the required roles: admin, editor' }
|
|
1606
|
+
*
|
|
1607
|
+
* @example <caption>AND logic — user must have every required role</caption>
|
|
1608
|
+
* hasRole(['admin', 'editor'], ['admin', 'editor'], 'all');
|
|
1609
|
+
* // => { allowed: true, reason: 'User has all required roles.' }
|
|
1610
|
+
*
|
|
1611
|
+
* @example <caption>AND logic — user is missing one role</caption>
|
|
1612
|
+
* hasRole(['editor'], ['admin', 'editor'], 'all');
|
|
1613
|
+
* // => { allowed: false, reason: 'User is missing required roles: admin' }
|
|
1614
|
+
*
|
|
1615
|
+
* @example <caption>Empty required roles — always allowed</caption>
|
|
1616
|
+
* hasRole([], []);
|
|
1617
|
+
* // => { allowed: true, reason: 'No roles required — access granted.' }
|
|
1618
|
+
*/
|
|
1619
|
+
function hasRole(userRoles, requiredRoles, logic = "any") {
|
|
1620
|
+
if (!Array.isArray(requiredRoles) || requiredRoles.length === 0) {
|
|
1621
|
+
return {
|
|
1622
|
+
allowed: true,
|
|
1623
|
+
reason: "No roles required — access granted."
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
if (!Array.isArray(userRoles) || userRoles.length === 0) {
|
|
1627
|
+
return {
|
|
1628
|
+
allowed: false,
|
|
1629
|
+
reason: "User has no roles assigned."
|
|
1630
|
+
};
|
|
1631
|
+
}
|
|
1632
|
+
const normalizedUser = userRoles.map(r => r.toLowerCase().trim());
|
|
1633
|
+
const normalizedRequired = requiredRoles.map(r => r.toLowerCase().trim());
|
|
1634
|
+
if (logic === "all") {
|
|
1635
|
+
const missing = normalizedRequired.filter(r => !normalizedUser.includes(r));
|
|
1636
|
+
if (missing.length > 0) {
|
|
1637
|
+
return {
|
|
1638
|
+
allowed: false,
|
|
1639
|
+
reason: `User is missing required roles: ${missing.join(", ")}`
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
return {
|
|
1643
|
+
allowed: true,
|
|
1644
|
+
reason: "User has all required roles."
|
|
1645
|
+
};
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
// Default: "any" (OR logic)
|
|
1649
|
+
const matched = normalizedRequired.filter(r => normalizedUser.includes(r));
|
|
1650
|
+
if (matched.length === 0) {
|
|
1651
|
+
return {
|
|
1652
|
+
allowed: false,
|
|
1653
|
+
reason: `User does not have any of the required roles: ${normalizedRequired.join(", ")}`
|
|
1654
|
+
};
|
|
1655
|
+
}
|
|
1656
|
+
return {
|
|
1657
|
+
allowed: true,
|
|
1658
|
+
reason: "User has at least one required role."
|
|
1659
|
+
};
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
// ─── Permission Checking ──────────────────────────────────────────────────────
|
|
1663
|
+
|
|
1664
|
+
/**
|
|
1665
|
+
* Checks whether a user's permissions satisfy the required permissions
|
|
1666
|
+
* using the specified logic operator. Supports wildcard `"*"` permissions.
|
|
1667
|
+
*
|
|
1668
|
+
* This is a **pure utility** — it accepts any string as a permission.
|
|
1669
|
+
* You define what permissions mean in your own application. A common
|
|
1670
|
+
* convention is `"action:resource"` format (e.g. `"read:invoices"`,
|
|
1671
|
+
* `"export:reports"`, `"delete:accounts"`), but any string works.
|
|
1672
|
+
*
|
|
1673
|
+
* **Wildcard rules:**
|
|
1674
|
+
* | User permission | Matches |
|
|
1675
|
+
* |-----------------|----------------------------------------------|
|
|
1676
|
+
* | `"*"` | Every possible permission — full super-access |
|
|
1677
|
+
* | `"read:*"` | Any permission starting with `"read:"` |
|
|
1678
|
+
* | `"write:posts"` | Only `"write:posts"` exactly |
|
|
1679
|
+
*
|
|
1680
|
+
* @param {string[]} userPermissions
|
|
1681
|
+
* Array of permission strings the user currently holds.
|
|
1682
|
+
* - Comparison is **case-insensitive** and **trims whitespace**.
|
|
1683
|
+
* - Pass `['*']` to grant superuser access to all checks.
|
|
1684
|
+
* - Pass an empty array `[]` when the user has no permissions.
|
|
1685
|
+
*
|
|
1686
|
+
* @param {string[]} requiredPermissions
|
|
1687
|
+
* Array of permission strings required to pass this check.
|
|
1688
|
+
* - If this array is **empty** (`[]`) or not provided, the check
|
|
1689
|
+
* is skipped and `allowed: true` is returned immediately.
|
|
1690
|
+
*
|
|
1691
|
+
* @param {"any" | "all"} [logic="any"]
|
|
1692
|
+
* Controls how multiple `requiredPermissions` are evaluated.
|
|
1693
|
+
*
|
|
1694
|
+
* | Value | Alias | Behaviour | Example |
|
|
1695
|
+
* |---------|-------|-----------------------------------------------------------|------------------------------------------------------|
|
|
1696
|
+
* | `"any"` | OR | User needs **at least one** of the required permissions | `required: ['read:x','write:x']` → read **or** write is enough |
|
|
1697
|
+
* | `"all"` | AND | User needs **every single** required permission | `required: ['read:x','write:x']` → must have **both** |
|
|
1698
|
+
*
|
|
1699
|
+
* **Default:** `"any"` (OR logic).
|
|
1700
|
+
*
|
|
1701
|
+
* ```js
|
|
1702
|
+
* // Default — OR logic, no third argument needed
|
|
1703
|
+
* hasPermission(['read:reports'], ['read:reports', 'write:reports']);
|
|
1704
|
+
* // same as:
|
|
1705
|
+
* hasPermission(['read:reports'], ['read:reports', 'write:reports'], 'any');
|
|
1706
|
+
* ```
|
|
1707
|
+
*
|
|
1708
|
+
* @returns {PermissionResult}
|
|
1709
|
+
* `{ allowed: boolean, reason: string }`
|
|
1710
|
+
*
|
|
1711
|
+
* @example <caption>OR logic (default) — user has one of the required permissions</caption>
|
|
1712
|
+
* hasPermission(['read:invoices'], ['read:invoices', 'write:invoices']);
|
|
1713
|
+
* // => { allowed: true, reason: 'User has at least one required permission.' }
|
|
1714
|
+
*
|
|
1715
|
+
* @example <caption>OR logic — user has none</caption>
|
|
1716
|
+
* hasPermission(['read:posts'], ['write:posts', 'delete:posts'], 'any');
|
|
1717
|
+
* // => { allowed: false, reason: 'User does not have any of the required permissions: ...' }
|
|
1718
|
+
*
|
|
1719
|
+
* @example <caption>AND logic — must have all required permissions</caption>
|
|
1720
|
+
* hasPermission(['read:users', 'write:users'], ['read:users', 'write:users'], 'all');
|
|
1721
|
+
* // => { allowed: true, reason: 'User has all required permissions.' }
|
|
1722
|
+
*
|
|
1723
|
+
* @example <caption>Full wildcard — grants everything</caption>
|
|
1724
|
+
* hasPermission(['*'], ['read:users', 'delete:posts'], 'all');
|
|
1725
|
+
* // => { allowed: true, reason: 'User has wildcard permission (*) — full access granted.' }
|
|
1726
|
+
*
|
|
1727
|
+
* @example <caption>Namespace wildcard — "read:*" satisfies any "read:" permission</caption>
|
|
1728
|
+
* hasPermission(['read:*'], ['read:invoices', 'read:reports'], 'all');
|
|
1729
|
+
* // => { allowed: true, reason: 'User has all required permissions.' }
|
|
1730
|
+
*/
|
|
1731
|
+
function hasPermission(userPermissions, requiredPermissions, logic = "any") {
|
|
1732
|
+
if (!Array.isArray(requiredPermissions) || requiredPermissions.length === 0) {
|
|
1733
|
+
return {
|
|
1734
|
+
allowed: true,
|
|
1735
|
+
reason: 'No permissions required — access granted.'
|
|
1736
|
+
};
|
|
1737
|
+
}
|
|
1738
|
+
if (!Array.isArray(userPermissions) || userPermissions.length === 0) {
|
|
1739
|
+
return {
|
|
1740
|
+
allowed: false,
|
|
1741
|
+
reason: 'User has no permissions assigned.'
|
|
1742
|
+
};
|
|
1743
|
+
}
|
|
1744
|
+
const normalizedUser = userPermissions.map(p => p.toLowerCase().trim());
|
|
1745
|
+
const normalizedRequired = requiredPermissions.map(p => p.toLowerCase().trim());
|
|
1746
|
+
|
|
1747
|
+
// Full wildcard check
|
|
1748
|
+
if (normalizedUser.includes("*")) {
|
|
1749
|
+
return {
|
|
1750
|
+
allowed: true,
|
|
1751
|
+
reason: "User has wildcard permission (*) — full access granted."
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
/**
|
|
1756
|
+
* Checks if a single required permission is satisfied by the user's permission set,
|
|
1757
|
+
* including namespace wildcard matching (e.g. "read:*" matches "read:users").
|
|
1758
|
+
*
|
|
1759
|
+
* @param {string} required - The required permission to satisfy.
|
|
1760
|
+
* @returns {boolean} Whether the user satisfies this specific permission.
|
|
1761
|
+
*/
|
|
1762
|
+
function isSatisfied(required) {
|
|
1763
|
+
if (normalizedUser.includes(required)) return true;
|
|
1764
|
+
|
|
1765
|
+
// Namespace wildcard: "read:*" should satisfy "read:users"
|
|
1766
|
+
const [requiredNamespace] = required.split(":");
|
|
1767
|
+
return normalizedUser.includes(`${requiredNamespace}:*`);
|
|
1768
|
+
}
|
|
1769
|
+
if (logic === "all") {
|
|
1770
|
+
const missing = normalizedRequired.filter(p => !isSatisfied(p));
|
|
1771
|
+
if (missing.length > 0) {
|
|
1772
|
+
return {
|
|
1773
|
+
allowed: false,
|
|
1774
|
+
reason: `User is missing required permissions: ${missing.join(", ")}`
|
|
1775
|
+
};
|
|
1776
|
+
}
|
|
1777
|
+
return {
|
|
1778
|
+
allowed: true,
|
|
1779
|
+
reason: "User has all required permissions."
|
|
1780
|
+
};
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
// Default: "any" (OR logic)
|
|
1784
|
+
const matched = normalizedRequired.filter(p => isSatisfied(p));
|
|
1785
|
+
if (matched.length === 0) {
|
|
1786
|
+
return {
|
|
1787
|
+
allowed: false,
|
|
1788
|
+
reason: `User does not have any of the required permissions: ${normalizedRequired.join(", ")}`
|
|
1789
|
+
};
|
|
1790
|
+
}
|
|
1791
|
+
return {
|
|
1792
|
+
allowed: true,
|
|
1793
|
+
reason: "User has at least one required permission."
|
|
1794
|
+
};
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
// ─── Combined Check ───────────────────────────────────────────────────────────
|
|
1798
|
+
|
|
1799
|
+
/**
|
|
1800
|
+
* Performs a **combined** role AND permission check in a single call.
|
|
1801
|
+
*
|
|
1802
|
+
* Both the role check and the permission check must independently pass
|
|
1803
|
+
* for `allowed` to be `true`. If a constraint array is empty or not
|
|
1804
|
+
* provided, that constraint is automatically satisfied (open access).
|
|
1805
|
+
*
|
|
1806
|
+
* @param {Object} options
|
|
1807
|
+
*
|
|
1808
|
+
* @param {string[]} [options.userRoles=[]]
|
|
1809
|
+
* The roles currently held by the user. Any strings are accepted;
|
|
1810
|
+
* you define what roles mean in your app.
|
|
1811
|
+
*
|
|
1812
|
+
* @param {string[]} [options.userPermissions=[]]
|
|
1813
|
+
* The permissions currently held by the user. Supports wildcards:
|
|
1814
|
+
* `"*"` (all access) and `"namespace:*"` (all in namespace).
|
|
1815
|
+
*
|
|
1816
|
+
* @param {string[]} [options.requiredRoles=[]]
|
|
1817
|
+
* Roles the user must have to pass the role check.
|
|
1818
|
+
* Pass `[]` (default) to skip the role check entirely.
|
|
1819
|
+
*
|
|
1820
|
+
* @param {string[]} [options.requiredPermissions=[]]
|
|
1821
|
+
* Permissions the user must have to pass the permission check.
|
|
1822
|
+
* Pass `[]` (default) to skip the permission check entirely.
|
|
1823
|
+
*
|
|
1824
|
+
* @param {"any" | "all"} [options.roleLogic="any"]
|
|
1825
|
+
* Controls how `requiredRoles` are evaluated.
|
|
1826
|
+
*
|
|
1827
|
+
* | Value | Behaviour | Default? |
|
|
1828
|
+
* |---------|--------------------------------------------------|----------|
|
|
1829
|
+
* | `"any"` | User needs **at least one** required role (OR) | ✅ Yes |
|
|
1830
|
+
* | `"all"` | User needs **every** required role (AND) | No |
|
|
1831
|
+
*
|
|
1832
|
+
* ```js
|
|
1833
|
+
* // 'any' is the default — no need to specify it explicitly for OR logic
|
|
1834
|
+
* checkAccess({ requiredRoles: ['admin', 'editor'], roleLogic: 'any' });
|
|
1835
|
+
* ```
|
|
1836
|
+
*
|
|
1837
|
+
* @param {"any" | "all"} [options.permissionLogic="any"]
|
|
1838
|
+
* Controls how `requiredPermissions` are evaluated.
|
|
1839
|
+
*
|
|
1840
|
+
* | Value | Behaviour | Default? |
|
|
1841
|
+
* |---------|-------------------------------------------------------|----------|
|
|
1842
|
+
* | `"any"` | User needs **at least one** required permission (OR) | ✅ Yes |
|
|
1843
|
+
* | `"all"` | User needs **every** required permission (AND) | No |
|
|
1844
|
+
*
|
|
1845
|
+
* ```js
|
|
1846
|
+
* // Require the user to have ALL listed permissions (AND logic)
|
|
1847
|
+
* checkAccess({
|
|
1848
|
+
* requiredPermissions: ['read:report', 'export:report'],
|
|
1849
|
+
* permissionLogic: 'all',
|
|
1850
|
+
* });
|
|
1851
|
+
* ```
|
|
1852
|
+
*
|
|
1853
|
+
* @returns {PermissionResult}
|
|
1854
|
+
* `{ allowed: boolean, reason: string }` — `allowed` is `true` only
|
|
1855
|
+
* when **both** role and permission checks pass.
|
|
1856
|
+
*
|
|
1857
|
+
* @example <caption>Combined check — OR role logic + OR permission logic (both defaults)</caption>
|
|
1858
|
+
* checkAccess({
|
|
1859
|
+
* userRoles: ['editor'],
|
|
1860
|
+
* userPermissions: ['write:posts'],
|
|
1861
|
+
* requiredRoles: ['editor', 'admin'], // editor OR admin
|
|
1862
|
+
* requiredPermissions: ['write:posts'], // write:posts required
|
|
1863
|
+
* });
|
|
1864
|
+
* // => { allowed: true, reason: 'Access granted.' }
|
|
1865
|
+
*
|
|
1866
|
+
* @example <caption>AND logic for permissions — user must have ALL listed permissions</caption>
|
|
1867
|
+
* checkAccess({
|
|
1868
|
+
* userRoles: ['manager'],
|
|
1869
|
+
* userPermissions: ['approve:leaves'],
|
|
1870
|
+
* requiredRoles: ['manager'],
|
|
1871
|
+
* requiredPermissions: ['approve:leaves', 'view:team'],
|
|
1872
|
+
* permissionLogic: 'all', // must have BOTH permissions
|
|
1873
|
+
* });
|
|
1874
|
+
* // => { allowed: false, reason: 'User is missing required permissions: view:team' }
|
|
1875
|
+
*
|
|
1876
|
+
* @example <caption>No constraints — always allowed</caption>
|
|
1877
|
+
* checkAccess({ userRoles: ['guest'], userPermissions: [] });
|
|
1878
|
+
* // => { allowed: true, reason: 'Access granted.' }
|
|
1879
|
+
*/
|
|
1880
|
+
function checkAccess({
|
|
1881
|
+
userRoles = [],
|
|
1882
|
+
userPermissions = [],
|
|
1883
|
+
requiredRoles = [],
|
|
1884
|
+
requiredPermissions = [],
|
|
1885
|
+
roleLogic = "any",
|
|
1886
|
+
permissionLogic = "any"
|
|
1887
|
+
}) {
|
|
1888
|
+
const roleResult = hasRole(userRoles, requiredRoles, roleLogic);
|
|
1889
|
+
if (!roleResult.allowed) return roleResult;
|
|
1890
|
+
const permResult = hasPermission(userPermissions, requiredPermissions, permissionLogic);
|
|
1891
|
+
if (!permResult.allowed) return permResult;
|
|
1892
|
+
return {
|
|
1893
|
+
allowed: true,
|
|
1894
|
+
reason: "Access granted."
|
|
1895
|
+
};
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
/**
|
|
1899
|
+
* @fileoverview `usePermission` hook — programmatic permission checking.
|
|
1900
|
+
*
|
|
1901
|
+
* This hook reads the current user's roles and permissions from the nearest
|
|
1902
|
+
* {@link PermissionProvider} and returns whether the user is allowed to
|
|
1903
|
+
* access a given set of roles/permissions.
|
|
1904
|
+
*
|
|
1905
|
+
* @module hooks/usePermission
|
|
1906
|
+
*/
|
|
1907
|
+
|
|
1908
|
+
|
|
1909
|
+
// ─── Type Definitions ─────────────────────────────────────────────────────────
|
|
1910
|
+
|
|
1911
|
+
/**
|
|
1912
|
+
* Options accepted by the `usePermission` hook.
|
|
1913
|
+
*
|
|
1914
|
+
* All fields are optional. Omitting a field (or passing `[]`) skips that
|
|
1915
|
+
* particular check and treats it as automatically satisfied.
|
|
1916
|
+
*
|
|
1917
|
+
* @typedef {Object} UsePermissionOptions
|
|
1918
|
+
*
|
|
1919
|
+
* @property {string[]} [roles=[]]
|
|
1920
|
+
* Role strings the user must have to be considered "allowed".
|
|
1921
|
+
* - Any strings are accepted — you define what roles mean in your app.
|
|
1922
|
+
* - Pass `[]` (default) to skip the role check entirely.
|
|
1923
|
+
* - Examples: `['admin']`, `['editor', 'manager']`
|
|
1924
|
+
*
|
|
1925
|
+
* @property {string[]} [permissions=[]]
|
|
1926
|
+
* Permission strings the user must have to be considered "allowed".
|
|
1927
|
+
* - Supports wildcards: `'*'` (all access), `'read:*'` (all read: perms).
|
|
1928
|
+
* - Pass `[]` (default) to skip the permission check entirely.
|
|
1929
|
+
* - Examples: `['write:posts']`, `['read:reports', 'export:reports']`
|
|
1930
|
+
*
|
|
1931
|
+
* @property {"any" | "all"} [roleLogic="any"]
|
|
1932
|
+
* Controls how multiple `roles` are evaluated.
|
|
1933
|
+
*
|
|
1934
|
+
* | Value | Alias | Behaviour | Default? |
|
|
1935
|
+
* |---------|-------|------------------------------------------------|----------|
|
|
1936
|
+
* | `"any"` | OR | User needs **at least one** required role | ✅ Yes |
|
|
1937
|
+
* | `"all"` | AND | User needs **every** required role | No |
|
|
1938
|
+
*
|
|
1939
|
+
* ```js
|
|
1940
|
+
* // OR logic (default) — no need to specify 'any' explicitly
|
|
1941
|
+
* usePermission({ roles: ['admin', 'editor'] });
|
|
1942
|
+
* // AND logic — user must be BOTH admin AND editor
|
|
1943
|
+
* usePermission({ roles: ['admin', 'editor'], roleLogic: 'all' });
|
|
1944
|
+
* ```
|
|
1945
|
+
*
|
|
1946
|
+
* @property {"any" | "all"} [permissionLogic="any"]
|
|
1947
|
+
* Controls how multiple `permissions` are evaluated.
|
|
1948
|
+
*
|
|
1949
|
+
* | Value | Alias | Behaviour | Default? |
|
|
1950
|
+
* |---------|-------|-----------------------------------------------------|----------|
|
|
1951
|
+
* | `"any"` | OR | User needs **at least one** required permission | ✅ Yes |
|
|
1952
|
+
* | `"all"` | AND | User needs **every** required permission | No |
|
|
1953
|
+
*
|
|
1954
|
+
* ```js
|
|
1955
|
+
* // AND logic — user must hold ALL listed permissions
|
|
1956
|
+
* usePermission({
|
|
1957
|
+
* permissions: ['read:reports', 'export:reports'],
|
|
1958
|
+
* permissionLogic: 'all',
|
|
1959
|
+
* });
|
|
1960
|
+
* ```
|
|
1961
|
+
*/
|
|
1962
|
+
|
|
1963
|
+
/**
|
|
1964
|
+
* The value returned by the `usePermission` hook.
|
|
1965
|
+
*
|
|
1966
|
+
* @typedef {Object} UsePermissionResult
|
|
1967
|
+
*
|
|
1968
|
+
* | Field | Type | Description |
|
|
1969
|
+
* |-------------------|-----------|----------------------------------------------------------|
|
|
1970
|
+
* | `allowed` | `boolean` | `true` when the user passes all role + permission checks |
|
|
1971
|
+
* | `denied` | `boolean` | Convenience inverse of `allowed` (`!allowed`) |
|
|
1972
|
+
* | `isLoading` | `boolean` | `true` while the auth state is still resolving |
|
|
1973
|
+
* | `isAuthenticated` | `boolean` | `true` when the user is signed in |
|
|
1974
|
+
* | `reason` | `string` | Human-readable explanation of the result |
|
|
1975
|
+
*
|
|
1976
|
+
* @property {boolean} allowed
|
|
1977
|
+
* `true` when the user passes all role + permission checks.
|
|
1978
|
+
* `false` while `isLoading` is `true` (to prevent premature rendering).
|
|
1979
|
+
*
|
|
1980
|
+
* @property {boolean} denied
|
|
1981
|
+
* Convenience inverse of `allowed`. Equivalent to `!allowed`.
|
|
1982
|
+
* Useful for inline conditional expressions: `if (denied) return <Forbidden />`.
|
|
1983
|
+
*
|
|
1984
|
+
* @property {boolean} isLoading
|
|
1985
|
+
* Mirrors `isLoading` from the nearest `PermissionProvider`.
|
|
1986
|
+
* While `true`, `allowed` is always `false` to prevent a flash of content.
|
|
1987
|
+
*
|
|
1988
|
+
* @property {boolean} isAuthenticated
|
|
1989
|
+
* Mirrors `isAuthenticated` from the nearest `PermissionProvider`.
|
|
1990
|
+
*
|
|
1991
|
+
* @property {string} reason
|
|
1992
|
+
* Human-readable explanation of why `allowed` is `true` or `false`.
|
|
1993
|
+
* Useful for debugging or showing contextual error messages.
|
|
1994
|
+
* Examples: `'User has at least one required role.'`, `'User is missing required permissions: write:posts'`
|
|
1995
|
+
*/
|
|
1996
|
+
|
|
1997
|
+
// ─── Hook ─────────────────────────────────────────────────────────────────────
|
|
1998
|
+
|
|
1999
|
+
/**
|
|
2000
|
+
* Hook for **programmatic** permission checking inside React components.
|
|
2001
|
+
*
|
|
2002
|
+
* Reads the current user's roles and permissions from the nearest
|
|
2003
|
+
* {@link PermissionProvider}, evaluates them against the provided
|
|
2004
|
+
* requirements, and returns a stable result object that only re-computes
|
|
2005
|
+
* when its inputs change (memoized with `useMemo`).
|
|
2006
|
+
*
|
|
2007
|
+
* Use this hook when you need access-check results in component logic
|
|
2008
|
+
* (conditional rendering, redirects, disabling buttons). For declarative
|
|
2009
|
+
* UI gates, prefer `<PermissionGate>`. For route blocking, prefer `<BlockRoute>`.
|
|
2010
|
+
*
|
|
2011
|
+
* @param {UsePermissionOptions} [options={}]
|
|
2012
|
+
* The permission requirements to evaluate. See {@link UsePermissionOptions}.
|
|
2013
|
+
* - Pass `{}` or nothing to get the raw auth state without any checks.
|
|
2014
|
+
* - All fields default to `[]` / `"any"` (open access).
|
|
2015
|
+
*
|
|
2016
|
+
* @returns {UsePermissionResult} See {@link UsePermissionResult} for the full
|
|
2017
|
+
* shape. Key fields:
|
|
2018
|
+
* - `allowed` / `denied` — result of the access check.
|
|
2019
|
+
* - `isLoading` — `true` while auth resolves (always `allowed: false`).
|
|
2020
|
+
* - `reason` — human-readable explanation string.
|
|
2021
|
+
*
|
|
2022
|
+
* @example <caption>Basic role check</caption>
|
|
2023
|
+
* import { usePermission } from 'role-permission-engine';
|
|
2024
|
+
*
|
|
2025
|
+
* function DeleteButton() {
|
|
2026
|
+
* const { allowed } = usePermission({ roles: ['admin'] });
|
|
2027
|
+
*
|
|
2028
|
+
* // denied is the inverse — both are available for readability
|
|
2029
|
+
* if (!allowed) return null;
|
|
2030
|
+
* return <button>Delete</button>;
|
|
2031
|
+
* }
|
|
2032
|
+
*
|
|
2033
|
+
* @example <caption>Combined role + permission with AND logic</caption>
|
|
2034
|
+
* function AdminPanel() {
|
|
2035
|
+
* const { allowed, isLoading, denied } = usePermission({
|
|
2036
|
+
* roles: ['admin', 'superadmin'],
|
|
2037
|
+
* permissions: ['read:users', 'write:users'],
|
|
2038
|
+
* roleLogic: 'any', // admin OR superadmin is enough
|
|
2039
|
+
* permissionLogic: 'all', // must have BOTH read:users AND write:users
|
|
2040
|
+
* });
|
|
2041
|
+
*
|
|
2042
|
+
* if (isLoading) return <Spinner />;
|
|
2043
|
+
* if (denied) return <p>Access denied.</p>;
|
|
2044
|
+
* return <AdminDashboard />;
|
|
2045
|
+
* }
|
|
2046
|
+
*
|
|
2047
|
+
* @example <caption>Show reason string for debugging</caption>
|
|
2048
|
+
* function SecretPage() {
|
|
2049
|
+
* const { allowed, isLoading, reason } = usePermission({
|
|
2050
|
+
* permissions: ['view:secrets'],
|
|
2051
|
+
* });
|
|
2052
|
+
*
|
|
2053
|
+
* if (isLoading) return <div>Loading...</div>;
|
|
2054
|
+
* if (!allowed) return <div title={reason}>Not allowed.</div>;
|
|
2055
|
+
* return <SecretContent />;
|
|
2056
|
+
* }
|
|
2057
|
+
*
|
|
2058
|
+
* @example <caption>No constraints — read raw auth state</caption>
|
|
2059
|
+
* function NavBar() {
|
|
2060
|
+
* // Pass nothing to just read isAuthenticated / isLoading
|
|
2061
|
+
* const { isAuthenticated, isLoading } = usePermission();
|
|
2062
|
+
*
|
|
2063
|
+
* if (isLoading) return <NavSkeleton />;
|
|
2064
|
+
* return isAuthenticated ? <UserMenu /> : <LoginButton />;
|
|
2065
|
+
* }
|
|
2066
|
+
*/
|
|
2067
|
+
function usePermission({
|
|
2068
|
+
roles: requiredRoles = [],
|
|
2069
|
+
permissions: requiredPermissions = [],
|
|
2070
|
+
roleLogic = 'any',
|
|
2071
|
+
permissionLogic = 'any'
|
|
2072
|
+
} = {}) {
|
|
2073
|
+
const {
|
|
2074
|
+
roles: userRoles,
|
|
2075
|
+
permissions: userPermissions,
|
|
2076
|
+
isAuthenticated,
|
|
2077
|
+
isLoading
|
|
2078
|
+
} = usePermissionContext();
|
|
2079
|
+
const result = useMemo(() => {
|
|
2080
|
+
// While loading, treat as "not allowed" to avoid premature rendering
|
|
2081
|
+
if (isLoading) {
|
|
2082
|
+
return {
|
|
2083
|
+
allowed: false,
|
|
2084
|
+
reason: 'Auth state is loading.'
|
|
2085
|
+
};
|
|
2086
|
+
}
|
|
2087
|
+
|
|
2088
|
+
// If no requirements, always allow authenticated users
|
|
2089
|
+
const hasRequirements = requiredRoles.length > 0 || requiredPermissions.length > 0;
|
|
2090
|
+
if (!hasRequirements) {
|
|
2091
|
+
return {
|
|
2092
|
+
allowed: true,
|
|
2093
|
+
reason: 'No constraints specified.'
|
|
2094
|
+
};
|
|
2095
|
+
}
|
|
2096
|
+
return checkAccess({
|
|
2097
|
+
userRoles,
|
|
2098
|
+
userPermissions,
|
|
2099
|
+
requiredRoles,
|
|
2100
|
+
requiredPermissions,
|
|
2101
|
+
roleLogic,
|
|
2102
|
+
permissionLogic
|
|
2103
|
+
});
|
|
2104
|
+
}, [userRoles, userPermissions, requiredRoles, requiredPermissions, roleLogic, permissionLogic, isLoading]);
|
|
2105
|
+
return {
|
|
2106
|
+
allowed: result.allowed,
|
|
2107
|
+
denied: !result.allowed,
|
|
2108
|
+
isLoading,
|
|
2109
|
+
isAuthenticated,
|
|
2110
|
+
reason: result.reason
|
|
2111
|
+
};
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
/**
|
|
2115
|
+
* @fileoverview `BlockRoute` component — role and permission-based route guard.
|
|
2116
|
+
*
|
|
2117
|
+
* `BlockRoute` wraps your application's route content and redirects
|
|
2118
|
+
* unauthorized users to a configurable URL. It is compatible with both
|
|
2119
|
+
* **React Router v5** (using `<Redirect>`) and **React Router v6**
|
|
2120
|
+
* (using `<Navigate>`), auto-detecting which version is installed.
|
|
2121
|
+
*
|
|
2122
|
+
* @module components/BlockRoute
|
|
2123
|
+
*/
|
|
2124
|
+
|
|
2125
|
+
function RouterRedirect({
|
|
2126
|
+
to,
|
|
2127
|
+
replace = true,
|
|
2128
|
+
state
|
|
2129
|
+
}) {
|
|
2130
|
+
try {
|
|
2131
|
+
// Try React Router v6 first
|
|
2132
|
+
// eslint-disable-next-line import/no-extraneous-dependencies
|
|
2133
|
+
const {
|
|
2134
|
+
Navigate
|
|
2135
|
+
} = require('react-router-dom');
|
|
2136
|
+
if (Navigate) {
|
|
2137
|
+
return /*#__PURE__*/jsxRuntimeExports.jsx(Navigate, {
|
|
2138
|
+
to: to,
|
|
2139
|
+
replace: replace,
|
|
2140
|
+
state: state
|
|
2141
|
+
});
|
|
2142
|
+
}
|
|
2143
|
+
} catch (_) {
|
|
2144
|
+
// fall through
|
|
2145
|
+
}
|
|
2146
|
+
try {
|
|
2147
|
+
// Fallback to React Router v5
|
|
2148
|
+
// eslint-disable-next-line import/no-extraneous-dependencies
|
|
2149
|
+
const {
|
|
2150
|
+
Redirect
|
|
2151
|
+
} = require('react-router-dom');
|
|
2152
|
+
if (Redirect) {
|
|
2153
|
+
return /*#__PURE__*/jsxRuntimeExports.jsx(Redirect, {
|
|
2154
|
+
to: {
|
|
2155
|
+
pathname: to,
|
|
2156
|
+
state: state
|
|
2157
|
+
},
|
|
2158
|
+
push: !replace
|
|
2159
|
+
});
|
|
2160
|
+
}
|
|
2161
|
+
} catch (_) {
|
|
2162
|
+
// No react-router-dom installed
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
// Ultimate fallback — cannot redirect, warn the developer
|
|
2166
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
2167
|
+
console.warn('[role-permission-engine] BlockRoute: react-router-dom is not installed or could not be detected. ' + 'Unable to redirect unauthorized user.');
|
|
2168
|
+
}
|
|
2169
|
+
return null;
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
// ─── Component ────────────────────────────────────────────────────────────────
|
|
2173
|
+
|
|
2174
|
+
/**
|
|
2175
|
+
* Route guard component that **blocks** unauthorized users from accessing
|
|
2176
|
+
* a route and **redirects** them to a configurable path.
|
|
2177
|
+
*
|
|
2178
|
+
* `BlockRoute` reads the current user's roles and permissions from the
|
|
2179
|
+
* nearest {@link PermissionProvider} in the tree. It calls {@link usePermission}
|
|
2180
|
+
* internally to run the access check, then:
|
|
2181
|
+
*
|
|
2182
|
+
* - ✅ **Allowed** → renders `children` (the protected page).
|
|
2183
|
+
* - ❌ **Denied** → redirects to `redirectTo` (default: `"/unauthorized"`).
|
|
2184
|
+
* - ⏳ **Loading** → renders `loadingComponent` (default: `null`).
|
|
2185
|
+
*
|
|
2186
|
+
* **React Router compatibility:**
|
|
2187
|
+
* - **v6** (recommended) — uses `<Navigate>` internally.
|
|
2188
|
+
* - **v5** — uses `<Redirect>` internally.
|
|
2189
|
+
* - Auto-detected at runtime; no configuration needed.
|
|
2190
|
+
*
|
|
2191
|
+
* @param {BlockRouteProps} props - See {@link BlockRouteProps} for full prop reference.
|
|
2192
|
+
* @returns {React.ReactElement|null}
|
|
2193
|
+
*
|
|
2194
|
+
* ---
|
|
2195
|
+
*
|
|
2196
|
+
* @example <caption>React Router v6 — basic role guard</caption>
|
|
2197
|
+
* import { Routes, Route } from 'react-router-dom';
|
|
2198
|
+
* import { BlockRoute } from 'role-permission-engine';
|
|
2199
|
+
*
|
|
2200
|
+
* // Only users whose roles include 'admin' can access /admin.
|
|
2201
|
+
* // All others are sent to /unauthorized.
|
|
2202
|
+
* <Routes>
|
|
2203
|
+
* <Route
|
|
2204
|
+
* path="/admin"
|
|
2205
|
+
* element={
|
|
2206
|
+
* <BlockRoute roles={['admin']}>
|
|
2207
|
+
* <AdminPage />
|
|
2208
|
+
* </BlockRoute>
|
|
2209
|
+
* }
|
|
2210
|
+
* />
|
|
2211
|
+
* </Routes>
|
|
2212
|
+
*
|
|
2213
|
+
* @example <caption>React Router v5 — using render prop</caption>
|
|
2214
|
+
* import { Switch, Route } from 'react-router-dom'; // v5
|
|
2215
|
+
*
|
|
2216
|
+
* <Switch>
|
|
2217
|
+
* <Route
|
|
2218
|
+
* path="/admin"
|
|
2219
|
+
* render={() => (
|
|
2220
|
+
* <BlockRoute roles={['admin']} redirectTo="/login">
|
|
2221
|
+
* <AdminPage />
|
|
2222
|
+
* </BlockRoute>
|
|
2223
|
+
* )}
|
|
2224
|
+
* />
|
|
2225
|
+
* </Switch>
|
|
2226
|
+
*
|
|
2227
|
+
* @example <caption>AND permission logic — user must have ALL permissions</caption>
|
|
2228
|
+
* <BlockRoute
|
|
2229
|
+
* permissions={['read:reports', 'export:reports']}
|
|
2230
|
+
* permissionLogic="all"
|
|
2231
|
+
* redirectTo="/access-denied"
|
|
2232
|
+
* >
|
|
2233
|
+
* <ReportsPage />
|
|
2234
|
+
* </BlockRoute>
|
|
2235
|
+
*
|
|
2236
|
+
* @example <caption>Combined roles + permissions with a loading spinner</caption>
|
|
2237
|
+
* <BlockRoute
|
|
2238
|
+
* roles={['editor', 'admin']}
|
|
2239
|
+
* roleLogic="any"
|
|
2240
|
+
* permissions={['write:posts']}
|
|
2241
|
+
* redirectTo="/unauthorized"
|
|
2242
|
+
* loadingComponent={<FullScreenSpinner />}
|
|
2243
|
+
* >
|
|
2244
|
+
* <EditPostPage />
|
|
2245
|
+
* </BlockRoute>
|
|
2246
|
+
*
|
|
2247
|
+
* @example <caption>Preserve "from" location for post-login redirect (v6)</caption>
|
|
2248
|
+
* import { useLocation } from 'react-router-dom';
|
|
2249
|
+
*
|
|
2250
|
+
* // After the user logs in, read location.state.from and redirect back.
|
|
2251
|
+
* function AuthRequired({ children }) {
|
|
2252
|
+
* const location = useLocation();
|
|
2253
|
+
* return (
|
|
2254
|
+
* <BlockRoute
|
|
2255
|
+
* roles={['user']}
|
|
2256
|
+
* redirectTo="/login"
|
|
2257
|
+
* state={{ from: location }}
|
|
2258
|
+
* >
|
|
2259
|
+
* {children}
|
|
2260
|
+
* </BlockRoute>
|
|
2261
|
+
* );
|
|
2262
|
+
* }
|
|
2263
|
+
*/
|
|
2264
|
+
function BlockRoute({
|
|
2265
|
+
children,
|
|
2266
|
+
roles = [],
|
|
2267
|
+
permissions = [],
|
|
2268
|
+
roleLogic = 'any',
|
|
2269
|
+
permissionLogic = 'any',
|
|
2270
|
+
redirectTo = '/unauthorized',
|
|
2271
|
+
loadingComponent = null,
|
|
2272
|
+
replace = true,
|
|
2273
|
+
state
|
|
2274
|
+
}) {
|
|
2275
|
+
const {
|
|
2276
|
+
allowed,
|
|
2277
|
+
isLoading
|
|
2278
|
+
} = usePermission({
|
|
2279
|
+
roles,
|
|
2280
|
+
permissions,
|
|
2281
|
+
roleLogic,
|
|
2282
|
+
permissionLogic
|
|
2283
|
+
});
|
|
2284
|
+
|
|
2285
|
+
// While auth is resolving, render the loading component (or null)
|
|
2286
|
+
if (isLoading) {
|
|
2287
|
+
return loadingComponent || null;
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2290
|
+
// Access denied — redirect
|
|
2291
|
+
if (!allowed) {
|
|
2292
|
+
return /*#__PURE__*/jsxRuntimeExports.jsx(RouterRedirect, {
|
|
2293
|
+
to: redirectTo,
|
|
2294
|
+
replace: replace,
|
|
2295
|
+
state: state
|
|
2296
|
+
});
|
|
2297
|
+
}
|
|
2298
|
+
|
|
2299
|
+
// Access granted — render children
|
|
2300
|
+
return children;
|
|
2301
|
+
}
|
|
2302
|
+
|
|
2303
|
+
/**
|
|
2304
|
+
* @fileoverview `PermissionGate` component — inline conditional rendering.
|
|
2305
|
+
*
|
|
2306
|
+
* Unlike `BlockRoute` (which redirects), `PermissionGate` simply shows or
|
|
2307
|
+
* hides its `children` based on the user's roles/permissions. Use it for
|
|
2308
|
+
* buttons, menu items, sections, or any UI element that should only be
|
|
2309
|
+
* visible to certain users.
|
|
2310
|
+
*
|
|
2311
|
+
* @module components/PermissionGate
|
|
2312
|
+
*/
|
|
2313
|
+
|
|
2314
|
+
|
|
2315
|
+
// ─── Type Definitions ─────────────────────────────────────────────────────────
|
|
2316
|
+
|
|
2317
|
+
/**
|
|
2318
|
+
* Props accepted by the `PermissionGate` component.
|
|
2319
|
+
*
|
|
2320
|
+
* @typedef {Object} PermissionGateProps
|
|
2321
|
+
*
|
|
2322
|
+
* @property {React.ReactNode} children
|
|
2323
|
+
* **Required.** Content shown when access is **granted** (or when `negate=true`
|
|
2324
|
+
* and access is **denied**). Can be any renderable React node.
|
|
2325
|
+
*
|
|
2326
|
+
* @property {string[]} [roles=[]]
|
|
2327
|
+
* Role strings the user must have for the gate to open.
|
|
2328
|
+
* - Any strings are accepted — you define what roles mean in your app.
|
|
2329
|
+
* - Pass `[]` (default) to skip the role check entirely.
|
|
2330
|
+
* - Examples: `['admin']`, `['editor', 'manager']`
|
|
2331
|
+
*
|
|
2332
|
+
* @property {string[]} [permissions=[]]
|
|
2333
|
+
* Permission strings the user must have for the gate to open.
|
|
2334
|
+
* - Supports wildcards: `'*'` (all access), `'read:*'` (all read: perms).
|
|
2335
|
+
* - Pass `[]` (default) to skip the permission check entirely.
|
|
2336
|
+
* - Examples: `['write:posts']`, `['read:reports', 'export:reports']`
|
|
2337
|
+
*
|
|
2338
|
+
* @property {"any" | "all"} [roleLogic="any"]
|
|
2339
|
+
* Controls how multiple `roles` are evaluated.
|
|
2340
|
+
*
|
|
2341
|
+
* | Value | Alias | Behaviour | Default? |
|
|
2342
|
+
* |---------|-------|------------------------------------------------|----------|
|
|
2343
|
+
* | `"any"` | OR | User needs **at least one** required role | ✅ Yes |
|
|
2344
|
+
* | `"all"` | AND | User needs **every** required role | No |
|
|
2345
|
+
*
|
|
2346
|
+
* ```jsx
|
|
2347
|
+
* // OR logic (default) — admin OR editor can see the content
|
|
2348
|
+
* <PermissionGate roles={['admin', 'editor']}>
|
|
2349
|
+
*
|
|
2350
|
+
* // AND logic — user must be BOTH admin AND editor
|
|
2351
|
+
* <PermissionGate roles={['admin', 'editor']} roleLogic="all">
|
|
2352
|
+
* ```
|
|
2353
|
+
*
|
|
2354
|
+
* @property {"any" | "all"} [permissionLogic="any"]
|
|
2355
|
+
* Controls how multiple `permissions` are evaluated.
|
|
2356
|
+
*
|
|
2357
|
+
* | Value | Alias | Behaviour | Default? |
|
|
2358
|
+
* |---------|-------|-----------------------------------------------------|----------|
|
|
2359
|
+
* | `"any"` | OR | User needs **at least one** required permission | ✅ Yes |
|
|
2360
|
+
* | `"all"` | AND | User needs **every** required permission | No |
|
|
2361
|
+
*
|
|
2362
|
+
* ```jsx
|
|
2363
|
+
* // AND logic — must have ALL listed permissions to see the content
|
|
2364
|
+
* <PermissionGate
|
|
2365
|
+
* permissions={['read:reports', 'export:reports']}
|
|
2366
|
+
* permissionLogic="all"
|
|
2367
|
+
* >
|
|
2368
|
+
* ```
|
|
2369
|
+
*
|
|
2370
|
+
* @property {React.ReactNode} [fallback=null]
|
|
2371
|
+
* What to render when access is **denied** (and `negate=false`).
|
|
2372
|
+
* - Default: `null` — renders nothing when the user lacks access.
|
|
2373
|
+
* - Use this to show a disabled state, a tooltip, or an upgrade prompt.
|
|
2374
|
+
* - Example: `fallback={<span className="disabled">No access</span>}`
|
|
2375
|
+
*
|
|
2376
|
+
* @property {React.ReactNode} [loadingComponent=null]
|
|
2377
|
+
* What to render while the auth state is being resolved (`isLoading=true`).
|
|
2378
|
+
* - Default: `null` — renders nothing during loading.
|
|
2379
|
+
* - Use a skeleton or spinner to avoid a flash of missing content.
|
|
2380
|
+
* - Example: `loadingComponent={<Skeleton />}`
|
|
2381
|
+
*
|
|
2382
|
+
* @property {boolean} [negate=false]
|
|
2383
|
+
* **Inverts** the access check result.
|
|
2384
|
+
*
|
|
2385
|
+
* | Value | Renders `children` when… | Default? |
|
|
2386
|
+
* |---------|--------------------------------------------------|----------|
|
|
2387
|
+
* | `false` | User **has** the required roles / permissions | ✅ Yes |
|
|
2388
|
+
* | `true` | User **does NOT have** the roles / permissions | No |
|
|
2389
|
+
*
|
|
2390
|
+
* Common use-cases for `negate`:
|
|
2391
|
+
* - Show a **Login button** only to unauthenticated users.
|
|
2392
|
+
* - Show a **"Free plan" banner** only to users without a `premium` role.
|
|
2393
|
+
*
|
|
2394
|
+
* ```jsx
|
|
2395
|
+
* // Show upgrade prompt ONLY to users who do NOT have the 'premium' role
|
|
2396
|
+
* <PermissionGate roles={['premium']} negate>
|
|
2397
|
+
* <UpgradeBanner />
|
|
2398
|
+
* </PermissionGate>
|
|
2399
|
+
* ```
|
|
2400
|
+
*/
|
|
2401
|
+
|
|
2402
|
+
// ─── Component ────────────────────────────────────────────────────────────────
|
|
2403
|
+
|
|
2404
|
+
/**
|
|
2405
|
+
* Conditionally **shows or hides** content based on the current user's
|
|
2406
|
+
* roles and permissions — without ever redirecting.
|
|
2407
|
+
*
|
|
2408
|
+
* `PermissionGate` reads auth state from the nearest {@link PermissionProvider}
|
|
2409
|
+
* and uses {@link usePermission} internally. Depending on the result:
|
|
2410
|
+
*
|
|
2411
|
+
* - ✅ **Allowed** → renders `children`.
|
|
2412
|
+
* - ❌ **Denied** → renders `fallback` (default: `null`, i.e. nothing).
|
|
2413
|
+
* - ⏳ **Loading** → renders `loadingComponent` (default: `null`).
|
|
2414
|
+
* - 🔄 **Negated** (`negate=true`) → swaps allowed ↔ denied before rendering.
|
|
2415
|
+
*
|
|
2416
|
+
* Unlike {@link BlockRoute}, this component **never redirects** the user.
|
|
2417
|
+
* Use it for inline UI elements: buttons, menu items, banners, panels, etc.
|
|
2418
|
+
*
|
|
2419
|
+
* @param {PermissionGateProps} props - See {@link PermissionGateProps} for full prop reference.
|
|
2420
|
+
* @returns {React.ReactElement|null}
|
|
2421
|
+
*
|
|
2422
|
+
* ---
|
|
2423
|
+
*
|
|
2424
|
+
* @example <caption>Basic role gate — hide element from non-admins</caption>
|
|
2425
|
+
* // The delete button is invisible to anyone who is not an admin.
|
|
2426
|
+
* // No fallback = renders nothing when denied.
|
|
2427
|
+
* <PermissionGate roles={['admin']}>
|
|
2428
|
+
* <button onClick={handleDelete}>Delete User</button>
|
|
2429
|
+
* </PermissionGate>
|
|
2430
|
+
*
|
|
2431
|
+
* @example <caption>With fallback — show read-only state to non-editors</caption>
|
|
2432
|
+
* <PermissionGate
|
|
2433
|
+
* permissions={['write:posts']}
|
|
2434
|
+
* fallback={<span className="badge">Read-only</span>}
|
|
2435
|
+
* >
|
|
2436
|
+
* <EditToolbar />
|
|
2437
|
+
* </PermissionGate>
|
|
2438
|
+
*
|
|
2439
|
+
* @example <caption>negate — show content ONLY to users who lack the role</caption>
|
|
2440
|
+
* // LoginButton is shown to guests (users who do NOT have 'user' or 'admin' role).
|
|
2441
|
+
* <PermissionGate roles={['user', 'admin']} negate>
|
|
2442
|
+
* <LoginButton />
|
|
2443
|
+
* </PermissionGate>
|
|
2444
|
+
*
|
|
2445
|
+
* @example <caption>AND permission logic — user must have ALL listed permissions</caption>
|
|
2446
|
+
* <PermissionGate
|
|
2447
|
+
* roles={['manager']}
|
|
2448
|
+
* permissions={['approve:leaves', 'view:team']}
|
|
2449
|
+
* permissionLogic="all"
|
|
2450
|
+
* fallback={<p>Insufficient privileges.</p>}
|
|
2451
|
+
* >
|
|
2452
|
+
* <TeamManagementPanel />
|
|
2453
|
+
* </PermissionGate>
|
|
2454
|
+
*
|
|
2455
|
+
* @example <caption>Loading state — show skeleton while auth resolves</caption>
|
|
2456
|
+
* <PermissionGate
|
|
2457
|
+
* permissions={['read:dashboard']}
|
|
2458
|
+
* loadingComponent={<DashboardSkeleton />}
|
|
2459
|
+
* >
|
|
2460
|
+
* <Dashboard />
|
|
2461
|
+
* </PermissionGate>
|
|
2462
|
+
*/
|
|
2463
|
+
function PermissionGate({
|
|
2464
|
+
children,
|
|
2465
|
+
roles = [],
|
|
2466
|
+
permissions = [],
|
|
2467
|
+
roleLogic = 'any',
|
|
2468
|
+
permissionLogic = 'any',
|
|
2469
|
+
fallback = null,
|
|
2470
|
+
loadingComponent = null,
|
|
2471
|
+
negate = false
|
|
2472
|
+
}) {
|
|
2473
|
+
const {
|
|
2474
|
+
allowed,
|
|
2475
|
+
isLoading
|
|
2476
|
+
} = usePermission({
|
|
2477
|
+
roles,
|
|
2478
|
+
permissions,
|
|
2479
|
+
roleLogic,
|
|
2480
|
+
permissionLogic
|
|
2481
|
+
});
|
|
2482
|
+
if (isLoading) {
|
|
2483
|
+
return loadingComponent || null;
|
|
2484
|
+
}
|
|
2485
|
+
|
|
2486
|
+
// Apply negation if requested
|
|
2487
|
+
const shouldRender = negate ? !allowed : allowed;
|
|
2488
|
+
return shouldRender ? children : fallback;
|
|
2489
|
+
}
|
|
2490
|
+
|
|
2491
|
+
/**
|
|
2492
|
+
* @fileoverview `withPermission` Higher Order Component (HOC).
|
|
2493
|
+
*
|
|
2494
|
+
* Wraps any React component with a permission gate, redirecting or hiding
|
|
2495
|
+
* the component based on the current user's roles and permissions.
|
|
2496
|
+
*
|
|
2497
|
+
* Use `withPermission` when you prefer the HOC pattern over JSX composition,
|
|
2498
|
+
* or when wrapping class-based components that cannot use hooks directly.
|
|
2499
|
+
*
|
|
2500
|
+
* @module components/withPermission
|
|
2501
|
+
*/
|
|
2502
|
+
|
|
2503
|
+
function withPermission(WrappedComponent, options = {}) {
|
|
2504
|
+
const {
|
|
2505
|
+
roles = [],
|
|
2506
|
+
permissions = [],
|
|
2507
|
+
roleLogic = 'any',
|
|
2508
|
+
permissionLogic = 'any',
|
|
2509
|
+
fallback = null,
|
|
2510
|
+
loadingComponent = null,
|
|
2511
|
+
negate = false
|
|
2512
|
+
} = options;
|
|
2513
|
+
|
|
2514
|
+
/**
|
|
2515
|
+
* The inner component produced by `withPermission`.
|
|
2516
|
+
*
|
|
2517
|
+
* @param {object} props - All props are forwarded to `WrappedComponent`.
|
|
2518
|
+
* @returns {React.ReactElement|null}
|
|
2519
|
+
*/
|
|
2520
|
+
function WithPermissionWrapper(props) {
|
|
2521
|
+
const {
|
|
2522
|
+
allowed,
|
|
2523
|
+
isLoading
|
|
2524
|
+
} = usePermission({
|
|
2525
|
+
roles,
|
|
2526
|
+
permissions,
|
|
2527
|
+
roleLogic,
|
|
2528
|
+
permissionLogic
|
|
2529
|
+
});
|
|
2530
|
+
if (isLoading) {
|
|
2531
|
+
return loadingComponent || null;
|
|
2532
|
+
}
|
|
2533
|
+
const shouldRender = negate ? !allowed : allowed;
|
|
2534
|
+
if (!shouldRender) {
|
|
2535
|
+
return fallback || null;
|
|
2536
|
+
}
|
|
2537
|
+
return /*#__PURE__*/jsxRuntimeExports.jsx(WrappedComponent, {
|
|
2538
|
+
...props
|
|
2539
|
+
});
|
|
2540
|
+
}
|
|
2541
|
+
|
|
2542
|
+
// Preserve a meaningful display name for React DevTools
|
|
2543
|
+
WithPermissionWrapper.displayName = `withPermission(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;
|
|
2544
|
+
return WithPermissionWrapper;
|
|
2545
|
+
}
|
|
2546
|
+
|
|
2547
|
+
export { BlockRoute, PermissionGate, PermissionProvider, checkAccess, hasPermission, hasRole, usePermission, usePermissionContext, withPermission };
|
|
2548
|
+
//# sourceMappingURL=index.esm.js.map
|