new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Cloudflare Workers · Runtime APIs · all subjects

runtime

283 notes in this subject, read out of this brain and free to use. This is page 5 of 5.

crypto.subtle.deriveKey method

crypto.subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages) returns a Promise<CryptoKey> derived from the base key and specific algorithm. The algorithm parameter is an object describing the algorithm in algorithm-specific format. The baseKey parameter is a CryptoKey. The derivedKeyAlgorithm parameter is an object defining the algorithm the derived key will be used for. The extractable parameter is a boolean. The keyUsages parameter is an array of strings indicating possible usages of the new key.

crypto.subtle.deriveBits method

crypto.subtle.deriveBits(algorithm, baseKey, length) returns a Promise<ArrayBuffer> containing pseudo-random bits derived from the base key and specific algorithm. This is similar to deriveKey() except it returns an ArrayBuffer rather than a CryptoKey. The algorithm parameter is an object in algorithm-specific format. The baseKey parameter is a CryptoKey. The length parameter is an integer specifying the length of the bit string to derive.

crypto.subtle.importKey method

crypto.subtle.importKey(format, keyData, algorithm, extractable, keyUsages) returns a Promise<CryptoKey> by transforming a key from an external format into a CryptoKey. The format parameter is a string describing the format of the key to import. The keyData parameter is an ArrayBuffer. The algorithm parameter is an object describing the algorithm in algorithm-specific format. The extractable parameter is a boolean. The keyUsages parameter is an array of strings indicating possible usages of the new key.

crypto.subtle.exportKey method

crypto.subtle.exportKey(format, key) returns a Promise<ArrayBuffer> by transforming a CryptoKey into a portable format if the CryptoKey is extractable. The format parameter is a string describing the format in which the key will be exported. The key parameter is a CryptoKey.

crypto.subtle.wrapKey method

crypto.subtle.wrapKey(format, key, wrappingKey, wrapAlgo) returns a Promise<ArrayBuffer> by transforming a CryptoKey into a portable format and encrypting it with another key, suitable for storage or transmission in untrusted environments. The format parameter is a string describing the format in which the key will be exported. The key parameter is a CryptoKey. The wrappingKey parameter is a CryptoKey. The wrapAlgo parameter is an object describing the algorithm used to encrypt the exported key in algorithm-specific format.

crypto.subtle.unwrapKey method

crypto.subtle.unwrapKey(format, key, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages) returns a Promise<CryptoKey> by transforming a key that was wrapped by wrapKey() back into a CryptoKey. The format parameter is a string describing the data format of the key to unwrap. The key parameter is a CryptoKey. The unwrappingKey parameter is a CryptoKey. The unwrapAlgo parameter is an object describing the algorithm used to encrypt the wrapped key. The unwrappedKeyAlgo parameter is an object describing the key to be unwrapped. The extractable parameter is a boolean. The keyUsages parameter is an array of strings indicating possible usages of the new key.

crypto.subtle.timingSafeEqual method

crypto.subtle.timingSafeEqual(a, b) returns a boolean comparing two buffers in a way that is resistant to timing attacks. This is a non-standard extension to the Web Crypto API. The a and b parameters are each either an ArrayBuffer or TypedArray.

crypto.subtle.decrypt method

crypto.subtle.decrypt(algorithm, key, data) returns a Promise<ArrayBuffer> that fulfills with the clear data. The algorithm parameter is an object describing the algorithm and required parameters in algorithm-specific format. The key parameter is a CryptoKey. The data parameter is a BufferSource.

crypto.randomUUID method

crypto.randomUUID() generates a new random version 4 UUID as defined in RFC 4122 and returns it as a string.

Web Crypto supported algorithms table

