UNPKG

permix

Version:

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

54 lines (53 loc) 1.61 kB
import { getContext, setContext } from 'svelte'; import { createCheck } from '../core/index.mjs'; const PERMIX_CONTEXT_KEY = Symbol('svelte-permix'); /** * Provides Permix context to the Svelte component tree. * * Must be called during component initialization (inside `<PermixProvider>`). * * @link https://permix.letstri.dev/docs/integrations/svelte */ export function providePermix(permix) { const context = $state({ permix, isReady: permix.isReady(), rules: permix.getRules(), }); setContext(PERMIX_CONTEXT_KEY, context); $effect(() => { const setup = permix.hook('setup', () => { context.rules = permix.getRules(); }); const ready = permix.hook('ready', () => { context.isReady = permix.isReady(); }); return () => { setup(); ready(); }; }); } // eslint-disable-next-line react/no-unnecessary-use-prefix export function usePermixContext() { const context = getContext(PERMIX_CONTEXT_KEY); if (!context) { throw new Error('[Permix]: Looks like you forgot to wrap your app with <PermixProvider>'); } return context; } /** * Access Permix check and readiness state inside a Svelte component. * * @link https://permix.letstri.dev/docs/integrations/svelte */ export function usePermix(permix) { const context = usePermixContext(); const check = (...args) => createCheck(() => (context.rules ?? permix.getRules()))(...args); return { check, get isReady() { return context.isReady; }, }; }