@testmuai/kane-cli 0.8.9 → 0.8.10

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 (161) hide show
  1. package/dist/{ChatSurface-HXCRGPSE.js → ChatSurface-OWGOCHG3.js} +1 -1
  2. package/dist/{ChromeProfilePicker-PJS4NGEC.js → ChromeProfilePicker-QIMCWPPI.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-Q56VKWKM.js → CliFeedbackPrompt-34E2AXS4.js} +1 -1
  4. package/dist/{CliUploadProgress-TMVTKNOT.js → CliUploadProgress-TRKOSED7.js} +1 -1
  5. package/dist/{ConfigView-Y7ZVYT2C.js → ConfigView-XVKR7ATN.js} +1 -1
  6. package/dist/{EvidenceViewOffer-XV3WF2EC.js → EvidenceViewOffer-M2TGMSNE.js} +1 -1
  7. package/dist/FolderPicker-WZTNQ5IV.js +2 -0
  8. package/dist/{InfoBox-IDJYGPXF.js → InfoBox-QM5YEBMH.js} +1 -1
  9. package/dist/{LinksBox-5XNJ3UJJ.js → LinksBox-CSEDEZGU.js} +1 -1
  10. package/dist/{ProfilesView-U73QBC5W.js → ProfilesView-CZVPREIS.js} +1 -1
  11. package/dist/{ProjectPicker-KCE2VZCO.js → ProjectPicker-F6FEWNMY.js} +1 -1
  12. package/dist/{SaveSessionPrompt-3FHLIRLS.js → SaveSessionPrompt-RUSFOLBZ.js} +1 -1
  13. package/dist/SingleShotApp-WBFVUZFP.js +2 -0
  14. package/dist/{SummaryBox-GKHU4C4H.js → SummaryBox-KOJXTZVZ.js} +1 -1
  15. package/dist/TestMdRunView-BEXL7TIN.js +2 -0
  16. package/dist/{TestrunEvidenceTable-INNZCGTM.js → TestrunEvidenceTable-KGVBX76H.js} +1 -1
  17. package/dist/{WhoamiView-PSL7PUVT.js → WhoamiView-IOTBOCGK.js} +1 -1
  18. package/dist/{app-download-MBUJGT3R.js → app-download-7AF6QL2C.js} +1 -1
  19. package/dist/{auth-TYG473Z4.js → auth-2HTDCT7X.js} +1 -1
  20. package/dist/{binary-QQXWA35Q.js → binary-NKX3NEK7.js} +1 -1
  21. package/dist/{bind-WJ5UEMMZ.js → bind-IMBQFRKT.js} +2 -2
  22. package/dist/{bootstrap-MYG4TJVF.js → bootstrap-TNFANHSS.js} +1 -1
  23. package/dist/bridge-SXYWYZDO.js +2 -0
  24. package/dist/{changelog-N4L5ZUGF.js → changelog-SQVLSCYO.js} +1 -1
  25. package/dist/{chunk-IBPF5IM5.js → chunk-2BIPFAGX.js} +1 -1
  26. package/dist/{chunk-NTEI2O3O.js → chunk-2ULZVQZV.js} +2 -2
  27. package/dist/chunk-47OUD76M.js +6 -0
  28. package/dist/{chunk-PH4RABYU.js → chunk-5EKTQY2S.js} +1 -1
  29. package/dist/{chunk-O3RRCPIU.js → chunk-5Q3W3SX7.js} +1 -1
  30. package/dist/{chunk-LRHSWJDR.js → chunk-5YBKKWJA.js} +1 -1
  31. package/dist/{chunk-OR6M5HCV.js → chunk-6S3Z3WPF.js} +2 -2
  32. package/dist/chunk-724NYDMU.js +27 -0
  33. package/dist/{chunk-367NASYK.js → chunk-AWEUKXZQ.js} +1 -1
  34. package/dist/{chunk-IPZFZUJX.js → chunk-B4CYIZP5.js} +1 -1
  35. package/dist/{chunk-QS3DXKZN.js → chunk-BG2AZQLI.js} +1 -1
  36. package/dist/{chunk-TJR4R45C.js → chunk-BQSLPF5M.js} +1 -1
  37. package/dist/{chunk-6MJGCETZ.js → chunk-BUM367KV.js} +1 -1
  38. package/dist/{chunk-IANCFSSL.js → chunk-BZCVLCMG.js} +1 -1
  39. package/dist/{chunk-KKBID6TD.js → chunk-C33E5XQM.js} +1 -1
  40. package/dist/{chunk-QDE2BBAK.js → chunk-CKNVMB4E.js} +1 -1
  41. package/dist/chunk-CPGUTSUD.js +6 -0
  42. package/dist/{chunk-VSEWQEM5.js → chunk-CSCJLGIY.js} +1 -1
  43. package/dist/{chunk-NVNPXOOC.js → chunk-CXKWVHZK.js} +1 -1
  44. package/dist/{chunk-IDQBMC3B.js → chunk-D6566A2X.js} +1 -1
  45. package/dist/{chunk-OME5EJ5X.js → chunk-DF3DUGJS.js} +4 -4
  46. package/dist/{chunk-ZAKX5BN6.js → chunk-EH3YMGQ7.js} +1 -1
  47. package/dist/{chunk-CJD3EEPT.js → chunk-EKOL4WCC.js} +1 -1
  48. package/dist/{chunk-6UNXON3J.js → chunk-ESHDTCSZ.js} +1 -1
  49. package/dist/{chunk-TN4SXGAP.js → chunk-ETIQJIDI.js} +1 -1
  50. package/dist/{chunk-WHMMOMUY.js → chunk-FH6EDP77.js} +1 -1
  51. package/dist/{chunk-H6KL3FSB.js → chunk-FOP6CJAM.js} +1 -1
  52. package/dist/{chunk-IJYV3KKD.js → chunk-GHL2A273.js} +2 -2
  53. package/dist/{chunk-BOZODWIZ.js → chunk-GOF5PQ5T.js} +1 -1
  54. package/dist/{chunk-DUEROGOF.js → chunk-HE3ZKFRC.js} +1 -1
  55. package/dist/{chunk-Z2DT2QMX.js → chunk-HNNVVK2O.js} +1 -1
  56. package/dist/{chunk-22HCCSL7.js → chunk-HXSOZWFL.js} +1 -1
  57. package/dist/{chunk-TJLGHGUO.js → chunk-I3OVXNBW.js} +2 -2
  58. package/dist/{chunk-FT23VFSR.js → chunk-I5KYZHJ5.js} +48 -48
  59. package/dist/{chunk-ME3DGP7G.js → chunk-JGZWR3CR.js} +2 -2
  60. package/dist/{chunk-7RAIRUXO.js → chunk-KUAFVRSR.js} +1 -1
  61. package/dist/{chunk-MJHLQKQC.js → chunk-LKUWEQ5M.js} +1 -1
  62. package/dist/{chunk-F5BI3ALG.js → chunk-LTNMOEHT.js} +1 -1
  63. package/dist/{chunk-SJBIXLL3.js → chunk-LUTRUSIV.js} +1 -1
  64. package/dist/{chunk-2YQ6TW77.js → chunk-M6SFFAAQ.js} +6 -6
  65. package/dist/{chunk-R7GMVPAF.js → chunk-ML2E3JGK.js} +1 -1
  66. package/dist/{chunk-JPZHCB4Z.js → chunk-NDKHC6KL.js} +1 -1
  67. package/dist/{chunk-WH5RVDD6.js → chunk-NJQNHD5P.js} +1 -1
  68. package/dist/{chunk-ZBJAYCPS.js → chunk-NYQOYOBA.js} +1 -1
  69. package/dist/{chunk-AOB2ZX45.js → chunk-NYSFEZUR.js} +1 -1
  70. package/dist/{chunk-P2VERPOP.js → chunk-OSRRMY6M.js} +1 -1
  71. package/dist/{chunk-VDKGMVXZ.js → chunk-P3UGM74Z.js} +1 -1
  72. package/dist/{chunk-QHUNFH5P.js → chunk-PCVTSFIX.js} +1 -1
  73. package/dist/chunk-PDXZROJM.js +2 -0
  74. package/dist/{chunk-DGNVKMGN.js → chunk-PMOUXVUC.js} +1 -1
  75. package/dist/{chunk-COJGXGKZ.js → chunk-QJNQN6ND.js} +1 -1
  76. package/dist/{chunk-CCEXSCTN.js → chunk-RJ4YFH7K.js} +1 -1
  77. package/dist/{chunk-27P7PJAL.js → chunk-RP7FW23G.js} +1 -1
  78. package/dist/{chunk-SV5ZTCQA.js → chunk-RSNG5PBN.js} +1 -1
  79. package/dist/{chunk-GWSGTZMK.js → chunk-SAFETUCL.js} +1 -1
  80. package/dist/{chunk-OEH4LU5L.js → chunk-SAKUG4KE.js} +1 -1
  81. package/dist/{chunk-2DKJZPIH.js → chunk-SU3QKERU.js} +1 -1
  82. package/dist/{chunk-W5BTYVZD.js → chunk-SXUQBPQ6.js} +1 -1
  83. package/dist/{chunk-6S426ODE.js → chunk-SXX7ZE6L.js} +3 -3
  84. package/dist/{chunk-OLKHUNSQ.js → chunk-TGPI7VDR.js} +2 -2
  85. package/dist/{chunk-FC6DEFUP.js → chunk-TI7MR3PB.js} +1 -1
  86. package/dist/{chunk-34VSIQNO.js → chunk-UEANTGQS.js} +1 -1
  87. package/dist/{chunk-XPFFH2PC.js → chunk-USUFF3S6.js} +1 -1
  88. package/dist/{chunk-AARF24Z3.js → chunk-VIJUT5AR.js} +9 -9
  89. package/dist/{chunk-H5TNYYZW.js → chunk-W7PBJXLJ.js} +1 -1
  90. package/dist/{chunk-AROBXG66.js → chunk-WAI5UHW3.js} +1 -1
  91. package/dist/{chunk-DKUD2D5Y.js → chunk-WAWMIKSI.js} +1 -1
  92. package/dist/chunk-WEJA3EVI.js +2 -0
  93. package/dist/{chunk-VQFJM7VP.js → chunk-WXJQDLXX.js} +1 -1
  94. package/dist/chunk-XIGTZTFP.js +5 -0
  95. package/dist/{chunk-R5PIIYN2.js → chunk-XTUSDGAB.js} +1 -1
  96. package/dist/{chunk-ZHB7V3NY.js → chunk-YHL5NA43.js} +1 -1
  97. package/dist/{chunk-UEIQTXB6.js → chunk-YUA2VDWH.js} +1 -1
  98. package/dist/{chunk-M7D7EHNN.js → chunk-YXPWGIQ2.js} +1 -1
  99. package/dist/{chunk-HKCZ67AT.js → chunk-ZFZB4CGJ.js} +1 -1
  100. package/dist/{chunk-6ZNRPDLP.js → chunk-ZXTVP4WX.js} +2 -2
  101. package/dist/{config-ZDGCZZT3.js → config-UF635MC4.js} +1 -1
  102. package/dist/{credentials-YEWA7HXA.js → credentials-3KBLEVJH.js} +1 -1
  103. package/dist/{deps-bundle-JQUW73W5.js → deps-bundle-WGF4YYGO.js} +1 -1
  104. package/dist/{deps-resolve-RXF3JWAP.js → deps-resolve-DVJPU4YX.js} +1 -1
  105. package/dist/{dispatch-TRYJZWJE.js → dispatch-YTIJKX6C.js} +1 -1
  106. package/dist/{doctor-F7R4WUSI.js → doctor-2KRK42L2.js} +1 -1
  107. package/dist/{evidence-F3CQJQIB.js → evidence-CDCFEYS7.js} +1 -1
  108. package/dist/{evolve-cmd-ICTXNYU4.js → evolve-cmd-L3JIBYP5.js} +1 -1
  109. package/dist/{extract-bind-PH3VB7PY.js → extract-bind-VFQWACVO.js} +2 -2
  110. package/dist/{extract-cmd-HSESPCTL.js → extract-cmd-2OFQBBJ4.js} +1 -1
  111. package/dist/{generate-headless-Z5YF7UHX.js → generate-headless-B35UUR5A.js} +2 -2
  112. package/dist/index.js +26 -26
  113. package/dist/{ingest-cmd-SNPNVPIO.js → ingest-cmd-LAUSXSI3.js} +1 -1
  114. package/dist/install-ENSOEMSX.js +2 -0
  115. package/dist/{interactive-bind-HZG2KCTX.js → interactive-bind-OWASLPBQ.js} +3 -3
  116. package/dist/{list-commands-BHQHPHOH.js → list-commands-SLQDF6AT.js} +1 -1
  117. package/dist/login-flow-YKQUXP75.js +2 -0
  118. package/dist/{mobile-prompts-ELBW35KK.js → mobile-prompts-6MGOXIKX.js} +1 -1
  119. package/dist/persist-recorded-session-RKG7HOEW.js +3 -0
  120. package/dist/pipeline-M25AR7RM.js +2 -0
  121. package/dist/prepare-target-UGACDQEJ.js +2 -0
  122. package/dist/{reconcile-cmd-DBOUGUEB.js → reconcile-cmd-MR2MSVZ5.js} +1 -1
  123. package/dist/{reconcile-deps-RX66LB4B.js → reconcile-deps-RYO67ZXY.js} +2 -2
  124. package/dist/{reconcile-engine-OEDO57U7.js → reconcile-engine-PRH6YIAZ.js} +1 -1
  125. package/dist/{recording-banner-COX2HBLL.js → recording-banner-CH2SZ4IU.js} +1 -1
  126. package/dist/registry-ARR5ITIQ.js +2 -0
  127. package/dist/{require-project-folder-XFUJYJEA.js → require-project-folder-XY77JKAQ.js} +1 -1
  128. package/dist/{resolve-run-intent-24D3BV2J.js → resolve-run-intent-JFIGIF72.js} +1 -1
  129. package/dist/{resolver-ITA6TGPJ.js → resolver-6VDNZ6KP.js} +1 -1
  130. package/dist/{run-OTSAYPBQ.js → run-GTBYWSLW.js} +1 -1
  131. package/dist/{run-IHELHWA2.js → run-UETW72YU.js} +1 -1
  132. package/dist/{run-test-md-U5PSCPZU.js → run-test-md-OLGWTC4I.js} +2 -2
  133. package/dist/{skill-installer-STKFBIY4.js → skill-installer-NT7ZT6O4.js} +1 -1
  134. package/dist/{spawner-R76ROCR2.js → spawner-YQSAPZR4.js} +1 -1
  135. package/dist/tcg-generate-D73BMKOE.js +2 -0
  136. package/dist/testmd-actions-XPYXS36F.js +2 -0
  137. package/dist/token-refresh-2XVSIFRM.js +2 -0
  138. package/dist/{validate-basic-BPJVV64Y.js → validate-basic-OMAFYHME.js} +1 -1
  139. package/dist/{verdicts-56ZZN3E4.js → verdicts-KEBSV2NL.js} +1 -1
  140. package/dist/{version-check-PWHLDMPD.js → version-check-FRVZSYNF.js} +1 -1
  141. package/dist/{walk-session-OMUB7DPJ.js → walk-session-LNFOCPJ6.js} +1 -1
  142. package/dist/{with-telemetry-WI5FZFEK.js → with-telemetry-4ATZC6IR.js} +1 -1
  143. package/package.json +11 -11
  144. package/dist/FolderPicker-UGHFCPUL.js +0 -2
  145. package/dist/SingleShotApp-ECA24PKW.js +0 -2
  146. package/dist/TestMdRunView-KLMMXQCN.js +0 -2
  147. package/dist/bridge-S3WZ4TH2.js +0 -2
  148. package/dist/chunk-7UCICMK7.js +0 -5
  149. package/dist/chunk-BVON52QL.js +0 -6
  150. package/dist/chunk-D5MK4WTK.js +0 -26
  151. package/dist/chunk-DWHXXPDX.js +0 -2
  152. package/dist/chunk-HPBI3P6I.js +0 -6
  153. package/dist/install-VBUDO2YW.js +0 -2
  154. package/dist/login-flow-TWGSFMWW.js +0 -2
  155. package/dist/persist-recorded-session-DXUJXHC5.js +0 -3
  156. package/dist/pipeline-ULKJX3FG.js +0 -2
  157. package/dist/prepare-target-M656XQLU.js +0 -2
  158. package/dist/registry-PAVGNBIB.js +0 -2
  159. package/dist/tcg-generate-VJARWDD4.js +0 -2
  160. package/dist/testmd-actions-PXGLZV5L.js +0 -2
  161. package/dist/token-refresh-ZFT457VI.js +0 -2
