prosemirror-suggestcat-plugin 2.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/grammarSuggestV2/types.d.ts +1 -1
- package/dist/index.es.js +1 -1
- package/dist/index.js +1 -1
- package/dist/styles/styles.css +142 -43
- package/package.json +1 -1
|
@@ -31,7 +31,7 @@ export interface GrammarSuggestV2Options {
|
|
|
31
31
|
maxRetries?: number;
|
|
32
32
|
backoffBase?: number;
|
|
33
33
|
debounceMs?: number;
|
|
34
|
-
createPopup?: (view: EditorView, decoration: Decoration, pos: number, applySuggestion: () => void, discardSuggestion: () => void, requestHint: () => Promise<string>) => HTMLElement;
|
|
34
|
+
createPopup?: "react" | ((view: EditorView, decoration: Decoration, pos: number, applySuggestion: () => void, discardSuggestion: () => void, requestHint: () => Promise<string>) => HTMLElement);
|
|
35
35
|
}
|
|
36
36
|
export interface GrammarDecorationSpec {
|
|
37
37
|
id: object;
|
package/dist/index.es.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Fragment as t,Slice as e}from"prosemirror-model";import{PluginKey as n,Plugin as s,TextSelection as o}from"prosemirror-state";import{__awaiter as r}from"tslib";import a from"fast-diff";import{getDiff as i,isIdentity as c}from"@emergence-engineering/fast-diff-merge";export{getDiff}from"@emergence-engineering/fast-diff-merge";import{StepMap as l,Mapping as d}from"prosemirror-transform";import{DecorationSet as u,Decoration as p}from"prosemirror-view";var g,m,f,E,T,S;!function(t){t.suggestionUpdate="suggestionUpdate",t.acceptSuggestion="acceptSuggestion",t.openSuggestion="openSuggestion",t.closeSuggestion="closeSuggestion",t.discardSuggestion="discardSuggestion",t.setEnabled="setEnabled"}(g||(g={})),function(t){t.grammarSuggestPopup="grammar-suggest-popup"}(m||(m={})),function(t){t.Casual="Casual",t.Confident="Confident",t.Straightforward="Straightforward",t.Friendly="Friendly"}(f||(f={})),function(t){t.English="English",t.Spanish="Spanish",t.French="French",t.German="German",t.Italian="Italian",t.Portuguese="Portuguese",t.Dutch="Dutch",t.Russian="Russian",t.Chinese="Chinese",t.Korean="Korean",t.Japanese="Japanese"}(E||(E={})),function(t){t.Complete="Complete",t.SmallComplete="SmallComplete",t.Improve="Improve",t.MakeLonger="MakeLonger",t.MakeShorter="MakeShorter",t.Simplify="Simplify",t.Explain="Explain",t.ActionItems="ActionItems"}(T||(T={})),function(t){t.ChangeTone="ChangeTone",t.Translate="Translate",t.Hint="Hint",t.Custom="Custom"}(S||(S={}));const h=T,y=S;var R,I,b;!function(t){t.idle="idle",t.new="new",t.streaming="streaming",t.finished="finished",t.accepted="accepted",t.cancelled="cancelled",t.rejected="rejected",t.done="done",t.error="error"}(R||(R={})),function(t){t.IDLE="idle",t.PENDING="pending",t.STREAMING="streaming",t.PREVIEW="preview",t.APPLYING="applying"}(I||(I={})),function(t){t.START_TASK="START_TASK",t.STREAM_UPDATE="STREAM_UPDATE",t.STREAM_COMPLETE="STREAM_COMPLETE",t.STREAM_ERROR="STREAM_ERROR",t.ACCEPT_RESULT="ACCEPT_RESULT",t.REJECT_RESULT="REJECT_RESULT",t.CANCEL_TASK="CANCEL_TASK",t.CLEAR_ERROR="CLEAR_ERROR",t.SET_ENABLED="SET_ENABLED"}(b||(b={}));const C={maxSelection:1e3},O="https://suggestion-gw5lxik4dq-uc.a.run.app",v="https://prosemirror-ai-plugin.web.app/api/suggestion",x="openai:gpt-4o-mini";function A(t){var e,n;return{apiKey:t.apiKey,endpoint:null!==(e=t.endpoint)&&void 0!==e?e:O,model:null!==(n=t.model)&&void 0!==n?n:x}}function D(t){var e,n;return{apiKey:t.apiKey,endpoint:null!==(e=t.endpoint)&&void 0!==e?e:v,model:null!==(n=t.model)&&void 0!==n?n:x}}function N(t,e){var n;return r(this,void 0,void 0,(function*(){const{apiKey:s,text:o,task:r,params:a,endpoint:i=O,model:c=x,signal:l}=t;let d="";const u={model:c,modelParams:{input:[o],task:r,params:a}};try{const t=yield fetch(i,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},signal:l,body:JSON.stringify(u)});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}`);const o=null===(n=t.body)||void 0===n?void 0:n.getReader();if(!o)throw new Error("No response body");for(;;){const{done:t,value:n}=yield o.read();if(t)break;if(null==l?void 0:l.aborted)return;const s=(new TextDecoder).decode(n);d+=s,e.onChunk(s,d)}(null==l?void 0:l.aborted)||e.onComplete(d)}catch(t){if(t instanceof Error&&"AbortError"===t.name)return;e.onError(t instanceof Error?t:new Error(String(t)))}}))}function M(t){return r(this,void 0,void 0,(function*(){const{apiKey:e,text:n,endpoint:s=v,model:o=x}=t,r={model:o,modelParams:{input:[...n.split("\n")]}};try{const t=yield fetch(s,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(r)});if(!t.ok){const e=yield t.text();return console.error({status:t.status,text:e}),{fixed:!1,result:n,error:!0}}const o=yield t.json();return(null==o?void 0:o.length)?{result:o.join("\n"),fixed:!0}:{fixed:!1,result:n}}catch(t){return console.error("Grammar request error:",t),{fixed:!1,result:n,error:!0}}}))}const w=new WeakMap;function P(t){const e=w.get(t);e&&(e.abort(),w.delete(t))}function j(t){return w.has(t)}const U=new n("completePluginV2"),_={status:I.IDLE,streamedResult:"",enabled:!0};function L(n,a={}){const{maxSelection:i,apiEndpoint:c,model:l}=Object.assign(Object.assign({},C),a);let d=!1;return new s({key:U,state:{init:()=>Object.assign({},_),apply(t,e){const n=t.getMeta(U);return n?function(t,e){switch(e.type){case b.SET_ENABLED:return Object.assign(Object.assign(Object.assign({},t),{enabled:e.enabled}),e.enabled?{}:_);case b.START_TASK:return t.status!==I.IDLE?t:Object.assign(Object.assign({},t),{status:I.PENDING,taskType:e.taskType,params:e.params,selection:e.selection,streamedResult:"",error:void 0});case b.STREAM_UPDATE:return t.status!==I.PENDING&&t.status!==I.STREAMING?t:Object.assign(Object.assign({},t),{status:I.STREAMING,streamedResult:e.result});case b.STREAM_COMPLETE:return t.status!==I.PENDING&&t.status!==I.STREAMING?t:Object.assign(Object.assign({},t),{status:I.PREVIEW,streamedResult:e.result});case b.STREAM_ERROR:return Object.assign(Object.assign({},t),{status:I.IDLE,error:e.error,streamedResult:"",taskType:void 0,params:void 0,selection:void 0});case b.ACCEPT_RESULT:return t.status!==I.PREVIEW?t:Object.assign(Object.assign({},t),{status:I.APPLYING});case b.REJECT_RESULT:return t.status!==I.PREVIEW?t:Object.assign(Object.assign({},_),{enabled:t.enabled});case b.CANCEL_TASK:return Object.assign(Object.assign({},_),{enabled:t.enabled});case b.CLEAR_ERROR:return Object.assign(Object.assign({},t),{error:void 0});default:return t}}(e,n):e.status===I.APPLYING?Object.assign(Object.assign({},_),{enabled:e.enabled}):e}},view:()=>({update(s){const a=U.getState(s.state);if(a&&a.enabled){if(a.status===I.PENDING&&!d){const{text:t,error:e}=function(t,e,n){const{taskType:s,selection:o}=e;if(s===T.Complete){const{doc:e}=t.state,n=[];return e.descendants((t=>{"paragraph"===t.type.name&&n.push(t.textContent)})),{text:n.length>=2?n.slice(-2).join(" "):n.join(" ")}}return o?t.state.doc.textBetween(o.from,o.to).length>n?{text:"",error:"Selection is too big"}:{text:t.state.doc.textBetween(o.from,o.to,"\n")}:{text:"",error:"No selection"}}(s,a,i);if(e)return void s.dispatch(s.state.tr.setMeta(U,{type:b.STREAM_ERROR,error:e}));if(!t)return void s.dispatch(s.state.tr.setMeta(U,{type:b.STREAM_ERROR,error:"No text to process"}));d=!0,function({view:t,pluginKey:e,apiKey:n,text:s,task:o,params:a,apiEndpoint:i,model:c}){return r(this,void 0,void 0,(function*(){P(t);const r=new AbortController;w.set(t,r);try{yield N({apiKey:n,text:s,task:o,params:a,endpoint:i,model:c,signal:r.signal},{onChunk:(n,s)=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:b.STREAM_UPDATE,result:s}))},onComplete:n=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:b.STREAM_COMPLETE,result:n}))},onError:n=>{console.error("Streaming request error:",n),t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:b.STREAM_ERROR,error:n.message}))}})}finally{w.delete(t)}}))}({view:s,pluginKey:U,apiKey:n,text:t,task:a.taskType,params:a.params,apiEndpoint:c,model:l}).finally((()=>{d=!1}))}a.status===I.APPLYING&&function(n,s){const{taskType:r,selection:a,streamedResult:i}=s;if(!i)return;let{tr:c}=n.state;if(r===T.Complete)c=c.insertText(i,n.state.doc.nodeSize-2);else if(a){const s=i.split("\n\n").map((t=>n.state.schema.node("paragraph",null,t?n.state.schema.text(t):void 0))),r=t.fromArray(s);c=c.setSelection(o.create(n.state.doc,a.from,a.to)),c.selection.replace(c,new e(r,0,0))}n.dispatch(c),n.focus()}(s,a)}},destroy(){}})})}function k(t,e,n){const s=t.state.selection;t.dispatch(t.state.tr.setMeta(U,{type:b.START_TASK,taskType:e,params:n,selection:s.empty?void 0:s}))}function G(t){t.dispatch(t.state.tr.setMeta(U,{type:b.ACCEPT_RESULT}))}function K(t){t.dispatch(t.state.tr.setMeta(U,{type:b.REJECT_RESULT}))}function V(t){P(t),t.dispatch(t.state.tr.setMeta(U,{type:b.CANCEL_TASK}))}function F(t,e){e||P(t),t.dispatch(t.state.tr.setMeta(U,{type:b.SET_ENABLED,enabled:e}))}function B(t){t.dispatch(t.state.tr.setMeta(U,{type:b.CLEAR_ERROR}))}function H(t){return U.getState(t.state)}const W={debounceMs:2e3,createUpdatePopup:(t,e,n,s,o)=>{const r=document.createElement("div");r.className="grammar-suggest-tooltip";const{spec:a}=e,i=t.dom.getBoundingClientRect();r.id=m.grammarSuggestPopup;const c=t.coordsAtPos(n),l=t.dom.scrollTop||0,d=t.dom.scrollLeft||0;r.style.left=`${c.left-i.left+d}px`,r.style.top=`${c.bottom-i.top+l+5}px`;const u=document.createElement("div");u.className="grammar-suggest-tooltip-apply",u.innerText=a.text||a.originalText,a.text||(u.style.textDecoration="line-through",u.style.color="red"),u.onclick=()=>{s(t,e)},r.appendChild(u);const p=document.createElement("div");return p.innerHTML="<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'><path d='M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z'></path></svg>",p.className="grammar-suggest-tooltip-discard",p.onclick=()=>{o(t,e)},r.appendChild(p),r},withYjs:!1},$={maxSelection:1e3},q=new n("completePlugin"),Q=new n("grammarSuggestPlugin"),Y=(t,e)=>{t.dispatch(t.state.tr.setMeta(Q,{type:g.setEnabled,enabled:e}))},z=(t,e)=>{t.dispatch(t.state.tr.setMeta(q,{type:"setEnabled",enabled:e}))},J=(t,e)=>{if(t===e)return{start:t.length,end:t.length,oldStart:t.length,oldEnd:t.length,oldText:"",newText:""};const n=a(t,e),s=n[0],o=s[0]===a.EQUAL?s[1].length-1:0,r=((t,e)=>{if(e[e.length-1][0]!==a.EQUAL)return t.length;const n=e.slice(0,e.length-1);let s=0;for(const t of n){const[e,n]=t;e===a.EQUAL&&(s+=n.length),e===a.DELETE&&(s+=n.length)}return s})(t,n),i=t.lastIndexOf("\n",o),c=t.indexOf("\n",r),l=-1===i?0:i+1,d=-1===c?t.length:c,u=t.slice(l,d),p=e.slice(l,e.length-(t.length-d));return{start:l,end:l+p.length,oldStart:l,oldEnd:d,oldText:u,newText:p}};var X,Z,tt;!function(t){t.IDLE="IDLE",t.ACTIVE="ACTIVE"}(X||(X={})),function(t){t.DIRTY="DIRTY",t.WAITING="WAITING",t.QUEUED="QUEUED",t.PROCESSING="PROCESSING",t.DONE="DONE",t.BACKOFF="BACKOFF",t.ERROR="ERROR"}(Z||(Z={})),function(t){t.INIT="INIT",t.FINISH="FINISH",t.CLEAR="CLEAR",t.RESUME="RESUME",t.UNIT_STARTED="UNIT_STARTED",t.UNIT_SUCCESS="UNIT_SUCCESS",t.UNIT_ERROR="UNIT_ERROR",t.UPDATE_CONTEXT="UPDATE_CONTEXT",t.REMOVE_DECORATION="REMOVE_DECORATION",t.SELECT_DECORATION="SELECT_DECORATION",t.DESELECT_DECORATION="DESELECT_DECORATION"}(tt||(tt={}));const et={nodeTypes:"paragraph",priorityFilter:()=>!0,visibilityFilter:()=>!0,getGroupId:()=>"default",batchSize:4,maxRetries:3,backoffBase:1e3,dirtyHandling:{shouldRecalculate:!0,debounceDelay:2e3,skipDirtyOnSelfChange:!0},forceRerender:()=>{},onUpdate:void 0};function nt(t){return Object.assign(Object.assign(Object.assign({},et),t),{dirtyHandling:Object.assign(Object.assign({},et.dirtyHandling),t.dirtyHandling)})}function st(t,e,n){const s=[];let o="",r=0;return t.nodesBetween(e,n,((t,a)=>{if(t.isText&&t.text){const i=Math.max(e,a),c=Math.min(n,a+t.nodeSize),l=t.text.slice(i-a,c-a);s.push({from:r,docPos:i}),o+=l,r+=l.length}else t.isBlock&&o.length>0&&(s.push({from:r,docPos:a}),o+="\n",r+=1)})),{text:o,mapping:s}}function ot(t,e){var n,s;for(let n=e.length-1;n>=0;n--)if(e[n].from<=t)return e[n].docPos+(t-e[n].from);return null!==(s=null===(n=e[0])||void 0===n?void 0:n.docPos)&&void 0!==s?s:0}function rt(t,e,n,s="paragraph"){const o=Array.isArray(s)?s:[s],r=[];return t.nodesBetween(e,n,((e,n)=>{if(o.includes(e.type.name)){const s=n+e.nodeSize,o=st(t,n,s);o.text.trim().length>0&&r.push(Object.assign({from:n,to:s},o))}})),r}const at=(t,e)=>t.map((t=>null==t?void 0:t.map(e,0,0))).filter((t=>null!==t)),it=(t,e)=>{const n=t.doc.content.findDiffStart(e.doc.content),s=e.doc.content.findDiffEnd(t.doc.content);if(!s||!n)return;let o=new l([0,0,0]),r=n,a=s.a;return s&&n&&(s.a<n?(r=s.a,a=s.b,o=new l([s.a,0,s.b-s.a])):s.b<n?(r=s.b,a=s.a,o=new l([s.b,s.a-s.b,0])):o=new l([n,s.a-n,s.b-n])),{end:a,mapping:new d([o]),start:r}};function ct(t,e,n,s,o=!1){var r;const a=it(e,n);if(!a)return t;const{start:i,end:c,mapping:l}=a,d=Array.isArray(s.nodeTypes)?s.nodeTypes:[s.nodeTypes],u=Date.now()+s.dirtyHandling.debounceDelay,p=null===(r=t.unitsInProgress)||void 0===r?void 0:r.slice().sort(((t,e)=>t.from-e.from));if(p){const n=[],s=l.map(p[0].from),r=l.map(p[p.length-1].to),a=rt(e.doc,s,r,d);for(const t in p){const e=p[t],s=a[t];if(s){let{status:t}=e;!o&&s.from<=c&&s.to>=i&&(t=Z.DIRTY),n.push(Object.assign(Object.assign(Object.assign({},e),{status:t,waitUntil:o?e.waitUntil:u}),s))}else n.push(Object.assign(Object.assign({},e),{status:Z.DONE,from:r,to:r}))}return Object.assign(Object.assign({},t),{unitsInProgress:n,decorations:at(t.decorations,l)})}return Object.assign(Object.assign({},t),{decorations:at(t.decorations,l)})}function lt(t,e){return 1e3*Math.pow(e/1e3,t)}function dt(t){var e;if(t.status!==X.ACTIVE)return{completed:0,total:0,decorations:t.decorations.length};const n=null!==(e=t.unitsInProgress)&&void 0!==e?e:[];return{completed:n.filter((t=>t.status===Z.DONE||t.status===Z.ERROR)).length,total:n.length,decorations:t.decorations.length}}function ut(t){return new Promise((e=>setTimeout(e,t)))}function pt(t,e,n){t.dispatch(t.state.tr.setMeta(e,n))}function gt(t,e,n){if(e.status===X.ACTIVE)return e.unitsInProgress.find((t=>t.id===n))}function mt(t,e,n){const s=t.unitsInProgress.map((t=>t.id===e?Object.assign(Object.assign({},t),n):t));return"waitUntil"in n&&s.sort(((t,e)=>t.waitUntil-e.waitUntil)),Object.assign(Object.assign({},t),{unitsInProgress:s})}function ft(t){return t.every((t=>t.status===Z.DONE||t.status===Z.ERROR))}function Et(t,e,n,s,o="paragraph"){return rt(t,e,n,o).map(((t,e)=>({id:{},status:Z.QUEUED,from:t.from,to:t.to,text:t.text,mapping:t.mapping,metadata:s(t,e),retryCount:0,waitUntil:0})))}function Tt(t,e){pt(t,e,{type:tt.FINISH})}function St(t,e){pt(t,e,{type:tt.RESUME})}function ht(t){var e;return t.status===X.IDLE&&!!(null===(e=t.unitsInProgress)||void 0===e?void 0:e.some((t=>t.status!==Z.DONE&&t.status!==Z.ERROR)))}function yt(t,e,n,s){var o;switch(e.type){case tt.INIT:return function(t,e,n,s){const o=Et(n,e.onlySelection?s.from:0,e.onlySelection?s.to:n.content.size,((t,n)=>{var s;if(void 0!==e.metadata.single)return e.metadata.single;if(void 0!==e.metadata.array)return null!==(s=e.metadata.array[n])&&void 0!==s?s:e.metadata.array[0];if(void 0!==e.metadata.factory){const n={id:{},status:Z.QUEUED,from:t.from,to:t.to,text:t.text,mapping:[],metadata:{},retryCount:0,waitUntil:0};return e.metadata.factory(n)}return{}})).map((e=>Object.assign(Object.assign({},e),{status:t.options.priorityFilter(e,t.contextState)?Z.QUEUED:Z.WAITING})));return Object.assign(Object.assign({},t),{status:X.ACTIVE,unitsInProgress:o})}(t,e,s.doc,s.selection);case tt.UNIT_STARTED:return t.status!==X.ACTIVE?t:function(t,e){const n=t.unitsInProgress.find((t=>t.id===e));return n?mt(t,e,{status:Z.PROCESSING,requestText:n.text}):t}(t,e.unitId);case tt.UNIT_SUCCESS:return t.status!==X.ACTIVE?t:function(t,e,n){const s=t.unitsInProgress.find((t=>t.id===e.unitId));if(!s)return t;const o=Date.now()+t.options.dirtyHandling.debounceDelay;if(void 0!==s.requestText&&s.requestText!==s.text)return mt(t,e.unitId,{status:Z.DIRTY,requestText:void 0,waitUntil:o});const r=n(e.response,s),a=mt(t,e.unitId,{status:Z.DONE,response:e.response,requestText:void 0});return Object.assign(Object.assign({},a),{decorations:[...a.decorations,...r]})}(t,e,n);case tt.UNIT_ERROR:return t.status!==X.ACTIVE?t:function(t,e){const n=t.unitsInProgress.find((t=>t.id===e.unitId));if(!n)return t;const s=Date.now()+t.options.dirtyHandling.debounceDelay;if(void 0!==n.requestText&&n.requestText!==n.text)return mt(t,e.unitId,{status:Z.DIRTY,requestText:void 0,waitUntil:s});const o=n.retryCount+1;return o>=t.options.maxRetries?mt(t,e.unitId,{status:Z.ERROR,retryCount:o,requestText:void 0}):mt(t,e.unitId,{status:Z.BACKOFF,retryCount:o,waitUntil:Date.now()+lt(o,t.options.backoffBase),requestText:void 0})}(t,e);case tt.FINISH:return Object.assign(Object.assign({},t),{status:X.IDLE});case tt.CLEAR:return Object.assign(Object.assign({},t),{decorations:[],unitsInProgress:void 0,status:X.IDLE,selected:void 0});case tt.RESUME:return t.status!==X.IDLE?t:(null===(o=t.unitsInProgress)||void 0===o?void 0:o.length)?Object.assign(Object.assign({},t),{status:X.ACTIVE}):t;case tt.UPDATE_CONTEXT:return Object.assign(Object.assign({},t),{contextState:e.contextState});case tt.REMOVE_DECORATION:return Object.assign(Object.assign({},t),{decorations:t.decorations.filter((t=>t.spec.id!==e.id))});case tt.SELECT_DECORATION:return Object.assign(Object.assign({},t),{selected:e.id});case tt.DESELECT_DECORATION:return Object.assign(Object.assign({},t),{selected:void 0});default:return t}}function Rt(t,e){return{status:X.IDLE,decorations:[],selected:void 0,contextState:t,options:e}}function It(t,e,n,s){return r(this,void 0,void 0,(function*(){const o=t.getState(e.state);if(!o||o.status!==X.ACTIVE)return!1;const r=function(t,e){var n;if(t.status!==X.ACTIVE)return;const s=Date.now(),o=null!==(n=t.unitsInProgress)&&void 0!==n?n:[],r=t=>[Z.QUEUED,Z.BACKOFF,Z.DIRTY].includes(t.status)&&t.waitUntil<=s,a=o.find((n=>r(n)&&e.priorityFilter(n,t.contextState)));if(a)return a;const i=o.find(r);if(i)return i;return o.find((t=>[Z.QUEUED,Z.BACKOFF,Z.DIRTY].includes(t.status)&&t.waitUntil>s))||void 0}(o,s);if(!r)return!1;pt(e,t,{type:tt.UNIT_STARTED,unitId:r.id});const a=t.getState(e.state);if(!a)return!1;const i=gt(0,a,r.id);if(i&&i.waitUntil>Date.now()){yield ut(i.waitUntil-Date.now());const n=t.getState(e.state);if(!n||n.status!==X.ACTIVE)return!1}try{const s=yield n(e,r);s.error?pt(e,t,{type:tt.UNIT_ERROR,unitId:r.id,error:s.error}):void 0!==s.data&&pt(e,t,{type:tt.UNIT_SUCCESS,unitId:r.id,response:s.data})}catch(n){pt(e,t,{type:tt.UNIT_ERROR,unitId:r.id,error:n instanceof Error?n:new Error(String(n))})}return!0}))}function bt(t,e,n,s){return r(this,void 0,void 0,(function*(){return!!(yield It(t,e,n,s))&&bt(t,e,n,s)}))}function Ct(t,e,n,s){return r(this,void 0,void 0,(function*(){const o=Array.from({length:s.batchSize},(()=>bt(t,e,n,s)));yield Promise.all(o)}))}function Ot(t){return t.status===X.ACTIVE&&t.unitsInProgress.some((t=>t.status===Z.QUEUED||t.status===Z.WAITING||t.status===Z.BACKOFF||t.status===Z.DIRTY||t.status===Z.PROCESSING))}function vt(t){const{pluginKey:e,unitProcessor:n,decorationFactory:o,decorationTransformer:r,widgetFactory:a,initialContextState:i,options:c,handleKeyDown:l}=t,d=nt(null!=c?c:{});let p=!1;return new s({key:e,state:{init:()=>Rt(i,d),apply(t,n,s,r){const a=t.getMeta(e),i=t.docChanged&&void 0!==a&&d.dirtyHandling.skipDirtyOnSelfChange;let c=n;if(t.docChanged&&(c=ct(n,t,s,d,i)),a){const t=yt(c,a,o,r);return d.onUpdate&&d.onUpdate(t),t}return c}},props:{decorations(t){const n=e.getState(t);if(!n)return u.empty;console.log("decorations",n.decorations.length);let s=n.decorations.filter((t=>d.visibilityFilter(t,n.contextState)));console.log("decorations VF",s.length),r&&(s=r(s,n)),console.log("after transformer",s.length);const o=[];if(a&&n.unitsInProgress)for(const t of n.unitsInProgress)if(t.status!==Z.DONE&&t.status!==Z.ERROR){const e=a(t);e&&o.push(e)}return u.create(t.doc,[...s,...o])},handleKeyDown:l},view:()=>({update(t){const s=e.getState(t.state);s&&s.status===X.ACTIVE&&!p&&Ot(s)&&(p=!0,Ct(e,t,n,d).finally((()=>{p=!1;const n=e.getState(t.state);!n||n.status!==X.ACTIVE||Ot(n)||d.dirtyHandling.shouldRecalculate||pt(t,e,{type:tt.FINISH})})))}})})}function xt(t){return new n(t)}const At=(t,e)=>t.map((n=>{const s=ot(n.from,e.mapping),o=ot(n.to,e.mapping);return p.inline(s,o,{class:"link-detected",style:"color: #0066cc; text-decoration: underline; cursor: pointer;"},{id:{},unitId:e.id,originalText:n.url,response:t,url:n.url})})),Dt=/https?:\/\/[^\s<>"')\]]+/g;const Nt=(t,e)=>r(void 0,void 0,void 0,(function*(){return{data:function(t){const e=[];let n=Dt.exec(t);for(;null!==n;)e.push({url:n[0],from:n.index,to:n.index+n[0].length}),n=Dt.exec(t);return e}(e.text)}})),Mt=xt("linkDetector");function wt(){const t=vt({pluginKey:Mt,unitProcessor:Nt,decorationFactory:At,initialContextState:{}});return new s({key:Mt,state:t.spec.state,props:Object.assign(Object.assign({},t.spec.props),{handleDOMEvents:{click:(t,e)=>{const n=e.target;if(n.classList.contains("link-detected")){const s=t.posAtDOM(n,0),o=Mt.getState(t.state);if(o){const t=o.decorations.find((t=>t.from<=s&&t.to>=s&&t.spec.url));if(null==t?void 0:t.spec.url)return window.open(t.spec.url,"_blank"),e.preventDefault(),!0}}return!1}}}),view:t.spec.view})}const Pt={moderate:{class:"word-complexity-moderate",style:"background-color: rgba(255, 193, 7, 0.3); border-radius: 2px;"},high:{class:"word-complexity-high",style:"background-color: rgba(244, 67, 54, 0.3); border-radius: 2px;"}},jt=(t,e)=>t.map((n=>{const s=ot(n.from,e.mapping),o=ot(n.to,e.mapping),r=Pt[n.complexity];return p.inline(s,o,{class:r.class,style:r.style},{id:{},unitId:e.id,originalText:n.word,response:t,syllables:n.syllables,complexity:n.complexity})}));function Ut(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");if(e.length<=3)return 1;e=e.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/,""),e=e.replace(/^y/,"");const n=e.match(/[aeiouy]{1,2}/g);return n?Math.max(1,n.length):1}const _t=/[a-zA-Z]+/g;function Lt(t,e,n){const s=[];let o=_t.exec(t);for(;null!==o;){const r=o[0],a=Ut(r);a>=e&&s.push({word:r,from:o.index,to:o.index+r.length,syllables:a,complexity:a>=n?"high":"moderate"}),o=_t.exec(t)}return s}const kt=t=>(e,n)=>r(void 0,void 0,void 0,(function*(){var e,s;const o=t(),r=null!==(e=o.moderateThreshold)&&void 0!==e?e:3,a=null!==(s=o.highThreshold)&&void 0!==s?s:4;return{data:Lt(n.text,r,a)}})),Gt=(t,e)=>r(void 0,void 0,void 0,(function*(){return{data:Lt(e.text,3,4)}})),Kt={moderateThreshold:3,highThreshold:4},Vt=xt("wordComplexity");function Ft(t={}){return vt({pluginKey:Vt,unitProcessor:Gt,decorationFactory:jt,initialContextState:Object.assign(Object.assign({},Kt),t)})}const Bt={warning:{class:"sentence-too-long-warning",style:"background-color: rgba(255, 152, 0, 0.2); border-radius: 2px;"},error:{class:"sentence-too-long-error",style:"background-color: rgba(244, 67, 54, 0.2); border-radius: 2px;"}},Ht=(t,e)=>t.map((n=>{const s=ot(n.from,e.mapping),o=ot(n.to,e.mapping),r=Bt[n.severity];return p.inline(s,o,{class:r.class,style:r.style},{id:{},unitId:e.id,originalText:e.text.slice(n.from,n.to),response:t,wordCount:n.wordCount,severity:n.severity})})),Wt=/[^.!?]*[.!?]+/g,$t=/\b\w+\b/g;function qt(t){const e=t.match($t);return e?e.length:0}function Qt(t,e,n){const s=[];let o=Wt.exec(t);for(;null!==o;){const r=o[0],a=qt(r);a>=e&&s.push({from:o.index,to:o.index+r.length,wordCount:a,severity:a>=n?"error":"warning"}),o=Wt.exec(t)}return s}const Yt=t=>(e,n)=>r(void 0,void 0,void 0,(function*(){var e,s;const o=t(),r=null!==(e=o.warningThreshold)&&void 0!==e?e:25,a=null!==(s=o.errorThreshold)&&void 0!==s?s:40;return{data:Qt(n.text,r,a)}})),zt=(t,e)=>r(void 0,void 0,void 0,(function*(){return{data:Qt(e.text,25,40)}})),Jt={warningThreshold:25,errorThreshold:40},Xt=xt("sentenceLength");function Zt(t={}){return vt({pluginKey:Xt,unitProcessor:zt,decorationFactory:Ht,initialContextState:Object.assign(Object.assign({},Jt),t)})}const te=(t,e)=>[p.inline(e.from+1,e.to-1,{class:"random-processor-success",style:"background-color: rgba(76, 175, 80, 0.2); border-radius: 2px;"},{id:{},unitId:e.id,originalText:e.text,response:t,processingTime:t.processingTime})],ee=t=>{let e,n;const s=Math.max(0,t.waitUntil-Date.now());switch(t.status){case Z.QUEUED:e="⏳ Queued...",n="random-processor-widget queued";break;case Z.PROCESSING:e="⚙️ Processing...",n="random-processor-widget processing";break;case Z.BACKOFF:e=`🔄 Retry in ${Math.ceil(s/1e3)}s (attempt ${t.retryCount+1})`,n="random-processor-widget backoff";break;case Z.ERROR:e=`❌ Failed after ${t.retryCount} retries`,n="random-processor-widget error";break;case Z.DIRTY:e="⚠️ Changed",n="random-processor-widget dirty";break;case Z.WAITING:e="⏸️ Waiting...",n="random-processor-widget waiting";break;default:return}let o,r;switch(t.status){case Z.ERROR:o="#ffebee",r="#c62828";break;case Z.DIRTY:o="#fff9c4",r="#f57f17";break;case Z.BACKOFF:o="#fff3e0",r="#e65100";break;default:o="#e3f2fd",r="#1565c0"}const a=document.createElement("span");return a.className=n,a.textContent=e,a.style.cssText=`\n display: inline-block;\n padding: 2px 8px;\n margin-right: 8px;\n font-size: 12px;\n border-radius: 4px;\n background: ${o};\n color: ${r};\n `,p.widget(t.from+1,a,{side:-1})};function ne(t,e){return Math.floor(Math.random()*(e-t+1))+t}function se(t){return new Promise((e=>setTimeout(e,t)))}const oe=t=>(e,n)=>r(void 0,void 0,void 0,(function*(){var e,s,o;const r=t(),a=null!==(e=r.minDelay)&&void 0!==e?e:500,i=null!==(s=r.maxDelay)&&void 0!==s?s:3e3,c=null!==(o=r.errorRate)&&void 0!==o?o:.3,l=ne(a,i);yield se(l);return Math.random()<c?{error:new Error(`Random error after ${l}ms (attempt ${n.metadata.attempt})`)}:{data:{processingTime:l,success:!0,message:`Processed "${n.text.slice(0,20)}..." in ${l}ms`}}})),re=(t,e)=>r(void 0,void 0,void 0,(function*(){const t=ne(500,3e3);yield se(t);return Math.random()<.3?{error:new Error(`Random error after ${t}ms (attempt ${e.metadata.attempt})`)}:{data:{processingTime:t,success:!0,message:`Processed "${e.text.slice(0,20)}..." in ${t}ms`}}})),ae={minDelay:500,maxDelay:3e3,errorRate:.3},ie=xt("randomProcessor");function ce(t={}){return vt({pluginKey:ie,unitProcessor:re,decorationFactory:te,widgetFactory:ee,initialContextState:Object.assign(Object.assign({},ae),t),options:{batchSize:2,maxRetries:3,backoffBase:2e3}})}const le=(t,e)=>t.fixed&&0!==t.suggestions.length?t.suggestions.map((n=>{const s=ot(n.from,e.mapping),o=ot(n.to,e.mapping),r=""===n.replacement,a={id:{},unitId:e.id,originalText:n.original,replacement:n.replacement,response:t};return p.inline(s,o,{class:"grammarSuggestionV2 "+(r?"removalSuggestionV2":"")},a)})):[],de=(t,e)=>{const n=e.contextState.selectedSuggestionId;return n?t.map((t=>{const e=t.spec;return e.id===n?p.inline(t.from,t.to,{class:"grammarSuggestionV2 grammarSuggestionV2-selected"},e):t})):t},ue=t=>{let e,n;const s=Math.max(0,t.waitUntil-Date.now());switch(t.status){case Z.QUEUED:case Z.WAITING:e="⏳",n="grammarWidgetV2 queued";break;case Z.PROCESSING:e="🔍",n="grammarWidgetV2 processing";break;case Z.BACKOFF:e=`🔄 ${Math.ceil(s/1e3)}s`,n="grammarWidgetV2 backoff";break;case Z.ERROR:e="❌",n="grammarWidgetV2 error";break;case Z.DIRTY:e="✏️",n="grammarWidgetV2 dirty";break;default:return}const o=document.createElement("span");return o.className=n,o.textContent=e,p.widget(t.from+1,o,{side:-1})};const pe=t=>{const{apiKey:e,apiEndpoint:n,model:s,modelStateManager:o}="string"==typeof t?{apiKey:t,apiEndpoint:void 0,model:void 0,modelStateManager:void 0}:t;return(t,a)=>r(void 0,void 0,void 0,(function*(){var t,r,l;try{const d=null!==(t=null==o?void 0:o.getCurrentModel())&&void 0!==t?t:s,u=yield M({apiKey:e,text:a.text,endpoint:n,model:d});if(u.error?null==o||o.handleFailure():null==o||o.handleSuccess(),!u.fixed)return{data:{fixed:!1,originalText:a.text,fixedText:a.text,suggestions:[]}};const p=(r=a.text,l=u.result,i(r,l).filter((t=>!c(t))).filter((t=>t.original!==`${t.replacement}\n`)).map((t=>({from:t.from,to:t.replacement.endsWith("\n")?t.to-1:t.to,original:t.original,replacement:t.replacement.endsWith("\n")?t.replacement.slice(0,-1):t.replacement}))));return{data:{fixed:p.length>0,originalText:a.text,fixedText:u.result,suggestions:p}}}catch(t){return null==o||o.handleFailure(),{error:t instanceof Error?t:new Error(String(t))}}}))};function ge(t,e,n){const s=e.getState(t.state);if(s)return s.decorations.find((t=>t.spec.id===n))}function me(n,s,r){const a=ge(n,s,r);if(!a)return;const i=a.spec,{replacement:c}=i,{from:l,to:d}=a,u=c.split("\n").map((t=>t?n.state.schema.node("paragraph",null,n.state.schema.text(t)):n.state.schema.node("paragraph"))),p=t.fromArray(u);let{tr:g}=n.state;g=g.setSelection(o.create(n.state.doc,l,d)),g.selection.replace(g,new e(p,1,1)),g=g.setMeta(s,{type:tt.REMOVE_DECORATION,id:r}),n.dispatch(g)}function fe(t,e,n){pt(t,e,{type:tt.REMOVE_DECORATION,id:n})}function Ee(t,e,n){pt(t,e,{type:tt.UPDATE_CONTEXT,contextState:{selectedSuggestionId:n}})}function Te(t,e){pt(t,e,{type:tt.UPDATE_CONTEXT,contextState:{selectedSuggestionId:void 0}})}function Se(t,e){const n=e.getState(t.state);if(null==n?void 0:n.contextState.selectedSuggestionId)return ge(t,e,n.contextState.selectedSuggestionId)}function he(t,e,n,s){var o,a,i;return r(this,void 0,void 0,(function*(){const r=null!==(o=null==s?void 0:s.endpoint)&&void 0!==o?o:O,c=null==s?void 0:s.modelStateManager,l=null!==(i=null!==(a=null==c?void 0:c.getCurrentModel())&&void 0!==a?a:null==s?void 0:s.model)&&void 0!==i?i:x;return new Promise(((s,o)=>{const a={previousPromptType:"Grammar",oldVersion:e,newVersion:n};N({apiKey:t,text:e,task:S.Hint,params:a,endpoint:r,model:l},{onChunk:()=>{},onComplete:t=>{null==c||c.handleSuccess(),s(t)},onError:t=>{null==c||c.handleFailure(),o(t)}})}))}))}const ye={selectedSuggestionId:void 0},Re=xt("grammarSuggestV2"),Ie=(t,e,n,s,o,a)=>{const i=e.spec,c=document.createElement("div");c.className="grammarPopupV2";const l=document.createElement("div");l.className="grammarPopupV2-mainRow";const d=document.createElement("span");d.className="grammarPopupV2-original",d.textContent=`"${i.originalText}"`;const u=document.createElement("span");u.className="grammarPopupV2-arrow",u.textContent=" → ";const p=document.createElement("span");p.className="grammarPopupV2-replacement",p.textContent=""===i.replacement?"(remove)":`"${i.replacement}"`;const g=document.createElement("button");g.className="grammarPopupV2-hint",g.textContent="?",g.title="Why this suggestion?";const m=document.createElement("div");m.className="grammarPopupV2-hintArea",m.style.display="none";let f=!1;g.onclick=t=>r(void 0,void 0,void 0,(function*(){if(t.preventDefault(),t.stopPropagation(),"none"===m.style.display){if(m.style.display="block",!f){m.innerHTML='<span class="grammarPopupV2-loading">Loading...</span>';try{const t=yield a();m.innerHTML="";const e=document.createElement("span");e.className="grammarPopupV2-hintText",e.textContent=t,m.appendChild(e),f=!0}catch(t){m.innerHTML='<span class="grammarPopupV2-hintError">Could not load hint</span>'}}}else m.style.display="none"}));const E=document.createElement("button");E.className="grammarPopupV2-accept",E.textContent="✓",E.onclick=t=>{t.preventDefault(),t.stopPropagation(),s()};const T=document.createElement("button");return T.className="grammarPopupV2-discard",T.textContent="✕",T.onclick=t=>{t.preventDefault(),t.stopPropagation(),o()},l.appendChild(d),l.appendChild(u),l.appendChild(p),l.appendChild(g),l.appendChild(E),l.appendChild(T),c.appendChild(l),c.appendChild(m),c};function be(t,e={}){var n;const{apiEndpoint:o,model:r,fallback:a,batchSize:i=4,maxRetries:c=3,backoffBase:l=2e3,debounceMs:d=1e3,createPopup:g=Ie}=e,m=a?function(t){const{primaryModel:e,fallbackModel:n,failureThreshold:s}=t;let o=0;return{getCurrentModel:()=>n&&s>0&&o>=s?n:e,handleSuccess(){o=0},handleFailure(){n&&o++}}}({primaryModel:r,fallbackModel:a.fallbackModel,failureThreshold:null!==(n=a.failureThreshold)&&void 0!==n?n:3}):void 0,f=pe({apiKey:t,apiEndpoint:o,model:r,modelStateManager:m}),E=vt({pluginKey:Re,unitProcessor:f,decorationFactory:le,decorationTransformer:de,widgetFactory:ue,initialContextState:ye,options:{batchSize:i,maxRetries:c,backoffBase:l,dirtyHandling:{debounceDelay:d}}});return new s({key:Re,state:E.spec.state,props:Object.assign(Object.assign({},E.spec.props),{decorations(e){var n;const s=null===(n=E.spec.props)||void 0===n?void 0:n.decorations,a=s?s.call(E,e):u.empty,i=Re.getState(e);if(!(null==i?void 0:i.contextState.selectedSuggestionId))return a;const c=i.decorations.find((t=>t.spec.id===i.contextState.selectedSuggestionId));if(!c)return a;const l=c.spec,d=p.widget(c.from,((e,n)=>{const s=n();return void 0===s?document.createElement("div"):g(e,c,s,(()=>me(e,Re,c.spec.id)),(()=>fe(e,Re,c.spec.id)),(()=>he(t,l.originalText,l.replacement,{endpoint:o,model:r,modelStateManager:m})))}),{id:c.spec.id,side:-1,stopEvent:()=>!0});return a.add(e.doc,[d])},handleClick(t,e,n){const s=Re.getState(t.state);if(!s)return!1;const o=s.decorations.find((t=>t.from<=e&&e<=t.to));return o?(o.spec.id===s.contextState.selectedSuggestionId||Ee(t,Re,o.spec.id),!1):(s.contextState.selectedSuggestionId&&Te(t,Re),!1)}}),view:E.spec.view})}var Ce,Oe;!function(t){t.IDLE="idle",t.DEBOUNCING="debouncing",t.PENDING="pending",t.STREAMING="streaming",t.SHOWING="showing"}(Ce||(Ce={})),function(t){t.SET_ENABLED="SET_ENABLED",t.START_DEBOUNCE="START_DEBOUNCE",t.START_REQUEST="START_REQUEST",t.STREAM_UPDATE="STREAM_UPDATE",t.STREAM_COMPLETE="STREAM_COMPLETE",t.STREAM_ERROR="STREAM_ERROR",t.DISMISS="DISMISS",t.ACCEPT="ACCEPT"}(Oe||(Oe={}));const ve={debounceMs:500,maxContextLength:2e3,ghostTextClass:"autoCompleteGhostText"},xe=new WeakMap;function Ae(t){const e=xe.get(t);e&&(e.abort(),xe.delete(t))}function De(t){return xe.has(t)}function Ne(t,e){if(!e)return e;const{doc:n,selection:s}=t.state,o=s.from;if(o<=0)return e;const r=n.textBetween(o-1,o,""),a=e.charAt(0),i=/[\s\-]/;return!i.test(r)&&!i.test(a)?` ${e}`:e}const Me=new n("autoCompletePlugin"),we={status:Ce.IDLE,enabled:!0,suggestion:"",cursorPos:0};function Pe(t,e){switch(e.type){case Oe.SET_ENABLED:return Object.assign(Object.assign({},we),{enabled:e.enabled});case Oe.START_DEBOUNCE:return Object.assign(Object.assign({},t),{status:Ce.DEBOUNCING,cursorPos:e.cursorPos,suggestion:"",error:void 0});case Oe.START_REQUEST:return t.status!==Ce.DEBOUNCING?t:Object.assign(Object.assign({},t),{status:Ce.PENDING});case Oe.STREAM_UPDATE:return t.status!==Ce.PENDING&&t.status!==Ce.STREAMING?t:Object.assign(Object.assign({},t),{status:Ce.STREAMING,suggestion:e.suggestion});case Oe.STREAM_COMPLETE:return t.status!==Ce.PENDING&&t.status!==Ce.STREAMING?t:Object.assign(Object.assign({},t),{status:Ce.SHOWING,suggestion:e.suggestion});case Oe.STREAM_ERROR:return Object.assign(Object.assign({},t),{status:Ce.IDLE,error:e.error,suggestion:""});case Oe.DISMISS:case Oe.ACCEPT:return Object.assign(Object.assign({},t),{status:Ce.IDLE,suggestion:""});default:return t}}function je(t,e={}){const n=Object.assign(Object.assign({},ve),e),{debounceMs:o,maxContextLength:a,apiEndpoint:i,model:c,ghostTextClass:l}=n;let d=null,g=!1,m=null,f=null;return new s({key:Me,state:{init:()=>Object.assign({},we),apply(t,e,n,s){const o=t.getMeta(Me);if(o)return Pe(e,o);if(t.docChanged&&(e.status===Ce.SHOWING||e.status===Ce.STREAMING)){if(s.selection.from!==e.cursorPos)return Pe(e,{type:Oe.DISMISS})}return!t.selectionSet||t.docChanged||e.status!==Ce.SHOWING&&e.status!==Ce.STREAMING?e:Pe(e,{type:Oe.DISMISS})}},props:{decorations(t){const e=Me.getState(t);if(!e||!e.enabled)return u.empty;if((e.status===Ce.STREAMING||e.status===Ce.SHOWING)&&e.suggestion){const n=document.createElement("span");n.className=l,n.textContent=e.suggestion,n.setAttribute("contenteditable","false");const s=p.widget(e.cursorPos,n,{side:1});return u.create(t.doc,[s])}return u.empty},handleKeyDown(t,e){const n=Me.getState(t.state);return!(!n||!n.enabled)&&("Tab"===e.key&&!e.shiftKey&&n.status===Ce.SHOWING&&n.suggestion?(e.preventDefault(),m=n.suggestion,f=n.cursorPos,t.dispatch(t.state.tr.setMeta(Me,{type:Oe.ACCEPT})),!0):"Escape"===e.key&&(n.status===Ce.STREAMING||n.status===Ce.SHOWING)&&(e.preventDefault(),Ae(t),t.dispatch(t.state.tr.setMeta(Me,{type:Oe.DISMISS})),!0))}},view:()=>({update(e,n){const s=Me.getState(e.state),l=Me.getState(n);if(s&&s.enabled){if(null!==m&&null!==f){const t=m,n=f;m=null,f=null;const s=e.state.tr.insertText(t,n);return e.dispatch(s),void e.focus()}if(e.state,e.state.doc!==n.doc&&(null==l?void 0:l.status)!==Ce.PENDING&&(null==l?void 0:l.status)!==Ce.STREAMING){e.state.tr,d&&(clearTimeout(d),d=null),Ae(e);const t=e.state.selection.from;e.dispatch(e.state.tr.setMeta(Me,{type:Oe.START_DEBOUNCE,cursorPos:t})),d=setTimeout((()=>{d=null;const t=Me.getState(e.state);(null==t?void 0:t.status)===Ce.DEBOUNCING&&e.dispatch(e.state.tr.setMeta(Me,{type:Oe.START_REQUEST}))}),o)}if(s.status===Ce.PENDING&&!g){if(!function(t){const{doc:e,selection:n}=t.state,s=n.from,o=e.resolve(s),r=o.parent,a=o.start();if(s!==a+r.content.size)return!1;const i=r.textBetween(0,s-a,"");return!!i.trim()&&!/[.!?]\s*$/.test(i)}(e))return void e.dispatch(e.state.tr.setMeta(Me,{type:Oe.DISMISS}));const n=function(t,e){const{doc:n,selection:s}=t.state,o=s.from,r=n.textBetween(0,o,"\n");return r.length>e?r.slice(-e):r}(e,a);if(!n.trim())return void e.dispatch(e.state.tr.setMeta(Me,{type:Oe.DISMISS}));g=!0,function({view:t,pluginKey:e,apiKey:n,context:s,apiEndpoint:o,model:a}){return r(this,void 0,void 0,(function*(){Ae(t);const r=new AbortController;xe.set(t,r);try{yield N({apiKey:n,text:s,task:T.SmallComplete,endpoint:o,model:a,signal:r.signal},{onChunk:(n,s)=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:Oe.STREAM_UPDATE,suggestion:Ne(t,s)}))},onComplete:n=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:Oe.STREAM_COMPLETE,suggestion:Ne(t,n)}))},onError:n=>{console.error("Auto-complete streaming error:",n),t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:Oe.STREAM_ERROR,error:n.message}))}})}finally{xe.delete(t)}}))}({view:e,pluginKey:Me,apiKey:t,context:n,apiEndpoint:i,model:c}).finally((()=>{g=!1}))}}else d&&(clearTimeout(d),d=null)},destroy(){d&&(clearTimeout(d),d=null)}})})}function Ue(t,e){e||Ae(t),t.dispatch(t.state.tr.setMeta(Me,{type:Oe.SET_ENABLED,enabled:e}))}function _e(t){const e=Me.getState(t.state);if(!e||!e.suggestion)return!1;const n=t.state.tr.insertText(e.suggestion,e.cursorPos);return t.dispatch(n),t.dispatch(t.state.tr.setMeta(Me,{type:Oe.DISMISS})),t.focus(),!0}function Le(t){Ae(t),t.dispatch(t.state.tr.setMeta(Me,{type:Oe.DISMISS}))}function ke(t){return Me.getState(t.state)}function Ge(t){var e;const n=Me.getState(t.state);return null!==(e=null==n?void 0:n.enabled)&&void 0!==e&&e}function Ke(t){const e=Me.getState(t.state);return!!(null==e?void 0:e.suggestion)}const Ve=L;export{tt as ActionType,S as AiPromptsWithParam,T as AiPromptsWithoutParam,Oe as AutoCompleteActionType,Ce as AutoCompleteStatus,b as CompleteActionType,I as CompleteStatus,O as DEFAULT_COMPLETION_ENDPOINT,v as DEFAULT_GRAMMAR_ENDPOINT,x as DEFAULT_MODEL,m as GrammarSuggestElementClass,g as GrammarSuggestMetaType,f as MoodParamType,y as OpenAiPromptsWithParam,h as OpenAiPromptsWithoutParam,X as RunnerStatus,R as Status,E as TranslationTargetLanguage,Z as UnitStatus,_e as acceptAutoCompletion,G as acceptResult,me as acceptSuggestion,ft as allUnitsFinished,Me as autoCompleteKey,je as autoCompletePlugin,vt as blockRunnerPlugin,lt as calculateBackoff,ht as canResume,P as cancelActiveRequest,Ae as cancelAutoCompleteRequest,V as cancelTask,B as clearError,Ve as completePlugin,q as completePluginKey,L as completePluginV2,U as completeV2Key,Ut as countSyllables,A as createApiConfig,xt as createBlockRunnerKey,D as createGrammarApiConfig,pe as createGrammarProcessor,Rt as createInitialState,wt as createLinkDetectorPlugin,oe as createRandomProcessor,ce as createRandomProcessorPlugin,Zt as createSentenceLengthPlugin,Yt as createSentenceLengthProcessor,Et as createUnitsFromDocument,Ft as createWordComplexityPlugin,kt as createWordComplexityProcessor,ve as defaultAutoCompleteOptions,$ as defaultCompleteOptions,C as defaultCompleteV2Options,W as defaultOptions,et as defaultRunnerOptions,Te as deselectSuggestion,fe as discardSuggestion,Le as dismissAutoCompletion,pt as dispatchAction,Ct as executeParallel,st as extractTextWithMapping,ke as getAutoCompleteState,J as getChangedRegions,H as getCompleteState,dt as getProgress,Se as getSelectedDecoration,gt as getUnitById,rt as getUnitsInRange,le as grammarDecorationFactory,de as grammarDecorationTransformer,M as grammarRequest,Q as grammarSuggestPluginKey,be as grammarSuggestPluginV2,Re as grammarSuggestV2Key,ue as grammarWidgetFactory,yt as handleAction,j as hasActiveRequest,De as hasAutoCompleteRequest,Ke as hasAutoCompletion,Ot as hasUnitsToProcess,Ge as isAutoCompleteEnabled,At as linkDetectorDecorationFactory,Mt as linkDetectorKey,Nt as linkDetectorProcessor,nt as mergeOptions,Tt as pauseRunner,re as randomProcessor,te as randomProcessorDecorationFactory,ie as randomProcessorKey,ee as randomProcessorWidgetFactory,K as rejectResult,ct as remapPositions,he as requestHint,St as resumeRunner,Ee as selectSuggestion,Ht as sentenceLengthDecorationFactory,Xt as sentenceLengthKey,zt as sentenceLengthProcessor,Ue as setAutoCompleteEnabled,z as setCompleteEnabled,F as setEnabled,Y as setGrammarSuggestEnabled,ut as sleep,k as startTask,N as streamingRequest,ot as textToDocPos,mt as updateUnit,jt as wordComplexityDecorationFactory,Vt as wordComplexityKey,Gt as wordComplexityProcessor};
|
|
1
|
+
import{Fragment as t,Slice as e}from"prosemirror-model";import{PluginKey as n,Plugin as s,TextSelection as o}from"prosemirror-state";import{__awaiter as r}from"tslib";import a from"fast-diff";import{getDiff as i,isIdentity as c}from"@emergence-engineering/fast-diff-merge";export{getDiff}from"@emergence-engineering/fast-diff-merge";import{StepMap as l,Mapping as d}from"prosemirror-transform";import{DecorationSet as u,Decoration as p}from"prosemirror-view";var g,m,f,E,T,S;!function(t){t.suggestionUpdate="suggestionUpdate",t.acceptSuggestion="acceptSuggestion",t.openSuggestion="openSuggestion",t.closeSuggestion="closeSuggestion",t.discardSuggestion="discardSuggestion",t.setEnabled="setEnabled"}(g||(g={})),function(t){t.grammarSuggestPopup="grammar-suggest-popup"}(m||(m={})),function(t){t.Casual="Casual",t.Confident="Confident",t.Straightforward="Straightforward",t.Friendly="Friendly"}(f||(f={})),function(t){t.English="English",t.Spanish="Spanish",t.French="French",t.German="German",t.Italian="Italian",t.Portuguese="Portuguese",t.Dutch="Dutch",t.Russian="Russian",t.Chinese="Chinese",t.Korean="Korean",t.Japanese="Japanese"}(E||(E={})),function(t){t.Complete="Complete",t.SmallComplete="SmallComplete",t.Improve="Improve",t.MakeLonger="MakeLonger",t.MakeShorter="MakeShorter",t.Simplify="Simplify",t.Explain="Explain",t.ActionItems="ActionItems"}(T||(T={})),function(t){t.ChangeTone="ChangeTone",t.Translate="Translate",t.Hint="Hint",t.Custom="Custom"}(S||(S={}));const h=T,y=S;var R,I,C;!function(t){t.idle="idle",t.new="new",t.streaming="streaming",t.finished="finished",t.accepted="accepted",t.cancelled="cancelled",t.rejected="rejected",t.done="done",t.error="error"}(R||(R={})),function(t){t.IDLE="idle",t.PENDING="pending",t.STREAMING="streaming",t.PREVIEW="preview",t.APPLYING="applying"}(I||(I={})),function(t){t.START_TASK="START_TASK",t.STREAM_UPDATE="STREAM_UPDATE",t.STREAM_COMPLETE="STREAM_COMPLETE",t.STREAM_ERROR="STREAM_ERROR",t.ACCEPT_RESULT="ACCEPT_RESULT",t.REJECT_RESULT="REJECT_RESULT",t.CANCEL_TASK="CANCEL_TASK",t.CLEAR_ERROR="CLEAR_ERROR",t.SET_ENABLED="SET_ENABLED"}(C||(C={}));const b={maxSelection:1e3},O="https://suggestion-gw5lxik4dq-uc.a.run.app",v="https://prosemirror-ai-plugin.web.app/api/suggestion",x="openai:gpt-4o-mini";function A(t){var e,n;return{apiKey:t.apiKey,endpoint:null!==(e=t.endpoint)&&void 0!==e?e:O,model:null!==(n=t.model)&&void 0!==n?n:x}}function D(t){var e,n;return{apiKey:t.apiKey,endpoint:null!==(e=t.endpoint)&&void 0!==e?e:v,model:null!==(n=t.model)&&void 0!==n?n:x}}function N(t,e){var n;return r(this,void 0,void 0,(function*(){const{apiKey:s,text:o,task:r,params:a,endpoint:i=O,model:c=x,signal:l}=t;let d="";const u={model:c,modelParams:{input:[o],task:r,params:a}};try{const t=yield fetch(i,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},signal:l,body:JSON.stringify(u)});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}`);const o=null===(n=t.body)||void 0===n?void 0:n.getReader();if(!o)throw new Error("No response body");for(;;){const{done:t,value:n}=yield o.read();if(t)break;if(null==l?void 0:l.aborted)return;const s=(new TextDecoder).decode(n);d+=s,e.onChunk(s,d)}(null==l?void 0:l.aborted)||e.onComplete(d)}catch(t){if(t instanceof Error&&"AbortError"===t.name)return;e.onError(t instanceof Error?t:new Error(String(t)))}}))}function w(t){return r(this,void 0,void 0,(function*(){const{apiKey:e,text:n,endpoint:s=v,model:o=x}=t,r={model:o,modelParams:{input:[...n.split("\n")]}};try{const t=yield fetch(s,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(r)});if(!t.ok){const e=yield t.text();return console.error({status:t.status,text:e}),{fixed:!1,result:n,error:!0}}const o=yield t.json();return(null==o?void 0:o.length)?{result:o.join("\n"),fixed:!0}:{fixed:!1,result:n}}catch(t){return console.error("Grammar request error:",t),{fixed:!1,result:n,error:!0}}}))}const M=new WeakMap;function P(t){const e=M.get(t);e&&(e.abort(),M.delete(t))}function U(t){return M.has(t)}const j=new n("completePluginV2"),_={status:I.IDLE,streamedResult:"",enabled:!0};function L(n,a={}){const{maxSelection:i,apiEndpoint:c,model:l}=Object.assign(Object.assign({},b),a);let d=!1;return new s({key:j,state:{init:()=>Object.assign({},_),apply(t,e){const n=t.getMeta(j);return n?function(t,e){switch(e.type){case C.SET_ENABLED:return Object.assign(Object.assign(Object.assign({},t),{enabled:e.enabled}),e.enabled?{}:_);case C.START_TASK:return t.status!==I.IDLE?t:Object.assign(Object.assign({},t),{status:I.PENDING,taskType:e.taskType,params:e.params,selection:e.selection,streamedResult:"",error:void 0});case C.STREAM_UPDATE:return t.status!==I.PENDING&&t.status!==I.STREAMING?t:Object.assign(Object.assign({},t),{status:I.STREAMING,streamedResult:e.result});case C.STREAM_COMPLETE:return t.status!==I.PENDING&&t.status!==I.STREAMING?t:Object.assign(Object.assign({},t),{status:I.PREVIEW,streamedResult:e.result});case C.STREAM_ERROR:return Object.assign(Object.assign({},t),{status:I.IDLE,error:e.error,streamedResult:"",taskType:void 0,params:void 0,selection:void 0});case C.ACCEPT_RESULT:return t.status!==I.PREVIEW?t:Object.assign(Object.assign({},t),{status:I.APPLYING});case C.REJECT_RESULT:return t.status!==I.PREVIEW?t:Object.assign(Object.assign({},_),{enabled:t.enabled});case C.CANCEL_TASK:return Object.assign(Object.assign({},_),{enabled:t.enabled});case C.CLEAR_ERROR:return Object.assign(Object.assign({},t),{error:void 0});default:return t}}(e,n):e.status===I.APPLYING?Object.assign(Object.assign({},_),{enabled:e.enabled}):e}},view:()=>({update(s){const a=j.getState(s.state);if(a&&a.enabled){if(a.status===I.PENDING&&!d){const{text:t,error:e}=function(t,e,n){const{taskType:s,selection:o}=e;if(s===T.Complete){const{doc:e}=t.state,n=[];return e.descendants((t=>{"paragraph"===t.type.name&&n.push(t.textContent)})),{text:n.length>=2?n.slice(-2).join(" "):n.join(" ")}}return o?t.state.doc.textBetween(o.from,o.to).length>n?{text:"",error:"Selection is too big"}:{text:t.state.doc.textBetween(o.from,o.to,"\n")}:{text:"",error:"No selection"}}(s,a,i);if(e)return void s.dispatch(s.state.tr.setMeta(j,{type:C.STREAM_ERROR,error:e}));if(!t)return void s.dispatch(s.state.tr.setMeta(j,{type:C.STREAM_ERROR,error:"No text to process"}));d=!0,function({view:t,pluginKey:e,apiKey:n,text:s,task:o,params:a,apiEndpoint:i,model:c}){return r(this,void 0,void 0,(function*(){P(t);const r=new AbortController;M.set(t,r);try{yield N({apiKey:n,text:s,task:o,params:a,endpoint:i,model:c,signal:r.signal},{onChunk:(n,s)=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:C.STREAM_UPDATE,result:s}))},onComplete:n=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:C.STREAM_COMPLETE,result:n}))},onError:n=>{console.error("Streaming request error:",n),t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:C.STREAM_ERROR,error:n.message}))}})}finally{M.delete(t)}}))}({view:s,pluginKey:j,apiKey:n,text:t,task:a.taskType,params:a.params,apiEndpoint:c,model:l}).finally((()=>{d=!1}))}a.status===I.APPLYING&&function(n,s){const{taskType:r,selection:a,streamedResult:i}=s;if(!i)return;let{tr:c}=n.state;if(r===T.Complete)c=c.insertText(i,n.state.doc.nodeSize-2);else if(a){const s=i.split("\n\n").map((t=>n.state.schema.node("paragraph",null,t?n.state.schema.text(t):void 0))),r=t.fromArray(s);c=c.setSelection(o.create(n.state.doc,a.from,a.to)),c.selection.replace(c,new e(r,0,0))}n.dispatch(c),n.focus()}(s,a)}},destroy(){}})})}function k(t,e,n){const s=t.state.selection;t.dispatch(t.state.tr.setMeta(j,{type:C.START_TASK,taskType:e,params:n,selection:s.empty?void 0:s}))}function G(t){t.dispatch(t.state.tr.setMeta(j,{type:C.ACCEPT_RESULT}))}function K(t){t.dispatch(t.state.tr.setMeta(j,{type:C.REJECT_RESULT}))}function F(t){P(t),t.dispatch(t.state.tr.setMeta(j,{type:C.CANCEL_TASK}))}function V(t,e){e||P(t),t.dispatch(t.state.tr.setMeta(j,{type:C.SET_ENABLED,enabled:e}))}function B(t){t.dispatch(t.state.tr.setMeta(j,{type:C.CLEAR_ERROR}))}function H(t){return j.getState(t.state)}const W={debounceMs:2e3,createUpdatePopup:(t,e,n,s,o)=>{const r=document.createElement("div");r.className="grammar-suggest-tooltip";const{spec:a}=e,i=t.dom.getBoundingClientRect();r.id=m.grammarSuggestPopup;const c=t.coordsAtPos(n),l=t.dom.scrollTop||0,d=t.dom.scrollLeft||0;r.style.left=`${c.left-i.left+d}px`,r.style.top=`${c.bottom-i.top+l+5}px`;const u=document.createElement("div");u.className="grammar-suggest-tooltip-apply",u.innerText=a.text||a.originalText,a.text||(u.style.textDecoration="line-through",u.style.color="red"),u.onclick=()=>{s(t,e)},r.appendChild(u);const p=document.createElement("div");return p.innerHTML="<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'><path d='M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z'></path></svg>",p.className="grammar-suggest-tooltip-discard",p.onclick=()=>{o(t,e)},r.appendChild(p),r},withYjs:!1},$={maxSelection:1e3},q=new n("completePlugin"),Q=new n("grammarSuggestPlugin"),Y=(t,e)=>{t.dispatch(t.state.tr.setMeta(Q,{type:g.setEnabled,enabled:e}))},z=(t,e)=>{t.dispatch(t.state.tr.setMeta(q,{type:"setEnabled",enabled:e}))},J=(t,e)=>{if(t===e)return{start:t.length,end:t.length,oldStart:t.length,oldEnd:t.length,oldText:"",newText:""};const n=a(t,e),s=n[0],o=s[0]===a.EQUAL?s[1].length-1:0,r=((t,e)=>{if(e[e.length-1][0]!==a.EQUAL)return t.length;const n=e.slice(0,e.length-1);let s=0;for(const t of n){const[e,n]=t;e===a.EQUAL&&(s+=n.length),e===a.DELETE&&(s+=n.length)}return s})(t,n),i=t.lastIndexOf("\n",o),c=t.indexOf("\n",r),l=-1===i?0:i+1,d=-1===c?t.length:c,u=t.slice(l,d),p=e.slice(l,e.length-(t.length-d));return{start:l,end:l+p.length,oldStart:l,oldEnd:d,oldText:u,newText:p}};var X,Z,tt;!function(t){t.IDLE="IDLE",t.ACTIVE="ACTIVE"}(X||(X={})),function(t){t.DIRTY="DIRTY",t.WAITING="WAITING",t.QUEUED="QUEUED",t.PROCESSING="PROCESSING",t.DONE="DONE",t.BACKOFF="BACKOFF",t.ERROR="ERROR"}(Z||(Z={})),function(t){t.INIT="INIT",t.FINISH="FINISH",t.CLEAR="CLEAR",t.RESUME="RESUME",t.UNIT_STARTED="UNIT_STARTED",t.UNIT_SUCCESS="UNIT_SUCCESS",t.UNIT_ERROR="UNIT_ERROR",t.UPDATE_CONTEXT="UPDATE_CONTEXT",t.REMOVE_DECORATION="REMOVE_DECORATION",t.SELECT_DECORATION="SELECT_DECORATION",t.DESELECT_DECORATION="DESELECT_DECORATION"}(tt||(tt={}));const et={nodeTypes:"paragraph",priorityFilter:()=>!0,visibilityFilter:()=>!0,getGroupId:()=>"default",batchSize:4,maxRetries:3,backoffBase:1e3,dirtyHandling:{shouldRecalculate:!0,debounceDelay:2e3,skipDirtyOnSelfChange:!0},forceRerender:()=>{},onUpdate:void 0};function nt(t){return Object.assign(Object.assign(Object.assign({},et),t),{dirtyHandling:Object.assign(Object.assign({},et.dirtyHandling),t.dirtyHandling)})}function st(t,e,n){const s=[];let o="",r=0;return t.nodesBetween(e,n,((t,a)=>{if(t.isText&&t.text){const i=Math.max(e,a),c=Math.min(n,a+t.nodeSize),l=t.text.slice(i-a,c-a);s.push({from:r,docPos:i}),o+=l,r+=l.length}else t.isBlock&&o.length>0&&(s.push({from:r,docPos:a}),o+="\n",r+=1)})),{text:o,mapping:s}}function ot(t,e){var n,s;for(let n=e.length-1;n>=0;n--)if(e[n].from<=t)return e[n].docPos+(t-e[n].from);return null!==(s=null===(n=e[0])||void 0===n?void 0:n.docPos)&&void 0!==s?s:0}function rt(t,e,n,s="paragraph"){const o=Array.isArray(s)?s:[s],r=[];return t.nodesBetween(e,n,((e,n)=>{if(o.includes(e.type.name)){const s=n+e.nodeSize,o=st(t,n,s);o.text.trim().length>0&&r.push(Object.assign({from:n,to:s},o))}})),r}const at=(t,e)=>t.map((t=>null==t?void 0:t.map(e,0,0))).filter((t=>null!==t)),it=(t,e)=>{const n=t.doc.content.findDiffStart(e.doc.content),s=e.doc.content.findDiffEnd(t.doc.content);if(!s||!n)return;let o=new l([0,0,0]),r=n,a=s.a;return s&&n&&(s.a<n?(r=s.a,a=s.b,o=new l([s.a,0,s.b-s.a])):s.b<n?(r=s.b,a=s.a,o=new l([s.b,s.a-s.b,0])):o=new l([n,s.a-n,s.b-n])),{end:a,mapping:new d([o]),start:r}};function ct(t,e,n,s,o=!1){var r;const a=it(e,n);if(!a)return t;const{start:i,end:c,mapping:l}=a,d=Array.isArray(s.nodeTypes)?s.nodeTypes:[s.nodeTypes],u=Date.now()+s.dirtyHandling.debounceDelay,p=null===(r=t.unitsInProgress)||void 0===r?void 0:r.slice().sort(((t,e)=>t.from-e.from));if(p){const n=[],s=l.map(p[0].from),r=l.map(p[p.length-1].to),a=rt(e.doc,s,r,d);for(const t in p){const e=p[t],s=a[t];if(s){let{status:t}=e;!o&&s.from<=c&&s.to>=i&&(t=Z.DIRTY),n.push(Object.assign(Object.assign(Object.assign({},e),{status:t,waitUntil:o?e.waitUntil:u}),s))}else n.push(Object.assign(Object.assign({},e),{status:Z.DONE,from:r,to:r}))}return Object.assign(Object.assign({},t),{unitsInProgress:n,decorations:at(t.decorations,l)})}return Object.assign(Object.assign({},t),{decorations:at(t.decorations,l)})}function lt(t,e){return 1e3*Math.pow(e/1e3,t)}function dt(t){var e;if(t.status!==X.ACTIVE)return{completed:0,total:0,decorations:t.decorations.length};const n=null!==(e=t.unitsInProgress)&&void 0!==e?e:[];return{completed:n.filter((t=>t.status===Z.DONE||t.status===Z.ERROR)).length,total:n.length,decorations:t.decorations.length}}function ut(t){return new Promise((e=>setTimeout(e,t)))}function pt(t,e,n){t.dispatch(t.state.tr.setMeta(e,n))}function gt(t,e,n){if(e.status===X.ACTIVE)return e.unitsInProgress.find((t=>t.id===n))}function mt(t,e,n){const s=t.unitsInProgress.map((t=>t.id===e?Object.assign(Object.assign({},t),n):t));return"waitUntil"in n&&s.sort(((t,e)=>t.waitUntil-e.waitUntil)),Object.assign(Object.assign({},t),{unitsInProgress:s})}function ft(t){return t.every((t=>t.status===Z.DONE||t.status===Z.ERROR))}function Et(t,e,n,s,o="paragraph"){return rt(t,e,n,o).map(((t,e)=>({id:{},status:Z.QUEUED,from:t.from,to:t.to,text:t.text,mapping:t.mapping,metadata:s(t,e),retryCount:0,waitUntil:0})))}function Tt(t,e){pt(t,e,{type:tt.FINISH})}function St(t,e){pt(t,e,{type:tt.RESUME})}function ht(t){var e;return t.status===X.IDLE&&!!(null===(e=t.unitsInProgress)||void 0===e?void 0:e.some((t=>t.status!==Z.DONE&&t.status!==Z.ERROR)))}function yt(t,e,n,s){var o;switch(e.type){case tt.INIT:return function(t,e,n,s){const o=Et(n,e.onlySelection?s.from:0,e.onlySelection?s.to:n.content.size,((t,n)=>{var s;if(void 0!==e.metadata.single)return e.metadata.single;if(void 0!==e.metadata.array)return null!==(s=e.metadata.array[n])&&void 0!==s?s:e.metadata.array[0];if(void 0!==e.metadata.factory){const n={id:{},status:Z.QUEUED,from:t.from,to:t.to,text:t.text,mapping:[],metadata:{},retryCount:0,waitUntil:0};return e.metadata.factory(n)}return{}})).map((e=>Object.assign(Object.assign({},e),{status:t.options.priorityFilter(e,t.contextState)?Z.QUEUED:Z.WAITING})));return Object.assign(Object.assign({},t),{status:X.ACTIVE,unitsInProgress:o})}(t,e,s.doc,s.selection);case tt.UNIT_STARTED:return t.status!==X.ACTIVE?t:function(t,e){const n=t.unitsInProgress.find((t=>t.id===e));return n?mt(t,e,{status:Z.PROCESSING,requestText:n.text}):t}(t,e.unitId);case tt.UNIT_SUCCESS:return t.status!==X.ACTIVE?t:function(t,e,n){const s=t.unitsInProgress.find((t=>t.id===e.unitId));if(!s)return t;const o=Date.now()+t.options.dirtyHandling.debounceDelay;if(void 0!==s.requestText&&s.requestText!==s.text)return mt(t,e.unitId,{status:Z.DIRTY,requestText:void 0,waitUntil:o});const r=n(e.response,s),a=mt(t,e.unitId,{status:Z.DONE,response:e.response,requestText:void 0});return Object.assign(Object.assign({},a),{decorations:[...a.decorations,...r]})}(t,e,n);case tt.UNIT_ERROR:return t.status!==X.ACTIVE?t:function(t,e){const n=t.unitsInProgress.find((t=>t.id===e.unitId));if(!n)return t;const s=Date.now()+t.options.dirtyHandling.debounceDelay;if(void 0!==n.requestText&&n.requestText!==n.text)return mt(t,e.unitId,{status:Z.DIRTY,requestText:void 0,waitUntil:s});const o=n.retryCount+1;return o>=t.options.maxRetries?mt(t,e.unitId,{status:Z.ERROR,retryCount:o,requestText:void 0}):mt(t,e.unitId,{status:Z.BACKOFF,retryCount:o,waitUntil:Date.now()+lt(o,t.options.backoffBase),requestText:void 0})}(t,e);case tt.FINISH:return Object.assign(Object.assign({},t),{status:X.IDLE});case tt.CLEAR:return Object.assign(Object.assign({},t),{decorations:[],unitsInProgress:void 0,status:X.IDLE,selected:void 0});case tt.RESUME:return t.status!==X.IDLE?t:(null===(o=t.unitsInProgress)||void 0===o?void 0:o.length)?Object.assign(Object.assign({},t),{status:X.ACTIVE}):t;case tt.UPDATE_CONTEXT:return Object.assign(Object.assign({},t),{contextState:e.contextState});case tt.REMOVE_DECORATION:return Object.assign(Object.assign({},t),{decorations:t.decorations.filter((t=>t.spec.id!==e.id))});case tt.SELECT_DECORATION:return Object.assign(Object.assign({},t),{selected:e.id});case tt.DESELECT_DECORATION:return Object.assign(Object.assign({},t),{selected:void 0});default:return t}}function Rt(t,e){return{status:X.IDLE,decorations:[],selected:void 0,contextState:t,options:e}}function It(t,e,n,s){return r(this,void 0,void 0,(function*(){const o=t.getState(e.state);if(!o||o.status!==X.ACTIVE)return!1;const r=function(t,e){var n;if(t.status!==X.ACTIVE)return;const s=Date.now(),o=null!==(n=t.unitsInProgress)&&void 0!==n?n:[],r=t=>[Z.QUEUED,Z.BACKOFF,Z.DIRTY].includes(t.status)&&t.waitUntil<=s,a=o.find((n=>r(n)&&e.priorityFilter(n,t.contextState)));if(a)return a;const i=o.find(r);if(i)return i;return o.find((t=>[Z.QUEUED,Z.BACKOFF,Z.DIRTY].includes(t.status)&&t.waitUntil>s))||void 0}(o,s);if(!r)return!1;pt(e,t,{type:tt.UNIT_STARTED,unitId:r.id});const a=t.getState(e.state);if(!a)return!1;const i=gt(0,a,r.id);if(i&&i.waitUntil>Date.now()){yield ut(i.waitUntil-Date.now());const n=t.getState(e.state);if(!n||n.status!==X.ACTIVE)return!1}try{const s=yield n(e,r);s.error?pt(e,t,{type:tt.UNIT_ERROR,unitId:r.id,error:s.error}):void 0!==s.data&&pt(e,t,{type:tt.UNIT_SUCCESS,unitId:r.id,response:s.data})}catch(n){pt(e,t,{type:tt.UNIT_ERROR,unitId:r.id,error:n instanceof Error?n:new Error(String(n))})}return!0}))}function Ct(t,e,n,s){return r(this,void 0,void 0,(function*(){return!!(yield It(t,e,n,s))&&Ct(t,e,n,s)}))}function bt(t,e,n,s){return r(this,void 0,void 0,(function*(){const o=Array.from({length:s.batchSize},(()=>Ct(t,e,n,s)));yield Promise.all(o)}))}function Ot(t){return t.status===X.ACTIVE&&t.unitsInProgress.some((t=>t.status===Z.QUEUED||t.status===Z.WAITING||t.status===Z.BACKOFF||t.status===Z.DIRTY||t.status===Z.PROCESSING))}function vt(t){const{pluginKey:e,unitProcessor:n,decorationFactory:o,decorationTransformer:r,widgetFactory:a,initialContextState:i,options:c,handleKeyDown:l}=t,d=nt(null!=c?c:{});let p=!1;return new s({key:e,state:{init:()=>Rt(i,d),apply(t,n,s,r){const a=t.getMeta(e),i=t.docChanged&&void 0!==a&&d.dirtyHandling.skipDirtyOnSelfChange;let c=n;if(t.docChanged&&(c=ct(n,t,s,d,i)),a){const t=yt(c,a,o,r);return d.onUpdate&&d.onUpdate(t),t}return c}},props:{decorations(t){const n=e.getState(t);if(!n)return u.empty;let s=n.decorations.filter((t=>d.visibilityFilter(t,n.contextState)));r&&(s=r(s,n));const o=[];if(a&&n.unitsInProgress)for(const t of n.unitsInProgress)if(t.status!==Z.DONE&&t.status!==Z.ERROR){const e=a(t);e&&o.push(e)}return u.create(t.doc,[...s,...o])},handleKeyDown:l},view:()=>({update(t){const s=e.getState(t.state);s&&s.status===X.ACTIVE&&!p&&Ot(s)&&(p=!0,bt(e,t,n,d).finally((()=>{p=!1;const n=e.getState(t.state);!n||n.status!==X.ACTIVE||Ot(n)||d.dirtyHandling.shouldRecalculate||pt(t,e,{type:tt.FINISH})})))}})})}function xt(t){return new n(t)}const At=(t,e)=>t.map((n=>{const s=ot(n.from,e.mapping),o=ot(n.to,e.mapping);return p.inline(s,o,{class:"link-detected",style:"color: #0066cc; text-decoration: underline; cursor: pointer;"},{id:{},unitId:e.id,originalText:n.url,response:t,url:n.url})})),Dt=/https?:\/\/[^\s<>"')\]]+/g;const Nt=(t,e)=>r(void 0,void 0,void 0,(function*(){return{data:function(t){const e=[];let n=Dt.exec(t);for(;null!==n;)e.push({url:n[0],from:n.index,to:n.index+n[0].length}),n=Dt.exec(t);return e}(e.text)}})),wt=xt("linkDetector");function Mt(){const t=vt({pluginKey:wt,unitProcessor:Nt,decorationFactory:At,initialContextState:{}});return new s({key:wt,state:t.spec.state,props:Object.assign(Object.assign({},t.spec.props),{handleDOMEvents:{click:(t,e)=>{const n=e.target;if(n.classList.contains("link-detected")){const s=t.posAtDOM(n,0),o=wt.getState(t.state);if(o){const t=o.decorations.find((t=>t.from<=s&&t.to>=s&&t.spec.url));if(null==t?void 0:t.spec.url)return window.open(t.spec.url,"_blank"),e.preventDefault(),!0}}return!1}}}),view:t.spec.view})}const Pt={moderate:{class:"word-complexity-moderate",style:"background-color: rgba(255, 193, 7, 0.3); border-radius: 2px;"},high:{class:"word-complexity-high",style:"background-color: rgba(244, 67, 54, 0.3); border-radius: 2px;"}},Ut=(t,e)=>t.map((n=>{const s=ot(n.from,e.mapping),o=ot(n.to,e.mapping),r=Pt[n.complexity];return p.inline(s,o,{class:r.class,style:r.style},{id:{},unitId:e.id,originalText:n.word,response:t,syllables:n.syllables,complexity:n.complexity})}));function jt(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");if(e.length<=3)return 1;e=e.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/,""),e=e.replace(/^y/,"");const n=e.match(/[aeiouy]{1,2}/g);return n?Math.max(1,n.length):1}const _t=/[a-zA-Z]+/g;function Lt(t,e,n){const s=[];let o=_t.exec(t);for(;null!==o;){const r=o[0],a=jt(r);a>=e&&s.push({word:r,from:o.index,to:o.index+r.length,syllables:a,complexity:a>=n?"high":"moderate"}),o=_t.exec(t)}return s}const kt=t=>(e,n)=>r(void 0,void 0,void 0,(function*(){var e,s;const o=t(),r=null!==(e=o.moderateThreshold)&&void 0!==e?e:3,a=null!==(s=o.highThreshold)&&void 0!==s?s:4;return{data:Lt(n.text,r,a)}})),Gt=(t,e)=>r(void 0,void 0,void 0,(function*(){return{data:Lt(e.text,3,4)}})),Kt={moderateThreshold:3,highThreshold:4},Ft=xt("wordComplexity");function Vt(t={}){return vt({pluginKey:Ft,unitProcessor:Gt,decorationFactory:Ut,initialContextState:Object.assign(Object.assign({},Kt),t)})}const Bt={warning:{class:"sentence-too-long-warning",style:"background-color: rgba(255, 152, 0, 0.2); border-radius: 2px;"},error:{class:"sentence-too-long-error",style:"background-color: rgba(244, 67, 54, 0.2); border-radius: 2px;"}},Ht=(t,e)=>t.map((n=>{const s=ot(n.from,e.mapping),o=ot(n.to,e.mapping),r=Bt[n.severity];return p.inline(s,o,{class:r.class,style:r.style},{id:{},unitId:e.id,originalText:e.text.slice(n.from,n.to),response:t,wordCount:n.wordCount,severity:n.severity})})),Wt=/[^.!?]*[.!?]+/g,$t=/\b\w+\b/g;function qt(t){const e=t.match($t);return e?e.length:0}function Qt(t,e,n){const s=[];let o=Wt.exec(t);for(;null!==o;){const r=o[0],a=qt(r);a>=e&&s.push({from:o.index,to:o.index+r.length,wordCount:a,severity:a>=n?"error":"warning"}),o=Wt.exec(t)}return s}const Yt=t=>(e,n)=>r(void 0,void 0,void 0,(function*(){var e,s;const o=t(),r=null!==(e=o.warningThreshold)&&void 0!==e?e:25,a=null!==(s=o.errorThreshold)&&void 0!==s?s:40;return{data:Qt(n.text,r,a)}})),zt=(t,e)=>r(void 0,void 0,void 0,(function*(){return{data:Qt(e.text,25,40)}})),Jt={warningThreshold:25,errorThreshold:40},Xt=xt("sentenceLength");function Zt(t={}){return vt({pluginKey:Xt,unitProcessor:zt,decorationFactory:Ht,initialContextState:Object.assign(Object.assign({},Jt),t)})}const te=(t,e)=>[p.inline(e.from+1,e.to-1,{class:"random-processor-success",style:"background-color: rgba(76, 175, 80, 0.2); border-radius: 2px;"},{id:{},unitId:e.id,originalText:e.text,response:t,processingTime:t.processingTime})],ee=t=>{let e,n;const s=Math.max(0,t.waitUntil-Date.now());switch(t.status){case Z.QUEUED:e="⏳ Queued...",n="random-processor-widget queued";break;case Z.PROCESSING:e="⚙️ Processing...",n="random-processor-widget processing";break;case Z.BACKOFF:e=`🔄 Retry in ${Math.ceil(s/1e3)}s (attempt ${t.retryCount+1})`,n="random-processor-widget backoff";break;case Z.ERROR:e=`❌ Failed after ${t.retryCount} retries`,n="random-processor-widget error";break;case Z.DIRTY:e="⚠️ Changed",n="random-processor-widget dirty";break;case Z.WAITING:e="⏸️ Waiting...",n="random-processor-widget waiting";break;default:return}let o,r;switch(t.status){case Z.ERROR:o="#ffebee",r="#c62828";break;case Z.DIRTY:o="#fff9c4",r="#f57f17";break;case Z.BACKOFF:o="#fff3e0",r="#e65100";break;default:o="#e3f2fd",r="#1565c0"}const a=document.createElement("span");if(a.className=n,a.textContent=e,t.status===Z.BACKOFF&&s>0){const e=setInterval((()=>{const n=Math.max(0,t.waitUntil-Date.now());a.textContent=`🔄 Retry in ${Math.ceil(n/1e3)}s (attempt ${t.retryCount+1})`,(n<=0||!a.isConnected)&&clearInterval(e)}),1e3)}return a.style.cssText=`\n display: inline-block;\n padding: 2px 8px;\n margin-right: 8px;\n font-size: 12px;\n border-radius: 4px;\n background: ${o};\n color: ${r};\n `,p.widget(t.from+1,a,{side:-1})};function ne(t,e){return Math.floor(Math.random()*(e-t+1))+t}function se(t){return new Promise((e=>setTimeout(e,t)))}const oe=t=>(e,n)=>r(void 0,void 0,void 0,(function*(){var e,s,o;const r=t(),a=null!==(e=r.minDelay)&&void 0!==e?e:500,i=null!==(s=r.maxDelay)&&void 0!==s?s:3e3,c=null!==(o=r.errorRate)&&void 0!==o?o:.3,l=ne(a,i);yield se(l);return Math.random()<c?{error:new Error(`Random error after ${l}ms (attempt ${n.metadata.attempt})`)}:{data:{processingTime:l,success:!0,message:`Processed "${n.text.slice(0,20)}..." in ${l}ms`}}})),re=(t,e)=>r(void 0,void 0,void 0,(function*(){const t=ne(500,3e3);yield se(t);return Math.random()<.3?{error:new Error(`Random error after ${t}ms (attempt ${e.metadata.attempt})`)}:{data:{processingTime:t,success:!0,message:`Processed "${e.text.slice(0,20)}..." in ${t}ms`}}})),ae={minDelay:500,maxDelay:3e3,errorRate:.3},ie=xt("randomProcessor");function ce(t={}){return vt({pluginKey:ie,unitProcessor:re,decorationFactory:te,widgetFactory:ee,initialContextState:Object.assign(Object.assign({},ae),t),options:{batchSize:2,maxRetries:3,backoffBase:2e3}})}const le=(t,e)=>t.fixed&&0!==t.suggestions.length?t.suggestions.map((n=>{const s=ot(n.from,e.mapping),o=ot(n.to,e.mapping),r=""===n.replacement,a={id:{},unitId:e.id,originalText:n.original,replacement:n.replacement,response:t};return p.inline(s,o,{class:"grammarSuggestionV2 "+(r?"removalSuggestionV2":"")},a)})):[],de=(t,e)=>{const n=e.contextState.selectedSuggestionId;return n?t.map((t=>{const e=t.spec;return e.id===n?p.inline(t.from,t.to,{class:"grammarSuggestionV2 grammarSuggestionV2-selected"},e):t})):t},ue=t=>{let e,n;const s=Math.max(0,t.waitUntil-Date.now());switch(t.status){case Z.QUEUED:case Z.WAITING:e="⏳",n="grammarWidgetV2 queued";break;case Z.PROCESSING:e="🔍",n="grammarWidgetV2 processing";break;case Z.BACKOFF:e=`🔄 ${Math.ceil(s/1e3)}s`,n="grammarWidgetV2 backoff";break;case Z.ERROR:e="❌",n="grammarWidgetV2 error";break;case Z.DIRTY:e="✏️",n="grammarWidgetV2 dirty";break;default:return}const o=document.createElement("span");if(o.className=n,o.textContent=e,t.status===Z.BACKOFF&&s>0){const e=setInterval((()=>{const n=Math.max(0,t.waitUntil-Date.now());o.textContent=`🔄 ${Math.ceil(n/1e3)}s`,(n<=0||!o.isConnected)&&clearInterval(e)}),1e3)}return p.widget(t.from+1,o,{side:-1})};const pe=t=>{const{apiKey:e,apiEndpoint:n,model:s,modelStateManager:o}="string"==typeof t?{apiKey:t,apiEndpoint:void 0,model:void 0,modelStateManager:void 0}:t;return(t,a)=>r(void 0,void 0,void 0,(function*(){var t,r,l;try{const d=null!==(t=null==o?void 0:o.getCurrentModel())&&void 0!==t?t:s,u=yield w({apiKey:e,text:a.text,endpoint:n,model:d});if(u.error)return null==o||o.handleFailure(),{error:new Error("Grammar API error")};if(null==o||o.handleSuccess(),!u.fixed)return{data:{fixed:!1,originalText:a.text,fixedText:a.text,suggestions:[]}};const p=(r=a.text,l=u.result,i(r,l).filter((t=>!c(t))).filter((t=>t.original!==`${t.replacement}\n`)).map((t=>({from:t.from,to:t.replacement.endsWith("\n")?t.to-1:t.to,original:t.original,replacement:t.replacement.endsWith("\n")?t.replacement.slice(0,-1):t.replacement}))));return{data:{fixed:p.length>0,originalText:a.text,fixedText:u.result,suggestions:p}}}catch(t){return null==o||o.handleFailure(),{error:t instanceof Error?t:new Error(String(t))}}}))};function ge(t,e,n){const s=e.getState(t.state);if(s)return s.decorations.find((t=>t.spec.id===n))}function me(n,s,r){const a=ge(n,s,r);if(!a)return;const i=a.spec,{replacement:c}=i,{from:l,to:d}=a,u=c.split("\n").map((t=>t?n.state.schema.node("paragraph",null,n.state.schema.text(t)):n.state.schema.node("paragraph"))),p=t.fromArray(u);let{tr:g}=n.state;g=g.setSelection(o.create(n.state.doc,l,d)),g.selection.replace(g,new e(p,1,1)),g=g.setMeta(s,{type:tt.REMOVE_DECORATION,id:r}),n.dispatch(g)}function fe(t,e,n){pt(t,e,{type:tt.REMOVE_DECORATION,id:n})}function Ee(t,e,n){pt(t,e,{type:tt.UPDATE_CONTEXT,contextState:{selectedSuggestionId:n}})}function Te(t,e){pt(t,e,{type:tt.UPDATE_CONTEXT,contextState:{selectedSuggestionId:void 0}})}function Se(t,e){const n=e.getState(t.state);if(null==n?void 0:n.contextState.selectedSuggestionId)return ge(t,e,n.contextState.selectedSuggestionId)}function he(t,e,n,s){var o,a,i;return r(this,void 0,void 0,(function*(){const r=null!==(o=null==s?void 0:s.endpoint)&&void 0!==o?o:O,c=null==s?void 0:s.modelStateManager,l=null!==(i=null!==(a=null==c?void 0:c.getCurrentModel())&&void 0!==a?a:null==s?void 0:s.model)&&void 0!==i?i:x;return new Promise(((s,o)=>{const a={previousPromptType:"Grammar",oldVersion:e,newVersion:n};N({apiKey:t,text:e,task:S.Hint,params:a,endpoint:r,model:l},{onChunk:()=>{},onComplete:t=>{null==c||c.handleSuccess(),s(t)},onError:t=>{null==c||c.handleFailure(),o(t)}})}))}))}const ye={selectedSuggestionId:void 0},Re=xt("grammarSuggestV2"),Ie=(t,e,n,s,o,a)=>{const i=e.spec,c=document.createElement("div");c.className="grammarPopupV2";const l=document.createElement("div");l.className="grammarPopupV2-mainRow";const d=document.createElement("span");d.className="grammarPopupV2-original",d.textContent=`"${i.originalText}"`;const u=document.createElement("span");u.className="grammarPopupV2-arrow",u.textContent=" → ";const p=document.createElement("span");p.className="grammarPopupV2-replacement",p.textContent=""===i.replacement?"(remove)":`"${i.replacement}"`;const g=document.createElement("button");g.className="grammarPopupV2-hint",g.textContent="?",g.title="Why this suggestion?";const m=document.createElement("div");m.className="grammarPopupV2-hintArea",m.style.display="none";let f=!1;g.onclick=t=>r(void 0,void 0,void 0,(function*(){if(t.preventDefault(),t.stopPropagation(),"none"===m.style.display){if(m.style.display="block",!f){m.innerHTML='<span class="grammarPopupV2-loading">Loading...</span>';try{const t=yield a();m.innerHTML="";const e=document.createElement("span");e.className="grammarPopupV2-hintText",e.textContent=t,m.appendChild(e),f=!0}catch(t){m.innerHTML='<span class="grammarPopupV2-hintError">Could not load hint</span>'}}}else m.style.display="none"}));const E=document.createElement("button");E.className="grammarPopupV2-accept",E.textContent="✓",E.onclick=t=>{t.preventDefault(),t.stopPropagation(),s()};const T=document.createElement("button");return T.className="grammarPopupV2-discard",T.textContent="✕",T.onclick=t=>{t.preventDefault(),t.stopPropagation(),o()},l.appendChild(d),l.appendChild(u),l.appendChild(p),l.appendChild(g),l.appendChild(E),l.appendChild(T),c.appendChild(l),c.appendChild(m),c};function Ce(t,e={}){var n;const{apiEndpoint:o,model:r,fallback:a,batchSize:i=4,maxRetries:c=3,backoffBase:l=2e3,debounceMs:d=1e3,createPopup:g=Ie}=e,m=a?function(t){const{primaryModel:e,fallbackModel:n,failureThreshold:s}=t;let o=0;return{getCurrentModel:()=>n&&s>0&&o>=s?n:e,handleSuccess(){o=0},handleFailure(){n&&o++}}}({primaryModel:r,fallbackModel:a.fallbackModel,failureThreshold:null!==(n=a.failureThreshold)&&void 0!==n?n:3}):void 0,f=pe({apiKey:t,apiEndpoint:o,model:r,modelStateManager:m}),E=vt({pluginKey:Re,unitProcessor:f,decorationFactory:le,decorationTransformer:de,widgetFactory:ue,initialContextState:ye,options:{batchSize:i,maxRetries:c,backoffBase:l,dirtyHandling:{debounceDelay:d}}});return new s({key:Re,state:E.spec.state,props:Object.assign(Object.assign({},E.spec.props),{decorations(e){var n;const s=null===(n=E.spec.props)||void 0===n?void 0:n.decorations,a=s?s.call(E,e):u.empty;if("react"===g)return a;const i=Re.getState(e);if(!(null==i?void 0:i.contextState.selectedSuggestionId))return a;const c=i.decorations.find((t=>t.spec.id===i.contextState.selectedSuggestionId));if(!c)return a;const l=c.spec,d=p.widget(c.from,((e,n)=>{const s=n();return void 0===s?document.createElement("div"):g(e,c,s,(()=>me(e,Re,c.spec.id)),(()=>fe(e,Re,c.spec.id)),(()=>he(t,l.originalText,l.replacement,{endpoint:o,model:r,modelStateManager:m})))}),{id:c.spec.id,side:-1,stopEvent:()=>!0});return a.add(e.doc,[d])},handleClick(t,e,n){const s=Re.getState(t.state);if(!s)return!1;const o=s.decorations.find((t=>t.from<=e&&e<=t.to));return o?(o.spec.id===s.contextState.selectedSuggestionId||Ee(t,Re,o.spec.id),!1):(s.contextState.selectedSuggestionId&&Te(t,Re),!1)}}),view:E.spec.view})}var be,Oe;!function(t){t.IDLE="idle",t.DEBOUNCING="debouncing",t.PENDING="pending",t.STREAMING="streaming",t.SHOWING="showing"}(be||(be={})),function(t){t.SET_ENABLED="SET_ENABLED",t.START_DEBOUNCE="START_DEBOUNCE",t.START_REQUEST="START_REQUEST",t.STREAM_UPDATE="STREAM_UPDATE",t.STREAM_COMPLETE="STREAM_COMPLETE",t.STREAM_ERROR="STREAM_ERROR",t.DISMISS="DISMISS",t.ACCEPT="ACCEPT"}(Oe||(Oe={}));const ve={debounceMs:500,maxContextLength:2e3,ghostTextClass:"autoCompleteGhostText"},xe=new WeakMap;function Ae(t){const e=xe.get(t);e&&(e.abort(),xe.delete(t))}function De(t){return xe.has(t)}function Ne(t,e){if(!e)return e;const{doc:n,selection:s}=t.state,o=s.from;if(o<=0)return e;const r=n.textBetween(o-1,o,""),a=e.charAt(0),i=/[\s\-]/;return!i.test(r)&&!i.test(a)?` ${e}`:e}const we=new n("autoCompletePlugin"),Me={status:be.IDLE,enabled:!0,suggestion:"",cursorPos:0};function Pe(t,e){switch(e.type){case Oe.SET_ENABLED:return Object.assign(Object.assign({},Me),{enabled:e.enabled});case Oe.START_DEBOUNCE:return Object.assign(Object.assign({},t),{status:be.DEBOUNCING,cursorPos:e.cursorPos,suggestion:"",error:void 0});case Oe.START_REQUEST:return t.status!==be.DEBOUNCING?t:Object.assign(Object.assign({},t),{status:be.PENDING});case Oe.STREAM_UPDATE:return t.status!==be.PENDING&&t.status!==be.STREAMING?t:Object.assign(Object.assign({},t),{status:be.STREAMING,suggestion:e.suggestion});case Oe.STREAM_COMPLETE:return t.status!==be.PENDING&&t.status!==be.STREAMING?t:Object.assign(Object.assign({},t),{status:be.SHOWING,suggestion:e.suggestion});case Oe.STREAM_ERROR:return Object.assign(Object.assign({},t),{status:be.IDLE,error:e.error,suggestion:""});case Oe.DISMISS:case Oe.ACCEPT:return Object.assign(Object.assign({},t),{status:be.IDLE,suggestion:""});default:return t}}function Ue(t,e={}){const n=Object.assign(Object.assign({},ve),e),{debounceMs:o,maxContextLength:a,apiEndpoint:i,model:c,ghostTextClass:l}=n;let d=null,g=!1,m=null,f=null;return new s({key:we,state:{init:()=>Object.assign({},Me),apply(t,e,n,s){const o=t.getMeta(we);if(o)return Pe(e,o);if(t.docChanged&&(e.status===be.SHOWING||e.status===be.STREAMING)){if(s.selection.from!==e.cursorPos)return Pe(e,{type:Oe.DISMISS})}return!t.selectionSet||t.docChanged||e.status!==be.SHOWING&&e.status!==be.STREAMING?e:Pe(e,{type:Oe.DISMISS})}},props:{decorations(t){const e=we.getState(t);if(!e||!e.enabled)return u.empty;if((e.status===be.STREAMING||e.status===be.SHOWING)&&e.suggestion){const n=document.createElement("span");n.className=l,n.textContent=e.suggestion,n.setAttribute("contenteditable","false");const s=p.widget(e.cursorPos,n,{side:1});return u.create(t.doc,[s])}return u.empty},handleKeyDown(t,e){const n=we.getState(t.state);return!(!n||!n.enabled)&&("Tab"===e.key&&!e.shiftKey&&n.status===be.SHOWING&&n.suggestion?(e.preventDefault(),m=n.suggestion,f=n.cursorPos,t.dispatch(t.state.tr.setMeta(we,{type:Oe.ACCEPT})),!0):"Escape"===e.key&&(n.status===be.STREAMING||n.status===be.SHOWING)&&(e.preventDefault(),Ae(t),t.dispatch(t.state.tr.setMeta(we,{type:Oe.DISMISS})),!0))}},view:()=>({update(e,n){const s=we.getState(e.state),l=we.getState(n);if(s&&s.enabled){if(null!==m&&null!==f){const t=m,n=f;m=null,f=null;const s=e.state.tr.insertText(t,n);return e.dispatch(s),void e.focus()}if(e.state,e.state.doc!==n.doc&&(null==l?void 0:l.status)!==be.PENDING&&(null==l?void 0:l.status)!==be.STREAMING){e.state.tr,d&&(clearTimeout(d),d=null),Ae(e);const t=e.state.selection.from;e.dispatch(e.state.tr.setMeta(we,{type:Oe.START_DEBOUNCE,cursorPos:t})),d=setTimeout((()=>{d=null;const t=we.getState(e.state);(null==t?void 0:t.status)===be.DEBOUNCING&&e.dispatch(e.state.tr.setMeta(we,{type:Oe.START_REQUEST}))}),o)}if(s.status===be.PENDING&&!g){if(!function(t){const{doc:e,selection:n}=t.state,s=n.from,o=e.resolve(s),r=o.parent,a=o.start();if(s!==a+r.content.size)return!1;const i=r.textBetween(0,s-a,"");return!!i.trim()&&!/[.!?]\s*$/.test(i)}(e))return void e.dispatch(e.state.tr.setMeta(we,{type:Oe.DISMISS}));const n=function(t,e){const{doc:n,selection:s}=t.state,o=s.from,r=n.textBetween(0,o,"\n");return r.length>e?r.slice(-e):r}(e,a);if(!n.trim())return void e.dispatch(e.state.tr.setMeta(we,{type:Oe.DISMISS}));g=!0,function({view:t,pluginKey:e,apiKey:n,context:s,apiEndpoint:o,model:a}){return r(this,void 0,void 0,(function*(){Ae(t);const r=new AbortController;xe.set(t,r);try{yield N({apiKey:n,text:s,task:T.SmallComplete,endpoint:o,model:a,signal:r.signal},{onChunk:(n,s)=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:Oe.STREAM_UPDATE,suggestion:Ne(t,s)}))},onComplete:n=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:Oe.STREAM_COMPLETE,suggestion:Ne(t,n)}))},onError:n=>{console.error("Auto-complete streaming error:",n),t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:Oe.STREAM_ERROR,error:n.message}))}})}finally{xe.delete(t)}}))}({view:e,pluginKey:we,apiKey:t,context:n,apiEndpoint:i,model:c}).finally((()=>{g=!1}))}}else d&&(clearTimeout(d),d=null)},destroy(){d&&(clearTimeout(d),d=null)}})})}function je(t,e){e||Ae(t),t.dispatch(t.state.tr.setMeta(we,{type:Oe.SET_ENABLED,enabled:e}))}function _e(t){const e=we.getState(t.state);if(!e||!e.suggestion)return!1;const n=t.state.tr.insertText(e.suggestion,e.cursorPos);return t.dispatch(n),t.dispatch(t.state.tr.setMeta(we,{type:Oe.DISMISS})),t.focus(),!0}function Le(t){Ae(t),t.dispatch(t.state.tr.setMeta(we,{type:Oe.DISMISS}))}function ke(t){return we.getState(t.state)}function Ge(t){var e;const n=we.getState(t.state);return null!==(e=null==n?void 0:n.enabled)&&void 0!==e&&e}function Ke(t){const e=we.getState(t.state);return!!(null==e?void 0:e.suggestion)}const Fe=L;export{tt as ActionType,S as AiPromptsWithParam,T as AiPromptsWithoutParam,Oe as AutoCompleteActionType,be as AutoCompleteStatus,C as CompleteActionType,I as CompleteStatus,O as DEFAULT_COMPLETION_ENDPOINT,v as DEFAULT_GRAMMAR_ENDPOINT,x as DEFAULT_MODEL,m as GrammarSuggestElementClass,g as GrammarSuggestMetaType,f as MoodParamType,y as OpenAiPromptsWithParam,h as OpenAiPromptsWithoutParam,X as RunnerStatus,R as Status,E as TranslationTargetLanguage,Z as UnitStatus,_e as acceptAutoCompletion,G as acceptResult,me as acceptSuggestion,ft as allUnitsFinished,we as autoCompleteKey,Ue as autoCompletePlugin,vt as blockRunnerPlugin,lt as calculateBackoff,ht as canResume,P as cancelActiveRequest,Ae as cancelAutoCompleteRequest,F as cancelTask,B as clearError,Fe as completePlugin,q as completePluginKey,L as completePluginV2,j as completeV2Key,jt as countSyllables,A as createApiConfig,xt as createBlockRunnerKey,D as createGrammarApiConfig,pe as createGrammarProcessor,Rt as createInitialState,Mt as createLinkDetectorPlugin,oe as createRandomProcessor,ce as createRandomProcessorPlugin,Zt as createSentenceLengthPlugin,Yt as createSentenceLengthProcessor,Et as createUnitsFromDocument,Vt as createWordComplexityPlugin,kt as createWordComplexityProcessor,ve as defaultAutoCompleteOptions,$ as defaultCompleteOptions,b as defaultCompleteV2Options,W as defaultOptions,et as defaultRunnerOptions,Te as deselectSuggestion,fe as discardSuggestion,Le as dismissAutoCompletion,pt as dispatchAction,bt as executeParallel,st as extractTextWithMapping,ke as getAutoCompleteState,J as getChangedRegions,H as getCompleteState,dt as getProgress,Se as getSelectedDecoration,gt as getUnitById,rt as getUnitsInRange,le as grammarDecorationFactory,de as grammarDecorationTransformer,w as grammarRequest,Q as grammarSuggestPluginKey,Ce as grammarSuggestPluginV2,Re as grammarSuggestV2Key,ue as grammarWidgetFactory,yt as handleAction,U as hasActiveRequest,De as hasAutoCompleteRequest,Ke as hasAutoCompletion,Ot as hasUnitsToProcess,Ge as isAutoCompleteEnabled,At as linkDetectorDecorationFactory,wt as linkDetectorKey,Nt as linkDetectorProcessor,nt as mergeOptions,Tt as pauseRunner,re as randomProcessor,te as randomProcessorDecorationFactory,ie as randomProcessorKey,ee as randomProcessorWidgetFactory,K as rejectResult,ct as remapPositions,he as requestHint,St as resumeRunner,Ee as selectSuggestion,Ht as sentenceLengthDecorationFactory,Xt as sentenceLengthKey,zt as sentenceLengthProcessor,je as setAutoCompleteEnabled,z as setCompleteEnabled,V as setEnabled,Y as setGrammarSuggestEnabled,ut as sleep,k as startTask,N as streamingRequest,ot as textToDocPos,mt as updateUnit,Ut as wordComplexityDecorationFactory,Ft as wordComplexityKey,Gt as wordComplexityProcessor};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var t,e,o,s,n,r=require("prosemirror-model"),a=require("prosemirror-state"),i=require("tslib"),c=require("fast-diff"),p=require("@emergence-engineering/fast-diff-merge"),u=require("prosemirror-transform"),l=require("prosemirror-view");exports.GrammarSuggestMetaType=void 0,(t=exports.GrammarSuggestMetaType||(exports.GrammarSuggestMetaType={})).suggestionUpdate="suggestionUpdate",t.acceptSuggestion="acceptSuggestion",t.openSuggestion="openSuggestion",t.closeSuggestion="closeSuggestion",t.discardSuggestion="discardSuggestion",t.setEnabled="setEnabled",exports.GrammarSuggestElementClass=void 0,(exports.GrammarSuggestElementClass||(exports.GrammarSuggestElementClass={})).grammarSuggestPopup="grammar-suggest-popup",exports.MoodParamType=void 0,(e=exports.MoodParamType||(exports.MoodParamType={})).Casual="Casual",e.Confident="Confident",e.Straightforward="Straightforward",e.Friendly="Friendly",exports.TranslationTargetLanguage=void 0,(o=exports.TranslationTargetLanguage||(exports.TranslationTargetLanguage={})).English="English",o.Spanish="Spanish",o.French="French",o.German="German",o.Italian="Italian",o.Portuguese="Portuguese",o.Dutch="Dutch",o.Russian="Russian",o.Chinese="Chinese",o.Korean="Korean",o.Japanese="Japanese",exports.AiPromptsWithoutParam=void 0,(s=exports.AiPromptsWithoutParam||(exports.AiPromptsWithoutParam={})).Complete="Complete",s.SmallComplete="SmallComplete",s.Improve="Improve",s.MakeLonger="MakeLonger",s.MakeShorter="MakeShorter",s.Simplify="Simplify",s.Explain="Explain",s.ActionItems="ActionItems",exports.AiPromptsWithParam=void 0,(n=exports.AiPromptsWithParam||(exports.AiPromptsWithParam={})).ChangeTone="ChangeTone",n.Translate="Translate",n.Hint="Hint",n.Custom="Custom";const d=exports.AiPromptsWithoutParam,m=exports.AiPromptsWithParam;var g,x,S;exports.Status=void 0,(g=exports.Status||(exports.Status={})).idle="idle",g.new="new",g.streaming="streaming",g.finished="finished",g.accepted="accepted",g.cancelled="cancelled",g.rejected="rejected",g.done="done",g.error="error",exports.CompleteStatus=void 0,(x=exports.CompleteStatus||(exports.CompleteStatus={})).IDLE="idle",x.PENDING="pending",x.STREAMING="streaming",x.PREVIEW="preview",x.APPLYING="applying",exports.CompleteActionType=void 0,(S=exports.CompleteActionType||(exports.CompleteActionType={})).START_TASK="START_TASK",S.STREAM_UPDATE="STREAM_UPDATE",S.STREAM_COMPLETE="STREAM_COMPLETE",S.STREAM_ERROR="STREAM_ERROR",S.ACCEPT_RESULT="ACCEPT_RESULT",S.REJECT_RESULT="REJECT_RESULT",S.CANCEL_TASK="CANCEL_TASK",S.CLEAR_ERROR="CLEAR_ERROR",S.SET_ENABLED="SET_ENABLED";const E={maxSelection:1e3},T="https://suggestion-gw5lxik4dq-uc.a.run.app",f="https://prosemirror-ai-plugin.web.app/api/suggestion",y="openai:gpt-4o-mini";function A(t,e){var o;return i.__awaiter(this,void 0,void 0,(function*(){const{apiKey:s,text:n,task:r,params:a,endpoint:i=T,model:c=y,signal:p}=t;let u="";const l={model:c,modelParams:{input:[n],task:r,params:a}};try{const t=yield fetch(i,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},signal:p,body:JSON.stringify(l)});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}`);const n=null===(o=t.body)||void 0===o?void 0:o.getReader();if(!n)throw new Error("No response body");for(;;){const{done:t,value:o}=yield n.read();if(t)break;if(null==p?void 0:p.aborted)return;const s=(new TextDecoder).decode(o);u+=s,e.onChunk(s,u)}(null==p?void 0:p.aborted)||e.onComplete(u)}catch(t){if(t instanceof Error&&"AbortError"===t.name)return;e.onError(t instanceof Error?t:new Error(String(t)))}}))}function C(t){return i.__awaiter(this,void 0,void 0,(function*(){const{apiKey:e,text:o,endpoint:s=f,model:n=y}=t,r={model:n,modelParams:{input:[...o.split("\n")]}};try{const t=yield fetch(s,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(r)});if(!t.ok){const e=yield t.text();return console.error({status:t.status,text:e}),{fixed:!1,result:o,error:!0}}const n=yield t.json();return(null==n?void 0:n.length)?{result:n.join("\n"),fixed:!0}:{fixed:!1,result:o}}catch(t){return console.error("Grammar request error:",t),{fixed:!1,result:o,error:!0}}}))}const h=new WeakMap;function R(t){const e=h.get(t);e&&(e.abort(),h.delete(t))}const b=new a.PluginKey("completePluginV2"),I={status:exports.CompleteStatus.IDLE,streamedResult:"",enabled:!0};function O(t,e={}){const{maxSelection:o,apiEndpoint:s,model:n}=Object.assign(Object.assign({},E),e);let c=!1;return new a.Plugin({key:b,state:{init:()=>Object.assign({},I),apply(t,e){const o=t.getMeta(b);return o?function(t,e){switch(e.type){case exports.CompleteActionType.SET_ENABLED:return Object.assign(Object.assign(Object.assign({},t),{enabled:e.enabled}),e.enabled?{}:I);case exports.CompleteActionType.START_TASK:return t.status!==exports.CompleteStatus.IDLE?t:Object.assign(Object.assign({},t),{status:exports.CompleteStatus.PENDING,taskType:e.taskType,params:e.params,selection:e.selection,streamedResult:"",error:void 0});case exports.CompleteActionType.STREAM_UPDATE:return t.status!==exports.CompleteStatus.PENDING&&t.status!==exports.CompleteStatus.STREAMING?t:Object.assign(Object.assign({},t),{status:exports.CompleteStatus.STREAMING,streamedResult:e.result});case exports.CompleteActionType.STREAM_COMPLETE:return t.status!==exports.CompleteStatus.PENDING&&t.status!==exports.CompleteStatus.STREAMING?t:Object.assign(Object.assign({},t),{status:exports.CompleteStatus.PREVIEW,streamedResult:e.result});case exports.CompleteActionType.STREAM_ERROR:return Object.assign(Object.assign({},t),{status:exports.CompleteStatus.IDLE,error:e.error,streamedResult:"",taskType:void 0,params:void 0,selection:void 0});case exports.CompleteActionType.ACCEPT_RESULT:return t.status!==exports.CompleteStatus.PREVIEW?t:Object.assign(Object.assign({},t),{status:exports.CompleteStatus.APPLYING});case exports.CompleteActionType.REJECT_RESULT:return t.status!==exports.CompleteStatus.PREVIEW?t:Object.assign(Object.assign({},I),{enabled:t.enabled});case exports.CompleteActionType.CANCEL_TASK:return Object.assign(Object.assign({},I),{enabled:t.enabled});case exports.CompleteActionType.CLEAR_ERROR:return Object.assign(Object.assign({},t),{error:void 0});default:return t}}(e,o):e.status===exports.CompleteStatus.APPLYING?Object.assign(Object.assign({},I),{enabled:e.enabled}):e}},view:()=>({update(e){const p=b.getState(e.state);if(p&&p.enabled){if(p.status===exports.CompleteStatus.PENDING&&!c){const{text:r,error:a}=function(t,e,o){const{taskType:s,selection:n}=e;if(s===exports.AiPromptsWithoutParam.Complete){const{doc:e}=t.state,o=[];return e.descendants((t=>{"paragraph"===t.type.name&&o.push(t.textContent)})),{text:o.length>=2?o.slice(-2).join(" "):o.join(" ")}}return n?t.state.doc.textBetween(n.from,n.to).length>o?{text:"",error:"Selection is too big"}:{text:t.state.doc.textBetween(n.from,n.to,"\n")}:{text:"",error:"No selection"}}(e,p,o);if(a)return void e.dispatch(e.state.tr.setMeta(b,{type:exports.CompleteActionType.STREAM_ERROR,error:a}));if(!r)return void e.dispatch(e.state.tr.setMeta(b,{type:exports.CompleteActionType.STREAM_ERROR,error:"No text to process"}));c=!0,function({view:t,pluginKey:e,apiKey:o,text:s,task:n,params:r,apiEndpoint:a,model:c}){return i.__awaiter(this,void 0,void 0,(function*(){R(t);const i=new AbortController;h.set(t,i);try{yield A({apiKey:o,text:s,task:n,params:r,endpoint:a,model:c,signal:i.signal},{onChunk:(o,s)=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.CompleteActionType.STREAM_UPDATE,result:s}))},onComplete:o=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.CompleteActionType.STREAM_COMPLETE,result:o}))},onError:o=>{console.error("Streaming request error:",o),t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.CompleteActionType.STREAM_ERROR,error:o.message}))}})}finally{h.delete(t)}}))}({view:e,pluginKey:b,apiKey:t,text:r,task:p.taskType,params:p.params,apiEndpoint:s,model:n}).finally((()=>{c=!1}))}p.status===exports.CompleteStatus.APPLYING&&function(t,e){const{taskType:o,selection:s,streamedResult:n}=e;if(!n)return;let{tr:i}=t.state;if(o===exports.AiPromptsWithoutParam.Complete)i=i.insertText(n,t.state.doc.nodeSize-2);else if(s){const e=n.split("\n\n").map((e=>t.state.schema.node("paragraph",null,e?t.state.schema.text(e):void 0))),o=r.Fragment.fromArray(e);i=i.setSelection(a.TextSelection.create(t.state.doc,s.from,s.to)),i.selection.replace(i,new r.Slice(o,0,0))}t.dispatch(i),t.focus()}(e,p)}},destroy(){}})})}const v={debounceMs:2e3,createUpdatePopup:(t,e,o,s,n)=>{const r=document.createElement("div");r.className="grammar-suggest-tooltip";const{spec:a}=e,i=t.dom.getBoundingClientRect();r.id=exports.GrammarSuggestElementClass.grammarSuggestPopup;const c=t.coordsAtPos(o),p=t.dom.scrollTop||0,u=t.dom.scrollLeft||0;r.style.left=`${c.left-i.left+u}px`,r.style.top=`${c.bottom-i.top+p+5}px`;const l=document.createElement("div");l.className="grammar-suggest-tooltip-apply",l.innerText=a.text||a.originalText,a.text||(l.style.textDecoration="line-through",l.style.color="red"),l.onclick=()=>{s(t,e)},r.appendChild(l);const d=document.createElement("div");return d.innerHTML="<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'><path d='M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z'></path></svg>",d.className="grammar-suggest-tooltip-discard",d.onclick=()=>{n(t,e)},r.appendChild(d),r},withYjs:!1},P=new a.PluginKey("completePlugin"),D=new a.PluginKey("grammarSuggestPlugin");var w,M,U;exports.RunnerStatus=void 0,(w=exports.RunnerStatus||(exports.RunnerStatus={})).IDLE="IDLE",w.ACTIVE="ACTIVE",exports.UnitStatus=void 0,(M=exports.UnitStatus||(exports.UnitStatus={})).DIRTY="DIRTY",M.WAITING="WAITING",M.QUEUED="QUEUED",M.PROCESSING="PROCESSING",M.DONE="DONE",M.BACKOFF="BACKOFF",M.ERROR="ERROR",exports.ActionType=void 0,(U=exports.ActionType||(exports.ActionType={})).INIT="INIT",U.FINISH="FINISH",U.CLEAR="CLEAR",U.RESUME="RESUME",U.UNIT_STARTED="UNIT_STARTED",U.UNIT_SUCCESS="UNIT_SUCCESS",U.UNIT_ERROR="UNIT_ERROR",U.UPDATE_CONTEXT="UPDATE_CONTEXT",U.REMOVE_DECORATION="REMOVE_DECORATION",U.SELECT_DECORATION="SELECT_DECORATION",U.DESELECT_DECORATION="DESELECT_DECORATION";const N={nodeTypes:"paragraph",priorityFilter:()=>!0,visibilityFilter:()=>!0,getGroupId:()=>"default",batchSize:4,maxRetries:3,backoffBase:1e3,dirtyHandling:{shouldRecalculate:!0,debounceDelay:2e3,skipDirtyOnSelfChange:!0},forceRerender:()=>{},onUpdate:void 0};function _(t){return Object.assign(Object.assign(Object.assign({},N),t),{dirtyHandling:Object.assign(Object.assign({},N.dirtyHandling),t.dirtyHandling)})}function L(t,e,o){const s=[];let n="",r=0;return t.nodesBetween(e,o,((t,a)=>{if(t.isText&&t.text){const i=Math.max(e,a),c=Math.min(o,a+t.nodeSize),p=t.text.slice(i-a,c-a);s.push({from:r,docPos:i}),n+=p,r+=p.length}else t.isBlock&&n.length>0&&(s.push({from:r,docPos:a}),n+="\n",r+=1)})),{text:n,mapping:s}}function j(t,e){var o,s;for(let o=e.length-1;o>=0;o--)if(e[o].from<=t)return e[o].docPos+(t-e[o].from);return null!==(s=null===(o=e[0])||void 0===o?void 0:o.docPos)&&void 0!==s?s:0}function k(t,e,o,s="paragraph"){const n=Array.isArray(s)?s:[s],r=[];return t.nodesBetween(e,o,((e,o)=>{if(n.includes(e.type.name)){const s=o+e.nodeSize,n=L(t,o,s);n.text.trim().length>0&&r.push(Object.assign({from:o,to:s},n))}})),r}const G=(t,e)=>t.map((t=>null==t?void 0:t.map(e,0,0))).filter((t=>null!==t)),K=(t,e)=>{const o=t.doc.content.findDiffStart(e.doc.content),s=e.doc.content.findDiffEnd(t.doc.content);if(!s||!o)return;let n=new u.StepMap([0,0,0]),r=o,a=s.a;return s&&o&&(s.a<o?(r=s.a,a=s.b,n=new u.StepMap([s.a,0,s.b-s.a])):s.b<o?(r=s.b,a=s.a,n=new u.StepMap([s.b,s.a-s.b,0])):n=new u.StepMap([o,s.a-o,s.b-o])),{end:a,mapping:new u.Mapping([n]),start:r}};function F(t,e,o,s,n=!1){var r;const a=K(e,o);if(!a)return t;const{start:i,end:c,mapping:p}=a,u=Array.isArray(s.nodeTypes)?s.nodeTypes:[s.nodeTypes],l=Date.now()+s.dirtyHandling.debounceDelay,d=null===(r=t.unitsInProgress)||void 0===r?void 0:r.slice().sort(((t,e)=>t.from-e.from));if(d){const o=[],s=p.map(d[0].from),r=p.map(d[d.length-1].to),a=k(e.doc,s,r,u);for(const t in d){const e=d[t],s=a[t];if(s){let{status:t}=e;!n&&s.from<=c&&s.to>=i&&(t=exports.UnitStatus.DIRTY),o.push(Object.assign(Object.assign(Object.assign({},e),{status:t,waitUntil:n?e.waitUntil:l}),s))}else o.push(Object.assign(Object.assign({},e),{status:exports.UnitStatus.DONE,from:r,to:r}))}return Object.assign(Object.assign({},t),{unitsInProgress:o,decorations:G(t.decorations,p)})}return Object.assign(Object.assign({},t),{decorations:G(t.decorations,p)})}function V(t,e){return 1e3*Math.pow(e/1e3,t)}function W(t){return new Promise((e=>setTimeout(e,t)))}function B(t,e,o){t.dispatch(t.state.tr.setMeta(e,o))}function H(t,e,o){if(e.status===exports.RunnerStatus.ACTIVE)return e.unitsInProgress.find((t=>t.id===o))}function q(t,e,o){const s=t.unitsInProgress.map((t=>t.id===e?Object.assign(Object.assign({},t),o):t));return"waitUntil"in o&&s.sort(((t,e)=>t.waitUntil-e.waitUntil)),Object.assign(Object.assign({},t),{unitsInProgress:s})}function $(t,e,o,s,n="paragraph"){return k(t,e,o,n).map(((t,e)=>({id:{},status:exports.UnitStatus.QUEUED,from:t.from,to:t.to,text:t.text,mapping:t.mapping,metadata:s(t,e),retryCount:0,waitUntil:0})))}function Q(t,e,o,s){var n;switch(e.type){case exports.ActionType.INIT:return function(t,e,o,s){const n=$(o,e.onlySelection?s.from:0,e.onlySelection?s.to:o.content.size,((t,o)=>{var s;if(void 0!==e.metadata.single)return e.metadata.single;if(void 0!==e.metadata.array)return null!==(s=e.metadata.array[o])&&void 0!==s?s:e.metadata.array[0];if(void 0!==e.metadata.factory){const o={id:{},status:exports.UnitStatus.QUEUED,from:t.from,to:t.to,text:t.text,mapping:[],metadata:{},retryCount:0,waitUntil:0};return e.metadata.factory(o)}return{}})).map((e=>Object.assign(Object.assign({},e),{status:t.options.priorityFilter(e,t.contextState)?exports.UnitStatus.QUEUED:exports.UnitStatus.WAITING})));return Object.assign(Object.assign({},t),{status:exports.RunnerStatus.ACTIVE,unitsInProgress:n})}(t,e,s.doc,s.selection);case exports.ActionType.UNIT_STARTED:return t.status!==exports.RunnerStatus.ACTIVE?t:function(t,e){const o=t.unitsInProgress.find((t=>t.id===e));return o?q(t,e,{status:exports.UnitStatus.PROCESSING,requestText:o.text}):t}(t,e.unitId);case exports.ActionType.UNIT_SUCCESS:return t.status!==exports.RunnerStatus.ACTIVE?t:function(t,e,o){const s=t.unitsInProgress.find((t=>t.id===e.unitId));if(!s)return t;const n=Date.now()+t.options.dirtyHandling.debounceDelay;if(void 0!==s.requestText&&s.requestText!==s.text)return q(t,e.unitId,{status:exports.UnitStatus.DIRTY,requestText:void 0,waitUntil:n});const r=o(e.response,s),a=q(t,e.unitId,{status:exports.UnitStatus.DONE,response:e.response,requestText:void 0});return Object.assign(Object.assign({},a),{decorations:[...a.decorations,...r]})}(t,e,o);case exports.ActionType.UNIT_ERROR:return t.status!==exports.RunnerStatus.ACTIVE?t:function(t,e){const o=t.unitsInProgress.find((t=>t.id===e.unitId));if(!o)return t;const s=Date.now()+t.options.dirtyHandling.debounceDelay;if(void 0!==o.requestText&&o.requestText!==o.text)return q(t,e.unitId,{status:exports.UnitStatus.DIRTY,requestText:void 0,waitUntil:s});const n=o.retryCount+1;return n>=t.options.maxRetries?q(t,e.unitId,{status:exports.UnitStatus.ERROR,retryCount:n,requestText:void 0}):q(t,e.unitId,{status:exports.UnitStatus.BACKOFF,retryCount:n,waitUntil:Date.now()+V(n,t.options.backoffBase),requestText:void 0})}(t,e);case exports.ActionType.FINISH:return Object.assign(Object.assign({},t),{status:exports.RunnerStatus.IDLE});case exports.ActionType.CLEAR:return Object.assign(Object.assign({},t),{decorations:[],unitsInProgress:void 0,status:exports.RunnerStatus.IDLE,selected:void 0});case exports.ActionType.RESUME:return t.status!==exports.RunnerStatus.IDLE?t:(null===(n=t.unitsInProgress)||void 0===n?void 0:n.length)?Object.assign(Object.assign({},t),{status:exports.RunnerStatus.ACTIVE}):t;case exports.ActionType.UPDATE_CONTEXT:return Object.assign(Object.assign({},t),{contextState:e.contextState});case exports.ActionType.REMOVE_DECORATION:return Object.assign(Object.assign({},t),{decorations:t.decorations.filter((t=>t.spec.id!==e.id))});case exports.ActionType.SELECT_DECORATION:return Object.assign(Object.assign({},t),{selected:e.id});case exports.ActionType.DESELECT_DECORATION:return Object.assign(Object.assign({},t),{selected:void 0});default:return t}}function Y(t,e){return{status:exports.RunnerStatus.IDLE,decorations:[],selected:void 0,contextState:t,options:e}}function z(t,e,o,s){return i.__awaiter(this,void 0,void 0,(function*(){const n=t.getState(e.state);if(!n||n.status!==exports.RunnerStatus.ACTIVE)return!1;const r=function(t,e){var o;if(t.status!==exports.RunnerStatus.ACTIVE)return;const s=Date.now(),n=null!==(o=t.unitsInProgress)&&void 0!==o?o:[],r=t=>[exports.UnitStatus.QUEUED,exports.UnitStatus.BACKOFF,exports.UnitStatus.DIRTY].includes(t.status)&&t.waitUntil<=s,a=n.find((o=>r(o)&&e.priorityFilter(o,t.contextState)));if(a)return a;const i=n.find(r);if(i)return i;return n.find((t=>[exports.UnitStatus.QUEUED,exports.UnitStatus.BACKOFF,exports.UnitStatus.DIRTY].includes(t.status)&&t.waitUntil>s))||void 0}(n,s);if(!r)return!1;B(e,t,{type:exports.ActionType.UNIT_STARTED,unitId:r.id});const a=t.getState(e.state);if(!a)return!1;const i=H(0,a,r.id);if(i&&i.waitUntil>Date.now()){yield W(i.waitUntil-Date.now());const o=t.getState(e.state);if(!o||o.status!==exports.RunnerStatus.ACTIVE)return!1}try{const s=yield o(e,r);s.error?B(e,t,{type:exports.ActionType.UNIT_ERROR,unitId:r.id,error:s.error}):void 0!==s.data&&B(e,t,{type:exports.ActionType.UNIT_SUCCESS,unitId:r.id,response:s.data})}catch(o){B(e,t,{type:exports.ActionType.UNIT_ERROR,unitId:r.id,error:o instanceof Error?o:new Error(String(o))})}return!0}))}function J(t,e,o,s){return i.__awaiter(this,void 0,void 0,(function*(){return!!(yield z(t,e,o,s))&&J(t,e,o,s)}))}function X(t,e,o,s){return i.__awaiter(this,void 0,void 0,(function*(){const n=Array.from({length:s.batchSize},(()=>J(t,e,o,s)));yield Promise.all(n)}))}function Z(t){return t.status===exports.RunnerStatus.ACTIVE&&t.unitsInProgress.some((t=>t.status===exports.UnitStatus.QUEUED||t.status===exports.UnitStatus.WAITING||t.status===exports.UnitStatus.BACKOFF||t.status===exports.UnitStatus.DIRTY||t.status===exports.UnitStatus.PROCESSING))}function tt(t){const{pluginKey:e,unitProcessor:o,decorationFactory:s,decorationTransformer:n,widgetFactory:r,initialContextState:i,options:c,handleKeyDown:p}=t,u=_(null!=c?c:{});let d=!1;return new a.Plugin({key:e,state:{init:()=>Y(i,u),apply(t,o,n,r){const a=t.getMeta(e),i=t.docChanged&&void 0!==a&&u.dirtyHandling.skipDirtyOnSelfChange;let c=o;if(t.docChanged&&(c=F(o,t,n,u,i)),a){const t=Q(c,a,s,r);return u.onUpdate&&u.onUpdate(t),t}return c}},props:{decorations(t){const o=e.getState(t);if(!o)return l.DecorationSet.empty;console.log("decorations",o.decorations.length);let s=o.decorations.filter((t=>u.visibilityFilter(t,o.contextState)));console.log("decorations VF",s.length),n&&(s=n(s,o)),console.log("after transformer",s.length);const a=[];if(r&&o.unitsInProgress)for(const t of o.unitsInProgress)if(t.status!==exports.UnitStatus.DONE&&t.status!==exports.UnitStatus.ERROR){const e=r(t);e&&a.push(e)}return l.DecorationSet.create(t.doc,[...s,...a])},handleKeyDown:p},view:()=>({update(t){const s=e.getState(t.state);s&&s.status===exports.RunnerStatus.ACTIVE&&!d&&Z(s)&&(d=!0,X(e,t,o,u).finally((()=>{d=!1;const o=e.getState(t.state);!o||o.status!==exports.RunnerStatus.ACTIVE||Z(o)||u.dirtyHandling.shouldRecalculate||B(t,e,{type:exports.ActionType.FINISH})})))}})})}function et(t){return new a.PluginKey(t)}const ot=(t,e)=>t.map((o=>{const s=j(o.from,e.mapping),n=j(o.to,e.mapping);return l.Decoration.inline(s,n,{class:"link-detected",style:"color: #0066cc; text-decoration: underline; cursor: pointer;"},{id:{},unitId:e.id,originalText:o.url,response:t,url:o.url})})),st=/https?:\/\/[^\s<>"')\]]+/g;const nt=(t,e)=>i.__awaiter(void 0,void 0,void 0,(function*(){return{data:function(t){const e=[];let o=st.exec(t);for(;null!==o;)e.push({url:o[0],from:o.index,to:o.index+o[0].length}),o=st.exec(t);return e}(e.text)}})),rt=et("linkDetector");const at={moderate:{class:"word-complexity-moderate",style:"background-color: rgba(255, 193, 7, 0.3); border-radius: 2px;"},high:{class:"word-complexity-high",style:"background-color: rgba(244, 67, 54, 0.3); border-radius: 2px;"}},it=(t,e)=>t.map((o=>{const s=j(o.from,e.mapping),n=j(o.to,e.mapping),r=at[o.complexity];return l.Decoration.inline(s,n,{class:r.class,style:r.style},{id:{},unitId:e.id,originalText:o.word,response:t,syllables:o.syllables,complexity:o.complexity})}));function ct(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");if(e.length<=3)return 1;e=e.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/,""),e=e.replace(/^y/,"");const o=e.match(/[aeiouy]{1,2}/g);return o?Math.max(1,o.length):1}const pt=/[a-zA-Z]+/g;function ut(t,e,o){const s=[];let n=pt.exec(t);for(;null!==n;){const r=n[0],a=ct(r);a>=e&&s.push({word:r,from:n.index,to:n.index+r.length,syllables:a,complexity:a>=o?"high":"moderate"}),n=pt.exec(t)}return s}const lt=(t,e)=>i.__awaiter(void 0,void 0,void 0,(function*(){return{data:ut(e.text,3,4)}})),dt={moderateThreshold:3,highThreshold:4},mt=et("wordComplexity");const gt={warning:{class:"sentence-too-long-warning",style:"background-color: rgba(255, 152, 0, 0.2); border-radius: 2px;"},error:{class:"sentence-too-long-error",style:"background-color: rgba(244, 67, 54, 0.2); border-radius: 2px;"}},xt=(t,e)=>t.map((o=>{const s=j(o.from,e.mapping),n=j(o.to,e.mapping),r=gt[o.severity];return l.Decoration.inline(s,n,{class:r.class,style:r.style},{id:{},unitId:e.id,originalText:e.text.slice(o.from,o.to),response:t,wordCount:o.wordCount,severity:o.severity})})),St=/[^.!?]*[.!?]+/g,Et=/\b\w+\b/g;function Tt(t){const e=t.match(Et);return e?e.length:0}function ft(t,e,o){const s=[];let n=St.exec(t);for(;null!==n;){const r=n[0],a=Tt(r);a>=e&&s.push({from:n.index,to:n.index+r.length,wordCount:a,severity:a>=o?"error":"warning"}),n=St.exec(t)}return s}const yt=(t,e)=>i.__awaiter(void 0,void 0,void 0,(function*(){return{data:ft(e.text,25,40)}})),At={warningThreshold:25,errorThreshold:40},Ct=et("sentenceLength");const ht=(t,e)=>[l.Decoration.inline(e.from+1,e.to-1,{class:"random-processor-success",style:"background-color: rgba(76, 175, 80, 0.2); border-radius: 2px;"},{id:{},unitId:e.id,originalText:e.text,response:t,processingTime:t.processingTime})],Rt=t=>{let e,o;const s=Math.max(0,t.waitUntil-Date.now());switch(t.status){case exports.UnitStatus.QUEUED:e="⏳ Queued...",o="random-processor-widget queued";break;case exports.UnitStatus.PROCESSING:e="⚙️ Processing...",o="random-processor-widget processing";break;case exports.UnitStatus.BACKOFF:e=`🔄 Retry in ${Math.ceil(s/1e3)}s (attempt ${t.retryCount+1})`,o="random-processor-widget backoff";break;case exports.UnitStatus.ERROR:e=`❌ Failed after ${t.retryCount} retries`,o="random-processor-widget error";break;case exports.UnitStatus.DIRTY:e="⚠️ Changed",o="random-processor-widget dirty";break;case exports.UnitStatus.WAITING:e="⏸️ Waiting...",o="random-processor-widget waiting";break;default:return}let n,r;switch(t.status){case exports.UnitStatus.ERROR:n="#ffebee",r="#c62828";break;case exports.UnitStatus.DIRTY:n="#fff9c4",r="#f57f17";break;case exports.UnitStatus.BACKOFF:n="#fff3e0",r="#e65100";break;default:n="#e3f2fd",r="#1565c0"}const a=document.createElement("span");return a.className=o,a.textContent=e,a.style.cssText=`\n display: inline-block;\n padding: 2px 8px;\n margin-right: 8px;\n font-size: 12px;\n border-radius: 4px;\n background: ${n};\n color: ${r};\n `,l.Decoration.widget(t.from+1,a,{side:-1})};function bt(t,e){return Math.floor(Math.random()*(e-t+1))+t}function It(t){return new Promise((e=>setTimeout(e,t)))}const Ot=(t,e)=>i.__awaiter(void 0,void 0,void 0,(function*(){const t=bt(500,3e3);yield It(t);return Math.random()<.3?{error:new Error(`Random error after ${t}ms (attempt ${e.metadata.attempt})`)}:{data:{processingTime:t,success:!0,message:`Processed "${e.text.slice(0,20)}..." in ${t}ms`}}})),vt={minDelay:500,maxDelay:3e3,errorRate:.3},Pt=et("randomProcessor");const Dt=(t,e)=>t.fixed&&0!==t.suggestions.length?t.suggestions.map((o=>{const s=j(o.from,e.mapping),n=j(o.to,e.mapping),r=""===o.replacement,a={id:{},unitId:e.id,originalText:o.original,replacement:o.replacement,response:t};return l.Decoration.inline(s,n,{class:"grammarSuggestionV2 "+(r?"removalSuggestionV2":"")},a)})):[],wt=(t,e)=>{const o=e.contextState.selectedSuggestionId;return o?t.map((t=>{const e=t.spec;return e.id===o?l.Decoration.inline(t.from,t.to,{class:"grammarSuggestionV2 grammarSuggestionV2-selected"},e):t})):t},Mt=t=>{let e,o;const s=Math.max(0,t.waitUntil-Date.now());switch(t.status){case exports.UnitStatus.QUEUED:case exports.UnitStatus.WAITING:e="⏳",o="grammarWidgetV2 queued";break;case exports.UnitStatus.PROCESSING:e="🔍",o="grammarWidgetV2 processing";break;case exports.UnitStatus.BACKOFF:e=`🔄 ${Math.ceil(s/1e3)}s`,o="grammarWidgetV2 backoff";break;case exports.UnitStatus.ERROR:e="❌",o="grammarWidgetV2 error";break;case exports.UnitStatus.DIRTY:e="✏️",o="grammarWidgetV2 dirty";break;default:return}const n=document.createElement("span");return n.className=o,n.textContent=e,l.Decoration.widget(t.from+1,n,{side:-1})};const Ut=t=>{const{apiKey:e,apiEndpoint:o,model:s,modelStateManager:n}="string"==typeof t?{apiKey:t,apiEndpoint:void 0,model:void 0,modelStateManager:void 0}:t;return(t,r)=>i.__awaiter(void 0,void 0,void 0,(function*(){var t,a,i;try{const c=null!==(t=null==n?void 0:n.getCurrentModel())&&void 0!==t?t:s,u=yield C({apiKey:e,text:r.text,endpoint:o,model:c});if(u.error?null==n||n.handleFailure():null==n||n.handleSuccess(),!u.fixed)return{data:{fixed:!1,originalText:r.text,fixedText:r.text,suggestions:[]}};const l=(a=r.text,i=u.result,p.getDiff(a,i).filter((t=>!p.isIdentity(t))).filter((t=>t.original!==`${t.replacement}\n`)).map((t=>({from:t.from,to:t.replacement.endsWith("\n")?t.to-1:t.to,original:t.original,replacement:t.replacement.endsWith("\n")?t.replacement.slice(0,-1):t.replacement}))));return{data:{fixed:l.length>0,originalText:r.text,fixedText:u.result,suggestions:l}}}catch(t){return null==n||n.handleFailure(),{error:t instanceof Error?t:new Error(String(t))}}}))};function Nt(t,e,o){const s=e.getState(t.state);if(s)return s.decorations.find((t=>t.spec.id===o))}function _t(t,e,o){const s=Nt(t,e,o);if(!s)return;const n=s.spec,{replacement:i}=n,{from:c,to:p}=s,u=i.split("\n").map((e=>e?t.state.schema.node("paragraph",null,t.state.schema.text(e)):t.state.schema.node("paragraph"))),l=r.Fragment.fromArray(u);let{tr:d}=t.state;d=d.setSelection(a.TextSelection.create(t.state.doc,c,p)),d.selection.replace(d,new r.Slice(l,1,1)),d=d.setMeta(e,{type:exports.ActionType.REMOVE_DECORATION,id:o}),t.dispatch(d)}function Lt(t,e,o){B(t,e,{type:exports.ActionType.REMOVE_DECORATION,id:o})}function jt(t,e,o){B(t,e,{type:exports.ActionType.UPDATE_CONTEXT,contextState:{selectedSuggestionId:o}})}function kt(t,e){B(t,e,{type:exports.ActionType.UPDATE_CONTEXT,contextState:{selectedSuggestionId:void 0}})}function Gt(t,e,o,s){var n,r,a;return i.__awaiter(this,void 0,void 0,(function*(){const i=null!==(n=null==s?void 0:s.endpoint)&&void 0!==n?n:T,c=null==s?void 0:s.modelStateManager,p=null!==(a=null!==(r=null==c?void 0:c.getCurrentModel())&&void 0!==r?r:null==s?void 0:s.model)&&void 0!==a?a:y;return new Promise(((s,n)=>{const r={previousPromptType:"Grammar",oldVersion:e,newVersion:o};A({apiKey:t,text:e,task:exports.AiPromptsWithParam.Hint,params:r,endpoint:i,model:p},{onChunk:()=>{},onComplete:t=>{null==c||c.handleSuccess(),s(t)},onError:t=>{null==c||c.handleFailure(),n(t)}})}))}))}const Kt={selectedSuggestionId:void 0},Ft=et("grammarSuggestV2"),Vt=(t,e,o,s,n,r)=>{const a=e.spec,c=document.createElement("div");c.className="grammarPopupV2";const p=document.createElement("div");p.className="grammarPopupV2-mainRow";const u=document.createElement("span");u.className="grammarPopupV2-original",u.textContent=`"${a.originalText}"`;const l=document.createElement("span");l.className="grammarPopupV2-arrow",l.textContent=" → ";const d=document.createElement("span");d.className="grammarPopupV2-replacement",d.textContent=""===a.replacement?"(remove)":`"${a.replacement}"`;const m=document.createElement("button");m.className="grammarPopupV2-hint",m.textContent="?",m.title="Why this suggestion?";const g=document.createElement("div");g.className="grammarPopupV2-hintArea",g.style.display="none";let x=!1;m.onclick=t=>i.__awaiter(void 0,void 0,void 0,(function*(){if(t.preventDefault(),t.stopPropagation(),"none"===g.style.display){if(g.style.display="block",!x){g.innerHTML='<span class="grammarPopupV2-loading">Loading...</span>';try{const t=yield r();g.innerHTML="";const e=document.createElement("span");e.className="grammarPopupV2-hintText",e.textContent=t,g.appendChild(e),x=!0}catch(t){g.innerHTML='<span class="grammarPopupV2-hintError">Could not load hint</span>'}}}else g.style.display="none"}));const S=document.createElement("button");S.className="grammarPopupV2-accept",S.textContent="✓",S.onclick=t=>{t.preventDefault(),t.stopPropagation(),s()};const E=document.createElement("button");return E.className="grammarPopupV2-discard",E.textContent="✕",E.onclick=t=>{t.preventDefault(),t.stopPropagation(),n()},p.appendChild(u),p.appendChild(l),p.appendChild(d),p.appendChild(m),p.appendChild(S),p.appendChild(E),c.appendChild(p),c.appendChild(g),c};var Wt,Bt;exports.AutoCompleteStatus=void 0,(Wt=exports.AutoCompleteStatus||(exports.AutoCompleteStatus={})).IDLE="idle",Wt.DEBOUNCING="debouncing",Wt.PENDING="pending",Wt.STREAMING="streaming",Wt.SHOWING="showing",exports.AutoCompleteActionType=void 0,(Bt=exports.AutoCompleteActionType||(exports.AutoCompleteActionType={})).SET_ENABLED="SET_ENABLED",Bt.START_DEBOUNCE="START_DEBOUNCE",Bt.START_REQUEST="START_REQUEST",Bt.STREAM_UPDATE="STREAM_UPDATE",Bt.STREAM_COMPLETE="STREAM_COMPLETE",Bt.STREAM_ERROR="STREAM_ERROR",Bt.DISMISS="DISMISS",Bt.ACCEPT="ACCEPT";const Ht={debounceMs:500,maxContextLength:2e3,ghostTextClass:"autoCompleteGhostText"},qt=new WeakMap;function $t(t){const e=qt.get(t);e&&(e.abort(),qt.delete(t))}function Qt(t,e){if(!e)return e;const{doc:o,selection:s}=t.state,n=s.from;if(n<=0)return e;const r=o.textBetween(n-1,n,""),a=e.charAt(0),i=/[\s\-]/;return!i.test(r)&&!i.test(a)?` ${e}`:e}const Yt=new a.PluginKey("autoCompletePlugin"),zt={status:exports.AutoCompleteStatus.IDLE,enabled:!0,suggestion:"",cursorPos:0};function Jt(t,e){switch(e.type){case exports.AutoCompleteActionType.SET_ENABLED:return Object.assign(Object.assign({},zt),{enabled:e.enabled});case exports.AutoCompleteActionType.START_DEBOUNCE:return Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.DEBOUNCING,cursorPos:e.cursorPos,suggestion:"",error:void 0});case exports.AutoCompleteActionType.START_REQUEST:return t.status!==exports.AutoCompleteStatus.DEBOUNCING?t:Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.PENDING});case exports.AutoCompleteActionType.STREAM_UPDATE:return t.status!==exports.AutoCompleteStatus.PENDING&&t.status!==exports.AutoCompleteStatus.STREAMING?t:Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.STREAMING,suggestion:e.suggestion});case exports.AutoCompleteActionType.STREAM_COMPLETE:return t.status!==exports.AutoCompleteStatus.PENDING&&t.status!==exports.AutoCompleteStatus.STREAMING?t:Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.SHOWING,suggestion:e.suggestion});case exports.AutoCompleteActionType.STREAM_ERROR:return Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.IDLE,error:e.error,suggestion:""});case exports.AutoCompleteActionType.DISMISS:case exports.AutoCompleteActionType.ACCEPT:return Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.IDLE,suggestion:""});default:return t}}const Xt=O;Object.defineProperty(exports,"getDiff",{enumerable:!0,get:function(){return p.getDiff}}),exports.DEFAULT_COMPLETION_ENDPOINT=T,exports.DEFAULT_GRAMMAR_ENDPOINT=f,exports.DEFAULT_MODEL=y,exports.OpenAiPromptsWithParam=m,exports.OpenAiPromptsWithoutParam=d,exports.acceptAutoCompletion=function(t){const e=Yt.getState(t.state);if(!e||!e.suggestion)return!1;const o=t.state.tr.insertText(e.suggestion,e.cursorPos);return t.dispatch(o),t.dispatch(t.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.DISMISS})),t.focus(),!0},exports.acceptResult=function(t){t.dispatch(t.state.tr.setMeta(b,{type:exports.CompleteActionType.ACCEPT_RESULT}))},exports.acceptSuggestion=_t,exports.allUnitsFinished=function(t){return t.every((t=>t.status===exports.UnitStatus.DONE||t.status===exports.UnitStatus.ERROR))},exports.autoCompleteKey=Yt,exports.autoCompletePlugin=function(t,e={}){const o=Object.assign(Object.assign({},Ht),e),{debounceMs:s,maxContextLength:n,apiEndpoint:r,model:c,ghostTextClass:p}=o;let u=null,d=!1,m=null,g=null;return new a.Plugin({key:Yt,state:{init:()=>Object.assign({},zt),apply(t,e,o,s){const n=t.getMeta(Yt);if(n)return Jt(e,n);if(t.docChanged&&(e.status===exports.AutoCompleteStatus.SHOWING||e.status===exports.AutoCompleteStatus.STREAMING)){if(s.selection.from!==e.cursorPos)return Jt(e,{type:exports.AutoCompleteActionType.DISMISS})}return!t.selectionSet||t.docChanged||e.status!==exports.AutoCompleteStatus.SHOWING&&e.status!==exports.AutoCompleteStatus.STREAMING?e:Jt(e,{type:exports.AutoCompleteActionType.DISMISS})}},props:{decorations(t){const e=Yt.getState(t);if(!e||!e.enabled)return l.DecorationSet.empty;if((e.status===exports.AutoCompleteStatus.STREAMING||e.status===exports.AutoCompleteStatus.SHOWING)&&e.suggestion){const o=document.createElement("span");o.className=p,o.textContent=e.suggestion,o.setAttribute("contenteditable","false");const s=l.Decoration.widget(e.cursorPos,o,{side:1});return l.DecorationSet.create(t.doc,[s])}return l.DecorationSet.empty},handleKeyDown(t,e){const o=Yt.getState(t.state);return!(!o||!o.enabled)&&("Tab"===e.key&&!e.shiftKey&&o.status===exports.AutoCompleteStatus.SHOWING&&o.suggestion?(e.preventDefault(),m=o.suggestion,g=o.cursorPos,t.dispatch(t.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.ACCEPT})),!0):"Escape"===e.key&&(o.status===exports.AutoCompleteStatus.STREAMING||o.status===exports.AutoCompleteStatus.SHOWING)&&(e.preventDefault(),$t(t),t.dispatch(t.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.DISMISS})),!0))}},view:()=>({update(e,o){const a=Yt.getState(e.state),p=Yt.getState(o);if(a&&a.enabled){if(null!==m&&null!==g){const t=m,o=g;m=null,g=null;const s=e.state.tr.insertText(t,o);return e.dispatch(s),void e.focus()}if(e.state,e.state.doc!==o.doc&&(null==p?void 0:p.status)!==exports.AutoCompleteStatus.PENDING&&(null==p?void 0:p.status)!==exports.AutoCompleteStatus.STREAMING){e.state.tr,u&&(clearTimeout(u),u=null),$t(e);const t=e.state.selection.from;e.dispatch(e.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.START_DEBOUNCE,cursorPos:t})),u=setTimeout((()=>{u=null;const t=Yt.getState(e.state);(null==t?void 0:t.status)===exports.AutoCompleteStatus.DEBOUNCING&&e.dispatch(e.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.START_REQUEST}))}),s)}if(a.status===exports.AutoCompleteStatus.PENDING&&!d){if(!function(t){const{doc:e,selection:o}=t.state,s=o.from,n=e.resolve(s),r=n.parent,a=n.start();if(s!==a+r.content.size)return!1;const i=r.textBetween(0,s-a,"");return!!i.trim()&&!/[.!?]\s*$/.test(i)}(e))return void e.dispatch(e.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.DISMISS}));const o=function(t,e){const{doc:o,selection:s}=t.state,n=s.from,r=o.textBetween(0,n,"\n");return r.length>e?r.slice(-e):r}(e,n);if(!o.trim())return void e.dispatch(e.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.DISMISS}));d=!0,function({view:t,pluginKey:e,apiKey:o,context:s,apiEndpoint:n,model:r}){return i.__awaiter(this,void 0,void 0,(function*(){$t(t);const a=new AbortController;qt.set(t,a);try{yield A({apiKey:o,text:s,task:exports.AiPromptsWithoutParam.SmallComplete,endpoint:n,model:r,signal:a.signal},{onChunk:(o,s)=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.AutoCompleteActionType.STREAM_UPDATE,suggestion:Qt(t,s)}))},onComplete:o=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.AutoCompleteActionType.STREAM_COMPLETE,suggestion:Qt(t,o)}))},onError:o=>{console.error("Auto-complete streaming error:",o),t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.AutoCompleteActionType.STREAM_ERROR,error:o.message}))}})}finally{qt.delete(t)}}))}({view:e,pluginKey:Yt,apiKey:t,context:o,apiEndpoint:r,model:c}).finally((()=>{d=!1}))}}else u&&(clearTimeout(u),u=null)},destroy(){u&&(clearTimeout(u),u=null)}})})},exports.blockRunnerPlugin=tt,exports.calculateBackoff=V,exports.canResume=function(t){var e;return t.status===exports.RunnerStatus.IDLE&&!!(null===(e=t.unitsInProgress)||void 0===e?void 0:e.some((t=>t.status!==exports.UnitStatus.DONE&&t.status!==exports.UnitStatus.ERROR)))},exports.cancelActiveRequest=R,exports.cancelAutoCompleteRequest=$t,exports.cancelTask=function(t){R(t),t.dispatch(t.state.tr.setMeta(b,{type:exports.CompleteActionType.CANCEL_TASK}))},exports.clearError=function(t){t.dispatch(t.state.tr.setMeta(b,{type:exports.CompleteActionType.CLEAR_ERROR}))},exports.completePlugin=Xt,exports.completePluginKey=P,exports.completePluginV2=O,exports.completeV2Key=b,exports.countSyllables=ct,exports.createApiConfig=function(t){var e,o;return{apiKey:t.apiKey,endpoint:null!==(e=t.endpoint)&&void 0!==e?e:T,model:null!==(o=t.model)&&void 0!==o?o:y}},exports.createBlockRunnerKey=et,exports.createGrammarApiConfig=function(t){var e,o;return{apiKey:t.apiKey,endpoint:null!==(e=t.endpoint)&&void 0!==e?e:f,model:null!==(o=t.model)&&void 0!==o?o:y}},exports.createGrammarProcessor=Ut,exports.createInitialState=Y,exports.createLinkDetectorPlugin=function(){const t=tt({pluginKey:rt,unitProcessor:nt,decorationFactory:ot,initialContextState:{}});return new a.Plugin({key:rt,state:t.spec.state,props:Object.assign(Object.assign({},t.spec.props),{handleDOMEvents:{click:(t,e)=>{const o=e.target;if(o.classList.contains("link-detected")){const s=t.posAtDOM(o,0),n=rt.getState(t.state);if(n){const t=n.decorations.find((t=>t.from<=s&&t.to>=s&&t.spec.url));if(null==t?void 0:t.spec.url)return window.open(t.spec.url,"_blank"),e.preventDefault(),!0}}return!1}}}),view:t.spec.view})},exports.createRandomProcessor=t=>(e,o)=>i.__awaiter(void 0,void 0,void 0,(function*(){var e,s,n;const r=t(),a=null!==(e=r.minDelay)&&void 0!==e?e:500,i=null!==(s=r.maxDelay)&&void 0!==s?s:3e3,c=null!==(n=r.errorRate)&&void 0!==n?n:.3,p=bt(a,i);yield It(p);return Math.random()<c?{error:new Error(`Random error after ${p}ms (attempt ${o.metadata.attempt})`)}:{data:{processingTime:p,success:!0,message:`Processed "${o.text.slice(0,20)}..." in ${p}ms`}}})),exports.createRandomProcessorPlugin=function(t={}){return tt({pluginKey:Pt,unitProcessor:Ot,decorationFactory:ht,widgetFactory:Rt,initialContextState:Object.assign(Object.assign({},vt),t),options:{batchSize:2,maxRetries:3,backoffBase:2e3}})},exports.createSentenceLengthPlugin=function(t={}){return tt({pluginKey:Ct,unitProcessor:yt,decorationFactory:xt,initialContextState:Object.assign(Object.assign({},At),t)})},exports.createSentenceLengthProcessor=t=>(e,o)=>i.__awaiter(void 0,void 0,void 0,(function*(){var e,s;const n=t(),r=null!==(e=n.warningThreshold)&&void 0!==e?e:25,a=null!==(s=n.errorThreshold)&&void 0!==s?s:40;return{data:ft(o.text,r,a)}})),exports.createUnitsFromDocument=$,exports.createWordComplexityPlugin=function(t={}){return tt({pluginKey:mt,unitProcessor:lt,decorationFactory:it,initialContextState:Object.assign(Object.assign({},dt),t)})},exports.createWordComplexityProcessor=t=>(e,o)=>i.__awaiter(void 0,void 0,void 0,(function*(){var e,s;const n=t(),r=null!==(e=n.moderateThreshold)&&void 0!==e?e:3,a=null!==(s=n.highThreshold)&&void 0!==s?s:4;return{data:ut(o.text,r,a)}})),exports.defaultAutoCompleteOptions=Ht,exports.defaultCompleteOptions={maxSelection:1e3},exports.defaultCompleteV2Options=E,exports.defaultOptions=v,exports.defaultRunnerOptions=N,exports.deselectSuggestion=kt,exports.discardSuggestion=Lt,exports.dismissAutoCompletion=function(t){$t(t),t.dispatch(t.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.DISMISS}))},exports.dispatchAction=B,exports.executeParallel=X,exports.extractTextWithMapping=L,exports.getAutoCompleteState=function(t){return Yt.getState(t.state)},exports.getChangedRegions=(t,e)=>{if(t===e)return{start:t.length,end:t.length,oldStart:t.length,oldEnd:t.length,oldText:"",newText:""};const o=c(t,e),s=o[0],n=s[0]===c.EQUAL?s[1].length-1:0,r=((t,e)=>{if(e[e.length-1][0]!==c.EQUAL)return t.length;const o=e.slice(0,e.length-1);let s=0;for(const t of o){const[e,o]=t;e===c.EQUAL&&(s+=o.length),e===c.DELETE&&(s+=o.length)}return s})(t,o),a=t.lastIndexOf("\n",n),i=t.indexOf("\n",r),p=-1===a?0:a+1,u=-1===i?t.length:i,l=t.slice(p,u),d=e.slice(p,e.length-(t.length-u));return{start:p,end:p+d.length,oldStart:p,oldEnd:u,oldText:l,newText:d}},exports.getCompleteState=function(t){return b.getState(t.state)},exports.getProgress=function(t){var e;if(t.status!==exports.RunnerStatus.ACTIVE)return{completed:0,total:0,decorations:t.decorations.length};const o=null!==(e=t.unitsInProgress)&&void 0!==e?e:[];return{completed:o.filter((t=>t.status===exports.UnitStatus.DONE||t.status===exports.UnitStatus.ERROR)).length,total:o.length,decorations:t.decorations.length}},exports.getSelectedDecoration=function(t,e){const o=e.getState(t.state);if(null==o?void 0:o.contextState.selectedSuggestionId)return Nt(t,e,o.contextState.selectedSuggestionId)},exports.getUnitById=H,exports.getUnitsInRange=k,exports.grammarDecorationFactory=Dt,exports.grammarDecorationTransformer=wt,exports.grammarRequest=C,exports.grammarSuggestPluginKey=D,exports.grammarSuggestPluginV2=function(t,e={}){var o;const{apiEndpoint:s,model:n,fallback:r,batchSize:i=4,maxRetries:c=3,backoffBase:p=2e3,debounceMs:u=1e3,createPopup:d=Vt}=e,m=r?function(t){const{primaryModel:e,fallbackModel:o,failureThreshold:s}=t;let n=0;return{getCurrentModel:()=>o&&s>0&&n>=s?o:e,handleSuccess(){n=0},handleFailure(){o&&n++}}}({primaryModel:n,fallbackModel:r.fallbackModel,failureThreshold:null!==(o=r.failureThreshold)&&void 0!==o?o:3}):void 0,g=Ut({apiKey:t,apiEndpoint:s,model:n,modelStateManager:m}),x=tt({pluginKey:Ft,unitProcessor:g,decorationFactory:Dt,decorationTransformer:wt,widgetFactory:Mt,initialContextState:Kt,options:{batchSize:i,maxRetries:c,backoffBase:p,dirtyHandling:{debounceDelay:u}}});return new a.Plugin({key:Ft,state:x.spec.state,props:Object.assign(Object.assign({},x.spec.props),{decorations(e){var o;const r=null===(o=x.spec.props)||void 0===o?void 0:o.decorations,a=r?r.call(x,e):l.DecorationSet.empty,i=Ft.getState(e);if(!(null==i?void 0:i.contextState.selectedSuggestionId))return a;const c=i.decorations.find((t=>t.spec.id===i.contextState.selectedSuggestionId));if(!c)return a;const p=c.spec,u=l.Decoration.widget(c.from,((e,o)=>{const r=o();return void 0===r?document.createElement("div"):d(e,c,r,(()=>_t(e,Ft,c.spec.id)),(()=>Lt(e,Ft,c.spec.id)),(()=>Gt(t,p.originalText,p.replacement,{endpoint:s,model:n,modelStateManager:m})))}),{id:c.spec.id,side:-1,stopEvent:()=>!0});return a.add(e.doc,[u])},handleClick(t,e,o){const s=Ft.getState(t.state);if(!s)return!1;const n=s.decorations.find((t=>t.from<=e&&e<=t.to));return n?(n.spec.id===s.contextState.selectedSuggestionId||jt(t,Ft,n.spec.id),!1):(s.contextState.selectedSuggestionId&&kt(t,Ft),!1)}}),view:x.spec.view})},exports.grammarSuggestV2Key=Ft,exports.grammarWidgetFactory=Mt,exports.handleAction=Q,exports.hasActiveRequest=function(t){return h.has(t)},exports.hasAutoCompleteRequest=function(t){return qt.has(t)},exports.hasAutoCompletion=function(t){const e=Yt.getState(t.state);return!!(null==e?void 0:e.suggestion)},exports.hasUnitsToProcess=Z,exports.isAutoCompleteEnabled=function(t){var e;const o=Yt.getState(t.state);return null!==(e=null==o?void 0:o.enabled)&&void 0!==e&&e},exports.linkDetectorDecorationFactory=ot,exports.linkDetectorKey=rt,exports.linkDetectorProcessor=nt,exports.mergeOptions=_,exports.pauseRunner=function(t,e){B(t,e,{type:exports.ActionType.FINISH})},exports.randomProcessor=Ot,exports.randomProcessorDecorationFactory=ht,exports.randomProcessorKey=Pt,exports.randomProcessorWidgetFactory=Rt,exports.rejectResult=function(t){t.dispatch(t.state.tr.setMeta(b,{type:exports.CompleteActionType.REJECT_RESULT}))},exports.remapPositions=F,exports.requestHint=Gt,exports.resumeRunner=function(t,e){B(t,e,{type:exports.ActionType.RESUME})},exports.selectSuggestion=jt,exports.sentenceLengthDecorationFactory=xt,exports.sentenceLengthKey=Ct,exports.sentenceLengthProcessor=yt,exports.setAutoCompleteEnabled=function(t,e){e||$t(t),t.dispatch(t.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.SET_ENABLED,enabled:e}))},exports.setCompleteEnabled=(t,e)=>{t.dispatch(t.state.tr.setMeta(P,{type:"setEnabled",enabled:e}))},exports.setEnabled=function(t,e){e||R(t),t.dispatch(t.state.tr.setMeta(b,{type:exports.CompleteActionType.SET_ENABLED,enabled:e}))},exports.setGrammarSuggestEnabled=(t,e)=>{t.dispatch(t.state.tr.setMeta(D,{type:exports.GrammarSuggestMetaType.setEnabled,enabled:e}))},exports.sleep=W,exports.startTask=function(t,e,o){const s=t.state.selection;t.dispatch(t.state.tr.setMeta(b,{type:exports.CompleteActionType.START_TASK,taskType:e,params:o,selection:s.empty?void 0:s}))},exports.streamingRequest=A,exports.textToDocPos=j,exports.updateUnit=q,exports.wordComplexityDecorationFactory=it,exports.wordComplexityKey=mt,exports.wordComplexityProcessor=lt;
|
|
1
|
+
"use strict";var t,e,o,s,n,r=require("prosemirror-model"),a=require("prosemirror-state"),i=require("tslib"),c=require("fast-diff"),p=require("@emergence-engineering/fast-diff-merge"),u=require("prosemirror-transform"),l=require("prosemirror-view");exports.GrammarSuggestMetaType=void 0,(t=exports.GrammarSuggestMetaType||(exports.GrammarSuggestMetaType={})).suggestionUpdate="suggestionUpdate",t.acceptSuggestion="acceptSuggestion",t.openSuggestion="openSuggestion",t.closeSuggestion="closeSuggestion",t.discardSuggestion="discardSuggestion",t.setEnabled="setEnabled",exports.GrammarSuggestElementClass=void 0,(exports.GrammarSuggestElementClass||(exports.GrammarSuggestElementClass={})).grammarSuggestPopup="grammar-suggest-popup",exports.MoodParamType=void 0,(e=exports.MoodParamType||(exports.MoodParamType={})).Casual="Casual",e.Confident="Confident",e.Straightforward="Straightforward",e.Friendly="Friendly",exports.TranslationTargetLanguage=void 0,(o=exports.TranslationTargetLanguage||(exports.TranslationTargetLanguage={})).English="English",o.Spanish="Spanish",o.French="French",o.German="German",o.Italian="Italian",o.Portuguese="Portuguese",o.Dutch="Dutch",o.Russian="Russian",o.Chinese="Chinese",o.Korean="Korean",o.Japanese="Japanese",exports.AiPromptsWithoutParam=void 0,(s=exports.AiPromptsWithoutParam||(exports.AiPromptsWithoutParam={})).Complete="Complete",s.SmallComplete="SmallComplete",s.Improve="Improve",s.MakeLonger="MakeLonger",s.MakeShorter="MakeShorter",s.Simplify="Simplify",s.Explain="Explain",s.ActionItems="ActionItems",exports.AiPromptsWithParam=void 0,(n=exports.AiPromptsWithParam||(exports.AiPromptsWithParam={})).ChangeTone="ChangeTone",n.Translate="Translate",n.Hint="Hint",n.Custom="Custom";const d=exports.AiPromptsWithoutParam,m=exports.AiPromptsWithParam;var g,x,S;exports.Status=void 0,(g=exports.Status||(exports.Status={})).idle="idle",g.new="new",g.streaming="streaming",g.finished="finished",g.accepted="accepted",g.cancelled="cancelled",g.rejected="rejected",g.done="done",g.error="error",exports.CompleteStatus=void 0,(x=exports.CompleteStatus||(exports.CompleteStatus={})).IDLE="idle",x.PENDING="pending",x.STREAMING="streaming",x.PREVIEW="preview",x.APPLYING="applying",exports.CompleteActionType=void 0,(S=exports.CompleteActionType||(exports.CompleteActionType={})).START_TASK="START_TASK",S.STREAM_UPDATE="STREAM_UPDATE",S.STREAM_COMPLETE="STREAM_COMPLETE",S.STREAM_ERROR="STREAM_ERROR",S.ACCEPT_RESULT="ACCEPT_RESULT",S.REJECT_RESULT="REJECT_RESULT",S.CANCEL_TASK="CANCEL_TASK",S.CLEAR_ERROR="CLEAR_ERROR",S.SET_ENABLED="SET_ENABLED";const E={maxSelection:1e3},T="https://suggestion-gw5lxik4dq-uc.a.run.app",f="https://prosemirror-ai-plugin.web.app/api/suggestion",y="openai:gpt-4o-mini";function C(t,e){var o;return i.__awaiter(this,void 0,void 0,(function*(){const{apiKey:s,text:n,task:r,params:a,endpoint:i=T,model:c=y,signal:p}=t;let u="";const l={model:c,modelParams:{input:[n],task:r,params:a}};try{const t=yield fetch(i,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},signal:p,body:JSON.stringify(l)});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}`);const n=null===(o=t.body)||void 0===o?void 0:o.getReader();if(!n)throw new Error("No response body");for(;;){const{done:t,value:o}=yield n.read();if(t)break;if(null==p?void 0:p.aborted)return;const s=(new TextDecoder).decode(o);u+=s,e.onChunk(s,u)}(null==p?void 0:p.aborted)||e.onComplete(u)}catch(t){if(t instanceof Error&&"AbortError"===t.name)return;e.onError(t instanceof Error?t:new Error(String(t)))}}))}function A(t){return i.__awaiter(this,void 0,void 0,(function*(){const{apiKey:e,text:o,endpoint:s=f,model:n=y}=t,r={model:n,modelParams:{input:[...o.split("\n")]}};try{const t=yield fetch(s,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(r)});if(!t.ok){const e=yield t.text();return console.error({status:t.status,text:e}),{fixed:!1,result:o,error:!0}}const n=yield t.json();return(null==n?void 0:n.length)?{result:n.join("\n"),fixed:!0}:{fixed:!1,result:o}}catch(t){return console.error("Grammar request error:",t),{fixed:!1,result:o,error:!0}}}))}const h=new WeakMap;function R(t){const e=h.get(t);e&&(e.abort(),h.delete(t))}const I=new a.PluginKey("completePluginV2"),O={status:exports.CompleteStatus.IDLE,streamedResult:"",enabled:!0};function b(t,e={}){const{maxSelection:o,apiEndpoint:s,model:n}=Object.assign(Object.assign({},E),e);let c=!1;return new a.Plugin({key:I,state:{init:()=>Object.assign({},O),apply(t,e){const o=t.getMeta(I);return o?function(t,e){switch(e.type){case exports.CompleteActionType.SET_ENABLED:return Object.assign(Object.assign(Object.assign({},t),{enabled:e.enabled}),e.enabled?{}:O);case exports.CompleteActionType.START_TASK:return t.status!==exports.CompleteStatus.IDLE?t:Object.assign(Object.assign({},t),{status:exports.CompleteStatus.PENDING,taskType:e.taskType,params:e.params,selection:e.selection,streamedResult:"",error:void 0});case exports.CompleteActionType.STREAM_UPDATE:return t.status!==exports.CompleteStatus.PENDING&&t.status!==exports.CompleteStatus.STREAMING?t:Object.assign(Object.assign({},t),{status:exports.CompleteStatus.STREAMING,streamedResult:e.result});case exports.CompleteActionType.STREAM_COMPLETE:return t.status!==exports.CompleteStatus.PENDING&&t.status!==exports.CompleteStatus.STREAMING?t:Object.assign(Object.assign({},t),{status:exports.CompleteStatus.PREVIEW,streamedResult:e.result});case exports.CompleteActionType.STREAM_ERROR:return Object.assign(Object.assign({},t),{status:exports.CompleteStatus.IDLE,error:e.error,streamedResult:"",taskType:void 0,params:void 0,selection:void 0});case exports.CompleteActionType.ACCEPT_RESULT:return t.status!==exports.CompleteStatus.PREVIEW?t:Object.assign(Object.assign({},t),{status:exports.CompleteStatus.APPLYING});case exports.CompleteActionType.REJECT_RESULT:return t.status!==exports.CompleteStatus.PREVIEW?t:Object.assign(Object.assign({},O),{enabled:t.enabled});case exports.CompleteActionType.CANCEL_TASK:return Object.assign(Object.assign({},O),{enabled:t.enabled});case exports.CompleteActionType.CLEAR_ERROR:return Object.assign(Object.assign({},t),{error:void 0});default:return t}}(e,o):e.status===exports.CompleteStatus.APPLYING?Object.assign(Object.assign({},O),{enabled:e.enabled}):e}},view:()=>({update(e){const p=I.getState(e.state);if(p&&p.enabled){if(p.status===exports.CompleteStatus.PENDING&&!c){const{text:r,error:a}=function(t,e,o){const{taskType:s,selection:n}=e;if(s===exports.AiPromptsWithoutParam.Complete){const{doc:e}=t.state,o=[];return e.descendants((t=>{"paragraph"===t.type.name&&o.push(t.textContent)})),{text:o.length>=2?o.slice(-2).join(" "):o.join(" ")}}return n?t.state.doc.textBetween(n.from,n.to).length>o?{text:"",error:"Selection is too big"}:{text:t.state.doc.textBetween(n.from,n.to,"\n")}:{text:"",error:"No selection"}}(e,p,o);if(a)return void e.dispatch(e.state.tr.setMeta(I,{type:exports.CompleteActionType.STREAM_ERROR,error:a}));if(!r)return void e.dispatch(e.state.tr.setMeta(I,{type:exports.CompleteActionType.STREAM_ERROR,error:"No text to process"}));c=!0,function({view:t,pluginKey:e,apiKey:o,text:s,task:n,params:r,apiEndpoint:a,model:c}){return i.__awaiter(this,void 0,void 0,(function*(){R(t);const i=new AbortController;h.set(t,i);try{yield C({apiKey:o,text:s,task:n,params:r,endpoint:a,model:c,signal:i.signal},{onChunk:(o,s)=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.CompleteActionType.STREAM_UPDATE,result:s}))},onComplete:o=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.CompleteActionType.STREAM_COMPLETE,result:o}))},onError:o=>{console.error("Streaming request error:",o),t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.CompleteActionType.STREAM_ERROR,error:o.message}))}})}finally{h.delete(t)}}))}({view:e,pluginKey:I,apiKey:t,text:r,task:p.taskType,params:p.params,apiEndpoint:s,model:n}).finally((()=>{c=!1}))}p.status===exports.CompleteStatus.APPLYING&&function(t,e){const{taskType:o,selection:s,streamedResult:n}=e;if(!n)return;let{tr:i}=t.state;if(o===exports.AiPromptsWithoutParam.Complete)i=i.insertText(n,t.state.doc.nodeSize-2);else if(s){const e=n.split("\n\n").map((e=>t.state.schema.node("paragraph",null,e?t.state.schema.text(e):void 0))),o=r.Fragment.fromArray(e);i=i.setSelection(a.TextSelection.create(t.state.doc,s.from,s.to)),i.selection.replace(i,new r.Slice(o,0,0))}t.dispatch(i),t.focus()}(e,p)}},destroy(){}})})}const v={debounceMs:2e3,createUpdatePopup:(t,e,o,s,n)=>{const r=document.createElement("div");r.className="grammar-suggest-tooltip";const{spec:a}=e,i=t.dom.getBoundingClientRect();r.id=exports.GrammarSuggestElementClass.grammarSuggestPopup;const c=t.coordsAtPos(o),p=t.dom.scrollTop||0,u=t.dom.scrollLeft||0;r.style.left=`${c.left-i.left+u}px`,r.style.top=`${c.bottom-i.top+p+5}px`;const l=document.createElement("div");l.className="grammar-suggest-tooltip-apply",l.innerText=a.text||a.originalText,a.text||(l.style.textDecoration="line-through",l.style.color="red"),l.onclick=()=>{s(t,e)},r.appendChild(l);const d=document.createElement("div");return d.innerHTML="<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'><path d='M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z'></path></svg>",d.className="grammar-suggest-tooltip-discard",d.onclick=()=>{n(t,e)},r.appendChild(d),r},withYjs:!1},P=new a.PluginKey("completePlugin"),D=new a.PluginKey("grammarSuggestPlugin");var w,M,U;exports.RunnerStatus=void 0,(w=exports.RunnerStatus||(exports.RunnerStatus={})).IDLE="IDLE",w.ACTIVE="ACTIVE",exports.UnitStatus=void 0,(M=exports.UnitStatus||(exports.UnitStatus={})).DIRTY="DIRTY",M.WAITING="WAITING",M.QUEUED="QUEUED",M.PROCESSING="PROCESSING",M.DONE="DONE",M.BACKOFF="BACKOFF",M.ERROR="ERROR",exports.ActionType=void 0,(U=exports.ActionType||(exports.ActionType={})).INIT="INIT",U.FINISH="FINISH",U.CLEAR="CLEAR",U.RESUME="RESUME",U.UNIT_STARTED="UNIT_STARTED",U.UNIT_SUCCESS="UNIT_SUCCESS",U.UNIT_ERROR="UNIT_ERROR",U.UPDATE_CONTEXT="UPDATE_CONTEXT",U.REMOVE_DECORATION="REMOVE_DECORATION",U.SELECT_DECORATION="SELECT_DECORATION",U.DESELECT_DECORATION="DESELECT_DECORATION";const N={nodeTypes:"paragraph",priorityFilter:()=>!0,visibilityFilter:()=>!0,getGroupId:()=>"default",batchSize:4,maxRetries:3,backoffBase:1e3,dirtyHandling:{shouldRecalculate:!0,debounceDelay:2e3,skipDirtyOnSelfChange:!0},forceRerender:()=>{},onUpdate:void 0};function _(t){return Object.assign(Object.assign(Object.assign({},N),t),{dirtyHandling:Object.assign(Object.assign({},N.dirtyHandling),t.dirtyHandling)})}function L(t,e,o){const s=[];let n="",r=0;return t.nodesBetween(e,o,((t,a)=>{if(t.isText&&t.text){const i=Math.max(e,a),c=Math.min(o,a+t.nodeSize),p=t.text.slice(i-a,c-a);s.push({from:r,docPos:i}),n+=p,r+=p.length}else t.isBlock&&n.length>0&&(s.push({from:r,docPos:a}),n+="\n",r+=1)})),{text:n,mapping:s}}function j(t,e){var o,s;for(let o=e.length-1;o>=0;o--)if(e[o].from<=t)return e[o].docPos+(t-e[o].from);return null!==(s=null===(o=e[0])||void 0===o?void 0:o.docPos)&&void 0!==s?s:0}function k(t,e,o,s="paragraph"){const n=Array.isArray(s)?s:[s],r=[];return t.nodesBetween(e,o,((e,o)=>{if(n.includes(e.type.name)){const s=o+e.nodeSize,n=L(t,o,s);n.text.trim().length>0&&r.push(Object.assign({from:o,to:s},n))}})),r}const G=(t,e)=>t.map((t=>null==t?void 0:t.map(e,0,0))).filter((t=>null!==t)),K=(t,e)=>{const o=t.doc.content.findDiffStart(e.doc.content),s=e.doc.content.findDiffEnd(t.doc.content);if(!s||!o)return;let n=new u.StepMap([0,0,0]),r=o,a=s.a;return s&&o&&(s.a<o?(r=s.a,a=s.b,n=new u.StepMap([s.a,0,s.b-s.a])):s.b<o?(r=s.b,a=s.a,n=new u.StepMap([s.b,s.a-s.b,0])):n=new u.StepMap([o,s.a-o,s.b-o])),{end:a,mapping:new u.Mapping([n]),start:r}};function F(t,e,o,s,n=!1){var r;const a=K(e,o);if(!a)return t;const{start:i,end:c,mapping:p}=a,u=Array.isArray(s.nodeTypes)?s.nodeTypes:[s.nodeTypes],l=Date.now()+s.dirtyHandling.debounceDelay,d=null===(r=t.unitsInProgress)||void 0===r?void 0:r.slice().sort(((t,e)=>t.from-e.from));if(d){const o=[],s=p.map(d[0].from),r=p.map(d[d.length-1].to),a=k(e.doc,s,r,u);for(const t in d){const e=d[t],s=a[t];if(s){let{status:t}=e;!n&&s.from<=c&&s.to>=i&&(t=exports.UnitStatus.DIRTY),o.push(Object.assign(Object.assign(Object.assign({},e),{status:t,waitUntil:n?e.waitUntil:l}),s))}else o.push(Object.assign(Object.assign({},e),{status:exports.UnitStatus.DONE,from:r,to:r}))}return Object.assign(Object.assign({},t),{unitsInProgress:o,decorations:G(t.decorations,p)})}return Object.assign(Object.assign({},t),{decorations:G(t.decorations,p)})}function V(t,e){return 1e3*Math.pow(e/1e3,t)}function B(t){return new Promise((e=>setTimeout(e,t)))}function W(t,e,o){t.dispatch(t.state.tr.setMeta(e,o))}function H(t,e,o){if(e.status===exports.RunnerStatus.ACTIVE)return e.unitsInProgress.find((t=>t.id===o))}function q(t,e,o){const s=t.unitsInProgress.map((t=>t.id===e?Object.assign(Object.assign({},t),o):t));return"waitUntil"in o&&s.sort(((t,e)=>t.waitUntil-e.waitUntil)),Object.assign(Object.assign({},t),{unitsInProgress:s})}function $(t,e,o,s,n="paragraph"){return k(t,e,o,n).map(((t,e)=>({id:{},status:exports.UnitStatus.QUEUED,from:t.from,to:t.to,text:t.text,mapping:t.mapping,metadata:s(t,e),retryCount:0,waitUntil:0})))}function Q(t,e,o,s){var n;switch(e.type){case exports.ActionType.INIT:return function(t,e,o,s){const n=$(o,e.onlySelection?s.from:0,e.onlySelection?s.to:o.content.size,((t,o)=>{var s;if(void 0!==e.metadata.single)return e.metadata.single;if(void 0!==e.metadata.array)return null!==(s=e.metadata.array[o])&&void 0!==s?s:e.metadata.array[0];if(void 0!==e.metadata.factory){const o={id:{},status:exports.UnitStatus.QUEUED,from:t.from,to:t.to,text:t.text,mapping:[],metadata:{},retryCount:0,waitUntil:0};return e.metadata.factory(o)}return{}})).map((e=>Object.assign(Object.assign({},e),{status:t.options.priorityFilter(e,t.contextState)?exports.UnitStatus.QUEUED:exports.UnitStatus.WAITING})));return Object.assign(Object.assign({},t),{status:exports.RunnerStatus.ACTIVE,unitsInProgress:n})}(t,e,s.doc,s.selection);case exports.ActionType.UNIT_STARTED:return t.status!==exports.RunnerStatus.ACTIVE?t:function(t,e){const o=t.unitsInProgress.find((t=>t.id===e));return o?q(t,e,{status:exports.UnitStatus.PROCESSING,requestText:o.text}):t}(t,e.unitId);case exports.ActionType.UNIT_SUCCESS:return t.status!==exports.RunnerStatus.ACTIVE?t:function(t,e,o){const s=t.unitsInProgress.find((t=>t.id===e.unitId));if(!s)return t;const n=Date.now()+t.options.dirtyHandling.debounceDelay;if(void 0!==s.requestText&&s.requestText!==s.text)return q(t,e.unitId,{status:exports.UnitStatus.DIRTY,requestText:void 0,waitUntil:n});const r=o(e.response,s),a=q(t,e.unitId,{status:exports.UnitStatus.DONE,response:e.response,requestText:void 0});return Object.assign(Object.assign({},a),{decorations:[...a.decorations,...r]})}(t,e,o);case exports.ActionType.UNIT_ERROR:return t.status!==exports.RunnerStatus.ACTIVE?t:function(t,e){const o=t.unitsInProgress.find((t=>t.id===e.unitId));if(!o)return t;const s=Date.now()+t.options.dirtyHandling.debounceDelay;if(void 0!==o.requestText&&o.requestText!==o.text)return q(t,e.unitId,{status:exports.UnitStatus.DIRTY,requestText:void 0,waitUntil:s});const n=o.retryCount+1;return n>=t.options.maxRetries?q(t,e.unitId,{status:exports.UnitStatus.ERROR,retryCount:n,requestText:void 0}):q(t,e.unitId,{status:exports.UnitStatus.BACKOFF,retryCount:n,waitUntil:Date.now()+V(n,t.options.backoffBase),requestText:void 0})}(t,e);case exports.ActionType.FINISH:return Object.assign(Object.assign({},t),{status:exports.RunnerStatus.IDLE});case exports.ActionType.CLEAR:return Object.assign(Object.assign({},t),{decorations:[],unitsInProgress:void 0,status:exports.RunnerStatus.IDLE,selected:void 0});case exports.ActionType.RESUME:return t.status!==exports.RunnerStatus.IDLE?t:(null===(n=t.unitsInProgress)||void 0===n?void 0:n.length)?Object.assign(Object.assign({},t),{status:exports.RunnerStatus.ACTIVE}):t;case exports.ActionType.UPDATE_CONTEXT:return Object.assign(Object.assign({},t),{contextState:e.contextState});case exports.ActionType.REMOVE_DECORATION:return Object.assign(Object.assign({},t),{decorations:t.decorations.filter((t=>t.spec.id!==e.id))});case exports.ActionType.SELECT_DECORATION:return Object.assign(Object.assign({},t),{selected:e.id});case exports.ActionType.DESELECT_DECORATION:return Object.assign(Object.assign({},t),{selected:void 0});default:return t}}function Y(t,e){return{status:exports.RunnerStatus.IDLE,decorations:[],selected:void 0,contextState:t,options:e}}function z(t,e,o,s){return i.__awaiter(this,void 0,void 0,(function*(){const n=t.getState(e.state);if(!n||n.status!==exports.RunnerStatus.ACTIVE)return!1;const r=function(t,e){var o;if(t.status!==exports.RunnerStatus.ACTIVE)return;const s=Date.now(),n=null!==(o=t.unitsInProgress)&&void 0!==o?o:[],r=t=>[exports.UnitStatus.QUEUED,exports.UnitStatus.BACKOFF,exports.UnitStatus.DIRTY].includes(t.status)&&t.waitUntil<=s,a=n.find((o=>r(o)&&e.priorityFilter(o,t.contextState)));if(a)return a;const i=n.find(r);if(i)return i;return n.find((t=>[exports.UnitStatus.QUEUED,exports.UnitStatus.BACKOFF,exports.UnitStatus.DIRTY].includes(t.status)&&t.waitUntil>s))||void 0}(n,s);if(!r)return!1;W(e,t,{type:exports.ActionType.UNIT_STARTED,unitId:r.id});const a=t.getState(e.state);if(!a)return!1;const i=H(0,a,r.id);if(i&&i.waitUntil>Date.now()){yield B(i.waitUntil-Date.now());const o=t.getState(e.state);if(!o||o.status!==exports.RunnerStatus.ACTIVE)return!1}try{const s=yield o(e,r);s.error?W(e,t,{type:exports.ActionType.UNIT_ERROR,unitId:r.id,error:s.error}):void 0!==s.data&&W(e,t,{type:exports.ActionType.UNIT_SUCCESS,unitId:r.id,response:s.data})}catch(o){W(e,t,{type:exports.ActionType.UNIT_ERROR,unitId:r.id,error:o instanceof Error?o:new Error(String(o))})}return!0}))}function J(t,e,o,s){return i.__awaiter(this,void 0,void 0,(function*(){return!!(yield z(t,e,o,s))&&J(t,e,o,s)}))}function X(t,e,o,s){return i.__awaiter(this,void 0,void 0,(function*(){const n=Array.from({length:s.batchSize},(()=>J(t,e,o,s)));yield Promise.all(n)}))}function Z(t){return t.status===exports.RunnerStatus.ACTIVE&&t.unitsInProgress.some((t=>t.status===exports.UnitStatus.QUEUED||t.status===exports.UnitStatus.WAITING||t.status===exports.UnitStatus.BACKOFF||t.status===exports.UnitStatus.DIRTY||t.status===exports.UnitStatus.PROCESSING))}function tt(t){const{pluginKey:e,unitProcessor:o,decorationFactory:s,decorationTransformer:n,widgetFactory:r,initialContextState:i,options:c,handleKeyDown:p}=t,u=_(null!=c?c:{});let d=!1;return new a.Plugin({key:e,state:{init:()=>Y(i,u),apply(t,o,n,r){const a=t.getMeta(e),i=t.docChanged&&void 0!==a&&u.dirtyHandling.skipDirtyOnSelfChange;let c=o;if(t.docChanged&&(c=F(o,t,n,u,i)),a){const t=Q(c,a,s,r);return u.onUpdate&&u.onUpdate(t),t}return c}},props:{decorations(t){const o=e.getState(t);if(!o)return l.DecorationSet.empty;let s=o.decorations.filter((t=>u.visibilityFilter(t,o.contextState)));n&&(s=n(s,o));const a=[];if(r&&o.unitsInProgress)for(const t of o.unitsInProgress)if(t.status!==exports.UnitStatus.DONE&&t.status!==exports.UnitStatus.ERROR){const e=r(t);e&&a.push(e)}return l.DecorationSet.create(t.doc,[...s,...a])},handleKeyDown:p},view:()=>({update(t){const s=e.getState(t.state);s&&s.status===exports.RunnerStatus.ACTIVE&&!d&&Z(s)&&(d=!0,X(e,t,o,u).finally((()=>{d=!1;const o=e.getState(t.state);!o||o.status!==exports.RunnerStatus.ACTIVE||Z(o)||u.dirtyHandling.shouldRecalculate||W(t,e,{type:exports.ActionType.FINISH})})))}})})}function et(t){return new a.PluginKey(t)}const ot=(t,e)=>t.map((o=>{const s=j(o.from,e.mapping),n=j(o.to,e.mapping);return l.Decoration.inline(s,n,{class:"link-detected",style:"color: #0066cc; text-decoration: underline; cursor: pointer;"},{id:{},unitId:e.id,originalText:o.url,response:t,url:o.url})})),st=/https?:\/\/[^\s<>"')\]]+/g;const nt=(t,e)=>i.__awaiter(void 0,void 0,void 0,(function*(){return{data:function(t){const e=[];let o=st.exec(t);for(;null!==o;)e.push({url:o[0],from:o.index,to:o.index+o[0].length}),o=st.exec(t);return e}(e.text)}})),rt=et("linkDetector");const at={moderate:{class:"word-complexity-moderate",style:"background-color: rgba(255, 193, 7, 0.3); border-radius: 2px;"},high:{class:"word-complexity-high",style:"background-color: rgba(244, 67, 54, 0.3); border-radius: 2px;"}},it=(t,e)=>t.map((o=>{const s=j(o.from,e.mapping),n=j(o.to,e.mapping),r=at[o.complexity];return l.Decoration.inline(s,n,{class:r.class,style:r.style},{id:{},unitId:e.id,originalText:o.word,response:t,syllables:o.syllables,complexity:o.complexity})}));function ct(t){let e=t.toLowerCase().replace(/[^a-z]/g,"");if(e.length<=3)return 1;e=e.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/,""),e=e.replace(/^y/,"");const o=e.match(/[aeiouy]{1,2}/g);return o?Math.max(1,o.length):1}const pt=/[a-zA-Z]+/g;function ut(t,e,o){const s=[];let n=pt.exec(t);for(;null!==n;){const r=n[0],a=ct(r);a>=e&&s.push({word:r,from:n.index,to:n.index+r.length,syllables:a,complexity:a>=o?"high":"moderate"}),n=pt.exec(t)}return s}const lt=(t,e)=>i.__awaiter(void 0,void 0,void 0,(function*(){return{data:ut(e.text,3,4)}})),dt={moderateThreshold:3,highThreshold:4},mt=et("wordComplexity");const gt={warning:{class:"sentence-too-long-warning",style:"background-color: rgba(255, 152, 0, 0.2); border-radius: 2px;"},error:{class:"sentence-too-long-error",style:"background-color: rgba(244, 67, 54, 0.2); border-radius: 2px;"}},xt=(t,e)=>t.map((o=>{const s=j(o.from,e.mapping),n=j(o.to,e.mapping),r=gt[o.severity];return l.Decoration.inline(s,n,{class:r.class,style:r.style},{id:{},unitId:e.id,originalText:e.text.slice(o.from,o.to),response:t,wordCount:o.wordCount,severity:o.severity})})),St=/[^.!?]*[.!?]+/g,Et=/\b\w+\b/g;function Tt(t){const e=t.match(Et);return e?e.length:0}function ft(t,e,o){const s=[];let n=St.exec(t);for(;null!==n;){const r=n[0],a=Tt(r);a>=e&&s.push({from:n.index,to:n.index+r.length,wordCount:a,severity:a>=o?"error":"warning"}),n=St.exec(t)}return s}const yt=(t,e)=>i.__awaiter(void 0,void 0,void 0,(function*(){return{data:ft(e.text,25,40)}})),Ct={warningThreshold:25,errorThreshold:40},At=et("sentenceLength");const ht=(t,e)=>[l.Decoration.inline(e.from+1,e.to-1,{class:"random-processor-success",style:"background-color: rgba(76, 175, 80, 0.2); border-radius: 2px;"},{id:{},unitId:e.id,originalText:e.text,response:t,processingTime:t.processingTime})],Rt=t=>{let e,o;const s=Math.max(0,t.waitUntil-Date.now());switch(t.status){case exports.UnitStatus.QUEUED:e="⏳ Queued...",o="random-processor-widget queued";break;case exports.UnitStatus.PROCESSING:e="⚙️ Processing...",o="random-processor-widget processing";break;case exports.UnitStatus.BACKOFF:e=`🔄 Retry in ${Math.ceil(s/1e3)}s (attempt ${t.retryCount+1})`,o="random-processor-widget backoff";break;case exports.UnitStatus.ERROR:e=`❌ Failed after ${t.retryCount} retries`,o="random-processor-widget error";break;case exports.UnitStatus.DIRTY:e="⚠️ Changed",o="random-processor-widget dirty";break;case exports.UnitStatus.WAITING:e="⏸️ Waiting...",o="random-processor-widget waiting";break;default:return}let n,r;switch(t.status){case exports.UnitStatus.ERROR:n="#ffebee",r="#c62828";break;case exports.UnitStatus.DIRTY:n="#fff9c4",r="#f57f17";break;case exports.UnitStatus.BACKOFF:n="#fff3e0",r="#e65100";break;default:n="#e3f2fd",r="#1565c0"}const a=document.createElement("span");if(a.className=o,a.textContent=e,t.status===exports.UnitStatus.BACKOFF&&s>0){const e=setInterval((()=>{const o=Math.max(0,t.waitUntil-Date.now());a.textContent=`🔄 Retry in ${Math.ceil(o/1e3)}s (attempt ${t.retryCount+1})`,(o<=0||!a.isConnected)&&clearInterval(e)}),1e3)}return a.style.cssText=`\n display: inline-block;\n padding: 2px 8px;\n margin-right: 8px;\n font-size: 12px;\n border-radius: 4px;\n background: ${n};\n color: ${r};\n `,l.Decoration.widget(t.from+1,a,{side:-1})};function It(t,e){return Math.floor(Math.random()*(e-t+1))+t}function Ot(t){return new Promise((e=>setTimeout(e,t)))}const bt=(t,e)=>i.__awaiter(void 0,void 0,void 0,(function*(){const t=It(500,3e3);yield Ot(t);return Math.random()<.3?{error:new Error(`Random error after ${t}ms (attempt ${e.metadata.attempt})`)}:{data:{processingTime:t,success:!0,message:`Processed "${e.text.slice(0,20)}..." in ${t}ms`}}})),vt={minDelay:500,maxDelay:3e3,errorRate:.3},Pt=et("randomProcessor");const Dt=(t,e)=>t.fixed&&0!==t.suggestions.length?t.suggestions.map((o=>{const s=j(o.from,e.mapping),n=j(o.to,e.mapping),r=""===o.replacement,a={id:{},unitId:e.id,originalText:o.original,replacement:o.replacement,response:t};return l.Decoration.inline(s,n,{class:"grammarSuggestionV2 "+(r?"removalSuggestionV2":"")},a)})):[],wt=(t,e)=>{const o=e.contextState.selectedSuggestionId;return o?t.map((t=>{const e=t.spec;return e.id===o?l.Decoration.inline(t.from,t.to,{class:"grammarSuggestionV2 grammarSuggestionV2-selected"},e):t})):t},Mt=t=>{let e,o;const s=Math.max(0,t.waitUntil-Date.now());switch(t.status){case exports.UnitStatus.QUEUED:case exports.UnitStatus.WAITING:e="⏳",o="grammarWidgetV2 queued";break;case exports.UnitStatus.PROCESSING:e="🔍",o="grammarWidgetV2 processing";break;case exports.UnitStatus.BACKOFF:e=`🔄 ${Math.ceil(s/1e3)}s`,o="grammarWidgetV2 backoff";break;case exports.UnitStatus.ERROR:e="❌",o="grammarWidgetV2 error";break;case exports.UnitStatus.DIRTY:e="✏️",o="grammarWidgetV2 dirty";break;default:return}const n=document.createElement("span");if(n.className=o,n.textContent=e,t.status===exports.UnitStatus.BACKOFF&&s>0){const e=setInterval((()=>{const o=Math.max(0,t.waitUntil-Date.now());n.textContent=`🔄 ${Math.ceil(o/1e3)}s`,(o<=0||!n.isConnected)&&clearInterval(e)}),1e3)}return l.Decoration.widget(t.from+1,n,{side:-1})};const Ut=t=>{const{apiKey:e,apiEndpoint:o,model:s,modelStateManager:n}="string"==typeof t?{apiKey:t,apiEndpoint:void 0,model:void 0,modelStateManager:void 0}:t;return(t,r)=>i.__awaiter(void 0,void 0,void 0,(function*(){var t,a,i;try{const c=null!==(t=null==n?void 0:n.getCurrentModel())&&void 0!==t?t:s,u=yield A({apiKey:e,text:r.text,endpoint:o,model:c});if(u.error)return null==n||n.handleFailure(),{error:new Error("Grammar API error")};if(null==n||n.handleSuccess(),!u.fixed)return{data:{fixed:!1,originalText:r.text,fixedText:r.text,suggestions:[]}};const l=(a=r.text,i=u.result,p.getDiff(a,i).filter((t=>!p.isIdentity(t))).filter((t=>t.original!==`${t.replacement}\n`)).map((t=>({from:t.from,to:t.replacement.endsWith("\n")?t.to-1:t.to,original:t.original,replacement:t.replacement.endsWith("\n")?t.replacement.slice(0,-1):t.replacement}))));return{data:{fixed:l.length>0,originalText:r.text,fixedText:u.result,suggestions:l}}}catch(t){return null==n||n.handleFailure(),{error:t instanceof Error?t:new Error(String(t))}}}))};function Nt(t,e,o){const s=e.getState(t.state);if(s)return s.decorations.find((t=>t.spec.id===o))}function _t(t,e,o){const s=Nt(t,e,o);if(!s)return;const n=s.spec,{replacement:i}=n,{from:c,to:p}=s,u=i.split("\n").map((e=>e?t.state.schema.node("paragraph",null,t.state.schema.text(e)):t.state.schema.node("paragraph"))),l=r.Fragment.fromArray(u);let{tr:d}=t.state;d=d.setSelection(a.TextSelection.create(t.state.doc,c,p)),d.selection.replace(d,new r.Slice(l,1,1)),d=d.setMeta(e,{type:exports.ActionType.REMOVE_DECORATION,id:o}),t.dispatch(d)}function Lt(t,e,o){W(t,e,{type:exports.ActionType.REMOVE_DECORATION,id:o})}function jt(t,e,o){W(t,e,{type:exports.ActionType.UPDATE_CONTEXT,contextState:{selectedSuggestionId:o}})}function kt(t,e){W(t,e,{type:exports.ActionType.UPDATE_CONTEXT,contextState:{selectedSuggestionId:void 0}})}function Gt(t,e,o,s){var n,r,a;return i.__awaiter(this,void 0,void 0,(function*(){const i=null!==(n=null==s?void 0:s.endpoint)&&void 0!==n?n:T,c=null==s?void 0:s.modelStateManager,p=null!==(a=null!==(r=null==c?void 0:c.getCurrentModel())&&void 0!==r?r:null==s?void 0:s.model)&&void 0!==a?a:y;return new Promise(((s,n)=>{const r={previousPromptType:"Grammar",oldVersion:e,newVersion:o};C({apiKey:t,text:e,task:exports.AiPromptsWithParam.Hint,params:r,endpoint:i,model:p},{onChunk:()=>{},onComplete:t=>{null==c||c.handleSuccess(),s(t)},onError:t=>{null==c||c.handleFailure(),n(t)}})}))}))}const Kt={selectedSuggestionId:void 0},Ft=et("grammarSuggestV2"),Vt=(t,e,o,s,n,r)=>{const a=e.spec,c=document.createElement("div");c.className="grammarPopupV2";const p=document.createElement("div");p.className="grammarPopupV2-mainRow";const u=document.createElement("span");u.className="grammarPopupV2-original",u.textContent=`"${a.originalText}"`;const l=document.createElement("span");l.className="grammarPopupV2-arrow",l.textContent=" → ";const d=document.createElement("span");d.className="grammarPopupV2-replacement",d.textContent=""===a.replacement?"(remove)":`"${a.replacement}"`;const m=document.createElement("button");m.className="grammarPopupV2-hint",m.textContent="?",m.title="Why this suggestion?";const g=document.createElement("div");g.className="grammarPopupV2-hintArea",g.style.display="none";let x=!1;m.onclick=t=>i.__awaiter(void 0,void 0,void 0,(function*(){if(t.preventDefault(),t.stopPropagation(),"none"===g.style.display){if(g.style.display="block",!x){g.innerHTML='<span class="grammarPopupV2-loading">Loading...</span>';try{const t=yield r();g.innerHTML="";const e=document.createElement("span");e.className="grammarPopupV2-hintText",e.textContent=t,g.appendChild(e),x=!0}catch(t){g.innerHTML='<span class="grammarPopupV2-hintError">Could not load hint</span>'}}}else g.style.display="none"}));const S=document.createElement("button");S.className="grammarPopupV2-accept",S.textContent="✓",S.onclick=t=>{t.preventDefault(),t.stopPropagation(),s()};const E=document.createElement("button");return E.className="grammarPopupV2-discard",E.textContent="✕",E.onclick=t=>{t.preventDefault(),t.stopPropagation(),n()},p.appendChild(u),p.appendChild(l),p.appendChild(d),p.appendChild(m),p.appendChild(S),p.appendChild(E),c.appendChild(p),c.appendChild(g),c};var Bt,Wt;exports.AutoCompleteStatus=void 0,(Bt=exports.AutoCompleteStatus||(exports.AutoCompleteStatus={})).IDLE="idle",Bt.DEBOUNCING="debouncing",Bt.PENDING="pending",Bt.STREAMING="streaming",Bt.SHOWING="showing",exports.AutoCompleteActionType=void 0,(Wt=exports.AutoCompleteActionType||(exports.AutoCompleteActionType={})).SET_ENABLED="SET_ENABLED",Wt.START_DEBOUNCE="START_DEBOUNCE",Wt.START_REQUEST="START_REQUEST",Wt.STREAM_UPDATE="STREAM_UPDATE",Wt.STREAM_COMPLETE="STREAM_COMPLETE",Wt.STREAM_ERROR="STREAM_ERROR",Wt.DISMISS="DISMISS",Wt.ACCEPT="ACCEPT";const Ht={debounceMs:500,maxContextLength:2e3,ghostTextClass:"autoCompleteGhostText"},qt=new WeakMap;function $t(t){const e=qt.get(t);e&&(e.abort(),qt.delete(t))}function Qt(t,e){if(!e)return e;const{doc:o,selection:s}=t.state,n=s.from;if(n<=0)return e;const r=o.textBetween(n-1,n,""),a=e.charAt(0),i=/[\s\-]/;return!i.test(r)&&!i.test(a)?` ${e}`:e}const Yt=new a.PluginKey("autoCompletePlugin"),zt={status:exports.AutoCompleteStatus.IDLE,enabled:!0,suggestion:"",cursorPos:0};function Jt(t,e){switch(e.type){case exports.AutoCompleteActionType.SET_ENABLED:return Object.assign(Object.assign({},zt),{enabled:e.enabled});case exports.AutoCompleteActionType.START_DEBOUNCE:return Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.DEBOUNCING,cursorPos:e.cursorPos,suggestion:"",error:void 0});case exports.AutoCompleteActionType.START_REQUEST:return t.status!==exports.AutoCompleteStatus.DEBOUNCING?t:Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.PENDING});case exports.AutoCompleteActionType.STREAM_UPDATE:return t.status!==exports.AutoCompleteStatus.PENDING&&t.status!==exports.AutoCompleteStatus.STREAMING?t:Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.STREAMING,suggestion:e.suggestion});case exports.AutoCompleteActionType.STREAM_COMPLETE:return t.status!==exports.AutoCompleteStatus.PENDING&&t.status!==exports.AutoCompleteStatus.STREAMING?t:Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.SHOWING,suggestion:e.suggestion});case exports.AutoCompleteActionType.STREAM_ERROR:return Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.IDLE,error:e.error,suggestion:""});case exports.AutoCompleteActionType.DISMISS:case exports.AutoCompleteActionType.ACCEPT:return Object.assign(Object.assign({},t),{status:exports.AutoCompleteStatus.IDLE,suggestion:""});default:return t}}const Xt=b;Object.defineProperty(exports,"getDiff",{enumerable:!0,get:function(){return p.getDiff}}),exports.DEFAULT_COMPLETION_ENDPOINT=T,exports.DEFAULT_GRAMMAR_ENDPOINT=f,exports.DEFAULT_MODEL=y,exports.OpenAiPromptsWithParam=m,exports.OpenAiPromptsWithoutParam=d,exports.acceptAutoCompletion=function(t){const e=Yt.getState(t.state);if(!e||!e.suggestion)return!1;const o=t.state.tr.insertText(e.suggestion,e.cursorPos);return t.dispatch(o),t.dispatch(t.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.DISMISS})),t.focus(),!0},exports.acceptResult=function(t){t.dispatch(t.state.tr.setMeta(I,{type:exports.CompleteActionType.ACCEPT_RESULT}))},exports.acceptSuggestion=_t,exports.allUnitsFinished=function(t){return t.every((t=>t.status===exports.UnitStatus.DONE||t.status===exports.UnitStatus.ERROR))},exports.autoCompleteKey=Yt,exports.autoCompletePlugin=function(t,e={}){const o=Object.assign(Object.assign({},Ht),e),{debounceMs:s,maxContextLength:n,apiEndpoint:r,model:c,ghostTextClass:p}=o;let u=null,d=!1,m=null,g=null;return new a.Plugin({key:Yt,state:{init:()=>Object.assign({},zt),apply(t,e,o,s){const n=t.getMeta(Yt);if(n)return Jt(e,n);if(t.docChanged&&(e.status===exports.AutoCompleteStatus.SHOWING||e.status===exports.AutoCompleteStatus.STREAMING)){if(s.selection.from!==e.cursorPos)return Jt(e,{type:exports.AutoCompleteActionType.DISMISS})}return!t.selectionSet||t.docChanged||e.status!==exports.AutoCompleteStatus.SHOWING&&e.status!==exports.AutoCompleteStatus.STREAMING?e:Jt(e,{type:exports.AutoCompleteActionType.DISMISS})}},props:{decorations(t){const e=Yt.getState(t);if(!e||!e.enabled)return l.DecorationSet.empty;if((e.status===exports.AutoCompleteStatus.STREAMING||e.status===exports.AutoCompleteStatus.SHOWING)&&e.suggestion){const o=document.createElement("span");o.className=p,o.textContent=e.suggestion,o.setAttribute("contenteditable","false");const s=l.Decoration.widget(e.cursorPos,o,{side:1});return l.DecorationSet.create(t.doc,[s])}return l.DecorationSet.empty},handleKeyDown(t,e){const o=Yt.getState(t.state);return!(!o||!o.enabled)&&("Tab"===e.key&&!e.shiftKey&&o.status===exports.AutoCompleteStatus.SHOWING&&o.suggestion?(e.preventDefault(),m=o.suggestion,g=o.cursorPos,t.dispatch(t.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.ACCEPT})),!0):"Escape"===e.key&&(o.status===exports.AutoCompleteStatus.STREAMING||o.status===exports.AutoCompleteStatus.SHOWING)&&(e.preventDefault(),$t(t),t.dispatch(t.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.DISMISS})),!0))}},view:()=>({update(e,o){const a=Yt.getState(e.state),p=Yt.getState(o);if(a&&a.enabled){if(null!==m&&null!==g){const t=m,o=g;m=null,g=null;const s=e.state.tr.insertText(t,o);return e.dispatch(s),void e.focus()}if(e.state,e.state.doc!==o.doc&&(null==p?void 0:p.status)!==exports.AutoCompleteStatus.PENDING&&(null==p?void 0:p.status)!==exports.AutoCompleteStatus.STREAMING){e.state.tr,u&&(clearTimeout(u),u=null),$t(e);const t=e.state.selection.from;e.dispatch(e.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.START_DEBOUNCE,cursorPos:t})),u=setTimeout((()=>{u=null;const t=Yt.getState(e.state);(null==t?void 0:t.status)===exports.AutoCompleteStatus.DEBOUNCING&&e.dispatch(e.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.START_REQUEST}))}),s)}if(a.status===exports.AutoCompleteStatus.PENDING&&!d){if(!function(t){const{doc:e,selection:o}=t.state,s=o.from,n=e.resolve(s),r=n.parent,a=n.start();if(s!==a+r.content.size)return!1;const i=r.textBetween(0,s-a,"");return!!i.trim()&&!/[.!?]\s*$/.test(i)}(e))return void e.dispatch(e.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.DISMISS}));const o=function(t,e){const{doc:o,selection:s}=t.state,n=s.from,r=o.textBetween(0,n,"\n");return r.length>e?r.slice(-e):r}(e,n);if(!o.trim())return void e.dispatch(e.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.DISMISS}));d=!0,function({view:t,pluginKey:e,apiKey:o,context:s,apiEndpoint:n,model:r}){return i.__awaiter(this,void 0,void 0,(function*(){$t(t);const a=new AbortController;qt.set(t,a);try{yield C({apiKey:o,text:s,task:exports.AiPromptsWithoutParam.SmallComplete,endpoint:n,model:r,signal:a.signal},{onChunk:(o,s)=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.AutoCompleteActionType.STREAM_UPDATE,suggestion:Qt(t,s)}))},onComplete:o=>{t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.AutoCompleteActionType.STREAM_COMPLETE,suggestion:Qt(t,o)}))},onError:o=>{console.error("Auto-complete streaming error:",o),t.isDestroyed||t.dispatch(t.state.tr.setMeta(e,{type:exports.AutoCompleteActionType.STREAM_ERROR,error:o.message}))}})}finally{qt.delete(t)}}))}({view:e,pluginKey:Yt,apiKey:t,context:o,apiEndpoint:r,model:c}).finally((()=>{d=!1}))}}else u&&(clearTimeout(u),u=null)},destroy(){u&&(clearTimeout(u),u=null)}})})},exports.blockRunnerPlugin=tt,exports.calculateBackoff=V,exports.canResume=function(t){var e;return t.status===exports.RunnerStatus.IDLE&&!!(null===(e=t.unitsInProgress)||void 0===e?void 0:e.some((t=>t.status!==exports.UnitStatus.DONE&&t.status!==exports.UnitStatus.ERROR)))},exports.cancelActiveRequest=R,exports.cancelAutoCompleteRequest=$t,exports.cancelTask=function(t){R(t),t.dispatch(t.state.tr.setMeta(I,{type:exports.CompleteActionType.CANCEL_TASK}))},exports.clearError=function(t){t.dispatch(t.state.tr.setMeta(I,{type:exports.CompleteActionType.CLEAR_ERROR}))},exports.completePlugin=Xt,exports.completePluginKey=P,exports.completePluginV2=b,exports.completeV2Key=I,exports.countSyllables=ct,exports.createApiConfig=function(t){var e,o;return{apiKey:t.apiKey,endpoint:null!==(e=t.endpoint)&&void 0!==e?e:T,model:null!==(o=t.model)&&void 0!==o?o:y}},exports.createBlockRunnerKey=et,exports.createGrammarApiConfig=function(t){var e,o;return{apiKey:t.apiKey,endpoint:null!==(e=t.endpoint)&&void 0!==e?e:f,model:null!==(o=t.model)&&void 0!==o?o:y}},exports.createGrammarProcessor=Ut,exports.createInitialState=Y,exports.createLinkDetectorPlugin=function(){const t=tt({pluginKey:rt,unitProcessor:nt,decorationFactory:ot,initialContextState:{}});return new a.Plugin({key:rt,state:t.spec.state,props:Object.assign(Object.assign({},t.spec.props),{handleDOMEvents:{click:(t,e)=>{const o=e.target;if(o.classList.contains("link-detected")){const s=t.posAtDOM(o,0),n=rt.getState(t.state);if(n){const t=n.decorations.find((t=>t.from<=s&&t.to>=s&&t.spec.url));if(null==t?void 0:t.spec.url)return window.open(t.spec.url,"_blank"),e.preventDefault(),!0}}return!1}}}),view:t.spec.view})},exports.createRandomProcessor=t=>(e,o)=>i.__awaiter(void 0,void 0,void 0,(function*(){var e,s,n;const r=t(),a=null!==(e=r.minDelay)&&void 0!==e?e:500,i=null!==(s=r.maxDelay)&&void 0!==s?s:3e3,c=null!==(n=r.errorRate)&&void 0!==n?n:.3,p=It(a,i);yield Ot(p);return Math.random()<c?{error:new Error(`Random error after ${p}ms (attempt ${o.metadata.attempt})`)}:{data:{processingTime:p,success:!0,message:`Processed "${o.text.slice(0,20)}..." in ${p}ms`}}})),exports.createRandomProcessorPlugin=function(t={}){return tt({pluginKey:Pt,unitProcessor:bt,decorationFactory:ht,widgetFactory:Rt,initialContextState:Object.assign(Object.assign({},vt),t),options:{batchSize:2,maxRetries:3,backoffBase:2e3}})},exports.createSentenceLengthPlugin=function(t={}){return tt({pluginKey:At,unitProcessor:yt,decorationFactory:xt,initialContextState:Object.assign(Object.assign({},Ct),t)})},exports.createSentenceLengthProcessor=t=>(e,o)=>i.__awaiter(void 0,void 0,void 0,(function*(){var e,s;const n=t(),r=null!==(e=n.warningThreshold)&&void 0!==e?e:25,a=null!==(s=n.errorThreshold)&&void 0!==s?s:40;return{data:ft(o.text,r,a)}})),exports.createUnitsFromDocument=$,exports.createWordComplexityPlugin=function(t={}){return tt({pluginKey:mt,unitProcessor:lt,decorationFactory:it,initialContextState:Object.assign(Object.assign({},dt),t)})},exports.createWordComplexityProcessor=t=>(e,o)=>i.__awaiter(void 0,void 0,void 0,(function*(){var e,s;const n=t(),r=null!==(e=n.moderateThreshold)&&void 0!==e?e:3,a=null!==(s=n.highThreshold)&&void 0!==s?s:4;return{data:ut(o.text,r,a)}})),exports.defaultAutoCompleteOptions=Ht,exports.defaultCompleteOptions={maxSelection:1e3},exports.defaultCompleteV2Options=E,exports.defaultOptions=v,exports.defaultRunnerOptions=N,exports.deselectSuggestion=kt,exports.discardSuggestion=Lt,exports.dismissAutoCompletion=function(t){$t(t),t.dispatch(t.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.DISMISS}))},exports.dispatchAction=W,exports.executeParallel=X,exports.extractTextWithMapping=L,exports.getAutoCompleteState=function(t){return Yt.getState(t.state)},exports.getChangedRegions=(t,e)=>{if(t===e)return{start:t.length,end:t.length,oldStart:t.length,oldEnd:t.length,oldText:"",newText:""};const o=c(t,e),s=o[0],n=s[0]===c.EQUAL?s[1].length-1:0,r=((t,e)=>{if(e[e.length-1][0]!==c.EQUAL)return t.length;const o=e.slice(0,e.length-1);let s=0;for(const t of o){const[e,o]=t;e===c.EQUAL&&(s+=o.length),e===c.DELETE&&(s+=o.length)}return s})(t,o),a=t.lastIndexOf("\n",n),i=t.indexOf("\n",r),p=-1===a?0:a+1,u=-1===i?t.length:i,l=t.slice(p,u),d=e.slice(p,e.length-(t.length-u));return{start:p,end:p+d.length,oldStart:p,oldEnd:u,oldText:l,newText:d}},exports.getCompleteState=function(t){return I.getState(t.state)},exports.getProgress=function(t){var e;if(t.status!==exports.RunnerStatus.ACTIVE)return{completed:0,total:0,decorations:t.decorations.length};const o=null!==(e=t.unitsInProgress)&&void 0!==e?e:[];return{completed:o.filter((t=>t.status===exports.UnitStatus.DONE||t.status===exports.UnitStatus.ERROR)).length,total:o.length,decorations:t.decorations.length}},exports.getSelectedDecoration=function(t,e){const o=e.getState(t.state);if(null==o?void 0:o.contextState.selectedSuggestionId)return Nt(t,e,o.contextState.selectedSuggestionId)},exports.getUnitById=H,exports.getUnitsInRange=k,exports.grammarDecorationFactory=Dt,exports.grammarDecorationTransformer=wt,exports.grammarRequest=A,exports.grammarSuggestPluginKey=D,exports.grammarSuggestPluginV2=function(t,e={}){var o;const{apiEndpoint:s,model:n,fallback:r,batchSize:i=4,maxRetries:c=3,backoffBase:p=2e3,debounceMs:u=1e3,createPopup:d=Vt}=e,m=r?function(t){const{primaryModel:e,fallbackModel:o,failureThreshold:s}=t;let n=0;return{getCurrentModel:()=>o&&s>0&&n>=s?o:e,handleSuccess(){n=0},handleFailure(){o&&n++}}}({primaryModel:n,fallbackModel:r.fallbackModel,failureThreshold:null!==(o=r.failureThreshold)&&void 0!==o?o:3}):void 0,g=Ut({apiKey:t,apiEndpoint:s,model:n,modelStateManager:m}),x=tt({pluginKey:Ft,unitProcessor:g,decorationFactory:Dt,decorationTransformer:wt,widgetFactory:Mt,initialContextState:Kt,options:{batchSize:i,maxRetries:c,backoffBase:p,dirtyHandling:{debounceDelay:u}}});return new a.Plugin({key:Ft,state:x.spec.state,props:Object.assign(Object.assign({},x.spec.props),{decorations(e){var o;const r=null===(o=x.spec.props)||void 0===o?void 0:o.decorations,a=r?r.call(x,e):l.DecorationSet.empty;if("react"===d)return a;const i=Ft.getState(e);if(!(null==i?void 0:i.contextState.selectedSuggestionId))return a;const c=i.decorations.find((t=>t.spec.id===i.contextState.selectedSuggestionId));if(!c)return a;const p=c.spec,u=l.Decoration.widget(c.from,((e,o)=>{const r=o();return void 0===r?document.createElement("div"):d(e,c,r,(()=>_t(e,Ft,c.spec.id)),(()=>Lt(e,Ft,c.spec.id)),(()=>Gt(t,p.originalText,p.replacement,{endpoint:s,model:n,modelStateManager:m})))}),{id:c.spec.id,side:-1,stopEvent:()=>!0});return a.add(e.doc,[u])},handleClick(t,e,o){const s=Ft.getState(t.state);if(!s)return!1;const n=s.decorations.find((t=>t.from<=e&&e<=t.to));return n?(n.spec.id===s.contextState.selectedSuggestionId||jt(t,Ft,n.spec.id),!1):(s.contextState.selectedSuggestionId&&kt(t,Ft),!1)}}),view:x.spec.view})},exports.grammarSuggestV2Key=Ft,exports.grammarWidgetFactory=Mt,exports.handleAction=Q,exports.hasActiveRequest=function(t){return h.has(t)},exports.hasAutoCompleteRequest=function(t){return qt.has(t)},exports.hasAutoCompletion=function(t){const e=Yt.getState(t.state);return!!(null==e?void 0:e.suggestion)},exports.hasUnitsToProcess=Z,exports.isAutoCompleteEnabled=function(t){var e;const o=Yt.getState(t.state);return null!==(e=null==o?void 0:o.enabled)&&void 0!==e&&e},exports.linkDetectorDecorationFactory=ot,exports.linkDetectorKey=rt,exports.linkDetectorProcessor=nt,exports.mergeOptions=_,exports.pauseRunner=function(t,e){W(t,e,{type:exports.ActionType.FINISH})},exports.randomProcessor=bt,exports.randomProcessorDecorationFactory=ht,exports.randomProcessorKey=Pt,exports.randomProcessorWidgetFactory=Rt,exports.rejectResult=function(t){t.dispatch(t.state.tr.setMeta(I,{type:exports.CompleteActionType.REJECT_RESULT}))},exports.remapPositions=F,exports.requestHint=Gt,exports.resumeRunner=function(t,e){W(t,e,{type:exports.ActionType.RESUME})},exports.selectSuggestion=jt,exports.sentenceLengthDecorationFactory=xt,exports.sentenceLengthKey=At,exports.sentenceLengthProcessor=yt,exports.setAutoCompleteEnabled=function(t,e){e||$t(t),t.dispatch(t.state.tr.setMeta(Yt,{type:exports.AutoCompleteActionType.SET_ENABLED,enabled:e}))},exports.setCompleteEnabled=(t,e)=>{t.dispatch(t.state.tr.setMeta(P,{type:"setEnabled",enabled:e}))},exports.setEnabled=function(t,e){e||R(t),t.dispatch(t.state.tr.setMeta(I,{type:exports.CompleteActionType.SET_ENABLED,enabled:e}))},exports.setGrammarSuggestEnabled=(t,e)=>{t.dispatch(t.state.tr.setMeta(D,{type:exports.GrammarSuggestMetaType.setEnabled,enabled:e}))},exports.sleep=B,exports.startTask=function(t,e,o){const s=t.state.selection;t.dispatch(t.state.tr.setMeta(I,{type:exports.CompleteActionType.START_TASK,taskType:e,params:o,selection:s.empty?void 0:s}))},exports.streamingRequest=C,exports.textToDocPos=j,exports.updateUnit=q,exports.wordComplexityDecorationFactory=it,exports.wordComplexityKey=mt,exports.wordComplexityProcessor=lt;
|
package/dist/styles/styles.css
CHANGED
|
@@ -1,64 +1,163 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/* Grammar Suggestion V2 styles */
|
|
2
|
+
|
|
3
|
+
.grammarSuggestionV2 {
|
|
4
|
+
background-color: rgba(76, 175, 80, 0.3);
|
|
5
|
+
border-radius: 2px;
|
|
6
|
+
cursor: pointer;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
.grammarSuggestionV2.removalSuggestionV2 {
|
|
10
|
+
background-color: rgba(244, 67, 54, 0.3);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
.grammarSuggestionV2-selected {
|
|
14
|
+
background-color: rgba(33, 150, 243, 0.4);
|
|
15
|
+
box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.5);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/* Grammar Widget V2 styles */
|
|
19
|
+
|
|
20
|
+
.grammarWidgetV2 {
|
|
21
|
+
position: absolute;
|
|
22
|
+
left: 0;
|
|
23
|
+
top: 0;
|
|
24
|
+
transform: translateX(-100%) translateX(-8px);
|
|
25
|
+
padding: 2px 8px;
|
|
26
|
+
font-size: 12px;
|
|
27
|
+
border-radius: 4px;
|
|
28
|
+
white-space: nowrap;
|
|
29
|
+
z-index: 10;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
.grammarWidgetV2.queued,
|
|
33
|
+
.grammarWidgetV2.processing {
|
|
34
|
+
background: #e3f2fd;
|
|
35
|
+
color: #1565c0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
.grammarWidgetV2.backoff {
|
|
39
|
+
background: #fff3e0;
|
|
40
|
+
color: #e65100;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
.grammarWidgetV2.error {
|
|
44
|
+
background: #ffebee;
|
|
45
|
+
color: #c62828;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/* Grammar Popup V2 styles */
|
|
49
|
+
|
|
50
|
+
.grammarPopupV2 {
|
|
51
|
+
position: absolute;
|
|
52
|
+
background: white;
|
|
53
|
+
border: 1px solid #ccc;
|
|
54
|
+
border-radius: 6px;
|
|
55
|
+
padding: 8px 12px;
|
|
56
|
+
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
|
|
57
|
+
z-index: 1000;
|
|
58
|
+
display: flex;
|
|
59
|
+
flex-direction: column;
|
|
60
|
+
gap: 8px;
|
|
61
|
+
font-size: 14px;
|
|
62
|
+
max-width: 400px;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
.grammarPopupV2-mainRow {
|
|
66
|
+
display: flex;
|
|
67
|
+
align-items: center;
|
|
68
|
+
gap: 8px;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
.grammarPopupV2-original {
|
|
72
|
+
color: #c62828;
|
|
73
|
+
text-decoration: line-through;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
.grammarPopupV2-arrow {
|
|
77
|
+
color: #666;
|
|
3
78
|
}
|
|
4
79
|
|
|
5
|
-
.
|
|
6
|
-
|
|
80
|
+
.grammarPopupV2-replacement {
|
|
81
|
+
color: #2e7d32;
|
|
82
|
+
font-weight: 500;
|
|
7
83
|
}
|
|
8
84
|
|
|
9
|
-
.
|
|
10
|
-
|
|
85
|
+
.grammarPopupV2-accept,
|
|
86
|
+
.grammarPopupV2-discard {
|
|
87
|
+
width: 28px;
|
|
88
|
+
height: 28px;
|
|
89
|
+
border: none;
|
|
90
|
+
border-radius: 4px;
|
|
91
|
+
cursor: pointer;
|
|
92
|
+
font-size: 14px;
|
|
93
|
+
display: flex;
|
|
94
|
+
align-items: center;
|
|
95
|
+
justify-content: center;
|
|
11
96
|
}
|
|
12
97
|
|
|
13
|
-
.
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
position: absolute;
|
|
17
|
-
padding: 5px;
|
|
18
|
-
border-radius: 5px;
|
|
19
|
-
z-index: 1000;
|
|
20
|
-
background: white;
|
|
21
|
-
height: 50px;
|
|
22
|
-
display: flex;
|
|
23
|
-
justify-content: center;
|
|
24
|
-
align-items: center;
|
|
25
|
-
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
|
|
98
|
+
.grammarPopupV2-accept {
|
|
99
|
+
background: #e8f5e9;
|
|
100
|
+
color: #2e7d32;
|
|
26
101
|
}
|
|
27
102
|
|
|
28
|
-
.
|
|
29
|
-
|
|
30
|
-
padding: 0.5rem;
|
|
31
|
-
border-radius: 0.5rem;
|
|
103
|
+
.grammarPopupV2-accept:hover {
|
|
104
|
+
background: #c8e6c9;
|
|
32
105
|
}
|
|
33
106
|
|
|
34
|
-
.
|
|
35
|
-
|
|
107
|
+
.grammarPopupV2-discard {
|
|
108
|
+
background: #ffebee;
|
|
109
|
+
color: #c62828;
|
|
36
110
|
}
|
|
37
111
|
|
|
38
|
-
.
|
|
39
|
-
|
|
40
|
-
width: 2rem;
|
|
112
|
+
.grammarPopupV2-discard:hover {
|
|
113
|
+
background: #ffcdd2;
|
|
41
114
|
}
|
|
42
115
|
|
|
43
|
-
.
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
116
|
+
.grammarPopupV2-hint {
|
|
117
|
+
width: 28px;
|
|
118
|
+
height: 28px;
|
|
119
|
+
border: none;
|
|
120
|
+
border-radius: 4px;
|
|
121
|
+
cursor: pointer;
|
|
122
|
+
font-size: 14px;
|
|
123
|
+
font-weight: bold;
|
|
124
|
+
display: flex;
|
|
125
|
+
align-items: center;
|
|
126
|
+
justify-content: center;
|
|
127
|
+
background: #e3f2fd;
|
|
128
|
+
color: #1565c0;
|
|
52
129
|
}
|
|
53
130
|
|
|
54
|
-
.
|
|
55
|
-
|
|
131
|
+
.grammarPopupV2-hint:hover {
|
|
132
|
+
background: #bbdefb;
|
|
56
133
|
}
|
|
57
134
|
|
|
58
|
-
.
|
|
59
|
-
|
|
135
|
+
.grammarPopupV2-hintArea {
|
|
136
|
+
padding: 8px;
|
|
137
|
+
background: #f5f5f5;
|
|
138
|
+
border-radius: 4px;
|
|
139
|
+
border: 1px solid #e0e0e0;
|
|
60
140
|
}
|
|
61
141
|
|
|
62
|
-
.
|
|
63
|
-
|
|
142
|
+
.grammarPopupV2-hintText {
|
|
143
|
+
color: #333;
|
|
144
|
+
line-height: 1.4;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
.grammarPopupV2-loading {
|
|
148
|
+
color: #666;
|
|
149
|
+
font-style: italic;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
.grammarPopupV2-hintError {
|
|
153
|
+
color: #c62828;
|
|
154
|
+
font-style: italic;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/* Auto-complete ghost text */
|
|
158
|
+
|
|
159
|
+
.autoCompleteGhostText {
|
|
160
|
+
color: #9ca3af;
|
|
161
|
+
opacity: 0.7;
|
|
162
|
+
pointer-events: none;
|
|
64
163
|
}
|