@pol-studios/db 1.0.36 → 1.0.38
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/dist/UserMetadataContext-yLZQu24J.d.ts +33 -0
- package/dist/auth/context.d.ts +5 -53
- package/dist/auth/context.js +1 -25
- package/dist/auth/hooks.d.ts +3 -107
- package/dist/auth/hooks.js +2 -8
- package/dist/auth/index.d.ts +5 -5
- package/dist/auth/index.js +9 -39
- package/dist/{chunk-YQUNORJD.js → chunk-6OSNGHRE.js} +77 -153
- package/dist/chunk-6OSNGHRE.js.map +1 -0
- package/dist/{chunk-7NFMEDJW.js → chunk-ILGWCJ6S.js} +9 -42
- package/dist/chunk-ILGWCJ6S.js.map +1 -0
- package/dist/{chunk-U4BZKCBH.js → chunk-INIX2V6L.js} +3 -3
- package/dist/chunk-NSIAAYW3.js +1 -0
- package/dist/{chunk-QHXN6BNL.js → chunk-QMHHKYZO.js} +2 -2
- package/dist/{chunk-HFIGNQ7T.js → chunk-TO5QB4UM.js} +4 -4
- package/dist/chunk-TO5QB4UM.js.map +1 -0
- package/dist/index.js +6 -7
- package/dist/index.native.js +6 -7
- package/dist/index.web.js +5 -6
- package/dist/index.web.js.map +1 -1
- package/dist/with-auth/index.js +4 -5
- package/dist/with-auth/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/UserMetadataContext-QLIv-mfF.d.ts +0 -171
- package/dist/chunk-5HJLTYRA.js +0 -355
- package/dist/chunk-5HJLTYRA.js.map +0 -1
- package/dist/chunk-6KN7KLEG.js +0 -1
- package/dist/chunk-7NFMEDJW.js.map +0 -1
- package/dist/chunk-HFIGNQ7T.js.map +0 -1
- package/dist/chunk-YQUNORJD.js.map +0 -1
- /package/dist/{chunk-U4BZKCBH.js.map → chunk-INIX2V6L.js.map} +0 -0
- /package/dist/{chunk-6KN7KLEG.js.map → chunk-NSIAAYW3.js.map} +0 -0
- /package/dist/{chunk-QHXN6BNL.js.map → chunk-QMHHKYZO.js.map} +0 -0
package/dist/chunk-5HJLTYRA.js
DELETED
|
@@ -1,355 +0,0 @@
|
|
|
1
|
-
// src/auth/context/SimpleAuthProvider.tsx
|
|
2
|
-
import { c as _c } from "react/compiler-runtime";
|
|
3
|
-
import { createContext, useContext } from "react";
|
|
4
|
-
import { jsx } from "react/jsx-runtime";
|
|
5
|
-
var SimpleAuthContext = createContext(null);
|
|
6
|
-
function matchesAccessPattern(pattern, requestedKey) {
|
|
7
|
-
if (pattern === requestedKey) return true;
|
|
8
|
-
if (pattern === "*:*:*") return true;
|
|
9
|
-
const patternParts = pattern.split(":");
|
|
10
|
-
const keyParts = requestedKey.split(":");
|
|
11
|
-
if (patternParts.length !== keyParts.length) {
|
|
12
|
-
return false;
|
|
13
|
-
}
|
|
14
|
-
for (let i = 0; i < patternParts.length; i++) {
|
|
15
|
-
const patternPart = patternParts[i];
|
|
16
|
-
const keyPart = keyParts[i];
|
|
17
|
-
if (patternPart === "*") continue;
|
|
18
|
-
if (patternPart !== keyPart) return false;
|
|
19
|
-
}
|
|
20
|
-
return true;
|
|
21
|
-
}
|
|
22
|
-
function checkAccess(accessKeys, requestedKey) {
|
|
23
|
-
if (!requestedKey) return true;
|
|
24
|
-
if (!accessKeys || accessKeys.length === 0) return false;
|
|
25
|
-
return accessKeys.some((pattern) => matchesAccessPattern(pattern, requestedKey));
|
|
26
|
-
}
|
|
27
|
-
function getPermissionLevel(action) {
|
|
28
|
-
switch (action.toLowerCase()) {
|
|
29
|
-
case "view":
|
|
30
|
-
case "read":
|
|
31
|
-
return 1;
|
|
32
|
-
case "edit":
|
|
33
|
-
case "write":
|
|
34
|
-
return 2;
|
|
35
|
-
case "admin":
|
|
36
|
-
case "delete":
|
|
37
|
-
case "share":
|
|
38
|
-
return 3;
|
|
39
|
-
default:
|
|
40
|
-
return 0;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
function hasResourceAccess(accessKeys, resourceType, resourceId, requiredAction) {
|
|
44
|
-
if (!accessKeys || accessKeys.length === 0) return false;
|
|
45
|
-
if (accessKeys.includes("*:*:*")) return true;
|
|
46
|
-
const requiredLevel = getPermissionLevel(requiredAction);
|
|
47
|
-
for (const key of accessKeys) {
|
|
48
|
-
const parts = key.split(":");
|
|
49
|
-
if (parts.length !== 3) continue;
|
|
50
|
-
const [keyType, keyId, keyAction] = parts;
|
|
51
|
-
if (keyType !== "*" && keyType.toLowerCase() !== resourceType.toLowerCase()) {
|
|
52
|
-
continue;
|
|
53
|
-
}
|
|
54
|
-
if (keyId !== "*" && keyId !== resourceId) {
|
|
55
|
-
continue;
|
|
56
|
-
}
|
|
57
|
-
const grantedLevel = getPermissionLevel(keyAction);
|
|
58
|
-
if (grantedLevel >= requiredLevel) {
|
|
59
|
-
return true;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
return false;
|
|
63
|
-
}
|
|
64
|
-
function SimpleAuthProvider(t0) {
|
|
65
|
-
const $ = _c(20);
|
|
66
|
-
const {
|
|
67
|
-
children,
|
|
68
|
-
user,
|
|
69
|
-
profile,
|
|
70
|
-
userAccess,
|
|
71
|
-
isLoading: t1,
|
|
72
|
-
onSignOut
|
|
73
|
-
} = t0;
|
|
74
|
-
const isLoading = t1 === void 0 ? false : t1;
|
|
75
|
-
let t2;
|
|
76
|
-
bb0: {
|
|
77
|
-
if (!userAccess) {
|
|
78
|
-
let t33;
|
|
79
|
-
if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
|
|
80
|
-
t33 = [];
|
|
81
|
-
$[0] = t33;
|
|
82
|
-
} else {
|
|
83
|
-
t33 = $[0];
|
|
84
|
-
}
|
|
85
|
-
t2 = t33;
|
|
86
|
-
break bb0;
|
|
87
|
-
}
|
|
88
|
-
let t32;
|
|
89
|
-
if ($[1] !== userAccess) {
|
|
90
|
-
t32 = userAccess.map(_temp).filter(Boolean);
|
|
91
|
-
$[1] = userAccess;
|
|
92
|
-
$[2] = t32;
|
|
93
|
-
} else {
|
|
94
|
-
t32 = $[2];
|
|
95
|
-
}
|
|
96
|
-
t2 = t32;
|
|
97
|
-
}
|
|
98
|
-
const accessKeys = t2;
|
|
99
|
-
const profileStatus = profile?.status;
|
|
100
|
-
const isArchived = profileStatus === "archived";
|
|
101
|
-
const isSuspended = profileStatus === "suspended";
|
|
102
|
-
let t3;
|
|
103
|
-
if ($[3] !== accessKeys || $[4] !== isArchived || $[5] !== isSuspended) {
|
|
104
|
-
t3 = (requestedKey) => {
|
|
105
|
-
if (isArchived || isSuspended) {
|
|
106
|
-
return false;
|
|
107
|
-
}
|
|
108
|
-
return checkAccess(accessKeys, requestedKey);
|
|
109
|
-
};
|
|
110
|
-
$[3] = accessKeys;
|
|
111
|
-
$[4] = isArchived;
|
|
112
|
-
$[5] = isSuspended;
|
|
113
|
-
$[6] = t3;
|
|
114
|
-
} else {
|
|
115
|
-
t3 = $[6];
|
|
116
|
-
}
|
|
117
|
-
const hasAccess = t3;
|
|
118
|
-
let t4;
|
|
119
|
-
if ($[7] !== accessKeys || $[8] !== hasAccess || $[9] !== isArchived || $[10] !== isLoading || $[11] !== isSuspended || $[12] !== onSignOut || $[13] !== profile || $[14] !== profileStatus || $[15] !== user) {
|
|
120
|
-
t4 = {
|
|
121
|
-
user,
|
|
122
|
-
profile,
|
|
123
|
-
accessKeys,
|
|
124
|
-
isLoading,
|
|
125
|
-
isArchived,
|
|
126
|
-
isSuspended,
|
|
127
|
-
profileStatus,
|
|
128
|
-
hasAccess,
|
|
129
|
-
signOut: onSignOut
|
|
130
|
-
};
|
|
131
|
-
$[7] = accessKeys;
|
|
132
|
-
$[8] = hasAccess;
|
|
133
|
-
$[9] = isArchived;
|
|
134
|
-
$[10] = isLoading;
|
|
135
|
-
$[11] = isSuspended;
|
|
136
|
-
$[12] = onSignOut;
|
|
137
|
-
$[13] = profile;
|
|
138
|
-
$[14] = profileStatus;
|
|
139
|
-
$[15] = user;
|
|
140
|
-
$[16] = t4;
|
|
141
|
-
} else {
|
|
142
|
-
t4 = $[16];
|
|
143
|
-
}
|
|
144
|
-
const value = t4;
|
|
145
|
-
let t5;
|
|
146
|
-
if ($[17] !== children || $[18] !== value) {
|
|
147
|
-
t5 = /* @__PURE__ */ jsx(SimpleAuthContext.Provider, { value, children });
|
|
148
|
-
$[17] = children;
|
|
149
|
-
$[18] = value;
|
|
150
|
-
$[19] = t5;
|
|
151
|
-
} else {
|
|
152
|
-
t5 = $[19];
|
|
153
|
-
}
|
|
154
|
-
return t5;
|
|
155
|
-
}
|
|
156
|
-
function _temp(ua) {
|
|
157
|
-
return ua.accessKey;
|
|
158
|
-
}
|
|
159
|
-
function useSimpleAuth() {
|
|
160
|
-
const context = useContext(SimpleAuthContext);
|
|
161
|
-
if (!context) {
|
|
162
|
-
throw new Error("useSimpleAuth must be used within a SimpleAuthProvider");
|
|
163
|
-
}
|
|
164
|
-
return context;
|
|
165
|
-
}
|
|
166
|
-
function useRequireAuth() {
|
|
167
|
-
const auth = useSimpleAuth();
|
|
168
|
-
if (!auth.user) {
|
|
169
|
-
throw new Error("User must be authenticated. Use useSimpleAuth() for nullable user.");
|
|
170
|
-
}
|
|
171
|
-
return auth;
|
|
172
|
-
}
|
|
173
|
-
function useResourceAccess(resourceType, resourceId, requiredAction) {
|
|
174
|
-
const $ = _c(5);
|
|
175
|
-
const {
|
|
176
|
-
accessKeys,
|
|
177
|
-
isArchived,
|
|
178
|
-
isSuspended
|
|
179
|
-
} = useSimpleAuth();
|
|
180
|
-
let t0;
|
|
181
|
-
bb0: {
|
|
182
|
-
if (resourceId === void 0 || resourceId === null) {
|
|
183
|
-
t0 = false;
|
|
184
|
-
break bb0;
|
|
185
|
-
}
|
|
186
|
-
if (isArchived || isSuspended) {
|
|
187
|
-
t0 = false;
|
|
188
|
-
break bb0;
|
|
189
|
-
}
|
|
190
|
-
const t1 = String(resourceId);
|
|
191
|
-
let t2;
|
|
192
|
-
if ($[0] !== accessKeys || $[1] !== requiredAction || $[2] !== resourceType || $[3] !== t1) {
|
|
193
|
-
t2 = hasResourceAccess(accessKeys, resourceType, t1, requiredAction);
|
|
194
|
-
$[0] = accessKeys;
|
|
195
|
-
$[1] = requiredAction;
|
|
196
|
-
$[2] = resourceType;
|
|
197
|
-
$[3] = t1;
|
|
198
|
-
$[4] = t2;
|
|
199
|
-
} else {
|
|
200
|
-
t2 = $[4];
|
|
201
|
-
}
|
|
202
|
-
t0 = t2;
|
|
203
|
-
}
|
|
204
|
-
return t0;
|
|
205
|
-
}
|
|
206
|
-
function useCanView(resourceType, resourceId) {
|
|
207
|
-
return useResourceAccess(resourceType, resourceId, "view");
|
|
208
|
-
}
|
|
209
|
-
function useCanEdit(resourceType, resourceId) {
|
|
210
|
-
return useResourceAccess(resourceType, resourceId, "edit");
|
|
211
|
-
}
|
|
212
|
-
function useCanDelete(resourceType, resourceId) {
|
|
213
|
-
return useResourceAccess(resourceType, resourceId, "admin");
|
|
214
|
-
}
|
|
215
|
-
function useCanShare(resourceType, resourceId) {
|
|
216
|
-
return useResourceAccess(resourceType, resourceId, "admin");
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// src/auth/context/OfflineAuthProvider.tsx
|
|
220
|
-
import { useCallback as useCallback2, useEffect, useState } from "react";
|
|
221
|
-
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
222
|
-
var PROFILE_QUERY = `
|
|
223
|
-
SELECT id, email, firstName, lastName, fullName, status, profilePath
|
|
224
|
-
FROM Profile
|
|
225
|
-
WHERE id = ?
|
|
226
|
-
LIMIT 1
|
|
227
|
-
`;
|
|
228
|
-
var USER_ACCESS_QUERY = `
|
|
229
|
-
SELECT id, userId, accessKey
|
|
230
|
-
FROM UserAccess
|
|
231
|
-
WHERE userId = ?
|
|
232
|
-
`;
|
|
233
|
-
function OfflineAuthProvider({
|
|
234
|
-
children,
|
|
235
|
-
db,
|
|
236
|
-
supabase,
|
|
237
|
-
isDbReady = true
|
|
238
|
-
}) {
|
|
239
|
-
const [user, setUser] = useState(null);
|
|
240
|
-
const [profile, setProfile] = useState(null);
|
|
241
|
-
const [userAccess, setUserAccess] = useState(null);
|
|
242
|
-
const [isLoadingUser, setIsLoadingUser] = useState(true);
|
|
243
|
-
const [isLoadingData, setIsLoadingData] = useState(true);
|
|
244
|
-
useEffect(() => {
|
|
245
|
-
let mounted = true;
|
|
246
|
-
async function loadUser() {
|
|
247
|
-
try {
|
|
248
|
-
const {
|
|
249
|
-
data
|
|
250
|
-
} = await supabase.auth.getSession();
|
|
251
|
-
if (mounted) {
|
|
252
|
-
setUser(data.session?.user ?? null);
|
|
253
|
-
setIsLoadingUser(false);
|
|
254
|
-
}
|
|
255
|
-
} catch (error) {
|
|
256
|
-
console.error("[OfflineAuthProvider] Error loading user:", error);
|
|
257
|
-
if (mounted) {
|
|
258
|
-
setUser(null);
|
|
259
|
-
setIsLoadingUser(false);
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
loadUser();
|
|
264
|
-
const {
|
|
265
|
-
data: {
|
|
266
|
-
subscription
|
|
267
|
-
}
|
|
268
|
-
} = supabase.auth.onAuthStateChange((_event, session) => {
|
|
269
|
-
if (mounted) {
|
|
270
|
-
setUser(session?.user ?? null);
|
|
271
|
-
}
|
|
272
|
-
});
|
|
273
|
-
return () => {
|
|
274
|
-
mounted = false;
|
|
275
|
-
subscription.unsubscribe();
|
|
276
|
-
};
|
|
277
|
-
}, [supabase]);
|
|
278
|
-
useEffect(() => {
|
|
279
|
-
if (!db || !isDbReady || !user?.id) {
|
|
280
|
-
setProfile(null);
|
|
281
|
-
setUserAccess(null);
|
|
282
|
-
setIsLoadingData(false);
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
let mounted_0 = true;
|
|
286
|
-
const abortController = new AbortController();
|
|
287
|
-
async function loadData() {
|
|
288
|
-
try {
|
|
289
|
-
setIsLoadingData(true);
|
|
290
|
-
const [profileResult, accessResult] = await Promise.all([db.getOptional(PROFILE_QUERY, [user.id]), db.getAll(USER_ACCESS_QUERY, [user.id])]);
|
|
291
|
-
if (mounted_0) {
|
|
292
|
-
setProfile(profileResult);
|
|
293
|
-
setUserAccess(accessResult);
|
|
294
|
-
setIsLoadingData(false);
|
|
295
|
-
}
|
|
296
|
-
} catch (error_0) {
|
|
297
|
-
console.error("[OfflineAuthProvider] Error loading auth data:", error_0);
|
|
298
|
-
if (mounted_0) {
|
|
299
|
-
setIsLoadingData(false);
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
loadData();
|
|
304
|
-
db.watch(PROFILE_QUERY, [user.id], {
|
|
305
|
-
onResult: (result) => {
|
|
306
|
-
if (mounted_0) {
|
|
307
|
-
const rows = result.rows?._array || [];
|
|
308
|
-
setProfile(rows[0] || null);
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
}, {
|
|
312
|
-
signal: abortController.signal
|
|
313
|
-
});
|
|
314
|
-
db.watch(USER_ACCESS_QUERY, [user.id], {
|
|
315
|
-
onResult: (result_0) => {
|
|
316
|
-
if (mounted_0) {
|
|
317
|
-
const rows_0 = result_0.rows?._array || [];
|
|
318
|
-
setUserAccess(rows_0);
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
}, {
|
|
322
|
-
signal: abortController.signal
|
|
323
|
-
});
|
|
324
|
-
return () => {
|
|
325
|
-
mounted_0 = false;
|
|
326
|
-
abortController.abort();
|
|
327
|
-
};
|
|
328
|
-
}, [db, isDbReady, user?.id]);
|
|
329
|
-
const handleSignOut = useCallback2(async () => {
|
|
330
|
-
const {
|
|
331
|
-
error: error_1
|
|
332
|
-
} = await supabase.auth.signOut();
|
|
333
|
-
if (error_1) {
|
|
334
|
-
console.error("[OfflineAuthProvider] Sign out error:", error_1);
|
|
335
|
-
throw error_1;
|
|
336
|
-
}
|
|
337
|
-
}, [supabase]);
|
|
338
|
-
const isLoading = isLoadingUser || !!user && isLoadingData;
|
|
339
|
-
return /* @__PURE__ */ jsx2(SimpleAuthProvider, { user, profile, userAccess, isLoading, onSignOut: handleSignOut, children });
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
export {
|
|
343
|
-
getPermissionLevel,
|
|
344
|
-
hasResourceAccess,
|
|
345
|
-
SimpleAuthProvider,
|
|
346
|
-
useSimpleAuth,
|
|
347
|
-
useRequireAuth,
|
|
348
|
-
useResourceAccess,
|
|
349
|
-
useCanView,
|
|
350
|
-
useCanEdit,
|
|
351
|
-
useCanDelete,
|
|
352
|
-
useCanShare,
|
|
353
|
-
OfflineAuthProvider
|
|
354
|
-
};
|
|
355
|
-
//# sourceMappingURL=chunk-5HJLTYRA.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/context/SimpleAuthProvider.tsx","../src/auth/context/OfflineAuthProvider.tsx"],"sourcesContent":["import { c as _c } from \"react/compiler-runtime\";\n/**\n * SimpleAuthProvider - Dead simple auth that works offline\n *\n * This provider is designed for offline-first apps using PowerSync.\n * All permission data is synced locally, no RPC calls needed.\n *\n * Features:\n * - Reads Profile from PowerSync (local SQLite)\n * - Reads UserAccess from PowerSync (local SQLite)\n * - Simple hasAccess() function with wildcard matching\n * - No batching, no caching, no TTL, no real-time subscriptions\n * - Works 100% offline\n */\n\nimport { ReactNode, useCallback, useMemo, createContext, useContext } from \"react\";\nimport { User } from \"@supabase/supabase-js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport type ProfileStatus = \"active\" | \"archived\" | \"suspended\";\nexport interface SimpleProfile {\n id: string;\n email?: string | null;\n firstName?: string | null;\n lastName?: string | null;\n fullName?: string | null;\n status?: ProfileStatus | null;\n profilePath?: string | null;\n [key: string]: unknown;\n}\nexport interface SimpleUserAccess {\n id: string;\n userId: string;\n accessKey: string;\n}\nexport interface SimpleAuthContextValue {\n /** Supabase user (from auth session) */\n user: User | null;\n /** Profile from PowerSync (local SQLite) */\n profile: SimpleProfile | null;\n /** Access keys from PowerSync (local SQLite) */\n accessKeys: string[];\n /** Whether auth data is loading */\n isLoading: boolean;\n /** Whether profile is archived */\n isArchived: boolean;\n /** Whether profile is suspended */\n isSuspended: boolean;\n /** Profile status */\n profileStatus: ProfileStatus | undefined;\n /**\n * Check if user has access to a resource.\n * Supports wildcards: *:*:*, project:*:read, project:123:*\n *\n * @example\n * hasAccess(\"admin\") // exact match\n * hasAccess(\"project:123:read\") // check specific resource\n */\n hasAccess: (accessKey: string) => boolean;\n /** Sign out the user */\n signOut: () => Promise<void>;\n}\n\n// ─── Context ─────────────────────────────────────────────────────────────────\n\nconst SimpleAuthContext = createContext<SimpleAuthContextValue | null>(null);\n\n// ─── Wildcard Matching ───────────────────────────────────────────────────────\n\n/**\n * Check if an access key pattern matches a requested key.\n * Supports wildcards (*) in any segment.\n *\n * Pattern examples:\n * - \"*:*:*\" matches everything (super admin)\n * - \"project:*:read\" matches project:123:read, project:456:read\n * - \"project:123:*\" matches project:123:read, project:123:write\n * - \"project:123:read\" exact match only\n */\nfunction matchesAccessPattern(pattern: string, requestedKey: string): boolean {\n // Exact match\n if (pattern === requestedKey) return true;\n\n // Super admin - matches everything\n if (pattern === \"*:*:*\") return true;\n\n // Split into segments for wildcard matching\n const patternParts = pattern.split(\":\");\n const keyParts = requestedKey.split(\":\");\n\n // Different number of segments - can't match\n // (unless pattern is shorter and last part is *)\n if (patternParts.length !== keyParts.length) {\n return false;\n }\n\n // Check each segment\n for (let i = 0; i < patternParts.length; i++) {\n const patternPart = patternParts[i];\n const keyPart = keyParts[i];\n\n // Wildcard matches anything\n if (patternPart === \"*\") continue;\n\n // Must match exactly\n if (patternPart !== keyPart) return false;\n }\n return true;\n}\n\n/**\n * Check if any of the user's access keys match the requested key.\n */\nfunction checkAccess(accessKeys: string[], requestedKey: string): boolean {\n // Empty key = no restriction\n if (!requestedKey) return true;\n\n // No access keys = no access\n if (!accessKeys || accessKeys.length === 0) return false;\n return accessKeys.some(pattern => matchesAccessPattern(pattern, requestedKey));\n}\n\n// ─── Permission Level Helpers ────────────────────────────────────────────────\n\n/**\n * Maps permission action strings to numeric levels for comparison.\n * Higher numbers grant more access.\n */\nexport function getPermissionLevel(action: string): number {\n switch (action.toLowerCase()) {\n case \"view\":\n case \"read\":\n return 1;\n case \"edit\":\n case \"write\":\n return 2;\n case \"admin\":\n case \"delete\":\n case \"share\":\n return 3;\n default:\n return 0;\n }\n}\n\n/**\n * Check if a user has at least the required permission level for a resource.\n * Checks all matching access keys and returns true if any grants sufficient access.\n *\n * @param accessKeys - User's access keys\n * @param resourceType - e.g., \"project\", \"client\", \"database\"\n * @param resourceId - The ID of the resource\n * @param requiredAction - e.g., \"read\", \"edit\", \"admin\"\n */\nexport function hasResourceAccess(accessKeys: string[], resourceType: string, resourceId: string, requiredAction: string): boolean {\n if (!accessKeys || accessKeys.length === 0) return false;\n\n // Super admin bypasses all checks\n if (accessKeys.includes(\"*:*:*\")) return true;\n const requiredLevel = getPermissionLevel(requiredAction);\n\n // Check each access key\n for (const key of accessKeys) {\n const parts = key.split(\":\");\n if (parts.length !== 3) continue;\n const [keyType, keyId, keyAction] = parts;\n\n // Check if type matches (or wildcard)\n if (keyType !== \"*\" && keyType.toLowerCase() !== resourceType.toLowerCase()) {\n continue;\n }\n\n // Check if ID matches (or wildcard)\n if (keyId !== \"*\" && keyId !== resourceId) {\n continue;\n }\n\n // Check permission level\n const grantedLevel = getPermissionLevel(keyAction);\n if (grantedLevel >= requiredLevel) {\n return true;\n }\n }\n return false;\n}\n\n// ─── Provider Props ──────────────────────────────────────────────────────────\n\nexport interface SimpleAuthProviderProps {\n children: ReactNode;\n /** Supabase user from auth session */\n user: User | null;\n /** Profile from PowerSync query */\n profile: SimpleProfile | null;\n /** User access records from PowerSync query */\n userAccess: SimpleUserAccess[] | null;\n /** Whether the data is loading */\n isLoading?: boolean;\n /** Sign out function */\n onSignOut: () => Promise<void>;\n}\n\n// ─── Provider Component ──────────────────────────────────────────────────────\n\nexport function SimpleAuthProvider(t0) {\n const $ = _c(20);\n const {\n children,\n user,\n profile,\n userAccess,\n isLoading: t1,\n onSignOut\n } = t0;\n const isLoading = t1 === undefined ? false : t1;\n let t2;\n bb0: {\n if (!userAccess) {\n let t3;\n if ($[0] === Symbol.for(\"react.memo_cache_sentinel\")) {\n t3 = [];\n $[0] = t3;\n } else {\n t3 = $[0];\n }\n t2 = t3;\n break bb0;\n }\n let t3;\n if ($[1] !== userAccess) {\n t3 = userAccess.map(_temp).filter(Boolean);\n $[1] = userAccess;\n $[2] = t3;\n } else {\n t3 = $[2];\n }\n t2 = t3;\n }\n const accessKeys = t2;\n const profileStatus = profile?.status as ProfileStatus | undefined;\n const isArchived = profileStatus === \"archived\";\n const isSuspended = profileStatus === \"suspended\";\n let t3;\n if ($[3] !== accessKeys || $[4] !== isArchived || $[5] !== isSuspended) {\n t3 = requestedKey => {\n if (isArchived || isSuspended) {\n return false;\n }\n return checkAccess(accessKeys, requestedKey);\n };\n $[3] = accessKeys;\n $[4] = isArchived;\n $[5] = isSuspended;\n $[6] = t3;\n } else {\n t3 = $[6];\n }\n const hasAccess = t3;\n let t4;\n if ($[7] !== accessKeys || $[8] !== hasAccess || $[9] !== isArchived || $[10] !== isLoading || $[11] !== isSuspended || $[12] !== onSignOut || $[13] !== profile || $[14] !== profileStatus || $[15] !== user) {\n t4 = {\n user,\n profile,\n accessKeys,\n isLoading,\n isArchived,\n isSuspended,\n profileStatus,\n hasAccess,\n signOut: onSignOut\n };\n $[7] = accessKeys;\n $[8] = hasAccess;\n $[9] = isArchived;\n $[10] = isLoading;\n $[11] = isSuspended;\n $[12] = onSignOut;\n $[13] = profile;\n $[14] = profileStatus;\n $[15] = user;\n $[16] = t4;\n } else {\n t4 = $[16];\n }\n const value = t4;\n let t5;\n if ($[17] !== children || $[18] !== value) {\n t5 = <SimpleAuthContext.Provider value={value}>{children}</SimpleAuthContext.Provider>;\n $[17] = children;\n $[18] = value;\n $[19] = t5;\n } else {\n t5 = $[19];\n }\n return t5;\n}\n\n// ─── Hook ────────────────────────────────────────────────────────────────────\n\n/**\n * Hook to access auth state and hasAccess function.\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { user, profile, hasAccess, isLoading } = useSimpleAuth();\n *\n * if (isLoading) return <Loading />;\n * if (!user) return <Login />;\n *\n * // Check simple access\n * if (hasAccess(\"admin\")) {\n * return <AdminPanel />;\n * }\n *\n * // Check resource access\n * if (hasAccess(\"project:123:edit\")) {\n * return <Editor />;\n * }\n *\n * return <ReadOnlyView />;\n * }\n * ```\n */\nfunction _temp(ua) {\n return ua.accessKey;\n}\nexport function useSimpleAuth() {\n const context = useContext(SimpleAuthContext);\n if (!context) {\n throw new Error(\"useSimpleAuth must be used within a SimpleAuthProvider\");\n }\n return context;\n}\n\n/**\n * Hook that requires authentication.\n * Throws if user is not authenticated.\n *\n * @example\n * ```tsx\n * function ProtectedComponent() {\n * const { user, hasAccess } = useRequireAuth();\n * // user is guaranteed to be non-null here\n * }\n * ```\n */\nexport function useRequireAuth() {\n const auth = useSimpleAuth();\n if (!auth.user) {\n throw new Error(\"User must be authenticated. Use useSimpleAuth() for nullable user.\");\n }\n return auth as SimpleAuthContextValue & {\n user: User;\n };\n}\n\n// ─── Utility Hook for Resource Access ────────────────────────────────────────\n\n/**\n * Hook to check resource-level access with permission levels.\n *\n * @example\n * ```tsx\n * function ProjectEditor({ projectId }: { projectId: string }) {\n * const canEdit = useResourceAccess(\"project\", projectId, \"edit\");\n * const canDelete = useResourceAccess(\"project\", projectId, \"admin\");\n *\n * return (\n * <div>\n * <button disabled={!canEdit}>Edit</button>\n * <button disabled={!canDelete}>Delete</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useResourceAccess(resourceType, resourceId, requiredAction) {\n const $ = _c(5);\n const {\n accessKeys,\n isArchived,\n isSuspended\n } = useSimpleAuth();\n let t0;\n bb0: {\n if (resourceId === undefined || resourceId === null) {\n t0 = false;\n break bb0;\n }\n if (isArchived || isSuspended) {\n t0 = false;\n break bb0;\n }\n const t1 = String(resourceId);\n let t2;\n if ($[0] !== accessKeys || $[1] !== requiredAction || $[2] !== resourceType || $[3] !== t1) {\n t2 = hasResourceAccess(accessKeys, resourceType, t1, requiredAction);\n $[0] = accessKeys;\n $[1] = requiredAction;\n $[2] = resourceType;\n $[3] = t1;\n $[4] = t2;\n } else {\n t2 = $[4];\n }\n t0 = t2;\n }\n return t0;\n}\n\n// ─── Convenience Hooks ───────────────────────────────────────────────────────\n\nexport function useCanView(resourceType, resourceId) {\n return useResourceAccess(resourceType, resourceId, \"view\");\n}\nexport function useCanEdit(resourceType, resourceId) {\n return useResourceAccess(resourceType, resourceId, \"edit\");\n}\nexport function useCanDelete(resourceType, resourceId) {\n return useResourceAccess(resourceType, resourceId, \"admin\");\n}\nexport function useCanShare(resourceType, resourceId) {\n return useResourceAccess(resourceType, resourceId, \"admin\");\n}","/**\n * OfflineAuthProvider - Pre-built auth provider for PowerSync apps\n *\n * This provider reads Profile and UserAccess from PowerSync (local SQLite)\n * and provides the SimpleAuthProvider context.\n *\n * Works 100% offline once data is synced.\n *\n * @example\n * ```tsx\n * import { OfflineAuthProvider } from \"@pol-studios/db\";\n * import { usePowerSync } from \"@pol-studios/powersync\";\n *\n * function App() {\n * const db = usePowerSync();\n * const supabase = useSupabase();\n *\n * return (\n * <OfflineAuthProvider db={db} supabase={supabase}>\n * <MyApp />\n * </OfflineAuthProvider>\n * );\n * }\n * ```\n */\n\nimport { ReactNode, useCallback, useEffect, useMemo, useState } from \"react\";\nimport { User } from \"@supabase/supabase-js\";\nimport { SimpleAuthProvider, type SimpleProfile, type SimpleUserAccess } from \"./SimpleAuthProvider\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\ninterface PowerSyncDB {\n getAll: <T>(sql: string, params?: any[]) => Promise<T[]>;\n getOptional: <T>(sql: string, params?: any[]) => Promise<T | null>;\n watch: (sql: string, params: any[], options: {\n onResult: (result: any) => void;\n }, abortOptions?: {\n signal: AbortSignal;\n }) => void;\n}\ninterface SupabaseClient {\n auth: {\n getUser: () => Promise<{\n data: {\n user: User | null;\n };\n error: any;\n }>;\n getSession: () => Promise<{\n data: {\n session: {\n user: User;\n } | null;\n };\n error: any;\n }>;\n signOut: () => Promise<{\n error: any;\n }>;\n onAuthStateChange: (callback: (event: string, session: any) => void) => {\n data: {\n subscription: {\n unsubscribe: () => void;\n };\n };\n };\n };\n}\nexport interface OfflineAuthProviderProps {\n children: ReactNode;\n /** PowerSync database instance */\n db: PowerSyncDB | null;\n /** Supabase client for auth */\n supabase: SupabaseClient;\n /** Whether PowerSync is ready */\n isDbReady?: boolean;\n}\n\n// ─── SQL Queries ─────────────────────────────────────────────────────────────\n\nconst PROFILE_QUERY = `\n SELECT id, email, firstName, lastName, fullName, status, profilePath\n FROM Profile\n WHERE id = ?\n LIMIT 1\n`;\nconst USER_ACCESS_QUERY = `\n SELECT id, userId, accessKey\n FROM UserAccess\n WHERE userId = ?\n`;\n\n// ─── Provider Component ──────────────────────────────────────────────────────\n\nexport function OfflineAuthProvider({\n children,\n db,\n supabase,\n isDbReady = true\n}: OfflineAuthProviderProps) {\n // ─── State ───────────────────────────────────────────────────────────────────\n const [user, setUser] = useState<User | null>(null);\n const [profile, setProfile] = useState<SimpleProfile | null>(null);\n const [userAccess, setUserAccess] = useState<SimpleUserAccess[] | null>(null);\n const [isLoadingUser, setIsLoadingUser] = useState(true);\n const [isLoadingData, setIsLoadingData] = useState(true);\n\n // ─── Auth State ──────────────────────────────────────────────────────────────\n\n // Get initial user\n useEffect(() => {\n let mounted = true;\n async function loadUser() {\n try {\n const {\n data\n } = await supabase.auth.getSession();\n if (mounted) {\n setUser(data.session?.user ?? null);\n setIsLoadingUser(false);\n }\n } catch (error) {\n console.error(\"[OfflineAuthProvider] Error loading user:\", error);\n if (mounted) {\n setUser(null);\n setIsLoadingUser(false);\n }\n }\n }\n loadUser();\n\n // Subscribe to auth changes\n const {\n data: {\n subscription\n }\n } = supabase.auth.onAuthStateChange((_event, session) => {\n if (mounted) {\n setUser(session?.user ?? null);\n }\n });\n return () => {\n mounted = false;\n subscription.unsubscribe();\n };\n }, [supabase]);\n\n // ─── Profile & UserAccess from PowerSync ─────────────────────────────────────\n\n // Load profile and user access when user or db changes\n useEffect(() => {\n if (!db || !isDbReady || !user?.id) {\n setProfile(null);\n setUserAccess(null);\n setIsLoadingData(false);\n return;\n }\n let mounted_0 = true;\n const abortController = new AbortController();\n\n // Initial load\n async function loadData() {\n try {\n setIsLoadingData(true);\n const [profileResult, accessResult] = await Promise.all([db!.getOptional<SimpleProfile>(PROFILE_QUERY, [user!.id]), db!.getAll<SimpleUserAccess>(USER_ACCESS_QUERY, [user!.id])]);\n if (mounted_0) {\n setProfile(profileResult);\n setUserAccess(accessResult);\n setIsLoadingData(false);\n }\n } catch (error_0) {\n console.error(\"[OfflineAuthProvider] Error loading auth data:\", error_0);\n if (mounted_0) {\n setIsLoadingData(false);\n }\n }\n }\n loadData();\n\n // Watch for profile changes\n db.watch(PROFILE_QUERY, [user.id], {\n onResult: result => {\n if (mounted_0) {\n const rows = result.rows?._array || [];\n setProfile(rows[0] || null);\n }\n }\n }, {\n signal: abortController.signal\n });\n\n // Watch for user access changes\n db.watch(USER_ACCESS_QUERY, [user.id], {\n onResult: result_0 => {\n if (mounted_0) {\n const rows_0 = result_0.rows?._array || [];\n setUserAccess(rows_0);\n }\n }\n }, {\n signal: abortController.signal\n });\n return () => {\n mounted_0 = false;\n abortController.abort();\n };\n }, [db, isDbReady, user?.id]);\n\n // ─── Sign Out ────────────────────────────────────────────────────────────────\n\n const handleSignOut = useCallback(async () => {\n const {\n error: error_1\n } = await supabase.auth.signOut();\n if (error_1) {\n console.error(\"[OfflineAuthProvider] Sign out error:\", error_1);\n throw error_1;\n }\n }, [supabase]);\n\n // ─── Loading State ───────────────────────────────────────────────────────────\n\n const isLoading = isLoadingUser || !!user && isLoadingData;\n\n // ─── Render ──────────────────────────────────────────────────────────────────\n\n return <SimpleAuthProvider user={user} profile={profile} userAccess={userAccess} isLoading={isLoading} onSignOut={handleSignOut}>\n {children}\n </SimpleAuthProvider>;\n}"],"mappings":";AAAA,SAAS,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IACT,IAAI,MAAM,SAAS,KAAK,QAAQ;AAChC,QAAI,SAAS;AACX,cAAQ,MAAM,yCAAyC,OAAO;AAC9D,YAAM;AAAA,IACR;AAAA,EACF,GAAG,CAAC,QAAQ,CAAC;AAIb,QAAM,YAAY,iBAAiB,CAAC,CAAC,QAAQ;AAI7C,SAAO,gBAAAD,KAAC,sBAAmB,MAAY,SAAkB,YAAwB,WAAsB,WAAW,eAC7G,UACH;AACJ;","names":["t3","useCallback","jsx","useCallback"]}
|
package/dist/chunk-6KN7KLEG.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=chunk-6KN7KLEG.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/hooks/useOfflineAuth.ts","../src/auth/hooks/useAuth.ts","../src/auth/hooks/usePermission.ts"],"sourcesContent":["/**\n * useOfflineAuth - Hook for offline-first authentication\n *\n * Reads Profile and UserAccess from PowerSync (local SQLite).\n * Works 100% offline once data is synced.\n *\n * Usage:\n * ```tsx\n * import { SimpleAuthProvider } from \"@pol-studios/db\";\n * import { useOfflineAuth } from \"@pol-studios/db\";\n *\n * function AuthWrapper({ children }) {\n * const authData = useOfflineAuth();\n *\n * return (\n * <SimpleAuthProvider {...authData}>\n * {children}\n * </SimpleAuthProvider>\n * );\n * }\n * ```\n */\n\nimport { useCallback, useMemo } from \"react\";\nimport { User } from \"@supabase/supabase-js\";\nimport type { SimpleProfile, SimpleUserAccess } from \"../context/SimpleAuthProvider\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface OfflineAuthData {\n /** Supabase user from auth session */\n user: User | null;\n /** Profile from PowerSync */\n profile: SimpleProfile | null;\n /** User access records from PowerSync */\n userAccess: SimpleUserAccess[] | null;\n /** Whether auth data is loading */\n isLoading: boolean;\n /** Sign out function */\n onSignOut: () => Promise<void>;\n}\nexport interface UseOfflineAuthOptions {\n /** Supabase client for auth operations */\n supabase: {\n auth: {\n getUser: () => Promise<{\n data: {\n user: User | null;\n };\n error: any;\n }>;\n signOut: () => Promise<{\n error: any;\n }>;\n onAuthStateChange: (callback: (event: string, session: any) => void) => {\n data: {\n subscription: {\n unsubscribe: () => void;\n };\n };\n };\n };\n };\n /** PowerSync database for local queries */\n db: {\n getAll: <T>(sql: string, params?: any[]) => Promise<T[]>;\n getOptional: <T>(sql: string, params?: any[]) => Promise<T | null>;\n } | null;\n /** Whether PowerSync is ready */\n isDbReady?: boolean;\n}\n\n// ─── SQL Queries ─────────────────────────────────────────────────────────────\n\nconst PROFILE_QUERY = `\n SELECT id, email, firstName, lastName, fullName, status, profilePath\n FROM Profile\n WHERE id = ?\n LIMIT 1\n`;\nconst USER_ACCESS_QUERY = `\n SELECT id, userId, accessKey\n FROM UserAccess\n WHERE userId = ?\n`;\n\n// ─── Hook Implementation ─────────────────────────────────────────────────────\n\n/**\n * Creates offline auth data by reading from PowerSync.\n *\n * This is a low-level hook. For most use cases, use the pre-built\n * `OfflineAuthProvider` component instead.\n */\nexport function createOfflineAuthHook(options: UseOfflineAuthOptions) {\n const {\n supabase,\n db,\n isDbReady = true\n } = options;\n return function useOfflineAuthInternal(user: User | null): {\n profile: SimpleProfile | null;\n userAccess: SimpleUserAccess[] | null;\n isLoading: boolean;\n } {\n // This is a synchronous hook that expects data to be pre-loaded\n // In practice, you'd use React Query or similar for async loading\n // Here we return loading state if DB isn't ready\n return useMemo(() => ({\n profile: null,\n userAccess: null,\n isLoading: !isDbReady || !user\n }), [user, isDbReady]);\n };\n}\n\n// ─── React Query Integration ─────────────────────────────────────────────────\n\n/**\n * Query keys for React Query integration\n */\nexport const offlineAuthQueryKeys = {\n profile: (userId: string | undefined) => [\"profile\", userId] as const,\n userAccess: (userId: string | undefined) => [\"userAccess\", userId] as const\n};\n\n/**\n * Query functions for React Query integration.\n * Use these with useQuery from @tanstack/react-query.\n *\n * @example\n * ```tsx\n * import { useQuery } from \"@tanstack/react-query\";\n * import { offlineAuthQueries, offlineAuthQueryKeys } from \"@pol-studios/db\";\n *\n * function useProfile(db, userId) {\n * return useQuery({\n * queryKey: offlineAuthQueryKeys.profile(userId),\n * queryFn: () => offlineAuthQueries.fetchProfile(db, userId),\n * enabled: !!userId && !!db,\n * });\n * }\n * ```\n */\nexport const offlineAuthQueries = {\n async fetchProfile(db: {\n getOptional: <T>(sql: string, params?: any[]) => Promise<T | null>;\n }, userId: string): Promise<SimpleProfile | null> {\n return db.getOptional<SimpleProfile>(PROFILE_QUERY, [userId]);\n },\n async fetchUserAccess(db: {\n getAll: <T>(sql: string, params?: any[]) => Promise<T[]>;\n }, userId: string): Promise<SimpleUserAccess[]> {\n return db.getAll<SimpleUserAccess>(USER_ACCESS_QUERY, [userId]);\n }\n};\n\n// ─── Utility Functions ───────────────────────────────────────────────────────\n\n/**\n * Extract access keys from UserAccess records.\n */\nexport function extractAccessKeys(userAccess: SimpleUserAccess[] | null): string[] {\n if (!userAccess) return [];\n return userAccess.map(ua => ua.accessKey).filter(Boolean);\n}","import { isUsable } from \"@pol-studios/utils\";\nimport { useCallback, useContext, useMemo } from \"react\";\nimport { User } from \"@supabase/supabase-js\";\nimport { SetupAuthContext, setupAuthContext, type EffectivePermission } from \"../context/AuthProvider\";\nimport { permissionContext } from \"../context/PermissionContext\";\nimport { EntityAction, EntityType } from \"../types/EntityPermissions\";\n\n// Re-export EffectivePermission type for consumers\nexport type { EffectivePermission };\n\n/**\n * Hook for authenticated users only.\n * Throws an error if the user is not authenticated.\n * Use useSetupAuth() if you need to handle unauthenticated users.\n *\n * @returns Auth context with guaranteed non-null user and hasAccess helper\n * @throws Error if user is not authenticated\n *\n * @example\n * ```tsx\n * function AuthenticatedComponent() {\n * const { user, hasAccess, profile } = useAuth();\n *\n * // user is guaranteed to be non-null\n * console.log(user.id);\n *\n * if (hasAccess('admin')) {\n * return <AdminDashboard />;\n * }\n *\n * return <UserDashboard />;\n * }\n * ```\n */\nexport function useAuth() {\n const auth = useContext(setupAuthContext);\n if (isUsable(auth.user) === false) {\n console.log({\n auth\n });\n throw new Error(\"User must not be null, use useSetupAuth() to use a nullable user.\");\n } else {\n return auth as any;\n }\n}\n\n/**\n * Hook for handling both authenticated and unauthenticated states.\n * Does not throw if user is not authenticated.\n *\n * @returns Auth context with possibly null user, hasAccess, and hasEntityAccess helpers\n *\n * @example\n * ```tsx\n * function FlexibleComponent() {\n * const { user, hasAccess, hasEntityAccess, isLoading } = useSetupAuth();\n *\n * if (isLoading) {\n * return <Spinner />;\n * }\n *\n * if (!user) {\n * return <LoginPrompt />;\n * }\n *\n * // Check global access\n * const isAdmin = hasAccess('admin');\n *\n * // Check entity-level access\n * const canEditProject = hasEntityAccess('Project', 123, 'edit');\n *\n * return <Dashboard />;\n * }\n * ```\n */\nexport function useSetupAuth(): SetupAuthContext & {\n hasAccess: (access: string) => boolean;\n hasEntityAccess: (entityType: EntityType, entityId: number, action: EntityAction) => boolean;\n effectivePermissions: EffectivePermission[];\n} {\n const auth = useContext(setupAuthContext);\n const entityPermissions = useContext(permissionContext);\n\n // Use the context's hasAccess which now includes effective permissions checking\n const hasAccess = useCallback((key: string) => {\n // Delegate to context hasAccess if available (includes effective permissions)\n if (auth.hasAccess) {\n return auth.hasAccess(key);\n }\n\n // Fallback for backward compatibility\n // Archived/suspended users have no access\n if (auth.isArchived || auth.isSuspended) {\n return false;\n }\n const accessGiven = auth.access;\n if (isUsable(accessGiven) === false) return false;\n // Super-admin key bypasses all permission checks\n if (accessGiven.includes(\"*:*:*\")) return true;\n if (accessGiven.includes(key)) return true;\n if (isUsable(key) === false) return true;\n return false;\n }, [auth.hasAccess, auth.access, auth.isArchived, auth.isSuspended]);\n\n /**\n * Check if the current user has access to a specific entity.\n * Super-admin key (*:*:*) bypasses entity permissions entirely.\n * Otherwise, delegates to the PermissionContext for granular permission checks.\n *\n * @param entityType - 'Project' | 'Client' | 'ProjectDatabase'\n * @param entityId - The ID of the entity to check\n * @param action - 'view' | 'adminView' | 'edit' | 'create' | 'delete' | 'share'\n * @returns boolean - true if user has permission for the action on the entity\n */\n const hasEntityAccess = useCallback((entityType: EntityType, entityId: number, action: EntityAction): boolean => {\n // Archived/suspended users have no entity access\n if (auth.isArchived || auth.isSuspended) {\n return false;\n }\n\n // Validate entityId is a valid positive integer\n if (!entityId || entityId <= 0 || !Number.isInteger(entityId)) {\n return false;\n }\n\n // Super-admin key bypasses all entity permission checks\n const accessGiven_0 = auth.access;\n if (isUsable(accessGiven_0) && accessGiven_0.includes(\"*:*:*\")) {\n return true;\n }\n\n // If PermissionContext is not available, deny access\n if (!entityPermissions || typeof entityPermissions.checkPermission !== \"function\") {\n return false;\n }\n\n // Delegate to PermissionContext\n return entityPermissions.checkPermission(entityType, entityId, action);\n }, [auth.access, auth.isArchived, auth.isSuspended, entityPermissions]);\n return useMemo(() => ({\n hasAccess,\n hasEntityAccess,\n ...auth,\n user: auth.user,\n effectivePermissions: auth.effectivePermissions || []\n }), [hasAccess, hasEntityAccess, auth]);\n}","import { c as _c } from \"react/compiler-runtime\";\nimport { useContext, useEffect, useMemo } from \"react\";\nimport { permissionContext } from \"../context/PermissionContext\";\nimport { EntityType, EntityAction, EntityPermissionCheck } from \"../types/EntityPermissions\";\n\n// Re-export types for convenience\nexport type { EntityType, EntityAction, EntityPermissionCheck };\n\n/**\n * Hook to get the full PermissionContext\n * @throws Error if used outside of PermissionProvider\n */\nfunction usePermissionContext() {\n const context = useContext(permissionContext);\n if (!context || Object.keys(context).length === 0) {\n throw new Error(\"usePermission hooks must be used within a PermissionProvider\");\n }\n return context;\n}\n\n/**\n * Hook to get full permission info for a single entity\n * @param entityType - 'Project' | 'Client' | 'ProjectDatabase'\n * @param entityId - The ID of the entity (can be undefined for loading states)\n * @returns EntityPermissionCheck with canView, canEdit, etc. and isLoading\n *\n * @example\n * ```tsx\n * function ProjectHeader({ projectId }: { projectId: number }) {\n * const permission = usePermission('Project', projectId);\n *\n * if (permission.isLoading) {\n * return <Spinner />;\n * }\n *\n * return (\n * <div>\n * {permission.canEdit && <EditButton />}\n * {permission.canDelete && <DeleteButton />}\n * </div>\n * );\n * }\n * ```\n */\nexport function usePermission(entityType, entityId) {\n const $ = _c(5);\n const {\n getPermission\n } = usePermissionContext();\n let t0;\n bb0: {\n if (entityId === undefined) {\n let t1;\n if ($[0] === Symbol.for(\"react.memo_cache_sentinel\")) {\n t1 = {\n canView: false,\n canAdminView: false,\n canEdit: false,\n canCreate: false,\n canDelete: false,\n canShare: false,\n permissionLevel: null,\n isLoading: true\n };\n $[0] = t1;\n } else {\n t1 = $[0];\n }\n t0 = t1;\n break bb0;\n }\n let t1;\n if ($[1] !== entityId || $[2] !== entityType || $[3] !== getPermission) {\n t1 = getPermission(entityType, entityId);\n $[1] = entityId;\n $[2] = entityType;\n $[3] = getPermission;\n $[4] = t1;\n } else {\n t1 = $[4];\n }\n t0 = t1;\n }\n return t0;\n}\n\n/**\n * Hook to check a single action permission\n * @param entityType - Entity type\n * @param entityId - Entity ID\n * @param action - 'view' | 'adminView' | 'edit' | 'create' | 'delete' | 'share'\n * @returns boolean - true if user has permission for action\n *\n * @example\n * ```tsx\n * function ProjectActions({ projectId }: { projectId: number }) {\n * const canEdit = usePermissionCheck('Project', projectId, 'edit');\n * const canDelete = usePermissionCheck('Project', projectId, 'delete');\n *\n * return (\n * <div>\n * <Button disabled={!canEdit}>Edit</Button>\n * <Button disabled={!canDelete}>Delete</Button>\n * </div>\n * );\n * }\n * ```\n */\nexport function usePermissionCheck(entityType, entityId, action) {\n const $ = _c(5);\n const {\n checkPermission\n } = usePermissionContext();\n let t0;\n bb0: {\n if (entityId === undefined) {\n t0 = false;\n break bb0;\n }\n let t1;\n if ($[0] !== action || $[1] !== checkPermission || $[2] !== entityId || $[3] !== entityType) {\n t1 = checkPermission(entityType, entityId, action);\n $[0] = action;\n $[1] = checkPermission;\n $[2] = entityId;\n $[3] = entityType;\n $[4] = t1;\n } else {\n t1 = $[4];\n }\n t0 = t1;\n }\n return t0;\n}\n\n/**\n * Result type for usePermissions batch hook\n */\nexport interface EntityWithPermission {\n type: EntityType;\n id: number;\n permission: EntityPermissionCheck;\n}\n\n/**\n * Hook for batch permission lookup - useful for lists\n * @param entities - Array of { type, id } objects\n * @returns Array of entities with their permissions attached\n *\n * This hook:\n * - Calls prefetchPermissions on mount and when entities change\n * - Returns memoized results\n * - Handles empty arrays gracefully\n *\n * @example\n * ```tsx\n * function ProjectList({ projects }: { projects: Array<{ id: number; name: string }> }) {\n * const entities = projects.map(p => ({ type: 'Project' as const, id: p.id }));\n * const entitiesWithPermissions = usePermissionsBatch(entities);\n *\n * return (\n * <ul>\n * {entitiesWithPermissions.map(({ id, permission }) => {\n * const project = projects.find(p => p.id === id);\n * return (\n * <li key={id}>\n * {project?.name}\n * {permission.canEdit && <EditIcon />}\n * </li>\n * );\n * })}\n * </ul>\n * );\n * }\n * ```\n */\nexport function usePermissionsBatch(entities: Array<{\n type: EntityType;\n id: number;\n}>): EntityWithPermission[] {\n const {\n getPermission,\n prefetchPermissions\n } = usePermissionContext();\n\n // Memoize the entities array to prevent unnecessary re-renders\n const entitiesKey = useMemo(() => entities.map(e => `${e.type}:${e.id}`).sort().join(\",\"), [entities]);\n\n // Prefetch permissions when entities change\n useEffect(() => {\n if (entities.length === 0) {\n return;\n }\n\n // Convert to the format expected by prefetchPermissions\n const entitiesToPrefetch = entities.map(e_0 => ({\n entityType: e_0.type,\n entityId: e_0.id\n }));\n prefetchPermissions(entitiesToPrefetch);\n }, [entities, entitiesKey, prefetchPermissions]);\n\n // Return memoized results\n return useMemo(() => {\n if (entities.length === 0) {\n return [];\n }\n return entities.map(entity => ({\n type: entity.type,\n id: entity.id,\n permission: getPermission(entity.type, entity.id)\n }));\n }, [getPermission, entitiesKey]);\n}\n\n/**\n * Simple boolean hook to check if user can view an entity\n * @param entityType - Entity type\n * @param entityId - Entity ID (can be undefined for loading states)\n * @returns boolean - true if user can view the entity\n *\n * @example\n * ```tsx\n * function ProjectPage({ projectId }: { projectId: number }) {\n * const canView = useCanView('Project', projectId);\n *\n * if (!canView) {\n * return <AccessDenied />;\n * }\n *\n * return <ProjectContent projectId={projectId} />;\n * }\n * ```\n */\nexport function useCanView(entityType, entityId) {\n return usePermissionCheck(entityType, entityId, \"view\");\n}\n\n/**\n * Simple boolean hook to check if user can edit an entity\n * @param entityType - Entity type\n * @param entityId - Entity ID (can be undefined for loading states)\n * @returns boolean - true if user can edit the entity\n *\n * @example\n * ```tsx\n * function ProjectEditor({ projectId }: { projectId: number }) {\n * const canEdit = useCanEdit('Project', projectId);\n *\n * return (\n * <form>\n * <input disabled={!canEdit} />\n * <button disabled={!canEdit}>Save</button>\n * </form>\n * );\n * }\n * ```\n */\nexport function useCanEdit(entityType, entityId) {\n return usePermissionCheck(entityType, entityId, \"edit\");\n}\n\n/**\n * Simple boolean hook to check if user can delete an entity\n * @param entityType - Entity type\n * @param entityId - Entity ID (can be undefined for loading states)\n * @returns boolean - true if user can delete the entity\n *\n * @example\n * ```tsx\n * function ProjectActions({ projectId }: { projectId: number }) {\n * const canDelete = useCanDelete('Project', projectId);\n *\n * return (\n * <Button\n * variant=\"destructive\"\n * disabled={!canDelete}\n * onClick={handleDelete}\n * >\n * Delete Project\n * </Button>\n * );\n * }\n * ```\n */\nexport function useCanDelete(entityType, entityId) {\n return usePermissionCheck(entityType, entityId, \"delete\");\n}\n\n/**\n * Simple boolean hook to check if user can share an entity\n * @param entityType - Entity type\n * @param entityId - Entity ID (can be undefined for loading states)\n * @returns boolean - true if user can share the entity\n *\n * @example\n * ```tsx\n * function ShareButton({ projectId }: { projectId: number }) {\n * const canShare = useCanShare('Project', projectId);\n *\n * if (!canShare) {\n * return null;\n * }\n *\n * return <Button onClick={openShareModal}>Share</Button>;\n * }\n * ```\n */\nexport function useCanShare(entityType, entityId) {\n return usePermissionCheck(entityType, entityId, \"share\");\n}\n\n/**\n * Simple boolean hook to check if user can create entities of a type\n * Note: For create permission, the entityId should be the parent entity ID\n * (e.g., for creating a ProjectDatabase, pass the Project ID)\n *\n * @param entityType - Entity type\n * @param entityId - Parent entity ID (can be undefined for loading states)\n * @returns boolean - true if user can create entities\n *\n * @example\n * ```tsx\n * function AddDatabaseButton({ projectId }: { projectId: number }) {\n * const canCreate = useCanCreate('ProjectDatabase', projectId);\n *\n * return (\n * <Button disabled={!canCreate} onClick={handleCreate}>\n * Add Database\n * </Button>\n * );\n * }\n * ```\n */\nexport function useCanCreate(entityType, entityId) {\n return usePermissionCheck(entityType, entityId, \"create\");\n}\n\n/**\n * Hook to invalidate permission cache for a specific entity\n * Useful after permission changes (e.g., after sharing an entity)\n *\n * @returns Function to invalidate permission for an entity\n *\n * @example\n * ```tsx\n * function ShareModal({ projectId }: { projectId: number }) {\n * const invalidatePermission = useInvalidatePermission();\n *\n * const handleShare = async (userId: string) => {\n * await shareProject(projectId, userId);\n * invalidatePermission('Project', projectId);\n * };\n *\n * return <ShareForm onShare={handleShare} />;\n * }\n * ```\n */\nexport function useInvalidatePermission() {\n const {\n invalidatePermission\n } = usePermissionContext();\n return invalidatePermission;\n}\n\n/**\n * Hook to get the loading state of the permission context\n * @returns boolean - true if permissions are being fetched\n *\n * @example\n * ```tsx\n * function PermissionAwareComponent() {\n * const isLoadingPermissions = usePermissionLoading();\n *\n * if (isLoadingPermissions) {\n * return <LoadingSpinner />;\n * }\n *\n * return <Content />;\n * }\n * ```\n */\nexport function usePermissionLoading() {\n const {\n isLoading\n } = usePermissionContext();\n return isLoading;\n}"],"mappings":";;;;;;AAuBA,SAAsB,eAAe;AAmDrC,IAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAMtB,IAAM,oBAAoB;AAAA;AAAA;AAAA;AAAA;AAyCnB,IAAM,uBAAuB;AAAA,EAClC,SAAS,CAAC,WAA+B,CAAC,WAAW,MAAM;AAAA,EAC3D,YAAY,CAAC,WAA+B,CAAC,cAAc,MAAM;AACnE;AAoBO,IAAM,qBAAqB;AAAA,EAChC,MAAM,aAAa,IAEhB,QAA+C;AAChD,WAAO,GAAG,YAA2B,eAAe,CAAC,MAA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