Skip to content

Commit

Permalink
Merge branch 'develop' into perf/poor-network-improvement
Browse files Browse the repository at this point in the history
  • Loading branch information
CurryYangxx authored May 29, 2024
2 parents 2070f38 + 55440c7 commit d39a4e9
Show file tree
Hide file tree
Showing 16 changed files with 166 additions and 73 deletions.
24 changes: 24 additions & 0 deletions packages/insomnia-sdk/src/objects/__tests__/environments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it } from '@jest/globals';
import { validate } from 'uuid';

import { Environment, Variables } from '../environments';

describe('test Variables object', () => {
it('test basic operations', () => {
const variables = new Variables({
globals: new Environment('globals', { value: '777' }),
environment: new Environment('environments', {}),
collection: new Environment('baseEnvironment', {}),
data: new Environment('iterationData', {}),
});

const uuidAnd777 = variables.replaceIn('{{ $randomUUID }}{{value }}');
expect(validate(uuidAnd777.replace('777', ''))).toBeTruthy();

const uuidAndBrackets1 = variables.replaceIn('{{ $randomUUID }}}}');
expect(validate(uuidAndBrackets1.replace('}}', ''))).toBeTruthy();

const uuidAndBrackets2 = variables.replaceIn('}}{{ $randomUUID }}');
expect(validate(uuidAndBrackets2.replace('}}', ''))).toBeTruthy();
});
});
38 changes: 37 additions & 1 deletion packages/insomnia-sdk/src/objects/interpolator.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { fakerFunctions } from 'insomnia/src/ui/components/templating/faker-functions';
import { configure, type ConfigureOptions, type Environment as NunjuncksEnv } from 'nunjucks';

