Skip to content

Commit

Permalink
Add support for all data URL formats (#3341).
Browse files Browse the repository at this point in the history
  • Loading branch information
ricmoo committed Sep 14, 2022
1 parent d083522 commit 4c86dc9
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions packages/web/src.ts/index.ts
Expand Up @@ -82,6 +82,12 @@ export type FetchJsonResponse = {

type Header = { key: string, value: string };

function unpercent(value: string): Uint8Array {
return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => {
return String.fromCharCode(parseInt(code, 16));
}));
}

// This API is still a work in progress; the future changes will likely be:
// - ConnectionInfo => FetchDataRequest<T = any>
// - FetchDataRequest.body? = string | Uint8Array | { contentType: string, data: string | Uint8Array }
Expand Down Expand Up @@ -165,15 +171,15 @@ export function _fetchData<T = Uint8Array>(connection: string | ConnectionInfo,
}
}

const reData = new RegExp("^data:([a-z0-9-]+/[a-z0-9-]+);base64,(.*)$", "i");
const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i");
const dataMatch = ((url) ? url.match(reData): null);
if (dataMatch) {
try {
const response = {
statusCode: 200,
statusMessage: "OK",
headers: { "content-type": dataMatch[1] },
body: base64Decode(dataMatch[2])
headers: { "content-type": (dataMatch[1] || "text/plain")},
body: (dataMatch[2] ? base64Decode(dataMatch[3]): unpercent(dataMatch[3]))
};

let result: T = <T><unknown>response.body;
Expand Down

0 comments on commit 4c86dc9

Please sign in to comment.