notemend 0.1.27 → 0.1.29

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.
@@ -1,7 +1,7 @@
1
- import{readFileSync as lt,existsSync as Y,statSync as jt,readdirSync as Nt,watch as Ot}from"node:fs";import{mask as kt}from"../store/mask.mjs";import{join as _,isAbsolute as $t}from"node:path";import{isIP as ut}from"node:net";import{pathToFileURL as At}from"node:url";import{openStore as It,retry as Bt,retryThread as Et,CABINET as ft,session as tt}from"../store/cloud.mjs";import{mentionsIn as Tt,cleanAssignee as et,cleanEmoji as bt,MAX_REACTIONS as Pt,STAGES as dt,toAgent as nt}from"../store/thread.mjs";import{fileFrame as rt,react as Ct,shotName as Dt}from"../store/comments.mjs";import{stateOf as _t}from"../store/status.mjs";import{CATEGORIES as Lt,categoryOf as Ft}from"../store/categories.mjs";import{BREAKPOINTS as Mt,DEVICES as Rt,ICONS as mt,SHELLS as pt,BROWSERS as gt}from"../presets.mjs";const zt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",webm:"video/webm",m4a:"audio/mp4",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},ht=t=>t.split(".").slice(0,2).map(Number).reduce((e,f)=>e*100+(Number.isNaN(f)?9999:f),0),Ht=(t,e)=>{try{const p=lt($t(e)?e:_(t,e),"utf8").match(/title="([^"]+)"|\btitle:\s*["'`]([^"'`]+)["'`]/);return(p?.[1]??p?.[2])?.split("\u2014").pop()?.trim()||null}catch{return null}};function ie(t){const e=["app","src/app"].map(c=>_(/* turbopackIgnore: true */ t,c)).find(Y),f=[],p=(c,y)=>{for(const l of Nt(c,{withFileTypes:!0})){const u=l.name;if(l.isDirectory()){if(/^[_@]|^\(\./.test(u))continue;p(_(c,u),/^\(.+\)$/.test(u)?y:[...y,u])}else/^page\.(jsx?|tsx?|mdx?)$/.test(u)&&f.push({origin:"project",type:"page",pattern:"/"+y.join("/"),entrypoint:_(c,u)})}};return e&&p(e,[]),f}const Gt=t=>t[0].toUpperCase()+t.slice(1).replace(/[-_]+/g," ");function Jt({root:t,options:e,routes:f}){const p=e.pages??{},c=(n,w,L)=>({route:n,name:w,label:w.replace(/^[\d.]+[A-Z]?\.\s*/,""),group:L}),y=f.filter(n=>n.origin==="project"&&n.type==="page"&&!n.pattern.includes("[")).map(n=>({route:n.pattern.replace(/\/+$/,"")||"/",entrypoint:n.entrypoint})),l=new Set(y.map(n=>n.route)),u=[...y,...Object.keys(p).filter(n=>!l.has(n)).map(n=>({route:n}))],T={};for(const{route:n}of u){const w=n.split("/")[1];w&&(T[w]=(T[w]||0)+1)}const B=n=>{const w=n.split("/")[1];return w&&T[w]>1?Gt(w):"Pages"},C=e.groups?()=>e.groups[e.groups.length-1]:B,E=u.map(({route:n,entrypoint:w})=>{const[L,U]=p[n]??[];return c(n,L??(w&&Ht(t,w))??n,U??C(n))}),H=e.groups??[...new Set([...Object.values(p).map(([,n])=>n).filter(Boolean),"Pages",...E.map(n=>n.group).sort()])],G=E.sort((n,w)=>H.indexOf(n.group)-H.indexOf(w.group)||ht(n.name)-ht(w.name)||n.route.localeCompare(w.route)),J=(e.breakpoints??Mt).map(n=>({id:n.id,label:n.label,min:n.min,ideal:n.ideal,max:Number.isFinite(n.max)?n.max:null,icon:n.icon??mt[n.id]??mt.desktop})),Z=(e.devices??Rt).filter(n=>n.w>0&&n.h>0&&pt.includes(n.shell)&&gt.includes(n.browser)?!0:(console.warn(`[notemend] device "${n.id}" skipped: it needs w and h, shell (${pt.join(", ")}) and browser (${gt.join(", ")})${n.frame?"; `frame` pictures were replaced by shell + browser in 0.3":""}`),!1));return{pages:G,groups:H.filter(n=>G.some(w=>w.group===n)),breakpoints:J,devices:Z,categories:Lt,sanity:!!e.sanity,shortcuts:e.shortcuts!==!1,ignore:e.ignore??[],grid:{container:"container",grid:"grid",columns:12,...e.grid},zIndex:e.zIndex??2000000020}}const Ut=t=>{const e=_(t,"notemend.config.mjs");let f=0,p={};return async()=>{if(!Y(e))return{};const c=jt(e).mtimeMs;if(c===f)return p;f=c;try{const{default:y,...l}=await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${At(e).href}?t=${c}`);p={...l,...y}}catch(y){console.warn(`[notemend] notemend.config.mjs: ${y.message}`)}return p}},Wt=t=>{const e=String(t.headers.host||"").toLowerCase(),f=e.startsWith("[")?e.slice(1,e.indexOf("]")):e.replace(/:\d+$/,"");return f.includes(":")?ut(f)===6:!f||!f.includes(".")||ut(f)===4||/\.(localhost|local|test|internal|lan|home\.arpa)$/.test(f)},x=(t,e)=>String(t??"").replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,e),Vt=t=>({route:x(t.route,500),text:String(t.text??"").slice(0,1e4),selector:x(t.selector,2e3),rx:Number.isFinite(t.rx)?t.rx:0,ry:Number.isFinite(t.ry)?t.ry:0,label:x(t.label,200),ctx:x(t.ctx,120),breakpoint:x(t.breakpoint,40),browser:x(t.browser,80),device:x(t.device,80),tag:x(t.tag,40),classes:Array.isArray(t.classes)?t.classes.slice(0,20).map(e=>x(e,80)):[],nth:Number.isInteger(t.nth)?t.nth:null,category:x(t.category,40),...["urgent","high","normal","low"].includes(t.priority)?{priority:t.priority}:{},...t.shared===!0?{shared:!0}:{},...Number.isInteger(t.from?.id)&&t.from.id>0?{from:{id:t.from.id}}:{},viewport:t.viewport&&Number.isFinite(t.viewport.w)&&Number.isFinite(t.viewport.h)?{w:t.viewport.w,h:t.viewport.h}:null,...et(t.assignee)?{assignee:et(t.assignee)}:{},...dt.includes(t.stage)?{stage:t.stage}:{},...typeof t.host=="string"&&/^[a-z0-9.-]{1,120}(:\d{1,5})?$/i.test(t.host)?{host:t.host.toLowerCase()}:{},...Array.isArray(t.logs)&&t.logs.length?{logs:t.logs.slice(-20).map(e=>({at:x(e?.at,30),kind:["console","error","rejection","network"].includes(e?.kind)?e.kind:"console",text:kt(x(e?.text,500))})).filter(e=>e.text)}:{},...t.suggest&&typeof t.suggest.from=="string"&&typeof t.suggest.to=="string"&&t.suggest.to.trim()?{suggest:{from:t.suggest.from.slice(0,2e3),to:t.suggest.to.slice(0,2e3)}}:{}}),Kt=t=>{const e={};if((t.status==="open"||t.status==="done")&&(e.status=t.status),t.status==="open"&&Object.assign(e,{reopenedAt:new Date().toISOString(),reopenedBy:"you"}),"doneBy"in t&&(e.doneBy=t.doneBy==="you"?"you":null),typeof t.category=="string"&&(e.category=Ft(t.category).id),"priority"in t&&(e.priority=["urgent","high","normal","low"].includes(t.priority)?t.priority:null),typeof t.shared=="boolean"&&(e.shared=t.shared||null),t.client===!1&&(e.client=null),"assignee"in t&&(e.assignee=et(t.assignee)),"stage"in t&&(e.stage=dt.includes(t.stage)?t.stage:null),typeof t.archived=="boolean"&&(e.archived=t.archived),t.move&&typeof t.move=="object"&&typeof t.move.selector=="string"){const f=t.move,p=c=>Number.isFinite(c)?Math.min(1,Math.max(0,c)):.5;Object.assign(e,{selector:x(f.selector,2e3),rx:p(f.rx),ry:p(f.ry),label:x(f.label,200),ctx:x(f.ctx,120),tag:x(f.tag,40),classes:Array.isArray(f.classes)?f.classes.slice(0,20).map(c=>x(c,80)):[],nth:Number.isInteger(f.nth)?f.nth:null})}return e},ot=t=>{const e=t.headers.origin;if(!e)return!1;try{return new URL(e).host!==t.headers.host}catch{return!0}};function Xt({root:t,options:e,routes:f,open:p=()=>It(t),crossOrigin:c=!1}){const y=Ut(t),l=(o,h=200)=>({status:h,type:"application/json",body:JSON.stringify(o)}),u=(o,h)=>({status:o,type:"text/plain; charset=utf-8",body:h}),T=async o=>{const h=await o.body();if(h.length>45e5)throw Object.assign(new Error("too large"),{status:413});try{return h.length?JSON.parse(h.toString("utf8")):{}}catch{throw Object.assign(new Error("not JSON"),{status:400})}},B=async(o,h,r)=>{const s=async d=>{const a=await h(d);if(a.status>=400)throw Object.assign(new Error("not written"),{out:a});return a};try{if(o.cloud)return await(r!=null&&o.thread?Et(o,r,s):Bt(o,s));const d=o.load(),a=await s(d);return o.save(d),a}catch(d){if(d.out)return d.out;throw d}finally{E=null,L++,U()&&V()}},C=new Set;let E=null,H=0,G=!1,J=!1,Z=null,n=null,w=0,L=0;const U=()=>C.size>0||Date.now()-w<3e4,V=async()=>{if(c)return;if(G){J=!0;return}G=!0,clearTimeout(Z);let o=!1;try{const h=await p();o=!!h.cloud;const r=L,s=h.version?String(await h.version()):null;if(r!==L)J=!0;else if(H=Date.now(),s!==E){E=s;for(const d of C)d(s)}if(!o&&!n&&U()&&Y(_(t,"feedback")))try{n=Ot(_(t,"feedback"),(d,a)=>{String(a).startsWith("comments.json")&&V()}),n.on("error",()=>{n?.close(),n=null})}catch{n=null}}catch{}if(G=!1,J)return J=!1,V();U()?Z=setTimeout(V,o?1500:n?1e3:250):(n?.close(),n=null)},yt=o=>(C.add(o),E!=null&&o(E),V(),()=>{C.delete(o),w=Date.now()}),wt=()=>U()&&E!=null&&Date.now()-H<3e3?E:null,st=new Map,vt=async(o,h)=>{if(o.method!=="GET"&&!c&&ot(o))return u(403,"Cross-origin write refused");const r=await p();if(o.method==="GET"){const i=h.searchParams.get("route"),A=h.searchParams.get("since"),I=wt();if(A!=null&&r.version&&A===(I??String(await r.version())))return{status:204,type:"text/plain",body:""};const R=h.searchParams.get("open")==="1",k=`${i??""}|${R}`,b=I!=null&&st.get(k);if(b&&b.v===I)return b.res;const $=await r.load(R?{open:!0}:void 0);let N=i?$.comments.filter(W=>W.route===i):$.comments;R&&(N=N.filter(W=>_t(W)!=="done")),N=N.map(({logs:W,...z})=>z);const D=r.versionOf?r.versionOf($):null,Q=l({version:D==null?null:String(D),comments:N,listening:$.listening??null,turbo:$.turbo??null});return!c&&D!=null&&st.set(k,{v:String(D),res:Q}),Q}const s=o.method==="DELETE"?null:await T(o);let d=null,a=null;const F=o.method==="POST"||!!s?.reply?.trim?.(),M=r.cloud&&s?(F?r.people():r.me().then(i=>({me:i,team:[]}))).then(i=>{d=i,a=i.me}).catch(i=>i):Promise.resolve(),at=async()=>{const i=await M;if(i instanceof Error)throw i},it=i=>{if(a&&i){i.by=a.email,i.byName=a.name;const A=Tt(i.text,d.team.filter(I=>I.email!==a.email));A.length&&(i.mentions=A)}return i};if(o.method==="POST"){const{image:i,images:A,before:I,...R}=s,k=Vt(R);return k.text.trim()?/^\/(?![\/\\])/.test(k.route)?B(r,async b=>{await at(),d?.client&&(k.client=!0,nt(k.assignee)&&delete k.assignee,k.stage==="approved"&&delete k.stage);const $=it(r.add(b,k));a&&nt($.assignee)&&($.handedBy=a.email);for(const N of[].concat(A??i??[]))await r.attach(b,$.id,N);return await rt(r,b,$.id,I,"before"),l($,201)}):l({error:"route must be a path"},400):l({error:"empty comment"},400)}if(o.method==="PATCH"){const i=s;if(i.turbo==="on"||i.turbo==="off")return B(r,async g=>(g.turbo={paused:i.turbo==="off",at:new Date().toISOString()},l({turbo:g.turbo})));if(Array.isArray(i.push)||Array.isArray(i.unpush)){const g=j=>(Array.isArray(j)?j:[]).map(Number).filter(m=>Number.isInteger(m)&&m>0).slice(0,500);return B(r,async j=>{const m=new Set(j.turbo?.push?.ids??[]);for(const P of g(i.push))m.add(P);for(const P of g(i.unpush))m.delete(P);const O=P=>j.comments.some(ct=>ct.id===P&&ct.status!=="done"),K=new Set((j.turbo?.batch?.ids??[]).filter(O)),X=!K.size;for(const P of g(i.push))K.add(P);for(const P of g(i.unpush))K.delete(P);const q=new Date().toISOString();return j.turbo={...j.turbo??{paused:!0},push:{at:q,ids:[...m]},batch:{at:X?q:j.turbo?.batch?.at??q,ids:[...K]}},l({turbo:j.turbo})})}const{id:A,reply:I,image:R,images:k,removeImage:b,uploaded:$,edit:N,unsay:D,before:Q,after:W,react:z,...xt}=i,v=Number(A);if(!Number.isInteger(v))return l({error:"bad id"},400);if(z){const g=bt(z.emoji),j=typeof z.at=="string"&&z.at?z.at:null;return g?r.cloud?r.react(v,j,g).then(l,m=>l({error:m.message},m.status>=400&&m.status<500?m.status:500)):B(r,async m=>{const O=Ct(m,v,j,g,"you");return O===!1?l({error:`${Pt} kinds of reaction at most`},400):O?l(O):l({error:`no message to react to in #${v}`},404)},v):l({error:"not an emoji"},400)}const S=Kt(xt);return B(r,async g=>{if(await at(),N){const m=g.comments.find(X=>X.id===Number(v)),O=N.at?m?.replies?.find(X=>X.at===N.at):m;if(a&&O?.by&&O.by!==a.email||!(N.text?.trim?.()&&r.edit(g,v,N.at??null,N.text.trim().slice(0,1e4))))return l({error:`no message of yours to edit in #${v}`},404)}if(typeof D=="string"){const m=g.comments.find(O=>O.id===v)?.replies?.find(O=>O.at===D);return!m||a&&m.by&&m.by!==a.email||!r.unsay(g,v,D)?l({error:`no reply of yours to delete in #${v}`},404):l(g.comments.find(O=>O.id===v))}I?.trim?.()&&it(r.reply(g,v,"you",I.trim().slice(0,1e4))?.replies.at(-1));for(const m of[].concat(k??R??[]))await r.attach(g,v,m);for(const m of[].concat($??[]))if(r.adopt&&!await r.adopt(g,v,m))return l({error:`${m} did not arrive`},400);for(const m of[].concat(b||[]))await r.detach(g,v,m);if(await rt(r,g,v,Q,"before"),await rt(r,g,v,W,"after"),a&&S.status==="done"&&Object.assign(S,{confirmedBy:a.email,confirmedAt:new Date().toISOString()}),a&&S.status==="open"&&Object.assign(S,{confirmedBy:null,confirmedAt:null,reopenedBy:a.email}),"archived"in S){const m=S.archived;delete S.archived,Object.assign(S,m?{archivedAt:new Date().toISOString(),archivedBy:a?.email??null}:{archivedAt:null,archivedBy:null})}S.status==="open"&&Object.assign(S,{archivedAt:null,archivedBy:null}),a&&S.stage==="review"&&(S.stageBy=a.email),a&&"assignee"in S&&(S.handedBy=nt(S.assignee)?a.email:null);const j=Object.keys(S).length||!I?r.patch(g,v,S):g.comments.find(m=>m.id===Number(v));return j?l(j):l({error:`no comment #${v}`},404)},v)}if(o.method==="DELETE"){const i=Number(h.searchParams.get("id"));return B(r,async A=>await r.remove(A,i)?l({ok:!0,id:i}):l({error:`no comment #${i}`},404))}return u(405,"Method not allowed")},St=(o,h)=>{const r=h.replace(/^.*[/\\]/,""),s=r.split(".").pop()?.toLowerCase()??"",d=zt[s]??(Dt(r)?"application/octet-stream":null);if(!/^[\w.-]+$/.test(r)||!d)return u(400,"Bad name");const a=_(o,r);return Y(a)?{status:200,type:d,body:lt(a)}:u(404,"Not found")};return async o=>{const h=new URL(o.url,"http://devbar"),r=h.pathname.slice(10);if(!c&&!Wt(o))return u(403,"Notemend answers local addresses only");try{if(r==="config"){const s=Jt({root:t,options:{...await y(),...e},routes:f()}),d=await p();return d.cloud&&Object.assign(s,await d.people().catch(a=>{if(a.said)throw a;return{}})),(d.cloud||await tt().catch(()=>null))&&(s.voice=!0),l(s)}if(r==="transcribe"&&o.method==="POST"){if(!c&&ot(o))return u(403,"Cross-origin write refused");const s=await p(),d=s.cloud?await s.token():(await tt().catch(()=>null))?.access_token;if(!d)return u(401,"Voice replies need Notemend \u2014 run `npx notemend login`.");const{audio:a}=await T(o),F=/^data:(audio\/(?:webm|mp4))(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(a||""));if(!F)return u(400,"Not a recording");const M=await fetch(`${ft}/api/transcribe`,{method:"POST",body:Buffer.from(F[2],"base64"),headers:{authorization:`Bearer ${d}`,"content-type":F[1]}});return{status:M.status,type:"application/json",body:await M.text()}}if(r==="translate"&&o.method==="POST"){if(!c&&ot(o))return u(403,"Cross-origin write refused");const s=await p(),d=s.cloud?await s.token():(await tt().catch(()=>null))?.access_token;if(!d)return u(401,"Translating needs Notemend \u2014 run `npx notemend login`.");const{text:a,to:F}=await T(o),M=await fetch(`${ft}/api/translate`,{method:"POST",body:JSON.stringify({text:a,to:F}),headers:{authorization:`Bearer ${d}`,"content-type":"application/json"}});return{status:M.status,type:"application/json",body:await M.text()}}if(r==="comments")return await vt(o,h);if(r==="events"&&!c)return{status:200,type:"text/event-stream",body:"",stream:yt};if(r==="image"){const s=await p(),d=(h.searchParams.get("name")||"").replace(/^.*[/\\]/,"");return s.cloud&&/^[\w.-]+$/.test(d)&&await s.fetchImage(d).catch(()=>null),St(s.imageDir,d)}return u(404,"Not found")}catch(s){return s.status===400||s.status===413?u(s.status,s.message):s.said?u(s.status,s.said):s.status===403?u(403,String(s.message).replace(/^notemend: /,"").replace(/ \(403\)$/,"")):(console.error("[notemend]",s),u(500,"Something went wrong on our side. Try again in a moment."))}}}function ce(t){const e=Xt(t),f=p=>new Promise((c,y)=>{const l=[];p.on("data",u=>l.push(u)),p.on("end",()=>c(Buffer.concat(l))),p.on("error",y)});return async function(c,y,l){if(!c.url||!c.url.startsWith("/__devbar/"))return l();const u=await e({method:c.method,url:c.url,headers:c.headers,body:()=>f(c)});if(u.stream){y.writeHead(200,{"content-type":u.type,"cache-control":"no-store",connection:"keep-alive"}),y.write(`retry: 1000
1
+ import{readFileSync as he,existsSync as re,statSync as Ce,readdirSync as _e,watch as De}from"node:fs";import{mask as Me}from"../store/mask.mjs";import{join as J,isAbsolute as Fe}from"node:path";import{isIP as ye}from"node:net";import{pathToFileURL as Le}from"node:url";import{openStore as He,retry as Re,retryThread as ze,CABINET as ue,session as oe,deviceLogin as Ge}from"../store/cloud.mjs";import{mentionsIn as Je,clashOf as Ue,cleanAssignee as fe,cleanBox as We,cleanEmoji as Ve,cut as Y,MAX_REACTIONS as Ke,STAGES as we,threadOf as Xe,toAgent as de}from"../store/thread.mjs";import{fileFrame as me,react as Ze,shotName as xe}from"../store/comments.mjs";import{stateOf as Qe}from"../store/status.mjs";import{CATEGORIES as Ye,categoryOf as qe}from"../store/categories.mjs";import{BREAKPOINTS as et,DEVICES as tt,ICONS as ve,SHELLS as Se,BROWSERS as je}from"../presets.mjs";const nt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",webm:"video/webm",m4a:"audio/mp4",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},Oe=e=>e.split(".").slice(0,2).map(Number).reduce((t,r)=>t*100+(Number.isNaN(r)?9999:r),0),Ne=(e,t)=>{try{const r=he(Fe(t)?t:J(e,t),"utf8"),f=r.match(/\bmetadata\b[^=]*=\s*\{[^}]*?\btitle:\s*["'`]([^"'`$]+)["'`]/)??r.match(/<title>([^<{]+)<\/title>/)??(/\.[jt]sx?$/.test(t)?r.match(/<h1\b[^>]*>\s*([^<{]+?)\s*<\/h1>/):r.match(/title="([^"]+)"|\btitle:\s*["'`]([^"'`]+)["'`]/));return(f?.[1]??f?.[2])?.trim()||null}catch{return null}},be=e=>e.split(/\s+[—–|]\s+/).map(t=>t.trim()).filter(Boolean),rt=(e,t,r)=>{const f=Ne(e,t);if(!f)return null;const i=be(f);return(r?i.filter(m=>m!==r)[0]:i.pop())||null},ot=e=>{const t={};for(const f of e){const i=f?be(f):[];if(i.length>1)for(const m of new Set([i[0],i.at(-1)]))t[m]=(t[m]||0)+1}const[r]=Object.entries(t).sort((f,i)=>i[1]-f[1]);return r?.[1]>1?r[0]:void 0};function Nt(e){const t=["app","src/app"].map(i=>J(/* turbopackIgnore: true */ e,i)).find(re),r=[],f=(i,m)=>{for(const u of _e(i,{withFileTypes:!0})){const l=u.name;if(u.isDirectory()){if(/^[_@]|^\(\./.test(l))continue;f(J(i,l),/^\(.+\)$/.test(l)?m:[...m,l])}else/^page\.(jsx?|tsx?|mdx?)$/.test(l)&&r.push({origin:"project",type:"page",pattern:"/"+m.join("/"),entrypoint:J(i,l)})}};return t&&f(t,[]),r}const $e=e=>e[0].toUpperCase()+e.slice(1).replace(/[-_]+/g," ");function st({root:e,options:t,routes:r}){const f=t.pages??{},i=(n,x,z)=>({route:n,name:x,label:x.replace(/^[\d.]+[A-Z]?\.\s*/,""),group:z}),m=r.filter(n=>n.origin==="project"&&n.type==="page"&&!n.pattern.includes("[")).map(n=>({route:n.pattern.replace(/\/+$/,"")||"/",entrypoint:n.entrypoint})),u=new Set(m.map(n=>n.route)),l=[...m,...Object.keys(f).filter(n=>!u.has(n)).map(n=>({route:n}))],A={};for(const{route:n}of l){const x=n.split("/")[1];x&&(A[x]=(A[x]||0)+1)}const b=n=>{const x=n.split("/")[1];return x&&A[x]>1?$e(x):"Pages"},R=t.groups?()=>t.groups[t.groups.length-1]:b,M=ot(l.map(({entrypoint:n})=>n&&Ne(e,n))),ee=l.map(({route:n,entrypoint:x})=>{const[z,V]=f[n]??[];return i(n,z??(x&&rt(e,x,M))??(n==="/"?"Home":$e(n.split("/").pop())),V??R(n))}),U=t.groups??[...new Set([...Object.values(f).map(([,n])=>n).filter(Boolean),"Pages",...ee.map(n=>n.group).sort()])],W=ee.sort((n,x)=>U.indexOf(n.group)-U.indexOf(x.group)||Oe(n.name)-Oe(x.name)||n.route.localeCompare(x.route)),te=(t.breakpoints??et).map(n=>({id:n.id,label:n.label,min:n.min,ideal:n.ideal,max:Number.isFinite(n.max)?n.max:null,icon:n.icon??ve[n.id]??ve.desktop})),T=(t.devices??tt).filter(n=>n.w>0&&n.h>0&&Se.includes(n.shell)&&je.includes(n.browser)?!0:(console.warn(`[notemend] device "${n.id}" skipped: it needs w and h, shell (${Se.join(", ")}) and browser (${je.join(", ")})${n.frame?"; `frame` pictures were replaced by shell + browser in 0.3":""}`),!1));return{pages:W,groups:U.filter(n=>W.some(x=>x.group===n)),breakpoints:te,devices:T,categories:Ye,sanity:!!t.sanity,shortcuts:t.shortcuts!==!1,ignore:t.ignore??[],grid:{container:"container",grid:"grid",columns:12,...t.grid},zIndex:t.zIndex??2000000020}}const at=e=>{const t=J(e,"notemend.config.mjs");let r=0,f={};return async()=>{if(!re(t))return{};const i=Ce(t).mtimeMs;if(i===r)return f;r=i;try{const{default:m,...u}=await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ `${Le(t).href}?t=${i}`);f={...u,...m}}catch(m){console.warn(`[notemend] notemend.config.mjs: ${m.message}`)}return f}},it=e=>{const t=String(e.headers.host||"").toLowerCase(),r=t.startsWith("[")?t.slice(1,t.indexOf("]")):t.replace(/:\d+$/,"");return r.includes(":")?ye(r)===6:!r||!r.includes(".")||ye(r)===4||/\.(localhost|local|test|internal|lan|home\.arpa)$/.test(r)},w=(e,t)=>Y(String(e??"").replace(/[\u0000-\u001f\u007f]+/g," ").trim(),t),ct=["id","data","aria","alt","title","src","href","head","sib"],q=e=>{if(!e||typeof e!="object")return;const t=Object.fromEntries(ct.filter(r=>typeof e[r]=="string"&&e[r].trim()).map(r=>[r,w(e[r],120)]));return Object.keys(t).length?t:void 0},se=e=>e&&Number.isFinite(e.x)&&Number.isFinite(e.y)?{x:Math.round(Math.min(Math.max(e.x,0),1e5)),y:Math.round(Math.min(Math.max(e.y,0),1e6))}:void 0,ke=e=>e&&typeof e=="object"&&typeof e.selector=="string"?{selector:w(e.selector,2e3),label:w(e.label,200),ctx:w(e.ctx,120),tag:w(e.tag,40),classes:Array.isArray(e.classes)?e.classes.slice(0,20).map(t=>w(t,80)):[],nth:Number.isInteger(e.nth)?e.nth:null,rx:.5,ry:.5,...q(e.fp)?{fp:q(e.fp)}:{}}:void 0,lt=e=>({...q(e.fp)?{fp:q(e.fp)}:{},...se(e.spot)?{spot:se(e.spot)}:{},...ke(e.opener)?{opener:ke(e.opener)}:{}}),ut=e=>({route:w(e.route,500),text:Y(e.text,1e4),selector:w(e.selector,2e3),rx:Number.isFinite(e.rx)?e.rx:0,ry:Number.isFinite(e.ry)?e.ry:0,label:w(e.label,200),ctx:w(e.ctx,120),breakpoint:w(e.breakpoint,40),browser:w(e.browser,80),device:w(e.device,80),tag:w(e.tag,40),classes:Array.isArray(e.classes)?e.classes.slice(0,20).map(t=>w(t,80)):[],nth:Number.isInteger(e.nth)?e.nth:null,category:w(e.category,40),...lt(e),...["urgent","high","normal","low"].includes(e.priority)?{priority:e.priority}:{},...e.shared===!0?{shared:!0}:{},...Number.isInteger(e.from?.id)&&e.from.id>0?{from:{id:e.from.id}}:{},viewport:e.viewport&&Number.isFinite(e.viewport.w)&&Number.isFinite(e.viewport.h)?{w:e.viewport.w,h:e.viewport.h}:null,...fe(e.assignee)?{assignee:fe(e.assignee)}:{},...we.includes(e.stage)?{stage:e.stage}:{},...typeof e.host=="string"&&/^[a-z0-9.-]{1,120}(:\d{1,5})?$/i.test(e.host)?{host:e.host.toLowerCase()}:{},...Array.isArray(e.logs)&&e.logs.length?{logs:e.logs.slice(-20).map(t=>({at:w(t?.at,30),kind:["console","error","rejection","network"].includes(t?.kind)?t.kind:"console",text:Me(w(t?.text,500))})).filter(t=>t.text)}:{},...e.suggest&&typeof e.suggest.from=="string"&&typeof e.suggest.to=="string"&&e.suggest.to.trim()?{suggest:{from:Y(e.suggest.from,2e3),to:Y(e.suggest.to,2e3)}}:{}}),ft=e=>{const t={};if((e.status==="open"||e.status==="done")&&(t.status=e.status),e.status==="open"&&Object.assign(t,{reopenedAt:new Date().toISOString(),reopenedBy:"you"}),"doneBy"in e&&(t.doneBy=e.doneBy==="you"?"you":null),typeof e.category=="string"&&(t.category=qe(e.category).id),"priority"in e&&(t.priority=["urgent","high","normal","low"].includes(e.priority)?e.priority:null),typeof e.shared=="boolean"&&(t.shared=e.shared||null),e.client===!1&&(t.client=null),"assignee"in e&&(t.assignee=fe(e.assignee)),"stage"in e&&(t.stage=we.includes(e.stage)?e.stage:null),typeof e.archived=="boolean"&&(t.archived=e.archived),"box"in e&&(t.box=We(e.box)),e.move&&typeof e.move=="object"&&typeof e.move.selector=="string"){const r=e.move,f=i=>Number.isFinite(i)?Math.min(1,Math.max(0,i)):.5;Object.assign(t,{selector:w(r.selector,2e3),rx:f(r.rx),ry:f(r.ry),label:w(r.label,200),ctx:w(r.ctx,120),tag:w(r.tag,40),classes:Array.isArray(r.classes)?r.classes.slice(0,20).map(i=>w(i,80)):[],nth:Number.isInteger(r.nth)?r.nth:null,...q(r.fp)?{fp:q(r.fp)}:{},...se(r.spot)?{spot:se(r.spot)}:{}}),typeof e.repin=="string"&&e.repin.trim()&&Object.assign(t,{repinnedAt:new Date().toISOString(),repinnedBy:"you",repinnedFrom:w(e.repin,120)}),e.repin===!1&&Object.assign(t,{repinnedAt:null,repinnedBy:null,repinnedFrom:null})}return"anchor"in e&&(t.anchor=["moved","probably","gone"].includes(e.anchor)?e.anchor:null),t},ae=e=>{const t=e.headers.origin;if(!t)return!1;try{return new URL(t).host!==e.headers.host}catch{return!0}};function dt({root:e,options:t,routes:r,open:f=()=>He(e),crossOrigin:i=!1}){const m=at(e),u=(c,h=200)=>({status:h,type:"application/json",body:JSON.stringify(c)}),l=(c,h)=>({status:c,type:"text/plain; charset=utf-8",body:h}),A=async c=>{const h=await c.body();if(h.length>(i?45e5:8e7))throw Object.assign(new Error("too large"),{status:413});try{return h.length?JSON.parse(h.toString("utf8")):{}}catch{throw Object.assign(new Error("not JSON"),{status:400})}},b=async(c,h,s)=>{const O=async a=>{const o=await h(a);if(o.status>=400)throw Object.assign(new Error("not written"),{out:o});return o};try{return c.cloud&&s!=null&&c.thread?await ze(c,s,O):await Re(c,O)}catch(a){if(a.out)return a.out;throw a}finally{M=null,x++,z()&&V()}},R=new Set;let M=null,ee=0,U=!1,W=!1,te=null,T=null,n=0,x=0;const z=()=>R.size>0||Date.now()-n<3e4,V=async()=>{if(i)return;if(U){W=!0;return}U=!0,clearTimeout(te);let c=!1;try{const h=await f();c=!!h.cloud;const s=x,O=h.version?String(await h.version()):null;if(s!==x)W=!0;else if(ee=Date.now(),O!==M){M=O;for(const a of R)a(O)}if(!c&&!T&&z()&&re(J(e,"feedback")))try{T=De(J(e,"feedback"),(a,o)=>{String(o).startsWith("comments.json")&&V()}),T.on("error",()=>{T?.close(),T=null})}catch{T=null}}catch{}if(U=!1,W)return W=!1,V();z()?te=setTimeout(V,c?1500:T?1e3:250):(T?.close(),T=null)},Ae=c=>(R.add(c),M!=null&&c(M),V(),()=>{R.delete(c),n=Date.now()}),Be=()=>z()&&M!=null&&Date.now()-ee<3e3?M:null,pe=new Map,Ie=async(c,h)=>{if(c.method!=="GET"&&!i&&ae(c))return l(403,"Cross-origin write refused");const s=await f();if(c.method==="GET"){const d=h.searchParams.get("route"),E=h.searchParams.get("since"),D=Be();if(E!=null&&s.version&&E===(D??String(await s.version())))return{status:204,type:"text/plain",body:""};const X=h.searchParams.get("open")==="1",$=`${d??""}|${X}`,L=D!=null&&pe.get($);if(L&&L.v===D)return L.res;const k=await s.load(X?{open:!0}:void 0);let N=d?k.comments.filter(Q=>Q.route===d):k.comments;X&&(N=N.filter(Q=>Qe(Q)!=="done")),N=N.map(({logs:Q,...Z})=>Z);const H=s.versionOf?s.versionOf(k):null,ne=u({version:H==null?null:String(H),comments:N,listening:k.listening??null,turbo:k.turbo??null});return!i&&H!=null&&pe.set($,{v:String(H),res:ne}),ne}const O=c.method==="DELETE"?null:await A(c);let a=null,o=null;const B=c.method==="POST"||!!O?.reply?.trim?.()||O?.stage!==void 0,F=s.cloud&&O?(B?s.people():s.me().then(d=>({me:d,team:[]}))).then(d=>{a=d,o=d.me}).catch(d=>d):Promise.resolve(),G=async()=>{const d=await F;if(d instanceof Error)throw d},ge=d=>{if(o&&d){d.by=o.email,d.byName=o.name;const E=Je(d.text,a.team.filter(D=>D.email!==o.email));E.length&&(d.mentions=E)}return d};if(c.method==="POST"){const{image:d,images:E,before:D,...X}=O,$=ut(X);return $.text.trim()?/^\/(?![\/\\])/.test($.route)?b(s,async L=>{await G(),a?.client&&($.client=!0,de($.assignee)&&delete $.assignee,$.stage==="approved"&&delete $.stage);const k=ge(s.add(L,$));o&&de(k.assignee)&&(k.handedBy=o.email);for(const N of[].concat(E??d??[]))await s.attach(L,k.id,N);return await me(s,L,k.id,D,"before"),u(k,201)}):u({error:"route must be a path"},400):u({error:"empty comment"},400)}if(c.method==="PATCH"){const d=O;if(d.turbo==="on"||d.turbo==="off")return b(s,async p=>(p.turbo={paused:d.turbo==="off",at:new Date().toISOString()},u({turbo:p.turbo})));if(Array.isArray(d.push)||Array.isArray(d.unpush)){const p=j=>(Array.isArray(j)?j:[]).map(Number).filter(S=>Number.isInteger(S)&&S>0).slice(0,500);return b(s,async j=>{const S=new Set(j.turbo?.push?.ids??[]);for(const I of p(d.push))S.add(I);for(const I of p(d.unpush))S.delete(I);const P=I=>j.comments.some(ce=>ce.id===I&&ce.status!=="done"),C=new Set((j.turbo?.batch?.ids??[]).filter(P)),_=!C.size;for(const I of p(d.push))C.add(I);for(const I of p(d.unpush))C.delete(I);const v=new Date().toISOString();return j.turbo={...j.turbo??{paused:!0},push:{at:v,ids:[...S]},batch:{at:_?v:j.turbo?.batch?.at??v,ids:[...C]}},u({turbo:j.turbo})})}const{id:E,reply:D,image:X,images:$,removeImage:L,uploaded:k,edit:N,unsay:H,before:ne,after:Q,react:Z,seen:Ee,...Pe}=d,g=Number(E);if(!Number.isInteger(g))return u({error:"bad id"},400);if(Z){const p=Ve(Z.emoji),j=typeof Z.at=="string"&&Z.at?Z.at:null;return p?s.cloud?s.react(g,j,p).then(u,S=>u({error:S.message},S.status>=400&&S.status<500?S.status:500)):b(s,async S=>{const P=Ze(S,g,j,p,"you");return P===!1?u({error:`${Ke} kinds of reaction at most`},400):P?u(P):u({error:`no message to react to in #${g}`},404)},g):u({error:"not an emoji"},400)}if(typeof H=="string"){let p=[];const j=await b(s,async S=>{const P=S.comments.find(_=>_.id===g),C=P?.replies?.find(_=>_.at===H);return!C||o&&C.by&&C.by!==o.email?u({error:`no reply of yours to delete in #${g}`},404):(p=Xe(P).find(_=>_.at===H&&_.author==="you")?.images??[],s.unsay(S,g,H)?u(P):u({error:`no reply of yours to delete in #${g}`},404))},g);if(j.status<400)for(const S of p)await s.forget(xe(S));return j}const y=ft(Pe);return b(s,async p=>{await G();const j=p.comments.find(v=>v.id===g),S=Ue(j,Ee,y,o?.email);if(S)return u({error:`#${g} was just changed by someone else`,...S,thread:j},409);if(N){const v=p.comments.find(le=>le.id===Number(g)),I=N.at?v?.replies?.find(le=>le.at===N.at):v;if(o&&I?.by&&I.by!==o.email||!(N.text?.trim?.()&&s.edit(p,g,N.at??null,Y(N.text.trim(),1e4))))return u({error:`no message of yours to edit in #${g}`},404)}D?.trim?.()&&ge(s.reply(p,g,"you",Y(D.trim(),1e4))?.replies.at(-1));for(const v of[].concat($??X??[]))await s.attach(p,g,v);for(const v of[].concat(k??[]))if(s.adopt&&!await s.adopt(p,g,v))return u({error:`${v} did not arrive`},400);for(const v of[].concat(L||[]))await s.detach(p,g,v);if(await me(s,p,g,ne,"before"),await me(s,p,g,Q,"after"),o&&y.status==="done"&&Object.assign(y,{confirmedBy:o.email,confirmedAt:new Date().toISOString()}),o&&y.status==="open"&&Object.assign(y,{confirmedBy:null,confirmedAt:null,reopenedBy:o.email}),o&&y.repinnedBy&&(y.repinnedBy=o.email),"archived"in y){const v=y.archived;delete y.archived,Object.assign(y,v?{archivedAt:new Date().toISOString(),archivedBy:o?.email??null}:{archivedAt:null,archivedBy:null})}y.status==="open"&&Object.assign(y,{archivedAt:null,archivedBy:null}),o&&(y.stage==="review"||y.stage!==void 0&&!a?.client)&&(y.stageBy=o.email),o&&"assignee"in y&&(y.handedBy=de(y.assignee)?o.email:null);const P=Object.keys(y).length&&Object.keys(y).every(v=>v==="anchor"),C=p.comments.find(v=>v.id===Number(g)),_=P?C&&Object.assign(C,y):Object.keys(y).length?s.patch(p,g,y):p.comments.find(v=>v.id===Number(g));return _?u(_):u({error:`no comment #${g}`},404)},g)}if(c.method==="DELETE"){const d=Number(h.searchParams.get("id"));return b(s,async E=>await s.remove(E,d)?u({ok:!0,id:d}):u({error:`no comment #${d}`},404))}return l(405,"Method not allowed")},Te=(c,h)=>{const s=h.replace(/^.*[/\\]/,""),O=s.split(".").pop()?.toLowerCase()??"",a=nt[O]??(xe(s)?"application/octet-stream":null);if(!/^[\w.-]+$/.test(s)||!a)return l(400,"Bad name");const o=J(c,s);return re(o)?{status:200,type:a,body:he(o)}:l(404,"Not found")};let ie=!1,K=null;return async c=>{const h=new URL(c.url,"http://devbar"),s=h.pathname.slice(10);if(!i&&!it(c))return l(403,"Notemend answers local addresses only");const O=c.headers["sec-fetch-site"];if(!i&&O&&O!=="same-origin")return l(403,"Notemend answers its own pages only");try{if(s==="config"&&c.method==="PATCH"){if(!i&&ae(c))return l(403,"Cross-origin write refused");const a=await f();if(!a.cloud)return l(400,"Link the site to a project to set its grid");const{grid:o}=await A(c);return u({grid:await a.setGrid(o??null)})}if(s==="config"){const a=st({root:e,options:{...await m(),...t},routes:r()}),o=await f();return o.cloud&&Object.assign(a,await o.people({fresh:!0}).catch(B=>{if(B.said)throw B;return{}})),(o.cloud||await oe().catch(()=>null))&&(a.voice=!0),o.cloud&&!i&&(a.cabinet=ue),u(a)}if(s==="transcribe"&&c.method==="POST"){if(!i&&ae(c))return l(403,"Cross-origin write refused");const a=await f(),o=a.cloud?await a.token():(await oe().catch(()=>null))?.access_token;if(!o)return l(401,"Voice replies need Notemend \u2014 run `npx notemend login`.");const{audio:B}=await A(c),F=/^data:(audio\/(?:webm|mp4))(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(B||""));if(!F)return l(400,"Not a recording");const G=await fetch(`${ue}/api/transcribe`,{method:"POST",body:Buffer.from(F[2],"base64"),headers:{authorization:`Bearer ${o}`,"content-type":F[1]}});return{status:G.status,type:"application/json",body:await G.text()}}if(s==="translate"&&c.method==="POST"){if(!i&&ae(c))return l(403,"Cross-origin write refused");const a=await f(),o=a.cloud?await a.token():(await oe().catch(()=>null))?.access_token;if(!o)return l(401,"Translating needs Notemend \u2014 run `npx notemend login`.");const{text:B,to:F}=await A(c),G=await fetch(`${ue}/api/translate`,{method:"POST",body:JSON.stringify({text:B,to:F}),headers:{authorization:`Bearer ${o}`,"content-type":"application/json"}});return{status:G.status,type:"application/json",body:await G.text()}}if(s==="signin"&&!i){if(h.searchParams.has("code"))return u({code:K?.code??null,done:!!await oe().catch(()=>null)});K||(K={},K.go=new Promise(o=>{Ge((B,F)=>{K.code=F,o(B)}).catch(B=>{console.warn(`[notemend] sign-in from the bar: ${B.message}`),o(null)}).finally(()=>{K=null,ie=!1})}));const a=await K.go;return a?{status:302,type:"text/plain",body:"",headers:{location:`${a}&from=bar`}}:l(502,"The cabinet did not answer. Try again in a moment.")}if(s==="comments")return await Ie(c,h);if(s==="events"&&!i)return{status:200,type:"text/event-stream",body:"",stream:Ae};if(s==="image"){const a=await f(),o=(h.searchParams.get("name")||"").replace(/^.*[/\\]/,"");return a.cloud&&/^[\w.-]+$/.test(o)&&await a.fetchImage(o).catch(()=>null),Te(a.imageDir,o)}return l(404,"Not found")}catch(a){return a.status===400||a.status===413?l(a.status,a.message):a.signin?(ie||(ie=!0,console.warn(`[notemend] ${a.said}`)),l(401,a.said)):a.said?l(a.status,a.said):a.status===403?l(403,String(a.message).replace(/^notemend: /,"").replace(/ \(403\)$/,"")):(console.error("[notemend]",a),l(500,"Something went wrong on our side. Try again in a moment."))}}}function bt(e){const t=dt(e),r=f=>new Promise((i,m)=>{const u=[];f.on("data",l=>u.push(l)),f.on("end",()=>i(Buffer.concat(u))),f.on("error",m)});return async function(i,m,u){if(!i.url||!i.url.startsWith("/__devbar/"))return u();const l=await t({method:i.method,url:i.url,headers:i.headers,body:()=>r(i)});if(l.stream){m.writeHead(200,{"content-type":l.type,"cache-control":"no-store",connection:"keep-alive"}),m.write(`retry: 1000
2
2
 
3
- `);const T=setInterval(()=>y.write(`: ping
3
+ `);const A=setInterval(()=>m.write(`: ping
4
4
 
5
- `),25e3),B=u.stream(C=>y.write(`data: ${C}
5
+ `),25e3),b=l.stream(R=>m.write(`data: ${R}
6
6
 
7
- `));c.on("close",()=>{clearInterval(T),B()});return}y.statusCode=u.status,y.setHeader("content-type",u.type),y.setHeader("cache-control","no-store"),y.end(u.body)}}export{Jt as buildConfig,Xt as notemendHandler,ce as notemendMiddleware,ie as scanApp,Ht as titleOf,Gt as titled};
7
+ `));i.on("close",()=>{clearInterval(A),b()});return}m.statusCode=l.status,m.setHeader("content-type",l.type),m.setHeader("cache-control","no-store");for(const[A,b]of Object.entries(l.headers??{}))m.setHeader(A,b);m.end(l.body)}}export{st as buildConfig,dt as notemendHandler,bt as notemendMiddleware,Nt as scanApp,rt as titleOf,$e as titled};
@@ -1,3 +1,3 @@
1
- import{readFileSync as P,writeFileSync as b,existsSync as I,mkdirSync as A,rmSync as D}from"node:fs";import{homedir as se}from"node:os";import{dirname as H,join as y}from"node:path";import{createStore as oe,add as ae,reply as ce,edit as ie,unsay as ue,patch as le,shotName as v,mediaOf as de,mediaName as L}from"./comments.mjs";const z=process.env.NOTEMEND_APP||"https://app.notemend.com",j={url:process.env.NOTEMEND_SUPABASE_URL||"https://xzhnjldvkirrydbyrdnm.supabase.co",key:process.env.NOTEMEND_SUPABASE_KEY||"sb_publishable_b8h8jTHZ9KtbPvMuroLhqA_-yBqZwd6"},N=y(process.env.NOTEMEND_HOME||y(se(),".config","notemend"),"session.json"),q=e=>y(e,".notemend.json"),he=e=>{try{return JSON.parse(P(q(e),"utf8")).project||null}catch{return null}},Ne=(e,t)=>b(q(e),JSON.stringify({project:t},null,2)+`
2
- `),Oe=e=>D(q(e),{force:!0}),fe=()=>{try{const e=JSON.parse(P(N,"utf8"));return e.url===j.url?e:null}catch{return null}},me=e=>{A(H(N),{recursive:!0}),b(N,JSON.stringify(e,null,2)+`
3
- `,{mode:384})},$e=()=>D(N,{force:!0});async function k(e,{method:t="GET",token:l,body:u,headers:i={},raw:d=!1}={}){const m=await fetch(`${j.url}${e}`,{method:t,headers:{apikey:j.key,authorization:`Bearer ${l||j.key}`,...u&&!d?{"content-type":"application/json"}:{},...i},body:d?u:u&&JSON.stringify(u),signal:AbortSignal.timeout(d?12e4:15e3)});if(!m.ok){const h=await m.text();let w=h;try{const _=JSON.parse(h);w=_.msg||_.message||_.error_description||_.error||h}catch{}const O=new Error(`${w} (${m.status})`);throw O.status=m.status,O}return m}const J=e=>{const t={url:j.url,email:e.user.email,user:e.user.id,access_token:e.access_token,refresh_token:e.refresh_token,expires_at:e.expires_at??Math.floor(Date.now()/1e3)+e.expires_in};return me(t),t},xe=e=>k("/auth/v1/otp",{method:"POST",body:{email:e,create_user:!0}}),Ee=async(e,t)=>J(await(await k("/auth/v1/verify",{method:"POST",body:{email:e,token:t,type:"email"}})).json());async function Te(e){const t=await fetch(`${z}/api/cli/device`,{method:"POST"}),l=await t.json().catch(()=>({}));if(!t.ok)throw new Error(l.error||`The cabinet said ${t.status}`);console.log(`Your code: ${l.code}`),e(l.url);const u=Date.now()+l.expires_in*1e3;for(;Date.now()<u;){await new Promise(h=>setTimeout(h,l.interval*1e3));const i=await fetch(`${z}/api/cli/device`,{headers:{authorization:`Bearer ${l.device}`}}).catch(()=>null);if(!i||i.status===202)continue;const d=await i.json().catch(()=>({}));if(!i.ok)throw new Error(d.error||`The cabinet said ${i.status}`);const m=await(await k("/auth/v1/user",{token:d.access_token})).json();return J({user:m,access_token:d.access_token,refresh_token:d.refresh_token,expires_at:Number(d.expires_at)})}throw new Error("No answer from the browser in 10 minutes.")}async function Pe(e,t){const l=await $();if(!l)throw new Error("Sign in first: npx notemend login");return(await(await k("/rest/v1/projects",{method:"POST",token:l.access_token,headers:{prefer:"return=representation"},body:{name:e,...t?{site_url:t}:{}}})).json())[0]}async function $(){const e=fe();if(!e)return null;if(e.expires_at-60>Date.now()/1e3)return e;try{const t=await k("/auth/v1/token?grant_type=refresh_token",{method:"POST",body:{refresh_token:e.refresh_token}});return J(await t.json())}catch(t){if(t.status===400||t.status===401)return null;throw t}}async function Ae(e,t,l){const u=y(H(N),"seen.json");let i={};try{i=JSON.parse(P(u,"utf8"))}catch{}const d=`${e}|${t}|${l}`;if(Date.now()-(i[d]||0)<6*36e5)return;const m=await $();m&&(await k("/rest/v1/rpc/agent_seen",{method:"POST",token:m.access_token,body:{p_agent:e,p_version:t,p_via:l}}),b(u,JSON.stringify({...i,[d]:Date.now()})))}class x extends Error{}const E=new Map;function pe(e,t,l=null){const u=y(e,"feedback","images"),i=n=>`feedback/images/${n}`,d=new WeakMap,m=l?async()=>l:async()=>{const n=await $();if(!n)throw new Error("Not signed in to Notemend \u2014 run `npx notemend login`.");return n},h=async(n,o={})=>k(`/rest/v1/${n}`,{...o,token:(await m()).access_token}),w=async(n,o={})=>k(`/storage/v1/object/shots/${t}/${n}`,{...o,token:(await m()).access_token}),O=`Project ${t} is not there, or you are not in it. Check \`npx notemend link\`.`,_=()=>Object.assign(new Error(O),{status:403,said:"You are not in this project any more \u2014 ask its owner to add you again."}),K="or=(data->>status.neq.done,data->>doneBy.eq.claude)",Y=async({open:n=!1}={})=>{if(!n){const a=await(await h(`stores?project_id=eq.${t}&select=doc,version`)).json();if(!a.length)throw _();const r=a[0].doc;return d.set(r,a[0].version),r}const[o,s]=await Promise.all([h(`stores_meta?project_id=eq.${t}&select=doc,version`).then(a=>a.json()),h(`threads?project_id=eq.${t}&${K}&select=data&order=id`).then(a=>a.json())]);if(!o.length)throw _();const c={...o[0].doc,comments:s.map(a=>a.data)};return d.set(c,o[0].version),c},R=n=>d.get(n)??null,W=async()=>(await(await h(`stores_meta?project_id=eq.${t}&select=version`)).json())[0]?.version??null,Z=async n=>{const o=d.get(n),s=await(await h(`stores?project_id=eq.${t}&version=eq.${o}&select=version`,{method:"PATCH",body:{doc:n},headers:{prefer:"return=representation"}})).json();if(!s.length)throw new x("Someone else wrote first");d.set(n,s[0].version)},G=async n=>(await(await h(`threads?project_id=eq.${t}&id=eq.${Number(n)}&select=data,v`)).json())[0]??null,Q=async(n,o,s,c)=>{const a={};for(const r of new Set([...Object.keys(o),...Object.keys(s)]))JSON.stringify(o[r])!==JSON.stringify(s[r])&&(a[r]=s[r]??null);if(Object.keys(a).length)try{await h("rpc/patch_thread",{method:"POST",body:{p_project:t,p_id:Number(n),p_patch:a,p_version:c}})}catch(r){throw r.status===409||r.status===404?new x(r.message):r}},U=async(n,o,s)=>(await(await h("rpc/react",{method:"POST",body:{p_project:t,p_id:Number(n),p_at:o,p_emoji:s}})).json()).thread,V=async()=>(await(await h(`threads?project_id=eq.${t}&select=route:data->>route`)).json()).map(n=>n.route),X=async()=>({email:(await m()).email}),B=new Map,ee=async(n,o,s,c)=>{const a=n.comments.find(g=>g.id===Number(o)),r=de(s);if(!a||!r)return null;const f=`${a.id}:${c??""}:${s.length}:${s.slice(-48)}`;let p=B.get(f);if(!p||a.images?.includes(i(p))){let g=Date.now();for(;I(y(u,L(a.id,g,r,c)));)g++;p=L(a.id,g,r,c),B.set(f,p)}const S=Buffer.from(r.base64,"base64");return await w(p,{method:"POST",body:S,raw:!0,headers:{"content-type":r.type,"x-upsert":"true"}}),A(u,{recursive:!0}),b(y(u,p),S),(a.images||=[]).push(i(p)),a.updatedAt=new Date().toISOString(),i(p)},te=async(n,o,s)=>{const c=n.comments.find(r=>r.id===Number(o));return!c||v(s)!==s||!s.startsWith(`${c.id}-`)?null:c.images?.includes(i(s))?i(s):await w(s,{method:"HEAD"}).then(()=>!0,()=>!1)?((c.images||=[]).push(i(s)),c.updatedAt=new Date().toISOString(),i(s)):null},M=async n=>{v(n)&&(D(y(u,n),{force:!0}),await w(n,{method:"DELETE"}).catch(()=>{}))};return{cloud:!0,project:t,root:e,imageDir:u,load:Y,versionOf:R,version:W,save:Z,thread:G,patchThread:Q,react:U,routes:V,me:X,attach:ee,adopt:te,detach:async(n,o,s)=>{const c=n.comments.find(f=>f.id===Number(o)),a=v(s),r=a&&c?.images?.find(f=>v(f)===a);return r?(await M(a),c.images=c.images.filter(f=>f!==r),c.updatedAt=new Date().toISOString(),!0):!1},remove:async(n,o)=>{const s=n.comments.find(c=>c.id===Number(o));if(!s)return!1;for(const c of s.images||[])await M(v(c));return n.comments=n.comments.filter(c=>c.id!==Number(o)),!0},fetchImage:async n=>{if(!v(n)||v(n)!==n)return null;const o=y(u,n);if(I(o))return o;const s=await w(n).catch(()=>null);return s?(A(u,{recursive:!0}),b(o,Buffer.from(await s.arrayBuffer())),o):null},people:async()=>{const n=await m(),o=`${t}|${n.email}`,s=E.get(o);if(s&&Date.now()-s.at<6e4)return s.p;const c=r=>h(`rpc/${r}`,{method:"POST",body:{p:t}}).then(f=>f.json()).catch(()=>null),a=Promise.all([h("profiles?select=email,name,nickname,avatar_url,agent_name,agent_avatar_url").then(r=>r.json()),c("project_people"),c("is_staff").then(r=>r??!0),c("project_staff"),c("project_lead"),h(`projects?id=eq.${t}&select=auto_archive_days,team_id`).then(r=>r.json()).then(async([r])=>{const[f]=r?.team_id?await h(`teams?id=eq.${r.team_id}&select=brand_color,brand_logo`).then(p=>p.json()).catch(()=>[]):[];return{autoArchive:r?.auto_archive_days??null,...f&&(f.brand_color||f.brand_logo)?{brand:{color:f.brand_color,logo:f.brand_logo}}:{}}}).catch(()=>({}))]).then(([r,f,p,S,g,ne])=>{if(Array.isArray(f)&&!f.length)throw _();const C=Array.isArray(f)?new Set(f):null,re=C?r.filter(T=>C.has(T.email)):r;return{me:r.find(T=>T.email===n.email)??{email:n.email,name:"",avatar_url:null},team:re,client:p===!1,...Array.isArray(S)?{studio:S}:{},...typeof g=="string"?{lead:g}:{},...ne}});return E.set(o,{at:Date.now(),p:a}),a.catch(()=>{E.get(o)?.p===a&&E.delete(o)}),a},add:ae,reply:ce,edit:ie,unsay:ue,patch:le,token:async()=>(await m()).access_token}}let F=!1;async function De(e){const t=he(e);return t&&await $()?pe(e,t):(t&&!F&&(F=!0,console.warn("[notemend] this site is linked to a Notemend project, but this computer is not signed in \u2014 comments stay in feedback/ until you run `npx notemend login`.")),oe(e))}async function qe(e,t,l){for(let u=0;;u++){const i=await e.thread(t);if(!i)return l({comments:[]});const d=JSON.parse(JSON.stringify(i.data)),m={comments:[i.data]},h=await l(m);try{return await e.patchThread(t,d,m.comments[0],i.v),h}catch(w){if(!(w instanceof x)||u>=4)throw w}}}async function Je(e,t){for(let l=0;;l++){const u=await e.load(),i=await t(u);try{return await e.save(u),i}catch(d){if(!(d instanceof x)||l>=4)throw d}}}export{j as BACKEND,z as CABINET,x as Conflict,pe as cloudStore,Pe as createProject,Te as deviceLogin,Ne as link,he as linkedProject,$e as logout,De as openStore,Je as retry,qe as retryThread,Ae as seen,xe as sendCode,$ as session,Oe as unlink,Ee as verifyCode};
1
+ import{readFileSync as A,writeFileSync as O,existsSync as H,mkdirSync as D,rmSync as q}from"node:fs";import{homedir as ie}from"node:os";import{dirname as G,join as g}from"node:path";import{createStore as ce,add as ue,reply as le,edit as de,unsay as he,patch as me,shotName as j,mediaOf as fe,mediaName as F,Conflict as $}from"./comments.mjs";import{changedFields as pe}from"./thread.mjs";const R=process.env.NOTEMEND_APP||"https://app.notemend.com",N={url:process.env.NOTEMEND_SUPABASE_URL||"https://xzhnjldvkirrydbyrdnm.supabase.co",key:process.env.NOTEMEND_SUPABASE_KEY||"sb_publishable_b8h8jTHZ9KtbPvMuroLhqA_-yBqZwd6"},x=g(process.env.NOTEMEND_HOME||g(ie(),".config","notemend"),"session.json"),M=t=>g(t,".notemend.json"),we=t=>{try{return JSON.parse(A(M(t),"utf8")).project||null}catch{return null}},Ae=(t,e)=>O(M(t),JSON.stringify({project:e},null,2)+`
2
+ `),De=t=>q(M(t),{force:!0}),ye=()=>{try{const t=JSON.parse(A(x,"utf8"));return t.url===N.url?t:null}catch{return null}},_e=t=>{D(G(x),{recursive:!0}),O(x,JSON.stringify(t,null,2)+`
3
+ `,{mode:384})},qe=()=>q(x,{force:!0});async function v(t,{method:e="GET",token:i,body:u,headers:c={},raw:d=!1}={}){const f=await fetch(`${N.url}${t}`,{method:e,headers:{apikey:N.key,authorization:`Bearer ${i||N.key}`,...u&&!d?{"content-type":"application/json"}:{},...c},body:d?u:u&&JSON.stringify(u),signal:AbortSignal.timeout(d?12e4:15e3)});if(!f.ok){const h=await f.text();let y=h;try{const k=JSON.parse(h);y=k.msg||k.message||k.error_description||k.error||h}catch{}const S=new Error(`${y} (${f.status})`);throw S.status=f.status,S}return f}const B=t=>{const e={url:N.url,email:t.user.email,user:t.user.id,access_token:t.access_token,refresh_token:t.refresh_token,expires_at:t.expires_at??Math.floor(Date.now()/1e3)+t.expires_in};return _e(e),e},Me=t=>v("/auth/v1/otp",{method:"POST",body:{email:t,create_user:!0}}),Be=async(t,e)=>B(await(await v("/auth/v1/verify",{method:"POST",body:{email:t,token:e,type:"email"}})).json());async function Ce(t){const e=await fetch(`${R}/api/cli/device`,{method:"POST"}),i=await e.json().catch(()=>({}));if(!e.ok)throw new Error(i.error||`The cabinet said ${e.status}`);console.log(`Your code: ${i.code}`),t(i.url,i.code);const u=Date.now()+i.expires_in*1e3;for(;Date.now()<u;){await new Promise(h=>setTimeout(h,i.interval*1e3));const c=await fetch(`${R}/api/cli/device`,{headers:{authorization:`Bearer ${i.device}`}}).catch(()=>null);if(!c||c.status===202)continue;const d=await c.json().catch(()=>({}));if(!c.ok)throw new Error(d.error||`The cabinet said ${c.status}`);const f=await(await v("/auth/v1/user",{token:d.access_token})).json();return B({user:f,access_token:d.access_token,refresh_token:d.refresh_token,expires_at:Number(d.expires_at)})}throw new Error("No answer from the browser in 10 minutes.")}async function Je(t,e){const i=await E();if(!i)throw new Error("Sign in first: npx notemend login");return(await(await v("/rest/v1/projects",{method:"POST",token:i.access_token,headers:{prefer:"return=representation"},body:{name:t,...e?{site_url:e}:{}}})).json())[0]}async function E(){const t=ye();if(!t)return null;if(t.expires_at-60>Date.now()/1e3)return t;try{const e=await v("/auth/v1/token?grant_type=refresh_token",{method:"POST",body:{refresh_token:t.refresh_token}});return B(await e.json())}catch(e){if(e.status===400||e.status===401)return null;throw e}}async function Le(t,e,i){const u=g(G(x),"seen.json");let c={};try{c=JSON.parse(A(u,"utf8"))}catch{}const d=`${t}|${e}|${i}`;if(Date.now()-(c[d]||0)<6*36e5)return;const f=await E();f&&(await v("/rest/v1/rpc/agent_seen",{method:"POST",token:f.access_token,body:{p_agent:t,p_version:e,p_via:i}}),O(u,JSON.stringify({...c,[d]:Date.now()})))}const z="Not saved \u2014 columns 1\u201324, gutter and margin 0\u2013200, max width 320\u20134000 or empty.",b=new Map;function ge(t,e,i=null){const u=g(t,"feedback","images"),c=n=>`feedback/images/${n}`,d=new WeakMap,f=i?async()=>i:async()=>{const n=await E();if(!n)throw new Error("Not signed in to Notemend \u2014 run `npx notemend login`.");return n},h=async(n,s={})=>v(`/rest/v1/${n}`,{...s,token:(await f()).access_token}),y=async(n,s={})=>v(`/storage/v1/object/shots/${e}/${n}`,{...s,token:(await f()).access_token}),S=`Project ${e} is not there, or you are not in it. Check \`npx notemend link\`.`,k=()=>Object.assign(new Error(S),{status:403,said:"You are not in this project any more \u2014 ask its owner to add you again."}),K="or=(data->>status.neq.done,data->>doneBy.eq.claude)",W=async({open:n=!1}={})=>{if(!n){const o=await(await h(`stores?project_id=eq.${e}&select=doc,version`)).json();if(!o.length)throw k();const m=o[0].doc;return d.set(m,o[0].version),m}const[s,r]=await Promise.all([h(`stores_meta?project_id=eq.${e}&select=doc,version`).then(o=>o.json()),h(`threads?project_id=eq.${e}&${K}&select=data&order=id`).then(o=>o.json())]);if(!s.length)throw k();const a={...s[0].doc,comments:r.map(o=>o.data)};return d.set(a,s[0].version),a},Y=n=>d.get(n)??null,Z=async()=>(await(await h(`stores_meta?project_id=eq.${e}&select=version`)).json())[0]?.version??null,U=async n=>{const s=d.get(n),r=await(await h(`stores?project_id=eq.${e}&version=eq.${s}&select=version`,{method:"PATCH",body:{doc:n},headers:{prefer:"return=representation"}})).json();if(!r.length)throw new $("Someone else wrote first");d.set(n,r[0].version)},Q=async n=>(await(await h(`threads?project_id=eq.${e}&id=eq.${Number(n)}&select=data,v`)).json())[0]??null,V=async(n,s,r,a)=>{const o=pe(s,r);if(Object.keys(o).length)try{await h("rpc/patch_thread",{method:"POST",body:{p_project:e,p_id:Number(n),p_patch:o,p_version:a}})}catch(m){throw m.status===409||m.status===404?new $(m.message):m}},X=async(n,s,r)=>(await(await h("rpc/react",{method:"POST",body:{p_project:e,p_id:Number(n),p_at:s,p_emoji:r}})).json()).thread,ee=async()=>(await(await h(`threads?project_id=eq.${e}&select=route:data->>route`)).json()).map(n=>n.route),te=async()=>({email:(await f()).email}),C=new Map,ne=async(n,s,r,a)=>{const o=n.comments.find(_=>_.id===Number(s)),m=fe(r);if(!o||!m)return null;const w=`${o.id}:${a??""}:${r.length}:${r.slice(-48)}`;let l=C.get(w);if(!l||o.images?.includes(c(l))){let _=Date.now();for(;H(g(u,F(o.id,_,m,a)));)_++;l=F(o.id,_,m,a),C.set(w,l)}const p=Buffer.from(m.base64,"base64");return await y(l,{method:"POST",body:p,raw:!0,headers:{"content-type":m.type,"x-upsert":"true"}}),D(u,{recursive:!0}),O(g(u,l),p),(o.images||=[]).push(c(l)),o.updatedAt=new Date().toISOString(),c(l)},re=async(n,s,r)=>{const a=n.comments.find(m=>m.id===Number(s));return!a||j(r)!==r||!r.startsWith(`${a.id}-`)?null:a.images?.includes(c(r))?c(r):await y(r,{method:"HEAD"}).then(()=>!0,()=>!1)?((a.images||=[]).push(c(r)),a.updatedAt=new Date().toISOString(),c(r)):null},T=async n=>{j(n)&&(q(g(u,n),{force:!0}),await y(n,{method:"DELETE"}).catch(()=>{}))};return{cloud:!0,setGrid:async n=>{const s=await(await h(`projects?id=eq.${e}&select=grid`,{method:"PATCH",body:{grid:n},headers:{prefer:"return=representation"}}).catch(r=>{throw/23514|check constraint/.test(r.message)?Object.assign(new Error(z),{status:400,said:z}):r})).json();if(!s.length)throw Object.assign(new Error("Only the project\u2019s admins change its grid."),{status:403,said:"Only the project\u2019s admins change its grid."});for(const r of b.keys())r.startsWith(`${e}|`)&&b.delete(r);return s[0].grid},project:e,root:t,imageDir:u,load:W,versionOf:Y,version:Z,save:U,thread:Q,patchThread:V,react:X,routes:ee,me:te,attach:ne,adopt:re,detach:async(n,s,r)=>{const a=n.comments.find(w=>w.id===Number(s)),o=j(r),m=o&&a?.images?.find(w=>j(w)===o);return m?(await T(o),a.images=a.images.filter(w=>w!==m),a.updatedAt=new Date().toISOString(),!0):!1},forget:T,remove:async(n,s)=>{const r=n.comments.find(a=>a.id===Number(s));if(!r)return!1;for(const a of r.images||[])await T(j(a));return n.comments=n.comments.filter(a=>a.id!==Number(s)),!0},fetchImage:async n=>{if(!j(n)||j(n)!==n)return null;const s=g(u,n);if(H(s))return s;const r=await y(n).catch(()=>null);return r?(D(u,{recursive:!0}),O(s,Buffer.from(await r.arrayBuffer())),s):null},people:async({fresh:n=!1}={})=>{const s=await f(),r=`${e}|${s.email}`,a=b.get(r);if(!n&&a&&Date.now()-a.at<6e4)return a.p;const o=l=>h(`rpc/${l}`,{method:"POST",body:{p:e}}).then(p=>p.json()).catch(()=>null);let m=!1;const w=Promise.all([h("profiles?select=email,name,nickname,avatar_url,agent_name,agent_avatar_url,avatar_hue").then(l=>l.ok?l.json():h("profiles?select=email,name,nickname,avatar_url,agent_name,agent_avatar_url").then(p=>p.json())),o("project_people"),o("is_staff"),o("project_staff"),o("project_lead"),h(`projects?id=eq.${e}&select=auto_archive_days,grid,team_id`).then(l=>l.json()).then(async([l])=>{const[p]=l?.team_id?await h(`teams?id=eq.${l.team_id}&select=brand_color,brand_logo`).then(_=>_.json()).catch(()=>[]):[];return{autoArchive:l?.auto_archive_days??null,projectGrid:l?.grid??null,...p&&(p.brand_color||p.brand_logo)?{brand:{color:p.brand_color,logo:p.brand_logo}}:{}}}).catch(()=>({})),o("runs_project")]).then(([l,p,_,J,L,se,oe])=>{if(Array.isArray(p)&&!p.length)throw k();m=typeof _!="boolean";const I=Array.isArray(p)?new Set(p):null,ae=I?l.filter(P=>I.has(P.email)):l;return{me:l.find(P=>P.email===s.email)??{email:s.email,name:"",avatar_url:null},team:ae,client:_!==!0,...Array.isArray(J)?{studio:J}:{},...typeof L=="string"?{lead:L}:{},...se,project:e,gridAdmin:oe===!0}});return b.set(r,{at:Date.now(),p:w}),w.then(()=>{m&&b.get(r)?.p===w&&b.delete(r)},()=>{b.get(r)?.p===w&&b.delete(r)}),w},add:ue,reply:le,edit:de,unsay:he,patch:me,token:async()=>(await f()).access_token}}const ke=()=>process.env.NOTEMEND_LOCAL==="1";async function Ie(t){const e=we(t);if(e&&await E())return ge(t,e);if(ke())return ce(t);const i=await E().catch(()=>null)?"Link this site to a project: run `npx notemend link <project-id>` in the site\u2019s folder.":"Sign in to comment: run `npx notemend login` in the site\u2019s folder.";throw Object.assign(new Error(i),{status:401,said:i,signin:!0})}async function He(t,e,i){for(let u=0;;u++){const c=await t.thread(e);if(!c)return i({comments:[]});const d=structuredClone(c.data),f={comments:[c.data]},h=await i(f);try{return await t.patchThread(e,d,f.comments[0],c.v),h}catch(y){if(!(y instanceof $)||u>=4)throw y;await new Promise(S=>setTimeout(S,300*(u+1)+Math.random()*300))}}}async function Ge(t,e){for(let i=0;;i++){const u=await t.load(),c=await e(u);try{return await t.save(u),c}catch(d){if(!(d instanceof $)||i>=4)throw d}}}export{N as BACKEND,R as CABINET,$ as Conflict,ge as cloudStore,Je as createProject,Ce as deviceLogin,Ae as link,we as linkedProject,ke as localOnly,qe as logout,Ie as openStore,Ge as retry,He as retryThread,Le as seen,Me as sendCode,E as session,De as unlink,Be as verifyCode};
@@ -1,3 +1,3 @@
1
- import{readFileSync as B,writeFileSync as D,existsSync as y,mkdirSync as A,renameSync as J,rmSync as z,statSync as T}from"node:fs";import{dirname as G,join as g}from"node:path";import{categoryOf as K}from"./categories.mjs";import{BLOCKED as W,DOCS as C,FRAMES as _,docSlug as q,fileExt as H,frameOf as P,toggledReaction as Q}from"./thread.mjs";import{CATEGORIES as ue,categoryIcon as fe,categoryOf as le}from"./categories.mjs";import{stateOf as pe,STATE_LABEL as ge}from"./status.mjs";const $=n=>{const t=String(n??"").split(/[/\\]/).pop(),e=/^[\w-][\w.-]*\.([a-z0-9]{1,8})$/i.exec(t);return e&&!W.test(e[1])?t:""},V=n=>{const t=/^data:(image|video|audio)\/(png|jpeg|webp|gif|webm|mp4)(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(n||""));if(t&&!/^data:[^,]*;ext=/.test(String(n).slice(0,300))){const[,i,s,m]=t;return(i==="image"?!/^(png|jpeg|webp|gif)$/.test(s):i==="video"?s!=="webm":!/^(webm|mp4)$/.test(s))?null:{base64:m,voice:i==="audio",ext:s==="jpeg"?"jpg":s==="mp4"?"m4a":s,type:`${i}/${s}`}}const e=/^data:([\w.+-]+\/[\w.+-]+)((?:;[\w=.-]+)*);base64,(.+)$/s.exec(String(n||""));if(!e)return null;const o=/;ext=([a-z0-9]{1,8})(?:;|$)/i.exec(e[2])?.[1],r=o?H(`x.${o}`):Object.keys(C).find(i=>C[i]===e[1]);return r?{base64:e[3],voice:!1,ext:r,type:r==="pdf"?"application/pdf":"application/octet-stream",slug:q(/;name=([\w.-]+)/.exec(e[2])?.[1])||"file"}:null},L=(n,t,e,o)=>`${e.voice?"voice-":_.includes(o)?`${o}-`:""}${n}-${t}${e.slug?`.${e.slug}`:""}.${e.ext}`,oe=async(n,t,e,o,r)=>{if(typeof o!="string")return null;const i=t.comments.find(m=>m.id===Number(e))?.images?.filter(m=>P(m)===r)??[],s=await n.attach(t,e,o,r);if(s)for(const m of i)await n.detach(t,e,m);return s},j=n=>Math.max(n.nextId||0,n.comments.reduce((t,e)=>Math.max(t,e.id),0)+1);function X(n,{route:t,selector:e,rx:o,ry:r,text:i,label:s,viewport:m,breakpoint:x,browser:I,device:v,tag:k,classes:E,nth:N,category:M,suggest:c,assignee:l,ctx:S,logs:a,host:u,priority:f,shared:d,stage:w,from:h,client:p}){const b={id:j(n),route:t,selector:e,rx:o,ry:r,text:i,tag:k||"",classes:E||[],nth:Number.isInteger(N)?N:null,label:s||"",ctx:S||"",viewport:m||null,breakpoint:x||"desktop",browser:I||"",device:v||"",category:K(M).id,status:"open",note:"",replies:[],doneBy:null,images:[],...c?{suggest:c}:{},...l?{assignee:l}:{},...f?{priority:f}:{},...w?{stage:w}:{},...d?{shared:!0}:{},...p?{client:!0}:{},...Number.isInteger(h?.id)?{from:{id:h.id}}:{},...u?{host:u}:{},...a?.length?{logs:a}:{},createdAt:new Date().toISOString(),updatedAt:null};return n.comments.push(b),n.nextId=b.id+1,b}function Y(n,t,e,o,r,i){const s=n.comments.find(m=>m.id===Number(t));return s?((s.replies||=[]).push({author:e,text:o,at:new Date().toISOString(),...r&&r!=="claude"?{agent:r}:{},...i?{by:i}:{}}),s.updatedAt=new Date().toISOString(),s):null}function Z(n,t,e,o){const r=n.comments.find(s=>s.id===Number(t)),i=e?r?.replies?.find(s=>s.at===e&&s.author==="you"):r;return i?(i.text=o,r.updatedAt=new Date().toISOString(),r):null}function U(n,t,e){const o=n.comments.find(i=>i.id===Number(t)),r=o?.replies?.find(i=>i.at===e&&i.author==="you");return r?(r.text="",r.deleted=!0,delete r.mentions,o.updatedAt=new Date().toISOString(),o):null}function ie(n,t,e,o,r){const i=n.comments.find(x=>x.id===Number(t)),s=e?i?.replies?.find(x=>x.at===e&&!x.deleted):i;if(!s)return null;const m=Q(s.reactions,o,r);return m===null?!1:(m?s.reactions=m:delete s.reactions,i)}function ee(n,t,e){const o=n.comments.find(r=>r.id===Number(t));return o?(Object.assign(o,e,{updatedAt:new Date().toISOString()}),o):null}function ce(n){const t=g(n,"feedback","comments.json"),e=g(n,"feedback","images"),o=g(n,"feedback","archive"),r=g(o,"images"),i=c=>`feedback/images/${c}`,s=new WeakMap,m=()=>{const c=y(t)?JSON.parse(B(t,"utf8")):{comments:[]};return s.set(c,v()),c},x=c=>s.get(c)??v(),I=c=>{A(G(t),{recursive:!0});const l=`${t}.${process.pid}.${Date.now()}.tmp`;D(l,JSON.stringify(c,null,2)+`
2
- `),J(l,t)},v=()=>{try{const c=T(t);return`${c.mtimeMs}-${c.size}`}catch{return"0"}};return{root:n,file:t,imageDir:e,archiveDir:o,archiveImageDir:r,load:m,version:v,versionOf:x,save:I,attach:(c,l,S,a)=>{const u=c.comments.find(h=>h.id===Number(l)),f=V(S);if(!u||!f)return null;A(e,{recursive:!0});let d=Date.now();for(;y(g(e,L(u.id,d,f,a)));)d++;const w=L(u.id,d,f,a);return D(g(e,w),Buffer.from(f.base64,"base64")),(u.images||=[]).push(i(w)),u.updatedAt=new Date().toISOString(),i(w)},detach:(c,l,S)=>{const a=c.comments.find(d=>d.id===Number(l)),u=$(S),f=u&&a?.images?.find(d=>$(d)===u);return f?(z(g(e,u),{force:!0}),a.images=a.images.filter(d=>d!==f),a.updatedAt=new Date().toISOString(),!0):!1},remove:(c,l)=>{const S=c.comments.find(a=>a.id===Number(l));if(!S)return!1;for(const a of S.images||[])$(a)&&z(g(e,$(a)),{force:!0});return c.comments=c.comments.filter(a=>a.id!==Number(l)),!0},add:X,patch:ee,reply:Y,edit:Z,unsay:U,nextId:j,prune:(c,{dry:l=!1,date:S=new Date().toISOString().slice(0,10)}={})=>{const a=c.comments.filter(p=>p.status==="done"),u=c.comments.filter(p=>p.status!=="done"),f=g(o,`comments-${S}.json`);if(l||!a.length)return{moving:a,keeping:u,archiveFile:f,images:a.flatMap(p=>p.images||[])};A(r,{recursive:!0});const d=[];for(const p of a)p.images=(p.images||[]).map(b=>{const O=$(b);if(!O)return b;const F=g(e,O),R=g(r,O);return y(F)&&J(F,R),d.push(O),`feedback/archive/images/${O}`});const w=y(f)?JSON.parse(B(f,"utf8")).comments||[]:[],h=new Set(w.map(p=>p.id));return D(f,JSON.stringify({comments:[...w,...a.filter(p=>!h.has(p.id))]},null,2)+`
3
- `),c.nextId=j(c),c.comments=u,{moving:a,keeping:u,archiveFile:f,images:d}}}}export{ue as CATEGORIES,ge as STATE_LABEL,X as add,fe as categoryIcon,le as categoryOf,ce as createStore,Z as edit,oe as fileFrame,L as mediaName,V as mediaOf,j as nextId,ee as patch,ie as react,Y as reply,$ as shotName,pe as stateOf,U as unsay};
1
+ import{readFileSync as J,writeFileSync as j,existsSync as I,mkdirSync as k,renameSync as z,rmSync as E,statSync as G}from"node:fs";import{dirname as K,join as S}from"node:path";import{categoryOf as W}from"./categories.mjs";import{BLOCKED as _,DOCS as L,FRAMES as q,docSlug as H,fileExt as P,frameOf as Q,toggledReaction as V}from"./thread.mjs";import{CATEGORIES as le,categoryIcon as de,categoryOf as pe}from"./categories.mjs";import{stateOf as Se,STATE_LABEL as xe}from"./status.mjs";class X extends Error{}const O=t=>{const n=String(t??"").split(/[/\\]/).pop(),e=/^[\w-][\w.-]*\.([a-z0-9]{1,8})$/i.exec(n);return e&&!_.test(e[1])?n:""},Y=t=>{const n=/^data:(image|video|audio)\/(png|jpeg|webp|gif|webm|mp4)(?:;[\w=.-]+)*;base64,(.+)$/s.exec(String(t||""));if(n&&!/^data:[^,]*;ext=/.test(String(t).slice(0,300))){const[,c,r,m]=n;return(c==="image"?!/^(png|jpeg|webp|gif)$/.test(r):c==="video"?r!=="webm":!/^(webm|mp4)$/.test(r))?null:{base64:m,voice:c==="audio",ext:r==="jpeg"?"jpg":r==="mp4"?"m4a":r,type:`${c}/${r}`}}const e=/^data:([\w.+-]+\/[\w.+-]+)((?:;[\w=.-]+)*);base64,(.+)$/s.exec(String(t||""));if(!e)return null;const i=/;ext=([a-z0-9]{1,8})(?:;|$)/i.exec(e[2])?.[1],s=i?P(`x.${i}`):Object.keys(L).find(c=>L[c]===e[1]);return s?{base64:e[3],voice:!1,ext:s,type:s==="pdf"?"application/pdf":"application/octet-stream",slug:H(/;name=([\w.-]+)/.exec(e[2])?.[1])||"file"}:null},R=(t,n,e,i)=>`${e.voice?"voice-":q.includes(i)?`${i}-`:""}${t}-${n}${e.slug?`.${e.slug}`:""}.${e.ext}`,ce=async(t,n,e,i,s)=>{if(typeof i!="string")return null;const c=n.comments.find(m=>m.id===Number(e))?.images?.filter(m=>Q(m)===s)??[],r=await t.attach(n,e,i,s);if(r)for(const m of c)await t.detach(n,e,m);return r},M=t=>Math.max(t.nextId||0,t.comments.reduce((n,e)=>Math.max(n,e.id),0)+1);function Z(t,{route:n,selector:e,rx:i,ry:s,text:c,label:r,viewport:m,breakpoint:x,browser:N,device:v,tag:F,classes:B,nth:D,category:C,suggest:A,assignee:o,ctx:u,logs:g,host:a,priority:f,shared:l,stage:d,from:w,client:b,fp:p,spot:y,opener:h}){const $={id:M(t),route:n,selector:e,rx:i,ry:s,text:c,tag:F||"",classes:B||[],nth:Number.isInteger(D)?D:null,label:r||"",ctx:u||"",viewport:m||null,...p?{fp:p}:{},...y?{spot:y}:{},...h?{opener:h}:{},breakpoint:x||"desktop",browser:N||"",device:v||"",category:W(C).id,status:"open",note:"",replies:[],doneBy:null,images:[],...A?{suggest:A}:{},...o?{assignee:o}:{},...f?{priority:f}:{},...d?{stage:d}:{},...l?{shared:!0}:{},...b?{client:!0}:{},...Number.isInteger(w?.id)?{from:{id:w.id}}:{},...a?{host:a}:{},...g?.length?{logs:g}:{},createdAt:new Date().toISOString(),updatedAt:null};return t.comments.push($),t.nextId=$.id+1,$}function U(t,n,e,i,s,c){const r=t.comments.find(m=>m.id===Number(n));return r?((r.replies||=[]).push({author:e,text:i,at:new Date().toISOString(),...s&&s!=="claude"?{agent:s}:{},...c?{by:c}:{}}),r.updatedAt=new Date().toISOString(),r):null}function ee(t,n,e,i){const s=t.comments.find(r=>r.id===Number(n)),c=e?s?.replies?.find(r=>r.at===e&&r.author==="you"):s;return c?(c.text=i,s.updatedAt=new Date().toISOString(),s):null}function te(t,n,e){const i=t.comments.find(c=>c.id===Number(n)),s=i?.replies?.find(c=>c.at===e&&c.author==="you");return s?(s.text="",s.deleted=!0,delete s.mentions,i.updatedAt=new Date().toISOString(),i):null}function ae(t,n,e,i,s){const c=t.comments.find(x=>x.id===Number(n)),r=e?c?.replies?.find(x=>x.at===e&&!x.deleted):c;if(!r)return null;const m=V(r.reactions,i,s);return m===null?!1:(m?r.reactions=m:delete r.reactions,c)}function ne(t,n,e){const i=t.comments.find(s=>s.id===Number(n));return i?(Object.assign(i,e,{updatedAt:new Date().toISOString()}),i):null}function me(t){const n=S(t,"feedback","comments.json"),e=S(t,"feedback","images"),i=S(t,"feedback","archive"),s=S(i,"images"),c=o=>`feedback/images/${o}`,r=new WeakMap,m=()=>{const o=v(),u=I(n)?JSON.parse(J(n,"utf8")):{comments:[]};return r.set(u,o),u},x=o=>r.get(o)??v(),N=o=>{const u=r.get(o);if(u!==void 0&&u!==v())throw new X("Someone else wrote first");k(K(n),{recursive:!0});const g=`${n}.${process.pid}.${Date.now()}.tmp`;j(g,JSON.stringify(o,null,2)+`
2
+ `),z(g,n),u!==void 0&&r.set(o,v())},v=()=>{try{const o=G(n);return`${o.mtimeMs}-${o.size}`}catch{return"0"}};return{root:t,file:n,imageDir:e,archiveDir:i,archiveImageDir:s,load:m,version:v,versionOf:x,save:N,attach:(o,u,g,a)=>{const f=o.comments.find(b=>b.id===Number(u)),l=Y(g);if(!f||!l)return null;k(e,{recursive:!0});let d=Date.now();for(;I(S(e,R(f.id,d,l,a)));)d++;const w=R(f.id,d,l,a);return j(S(e,w),Buffer.from(l.base64,"base64")),(f.images||=[]).push(c(w)),f.updatedAt=new Date().toISOString(),c(w)},detach:(o,u,g)=>{const a=o.comments.find(d=>d.id===Number(u)),f=O(g),l=f&&a?.images?.find(d=>O(d)===f);return l?(E(S(e,f),{force:!0}),a.images=a.images.filter(d=>d!==l),a.updatedAt=new Date().toISOString(),!0):!1},forget:o=>{O(o)&&E(S(e,O(o)),{force:!0})},remove:(o,u)=>{const g=o.comments.find(a=>a.id===Number(u));if(!g)return!1;for(const a of g.images||[])O(a)&&E(S(e,O(a)),{force:!0});return o.comments=o.comments.filter(a=>a.id!==Number(u)),!0},add:Z,patch:ne,reply:U,edit:ee,unsay:te,nextId:M,prune:(o,{dry:u=!1,date:g=new Date().toISOString().slice(0,10)}={})=>{const a=o.comments.filter(p=>p.status==="done"),f=o.comments.filter(p=>p.status!=="done"),l=S(i,`comments-${g}.json`);if(u||!a.length)return{moving:a,keeping:f,archiveFile:l,images:a.flatMap(p=>p.images||[])};k(s,{recursive:!0});const d=[];for(const p of a)p.images=(p.images||[]).map(y=>{const h=O(y);if(!h)return y;const $=S(e,h),T=S(s,h);return I($)&&z($,T),d.push(h),`feedback/archive/images/${h}`});const w=I(l)?JSON.parse(J(l,"utf8")).comments||[]:[],b=new Set(w.map(p=>p.id));return j(l,JSON.stringify({comments:[...w,...a.filter(p=>!b.has(p.id))]},null,2)+`
3
+ `),o.nextId=M(o),o.comments=f,{moving:a,keeping:f,archiveFile:l,images:d}}}}export{le as CATEGORIES,X as Conflict,xe as STATE_LABEL,Z as add,de as categoryIcon,pe as categoryOf,me as createStore,ee as edit,ce as fileFrame,R as mediaName,Y as mediaOf,M as nextId,ne as patch,ae as react,U as reply,O as shotName,Se as stateOf,te as unsay};
@@ -1 +1 @@
1
- const j=["before","after"],u=e=>/(?:^|\/)(before|after)-[^/]*$/.exec(String(e))?.[1]??null,z=e=>{const t={};for(const n of e?.images||[]){const o=u(n);o&&(t[o]=n)}return t},g={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},w=/^(exe|msi|msp|dmg|pkg|mpkg|app|sh|bash|zsh|command|bat|cmd|com|scr|cpl|ps1|psm1|vbs|vbe|js[e]?|wsf|wsh|hta|jar|apk|ipa|deb|rpm|bin|run|reg|lnk|inf|gadget|appimage)$/i,b=/^(png|jpe?g|webp|gif|webm)$/i,k=[["PDF","#e5484d","pdf"],["DOC","#0d99ff","doc docx rtf odt pages"],["XLS","#30a46c","xls xlsx csv tsv numbers ods"],["PPT","#f76b15","ppt pptx key odp"],["ZIP","#ffb224","zip rar 7z tar gz tgz bz2"],["FIG","#7c6cf2","fig sketch psd ai xd indd eps"],["TXT","#12a594","txt md json html htm css ts tsx jsx xml yml yaml svg log"],["MP3","#d6409f","mp3 wav m4a ogg flac aac"],["MP4","#e93d82","mp4 mov avi mkv m4v"]],T=e=>{const t=String(e??"").split(".").pop().toLowerCase(),n=k.find(([,,o])=>o.split(" ").includes(t));return n?{label:n[0],color:n[1]}:{label:"FILE",color:"#717171"}},B=e=>/\.(pdf|png|jpe?g|webp|gif|mp4|mov|webm|mp3|wav|m4a)$/i.test(String(e??"").split("?")[0]),L=Object.fromEntries([..."\u0430\u0431\u0432\u0433\u0491\u0434\u0435\u0454\u0436\u0437\u0438\u0456\u0457\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044C\u044E\u044F\u044B\u044D\u0451\u044A"].map((e,t)=>[e,["a","b","v","h","g","d","e","ie","zh","z","y","i","i","i","k","l","m","n","o","p","r","s","t","u","f","kh","ts","ch","sh","shch","","iu","ia","y","e","io",""][t]])),F=e=>String(e??"").replace(/\.[^.]*$/,"").toLowerCase().replace(/[а-яёєіїґ]/g,t=>L[t]??"").normalize("NFKD").replace(/[^\w-]+/g,"-").replace(/^[-_]+|-+$/g,"").slice(0,60),W=e=>{const t=/\.([a-z0-9]{1,8})$/i.exec(String(e??""));return t&&!w.test(t[1])?t[1].toLowerCase():""},G=e=>{const t=String(e??"");if(t.startsWith("data:")){const r=/^data:([^;,]+)((?:;[^;,]*)*)[;,]/.exec(t);if(!r)return null;const s=/;ext=([a-z0-9]{1,8})/i.exec(r[2])?.[1]?.toLowerCase()??Object.keys(g).find(a=>g[a]===r[1]);return s?`${/;name=([\w-]+)/.exec(r[2])?.[1]||"document"}.${s}`:null}const n=t.split("/").pop().split("?")[0];if(/^(voice|before|after)-/.test(n))return null;const o=/-\d+(?:\.([\w-]+))?\.([a-z0-9]{1,8})$/i.exec(n);return o&&!b.test(o[2])?`${o[1]||"document"}.${o[2].toLowerCase()}`:null},S=e=>{const t=[{author:"you",text:e.text,at:e.createdAt,by:e.by,byName:e.byName,images:[],...e.reactions?{reactions:e.reactions}:{}},...e.note?[{author:"claude",text:e.note,at:e.updatedAt,images:[]}]:[],...(e.replies||[]).map(n=>({...n,images:[]}))];for(const n of e.images||[]){if(u(n))continue;const o=Number(/-(\d+)(?:\.[\w-]+)?\.\w+$/.exec(n)?.[1]);let r=0;t.forEach((s,a)=>{Date.parse(s.at)<=o&&(r=a)}),t[r].images.push(n)}return t.filter(n=>!n.deleted)},H=["\u{1F44D}","\u2764\uFE0F","\u{1F602}","\u{1F389}","\u{1F440}","\u{1F525}"],K=["\u{1F44D}","\u{1F44E}","\u{1F44F}","\u{1F64C}","\u{1F64F}","\u{1F4AA}","\u{1F44C}","\u270C\uFE0F","\u{1F91D}","\u{1F44B}","\u2764\uFE0F","\u{1F525}","\u{1F389}","\u2728","\u2B50","\u2705","\u274C","\u26A0\uFE0F","\u{1F4AF}","\u{1F680}","\u{1F600}","\u{1F602}","\u{1F60A}","\u{1F60D}","\u{1F914}","\u{1F605}","\u{1F60E}","\u{1F973}","\u{1F622}","\u{1F62E}","\u{1F648}","\u{1F92F}","\u{1F62C}","\u{1F643}","\u{1F440}","\u{1F4A1}","\u{1F4CC}","\u{1F41B}","\u{1F3A8}","\u2615"],y=/^(?:\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|\u200d|\ufe0f)+$/u,U=e=>typeof e!="string"||!e||e.length>16||!y.test(e)?null:[...new Intl.Segmenter().segment(e)].length===1?e:null,A=20,V=(e,t,n)=>{const o={...e||{}},r=o[t]||[];if(!r.length&&Object.keys(o).length>=A)return null;const s=r.includes(n)?r.filter(a=>a!==n):[...r,n];return s.length?o[t]=s:delete o[t],Object.keys(o).length?o:void 0},X=e=>e.nickname||e.name||e.email,m=(e,t)=>{const n="@"+t.toLowerCase();let o=-1;for(let r=e.indexOf(n);r!==-1;r=e.indexOf(n,r+1))/[\p{L}\p{N}_.-]/u.test(e[r+n.length]??"")||(o=r);return o},Y=(e,t)=>{const n=String(e||"").toLowerCase();return n.includes("@")?[...new Set(t.filter(o=>[o.name,o.nickname,o.email].some(r=>r&&m(n,r)!==-1)).map(o=>o.email))]:[]},C=/https?:\/\/[^\s<>"']+/g,f=e=>{const t=e.filter(Boolean).pop();try{return t?decodeURIComponent(t):""}catch{return t}},M=e=>{let t;try{t=new URL(e)}catch{return{label:String(e),kind:"link"}}const n=t.hostname.replace(/^www\./,""),o=t.pathname.split("/").filter(Boolean);if(/(^|\.)figma\.com$/.test(n))return{label:o[2]?`Figma \xB7 ${f([o[2]]).replace(/-/g," ")}`:"Figma",kind:"link"};if(n==="github.com"&&o.length){const[s,a,c,d]=o;return{label:`GitHub \xB7 ${a??s}${/^(pull|issues)$/.test(c??"")&&d?` #${d}`:""}`,kind:c==="pull"?"pr":"github"}}if(/(^|\.)loom\.com$/.test(n))return{label:"Loom",kind:"link"};const r=f(o);return{label:r?`${n} \xB7 ${r.length>32?r.slice(0,31)+"\u2026":r}`:n,kind:"link"}},O=e=>{const t=String(e??""),n=[];let o=0;for(const r of t.matchAll(C)){const s=r[0].replace(/[.,;:!?)\]]+$/,"");r.index>o&&n.push(t.slice(o,r.index)),n.push({url:s,...M(s)}),o=r.index+s.length}return o<t.length&&n.push(t.slice(o)),n},q=e=>O(e).map(t=>typeof t=="string"?t:t.label).join(""),$={claude:"Claude",codex:"Codex",gemini:"Gemini",cursor:"Cursor",copilot:"Copilot",windsurf:"Windsurf",amp:"Amp",aider:"Aider",opencode:"OpenCode",agent:"AI agent"},I=e=>$[e]||(e?"AI agent":"Claude"),J="3.6 3.6 10.8 10.8",E="M10.116 9H13.883M9.966 9.558L12.222 10.86M9.558 9.966L11.441 13.228M9 10.116V12.72M8.442 9.966L6.559 13.228M8.034 9.558L5.778 10.86M7.884 9H4.118M8.034 8.442L5.778 7.14M8.442 8.034L6.559 4.772M9 7.884V5.28M9.558 8.034L11.441 4.772M9.966 8.442L12.222 7.14",i=e=>typeof e=="string"&&e.startsWith("agent:")?e.slice(6):null,l=e=>e==="claude"||i(e)!=null,D=/^[^\s@]+@[^\s@]+$/,Q=e=>{if(e==="claude")return e;if(typeof e!="string"||e.length>210)return null;const t=e.toLowerCase();return D.test(i(t)??t)?t:null},v=["new","approved","progress","review","waiting"],x=e=>v.includes(e?.stage)?e.stage:e?.stage==="accepted"?"review":l(e?.assignee)?"approved":"new",N=e=>e?.client===!0||e?.shared===!0,Z=(e,t)=>{const n=i(e.assignee);return!N(e)&&x(e)==="approved"&&(!e.assignee||e.assignee==="claude"||n!=null&&(t===void 0||n===t))&&!p(e)},_=()=>[{assignee:"claude",handle:"Claude",owner:null}],ee=(e,t=[])=>{const n=String(e||"").toLowerCase();let o=null,r=-1;for(const s of _()){const a=m(n,s.handle);a>r&&(r=a,o=s.assignee)}return o},te=(e,t,n=o=>o)=>I(e)+(t?` \xB7 ${n(t)}`:""),P=2*36e5,h=(e,t=Date.now())=>e?.working&&e.status!=="done"&&t-Date.parse(e.working.at)<P?e.working:null,ne=(e,t,n=Date.now())=>{const o=String(e?.by||e?.byName||"").toLowerCase();if(!o||t==="done")return null;const r=t==="claude"||l(e.assignee),s=p(e)?"":r?h(e,n)?.by||e.doneFor||e.handedBy||i(e.assignee)||o:e.assignee||"";return{writer:o,taker:String(s).toLowerCase(),claude:r}},R=e=>/@guest\.notemend\.com$/i.test(String(e||"")),p=e=>R(e.by)&&!e.approvedBy,oe=(e,t=Date.now())=>{if(!e)return null;if(e.status==="done")return e.doneBy==="claude"?"review":l(e.assignee)?"done":null;if(p(e))return"held";if(!l(e.assignee))return null;const n=S(e),o=n[n.length-1];return n.length>1&&o.author==="claude"&&!(e.reopenedAt&&Date.parse(e.reopenedAt)>=Date.parse(o.at))?"asks":h(e,t)?"working":e.working?"stuck":x(e)==="approved"?"queued":null},re={held:0,queued:2,asks:6,working:6,stuck:6,review:10,done:12},se=E.split("M").filter(Boolean).map(e=>{const t=e.match(/[\d.]+/g).map(Number),[n,o]=/H/.test(e)?[t[2],t[1]]:/V/.test(e)?[t[0],t[2]]:[t[2],t[3]];return{d:"M"+e,a:(Math.atan2(n-9,9-o)+2*Math.PI)%(2*Math.PI)}}).sort((e,t)=>e.a-t.a).map(e=>e.d),ae={plugin:"Claude Code: /plugin \u2192 Installed \u2192 notemend \u2192 Update now, then /reload-plugins",npx:'run it as npx -y notemend@latest (npx keeps an old copy of plain "notemend"), then restart the agent',project:"npm i -D notemend@latest in the site, then restart the agent",desktop:"Claude Desktop: download app.notemend.com/notemend.mcpb again and open it",source:"pull the notemend repository"},ie=(e,t)=>{const n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);for(let r=0;r<3;r++)if((n[r]||0)!==(o[r]||0))return(n[r]||0)>(o[r]||0);return!1},le=(e,t)=>{if(e.archivedAt)return!0;if(!t||e.status!=="done"||e.doneBy==="claude")return!1;const n=Math.max(Date.parse(e.confirmedAt||e.updatedAt||"")||0,...(e.replies||[]).filter(o=>!o.deleted).map(o=>Date.parse(o.at||"")||0));return!!n&&Date.now()-n>t*864e5};export{$ as AGENTS,J as AI_BOX,E as AI_RAYS,se as AI_RAYS_CW,w as BLOCKED,g as DOCS,K as EMOJI,k as FILE_KINDS,j as FRAMES,A as MAX_REACTIONS,H as QUICK,v as STAGES,re as STEP_RAYS,ae as UPDATE_HOW,P as WORKING_TTL,_ as agentHandles,te as agentLabel,ee as agentMentioned,I as agentName,i as agentOwner,oe as agentStep,le as archivedOf,Q as cleanAssignee,U as cleanEmoji,N as clientSpace,G as docOf,F as docSlug,W as fileExt,T as fileKind,Z as forAgentOf,u as frameOf,z as framesOf,X as handleOf,p as held,R as isGuest,M as linkLabel,O as linkParts,q as linkWords,Y as mentionsIn,ie as newer,B as opensInTab,ne as pinWho,x as stageOf,S as threadOf,l as toAgent,V as toggledReaction,h as workingOn};
1
+ const U=["before","after"],f=e=>/(?:^|\/)(before|after)-[^/]*$/.exec(String(e))?.[1]??null,K=e=>{const t={};for(const n of e?.images||[]){const o=f(n);o&&(t[o]=n)}return t},m={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},L=/^(exe|msi|msp|dmg|pkg|mpkg|app|sh|bash|zsh|command|bat|cmd|com|scr|cpl|ps1|psm1|vbs|vbe|js[e]?|wsf|wsh|hta|jar|apk|ipa|deb|rpm|bin|run|reg|lnk|inf|gadget|appimage)$/i,A=/^(png|jpe?g|webp|gif|webm)$/i,d=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter:null,C=(e,t)=>{const n=String(e??"");if(n.length<=t)return n;let o="";if(d)for(const{segment:r}of d.segment(n)){if(o.length+r.length>t)break;o+=r}else for(const r of n){if(o.length+r.length>t)break;o+=r}return o},O=[["PDF","#e5484d","pdf"],["DOC","#0d99ff","doc docx rtf odt pages"],["XLS","#30a46c","xls xlsx csv tsv numbers ods"],["PPT","#f76b15","ppt pptx key odp"],["ZIP","#ffb224","zip rar 7z tar gz tgz bz2"],["FIG","#7c6cf2","fig sketch psd ai xd indd eps"],["TXT","#12a594","txt md json html htm css ts tsx jsx xml yml yaml svg log"],["MP3","#d6409f","mp3 wav m4a ogg flac aac"],["MP4","#e93d82","mp4 mov avi mkv m4v"]],J=e=>{const t=String(e??"").split(".").pop().toLowerCase(),n=O.find(([,,o])=>o.split(" ").includes(t));return n?{label:n[0],color:n[1]}:{label:"FILE",color:"#717171"}},V=e=>/\.(pdf|png|jpe?g|webp|gif|mp4|mov|webm|mp3|wav|m4a)$/i.test(String(e??"").split("?")[0]),N=Object.fromEntries([..."\u0430\u0431\u0432\u0433\u0491\u0434\u0435\u0454\u0436\u0437\u0438\u0456\u0457\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044C\u044E\u044F\u044B\u044D\u0451\u044A"].map((e,t)=>[e,["a","b","v","h","g","d","e","ie","zh","z","y","i","i","i","k","l","m","n","o","p","r","s","t","u","f","kh","ts","ch","sh","shch","","iu","ia","y","e","io",""][t]])),X=e=>String(e??"").replace(/\.[^.]*$/,"").toLowerCase().replace(/[а-яёєіїґ]/g,t=>N[t]??"").normalize("NFKD").replace(/[^\w-]+/g,"-").replace(/^[-_]+|-+$/g,"").slice(0,60),Y=e=>{const t=/\.([a-z0-9]{1,8})$/i.exec(String(e??""));return t&&!L.test(t[1])?t[1].toLowerCase():""},q=e=>Number(/^(?:before-|after-|voice-)?(\d+)-\d+(?:\.[\w-]+)?\.\w+$/i.exec(String(e??"").split("/").pop())?.[1])||null,Q=e=>["","before-","after-","voice-"].map(t=>`${t}${Number(e)}-`),Z=e=>{const t=String(e??"");if(t.startsWith("data:")){const r=/^data:([^;,]+)((?:;[^;,]*)*)[;,]/.exec(t);if(!r)return null;const s=/;ext=([a-z0-9]{1,8})/i.exec(r[2])?.[1]?.toLowerCase()??Object.keys(m).find(a=>m[a]===r[1]);return s?`${/;name=([\w-]+)/.exec(r[2])?.[1]||"document"}.${s}`:null}const n=t.split("/").pop().split("?")[0];if(/^(voice|before|after)-/.test(n))return null;const o=/-\d+(?:\.([\w-]+))?\.([a-z0-9]{1,8})$/i.exec(n);return o&&!A.test(o[2])?`${o[1]||"document"}.${o[2].toLowerCase()}`:null},I=e=>{const t=[{author:"you",text:e.text,at:e.createdAt,by:e.by,byName:e.byName,images:[],...e.reactions?{reactions:e.reactions}:{}},...e.note?[{author:"claude",text:e.note,at:e.updatedAt,images:[]}]:[],...(e.replies||[]).map(n=>({...n,images:[]}))];for(const n of e.images||[]){if(f(n))continue;const o=Number(/-(\d+)(?:\.[\w-]+)?\.\w+$/.exec(n)?.[1]?.slice(0,13));let r=0;t.forEach((s,a)=>{Date.parse(s.at)<=o&&(r=a)}),t[r].images.push(n)}return t.filter(n=>!n.deleted)},ee=["\u{1F44D}","\u2764\uFE0F","\u{1F602}","\u{1F389}","\u{1F440}","\u{1F525}"],te=["\u{1F44D}","\u{1F44E}","\u{1F44F}","\u{1F64C}","\u{1F64F}","\u{1F4AA}","\u{1F44C}","\u270C\uFE0F","\u{1F91D}","\u{1F44B}","\u2764\uFE0F","\u{1F525}","\u{1F389}","\u2728","\u2B50","\u2705","\u274C","\u26A0\uFE0F","\u{1F4AF}","\u{1F680}","\u{1F600}","\u{1F602}","\u{1F60A}","\u{1F60D}","\u{1F914}","\u{1F605}","\u{1F60E}","\u{1F973}","\u{1F622}","\u{1F62E}","\u{1F648}","\u{1F92F}","\u{1F62C}","\u{1F643}","\u{1F440}","\u{1F4A1}","\u{1F4CC}","\u{1F41B}","\u{1F3A8}","\u2615"],$=/^(?:\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|\u200d|\ufe0f)+$/u,ne=e=>typeof e!="string"||!e||e.length>16||!$.test(e)?null:[...new Intl.Segmenter().segment(e)].length===1?e:null,oe=e=>{if(!e||typeof e!="object")return null;const t=[e.x,e.y,e.w,e.h].map(Number);if(!t.every(Number.isFinite))return null;const n=i=>Math.min(1,Math.max(0,i)),o=i=>Math.round(i*1e4)/1e4,r=n(t[0]),s=n(t[1]),a=n(t[0]+t[2])-r,p=n(t[1]+t[3])-s;return a>0&&p>0?{x:o(r),y:o(s),w:o(a),h:o(p)}:null},D=20,re=(e,t,n)=>{const o={...e||{}},r=o[t]||[];if(!r.length&&Object.keys(o).length>=D)return null;const s=r.includes(n)?r.filter(a=>a!==n):[...r,n];return s.length?o[t]=s:delete o[t],Object.keys(o).length?o:void 0},se=e=>e.nickname||e.name||e.email,M="(?![\\p{L}\\p{N}_]|[.-][\\p{L}\\p{N}_])",E=new RegExp("^"+M,"u"),x=(e,t)=>{const n="@"+t.toLowerCase();let o=-1;for(let r=e.indexOf(n);r!==-1;r=e.indexOf(n,r+1))E.test(e.slice(r+n.length))&&(o=r);return o},ae=(e,t)=>{const n=String(e||"").toLowerCase();return n.includes("@")?[...new Set(t.filter(o=>[o.name,o.nickname,o.email].some(r=>r&&x(n,r)!==-1)).map(o=>o.email))]:[]},v=/https?:\/\/[^\s<>"']+/g,h=e=>{const t=e.filter(Boolean).pop();try{return t?decodeURIComponent(t):""}catch{return t}},_=e=>{let t;try{t=new URL(e)}catch{return{label:String(e),kind:"link"}}const n=t.hostname.replace(/^www\./,""),o=t.pathname.split("/").filter(Boolean);if(/(^|\.)figma\.com$/.test(n))return{label:o[2]?`Figma \xB7 ${h([o[2]]).replace(/-/g," ")}`:"Figma",kind:"link"};if(n==="github.com"&&o.length){const[s,a,p,i]=o;return{label:`GitHub \xB7 ${a??s}${/^(pull|issues)$/.test(p??"")&&i?` #${i}`:""}`,kind:p==="pull"?"pr":"github"}}if(/(^|\.)loom\.com$/.test(n))return{label:"Loom",kind:"link"};const r=h(o);return{label:r?`${n} \xB7 ${r.length>32?C(r,31)+"\u2026":r}`:n,kind:"link"}},j=e=>{const t=String(e??""),n=[];let o=0;for(const r of t.matchAll(v)){const s=r[0].replace(/[.,;:!?)\]]+$/,"");r.index>o&&n.push(t.slice(o,r.index)),n.push({url:s,..._(s)}),o=r.index+s.length}return o<t.length&&n.push(t.slice(o)),n},ie=e=>j(e).map(t=>typeof t=="string"?t:t.label).join(""),w={claude:"Claude",codex:"Codex",gemini:"Gemini",cursor:"Cursor",copilot:"Copilot",windsurf:"Windsurf",amp:"Amp",aider:"Aider",opencode:"OpenCode",agent:"AI agent"},y=new Map,le=(e=[])=>{for(const t of e)t?.email&&y.set(t.email.toLowerCase(),t.agent_name?.trim()||"")},T=(e,t)=>t&&y.get(String(c(t)??t).toLowerCase())||"Agent",pe=e=>!e||e==="claude"?"via Claude Code":e==="agent"||!w[e]?"":`via ${w[e]}`,ce="3.6 3.6 10.8 10.8",B="M10.116 9H13.883M9.966 9.558L12.222 10.86M9.558 9.966L11.441 13.228M9 10.116V12.72M8.442 9.966L6.559 13.228M8.034 9.558L5.778 10.86M7.884 9H4.118M8.034 8.442L5.778 7.14M8.442 8.034L6.559 4.772M9 7.884V5.28M9.558 8.034L11.441 4.772M9.966 8.442L12.222 7.14",c=e=>typeof e=="string"&&e.startsWith("agent:")?e.slice(6):null,u=e=>e==="claude"||c(e)!=null,F=/^[^\s@]+@[^\s@]+$/,ue=e=>{if(e==="claude")return e;if(typeof e!="string"||e.length>210)return null;const t=e.toLowerCase();return F.test(c(t)??t)?t:null},R=["new","approved","progress","review","waiting"],b=e=>R.includes(e?.stage)?e.stage:e?.stage==="accepted"?"review":u(e?.assignee)?"approved":"new",l=e=>e?.client===!0||e?.shared===!0,de=(e,t,n="")=>`Duplicated from ${n?n==="you"?"your":`${n}\u2019s`:"a"} ${(t?l(t):!l(e))?"client":"studio"} thread`,ge=e=>l(e)?"Duplicated for the client":"Duplicated to the workspace",fe="Fixed \u2014 please check.",me=e=>e?.status==="done"&&!l(e)&&Number.isInteger(e.from?.id)?e.from.id:null,xe=(e,t)=>!l(e)||e.status==="done"?!1:((e.replies||=[]).push(t),Object.assign(e,{status:"done",doneBy:"you",updatedAt:t.at}),!0),he=(e,t)=>{const n=c(e.assignee);return!l(e)&&b(e)==="approved"&&(!e.assignee||e.assignee==="claude"||n!=null&&(t===void 0||n===t))},k=["agent","claude","codex","gemini"],we=()=>[{assignee:"claude",handle:"agent",owner:null}],ye=(e,t=[])=>{const n=String(e||"").toLowerCase();return k.some(o=>x(n,o)!==-1)?"claude":null},be=(e,t=[],n="")=>{const o=String(e||"").replace(/^@/,"").toLowerCase();if(k.includes(o))return"agent";const r=t.find(s=>[s.name,s.nickname,s.email].some(a=>a&&a.toLowerCase()===o));return r&&n&&r.email?.toLowerCase()===n.toLowerCase()?"you":"person"},ke=(e,t,n=o=>o)=>T(e,t)+(t?` \xB7 ${n(t)}`:""),P=2*36e5,g=(e,t=Date.now())=>e?.working&&e.status!=="done"&&t-Date.parse(e.working.at)<P?e.working:null,Se=(e,t)=>({status:"done",doneBy:"claude",working:null,doneAgent:e!=="claude"?e:null,doneFor:t??null}),Le=(e,t=new Date().toISOString())=>({status:"open",doneBy:null,doneAgent:null,doneFor:null,working:null,reopenedAt:t,...u(e?.assignee)?{stage:"approved"}:{}}),Ae=(e,t)=>{const n={};for(const o of new Set([...Object.keys(e),...Object.keys(t)]))JSON.stringify(e[o])!==JSON.stringify(t[o])&&(n[o]=t[o]??null);return n},z={status:e=>e.status!=="done"?e.reopenedBy:e.doneBy==="claude"?"claude":e.confirmedBy??e.archivedBy,stage:e=>e.stageBy,assignee:e=>e.handedBy},Ce=(e,t,n,o)=>{if(!e||!t||typeof t!="object")return null;const r=(s,a)=>JSON.stringify(s??null)===JSON.stringify(a??null);for(const s of["stage","status","priority","assignee"]){if(!(s in t)||r(e[s],t[s])||s in n&&r(e[s],n[s]))continue;const a=z[s]?.(e)??null;if(!(a&&o&&String(a).toLowerCase()===o.toLowerCase()))return{field:s==="stage"?"status":s,by:a}}return null},Oe=(e,t,n=Date.now())=>{const o=String(e?.by||e?.byName||"").toLowerCase();if(!o||t==="done")return null;const r=t==="claude"||u(e.assignee),s=r?g(e,n)?.by||e.doneFor||e.handedBy||c(e.assignee)||o:e.assignee||"";return{writer:o,taker:String(s).toLowerCase(),claude:r}},Ne=e=>/@guest\.notemend\.com$/i.test(String(e||"")),Ie=(e,t=Date.now())=>{if(!e)return null;if(e.status==="done")return e.doneBy==="claude"?"review":u(e.assignee)?"done":null;if(!u(e.assignee))return null;const n=I(e),o=n[n.length-1],r=g(e,t);return n.length>1&&o.author==="claude"&&!(e.reopenedAt&&Date.parse(e.reopenedAt)>=Date.parse(o.at))&&(!r||String(o.text??"").includes("?"))?"asks":r?r.step&&t-Date.parse(r.at)>G?"stuck":"working":e.working?"stuck":b(e)==="approved"?"queued":null},G=10*6e4,S=(e,t=Date.now())=>{const n=Math.floor((t-Date.parse(e??""))/6e4);return n>=1?n<60?`${n} min`:`${Math.floor(n/60)} h`:"now"},$e=(e,t=31)=>{const n=d?[...d.segment(String(e??""))].map(s=>s.segment):[...String(e??"")];if(n.length<=t)return n.join("");const o=n.join("").match(/\.\w{1,8}$/)?.[0],r=o?o.length+3:0;return n.slice(0,t-1-r).join("")+"\u2026"+(r?n.slice(-r).join(""):"")},De=(e,t=Date.now())=>{const n=e?.status!=="done"?e?.working:null;return n?.at?{step:n.step?String(n.step):null,elapsed:S(n.since??n.at,t),silent:S(n.at,t),stale:!g(e,t)}:null},Me={queued:2,asks:6,working:6,stuck:6,review:10,done:12},Ee=B.split("M").filter(Boolean).map(e=>{const t=e.match(/[\d.]+/g).map(Number),[n,o]=/H/.test(e)?[t[2],t[1]]:/V/.test(e)?[t[0],t[2]]:[t[2],t[3]];return{d:"M"+e,a:(Math.atan2(n-9,9-o)+2*Math.PI)%(2*Math.PI)}}).sort((e,t)=>e.a-t.a).map(e=>e.d),ve={plugin:"Claude Code: /plugin \u2192 Installed \u2192 notemend \u2192 Update now, then /reload-plugins",npx:'run it as npx -y notemend@latest (npx keeps an old copy of plain "notemend"), then restart the agent',project:"npm i -D notemend@latest in the site, then restart the agent",desktop:"Claude Desktop: download app.notemend.com/notemend.mcpb again and open it",source:"pull the notemend repository"},_e=(e,t)=>{const n=String(e).split(".").map(Number),o=String(t).split(".").map(Number);for(let r=0;r<3;r++)if((n[r]||0)!==(o[r]||0))return(n[r]||0)>(o[r]||0);return!1},je=(e,t)=>{if(e.archivedAt)return!0;if(!t||e.status!=="done"||e.doneBy==="claude")return!1;const n=Math.max(Date.parse(e.confirmedAt||e.updatedAt||"")||0,...(e.replies||[]).filter(o=>!o.deleted).map(o=>Date.parse(o.at||"")||0));return!!n&&Date.now()-n>t*864e5},W=["uk","ru","en"],Te=e=>{try{const t=new Intl.DisplayNames([e],{type:"language"}).of(e)??e;return t[0].toUpperCase()+t.slice(1)}catch{return e}},Be=e=>{try{return new Intl.DisplayNames(["en"],{type:"language"}).of(e)??e}catch{return e}},H=e=>/[іїєґІЇЄҐ]/.test(e)?"uk":/[ыэъёЫЭЪЁ]/.test(e)?"ru":/\p{Script=Cyrillic}/u.test(e)?"":/\p{L}/u.test(e)&&!/[^\p{Script=Latin}\P{L}]/u.test(e)?"en":"",Fe=(e,t="en")=>{const n=H(e),o=t.split("-")[0].toLowerCase();return[...new Set([o,...W])].filter(r=>r!==n)};export{w as AGENTS,k as AGENT_ALIASES,ce as AI_BOX,B as AI_RAYS,Ee as AI_RAYS_CW,L as BLOCKED,m as DOCS,te as EMOJI,O as FILE_KINDS,fe as FIXED_NOTICE,U as FRAMES,M as HANDLE_END,D as MAX_REACTIONS,ee as QUICK,G as QUIET,R as STAGES,Me as STEP_RAYS,W as TR_LANGS,ve as UPDATE_HOW,P as WORKING_TTL,Se as agentDone,we as agentHandles,ke as agentLabel,ye as agentMentioned,T as agentName,c as agentOwner,Le as agentReopen,Ie as agentStep,pe as agentVia,je as archivedOf,Ae as changedFields,Ce as clashOf,ue as cleanAssignee,oe as cleanBox,ne as cleanEmoji,l as clientSpace,C as cut,Z as docOf,X as docSlug,de as duplicatedFrom,ge as duplicatedTo,S as elapsed,Y as fileExt,J as fileKind,Q as filePrefixes,q as fileThread,he as forAgentOf,f as frameOf,K as framesOf,se as handleOf,Ne as isOldGuest,Te as langName,Be as langNameEn,_ as linkLabel,j as linkParts,ie as linkWords,De as liveStep,be as mentionKind,ae as mentionsIn,_e as newer,V as opensInTab,me as originOf,Oe as pinWho,le as setAgentNames,b as stageOf,$e as stepWords,xe as tellFixed,I as threadOf,u as toAgent,re as toggledReaction,Fe as trTargets,g as workingOn,H as writtenIn};
package/store.d.ts CHANGED
@@ -21,23 +21,25 @@ export interface Comment {
21
21
  priority?: 'urgent' | 'high' | 'normal' | 'low';
22
22
  /** the project's clients see it too */
23
23
  shared?: boolean;
24
- /** written by a client or a guest: the clients' space */
24
+ /** written by a client: the clients' space */
25
25
  client?: boolean;
26
26
  /** a copy of this thread, in the other space */
27
27
  from?: { id: number };
28
28
  reactions?: Reactions;
29
29
  /** put away by a person */
30
- archivedAt?: string | null;
30
+ archivedAt?: string | null; archivedBy?: string | null;
31
31
  /** a person sent it back: the agent's last word before this is no question */
32
- reopenedAt?: string; acceptedAt?: string;
32
+ reopenedAt?: string; reopenedBy?: string | null; acceptedAt?: string;
33
+ /** who sent it to review */
34
+ stageBy?: string | null;
33
35
  /** who ticked it as fixed, in a team */
34
36
  confirmedBy?: string | null; confirmedAt?: string | null;
35
37
  /** the person the agent ran as when it resolved it */
36
38
  doneFor?: string | null;
39
+ /** where the element sat in the before frame, as fractions of the frame (0–1): the drawer outlines it there */
40
+ box?: { x: number; y: number; w: number; h: number } | null;
37
41
  /** who handed it to an agent — whose Claude its pin shows (the server sets it) */
38
42
  handedBy?: string | null;
39
- /** a guest's thread, approved by the studio */
40
- approvedBy?: string | null;
41
43
  /** the copy of the site it was written on — live, staging, localhost — as host[:port] */
42
44
  host?: string;
43
45
  by?: string; byName?: string; createdAt: string; updatedAt: string | null;
package/thread.d.ts CHANGED
@@ -1,8 +1,23 @@
1
1
  export type Mentionable = { email: string; name?: string | null; nickname?: string | null };
2
2
  /** What a pick from the @ list writes: the nickname, else the name, else the email */
3
3
  export function handleOf(p: Mentionable): string;
4
+ type Spaced = { client?: boolean; shared?: boolean; by?: string; byName?: string };
5
+ /** A copy's line: «Duplicated from Sarah's client thread» — the original's space and writer when seen */
6
+ export function duplicatedFrom(copy: Spaced, orig?: Spaced | null, who?: string): string;
7
+ /** The original's line: where its copy is now */
8
+ export function duplicatedTo(copy: Spaced): string;
9
+ /** What the client's original hears when the studio's copy of it is resolved */
10
+ export const FIXED_NOTICE: string;
11
+ /** The id of the client's original a resolved studio copy tells, or null */
12
+ export function originOf(copy: { status?: string; client?: boolean; shared?: boolean; from?: { id: number } } | undefined): number | null;
13
+ /** The original told: the reply added and resolved in place; false when it has nothing to hear */
14
+ export function tellFixed(orig: { status?: string; client?: boolean; shared?: boolean; replies?: unknown[]; [k: string]: unknown }, reply: { author: string; text: string; at: string; [k: string]: unknown }): boolean;
15
+ /** A regex lookahead source: what may not follow a handle for the @mention to be whole */
16
+ export const HANDLE_END: string;
4
17
  /** Everyone a text @mentions, by email */
5
18
  export function mentionsIn(text: string, people: Mentionable[]): string[];
19
+ /** At most `n` UTF-16 units of a text, never cutting an emoji or a joined character in half */
20
+ export function cut(text: string | null | undefined, n: number): string;
6
21
  /** A link named the way a message shows it: "Figma · Notemend", "GitHub · notemend #42", or the host and the last part */
7
22
  export function linkLabel(url: string): { label: string; kind: "link" | "github" | "pr" };
8
23
  /** A text cut into its words and its links, in order */
@@ -11,8 +26,15 @@ export function linkParts(text: string | null | undefined): (string | { url: str
11
26
  export function linkWords(text: string | null | undefined): string;
12
27
  /** Display names of the coding agents, by id */
13
28
  export const AGENTS: Record<string, string>;
14
- /** The name to show for an agent's message: its `agent`, or Claude when there is none */
15
- export function agentName(id?: string | null): string;
29
+ /** The name every agent shows under: «Agent» (one name since 03.11; the id is ignored) */
30
+ export function agentName(id?: string | null, owner?: string | null): string;
31
+ export function setAgentNames(people?: { email?: string | null; agent_name?: string | null }[] | null): void;
32
+ /** The tool behind an agent, as a subtitle: «via Claude Code», «via Codex», or '' */
33
+ export function agentVia(id?: string | null): string;
34
+ /** The handles that @mention the agent: agent, and the names it went by before (claude, codex, gemini) */
35
+ export const AGENT_ALIASES: string[];
36
+ /** Whose an @mention is: the agent, you (`me`), or another person */
37
+ export function mentionKind(handle: string, people?: { name?: string | null; nickname?: string | null; email?: string | null }[], me?: string | null): "agent" | "you" | "person";
16
38
  /** The agent mark: twelve rays drawn with a stroke, in viewBox AI_BOX. */
17
39
  export const AI_BOX: string;
18
40
  export const AI_RAYS: string;
@@ -25,29 +47,47 @@ export function cleanAssignee(v: unknown): string | null;
25
47
  /** Where a thread stands: new, approved for an agent, in progress (a person on it), waiting for a person's review, or waiting on someone */
26
48
  export const STAGES: string[];
27
49
  export function stageOf(c: { stage?: string | null; assignee?: string | null } | null | undefined): "new" | "approved" | "progress" | "review" | "waiting" | "accepted";
50
+ /** A change made on a stale look: the field someone else changed since `seen` (a stage and the status are one), and who when the thread keeps it — else null */
51
+ export function clashOf(c: Record<string, unknown> | null | undefined, seen: Record<string, unknown> | null | undefined, sent: Record<string, unknown>, me?: string | null): { field: "status" | "priority" | "assignee"; by: string | null } | null;
28
52
  /** A thread for the agent running as `me` (null: a CI key, the shared queue only; undefined: a local store, all) */
29
- export function forAgentOf(c: { assignee?: string | null; stage?: string | null; by?: string | null; approvedBy?: string | null; shared?: boolean | null; client?: boolean | null }, me?: string | null): boolean;
53
+ export function forAgentOf(c: { assignee?: string | null; stage?: string | null; by?: string | null; shared?: boolean | null; client?: boolean | null }, me?: string | null): boolean;
30
54
  export function clientSpace(c: { shared?: boolean | null; client?: boolean | null } | null | undefined): boolean;
31
- /** "Claude · Ann": the agent, and the person it ran as */
55
+ /** "Agent · Ann": the agent, and the person it ran as */
32
56
  export function agentLabel(agent?: string | null, owner?: string | null, nameOf?: (email: string) => string): string;
33
- export type Working = { agent: string; by?: string | null; at: string; v?: string };
57
+ export type Working = { agent: string; by?: string | null; at: string; v?: string;
58
+ /** what the agent is doing right now, for the bar's banner ("Editing Hero.astro") */
59
+ step?: string;
60
+ /** when the agent took the thread; `at` is its last step */
61
+ since?: string };
34
62
  /** How long a "working" mark holds before it counts as left behind, in ms */
35
63
  export const WORKING_TTL: number;
36
64
  /** The agent working on an open thread now, or null when nobody is or the mark is stale */
37
65
  export function workingOn(c: { working?: Working | null; status?: string } | null | undefined, now?: number): Working | null;
38
66
  /** Who is on a thread, for its pin: its writer and whoever has it ('' nobody yet); null when resolved or no writer is known. `st` as stateOf gives it */
39
67
  export function pinWho(c: Record<string, any>, st: 'open' | 'done' | 'claude', now?: number): { writer: string; taker: string; claude: boolean } | null;
40
- /** A guest's address: someone let in by link, without an account */
41
- export function isGuest(email?: string | null): boolean;
42
- /** A guest's thread the studio has not approved yet: no agent takes it */
43
- export function held(c: { by?: string | null; approvedBy?: string | null }): boolean;
68
+ /** An address a guest link made before links were removed: left out of the people to pick */
69
+ export function isOldGuest(email?: string | null): boolean;
70
+ /** What an agent's done writes on a thread: resolved by it, for `by`, its working mark cleared */
71
+ export function agentDone(agent: string, by?: string | null): { status: "done"; doneBy: "claude"; working: null; doneAgent: string | null; doneFor: string | null };
72
+ /** What an agent's reopen writes: open, stamped, back in the agent's queue when it is the agent's */
73
+ export function agentReopen(c: { assignee?: string | null } | null | undefined, at?: string): { status: "open"; doneBy: null; doneAgent: null; doneFor: null; working: null; reopenedAt: string; stage?: "approved" };
74
+ /** The fields that differ between two copies of a thread, a field taken away as null (patch_thread.sql) */
75
+ export function changedFields(was: Record<string, unknown>, now: Record<string, unknown>): Record<string, unknown>;
44
76
  /** The agent a message can @mention: one, Claude */
45
77
  export function agentHandles(): { assignee: string; handle: string; owner: string | null }[];
46
78
  /** The agent a text hands its thread to: the last one it @mentions, else null */
47
79
  export function agentMentioned(text: string, people?: { email: string; name?: string | null; agent_name?: string | null }[]): string | null;
48
- export type AgentStep = "held" | "queued" | "asks" | "working" | "stuck" | "review" | "done";
80
+ export type AgentStep = "queued" | "asks" | "working" | "stuck" | "review" | "done";
49
81
  /** Where a thread is on an agent's way; null when no agent is in it */
50
82
  export function agentStep(c: Record<string, any> | null | undefined, now?: number): AgentStep | null;
83
+ /** No step for this long (ms) and a run that steps went quiet */
84
+ export const QUIET: number;
85
+ /** «now», «4 min», «2 h» since an ISO time */
86
+ export function elapsed(iso?: string | null, now?: number): string;
87
+ /** A step cut in the middle to `max` characters (31), keeping the file's extension */
88
+ export function stepWords(text?: string | null, max?: number): string;
89
+ /** Claude's live step: its words (null without the hook), time since taken, time since the last step, the mark gone stale */
90
+ export function liveStep(c: Record<string, any> | null | undefined, now?: number): { step: string | null; elapsed: string; silent: string; stale: boolean } | null;
51
91
  /** How far along each step is: rays of the agent mark lit, of 12 */
52
92
  export const STEP_RAYS: Record<AgentStep, number>;
53
93
  /** The agent mark's rays one by one, clockwise from the top (viewBox AI_BOX) */
@@ -62,6 +102,8 @@ export const DOCS: { pdf: string; doc: string; docx: string };
62
102
  export function docSlug(name: string): string;
63
103
  /** What to call a document — "brief.pdf" — by its path or data: URL; null when it is not one */
64
104
  export function docOf(path: string): string | null;
105
+ export function fileThread(name: string): number | null;
106
+ export function filePrefixes(id: number): string[];
65
107
  /** Programs, installers and scripts a double-click runs: never taken. */
66
108
  export const BLOCKED: RegExp;
67
109
  export const FILE_KINDS: [label: string, color: string, extensions: string][];
@@ -84,6 +126,8 @@ export const QUICK: string[];
84
126
  export const EMOJI: string[];
85
127
  /** One emoji (a single grapheme of emoji code points), else null */
86
128
  export function cleanEmoji(v: unknown): string | null;
129
+ /** Where the element sat in its before frame, as fractions of the frame (0–1), clipped to it; else null */
130
+ export function cleanBox(v: unknown): { x: number; y: number; w: number; h: number } | null;
87
131
  /** The most kinds of reaction a message holds */
88
132
  export const MAX_REACTIONS: number;
89
133
  /** The reactions with `who`'s `emoji` toggled — undefined when none is left, null past MAX_REACTIONS kinds */
@@ -93,3 +137,9 @@ export type ThreadMessage = { author: string; text: string; at?: string | null;
93
137
  export function threadOf(c: { text: string; reactions?: Reactions; createdAt?: string; by?: string; byName?: string; note?: string; updatedAt?: string | null; replies?: Record<string, any>[]; images?: string[] }): ThreadMessage[];
94
138
  /** Put away: archived by a person, or resolved by one `days` ago with nobody saying a word since (the project's auto-archive). */
95
139
  export function archivedOf(c: { archivedAt?: string | null; status?: string; doneBy?: string | null; confirmedAt?: string | null; updatedAt?: string | null; replies?: { at?: string; deleted?: boolean }[] }, days?: number | null): boolean;
140
+ /** Translate's menu: the languages offered, a language's own name and its English name, the language a text is written in ('' unknown), and the targets with yours first. */
141
+ export const TR_LANGS: string[];
142
+ export function langName(tag: string): string;
143
+ export function langNameEn(tag: string): string;
144
+ export function writtenIn(text: string): string;
145
+ export function trTargets(text: string, yours?: string): string[];