@@ -1,17 +1,17 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as J,b as F}from"./chunk-2UIHS2FH.js";import{a as we}from"./chunk-YKTYVJBN.js";import{a as N,b as he,c as ye,d as be,e as Ee,f as _e,m as T}from"./chunk-54JZ6VEW.js";import{a as M}from"./chunk-N2P4MI32.js";import{b as B,d as W}from"./chunk-NVGBE2DR.js";import{C as j}from"./chunk-W3Z7AZNT.js";import{w as ge}from"./chunk-DWHXXPDX.js";var A="https://integrations.lambdatest.com",E=class extends Error{constructor(e,r){super(r);this.code=e;this.name="LisError"}};function ft(t){let n=t.TESTMUAI_ENV==="stage"?"stage":"prod";return`${ge[n].shareApiBaseUrl}/lis/api/v1`}function gt(t){let n=t.env??process.env,e=t.auth?.TESTMUAI_BASIC_AUTH||n.TESTMUAI_BASIC_AUTH;if(e)return{authorization:`Basic ${e}`};let r=t.auth?.TESTMUAI_API_KEY||n.TESTMUAI_API_KEY;return r?{authorization:`Bearer ${r}`}:{}}function k(t){let n=t.split(`
2
+ import{a as J,b as F}from"./chunk-2UIHS2FH.js";import{a as we}from"./chunk-YKTYVJBN.js";import{a as N,b as he,c as ye,d as be,e as Ee,f as _e,m as T}from"./chunk-54JZ6VEW.js";import{a as M}from"./chunk-N2P4MI32.js";import{b as B,d as W}from"./chunk-NVGBE2DR.js";import{C as j}from"./chunk-W3Z7AZNT.js";import{w as ge}from"./chunk-WEJA3EVI.js";var A="https://integrations.lambdatest.com",E=class extends Error{constructor(e,r){super(r);this.code=e;this.name="LisError"}};function ft(t){let n=t.TESTMUAI_ENV==="stage"?"stage":"prod";return`${ge[n].shareApiBaseUrl}/lis/api/v1`}function gt(t){let n=t.env??process.env,e=t.auth?.TESTMUAI_BASIC_AUTH||n.TESTMUAI_BASIC_AUTH;if(e)return{authorization:`Basic ${e}`};let r=t.auth?.TESTMUAI_API_KEY||n.TESTMUAI_API_KEY;return r?{authorization:`Bearer ${r}`}:{}}function k(t){let n=t.split(`
3
3
  `,1)[0].replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return n.length>200?`${n.slice(0,200)}\u2026`:n}function ht(t,n,e="the issue"){return t===401||t===403?new E("LIS_AUTH","credentials rejected \u2014 run `kane-cli login` and retry"):t>=500?new E("LIS_UNAVAILABLE",`the integrations service returned an error (HTTP ${t}) \u2014 retry later`):new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${e}: ${k(n)||`HTTP ${t}`}`)}function C(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{throw new E("LIS_UNAVAILABLE","the integrations service returned a malformed response \u2014 retry later")}}function ce(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{return{}}}function Le(t){return ce(t).code}function S(t,n="the issue",e="Atlassian"){let r=ce(t),s=e==="Atlassian"?"Confluence":e;switch(r.code){case"TOKEN_EXPIRED":return new E("LIS_SETUP",`your ${e} connection needs a resync \u2014 reconnect at ${A} and retry`);case"NOT_INSTALLED":return new E("LIS_SETUP",`no ${e} connection for this account \u2014 create one at ${A} and retry`);case"SCOPE_MISSING":return new E("LIS_SETUP",`the connection has no ${s} access \u2014 reconnect with ${s} at ${A} and retry`);case"FORBIDDEN":return new E("LIS_FORBIDDEN",`you don't have access to ${n}`);case"NOT_FOUND":return new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${n}: ${k(r.message??"")||"not found"}`);case"PAYLOAD_TOO_LARGE":return new E("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");case"INVALID_PAYLOAD":return new E("LIS_UNAVAILABLE",`the integrations service rejected the request (${k(r.message??"")||"invalid payload"}) \u2014 retry later`);case"NOT_SUPPORTED":return new E("LIS_UNAVAILABLE","the integrations service does not support this operation yet");case"UPSTREAM_ERROR":case"UPSTREAM_TIMEOUT":return new E("LIS_UNAVAILABLE",`${e} is not responding through the integrations service \u2014 retry later`);default:return ht(t.status,r.message??"",n)}}var yt=3e4,bt=5;async function $(t,n,e){let r=e.env??process.env,s=e.fetchImpl??fetch;for(let o=0;;o++){let l=new AbortController,u=setTimeout(()=>l.abort(),yt);try{let i=await s(`${ft(r)}${t}`,{...n,headers:{"content-type":"application/json",...gt(e),...n.headers??{}},signal:l.signal}),c=await Promise.race([i.arrayBuffer(),new Promise((d,p)=>{l.signal.addEventListener("abort",()=>p(new DOMException("aborted","AbortError")),{once:!0})})]),a={status:i.status,ok:i.ok,headers:i.headers,bytes:Buffer.from(c)};if(a.status===429){if(o>0)throw new E("LIS_RATE_LIMITED","the integrations service is busy \u2014 try again in a moment");let d=ce(a).data?.retry_after_sec,p=Math.min(Math.max(typeof d=="number"&&Number.isFinite(d)?d:1,0),bt);clearTimeout(u),await new Promise(y=>setTimeout(y,p*1e3));continue}return a}catch(i){throw i instanceof E?i:l.signal.aborted?new E("LIS_UNAVAILABLE","the integrations service did not respond within 30 seconds \u2014 retry later"):new E("LIS_UNAVAILABLE",`could not reach the integrations service (${k(i instanceof Error?i.message:String(i))}) \u2014 check your connection and retry`)}finally{clearTimeout(u)}}}function V(t){let n=t.headers.get("content-type")??"application/octet-stream";if(n.includes("json"))try{let e=JSON.parse(t.bytes.toString("utf8")),r=e.content??e.data?.content;if(typeof r=="string")return{bytes:Buffer.from(r,"base64"),mediaType:e.mime_type??e.data?.mime_type??"application/octet-stream"}}catch{}return{bytes:t.bytes,mediaType:n}}async function H(t={}){let n=await $("/jira/info",{method:"GET"},t);if(!n.ok)throw S(n);let e=C(n),r=(e.data?.SELECTED_PROJECTS??[]).map(s=>s?.key).filter(s=>typeof s=="string"&&s.length>0);return{installed:e.data?.INSTALLED==="YES",selectAll:e.data?.SELECT_ALL===!0,selectedProjects:r,capabilities:{document:e.data?.capabilities?.document===!0,comments:e.data?.capabilities?.comments===!0}}}async function z(t,n={}){let e=await $("/jira/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"jira",issueKey:t})},n);if(!e.ok)throw S(e);let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${k(r.message??"")||"issue not found or not accessible"}`);return r.data}var Ie=100,Et=5e3,_t=60;async function X(t,n={}){let e=[],r=new Set,s=null,o=0;for(let l=0;;l++){if(l>=_t)throw new E("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let u=await $("/jira/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:Ie,cursor:s,start_at:o,order_by:"created",fetch_all:!1})},n);if(!u.ok)throw S(u,"the issue's comments");let i=C(u);if(i.type==="error"||!i.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${k(i.message??"")||"unavailable"}`);for(let w of i.data.comments??[]){let f=String(w.id);r.has(f)||(r.add(f),e.push(w))}let c=i.data.pagination;if(!c?.has_more)return e;if(e.length>=Et)throw new E("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let a=c.next_cursor??null,d=c.next_start_at!=null,p=d?c.next_start_at:o+Ie;if(!(a!=null&&a!==s||a==null&&d&&p!==o))throw new E("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");s=a,o=p}}async function Z(t,n={}){let e=await $("/jira/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok){if(Le(e)===void 0){if(e.status===413)throw new E("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");if(e.status===404)throw new E("JIRA_NOT_CONNECTED",`Jira is not connected for this account \u2014 connect it at ${A} and retry`)}throw S(e,`attachment ${t}`)}return V(e)}var q="kane.source.jira/2";function Ae(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t)){let n=t.map(Ae).filter(e=>e!==null);return n.length===0?null:n.join(", ")}if(t!==null&&typeof t=="object"){let n=t;for(let e of["name","value","displayName"])if(typeof n[e]=="string")return n[e];return null}return null}function ve(t,n,e){let r=[],s={},o=t.additional_fields??{};for(let a of Object.keys(o).sort()){let d=Ae(o[a]);if(d===null){r.push(`field "${a}" has no stable text form \u2014 dropped from the envelope`);continue}s[a]=d}let l=[...t.attachments??[]].map(a=>({id:String(a.id),filename:a.filename??"",media_type:a.mime_type??"application/octet-stream",size:a.size??0})).sort((a,d)=>{let p=Number(a.id),y=Number(d.id);return Number.isFinite(p)&&Number.isFinite(y)?p-y:a.id<d.id?-1:a.id>d.id?1:0}),u=e.map(a=>({id:String(a.id),author:a.author?.display_name??"",body:a.body??"",created:a.created??""})).sort((a,d)=>{if(a.created!==d.created)return a.created<d.created?-1:1;let p=Number(a.id),y=Number(d.id);return Number.isFinite(p)&&Number.isFinite(y)&&p!==y?p-y:a.id<d.id?-1:a.id>d.id?1:0}),i=t.key;if(!/^[A-Za-z][A-Za-z0-9_]*-\d+$/.test(i))throw new Error(`cannot build a stable identity for issue key "${i}" \u2014 expected a PROJECT-NUMBER key`);let c={schema:q,site:n,project:i.slice(0,i.lastIndexOf("-")),issue:{id:t.id,key:i},content:{summary:t.summary??"",description:t.description??"",fields:s},attachments:l,comments:u};return{bytes:Buffer.from(JSON.stringify(c),"utf8"),envelope:c,warnings:r}}var Se=64,wt=16,Lt=6e6,It=5e7,At=12e6,vt={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},St=new Set(["png","jpeg","webp"]);function $e(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("JIRA_ENVELOPE_SCHEMA: source bytes are not a kane jira envelope")}if(e.schema!==q)throw new Error(`JIRA_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${q}`);let r=[],s=new Map,o=[],l=0,u=new Map,i=[];for(let d=0;d<e.attachments.length;d++){let p=e.attachments[d],y=`i${d+1}`,w=`attachment:${p.filename}`,f=v=>`[img#${y}] ${p.filename} (${p.media_type}, ${p.size} bytes${v?"":" \u2014 not delivered"})`,h=(v,R,x)=>{r.push({ref:y,loc:w,media_type:v,...x?.blob?{blob:x.blob}:{},...x?.appearance?{appearance:x.appearance}:{},delivery:R,...x?.duplicate_of?{duplicate_of:x.duplicate_of}:{}})};if(!p.media_type.startsWith("image/")){h(p.media_type,"unsupported-vision-media-type"),i.push(f(!1));continue}let _;try{_=await t.fetchAttachment(p.id)}catch{h(p.media_type,"external-image-not-fetched"),i.push(f(!1));continue}let b=_.bytes,g=J(b),m=vt[g.format],I=B(b);if(s.set(I,b),!St.has(g.format)){let v=g.format==="gif"||g.format==="bmp"||g.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(m,v,{blob:I}),i.push(f(!1));continue}if(g.width===void 0||g.height===void 0||g.width*g.height>It){h(m,"undecodable",{blob:I}),i.push(f(!1));continue}let L;if(g.format==="png"||g.format==="jpeg"){let v=F(b,g.format);if(v===null){h(m,"undecodable",{blob:I}),i.push(f(!1));continue}L=M(v.data,{width:v.width,height:v.height,channels:v.channels})}if(g.width<Se||g.height<Se){h(m,"below-dimension-floor",{blob:I,appearance:L}),i.push(f(!1));continue}let O=u.get(I);if(O!==void 0){h(m,"duplicate",{blob:I,appearance:L,duplicate_of:O}),i.push(f(!1));continue}if(b.byteLength>Lt){h(m,"image-too-large",{blob:I,appearance:L}),i.push(f(!1));continue}if(l+b.byteLength>At){h(m,"vision-byte-budget-reached",{blob:I,appearance:L}),i.push(f(!1));continue}if(o.length>=wt){h(m,"image-cap-reached",{blob:I,appearance:L}),i.push(f(!1));continue}u.set(I,y),l+=b.byteLength,o.push(y),h(m,"selected",{blob:I,appearance:L}),i.push(f(!0))}let c=[];c.push(`${e.issue.key} \xB7 ${e.site}/${e.project}`,`Summary: ${e.content.summary}`),e.content.description!==""&&c.push("",...e.content.description.split(`
4
4
  `));let a=Object.keys(e.content.fields);return a.length>0&&c.push("","--- fields ---",...a.map(d=>`${d}: ${e.content.fields[d]}`)),i.length>0&&c.push("","--- attachments ---",...i),e.comments.length>0&&(c.push("","--- comments ---"),e.comments.forEach((d,p)=>{p>0&&c.push(""),c.push(`[${p+1}] ${d.author} \xB7 ${d.created}`,...d.body.split(`
5
5
  `))})),{projection:c.join(`
6
6
  `)+`
7
- `,inventory:r,blobs:s,delivered:o,converter:{name:"jira-convert",version:"2",policy:"v1"}}}}var $t=/^[A-Za-z][A-Za-z0-9_]*-\d+$/;function Q(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.lastIndexOf("browse");if(r===-1||r+1>=e.length)return null;let s=e[r+1];return $t.test(s)?{site:n.hostname,issueKey:s.toUpperCase()}:null}function ee(t,n){let e=j(t),r=e.heads.get(n);return r==null?null:Ce(t,e,r)}function te(t,n){let r=ee(t,n)?.site;return typeof r=="string"&&r.length>0?r:null}function ke(t,n,e,r){let s=j(t);for(let[o,l]of s.heads){if(l==null||s.mediaOf(l).format!==n)continue;let u=Ce(t,s,l);if(u===null)continue;let i=u;for(let c of e){if(i===null||typeof i!="object"){i=void 0;break}i=i[c]}if(i===r)return o}return null}function Ce(t,n,e){let r=n.getNode(e)?.content?.blob;if(typeof r!="string")return null;let s=W(t,r);if(s===null)return null;try{let o=JSON.parse(s.toString("utf8"));return o!==null&&typeof o=="object"?o:null}catch{return null}}var Re={jira:"a jira issue source",confluence:"a confluence page source",linear:"a linear issue source","linear-doc":"a linear document source",web:"a web page source"};function P(t,n,e){let r=j(t),s=r.heads.get(n);if(s==null)return null;let o=r.mediaOf(s).format;if(o===e)return null;let l=Re[o]??`${o} content`;return`source '${n}' is already backed by ${l}, not ${Re[e]??e} \u2014 retire it first (kane-cli context retire ${n}) or ingest under a different id with --as`}async function Rt(t,n,e,r,s){let o=Q(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Jira issue URL (https://<site>/browse/KEY-123)`),{code:1};let l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X};try{let i={auth:await(s?.authEnv??(await import("./auth-TYG473Z4.js")).resolveLisAuthEnv)(),env:process.env},c=await l.jiraInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issue comments yet \u2014 resync it at ${A} and retry`),{code:1};let a=o.issueKey.slice(0,o.issueKey.lastIndexOf("-"));if(!c.selectAll&&c.selectedProjects.length>0&&!c.selectedProjects.includes(a))return(e.err??e.out)(`error: ${t}: project ${a} is not in the integration's selected projects (${c.selectedProjects.join(", ")}) \u2014 add it at ${A}`),{code:1};let d=await l.jiraIssue(o.issueKey,i),p=await l.jiraComments(o.issueKey,i),y=o.site;if(d.host)try{y=new URL(d.host).hostname}catch{y=d.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:w,warnings:f}=ve(d,y,p),h=n??o.issueKey.toLowerCase();N(h);let _=P(r,h,"jira");if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let b=te(r,h);if(b!==null&&b!==y)return(e.err??e.out)(`error: ${t}: source '${h}' was ingested from ${b}, but this read serves ${y} \u2014 retire it first (kane-cli context retire ${h}) or ingest under a different id with --as`),{code:1};let g=await T({contextDir:r,bytes:w,media:he,sourceId:h,label:t,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{jira:$e({fetchAttachment:m=>l.jiraAttachment(m,i)})}});e.out(U(e.isTTY,g,o.issueKey));for(let m of f)e.out(`warning: ${m}`);for(let m of g.warnings??[])e.out(`warning: ${m}`);if(g.composite){let m=g.composite.delivered+g.composite.omitted;e.out(`${g.source_id}: jira, ${m} attachments, ${g.composite.delivered} images delivered (${g.composite.omitted} omitted)`)}return{code:0,result:{status:g.status,source_id:g.source_id,source_cid:g.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${kt(u instanceof Error?u.message:String(u))}`),{code:1})}}function kt(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the issue's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the description or attachments in Jira and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the issue's text is too large to ingest \u2014 trim the description in Jira and retry":t}var Oe={name:"jira",hint:"Jira issue URLs (https://<site>/browse/KEY-123)",match:t=>Q(t)!==null,ingest:Rt,sourceIdFor:t=>{let n=Q(t);return n?n.issueKey.toLowerCase():null}};async function Ne(t,n={}){let e=await $("/jira/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the page");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the page: ${k(r.message??"")||"page not found or not accessible"}`);return r.data}async function Te(t,n={}){let e=await $("/jira/attachment",{method:"POST",body:JSON.stringify({source:"confluence",download:t})},n);if(!e.ok)throw S(e,"the page's attachment");return{bytes:V(e).bytes}}var ne="kane.source.confluence/1";function Pe(t,n){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this page \u2014 the integrations service returned no page id");let e=[...t.labels??[]].filter(o=>typeof o=="string").sort(),r=[...t.attachments??[]].map(o=>({id:String(o.id),filename:o.filename??"",media_type:o.mime_type??"application/octet-stream",size:o.size??0})).sort((o,l)=>o.id<l.id?-1:o.id>l.id?1:0),s={schema:ne,site:n,page:{id:t.id},space:{key:t.space?.key??""},title:t.title??"",labels:e,content:{body:t.body??""},attachments:r};return{bytes:Buffer.from(JSON.stringify(s),"utf8"),envelope:s,warnings:[]}}var Ue=64,Ct=16,Ot=6e6,Nt=5e7,Tt=12e6,Pt={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},Ut=new Set(["png","jpeg","webp"]);function xe(t){let n=new Map(Object.entries(t.downloads));return async e=>{let r;try{r=JSON.parse(e.toString("utf8"))}catch{throw new Error("CONFLUENCE_ENVELOPE_SCHEMA: source bytes are not a kane confluence envelope")}if(r.schema!==ne)throw new Error(`CONFLUENCE_ENVELOPE_SCHEMA: unknown envelope schema "${r.schema}" \u2014 this CLI understands ${ne}`);let s=[],o=new Map,l=[],u=0,i=new Map,c=[];for(let d=0;d<r.attachments.length;d++){let p=r.attachments[d],y=`i${d+1}`,w=`attachment:${p.filename}`,f=R=>`[img#${y}] ${p.filename} (${p.media_type}, ${p.size} bytes${R?"":" \u2014 not delivered"})`,h=(R,x,D)=>{s.push({ref:y,loc:w,media_type:R,...D?.blob?{blob:D.blob}:{},...D?.appearance?{appearance:D.appearance}:{},delivery:x,...D?.duplicate_of?{duplicate_of:D.duplicate_of}:{}})};if(!p.media_type.startsWith("image/")){h(p.media_type,"unsupported-vision-media-type"),c.push(f(!1));continue}let _=n.get(p.id);if(!_){h(p.media_type,"external-image-not-fetched"),c.push(f(!1));continue}let b;try{b=await t.fetchAttachment({id:p.id,download:_})}catch{h(p.media_type,"external-image-not-fetched"),c.push(f(!1));continue}let g=b.bytes,m=J(g),I=Pt[m.format],L=B(g);if(o.set(L,g),!Ut.has(m.format)){let R=m.format==="gif"||m.format==="bmp"||m.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(I,R,{blob:L}),c.push(f(!1));continue}if(m.width===void 0||m.height===void 0||m.width*m.height>Nt){h(I,"undecodable",{blob:L}),c.push(f(!1));continue}let O;if(m.format==="png"||m.format==="jpeg"){let R=F(g,m.format);if(R===null){h(I,"undecodable",{blob:L}),c.push(f(!1));continue}O=M(R.data,{width:R.width,height:R.height,channels:R.channels})}if(m.width<Ue||m.height<Ue){h(I,"below-dimension-floor",{blob:L,appearance:O}),c.push(f(!1));continue}let v=i.get(L);if(v!==void 0){h(I,"duplicate",{blob:L,appearance:O,duplicate_of:v}),c.push(f(!1));continue}if(g.byteLength>Ot){h(I,"image-too-large",{blob:L,appearance:O}),c.push(f(!1));continue}if(u+g.byteLength>Tt){h(I,"vision-byte-budget-reached",{blob:L,appearance:O}),c.push(f(!1));continue}if(l.length>=Ct){h(I,"image-cap-reached",{blob:L,appearance:O}),c.push(f(!1));continue}i.set(L,y),u+=g.byteLength,l.push(y),h(I,"selected",{blob:L,appearance:O}),c.push(f(!0))}let a=[];return a.push(`${r.title} \xB7 ${r.site} \xB7 ${r.space.key}`),r.labels.length>0&&a.push(`labels: ${r.labels.join(", ")}`),r.content.body!==""&&a.push("",...r.content.body.split(`
7
+ `,inventory:r,blobs:s,delivered:o,converter:{name:"jira-convert",version:"2",policy:"v1"}}}}var $t=/^[A-Za-z][A-Za-z0-9_]*-\d+$/;function Q(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.lastIndexOf("browse");if(r===-1||r+1>=e.length)return null;let s=e[r+1];return $t.test(s)?{site:n.hostname,issueKey:s.toUpperCase()}:null}function ee(t,n){let e=j(t),r=e.heads.get(n);return r==null?null:Ce(t,e,r)}function te(t,n){let r=ee(t,n)?.site;return typeof r=="string"&&r.length>0?r:null}function ke(t,n,e,r){let s=j(t);for(let[o,l]of s.heads){if(l==null||s.mediaOf(l).format!==n)continue;let u=Ce(t,s,l);if(u===null)continue;let i=u;for(let c of e){if(i===null||typeof i!="object"){i=void 0;break}i=i[c]}if(i===r)return o}return null}function Ce(t,n,e){let r=n.getNode(e)?.content?.blob;if(typeof r!="string")return null;let s=W(t,r);if(s===null)return null;try{let o=JSON.parse(s.toString("utf8"));return o!==null&&typeof o=="object"?o:null}catch{return null}}var Re={jira:"a jira issue source",confluence:"a confluence page source",linear:"a linear issue source","linear-doc":"a linear document source",web:"a web page source"};function P(t,n,e){let r=j(t),s=r.heads.get(n);if(s==null)return null;let o=r.mediaOf(s).format;if(o===e)return null;let l=Re[o]??`${o} content`;return`source '${n}' is already backed by ${l}, not ${Re[e]??e} \u2014 retire it first (kane-cli context retire ${n}) or ingest under a different id with --as`}async function Rt(t,n,e,r,s){let o=Q(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Jira issue URL (https://<site>/browse/KEY-123)`),{code:1};let l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X};try{let i={auth:await(s?.authEnv??(await import("./auth-2HTDCT7X.js")).resolveLisAuthEnv)(),env:process.env},c=await l.jiraInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issue comments yet \u2014 resync it at ${A} and retry`),{code:1};let a=o.issueKey.slice(0,o.issueKey.lastIndexOf("-"));if(!c.selectAll&&c.selectedProjects.length>0&&!c.selectedProjects.includes(a))return(e.err??e.out)(`error: ${t}: project ${a} is not in the integration's selected projects (${c.selectedProjects.join(", ")}) \u2014 add it at ${A}`),{code:1};let d=await l.jiraIssue(o.issueKey,i),p=await l.jiraComments(o.issueKey,i),y=o.site;if(d.host)try{y=new URL(d.host).hostname}catch{y=d.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:w,warnings:f}=ve(d,y,p),h=n??o.issueKey.toLowerCase();N(h);let _=P(r,h,"jira");if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let b=te(r,h);if(b!==null&&b!==y)return(e.err??e.out)(`error: ${t}: source '${h}' was ingested from ${b}, but this read serves ${y} \u2014 retire it first (kane-cli context retire ${h}) or ingest under a different id with --as`),{code:1};let g=await T({contextDir:r,bytes:w,media:he,sourceId:h,label:t,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{jira:$e({fetchAttachment:m=>l.jiraAttachment(m,i)})}});e.out(U(e.isTTY,g,o.issueKey));for(let m of f)e.out(`warning: ${m}`);for(let m of g.warnings??[])e.out(`warning: ${m}`);if(g.composite){let m=g.composite.delivered+g.composite.omitted;e.out(`${g.source_id}: jira, ${m} attachments, ${g.composite.delivered} images delivered (${g.composite.omitted} omitted)`)}return{code:0,result:{status:g.status,source_id:g.source_id,source_cid:g.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${kt(u instanceof Error?u.message:String(u))}`),{code:1})}}function kt(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the issue's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the description or attachments in Jira and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the issue's text is too large to ingest \u2014 trim the description in Jira and retry":t}var Oe={name:"jira",hint:"Jira issue URLs (https://<site>/browse/KEY-123)",match:t=>Q(t)!==null,ingest:Rt,sourceIdFor:t=>{let n=Q(t);return n?n.issueKey.toLowerCase():null}};async function Ne(t,n={}){let e=await $("/jira/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the page");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the page: ${k(r.message??"")||"page not found or not accessible"}`);return r.data}async function Te(t,n={}){let e=await $("/jira/attachment",{method:"POST",body:JSON.stringify({source:"confluence",download:t})},n);if(!e.ok)throw S(e,"the page's attachment");return{bytes:V(e).bytes}}var ne="kane.source.confluence/1";function Pe(t,n){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this page \u2014 the integrations service returned no page id");let e=[...t.labels??[]].filter(o=>typeof o=="string").sort(),r=[...t.attachments??[]].map(o=>({id:String(o.id),filename:o.filename??"",media_type:o.mime_type??"application/octet-stream",size:o.size??0})).sort((o,l)=>o.id<l.id?-1:o.id>l.id?1:0),s={schema:ne,site:n,page:{id:t.id},space:{key:t.space?.key??""},title:t.title??"",labels:e,content:{body:t.body??""},attachments:r};return{bytes:Buffer.from(JSON.stringify(s),"utf8"),envelope:s,warnings:[]}}var Ue=64,Ct=16,Ot=6e6,Nt=5e7,Tt=12e6,Pt={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},Ut=new Set(["png","jpeg","webp"]);function xe(t){let n=new Map(Object.entries(t.downloads));return async e=>{let r;try{r=JSON.parse(e.toString("utf8"))}catch{throw new Error("CONFLUENCE_ENVELOPE_SCHEMA: source bytes are not a kane confluence envelope")}if(r.schema!==ne)throw new Error(`CONFLUENCE_ENVELOPE_SCHEMA: unknown envelope schema "${r.schema}" \u2014 this CLI understands ${ne}`);let s=[],o=new Map,l=[],u=0,i=new Map,c=[];for(let d=0;d<r.attachments.length;d++){let p=r.attachments[d],y=`i${d+1}`,w=`attachment:${p.filename}`,f=R=>`[img#${y}] ${p.filename} (${p.media_type}, ${p.size} bytes${R?"":" \u2014 not delivered"})`,h=(R,x,D)=>{s.push({ref:y,loc:w,media_type:R,...D?.blob?{blob:D.blob}:{},...D?.appearance?{appearance:D.appearance}:{},delivery:x,...D?.duplicate_of?{duplicate_of:D.duplicate_of}:{}})};if(!p.media_type.startsWith("image/")){h(p.media_type,"unsupported-vision-media-type"),c.push(f(!1));continue}let _=n.get(p.id);if(!_){h(p.media_type,"external-image-not-fetched"),c.push(f(!1));continue}let b;try{b=await t.fetchAttachment({id:p.id,download:_})}catch{h(p.media_type,"external-image-not-fetched"),c.push(f(!1));continue}let g=b.bytes,m=J(g),I=Pt[m.format],L=B(g);if(o.set(L,g),!Ut.has(m.format)){let R=m.format==="gif"||m.format==="bmp"||m.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(I,R,{blob:L}),c.push(f(!1));continue}if(m.width===void 0||m.height===void 0||m.width*m.height>Nt){h(I,"undecodable",{blob:L}),c.push(f(!1));continue}let O;if(m.format==="png"||m.format==="jpeg"){let R=F(g,m.format);if(R===null){h(I,"undecodable",{blob:L}),c.push(f(!1));continue}O=M(R.data,{width:R.width,height:R.height,channels:R.channels})}if(m.width<Ue||m.height<Ue){h(I,"below-dimension-floor",{blob:L,appearance:O}),c.push(f(!1));continue}let v=i.get(L);if(v!==void 0){h(I,"duplicate",{blob:L,appearance:O,duplicate_of:v}),c.push(f(!1));continue}if(g.byteLength>Ot){h(I,"image-too-large",{blob:L,appearance:O}),c.push(f(!1));continue}if(u+g.byteLength>Tt){h(I,"vision-byte-budget-reached",{blob:L,appearance:O}),c.push(f(!1));continue}if(l.length>=Ct){h(I,"image-cap-reached",{blob:L,appearance:O}),c.push(f(!1));continue}i.set(L,y),u+=g.byteLength,l.push(y),h(I,"selected",{blob:L,appearance:O}),c.push(f(!0))}let a=[];return a.push(`${r.title} \xB7 ${r.site} \xB7 ${r.space.key}`),r.labels.length>0&&a.push(`labels: ${r.labels.join(", ")}`),r.content.body!==""&&a.push("",...r.content.body.split(`
8
8
  `)),c.length>0&&a.push("","--- attachments ---",...c),{projection:a.join(`
9
9
  `)+`
10
- `,inventory:s,blobs:o,delivered:l,converter:{name:"confluence-convert",version:"1",policy:"v1"}}}}var xt=/^[A-Za-z0-9~][A-Za-z0-9._~-]*$/;function re(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.indexOf("wiki");if(r===-1||e[r+1]!=="spaces"||e[r+3]!=="pages")return null;let s=e[r+2],o=e[r+4];return s===void 0||o===void 0||!xt.test(s)||!/^\d+$/.test(o)?null:{site:n.hostname,spaceKey:s,pageId:o}}async function Dt(t,n,e,r,s){let o=re(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Confluence page URL (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)`),{code:1};let l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X},u=s?.confluence??{confluenceDocument:Ne,confluenceAttachment:Te};try{let c={auth:await(s?.authEnv??(await import("./auth-TYG473Z4.js")).resolveLisAuthEnv)(),env:process.env},a=await l.jiraInfo(c);if(!a.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} and retry`),{code:1};if(a.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection has no Confluence access \u2014 reconnect with Confluence at ${A} and retry`),{code:1};let d=await u.confluenceDocument(o.pageId,c),p=o.site;if(d.url)try{p=new URL(d.url).hostname}catch{}let{bytes:y,warnings:w}=Pe(d,p),f=n??`page-${o.pageId}`;N(f);let h=P(r,f,"confluence");if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=te(r,f);if(_!==null&&_!==p)return(e.err??e.out)(`error: ${t}: source '${f}' was ingested from ${_}, but this read serves ${p} \u2014 retire it first (kane-cli context retire ${f}) or ingest under a different id with --as`),{code:1};let b=Object.fromEntries((d.attachments??[]).filter(m=>typeof m.download=="string"&&m.download.length>0).map(m=>[String(m.id),m.download])),g=await T({contextDir:r,bytes:y,media:ye,sourceId:f,label:t,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{confluence:xe({downloads:b,fetchAttachment:m=>u.confluenceAttachment(m.download,c)})}});e.out(U(e.isTTY,g,`${o.spaceKey}/${o.pageId}`));for(let m of w)e.out(`warning: ${m}`);for(let m of g.warnings??[])e.out(`warning: ${m}`);if(g.composite){let m=g.composite.delivered+g.composite.omitted;e.out(`${g.source_id}: confluence, ${m} attachments, ${g.composite.delivered} images delivered (${g.composite.omitted} omitted)`)}return{code:0,result:{status:g.status,source_id:g.source_id,source_cid:g.cid}}}catch(i){return i instanceof E?((e.err??e.out)(`error: ${t}: ${i.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${jt(i instanceof Error?i.message:String(i))}`),{code:1})}}function jt(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the page in Confluence and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page's text is too large to ingest \u2014 trim the page in Confluence and retry":t}var De={name:"confluence",hint:"Confluence page URLs (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)",match:t=>re(t)!==null,ingest:Dt,sourceIdFor:t=>{let n=re(t);return n?`page-${n.pageId}`:null}};async function je(t={}){let n=await $("/linear-app/info",{method:"GET"},t);if(!n.ok)throw S(n,"the connection","Linear");let e=C(n);return{installed:e.data?.INSTALLED==="YES",capabilities:{issue:e.data?.capabilities?.issue===!0,comments:e.data?.capabilities?.comments===!0,document:e.data?.capabilities?.document===!0}}}async function Be(t,n={}){let e=await $("/linear-app/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"linear-app",issueKey:t})},n);if(!e.ok)throw S(e,"the issue","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${k(r.message??"")||"issue not found or not accessible"}`);return r.data}var Bt=100,Mt=5e3,Jt=60;async function Me(t,n={}){let e=[],r=new Set,s=null;for(let o=0;;o++){if(o>=Jt)throw new E("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let l=await $("/linear-app/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:Bt,...s===null?{}:{cursor:s},fetch_all:!1})},n);if(!l.ok)throw S(l,"the issue's comments","Linear");let u=C(l);if(u.type==="error"||!u.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${k(u.message??"")||"unavailable"}`);if(u.data.partial)throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 retry later");for(let a of u.data.comments??[]){if(typeof a.id!="string"||a.id==="")throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 a comment row has no comment id");r.has(a.id)||(r.add(a.id),e.push(a))}let i=u.data.pagination;if(!i?.has_more)return e;if(e.length>=Mt)throw new E("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let c=i.next_cursor??null;if(c==null||c===s)throw new E("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");s=c}}async function Je(t,n={}){let e=await $("/linear-app/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the document","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the document: ${k(r.message??"")||"document not found or not accessible"}`);return r.data}async function Fe(t,n={}){let e=await $("/linear-app/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok)throw S(e,"the attachment","Linear");return{bytes:V(e).bytes}}var oe="kane.source.linear/1",ie="kane.source.linear-doc/1",Ft=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g;function G(t){return t.replace(Ft,n=>{let e=n.indexOf("?");return e===-1?n:n.slice(0,e)})}function Ve(t,n){return t.id<n.id?-1:t.id>n.id?1:0}function Vt(t,n){return Ve(t,n)||(t.filename<n.filename?-1:t.filename>n.filename?1:0)||(t.url<n.url?-1:t.url>n.url?1:0)}function Ge(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this issue \u2014 the integrations service returned no issue id");let r=t.key;if(!/^[A-Za-z][A-Za-z0-9]*-\d+$/.test(r)){let c=String(r).replace(/[\u0000-\u001f\u007f-\u009f]/g,"").slice(0,80);throw new Error(`cannot build a stable identity for issue key "${c}" \u2014 expected a TEAM-NUMBER key`)}let s={},o=[...t.labels??[]].filter(c=>typeof c=="string").sort();o.length>0&&(s.labels=o.join(", ")),typeof t.priority=="string"&&t.priority!==""&&(s.priority=t.priority),typeof t.project=="string"&&t.project!==""&&(s.project=t.project),typeof t.status=="string"&&t.status!==""&&(s.status=t.status);let l=(t.attachments??[]).map(c=>({id:c.id!=null&&String(c.id)!==""?String(c.id):G(c.download??""),filename:c.filename??"",url:G(c.download??"")})).sort(Vt),u=n.map(c=>({id:String(c.id),author:c.author?.display_name??"",body:G(c.body??""),created:c.created??""})).sort((c,a)=>c.created!==a.created?c.created<a.created?-1:1:Ve(c,a)),i={schema:oe,site:e,team:r.slice(0,r.lastIndexOf("-")),issue:{uuid:t.id,key:r},content:{title:t.summary??"",description:G(t.description??""),fields:s},attachments:l,comments:u};return{bytes:Buffer.from(JSON.stringify(i),"utf8"),envelope:i,warnings:[]}}function Ye(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this document \u2014 the integrations service returned no document id");let r=(t.attachments??[]).map(o=>({url:G(o.download??String(o.id??"")),filename:o.filename??""})).sort((o,l)=>o.url<l.url?-1:o.url>l.url?1:0),s={schema:ie,site:n,document:{uuid:t.id,slug_id:e},project:{id:t.space?.key??""},title:t.title??"",content:{body:G(t.body??"")},attachments:r};return{bytes:Buffer.from(JSON.stringify(s),"utf8"),envelope:s,warnings:[]}}var Ke=64,Gt=16,Yt=6e6,Kt=5e7,Wt=12e6,se=64,We="https://uploads.linear.app/",Ht=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g,zt={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},Xt=new Set(["png","jpeg","webp"]);async function He(t,n){let e=[],r=new Map,s=[],o=0,l=new Map,u=[];for(let i=0;i<t.length;i++){let c=t[i],a=`i${i+1}`,d=m=>`[img#${a}] ${c.label}${m?"":" \u2014 not delivered"}`,p=(m,I,L)=>{e.push({ref:a,loc:c.loc,media_type:m,...L?.blob?{blob:L.blob}:{},...L?.appearance?{appearance:L.appearance}:{},delivery:I,...L?.duplicate_of?{duplicate_of:L.duplicate_of}:{}})},y;try{y=await n(c.url)}catch{p("application/octet-stream","external-image-not-fetched"),u.push(d(!1));continue}let w=y.bytes,f=J(w),h=zt[f.format],_=B(w);if(r.set(_,w),!Xt.has(f.format)){let m=f.format==="gif"||f.format==="bmp"||f.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";p(h,m,{blob:_}),u.push(d(!1));continue}if(f.width===void 0||f.height===void 0||f.width*f.height>Kt){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}let b;if(f.format==="png"||f.format==="jpeg"){let m=F(w,f.format);if(m===null){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}b=M(m.data,{width:m.width,height:m.height,channels:m.channels})}if(f.width<Ke||f.height<Ke){p(h,"below-dimension-floor",{blob:_,appearance:b}),u.push(d(!1));continue}let g=l.get(_);if(g!==void 0){p(h,"duplicate",{blob:_,appearance:b,duplicate_of:g}),u.push(d(!1));continue}if(w.byteLength>Yt){p(h,"image-too-large",{blob:_,appearance:b}),u.push(d(!1));continue}if(o+w.byteLength>Wt){p(h,"vision-byte-budget-reached",{blob:_,appearance:b}),u.push(d(!1));continue}if(s.length>=Gt){p(h,"image-cap-reached",{blob:_,appearance:b}),u.push(d(!1));continue}l.set(_,a),o+=w.byteLength,s.push(a),p(h,"selected",{blob:_,appearance:b}),u.push(d(!0))}return{inventory:e,blobs:r,delivered:s,lines:u}}function Zt(t){let n=new Set,e=[];for(let r of t.match(Ht)??[])n.has(r)||(n.add(r),e.push(r));return e}function ze(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("LINEAR_ENVELOPE_SCHEMA: source bytes are not a kane linear envelope")}if(e.schema!==oe)throw new Error(`LINEAR_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${oe}`);let r=[],s=new Set;for(let a of Zt(e.content.description))s.add(a),r.push({url:a,label:a,loc:`body:${a}`});let o=[];for(let a of e.attachments)if(a.url.startsWith(We)){if(s.has(a.url)){if(a.filename!==""){let d=r.find(p=>p.url===a.url);d!==void 0&&d.label===d.url&&(d.label=a.filename)}continue}s.add(a.url),r.push({url:a.url,label:a.filename||a.url,loc:`attachment:${a.filename||a.url}`})}else a.url!==""&&o.push(`[${o.length+1}] ${a.filename||a.url} \u2014 ${a.url}`);let l=Math.max(0,r.length-se),u=await He(r.slice(0,se),t.fetchAttachment);l>0&&u.lines.push(`${l} more upload links not examined`);let i=[];i.push(`${e.issue.key} \xB7 ${e.site}`,`Title: ${e.content.title}`),e.content.description!==""&&i.push("",...e.content.description.split(`
10
+ `,inventory:s,blobs:o,delivered:l,converter:{name:"confluence-convert",version:"1",policy:"v1"}}}}var xt=/^[A-Za-z0-9~][A-Za-z0-9._~-]*$/;function re(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.indexOf("wiki");if(r===-1||e[r+1]!=="spaces"||e[r+3]!=="pages")return null;let s=e[r+2],o=e[r+4];return s===void 0||o===void 0||!xt.test(s)||!/^\d+$/.test(o)?null:{site:n.hostname,spaceKey:s,pageId:o}}async function Dt(t,n,e,r,s){let o=re(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Confluence page URL (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)`),{code:1};let l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X},u=s?.confluence??{confluenceDocument:Ne,confluenceAttachment:Te};try{let c={auth:await(s?.authEnv??(await import("./auth-2HTDCT7X.js")).resolveLisAuthEnv)(),env:process.env},a=await l.jiraInfo(c);if(!a.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} and retry`),{code:1};if(a.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection has no Confluence access \u2014 reconnect with Confluence at ${A} and retry`),{code:1};let d=await u.confluenceDocument(o.pageId,c),p=o.site;if(d.url)try{p=new URL(d.url).hostname}catch{}let{bytes:y,warnings:w}=Pe(d,p),f=n??`page-${o.pageId}`;N(f);let h=P(r,f,"confluence");if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=te(r,f);if(_!==null&&_!==p)return(e.err??e.out)(`error: ${t}: source '${f}' was ingested from ${_}, but this read serves ${p} \u2014 retire it first (kane-cli context retire ${f}) or ingest under a different id with --as`),{code:1};let b=Object.fromEntries((d.attachments??[]).filter(m=>typeof m.download=="string"&&m.download.length>0).map(m=>[String(m.id),m.download])),g=await T({contextDir:r,bytes:y,media:ye,sourceId:f,label:t,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{confluence:xe({downloads:b,fetchAttachment:m=>u.confluenceAttachment(m.download,c)})}});e.out(U(e.isTTY,g,`${o.spaceKey}/${o.pageId}`));for(let m of w)e.out(`warning: ${m}`);for(let m of g.warnings??[])e.out(`warning: ${m}`);if(g.composite){let m=g.composite.delivered+g.composite.omitted;e.out(`${g.source_id}: confluence, ${m} attachments, ${g.composite.delivered} images delivered (${g.composite.omitted} omitted)`)}return{code:0,result:{status:g.status,source_id:g.source_id,source_cid:g.cid}}}catch(i){return i instanceof E?((e.err??e.out)(`error: ${t}: ${i.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${jt(i instanceof Error?i.message:String(i))}`),{code:1})}}function jt(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the page in Confluence and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page's text is too large to ingest \u2014 trim the page in Confluence and retry":t}var De={name:"confluence",hint:"Confluence page URLs (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)",match:t=>re(t)!==null,ingest:Dt,sourceIdFor:t=>{let n=re(t);return n?`page-${n.pageId}`:null}};async function je(t={}){let n=await $("/linear-app/info",{method:"GET"},t);if(!n.ok)throw S(n,"the connection","Linear");let e=C(n);return{installed:e.data?.INSTALLED==="YES",capabilities:{issue:e.data?.capabilities?.issue===!0,comments:e.data?.capabilities?.comments===!0,document:e.data?.capabilities?.document===!0}}}async function Be(t,n={}){let e=await $("/linear-app/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"linear-app",issueKey:t})},n);if(!e.ok)throw S(e,"the issue","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${k(r.message??"")||"issue not found or not accessible"}`);return r.data}var Bt=100,Mt=5e3,Jt=60;async function Me(t,n={}){let e=[],r=new Set,s=null;for(let o=0;;o++){if(o>=Jt)throw new E("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let l=await $("/linear-app/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:Bt,...s===null?{}:{cursor:s},fetch_all:!1})},n);if(!l.ok)throw S(l,"the issue's comments","Linear");let u=C(l);if(u.type==="error"||!u.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${k(u.message??"")||"unavailable"}`);if(u.data.partial)throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 retry later");for(let a of u.data.comments??[]){if(typeof a.id!="string"||a.id==="")throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 a comment row has no comment id");r.has(a.id)||(r.add(a.id),e.push(a))}let i=u.data.pagination;if(!i?.has_more)return e;if(e.length>=Mt)throw new E("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let c=i.next_cursor??null;if(c==null||c===s)throw new E("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");s=c}}async function Je(t,n={}){let e=await $("/linear-app/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the document","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the document: ${k(r.message??"")||"document not found or not accessible"}`);return r.data}async function Fe(t,n={}){let e=await $("/linear-app/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok)throw S(e,"the attachment","Linear");return{bytes:V(e).bytes}}var oe="kane.source.linear/1",ie="kane.source.linear-doc/1",Ft=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g;function G(t){return t.replace(Ft,n=>{let e=n.indexOf("?");return e===-1?n:n.slice(0,e)})}function Ve(t,n){return t.id<n.id?-1:t.id>n.id?1:0}function Vt(t,n){return Ve(t,n)||(t.filename<n.filename?-1:t.filename>n.filename?1:0)||(t.url<n.url?-1:t.url>n.url?1:0)}function Ge(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this issue \u2014 the integrations service returned no issue id");let r=t.key;if(!/^[A-Za-z][A-Za-z0-9]*-\d+$/.test(r)){let c=String(r).replace(/[\u0000-\u001f\u007f-\u009f]/g,"").slice(0,80);throw new Error(`cannot build a stable identity for issue key "${c}" \u2014 expected a TEAM-NUMBER key`)}let s={},o=[...t.labels??[]].filter(c=>typeof c=="string").sort();o.length>0&&(s.labels=o.join(", ")),typeof t.priority=="string"&&t.priority!==""&&(s.priority=t.priority),typeof t.project=="string"&&t.project!==""&&(s.project=t.project),typeof t.status=="string"&&t.status!==""&&(s.status=t.status);let l=(t.attachments??[]).map(c=>({id:c.id!=null&&String(c.id)!==""?String(c.id):G(c.download??""),filename:c.filename??"",url:G(c.download??"")})).sort(Vt),u=n.map(c=>({id:String(c.id),author:c.author?.display_name??"",body:G(c.body??""),created:c.created??""})).sort((c,a)=>c.created!==a.created?c.created<a.created?-1:1:Ve(c,a)),i={schema:oe,site:e,team:r.slice(0,r.lastIndexOf("-")),issue:{uuid:t.id,key:r},content:{title:t.summary??"",description:G(t.description??""),fields:s},attachments:l,comments:u};return{bytes:Buffer.from(JSON.stringify(i),"utf8"),envelope:i,warnings:[]}}function Ye(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this document \u2014 the integrations service returned no document id");let r=(t.attachments??[]).map(o=>({url:G(o.download??String(o.id??"")),filename:o.filename??""})).sort((o,l)=>o.url<l.url?-1:o.url>l.url?1:0),s={schema:ie,site:n,document:{uuid:t.id,slug_id:e},project:{id:t.space?.key??""},title:t.title??"",content:{body:G(t.body??"")},attachments:r};return{bytes:Buffer.from(JSON.stringify(s),"utf8"),envelope:s,warnings:[]}}var Ke=64,Gt=16,Yt=6e6,Kt=5e7,Wt=12e6,se=64,We="https://uploads.linear.app/",Ht=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g,zt={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},Xt=new Set(["png","jpeg","webp"]);async function He(t,n){let e=[],r=new Map,s=[],o=0,l=new Map,u=[];for(let i=0;i<t.length;i++){let c=t[i],a=`i${i+1}`,d=m=>`[img#${a}] ${c.label}${m?"":" \u2014 not delivered"}`,p=(m,I,L)=>{e.push({ref:a,loc:c.loc,media_type:m,...L?.blob?{blob:L.blob}:{},...L?.appearance?{appearance:L.appearance}:{},delivery:I,...L?.duplicate_of?{duplicate_of:L.duplicate_of}:{}})},y;try{y=await n(c.url)}catch{p("application/octet-stream","external-image-not-fetched"),u.push(d(!1));continue}let w=y.bytes,f=J(w),h=zt[f.format],_=B(w);if(r.set(_,w),!Xt.has(f.format)){let m=f.format==="gif"||f.format==="bmp"||f.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";p(h,m,{blob:_}),u.push(d(!1));continue}if(f.width===void 0||f.height===void 0||f.width*f.height>Kt){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}let b;if(f.format==="png"||f.format==="jpeg"){let m=F(w,f.format);if(m===null){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}b=M(m.data,{width:m.width,height:m.height,channels:m.channels})}if(f.width<Ke||f.height<Ke){p(h,"below-dimension-floor",{blob:_,appearance:b}),u.push(d(!1));continue}let g=l.get(_);if(g!==void 0){p(h,"duplicate",{blob:_,appearance:b,duplicate_of:g}),u.push(d(!1));continue}if(w.byteLength>Yt){p(h,"image-too-large",{blob:_,appearance:b}),u.push(d(!1));continue}if(o+w.byteLength>Wt){p(h,"vision-byte-budget-reached",{blob:_,appearance:b}),u.push(d(!1));continue}if(s.length>=Gt){p(h,"image-cap-reached",{blob:_,appearance:b}),u.push(d(!1));continue}l.set(_,a),o+=w.byteLength,s.push(a),p(h,"selected",{blob:_,appearance:b}),u.push(d(!0))}return{inventory:e,blobs:r,delivered:s,lines:u}}function Zt(t){let n=new Set,e=[];for(let r of t.match(Ht)??[])n.has(r)||(n.add(r),e.push(r));return e}function ze(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("LINEAR_ENVELOPE_SCHEMA: source bytes are not a kane linear envelope")}if(e.schema!==oe)throw new Error(`LINEAR_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${oe}`);let r=[],s=new Set;for(let a of Zt(e.content.description))s.add(a),r.push({url:a,label:a,loc:`body:${a}`});let o=[];for(let a of e.attachments)if(a.url.startsWith(We)){if(s.has(a.url)){if(a.filename!==""){let d=r.find(p=>p.url===a.url);d!==void 0&&d.label===d.url&&(d.label=a.filename)}continue}s.add(a.url),r.push({url:a.url,label:a.filename||a.url,loc:`attachment:${a.filename||a.url}`})}else a.url!==""&&o.push(`[${o.length+1}] ${a.filename||a.url} \u2014 ${a.url}`);let l=Math.max(0,r.length-se),u=await He(r.slice(0,se),t.fetchAttachment);l>0&&u.lines.push(`${l} more upload links not examined`);let i=[];i.push(`${e.issue.key} \xB7 ${e.site}`,`Title: ${e.content.title}`),e.content.description!==""&&i.push("",...e.content.description.split(`
11
11
  `));let c=Object.keys(e.content.fields);return c.length>0&&i.push("","--- fields ---",...c.map(a=>`${a}: ${e.content.fields[a]}`)),u.lines.length>0&&i.push("","--- images ---",...u.lines),o.length>0&&i.push("","--- links ---",...o),e.comments.length>0&&(i.push("","--- comments ---"),e.comments.forEach((a,d)=>{d>0&&i.push(""),i.push(`[${d+1}] ${a.author} \xB7 ${a.created}`,...a.body.split(`
12
12
  `))})),{projection:i.join(`
13
13
  `)+`
14
14
  `,inventory:u.inventory,blobs:u.blobs,delivered:u.delivered,converter:{name:"linear-convert",version:"1",policy:"v1"}}}}function Xe(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("LINEAR_DOC_ENVELOPE_SCHEMA: source bytes are not a kane linear document envelope")}if(e.schema!==ie)throw new Error(`LINEAR_DOC_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${ie}`);let r=new Set,s=[];for(let i of e.attachments)!i.url.startsWith(We)||r.has(i.url)||(r.add(i.url),s.push({url:i.url,label:i.filename||i.url,loc:`body:${i.url}`}));let o=Math.max(0,s.length-se),l=await He(s.slice(0,se),t.fetchAttachment);o>0&&l.lines.push(`${o} more upload links not examined`);let u=[];return u.push(`${e.title} \xB7 ${e.site}`),e.content.body!==""&&u.push("",...e.content.body.split(`
15
15
  `)),l.lines.length>0&&u.push("","--- images ---",...l.lines),{projection:u.join(`
16
16
  `)+`
17
- `,inventory:l.inventory,blobs:l.blobs,delivered:l.delivered,converter:{name:"linear-doc-convert",version:"1",policy:"v1"}}}}var qt=/^[A-Za-z][A-Za-z0-9]*-\d+$/,Qt=/-([0-9a-f]{12})$/;function ue(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname.toLowerCase()!=="linear.app"?null:n.pathname.split("/").filter(Boolean)}function Ze(t){let n=ue(t);return n===null||n.length<3?null:{workspace:n[0],segs:n}}function Y(t){let n=Ze(t);if(n===null||n.segs[1]!=="issue")return null;let e=n.segs[2];return qt.test(e)?{workspace:n.workspace,key:e}:null}function K(t){let n=Ze(t);if(n===null||n.segs[1]!=="document")return null;let e=n.segs[2].match(Qt);return e===null?null:{workspace:n.workspace,slugId:e[1]}}var en=new Set(["project","team","view","initiative","cycle","roadmap","inbox","triage","my-issues"]),qe=new Set(["docs","features","method","blog","customers","pricing","integrations","developers","changelog","about","careers","security","download","contact","now","switch","homepage"]);function le(t){let n=ue(t);return n===null||n.length<2||!en.has(n[1])||qe.has(n[0].toLowerCase())?null:{workspace:n[0],section:n[1]}}function de(t){let n=ue(t);return n===null||n.length<2||n[1]!=="issue"&&n[1]!=="document"||qe.has(n[0].toLowerCase())||Y(t)!==null||K(t)!==null?null:{workspace:n[0],section:n[1]}}function Qe(t){let n=Y(t);return n?n.key.toLowerCase():null}function et(t){let n=K(t);return n?`doc-${n.slugId}`:null}var tt={linearInfo:je,linearIssue:Be,linearComments:Me,linearDocument:Je,linearAttachment:Fe};function nt(t,n){if(t)try{let e=new URL(t).pathname.split("/").filter(Boolean)[0];if(e)return`linear.app/${e.toLowerCase()}`}catch{}return`linear.app/${n.toLowerCase()}`}function rt(t,n,e,r,s,o){let l=ee(t,r);if(l!==null&&typeof l.schema=="string"&&l.schema.startsWith(`kane.source.${n}/`)){let i=l;for(let c of e)i=i!==null&&typeof i=="object"?i[c]:void 0;if(typeof i=="string"&&i!==""&&i!==s)return`source '${r}' was ingested from a different ${o} that used this key \u2014 the key was recycled; retire it first (kane-cli context retire ${r}) or ingest under a different id with --as`}let u=ke(t,n,e,s);return u!==null&&u!==r?`this ${o} is already ingested as '${u}' (its key changed) \u2014 reconcile that source, or retire it to re-ingest under the new key`:null}function ot(t,n,e,r){let s=ee(t,e);if(s===null||typeof s.schema!="string"||!s.schema.startsWith(`kane.source.${n}/`))return null;let o=s.site;return typeof o!="string"||o.length===0||o===r?null:`source '${e}' was ingested from ${o}, but this read serves ${r} \u2014 retire it first (kane-cli context retire ${e}) or ingest under a different id with --as`}async function tn(t,n,e,r,s){let o=Y(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear issue URL (https://linear.app/<workspace>/issue/KEY-123)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-TYG473Z4.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.issue===!1||c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issues or their comments yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearIssue(o.key,i),d=await l.linearComments(o.key,i),p=nt(a.host,o.workspace),{bytes:y,envelope:w,warnings:f}=Ge(a,d,p),h=n??o.key.toLowerCase();N(h);let _=rt(r,"linear",["issue","uuid"],h,w.issue.uuid,"issue")??P(r,h,"linear")??ot(r,"linear",h,p);if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let b=await T({contextDir:r,bytes:y,media:Ee,sourceId:h,label:t,confirmSameSource:e.isTTY?g=>e.confirm(`identical content already ingested as ${g} \u2014 treat as the same source?`):void 0,converters:{linear:ze({fetchAttachment:g=>l.linearAttachment(g,i)})}});e.out(U(e.isTTY,b,w.issue.key));for(let g of f)e.out(`warning: ${g}`);for(let g of b.warnings??[])e.out(`warning: ${g}`);if(b.composite){let g=b.composite.delivered+b.composite.omitted;e.out(`${b.source_id}: linear, ${g} images, ${b.composite.delivered} delivered (${b.composite.omitted} omitted)`)}return{code:0,result:{status:b.status,source_id:b.source_id,source_cid:b.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"issue","Linear")}`),{code:1})}}async function nn(t,n,e,r,s){let o=K(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear document URL (https://linear.app/<workspace>/document/<slug>)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-TYG473Z4.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read documents yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearDocument(o.slugId,i),d=nt(a.url,o.workspace),{bytes:p,envelope:y,warnings:w}=Ye(a,d,o.slugId),f=n??`doc-${o.slugId}`;N(f);let h=rt(r,"linear-doc",["document","uuid"],f,y.document.uuid,"document")??P(r,f,"linear-doc")??ot(r,"linear-doc",f,d);if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=await T({contextDir:r,bytes:p,media:_e,sourceId:f,label:t,confirmSameSource:e.isTTY?b=>e.confirm(`identical content already ingested as ${b} \u2014 treat as the same source?`):void 0,converters:{linearDoc:Xe({fetchAttachment:b=>l.linearAttachment(b,i)})}});e.out(U(e.isTTY,_,y.title||`document ${o.slugId}`));for(let b of w)e.out(`warning: ${b}`);for(let b of _.warnings??[])e.out(`warning: ${b}`);if(_.composite){let b=_.composite.delivered+_.composite.omitted;e.out(`${_.source_id}: linear document, ${b} images, ${_.composite.delivered} delivered (${_.composite.omitted} omitted)`)}return{code:0,result:{status:_.status,source_id:_.source_id,source_cid:_.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"document","Linear")}`),{code:1})}}function it(t,n,e){let r=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return r?`the ${n}'s content is too large to ingest (${r[1]}; the limit is ${r[2]}) \u2014 trim the ${n} in ${e} and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?`the ${n}'s text is too large to ingest \u2014 trim the ${n} in ${e} and retry`:t}var st={name:"linear",hint:"Linear issue URLs (https://linear.app/<workspace>/issue/KEY-123)",match:t=>Y(t)!==null,ingest:tn,sourceIdFor:Qe},at={name:"linear-doc",hint:"Linear document URLs (https://linear.app/<workspace>/document/<slug>)",match:t=>K(t)!==null,ingest:nn,sourceIdFor:et},ct={name:"linear-page",hint:"Linear issue or document URLs (other linear.app pages are not ingestable)",match:t=>le(t)!==null||de(t)!==null,ingest:async(t,n,e)=>{let r=le(t);if(r===null){let s=de(t);return s!==null?((e.err??e.out)(`error: ${t}: this Linear ${s.section} link is incomplete or malformed \u2014 use the full form (https://linear.app/${s.workspace}/issue/KEY-123 or https://linear.app/${s.workspace}/document/<slug>-<id>)`),{code:1}):((e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear workspace page`),{code:1})}return(e.err??e.out)(`error: ${t}: this Linear page can't be ingested \u2014 only issue and document URLs are supported; ingest the project's issues or documents individually (https://linear.app/${r.workspace}/issue/KEY-123)`),{code:1}},sourceIdFor:()=>null};var rn=new Set(["invalid_url","target_disallowed","page_not_found","page_access_blocked","page_paywalled","unsupported_content_type","page_too_large","page_timeout","scrape_unavailable","scrape_rate_limited","internal_error","credit_denied"]);async function ut(t,n){let e=n.env??process.env,r=n.fetchImpl??fetch,s=we(e),o={"Content-Type":"application/json"},l=await n.authEnv(),u=l.TESTMUAI_BASIC_AUTH??e.TESTMUAI_BASIC_AUTH,i=l.TESTMUAI_API_KEY??e.TESTMUAI_API_KEY;u?o.Authorization=`Basic ${u}`:i&&(o.Authorization=`Bearer ${i}`);let c;try{c=await r(`${s}/assurance/web/scrape`,{method:"POST",headers:o,body:JSON.stringify({url:t}),signal:AbortSignal.timeout(n.timeoutMs??55e3)})}catch{return{ok:!1,kind:"transport_unreachable"}}if(c.status===401)return{ok:!1,kind:"auth_rejected"};let a;try{a=await c.json()}catch{return{ok:!1,kind:c.status===404?"route_missing":"malformed_response"}}if(c.ok){let p=a.page;return p===void 0||typeof p.markdown!="string"||p.markdown===""||typeof p.final_url!="string"||p.final_url===""||typeof p.projection?.kind!="string"||typeof p.projection?.version!="string"?{ok:!1,kind:"malformed_response"}:{ok:!0,page:p}}let d=a.code;return typeof d=="string"&&rn.has(d)?{ok:!1,kind:d}:c.status===404?{ok:!1,kind:"route_missing"}:c.status===403?{ok:!1,kind:"auth_rejected"}:{ok:!1,kind:"malformed_response"}}var pe="kane.source.web/1";function lt(t,n,e){if(e==="")throw new Error("cannot build a web source from an empty page projection");if(n.kind===""||n.version==="")throw new Error("cannot build a stable identity without a server-reported projection kind/version");let r={schema:pe,url:t,projection:{kind:n.kind,version:n.version},content:{markdown:e}};return{bytes:Buffer.from(JSON.stringify(r),"utf8"),envelope:r}}var on=new Set(["markdown"]);function dt(){return async t=>{let n;try{n=JSON.parse(t.toString("utf8"))}catch{throw new Error("this web source's stored envelope is not readable \u2014 re-ingest the page")}if(n.schema!==pe)throw new Error(`unknown web envelope schema '${String(n.schema)}' \u2014 re-ingest the page with this CLI version`);if(!on.has(n.projection?.kind??""))throw new Error(`unknown web projection kind '${String(n.projection?.kind)}' \u2014 update kane-cli to read this source`);if(typeof n.content?.markdown!="string"||n.content.markdown==="")throw new Error("this web source's stored envelope carries no content \u2014 re-ingest the page");return{projection:n.content.markdown,inventory:[],blobs:new Map,delivered:[],converter:{name:"web-convert",version:"1",policy:"markdown-passthrough"}}}}import{createHash as sn}from"crypto";function pt(t){return ae(t)!==null}function ae(t){if(!/^https?:\/\//i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname===""?null:(n.hash="",n.username="",n.password="",n.toString())}function me(t){let n=ae(t);if(n===null)return null;let e=new URL(n),r=(e.hostname+e.pathname).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,""),s=sn("sha256").update(n,"utf8").digest("hex").slice(0,8);return`${r||"page"}-${s}`}function an(t,n){let e=j(t),r=e.heads.get(n);if(r==null)return null;let s=e.getNode(r)?.content?.blob;if(typeof s!="string")return null;let o=W(t,s);if(o===null)return null;try{let l=JSON.parse(o.toString("utf8"));return l.schema!=="kane.source.web/1"?null:typeof l.url=="string"&&l.url.length>0?l.url:null}catch{return null}}function fe(t){switch(t){case"invalid_url":return"this is not a valid public HTTP or HTTPS page URL \u2014 check the address and try again";case"target_disallowed":return"that address cannot be fetched because it does not point to an allowed public web page";case"page_not_found":return"the page could not be found \u2014 check that the URL is correct and that the page still exists";case"page_access_blocked":return"the page refused automated access, so its contents could not be ingested \u2014 use a publicly accessible version of the page";case"page_paywalled":return"the page is behind a paywall or sign-in screen, so its full contents could not be ingested \u2014 use a publicly accessible copy";case"unsupported_content_type":return"the URL does not point to an HTML web page \u2014 download the document and ingest the supported file instead";case"page_too_large":return"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first";case"page_timeout":return"the page took too long to load \u2014 try again later";case"scrape_unavailable":case"scrape_rate_limited":case"internal_error":return"the page ingest service is temporarily unavailable \u2014 try again later";case"credit_denied":return"the page could not be ingested \u2014 your organization is out of credits";case"auth_rejected":return"your credentials were rejected \u2014 run `kane-cli login` and retry";case"route_missing":return"ingesting web pages is not available in your environment yet \u2014 nothing is wrong with the URL; try again later";case"transport_unreachable":return"the page ingest service could not be reached \u2014 check your connection and try again";case"malformed_response":return"the page ingest service returned a response that could not be read safely \u2014 try again later"}}function cn(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page contains too much text to ingest as a single source (${n[1]}; the limit is ${n[2]}) \u2014 use a narrower page or trim the content first`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first":t}async function un(t,n,e,r,s){let o=ae(t);if(o===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};let l=me(t),u=n??l;if(u===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};try{N(u)}catch(y){return(e.err??e.out)(`error: ${t}: ${y instanceof Error?y.message:String(y)}`),{code:1}}let i=P(r,u,"web");if(i!==null)return(e.err??e.out)(`error: ${t}: ${i}`),{code:1};let c=an(r,u);if(c!==null&&c!==o){if(!e.isTTY)return(e.err??e.out)(`error: ${t}: source '${u}' was ingested from ${c} \u2014 re-run on a TTY to adopt the new URL as its next version, or ingest under a different id with --as`),{code:1};if(!await e.confirm(`source '${u}' was ingested from ${c} \u2014 treat ${o} as its new version (replaces the current version; items built on it go stale)?`))return e.out(`skipped ${t} \u2014 ingest under a different id with --as to keep both pages`),{code:1}}let a=s?.web?.scrape??ut,d=s?.authEnv??(async()=>(await import("./spawner-R76ROCR2.js")).resolveAgentAuthEnv()),p=await a(o,{authEnv:d});if(!p.ok)return(e.err??e.out)(`error: ${t}: ${fe(p.kind)}`),{code:1};try{let{bytes:y}=lt(o,p.page.projection,p.page.markdown),w=await T({contextDir:r,bytes:y,media:be,sourceId:u,label:o,confirmSameSource:e.isTTY?h=>e.confirm(`identical content already ingested as ${h} \u2014 treat as the same source?`):void 0,converters:{web:dt()}}),f=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,w,f));for(let h of w.warnings??[])e.out(`warning: ${h}`);return e.isTTY&&p.page.title&&e.out(` title: ${p.page.title}`),{code:0,result:{status:w.status,source_id:w.source_id,source_cid:w.cid}}}catch(y){return(e.err??e.out)(`error: ${t}: ${cn(y instanceof Error?y.message:String(y))}`),{code:1}}}var mt={name:"web",hint:"any public web page URL (https://\u2026)",match:pt,ingest:un,sourceIdFor:me};function U(t,n,e){return t?n.status==="created"?`landed ${n.source_id} (${e}) \u2014 new source`:n.status==="versioned"?`landed ${n.source_id} (${e}) \u2014 new version; dependents go stale`:`${n.source_id} unchanged \u2014 already landed`:`${n.status} ${n.source_id} source ${n.cid} blob ${n.blob}`}var ln=[Oe,De,st,at,ct,mt];function Kr(t){return/^https?:\/\/.+/i.test(t)}function Wr(t){return ln.find(n=>n.match(t))??null}export{U as a,ln as b,Kr as c,Wr as d};
17
+ `,inventory:l.inventory,blobs:l.blobs,delivered:l.delivered,converter:{name:"linear-doc-convert",version:"1",policy:"v1"}}}}var qt=/^[A-Za-z][A-Za-z0-9]*-\d+$/,Qt=/-([0-9a-f]{12})$/;function ue(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname.toLowerCase()!=="linear.app"?null:n.pathname.split("/").filter(Boolean)}function Ze(t){let n=ue(t);return n===null||n.length<3?null:{workspace:n[0],segs:n}}function Y(t){let n=Ze(t);if(n===null||n.segs[1]!=="issue")return null;let e=n.segs[2];return qt.test(e)?{workspace:n.workspace,key:e}:null}function K(t){let n=Ze(t);if(n===null||n.segs[1]!=="document")return null;let e=n.segs[2].match(Qt);return e===null?null:{workspace:n.workspace,slugId:e[1]}}var en=new Set(["project","team","view","initiative","cycle","roadmap","inbox","triage","my-issues"]),qe=new Set(["docs","features","method","blog","customers","pricing","integrations","developers","changelog","about","careers","security","download","contact","now","switch","homepage"]);function le(t){let n=ue(t);return n===null||n.length<2||!en.has(n[1])||qe.has(n[0].toLowerCase())?null:{workspace:n[0],section:n[1]}}function de(t){let n=ue(t);return n===null||n.length<2||n[1]!=="issue"&&n[1]!=="document"||qe.has(n[0].toLowerCase())||Y(t)!==null||K(t)!==null?null:{workspace:n[0],section:n[1]}}function Qe(t){let n=Y(t);return n?n.key.toLowerCase():null}function et(t){let n=K(t);return n?`doc-${n.slugId}`:null}var tt={linearInfo:je,linearIssue:Be,linearComments:Me,linearDocument:Je,linearAttachment:Fe};function nt(t,n){if(t)try{let e=new URL(t).pathname.split("/").filter(Boolean)[0];if(e)return`linear.app/${e.toLowerCase()}`}catch{}return`linear.app/${n.toLowerCase()}`}function rt(t,n,e,r,s,o){let l=ee(t,r);if(l!==null&&typeof l.schema=="string"&&l.schema.startsWith(`kane.source.${n}/`)){let i=l;for(let c of e)i=i!==null&&typeof i=="object"?i[c]:void 0;if(typeof i=="string"&&i!==""&&i!==s)return`source '${r}' was ingested from a different ${o} that used this key \u2014 the key was recycled; retire it first (kane-cli context retire ${r}) or ingest under a different id with --as`}let u=ke(t,n,e,s);return u!==null&&u!==r?`this ${o} is already ingested as '${u}' (its key changed) \u2014 reconcile that source, or retire it to re-ingest under the new key`:null}function ot(t,n,e,r){let s=ee(t,e);if(s===null||typeof s.schema!="string"||!s.schema.startsWith(`kane.source.${n}/`))return null;let o=s.site;return typeof o!="string"||o.length===0||o===r?null:`source '${e}' was ingested from ${o}, but this read serves ${r} \u2014 retire it first (kane-cli context retire ${e}) or ingest under a different id with --as`}async function tn(t,n,e,r,s){let o=Y(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear issue URL (https://linear.app/<workspace>/issue/KEY-123)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-2HTDCT7X.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.issue===!1||c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issues or their comments yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearIssue(o.key,i),d=await l.linearComments(o.key,i),p=nt(a.host,o.workspace),{bytes:y,envelope:w,warnings:f}=Ge(a,d,p),h=n??o.key.toLowerCase();N(h);let _=rt(r,"linear",["issue","uuid"],h,w.issue.uuid,"issue")??P(r,h,"linear")??ot(r,"linear",h,p);if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let b=await T({contextDir:r,bytes:y,media:Ee,sourceId:h,label:t,confirmSameSource:e.isTTY?g=>e.confirm(`identical content already ingested as ${g} \u2014 treat as the same source?`):void 0,converters:{linear:ze({fetchAttachment:g=>l.linearAttachment(g,i)})}});e.out(U(e.isTTY,b,w.issue.key));for(let g of f)e.out(`warning: ${g}`);for(let g of b.warnings??[])e.out(`warning: ${g}`);if(b.composite){let g=b.composite.delivered+b.composite.omitted;e.out(`${b.source_id}: linear, ${g} images, ${b.composite.delivered} delivered (${b.composite.omitted} omitted)`)}return{code:0,result:{status:b.status,source_id:b.source_id,source_cid:b.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"issue","Linear")}`),{code:1})}}async function nn(t,n,e,r,s){let o=K(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear document URL (https://linear.app/<workspace>/document/<slug>)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-2HTDCT7X.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read documents yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearDocument(o.slugId,i),d=nt(a.url,o.workspace),{bytes:p,envelope:y,warnings:w}=Ye(a,d,o.slugId),f=n??`doc-${o.slugId}`;N(f);let h=rt(r,"linear-doc",["document","uuid"],f,y.document.uuid,"document")??P(r,f,"linear-doc")??ot(r,"linear-doc",f,d);if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=await T({contextDir:r,bytes:p,media:_e,sourceId:f,label:t,confirmSameSource:e.isTTY?b=>e.confirm(`identical content already ingested as ${b} \u2014 treat as the same source?`):void 0,converters:{linearDoc:Xe({fetchAttachment:b=>l.linearAttachment(b,i)})}});e.out(U(e.isTTY,_,y.title||`document ${o.slugId}`));for(let b of w)e.out(`warning: ${b}`);for(let b of _.warnings??[])e.out(`warning: ${b}`);if(_.composite){let b=_.composite.delivered+_.composite.omitted;e.out(`${_.source_id}: linear document, ${b} images, ${_.composite.delivered} delivered (${_.composite.omitted} omitted)`)}return{code:0,result:{status:_.status,source_id:_.source_id,source_cid:_.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"document","Linear")}`),{code:1})}}function it(t,n,e){let r=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return r?`the ${n}'s content is too large to ingest (${r[1]}; the limit is ${r[2]}) \u2014 trim the ${n} in ${e} and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?`the ${n}'s text is too large to ingest \u2014 trim the ${n} in ${e} and retry`:t}var st={name:"linear",hint:"Linear issue URLs (https://linear.app/<workspace>/issue/KEY-123)",match:t=>Y(t)!==null,ingest:tn,sourceIdFor:Qe},at={name:"linear-doc",hint:"Linear document URLs (https://linear.app/<workspace>/document/<slug>)",match:t=>K(t)!==null,ingest:nn,sourceIdFor:et},ct={name:"linear-page",hint:"Linear issue or document URLs (other linear.app pages are not ingestable)",match:t=>le(t)!==null||de(t)!==null,ingest:async(t,n,e)=>{let r=le(t);if(r===null){let s=de(t);return s!==null?((e.err??e.out)(`error: ${t}: this Linear ${s.section} link is incomplete or malformed \u2014 use the full form (https://linear.app/${s.workspace}/issue/KEY-123 or https://linear.app/${s.workspace}/document/<slug>-<id>)`),{code:1}):((e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear workspace page`),{code:1})}return(e.err??e.out)(`error: ${t}: this Linear page can't be ingested \u2014 only issue and document URLs are supported; ingest the project's issues or documents individually (https://linear.app/${r.workspace}/issue/KEY-123)`),{code:1}},sourceIdFor:()=>null};var rn=new Set(["invalid_url","target_disallowed","page_not_found","page_access_blocked","page_paywalled","unsupported_content_type","page_too_large","page_timeout","scrape_unavailable","scrape_rate_limited","internal_error","credit_denied"]);async function ut(t,n){let e=n.env??process.env,r=n.fetchImpl??fetch,s=we(e),o={"Content-Type":"application/json"},l=await n.authEnv(),u=l.TESTMUAI_BASIC_AUTH??e.TESTMUAI_BASIC_AUTH,i=l.TESTMUAI_API_KEY??e.TESTMUAI_API_KEY;u?o.Authorization=`Basic ${u}`:i&&(o.Authorization=`Bearer ${i}`);let c;try{c=await r(`${s}/assurance/web/scrape`,{method:"POST",headers:o,body:JSON.stringify({url:t}),signal:AbortSignal.timeout(n.timeoutMs??55e3)})}catch{return{ok:!1,kind:"transport_unreachable"}}if(c.status===401)return{ok:!1,kind:"auth_rejected"};let a;try{a=await c.json()}catch{return{ok:!1,kind:c.status===404?"route_missing":"malformed_response"}}if(c.ok){let p=a.page;return p===void 0||typeof p.markdown!="string"||p.markdown===""||typeof p.final_url!="string"||p.final_url===""||typeof p.projection?.kind!="string"||typeof p.projection?.version!="string"?{ok:!1,kind:"malformed_response"}:{ok:!0,page:p}}let d=a.code;return typeof d=="string"&&rn.has(d)?{ok:!1,kind:d}:c.status===404?{ok:!1,kind:"route_missing"}:c.status===403?{ok:!1,kind:"auth_rejected"}:{ok:!1,kind:"malformed_response"}}var pe="kane.source.web/1";function lt(t,n,e){if(e==="")throw new Error("cannot build a web source from an empty page projection");if(n.kind===""||n.version==="")throw new Error("cannot build a stable identity without a server-reported projection kind/version");let r={schema:pe,url:t,projection:{kind:n.kind,version:n.version},content:{markdown:e}};return{bytes:Buffer.from(JSON.stringify(r),"utf8"),envelope:r}}var on=new Set(["markdown"]);function dt(){return async t=>{let n;try{n=JSON.parse(t.toString("utf8"))}catch{throw new Error("this web source's stored envelope is not readable \u2014 re-ingest the page")}if(n.schema!==pe)throw new Error(`unknown web envelope schema '${String(n.schema)}' \u2014 re-ingest the page with this CLI version`);if(!on.has(n.projection?.kind??""))throw new Error(`unknown web projection kind '${String(n.projection?.kind)}' \u2014 update kane-cli to read this source`);if(typeof n.content?.markdown!="string"||n.content.markdown==="")throw new Error("this web source's stored envelope carries no content \u2014 re-ingest the page");return{projection:n.content.markdown,inventory:[],blobs:new Map,delivered:[],converter:{name:"web-convert",version:"1",policy:"markdown-passthrough"}}}}import{createHash as sn}from"crypto";function pt(t){return ae(t)!==null}function ae(t){if(!/^https?:\/\//i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname===""?null:(n.hash="",n.username="",n.password="",n.toString())}function me(t){let n=ae(t);if(n===null)return null;let e=new URL(n),r=(e.hostname+e.pathname).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,""),s=sn("sha256").update(n,"utf8").digest("hex").slice(0,8);return`${r||"page"}-${s}`}function an(t,n){let e=j(t),r=e.heads.get(n);if(r==null)return null;let s=e.getNode(r)?.content?.blob;if(typeof s!="string")return null;let o=W(t,s);if(o===null)return null;try{let l=JSON.parse(o.toString("utf8"));return l.schema!=="kane.source.web/1"?null:typeof l.url=="string"&&l.url.length>0?l.url:null}catch{return null}}function fe(t){switch(t){case"invalid_url":return"this is not a valid public HTTP or HTTPS page URL \u2014 check the address and try again";case"target_disallowed":return"that address cannot be fetched because it does not point to an allowed public web page";case"page_not_found":return"the page could not be found \u2014 check that the URL is correct and that the page still exists";case"page_access_blocked":return"the page refused automated access, so its contents could not be ingested \u2014 use a publicly accessible version of the page";case"page_paywalled":return"the page is behind a paywall or sign-in screen, so its full contents could not be ingested \u2014 use a publicly accessible copy";case"unsupported_content_type":return"the URL does not point to an HTML web page \u2014 download the document and ingest the supported file instead";case"page_too_large":return"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first";case"page_timeout":return"the page took too long to load \u2014 try again later";case"scrape_unavailable":case"scrape_rate_limited":case"internal_error":return"the page ingest service is temporarily unavailable \u2014 try again later";case"credit_denied":return"the page could not be ingested \u2014 your organization is out of credits";case"auth_rejected":return"your credentials were rejected \u2014 run `kane-cli login` and retry";case"route_missing":return"ingesting web pages is not available in your environment yet \u2014 nothing is wrong with the URL; try again later";case"transport_unreachable":return"the page ingest service could not be reached \u2014 check your connection and try again";case"malformed_response":return"the page ingest service returned a response that could not be read safely \u2014 try again later"}}function cn(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page contains too much text to ingest as a single source (${n[1]}; the limit is ${n[2]}) \u2014 use a narrower page or trim the content first`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first":t}async function un(t,n,e,r,s){let o=ae(t);if(o===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};let l=me(t),u=n??l;if(u===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};try{N(u)}catch(y){return(e.err??e.out)(`error: ${t}: ${y instanceof Error?y.message:String(y)}`),{code:1}}let i=P(r,u,"web");if(i!==null)return(e.err??e.out)(`error: ${t}: ${i}`),{code:1};let c=an(r,u);if(c!==null&&c!==o){if(!e.isTTY)return(e.err??e.out)(`error: ${t}: source '${u}' was ingested from ${c} \u2014 re-run on a TTY to adopt the new URL as its next version, or ingest under a different id with --as`),{code:1};if(!await e.confirm(`source '${u}' was ingested from ${c} \u2014 treat ${o} as its new version (replaces the current version; items built on it go stale)?`))return e.out(`skipped ${t} \u2014 ingest under a different id with --as to keep both pages`),{code:1}}let a=s?.web?.scrape??ut,d=s?.authEnv??(async()=>(await import("./spawner-YQSAPZR4.js")).resolveAgentAuthEnv()),p=await a(o,{authEnv:d});if(!p.ok)return(e.err??e.out)(`error: ${t}: ${fe(p.kind)}`),{code:1};try{let{bytes:y}=lt(o,p.page.projection,p.page.markdown),w=await T({contextDir:r,bytes:y,media:be,sourceId:u,label:o,confirmSameSource:e.isTTY?h=>e.confirm(`identical content already ingested as ${h} \u2014 treat as the same source?`):void 0,converters:{web:dt()}}),f=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,w,f));for(let h of w.warnings??[])e.out(`warning: ${h}`);return e.isTTY&&p.page.title&&e.out(` title: ${p.page.title}`),{code:0,result:{status:w.status,source_id:w.source_id,source_cid:w.cid}}}catch(y){return(e.err??e.out)(`error: ${t}: ${cn(y instanceof Error?y.message:String(y))}`),{code:1}}}var mt={name:"web",hint:"any public web page URL (https://\u2026)",match:pt,ingest:un,sourceIdFor:me};function U(t,n,e){return t?n.status==="created"?`landed ${n.source_id} (${e}) \u2014 new source`:n.status==="versioned"?`landed ${n.source_id} (${e}) \u2014 new version; dependents go stale`:`${n.source_id} unchanged \u2014 already landed`:`${n.status} ${n.source_id} source ${n.cid} blob ${n.blob}`}var ln=[Oe,De,st,at,ct,mt];function Kr(t){return/^https?:\/\/.+/i.test(t)}function Wr(t){return ln.find(n=>n.match(t))??null}export{U as a,ln as b,Kr as c,Wr as d};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as l}from"./chunk-O3RRCPIU.js";import{a as m}from"./chunk-H6KL3FSB.js";import{a as p}from"./chunk-RZ4F3BHX.js";import{a as f}from"./chunk-6MJGCETZ.js";import{a as c,b as s,h as a,w as u}from"./chunk-DWHXXPDX.js";var v="/public/skills/kane-cli";function C(){try{let n=new f().getDefaultEnv();if(n in u)return n}catch{}return"prod"}function k(){return`${m(C()).controllerBaseUrl}${v}`}import{readFileSync as S,writeFileSync as E,mkdirSync as g}from"fs";import{join as d}from"path";var h=d(s,"skill-check.json"),y=3600*1e3;function V(){try{let n=JSON.parse(S(h,"utf-8"));if(Date.now()-n.checkedAt<y)return n}catch{}return null}function A(n){try{g(s,{recursive:!0}),E(h,JSON.stringify({map:n,checkedAt:Date.now()}))}catch{}}function I(){for(let{dir:n}of a)try{let t=S(d(n,"VERSION"),"utf-8").trim();if(t)return t}catch{}return null}function M(n,t){let i=Object.keys(n.versions??{});if(i.length===0)return null;let o=i.slice().sort((r,e)=>l(r,e));for(let r of o){let e=n.versions[r]?.kaneCliMinVersion;if(!e||l(t,e)<=0)return r}return null}async function U(){try{let n=V()?.map;if(!n){let o=new AbortController,r=setTimeout(()=>o.abort(),5e3),e=await p(k(),{headers:{Accept:"application/json"},signal:o.signal});if(clearTimeout(r),!e.ok)return null;n=await e.json(),A(n)}let t=M(n,c);if(!t)return null;let i=I();return i===null?{current:null,latestCompatible:t}:l(i,t)>0?{current:i,latestCompatible:t}:null}catch{return null}}export{k as a,M as b,U as c};
2
+ import{b as l}from"./chunk-5Q3W3SX7.js";import{a as m}from"./chunk-FOP6CJAM.js";import{a as p}from"./chunk-RZ4F3BHX.js";import{a as f}from"./chunk-BUM367KV.js";import{a as c,b as s,h as a,w as u}from"./chunk-WEJA3EVI.js";var v="/public/skills/kane-cli";function C(){try{let n=new f().getDefaultEnv();if(n in u)return n}catch{}return"prod"}function k(){return`${m(C()).controllerBaseUrl}${v}`}import{readFileSync as S,writeFileSync as E,mkdirSync as g}from"fs";import{join as d}from"path";var h=d(s,"skill-check.json"),y=3600*1e3;function V(){try{let n=JSON.parse(S(h,"utf-8"));if(Date.now()-n.checkedAt<y)return n}catch{}return null}function A(n){try{g(s,{recursive:!0}),E(h,JSON.stringify({map:n,checkedAt:Date.now()}))}catch{}}function I(){for(let{dir:n}of a)try{let t=S(d(n,"VERSION"),"utf-8").trim();if(t)return t}catch{}return null}function M(n,t){let i=Object.keys(n.versions??{});if(i.length===0)return null;let o=i.slice().sort((r,e)=>l(r,e));for(let r of o){let e=n.versions[r]?.kaneCliMinVersion;if(!e||l(t,e)<=0)return r}return null}async function U(){try{let n=V()?.map;if(!n){let o=new AbortController,r=setTimeout(()=>o.abort(),5e3),e=await p(k(),{headers:{Accept:"application/json"},signal:o.signal});if(clearTimeout(r),!e.ok)return null;n=await e.json(),A(n)}let t=M(n,c);if(!t)return null;let i=I();return i===null?{current:null,latestCompatible:t}:l(i,t)>0?{current:i,latestCompatible:t}:null}catch{return null}}export{k as a,M as b,U as c};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as R}from"./chunk-7RAIRUXO.js";import{x as i}from"./chunk-DWHXXPDX.js";import{a as Y}from"./chunk-HCBYKLMW.js";import{a,b as l,i as X}from"./chunk-C44QQJR4.js";import{a as K}from"./chunk-6YGTRKDT.js";import{e as P}from"./chunk-UR6MHSHU.js";var x=P(K(),1);var e=P(Y(),1),f=5;function Z(t,S){if(!S)return t;let c=S.toLowerCase();return t.filter(B=>B.label.toLowerCase().includes(c))}function Q(t){let{title:S,items:c,loading:B=!1,loadingText:p,error:L=null,itemNoun:v="items",onSelect:O,onCancel:E,defaultActiveId:w,onTab:y,extraHint:H}=t,[g,s]=(0,x.useState)(0),[h,u]=(0,x.useState)(0),[d,A]=(0,x.useState)(""),[C,I]=(0,x.useState)(null),N=!t.onSearch&&d!=="";(0,x.useEffect)(()=>{if(c.length===0||N)return;if(t.preserveSelectionById&&C!==null){let o=c.findIndex(n=>n.id===C);if(o>=0){u(Math.floor(o/f)),s(o%f);return}}let r=w?c.findIndex(o=>o.id===w):c.findIndex(o=>o.isActive);r>=0?(u(Math.floor(r/f)),s(r%f),t.preserveSelectionById&&I(c[r].id)):t.preserveSelectionById&&(u(0),s(0),I(c[0]?.id??null))},[c,w,t.preserveSelectionById,C,N]),(0,x.useEffect)(()=>{if(!t.onSearch)return;let r=setTimeout(()=>t.onSearch(d),t.searchDebounceMs??250);return()=>clearTimeout(r)},[d,t.onSearch,t.searchDebounceMs]);let b=t.onSearch?c:Z(c,d),D=h*f,F=Math.min(D+f,b.length),M=Math.ceil(b.length/f),$=F-D,T=b.slice(D,F);return X((r,o)=>{if(L){o.escape&&E();return}if(o.escape){d?(A(""),s(0),u(0)):E();return}if(o.tab&&y){y();return}if(o.upArrow){if(g>0){let n=g-1;s(n),t.preserveSelectionById&&I(T[n]?.id??null)}else if(h>0){let n=h-1,m=f-1;u(n),s(m),t.preserveSelectionById&&I(b[n*f+m]?.id??null)}return}if(o.downArrow){if(g<$-1){let n=g+1;s(n),t.preserveSelectionById&&I(T[n]?.id??null)}else if(h<M-1){let n=h+1,m=0;u(n),s(m),t.preserveSelectionById&&I(b[n*f+m]?.id??null)}return}if(o.return&&T[g]){if(T[g].disabled)return;O(T[g]);return}if(o.backspace||o.delete){A(n=>n.slice(0,-1)),s(0),u(0);return}r&&!o.ctrl&&!o.meta&&(A(n=>n+r),s(0),u(0))},{isActive:!B}),B?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,e.jsx)(l,{color:i.orange,bold:!0,children:S}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(l,{color:i.secondary,children:p??`Loading ${v}\u2026`})})]}):L?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.red,paddingX:2,paddingY:1,children:[(0,e.jsx)(l,{color:i.red,bold:!0,children:S}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(l,{color:i.red,children:L})}),(0,e.jsx)(R,{bindings:[]})]}):(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(l,{color:i.orange,bold:!0,children:S}),(0,e.jsxs)(l,{color:i.dim,children:[" (",b.length,!t.onSearch&&d?`/${c.length}`:""," ",v,t.loadingMore?" \xB7 loading more":"",")"]})]}),(0,e.jsxs)(a,{marginTop:1,children:[(0,e.jsx)(l,{color:i.secondary,children:d?"filter: ":""}),d?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(l,{children:d}),(0,e.jsx)(l,{inverse:!0,children:" "})]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(l,{color:i.dim,children:["Search ",v,"\u2026"]}),(0,e.jsx)(l,{inverse:!0,children:" "})]})]}),(0,e.jsx)(a,{flexDirection:"column",marginTop:1,children:t.searching?(0,e.jsxs)(l,{color:i.secondary,children:["Searching ",v,"\u2026"]}):b.length===0?(0,e.jsxs)(l,{color:i.dim,children:["No ",v,' match "',d,'"']}):T.map((r,o)=>{let n=o===g,m=n?"\u276F ":" ",G=r.disabled?i.muted:r.isActive?i.green:n?i.orange:void 0;return(0,e.jsxs)(a,{flexDirection:"column",children:[(0,e.jsxs)(l,{color:G,children:[m,r.label,r.isActive&&!r.disabled?" \u25CF selected":""]}),n&&r.disabled&&r.disabledHint&&(0,e.jsxs)(l,{color:i.red,children:[" ",r.disabledHint]})]},r.id)})}),!t.searching&&M>1&&(0,e.jsx)(a,{marginTop:1,children:(0,e.jsxs)(l,{color:i.dim,children:["Page ",h+1,"/",M]})}),t.footer&&(0,e.jsx)(a,{marginTop:1,flexDirection:"column",children:t.footer}),(0,e.jsx)(R,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"type",label:"to search"},{keys:"\u21B5",label:"select"},...y&&H?[{keys:"tab",label:H}]:[]],escBackLabel:d?"clear":"back to chat"})]})}export{Q as a};
2
+ import{a as R}from"./chunk-KUAFVRSR.js";import{x as i}from"./chunk-WEJA3EVI.js";import{a as Y}from"./chunk-HCBYKLMW.js";import{a,b as l,i as X}from"./chunk-C44QQJR4.js";import{a as K}from"./chunk-6YGTRKDT.js";import{e as P}from"./chunk-UR6MHSHU.js";var x=P(K(),1);var e=P(Y(),1),f=5;function Z(t,S){if(!S)return t;let c=S.toLowerCase();return t.filter(B=>B.label.toLowerCase().includes(c))}function Q(t){let{title:S,items:c,loading:B=!1,loadingText:p,error:L=null,itemNoun:v="items",onSelect:O,onCancel:E,defaultActiveId:w,onTab:y,extraHint:H}=t,[g,s]=(0,x.useState)(0),[h,u]=(0,x.useState)(0),[d,A]=(0,x.useState)(""),[C,I]=(0,x.useState)(null),N=!t.onSearch&&d!=="";(0,x.useEffect)(()=>{if(c.length===0||N)return;if(t.preserveSelectionById&&C!==null){let o=c.findIndex(n=>n.id===C);if(o>=0){u(Math.floor(o/f)),s(o%f);return}}let r=w?c.findIndex(o=>o.id===w):c.findIndex(o=>o.isActive);r>=0?(u(Math.floor(r/f)),s(r%f),t.preserveSelectionById&&I(c[r].id)):t.preserveSelectionById&&(u(0),s(0),I(c[0]?.id??null))},[c,w,t.preserveSelectionById,C,N]),(0,x.useEffect)(()=>{if(!t.onSearch)return;let r=setTimeout(()=>t.onSearch(d),t.searchDebounceMs??250);return()=>clearTimeout(r)},[d,t.onSearch,t.searchDebounceMs]);let b=t.onSearch?c:Z(c,d),D=h*f,F=Math.min(D+f,b.length),M=Math.ceil(b.length/f),$=F-D,T=b.slice(D,F);return X((r,o)=>{if(L){o.escape&&E();return}if(o.escape){d?(A(""),s(0),u(0)):E();return}if(o.tab&&y){y();return}if(o.upArrow){if(g>0){let n=g-1;s(n),t.preserveSelectionById&&I(T[n]?.id??null)}else if(h>0){let n=h-1,m=f-1;u(n),s(m),t.preserveSelectionById&&I(b[n*f+m]?.id??null)}return}if(o.downArrow){if(g<$-1){let n=g+1;s(n),t.preserveSelectionById&&I(T[n]?.id??null)}else if(h<M-1){let n=h+1,m=0;u(n),s(m),t.preserveSelectionById&&I(b[n*f+m]?.id??null)}return}if(o.return&&T[g]){if(T[g].disabled)return;O(T[g]);return}if(o.backspace||o.delete){A(n=>n.slice(0,-1)),s(0),u(0);return}r&&!o.ctrl&&!o.meta&&(A(n=>n+r),s(0),u(0))},{isActive:!B}),B?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,e.jsx)(l,{color:i.orange,bold:!0,children:S}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(l,{color:i.secondary,children:p??`Loading ${v}\u2026`})})]}):L?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.red,paddingX:2,paddingY:1,children:[(0,e.jsx)(l,{color:i.red,bold:!0,children:S}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(l,{color:i.red,children:L})}),(0,e.jsx)(R,{bindings:[]})]}):(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(l,{color:i.orange,bold:!0,children:S}),(0,e.jsxs)(l,{color:i.dim,children:[" (",b.length,!t.onSearch&&d?`/${c.length}`:""," ",v,t.loadingMore?" \xB7 loading more":"",")"]})]}),(0,e.jsxs)(a,{marginTop:1,children:[(0,e.jsx)(l,{color:i.secondary,children:d?"filter: ":""}),d?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(l,{children:d}),(0,e.jsx)(l,{inverse:!0,children:" "})]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(l,{color:i.dim,children:["Search ",v,"\u2026"]}),(0,e.jsx)(l,{inverse:!0,children:" "})]})]}),(0,e.jsx)(a,{flexDirection:"column",marginTop:1,children:t.searching?(0,e.jsxs)(l,{color:i.secondary,children:["Searching ",v,"\u2026"]}):b.length===0?(0,e.jsxs)(l,{color:i.dim,children:["No ",v,' match "',d,'"']}):T.map((r,o)=>{let n=o===g,m=n?"\u276F ":" ",G=r.disabled?i.muted:r.isActive?i.green:n?i.orange:void 0;return(0,e.jsxs)(a,{flexDirection:"column",children:[(0,e.jsxs)(l,{color:G,children:[m,r.label,r.isActive&&!r.disabled?" \u25CF selected":""]}),n&&r.disabled&&r.disabledHint&&(0,e.jsxs)(l,{color:i.red,children:[" ",r.disabledHint]})]},r.id)})}),!t.searching&&M>1&&(0,e.jsx)(a,{marginTop:1,children:(0,e.jsxs)(l,{color:i.dim,children:["Page ",h+1,"/",M]})}),t.footer&&(0,e.jsx)(a,{marginTop:1,flexDirection:"column",children:t.footer}),(0,e.jsx)(R,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"type",label:"to search"},{keys:"\u21B5",label:"select"},...y&&H?[{keys:"tab",label:H}]:[]],escBackLabel:d?"clear":"back to chat"})]})}export{Q as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as t}from"./chunk-IPZFZUJX.js";async function l(e){let o=e.credentials.expires_at,i=e.thresholdSeconds??300;if(o-Date.now()/1e3>=i)return null;let r=e.creds.loadClient(e.profile,e.env);if(!r)return null;let n=await new t(e.env).refreshToken(e.credentials.refresh_token,r.client_id),s=Math.floor(Date.now()/1e3)+n.expires_in;return e.creds.saveCredentials(e.profile,e.env,{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:s,scope:n.scope}),{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:s,scope:n.scope}}export{l as a};
2
+ import{a as t}from"./chunk-B4CYIZP5.js";async function l(e){let o=e.credentials.expires_at,i=e.thresholdSeconds??300;if(o-Date.now()/1e3>=i)return null;let r=e.creds.loadClient(e.profile,e.env);if(!r)return null;let n=await new t(e.env).refreshToken(e.credentials.refresh_token,r.client_id),s=Math.floor(Date.now()/1e3)+n.expires_in;return e.creds.saveCredentials(e.profile,e.env,{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:s,scope:n.scope}),{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:s,scope:n.scope}}export{l as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as t}from"./chunk-DWHXXPDX.js";import{join as i}from"path";function e(n=t){return i(n,"plugins")}function g(n,r=t){return i(e(r),n)}function c(n,r,o=t){return i(g(n,o),r)}function f(n,r=t){return i(g(n,r),"current")}function x(n,r=t){return i(g(n,r),"config.json")}function l(n,r=t){return i(g(n,r),".jobs")}function s(n=t){return i(n,"bin")}function h(n=t){return i(s(n),"hyperexecute")}export{e as a,g as b,c,f as d,x as e,l as f,s as g,h};
2
+ import{b as t}from"./chunk-WEJA3EVI.js";import{join as i}from"path";function e(n=t){return i(n,"plugins")}function g(n,r=t){return i(e(r),n)}function c(n,r,o=t){return i(g(n,o),r)}function f(n,r=t){return i(g(n,r),"current")}function x(n,r=t){return i(g(n,r),"config.json")}function l(n,r=t){return i(g(n,r),".jobs")}function s(n=t){return i(n,"bin")}function h(n=t){return i(s(n),"hyperexecute")}export{e as a,g as b,c,f as d,x as e,l as f,s as g,h};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as m,d as g,e as f}from"./chunk-TN4SXGAP.js";import{b as d}from"./chunk-DWHXXPDX.js";import{mkdirSync as M,writeFileSync as o,existsSync as c,readFileSync as O}from"fs";import{join as a}from"path";var p={name:"remote-execution",version:"0.3.0",backendId:"hyper",kaneCompat:">=0.4.0",defaults:{runson:"mac",concurrency:1}},E={runson:"mac",concurrency:1,timeoutMinutes:120},y=`version: "0.1"
2
+ import{c as m,d as g,e as f}from"./chunk-ETIQJIDI.js";import{b as d}from"./chunk-WEJA3EVI.js";import{mkdirSync as M,writeFileSync as o,existsSync as c,readFileSync as O}from"fs";import{join as a}from"path";var p={name:"remote-execution",version:"0.3.0",backendId:"hyper",kaneCompat:">=0.4.0",defaults:{runson:"mac",concurrency:1}},E={runson:"mac",concurrency:1,timeoutMinutes:120},y=`version: "0.1"
3
3
  runson: {{runson}}
