Public
Edited
Nov 25, 2021
Importers
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
someWorkResultTestSuccess = "result1" in doSomeWorkAndReturnResult()
Insert cell
Insert cell
Insert cell
Insert cell
worker = ({
name: "observable-worker-sk61",
code: `
${injectJson({ corsHeaders })}
${injectAsIs({ uuid: uuidBundle.code })}
${injectAsIs({ doSomeWorkAndReturnResult })}

function Secret(key) {
return ({
// SOME_ENV_VAR_1,
// SOME_ENV_VAR_2,
})[key];
}

addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})

addEventListener("scheduled", event => {
event.waitUntil(handleSchedule(event.scheduledTime))
})

async function handleSchedule(scheduledDate) {
}

async function handleRequest(request) {
const someWorkResult = doSomeWorkAndReturnResult();
return new Response(JSON.stringify({__buildTimestamp, someWorkResult}), {
headers: {
...corsHeaders,
"content-type": "application/json;charset=UTF-8",
}
});
}
`
})
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
async function deployWorker(worker, skipMinify) {
const __buildTimestamp = +new Date();
let code = injectJson({ __buildTimestamp }) + "\n" + worker.code;
if (!skipMinify) {
code = (await minify(code)).code;
}
return {
...(await cf
.accounts(Secret("CLOUDFLARE_ACCOUNT_ID"))
.workers.scripts(worker.name)
.upload(code)),
__buildTimestamp
};
}
Insert cell
Insert cell
function injectAsIs(vals) {
return Object.entries(vals)
.map(([name, val]) => `const ${name} = ${val};`)
.join("\n");
}
Insert cell
Insert cell
Insert cell
function corsProxyFetch(resource, init) {
if (resource instanceof Request) {
throw `corsProxyFetch only works for fetch(resource[, init]) calls, not fetch(request)`;
}
return fetch(`${Secret("CORS_PROXY_URL")}?${resource}`, init);
}
Insert cell
function cloudflare({ token, fetchProxy = fetch } = {}) {
const _fetch = fetchProxy;
const api = Object.assign(async function (
endpoint,
{ body, json, headers = {}, method = "GET" } = {}
) {
const prefixUrl = "https://api.cloudflare.com/client/v4/";
const isGet = method === "GET";
const url =
prefixUrl + endpoint + (isGet ? "?" + new URLSearchParams(json) : "");

if (!body && !isGet && json) {
body = JSON.stringify(json);
headers = {
"Content-Type": "application/json",
...headers
};
}
const response = await _fetch(url, {
method,
body,
headers: {
...headers,
Authorization: "Bearer " + token
}
});

let responseBody = response.headers
.get("content-type")
.includes("application/json")
? await response.json()
: await response.text();

if (!response.ok) {
throw new Error(
`HTTP error\n${JSON.stringify(
{
ok: response.ok,
status: response.status,
statusText: response.statusText,
responseBody
},
undefined,
" "
)}`
);
}

if ("success" in responseBody) {
if (!responseBody.success) {
throw new Error(
`API error\n${JSON.stringify(responseBody)},
undefined,
" "
)}`
);
}
responseBody = responseBody.result;
}

return responseBody;
},
Object.fromEntries(["get", "head", "put", "post", "delete", "options"].map((method) => [method, (endpoint, options) => api(endpoint, { ...options, method })])));

return {
accounts(accountId) {
return {
details: () => api(`accounts/${accountId}/`),
workers: {
scripts(scriptName) {
// ref: https://api.cloudflare.com/#worker-script-properties
if (!scriptName) {
return api(`accounts/${accountId}/workers/scripts/`);
}
const endpoint = `accounts/${accountId}/workers/scripts/${scriptName}/`;
return {
upload: (sourceCode) =>
api.put(endpoint, {
body: sourceCode,
headers: {
"Content-Type": "application/javascript"
}
}),
download: () => api(endpoint),
subdomain: (props) =>
props
? api.post(endpoint + "subdomain/", { json: props })
: api(endpoint + "subdomain/"),
delete: () => api.delete(endpoint)
};
}
}
};
},
zones(zoneId) {}
};
}
Insert cell
async function bundle(url) {
const warnings = [];
const rollupConfig = {
input: url,
plugins: [rollup_plugin_fetchUrl()],
onwarn(warning) {
warnings.push(warning);
},
output: {
format: "iife"
}
};

const bundle = await rollup(rollupConfig);
const generated = await bundle.generate(rollupConfig.output);
await bundle.close();

return { warnings, code: generated.output[0].code, ...generated };
}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more