apify-cli 1.4.2-beta.5 → 1.4.2-beta.7

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.
@@ -0,0 +1,307 @@
1
+ var jc=Object.defineProperty;var m=(r,e)=>jc(r,"name",{value:e,configurable:!0});import xe from"process";import{parseArgs as aa}from"util";import co from"chalk";import{satisfies as Yd}from"semver";import fi from"chalk";import Cd from"indent-string";import Id from"widest-line";import Ed from"wrap-ansi";import qi from"ci-info";var Bc=[["CLAUDECODE","claude_code"],["CLAUDE_CODE_ENTRYPOINT","claude_code"],["CURSOR_AGENT","cursor"],["CLINE_ACTIVE","cline"],["CODEX_SANDBOX","codex_cli"],["CODEX_THREAD_ID","codex_cli"],["GEMINI_CLI","gemini_cli"],["OPENCODE","open_code"],["OPENCLAW_SHELL","openclaw"]];function Ki(){for(let[r,e]of Bc)if(process.env[r])return e}m(Ki,"detectAiAgent");function Wi(){return qi.isCI?{isCi:!0,ciProvider:qi.id?.toLowerCase()??"unknown"}:{isCi:!1,ciProvider:void 0}}m(Wi,"detectCi");function zi(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}m(zi,"detectIsInteractive");import Vc from"chalk";function T(r,...e){process.env.APIFY_CLI_DEBUG&&console.error(Vc.gray(`[${r}]`),...e)}m(T,"cliDebugPrint");import{realpathSync as Gc}from"fs";import{dirname as Yc}from"path";import gt from"chalk";function tt(r){r.stdoutOutput&&console.log(...r.stdoutOutput),r.stderrOutput&&console.error(...r.stderrOutput)}m(tt,"internalLog");function $(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[r.message]})}m($,"simpleLog");function g(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.red("Error:"),r.message]})}m(g,"error");function x(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.yellow.bold("Warning:"),r.message]})}m(x,"warning");function R(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.green("Success:"),r.message]})}m(R,"success");function Ce(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.gray("Run:"),r.message]})}m(Ce,"run");function b(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.white("Info:"),r.message]})}m(b,"info");function Hs(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.blue(r.message),r.url]})}m(Hs,"link");var Js="0.0.0";var Hc="1.4.2-beta.7",Jc="ed31fcb995895b1d949e0922a945b103ba17d39c";function qc(){if(process.env.APIFY_CLI_MARKED_INSTALL_METHOD)return process.env.APIFY_CLI_MARKED_INSTALL_METHOD;if(process.env.APIFY_CLI_BUNDLE)return"bundle";let r=process.argv[1];if(!r)return x({message:"Failed to detect install method of CLI, assuming npm"}),"npm";let e=Gc(r);return process.env.VOLTA_HOME&&e.includes(process.env.VOLTA_HOME)?"volta":e.includes("homebrew/Cellar")||e.includes("linuxbrew/Cellar")?"homebrew":process.env.PNPM_HOME&&e.includes(process.env.PNPM_HOME)?"pnpm":process.env.BUN_INSTALL&&e.includes(process.env.BUN_INSTALL)?"bun":"npm"}m(qc,"detectInstallMethod");function Kc(){return process.versions.bun?{runtime:"bun",version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:"deno",version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:"node",version:process.versions.node}}m(Kc,"getRuntimeInfo");var Vt=null;function z(){if(Vt)return Vt;let r=qc(),e=Kc();return Vt={version:Hc,hash:Jc,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform==="win32"?"windows":process.platform,runtime:e,extraRuntimeData:e.nodeVersion?`(emulating node ${e.nodeVersion})`:"",installMethod:r,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${e.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:""}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes("beta")||this.version===Js}},r==="bundle"&&(Vt.installPath=Yc(process.execPath)),Vt}m(z,"useCLIMetadata");import{existsSync as Ol,mkdirSync as Nl,readFileSync as Ll,writeFileSync as Dl}from"fs";import{dirname as Fl}from"path";import{cryptoRandomObjectId as Ul}from"@apify/utilities";import{homedir as zc}from"os";import{join as rt}from"path";import{KEY_VALUE_STORE_KEYS as Xc,META_ORIGINS as Zc}from"@apify/consts";var Xi={name:"apify-cli",version:"1.4.2-beta.7",description:"Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",exports:"./dist/index.js",type:"module",scripts:{"dev:apify":"tsx ./src/entrypoints/apify.ts","dev:actor":"tsx ./src/entrypoints/actor.ts","test:all":"yarn test:local && yarn test:api","test:local":"vitest run --testNamePattern '^((?!\\[api]).)*$' --exclude ./test/api --exclude ./test/e2e","test:e2e":"vitest run --testNamePattern '\\[e2e\\]' --exclude ./test/api","test:e2e:local":"vitest run --testNamePattern '^(?=.*\\[e2e\\])(?!.*\\[api\\]).*$' --exclude ./test/api","test:api":"vitest run --testNamePattern '^(?=.*\\[api\\])(?!.*\\[e2e\\]).*$' --exclude ./test/e2e","test:python":"vitest run --testNamePattern '\\[python\\]'",lint:"eslint src test scripts --ext .ts,.cjs,.mjs","lint:fix":"eslint src test scripts --fix --ext .ts,.cjs,.mjs",format:'biome format . && prettier --check "**/*.{md,yml,yaml}"',"format:fix":'biome format --write . && prettier --write "**/*.{md,yml,yaml}"',clean:"rimraf dist",build:"yarn clean && tsc && tsup","build-bundles":"bun run scripts/build-cli-bundles.ts",prepack:"yarn insert-cli-metadata && yarn build && yarn update-docs","insert-cli-metadata":"tsx scripts/insert-cli-metadata.ts","update-docs":"tsx scripts/generate-cli-docs.ts",postinstall:`node -e "console.log('We have an active developer community on Discord. You can find it on https://discord.gg/crawlee-apify-801163717915574323.');"`,prepare:"husky"},files:["dist"],bin:{actor:"./dist/actor.js",apify:"./dist/apify.js","apify-cli":"./dist/apify.js"},contributors:["Jakub Drobn\xEDk <jakub.drobnik@apify.com>","Jan Curn <jan@apify.com>","Vlad Frangu <vlad.frangu@apify.com>"],repository:{type:"git",url:"git+https://github.com/apify/apify-cli.git"},keywords:["apify","client","node","command","line","bash"],author:{name:"Apify",email:"support@apify.com",url:"https://www.apify.com"},license:"Apache-2.0",bugs:{url:"https://github.com/apify/apify-cli/issues"},homepage:"https://github.com/apify/apify-cli#readme",engines:{node:">=20"},dependencies:{"@apify/actor-memory-expression":"^0.1.12","@apify/actor-templates":"^0.1.5","@apify/consts":"^2.36.0","@apify/input_schema":"^3.17.0","@apify/utilities":"^2.18.0","@crawlee/memory-storage":"^3.12.0","@inquirer/core":"^11.0.0","@inquirer/input":"^5.0.0","@inquirer/password":"^5.0.0","@inquirer/select":"^5.0.0","@root/walk":"~1.1.0","@sapphire/duration":"^1.1.2","@sapphire/result":"^2.7.2","@sapphire/timestamp":"^1.0.3","@skyra/jaro-winkler":"^1.1.1","adm-zip":"~0.5.15",ajv:"~8.18.0","apify-client":"^2.22.0",archiver:"~7.0.1",axios:"^1.15.0",chalk:"~5.6.0","ci-info":"~4.4.0","cli-table3":"^0.6.5","computer-name":"~0.1.0",configparser:"~0.3.10",cors:"~2.8.5","detect-indent":"~7.0.1","es-toolkit":"^1.45.1","escape-string-regexp":"~5.0.0",execa:"^9.5.2",express:"~5.2.0",handlebars:"~4.7.8",ignore:"^7.0.0","indent-string":"^5.0.0","is-ci":"~4.1.0",istextorbinary:"~9.5.0",jju:"~1.4.0","js-levenshtein":"^1.1.6","json-schema-to-typescript":"^15.0.4",mime:"~4.1.0",open:"~11.0.0",rimraf:"~6.1.0",semver:"~7.7.0","string-width":"^8.0.0","strip-ansi":"^7.1.0",tiged:"~2.12.7",tinyglobby:"^0.2.15",which:"^6.0.0","widest-line":"^6.0.0","wrap-ansi":"^10.0.0"},devDependencies:{"@apify/eslint-config":"^1.0.0","@apify/tsconfig":"^0.1.1","@biomejs/biome":"^2.0.0","@crawlee/types":"^3.11.1","@types/adm-zip":"^0.5.5","@types/archiver":"^7.0.0","@types/bun":"^1.2.5","@types/cors":"^2.8.17","@types/execa":"^2.0.2","@types/express":"^5.0.0","@types/jju":"^1.4.5","@types/js-levenshtein":"^1","@types/mime":"^4.0.0","@types/node":"^24.0.0","@types/semver":"^7.5.8","@types/which":"^3.0.4","@yarnpkg/core":"^4.1.2",apify:"^3.2.4","cross-env":"^10.0.0",eslint:"^9.25.1","eslint-config-prettier":"^10.1.2",husky:"^9","lint-staged":"^16.0.0","mock-stdin":"^1.0.0",prettier:"^3.5.3",tsup:"^8.5.0",tsx:"^4.16.5",typescript:"^6.0.0","typescript-eslint":"^8.31.0",vitest:"^4.0.0"},volta:{node:"24.14.1",yarn:"4.13.0"},packageManager:"yarn@4.13.0",devEngines:{runtime:[{name:"node",version:">= 20",onFail:"error"},{name:"bun",version:">= 1.2.5",onFail:"ignore"}],packageManager:{name:"yarn",version:">= 4",onFail:"warn"}},"lint-staged":{"*":"biome format --write --no-errors-on-unmatched","*.{mjs,js,ts}":"eslint --fix --ext mjs,js,ts","*.md":"prettier --write"},resolutions:{tar:"7.5.13"}};var ot="storage",qs="apify_storage",Ks=1,Cr={actorSpecification:Ks,name:null,version:"0.0",buildTag:"latest",environmentVariables:{}},Zi=1440*60*1e3,ht=m(()=>{let r=rt(zc(),".apify");return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?rt(r,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):r},"GLOBAL_CONFIGS_FOLDER"),ge=m(()=>rt(ht(),"auth.json"),"AUTH_FILE_PATH"),Ir=m(()=>rt(ht(),"secrets.json"),"SECRETS_FILE_PATH"),Er=m(()=>rt(ht(),"state.json"),"STATE_FILE_PATH"),$r=m(()=>rt(ht(),"telemetry.json"),"TELEMETRY_FILE_PATH"),Rr="apify.json",xr=".actor",Qc="actor.json",D=rt(xr,Qc),Ws=new RegExp(`(^${Xc.INPUT}(?:\\.[^.]+)?$)`),Ie=Xi.engines.node,_r={"X-Apify-Request-Origin":Zc.CLI},st="3.9.0",Qi=".venv";import{execSync as al}from"child_process";import{createWriteStream as cl,existsSync as oe,mkdirSync as ll,readdirSync as nn,readFileSync as Kt,writeFileSync as kr}from"fs";import{mkdir as dl,readFile as Or}from"fs/promises";import{get as ml}from"https";import{homedir as zs}from"os";import{dirname as yt,join as q,relative as ul}from"path";import X from"process";import{finished as pl}from"stream/promises";import{DurationFormatter as an,TimeTypes as it}from"@sapphire/duration";import{Timestamp as Xs}from"@sapphire/timestamp";import fl from"adm-zip";import gl from"ajv/dist/2019.js";import{ApifyClient as cn}from"apify-client";import hl from"archiver";import{AxiosHeaders as yl}from"axios";import wl from"escape-string-regexp";import Al from"ignore";import{getEncoding as vl}from"istextorbinary";import{Mime as bl}from"mime";import Sl from"mime/types/other.js";import Tl from"mime/types/standard.js";import{gte as Cl,minVersion as Il,satisfies as El}from"semver";import{glob as Zs}from"tinyglobby";import{ACTOR_ENV_VARS as Qs,ACTOR_JOB_TERMINAL_STATUSES as $l,ACTOR_NAME as Jt,APIFY_ENV_VARS as Rl,KEY_VALUE_STORE_KEYS as sn,LOCAL_ACTOR_ENV_VARS as ei,LOCAL_STORAGE_SUBDIRS as ti,SOURCE_FILE_FORMATS as Ht}from"@apify/consts";import{existsSync as el,mkdirSync as tl}from"fs";import{readFile as rl,stat as en,unlink as ol,writeFile as sl}from"fs/promises";import{join as tn,sep as il}from"path";import{rimraf as nl}from"rimraf";var rn=m(async(r,e={},t=null)=>{let o=await rl(r,"utf-8"),s=JSON.parse(o),i;t?(i=s,i[t]={...s[t],...e}):i={...s,...e},await sl(r,JSON.stringify(i,null," "))},"updateLocalJson"),Pr=m((r,e)=>{e||(e=r,r="."),e.split(il).reduce((o,s)=>(o=tn(o,s),el(o)||tl(o),o),r)},"ensureFolderExistsSync"),Gt=m(async r=>{await nl(r)},"rimrafPromised"),Yt=m(async r=>{(await en(r)).isFile()&&await ol(r)},"deleteFile"),on=m(async(r,e)=>(await Promise.all(r.map(async s=>en(tn(e,s))))).map(s=>s.size).reduce((s,i)=>s+i,0),"sumFilesSizeInBytes");var qt=Al,Wt=gl,Nr=m(async r=>new Promise((e,t)=>{ml(r,o=>{o.statusCode===301||o.statusCode===302?(e(Nr(o.headers.location)),o.destroy()):e(o)}).on("error",t)}),"httpsGet"),we=m(()=>{let r=Rl.LOCAL_STORAGE_DIR;return X.env[r]||X.env.CRAWLEE_STORAGE_DIR||ot},"getLocalStorageDir"),he=m(r=>{let e=Qs.DEFAULT_KEY_VALUE_STORE_ID,t=r||X.env[e]||ei[e];return q(we(),ti.keyValueStores,t)},"getLocalKeyValueStorePath"),ln=m(r=>{let e=Qs.DEFAULT_DATASET_ID,t=r||X.env[e]||ei[e];return q(we(),ti.datasets,t)},"getLocalDatasetPath"),dn=m(r=>{let e=Qs.DEFAULT_REQUEST_QUEUE_ID,t=r||X.env[e]||ei[e];return q(we(),ti.requestQueues,t)},"getLocalRequestQueuePath"),M=m(async()=>{let r={};try{let e=await Or(ge(),"utf-8");r=JSON.parse(e)}catch{return{}}if(!r.username&&!r.id)throw new Error('Corrupted local user info was found. Please run "apify login" to fix it.');return r},"getLocalUserInfo");async function I(){let r=await Xt();if(!r)throw X.exitCode=1,new Error('You are not logged in with your Apify account. Call "apify login" to fix that.');return r}m(I,"getLoggedClientOrThrow");var mn=m(r=>{if(!r&&oe(ht())&&oe(ge())){let e=Kt(ge(),"utf-8");return JSON.parse(e).token}return r},"getTokenWithAuthFileFallback"),zt=m((r,e)=>(r=mn(r),{token:r,baseUrl:e||X.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[t=>{t.headers??=new yl;for(let[o,s]of Object.entries(_r))t.headers[o]=s;return t}]}),"getApifyClientOptions");async function Xt(r,e){r=mn(r);let t=new cn(zt(r,e)),o;try{o=await t.user("me").get()}catch(s){return T("[getLoggedClient] error getting user info",{error:s,apiBaseUrl:e}),null}return oi(ge()),kr(ge(),JSON.stringify({token:t.token,...o},null," ")),t}m(Xt,"getLoggedClient");var ri=m(r=>q(r,D),"getLocalConfigPath"),de=m(r=>{if(oe(r))return JSON.parse(Kt(r,{encoding:"utf-8"}))},"getJsonFileContent"),Me=m(r=>de(ri(r)),"getLocalConfig"),Lr=m(async(r,e)=>{let t=q(e||X.cwd(),D);await dl(yt(t),{recursive:!0}),kr(t,JSON.stringify(r,null," "))},"setLocalConfig"),xl=[we(),"node_modules",".venv"],Dr=m(async r=>{let e=he();Pr(r,ln()),Pr(r,dn()),Pr(r,e);let t=q(r,".gitignore"),o="";oe(t)&&(o=Kt(t,{encoding:"utf-8"}));let s=[];for(let i of xl)RegExp(`^${wl(i)}$`,"mg").test(o)||s.push(i);s.length>0&&(o.length>0?(s.unshift("# Added by Apify CLI"),kr(t,`
2
+ ${s.join(`
3
+ `)}
4
+ `,{flag:"a"})):kr(t,`${s.join(`
5
+ `)}
6
+ `,{flag:"w"}))},"setLocalEnv"),un=new bl(Tl,Sl).define({"application/gzip":["tgz"],"text/typescript":["ts","tsx","mts"]},!0),_l=m((r,e)=>{let t=un.getType(r);return t?t.startsWith("text/")||t.includes("javascript")||t.includes("json")||t.includes("xml")||t.includes("application/node")||t.includes("application/toml")||t.includes("application/x-sh")||t.includes("application/x-httpd-php")?Ht.TEXT:Ht.BASE64:vl(e)==="binary"?Ht.BASE64:Ht.TEXT},"getSourceFileFormat"),pn=m(async(r,e)=>r.map(t=>{let o=Kt(q(e,t)),s=_l(t,o);return{name:t,format:s,content:s===Ht.TEXT?o.toString("utf8"):o.toString("base64")}}),"createSourceFiles"),Pl=m(async r=>{let e=await Zs("**/.gitignore",{dot:!0,cwd:r,ignore:[".git/**"],expandDirectories:!1}),t=[];for(let s of e){let i=yt(s),n=await Or(q(r,s),"utf-8");t.push({dir:i==="."?"":i,ig:qt().add(n)})}let o=yt(r);for(;o!==yt(o)&&!oe(q(o,".git"));){let s=q(o,".gitignore");if(oe(s))try{let i=await Or(s,"utf-8"),n=ul(o,r);t.push({dir:"",ig:qt().add(i),ancestorPrefix:n})}catch{}o=yt(o)}return t.length===0?s=>s:s=>s.filter(i=>{for(let{dir:n,ig:a,ancestorPrefix:c}of t){let l;if(n?i.startsWith(`${n}/`)?l=i.slice(n.length+1):l=null:l=c?`${c}/${i}`:i,l!==null&&a.ignores(l))return!1}return!0})},"getGitignoreFallbackFilter"),kl=m(async r=>{let e=q(r,".actorignore");if(!oe(e))return{excludeFilter:null,forceIncludePatterns:[]};let o=(await Or(e,"utf-8")).split(`
7
+ `),s=[],i=[];for(let a of o){let c=a.trim();!c||c.startsWith("#")||(c.startsWith("!")?i.push(c.slice(1)):s.push(c))}return{excludeFilter:s.length>0?a=>{let c=qt().add(s);return a.filter(l=>!c.ignores(l))}:null,forceIncludePatterns:i}},"parseActorIgnore"),fn=m(async r=>{let e=r??X.cwd(),t=[".git/**","apify_storage","node_modules","storage","crawlee_storage"],{excludeFilter:o,forceIncludePatterns:s}=await kl(e),i=null;try{let l=al("git ls-files --others --ignored --exclude-standard --directory",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
8
+ `).filter(Boolean);if(l.length>0){let d=qt().add(l);i=m(u=>u.filter(p=>!d.ignores(p)),"gitIgnoreFilter")}}catch{i=await Pl(e)}let n=await Zs(["*","**/**"],{ignore:t,dot:!0,expandDirectories:!1,cwd:e}),a=i?i(n):n;if(o&&(a=o(a)),s.length>0){let l=qt().add(s),d=n.filter(p=>l.ignores(p)),u=new Set(a);for(let p of d)u.add(p);a=[...u]}let c=n.filter(l=>l===".actor"||l.startsWith(".actor/"));if(c.length>0){let l=new Set(a);for(let d of c)l.add(d);a=[...l]}return a},"getActorLocalFilePaths"),gn=m(async(r,e,t)=>{oe(r)&&await Yt(r);let o=cl(r),s=hl("zip",{zlib:{level:6}});s.pipe(o),e.forEach(i=>s.file(q(t,i),{name:i})),await s.finalize()},"createActZip"),Zt=m(r=>{let e=he();if(!oe(q(r,e)))return;let s=nn(q(r,e)).find(a=>!!a.match(Ws));if(!s)return;let i=Kt(q(r,e,s)),n=un.getType(s);return{body:i,contentType:n,fileName:s}},"getLocalInput"),hn=m(async()=>{let r=dn();oe(we())&&oe(r)&&await Gt(r)},"purgeDefaultQueue"),yn=m(async()=>{let r=ln();oe(we())&&oe(r)&&await Gt(r)},"purgeDefaultDataset"),wn=m(async()=>{let r=he();if(!oe(we())||!oe(r))return;let e=nn(r),t=[];e.forEach(o=>{o.match(Ws)||t.push(Yt(q(r,o)))}),await Promise.all(t)},"purgeDefaultKeyValueStore"),ke=m(async({job:r,timeoutMillis:e,apifyClient:t})=>{let{id:o,status:s}=r,i=t||new cn({baseUrl:X.env.APIFY_CLIENT_BASE_URL});if($l.includes(s)){if(X.env.APIFY_NO_LOGS_IN_TESTS)return;let n=await i.log(o).get();X.stderr.write(n);return}return new Promise(async n=>{let a=await i.log(o).stream();if(!a){n("no-logs");return}let c=null;a.on("data",l=>{X.env.APIFY_NO_LOGS_IN_TESTS||X.stderr.write(l.toString())}),a.once("end",()=>{n("finished"),c&&clearTimeout(c)}),e&&(c=setTimeout(()=>{a.destroy(),n("timeouts")},e))})},"outputJobLog");var An=m(async()=>(await Zs([`${we()}/**`,`!${he()}/${sn.INPUT}.*`,`!${he()}/${sn.INPUT}_CLI-*`])).length===0,"checkIfStorageIsEmpty"),Qt=m(r=>{if(!Jt.REGEX.test(r))throw new Error("The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).");if(r.length<Jt.MIN_LENGTH)throw new Error("The Actor name must be at least 3 characters long.");if(r.length>Jt.MAX_LENGTH)throw new Error("The Actor name must be a maximum of 30 characters long.")},"validateActorName"),Fr=m(r=>{let e=r.replaceAll(/[^a-zA-Z0-9-]/g,"-");return e.length<Jt.MIN_LENGTH&&(e=`${e}-apify-actor`),e=e.replaceAll(/^-+/g,"").replaceAll(/-+$/g,""),e.slice(0,Jt.MAX_LENGTH)},"sanitizeActorName"),Ur=m(r=>El(r,`^${st}`),"isPythonVersionSupported"),Mr=m(r=>{let e=Il(Ie);return Cl(r,e)},"isNodeVersionSupported"),jr=m(async({url:r,pathTo:e})=>{let t=await Nr(r),o=[];t.on("data",i=>o.push(i)),await pl(t),new fl(Buffer.concat(o)).extractAllTo(e,!0)},"downloadAndUnzip");function oi(r){let e=yt(r);ll(e,{recursive:!0})}m(oi,"ensureApifyDirectory");var Y=new Xs("YYYY-MM-DD [at] HH:mm:ss"),er=new Xs(`YYYY-MM-DD[
9
+ ]HH:mm:ss`),vn=new Xs("YYYY-MM-DD"),tr=new an,me=new an({[it.Day]:{DEFAULT:"d"},[it.Hour]:{DEFAULT:"h"},[it.Minute]:{DEFAULT:"m"},[it.Month]:{DEFAULT:"M"},[it.Second]:{DEFAULT:"s"},[it.Week]:{DEFAULT:"w"},[it.Year]:{DEFAULT:"y"}});function Br(r,e){if("groupBy"in Object)return Object.groupBy(r,e);let t={},o=0;for(let s of r){let i=e(s,o++);t[i]||(t[i]=[]),t[i].push(s)}return t}m(Br,"objectGroupBy");function L(r){console.log(JSON.stringify(r,null,2))}m(L,"printJsonToStdout");var le=m(r=>r.startsWith(zs())?r.replace(zs(),"~"):r,"tildify");function bn(){let r=X.env.SHELL??"";return r.includes("zsh")?"zsh":r.includes("bash")?"bash":r.includes("fish")?"fish":"unknown"}m(bn,"detectShell");function Sn(r,e){switch(e){case"bash":{let t=[q(r,".bashrc"),q(r,".bash_profile")];X.env.XDG_CONFIG_HOME&&t.push(q(X.env.XDG_CONFIG_HOME,".bashrc"),q(X.env.XDG_CONFIG_HOME,".bash_profile"),q(X.env.XDG_CONFIG_HOME,"bashrc"),q(X.env.XDG_CONFIG_HOME,"bash_profile"));for(let o of t)if(oe(o))return o;return null}case"zsh":{let t=X.env.ZDOTDIR||zs();return q(t,".zshrc")}case"fish":return q(r,".config","fish","config.fish");case"unknown":return null}}m(Sn,"shellConfigFile");var Ml=["Apify collects telemetry data about general usage of Apify CLI to help us improve the product.",'This feature is enabled by default, and you can disable it by setting the "APIFY_CLI_DISABLE_TELEMETRY" environment variable to "1", or by running "apify telemetry disable".',"You can find more information about our telemetry in https://docs.apify.com/cli/docs/telemetry."].join(`
10
+ `);function Tn(){return`CLI:${Ul()}`}m(Tn,"createAnonymousId");async function jl(r){if(r.version&&r.version>=1)return!1;let e=r,t=await M().catch(()=>({}));return rr({version:1,enabled:!0},o=>{t.id&&e.distinctId===t.id?(o.anonymousId=Tn(),o.userId=t.id):o.anonymousId=e.distinctId}),!0}m(jl,"migrateStateV0ToV1");async function ue(){let r=$r();if(!Ol(r)){let s=await M().catch(()=>({}));return rr({version:1,enabled:!0,anonymousId:Tn(),userId:s.id}),(!process.env.APIFY_CLI_DISABLE_TELEMETRY||["false","0"].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))&&b({message:Ml}),ue()}let t=JSON.parse(Ll(r,"utf-8"));return await jl(t)?ue():t}m(ue,"useTelemetryState");function rr(r,e){let t={...r};e?.(t);let o=$r(),s=Fl(o);Nl(s,{recursive:!0}),Dl($r(),JSON.stringify(t,null," "))}m(rr,"updateTelemetryState");async function Vr(r){let e=await ue();rr(e,t=>{t.userId=r})}m(Vr,"updateUserId");var Bl=1e4;async function Cn(r){try{let e=await ue(),t=Date.now(),o=e.lastCommand===r&&t-(e.lastCommandTimestamp??0)<Bl;return rr(e,s=>{s.lastCommand=r,s.lastCommandTimestamp=t}),o}catch{return!1}}m(Cn,"checkAndUpdateLastCommand");async function Gr(r){let e=await ue();rr(e,t=>{t.enabled=r})}m(Gr,"updateTelemetryEnabled");async function In(){if(process.env.APIFY_CLI_DISABLE_TELEMETRY&&!["false","0"].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))return T("telemetry","disabled by env variable"),!1;let r=await ue();return T("telemetry state",{telemetryState:r}),r.enabled}m(In,"useTelemetryEnabled");async function En(){let r=await ue();return{anonymousId:r.anonymousId,userId:r.userId}}m(En,"useTelemetryIdentifiers");var or=z(),Vl="https://api.segment.io/v1/track",Gl=or.isBeta?"rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC":"2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t";async function $n(r,e){let t=await En(),o={anonymousId:t.anonymousId,context:{app:{name:"apify-cli",version:or.version,build:or.hash},library:{name:"apify-cli",version:or.version},os:{name:or.platform},userAgent:nt,channel:"server"},event:r,properties:{...e,app:"cli"},timestamp:new Date().toISOString(),userId:t.userId,writeKey:Gl};if(T("trackEvent",o),!await In()){T("trackEvent","telemetry disabled");return}try{let i=await fetch(Vl,{method:"POST",body:JSON.stringify(o)});if(!i.ok){T("trackEvent","failed to send event",await i.text());return}T("trackEvent","event sent")}catch(i){T("trackEvent","failed to send event",i)}}m($n,"trackEvent");import{access as ci,readdir as wt,readFile as nd,stat as ad}from"fs/promises";import{join as j,resolve as Vn}from"path";import cd from"process";import{err as ld,ok as ai}from"@sapphire/result";import{existsSync as Pn,readdirSync as zl}from"fs";import{join as qr,resolve as Xl}from"path";import Zl from"configparser";import Kl from"@inquirer/input";import ql from"is-ci";import{constants as Rn,fstat as Yl}from"fs";import xn from"process";import{promisify as Hl}from"util";var Jl=Hl(Yl),si;async function Yr(){if(si)return si;let r=xn.stdin,e={isTTY:r.isTTY,hasData:!1,waitDelay:0,stream:r},t=await Jl(0).then(o=>{if(T("useStdin",{stat:o,isRegularFile:o.isFile(),isDirectory:o.isDirectory(),isBlockDevice:o.isBlockDevice(),isCharDevice:o.isCharacterDevice(),isSymbolicLink:o.isSymbolicLink(),isFIFO:o.isFIFO(),isSocket:o.isSocket()}),xn.platform==="win32"){if((o.mode&Rn.S_IFIFO)===Rn.S_IFIFO)return 100;if(o.isFile())return 50}return o.isFIFO()||o.isFile()||(o.isSocket()?50:!1)}).catch(()=>!1);return T("useStdin",{hasData:e.hasData,waitDelay:e.waitDelay,isTTY:e.isTTY,pipedIn:t,readableEnded:r.readableEnded}),(!r.isTTY||t!==!1&&(r.isTTY!==void 0||!r.readableEnded))&&(e.hasData=!0),typeof t=="number"&&(e.waitDelay=t),si=e,e}m(Yr,"useStdin");var ii="confirm",_n=`no-${ii}`;function Oe(r,{errorMessageForStdin:e=`Please use the --${ii}/--${_n} flags to confirm the action.`}={}){return async(t,...o)=>{let{isTTY:s,hasData:i}=await Yr(),n=t;if(ql||!s&&!i){if(typeof n.providedConfirmFromStdin>"u")throw new Error(n.errorMessageForStdin??e??`Please use the --${ii}/--${_n} flags to confirm the action.`);return n.providedConfirmFromStdin}return await r(t,...o)}}m(Oe,"stdinCheckWrapper");var at=Oe(async({message:r,validate:e,default:t})=>await Kl({message:r,validate:e,default:t}),{errorMessageForStdin:"Please provide a valid input based on the command options."});import{readFileSync as Wl}from"fs";var Hr=class{static{m(this,"Spider")}name;class_name;start_urls;pathname;constructor(e){this.name=e.name,this.class_name=e.class_name,this.start_urls=e.start_urls,this.pathname=e.pathname}};var Jr=class{static{m(this,"SpiderFileAnalyzer")}pathname;constructor(e){this.pathname=e}getSpiders(){let e=Wl(this.pathname,"utf8"),t=/class\s+(\w+)/g,o=[],s=t.exec(e);for(;s;)o.push(new Hr({class_name:s[1],pathname:this.pathname})),s=t.exec(e);return o}};var ct=class{static{m(this,"ScrapyProjectAnalyzer")}pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return Pn(qr(e,"scrapy.cfg"))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new Zl,t=Xl(qr(this.pathname,"scrapy.cfg"));if(!Pn(t))throw new Error(`scrapy.cfg not found in "${t}".
11
+ Are you sure there is a Scrapy project there?`);e.read(t),this.configuration=e}async loadSettings(){let e=this.configuration.get("settings","default").split(".")[0],t=await at({message:"Enter the Scrapy BOT_NAME (see settings.py):",default:e}),o=await at({message:"What folder are the Scrapy spider modules stored in? (see SPIDER_MODULES in settings.py):",default:`${e}.spiders`});this.settings={BOT_NAME:t,SPIDER_MODULES:typeof o=="string"?[o]:o}}getName(){return this.settings?.BOT_NAME}getAvailableSpiders(){let e=this.settings?.SPIDER_MODULES;if(!e)throw new Error("SPIDER_MODULES path not found in settings.");let t=[];for(let o of e){let s=qr(this.pathname,o.replaceAll(".","/")),i=zl(s,{withFileTypes:!0});for(let n of i)n.isFile()&&n.name.endsWith(".py")&&n.name!=="__init__.py"&&t.push(...new Jr(qr(s,n.name)).getSpiders())}return t}};import ni from"process";import{none as On,some as Nn}from"@sapphire/result";import{execa as Dn}from"execa";import Ln from"which";import{stat as Kr}from"fs/promises";import{isAbsolute as Ql,join as Wr}from"path";function Ge(r){return r?r.startsWith('"')?r:Ql(r)&&r.includes(" ")?`"${r}"`:r:null}m(Ge,"normalizeExecutablePath");async function kn(r){let e=null;return await(await Ne({cwd:r})).inspectAsync(async o=>{if(o.type===0){let[s,i,n,a]=await Promise.all([Kr(Wr(r,"yarn.lock")).then(()=>!0).catch(()=>!1),Kr(Wr(r,"pnpm-lock.yaml")).then(()=>!0).catch(()=>!1),Kr(Wr(r,"bun.lockb")).then(()=>!0).catch(()=>!1),Kr(Wr(r,"bun.lock")).then(()=>!0).catch(()=>!1)]);s?e="yarn install":i?e="pnpm install":n||a||o.runtime?.pmName==="bun"?e="bun install":o.runtime?.pmName==="deno"?e="deno install --node-modules-dir":e="npm install"}else(o.type===1||o.type===2)&&(e="python -m pip install -r requirements.txt")}),e}m(kn,"getInstallCommandSuggestion");var zr=new Map,ed={node:["--version"],deno:["eval",'"console.log(process.versions.node)"'],bun:["--eval",'"console.log(process.versions.node)"']};async function td(r,e){try{let t=await Dn(r,e,{shell:!0,windowsHide:!0,verbose:ni.env.APIFY_CLI_DEBUG?"full":void 0});return t.stdout?t.stdout.trim().replace(/^v/,""):null}catch{return null}}m(td,"getRuntimeVersion");async function rd(r){let e=await Dn(r,["--version"],{shell:!0,windowsHide:!0,verbose:ni.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim().replace(/^v/,""):null}m(rd,"getNpmVersion");async function Fn(r=ni.cwd()){let e=zr.get(r);if(e)return T("useJavaScriptRuntime",{cacheHit:!0,cwd:r,runtime:e.unwrapOr(null)}),e;for(let[t,o]of Object.entries(ed))try{let s=Ge(await Ln(t)),i=await td(s,o);if(i){let n={executablePath:s,version:i};if(t==="node"){let a=Ge(await Ln("npm").catch(()=>null));a&&(n.pmPath=a,n.pmVersion=await rd(a),n.pmName="npm")}else n.runtimeShorthand=t,n.pmPath=s,n.pmVersion=i,n.pmName=t;return zr.set(r,Nn(n)),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:zr.get(r)?.unwrap()}),Nn(n)}}catch{}return zr.set(r,On),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:null}),On}m(Fn,"useJavaScriptRuntime");import{platform as od}from"os";import{join as Un}from"path";import Xr from"process";import{none as Mn,some as jn}from"@sapphire/result";import{execa as sd}from"execa";import id from"which";var Ye=new Map;async function Bn(r){try{let e=await sd(r,["-c",'"import platform; print(platform.python_version())"'],{shell:!0,windowsHide:!0,verbose:Xr.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim():null}catch{return null}}m(Bn,"getPythonVersion");async function ir({cwd:r=Xr.cwd(),force:e=!1}={}){let t=Ye.get(r);if(t&&!e)return T("usePythonRuntime",{cacheHit:!0,cwd:r,runtime:t.unwrapOr(null)}),t;let o=od()==="win32",s=o?["Scripts","python.exe"]:["bin","python3"],i;Xr.env.VIRTUAL_ENV?i=Un(Xr.env.VIRTUAL_ENV,...s):i=Un(r,".venv",...s),i=Ge(i);try{let a=await Bn(i);if(a)return Ye.set(r,jn({executablePath:i,version:a})),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ye.get(r)?.unwrap()}),Ye.get(r)}catch{}let n=["python3","python",...o?["python3.exe","python.exe"]:[]];for(let a of n)try{let c=Ge(await id(a)),l=await Bn(c);if(l)return Ye.set(r,jn({executablePath:c,version:l})),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ye.get(r)?.unwrap()}),Ye.get(r)}catch{}return Ye.set(r,Mn),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:null}),Mn}m(ir,"usePythonRuntime");var Gn=new Map;async function Ne({cwd:r=cd.cwd()}={}){let e=Gn.get(r);if(e)return T("useCwdProject",{cacheHit:!0,project:e}),ai(e);let t={type:3},s=await m(async()=>{if(await fd(r)){t.type=2;let a=await ir({cwd:r});t.runtime=a.unwrapOr(void 0);let c=new ct(r);if(c.loadScrapyCfg(),c.configuration.hasKey("apify","mainpy_location"))t.entrypoint={path:c.configuration.get("apify","mainpy_location")};else try{let l=await Jn(r);l&&(t.entrypoint={path:l})}catch{}return}let n=await dd(r);if(!n){let a=null;try{a=await Jn(r)}catch(c){return ld({message:c instanceof Error?c.message:String(c)})}if(a){t.type=1;let c=await ir({cwd:r});t.entrypoint={path:a},t.runtime=c.unwrapOr(void 0);let l=j(r,a.replace(/\./g,"/"));await nr(j(l,"__main__.py"))||(t.warnings=[`The detected Python package "${a}" is missing __main__.py. Running with "python -m" will fail without it.`]);return}}if(n){t.type=0;let a=await Fn();t.runtime=a.unwrapOr(void 0),n.type==="file"?t.entrypoint={path:n.path}:n.type==="script"&&(t.entrypoint={script:n.script});return}return ai(t)},"check")();return s?.isErr()?(T("useCwdProject",{cacheHit:!1,error:s}),s):(T("useCwdProject",{cacheHit:!1,project:t}),Gn.set(r,t),ai(t))}m(Ne,"useCwdProject");async function dd(r){let e=j(r,"package.json");try{let o=await nd(e,"utf-8"),s=JSON.parse(o);if(s.scripts?.start)return{type:"script",script:"start"};if(s.main)try{return await ci(Vn(r,s.main)),{path:Vn(r,s.main),type:"file"}}catch{}return{type:"unknown-entrypoint"}}catch{}let t=[j(r,"index.js"),j(r,"index.mjs"),j(r,"index.cjs"),j(r,"main.js"),j(r,"main.mjs"),j(r,"main.cjs"),j(r,"src","index.js"),j(r,"src","index.mjs"),j(r,"src","index.cjs"),j(r,"src","main.js"),j(r,"src","main.mjs"),j(r,"src","main.cjs"),j(r,"dist","index.js"),j(r,"dist","index.mjs"),j(r,"dist","index.cjs"),j(r,"dist","main.js"),j(r,"dist","main.mjs"),j(r,"dist","main.cjs")];for(let o of t)try{return await ci(o),{path:o,type:"file"}}catch{}return null}m(dd,"checkNodeProject");async function nr(r){try{return await ci(r),!0}catch{return!1}}m(nr,"fileExists");async function qn(r){try{return(await ad(r)).isDirectory()}catch{return!1}}m(qn,"dirExists");function Kn(r){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)}m(Kn,"isValidPythonIdentifier");async function md(r){try{let e=await wt(r,{withFileTypes:!0});if(e.some(t=>t.isFile()&&t.name.endsWith(".py")))return!0;for(let t of e){if(!t.isDirectory()||t.name.startsWith(".")||t.name.startsWith("_"))continue;let o=j(r,t.name);try{let s=await wt(o,{withFileTypes:!0});if(s.some(i=>i.isFile()&&i.name.endsWith(".py")))return!0;if(t.name==="src"){for(let i of s)if(i.isDirectory()&&!(i.name.startsWith(".")||i.name.startsWith("_")))try{if((await wt(j(o,i.name),{withFileTypes:!0})).some(a=>a.isFile()&&a.name.endsWith(".py")))return!0}catch{}}}catch{}}return!1}catch{return!1}}m(md,"hasPythonFilesInDirOrSubdirs");async function ud(r){try{return(await wt(r,{withFileTypes:!0})).some(t=>t.isFile()&&t.name.endsWith(".py")&&t.name!=="__init__.py")}catch{return!1}}m(ud,"dirHasPyFiles");async function Yn(r){try{let e=await wt(r,{withFileTypes:!0}),t=[];for(let o of e){if(!o.isDirectory()||o.name.startsWith(".")||o.name.startsWith("_"))continue;let s=Kn(o.name),i=await nr(j(r,o.name,"__init__.py")),n=i||await ud(j(r,o.name));s&&i||n&&t.push({name:o.name,needsRename:!s,needsInit:!i})}return t}catch{return[]}}m(Yn,"findNearMissPackagesInDir");async function Hn(r){try{let e=await wt(r,{withFileTypes:!0}),t=[];for(let o of e){if(!o.isDirectory())continue;let{name:s}=o;if(s.startsWith(".")||s.startsWith("_")||!Kn(s))continue;let i=j(r,s,"__init__.py");await nr(i)&&t.push({name:s,path:j(r,s)})}return t}catch{return[]}}m(Hn,"findPackagesInDir");async function pd(r){let e=[],t=await Hn(r);e.push(...t.map(i=>i.name));let o=j(r,"src"),s=await nr(j(o,"__init__.py"));if(await qn(o)&&!s){let i=await Hn(o);e.push(...i.map(n=>`src.${n.name}`))}return e}m(pd,"discoverPythonPackages");async function Jn(r){let e=await pd(r);if(e.length===1)return e[0];if(e.length>1){let c=e.map(l=>` - ${l}`).join(`
12
+ `);throw new Error(`Multiple Python packages found:
13
+ ${c}
14
+
15
+ Apify CLI cannot determine which package to run.
16
+ Please specify the package using the --entrypoint flag, e.g.:
17
+ apify run --entrypoint <package_name>`)}let t=await Yn(r),o=j(r,"src"),i=!await nr(j(o,"__init__.py"))&&await qn(o)?await Yn(o):[],n=[...t.map(c=>({...c,prefix:""})),...i.map(c=>({...c,prefix:"src/"}))];if(n.length>0){let c=n.map(({name:l,prefix:d,needsRename:u,needsInit:p})=>{let f=[];return u&&f.push(`rename to "${d}${l.replace(/[^a-zA-Z0-9_]/g,"_")}/"`),p&&f.push("add __init__.py"),` - "${d}${l}/" \u2192 ${f.join(" and ")}`}).join(`
18
+ `);throw new Error(`Found directories that appear to be Python packages but have issues:
19
+ ${c}
20
+
21
+ A valid Python package requires a directory with a valid identifier name (letters, numbers, underscores) and an __init__.py file.`)}if(await md(r))throw new Error(`No Python package found. Found Python files, but no valid package structure detected.
22
+ A Python package requires:
23
+ - A directory with a valid Python identifier name (letters, numbers, underscores)
24
+ - An __init__.py file inside the directory
25
+
26
+ Common package structures:
27
+ my_package/
28
+ __init__.py
29
+ main.py
30
+
31
+ src/
32
+ my_package/
33
+ __init__.py
34
+ main.py`);return null}m(Jn,"checkPythonProject");async function fd(r){return ct.isApplicable(r)}m(fd,"checkScrapyProject");import K from"chalk";import lt from"chalk";import Zn from"indent-string";import vd from"widest-line";import Qn from"wrap-ansi";import Zr from"chalk";import mi from"indent-string";import gd from"string-width";import zn from"strip-ansi";import Xn from"widest-line";import ui from"wrap-ansi";import At from"chalk";import li from"indent-string";import Wn from"string-width";import di from"wrap-ansi";var He;function se(){if(He)return He;let r=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(r))He=r;else if(!process.stdout.isTTY)He=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;e<1?He=80:e<40?He=40:He=e}return He}m(se,"getMaxLineWidth");var vt=class{static{m(this,"BaseCommandRenderer")}command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let t=this.command.interactive?`${At.yellow("[INTERACTIVE]")} `:"";this.command.shortDescription?e.push(`${t}${this.command.shortDescription}`,""):this.command.description&&e.push(`${t}${this.command.description.split(`
35
+ `)[0]}`,"")}pushDescription(e){if(!this.command.description)return;e.push(At.bold("DESCRIPTION"));let t=di(this.command.description,se()-2,{trim:!1}),o=li(t,2);e.push(o),e.push("")}pushExamples(e){let{examples:t}=this.command;if(t?.length){e.push(At.bold("EXAMPLES"));for(let o of t){if(o.description){let i=di(o.description,se()-4,{trim:!1}).split(`
36
+ `).map(a=>`# ${a}`).join(`
37
+ `),n=li(i,2);e.push(At.dim(n))}e.push(` $ ${this.normalizeExampleCommand(o.command)}`),e.push("")}}}normalizeExampleCommand(e){let t=this.entrypoint.split(" ");if(t.length<2)return e;let o=t[t.length-1],s=`${t.slice(0,-1).join(" ")} `,i=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=e;return n.startsWith(`${o} `)&&(n=`${s}${n}`),n=n.replace(new RegExp(`\\|\\s+${i}\\s`,"g"),`| ${s}${o} `),n}pushInteractiveNote(e){if(!this.command.interactive)return;e.push(At.bold("NOTE"));let o=this.command.interactiveNote||"This command prompts the user for input. To run non-interactively (e.g. in CI or from an AI agent), pass all required arguments and flags explicitly.",s=di(o,se()-2,{trim:!1}),i=li(s,2);e.push(i),e.push("")}pushLearnMore(e){this.command.docsUrl&&(e.push(At.bold("LEARN MORE")),e.push(` ${this.command.docsUrl}`),e.push(""))}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:o}){let s=Wn(e.join(" ").split(`
38
+ `).at(-1)||"")+o,i=Wn(t);s+i>se()&&e.push(`
39
+ `),e.push(t)}kebabFlagName(e){return Ee($e(e)).toLowerCase()}makeFlagString(e,t){let o=this.kebabFlagName(e),s=t.char?`-${t.char}`:`--${o}`;switch(t.flagTag){case"boolean":return s;case"string":case"integer":{let i=t.choices?.length?`${t.choices.join("|")}`:"<value>";return`${s} ${i}`}default:throw new RangeError(`Unhandled flag type: ${t.flagTag}`)}}};var Qr=class extends vt{static{m(this,"CommandHelp")}render(){let e=[];return this.pushShortDescription(e),this.pushUsageString(e),this.command.description&&this.pushDescription(e),this.pushExamples(e),this.pushInteractiveNote(e),this.pushLearnMore(e),e.join(`
40
+ `).trim()}selectiveRender(e){let t=[];return e.showShortDescription&&this.pushShortDescription(t),e.showUsageString&&this.pushUsageString(t),e.showDescription&&this.command.description&&this.pushDescription(t),e.showExamples&&this.pushExamples(t),e.showLearnMore&&this.pushLearnMore(t),t.join(`
41
+ `).trim()}pushUsageString(e){e.push(Zr.bold("USAGE"));let t=`$ ${this.entrypoint} ${this.command.name}`,o=2+gd(t),s=[t],i=Object.entries(this.command.args??{});if(i.length)for(let[u,p]of i){if(typeof p=="string")throw new RangeError("This is a type-check only value, do not actually use it");this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:p.required?`<${u}>`:`[${u}]`,indentSize:o})}let n=Object.entries(this.command.flags??{}).filter(([,u])=>{if(typeof u=="string")throw new RangeError("This is a type-check only value, do not actually use it");return!u.hidden});this.command.enableJsonFlag&&n.push(["json",{choices:null,flagTag:"boolean",hasDefault:!1,required:!1,stdin:null,builder:null,aliases:void 0,char:void 0,description:"Format the command output as JSON",hidden:void 0,exclusive:void 0}]);let a=new Map(n.sort((u,p)=>{if(typeof u[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(typeof p[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");return u[1].required&&!p[1].required?-1:!u[1].required&&p[1].required?1:u[0].localeCompare(p[0])})),c=new Set;if(n.length)for(let[u,p]of a){if(typeof p=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(c.has(u))continue;let f=p.required,v=[this.makeFlagString(u,p)];if(p.exclusive?.length)for(let S of p.exclusive){c.add(S);let E=a.get(S),C=this.makeFlagString(S,E);v.push(C),E.required&&(f=!0)}this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:f?v.join(" | "):`[${v.join(" | ")}]`,indentSize:o})}let l=ui(s.join(" "),se()-o),d=mi(l,o+1).trim();e.push(` ${d}`,""),i.length&&this.pushArguments(e,i),n.length&&this.pushFlags(e,a)}pushArguments(e,t){if(!t.length)return;e.push(Zr.bold("ARGUMENTS"));let o=Xn(t.map(([s])=>s).join(`
42
+ `));for(let[s,i]of t){let n=`${s.padEnd(o)} ${i.description}`,a=ui(n,se()-o-2),c=mi(a,o+2+2).trim();e.push(` ${c}`)}e.push("")}pushFlags(e,t){if(!t.size)return;e.push(Zr.bold("FLAGS"));let o=new Map;for(let[i,n]of t){let a=[];switch(n.char?a.push(`-${n.char},`):a.push(" ".repeat(3)),n.flagTag){case"boolean":a.push(`--${this.kebabFlagName(i)}`);break;case"string":case"integer":{let c=n.choices?"<option>":"<value>";a.push(`--${this.kebabFlagName(i)}=${Zr.underline(c)}`);break}default:throw new Error(`Unhandled flag tag: ${n.flagTag}`)}o.set(a.join(" "),n)}let s=Xn([...o.keys()].map(zn).join(`
43
+ `));for(let[i,n]of o){let a=s-zn(i).length,c=`${i}${" ".repeat(a)} ${n.description??""}`;n.choices?.length&&(c+=`
44
+ <options: ${n.choices.join("|")}>`);let l=ui(c,se()-s),d=mi(l,s).trim().split(`
45
+ `).map(u=>/^-[a-z]/.test(u.trim())?u:` ${u}`).join(`
46
+ `);e.push(` ${d}`)}e.push("")}};import hd from"chalk";import yd from"indent-string";import wd from"widest-line";import Ad from"wrap-ansi";var eo=class extends vt{static{m(this,"CommandWithSubcommandsHelp")}render(){let e=[];return this.pushShortDescription(e),this.command.description&&this.pushDescription(e),this.pushSubcommands(e),this.pushExamples(e),this.pushInteractiveNote(e),this.pushLearnMore(e),e.join(`
47
+ `).trim()}selectiveRender(e){let t=[];return e.showShortDescription&&this.pushShortDescription(t),e.showDescription&&this.command.description&&this.pushDescription(t),e.showSubcommands&&this.pushSubcommands(t),e.showExamples&&this.pushExamples(t),e.showLearnMore&&this.pushLearnMore(t),t.join(`
48
+ `).trim()}pushSubcommands(e){if(!this.command.subcommands?.length)return;e.push(hd.bold("SUBCOMMANDS"));let t=wd(this.command.subcommands.map(o=>`${this.command.name} ${o.name}`).join(`
49
+ `));for(let o of this.command.subcommands){let s=o.shortDescription||o.description?.split(`
50
+ `)[0]||"",i=`${this.command.name} ${o.name.padEnd(t-this.command.name.length-1)} ${s}`,n=Ad(i,se()-t-2),a=yd(n,t+2+2).trim();e.push(` ${a}`)}e.push("")}};var ar=new Map;function pi(r,e){if(e.name.toLowerCase()!==e.name){g({message:`Command name "${e.name}" is not correctly set up internally. Make sure you fill out the "name" field in the command class extension.`});return}if(e.subcommands?.length){ar.set(e,new eo(r,e));for(let t of e.subcommands)pi(`${r} ${e.name}`,t)}else ar.set(e,new Qr(r,e))}m(pi,"registerCommandForHelpGeneration");function ro(r){let e=ar.get(r);if(!e)throw new Error(`No help renderer found for command ${r.name}`);return e.render()}m(ro,"renderHelpForCommand");function oo(r,e){let t=ar.get(r);if(!t)throw new Error(`No help renderer found for command ${r.name}`);return t.selectiveRender(e)}m(oo,"selectiveRenderHelpForCommand");function bd(r,e){return r[0].name.localeCompare(e[0].name)}m(bd,"sortByName");var ea=["Local Actor Development","Apify Console","Authentication","Utilities"],to="Other",Sd=[{command:"apify login"},{description:"Walks you interactively through the Actor creation flow.",command:"apify create"},{command:"apify run"},{command:"apify push"},{command:'apify actors search "web scraper"'}],Td=[{command:"actor get-input"},{command:`actor push-data '{"url":"https://example.com"}'`},{command:`actor set-value OUTPUT '{"done":true}'`}];function so(r){let e=z(),t=[];r==="actor"?t.push("'actor' is the runtime CLI baked into Apify Actor Docker images. It exposes a reduced command set intended for use from inside a running Actor. When available, these commands are equivalent to 'apify actor <subcommand>'.",""):t.push("Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",""),t.push(lt.bold("VERSION")),t.push(` ${e.fullVersionString}`),t.push(""),t.push(lt.bold("USAGE")),t.push(` $ ${r} <command> [options]`),t.push("");let o=[];for(let[u,p]of ar)p.entrypoint.includes(" ")||u.hidden||o.push([u,p]);let s=new Map;for(let u of o){let[p]=u,f=p.group||to;s.has(f)||s.set(f,[]),s.get(f).push(u)}for(let u of s.values())u.sort(bd);let i=[];for(let u of ea)s.has(u)&&i.push(u);let n=[...s.keys()].filter(u=>!ea.includes(u)&&u!==to).sort();i.push(...n),s.has(to)&&i.push(to);let a=o.map(([u])=>u.name).join(`
51
+ `),c=vd(a)||1,l=m(([u])=>{let p=u.shortDescription||u.description?.split(`
52
+ `)[0]||"",y=`${u.name.padEnd(c)} ${p}`,v=Qn(y,se()-c-4);return` ${Zn(v,c+2+2).trim()}`},"renderEntry");for(let u of i){let p=s.get(u);p.length&&(t.push(lt.bold(u.toUpperCase())),t.push(...p.map(l),""))}let d=r==="actor"?Td:Sd;if(d.length){t.push(lt.bold("EXAMPLES"));for(let u=0;u<d.length;u++){let p=d[u];if(p.description){u>0&&t.push("");let y=Qn(p.description,se()-4,{trim:!1}).split(`
53
+ `).map(v=>`# ${v}`).join(`
54
+ `);t.push(lt.dim(Zn(y,2)))}t.push(` $ ${p.command}`),p.description&&u<d.length-1&&t.push("")}t.push("")}return t.push(lt.bold("LEARN MORE"),` Use '${r} <command> --help' for more information about a command.`," Read the docs at https://docs.apify.com/cli.",""),t.push(lt.bold("TROUBLESHOOTING")," For general support, reach out to us at https://apify.com/contact."," If you believe you are encountering a bug, file it at https://github.com/apify/apify-cli/issues/new."),t.join(`
55
+ `).trim()}m(so,"renderMainHelpMenu");var io=(d=>(d[d.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]="NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE",d[d.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]="NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL",d[d.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]="NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION",d[d.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]="APIFY_FLAG_PROVIDED_MULTIPLE_TIMES",d[d.APIFY_INVALID_FLAG_INTEGER_VALUE=4]="APIFY_INVALID_FLAG_INTEGER_VALUE",d[d.APIFY_INVALID_CHOICE=5]="APIFY_INVALID_CHOICE",d[d.APIFY_MISSING_FLAG=6]="APIFY_MISSING_FLAG",d[d.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]="APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG",d[d.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]="APIFY_TOO_MANY_REQUESTERS_OF_STDIN",d[d.APIFY_UNKNOWN_ERROR=9]="APIFY_UNKNOWN_ERROR",d))(io||{}),pe=class r extends Error{static{m(this,"CommandError")}code;command;metadata;constructor({code:e,message:t="",metadata:o={},command:s}){super(t||String(io[e])),this.code=e,this.metadata=o,this.command=s}extractFlagNameFromMessage(){switch(this.code){case 0:{let e=/'(?:-[a-z], )?-?-(?<flagName>[a-zA-Z-]+)(?: <value>)?' (?<noArg>does not take)?(?<missingArg>argument missing)?(?<ambiguous>argument is ambiguous\.(?<ambiguousMessage>\s*.*\s*.*)?)?/gi.exec(this.message);if(!e)throw new Error(`Encountered unparsable error message from argument parser: ${this.message}.
56
+
57
+ Please report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.flagName,expectsValue:e.groups.noArg===void 0,ambiguousFlag:e.groups.ambiguous?e.groups.ambiguous:void 0,ambiguousMessage:e.groups.ambiguousMessage?e.groups.ambiguousMessage.trim():void 0}}case 2:{let e=/Unknown option '-(?<longForm>-)?(?<optionName>.+)'\.(?<nodeSuggestion>.*)/gi.exec(this.message);if(!e)throw new Error(`Encountered unparsable error message from argument parser: ${this.message}.
58
+
59
+ Please report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.optionName,expectsValue:!1,unknownOptionSuggestion:e.groups.nodeSuggestion,shortForm:!e.groups.longForm}}default:throw new Error("Not implemented")}}getPrettyMessage(){switch(this.code){case 0:{let e=this.extractFlagNameFromMessage();return r.buildMessageFromFlagData(e)}case 2:{let e=this.extractFlagNameFromMessage(),t=oo(this.command,{showUsageString:!0});return[K.gray(`Unknown flag provided: ${K.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`),e.unknownOptionSuggestion?K.gray(` ${e.unknownOptionSuggestion.trim()}`):null,"",t].filter(o=>o!==null).join(`
60
+ `)}case 3:{let e=`--${this.metadata.flag}`;return K.gray(`Flag ${K.white.bold(e)} can only be specified once.`)}case 4:{let e=`--${this.metadata.flag}`,t=K.whiteBright(String(this.metadata.value));return K.gray(`The provided value for the '${K.white.bold(e)}' flag could not be processed as an integer. Received: ${t}.`)}case 6:{let{flag:e,matcher:t,providedButReceivedNoValue:o}=this.metadata,s=`'${K.white.bold(`--${e}`)}'`;return t&&(s=`${s} (alias used: '${K.white.bold(`--${t}`)}')`),o?K.gray(`Flag ${s} was provided, but no value was received. Did you mean to pass the value as an argument or through standard input?`):K.gray(`Flag ${s} is required, but was not provided.`)}case 7:{let{flagPairs:e}=this.metadata,t=[K.gray("The following errors occurred:")],o=K.red(" > ");for(let[s,i]of e)t.push(K.gray(`${o}${K.white.bold(s)} cannot also be provided when using ${K.white.bold(i)}`));return t.push(K.gray(`${o}See more help with ${K.white.bold("--help")}`)),t.join(`
61
+ `)}case 8:{let{firstUse:e,secondUse:t}=this.metadata;return K.gray(`Flag ${K.white.bold(`--${e}`)} and ${K.white.bold(`--${t}`)} cannot both request that their value comes from standard input at the same time.`)}default:{let e=z();return["The CLI encountered an unhandled argument parsing error!","Please report this issue at https://github.com/apify/apify-cli/issues, and provide the following information:","",`- Error code: ${this.code} (${io[this.code]})`,`- Error metadata: ${JSON.stringify(this.metadata)}`,"",`- Stack:
62
+ ${this.stack}`,"","- Arguments (!!!only provide these as is if there is no sensitive information!!!):",` ${JSON.stringify(process.argv.slice(2))}`,"",`- CLI version: \`${e.fullVersionString}\``,`- CLI debug logs (process.env.APIFY_CLI_DEBUG): ${process.env.APIFY_CLI_DEBUG?"Enabled":"Disabled"}`,`- Stdin data? ${Re?"Yes":"No"}`].join(`
63
+ `)}}}static buildMessageFromFlagData(e){let t=[`Flag ${K.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`];return e.ambiguousFlag?(t.push("is ambiguous (meaning the provided value could be interpreted as a flag too)."),e.ambiguousMessage?t.push(`
64
+ ${e.ambiguousMessage.split(`
65
+ `).map(o=>` ${o}`).join(`
66
+ `)}`):t.push(`To solve this, provide the flag like this: --${e.name}=<value>`)):e.expectsValue?t.push("expects a value"):t.push("does not take an argument"),t.map(o=>K.gray(o)).join(" ")}static into(e,t){if(e instanceof r)return e;if(e instanceof Error&&"code"in e){let o=e;switch(o.code){case"ERR_PARSE_ARGS_INVALID_OPTION_VALUE":return new r({code:0,message:o.message,command:t});case"ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL":return new r({code:1,message:o.message,command:t});case"ERR_PARSE_ARGS_UNKNOWN_OPTION":return new r({code:2,message:o.message,command:t});default:return new r({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}}return new r({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}};function ta(r){return r.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}m(ta,"camelCaseString");function Ee(r){return r.replace(/[\s_]+/g,"-")}m(Ee,"kebabCaseString");function $e(r){return r.replace(/([A-Z])/g,"-$1").toLowerCase()}m($e,"camelCaseToKebabCase");var $d={type:"boolean",multiple:!1,short:"h"},Rd={type:"boolean",multiple:!1},W=new Map,xd=["init","run","push","actors push","pull","actors pull","call","actors call","actors start"],h=class{static args;static flags;static subcommands;static enableJsonFlag=!1;static name;static shortDescription;static description;static examples;static docsUrl;static interactive;static interactiveNote;static group;static aliases;static hidden;static hiddenAliases;telemetryData={};flags;args;entrypoint;commandString;aliasUsed;subcommandAliasUsed;skipTelemetry=!1;constructor(e,t,o,s){this.entrypoint=e,this.commandString=t,this.aliasUsed=o,this.subcommandAliasUsed=s;let i=z();this.telemetryData.installMethod=i.installMethod,this.telemetryData.osArch=i.arch,this.telemetryData.runtime=i.runtime.runtime,this.telemetryData.runtimeVersion=i.runtime.version,this.telemetryData.runtimeNodeVersion=i.runtime.nodeVersion??i.runtime.version,this.telemetryData.commandString=t,this.telemetryData.entrypoint=e;let n=Wi();this.telemetryData.aiAgent=Ki(),this.telemetryData.isCi=n.isCi,this.telemetryData.ciProvider=n.ciProvider,this.telemetryData.isInteractive=zi()}get ctor(){return this.constructor}pluralString(e,t,o){return e===1?t:o}static printHelp(){console.log(ro(this)),process.exit(0)}printHelp(){return this.ctor.printHelp()}async _run(e){let t=Date.now(),{values:o,positionals:s,tokens:i}=e;o.help&&this.ctor.printHelp(),this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof o.json=="boolean"?this.flags.json=o.json:this.flags.json=!1);let n=new Map;if(this.ctor.args){let a=0;for(let[c,l]of Object.entries(this.ctor.args)){if(typeof l=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let d=ta(c),u=s[a++];if(u)switch(l.argTag){default:this.args[d]=String(u),u==="-"&&l.stdin&&(this.args[d]=this._handleStdin(l.stdin)),l.catchAll&&(this.args[d]=s.slice(a-1).join(" "));break}else l.required&&n.set(c,l)}}if(n.size){process.exitCode=1,this._printMissingRequiredArgs(n);return}this._parseFlags(o,i);try{await this.run()}catch(a){g({message:a.message}),process.exitCode||=1}finally{!this.telemetryData.actorLanguage&&xd.includes(this.commandString)&&(await Ne()).inspect(c=>{c.type===0?(this.telemetryData.actorLanguage="javascript",this.telemetryData.actorRuntime=c.runtime.runtimeShorthand||"node",this.telemetryData.actorRuntimeVersion=c.runtime.version):(c.type===1||c.type===2)&&(this.telemetryData.actorLanguage="python",this.telemetryData.actorRuntime="python",this.telemetryData.actorRuntimeVersion=c.runtime.version)}),this.skipTelemetry||(this.telemetryData.flagsUsed=Object.keys(this.flags),this.telemetryData.exitCode=typeof process.exitCode=="number"?process.exitCode:0,this.telemetryData.durationMs=Date.now()-t,this.telemetryData.wasRetried=await Cn(this.commandString),await $n(`cli_command_${this.commandString.replaceAll(" ","_").toLowerCase()}`,this.telemetryData))}}_userFlagNameToRegisteredName(e,t){let o=Ee($e(e)).toLowerCase(),s=o;o.startsWith("no-")&&(s=o.slice(3));let i=new Set;for(let n of t.aliases??[])i.add(Ee($e(n)).toLowerCase());return{baseFlagName:s,rawBaseFlagName:o,allMatchers:[s,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=Ee($e(e)).toLowerCase();return t.startsWith("no-")&&(t=t.slice(3)),t}_parseFlags(e,t){if(!this.ctor.flags)return;let o=new Map,s;for(let[n,a]of Object.entries(this.ctor.flags)){if(typeof a=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let{allMatchers:c,baseFlagName:l,rawBaseFlagName:d}=this._userFlagNameToRegisteredName(n,a),u=ta(d),p=t.some(v=>v.kind==="option"&&v.name===l);if(a.exclusive?.length){let v=o.get(l)??new Set;for(let S of a.exclusive)v.add(this._commandFlagKeyToKebabCaseRegisteredName(S));o.set(l,v);for(let S of a.exclusive){let E=this._commandFlagKeyToKebabCaseRegisteredName(S),C=o.get(E)??new Set;C.add(l),o.set(E,C)}}let f=c.filter(v=>e[v]);if(f.length>1)throw new pe({code:3,command:this.ctor,metadata:{flag:l}});let y=e[f[0]];if(!y&&a.required)throw new pe({code:6,command:this.ctor,metadata:{flag:l,matcher:f[0]}});if(Array.isArray(y)){if(y.length>1)throw new pe({code:3,command:this.ctor,metadata:{flag:l}});y=y[0]}if(p&&typeof y=="string"&&y.startsWith("=")&&(y=y.slice(1)),typeof y<"u")switch(a.flagTag){case"boolean":{this.flags[u]=d.startsWith("no-")?!y:y;break}case"integer":{let v=Number(y);if(Number.isNaN(v)||!Number.isInteger(v))throw new pe({code:4,command:this.ctor,metadata:{flag:l,value:String(y)}});this.flags[u]=v;break}default:{if(this.flags[u]=y,y==="-"&&a.stdin){if(s)throw new pe({code:8,command:this.ctor,metadata:{firstUse:s,secondUse:l}});s=l,this.flags[u]=this._handleStdin(a.stdin)}break}}else typeof a.hasDefault<"u"&&(this.flags[u]=a.hasDefault);if(this.flags[u]&&a.choices&&!a.choices.includes(this.flags[u]))throw new pe({code:5,command:this.ctor,metadata:{flag:l,choices:a.choices.map(v=>fi.white.bold(v)).join(", ")}});if(this.flags[u]==null&&(a.required||y!=null))throw new pe({code:6,command:this.ctor,metadata:{flag:l,matcher:f[0],providedButReceivedNoValue:!!y}})}let i=[];for(let[n,a]of o)if(e[n]!=null)for(let c of a){if(e[c]==null)continue;let l=e[n][0],d=e[c][0],u=m((p,f)=>typeof f=="boolean"?f?`--${p}`:`--no-${p}`:`--${p}=${f}`,"flagRepresentation");i.push([u(n,l),u(c,d)]);break}if(i.length)throw new pe({code:7,command:this.ctor,metadata:{flagPairs:i}})}_printMissingRequiredArgs(e){let t;try{t=oo(this.ctor,{showUsageString:!0})}catch{}let o=Id([...e.keys()].join(`
67
+ `)),s=[];for(let[n,a]of e){let c=`${n.padEnd(o)} ${a.description}`,l=Ed(c,se()-o-2),d=Cd(l,o+2+2).trim();s.push(` ${fi.red(">")} ${d}`)}let i=[`Missing ${e.size} required ${this.pluralString(e.size,"argument","arguments")}:`,...s,fi.gray(" See more help with --help")];t&&i.push("",t),g({message:i.join(`
68
+ `)})}_handleStdin(e){return e===2?(Re?.toString("utf8")??"").trim():Re}_buildParseArgsOption(){let e={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:{help:$d}};if(this.ctor.flags)for(let[t,o]of Object.entries(this.ctor.flags)){if(typeof o=="string")throw new RangeError("Do not provide the string for the json flag! It is a type level assertion!");if(t.toLowerCase()==="json")continue;let s=Ee($e(t)).toLowerCase();s.startsWith("no-")&&(s=s.slice(3));let i=o.builder(s);for(let{flagName:n,option:a}of i)e.options[n]=a}return this.ctor.enableJsonFlag&&(e.options.json=Rd),e}static registerCommand(e){if(pi(e,this),W.set(this.name,this),this.aliases?.length)for(let t of this.aliases)W.set(t,this);if(this.hiddenAliases?.length)for(let t of this.hiddenAliases)W.set(t,this);if(this.subcommands?.length)for(let t of this.subcommands){if(W.set(`${this.name} ${t.name}`,t),this.aliases?.length)for(let o of this.aliases)W.set(`${o} ${t.name}`,t);if(this.hiddenAliases?.length)for(let o of this.hiddenAliases)W.set(`${o} ${t.name}`,t);if(t.aliases?.length)for(let o of t.aliases){if(W.set(`${this.name} ${o}`,t),this.aliases?.length)for(let s of this.aliases)W.set(`${s} ${o}`,t);if(this.hiddenAliases?.length)for(let s of this.hiddenAliases)W.set(`${s} ${o}`,t)}if(t.hiddenAliases?.length)for(let o of t.hiddenAliases){if(W.set(`${this.name} ${o}`,t),this.aliases?.length)for(let s of this.aliases)W.set(`${s} ${o}`,t);if(this.hiddenAliases?.length)for(let s of this.hiddenAliases)W.set(`${s} ${o}`,t)}}}};async function ra(r,e,t){let o={positionals:[],values:{},tokens:[]},s=0;for(let[n,a]of Object.entries(t)){let[c,l]=n.split("_");if(c==="args")o.positionals[s++]=a;else{let d=Ee($e(l)).toLowerCase();d.startsWith("no-")?o.values[d.slice(3)]=!a:o.values[d]=a}}let i=new e(r,e.name,e.name);i.skipTelemetry=!0,await i._run(o)}m(ra,"internalRunCommand");import{once as _d}from"events";async function oa(){let r=await Yr(),{hasData:e,waitDelay:t,stream:o}=r;if(!e)return;let s=[],i=new AbortController,n=null;t&&(n=setTimeout(()=>{i.abort()},t).unref()),o.on("data",c=>{s.push(c),n&&(clearTimeout(n),n=null)});try{await _d(o,"end",{signal:i.signal})}catch(c){if(c.name==="AbortError")return}n&&clearTimeout(n),r.hasData=!1;let a=Buffer.concat(s);if(a.length)return a}m(oa,"readStdin");import{gt as Ud}from"semver";import{existsSync as Pd,mkdirSync as kd,readFileSync as Od,writeFileSync as Nd}from"fs";import{dirname as Ld}from"path";function Dd(r){if(r.version&&r.version>=1)return!1;let e=r;if(e.latestNpmVersionCheckedAt){let t=new Date(e.latestNpmVersionCheckedAt).getTime(),o=e.latestNpmVersion;T("LocalStateV0ToV1","Migrating state from v0 to v1",{oldState:r,newState:{versionCheck:{lastChecked:t,lastVersion:o}}}),hi({version:1},s=>{s.versionCheck={lastChecked:t,lastVersion:o}})}return!0}m(Dd,"migrateStateV0ToV1");var Fd={version:1};function gi(){let r=Er();if(!Pd(r))return Fd;let t=JSON.parse(Od(r,"utf-8"));return Dd(t)?gi():t}m(gi,"useLocalState");function hi(r,e){let t={...r};e(t);let o=Er(),s=Ld(o);kd(s,{recursive:!0}),Nd(Er(),JSON.stringify(t,null," "))}m(hi,"updateLocalState");var no=z(),sa=`Apify CLI/${no.version} (https://github.com/apify/apify-cli)`,Md=["https://1.1.1.1","https://8.8.8.8"];async function jd(r=500){let e=new AbortController,t=setTimeout(()=>{e.abort()},r),o=await Promise.any(Md.map(async s=>fetch(s,{signal:e.signal,headers:{"User-Agent":sa},keepalive:!1}))).catch(()=>null);return clearTimeout(t),o?o.ok?(T("isOnline",{state:"online",site:o.url}),!0):(T("isOnline",{state:"offline"}),!1):(T("isOnline",{state:"timeout"}),!1)}m(jd,"isOnline");async function Bd(r){let e=await fetch("https://api.github.com/repos/apify/apify-cli/releases/latest",{headers:{"User-Agent":sa}});if(!e.ok)return T("useCLIVersionCheck","Failed to fetch latest version",{statusCode:e.status,body:await e.text()}),x({message:"Failed to fetch latest version of Apify CLI, using the cached version instead."}),null;let o=(await e.json()).tag_name.replace(/^v/,"");return T("useCLIVersionCheck","Fetched latest version",{version:o}),hi(r,s=>{s.versionCheck={lastChecked:Date.now(),lastVersion:o}}),o}m(Bd,"getLatestVersion");function ia(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&!["0","false"].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}m(ia,"shouldSkipVersionCheck");async function na(r=!1){let e=gi(),t=!e.versionCheck||Date.now()-e.versionCheck.lastChecked>Zi,o=r||t&&await jd(),s=o?await Bd(e):e.versionCheck?.lastVersion;if(!s)return{currentVersion:no.version,latestVersion:"unknown",shouldUpdate:!1,cacheHit:!1};let i=Ud(s,no.version);return{currentVersion:no.version,latestVersion:s,shouldUpdate:i,cacheHit:!o}}m(na,"useCLIVersionCheck");import{jaroWinkler as Vd}from"@skyra/jaro-winkler";import Gd from"js-levenshtein";function ao(r){let e=[...W.entries()].sort(([s],[i])=>s.localeCompare(i)),t=r.toLowerCase();return e.map(([s,i])=>{let n=s.toLowerCase(),a=s.split(" "),c=a[a.length-1].toLowerCase(),l=i.aliases?.includes(c)||i.hiddenAliases?.includes(c)||!1,d=Gd(t,n),u=Vd(t,n),p=d<=2||u>=.975;return p?(T("useCommandSuggestions",{inputString:t,lowercased:n,matches:p,levenshtein:d,jaroWinkler:u}),l?{string:`${n} (alias for ${i.name})`,distance:u}:{string:`${n}`,distance:u}):null}).filter(s=>s!==null).sort((s,i)=>i.distance-s.distance).map(s=>s.string)}m(ao,"useCommandSuggestions");var Re=await oa(),cr=z(),nt=`Apify CLI/${cr.version} (https://github.com/apify/apify-cli)`;function vw(r){cr.installMethod!=="bundle"&&(Yd(xe.version,Ie)||(g({message:`${r} CLI requires Node.js version ${Ie}. Your current version is ${xe.version}.`}),xe.exit(1)))}m(vw,"processVersionCheck");function Hd(r){r.values.version===!0&&r.positionals.length===0&&(console.log(cr.fullVersionString),xe.exit(0))}m(Hd,"printCLIVersionAndExitIfFlagUsed");function Jd(r,e){(r.values.help===!0&&r.positionals.length===0||r.positionals.length===0)&&(console.log(so(e)),xe.exit(0))}m(Jd,"printHelpAndExitIfFlagUsedOrNoCommandPassed");function ca(r){let e=ao(String(r)),t=co.gray(`Command ${co.whiteBright(r)} not found`);e.length&&(t+=`
69
+ `,t+=co.gray(`Did you mean: ${e.map(o=>co.whiteBright(o)).join(", ")}?`)),g({message:t}),xe.exit(1)}m(ca,"handleCommandNotFound");async function qd(r,e){let t=W.get("upgrade");if([t.name,...t.aliases??[]].some(s=>e===s)){T("[VersionCheckMiddleware]","upgrade command detected, skipping version check");return}if(ia()){T("[VersionCheckMiddleware]","skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set");return}await ra(r,t,{flags_internalAutomaticCall:!0})}m(qd,"runVersionCheck");async function bw(r){T("CLIMetadata",{...cr,fullVersionString:cr.fullVersionString,argv:xe.argv,cwd:xe.cwd(),execPath:xe.execPath});let e=xe.argv.slice(2);T("ProcessArgv",e);let t=aa({allowPositionals:!0,strict:!1,options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}},args:e});Hd(t),Jd(t,r),await qd(r,t.positionals[0]),T("TopLevelOptions",t);let o=t.positionals[0],s=-1;if(W.get(o)?.subcommands?.length){if(t.positionals[1]?.toLowerCase()==="help")s=1;else if(t.positionals[2]?.toLowerCase()==="help"){let y=W.get(`${o} ${t.positionals[1]}`);y&&!y.args&&(s=2)}}if(s!==-1){let y=t.positionals[s],v=e.indexOf(y);v!==-1&&e.splice(v,1),!e.includes("--help")&&!e.includes("-h")&&e.push("--help"),t.positionals.splice(s,1),t.values.help=!0}let n=t.positionals[1],a=!1,c=W.get(o);if(!c)return ca(o);let l=c;if(c.subcommands?.length){if(!n)return c.printHelp();a=!0,l=W.get(`${o} ${n}`)}if(!l)return ca(`${o} ${n}`);let d=[...e],u=d.indexOf(o);if(T("CommandNameIndex",u),d.splice(u,1),a){let y=d.indexOf(n);T("SubcommandNameIndex",y),d.splice(y,1)}T("RebuiltArgs",d),T("CommandToRun",l);let p=new l(r,a?`${c.name} ${n}`:c.name,o,a?n:void 0),f=p._buildParseArgsOption();T("ParserOptionsForCommand",f);try{let y=aa({...f,args:d});await p._run(y),T("CommandArgsResult",y)}catch(y){let v=pe.into(y,l);g({message:v.getPrettyMessage()}),xe.exit(1)}}m(bw,"runCLI");import{join as um,resolve as pm}from"path";import wi from"process";import{calculateRunDynamicMemory as fm}from"@apify/actor-memory-expression";var w={string:Kd,boolean:Wd,integer:zd},ie={yes:w.boolean({char:"y",description:'Automatic yes to prompts; assume "yes" as answer to all prompts.',default:!1})};function Kd(r){return{flagTag:"string",builder:m(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"string",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Ee($e(s)).toLowerCase(),option:{type:"string",multiple:!0}});return o},"builder"),choices:r.choices,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??2,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}m(Kd,"stringFlag");function Wd(r){return{flagTag:"boolean",builder:m(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"boolean",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Ee($e(s)).toLowerCase(),option:{type:"boolean",multiple:!0}});return o},"builder"),choices:null,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??1,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}m(Wd,"booleanFlag");function zd(r){return{flagTag:"integer",builder:m(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"string",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Ee($e(s)).toLowerCase(),option:{type:"string",multiple:!0}});return o},"builder"),choices:null,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??1,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}m(zd,"integerFlag");import{mkdir as rm,rename as pa,writeFile as om}from"fs/promises";import{dirname as sm,join as im}from"path";import ua from"process";import{inspect as nm}from"util";import{err as dr,ok as mo}from"@sapphire/result";import{createPrompt as Xd,isEnterKey as Zd,makeTheme as Qd,useKeypress as em,usePrefix as tm,useState as la}from"@inquirer/core";function yi(r,e){let t=e!==!1;return/^(y|yes)/i.test(r)?t=!0:/^(n|no)/i.test(r)&&(t=!1),t}m(yi,"getBooleanValue");function da(r){return r?"Yes":"No"}m(da,"boolToString");var ma=Xd((r,e)=>{let t=da,[o,s]=la("idle"),[i,n]=la(""),a=Qd(),c=tm({status:o,theme:a});em((p,f)=>{if(Zd(p)){let y=yi(i,r.default);n(t(y)),s("done"),e(y);return}if(p.name==="tab"){let y=da(!yi(i,r.default));f.clearLine(0),f.write(y),n(y);return}if(p.name==="y"||p.name==="n"){let y=yi(p.name,r.default);n(t(y)),s("done"),e(y);return}f.clearLine(0),f.write(i),n(f.line)});let l=i,d="";o==="done"?l=a.style.answer(i):d=` ${a.style.defaultAnswer(r.default===!1?"y/N":"Y/n")}`;let u=a.style.message(r.message,o);return`${c} ${u}${d} ${l}`});var Z=Oe(async({message:r,default:e})=>await ma({message:r,default:e}));var am=m(r=>im(r,Rr),"getDeprecatedLocalConfigPath"),lo=new Map;async function Le({cwd:r=ua.cwd(),migrateConfig:e=!0,warnAboutOldConfig:t=!0}={cwd:ua.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let o=lo.get(r);if(o)return T("useActorConfig",{cacheHit:!0,config:o}),mo(o);let s=ri(r),i=am(r),n,a;try{n=de(s)}catch(l){return dr({message:`Failed to read local config at path: '${s}':`,cause:l,exists:!1,config:{}})}try{a=de(i)}catch(l){return dr({message:`Failed to read local config at path: '${i}':`,cause:l,exists:!1,config:{}})}if(n&&a&&t&&await cm(i),!n&&!a)return lo.set(r,{exists:!1,migrated:!1,config:{}}),mo({exists:!1,migrated:!1,config:{}});let c=!1;if(!n&&a&&e){let l=await dm(a,i,s);if(l.isErr())return dr(l.unwrapErr());n=l.unwrap(),c=!0}return lo.set(r,{exists:!0,migrated:c,config:n||a||{}}),T("useActorConfig",{cacheHit:!1,config:lo.get(r)}),mo({exists:!0,migrated:c,config:n||a||{}})}m(Le,"useActorConfig");async function cm(r){if(!await Z({message:'The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Since we have found both files in your Actor directory, "apify.json" will be renamed to "apify.json.deprecated". Going forward, all commands will use ".actor/actor.json". You can read about the differences between the old and the new config at https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md. Do you want to continue?'})){x({message:'The "apify.json" file present in your Actor directory will be ignored, and the new ".actor/actor.json" file will be used instead. Please, either rename or remove the old file.'});return}try{await pa(r,`${r}.deprecated`),b({message:'The "apify.json" file has been renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted.'})}catch(t){t instanceof Error?g({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
70
+ ${t.message||t}`}):g({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
71
+ ${nm(t,{showHidden:!1})}`})}}m(cm,"handleBothConfigVersionsFound");var lm=["name","version","buildTag"];async function dm(r,e,t){let o={...r};if(typeof o.version=="object"&&(o=mm(o)),o={actorSpecification:Ks,environmentVariables:r?.env||void 0,...lm.reduce((i,n)=>(i[n]=r[n],i),{})},!await Z({message:'The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Your "apify.json" file will be automatically updated to the new format under ".actor/actor.json". The original file will be renamed by adding the ".deprecated" suffix. Do you want to continue?'}))return dr({message:'Command can not run with old "apify.json" structure. Either let the CLI auto-update it or follow the guide on https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md and update it manually.',exists:!0,config:o});try{await rm(sm(t),{recursive:!0}),await om(t,JSON.stringify(o,null," "))}catch(i){let n=i;return dr({message:`Failed to write the new "actor.json" file to path: '${t}'.
72
+ ${n.message||n}`,exists:!0,config:o})}try{await pa(e,`${e}.deprecated`)}catch(i){let n=i;x({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
73
+ ${n.message||n}`})}return b({message:'The "apify.json" file has been migrated to ".actor/actor.json" and the original file renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted. Do not forget to commit the new file to your Git repository.'}),mo(o)}m(dm,"handleMigrationFlow");function mm(r){let e={name:r.name,template:r.template,version:r.version.versionNumber,buildTag:r.version.buildTag,env:null};if(r.version.envVars?.length){let t={};r.version.envVars.forEach(o=>{o.name&&o.value&&(t[o.name]=o.value)}),e.env=t}return e}m(mm,"updateLocalConfigStructure");var gm=um(he("default"),"INPUT.json"),bt=class extends h{static name="calculate-memory";static description="Calculates the Actor\u2019s dynamic memory usage based on a memory expression from actor.json, input data, and run options.";static group="Actor Runtime";static examples=[{description:"Calculate memory using the expression and input defaults from actor.json.",command:"actor calculate-memory"},{description:"Override the memory expression and input file.",command:'actor calculate-memory --defaultMemoryMbytes "input.length * 128" --input ./my-input.json'}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-calculate-memory";static flags={input:w.string({description:"Path to the input JSON file used for the calculation.",required:!1,default:gm}),defaultMemoryMbytes:w.string({description:"Memory-calculation expression (in MB). If omitted, the value is loaded from the actor.json file.",required:!1}),build:w.string({description:"Actor build version or build tag to evaluate the expression with.",required:!1}),timeoutSecs:w.integer({description:"Maximum run timeout, in seconds.",required:!1}),maxItems:w.integer({description:"Maximum number of items Actor can output.",required:!1}),maxTotalChargeUsd:w.integer({description:"Maximum total charge in USD.",required:!1})};async run(){let{input:e,memoryExpression:t,minMemory:o,maxMemory:s,runOptions:i}=await this.prepareMemoryArguments();if(!t)throw new Error("No memory-calculation expression found. Provide it via the --default-memory-mbytes flag or define defaultMemoryMbytes in actor.json.");let n=pm(wi.cwd(),e),a=de(n)??{};b({message:`Evaluating memory expression: ${t}`});try{let c=await fm(t,{input:a,runOptions:i}),l=Math.min(Math.max(c,o),s);R({message:`Calculated memory: ${l} MB`,stdout:!0})}catch(c){g({message:`Memory calculation failed: ${c.message}`})}}async prepareMemoryArguments(){let{input:e,defaultMemoryMbytes:t,...o}=this.flags,s=t,i=0,n=1/0;return s||({defaultMemoryMbytes:s,minMemoryMbytes:i=i,maxMemoryMbytes:n=n}=await this.getExpressionFromConfig()),{memoryExpression:s,minMemory:i,maxMemory:n,input:e,runOptions:o}}async getExpressionFromConfig(){let e=wi.cwd(),t=await Le({cwd:e});if(t.isErr()){let{message:s,cause:i}=t.unwrapErr();return g({message:`${s}${i?`
74
+ ${i.message}`:""}`}),wi.exitCode=5,{}}let{config:o}=t.unwrap();return{defaultMemoryMbytes:o?.defaultMemoryMbytes?.toString(),minMemoryMbytes:o?.minMemoryMbytes,maxMemoryMbytes:o?.maxMemoryMbytes}}};import{APIFY_ENV_VARS as Sm}from"@apify/consts";import mr from"process";import{pipeline as hm}from"stream/promises";import{MemoryStorage as ym}from"@crawlee/memory-storage";import{ApifyClient as wm}from"apify-client";import{ACTOR_ENV_VARS as fa,APIFY_ENV_VARS as ga,KEY_VALUE_STORE_KEYS as Am,LOCAL_ACTOR_ENV_VARS as vm}from"@apify/consts";var ur={KEY_VALUE_STORE:"KEY_VALUE_STORE",DATASET:"DATASET",REQUEST_QUEUE:"REQUEST_QUEUE"},Ai=m(async()=>{let r=mr.env[ga.TOKEN];if(r)return r;let e=await M();if(!e||!e.token)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN or apify login command.");return e.token},"getApifyTokenFromEnvOrAuthFile"),dt=m(async(r={},e=Reflect.has(mr.env,ga.IS_AT_HOME))=>{let t=we();if(t&&!e)return new ym({localDataDirectory:t,...r});let o=await Ai();return new wm({...zt(o),...r})},"getApifyStorageClient"),pr=m(r=>{let e=fa[`DEFAULT_${r}_ID`];return mr.env[e]||vm[e]},"getDefaultStorageId"),vi=m(async r=>{let e=await dt(),t=pr(ur.KEY_VALUE_STORE),o=await e.keyValueStore(t).getRecord(r,{stream:!0});o&&await hm(o.value,mr.stdout,{end:!1})},"outputRecordFromDefaultStore"),ha=m(async()=>vi(mr.env[fa.INPUT_KEY]||Am.INPUT),"outputInputFromDefaultStore");function bm(r){return{argTag:"string",required:r.required??!1,stdin:r.stdin??1,description:r.description,aliases:r.aliases,catchAll:r.catchAll??!1}}m(bm,"stringArg");var A={string:bm};var St=class extends h{static name="charge";static description="Charge for a specific event in a pay-per-event Actor run.";static group="Actor Runtime";static examples=[{description:"Charge one event of the given type.",command:"actor charge result-item"},{description:"Charge 5 events with an idempotency key.",command:"actor charge result-item --count 5 --idempotency-key req-123"},{description:"Test locally without actually charging.",command:"actor charge result-item --test-pay-per-event"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-charge";static args={eventName:A.string({description:"Name of the event to charge for.",required:!0})};static flags={count:w.integer({description:"Number of events to charge.",required:!1,default:1}),"idempotency-key":w.string({description:"Idempotency key for the charge request.",required:!1}),"test-pay-per-event":w.boolean({description:"Test pay-per-event charging without actually charging.",required:!1,default:!1})};async run(){let{eventName:e}=this.args,{count:t,testPayPerEvent:o,idempotencyKey:s}=this.flags;if(!!!process.env.APIFY_IS_AT_HOME){b({message:`No platform detected: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}if(o){b({message:`PPE test mode: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}let n=await Ai(),a=await Xt(n);if(!a)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN.");let c=process.env[Sm.ACTOR_RUN_ID];if(!c)throw new Error("Charge command must be executed in a running Actor. Run ID not found.");if((await a.run(c).get())?.pricingInfo?.pricingModel!=="PAY_PER_EVENT")throw new Error("Charge command can only be used with pay-per-event pricing model.");b({message:`Charging ${t} events of type "${e}" with idempotency key "${s??"not-provided"}" (runId: ${c}).`,stdout:!0}),await a.run(c).charge({eventName:e,count:t,idempotencyKey:s})}};import{mkdir as $m,writeFile as go}from"fs/promises";import Et from"path";import Ea from"process";import{compile as ho}from"json-schema-to-typescript";import{existsSync as Tm,writeFileSync as Cm}from"fs";import{join as fr}from"path";import{cloneDeep as Im}from"es-toolkit";import{KEY_VALUE_STORE_KEYS as Em}from"@apify/consts";import{validateInputSchema as wa}from"@apify/input_schema";var ya=[".actor/INPUT_SCHEMA.json","./INPUT_SCHEMA.json",".actor/input_schema.json","./input_schema.json"],Tt=m(async({forcePath:r,cwd:e})=>{if(r)return{inputSchema:de(r),inputSchemaPath:r};let t=Me(e);if(typeof t?.input=="object")return{inputSchema:t.input,inputSchemaPath:null};if(typeof t?.input=="string"){let o=fr(e,xr,t.input);return{inputSchema:de(o),inputSchemaPath:o}}for(let o of ya){let s=fr(e,o);if(Tm(s))return{inputSchema:de(s),inputSchemaPath:s}}return{inputSchema:null,inputSchemaPath:fr(e,ya[0])}},"readInputSchema"),uo=m(async({forcePath:r,cwd:e,getMessage:t})=>{let{inputSchema:o,inputSchemaPath:s}=await Tt({forcePath:r,cwd:e});if(!o)throw new Error(`Input schema has not been found at ${s}.`);b({message:t(s)});let i=new Wt({strict:!1});return wa(i,o),{inputSchema:o,inputSchemaPath:s}},"readAndValidateInputSchema"),po=m(({cwd:r,key:e,label:t,getRef:o})=>{let s=Me(r),i=o?o(s):s?.storages?.[e];if(typeof i=="object"&&i!==null)return{schema:i,schemaPath:null};if(typeof i=="string"){let n=fr(r,xr,i),a=de(n);return a?{schema:a,schemaPath:n}:(x({message:`${t} schema file not found at ${n} (referenced in '${D}').`}),null)}return null},"readStorageSchema"),Aa=m(({cwd:r})=>{let e=po({cwd:r,key:"dataset",label:"Dataset"});return e?{datasetSchema:e.schema,datasetSchemaPath:e.schemaPath}:null},"readDatasetSchema"),va=m(({cwd:r})=>{let e=po({cwd:r,key:"output",label:"Output",getRef:m(t=>t?.output,"getRef")});return e?{outputSchema:e.schema,outputSchemaPath:e.schemaPath}:null},"readOutputSchema"),fo=m(async r=>{let e={};try{let{inputSchema:t}=await Tt({cwd:r});if(t){let o=new Wt({strict:!1});wa(o,t),e=Object.entries(t.properties).reduce((s,[i,n])=>(s[i]=n.type==="boolean"||n.editor==="hidden"?n.default:n.prefill,s),{})}}catch(t){x({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${t.message}`})}finally{let t=he(),o=fr(r,t,`${Em.INPUT}.json`);Cm(o,JSON.stringify(e,null," "))}},"createPrefilledInputFileFromInputSchema"),ba=m(r=>{let e={};for(let[t,o]of Object.entries(r.properties))o.default!==void 0&&(e[t]=o.default);return e},"getDefaultsFromInputSchema"),Sa=m((r,e)=>{let t=Im(r);t.required=[];for(let[o,s]of Object.entries(r.properties)){let i=r.required?.includes(o),n=s.default!==void 0;i&&!n&&(t.required.push(o),s.type==="array"&&(s.minItems=Math.max(1,s.minItems||0)))}return delete t.$schema,e.compile(t)},"getAjvValidator");import{cloneDeep as Ct}from"es-toolkit";function bi(r){let e=Ct(r);if(!e.properties||typeof e.properties!="object")return e;let t=e.properties,o=new Set(Array.isArray(e.required)?e.required:[]);for(let[s,i]of Object.entries(t))i.default!==void 0&&o.add(s),i.type==="object"&&i.properties&&(t[s]=bi(i));return e.required=Array.from(o),e}m(bi,"makePropertiesRequired");function It(r){let e=Ct(r);if(delete e.required,e.properties&&typeof e.properties=="object"){let t=e.properties;for(let[o,s]of Object.entries(t))s.type==="object"&&s.properties&&(t[o]=It(s))}return e}m(It,"clearAllRequired");function Ae(r){let e=Ct(r);if(delete e.title,e.properties&&typeof e.properties=="object"){let t=e.properties;for(let[o,s]of Object.entries(t))s&&typeof s=="object"&&(t[o]=Ae(s))}e.items&&typeof e.items=="object"&&(e.items=Ae(e.items));for(let t of["allOf","anyOf","oneOf"])Array.isArray(e[t])&&(e[t]=e[t].map(o=>o&&typeof o=="object"?Ae(o):o));for(let t of["definitions","$defs"])if(e[t]&&typeof e[t]=="object"&&!Array.isArray(e[t])){let o=e[t];for(let[s,i]of Object.entries(o))i&&typeof i=="object"&&(o[s]=Ae(i))}e.additionalProperties&&typeof e.additionalProperties=="object"&&(e.additionalProperties=Ae(e.additionalProperties));for(let t of["if","then","else","not"])e[t]&&typeof e[t]=="object"&&(e[t]=Ae(e[t]));if(e.patternProperties&&typeof e.patternProperties=="object"&&!Array.isArray(e.patternProperties)){let t=e.patternProperties;for(let[o,s]of Object.entries(t))s&&typeof s=="object"&&(t[o]=Ae(s))}return e}m(Ae,"stripTitles");function Ta(r){let e=r.fields;if(!e||typeof e!="object"||!e.properties||typeof e.properties!="object")return null;let t=Ct(e);return t.type||(t.type="object"),t}m(Ta,"prepareFieldsSchemaForCompilation");function Ca(r){let e=r.properties;if(!e||typeof e!="object"||Object.keys(e).length===0)return null;let t=Ct(e);for(let s of Object.values(t))s&&typeof s=="object"&&delete s.template;let o={type:r.type||"object",properties:t};return Array.isArray(r.required)&&(o.required=[...r.required]),o}m(Ca,"prepareOutputSchemaForCompilation");function Ia(r){let e=r.collections;if(!e||typeof e!="object")return[];let t=[];for(let[o,s]of Object.entries(e)){if(!s||typeof s!="object")continue;let i=s.jsonSchema;if(!i||typeof i!="object"||Object.keys(i).length===0)continue;let n=Ct(i);n.type||(n.type="object"),t.push({name:o,schema:n})}return t}m(Ia,"prepareKvsCollectionsForCompilation");var Rm=`
75
+ // biome-ignore-all lint: generated
76
+ // biome-ignore-all format: generated
77
+ /* eslint-disable */
78
+ /* prettier-ignore-start */
79
+ /*
80
+ * This file was automatically generated by json-schema-to-typescript.
81
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
82
+ * and run apify actor generate-schema-types to regenerate this file.
83
+ */
84
+ `,$t=class extends h{static name="generate-schema-types";static hiddenAliases=["generate-types"];static description=`Generate TypeScript types from Actor schemas.
85
+
86
+ Generates types from the input schema and, when no custom path is provided,
87
+ also from the Dataset, Output (experimental), and Key-Value Store (experimental)
88
+ schemas defined in '${D}'.
89
+
90
+ Reads the input schema from one of these locations (in priority order):
91
+ 1. Object in '${D}' under "input" key
92
+ 2. JSON file path in '${D}' "input" key
93
+ 3. .actor/INPUT_SCHEMA.json
94
+ 4. INPUT_SCHEMA.json
95
+
96
+ Optionally specify custom schema path to use.`;static group="Actor Runtime";static examples=[{description:"Generate TypeScript types from the input schema into the default output directory.",command:"actor generate-schema-types"},{description:"Generate types from a custom schema path.",command:"actor generate-schema-types ./schemas/my-input.json"},{description:"Mark all generated properties as optional.",command:"actor generate-schema-types --all-optional"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-generate-schema-types";static flags={output:w.string({char:"o",description:"Directory where the generated files should be outputted. Defaults to src/.generated/actor/ to stay within the typical tsconfig rootDir.",required:!1,default:Et.join("src",".generated","actor")}),strict:w.boolean({description:"Whether generated interfaces should be strict (no index signature [key: string]: unknown).",required:!1,default:!0}),"all-optional":w.boolean({description:"Mark all properties as optional in generated types.",required:!1,default:!1})};static args={path:A.string({required:!1,description:"Optional path to the input schema file. If not provided, searches default locations."})};async run(){let e=Ea.cwd(),{inputSchema:t}=await uo({forcePath:this.args.path,cwd:e,getMessage:m(l=>l?`Generating types from input schema at ${l}`:`Generating types from input schema embedded in '${D}'`,"getMessage")}),o="input",s=this.flags.allOptional?It(t):bi(t),i={bannerComment:Rm,maxItems:-1,unknownAny:!0,format:!0,additionalProperties:!this.flags.strict,$refOptions:{resolve:{external:!1,file:!1,http:!1}}},n=await ho(Ae(s),o,i),a=Et.resolve(e,this.flags.output);await $m(a,{recursive:!0});let c=Et.join(a,`${o}.ts`);if(await go(c,n,"utf-8"),R({message:`Generated types written to ${c}`}),!this.args.path){let l=await Promise.allSettled([this.generateDatasetTypes({cwd:e,outputDir:a,compileOptions:i}),this.generateOutputTypes({cwd:e,outputDir:a,compileOptions:i}),this.generateKvsTypes({cwd:e,outputDir:a,compileOptions:i})]),d=["Dataset","Output","Key-Value Store"],u=!1;for(let[p,f]of l.entries())f.status==="rejected"&&(u=!0,g({message:`Failed to generate types for ${d[p]} schema: ${f.reason instanceof Error?f.reason.message:String(f.reason)}`}));u&&(Ea.exitCode=1)}}async generateDatasetTypes({cwd:e,outputDir:t,compileOptions:o}){let s=Aa({cwd:e});if(!s)return;let{datasetSchema:i,datasetSchemaPath:n}=s;n?b({message:`[experimental] Generating types from Dataset schema at ${n}`}):b({message:`[experimental] Generating types from Dataset schema embedded in '${D}'`});let a=Ta(i);if(!a){x({message:"Dataset schema has no fields defined, skipping type generation."});return}let c="dataset",l=this.flags.allOptional?It(a):a,d=await ho(Ae(l),c,o),u=Et.join(t,`${c}.ts`);await go(u,d,"utf-8"),R({message:`Generated types written to ${u}`})}async generateOutputTypes({cwd:e,outputDir:t,compileOptions:o}){let s=va({cwd:e});if(!s)return;let{outputSchema:i,outputSchemaPath:n}=s;n?b({message:`[experimental] Generating types from Output schema at ${n}`}):b({message:`[experimental] Generating types from Output schema embedded in '${D}'`});let a=Ca(i);if(!a){x({message:"Output schema has no properties defined, skipping type generation."});return}let c="output",l=this.flags.allOptional?It(a):a,d=await ho(Ae(l),c,o),u=Et.join(t,`${c}.ts`);await go(u,d,"utf-8"),R({message:`Generated types written to ${u}`})}async generateKvsTypes({cwd:e,outputDir:t,compileOptions:o}){let s=po({cwd:e,key:"keyValueStore",label:"Key-Value Store"});if(!s)return;let{schema:i,schemaPath:n}=s;n?b({message:`[experimental] Generating types from Key-Value Store schema at ${n}`}):b({message:`[experimental] Generating types from Key-Value Store schema embedded in '${D}'`});let a=Ia(i);if(a.length===0){x({message:"Key-Value Store schema has no collections with JSON schemas, skipping type generation."});return}let c=[];for(let{name:d,schema:u}of a){let p=this.flags.allOptional?It(u):u,f=await ho(Ae(p),d,{...o,bannerComment:c.length===0?o.bannerComment:""});c.push(f)}let l=Et.join(t,"key-value-store.ts");await go(l,c.join(`
97
+ `),"utf-8"),R({message:`Generated types written to ${l}`})}};var Rt=class extends h{static name="get-input";static description="Gets the Actor input value from the default key-value store associated with the Actor run.";static group="Actor Runtime";static examples=[{description:"Print the current Actor input to stdout.",command:"actor get-input"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-get-input";async run(){await ha()}};import{ACTOR_ENV_VARS as Si,APIFY_ENV_VARS as xm}from"@apify/consts";var xt=class extends h{static name="get-public-url";static description="Get an HTTP URL that allows public access to a key-value store item.";static group="Actor Runtime";static examples=[{description:"Get a public URL for the record stored under the given key.",command:"actor get-public-url OUTPUT"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-get-public-url";static args={key:A.string({required:!0,description:"Key of the record in the key-value store."})};async run(){let{key:e}=this.args;if([void 0,"false",""].includes(process.env[xm.IS_AT_HOME])){g({message:"get-public-url is not yet implemented for local development"}),process.exitCode=255;return}let t=process.env[Si.DEFAULT_KEY_VALUE_STORE_ID];if(!t){g({message:`Missing environment variable: ${Si.DEFAULT_KEY_VALUE_STORE_ID}. Please set it before running the command.`}),process.exitCode=5;return}let o=await dt();if(!await o.keyValueStore(t).get()){g({message:`Key-Value store with ID '${t}' was not found. Ensure the store exists and that the correct ID is set in ${Si.DEFAULT_KEY_VALUE_STORE_ID}.`}),process.exitCode=250;return}let i=await o.keyValueStore(t).getRecordPublicUrl(e);console.log(i)}};var _t=class extends h{static name="get-value";static description="Gets a value from the default key-value store associated with the Actor run.";static group="Actor Runtime";static examples=[{description:'Read the record stored under the key "INPUT".',command:"actor get-value INPUT"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-get-value";static args={key:A.string({required:!0,description:"Key of the record in the key-value store."})};async run(){let{key:e}=this.args;await vi(e)}};var Pt=class extends h{static name="push-data";static description="Saves data to Actor's run default dataset.";static group="Actor Runtime";static examples=[{description:"Push a single item as an inline JSON argument.",command:`actor push-data '{"key":"value"}'`},{description:"Push an array of items by piping from stdin.",command:"cat ./items.json | actor push-data"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-push-data";static args={item:A.string({description:"JSON string with one object or array of objects containing data to be stored in the default dataset."})};async run(){let{item:e}=this.args,t=e||Re;if(!t){g({message:"No item was provided."});return}let o=await dt(),s=pr(ur.DATASET),i;try{i=JSON.parse(t.toString("utf8"))}catch(n){throw new Error(`Failed to parse data as JSON string: ${n.message}`)}await o.dataset(s).pushItems(i)}};var kt=class extends h{static name="set-value";static description="Sets or removes a record in the default key-value store associated with the Actor run.";static group="Actor Runtime";static examples=[{description:'Store a JSON value under the key "OUTPUT".',command:`actor set-value OUTPUT '{"status":"done"}'`},{description:"Store a file as a text record.",command:"cat ./report.txt | actor set-value REPORT --contentType text/plain"},{description:"Delete the record stored under the given key.",command:"actor set-value OUTPUT"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-set-value";static args={key:A.string({required:!0,description:"Key of the record in key-value store."}),value:A.string({required:!1,description:`Record data, which can be one of the following values:
98
+ - If empty, the record in the key-value store is deleted.
99
+ - If no \`contentType\` flag is specified, value is expected to be any JSON string value.
100
+ - If options.contentType is set, value is taken as is.`})};static flags={contentType:w.string({char:"c",description:'Specifies a custom MIME content type of the record. By default "application/json" is used.',required:!1})};async run(){let{key:e,value:t}=this.args,{contentType:o="application/json; charset=utf-8"}=this.flags,s=t||process.stdin,n=(await dt()).keyValueStore(pr(ur.KEY_VALUE_STORE));s==null||s===""||s==="null"||s==="undefined"?await n.deleteRecord(e):await n.setRecord({key:e,value:s,contentType:o})}};var yo=class extends h{static name="actor";static description=`Runtime data operations intended to be called from inside a running Actor: read input, push data, get/set records in the default key-value store, charge pay-per-event, generate schema types.
101
+
102
+ For platform-level management (deploy, list, call Actors), see 'apify actors' (plural).`;static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actor";static subcommands=[kt,Pt,_t,xt,Rt,St,bt,$t];async run(){this.printHelp()}};import De from"chalk";import _m from"process";async function Je({providedActorNameOrId:r,client:e}){let t=await M(),o=t.username||t.id,s=Me(_m.cwd())||{};if(r?.includes("/")){let i=await e.actor(r).get();return i?{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id}:{valid:!1,reason:`Actor with ID "${r}" was not found`}}if(r){let i=await e.actor(r).get();if(i)return{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id};let n=await e.actor(`${o}/${r.toLowerCase()}`).get();return n?{valid:!0,userFriendlyId:`${n.username}/${n.name}`,id:n.id}:{valid:!1,reason:`Actor with name or ID "${r}" was not found`}}if(s.name){let i=await e.actor(`${o}/${s.name}`).get();return i?{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id}:{valid:!1,reason:`Actor with name "${s.name}" was not found`}}return{valid:!1,reason:"Unable to detect what Actor to create a build for"}}m(Je,"resolveActorContext");var Ot=class extends h{static name="create";static description="Creates a new build of the Actor.";static examples=[{description:'Build the Actor in the current directory with the default "latest" tag.',command:"apify builds create"},{description:"Build a specific Actor with a custom tag and stream the build log.",command:"apify builds create apify/hello-world --tag beta --log"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-create";static flags={tag:w.string({description:'Build tag to be applied to the successful Actor build. By default, this is "latest".'}),version:w.string({description:"Optional Actor Version to build. By default, this will be inferred from the tag, but this flag is required when multiple versions have the same tag.",required:!1}),log:w.boolean({description:"Whether to print out the build log after the build is triggered."})};static args={actorId:A.string({description:"Optional Actor ID or Name to trigger a build for. By default, it will use the Actor from the current directory."})};static enableJsonFlag=!0;async run(){let{tag:e,version:t,json:o,log:s}=this.flags,{actorId:i}=this.args,n=await I(),a=await Je({providedActorNameOrId:i,client:n});if(!a.valid){g({message:`${a.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let c=await n.actor(a.id).get(),d=Br(c.versions,C=>C.buildTag??"latest")[e??"latest"],u=c.versions.find(C=>C.versionNumber===t),p,f=e;if(u){if(e&&(!d||!d.some(C=>C.versionNumber===t))){g({message:`The Actor Version "${t}" does not have the tag "${e}".`,stdout:!0});return}p=t,f=u.buildTag??"latest"}else if(d&&(p=d[0].versionNumber,f=e??"latest",d.length>1&&!t)){g({message:`Multiple Actor versions with the tag "${e}" found. Please specify the version number using the "--version" flag.
103
+ Available versions for this tag: ${d.map(C=>De.yellow(C.versionNumber)).join(", ")}`,stdout:!0});return}if(!p){g({message:`No Actor versions with the tag "${e}" found. You can push a new version with this tag by using "apify push --build-tag=${e}".`,stdout:!0});return}let y=await n.actor(a.id).build(p,{tag:e});if(o){L(y);return}let v=[`${De.yellow("Actor")}: ${c?.username?`${c.username}/`:""}${c?.name??"unknown-actor"} (${De.gray(y.actId)})`,` ${De.yellow("Version")}: ${p} (tagged with ${De.yellow(f)})`,"",`${De.greenBright("Build Started")} (ID: ${De.gray(y.id)})`,` ${De.yellow("Build Number")}: ${y.buildNumber} (will get tagged once finished)`,` ${De.yellow("Started")}: ${Y.display(y.startedAt)}`,""],S=`https://console.apify.com/actors/${y.actId}/builds/${y.buildNumber}`,E=`${De.blue("View in Apify Console")}: ${S}`;if($({message:v.join(`
104
+ `),stdout:!0}),s){try{await ke({job:y,apifyClient:n})}catch(C){g({message:`Failed to print log for build with ID "${y.id}": ${C.message}`,stdout:!0})}$({message:"",stdout:!0})}$({message:E,stdout:!0})}};var wo=class extends Ot{static name="build"};import _a from"process";import{DownloadItemsFormat as Lm}from"apify-client";import ce from"chalk";import{access as Pm,readFile as km}from"fs/promises";import Om,{resolve as $a}from"path";import Fe from"process";import Nm from"mime";function Ra(r,e){let t,o;if(e)t=e,o="application/json";else{let s=Zt(r);s&&(Nm.getExtension(s.contentType)==="json"?(t=JSON.parse(s.body.toString("utf8")),o="application/json"):(t=s.body,o=s.contentType))}return!t||!o?null:{inputToUse:t,contentType:o}}m(Ra,"resolveInput");async function Nt(r,e,t){let o,s;if(!e&&!t){let i=Re;if(i)try{let n=JSON.parse(i.toString("utf8"));if(Array.isArray(n))return g({message:"The provided input is invalid. It should be an object, not an array."}),Fe.exitCode=5,!1;o=n,s="stdin"}catch(n){return g({message:`Cannot parse JSON input from standard input.
105
+ ${n.message}`}),Fe.exitCode=5,!1}}if(e)switch(e[0]){case"-":return g({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),Fe.exitCode=5,!1;default:{let i=await Pm($a(r,e)).then(()=>!0).catch(()=>!1),n=e.endsWith(".json")||e.endsWith(".json5")||Om.isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.includes("~")||e.startsWith(".\\")||e.startsWith("..\\");if(i||n)return g({message:'Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead'}),Fe.exitCode=5,!1;try{let a=JSON.parse(e);if(Array.isArray(a))return g({message:"The provided input is invalid. It should be an object, not an array."}),Fe.exitCode=5,!1;o=a,s="input"}catch(a){return g({message:`Cannot parse JSON input.
106
+ ${a.message}`}),Fe.exitCode=5,!1}}}else if(t)switch(t[0]){case"-":return g({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),Fe.exitCode=5,!1;default:{let i=$a(r,t),n;try{let a=await km(i,"utf8"),c=JSON.parse(a);if(Array.isArray(c))return g({message:"The provided input is invalid. It should be an object, not an array."}),Fe.exitCode=5,!1;o=c,s=t}catch(a){n=a}if(n)try{let a=JSON.parse(t);if(Array.isArray(a))return g({message:"The provided input is invalid. It should be an object, not an array."}),Fe.exitCode=5,!1;o=a,s=t}catch{return g({message:`Cannot read input file at path "${i}".
107
+ ${n.message}`}),Fe.exitCode=5,!1}}}return o?{input:o,source:s}:void 0}m(Nt,"getInputOverride");import Ti from"process";import Ao from"chalk";import{ACTOR_JOB_STATUSES as qe}from"@apify/consts";var xa=[qe.SUCCEEDED,qe.ABORTED,qe.FAILED,qe.TIMED_OUT];async function*Lt(r,e){let t=Ti.cwd(),{actorOrTaskData:o,runOptions:s,type:i,waitForFinishMillis:n,inputOverride:a,silent:c,waitForRunToFinish:l,printRunLogs:d}=e,u=i==="Actor"?"actor":"task",p=Ra(t,a);c||(i==="Actor"?Ce({message:`Calling ${i} ${o.userFriendlyId} (${Ao.gray(o.id)})
108
+ `}):o.title?Ce({message:`Calling ${i} ${o.title} (${o.userFriendlyId}, ${Ao.gray(o.id)})
109
+ `}):Ce({message:`Calling ${i} ${o.userFriendlyId} (${Ao.gray(o.id)})
110
+ `}));let f;try{p&&i==="Actor"?f=await r[u](o.id).start(p.inputToUse,{...s,contentType:p.contentType}):f=await r[u](o.id).start(void 0,s)}catch(y){throw y.type==="record-not-found"?new Error(`${i} ${o.userFriendlyId} (${o.id}) not found!`):y}if(yield f,!c&&d)try{await ke({job:f,timeoutMillis:n,apifyClient:r})==="timeouts"?console.error(`
111
+ ${Ao.gray("Timeout for printing logs was hit, there may be future logs.")}
112
+ `):console.error()}catch(y){x({message:"Can not get log:"}),console.error(y)}if(f=await r.run(f.id).get(),l)for(;!xa.includes(f.status)&&(f=await r.run(f.id).get(),!xa.includes(f.status));)await new Promise(y=>{setTimeout(y,1e3)});c||(f.status===qe.SUCCEEDED?R({message:`${i} finished.`}):f.status===qe.RUNNING?x({message:`${i} is still running!`}):f.status===qe.ABORTED||f.status===qe.ABORTING?(x({message:`${i} was aborted!`}),Ti.exitCode=3):(g({message:`${i} failed!`}),Ti.exitCode=1)),yield f}m(Lt,"runActorOrTaskOnCloud");var Dt=m(r=>({build:w.string({char:"b",description:'Tag or number of the build to run (e.g. "latest" or "1.2.34").',required:!1}),timeout:w.integer({char:"t",description:`Timeout for the ${r} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:w.integer({char:"m",description:`Amount of memory allocated for the ${r} run, in megabytes.`,required:!1})}),"SharedRunOnCloudFlags");var Ke=class r extends h{static name="call";static description=`Executes Actor remotely using your authenticated account.
113
+ Reads input from local key-value store by default.`;static group="Apify Console";static examples=[{description:"Call the Actor defined in the current directory (from .actor/actor.json).",command:"apify call"},{description:"Call a specific Actor by its full name.",command:"apify call apify/hello-world"},{description:"Call an Actor with inline JSON input.",command:`apify call apify/hello-world --input '{"url":"https://example.com"}'`},{description:"Call an Actor with input from a file and print the dataset on success.",command:"apify call apify/web-scraper --input-file input.json --output-dataset"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-call";static flags={...Dt("Actor"),input:w.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":w.string({char:"f",description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]}),silent:w.boolean({char:"s",description:"Prevents printing the logs of the Actor run to the console.",default:!1}),"output-dataset":w.boolean({char:"o",description:"Prints out the entire default dataset on successful run of the Actor."})};static enableJsonFlag=!0;static args={actorId:A.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${D}' file.`})};async run(){let e=_a.cwd(),t=Me(e)||{},o=await I(),s=await M(),i=s.username||s.id;if(this.flags.json&&this.flags.outputDataset){g({message:"You cannot use both the --json and --output-dataset flags when running this command."}),_a.exitCode=5;return}let{id:n,userFriendlyId:a,actorData:c}=await r.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),l={waitForFinish:2};this.flags.build&&(l.build=this.flags.build),this.flags.timeout&&(l.timeout=this.flags.timeout),this.flags.memory&&(l.memory=this.flags.memory);let d=await Nt(e,this.flags.input,this.flags.inputFile);if(d===!1)return;let u=!1,p,f,y,v=Lt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:l,type:"Actor",inputOverride:d?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0});for await(let S of v)if(p=S,!u&&(u=!0,!this.flags.silent)){f=`https://console.apify.com/actors/${n}/runs/${S.id}`,y=`https://console.apify.com/storage/datasets/${S.defaultDatasetId}`;let E=[`${ce.yellow("Started")}: ${Y.display(S.startedAt)}`];S.containerUrl&&E.push(`${ce.yellow("Container URL")}: ${ce.blue(S.containerUrl)}`);let C=p.buildNumber.split(".").slice(0,2).join("."),P=c.versions.find(U=>U.versionNumber===C),N=Object.entries(c.taggedBuilds??{}).find(([,U])=>U.buildNumber===S.buildNumber)?.[0],O=[`${ce.yellow("Build")}:`,ce.cyan(p.buildNumber)];N?O.push(`(${ce.yellow(N)})`):O.push(`(${ce.gray("N/A")})`),P&&O.push(`| ${ce.gray("Actor version:")} ${ce.cyan(P.versionNumber)} (${ce.yellow(P.buildTag)})`),E.push(O.join(" ")),E.push(`${ce.yellow("Timeout")}: ${p.options.timeoutSecs.toLocaleString("en-US")} seconds`),E.push(`${ce.yellow("Memory")}: ${p.options.memoryMbytes} MB`),E.push(`${ce.blue("View on Apify Console")}: ${f}`,""),$({message:E.join(`
114
+ `),stdout:!this.flags.json})}if(this.flags.json){L(p);return}if(this.flags.silent||$({message:["",`${ce.blue("Export results")}: ${y}`,`${ce.blue("View on Apify Console")}: ${f}`].join(`
115
+ `),stdout:!0}),this.flags.outputDataset){let S=p.defaultDatasetId,E,C=4;do{if(E=await o.dataset(S).get(),E?.itemCount)break;await new Promise(N=>{setTimeout(N,250)})}while(C--);let P=await o.dataset(S).downloadItems(Lm.JSON,{clean:!0});console.log(P.toString())}}static async resolveActorId({client:e,localActorName:t,usernameOrId:o,providedActorNameOrId:s}){if(s?.includes("/")){let i=await e.actor(s).get();if(!i)throw new Error(`Cannot find Actor with ID '${s}' in your account.`);return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i}}if(s){let i=await e.actor(s).get();if(i)return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i};let n=await e.actor(`${o}/${s.toLowerCase()}`).get();if(n)return{userFriendlyId:`${n.username}/${n.name}`,id:n.id,actorData:n};throw new Error(`Cannot find Actor with name or ID '${s}' in your account.`)}if(t){let i=await e.actor(`${o}/${t}`).get();if(!i)throw new Error(`Cannot find Actor with ID '${o}/${t}' in your account. Call "apify push" to push this Actor to Apify platform.`);return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i}}throw new Error("Please provide an Actor ID or name, or run this command from a directory with a valid Apify Actor.")}};import k from"chalk";import Dm from"cli-table3";var Fm={mid:"","left-mid":"","mid-mid":"","right-mid":"",middle:" ","top-mid":"\u2500","bottom-mid":"\u2500"},Um={middle:" ","top-mid":"\u2500","bottom-mid":"\u2500",top:"\u2500",bottom:"\u2500","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u2500","right-mid":"\u2524"},Mm={left:"",right:"",mid:"","bottom-left":"","bottom-mid":"","bottom-right":"",top:"","top-left":"","top-mid":"","top-right":"","left-mid":"","mid-mid":"","right-mid":"",bottom:"",middle:" "};var jm={[-1]:void 0,0:Fm,1:Um,2:Mm};function Bm(r){return Array.from({length:r},()=>"cyan")}m(Bm,"generateHeaderColors");var Vm=process.stdout.columns??100,vo=Symbol.for("@apify/cli:responsive-table:skip-column"),B=class r{static{m(this,"ResponsiveTable")}options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=r.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,o=Bm(t.length),s=e===0||e===2,i=jm[e],n=[],a=[],c=[];for(let d of t)this.options.hiddenColumns?.includes(d)||this.rows.some(u=>u[d]===vo)||(n.push(this.options.columnAlignments?.[d]||"left"),r.isSmallTerminal()?(a.push(this.options.breakpointOverrides?.small?.[d]?.label??d),c.push(this.options.breakpointOverrides?.small?.[d]?.valueFrom??d)):(a.push(d),c.push(d)));let l=new Dm({head:a,style:{head:o,compact:s},colAligns:n,chars:i});for(let d of this.rows){let u=c.map(p=>d[p]);l.push(u)}return l.toString()}static isSmallTerminal(){return Vm<100}};var bo="\u200B",So="\u200B\u200B",Pa=new B({allColumns:[bo,So],mandatoryColumns:[bo,So],columnAlignments:{[bo]:"left",[So]:"right"}}),To=class extends h{static name="info";static description="Get information about an Actor.";static examples=[{description:"Print summary information about an Actor.",command:"apify actors info apify/hello-world"},{description:"Print the Actor README only.",command:"apify actors info apify/hello-world --readme"},{description:"Print the Actor input schema as JSON.",command:"apify actors info apify/hello-world --input"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors-info";static flags={readme:w.boolean({description:"Return the Actor README.",exclusive:["input"]}),input:w.boolean({description:"Return the Actor input schema.",exclusive:["readme"]})};static args={actorId:A.string({description:"The ID of the Actor to return information about.",required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:t,input:o,json:s}=this.flags,i=await I(),n=await Je({providedActorNameOrId:e,client:i});if(!n.valid){g({message:`${n.reason}. Please specify the Actor ID.`,stdout:!0});return}let a=await i.actor(n.id).get(),c=await i.user(a.userId).get();a.actorMaker=c;for(let p of Object.values(a.taggedBuilds??{})){if(!p.buildId)continue;let f=await i.build(p.buildId).get();p.build=f}if(s){L(a);return}let l=a.taggedBuilds?.latest;if(t){if(!l){g({message:"No README found for this Actor.",stdout:!0});return}if(!l.build?.readme){g({message:"No README found for this Actor.",stdout:!0});return}$({message:l.build.readme,stdout:!0})}if(o){if(!l){g({message:"No input schema found for this Actor.",stdout:!0});return}if(!l.build?.inputSchema){g({message:"No input schema found for this Actor.",stdout:!0});return}$({message:l.build.inputSchema,stdout:!0})}let d=[`Information about Actor ${k.yellow(`${a.username}/${a.name}`)} (${k.gray(a.id)})`,""];a.title&&d.push(`${k.yellow("Title:")} ${k.bold(a.title)}`),a.description&&d.push(`${k.yellow("Description:")} ${a.description}`),d.push(`${k.yellow("Created at:")} ${k.cyan(Y.display(a.createdAt))} ${k.gray("|")} ${k.yellow("Updated at:")} ${k.cyan(Y.display(a.modifiedAt))}`),a.actorMaker&&(d.push("",`${k.yellow("Made by:")} ${k.cyan(a.actorMaker.profile.name??a.actorMaker.username)}`),Reflect.get(a,"isCritical")&&(d[d.length-1]+=` ${k.bgGray("Maintained by Apify")}`)),a.isPublic?d.push("",`${k.yellow("Actor is")} ${k.green("PUBLIC")}`):d.push("",`${k.yellow("Actor is")} ${k.cyan("PRIVATE")}`),a.isDeprecated&&d.push("",`${k.yellow("Actor is")} ${k.red("DEPRECATED")}`);let u=Reflect.get(a,"pricingInfos");if(u?.length){let p=u.at(-1);switch(p.pricingModel){case"FLAT_PRICE_PER_MONTH":{if(d.push(`${k.yellow("Pricing information:")} ${k.bgGray(`$${p.pricePerUnitUsd}/month + usage`)}`),p.trialMinutes){let f=p.trialMinutes*60*1e3,y=tr.format(f);d.push(` ${k.yellow("Trial duration:")} ${k.bold(y)}`)}break}case"PRICE_PER_DATASET_ITEM":{let f=p.pricePerUnitUsd*1e3;d.push(`${k.yellow("Pricing information:")} ${k.bgGray(`$${f.toFixed(2)} / 1,000 results`)}`);break}case"PAY_PER_EVENT":{d.push(`${k.yellow("Pricing information:")} ${k.bgGray("Pay per event")}`);let f=Object.values(p.pricingPerEvent?.actorChargeEvents??{});for(let S of f)Pa.pushRow({[bo]:S.eventTitle,[So]:k.bold(`$${S.eventPriceUsd.toFixed(2)}`)});let v=Pa.render(0).split(`
116
+ `);v.splice(1,1),d.push(v.join(`
117
+ `));break}case"FREE":{d.push(`${k.yellow("Pricing information:")} ${k.bgGray("Pay for usage")}`);break}default:d.push(`${k.yellow("Pricing information:")} ${k.bgGray(`Unknown pricing model (${k.yellow(p.pricingModel)})`)}`)}}else d.push(`${k.yellow("Pricing information:")} ${k.bgGray("Pay for usage")}`);if((a.seoTitle||a.seoDescription)&&(d.push("",k.yellow("SEO information:")),a.seoTitle&&d.push(` ${k.yellow("Title:")} ${a.seoTitle}`),a.seoDescription&&d.push(` ${k.yellow("Description:")} ${a.seoDescription}`)),a.taggedBuilds){d.push("",k.yellow("Builds:"));let p=a.taggedBuilds.latest;p&&d.push(` ${k.yellow("-")} ${k.cyan(p.buildNumber)} ${k.gray("/")} ${k.yellow("latest")}`);for(let[f,y]of Object.entries(a.taggedBuilds))f!=="latest"&&d.push(` ${k.yellow("-")} ${k.cyan(y.buildNumber)} ${k.gray("/")} ${k.yellow(f)}`)}$({message:d.join(`
118
+ `),stdout:!0})}};import{Time as Gm}from"@sapphire/duration";import Q from"chalk";import je from"chalk";function Pe(r){switch(r){case"READY":return je.green("Ready");case"RUNNING":return je.blue("Running");case"SUCCEEDED":return je.green("Succeeded");case"FAILED":return je.red("Failed");case"ABORTING":return je.yellow("Aborting");case"ABORTED":return je.red("Aborted");case"TIMING-OUT":return je.yellow("Timing Out");case"TIMED-OUT":return je.red("Timed Out");default:return je.gray(r.split("-").map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(" "))}}m(Pe,"prettyPrintStatus");var Ym={"TIMED-OUT":Q.gray("after"),"TIMING-OUT":Q.gray("after"),ABORTED:Q.gray("after"),ABORTING:Q.gray("after"),FAILED:Q.gray("after"),READY:Q.gray("for"),RUNNING:Q.gray("for"),SUCCEEDED:Q.gray("after")},Hm=new B({allColumns:["Name","Runs","Last run started at","Last run status","Last run duration","_Small_LastRunText"],mandatoryColumns:["Name","Runs","Last run status","Last run duration"],columnAlignments:{Runs:"right","Last run duration":"right",Name:"left","Last run status":"center"},hiddenColumns:["_Small_LastRunText"],breakpointOverrides:{small:{"Last run status":{label:"Last run",valueFrom:"_Small_LastRunText"}}}}),Jm=new B({allColumns:["Name","Modified at","Builds","Default build","Runs","Last run","Last run status","Last run duration","_Small_LastRunText"],mandatoryColumns:["Name","Runs","Last run","Last run duration"],hiddenColumns:["_Small_LastRunText"],columnAlignments:{Builds:"right",Runs:"right","Last run duration":"right",Name:"left","Last run status":"center"},breakpointOverrides:{small:{"Last run":{label:"Last run",valueFrom:"_Small_LastRunText"}}}}),Co=class extends h{static name="ls";static description="Prints a list of recently executed Actors or Actors you own.";static examples=[{description:"List Actors you recently interacted with.",command:"apify actors ls"},{description:"List Actors you own, newest first.",command:"apify actors ls --my --desc"},{description:"List the next page of 50 Actors.",command:"apify actors ls --limit 50 --offset 50"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors-ls";static flags={my:w.boolean({description:"Whether to list Actors made by the logged in user.",default:!1}),offset:w.integer({description:"Number of Actors that will be skipped.",default:0}),limit:w.integer({description:"Number of Actors that will be listed.",default:20}),desc:w.boolean({description:"Sort Actors in descending order.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:t,offset:o,my:s,json:i}=this.flags,n=await I(),a=await n.actors().list({limit:t,offset:o,desc:e,my:s});if(a.count===0){if(i){L(a);return}b({message:s?"You don't have any Actors yet!":"There are no recent Actors used by you.",stdout:!0});return}let c={...a,items:await Promise.all(a.items.map(async u=>{let p=await n.actor(u.id).get(),f=await n.actor(u.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...u,actor:p??null,lastRun:f.items[0]??null}}))};if(c.items=s?this.sortByModifiedAt(c.items):this.sortByLastRun(c.items),i){L(c);return}let l=s?Jm:Hm,d=c.items.reduce((u,p)=>{let f=`${p.username}/${p.name}`;return f.length>u?f.length:u},0)+2+6;for(let u of c.items){let p=u.stats.lastRunStartedAt?er.display(u.stats.lastRunStartedAt):"",f=u.lastRun?(()=>{if(u.lastRun.finishedAt)return me.format(u.lastRun.finishedAt.getTime()-u.lastRun.startedAt.getTime());let S=Date.now()-u.lastRun.startedAt.getTime();return`${me.format(S)}\u2026`})():"",y=u.actor?(()=>{let S=Object.entries(u.actor.taggedBuilds??{}).find(([E,C])=>C.buildNumber===u.actor.defaultRunOptions.build||E===u.actor.defaultRunOptions.build);return S?`${Q.yellow(S[0])} / ${Q.cyan(S[1].buildNumber??u.actor.defaultRunOptions.build)}`:Q.gray("Unknown")})():Q.gray("Unknown"),v=(()=>{if(u.lastRun){let E=[Pe(u.lastRun.status)];if(f&&E.push(Ym[u.lastRun.status],Q.cyan(f)),u.lastRun.finishedAt){let C=Date.now()-u.lastRun.finishedAt.getTime();C<Gm.Week?E.push(`
119
+ `,Q.gray(`${me.format(C)} ago`)):E.push(`
120
+ `,Q.gray("On",vn.display(u.lastRun.finishedAt)))}return E.join(" ")}return""})();l.pushRow({Name:`${u.title}
121
+ ${Q.gray(`${u.username}/${u.name}`)}`,Runs:B.isSmallTerminal()&&d>=56?vo:Q.cyan(`${u.stats?.totalRuns??0}`),"Last run started at":p,"Last run":p,"Last run status":u.lastRun?Pe(u.lastRun.status):"","Modified at":er.display(u.modifiedAt),Builds:u.actor?Q.cyan(u.actor.stats.totalBuilds):Q.gray("Unknown"),"Last run duration":B.isSmallTerminal()?vo:Q.cyan(f),"Default build":y,_Small_LastRunText:v})}$({message:l.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((t,o)=>{let s=new Date(t.modifiedAt);return new Date(o.modifiedAt).getTime()-s.getTime()})}sortByLastRun(e){return e.sort((t,o)=>{let s=new Date(t.stats?.lastRunStartedAt??"1970-01-01T00:00Z");return new Date(o.stats?.lastRunStartedAt??"1970-01-01T00:00Z").getTime()-s.getTime()})}};import{mkdirSync as ka,readdirSync as qm,writeFileSync as Oa}from"fs";import{dirname as Km,join as Wm}from"path";import Na from"process";import zm from"adm-zip";import Xm from"axios";import La from"jju";import{gt as Zm}from"semver";import Qm from"tiged";var Da=m(async(r,e)=>{let{data:t}=await Xm.get(r,{responseType:"arraybuffer"}),o=new zm(Buffer.from(t,"binary"));o.extractEntryTo(o.getEntries()[0].entryName,e,!1)},"extractGitHubZip"),Ft=class extends h{static name="pull";static description="Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.";static group="Local Actor Development";static examples=[{description:"Pull the Actor linked to the current directory from the Apify platform.",command:"apify pull"},{description:"Pull a specific Actor by its full name into a target directory.",command:"apify pull apify/hello-world --dir ./hello-world"},{description:"Pull a specific version of an Actor.",command:"apify pull apify/hello-world --version 1.2"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-pull";static flags={version:w.string({char:"v",description:"Actor version number which will be pulled, e.g. 1.2. Default: the highest version.",required:!1}),dir:w.string({description:"Directory where the Actor should be pulled to.",required:!1})};static args={actorId:A.string({required:!1,description:'Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.'})};async run(){let e=Na.cwd(),t=await Le({cwd:e});if(t.isErr()){g({message:t.unwrapErr().message}),Na.exitCode=5;return}let{config:o}=t.unwrap(),s=await M(),i=await I(),n=!this.args.actorId,a=s.username||s.id,c=this.args?.actorId||o?.id||(o?.name?`${a}/${o.name}`:void 0);if(!c)throw new Error("Cannot find Actor in this directory.");let l;try{l=await i.actor(c).get()}catch{throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`)}if(!l)throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`);let{name:d,versions:u}=l,p=m(()=>{throw new Error("You cannot pull source code of this Actor because you do not have permission to do so.")},"throwMissingSourceCodeAccessError");if(!l.versions.length)throw new Error(`Actor ${c} has no versions.`);let f=null;if(this.flags.version&&(f=u.find(S=>S.versionNumber===this.flags.version),!f))throw new Error(`Cannot find version ${this.flags.version} of Actor ${c}.`);f||(f=u.reduce((S,E)=>Zm(`${E.versionNumber}.0`,`${S.versionNumber}.0`)?E:S));let y=n?e:Wm(e,this.flags.dir??d);if(ka(y,{recursive:!0}),!n&&qm(y).length!==0){g({message:`Directory ${y} is not empty. Please empty it or choose another directory.`});return}let{sourceType:v}=f;switch(v){case"TARBALL":{f.tarballUrl||p(),await Da(f.tarballUrl,y);break}case"SOURCE_FILES":{f.sourceFiles||p();let{sourceFiles:S}=f;for(let E of S){let C=Km(E.name);if(ka(`${y}/${C}`,{recursive:!0}),!E.folder){let P=E.format==="BASE64"?Buffer.from(E.content,"base64").toString():E.content;if(E.name===D){let N=La.parse(P);N.name=l.name,Oa(`${y}/${E.name}`,La.update(P,N))}else Oa(`${y}/${E.name}`,P)}}break}case"GIT_REPO":{f.gitRepoUrl||p();let{gitRepoUrl:S}=f,[E,C]=S.split("#"),P,N;C&&([P,N]=C.split(":"));let O=E;N&&(O+=`/${N}`),P&&(O+=`#${P}`);let U=Qm(O);try{await U.clone(y)}catch(J){throw new Error(`Failed to pull Actor from ${S}. ${J.message}`)}break}case"GITHUB_GIST":{f.gitHubGistUrl||p(),await Da(`${f.gitHubGistUrl}/archive/master.zip`,y);break}default:throw new Error(`Unknown source type: ${v}`)}R({message:n?`Actor ${d} updated at ${y}/`:`Pulled to ${y}/`})}};import{readFileSync as ru,statSync as ou,unlinkSync as su}from"fs";import{join as iu,resolve as nu}from"path";import mt from"process";import au from"open";import{fetchManifest as cu}from"@apify/actor-templates";import{ACTOR_JOB_STATUSES as ut,ACTOR_SOURCE_TYPES as Ii,MAX_MULTIFILE_BYTES as Ha}from"@apify/consts";import{createHmacSignature as lu}from"@apify/utilities";import{readFileSync as eu,writeFileSync as tu}from"fs";var Ci="@",Fa=100,Ua=5e4,Ut=m(()=>{try{return JSON.parse(eu(Ir(),"utf-8"))||{}}catch{return{}}},"getSecretsFile"),Ma=m(r=>(oi(Ir()),tu(Ir(),JSON.stringify(r,null," ")),r),"writeSecretsFile"),ja=m((r,e)=>{let t=Ut();if(t[r])throw new Error(`Secret with name ${r} already exists. Call "apify secrets rm ${r}" to remove it.`);if(typeof r!="string"||r.length>Fa)throw new Error(`Secret name has to be string with maximum length ${Fa}.`);if(typeof e!="string"||e.length>Ua)throw new Error(`Secret value has to be string with maximum length ${Ua}.`);return t[r]=e,Ma(t)},"addSecret"),Ba=m(r=>{let e=Ut();if(!e[r])throw new Error(`Secret with name ${r} doesn't exist.`);delete e[r],Ma(e)},"removeSecret"),Va=m(r=>new RegExp(`^${Ci}.{1}`).test(r),"isSecretKey"),Ga=m((r,e,{allowMissing:t=!1}={})=>{e=e||Ut();let o={},s=[];if(Object.keys(r).forEach(i=>{if(Va(r[i])){let n=r[i].replace(new RegExp(`^${Ci}`),"");e[n]?o[i]=e[n]:s.push(n)}else o[i]=r[i]}),s.length>0){let i=s.map(n=>` - ${n}`).join(`
122
+ `);if(t)for(let n of s)x({message:`Value for ${n} not found in local secrets. Set it by calling "apify secrets add ${n} [SECRET_VALUE]"`});else throw new Error(`The following secrets are missing:
123
+ ${i}
124
+
125
+ Set them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
126
+ If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return o},"replaceSecretsValue"),Ya=m((r,e,{allowMissing:t=!1}={})=>{e=e||Ut();let o=[],s=[];if(Object.keys(r).forEach(i=>{if(Va(r[i])){let n=r[i].replace(new RegExp(`^${Ci}`),"");e[n]?o.push({name:i,value:e[n],isSecret:!0}):s.push(n)}else o.push({name:i,value:r[i]})}),s.length>0){let i=s.map(n=>` - ${n}`).join(`
127
+ `);if(t)for(let n of s)x({message:`Value for ${n} not found in local secrets. Set it by calling "apify secrets add ${n} [SECRET_VALUE]"`});else throw new Error(`The following secrets are missing:
128
+ ${i}
129
+
130
+ Set them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
131
+ If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return o},"transformEnvToEnvVars");var Ei="temp_file.zip",du={build:"latest",memoryMbytes:4096,timeoutSecs:3600},Ja="0.0",mu="latest",Mt=class extends h{static name="push";static description=`Deploys Actor to Apify platform using settings from '${D}'.
132
+ Files under '${Ha/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
133
+ Files matched by .gitignore and .actorignore are excluded. Use negation patterns (e.g. !dist/) in .actorignore to force-include git-ignored files.
134
+ Use --force to override newer remote versions.`;static group="Local Actor Development";static examples=[{description:"Deploy the current Actor to the Apify platform.",command:"apify push"},{description:"Deploy to a specific Actor by ID, overriding newer remote versions.",command:"apify push E2jjCZBezvAZnX8Rb --force"},{description:"Deploy without waiting for the build to finish.",command:"apify push --no-wait-for-finish"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-push";static enableJsonFlag=!0;static flags={version:w.string({char:"v",description:`Actor version number to which the files should be pushed. By default, it is taken from the '${D}' file.`,required:!1}),"build-tag":w.string({char:"b",description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${D}' file.`,required:!1}),"wait-for-finish":w.string({char:"w",description:"Seconds for waiting to build to finish, if no value passed, it waits forever.",required:!1}),open:w.boolean({description:"Whether to open the browser automatically to the Actor details page.",default:!1,required:!1}),force:w.boolean({char:"f",description:"Push an Actor even when the local files are older than the Actor on the platform.",default:!1,required:!1}),dir:w.string({description:"Directory where the Actor is located.",required:!1}),"allow-missing-secrets":w.boolean({description:"Allow the command to continue even when secret values are not found in the local secrets storage.",required:!1,default:!1})};static args={actorId:A.string({required:!1,description:`Name or ID of the Actor to push (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will create or modify the Actor with the name specified in '${D}' file.`})};async run(){let e=nu(mt.cwd(),this.flags.dir??"."),t=await fn(e);if(!t.length){g({message:"You need to call this command from a folder that has an Actor in it!"}),mt.exitCode=4;return}if(![Rr,"actor.json",".actor/actor.json",".actor"].some(F=>t.some(re=>re===F||re.startsWith(F)))){g({message:["A valid Actor could not be found in the current directory. Please make sure you are in the correct directory.","You can also turn this directory into an Actor by running `apify init`."].join(`
135
+ `)}),mt.exitCode=4;return}let o=await I(),s=await Le({cwd:e});if(s.isErr()){g({message:s.unwrapErr().message}),mt.exitCode=5;return}let{config:i}=s.unwrap(),n=await M(),c=!!n.organizationOwnerUserId?`/organization/${n.id}`:"",l,d,u=!1,p=this.flags.version||i?.version||Ja,f=this.flags.buildTag||i?.buildTag;!f&&p===Ja&&(f=mu);let y=Number.isNaN(this.flags.waitForFinish)?void 0:Number.parseInt(this.flags.waitForFinish,10)*1e3,v=this.args.actorId;if(v){if(d=await o.actor(v).get(),!d)throw new Error(`Cannot find Actor with ID '${v}' in your account.`);l=d.id}else{let F=n.username||n.id;if(d=await o.actor(`${F}/${i.name}`).get(),d)l=d.id;else{let{templates:re}=await cu(),Te=re.find(Tr=>Tr.name===i.template)?.defaultRunOptions||du,ft={name:i.name,title:i.title,description:i.description,defaultRunOptions:Te,versions:[{versionNumber:p,buildTag:f,sourceType:Ii.SOURCE_FILES,sourceFiles:[]}]};i.usesStandbyMode&&(ft.actorStandby={isEnabled:!0}),d=await o.actors().create(ft),l=d.id,u=!0,b({message:`Created Actor with name ${i.name} on Apify.`})}}let S=o.actor(l);b({message:`Deploying Actor '${i.name}' to Apify.`});let E=await on(t,e),C,P,N;if(E<Ha){let F=await S.get();if(!u){let re=t.reduce((Te,ft)=>{let{mtimeMs:Tr,ctimeMs:Hi}=ou(iu(e,ft)),Ji=Tr>Hi?Tr:Hi;return Te>Ji?Te:Ji},0),Se=F?.modifiedAt.valueOf();if(!this.flags.force&&Se&&re<Se&&(i?.name||v))throw new Error(`Actor with identifier "${i?.name||v}" is already on the platform and was modified there since modified locally.
136
+ Skipping push. Use --force to override.`)}P=await pn(t,e),C=Ii.SOURCE_FILES}else{Ce({message:"Zipping Actor files"}),await gn(Ei,t,e);let F=await o.keyValueStores().getOrCreate(`actor-${l}-source`),re=`version-${p}.zip`,Se=ru(Ei);await o.keyValueStore(F.id).setRecord({key:re,value:Se,contentType:"application/zip"}),su(Ei);let Te=new URL(`${o.baseUrl}/key-value-stores/${F.id}/records/${re}?disableRedirect=true`);if(F?.urlSigningSecretKey){let ft=lu(F.urlSigningSecretKey,re);Te.searchParams.set("signature",ft)}N=Te.toString(),C=Ii.TARBALL}let O=await S.version(p).get(),U=i.environmentVariables?Ya(i.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(O){let F={tarballUrl:N,sourceFiles:P,buildTag:f,sourceType:C,envVars:U};await S.version(p).update(F),Ce({message:`Updated version ${p} for Actor ${d.name}.`})}else{let F={versionNumber:p,tarballUrl:N,sourceFiles:P,buildTag:f,sourceType:C,envVars:U};await S.versions().create({...F}),Ce({message:`Created version ${p} for Actor ${d.name}.`})}if(!u&&!!i.usesStandbyMode!=!!d.actorStandby?.isEnabled){let F=!!i.usesStandbyMode;await S.update({actorStandby:{isEnabled:F}}),b({message:`${F?"Enabled":"Disabled"} standby mode for Actor ${d.name}.`})}Ce({message:`Building Actor ${d.name}`});let J=await S.build(p,{useCache:!0,waitForFinish:2});try{await ke({job:J,timeoutMillis:y,apifyClient:o})}catch(F){x({message:"Can not get log:"}),console.error(F)}if(J=await o.build(J.id).get(),this.flags.json){L(J);return}Hs({message:"Actor build detail",url:`https://console.apify.com${c}/actors/${J.actId}#/builds/${J.buildNumber}`}),Hs({message:"Actor detail",url:`https://console.apify.com${c}/actors/${J.actId}`}),this.flags.open&&await au(`https://console.apify.com${c}/actors/${J.actId}`),J.status===ut.SUCCEEDED?R({message:"Actor was deployed to Apify cloud and built there."}):J.status===ut.READY?x({message:"Build is waiting for allocation."}):J.status===ut.RUNNING?x({message:"Build is still running."}):J.status===ut.ABORTED||J.status===ut.ABORTING?(x({message:"Build was aborted!"}),mt.exitCode=3):J.status===ut.TIMED_OUT||J.status===ut.TIMING_OUT?(x({message:"Build timed out!"}),mt.exitCode=2):(g({message:"Build failed!"}),mt.exitCode=1)}};var Io=class extends h{static name="rm";static description="Permanently removes an Actor from your account.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.";static examples=[{description:"Delete an Actor by its full name (prompts for confirmation).",command:"apify actors rm my-username/my-actor"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors-rm";static args={actorId:A.string({description:"The Actor ID to delete.",required:!0})};static flags={...ie};async run(){let{actorId:e}=this.args,{yes:t}=this.flags,o=await I();if(!await o.actor(e).get()){g({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await Z({message:"Are you sure you want to delete this Actor?",providedConfirmFromStdin:t||void 0})){b({message:`Deletion of Actor "${e}" was canceled.`});return}try{await o.actor(e).delete(),R({message:`Actor with ID "${e}" was deleted.`})}catch(n){let a=n;g({message:`Failed to delete Actor "${e}".
137
+ ${a.message||a}`})}}};import{ApifyClient as uu}from"apify-client";import $i from"chalk";var pu={FREE:"Free",FLAT_PRICE_PER_MONTH:"Subscription",PRICE_PER_DATASET_ITEM:"Pay per result",PAY_PER_EVENT:"Pay per event"};function fu(r){return r?pu[r]??r:$i.gray("Unknown")}m(fu,"formatPricingModel");function gu(r,e=60){return r?r.length<=e?r:`${r.slice(0,e-1)}\u2026`:""}m(gu,"truncateDescription");var Eo=class extends h{static name="search";static description=`Searches Actors in the Apify Store.
138
+
139
+ Searches the Apify Store for Actors matching the given query. Results can be filtered by category, author, pricing model, and more. This command does not require authentication.`;static examples=[{description:'Search the Apify Store for "web scraper" Actors.',command:'apify actors search "web scraper"'},{description:"Search for TikTok Actors sorted by popularity, limit to 5 results.",command:'apify actors search "tiktok" --limit 5 --sort-by popularity'},{description:"Find free AI Actors.",command:'apify actors search "ai" --category AI --pricing-model FREE'},{description:"Output results as JSON for scripting.",command:'apify actors search "web scraper" --json'}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors-search";static args={query:A.string({description:"Search query to find Actors by title, name, description, username, or readme.",required:!1})};static flags={"sort-by":w.string({description:"Sort order for the results.",options:["relevance","popularity","newest","lastUpdate"],default:"relevance"}),category:w.string({description:"Filter by category (e.g. AI)."}),username:w.string({description:"Filter by Actor author username."}),"pricing-model":w.string({description:"Filter by pricing model.",options:["FREE","FLAT_PRICE_PER_MONTH","PRICE_PER_DATASET_ITEM","PAY_PER_EVENT"]}),limit:w.integer({description:"Maximum number of results to return.",default:20}),offset:w.integer({description:"Number of results to skip for pagination.",default:0})};static enableJsonFlag=!0;async run(){let{query:e}=this.args,{json:t,sortBy:o,category:s,username:i,pricingModel:n,limit:a,offset:c}=this.flags,l=zt();delete l.token;let d=new uu(l),u;try{u=await d.store().list({search:e,sortBy:o,category:s,username:i,pricingModel:n,limit:a,offset:c})}catch(f){process.exitCode=1,g({message:`Failed to search Apify Store: ${f instanceof Error?f.message:String(f)}`,stdout:!0});return}if(u.count===0){if(t){L(u);return}b({message:"No Actors found matching your search.",stdout:!0});return}if(t){L(u);return}let p=new B({allColumns:["Name","Description","Users (30d)","Pricing"],mandatoryColumns:["Name","Pricing"],columnAlignments:{"Users (30d)":"right",Name:"left"}});for(let f of u.items)p.pushRow({Name:`${f.title}
140
+ ${$i.gray(`${f.username}/${f.name}`)}`,Description:gu(f.description),"Users (30d)":$i.cyan(`${f.stats?.totalUsers30Days??0}`),Pricing:fu(f.currentPricingInfo?.pricingModel)});$({message:p.render(1),stdout:!0})}};import ne from"chalk";var $o=class extends h{static name="start";static description=`Starts Actor remotely and returns run details immediately.
141
+ Uses authenticated account and local key-value store for input.`;static examples=[{description:"Start the Actor defined in the current directory and return immediately.",command:"apify actors start"},{description:"Start a specific Actor with inline JSON input.",command:`apify actors start apify/hello-world --input '{"url":"https://example.com"}'`},{description:"Start with input from a file and custom memory/timeout.",command:"apify actors start apify/web-scraper --input-file ./input.json --memory 4096 --timeout 600"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors-start";static flags={...Dt("Actor"),input:w.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":w.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]})};static enableJsonFlag=!0;static args={actorId:A.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${D}' file.`})};async run(){let e=process.cwd(),t=Me(e)||{},o=await I(),s=await M(),i=s.username||s.id,{id:n,userFriendlyId:a,actorData:c}=await Ke.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),l={};this.flags.build&&(l.build=this.flags.build),this.flags.timeout&&(l.timeout=this.flags.timeout),this.flags.memory&&(l.memory=this.flags.memory);let d=await Nt(e,this.flags.input,this.flags.inputFile);if(d===!1)return;let u=Lt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:l,type:"Actor",inputOverride:d?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),p;for await(let N of u)p=N;if(this.flags.json){L(p);return}let f=`https://console.apify.com/actors/${n}/runs/${p.id}`,y=`https://console.apify.com/storage/datasets/${p.defaultDatasetId}`,v=[`${ne.gray("Run:")} Calling Actor ${a} (${ne.gray(n)})`,"",`${ne.yellow("Started")}: ${Y.display(p.startedAt)}`];p.containerUrl&&v.push(`${ne.yellow("Container URL")}: ${ne.blue(p.containerUrl)}`);let S=p.buildNumber.split(".").slice(0,2).join("."),E=c.versions.find(N=>N.versionNumber===S),C=Object.entries(c.taggedBuilds??{}).find(([,N])=>N.buildNumber===p.buildNumber)?.[0],P=[`${ne.yellow("Build")}:`,ne.cyan(p.buildNumber)];C?P.push(`(${ne.yellow(C)})`):P.push(`(${ne.gray("N/A")})`),E&&P.push(`| ${ne.gray("Actor version:")} ${ne.cyan(E.versionNumber)} (${ne.yellow(E.buildTag)})`),v.push(P.join(" ")),v.push(`${ne.yellow("Timeout")}: ${p.options.timeoutSecs.toLocaleString("en-US")} seconds`),v.push(`${ne.yellow("Memory")}: ${p.options.memoryMbytes} MB`),v.push("",`${ne.blue("Export results")}: ${y}`,`${ne.blue("View on Apify Console")}: ${f}`),$({message:v.join(`
142
+ `),stdout:!0})}};var Ro=class extends h{static name="actors";static description=`Search, list, deploy, and call Actors on the Apify platform.
143
+ For runtime operations inside a running Actor (push-data, get-input, set-value...), see 'apify actor' (singular).`;static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors";static subcommands=[$o,Io,Eo,Mt,Ft,Co,To,Ke,wo];async run(){this.printHelp()}};import hu from"process";import We from"chalk";var xi=["GET","POST","PUT","PATCH","DELETE"],yu=new Set(["GET","HEAD"]),Ri="https://docs.apify.com/api/openapi.json";function wu(r){if(!r)return"";let e;try{e=JSON.parse(r)}catch{throw new Error(`Invalid JSON in --params flag. Please provide a valid JSON object, e.g. '{"limit": 1}'.`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`--params must be a JSON object (e.g. '{"limit": 1}').`);let t=new URLSearchParams;for(let[o,s]of Object.entries(e))if(s!=null){if(typeof s=="object")throw new Error(`--params value for "${o}" must be a scalar (string, number, or boolean), got ${Array.isArray(s)?"array":"object"}. Query parameters cannot contain nested objects or arrays.`);t.append(o,String(s))}return t.toString()}m(wu,"parseParams");function Au(r){if(!r)return{};let e=r.trim();if(e.startsWith("{")){let o;try{o=JSON.parse(e)}catch{throw new Error(`Invalid JSON in --header flag. Provide a JSON object like '{"X-Foo": "bar"}'.`)}if(o===null||typeof o!="object"||Array.isArray(o))throw new Error("--header JSON must be an object mapping header names to string values.");let s={};for(let[i,n]of Object.entries(o)){if(typeof n!="string")throw new Error(`--header value for "${i}" must be a string, got ${typeof n}.`);s[i.trim()]=n.trim()}return s}let t=e.indexOf(":");if(t===-1)throw new Error('Header must be in "key:value" format, or a JSON object for multiple headers.');return{[e.slice(0,t).trim()]:e.slice(t+1).trim()}}m(Au,"parseHeaders");var xo=class extends h{static name="api";static description=`Makes an authenticated HTTP request to the Apify API and prints the response.
144
+ The endpoint can be a relative path (e.g. "acts", "v2/acts", or "/v2/acts"); the "v2/" prefix is added automatically if omitted.
145
+
146
+ Use --list-endpoints to see all available API endpoints.`;static examples=[{description:"Make a GET request to an API endpoint (defaults to GET).",command:"apify api users/me"},{description:"Pass the HTTP method as a positional argument before the endpoint.",command:"apify api GET /v2/actor-runs"},{description:"Create a resource by POSTing a JSON body.",command:`apify api POST acts -d '{"name":"my-actor"}'`},{description:"Pass query parameters as a JSON object.",command:`apify api actor-runs -p '{"limit":1,"desc":true}'`},{description:"Send one or more custom headers as a JSON object.",command:`apify api acts -H '{"X-Foo":"bar","X-Baz":"qux"}'`},{description:"List all available Apify API endpoints.",command:"apify api --list-endpoints"}];static docsUrl="https://docs.apify.com/api/v2";static args={methodOrEndpoint:A.string({required:!1,description:'The API endpoint path (e.g. "acts", "v2/acts", "/v2/users/me"), or an HTTP method followed by the endpoint (e.g. "GET /v2/users/me").'}),endpoint:A.string({required:!1,description:"The API endpoint path when the first argument is an HTTP method."})};static flags={method:w.string({char:"X",description:"The HTTP method to use. Defaults to GET.",choices:xi}),body:w.string({char:"d",description:'The request body (JSON string). Use "-" to read from stdin.',required:!1,stdin:2}),header:w.string({char:"H",description:`Additional HTTP header(s). Pass a single "key:value" string, or a JSON object like '{"X-Foo": "bar", "X-Baz": "qux"}' to send multiple headers. The flag can only be used once; use the JSON form for multiple headers.`,required:!1}),params:w.string({char:"p",description:`Query parameters as a JSON object, e.g. '{"limit": 1, "desc": true}'.`,required:!1}),"list-endpoints":w.boolean({char:"l",description:"List all available Apify API endpoints.",default:!1})};async run(){if(this.flags.listEndpoints){await this.printEndpoints();return}let e=this.flags.method?.toUpperCase(),t,o=this.args.methodOrEndpoint;if(o&&xi.includes(o.toUpperCase())){let f=o.toUpperCase();if(e&&e!==f)throw new Error(`Conflicting HTTP methods: positional "${f}" vs --method "${e}". Please specify the method only once.`);t=f,o=this.args.endpoint}else t=e;if(t??="GET",!o){this.printHelp();return}let s=wu(this.flags.params),i=Au(this.flags.header);if(this.flags.body){if(yu.has(t))throw new Error(`HTTP ${t} requests cannot have a request body. Use a different method (e.g. POST, PUT, PATCH) or omit --body.`);try{JSON.parse(this.flags.body)}catch{throw new Error("Invalid JSON in --body flag. Please provide a valid JSON string.")}}let n=await I(),a=n.token,c=o;c.startsWith("/")&&(c=c.slice(1)),c=c.replace(/^v2\//i,"");let l=`${n.baseUrl}/${c}`;if(s){let f=l.includes("?")?"&":"?";l=`${l}${f}${s}`}let d={..._r,Authorization:`Bearer ${a}`};this.flags.body&&(d["Content-Type"]="application/json");for(let[f,y]of Object.entries(i)){for(let v of Object.keys(d))v.toLowerCase()===f.toLowerCase()&&delete d[v];d[f]=y}let u=await fetch(l,{method:t,headers:d,body:this.flags.body||void 0}),p=await u.text();if(!u.ok){if(hu.exitCode=1,g({message:`${u.status} ${u.statusText}`}),p)try{let f=JSON.parse(p);$({message:JSON.stringify(f,null,2),stdout:!0})}catch{$({message:p,stdout:!0})}u.status===404&&$({message:`
147
+ Run ${We.cyan("apify api --list-endpoints")} to see all available Apify API endpoints.`,stdout:!1});return}if(p)try{let f=JSON.parse(p);$({message:JSON.stringify(f,null,2),stdout:!0})}catch{$({message:p,stdout:!0})}}async printEndpoints(){let e=await vu(),t={GET:We.green,POST:We.yellow,PUT:We.blue,PATCH:We.cyan,DELETE:We.red};for(let{method:o,path:s,summary:i}of e){let a=(t[o]||We.white)(o.padEnd(7)),c=i?We.gray(` ${i}`):"";console.log(`${a} ${s}${c}`)}}};async function vu(){let r;try{r=await fetch(Ri)}catch(o){throw new Error(`Failed to download the Apify OpenAPI spec from ${Ri}: ${o.message}`)}if(!r.ok)throw new Error(`Failed to download the Apify OpenAPI spec from ${Ri}: ${r.status} ${r.statusText}`);let e=await r.json(),t=[];for(let[o,s]of Object.entries(e.paths))for(let[i,n]of Object.entries(s))xi.includes(i.toUpperCase())&&t.push({method:i.toUpperCase(),path:o,summary:n.summary||""});return t.sort((o,s)=>o.path.localeCompare(s.path)||o.method.localeCompare(s.method)),t}m(vu,"fetchEndpoints");import Tu from"chalk";import Cu from"computer-name";import Iu from"cors";import _i from"express";import Eu from"open";import{cryptoRandomObjectId as $u}from"@apify/utilities";import bu from"@inquirer/password";var qa=Oe(async({message:r,mask:e})=>await bu({message:r,mask:e??"*"}));import Su from"@inquirer/select";var ze=Oe(async({message:r,choices:e,pageSize:t,loop:o,default:s})=>await Su({message:r,choices:e,pageSize:t,loop:o,default:s}));var ki="https://console.apify.com/settings/integrations",Ru=new URL(ki).origin,xu=ki.includes("localhost")?"http://localhost:3333":void 0,Ka="v1",Pi=m(async r=>{let e=await Xt(r,xu),t=await M();return e?(await Vr(t.id),R({message:`You are logged in to Apify as ${t.username||t.id}. ${Tu.gray(`Your token is stored at ${ge()}.`)}`})):g({message:"Login to Apify failed, the provided API token is not valid."}),e},"tryToLogin"),jt=class extends h{static name="login";static description=`Authenticates your Apify account and saves credentials to '${le(ge())}'.
148
+ All other commands use these stored credentials.
149
+
150
+ Run 'apify logout' to remove authentication.`;static group="Authentication";static interactive=!0;static interactiveNote="Prompts for an API token if not provided. To run non-interactively, pass --token <api-token>.";static examples=[{description:"Log in interactively (prompts to choose a method, then completes the flow accordingly).",command:"apify login"},{description:"Log in non-interactively with an API token.",command:"apify login --token apify_api_xxxxx"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-login";static flags={token:w.string({char:"t",description:"Apify API token.",required:!1}),method:w.string({char:"m",description:"Method of logging in to Apify.",choices:["console","manual"],required:!1})};async run(){let{token:e,method:t}=this.flags;if(e){await Pi(e);return}let o=t;if(t||(o=await ze({message:"Choose how you want to log in to Apify",choices:[{value:"console",name:"Through Apify Console in your default browser",short:"Through Apify Console"},{value:"manual",name:"Enter API token manually",short:"Manually"}],loop:!0})),o==="console"){let s,i=_i();i.use(Iu({origin:Ru,allowedHeaders:["Content-Type","Authorization"]})),i.use((d,u,p)=>{u.set("Connection","close"),p()}),i.use(_i.json());let n=$u();i.use((d,u,p)=>{let{token:f}=d.query;if(!f){let y=d.get("Authorization");if(y){let[v,S,...E]=y.trim().split(/\s+/);v.toLowerCase()==="bearer"&&S&&E.length===0&&(f=S)}}f!==n?(u.status(401),u.send("Authorization failed")):p()});let a=_i.Router();i.use(`/api/${Ka}`,a),a.post("/login-token",async(d,u)=>{try{if(d.body.apiToken)await Pi(d.body.apiToken);else throw new Error("Request did not contain API token");u.end()}catch(p){let f=`Login to Apify failed with error: ${p.message}`;g({message:f}),u.status(500),u.send(f)}s.close()}),a.post("/exit",(d,u)=>{d.body.isWindowClosed?g({message:"Login to Apify failed, the console window was closed."}):d.body.actionCanceled?g({message:"Login to Apify failed, the action was canceled in the Apify Console."}):g({message:"Login to Apify failed."}),u.end(),s.close()}),s=i.listen(0);let{port:c}=s.address(),l=new URL(ki);l.searchParams.set("localCliCommand","login"),l.searchParams.set("localCliPort",`${c}`),l.searchParams.set("localCliToken",n),l.searchParams.set("localCliApiVersion",Ka);try{l.searchParams.set("localCliComputerName",encodeURIComponent(Cu()))}catch{}b({message:`Opening Apify Console at "${l.href}"...`}),await Eu(l.href)}else{console.log("Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations");let s=await qa({message:"token:"});await Pi(s)}}};var Bt=class extends h{static name="logout";static description=`Removes authentication by deleting your API token and account information from '${le(ge())}'.
151
+ Run 'apify login' to authenticate again.`;static group="Authentication";static examples=[{description:"Remove the stored Apify credentials.",command:"apify logout"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-logout";async run(){await Gt(ge()),await Vr(null),R({message:"You are logged out from your Apify account."})}};var _o=class extends h{static name="token";static description="Prints the current API token for the Apify CLI.";static examples=[{description:"Print the stored API token to stdout (use with care \u2014 it is a secret).",command:"apify auth token"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-auth-token";async run(){await I();let e=await M();e.token&&$({message:e.token,stdout:!0})}};var Po=class extends h{static name="auth";static description="Log in, log out, and inspect your stored Apify API token. Also available as `apify login` / `apify logout`.";static group="Authentication";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-auth";static subcommands=[jt,Bt,_o];async run(){this.printHelp()}};import ko from"chalk";var Oo=class extends h{static name="add-tag";static description="Adds a tag to a specific Actor build.";static examples=[{description:'Tag a successful build as "latest".',command:"apify builds add-tag --build <buildId> --tag latest"},{description:'Tag a build with a custom name like "beta".',command:"apify builds add-tag --build <buildId> --tag beta"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-add-tag";static flags={build:w.string({char:"b",description:"The build ID to tag.",required:!0}),tag:w.string({char:"t",description:"The tag to add to the build.",required:!0})};async run(){let{build:e,tag:t}=this.flags,o=await I(),s=await o.build(e).get();if(!s){g({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(s.status!=="SUCCEEDED"){g({message:`Build with ID "${e}" has status "${s.status}". Only successful builds can be tagged.`,stdout:!0});return}let i=await o.actor(s.actId).get();if(!i){g({message:`Actor with ID "${s.actId}" was not found.`,stdout:!0});return}let a=(i.taggedBuilds??{})[t];if(a?.buildId===e){x({message:`Build "${e}" is already tagged as "${t}".`,stdout:!0});return}try{await o.actor(s.actId).update({taggedBuilds:{[t]:{buildId:s.id}}});let c=a?.buildNumber?` (previously pointed to build ${ko.gray(a.buildNumber)})`:"";R({message:`Tag "${ko.yellow(t)}" added to build ${ko.gray(s.buildNumber)} (${ko.gray(e)})${c}`,stdout:!0})}catch(c){let l=c;g({message:`Failed to add tag "${t}" to build "${e}".
152
+ ${l.message||l}`,stdout:!0})}}};import te from"chalk";var _u=m(r=>r,"noColor");function ee({bytes:r,shortBytes:e=!1,colorFunc:t=_u,precision:o=2}){let s=[e?"B":"Bytes","KB","MB","GB","TB"];if(r===0)return e?`${0 .toPrecision(o)} B`:`${0 .toPrecision(o)} Byte`;let i=Math.floor(Math.log(r)/Math.log(1e3));return`${(r/1e3**i).toFixed(o)} ${t(s[i])}`}m(ee,"prettyPrintBytes");var No=class extends h{static name="info";static description="Prints information about a specific build.";static examples=[{description:"Print information about a build.",command:"apify builds info <buildId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-info";static args={buildId:A.string({required:!0,description:"The build ID to get information about."})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,t=await I(),o=await t.build(e).get();if(!o){g({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){L(o);return}let s=await t.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[f,y]of Object.entries(s.taggedBuilds))if(y.buildId===o.id){i=f;break}}let n=Reflect.get(o,"exitCode"),a=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",c=i?` (tagged as ${te.yellow(i)})`:"",l=typeof n<"u"?` (exit code: ${te.gray(n)})`:"",d=[`${te.yellow("Actor")}: ${a} (${te.gray(o.actId)})`,"",`${te.yellow("Build Information")} (ID: ${te.gray(o.id)})`,` ${te.yellow("Build Number")}: ${o.buildNumber}${c}`,` ${te.yellow("Status")}: ${Pe(o.status)}${l}`,` ${te.yellow("Started")}: ${Y.display(o.startedAt)}`];if(o.finishedAt)d.push(` ${te.yellow("Finished")}: ${Y.display(o.finishedAt)} (took ${te.gray(tr.format(o.stats?.durationMillis??0))})`);else{let f=Date.now()-o.startedAt.getTime();d.push(` ${te.yellow("Finished")}: ${te.gray(`Running for ${tr.format(f)}`)}`)}o.stats?.computeUnits&&d.push(` ${te.yellow("Compute Units")}: ${o.stats.computeUnits.toFixed(3)}`);let u=Reflect.get(o.stats??{},"imageSizeBytes");u&&d.push(` ${te.yellow("Docker Image Size")}: ${ee({bytes:u})}`),d.push(` ${te.yellow("Origin")}: ${o.meta.origin??"UNKNOWN"}`),d.push("");let p=`https://console.apify.com/actors/${o.actId}/builds/${o.buildNumber}`;d.push(`${te.blue("View in Apify Console")}: ${p}`),$({message:d.join(`
153
+ `),stdout:!0})}};var Lo=class extends h{static name="log";static description="Prints the log of a specific build.";static examples=[{description:"Print the build log.",command:"apify builds log <buildId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-log";static args={buildId:A.string({required:!0,description:"The build ID to get the log from."})};async run(){let{buildId:e}=this.args,t=await I(),o=await t.build(e).get();if(!o){g({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}b({message:`Log for build with ID "${e}":
154
+ `});try{await ke({job:o,apifyClient:t})}catch(s){g({message:`Failed to get log for build with ID "${e}": ${s.message}`,stdout:!0})}}};import ve from"chalk";var Pu=m(()=>new B({allColumns:["Number","ID","Status","Took"],mandatoryColumns:["Number","ID","Status","Took"],columnAlignments:{Took:"right"}}),"tableFactory"),Do=class extends h{static name="ls";static description="Lists all builds of the Actor.";static examples=[{description:"List builds of the Actor in the current directory.",command:"apify builds ls"},{description:"List builds of a specific Actor.",command:"apify builds ls apify/hello-world"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-ls";static flags={offset:w.integer({description:"Number of builds that will be skipped.",default:0}),limit:w.integer({description:"Number of builds that will be listed.",default:10}),desc:w.boolean({description:"Sort builds in descending order.",default:!1}),compact:w.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:A.string({description:"Optional Actor ID or Name to list runs for. By default, it will use the Actor from the current directory."})};static enableJsonFlag=!0;async run(){let{desc:e,limit:t,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await I(),c=await Je({providedActorNameOrId:n,client:a});if(!c.valid){g({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let l=await a.actor(c.id).builds().list({desc:e,limit:t,offset:o}),d=await a.actor(c.id).get(),u=Br(l.items,y=>{let v=Reflect.get(y,"buildNumber"),[S,E]=v.split(".");return`${S}.${E}`}),p=Object.entries(d.taggedBuilds??{}).reduce((y,[v,S])=>(y[S.buildNumber]=v,y),{});if(i){for(let y of l.items){let v=Reflect.get(y,"buildNumber"),S=p[v];S&&Reflect.set(y,"buildTag",S)}L(l);return}$({message:`${ve.reset("Showing")} ${ve.yellow(l.items.length)} out of ${ve.yellow(l.total)} builds for Actor ${ve.yellow(c.userFriendlyId)} (${ve.gray(c.id)})
155
+ `,stdout:!0});let f=Object.entries(u).sort((y,v)=>y[0].localeCompare(v[0]));for(let[y,v]of f){if(!v?.length){$({message:`No builds for version ${y}`,stdout:!0});continue}let S=d.versions.find(N=>N.versionNumber===y)?.buildTag,E=this.generateTableForActorVersion({buildsForVersion:v,buildTagToActorVersion:p}),C=S?` (latest build gets tagged with ${ve.yellow(S)})`:"",P=[ve.reset(`Builds for Actor Version ${ve.yellow(y)}${C}`),E.render(s?0:-1),""];$({message:P.join(`
156
+ `),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:t}){let o=Pu();for(let s of e){let i=Reflect.get(s,"buildNumber"),n=t[i]?` (${ve.yellow(t[i])})`:"",a;if(s.finishedAt){let c=s.finishedAt.getTime()-s.startedAt.getTime();a=ve.gray(`${me.format(c,void 0,{left:""})}`)}else{let c=Date.now()-s.startedAt.getTime();a=ve.gray(`Running for ${me.format(c,void 0,{left:""})}`)}o.pushRow({Number:`${i}${n}`,ID:ve.gray(s.id),Status:Pe(s.status),Took:a})}return o}};import gr from"chalk";var Fo=class extends h{static name="remove-tag";static description="Removes a tag from a specific Actor build.";static examples=[{description:"Remove a tag from a build (prompts for confirmation).",command:"apify builds remove-tag --build <buildId> --tag beta"},{description:"Remove a tag non-interactively.",command:"apify builds remove-tag --build <buildId> --tag beta --yes"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-remove-tag";static flags={build:w.string({char:"b",description:"The build ID to remove the tag from.",required:!0}),tag:w.string({char:"t",description:"The tag to remove from the build.",required:!0}),...ie};async run(){let{build:e,tag:t,yes:o}=this.flags,s=await I(),i=await s.build(e).get();if(!i){g({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let n=await s.actor(i.actId).get();if(!n){g({message:`Actor with ID "${i.actId}" was not found.`,stdout:!0});return}let c=(n.taggedBuilds??{})[t];if(!c){g({message:`Tag "${t}" does not exist on Actor "${n.name}".`,stdout:!0});return}if(c.buildId!==e){g({message:`Tag "${t}" is not associated with build "${e}". It points to build "${c.buildNumber}" (${c.buildId}).`,stdout:!0});return}if(!await Z({message:`Are you sure you want to remove tag "${gr.yellow(t)}" from build ${gr.gray(i.buildNumber)}?`,providedConfirmFromStdin:o||void 0})){b({message:"Tag removal was canceled.",stdout:!0});return}try{await s.actor(i.actId).update({taggedBuilds:{[t]:null}}),R({message:`Tag "${gr.yellow(t)}" removed from build ${gr.gray(i.buildNumber)} (${gr.gray(e)})`,stdout:!0})}catch(d){let u=d;g({message:`Failed to remove tag "${t}" from build "${e}".
157
+ ${u.message||u}`,stdout:!0})}}};import ku from"@inquirer/input";var Wa=Oe(async({message:r,expectedValue:e,failureMessage:t})=>await ku({message:r,validate(s){return s===e?!0:t??"That is not the correct input!"}}));var Uo=class extends h{static name="rm";static description="Permanently removes an Actor build from the Apify platform.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting. Tagged builds additionally require typing the tag name.";static examples=[{description:"Delete a build (prompts for confirmation).",command:"apify builds rm <buildId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-rm";static args={buildId:A.string({description:"The build ID to delete.",required:!0})};static flags={...ie};async run(){let{buildId:e}=this.args,{yes:t}=this.flags,o=await I(),s=await o.build(e).get();if(!s){g({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let i=await o.actor(s.actId).get(),n;if(i?.taggedBuilds){for(let[c,l]of Object.entries(i.taggedBuilds))if(e===l.buildId){n=c;break}}let a;if(n?a=await Wa({message:`Are you sure you want to delete this Actor Build? If so, please type in "${n}":`,expectedValue:n,failureMessage:"Your provided value does not match the build tag.",providedConfirmFromStdin:t?n:void 0}):a=await Z({message:"Are you sure you want to delete this Actor Build?",providedConfirmFromStdin:t||void 0}),!a){b({message:`Deletion of build "${e}" was canceled.`,stdout:!0});return}try{await o.build(e).delete(),R({message:`Build with ID "${e}" was deleted.`,stdout:!0})}catch(c){let l=c;g({message:`Failed to delete build "${e}".
158
+ ${l.message||l}`,stdout:!0})}}};var Mo=class extends h{static name="builds";static description="Create, inspect, tag, and delete Actor builds on the Apify platform.";static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds";static subcommands=[Oo,Fo,Uo,Do,Lo,No,Ot];async run(){this.printHelp()}};var jo=class extends Ke{static name="call"};import Ou from"assert";import{existsSync as za,openSync as Nu}from"fs";import{mkdir as Xa,readFile as Lu,symlink as Du,unlink as Fu,writeFile as Za}from"fs/promises";import{homedir as Uu}from"os";import{dirname as Mu,join as Xe}from"path";import{ReadStream as ju}from"tty";import H from"chalk";import Qa from"which";var Bu=m(r=>Xe(r,".install-marker"),"pathToInstallMarker"),ec=m(()=>process.env.HOME??Uu(),"HOMEDIR"),hr=class extends h{static name="install";static description="Finalizes the first-time setup of Apify and Actor CLI.";static hidden=!0;async run(){let{installMethod:e,installPath:t,version:o}=z();if(e!=="bundle"){b({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}Ou(t,"When CLI is installed via bundles, the install path must be set");let s=Bu(t);if(za(s)){b({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}if(process.platform!=="win32"){await this.symlinkToLocalBin(t);try{await this.promptAddToShell()}catch(i){g({message:i.message||"Failed to automatically handle shell integration"})}$({message:""})}await Za(s,o),T("[install] install marker written to",s),$({message:["",H.green("Apify and Actor CLI were installed successfully!"),"",H.gray(` Version: ${H.green(o)}`),H.gray(` Location: ${H.bold.white(le(Xe(t,"apify")))} and ${H.bold.white(le(Xe(t,"actor")))}`)].join(`
159
+ `)}),$({message:""}),R({message:"To get started, run:"}),$({message:H.white.bold(` apify --help
160
+ actor --help`)})}async symlinkToLocalBin(e){let t=ec();if(T("[install -> symlinkToLocalBin] user home directory",t),!t){T("[install -> symlinkToLocalBin] user home directory not found"),x({message:H.gray("User home directory not found, cannot symlink to ~/.local/bin")});return}let o=Xe(t,".local","bin");await Xa(o,{recursive:!0});let s=["apify","actor","apify-cli"];for(let i of s){let n=Xe(e,i);if(!za(n)){T("[install] file not found for symlinking",i,n),x({message:H.gray(`Bundle not found for symlinking: ${i}`)});continue}let a=Xe(o,i);await Fu(a).catch(()=>{}),await Du(n,a),T("[install] symlink created for item",i,a)}b({message:H.gray(`Symlinked apify, actor, and apify-cli to ${le(o)}`)})}async confirmFromTty(e){let t,o,s=`${H.green("?")} ${H.bold(e)} ${H.dim("(Y/n)")} `,i=m(n=>{process.stdout.write(`\r\x1B[2K${H.green("?")} ${H.bold(e)} ${H.cyan(n)}
161
+ `)},"writeDone");try{return T("[install] opening /dev/tty for raw mode"),t=Nu("/dev/tty","r"),o=new ju(t),process.stdout.write(s),o.setRawMode(!0),o.resume(),await new Promise(a=>{let c=m(l=>{let d=l.toString();d==="y"||d==="Y"||d==="\r"||d===`
162
+ `?(o.removeListener("data",c),i("Yes"),a(!0)):d==="n"||d==="N"?(o.removeListener("data",c),i("No"),a(!1)):(d===""||d==="")&&(o.removeListener("data",c),process.stdout.write(`
163
+ `),a(!1))},"onData");o.on("data",c)})}catch(n){return T("[install] failed to open /dev/tty for raw mode",n),!1}finally{o&&(o.setRawMode(!1),o.pause(),o.destroy())}}async promptAddToShell(){let[e,t]=await Promise.allSettled([Qa("apify",{nothrow:!0}),Qa("actor",{nothrow:!0})]);if(e.status==="fulfilled"&&t.status==="fulfilled"&&e.value&&t.value){T("[install -> promptAddToShell] already in PATH",{apifyCliPath:e,actorCliPath:t}),b({message:H.gray("Apify and Actor CLIs are already in PATH, skipping shell integration")});return}let o=ec();T("[install -> promptAddToShell] user home directory",o);let s=process.env.APIFY_CLI_INSTALL??Xe(o,".apify"),i=process.env.FINAL_BIN_DIR??Xe(s,"bin"),n=process.env.PROVIDED_INSTALL_DIR??s;if(!n){x({message:H.gray("Install directory not found, cannot add to shell")});return}let a=process.env.FINAL_BIN_DIR??i;$({message:""});let c="Should the CLI handle adding itself to your shell automatically?",l;process.env.APIFY_OPEN_TTY?l=await this.confirmFromTty(c):(T("[install] opening /dev/tty for raw mode not requested, falling back to normal flow"),l=await Z({message:c,providedConfirmFromStdin:!1}));let d=bn(),u=Sn(o,d),p=`"${n.replaceAll('"','\\"')}"`,f=[],y=!0;switch(d){case"bash":case"zsh":{f.push(`export APIFY_CLI_INSTALL=${p}`),f.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"');break}case"fish":{f.push(`set --export APIFY_CLI_INSTALL ${p}`),f.push(`set --export PATH ${a} $PATH`);break}default:{f.push(`export APIFY_CLI_INSTALL=${p}`),f.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),l=!1,y=!1;break}}if($({message:""}),l&&u){let E=`${await Lu(u,"utf-8").catch(C=>{if(C.code==="ENOENT")return"";throw new Error(`Failed to read config file "${le(u)}". Received error code: ${C.code}; ${C.message}`)})}
164
+
165
+ # apify cli
166
+ ${f.join(`
167
+ `)}
168
+ `;try{await Xa(Mu(u),{recursive:!0}),await Za(u,E)}catch(C){throw C.code==="EACCES"?new Error(`Failed to write to config file "${le(u)}", as the CLI does not have permission to write to it.`):new Error(`Failed to write to config file "${le(u)}". Received error code: ${C.code}; ${C.message}`)}b({message:[H.gray(`Added "${le(a)}" to your PATH in ${le(u)}.`),H.gray(` You may need to run ${H.white.bold(`source ${le(u)}`)} to reload your shell.`)].join(`
169
+ `)});return}let v=u??"your shell config file";if(y){let S=`echo -e '${f.join("\\n")}' >> "${v}" && source "${v}"`;b({message:[H.gray("The Apify & Actor CLIs are not in your PATH. Run:"),"",H.white.bold(` ${S}`)].join(`
170
+ `)});return}b({message:[H.gray(`Manually add the following lines to ${v} or similar:`),...f.map(S=>H.white.bold(` ${S}`))].join(`
171
+ `)})}};import{spawn as Wu}from"child_process";import{existsSync as zu}from"fs";import{lstat as Xu,readdir as Zu,writeFile as oc}from"fs/promises";import{dirname as Qu,join as Oi}from"path";import Ni from"chalk";import{gte as sc}from"semver";import{Result as Vu}from"@sapphire/result";import{execa as Gu}from"execa";var Yu=m(async(r,e,t)=>{let o=Ge(r);T("spawnPromised",{escapedCommand:o,args:e,opts:t});let s=Gu(o,e,{shell:!0,windowsHide:!0,env:t.env,cwd:t.cwd,stdout:process.env.APIFY_NO_LOGS_IN_TESTS?["pipe"]:["pipe","inherit"],stderr:process.env.APIFY_NO_LOGS_IN_TESTS?["pipe"]:["pipe","inherit"],verbose:process.env.APIFY_CLI_DEBUG?"full":void 0});return Vu.fromAsync(s.catch(i=>{throw new Error(`${r} exited with code ${i.exitCode}`,{cause:i})}))},"spawnPromised");async function fe({cmd:r,args:e=[],opts:t={},overrideCommand:o}){Ce({message:`${o||r} ${e.join(" ")}`});let s=await Yu(r,e,t);if(s.isErr()){let i=s.unwrapErr();if(g({message:i.message}),i.cause)throw i.cause}}m(fe,"execWithLog");import{execSync as tc}from"child_process";import{existsSync as Hu,readFileSync as Ju}from"fs";var Be=z();function qu(){return Be.platform==="linux"?Hu("/etc/alpine-release"):!1}m(qu,"isInstalledOnMusl");function Ku(){return Be.platform==="darwin"&&Be.arch==="x64"?!tc("sysctl -a",{encoding:"utf-8"}).includes("AVX2"):Be.platform==="linux"&&Be.arch==="x64"?!Ju("/proc/cpuinfo","utf-8").includes("avx2"):Be.platform==="windows"?Be.arch==="arm64"?!0:tc(`pwsh -c "!(Add-Type -MemberDefinition '[DllImport(\\"kernel32.dll\\")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);' -Name 'Kernel32' -Namespace 'Win32' -PassThru)::IsProcessorFeaturePresent(40)"`,{encoding:"utf-8",windowsHide:!0}).trim().toLowerCase()==="true":!1}m(Ku,"isInstalledOnBaseline");async function rc(r){let e=r.replace(/^v(\d+)/,"$1"),t=e==="latest"?"latest":`tags/v${e}`,o=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/${t}`,{headers:{"User-Agent":nt}});if(!o.ok)return T("useCLIVersionAssets","Failed to fetch release",{statusCode:o.status,body:await o.text(),version:r,tag:t}),null;let s=await o.json(),i=qu(),n=Ku(),a=s.assets.filter(c=>{let[l,d,u,p,f,y]=c.name.replace(e,"version").replace(".exe","").split("-");return u!==Be.platform||p!==Be.arch?!1:i?f==="musl":n?y==="baseline"||f==="baseline":!f&&!y});return T("useCLIVersionAssets","Fetched release",{version:s.tag_name,filteredAssets:a}),{assets:a,version:s.tag_name.replace(/^v(\d+)/,"$1")}}m(rc,"useCLIVersionAssets");var ic={bundle:m((r,e)=>[`${e}`,"upgrade"],"bundle"),npm:m(r=>["npm","install","-g",`apify-cli@${r}`],"npm"),pnpm:m(r=>["pnpm","install","-g",`apify-cli@${r}`],"pnpm"),bun:m(r=>["bun","install","-g",`apify-cli@${r}`],"bun"),homebrew:m(()=>["brew","upgrade","apify-cli"],"homebrew"),volta:m(r=>["volta","install",`apify-cli@${r}`],"volta")},Bo="1.0.1",nc="https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1",yr=class extends h{static name="upgrade";static description="Checks that installed Apify CLI version is up to date.";static group="Utilities";static examples=[{description:"Check for a newer CLI version and upgrade if available.",command:"apify upgrade"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-upgrade";static hidden=!0;static aliases=["cv","check-version"];static flags={force:w.boolean({description:"[DEPRECATED] This flag is now ignored, as running the command manually will always check for the latest version.",required:!1,char:"f"}),version:w.string({description:"The version of the CLI to upgrade to. If not provided, the latest version will be used.",required:!1}),"internal-automatic-call":w.boolean({description:"Whether the command was called automatically by the CLI for a version check.",hidden:!0,default:!1})};get cliName(){return this.entrypoint==="apify"?"Apify CLI":"Actor CLI"}async run(){if(this.flags.version){await this.handleInstallSpecificVersion(this.flags.version);return}let e=await na(!this.flags.internalAutomaticCall),{installMethod:t}=z();if(!e.shouldUpdate||e.currentVersion===Js){T("[upgrade] no update needed",{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||b({message:`${this.cliName} is up to date \u{1F44D}
172
+ `});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion("latest");return}let o=ic[t]("latest",this.entrypoint).join(" ");$({message:""});let s=[`You are using an old version of ${this.cliName}. We strongly recommend you always use the latest available version.`,` \u21AA Run ${Ni.bgWhite(Ni.black(o))} to update! \u{1F44D}
173
+ `].join(`
174
+ `);x({message:s})}async handleInstallSpecificVersion(e){if(e!=="latest"&&!sc(e,Bo)){g({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Bo}.`});return}let t=await rc(e);if(!t){g({message:"The provided version does not exist. Please check the version number and try again."});return}let{assets:o,version:s}=t;if(!sc(s,Bo)){g({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Bo}.`});return}let i=z();if(i.installMethod==="bundle"){if(!o.length){g({message:["Failed to find the assets for your system and the provided version. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:",`- The version you are trying to upgrade to: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`].join(`
175
+ `)});return}let a=Qu(process.execPath);T("[upgrade] bundleDirectory",a);let c=await Zu(a);if(!c.some(l=>l.startsWith("apify")||l.startsWith("actor"))){T("[upgrade] directoryEntries",c),g({message:[`Failed to find the currently installed ${this.cliName} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${a}`].join(`
176
+ `)});return}if(i.platform==="windows")return this.startUpgradeProcess(a,s,o);await this.handleUnixUpgrade(a,s,o),this.successMessage(s);return}let n=ic[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){b({message:`Would run command: ${n.join(" ")}`});return}try{await fe({cmd:n[0],args:n.slice(1)}),this.successMessage(s)}catch{g({message:`Failed to upgrade the CLI. Please run the following command manually: ${n.join(" ")}`})}}successMessage(e){R({message:`Successfully upgraded to ${e} \u{1F44D}`})}async startUpgradeProcess(e,t,o){await this.upsertUpgradeScript(e);let s=["-ExecutionPolicy","Bypass","-File",`"${Oi(e,"upgrade.ps1")}"`,"-ProcessId",process.pid.toString(),"-InstallLocation",`"${e}"`,"-Version",`"${t}"`],i=o.map(a=>a.browser_download_url).join(",");s.push("-AllUrls",`"${i}"`),T("[upgrade] starting upgrade process with args",s),b({message:"Starting upgrade process..."});let n=Wu("powershell.exe",s,{detached:!0,shell:!0,stdio:"inherit",windowsHide:!1,windowsVerbatimArguments:!0});n.on("spawn",()=>{T("[upgrade] upgrade process spawned"),n.unref(),process.exit(0)}),n.on("error",a=>{g({message:`Failed to start the upgrade process: ${a.message}`})})}async upsertUpgradeScript(e){let t=Oi(e,"upgrade.ps1");if(zu(t))return;let o=z(),s=await fetch(nc,{headers:{"User-Agent":nt}});s.ok||(g({message:["Failed to fetch the upgrade script. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:",`- The system you are running on: ${o.platform} ${o.arch}`,`- The URL of the asset that failed to fetch: ${nc}`,`- The status code of the response: ${s.status}`].join(`
177
+ `)}),process.exit(1));let i=await s.arrayBuffer();await oc(t,Buffer.from(i)),T("[upgrade] downloaded upgrade script to",t)}async handleUnixUpgrade(e,t,o){let s=z();for(let i of o){let n=i.name.split("-")[0],a=Oi(e,n);b({message:`Downloading \`${n}\` binary of the Apify CLI...`});let c=await fetch(i.browser_download_url,{headers:{"User-Agent":nt}});if(!c.ok){let d=await c.text();T("[upgrade] failed to fetch asset",{asset:i,status:c.status,body:d}),g({message:[`Failed to fetch the ${n} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${t}`,`- The system you are running on: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The status code of the response: ${c.status}`,`- The body of the response: ${d}`].join(`
178
+ `)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){b({message:`Would write asset ${n} to ${a}`});continue}b({message:Ni.gray(`Writing ${n} to ${a}...`)});let l=await c.arrayBuffer();try{let d=await Xu(a).then(u=>u.mode).catch(()=>493);await oc(a,Buffer.from(l),{mode:d|448}),T(`[upgrade ${n}] wrote asset to`,a)}catch(d){T("[upgrade] failed to write asset",{error:d}),g({message:[`Failed to write the ${n} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${t}`,`- The system you are running on: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The error: ${d.message}`].join(`
179
+ `)})}}}};import{mkdir as np,readdir as ap,stat as pc}from"fs/promises";import{join as pt}from"path";import fc from"process";import{gte as cp,minVersion as lp}from"semver";import{fetchManifest as dp,manifestUrl as mp}from"@apify/actor-templates";import{createWriteStream as ep}from"fs";import{pipeline as tp}from"stream/promises";import{Separator as cc}from"@inquirer/core";var ac=["JavaScript","TypeScript","Python"];async function Li(r){return r?(Qt(r),r):rp()}m(Li,"ensureValidActorName");async function lc(r,e){let t=await e;if(t instanceof Error)throw t;if(r){let o=t.templates.find(s=>s.name===r);if(!o)throw new Error(`Could not find the selected template: ${r} in the list of templates.`);return o}return uc(t)}m(lc,"getTemplateDefinition");async function dc(r,e){let t=await e;if(t instanceof Error)throw t;try{let o=await Nr(t.localReadmeSuffixUrl),s=ep(r,{flags:"a"});s.write(`
180
+
181
+ `),await tp(o,s)}catch(o){x({message:`Could not append local development instructions to README.md. Cause: ${o.message}`})}}m(dc,"enhanceReadmeWithLocalSuffix");function mc(r){let{actorName:e,dependenciesInstalled:t,postCreate:o,gitRepositoryInitialized:s,installCommandSuggestion:i}=r,n=`\u2705 Actor '${e}' created successfully!`;return t?n+=`
182
+
183
+ Next steps:
184
+
185
+ cd "${e}"
186
+ apify run`:n+=`
187
+
188
+ Next steps:
189
+
190
+ cd "${e}"
191
+ ${i||"install dependencies with your package manager"}
192
+ apify run`,n+=`
193
+
194
+ \u{1F4A1} Tip: Use 'apify push' to deploy your Actor to the Apify platform
195
+ \u{1F4D6} Docs: https://docs.apify.com/platform/actors/development`,s&&(n+=`
196
+ \u{1F331} Git repository initialized in '${e}'. You can now commit and push your Actor to Git.`),o&&(n+=`
197
+
198
+ ${o}`),n}m(mc,"formatCreateSuccessMessage");async function uc(r){let e=await op();for(;;){let t=await sp(r,e);if(t){if(await ip())return t}else return uc(r)}}m(uc,"executePrompts");async function rp(){return await at({message:"Name of your new Actor:",validate:m(e=>{try{Qt(e)}catch(t){return t.message}return!0},"validate")})}m(rp,"promptActorName");async function op(){return await ze({message:"Choose the programming language of your new Actor:",choices:ac,loop:!1,default:ac[0]})}m(op,"promptProgrammingLanguage");async function sp(r,e){let t=[...r.templates.filter(s=>s.category.toLowerCase()===e.toLowerCase()).map(s=>({name:s.label,value:s})),new cc,{name:"Go back",value:!1}];return await ze({message:"Choose a template for your new Actor. You can check more information at https://apify.com/templates.",default:t[0],choices:t,loop:!1,pageSize:8})}m(sp,"promptTemplateDefinition");async function ip(){let r=[{name:"Install dependencies",value:!0},new cc,{name:"Go back",value:!1}];return await ze({message:"Almost done! Last step is to install dependencies.",default:r[0],choices:r,loop:!1})}m(ip,"promptTemplateInstallation");var Vo=class extends h{static name="create";static description="Creates an Actor project from a template in a new directory. The command automatically initializes a git repository in the newly created Actor directory.";static group="Local Actor Development";static interactive=!0;static interactiveNote="Prompts for an Actor name and template if not provided. To run non-interactively, pass the name as a positional argument and --template.";static examples=[{description:"Create a new Actor project interactively (prompts for name and template).",command:"apify create"},{description:"Create non-interactively with explicit name and template.",command:"apify create my-actor --template js-crawlee-cheerio"},{description:"Create without installing dependencies (faster; run install yourself later).",command:"apify create my-actor --template python-start --skip-dependency-install"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-create";static flags={template:w.string({char:"t",description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${mp} to find available template names.`,required:!1}),"skip-dependency-install":w.boolean({description:"Skip installing Actor dependencies.",required:!1}),"template-archive-url":w.string({description:"Actor template archive url. Useful for developing new templates.",required:!1,hidden:!0}),"omit-optional-deps":w.boolean({aliases:["no-optional"],description:"Skip installing optional dependencies.",required:!1}),"skip-git-init":w.boolean({description:"Skip initializing a git repository in the Actor directory.",required:!1})};static args={actorName:A.string({required:!1,description:"Name of the Actor and its directory."})};async run(){let{actorName:e}=this.args,{template:t,skipDependencyInstall:o,skipGitInit:s}=this.flags,{templateArchiveUrl:i}=this.flags,n=!1,a=dp().catch(C=>new Error(`Could not fetch template list from server. Cause: ${C?.message}`));e=await Li(e);let c=fc.cwd(),l=pt(c,e);for(;;){let C=await pc(l).catch(()=>null),P=C&&await ap(l).then(N=>N.length>0).catch(()=>!1);if(C?.isDirectory()&&P){g({message:`Cannot create new Actor, directory '${e}' already exists. Please provide a different name. You can use "apify init" to create a local Actor environment inside an existing directory.`}),e=await Li(),l=pt(c,e);continue}C||await np(l,{recursive:!0});break}let d=null;if(this.telemetryData.fromArchiveUrl=!!i,!i){let C=await lc(t,a);({archiveUrl:i,messages:d}=C),this.telemetryData.templateId=C.id,this.telemetryData.templateName=C.name,this.telemetryData.templateLanguage=C.category,"skipOptionalDeps"in C&&(n=C.skipOptionalDeps)}this.flags.omitOptionalDeps&&(n=!0),await jr({url:i,pathTo:l});let u=de(pt(l,D));await Lr(Object.assign(u||Cr,{name:e}),l),await Dr(l),await fo(l);let p=pt(l,"package.json"),f=pt(l,"README.md");await dc(f,a);let y=!1;o||await(await Ne({cwd:l})).inspectAsync(async P=>{let N=lp(Ie);if(!P.runtime){switch(P.type){case 0:{x({message:`No Node.js detected! Please install Node.js ${N} or higher to be able to run Node.js Actors locally.`});break}case 2:case 1:{x({message:`No Python detected! Please install Python ${st} or higher to be able to run Python Actors locally.`});break}default:}return}let{runtime:O}=P;switch(P.type){case 0:{Mr(O.version)||x({message:`You are running Node.js version ${O.version}, which is no longer supported. Please upgrade to Node.js version ${N} or later.`}),await rn(p,{name:e});let U=["install"];if(n)switch(O.pmName){case"npm":{cp(O.pmVersion,"7.0.0")?U.push("--omit=optional"):U.push("--no-optional");break}case"bun":{U.push("--omit=optional");break}case"deno":{U.push("--node-modules-dir");break}default:}await fe({cmd:O.pmPath,args:U,opts:{cwd:l},overrideCommand:O.pmName}),y=!0;break}case 1:case 2:{if(!Ur(O.version)){x({message:`Python Actors require Python 3.9 or higher, but you have Python ${O.version}!`}),x({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}let U=pt(l,".venv");b({message:`Python version ${O.version} detected.`}),b({message:`Creating a virtual environment in "${U}" and installing dependencies from "requirements.txt"...`}),fc.env.VIRTUAL_ENV||(await fe({cmd:O.executablePath,args:["-m","venv","--prompt",".",Qi],opts:{cwd:l}}),O=(await ir({cwd:l,force:!0})).unwrap(),P.runtime=O),await fe({cmd:O.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","--upgrade","pip","setuptools","wheel"],opts:{cwd:l}}),await fe({cmd:O.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","-r","requirements.txt"],opts:{cwd:l}}),y=!0;break}default:}});let v={success:!0},S=await pc(pt(c,".git")).catch(()=>null);if(!s&&!S)try{await fe({cmd:"git",args:["init"],opts:{cwd:l}})}catch(C){v={success:!1,error:C}}let E=y?null:await kn(l);$({message:""}),R({message:mc({actorName:e,dependenciesInstalled:y,postCreate:d?.postCreate??null,gitRepositoryInitialized:!s&&!S&&v.success,installCommandSuggestion:E})}),!s&&!S&&!v.success&&(x({message:`Failed to initialize git repository: ${v.error.message}`}),x({message:'You can manually run "git init" in the Actor directory if needed.'}))}};import hc from"chalk";async function gc(r,e,t){let o=await r[t](e).get().catch(()=>{});if(o)return{[t]:o,[`${t}Client`]:r[t](o.id)};let s=await M(),i=await r[t](`${s.username}/${e}`).get().catch(()=>{});return i?{[t]:i,[`${t}Client`]:r[t](i.id)}:null}m(gc,"tryToGetStorage");async function Ue(r,e){return gc(r,e,"dataset")}m(Ue,"tryToGetDataset");async function ae(r,e){return gc(r,e,"keyValueStore")}m(ae,"tryToGetKeyValueStore");var Go=class extends h{static name="create";static description="Creates a new dataset for storing structured data on your account.";static examples=[{description:"Create an unnamed dataset.",command:"apify datasets create"},{description:"Create a named dataset.",command:"apify datasets create my-dataset"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-create";static args={datasetName:A.string({description:"Optional name for the Dataset.",required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,t=await I();if(e&&await Ue(t,e)){g({message:"A Dataset with this name already exists!"});return}let o=await t.datasets().getOrCreate(e);if(this.flags.json){L(o);return}R({message:`Dataset with ID ${hc.yellow(o.id)}${e?` (called ${hc.yellow(e)})`:""} was created.`,stdout:!0})}};import{DownloadItemsFormat as Ze}from"apify-client";var yc={[Ze.JSON]:"application/json",[Ze.JSONL]:"application/jsonl",[Ze.CSV]:"text/csv",[Ze.HTML]:"text/html",[Ze.RSS]:"application/rss+xml",[Ze.XML]:"application/xml",[Ze.XLSX]:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},Yo=class extends h{static name="get-items";static description="Retrieves dataset items in specified format (JSON, CSV, etc).";static examples=[{description:"Print all items from a dataset as JSON.",command:"apify datasets get-items <datasetId>"},{description:"Export the first 100 items as CSV to a file.",command:"apify datasets get-items <datasetId> --format csv --limit 100 > items.csv"},{description:"Paginate: skip the first 500 items, return the next 500.",command:"apify datasets get-items <datasetId> --offset 500 --limit 500"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-get-items";static flags={limit:w.integer({description:"The amount of elements to get from the dataset. By default, it will return all available items."}),offset:w.integer({description:"The offset in the dataset where to start getting items."}),format:w.string({description:"The format of the returned output. By default, it is set to 'json'.",choices:Object.keys(yc),default:Ze.JSON})};static args={datasetId:A.string({description:"The ID of the Dataset to export the items for.",required:!0})};async run(){let{limit:e,offset:t,format:o}=this.flags,{datasetId:s}=this.args,i=await I(),n=await this.tryToGetDataset(i,s);if(!n){g({message:`Dataset with ID "${s}" not found.`});return}let{datasetClient:a}=n;process.stdout.write("");let c=await a.downloadItems(o,{limit:e,offset:t}),l=yc[o]??"application/octet-stream";$({message:l}),process.stdout.write(c),process.stdout.write(`
199
+ `)}async tryToGetDataset(e,t){let o=await e.dataset(t).get().catch(()=>{});if(o)return{dataset:o,datasetClient:e.dataset(o.id)};let s=await M(),i=await e.dataset(`${s.username}/${t}`).get().catch(()=>{});return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};import G from"chalk";function Ho(r){let e=Reflect.get(r,"planPricing");return e?Reflect.get(e,"chargeableServiceUnitPricesUsd"):null}m(Ho,"getUserPlanPricing");var wc=new B({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),Jo=class extends h{static name="info";static description="Prints information about a specific dataset.";static examples=[{description:"Show dataset metadata (item count, size, timestamps).",command:"apify datasets info <datasetId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-info";static args={storeId:A.string({description:"The dataset store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,t=await I(),o=await Ue(t,e);if(!o){g({message:`Key-value store with ID or name "${e}" not found.`});return}let{dataset:s}=o,[i,n,a]=await Promise.all([t.user(s.userId).get().then(F=>F),s.actId?t.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?t.run(s.actRunId).get():Promise.resolve(void 0)]),c;if(a?.actorTaskId&&(c=await t.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){L({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let l=s.stats?.storageBytes||0,d=s.stats?.readCount||0,u=s.stats?.writeCount||0,p=(s.cleanItemCount||0).toLocaleString("en-US"),f=(s.itemCount||0).toLocaleString("en-US"),y=[`${G.bold(d.toLocaleString("en-US"))} ${G.gray(this.pluralString(d,"read","reads"))}`,`${G.bold(u.toLocaleString("en-US"))} ${G.gray(this.pluralString(u,"write","writes"))}`],v=`Items: ${G.bold(p)} ${G.gray("clean")} / ${G.bold(f)} ${G.gray("total")}
200
+ Operations: ${y.join(" / ")}`;if(i.plan){let F=Ho(i.plan);if(F){let re=F.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(l/1e9),Se=re*24*30,Te=Se>1?`$${Se.toFixed(2)}`:`$${re.toFixed(3)}`;v+=`
201
+ Storage size: ${ee({bytes:l,shortBytes:!0,precision:1})} / ${G.gray(`${Te} per month`)}`}}else v+=`
202
+ Storage size: ${ee({bytes:l,shortBytes:!0,precision:1})}`;let S=[`Dataset ID: ${G.bgGray(s.id)}`,`Name: ${s.name?G.bgGray(s.name):G.bold(G.italic("Unnamed"))}`,`Created: ${G.bold(Y.display(s.createdAt))}`,`Modified: ${G.bold(Y.display(s.modifiedAt))}`].join(`
203
+ `),E=G.bold("\u2014");s.actRunId&&(a?E=G.bgBlue(a.id):E=G.italic(G.gray("Run removed")));let C=G.bold("\u2014");n&&(C=G.blue(n.title||n.name));let P=G.bold("\u2014");c&&(P=G.blue(c.title||c.name));let N=[`Run: ${E}`,`Actor: ${C}`,`Task: ${P}`].join(`
204
+ `);wc.pushRow({Row1:S,Row2:N});let U=wc.render(2).split(`
205
+ `).map(F=>F.trim());U.shift();let J=[`${G.bold(s.name||G.italic("Unnamed"))}`,`${G.gray(s.name?`${i.username}/${s.name}`:s.id)} ${G.gray("Owned by")} ${G.blue(i.username)}`,"",U.join(`
206
+ `),"",v].join(`
207
+ `);$({message:J,stdout:!0})}};import Ac from"chalk";var vc=new B({allColumns:["Dataset ID","Name","Items","Size","Created","Modified"],mandatoryColumns:["Dataset ID","Name","Items","Size"],columnAlignments:{Items:"right"}}),qo=class extends h{static name="ls";static description="Prints all datasets on your account.";static examples=[{description:"List your datasets (most recently modified first).",command:"apify datasets ls --desc"},{description:"List only unnamed (auto-generated) datasets.",command:"apify datasets ls --unnamed"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-ls";static flags={offset:w.integer({description:"Number of datasets that will be skipped.",default:0}),limit:w.integer({description:"Number of datasets that will be listed.",default:20}),desc:w.boolean({description:"Sorts datasets in descending order.",default:!1}),unnamed:w.boolean({description:"Lists datasets that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:t,limit:o,json:s,unnamed:i}=this.flags,n=await I(),a=await M(),c=await n.datasets().list({desc:e,offset:t,limit:o,unnamed:i});if(s){L(c);return}if(c.count===0){b({message:"You don't have any Datasets on your account",stdout:!0});return}for(let l of c.items){let d=Reflect.get(l.stats,"s3StorageBytes");vc.pushRow({"Dataset ID":l.id,Created:Y.display(l.createdAt),Items:`${l.itemCount}`,Modified:Y.display(l.modifiedAt),Name:l.name?`${a.username}/${l.name}`:"",Size:typeof d=="number"?ee({bytes:d,shortBytes:!0,colorFunc:Ac.gray,precision:0}):Ac.gray("N/A")})}$({message:vc.render(1),stdout:!0})}};import Ko from"chalk";var Wo=class extends h{static name="push-items";static description="Adds data items to specified dataset. Accepts single object or array of objects.";static examples=[{description:"Push a single item as an inline JSON argument.",command:`apify datasets push-items my-dataset '{"url":"https://example.com"}'`},{description:"Push an array of items from stdin.",command:"cat ./items.json | apify datasets push-items my-dataset"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-push-items";static args={nameOrId:A.string({required:!0,description:"The dataset ID or name to push the objects to.",ignoreStdin:!0}),item:A.string({description:"The object or array of objects to be pushed."})};async run(){let{nameOrId:e,item:t}=this.args,o=await I(),s=await Ue(o,e);if(!s){g({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:n}=s,a,c=t||Re;if(!c){g({message:"No items were provided."});return}try{a=JSON.parse(c.toString("utf8"))}catch(d){g({message:`Failed to parse data as JSON string: ${d.message}`});return}if(Array.isArray(a)&&a.length===0){g({message:"No items were provided."});return}let l=n.name?`Dataset named ${Ko.yellow(n.name)} (${Ko.gray("ID:")} ${Ko.yellow(n.id)})`:`Dataset with ID ${Ko.yellow(n.id)}`;try{await i.pushItems(a),R({message:`${this.pluralString(Array.isArray(a)?a.length:1,"Object","Objects")} pushed to ${l} successfully.`})}catch(d){let u=d;g({message:`Failed to push items into ${l}
208
+ ${u.message||u}`})}}};import Qe from"chalk";var zo=class extends h{static name="rename";static description="Change the dataset name or remove the name with --unname flag.";static examples=[{description:"Rename a dataset.",command:"apify datasets rename old-name new-name"},{description:"Remove the name from a dataset (makes it unnamed).",command:"apify datasets rename my-dataset --unname"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-rename";static flags={unname:w.boolean({description:"Removes the unique name of the dataset."})};static args={nameOrId:A.string({description:"The dataset ID or name to delete.",required:!0}),newName:A.string({description:"The new name for the dataset."})};async run(){let{unname:e}=this.flags,{newName:t,nameOrId:o}=this.args;if(!t&&!e){g({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){g({message:"You cannot provide a new name and the --unname flag."});return}let s=await I(),i=await Ue(s,o);if(!i){g({message:`Dataset with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.dataset,c=a?e?`The name of the dataset with ID ${Qe.yellow(n)} has been removed (was ${Qe.yellow(a)} previously).`:`The name of the dataset with ID ${Qe.yellow(n)} was changed from ${Qe.yellow(a)} to ${Qe.yellow(t)}.`:`The name of the dataset with ID ${Qe.yellow(n)} has been set to: ${Qe.yellow(t)}`;try{await i.datasetClient.update({name:e?null:t}),R({message:c,stdout:!0})}catch(l){let d=l;g({message:`Failed to rename dataset with ID ${Qe.yellow(n)}
209
+ ${d.message||d}`})}}};import Di from"chalk";var Xo=class extends h{static name="rm";static description="Permanently removes a dataset.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.";static examples=[{description:"Delete a dataset by name or ID (prompts for confirmation).",command:"apify datasets rm my-dataset"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-rm";static args={datasetNameOrId:A.string({description:"The dataset ID or name to delete.",required:!0})};static flags={...ie};async run(){let{datasetNameOrId:e}=this.args,{yes:t}=this.flags,o=await I(),s=await Ue(o,e);if(!s){g({message:`Dataset with ID or name "${e}" not found.`});return}if(!await Z({message:"Are you sure you want to delete this Dataset?",providedConfirmFromStdin:t||void 0})){b({message:"Dataset deletion has been aborted."});return}let{id:n,name:a}=s.dataset;try{await s.datasetClient.delete(),R({message:`Dataset with ID ${Di.yellow(n)}${a?` (called ${Di.yellow(a)})`:""} has been deleted.`,stdout:!0})}catch(c){let l=c;g({message:`Failed to delete dataset with ID ${Di.yellow(n)}
210
+ ${l.message||l}`})}}};var Zo=class extends h{static name="datasets";static description="Manage Apify datasets \u2014 create, list, rename, delete, push items, and download items in various formats.";static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets";static subcommands=[Go,Yo,qo,Jo,Xo,zo,Wo];async run(){this.printHelp()}};import{existsSync as Fi,mkdirSync as up,readFileSync as pp,writeFileSync as fp}from"fs";import{dirname as gp}from"path";import hp from"cors";import yp from"detect-indent";import Ui from"express";import wp from"open";import{cryptoRandomObjectId as Ap}from"@apify/utilities";var Sc="https://apify.github.io/input-schema-editor-react/",vp=new URL(Sc).origin,bc="v1",Qo=class extends h{static name="edit-input-schema";static description="Lets you edit your input schema that would be used on the platform in a visual input schema editor.";static group="Local Actor Development";static interactive=!0;static interactiveNote="Opens a browser-based schema editor. Requires a local display; cannot be run headlessly.";static examples=[{description:"Edit the input schema of the Actor in the current directory.",command:"apify edit-input-schema"},{description:"Edit a specific INPUT_SCHEMA.json file.",command:"apify edit-input-schema ./.actor/INPUT_SCHEMA.json"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-edit-input-schema";static args={path:A.string({required:!1,description:"Optional path to your INPUT_SCHEMA.json file. If not provided default platform location for input schema is used."})};static hidden=!0;static aliases=["eis"];async run(){let{inputSchema:e,inputSchemaPath:t}=await Tt({forcePath:this.args.path,cwd:process.cwd()});if(e&&!t)throw new Error(`Editing an input schema directly embedded in '${D}' is not yet supported.`);x({message:`This command is still experimental and might break at any time. Use at your own risk.
211
+ `}),b({message:`Editing input schema at "${t}"...`});let o,s=Ui();s.use(hp({origin:vp,allowedHeaders:["Content-Type","Authorization"]})),s.use((u,p,f)=>{p.set("Connection","close"),f()}),s.use(Ui.json());let i=Ap();s.use((u,p,f)=>{let{token:y}=u.query;if(!y){let v=u.get("Authorization");if(v){let[S,E,...C]=v.trim().split(/\s+/);S.toLowerCase()==="bearer"&&E&&C.length===0&&(y=E)}}y!==i?(p.status(401),p.send("Authorization failed")):f()});let n=Ui.Router();s.use(`/api/${bc}`,n);let a=" ",c=!0;n.get("/input-schema",(u,p)=>{let f;try{f=Fi(t)?pp(t,{encoding:"utf-8"}):`{}
212
+ `,f.length>3&&(a=yp(f).indent||a),f&&(c=f[f.length-1]===`
213
+ `),Fi(t)?b({message:`Input schema loaded from "${t}"`}):b({message:"Empty input schema initialized."})}catch(v){let S=`Reading input schema from disk failed with: ${v.message}`;g({message:S}),p.status(500),p.send(S);return}let y;try{y=JSON.parse(f||"{}")}catch(v){let S=`Parsing input schema failed with error: ${v.message}`;g({message:S}),p.status(500),p.send(S);return}p.send(y),b({message:"Input schema sent to editor."})}),n.post("/input-schema",(u,p)=>{try{b({message:"Got input schema from editor..."});let f=u.body,y=JSON.stringify(f,null,a);c&&(y+=`
214
+ `);let v=gp(t);Fi(v)||up(v,{recursive:!0}),fp(t,y,{encoding:"utf-8",flag:"w+"}),p.end(),b({message:"Input schema saved to disk."})}catch(f){let y=`Saving input schema failed with error: ${f.message}`;g({message:y}),p.status(500),p.send(y)}}),n.post("/exit",(u,p)=>{u.body.isWindowClosed?b({message:"Editor closed, finishing..."}):b({message:"Editing finished, you can close the editor."}),p.end(),o.close(()=>R({message:"Done."}))}),o=s.listen(0);let{port:l}=o.address();b({message:`Listening for messages from input schema editor on port ${l}...`});let d=`${Sc}?localCliPort=${l}&localCliToken=${i}&localCliApiVersion=${bc}`;b({message:`Opening input schema editor at "${d}"...`}),await wp(d)}};import es from"chalk";var wr=class extends h{static name="help";static description="Prints out help about a command, or all available commands.";static hidden=!0;static args={commandString:A.string({required:!1,description:"The command to get help for.",catchAll:!0})};async run(){let{commandString:e}=this.args;if(!e||e.toLowerCase().startsWith("help")){let i=so(this.entrypoint);console.log(i);return}let t=e.toLowerCase(),o=W.get(t);if(!o){let i=ao(t),n=es.gray(`Command ${es.whiteBright(e)} not found`);i.length&&(n+=`
215
+ `,n+=es.gray(`Did you mean: ${i.map(a=>es.whiteBright(a)).join(", ")}?`)),g({message:n});return}let s=ro(o);console.log(s)}};import Tc from"chalk";var ts=class extends h{static name="info";static description="Prints details about your currently authenticated Apify account.";static group="Apify Console";static examples=[{description:"Print the currently logged-in account username and user ID.",command:"apify info"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-info";async run(){await I();let e=await M();if(e){let t={username:e.username,userId:e.id};for(let o of Object.keys(t))console.log(`${Tc.gray(o)}: ${Tc.bold(t[o])}`)}}};import{basename as Lp}from"path";import Vi from"process";import{appendFileSync as bp,copyFileSync as Sp,createWriteStream as Tp,existsSync as Mi,mkdirSync as Cp,readFileSync as Cc,rmSync as Ip,writeFileSync as Ep}from"fs";import{basename as $p,join as ji,relative as Ic,sep as Bi}from"path";import{fileURLToPath as Rp}from"url";import xp from"@root/walk";import _p from"configparser";import Pp from"handlebars";import{fetchManifest as kp,wrapperManifestUrl as Op}from"@apify/actor-templates";var Np=[".dockerignore",".gitignore"],rs=Rp(new URL("./templates/python-scrapy",import.meta.url));async function Ec(r,e,t={bindings:{}}){await xp.walk(r,async(o,s,i)=>{if(s===r)return;let n=Ic(r,s),a=n.split(Bi).map(l=>{if(l.startsWith("{")&&l.endsWith("}")){l=l.replace("{","").replace("}","");let d=t.bindings[l];if(!d)throw new Error(`Binding for ${l} not found.`);return d}return l}).join(Bi),c=ji(e,a);if(i.isDirectory())return Mi(c)||Cp(c),Ec(s,c);n.includes(".template")?Ep(ji(e,a.replace(".template","")),Pp.compile(Cc(s,"utf8"))(t.bindings)):Mi(c)&&Np.includes($p(a))?bp(c,Cc(s)):Sp(s,c)})}m(Ec,"merge");async function os({projectPath:r}){r||(r=".");let e=new ct(r);if(e.configuration.hasSection("apify"))throw new Error("The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?");await e.init();let t=await ze({message:"Pick the Scrapy spider you want to wrap:",choices:e.getAvailableSpiders().map((l,d)=>({name:`${l.class_name} (${l.pathname})`,value:d}))});function o(l){return`.${Ic(r,l).split(Bi).slice(1).join(".").replace(".py","")}`}m(o,"translatePathToRelativeModuleName");let s={botName:Fr(e.settings.BOT_NAME),scrapy_settings_module:e.configuration.get("settings","default"),apify_module_path:`${e.settings.BOT_NAME}.apify`,spider_class_name:e.getAvailableSpiders()[t].class_name,spider_module_name:`${o(e.getAvailableSpiders()[t].pathname)}`,projectFolder:e.settings.BOT_NAME},i=await kp(Op);b({message:"Downloading the latest Scrapy wrapper template..."});let{archiveUrl:n}=i.templates.find(({id:l})=>l==="python-scrapy");Mi(rs)&&Ip(rs,{recursive:!0}),await jr({url:n,pathTo:rs}),b({message:"Wrapping the Scrapy project..."}),await Ec(rs,r,{bindings:s});let a=new _p;a.addSection("apify"),a.set("apify","mainpy_location",e.settings.BOT_NAME);let c=Tp(ji(r,"scrapy.cfg"),{flags:"a"});await new Promise(l=>{c.on("open",d=>{c.write(`
216
+ `,()=>{a.write(d),l()})})}),R({message:"The Scrapy project has been wrapped successfully."})}m(os,"wrapScrapyProject");var ss=class extends h{static name="init";static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
217
+ If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
218
+ Creates the '${D}' file and the '${ot}' directory in the current directory, but does not touch any other existing files or directories.
219
+
220
+ WARNING: Overwrites existing '${ot}' directory.`;static group="Local Actor Development";static interactive=!0;static interactiveNote="Prompts for an Actor name if not provided. To run non-interactively, pass the Actor name as a positional argument, or pass --yes to accept the default (current directory name).";static examples=[{description:"Initialize an Actor in the current directory, prompting for a name.",command:"apify init"},{description:"Initialize non-interactively with an explicit Actor name.",command:"apify init my-actor"},{description:"Initialize non-interactively, accepting the default Actor name.",command:"apify init --yes"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-init";static args={actorName:A.string({required:!1,description:"Name of the Actor. If not provided, you will be prompted for it."})};static flags={...ie,dockerfile:w.string({description:'Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").',required:!1})};async run(){let{actorName:e}=this.args,t=Vi.cwd(),o=await Ne();o.isErr()&&(g({message:o.unwrapErr().message}),Vi.exit(1));let s=o.unwrap();if(s.warnings?.length)for(let a of s.warnings)x({message:a});let i=Lp(t);if(s.type===1&&s.entrypoint?.path){let a=s.entrypoint.path,c=a.includes(".")?a.split(".").pop():a;i=Fr(c)}if(s.type===2)return b({message:"The current directory looks like a Scrapy project. Using automatic project wrapping."}),this.telemetryData.actorWrapper="scrapy",os({projectPath:t});if(!this.flags.yes&&s.type===3&&(x({message:"The current directory does not look like a Node.js or Python project."}),!await Z({message:"Do you want to continue?",providedConfirmFromStdin:this.flags.yes})))return;let n=await Le({cwd:t});if(n.isOkAnd(a=>a.exists&&!a.migrated))x({message:`Skipping creation of '${D}', the file already exists in the current directory.`});else{if(n.isErr()){g({message:n.unwrapErr().message}),Vi.exitCode=5;return}if(!e){let l=n.isOkAnd(d=>d.exists)?n.unwrap().config.name:null;for(;!l;)try{let d=await at({message:"Actor name:",default:i});Qt(d),l=d}catch(d){g({message:d.message})}e=l}let c={...{...Cr,...n.unwrap().config},name:e};this.flags.dockerfile&&(c.dockerfile=this.flags.dockerfile),await Lr(c,t)}await Dr(t),await fo(t),R({message:"The Actor has been initialized in the current directory."})}};var is=class extends h{static name="init-wrap-scrapy";static description=`Wraps your existing Scrapy project to work like an Apify Actor.
221
+
222
+ It adds the following features:
223
+ - Automatic retry of failed requests
224
+ - Automatic proxy rotation
225
+ - Automatic user agent rotation
226
+ ...
227
+ `;static args={path:A.string({required:!1,description:"Optional path to your scrapy project. If not provided, the current directory is used."})};static hidden=!0;async run(){await os({projectPath:this.args.path}),b({message:"Scrapy project wrapped successfully."})}};import $c from"chalk";var ns=class extends h{static name="create";static description="Creates a new key-value store on your account.";static examples=[{description:"Create an unnamed key-value store.",command:"apify key-value-stores create"},{description:"Create a named key-value store.",command:"apify key-value-stores create my-store"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-create";static args={"key-value store name":A.string({description:"Optional name for the key-value store.",required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,t=await I();if(e&&await ae(t,e)){g({message:"Cannot create a key-value store with the same name!"});return}let o=await t.keyValueStores().getOrCreate(e);if(this.flags.json){L(o);return}R({message:`Key-value store with ID ${$c.yellow(o.id)}${e?` (called ${$c.yellow(e)})`:""} was created.`,stdout:!0})}};import Dp from"chalk";var as=class extends h{static name="delete-value";static description="Delete a value from a key-value store.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting the record. Cannot be bypassed; deletion is irreversible.";static examples=[{description:"Delete a single record by key.",command:"apify key-value-stores delete-value <storeId> OUTPUT"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-delete-value";static args={"store id":A.string({description:"The key-value store ID to delete the value from.",required:!0}),itemKey:A.string({description:"The key of the item in the key-value store.",required:!0})};static flags={...ie};async run(){let{storeId:e,itemKey:t}=this.args,{yes:o}=this.flags,s=await I(),i=await ae(s,e);if(!i){g({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:n}=i;if(!await n.getRecord(t)){g({message:`Item with key "${t}" not found in the key-value store.`});return}if(!await Z({message:"Are you sure you want to delete this record?",providedConfirmFromStdin:o||void 0})){b({message:"Key-value store record deletion aborted.",stdout:!0});return}try{await n.deleteRecord(t),b({message:`Record with key "${Dp.yellow(t)}" deleted from the key-value store.`,stdout:!0})}catch(l){let d=l;g({message:`Failed to delete record with key "${t}" from the key-value store.
228
+ ${d.message||d}`})}}};var cs=class extends h{static name="get-value";static description="Retrieves stored value for specified key. Use --only-content-type to check MIME type.";static examples=[{description:"Read a record value and print it to stdout.",command:"apify key-value-stores get-value <storeId> INPUT"},{description:"Print only the record content-type.",command:"apify key-value-stores get-value <storeId> INPUT --only-content-type"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-get-value";static flags={"only-content-type":w.boolean({description:"Only return the content type of the specified key.",default:!1})};static args={keyValueStoreId:A.string({description:"The key-value store ID to get the value from.",required:!0}),itemKey:A.string({description:"The key of the item in the key-value store.",required:!0})};async run(){let{onlyContentType:e}=this.flags,{keyValueStoreId:t,itemKey:o}=this.args,s=await I(),i=await ae(s,t);if(!i){g({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.getRecord(o,{stream:!0});if(!a){g({message:`Item with key "${o}" not found in the key-value store.`});return}if($({message:a.contentType??"application/octet-stream"}),e){a.value.destroy();return}if(a.contentType?.includes("application/json")){let{value:c}=a,l=[];for await(let u of c)l.push(u);let d=Buffer.concat(l).toString();try{let u=JSON.parse(d);$({message:JSON.stringify(u,null,2),stdout:!0})}catch{$({message:d,stdout:!0})}return}a.value.pipe(process.stdout)}};import V from"chalk";var Rc=new B({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),ls=class extends h{static name="info";static description="Shows information about a key-value store.";static examples=[{description:"Show metadata about a key-value store.",command:"apify key-value-stores info <storeId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-info";static args={storeId:A.string({description:"The key-value store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,t=await I(),o=await ae(t,e);if(!o){g({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStore:s}=o,[i,n,a]=await Promise.all([t.user(s.userId).get().then(F=>F),s.actId?t.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?t.run(s.actRunId).get():Promise.resolve(void 0)]),c;if(a?.actorTaskId&&(c=await t.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){L({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let l=s.stats?.storageBytes||0,d=s.stats?.readCount||0,u=s.stats?.writeCount||0,p=s.stats?.deleteCount||0,f=s.stats?.listCount||0,v=`Operations: ${[`${V.bold(d.toLocaleString("en-US"))} ${V.gray(this.pluralString(d,"read","reads"))}`,`${V.bold(u.toLocaleString("en-US"))} ${V.gray(this.pluralString(u,"write","writes"))}`,`${V.bold(p.toLocaleString("en-US"))} ${V.gray(this.pluralString(p,"delete","deletes"))}`,`${V.bold(f.toLocaleString("en-US"))} ${V.gray(this.pluralString(f,"list","lists"))}`].join(" / ")}`;if(i.plan){let F=Ho(i.plan);if(F){let re=F.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(l/1e9),Se=re*24*30,Te=Se>1?`$${Se.toFixed(2)}`:`$${re.toFixed(3)}`;v+=`
229
+ Storage size: ${ee({bytes:l,shortBytes:!0,precision:1})} / ${V.gray(`${Te} per month`)}`}}else v+=`
230
+ Storage size: ${ee({bytes:l,shortBytes:!0,precision:1})} / ${V.gray("$unknown per month")}`;let S=[`Store ID: ${V.bgGray(s.id)}`,`Name: ${s.name?V.bgGray(s.name):V.bold(V.italic("Unnamed"))}`,`Created: ${V.bold(Y.display(s.createdAt))}`,`Modified: ${V.bold(Y.display(s.modifiedAt))}`].join(`
231
+ `),E=V.bold("\u2014");s.actRunId&&(a?E=V.bgBlue(a.id):E=V.italic(V.gray("Run removed")));let C=V.bold("\u2014");n&&(C=V.blue(n.title||n.name));let P=V.bold("\u2014");c&&(P=V.blue(c.title||c.name));let N=[`Run: ${E}`,`Actor: ${C}`,`Task: ${P}`].join(`
232
+ `);Rc.pushRow({Row1:S,Row2:N});let U=Rc.render(2).split(`
233
+ `).map(F=>F.trim());U.shift();let J=[`${V.bold(s.name||V.italic("Unnamed"))}`,`${V.gray(s.name?`${i.username}/${s.name}`:s.id)} ${V.gray("Owned by")} ${V.blue(i.username)}`,"",U.join(`
234
+ `),"",v].join(`
235
+ `);$({message:J,stdout:!0})}};var xc=new B({allColumns:["Key","Size"],mandatoryColumns:["Key","Size"]}),ds=class extends h{static name="keys";static description="Lists all keys in a key-value store.";static examples=[{description:"List the first 20 keys in a key-value store.",command:"apify key-value-stores keys <storeId>"},{description:"Paginate keys past an exclusive start key.",command:"apify key-value-stores keys <storeId> --exclusive-start-key last-seen-key --limit 100"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-keys";static flags={limit:w.integer({description:"The maximum number of keys to return.",default:20}),"exclusive-start-key":w.string({description:"The key to start the list from."})};static args={storeId:A.string({description:"The key-value store ID to list keys for.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,{limit:t,exclusiveStartKey:o}=this.flags,s=await I(),i=await ae(s,e);if(!i){g({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.listKeys({limit:t,exclusiveStartKey:o});if(this.flags.json){L(a);return}for(let c of a.items)xc.pushRow({Key:c.key,Size:ee({bytes:c.size,shortBytes:!0,precision:0})});$({message:xc.render(1),stdout:!0})}};import _c from"chalk";var Pc=new B({allColumns:["Store ID","Name","Size","Created","Modified"],mandatoryColumns:["Store ID","Name","Size"]}),ms=class extends h{static name="ls";static description="Lists all key-value stores on your account.";static examples=[{description:"List your key-value stores.",command:"apify key-value-stores ls"},{description:"List the next page of stores, sorted descending.",command:"apify key-value-stores ls --limit 50 --offset 50 --desc"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-ls";static flags={offset:w.integer({description:"Number of key-value stores that will be skipped.",default:0}),limit:w.integer({description:"Number of key-value stores that will be listed.",default:20}),desc:w.boolean({description:"Sorts key-value stores in descending order.",default:!1}),unnamed:w.boolean({description:"Lists key-value stores that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:t,limit:o,json:s,unnamed:i}=this.flags,n=await I(),a=await M(),c=await n.keyValueStores().list({desc:e,offset:t,limit:o,unnamed:i});if(s){L(c);return}if(c.count===0){b({message:"You don't have any key-value stores on your account",stdout:!0});return}for(let l of c.items){let u=Reflect.get(l,"stats").s3StorageBytes;Pc.pushRow({"Store ID":l.id,Created:Y.display(l.createdAt),Modified:Y.display(l.modifiedAt),Name:l.name?`${a.username}/${l.name}`:"",Size:typeof u=="number"?ee({bytes:u,shortBytes:!0,colorFunc:_c.gray,precision:0}):_c.gray("N/A")})}$({message:Pc.render(1),stdout:!0})}};import et from"chalk";var us=class extends h{static name="rename";static description="Renames a key-value store, or removes its unique name.";static examples=[{description:"Rename a key-value store.",command:"apify key-value-stores rename old-name new-name"},{description:"Remove the name from a key-value store.",command:"apify key-value-stores rename my-store --unname"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rename";static flags={unname:w.boolean({description:"Removes the unique name of the key-value store."})};static args={keyValueStoreNameOrId:A.string({description:"The key-value store ID or name to delete.",required:!0}),newName:A.string({description:"The new name for the key-value store."})};async run(){let{unname:e}=this.flags,{newName:t,keyValueStoreNameOrId:o}=this.args;if(!t&&!e){g({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){g({message:"You cannot provide a new name and the --unname flag."});return}let s=await I(),i=await ae(s,o);if(!i){g({message:`Key-value store with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.keyValueStore,c=a?e?`The name of the key-value store with ID ${et.yellow(n)} has been removed (was ${et.yellow(a)} previously).`:`The name of the key-value store with ID ${et.yellow(n)} was changed from ${et.yellow(a)} to ${et.yellow(t)}.`:`The name of the key-value store with ID ${et.yellow(n)} has been set to: ${et.yellow(t)}`;try{await i.keyValueStoreClient.update({name:e?null:t}),R({message:c,stdout:!0})}catch(l){let d=l;g({message:`Failed to rename key-value store with ID ${et.yellow(n)}
236
+ ${d.message||d}`})}}};import Gi from"chalk";var ps=class extends h{static name="rm";static description="Permanently removes a key-value store.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.";static examples=[{description:"Delete a key-value store (prompts for confirmation).",command:"apify key-value-stores rm my-store"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rm";static args={keyValueStoreNameOrId:A.string({description:"The key-value store ID or name to delete.",required:!0})};static flags={...ie};async run(){let{keyValueStoreNameOrId:e}=this.args,{yes:t}=this.flags,o=await I(),s=await ae(o,e);if(!s){g({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await Z({message:"Are you sure you want to delete this Key-value store?",providedConfirmFromStdin:t||void 0})){b({message:"Key-value store deletion has been aborted."});return}let{id:n,name:a}=s.keyValueStore;try{await s.keyValueStoreClient.delete(),R({message:`Key-value store with ID ${Gi.yellow(n)}${a?` (called ${Gi.yellow(a)})`:""} has been deleted.`,stdout:!0})}catch(c){let l=c;g({message:`Failed to delete key-value store with ID ${Gi.yellow(n)}
237
+ ${l.message||l}`})}}};var fs=class extends h{static name="set-value";static description="Stores value with specified key. Set content-type with --content-type flag.";static examples=[{description:"Store a JSON value under a key.",command:`apify key-value-stores set-value <storeId> OUTPUT '{"status":"done"}'`},{description:"Store a plain-text file read from stdin.",command:"cat ./report.txt | apify key-value-stores set-value <storeId> REPORT --content-type text/plain"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-set-value";static flags={"content-type":w.string({description:'The MIME content type of the value. By default, "application/json" is assumed.',default:"application/json"})};static args={storeId:A.string({description:"The key-value store ID to set the value in.",required:!0}),itemKey:A.string({description:"The key of the item in the key-value store.",required:!0}),value:A.string({description:"The value to set."})};async run(){let{storeId:e,itemKey:t,value:o}=this.args,{contentType:s}=this.flags,i=await I(),n=await ae(i,e);if(!n){g({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=n;try{await a.setRecord({key:t,value:o||process.stdin,contentType:s}),R({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(c){let l=c;g({message:`Failed to set value with key "${t}" in the key-value store.
238
+ ${l.message||l}`})}}};var gs=class extends h{static name="key-value-stores";static description=`Manage Apify key-value stores \u2014 create, list, rename, delete stores, and get/set/delete individual records.
239
+
240
+ Alias: kvs.`;static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores";static hiddenAliases=["kvs"];static subcommands=[ns,as,cs,ls,ds,ms,us,ps,fs];async run(){this.printHelp()}};var hs=class extends jt{static name="login"};var ys=class extends Bt{static name="logout"};var ws=class extends Ft{static name="pull"};var As=class extends Mt{static name="push"};var vs=class extends h{static name="request-queues";static description="Manage Apify request queues. No subcommands are available yet.";static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-request-queues";async run(){this.printHelp()}};import{existsSync as Oc,renameSync as Bp}from"fs";import{mkdir as bs,readFile as Vp,stat as Nc,writeFile as vr}from"fs/promises";import{dirname as Ss,join as Ts}from"path";import Ve from"process";import Gp from"mime";import{minVersion as Yp}from"semver";import{APIFY_ENV_VARS as Cs}from"@apify/consts";import{validateInputSchema as Hp,validateInputUsingValidator as Lc}from"@apify/input_schema";import{none as Ar,some as Fp}from"@sapphire/result";import{execa as Up}from"execa";var Yi=m(r=>`
241
+ (async () => {
242
+ const [nodeModule, process, path, fs] = await Promise.all([
243
+ import('node:module'),
244
+ import('node:process'),
245
+ import('node:path'),
246
+ import('node:fs/promises'),
247
+ ]);
248
+
249
+ /* we fake a script file here because otherwise node AND deno will fail to resolve modules, but bun works -.- */
250
+ const dirname = path.join(process.cwd(), '__apify_cli_fetch_module_version__.js');
251
+
252
+ const _require = nodeModule.createRequire(dirname);
253
+
254
+ try {
255
+ const modulePath = _require.resolve('${r}');
256
+ const moduleDir = path.dirname(modulePath);
257
+
258
+ const packageJson = await fs.readFile(path.join(moduleDir, 'package.json'), 'utf8').catch(() => null);
259
+
260
+ if (!packageJson) {
261
+ console.log('n/a');
262
+ return;
263
+ }
264
+
265
+ const packageJsonObj = JSON.parse(packageJson);
266
+ console.log(packageJsonObj.version);
267
+ } catch {
268
+ console.log('n/a');
269
+ }
270
+ })();
271
+ `.replaceAll(`
272
+ `," ").replaceAll(" "," "),"jsScript"),Mp=m(r=>`
273
+ try:
274
+ import ${r}
275
+ print(${r}.__version__)
276
+ except:
277
+ print('n/a')
278
+ `,"pyScript"),jp={node(r){return["-e",`"${Yi(r)}"`]},deno(r){return["eval",`"${Yi(r)}"`]},bun(r){return["--eval",`"${Yi(r)}"`]},python(r){return["-c",`"${Mp(r)}"`]}};async function kc({moduleName:r,project:e}){if(!e.runtime)return T("useModuleVersion",{status:"no_runtime_found",project:e,moduleName:r}),Ar;let t;if(e.type===0)t=e.runtime.runtimeShorthand||"node";else if(e.type===1||e.type===2)t="python";else return T("useModuleVersion",{status:"unsupported_project_type",project:e,moduleName:r}),Ar;let o=jp[t]?.(r);if(!o)return T("useModuleVersion",{status:"no_version_script_found",project:e,moduleName:r}),Ar;try{let s=await Up(e.runtime.executablePath,o,{shell:!0,windowsHide:!0,verbose:process.env.APIFY_CLI_DEBUG?"full":void 0});return s.stdout.trim()==="n/a"?(T("useModuleVersion",{status:"no_version_found",project:e,moduleName:r}),Ar):(T("useModuleVersion",{status:"success",project:e,moduleName:r,version:s.stdout.trim()}),Fp(s.stdout.trim()))}catch(s){return T("useModuleVersion",{status:"failed_to_run_version_script",project:e,moduleName:r,error:s}),Ar}}m(kc,"useModuleVersion");var Is=class extends h{static name="run";static description=`Executes Actor locally with simulated Apify environment variables.
279
+ Stores data in local '${ot}' directory.
280
+
281
+ NOTE: For Node.js Actors, customize behavior by modifying the 'start' script in package.json file.`;static group="Local Actor Development";static examples=[{description:"Run the Actor in the current directory with the stored input.",command:"apify run"},{description:"Run and purge the default storage first (dataset, request queue, key-value store).",command:"apify run --purge"},{description:"Run with inline JSON input (overrides the stored INPUT).",command:`apify run --input '{"startUrls":[{"url":"https://example.com"}]}'`},{description:"Run with input from a file.",command:"apify run --input-file ./input.json"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-run";static flags={purge:w.boolean({char:"p",description:"Whether to purge the default request queue, dataset and key-value store before the run starts.\nFor crawlee projects, this is the default behavior, and the flag is optional.\nUse `--no-purge` to keep the storage folder intact.",required:!1,default:!0,exclusive:["resurrect"]}),resurrect:w.boolean({description:"Whether to keep the default request queue, dataset and key-value store before the run starts.",required:!1,default:!1,exclusive:["purge"]}),entrypoint:w.string({description:["Optional entrypoint for running with injected environment variables.",`
282
+ `,"For Python, it is the module name, or a path to a file.",`
283
+ `,"For Node.js, it is the npm script name, or a path to a JS/MJS file.",'You can also pass in a directory name, provided that directory contains an "index.js" file.'].join(" "),required:!1}),input:w.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":w.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]}),"allow-missing-secrets":w.boolean({description:"Allow the command to continue even when secret values are not found in the local secrets storage.",required:!1,default:!1})};async run(){let e=Ve.cwd(),{proxy:t,id:o,token:s}=await M(),i=await Le({cwd:e});if(i.isErr()){let{message:O,cause:U}=i.unwrapErr();g({message:`${O}${U?`
284
+ ${U.message}`:""}`}),Ve.exitCode=5;return}let{config:n}=i.unwrap(),a=we(),c=await Ne({cwd:e});if(c.isErr()){g({message:c.unwrapErr().message}),Ve.exitCode=5;return}let l=c.unwrap(),{type:d,entrypoint:u,runtime:p}=l;if(l.warnings?.length)for(let O of l.warnings)x({message:O});if(d===3)throw new Error("Actor is of an unknown format. Make sure your project is supported by Apify CLI (either a package.json file is present, or a Python entrypoint could be found) or you are in a migrated Scrapy project.");if(!p){switch(d){case 0:g({message:`No Node.js detected! Please install Node.js ${Ie} (or higher) to be able to run Node.js Actors locally.`});break;case 2:case 1:g({message:`No Python detected! Please install Python ${st} (or higher) to be able to run Python Actors locally.`});break;default:g({message:`No runtime detected! Make sure you have Python ${st} (or higher) or Node.js ${Ie} (or higher) installed.`})}return}let f,y;if(this.flags.entrypoint){y=this.flags.entrypoint;let O=Ts(e,this.flags.entrypoint),U=await Nc(O).catch(()=>null);U?.isDirectory()?f=1:U?.isFile()?f=0:f=2}else if(u?.script)f=2,y=u.script;else if(u?.path)f=d!==0?1:0,y=u.path;else{g({message:"No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint."});return}Oc(qs)&&!Oc(a)&&(Bp(qs,a),x({message:`The legacy 'apify_storage' directory was renamed to '${a}' to align it with Apify SDK v3. Contents were left intact.`}));let v=await kc({moduleName:"crawlee",project:l}),S="0";this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(S="1",v.isNone()&&(await Promise.all([hn(),wn(),yn()]),b({message:"All default local stores were purged."}))),this.flags.purge||!await An()&&!this.flags.resurrect&&x({message:"The storage directory contains a previous state, the Actor will continue where it left off. To start from the initial state, use --purge parameter to clean the storage directory."});let E=await Nt(e,this.flags.input,this.flags.inputFile);if(E===!1)return;let C=await this.validateAndStoreInput(E),P={[Cs.LOCAL_STORAGE_DIR]:a,CRAWLEE_STORAGE_DIR:a,CRAWLEE_PURGE_ON_START:S};if(t&&t.password&&(P[Cs.PROXY_PASSWORD]=t.password),o&&(P[Cs.USER_ID]=o),s&&(P[Cs.TOKEN]=s),n.environmentVariables){let O=Ga(n.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets});Object.assign(P,O)}let N=Object.assign(P,Ve.env);o||x({message:'You are not logged in with your Apify Account. Some features like Apify Proxy will not work. Call "apify login" to fix that.'});try{switch(d){case 0:{let O=Yp(Ie);if(Mr(p.version)?N.NODE_OPTIONS=N.NODE_OPTIONS?`${N.NODE_OPTIONS} --max-http-header-size=80000`:"--max-http-header-size=80000":x({message:`You are running Node.js version ${p.version}, which is no longer supported. Please upgrade to Node.js version ${O} or later.`}),f===0||f===1)await fe({cmd:p.executablePath,args:[y],opts:{env:N,cwd:e}});else{let U=await Vp(Ts(e,"package.json"),"utf8").catch(()=>"{}"),J=JSON.parse(U);if(!J.scripts)throw new Error('No scripts were found in package.json. Please set it up for your project. For more information about that call "apify help run".');if(!J.scripts[y])throw new Error(`The script "${y}" was not found in package.json. Please set it up for your project. For more information about that call "apify help run".`);if(!p.pmPath)throw new Error("No npm executable found! Please make sure your Node.js runtime has npm installed if you want to run package.json scripts locally.");await fe({cmd:p.pmPath,args:["run",y],opts:{env:N,cwd:e},overrideCommand:p.pmName})}break}case 1:case 2:{if(!Ur(p.version)){g({message:`Python Actors require Python 3.9 or higher, but you have Python ${p.version}!`}),g({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}f===1?await fe({cmd:p.executablePath,args:["-m",y],opts:{env:N,cwd:e}}):await fe({cmd:p.executablePath,args:[y],opts:{env:N,cwd:e}});break}default:g({message:"Failed to detect the language of your project. Please report this issue to the Apify team with your project structure over at https://github.com/apify/apify-cli/issues"})}}catch(O){let{stderr:U}=O}finally{if(C)if(C.existingInput){let O=await Nc(C.inputFilePath);if(Math.trunc(O.mtimeMs)-C.writtenAt>=5){x({message:`The "${C.inputFilePath}" file was overwritten during the run. The CLI will not undo the setting of missing default fields from your input schema.`});return}await vr(C.inputFilePath,C.existingInput.body)}else await Yt(C.inputFilePath)}}async validateAndStoreInput(e){let{inputSchema:t}=await Tt({cwd:Ve.cwd()});if(!t){if(!e)return null;let l=Zt(Ve.cwd()),d=Ts(Ve.cwd(),he(),l?.fileName??"INPUT.json");return await bs(Ss(d),{recursive:!0}),await vr(d,JSON.stringify(e.input,null,2)),{existingInput:l,inputFilePath:d,writtenAt:Date.now()}}let o=new Wt({strict:!1,unicodeRegExp:!1});Hp(o,t);let s=ba(t),i=Sa(t,o),n=Zt(Ve.cwd()),a=Ts(Ve.cwd(),he(),n?.fileName??"INPUT.json"),c;switch(e?.source){case"stdin":c=`The input provided through standard input is invalid. Please fix the following errors:
285
+ `;break;case"input":c=`The input provided through the --input flag is invalid. Please fix the following errors:
286
+ `;break;default:e?c=`The input provided through the ${e.source} file is invalid. Please fix the following errors:
287
+ `:c=`The input in your storage is invalid. Please fix the following errors:
288
+ `;break}if(e){let l={...s,...e.input},d=Lc(i,t,l);if(d.length>0)throw new Error(`${c}${d.map(u=>` - ${u.message.replace("Field input.","Field ")}`).join(`
289
+ `)}`);return await bs(Ss(a),{recursive:!0}),await vr(a,JSON.stringify(l,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}if(!n)return await bs(Ss(a),{recursive:!0}),await vr(a,JSON.stringify(s,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()};if(Gp.getExtension(n.contentType)==="json"){let l=JSON.parse(n.body.toString("utf-8"));if(Array.isArray(l))throw new Error("The input in your storage is invalid. It should be an object, not an array.");let d={...s,...l},u=Lc(i,t,d);if(u.length>0)throw new Error(`${c}${u.map(p=>` - ${p.message.replace("Field input.","Field ")}`).join(`
290
+ `)}`);return await bs(Ss(a),{recursive:!0}),await vr(a,JSON.stringify(d,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}return null}};import{ACTOR_JOB_STATUSES as Es}from"@apify/consts";var Jp=[Es.READY,Es.RUNNING],qp=[Es.ABORTING,Es.TIMING_OUT],$s=class extends h{static name="abort";static description="Aborts an Actor run.";static examples=[{description:"Abort a running Actor gracefully (up to 30s drain).",command:"apify runs abort <runId>"},{description:"Force-abort a running Actor immediately.",command:"apify runs abort <runId> --force"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-abort";static args={runId:A.string({required:!0,description:"The run ID to abort."})};static flags={force:w.boolean({description:"Whether to force the run to abort immediately, instead of gracefully.",default:!1,char:"f"})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){g({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Jp.includes(o.status)){qp.includes(o.status)?g({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):g({message:`Run with ID "${e}" is already aborted.`,stdout:!0});return}try{let s=await t.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){L(s);return}this.flags.force?R({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):R({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(s){let i=s;g({message:`Failed to abort run "${e}".
291
+ ${i.message||i}`,stdout:!0})}}};import _ from"chalk";var br=new B({allColumns:["","Unit","USD Amount"],mandatoryColumns:["","Unit","USD Amount"],columnAlignments:{Unit:"right","USD Amount":"right"}}),Dc={"Actor compute units":"ACTOR_COMPUTE_UNITS","Dataset reads":"DATASET_READS","Dataset writes":"DATASET_WRITES","Key-value store reads":"KEY_VALUE_STORE_READS","Key-value store writes":"KEY_VALUE_STORE_WRITES","Key-value store lists":"KEY_VALUE_STORE_LISTS","Request queue reads":"REQUEST_QUEUE_READS","Request queue writes":"REQUEST_QUEUE_WRITES","Data transfer internal":"DATA_TRANSFER_INTERNAL_GBYTES","Data transfer external":"DATA_TRANSFER_EXTERNAL_GBYTES","Proxy residential data transfer":"PROXY_RESIDENTIAL_TRANSFER_GBYTES","Proxy SERPs":"PROXY_SERPS"},Rs=class extends h{static name="info";static description="Prints information about an Actor run.";static examples=[{description:"Show a summary of a run.",command:"apify runs info <runId>"},{description:"Show verbose details including usage breakdown.",command:"apify runs info <runId> --verbose"},{description:"Emit the full run object as JSON.",command:"apify runs info <runId> --json"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-info";static args={runId:A.string({required:!0,description:"The run ID to print information about."})};static flags={verbose:w.boolean({char:"v",description:"Prints more in-depth information about the Actor run.",default:!1})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){g({message:`Run with ID "${e}" was not found on your account.`});return}let[s,i,n,a,c]=await Promise.all([t.actor(o.actId).get(),t.build(o.buildId).get(),o.actorTaskId?t.task(o.actorTaskId).get():Promise.resolve(void 0),t.dataset(o.defaultDatasetId).get(),t.requestQueue(o.defaultRequestQueueId).get()]);if(this.flags.json){L({...o,actor:s,build:i,task:n,defaultDataset:a,defaultRequestQueue:c});return}this.addDetailedUsage(o);let l=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",d=[`${_.yellow("Actor")}: ${l} (${_.grey(o.actId)})`];n?d.push(`\u2514\u2500 ${_.yellow("Task")}: ${n.title??n.name} (${_.gray(o.actorTaskId)})`,""):o.actorTaskId?d.push(`\u2514\u2500 ${_.yellow("Task")}: unknown-task (${_.gray(o.actorTaskId)})`,""):d.push("");let u=` (exit code: ${_.gray(o.exitCode!==null?o.exitCode:"N/A")})`;d.push(`${_.yellow("Status")}: ${Pe(o.status)}${u}`),o.statusMessage&&d.push(`\u2514\u2500 ${_.yellow("Status Message:")} ${o.statusMessage}`);let p=a?.itemCount??0;d.push(`${_.yellow("Results")}: ${_.cyan(p.toLocaleString("en-US"))}`),c?d.push(`${_.yellow("Requests")}: ${_.cyan(c.handledRequestCount.toLocaleString("en-US"))} out of ${_.cyan(c.totalRequestCount.toLocaleString("en-US"))} handled`):d.push(`${_.yellow("Requests")}: ${_.gray("unknown handled")}`);let f=this.flags.verbose?"":_.gray(` (run with ${_.yellow("--verbose")} for a detailed breakdown)`);if(o.usageTotalUsd?d.push(`${_.yellow("Usage")}: ${_.cyan(this.formatUsd(o.usageTotalUsd))}${f}`):d.push(`${_.yellow("Usage")}: $${_.gray("0.000")}${f}`),this.flags.verbose&&d.push(br.render(0)),d.push(""),d.push(`${_.yellow("Started")}: ${Y.display(o.startedAt)}`),o.finishedAt)d.push(`${_.yellow("Finished")}: ${Y.display(o.finishedAt)} (took ${_.gray(me.format(o.stats.durationMillis))})`);else{let E=Date.now()-o.startedAt.getTime();d.push(`${_.yellow("Finished")}: ${_.gray(`Running for ${me.format(E)}`)}`)}if(d.push(""),o.stats.resurrectCount?d.push(`${_.yellow("Resurrected")}: Yes, ${_.cyan(o.stats.resurrectCount.toLocaleString("en-US"))} ${this.pluralString(o.stats.resurrectCount,"time","times")}`):d.push(`${_.yellow("Resurrected")}: No`),o.containerUrl&&d.push(`${_.yellow("Container URL")}: ${_.blue(o.containerUrl)}`),d.push(`${_.yellow("Origin")}: ${o.meta.origin}`),s){let E=o.buildNumber.split(".").slice(0,2).join("."),C=s.versions.find(O=>O.versionNumber===E),P=Object.entries(s.taggedBuilds??{}).find(([,O])=>O.buildNumber===o.buildNumber)?.[0],N=[`${_.yellow("Build")}:`,_.cyan(o.buildNumber)];P?N.push(`(${_.yellow(P)})`):N.push(`(${_.gray("N/A")})`),C&&N.push(`| ${_.gray("Actor version:")} ${_.cyan(C.versionNumber)} (${_.yellow(C.buildTag)})`),d.push(N.join(" "))}else d.push(`${_.yellow("Build")}: ${_.cyan(o.buildNumber)}`);d.push(`${_.yellow("Timeout")}: ${o.options.timeoutSecs.toLocaleString("en-US")} seconds`),d.push(`${_.yellow("Memory")}: ${o.options.memoryMbytes} MB`),d.push(""),d.push(`${_.yellow("CPU")}: ${_.gray("Average:")} ${o.stats.cpuAvgUsage.toFixed(2)}% | ${_.gray("Maximum:")} ${o.stats.cpuMaxUsage.toFixed(2)}%`),d.push(`${_.yellow("Memory")}: ${_.gray("Average:")} ${ee({bytes:o.stats.memAvgBytes,shortBytes:!0})} | ${_.gray("Maximum:")} ${ee({bytes:o.stats.memMaxBytes,shortBytes:!0})}`),d.push("");let y=`https://console.apify.com/actors/${o.actId}/runs/${o.id}`,v=`https://console.apify.com/storage/datasets/${o.defaultDatasetId}`,S=`https://console.apify.com/storage/key-value-stores/${o.defaultKeyValueStoreId}`;d.push(`${_.blue("Export results")}: ${v}`),d.push(`${_.blue("View saved items")}: ${S}`),d.push(`${_.blue("View in Apify Console")}: ${y}`),$({message:d.join(`
292
+ `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:o}=e;if(!t||!o){for(let s of Object.keys(Dc))br.pushRow({"":s,Unit:"N/A","USD Amount":"N/A"});return}for(let[s,i]of Object.entries(Dc)){let n=t[i]??0,a=o[i]??0;switch(i){case"ACTOR_COMPUTE_UNITS":{br.pushRow({"":s,Unit:n.toFixed(4),"USD Amount":this.formatUsd(a)});break}case"DATA_TRANSFER_INTERNAL_GBYTES":case"DATA_TRANSFER_EXTERNAL_GBYTES":case"PROXY_RESIDENTIAL_TRANSFER_GBYTES":{br.pushRow({"":s,Unit:ee({bytes:n*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break}default:br.pushRow({"":s,Unit:n.toLocaleString("en-US"),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}};var xs=class extends h{static name="log";static description="Prints the log of a specific run.";static examples=[{description:"Print the log of a specific run to stdout.",command:"apify runs log <runId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-log";static args={runId:A.string({required:!0,description:"The run ID to get the log from."})};async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){g({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}b({message:`Log for run with ID "${e}":
293
+ `,stdout:!0});try{await ke({job:o,apifyClient:t})}catch(s){g({message:`Failed to get log for run with ID "${e}": ${s.message}`})}}};import be from"chalk";var Fc=new B({allColumns:["ID","Status","Results","Usage","Started At","Took","Build No.","Origin"],mandatoryColumns:["ID","Status","Results","Usage","Started At","Took"],columnAlignments:{Results:"right",Usage:"right",Took:"right","Build No.":"right"}}),_s=class extends h{static name="ls";static description="Lists all runs of the Actor.";static examples=[{description:"List runs of the Actor in the current directory.",command:"apify runs ls"},{description:"List runs of a specific Actor.",command:"apify runs ls apify/hello-world"},{description:"List the 50 most recent runs in descending order.",command:"apify runs ls --limit 50 --desc"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-ls";static flags={offset:w.integer({description:"Number of runs that will be skipped.",default:0}),limit:w.integer({description:"Number of runs that will be listed.",default:10}),desc:w.boolean({description:"Sort runs in descending order.",default:!1}),compact:w.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:A.string({description:"Optional Actor ID or Name to list runs for. By default, it will use the Actor from the current directory."})};static enableJsonFlag=!0;async run(){let{desc:e,limit:t,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await I(),c=await Je({providedActorNameOrId:n,client:a});if(!c.valid){g({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let l=await a.actor(c.id).runs().list({desc:e,limit:t,offset:o});if(i){L(l);return}if(!l.items.length){$({message:"There are no recent runs found for this Actor."});return}let d=[`${be.reset("Showing")} ${be.yellow(l.items.length)} out of ${be.yellow(l.total)} runs for Actor ${be.yellow(c.userFriendlyId)} (${be.gray(c.id)})`],u=new Map(await Promise.all(l.items.map(async p=>a.dataset(p.defaultDatasetId).get().then(f=>[p.id,be.yellow(f?.itemCount??0)],()=>[p.id,be.gray("N/A")]))));for(let p of l.items){let f;if(p.finishedAt){let y=p.finishedAt.getTime()-p.startedAt.getTime();f=be.gray(`${me.format(y,void 0,{left:""})}`)}else{let y=Date.now()-p.startedAt.getTime();f=be.gray(`Running for ${me.format(y,void 0,{left:""})}`)}Fc.pushRow({ID:be.gray(p.id),Status:Pe(p.status),Results:u.get(p.id)||be.gray("N/A"),Usage:be.cyan(`$${(p.usageTotalUsd??0).toFixed(3)}`),"Started At":er.display(p.startedAt),Took:f,"Build No.":p.buildNumber,Origin:p.meta.origin??"UNKNOWN"})}d.push(Fc.render(s?0:1)),$({message:d.join(`
294
+ `),stdout:!0})}};import{ACTOR_JOB_STATUSES as Ps}from"@apify/consts";var Kp=[Ps.SUCCEEDED,Ps.FAILED,Ps.ABORTED,Ps.TIMED_OUT],ks=class extends h{static name="resurrect";static description="Resurrects an aborted or finished Actor Run.";static examples=[{description:"Resurrect a finished or aborted run.",command:"apify runs resurrect <runId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-resurrect";static args={runId:A.string({required:!0,description:"The run ID to resurrect."})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){g({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Kp.includes(o.status)){g({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});return}try{let s=await t.run(e).resurrect();if(this.flags.json){L(s);return}R({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(s){let i=s;g({message:`Failed to resurrect run "${e}".
295
+ ${i.message||i}`,stdout:!0})}}};import{ACTOR_JOB_STATUSES as Os}from"@apify/consts";var Wp=[Os.SUCCEEDED,Os.FAILED,Os.ABORTED,Os.TIMED_OUT],Ns=class extends h{static name="rm";static description="Deletes an Actor Run.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.";static examples=[{description:"Delete a finished or aborted run (prompts for confirmation).",command:"apify runs rm <runId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-rm";static args={runId:A.string({description:"The run ID to delete.",required:!0})};static flags={...ie};async run(){let{runId:e}=this.args,{yes:t}=this.flags,o=await I(),s=await o.run(e).get();if(!s){g({message:`Run with ID "${e}" was not found on your account.`});return}if(!Wp.includes(s.status)){g({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await Z({message:"Are you sure you want to delete this Actor Run?",providedConfirmFromStdin:t||void 0})){b({message:`Deletion of run "${e}" was canceled.`});return}try{await o.run(e).delete(),R({message:`Run with ID "${e}" was deleted.`})}catch(n){let a=n;g({message:`Failed to delete run "${e}".
296
+ ${a.message||a}`})}}};var Ls=class extends h{static name="runs";static description=`Inspect, abort, resurrect, or delete existing Actor runs.
297
+ Does not start new runs \u2014 use 'apify call' (synchronous) or 'apify actors start' (asynchronous) for that.`;static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs";static subcommands=[$s,Rs,xs,_s,ks,Ns];async run(){this.printHelp()}};var Ds=class extends h{static name="add";static description="Adds a new secret to '~/.apify' for use in Actor environment variables.";static examples=[{description:'Add a secret named "mySecret". Reference it in .actor/actor.json as "@mySecret".',command:"apify secrets add mySecret TopSecretValue123"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-secrets-add";static args={name:A.string({required:!0,description:"Name of the secret."}),value:A.string({required:!0,description:"Value of the secret."})};async run(){let{name:e,value:t}=this.args;ja(e,t)}};import zp from"chalk";var Uc=new B({allColumns:["Secret Name"],mandatoryColumns:["Secret Name"],columnAlignments:{"Secret Name":"left"}}),Fs=class extends h{static name="ls";static description="Lists all secret keys stored in your local configuration.";static examples=[{description:"List the names of all locally stored secrets.",command:"apify secrets ls"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-secrets-ls";static enableJsonFlag=!0;async run(){let{json:e}=this.flags,t=Ut(),o=Object.keys(t);if(e){L({keys:o});return}if(o.length===0){b({message:"You don't have any secrets stored locally. Use 'apify secrets add' to add a secret.",stdout:!0});return}for(let s of o)Uc.pushRow({"Secret Name":zp.cyan(s)});$({message:Uc.render(1),stdout:!0})}};var Us=class extends h{static name="rm";static description="Permanently deletes a secret from your stored credentials.";static examples=[{description:"Delete a locally stored secret by name.",command:"apify secrets rm mySecret"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-secrets-rm";static args={name:A.string({required:!0,description:"Name of the secret."})};async run(){let{name:e}=this.args;Ba(e)}};var Ms=class extends h{static name="secrets";static description=`Manage locally stored secrets that can be referenced from '${D}' environment variables using the "@" prefix (e.g. "@mySecret"). Secrets are uploaded alongside the Actor and stored encrypted on the Apify platform.`;static group="Authentication";static examples=[{description:'Store a secret called "mySecret".',command:"apify secrets add mySecret TopSecretValue123"},{description:'Reference the secret from .actor/actor.json using the "@" prefix, e.g. "environmentVariables": { "SECRET_ENV_VAR": "@mySecret" }, then push as usual.',command:"apify push"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-secrets";static subcommands=[Ds,Fs,Us];async run(){this.printHelp()}};import Mc from"chalk";var js=class extends h{static name="run";static description=`Executes predefined Actor task remotely using local key-value store for input.
298
+ Customize with --memory and --timeout flags.
299
+ `;static examples=[{description:"Run a task by name.",command:"apify task run my-task"},{description:"Run a task by full ID with custom memory and timeout.",command:"apify task run username/my-task --memory 4096 --timeout 600"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-task-run";static flags=Dt("Task");static args={taskId:A.string({required:!0,description:'Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").'})};async run(){let e=await I(),t=await M(),o=t.username||t.id,{id:s,userFriendlyId:i,title:n}=await this.resolveTaskId(e,o),a={waitForFinish:2};this.flags.build&&(a.build=this.flags.build),this.flags.timeout&&(a.timeout=this.flags.timeout),this.flags.memory&&(a.memory=this.flags.memory);let c,l,d=Lt(e,{actorOrTaskData:{id:s,userFriendlyId:i,title:n},runOptions:a,type:"Task",printRunLogs:!0});for await(let u of d)c=`https://console.apify.com/actors/${u.actId}/runs/${u.id}`,l=`https://console.apify.com/storage/datasets/${u.defaultDatasetId}`;$({message:["",`${Mc.blue("Export results")}: ${l}`,`${Mc.blue("View on Apify Console")}: ${c}`].join(`
300
+ `),stdout:!0})}async resolveTaskId(e,t){let{taskId:o}=this.args;if(o?.includes("/")){let s=await e.task(o).get();if(!s)throw new Error(`Cannot find Task with ID '${o}' in your account.`);return{id:s.id,userFriendlyId:`${t}/${s.name}`,title:s.title,task:s}}if(o){let s=await e.task(`${t}/${o.toLowerCase()}`).get();if(!s)throw new Error(`Cannot find Task with name '${o}' in your account.`);return{id:s.id,userFriendlyId:`${t}/${s.name}`,title:s.title,task:s}}throw new Error("Please provide a valid Task ID or name.")}};var Bs=class extends h{static name="task";static description="Run saved Apify tasks (named Actor configurations). Only 'task run' is available; create and manage tasks in Apify Console.";static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-task";static subcommands=[js];async run(){this.printHelp()}};var Vs=class extends h{static name="disable";static description="Disables telemetry.";static examples=[{description:"Opt out of anonymous telemetry.",command:"apify telemetry disable"}];static docsUrl="https://docs.apify.com/cli/docs/telemetry";async run(){(await ue()).enabled?(await Gr(!1),R({message:"Telemetry disabled."})):b({message:"Telemetry is already disabled."})}};var Gs=class extends h{static name="enable";static description="Enables telemetry.";static examples=[{description:"Opt in to anonymous telemetry.",command:"apify telemetry enable"}];static docsUrl="https://docs.apify.com/cli/docs/telemetry";async run(){(await ue()).enabled?b({message:"Telemetry is already enabled."}):(await Gr(!0),R({message:"Telemetry enabled."}))}};var Sr=class extends h{static name="telemetry";static description="Enable or disable anonymous telemetry. We use this data to improve the CLI and the Apify platform.";static group="Utilities";static docsUrl="https://docs.apify.com/cli/docs/telemetry";static subcommands=[Gs,Vs];async run(){this.printHelp()}};import Xp from"process";var Ys=class extends h{static name="validate-schema";static description=`Validates Actor input schema from one of these locations (in priority order):
301
+ 1. Object in '${D}' under "input" key
302
+ 2. JSON file path in '${D}' "input" key
303
+ 3. .actor/INPUT_SCHEMA.json
304
+ 4. INPUT_SCHEMA.json
305
+
306
+ Optionally specify custom schema path to validate.`;static group="Local Actor Development";static examples=[{description:"Validate the input schema discovered from the default locations.",command:"apify validate-schema"},{description:"Validate a specific INPUT_SCHEMA.json file.",command:"apify validate-schema ./my-schema.json"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-validate-schema";static args={path:A.string({required:!1,description:"Optional path to your INPUT_SCHEMA.json file. If not provided ./INPUT_SCHEMA.json is used."})};static hiddenAliases=["vis"];async run(){await uo({forcePath:this.args.path,cwd:Xp.cwd(),getMessage:m(e=>e?`Validating input schema at ${e}`:`Validating input schema embedded in '${D}'`,"getMessage")}),R({message:"Input schema is valid."})}};var eN=[yo,Ro,Po,Mo,Zo,gs,vs,Ls,Ms,Bs,Sr,xo,jo,yr,hr,Vo,Qo,ts,is,ss,hs,ys,ws,As,Is,Ys,wr],tN=[kt,Pt,_t,xt,Rt,St,bt,$t,wr,yr,hr,Sr];export{vw as a,bw as b,eN as c,tN as d};
307
+ //# sourceMappingURL=chunk-K6JWY7BZ.js.map