Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Returns the boundary from the content-type header of a multipart/form-data request.
* @throws {Error} Throws an error if no boundary is found in the content-type header.
*/
export const getBoundaryFromContentType = (
contentType: string | null,
): string => {
const match = contentType?.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
if (!match) throw new Error('No boundary in content-type');
return match[1] || match[2];
};
/**
* Transforms the key of the current field in the multipart/form-data request body using the fieldsMapping.
* @returns The transformed headers.
*/
const transformHeaders = (
headers: string,
fieldsMapping: Record<string, string>,
): string => {
const field = Object.keys(fieldsMapping).find((key) =>
headers.includes(`name="${key}"`),
);
if (!field) return headers;
return headers.replace(`name="${field}"`, `name="${fieldsMapping[field]}"`);
};
/**
* Enqueues the value of the current field in the multipart/form-data request body.
* (This currently does not transform the value)
* @returns The updated buffer.
*/
const enqueueFieldValueAndUpdateBuffer = (
chunk: string,
controller: TransformStreamDefaultController,
buffer: string,
): string => {
controller.enqueue(new TextEncoder().encode(chunk));
return buffer.slice(chunk.length);
};
/**
* Enqueues the file content and updates the buffer for each jsonl row in the multipart/form-data body.
* @returns The updated buffer.
*/
const enqueueFileContentAndUpdateBuffer = (
chunk: string,
controller: TransformStreamDefaultController,
buffer: string,
rowTransform: (row: Record<string, unknown>) => Record<string, unknown>,
): string => {
const jsonLines = chunk.split('\n');
for (const line of jsonLines) {
if (line === '\r') {
buffer = buffer.slice(line.length + 1);
continue;
}
try {
const json = JSON.parse(line);
const transformedLine = rowTransform(json);
controller.enqueue(
new TextEncoder().encode(JSON.stringify(transformedLine)),
);
controller.enqueue(new TextEncoder().encode('\r\n'));
buffer = buffer.slice(line.length + 1);
} catch (_) {
// this is not a valid json line, so we don't update the buffer
}
}
return buffer;
};
/**
* Enqueues the file content and updates the buffer for each jsonl row in the multipart/form-data body.
* @returns The updated buffer.
*/
const enqueueFileContentAndUpdateOctetStreamBuffer = (
controller: TransformStreamDefaultController,
buffer: string,
rowTransform: (row: Record<string, unknown>) => Record<string, unknown>,
): string => {
const jsonLines = buffer.split('\n');
for (const line of jsonLines) {
if (line === '\r') {
buffer = buffer.slice(line.length + 1);
continue;
}
try {
const json = JSON.parse(line);
const transformedLine = rowTransform(json);
controller.enqueue(
new TextEncoder().encode(JSON.stringify(transformedLine)),
);
controller.enqueue(new TextEncoder().encode('\r\n'));
buffer = buffer.slice(line.length + 1);
} catch (_) {
// this is not a valid json line, so we don't update the buffer
}
}
return buffer;
};
/**
* Returns an instance of TransformStream used for transforming a multipart/form-data
* @param requestHeaders - The headers of the original request.
* @param rowTransform - The function used to transform the row.
* @returns An instance of TransformStream.
*/
export const getFormdataToFormdataStreamTransformer = (
requestHeaders: Record<string, string>,
rowTransform: (row: Record<string, unknown>) => Record<string, unknown>,
fieldsMapping: Record<string, string>,
): TransformStream => {
const decoder = new TextDecoder();
const boundary = `--${getBoundaryFromContentType(requestHeaders['content-type'])}`;
const newBoundary = `------FormBoundary${Math.random().toString(36).slice(2)}`;
requestHeaders['content-type'] =
`multipart/form-data; boundary=${newBoundary.slice(2)}`;
let buffer = '';
let isParsingHeaders = true;
let currentHeaders = '';
let isFileContent = false;
const encoder = new TextEncoder();
let isValidField = true;
const transformStream = new TransformStream({
transform(chunk, controller): void {
buffer += decoder.decode(chunk, { stream: true });
while (buffer.length > 0) {
if (isParsingHeaders) {
const headersEndIndex = buffer.indexOf('\r\n\r\n');
const boundaryEndIndex =
buffer.indexOf(boundary) + boundary.length + 2;
currentHeaders += buffer.slice(boundaryEndIndex, headersEndIndex);
isFileContent = currentHeaders.includes(
'Content-Disposition: form-data; name="file"',
);
// this will be specific to provider supported fields
isValidField = currentHeaders.includes(
'Content-Disposition: form-data; name="file"',
);
if (isValidField) {
const transformedHeaders = transformHeaders(
currentHeaders,
fieldsMapping,
);
controller.enqueue(encoder.encode(`${newBoundary}\r\n`));
controller.enqueue(encoder.encode(`${transformedHeaders}\r\n\r\n`));
}
buffer = buffer.slice(headersEndIndex + 4);
isParsingHeaders = false;
}
const boundaryIndex = buffer.indexOf(boundary);
const safeLength = boundaryIndex ?? buffer.length;
const content = buffer.slice(0, safeLength);
if (isFileContent) {
buffer = enqueueFileContentAndUpdateBuffer(
content,
controller,
buffer,
rowTransform,
);
} else if (isValidField) {
buffer = enqueueFieldValueAndUpdateBuffer(
content,
controller,
buffer,
);
} else {
buffer = buffer.slice(safeLength);
}
if (buffer.startsWith(`${boundary}--`)) {
controller.enqueue(new TextEncoder().encode(`\r\n${newBoundary}--`));
buffer = '';
} else if (buffer.startsWith(boundary)) {
isParsingHeaders = true;
currentHeaders = '';
} else {
break;
}
}
},
});
return transformStream;
};
/**
* Returns an instance of TransformStream used for transforming a binary/octet-stream
* @param rowTransform - The function used to transform the row.
* @returns An instance of TransformStream.
*/
export const getOctetStreamToOctetStreamTransformer = (
rowTransform: (row: Record<string, unknown>) => Record<string, unknown>,
): TransformStream => {
const decoder = new TextDecoder();
let buffer = '';
const transformStream = new TransformStream({
transform(chunk, controller): void {
buffer += decoder.decode(new Uint8Array(chunk), { stream: true });
buffer = enqueueFileContentAndUpdateOctetStreamBuffer(
controller,
buffer,
rowTransform,
);
},
});
return transformStream;
};
export const formDataToOctetStreamTransformer = (
requestHeaders: Record<string, string>,
rowTransform: (row: Record<string, unknown>) => Record<string, unknown>,
): TransformStream => {
const decoder = new TextDecoder();
const boundary = `--${getBoundaryFromContentType(requestHeaders['content-type'])}`;
requestHeaders['content-type'] = `application/octet-stream`;
let buffer = '';
let isParsingHeaders = true;
let currentHeaders = '';
let isFileContent = false;
const transformStream = new TransformStream({
transform(chunk, controller): void {
buffer += decoder.decode(chunk, { stream: true });
while (buffer.length > 0) {
if (isParsingHeaders) {
const headersEndIndex = buffer.indexOf('\r\n\r\n');
const boundaryEndIndex =
buffer.indexOf(boundary) + boundary.length + 2;
// if (headersEndIndex < 0) break;
currentHeaders += buffer.slice(boundaryEndIndex, headersEndIndex);
isFileContent = currentHeaders.includes(
'Content-Disposition: form-data; name="file"',
);
// this will be specific to provider supported fields
buffer = buffer.slice(headersEndIndex + 4);
isParsingHeaders = false;
}
const boundaryIndex = buffer.indexOf(boundary);
const safeLength = boundaryIndex ?? buffer.length;
// if (safeLength <= 0) break;
const content = buffer.slice(0, safeLength);
if (isFileContent) {
buffer = enqueueFileContentAndUpdateBuffer(
content,
controller,
buffer,
rowTransform,
);
} else {
buffer = buffer.slice(safeLength);
}
if (buffer.startsWith(`${boundary}--`)) {
buffer = '';
} else if (buffer.startsWith(boundary)) {
isParsingHeaders = true;
currentHeaders = '';
} else {
break;
}
}
},
});
return transformStream;
};
const decoder = new TextDecoder();
export function createLineSplitter(): TransformStream {
let leftover = '';
return new TransformStream({
transform(_chunk, controller): void {
const chunk = decoder.decode(_chunk);
leftover += chunk.toString();
const lines = leftover.split('\n');
leftover = lines.pop() || '';
for (const line of lines) {
if (line.trim()) {
controller.enqueue(line);
}
}
return;
},
flush(controller): void {
if (leftover.trim()) {
controller.enqueue(leftover);
}
},
});
}
|