fancive_obsidian-parallel-r.../main.js
wujunchen 206a50f8d0 fix: guard regeneration and scroll sync
Change-Id: I08e2c55d5e88a51bad9a007e57962ebe48dc7c64
2026-04-25 19:52:27 +08:00

101 lines
80 KiB
JavaScript

'use strict';
"use strict";var et=Object.create;var B=Object.defineProperty;var tt=Object.getOwnPropertyDescriptor;var at=Object.getOwnPropertyNames;var rt=Object.getPrototypeOf,nt=Object.prototype.hasOwnProperty;var it=(a,e)=>{for(var t in e)B(a,t,{get:e[t],enumerable:!0})},Ve=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of at(e))!nt.call(a,i)&&i!==t&&B(a,i,{get:()=>e[i],enumerable:!(r=tt(e,i))||r.enumerable});return a};var U=(a,e,t)=>(t=a!=null?et(rt(a)):{},Ve(e||!a||!a.__esModule?B(t,"default",{value:a,enumerable:!0}):t,a)),st=a=>Ve(B({},"__esModule",{value:!0}),a);var It={};it(It,{__test:()=>Mt,default:()=>Dt});module.exports=st(It);var c=require("obsidian"),Xe=require("child_process"),te=U(require("os")),x=U(require("path")),Ze=U(require("fs"));function j(a,e){if(!e)return-1;let t=p=>p.replace(/\s+/g," ").trim(),r=p=>{let h=[],m=[],u=!1;for(let S=0;S<p.length;S++){let _e=p[S];if(/\s/.test(_e)){u=h.length>0;continue}u&&(h.push(" "),m.push(S),u=!1),h.push(_e),m.push(S)}return{text:h.join(""),map:m}},i=p=>{if(!p)return-1;let h=a.indexOf(p);if(h===-1)return-1;let m=0;for(let u=0;u<h;u++)a[u]===`
`&&m++;return m},n=i(e);if(n>=0||(n=i(e.trim()),n>=0))return n;for(let p of[60,40,25,15]){let h=e.trim().slice(0,p);if(n=i(h),n>=0)return n}let s=r(a),o=t(e).slice(0,30);if(!o)return-1;let l=s.text.indexOf(o);if(l===-1)return-1;let d=s.map[l];if(d==null)return-1;let f=0;for(let p=0;p<d;p++)a[p]===`
`&&f++;return f}function ie(a,e){return a?(a.lastAccessedAt=e||new Date().toISOString(),a):null}function se(a){return JSON.stringify({version:1,entries:a||{}})}function oe(a,e){return!!e&&!!a&&typeof a.updatedAt=="string"&&a.updatedAt.trim().length>0}function ce(a,e){let t=Array.isArray(a)?a.slice():[];return!Number.isInteger(e)||e<0||e>=t.length||t.splice(e,1),t}function le(a,e,t){if(!Number.isInteger(a)||!Number.isInteger(e)||e<=0||!Number.isInteger(t)||t<0||a<0||a>=e)return t;let r=e-1;return r<=0?-1:a<t?Math.max(0,t-1):a===t?Math.min(t,r-1):t}function ue(a,e,t){let r=Array.isArray(a)?a.slice():[];return!Number.isInteger(e)||e<0||e>=r.length||(r[e]=Object.assign({},r[e],t||{})),r}var H={zh:{appTitle:"\u5BF9\u7167\u9605\u8BFB\u7B14\u8BB0",settingsTitle:"Parallel Reader \u8BBE\u7F6E",emptyOpenNote:"\u6253\u5F00\u4E00\u7BC7\u7B14\u8BB0\uFF0C\u7136\u540E\u8FD0\u884C\u547D\u4EE4\uFF1A",emptyNoCache:"\u8BE5\u7B14\u8BB0\u5C1A\u65E0\u5BF9\u7167\u7B14\u8BB0\u7F13\u5B58\u3002\u8FD0\u884C\u547D\u4EE4\uFF1A",commandGenerate:"Parallel Reader: \u4E3A\u5F53\u524D\u7B14\u8BB0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",displayName:"\u5BF9\u7167\u9605\u8BFB\u7B14\u8BB0",ribbonOpen:"\u6253\u5F00\u5BF9\u7167\u7B14\u8BB0\u9762\u677F",cmdRun:"\u4E3A\u5F53\u524D\u7B14\u8BB0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0\uFF08\u7F13\u5B58\u4F18\u5148\uFF09",cmdRegen:"\u5F3A\u5236\u91CD\u65B0\u751F\u6210\uFF08\u7ED5\u8FC7\u7F13\u5B58\uFF09",cmdOpenView:"\u6253\u5F00\u5BF9\u7167\u7B14\u8BB0\u9762\u677F",cmdExport:"\u5BFC\u51FA\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0\u5230 Vault",cmdCopyMarkdown:"\u590D\u5236\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0 Markdown",cmdCancel:"\u53D6\u6D88\u5F53\u524D\u5BF9\u7167\u7B14\u8BB0\u751F\u6210",cmdClearCurrent:"\u6E05\u9664\u5F53\u524D\u7B14\u8BB0\u7684\u7F13\u5B58",cmdClearAll:"\u6E05\u9664\u6240\u6709\u7F13\u5B58",cmdCardPrev:"\u805A\u7126\u4E0A\u4E00\u5F20\u6458\u8981\u5361\u7247",cmdCardNext:"\u805A\u7126\u4E0B\u4E00\u5F20\u6458\u8981\u5361\u7247",cmdCardJump:"\u8DF3\u8F6C\u5230\u5F53\u524D\u6458\u8981\u5361\u7247\u539F\u6587",actionCancel:"\u53D6\u6D88\u751F\u6210",actionRegenerate:"\u91CD\u65B0\u751F\u6210",actionCopyAll:"\u590D\u5236\u5168\u90E8 Markdown",actionExport:"\u5BFC\u51FA\u5230 Vault",staleBanner:"\u6E90\u7B14\u8BB0\u6216\u751F\u6210\u914D\u7F6E\u5DF2\u4FEE\u6539\uFF0C\u5F53\u524D\u662F\u65E7\u7F13\u5B58\u3002",loadingDefault:"\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0...",loadingGenerating:"\u5BF9\u7167\u9605\u8BFB\uFF1A\u8BA9 LLM \u8BFB\u5168\u6587\u5E76\u81EA\u9002\u5E94\u5207\u6BB5...",loadingSubtitle:"\u53EF\u4EE5\u7EE7\u7EED\u9605\u8BFB\u539F\u6587\uFF0C\u751F\u6210\u5B8C\u6210\u540E\u4F1A\u81EA\u52A8\u5237\u65B0\u53F3\u4FA7\u5361\u7247\u3002",errorTitle:"\u751F\u6210\u5931\u8D25",emptyCard:"\uFF08\u672A\u751F\u6210\uFF09",anchorMismatch:"anchor \u5339\u914D\u5931\u8D25\uFF0C\u65E0\u6CD5\u6EDA\u52A8\u8054\u52A8",menuCopyMarkdown:"\u590D\u5236 Markdown",menuCopyPlain:"\u590D\u5236\u7EAF\u6587\u672C",menuCopyAnchor:"\u590D\u5236 anchor \u5F15\u7528",menuJumpSource:"\u8DF3\u8F6C\u5230\u539F\u6587",menuEditCard:"\u7F16\u8F91\u6B64\u5361\u7247",menuDeleteCard:"\u5220\u9664\u6B64\u5361\u7247",copiedMarkdown:"\u5DF2\u590D\u5236 Markdown",copiedPlain:"\u5DF2\u590D\u5236\u7EAF\u6587\u672C",copiedAnchor:"\u5DF2\u590D\u5236\u5F15\u7528\u539F\u6587",copiedAllMarkdown:"\u5DF2\u590D\u5236\u5168\u90E8 Markdown",copyFailed:"\u590D\u5236\u5931\u8D25\uFF1A{error}",actionFailed:"{label}\u5931\u8D25\uFF1A{error}",exported:"\u5DF2\u5BFC\u51FA \u2192 {path}",noCurrentNote:"\u6CA1\u6709\u5F53\u524D\u7B14\u8BB0",cacheClearedFile:"\u5DF2\u6E05\u9664\u7F13\u5B58\uFF1A{name}",cacheClearedAll:"\u5DF2\u6E05\u9664 {count} \u6761\u7F13\u5B58",noCancelableJob:"\u5F53\u524D\u6CA1\u6709\u53EF\u53D6\u6D88\u7684\u751F\u6210\u4EFB\u52A1",cancelRequested:"\u5DF2\u8BF7\u6C42\u53D6\u6D88\u751F\u6210",cancelRequestedApiInFlight:"\u5DF2\u8BF7\u6C42\u53D6\u6D88\u751F\u6210\uFF1B\u5F53\u524D API \u8BF7\u6C42\u65E0\u6CD5\u7ACB\u5373\u4E2D\u65AD\uFF0C\u8FD4\u56DE\u540E\u4F1A\u4E22\u5F03\u7ED3\u679C\u3002",fileMenuGenerate:"\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",fileMenuRegen:"\u5F3A\u5236\u91CD\u65B0\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",fileMenuClear:"\u6E05\u9664\u5BF9\u7167\u7B14\u8BB0\u7F13\u5B58",noExportContent:"\u5F53\u524D\u6CA1\u6709\u53EF\u5BFC\u51FA\u7684\u5BF9\u7167\u7B14\u8BB0",noCopyContent:"\u5F53\u524D\u6CA1\u6709\u53EF\u590D\u5236\u7684\u5BF9\u7167\u7B14\u8BB0",noActiveCard:"\u5F53\u524D\u6CA1\u6709\u53EF\u8DF3\u8F6C\u7684\u6458\u8981\u5361\u7247",confirmRegenerateEditedCards:"\u8FD9\u7BC7\u7B14\u8BB0\u7684\u5BF9\u7167\u5361\u7247\u5DF2\u88AB\u624B\u52A8\u7F16\u8F91\u3002\u91CD\u65B0\u751F\u6210\u4F1A\u8986\u76D6\u8FD9\u4E9B\u4FEE\u6539\uFF0C\u662F\u5426\u7EE7\u7EED\uFF1F",regenerateCancelled:"\u5DF2\u53D6\u6D88\u91CD\u65B0\u751F\u6210",cardDeleted:"\u5DF2\u5220\u9664\u6B64\u5361\u7247",cardSaved:"\u5DF2\u4FDD\u5B58\u6B64\u5361\u7247",editCardTitle:"\u7F16\u8F91\u6458\u8981\u5361\u7247",editCardTitleField:"\u6807\u9898",editCardGistField:"\u9886\u8BFB",editCardBulletsField:"\u8981\u70B9\uFF08\u6BCF\u884C\u4E00\u6761\uFF09",editCardCancel:"\u53D6\u6D88",editCardSave:"\u4FDD\u5B58",openNoteFirst:"\u5148\u6253\u5F00\u4E00\u7BC7\u7B14\u8BB0",alreadyGenerating:"\u8BE5\u7B14\u8BB0\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0",emptyNote:"\u7B14\u8BB0\u4E3A\u7A7A",longNoteTruncated:"\u7B14\u8BB0\u8F83\u957F\uFF1A\u4EC5\u53D1\u9001\u524D {count} \u4E2A\u5B57\u7B26\u7ED9\u6A21\u578B",generatingNotice:"\u5BF9\u7167\u9605\u8BFB\uFF1A\u8BA9 LLM \u8BFB\u5168\u6587\u5E76\u81EA\u9002\u5E94\u5207\u6BB5\u2026",noCardsReturned:"LLM \u672A\u8FD4\u56DE\u4EFB\u4F55 card",generationDone:"\u5BF9\u7167\u7B14\u8BB0\u751F\u6210\u5B8C\u6210\uFF1A{count} \u6BB5{suffix}",unanchoredSuffix:"\uFF08\u26A0 {count} \u6BB5 anchor \u672A\u5339\u914D\uFF09",cancelled:"\u5DF2\u53D6\u6D88\u751F\u6210",cancelledError:"\u751F\u6210\u5DF2\u53D6\u6D88",generationFailed:"\u751F\u6210\u5931\u8D25{kind}\uFF1A{error}",errorCustomProviderBaseUrlRequired:"\u81EA\u5B9A\u4E49 provider \u9700\u8981\u586B\u5199 API Base URL\u3002",errorApiBaseUrlMissing:"API Base URL \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u9009\u62E9 provider \u6216\u586B\u5199\u81EA\u5B9A\u4E49 base URL\u3002",errorModelMissing:"Model \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u586B\u5199\u6A21\u578B ID\u3002",errorApiKeyMissing:"API key \u672A\u8BBE\u7F6E\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u586B\u5199 API Key{hint}\u3002",errorApiKeyEnvHint:" \u6216\u73AF\u5883\u53D8\u91CF {envVar}",errorLlmNonJson:`LLM \u8FD4\u56DE\u975E JSON\uFF1A
{excerpt}`,errorCustomHeadersJsonParse:"\u81EA\u5B9A\u4E49 headers JSON \u89E3\u6790\u5931\u8D25\uFF1A{error}",errorCustomHeadersJsonObject:"\u81EA\u5B9A\u4E49 headers JSON \u5FC5\u987B\u662F\u5BF9\u8C61",errorCustomHeadersLineFormat:"\u81EA\u5B9A\u4E49 headers \u6BCF\u884C\u683C\u5F0F\u5E94\u4E3A `Header-Name: value`",errorProviderNonJson:`{label} \u8FD4\u56DE\u975E JSON\uFF1A
{excerpt}`,errorProviderRequestFailed:"{label} \u8BF7\u6C42\u5931\u8D25\uFF1A{error}",errorProviderApiStatus:"{label} API \u8FD4\u56DE HTTP {status}\uFF1A{excerpt}",noEditor:"\u627E\u4E0D\u5230\u6E90\u7B14\u8BB0\u5BF9\u5E94\u7684\u7F16\u8F91\u5668\u7A97\u53E3",settingUiLanguageName:"\u754C\u9762\u8BED\u8A00",settingUiLanguageDesc:"\u63A7\u5236\u63D2\u4EF6\u754C\u9762\u3001\u547D\u4EE4\u548C\u63D0\u793A\u6587\u6848\uFF1BAuto \u8DDF\u968F Obsidian/\u7CFB\u7EDF\u8BED\u8A00",settingBackendName:"Backend",settingBackendDesc:"\u751F\u6210 bullet \u7684\u540E\u7AEF\uFF1ACLI \u590D\u7528\u672C\u673A\u767B\u5F55\uFF1BAPI \u652F\u6301 OpenAI/Anthropic/Gemini \u53CA\u517C\u5BB9\u4EE3\u7406",settingCliPathName:"CLI \u8DEF\u5F84\uFF08\u53EF\u9009\uFF09",settingCliPathDesc:"\u7559\u7A7A\u5219\u81EA\u52A8\u63A2\u6D4B\u5E38\u89C1\u4F4D\u7F6E\uFF1BObsidian GUI \u542F\u52A8\u65F6\u4E0D\u7EE7\u627F shell PATH\uFF0C\u5FC5\u8981\u65F6\u586B\u7EDD\u5BF9\u8DEF\u5F84",settingCliPathPlaceholder:"\u4F8B\uFF1A/Users/you/bin/codex",settingCliTimeoutName:"CLI \u8D85\u65F6 (ms)",apiProviderHeader:"API Provider",settingProviderPresetName:"Provider preset",settingProviderPresetDesc:"\u53C2\u8003 OpenClaw \u7684 provider/model \u601D\u8DEF\uFF1Apreset \u53EA\u8D1F\u8D23\u534F\u8BAE\u3001base URL \u548C\u8BA4\u8BC1\u9ED8\u8BA4\u503C",settingApiFormatName:"API format",settingApiFormatDesc:"\u4E0D\u540C provider \u7684 wire protocol\uFF1BOpenAI-compatible \u4EE3\u7406\u901A\u5E38\u9009 Chat Completions",settingBaseUrlName:"Base URL",settingBaseUrlDesc:"\u586B provider \u6839\u5730\u5740\uFF0C\u4E0D\u8981\u9644\u52A0 /chat/completions\uFF1B\u7559\u7A7A\u65F6\u4F7F\u7528 preset \u9ED8\u8BA4\u503C",settingApiKeyName:"API Key",settingApiKeyDesc:"\u672C\u5730 Ollama/LM Studio \u53EF\u7559\u7A7A\uFF1B\u5176\u4ED6 provider \u901A\u5E38\u9700\u8981 key",settingApiKeyEnvName:"API Key \u73AF\u5883\u53D8\u91CF",settingApiKeyEnvDesc:"\u53EF\u9009\uFF1BObsidian GUI \u4E0D\u4E00\u5B9A\u7EE7\u627F shell \u73AF\u5883\uFF0C\u76F4\u63A5\u586B API Key \u66F4\u7A33\u5B9A",settingAuthTypeName:"\u8BA4\u8BC1\u65B9\u5F0F",settingAuthTypeDesc:"Auto \u4F7F\u7528 provider preset\uFF1B\u81EA\u5B9A\u4E49\u4EE3\u7406\u53EF\u6309\u9700\u8981\u6539\u6210 Bearer\u3001x-api-key \u6216 none",settingHeadersName:"\u989D\u5916 headers",settingHeadersDesc:"\u53EF\u9009\u3002\u652F\u6301 JSON \u5BF9\u8C61\u6216\u6BCF\u884C `Header: value`\uFF0C\u7528\u4E8E Cloudflare AI Gateway \u7B49\u4EE3\u7406",settingMaxTokensName:"\u6700\u5927\u8F93\u51FA tokens",settingModelName:"Model",settingModelDescApi:"API \u8C03\u7528\u7684\u6A21\u578B ID\uFF1B\u652F\u6301 OpenClaw \u98CE\u683C provider/model\uFF0C\u82E5 provider \u524D\u7F00\u5339\u914D\u5F53\u524D preset \u4F1A\u81EA\u52A8\u5265\u79BB",settingModelDescCli:"Claude Code \u4E0B\u4F1A\u4F20 --model\uFF1BCodex \u4E0B\u901A\u5E38\u5FFD\u7565\uFF08\u7528 Codex \u9ED8\u8BA4\u914D\u7F6E\uFF09",settingMaxInputName:"\u6700\u5927\u8F93\u5165\u5B57\u7B26\u6570",settingMaxInputDesc:"\u8D85\u8FC7\u8BE5\u957F\u5EA6\u4F1A\u622A\u65AD\u540E\u518D\u53D1\u9001\u7ED9\u6A21\u578B\uFF1B\u957F\u4E0A\u4E0B\u6587\u6A21\u578B\u53EF\u9002\u5F53\u8C03\u5927",promptHeader:"Prompt",settingPromptLanguageName:"\u8F93\u51FA\u8BED\u8A00",settingPromptLanguageDesc:"\u63A7\u5236 title/gist/bullets \u7684\u8BED\u8A00\uFF1Banchor \u59CB\u7EC8\u9010\u5B57\u590D\u5236\u539F\u6587",settingCardRangeName:"\u5361\u7247\u6570\u91CF\u8303\u56F4",settingCardRangeDesc:"\u6A21\u578B\u4F1A\u5728\u8FD9\u4E2A\u8303\u56F4\u5185\u81EA\u9002\u5E94\u5207\u6BB5",settingCustomPromptName:"\u81EA\u5B9A\u4E49 system prompt",settingCustomPromptDesc:"\u53EF\u9009\u3002\u652F\u6301\u53D8\u91CF\uFF1A{minCards}\u3001{maxCards}\u3001{languageInstruction}\u3001{schema}\u3001{example}",settingCustomPromptPlaceholder:"\u7559\u7A7A\u4F7F\u7528\u5185\u7F6E prompt",settingTestBackendName:"\u6D4B\u8BD5\u5F53\u524D\u540E\u7AEF",settingTestBackendDescApi:"\u4F1A\u53D1\u8D77\u4E00\u6B21\u6700\u5C0F LLM \u8BF7\u6C42\u9A8C\u8BC1 API \u8BBE\u7F6E",settingTestBackendDescCli:"\u8C03\u7528 `<cli> --version` \u9A8C\u8BC1 spawn \u80FD\u627E\u5230\u4E8C\u8FDB\u5236",backendTestFailed:"\u2717 \u540E\u7AEF\u6D4B\u8BD5\u5931\u8D25\uFF1A{error}",settingExportFolderName:"\u5BFC\u51FA\u6587\u4EF6\u5939",settingExportFolderDesc:"\u5BF9\u7167\u7B14\u8BB0\u751F\u6210\u4F4D\u7F6E\uFF08\u76F8\u5BF9 Vault \u6839\uFF09",cacheHeader:"\u7F13\u5B58",settingMaxCacheName:"\u6700\u5927\u7F13\u5B58\u7BC7\u6570",settingMaxCacheDesc:"\u8D85\u8FC7\u4E0A\u9650\u540E\u6309\u6700\u8FD1\u8BBF\u95EE\u65F6\u95F4\u6DD8\u6C70\u6700\u65E7\u7684\u7B14\u8BB0\u7F13\u5B58\uFF1B\u7F13\u5B58\u4FDD\u5B58\u5728\u63D2\u4EF6\u76EE\u5F55\u7684 cache.json",cachePruned:"\u5DF2\u6DD8\u6C70 {count} \u6761\u65E7\u7F13\u5B58",cachedNotesName:"\u5DF2\u7F13\u5B58\u7B14\u8BB0\uFF1A{count} \u7BC7",cachedNotesDesc:"\u7F13\u5B58\u4EE5\u6E90\u7B14\u8BB0 SHA1 + \u751F\u6210\u914D\u7F6E\u6307\u7EB9\u4F5C\u4E3A\u5931\u6548\u952E\uFF0C\u6E90\u7B14\u8BB0\u6216\u6A21\u578B\u914D\u7F6E\u4FEE\u6539\u540E\u4F1A\u663E\u793A stale \u63D0\u793A",clearAllCacheButton:"\u6E05\u9664\u6240\u6709\u7F13\u5B58"},en:{appTitle:"Parallel Reader",settingsTitle:"Parallel Reader Settings",emptyOpenNote:"Open a note, then run:",emptyNoCache:"This note has no cached parallel notes. Run:",commandGenerate:"Parallel Reader: Generate notes for current note",displayName:"Parallel Reader",ribbonOpen:"Open Parallel Reader pane",cmdRun:"Generate parallel notes for current note (cache first)",cmdRegen:"Regenerate parallel notes (bypass cache)",cmdOpenView:"Open Parallel Reader pane",cmdExport:"Export current parallel notes to Vault",cmdCopyMarkdown:"Copy current parallel notes as Markdown",cmdCancel:"Cancel current parallel-note generation",cmdClearCurrent:"Clear cache for current note",cmdClearAll:"Clear all caches",cmdCardPrev:"Focus previous summary card",cmdCardNext:"Focus next summary card",cmdCardJump:"Jump current summary card to source",actionCancel:"Cancel generation",actionRegenerate:"Regenerate",actionCopyAll:"Copy all Markdown",actionExport:"Export to Vault",staleBanner:"The source note or generation settings changed. This is stale cache.",loadingDefault:"Generating parallel notes...",loadingGenerating:"Parallel Reader: asking the LLM to read and segment the full note...",loadingSubtitle:"You can keep reading. Cards will refresh when generation finishes.",errorTitle:"Generation failed",emptyCard:"(not generated)",anchorMismatch:"Anchor did not match; scroll sync is unavailable",menuCopyMarkdown:"Copy Markdown",menuCopyPlain:"Copy plain text",menuCopyAnchor:"Copy anchor quote",menuJumpSource:"Jump to source",menuEditCard:"Edit this card",menuDeleteCard:"Delete this card",copiedMarkdown:"Copied Markdown",copiedPlain:"Copied plain text",copiedAnchor:"Copied anchor quote",copiedAllMarkdown:"Copied all Markdown",copyFailed:"Copy failed: {error}",actionFailed:"{label} failed: {error}",exported:"Exported \u2192 {path}",noCurrentNote:"No current note",cacheClearedFile:"Cleared cache: {name}",cacheClearedAll:"Cleared {count} cache entries",noCancelableJob:"No cancellable generation job",cancelRequested:"Cancel requested",cancelRequestedApiInFlight:"Cancel requested. The in-flight API request cannot be aborted immediately; its result will be ignored.",fileMenuGenerate:"Generate parallel notes",fileMenuRegen:"Regenerate parallel notes",fileMenuClear:"Clear parallel-note cache",noExportContent:"No parallel notes to export",noCopyContent:"No parallel notes to copy",noActiveCard:"No active summary card to jump",confirmRegenerateEditedCards:"These parallel-reader cards were edited manually. Regenerating will overwrite those edits. Continue?",regenerateCancelled:"Regeneration cancelled",cardDeleted:"Deleted this card",cardSaved:"Saved this card",editCardTitle:"Edit summary card",editCardTitleField:"Title",editCardGistField:"Gist",editCardBulletsField:"Bullets (one per line)",editCardCancel:"Cancel",editCardSave:"Save",openNoteFirst:"Open a note first",alreadyGenerating:"This note is already being generated",emptyNote:"The note is empty",longNoteTruncated:"Long note: only the first {count} characters will be sent to the model",generatingNotice:"Parallel Reader: asking the LLM to read and segment the full note...",noCardsReturned:"LLM returned no cards",generationDone:"Generated {count} sections{suffix}",unanchoredSuffix:" (\u26A0 {count} anchors unmatched)",cancelled:"Generation cancelled",cancelledError:"Generation cancelled",generationFailed:"Generation failed{kind}: {error}",errorCustomProviderBaseUrlRequired:"Custom provider requires an API Base URL.",errorApiBaseUrlMissing:"API Base URL is not set. Choose a provider or enter a custom base URL in settings.",errorModelMissing:"Model is not set. Enter a model ID in settings.",errorApiKeyMissing:"API key is not set. Enter an API Key in settings{hint}.",errorApiKeyEnvHint:" or set environment variable {envVar}",errorLlmNonJson:`LLM returned non-JSON:
{excerpt}`,errorCustomHeadersJsonParse:"Custom headers JSON parse failed: {error}",errorCustomHeadersJsonObject:"Custom headers JSON must be an object",errorCustomHeadersLineFormat:"Custom headers lines must use `Header-Name: value`",errorProviderNonJson:`{label} returned non-JSON:
{excerpt}`,errorProviderRequestFailed:"{label} request failed: {error}",errorProviderApiStatus:"{label} API returned HTTP {status}: {excerpt}",noEditor:"Could not find the source note editor",settingUiLanguageName:"UI language",settingUiLanguageDesc:"Controls plugin UI, commands, and notices. Auto follows Obsidian/system language.",settingBackendName:"Backend",settingBackendDesc:"Backend for generating bullets: CLI reuses local login; API supports OpenAI, Anthropic, Gemini, and compatible proxies.",settingCliPathName:"CLI path (optional)",settingCliPathDesc:"Leave blank to auto-detect common paths. Obsidian launched from the GUI may not inherit shell PATH.",settingCliPathPlaceholder:"Example: /Users/you/bin/codex",settingCliTimeoutName:"CLI timeout (ms)",apiProviderHeader:"API Provider",settingProviderPresetName:"Provider preset",settingProviderPresetDesc:"OpenClaw-style provider/model setup: presets define protocol, base URL, and auth defaults.",settingApiFormatName:"API format",settingApiFormatDesc:"Wire protocol for the provider. OpenAI-compatible proxies usually use Chat Completions.",settingBaseUrlName:"Base URL",settingBaseUrlDesc:"Provider root URL, without /chat/completions. Blank uses the preset default.",settingApiKeyName:"API Key",settingApiKeyDesc:"Can be blank for local Ollama/LM Studio; most hosted providers require a key.",settingApiKeyEnvName:"API key env var",settingApiKeyEnvDesc:"Optional. Obsidian GUI may not inherit shell env; direct API Key is usually more reliable.",settingAuthTypeName:"Auth type",settingAuthTypeDesc:"Auto uses provider preset. Custom proxies can use Bearer, x-api-key, or none.",settingHeadersName:"Extra headers",settingHeadersDesc:"Optional. JSON object or one `Header: value` per line, useful for Cloudflare AI Gateway.",settingMaxTokensName:"Max output tokens",settingModelName:"Model",settingModelDescApi:"Model ID for API calls. Supports OpenClaw-style provider/model; matching provider prefixes are stripped.",settingModelDescCli:"Passed as --model for Claude Code. Usually ignored by Codex, which uses its default config.",settingMaxInputName:"Max input characters",settingMaxInputDesc:"Longer notes are truncated before sending to the model. Raise this for long-context models.",promptHeader:"Prompt",settingPromptLanguageName:"Output language",settingPromptLanguageDesc:"Controls title/gist/bullets language. Anchor is always copied verbatim from source.",settingCardRangeName:"Card count range",settingCardRangeDesc:"The model adapts segmentation within this range.",settingCustomPromptName:"Custom system prompt",settingCustomPromptDesc:"Optional. Variables: {minCards}, {maxCards}, {languageInstruction}, {schema}, {example}",settingCustomPromptPlaceholder:"Leave blank to use built-in prompt",settingTestBackendName:"Test current backend",settingTestBackendDescApi:"Sends a minimal LLM request to validate API settings.",settingTestBackendDescCli:"Runs `<cli> --version` to verify the binary can be spawned.",backendTestFailed:"\u2717 Backend test failed: {error}",settingExportFolderName:"Export folder",settingExportFolderDesc:"Parallel-note output location, relative to the Vault root.",cacheHeader:"Cache",settingMaxCacheName:"Max cached notes",settingMaxCacheDesc:"Prunes least-recently accessed note caches above this limit. Cache is stored in plugin cache.json.",cachePruned:"Pruned {count} old cache entries",cachedNotesName:"Cached notes: {count}",cachedNotesDesc:"Cache is invalidated by source SHA1 and generation settings fingerprint.",clearAllCacheButton:"Clear all caches"}};function ot(a){let e=a&&a.uiLanguage;return e==="zh"||e==="en"?e:String((typeof navigator<"u"?navigator:null)?.language||"").toLowerCase().startsWith("zh")?"zh":"en"}function y(a,e,t){let r=ot(a),i=H[r]||H.en,n=H.en[e]||H.zh[e]||e,s=i[e]||n;return String(s).replace(/\{([a-zA-Z0-9_]+)\}/g,(o,l)=>t&&Object.prototype.hasOwnProperty.call(t,l)?String(t[l]):o)}function pe(a){let e=[`## ${a.title}`];if(a.anchor){let t=a.anchor.replace(/\s+/g," ").trim();e.push(`> ${t}`)}return a.gist&&e.push(a.gist),a.bullets&&a.bullets.length>0&&e.push(a.bullets.map(t=>`- ${t}`).join(`
`)),e.join(`
`)}function Be(a){return[a.title,a.gist||"",...(a.bullets||[]).map(e=>"\u2022 "+e)].filter(Boolean).join(`
`)}function G(a,e){let t=[`# ${a||"\u5BF9\u7167\u7B14\u8BB0"}`];for(let r of e||[])t.push(pe(r));return t.join(`
`)}function de(a,e,t){if(!Number.isFinite(e)||e<=0)return-1;let r=Math.floor(e),i=t<0?-1:1;return a<0||a>=r?i<0?r-1:0:Math.min(r-1,Math.max(0,a+i))}function he(a,e){if(!Array.isArray(a)||e<0||e>=a.length)return-1;let t=Number(a[e]?.startLine);return Number.isFinite(t)&&t>=0?t:-1}var He=U(require("crypto"));var ge=2e4,ct=2,D=2,M=100,I={zh:"\u4E2D\u6587",en:"English",auto:"Auto-detect"},fe={auto:"Auto",zh:"\u4E2D\u6587",en:"English"},g={uiLanguage:"auto",backend:"claude-code",cliPath:"",apiProvider:"anthropic",apiFormat:"anthropic-messages",apiBaseUrl:"",apiKey:"",apiKeyEnvVar:"",apiAuthType:"auto",apiHeaders:"",apiMaxTokens:4096,maxDocChars:ge,maxCacheEntries:M,promptLanguage:"zh",minCards:5,maxCards:15,customSystemPrompt:"",model:"claude-sonnet-4-6",exportFolder:"Reading/Articles",cliTimeoutMs:12e4},w={"anthropic-messages":{label:"Anthropic Messages",defaultBaseUrl:"https://api.anthropic.com/v1",defaultAuthType:"x-api-key"},"openai-chat":{label:"OpenAI Chat Completions",defaultBaseUrl:"https://api.openai.com/v1",defaultAuthType:"bearer",tokenLimitField:"max_tokens"},"openai-responses":{label:"OpenAI Responses",defaultBaseUrl:"https://api.openai.com/v1",defaultAuthType:"bearer"},"google-generative-ai":{label:"Google Gemini generateContent",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta",defaultAuthType:"x-goog-api-key"}},ye={auto:"Auto",bearer:"Authorization: Bearer","x-api-key":"x-api-key","x-goog-api-key":"x-goog-api-key","api-key":"api-key",none:"None"},P={anthropic:{label:"Anthropic",format:"anthropic-messages",baseUrl:"https://api.anthropic.com/v1",authType:"x-api-key",envVar:"ANTHROPIC_API_KEY",model:"claude-sonnet-4-6"},openai:{label:"OpenAI",format:"openai-chat",baseUrl:"https://api.openai.com/v1",authType:"bearer",envVar:"OPENAI_API_KEY",tokenLimitField:"max_completion_tokens",model:"gpt-5.1"},"openai-responses":{label:"OpenAI Responses",format:"openai-responses",baseUrl:"https://api.openai.com/v1",authType:"bearer",envVar:"OPENAI_API_KEY",modelPrefix:"openai",model:"gpt-5.1"},google:{label:"Google Gemini",format:"google-generative-ai",baseUrl:"https://generativelanguage.googleapis.com/v1beta",authType:"x-goog-api-key",envVar:"GEMINI_API_KEY",model:"gemini-3-pro-preview"},openrouter:{label:"OpenRouter",format:"openai-chat",baseUrl:"https://openrouter.ai/api/v1",authType:"bearer",envVar:"OPENROUTER_API_KEY",model:""},groq:{label:"Groq",format:"openai-chat",baseUrl:"https://api.groq.com/openai/v1",authType:"bearer",envVar:"GROQ_API_KEY",model:""},deepseek:{label:"DeepSeek",format:"openai-chat",baseUrl:"https://api.deepseek.com",authType:"bearer",envVar:"DEEPSEEK_API_KEY",model:"deepseek-chat"},moonshot:{label:"Moonshot / Kimi",format:"openai-chat",baseUrl:"https://api.moonshot.ai/v1",authType:"bearer",envVar:"MOONSHOT_API_KEY",model:"kimi-k2.5"},qianfan:{label:"Baidu Qianfan",format:"openai-chat",baseUrl:"https://qianfan.baidubce.com/v2",authType:"bearer",envVar:"QIANFAN_API_KEY",model:"deepseek-v3.2"},minimax:{label:"MiniMax (Anthropic-compatible)",format:"anthropic-messages",baseUrl:"https://api.minimax.io/anthropic",authType:"bearer",envVar:"MINIMAX_API_KEY",model:"MiniMax-M2.1"},xai:{label:"xAI",format:"openai-chat",baseUrl:"https://api.x.ai/v1",authType:"bearer",envVar:"XAI_API_KEY",model:""},mistral:{label:"Mistral",format:"openai-chat",baseUrl:"https://api.mistral.ai/v1",authType:"bearer",envVar:"MISTRAL_API_KEY",model:""},cerebras:{label:"Cerebras",format:"openai-chat",baseUrl:"https://api.cerebras.ai/v1",authType:"bearer",envVar:"CEREBRAS_API_KEY",model:""},zai:{label:"Z.AI / GLM",format:"openai-chat",baseUrl:"https://api.z.ai/api/paas/v4",authType:"bearer",envVar:"ZAI_API_KEY",model:""},ollama:{label:"Ollama (local)",format:"openai-chat",baseUrl:"http://127.0.0.1:11434/v1",authType:"none",envVar:"",model:""},lmstudio:{label:"LM Studio (local)",format:"openai-chat",baseUrl:"http://127.0.0.1:1234/v1",authType:"none",envVar:"",model:""},"custom-openai":{label:"Custom OpenAI-compatible",format:"openai-chat",baseUrl:"",authType:"bearer",envVar:"",model:""},"custom-anthropic":{label:"Custom Anthropic-compatible",format:"anthropic-messages",baseUrl:"",authType:"x-api-key",envVar:"",model:""}};function N(a){return He.default.createHash("sha1").update(a,"utf8").digest("hex")}function me(a){return Array.isArray(a)?"["+a.map(me).join(",")+"]":a&&typeof a=="object"?"{"+Object.keys(a).sort().map(e=>JSON.stringify(e)+":"+me(a[e])).join(",")+"}":JSON.stringify(a)}function L(a){return a==="api"||a==="anthropic-api"}function C(a){return P[a.apiProvider]||P.anthropic}function b(a){let e=C(a),t=(a.apiFormat||e.format||"").trim();return w[t]?t:e.format}function E(a){let e=b(a),t=C(a),r=(a.apiBaseUrl||"").trim();if(r)return r.replace(/\/+$/,"");if((a.apiProvider||"").startsWith("custom-"))throw new Error(y(a,"errorCustomProviderBaseUrlRequired"));let i=(t.baseUrl||w[e].defaultBaseUrl||"").trim();if(!i)throw new Error(y(a,"errorApiBaseUrlMissing"));return i.replace(/\/+$/,"")}function Ce(a){let e=(a.apiAuthType||"auto").trim();if(e&&e!=="auto")return e;let t=C(a),r=b(a);return t.authType||w[r].defaultAuthType||"bearer"}function Ge(a){let e=(a.apiKey||"").trim();if(e)return e;let t=(a.apiKeyEnvVar||C(a).envVar||"").trim();return t&&process.env&&process.env[t]?String(process.env[t]).trim():""}function k(a){let e=(a.model||"").trim();if(!e)throw new Error(y(a,"errorModelMissing"));let t=C(a),r=[a.apiProvider,t.modelPrefix].map(n=>(n||"").trim()).filter(Boolean),i=e.toLowerCase();for(let n of r){let s=n.toLowerCase();if(i.startsWith(s+"/"))return e.slice(n.length+1).trim()}return e}function ve(a,e){let t=C(a),r=P[e]||P.anthropic,i=(a.model||"").trim(),n=!i||i===g.model||!!t.model&&i===t.model;a.apiProvider=e,a.apiFormat=r.format,a.apiBaseUrl=r.baseUrl,a.apiAuthType=r.authType||"auto",a.apiKeyEnvVar=r.envVar||"",n&&(a.model=r.model||"")}function we(a){fe[a.uiLanguage]||(a.uiLanguage=g.uiLanguage),(!a.apiProvider||!P[a.apiProvider])&&(a.apiProvider="anthropic");let e=C(a);(!a.apiFormat||!w[a.apiFormat])&&(a.apiFormat=e.format),(!a.apiAuthType||!ye[a.apiAuthType])&&(a.apiAuthType="auto"),a.backend==="anthropic-api"&&(a.apiProvider=a.apiProvider||"anthropic",a.apiFormat=a.apiFormat||"anthropic-messages",a.apiBaseUrl=a.apiBaseUrl||P.anthropic.baseUrl,a.apiAuthType=a.apiAuthType||"x-api-key",a.apiKeyEnvVar=a.apiKeyEnvVar||"ANTHROPIC_API_KEY");let t=Number(a.apiMaxTokens);(!Number.isFinite(t)||t<=0)&&(a.apiMaxTokens=g.apiMaxTokens);let r=Number(a.maxDocChars);return(!Number.isFinite(r)||r<1e3)&&(a.maxDocChars=g.maxDocChars),a.maxCacheEntries=Je(a.maxCacheEntries),I[a.promptLanguage]||(a.promptLanguage=g.promptLanguage),a.minCards=Ue(a.minCards,g.minCards),a.maxCards=Ue(a.maxCards,g.maxCards),a.maxCards<a.minCards&&(a.maxCards=a.minCards),typeof a.customSystemPrompt!="string"&&(a.customSystemPrompt=""),a}function Ue(a,e){let t=Math.floor(Number(a));return Number.isFinite(t)?Math.min(30,Math.max(1,t)):e}function Je(a){let e=Math.floor(Number(a));return!Number.isFinite(e)||e<=0?M:e}function je(a){let e=a&&(a.lastAccessedAt||a.generatedAt||a.updatedAt),t=Date.parse(e||"");return Number.isFinite(t)?t:0}function be(a,e){if(!a||typeof a!="object")return[];let t=Je(e),r=Object.entries(a);if(r.length<=t)return[];let i=r.sort(([n,s],[o,l])=>je(s)-je(l)||n.localeCompare(o)).slice(0,r.length-t).map(([n])=>n);for(let n of i)delete a[n];return i}function J(a){let e=we(Object.assign({},g,a||{})),t=L(e.backend),r=C(e),i=b(e),n=t?(e.apiBaseUrl||r.baseUrl||w[i]?.defaultBaseUrl||"").trim().replace(/\/+$/,""):"";return N(me({cacheSchemaVersion:D,promptVersion:ct,maxDocChars:Number(e.maxDocChars)||g.maxDocChars,promptLanguage:e.promptLanguage,minCards:e.minCards,maxCards:e.maxCards,customSystemPromptHash:N(e.customSystemPrompt||""),backend:e.backend,model:e.model,apiProvider:t?e.apiProvider:"",apiFormat:t?i:"",apiBaseUrl:n,apiAuthType:t?Ce(e):"",apiHeadersHash:t?N(e.apiHeaders||""):"",apiMaxTokens:t?Number(e.apiMaxTokens)||g.apiMaxTokens:0,structuredOutputVersion:1}))}function K(a,e,t){return!!a&&a.schemaVersion===D&&a.contentHash===N(e)&&a.settingsHash===J(t)}function lt(a){return a==="en"?"Write title, gist, and bullets in English.":a==="auto"?"Write title, gist, and bullets in the main language of the source document.":"\u7528\u4E2D\u6587\u8F93\u51FA title\u3001gist \u548C bullets\u3002"}function ut(a){return a==="en"?`{"cards":[
{"title":"U-shaped gains","anchor":"Who benefits from AI? Overall, it shifts the score from one to seven","gist":"AI productivity gains form a U shape, with both ends benefiting most","bullets":["Top-paid software managers benefit by accelerating existing work","Low-paid workers use AI to create new side income","Middle-layer specialists gain less because prompt precision is hard to trust","Average reported benefit is 5.1/7, with 42% describing gains as unclear"]}
]}`:`{"cards":[
{"title":"U \u578B\u6536\u76CA\u66F2\u7EBF","anchor":"\u90A3\u8C01\u53C8\u4F1A\u88AB AI \u6240\u53D7\u76CA\uFF1F\u6574\u4F53\u6765\u770B\uFF0C\u5B83\u628A\u6574\u4E2A\u5206\u6570\u53D8\u6210\u4E86\u4E00\u5206\u5230\u4E03\u5206","gist":"AI \u751F\u4EA7\u529B\u6536\u76CA\u5448 U \u578B\uFF0C\u4E24\u7AEF\u53D7\u76CA\u6700\u5927\u3001\u4E2D\u95F4\u5C42\u584C\u9677","bullets":["\u6700\u9AD8\u85AA\u5C97\u4F4D\uFF08\u8F6F\u4EF6\u7BA1\u7406\uFF09\u901A\u8FC7\u52A0\u901F\u65E2\u6709\u5DE5\u4F5C\u53D7\u76CA\u6700\u5927","\u6700\u4F4E\u85AA\u5C97\u4F4D\uFF08\u5916\u5356\u5458\u3001\u56ED\u827A\u5DE5\uFF09\u7528 AI \u5F00\u526F\u4E1A\u521B\u9020\u65B0\u6536\u5165","\u4E2D\u95F4\u5C42\u79D1\u5B66\u5BB6\u3001\u5F8B\u5E08\u6536\u76CA\u6700\u5C11\uFF0C\u90E8\u5206\u56E0\u5BF9 prompt \u7CBE\u5EA6\u4FE1\u4EFB\u4E0D\u8DB3","\u5168\u4F53\u5747\u5206 5.1/7\uFF0C42% \u62A5\u544A\u6536\u76CA\u6A21\u7CCA"]}
]}`}function pt(a,e){return String(a||"").replace(/\{([a-zA-Z0-9_]+)\}/g,(t,r)=>Object.prototype.hasOwnProperty.call(e,r)?String(e[r]):t)}function dt(a,e,t,r,i,n){return a==="en"?`You are a long-form reading summary assistant. After reading the full document, split it into ${e}-${t} natural topic units. They do not need to match markdown headings; use a complete argument or topic as the unit, merging short sections and splitting long ones when needed.
Each card has one guiding sentence plus several bullets. Bullets carry details; gist is the lead-in.
Language:
- ${r}
For each unit, output:
- title: a concise 3-10 word heading that clearly states what the section is about; avoid vague labels like "Background" or "Introduction"
- anchor: a verbatim quote from the start of this unit, copied 1:1 from the source, 40-80 characters where possible, preserving punctuation, spaces, and line breaks; it is only used internally for positioning
- gist: one guiding sentence, 20-40 words, stating the core claim or conclusion
- bullets: 3-6 supporting bullets, each 20-50 words, carrying data, comparisons, mechanisms, examples, or counterintuitive observations. Gist and bullets must not repeat each other.
Rules:
- anchor must exact-substring-match the source. Never paraphrase, translate, summarize, or alter it.
- Choose the earliest sufficiently distinctive quote for each unit; avoid generic phrases.
- Every card must include both gist and bullets.
- Each bullet must be a standalone assertion; avoid sequencing phrases such as "first" or "then".
- Output strict JSON only: no markdown fence, no explanation, no tool call.
Output shape:
${i}
Example:
${n}`:`\u4F60\u662F\u4E00\u4E2A\u957F\u6587\u9605\u8BFB\u6458\u8981\u52A9\u624B\u3002\u9605\u8BFB\u5168\u6587\u540E\uFF0C\u628A\u6587\u7AE0\u5207\u6210 ${e}-${t} \u4E2A"\u81EA\u7136\u4E3B\u9898\u5355\u5143"\u2014\u2014\u4E0D\u5FC5\u5BF9\u5E94 markdown heading\uFF0C\u4EE5"\u4E00\u4E2A\u5B8C\u6574\u8BBA\u70B9\u6216\u8BDD\u9898"\u4E3A\u5355\u4F4D\u81EA\u884C\u5224\u65AD\u7C92\u5EA6\uFF1A\u77ED\u7AE0\u8282\u5408\u5E76\u3001\u957F\u7AE0\u8282\u62C6\u5206\u3002
**\u6BCF\u5F20\u5361\u7247\u7684\u7ED3\u6784\uFF1A\u4E00\u53E5\u8BDD\u9886\u8BFB + \u82E5\u5E72\u6761 bullet\u3002bullet \u627F\u8F7D\u7EC6\u8282\uFF0Cgist \u662F\u4E00\u53E5\u8BDD\u5BFC\u8BFB\u3002**
\u8BED\u8A00\uFF1A
- ${r}
\u5BF9\u6BCF\u4E2A\u5355\u5143\u8F93\u51FA\uFF1A
- title: 3-10 \u5B57\u7684\u77ED\u6807\u9898\uFF0C\u8981\u80FD\u72EC\u7ACB\u8BF4\u660E\u8FD9\u6BB5\u8BB2\u4EC0\u4E48\uFF0C\u907F\u514D"\u80CC\u666F""\u4ECB\u7ECD"\u8FD9\u7C7B\u7A7A\u6CDB\u8BCD
- anchor: \u8BE5\u5355\u5143\u5F00\u5934\u7684**\u9010\u5B57\u5F15\u7528**\uFF0C\u4ECE\u539F\u6587 1:1 \u590D\u5236 40-80 \u5B57\uFF0C\u4FDD\u7559\u539F\u59CB\u6807\u70B9/\u7A7A\u683C/\u6362\u884C\uFF1B\u4EC5\u4F9B\u63D2\u4EF6\u5185\u90E8\u5B9A\u4F4D\uFF0C\u7528\u6237\u4E0D\u53EF\u89C1
- gist: **\u4E00\u53E5\u8BDD\u9886\u8BFB**\uFF0820-40 \u5B57\uFF09\uFF0C\u70B9\u51FA\u8BE5\u5355\u5143\u7684\u6838\u5FC3\u7ACB\u573A\u6216\u7ED3\u8BBA\uFF0C\u4F5C\u4E3A bullets \u7684\u5BFC\u8BFB
- bullets: **3-6 \u6761**\u652F\u6491 bullet\uFF0C\u6BCF\u6761 20-50 \u5B57\u3002\u627F\u8F7D\u6570\u636E\u3001\u5BF9\u6BD4\u3001\u673A\u5236\u3001\u4F8B\u5B50\u3001\u53CD\u76F4\u89C9\u89C2\u5BDF\u3002gist \u662F\u7ACB\u573A\uFF0Cbullets \u662F\u5177\u4F53\u5185\u5BB9\uFF0C\u4E24\u8005\u4E0D\u5141\u8BB8\u91CD\u590D\u3002
\u89C4\u5219\uFF1A
- anchor \u5FC5\u987B\u80FD\u5728\u539F\u6587\u91CC exact substring match \u627E\u5230\u3002\u7EDD\u5BF9\u4E0D\u8981\u6539\u52A8\u3001\u603B\u7ED3\u3001\u7FFB\u8BD1\uFF0C\u5FC5\u987B\u539F\u6837\u590D\u5236
- anchor \u9009\u7528\u8BE5\u5355\u5143\u6700\u9760\u524D\u4E14\u8DB3\u591F\u72EC\u7279\u7684\u4E00\u6BB5\uFF08\u907F\u514D\u901A\u7528\u5957\u8BDD\u5982"\u7EFC\u4E0A\u6240\u8FF0"\uFF09
- \u6BCF\u5F20\u5361\u90FD\u5FC5\u987B\u540C\u65F6\u6709 gist \u548C bullets\u2014\u2014\u4E0D\u8981\u53EA\u6709 gist\uFF0C\u4E5F\u4E0D\u8981\u53EA\u6709 bullets
- bullet \u6BCF\u6761\u662F\u4E00\u4E2A\u5B8C\u6574\u72EC\u7ACB\u7684\u65AD\u8A00\uFF0C\u4E0D\u8981\u7528"\u9996\u5148""\u5176\u6B21"\u8FD9\u79CD\u987A\u5E8F\u8BCD
- \u4E25\u683C\u53EA\u8F93\u51FA JSON\uFF0C\u65E0 markdown fence\u3001\u65E0\u89E3\u91CA\u3001\u65E0 tool call
\u8F93\u51FA\u683C\u5F0F\uFF1A
${i}
\u793A\u4F8B\uFF1A
${n}`}function ht(a,e,t,r,i){return a==="en"?`Non-overridable output contract:
- Must output ${e}-${t} cards.
- ${r}
- anchor must be copied verbatim from the source and exact-substring-match the source.
- Output strict JSON only: no markdown fence, no explanation, no tool call.
- JSON shape: ${i}`:`\u4E0D\u53EF\u8986\u76D6\u7684\u8F93\u51FA\u5951\u7EA6\uFF1A
- \u5FC5\u987B\u8F93\u51FA ${e}-${t} \u5F20 cards\u3002
- ${r}
- anchor \u5FC5\u987B\u4ECE\u539F\u6587\u9010\u5B57\u590D\u5236\uFF0C\u5FC5\u987B\u80FD\u5728\u539F\u6587 exact substring match \u627E\u5230\u3002
- \u4E25\u683C\u53EA\u8F93\u51FA JSON\uFF0C\u65E0 markdown fence\u3001\u65E0\u89E3\u91CA\u3001\u65E0 tool call\u3002
- JSON shape: ${i}`}function Ae(a,e){let t=Number(e.maxDocChars)||ge,r=I[e.promptLanguage]?e.promptLanguage:g.promptLanguage,i=Math.max(1,Number(e.minCards)||g.minCards),n=Math.max(i,Number(e.maxCards)||g.maxCards),s=lt(r),o=a.length>t?a.slice(0,t)+(r==="en"?`
[Document truncated]`:`
[\u6587\u6863\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]`):a,l='{"cards":[{"title":"...","anchor":"...","gist":"...","bullets":["...","..."]}]}',d=ut(r),f={minCards:i,maxCards:n,languageInstruction:s,schema:l,example:d},p=pt(e.customSystemPrompt,f).trim(),h=ht(r,i,n,s,l),m=dt(r,i,n,s,l,d),u=p?`${p}
${h}`:m,S=r==="en"?`Source document:
${o}`:`\u4EE5\u4E0B\u662F\u9700\u8981\u5904\u7406\u7684\u6587\u6863\u5168\u6587\uFF1A
${o}`;return{system:u,user:S}}function xe(a){return String(a||"").split("/").map(e=>e.trim()).filter(Boolean).join("/")}function Te(a){let e=xe(a);if(!e)return[];let t=e.split("/");return t.map((r,i)=>t.slice(0,i+1).join("/"))}async function Ke(a,e){for(let t of Te(e))if(!a.vault.getAbstractFileByPath(t))try{await a.vault.createFolder(t)}catch(r){if(!a.vault.getAbstractFileByPath(t))throw r}}var $="record_parallel_reader_cards";function mt(a){let e=[],t=-1,r=0,i=!1,n=!1;for(let s=0;s<a.length;s++){let o=a[s];if(i){n?n=!1:o==="\\"?n=!0:o==='"'&&(i=!1);continue}o==='"'?i=!0:o==="{"?(r===0&&(t=s),r++):o==="}"&&(r>0&&r--,r===0&&t>=0&&(e.push(a.slice(t,s+1)),t=-1))}return e}function Pe(a){let e=(a||"").trim();if(!e)return e;try{return JSON.parse(e),e}catch{}let t=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(t){let i=t[1].trim();try{return JSON.parse(i),i}catch{}}let r=mt(e);r.sort((i,n)=>n.length-i.length);for(let i of r)try{return JSON.parse(i),i}catch{}return e}function T(a,e){let t=Pe(a),r;try{r=JSON.parse(t)}catch{throw new Error(y(e,"errorLlmNonJson",{excerpt:(a||"").slice(0,500)}))}return O(r)}function O(a){return(a&&Array.isArray(a.cards)?a.cards:[]).filter(t=>t&&typeof t=="object").map(t=>({title:typeof t.title=="string"?t.title:"(\u65E0\u6807\u9898)",anchor:typeof t.anchor=="string"?t.anchor:"",gist:typeof t.gist=="string"?t.gist:"",bullets:Array.isArray(t.bullets)?t.bullets.filter(r=>typeof r=="string"):[]}))}function R(a){let e={type:"object",properties:{title:{type:"string"},anchor:{type:"string"},gist:{type:"string"},bullets:{type:"array",items:{type:"string"}}},required:["title","anchor","gist","bullets"]},t={type:"object",properties:{cards:{type:"array",items:e}},required:["cards"]};return a&&(e.additionalProperties=!1,t.additionalProperties=!1),t}function $e(){return{type:"json_schema",json_schema:{name:"parallel_reader_cards",strict:!0,schema:R(!0)}}}function ze(){return{format:{type:"json_schema",name:"parallel_reader_cards",strict:!0,schema:R(!0)}}}function qe(){return{name:$,description:"Return the generated Parallel Reader summary cards.",input_schema:R(!0)}}function Se(a,e=80,t=.1){let r=Number(a?.top)||0,i=Math.max(0,Number(a?.height)||0),n=Math.min(Number(e)||0,i*t);return r+Math.max(0,n)}function gt(a){return typeof requestAnimationFrame=="function"?requestAnimationFrame(a):setTimeout(()=>a(Date.now()),16)}function ft(a){if(typeof cancelAnimationFrame=="function"){cancelAnimationFrame(a);return}clearTimeout(a)}function Ee(a,e=gt,t=ft){let r=null,i=()=>{r===null&&(r=e(()=>{r=null,a()}))};return i.cancel=()=>{r!==null&&(t(r),r=null)},i}function ke(a,e){let t=a.replace(/\/+$/,"");for(let r of e)if(t.endsWith(r))return t;return t+e[0]}function yt(a,e){let t=(a||"").trim();if(!t)return{};if(t.startsWith("{")){let i;try{i=JSON.parse(t)}catch(s){throw new Error(y(e,"errorCustomHeadersJsonParse",{error:s.message}))}if(!i||typeof i!="object"||Array.isArray(i))throw new Error(y(e,"errorCustomHeadersJsonObject"));let n={};for(let[s,o]of Object.entries(i))typeof o=="string"&&s.trim()&&(n[s.trim()]=o);return n}let r={};for(let i of t.split(/\r?\n/)){let n=i.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf(":");if(s<=0)throw new Error(y(e,"errorCustomHeadersLineFormat"));let o=n.slice(0,s).trim(),l=n.slice(s+1).trim();o&&(r[o]=l)}return r}function Ct(a){let e=Ce(a);if(e==="none")return{};let t=Ge(a);if(!t){let r=(a.apiKeyEnvVar||C(a).envVar||"").trim(),i=r?y(a,"errorApiKeyEnvHint",{envVar:r}):"";throw new Error(y(a,"errorApiKeyMissing",{hint:i}))}return e==="bearer"?{authorization:`Bearer ${t}`}:e==="x-api-key"?{"x-api-key":t}:e==="x-goog-api-key"?{"x-goog-api-key":t}:e==="api-key"?{"api-key":t}:{authorization:`Bearer ${t}`}}function X(a,e){return{"content-type":"application/json",...Ct(a),...e||{},...yt(a.apiHeaders,a)}}function vt(a,e,t){if(a.json&&typeof a.json=="object")return a.json;try{return JSON.parse(a.text||"{}")}catch{throw new Error(y(t,"errorProviderNonJson",{label:e,excerpt:(a.text||"").slice(0,500)}))}}async function We(a,e,t,r,i,n){let s;try{s=await a({url:t,method:"POST",headers:r,body:JSON.stringify(i),throw:!1})}catch(o){throw new Error(y(n,"errorProviderRequestFailed",{label:e,error:o.message||o}))}if(s.status>=400)throw new Error(y(n,"errorProviderApiStatus",{label:e,status:s.status,excerpt:(s.text||"").slice(0,500)}));return vt(s,e,n)}function wt(a){let e=String(a&&a.message?a.message:a);return/(?:API (?:400|404|422):|API returned HTTP (?:400|404|422)|API 返回 HTTP (?:400|404|422))/.test(e)?/response_format|json_schema|responseJsonSchema|responseMimeType|tools?|tool_choice|unsupported|unrecognized|unknown|schema/i.test(e):!1}async function Z(a,e,t,r,i,n,s){try{return await We(a,e,t,r,i,s)}catch(o){if(!n||!wt(o))throw o;return console.warn(`[parallel-reader] ${e} structured output rejected; retrying without structured output`,o),We(a,e+" fallback",t,r,n,s)}}function Ne(a){return typeof a=="string"?a:Array.isArray(a)?a.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&(e.text||e.output_text)||"").join(""):a&&typeof a=="object"&&(a.text||a.output_text)||""}function bt(a){if(typeof a.output_text=="string")return a.output_text;let e=[],t=r=>{if(r&&typeof r!="string"){if(Array.isArray(r)){r.forEach(t);return}typeof r=="object"&&(typeof r.text=="string"&&e.push(r.text),typeof r.output_text=="string"&&e.push(r.output_text),r.type==="output_text"&&typeof r.content=="string"&&e.push(r.content),r.content&&t(r.content),r.output&&t(r.output))}};return t(a.output),e.join("")}function Fe(a){let e=C(a),t=w[b(a)]||{};return e.tokenLimitField||t.tokenLimitField||"max_tokens"}function z(a,e,t,r){let i=!r||r.structured!==!1,n={model:k(t),max_tokens:Number(t.apiMaxTokens)||4096,system:a,messages:[{role:"user",content:e}]};return i&&(n.tools=[qe()],n.tool_choice={type:"tool",name:$}),n}function q(a,e,t,r){let i=!r||r.structured!==!1,n={model:k(t),messages:[{role:"system",content:a},{role:"user",content:e}]};return n[Fe(t)]=Number(t.apiMaxTokens)||4096,i&&(n.response_format=$e()),n}function W(a,e,t,r){let i=!r||r.structured!==!1,n={model:k(t),instructions:a,input:e,max_output_tokens:Number(t.apiMaxTokens)||4096};return i&&(n.text=ze()),n}function Y(a,e,t,r){let i=!r||r.structured!==!1,n={temperature:0,maxOutputTokens:Number(t.apiMaxTokens)||4096};return i&&(n.responseMimeType="application/json",n.responseJsonSchema=R(!1)),{systemInstruction:{parts:[{text:a}]},contents:[{role:"user",parts:[{text:e}]}],generationConfig:n}}function At(a,e){let r=(Array.isArray(a&&a.content)?a.content:[]).find(i=>i&&i.type==="tool_use"&&i.name===$);return r?typeof r.input=="string"?T(r.input,e):r.input&&typeof r.input=="object"?O(r.input):[]:null}async function xt(a,e,t,r){let i=ke(E(r),["/messages"]),n=await Z(a,"Anthropic-compatible",i,X(r,{"anthropic-version":"2023-06-01"}),z(e,t,r),z(e,t,r,{structured:!1}),r),s=At(n,r);if(s)return s;let o=(n.content||[]).map(l=>Ne(l)).join("").trim();return T(o,r)}async function Tt(a,e,t,r){let i=ke(E(r),["/chat/completions"]),s=((await Z(a,"OpenAI-compatible Chat",i,X(r),q(e,t,r),q(e,t,r,{structured:!1}),r)).choices||[])[0]||{},o=Ne(s.message?.content||s.text||"").trim();return T(o,r)}async function Pt(a,e,t,r){let i=ke(E(r),["/responses"]),n=await Z(a,"OpenAI Responses",i,X(r),W(e,t,r),W(e,t,r,{structured:!1}),r);return T(bt(n).trim(),r)}async function St(a,e,t,r){let i=encodeURIComponent(k(r)),n=E(r);/:generateContent(?:\?|$)/.test(n)||(n=`${n.replace(/\/+$/,"")}/models/${i}:generateContent`);let s=X(r),f=((((await Z(a,"Google Gemini",n,s,Y(e,t,r),Y(e,t,r,{structured:!1}),r)).candidates||[])[0]||{}).content?.parts||[]).map(p=>Ne(p)).join("").trim();return T(f,r)}async function _(a,e,t,r){switch(b(r)){case"openai-chat":return Tt(a,e,t,r);case"openai-responses":return Pt(a,e,t,r);case"google-generative-ai":return St(a,e,t,r);case"anthropic-messages":default:return xt(a,e,t,r)}}async function Ye(a,e){await _(a,'\u53EA\u8F93\u51FA JSON\uFF1A{"cards":[]}','\u8FDE\u901A\u6027\u6D4B\u8BD5\uFF1A\u8BF7\u539F\u6837\u8F93\u51FA {"cards":[]}',e);let t=b(e);return`${C(e).label} / ${w[t].label}`}var F=class extends Error{constructor(e){super("\u8BE5\u7B14\u8BB0\u6B63\u5728\u751F\u6210\u5BF9\u7167\u7B14\u8BB0"),this.name="GenerationJobAlreadyRunningError",this.code="already-running",this.key=e}},A=class extends Error{constructor(e){super("\u751F\u6210\u5DF2\u53D6\u6D88"),this.name="GenerationJobCancelledError",this.code="cancelled",this.key=e}},De=class{constructor(e){this.key=e,this.phase="queued",this.cancelled=!1,this.startedAt=new Date().toISOString(),this.updatedAt=this.startedAt,this._cancelHandlers=[]}setPhase(e){this.phase=e,this.updatedAt=new Date().toISOString()}onCancel(e){if(typeof e=="function"){if(this.cancelled){e();return}this._cancelHandlers.push(e)}}cancel(){if(this.cancelled)return!1;this.cancelled=!0,this.setPhase("cancelled");for(let e of this._cancelHandlers.splice(0))try{e()}catch{}return!0}throwIfCancelled(){if(this.cancelled)throw new A(this.key)}},V=class{constructor(){this.jobs=new Map}get(e){return this.jobs.get(e)||null}isRunning(e){return this.jobs.has(e)}async start(e,t){if(this.jobs.has(e))throw new F(e);let r=new De(e);this.jobs.set(e,r);try{r.setPhase("running");let i=await t(r);return r.throwIfCancelled(),i}catch(i){throw r.cancelled&&!(i instanceof A)?new A(e):i}finally{this.jobs.delete(e)}}cancel(e){let t=this.jobs.get(e);return t?t.cancel():!1}};function Me(a){if(a instanceof A||a?.code==="cancelled")return"cancelled";let e=String(a&&a.message?a.message:a);return/api key|unauthorized|401|403|认证|权限/i.test(e)?"auth":/timeout|超时|timed out/i.test(e)?"timeout":/429|rate limit|too many requests/i.test(e)?"rate-limit":/非 JSON|json_schema|schema|structured/i.test(e)?"schema":/model 未设置|base url|配置|config/i.test(e)?"config":"unknown"}var v="parallel-reader-view";function ae(a,e){if(e&&e.trim())return e.trim();let t=te.default.homedir(),r=[x.default.join(t,"bin",a),x.default.join(t,".local/bin",a),x.default.join(t,".claude/local",a),x.default.join(t,".codex/bin",a),x.default.join(t,".bun/bin",a),x.default.join(t,".npm-global/bin",a),x.default.join(t,".cargo/bin",a),"/opt/homebrew/bin/"+a,"/usr/local/bin/"+a];for(let i of r)try{if(Ze.default.existsSync(i))return i}catch{}return a}function re(a,e,t,r,i){return new Promise((n,s)=>{let o,l=!1,d,f=u=>{l||(l=!0,d&&clearTimeout(d),s(u))},p=u=>{l||(l=!0,d&&clearTimeout(d),n(u))};try{o=(0,Xe.spawn)(a,e,{stdio:["pipe","pipe","pipe"],env:{...process.env,PATH:[process.env.PATH||"","/usr/local/bin","/opt/homebrew/bin",x.default.join(te.default.homedir(),".local/bin"),x.default.join(te.default.homedir(),".claude/local")].filter(Boolean).join(":")}})}catch(u){return s(new Error(`Failed to start ${a}: ${u.message}`))}let h="",m="";if(d=setTimeout(()=>{try{o.kill("SIGKILL")}catch{}f(new Error(`CLI timed out (${r}ms)`))},r),i&&i.onCancel(()=>{try{o.kill("SIGKILL")}catch{}f(new A(i.key))}),o.stdout.on("data",u=>{h+=u.toString("utf8")}),o.stderr.on("data",u=>{m+=u.toString("utf8")}),o.on("error",u=>{f(new Error(`CLI startup error: ${u.message}. Try setting an absolute CLI path.`))}),o.on("close",u=>{if(!l){if(u!==0)return f(new Error(`CLI exited with code ${u}
stderr:
${m.slice(0,1e3)}`));p({stdout:h,stderr:m})}}),t)try{o.stdin.write(t),o.stdin.end()}catch{}else try{o.stdin.end()}catch{}})}async function Et(a,e,t,r){let i=ae("claude",t.cliPath),n=["-p","--output-format","json","--append-system-prompt",a,"--disallowed-tools","Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch,TodoWrite,Task"];t.model&&n.push("--model",t.model);let{stdout:s}=await re(i,n,e,t.cliTimeoutMs,r),o;try{o=JSON.parse(s)}catch{throw new Error(`claude CLI returned a non-JSON envelope:
`+s.slice(0,500))}let l=o.result||o.content||"";return T(l,t)}async function kt(a,e,t,r){let i=ae("codex",t.cliPath),n=`<<SYSTEM>>
${a}
<<USER>>
${e}
Output JSON directly with no explanation.`,s=["exec","--skip-git-repo-check","-"],{stdout:o}=await re(i,s,n,t.cliTimeoutMs,r);return T(o,t)}async function Nt(a){if(a.backend==="codex"){let e=ae("codex",a.cliPath),{stdout:t}=await re(e,["--version"],"",1e4);return`codex @ ${e}
${t.trim()}`}if(a.backend==="claude-code"){let e=ae("claude",a.cliPath),{stdout:t}=await re(e,["--version"],"",1e4);return`claude @ ${e}
${t.trim()}`}if(L(a.backend))return Ye(c.requestUrl,a);throw new Error("Unknown backend: "+a.backend)}async function Ft(a,e,t){let{system:r,user:i}=Ae(a,e),n;switch(e.backend){case"codex":n=await kt(r,i,e,t);break;case"api":n=await _(c.requestUrl,r,i,e);break;case"anthropic-api":n=await _(c.requestUrl,r,i,e);break;case"claude-code":default:n=await Et(r,i,e,t);break}let s=n.map(o=>({title:o.title,level:2,anchor:o.anchor,gist:o.gist,startLine:j(a,o.anchor),bullets:o.bullets}));return s.sort((o,l)=>o.startLine<0&&l.startLine<0?0:o.startLine<0?1:l.startLine<0?-1:o.startLine-l.startLine),s}function Q(a,e,t,r){let i=a.createEl("button",{cls:"parallel-reader-icon-button",attr:{type:"button","aria-label":t}});return i.title=t,typeof c.setIcon=="function"?(0,c.setIcon)(i,e):i.textContent=t,i.addEventListener("click",async n=>{n.preventDefault(),n.stopPropagation();try{await r()}catch(s){console.error(s),new c.Notice(`${t} failed: `+(s.message||s))}}),i}function ne(a,e,t,r,i){let n=a.createEl("button",{cls:i||"parallel-reader-text-button",attr:{type:"button"}});return e&&typeof c.setIcon=="function"&&(0,c.setIcon)(n,e),n.createSpan({text:t}),n.addEventListener("click",async s=>{s.preventDefault(),s.stopPropagation();try{await r()}catch(o){console.error(o),new c.Notice(`${t} failed: `+(o.message||o))}}),n}async function ee(a,e){try{await navigator.clipboard.writeText(a),new c.Notice(e)}catch(t){new c.Notice("Copy failed: "+(t.message||t))}}function Qe(a,e){return e?.phase==="generating"&&L(a?.backend)?"cancelRequestedApiInFlight":"cancelRequested"}var Ie=class extends c.Modal{constructor(e,t,r,i){super(e),this.plugin=t,this.card=r||{},this.onSave=i}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:this.plugin.t("editCardTitle")});let t=this.createLabeledInput(e,this.plugin.t("editCardTitleField"),this.card.title||""),r=this.createLabeledTextarea(e,this.plugin.t("editCardGistField"),this.card.gist||"",3),i=this.createLabeledTextarea(e,this.plugin.t("editCardBulletsField"),(this.card.bullets||[]).join(`
`),8),n=e.createDiv({cls:"parallel-reader-modal-actions"});ne(n,null,this.plugin.t("editCardCancel"),()=>this.close(),"parallel-reader-text-button"),ne(n,null,this.plugin.t("editCardSave"),async()=>{await this.onSave({title:t.value.trim()||this.card.title||"",gist:r.value.trim(),bullets:i.value.split(/\r?\n/).map(s=>s.trim()).filter(Boolean)}),this.close()},"parallel-reader-text-button")}createLabeledInput(e,t,r){let i=e.createDiv({cls:"parallel-reader-modal-field"});i.createEl("label",{text:t});let n=i.createEl("input",{attr:{type:"text"}});return n.value=r,n}createLabeledTextarea(e,t,r,i){let n=e.createDiv({cls:"parallel-reader-modal-field"});n.createEl("label",{text:t});let s=n.createEl("textarea");return s.rows=i,s.value=r,s}},Le=class extends c.ItemView{constructor(e,t){super(e),this.plugin=t,this.sections=[],this.sourceFile=null,this.cards=[],this.activeIdx=-1,this.loadingMessage="",this.errorMessage=""}getViewType(){return v}getDisplayText(){return this.plugin.t("displayName")}getIcon(){return"book-open"}onOpen(){let e=this.containerEl.children[1];return e.empty(),e.addClass("parallel-reader-container"),e.setAttr("tabindex","0"),e.addEventListener("keydown",t=>this.handleKeydown(t)),this.renderEmpty(),this.focusSummaryPane(),Promise.resolve()}onClose(){return Promise.resolve()}renderEmpty(){this.sourceFile=null,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage="";let e=this.containerEl.children[1];e.empty();let t=e.createDiv({cls:"parallel-reader-empty"});t.createEl("h3",{text:this.plugin.t("appTitle")}),t.createEl("p",{text:this.plugin.t("emptyOpenNote")}),t.createEl("code",{text:this.plugin.t("commandGenerate")})}focusSummaryPane(){let e=this.containerEl.children[1];return!e||typeof e.focus!="function"?!1:(e.focus({preventScroll:!0}),!0)}async loadFor(e,t,r){this.sourceFile=e,this.sections=t,this.stale=!!r,this.loadingMessage="",this.errorMessage="",this.render()}async renderLoading(e,t){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage=t||this.plugin.t("loadingDefault"),this.errorMessage="",this.render()}async renderError(e,t){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage=t||this.plugin.t("errorTitle"),this.render()}renderEmptyWithHint(e){this.sourceFile=e,this.sections=[],this.stale=!1,this.loadingMessage="",this.errorMessage="";let t=this.containerEl.children[1];t.empty();let r=t.createDiv({cls:"parallel-reader-empty"});r.createEl("h3",{text:e.basename}),r.createEl("p",{text:this.plugin.t("emptyNoCache")}),r.createEl("code",{text:this.plugin.t("commandGenerate")})}render(){let e=this.containerEl.children[1];e.empty();let r=e.createDiv({cls:"parallel-reader-header"}).createDiv({cls:"parallel-reader-header-row"});r.createEl("div",{text:this.sourceFile?.basename||"",cls:"parallel-reader-title"});let i=r.createDiv({cls:"parallel-reader-actions"});if(this.sourceFile&&(this.plugin.isGeneratingFile(this.sourceFile)?Q(i,"square",this.plugin.t("actionCancel"),()=>this.plugin.cancelGenerationForFile(this.sourceFile)):Q(i,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0)),Q(i,"copy",this.plugin.t("actionCopyAll"),()=>this.plugin.copyCurrentViewMarkdown()),Q(i,"download",this.plugin.t("actionExport"),()=>this.exportToVault())),this.stale){let o=e.createDiv({cls:"parallel-reader-stale-banner"});o.createSpan({text:this.plugin.t("staleBanner")}),ne(o,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0),"parallel-reader-stale-button")}if(this.loadingMessage){let o=e.createDiv({cls:"parallel-reader-state parallel-reader-loading"});o.createDiv({cls:"parallel-reader-spinner"}),o.createEl("div",{text:this.loadingMessage,cls:"parallel-reader-state-title"}),o.createEl("div",{text:this.plugin.t("loadingSubtitle"),cls:"parallel-reader-state-subtitle"});return}if(this.errorMessage){let o=e.createDiv({cls:"parallel-reader-state parallel-reader-error"});o.createEl("div",{text:this.plugin.t("errorTitle"),cls:"parallel-reader-state-title"}),o.createEl("div",{text:this.errorMessage,cls:"parallel-reader-state-subtitle"}),ne(o,"refresh-cw",this.plugin.t("actionRegenerate"),()=>this.plugin.runForFile(this.sourceFile,!0),"parallel-reader-text-button");return}let n=e.createDiv({cls:"parallel-reader-cards"});this.cards=[];let s=this.sourceFile?.path||"";this.sections.forEach((o,l)=>{let d=n.createDiv({cls:"parallel-reader-card"});d.dataset.idx=String(l),o.startLine<0&&d.addClass("parallel-reader-card-unanchored");let f=d.createEl("div",{cls:"parallel-reader-card-title"});if(f.createSpan({text:o.title}),o.startLine<0&&f.createEl("span",{text:" \u26A0",cls:"parallel-reader-warn",title:this.plugin.t("anchorMismatch")}),o.gist){let h=d.createEl("div",{cls:"parallel-reader-gist"});c.MarkdownRenderer.render(this.app,o.gist,h,s,this).catch(()=>{h.setText(o.gist)})}let p=o.bullets||[];if(p.length>0){let h=d.createEl("div",{cls:"parallel-reader-bullets-md"}),m=p.map(u=>`- ${u}`).join(`
`);c.MarkdownRenderer.render(this.app,m,h,s,this).catch(()=>{h.setText(m)})}else o.gist||d.createEl("div",{cls:"parallel-reader-empty-li",text:this.plugin.t("emptyCard")});d.addEventListener("click",h=>{let m=window.getSelection();if(m&&m.toString().length>0)return;let u=h.target;u&&u.tagName==="A"||o.startLine>=0&&this.plugin.scrollEditorToLine(o.startLine,this.sourceFile)}),d.addEventListener("contextmenu",h=>{h.preventDefault();let m=new c.Menu;m.addItem(u=>u.setTitle(this.plugin.t("menuCopyMarkdown")).setIcon("copy").onClick(()=>ee(pe(o),this.plugin.t("copiedMarkdown")))),m.addItem(u=>u.setTitle(this.plugin.t("menuCopyPlain")).setIcon("clipboard-copy").onClick(()=>ee(Be(o),this.plugin.t("copiedPlain")))),o.anchor&&m.addItem(u=>u.setTitle(this.plugin.t("menuCopyAnchor")).setIcon("quote-glyph").onClick(()=>ee(o.anchor,this.plugin.t("copiedAnchor")))),m.addSeparator(),o.startLine>=0&&m.addItem(u=>u.setTitle(this.plugin.t("menuJumpSource")).setIcon("arrow-right").onClick(()=>this.plugin.scrollEditorToLine(o.startLine,this.sourceFile))),m.addSeparator(),m.addItem(u=>u.setTitle(this.plugin.t("menuEditCard")).setIcon("pencil").onClick(()=>this.openEditCardModal(l))),m.addItem(u=>u.setTitle(this.plugin.t("menuDeleteCard")).setIcon("trash").onClick(()=>this.deleteCard(l))),m.showAtMouseEvent(h)}),this.cards.push(d)}),this.activeIdx>=0&&this.cards[this.activeIdx]&&this.cards[this.activeIdx].addClass("is-active")}setActiveSection(e){e!==this.activeIdx&&(this.activeIdx>=0&&this.cards[this.activeIdx]&&this.cards[this.activeIdx].removeClass("is-active"),this.activeIdx=e,e>=0&&this.cards[e]&&(this.cards[e].addClass("is-active"),this.cards[e].scrollIntoView({block:"nearest",behavior:"smooth"})))}moveActiveSection(e){let t=de(this.activeIdx,this.sections.length,e);return this.setActiveSection(t),this.focusSummaryPane(),t}jumpToActiveSection(){let e=he(this.sections,this.activeIdx);return e<0||!this.sourceFile?-1:(this.plugin.scrollEditorToLine(e,this.sourceFile),e)}handleKeydown(e){if(e.altKey&&e.key==="ArrowUp"){e.preventDefault(),this.moveActiveSection(-1);return}if(e.altKey&&e.key==="ArrowDown"){e.preventDefault(),this.moveActiveSection(1);return}!e.altKey&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&e.key==="Enter"&&this.jumpToActiveSection()>=0&&e.preventDefault()}async deleteCard(e){if(!this.sourceFile)return!1;let t=ce(this.sections,e);if(t.length===this.sections.length)return!1;let r=this.sections.length;return this.sections=t,this.activeIdx=le(e,r,this.activeIdx),await this.plugin.cacheReplaceCards(this.sourceFile.path,t),this.render(),new c.Notice(this.plugin.t("cardDeleted")),!0}openEditCardModal(e){return!this.sourceFile||!this.sections[e]?!1:(new Ie(this.app,this.plugin,this.sections[e],t=>this.updateCard(e,t)).open(),!0)}async updateCard(e,t){if(!this.sourceFile)return!1;let r=ue(this.sections,e,t);return r.length!==this.sections.length?!1:(this.sections=r,await this.plugin.cacheReplaceCards(this.sourceFile.path,r),this.render(),new c.Notice(this.plugin.t("cardSaved")),!0)}async exportToVault(){if(!this.sourceFile)return;let e=xe(this.plugin.settings.exportFolder),t=`${this.sourceFile.basename} - ${this.plugin.t("displayName")}.md`,r=`${e}/${t}`,i=["---",`source: [[${this.sourceFile.basename}]]`,`generated: ${new Date().toISOString().slice(0,10)}`,"tool: parallel-reader","---","",G(`${this.sourceFile.basename} \xB7 ${this.plugin.t("displayName")}`,this.sections),""].join(`
`),n=this.plugin.app;await Ke(n,e);let s=n.vault.getAbstractFileByPath(r);s instanceof c.TFile?await n.vault.modify(s,i):await n.vault.create(r,i),new c.Notice(this.plugin.t("exported",{path:r}))}},Oe=class extends c.Plugin{t(e,t){return y(this.settings||g,e,t)}async onload(){await this.loadSettings(),this.jobs=new V,this._cacheSaveTimer=null,this._cacheDirty=!1,this.addRibbonIcon("book-open",this.t("ribbonOpen"),async()=>{let e=this.getActiveView();await this.ensureView(),e?.file&&await this.syncViewToFile(e.file)}),this.registerView(v,e=>new Le(e,this)),this.addCommand({id:"parallel-reader-run",name:this.t("cmdRun"),callback:()=>this.runForActiveFile(!1)}),this.addCommand({id:"parallel-reader-regen",name:this.t("cmdRegen"),callback:()=>this.runForActiveFile(!0)}),this.addCommand({id:"parallel-reader-open-view",name:this.t("cmdOpenView"),callback:async()=>{let e=this.getActiveView();await this.ensureView(),e?.file&&this.syncViewToFile(e.file)}}),this.addCommand({id:"parallel-reader-export-current",name:this.t("cmdExport"),callback:()=>this.exportCurrentView()}),this.addCommand({id:"parallel-reader-copy-current-markdown",name:this.t("cmdCopyMarkdown"),callback:()=>this.copyCurrentViewMarkdown()}),this.addCommand({id:"parallel-reader-cancel-current",name:this.t("cmdCancel"),callback:()=>this.cancelActiveGeneration()}),this.addCommand({id:"parallel-reader-clear-current",name:this.t("cmdClearCurrent"),callback:async()=>{let e=this.getActiveView();if(!e?.file)return new c.Notice(this.t("noCurrentNote"));await this.cacheDelete(e.file.path),new c.Notice(this.t("cacheClearedFile",{name:e.file.basename}))}}),this.addCommand({id:"parallel-reader-clear-all",name:this.t("cmdClearAll"),callback:async()=>{let e=Object.keys(this.cache).length;await this.cacheClear(),new c.Notice(this.t("cacheClearedAll",{count:e}))}}),this.addCommand({id:"parallel-reader-card-prev",name:this.t("cmdCardPrev"),hotkeys:[{modifiers:["Alt"],key:"ArrowUp"}],callback:()=>this.moveActiveCard(-1)}),this.addCommand({id:"parallel-reader-card-next",name:this.t("cmdCardNext"),hotkeys:[{modifiers:["Alt"],key:"ArrowDown"}],callback:()=>this.moveActiveCard(1)}),this.addCommand({id:"parallel-reader-card-jump",name:this.t("cmdCardJump"),callback:()=>this.jumpActiveCard()}),this.addSettingTab(new Re(this.app,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>this.bindScrollSync())),this.registerEvent(this.app.workspace.on("file-open",e=>{e&&this.syncViewToFile(e)})),this.registerEvent(this.app.workspace.on("file-menu",(e,t)=>this.addFileMenuItems(e,t))),this.registerEvent(this.app.vault.on("rename",(e,t)=>this.handleFileRename(e,t))),this.registerEvent(this.app.vault.on("delete",e=>this.handleFileDelete(e))),this.bindScrollSync()}async onunload(){await this.flushSettingsSave(),await this.flushCacheSave(),this.app.workspace.detachLeavesOfType(v)}async loadSettings(){let t=(await this.loadData()||{}).settings||{};this.settings=we(Object.assign({},g,t)),await this.loadCache()}async saveSettings(){this._settingsSaveTimer&&(clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=null),await this.saveData({settings:this.settings})}saveSettingsDebounced(e=400){this._settingsSaveTimer&&clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=setTimeout(()=>{this._settingsSaveTimer=null,this.saveSettings().catch(t=>console.error("[parallel-reader] failed to save settings",t))},e)}async flushSettingsSave(){this._settingsSaveTimer&&(clearTimeout(this._settingsSaveTimer),this._settingsSaveTimer=null,await this.saveSettings())}async saveCache(){this._cacheSaveTimer&&(clearTimeout(this._cacheSaveTimer),this._cacheSaveTimer=null),this.pruneCache(),await this.writeCacheFile(),this._cacheDirty=!1}scheduleCacheSave(e=5e3){this._cacheDirty=!0,!this._cacheSaveTimer&&(this._cacheSaveTimer=setTimeout(()=>{this._cacheSaveTimer=null,this._cacheDirty&&this.saveCache().catch(t=>console.error("[parallel-reader] failed to save cache",t))},e))}async flushCacheSave(){this._cacheSaveTimer&&(clearTimeout(this._cacheSaveTimer),this._cacheSaveTimer=null),this._cacheDirty&&await this.saveCache()}cacheFilePath(){let e=this.app.vault.configDir||".obsidian",t=this.manifest?.id||"parallel-reader";return`${e}/plugins/${t}/cache.json`}async ensurePluginDataDir(){let e=this.app.vault.adapter,t=this.app.vault.configDir||".obsidian",r=this.manifest?.id||"parallel-reader",i=`${t}/plugins/${r}`;try{if(typeof e.exists=="function"&&await e.exists(i))return;await e.mkdir(i)}catch{}}async readCacheFile(){let e=this.app.vault.adapter;try{let t=await e.read(this.cacheFilePath()),r=JSON.parse(t);if(r&&typeof r=="object"&&r.entries&&typeof r.entries=="object")return r.entries}catch(t){let r=String(t?.message||t||"");/not found|does not exist|ENOENT/i.test(r)||console.warn("[parallel-reader] failed to read cache.json",t)}return{}}async writeCacheFile(){await this.ensurePluginDataDir(),await this.app.vault.adapter.write(this.cacheFilePath(),se(this.cache))}async loadCache(){let e=await this.readCacheFile();this.cache=e,this.pruneCache().length>0&&await this.writeCacheFile()}pruneCache(){return be(this.cache,this.settings?.maxCacheEntries||M)}async pruneCacheIfNeeded(){let e=this.pruneCache();return e.length>0&&await this.saveCache(),e}cacheGet(e){return this.cache[e]||null}async cacheTouch(e){let t=ie(this.cache[e]||null);return t?(this.scheduleCacheSave(),t):null}async cachePut(e,t,r,i){let n=new Date().toISOString();this.cache[e]={schemaVersion:D,contentHash:N(t),settingsHash:J(i||this.settings),cards:r,generatedAt:n,lastAccessedAt:n},await this.saveCache()}async cacheReplaceCards(e,t){let r=this.cache[e];if(!r)return!1;let i=new Date().toISOString();return r.cards=(t||[]).map(n=>({title:n.title,anchor:n.anchor,gist:n.gist,bullets:n.bullets||[]})),r.updatedAt=i,r.lastAccessedAt=i,await this.saveCache(),!0}async cacheDelete(e){this.cache[e]&&(delete this.cache[e],await this.saveCache())}async cacheClear(){this.cache={},await this.saveCache()}async ensureView(){let{workspace:e}=this.app,t=e.getLeavesOfType(v)[0];return t||(t=e.getRightLeaf(!1),await t.setViewState({type:v,active:!0})),e.revealLeaf(t),t.view}getActiveView(){return this.app.workspace.getActiveViewOfType(c.MarkdownView)}getParallelView(){return this.app.workspace.getLeavesOfType(v)[0]?.view}moveActiveCard(e){let t=this.getParallelView();return!t||!t.sections.length?(new c.Notice(this.t("noActiveCard")),-1):t.moveActiveSection(e)}jumpActiveCard(){let e=this.getParallelView();return!e||e.jumpToActiveSection()<0?(new c.Notice(this.t("noActiveCard")),!1):!0}isGeneratingFile(e){return!!e&&!!e.path&&this.jobs.isRunning(e.path)}cancelGenerationForFile(e){if(!e||!e.path)return new c.Notice(this.t("noCancelableJob")),!1;let t=this.jobs.get(e.path),r=Qe(this.settings,t),i=this.jobs.cancel(e.path);return new c.Notice(i?this.t(r):this.t("noCancelableJob")),i}viewIsShowingFile(e,t){return!!e&&!!t&&e.sourceFile?.path===t.path}activeFileStillMatches(e){let t=this.getActiveView();return!t?.file||t.file.path===e.path}cancelActiveGeneration(){let e=this.getActiveView();if(e?.file&&this.cancelGenerationForFile(e.file))return;let t=this.app.workspace.getLeavesOfType(v)[0]?.view;t?.sourceFile?this.cancelGenerationForFile(t.sourceFile):new c.Notice(this.t("noCancelableJob"))}confirmRegenerateEditedCards(){let e=this.t("confirmRegenerateEditedCards");return typeof window<"u"&&typeof window.confirm=="function"?window.confirm(e):!0}addFileMenuItems(e,t){!(t instanceof c.TFile)||!t.path.endsWith(".md")||(e.addSeparator(),e.addItem(r=>r.setTitle(this.t("fileMenuGenerate")).setIcon("book-open").onClick(()=>this.runForFile(t,!1))),e.addItem(r=>r.setTitle(this.t("fileMenuRegen")).setIcon("refresh-cw").onClick(()=>this.runForFile(t,!0))),this.cacheGet(t.path)&&e.addItem(r=>r.setTitle(this.t("fileMenuClear")).setIcon("trash").onClick(async()=>{await this.cacheDelete(t.path),new c.Notice(this.t("cacheClearedFile",{name:t.basename}))})))}async handleFileRename(e,t){if(!(e instanceof c.TFile)||!t)return;let r=t.endsWith(".md"),i=e.path.endsWith(".md");if(!r&&!i)return;if(r&&!i){this.cache[t]&&(delete this.cache[t],await this.saveCache());let l=this.app.workspace.getLeavesOfType(v)[0]?.view;l?.sourceFile?.path===t&&l.renderEmpty();return}if(!r)return;this.cache[t]&&(this.cache[e.path]=this.cache[t],delete this.cache[t],await this.saveCache());let s=this.app.workspace.getLeavesOfType(v)[0]?.view;s?.sourceFile&&(s.sourceFile.path===t||s.sourceFile.path===e.path)&&(s.sourceFile=e,await this.syncViewToFile(e))}async handleFileDelete(e){if(!(e instanceof c.TFile))return;!!this.cache[e.path]&&(delete this.cache[e.path],await this.saveCache());let i=this.app.workspace.getLeavesOfType(v)[0]?.view;i?.sourceFile?.path===e.path&&i.renderEmpty()}async exportCurrentView(){let e=this.getActiveView(),t=await this.ensureView();if((!t.sourceFile||!t.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!t.sourceFile||!t.sections.length){new c.Notice(this.t("noExportContent"));return}await t.exportToVault()}async copyCurrentViewMarkdown(){let e=this.getActiveView(),t=await this.ensureView();if((!t.sourceFile||!t.sections.length)&&e?.file&&await this.syncViewToFile(e.file),!t.sourceFile||!t.sections.length){new c.Notice(this.t("noCopyContent"));return}await ee(G(`${t.sourceFile.basename} \xB7 ${this.t("displayName")}`,t.sections),this.t("copiedAllMarkdown"))}async runForActiveFile(e){let t=this.getActiveView();if(!t||!t.file){new c.Notice(this.t("openNoteFirst"));return}return this.runForFile(t.file,e)}async runForFile(e,t){if(!e){new c.Notice(this.t("openNoteFirst"));return}let r=e.path;if(this.jobs.isRunning(r)){new c.Notice(this.t("alreadyGenerating"));return}if(oe(this.cacheGet(e.path),t)&&!this.confirmRegenerateEditedCards())return new c.Notice(this.t("regenerateCancelled")),!1;let i=null;return this.jobs.start(r,async n=>{n.setPhase("reading");let s=await this.app.vault.read(e);if(n.throwIfCancelled(),!s.trim()){new c.Notice(this.t("emptyNote"));return}if(i=await this.ensureView(),n.throwIfCancelled(),n.setPhase("cache-check"),!t){let p=this.cacheGet(e.path);if(K(p,s,this.settings)){await this.cacheTouch(e.path),this.activeFileStillMatches(e)&&await i.loadFor(e,this.resolveCardAnchors(s,p.cards),!1);return}}await i.renderLoading(e,this.t("loadingGenerating"));let o=Number(this.settings.maxDocChars)||g.maxDocChars;s.length>o&&new c.Notice(this.t("longNoteTruncated",{count:o})),new c.Notice(this.t("generatingNotice")),n.setPhase("generating");let l=await Ft(s,this.settings,n);if(n.throwIfCancelled(),l.length===0){new c.Notice(this.t("noCardsReturned"));return}let d=l.map(p=>({title:p.title,anchor:p.anchor,gist:p.gist,bullets:p.bullets}));n.setPhase("saving"),await this.cachePut(e.path,s,d,this.settings),n.throwIfCancelled(),this.viewIsShowingFile(i,e)&&await i.loadFor(e,l,!1);let f=l.filter(p=>p.startLine<0).length;new c.Notice(this.t("generationDone",{count:l.length,suffix:f?this.t("unanchoredSuffix",{count:f}):""}))}).catch(async n=>{if(n instanceof F){new c.Notice(n.message);return}if(n instanceof A){this.viewIsShowingFile(i,e)&&await i.renderError(e,this.t("cancelledError")),new c.Notice(this.t("cancelled"));return}let s=Me(n);console.error(n),this.viewIsShowingFile(i,e)&&await i.renderError(e,n.message||String(n)),new c.Notice(this.t("generationFailed",{kind:s==="unknown"?"":` (${s})`,error:n.message||n}))})}resolveCardAnchors(e,t){let r=(t||[]).map(i=>({title:i.title,level:2,anchor:i.anchor,gist:i.gist,startLine:j(e,i.anchor),bullets:i.bullets||[]}));return r.sort((i,n)=>i.startLine<0&&n.startLine<0?0:i.startLine<0?1:n.startLine<0?-1:i.startLine-n.startLine),r}async syncViewToFile(e){if(!e||!e.path||!e.path.endsWith(".md"))return;let t=this.app.workspace.getLeavesOfType(v);if(t.length===0)return;let r=t[0].view;if(!r||!this.activeFileStillMatches(e))return;let i=this.cacheGet(e.path);if(!i){await r.loadFor(e,[],!1),r.renderEmptyWithHint(e);return}let n=await this.app.vault.read(e);if(!this.activeFileStillMatches(e))return;let s=!K(i,n,this.settings);await this.cacheTouch(e.path);let o=this.resolveCardAnchors(n,i.cards);await r.loadFor(e,o,s)}bindScrollSync(){this._scrollDispose&&(this._scrollDispose(),this._scrollDispose=null);let e=this.getActiveView();if(!e)return;let t=e.editor,r=t&&t.cm,i=r&&r.scrollDOM?r.scrollDOM:e.contentEl.querySelector(".cm-scroller");if(!i)return;let n=Ee(()=>this.handleEditorScroll(e));i.addEventListener("scroll",n,{passive:!0}),this._scrollDispose=()=>{n.cancel(),i.removeEventListener("scroll",n)}}handleEditorScroll(e){let t=this.app.workspace.getLeavesOfType(v);if(t.length===0)return;let r=t[0].view;if(!r||!e.file||r.sourceFile?.path!==e.file.path)return;let i=e.editor,n=i&&i.cm;if(!n)return;let s=n.scrollDOM;if(!s)return;let o=s.getBoundingClientRect(),l=Se(o),d=0;try{let p=n.posAtCoords({x:o.left+20,y:l});p!=null&&(d=n.state.doc.lineAt(p).number-1)}catch{return}let f=-1;for(let p=0;p<r.sections.length;p++){let h=r.sections[p];if(!(h.startLine<0))if(h.startLine<=d)f=p;else break}r.setActiveSection(f)}findLeafForFile(e){if(!e)return null;let t=this.app.workspace.getLeavesOfType("markdown");for(let r of t){let i=r.view;if(i&&i.file&&i.file.path===e.path)return r}return null}async scrollEditorToLine(e,t){let r=t?this.findLeafForFile(t):null;if(!r&&t&&(r=this.app.workspace.getLeaf("tab"),await r.openFile(t,{active:!1})),!r){let n=this.getActiveView();n&&(r=n.leaf)}if(!r){new c.Notice(this.t("noEditor"));return}this.app.workspace.setActiveLeaf(r,{focus:!0});let i=r.view;if(i instanceof c.MarkdownView&&(i.setEphemeralState({line:e}),i.editor))try{i.editor.setCursor({line:e,ch:0}),i.editor.scrollIntoView({from:{line:e,ch:0},to:{line:e,ch:0}},!0)}catch{}}},Re=class extends c.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this,t=(n,s)=>this.plugin.t(n,s);e.empty(),e.createEl("h2",{text:t("settingsTitle")}),new c.Setting(e).setName(t("settingUiLanguageName")).setDesc(t("settingUiLanguageDesc")).addDropdown(n=>{for(let[s,o]of Object.entries(fe))n.addOption(s,o);return n.setValue(this.plugin.settings.uiLanguage||g.uiLanguage).onChange(async s=>{this.plugin.settings.uiLanguage=s,await this.plugin.saveSettings(),this.display()})}),new c.Setting(e).setName(t("settingBackendName")).setDesc(t("settingBackendDesc")).addDropdown(n=>n.addOption("claude-code","Claude Code CLI").addOption("codex","Codex CLI").addOption("api","API / Provider").addOption("anthropic-api","Anthropic API (legacy)").setValue(this.plugin.settings.backend).onChange(async s=>{this.plugin.settings.backend=s,s==="api"&&!this.plugin.settings.apiBaseUrl&&ve(this.plugin.settings,this.plugin.settings.apiProvider||"anthropic"),await this.plugin.saveSettings(),this.display()}));let r=L(this.plugin.settings.backend);if(!r)new c.Setting(e).setName(t("settingCliPathName")).setDesc(t("settingCliPathDesc")).addText(n=>n.setPlaceholder(t("settingCliPathPlaceholder")).setValue(this.plugin.settings.cliPath).onChange(async s=>{this.plugin.settings.cliPath=s.trim(),this.plugin.saveSettingsDebounced()})),new c.Setting(e).setName(t("settingCliTimeoutName")).addText(n=>n.setValue(String(this.plugin.settings.cliTimeoutMs)).onChange(async s=>{let o=parseInt(s,10);!isNaN(o)&&o>0&&(this.plugin.settings.cliTimeoutMs=o,this.plugin.saveSettingsDebounced())}));else{e.createEl("h3",{text:t("apiProviderHeader")});let n=C(this.plugin.settings);new c.Setting(e).setName(t("settingProviderPresetName")).setDesc(t("settingProviderPresetDesc")).addDropdown(s=>{for(let[o,l]of Object.entries(P))s.addOption(o,l.label);return s.setValue(this.plugin.settings.apiProvider).onChange(async o=>{ve(this.plugin.settings,o),await this.plugin.saveSettings(),this.display()})}),new c.Setting(e).setName(t("settingApiFormatName")).setDesc(t("settingApiFormatDesc")).addDropdown(s=>{for(let[o,l]of Object.entries(w))s.addOption(o,l.label);return s.setValue(b(this.plugin.settings)).onChange(async o=>{this.plugin.settings.apiFormat=o,await this.plugin.saveSettings(),this.display()})}),new c.Setting(e).setName(t("settingBaseUrlName")).setDesc(t("settingBaseUrlDesc")).addText(s=>s.setPlaceholder((this.plugin.settings.apiProvider||"").startsWith("custom-")?"https://your-provider.example/v1":n.baseUrl||w[b(this.plugin.settings)].defaultBaseUrl).setValue(this.plugin.settings.apiBaseUrl).onChange(async o=>{this.plugin.settings.apiBaseUrl=o.trim(),this.plugin.saveSettingsDebounced()})),new c.Setting(e).setName(t("settingApiKeyName")).setDesc(t("settingApiKeyDesc")).addText(s=>(s.inputEl.type="password",s.setPlaceholder("sk-...").setValue(this.plugin.settings.apiKey).onChange(async o=>{this.plugin.settings.apiKey=o.trim(),this.plugin.saveSettingsDebounced()}))),new c.Setting(e).setName(t("settingApiKeyEnvName")).setDesc(t("settingApiKeyEnvDesc")).addText(s=>s.setPlaceholder(n.envVar||"OPENAI_API_KEY").setValue(this.plugin.settings.apiKeyEnvVar).onChange(async o=>{this.plugin.settings.apiKeyEnvVar=o.trim(),this.plugin.saveSettingsDebounced()})),new c.Setting(e).setName(t("settingAuthTypeName")).setDesc(t("settingAuthTypeDesc")).addDropdown(s=>{for(let[o,l]of Object.entries(ye))s.addOption(o,l);return s.setValue(this.plugin.settings.apiAuthType||"auto").onChange(async o=>{this.plugin.settings.apiAuthType=o,await this.plugin.saveSettings()})}),new c.Setting(e).setName(t("settingHeadersName")).setDesc(t("settingHeadersDesc")).addTextArea(s=>s.setPlaceholder("cf-aig-authorization: Bearer ...").setValue(this.plugin.settings.apiHeaders).onChange(async o=>{this.plugin.settings.apiHeaders=o,this.plugin.saveSettingsDebounced()})),new c.Setting(e).setName(t("settingMaxTokensName")).addText(s=>s.setValue(String(this.plugin.settings.apiMaxTokens)).onChange(async o=>{let l=parseInt(o,10);!isNaN(l)&&l>0&&(this.plugin.settings.apiMaxTokens=l,this.plugin.saveSettingsDebounced())}))}new c.Setting(e).setName(t("settingModelName")).setDesc(t(r?"settingModelDescApi":"settingModelDescCli")).addText(n=>n.setPlaceholder(r?C(this.plugin.settings).model||"model-id":g.model).setValue(this.plugin.settings.model).onChange(async s=>{this.plugin.settings.model=s.trim()||(r?"":g.model),this.plugin.saveSettingsDebounced()})),new c.Setting(e).setName(t("settingMaxInputName")).setDesc(t("settingMaxInputDesc")).addText(n=>n.setValue(String(this.plugin.settings.maxDocChars||g.maxDocChars)).onChange(async s=>{let o=parseInt(s,10);!isNaN(o)&&o>=1e3&&(this.plugin.settings.maxDocChars=o,this.plugin.saveSettingsDebounced())})),e.createEl("h3",{text:t("promptHeader")}),new c.Setting(e).setName(t("settingPromptLanguageName")).setDesc(t("settingPromptLanguageDesc")).addDropdown(n=>{for(let[s,o]of Object.entries(I))n.addOption(s,o);return n.setValue(this.plugin.settings.promptLanguage||g.promptLanguage).onChange(async s=>{this.plugin.settings.promptLanguage=s,await this.plugin.saveSettings()})}),new c.Setting(e).setName(t("settingCardRangeName")).setDesc(t("settingCardRangeDesc")).addText(n=>n.setPlaceholder("min").setValue(String(this.plugin.settings.minCards||g.minCards)).onChange(async s=>{let o=parseInt(s,10);!isNaN(o)&&o>0&&(this.plugin.settings.minCards=o,this.plugin.settings.maxCards<o&&(this.plugin.settings.maxCards=o),this.plugin.saveSettingsDebounced())})).addText(n=>n.setPlaceholder("max").setValue(String(this.plugin.settings.maxCards||g.maxCards)).onChange(async s=>{let o=parseInt(s,10);!isNaN(o)&&o>0&&(this.plugin.settings.maxCards=Math.max(o,this.plugin.settings.minCards||g.minCards),this.plugin.saveSettingsDebounced())})),new c.Setting(e).setName(t("settingCustomPromptName")).setDesc(t("settingCustomPromptDesc")).addTextArea(n=>(n.inputEl.rows=8,n.setPlaceholder(t("settingCustomPromptPlaceholder")).setValue(this.plugin.settings.customSystemPrompt||"").onChange(async s=>{this.plugin.settings.customSystemPrompt=s,this.plugin.saveSettingsDebounced()}))),new c.Setting(e).setName(t("settingTestBackendName")).setDesc(t(r?"settingTestBackendDescApi":"settingTestBackendDescCli")).addButton(n=>n.setButtonText("Test").onClick(async()=>{try{let s=await Nt(this.plugin.settings);new c.Notice(`\u2713 ${s.slice(0,180)}`,8e3)}catch(s){new c.Notice(t("backendTestFailed",{error:s.message}),1e4)}})),new c.Setting(e).setName(t("settingExportFolderName")).setDesc(t("settingExportFolderDesc")).addText(n=>n.setValue(this.plugin.settings.exportFolder).onChange(async s=>{this.plugin.settings.exportFolder=s.trim()||g.exportFolder,this.plugin.saveSettingsDebounced()})),e.createEl("h3",{text:t("cacheHeader")}),new c.Setting(e).setName(t("settingMaxCacheName")).setDesc(t("settingMaxCacheDesc")).addText(n=>{n.setValue(String(this.plugin.settings.maxCacheEntries||M));let s=async()=>{let o=parseInt(n.getValue(),10);if(Number.isFinite(o)&&o>0){this.plugin.settings.maxCacheEntries=o,await this.plugin.saveSettings();let l=await this.plugin.pruneCacheIfNeeded();l.length>0&&new c.Notice(t("cachePruned",{count:l.length})),this.display()}};return n.inputEl.addEventListener("change",s),n.inputEl.addEventListener("keydown",o=>{o.key==="Enter"&&n.inputEl.blur()}),n});let i=Object.keys(this.plugin.cache).length;new c.Setting(e).setName(t("cachedNotesName",{count:i})).setDesc(t("cachedNotesDesc")).addButton(n=>n.setButtonText(t("clearAllCacheButton")).setWarning().onClick(async()=>{let s=Object.keys(this.plugin.cache).length;await this.plugin.cacheClear(),new c.Notice(t("cacheClearedAll",{count:s})),this.display()}))}},Dt=Oe,Mt={CACHE_SCHEMA_VERSION:D,GenerationJobAlreadyRunningError:F,GenerationJobCancelledError:A,GenerationJobManager:V,activeIndexAfterCardDelete:le,activeSectionLine:he,buildAnthropicMessagesBody:z,buildGeminiBody:Y,buildOpenAiChatBody:q,buildOpenAiResponsesBody:W,buildPrompts:Ae,cardsToMarkdown:G,cacheEntryMatches:K,cancellationNoticeKey:Qe,classifyGenerationError:Me,createRafThrottledHandler:Ee,extractJson:Pe,findLineForAnchor:j,folderPathsForTarget:Te,generationFingerprint:J,getApiBaseUrl:E,modelForApi:k,normalizeCardsPayload:O,nextCardIndex:de,pruneCacheEntries:be,removeCardAt:ce,serializeCacheFile:se,shouldConfirmRegenerate:oe,summarizeViaApi:_,touchCacheEntry:ie,translate:y,tokenLimitFieldForOpenAiChat:Fe,updateCardAt:ue,visibleTopProbeY:Se};0&&(module.exports={__test});