mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-12-05 14:26:23 +01:00
Fix Insomnia template and GraphQL import fidelity (#693)
This commit is contained in:
1 parent
6fc43a60e2
commit
34815f327a
15 files changed
+921
-35
No files matched your search
@@ -34,13 +34,15 @@ export function importHttpBodyAndHeaders(obj: any) {
|
||||
const { headers } = importHeaders(obj);
|
||||
const { body, bodyType } = importHttpBody(obj.body);
|
||||
const mimeType = typeof obj.body?.mimeType === "string" ? obj.body.mimeType.trim() : "";
|
||||
// Insomnia uses application/graphql as an editor marker, but sends a JSON envelope.
|
||||
const contentType = bodyType === "graphql" ? "application/json" : mimeType;
|
||||
|
||||
if (
|
||||
bodyType != null &&
|
||||
mimeType !== "" &&
|
||||
!headers.some((header: { name: string }) => header.name.toLowerCase() === "content-type")
|
||||
) {
|
||||
headers.push({ enabled: true, name: "Content-Type", value: mimeType });
|
||||
headers.push({ enabled: true, name: "Content-Type", value: contentType });
|
||||
}
|
||||
|
||||
return { body, bodyType, headers };
|
||||
@@ -93,7 +95,36 @@ function importHttpBody(rawBody: any) {
|
||||
}
|
||||
|
||||
if (normalizedMimeType === "application/graphql") {
|
||||
return { bodyType: "graphql", body: { text: rawBody.text ?? "" } };
|
||||
const text = typeof rawBody.text === "string" ? rawBody.text : "";
|
||||
try {
|
||||
const parsed = JSON.parse(text);
|
||||
if (typeof parsed?.query === "string") {
|
||||
return {
|
||||
bodyType: "graphql",
|
||||
body: {
|
||||
query: parsed.query,
|
||||
variables:
|
||||
typeof parsed.variables === "string"
|
||||
? parsed.variables
|
||||
: parsed.variables == null
|
||||
? ""
|
||||
: JSON.stringify(parsed.variables, null, 2),
|
||||
...(typeof parsed.operationName === "string"
|
||||
? { operationName: parsed.operationName }
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// A raw GraphQL document is also valid; preserve it verbatim. An envelope that
|
||||
// failed to parse is usually one with template tags in it, so recover its parts
|
||||
// rather than dropping the whole envelope into the query editor.
|
||||
const recovered = recoverGraphQLEnvelope(text);
|
||||
if (recovered != null) {
|
||||
return { bodyType: "graphql", body: recovered };
|
||||
}
|
||||
}
|
||||
return { bodyType: "graphql", body: { query: text, variables: "" } };
|
||||
}
|
||||
|
||||
if (normalizedMimeType === "application/json" || normalizedMimeType.endsWith("+json")) {
|
||||
@@ -115,6 +146,109 @@ function importHttpBody(rawBody: any) {
|
||||
return { bodyType: null, body: {} };
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull the parts out of a GraphQL envelope that isn't valid JSON.
|
||||
*
|
||||
* Insomnia lets template tags be written straight into the envelope
|
||||
* ({"query":"{me{id}}","variables":{"id":{{ _.id }}}}), which makes the text
|
||||
* unparseable. Members are read as raw text so the tags survive the trip.
|
||||
*/
|
||||
function recoverGraphQLEnvelope(
|
||||
text: string,
|
||||
): { query: string; variables: string; operationName?: string } | null {
|
||||
const members = readTopLevelMembers(text);
|
||||
if (members == null) return null;
|
||||
|
||||
const query = parseJSONString(members.get("query"));
|
||||
if (query == null) return null;
|
||||
|
||||
const variables = members.get("variables") ?? "";
|
||||
const operationName = parseJSONString(members.get("operationName"));
|
||||
return {
|
||||
query,
|
||||
variables: variables === "null" ? "" : variables,
|
||||
...(operationName == null ? {} : { operationName }),
|
||||
};
|
||||
}
|
||||
|
||||
function parseJSONString(raw: string | undefined): string | null {
|
||||
if (raw == null || !raw.startsWith('"')) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return typeof parsed === "string" ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The raw text of each member of the outermost object, without parsing the values.
|
||||
* Returns null unless the whole object is well-formed enough to walk.
|
||||
*/
|
||||
function readTopLevelMembers(text: string): Map<string, string> | null {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed.startsWith("{")) return null;
|
||||
|
||||
const members = new Map<string, string>();
|
||||
let offset = 1;
|
||||
while (offset < trimmed.length) {
|
||||
while (/[\s,]/.test(trimmed[offset] ?? "")) offset++;
|
||||
if (trimmed[offset] === "}") return members;
|
||||
|
||||
const keyEnd = scanJSONString(trimmed, offset);
|
||||
if (keyEnd == null) return null;
|
||||
const key = parseJSONString(trimmed.slice(offset, keyEnd));
|
||||
if (key == null) return null;
|
||||
|
||||
offset = keyEnd;
|
||||
while (/\s/.test(trimmed[offset] ?? "")) offset++;
|
||||
if (trimmed[offset] !== ":") return null;
|
||||
offset++;
|
||||
while (/\s/.test(trimmed[offset] ?? "")) offset++;
|
||||
|
||||
const valueEnd = scanJSONValue(trimmed, offset);
|
||||
if (valueEnd == null) return null;
|
||||
members.set(key, trimmed.slice(offset, valueEnd).trim());
|
||||
offset = valueEnd;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Offset just past the string starting at `start`, or null if it never closes. */
|
||||
function scanJSONString(text: string, start: number): number | null {
|
||||
if (text[start] !== '"') return null;
|
||||
for (let i = start + 1; i < text.length; i++) {
|
||||
if (text[i] === "\\") i++;
|
||||
else if (text[i] === '"') return i + 1;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Offset just past the value starting at `start`. Nesting is tracked so template
|
||||
* tags come back whole, but the value itself is not validated.
|
||||
*/
|
||||
function scanJSONValue(text: string, start: number): number | null {
|
||||
let depth = 0;
|
||||
for (let i = start; i < text.length; i++) {
|
||||
const char = text[i]!;
|
||||
if (char === '"') {
|
||||
const end = scanJSONString(text, i);
|
||||
if (end == null) return null;
|
||||
i = end - 1;
|
||||
} else if (char === "{" || char === "[") {
|
||||
depth++;
|
||||
} else if (char === "}" || char === "]") {
|
||||
if (depth === 0) return i; // The member ended with the enclosing object
|
||||
depth--;
|
||||
if (depth === 0) return i + 1;
|
||||
} else if (depth === 0 && char === ",") {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function deleteUndefinedAttrs<T>(obj: T): T {
|
||||
if (Array.isArray(obj) && obj != null) {
|
||||
return obj.map(deleteUndefinedAttrs) as T;
|
||||
@@ -128,20 +262,3 @@ export function deleteUndefinedAttrs<T>(obj: T): T {
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
/** Recursively render all nested object properties */
|
||||
export function convertTemplateSyntax<T>(obj: T): T {
|
||||
if (typeof obj === "string") {
|
||||
// oxlint-disable-next-line no-template-curly-in-string -- Yaak template syntax
|
||||
return obj.replaceAll(/{{\s*(_\.)?([^}]+)\s*}}/g, "${[$2]}") as T;
|
||||
}
|
||||
if (Array.isArray(obj) && obj != null) {
|
||||
return obj.map(convertTemplateSyntax) as T;
|
||||
}
|
||||
if (typeof obj === "object" && obj != null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj).map(([k, v]) => [k, convertTemplateSyntax(v)]),
|
||||
) as T;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
import { convertId } from "./common";
|
||||
|
||||
// Convert only syntax with a native equivalent. Leave filters, expressions and third-party
|
||||
// tags intact rather than importing something that looks valid but means something different.
|
||||
const identifier = /^[\p{L}\p{N}_][\p{L}\p{N}_.-]*$/u;
|
||||
|
||||
function argument(value: string): string {
|
||||
return `b64'${Buffer.from(value).toString("base64url")}'`;
|
||||
}
|
||||
|
||||
function decodeArgument(value: string): string | null {
|
||||
if (!value.startsWith("b64::")) return value;
|
||||
const match = /^b64::([A-Za-z0-9+/_-]*={0,2})(?:::[^:]*)?$/.exec(value);
|
||||
if (!match) return null;
|
||||
const bytes = Buffer.from(match[1]!, "base64");
|
||||
const normalized = match[1]!.replace(/=+$/, "").replaceAll("+", "-").replaceAll("/", "_");
|
||||
if (bytes.toString("base64url") !== normalized) return null;
|
||||
const decoded = bytes.toString("utf8");
|
||||
return Buffer.from(decoded).equals(bytes) ? decoded : null;
|
||||
}
|
||||
|
||||
/** Literal arguments only; never evaluate Nunjucks or silently skip unexpected tokens. */
|
||||
function parseArgs(input: string): string[] | null {
|
||||
const args: string[] = [];
|
||||
const token =
|
||||
/\s*(?:'((?:[^'\\]|\\['"\\nrt])*)'|"((?:[^"\\]|\\['"\\nrt])*)"|(-?\d+(?:\.\d+)?))\s*/y;
|
||||
let offset = 0;
|
||||
while (offset < input.length) {
|
||||
token.lastIndex = offset;
|
||||
const match = token.exec(input);
|
||||
if (!match) return input.trim() === "" ? [] : null;
|
||||
const literal = (match[1] ?? match[2] ?? match[3]!).replace(
|
||||
/\\(['"\\nrt])/g,
|
||||
(_, char: string) => ({ n: "\n", r: "\r", t: "\t" })[char] ?? char,
|
||||
);
|
||||
const decoded = decodeArgument(literal);
|
||||
if (decoded == null) return null;
|
||||
args.push(decoded);
|
||||
offset = token.lastIndex;
|
||||
if (offset === input.length) break;
|
||||
if (input[offset] !== ",") return null;
|
||||
offset++;
|
||||
if (input.slice(offset).trim() === "") return null;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function convertTag(name: string, input: string, requestIds: Set<string>): string | null {
|
||||
const args = parseArgs(input);
|
||||
if (args == null) return null;
|
||||
if (name === "uuid" && args.length === 1 && ["v1", "v4"].includes(args[0]!)) {
|
||||
return `uuid.${args[0]}()`;
|
||||
}
|
||||
if (name === "faker" && args.length === 1 && args[0] === "randomUUID") {
|
||||
return "uuid.v4()";
|
||||
}
|
||||
if (name !== "response" || args.length < 3 || args.length > 5) return null;
|
||||
const [attribute, request, filter = "", behavior = "never", maxAge = "0"] = args;
|
||||
if (!request || !requestIds.has(convertId(request))) return null;
|
||||
const behaviors: Record<string, string> = {
|
||||
never: "never",
|
||||
"no-history": "smart",
|
||||
always: "always",
|
||||
"when-expired": "ttl",
|
||||
};
|
||||
const convertedBehavior = Object.hasOwn(behaviors, behavior) ? behaviors[behavior] : null;
|
||||
if (!convertedBehavior || !/^\d+$/.test(maxAge)) return null;
|
||||
// Insomnia treats zero as immediately expired; Yaak uses zero for never expiring.
|
||||
if (convertedBehavior === "ttl" && Number(maxAge) === 0) return null;
|
||||
const common = `request=${argument(convertId(request))}, behavior='${convertedBehavior}', ttl='${maxAge}'`;
|
||||
if (attribute === "raw") {
|
||||
return `response.body.raw(${common})`;
|
||||
}
|
||||
if (attribute === "body") {
|
||||
// Insomnia returns a scalar for one match, but an array for several. Yaak's first/all
|
||||
// modes cannot express that automatically. Only convert definite paths for now.
|
||||
if (!/^\$(?:\.[\p{L}\p{N}_-]+|\[(?:0|[1-9]\d*)\])*$/u.test(filter.trim())) return null;
|
||||
return `response.body.path(${common}, path=${argument(filter.trim())}, result='first')`;
|
||||
}
|
||||
if (attribute === "header" && filter !== "") {
|
||||
return `response.header(${common}, header=${argument(filter.trim())})`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function convertTemplateSyntax<T>(obj: T, requestIds = new Set<string>()): T {
|
||||
if (typeof obj === "string") {
|
||||
return obj
|
||||
.replace(/{{\s*([\s\S]*?)\s*}}/g, (full, expression: string) => {
|
||||
const trimmed = expression.trim();
|
||||
const bracket = /^_\s*\[\s*(['"])([^'"\\]+)\1\s*\]$/.exec(trimmed);
|
||||
const name = bracket?.[2] ?? trimmed.replace(/^_\./, "");
|
||||
return identifier.test(name) && !["true", "false", "null"].includes(name)
|
||||
? `\${[ ${name} ]}`
|
||||
: full;
|
||||
})
|
||||
.replace(
|
||||
/{%\s*(\w+)\s*((?:'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|[^'"])*?)%}/g,
|
||||
(full, name: string, input: string) => {
|
||||
const converted = convertTag(name, input, requestIds);
|
||||
return converted == null ? full : `\${[ ${converted} ]}`;
|
||||
},
|
||||
) as T;
|
||||
}
|
||||
if (Array.isArray(obj)) return obj.map((value) => convertTemplateSyntax(value, requestIds)) as T;
|
||||
if (typeof obj === "object" && obj != null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj).map(([key, value]) => [key, convertTemplateSyntax(value, requestIds)]),
|
||||
) as T;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
@@ -2,12 +2,12 @@
|
||||
import type { PartialImportResources } from "@yaakapp/api";
|
||||
import {
|
||||
convertId,
|
||||
convertTemplateSyntax,
|
||||
createSourceKeys,
|
||||
importHttpBodyAndHeaders,
|
||||
isJSObject,
|
||||
type SourceKeys,
|
||||
} from "./common";
|
||||
import { convertTemplateSyntax } from "./templates";
|
||||
|
||||
export function convertInsomniaV4(parsed: any) {
|
||||
if (!Array.isArray(parsed.resources)) return null;
|
||||
@@ -68,7 +68,10 @@ export function convertInsomniaV4(parsed: any) {
|
||||
resources.environments = resources.environments.filter(Boolean);
|
||||
resources.workspaces = resources.workspaces.filter(Boolean);
|
||||
|
||||
return { resources: convertTemplateSyntax(resources), sourceKeys: keys.all() };
|
||||
return {
|
||||
resources: convertTemplateSyntax(resources, new Set(resources.httpRequests.map((r) => r.id))),
|
||||
sourceKeys: keys.all(),
|
||||
};
|
||||
}
|
||||
|
||||
function importHttpRequest(
|
||||
@@ -78,12 +81,12 @@ function importHttpRequest(
|
||||
): PartialImportResources["httpRequests"][0] {
|
||||
let authenticationType: string | null = null;
|
||||
let authentication = {};
|
||||
if (r.authentication.type === "bearer") {
|
||||
if (r.authentication?.type === "bearer") {
|
||||
authenticationType = "bearer";
|
||||
authentication = {
|
||||
token: r.authentication.token,
|
||||
};
|
||||
} else if (r.authentication.type === "basic") {
|
||||
} else if (r.authentication?.type === "basic") {
|
||||
authenticationType = "basic";
|
||||
authentication = {
|
||||
username: r.authentication.username,
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
import type { PartialImportResources } from "@yaakapp/api";
|
||||
import {
|
||||
convertId,
|
||||
convertTemplateSyntax,
|
||||
createSourceKeys,
|
||||
importHeaders,
|
||||
importHttpBodyAndHeaders,
|
||||
isJSObject,
|
||||
type SourceKeys,
|
||||
} from "./common";
|
||||
import { convertTemplateSyntax } from "./templates";
|
||||
|
||||
export function convertInsomniaV5(parsed: any) {
|
||||
// Assert parsed is object
|
||||
@@ -80,7 +80,10 @@ export function convertInsomniaV5(parsed: any) {
|
||||
resources.environments = resources.environments.filter(Boolean);
|
||||
resources.workspaces = resources.workspaces.filter(Boolean);
|
||||
|
||||
return { resources: convertTemplateSyntax(resources), sourceKeys: keys.all() };
|
||||
return {
|
||||
resources: convertTemplateSyntax(resources, new Set(resources.httpRequests.map((r) => r.id))),
|
||||
sourceKeys: keys.all(),
|
||||
};
|
||||
}
|
||||
|
||||
function importHttpRequest(
|
||||
|
||||
Reference in new issue
Block a user