@inkly-org/cli 0.6.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/capture-listener.js +33 -21
- package/dist/cli.js +378 -233
- package/dist/skills/inkly/SKILL.md +133 -0
- package/package.json +4 -1
- package/skills/inkly/SKILL.md +133 -0
package/dist/capture-listener.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,{encoding:"utf8",mode:384})}async function
|
|
2
|
+
import An from"mri";import{spawn as Vt,execFile as rr}from"child_process";import{createHash as sr,randomUUID as or}from"crypto";import{mkdir as Y,mkdtemp as lr,open as cr,readFile as Q,readdir as ur,rm as qt,writeFile as W}from"fs/promises";import{existsSync as Ue}from"fs";import{dirname as Oe,isAbsolute as fr,join as x,resolve as zt,sep as mr}from"path";import{tmpdir as gr,homedir as Gt}from"os";import{fileURLToPath as Kt}from"url";import{unzipSync as br,zipSync as vr}from"fflate";import Jt from"ws";import Pr from"sharp";import Ar from"subset-font";import{zipSync as Tn}from"fflate";import{JSDOM as Tr}from"jsdom";import{randomUUID as Xe}from"crypto";import{mkdir as Ye,readFile as Qe,writeFile as et}from"fs/promises";import{dirname as tt,join as nt}from"path";import{homedir as rt}from"os";import{PostHog as it}from"posthog-node";var we=process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN??process.env.POSTHOG_PROJECT_TOKEN??"phc_Dmh4w8YFNosi3YHD4Sv7ShHX7ccS8kmtRcm8XSVmB5jT",st=process.env.NEXT_PUBLIC_POSTHOG_HOST??process.env.POSTHOG_HOST??"https://us.i.posthog.com",ot="@inkly-org/cli@0.5.1",se=nt(rt(),".inkly","analytics.json"),ge=null,z=null,ye=null;function at(){return!!we&&process.env.INKLY_TELEMETRY_DISABLED!=="1"}function lt(){return at()?(ge??=new it(we,{host:st,flushAt:1,flushInterval:0}),ge):null}async function ct(){try{let e=await Qe(se,"utf8");return JSON.parse(e)}catch{return{}}}async function ut(e){await Ye(tt(se),{recursive:!0}),await et(se,JSON.stringify(e,null,2)+`
|
|
3
|
+
`,{encoding:"utf8",mode:384})}async function dt(){return z||(z=(async()=>{let e=await ct();if(typeof e.platformUserId=="string"&&e.platformUserId&&(ye=e.platformUserId),typeof e.distinctId=="string"&&e.distinctId)return e.distinctId;let t=`cli_${Xe()}`;return await ut({...e,distinctId:t}),t})(),z)}async function pt(){let e=await dt();return ye??e}function ft(){return{surface:"cli",release:process.env.POSTHOG_RELEASE??ot,node_version:process.versions.node,platform:process.platform,arch:process.arch,ci:!!process.env.CI}}async function be(e,t={}){let n=lt();if(n)try{n.capture({distinctId:await pt(),event:e,properties:{...ft(),...t}})}catch{}}import{mkdir as mt,rename as ht,writeFile as gt}from"fs/promises";import{dirname as wt}from"path";async function ve(e,t,n){await mt(wt(e),{recursive:!0});let r=`${e}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await gt(r,t,n?.mode!=null?{mode:n.mode}:void 0),await ht(r,e)}import{Stagehand as Dt}from"@browserbasehq/stagehand";import{NodeHtmlMarkdown as Nt}from"node-html-markdown";function ke(){return{urlMap:{},xpathMap:{}}}function yt(e){if(e.startsWith("@")){let t=e.slice(1);return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}return e.startsWith("[")&&e.endsWith("]")&&/^\[\d+-\d+]$/.test(e)?e.slice(1,-1):e.startsWith("ref=")?e.slice(4):/^\d+-\d+$/.test(e)?e:null}function M(e,t){let n=yt(e);if(!n)return e;let r=t.xpathMap[n];if(!r)throw new Error(`Unknown ref "${n}" - run \`inkly capture nav snapshot\` first to populate refs (have ${Object.keys(t.xpathMap).length} refs).`);return r}function oe(e,t={}){let n=e.split(`
|
|
4
|
+
`);return t.maxDepth!==void 0&&(n=n.filter(r=>j(r)<=t.maxDepth)),t.filter&&(n=kt(n,t.filter)),t.trim?n=Rt(n):t.compact&&(n=Ce(n)),(t.trim||t.compact)&&(n=vt(n)),n.join(`
|
|
5
|
+
`).trim()}function Se(e){let t=e.match(/^\s*(?:\[[\w-]+]\s*)?([A-Za-z]+)/);return t?t[1].toLowerCase():null}function bt(e){let t=e.match(/^\s*(?:\[[\w-]+]\s*)?[A-Za-z]+(?:,[^:]*)?:\s*(.*)$/);return t?t[1].trim():""}function vt(e){let r=[],i=0;for(;i<e.length;){let s=j(e[i]),o=Se(e[i]),u=i+1;if(o)for(;u<e.length&&j(e[u])===s&&Se(e[u])===o;)u+=1;let d=u-i,g=new Set;for(let c=i;c<u;c+=1)g.add(bt(e[c]));let b=g.size<=d/2;if(o&&d>=14&&b){for(let w=i;w<i+6;w+=1)r.push(e[w]);let c=" ".repeat(s*2);r.push(`${c}\u2026 (+${d-6} more ${o}, repeated)`),i=u}else r.push(e[i]),i+=1}return r}function kt(e,t){let n=St(t);return ae(e,n)}function ae(e,t){let n=new Set;for(let r=0;r<e.length;r+=1){if(!t(e[r]??""))continue;n.add(r);let i=j(e[r]??"");for(let s=r-1;s>=0;s-=1){let o=j(e[s]??"");if(o<i&&(n.add(s),i=o,o===0))break}}return e.filter((r,i)=>n.has(i))}function St(e){let t=Pt(e);if(t)return r=>t.test(r);let n=e.toLowerCase();return r=>r.toLowerCase().includes(n)}function Pt(e){let t=e.match(/^\/(.+)\/([a-z]*)$/i);if(!t)return null;try{return new RegExp(t[1]??"",t[2]??"")}catch{return null}}function Ce(e){let t=ae(e,Ct);return t.length>0?t:e}function Ct(e){return/\[\d+-\d+]/.test(e)||e.includes(": ")||/\b(button|link|textbox|checkbox|radio|combobox)\b/i.test(e)}var At=["button","link","textbox","searchbox","checkbox","radio","combobox","listbox","option","switch","slider","spinbutton","tab","menuitem","menuitemcheckbox","menuitemradio","treeitem"],xt=["navigation","main","banner","contentinfo","complementary","search","form","dialog","alertdialog","menu","menubar","tablist","region"],B="^\\s*(?:\\[[\\w-]+]\\s*)?",_t=new RegExp(`${B}(?:${At.join("|")})\\b`,"i"),Et=new RegExp(`${B}(?:${xt.join("|")})\\b`,"i"),Tt=new RegExp(`${B}heading\\b`,"i"),Mt=new RegExp(`${B}StaticText\\b`,"i");function Pe(e){return Mt.test(e)?!1:_t.test(e)||Tt.test(e)||Et.test(e)}var It=new RegExp(`${B}[\\w-]+(?:,[^:]*)?:\\s`,"i");function Lt(e){return It.test(e)}function Rt(e){let n=ae(e,Pe).filter(r=>Pe(r)||Lt(r));return n.length>0?n:Ce(e)}function j(e){let t=e.match(/^\s*/);return Math.floor((t?.[0].length??0)/2)}var $t={trim:!0},G=90,Ut=110,_e=1600,Ae=2600,Ot=1800,xe={width:1440,height:900},K=class{constructor(t,n){this.browserWsUrl=t;this.targetId=n;this.stagehand=null;this.context=null;this.refMaps=ke()}async init(){if(this.stagehand)return;let t=new Dt({disablePino:!0,env:"LOCAL",localBrowserLaunchOptions:{cdpUrl:this.browserWsUrl},verbose:0});try{await t.init()}catch(n){throw await t.close().catch(()=>{}),n}this.stagehand=t,this.context=t.context,this.selectRecorderPage()}selectRecorderPage(){if(!this.context)throw new Error("nav driver not initialized");let t=this.context.pages(),r=t.find(i=>{try{return i.targetId()===this.targetId}catch{return!1}})??this.activePageIfPresent()??t[0];if(!r)throw new Error("nav driver found no page in the attached browser");return this.context.setActivePage(r),r}activePageIfPresent(){try{return this.context?.activePage()??void 0}catch{return}}activePage(){return this.selectRecorderPage()}async snapshot(t){let n=this.activePage(),r=await n.snapshot();this.refMaps={urlMap:r.urlMap??{},xpathMap:r.xpathMap??{}};let i=oe(r.formattedTree,t);return t.includeMaps?{tree:i,url:n.url(),urlMap:r.urlMap,xpathMap:r.xpathMap}:{tree:i,url:n.url()}}async agentSnapshot(){let t=this.activePage(),n=await t.snapshot();return this.refMaps={urlMap:n.urlMap??{},xpathMap:n.xpathMap??{}},{tree:oe(n.formattedTree,$t),url:t.url()}}url(){return this.activePage().url()}resolveRef(t){return M(t,this.refMaps)}async click(t){if(!this.stagehand)throw new Error("nav driver not initialized");this.activePage();let n=M(t,this.refMaps);return await this.stagehand.act({arguments:[],description:"click element",method:"click",selector:n}),{clicked:!0,selector:n}}async fill(t,n,r){if(!this.stagehand)throw new Error("nav driver not initialized");let i=this.activePage(),s=M(t,this.refMaps);return await this.stagehand.act({arguments:[n],description:"fill element",method:"fill",selector:s}),r&&await i.keyPress("Enter"),{filled:!0,pressedEnter:r,selector:s}}async type(t,n){return await this.activePage().type(t,{delay:n}),{typed:!0}}async key(t){return await this.activePage().keyPress(t),{pressed:t}}async select(t,n){let r=this.activePage(),i=M(t,this.refMaps);return{selected:await r.deepLocator(i).selectOption(n),selector:i}}async upload(t,n){let r=this.activePage(),i=M(t,this.refMaps);return await r.deepLocator(i).setInputFiles(n.length===1?n[0]:n),{uploaded:!0,files:n,selector:i}}async get(t,n){let r=this.activePage();if(t==="url")return{url:r.url()};if(t==="title")return{title:await r.title()};let i=M(n??"body",this.refMaps),s=r.deepLocator(i);if(t==="text")return{text:await s.textContent()};if(t==="html")return{html:await s.innerHtml()};if(t==="value")return{value:await s.inputValue()};if(t==="visible")return{visible:await s.isVisible()};if(t==="checked")return{checked:await s.isChecked()};if(t==="markdown")return{markdown:Nt.translate(await s.innerHtml())};if(t==="box"){let{x:o,y:u}=await s.centroid();return{x:Math.round(o),y:Math.round(u)}}throw new Error(`unknown get target "${t}" \u2014 expected url|title|text|html|value|visible|checked|markdown|box`)}async is(t,n){let i=this.activePage().deepLocator(M(n,this.refMaps));if(t==="visible")return{visible:await i.isVisible()};if(t==="checked")return{checked:await i.isChecked()};throw new Error(`unknown is check "${t}" \u2014 expected visible|checked`)}async wait(t){let n=this.activePage();if(t.type==="load")await n.waitForLoadState(t.arg??"load",t.timeoutMs);else if(t.type==="selector"){if(!t.arg)throw new Error("nav wait selector requires a <selector> argument");await n.waitForSelector(M(t.arg,this.refMaps),{state:t.state??"visible",timeout:t.timeoutMs??3e4})}else if(t.type==="timeout"){let r=Number(t.arg);if(!Number.isInteger(r)||r<0)throw new Error("nav wait timeout requires a non-negative integer <ms>");await n.waitForTimeout(r)}else throw new Error(`unknown wait type "${t.type}" \u2014 expected load|selector|timeout`);return{waited:!0}}async back(t){let n=this.activePage();return await n.goBack(t),{navigated:!0,url:n.url()}}async forward(t){let n=this.activePage();return await n.goForward(t),{navigated:!0,url:n.url()}}async reload(t){let n=this.activePage();return await n.reload(t),{reloaded:!0,url:n.url()}}refs(){return{count:Object.keys(this.refMaps.xpathMap).length,urlMap:this.refMaps.urlMap,xpathMap:this.refMaps.xpathMap}}async mouseClick(t,n,r={}){return await this.activePage().click(t,n,r),{clicked:!0}}async mouseHover(t,n){return await this.activePage().hover(t,n),{hovered:!0}}async mouseScroll(t,n,r,i){return await this.activePage().scroll(t,n,r,i),{scrolled:!0}}async scroll(t,n){let r=this.activePage(),i=Math.round(xe.width/2),s=Math.round(xe.height/2),o=Math.max(G,Math.round(Math.abs(n))),u=t==="up"?-1:1,d=Math.ceil(o/G),g=Math.max(1,d-1),b=Math.min(Math.round(Ae/g),Math.max(Ut,Math.round(Ot/g))),c=Date.now(),w=o;for(let v=0;v<d&&!(Date.now()-c>Ae);v+=1){let S=Math.min(G,w)*u;w-=G,await r.scroll(i,s,0,S),v<d-1&&await new Promise(C=>setTimeout(C,b))}return{scrolled:!0,direction:t,amount:o}}async close(){let t=this.stagehand;this.stagehand=null,this.context=null,t&&await t.close().catch(()=>{})}};import Ft from"net";import Ht from"readline";import{rm as Ee}from"fs/promises";import{join as le}from"path";import{homedir as jt}from"os";function Bt(){return le(process.env.INKLY_CAPTURE_AGENT_HOME||le(jt(),".inkly"),"capture-agent","sessions")}function Me(e){if(!/^[a-zA-Z0-9._:-]+$/.test(e))throw new Error(`invalid session id: ${e}`);return le(Bt(),`${e}.nav.sock`)}async function Ie(e,t){let n=Ft.createServer(r=>{let i=Ht.createInterface({input:r});r.once("error",()=>{i.close(),r.destroy()}),i.once("line",s=>{Wt(s,t).then(o=>Te(r,o)).catch(o=>Te(r,{type:"error",error:o instanceof Error?o.message:String(o)})).finally(()=>{i.close(),r.end()})})});return await Ee(e,{force:!0}).catch(()=>{}),await new Promise((r,i)=>{let s=o=>i(o);n.once("error",s),n.listen(e,()=>{n.off("error",s),r()})}),{close(){return new Promise(r=>{n.close(()=>{Ee(e,{force:!0}).catch(()=>{}).finally(()=>r())})})}}}async function Wt(e,t){let n;try{n=JSON.parse(e)}catch(r){return{type:"error",error:r instanceof Error?r.message:String(r)}}if(n.type!=="command"||typeof n.command!="string")return{id:n.id,type:"error",error:"invalid nav request"};try{let r=await t(n);return{id:n.id,type:"success",data:r}}catch(r){return{id:n.id,type:"error",error:r instanceof Error?r.message:String(r)}}}function Te(e,t){e.write(`${JSON.stringify(t)}
|
|
6
|
+
`)}var Fe=`Options:
|
|
4
7
|
--url <url> URL to open and arm for recording.
|
|
5
8
|
--name <name> Demo name written into the exported ZIP.
|
|
6
9
|
--session <id> Session id printed by start.
|
|
@@ -20,7 +23,7 @@ import vt from"mri";import{spawn as Ke,execFile as Ot}from"child_process";import
|
|
|
20
23
|
done once in this profile survives, so later captures of the same site need
|
|
21
24
|
no re-login. Implies --keep-profile. Run --headed the first time so the user
|
|
22
25
|
can sign in; reuse can run headless.
|
|
23
|
-
--no-unpack On stop, write only the ZIP.`,
|
|
26
|
+
--no-unpack On stop, write only the ZIP.`,Zt=`inkly capture - capture an image/video walkthrough for an external browser agent
|
|
24
27
|
|
|
25
28
|
Usage:
|
|
26
29
|
inkly capture start --url <url> --name <name>
|
|
@@ -28,9 +31,10 @@ Usage:
|
|
|
28
31
|
inkly capture cancel --session <id>
|
|
29
32
|
inkly capture status --session <id>
|
|
30
33
|
inkly capture undo --session <id>
|
|
34
|
+
inkly capture nav <verb> --session <id> (snapshot|click|fill|type|press|select|upload|get|is|wait|back|forward|reload|refs|mouse)
|
|
31
35
|
inkly capture profiles
|
|
32
36
|
|
|
33
|
-
${
|
|
37
|
+
${Fe}
|
|
34
38
|
--video, --record-video Record motion segments. Enabled by default; use --no-video to disable.
|
|
35
39
|
--zoom Apply click zoom/pan to screenshot steps. Enabled by default; use --no-zoom to disable.
|
|
36
40
|
--compress-images Re-encode captured PNG/JPEG screenshots to WebP (smaller, near-lossless).
|
|
@@ -39,7 +43,7 @@ ${me}
|
|
|
39
43
|
Output:
|
|
40
44
|
Every subcommand prints JSON. This command does not accept prompts and does not plan or drive the page.
|
|
41
45
|
For self-contained HTML snapshot capture, use \`inkly capture-html\`.
|
|
42
|
-
`,
|
|
46
|
+
`,Dr=`inkly capture-html - capture a self-contained HTML walkthrough for an external browser agent
|
|
43
47
|
|
|
44
48
|
Usage:
|
|
45
49
|
inkly capture-html start --url <url> --name <name>
|
|
@@ -47,21 +51,22 @@ Usage:
|
|
|
47
51
|
inkly capture-html cancel --session <id>
|
|
48
52
|
inkly capture-html status --session <id>
|
|
49
53
|
inkly capture-html undo --session <id>
|
|
54
|
+
inkly capture-html nav <verb> --session <id> (snapshot|click|fill|type|press|select|upload|get|is|wait|back|forward|reload|refs|mouse)
|
|
50
55
|
inkly capture-html profiles
|
|
51
56
|
|
|
52
|
-
${
|
|
57
|
+
${Fe}
|
|
53
58
|
--block-videos Replace <video> with its poster frame instead of inlining the video.
|
|
54
59
|
|
|
55
60
|
Output:
|
|
56
61
|
Every subcommand prints JSON. This command does not accept prompts and does not plan or drive the page.
|
|
57
|
-
`,
|
|
62
|
+
`,Le=Oe(Kt(import.meta.url));var He=1440,je=900;var Be=3e4,Xt=30,J=720,Yt=3e4,Qt=350,en=10,tn=1200,nn=1500,rn=1e3,sn=720,We=60,on=Math.round(sn/We);function N(e){return new Promise(t=>setTimeout(t,e))}function an(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))return;let n=e[t];return typeof n=="string"?n:""}function ln(e){return{click_tag:e?.tag??null,has_click_label:!!e?.label,has_click_selector:!!e?.selector,has_click_alpha_id:!!e?.alphaId}}async function Z(e){await be("inkly_cli_capture_step_captured",{runtime:e.session.runtime??"cli",capture_kind:e.session.cliCaptureKind??e.stepKind,step_kind:e.stepKind,action:e.action,step_count:e.session.cliScreens?.length??null,window_width:e.session.width,window_height:e.session.height,record_video:e.session.cliRecordVideo===!0,auto_apply_zoom:e.session.autoApplyZoom!==!1,...ln(e.click)})}function Re(e){let t=e.cliScreens??[],n=t[t.length-1]?.kind;return n==="video"||n==="html"?n:"image"}function cn(e,t,n){let r=an(e,t);if(!r)throw new Error(`missing --${t} <value>
|
|
58
63
|
|
|
59
|
-
${
|
|
64
|
+
${n}`);return r}function De(e,t){let n=zt(e);for(;;){let r=x(n,t);if(Ue(r))return r;let i=Oe(n);if(i===n)return null;n=i}}var U=class{constructor(t){this.nextId=1;this.pending=new Map;this.listeners=new Map;this.ws=new Jt(t,{perMessageDeflate:!1,maxPayload:512*1024*1024}),this.ready=new Promise((n,r)=>{this.ws.once("open",()=>n()),this.ws.once("error",i=>r(i))}),this.ws.on("message",n=>{let r=JSON.parse(n.toString());if(typeof r.id=="number"&&this.pending.has(r.id)){let s=this.pending.get(r.id);if(this.pending.delete(r.id),!s)return;r.error?s.reject(new Error(`${r.error.message??"CDP error"}: ${JSON.stringify(r.error.data??"")}`)):s.resolve(r.result??{});return}if(!r.method)return;let i=this.listeners.get(r.method);if(i)for(let s of i)s(r.params,r.sessionId)})}async send(t,n={},r){await this.ready;let i=this.nextId;this.nextId+=1;let s={id:i,method:t,params:n};return r&&(s.sessionId=r),new Promise((o,u)=>{this.pending.set(i,{resolve:o,reject:u}),this.ws.send(JSON.stringify(s),d=>{d&&(this.pending.delete(i),u(d))})})}on(t,n){let r=this.listeners.get(t)??new Set;return r.add(n),this.listeners.set(t,r),()=>r.delete(n)}close(){try{this.ws.close()}catch{}}};async function I(e,t,n,r=3e4){let i=await e.send("Runtime.evaluate",{expression:n,awaitPromise:!0,returnByValue:!0,timeout:r,userGesture:!0},t);if(i.exceptionDetails)throw new Error(`Runtime.evaluate failed: ${JSON.stringify(i.exceptionDetails)}`);return i.result?.value}async function ee(e,t){let r=(await e.send("Target.attachToTarget",{targetId:t,flatten:!0})).sessionId;if(typeof r!="string")throw new Error("Target.attachToTarget returned no sessionId");return r}async function Ne(e){return((await e.send("Target.getTargets",{filter:[{type:"page"}]})).targetInfos??[]).filter(r=>r.type==="page")}async function un(e,t){let n=await I(e,t,`JSON.stringify({
|
|
60
65
|
innerWidth: window.innerWidth,
|
|
61
66
|
innerHeight: window.innerHeight,
|
|
62
67
|
outerWidth: window.outerWidth,
|
|
63
68
|
outerHeight: window.outerHeight
|
|
64
|
-
})`,5e3),
|
|
69
|
+
})`,5e3),r=JSON.parse(String(n)),i={innerWidth:Number(r.innerWidth),innerHeight:Number(r.innerHeight),outerWidth:Number(r.outerWidth),outerHeight:Number(r.outerHeight)};if(!Number.isFinite(i.innerWidth)||!Number.isFinite(i.innerHeight)||!Number.isFinite(i.outerWidth)||!Number.isFinite(i.outerHeight))throw new Error(`could not measure Chrome viewport: ${JSON.stringify(r)}`);return i}async function te(e,t,n,r,i){try{let o=(await e.send("Browser.getWindowForTarget",{targetId:n})).windowId;if(typeof o!="number")throw new Error("Browser.getWindowForTarget returned no windowId");for(let u=0;u<4;u+=1){let d=await un(e,t),g=Math.max(0,d.outerWidth-d.innerWidth),b=Math.max(0,d.outerHeight-d.innerHeight),c=r+g,w=i+b;if(Math.abs(d.innerWidth-r)<=1&&Math.abs(d.innerHeight-i)<=1)return;await e.send("Browser.setWindowBounds",{windowId:o,bounds:{windowState:"normal",width:c,height:w}}),await N(250)}}catch{}await e.send("Emulation.setDeviceMetricsOverride",{width:r,height:i,deviceScaleFactor:1,mobile:!1},t).catch(()=>{}),await N(100)}function pe(e){if(e.length<24)return null;let t=[137,80,78,71,13,10,26,10];for(let o=0;o<t.length;o+=1)if(e[o]!==t[o])return null;if(String.fromCharCode(e[12],e[13],e[14],e[15])!=="IHDR")return null;let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=r.getUint32(16,!1),s=r.getUint32(20,!1);return i>0&&s>0?{width:i,height:s}:null}var ue=`(() => {
|
|
65
70
|
if (window.__inklyCliRecorderInstalled) return;
|
|
66
71
|
window.__inklyCliRecorderInstalled = true;
|
|
67
72
|
window.__inklyCliLastClick = null;
|
|
@@ -245,7 +250,7 @@ function selectorFor(el) {
|
|
|
245
250
|
window.addEventListener("scroll", onMotionScroll, true);
|
|
246
251
|
window.addEventListener("wheel", onMotionScroll, true);
|
|
247
252
|
window.addEventListener("touchmove", onMotionScroll, true);
|
|
248
|
-
})();`;async function
|
|
253
|
+
})();`;async function ne(e,t,n=!1){n&&(await e.send("Runtime.addBinding",{name:"__inklyCliCaptureEvent"},t).catch(()=>{}),await e.send("Runtime.addBinding",{name:"__inklyCliCaptureClick"},t).catch(()=>{})),await e.send("Page.addScriptToEvaluateOnNewDocument",{source:ue},t),await I(e,t,ue,5e3).catch(()=>{})}async function re(e,t){await I(e,t,ue,5e3).catch(()=>{});let n=await I(e,t,`JSON.stringify({
|
|
249
254
|
viewport: { width: window.innerWidth, height: window.innerHeight },
|
|
250
255
|
sourceUrl: location.href,
|
|
251
256
|
title: document.title || "Captured screen",
|
|
@@ -256,7 +261,7 @@ function selectorFor(el) {
|
|
|
256
261
|
maxX: Math.max(0, document.documentElement.scrollWidth - window.innerWidth),
|
|
257
262
|
maxY: Math.max(0, document.documentElement.scrollHeight - window.innerHeight)
|
|
258
263
|
}
|
|
259
|
-
})`,5e3),
|
|
264
|
+
})`,5e3),r=JSON.parse(String(n));return{viewport:{width:Number(r.viewport?.width)||He,height:Number(r.viewport?.height)||je},sourceUrl:typeof r.sourceUrl=="string"?r.sourceUrl:"",title:typeof r.title=="string"?r.title:"Captured screen",click:r.click??null,scroll:{x:Number(r.scroll?.x)||0,y:Number(r.scroll?.y)||0,maxX:Number(r.scroll?.maxX)||0,maxY:Number(r.scroll?.maxY)||0}}}function dn(){let e=x(Le,"singlefile-injected.js");if(Ue(e))return e;let t=De(process.cwd(),"packages/capture-extension/dist/singlefile-injected.js"),n=De(Le,"packages/capture-extension/dist/singlefile-injected.js"),r=t??n;if(!r)throw new Error("SingleFile bundle not found. Run `npm run extension:build` before --html capture.");return r}var pn={removeFrames:!0,blockScripts:!0,compressHTML:!1,compressCSS:!1,saveRawPage:!1,loadDeferredImages:!1,loadDeferredImagesMaxIdleTime:1500,loadDeferredImagesKeepZoomLevel:!1,loadDeferredImagesBlockCookies:!1,loadDeferredImagesBlockStorage:!1,blockMixedContent:!1,insertMetaCSP:!0,insertMetaNoIndex:!1,insertSingleFileComment:!1,removeAlternativeFonts:!0,removeAlternativeImages:!0,removeAlternativeMedias:!0,removeUnusedFonts:!0,backgroundSave:!1,removeUnusedStyles:!0,removeHiddenElements:!0,compressContent:!1,groupDuplicateImages:!0,groupDuplicateStylesheets:!0},de="__inklySingleFileFetch",fn=`(() => {
|
|
260
265
|
if (globalThis.__inklyFetchInstalled) return;
|
|
261
266
|
globalThis.__inklyFetchInstalled = true;
|
|
262
267
|
const pending = new Map();
|
|
@@ -276,7 +281,7 @@ function selectorFor(el) {
|
|
|
276
281
|
const id = nextId++;
|
|
277
282
|
pending.set(id, { resolve, reject });
|
|
278
283
|
try {
|
|
279
|
-
globalThis.${
|
|
284
|
+
globalThis.${de}(JSON.stringify({
|
|
280
285
|
id,
|
|
281
286
|
url: String(url),
|
|
282
287
|
options: {
|
|
@@ -299,7 +304,7 @@ function selectorFor(el) {
|
|
|
299
304
|
return viaNode(url, options);
|
|
300
305
|
}
|
|
301
306
|
};
|
|
302
|
-
})();`;function
|
|
307
|
+
})();`;function mn(e,t){let n,r,i;try{let s=new URL(e);n=s.hostname,r=s.pathname||"/",i=s.protocol==="https:"}catch{return""}return t.filter(s=>{let o=s.domain.replace(/^\./,""),u=n===o||n.endsWith(`.${o}`),d=r.startsWith(s.path||"/"),g=!s.secure||i;return u&&d&&g}).map(s=>`${s.name}=${s.value}`).join("; ")}async function hn(e,t,n,r){let i;try{let s=JSON.parse(n);i=s.id;let o={...s.options?.headers??{}},u=mn(s.url,r);u&&(o.cookie=u),s.options?.referrer&&(o.referer=s.options.referrer);let d=await fetch(s.url,{headers:o,redirect:"follow"}),g=Buffer.from(await d.arrayBuffer()),b={};d.headers.forEach((w,v)=>{b[v]=w});let c={status:d.status,headers:b,data:g.toString("base64")};await I(e,t,`globalThis.__inklyResolveFetch(${i}, ${JSON.stringify(c)})`,2e4)}catch(s){if(i===void 0)return;await I(e,t,`globalThis.__inklyRejectFetch(${i}, ${JSON.stringify({error:String(s)})})`,2e4).catch(()=>{})}}var ce=Math.max(6e4,Number(process.env.INKLY_CAPTURE_TIMEOUT_MS)||24e4);async function gn(e,t,n=!1){let r=await Q(dn(),"utf8");await e.send("Network.enable",{},t).catch(()=>{}),await e.send("Runtime.addBinding",{name:de},t).catch(()=>{});let i=[];try{i=(await e.send("Network.getAllCookies",{},t)).cookies??[]}catch{}let s=e.on("Runtime.bindingCalled",(o,u)=>{if(u!==t)return;let d=o;d.name!==de||typeof d.payload!="string"||hn(e,t,d.payload,i)});try{await I(e,t,r,3e4),await I(e,t,fn,1e4);let o=await I(e,t,`(async () => {
|
|
303
308
|
const sf = globalThis.__inklySingleFile;
|
|
304
309
|
if (!sf || typeof sf.getPageData !== "function") throw new Error("SingleFile not loaded");
|
|
305
310
|
// initOptions (2nd arg) is forwarded to single-file-core/core/util.js
|
|
@@ -310,15 +315,22 @@ function selectorFor(el) {
|
|
|
310
315
|
frameFetch: globalThis.__inklyPrivilegedFetch,
|
|
311
316
|
};
|
|
312
317
|
const data = await Promise.race([
|
|
313
|
-
sf.getPageData(${JSON.stringify({...
|
|
314
|
-
new Promise((_, reject) => setTimeout(() => reject(new Error("SingleFile getPageData exceeded ${
|
|
318
|
+
sf.getPageData(${JSON.stringify({...pn,blockVideos:n})}, initOptions),
|
|
319
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("SingleFile getPageData exceeded ${ce}ms")), ${ce}))
|
|
315
320
|
]);
|
|
316
321
|
if (typeof data.content === "string") return data.content;
|
|
317
322
|
return new TextDecoder().decode(new Uint8Array(data.content));
|
|
318
|
-
})()`,
|
|
319
|
-
`)}
|
|
320
|
-
`)
|
|
321
|
-
`)}))}),n.
|
|
322
|
-
`)}
|
|
323
|
-
`)
|
|
323
|
+
})()`,ce+15e3);return String(o)}finally{s()}}async function wn(e,t){if(e.runtime!=="cli")throw new Error("HTML capture is only available for --runtime cli sessions");if(!e.captureDir)throw new Error("CLI capture session has no captureDir");let n=new U(e.browserWsUrl);try{let r=await ee(n,e.targetId);await n.send("Page.enable",{},r).catch(()=>{}),await n.send("Runtime.enable",{},r).catch(()=>{}),await ne(n,r),await te(n,r,e.targetId,e.width,e.height);let i=await re(n,r),s=await gn(n,r,e.cliBlockVideos===!0),o=(e.cliScreens?.length??0)+1,u=x(e.captureDir,`html-${String(o).padStart(3,"0")}`),d=x(u,"index.html");await Y(u,{recursive:!0}),await W(d,s,"utf8");let g={...e,cliScreens:[...e.cliScreens??[],{kind:"html",pngPath:null,htmlPath:d,viewport:i.viewport,naturalSize:i.viewport,sourceUrl:i.sourceUrl,title:i.title,click:t??i.click,scroll:i.scroll,capturedAt:new Date().toISOString()}],tabUrl:i.sourceUrl};return await n.send("Target.detachFromTarget",{sessionId:r}).catch(()=>{}),await O(g),g}finally{n.close()}}async function yn(e){await new Promise((t,n)=>{let r=Vt("ffmpeg",e,{stdio:["ignore","ignore","pipe"]}),i=[];r.stderr.on("data",s=>i.push(s)),r.on("error",n),r.on("close",s=>{if(s===0){t();return}n(new Error(`ffmpeg exited ${s}: ${Buffer.concat(i).toString("utf8").slice(-2e3)}`))})})}function bn(e){if(e.length<=2)return e;let t=[],n=0;for(let s=1;s<e.length;s++)e[s].receivedAt-e[s-1].receivedAt>Qt&&(t.push({start:n,end:s-1}),n=s);t.push({start:n,end:e.length-1});let r=t[0],i=e[r.end].receivedAt-e[r.start].receivedAt;for(let s of t){let o=e[s.end].receivedAt-e[s.start].receivedAt;o>=i&&(r=s,i=o)}return e.slice(r.start,r.end+1)}async function vn(e){let t=e.fps,n=[...e.frames].sort((A,P)=>A.receivedAt-P.receivedAt),r=[],i=n[0]?.receivedAt;if(i!==void 0){let A=1e3/t,P=i;for(let _ of n)_.receivedAt<P&&_!==n[n.length-1]||(r.push(_),P=_.receivedAt+A)}let s=r.slice(-Math.ceil(Be/1e3*t)-2);if(process.env.INKLY_NAV_DEBUG){let A=s.map((P,_)=>_===0?0:P.receivedAt-s[_-1].receivedAt);process.stderr.write(`[navdbg] writeVideo: raw=${n.length} sampled=${r.length} preTrim=${s.length} gaps=${JSON.stringify(A)}
|
|
324
|
+
`)}let o=bn(s),u=o[0]?.receivedAt,d=o[o.length-1]?.receivedAt,g=u!==void 0&&d!==void 0?d-u:0;if(o.length<en||g<tn)return process.env.INKLY_NAV_DEBUG&&process.stderr.write(`[navdbg] video reject: frames=${o.length} durationMs=${g}
|
|
325
|
+
`),null;if(new Set(o.map(A=>A.data)).size<=1)return process.env.INKLY_NAV_DEBUG&&process.stderr.write(`[navdbg] video reject: frozen (all ${o.length} frames identical)
|
|
326
|
+
`),null;let b=Math.round(rn/1e3*t),c=Array.from({length:b},()=>o[0]).concat(o),w=Math.ceil(nn/1e3*t),v=c.length>=w?c:c.concat(Array.from({length:w-c.length},()=>c[c.length-1])),S=x(e.captureDir,`video-${String(e.index).padStart(3,"0")}`);await qt(S,{recursive:!0,force:!0}).catch(()=>{}),await Y(S,{recursive:!0});for(let[A,P]of v.entries())await W(x(S,`frame-${String(A+1).padStart(5,"0")}.png`),Buffer.from(P.data,"base64"));let C=x(S,"poster.png");await W(C,Buffer.from(o[0].data,"base64"));let y=x(e.captureDir,`video-${String(e.index).padStart(3,"0")}.webm`);await yn(["-y","-framerate",String(t),"-i",x(S,"frame-%05d.png"),"-c:v","libvpx-vp9","-pix_fmt","yuv420p","-deadline","realtime","-cpu-used","6",y]);let L=new Uint8Array(await Q(C));return{videoPath:y,posterPngPath:C,naturalSize:pe(L)??{width:He,height:je}}}async function Ve(e,t,n,r){if(!e.captureDir)throw new Error("CLI capture session has no captureDir");let i=Buffer.from(t,"base64"),s=(e.cliScreens?.length??0)+1,o=x(e.captureDir,`screen-${String(s).padStart(3,"0")}.png`);await Y(e.captureDir,{recursive:!0}),await W(o,i);let u=pe(i)??n.viewport,d={...e,cliScreens:[...e.cliScreens??[],{kind:"image",pngPath:o,viewport:n.viewport,naturalSize:u,sourceUrl:n.sourceUrl,title:n.title,click:r,scroll:n.scroll,capturedAt:new Date().toISOString()}],tabUrl:n.sourceUrl};return await O(d),d}async function kn(e,t,n,r,i){if(e.runtime!=="cli")throw new Error("video capture is only available for --runtime cli sessions");if(!e.captureDir)throw new Error("CLI capture session has no captureDir");let s=r??null,o=null;try{if(!s){o=new U(e.browserWsUrl);let c=await ee(o,e.targetId);await o.send("Page.enable",{},c).catch(()=>{}),await o.send("Runtime.enable",{},c).catch(()=>{}),await ne(o,c),await te(o,c,e.targetId,e.width,e.height),s=await re(o,c),await o.send("Target.detachFromTarget",{sessionId:c}).catch(()=>{})}let u=(e.cliScreens?.length??0)+1,d=e.cliHeadless?We:Xt,g=await vn({frames:t,captureDir:e.captureDir,index:u,fps:d});if(!g)return i&&r?Ve(e,i,r,n??null):qe(e,void 0,n,"click");let b={...e,cliScreens:[...e.cliScreens??[],{kind:"video",pngPath:g.posterPngPath,videoPath:g.videoPath,posterPngPath:g.posterPngPath,viewport:s.viewport,naturalSize:g.naturalSize,sourceUrl:s.sourceUrl,title:s.title,click:n??s.click,scroll:s.scroll,capturedAt:new Date().toISOString()}],tabUrl:s.sourceUrl};return await O(b),b}finally{o?.close()}}async function qe(e,t,n,r="click"){if(e.runtime!=="cli")throw new Error("capture is only available for --runtime cli sessions");if(!e.captureDir)throw new Error("CLI capture session has no captureDir");let i=new U(e.browserWsUrl);try{let s=await ee(i,e.targetId);await i.send("Page.enable",{},s).catch(()=>{}),await i.send("Runtime.enable",{},s).catch(()=>{}),await ne(i,s),await te(i,s,e.targetId,e.width,e.height);let o=await re(i,s),d=(await i.send("Page.captureScreenshot",{format:"png",fromSurface:!0,captureBeyondViewport:!1},s)).data;if(typeof d!="string")throw new Error("Page.captureScreenshot returned no data");let g=Buffer.from(d,"base64"),b=(e.cliScreens?.length??0)+1,c=x(e.captureDir,`screen-${String(b).padStart(3,"0")}.png`);await Y(e.captureDir,{recursive:!0}),await W(c,g);let w=pe(g)??o.viewport,v=r==="click"?n??o.click:null,S=t&&r==="click"?{...v??{x:.5,y:.5},label:t}:v,C={...e,cliScreens:[...e.cliScreens??[],{kind:"image",pngPath:c,viewport:o.viewport,naturalSize:w,sourceUrl:o.sourceUrl,title:o.title,click:S,scroll:o.scroll,capturedAt:new Date().toISOString()}],tabUrl:o.sourceUrl};return await i.send("Target.detachFromTarget",{sessionId:s}).catch(()=>{}),await O(C),C}finally{i.close()}}function ze(){return x(process.env.INKLY_CAPTURE_AGENT_HOME||x(Gt(),".inkly"),"capture-agent","sessions")}function Ge(e){if(!/^[a-zA-Z0-9._:-]+$/.test(e))throw new Error(`invalid session id: ${e}`);return x(ze(),`${e}.json`)}function Sn(e){return x(ze(),`${e}.listener.json`)}async function Pn(e){try{let t=await Q(Sn(e),"utf8");return JSON.parse(t)}catch{return null}}async function O(e){await ve(Ge(e.id),`${JSON.stringify(e,null,2)}
|
|
327
|
+
`)}async function D(e){let t=await Q(Ge(e),"utf8");return JSON.parse(t)}async function Ke(e){let t=cn(e,"session",Zt),n=await D(t);if(n.runtime!=="cli")throw new Error("listen subcommand is only available for cli runtime sessions");let r=await Pn(t);process.stderr.write(`capture listener: session ${t} connecting to ${n.browserWsUrl}
|
|
328
|
+
`);let i=new U(n.browserWsUrl),s=null,o=n.targetId,u=Promise.resolve(),d=Promise.resolve(),g=0,b=new Set,c=[],w=!1,v=null,S=null,C=!1,y=null,L=null;async function A(m){s&&(await i.send("Page.stopScreencast",{},s).catch(()=>{}),await i.send("Target.detachFromTarget",{sessionId:s}).catch(()=>{})),c=[],w=!1,v=null,S=null,o=m,s=await ee(i,m),await i.send("Page.enable",{},s).catch(()=>{}),await i.send("Runtime.enable",{},s).catch(()=>{});let h=await D(t).catch(()=>n);await te(i,s,m,h.width,h.height),await ne(i,s,!0),c=[],w=!1,v=null,S=null;let a=await D(t).catch(()=>h);a.cliRecordVideo&&a.cliCaptureKind!=="html"&&await i.send("Page.startScreencast",{format:"png",quality:90,maxWidth:a.width,maxHeight:a.height,everyNthFrame:1},s).catch(l=>{process.stderr.write(`capture video start failed: ${l.message}
|
|
329
|
+
`)});let p=await D(t).catch(()=>n);await O({...p,targetId:m,cliListenerPid:p.cliListenerPid??r?.cliListenerPid??null,cliListenerLogPath:p.cliListenerLogPath??r?.cliListenerLogPath??null,cliListenerReadyAt:p.cliListenerReadyAt??new Date().toISOString()})}async function P(m){C||(C=!0,L&&(await L.close().catch(()=>{}),L=null),y&&(await y.close().catch(()=>{}),y=null),s&&(await i.send("Page.stopScreencast",{},s).catch(()=>{}),await i.send("Target.detachFromTarget",{sessionId:s}).catch(()=>{})),i.close(),process.exit(m))}process.once("SIGTERM",()=>{P(0)}),process.once("SIGINT",()=>{P(0)}),await i.send("Target.setDiscoverTargets",{discover:!0}).catch(()=>{});for(let m of await Ne(i).catch(()=>[]))b.add(m.targetId);await A(n.targetId);{let m=await D(t).catch(()=>n);await O({...m,targetId:o,cliListenerPid:m.cliListenerPid??r?.cliListenerPid??null,cliListenerLogPath:m.cliListenerLogPath??r?.cliListenerLogPath??null,cliListenerReadyAt:m.cliListenerReadyAt??new Date().toISOString()})}process.stderr.write(`capture listener: session ${t} armed and recording
|
|
330
|
+
`);let _=async m=>{let h=await i.send("Page.captureScreenshot",{format:"png"},m).catch(()=>null),a=h&&h.data;typeof a=="string"&&(c.push({data:a,receivedAt:Date.now()}),c.length>J&&(c=c.slice(-J)))};try{y=new K(n.browserWsUrl,o),await y.init(),L=await Ie(Me(t),async m=>{if(!y)throw new Error("nav driver unavailable");let h=y,a=m.params??{},p=async l=>{if(a.noSnapshot===!0)return l;try{await h.wait({type:"load",arg:"load",timeoutMs:5e3}).catch(()=>{});let f=await h.agentSnapshot();return{...l,snapshot:f}}catch{return l}};switch(m.command){case"snapshot":return y.snapshot({trim:a.full!==!0,filter:typeof a.filter=="string"?a.filter:void 0,maxDepth:typeof a.maxDepth=="number"?a.maxDepth:void 0,includeMaps:a.json===!0});case"click":{let l=a.selector;if(typeof l!="string"||!l)throw new Error("nav click requires a selector");let f=(await X(t)).steps??0;if(s){let $=s,q=n.cliHeadless?()=>_($):void 0;await Cn(i,$,h.resolveRef(l),{width:n.width,height:n.height},q).catch(()=>{})}let k=await h.click(l),E=await $e(t,f);return p({...k,steps:E.steps,lastLabel:E.lastLabel})}case"fill":{let l=a.selector,f=a.value;if(typeof l!="string"||!l)throw new Error("nav fill requires a selector");if(typeof f!="string")throw new Error("nav fill requires a value");return p(await h.fill(l,f,a.pressEnter===!0))}case"type":{let l=a.text;if(typeof l!="string")throw new Error("nav type requires text");return p(await h.type(l,typeof a.delay=="number"?a.delay:void 0))}case"key":{let l=a.key;if(typeof l!="string"||!l)throw new Error("nav press requires a key");return p(await h.key(l))}case"select":{let l=a.selector,f=a.values;if(typeof l!="string"||!l)throw new Error("nav select requires a selector");if(!Array.isArray(f)||f.some(k=>typeof k!="string"))throw new Error("nav select requires one or more string values");return p(await h.select(l,f))}case"upload":{let l=a.selector,f=a.files;if(typeof l!="string"||!l)throw new Error("nav upload requires a selector");if(!Array.isArray(f)||f.length===0||f.some(k=>typeof k!="string"))throw new Error("nav upload requires one or more file paths");return y.upload(l,f)}case"get":{let l=a.what;if(typeof l!="string"||!l)throw new Error("nav get requires a target");return y.get(l,typeof a.selector=="string"?a.selector:void 0)}case"is":{let l=a.check,f=a.selector;if(typeof l!="string"||!l)throw new Error("nav is requires a check");if(typeof f!="string"||!f)throw new Error("nav is requires a selector");return y.is(l,f)}case"wait":{let l=a.type;if(typeof l!="string"||!l)throw new Error("nav wait requires a type");return y.wait({type:l,arg:typeof a.arg=="string"?a.arg:void 0,state:typeof a.state=="string"?a.state:void 0,timeoutMs:typeof a.timeoutMs=="number"?a.timeoutMs:void 0})}case"back":return p(await h.back({waitUntil:typeof a.waitUntil=="string"?a.waitUntil:void 0,timeoutMs:typeof a.timeoutMs=="number"?a.timeoutMs:void 0}));case"forward":return p(await h.forward({waitUntil:typeof a.waitUntil=="string"?a.waitUntil:void 0,timeoutMs:typeof a.timeoutMs=="number"?a.timeoutMs:void 0}));case"reload":return p(await h.reload({waitUntil:typeof a.waitUntil=="string"?a.waitUntil:void 0,timeoutMs:typeof a.timeoutMs=="number"?a.timeoutMs:void 0}));case"scroll":{let l=a.direction==="up"?"up":"down",f=typeof a.amount=="number"&&a.amount>0?a.amount:_e;if(s){let k=s,E=n.cliHeadless?()=>_(k):void 0;await Je(i,k,l,f,{width:n.width,height:n.height},E)}else await h.scroll(l,f);return p({scrolled:!0,direction:l,amount:f})}case"refs":return y.refs();case"mouse.click":{let l=a.x,f=a.y;if(typeof l!="number"||typeof f!="number")throw new Error("nav mouse click requires numeric x and y");let k=(await X(t)).steps??0,E=await h.mouseClick(l,f,{button:typeof a.button=="string"?a.button:void 0,clickCount:typeof a.clickCount=="number"?a.clickCount:void 0}),$=await $e(t,k);return p({...E,steps:$.steps,lastLabel:$.lastLabel})}case"mouse.hover":{let l=a.x,f=a.y;if(typeof l!="number"||typeof f!="number")throw new Error("nav mouse hover requires numeric x and y");return y.mouseHover(l,f)}case"mouse.scroll":{let l=a.x,f=a.y,k=a.deltaX,E=a.deltaY;if(typeof l!="number"||typeof f!="number"||typeof k!="number"||typeof E!="number")throw new Error("nav mouse scroll requires numeric x, y, deltaX, deltaY");return p(await h.mouseScroll(l,f,k,E))}default:throw new Error(`unknown nav command: ${m.command}`)}})}catch(m){process.stderr.write(`capture nav driver init failed: ${m.message}
|
|
331
|
+
`),y&&(await y.close().catch(()=>{}),y=null)}i.on("Target.targetCreated",m=>{let a=m.targetInfo;!a||a.type!=="page"||!(a.openerId===o||Date.now()<g)||(d=d.then(async()=>{await N(250),await A(a.targetId),b.add(a.targetId)}).catch(l=>{process.stderr.write(`capture target follow failed: ${l.message}
|
|
332
|
+
`)}))}),i.on("Page.screencastFrame",(m,h)=>{if(h!==s)return;let a=m;typeof a.sessionId=="number"&&i.send("Page.screencastFrameAck",{sessionId:a.sessionId},h).catch(()=>{}),typeof a.data=="string"&&(c.push({data:a.data,receivedAt:Date.now()}),c.length>J&&(c=c.slice(-J)))});async function V(){let m=await Ne(i).catch(()=>[]),h=m.find(a=>a.openerId===o)??m.find(a=>a.targetId!==o&&!b.has(a.targetId));for(let a of m)b.add(a.targetId);!h||h.targetId===o||await A(h.targetId)}async function fe(m){!m||!s||await i.send("Page.navigate",{url:m},s).catch(h=>{process.stderr.write(`capture post-click navigation failed: ${h.message}
|
|
333
|
+
`)})}i.on("Runtime.bindingCalled",(m,h)=>{if(h!==s)return;let a=m;if(a.name!=="__inklyCliCaptureEvent"&&a.name!=="__inklyCliCaptureClick"||typeof a.payload!="string")return;let p=null;try{let l=JSON.parse(a.payload);a.name==="__inklyCliCaptureClick"?p={type:"click",click:l,page:null}:p={type:l.type==="input"||l.type==="scroll"?l.type:"click",click:typeof l.click=="object"&&l.click?l.click:null,page:typeof l.page=="object"&&l.page?l.page:null}}catch{p=null}if(p){if(p.type==="click")g=Date.now()+3e3;else{let l=Date.now();v=v??l,S=l,w=!0}u=u.then(async()=>{if(p.type!=="click")return;let l=Date.now(),f=v,k=S,E=w&&f!==null&&k!==null&&l-k<=Yt;w=!1,v=null,S=null;let $=Math.max(f?f-250:0,l-Be),q=f?c.filter(T=>T.receivedAt>=$):[...c],ie=p.page?.navigationUrl??null;process.env.INKLY_NAV_DEBUG&&process.stderr.write(`[navdbg] click: attachVideo=${E} hadMotion=${w} motionStart=${f} bufFrames=${c.length} segFrames=${q.length} sinceMotion=${k?l-k:"n/a"}
|
|
334
|
+
`);let F=c.length?c[c.length-1].data:null,H=p.page?{viewport:p.page.viewport,sourceUrl:p.page.url,title:p.page.title,click:p.click,scroll:p.page.scroll}:null;if(s&&(H||(H=await re(i,s).catch(()=>null)),!F)){let T=await i.send("Page.captureScreenshot",{format:"png",fromSurface:!0,captureBeyondViewport:!1},s).catch(()=>null),he=T&&T.data;F=typeof he=="string"?he:null}c=[];let R=await D(t).catch(()=>null);if(!R||R.runtime!=="cli"){await P(0);return}if(R.cliCaptureKind==="html"){await N(ie?500:2e3);let T=await wn(R,p.click);await Z({session:T,stepKind:"html",action:p.type,click:p.click}),await fe(ie),await N(2e3),await d,await V();return}if(await fe(ie),await N(2e3),await d,await V(),R.cliRecordVideo&&E){let T=await kn(R,q,p.click,H??void 0,F);await Z({session:T,stepKind:Re(T),action:p.type,click:p.click});return}if(F&&H){let T=await Ve(R,F,H,p.click??null);await Z({session:T,stepKind:"image",action:p.type,click:p.click});return}let me=await qe(R,void 0,p.click,"click");await Z({session:me,stepKind:Re(me),action:p.type,click:p.click})}).catch(l=>{process.stderr.write(`capture listener failed: ${l.message}
|
|
335
|
+
`)})}});let Ze=setInterval(()=>{D(t).catch(()=>{clearInterval(Ze),P(0)})},1e3);return await new Promise(()=>{}),0}async function X(e){let n=(await D(e).catch(()=>null))?.cliScreens??[],r=n[n.length-1];return{steps:n.length,lastLabel:r&&(r.click?.label||r.title)||null,lastKind:r?.kind??null}}async function Je(e,t,n,r,i,s){let o=!!s,u=o?on:90,d=1800,g=o?6e3:5e3,b=110,c=Math.round(i.width/2),w=Math.round(i.height/2),v=Math.max(u,Math.round(Math.abs(r))),S=n==="up"?-1:1,C=Math.ceil(v/u),y=Math.max(1,C-1),L=Math.min(Math.round(g/y),Math.max(b,Math.round(d/y)));await e.send("Input.dispatchMouseEvent",{type:"mouseMoved",x:c,y:w,button:"none"},t).catch(()=>{});let A=Date.now(),P=v;for(let _=0;_<C&&!(Date.now()-A>g);_+=1){let V=Math.min(u,P)*S;P-=u,await e.send("Input.dispatchMouseEvent",{type:"mouseWheel",x:c,y:w,deltaX:0,deltaY:V,button:"none"},t).catch(()=>{}),s&&await s(),!o&&_<C-1&&await N(L)}}async function Cn(e,t,n,r,i){if(!n.startsWith("/"))return!1;let s=`(()=>{try{const el=document.evaluate(${JSON.stringify(n)},document,null,9,null).singleNodeValue;if(!el)return null;const r=el.getBoundingClientRect();const vh=window.innerHeight||${r.height};if(r.width<=0&&r.height<=0)return null;if(r.top>=0&&r.bottom<=vh)return 0;return Math.round(r.top-vh*0.2);}catch{return null;}})()`,o=await e.send("Runtime.evaluate",{expression:s,returnByValue:!0},t).catch(()=>null),u=o&&o.result?.value;return typeof u!="number"||Math.abs(u)<48?!1:(await Je(e,t,u>0?"down":"up",Math.abs(u),r,i),!0)}async function $e(e,t,n=7e3){let r=Date.now()+n,i=await X(e);for(;(i.steps??0)<=t&&Date.now()<r;)await N(200),i=await X(e);return i}async function xn(){let e=An(process.argv.slice(2));process.exit(await Ke(e))}xn().catch(e=>{process.stderr.write(`capture listener failed: ${e.message}
|
|
324
336
|
`),process.exit(1)});
|