@vercel/board 0.43.1 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/access.d.mts +2 -2
  2. package/dist/{auth-Bn8J_1F2.d.mts → auth-C8jxty0C.d.mts} +1 -1
  3. package/dist/{backend-DMrK55mU.d.mts → backend-_3W_5g6y.d.mts} +3 -3
  4. package/dist/backend-local.d.mts +1 -1
  5. package/dist/backend-local.mjs +1 -1
  6. package/dist/{bots-CGkO76qH.mjs → bots-CLKKMgYf.mjs} +6 -1
  7. package/dist/{chat-provider-CPZg2MQb.mjs → chat-provider-DZ4DsAZ7.mjs} +6 -4
  8. package/dist/{chat-provider-Cgkh9xJw.d.mts → chat-provider-HQo68RWL.d.mts} +4 -4
  9. package/dist/cli-commands.d.mts +1 -1
  10. package/dist/cli-commands.mjs +1 -1
  11. package/dist/cli-embedded.d.mts +2 -2
  12. package/dist/cli-embedded.mjs +2 -2
  13. package/dist/cli.mjs +6 -6
  14. package/dist/{commands-C4fR0md0.mjs → commands-B75pBXIV.mjs} +1 -1
  15. package/dist/{commands-BlM-ckFS.d.mts → commands-DHGZWeSZ.d.mts} +1 -1
  16. package/dist/{conformance-BORt5nky.mjs → conformance-CHqXZoGe.mjs} +66 -0
  17. package/dist/conformance.d.mts +1 -1
  18. package/dist/conformance.mjs +1 -1
  19. package/dist/{data-values-C-Cq80hz.mjs → data-values-CoTP0SQG.mjs} +43 -54
  20. package/dist/{engine-BVHSH2Kn.mjs → engine-D07DTYSi.mjs} +16 -9
  21. package/dist/{events-BT8y_81j.mjs → events-voButVQW.mjs} +3 -1
  22. package/dist/{exports-BVgUNVsP.mjs → exports-BNk4w-b2.mjs} +3 -2
  23. package/dist/exports-DFwXKst5.d.mts +4 -0
  24. package/dist/{index-CydxnBND.d.mts → index-CwOOIT0e.d.mts} +2 -2
  25. package/dist/index.d.mts +6 -6
  26. package/dist/index.mjs +2 -2
  27. package/dist/index.node.d.mts +6 -6
  28. package/dist/index.node.mjs +1 -1
  29. package/dist/inspect/app.js +29 -29
  30. package/dist/inspect/engine.js +5 -5
  31. package/dist/inspect-DBLdh9NM.mjs +2 -0
  32. package/dist/{inspect-ZGkTJl3f.mjs → inspect-dtQlHBcq.mjs} +1 -1
  33. package/dist/{local-yB2DFcRi.mjs → local-CnGNTReZ.mjs} +3 -1
  34. package/dist/{main-DjEJPCgo.mjs → main-CpsAmpEy.mjs} +22 -7
  35. package/dist/origin-D4ER_Tze.mjs +428 -0
  36. package/dist/{provider-dY54GFNz.d.mts → provider-CVI-DlWl.d.mts} +27 -2
  37. package/dist/{routes-By9lmvUD.d.mts → routes-CErTwlSZ.d.mts} +3 -1
  38. package/dist/{origin-9Ch-Zonv.mjs → routes-DrByOCc1.mjs} +4 -426
  39. package/dist/schemas.mjs +1 -1
  40. package/dist/{serve-Cnb4TpaJ.mjs → serve-BQT5quKD.mjs} +2 -2
  41. package/dist/{server-BHpUqip5.mjs → server-FlDE6BDt.mjs} +4 -3
  42. package/dist/sync-chat-sdk.d.mts +2 -2
  43. package/dist/sync-chat-sdk.mjs +2 -2
  44. package/dist/sync-github.d.mts +2 -2
  45. package/dist/sync-github.mjs +2 -2
  46. package/dist/sync-linear.d.mts +3 -3
  47. package/dist/sync-linear.mjs +3 -3
  48. package/dist/sync-slack.d.mts +27 -4
  49. package/dist/sync-slack.mjs +206 -10
  50. package/dist/sync.d.mts +3 -3
  51. package/dist/sync.mjs +1 -1
  52. package/docs/02-sync/02-functions.md +4 -1
  53. package/docs/02-sync/03-slack.md +24 -1
  54. package/docs/02-sync/04-github.md +5 -2
  55. package/docs/02-sync/06-providers.md +1 -1
  56. package/docs/04-reference/01-cli.md +1 -1
  57. package/docs/04-reference/02-board.md +1 -1
  58. package/docs/04-reference/03-http.md +6 -0
  59. package/docs/04-reference/05-conformance.md +1 -1
  60. package/package.json +3 -1
  61. package/dist/exports-Bw_OYNRl.d.mts +0 -4
  62. package/dist/inspect-DRPRCOaV.mjs +0 -2