class Intepolator {
Expand All @@ -10,7 +11,42 @@ class Intepolator {
render = (template: string, context: object) => {
// TODO: handle timeout
// TODO: support plugin?
return this.engine.renderString(template, context);
return this.engine.renderString(
this.renderWithFaker(template),
context
);
};

renderWithFaker = (template: string) => {
const segments = template.split('}}');
if (segments.length === 1) {
return template;
}

const translatedSegments = segments.map(segment => {
const tagStart = segment.lastIndexOf('{{');
if ((tagStart) < 0) {
return segment;
}

const tagName = segment
.slice(tagStart + 2)
.trim();
if (!tagName.startsWith('$')) {
// it is a tag probably for interpolating, at least not for generating
return segment + '}}';
}
const funcName = tagName.slice(1) as keyof typeof fakerFunctions; // remove prefix '$'

if (!fakerFunctions[funcName]) {
throw Error(`replaceIn: no faker function is found: ${funcName}`);
};

const generated = fakerFunctions[funcName]();
return segment.slice(0, tagStart) + generated;
});

return translatedSegments.join('');
};
}

Expand Down
4 changes: 2 additions & 2 deletions packages/insomnia-smoke-test/fixtures/oauth.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ resources:
environmentPropertyOrder: null
metaSortKey: -1715935256495
preRequestScript: ""
postRequestScript: ""
afterResponseScript: ""
authentication: {}
_type: request_group
- _id: fld_e45987966c224b63b68b09b34687209c
Expand All @@ -51,7 +51,7 @@ resources:
environmentPropertyOrder: null
metaSortKey: -1715935030239
preRequestScript: ""
postRequestScript: ""
afterResponseScript: ""
authentication:
accessTokenUrl: "http://127.0.0.1:4010/oidc/token"
authorizationUrl: "http://127.0.0.1:4010/oidc/auth"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ test('can send request with custom ca root certificate', async ({ app, page }) =

await page.getByLabel('Request Collection').getByTestId('sends request with certs').press('Enter');

await page.getByRole('button', { name: 'Send' }).click();
await page.getByRole('button', { name: 'Send', exact: true }).click();
await page.getByText('Error: SSL peer certificate or SSH remote key was not OK').click();

const fixturePath = getFixturePath('certificates');
Expand All @@ -32,7 +32,7 @@ test('can send request with custom ca root certificate', async ({ app, page }) =
await page.getByRole('button', { name: 'Done' }).click();

// test request with certs
await page.getByRole('button', { name: 'Send' }).click();
await page.getByRole('button', { name: 'Send', exact: true }).click();
await page.getByText('200 OK').click();
await page.locator('pre').filter({ hasText: '"id": "1"' }).click();
});
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ test('Command palette - can switch between requests and workspaces', async ({ ap
await page.getByRole('dialog').getByRole('button', { name: 'Import' }).click();

await page.getByLabel('Smoke tests').click();
await page.getByTestId('sends request with cookie and get cookie in response').getByLabel('request name').click();
await page.getByTestId('sends request with cookie and get cookie in response').getByText('GET', { exact: true }).click();
await page.getByTestId('OneLineEditor').getByText('http://127.0.0.1:4010/cookies').click();
const requestSwitchKeyboardShortcut = process.platform === 'darwin' ? 'Meta+p' : 'Control+p';
await page.locator('body').press(requestSwitchKeyboardShortcut);
await page.getByPlaceholder('Search and switch between').fill('send js');
await page.getByPlaceholder('Search and switch between').press('ArrowDown');
await page.getByPlaceholder('Search and switch between').press('Enter');
await page.getByTestId('OneLineEditor').getByText('http://127.0.0.1:4010/pets/').click();
await page.getByRole('button', { name: 'Send' }).click();
await page.getByRole('button', { name: 'Send', exact: true }).click();
await page.getByText('200 OK').click();

await page.locator('body').press(requestSwitchKeyboardShortcut);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,10 @@ test.describe('Debug-Sidebar', async () => {
});

test('Rename a request by clicking', async ({ page }) => {
await page.getByTestId('example http').getByLabel('request name').dblclick();
await page.getByRole('textbox', { name: 'request name' }).fill('new name');
await page.getByTestId('example http').getByLabel('GET example http', { exact: true }).dblclick();
await page.getByRole('textbox', { name: 'GET example http' }).fill('new name');
await page.getByLabel('Request Collection').click();
await expect(page.getByTestId('new name').getByLabel('request name')).toContainText('new name');
await expect(page.getByTestId('new name').getByLabel('GET new name', { exact: true })).toContainText('new name');
});

test('Create a new HTTP request', async ({ page }) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,27 @@ test.describe('test hidden window handling', async () => {

await page.getByText('Pre-request Scripts').click();
await page.getByLabel('Request Collection').getByTestId('Long running task').press('Enter');
await page.getByTestId('request-pane').getByRole('button', { name: 'Send' }).click();
await page.getByTestId('request-pane').getByRole('button', { name: 'Send', exact: true }).click();

await page.waitForSelector('[data-testid="response-status-tag"]:visible');

await page.getByText('Timeout: Running script took too long').click();
expect(await page.locator('.pane-two pre').innerText()).toEqual('Timeout: Running script took too long');
await page.getByRole('tab', { name: 'Timeline' }).click();
await page.getByRole('tab', { name: 'Preview ' }).click();
const windows = await app.windows();
const hiddenWindow = windows[1];
hiddenWindow.close();
await page.getByRole('button', { name: 'Send' }).click();
// as the hidden window is restarted, it should not show "Timeout: Hidden browser window is not responding"
await page.getByText('Timeout: Running script took too long').click();

await page.getByTestId('settings-button').click();
await page.getByLabel('Request timeout (ms)').fill('6000');
await page.getByRole('button', { name: '' }).click();

await page.getByTestId('request-pane').getByRole('button', { name: 'Send' }).click();

// it should still work
const statusTag = page.locator('[data-testid="response-status-tag"]:visible');
await page.waitForSelector('[data-testid="response-status-tag"]:visible');
await expect(statusTag).toContainText('200 OK');
});

test('window should be restarted if it hangs', async ({ app, page }) => {
Expand All @@ -77,56 +87,22 @@ test.describe('test hidden window handling', async () => {

// update timeout
await page.getByTestId('settings-button').click();
await page.getByLabel('Request timeout (ms)').fill('100');
await page.getByLabel('Request timeout (ms)').fill('1000');
await page.getByRole('button', { name: '' }).click();

// send the request with infinite loop script
await page.getByText('Pre-request Scripts').click();
await page.getByLabel('Request Collection').getByTestId('infinite loop').press('Enter');
await page.getByTestId('request-pane').getByRole('button', { name: 'Send' }).click();
await page.getByTestId('request-pane').getByRole('button', { name: 'Send', exact: true }).click();
await page.getByText('Timeout: Hidden browser window is not responding').click();

// send the another script with normal script
await page.getByLabel('Request Collection').getByTestId('simple log').press('Enter');
await page.getByTestId('request-pane').getByRole('button', { name: 'Send' }).click();
await page.getByTestId('request-pane').getByRole('button', { name: 'Send', exact: true }).click();

// it should still work
const statusTag = page.locator('[data-testid="response-status-tag"]:visible');
await page.waitForSelector('[data-testid="response-status-tag"]:visible');
await expect(statusTag).toContainText('200 OK');
});
});

test('window should be restarted if it hangs', async ({ app, page }) => {
test.slow(process.platform === 'darwin' || process.platform === 'win32', 'Slow app start on these platforms');

// load collection
const text = await loadFixture('pre-request-collection.yaml');
await app.evaluate(async ({ clipboard }, text) => clipboard.writeText(text), text);

await page.getByRole('button', { name: 'Create in project' }).click();
await page.getByRole('menuitemradio', { name: 'Import' }).click();
await page.locator('[data-test-id="import-from-clipboard"]').click();
await page.getByRole('button', { name: 'Scan' }).click();
await page.getByRole('dialog').getByRole('button', { name: 'Import' }).click();

// update timeout
await page.getByTestId('settings-button').click();
await page.getByLabel('Request timeout (ms)').fill('100');
await page.getByRole('button', { name: '' }).click();

// send the request with infinite loop script
await page.getByText('Pre-request Scripts').click();
await page.getByLabel('Request Collection').getByTestId('infinite loop').press('Enter');
await page.getByTestId('request-pane').getByRole('button', { name: 'Send' }).click();
await page.getByText('Timeout: Hidden browser window is not responding').click();

// send the another script with normal script
await page.getByLabel('Request Collection').getByTestId('simple log').press('Enter');
await page.getByTestId('request-pane').getByRole('button', { name: 'Send' }).click();

// it should still work
const statusTag = page.locator('[data-testid="response-status-tag"]:visible');
await page.waitForSelector('[data-testid="response-status-tag"]:visible');
await expect(statusTag).toContainText('200 OK');
});
4 changes: 2 additions & 2 deletions packages/insomnia/src/models/request-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ interface BaseRequestGroup {
environmentPropertyOrder: Record<string, any> | null;
metaSortKey: number;
preRequestScript: string;
postRequestScript: string;
afterResponseScript: string;
authentication?: RequestAuthentication | {};
headers?: RequestHeader[];
}
Expand All @@ -37,7 +37,7 @@ export function init(): BaseRequestGroup {
environmentPropertyOrder: null,
metaSortKey: -1 * Date.now(),
preRequestScript: '',
postRequestScript: '',
afterResponseScript: '',
authentication: {},
headers: [],
};
Expand Down
2 changes: 1 addition & 1 deletion packages/insomnia/src/network/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ export const tryToExecuteScript = async (context: RequestAndContextAndOptionalRe
reject(new Error('Timeout: Hidden browser window is not responding'));
// Add one extra second to ensure the hidden browser window has had a chance to return its timeout
// TODO: restart the hidden browser window
}, timeout + 1000);
}, timeout + 2000);
});
// const isBaseEnvironmentSelected = environment._id === baseEnvironment._id;
// if (isBaseEnvironmentSelected) {
Expand Down
1 change: 1 addition & 0 deletions packages/insomnia/src/ui/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export enum SegmentEvent {
dataExport = 'Data Exported',
dataImport = 'Data Imported',
documentCreate = 'Document Created',
mockCreate = 'Mock Created',
exportAllCollections = 'Exported All Collections',
kongConnected = 'Kong Connected',
kongSync = 'Kong Synced',
Expand Down
41 changes: 39 additions & 2 deletions packages/insomnia/src/ui/auth-session-provider.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { decodeBase64, encodeBase64 } from '@getinsomnia/api-client/base64';
import { keyPair, open } from '@getinsomnia/api-client/sealedbox';

import * as session from '../account/session';
Expand Down Expand Up @@ -29,6 +28,43 @@ encodeBase64(sessionKeyPair.secretKey).then(res => {
* Keypair used for the login handshake.
* This keypair can be re-used for the entire session.
*/

export async function decodeBase64(base64: string): Promise<Uint8Array> {
try {
let uri = 'data:application/octet-binary;base64,';
uri += base64;
const res = await fetch(uri);
const buffer = await res.arrayBuffer();
return new Uint8Array(buffer);

} catch (error) {
console.error(error);
throw new Error('Failed to decode base64');
}
}

export async function encodeBase64(data: Uint8Array): Promise<string> {
const dataUri = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
if (typeof reader.result === 'string') {
resolve(reader.result);
} else {
reject();
}
};
reader.onerror = reject;
reader.readAsDataURL(new Blob([data]));
});

const dataAt = dataUri.indexOf(',');
if (dataAt === -1) {
throw new Error(`unexpected data uri output: ${dataUri}`);
}

return dataUri.slice(dataAt + 1);
}