Workers implements the following algorithms: RSASSA PKCS1 v1.5 (sign/verify, generateKey, exportKey, importKey), RSA PSS (sign/verify, generateKey, exportKey, importKey), RSA OAEP (encrypt/decrypt, generateKey, wrapKey/unwrapKey, exportKey, importKey), ECDSA (sign/verify, generateKey, exportKey, importKey), ECDH (deriveBits/deriveKey, generateKey, exportKey, importKey), Ed25519 per Secure Curves API (sign/verify, generateKey, exportKey, importKey), X25519 per Secure Curves API (deriveBits/deriveKey, generateKey, exportKey, importKey), NODE-ED25519 legacy non-standard EdDSA (sign/verify, generateKey, exportKey, importKey), AES-CTR (encrypt/decrypt, generateKey, wrapKey/unwrapKey, exportKey, importKey), AES-CBC (encrypt/decrypt, generateKey, wrapKey/unwrapKey, exportKey, importKey), AES-GCM (encrypt/decrypt, generateKey, wrapKey/unwrapKey, exportKey, importKey), AES-KW (generateKey, wrapKey/unwrapKey, exportKey, importKey), HMAC (sign/verify, generateKey, exportKey, importKey), SHA-1 (digest), SHA-256 (digest), SHA-384 (digest), SHA-512 (digest), MD5 (digest), HKDF (deriveBits/deriveKey, importKey), PBKDF2 (deriveBits/deriveKey, importKey).

navigator.sendBeacon() usage example

navigator.sendBeacon("https://example.com", "hello world");

Web File System Access API example

const root = await navigator.storage.getDirectory(); export default { async fetch(request) { const fileHandle = await root.getFileHandle("hello.txt", { create: true }); const writable = await fileHandle.createWritable(); await writable.write("Hello, world!"); await writable.close(); const file = await fileHandle.getFile(); const contents = await file.text(); return new Response(contents, { status: 200 }); }, };

Workers runtime uses V8 updated weekly

The Cloudflare Workers runtime is built on top of the V8 JavaScript and WebAssembly engine. The Workers runtime is updated at least once a week to at least the version of V8 that is currently used by Google Chrome's stable release. This means you can safely use the latest JavaScript features with no need for transpilers.

Disallowed JavaScript features in Workers

For security reasons, the following JavaScript features are not allowed in Workers: eval(), new Function, WebAssembly.compile, WebAssembly.compileStreaming, WebAssembly.instantiate with a buffer parameter, and WebAssembly.instantiateStreaming.

Date.now() behavior in Workers

Date.now() returns the time of the last I/O; it does not advance during code execution.

Base64 utility methods available

The atob() and btoa() methods are available. atob() decodes a string of data which has been encoded using base-64 encoding. btoa() creates a base-64 encoded ASCII string from a string of binary data.

Timer functions available in Request Context

The setInterval(), clearInterval(), setTimeout(), and clearTimeout() methods are available. The scheduler.wait() method returns a Promise that resolves after a given number of milliseconds and serves as an await-able alternative to setTimeout(). Timers are only available inside the Request Context.

performance.timeOrigin and performance.now() behavior

Workers uses the UNIX epoch as the time origin, so performance.timeOrigin always returns 0. performance.now() returns a DOMHighResTimeStamp representing the number of milliseconds elapsed since performance.timeOrigin. Workers intentionally reduces the precision of performance.now() such that it returns the time of the last I/O and does not advance during code execution. Because performance.timeOrigin is always 0, performance.now() will always equal Date.now(), yielding a consistent view of the passage of time within a Worker.

EventTarget and Event APIs available

The EventTarget and Event APIs are available and allow objects to publish and subscribe to events.

AbortController and AbortSignal APIs available

The AbortController and AbortSignal APIs are available and provide a common model for canceling asynchronous operations.

URL API supports HTTP and HTTPS schemes

The URL API supports URLs conforming to HTTP and HTTPS schemes. A new spec-compliant implementation of the URL class can be enabled using the url_standard compatibility flag.

URLPattern API for URL matching

The URLPattern API provides a mechanism for matching URLs based on a convenient pattern syntax.

Intl API for internationalization

The Intl API allows you to format dates, times, numbers, and more to the format that is used by a provided locale (language and region).

navigator.userAgent with global_navigator flag

When the global_navigator compatibility flag is set, the navigator.userAgent property is available with the value 'Cloudflare-Workers'. This can be used to reliably determine that code is running within the Workers environment.

Unhandled promise rejection events

The unhandledrejection event is emitted by the global scope when a JavaScript promise is rejected without a rejection handler attached. The rejectionhandled event is emitted by the global scope when a JavaScript promise rejection is handled late (after a rejection handler is attached to the promise after an unhandledrejection event has already been emitted).

Unhandled rejection event listener example

