@terreno/admin-frontend 0.10.0 → 0.11.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/dist/AdminFieldRenderer.js +7 -2
- package/dist/AdminFieldRenderer.js.map +1 -1
- package/dist/AdminObjectPicker.js.map +1 -1
- package/dist/AdminPrimitiveArrayField.d.ts +26 -0
- package/dist/AdminPrimitiveArrayField.js +55 -0
- package/dist/AdminPrimitiveArrayField.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +7 -1
- package/dist/types.js.map +1 -1
- package/package.json +5 -4
- package/src/AdminFieldRenderer.test.tsx +445 -0
- package/src/AdminFieldRenderer.tsx +22 -2
- package/src/AdminModelForm.test.tsx +541 -0
- package/src/AdminModelList.test.tsx +81 -0
- package/src/AdminModelTable.test.tsx +267 -0
- package/src/AdminObjectPicker.tsx +0 -2
- package/src/AdminPrimitiveArrayField.test.tsx +186 -0
- package/src/AdminPrimitiveArrayField.tsx +186 -0
- package/src/AdminScriptList.test.tsx +49 -2
- package/src/AdminVersionConfig.test.tsx +196 -0
- package/src/CheckboxListEditor.test.tsx +80 -0
- package/src/ConfigurationScreen.test.tsx +140 -0
- package/src/ConsentFormEditor.test.tsx +512 -0
- package/src/ConsentFormList.test.tsx +115 -0
- package/src/ConsentResponseViewer.test.tsx +115 -0
- package/src/DocumentStorageBrowser.test.tsx +398 -0
- package/src/LocaleContentEditor.test.tsx +143 -0
- package/src/index.tsx +1 -0
- package/src/isolated/AdminFieldRenderer.isolated.tsx +289 -0
- package/src/isolated/AdminNestedArrayField.isolated.tsx +297 -0
- package/src/isolated/AdminObjectPicker.isolated.tsx +382 -0
- package/src/isolated/AdminRefField.isolated.tsx +29 -0
- package/src/isolated/AdminScriptRunModal.isolated.tsx +414 -0
- package/src/isolated/DocumentStorageBrowser.isolated.tsx +680 -0
- package/src/isolated/generateConsentPdf.isolated.ts +295 -0
- package/src/isolated/hooks.isolated.tsx +390 -0
- package/src/types.ts +7 -1
- package/src/AdminScriptRunModal.test.tsx +0 -69
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import {beforeEach, describe, expect, it, mock} from "bun:test";
|
|
2
|
+
|
|
3
|
+
interface JsPDFCall {
|
|
4
|
+
method: string;
|
|
5
|
+
args: unknown[];
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// All tests share this single calls array and single mock module. We toggle
|
|
9
|
+
// behavior via closure flags so the generateConsentPdf module is imported
|
|
10
|
+
// once and its coverage counters accumulate across every test.
|
|
11
|
+
const calls: JsPDFCall[] = [];
|
|
12
|
+
let imageMode: "success" | "throw" = "success";
|
|
13
|
+
let splitMode: "default" | "overflow" = "default";
|
|
14
|
+
|
|
15
|
+
class MockJsPDF {
|
|
16
|
+
constructor(_opts?: unknown) {
|
|
17
|
+
calls.push({args: [_opts], method: "ctor"});
|
|
18
|
+
}
|
|
19
|
+
addImage(...args: unknown[]) {
|
|
20
|
+
calls.push({args, method: "addImage"});
|
|
21
|
+
if (imageMode === "throw") {
|
|
22
|
+
throw new Error("bad image");
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
addPage() {
|
|
26
|
+
calls.push({args: [], method: "addPage"});
|
|
27
|
+
}
|
|
28
|
+
line(...args: unknown[]) {
|
|
29
|
+
calls.push({args, method: "line"});
|
|
30
|
+
}
|
|
31
|
+
save(...args: unknown[]) {
|
|
32
|
+
calls.push({args, method: "save"});
|
|
33
|
+
}
|
|
34
|
+
setDrawColor(...args: unknown[]) {
|
|
35
|
+
calls.push({args, method: "setDrawColor"});
|
|
36
|
+
}
|
|
37
|
+
setFont(...args: unknown[]) {
|
|
38
|
+
calls.push({args, method: "setFont"});
|
|
39
|
+
}
|
|
40
|
+
setFontSize(...args: unknown[]) {
|
|
41
|
+
calls.push({args, method: "setFontSize"});
|
|
42
|
+
}
|
|
43
|
+
setTextColor(...args: unknown[]) {
|
|
44
|
+
calls.push({args, method: "setTextColor"});
|
|
45
|
+
}
|
|
46
|
+
splitTextToSize(text: string, _width: number): string[] {
|
|
47
|
+
if (splitMode === "overflow") {
|
|
48
|
+
return Array.from({length: 200}, (_v, i) => `overflow-line-${i}`);
|
|
49
|
+
}
|
|
50
|
+
return text.split("\n");
|
|
51
|
+
}
|
|
52
|
+
text(...args: unknown[]) {
|
|
53
|
+
calls.push({args, method: "text"});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
mock.module("jspdf", () => ({jsPDF: MockJsPDF}));
|
|
58
|
+
|
|
59
|
+
// Single import of the module-under-test so all tests share coverage counters.
|
|
60
|
+
import {generateConsentPdf} from "../generateConsentPdf";
|
|
61
|
+
|
|
62
|
+
describe("generateConsentPdf", () => {
|
|
63
|
+
beforeEach(() => {
|
|
64
|
+
calls.length = 0;
|
|
65
|
+
imageMode = "success";
|
|
66
|
+
splitMode = "default";
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("generates a pdf with a populated consent response (object form + signature + checkboxes + audit trail)", async () => {
|
|
70
|
+
const longContent = Array.from({length: 120}, (_, i) => `line ${i}`).join("\n");
|
|
71
|
+
|
|
72
|
+
await generateConsentPdf({
|
|
73
|
+
_id: "response-123",
|
|
74
|
+
agreed: true,
|
|
75
|
+
agreedAt: "2024-01-15T12:00:00Z",
|
|
76
|
+
checkboxValues: {"0": true, "1": false},
|
|
77
|
+
consentFormId: {
|
|
78
|
+
slug: "privacy",
|
|
79
|
+
title: "Privacy Policy",
|
|
80
|
+
type: "legal",
|
|
81
|
+
version: 2,
|
|
82
|
+
},
|
|
83
|
+
contentSnapshot: longContent,
|
|
84
|
+
formVersionSnapshot: 2,
|
|
85
|
+
ipAddress: "127.0.0.1",
|
|
86
|
+
locale: "en",
|
|
87
|
+
signature: "data:image/png;base64,AAA",
|
|
88
|
+
signedAt: "2024-01-15T12:01:00Z",
|
|
89
|
+
userAgent: "Mozilla",
|
|
90
|
+
userId: {_id: "user-1", email: "u@x.com", name: "User"},
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const methods = calls.map((c) => c.method);
|
|
94
|
+
expect(methods).toContain("ctor");
|
|
95
|
+
expect(methods).toContain("save");
|
|
96
|
+
expect(methods).toContain("addImage");
|
|
97
|
+
// Long content should force at least one additional page.
|
|
98
|
+
expect(methods).toContain("addPage");
|
|
99
|
+
|
|
100
|
+
// Filename starts with "consent-<slug>-<last6 of id>-"
|
|
101
|
+
const saveCall = calls.find((c) => c.method === "save");
|
|
102
|
+
expect(String(saveCall?.args[0])).toMatch(/^consent-privacy-user-1-/);
|
|
103
|
+
|
|
104
|
+
// Response ID footer rendered (uses _id)
|
|
105
|
+
const textArgs = calls.filter((c) => c.method === "text").map((c) => String(c.args[0]));
|
|
106
|
+
expect(textArgs.some((t) => t.startsWith("Response ID: response-123"))).toBe(true);
|
|
107
|
+
// Locale label rendered
|
|
108
|
+
expect(textArgs.some((t) => t === "en")).toBe(true);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it("handles declined responses and string-based consentFormId/userId", async () => {
|
|
112
|
+
await generateConsentPdf({
|
|
113
|
+
agreed: false,
|
|
114
|
+
consentFormId: "legacy-string",
|
|
115
|
+
userId: "legacy-user",
|
|
116
|
+
});
|
|
117
|
+
const saveCall = calls.find((c) => c.method === "save");
|
|
118
|
+
expect(String(saveCall?.args[0])).toMatch(/^consent-response-/);
|
|
119
|
+
const textArgs = calls.filter((c) => c.method === "text").map((c) => String(c.args[0]));
|
|
120
|
+
// Decision rendered as "Declined"
|
|
121
|
+
expect(textArgs.some((t) => t === "Declined")).toBe(true);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("falls back gracefully when signature addImage throws", async () => {
|
|
125
|
+
imageMode = "throw";
|
|
126
|
+
await generateConsentPdf({
|
|
127
|
+
agreed: true,
|
|
128
|
+
signature: "data:image/jpeg;base64,BBB",
|
|
129
|
+
userId: "u1",
|
|
130
|
+
});
|
|
131
|
+
const textCalls = calls.filter((c) => c.method === "text" && typeof c.args[0] === "string");
|
|
132
|
+
const messages = textCalls.map((c) => c.args[0]);
|
|
133
|
+
expect(
|
|
134
|
+
messages.some((m) => String(m).includes("(Signature image could not be embedded)"))
|
|
135
|
+
).toBe(true);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("formats invalid dates by returning the raw value", async () => {
|
|
139
|
+
await generateConsentPdf({
|
|
140
|
+
agreed: true,
|
|
141
|
+
agreedAt: "not-a-date",
|
|
142
|
+
userId: "user-short",
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
const textCalls = calls.filter((c) => c.method === "text");
|
|
146
|
+
const rendered = textCalls.map((c) => String(c.args[0]));
|
|
147
|
+
expect(rendered.some((t) => t === "not-a-date")).toBe(true);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("formats empty/undefined date values as empty string", async () => {
|
|
151
|
+
await generateConsentPdf({
|
|
152
|
+
agreed: true,
|
|
153
|
+
agreedAt: "",
|
|
154
|
+
userId: "u",
|
|
155
|
+
});
|
|
156
|
+
expect(calls.find((c) => c.method === "save")).toBeDefined();
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it("renders agreedAt with a valid date", async () => {
|
|
160
|
+
await generateConsentPdf({
|
|
161
|
+
agreed: true,
|
|
162
|
+
agreedAt: "2024-06-15T10:30:00Z",
|
|
163
|
+
userId: "u",
|
|
164
|
+
});
|
|
165
|
+
const textArgs = calls.filter((c) => c.method === "text").map((c) => String(c.args[0]));
|
|
166
|
+
expect(textArgs.some((t) => t.includes("Agreed At:"))).toBe(true);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("covers audit trail branches independently (ipAddress only)", async () => {
|
|
170
|
+
await generateConsentPdf({
|
|
171
|
+
agreed: true,
|
|
172
|
+
ipAddress: "10.0.0.1",
|
|
173
|
+
userId: "u",
|
|
174
|
+
});
|
|
175
|
+
const textArgs = calls.filter((c) => c.method === "text").map((c) => String(c.args[0]));
|
|
176
|
+
expect(textArgs.some((t) => t.includes("Audit Trail"))).toBe(true);
|
|
177
|
+
expect(textArgs.some((t) => t === "10.0.0.1")).toBe(true);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it("covers audit trail branches independently (userAgent only)", async () => {
|
|
181
|
+
await generateConsentPdf({
|
|
182
|
+
agreed: true,
|
|
183
|
+
userAgent: "Mozilla",
|
|
184
|
+
userId: "u",
|
|
185
|
+
});
|
|
186
|
+
const textArgs = calls.filter((c) => c.method === "text").map((c) => String(c.args[0]));
|
|
187
|
+
expect(textArgs.some((t) => t === "Mozilla")).toBe(true);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it("covers audit trail branches independently (signedAt valid date)", async () => {
|
|
191
|
+
await generateConsentPdf({
|
|
192
|
+
agreed: true,
|
|
193
|
+
formVersionSnapshot: 3,
|
|
194
|
+
signedAt: "2024-02-01T10:00:00Z",
|
|
195
|
+
userId: "u",
|
|
196
|
+
});
|
|
197
|
+
const textArgs = calls.filter((c) => c.method === "text").map((c) => String(c.args[0]));
|
|
198
|
+
expect(textArgs.some((t) => t.includes("Signed At:"))).toBe(true);
|
|
199
|
+
// formVersionSnapshot renders inside the audit trail
|
|
200
|
+
expect(textArgs.some((t) => t === "3")).toBe(true);
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it("covers contentSnapshot without audit trail", async () => {
|
|
204
|
+
await generateConsentPdf({
|
|
205
|
+
agreed: true,
|
|
206
|
+
contentSnapshot: "paragraph one\nparagraph two\nparagraph three",
|
|
207
|
+
userId: "u",
|
|
208
|
+
});
|
|
209
|
+
const textArgs = calls.filter((c) => c.method === "text").map((c) => String(c.args[0]));
|
|
210
|
+
expect(textArgs.some((t) => t === "paragraph one")).toBe(true);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it("covers checkboxValues with only falsy entries and no other optional fields", async () => {
|
|
214
|
+
await generateConsentPdf({
|
|
215
|
+
agreed: false,
|
|
216
|
+
checkboxValues: {"0": false, "1": false},
|
|
217
|
+
userId: "user",
|
|
218
|
+
});
|
|
219
|
+
const textArgs = calls.filter((c) => c.method === "text").map((c) => String(c.args[0]));
|
|
220
|
+
expect(textArgs.some((t) => t.startsWith("[ ] Checkbox"))).toBe(true);
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it("handles consentFormId object with missing optional fields", async () => {
|
|
224
|
+
await generateConsentPdf({
|
|
225
|
+
agreed: true,
|
|
226
|
+
consentFormId: {} as unknown as {title?: string},
|
|
227
|
+
userId: {} as unknown as {_id?: string},
|
|
228
|
+
});
|
|
229
|
+
expect(calls.find((c) => c.method === "save")).toBeDefined();
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
it("renders a JPEG signature successfully (no throw)", async () => {
|
|
233
|
+
await generateConsentPdf({
|
|
234
|
+
_id: "id-final",
|
|
235
|
+
agreed: true,
|
|
236
|
+
signature: "data:image/jpeg;base64,ZZZ",
|
|
237
|
+
userId: "u",
|
|
238
|
+
});
|
|
239
|
+
const imgCalls = calls.filter((c) => c.method === "addImage");
|
|
240
|
+
expect(imgCalls.length).toBe(1);
|
|
241
|
+
expect(imgCalls[0].args[1]).toBe("JPEG");
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
it("renders a PNG signature successfully (no throw)", async () => {
|
|
245
|
+
await generateConsentPdf({
|
|
246
|
+
agreed: true,
|
|
247
|
+
signature: "data:image/png;base64,AAA",
|
|
248
|
+
userId: "u",
|
|
249
|
+
});
|
|
250
|
+
const imgCalls = calls.filter((c) => c.method === "addImage");
|
|
251
|
+
expect(imgCalls[0].args[1]).toBe("PNG");
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it("handles object-form userId missing _id by falling back to String(userId)", async () => {
|
|
255
|
+
const userIdObj = {email: "only@email.com"};
|
|
256
|
+
await generateConsentPdf({
|
|
257
|
+
agreed: true,
|
|
258
|
+
userId: userIdObj as unknown as {_id?: string},
|
|
259
|
+
});
|
|
260
|
+
// No crash and a save is produced; filename uses last 6 chars of
|
|
261
|
+
// String({email:...}) which is "[object Object]" → "Object]".
|
|
262
|
+
expect(calls.find((c) => c.method === "save")).toBeDefined();
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
it("renders formVersionSnapshot as Form Version when consentFormId is a string", async () => {
|
|
266
|
+
await generateConsentPdf({
|
|
267
|
+
agreed: true,
|
|
268
|
+
consentFormId: "legacy",
|
|
269
|
+
formVersionSnapshot: 7,
|
|
270
|
+
userId: "u",
|
|
271
|
+
});
|
|
272
|
+
const textArgs = calls.filter((c) => c.method === "text").map((c) => String(c.args[0]));
|
|
273
|
+
// "Form Version:" label appears in Response Details (from formVersionSnapshot)
|
|
274
|
+
expect(textArgs.some((t) => t === "Form Version:")).toBe(true);
|
|
275
|
+
expect(textArgs.some((t) => t === "7")).toBe(true);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it("adds a new page when ensureSpace needs space for content snapshot that overflows", async () => {
|
|
279
|
+
splitMode = "overflow";
|
|
280
|
+
await generateConsentPdf({
|
|
281
|
+
agreed: true,
|
|
282
|
+
checkboxValues: Object.fromEntries(
|
|
283
|
+
Array.from({length: 40}, (_v, i) => [String(i), i % 2 === 0])
|
|
284
|
+
),
|
|
285
|
+
consentFormId: {slug: "x", title: "T", type: "t", version: 1},
|
|
286
|
+
contentSnapshot: "content",
|
|
287
|
+
ipAddress: "a",
|
|
288
|
+
signedAt: "2024-01-01T00:00:00Z",
|
|
289
|
+
userAgent: "a",
|
|
290
|
+
userId: {_id: "u", email: "e@x", name: "N"},
|
|
291
|
+
});
|
|
292
|
+
const pageBreaks = calls.filter((c) => c.method === "addPage");
|
|
293
|
+
expect(pageBreaks.length).toBeGreaterThan(0);
|
|
294
|
+
});
|
|
295
|
+
});
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for admin-frontend hooks: useAdminApi, useAdminConfig,
|
|
3
|
+
* useAdminScripts, useConfigurationApi, useDocumentStorageApi.
|
|
4
|
+
*
|
|
5
|
+
* These hooks all inject RTK Query endpoints into a provided Api instance,
|
|
6
|
+
* and expose generated RTK hooks by name. We assert:
|
|
7
|
+
* - the right endpoint keys are injected with expected method/url shapes
|
|
8
|
+
* - the returned hook functions correspond to the generated hook names
|
|
9
|
+
*/
|
|
10
|
+
import {describe, expect, it, mock} from "bun:test";
|
|
11
|
+
import {renderWithTheme} from "@terreno/ui/src/test-utils";
|
|
12
|
+
import React from "react";
|
|
13
|
+
import {useAdminApi} from "../useAdminApi";
|
|
14
|
+
import {useAdminConfig} from "../useAdminConfig";
|
|
15
|
+
import {useAdminScripts} from "../useAdminScripts";
|
|
16
|
+
import {useConfigurationApi} from "../useConfigurationApi";
|
|
17
|
+
import {useDocumentStorageApi} from "../useDocumentStorageApi";
|
|
18
|
+
|
|
19
|
+
interface BuildSpec {
|
|
20
|
+
query?: (arg?: unknown) => unknown;
|
|
21
|
+
mutation?: (arg?: unknown) => unknown;
|
|
22
|
+
providesTags?: unknown;
|
|
23
|
+
invalidatesTags?: unknown;
|
|
24
|
+
extraOptions?: unknown;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface CapturedEndpoints {
|
|
28
|
+
[key: string]: BuildSpec;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const makeMockApi = () => {
|
|
32
|
+
const injected: CapturedEndpoints = {};
|
|
33
|
+
const enhancedTagTypes: string[] = [];
|
|
34
|
+
|
|
35
|
+
const fakeHooks: Record<string, any> = {};
|
|
36
|
+
|
|
37
|
+
const addHookFor = (key: string, type: "query" | "mutation") => {
|
|
38
|
+
const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
39
|
+
const hookName = type === "query" ? `use${cap(key)}Query` : `use${cap(key)}Mutation`;
|
|
40
|
+
const lazyHookName = `useLazy${cap(key)}Query`;
|
|
41
|
+
fakeHooks[hookName] = mock(() =>
|
|
42
|
+
type === "query"
|
|
43
|
+
? {data: undefined, error: null, isLoading: false}
|
|
44
|
+
: [mock(() => ({unwrap: async () => ({})})), {isLoading: false}]
|
|
45
|
+
);
|
|
46
|
+
if (type === "query") {
|
|
47
|
+
fakeHooks[lazyHookName] = mock(() => [
|
|
48
|
+
mock(() => ({unwrap: async () => ({})})),
|
|
49
|
+
{data: undefined, isLoading: false},
|
|
50
|
+
]);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const base: any = {};
|
|
55
|
+
Object.defineProperty(base, "__fakeHooks", {value: fakeHooks});
|
|
56
|
+
Object.defineProperty(base, "__injected", {value: injected});
|
|
57
|
+
Object.defineProperty(base, "__tagTypes", {value: enhancedTagTypes});
|
|
58
|
+
|
|
59
|
+
const apiProxy: any = new Proxy(base, {
|
|
60
|
+
get(target, prop: string) {
|
|
61
|
+
if (prop === "enhanceEndpoints") {
|
|
62
|
+
return ({addTagTypes}: {addTagTypes: string[]}) => {
|
|
63
|
+
enhancedTagTypes.push(...addTagTypes);
|
|
64
|
+
return apiProxy;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
if (prop === "injectEndpoints") {
|
|
68
|
+
return ({endpoints}: {endpoints: (build: any) => Record<string, BuildSpec>}) => {
|
|
69
|
+
const build = {
|
|
70
|
+
mutation: (spec: BuildSpec) => ({...spec, __kind: "mutation"}),
|
|
71
|
+
query: (spec: BuildSpec) => ({...spec, __kind: "query"}),
|
|
72
|
+
};
|
|
73
|
+
const defs = endpoints(build);
|
|
74
|
+
for (const [key, def] of Object.entries(defs)) {
|
|
75
|
+
injected[key] = def;
|
|
76
|
+
const kind = (def as any).__kind === "mutation" ? "mutation" : "query";
|
|
77
|
+
addHookFor(key, kind);
|
|
78
|
+
}
|
|
79
|
+
return apiProxy;
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
if (prop in target) {
|
|
83
|
+
return target[prop];
|
|
84
|
+
}
|
|
85
|
+
if (prop in fakeHooks) {
|
|
86
|
+
return fakeHooks[prop];
|
|
87
|
+
}
|
|
88
|
+
return undefined;
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
return apiProxy;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const runHook = <T,>(fn: () => T): T => {
|
|
96
|
+
let captured: T | undefined;
|
|
97
|
+
const Probe = () => {
|
|
98
|
+
captured = fn();
|
|
99
|
+
return null;
|
|
100
|
+
};
|
|
101
|
+
renderWithTheme(<Probe />);
|
|
102
|
+
return captured as T;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
describe("useAdminApi", () => {
|
|
106
|
+
it("injects list/read/create/update/delete endpoints with admin tag", () => {
|
|
107
|
+
const api = makeMockApi();
|
|
108
|
+
const result = runHook(() => useAdminApi(api, "/admin/users", "User"));
|
|
109
|
+
|
|
110
|
+
const injected = (api as any).__injected as CapturedEndpoints;
|
|
111
|
+
expect(injected.adminList_User).toBeDefined();
|
|
112
|
+
expect(injected.adminRead_User).toBeDefined();
|
|
113
|
+
expect(injected.adminCreate_User).toBeDefined();
|
|
114
|
+
expect(injected.adminUpdate_User).toBeDefined();
|
|
115
|
+
expect(injected.adminDelete_User).toBeDefined();
|
|
116
|
+
|
|
117
|
+
// tag types include the admin_<model>
|
|
118
|
+
expect((api as any).__tagTypes).toContain("admin_User");
|
|
119
|
+
|
|
120
|
+
// Each endpoint's query fn produces expected URL/method
|
|
121
|
+
const listDef: any = injected.adminList_User;
|
|
122
|
+
expect(listDef.query({limit: 1})).toEqual({
|
|
123
|
+
method: "GET",
|
|
124
|
+
params: {limit: 1},
|
|
125
|
+
url: "/admin/users",
|
|
126
|
+
});
|
|
127
|
+
expect(listDef.query(undefined)).toEqual({
|
|
128
|
+
method: "GET",
|
|
129
|
+
params: {},
|
|
130
|
+
url: "/admin/users",
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
const readDef: any = injected.adminRead_User;
|
|
134
|
+
expect(readDef.query("abc")).toEqual({
|
|
135
|
+
method: "GET",
|
|
136
|
+
url: "/admin/users/abc",
|
|
137
|
+
});
|
|
138
|
+
expect(readDef.providesTags(null, null, "abc")).toEqual([{id: "abc", type: "admin_User"}]);
|
|
139
|
+
|
|
140
|
+
const createDef: any = injected.adminCreate_User;
|
|
141
|
+
expect(createDef.query({name: "x"})).toEqual({
|
|
142
|
+
body: {name: "x"},
|
|
143
|
+
method: "POST",
|
|
144
|
+
url: "/admin/users",
|
|
145
|
+
});
|
|
146
|
+
expect(createDef.invalidatesTags).toEqual(["admin_User"]);
|
|
147
|
+
|
|
148
|
+
const updateDef: any = injected.adminUpdate_User;
|
|
149
|
+
expect(updateDef.query({body: {x: 1}, id: "123"})).toEqual({
|
|
150
|
+
body: {x: 1},
|
|
151
|
+
method: "PATCH",
|
|
152
|
+
url: "/admin/users/123",
|
|
153
|
+
});
|
|
154
|
+
expect(updateDef.invalidatesTags(null, null, {id: "123"})).toEqual([
|
|
155
|
+
{id: "123", type: "admin_User"},
|
|
156
|
+
"admin_User",
|
|
157
|
+
]);
|
|
158
|
+
|
|
159
|
+
const deleteDef: any = injected.adminDelete_User;
|
|
160
|
+
expect(deleteDef.query("123")).toEqual({
|
|
161
|
+
method: "DELETE",
|
|
162
|
+
url: "/admin/users/123",
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
// Returned hooks should be functions (generated by our mock)
|
|
166
|
+
expect(typeof result.useListQuery).toBe("function");
|
|
167
|
+
expect(typeof result.useReadQuery).toBe("function");
|
|
168
|
+
expect(typeof result.useCreateMutation).toBe("function");
|
|
169
|
+
expect(typeof result.useUpdateMutation).toBe("function");
|
|
170
|
+
expect(typeof result.useDeleteMutation).toBe("function");
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
describe("useAdminConfig", () => {
|
|
175
|
+
it("injects adminConfig query and exposes config hook data", () => {
|
|
176
|
+
const api = makeMockApi();
|
|
177
|
+
const result = runHook(() => useAdminConfig(api, "/admin"));
|
|
178
|
+
|
|
179
|
+
const injected = (api as any).__injected as CapturedEndpoints;
|
|
180
|
+
expect(injected.adminConfig).toBeDefined();
|
|
181
|
+
const def: any = injected.adminConfig;
|
|
182
|
+
expect(def.query()).toEqual({method: "GET", url: "/admin/config"});
|
|
183
|
+
|
|
184
|
+
expect(result).toMatchObject({
|
|
185
|
+
config: undefined,
|
|
186
|
+
error: null,
|
|
187
|
+
isLoading: false,
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
describe("useAdminScripts", () => {
|
|
193
|
+
it("injects run/get/cancel task endpoints", () => {
|
|
194
|
+
const api = makeMockApi();
|
|
195
|
+
const result = runHook(() => useAdminScripts(api, "/admin"));
|
|
196
|
+
|
|
197
|
+
const injected = (api as any).__injected as CapturedEndpoints;
|
|
198
|
+
expect(injected.adminRunScript).toBeDefined();
|
|
199
|
+
expect(injected.adminGetScriptTask).toBeDefined();
|
|
200
|
+
expect(injected.adminCancelScriptTask).toBeDefined();
|
|
201
|
+
|
|
202
|
+
const runDef: any = injected.adminRunScript;
|
|
203
|
+
expect(runDef.query({name: "migrate", wetRun: false})).toEqual({
|
|
204
|
+
method: "POST",
|
|
205
|
+
url: "/admin/scripts/migrate/run?wetRun=false",
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
const getDef: any = injected.adminGetScriptTask;
|
|
209
|
+
expect(getDef.query("task-1")).toEqual({
|
|
210
|
+
method: "GET",
|
|
211
|
+
url: "/admin/scripts/tasks/task-1",
|
|
212
|
+
});
|
|
213
|
+
expect(getDef.providesTags).toEqual(["admin_scriptTask"]);
|
|
214
|
+
|
|
215
|
+
const cancelDef: any = injected.adminCancelScriptTask;
|
|
216
|
+
expect(cancelDef.query("task-1")).toEqual({
|
|
217
|
+
method: "DELETE",
|
|
218
|
+
url: "/admin/scripts/tasks/task-1",
|
|
219
|
+
});
|
|
220
|
+
expect(cancelDef.invalidatesTags).toEqual(["admin_scriptTask"]);
|
|
221
|
+
|
|
222
|
+
expect(typeof result.useRunScriptMutation).toBe("function");
|
|
223
|
+
expect(typeof result.useGetScriptTaskQuery).toBe("function");
|
|
224
|
+
expect(typeof result.useCancelScriptTaskMutation).toBe("function");
|
|
225
|
+
});
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
describe("useConfigurationApi", () => {
|
|
229
|
+
it("injects meta/values/update/refresh-secrets endpoints", () => {
|
|
230
|
+
const api = makeMockApi();
|
|
231
|
+
const result = runHook(() => useConfigurationApi({api, basePath: "/admin/configuration"}));
|
|
232
|
+
|
|
233
|
+
const injected = (api as any).__injected as CapturedEndpoints;
|
|
234
|
+
expect(injected.configMeta).toBeDefined();
|
|
235
|
+
expect(injected.configValues).toBeDefined();
|
|
236
|
+
expect(injected.configUpdate).toBeDefined();
|
|
237
|
+
expect(injected.configRefreshSecrets).toBeDefined();
|
|
238
|
+
expect((api as any).__tagTypes).toContain("configuration");
|
|
239
|
+
|
|
240
|
+
expect((injected.configMeta as any).query()).toEqual({
|
|
241
|
+
method: "GET",
|
|
242
|
+
url: "/admin/configuration/meta",
|
|
243
|
+
});
|
|
244
|
+
expect((injected.configValues as any).query()).toEqual({
|
|
245
|
+
method: "GET",
|
|
246
|
+
url: "/admin/configuration",
|
|
247
|
+
});
|
|
248
|
+
expect((injected.configValues as any).providesTags).toEqual(["configuration"]);
|
|
249
|
+
expect((injected.configUpdate as any).query({a: 1})).toEqual({
|
|
250
|
+
body: {a: 1},
|
|
251
|
+
method: "PATCH",
|
|
252
|
+
url: "/admin/configuration",
|
|
253
|
+
});
|
|
254
|
+
expect((injected.configUpdate as any).invalidatesTags).toEqual(["configuration"]);
|
|
255
|
+
expect((injected.configRefreshSecrets as any).query()).toEqual({
|
|
256
|
+
method: "POST",
|
|
257
|
+
url: "/admin/configuration/refresh-secrets",
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
expect(typeof result.useMetaQuery).toBe("function");
|
|
261
|
+
expect(typeof result.useValuesQuery).toBe("function");
|
|
262
|
+
expect(typeof result.useUpdateMutation).toBe("function");
|
|
263
|
+
expect(typeof result.useRefreshSecretsMutation).toBe("function");
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
describe("useDocumentStorageApi", () => {
|
|
268
|
+
it("injects list/upload/download/delete/folder endpoints", () => {
|
|
269
|
+
const api = makeMockApi();
|
|
270
|
+
const result = runHook(() => useDocumentStorageApi(api, "/documents"));
|
|
271
|
+
|
|
272
|
+
const injected = (api as any).__injected as CapturedEndpoints;
|
|
273
|
+
expect(injected.documentStorageList).toBeDefined();
|
|
274
|
+
expect(injected.documentStorageUpload).toBeDefined();
|
|
275
|
+
expect(injected.documentStorageDownload).toBeDefined();
|
|
276
|
+
expect(injected.documentStorageDelete).toBeDefined();
|
|
277
|
+
expect(injected.documentStorageDeleteFolder).toBeDefined();
|
|
278
|
+
expect(injected.documentStorageCreateFolder).toBeDefined();
|
|
279
|
+
|
|
280
|
+
const listDef: any = injected.documentStorageList;
|
|
281
|
+
expect(listDef.query()).toEqual({
|
|
282
|
+
method: "GET",
|
|
283
|
+
params: {},
|
|
284
|
+
url: "/documents/",
|
|
285
|
+
});
|
|
286
|
+
expect(listDef.query("my/folder")).toEqual({
|
|
287
|
+
method: "GET",
|
|
288
|
+
params: {prefix: "my/folder"},
|
|
289
|
+
url: "/documents/",
|
|
290
|
+
});
|
|
291
|
+
expect(listDef.providesTags).toEqual(["documentStorage"]);
|
|
292
|
+
|
|
293
|
+
// Upload appends prefix to formData when provided
|
|
294
|
+
const uploadDef: any = injected.documentStorageUpload;
|
|
295
|
+
const fd: {append: (k: string, v: string) => void; entries: string[]} = {
|
|
296
|
+
append(k: string, v: string) {
|
|
297
|
+
this.entries.push(`${k}=${v}`);
|
|
298
|
+
},
|
|
299
|
+
entries: [],
|
|
300
|
+
};
|
|
301
|
+
const uploadWithPrefix = uploadDef.query({
|
|
302
|
+
formData: fd as unknown as FormData,
|
|
303
|
+
prefix: "sub/",
|
|
304
|
+
});
|
|
305
|
+
expect(uploadWithPrefix).toMatchObject({
|
|
306
|
+
method: "POST",
|
|
307
|
+
url: "/documents/",
|
|
308
|
+
});
|
|
309
|
+
expect(fd.entries).toContain("prefix=sub/");
|
|
310
|
+
|
|
311
|
+
const fd2: {append: (k: string, v: string) => void; entries: string[]} = {
|
|
312
|
+
append(k: string, v: string) {
|
|
313
|
+
this.entries.push(`${k}=${v}`);
|
|
314
|
+
},
|
|
315
|
+
entries: [],
|
|
316
|
+
};
|
|
317
|
+
uploadDef.query({formData: fd2 as unknown as FormData});
|
|
318
|
+
expect(fd2.entries.length).toBe(0);
|
|
319
|
+
|
|
320
|
+
// Download returns a URL with encoded path and a responseHandler
|
|
321
|
+
const downloadDef: any = injected.documentStorageDownload;
|
|
322
|
+
const dlSpec = downloadDef.query("my folder/file.pdf");
|
|
323
|
+
expect(dlSpec.url).toBe("/documents/download/my%20folder%2Ffile.pdf");
|
|
324
|
+
expect(dlSpec.method).toBe("GET");
|
|
325
|
+
expect(typeof dlSpec.responseHandler).toBe("function");
|
|
326
|
+
|
|
327
|
+
// responseHandler returns the blob on ok
|
|
328
|
+
const okBlob = {size: 5, type: "text/plain"};
|
|
329
|
+
const okResp = {
|
|
330
|
+
blob: async () => okBlob,
|
|
331
|
+
headers: {get: () => "text/plain"},
|
|
332
|
+
ok: true,
|
|
333
|
+
status: 200,
|
|
334
|
+
statusText: "OK",
|
|
335
|
+
};
|
|
336
|
+
return dlSpec.responseHandler(okResp).then(async (blob: unknown) => {
|
|
337
|
+
expect(blob).toBe(okBlob);
|
|
338
|
+
|
|
339
|
+
// non-ok JSON response
|
|
340
|
+
const errJson = '{"detail":"Bad","status":400}';
|
|
341
|
+
const jsonResp = {
|
|
342
|
+
headers: {get: () => "application/json"},
|
|
343
|
+
ok: false,
|
|
344
|
+
status: 400,
|
|
345
|
+
statusText: "Bad Request",
|
|
346
|
+
text: async () => errJson,
|
|
347
|
+
};
|
|
348
|
+
const parsed = await dlSpec.responseHandler(jsonResp);
|
|
349
|
+
expect(parsed).toEqual({detail: "Bad", status: 400});
|
|
350
|
+
|
|
351
|
+
// non-ok non-JSON response (fallback)
|
|
352
|
+
const textResp = {
|
|
353
|
+
headers: {get: () => "text/plain"},
|
|
354
|
+
ok: false,
|
|
355
|
+
status: 500,
|
|
356
|
+
statusText: "err",
|
|
357
|
+
text: async () => "boom",
|
|
358
|
+
};
|
|
359
|
+
const textParsed = await dlSpec.responseHandler(textResp);
|
|
360
|
+
expect(textParsed).toEqual({detail: "boom", status: 500});
|
|
361
|
+
|
|
362
|
+
// Delete endpoints
|
|
363
|
+
const deleteDef: any = injected.documentStorageDelete;
|
|
364
|
+
expect(deleteDef.query("a b.pdf")).toEqual({
|
|
365
|
+
method: "DELETE",
|
|
366
|
+
url: "/documents/a%20b.pdf",
|
|
367
|
+
});
|
|
368
|
+
const deleteFolderDef: any = injected.documentStorageDeleteFolder;
|
|
369
|
+
expect(deleteFolderDef.query("subdir/")).toEqual({
|
|
370
|
+
method: "DELETE",
|
|
371
|
+
url: "/documents/folder/subdir%2F",
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
const createDef: any = injected.documentStorageCreateFolder;
|
|
375
|
+
expect(createDef.query({folderName: "new", prefix: "a/"})).toEqual({
|
|
376
|
+
body: {folderName: "new", prefix: "a/"},
|
|
377
|
+
method: "POST",
|
|
378
|
+
url: "/documents/folder",
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
// Hooks exposed
|
|
382
|
+
expect(typeof result.useListQuery).toBe("function");
|
|
383
|
+
expect(typeof result.useUploadMutation).toBe("function");
|
|
384
|
+
expect(typeof result.useLazyDownloadQuery).toBe("function");
|
|
385
|
+
expect(typeof result.useDeleteMutation).toBe("function");
|
|
386
|
+
expect(typeof result.useDeleteFolderMutation).toBe("function");
|
|
387
|
+
expect(typeof result.useCreateFolderMutation).toBe("function");
|
|
388
|
+
});
|
|
389
|
+
});
|
|
390
|
+
});
|
package/src/types.ts
CHANGED
|
@@ -9,8 +9,14 @@ export interface AdminFieldConfig {
|
|
|
9
9
|
ref?: string;
|
|
10
10
|
searchable?: boolean;
|
|
11
11
|
widget?: string;
|
|
12
|
-
/** For array fields: metadata about each item's sub-fields */
|
|
12
|
+
/** For array fields of sub-documents: metadata about each item's sub-fields */
|
|
13
13
|
items?: Record<string, AdminFieldConfig>;
|
|
14
|
+
/** For array fields of primitives: the item type (string/number/boolean/objectid) */
|
|
15
|
+
itemType?: string;
|
|
16
|
+
/** For array fields of primitives: enum values for each item */
|
|
17
|
+
itemEnum?: string[];
|
|
18
|
+
/** For array fields of ObjectId refs: the referenced model name */
|
|
19
|
+
itemRef?: string;
|
|
14
20
|
}
|
|
15
21
|
|
|
16
22
|
export interface AdminModelConfig {
|