Skip to content

Commit c28e227

Browse files
committed
Merge remote-tracking branch 'origin/main' into release/1.0.0
2 parents 61afe0f + 418f3d2 commit c28e227

23 files changed

Lines changed: 1216 additions & 98 deletions
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { TestBed, type ComponentFixture } from '@angular/core/testing';
2+
import type { DevframeRpcClient } from 'devframe/client';
3+
import { afterEach, describe, expect, it } from 'vitest';
4+
import { AnalogInspector } from '../pages/analog-inspector';
5+
6+
const project = { analog: true, routes: [], api: [], middleware: [], content: [] };
7+
8+
function client() {
9+
const sent: Record<string, unknown>[] = [];
10+
const rpc = {
11+
call: (name: string, arg?: Record<string, unknown>) => {
12+
if (name === 'analog-project') return Promise.resolve(project);
13+
if (name === 'analog-render') return Promise.resolve({ rows: [], plan: null });
14+
if (name === 'analog-call-api') {
15+
sent.push(arg ?? {});
16+
return Promise.resolve({ status: 201, ms: 3, body: '{}' });
17+
}
18+
return Promise.resolve([]);
19+
},
20+
callEvent: () => Promise.resolve(),
21+
sharedState: () => Promise.resolve({ value: () => ({}), on: () => () => {} }),
22+
};
23+
const rpcClient = { connectionMeta: {}, scope: () => ({ rpc }) } as unknown as DevframeRpcClient;
24+
return { rpcClient, sent };
25+
}
26+
27+
async function settle(fixture: ComponentFixture<unknown>) {
28+
for (let i = 0; i < 4; i++) {
29+
await new Promise((resolve) => setTimeout(resolve));
30+
await fixture.whenStable();
31+
}
32+
}
33+
34+
async function render() {
35+
const { rpcClient, sent } = client();
36+
const fixture = TestBed.createComponent(AnalogInspector);
37+
fixture.componentRef.setInput('rpc', rpcClient);
38+
await settle(fixture);
39+
return { inspector: fixture.componentInstance, sent };
40+
}
41+
42+
afterEach(() => {
43+
document.body.innerHTML = '';
44+
});
45+
46+
describe('Analog request playground confirmation', () => {
47+
it('asks again after a confirmed POST is sent', async () => {
48+
const { inspector, sent } = await render();
49+
inspector.method.set('POST');
50+
inspector.apiPath.set('/api/v1/products');
51+
inspector.confirmSend.set(true);
52+
expect(inspector.canSend()).toBe(true);
53+
54+
await inspector.send();
55+
expect(sent).toEqual([
56+
expect.objectContaining({ method: 'POST', path: '/api/v1/products', confirm: true }),
57+
]);
58+
expect(inspector.confirmSend()).toBe(false);
59+
expect(inspector.needsConfirm()).toBe(true);
60+
61+
await inspector.send();
62+
expect(sent).toHaveLength(1);
63+
});
64+
65+
it('asks again when the method or the path changes', async () => {
66+
const { inspector } = await render();
67+
inspector.method.set('POST');
68+
inspector.apiPath.set('/api/v1/products');
69+
inspector.confirmSend.set(true);
70+
71+
inspector.apiPath.set('/api/v1/orders');
72+
expect(inspector.needsConfirm()).toBe(true);
73+
74+
inspector.confirmSend.set(true);
75+
inspector.method.set('DELETE');
76+
expect(inspector.needsConfirm()).toBe(true);
77+
});
78+
79+
it('asks again when Try loads another route', async () => {
80+
const { inspector } = await render();
81+
inspector.method.set('PUT');
82+
inspector.apiPath.set('/api/v1/products/1');
83+
inspector.confirmSend.set(true);
84+
85+
inspector.tryApi({ method: 'PUT', path: '/api/v1/orders/:id', file: 'orders.put.ts' });
86+
expect(inspector.needsConfirm()).toBe(true);
87+
});
88+
});
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import { TestBed, type ComponentFixture } from '@angular/core/testing';
2+
import { afterEach, describe, expect, it, vi } from 'vitest';
3+
4+
interface Pending {
5+
name: string;
6+
list: { id: string; enabled?: boolean }[];
7+
resolve: () => void;
8+
}
9+
10+
/** Each save waits until the test answers it, like a slow devtools server. */
11+
const pending: Pending[] = [];
12+
const sent: string[] = [];
13+
vi.mock('../rpc', () => ({
14+
rpcCall: (_rpc: unknown, name: string, list: Pending['list']) => {
15+
sent.push(name);
16+
return new Promise((resolve) => pending.push({ name, list, resolve: () => resolve(list) }));
17+
},
18+
}));
19+
20+
const { NetworkInspector } = await import('../pages/network-inspector');
21+
22+
let fixture: ComponentFixture<InstanceType<typeof NetworkInspector>>;
23+
type HttpRule = ReturnType<InstanceType<typeof NetworkInspector>['rules']>[number];
24+
25+
const rule = (id: string, pattern: string): HttpRule => ({
26+
id,
27+
pattern,
28+
method: '',
29+
target: 'client',
30+
enabled: true,
31+
});
32+
33+
const override = (id: string, pattern: string) => ({
34+
id,
35+
kind: 'client-render' as const,
36+
pattern,
37+
enabled: true,
38+
});
39+
40+
/** Lets queued saves start, then answers every save that is waiting, oldest first. */
41+
async function answerAll() {
42+
for (let i = 0; i < 10; i++) {
43+
await new Promise((resolve) => setTimeout(resolve));
44+
pending.shift()?.resolve();
45+
}
46+
await new Promise((resolve) => setTimeout(resolve));
47+
}
48+
49+
afterEach(() => {
50+
pending.length = 0;
51+
sent.length = 0;
52+
fixture?.destroy();
53+
TestBed.resetTestingModule();
54+
});
55+
56+
describe('NetworkInspector rule and override saves', () => {
57+
it('keeps both changes when two rules change before the first save answers', async () => {
58+
fixture = TestBed.createComponent(NetworkInspector);
59+
const inspector = fixture.componentInstance;
60+
inspector.rules.set([rule('a', '/api/a'), rule('b', '/api/b')]);
61+
await fixture.whenStable();
62+
63+
inspector.toggleRule('a');
64+
void inspector.removeRule('b');
65+
await answerAll();
66+
67+
expect(inspector.rules()).toEqual([{ ...rule('a', '/api/a'), enabled: false }]);
68+
});
69+
70+
it('adds a rule once when Add is pressed twice during a save', async () => {
71+
fixture = TestBed.createComponent(NetworkInspector);
72+
const inspector = fixture.componentInstance;
73+
await fixture.whenStable();
74+
inspector.setDraft('pattern', '/api/products');
75+
inspector.setDraft('status', '500');
76+
77+
const first = inspector.addRule(new Event('submit'));
78+
const second = inspector.addRule(new Event('submit'));
79+
await answerAll();
80+
await Promise.all([first, second]);
81+
82+
expect(sent).toEqual(['set-http-rules']);
83+
expect(inspector.rules().map((r) => r.pattern)).toEqual(['/api/products']);
84+
});
85+
86+
it('keeps both changes when two overrides change before the first save answers', async () => {
87+
fixture = TestBed.createComponent(NetworkInspector);
88+
const inspector = fixture.componentInstance;
89+
inspector.overrides.set([override('a', '/a'), override('b', '/b')]);
90+
await fixture.whenStable();
91+
92+
inspector.toggleOverride('a');
93+
void inspector.removeOverride('b');
94+
await answerAll();
95+
96+
expect(inspector.overrides()).toEqual([{ ...override('a', '/a'), enabled: false }]);
97+
});
98+
99+
it('adds an override once when Add is pressed twice during a save', async () => {
100+
fixture = TestBed.createComponent(NetworkInspector);
101+
const inspector = fixture.componentInstance;
102+
await fixture.whenStable();
103+
inspector.setOverrideDraft('kind', 'client-render');
104+
inspector.setOverrideDraft('pattern', '/examples/ssr');
105+
106+
const first = inspector.addOverride(new Event('submit'));
107+
const second = inspector.addOverride(new Event('submit'));
108+
await answerAll();
109+
await Promise.all([first, second]);
110+
111+
expect(sent).toEqual(['set-ssr-overrides']);
112+
expect(inspector.overrides().map((o) => o.pattern)).toEqual(['/examples/ssr']);
113+
});
114+
});
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
import { TestBed, type ComponentFixture } from '@angular/core/testing';
2+
import type { DevframeRpcClient } from 'devframe/client';
3+
import { afterEach, describe, expect, it } from 'vitest';
4+
import { travelView, type TravelSource } from '../../../src/app/devtools/travel-plugin';
5+
import { PluginsInspector } from '../pages/plugins-inspector';
6+
7+
const source = (saved = ['kyoto']): TravelSource => ({
8+
bookings: () => [
9+
{
10+
id: 'TRV-1041',
11+
destinationName: 'Kyoto',
12+
startDate: '2026-11-02',
13+
travelers: 2,
14+
total: 3120,
15+
16+
},
17+
{
18+
id: 'TRV-1042',
19+
destinationName: 'Lisbon',
20+
startDate: '2026-12-10',
21+
travelers: 1,
22+
total: 980,
23+
24+
},
25+
],
26+
saved: () => saved,
27+
recentQueries: () => ['beach'],
28+
filters: () => ({ query: '', region: 'Europe', sort: 'price' }),
29+
unsaveAll: () => {},
30+
});
31+
32+
const page = (pageId: string, extra: Record<string, unknown> = {}) => ({
33+
pageId,
34+
url: `http://localhost/${pageId}`,
35+
title: `Travel ${pageId}`,
36+
reportedAt: 5_000,
37+
plugins: [
38+
{
39+
id: 'travel',
40+
version: '1.0.0',
41+
title: 'Travel store',
42+
description: 'Bookings from the demo TravelStore.',
43+
apiVersion: 1,
44+
status: 'running',
45+
view: travelView(source()),
46+
actions: ['unsave-all'],
47+
...extra,
48+
},
49+
],
50+
});
51+
52+
function fakeClient(value: unknown, configs: Record<string, unknown> = {}) {
53+
const calls: { name: string; args: unknown[] }[] = [];
54+
const rpc = {
55+
call: (name: string, ...args: unknown[]) => {
56+
calls.push({ name, args });
57+
return Promise.resolve(name === 'request-plugin-action' ? { ok: true } : []);
58+
},
59+
callEvent: () => Promise.resolve(),
60+
sharedState: (name: string) =>
61+
Promise.resolve({
62+
value: () => (name === 'plugins' ? value : null),
63+
on: () => () => {},
64+
}),
65+
};
66+
const client = {
67+
status: 'connected',
68+
connectionMeta: { configs },
69+
scope: () => ({ rpc }),
70+
events: { on: () => () => {} },
71+
} as unknown as DevframeRpcClient;
72+
return { client, calls };
73+
}
74+
75+
async function settle(fixture: ComponentFixture<unknown>) {
76+
for (let i = 0; i < 4; i++) {
77+
await new Promise((resolve) => setTimeout(resolve));
78+
await fixture.whenStable();
79+
}
80+
}
81+
82+
const host = (fixture: ComponentFixture<unknown>) => fixture.nativeElement as HTMLElement;
83+
const text = (fixture: ComponentFixture<unknown>) =>
84+
(host(fixture).textContent ?? '').replace(/\s+/g, ' ');
85+
86+
async function mount(value: unknown, configs: Record<string, unknown> = {}) {
87+
const fixture = TestBed.createComponent(PluginsInspector);
88+
const fake = fakeClient(value, configs);
89+
fixture.componentRef.setInput('rpc', fake.client);
90+
document.body.append(host(fixture));
91+
await settle(fixture);
92+
return { fixture, calls: fake.calls };
93+
}
94+
95+
function button(fixture: ComponentFixture<unknown>, name: string): HTMLButtonElement {
96+
const found = [...host(fixture).querySelectorAll('button')].find((b) =>
97+
(b.textContent ?? '').replace(/\s+/g, ' ').trim().startsWith(name),
98+
);
99+
if (!found) throw new Error(`No button ${name}`);
100+
return found;
101+
}
102+
103+
afterEach(() => {
104+
document.body.innerHTML = '';
105+
});
106+
107+
const queryPage = (pageId: string) => ({
108+
pageId,
109+
url: `http://localhost/${pageId}`,
110+
title: `Query ${pageId}`,
111+
reportedAt: 4_000,
112+
plugins: [
113+
{
114+
id: 'query',
115+
version: '5.0.0',
116+
title: 'Query cache',
117+
status: 'running',
118+
view: {
119+
sections: [{ kind: 'text', title: 'Note', text: 'Two queries' }],
120+
actions: [{ name: 'refetch', label: 'Refetch all' }],
121+
},
122+
actions: ['refetch'],
123+
},
124+
],
125+
});
126+
127+
const actionCalls = (calls: { name: string; args: unknown[] }[]) =>
128+
calls.filter((call) => call.name === 'request-plugin-action').map((call) => call.args[0]);
129+
130+
describe('the Plugins tab confirm prompt', () => {
131+
it('drops the pending confirm and the old result when another plugin is picked', async () => {
132+
const { fixture, calls } = await mount({
133+
pages: { p1: page('p1'), p2: queryPage('p2') },
134+
server: [],
135+
});
136+
button(fixture, 'Travel store').click();
137+
await settle(fixture);
138+
fixture.componentInstance.result.set('Done.');
139+
button(fixture, 'Clear saved destinations').click();
140+
await settle(fixture);
141+
expect(text(fixture)).toContain('Remove every saved destination from the store?');
142+
143+
button(fixture, 'Query cache').click();
144+
await settle(fixture);
145+
expect(text(fixture)).not.toContain('Remove every saved destination from the store?');
146+
expect(() => button(fixture, 'Clear saved destinations')).toThrow();
147+
expect(host(fixture).querySelector('[role="status"].result')?.textContent).toBe('');
148+
149+
// Going back does not bring the old prompt back.
150+
button(fixture, 'Travel store').click();
151+
await settle(fixture);
152+
expect(text(fixture)).not.toContain('Remove every saved destination from the store?');
153+
expect(actionCalls(calls)).toEqual([]);
154+
});
155+
156+
it('drops the pending confirm when another page is picked', async () => {
157+
const { fixture, calls } = await mount({
158+
pages: { p1: page('p1'), p3: { ...page('p3'), reportedAt: 1 } },
159+
server: [],
160+
});
161+
button(fixture, 'Clear saved destinations').click();
162+
await settle(fixture);
163+
expect(text(fixture)).toContain('Remove every saved destination from the store?');
164+
165+
fixture.componentInstance.pageId.set('p3');
166+
await settle(fixture);
167+
expect(text(fixture)).not.toContain('Remove every saved destination from the store?');
168+
expect(actionCalls(calls)).toEqual([]);
169+
});
170+
171+
it('never sends an action the picked plugin does not have', async () => {
172+
const { fixture, calls } = await mount({
173+
pages: { p1: page('p1'), p2: queryPage('p2') },
174+
server: [],
175+
});
176+
expect(fixture.componentInstance.pluginId()).toBe('query');
177+
await fixture.componentInstance.run('unsave-all');
178+
expect(actionCalls(calls)).toEqual([]);
179+
await fixture.componentInstance.run('refetch');
180+
expect(actionCalls(calls)).toEqual([{ pageId: 'p2', pluginId: 'query', action: 'refetch' }]);
181+
});
182+
});

0 commit comments

Comments
 (0)