addEventListener("unhandledrejection", (event) => { console.log(event.promise); // The promise that was rejected. console.log(event.reason); // The value or Error with which the promise was rejected. }); addEventListener("rejectionhandled", (event) => { console.log(event.promise); // The promise that was rejected. console.log(event.reason); // The value or Error with which the promise was rejected. });

navigator.sendBeacon() with global_navigator flag

When the global_navigator compatibility flag is set, the navigator.sendBeacon(url[, data]) API is available to send an HTTP POST request containing a small amount of data to a web server. This API is intended as a means of transmitting analytics or diagnostics information asynchronously on a best-effort basis.

Web File System Access API with enable_web_file_system flag

When the enable_web_file_system compatibility flag is set, Workers supports the Web File System Access API, which allows you to read and write files and directories to a virtual file system within the Worker environment. This API provides access to the same in-memory virtual file system as the node:fs module but does not require Node.js compatibility to be enabled.

WebAssembly.instantiate() for pre-compiled modules

The WebAssembly.instantiate() API is available in Workers for executing pre-compiled WebAssembly modules. It only supports pre-compiled modules as documented in the web-standards documentation.

Write entire Worker in Rust

You can write an entire Cloudflare Worker in Rust using bindings that make Workers' JavaScript APIs available directly from Rust code.

SIMD support in Workers WebAssembly

SIMD (Single Instruction Multiple Data) is supported on Cloudflare Workers for WebAssembly applications.

Threading not supported in Workers

Threading is not possible in Cloudflare Workers. Each Worker runs in a single thread, and the Web Worker API is not supported.

WebAssembly binary size considerations

Workers using WebAssembly are typically larger than equivalent Workers written in JavaScript because compiling to WebAssembly often requires including additional runtime dependencies. Larger Workers may take longer to start. Tools like wasm-opt can be used to optimize the size of Wasm binaries.

WASI support is experimental

WebAssembly System Interface (WASI) support is experimental on Cloudflare Workers, with only some syscalls implemented. An open source implementation of WASI is available at github.com/cloudflare/workers-wasi.

Workers supports same WebAssembly features as Google Chrome

In general, Cloudflare Workers supports the same set of WebAssembly features that are available in Google Chrome.

WebAssembly support in Workers

Cloudflare Workers supports WebAssembly, allowing you to execute code written in languages like Rust, Go, or C that have been compiled to Wasm binary format.

Wasm module import and export structure

Wasm modules are defined in WebAssembly Text Format (WAT) where functions can be imported from JavaScript via the (import) directive specifying a namespace and function name, and exported via the (export) directive specifying a function name. Imported functions can be called from within the Wasm module using the call instruction.

Accessing Wasm exported functions from JavaScript

After instantiating a Wasm module, exported functions can be accessed and invoked through the instance.exports property, passing any required arguments. For example, instance.exports.exported_func(42) invokes an exported function named exported_func with the argument 42.

Wasm use cases in Workers

WebAssembly can be used to accelerate computationally intensive operations in Cloudflare Workers that do not involve significant I/O.

Wasm module import and instantiation in JavaScript Worker

Example showing how to import a Wasm module and instantiate it: import mod from './simple.wasm'; const importObject = { imports: { imported_func: (arg: number) => { console.log(`Hello from JavaScript: ${arg}`); } } }; const instance = await WebAssembly.instantiate(mod, importObject); export default { async fetch() { const retval = instance.exports.exported_func(42); return new Response(`Success: ${retval}`); } };

Convert WAT to WebAssembly Binary Format

WebAssembly Text Format (.wat) files can be converted to WebAssembly Binary Format (.wasm) using the wat2wasm tool from WABT, with the command: wat2wasm src/simple.wat -o src/simple.wasm

WebAssembly.instantiate() usage in Workers

WebAssembly modules can be imported and instantiated in Cloudflare Workers using WebAssembly.instantiate(). This accepts two parameters: the compiled Wasm module and an importObject containing any imports the Wasm expects. Instantiation should be done at the top level of the script to avoid instantiation on every request.

Wrangler bundles .wasm and .wasm?module files

Wrangler automatically bundles any Wasm module that ends in .wasm or .wasm?module so that it is available at runtime within your Worker. This bundling rule can be customized in the Wrangler configuration file.

Give your agent this brain