外观
标准入口示例.js
js
/** 本文件是参与类型/行为检查的完整函数;调用网络/文件示例时传所属任务的signal。 */
import {http,html,archive,cache} from '@kodet/core';
/** @param {string} url @param {AbortSignal} signal */
export async function fetchStatusAndText(url, signal) {
const response = await fetch(url, {signal});
try {
if (!response.ok) throw new Error('HTTP '+response.status);
return await response.text();
} finally { await response.body?.cancel().catch(()=>{}); }
}
/** 绑定宿主超时,保留标准 Fetch 的响应形状。
* @param {string} url @param {AbortSignal} signal
*/
export function hostFetch(url, signal) { return http.createFetch({timeoutMs:15000})(url, {signal}); }
/** @param {string | Response} input @param {AbortSignal} signal */
export function parseArticles(input, signal) {
return html.use(input, document => document.select('article').extract({
title:'h2', url:{selector:'a',value:'url',attribute:'href'},
},{limit:20,signal}), {signal,baseURL:'https://example.invalid/'});
}
/** @param {Response | Blob | Uint8Array<ArrayBuffer>} input @param {AbortSignal} signal */
export async function archiveNames(input, signal) {
const opened = await archive.open(input, {signal});
try { return opened.entries.map(entry => entry.name); }
finally { await opened.close(); }
}
/** @param {Uint8Array<ArrayBuffer>} input */
export async function brotliRoundTrip(input) {
const packed = new Blob([input]).stream().pipeThrough(new CompressionStream('brotli'));
const restored = packed.pipeThrough(new DecompressionStream('brotli'));
return new Uint8Array(await new Response(restored).arrayBuffer());
}
/** @param {string} text */
export function binaryPacket(text) {
const encoded = new TextEncoder().encode(text), packet = new Uint8Array(4 + encoded.length);
new DataView(packet.buffer).setUint32(0, encoded.length, false);
packet.set(encoded, 4);
return {hex:packet.toHex(),text:new TextDecoder().decode(packet.subarray(4))};
}
export async function microtaskAndTimerOrder() {
const started=performance.now(), order=[];
queueMicrotask(()=>order.push('microtask'));
await new Promise(resolve=>setTimeout(resolve,1));
order.push('timer');
return {order,elapsed:performance.now()-started};
}
/** @param {string} namespace @param {Response | Blob | Uint8Array<ArrayBuffer>} input */
export async function cacheBytes(namespace, input) {
const box = cache.namespace(namespace).files;
await box.set('current', input, {ttlMs:60000});
const entry = await box.entry('current');
if (!entry) throw new Error('Cache entry expired');
try { return await entry.file.readBytes(); }
finally { await entry.file.close(); }
}