-
Notifications
You must be signed in to change notification settings - Fork 0
/
parseBlockText.ts
228 lines (198 loc) · 6.26 KB
/
parseBlockText.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import type { Block, Meta } from "./types.ts";
import { _Request, _Response, httpMethods } from "./types.ts";
import * as eta from "https://deno.land/x/eta@v1.12.3/mod.ts";
import { extract } from "https://deno.land/std@0.160.0/encoding/front_matter.ts";
async function renderTemplate(template: string, data: Record<string, unknown>) {
const result = await eta.render(
template,
data,
{
async: true,
useWith: true,
rmWhitespace: false,
autoTrim: false,
// TODO: add custom tags??
// tags: ["{{", "}}"]
},
);
return result;
}
export const isRequestStartLine = (line: string): boolean =>
httpMethods.some((method) => line.trim().startsWith(method));
const isResponseStartLine = (line: string): boolean =>
line.trim().startsWith("HTTP/");
const isHeaderLine = (line: string): boolean =>
!!line.trim().match(/^[^:]+:\s*.+$/);
export async function parseBlockText(block: Block): Promise<Block> {
block.meta = await parseMetaFromText(block.text);
block.request = await parseRequestFromText(block);
block.expectedResponse = await parseResponseFromText(block.text);
return block;
}
const findFrontMatterTextRegex = /^---\s*([\s\S]*?)\s*---\s*/gm;
export async function parseMetaFromText(
textRaw = "",
dataToInterpolate = {},
): Promise<Meta> {
const meta: Meta = {};
const lines: string[] = splitLines(textRaw);
const requestStartLine = lines.findIndex(isRequestStartLine);
const metaText = lines.slice(0, requestStartLine).join("\n");
const text = await renderTemplate(metaText, dataToInterpolate) || "";
const frontMatterText = text.match(findFrontMatterTextRegex)?.[0] || "";
if (frontMatterText) {
const data = extract(frontMatterText);
Object.assign(meta, data.attrs);
}
return meta;
}
function splitLines(text: string): string[] {
return text.replaceAll("\r", "\n").split("\n");
}
export async function parseRequestFromText(
block: Block,
dataToInterpolate = {},
): Promise<_Request | undefined> {
const textRaw = block.text || "";
const meta = block.meta;
const linesRaw: string[] = splitLines(textRaw);
const requestStartLine = linesRaw.findIndex(isRequestStartLine);
if (requestStartLine === -1) {
return;
}
let requestEndLine = linesRaw.findIndex(
isResponseStartLine,
requestStartLine,
);
if (requestEndLine === -1) requestEndLine = linesRaw.length;
const requestText = linesRaw.slice(requestStartLine, requestEndLine).join(
"\n",
);
const text = await renderTemplate(requestText, dataToInterpolate) || "";
const lines = splitLines(text);
let url = "";
const headers: Headers = new Headers();
const requestInit: RequestInit = {
method: "GET",
mode: "cors",
credentials: "same-origin",
cache: "default",
redirect: "follow",
referrer: "client",
referrerPolicy: "no-referrer-when-downgrade",
integrity: "",
keepalive: false,
signal: undefined,
};
for (const key in meta) {
if (key in requestInit) {
requestInit[key as keyof RequestInit] = meta[key];
}
}
let lookingFor = "url";
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith("###")) {
break;
}
if (lookingFor !== "body" && trimmed.startsWith("#")) {
continue;
}
if (lookingFor === "url" && isRequestStartLine(line)) {
const [method, _url] = trimmed.split(" ");
requestInit.method = method;
url = _url;
lookingFor = "headers";
continue;
}
if (lookingFor === "headers" && isHeaderLine(line)) {
const [key, value] = extractHeader(trimmed);
headers.set(key, value);
continue;
}
if (lookingFor === "headers" && !isHeaderLine(line)) {
lookingFor = "body";
}
if (lookingFor === "body") {
requestInit.body = (requestInit.body || "") + "\n" + line;
}
}
requestInit.body = (requestInit.body as string || "").trim();
if (requestInit.body === "") {
requestInit.body = null;
}
requestInit.headers = headers;
let host = requestInit.headers.get("host") || meta.host || "";
host = String(host).trim();
const hasProtocol = url.match(/^https?:\/\//);
if (host && !hasProtocol) {
if (host.endsWith("/") && url.startsWith("/")) {
host = host.slice(0, -1);
}
url = host + (url || "");
}
if (!url.match(/^https?:\/\//)) {
url = `http://${url}`;
}
const request: _Request = new _Request(url, requestInit);
return request;
}
export async function parseResponseFromText(
textRaw = "",
dataToInterpolate = {},
): Promise<_Response | undefined> {
const linesRaw: string[] = splitLines(textRaw);
const responseInit: ResponseInit = {};
const headers = new Headers();
let responseBody: BodyInit | null = "";
const statusLine = linesRaw.findIndex(isResponseStartLine);
if (statusLine === -1) return;
const responseText = linesRaw.slice(statusLine).join("\n");
const text = await renderTemplate(responseText, dataToInterpolate) || "";
const lines = splitLines(text);
let lookingFor = "status";
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith("###")) {
break;
}
if (lookingFor !== "body" && trimmed.startsWith("#")) {
continue;
}
if (lookingFor !== "body" && trimmed.startsWith("#")) {
continue;
}
if (lookingFor === "status" && isResponseStartLine(line)) {
const [, status, ...statusText] = trimmed.split(" ");
responseInit.status = parseInt(status);
responseInit.statusText = statusText.join(" ");
lookingFor = "headers";
continue;
}
if (lookingFor === "headers" && isHeaderLine(line)) {
const [key, value] = extractHeader(trimmed);
headers.set(key, value);
continue;
}
if (lookingFor !== "body" && !trimmed) {
if (lookingFor === "headers") {
lookingFor = "body";
}
continue;
}
if (lookingFor === "body") {
responseBody += "\n" + line;
continue;
}
}
responseInit.headers = headers;
responseBody = responseBody.trim();
responseBody ||= null;
const response: _Response = new _Response(responseBody, responseInit);
return response;
}
function extractHeader(line: string): [string, string] {
const [key, ...values] = line.split(":");
const value = values.join(":").trim();
return [key, value];
}