UNPKG

permix

Version:

Permix is a lightweight, framework-agnostic, type-safe permissions management library for JavaScript applications on the client and server sides.

55 lines (52 loc) 1.64 kB
import { os, ORPCError } from '@orpc/server'; import { c as createTemplate, a as createPermix$1 } from '../shared/permix.Q-O041RP.mjs'; import { c as createCheckContext, p as pick } from '../shared/permix.q13nxITM.mjs'; /** * Create a middleware function that checks permissions for ORPC routes. * * @link https://permix.letstri.dev/docs/integrations/orpc */ function createPermix({ forbiddenError = () => new ORPCError('FORBIDDEN', { message: 'You do not have permission to perform this action' }) } = {}) { const plugin = os.$context(); function setup(rules) { return pick(createPermix$1(rules), ['check', 'dehydrate']); } function checkMiddleware(...params) { return plugin.middleware(async ({ context, next }) => { if (!context.permix) { throw new Error('[Permix] Instance not found. Please use the `setupMiddleware` function.'); } const hasPermission = context.permix.check(...params); if (!hasPermission) { const error = typeof forbiddenError === 'function' ? forbiddenError({ ...createCheckContext(...params), context }) : forbiddenError; if (!(error instanceof ORPCError)) { console.error('[Permix]: forbiddenError is not ORPCError'); throw new ORPCError('FORBIDDEN', { message: 'You do not have permission to perform this action' }); } throw error; } return next(); }); } function template(...params) { return createTemplate(...params); } return { setup, checkMiddleware, template }; } export { createPermix };