4
4
  autosplit: true
5
5
  concurrency: {{concurrency}}
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{w as s}from"./chunk-DWHXXPDX.js";function n(r="prod"){let e=s[r];return r!=="stage"?e:{authBaseUrl:process.env.KANE_STAGE_AUTH_URL??e.authBaseUrl,consentUrl:process.env.KANE_STAGE_CONSENT_URL??e.consentUrl,controllerBaseUrl:process.env.TESTMUAI_BASE_URL??e.controllerBaseUrl,tmsBaseUrl:process.env.KANE_STAGE_TMS_URL??e.tmsBaseUrl,testGeneratorBaseUrl:process.env.KANE_STAGE_TCG_URL??e.testGeneratorBaseUrl,secretsBaseUrl:process.env.KANE_STAGE_SECRETS_URL??e.secretsBaseUrl,testManagerUiUrl:process.env.KANE_STAGE_TEST_MANAGER_UI_URL??e.testManagerUiUrl,shareApiBaseUrl:process.env.KANE_STAGE_SHARE_API_URL??e.shareApiBaseUrl,v16ServerHost:process.env.KANE_STAGE_V16_SERVER_HOST??e.v16ServerHost,evidenceViewerUrl:process.env.KANE_STAGE_EVIDENCE_VIEWER_URL??e.evidenceViewerUrl,mediaArtefactsHost:process.env.KANE_STAGE_MEDIA_ARTEFACTS_HOST??e.mediaArtefactsHost,mobileAppBaseUrl:process.env.KANE_STAGE_MOBILE_APP_URL??e.mobileAppBaseUrl}}export{n as a};
2
+ import{w as s}from"./chunk-WEJA3EVI.js";function n(r="prod"){let e=s[r];return r!=="stage"?e:{authBaseUrl:process.env.KANE_STAGE_AUTH_URL??e.authBaseUrl,consentUrl:process.env.KANE_STAGE_CONSENT_URL??e.consentUrl,controllerBaseUrl:process.env.TESTMUAI_BASE_URL??e.controllerBaseUrl,tmsBaseUrl:process.env.KANE_STAGE_TMS_URL??e.tmsBaseUrl,testGeneratorBaseUrl:process.env.KANE_STAGE_TCG_URL??e.testGeneratorBaseUrl,secretsBaseUrl:process.env.KANE_STAGE_SECRETS_URL??e.secretsBaseUrl,testManagerUiUrl:process.env.KANE_STAGE_TEST_MANAGER_UI_URL??e.testManagerUiUrl,shareApiBaseUrl:process.env.KANE_STAGE_SHARE_API_URL??e.shareApiBaseUrl,v16ServerHost:process.env.KANE_STAGE_V16_SERVER_HOST??e.v16ServerHost,evidenceViewerUrl:process.env.KANE_STAGE_EVIDENCE_VIEWER_URL??e.evidenceViewerUrl,mediaArtefactsHost:process.env.KANE_STAGE_MEDIA_ARTEFACTS_HOST??e.mediaArtefactsHost,mobileAppBaseUrl:process.env.KANE_STAGE_MOBILE_APP_URL??e.mobileAppBaseUrl}}export{n as a};
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as k}from"./chunk-IBPF5IM5.js";import{a as m}from"./chunk-BPMSNGXQ.js";import{r as a}from"./chunk-RSSOJ3L2.js";import{a as y}from"./chunk-H6KL3FSB.js";import{a as h}from"./chunk-6MJGCETZ.js";var $=10,u=200,N=1e4,S=1e6;function T(t,e,r="streaming"){let n=r==="full-fetch"?S:N,o=$,i=0;if(t!==void 0){let s=Number(t);if(!Number.isInteger(s)||s<1||s>u)return{error:`--limit must be an integer in [1, ${u}] (got "${t}")`};o=s}if(e!==void 0){let s=Number(e);if(!Number.isInteger(s)||s<0||s>n)return{error:`--offset must be an integer in [0, ${n}] (got "${e}")`};i=s}return{limit:o,offset:i}}function C(t,e){if(!e)return t;let r=e.toLowerCase();return t.filter(n=>n.name.toLowerCase().includes(r))}function j(t,{limit:e,offset:r}){let n=t.slice(r,r+e),o=t.length>r+e;return{slice:n,hasMore:o}}function v(t,e,r=n=>process.stdout.write(`${n}
2
+ import{a as k}from"./chunk-2BIPFAGX.js";import{a as m}from"./chunk-BPMSNGXQ.js";import{r as a}from"./chunk-RSSOJ3L2.js";import{a as y}from"./chunk-FOP6CJAM.js";import{a as h}from"./chunk-BUM367KV.js";var $=10,u=200,N=1e4,S=1e6;function T(t,e,r="streaming"){let n=r==="full-fetch"?S:N,o=$,i=0;if(t!==void 0){let s=Number(t);if(!Number.isInteger(s)||s<1||s>u)return{error:`--limit must be an integer in [1, ${u}] (got "${t}")`};o=s}if(e!==void 0){let s=Number(e);if(!Number.isInteger(s)||s<0||s>n)return{error:`--offset must be an integer in [0, ${n}] (got "${e}")`};i=s}return{limit:o,offset:i}}function C(t,e){if(!e)return t;let r=e.toLowerCase();return t.filter(n=>n.name.toLowerCase().includes(r))}function j(t,{limit:e,offset:r}){let n=t.slice(r,r+e),o=t.length>r+e;return{slice:n,hasMore:o}}function v(t,e,r=n=>process.stdout.write(`${n}
3
3
  `)){for(let n of t)r(JSON.stringify(n));r(JSON.stringify({_meta:"page",limit:e.limit,offset:e.offset,returned:t.length,has_more:e.has_more}))}function b(t,e,r=n=>process.stdout.write(`${n}
4
- `)){if(t.length===0){r("(no results)");return}let n=Math.max(2,...t.map(s=>s.id.length)),o=`${"ID".padEnd(n)} NAME`;r(o),r(`${"-".repeat(n)} ----`);for(let s of t)r(`${s.id.padEnd(n)} ${s.name}`);r("");let i=e.offset+t.length;if(e.hasMore){let s=e.totalIsLowerBound?`${e.total}+`:`${e.total}`;r(`${i} of ${s} \u2014 next: --offset ${e.offset+e.limit}`)}else r(`${t.length} shown (${e.total} total)`)}async function B(t,e,r){if(r.username&&r.accessKey)return{ok:!0,creds:{username:r.username,access_key:r.accessKey}};let n=new h,o=n.loadBasicAuth(t,e);if(o)return{ok:!0,creds:{username:o.username,access_key:o.access_key}};let i=n.loadCredentials(t,e);if(!i)return{ok:!1,reason:"no_credentials"};let s=i.access_token;try{let{refreshOAuthToken:d}=await import("./token-refresh-ZFT457VI.js"),w=await d({creds:n,profile:t,env:e,credentials:i});w&&(s=w.accessToken)}catch(d){return{ok:!1,reason:"refresh_failed",detail:d instanceof Error?d.message:String(d)}}let c=y(e),f=await new k(c.controllerBaseUrl,async()=>s,null).resolve();return f?{ok:!0,creds:{username:f.username,access_key:f.access_key}}:{ok:!1,reason:"exchange_failed"}}function E(t,e,r){switch(r.reason){case"no_credentials":return{message:`error: no credentials for profile "${t}" [${e}]. Run \`kane-cli login\` or pass --username/--access-key.
4
+ `)){if(t.length===0){r("(no results)");return}let n=Math.max(2,...t.map(s=>s.id.length)),o=`${"ID".padEnd(n)} NAME`;r(o),r(`${"-".repeat(n)} ----`);for(let s of t)r(`${s.id.padEnd(n)} ${s.name}`);r("");let i=e.offset+t.length;if(e.hasMore){let s=e.totalIsLowerBound?`${e.total}+`:`${e.total}`;r(`${i} of ${s} \u2014 next: --offset ${e.offset+e.limit}`)}else r(`${t.length} shown (${e.total} total)`)}async function B(t,e,r){if(r.username&&r.accessKey)return{ok:!0,creds:{username:r.username,access_key:r.accessKey}};let n=new h,o=n.loadBasicAuth(t,e);if(o)return{ok:!0,creds:{username:o.username,access_key:o.access_key}};let i=n.loadCredentials(t,e);if(!i)return{ok:!1,reason:"no_credentials"};let s=i.access_token;try{let{refreshOAuthToken:d}=await import("./token-refresh-2XVSIFRM.js"),w=await d({creds:n,profile:t,env:e,credentials:i});w&&(s=w.accessToken)}catch(d){return{ok:!1,reason:"refresh_failed",detail:d instanceof Error?d.message:String(d)}}let c=y(e),f=await new k(c.controllerBaseUrl,async()=>s,null).resolve();return f?{ok:!0,creds:{username:f.username,access_key:f.access_key}}:{ok:!1,reason:"exchange_failed"}}function E(t,e,r){switch(r.reason){case"no_credentials":return{message:`error: no credentials for profile "${t}" [${e}]. Run \`kane-cli login\` or pass --username/--access-key.
5
5
  `,exitCode:2};case"refresh_failed":return{message:`error: OAuth token refresh failed for profile "${t}" [${e}]${r.detail?`: ${r.detail}`:""}. Run \`kane-cli login\` to re-auth.
6
6
  `,exitCode:2};case"exchange_failed":return{message:`error: TMS credential exchange failed for profile "${t}" [${e}]. Token may be revoked \u2014 try \`kane-cli login\`; if the problem persists, TMS may be down.
7
7
  `,exitCode:2}}}function O(t){return{id:t.project_id,name:t.name}}function M(t){return{id:t.id,name:t.name}}async function P(t,e,r,n){let o=r+n+1,i=[],s=!0;for await(let c of t.listProjectsStream({name:e})){if(i.push(...c.projects),c.done){s=!0;break}if(i.length>=o){s=!1;break}}return{items:i,doneStreaming:s}}function g(t){return!!t.agent||!process.stdin.isTTY||!process.stdout.isTTY}function _(t,e=r=>process.stdout.write(`${r}
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{g as S,h as v}from"./chunk-MJHLQKQC.js";import{d as c,i as m}from"./chunk-Z7S3IWUX.js";import{a as h,c as _,e as f}from"./chunk-EYOCNMUM.js";var y=["desktop","emulator","simulator"];function T(n,t){return n.kind==="app_id"?!0:t==="emulator"?n.kind==="apk":n.kind==="zip"}function $(n){let t=n.deviceName,e=n.osVersion;return t!==void 0&&t.trim()===""||e!==void 0&&e.trim()===""?{ok:!1,message:"--device-name and --os-version cannot be empty."}:{ok:!0,...t!==void 0?{name:t.trim()}:{},...e!==void 0?{osVersion:e.trim()}:{}}}function R(n){return`--device-name needs an OS version \u2014 a bare name matches every runtime that ships it.
2
+ import{g as S,h as v}from"./chunk-LKUWEQ5M.js";import{d as c,i as m}from"./chunk-Z7S3IWUX.js";import{a as h,c as _,e as f}from"./chunk-EYOCNMUM.js";var y=["desktop","emulator","simulator"];function T(n,t){return n.kind==="app_id"?!0:t==="emulator"?n.kind==="apk":n.kind==="zip"}function $(n){let t=n.deviceName,e=n.osVersion;return t!==void 0&&t.trim()===""||e!==void 0&&e.trim()===""?{ok:!1,message:"--device-name and --os-version cannot be empty."}:{ok:!0,...t!==void 0?{name:t.trim()}:{},...e!==void 0?{osVersion:e.trim()}:{}}}function R(n){return`--device-name needs an OS version \u2014 a bare name matches every runtime that ships it.
3
3
  Provide one: ${n}`}function k(n,t,e){let r=v(n);return r?T(r,t)?null:t==="emulator"?`${e} cannot run on an emulator (needs an .apk, or an APP\u2026 id).`:`${e} cannot run on a simulator (needs a .zip of the .app bundle, or an APP\u2026 id).`:`${n}: ${S}`}function I(n){return y.includes(n)?n:null}function V(n){return`--target must be one of desktop, emulator, simulator (got "${n}")`}function x(n){let t=[];for(let[e,r]of[["--device-name",n.deviceName],["--os-version",n.osVersion],["--app",n.app]])r!==void 0&&t.push(`ignored ${e} ${r}: session target is desktop \u2014 set --target emulator|simulator to run on a device`);return t}function F(n){let{flags:t,saved:e}=n,r=[],s;if(t.target!==void 0){let i=I(t.target);if(!i)return{kind:"invalid",message:V(t.target)};s=i}else{let i=h(e?.tui_target,e?.default_target?.kind);if(i.kind==="choose-mobile")return{kind:"choose-mobile-kind"};s=i.kind==="unset"?"desktop":i.kind}if(s==="desktop")return r.push(...x(t)),{kind:"web",warnings:r};if(!n.host.supported)return{kind:"invalid",message:n.host.reason??"this machine cannot run mobile targets."};let a=[],d,u,o=$(t);if(!o.ok)return{kind:"invalid",message:o.message};let l=e?.default_target&&e.default_target.kind===s?c(e.default_target):void 0;if(o.name!==void 0||o.osVersion!==void 0){let i=o.name??l?.name,p=o.osVersion??l?.osVersion;if(p===void 0)return{kind:"invalid",message:R("--os-version <version>, or save one (kane-cli config set-os-version)")};u={...i!==void 0?{name:i}:{},osVersion:p},d={value:i?`${i} (${p})`:`any device on ${p}`,source:"flag"}}else if(e?.default_target&&e.default_target.kind===s&&(c(e.default_target)!==void 0||e.default_target.id!==void 0))d={value:m(e.default_target)??"(saved device)",source:"saved"};else{if(e?.default_target&&e.default_target.kind!==s&&(c(e.default_target)!==void 0||e.default_target.id!==void 0))return{kind:"invalid",message:`Your saved device '${m(e.default_target)}' is ${e.default_target.kind==="simulator"?"a simulator":"an emulator"}, but this run targets ${s==="simulator"?"a simulator":"an emulator"}. Pass --device-name and --os-version, or update your config (set-target, set-device-name, set-os-version).`};a.push("device")}let g;if(t.app!==void 0){let i=k(t.app,s,`--app ${t.app}`);if(i)return{kind:"invalid",message:i};g={value:t.app,source:"flag"}}else{let i=e?.default_app,p=i?v(i):null;p&&T(p,s)&&e?.default_target?.kind===s?g={value:i,source:"saved"}:a.push("app")}return{kind:"mobile",target:s,...u?{deviceSelector:u}:{},...d?{device:d}:{},...g?{app:g}:{},missing:a,warnings:r}}function M(n){let{flags:t,file:e}=n,r=[],s=e.target==="emulator"||e.target==="simulator"?e.target:void 0,a;if(t.target!==void 0){let i=I(t.target);if(!i)return{kind:"invalid",message:V(t.target)};a=i,s&&s!==a&&r.push(`--target ${a} overrides the file's \`target: ${s}\` \u2014 steps recorded on ${s==="emulator"?"an emulator":"a simulator"} may not replay here`)}else a=s??"desktop";if(a==="desktop")return r.push(...x(t)),{kind:"web",warnings:r};let d=$(t);if(!d.ok)return{kind:"invalid",message:d.message};let u=d.name??(e.device_name?.trim()||void 0),o=d.osVersion??(e.os_version?.trim()||void 0);if(u!==void 0&&o===void 0)return{kind:"invalid",message:R("--os-version <version>, or os_version: in the test file")};let l=o!==void 0?{...u!==void 0?{name:u}:{},osVersion:o}:void 0;if(a==="simulator"&&l&&l.name===void 0&&r.push(`the file names no device_name \u2014 any simulator on ${o} may be used. Add device_name: to the file (or pass --device-name) to pin the device.`),t.app!==void 0){let i=k(t.app,a,`--app ${t.app}`);if(i)return{kind:"invalid",message:i}}else if(e.app){let i=k(e.app,a,`the file's app: ${e.app}`);if(i)return{kind:"invalid",message:i}}let g=t.app??(e.app||void 0);return{kind:"mobile",target:a,platform:_(a)??"",...g?{app:g}:{},...l?{deviceSelector:l}:{},...e.no_reset!==void 0?{noReset:e.no_reset}:{},warnings:r}}function D(n){return n.target==="desktop"?"Running on: Desktop \xB7 Chrome":`Running on: ${f(n.target)} \xB7 ${n.deviceLabel} \xB7 ${n.appLabel}`}var b={emulator:"</path/to/app.apk | AppId>",simulator:"</path/to/app.zip | AppId>"};function E(n,t){let e=f(n).toLowerCase();return t==="device"?[`session target is "${e}" but no device is set.`,` See devices: kane-cli devices list --target ${n}`,' Set one: kane-cli config set-device-name "<name>" && kane-cli config set-os-version "<version>"',' Or per-run: --device-name "<name>" --os-version "<version>"'].join(`
4
4
  `):[`session target is "${e}" but no app is set.`,` Set one: kane-cli config set-app ${b[n]}`,` Or per-run: --app ${b[n]}`].join(`
5
5
  `)}function K(n){return[`saved device "${n}" was not found on this machine.`," See devices: kane-cli devices list",' Set one: kane-cli config set-device-name "<name>" && kane-cli config set-os-version "<version>"'].join(`
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as $}from"./chunk-MMBBQ4OZ.js";import{j as h}from"./chunk-OR6M5HCV.js";import{a as w}from"./chunk-RZ4F3BHX.js";import{b as v}from"./chunk-DWHXXPDX.js";import{spawn as V,spawnSync as _}from"child_process";import{createServer as K}from"net";import{mkdirSync as g,openSync as W,readFileSync as I,renameSync as j,rmSync as x,statSync as Y,writeFileSync as M}from"fs";import{readFile as q}from"fs/promises";import{dirname as l,join as y}from"path";var G=[4723,4724,4725,4726,4727,4728,4729,4730],X={emulator:4750,simulator:4790},z=40,E=2e3,D=3e4,T=500,Ce=["emulator","simulator"];function Q(e){return y(v,"mobile",`appium-server-${e}.log`)}function m(){return y(v,"mobile","appium-servers.json")}function Z(){return y(v,"mobile","appium-servers.lock")}var ee=1e4,re=50;function C(e){let r=Z();try{g(l(r),{recursive:!0})}catch{return e()}let n=!1;for(let o=0;o<re;o++)try{g(r),n=!0;break}catch{try{Date.now()-Y(r).mtimeMs>ee&&x(r,{recursive:!0,force:!0})}catch{}ne(10)}try{return e()}finally{if(n)try{x(r,{recursive:!0,force:!0})}catch{}}}function ne(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}function te(){try{let e=JSON.parse(I(m(),"utf8"));return Array.isArray(e)?e:[]}catch{return[]}}function oe(e){let r=m();g(l(r),{recursive:!0});let n=`${r}.tmp`;M(n,JSON.stringify(e,null,2)),j(n,r)}function se(e,r,n){return`Another mobile session is already running${n?` on ${n}`:""}. Wait for it to finish, or close the terminal running it.`}var A=class extends Error{constructor(n,o){super(n);this.port=o;this.name="DeviceBusyError"}};function ie(e){return w(e,{signal:AbortSignal.timeout(E)}).then(r=>r.ok,()=>!1)}async function ae(e,r){try{return(await w(`http://127.0.0.1:${e}/session/${r}`,{method:"DELETE",signal:AbortSignal.timeout(E)})).ok}catch{return!1}}function R(e){let r=e?.value;return Array.isArray(r)?r.map(n=>{let o=n??{},t=o.capabilities??o;return{...typeof o.id=="string"?{id:o.id}:{},caps:t}}):[]}async function ue(e){try{let r=await w(`http://127.0.0.1:${e}/sessions`,{signal:AbortSignal.timeout(E)});return r.ok?R(await r.json()):[]}catch{return[]}}var ce=["udid","appium:udid","deviceUDID","appium:deviceUDID","deviceName","appium:deviceName"];function L(){let e=r=>{try{let n=_("curl",["-s","--noproxy","*","--max-time","2",...r],{encoding:"utf8",timeout:5e3});return{ok:n.status===0,stdout:n.stdout??""}}catch{return{ok:!1,stdout:""}}};return{readState:()=>{try{let r=JSON.parse(I(m(),"utf8"));return Array.isArray(r)?r:[]}catch{return[]}},alive:b,getJson:r=>{let n=e([r]);if(n.ok)try{return JSON.parse(n.stdout)}catch{return}},del:r=>{let n=e(["-o","/dev/null","-w","%{http_code}","-X","DELETE",r]);return n.ok&&/^2\d\d$/.test(n.stdout.trim())}}}function Le(e,r={}){let n={...L(),...r},o=0;try{for(let t of n.readState()){if(!n.alive(t.pid))continue;let i=R(n.getJson(`http://127.0.0.1:${t.port}/sessions`));for(let s of i)s.id&&de(s.caps,e.udid,e.displayName)&&n.del(`http://127.0.0.1:${t.port}/session/${s.id}`)&&(o+=1)}}catch{}return o}function de(e,r,n){let o=[r,n].filter(t=>!!t).map(t=>t.toLowerCase());for(let t of ce){let i=e[t];if(typeof i=="string"&&o.includes(i.toLowerCase()))return!0}return!1}function pe(e,r,n){let o=W(n.logPath,"a"),t=V(e,r,{stdio:["ignore",o,o],detached:!0,env:{...process.env,...n.env}});return t.unref(),t.pid}async function le(e,r){for(let n=e;n<e+r;n++)if(await new Promise(t=>{let i=K();i.once("error",()=>t(!1)),i.once("listening",()=>i.close(()=>t(!0))),i.listen(n)}))return n;throw new Error(`No free port for the managed Appium server in ${e}-${e+r-1}.`)}function b(e){try{return process.kill(e,0),!0}catch{return!1}}function P(e){try{let r=_("ps",["-o","comm=","-p",String(e)],{encoding:"utf8",timeout:2e3});if(r.status!==0)return!1;let n=r.stdout.trim().toLowerCase();return n===""?!0:n.includes("node")||n.includes("kane")}catch{return!0}}function k(e){try{process.kill(e)}catch{}}async function me(){try{let e=JSON.parse(await q(m(),"utf8"));return Array.isArray(e)?e:[]}catch{return[]}}async function fe(e){let r=process.pid,n=e.filter(o=>o.owner===r);C(()=>{let o=[];for(let t of te())t.owner!==r&&(Se(t)?o.push(t):b(t.pid)&&k(t.pid));oe([...o,...n])})}function Se(e){return e.owner===void 0?!1:b(e.owner)&&P(e.owner)}function ve(){return{probe:ie,sessions:ue,deleteSession:ae,spawn:pe,freePort:le,alive:b,kill:k,readState:me,writeState:fe,owner:process.pid,depsEnv:e=>h().environment(e),bundleVersion:async e=>(await h().status(e)).version,nodeBinary:process.execPath,env:process.env,os:process.platform,now:()=>Date.now(),sleep:e=>new Promise(r=>setTimeout(r,e))}}function we(e,r,n){if(!e.platformToolsDir)return{};let o=n==="win32"?";":":",t=$(r),i=t?.root??l(e.platformToolsDir),s=t?.platformToolsDir??e.platformToolsDir;return{ANDROID_HOME:i,ANDROID_SDK_ROOT:i,PATH:r.PATH?`${s}${o}${r.PATH}`:s}}async function ge(e){let r=await e.readState(),n=[],o=[];for(let t of r)t.owner!==void 0&&e.alive(t.owner)&&(e.ownerIsOurs??P)(t.owner)?n.push(t):o.push(t);for(let t of o){let i=e.ownerIsOurs??P;e.alive(t.pid)&&i(t.pid)&&e.kill(t.pid)}return o.length>0&&await e.writeState(n),n}async function Je(e,r={}){if(r.appiumUrl)return{result:"external",url:r.appiumUrl};let n={...ve(),...r.deps},o=await ge(n),t=o.filter(a=>a.owner===n.owner),i=new Set(t.map(a=>a.port)),s=new Set(o.map(a=>a.port));if(r.device){let a=await ye(n,s,i,e);if(a!==null)throw new A(se(r.device,a.port,a.device),a.port)}let c=await n.bundleVersion(e),u=t.find(a=>a.deviceClass===e&&(a.bundleVersion??c)===c);if(u&&await n.probe(`http://127.0.0.1:${u.port}/status`))return{result:"reused",url:`http://127.0.0.1:${u.port}`};for(let a of t.filter(S=>S.deviceClass===e&&S!==u))n.kill(a.pid);u&&n.kill(u.pid);let d=await n.depsEnv(e);if(!d.appiumHome)throw new Error(`The managed dependencies for the ${e} class are not installed.
2
+ import{a as $}from"./chunk-MMBBQ4OZ.js";import{j as h}from"./chunk-6S3Z3WPF.js";import{a as w}from"./chunk-RZ4F3BHX.js";import{b as v}from"./chunk-WEJA3EVI.js";import{spawn as V,spawnSync as _}from"child_process";import{createServer as K}from"net";import{mkdirSync as g,openSync as W,readFileSync as I,renameSync as j,rmSync as x,statSync as Y,writeFileSync as M}from"fs";import{readFile as q}from"fs/promises";import{dirname as l,join as y}from"path";var G=[4723,4724,4725,4726,4727,4728,4729,4730],X={emulator:4750,simulator:4790},z=40,E=2e3,D=3e4,T=500,Ce=["emulator","simulator"];function Q(e){return y(v,"mobile",`appium-server-${e}.log`)}function m(){return y(v,"mobile","appium-servers.json")}function Z(){return y(v,"mobile","appium-servers.lock")}var ee=1e4,re=50;function C(e){let r=Z();try{g(l(r),{recursive:!0})}catch{return e()}let n=!1;for(let o=0;o<re;o++)try{g(r),n=!0;break}catch{try{Date.now()-Y(r).mtimeMs>ee&&x(r,{recursive:!0,force:!0})}catch{}ne(10)}try{return e()}finally{if(n)try{x(r,{recursive:!0,force:!0})}catch{}}}function ne(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}function te(){try{let e=JSON.parse(I(m(),"utf8"));return Array.isArray(e)?e:[]}catch{return[]}}function oe(e){let r=m();g(l(r),{recursive:!0});let n=`${r}.tmp`;M(n,JSON.stringify(e,null,2)),j(n,r)}function se(e,r,n){return`Another mobile session is already running${n?` on ${n}`:""}. Wait for it to finish, or close the terminal running it.`}var A=class extends Error{constructor(n,o){super(n);this.port=o;this.name="DeviceBusyError"}};function ie(e){return w(e,{signal:AbortSignal.timeout(E)}).then(r=>r.ok,()=>!1)}async function ae(e,r){try{return(await w(`http://127.0.0.1:${e}/session/${r}`,{method:"DELETE",signal:AbortSignal.timeout(E)})).ok}catch{return!1}}function R(e){let r=e?.value;return Array.isArray(r)?r.map(n=>{let o=n??{},t=o.capabilities??o;return{...typeof o.id=="string"?{id:o.id}:{},caps:t}}):[]}async function ue(e){try{let r=await w(`http://127.0.0.1:${e}/sessions`,{signal:AbortSignal.timeout(E)});return r.ok?R(await r.json()):[]}catch{return[]}}var ce=["udid","appium:udid","deviceUDID","appium:deviceUDID","deviceName","appium:deviceName"];function L(){let e=r=>{try{let n=_("curl",["-s","--noproxy","*","--max-time","2",...r],{encoding:"utf8",timeout:5e3});return{ok:n.status===0,stdout:n.stdout??""}}catch{return{ok:!1,stdout:""}}};return{readState:()=>{try{let r=JSON.parse(I(m(),"utf8"));return Array.isArray(r)?r:[]}catch{return[]}},alive:b,getJson:r=>{let n=e([r]);if(n.ok)try{return JSON.parse(n.stdout)}catch{return}},del:r=>{let n=e(["-o","/dev/null","-w","%{http_code}","-X","DELETE",r]);return n.ok&&/^2\d\d$/.test(n.stdout.trim())}}}function Le(e,r={}){let n={...L(),...r},o=0;try{for(let t of n.readState()){if(!n.alive(t.pid))continue;let i=R(n.getJson(`http://127.0.0.1:${t.port}/sessions`));for(let s of i)s.id&&de(s.caps,e.udid,e.displayName)&&n.del(`http://127.0.0.1:${t.port}/session/${s.id}`)&&(o+=1)}}catch{}return o}function de(e,r,n){let o=[r,n].filter(t=>!!t).map(t=>t.toLowerCase());for(let t of ce){let i=e[t];if(typeof i=="string"&&o.includes(i.toLowerCase()))return!0}return!1}function pe(e,r,n){let o=W(n.logPath,"a"),t=V(e,r,{stdio:["ignore",o,o],detached:!0,env:{...process.env,...n.env}});return t.unref(),t.pid}async function le(e,r){for(let n=e;n<e+r;n++)if(await new Promise(t=>{let i=K();i.once("error",()=>t(!1)),i.once("listening",()=>i.close(()=>t(!0))),i.listen(n)}))return n;throw new Error(`No free port for the managed Appium server in ${e}-${e+r-1}.`)}function b(e){try{return process.kill(e,0),!0}catch{return!1}}function P(e){try{let r=_("ps",["-o","comm=","-p",String(e)],{encoding:"utf8",timeout:2e3});if(r.status!==0)return!1;let n=r.stdout.trim().toLowerCase();return n===""?!0:n.includes("node")||n.includes("kane")}catch{return!0}}function k(e){try{process.kill(e)}catch{}}async function me(){try{let e=JSON.parse(await q(m(),"utf8"));return Array.isArray(e)?e:[]}catch{return[]}}async function fe(e){let r=process.pid,n=e.filter(o=>o.owner===r);C(()=>{let o=[];for(let t of te())t.owner!==r&&(Se(t)?o.push(t):b(t.pid)&&k(t.pid));oe([...o,...n])})}function Se(e){return e.owner===void 0?!1:b(e.owner)&&P(e.owner)}function ve(){return{probe:ie,sessions:ue,deleteSession:ae,spawn:pe,freePort:le,alive:b,kill:k,readState:me,writeState:fe,owner:process.pid,depsEnv:e=>h().environment(e),bundleVersion:async e=>(await h().status(e)).version,nodeBinary:process.execPath,env:process.env,os:process.platform,now:()=>Date.now(),sleep:e=>new Promise(r=>setTimeout(r,e))}}function we(e,r,n){if(!e.platformToolsDir)return{};let o=n==="win32"?";":":",t=$(r),i=t?.root??l(e.platformToolsDir),s=t?.platformToolsDir??e.platformToolsDir;return{ANDROID_HOME:i,ANDROID_SDK_ROOT:i,PATH:r.PATH?`${s}${o}${r.PATH}`:s}}async function ge(e){let r=await e.readState(),n=[],o=[];for(let t of r)t.owner!==void 0&&e.alive(t.owner)&&(e.ownerIsOurs??P)(t.owner)?n.push(t):o.push(t);for(let t of o){let i=e.ownerIsOurs??P;e.alive(t.pid)&&i(t.pid)&&e.kill(t.pid)}return o.length>0&&await e.writeState(n),n}async function Je(e,r={}){if(r.appiumUrl)return{result:"external",url:r.appiumUrl};let n={...ve(),...r.deps},o=await ge(n),t=o.filter(a=>a.owner===n.owner),i=new Set(t.map(a=>a.port)),s=new Set(o.map(a=>a.port));if(r.device){let a=await ye(n,s,i,e);if(a!==null)throw new A(se(r.device,a.port,a.device),a.port)}let c=await n.bundleVersion(e),u=t.find(a=>a.deviceClass===e&&(a.bundleVersion??c)===c);if(u&&await n.probe(`http://127.0.0.1:${u.port}/status`))return{result:"reused",url:`http://127.0.0.1:${u.port}`};for(let a of t.filter(S=>S.deviceClass===e&&S!==u))n.kill(a.pid);u&&n.kill(u.pid);let d=await n.depsEnv(e);if(!d.appiumHome)throw new Error(`The managed dependencies for the ${e} class are not installed.
3
3
  Run \`kane-cli doctor --target ${e} --install\` to install them, or pass --appium-url for an external server.`);let p=await n.freePort(X[e],z),O=`http://127.0.0.1:${p}`,J=l(d.appiumHome),U=y(J,"appium","node_modules","appium","index.js"),N=Q(e);r.onProgress?.(`starting the managed Appium server (${e}, port ${p})\u2026`);let f=n.spawn(n.nodeBinary,[U,"--port",String(p),"--allow-insecure=uiautomator2:adb_shell"],{env:{APPIUM_HOME:d.appiumHome,...we(d,n.env,n.os)},logPath:N}),B=n.now()+D,F=Math.ceil(D/T)+1;for(let a=0;a<F&&n.now()<B;a++)if(await n.sleep(T),await n.probe(`${O}/status`)){if(f!==void 0){let S=t.filter(H=>H.deviceClass!==e);await n.writeState([...S,{port:p,pid:f,owner:n.owner,deviceClass:e,...c?{bundleVersion:c}:{},startedAt:new Date(n.now()).toISOString()}])}return r.onProgress?.("Appium server ready"),{result:"started",url:O}}throw f!==void 0&&n.kill(f),new Error(`The managed Appium server (${e}) did not answer on ${p} within ${D/1e3}s.
4
4
  Check its log: ${N}`)}async function ye(e,r=[],n=[],o){let t=new Set(n),i=new Set([...G,...r]);for(let s of i)if(!t.has(s))for(let c of await e.sessions(s)){if(!c.id)continue;if(o){let d=be(c.caps);if(d&&d!==o)continue}let u=De(c.caps);return{port:s,...u?{device:u}:{}}}return null}function be(e){let r=t=>{let i=e[t];return typeof i=="string"?i.toLowerCase():""},n=r("platformName")||r("appium:platformName");if(n.includes("ios"))return"simulator";if(n.includes("android"))return"emulator";let o=r("appium:automationName")||r("automationName");if(o.includes("xcuitest"))return"simulator";if(o.includes("uiautomator"))return"emulator"}var he=["appium:deviceName","deviceName","appium:udid","udid","appium:deviceUDID","deviceUDID"];function De(e){for(let r of he){let n=e[r];if(typeof n=="string"&&n.trim())return n}}function Ue(e={}){let r={...L(),kill:k,writeState:Ae,...e.deps};try{let n=r.readState(),o=e.owner??process.pid,t=n.filter(s=>s.owner===o&&(!e.deviceClass||s.deviceClass===e.deviceClass));for(let s of t){if(!r.alive(s.pid))continue;let c=R(r.getJson(`http://127.0.0.1:${s.port}/sessions`));for(let u of c)u.id&&r.del(`http://127.0.0.1:${s.port}/session/${u.id}`);r.kill(s.pid)}let i=new Set(t.map(s=>`${s.port}:${s.pid}`));C(()=>{r.writeState(r.readState().filter(s=>!i.has(`${s.port}:${s.pid}`)))})}catch{}}function Ae(e){try{let r=m();g(l(r),{recursive:!0}),M(r,JSON.stringify(e,null,2))}catch{}}export{Ce as a,Q as b,se as c,Le as d,ve as e,Je as f,ye as g,Ue as h};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as y}from"./chunk-H6KL3FSB.js";import{createServer as b}from"http";import{createReadStream as C,promises as S}from"fs";import{randomBytes as R}from"crypto";var u="127.0.0.1";function A(n,e){if(!n)return null;let o=/^bytes=(\d*)-(\d*)$/.exec(n.trim());if(!o)return null;let[,a,r]=o;if(a===""&&r==="")return null;if(a===""){let i=Number(r);return i===0||e===0?"unsatisfiable":{start:Math.max(0,e-i),end:e-1}}let t=Number(a);if(t>=e)return"unsatisfiable";let c=r===""?e-1:Math.min(Number(r),e-1);return c<t?null:{start:t,end:c}}async function I(n){let e=R(16).toString("hex"),o=b((r,t)=>{H(r,t,n,e).catch(()=>t.destroy())});await new Promise((r,t)=>{o.once("error",t),o.listen(n.port??0,u,()=>{o.removeListener("error",t),r()})});let a=o.address().port;return{port:a,urlFor:r=>`http://${u}:${a}/${e}/${encodeURIComponent(r)}`,close:()=>new Promise(r=>{o.close(()=>r()),o.closeAllConnections()})}}async function H(n,e,o,a){let r=n.url??"/",t=s=>{try{o.log?.("warn","EVIDENCE_SERVE_DENIED",{reason:s,path:r})}catch{}};if(n.headers.host!==`${u}:${n.socket.localPort}`){t("host_mismatch"),e.writeHead(403).end();return}let c=n.headers.origin;if(c!==void 0&&!o.allowedOrigins.includes(c)){t("origin_denied"),e.writeHead(403).end();return}let i=c?{"Access-Control-Allow-Origin":c,Vary:"Origin","Access-Control-Expose-Headers":"Content-Range, Content-Length"}:{};if(n.method==="OPTIONS"){let s={...i,"Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Headers":"range","Access-Control-Max-Age":"86400"};n.headers["access-control-request-private-network"]==="true"&&(s["Access-Control-Allow-Private-Network"]="true"),e.writeHead(204,s).end();return}if(n.method!=="GET"&&n.method!=="HEAD"){e.writeHead(405,i).end();return}let v;try{let s=new URL(n.url??"/",`http://${u}`).pathname.split("/");if(s.length!==3||s[1]!==a){t("bad_token"),e.writeHead(404,i).end();return}v=decodeURIComponent(s[2])}catch{t("not_found"),e.writeHead(404,i).end();return}let g=o.packs.get(v);if(!g){t("not_found"),e.writeHead(404,i).end();return}let d;try{let s=await S.stat(g);if(!s.isFile())throw new Error("not a file");d=s.size}catch{t("not_found"),e.writeHead(404,i).end();return}let h={...i,"Accept-Ranges":"bytes","Content-Type":"application/zip","Cache-Control":"no-store"};if(n.method==="HEAD"){e.writeHead(200,{...h,"Content-Length":String(d)}).end();return}let l=A(n.headers.range,d);if(l==="unsatisfiable"){t("unsatisfiable"),e.writeHead(416,{...i,"Content-Range":`bytes */${d}`}).end();return}let[m,p,w]=l===null?[0,d-1,200]:[l.start,l.end,206],E={...h,"Content-Length":String(p-m+1)};if(w===206&&(E["Content-Range"]=`bytes ${m}-${p}/${d}`),e.writeHead(w,E),d===0){e.end();return}let f=C(g,{start:m,end:p});f.on("error",()=>e.destroy()),e.on("close",()=>f.destroy()),f.pipe(e)}function O(n,e){return(e??y(n).evidenceViewerUrl).replace(/\/+$/,"")}function k(n,e){return`${e}/?pack=${encodeURIComponent(n)}`}function P(n){return`evidence: view locally with \`kane-cli evidence serve ${n}\``}export{A as a,I as b,O as c,k as d,P as e};
2
+ import{a as y}from"./chunk-FOP6CJAM.js";import{createServer as b}from"http";import{createReadStream as C,promises as S}from"fs";import{randomBytes as R}from"crypto";var u="127.0.0.1";function A(n,e){if(!n)return null;let o=/^bytes=(\d*)-(\d*)$/.exec(n.trim());if(!o)return null;let[,a,r]=o;if(a===""&&r==="")return null;if(a===""){let i=Number(r);return i===0||e===0?"unsatisfiable":{start:Math.max(0,e-i),end:e-1}}let t=Number(a);if(t>=e)return"unsatisfiable";let c=r===""?e-1:Math.min(Number(r),e-1);return c<t?null:{start:t,end:c}}async function I(n){let e=R(16).toString("hex"),o=b((r,t)=>{H(r,t,n,e).catch(()=>t.destroy())});await new Promise((r,t)=>{o.once("error",t),o.listen(n.port??0,u,()=>{o.removeListener("error",t),r()})});let a=o.address().port;return{port:a,urlFor:r=>`http://${u}:${a}/${e}/${encodeURIComponent(r)}`,close:()=>new Promise(r=>{o.close(()=>r()),o.closeAllConnections()})}}async function H(n,e,o,a){let r=n.url??"/",t=s=>{try{o.log?.("warn","EVIDENCE_SERVE_DENIED",{reason:s,path:r})}catch{}};if(n.headers.host!==`${u}:${n.socket.localPort}`){t("host_mismatch"),e.writeHead(403).end();return}let c=n.headers.origin;if(c!==void 0&&!o.allowedOrigins.includes(c)){t("origin_denied"),e.writeHead(403).end();return}let i=c?{"Access-Control-Allow-Origin":c,Vary:"Origin","Access-Control-Expose-Headers":"Content-Range, Content-Length"}:{};if(n.method==="OPTIONS"){let s={...i,"Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Headers":"range","Access-Control-Max-Age":"86400"};n.headers["access-control-request-private-network"]==="true"&&(s["Access-Control-Allow-Private-Network"]="true"),e.writeHead(204,s).end();return}if(n.method!=="GET"&&n.method!=="HEAD"){e.writeHead(405,i).end();return}let v;try{let s=new URL(n.url??"/",`http://${u}`).pathname.split("/");if(s.length!==3||s[1]!==a){t("bad_token"),e.writeHead(404,i).end();return}v=decodeURIComponent(s[2])}catch{t("not_found"),e.writeHead(404,i).end();return}let g=o.packs.get(v);if(!g){t("not_found"),e.writeHead(404,i).end();return}let d;try{let s=await S.stat(g);if(!s.isFile())throw new Error("not a file");d=s.size}catch{t("not_found"),e.writeHead(404,i).end();return}let h={...i,"Accept-Ranges":"bytes","Content-Type":"application/zip","Cache-Control":"no-store"};if(n.method==="HEAD"){e.writeHead(200,{...h,"Content-Length":String(d)}).end();return}let l=A(n.headers.range,d);if(l==="unsatisfiable"){t("unsatisfiable"),e.writeHead(416,{...i,"Content-Range":`bytes */${d}`}).end();return}let[m,p,w]=l===null?[0,d-1,200]:[l.start,l.end,206],E={...h,"Content-Length":String(p-m+1)};if(w===206&&(E["Content-Range"]=`bytes ${m}-${p}/${d}`),e.writeHead(w,E),d===0){e.end();return}let f=C(g,{start:m,end:p});f.on("error",()=>e.destroy()),e.on("close",()=>f.destroy()),f.pipe(e)}function O(n,e){return(e??y(n).evidenceViewerUrl).replace(/\/+$/,"")}function k(n,e){return`${e}/?pack=${encodeURIComponent(n)}`}function P(n){return`evidence: view locally with \`kane-cli evidence serve ${n}\``}export{A as a,I as b,O as c,k as d,P as e};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as b}from"./chunk-7RAIRUXO.js";import{m as d,x as o}from"./chunk-DWHXXPDX.js";import{a as L}from"./chunk-HCBYKLMW.js";import{a as u,b as c,i as A}from"./chunk-C44QQJR4.js";import{a as D}from"./chunk-6YGTRKDT.js";import{e as h}from"./chunk-UR6MHSHU.js";var x=h(D(),1);import{readdirSync as N,mkdirSync as B,statSync as k}from"fs";import{join as P}from"path";var r=h(L(),1);function O(n){try{return N(n).filter(l=>{try{return k(P(n,l)).isDirectory()}catch{return!1}})}catch{return[]}}function E(n,l,f,v){return{name:n,path:l,label:n,isActive:v}}function H({currentPath:n,onSelect:l,onCancel:f}){let s=O(d).map(i=>{let e=P(d,i);return E(i,e,n,e===n)}),p=!n,R=s.length+2,[a,C]=(0,x.useState)(()=>{if(p)return 0;let i=s.findIndex(e=>e.isActive);return i>=0?i+1:0}),[T,I]=(0,x.useState)(!1),[S,g]=(0,x.useState)("");return A((i,e)=>{if(T){if(e.escape){I(!1),g("");return}if(e.return){let t=S.trim();if(t){let m=P(d,t);B(m,{recursive:!0}),l(m),f()}return}if(e.backspace||e.delete){g(t=>t.slice(0,-1));return}i&&!e.ctrl&&!e.meta&&g(t=>t+i);return}if(e.escape){f();return}if(e.upArrow){C(t=>Math.max(0,t-1));return}if(e.downArrow){C(t=>Math.min(R-1,t+1));return}if(e.return){if(a===0){p||l(""),f();return}if(a===s.length+1){B(d,{recursive:!0}),I(!0),g("");return}let t=s[a-1];t&&!t.isActive&&l(t.path),f();return}}),T?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile \u203A New"}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(c,{color:o.secondary,children:"Name: "}),(0,r.jsx)(c,{children:S}),(0,r.jsx)(c,{color:o.dim,children:"\u2588"})]}),(0,r.jsx)(b,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:"back"})]}):(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile"}),(0,r.jsxs)(u,{flexDirection:"column",marginTop:1,children:[(0,r.jsxs)(c,{color:p?o.green:a===0?o.orange:o.dim,children:[a===0?"\u276F ":" ","Use temporary (no profile)",p?" \u25CF active":""]}),s.map((i,e)=>{let m=e+1===a,w=m?"\u276F ":" ",y=i.isActive?o.green:m?o.orange:void 0;return(0,r.jsxs)(c,{color:y,children:[w,i.label,i.isActive?" \u25CF active":""]},i.name)}),(0,r.jsxs)(c,{color:a===s.length+1?o.orange:o.dim,children:[a===s.length+1?"\u276F ":" ","+ Create new"]})]}),(0,r.jsx)(b,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}export{O as a,E as b,H as c};
2
+ import{a as b}from"./chunk-KUAFVRSR.js";import{m as d,x as o}from"./chunk-WEJA3EVI.js";import{a as L}from"./chunk-HCBYKLMW.js";import{a as u,b as c,i as A}from"./chunk-C44QQJR4.js";import{a as D}from"./chunk-6YGTRKDT.js";import{e as h}from"./chunk-UR6MHSHU.js";var x=h(D(),1);import{readdirSync as N,mkdirSync as B,statSync as k}from"fs";import{join as P}from"path";var r=h(L(),1);function O(n){try{return N(n).filter(l=>{try{return k(P(n,l)).isDirectory()}catch{return!1}})}catch{return[]}}function E(n,l,f,v){return{name:n,path:l,label:n,isActive:v}}function H({currentPath:n,onSelect:l,onCancel:f}){let s=O(d).map(i=>{let e=P(d,i);return E(i,e,n,e===n)}),p=!n,R=s.length+2,[a,C]=(0,x.useState)(()=>{if(p)return 0;let i=s.findIndex(e=>e.isActive);return i>=0?i+1:0}),[T,I]=(0,x.useState)(!1),[S,g]=(0,x.useState)("");return A((i,e)=>{if(T){if(e.escape){I(!1),g("");return}if(e.return){let t=S.trim();if(t){let m=P(d,t);B(m,{recursive:!0}),l(m),f()}return}if(e.backspace||e.delete){g(t=>t.slice(0,-1));return}i&&!e.ctrl&&!e.meta&&g(t=>t+i);return}if(e.escape){f();return}if(e.upArrow){C(t=>Math.max(0,t-1));return}if(e.downArrow){C(t=>Math.min(R-1,t+1));return}if(e.return){if(a===0){p||l(""),f();return}if(a===s.length+1){B(d,{recursive:!0}),I(!0),g("");return}let t=s[a-1];t&&!t.isActive&&l(t.path),f();return}}),T?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile \u203A New"}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(c,{color:o.secondary,children:"Name: "}),(0,r.jsx)(c,{children:S}),(0,r.jsx)(c,{color:o.dim,children:"\u2588"})]}),(0,r.jsx)(b,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:"back"})]}):(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile"}),(0,r.jsxs)(u,{flexDirection:"column",marginTop:1,children:[(0,r.jsxs)(c,{color:p?o.green:a===0?o.orange:o.dim,children:[a===0?"\u276F ":" ","Use temporary (no profile)",p?" \u25CF active":""]}),s.map((i,e)=>{let m=e+1===a,w=m?"\u276F ":" ",y=i.isActive?o.green:m?o.orange:void 0;return(0,r.jsxs)(c,{color:y,children:[w,i.label,i.isActive?" \u25CF active":""]},i.name)}),(0,r.jsxs)(c,{color:a===s.length+1?o.orange:o.dim,children:[a===s.length+1?"\u276F ":" ","+ Create new"]})]}),(0,r.jsx)(b,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}export{O as a,E as b,H as c};
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as p,c as j,d as M,e as y,f as C,g as A,i as D,l as F,o as T,q as $,r as O}from"./chunk-WHEWZR2C.js";import{c as H,d as z}from"./chunk-2YQ6TW77.js";import{a as E}from"./chunk-IPEA7ZOF.js";import{a as k}from"./chunk-NTEI2O3O.js";import{r as B,s as R}from"./chunk-RSSOJ3L2.js";import{a as P}from"./chunk-DWHXXPDX.js";import{e as q}from"./chunk-UR6MHSHU.js";import{existsSync as f,mkdirSync as V,readFileSync as Z,renameSync as N,writeFileSync as K}from"fs";import{join as Q}from"path";function fe(e){F(p(e));let t=p(e);if(!f(t))return;let n=Q(t,"meta.json"),r=y(e);if(f(n)&&!f(r))try{V(M(e),{recursive:!0}),N(n,r)}catch(o){process.stderr.write(`warn: meta.json migration failed: ${o.message}
2
+ import{b as p,c as j,d as M,e as y,f as C,g as A,i as D,l as F,o as T,q as $,r as O}from"./chunk-WHEWZR2C.js";import{a as H,b as z}from"./chunk-M6SFFAAQ.js";import{a as E}from"./chunk-IPEA7ZOF.js";import{a as k}from"./chunk-2ULZVQZV.js";import{r as B,s as R}from"./chunk-RSSOJ3L2.js";import{a as P}from"./chunk-WEJA3EVI.js";import{e as q}from"./chunk-UR6MHSHU.js";import{existsSync as f,mkdirSync as V,readFileSync as Z,renameSync as N,writeFileSync as K}from"fs";import{join as Q}from"path";function fe(e){F(p(e));let t=p(e);if(!f(t))return;let n=Q(t,"meta.json"),r=y(e);if(f(n)&&!f(r))try{V(M(e),{recursive:!0}),N(n,r)}catch(o){process.stderr.write(`warn: meta.json migration failed: ${o.message}
3
3
  `)}let i=A(e);if(f(i)){let o="python";try{let c=new k().load();c.code_export?.language&&(o=c.code_export.language)}catch{}let a=C(e,"playwright",o);if(!f(a))try{N(i,a)}catch(c){process.stderr.write(`warn: generated-code migration failed: ${c.message}
4
4
  `)}}if(f(r))try{let o=JSON.parse(Z(r,"utf8"));"md5sum"in o&&(delete o.md5sum,K(r,JSON.stringify(o,null,2)+`
5
5
  `,"utf8"))}catch(o){process.stderr.write(`warn: meta.json md5sum strip failed: ${o.message}
6
- `)}}async function ye(e){if(!e.isInteractive)return{recovered:!1};if(W(e.creds))return{recovered:!1};let{SingleShotApp:t}=await import("./SingleShotApp-ECA24PKW.js"),{ScrollbackProvider:n}=await import("./scrollback-JLPJR25X.js"),{render:r}=await import("./build-JIKYOZUH.js"),i=await import("./react-QWOAB3TB.js"),o={current:null},a={current:!1},{waitUntilExit:c,unmount:l}=r(i.default.createElement(n,null,i.default.createElement(t,{resultRef:o,mode:"login",loginCompleteRef:a})),{exitOnCtrlC:!1});R(()=>l()),await c();try{process.stdin.setRawMode?.(!1)}catch{}return process.stdout.write("\x1B[?25h"),a.current?{recovered:!0}:(B(0,"Startup gate cancelled"),{recovered:!1})}function W(e){let t=e.getActiveProfile(),n=e.getDefaultEnv();if(!t||!!!(e.loadBasicAuth(t,n)||e.loadCredentials(t,n)))return!1;let i=e.loadProfileConfig(t,n)??{};return!!i.project_id&&!!i.folder_id}var J=q(H(),1);import{existsSync as v,readFileSync as U,readdirSync as X,statSync as Y}from"fs";import{dirname as ee,isAbsolute as te,join as g,relative as x,resolve as re,sep as h}from"path";import{createHash as ne}from"crypto";var S="testmd-bundle.json",d=class extends Error{constructor(t){super(t),this.name="BundleUsageError"}},_=e=>e.split(h).join("/");function I(e){if(!v(e))return[];let t=[];for(let n of X(e).sort()){let r=g(e,n);Y(r).isDirectory()?t.push(...I(r)):t.push(r)}return t}function se(e){let t=e.map(r=>ee(r).split(h)),n=t[0];for(let r of t.slice(1)){let i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;n=n.slice(0,i)}return n.join(h)||h}function ie(e){for(let t of e){let n=E(t,U(t,"utf8"));for(let r of n.steps)if(r.body.kind==="import_ref"&&te(r.body.path))throw new d(`bundle sync: absolute @import is not portable after unzip: ${t} step ${r.index} (@import ${r.body.path})`)}}function G(e){let t=re(e),n=T(t);if(!n?.commit_id||!n?.test_id)throw new d(`bundle sync: ${t} is not authored \u2014 run \`kane-cli testmd run\` first (output-<stem>/.internal/meta.json needs commit_id + test_id)`);let r;try{r=O(t)}catch(s){throw s instanceof $?new d(`bundle sync: ${s.message}`):s}let i=[t];for(let s of r.steps)for(let u of s.trace.slice(1))i.includes(u.file)||i.push(u.file);ie(i);let o=[];for(let s of r.unitFiles){if(s.file===t)continue;let u=p(s.file);o.includes(u)||o.push(u)}let a=[...i],c=s=>{v(s)&&a.push(s)};c(j(t)),a.push(y(t)),c(g(p(t),".internal","execution.json")),a.push(...I(D(t)));for(let s of o)c(g(s,"Result.md")),a.push(...I(g(s,".internal","steps")));let l=se(a);if(v(g(l,S)))throw new d(`bundle sync: a real file named ${S} exists at the zip root (${l}) \u2014 it would collide with the generated manifest`);let b=a.map(s=>{let u=U(s);return{abs:s,rel:_(x(l,s)),sha256:ne("sha256").update(u).digest("hex"),bytes:u.length}}).sort((s,u)=>s.rel<u.rel?-1:1),m=_(x(l,t)),L={schema_version:2,entry:m,commit_id:n.commit_id,test_id:n.test_id,testcase_id:n.testcase_id??null,project_id:n.project_id??null,folder_id:n.folder_id??null,org_id:n.org_id??null,created_at:new Date().toISOString(),producer:{name:"kane-cli",version:P},files:b.map(s=>({path:s.rel,sha256:s.sha256,bytes:s.bytes})),units:r.unitFiles.filter(s=>s.file!==t).map(s=>({path:_(x(l,s.file)),kind:s.kind}))};return{zipRoot:l,entry:m,files:b,manifest:L}}var w=e=>e instanceof Error?e.message:String(e);function oe(e){return new Promise((t,n)=>{let r=(0,J.default)("zip",{zlib:{level:6}}),i=[];r.on("data",o=>i.push(o)),r.on("error",n),r.on("end",()=>t(Buffer.concat(i))),r.append(JSON.stringify(e.manifest,null,2)+`
6
+ `)}}async function ye(e){if(!e.isInteractive)return{recovered:!1};if(W(e.creds))return{recovered:!1};let{SingleShotApp:t}=await import("./SingleShotApp-WBFVUZFP.js"),{ScrollbackProvider:n}=await import("./scrollback-JLPJR25X.js"),{render:r}=await import("./build-JIKYOZUH.js"),i=await import("./react-QWOAB3TB.js"),o={current:null},a={current:!1},{waitUntilExit:c,unmount:l}=r(i.default.createElement(n,null,i.default.createElement(t,{resultRef:o,mode:"login",loginCompleteRef:a})),{exitOnCtrlC:!1});R(()=>l()),await c();try{process.stdin.setRawMode?.(!1)}catch{}return process.stdout.write("\x1B[?25h"),a.current?{recovered:!0}:(B(0,"Startup gate cancelled"),{recovered:!1})}function W(e){let t=e.getActiveProfile(),n=e.getDefaultEnv();if(!t||!!!(e.loadBasicAuth(t,n)||e.loadCredentials(t,n)))return!1;let i=e.loadProfileConfig(t,n)??{};return!!i.project_id&&!!i.folder_id}var J=q(H(),1);import{existsSync as v,readFileSync as U,readdirSync as X,statSync as Y}from"fs";import{dirname as ee,isAbsolute as te,join as g,relative as x,resolve as re,sep as h}from"path";import{createHash as ne}from"crypto";var S="testmd-bundle.json",d=class extends Error{constructor(t){super(t),this.name="BundleUsageError"}},_=e=>e.split(h).join("/");function I(e){if(!v(e))return[];let t=[];for(let n of X(e).sort()){let r=g(e,n);Y(r).isDirectory()?t.push(...I(r)):t.push(r)}return t}function se(e){let t=e.map(r=>ee(r).split(h)),n=t[0];for(let r of t.slice(1)){let i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;n=n.slice(0,i)}return n.join(h)||h}function ie(e){for(let t of e){let n=E(t,U(t,"utf8"));for(let r of n.steps)if(r.body.kind==="import_ref"&&te(r.body.path))throw new d(`bundle sync: absolute @import is not portable after unzip: ${t} step ${r.index} (@import ${r.body.path})`)}}function G(e){let t=re(e),n=T(t);if(!n?.commit_id||!n?.test_id)throw new d(`bundle sync: ${t} is not authored \u2014 run \`kane-cli testmd run\` first (output-<stem>/.internal/meta.json needs commit_id + test_id)`);let r;try{r=O(t)}catch(s){throw s instanceof $?new d(`bundle sync: ${s.message}`):s}let i=[t];for(let s of r.steps)for(let u of s.trace.slice(1))i.includes(u.file)||i.push(u.file);ie(i);let o=[];for(let s of r.unitFiles){if(s.file===t)continue;let u=p(s.file);o.includes(u)||o.push(u)}let a=[...i],c=s=>{v(s)&&a.push(s)};c(j(t)),a.push(y(t)),c(g(p(t),".internal","execution.json")),a.push(...I(D(t)));for(let s of o)c(g(s,"Result.md")),a.push(...I(g(s,".internal","steps")));let l=se(a);if(v(g(l,S)))throw new d(`bundle sync: a real file named ${S} exists at the zip root (${l}) \u2014 it would collide with the generated manifest`);let b=a.map(s=>{let u=U(s);return{abs:s,rel:_(x(l,s)),sha256:ne("sha256").update(u).digest("hex"),bytes:u.length}}).sort((s,u)=>s.rel<u.rel?-1:1),m=_(x(l,t)),L={schema_version:2,entry:m,commit_id:n.commit_id,test_id:n.test_id,testcase_id:n.testcase_id??null,project_id:n.project_id??null,folder_id:n.folder_id??null,org_id:n.org_id??null,created_at:new Date().toISOString(),producer:{name:"kane-cli",version:P},files:b.map(s=>({path:s.rel,sha256:s.sha256,bytes:s.bytes})),units:r.unitFiles.filter(s=>s.file!==t).map(s=>({path:_(x(l,s.file)),kind:s.kind}))};return{zipRoot:l,entry:m,files:b,manifest:L}}var w=e=>e instanceof Error?e.message:String(e);function oe(e){return new Promise((t,n)=>{let r=(0,J.default)("zip",{zlib:{level:6}}),i=[];r.on("data",o=>i.push(o)),r.on("error",n),r.on("end",()=>t(Buffer.concat(i))),r.append(JSON.stringify(e.manifest,null,2)+`
7
7
  `,{name:S});for(let o of e.files)r.file(o.abs,{name:o.rel});r.finalize()})}async function ae(e){let{plan:t,controller:n,testId:r,sessionId:i,commitId:o}=e,a;try{a=await oe(t)}catch(l){return{ok:!1,stage:"zip",error:w(l)}}let c;try{let l={key:"testmd",content_type:"application/zip",filename:`${o}-testmd.zip`},m=(await n.getPresignedUrls(r,i,[l])).urls?.testmd?.upload_url;if(!m)return{ok:!1,stage:"presign",error:"presign response missing testmd upload_url"};c=m}catch(l){return{ok:!1,stage:"presign",error:w(l)}}try{await z(c,a,"application/zip")}catch(l){return{ok:!1,stage:"upload",error:w(l)}}return{ok:!0,bytes:a.length}}async function Ee(e){let t;try{t=G(e.sourcePath)}catch(n){return n instanceof d?{ok:!1,stage:"collect",error:n.message}:{ok:!1,stage:"collect",error:w(n)}}return ae({...e,plan:t})}function je(e){return e.shouldUploadPipeline&&e.uploadSucceeded&&!!e.metaCommitId&&!!e.metaTestId}export{fe as a,ye as b,G as c,Ee as d,je as e};