export async function submitAuthCode(code: string) {
try {
const rawBox = await decodeBase64(code.trim());
Expand All @@ -41,7 +77,8 @@ export async function submitAuthCode(code: string) {
const box: AuthBox = JSON.parse(decoder.decode(boxData));
await session.absorbKey(box.token, box.key);
} catch (error) {
return error.message;
console.error(error);
return error;
}
}

Expand Down
8 changes: 4 additions & 4 deletions packages/insomnia/src/ui/components/command-palette.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,11 @@ const CommandPaletteCombobox = ({ close }: { close: () => void }) => {
{getMethodShortHand(request.item)}
</span>
) : isWebSocketRequest(request.item) ? (
<span className="w-10 flex-shrink-0 flex text-[0.65rem] rounded-sm border border-solid border-[--hl-sm] items-center justify-center text-[--color-font-notice] bg-[rgba(var(--color-notice-rgb),0.5)]">
<span className="w-10 flex-shrink-0 flex text-[0.65rem] rounded-sm border border-solid border-[--hl-sm] items-center justify-center text-[--color-font-notice] bg-[rgba(var(--color-notice-rgb),0.5)]">
WS
</span>
) : isGrpcRequest(request.item) && (
<span className="w-10 flex-shrink-0 flex text-[0.65rem] rounded-sm border border-solid border-[--hl-sm] items-center justify-center text-[--color-font-info] bg-[rgba(var(--color-info-rgb),0.5)]">
<span className="w-10 flex-shrink-0 flex text-[0.65rem] rounded-sm border border-solid border-[--hl-sm] items-center justify-center text-[--color-font-info] bg-[rgba(var(--color-info-rgb),0.5)]">
gRPC
</span>
),
Expand Down Expand Up @@ -293,11 +293,11 @@ const CommandPaletteCombobox = ({ close }: { close: () => void }) => {
{getMethodShortHand(request.item)}
</span>
) : isWebSocketRequest(request.item) ? (
<span className="w-10 flex-shrink-0 flex text-[0.65rem] rounded-sm border border-solid border-[--hl-sm] items-center justify-center text-[--color-font-notice] bg-[rgba(var(--color-notice-rgb),0.5)]">
<span className="w-10 flex-shrink-0 flex text-[0.65rem] rounded-sm border border-solid border-[--hl-sm] items-center justify-center text-[--color-font-notice] bg-[rgba(var(--color-notice-rgb),0.5)]">
WS
</span>
) : isGrpcRequest(request.item) && (
<span className="w-10 flex-shrink-0 flex text-[0.65rem] rounded-sm border border-solid border-[--hl-sm] items-center justify-center text-[--color-font-info] bg-[rgba(var(--color-info-rgb),0.5)]">
<span className="w-10 flex-shrink-0 flex text-[0.65rem] rounded-sm border border-solid border-[--hl-sm] items-center justify-center text-[--color-font-info] bg-[rgba(var(--color-info-rgb),0.5)]">
gRPC
</span>
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const RequestGroupRow: FC<{
return (
<li key={requestGroup._id} className="flex flex-col">
<div className="flex items-center gap-2 p-2">
<Checkbox isIndeterminate={isIndeterminate} slot={null} isSelected={isSelected} onChange={isSelected => handleSetItemSelected(requestGroup._id, isSelected)} className="group p-0 flex items-center h-full">
<Checkbox aria-label={requestGroup.name} isIndeterminate={isIndeterminate} slot={null} isSelected={isSelected} onChange={isSelected => handleSetItemSelected(requestGroup._id, isSelected)} className="group p-0 flex items-center h-full">
<div className="w-4 h-4 rounded flex items-center justify-center transition-colors group-data-[selected]:bg-[--hl-xs] group-focus:ring-2 ring-1 ring-[--hl-sm]">
<Icon icon={isIndeterminate ? 'minus' : 'check'} className='opacity-0 group-data-[selected]:opacity-100 group-data-[indeterminate]:opacity-100 group-data-[selected]:text-[--color-success] w-3 h-3' />
</div>
Expand Down Expand Up @@ -78,6 +78,7 @@ export const RequestRow: FC<{
<li className="flex items-center gap-2 p-2">
<Checkbox
slot={null}
aria-label={request.name}
isSelected={isSelected}
onChange={isSelected => {
handleSetItemSelected(request._id, isSelected);
Expand Down
Loading

0 comments on commit d39a4e9

Please sign in to comment.