@eskais/app-sdk 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +68 -2
- package/dist/action/action.d.ts +74 -0
- package/dist/action/action.js +106 -0
- package/dist/cli/cli.d.ts +2 -0
- package/dist/cli/cli.js +51 -0
- package/dist/cli/routes.d.ts +17 -0
- package/dist/cli/routes.js +36 -0
- package/dist/core/assume.d.ts +1 -0
- package/dist/core/assume.js +8 -0
- package/dist/core/constants.d.ts +302 -0
- package/dist/core/constants.js +156 -0
- package/dist/core/contracts.d.ts +100 -0
- package/dist/core/contracts.js +3 -0
- package/dist/core/data-labels.d.ts +196 -0
- package/dist/core/data-labels.js +345 -0
- package/dist/core/errors.d.ts +46 -0
- package/dist/core/errors.js +166 -0
- package/dist/core/guards.d.ts +9 -0
- package/dist/core/guards.js +14 -0
- package/dist/core/refusal.d.ts +30 -0
- package/dist/core/refusal.js +53 -0
- package/dist/draft/draft.d.ts +36 -0
- package/dist/draft/draft.js +87 -0
- package/dist/export/csv.d.ts +25 -0
- package/dist/export/csv.js +59 -0
- package/dist/import/csv-parse.d.ts +11 -0
- package/dist/import/csv-parse.js +70 -0
- package/dist/import/import.d.ts +102 -0
- package/dist/import/import.js +263 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +30 -0
- package/dist/navigation/nav.d.ts +119 -0
- package/dist/navigation/nav.js +278 -0
- package/dist/navigation/router.d.ts +81 -0
- package/dist/navigation/router.js +249 -0
- package/dist/navigation/shortcuts.d.ts +37 -0
- package/dist/navigation/shortcuts.js +93 -0
- package/dist/next/index.d.ts +3 -0
- package/dist/next/index.js +3 -0
- package/dist/next/screen-hydration.d.ts +12 -0
- package/dist/next/screen-hydration.js +26 -0
- package/dist/next/screen.d.ts +25 -0
- package/dist/next/screen.js +44 -0
- package/dist/next/server/handler.d.ts +39 -0
- package/dist/next/server/handler.js +190 -0
- package/dist/next/server/index.d.ts +5 -0
- package/dist/next/server/index.js +5 -0
- package/dist/next/server/page.d.ts +57 -0
- package/dist/next/server/page.js +103 -0
- package/dist/next/server/prefetch.d.ts +29 -0
- package/dist/next/server/prefetch.js +97 -0
- package/dist/next/server/session.d.ts +12 -0
- package/dist/next/server/session.js +10 -0
- package/dist/next/use-next-router.d.ts +21 -0
- package/dist/next/use-next-router.js +104 -0
- package/dist/react/data-layer.d.ts +31 -0
- package/dist/react/data-layer.js +31 -0
- package/dist/react/hooks/use-action.d.ts +12 -0
- package/dist/react/hooks/use-action.js +67 -0
- package/dist/react/hooks/use-better-auth.d.ts +12 -0
- package/dist/react/hooks/use-better-auth.js +11 -0
- package/dist/react/hooks/use-draft.d.ts +5 -0
- package/dist/react/hooks/use-draft.js +17 -0
- package/dist/react/hooks/use-nav.d.ts +17 -0
- package/dist/react/hooks/use-nav.js +34 -0
- package/dist/react/hooks/use-resource.d.ts +69 -0
- package/dist/react/hooks/use-resource.js +218 -0
- package/dist/react/hooks/use-view.d.ts +6 -0
- package/dist/react/hooks/use-view.js +24 -0
- package/dist/react/index.d.ts +8 -0
- package/dist/react/index.js +8 -0
- package/dist/react/keys.d.ts +51 -0
- package/dist/react/keys.js +67 -0
- package/dist/resource/form-schema.d.ts +11 -0
- package/dist/resource/form-schema.js +51 -0
- package/dist/resource/relations.d.ts +99 -0
- package/dist/resource/relations.js +194 -0
- package/dist/resource/resource-relations.d.ts +44 -0
- package/dist/resource/resource-relations.js +141 -0
- package/dist/resource/resource-schema.d.ts +9 -0
- package/dist/resource/resource-schema.js +73 -0
- package/dist/resource/resource-types.d.ts +281 -0
- package/dist/resource/resource-types.js +1 -0
- package/dist/resource/resource.d.ts +11 -0
- package/dist/resource/resource.js +354 -0
- package/dist/resource/schema.d.ts +57 -0
- package/dist/resource/schema.js +115 -0
- package/dist/services/from-page-source.d.ts +15 -0
- package/dist/services/from-page-source.js +27 -0
- package/dist/services/memory-query.d.ts +8 -0
- package/dist/services/memory-query.js +165 -0
- package/dist/services/memory-service.d.ts +33 -0
- package/dist/services/memory-service.js +291 -0
- package/dist/services/rest-service.d.ts +62 -0
- package/dist/services/rest-service.js +220 -0
- package/dist/services/rng.d.ts +9 -0
- package/dist/services/rng.js +22 -0
- package/dist/services/spring-service.d.ts +58 -0
- package/dist/services/spring-service.js +132 -0
- package/dist/session/better-auth.d.ts +83 -0
- package/dist/session/better-auth.js +86 -0
- package/dist/session/session.d.ts +45 -0
- package/dist/session/session.js +36 -0
- package/dist/view/preferences.d.ts +35 -0
- package/dist/view/preferences.js +93 -0
- package/dist/view/view-types.d.ts +122 -0
- package/dist/view/view-types.js +1 -0
- package/dist/view/view-url.d.ts +7 -0
- package/dist/view/view-url.js +54 -0
- package/dist/view/view.d.ts +4 -0
- package/dist/view/view.js +392 -0
- package/package.json +85 -4
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { assumeType } from "../core/assume.js";
|
|
2
|
+
import { PagePositionKind, TotalKind } from "../core/constants.js";
|
|
3
|
+
import { isBoolean, isNumber, isRecord, isString } from "../core/guards.js";
|
|
4
|
+
import { restService } from "./rest-service.js";
|
|
5
|
+
const quote = (value) => `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
|
|
6
|
+
function literal(value) {
|
|
7
|
+
if (isString(value))
|
|
8
|
+
return quote(value);
|
|
9
|
+
if (isNumber(value) || isBoolean(value))
|
|
10
|
+
return String(value);
|
|
11
|
+
if (value instanceof Date)
|
|
12
|
+
return quote(value.toISOString());
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
function clauses(path, value) {
|
|
16
|
+
if (value === undefined || value === null || value === "")
|
|
17
|
+
return [];
|
|
18
|
+
if (Array.isArray(value)) {
|
|
19
|
+
const entries = value;
|
|
20
|
+
const items = entries.flatMap((entry) => {
|
|
21
|
+
const text = literal(entry);
|
|
22
|
+
return text === undefined ? [] : [text];
|
|
23
|
+
});
|
|
24
|
+
return items.length === 0 ? [] : [`${path} in [${items.join(", ")}]`];
|
|
25
|
+
}
|
|
26
|
+
if (isRecord(value)) {
|
|
27
|
+
const lower = value.from ?? value.min ?? value.gte;
|
|
28
|
+
const upper = value.to ?? value.max ?? value.lte;
|
|
29
|
+
if (lower !== undefined || upper !== undefined) {
|
|
30
|
+
const low = literal(lower);
|
|
31
|
+
const high = literal(upper);
|
|
32
|
+
return [
|
|
33
|
+
...(low === undefined ? [] : [`${path} >: ${low}`]),
|
|
34
|
+
...(high === undefined ? [] : [`${path} <: ${high}`]),
|
|
35
|
+
];
|
|
36
|
+
}
|
|
37
|
+
return Object.entries(value).flatMap(([key, entry]) => clauses(`${path}.${key}`, entry));
|
|
38
|
+
}
|
|
39
|
+
const text = literal(value);
|
|
40
|
+
return text === undefined ? [] : [`${path} : ${text}`];
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A filter as a spring-filter expression: a value is `field : 'x'`, a list `field in ['a', 'b']`, a range
|
|
44
|
+
* (`{ from, to }`, `{ min, max }`) `field >: a and field <: b`, and a nested record `country.code : 'ES'`.
|
|
45
|
+
*/
|
|
46
|
+
export function springFilter(filter) {
|
|
47
|
+
if (!isRecord(filter))
|
|
48
|
+
return undefined;
|
|
49
|
+
const parts = Object.entries(filter).flatMap(([key, value]) => clauses(key, value));
|
|
50
|
+
return parts.length === 0 ? undefined : parts.join(" and ");
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* A filter as query parameters Spring's data binder reads: a list repeats its parameter (`status=a&status=b`, a
|
|
54
|
+
* `List<String>`), a nested record goes by dotted path (`createdAt.from=…`, a nested object), a date as ISO text.
|
|
55
|
+
*/
|
|
56
|
+
export function springParams(filter, prefix = "") {
|
|
57
|
+
if (!isRecord(filter))
|
|
58
|
+
return {};
|
|
59
|
+
const params = {};
|
|
60
|
+
for (const [key, value] of Object.entries(filter)) {
|
|
61
|
+
const name = `${prefix}${key}`;
|
|
62
|
+
if (value instanceof Date)
|
|
63
|
+
params[name] = value.toISOString();
|
|
64
|
+
else if (isRecord(value))
|
|
65
|
+
Object.assign(params, springParams(value, `${name}.`));
|
|
66
|
+
else
|
|
67
|
+
params[name] = value;
|
|
68
|
+
}
|
|
69
|
+
return params;
|
|
70
|
+
}
|
|
71
|
+
const violationPrefix = /^[A-Za-z_$][\w$]*\.arg\d+\./u;
|
|
72
|
+
function readSpringPage(raw, slice) {
|
|
73
|
+
if (Array.isArray(raw)) {
|
|
74
|
+
// Workaround: a body that is a bare list is the server's rows, typed by the service's `T`.
|
|
75
|
+
return { items: assumeType(raw) };
|
|
76
|
+
}
|
|
77
|
+
if (!isRecord(raw) || !Array.isArray(raw.content))
|
|
78
|
+
return { items: [] };
|
|
79
|
+
const meta = isRecord(raw.page) ? raw.page : raw;
|
|
80
|
+
const number = isNumber(meta.number) ? meta.number : undefined;
|
|
81
|
+
const totalPages = isNumber(meta.totalPages) ? meta.totalPages : undefined;
|
|
82
|
+
const totalElements = isNumber(meta.totalElements) ? meta.totalElements : undefined;
|
|
83
|
+
const hasMore = isBoolean(raw.hasNext)
|
|
84
|
+
? raw.hasNext
|
|
85
|
+
: isBoolean(raw.last)
|
|
86
|
+
? !raw.last
|
|
87
|
+
: number !== undefined && totalPages !== undefined
|
|
88
|
+
? number + 1 < totalPages
|
|
89
|
+
: undefined;
|
|
90
|
+
const hasPrevious = isBoolean(raw.first) ? !raw.first : number === undefined ? undefined : number > 0;
|
|
91
|
+
return {
|
|
92
|
+
// Workaround: `content` is checked to be a list above; its rows are the server's, typed by the service's `T`.
|
|
93
|
+
items: assumeType(raw.content),
|
|
94
|
+
...(slice || totalElements === undefined ? {} : { total: totalElements }),
|
|
95
|
+
...(hasMore === undefined ? {} : { hasMore }),
|
|
96
|
+
...(hasPrevious === undefined ? {} : { hasPrevious }),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* A Spring Boot backend: Spring Data's `Pageable` (`?page=0&size=25&sort=name,asc&sort=id,desc`), its `Page<T>` or
|
|
101
|
+
* `PagedModel` (or `Slice<T>` with `slice`), the filter as parameters the data binder reads or as spring-filter,
|
|
102
|
+
* and errors from `ProblemDetail` (RFC 9457) and Bean Validation as `ServiceError`s with their field errors.
|
|
103
|
+
*/
|
|
104
|
+
export function springService(base, options = {}) {
|
|
105
|
+
const { slice = false, select, springFilter: expression, fieldPath, projection, ...rest } = options;
|
|
106
|
+
const pathOf = fieldPath ?? ((path) => path.replace(violationPrefix, ""));
|
|
107
|
+
const mapError = (error) => {
|
|
108
|
+
const mapped = error.fields
|
|
109
|
+
? { ...error, fields: error.fields.map((field) => ({ ...field, path: pathOf(field.path) })) }
|
|
110
|
+
: error;
|
|
111
|
+
return rest.mapError ? rest.mapError(mapped) : mapped;
|
|
112
|
+
};
|
|
113
|
+
const writeExpression = expression === true ? (filter) => springFilter(filter) : expression === false ? undefined : expression;
|
|
114
|
+
return restService(base, {
|
|
115
|
+
...rest,
|
|
116
|
+
pageBase: 0,
|
|
117
|
+
position: PagePositionKind.page,
|
|
118
|
+
total: slice ? TotalKind.none : TotalKind.exact,
|
|
119
|
+
filterParams: rest.filterParams ??
|
|
120
|
+
(writeExpression
|
|
121
|
+
? (filter) => {
|
|
122
|
+
const text = writeExpression(filter);
|
|
123
|
+
return text === undefined ? {} : { filter: text };
|
|
124
|
+
}
|
|
125
|
+
: springParams),
|
|
126
|
+
read: (raw) => readSpringPage(select ? select(raw) : raw, slice),
|
|
127
|
+
includeParams: projection === false
|
|
128
|
+
? false
|
|
129
|
+
: (projection ?? ((include) => ({ projection: include.join(",") }))),
|
|
130
|
+
mapError,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { PermissionSubject, Session } from "./session.js";
|
|
2
|
+
/** What Better Auth's `useSession()` gives as `data`, and `auth.api.getSession({ headers })` returns. */
|
|
3
|
+
export type BetterAuthSessionData<User = BetterAuthUser> = {
|
|
4
|
+
user: User;
|
|
5
|
+
session: {
|
|
6
|
+
activeOrganizationId?: string | null;
|
|
7
|
+
token?: string;
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
};
|
|
10
|
+
} | null;
|
|
11
|
+
export type BetterAuthUser = {
|
|
12
|
+
id: string;
|
|
13
|
+
role?: string | null;
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
};
|
|
16
|
+
/** Better Auth's statements: `{ project: ["create", "update"] }`. */
|
|
17
|
+
export type BetterAuthPermissions = Record<string, string[]>;
|
|
18
|
+
/** A role made with Better Auth's access control (`ac.newRole({ … })`). */
|
|
19
|
+
export type BetterAuthRoleLike = {
|
|
20
|
+
authorize(request: BetterAuthPermissions): {
|
|
21
|
+
success: boolean;
|
|
22
|
+
error?: string | undefined;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
/** `authClient.useSession` in Better Auth's vanilla client: a store of `{ data }`. */
|
|
26
|
+
export type BetterAuthStoreLike<User = BetterAuthUser> = {
|
|
27
|
+
get(): {
|
|
28
|
+
data: BetterAuthSessionData<User> | undefined;
|
|
29
|
+
isPending?: boolean;
|
|
30
|
+
};
|
|
31
|
+
listen?(listener: () => void): () => void;
|
|
32
|
+
subscribe?(listener: () => void): () => void;
|
|
33
|
+
};
|
|
34
|
+
/** `auth` on the server: `auth.api.getSession({ headers })`. */
|
|
35
|
+
export type BetterAuthServerLike<User = BetterAuthUser> = {
|
|
36
|
+
api: {
|
|
37
|
+
getSession(input: {
|
|
38
|
+
headers: Headers;
|
|
39
|
+
}): Promise<BetterAuthSessionData<User> | undefined>;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
export type BetterAuthSessionOptions<User = BetterAuthUser> = {
|
|
43
|
+
/**
|
|
44
|
+
* The person's roles: the admin plugin's `user.role` by default (`"admin,support"` gives two). With the
|
|
45
|
+
* organization plugin, pass the active member's role, which the session doesn't carry.
|
|
46
|
+
*/
|
|
47
|
+
role?: string | readonly string[] | ((data: NonNullable<BetterAuthSessionData<User>>) => string | readonly string[] | undefined);
|
|
48
|
+
/** The access control roles by name (`{ admin, member }` from `ac.newRole`); a role may grant what's asked. */
|
|
49
|
+
roles?: Record<string, BetterAuthRoleLike>;
|
|
50
|
+
/**
|
|
51
|
+
* Checks a role instead of `roles`: `authClient.organization.checkRolePermission` or
|
|
52
|
+
* `authClient.admin.checkRolePermission`, called with `{ role, permissions }`.
|
|
53
|
+
*/
|
|
54
|
+
checkRolePermission?: (input: {
|
|
55
|
+
role: string;
|
|
56
|
+
permissions: BetterAuthPermissions;
|
|
57
|
+
}) => boolean;
|
|
58
|
+
/**
|
|
59
|
+
* What an action asks for. By default `customers.block` asks `{ customers: ["block"] }`, and a resource action
|
|
60
|
+
* (`create` on customers) `{ customers: ["create"] }`; an action with no resource is allowed.
|
|
61
|
+
*/
|
|
62
|
+
permissions?: (action: string, subject?: PermissionSubject) => BetterAuthPermissions | undefined;
|
|
63
|
+
/** The refusal's reason when nobody is signed in; a plain `false` (the dictionary's "not allowed") without it. */
|
|
64
|
+
signedOut?: string;
|
|
65
|
+
/** The refusal's reason when no role grants it, unless the access control gave one. */
|
|
66
|
+
denied?: string;
|
|
67
|
+
token?: () => Promise<string | undefined>;
|
|
68
|
+
};
|
|
69
|
+
/** `customers.block` asks `{ customers: ["block"] }`; `create` on customers asks `{ customers: ["create"] }`. */
|
|
70
|
+
export declare function betterAuthPermissions(action: string, subject?: PermissionSubject): BetterAuthPermissions | undefined;
|
|
71
|
+
/**
|
|
72
|
+
* A session from Better Auth's session data: the `data` of `authClient.useSession()` in a component, or what
|
|
73
|
+
* `auth.api.getSession({ headers })` returns on the server. `can` asks the person's roles (`user.role` by default)
|
|
74
|
+
* through your access control (`roles`) or `checkRolePermission`; the organization is the active one.
|
|
75
|
+
*/
|
|
76
|
+
export declare function betterAuthSession<User = BetterAuthUser>(data: BetterAuthSessionData<User> | undefined, options?: BetterAuthSessionOptions<User>): Session<User>;
|
|
77
|
+
/**
|
|
78
|
+
* A live session over the vanilla client's store (`authClient.useSession` from `better-auth/client`): `user`,
|
|
79
|
+
* `organization` and `can` read the latest data, and `subscribe` follows sign-in, sign-out and organization changes.
|
|
80
|
+
*/
|
|
81
|
+
export declare function betterAuthStoreSession<User = BetterAuthUser>(store: BetterAuthStoreLike<User>, options?: BetterAuthSessionOptions<User>): Session<User>;
|
|
82
|
+
/** The request's session on the server: `auth.api.getSession({ headers })`, as a `Session`. */
|
|
83
|
+
export declare function betterAuthServerSession<User = BetterAuthUser>(auth: BetterAuthServerLike<User>, headers: Headers, options?: BetterAuthSessionOptions<User>): Promise<Session<User>>;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { isFunction, isRecord, isString } from "../core/guards.js";
|
|
2
|
+
const roleSplit = /\s*,\s*/u;
|
|
3
|
+
/** `customers.block` asks `{ customers: ["block"] }`; `create` on customers asks `{ customers: ["create"] }`. */
|
|
4
|
+
export function betterAuthPermissions(action, subject) {
|
|
5
|
+
const dot = action.lastIndexOf(".");
|
|
6
|
+
const resource = dot > 0 ? action.slice(0, dot) : subject?.resource;
|
|
7
|
+
const verb = dot > 0 ? action.slice(dot + 1) : action;
|
|
8
|
+
return resource === undefined || verb === "" ? undefined : { [resource]: [verb] };
|
|
9
|
+
}
|
|
10
|
+
function rolesOf(data, option) {
|
|
11
|
+
const given = isFunction(option) ? option(data) : option;
|
|
12
|
+
const raw = given ?? (isRecord(data.user) && isString(data.user.role) ? data.user.role : undefined);
|
|
13
|
+
const list = raw === undefined ? [] : isString(raw) ? raw.split(roleSplit) : raw;
|
|
14
|
+
return list.filter((role) => role !== "");
|
|
15
|
+
}
|
|
16
|
+
function checkerOf(data, options) {
|
|
17
|
+
return (action, subject) => {
|
|
18
|
+
if (data === undefined || data === null)
|
|
19
|
+
return options.signedOut === undefined ? false : { allowed: false, reason: options.signedOut };
|
|
20
|
+
if (!options.roles && !options.checkRolePermission)
|
|
21
|
+
return true;
|
|
22
|
+
const asked = (options.permissions ?? betterAuthPermissions)(action, subject);
|
|
23
|
+
if (asked === undefined)
|
|
24
|
+
return true;
|
|
25
|
+
let reason;
|
|
26
|
+
for (const role of rolesOf(data, options.role)) {
|
|
27
|
+
if (options.checkRolePermission?.({ role, permissions: asked }) === true)
|
|
28
|
+
return true;
|
|
29
|
+
const answer = options.roles?.[role]?.authorize(asked);
|
|
30
|
+
if (answer?.success === true)
|
|
31
|
+
return true;
|
|
32
|
+
reason ??= answer?.error;
|
|
33
|
+
}
|
|
34
|
+
const why = options.denied ?? reason;
|
|
35
|
+
return why === undefined ? false : { allowed: false, reason: why };
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function organizationOf(data) {
|
|
39
|
+
const id = data?.session.activeOrganizationId;
|
|
40
|
+
return isString(id) ? id : undefined;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A session from Better Auth's session data: the `data` of `authClient.useSession()` in a component, or what
|
|
44
|
+
* `auth.api.getSession({ headers })` returns on the server. `can` asks the person's roles (`user.role` by default)
|
|
45
|
+
* through your access control (`roles`) or `checkRolePermission`; the organization is the active one.
|
|
46
|
+
*/
|
|
47
|
+
export function betterAuthSession(data, options = {}) {
|
|
48
|
+
return {
|
|
49
|
+
user: data?.user ?? null,
|
|
50
|
+
organization: organizationOf(data),
|
|
51
|
+
can: checkerOf(data, options),
|
|
52
|
+
...(options.token ? { token: options.token } : {}),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A live session over the vanilla client's store (`authClient.useSession` from `better-auth/client`): `user`,
|
|
57
|
+
* `organization` and `can` read the latest data, and `subscribe` follows sign-in, sign-out and organization changes.
|
|
58
|
+
*/
|
|
59
|
+
export function betterAuthStoreSession(store, options = {}) {
|
|
60
|
+
const data = () => store.get().data;
|
|
61
|
+
return {
|
|
62
|
+
get user() {
|
|
63
|
+
return data()?.user ?? null;
|
|
64
|
+
},
|
|
65
|
+
get organization() {
|
|
66
|
+
return organizationOf(data());
|
|
67
|
+
},
|
|
68
|
+
can: (action, subject) => checkerOf(data(), options)(action, subject),
|
|
69
|
+
subscribe(listener) {
|
|
70
|
+
if (store.listen)
|
|
71
|
+
return store.listen(listener);
|
|
72
|
+
let first = true;
|
|
73
|
+
return (store.subscribe?.(() => {
|
|
74
|
+
if (first)
|
|
75
|
+
first = false;
|
|
76
|
+
else
|
|
77
|
+
listener();
|
|
78
|
+
}) ?? (() => { }));
|
|
79
|
+
},
|
|
80
|
+
...(options.token ? { token: options.token } : {}),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** The request's session on the server: `auth.api.getSession({ headers })`, as a `Session`. */
|
|
84
|
+
export async function betterAuthServerSession(auth, headers, options = {}) {
|
|
85
|
+
return betterAuthSession(await auth.api.getSession({ headers }), options);
|
|
86
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ResourceAction } from "../core/constants.js";
|
|
2
|
+
import type { Refusal } from "../core/refusal.js";
|
|
3
|
+
export type PermissionSubject = {
|
|
4
|
+
resource: string;
|
|
5
|
+
row?: unknown;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Who is asking and what they may do. It only reads: signing in or out and refreshing tokens stay in the auth
|
|
9
|
+
* library. `can` is the one place permissions live; tables, forms, actions, navigation and agents ask it.
|
|
10
|
+
*/
|
|
11
|
+
export interface Session<User = unknown> {
|
|
12
|
+
user: User | null;
|
|
13
|
+
organization?: string | undefined;
|
|
14
|
+
token?(): Promise<string | undefined>;
|
|
15
|
+
can(action: ResourceAction | string, subject?: PermissionSubject): boolean | Refusal;
|
|
16
|
+
subscribe?(listener: () => void): () => void;
|
|
17
|
+
}
|
|
18
|
+
export type SessionOptions<User> = {
|
|
19
|
+
user: User | null;
|
|
20
|
+
organization?: string;
|
|
21
|
+
token?: () => Promise<string | undefined>;
|
|
22
|
+
/** Allows everything when left out. */
|
|
23
|
+
can?: (action: ResourceAction | string, subject?: PermissionSubject) => boolean | Refusal;
|
|
24
|
+
subscribe?: (listener: () => void) => () => void;
|
|
25
|
+
};
|
|
26
|
+
export declare function createSession<User>(options: SessionOptions<User>): Session<User>;
|
|
27
|
+
export type CaslAbilityLike = {
|
|
28
|
+
can(action: string, subject: unknown, field?: string): boolean;
|
|
29
|
+
relevantRuleFor?(action: string, subject: unknown): {
|
|
30
|
+
reason?: string | undefined;
|
|
31
|
+
} | null | undefined;
|
|
32
|
+
on?(event: string, listener: () => void): () => void;
|
|
33
|
+
};
|
|
34
|
+
export type CaslSessionOptions<User> = {
|
|
35
|
+
user: User | null;
|
|
36
|
+
organization?: string;
|
|
37
|
+
token?: () => Promise<string | undefined>;
|
|
38
|
+
/** Wraps a row as CASL's `subject(type, row)`; by default the row gets a `__caslSubjectType__`. */
|
|
39
|
+
subject?: (resource: string, row: unknown) => unknown;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* A session over a CASL ability: `can(action, { resource, row })` asks `ability.can(action, subject(resource, row))`.
|
|
43
|
+
* A rule's `because(...)` reason becomes the refusal's reason.
|
|
44
|
+
*/
|
|
45
|
+
export declare function fromCasl<User>(ability: CaslAbilityLike, options: CaslSessionOptions<User>): Session<User>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { isObject } from "../core/guards.js";
|
|
2
|
+
const allowAll = () => true;
|
|
3
|
+
export function createSession(options) {
|
|
4
|
+
return {
|
|
5
|
+
user: options.user,
|
|
6
|
+
organization: options.organization,
|
|
7
|
+
can: options.can ?? allowAll,
|
|
8
|
+
...(options.token ? { token: options.token } : {}),
|
|
9
|
+
...(options.subscribe ? { subscribe: options.subscribe } : {}),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
function caslSubject(resource, row) {
|
|
13
|
+
if (row === undefined || row === null)
|
|
14
|
+
return resource;
|
|
15
|
+
return isObject(row) ? { ...row, __caslSubjectType__: resource } : row;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A session over a CASL ability: `can(action, { resource, row })` asks `ability.can(action, subject(resource, row))`.
|
|
19
|
+
* A rule's `because(...)` reason becomes the refusal's reason.
|
|
20
|
+
*/
|
|
21
|
+
export function fromCasl(ability, options) {
|
|
22
|
+
const subjectOf = options.subject ?? caslSubject;
|
|
23
|
+
return {
|
|
24
|
+
user: options.user,
|
|
25
|
+
organization: options.organization,
|
|
26
|
+
...(options.token ? { token: options.token } : {}),
|
|
27
|
+
can(action, subject) {
|
|
28
|
+
const target = subject ? subjectOf(subject.resource, subject.row) : "all";
|
|
29
|
+
if (ability.can(action, target))
|
|
30
|
+
return true;
|
|
31
|
+
const reason = ability.relevantRuleFor?.(action, target)?.reason;
|
|
32
|
+
return reason === undefined ? false : { allowed: false, reason };
|
|
33
|
+
},
|
|
34
|
+
...(ability.on ? { subscribe: (listener) => ability.on?.("updated", listener) ?? (() => { }) } : {}),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { CallContext } from "../core/contracts.js";
|
|
2
|
+
import type { ViewState } from "./view.js";
|
|
3
|
+
export interface PreferencesStore {
|
|
4
|
+
get(key: string): Promise<unknown> | unknown;
|
|
5
|
+
set(key: string, value: unknown): Promise<void> | void;
|
|
6
|
+
}
|
|
7
|
+
type StorageLike = Pick<Storage, "getItem" | "setItem">;
|
|
8
|
+
/**
|
|
9
|
+
* Preferences in this browser's `localStorage`, under `prefix:key`. Reads and writes never throw: a private window
|
|
10
|
+
* or blocked storage reads nothing and forgets the write. Storage is only touched on a read or write, never when the
|
|
11
|
+
* store is made, so a module or a server render can create one.
|
|
12
|
+
*/
|
|
13
|
+
export declare function localPreferences(prefix?: string, storage?: StorageLike): PreferencesStore;
|
|
14
|
+
export declare function memoryPreferences(initial?: Record<string, unknown>): PreferencesStore;
|
|
15
|
+
export declare function remotePreferences(service: {
|
|
16
|
+
get(key: string): Promise<unknown>;
|
|
17
|
+
set(key: string, value: unknown): Promise<void>;
|
|
18
|
+
}): PreferencesStore;
|
|
19
|
+
export type SavedView<F> = {
|
|
20
|
+
id: string;
|
|
21
|
+
label: string;
|
|
22
|
+
resource: string;
|
|
23
|
+
state: Partial<ViewState<F>>;
|
|
24
|
+
shared?: boolean;
|
|
25
|
+
isDefault?: boolean;
|
|
26
|
+
/** Kept in this browser only: no other device or colleague sees it. */
|
|
27
|
+
local?: boolean;
|
|
28
|
+
};
|
|
29
|
+
export interface ViewStore<F> {
|
|
30
|
+
list(resource: string, context: CallContext): Promise<SavedView<F>[]>;
|
|
31
|
+
save(view: SavedView<F>, context: CallContext): Promise<SavedView<F>>;
|
|
32
|
+
remove(id: string, context: CallContext): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
export declare function localViews<F>(store?: PreferencesStore): ViewStore<F>;
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { isRecord, isString } from "../core/guards.js";
|
|
2
|
+
function defaultStorage() {
|
|
3
|
+
try {
|
|
4
|
+
return globalThis.localStorage;
|
|
5
|
+
}
|
|
6
|
+
catch {
|
|
7
|
+
return undefined;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
function parse(raw) {
|
|
11
|
+
if (raw === null)
|
|
12
|
+
return undefined;
|
|
13
|
+
try {
|
|
14
|
+
return JSON.parse(raw);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Preferences in this browser's `localStorage`, under `prefix:key`. Reads and writes never throw: a private window
|
|
22
|
+
* or blocked storage reads nothing and forgets the write. Storage is only touched on a read or write, never when the
|
|
23
|
+
* store is made, so a module or a server render can create one.
|
|
24
|
+
*/
|
|
25
|
+
export function localPreferences(prefix = "app-sdk", storage) {
|
|
26
|
+
const store = () => storage ?? defaultStorage();
|
|
27
|
+
return {
|
|
28
|
+
get(key) {
|
|
29
|
+
try {
|
|
30
|
+
return parse(store()?.getItem(`${prefix}:${key}`) ?? null);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
set(key, value) {
|
|
37
|
+
try {
|
|
38
|
+
store()?.setItem(`${prefix}:${key}`, JSON.stringify(value));
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// Security: storage that refuses a write (quota, a private window) loses a preference, never the screen.
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export function memoryPreferences(initial = {}) {
|
|
47
|
+
const values = new Map(Object.entries(initial));
|
|
48
|
+
return {
|
|
49
|
+
get: (key) => values.get(key),
|
|
50
|
+
set(key, value) {
|
|
51
|
+
values.set(key, value);
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export function remotePreferences(service) {
|
|
56
|
+
return { get: (key) => service.get(key), set: (key, value) => service.set(key, value) };
|
|
57
|
+
}
|
|
58
|
+
function isSavedView(value) {
|
|
59
|
+
return isRecord(value) && isString(value.id) && isString(value.label) && isString(value.resource);
|
|
60
|
+
}
|
|
61
|
+
const viewsKey = (resource) => `views:${resource}`;
|
|
62
|
+
export function localViews(store = localPreferences()) {
|
|
63
|
+
const read = async (resource) => {
|
|
64
|
+
const stored = await store.get(viewsKey(resource));
|
|
65
|
+
return Array.isArray(stored) ? stored.filter(isSavedView).map((view) => ({ ...view, local: true })) : [];
|
|
66
|
+
};
|
|
67
|
+
const owners = new Map();
|
|
68
|
+
return {
|
|
69
|
+
async list(resource) {
|
|
70
|
+
const views = await read(resource);
|
|
71
|
+
for (const view of views)
|
|
72
|
+
owners.set(view.id, resource);
|
|
73
|
+
return views;
|
|
74
|
+
},
|
|
75
|
+
async save(view) {
|
|
76
|
+
const views = await read(view.resource);
|
|
77
|
+
const saved = { ...view, local: true };
|
|
78
|
+
const next = views.some((entry) => entry.id === view.id)
|
|
79
|
+
? views.map((entry) => (entry.id === view.id ? saved : entry))
|
|
80
|
+
: [...views, saved];
|
|
81
|
+
owners.set(view.id, view.resource);
|
|
82
|
+
await store.set(viewsKey(view.resource), next);
|
|
83
|
+
return saved;
|
|
84
|
+
},
|
|
85
|
+
async remove(id) {
|
|
86
|
+
const resource = owners.get(id);
|
|
87
|
+
if (resource === undefined)
|
|
88
|
+
return;
|
|
89
|
+
const views = await read(resource);
|
|
90
|
+
await store.set(viewsKey(resource), views.filter((view) => view.id !== id));
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { ActionTarget } from "../action/action.js";
|
|
2
|
+
import type { SelectionKind, SelectionMode } from "../core/constants.js";
|
|
3
|
+
import type { CallContext, Query, SortSpec, Target } from "../core/contracts.js";
|
|
4
|
+
import type { PreferencesStore, SavedView, ViewStore } from "./preferences.js";
|
|
5
|
+
import type { Allowed } from "../core/refusal.js";
|
|
6
|
+
import type { Resource } from "../resource/resource.js";
|
|
7
|
+
import type { RouterAdapter } from "../navigation/router.js";
|
|
8
|
+
export type ViewState<F> = {
|
|
9
|
+
filter: Partial<F>;
|
|
10
|
+
search: string;
|
|
11
|
+
sort: readonly SortSpec[];
|
|
12
|
+
page: number;
|
|
13
|
+
size: number;
|
|
14
|
+
/** Visible columns, in order; every column that isn't hidden by default when unset. */
|
|
15
|
+
columns?: readonly string[] | undefined;
|
|
16
|
+
scope?: string | undefined;
|
|
17
|
+
/** The saved view or preset applied; it stays when the state moves away from it, which `views.modified()` tells. */
|
|
18
|
+
view?: string | undefined;
|
|
19
|
+
};
|
|
20
|
+
export type ViewScope<F> = {
|
|
21
|
+
id: string;
|
|
22
|
+
label: string;
|
|
23
|
+
filter: Partial<F>;
|
|
24
|
+
count?: boolean;
|
|
25
|
+
};
|
|
26
|
+
export type ViewPreset<F> = {
|
|
27
|
+
id: string;
|
|
28
|
+
label: string;
|
|
29
|
+
state: Partial<ViewState<F>>;
|
|
30
|
+
};
|
|
31
|
+
export type ViewOptions<F> = {
|
|
32
|
+
/** Keeps the state in the URL through the `RouterAdapter`. Default true. */
|
|
33
|
+
url?: boolean;
|
|
34
|
+
urlPrefix?: string;
|
|
35
|
+
scopes?: readonly ViewScope<F>[];
|
|
36
|
+
presets?: readonly ViewPreset<F>[];
|
|
37
|
+
/** Where saved views live. Default: this browser (`localViews`), marked "only in this browser". */
|
|
38
|
+
store?: ViewStore<F>;
|
|
39
|
+
preferences?: PreferencesStore;
|
|
40
|
+
/** Rows per page. Default 25. */
|
|
41
|
+
size?: number;
|
|
42
|
+
selection?: SelectionMode;
|
|
43
|
+
/** A filter that always applies and never shows, like a tenant. */
|
|
44
|
+
baseFilter?: Partial<F>;
|
|
45
|
+
/**
|
|
46
|
+
* The URL's query when the view is created (`?status=blocked&page=2`), so the first state is the URL's, not the
|
|
47
|
+
* default: a server render, the prefetch and the first client render then ask for the same page.
|
|
48
|
+
*/
|
|
49
|
+
search?: string;
|
|
50
|
+
};
|
|
51
|
+
export type Selection = {
|
|
52
|
+
kind: typeof SelectionKind.ids;
|
|
53
|
+
ids: readonly string[];
|
|
54
|
+
} | {
|
|
55
|
+
kind: typeof SelectionKind.query;
|
|
56
|
+
except: readonly string[];
|
|
57
|
+
};
|
|
58
|
+
export type ViewSnapshot<F> = {
|
|
59
|
+
state: ViewState<F>;
|
|
60
|
+
selection: Selection;
|
|
61
|
+
views: readonly SavedView<F>[];
|
|
62
|
+
};
|
|
63
|
+
export type View<T, F, Id = unknown> = {
|
|
64
|
+
readonly resource: Resource<T, Id, F>;
|
|
65
|
+
readonly options: ViewOptions<F>;
|
|
66
|
+
readonly scopes: readonly ViewScope<F>[];
|
|
67
|
+
readonly presets: readonly ViewPreset<F>[];
|
|
68
|
+
readonly selectionMode: SelectionMode;
|
|
69
|
+
readonly local: boolean;
|
|
70
|
+
/** The same object until something changes. */
|
|
71
|
+
getSnapshot(): ViewSnapshot<F>;
|
|
72
|
+
getState(): ViewState<F>;
|
|
73
|
+
subscribe(listener: () => void): () => void;
|
|
74
|
+
/** Changes the state; a new filter, search, sort, size or scope goes back to page 1 and clears a query selection. */
|
|
75
|
+
setState(patch: Partial<ViewState<F>>): void;
|
|
76
|
+
setFilter(key: string, value: unknown): void;
|
|
77
|
+
clearFilters(): void;
|
|
78
|
+
setSearch(text: string): void;
|
|
79
|
+
setSort(sort: readonly SortSpec[]): void;
|
|
80
|
+
setPage(page: number): void;
|
|
81
|
+
setSize(size: number): void;
|
|
82
|
+
setScope(id: string | undefined): void;
|
|
83
|
+
setColumns(columns: readonly string[] | undefined): void;
|
|
84
|
+
filter(): Partial<F>;
|
|
85
|
+
query(): Query<Partial<F>>;
|
|
86
|
+
checkFilter(key: string): Allowed;
|
|
87
|
+
checkPage(page: number, pageCount?: number): Allowed;
|
|
88
|
+
readonly selection: {
|
|
89
|
+
get(): Selection;
|
|
90
|
+
select(ids: readonly string[]): void;
|
|
91
|
+
toggle(id: string, selected?: boolean): void;
|
|
92
|
+
selectAllMatching(): void;
|
|
93
|
+
clear(): void;
|
|
94
|
+
count(total?: number): number | undefined;
|
|
95
|
+
has(id: string): boolean;
|
|
96
|
+
target(): Target<string, Partial<F>>;
|
|
97
|
+
actionTarget(rows: readonly T[]): ActionTarget<T>;
|
|
98
|
+
};
|
|
99
|
+
readonly views: {
|
|
100
|
+
list(): readonly SavedView<F>[];
|
|
101
|
+
/** Reads the store; when the state is still the initial one, applies the default view. */
|
|
102
|
+
load(context: CallContext): Promise<readonly SavedView<F>[]>;
|
|
103
|
+
/** Saves the current state as a new view and applies it. */
|
|
104
|
+
save(label: string, context: CallContext, extra?: Pick<SavedView<F>, "shared" | "isDefault">): Promise<SavedView<F>>;
|
|
105
|
+
apply(id: string): Allowed;
|
|
106
|
+
/** The applied view's id, saved view or preset. */
|
|
107
|
+
current(): string | undefined;
|
|
108
|
+
/** Whether the state moved away from the applied view: another filter, search, sort, scope or columns. */
|
|
109
|
+
modified(): boolean;
|
|
110
|
+
/** A saved view (not a preset) by id, or why there's none to change. */
|
|
111
|
+
checkSaved(id: string): Allowed;
|
|
112
|
+
/** Writes the current state into a saved view. */
|
|
113
|
+
update(id: string, context: CallContext): Promise<SavedView<F>>;
|
|
114
|
+
rename(id: string, label: string, context: CallContext): Promise<SavedView<F>>;
|
|
115
|
+
/** Makes a saved view the one applied on load, or none with `undefined`; only one is the default. */
|
|
116
|
+
setDefault(id: string | undefined, context: CallContext): Promise<void>;
|
|
117
|
+
defaultView(): SavedView<F> | undefined;
|
|
118
|
+
remove(id: string, context: CallContext): Promise<void>;
|
|
119
|
+
};
|
|
120
|
+
/** Follows and writes the URL. Returns the cleanup; call it from an effect. */
|
|
121
|
+
attach(router: RouterAdapter): () => void;
|
|
122
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SortSpec } from "../core/contracts.js";
|
|
2
|
+
export declare function same(a: unknown, b: unknown): boolean;
|
|
3
|
+
export declare function compact<F>(filter: Partial<F>): Partial<F>;
|
|
4
|
+
export declare function encodeSort(sort: readonly SortSpec[]): string;
|
|
5
|
+
export declare function decodeSort(raw: string | null): SortSpec[] | undefined;
|
|
6
|
+
export declare function encodeValue(value: unknown): string[];
|
|
7
|
+
export declare function parseJson(raw: string): unknown;
|