UNPKG

permix

Version:

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

51 lines (50 loc) 1.5 kB
import { getContext, onDestroy, 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); const setup = permix.hook('setup', () => { context.rules = permix.getRules(); }); const ready = permix.hook('ready', () => { context.isReady = permix.isReady(); }); onDestroy(() => { setup(); ready(); }); } 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; }, }; }