@@ -1,5 +1,5 @@
1
- import{A as e,C as t,D as n,E as r,M as i,N as a,O as o,S as s,T as c,_ as l,a as u,b as d,c as f,d as p,f as m,g as h,h as g,i as _,j as v,k as y,l as b,m as x,n as S,o as C,p as w,r as ee,s as te,t as ne,u as T,v as E,w as re,x as D,y as O}from"./app.js";const k=/^\[vc\]: #\S*\r?\n/,A=/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g,j=/!\[([^\]]+)\]\(https:\/\/vercel\.com\/static\/status\/[^)]+\)\s*(?:\[[^\]]*\]\((https?:\/\/[^)\s]+)\))?/;function M(e){if(!k.test(e))return null;let t=e.search(/<details><summary>\d+ Skipped Deployments?<\/summary>/),n=[],r=0;for(let i of e.split(/\r?\n/)){let a=r;if(r=e.indexOf(`
2
- `,r)+1||e.length,!i.startsWith(`|`)||/^\|\s*(Project|Name)\s*\|/.test(i)||/^\|\s*:?-/.test(i))continue;let o=i.split(`|`).slice(1,-1).map(e=>e.trim());if(o.length<2)continue;let s=j.exec(o[1]);if(!s)continue;let c=[...o[0].matchAll(A)].at(-1),l=c?.[1]??o[0].replace(/<[^>]*>/g,``).trim();if(!l)continue;let u=o[2]?[...o[2].matchAll(A)].find(e=>/preview/i.test(e[1])):void 0,d=o[3]?.match(/<relative-time[^>]*>([^<]+)<\/relative-time>/)?.[1]?.trim()??(o[3]?.replace(/<[^>]*>/g,``).trim()||null);n.push({project:l,projectUrl:c?.[2]??null,status:s[1].trim(),deploymentUrl:s[2]??null,previewUrl:u?.[2]??null,updated:d,skipped:t!==-1&&a>t})}return n.length>0?n:null}const N={ready:`✅`,building:`⏳`,queued:`⏳`,initializing:`⏳`,error:`❌`,failed:`❌`,canceled:`⚪`,ignored:`⚪`},P=(e,t)=>t?`[${e}](${t})`:e;function ie(e){return e.map(e=>`- ${[`${N[e.status.toLowerCase()]??`▲`} **${P(e.project,e.projectUrl)}**`,`${P(e.status,e.deploymentUrl)}${e.skipped?` (skipped)`:``}`,...e.previewUrl?[P(`Preview`,e.previewUrl)]:[],...e.updated?[e.updated]:[]].join(` · `)}`).join(`
3
- `)}function ae(e,t){let n=t===`github:user:35613825`?M(e):null;return n?`**▲ Vercel**\n${ie(n)}`:e}const F=/```[\s\S]*?```/g,oe=/`[^`\n]*`/g,I=`[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?`,se=RegExp(`(?<![\\w@.-])@(${I}(?:/${I})?)(?!:\\S|[a-z0-9_/-]|\\.(?=[a-z0-9]))`,`gi`),L=/(?<![\w@.-])@\[([^\]\s]+)\]/g;function ce(e){let t=e.replace(F,e=>` `.repeat(e.length)).replace(oe,e=>` `.repeat(e.length));if(e.includes(`json#`))for(let{start:n,end:r}of o(e))t=`${t.slice(0,n)}${` `.repeat(r-n)}${t.slice(r)}`;return t}function le(e){let t=ce(e),n=[];for(let e of t.matchAll(L)){let t=e[1];t!==void 0&&n.push({index:e.index,token:{kind:`actor`,actor:t},key:`actor:${t}`})}for(let e of t.replace(L,e=>` `.repeat(e.length)).matchAll(se)){let t=e[1]?.toLowerCase();t!==void 0&&n.push({index:e.index,token:{kind:`handle`,handle:t},key:`handle:${t}`})}let r=/* @__PURE__ */ new Set;return n.sort((e,t)=>e.index-t.index).filter(({key:e})=>!r.has(e)&&r.add(e)).map(({token:e})=>e)}const ue=e=>/^[^\s@:]+@[^\s@:]+$/.test(e);function de(e,t){let n=ce(e),r=[];for(let e of n.matchAll(L))r.push({index:e.index,length:e[0].length,token:{kind:`actor`,actor:e[1]}});for(let e of n.replace(L,e=>` `.repeat(e.length)).matchAll(se))r.push({index:e.index,length:e[0].length,token:{kind:`handle`,handle:e[1].toLowerCase()}});let i=``,a=0;for(let{index:n,length:o,token:s}of r.sort((e,t)=>e.index-t.index)){let r=e.slice(n,n+o);i+=e.slice(a,n)+(t(s,r)??r),a=n+o}return i+e.slice(a)}D({id:s().min(1),platform:s().min(1),key:s().min(1),...b.shape,raw:t()});const fe=D({root:d(e=>typeof e==`function`).optional(),text:s().optional(),labels:x.optional(),unset:E(w).optional(),noSync:O().optional()}).strict();function R(e){if(e&&typeof e==`object`){for(let t of Object.values(e))R(t);Object.freeze(e)}return e}const pe=D({target:s().min(1),channel:s().min(1),kind:l([`channel`,`thread`])}).strict();var z=class extends Error{code;constructor(e,t){super(t),this.code=e}};const me=e=>e instanceof z&&e.code===`channel_not_found`,he=D({event:f,raw:t(),dedupe:s().min(1)}),B=/* @__PURE__ */ new WeakMap,ge=e=>B.get(e),V=(e,t=!1)=>{let n=h(e),r=n.trim()===``?t?``:`(no text)`:n;return r.length>1e4?`${r.slice(0,g-1).toWellFormed()}…`:r},H=(e,t,n=e.name??`a file`)=>`📎 ${n}${e.size===void 0?``:` (${v(e.size)})`} didn't come over: ${t}`,U=e=>e instanceof _&&e.code===`no_files`,_e=(e,t)=>{let n=e.name??`a file`;if(!e.url||!/^https?:\/\//.test(e.url))return H(e,t);let r=n.replace(/[[\]\\]/g,e=>`\\${e}`),i=e.url.replace(/[ ()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`);return H(e,t,`[${r}](${i})`)},W=(e,t)=>t.length?`${e.trim()?`${e}\n\n`:``}${t.join(`
4
- `)}`:e,ve=e=>e.split(`
5
- `).filter(e=>/^📎 .* didn't come over: /u.test(e)),G=e=>JSON.stringify([e.url,e.message,e.snapshot,e.unavailable]),ye=(e,t)=>e.length===t.length&&e.every((e,n)=>G(e)===G(t[n])),be=new AbortController().signal,xe=e=>{try{return JSON.parse(JSON.stringify(e??null))}catch{return null}},K=e=>typeof e==`string`?h(e):Array.isArray(e)?e.map(K):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[h(e),K(t)])):e,q=e=>{let t=e?.data?.error,n=typeof t==`string`?t:e instanceof Error?e.message:String(e);return h(n.slice(0,500))||`unknown error`},Se=e=>e instanceof _&&e.status===404;function J(e,t,n){return n.startsWith(`${e}:`)?n:`${e}:${n.startsWith(`${t}:`)?n.slice(t.length+1):n}`}function Ce(e,t,n){return`author`in n?{...n,author:{...n.author,id:J(e,t,n.author.id)}}:n}function Y(t){let o=null,s=()=>{if(!o)throw Error(`sync used before board() bound it`);return o},l={self:`sync`,origin:{via:{kind:`engine`}}};function d(e,t,n=be,r=l){let i=s().backend;return i[e].call(i,r,t,n)}let f=e=>{let n=t[e];if(!n)throw u(`no sync entry named ${e}`);return n},h=e=>e.slice(0,e.indexOf(`:`)),g=e=>s().syncedHere(e),b=async e=>t[h(e)]!==void 0&&await g(h(e)),x=e=>e.slice(e.indexOf(`:`)+1);async function w(e){try{return await d(`syncThread`,{thread:e})}catch(e){if(Se(e))return null;throw e}}async function E(e){try{let{message:t,replies:n}=await d(`message`,{id:e});return[t,...n]}catch(e){if(Se(e))return[];throw e}}async function D(e){return(await E(e)).find(t=>t.id===e)??null}async function O(e){return e.length===0?{}:(await d(`syncCopies`,{message:[...new Set(e)]})).copies}let k=(e,t)=>d(`syncFind`,e,t),A=null;function j(){if(A)return A;let e=d(`me`,{}).then(e=>e.principal);return A=e,e.catch(()=>{A===e&&(A=null)}),e}async function M(){let[{actors:e},t]=await Promise.all([d(`actors`,{}),j().catch(()=>null)]),n={byId:{},principal:t};for(let t of e)n.byId[t.id]={id:t.id,kind:t.kind,handle:t.handle,name:t.name,avatar:t.avatar,...t.via?{via:{...t.via}}:{},...t.platform?{platform:t.platform}:{},...t.verified?{verified:!0}:{}};return n}let N=/* @__PURE__ */ new Map;function P(e,t){let n=`${e}:${t}`,r=N.get(n);if(r&&(!r.failed||Date.now()-r.at<6e4))return r.id;let i={id:f(e).resolveChannel(t),failed:!1,at:Date.now()};return i.id.catch(r=>{i.failed=!0;let a=me(r);!a&&N.get(n)===i&&N.delete(n),console.warn(`[board] sync ${e}: ${a?`skipping`:`couldn't resolve`} ${t}: ${r.message}`)}),N.set(n,i),i.id}function ie(e,t){if(!p(t))return x(t);try{let n=f(e).inboxChannel(e,t);return n===null?null:x(n)}catch{return null}}let F=/* @__PURE__ */ new Map;function oe(e,t){let n=`${e}\u001f${t.toLowerCase()}`,r=F.get(n);if(r&&Date.now()-r.at<3e5)return r.mention;F.size>=1e3&&F.clear();let i=f(e),a=i.findByEmail(t).then(e=>e?i.mention({id:e.id,kind:`external`,handle:e.handle,name:e.name,avatar:e.avatar}):null,()=>null);return F.set(n,{at:Date.now(),mention:a}),a}async function I(e){let t=e.indexOf(`:`);if(t<=0)throw u(`sync targets look like <key>:<channel or thread>, got: ${e}`);let n=e.slice(0,t),r=f(n);try{let i=pe.parse(await r.resolveTarget(e.slice(t+1)));if(i.kind===`channel`&&!r.canStartThreads)throw Error(`${r.platform} cannot start threads; use an existing thread`);return{target:`${n}:${i.target}`,kind:i.kind}}catch(t){throw u(`can't sync to ${e}: ${t.message}`)}}async function se(e,t){let{event:n,raw:r,dedupe:i}=he.parse(K({...t,raw:xe(t.raw)}));for(let t of[n.channel,n.thread,`subthread`in n?n.subthread:null])if(t!==null&&!t.startsWith(`${e}:`))throw u(`provider locations must belong to sync entry ${e}`);let a=ge(f(e)),o=a&&await a(x(n.channel),t=>P(e,t)).catch(async e=>{if(await L(n.thread))return!0;throw e});(!a||o||await L(n.thread))&&await d(`inboxPush`,{key:e,events:[{id:i,event:n,raw:r}]})}async function L(e){try{return(await k({thread:e},AbortSignal.timeout(2e3))).thread!==null}catch(e){let t=e?.name;if(t===`TimeoutError`||t===`AbortError`)return!0;throw e}}async function ce(e,n){let r=t[e];if(!r)throw C(`no sync entry named ${e}`);if(!await g(e))return new Response(null,{status:200});let i;try{i=await r.receive(e,n,t=>se(e,t))}catch(e){return console.error(`[board] intake failed`,e),new Response(`intake failed`,{status:500})}let a=B([e]).catch(t=>console.error(`[board] couldn't pull ${e}'s inbox:`,q(t)));return ee(a),i}async function B(e=Object.keys(t)){let n=0,r=Date.now()+24e4;for(let t of e)if(await g(t))for(;Date.now()<r;){let{items:e}=await d(`inboxNext`,{key:t,limit:10});if(e.length===0)break;await Promise.all(e.map(e=>G(t,e))),n+=e.length}return n}async function G(e,t){let n;try{await Te(e,{event:t.event,raw:t.raw},{id:t.id,attempt:t.attempt+1})}catch(r){console.error(`[board] sync ${e} couldn't import ${t.id}:`,q(r)),n=q(r)}await d(`inboxAck`,{key:e,id:t.id,lease:t.lease,...n===void 0?{}:{error:n}}).catch(e=>console.error(`[board] couldn't ack an inbox event:`,q(e)))}async function Y(e,t,n,i,a=[]){if(t.length===0)return[];let o=[];for(let s of t){if(o.some(e=>e.url===s.url))continue;let t=(await k({thread:s.thread,message:s.message})).message,c=t===null?null:await D(t);if(c&&!c.deleted&&c.channel===i){o.push({url:s.url,message:c.id,unavailable:null,snapshot:{author:c.author?r(c.author):c.by.actor,text:c.text,createdAt:c.createdAt,files:c.attachments.map(e=>({name:e.name,url:null}))}});continue}if(s.snapshot){o.push({url:s.url,message:null,snapshot:s.snapshot,unavailable:null});continue}let l=a.find(e=>e.url===s.url&&e.snapshot&&e.message===null);if(l){o.push(l);continue}let u=await e.fetchLink(s,n).catch(e=>({snapshot:null,unavailable:q(e)}));o.push({url:s.url,message:null,snapshot:u.snapshot,unavailable:u.snapshot?null:(u.unavailable??`unknown`).slice(0,300)})}return K(o)}async function we(t,n,r){let a=[],o=[],s=null;for(let c of n.slice(0,10)){if(s!==null){o.push(_e(c,s));continue}if(c.size!==void 0&&c.size>26214400){o.push(H(c,`over ${e/1024/1024} MB`));continue}let n;try{let e=await t.fetchFile(c);if(e===null){o.push(H(c,`${t.platform} can't hand it over`));continue}n=e}catch(e){if(r<3)throw e;console.warn(`[board] couldn't fetch ${c.name??`a file`} from ${t.platform}:`,q(e)),o.push(H(c,`${t.platform} wouldn't hand it over`));continue}if(n.byteLength>26214400){o.push(H(c,`over ${e/1024/1024} MB`));continue}if(n.byteLength===0){o.push(H(c,`it was empty`));continue}let l=c.name??`${c.type}`;try{a.push((await d(`upload`,{data:n,name:l,type:c.mimeType||i(l)})).attachment)}catch(e){if(e instanceof _&&(e.code===`too_large`||e.code===`no_direct_uploads`)){o.push(H(c,`over ${y/1024/1024} MB`));continue}if(!U(e))throw e;s=e.message,o.push(_e(c,s))}}for(let e of n.slice(10))o.push(H(e,`a message carries at most 10`));return{attachments:a,notes:o}}async function Te(e,t,n){let r=f(e),i={...t,event:Ce(e,r.platform,t.event)},{event:a,raw:o}=i,c=(await k({thread:a.thread})).thread??void 0;if(a.kind===`message`){let e=(await k({thread:a.subthread??a.thread,message:a.message})).message;if(e!==null){let t=(await D(e))?.origin;if(!t||t.message!==a.message||(t.subthread??t.thread)!==(a.subthread??a.thread))return}}let l=`author`in a?a.author:{id:`${e}:system`,handle:r.platform,name:r.platform,avatar:null,isBot:!0},d,p=()=>d??=R(r.event({id:n.id,key:e,event:a,raw:o})),m,h,g=!0,_={direction:`in`,key:e,channel:x(a.channel),get event(){return p()},board:s().client({author:l,key:e,...De(e,a)},n.id),import(t,r={}){if(!g)throw u(`the sync function has finished`);return m??=Ee(e,i,n,c,t,r),m},permalink(){let e=h??r.permalink(p());return h=e,e.catch(()=>{h===e&&(h=void 0)}),e},resolve:t=>P(e,t)};try{await r.sync(_),await m}finally{g=!1}}async function Ee(e,t,n,r,i,a){let o=i??(r?(await w(r))?.channel:void 0);if(o===void 0)return{root:null,message:null};try{return await Oe(e,t,n,m.parse(o),fe.parse(a))}catch(e){if(!(e instanceof ne))throw e;let n=(await k({thread:t.event.thread})).thread;return{root:n===null?null:(await w(n))?.root??null,message:null}}}function De(e,t){let n=f(e),r=(`subthread`in t?t.subthread:null)??t.thread;return{via:{kind:`sync`,key:e,platform:n.platform,channel:t.channel,thread:r},respond:async e=>{await n.post(x(r),`thread`,{markdown:e})}}}async function Oe(e,t,n,r,i){let{event:o,raw:s}=t,c=De(e,o),l=f(e),p=(await k({thread:o.thread})).thread??void 0,m=p?await w(p):null,h=m?.root,g=e=>te(`board-inbound`,n.id,String(e)),_={key:e,channel:c.via.channel,thread:c.via.thread},v=async e=>{if(!e.dropped)return e.message;for(let t of e.dropped)await c.respond(t);throw new ne(e.dropped)},y=async({attachments:t=[],...n})=>({id:await v(await d(`syncImport`,{op:`post`,from:e,source:_,...n,origin:n.origin??null,...t.length?{attachments:t.map(e=>e.id)}:{}})),re:n.re??null}),b=e=>({root:e.re??e.id,message:e.id}),S=(e={})=>{let t={...e,...i.labels};for(let e of i.unset??[])delete t[e];return t},C=e=>{if(!i.root)return e;let t=i.root(R(structuredClone(e)));if(t&&typeof t==`object`&&`then`in t)throw u(`root overrides must be synchronous`);let n=fe.pick({text:!0,labels:!0}).parse(t);return{...e,text:n.text??e.text,labels:{...e.labels,...n.labels}}},ee=(t,n,r)=>d(`syncImport`,{op:`labels`,author:t,from:e,origin:{thread:o.thread},set:n,unset:r}),T=async(e,t)=>{if(!i.labels&&!i.unset)return;let n=await D(t),r=Object.fromEntries(Object.entries(i.labels??{}).filter(([e,t])=>n?.labels[e]!==t)),a=(i.unset??[]).filter(e=>n?.labels[e]!==void 0);(Object.keys(r).length||a.length)&&await ee(e,r,a)};switch(o.kind){case`message`:{let t=(await k({thread:o.subthread??o.thread,message:o.message})).message;if(t!==null)return{root:h??t,message:t};let{attachments:a,notes:c}=o.files?.length?await we(l,o.files,n.attempt):{attachments:[],notes:[]},u=await Y(l,o.links??[],{thread:o.subthread??o.thread,message:o.message},m?.channel??r),d={...u.length?{links:u}:{},author:o.author,text:V(W(i.text??o.text,c),a.length>0),...a.length?{attachments:a}:{},origin:{channel:o.channel,thread:o.thread,subthread:o.subthread,message:o.message,context:o.context},id:await g(0)},f={...d,...i.noSync?{noSync:!0}:{}};if(h!==void 0)return await T(o.author,h),b(await y({...f,re:h}));let p=await l.fetchRoot(x(o.thread));if(p===null){let e=C({text:o.text,labels:{},author:o.author,raw:s});return b(await y({...d,channel:r,text:V(W(i.text??e.text,c),a.length>0),labels:S(e.labels)}))}let _=C({...p,raw:p.raw??null}),v=await y({author:{...p.author,id:J(e,l.platform,p.author.id)},channel:r,text:V(_.text),labels:S(_.labels),origin:{channel:o.channel,thread:o.thread,subthread:null,message:`root:${n.id}`,context:null},id:await g(1)});return b(await y({...f,re:v.id}))}case`edited`:case`deleted`:case`reaction`:{let t=(await k({thread:o.subthread??o.thread,message:o.message})).message;if(t===null)return{root:h??null,message:null};let n=`author`in o?o.author:{id:`${e}:system`,handle:l.platform,name:l.platform,avatar:null,isBot:!0},r={thread:o.subthread??o.thread,message:o.message};if(h!==void 0&&await T(n,h),o.kind===`deleted`)await d(`syncImport`,{op:`delete`,author:n,from:e,origin:r});else if(o.kind===`edited`){let a=await D(t),s=V(W(i.text??o.text,a?ve(a.text):[]),(a?.attachments.length??0)>0);a&&!o.linksOnly&&a.text!==s&&await v(await d(`syncImport`,{op:`edit`,author:n,from:e,origin:r,text:s,source:_}));let c=a?await Y(l,o.links??[],r,a.channel,a.links):[];a&&!ye(c,a.links)&&await d(`syncImport`,{op:`links`,author:n,from:e,origin:r,links:c})}else{if(l.singleReaction){let i=a(o.emoji),s=/* @__PURE__ */ new Set([n.id,`${await j()}+${n.id}`]);for(let[a,c]of Object.entries((await D(t))?.reactions??{}))c.some(e=>s.has(e))&&!(o.added&&a===i)&&await d(`syncImport`,{op:`react`,author:n,from:e,origin:r,emoji:a,remove:!0})}(!l.singleReaction||o.added)&&await d(`syncImport`,{op:`react`,author:n,from:e,origin:r,emoji:o.emoji,remove:!o.added})}return{root:h??null,message:t}}case`lifecycle`:{if(h!==void 0){let t=await D(h),r=t?.origin?.message===`lifecycle:${n.id}`,a=S((r?C({text:X(o),labels:o.labels,author:o.author,raw:s}):null)?.labels??o.labels),c=e=>o.owns?.some(t=>e.startsWith(t))??!1,l=Object.fromEntries(Object.entries(a).filter(([e,n])=>t?.labels[e]!==n)),u=Object.keys(t?.labels??{}).filter(e=>!(e in a)&&(o.unset.includes(e)||i.unset?.includes(e)||c(e)));if(t&&!t.deleted&&(Object.keys(l).length||u.length)&&await ee(o.author,l,u),o.retitled&&t&&!t.deleted&&t.from===e&&t.origin?.thread===o.thread){let n=V(i.text??C({text:X(o),labels:t.labels,author:o.author,raw:s}).text);t.text!==n&&await v(await d(`syncImport`,{op:`edit`,author:o.author,from:e,origin:{thread:t.origin.thread,message:t.origin.message},text:n}))}return o.reply?b(await y({author:o.author,re:h,text:V(i.text??o.reply),...i.noSync?{noSync:!0}:{},id:await g(1)})):{root:h,message:r?h:null}}if(!o.createRoot)return{root:null,message:null};let t=C({text:X(o),labels:o.labels,author:o.author,raw:s}),a=await y({author:o.author,channel:r,text:V(o.reply?t.text:i.text??t.text),labels:S(t.labels),origin:{channel:o.channel,thread:o.thread,subthread:null,message:`lifecycle:${n.id}`,context:null},id:await g(0)});return o.reply?b(await y({author:o.author,re:a.id,text:V(i.text??o.reply),...i.noSync?{noSync:!0}:{},id:await g(1)})):b(a)}}}async function ke(e,t,n,r){let i=le(r);if(i.length===0)return r;let a=/* @__PURE__ */ new Map;for(let t of i)t.kind===`actor`&&!n.byId[t.actor]&&ue(t.actor)&&a.set(t.actor,await oe(e,t.actor));let o=/* @__PURE__ */ new Map;for(let t of i){if(t.kind!==`handle`)continue;let r=Object.values(n.byId).filter(e=>{let n=e.handle.toLowerCase();return n===t.handle||!t.handle.includes(`/`)&&n.slice(n.indexOf(`/`)+1)===t.handle});o.set(t.handle,r.flatMap(t=>{let r=je(e,t.id,n);return r===null?[]:[{id:t.id,mention:r}]}))}let s=[...o.values()].some(e=>new Set(e.map(e=>e.mention)).size>1)?new Set((await E(t.re??t.id)).map(e=>e.by.actor)):null,c=e=>{let t=new Set(e.map(e=>e.mention));return t.size===1?[...t][0]:null};return de(r,t=>{if(t.kind===`handle`){let e=o.get(t.handle)??[];return c(e)??(s?c(e.filter(e=>s.has(e.id))):null)}if(a.has(t.actor))return a.get(t.actor)??t.actor;let r=n.byId[t.actor];return r?je(e,r.id,n)??r.name:null})}function Ae(e,t,n){let{principal:r,profile:i}=re(t),a=i===null?t:c(i)!==null&&r===n.principal?i:null;return a?.startsWith(`${e}:`)?a.slice(e.length+1):null}function je(e,t,n){let r=n.byId[t],i=r?Ae(e,t,n):null;if(i===null)return null;let a=f(e);return a.mention({...r,id:`${a.platform}:${i}`})}async function Me(e,r,i,a,o){let s=a.byId[i.by.actor],c=s?.name??i.by.actor,l=`${s?.via?` ${n(s.via)}`:``}${i.from?` (${s?.platform??t[i.from]?.platform??i.from})`:``}`,d=s?.kind===`deployment`&&!s.via?/(?:@[^@/]+| \([^()]+\))$/.exec(c)?.[0]??``:``,p=`${c}${l}`,m=`${d}${l}`,h=f(e),g=(o??(e=>h.render(e)))(R({message:{...structuredClone(i),text:ae(i.text,i.by.actor)},author:s?{...s}:null,mentionOf:t=>je(e,t,a),label:p,target:r}));if(typeof g!=`string`)throw u(`a provider renderer must return markdown`);let _=await ke(e,i,a,g);return s?.verified?{markdown:_,as:{name:p,avatar:Ne(i,s),attribution:m}}:{markdown:_}}function Ne(e,t){let n=e=>!e||/\/avatars\/[a-z0-9-]+$/.test(e),r=t?.avatar??null;if(!n(r))return r;let i=t?.handle.split(`/`)[0]??``,a=e.by.principal.slice(12);return!e.by.principal.startsWith(`vercel:user:`)||!i||/^user-/.test(i)||i.toLowerCase()===a.toLowerCase()?r:`https://vercel.com/api/www/avatar?u=${encodeURIComponent(i)}&s=64&format=png`}let Pe=e=>e.attachments.map(t=>`\n📎 ${t.name} (${v(t.size)}, on the board: #${e.id})`).join(``),Z=async(e,t,n,r=!1,i)=>{let a=h(e),{markdown:o,as:s}=await Me(a,e,t,n,i);return{markdown:t.attachments.length>0&&(r||!f(a).uploadsFiles)?`${o}\n${Pe(t)}`:o,...s?{as:s}:{}}};async function Fe(e,t,n,r,i){let a=e.replyTo===null?void 0:(await O([e.replyTo]))[e.replyTo]?.[t],o=a!==void 0&&a.thread!==n?a.thread:n,s=f(h(t)),c=await Z(t,e,r,!1,i),l,d;if(!c.markdown.trim()&&e.attachments.length&&s.uploadsFiles)try{let n=await Re(e,t,o);d=n.message,l=n.files}catch(n){if(!s.refusesFiles(n)&&!U(n))throw n;c=await Z(t,e,r,!0,i),d=(await s.post(x(o),`thread`,c)).message,l=null}else{if(!c.markdown.trim())throw u(`a renderer must return text unless the message has media`);d=(await s.post(x(o),`thread`,c)).message}let p={thread:o,message:d,...l===void 0?{}:{files:l}};return await Ie(e,t,p),p}async function Ie(e,t,n){await d(`syncReceipt`,{kind:`message`,message:e.id,target:t,external:{thread:n.thread,message:n.message},...n.files===void 0?{}:{files:n.files}})}async function Le(e){return Promise.all(e.attachments.map(async e=>{let{data:t}=await d(`attachment`,{id:e.id});return{data:t instanceof Uint8Array?t:new Uint8Array(await new Response(t).arrayBuffer()),filename:e.name,mimeType:e.type}}))}async function Re(e,t,n){return f(h(t)).uploadFiles(x(n),await Le(e))}async function Q(e,t,n,r,i){let a=f(h(t));if(!a.uploadsFiles||e.attachments.length===0||n.files!==void 0)return;let o;try{o=(await Re(e,t,n.thread)).files}catch(s){if(!a.refusesFiles(s)&&!U(s))throw Object.assign(/* @__PURE__ */ Error(`files: ${q(s)}`),{cause:s,data:{error:`files: ${q(s)}`}});console.warn(`[board] ${t} won't take #${e.id}'s files (${q(s)}); noting them in its text`),o=null,await Z(t,e,r,!0,i).then(e=>a.edit(x(n.thread),n.message,e)).catch(n=>console.warn(`[board] couldn't note #${e.id}'s files on ${t}:`,q(n)))}await d(`syncReceipt`,{kind:`files`,message:e.id,target:t,files:o})}let ze=(e,t,n,r)=>{e.some(e=>e.error===r)||e.push({id:t,target:n,error:r})};async function Be(e,t){if(t.length!==0){if(e<5||S(e))throw t[0].error;for(let{id:e,target:n,error:r}of t)console.error(`[board] gave up ${n===null?`syncing #${e}`:`delivering #${e} to ${n}`}:`,q(r)),n!==null&&await d(`syncReceipt`,{kind:`failed`,message:e,target:n,error:q(r)})}}async function $(e,t,n,r,i){let a,o=!0,s=()=>u(`the sync function has finished`),c={direction:`out`,key:e,channel:r===null?null:ie(e,r),event:R(structuredClone(t)),message:R(structuredClone(n)),target:r,deliver(e={}){if(!o)throw s();return a??=r===null?Promise.resolve():i(e.render),a},start(t){if(!o)throw s();return Ve(e,n,t)},resolve:t=>P(e,t)};try{await f(e).sync(c),await a}finally{o=!1}}async function Ve(e,t,n){let{target:r,kind:i}=await I(`${e}:${n}`),a=t.re===null?t:await D(t.re);!a||a.deleted||a.noSync||r!==(a.origin?a.origin.channel??T(a.origin.thread):null)&&await d(`syncReceipt`,{kind:`thread`,message:a.id,target:r,targetKind:i,cause:`config`})}async function He(e,n){let r=[];for(let e of Object.keys(t))t[e].canStartThreads&&await g(e)&&r.push(e);if(e.payload.noSync||r.length===0)return;let i=await D(e.message.id);if(!i||i.deleted)return;let a=[];for(let t of r)try{await $(t,e,i,null,async()=>{})}catch(e){ze(a,i.id,null,e)}await Be(n,a)}async function Ue(e,t){let{thread:n,target:r}=e.payload;if(!await b(r)||(e.payload.kind??(p(r)?`thread`:`channel`))===`thread`)return;let i=await w(n);if(!i?.targets.includes(r))return;let[a,...o]=await E(i.root);if(!a||a.id!==i.root||a.deleted)return;let s=[];try{await $(h(r),e,a,r,e=>We(i,a,o,r,s,e))}catch(e){ze(s,a.id,r,e)}await Be(t,s)}async function We(e,t,n,r,i,a){let o=await M(),s=await O([t.id,...n.map(e=>e.id)]),c=e=>(i.push({id:t.id,target:r,error:e}),e),l=e.external[r];if(l){let e=s[t.id]?.[r];if(e)try{await Q(t,r,e,o,a)}catch(e){throw c(e)}}else try{let e=f(h(r)),n=await Z(r,t,o,!1,a),i=!n.markdown.trim()&&t.attachments.length>0&&e.uploadsFiles;if(!n.markdown.trim()&&!i)throw u(`a renderer must return text unless the message has media`);let s,c=await(async()=>{if(!i&&(t.attachments.length===0||!e.startsThreadsWithFiles))return e.post(x(r),`channel`,n);try{let a=await e.post(x(r),`channel`,{...n,files:await Le(t)});return s=i?a.files??[]:a.files,a}catch(n){if(!e.refusesFiles(n)&&!U(n))throw n;return s=null,e.post(x(r),`channel`,await Z(r,t,o,!0,a))}})();l=`${h(r)}:${c.thread}`;let d={thread:l,message:c.message,...s===void 0?{}:{files:s}};await Ie(t,r,d),await Q(t,r,d,o,a)}catch(e){throw c(e)}let d=[];for(let e of n)if(!(e.deleted||e.noSync||Ge(e,r)))try{await Q(e,r,s[e.id]?.[r]??await Fe(e,r,l,o,a),o,a)}catch(t){d.push({id:e.id,target:r,error:t})}if(i.push(...d),d.length)throw d[0].error}let Ge=(e,t)=>e.origin?.thread===t||e.from!==null&&h(t)===e.from;async function Ke(e,t){if(!e.message)return;if(e.message.re===null)return He(e,t);if(e.payload.noSync)return;let n=await w(e.payload.thread);if(!n||n.targets.length===0)return;let r=await D(e.message.id);if(!r||r.deleted)return;let i=await M(),a=[];for(let t of n.targets){let o=n.external[t];if(await b(t)&&o&&!Ge(r,t))try{await $(h(t),e,r,t,async e=>{let n=(await O([r.id]))[r.id]?.[t]??await Fe(r,t,o,i,e);await Q(r,t,n,i,e)})}catch(e){ze(a,r.id,t,e)}}await Be(t,a)}async function qe(e){let t=(await O([e.payload.id]))[e.payload.id]??{};if(Object.keys(t).length===0)return;let n=e.type===`message.edited`?await D(e.payload.id):e.message??await D(e.payload.id);if(!n||e.type===`message.edited`&&n.deleted)return;let r=await M();for(let[i,o]of Object.entries(t))if(!(!await b(i)||e.payload.from!==null&&h(i)===e.payload.from))try{await $(h(i),e,n,i,async t=>{let s=f(h(i)),c=x(o.thread);e.type===`message.edited`?await s.edit(c,o.message,await Z(i,n,r,o.files===null,t)):e.type===`message.deleted`?(await s.delete(c,o.message),o.files?.length&&await s.deleteFiles(o.files)):e.type===`reaction.added`?await s.react(c,o.message,a(e.payload.emoji),!0):await s.react(c,o.message,a(e.payload.emoji),!1)})}catch(t){console.warn(`[board] skipped ${e.type} on ${i}:`,t.message)}}async function Je(e){let{id:t}=e.payload,n=(await O([t]))[t]??{},r=e.message;if(!r||Object.keys(n).length===0)return;let i=await D(t);if(!i||i.deleted)return;let a=await M(),o={...i,labels:r.labels},s={...i,labels:e.before?.labels??{}};for(let[t,r]of Object.entries(n))if(await b(t))try{await $(h(t),e,o,t,async e=>{let n=await Z(t,o,a,r.files===null,e);n.markdown!==(await Z(t,s,a,r.files===null,e)).markdown&&await f(h(t)).edit(x(r.thread),r.message,n)})}catch(e){console.warn(`[board] skipped labels.changed on ${t}:`,q(e))}}async function Ye(e,{attempt:t}){switch(e.type){case`thread.synced`:return Ue(e,t);case`message.posted`:return Ke(e,t);case`message.edited`:case`message.deleted`:case`reaction.added`:case`reaction.removed`:return qe(e);case`labels.changed`:return Je(e)}}async function Xe(e,t){let n=e[0]?await w(e[0].thread):null;if(!n)return[];let r=[];for(let e of new Set(Object.values(n.external)))await b(e)&&r.push(e);return(await Promise.all(r.map(async n=>{let r=h(n);try{let i=f(r),a=null;for(let t=e.length-1;t>=0&&a===null;t--){let r=e[t];!r.deleted&&r.origin?.thread===n&&(a=r.origin.message)}return await i.startTyping(x(n),a,t),n}catch(e){return console.warn(`[board] skipped typing on ${n}:`,q(e)),null}}))).filter(e=>e!==null)}async function Ze(e,t){try{return`${e}:${await f(e).resolveChannel(t)}`}catch(e){throw u(`can't resolve inbox channel: ${e.message}`)}}let Qe=e=>e===`unsupported`||e===`invalid_target`?400:e===`channel_not_found`?404:e===`ratelimited`?429:[`no_client`,`list_failed`,`internal_error`,`fatal_error`,`service_unavailable`,`request_timeout`].includes(e)?502:403;async function $e(e,t,n,r){let i=f(e);try{return await i.read(t,{limit:n,after:r})}catch(n){throw n instanceof z?new _(Qe(n.code),n.code,n.message):u(`can't read ${t} from ${e}: ${q(n)}`,`platform_error`)}}async function et(e,t){let n=f(e);try{return await n.join(t)}catch(n){throw n instanceof z?new _(Qe(n.code),n.code,n.message):u(`can't join ${t} on ${e}: ${q(n)}`,`platform_error`)}}return{entries:t,bind(e){o=e},caller:l,deliver:Ye,receive:Te,pull:B,normalizeTarget:I,handleWebhook:ce,inboxChannel:Ze,typing:Xe,readSource:$e,joinSource:et}}function X(e){let t=e.url?`${e.title}\n${e.url}`:e.title;return e.body?`${t}\n\n${e.body}`:t}export{Y as createSyncEngine,J as keyedId};
1
+ import{A as e,C as t,D as n,E as r,M as i,N as a,O as o,S as s,T as c,_ as l,a as u,b as d,c as f,d as p,f as m,g as h,h as g,i as _,j as v,k as y,l as b,m as x,n as S,o as C,p as w,r as T,s as ee,t as te,u as ne,v as E,w as re,x as D,y as O}from"./app.js";const k=/^\[vc\]: #\S*\r?\n/,A=/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g,ie=/!\[([^\]]+)\]\(https:\/\/vercel\.com\/static\/status\/[^)]+\)\s*(?:\[[^\]]*\]\((https?:\/\/[^)\s]+)\))?/;function ae(e){if(!k.test(e))return null;let t=e.search(/<details><summary>\d+ Skipped Deployments?<\/summary>/),n=[],r=0;for(let i of e.split(/\r?\n/)){let a=r;if(r=e.indexOf(`
2
+ `,r)+1||e.length,!i.startsWith(`|`)||/^\|\s*(Project|Name)\s*\|/.test(i)||/^\|\s*:?-/.test(i))continue;let o=i.split(`|`).slice(1,-1).map(e=>e.trim());if(o.length<2)continue;let s=ie.exec(o[1]);if(!s)continue;let c=[...o[0].matchAll(A)].at(-1),l=c?.[1]??o[0].replace(/<[^>]*>/g,``).trim();if(!l)continue;let u=o[2]?[...o[2].matchAll(A)].find(e=>/preview/i.test(e[1])):void 0,d=o[3]?.match(/<relative-time[^>]*>([^<]+)<\/relative-time>/)?.[1]?.trim()??(o[3]?.replace(/<[^>]*>/g,``).trim()||null),f=o[3]?.match(/<relative-time[^>]*\sdatetime="([^"]+)"/)?.[1]??null;n.push({project:l,projectUrl:c?.[2]??null,status:s[1].trim(),deploymentUrl:s[2]??null,previewUrl:u?.[2]??null,updated:d,updatedAt:f!==null&&!Number.isNaN(Date.parse(f))?f:null,skipped:t!==-1&&a>t})}return n.length>0?n:null}const j={ready:`✅`,building:`⏳`,queued:`⏳`,initializing:`⏳`,error:`❌`,failed:`❌`,canceled:`⚪`,ignored:`⚪`},M=(e,t)=>t?`[${e}](${t})`:e;function N(e){return e.map(e=>`- ${[`${j[e.status.toLowerCase()]??`▲`} **${M(e.project,e.projectUrl)}**`,`${M(e.status,e.deploymentUrl)}${e.skipped?` (skipped)`:``}`,...e.previewUrl?[M(`Preview`,e.previewUrl)]:[],...e.updated?[e.updated]:[]].join(` · `)}`).join(`
3
+ `)}function oe(e,t){let n=t===`github:user:35613825`?ae(e):null;return n?`**▲ Vercel**\n${N(n)}`:e}const se=/```[\s\S]*?```/g,P=/`[^`\n]*`/g,F=`[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?`,I=RegExp(`(?<![\\w@.-])@(${F}(?:/${F})?)(?!:\\S|[a-z0-9_/-]|\\.(?=[a-z0-9]))`,`gi`),L=/(?<![\w@.-])@\[([^\]\s]+)\]/g;function R(e){let t=e.replace(se,e=>` `.repeat(e.length)).replace(P,e=>` `.repeat(e.length));if(e.includes(`json#`))for(let{start:n,end:r}of o(e))t=`${t.slice(0,n)}${` `.repeat(r-n)}${t.slice(r)}`;return t}function ce(e){let t=R(e),n=[];for(let e of t.matchAll(L)){let t=e[1];t!==void 0&&n.push({index:e.index,token:{kind:`actor`,actor:t},key:`actor:${t}`})}for(let e of t.replace(L,e=>` `.repeat(e.length)).matchAll(I)){let t=e[1]?.toLowerCase();t!==void 0&&n.push({index:e.index,token:{kind:`handle`,handle:t},key:`handle:${t}`})}let r=/* @__PURE__ */ new Set;return n.sort((e,t)=>e.index-t.index).filter(({key:e})=>!r.has(e)&&r.add(e)).map(({token:e})=>e)}const le=e=>/^[^\s@:]+@[^\s@:]+$/.test(e);function ue(e,t){let n=R(e),r=[];for(let e of n.matchAll(L))r.push({index:e.index,length:e[0].length,token:{kind:`actor`,actor:e[1]}});for(let e of n.replace(L,e=>` `.repeat(e.length)).matchAll(I))r.push({index:e.index,length:e[0].length,token:{kind:`handle`,handle:e[1].toLowerCase()}});let i=``,a=0;for(let{index:n,length:o,token:s}of r.sort((e,t)=>e.index-t.index)){let r=e.slice(n,n+o);i+=e.slice(a,n)+(t(s,r)??r),a=n+o}return i+e.slice(a)}D({id:s().min(1),platform:s().min(1),key:s().min(1),...b.shape,raw:t()});const de=D({root:d(e=>typeof e==`function`).optional(),text:s().optional(),labels:x.optional(),unset:E(w).optional(),noSync:O().optional()}).strict();function z(e){if(e&&typeof e==`object`){for(let t of Object.values(e))z(t);Object.freeze(e)}return e}const fe=D({target:s().min(1),channel:s().min(1),kind:l([`channel`,`thread`])}).strict();var B=class extends Error{code;constructor(e,t){super(t),this.code=e}};const pe=e=>e instanceof B&&e.code===`channel_not_found`,me=D({event:f,raw:t(),dedupe:s().min(1)}),he=/* @__PURE__ */ new WeakMap,ge=e=>he.get(e),_e=e=>/^(```|~~~|[-*+] |\d+[.)] |#{1,6} |>|\|)/.test(e),V=(e,t=!1)=>{let n=h(e),r=n.trim()===``?t?``:`(no text)`:n;return r.length>1e4?`${r.slice(0,g-1).toWellFormed()}…`:r},H=(e,t,n=e.name??`a file`)=>`📎 ${n}${e.size===void 0?``:` (${v(e.size)})`} didn't come over: ${t}`,U=e=>e instanceof _&&e.code===`no_files`,ve=(e,t)=>{let n=e.name??`a file`;if(!e.url||!/^https?:\/\//.test(e.url))return H(e,t);let r=n.replace(/[[\]\\]/g,e=>`\\${e}`),i=e.url.replace(/[ ()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`);return H(e,t,`[${r}](${i})`)},W=(e,t)=>t.length?`${e.trim()?`${e}\n\n`:``}${t.join(`
4
+ `)}`:e,ye=e=>e.split(`
5
+ `).filter(e=>/^📎 .* didn't come over: /u.test(e)),G=e=>JSON.stringify([e.url,e.message,e.snapshot,e.unavailable]),be=(e,t)=>e.length===t.length&&e.every((e,n)=>G(e)===G(t[n])),xe=new AbortController().signal,Se=e=>{try{return JSON.parse(JSON.stringify(e??null))}catch{return null}},K=e=>typeof e==`string`?h(e):Array.isArray(e)?e.map(K):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,t])=>[h(e),K(t)])):e,q=e=>{let t=e?.data?.error,n=typeof t==`string`?t:e instanceof Error?e.message:String(e);return h(n.slice(0,500))||`unknown error`},Ce=e=>e instanceof _&&e.status===404;function J(e,t,n){return n.startsWith(`${e}:`)?n:`${e}:${n.startsWith(`${t}:`)?n.slice(t.length+1):n}`}function we(e,t,n){return`author`in n?{...n,author:{...n.author,id:J(e,t,n.author.id)}}:n}function Te(t){let o=null,s=()=>{if(!o)throw Error(`sync used before board() bound it`);return o},l={self:`sync`,origin:{via:{kind:`engine`}}};function d(e,t,n=xe,r=l){let i=s().backend;return i[e].call(i,r,t,n)}let f=e=>{let n=t[e];if(!n)throw u(`no sync entry named ${e}`);return n},h=e=>e.slice(0,e.indexOf(`:`)),g=e=>s().syncedHere(e),b=async e=>t[h(e)]!==void 0&&await g(h(e)),x=e=>e.slice(e.indexOf(`:`)+1);async function w(e){try{return await d(`syncThread`,{thread:e})}catch(e){if(Ce(e))return null;throw e}}async function E(e){try{let{message:t,replies:n}=await d(`message`,{id:e});return[t,...n]}catch(e){if(Ce(e))return[];throw e}}async function D(e){return(await E(e)).find(t=>t.id===e)??null}async function O(e){return e.length===0?{}:(await d(`syncCopies`,{message:[...new Set(e)]})).copies}let k=(e,t)=>d(`syncFind`,e,t),A=null;function ie(){if(A)return A;let e=d(`me`,{}).then(e=>e.principal);return A=e,e.catch(()=>{A===e&&(A=null)}),e}async function j(){let[{actors:e},t]=await Promise.all([d(`actors`,{}),ie().catch(()=>null)]),n={byId:{},principal:t};for(let t of e)n.byId[t.id]={id:t.id,kind:t.kind,handle:t.handle,name:t.name,avatar:t.avatar,...t.via?{via:{...t.via}}:{},...t.platform?{platform:t.platform}:{},...t.verified?{verified:!0}:{}};return n}let M=/* @__PURE__ */ new Map;function N(e,t){let n=`${e}:${t}`,r=M.get(n);if(r&&(!r.failed||Date.now()-r.at<6e4))return r.id;let i={id:f(e).resolveChannel(t),failed:!1,at:Date.now()};return i.id.catch(r=>{i.failed=!0;let a=pe(r);!a&&M.get(n)===i&&M.delete(n),console.warn(`[board] sync ${e}: ${a?`skipping`:`couldn't resolve`} ${t}: ${r.message}`)}),M.set(n,i),i.id}function se(e,t){if(!p(t))return x(t);try{let n=f(e).inboxChannel(e,t);return n===null?null:x(n)}catch{return null}}let P=/* @__PURE__ */ new Map;function F(e,t){let n=`${e}\u001f${t.toLowerCase()}`,r=P.get(n);if(r&&Date.now()-r.at<3e5)return r.mention;P.size>=1e3&&P.clear();let i=f(e),a=i.findByEmail(t).then(e=>e?i.mention({id:e.id,kind:`external`,handle:e.handle,name:e.name,avatar:e.avatar}):null,()=>null);return P.set(n,{at:Date.now(),mention:a}),a}async function I(e){let t=e.indexOf(`:`);if(t<=0)throw u(`sync targets look like <key>:<channel or thread>, got: ${e}`);let n=e.slice(0,t),r=f(n);try{let i=fe.parse(await r.resolveTarget(e.slice(t+1)));if(i.kind===`channel`&&!r.canStartThreads)throw Error(`${r.platform} cannot start threads; use an existing thread`);return{target:`${n}:${i.target}`,kind:i.kind}}catch(t){throw u(`can't sync to ${e}: ${t.message}`)}}async function L(e,t){let{event:n,raw:r,dedupe:i}=me.parse(K({...t,raw:Se(t.raw)}));for(let t of[n.channel,n.thread,`subthread`in n?n.subthread:null])if(t!==null&&!t.startsWith(`${e}:`))throw u(`provider locations must belong to sync entry ${e}`);let a=ge(f(e)),o=a&&await a(x(n.channel),t=>N(e,t)).catch(async e=>{if(await R(n.thread))return!0;throw e});(!a||o||await R(n.thread))&&await d(`inboxPush`,{key:e,events:[{id:i,event:n,raw:r}]})}async function R(e){try{return(await k({thread:e},AbortSignal.timeout(2e3))).thread!==null}catch(e){let t=e?.name;if(t===`TimeoutError`||t===`AbortError`)return!0;throw e}}async function he(e,n){let r=t[e];if(!r)throw C(`no sync entry named ${e}`);if(!await g(e))return new Response(null,{status:200});let i;try{i=await r.receive(e,n,t=>L(e,t))}catch(e){return e instanceof _&&e.status===400?(console.error(`[board] dropped an event the board refuses`,e),new Response(null,{status:200})):(console.error(`[board] intake failed`,e),new Response(`intake failed`,{status:500}))}let a=G([e]).catch(t=>console.error(`[board] couldn't pull ${e}'s inbox:`,q(t)));return T(a),i}async function G(e=Object.keys(t)){let n=0,r=Date.now()+24e4;for(let t of e)if(await g(t))for(;Date.now()<r;){let{items:e}=await d(`inboxNext`,{key:t,limit:10});if(e.length===0)break;await Promise.all(e.map(e=>Te(t,e))),n+=e.length}return n}async function Te(e,t){let n;try{await Oe(e,{event:t.event,raw:t.raw},{id:t.id,attempt:t.attempt+1})}catch(r){console.error(`[board] sync ${e} couldn't import ${t.id}:`,q(r)),n=q(r)}await d(`inboxAck`,{key:e,id:t.id,lease:t.lease,...n===void 0?{}:{error:n}}).catch(e=>console.error(`[board] couldn't ack an inbox event:`,q(e)))}async function Ee(e,t,n,i,a=[]){if(t.length===0)return[];let o=[];for(let s of t){if(o.some(e=>e.url===s.url))continue;let t=(await k({thread:s.thread,message:s.message})).message,c=t===null?null:await D(t);if(c&&!c.deleted&&c.channel===i){o.push({url:s.url,message:c.id,unavailable:null,snapshot:{author:c.author?r(c.author):c.by.actor,text:c.text,createdAt:c.createdAt,files:c.attachments.map(e=>({name:e.name,url:null}))}});continue}if(s.snapshot){o.push({url:s.url,message:null,snapshot:s.snapshot,unavailable:null});continue}let l=a.find(e=>e.url===s.url&&e.snapshot&&e.message===null);if(l){o.push(l);continue}let u=await e.fetchLink(s,n).catch(e=>({snapshot:null,unavailable:q(e)}));o.push({url:s.url,message:null,snapshot:u.snapshot,unavailable:u.snapshot?null:(u.unavailable??`unknown`).slice(0,300)})}return K(o)}async function De(t,n,r){let a=[],o=[],s=null;for(let c of n.slice(0,10)){if(s!==null){o.push(ve(c,s));continue}if(c.size!==void 0&&c.size>26214400){o.push(H(c,`over ${e/1024/1024} MB`));continue}let n;try{let e=await t.fetchFile(c);if(e===null){o.push(H(c,`${t.platform} can't hand it over`));continue}n=e}catch(e){if(r<3)throw e;console.warn(`[board] couldn't fetch ${c.name??`a file`} from ${t.platform}:`,q(e)),o.push(H(c,`${t.platform} wouldn't hand it over`));continue}if(n.byteLength>26214400){o.push(H(c,`over ${e/1024/1024} MB`));continue}if(n.byteLength===0){o.push(H(c,`it was empty`));continue}let l=c.name??`${c.type}`;try{a.push((await d(`upload`,{data:n,name:l,type:c.mimeType||i(l)})).attachment)}catch(e){if(e instanceof _&&(e.code===`too_large`||e.code===`no_direct_uploads`)){o.push(H(c,`over ${y/1024/1024} MB`));continue}if(!U(e))throw e;s=e.message,o.push(ve(c,s))}}for(let e of n.slice(10))o.push(H(e,`a message carries at most 10`));return{attachments:a,notes:o}}async function Oe(e,t,n){let r=f(e),i={...t,event:we(e,r.platform,t.event)},{event:a,raw:o}=i,c=(await k({thread:a.thread})).thread??void 0;if(a.kind===`message`){let e=(await k({thread:a.subthread??a.thread,message:a.message})).message;if(e!==null){let t=(await D(e))?.origin;if(!t||t.message!==a.message||(t.subthread??t.thread)!==(a.subthread??a.thread))return}}let l=`author`in a?a.author:{id:`${e}:system`,handle:r.platform,name:r.platform,avatar:null,isBot:!0},d,p=()=>d??=z(r.event({id:n.id,key:e,event:a,raw:o})),m,h,g=!0,_={direction:`in`,key:e,channel:x(a.channel),get event(){return p()},board:s().client({author:l,key:e,...Ae(e,a)},n.id),import(t,r={}){if(!g)throw u(`the sync function has finished`);return m??=ke(e,i,n,c,t,r),m},permalink(){let e=h??r.permalink(p());return h=e,e.catch(()=>{h===e&&(h=void 0)}),e},resolve:t=>N(e,t)};try{await r.sync(_),await m}finally{g=!1}}async function ke(e,t,n,r,i,a){let o=i??(r?(await w(r))?.channel:void 0);if(o===void 0)return{root:null,message:null};try{return await je(e,t,n,m.parse(o),de.parse(a))}catch(e){if(!(e instanceof te))throw e;let n=(await k({thread:t.event.thread})).thread;return{root:n===null?null:(await w(n))?.root??null,message:null}}}function Ae(e,t){let n=f(e),r=(`subthread`in t?t.subthread:null)??t.thread;return{via:{kind:`sync`,key:e,platform:n.platform,channel:t.channel,thread:r},respond:async e=>{await n.post(x(r),`thread`,{markdown:e})}}}async function je(e,t,n,r,i){let{event:o,raw:s}=t,c=Ae(e,o),l=f(e),p=(await k({thread:o.thread})).thread??void 0,m=p?await w(p):null,h=m?.root,g=e=>ee(`board-inbound`,n.id,String(e)),_={key:e,channel:c.via.channel,thread:c.via.thread},v=async e=>{if(!e.dropped)return e.message;for(let t of e.dropped)await c.respond(t);throw new te(e.dropped)},y=async({attachments:t=[],...n})=>({id:await v(await d(`syncImport`,{op:`post`,from:e,source:_,...n,origin:n.origin??null,...t.length?{attachments:t.map(e=>e.id)}:{}})),re:n.re??null}),b=e=>({root:e.re??e.id,message:e.id}),S=(e={})=>{let t={...e,...i.labels};for(let e of i.unset??[])delete t[e];return t},C=e=>{if(!i.root)return e;let t=i.root(z(structuredClone(e)));if(t&&typeof t==`object`&&`then`in t)throw u(`root overrides must be synchronous`);let n=de.pick({text:!0,labels:!0}).parse(t);return{...e,text:n.text??e.text,labels:{...e.labels,...n.labels}}},T=(t,n,r)=>d(`syncImport`,{op:`labels`,author:t,from:e,origin:{thread:o.thread},set:n,unset:r}),ne=async(e,t)=>{if(!i.labels&&!i.unset)return;let n=await D(t),r=Object.fromEntries(Object.entries(i.labels??{}).filter(([e,t])=>n?.labels[e]!==t)),a=(i.unset??[]).filter(e=>n?.labels[e]!==void 0);(Object.keys(r).length||a.length)&&await T(e,r,a)};switch(o.kind){case`message`:{let t=(await k({thread:o.subthread??o.thread,message:o.message})).message;if(t!==null)return{root:h??t,message:t};let{attachments:a,notes:c}=o.files?.length?await De(l,o.files,n.attempt):{attachments:[],notes:[]},u=await Ee(l,o.links??[],{thread:o.subthread??o.thread,message:o.message},m?.channel??r),d={...u.length?{links:u}:{},author:o.author,text:V(W(i.text??o.text,c),a.length>0),...a.length?{attachments:a}:{},origin:{channel:o.channel,thread:o.thread,subthread:o.subthread,message:o.message,context:o.context},id:await g(0)},f={...d,...i.noSync?{noSync:!0}:{}};if(h!==void 0)return await ne(o.author,h),b(await y({...f,re:h}));let p=await l.fetchRoot(x(o.thread));if(p===null){let e=C({text:o.text,labels:{},author:o.author,raw:s});return b(await y({...d,channel:r,text:V(W(i.text??e.text,c),a.length>0),labels:S(e.labels)}))}let _=C({...p,raw:p.raw??null}),v=await y({author:{...p.author,id:J(e,l.platform,p.author.id)},channel:r,text:V(_.text),labels:S(_.labels),origin:{channel:o.channel,thread:o.thread,subthread:null,message:`root:${n.id}`,context:null},id:await g(1)});return b(await y({...f,re:v.id}))}case`edited`:case`deleted`:case`reaction`:{let t=(await k({thread:o.subthread??o.thread,message:o.message})).message;if(t===null)return{root:h??null,message:null};let n=`author`in o?o.author:{id:`${e}:system`,handle:l.platform,name:l.platform,avatar:null,isBot:!0},r={thread:o.subthread??o.thread,message:o.message};if(h!==void 0&&await ne(n,h),o.kind===`deleted`)await d(`syncImport`,{op:`delete`,author:n,from:e,origin:r});else if(o.kind===`edited`){let a=await D(t),s=V(W(i.text??o.text,a?ye(a.text):[]),(a?.attachments.length??0)>0);a&&!o.linksOnly&&a.text!==s&&await v(await d(`syncImport`,{op:`edit`,author:n,from:e,origin:r,text:s,source:_}));let c=a?await Ee(l,o.links??[],r,a.channel,a.links):[];a&&!be(c,a.links)&&await d(`syncImport`,{op:`links`,author:n,from:e,origin:r,links:c})}else{if(l.singleReaction){let i=a(o.emoji),s=/* @__PURE__ */ new Set([n.id,`${await ie()}+${n.id}`]);for(let[a,c]of Object.entries((await D(t))?.reactions??{}))c.some(e=>s.has(e))&&!(o.added&&a===i)&&await d(`syncImport`,{op:`react`,author:n,from:e,origin:r,emoji:a,remove:!0})}(!l.singleReaction||o.added)&&await d(`syncImport`,{op:`react`,author:n,from:e,origin:r,emoji:o.emoji,remove:!o.added})}return{root:h??null,message:t}}case`lifecycle`:{if(h!==void 0){let t=await D(h),r=t?.origin?.message===`lifecycle:${n.id}`,a=S((r?C({text:Y(o),labels:o.labels,author:o.author,raw:s}):null)?.labels??o.labels),c=e=>o.owns?.some(t=>e.startsWith(t))??!1,l=Object.fromEntries(Object.entries(a).filter(([e,n])=>t?.labels[e]!==n)),u=Object.keys(t?.labels??{}).filter(e=>!(e in a)&&(o.unset.includes(e)||i.unset?.includes(e)||c(e)));if(t&&!t.deleted&&(Object.keys(l).length||u.length)&&await T(o.author,l,u),o.retitled&&t&&!t.deleted&&t.from===e&&t.origin?.thread===o.thread){let n=V(i.text??C({text:Y(o),labels:t.labels,author:o.author,raw:s}).text);t.text!==n&&await v(await d(`syncImport`,{op:`edit`,author:o.author,from:e,origin:{thread:t.origin.thread,message:t.origin.message},text:n}))}return o.reply?b(await y({author:o.author,re:h,text:V(i.text??o.reply),...i.noSync?{noSync:!0}:{},id:await g(1)})):{root:h,message:r?h:null}}if(!o.createRoot)return{root:null,message:null};let t=C({text:Y(o),labels:o.labels,author:o.author,raw:s}),a=await y({author:o.author,channel:r,text:V(o.reply?t.text:i.text??t.text),labels:S(t.labels),origin:{channel:o.channel,thread:o.thread,subthread:null,message:`lifecycle:${n.id}`,context:null},id:await g(0)});return o.reply?b(await y({author:o.author,re:a.id,text:V(i.text??o.reply),...i.noSync?{noSync:!0}:{},id:await g(1)})):b(a)}}}async function Me(e,t,n,r){let i=ce(r);if(i.length===0)return r;let a=/* @__PURE__ */ new Map;for(let t of i)t.kind===`actor`&&!n.byId[t.actor]&&le(t.actor)&&a.set(t.actor,await F(e,t.actor));let o=/* @__PURE__ */ new Map;for(let t of i){if(t.kind!==`handle`)continue;let r=Object.values(n.byId).filter(e=>{let n=e.handle.toLowerCase();return n===t.handle||!t.handle.includes(`/`)&&n.slice(n.indexOf(`/`)+1)===t.handle});o.set(t.handle,r.flatMap(t=>{let r=X(e,t.id,n);return r===null?[]:[{id:t.id,mention:r}]}))}let s=[...o.values()].some(e=>new Set(e.map(e=>e.mention)).size>1)?new Set((await E(t.re??t.id)).map(e=>e.by.actor)):null,c=e=>{let t=new Set(e.map(e=>e.mention));return t.size===1?[...t][0]:null};return ue(r,t=>{if(t.kind===`handle`){let e=o.get(t.handle)??[];return c(e)??(s?c(e.filter(e=>s.has(e.id))):null)}if(a.has(t.actor))return a.get(t.actor)??t.actor;let r=n.byId[t.actor];return r?X(e,r.id,n)??r.name:null})}function Ne(e,t,n){let{principal:r,profile:i}=re(t),a=i===null?t:c(i)!==null&&r===n.principal?i:null;return a?.startsWith(`${e}:`)?a.slice(e.length+1):null}function X(e,t,n){let r=n.byId[t],i=r?Ne(e,t,n):null;if(i===null)return null;let a=f(e);return a.mention({...r,id:`${a.platform}:${i}`})}async function Pe(e,r,i,a,o){let s=a.byId[i.by.actor],c=s?.name??i.by.actor,l=`${s?.via?` ${n(s.via)}`:``}${i.from?` (${s?.platform??t[i.from]?.platform??i.from})`:``}`,d=s?.kind===`deployment`&&!s.via?/(?:@[^@/]+| \([^()]+\))$/.exec(c)?.[0]??``:``,p=`${c}${l}`,m=`${d}${l}`,h=f(e),g=(o??(e=>h.render(e)))(z({message:{...structuredClone(i),text:oe(i.text,i.by.actor)},author:s?{...s}:null,mentionOf:t=>X(e,t,a),label:p,target:r}));if(typeof g!=`string`)throw u(`a provider renderer must return markdown`);let _=`**${p}**: `,v=await Me(e,i,a,g.startsWith(_)&&_e(g.slice(_.length))?`**${p}**:\n\n${g.slice(_.length)}`:g),y=i.by.actor===`github:user:35613825`?ae(i.text):null;return{markdown:v,...s?.verified?{as:{name:p,avatar:Fe(i,s),attribution:m}}:{},...y?{deployments:y}:{}}}function Fe(e,t){let n=e=>!e||/\/avatars\/[a-z0-9-]+$/.test(e),r=t?.avatar??null;if(!n(r))return r;let i=t?.handle.split(`/`)[0]??``,a=e.by.principal.slice(12);return!e.by.principal.startsWith(`vercel:user:`)||!i||/^user-/.test(i)||i.toLowerCase()===a.toLowerCase()?r:`https://vercel.com/api/www/avatar?u=${encodeURIComponent(i)}&s=64&format=png`}let Ie=e=>e.attachments.map(t=>`\n📎 ${t.name} (${v(t.size)}, on the board: #${e.id})`).join(``),Z=async(e,t,n,r=!1,i)=>{let a=h(e),{markdown:o,...s}=await Pe(a,e,t,n,i);return{markdown:t.attachments.length>0&&(r||!f(a).uploadsFiles)?`${o}\n${Ie(t)}`:o,...s}};async function Le(e,t,n,r,i){let a=e.replyTo===null?void 0:(await O([e.replyTo]))[e.replyTo]?.[t],o=a!==void 0&&a.thread!==n?a.thread:n,s=f(h(t)),c=await Z(t,e,r,!1,i),l,d;if(!c.markdown.trim()&&e.attachments.length&&s.uploadsFiles)try{let n=await Be(e,t,o);d=n.message,l=n.files}catch(n){if(!s.refusesFiles(n)&&!U(n))throw n;c=await Z(t,e,r,!0,i),d=(await s.post(x(o),`thread`,c)).message,l=null}else{if(!c.markdown.trim())throw u(`a renderer must return text unless the message has media`);d=(await s.post(x(o),`thread`,c)).message}let p={thread:o,message:d,...l===void 0?{}:{files:l}};return await Re(e,t,p),p}async function Re(e,t,n){await d(`syncReceipt`,{kind:`message`,message:e.id,target:t,external:{thread:n.thread,message:n.message},...n.files===void 0?{}:{files:n.files}})}async function ze(e){return Promise.all(e.attachments.map(async e=>{let{data:t}=await d(`attachment`,{id:e.id});return{data:t instanceof Uint8Array?t:new Uint8Array(await new Response(t).arrayBuffer()),filename:e.name,mimeType:e.type}}))}async function Be(e,t,n){return f(h(t)).uploadFiles(x(n),await ze(e))}async function Q(e,t,n,r,i){let a=f(h(t));if(!a.uploadsFiles||e.attachments.length===0||n.files!==void 0)return;let o;try{o=(await Be(e,t,n.thread)).files}catch(s){if(!a.refusesFiles(s)&&!U(s))throw Object.assign(/* @__PURE__ */ Error(`files: ${q(s)}`),{cause:s,data:{error:`files: ${q(s)}`}});console.warn(`[board] ${t} won't take #${e.id}'s files (${q(s)}); noting them in its text`),o=null,await Z(t,e,r,!0,i).then(e=>a.edit(x(n.thread),n.message,e)).catch(n=>console.warn(`[board] couldn't note #${e.id}'s files on ${t}:`,q(n)))}await d(`syncReceipt`,{kind:`files`,message:e.id,target:t,files:o})}let Ve=(e,t,n,r)=>{e.some(e=>e.error===r)||e.push({id:t,target:n,error:r})};async function He(e,t){if(t.length!==0){if(e<5||S(e))throw t[0].error;for(let{id:e,target:n,error:r}of t)console.error(`[board] gave up ${n===null?`syncing #${e}`:`delivering #${e} to ${n}`}:`,q(r)),n!==null&&await d(`syncReceipt`,{kind:`failed`,message:e,target:n,error:q(r)})}}async function $(e,t,n,r,i){let a,o=!0,s=()=>u(`the sync function has finished`),c={direction:`out`,key:e,channel:r===null?null:se(e,r),event:z(structuredClone(t)),message:z(structuredClone(n)),target:r,deliver(e={}){if(!o)throw s();return a??=r===null?Promise.resolve():i(e.render),a},start(t){if(!o)throw s();return Ue(e,n,t)},resolve:t=>N(e,t)};try{await f(e).sync(c),await a}finally{o=!1}}async function Ue(e,t,n){let{target:r,kind:i}=await I(`${e}:${n}`),a=t.re===null?t:await D(t.re);!a||a.deleted||a.noSync||r!==(a.origin?a.origin.channel??ne(a.origin.thread):null)&&await d(`syncReceipt`,{kind:`thread`,message:a.id,target:r,targetKind:i,cause:`config`})}async function We(e,n){let r=[];for(let e of Object.keys(t))t[e].canStartThreads&&await g(e)&&r.push(e);if(e.payload.noSync||r.length===0)return;let i=await D(e.message.id);if(!i||i.deleted)return;let a=[];for(let t of r)try{await $(t,e,i,null,async()=>{})}catch(e){Ve(a,i.id,null,e)}await He(n,a)}async function Ge(e,t){let{thread:n,target:r}=e.payload;if(!await b(r)||(e.payload.kind??(p(r)?`thread`:`channel`))===`thread`)return;let i=await w(n);if(!i?.targets.includes(r))return;let[a,...o]=await E(i.root);if(!a||a.id!==i.root||a.deleted)return;let s=[];try{await $(h(r),e,a,r,e=>Ke(i,a,o,r,s,e))}catch(e){Ve(s,a.id,r,e)}await He(t,s)}async function Ke(e,t,n,r,i,a){let o=await j(),s=await O([t.id,...n.map(e=>e.id)]),c=e=>(i.push({id:t.id,target:r,error:e}),e),l=e.external[r];if(l){let e=s[t.id]?.[r];if(e)try{await Q(t,r,e,o,a)}catch(e){throw c(e)}}else try{let e=f(h(r)),n=await Z(r,t,o,!1,a),i=!n.markdown.trim()&&t.attachments.length>0&&e.uploadsFiles;if(!n.markdown.trim()&&!i)throw u(`a renderer must return text unless the message has media`);let s,c=await(async()=>{if(!i&&(t.attachments.length===0||!e.startsThreadsWithFiles))return e.post(x(r),`channel`,n);try{let a=await e.post(x(r),`channel`,{...n,files:await ze(t)});return s=i?a.files??[]:a.files,a}catch(n){if(!e.refusesFiles(n)&&!U(n))throw n;return s=null,e.post(x(r),`channel`,await Z(r,t,o,!0,a))}})();l=`${h(r)}:${c.thread}`;let d={thread:l,message:c.message,...s===void 0?{}:{files:s}};await Re(t,r,d),await Q(t,r,d,o,a)}catch(e){throw c(e)}let d=[];for(let e of n)if(!(e.deleted||e.noSync||qe(e,r)))try{await Q(e,r,s[e.id]?.[r]??await Le(e,r,l,o,a),o,a)}catch(t){d.push({id:e.id,target:r,error:t})}if(i.push(...d),d.length)throw d[0].error}let qe=(e,t)=>e.origin?.thread===t||e.from!==null&&h(t)===e.from;async function Je(e,t){if(!e.message)return;if(e.message.re===null)return We(e,t);if(e.payload.noSync)return;let n=await w(e.payload.thread);if(!n||n.targets.length===0)return;let r=await D(e.message.id);if(!r||r.deleted)return;let i=await j(),a=[];for(let t of n.targets){let o=n.external[t];if(await b(t)&&o&&!qe(r,t))try{await $(h(t),e,r,t,async e=>{let n=(await O([r.id]))[r.id]?.[t]??await Le(r,t,o,i,e);await Q(r,t,n,i,e)})}catch(e){Ve(a,r.id,t,e)}}await He(t,a)}async function Ye(e){let t=(await O([e.payload.id]))[e.payload.id]??{};if(Object.keys(t).length===0)return;let n=e.type===`message.edited`?await D(e.payload.id):e.message??await D(e.payload.id);if(!n||e.type===`message.edited`&&n.deleted)return;let r=await j();for(let[i,o]of Object.entries(t))if(!(!await b(i)||e.payload.from!==null&&h(i)===e.payload.from))try{await $(h(i),e,n,i,async t=>{let s=f(h(i)),c=x(o.thread);e.type===`message.edited`?await s.edit(c,o.message,await Z(i,n,r,o.files===null,t)):e.type===`message.deleted`?(await s.delete(c,o.message),o.files?.length&&await s.deleteFiles(o.files)):e.type===`reaction.added`?await s.react(c,o.message,a(e.payload.emoji),!0):await s.react(c,o.message,a(e.payload.emoji),!1)})}catch(t){console.warn(`[board] skipped ${e.type} on ${i}:`,t.message)}}async function Xe(e){let{id:t}=e.payload,n=(await O([t]))[t]??{},r=e.message;if(!r||Object.keys(n).length===0)return;let i=await D(t);if(!i||i.deleted)return;let a=await j(),o={...i,labels:r.labels},s={...i,labels:e.before?.labels??{}};for(let[t,r]of Object.entries(n))if(await b(t))try{await $(h(t),e,o,t,async e=>{let n=await Z(t,o,a,r.files===null,e);n.markdown!==(await Z(t,s,a,r.files===null,e)).markdown&&await f(h(t)).edit(x(r.thread),r.message,n)})}catch(e){console.warn(`[board] skipped labels.changed on ${t}:`,q(e))}}async function Ze(e,{attempt:t}){switch(e.type){case`thread.synced`:return Ge(e,t);case`message.posted`:return Je(e,t);case`message.edited`:case`message.deleted`:case`reaction.added`:case`reaction.removed`:return Ye(e);case`labels.changed`:return Xe(e)}}async function Qe(e,t){let n=e[0]?await w(e[0].thread):null;if(!n)return[];let r=[];for(let e of new Set(Object.values(n.external)))await b(e)&&r.push(e);return(await Promise.all(r.map(async n=>{let r=h(n);try{let i=f(r),a=null;for(let t=e.length-1;t>=0&&a===null;t--){let r=e[t];!r.deleted&&r.origin?.thread===n&&(a=r.origin.message)}return await i.startTyping(x(n),a,t),n}catch(e){return console.warn(`[board] skipped typing on ${n}:`,q(e)),null}}))).filter(e=>e!==null)}async function $e(e,t){try{return`${e}:${await f(e).resolveChannel(t)}`}catch(e){throw u(`can't resolve inbox channel: ${e.message}`)}}let et=e=>e===`unsupported`||e===`invalid_target`?400:e===`channel_not_found`?404:e===`ratelimited`?429:[`no_client`,`list_failed`,`internal_error`,`fatal_error`,`service_unavailable`,`request_timeout`].includes(e)?502:403;async function tt(e,t,n,r){let i=f(e);try{return await i.read(t,{limit:n,after:r})}catch(n){throw n instanceof B?new _(et(n.code),n.code,n.message):u(`can't read ${t} from ${e}: ${q(n)}`,`platform_error`)}}async function nt(e,t){let n=f(e);try{return await n.join(t)}catch(n){throw n instanceof B?new _(et(n.code),n.code,n.message):u(`can't join ${t} on ${e}: ${q(n)}`,`platform_error`)}}return{entries:t,bind(e){o=e},caller:l,deliver:Ze,receive:Oe,pull:G,normalizeTarget:I,handleWebhook:he,inboxChannel:$e,typing:Qe,readSource:tt,joinSource:nt}}function Y(e){let t=e.url?`${e.title}\n${e.url}`:e.title;return e.body?`${t}\n\n${e.body}`:t}export{Te as createSyncEngine,J as keyedId};
@@ -0,0 +1,2 @@
1
+ import { t as inspect } from "./inspect-dtQlHBcq.mjs";
2
+ export { inspect };
@@ -1,6 +1,6 @@
1
1
  import { h as ATTACHMENT_BYTES_MAX } from "./errors-DUzpDSrJ.mjs";
2
2
  import "./schemas-DAzSsgWk.mjs";
3
- import { t as Failed, u as who } from "./main-DjEJPCgo.mjs";
3
+ import { t as Failed, u as who } from "./main-CpsAmpEy.mjs";
4
4
  import { t as page } from "./page-D-OzDOAX.mjs";
5
5
  import { randomBytes, timingSafeEqual } from "node:crypto";
6
6
  import { createServer } from "node:http";
@@ -2,8 +2,9 @@ import { _ as IMPORT_BYTES_MAX, a as forbidden$1, b as mediaType, c as toErrorRe
2
2
  import { _ as actorKind, a as CAN_MAX, b as storable, c as Handle, d as Labels, g as SeenActorKind, h as RemoteWatcherId, i as Author, l as LabelKey, m as MessageText, n as Attachment, o as ChannelPath, p as MessageId, s as Emoji, t as ActorId, v as authorView, y as platformAvatar } from "./schemas-DAzSsgWk.mjs";
3
3
  import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-DymyhUzl.mjs";
4
4
  import { a as SCHEMA_DESCRIPTION_MAX, c as canonical, d as parseSchemaId, f as schemaId, i as BUILT_IN_SCHEMAS, l as checkDefinition, n as blocksIn, o as SCHEMA_NAME, s as SCHEMA_VERSION_MAX, u as isBuiltInName } from "./blocks-CVoBC7ur.mjs";
5
- import { a as compileWatcher, c as METHODS, h as VERSION, i as runMatch, m as SYNC, n as syncTarget, o as hasCriteria, r as canonicalWatchers, t as SYNC_ACTOR } from "./origin-9Ch-Zonv.mjs";
5
+ import "./routes-DrByOCc1.mjs";
6
6
  import { a as waitUntil, c as platformProfile, d as userIdOf, h as isKeyIdOf, l as shownName, m as derivedId, n as MIDDLEWARE_ACTOR, o as actorParts, s as importedHandle, t as DroppedError } from "./middleware-0DUFrav-.mjs";
7
+ import { a as compileWatcher, c as METHODS, h as VERSION, i as runMatch, m as SYNC, n as syncTarget, o as hasCriteria, r as canonicalWatchers, t as SYNC_ACTOR } from "./origin-D4ER_Tze.mjs";
7
8
  import { c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-BgBiaCyx.mjs";
8
9
  import { S as wroteAs, _ as removes, a as authenticates, c as checkPrincipal, d as grantIssuers, m as joined, n as GITHUB_ISSUER, o as checkCan, p as issuerName, s as checkGrant, x as workflowPath } from "./auth-Ft4AJptx.mjs";
9
10
  import { n as setOwn, t as own } from "./own-OwgPWdmh.mjs";
@@ -8340,6 +8341,7 @@ function build(options, binding) {
8340
8341
  },
8341
8342
  async inboxPush(caller, { key, events }) {
8342
8343
  const { principal } = await needSync(caller, "push to an inbox", true);
8344
+ for (const { id } of events) if (id.length > 300) throw badRequest(`an inbox event ID is 300 characters at most, got ${id.length}`);
8343
8345
  for (const { event } of events) for (const location of [
8344
8346
  event.channel,
8345
8347
  event.thread,
@@ -1,15 +1,15 @@
1
1
  import { g as DIRECT_UPLOAD_BYTES_MAX, u as BoardError, y as fileSize } from "./errors-DUzpDSrJ.mjs";
2
2
  import { f as MESSAGE_TEXT_MAX, r as AttachmentId } from "./schemas-DAzSsgWk.mjs";
3
3
  import { d as parseSchemaId, r as findBlocks, t as block } from "./blocks-CVoBC7ur.mjs";
4
- import { h as VERSION, s as withMentions } from "./origin-9Ch-Zonv.mjs";
5
4
  import { n as displayEmoji, r as normalizeEmoji } from "./emoji-CTLpvH-A.mjs";
6
5
  import { l as shownName } from "./middleware-0DUFrav-.mjs";
6
+ import { h as VERSION, s as withMentions } from "./origin-D4ER_Tze.mjs";
7
7
  import { r as PERMISSIONS } from "./access-BgBiaCyx.mjs";
8
- import { a as isApiMessageId, n as isBoardName } from "./exports-BVgUNVsP.mjs";
9
- import { i as groups, n as filters$1, o as options, r as globalOptions, s as usage$1, t as commands } from "./commands-C4fR0md0.mjs";
10
- import { a as vercel, c as connect, i as handTeam, l as handFetch, n as credentialSource, o as http, p as vercelProjectFile, r as credentialed, s as boardUrl, t as board, u as handLogin } from "./server-BHpUqip5.mjs";
11
- import { t as conformance } from "./conformance-BORt5nky.mjs";
12
- import { t as displayText } from "./bots-CGkO76qH.mjs";
8
+ import { a as isApiMessageId, n as isBoardName } from "./exports-BNk4w-b2.mjs";
9
+ import { i as groups, n as filters$1, o as options, r as globalOptions, s as usage$1, t as commands } from "./commands-B75pBXIV.mjs";
10
+ import { a as vercel, c as connect, i as handTeam, l as handFetch, n as credentialSource, o as http, p as vercelProjectFile, r as credentialed, s as boardUrl, t as board, u as handLogin } from "./server-FlDE6BDt.mjs";
11
+ import { t as conformance } from "./conformance-CHqXZoGe.mjs";
12
+ import { n as displayText } from "./bots-CLKKMgYf.mjs";
13
13
  import { spawn } from "node:child_process";
14
14
  import { readFile, stat, writeFile } from "node:fs/promises";
15
15
  import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
@@ -1341,8 +1341,23 @@ async function text(value, { optional = false } = {}) {
1341
1341
  }
1342
1342
  /** Uploads each `--attach` file, reading them all before sending any. */
1343
1343
  async function attachments(board) {
1344
+ const paths = flags.attach ?? [];
1345
+ if (paths.length > 10) throw usage(`Can't attach ${paths.length} files. A message carries at most 10.`, {
1346
+ reason: "too_many_attachments",
1347
+ next: [{
1348
+ instruction: `Attach the rest in another reply, or bundle them into one file (a zip or tarball)`,
1349
+ argv: [
1350
+ ...cli(),
1351
+ "reply",
1352
+ "<ID>",
1353
+ "<TEXT>",
1354
+ "--attach",
1355
+ "<FILE>"
1356
+ ]
1357
+ }]
1358
+ });
1344
1359
  const files = [];
1345
- for (const path of flags.attach ?? []) {
1360
+ for (const path of paths) {
1346
1361
  const data = await io.readFile(path);
1347
1362
  if (!data && path === "-") throw usage("Can't attach -: stdin is for the message's text. Pass - as the text to read it from stdin.", {
1348
1363
  reason: "file_not_found",
@@ -0,0 +1,428 @@
1
+ import { h as ATTACHMENT_BYTES_MAX, r as badRequest, t as HttpError } from "./errors-DUzpDSrJ.mjs";
2
+ import "./schemas-DAzSsgWk.mjs";
3
+ import { l as isThreadTarget } from "./external-DymyhUzl.mjs";
4
+ import { F as routes, s as Filters } from "./routes-DrByOCc1.mjs";
5
+ import { i as afterRetry } from "./middleware-0DUFrav-.mjs";
6
+ import { o as options } from "./commands-B75pBXIV.mjs";
7
+ import { z } from "zod";
8
+ //#endregion
9
+ //#region src/version.ts
10
+ const VERSION = "0.44.0";
11
+ //#endregion
12
+ //#region src/server/backend.ts
13
+ /** The subscription sync's outbound runs on, in `BoardBinding.subscriptions`. No watcher's ID starts with `@`. */
14
+ const SYNC = "@sync";
15
+ //#endregion
16
+ //#region src/server/routing.ts
17
+ /** board()'s own routes: the files it serves, and sync's, which run where board() does. */
18
+ const BOARD_ROUTES = [
19
+ "avatar",
20
+ "openapi",
21
+ "webhook",
22
+ "sync"
23
+ ];
24
+ /** Every protocol method, by the route it's served at. */
25
+ const METHODS = [
26
+ "discovery",
27
+ "me",
28
+ "channels",
29
+ "createChannel",
30
+ "actors",
31
+ "messages",
32
+ "threads",
33
+ "message",
34
+ "post",
35
+ "posted",
36
+ "edit",
37
+ "delete",
38
+ "react",
39
+ "label",
40
+ "schedule",
41
+ "schedules",
42
+ "cancelSchedule",
43
+ "grants",
44
+ "createGrant",
45
+ "updateGrant",
46
+ "explain",
47
+ "revokeGrant",
48
+ "schemas",
49
+ "schema",
50
+ "createSchema",
51
+ "upload",
52
+ "attachment",
53
+ "uploadStart",
54
+ "uploadFinish",
55
+ "watchers",
56
+ "register",
57
+ "matches",
58
+ "ack",
59
+ "events",
60
+ "syncImport",
61
+ "syncReceipt",
62
+ "syncThread",
63
+ "syncFind",
64
+ "syncCopies",
65
+ "inboxPush",
66
+ "inboxNext",
67
+ "inboxAck",
68
+ "inbox",
69
+ "typing",
70
+ "readSource",
71
+ "joinSource",
72
+ "synced",
73
+ "linked"
74
+ ];
75
+ const escape = (literal) => literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
76
+ function compile(method, path, target, own) {
77
+ const parts = path.split("/").filter(Boolean);
78
+ const source = parts.map((part) => part.startsWith(":") ? "/([^/]+)" : `/${escape(part)}`).join("");
79
+ return {
80
+ method,
81
+ pattern: new RegExp(`${source}$`),
82
+ names: parts.filter((part) => part.startsWith(":")).map((part) => part.slice(1)),
83
+ target,
84
+ segments: parts.length,
85
+ literals: parts.filter((part) => !part.startsWith(":")).length,
86
+ own
87
+ };
88
+ }
89
+ /**
90
+ * The routes a board answers, most specific first: each is matched as a suffix of the request's
91
+ * path, so `/api/board/messages/12` is `GET /messages/:id` under `/api/board`. A backend's own
92
+ * route at a protocol path takes its place. Discovery is the mount itself.
93
+ */
94
+ function createRouter(backendRoutes, basePath) {
95
+ const patterns = [
96
+ ...BOARD_ROUTES.map((name) => compile(routes[name].method, routes[name].path, {
97
+ kind: "board",
98
+ name
99
+ }, false)),
100
+ ...METHODS.filter((name) => name !== "discovery").map((name) => compile(routes[name].method, routes[name].path, {
101
+ kind: "protocol",
102
+ name
103
+ }, false)),
104
+ ...backendRoutes.map((route) => compile(route.method, route.path, {
105
+ kind: "backend",
106
+ route
107
+ }, true))
108
+ ].sort((a, b) => b.segments - a.segments || b.literals - a.literals || Number(b.own) - Number(a.own));
109
+ /** A segment that isn't URI-encoded names nothing: no route. */
110
+ const found = (candidate, base, values) => {
111
+ const params = {};
112
+ try {
113
+ candidate.names.forEach((name, i) => params[name] = decodeURIComponent(values[i]));
114
+ } catch {
115
+ return null;
116
+ }
117
+ const first = candidate.names[0];
118
+ return {
119
+ target: candidate.target,
120
+ base,
121
+ param: first === void 0 ? null : params[first],
122
+ params
123
+ };
124
+ };
125
+ const discovery = (base) => ({
126
+ target: {
127
+ kind: "protocol",
128
+ name: "discovery"
129
+ },
130
+ base,
131
+ param: null,
132
+ params: {},
133
+ root: true
134
+ });
135
+ return function route(method, pathname) {
136
+ const path = pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname;
137
+ if (basePath !== void 0) {
138
+ const base = basePath.replace(/\/+$/, "");
139
+ if (path !== base && !path.startsWith(`${base}/`)) return null;
140
+ const rest = path.slice(base.length) || "/";
141
+ if (rest === "/") return method === "GET" ? discovery(base) : null;
142
+ for (const candidate of patterns) {
143
+ const hit = candidate.method === method ? rest.match(new RegExp(`^${candidate.pattern.source}`)) : null;
144
+ if (hit) return found(candidate, base, hit.slice(1));
145
+ }
146
+ return null;
147
+ }
148
+ for (const candidate of patterns) {
149
+ if (candidate.method !== method) continue;
150
+ const hit = path.match(candidate.pattern);
151
+ if (hit) return found(candidate, path.slice(0, hit.index), hit.slice(1));
152
+ }
153
+ return method === "GET" ? discovery(path === "/" ? "" : path) : null;
154
+ };
155
+ }
156
+ function queryObject(url) {
157
+ const out = {};
158
+ for (const key of new Set(url.searchParams.keys())) {
159
+ const values = url.searchParams.getAll(key);
160
+ out[key] = values.length > 1 ? values : values[0];
161
+ }
162
+ return out;
163
+ }
164
+ async function readJson(request) {
165
+ const text = await request.text();
166
+ if (text.trim() === "") return void 0;
167
+ try {
168
+ return JSON.parse(text);
169
+ } catch {
170
+ throw badRequest("request body is not valid JSON");
171
+ }
172
+ }
173
+ const tooLarge = () => new HttpError(413, "too_large", `attachments are at most ${ATTACHMENT_BYTES_MAX / 1024 / 1024} MB`);
174
+ /** The body, refused as soon as it's past `max`: with or without a `content-length`, it never reads more. */
175
+ async function readCapped(request, max) {
176
+ if (Number(request.headers.get("content-length") ?? 0) > max) throw tooLarge();
177
+ const chunks = [];
178
+ let size = 0;
179
+ for await (const chunk of request.body ?? []) {
180
+ size += chunk.byteLength;
181
+ if (size > max) throw tooLarge();
182
+ chunks.push(chunk);
183
+ }
184
+ const body = new Uint8Array(size);
185
+ let at = 0;
186
+ for (const chunk of chunks) {
187
+ body.set(chunk, at);
188
+ at += chunk.byteLength;
189
+ }
190
+ return body;
191
+ }
192
+ function openapi() {
193
+ const paths = {};
194
+ for (const [name, definition] of Object.entries(routes)) {
195
+ const path = definition.path.replace(/:(\w+)/g, "{$1}");
196
+ const operation = { operationId: name };
197
+ if ("query" in definition) operation["x-query-schema"] = z.toJSONSchema(definition.query, { io: "input" });
198
+ if ("body" in definition) operation.requestBody = { content: { "application/json": { schema: z.toJSONSchema(definition.body, { io: "input" }) } } };
199
+ (paths[path] ??= {})[definition.method.toLowerCase()] = operation;
200
+ }
201
+ return {
202
+ openapi: "3.1.0",
203
+ info: {
204
+ title: "board",
205
+ version: VERSION
206
+ },
207
+ paths
208
+ };
209
+ }
210
+ //#endregion
211
+ //#region src/api/tail.ts
212
+ /** The filter flags `read`, `tail`, and `wait` share, and that a watcher's `tail` accepts. */
213
+ const FILTER_FLAGS = {
214
+ re: options.re,
215
+ by: options.by,
216
+ mentions: options.mentions,
217
+ label: options.label,
218
+ source: options.source,
219
+ text: options.text
220
+ };
221
+ /**
222
+ * What `--mentions` takes as its value when it's the next word: `@ada`, `ada@vercel.com`, or `me`.
223
+ * A channel never has an `@`, and a flag (`--text=a@b`) is never the value.
224
+ */
225
+ const mentionValue = (word) => word !== void 0 && !word.startsWith("-") && (word === "me" || word.includes("@"));
226
+ /**
227
+ * `--mentions` alone means mentions of me; `--mentions @ada`, mentions of ada; `--mentions
228
+ * ada@vercel.com`, of the user with that email. Nothing after `--` is a flag.
229
+ */
230
+ function withMentions(args) {
231
+ const out = [];
232
+ for (let i = 0; i < args.length; i++) {
233
+ const arg = args[i];
234
+ if (arg === "--") {
235
+ out.push(...args.slice(i));
236
+ break;
237
+ }
238
+ if (arg !== "--mentions") out.push(arg);
239
+ else if (mentionValue(args[i + 1])) out.push(`--mentions=${args[++i]}`);
240
+ else out.push("--mentions=me");
241
+ }
242
+ return out;
243
+ }
244
+ /** Splits an expression the way a shell would: whitespace separates, quotes group, `\` escapes. */
245
+ function words(expression) {
246
+ const out = [];
247
+ let word = null;
248
+ let quote = null;
249
+ for (let i = 0; i < expression.length; i++) {
250
+ const char = expression[i];
251
+ if (quote) {
252
+ if (char === quote) quote = null;
253
+ else if (char === "\\" && quote === "\"" && i + 1 < expression.length) word += expression[++i];
254
+ else word += char;
255
+ } else if (/\s/.test(char)) {
256
+ if (word !== null) out.push(word);
257
+ word = null;
258
+ } else if (char === "\"" || char === "'") {
259
+ quote = char;
260
+ word ??= "";
261
+ } else if (char === "\\" && i + 1 < expression.length) word = (word ?? "") + expression[++i];
262
+ else word = (word ?? "") + char;
263
+ }
264
+ if (quote) throw new Error(`unterminated ${quote}`);
265
+ if (word !== null) out.push(word);
266
+ return out;
267
+ }
268
+ /** A watcher's tail takes the filters and `--all`, which shows receipts as it does in `vb tail`. */
269
+ const TAIL_FLAGS = {
270
+ ...FILTER_FLAGS,
271
+ all: { type: "boolean" }
272
+ };
273
+ /**
274
+ * Parses filter flags as the CLI's parser does (Node's `parseArgs`, strict), written out so a tail
275
+ * parses wherever board() runs, a browser included.
276
+ */
277
+ function parseFilterFlags(args) {
278
+ const values = {};
279
+ const positionals = [];
280
+ for (let i = 0; i < args.length; i++) {
281
+ const arg = args[i];
282
+ if (arg === "--") {
283
+ positionals.push(...args.slice(i + 1));
284
+ break;
285
+ }
286
+ if (!arg.startsWith("-") || arg === "-") {
287
+ positionals.push(arg);
288
+ continue;
289
+ }
290
+ const eq = arg.indexOf("=");
291
+ const name = arg.startsWith("--") ? arg.slice(2, eq === -1 ? void 0 : eq) : null;
292
+ const spec = name !== null && Object.hasOwn(TAIL_FLAGS, name) ? TAIL_FLAGS[name] : null;
293
+ if (!spec) throw new Error(`${name !== null ? `--${name}` : arg.slice(0, 2)} isn't a filter`);
294
+ if (spec.type === "boolean") {
295
+ if (eq !== -1) throw new Error(`--${name} takes no value`);
296
+ values[name] = true;
297
+ continue;
298
+ }
299
+ let value;
300
+ if (eq !== -1) value = arg.slice(eq + 1);
301
+ else {
302
+ const next = args[i + 1];
303
+ if (next === void 0 || next.length > 1 && next.startsWith("-")) throw new Error(`--${name} needs a value`);
304
+ value = next;
305
+ i++;
306
+ }
307
+ if ("multiple" in spec) values[name] = [...values[name] ?? [], value];
308
+ else values[name] = value;
309
+ }
310
+ return {
311
+ values,
312
+ positionals
313
+ };
314
+ }
315
+ /** A watcher's `tail`: its filters, and whether `--all` shows it receipts too. */
316
+ function parseWatchTail(expression) {
317
+ const { values, positionals } = parseFilterFlags(withMentions(words(expression)));
318
+ if (positionals.length > 1) throw new Error(`expected one channel, got: ${positionals.join(" ")}`);
319
+ const channel = positionals[0];
320
+ const parsed = Filters.safeParse({
321
+ ...channel ? { channel } : {},
322
+ ...values.re ? { re: values.re.replace(/^#/, "") } : {},
323
+ ...values.by ? { by: values.by.replace(/^@/, "") } : {},
324
+ ...values.mentions ? { mentions: values.mentions.replace(/^@/, "") } : {},
325
+ ...values.label?.length ? { label: values.label } : {},
326
+ ...values.source ? { from: values.source } : {},
327
+ ...values.text ? { text: values.text } : {}
328
+ });
329
+ if (!parsed.success) {
330
+ const issue = parsed.error.issues[0];
331
+ throw new Error(`${issue?.path.length ? `--${String(issue.path[0])}: ` : ""}${issue?.message ?? "invalid filters"}`);
332
+ }
333
+ return {
334
+ filters: parsed.data,
335
+ all: values.all === true
336
+ };
337
+ }
338
+ //#endregion
339
+ //#region src/server/watch-spec.ts
340
+ /** Whether filters narrow anything: a view a message can enter. */
341
+ const hasCriteria = (filters) => filters.channel !== void 0 || filters.re !== void 0 || filters.by !== void 0 || filters.mentions !== void 0 || filters.from !== void 0 || filters.text !== void 0 || (filters.label?.length ?? 0) > 0;
342
+ /** A watcher's tail, checked the way a boot checks it: errors name the watcher. */
343
+ function compileWatcher(id, spec) {
344
+ let filters;
345
+ let all;
346
+ try {
347
+ ({filters, all} = parseWatchTail(spec.tail));
348
+ } catch (error) {
349
+ throw new Error(`watch ${id}: ${error.message}`);
350
+ }
351
+ if (filters.mentions === "me") throw new Error(`watch ${id}: a watcher has no "me": use --mentions @handle`);
352
+ return {
353
+ filters,
354
+ criteria: hasCriteria(filters),
355
+ all
356
+ };
357
+ }
358
+ //#endregion
359
+ //#region src/server/watch-run.ts
360
+ /**
361
+ * A2 dead-letters an event after 10 failures, and a dead letter stops its
362
+ * lane, which is the thread's: the watcher would never run on that thread
363
+ * again. So `run` gets a few tries, then the failure is recorded and the
364
+ * thread moves on.
365
+ */
366
+ const RUN_ATTEMPTS = 5;
367
+ /**
368
+ * A run that's killed (a timeout, out of memory) never throws. A2 counts it
369
+ * toward the 10 failures when the next attempt takes over, and dead-letters
370
+ * the event at that takeover instead of running it: the 10th attempt is the
371
+ * last one a watcher sees. Throws give up at RUN_ATTEMPTS, so getting this far
372
+ * means runs keep dying, and the 10th records the failure without running.
373
+ */
374
+ const KILLED_ATTEMPTS = 10;
375
+ const describe = (error) => ((error instanceof Error ? error.message : String(error)) || "unknown error").slice(0, 500);
376
+ /**
377
+ * One match, on its thread's lane: `run`, retried while it fails (by A2 on a local board, by the
378
+ * tail on a person's Vercel board), then given up on and recorded so the thread's next event runs.
379
+ */
380
+ async function runMatch(input) {
381
+ const { watcher, match, attempt } = input;
382
+ const event = match.payload.event;
383
+ const giveUp = async (error) => {
384
+ console.error(`[board] watcher ${watcher.id} gave up on event #${event.cursor} after ${attempt} tries:`, error);
385
+ await input.record({
386
+ matched: match.id,
387
+ thread: match.payload.thread,
388
+ error
389
+ });
390
+ };
391
+ const early = !afterRetry(attempt);
392
+ if (early && attempt >= KILLED_ATTEMPTS) return giveUp(`its run was cut short ${attempt - 1} times (a timeout, or out of memory)`);
393
+ try {
394
+ await watcher.run(event);
395
+ } catch (error) {
396
+ if (!early || attempt < RUN_ATTEMPTS) throw error;
397
+ await giveUp(describe(error));
398
+ }
399
+ }
400
+ //#endregion
401
+ //#region src/server/watchers-hash.ts
402
+ /** By UTF-16 code unit, as `sort()` orders strings: the same in every locale and runtime. */
403
+ const byCodeUnit = (a, b) => a < b ? -1 : a > b ? 1 : 0;
404
+ /**
405
+ * What `watchersHash` hashes, the same on both ends: a board on `http()` hashes its watchers, and
406
+ * whether its sync subscribes, and the board it uses hashes what it holds.
407
+ */
408
+ function canonicalWatchers(watch, sync = []) {
409
+ const canonical = Object.keys(watch).sort(byCodeUnit).map((id) => [id, watch[id].tail]);
410
+ if (sync.length > 0) canonical.push(["sync", [...sync].sort((a, b) => byCodeUnit(a.key, b.key)).map((entry) => [entry.key, entry.platform])]);
411
+ return JSON.stringify(canonical);
412
+ }
413
+ //#endregion
414
+ //#region src/server/targets.ts
415
+ /** A target as a post or a receipt names it, resolved: a plain one's kind goes by its shape. */
416
+ const syncTarget = (target) => typeof target === "string" ? {
417
+ target,
418
+ kind: isThreadTarget(target) ? "thread" : "channel"
419
+ } : target;
420
+ //#endregion
421
+ //#region src/server/origin.ts
422
+ /**
423
+ * Sync in board() itself, on a board whose log is in this deployment (`local()`): it checked each
424
+ * platform event itself, so what it imports is by the platform user, not a profile of anyone.
425
+ */
426
+ const SYNC_ACTOR = "board:sync";
427
+ //#endregion
428
+ export { compileWatcher as a, METHODS as c, queryObject as d, readCapped as f, VERSION as h, runMatch as i, createRouter as l, SYNC as m, syncTarget as n, hasCriteria as o, readJson as p, canonicalWatchers as r, withMentions as s, SYNC_ACTOR as t, openapi as u };