@svadmin/core 0.67.0 → 0.69.3
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/package.json +6 -2
- package/src/adapters/ably.ts +58 -0
- package/src/adapters/cerbos.ts +92 -0
- package/src/adapters/firebase.ts +46 -0
- package/src/adapters/graphql-subscription.ts +45 -0
- package/src/adapters/live-event.ts +21 -0
- package/src/adapters/permit.ts +78 -0
- package/src/audit-hooks.svelte.ts +119 -0
- package/src/contract-form.svelte.ts +96 -6
- package/src/contracts.ts +11 -0
- package/src/crud-operator-schema.ts +20 -0
- package/src/editable-table.svelte.ts +90 -0
- package/src/editable-table.ts +314 -0
- package/src/hooks.svelte.ts +34 -0
- package/src/i18n.svelte.ts +7 -4
- package/src/index.ts +29 -8
- package/src/inferencer-contract.ts +114 -0
- package/src/inferencer.ts +219 -42
- package/src/query-hooks.svelte.ts +16 -6
- package/src/query-options.ts +50 -0
- package/src/query-snapshot.ts +3 -4
- package/src/resource-contract.ts +6 -3
- package/src/resource-schemas.ts +3 -6
- package/src/router-provider.ts +11 -0
- package/src/routing-hooks.svelte.ts +84 -3
- package/src/select-options.ts +35 -1
- package/src/select-query.svelte.ts +20 -5
- package/src/session-query.svelte.ts +6 -1
- package/src/strict-hooks.svelte.ts +9 -5
- package/src/table-hooks.svelte.ts +12 -0
- package/src/task-hooks.svelte.ts +1 -0
- package/src/theme.svelte.ts +8 -6
- package/src/types.ts +22 -7
- package/src/url-sync.ts +37 -17
- package/src/utility-hooks.svelte.ts +68 -5
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@svadmin/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.69.3",
|
|
4
4
|
"author": "zuohuadong",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"@testing-library/dom": "^10.4.1",
|
|
15
15
|
"@testing-library/svelte": "^5.4.2",
|
|
16
16
|
"@testing-library/user-event": "^14.6.6",
|
|
17
|
-
"@types/bun": "^1.4.
|
|
17
|
+
"@types/bun": "^1.4.4",
|
|
18
18
|
"@types/jsdom": "^30.0.0",
|
|
19
19
|
"exceljs": "4.4.0",
|
|
20
20
|
"happy-dom": "^21.0.4",
|
|
@@ -134,6 +134,10 @@
|
|
|
134
134
|
"./admin-tool": {
|
|
135
135
|
"types": "./src/admin-tool.ts",
|
|
136
136
|
"default": "./src/admin-tool.ts"
|
|
137
|
+
},
|
|
138
|
+
"./contracts": {
|
|
139
|
+
"types": "./src/contracts.ts",
|
|
140
|
+
"default": "./src/contracts.ts"
|
|
137
141
|
}
|
|
138
142
|
},
|
|
139
143
|
"bugs": {
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ably LiveProvider adapter.
|
|
3
|
+
*
|
|
4
|
+
* Pass an Ably Realtime client (or a compatible shape) so svadmin does not take
|
|
5
|
+
* a dependency on `ably`. One channel is opened per resource.
|
|
6
|
+
*/
|
|
7
|
+
import type { LiveEvent, LiveProvider } from '../live.svelte';
|
|
8
|
+
import { createLiveSubscribers } from '../live-transport';
|
|
9
|
+
import { liveEventFrom } from './live-event';
|
|
10
|
+
|
|
11
|
+
export interface AblyMessage {
|
|
12
|
+
name?: string;
|
|
13
|
+
data?: unknown;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface AblyChannelLike {
|
|
17
|
+
subscribe(callback: (message: AblyMessage) => void): unknown;
|
|
18
|
+
unsubscribe?(callback: (message: AblyMessage) => void): void;
|
|
19
|
+
publish?(name: string, data: unknown): unknown;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface AblyClientLike {
|
|
23
|
+
channels: { get(name: string): AblyChannelLike };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface AblyAdapterOptions {
|
|
27
|
+
/** Channel name; defaults to the svadmin resource. */
|
|
28
|
+
channel?: (resource: string) => string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createAblyLiveProvider(client: AblyClientLike, options: AblyAdapterOptions = {}): LiveProvider {
|
|
32
|
+
if (typeof client !== 'object' || client === null || typeof client.channels?.get !== 'function') {
|
|
33
|
+
throw new TypeError('Ably adapter requires a client with channels.get()');
|
|
34
|
+
}
|
|
35
|
+
const subscribers = createLiveSubscribers();
|
|
36
|
+
const channelName = options.channel ?? ((resource: string) => resource);
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
subscribe: ({ resource, callback }) => {
|
|
40
|
+
const name = channelName(resource);
|
|
41
|
+
const channel = client.channels.get(name);
|
|
42
|
+
const entry = subscribers.add({ resource, callback });
|
|
43
|
+
const listener = (message: AblyMessage) => {
|
|
44
|
+
const event = liveEventFrom(message.data, resource, message.name);
|
|
45
|
+
if (event) subscribers.notify(event, () => true);
|
|
46
|
+
};
|
|
47
|
+
void channel.subscribe(listener);
|
|
48
|
+
return () => {
|
|
49
|
+
entry.remove();
|
|
50
|
+
channel.unsubscribe?.(listener);
|
|
51
|
+
};
|
|
52
|
+
},
|
|
53
|
+
publish: (event: LiveEvent) => {
|
|
54
|
+
const name = channelName(event.resource);
|
|
55
|
+
void client.channels.get(name).publish?.(event.type, event.payload);
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cerbos PDP adapter for svadmin AccessControlProvider.
|
|
3
|
+
*
|
|
4
|
+
* Uses the Cerbos REST API (`POST /api/check/resources`). Browser checks remain
|
|
5
|
+
* UI hints; the backend must still enforce the same policy.
|
|
6
|
+
*/
|
|
7
|
+
import type { AccessControlProvider, CanParams } from '../permissions.svelte';
|
|
8
|
+
import { definedOptions } from '../defined-options';
|
|
9
|
+
import { accessControlFailure, decodeCanResult, snapshotCanParams } from '../access-control-contract';
|
|
10
|
+
|
|
11
|
+
export interface CerbosPrincipal {
|
|
12
|
+
id: string;
|
|
13
|
+
roles?: string[];
|
|
14
|
+
attributes?: Record<string, unknown>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface CerbosAdapterOptions {
|
|
18
|
+
/** Cerbos PDP origin, for example `https://cerbos.internal:3592`. */
|
|
19
|
+
endpoint: string;
|
|
20
|
+
principal: () => CerbosPrincipal | Promise<CerbosPrincipal>;
|
|
21
|
+
headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
|
|
22
|
+
/** Defaults to the svadmin resource name. */
|
|
23
|
+
resourceKind?: (params: CanParams) => string;
|
|
24
|
+
/** Defaults to `params.params.id` or `*`. */
|
|
25
|
+
resourceId?: (params: CanParams) => string;
|
|
26
|
+
fetch?: typeof fetch;
|
|
27
|
+
providerOptions?: AccessControlProvider['options'];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface CerbosResponse {
|
|
31
|
+
results?: Array<{
|
|
32
|
+
actions?: Record<string, string>;
|
|
33
|
+
isAllowed?: boolean;
|
|
34
|
+
meta?: { effectivePolicies?: unknown };
|
|
35
|
+
}>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function createCerbosAccessControl(options: CerbosAdapterOptions): AccessControlProvider {
|
|
39
|
+
const request = options.fetch ?? globalThis.fetch;
|
|
40
|
+
if (typeof request !== 'function') throw new TypeError('Cerbos adapter requires fetch');
|
|
41
|
+
const endpoint = options.endpoint.replace(/\/+$/, '');
|
|
42
|
+
if (!endpoint) throw new TypeError('Cerbos adapter requires an endpoint');
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
can: async (input) => {
|
|
46
|
+
try {
|
|
47
|
+
const params = snapshotCanParams(input);
|
|
48
|
+
const principal = await options.principal();
|
|
49
|
+
const id = options.resourceId?.(params) ?? String(params.params?.id ?? '*');
|
|
50
|
+
const kind = options.resourceKind?.(params) ?? params.resource;
|
|
51
|
+
const headers: Record<string, string> = {
|
|
52
|
+
'content-type': 'application/json',
|
|
53
|
+
...(typeof options.headers === 'function' ? await options.headers() : options.headers ?? {}),
|
|
54
|
+
};
|
|
55
|
+
const response = await request(`${endpoint}/api/check/resources`, {
|
|
56
|
+
method: 'POST',
|
|
57
|
+
headers,
|
|
58
|
+
body: JSON.stringify({
|
|
59
|
+
requestId: typeof crypto !== 'undefined' && 'randomUUID' in crypto ? crypto.randomUUID() : String(Date.now()),
|
|
60
|
+
principal: {
|
|
61
|
+
id: principal.id,
|
|
62
|
+
...(principal.roles === undefined ? {} : { roles: principal.roles }),
|
|
63
|
+
...(principal.attributes === undefined ? {} : { attr: principal.attributes }),
|
|
64
|
+
},
|
|
65
|
+
resources: [{
|
|
66
|
+
resource: {
|
|
67
|
+
kind,
|
|
68
|
+
id,
|
|
69
|
+
...(params.meta === undefined ? {} : { attr: params.meta }),
|
|
70
|
+
},
|
|
71
|
+
actions: [params.action],
|
|
72
|
+
}],
|
|
73
|
+
}),
|
|
74
|
+
});
|
|
75
|
+
if (!response.ok) throw new Error(`Cerbos responded ${response.status}`);
|
|
76
|
+
const body = await response.json() as CerbosResponse;
|
|
77
|
+
const result = body.results?.[0];
|
|
78
|
+
if (!result) throw new Error('Cerbos returned no result');
|
|
79
|
+
const allowed = result.isAllowed === true || result.actions?.[params.action] === 'EFFECT_ALLOW';
|
|
80
|
+
return decodeCanResult({
|
|
81
|
+
can: allowed,
|
|
82
|
+
...definedOptions({ reason: allowed ? undefined : `Cerbos denied ${params.action} on ${kind}` }),
|
|
83
|
+
});
|
|
84
|
+
} catch (cause) {
|
|
85
|
+
throw accessControlFailure(cause);
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
...definedOptions({ options: options.providerOptions }),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export type CerbosOptions = CerbosAdapterOptions;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Firebase Realtime Database / Firestore LiveProvider adapter.
|
|
3
|
+
*
|
|
4
|
+
* Pass a transport that resolves a path and registers a listener, so svadmin
|
|
5
|
+
* does not depend on the Firebase SDK. Values are expected to look like
|
|
6
|
+
* `{ type: 'created' | 'updated' | 'deleted', payload }`.
|
|
7
|
+
*/
|
|
8
|
+
import type { LiveEvent, LiveProvider } from '../live.svelte';
|
|
9
|
+
import { createLiveSubscribers } from '../live-transport';
|
|
10
|
+
import { liveEventFrom } from './live-event';
|
|
11
|
+
|
|
12
|
+
export interface FirebaseLiveTransport {
|
|
13
|
+
subscribe(path: string, callback: (value: unknown) => void, onError?: (error: unknown) => void): () => void;
|
|
14
|
+
publish?(path: string, value: unknown): unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface FirebaseAdapterOptions {
|
|
18
|
+
/** Database path per resource; defaults to the resource name. */
|
|
19
|
+
path?: (resource: string) => string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createFirebaseLiveProvider(transport: FirebaseLiveTransport, options: FirebaseAdapterOptions = {}): LiveProvider {
|
|
23
|
+
if (typeof transport !== 'object' || transport === null || typeof transport.subscribe !== 'function') {
|
|
24
|
+
throw new TypeError('Firebase adapter requires a subscribe() transport');
|
|
25
|
+
}
|
|
26
|
+
const subscribers = createLiveSubscribers();
|
|
27
|
+
const pathFor = options.path ?? ((resource: string) => resource);
|
|
28
|
+
|
|
29
|
+
return {
|
|
30
|
+
subscribe: ({ resource, callback, liveParams }) => {
|
|
31
|
+
const path = pathFor(resource);
|
|
32
|
+
const entry = subscribers.add({ resource, callback, ...(liveParams === undefined ? {} : { liveParams }) });
|
|
33
|
+
const dispose = transport.subscribe(path, (value) => {
|
|
34
|
+
const event = liveEventFrom(value, resource);
|
|
35
|
+
if (event) subscribers.notify(event, () => true);
|
|
36
|
+
});
|
|
37
|
+
return () => {
|
|
38
|
+
entry.remove();
|
|
39
|
+
dispose();
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
...(typeof transport.publish === 'function' ? {
|
|
43
|
+
publish: (event: LiveEvent) => { void transport.publish?.(pathFor(event.resource), event); },
|
|
44
|
+
} : {}),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GraphQL subscriptions LiveProvider adapter.
|
|
3
|
+
*
|
|
4
|
+
* Pass a `subscribe` function backed by graphql-ws, Apollo, or urql; svadmin
|
|
5
|
+
* keeps the transport seam and validates every delivered event.
|
|
6
|
+
*/
|
|
7
|
+
import type { LiveEvent, LiveProvider } from '../live.svelte';
|
|
8
|
+
import { createLiveSubscribers } from '../live-transport';
|
|
9
|
+
import { liveEventFrom } from './live-event';
|
|
10
|
+
|
|
11
|
+
export interface GraphQLSubscriptionTransport {
|
|
12
|
+
subscribe(
|
|
13
|
+
params: { resource: string; liveParams?: Record<string, unknown> },
|
|
14
|
+
callback: (value: unknown) => void,
|
|
15
|
+
onError?: (error: unknown) => void,
|
|
16
|
+
): () => void;
|
|
17
|
+
publish?(event: LiveEvent): unknown;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createGraphQLSubscriptionLiveProvider(transport: GraphQLSubscriptionTransport): LiveProvider {
|
|
21
|
+
if (typeof transport !== 'object' || transport === null || typeof transport.subscribe !== 'function') {
|
|
22
|
+
throw new TypeError('GraphQL subscriptions adapter requires a subscribe() transport');
|
|
23
|
+
}
|
|
24
|
+
const subscribers = createLiveSubscribers();
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
subscribe: ({ resource, callback, liveParams }) => {
|
|
28
|
+
const entry = subscribers.add({ resource, callback, ...(liveParams === undefined ? {} : { liveParams }) });
|
|
29
|
+
const dispose = transport.subscribe(
|
|
30
|
+
{ resource, ...(liveParams === undefined ? {} : { liveParams }) },
|
|
31
|
+
(value) => {
|
|
32
|
+
const event = liveEventFrom(value, resource);
|
|
33
|
+
if (event) subscribers.notify(event, () => true);
|
|
34
|
+
},
|
|
35
|
+
);
|
|
36
|
+
return () => {
|
|
37
|
+
entry.remove();
|
|
38
|
+
dispose();
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
...(typeof transport.publish === 'function' ? {
|
|
42
|
+
publish: (event: LiveEvent) => { void transport.publish?.(event); },
|
|
43
|
+
} : {}),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { snapshotLiveEvent, type LiveEvent } from '../live-transport';
|
|
2
|
+
|
|
3
|
+
const types: Record<string, LiveEvent['type']> = {
|
|
4
|
+
created: 'INSERT', updated: 'UPDATE', deleted: 'DELETE',
|
|
5
|
+
insert: 'INSERT', update: 'UPDATE', delete: 'DELETE',
|
|
6
|
+
INSERT: 'INSERT', UPDATE: 'UPDATE', DELETE: 'DELETE',
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
10
|
+
return typeof value === 'object' && value !== null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Normalize provider payloads that carry a type name and a payload object. */
|
|
14
|
+
export function liveEventFrom(value: unknown, resource: string, typeHint?: string): LiveEvent | undefined {
|
|
15
|
+
const hinted = typeHint ?? (isRecord(value) && typeof value['type'] === 'string' ? value['type'] : undefined);
|
|
16
|
+
const type = hinted === undefined ? undefined : types[hinted];
|
|
17
|
+
if (!type) return undefined;
|
|
18
|
+
const payload = isRecord(value) && 'payload' in value ? value['payload'] : value;
|
|
19
|
+
const target = isRecord(value) && typeof value['resource'] === 'string' ? value['resource'] : resource;
|
|
20
|
+
return snapshotLiveEvent({ type, resource: target, payload: isRecord(payload) ? payload : {} });
|
|
21
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Permit.io PDP adapter for svadmin AccessControlProvider.
|
|
3
|
+
*
|
|
4
|
+
* Uses Permit's v2 enforcement endpoint. Verify the response contract against
|
|
5
|
+
* your Permit deployment; browser checks are never authorization evidence.
|
|
6
|
+
*/
|
|
7
|
+
import type { AccessControlProvider, CanParams } from '../permissions.svelte';
|
|
8
|
+
import { definedOptions } from '../defined-options';
|
|
9
|
+
import { accessControlFailure, decodeCanResult, snapshotCanParams } from '../access-control-contract';
|
|
10
|
+
|
|
11
|
+
export interface PermitAdapterOptions {
|
|
12
|
+
/** Permit API origin; defaults to `https://api.permit.io`. */
|
|
13
|
+
endpoint?: string;
|
|
14
|
+
token: string;
|
|
15
|
+
/** Permit user key for the signed-in subject. */
|
|
16
|
+
user: (params: CanParams) => string | Promise<string>;
|
|
17
|
+
/** Permit resource type; defaults to the svadmin resource name. */
|
|
18
|
+
resourceType?: (params: CanParams) => string;
|
|
19
|
+
/** Permit resource instance key; defaults to `params.params.id` when present. */
|
|
20
|
+
resourceKey?: (params: CanParams) => string | undefined;
|
|
21
|
+
/** Permit action; defaults to the svadmin action. */
|
|
22
|
+
action?: (params: CanParams) => string;
|
|
23
|
+
context?: (params: CanParams) => Record<string, unknown> | undefined;
|
|
24
|
+
tenant?: string;
|
|
25
|
+
fetch?: typeof fetch;
|
|
26
|
+
providerOptions?: AccessControlProvider['options'];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface PermitResponse {
|
|
30
|
+
allow?: boolean;
|
|
31
|
+
result?: boolean;
|
|
32
|
+
reason?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createPermitAccessControl(options: PermitAdapterOptions): AccessControlProvider {
|
|
36
|
+
const request = options.fetch ?? globalThis.fetch;
|
|
37
|
+
if (typeof request !== 'function') throw new TypeError('Permit adapter requires fetch');
|
|
38
|
+
if (!options.token) throw new TypeError('Permit adapter requires a token');
|
|
39
|
+
const endpoint = (options.endpoint ?? 'https://api.permit.io').replace(/\/+$/, '');
|
|
40
|
+
|
|
41
|
+
return {
|
|
42
|
+
can: async (input) => {
|
|
43
|
+
try {
|
|
44
|
+
const params = snapshotCanParams(input);
|
|
45
|
+
const type = options.resourceType?.(params) ?? params.resource;
|
|
46
|
+
const key = options.resourceKey?.(params) ?? (params.params?.id === undefined ? undefined : String(params.params.id));
|
|
47
|
+
const action = options.action?.(params) ?? params.action;
|
|
48
|
+
const context = options.context?.(params);
|
|
49
|
+
const response = await request(`${endpoint}/api/v2/enforcement/check`, {
|
|
50
|
+
method: 'POST',
|
|
51
|
+
headers: {
|
|
52
|
+
'content-type': 'application/json',
|
|
53
|
+
authorization: `Bearer ${options.token}`,
|
|
54
|
+
},
|
|
55
|
+
body: JSON.stringify({
|
|
56
|
+
user: { key: await options.user(params) },
|
|
57
|
+
action,
|
|
58
|
+
resource: { type, ...(key === undefined ? {} : { key }) },
|
|
59
|
+
...(context === undefined ? {} : { context }),
|
|
60
|
+
...(options.tenant === undefined ? {} : { tenant: options.tenant }),
|
|
61
|
+
}),
|
|
62
|
+
});
|
|
63
|
+
if (!response.ok) throw new Error(`Permit responded ${response.status}`);
|
|
64
|
+
const body = await response.json() as PermitResponse;
|
|
65
|
+
const allowed = body.allow === true || body.result === true;
|
|
66
|
+
return decodeCanResult({
|
|
67
|
+
can: allowed,
|
|
68
|
+
...definedOptions({ reason: body.reason ?? (allowed ? undefined : `Permit denied ${action} on ${type}`) }),
|
|
69
|
+
});
|
|
70
|
+
} catch (cause) {
|
|
71
|
+
throw accessControlFailure(cause);
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
...definedOptions({ options: options.providerOptions }),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export type PermitOptions = PermitAdapterOptions;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { createQuery } from '@tanstack/svelte-query';
|
|
2
|
+
import { captureAdminContext } from './context.svelte';
|
|
3
|
+
import { captureAuthLiveScope } from './auth-hooks.svelte';
|
|
4
|
+
import { auditWithProvider, writeAuditEntry, type AuditDraft, type AuditEntry } from './audit';
|
|
5
|
+
import type { AuditQueryParams } from './audit-contract';
|
|
6
|
+
import { definedOptions } from './defined-options';
|
|
7
|
+
import { HttpError } from './types';
|
|
8
|
+
|
|
9
|
+
export interface UseLogOptions {
|
|
10
|
+
/** 为 false 时不写入 provider,只调用本地 audit handler。 */
|
|
11
|
+
enabled?: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface UseLogMutation {
|
|
15
|
+
log: (params: AuditDraft) => Promise<void>;
|
|
16
|
+
logAsync: (params: AuditDraft) => Promise<void>;
|
|
17
|
+
mutate: (params: AuditDraft, options?: { onSuccess?: () => void; onError?: (error: unknown) => void }) => void;
|
|
18
|
+
mutateAsync: (params: AuditDraft) => Promise<void>;
|
|
19
|
+
readonly isLoading: boolean;
|
|
20
|
+
readonly isError: boolean;
|
|
21
|
+
readonly error: unknown;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 写一条自定义审计记录。
|
|
26
|
+
*
|
|
27
|
+
* 有 `auditLogProvider` 时等待 provider 回执;没有时退化为本地 handler,
|
|
28
|
+
* 与框架内部 mutation 审计保持同一份输入校验。
|
|
29
|
+
*/
|
|
30
|
+
export function useLog(options: UseLogOptions = {}): UseLogMutation {
|
|
31
|
+
const context = captureAdminContext();
|
|
32
|
+
let pending = $state(0);
|
|
33
|
+
let error = $state<unknown>(null);
|
|
34
|
+
|
|
35
|
+
async function log(params: AuditDraft): Promise<void> {
|
|
36
|
+
if (options.enabled === false) return;
|
|
37
|
+
const provider = context.auditLogProvider;
|
|
38
|
+
pending++;
|
|
39
|
+
error = null;
|
|
40
|
+
try {
|
|
41
|
+
if (provider) await writeAuditEntry(params, provider);
|
|
42
|
+
else auditWithProvider(params, null);
|
|
43
|
+
} catch (cause) {
|
|
44
|
+
error = cause;
|
|
45
|
+
throw cause;
|
|
46
|
+
} finally {
|
|
47
|
+
pending--;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
log,
|
|
53
|
+
logAsync: log,
|
|
54
|
+
mutate(params, callbacks) {
|
|
55
|
+
void log(params).then(
|
|
56
|
+
() => callbacks?.onSuccess?.(),
|
|
57
|
+
(cause) => callbacks?.onError?.(cause),
|
|
58
|
+
);
|
|
59
|
+
},
|
|
60
|
+
mutateAsync: log,
|
|
61
|
+
get isLoading() { return pending > 0; },
|
|
62
|
+
get isError() { return error !== null; },
|
|
63
|
+
get error() { return error; },
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface UseLogListOptions {
|
|
68
|
+
resource?: string;
|
|
69
|
+
action?: string;
|
|
70
|
+
meta?: Record<string, unknown>;
|
|
71
|
+
queryOptions?: { enabled?: boolean; staleTime?: number };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface UseLogListResult {
|
|
75
|
+
readonly data: AuditEntry[];
|
|
76
|
+
readonly isLoading: boolean;
|
|
77
|
+
readonly isError: boolean;
|
|
78
|
+
readonly error: unknown;
|
|
79
|
+
refetch: () => Promise<unknown>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 读取审计记录列表。审计是追加写模型;查询结果不缓存跨租户/会话。
|
|
84
|
+
*/
|
|
85
|
+
export function useLogList(options: UseLogListOptions = {}): UseLogListResult {
|
|
86
|
+
const context = captureAdminContext();
|
|
87
|
+
const authScope = captureAuthLiveScope(context.authProvider);
|
|
88
|
+
const tenant = context.tenantCacheKey?.__svadminTenant;
|
|
89
|
+
const enabled = options.queryOptions?.enabled !== false && context.auditLogProvider !== null;
|
|
90
|
+
|
|
91
|
+
const query = createQuery<AuditEntry[], unknown>(() => ({
|
|
92
|
+
queryKey: ['svadmin-audit-log-list', {
|
|
93
|
+
resource: options.resource ?? null,
|
|
94
|
+
action: options.action ?? null,
|
|
95
|
+
meta: options.meta ?? null,
|
|
96
|
+
tenant: tenant ?? null,
|
|
97
|
+
auth: authScope.cacheKey,
|
|
98
|
+
provider: context.auditLogProvider !== null,
|
|
99
|
+
}],
|
|
100
|
+
queryFn: async () => {
|
|
101
|
+
const provider = context.auditLogProvider;
|
|
102
|
+
if (!provider) throw new HttpError('Audit log provider unavailable', 400, undefined, { code: 'AUDIT_PROVIDER_REQUIRED' });
|
|
103
|
+
const params: AuditQueryParams = {
|
|
104
|
+
...definedOptions({ resource: options.resource, action: options.action, meta: options.meta }),
|
|
105
|
+
};
|
|
106
|
+
return provider.get(params);
|
|
107
|
+
},
|
|
108
|
+
enabled,
|
|
109
|
+
staleTime: options.queryOptions?.staleTime ?? 0,
|
|
110
|
+
}));
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
get data() { return query.data ?? []; },
|
|
114
|
+
get isLoading() { return query.isPending && enabled; },
|
|
115
|
+
get isError() { return query.isError; },
|
|
116
|
+
get error() { return query.error; },
|
|
117
|
+
refetch: () => query.refetch(),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -27,6 +27,20 @@ type Redirect = 'list' | 'edit' | 'show' | false;
|
|
|
27
27
|
type Values<S extends ContractSchemas, A extends ContractFormAction> = ContractFormValues<S, A>;
|
|
28
28
|
type Draft<S extends ContractSchemas, A extends ContractFormAction> = ContractFormDraft<S, A>;
|
|
29
29
|
type Field<S extends ContractSchemas, A extends ContractFormAction> = Extract<keyof Values<S, A>, string>;
|
|
30
|
+
export interface AutoSaveOptions {
|
|
31
|
+
enabled: boolean;
|
|
32
|
+
/** 停止输入后的等待时间,默认 1000ms。 */
|
|
33
|
+
debounce?: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type AutoSaveStatus = 'idle' | 'saving' | 'saved' | 'error';
|
|
37
|
+
|
|
38
|
+
export interface AutoSaveState {
|
|
39
|
+
status: AutoSaveStatus;
|
|
40
|
+
data: ContractRecord<ContractSchemas> | null;
|
|
41
|
+
error: HttpError | null;
|
|
42
|
+
}
|
|
43
|
+
|
|
30
44
|
interface FormOptions<S extends ContractSchemas, A extends ContractFormAction> {
|
|
31
45
|
resource: ResourceContract<S>;
|
|
32
46
|
action: A;
|
|
@@ -42,6 +56,8 @@ interface FormOptions<S extends ContractSchemas, A extends ContractFormAction> {
|
|
|
42
56
|
/** 为 false 时不弹默认失败 toast。调用方已有表单内提示时使用。 */
|
|
43
57
|
errorNotification?: NotificationConfig;
|
|
44
58
|
warnWhenUnsavedChanges?: boolean;
|
|
59
|
+
/** 脏字段停止输入后自动保存;保存失败保留在 autoSave.error。 */
|
|
60
|
+
autoSave?: AutoSaveOptions;
|
|
45
61
|
}
|
|
46
62
|
export type ContractFormOptions<S extends ContractSchemas, A extends ContractFormAction> =
|
|
47
63
|
FormOptions<S, A> & ([Values<NoInfer<S>, NoInfer<A>>] extends [never] ? never : unknown) &
|
|
@@ -122,6 +138,11 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
|
|
|
122
138
|
let tainted = $state<Record<string, boolean>>({});
|
|
123
139
|
let error = $state<HttpError | null>(null);
|
|
124
140
|
let submitting = $state(false);
|
|
141
|
+
let autoSaveStatus = $state<AutoSaveStatus>('idle');
|
|
142
|
+
let autoSaveData = $state<ContractRecord<S> | null>(null);
|
|
143
|
+
let autoSaveError = $state<HttpError | null>(null);
|
|
144
|
+
let autoSaveRevision = 0;
|
|
145
|
+
let autoSaveFailedSignature: string | undefined;
|
|
125
146
|
let hydratedKey = $state<string | undefined>();
|
|
126
147
|
let active: { token: object; scope: Scope; promise: Promise<{ data: ContractRecord<S> }>; wasDispatched: () => boolean } | undefined;
|
|
127
148
|
let latest: object | undefined;
|
|
@@ -245,6 +266,10 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
|
|
|
245
266
|
error = null;
|
|
246
267
|
errors = {};
|
|
247
268
|
tainted = {};
|
|
269
|
+
autoSaveRevision++;
|
|
270
|
+
autoSaveStatus = 'idle';
|
|
271
|
+
autoSaveData = null;
|
|
272
|
+
autoSaveError = null;
|
|
248
273
|
hydratedKey = undefined;
|
|
249
274
|
values = snapshotContractFormDraft(options.resource, options.action, options.defaultValues ?? {});
|
|
250
275
|
initial = snapshotContractFormDraft(options.resource, options.action, values);
|
|
@@ -290,12 +315,20 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
|
|
|
290
315
|
if (settings.taint !== false) tainted = { ...tainted, ...Object.fromEntries(changed.map(key => [key, true])) };
|
|
291
316
|
errors = Object.fromEntries(Object.entries(errors).filter(([key]) => !changed.includes(key)));
|
|
292
317
|
error = null;
|
|
318
|
+
if (options.autoSave?.enabled) {
|
|
319
|
+
autoSaveFailedSignature = undefined;
|
|
320
|
+
if (autoSaveStatus !== 'saving') autoSaveStatus = 'idle';
|
|
321
|
+
}
|
|
293
322
|
}
|
|
294
323
|
function reset() {
|
|
295
324
|
draftRevision = {};
|
|
325
|
+
autoSaveRevision++;
|
|
296
326
|
active = undefined;
|
|
297
327
|
latest = undefined;
|
|
298
328
|
submitting = false;
|
|
329
|
+
autoSaveStatus = 'idle';
|
|
330
|
+
autoSaveData = null;
|
|
331
|
+
autoSaveError = null;
|
|
299
332
|
if (!state.ok || !ready()) return;
|
|
300
333
|
values = draft(state.scope, initial);
|
|
301
334
|
tainted = {};
|
|
@@ -363,7 +396,12 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
|
|
|
363
396
|
if (current() && !isTainted()) return context.navigate(path);
|
|
364
397
|
}, undefined);
|
|
365
398
|
}
|
|
366
|
-
function submit(overrides: { redirect?: Redirect } = {}): Promise<{ data: ContractRecord<S> }> {
|
|
399
|
+
function submit(overrides: { redirect?: Redirect } = {}, internal: { autoSave?: boolean } = {}): Promise<{ data: ContractRecord<S> }> {
|
|
400
|
+
const autoSaving = internal.autoSave === true;
|
|
401
|
+
if (autoSaving) {
|
|
402
|
+
autoSaveStatus = 'saving';
|
|
403
|
+
autoSaveError = null;
|
|
404
|
+
}
|
|
367
405
|
function joined(operation: NonNullable<typeof active>) {
|
|
368
406
|
const current = () => isCurrent(operation.scope) && latest === operation.token;
|
|
369
407
|
return operation.promise.then(result => {
|
|
@@ -388,6 +426,13 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
|
|
|
388
426
|
const rejected = failure(cause);
|
|
389
427
|
if (!active) latest = undefined;
|
|
390
428
|
error = rejected;
|
|
429
|
+
if (autoSaving) {
|
|
430
|
+
autoSaveStatus = 'error';
|
|
431
|
+
autoSaveError = rejected;
|
|
432
|
+
autoSaveRevision++;
|
|
433
|
+
}
|
|
434
|
+
if (!autoSaving) notify(() => fireErrorNotification({ config: options.errorNotification, defaultMessage: i18n.t('common.operationFailed'), error: copyFailure(rejected),
|
|
435
|
+
resource: options.resource.name, ...definedOptions({ provider: context.notificationProvider }) }), undefined);
|
|
391
436
|
notify(options.onMutationError, copyFailure(rejected));
|
|
392
437
|
if (origin && !isCurrent(origin)) return Promise.reject(cancelled());
|
|
393
438
|
return Promise.reject(copyFailure(rejected));
|
|
@@ -479,7 +524,11 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
|
|
|
479
524
|
() => targetCurrent(target) && latest === token,
|
|
480
525
|
() => clearAuthQueries(client, target.authProvider), target.authScope,
|
|
481
526
|
() => mounted && latest !== token); }, undefined);
|
|
482
|
-
if (current()
|
|
527
|
+
if (current() && autoSaving) {
|
|
528
|
+
autoSaveStatus = 'error';
|
|
529
|
+
autoSaveError = failed.error;
|
|
530
|
+
}
|
|
531
|
+
if (current() && !autoSaving) notify(() => fireErrorNotification({ config: options.errorNotification, defaultMessage: i18n.t('common.operationFailed'), error: copyFailure(failed.error),
|
|
483
532
|
resource: target.contract.name, ...definedOptions({ provider: target.notificationProvider }) }), undefined);
|
|
484
533
|
if (current()) notify(onError, copyFailure(failed.error));
|
|
485
534
|
throw failed.error;
|
|
@@ -497,10 +546,16 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
|
|
|
497
546
|
values = draft(target, reconciled);
|
|
498
547
|
initial = draft(target, persisted);
|
|
499
548
|
tainted = Object.fromEntries(changed.map(key => [key, true]));
|
|
500
|
-
|
|
501
|
-
|
|
549
|
+
if (autoSaving) {
|
|
550
|
+
autoSaveStatus = 'saved';
|
|
551
|
+
autoSaveData = record;
|
|
552
|
+
autoSaveError = null;
|
|
553
|
+
} else {
|
|
554
|
+
notify(() => fireSuccessNotification({ config: undefined, defaultMessage: i18n.t(target.action === 'edit' ? 'common.updateSuccess' : 'common.createSuccess'),
|
|
555
|
+
resource: target.contract.name, ...definedOptions({ provider: target.notificationProvider }) }), undefined);
|
|
556
|
+
}
|
|
502
557
|
if (current()) notify(onSuccess, { data: parseContractRecord(target.contract, record) });
|
|
503
|
-
if (current()) redirect(target, destination, resultId, current);
|
|
558
|
+
if (current() && !autoSaving) redirect(target, destination, resultId, current);
|
|
504
559
|
if (!current()) throw cancelled(dispatched);
|
|
505
560
|
return { data: parseContractRecord(target.contract, record) };
|
|
506
561
|
}).finally(() => {
|
|
@@ -509,6 +564,34 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
|
|
|
509
564
|
active = { token, scope: target, promise, wasDispatched: () => dispatched };
|
|
510
565
|
return joined(active);
|
|
511
566
|
}
|
|
567
|
+
$effect(() => {
|
|
568
|
+
const config = options.autoSave;
|
|
569
|
+
if (!config?.enabled) return;
|
|
570
|
+
// Track draft, submission and hydration without starting a write before the form is usable.
|
|
571
|
+
void values;
|
|
572
|
+
void tainted;
|
|
573
|
+
void submitting;
|
|
574
|
+
// Auto-save requires an existing record; create forms would keep creating duplicates.
|
|
575
|
+
if (!state.ok || !ready() || submitting || !isTainted() || state.scope.action !== 'edit') return;
|
|
576
|
+
const signature = JSON.stringify([values, tainted]);
|
|
577
|
+
if (autoSaveFailedSignature === signature) return;
|
|
578
|
+
const delay = config.debounce ?? 1000;
|
|
579
|
+
if (!Number.isFinite(delay) || delay < 0) return;
|
|
580
|
+
const revision = ++autoSaveRevision;
|
|
581
|
+
const timer = setTimeout(() => {
|
|
582
|
+
if (revision !== autoSaveRevision || autoSaveFailedSignature === signature ||
|
|
583
|
+
!state.ok || !ready() || submitting || !isTainted()) return;
|
|
584
|
+
void submit({ redirect: false }, { autoSave: true }).catch(() => { autoSaveFailedSignature = signature; });
|
|
585
|
+
}, delay);
|
|
586
|
+
return () => clearTimeout(timer);
|
|
587
|
+
});
|
|
588
|
+
function triggerAutoSave(): void {
|
|
589
|
+
if (!options.autoSave?.enabled || !state.ok || !ready() || submitting || !isTainted() || state.scope.action !== 'edit') return;
|
|
590
|
+
const signature = JSON.stringify([values, tainted]);
|
|
591
|
+
autoSaveFailedSignature = undefined;
|
|
592
|
+
autoSaveRevision++;
|
|
593
|
+
void submit({ redirect: false }, { autoSave: true }).catch(() => { autoSaveFailedSignature = signature; });
|
|
594
|
+
}
|
|
512
595
|
$effect(() => {
|
|
513
596
|
if (!(options.warnWhenUnsavedChanges ?? adminOptions.warnWhenUnsavedChanges) || !isTainted() || !enabled() || typeof window === 'undefined') return;
|
|
514
597
|
const scope = state.ok ? state.scope : undefined;
|
|
@@ -524,7 +607,14 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
|
|
|
524
607
|
return state.ok && isCurrent(state.scope) && hydratedKey === state.scope.key
|
|
525
608
|
? draft(state.scope, values) : snapshotContractFormDraft(options.resource, options.action, {});
|
|
526
609
|
},
|
|
527
|
-
setValues, setFieldValue, reset, submit, validateFields,
|
|
610
|
+
setValues, setFieldValue, reset, submit, validateFields, triggerAutoSave,
|
|
611
|
+
get autoSave(): AutoSaveState {
|
|
612
|
+
return {
|
|
613
|
+
status: options.autoSave?.enabled ? autoSaveStatus : 'idle',
|
|
614
|
+
data: autoSaveStatus === 'saved' ? (autoSaveData as ContractRecord<ContractSchemas> | null) : null,
|
|
615
|
+
error: autoSaveStatus === 'error' && autoSaveError ? copyFailure(autoSaveError) : null,
|
|
616
|
+
};
|
|
617
|
+
},
|
|
528
618
|
get errors(): Readonly<Record<string, string>> { return ready() ? { ...errors } : {}; },
|
|
529
619
|
setFieldError(field: Field<S, A> | '_root', message: string) {
|
|
530
620
|
if (!ready()) return;
|