@svadmin/core 0.62.0 → 0.65.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/package.json +2 -2
- package/src/command-contract.ts +96 -10
- package/src/context.svelte.ts +4 -2
- package/src/contract-form.svelte.ts +6 -1
- package/src/create-hooks.svelte.ts +3 -0
- package/src/dashboard-contract.ts +38 -1
- package/src/delete-many-hooks.svelte.ts +3 -0
- package/src/hook-utils.svelte.ts +1 -2
- package/src/i18n.svelte.ts +136 -0
- package/src/import-contract.ts +17 -0
- package/src/index.ts +6 -4
- package/src/query-session.svelte.ts +19 -2
- package/src/select-query.svelte.ts +122 -12
- package/src/strict-command-hooks.svelte.ts +28 -16
- package/src/types.ts +1 -0
- package/src/update-many-hooks.svelte.ts +3 -0
- package/src/useCan.ts +3 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@svadmin/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.65.0",
|
|
4
4
|
"author": "zuohuadong",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"@types/bun": "^1.4.2",
|
|
18
18
|
"@types/jsdom": "^30.0.0",
|
|
19
19
|
"exceljs": "4.4.0",
|
|
20
|
-
"happy-dom": "^
|
|
20
|
+
"happy-dom": "^21.0.4",
|
|
21
21
|
"jsdom": "^30.0.1",
|
|
22
22
|
"vitest": "^4.1.11"
|
|
23
23
|
},
|
package/src/command-contract.ts
CHANGED
|
@@ -11,12 +11,24 @@ export interface CommandContract<I extends TObject = TObject, O extends TSchema
|
|
|
11
11
|
}
|
|
12
12
|
export type CommandInput<I extends TObject> = SchemaValue<I> extends infer Input extends Record<string, unknown> ? Input : Record<string, unknown>;
|
|
13
13
|
export type CommandOutput<O extends TSchema> = SchemaValue<O>;
|
|
14
|
+
/** The only provider diagnostic fields that may cross the command boundary. */
|
|
15
|
+
export interface CommandErrorDiagnostic {
|
|
16
|
+
readonly code: string;
|
|
17
|
+
readonly message: string;
|
|
18
|
+
}
|
|
19
|
+
/** A fixed business error code to UI message mapping declared at registration. */
|
|
20
|
+
export type CommandErrorDiagnostics = Readonly<Record<string, string>>;
|
|
21
|
+
/** Command diagnostics are declarative, static and limited to safe business codes. */
|
|
22
|
+
export interface CommandDiagnostics {
|
|
23
|
+
readonly safe: CommandErrorDiagnostics;
|
|
24
|
+
}
|
|
14
25
|
interface Definition {
|
|
15
26
|
key: string;
|
|
16
27
|
url: string;
|
|
17
28
|
method: 'get' | 'post' | 'put' | 'patch' | 'delete';
|
|
18
29
|
input: TSchema;
|
|
19
30
|
response: TSchema;
|
|
31
|
+
diagnostics: CommandErrorDiagnostics | undefined;
|
|
20
32
|
}
|
|
21
33
|
const definitions = new WeakMap<CommandContract, Definition>();
|
|
22
34
|
let nextKey = 0;
|
|
@@ -25,6 +37,70 @@ function invalidContract(): never {
|
|
|
25
37
|
throw new HttpError('Invalid command contract', 400, undefined, { code: 'INVALID_COMMAND_CONTRACT' });
|
|
26
38
|
}
|
|
27
39
|
|
|
40
|
+
const diagnosticCode = /^[A-Z][A-Z0-9_]{1,63}$/;
|
|
41
|
+
|
|
42
|
+
/** 诊断文案长度 1–200,且拒绝 C0 控制符与 DEL。按码元判断,避免 no-control-regex。 */
|
|
43
|
+
function safeDiagnosticMessage(message: string): boolean {
|
|
44
|
+
if (message.length < 1 || message.length > 200) return false;
|
|
45
|
+
for (let index = 0; index < message.length; index += 1) {
|
|
46
|
+
const code = message.charCodeAt(index);
|
|
47
|
+
if (code <= 0x1f || code === 0x7f) return false;
|
|
48
|
+
}
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function ownData(target: object, key: string): unknown {
|
|
53
|
+
try {
|
|
54
|
+
const descriptor = Object.getOwnPropertyDescriptor(target, key);
|
|
55
|
+
return descriptor && 'value' in descriptor ? descriptor.value : undefined;
|
|
56
|
+
} catch {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function diagnosticMapping(value: unknown): CommandErrorDiagnostics {
|
|
62
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return invalidContract();
|
|
63
|
+
const proto = Object.getPrototypeOf(value);
|
|
64
|
+
if (proto !== Object.prototype && proto !== null) return invalidContract();
|
|
65
|
+
if (Object.getOwnPropertySymbols(value).length) return invalidContract();
|
|
66
|
+
const entries: [string, string][] = [];
|
|
67
|
+
for (const [code, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
|
|
68
|
+
const message: unknown = 'value' in descriptor ? descriptor.value : undefined;
|
|
69
|
+
if (!descriptor.enumerable || !('value' in descriptor) || !diagnosticCode.test(code) ||
|
|
70
|
+
typeof message !== 'string' || !safeDiagnosticMessage(message) || message !== message.trim()) {
|
|
71
|
+
return invalidContract();
|
|
72
|
+
}
|
|
73
|
+
entries.push([code, message]);
|
|
74
|
+
}
|
|
75
|
+
if (!entries.length) return invalidContract();
|
|
76
|
+
entries.sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
|
|
77
|
+
return Object.freeze(Object.fromEntries(entries));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function parseDiagnostics(value: unknown): CommandErrorDiagnostics | undefined {
|
|
81
|
+
if (value === undefined) return undefined;
|
|
82
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return invalidContract();
|
|
83
|
+
const proto = Object.getPrototypeOf(value);
|
|
84
|
+
if (proto !== Object.prototype && proto !== null) return invalidContract();
|
|
85
|
+
const keys = Reflect.ownKeys(value);
|
|
86
|
+
if (keys.length !== 1 || keys[0] !== 'safe') return invalidContract();
|
|
87
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, 'safe');
|
|
88
|
+
if (!descriptor || !descriptor.enumerable || !('value' in descriptor)) return invalidContract();
|
|
89
|
+
return diagnosticMapping(descriptor.value);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Read only a provider-owned code and resolve it against the declared static mapping. */
|
|
93
|
+
export function safeCommandDiagnostic(
|
|
94
|
+
cause: unknown,
|
|
95
|
+
diagnostics: CommandErrorDiagnostics | undefined,
|
|
96
|
+
): CommandErrorDiagnostic | undefined {
|
|
97
|
+
if (!diagnostics || typeof cause !== 'object' || cause === null) return undefined;
|
|
98
|
+
const code = ownData(cause, 'code');
|
|
99
|
+
if (typeof code !== 'string' || !Object.hasOwn(diagnostics, code)) return undefined;
|
|
100
|
+
const message = diagnostics[code];
|
|
101
|
+
return typeof message === 'string' ? Object.freeze({ code, message }) : undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
28
104
|
function matches(schema: TSchema, value: unknown): boolean {
|
|
29
105
|
return checkExact(schema, value);
|
|
30
106
|
}
|
|
@@ -56,7 +132,8 @@ function responseSnapshot(definition: Definition, response: unknown): { data: un
|
|
|
56
132
|
});
|
|
57
133
|
}
|
|
58
134
|
|
|
59
|
-
function executionError(error: unknown, writeMayHaveSucceeded: boolean
|
|
135
|
+
function executionError(error: unknown, writeMayHaveSucceeded: boolean,
|
|
136
|
+
diagnostics: CommandErrorDiagnostics | undefined): HttpError {
|
|
60
137
|
let status = 502;
|
|
61
138
|
try {
|
|
62
139
|
if (typeof error === 'object' && error !== null) {
|
|
@@ -68,8 +145,9 @@ function executionError(error: unknown, writeMayHaveSucceeded: boolean): HttpErr
|
|
|
68
145
|
} catch {
|
|
69
146
|
// Error reflection failures are not authentication instructions.
|
|
70
147
|
}
|
|
71
|
-
|
|
72
|
-
|
|
148
|
+
const diagnostic = safeCommandDiagnostic(error, diagnostics);
|
|
149
|
+
return new HttpError(diagnostic?.message ?? 'Command execution failed', status, undefined, {
|
|
150
|
+
code: diagnostic?.code ?? 'COMMAND_FAILED', details: { writeMayHaveSucceeded },
|
|
73
151
|
});
|
|
74
152
|
}
|
|
75
153
|
|
|
@@ -80,10 +158,12 @@ export function defineCommand<I extends TObject, O extends TSchema>(
|
|
|
80
158
|
method: Definition['method'];
|
|
81
159
|
input: I & SafeSchema<I>;
|
|
82
160
|
output: O & SafeSchema<O>;
|
|
161
|
+
diagnostics?: CommandDiagnostics;
|
|
83
162
|
},
|
|
84
163
|
): CommandContract<I, O>;
|
|
85
164
|
export function defineCommand(name: string, definition: {
|
|
86
165
|
url: string; method: Definition['method']; input: TObject; output: TSchema;
|
|
166
|
+
diagnostics?: CommandDiagnostics;
|
|
87
167
|
}): CommandContract {
|
|
88
168
|
try {
|
|
89
169
|
if (typeof name !== 'string' || !name.trim() || typeof definition !== 'object' || definition === null) {
|
|
@@ -98,6 +178,9 @@ export function defineCommand(name: string, definition: {
|
|
|
98
178
|
const method: unknown = fields['method']?.value;
|
|
99
179
|
const inputSchema: unknown = fields['input']?.value;
|
|
100
180
|
const outputSchema: unknown = fields['output']?.value;
|
|
181
|
+
const diagnosticsField = fields['diagnostics'];
|
|
182
|
+
if (diagnosticsField && !('value' in diagnosticsField)) return invalidContract();
|
|
183
|
+
const diagnostics = parseDiagnostics(diagnosticsField?.value);
|
|
101
184
|
if (typeof url !== 'string' || !url.trim() ||
|
|
102
185
|
(method !== 'get' && method !== 'post' && method !== 'put' && method !== 'patch' && method !== 'delete') ||
|
|
103
186
|
!Type.IsObject(inputSchema) || !Type.IsSchema(outputSchema)) {
|
|
@@ -109,8 +192,9 @@ export function defineCommand(name: string, definition: {
|
|
|
109
192
|
name, [brand]: Object.freeze({ input: inputSchema, output: outputSchema }),
|
|
110
193
|
});
|
|
111
194
|
definitions.set(contract, {
|
|
112
|
-
key: JSON.stringify([++nextKey, name, url, method, input, response
|
|
113
|
-
|
|
195
|
+
key: JSON.stringify([++nextKey, name, url, method, input, response,
|
|
196
|
+
diagnostics ? Object.entries(diagnostics) : null]),
|
|
197
|
+
url, method, input, response, diagnostics,
|
|
114
198
|
});
|
|
115
199
|
return contract;
|
|
116
200
|
} catch {
|
|
@@ -124,9 +208,11 @@ function definitionOf(command: CommandContract): Definition {
|
|
|
124
208
|
return definition;
|
|
125
209
|
}
|
|
126
210
|
|
|
127
|
-
export function commandDefinition(
|
|
128
|
-
|
|
129
|
-
|
|
211
|
+
export function commandDefinition(
|
|
212
|
+
command: CommandContract,
|
|
213
|
+
): Readonly<Pick<Definition, 'key' | 'url' | 'method' | 'diagnostics'>> {
|
|
214
|
+
const { key, url, method, diagnostics } = definitionOf(command);
|
|
215
|
+
return Object.freeze({ key, url, method, diagnostics });
|
|
130
216
|
}
|
|
131
217
|
|
|
132
218
|
export function parseCommandInput<I extends TObject, O extends TSchema>(
|
|
@@ -160,7 +246,7 @@ export function prepareCommand(
|
|
|
160
246
|
try {
|
|
161
247
|
custom = provider.custom;
|
|
162
248
|
} catch (error) {
|
|
163
|
-
throw executionError(error, false);
|
|
249
|
+
throw executionError(error, false, definition.diagnostics);
|
|
164
250
|
}
|
|
165
251
|
if (typeof custom !== 'function') {
|
|
166
252
|
throw new HttpError('Provider does not support commands', 400, undefined, { code: 'COMMAND_NOT_SUPPORTED' });
|
|
@@ -178,7 +264,7 @@ export function prepareCommand(
|
|
|
178
264
|
}]);
|
|
179
265
|
response = await pending;
|
|
180
266
|
} catch (error) {
|
|
181
|
-
throw executionError(error, definition.method !== 'get');
|
|
267
|
+
throw executionError(error, definition.method !== 'get', definition.diagnostics);
|
|
182
268
|
}
|
|
183
269
|
return responseSnapshot(definition, response);
|
|
184
270
|
},
|
package/src/context.svelte.ts
CHANGED
|
@@ -55,10 +55,12 @@ import { resetSidebarCollapsed } from './hooks.svelte';
|
|
|
55
55
|
|
|
56
56
|
export type { DataProviderInput } from './provider-bundle';
|
|
57
57
|
|
|
58
|
-
interface AdminContextSourceBase extends Omit<Partial<ProviderBundle>,'dataProvider'> {
|
|
58
|
+
interface AdminContextSourceBase extends Omit<Partial<ProviderBundle>,'dataProvider'|'taskProvider'> {
|
|
59
59
|
readonly resources: ResourceDefinition[];
|
|
60
60
|
/** Tenant for the request tree; inherits the nearest provideTenantContext when omitted. */
|
|
61
|
-
readonly tenant?: TenantContext;
|
|
61
|
+
readonly tenant?: TenantContext | undefined;
|
|
62
|
+
/** Explicit undefined keeps reactive getters assignable under exactOptionalPropertyTypes. */
|
|
63
|
+
readonly taskProvider?: TaskProvider | undefined;
|
|
62
64
|
}
|
|
63
65
|
|
|
64
66
|
/** Requires either the legacy dataProvider or a first-class ProviderBundle; matching top-level fields take precedence. */
|
|
@@ -166,6 +166,11 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
|
|
|
166
166
|
function isCurrent(scope: Scope): boolean {
|
|
167
167
|
return targetCurrent(scope) && sessionCurrent(scope);
|
|
168
168
|
}
|
|
169
|
+
function readCurrent(scope: Scope): boolean {
|
|
170
|
+
return enabled() && state.ok && state.scope.targetKey === scope.targetKey &&
|
|
171
|
+
context.authProvider === scope.authProvider && context.routerProvider === scope.router &&
|
|
172
|
+
sessionCurrent(scope);
|
|
173
|
+
}
|
|
169
174
|
function ready(): boolean {
|
|
170
175
|
return state.ok && isCurrent(state.scope) && hydratedKey === state.scope.key;
|
|
171
176
|
}
|
|
@@ -201,7 +206,7 @@ export function useContractForm<S extends ContractSchemas, A extends ContractFor
|
|
|
201
206
|
const response = await scope.provider.getOne(snapshotOneParams({
|
|
202
207
|
resource: scope.contract.name, id: scope.id, ...definedOptions({ meta: scope.meta }),
|
|
203
208
|
}));
|
|
204
|
-
if (!
|
|
209
|
+
if (!readCurrent(scope)) throw cancelled();
|
|
205
210
|
const result = decodeOneResult(snapshotPlainData(response), value => parseContractRecord(scope.contract, value));
|
|
206
211
|
if (result.data.id !== scope.id) return rejectProviderResponse();
|
|
207
212
|
return result;
|
|
@@ -23,6 +23,8 @@ export interface ContractCreateOptions<S extends ContractSchemas> {
|
|
|
23
23
|
resource: ResourceContract<S>;
|
|
24
24
|
enabled?: boolean;
|
|
25
25
|
overtimeOptions?: OvertimeOptions;
|
|
26
|
+
successNotification?: false;
|
|
27
|
+
errorNotification?: false;
|
|
26
28
|
}
|
|
27
29
|
type Result<S extends ContractSchemas> = { data: ContractRecord<S> };
|
|
28
30
|
export interface Callbacks<S extends ContractSchemas> {
|
|
@@ -145,6 +147,7 @@ export function useContractCreate<S extends ContractSchemas>(options: ContractCr
|
|
|
145
147
|
function notify(scope: Scope, current: () => boolean, type: 'success' | 'error', message: string): void {
|
|
146
148
|
observe(() => {
|
|
147
149
|
if (!current()) return;
|
|
150
|
+
if (type === 'success' ? options.successNotification === false : options.errorNotification === false) return;
|
|
148
151
|
if (scope.notification) return scope.notification.open({ type, message });
|
|
149
152
|
if (type === 'success') toast.success(message);
|
|
150
153
|
else toast.error(message);
|
|
@@ -5,6 +5,26 @@ import type { EnterpriseProviderRequestContext } from './enterprise';
|
|
|
5
5
|
|
|
6
6
|
const id = Type.String({ minLength: 1, maxLength: 200, pattern: '^\\S(?:[\\s\\S]*\\S)?$' });
|
|
7
7
|
const scalar = Type.Union([Type.String(), Type.Number(), Type.Boolean(), Type.Null()]);
|
|
8
|
+
const instant = Type.String({ pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$' });
|
|
9
|
+
const instantPattern = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/;
|
|
10
|
+
function instantTimestamp(value: string): number | undefined {
|
|
11
|
+
const match = instantPattern.exec(value);
|
|
12
|
+
if (!match) return undefined;
|
|
13
|
+
const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number) as [number, number, number, number, number, number];
|
|
14
|
+
if (month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 59) return undefined;
|
|
15
|
+
const milliseconds = Number((match[7] ?? '0').padEnd(3, '0'));
|
|
16
|
+
const date = new Date(0);
|
|
17
|
+
date.setUTCFullYear(year, month - 1, day);
|
|
18
|
+
date.setUTCHours(hour, minute, second, milliseconds);
|
|
19
|
+
if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day
|
|
20
|
+
|| date.getUTCHours() !== hour || date.getUTCMinutes() !== minute || date.getUTCSeconds() !== second
|
|
21
|
+
|| date.getUTCMilliseconds() !== milliseconds) return undefined;
|
|
22
|
+
return date.getTime();
|
|
23
|
+
}
|
|
24
|
+
const timeRange = Type.Object({
|
|
25
|
+
from: instant,
|
|
26
|
+
to: instant,
|
|
27
|
+
}, { additionalProperties: false });
|
|
8
28
|
const metric = Type.Object({
|
|
9
29
|
id,
|
|
10
30
|
label: Type.String({ minLength: 1, maxLength: 200 }),
|
|
@@ -32,13 +52,23 @@ const query = Type.Object({
|
|
|
32
52
|
field: id,
|
|
33
53
|
value: scalar,
|
|
34
54
|
}, { additionalProperties: false }), { maxItems: 50 })),
|
|
55
|
+
timeRange: Type.Optional(timeRange),
|
|
35
56
|
}, { additionalProperties: false });
|
|
36
57
|
|
|
37
58
|
export type DashboardMetric = Static<typeof metric>;
|
|
38
59
|
export type DashboardWidget = Static<typeof widget>;
|
|
60
|
+
export type DashboardTimeRange = Static<typeof timeRange>;
|
|
39
61
|
export type DashboardSnapshot = Static<typeof snapshot>;
|
|
40
62
|
export type DashboardQuery = Static<typeof query>;
|
|
41
63
|
|
|
64
|
+
export interface DashboardDrilldown {
|
|
65
|
+
dashboardId: string;
|
|
66
|
+
widget: Pick<DashboardWidget, 'id' | 'title' | 'kind'>;
|
|
67
|
+
metric?: DashboardMetric;
|
|
68
|
+
filters: NonNullable<DashboardQuery['filters']>;
|
|
69
|
+
timeRange?: DashboardTimeRange;
|
|
70
|
+
}
|
|
71
|
+
|
|
42
72
|
export interface DashboardProvider {
|
|
43
73
|
get(context: EnterpriseProviderRequestContext, query: DashboardQuery): Promise<unknown>;
|
|
44
74
|
}
|
|
@@ -66,7 +96,14 @@ export function decodeDashboardSnapshot(value: unknown): DashboardSnapshot {
|
|
|
66
96
|
export function decodeDashboardQuery(value: unknown): DashboardQuery {
|
|
67
97
|
try {
|
|
68
98
|
const result = snapshotPlainData(value);
|
|
69
|
-
if (checkExact(query, result))
|
|
99
|
+
if (checkExact(query, result)) {
|
|
100
|
+
if (result.timeRange) {
|
|
101
|
+
const from = instantTimestamp(result.timeRange.from);
|
|
102
|
+
const to = instantTimestamp(result.timeRange.to);
|
|
103
|
+
if (from === undefined || to === undefined || from > to) throw new DashboardContractError();
|
|
104
|
+
}
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
70
107
|
} catch { /* Query payloads fail closed. */ }
|
|
71
108
|
throw new DashboardContractError();
|
|
72
109
|
}
|
|
@@ -22,6 +22,8 @@ export interface ContractDeleteManyOptions<S extends ContractSchemas> {
|
|
|
22
22
|
resource: ResourceContract<S>;
|
|
23
23
|
enabled?: boolean;
|
|
24
24
|
overtimeOptions?: OvertimeOptions;
|
|
25
|
+
successNotification?: false;
|
|
26
|
+
errorNotification?: false;
|
|
25
27
|
}
|
|
26
28
|
export type { ContractDeleteManyParams } from './delete-many-contract';
|
|
27
29
|
type Result<S extends ContractSchemas> = { data: ContractRecord<S>[] };
|
|
@@ -110,6 +112,7 @@ export function useContractDeleteMany<S extends ContractSchemas>(options: Contra
|
|
|
110
112
|
function notify(scope: Scope, current: () => boolean, type: 'success' | 'error', message: string): void {
|
|
111
113
|
observe(() => {
|
|
112
114
|
if (!current()) return;
|
|
115
|
+
if (type === 'success' ? options.successNotification === false : options.errorNotification === false) return;
|
|
113
116
|
if (scope.notification) return scope.notification.open({ type, message });
|
|
114
117
|
if (type === 'success') toast.success(message);
|
|
115
118
|
else toast.error(message);
|
package/src/hook-utils.svelte.ts
CHANGED
|
@@ -132,6 +132,5 @@ export function fireErrorNotification(request: ErrorNotificationRequest): void {
|
|
|
132
132
|
},provider);
|
|
133
133
|
return;
|
|
134
134
|
}
|
|
135
|
-
|
|
136
|
-
notifyWithProvider({ type: 'error',message: config||`${defaultMessage}${errMsg? ': '+errMsg:''}` },provider);
|
|
135
|
+
notifyWithProvider({ type: 'error',message: config||defaultMessage },provider);
|
|
137
136
|
}
|
package/src/i18n.svelte.ts
CHANGED
|
@@ -9,6 +9,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
9
9
|
'dashboard.empty': '暂无仪表盘数据',
|
|
10
10
|
'dashboard.load': '无法加载仪表盘数据。',
|
|
11
11
|
'dashboard.invalid': '仪表盘数据无效。',
|
|
12
|
+
'dashboard.drilldown': '查看详情',
|
|
12
13
|
'approval.title': '审批中心',
|
|
13
14
|
'approval.pending': '待办',
|
|
14
15
|
'approval.history': '审批历史',
|
|
@@ -41,6 +42,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
41
42
|
'tree.toggleChildren': '展开或折叠子节点',
|
|
42
43
|
'tree.loadFailed': '子节点加载失败',
|
|
43
44
|
'tree.selectionFailed': '无法完成整组选择,请重试或缩小选择范围',
|
|
45
|
+
'tree.childrenUnavailable': '暂无法展开该节点,请稍后再试或联系管理员',
|
|
44
46
|
'tree.removeSelection': '移除 {label}',
|
|
45
47
|
'virtualTable.label': '数据表格',
|
|
46
48
|
'virtualTable.invalidKeys': '记录标识无效或重复,请检查数据。',
|
|
@@ -62,12 +64,19 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
62
64
|
'pivot.overflow': '聚合结果超出数值范围,请调整统计单位或使用服务端精确计算。',
|
|
63
65
|
'gantt.title': '项目甘特图',
|
|
64
66
|
'import.limit': '导入文件或记录数量超过限制。',
|
|
67
|
+
'import.fileReadFailed': '无法读取或解析导入文件,请检查文件格式后重试。',
|
|
65
68
|
'import.invalidRow': '第 {row} 条记录不符合资源创建规则,请检查字段映射和原始数据。',
|
|
66
69
|
'import.invalidLimits': '导入容量配置无效。',
|
|
67
70
|
'import.taskConfiguration': '服务端导入需要任务 Provider、任务名称和幂等键。',
|
|
68
71
|
'import.taskPayloadLimit': '导入任务载荷超过配置的字节限制。',
|
|
69
72
|
'import.taskUnconfirmed': '任务提交结果未确认。请先查询任务中心,重试时必须使用相同的幂等键和载荷。',
|
|
70
73
|
'import.retryFailedRows': '重试可恢复失败行',
|
|
74
|
+
'import.preview': '试运行预览',
|
|
75
|
+
'import.previewSummary': '本地校验通过 {importable} 条,失败 {failed} 条,共 {total} 条。',
|
|
76
|
+
'import.previewHint': '仅执行客户端解析、映射和创建规则校验,不保证服务端导入成功,且没有写入任何记录。',
|
|
77
|
+
'import.previewFailed': '本地校验失败行',
|
|
78
|
+
'import.previewFailedRow': '第 {row} 条:{error}',
|
|
79
|
+
'import.backToImport': '返回导入',
|
|
71
80
|
'dateInput.presets': '快捷范围',
|
|
72
81
|
'dateInput.to': '至',
|
|
73
82
|
'dateInput.unavailable': '该日期或时间不可选。',
|
|
@@ -111,6 +120,19 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
111
120
|
'upload.cleanupPending': '正在回收临时文件',
|
|
112
121
|
'upload.cleanupFailed': '临时文件回收失败',
|
|
113
122
|
'upload.rejectedFiles': '被拒绝的文件',
|
|
123
|
+
'upload.selectedFiles': '已选文件',
|
|
124
|
+
'upload.cancel': '取消上传',
|
|
125
|
+
'upload.retry': '重试上传',
|
|
126
|
+
'upload.remove': '移除文件',
|
|
127
|
+
'upload.status.queued': '待上传',
|
|
128
|
+
'upload.status.success': '上传成功',
|
|
129
|
+
'upload.status.error': '上传失败',
|
|
130
|
+
'upload.status.cancelled': '已取消',
|
|
131
|
+
'upload.cancelled': '上传已取消。',
|
|
132
|
+
'upload.failed': '上传失败,请重试。',
|
|
133
|
+
'upload.typeRejected': '不支持此文件类型。',
|
|
134
|
+
'upload.tooLarge': '文件过大。',
|
|
135
|
+
'upload.tooMany': '超出文件数量限制。',
|
|
114
136
|
'spreadsheet.title': '电子表格',
|
|
115
137
|
'spreadsheet.row': '行',
|
|
116
138
|
'spreadsheet.column': '列',
|
|
@@ -162,6 +184,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
162
184
|
'common.selectLeafOnly': '只允许选择叶子节点',
|
|
163
185
|
'common.save': '保存',
|
|
164
186
|
'common.cancel': '取消',
|
|
187
|
+
'permissions.toggleAction': '切换{action}',
|
|
165
188
|
'common.create': '新建',
|
|
166
189
|
'common.progress': '进度',
|
|
167
190
|
'common.edit': '编辑',
|
|
@@ -188,6 +211,9 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
188
211
|
'common.page': '{current} / {total}',
|
|
189
212
|
'common.export': '导出',
|
|
190
213
|
'common.download': '下载',
|
|
214
|
+
'common.preview': '预览',
|
|
215
|
+
'common.remove': '移除',
|
|
216
|
+
'common.file': '文件',
|
|
191
217
|
'common.import': '导入',
|
|
192
218
|
'common.chooseFile': '选择文件',
|
|
193
219
|
'common.noFileChosen': '未选择文件',
|
|
@@ -224,6 +250,8 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
224
250
|
'common.selectRow': '选择记录 {id}',
|
|
225
251
|
'common.batchDelete': '批量删除 ({count})',
|
|
226
252
|
'common.selectedCount': '已选择 {count} 条记录',
|
|
253
|
+
'common.selectedOfTotal': '已选择 {count} / {total} 条记录',
|
|
254
|
+
'common.batchActions': '批量操作',
|
|
227
255
|
'common.openFullDetail': '完整详情',
|
|
228
256
|
'common.additionalDetails': '补充详情',
|
|
229
257
|
'common.unsavedChanges': '有未保存的修改,确定离开吗?',
|
|
@@ -233,6 +261,9 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
233
261
|
'common.confirmAction': '确认操作',
|
|
234
262
|
'common.operationSuccess': '操作成功',
|
|
235
263
|
'common.operationFailed': '操作失败',
|
|
264
|
+
'common.permissionDenied': '无权执行此操作',
|
|
265
|
+
'common.permissionUnavailable': '权限校验暂不可用,请重试。',
|
|
266
|
+
'common.test': '测试',
|
|
236
267
|
'common.accessDenied': '无权查看此记录',
|
|
237
268
|
'common.createSuccess': '创建成功',
|
|
238
269
|
'common.updateSuccess': '更新成功',
|
|
@@ -250,10 +281,19 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
250
281
|
'common.darkMode': '暗色模式',
|
|
251
282
|
'common.lightMode': '亮色模式',
|
|
252
283
|
'common.detail': '详情',
|
|
284
|
+
'detailWorkspace.relations': '关联记录',
|
|
285
|
+
'detailWorkspace.attachments': '附件',
|
|
286
|
+
'detailWorkspace.activity': '活动',
|
|
287
|
+
'detailWorkspace.audit': '审计',
|
|
288
|
+
'detailWorkspace.versions': '版本差异',
|
|
289
|
+
'detailWorkspace.unavailable': '未配置数据源',
|
|
290
|
+
'detailWorkspace.loading': '正在加载...',
|
|
253
291
|
'common.show': '查看',
|
|
254
292
|
'common.loadFailed': '加载失败: {message}',
|
|
255
293
|
'common.pageNotFound': '页面未找到',
|
|
256
294
|
'common.error': '出错了',
|
|
295
|
+
'common.fileTypeNotAccepted': '文件类型不符合要求。',
|
|
296
|
+
'common.singleFileOnly': '一次只能导入一个文件。',
|
|
257
297
|
'common.retry': '重试',
|
|
258
298
|
'common.yes': '是',
|
|
259
299
|
'common.no': '否',
|
|
@@ -267,6 +307,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
267
307
|
'common.expand': '展开',
|
|
268
308
|
'common.collapse': '收起',
|
|
269
309
|
'common.close': '关闭',
|
|
310
|
+
'common.user': '用户',
|
|
270
311
|
'common.copy': '复制',
|
|
271
312
|
'common.copyAll': '复制全部',
|
|
272
313
|
'common.copied': '已复制',
|
|
@@ -276,6 +317,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
276
317
|
'common.columns': '列',
|
|
277
318
|
'common.savedViews': '视图',
|
|
278
319
|
'common.savedViewsHint': '将当前筛选、搜索、排序、分页和列布局保存在此浏览器。',
|
|
320
|
+
'common.savedViewStaleFields': '已忽略 {count} 个失效字段:资源中已不存在的列不会应用到当前视图。',
|
|
279
321
|
'common.currentView': '当前未保存视图',
|
|
280
322
|
'common.viewName': '视图名称',
|
|
281
323
|
'common.saveView': '保存',
|
|
@@ -358,6 +400,14 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
358
400
|
'empty.title': '暂无数据',
|
|
359
401
|
'empty.description': '没有找到符合条件的记录。',
|
|
360
402
|
'empty.noMore': '没有更多了',
|
|
403
|
+
'audit.emptyTitle': '暂无审计事件',
|
|
404
|
+
'audit.emptyDescription': '活动事件和状态变更将在此显示。',
|
|
405
|
+
'audit.actorPrefix': '操作人:',
|
|
406
|
+
'audit.status.success': '成功',
|
|
407
|
+
'audit.status.warning': '警告',
|
|
408
|
+
'audit.status.danger': '危险',
|
|
409
|
+
'audit.status.info': '信息',
|
|
410
|
+
'audit.status.neutral': '一般',
|
|
361
411
|
// DevTools
|
|
362
412
|
'devtools.title': '开发者工具 (Ctrl+Shift+D)',
|
|
363
413
|
// Validation
|
|
@@ -396,6 +446,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
396
446
|
'security.enable2fa': '启用双重身份验证',
|
|
397
447
|
'security.twoFactorActive': '双重身份验证已启用。新登录时将需要验证码。',
|
|
398
448
|
'security.twoFactorInactive': '双重身份验证已禁用。建议开启以保护账户安全。',
|
|
449
|
+
'security.twoFactorUnknown': '暂时无法确认双重身份验证状态。',
|
|
399
450
|
'security.passwordLastChanged': '上次修改:{time}',
|
|
400
451
|
'security.activeSessions': '活跃会话',
|
|
401
452
|
'security.sessionsDescription': '以下是已登录您账户的设备。您可以撤销任何不识别的设备。',
|
|
@@ -435,7 +486,12 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
435
486
|
'api.generateTitle': '创建新 API 密钥',
|
|
436
487
|
'api.generateDesc': '配置权限范围并生成访问令牌。',
|
|
437
488
|
'api.keyName': '密钥名称',
|
|
489
|
+
'api.keyNamePlaceholder': 'CI 部署令牌',
|
|
438
490
|
'api.permissions': '权限范围',
|
|
491
|
+
'api.permission.read': '读取',
|
|
492
|
+
'api.permission.write': '写入',
|
|
493
|
+
'api.permission.delete': '删除',
|
|
494
|
+
'api.permission.admin': '管理员',
|
|
439
495
|
'api.generateButton': '生成令牌',
|
|
440
496
|
'api.activeKeysTitle': '活跃 API 密钥',
|
|
441
497
|
'api.activeKeysDesc': '请妥善保管这些密钥。切勿在公共仓库中分享。',
|
|
@@ -450,6 +506,14 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
450
506
|
'settings.dark': '深色',
|
|
451
507
|
'settings.systemTheme': '跟随系统',
|
|
452
508
|
'settings.colorAccent': '强调色',
|
|
509
|
+
'settings.accent.neutral': '中性色',
|
|
510
|
+
'settings.accent.indigo': '靛蓝色',
|
|
511
|
+
'settings.accent.blue': '蓝色',
|
|
512
|
+
'settings.accent.green': '绿色',
|
|
513
|
+
'settings.accent.rose': '玫瑰色',
|
|
514
|
+
'settings.accent.orange': '橙色',
|
|
515
|
+
'settings.accent.violet': '紫罗兰色',
|
|
516
|
+
'settings.accent.stripe': '条纹',
|
|
453
517
|
'settings.language': '语言',
|
|
454
518
|
'settings.interface': '界面',
|
|
455
519
|
'settings.sidebarDensity': '侧边栏密度',
|
|
@@ -534,6 +598,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
534
598
|
'profile.changePassword': '修改密码',
|
|
535
599
|
'profile.currentPassword': '当前密码',
|
|
536
600
|
'profile.passwordChanged': '密码已修改',
|
|
601
|
+
'profile.passwordChangedRecently': '最近修改:刚刚',
|
|
537
602
|
'profile.updatePassword': '更新密码',
|
|
538
603
|
'profile.newPassword': '新密码',
|
|
539
604
|
'profile.company': '企业',
|
|
@@ -657,6 +722,8 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
657
722
|
'task.loadingDetail': '正在加载任务详情...',
|
|
658
723
|
'task.noTasks': '暂无任务',
|
|
659
724
|
'task.noDlq': '暂无死信任务',
|
|
725
|
+
'task.listUnavailable': '当前任务服务未提供任务列表。',
|
|
726
|
+
'task.dlqUnavailable': '当前任务服务未提供死信列表。',
|
|
660
727
|
'task.noSelection': '未选择任务',
|
|
661
728
|
'task.selectHint': '从左侧选择一个任务查看详情',
|
|
662
729
|
'task.taskColumn': '任务',
|
|
@@ -692,6 +759,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
692
759
|
'task.submitFailed': '任务提交失败',
|
|
693
760
|
'task.fetchFailed': '加载任务失败',
|
|
694
761
|
'task.fetchListFailed': '加载任务列表失败',
|
|
762
|
+
'task.actionFailed': '无法确认任务操作结果,请核对任务状态后再试。',
|
|
695
763
|
'task.status.pending': '等待中',
|
|
696
764
|
'task.status.queued': '已排队',
|
|
697
765
|
'task.status.running': '执行中',
|
|
@@ -874,6 +942,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
874
942
|
'tree.toggleChildren': 'Expand or collapse children',
|
|
875
943
|
'tree.loadFailed': 'Failed to load child nodes',
|
|
876
944
|
'tree.selectionFailed': 'Could not select the entire group. Retry or select a smaller branch.',
|
|
945
|
+
'tree.childrenUnavailable': 'This node cannot be expanded right now. Try again later or contact your administrator.',
|
|
877
946
|
'tree.removeSelection': 'Remove {label}',
|
|
878
947
|
'virtualTable.label': 'Data table',
|
|
879
948
|
'virtualTable.invalidKeys': 'Record keys are invalid or duplicated. Check the data.',
|
|
@@ -895,12 +964,19 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
895
964
|
'pivot.overflow': 'The aggregate exceeds the numeric range. Change units or use exact server-side calculation.',
|
|
896
965
|
'gantt.title': 'Project Gantt Schedule',
|
|
897
966
|
'import.limit': 'Import file or record count exceeds the limit.',
|
|
967
|
+
'import.fileReadFailed': 'Unable to read or parse the import file. Check the file format and try again.',
|
|
898
968
|
'import.invalidRow': 'Row {row} does not match the resource create schema. Check the mapping and source data.',
|
|
899
969
|
'import.invalidLimits': 'Invalid import capacity configuration.',
|
|
900
970
|
'import.taskConfiguration': 'Server import requires a task provider, task name and idempotency key.',
|
|
901
971
|
'import.taskPayloadLimit': 'The import task payload exceeds the configured byte limit.',
|
|
902
972
|
'import.taskUnconfirmed': 'Task submission is unconfirmed. Check the task center before retrying with the same idempotency key and payload.',
|
|
903
973
|
'import.retryFailedRows': 'Retry recoverable failed rows',
|
|
974
|
+
'import.preview': 'Preview import',
|
|
975
|
+
'import.previewSummary': 'Local validation passed for {importable} of {total} rows; {failed} failed.',
|
|
976
|
+
'import.previewHint': 'Client-side parsing, mapping and create-rule validation only. This does not guarantee the server import will succeed, and no records were written.',
|
|
977
|
+
'import.previewFailed': 'Rows failing local validation',
|
|
978
|
+
'import.previewFailedRow': 'Row {row}: {error}',
|
|
979
|
+
'import.backToImport': 'Back to import',
|
|
904
980
|
'dateInput.presets': 'Quick ranges',
|
|
905
981
|
'dateInput.to': 'to',
|
|
906
982
|
'dateInput.unavailable': 'This date or time is unavailable.',
|
|
@@ -944,6 +1020,19 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
944
1020
|
'upload.cleanupPending': 'Cleanup pending',
|
|
945
1021
|
'upload.cleanupFailed': 'Cleanup failed',
|
|
946
1022
|
'upload.rejectedFiles': 'Rejected files',
|
|
1023
|
+
'upload.selectedFiles': 'Selected files',
|
|
1024
|
+
'upload.cancel': 'Cancel upload',
|
|
1025
|
+
'upload.retry': 'Retry upload',
|
|
1026
|
+
'upload.remove': 'Remove file',
|
|
1027
|
+
'upload.status.queued': 'queued',
|
|
1028
|
+
'upload.status.success': 'success',
|
|
1029
|
+
'upload.status.error': 'error',
|
|
1030
|
+
'upload.status.cancelled': 'cancelled',
|
|
1031
|
+
'upload.cancelled': 'Upload cancelled.',
|
|
1032
|
+
'upload.failed': 'Upload failed.',
|
|
1033
|
+
'upload.typeRejected': 'File type is not accepted.',
|
|
1034
|
+
'upload.tooLarge': 'File is too large.',
|
|
1035
|
+
'upload.tooMany': 'Maximum file count exceeded.',
|
|
947
1036
|
'spreadsheet.title': 'Spreadsheet',
|
|
948
1037
|
'spreadsheet.row': 'Row',
|
|
949
1038
|
'spreadsheet.column': 'Column',
|
|
@@ -996,6 +1085,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
996
1085
|
'dashboard.empty': 'No dashboard data',
|
|
997
1086
|
'dashboard.load': 'Unable to load dashboard data.',
|
|
998
1087
|
'dashboard.invalid': 'Dashboard data is invalid.',
|
|
1088
|
+
'dashboard.drilldown': 'View details',
|
|
999
1089
|
'approval.title': 'Approval center',
|
|
1000
1090
|
'approval.pending': 'Pending',
|
|
1001
1091
|
'approval.history': 'Approval history',
|
|
@@ -1014,6 +1104,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1014
1104
|
'common.selectLeafOnly': 'Select leaf only',
|
|
1015
1105
|
'common.save': 'Save',
|
|
1016
1106
|
'common.cancel': 'Cancel',
|
|
1107
|
+
'permissions.toggleAction': 'Toggle {action}',
|
|
1017
1108
|
'common.create': 'Create',
|
|
1018
1109
|
'common.progress': 'Progress',
|
|
1019
1110
|
'common.edit': 'Edit',
|
|
@@ -1040,6 +1131,9 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1040
1131
|
'common.page': '{current} / {total}',
|
|
1041
1132
|
'common.export': 'Export',
|
|
1042
1133
|
'common.download': 'Download',
|
|
1134
|
+
'common.preview': 'Preview',
|
|
1135
|
+
'common.remove': 'Remove',
|
|
1136
|
+
'common.file': 'File',
|
|
1043
1137
|
'common.import': 'Import',
|
|
1044
1138
|
'common.chooseFile': 'Choose file',
|
|
1045
1139
|
'common.noFileChosen': 'No file chosen',
|
|
@@ -1076,6 +1170,8 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1076
1170
|
'common.selectRow': 'Select record {id}',
|
|
1077
1171
|
'common.batchDelete': 'Batch Delete ({count})',
|
|
1078
1172
|
'common.selectedCount': '{count} records selected',
|
|
1173
|
+
'common.selectedOfTotal': '{count} of {total} records selected',
|
|
1174
|
+
'common.batchActions': 'Batch actions',
|
|
1079
1175
|
'common.openFullDetail': 'Full details',
|
|
1080
1176
|
'common.additionalDetails': 'Additional details',
|
|
1081
1177
|
'common.unsavedChanges': 'You have unsaved changes. Leave anyway?',
|
|
@@ -1085,6 +1181,9 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1085
1181
|
'common.confirmAction': 'Confirm Action',
|
|
1086
1182
|
'common.operationSuccess': 'Operation successful',
|
|
1087
1183
|
'common.operationFailed': 'Operation failed',
|
|
1184
|
+
'common.permissionDenied': 'You do not have permission to perform this action',
|
|
1185
|
+
'common.permissionUnavailable': 'Permission check is unavailable. Please retry.',
|
|
1186
|
+
'common.test': 'Test',
|
|
1088
1187
|
'common.accessDenied': 'You do not have access to this record',
|
|
1089
1188
|
'common.createSuccess': 'Created successfully',
|
|
1090
1189
|
'common.updateSuccess': 'Updated successfully',
|
|
@@ -1102,10 +1201,19 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1102
1201
|
'common.darkMode': 'Dark mode',
|
|
1103
1202
|
'common.lightMode': 'Light mode',
|
|
1104
1203
|
'common.detail': 'Detail',
|
|
1204
|
+
'detailWorkspace.relations': 'Related records',
|
|
1205
|
+
'detailWorkspace.attachments': 'Attachments',
|
|
1206
|
+
'detailWorkspace.activity': 'Activity',
|
|
1207
|
+
'detailWorkspace.audit': 'Audit',
|
|
1208
|
+
'detailWorkspace.versions': 'Version differences',
|
|
1209
|
+
'detailWorkspace.unavailable': 'No data source configured',
|
|
1210
|
+
'detailWorkspace.loading': 'Loading...',
|
|
1105
1211
|
'common.show': 'Show',
|
|
1106
1212
|
'common.loadFailed': 'Load failed: {message}',
|
|
1107
1213
|
'common.pageNotFound': 'Page not found',
|
|
1108
1214
|
'common.error': 'Something went wrong',
|
|
1215
|
+
'common.fileTypeNotAccepted': 'File type is not accepted.',
|
|
1216
|
+
'common.singleFileOnly': 'Select one file at a time.',
|
|
1109
1217
|
'common.retry': 'Retry',
|
|
1110
1218
|
'common.yes': 'Yes',
|
|
1111
1219
|
'common.no': 'No',
|
|
@@ -1119,6 +1227,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1119
1227
|
'common.expand': 'Expand',
|
|
1120
1228
|
'common.collapse': 'Collapse',
|
|
1121
1229
|
'common.close': 'Close',
|
|
1230
|
+
'common.user': 'User',
|
|
1122
1231
|
'common.copy': 'Copy',
|
|
1123
1232
|
'common.copyAll': 'Copy All',
|
|
1124
1233
|
'common.copied': 'Copied!',
|
|
@@ -1128,6 +1237,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1128
1237
|
'common.columns': 'Columns',
|
|
1129
1238
|
'common.savedViews': 'Views',
|
|
1130
1239
|
'common.savedViewsHint': 'Save filters, search, sorting, pagination, and column layout in this browser.',
|
|
1240
|
+
'common.savedViewStaleFields': 'Ignored {count} unavailable field(s): columns that no longer exist in this resource are not applied.',
|
|
1131
1241
|
'common.currentView': 'Current unsaved view',
|
|
1132
1242
|
'common.viewName': 'View name',
|
|
1133
1243
|
'common.saveView': 'Save',
|
|
@@ -1210,6 +1320,14 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1210
1320
|
'empty.title': 'No data',
|
|
1211
1321
|
'empty.description': 'No records found matching your criteria.',
|
|
1212
1322
|
'empty.noMore': 'No more items',
|
|
1323
|
+
'audit.emptyTitle': 'No timeline events',
|
|
1324
|
+
'audit.emptyDescription': 'Activity events and status transitions will appear here.',
|
|
1325
|
+
'audit.actorPrefix': 'by ',
|
|
1326
|
+
'audit.status.success': 'success',
|
|
1327
|
+
'audit.status.warning': 'warning',
|
|
1328
|
+
'audit.status.danger': 'danger',
|
|
1329
|
+
'audit.status.info': 'info',
|
|
1330
|
+
'audit.status.neutral': 'neutral',
|
|
1213
1331
|
// DevTools
|
|
1214
1332
|
'devtools.title': 'DevTools (Ctrl+Shift+D)',
|
|
1215
1333
|
// Validation
|
|
@@ -1248,6 +1366,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1248
1366
|
'security.enable2fa': 'Enable 2FA Verification',
|
|
1249
1367
|
'security.twoFactorActive': '2FA is currently active. Verification codes will be required on new logins.',
|
|
1250
1368
|
'security.twoFactorInactive': '2FA is currently disabled. Protect your account by turning it on.',
|
|
1369
|
+
'security.twoFactorUnknown': 'Two-factor authentication status is currently unavailable.',
|
|
1251
1370
|
'security.passwordLastChanged': 'Last changed: {time}',
|
|
1252
1371
|
'security.activeSessions': 'Active Sessions',
|
|
1253
1372
|
'security.sessionsDescription': 'These are the devices that have logged into your account. Revoke any you do not recognize.',
|
|
@@ -1287,7 +1406,12 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1287
1406
|
'api.generateTitle': 'Create New API Key',
|
|
1288
1407
|
'api.generateDesc': 'Configure scopes and generate a token.',
|
|
1289
1408
|
'api.keyName': 'Key Name',
|
|
1409
|
+
'api.keyNamePlaceholder': 'CI deployment token',
|
|
1290
1410
|
'api.permissions': 'Permissions',
|
|
1411
|
+
'api.permission.read': 'Read',
|
|
1412
|
+
'api.permission.write': 'Write',
|
|
1413
|
+
'api.permission.delete': 'Delete',
|
|
1414
|
+
'api.permission.admin': 'Admin',
|
|
1291
1415
|
'api.generateButton': 'Generate Token',
|
|
1292
1416
|
'api.activeKeysTitle': 'Active API Keys',
|
|
1293
1417
|
'api.activeKeysDesc': 'Keep these keys secure. Do not share them in public repositories.',
|
|
@@ -1302,6 +1426,14 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1302
1426
|
'settings.dark': 'Dark',
|
|
1303
1427
|
'settings.systemTheme': 'System',
|
|
1304
1428
|
'settings.colorAccent': 'Color Accent',
|
|
1429
|
+
'settings.accent.neutral': 'Neutral',
|
|
1430
|
+
'settings.accent.indigo': 'Indigo',
|
|
1431
|
+
'settings.accent.blue': 'Blue',
|
|
1432
|
+
'settings.accent.green': 'Green',
|
|
1433
|
+
'settings.accent.rose': 'Rose',
|
|
1434
|
+
'settings.accent.orange': 'Orange',
|
|
1435
|
+
'settings.accent.violet': 'Violet',
|
|
1436
|
+
'settings.accent.stripe': 'Stripe',
|
|
1305
1437
|
'settings.language': 'Language',
|
|
1306
1438
|
'settings.interface': 'Interface',
|
|
1307
1439
|
'settings.sidebarDensity': 'Sidebar Density',
|
|
@@ -1386,6 +1518,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1386
1518
|
'profile.changePassword': 'Change Password',
|
|
1387
1519
|
'profile.currentPassword': 'Current Password',
|
|
1388
1520
|
'profile.passwordChanged': 'Password updated successfully',
|
|
1521
|
+
'profile.passwordChangedRecently': 'Last changed: just now',
|
|
1389
1522
|
'profile.updatePassword': 'Update Password',
|
|
1390
1523
|
'profile.newPassword': 'New Password',
|
|
1391
1524
|
'profile.company': 'Company',
|
|
@@ -1509,6 +1642,8 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1509
1642
|
'task.loadingDetail': 'Loading task...',
|
|
1510
1643
|
'task.noTasks': 'No tasks found',
|
|
1511
1644
|
'task.noDlq': 'No dead-letter tasks',
|
|
1645
|
+
'task.listUnavailable': 'The current task service does not provide a task list.',
|
|
1646
|
+
'task.dlqUnavailable': 'The current task service does not provide a dead-letter list.',
|
|
1512
1647
|
'task.noSelection': 'No task selected',
|
|
1513
1648
|
'task.selectHint': 'Select a task from the list to inspect details',
|
|
1514
1649
|
'task.taskColumn': 'Task',
|
|
@@ -1544,6 +1679,7 @@ const baseLocales: Record<string, Record<string, string>> = {
|
|
|
1544
1679
|
'task.submitFailed': 'Task submission failed',
|
|
1545
1680
|
'task.fetchFailed': 'Fetch task failed',
|
|
1546
1681
|
'task.fetchListFailed': 'Fetch tasks failed',
|
|
1682
|
+
'task.actionFailed': 'Unable to confirm the task action. Check the task status before trying again.',
|
|
1547
1683
|
'task.status.pending': 'Pending',
|
|
1548
1684
|
'task.status.queued': 'Queued',
|
|
1549
1685
|
'task.status.running': 'Running',
|
package/src/import-contract.ts
CHANGED
|
@@ -8,6 +8,17 @@ import { decodeOneResult, decodeManyResult, rejectProviderResponse } from './rec
|
|
|
8
8
|
|
|
9
9
|
export type ImportFormat = 'auto' | 'csv' | 'json';
|
|
10
10
|
export const IMPORT_LIMITS = Object.freeze({ maxRows: 10_000, maxBytes: 50 * 1024 * 1024 });
|
|
11
|
+
/** A dry-run failure uses the same local, non-diagnostic reason as an import failure. */
|
|
12
|
+
export interface ImportPreviewFailure {
|
|
13
|
+
row: number;
|
|
14
|
+
error: string;
|
|
15
|
+
}
|
|
16
|
+
export interface ImportPreviewResult {
|
|
17
|
+
totalRows: number;
|
|
18
|
+
/** Rows that pass local schema validation only; this is not a server import guarantee. */
|
|
19
|
+
importableRows: number;
|
|
20
|
+
failedRows: ImportPreviewFailure[];
|
|
21
|
+
}
|
|
11
22
|
export interface ImportArtifact {
|
|
12
23
|
artifactId: string;
|
|
13
24
|
fileName: string;
|
|
@@ -95,6 +106,12 @@ export function snapshotImportTaskResult(value: unknown): ImportTaskResult | und
|
|
|
95
106
|
}
|
|
96
107
|
}
|
|
97
108
|
|
|
109
|
+
/** Preview failures deliberately drop parser/provider diagnostics and keep only the safe import reason. */
|
|
110
|
+
export function invalidImportPreviewFailure(row: number): ImportPreviewFailure {
|
|
111
|
+
if (!Number.isSafeInteger(row) || row < 1 || row > IMPORT_LIMITS.maxRows) invalidImportInput();
|
|
112
|
+
return Object.freeze({ row, error: 'Invalid import input' });
|
|
113
|
+
}
|
|
114
|
+
|
|
98
115
|
export function invalidImportInput(row?: number): never {
|
|
99
116
|
throw new HttpError('Invalid import input', 422, undefined, {
|
|
100
117
|
code: 'INVALID_RESOURCE_INPUT',
|
package/src/index.ts
CHANGED
|
@@ -114,7 +114,8 @@ export type { ContractProjectionOptions } from './resource-contract';
|
|
|
114
114
|
export type { ResourceContract, ContractSchemas, ContractRecord, ContractId, ContractInput } from './resource-contract';
|
|
115
115
|
export type { ContractFilter, ContractSort } from './strict-hooks.svelte';
|
|
116
116
|
export { defineCommand } from './command-contract';
|
|
117
|
-
export type { CommandContract, CommandInput, CommandOutput
|
|
117
|
+
export type { CommandContract, CommandInput, CommandOutput, CommandErrorDiagnostic, CommandErrorDiagnostics,
|
|
118
|
+
CommandDiagnostics } from './command-contract';
|
|
118
119
|
export { useCustom, useCustomMutation } from './strict-command-hooks.svelte';
|
|
119
120
|
export { matchRoute, navigate, currentPath, setActiveRouterProvider, beforeEach, afterEach, resetRouter } from './router';
|
|
120
121
|
export type { RouteGuard } from './router';
|
|
@@ -187,7 +188,8 @@ export type {
|
|
|
187
188
|
export { assertEnterpriseRequestContext, createEnterpriseRequestContext } from './enterprise';
|
|
188
189
|
export {
|
|
189
190
|
DashboardContractError, decodeDashboardQuery, decodeDashboardSnapshot,
|
|
190
|
-
type
|
|
191
|
+
type DashboardDrilldown, type DashboardMetric, type DashboardProvider, type DashboardQuery,
|
|
192
|
+
type DashboardSnapshot, type DashboardTimeRange, type DashboardWidget,
|
|
191
193
|
} from './dashboard-contract';
|
|
192
194
|
export { setChatProvider, getChatProvider, setChatContext, getChatContext, setAgentProvider, getAgentProvider, registerApproval, resolveApproval, hasPendingApprovals, resetChatProvider, defineAdminTool, decodeAdminToolArgs, executeAdminTool, projectAdminToolSchema } from './chatProvider.svelte';
|
|
193
195
|
export { ENTERPRISE_MATURITY, enterpriseMaturityFor } from './enterprise-maturity';
|
|
@@ -259,8 +261,8 @@ export { snapshotExportTaskResult, downloadExportArtifact, safeArtifactUrl } fro
|
|
|
259
261
|
export type { ExportTaskResult } from './export-format';
|
|
260
262
|
export type { UseExportOptions } from './export-hooks.svelte';
|
|
261
263
|
export { useImport } from './import-hooks.svelte';
|
|
262
|
-
export type { ImportArtifact, ImportArtifactProvider, ImportTaskResult } from './import-contract';
|
|
263
|
-
export { snapshotImportArtifact, snapshotImportTaskResult } from './import-contract';
|
|
264
|
+
export type { ImportArtifact, ImportArtifactProvider, ImportTaskResult, ImportPreviewFailure, ImportPreviewResult } from './import-contract';
|
|
265
|
+
export { snapshotImportArtifact, snapshotImportTaskResult, invalidImportPreviewFailure } from './import-contract';
|
|
264
266
|
export { IMPORT_LIMITS } from './import-contract';
|
|
265
267
|
export type { UseImportOptions, ImportProgress, ImportResult } from './import-hooks.svelte';
|
|
266
268
|
export type { ExportFormat } from './data-transfer.svelte';
|
|
@@ -8,6 +8,7 @@ import { HttpError } from './types';
|
|
|
8
8
|
import type { QueryKey } from './query-keys';
|
|
9
9
|
import { definedOptions } from './defined-options';
|
|
10
10
|
import type { NotificationConfig } from './hook-utils.svelte';
|
|
11
|
+
import { t } from './i18n.svelte';
|
|
11
12
|
import { notifyWithProvider } from './notification.svelte';
|
|
12
13
|
import { snapshotPlainData } from './plain-data';
|
|
13
14
|
import { checkExact } from './schema-validation';
|
|
@@ -17,6 +18,9 @@ const notificationSchema = Type.Object({
|
|
|
17
18
|
type: Type.Optional(Type.Union([Type.Literal('success'), Type.Literal('error')])),
|
|
18
19
|
}, { additionalProperties: false });
|
|
19
20
|
|
|
21
|
+
const queryErrorNotificationKeys = new WeakMap<object, string>();
|
|
22
|
+
let nextQueryErrorNotificationId = 0;
|
|
23
|
+
|
|
20
24
|
export interface QuerySessionOptions {
|
|
21
25
|
queryKey: QueryKey;
|
|
22
26
|
resource: string;
|
|
@@ -45,6 +49,7 @@ export function querySessionError(error: unknown): HttpError {
|
|
|
45
49
|
if (typeof statusValue === 'number' && Number.isInteger(statusValue) && statusValue >= 400 && statusValue <= 599) status = statusValue;
|
|
46
50
|
if (codeValue === 'INVALID_PROVIDER_RESPONSE' || codeValue === 'INVALID_RESOURCE_INPUT' ||
|
|
47
51
|
codeValue === 'DATA_PROVIDER_REQUIRED' || codeValue === 'QUERY_SESSION_SUPERSEDED' ||
|
|
52
|
+
codeValue === 'SELECT_REQUEST_CANCELLED' || codeValue === 'SELECT_REQUEST_TIMEOUT' ||
|
|
48
53
|
codeValue === 'INVALID_SELECT_OPTION' || codeValue === 'INVALID_COMMAND_INPUT' ||
|
|
49
54
|
codeValue === 'INVALID_COMMAND_RESPONSE' || codeValue === 'INVALID_COMMAND_CONTRACT' ||
|
|
50
55
|
codeValue === 'INVALID_COMMAND_METHOD' || codeValue === 'COMMAND_NOT_SUPPORTED' ||
|
|
@@ -98,13 +103,25 @@ export function createQuerySession<O extends QuerySessionOptions>(context: Admin
|
|
|
98
103
|
const config = type === 'success' ? origin.successNotification : origin.errorNotification;
|
|
99
104
|
if (config === false || !current(origin)) return;
|
|
100
105
|
if (config !== undefined && typeof config !== 'function' && typeof config !== 'string') return;
|
|
101
|
-
const fallback = type === 'success' ? '' : '
|
|
106
|
+
const fallback = type === 'success' ? '' : t('common.loadFailed', { message: t('common.error') });
|
|
102
107
|
if (typeof config !== 'function' && !config && !fallback) return;
|
|
103
108
|
const candidate = snapshotPlainData(typeof config === 'function'
|
|
104
109
|
? config(value, undefined, origin.resource) : { message: config || fallback });
|
|
105
110
|
if (!checkExact(notificationSchema, candidate) || !current(origin) || origin.notification !== context.notificationProvider) return;
|
|
111
|
+
let key = candidate.key;
|
|
112
|
+
if (type === 'error' && !config) {
|
|
113
|
+
const query = client.getQueryCache().find({ queryKey: origin.queryKey, exact: true });
|
|
114
|
+
if (query) {
|
|
115
|
+
key = queryErrorNotificationKeys.get(query);
|
|
116
|
+
if (!key) {
|
|
117
|
+
// 查询对象共享不透明标识,避免向通知 Provider 暴露筛选条件和请求元数据。
|
|
118
|
+
key = `svadmin-query-error:${nextQueryErrorNotificationId++}`;
|
|
119
|
+
queryErrorNotificationKeys.set(query, key);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
106
123
|
notifyWithProvider({
|
|
107
|
-
type, message: candidate.message, ...definedOptions({ description: candidate.description, key
|
|
124
|
+
type, message: candidate.message, ...definedOptions({ description: candidate.description, key }),
|
|
108
125
|
}, origin.notification);
|
|
109
126
|
} catch {
|
|
110
127
|
// Observer failures and malformed receipts cannot change query state.
|
|
@@ -1,15 +1,22 @@
|
|
|
1
1
|
import { untrack } from 'svelte';
|
|
2
|
+
import { useQueryClient } from '@tanstack/svelte-query';
|
|
2
3
|
import { createSessionQuery } from './session-query.svelte';
|
|
3
4
|
import { captureAuthLiveScope } from './auth-hooks.svelte';
|
|
4
5
|
import { definedOptions } from './defined-options';
|
|
5
6
|
import { captureContractContext, type ContractOptions } from './contract-context.svelte';
|
|
6
7
|
import { getAdminOptions } from './options.svelte';
|
|
7
8
|
import { captureQueryProvider, snapshotListParams, snapshotManyParams } from './query-snapshot';
|
|
8
|
-
import { decodeListResult, decodeManyResult, rejectProviderResponse, type RecordDecoder } from './record-decoder';
|
|
9
|
+
import { decodeListResult, decodeManyResult, decodeBaseRecord, rejectProviderResponse, type RecordDecoder } from './record-decoder';
|
|
9
10
|
import { createOvertimeTracker } from './hook-utils.svelte';
|
|
10
11
|
import type { NotificationConfig, OvertimeOptions } from './hook-utils.svelte';
|
|
11
12
|
import { createSelectProjection, mergeSelectOptions, type SelectOption } from './select-options';
|
|
12
13
|
import { HttpError, type BaseRecord, type KnownResources, type Pagination, type Sort, type Filter } from './types';
|
|
14
|
+
import type { QueryKey } from './query-keys';
|
|
15
|
+
|
|
16
|
+
function withAuthSession(key: QueryKey, authSession: string): QueryKey {
|
|
17
|
+
const descriptor = key[0];
|
|
18
|
+
return [{ ...descriptor, params: { ...decodeBaseRecord(descriptor.params), authSession } }];
|
|
19
|
+
}
|
|
13
20
|
|
|
14
21
|
export interface UseSelectOptions<TData extends BaseRecord = BaseRecord> extends ContractOptions {
|
|
15
22
|
resource: KnownResources;
|
|
@@ -23,6 +30,8 @@ export interface UseSelectOptions<TData extends BaseRecord = BaseRecord> extends
|
|
|
23
30
|
fetchSize?: number;
|
|
24
31
|
pagination?: Pagination;
|
|
25
32
|
debounce?: number;
|
|
33
|
+
/** Optional timeout in milliseconds for list and selected-record reads. */
|
|
34
|
+
requestTimeout?: number;
|
|
26
35
|
queryOptions?: { staleTime?: number; enabled?: boolean };
|
|
27
36
|
defaultValueQueryOptions?: { staleTime?: number; enabled?: boolean };
|
|
28
37
|
meta?: Record<string, unknown>;
|
|
@@ -38,7 +47,91 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
38
47
|
) {
|
|
39
48
|
const context = captureContractContext(options);
|
|
40
49
|
const adminOptions = getAdminOptions();
|
|
50
|
+
const queryClient = useQueryClient();
|
|
41
51
|
let disposed = false;
|
|
52
|
+
interface ActiveRequest { controller: AbortController; key: QueryKey; active: boolean }
|
|
53
|
+
const listRequests = new Set<ActiveRequest>();
|
|
54
|
+
const defaultsRequests = new Set<ActiveRequest>();
|
|
55
|
+
// 当前观察者仍挂载的查询 key;用于区分“同 key 显式取消”和“已切到新搜索/作用域”。
|
|
56
|
+
let currentListKey: QueryKey | undefined;
|
|
57
|
+
let currentDefaultsKey: QueryKey | undefined;
|
|
58
|
+
// 请求由共享的 TanStack query 持有;单个消费者离开时不能中止仍有其他 observer 的请求。
|
|
59
|
+
function cancelOwnedRequests(requests: Set<ActiveRequest>, getCurrentKey: () => QueryKey | undefined): void {
|
|
60
|
+
const snapshot = [...requests];
|
|
61
|
+
// 延后到 Svelte 完成 observer key 切换后再判定,避免把仍在使用的共享请求误判为本消费者独占。
|
|
62
|
+
setTimeout(() => {
|
|
63
|
+
for (const entry of snapshot) {
|
|
64
|
+
if (!entry.active || entry.controller.signal.aborted) continue;
|
|
65
|
+
const cached = queryClient.getQueryCache().find({ queryKey: entry.key, exact: true });
|
|
66
|
+
const observers = cached?.getObserversCount() ?? 0;
|
|
67
|
+
const stillOnKey = getCurrentKey() === entry.key;
|
|
68
|
+
// 已卸载或已切到新 key 时,本消费者不再使用旧请求,仅在没有其他 observer 时中止。
|
|
69
|
+
// 同 key 显式 cancel 时本 observer 仍计入数量,因此最多保留一个 observer。
|
|
70
|
+
if (disposed || !stillOnKey ? observers === 0 : observers <= 1) entry.controller.abort();
|
|
71
|
+
}
|
|
72
|
+
}, 0);
|
|
73
|
+
}
|
|
74
|
+
function cancelListRequests(): void { cancelOwnedRequests(listRequests, () => currentListKey); }
|
|
75
|
+
function cancelRequests(): void {
|
|
76
|
+
cancelOwnedRequests(listRequests, () => currentListKey);
|
|
77
|
+
cancelOwnedRequests(defaultsRequests, () => currentDefaultsKey);
|
|
78
|
+
}
|
|
79
|
+
function selectRequest<T>(
|
|
80
|
+
requests: Set<ActiveRequest>, key: QueryKey, signal: AbortSignal | undefined,
|
|
81
|
+
run: (signal: AbortSignal) => Promise<T>,
|
|
82
|
+
): Promise<T> {
|
|
83
|
+
const timeout = options.requestTimeout;
|
|
84
|
+
if (timeout !== undefined && (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > 2_147_483_647)) {
|
|
85
|
+
return Promise.reject(new HttpError('Invalid select request timeout', 422, undefined, { code: 'INVALID_RESOURCE_INPUT' }));
|
|
86
|
+
}
|
|
87
|
+
const controller = new AbortController();
|
|
88
|
+
const entry: ActiveRequest = { controller, key, active: true };
|
|
89
|
+
requests.add(entry);
|
|
90
|
+
const forwardAbort = () => controller.abort();
|
|
91
|
+
if (signal) {
|
|
92
|
+
if (signal.aborted) controller.abort();
|
|
93
|
+
else signal.addEventListener('abort', forwardAbort, { once: true });
|
|
94
|
+
}
|
|
95
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
96
|
+
return new Promise<T>((resolve, reject) => {
|
|
97
|
+
let settled = false;
|
|
98
|
+
const finish = (): boolean => {
|
|
99
|
+
if (settled) return false;
|
|
100
|
+
settled = true;
|
|
101
|
+
entry.active = false;
|
|
102
|
+
requests.delete(entry);
|
|
103
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
104
|
+
signal?.removeEventListener('abort', forwardAbort);
|
|
105
|
+
return true;
|
|
106
|
+
};
|
|
107
|
+
const fail = (error: Error): void => {
|
|
108
|
+
if (finish()) reject(error);
|
|
109
|
+
};
|
|
110
|
+
if (controller.signal.aborted) {
|
|
111
|
+
fail(new HttpError('Select request cancelled', 409, undefined, { code: 'SELECT_REQUEST_CANCELLED' }));
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (timeout !== undefined) {
|
|
115
|
+
timer = setTimeout(() => {
|
|
116
|
+
fail(new HttpError('Select request timed out', 504, undefined, { code: 'SELECT_REQUEST_TIMEOUT' }));
|
|
117
|
+
controller.abort();
|
|
118
|
+
}, timeout);
|
|
119
|
+
}
|
|
120
|
+
let request: Promise<T>;
|
|
121
|
+
try {
|
|
122
|
+
request = run(controller.signal);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
fail(error instanceof Error ? error : new Error('Select request failed'));
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
request.then(value => {
|
|
128
|
+
if (!finish()) return;
|
|
129
|
+
resolve(value);
|
|
130
|
+
}, (error: unknown) => {
|
|
131
|
+
fail(error instanceof Error ? error : new Error('Select request failed'));
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
}
|
|
42
135
|
const scope = $derived.by(() => {
|
|
43
136
|
const resource = options.resource;
|
|
44
137
|
const contract = options.contract;
|
|
@@ -107,15 +200,22 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
107
200
|
if (origin.checkIds && new Set(result.data.map(record => record['id'])).size !== result.data.length) return rejectProviderResponse();
|
|
108
201
|
return result;
|
|
109
202
|
};
|
|
203
|
+
const queryKey = keys.data.select(params.resource, {
|
|
204
|
+
...params, source: captured.source, search: text, invalid: !!error, projection: origin.projectionKey,
|
|
205
|
+
});
|
|
206
|
+
const requestKey = withAuthSession(queryKey, origin.auth.cacheKey);
|
|
207
|
+
currentListKey = requestKey;
|
|
110
208
|
return {
|
|
111
209
|
resource: params.resource, successNotification: options.successNotification, errorNotification: options.errorNotification,
|
|
112
210
|
decode: createSelectProjection(decodeResult, label, value, decode, () => sessionCurrent(origin)),
|
|
113
|
-
queryKey
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
queryFn: async () => {
|
|
211
|
+
queryKey,
|
|
212
|
+
// 同一 key 的请求可由其他 observer 共享,不能因本实例卸载或切换搜索而丢弃共享结果。
|
|
213
|
+
allowRetiredQueryFn: true,
|
|
214
|
+
queryFn: async (signal) => {
|
|
117
215
|
if (error) throw error;
|
|
118
|
-
return
|
|
216
|
+
return selectRequest(listRequests, requestKey, signal, requestSignal =>
|
|
217
|
+
captured.provider.getList(snapshotListParams({ ...params, ...definedOptions({ signal: requestSignal }) })),
|
|
218
|
+
).then(decodeResult);
|
|
119
219
|
},
|
|
120
220
|
enabled: options.queryOptions?.enabled ?? true,
|
|
121
221
|
...definedOptions({ staleTime: options.queryOptions?.staleTime ?? adminOptions.reactQuery?.staleTime }),
|
|
@@ -139,15 +239,21 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
139
239
|
result.data.some(record => !expected.has(record['id'])))) return rejectProviderResponse();
|
|
140
240
|
return result;
|
|
141
241
|
};
|
|
242
|
+
const queryKey = keys.data.selectDefaults(params.resource, { ...params, source: captured.source, projection: origin.projectionKey });
|
|
243
|
+
const requestKey = withAuthSession(queryKey, origin.auth.cacheKey);
|
|
244
|
+
currentDefaultsKey = requestKey;
|
|
142
245
|
return {
|
|
143
246
|
resource: params.resource, successNotification: false, errorNotification: options.errorNotification,
|
|
144
247
|
decode: createSelectProjection(decodeResult, label, value, decode, () => sessionCurrent(origin)),
|
|
145
|
-
queryKey
|
|
146
|
-
|
|
248
|
+
queryKey,
|
|
249
|
+
allowRetiredQueryFn: true,
|
|
250
|
+
queryFn: async (signal) => {
|
|
147
251
|
if (!params.ids.length) return { data: [] };
|
|
148
252
|
const getMany = captured.provider.getMany;
|
|
149
253
|
if (!getMany) throw new Error('Captured query provider must support getMany');
|
|
150
|
-
return
|
|
254
|
+
return selectRequest(defaultsRequests, requestKey, signal, requestSignal =>
|
|
255
|
+
getMany.call(captured.provider, snapshotManyParams({ ...params, ...definedOptions({ signal: requestSignal }) })),
|
|
256
|
+
).then(decodeResult);
|
|
151
257
|
},
|
|
152
258
|
enabled: (options.queryOptions?.enabled ?? true) &&
|
|
153
259
|
(options.defaultValueQueryOptions?.enabled ?? true) && params.ids.length > 0,
|
|
@@ -166,21 +272,25 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
166
272
|
const current = scope;
|
|
167
273
|
if (!sessionCurrent(current)) return;
|
|
168
274
|
if (!value || delay === 0) {
|
|
275
|
+
cancelListRequests();
|
|
169
276
|
search = { scope: current, value };
|
|
170
277
|
return;
|
|
171
278
|
}
|
|
172
279
|
timer = setTimeout(() => {
|
|
173
|
-
if (scope === current && sessionCurrent(current))
|
|
280
|
+
if (scope === current && sessionCurrent(current)) {
|
|
281
|
+
cancelListRequests();
|
|
282
|
+
search = { scope: current, value };
|
|
283
|
+
}
|
|
174
284
|
}, delay);
|
|
175
285
|
}
|
|
176
286
|
$effect(() => {
|
|
177
287
|
void scope;
|
|
178
288
|
return () => clearTimeout(timer);
|
|
179
289
|
});
|
|
180
|
-
$effect(() => () => { disposed = true; });
|
|
290
|
+
$effect(() => () => { disposed = true; cancelRequests(); });
|
|
181
291
|
|
|
182
292
|
return {
|
|
183
|
-
query, defaultValueQuery, onSearchChange,
|
|
293
|
+
query, defaultValueQuery, onSearchChange, cancel: cancelRequests,
|
|
184
294
|
get options() { return mergeSelectOptions(query.data?.options ?? [], defaultValueQuery.data?.options ?? []); },
|
|
185
295
|
get overtime() { return overtime; },
|
|
186
296
|
get isLoading() { return query.isLoading || defaultValueQuery.isLoading; },
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { TObject, TSchema } from 'typebox';
|
|
2
2
|
import { hashKey, useQueryClient } from '@tanstack/svelte-query';
|
|
3
3
|
import { captureAdminContext, type AdminContextAccessor } from './context.svelte';
|
|
4
|
-
import { commandDefinition, prepareCommand, parseCommandInput, parseCommandResponse,
|
|
5
|
-
type CommandContract, type CommandInput, type CommandOutput } from './command-contract';
|
|
4
|
+
import { commandDefinition, prepareCommand, parseCommandInput, parseCommandResponse, safeCommandDiagnostic,
|
|
5
|
+
type CommandContract, type CommandErrorDiagnostics, type CommandInput, type CommandOutput } from './command-contract';
|
|
6
6
|
import { captureAuthLiveScope, clearAuthQueries, handleAuthError } from './auth-hooks.svelte';
|
|
7
7
|
import { createSessionQuery } from './session-query.svelte';
|
|
8
8
|
import { createQueryResultView, supersededQuerySession } from './query-session.svelte';
|
|
@@ -60,9 +60,11 @@ function observe(callback: () => unknown): void {
|
|
|
60
60
|
try { void Promise.resolve(callback()).catch(() => {}); }
|
|
61
61
|
catch { /* Observers do not own the command outcome. */ }
|
|
62
62
|
}
|
|
63
|
-
function failure(cause: unknown, dispatched = false
|
|
63
|
+
function failure(cause: unknown, dispatched = false,
|
|
64
|
+
diagnostics?: CommandErrorDiagnostics): HttpError {
|
|
64
65
|
let status = 502;
|
|
65
66
|
let code = 'COMMAND_FAILED';
|
|
67
|
+
let message = 'Command failed';
|
|
66
68
|
try {
|
|
67
69
|
if (typeof cause === 'object' && cause !== null) {
|
|
68
70
|
const value: unknown = Object.getOwnPropertyDescriptor(cause, 'statusCode')?.value;
|
|
@@ -71,9 +73,15 @@ function failure(cause: unknown, dispatched = false): HttpError {
|
|
|
71
73
|
if (label === 'INVALID_COMMAND_INPUT' || label === 'INVALID_COMMAND_RESPONSE' ||
|
|
72
74
|
label === 'INVALID_COMMAND_CONTRACT' || label === 'INVALID_COMMAND_METHOD' ||
|
|
73
75
|
label === 'COMMAND_NOT_SUPPORTED' || label === 'DATA_PROVIDER_REQUIRED') code = label;
|
|
76
|
+
else if (diagnostics) message = 'Command execution failed';
|
|
77
|
+
const diagnostic = safeCommandDiagnostic(cause, diagnostics);
|
|
78
|
+
if (diagnostic) {
|
|
79
|
+
code = diagnostic.code;
|
|
80
|
+
message = diagnostic.message;
|
|
81
|
+
}
|
|
74
82
|
}
|
|
75
83
|
} catch { /* Reflection errors remain private. */ }
|
|
76
|
-
return new HttpError(
|
|
84
|
+
return new HttpError(message, status, undefined, { code, details: { writeMayHaveSucceeded: dispatched } });
|
|
77
85
|
}
|
|
78
86
|
function cancelled(dispatched: boolean): HttpError {
|
|
79
87
|
return new HttpError('Command scope changed', 409, undefined, {
|
|
@@ -168,8 +176,9 @@ export function useCustomMutation<I extends TObject, O extends TSchema>(options:
|
|
|
168
176
|
}
|
|
169
177
|
const current = (scope: Scope, token: object) =>
|
|
170
178
|
targetCurrent(scope) && scope.authScope.isCurrent() && latestToken === token;
|
|
171
|
-
function copyError(error: HttpError, dispatched: boolean
|
|
172
|
-
|
|
179
|
+
function copyError(error: HttpError, dispatched: boolean,
|
|
180
|
+
diagnostics: CommandErrorDiagnostics | undefined): HttpError {
|
|
181
|
+
return error.code === 'COMMAND_CANCELLED' ? cancelled(dispatched) : failure(error, dispatched, diagnostics);
|
|
173
182
|
}
|
|
174
183
|
function callbacks(value: Callbacks<I, O>): Callbacks<I, O> {
|
|
175
184
|
if (typeof value !== 'object' || value === null) {
|
|
@@ -201,10 +210,10 @@ export function useCustomMutation<I extends TObject, O extends TSchema>(options:
|
|
|
201
210
|
result = await scope.prepared.execute();
|
|
202
211
|
} catch (cause) {
|
|
203
212
|
ensure(invocation);
|
|
204
|
-
const error = failure(cause, invocation.dispatched);
|
|
213
|
+
const error = failure(cause, invocation.dispatched, scope.definition.diagnostics);
|
|
205
214
|
state = { status: 'error', isIdle: false, isPending: false, isSuccess: false, isError: true,
|
|
206
215
|
data: undefined, error, variables: scope.prepared.input };
|
|
207
|
-
observe(() => handleAuthError(copyError(error, invocation.dispatched), context,
|
|
216
|
+
observe(() => handleAuthError(copyError(error, invocation.dispatched, scope.definition.diagnostics), context,
|
|
208
217
|
() => targetCurrent(scope) && latestToken === token,
|
|
209
218
|
() => clearAuthQueries(client, scope.auth), scope.authScope));
|
|
210
219
|
throw error;
|
|
@@ -225,10 +234,11 @@ export function useCustomMutation<I extends TObject, O extends TSchema>(options:
|
|
|
225
234
|
return parseCommandResponse(scope.command, result);
|
|
226
235
|
}, (cause: unknown) => {
|
|
227
236
|
ensure(invocation);
|
|
228
|
-
const error = failure(cause, invocation.dispatched);
|
|
229
|
-
observe(() => observers.onError?.(copyError(error, invocation.dispatched), scope.prepared.input));
|
|
237
|
+
const error = failure(cause, invocation.dispatched, scope.definition.diagnostics);
|
|
238
|
+
observe(() => observers.onError?.(copyError(error, invocation.dispatched, scope.definition.diagnostics), scope.prepared.input));
|
|
230
239
|
ensure(invocation);
|
|
231
|
-
observe(() => observers.onSettled?.(undefined,
|
|
240
|
+
observe(() => observers.onSettled?.(undefined,
|
|
241
|
+
copyError(error, invocation.dispatched, scope.definition.diagnostics), scope.prepared.input));
|
|
232
242
|
ensure(invocation);
|
|
233
243
|
throw error;
|
|
234
244
|
});
|
|
@@ -247,7 +257,7 @@ export function useCustomMutation<I extends TObject, O extends TSchema>(options:
|
|
|
247
257
|
scope = capture(owner, input);
|
|
248
258
|
} catch (cause) {
|
|
249
259
|
if (!available()) return Promise.reject(cancelled(false));
|
|
250
|
-
const error = failure(cause);
|
|
260
|
+
const error = failure(cause, false, owner.definition.diagnostics);
|
|
251
261
|
const preserved = active && current(active.scope, active.token);
|
|
252
262
|
const token = preserved ? latestToken : {};
|
|
253
263
|
if (!preserved) {
|
|
@@ -264,11 +274,12 @@ export function useCustomMutation<I extends TObject, O extends TSchema>(options:
|
|
|
264
274
|
if (!targetCurrent(owner) || !owner.authScope.isCurrent() || latestToken !== token) throw cancelled(false);
|
|
265
275
|
};
|
|
266
276
|
ensure();
|
|
267
|
-
observe(() => observers.onError?.(copyError(error, false), undefined));
|
|
277
|
+
observe(() => observers.onError?.(copyError(error, false, owner.definition.diagnostics), undefined));
|
|
268
278
|
ensure();
|
|
269
|
-
observe(() => observers.onSettled?.(undefined,
|
|
279
|
+
observe(() => observers.onSettled?.(undefined,
|
|
280
|
+
copyError(error, false, owner.definition.diagnostics), undefined));
|
|
270
281
|
ensure();
|
|
271
|
-
throw copyError(error, false);
|
|
282
|
+
throw copyError(error, false, owner.definition.diagnostics);
|
|
272
283
|
});
|
|
273
284
|
}
|
|
274
285
|
if (!available()) return Promise.reject(cancelled(false));
|
|
@@ -315,7 +326,8 @@ export function useCustomMutation<I extends TObject, O extends TSchema>(options:
|
|
|
315
326
|
if (!mounted || (owner && (!targetCurrent(owner) || !owner.authScope.isCurrent()))) return idle();
|
|
316
327
|
if (state.isIdle) return state;
|
|
317
328
|
const variables = scope ? parseCommandInput(scope.command, state.variables) : undefined;
|
|
318
|
-
if (state.isError) return { ...state,
|
|
329
|
+
if (state.isError) return { ...state,
|
|
330
|
+
error: failure(state.error, scope !== undefined, owner?.definition.diagnostics), variables };
|
|
319
331
|
if (!scope || variables === undefined) return idle();
|
|
320
332
|
if (state.isSuccess) return { ...state, data: parseCommandResponse(scope.command, state.data), variables };
|
|
321
333
|
return { ...state, variables };
|
package/src/types.ts
CHANGED
|
@@ -424,6 +424,7 @@ export interface DateInputOptions {
|
|
|
424
424
|
export interface FieldDefinition {
|
|
425
425
|
key: string;
|
|
426
426
|
label: string;
|
|
427
|
+
description?: string;
|
|
427
428
|
type: 'text' | 'number' | 'boolean' | 'date' | 'time' | 'datetime' | 'daterange' | 'select' | 'multiselect' | 'tags'
|
|
428
429
|
| 'textarea' | 'richtext' | 'image' | 'images' | 'json' | 'relation' | 'color'
|
|
429
430
|
| 'url' | 'email' | 'phone' | 'currency' | 'percent' | 'file' | 'markdown' | 'password' | 'array'
|
|
@@ -22,6 +22,8 @@ export interface ContractUpdateManyOptions<S extends ContractSchemas> {
|
|
|
22
22
|
resource: ResourceContract<S>;
|
|
23
23
|
enabled?: boolean;
|
|
24
24
|
overtimeOptions?: OvertimeOptions;
|
|
25
|
+
successNotification?: false;
|
|
26
|
+
errorNotification?: false;
|
|
25
27
|
}
|
|
26
28
|
type Result<S extends ContractSchemas> = { data: ContractRecord<S>[] };
|
|
27
29
|
type Failure = HttpError | UpdateManyPartialError;
|
|
@@ -147,6 +149,7 @@ export function useContractUpdateMany<S extends ContractSchemas>(options: Contra
|
|
|
147
149
|
function notify(scope: Scope, current: () => boolean, type: 'success' | 'error', message: string): void {
|
|
148
150
|
observe(() => {
|
|
149
151
|
if (!current()) return;
|
|
152
|
+
if (type === 'success' ? options.successNotification === false : options.errorNotification === false) return;
|
|
150
153
|
if (scope.notification) return scope.notification.open({ type, message });
|
|
151
154
|
if (type === 'success') toast.success(message);
|
|
152
155
|
else toast.error(message);
|
package/src/useCan.ts
CHANGED
|
@@ -35,6 +35,8 @@ export interface UseCanResult {
|
|
|
35
35
|
readonly allowed: boolean;
|
|
36
36
|
readonly reason: string|undefined;
|
|
37
37
|
readonly isLoading: boolean;
|
|
38
|
+
/** True only when the current permission query itself failed; never exposes the error. */
|
|
39
|
+
readonly isError: boolean;
|
|
38
40
|
}
|
|
39
41
|
|
|
40
42
|
/**
|
|
@@ -130,5 +132,6 @@ export function useCan(options: () => UseCanOptions): UseCanResult {
|
|
|
130
132
|
},
|
|
131
133
|
get reason() { return query.isEnabled && query.isSuccess ? query.data?.reason : undefined; },
|
|
132
134
|
get isLoading() { return adminContext.accessControlProvider !== null && query.isLoading; },
|
|
135
|
+
get isError() { return adminContext.accessControlProvider !== null && query.isEnabled && query.isError; },
|
|
133
136
|
});
|
|
134
137
|
}
|