translator-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTranslator API
Translator API
Procedures
操作流程
Step 1: Identify the browser integration surface
- Inspect the workspace for browser entry points, text-input flows, localization UI, and any existing AI abstraction layer.
- Execute to inventory likely frontend files and existing Translator API markers when a Node runtime is available.
node scripts/find-translator-targets.mjs . - If a Node runtime is unavailable, inspect the nearest , HTML entry point, and framework bootstrap files manually to identify the browser app boundary.
package.json - If the workspace contains multiple frontend apps, prefer the app that contains the active route, translation UI, or user-requested feature surface.
- If the inventory still leaves multiple plausible frontend targets, stop and ask which app should receive the Translator API integration.
- If the project is not a browser web app, stop and explain that this skill does not apply.
Step 2: Confirm API viability and choose the integration shape
- Read before writing code.
references/translator-reference.md - Read when the feature needs a session wrapper, download-progress UI, streaming output, cancellation, or cleanup shape.
references/examples.md - Read when preview flags, browser channels, iframe rules, or environment constraints matter.
references/compatibility.md - Read when support checks, session creation, translation, or cleanup fail.
references/troubleshooting.md - Verify that the feature runs in a secure context.
Window - Verify that the current frame is allowed to use the permissions-policy feature.
translator - Choose the narrowest session shape that matches the task:
- bare for a fixed language pair and full-result translation
Translator.create() - monitored when the UI must surface model download progress
create() - when the UI should reveal translated output incrementally
translateStreaming() - when quota or input-size budgeting affects the flow
measureInputUsage()
- bare
- If the feature must run in a worker, on the server, or through a cloud translation contract, stop and explain the platform mismatch.
- If the project uses TypeScript, add or preserve narrow typings for the Translator API surface used by the feature.
Step 3: Implement a guarded translator session
- Read and adapt it to the framework, state model, and file layout in the workspace.
assets/translator-session.template.ts - Centralize support checks around ,
globalThis.isSecureContext, and the sameTranslatorandsourceLanguageshape the feature will use at runtime.targetLanguage - Gate session creation behind using the same language pair that will be passed to
Translator.availability().Translator.create() - Treat as a capability check, not a guarantee that creation will succeed without download time, policy approval, or user activation.
availability() - Create sessions only after user activation when creation may trigger a model download.
- Use the option during
monitorwhen the product needs download progress.create() - Use for cancelable
AbortController,create(),translate(), ortranslateStreaming()calls, and callmeasureInputUsage()when the session is no longer needed.destroy() - Recreate the session instead of mutating or
sourceLanguageafter creation; session options are fixed per instance.targetLanguage - If the feature lives in a cross-origin iframe, require explicit delegation through .
allow="translator"
Step 4: Wire UX and fallback behavior
- Surface distinct states for missing APIs, insecure contexts, blocked frames, unsupported language pairs, downloadable or downloading models, ready sessions, in-flight translation, and aborted work.
- Keep a non-AI fallback for unsupported browsers, blocked frames, or environments that do not meet current preview requirements.
- Preserve the source and target language pair explicitly in product state instead of inferring them from translated output.
- Use when downstream logic needs the full result before continuing, and use
translate()when the UI should reveal translated text incrementally.translateStreaming() - Use when large inputs can exceed session quota.
measureInputUsage() - Treat same-language or best-fit identity translations as valid outcomes instead of forcing a fallback when the translated result matches the input.
- Chunk or queue long-running product workflows deliberately; translation requests are not a substitute for general summarization, writing, or chat tasks.
- Do not route generic cloud translation, document localization pipelines, or server-side batch translation through this API; switch to the approved service or runtime when the task is not browser on-device translation.
Step 5: Validate behavior
- Execute to confirm that the intended app boundary and Translator API markers still resolve to the edited integration surface.
node scripts/find-translator-targets.mjs . - Verify secure-context checks, feature detection, and
Translatorbehavior before debugging deeper runtime failures.availability() - Test at least one plus
create()flow with representative user text for the target language pair.translate() - If the feature exposes streaming, test separately and confirm partial output stops cleanly on abort.
translateStreaming() - If the feature depends on quota budgeting, verify behavior before sending large input.
measureInputUsage() - Confirm that cancellation rejects with the expected abort reason and that destroyed sessions are not reused.
- If the target environment depends on preview browser flags or channel-specific behavior, confirm the required browser state from before treating failures as application bugs.
references/compatibility.md - Run the workspace build, typecheck, or tests after editing.
步骤1:确定浏览器集成范围
- 检查工作区中的浏览器入口点、文本输入流程、本地化UI以及所有现有AI抽象层。
- 当有Node运行时可用时,执行来盘点可能的前端文件和现有Translator API标记。
node scripts/find-translator-targets.mjs . - 若没有Node运行时,手动检查就近的、HTML入口点和框架启动文件,确定浏览器应用边界。
package.json - 如果工作区包含多个前端应用,优先选择包含活跃路由、翻译UI或用户请求功能界面的应用。
- 如果盘点后仍有多个可能的前端目标,暂停操作并询问需要将Translator API集成到哪个应用中。
- 如果项目不是浏览器Web应用,暂停操作并说明本技能不适用。
步骤2:确认API可行性并选择集成形式
- 编写代码前先阅读。
references/translator-reference.md - 当功能需要会话封装、下载进度UI、流式输出、取消或清理逻辑时,阅读。
references/examples.md - 当涉及预览标志、浏览器渠道、iframe规则或环境约束时,阅读。
references/compatibility.md - 当支持检测、会话创建、翻译或清理操作失败时,阅读。
references/troubleshooting.md - 确认功能运行在安全的上下文中。
Window - 确认当前框架允许使用权限策略特性。
translator - 选择符合任务要求的最小会话形式:
- 纯适用于固定语言对和全量结果翻译场景
Translator.create() - 带监控的适用于UI需要展示模型下载进度的场景
create() - 适用于UI需要逐步展示翻译输出的场景
translateStreaming() - 适用于配额或输入大小预算会影响流程的场景
measureInputUsage()
- 纯
- 如果功能必须运行在Worker、服务端或通过云翻译协议调用,暂停操作并说明平台不匹配。
- 如果项目使用TypeScript,为功能用到的Translator API接口添加或保留窄类型定义。
步骤3:实现带防护的翻译器会话
- 阅读,并适配工作区中的框架、状态模型和文件结构。
assets/translator-session.template.ts - 围绕、
globalThis.isSecureContext以及功能运行时会用到的Translator和sourceLanguage结构集中做支持检测。targetLanguage - 使用和传入相同的语言对,通过
Translator.create()来做会话创建的前置校验。Translator.availability() - 将视为能力检测,不代表会话创建一定能成功,可能会受下载耗时、策略审批或用户激活等因素影响。
availability() - 当创建会话可能触发模型下载时,仅在用户激活后再创建会话。
- 当产品需要展示下载进度时,在调用时使用
create()选项。monitor - 对可取消的、
create()、translate()或translateStreaming()调用使用measureInputUsage(),会话不再需要时调用AbortController。destroy() - 会话创建后不要修改或
sourceLanguage,而是重新创建会话;每个实例的会话选项是固定的。targetLanguage - 如果功能位于跨源iframe中,需要通过显式授权。
allow="translator"
步骤4:对接UX和降级逻辑
- 为以下场景分别展示不同状态:API缺失、不安全上下文、框架被屏蔽、语言对不支持、模型可下载/下载中、会话就绪、翻译中、任务已中止。
- 为不支持的浏览器、被屏蔽的框架或不符合当前预览要求的环境保留非AI降级方案。
- 在产品状态中显式存储源语言和目标语言对,不要通过翻译输出反向推断。
- 当下游逻辑需要获取全量结果后再继续时使用,UI需要逐步展示翻译文本时使用
translate()。translateStreaming() - 当大输入可能超出会话配额时使用。
measureInputUsage() - 当翻译结果和输入一致时,将同语言或最佳匹配的同一性翻译视为合法结果,不要强制降级。
- 对长时间运行的产品工作流做刻意的分块或队列处理;翻译请求不能替代通用的摘要、写作或聊天任务。
- 不要将通用云翻译、文档本地化流水线或服务端批量翻译路由到该API;如果任务不是浏览器端侧翻译,切换到获批的服务或运行时。
步骤5:验证行为
- 执行,确认预期的应用边界和Translator API标记仍指向修改后的集成范围。
node scripts/find-translator-targets.mjs . - 在调试更深层的运行时故障前,先验证安全上下文检测、特性检测和
Translator的行为是否正常。availability() - 针对目标语言对,使用有代表性的用户文本测试至少一次加
create()的完整流程。translate() - 如果功能支持流式输出,单独测试,确认中止时部分输出会正常停止。
translateStreaming() - 如果功能依赖配额预算,在发送大输入前验证的行为是否正常。
measureInputUsage() - 确认取消操作会按预期抛出中止原因,且已销毁的会话不会被复用。
- 如果目标环境依赖预览浏览器标志或特定渠道的行为,在将故障判定为应用bug前,先从确认所需的浏览器状态。
references/compatibility.md - 修改完成后运行工作区的构建、类型检查或测试任务。
Error Handling
错误处理
- If is missing, keep a non-AI fallback and confirm secure-context, browser, channel, and flag requirements before changing product logic.
Translator - If returns
availability()ordownloadable, require user-driven session creation before promising that translation is ready.downloading - If throws
create(), check permissions-policy constraints, missing user activation for downloads, browser policy restrictions, or user rejection.NotAllowedError - If throws
create(), treat model initialization as failed and retry only after checking browser state, required flags, and download readiness.OperationError - If a translation call throws , reduce the input size or measure usage before retrying.
QuotaExceededError - If a translation call throws or
NotReadableError, surface a visible fallback instead of retrying blindly with the same input.UnknownError - If the feature must run in a worker or server context, stop and explain that the Translator API is a window-only browser API.
- 如果不存在,保留非AI降级方案,修改产品逻辑前先确认安全上下文、浏览器、渠道和标志要求是否满足。
Translator - 如果返回
availability()或downloadable,在承诺翻译就绪前需要用户主动触发会话创建。downloading - 如果抛出
create(),检查权限策略约束、下载缺少用户激活、浏览器策略限制或用户拒绝授权等情况。NotAllowedError - 如果抛出
create(),判定为模型初始化失败,仅在检查浏览器状态、所需标志和下载就绪状态后再重试。OperationError - 如果翻译调用抛出,减小输入大小或先统计使用量再重试。
QuotaExceededError - 如果翻译调用抛出或
NotReadableError,展示可见的降级提示,不要用相同输入盲目重试。UnknownError - 如果功能必须运行在Worker或服务端上下文,暂停操作并说明Translator API是仅Window可用的浏览器API。