外观
平台能力.js
js
/** 公开入口:@kodet/core 的 env、capabilities、toast、links、sniffer、web、files、describeError、KodetError、HttpError。 */
/**
* 宿主环境是模块执行前安装的只读实时快照;读取不发起 IO。
* env.colorScheme 是宿主页面实际明暗,可能与系统偏好不同;
* env.system.colorScheme 是 Android 系统原始偏好。通用宿主未给覆盖时前者可为 null:
* const effectiveScheme = env.colorScheme ?? env.system.colorScheme;
*
* const stop = env.onChange(({ current, previous, changed }) => { });
* 事件只在实际变化时触发,同一 listener 不并行重入;返回的 stop 幂等。
* 页面 owner/Runtime 释放会自动取消对应监听,listener 异常交给 app.onError 观察。
*/
const environment = {
platform: "android",
colorScheme: "dark", // light/dark/null;宿主当前有效主题。
locale: "zh-CN",
locales: ["zh-CN", "en-US"], // 宿主应用实际语言和回退链。
timeZone: "Asia/Tokyo",
host: { id: "host.package", name: "宿主", versionName: "1.0", versionCode: 1 },
os: { name: "Android", version: "16", sdk: 36 },
system: {
colorScheme: "light", // 永远是 light/dark;系统原始值,不等于 ThemeHelper 最终模式。
locales: ["ja-JP"],
},
};
/**
* 能力查询返回值示意。实际能力名称以当前宿主返回为准。
* 调用写法:
*
* const names = capabilities.list();
* const exists = capabilities.has("http");
* const detail = await capabilities.get("http");
*/
const capabilitiesResult = {
list: ["archive", "http"], // 示例,不是保证只有这些能力。
has: true, // 当前宿主实际支持;不弹UI、不做权限申请。
detail: { supported: true, requiresInteraction: false, features: ["request"], limits: {}, notes: [] },
};
/**
* Toast 参数。调用:await toast.show("提示文字", toastOptions)。
* 可以在 onInit 中使用;core 不需要构建命令再 .run()。
*/
const toastOptions = {
duration: "short", // short(默认)/long。
};
/**
* 链接调用:await links.open("https://example.invalid/")。
* 默认 HTTP(S) 打开宿主内置浏览器,其他允许协议确认后交给系统。显式 target:"system" 强制交给系统;绝对协议地址 string/URL。
* 内部协议:await links.open("book://detail/123", { target: "kodet" })。
* 指定应用:await links.openApp("example.reader", { route: "detail", params: { bookId: "123" } })。
* 多内部候选手动选择、单个确认;系统候选交给 Android。同应用无需跨应用确认。
* options 可含 signal;无 chooser。无匹配 NOT_FOUND,取消正常返回 cancelled。
*/
/**
* 网页媒体地址检测。调用:await sniffer.scan(pageUrl, snifferOptions)。
* 依赖宿主网页能力,不直接播放视频;支持 signal 取消。
*/
const snifferOptions = {
pattern: "\\.(mp4|m3u8)(\\?|$)", // 可选字符串或 RegExp;正则标志仅 i/m/s。
contains: [".webm"], // 与 pattern 按“或”匹配,忽略大小写。
exclude: ["example-preview"], // 排除优先,忽略大小写。
timeoutMs: 15000,
idleTimeoutMs: 1200,
maxMatches: 5,
stopOnFirst: true,
blockAutoNavigation: true,
headers: {}, // 只用于初始主文档,不保证所有子资源请求都带上。
// signal:可选 AbortSignal。
// session:web.session("login");不传则每次扫描使用独立临时网页会话。
};
const snifferResult = {
urls: ["https://example.invalid/video.mp4"],
pageUrl: "https://example.invalid/watch",
elapsedMs: 800,
reason: "match", // match/limit/idle/timeout;取消则抛 ABORTED。
};
/**
* SDK 错误对象的主要字段;Error 实例还可能有 cause/stack,不是固定 JSON 信封。
* 调用写法:
*
* try {
* // await 某项能力。
* } catch (error) {
* if (error instanceof HttpError) {
* // HTTP 能力错误;4xx/5xx 本身不自动抛这个异常。
* } else if (error instanceof KodetError) {
* // 其他宿主能力错误。
* } else {
* // 普通 Error/TypeError/JSON 解析错误等。
* }
* }
*/
const error = {
name: "TimeoutError", // ABORTED=AbortError、TIMEOUT=TimeoutError,其余为 KodetError/HttpError。
code: "TIMEOUT", // 根据稳定 code 分类,不匹配文案。
message: "请求超时",
};
const errorCodes = [
"INVALID_ARGUMENT",
"NETWORK_ERROR",
"TIMEOUT",
"ABORTED",
"RESPONSE_TOO_LARGE",
"BODY_CLOSED",
"PERMISSION_DENIED",
"NOT_SUPPORTED",
"RESOURCE_LIMIT",
"NOT_FOUND",
"CONFLICT",
"STORAGE_ERROR",
"IO_ERROR",
"CRYPTO_ERROR",
"FORMAT_CORRUPT",
"PASSWORD_REQUIRED",
"INVALID_PASSWORD",
"SCRIPT_ERROR",
"INTERNAL_ERROR",
];
/**
* 显式网页会话:只共享 Cookie/网页存储,不共享实例、导航、回调或任务。
* const session = web.session("login", webSessionOptions);
* blocks.webView({ id: "login", url: loginURL, height: "fill", session });
* const result = await sniffer.scan(pageURL, { session });
* await session.setCookie(loginURL, "token=value; Path=/; Secure");
* const cookie = await session.getCookie(loginURL);
* const info = await session.getCookieInfo(loginURL); // 提供方不支持结构化信息时为 NOT_SUPPORTED。
* await session.removeCookie(loginURL, { name: "token", path: "/" });
* await session.clearCookies();
* // 所有消费者关闭后:
* await session.clearData(); // Cookie、缓存、网页存储;活跃/并发清理时报 CONFLICT。
*
* 同名会话默认跨 Runtime 保留。persistent:false 只限制复用范围,并非完全不落盘。
* 取消 clearData 的等待不会中断平台清理;直到完成前禁止新 lease。
* Cookie URL 必须是无凭据 HTTP(S),Set-Cookie 值不能含换行/NUL;Cookie 信息是只读快照。
* 不与 http.session 自动同步 Cookie;旧 WebView 不支持隔离/清理/GET_COOKIE_INFO 时明确 NOT_SUPPORTED。
* const url = await web.resourceURL("@res/page.html"); // 应用专属 HTTPS URL,只开放 src/res。
*/
const webSessionOptions = {
persistent: true, // 默认 true;同一名字不能改变持久化选项。
};
/** const report = describeError(anyThrownValue); 普通错误也可转成有界、不可变诊断。 */
const errorReport = {
code: "SCRIPT_ERROR",
category: "script",
name: "TypeError",
message: "错误说明",
stack: "受限堆栈", // 可选,还可有 file/line/column。
// cause:同样结构,最多四层;不包含原始请求/回调参数。
};
// capabilities.apiVersion:宿主 SDK API 版本,读取当前运行宿主的实际支持等级,不能当作应用最低需求。
// await capabilities.get("web.sessions"):实际支持、前台交互与详细限制。
const capabilityDetail = {
supported: false,
requiresInteraction: false,
reason: "platform-unsupported", // 可选;实现缺失时为 not-implemented。
features: [], limits: {}, notes: [],
};
// 以下均在所属页面回调中调用;不会在 init 里弹系统界面。
// const shared = await file.share({mimeType:"text/plain"});
// try { /* 原生保持文件租约 */ } finally { await shared.close(); }
// const [file] = await files.pick(fileSelection); // 始终返回只读数组,用户取消为 []。
// try { if (file) console.log(file.name, await file.text()); }
// finally { if (file) await file.close(); }
const fileSelection = {
mimeTypes: ["text/*"], // 可选,默认所有文件;1–16 个类型。
maxBytes: 1024 * 1024, // 默认64 MiB,省略取host与默认较小值;显式超host RESOURCE_LIMIT。
// signal: controller.signal, // 可选;显式取消拒绝为 ABORTED。
};
/** opened 只表示已提交内部启动;dispatched 只表示已交给系统,不表示业务成功。 */
const linkOpenResults = [
{ status: "opened", target: "kodet", appId: "example.reader" },
{ status: "opened", target: "browser" },
{ status: "dispatched", target: "system" },
{ status: "cancelled" },
];
/** Intl格式化/Locale使用有效宿主语言和时区。
* const number = new Intl.NumberFormat(env.locales,{style:"currency",currency:"CNY"}).format(12);
* const date = new Intl.DateTimeFormat(undefined,{timeZone:env.timeZone}).format(new Date());
* 新实例使用最新环境,旧实例保留resolvedOptions快照;语言/时区数据按需加载。
* Reader的原文/简体/繁体显示由宿主OpenCC提供,保留原文与稳定段落坐标。
*/
/** 通用渲染任务,明确会话复用而实例独立。
* const rendered = await web.render(url, { session:web.session("login"), waitFor:"domcontentloaded",
* selector:"main", script:"document.title", timeoutMs:15000, signal });
* 返回url/html/value/userAgent;等待最终主文档/元素后提取,关闭/取消销毁实例,每Runtime最多2路。
* 缺少隔离Profile(如Android6旧Provider)明确NOT_SUPPORTED,不降级共享Cookie,不实现验证绕过。
* await capabilities.get按实际服务返回格式、算法和限制;诊断耗时是墙钟时间,不等于CPU时间。
*/
/**
* 内置浏览器:从 @kodet/core 导入 web;await web.open(url, options?) 返回 Promise<void>。
* options: headers?:Record<string,string>、cookie?:string、userAgent?:string、userScript?:string、signal?:AbortSignal。
* URL 只接受无凭据 HTTP(S),显式 cookie/userAgent 覆盖同名请求头;省略保持宿主默认。
* 点击声明使用 onClick: () => web.open(url, options),不提供 Host 命令或 .run()/.wait()。
* 返回表示导航已接受,不保证网页加载完成,不返回浏览器控制对象。
* onOpen 与所属前台回调可用;模块顶层、onInit、诊断和失效 owner 不可打开。
*/