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

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,303 @@
1
+ var Lc=Object.defineProperty;var m=(r,e)=>Lc(r,"name",{value:e,configurable:!0});import Re from"process";import{parseArgs as ra}from"util";import so from"chalk";import{satisfies as Md}from"semver";import di from"chalk";import Ad from"indent-string";import vd from"widest-line";import bd from"wrap-ansi";import Bi from"ci-info";var Dc=[["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 Vi(){for(let[r,e]of Dc)if(process.env[r])return e}m(Vi,"detectAiAgent");function Gi(){return Bi.isCI?{isCi:!0,ciProvider:Bi.id?.toLowerCase()??"unknown"}:{isCi:!1,ciProvider:void 0}}m(Gi,"detectCi");function Yi(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}m(Yi,"detectIsInteractive");import Fc from"chalk";function T(r,...e){process.env.APIFY_CLI_DEBUG&&console.error(Fc.gray(`[${r}]`),...e)}m(T,"cliDebugPrint");import{realpathSync as Uc}from"fs";import{dirname as Mc}from"path";import pt from"chalk";function Qe(r){r.stdoutOutput&&console.log(...r.stdoutOutput),r.stderrOutput&&console.error(...r.stderrOutput)}m(Qe,"internalLog");function R(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[r.message]})}m(R,"simpleLog");function f(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[pt.red("Error:"),r.message]})}m(f,"error");function x(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[pt.yellow.bold("Warning:"),r.message]})}m(x,"warning");function $(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[pt.green("Success:"),r.message]})}m($,"success");function Se(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[pt.gray("Run:"),r.message]})}m(Se,"run");function v(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[pt.white("Info:"),r.message]})}m(v,"info");function Bs(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[pt.blue(r.message),r.url]})}m(Bs,"link");var Vs="0.0.0";var jc="1.4.2-beta.5",Bc="551cf5513ab814ddd6f7bd6a35a9cbbc004fe400";function Vc(){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=Uc(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(Vc,"detectInstallMethod");function Gc(){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(Gc,"getRuntimeInfo");var jt=null;function z(){if(jt)return jt;let r=Vc(),e=Gc();return jt={version:jc,hash:Bc,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===Vs}},r==="bundle"&&(jt.installPath=Mc(process.execPath)),jt}m(z,"useCLIMetadata");import{existsSync as Rl,mkdirSync as xl,readFileSync as _l,writeFileSync as kl}from"fs";import{dirname as Pl}from"path";import{cryptoRandomObjectId as Ol}from"@apify/utilities";import{homedir as Hc}from"os";import{join as et}from"path";import{KEY_VALUE_STORE_KEYS as qc,META_ORIGINS as Jc}from"@apify/consts";var Hi={name:"apify-cli",version:"1.4.2-beta.5",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 tt="storage",Gs="apify_storage",Ys=1,br={actorSpecification:Ys,name:null,version:"0.0",buildTag:"latest",environmentVariables:{}},qi=1440*60*1e3,ft=m(()=>{let r=et(Hc(),".apify");return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?et(r,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):r},"GLOBAL_CONFIGS_FOLDER"),fe=m(()=>et(ft(),"auth.json"),"AUTH_FILE_PATH"),Sr=m(()=>et(ft(),"secrets.json"),"SECRETS_FILE_PATH"),Tr=m(()=>et(ft(),"state.json"),"STATE_FILE_PATH"),Cr=m(()=>et(ft(),"telemetry.json"),"TELEMETRY_FILE_PATH"),Ir="apify.json",Er=".actor",Kc="actor.json",D=et(Er,Kc),Hs=new RegExp(`(^${qc.INPUT}(?:\\.[^.]+)?$)`),Te=Hi.engines.node,Ji={"X-Apify-Request-Origin":Jc.CLI},rt="3.9.0",Ki=".venv";import{execSync as rl}from"child_process";import{createWriteStream as ol,existsSync as oe,mkdirSync as sl,readdirSync as en,readFileSync as qt,writeFileSync as Rr}from"fs";import{mkdir as il,readFile as xr}from"fs/promises";import{get as nl}from"https";import{homedir as qs}from"os";import{dirname as gt,join as J,relative as al}from"path";import X from"process";import{finished as cl}from"stream/promises";import{DurationFormatter as tn,TimeTypes as ot}from"@sapphire/duration";import{Timestamp as Js}from"@sapphire/timestamp";import ll from"adm-zip";import dl from"ajv/dist/2019.js";import{ApifyClient as rn}from"apify-client";import ml from"archiver";import{AxiosHeaders as ul}from"axios";import pl from"escape-string-regexp";import fl from"ignore";import{getEncoding as gl}from"istextorbinary";import{Mime as yl}from"mime";import hl from"mime/types/other.js";import wl from"mime/types/standard.js";import{gte as Al,minVersion as vl,satisfies as bl}from"semver";import{glob as Ks}from"tinyglobby";import{ACTOR_ENV_VARS as Ws,ACTOR_JOB_TERMINAL_STATUSES as Sl,ACTOR_NAME as Yt,APIFY_ENV_VARS as Tl,KEY_VALUE_STORE_KEYS as Qi,LOCAL_ACTOR_ENV_VARS as zs,LOCAL_STORAGE_SUBDIRS as Xs,SOURCE_FILE_FORMATS as Gt}from"@apify/consts";import{existsSync as Wc,mkdirSync as zc}from"fs";import{readFile as Xc,stat as Wi,unlink as Zc,writeFile as Qc}from"fs/promises";import{join as zi,sep as el}from"path";import{rimraf as tl}from"rimraf";var Xi=m(async(r,e={},t=null)=>{let o=await Xc(r,"utf-8"),s=JSON.parse(o),i;t?(i=s,i[t]={...s[t],...e}):i={...s,...e},await Qc(r,JSON.stringify(i,null," "))},"updateLocalJson"),$r=m((r,e)=>{e||(e=r,r="."),e.split(el).reduce((o,s)=>(o=zi(o,s),Wc(o)||zc(o),o),r)},"ensureFolderExistsSync"),Bt=m(async r=>{await tl(r)},"rimrafPromised"),Vt=m(async r=>{(await Wi(r)).isFile()&&await Zc(r)},"deleteFile"),Zi=m(async(r,e)=>(await Promise.all(r.map(async s=>Wi(zi(e,s))))).map(s=>s.size).reduce((s,i)=>s+i,0),"sumFilesSizeInBytes");var Ht=fl,Jt=dl,_r=m(async r=>new Promise((e,t)=>{nl(r,o=>{o.statusCode===301||o.statusCode===302?(e(_r(o.headers.location)),o.destroy()):e(o)}).on("error",t)}),"httpsGet"),ye=m(()=>{let r=Tl.LOCAL_STORAGE_DIR;return X.env[r]||X.env.CRAWLEE_STORAGE_DIR||tt},"getLocalStorageDir"),ge=m(r=>{let e=Ws.DEFAULT_KEY_VALUE_STORE_ID,t=r||X.env[e]||zs[e];return J(ye(),Xs.keyValueStores,t)},"getLocalKeyValueStorePath"),on=m(r=>{let e=Ws.DEFAULT_DATASET_ID,t=r||X.env[e]||zs[e];return J(ye(),Xs.datasets,t)},"getLocalDatasetPath"),sn=m(r=>{let e=Ws.DEFAULT_REQUEST_QUEUE_ID,t=r||X.env[e]||zs[e];return J(ye(),Xs.requestQueues,t)},"getLocalRequestQueuePath"),M=m(async()=>{let r={};try{let e=await xr(fe(),"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 Wt();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 nn=m(r=>{if(!r&&oe(ft())&&oe(fe())){let e=qt(fe(),"utf-8");return JSON.parse(e).token}return r},"getTokenWithAuthFileFallback"),Kt=m((r,e)=>(r=nn(r),{token:r,baseUrl:e||X.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[t=>{t.headers??=new ul;for(let[o,s]of Object.entries(Ji))t.headers[o]=s;return t}]}),"getApifyClientOptions");async function Wt(r,e){r=nn(r);let t=new rn(Kt(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 Qs(fe()),Rr(fe(),JSON.stringify({token:t.token,...o},null," ")),t}m(Wt,"getLoggedClient");var Zs=m(r=>J(r,D),"getLocalConfigPath"),le=m(r=>{if(oe(r))return JSON.parse(qt(r,{encoding:"utf-8"}))},"getJsonFileContent"),Ue=m(r=>le(Zs(r)),"getLocalConfig"),kr=m(async(r,e)=>{let t=J(e||X.cwd(),D);await il(gt(t),{recursive:!0}),Rr(t,JSON.stringify(r,null," "))},"setLocalConfig"),Cl=[ye(),"node_modules",".venv"],Pr=m(async r=>{let e=ge();$r(r,on()),$r(r,sn()),$r(r,e);let t=J(r,".gitignore"),o="";oe(t)&&(o=qt(t,{encoding:"utf-8"}));let s=[];for(let i of Cl)RegExp(`^${pl(i)}$`,"mg").test(o)||s.push(i);s.length>0&&(o.length>0?(s.unshift("# Added by Apify CLI"),Rr(t,`
2
+ ${s.join(`
3
+ `)}
4
+ `,{flag:"a"})):Rr(t,`${s.join(`
5
+ `)}
6
+ `,{flag:"w"}))},"setLocalEnv"),an=new yl(wl,hl).define({"application/gzip":["tgz"],"text/typescript":["ts","tsx","mts"]},!0),Il=m((r,e)=>{let t=an.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")?Gt.TEXT:Gt.BASE64:gl(e)==="binary"?Gt.BASE64:Gt.TEXT},"getSourceFileFormat"),cn=m(async(r,e)=>r.map(t=>{let o=qt(J(e,t)),s=Il(t,o);return{name:t,format:s,content:s===Gt.TEXT?o.toString("utf8"):o.toString("base64")}}),"createSourceFiles"),El=m(async r=>{let e=await Ks("**/.gitignore",{dot:!0,cwd:r,ignore:[".git/**"],expandDirectories:!1}),t=[];for(let s of e){let i=gt(s),n=await xr(J(r,s),"utf-8");t.push({dir:i==="."?"":i,ig:Ht().add(n)})}let o=gt(r);for(;o!==gt(o)&&!oe(J(o,".git"));){let s=J(o,".gitignore");if(oe(s))try{let i=await xr(s,"utf-8"),n=al(o,r);t.push({dir:"",ig:Ht().add(i),ancestorPrefix:n})}catch{}o=gt(o)}return t.length===0?s=>s:s=>s.filter(i=>{for(let{dir:n,ig:a,ancestorPrefix:c}of t){let d;if(n?i.startsWith(`${n}/`)?d=i.slice(n.length+1):d=null:d=c?`${c}/${i}`:i,d!==null&&a.ignores(d))return!1}return!0})},"getGitignoreFallbackFilter"),$l=m(async r=>{let e=J(r,".actorignore");if(!oe(e))return{excludeFilter:null,forceIncludePatterns:[]};let o=(await xr(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=Ht().add(s);return a.filter(d=>!c.ignores(d))}:null,forceIncludePatterns:i}},"parseActorIgnore"),ln=m(async r=>{let e=r??X.cwd(),t=[".git/**","apify_storage","node_modules","storage","crawlee_storage"],{excludeFilter:o,forceIncludePatterns:s}=await $l(e),i=null;try{let d=rl("git ls-files --others --ignored --exclude-standard --directory",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
8
+ `).filter(Boolean);if(d.length>0){let l=Ht().add(d);i=m(u=>u.filter(p=>!l.ignores(p)),"gitIgnoreFilter")}}catch{i=await El(e)}let n=await Ks(["*","**/**"],{ignore:t,dot:!0,expandDirectories:!1,cwd:e}),a=i?i(n):n;if(o&&(a=o(a)),s.length>0){let d=Ht().add(s),l=n.filter(p=>d.ignores(p)),u=new Set(a);for(let p of l)u.add(p);a=[...u]}let c=n.filter(d=>d===".actor"||d.startsWith(".actor/"));if(c.length>0){let d=new Set(a);for(let l of c)d.add(l);a=[...d]}return a},"getActorLocalFilePaths"),dn=m(async(r,e,t)=>{oe(r)&&await Vt(r);let o=ol(r),s=ml("zip",{zlib:{level:6}});s.pipe(o),e.forEach(i=>s.file(J(t,i),{name:i})),await s.finalize()},"createActZip"),zt=m(r=>{let e=ge();if(!oe(J(r,e)))return;let s=en(J(r,e)).find(a=>!!a.match(Hs));if(!s)return;let i=qt(J(r,e,s)),n=an.getType(s);return{body:i,contentType:n,fileName:s}},"getLocalInput"),mn=m(async()=>{let r=sn();oe(ye())&&oe(r)&&await Bt(r)},"purgeDefaultQueue"),un=m(async()=>{let r=on();oe(ye())&&oe(r)&&await Bt(r)},"purgeDefaultDataset"),pn=m(async()=>{let r=ge();if(!oe(ye())||!oe(r))return;let e=en(r),t=[];e.forEach(o=>{o.match(Hs)||t.push(Vt(J(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 rn({baseUrl:X.env.APIFY_CLIENT_BASE_URL});if(Sl.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",d=>{X.env.APIFY_NO_LOGS_IN_TESTS||X.stderr.write(d.toString())}),a.once("end",()=>{n("finished"),c&&clearTimeout(c)}),e&&(c=setTimeout(()=>{a.destroy(),n("timeouts")},e))})},"outputJobLog");var fn=m(async()=>(await Ks([`${ye()}/**`,`!${ge()}/${Qi.INPUT}.*`,`!${ge()}/${Qi.INPUT}_CLI-*`])).length===0,"checkIfStorageIsEmpty"),Xt=m(r=>{if(!Yt.REGEX.test(r))throw new Error("The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).");if(r.length<Yt.MIN_LENGTH)throw new Error("The Actor name must be at least 3 characters long.");if(r.length>Yt.MAX_LENGTH)throw new Error("The Actor name must be a maximum of 30 characters long.")},"validateActorName"),Or=m(r=>{let e=r.replaceAll(/[^a-zA-Z0-9-]/g,"-");return e.length<Yt.MIN_LENGTH&&(e=`${e}-apify-actor`),e=e.replaceAll(/^-+/g,"").replaceAll(/-+$/g,""),e.slice(0,Yt.MAX_LENGTH)},"sanitizeActorName"),Nr=m(r=>bl(r,`^${rt}`),"isPythonVersionSupported"),Lr=m(r=>{let e=vl(Te);return Al(r,e)},"isNodeVersionSupported"),Dr=m(async({url:r,pathTo:e})=>{let t=await _r(r),o=[];t.on("data",i=>o.push(i)),await cl(t),new ll(Buffer.concat(o)).extractAllTo(e,!0)},"downloadAndUnzip");function Qs(r){let e=gt(r);sl(e,{recursive:!0})}m(Qs,"ensureApifyDirectory");var Y=new Js("YYYY-MM-DD [at] HH:mm:ss"),Zt=new Js(`YYYY-MM-DD[
9
+ ]HH:mm:ss`),gn=new Js("YYYY-MM-DD"),Qt=new tn,de=new tn({[ot.Day]:{DEFAULT:"d"},[ot.Hour]:{DEFAULT:"h"},[ot.Minute]:{DEFAULT:"m"},[ot.Month]:{DEFAULT:"M"},[ot.Second]:{DEFAULT:"s"},[ot.Week]:{DEFAULT:"w"},[ot.Year]:{DEFAULT:"y"}});function Fr(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(Fr,"objectGroupBy");function L(r){console.log(JSON.stringify(r,null,2))}m(L,"printJsonToStdout");var ce=m(r=>r.startsWith(qs())?r.replace(qs(),"~"):r,"tildify");function yn(){let r=X.env.SHELL??"";return r.includes("zsh")?"zsh":r.includes("bash")?"bash":r.includes("fish")?"fish":"unknown"}m(yn,"detectShell");function hn(r,e){switch(e){case"bash":{let t=[J(r,".bashrc"),J(r,".bash_profile")];X.env.XDG_CONFIG_HOME&&t.push(J(X.env.XDG_CONFIG_HOME,".bashrc"),J(X.env.XDG_CONFIG_HOME,".bash_profile"),J(X.env.XDG_CONFIG_HOME,"bashrc"),J(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||qs();return J(t,".zshrc")}case"fish":return J(r,".config","fish","config.fish");case"unknown":return null}}m(hn,"shellConfigFile");var Nl=["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 wn(){return`CLI:${Ol()}`}m(wn,"createAnonymousId");async function Ll(r){if(r.version&&r.version>=1)return!1;let e=r,t=await M().catch(()=>({}));return er({version:1,enabled:!0},o=>{t.id&&e.distinctId===t.id?(o.anonymousId=wn(),o.userId=t.id):o.anonymousId=e.distinctId}),!0}m(Ll,"migrateStateV0ToV1");async function me(){let r=Cr();if(!Rl(r)){let s=await M().catch(()=>({}));return er({version:1,enabled:!0,anonymousId:wn(),userId:s.id}),(!process.env.APIFY_CLI_DISABLE_TELEMETRY||["false","0"].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))&&v({message:Nl}),me()}let t=JSON.parse(_l(r,"utf-8"));return await Ll(t)?me():t}m(me,"useTelemetryState");function er(r,e){let t={...r};e?.(t);let o=Cr(),s=Pl(o);xl(s,{recursive:!0}),kl(Cr(),JSON.stringify(t,null," "))}m(er,"updateTelemetryState");async function Ur(r){let e=await me();er(e,t=>{t.userId=r})}m(Ur,"updateUserId");var Dl=1e4;async function An(r){try{let e=await me(),t=Date.now(),o=e.lastCommand===r&&t-(e.lastCommandTimestamp??0)<Dl;return er(e,s=>{s.lastCommand=r,s.lastCommandTimestamp=t}),o}catch{return!1}}m(An,"checkAndUpdateLastCommand");async function Mr(r){let e=await me();er(e,t=>{t.enabled=r})}m(Mr,"updateTelemetryEnabled");async function vn(){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 me();return T("telemetry state",{telemetryState:r}),r.enabled}m(vn,"useTelemetryEnabled");async function bn(){let r=await me();return{anonymousId:r.anonymousId,userId:r.userId}}m(bn,"useTelemetryIdentifiers");var tr=z(),Fl="https://api.segment.io/v1/track",Ul=tr.isBeta?"rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC":"2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t";async function Sn(r,e){let t=await bn(),o={anonymousId:t.anonymousId,context:{app:{name:"apify-cli",version:tr.version,build:tr.hash},library:{name:"apify-cli",version:tr.version},os:{name:tr.platform},userAgent:st,channel:"server"},event:r,properties:{...e,app:"cli"},timestamp:new Date().toISOString(),userId:t.userId,writeKey:Ul};if(T("trackEvent",o),!await vn()){T("trackEvent","telemetry disabled");return}try{let i=await fetch(Fl,{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(Sn,"trackEvent");import{access as si,readdir as yt,readFile as td,stat as rd}from"fs/promises";import{join as j,resolve as Fn}from"path";import od from"process";import{err as sd,ok as oi}from"@sapphire/result";import{existsSync as En,readdirSync as Hl}from"fs";import{join as Gr,resolve as ql}from"path";import Jl from"configparser";import Gl from"@inquirer/input";import Vl from"is-ci";import{constants as Tn,fstat as Ml}from"fs";import Cn from"process";import{promisify as jl}from"util";var Bl=jl(Ml),ei;async function jr(){if(ei)return ei;let r=Cn.stdin,e={isTTY:r.isTTY,hasData:!1,waitDelay:0,stream:r},t=await Bl(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()}),Cn.platform==="win32"){if((o.mode&Tn.S_IFIFO)===Tn.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),ei=e,e}m(jr,"useStdin");var ti="confirm",In=`no-${ti}`;function Pe(r,{errorMessageForStdin:e=`Please use the --${ti}/--${In} flags to confirm the action.`}={}){return async(t,...o)=>{let{isTTY:s,hasData:i}=await jr(),n=t;if(Vl||!s&&!i){if(typeof n.providedConfirmFromStdin>"u")throw new Error(n.errorMessageForStdin??e??`Please use the --${ti}/--${In} flags to confirm the action.`);return n.providedConfirmFromStdin}return await r(t,...o)}}m(Pe,"stdinCheckWrapper");var it=Pe(async({message:r,validate:e,default:t})=>await Gl({message:r,validate:e,default:t}),{errorMessageForStdin:"Please provide a valid input based on the command options."});import{readFileSync as Yl}from"fs";var Br=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 Vr=class{static{m(this,"SpiderFileAnalyzer")}pathname;constructor(e){this.pathname=e}getSpiders(){let e=Yl(this.pathname,"utf8"),t=/class\s+(\w+)/g,o=[],s=t.exec(e);for(;s;)o.push(new Br({class_name:s[1],pathname:this.pathname})),s=t.exec(e);return o}};var nt=class{static{m(this,"ScrapyProjectAnalyzer")}pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return En(Gr(e,"scrapy.cfg"))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new Jl,t=ql(Gr(this.pathname,"scrapy.cfg"));if(!En(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 it({message:"Enter the Scrapy BOT_NAME (see settings.py):",default:e}),o=await it({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=Gr(this.pathname,o.replaceAll(".","/")),i=Hl(s,{withFileTypes:!0});for(let n of i)n.isFile()&&n.name.endsWith(".py")&&n.name!=="__init__.py"&&t.push(...new Vr(Gr(s,n.name)).getSpiders())}return t}};import ri from"process";import{none as Rn,some as xn}from"@sapphire/result";import{execa as kn}from"execa";import _n from"which";import{stat as Yr}from"fs/promises";import{isAbsolute as Kl,join as Hr}from"path";function Ve(r){return r?r.startsWith('"')?r:Kl(r)&&r.includes(" ")?`"${r}"`:r:null}m(Ve,"normalizeExecutablePath");async function $n(r){let e=null;return await(await Oe({cwd:r})).inspectAsync(async o=>{if(o.type===0){let[s,i,n,a]=await Promise.all([Yr(Hr(r,"yarn.lock")).then(()=>!0).catch(()=>!1),Yr(Hr(r,"pnpm-lock.yaml")).then(()=>!0).catch(()=>!1),Yr(Hr(r,"bun.lockb")).then(()=>!0).catch(()=>!1),Yr(Hr(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($n,"getInstallCommandSuggestion");var qr=new Map,Wl={node:["--version"],deno:["eval",'"console.log(process.versions.node)"'],bun:["--eval",'"console.log(process.versions.node)"']};async function zl(r,e){try{let t=await kn(r,e,{shell:!0,windowsHide:!0,verbose:ri.env.APIFY_CLI_DEBUG?"full":void 0});return t.stdout?t.stdout.trim().replace(/^v/,""):null}catch{return null}}m(zl,"getRuntimeVersion");async function Xl(r){let e=await kn(r,["--version"],{shell:!0,windowsHide:!0,verbose:ri.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim().replace(/^v/,""):null}m(Xl,"getNpmVersion");async function Pn(r=ri.cwd()){let e=qr.get(r);if(e)return T("useJavaScriptRuntime",{cacheHit:!0,cwd:r,runtime:e.unwrapOr(null)}),e;for(let[t,o]of Object.entries(Wl))try{let s=Ve(await _n(t)),i=await zl(s,o);if(i){let n={executablePath:s,version:i};if(t==="node"){let a=Ve(await _n("npm").catch(()=>null));a&&(n.pmPath=a,n.pmVersion=await Xl(a),n.pmName="npm")}else n.runtimeShorthand=t,n.pmPath=s,n.pmVersion=i,n.pmName=t;return qr.set(r,xn(n)),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:qr.get(r)?.unwrap()}),xn(n)}}catch{}return qr.set(r,Rn),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:null}),Rn}m(Pn,"useJavaScriptRuntime");import{platform as Zl}from"os";import{join as On}from"path";import Jr from"process";import{none as Nn,some as Ln}from"@sapphire/result";import{execa as Ql}from"execa";import ed from"which";var Ge=new Map;async function Dn(r){try{let e=await Ql(r,["-c",'"import platform; print(platform.python_version())"'],{shell:!0,windowsHide:!0,verbose:Jr.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim():null}catch{return null}}m(Dn,"getPythonVersion");async function or({cwd:r=Jr.cwd(),force:e=!1}={}){let t=Ge.get(r);if(t&&!e)return T("usePythonRuntime",{cacheHit:!0,cwd:r,runtime:t.unwrapOr(null)}),t;let o=Zl()==="win32",s=o?["Scripts","python.exe"]:["bin","python3"],i;Jr.env.VIRTUAL_ENV?i=On(Jr.env.VIRTUAL_ENV,...s):i=On(r,".venv",...s),i=Ve(i);try{let a=await Dn(i);if(a)return Ge.set(r,Ln({executablePath:i,version:a})),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ge.get(r)?.unwrap()}),Ge.get(r)}catch{}let n=["python3","python",...o?["python3.exe","python.exe"]:[]];for(let a of n)try{let c=Ve(await ed(a)),d=await Dn(c);if(d)return Ge.set(r,Ln({executablePath:c,version:d})),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ge.get(r)?.unwrap()}),Ge.get(r)}catch{}return Ge.set(r,Nn),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:null}),Nn}m(or,"usePythonRuntime");var Un=new Map;async function Oe({cwd:r=od.cwd()}={}){let e=Un.get(r);if(e)return T("useCwdProject",{cacheHit:!0,project:e}),oi(e);let t={type:3},s=await m(async()=>{if(await ld(r)){t.type=2;let a=await or({cwd:r});t.runtime=a.unwrapOr(void 0);let c=new nt(r);if(c.loadScrapyCfg(),c.configuration.hasKey("apify","mainpy_location"))t.entrypoint={path:c.configuration.get("apify","mainpy_location")};else try{let d=await Bn(r);d&&(t.entrypoint={path:d})}catch{}return}let n=await id(r);if(!n){let a=null;try{a=await Bn(r)}catch(c){return sd({message:c instanceof Error?c.message:String(c)})}if(a){t.type=1;let c=await or({cwd:r});t.entrypoint={path:a},t.runtime=c.unwrapOr(void 0);let d=j(r,a.replace(/\./g,"/"));await sr(j(d,"__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 Pn();t.runtime=a.unwrapOr(void 0),n.type==="file"?t.entrypoint={path:n.path}:n.type==="script"&&(t.entrypoint={script:n.script});return}return oi(t)},"check")();return s?.isErr()?(T("useCwdProject",{cacheHit:!1,error:s}),s):(T("useCwdProject",{cacheHit:!1,project:t}),Un.set(r,t),oi(t))}m(Oe,"useCwdProject");async function id(r){let e=j(r,"package.json");try{let o=await td(e,"utf-8"),s=JSON.parse(o);if(s.scripts?.start)return{type:"script",script:"start"};if(s.main)try{return await si(Fn(r,s.main)),{path:Fn(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 si(o),{path:o,type:"file"}}catch{}return null}m(id,"checkNodeProject");async function sr(r){try{return await si(r),!0}catch{return!1}}m(sr,"fileExists");async function Vn(r){try{return(await rd(r)).isDirectory()}catch{return!1}}m(Vn,"dirExists");function Gn(r){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)}m(Gn,"isValidPythonIdentifier");async function nd(r){try{let e=await yt(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 yt(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 yt(j(o,i.name),{withFileTypes:!0})).some(a=>a.isFile()&&a.name.endsWith(".py")))return!0}catch{}}}catch{}}return!1}catch{return!1}}m(nd,"hasPythonFilesInDirOrSubdirs");async function ad(r){try{return(await yt(r,{withFileTypes:!0})).some(t=>t.isFile()&&t.name.endsWith(".py")&&t.name!=="__init__.py")}catch{return!1}}m(ad,"dirHasPyFiles");async function Mn(r){try{let e=await yt(r,{withFileTypes:!0}),t=[];for(let o of e){if(!o.isDirectory()||o.name.startsWith(".")||o.name.startsWith("_"))continue;let s=Gn(o.name),i=await sr(j(r,o.name,"__init__.py")),n=i||await ad(j(r,o.name));s&&i||n&&t.push({name:o.name,needsRename:!s,needsInit:!i})}return t}catch{return[]}}m(Mn,"findNearMissPackagesInDir");async function jn(r){try{let e=await yt(r,{withFileTypes:!0}),t=[];for(let o of e){if(!o.isDirectory())continue;let{name:s}=o;if(s.startsWith(".")||s.startsWith("_")||!Gn(s))continue;let i=j(r,s,"__init__.py");await sr(i)&&t.push({name:s,path:j(r,s)})}return t}catch{return[]}}m(jn,"findPackagesInDir");async function cd(r){let e=[],t=await jn(r);e.push(...t.map(i=>i.name));let o=j(r,"src"),s=await sr(j(o,"__init__.py"));if(await Vn(o)&&!s){let i=await jn(o);e.push(...i.map(n=>`src.${n.name}`))}return e}m(cd,"discoverPythonPackages");async function Bn(r){let e=await cd(r);if(e.length===1)return e[0];if(e.length>1){let c=e.map(d=>` - ${d}`).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 Mn(r),o=j(r,"src"),i=!await sr(j(o,"__init__.py"))&&await Vn(o)?await Mn(o):[],n=[...t.map(c=>({...c,prefix:""})),...i.map(c=>({...c,prefix:"src/"}))];if(n.length>0){let c=n.map(({name:d,prefix:l,needsRename:u,needsInit:p})=>{let g=[];return u&&g.push(`rename to "${l}${d.replace(/[^a-zA-Z0-9_]/g,"_")}/"`),p&&g.push("add __init__.py"),` - "${l}${d}/" \u2192 ${g.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 nd(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(Bn,"checkPythonProject");async function ld(r){return nt.isApplicable(r)}m(ld,"checkScrapyProject");import K from"chalk";import at from"chalk";import Jn from"indent-string";import gd from"widest-line";import Kn from"wrap-ansi";import Kr from"chalk";import ai from"indent-string";import dd from"string-width";import Hn from"strip-ansi";import qn from"widest-line";import ci from"wrap-ansi";import ht from"chalk";import ii from"indent-string";import Yn from"string-width";import ni from"wrap-ansi";var Ye;function se(){if(Ye)return Ye;let r=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(r))Ye=r;else if(!process.stdout.isTTY)Ye=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;e<1?Ye=80:e<40?Ye=40:Ye=e}return Ye}m(se,"getMaxLineWidth");var wt=class{static{m(this,"BaseCommandRenderer")}command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let t=this.command.interactive?`${ht.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(ht.bold("DESCRIPTION"));let t=ni(this.command.description,se()-2,{trim:!1}),o=ii(t,2);e.push(o),e.push("")}pushExamples(e){let{examples:t}=this.command;if(t?.length){e.push(ht.bold("EXAMPLES"));for(let o of t){if(o.description){let i=ni(o.description,se()-4,{trim:!1}).split(`
36
+ `).map(a=>`# ${a}`).join(`
37
+ `),n=ii(i,2);e.push(ht.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(ht.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=ni(o,se()-2,{trim:!1}),i=ii(s,2);e.push(i),e.push("")}pushLearnMore(e){this.command.docsUrl&&(e.push(ht.bold("LEARN MORE")),e.push(` ${this.command.docsUrl}`),e.push(""))}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:o}){let s=Yn(e.join(" ").split(`
38
+ `).at(-1)||"")+o,i=Yn(t);s+i>se()&&e.push(`
39
+ `),e.push(t)}kebabFlagName(e){return Ie(Ee(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 Wr=class extends wt{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(Kr.bold("USAGE"));let t=`$ ${this.entrypoint} ${this.command.name}`,o=2+dd(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 g=p.required,b=[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);b.push(C),E.required&&(g=!0)}this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:g?b.join(" | "):`[${b.join(" | ")}]`,indentSize:o})}let d=ci(s.join(" "),se()-o),l=ai(d,o+1).trim();e.push(` ${l}`,""),i.length&&this.pushArguments(e,i),n.length&&this.pushFlags(e,a)}pushArguments(e,t){if(!t.length)return;e.push(Kr.bold("ARGUMENTS"));let o=qn(t.map(([s])=>s).join(`
42
+ `));for(let[s,i]of t){let n=`${s.padEnd(o)} ${i.description}`,a=ci(n,se()-o-2),c=ai(a,o+2+2).trim();e.push(` ${c}`)}e.push("")}pushFlags(e,t){if(!t.size)return;e.push(Kr.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)}=${Kr.underline(c)}`);break}default:throw new Error(`Unhandled flag tag: ${n.flagTag}`)}o.set(a.join(" "),n)}let s=qn([...o.keys()].map(Hn).join(`
43
+ `));for(let[i,n]of o){let a=s-Hn(i).length,c=`${i}${" ".repeat(a)} ${n.description??""}`;n.choices?.length&&(c+=`
44
+ <options: ${n.choices.join("|")}>`);let d=ci(c,se()-s),l=ai(d,s).trim().split(`
45
+ `).map(u=>/^-[a-z]/.test(u.trim())?u:` ${u}`).join(`
46
+ `);e.push(` ${l}`)}e.push("")}};import md from"chalk";import ud from"indent-string";import pd from"widest-line";import fd from"wrap-ansi";var zr=class extends wt{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(md.bold("SUBCOMMANDS"));let t=pd(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=fd(i,se()-t-2),a=ud(n,t+2+2).trim();e.push(` ${a}`)}e.push("")}};var ir=new Map;function li(r,e){if(e.name.toLowerCase()!==e.name){f({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){ir.set(e,new zr(r,e));for(let t of e.subcommands)li(`${r} ${e.name}`,t)}else ir.set(e,new Wr(r,e))}m(li,"registerCommandForHelpGeneration");function Zr(r){let e=ir.get(r);if(!e)throw new Error(`No help renderer found for command ${r.name}`);return e.render()}m(Zr,"renderHelpForCommand");function Qr(r,e){let t=ir.get(r);if(!t)throw new Error(`No help renderer found for command ${r.name}`);return t.selectiveRender(e)}m(Qr,"selectiveRenderHelpForCommand");function yd(r,e){return r[0].name.localeCompare(e[0].name)}m(yd,"sortByName");var Wn=["Local Actor Development","Apify Console","Authentication","Utilities"],Xr="Other",hd=[{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"'}],wd=[{command:"actor get-input"},{command:`actor push-data '{"url":"https://example.com"}'`},{command:`actor set-value OUTPUT '{"done":true}'`}];function eo(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(at.bold("VERSION")),t.push(` ${e.fullVersionString}`),t.push(""),t.push(at.bold("USAGE")),t.push(` $ ${r} <command> [options]`),t.push("");let o=[];for(let[u,p]of ir)p.entrypoint.includes(" ")||u.hidden||o.push([u,p]);let s=new Map;for(let u of o){let[p]=u,g=p.group||Xr;s.has(g)||s.set(g,[]),s.get(g).push(u)}for(let u of s.values())u.sort(yd);let i=[];for(let u of Wn)s.has(u)&&i.push(u);let n=[...s.keys()].filter(u=>!Wn.includes(u)&&u!==Xr).sort();i.push(...n),s.has(Xr)&&i.push(Xr);let a=o.map(([u])=>u.name).join(`
51
+ `),c=gd(a)||1,d=m(([u])=>{let p=u.shortDescription||u.description?.split(`
52
+ `)[0]||"",h=`${u.name.padEnd(c)} ${p}`,b=Kn(h,se()-c-4);return` ${Jn(b,c+2+2).trim()}`},"renderEntry");for(let u of i){let p=s.get(u);p.length&&(t.push(at.bold(u.toUpperCase())),t.push(...p.map(d),""))}let l=r==="actor"?wd:hd;if(l.length){t.push(at.bold("EXAMPLES"));for(let u=0;u<l.length;u++){let p=l[u];if(p.description){u>0&&t.push("");let h=Kn(p.description,se()-4,{trim:!1}).split(`
53
+ `).map(b=>`# ${b}`).join(`
54
+ `);t.push(at.dim(Jn(h,2)))}t.push(` $ ${p.command}`),p.description&&u<l.length-1&&t.push("")}t.push("")}return t.push(at.bold("LEARN MORE"),` Use '${r} <command> --help' for more information about a command.`," Read the docs at https://docs.apify.com/cli.",""),t.push(at.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(eo,"renderMainHelpMenu");var to=(l=>(l[l.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]="NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE",l[l.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]="NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL",l[l.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]="NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION",l[l.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]="APIFY_FLAG_PROVIDED_MULTIPLE_TIMES",l[l.APIFY_INVALID_FLAG_INTEGER_VALUE=4]="APIFY_INVALID_FLAG_INTEGER_VALUE",l[l.APIFY_INVALID_CHOICE=5]="APIFY_INVALID_CHOICE",l[l.APIFY_MISSING_FLAG=6]="APIFY_MISSING_FLAG",l[l.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]="APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG",l[l.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]="APIFY_TOO_MANY_REQUESTERS_OF_STDIN",l[l.APIFY_UNKNOWN_ERROR=9]="APIFY_UNKNOWN_ERROR",l))(to||{}),ue=class r extends Error{static{m(this,"CommandError")}code;command;metadata;constructor({code:e,message:t="",metadata:o={},command:s}){super(t||String(to[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=Qr(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} (${to[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? ${$e?"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 zn(r){return r.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}m(zn,"camelCaseString");function Ie(r){return r.replace(/[\s_]+/g,"-")}m(Ie,"kebabCaseString");function Ee(r){return r.replace(/([A-Z])/g,"-$1").toLowerCase()}m(Ee,"camelCaseToKebabCase");var Sd={type:"boolean",multiple:!1,short:"h"},Td={type:"boolean",multiple:!1},W=new Map,Cd=["init","run","push","actors push","pull","actors pull","call","actors call","actors start"],y=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=Gi();this.telemetryData.aiAgent=Vi(),this.telemetryData.isCi=n.isCi,this.telemetryData.ciProvider=n.ciProvider,this.telemetryData.isInteractive=Yi()}get ctor(){return this.constructor}pluralString(e,t,o){return e===1?t:o}static printHelp(){console.log(Zr(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,d]of Object.entries(this.ctor.args)){if(typeof d=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let l=zn(c),u=s[a++];if(u)switch(d.argTag){default:this.args[l]=String(u),u==="-"&&d.stdin&&(this.args[l]=this._handleStdin(d.stdin)),d.catchAll&&(this.args[l]=s.slice(a-1).join(" "));break}else d.required&&n.set(c,d)}}if(n.size){process.exitCode=1,this._printMissingRequiredArgs(n);return}this._parseFlags(o,i);try{await this.run()}catch(a){f({message:a.message}),process.exitCode||=1}finally{!this.telemetryData.actorLanguage&&Cd.includes(this.commandString)&&(await Oe()).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 An(this.commandString),await Sn(`cli_command_${this.commandString.replaceAll(" ","_").toLowerCase()}`,this.telemetryData))}}_userFlagNameToRegisteredName(e,t){let o=Ie(Ee(e)).toLowerCase(),s=o;o.startsWith("no-")&&(s=o.slice(3));let i=new Set;for(let n of t.aliases??[])i.add(Ie(Ee(n)).toLowerCase());return{baseFlagName:s,rawBaseFlagName:o,allMatchers:[s,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=Ie(Ee(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:d,rawBaseFlagName:l}=this._userFlagNameToRegisteredName(n,a),u=zn(l),p=t.some(b=>b.kind==="option"&&b.name===d);if(a.exclusive?.length){let b=o.get(d)??new Set;for(let S of a.exclusive)b.add(this._commandFlagKeyToKebabCaseRegisteredName(S));o.set(d,b);for(let S of a.exclusive){let E=this._commandFlagKeyToKebabCaseRegisteredName(S),C=o.get(E)??new Set;C.add(d),o.set(E,C)}}let g=c.filter(b=>e[b]);if(g.length>1)throw new ue({code:3,command:this.ctor,metadata:{flag:d}});let h=e[g[0]];if(!h&&a.required)throw new ue({code:6,command:this.ctor,metadata:{flag:d,matcher:g[0]}});if(Array.isArray(h)){if(h.length>1)throw new ue({code:3,command:this.ctor,metadata:{flag:d}});h=h[0]}if(p&&typeof h=="string"&&h.startsWith("=")&&(h=h.slice(1)),typeof h<"u")switch(a.flagTag){case"boolean":{this.flags[u]=l.startsWith("no-")?!h:h;break}case"integer":{let b=Number(h);if(Number.isNaN(b)||!Number.isInteger(b))throw new ue({code:4,command:this.ctor,metadata:{flag:d,value:String(h)}});this.flags[u]=b;break}default:{if(this.flags[u]=h,h==="-"&&a.stdin){if(s)throw new ue({code:8,command:this.ctor,metadata:{firstUse:s,secondUse:d}});s=d,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 ue({code:5,command:this.ctor,metadata:{flag:d,choices:a.choices.map(b=>di.white.bold(b)).join(", ")}});if(this.flags[u]==null&&(a.required||h!=null))throw new ue({code:6,command:this.ctor,metadata:{flag:d,matcher:g[0],providedButReceivedNoValue:!!h}})}let i=[];for(let[n,a]of o)if(e[n]!=null)for(let c of a){if(e[c]==null)continue;let d=e[n][0],l=e[c][0],u=m((p,g)=>typeof g=="boolean"?g?`--${p}`:`--no-${p}`:`--${p}=${g}`,"flagRepresentation");i.push([u(n,d),u(c,l)]);break}if(i.length)throw new ue({code:7,command:this.ctor,metadata:{flagPairs:i}})}_printMissingRequiredArgs(e){let t;try{t=Qr(this.ctor,{showUsageString:!0})}catch{}let o=vd([...e.keys()].join(`
67
+ `)),s=[];for(let[n,a]of e){let c=`${n.padEnd(o)} ${a.description}`,d=bd(c,se()-o-2),l=Ad(d,o+2+2).trim();s.push(` ${di.red(">")} ${l}`)}let i=[`Missing ${e.size} required ${this.pluralString(e.size,"argument","arguments")}:`,...s,di.gray(" See more help with --help")];t&&i.push("",t),f({message:i.join(`
68
+ `)})}_handleStdin(e){return e===2?($e?.toString("utf8")??"").trim():$e}_buildParseArgsOption(){let e={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:{help:Sd}};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=Ie(Ee(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=Td),e}static registerCommand(e){if(li(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 Xn(r,e,t){let o={positionals:[],values:{},tokens:[]},s=0;for(let[n,a]of Object.entries(t)){let[c,d]=n.split("_");if(c==="args")o.positionals[s++]=a;else{let l=Ie(Ee(d)).toLowerCase();l.startsWith("no-")?o.values[l.slice(3)]=!a:o.values[l]=a}}let i=new e(r,e.name,e.name);i.skipTelemetry=!0,await i._run(o)}m(Xn,"internalRunCommand");import{once as Id}from"events";async function Zn(){let r=await jr(),{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 Id(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(Zn,"readStdin");import{gt as Od}from"semver";import{existsSync as Ed,mkdirSync as $d,readFileSync as Rd,writeFileSync as xd}from"fs";import{dirname as _d}from"path";function kd(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}}}),ui({version:1},s=>{s.versionCheck={lastChecked:t,lastVersion:o}})}return!0}m(kd,"migrateStateV0ToV1");var Pd={version:1};function mi(){let r=Tr();if(!Ed(r))return Pd;let t=JSON.parse(Rd(r,"utf-8"));return kd(t)?mi():t}m(mi,"useLocalState");function ui(r,e){let t={...r};e(t);let o=Tr(),s=_d(o);$d(s,{recursive:!0}),xd(Tr(),JSON.stringify(t,null," "))}m(ui,"updateLocalState");var ro=z(),Qn=`Apify CLI/${ro.version} (https://github.com/apify/apify-cli)`,Nd=["https://1.1.1.1","https://8.8.8.8"];async function Ld(r=500){let e=new AbortController,t=setTimeout(()=>{e.abort()},r),o=await Promise.any(Nd.map(async s=>fetch(s,{signal:e.signal,headers:{"User-Agent":Qn},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(Ld,"isOnline");async function Dd(r){let e=await fetch("https://api.github.com/repos/apify/apify-cli/releases/latest",{headers:{"User-Agent":Qn}});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}),ui(r,s=>{s.versionCheck={lastChecked:Date.now(),lastVersion:o}}),o}m(Dd,"getLatestVersion");function ea(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&!["0","false"].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}m(ea,"shouldSkipVersionCheck");async function ta(r=!1){let e=mi(),t=!e.versionCheck||Date.now()-e.versionCheck.lastChecked>qi,o=r||t&&await Ld(),s=o?await Dd(e):e.versionCheck?.lastVersion;if(!s)return{currentVersion:ro.version,latestVersion:"unknown",shouldUpdate:!1,cacheHit:!1};let i=Od(s,ro.version);return{currentVersion:ro.version,latestVersion:s,shouldUpdate:i,cacheHit:!o}}m(ta,"useCLIVersionCheck");import{jaroWinkler as Fd}from"@skyra/jaro-winkler";import Ud from"js-levenshtein";function oo(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(),d=i.aliases?.includes(c)||i.hiddenAliases?.includes(c)||!1,l=Ud(t,n),u=Fd(t,n),p=l<=2||u>=.975;return p?(T("useCommandSuggestions",{inputString:t,lowercased:n,matches:p,levenshtein:l,jaroWinkler:u}),d?{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(oo,"useCommandSuggestions");var $e=await Zn(),nr=z(),st=`Apify CLI/${nr.version} (https://github.com/apify/apify-cli)`;function dw(r){nr.installMethod!=="bundle"&&(Md(Re.version,Te)||(f({message:`${r} CLI requires Node.js version ${Te}. Your current version is ${Re.version}.`}),Re.exit(1)))}m(dw,"processVersionCheck");function jd(r){r.values.version===!0&&r.positionals.length===0&&(console.log(nr.fullVersionString),Re.exit(0))}m(jd,"printCLIVersionAndExitIfFlagUsed");function Bd(r,e){(r.values.help===!0&&r.positionals.length===0||r.positionals.length===0)&&(console.log(eo(e)),Re.exit(0))}m(Bd,"printHelpAndExitIfFlagUsedOrNoCommandPassed");function oa(r){let e=oo(String(r)),t=so.gray(`Command ${so.whiteBright(r)} not found`);e.length&&(t+=`
69
+ `,t+=so.gray(`Did you mean: ${e.map(o=>so.whiteBright(o)).join(", ")}?`)),f({message:t}),Re.exit(1)}m(oa,"handleCommandNotFound");async function Vd(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(ea()){T("[VersionCheckMiddleware]","skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set");return}await Xn(r,t,{flags_internalAutomaticCall:!0})}m(Vd,"runVersionCheck");async function mw(r){T("CLIMetadata",{...nr,fullVersionString:nr.fullVersionString,argv:Re.argv,cwd:Re.cwd(),execPath:Re.execPath});let e=Re.argv.slice(2);T("ProcessArgv",e);let t=ra({allowPositionals:!0,strict:!1,options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}},args:e});jd(t),Bd(t,r),await Vd(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 h=W.get(`${o} ${t.positionals[1]}`);h&&!h.args&&(s=2)}}if(s!==-1){let h=t.positionals[s],b=e.indexOf(h);b!==-1&&e.splice(b,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 oa(o);let d=c;if(c.subcommands?.length){if(!n)return c.printHelp();a=!0,d=W.get(`${o} ${n}`)}if(!d)return oa(`${o} ${n}`);let l=[...e],u=l.indexOf(o);if(T("CommandNameIndex",u),l.splice(u,1),a){let h=l.indexOf(n);T("SubcommandNameIndex",h),l.splice(h,1)}T("RebuiltArgs",l),T("CommandToRun",d);let p=new d(r,a?`${c.name} ${n}`:c.name,o,a?n:void 0),g=p._buildParseArgsOption();T("ParserOptionsForCommand",g);try{let h=ra({...g,args:l});await p._run(h),T("CommandArgsResult",h)}catch(h){let b=ue.into(h,d);f({message:b.getPrettyMessage()}),Re.exit(1)}}m(mw,"runCLI");import{join as am,resolve as cm}from"path";import fi from"process";import{calculateRunDynamicMemory as lm}from"@apify/actor-memory-expression";var w={string:Gd,boolean:Yd,integer:Hd};function Gd(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:Ie(Ee(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(Gd,"stringFlag");function Yd(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:Ie(Ee(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(Yd,"booleanFlag");function Hd(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:Ie(Ee(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(Hd,"integerFlag");import{mkdir as Xd,rename as ca,writeFile as Zd}from"fs/promises";import{dirname as Qd,join as em}from"path";import aa from"process";import{inspect as tm}from"util";import{err as ar,ok as ao}from"@sapphire/result";import{createPrompt as qd,isEnterKey as Jd,makeTheme as Kd,useKeypress as Wd,usePrefix as zd,useState as sa}from"@inquirer/core";function pi(r,e){let t=e!==!1;return/^(y|yes)/i.test(r)?t=!0:/^(n|no)/i.test(r)&&(t=!1),t}m(pi,"getBooleanValue");function ia(r){return r?"Yes":"No"}m(ia,"boolToString");var na=qd((r,e)=>{let t=ia,[o,s]=sa("idle"),[i,n]=sa(""),a=Kd(),c=zd({status:o,theme:a});Wd((p,g)=>{if(Jd(p)){let h=pi(i,r.default);n(t(h)),s("done"),e(h);return}if(p.name==="tab"){let h=ia(!pi(i,r.default));g.clearLine(0),g.write(h),n(h);return}if(p.name==="y"||p.name==="n"){let h=pi(p.name,r.default);n(t(h)),s("done"),e(h);return}g.clearLine(0),g.write(i),n(g.line)});let d=i,l="";o==="done"?d=a.style.answer(i):l=` ${a.style.defaultAnswer(r.default===!1?"y/N":"Y/n")}`;let u=a.style.message(r.message,o);return`${c} ${u}${l} ${d}`});var Z=Pe(async({message:r,default:e})=>await na({message:r,default:e}));var rm=m(r=>em(r,Ir),"getDeprecatedLocalConfigPath"),no=new Map;async function Ne({cwd:r=aa.cwd(),migrateConfig:e=!0,warnAboutOldConfig:t=!0}={cwd:aa.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let o=no.get(r);if(o)return T("useActorConfig",{cacheHit:!0,config:o}),ao(o);let s=Zs(r),i=rm(r),n,a;try{n=le(s)}catch(d){return ar({message:`Failed to read local config at path: '${s}':`,cause:d,exists:!1,config:{}})}try{a=le(i)}catch(d){return ar({message:`Failed to read local config at path: '${i}':`,cause:d,exists:!1,config:{}})}if(n&&a&&t&&await om(i),!n&&!a)return no.set(r,{exists:!1,migrated:!1,config:{}}),ao({exists:!1,migrated:!1,config:{}});let c=!1;if(!n&&a&&e){let d=await im(a,i,s);if(d.isErr())return ar(d.unwrapErr());n=d.unwrap(),c=!0}return no.set(r,{exists:!0,migrated:c,config:n||a||{}}),T("useActorConfig",{cacheHit:!1,config:no.get(r)}),ao({exists:!0,migrated:c,config:n||a||{}})}m(Ne,"useActorConfig");async function om(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 ca(r,`${r}.deprecated`),v({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?f({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
70
+ ${t.message||t}`}):f({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
71
+ ${tm(t,{showHidden:!1})}`})}}m(om,"handleBothConfigVersionsFound");var sm=["name","version","buildTag"];async function im(r,e,t){let o={...r};if(typeof o.version=="object"&&(o=nm(o)),o={actorSpecification:Ys,environmentVariables:r?.env||void 0,...sm.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 ar({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 Xd(Qd(t),{recursive:!0}),await Zd(t,JSON.stringify(o,null," "))}catch(i){let n=i;return ar({message:`Failed to write the new "actor.json" file to path: '${t}'.
72
+ ${n.message||n}`,exists:!0,config:o})}try{await ca(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 v({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.'}),ao(o)}m(im,"handleMigrationFlow");function nm(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(nm,"updateLocalConfigStructure");var dm=am(ge("default"),"INPUT.json"),At=class extends y{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:dm}),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=cm(fi.cwd(),e),a=le(n)??{};v({message:`Evaluating memory expression: ${t}`});try{let c=await lm(t,{input:a,runOptions:i}),d=Math.min(Math.max(c,o),s);$({message:`Calculated memory: ${d} MB`,stdout:!0})}catch(c){f({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=fi.cwd(),t=await Ne({cwd:e});if(t.isErr()){let{message:s,cause:i}=t.unwrapErr();return f({message:`${s}${i?`
74
+ ${i.message}`:""}`}),fi.exitCode=5,{}}let{config:o}=t.unwrap();return{defaultMemoryMbytes:o?.defaultMemoryMbytes?.toString(),minMemoryMbytes:o?.minMemoryMbytes,maxMemoryMbytes:o?.maxMemoryMbytes}}};import{APIFY_ENV_VARS as hm}from"@apify/consts";import cr from"process";import{pipeline as mm}from"stream/promises";import{MemoryStorage as um}from"@crawlee/memory-storage";import{ApifyClient as pm}from"apify-client";import{ACTOR_ENV_VARS as la,APIFY_ENV_VARS as da,KEY_VALUE_STORE_KEYS as fm,LOCAL_ACTOR_ENV_VARS as gm}from"@apify/consts";var lr={KEY_VALUE_STORE:"KEY_VALUE_STORE",DATASET:"DATASET",REQUEST_QUEUE:"REQUEST_QUEUE"},gi=m(async()=>{let r=cr.env[da.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"),ct=m(async(r={},e=Reflect.has(cr.env,da.IS_AT_HOME))=>{let t=ye();if(t&&!e)return new um({localDataDirectory:t,...r});let o=await gi();return new pm({...Kt(o),...r})},"getApifyStorageClient"),dr=m(r=>{let e=la[`DEFAULT_${r}_ID`];return cr.env[e]||gm[e]},"getDefaultStorageId"),yi=m(async r=>{let e=await ct(),t=dr(lr.KEY_VALUE_STORE),o=await e.keyValueStore(t).getRecord(r,{stream:!0});o&&await mm(o.value,cr.stdout,{end:!1})},"outputRecordFromDefaultStore"),ma=m(async()=>yi(cr.env[la.INPUT_KEY]||fm.INPUT),"outputInputFromDefaultStore");function ym(r){return{argTag:"string",required:r.required??!1,stdin:r.stdin??1,description:r.description,aliases:r.aliases,catchAll:r.catchAll??!1}}m(ym,"stringArg");var A={string:ym};var vt=class extends y{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){v({message:`No platform detected: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}if(o){v({message:`PPE test mode: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}let n=await gi(),a=await Wt(n);if(!a)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN.");let c=process.env[hm.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.");v({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 Sm,writeFile as uo}from"fs/promises";import Ct from"path";import ba from"process";import{compile as po}from"json-schema-to-typescript";import{existsSync as wm,writeFileSync as Am}from"fs";import{join as mr}from"path";import{cloneDeep as vm}from"es-toolkit";import{KEY_VALUE_STORE_KEYS as bm}from"@apify/consts";import{validateInputSchema as pa}from"@apify/input_schema";var ua=[".actor/INPUT_SCHEMA.json","./INPUT_SCHEMA.json",".actor/input_schema.json","./input_schema.json"],bt=m(async({forcePath:r,cwd:e})=>{if(r)return{inputSchema:le(r),inputSchemaPath:r};let t=Ue(e);if(typeof t?.input=="object")return{inputSchema:t.input,inputSchemaPath:null};if(typeof t?.input=="string"){let o=mr(e,Er,t.input);return{inputSchema:le(o),inputSchemaPath:o}}for(let o of ua){let s=mr(e,o);if(wm(s))return{inputSchema:le(s),inputSchemaPath:s}}return{inputSchema:null,inputSchemaPath:mr(e,ua[0])}},"readInputSchema"),co=m(async({forcePath:r,cwd:e,getMessage:t})=>{let{inputSchema:o,inputSchemaPath:s}=await bt({forcePath:r,cwd:e});if(!o)throw new Error(`Input schema has not been found at ${s}.`);v({message:t(s)});let i=new Jt({strict:!1});return pa(i,o),{inputSchema:o,inputSchemaPath:s}},"readAndValidateInputSchema"),lo=m(({cwd:r,key:e,label:t,getRef:o})=>{let s=Ue(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=mr(r,Er,i),a=le(n);return a?{schema:a,schemaPath:n}:(x({message:`${t} schema file not found at ${n} (referenced in '${D}').`}),null)}return null},"readStorageSchema"),fa=m(({cwd:r})=>{let e=lo({cwd:r,key:"dataset",label:"Dataset"});return e?{datasetSchema:e.schema,datasetSchemaPath:e.schemaPath}:null},"readDatasetSchema"),ga=m(({cwd:r})=>{let e=lo({cwd:r,key:"output",label:"Output",getRef:m(t=>t?.output,"getRef")});return e?{outputSchema:e.schema,outputSchemaPath:e.schemaPath}:null},"readOutputSchema"),mo=m(async r=>{let e={};try{let{inputSchema:t}=await bt({cwd:r});if(t){let o=new Jt({strict:!1});pa(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=ge(),o=mr(r,t,`${bm.INPUT}.json`);Am(o,JSON.stringify(e,null," "))}},"createPrefilledInputFileFromInputSchema"),ya=m(r=>{let e={};for(let[t,o]of Object.entries(r.properties))o.default!==void 0&&(e[t]=o.default);return e},"getDefaultsFromInputSchema"),ha=m((r,e)=>{let t=vm(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 St}from"es-toolkit";function hi(r){let e=St(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]=hi(i));return e.required=Array.from(o),e}m(hi,"makePropertiesRequired");function Tt(r){let e=St(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]=Tt(s))}return e}m(Tt,"clearAllRequired");function he(r){let e=St(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]=he(s))}e.items&&typeof e.items=="object"&&(e.items=he(e.items));for(let t of["allOf","anyOf","oneOf"])Array.isArray(e[t])&&(e[t]=e[t].map(o=>o&&typeof o=="object"?he(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]=he(i))}e.additionalProperties&&typeof e.additionalProperties=="object"&&(e.additionalProperties=he(e.additionalProperties));for(let t of["if","then","else","not"])e[t]&&typeof e[t]=="object"&&(e[t]=he(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]=he(s))}return e}m(he,"stripTitles");function wa(r){let e=r.fields;if(!e||typeof e!="object"||!e.properties||typeof e.properties!="object")return null;let t=St(e);return t.type||(t.type="object"),t}m(wa,"prepareFieldsSchemaForCompilation");function Aa(r){let e=r.properties;if(!e||typeof e!="object"||Object.keys(e).length===0)return null;let t=St(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(Aa,"prepareOutputSchemaForCompilation");function va(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=St(i);n.type||(n.type="object"),t.push({name:o,schema:n})}return t}m(va,"prepareKvsCollectionsForCompilation");var Tm=`
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
+ `,It=class extends y{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:Ct.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=ba.cwd(),{inputSchema:t}=await co({forcePath:this.args.path,cwd:e,getMessage:m(d=>d?`Generating types from input schema at ${d}`:`Generating types from input schema embedded in '${D}'`,"getMessage")}),o="input",s=this.flags.allOptional?Tt(t):hi(t),i={bannerComment:Tm,maxItems:-1,unknownAny:!0,format:!0,additionalProperties:!this.flags.strict,$refOptions:{resolve:{external:!1,file:!1,http:!1}}},n=await po(he(s),o,i),a=Ct.resolve(e,this.flags.output);await Sm(a,{recursive:!0});let c=Ct.join(a,`${o}.ts`);if(await uo(c,n,"utf-8"),$({message:`Generated types written to ${c}`}),!this.args.path){let d=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})]),l=["Dataset","Output","Key-Value Store"],u=!1;for(let[p,g]of d.entries())g.status==="rejected"&&(u=!0,f({message:`Failed to generate types for ${l[p]} schema: ${g.reason instanceof Error?g.reason.message:String(g.reason)}`}));u&&(ba.exitCode=1)}}async generateDatasetTypes({cwd:e,outputDir:t,compileOptions:o}){let s=fa({cwd:e});if(!s)return;let{datasetSchema:i,datasetSchemaPath:n}=s;n?v({message:`[experimental] Generating types from Dataset schema at ${n}`}):v({message:`[experimental] Generating types from Dataset schema embedded in '${D}'`});let a=wa(i);if(!a){x({message:"Dataset schema has no fields defined, skipping type generation."});return}let c="dataset",d=this.flags.allOptional?Tt(a):a,l=await po(he(d),c,o),u=Ct.join(t,`${c}.ts`);await uo(u,l,"utf-8"),$({message:`Generated types written to ${u}`})}async generateOutputTypes({cwd:e,outputDir:t,compileOptions:o}){let s=ga({cwd:e});if(!s)return;let{outputSchema:i,outputSchemaPath:n}=s;n?v({message:`[experimental] Generating types from Output schema at ${n}`}):v({message:`[experimental] Generating types from Output schema embedded in '${D}'`});let a=Aa(i);if(!a){x({message:"Output schema has no properties defined, skipping type generation."});return}let c="output",d=this.flags.allOptional?Tt(a):a,l=await po(he(d),c,o),u=Ct.join(t,`${c}.ts`);await uo(u,l,"utf-8"),$({message:`Generated types written to ${u}`})}async generateKvsTypes({cwd:e,outputDir:t,compileOptions:o}){let s=lo({cwd:e,key:"keyValueStore",label:"Key-Value Store"});if(!s)return;let{schema:i,schemaPath:n}=s;n?v({message:`[experimental] Generating types from Key-Value Store schema at ${n}`}):v({message:`[experimental] Generating types from Key-Value Store schema embedded in '${D}'`});let a=va(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:l,schema:u}of a){let p=this.flags.allOptional?Tt(u):u,g=await po(he(p),l,{...o,bannerComment:c.length===0?o.bannerComment:""});c.push(g)}let d=Ct.join(t,"key-value-store.ts");await uo(d,c.join(`
97
+ `),"utf-8"),$({message:`Generated types written to ${d}`})}};var Et=class extends y{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 ma()}};import{ACTOR_ENV_VARS as wi,APIFY_ENV_VARS as Cm}from"@apify/consts";var $t=class extends y{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[Cm.IS_AT_HOME])){f({message:"get-public-url is not yet implemented for local development"}),process.exitCode=255;return}let t=process.env[wi.DEFAULT_KEY_VALUE_STORE_ID];if(!t){f({message:`Missing environment variable: ${wi.DEFAULT_KEY_VALUE_STORE_ID}. Please set it before running the command.`}),process.exitCode=5;return}let o=await ct();if(!await o.keyValueStore(t).get()){f({message:`Key-Value store with ID '${t}' was not found. Ensure the store exists and that the correct ID is set in ${wi.DEFAULT_KEY_VALUE_STORE_ID}.`}),process.exitCode=250;return}let i=await o.keyValueStore(t).getRecordPublicUrl(e);console.log(i)}};var Rt=class extends y{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 yi(e)}};var xt=class extends y{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||$e;if(!t){f({message:"No item was provided."});return}let o=await ct(),s=dr(lr.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 _t=class extends y{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 ct()).keyValueStore(dr(lr.KEY_VALUE_STORE));s==null||s===""||s==="null"||s==="undefined"?await n.deleteRecord(e):await n.setRecord({key:e,value:s,contentType:o})}};var fo=class extends y{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=[_t,xt,Rt,$t,Et,vt,At,It];async run(){this.printHelp()}};import Le from"chalk";import Im from"process";async function He({providedActorNameOrId:r,client:e}){let t=await M(),o=t.username||t.id,s=Ue(Im.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(He,"resolveActorContext");var kt=class extends y{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 He({providedActorNameOrId:i,client:n});if(!a.valid){f({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(),l=Fr(c.versions,C=>C.buildTag??"latest")[e??"latest"],u=c.versions.find(C=>C.versionNumber===t),p,g=e;if(u){if(e&&(!l||!l.some(C=>C.versionNumber===t))){f({message:`The Actor Version "${t}" does not have the tag "${e}".`,stdout:!0});return}p=t,g=u.buildTag??"latest"}else if(l&&(p=l[0].versionNumber,g=e??"latest",l.length>1&&!t)){f({message:`Multiple Actor versions with the tag "${e}" found. Please specify the version number using the "--version" flag.
103
+ Available versions for this tag: ${l.map(C=>Le.yellow(C.versionNumber)).join(", ")}`,stdout:!0});return}if(!p){f({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 h=await n.actor(a.id).build(p,{tag:e});if(o){L(h);return}let b=[`${Le.yellow("Actor")}: ${c?.username?`${c.username}/`:""}${c?.name??"unknown-actor"} (${Le.gray(h.actId)})`,` ${Le.yellow("Version")}: ${p} (tagged with ${Le.yellow(g)})`,"",`${Le.greenBright("Build Started")} (ID: ${Le.gray(h.id)})`,` ${Le.yellow("Build Number")}: ${h.buildNumber} (will get tagged once finished)`,` ${Le.yellow("Started")}: ${Y.display(h.startedAt)}`,""],S=`https://console.apify.com/actors/${h.actId}/builds/${h.buildNumber}`,E=`${Le.blue("View in Apify Console")}: ${S}`;if(R({message:b.join(`
104
+ `),stdout:!0}),s){try{await ke({job:h,apifyClient:n})}catch(C){f({message:`Failed to print log for build with ID "${h.id}": ${C.message}`,stdout:!0})}R({message:"",stdout:!0})}R({message:E,stdout:!0})}};var go=class extends kt{static name="build"};import Ia from"process";import{DownloadItemsFormat as _m}from"apify-client";import ae from"chalk";import{access as Em,readFile as $m}from"fs/promises";import Rm,{resolve as Sa}from"path";import De from"process";import xm from"mime";function Ta(r,e){let t,o;if(e)t=e,o="application/json";else{let s=zt(r);s&&(xm.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(Ta,"resolveInput");async function Pt(r,e,t){let o,s;if(!e&&!t){let i=$e;if(i)try{let n=JSON.parse(i.toString("utf8"));if(Array.isArray(n))return f({message:"The provided input is invalid. It should be an object, not an array."}),De.exitCode=5,!1;o=n,s="stdin"}catch(n){return f({message:`Cannot parse JSON input from standard input.
105
+ ${n.message}`}),De.exitCode=5,!1}}if(e)switch(e[0]){case"-":return f({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),De.exitCode=5,!1;default:{let i=await Em(Sa(r,e)).then(()=>!0).catch(()=>!1),n=e.endsWith(".json")||e.endsWith(".json5")||Rm.isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.includes("~")||e.startsWith(".\\")||e.startsWith("..\\");if(i||n)return f({message:'Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead'}),De.exitCode=5,!1;try{let a=JSON.parse(e);if(Array.isArray(a))return f({message:"The provided input is invalid. It should be an object, not an array."}),De.exitCode=5,!1;o=a,s="input"}catch(a){return f({message:`Cannot parse JSON input.
106
+ ${a.message}`}),De.exitCode=5,!1}}}else if(t)switch(t[0]){case"-":return f({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),De.exitCode=5,!1;default:{let i=Sa(r,t),n;try{let a=await $m(i,"utf8"),c=JSON.parse(a);if(Array.isArray(c))return f({message:"The provided input is invalid. It should be an object, not an array."}),De.exitCode=5,!1;o=c,s=t}catch(a){n=a}if(n)try{let a=JSON.parse(t);if(Array.isArray(a))return f({message:"The provided input is invalid. It should be an object, not an array."}),De.exitCode=5,!1;o=a,s=t}catch{return f({message:`Cannot read input file at path "${i}".
107
+ ${n.message}`}),De.exitCode=5,!1}}}return o?{input:o,source:s}:void 0}m(Pt,"getInputOverride");import Ai from"process";import yo from"chalk";import{ACTOR_JOB_STATUSES as qe}from"@apify/consts";var Ca=[qe.SUCCEEDED,qe.ABORTED,qe.FAILED,qe.TIMED_OUT];async function*Ot(r,e){let t=Ai.cwd(),{actorOrTaskData:o,runOptions:s,type:i,waitForFinishMillis:n,inputOverride:a,silent:c,waitForRunToFinish:d,printRunLogs:l}=e,u=i==="Actor"?"actor":"task",p=Ta(t,a);c||(i==="Actor"?Se({message:`Calling ${i} ${o.userFriendlyId} (${yo.gray(o.id)})
108
+ `}):o.title?Se({message:`Calling ${i} ${o.title} (${o.userFriendlyId}, ${yo.gray(o.id)})
109
+ `}):Se({message:`Calling ${i} ${o.userFriendlyId} (${yo.gray(o.id)})
110
+ `}));let g;try{p&&i==="Actor"?g=await r[u](o.id).start(p.inputToUse,{...s,contentType:p.contentType}):g=await r[u](o.id).start(void 0,s)}catch(h){throw h.type==="record-not-found"?new Error(`${i} ${o.userFriendlyId} (${o.id}) not found!`):h}if(yield g,!c&&l)try{await ke({job:g,timeoutMillis:n,apifyClient:r})==="timeouts"?console.error(`
111
+ ${yo.gray("Timeout for printing logs was hit, there may be future logs.")}
112
+ `):console.error()}catch(h){x({message:"Can not get log:"}),console.error(h)}if(g=await r.run(g.id).get(),d)for(;!Ca.includes(g.status)&&(g=await r.run(g.id).get(),!Ca.includes(g.status));)await new Promise(h=>{setTimeout(h,1e3)});c||(g.status===qe.SUCCEEDED?$({message:`${i} finished.`}):g.status===qe.RUNNING?x({message:`${i} is still running!`}):g.status===qe.ABORTED||g.status===qe.ABORTING?(x({message:`${i} was aborted!`}),Ai.exitCode=3):(f({message:`${i} failed!`}),Ai.exitCode=1)),yield g}m(Ot,"runActorOrTaskOnCloud");var Nt=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 Je=class r extends y{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={...Nt("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=Ia.cwd(),t=Ue(e)||{},o=await I(),s=await M(),i=s.username||s.id;if(this.flags.json&&this.flags.outputDataset){f({message:"You cannot use both the --json and --output-dataset flags when running this command."}),Ia.exitCode=5;return}let{id:n,userFriendlyId:a,actorData:c}=await r.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),d={waitForFinish:2};this.flags.build&&(d.build=this.flags.build),this.flags.timeout&&(d.timeout=this.flags.timeout),this.flags.memory&&(d.memory=this.flags.memory);let l=await Pt(e,this.flags.input,this.flags.inputFile);if(l===!1)return;let u=!1,p,g,h,b=Ot(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:d,type:"Actor",inputOverride:l?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0});for await(let S of b)if(p=S,!u&&(u=!0,!this.flags.silent)){g=`https://console.apify.com/actors/${n}/runs/${S.id}`,h=`https://console.apify.com/storage/datasets/${S.defaultDatasetId}`;let E=[`${ae.yellow("Started")}: ${Y.display(S.startedAt)}`];S.containerUrl&&E.push(`${ae.yellow("Container URL")}: ${ae.blue(S.containerUrl)}`);let C=p.buildNumber.split(".").slice(0,2).join("."),k=c.versions.find(U=>U.versionNumber===C),N=Object.entries(c.taggedBuilds??{}).find(([,U])=>U.buildNumber===S.buildNumber)?.[0],O=[`${ae.yellow("Build")}:`,ae.cyan(p.buildNumber)];N?O.push(`(${ae.yellow(N)})`):O.push(`(${ae.gray("N/A")})`),k&&O.push(`| ${ae.gray("Actor version:")} ${ae.cyan(k.versionNumber)} (${ae.yellow(k.buildTag)})`),E.push(O.join(" ")),E.push(`${ae.yellow("Timeout")}: ${p.options.timeoutSecs.toLocaleString("en-US")} seconds`),E.push(`${ae.yellow("Memory")}: ${p.options.memoryMbytes} MB`),E.push(`${ae.blue("View on Apify Console")}: ${g}`,""),R({message:E.join(`
114
+ `),stdout:!this.flags.json})}if(this.flags.json){L(p);return}if(this.flags.silent||R({message:["",`${ae.blue("Export results")}: ${h}`,`${ae.blue("View on Apify Console")}: ${g}`].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 k=await o.dataset(S).downloadItems(_m.JSON,{clean:!0});console.log(k.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 P from"chalk";import km from"cli-table3";var Pm={mid:"","left-mid":"","mid-mid":"","right-mid":"",middle:" ","top-mid":"\u2500","bottom-mid":"\u2500"},Om={middle:" ","top-mid":"\u2500","bottom-mid":"\u2500",top:"\u2500",bottom:"\u2500","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u2500","right-mid":"\u2524"},Nm={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 Lm={[-1]:void 0,0:Pm,1:Om,2:Nm};function Dm(r){return Array.from({length:r},()=>"cyan")}m(Dm,"generateHeaderColors");var Fm=process.stdout.columns??100,ho=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=Dm(t.length),s=e===0||e===2,i=Lm[e],n=[],a=[],c=[];for(let l of t)this.options.hiddenColumns?.includes(l)||this.rows.some(u=>u[l]===ho)||(n.push(this.options.columnAlignments?.[l]||"left"),r.isSmallTerminal()?(a.push(this.options.breakpointOverrides?.small?.[l]?.label??l),c.push(this.options.breakpointOverrides?.small?.[l]?.valueFrom??l)):(a.push(l),c.push(l)));let d=new km({head:a,style:{head:o,compact:s},colAligns:n,chars:i});for(let l of this.rows){let u=c.map(p=>l[p]);d.push(u)}return d.toString()}static isSmallTerminal(){return Fm<100}};var wo="\u200B",Ao="\u200B\u200B",Ea=new B({allColumns:[wo,Ao],mandatoryColumns:[wo,Ao],columnAlignments:{[wo]:"left",[Ao]:"right"}}),vo=class extends y{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 He({providedActorNameOrId:e,client:i});if(!n.valid){f({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 g=await i.build(p.buildId).get();p.build=g}if(s){L(a);return}let d=a.taggedBuilds?.latest;if(t){if(!d){f({message:"No README found for this Actor.",stdout:!0});return}if(!d.build?.readme){f({message:"No README found for this Actor.",stdout:!0});return}R({message:d.build.readme,stdout:!0})}if(o){if(!d){f({message:"No input schema found for this Actor.",stdout:!0});return}if(!d.build?.inputSchema){f({message:"No input schema found for this Actor.",stdout:!0});return}R({message:d.build.inputSchema,stdout:!0})}let l=[`Information about Actor ${P.yellow(`${a.username}/${a.name}`)} (${P.gray(a.id)})`,""];a.title&&l.push(`${P.yellow("Title:")} ${P.bold(a.title)}`),a.description&&l.push(`${P.yellow("Description:")} ${a.description}`),l.push(`${P.yellow("Created at:")} ${P.cyan(Y.display(a.createdAt))} ${P.gray("|")} ${P.yellow("Updated at:")} ${P.cyan(Y.display(a.modifiedAt))}`),a.actorMaker&&(l.push("",`${P.yellow("Made by:")} ${P.cyan(a.actorMaker.profile.name??a.actorMaker.username)}`),Reflect.get(a,"isCritical")&&(l[l.length-1]+=` ${P.bgGray("Maintained by Apify")}`)),a.isPublic?l.push("",`${P.yellow("Actor is")} ${P.green("PUBLIC")}`):l.push("",`${P.yellow("Actor is")} ${P.cyan("PRIVATE")}`),a.isDeprecated&&l.push("",`${P.yellow("Actor is")} ${P.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(l.push(`${P.yellow("Pricing information:")} ${P.bgGray(`$${p.pricePerUnitUsd}/month + usage`)}`),p.trialMinutes){let g=p.trialMinutes*60*1e3,h=Qt.format(g);l.push(` ${P.yellow("Trial duration:")} ${P.bold(h)}`)}break}case"PRICE_PER_DATASET_ITEM":{let g=p.pricePerUnitUsd*1e3;l.push(`${P.yellow("Pricing information:")} ${P.bgGray(`$${g.toFixed(2)} / 1,000 results`)}`);break}case"PAY_PER_EVENT":{l.push(`${P.yellow("Pricing information:")} ${P.bgGray("Pay per event")}`);let g=Object.values(p.pricingPerEvent?.actorChargeEvents??{});for(let S of g)Ea.pushRow({[wo]:S.eventTitle,[Ao]:P.bold(`$${S.eventPriceUsd.toFixed(2)}`)});let b=Ea.render(0).split(`
116
+ `);b.splice(1,1),l.push(b.join(`
117
+ `));break}case"FREE":{l.push(`${P.yellow("Pricing information:")} ${P.bgGray("Pay for usage")}`);break}default:l.push(`${P.yellow("Pricing information:")} ${P.bgGray(`Unknown pricing model (${P.yellow(p.pricingModel)})`)}`)}}else l.push(`${P.yellow("Pricing information:")} ${P.bgGray("Pay for usage")}`);if((a.seoTitle||a.seoDescription)&&(l.push("",P.yellow("SEO information:")),a.seoTitle&&l.push(` ${P.yellow("Title:")} ${a.seoTitle}`),a.seoDescription&&l.push(` ${P.yellow("Description:")} ${a.seoDescription}`)),a.taggedBuilds){l.push("",P.yellow("Builds:"));let p=a.taggedBuilds.latest;p&&l.push(` ${P.yellow("-")} ${P.cyan(p.buildNumber)} ${P.gray("/")} ${P.yellow("latest")}`);for(let[g,h]of Object.entries(a.taggedBuilds))g!=="latest"&&l.push(` ${P.yellow("-")} ${P.cyan(h.buildNumber)} ${P.gray("/")} ${P.yellow(g)}`)}R({message:l.join(`
118
+ `),stdout:!0})}};import{Time as Um}from"@sapphire/duration";import Q from"chalk";import Me from"chalk";function _e(r){switch(r){case"READY":return Me.green("Ready");case"RUNNING":return Me.blue("Running");case"SUCCEEDED":return Me.green("Succeeded");case"FAILED":return Me.red("Failed");case"ABORTING":return Me.yellow("Aborting");case"ABORTED":return Me.red("Aborted");case"TIMING-OUT":return Me.yellow("Timing Out");case"TIMED-OUT":return Me.red("Timed Out");default:return Me.gray(r.split("-").map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(" "))}}m(_e,"prettyPrintStatus");var Mm={"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")},jm=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"}}}}),Bm=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"}}}}),bo=class extends y{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}v({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(),g=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:g.items[0]??null}}))};if(c.items=s?this.sortByModifiedAt(c.items):this.sortByLastRun(c.items),i){L(c);return}let d=s?Bm:jm,l=c.items.reduce((u,p)=>{let g=`${p.username}/${p.name}`;return g.length>u?g.length:u},0)+2+6;for(let u of c.items){let p=u.stats.lastRunStartedAt?Zt.display(u.stats.lastRunStartedAt):"",g=u.lastRun?(()=>{if(u.lastRun.finishedAt)return de.format(u.lastRun.finishedAt.getTime()-u.lastRun.startedAt.getTime());let S=Date.now()-u.lastRun.startedAt.getTime();return`${de.format(S)}\u2026`})():"",h=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"),b=(()=>{if(u.lastRun){let E=[_e(u.lastRun.status)];if(g&&E.push(Mm[u.lastRun.status],Q.cyan(g)),u.lastRun.finishedAt){let C=Date.now()-u.lastRun.finishedAt.getTime();C<Um.Week?E.push(`
119
+ `,Q.gray(`${de.format(C)} ago`)):E.push(`
120
+ `,Q.gray("On",gn.display(u.lastRun.finishedAt)))}return E.join(" ")}return""})();d.pushRow({Name:`${u.title}
121
+ ${Q.gray(`${u.username}/${u.name}`)}`,Runs:B.isSmallTerminal()&&l>=56?ho:Q.cyan(`${u.stats?.totalRuns??0}`),"Last run started at":p,"Last run":p,"Last run status":u.lastRun?_e(u.lastRun.status):"","Modified at":Zt.display(u.modifiedAt),Builds:u.actor?Q.cyan(u.actor.stats.totalBuilds):Q.gray("Unknown"),"Last run duration":B.isSmallTerminal()?ho:Q.cyan(g),"Default build":h,_Small_LastRunText:b})}R({message:d.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 $a,readdirSync as Vm,writeFileSync as Ra}from"fs";import{dirname as Gm,join as Ym}from"path";import xa from"process";import Hm from"adm-zip";import qm from"axios";import _a from"jju";import{gt as Jm}from"semver";import Km from"tiged";var ka=m(async(r,e)=>{let{data:t}=await qm.get(r,{responseType:"arraybuffer"}),o=new Hm(Buffer.from(t,"binary"));o.extractEntryTo(o.getEntries()[0].entryName,e,!1)},"extractGitHubZip"),Lt=class extends y{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=xa.cwd(),t=await Ne({cwd:e});if(t.isErr()){f({message:t.unwrapErr().message}),xa.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 d;try{d=await i.actor(c).get()}catch{throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`)}if(!d)throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`);let{name:l,versions:u}=d,p=m(()=>{throw new Error("You cannot pull source code of this Actor because you do not have permission to do so.")},"throwMissingSourceCodeAccessError");if(!d.versions.length)throw new Error(`Actor ${c} has no versions.`);let g=null;if(this.flags.version&&(g=u.find(S=>S.versionNumber===this.flags.version),!g))throw new Error(`Cannot find version ${this.flags.version} of Actor ${c}.`);g||(g=u.reduce((S,E)=>Jm(`${E.versionNumber}.0`,`${S.versionNumber}.0`)?E:S));let h=n?e:Ym(e,this.flags.dir??l);if($a(h,{recursive:!0}),!n&&Vm(h).length!==0){f({message:`Directory ${h} is not empty. Please empty it or choose another directory.`});return}let{sourceType:b}=g;switch(b){case"TARBALL":{g.tarballUrl||p(),await ka(g.tarballUrl,h);break}case"SOURCE_FILES":{g.sourceFiles||p();let{sourceFiles:S}=g;for(let E of S){let C=Gm(E.name);if($a(`${h}/${C}`,{recursive:!0}),!E.folder){let k=E.format==="BASE64"?Buffer.from(E.content,"base64").toString():E.content;if(E.name===D){let N=_a.parse(k);N.name=d.name,Ra(`${h}/${E.name}`,_a.update(k,N))}else Ra(`${h}/${E.name}`,k)}}break}case"GIT_REPO":{g.gitRepoUrl||p();let{gitRepoUrl:S}=g,[E,C]=S.split("#"),k,N;C&&([k,N]=C.split(":"));let O=E;N&&(O+=`/${N}`),k&&(O+=`#${k}`);let U=Km(O);try{await U.clone(h)}catch(q){throw new Error(`Failed to pull Actor from ${S}. ${q.message}`)}break}case"GITHUB_GIST":{g.gitHubGistUrl||p(),await ka(`${g.gitHubGistUrl}/archive/master.zip`,h);break}default:throw new Error(`Unknown source type: ${b}`)}$({message:n?`Actor ${l} updated at ${h}/`:`Pulled to ${h}/`})}};import{readFileSync as Xm,statSync as Zm,unlinkSync as Qm}from"fs";import{join as eu,resolve as tu}from"path";import lt from"process";import ru from"open";import{fetchManifest as ou}from"@apify/actor-templates";import{ACTOR_JOB_STATUSES as dt,ACTOR_SOURCE_TYPES as bi,MAX_MULTIFILE_BYTES as ja}from"@apify/consts";import{createHmacSignature as su}from"@apify/utilities";import{readFileSync as Wm,writeFileSync as zm}from"fs";var vi="@",Pa=100,Oa=5e4,Dt=m(()=>{try{return JSON.parse(Wm(Sr(),"utf-8"))||{}}catch{return{}}},"getSecretsFile"),Na=m(r=>(Qs(Sr()),zm(Sr(),JSON.stringify(r,null," ")),r),"writeSecretsFile"),La=m((r,e)=>{let t=Dt();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>Pa)throw new Error(`Secret name has to be string with maximum length ${Pa}.`);if(typeof e!="string"||e.length>Oa)throw new Error(`Secret value has to be string with maximum length ${Oa}.`);return t[r]=e,Na(t)},"addSecret"),Da=m(r=>{let e=Dt();if(!e[r])throw new Error(`Secret with name ${r} doesn't exist.`);delete e[r],Na(e)},"removeSecret"),Fa=m(r=>new RegExp(`^${vi}.{1}`).test(r),"isSecretKey"),Ua=m((r,e,{allowMissing:t=!1}={})=>{e=e||Dt();let o={},s=[];if(Object.keys(r).forEach(i=>{if(Fa(r[i])){let n=r[i].replace(new RegExp(`^${vi}`),"");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"),Ma=m((r,e,{allowMissing:t=!1}={})=>{e=e||Dt();let o=[],s=[];if(Object.keys(r).forEach(i=>{if(Fa(r[i])){let n=r[i].replace(new RegExp(`^${vi}`),"");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 Si="temp_file.zip",iu={build:"latest",memoryMbytes:4096,timeoutSecs:3600},Ba="0.0",nu="latest",Ft=class extends y{static name="push";static description=`Deploys Actor to Apify platform using settings from '${D}'.
132
+ Files under '${ja/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=tu(lt.cwd(),this.flags.dir??"."),t=await ln(e);if(!t.length){f({message:"You need to call this command from a folder that has an Actor in it!"}),lt.exitCode=4;return}if(![Ir,"actor.json",".actor/actor.json",".actor"].some(F=>t.some(re=>re===F||re.startsWith(F)))){f({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
+ `)}),lt.exitCode=4;return}let o=await I(),s=await Ne({cwd:e});if(s.isErr()){f({message:s.unwrapErr().message}),lt.exitCode=5;return}let{config:i}=s.unwrap(),n=await M(),c=!!n.organizationOwnerUserId?`/organization/${n.id}`:"",d,l,u=!1,p=this.flags.version||i?.version||Ba,g=this.flags.buildTag||i?.buildTag;!g&&p===Ba&&(g=nu);let h=Number.isNaN(this.flags.waitForFinish)?void 0:Number.parseInt(this.flags.waitForFinish,10)*1e3,b=this.args.actorId;if(b){if(l=await o.actor(b).get(),!l)throw new Error(`Cannot find Actor with ID '${b}' in your account.`);d=l.id}else{let F=n.username||n.id;if(l=await o.actor(`${F}/${i.name}`).get(),l)d=l.id;else{let{templates:re}=await ou(),be=re.find(vr=>vr.name===i.template)?.defaultRunOptions||iu,ut={name:i.name,title:i.title,description:i.description,defaultRunOptions:be,versions:[{versionNumber:p,buildTag:g,sourceType:bi.SOURCE_FILES,sourceFiles:[]}]};i.usesStandbyMode&&(ut.actorStandby={isEnabled:!0}),l=await o.actors().create(ut),d=l.id,u=!0,v({message:`Created Actor with name ${i.name} on Apify.`})}}let S=o.actor(d);v({message:`Deploying Actor '${i.name}' to Apify.`});let E=await Zi(t,e),C,k,N;if(E<ja){let F=await S.get();if(!u){let re=t.reduce((be,ut)=>{let{mtimeMs:vr,ctimeMs:Mi}=Zm(eu(e,ut)),ji=vr>Mi?vr:Mi;return be>ji?be:ji},0),ve=F?.modifiedAt.valueOf();if(!this.flags.force&&ve&&re<ve&&(i?.name||b))throw new Error(`Actor with identifier "${i?.name||b}" is already on the platform and was modified there since modified locally.
136
+ Skipping push. Use --force to override.`)}k=await cn(t,e),C=bi.SOURCE_FILES}else{Se({message:"Zipping Actor files"}),await dn(Si,t,e);let F=await o.keyValueStores().getOrCreate(`actor-${d}-source`),re=`version-${p}.zip`,ve=Xm(Si);await o.keyValueStore(F.id).setRecord({key:re,value:ve,contentType:"application/zip"}),Qm(Si);let be=new URL(`${o.baseUrl}/key-value-stores/${F.id}/records/${re}?disableRedirect=true`);if(F?.urlSigningSecretKey){let ut=su(F.urlSigningSecretKey,re);be.searchParams.set("signature",ut)}N=be.toString(),C=bi.TARBALL}let O=await S.version(p).get(),U=i.environmentVariables?Ma(i.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(O){let F={tarballUrl:N,sourceFiles:k,buildTag:g,sourceType:C,envVars:U};await S.version(p).update(F),Se({message:`Updated version ${p} for Actor ${l.name}.`})}else{let F={versionNumber:p,tarballUrl:N,sourceFiles:k,buildTag:g,sourceType:C,envVars:U};await S.versions().create({...F}),Se({message:`Created version ${p} for Actor ${l.name}.`})}if(!u&&!!i.usesStandbyMode!=!!l.actorStandby?.isEnabled){let F=!!i.usesStandbyMode;await S.update({actorStandby:{isEnabled:F}}),v({message:`${F?"Enabled":"Disabled"} standby mode for Actor ${l.name}.`})}Se({message:`Building Actor ${l.name}`});let q=await S.build(p,{useCache:!0,waitForFinish:2});try{await ke({job:q,timeoutMillis:h,apifyClient:o})}catch(F){x({message:"Can not get log:"}),console.error(F)}if(q=await o.build(q.id).get(),this.flags.json){L(q);return}Bs({message:"Actor build detail",url:`https://console.apify.com${c}/actors/${q.actId}#/builds/${q.buildNumber}`}),Bs({message:"Actor detail",url:`https://console.apify.com${c}/actors/${q.actId}`}),this.flags.open&&await ru(`https://console.apify.com${c}/actors/${q.actId}`),q.status===dt.SUCCEEDED?$({message:"Actor was deployed to Apify cloud and built there."}):q.status===dt.READY?x({message:"Build is waiting for allocation."}):q.status===dt.RUNNING?x({message:"Build is still running."}):q.status===dt.ABORTED||q.status===dt.ABORTING?(x({message:"Build was aborted!"}),lt.exitCode=3):q.status===dt.TIMED_OUT||q.status===dt.TIMING_OUT?(x({message:"Build timed out!"}),lt.exitCode=2):(f({message:"Build failed!"}),lt.exitCode=1)}};var So=class extends y{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})};async run(){let{actorId:e}=this.args,t=await I();if(!await t.actor(e).get()){f({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?"})){v({message:`Deletion of Actor "${e}" was canceled.`});return}try{await t.actor(e).delete(),$({message:`Actor with ID "${e}" was deleted.`})}catch(i){let n=i;f({message:`Failed to delete Actor "${e}".
137
+ ${n.message||n}`})}}};import{ApifyClient as au}from"apify-client";import Ti from"chalk";var cu={FREE:"Free",FLAT_PRICE_PER_MONTH:"Subscription",PRICE_PER_DATASET_ITEM:"Pay per result",PAY_PER_EVENT:"Pay per event"};function lu(r){return r?cu[r]??r:Ti.gray("Unknown")}m(lu,"formatPricingModel");function du(r,e=60){return r?r.length<=e?r:`${r.slice(0,e-1)}\u2026`:""}m(du,"truncateDescription");var To=class extends y{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,d=Kt();delete d.token;let l=new au(d),u;try{u=await l.store().list({search:e,sortBy:o,category:s,username:i,pricingModel:n,limit:a,offset:c})}catch(g){process.exitCode=1,f({message:`Failed to search Apify Store: ${g instanceof Error?g.message:String(g)}`,stdout:!0});return}if(u.count===0){if(t){L(u);return}v({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 g of u.items)p.pushRow({Name:`${g.title}
140
+ ${Ti.gray(`${g.username}/${g.name}`)}`,Description:du(g.description),"Users (30d)":Ti.cyan(`${g.stats?.totalUsers30Days??0}`),Pricing:lu(g.currentPricingInfo?.pricingModel)});R({message:p.render(1),stdout:!0})}};import ie from"chalk";var Co=class extends y{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={...Nt("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=Ue(e)||{},o=await I(),s=await M(),i=s.username||s.id,{id:n,userFriendlyId:a,actorData:c}=await Je.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),d={};this.flags.build&&(d.build=this.flags.build),this.flags.timeout&&(d.timeout=this.flags.timeout),this.flags.memory&&(d.memory=this.flags.memory);let l=await Pt(e,this.flags.input,this.flags.inputFile);if(l===!1)return;let u=Ot(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:d,type:"Actor",inputOverride:l?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),p;for await(let N of u)p=N;if(this.flags.json){L(p);return}let g=`https://console.apify.com/actors/${n}/runs/${p.id}`,h=`https://console.apify.com/storage/datasets/${p.defaultDatasetId}`,b=[`${ie.gray("Run:")} Calling Actor ${a} (${ie.gray(n)})`,"",`${ie.yellow("Started")}: ${Y.display(p.startedAt)}`];p.containerUrl&&b.push(`${ie.yellow("Container URL")}: ${ie.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],k=[`${ie.yellow("Build")}:`,ie.cyan(p.buildNumber)];C?k.push(`(${ie.yellow(C)})`):k.push(`(${ie.gray("N/A")})`),E&&k.push(`| ${ie.gray("Actor version:")} ${ie.cyan(E.versionNumber)} (${ie.yellow(E.buildTag)})`),b.push(k.join(" ")),b.push(`${ie.yellow("Timeout")}: ${p.options.timeoutSecs.toLocaleString("en-US")} seconds`),b.push(`${ie.yellow("Memory")}: ${p.options.memoryMbytes} MB`),b.push("",`${ie.blue("Export results")}: ${h}`,`${ie.blue("View on Apify Console")}: ${g}`),R({message:b.join(`
142
+ `),stdout:!0})}};var Io=class extends y{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=[Co,So,To,Ft,Lt,bo,vo,Je,go];async run(){this.printHelp()}};import pu from"chalk";import fu from"computer-name";import gu from"cors";import Ci from"express";import yu from"open";import{cryptoRandomObjectId as hu}from"@apify/utilities";import mu from"@inquirer/password";var Va=Pe(async({message:r,mask:e})=>await mu({message:r,mask:e??"*"}));import uu from"@inquirer/select";var Ke=Pe(async({message:r,choices:e,pageSize:t,loop:o,default:s})=>await uu({message:r,choices:e,pageSize:t,loop:o,default:s}));var Ei="https://console.apify.com/settings/integrations",wu=new URL(Ei).origin,Au=Ei.includes("localhost")?"http://localhost:3333":void 0,Ga="v1",Ii=m(async r=>{let e=await Wt(r,Au),t=await M();return e?(await Ur(t.id),$({message:`You are logged in to Apify as ${t.username||t.id}. ${pu.gray(`Your token is stored at ${fe()}.`)}`})):f({message:"Login to Apify failed, the provided API token is not valid."}),e},"tryToLogin"),Ut=class extends y{static name="login";static description=`Authenticates your Apify account and saves credentials to '${ce(fe())}'.
144
+ All other commands use these stored credentials.
145
+
146
+ 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 Ii(e);return}let o=t;if(t||(o=await Ke({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=Ci();i.use(gu({origin:wu,allowedHeaders:["Content-Type","Authorization"]})),i.use((l,u,p)=>{u.set("Connection","close"),p()}),i.use(Ci.json());let n=hu();i.use((l,u,p)=>{let{token:g}=l.query;if(!g){let h=l.get("Authorization");if(h){let[b,S,...E]=h.trim().split(/\s+/);b.toLowerCase()==="bearer"&&S&&E.length===0&&(g=S)}}g!==n?(u.status(401),u.send("Authorization failed")):p()});let a=Ci.Router();i.use(`/api/${Ga}`,a),a.post("/login-token",async(l,u)=>{try{if(l.body.apiToken)await Ii(l.body.apiToken);else throw new Error("Request did not contain API token");u.end()}catch(p){let g=`Login to Apify failed with error: ${p.message}`;f({message:g}),u.status(500),u.send(g)}s.close()}),a.post("/exit",(l,u)=>{l.body.isWindowClosed?f({message:"Login to Apify failed, the console window was closed."}):l.body.actionCanceled?f({message:"Login to Apify failed, the action was canceled in the Apify Console."}):f({message:"Login to Apify failed."}),u.end(),s.close()}),s=i.listen(0);let{port:c}=s.address(),d=new URL(Ei);d.searchParams.set("localCliCommand","login"),d.searchParams.set("localCliPort",`${c}`),d.searchParams.set("localCliToken",n),d.searchParams.set("localCliApiVersion",Ga);try{d.searchParams.set("localCliComputerName",encodeURIComponent(fu()))}catch{}v({message:`Opening Apify Console at "${d.href}"...`}),await yu(d.href)}else{console.log("Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations");let s=await Va({message:"token:"});await Ii(s)}}};var Mt=class extends y{static name="logout";static description=`Removes authentication by deleting your API token and account information from '${ce(fe())}'.
147
+ 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 Bt(fe()),await Ur(null),$({message:"You are logged out from your Apify account."})}};var Eo=class extends y{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&&R({message:e.token,stdout:!0})}};var $o=class extends y{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=[Ut,Mt,Eo];async run(){this.printHelp()}};import Ro from"chalk";var xo=class extends y{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){f({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(s.status!=="SUCCEEDED"){f({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){f({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 ${Ro.gray(a.buildNumber)})`:"";$({message:`Tag "${Ro.yellow(t)}" added to build ${Ro.gray(s.buildNumber)} (${Ro.gray(e)})${c}`,stdout:!0})}catch(c){let d=c;f({message:`Failed to add tag "${t}" to build "${e}".
148
+ ${d.message||d}`,stdout:!0})}}};import te from"chalk";var vu=m(r=>r,"noColor");function ee({bytes:r,shortBytes:e=!1,colorFunc:t=vu,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 _o=class extends y{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){f({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[g,h]of Object.entries(s.taggedBuilds))if(h.buildId===o.id){i=g;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)})`:"",d=typeof n<"u"?` (exit code: ${te.gray(n)})`:"",l=[`${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")}: ${_e(o.status)}${d}`,` ${te.yellow("Started")}: ${Y.display(o.startedAt)}`];if(o.finishedAt)l.push(` ${te.yellow("Finished")}: ${Y.display(o.finishedAt)} (took ${te.gray(Qt.format(o.stats?.durationMillis??0))})`);else{let g=Date.now()-o.startedAt.getTime();l.push(` ${te.yellow("Finished")}: ${te.gray(`Running for ${Qt.format(g)}`)}`)}o.stats?.computeUnits&&l.push(` ${te.yellow("Compute Units")}: ${o.stats.computeUnits.toFixed(3)}`);let u=Reflect.get(o.stats??{},"imageSizeBytes");u&&l.push(` ${te.yellow("Docker Image Size")}: ${ee({bytes:u})}`),l.push(` ${te.yellow("Origin")}: ${o.meta.origin??"UNKNOWN"}`),l.push("");let p=`https://console.apify.com/actors/${o.actId}/builds/${o.buildNumber}`;l.push(`${te.blue("View in Apify Console")}: ${p}`),R({message:l.join(`
149
+ `),stdout:!0})}};var ko=class extends y{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){f({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}v({message:`Log for build with ID "${e}":
150
+ `});try{await ke({job:o,apifyClient:t})}catch(s){f({message:`Failed to get log for build with ID "${e}": ${s.message}`,stdout:!0})}}};import we from"chalk";var bu=m(()=>new B({allColumns:["Number","ID","Status","Took"],mandatoryColumns:["Number","ID","Status","Took"],columnAlignments:{Took:"right"}}),"tableFactory"),Po=class extends y{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 He({providedActorNameOrId:n,client:a});if(!c.valid){f({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let d=await a.actor(c.id).builds().list({desc:e,limit:t,offset:o}),l=await a.actor(c.id).get(),u=Fr(d.items,h=>{let b=Reflect.get(h,"buildNumber"),[S,E]=b.split(".");return`${S}.${E}`}),p=Object.entries(l.taggedBuilds??{}).reduce((h,[b,S])=>(h[S.buildNumber]=b,h),{});if(i){for(let h of d.items){let b=Reflect.get(h,"buildNumber"),S=p[b];S&&Reflect.set(h,"buildTag",S)}L(d);return}R({message:`${we.reset("Showing")} ${we.yellow(d.items.length)} out of ${we.yellow(d.total)} builds for Actor ${we.yellow(c.userFriendlyId)} (${we.gray(c.id)})
151
+ `,stdout:!0});let g=Object.entries(u).sort((h,b)=>h[0].localeCompare(b[0]));for(let[h,b]of g){if(!b?.length){R({message:`No builds for version ${h}`,stdout:!0});continue}let S=l.versions.find(N=>N.versionNumber===h)?.buildTag,E=this.generateTableForActorVersion({buildsForVersion:b,buildTagToActorVersion:p}),C=S?` (latest build gets tagged with ${we.yellow(S)})`:"",k=[we.reset(`Builds for Actor Version ${we.yellow(h)}${C}`),E.render(s?0:-1),""];R({message:k.join(`
152
+ `),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:t}){let o=bu();for(let s of e){let i=Reflect.get(s,"buildNumber"),n=t[i]?` (${we.yellow(t[i])})`:"",a;if(s.finishedAt){let c=s.finishedAt.getTime()-s.startedAt.getTime();a=we.gray(`${de.format(c,void 0,{left:""})}`)}else{let c=Date.now()-s.startedAt.getTime();a=we.gray(`Running for ${de.format(c,void 0,{left:""})}`)}o.pushRow({Number:`${i}${n}`,ID:we.gray(s.id),Status:_e(s.status),Took:a})}return o}};import ur from"chalk";var Oo=class extends y{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}),yes:w.boolean({char:"y",description:'Automatic yes to prompts; assume "yes" as answer to all prompts.',default:!1})};async run(){let{build:e,tag:t,yes:o}=this.flags,s=await I(),i=await s.build(e).get();if(!i){f({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let n=await s.actor(i.actId).get();if(!n){f({message:`Actor with ID "${i.actId}" was not found.`,stdout:!0});return}let c=(n.taggedBuilds??{})[t];if(!c){f({message:`Tag "${t}" does not exist on Actor "${n.name}".`,stdout:!0});return}if(c.buildId!==e){f({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 "${ur.yellow(t)}" from build ${ur.gray(i.buildNumber)}?`,providedConfirmFromStdin:o||void 0})){v({message:"Tag removal was canceled.",stdout:!0});return}try{await s.actor(i.actId).update({taggedBuilds:{[t]:null}}),$({message:`Tag "${ur.yellow(t)}" removed from build ${ur.gray(i.buildNumber)} (${ur.gray(e)})`,stdout:!0})}catch(l){let u=l;f({message:`Failed to remove tag "${t}" from build "${e}".
153
+ ${u.message||u}`,stdout:!0})}}};import Su from"@inquirer/input";var Ya=Pe(async({message:r,expectedValue:e,failureMessage:t})=>await Su({message:r,validate(s){return s===e?!0:t??"That is not the correct input!"}}));var No=class extends y{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})};async run(){let{buildId:e}=this.args,t=await I(),o=await t.build(e).get();if(!o){f({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let s=await t.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[a,c]of Object.entries(s.taggedBuilds))if(e===c.buildId){i=a;break}}if(!await(i?Ya:Z)({message:`Are you sure you want to delete this Actor Build?${i?` If so, please type in "${i}":`:""}`,expectedValue:i??"",failureMessage:"Your provided value does not match the build tag."})){v({message:`Deletion of build "${e}" was canceled.`,stdout:!0});return}try{await t.build(e).delete(),$({message:`Build with ID "${e}" was deleted.`,stdout:!0})}catch(a){let c=a;f({message:`Failed to delete build "${e}".
154
+ ${c.message||c}`,stdout:!0})}}};var Lo=class extends y{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=[xo,Oo,No,Po,ko,_o,kt];async run(){this.printHelp()}};var Do=class extends Je{static name="call"};import Tu from"assert";import{existsSync as Ha,openSync as Cu}from"fs";import{mkdir as qa,readFile as Iu,symlink as Eu,unlink as $u,writeFile as Ja}from"fs/promises";import{homedir as Ru}from"os";import{dirname as xu,join as We}from"path";import{ReadStream as _u}from"tty";import H from"chalk";import Ka from"which";var ku=m(r=>We(r,".install-marker"),"pathToInstallMarker"),Wa=m(()=>process.env.HOME??Ru(),"HOMEDIR"),pr=class extends y{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"){v({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}Tu(t,"When CLI is installed via bundles, the install path must be set");let s=ku(t);if(Ha(s)){v({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){f({message:i.message||"Failed to automatically handle shell integration"})}R({message:""})}await Ja(s,o),T("[install] install marker written to",s),R({message:["",H.green("Apify and Actor CLI were installed successfully!"),"",H.gray(` Version: ${H.green(o)}`),H.gray(` Location: ${H.bold.white(ce(We(t,"apify")))} and ${H.bold.white(ce(We(t,"actor")))}`)].join(`
155
+ `)}),R({message:""}),$({message:"To get started, run:"}),R({message:H.white.bold(` apify --help
156
+ actor --help`)})}async symlinkToLocalBin(e){let t=Wa();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=We(t,".local","bin");await qa(o,{recursive:!0});let s=["apify","actor","apify-cli"];for(let i of s){let n=We(e,i);if(!Ha(n)){T("[install] file not found for symlinking",i,n),x({message:H.gray(`Bundle not found for symlinking: ${i}`)});continue}let a=We(o,i);await $u(a).catch(()=>{}),await Eu(n,a),T("[install] symlink created for item",i,a)}v({message:H.gray(`Symlinked apify, actor, and apify-cli to ${ce(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)}
157
+ `)},"writeDone");try{return T("[install] opening /dev/tty for raw mode"),t=Cu("/dev/tty","r"),o=new _u(t),process.stdout.write(s),o.setRawMode(!0),o.resume(),await new Promise(a=>{let c=m(d=>{let l=d.toString();l==="y"||l==="Y"||l==="\r"||l===`
158
+ `?(o.removeListener("data",c),i("Yes"),a(!0)):l==="n"||l==="N"?(o.removeListener("data",c),i("No"),a(!1)):(l===""||l==="")&&(o.removeListener("data",c),process.stdout.write(`
159
+ `),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([Ka("apify",{nothrow:!0}),Ka("actor",{nothrow:!0})]);if(e.status==="fulfilled"&&t.status==="fulfilled"&&e.value&&t.value){T("[install -> promptAddToShell] already in PATH",{apifyCliPath:e,actorCliPath:t}),v({message:H.gray("Apify and Actor CLIs are already in PATH, skipping shell integration")});return}let o=Wa();T("[install -> promptAddToShell] user home directory",o);let s=process.env.APIFY_CLI_INSTALL??We(o,".apify"),i=process.env.FINAL_BIN_DIR??We(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;R({message:""});let c="Should the CLI handle adding itself to your shell automatically?",d;process.env.APIFY_OPEN_TTY?d=await this.confirmFromTty(c):(T("[install] opening /dev/tty for raw mode not requested, falling back to normal flow"),d=await Z({message:c,providedConfirmFromStdin:!1}));let l=yn(),u=hn(o,l),p=`"${n.replaceAll('"','\\"')}"`,g=[],h=!0;switch(l){case"bash":case"zsh":{g.push(`export APIFY_CLI_INSTALL=${p}`),g.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"');break}case"fish":{g.push(`set --export APIFY_CLI_INSTALL ${p}`),g.push(`set --export PATH ${a} $PATH`);break}default:{g.push(`export APIFY_CLI_INSTALL=${p}`),g.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),d=!1,h=!1;break}}if(R({message:""}),d&&u){let E=`${await Iu(u,"utf-8").catch(C=>{if(C.code==="ENOENT")return"";throw new Error(`Failed to read config file "${ce(u)}". Received error code: ${C.code}; ${C.message}`)})}
160
+
161
+ # apify cli
162
+ ${g.join(`
163
+ `)}
164
+ `;try{await qa(xu(u),{recursive:!0}),await Ja(u,E)}catch(C){throw C.code==="EACCES"?new Error(`Failed to write to config file "${ce(u)}", as the CLI does not have permission to write to it.`):new Error(`Failed to write to config file "${ce(u)}". Received error code: ${C.code}; ${C.message}`)}v({message:[H.gray(`Added "${ce(a)}" to your PATH in ${ce(u)}.`),H.gray(` You may need to run ${H.white.bold(`source ${ce(u)}`)} to reload your shell.`)].join(`
165
+ `)});return}let b=u??"your shell config file";if(h){let S=`echo -e '${g.join("\\n")}' >> "${b}" && source "${b}"`;v({message:[H.gray("The Apify & Actor CLIs are not in your PATH. Run:"),"",H.white.bold(` ${S}`)].join(`
166
+ `)});return}v({message:[H.gray(`Manually add the following lines to ${b} or similar:`),...g.map(S=>H.white.bold(` ${S}`))].join(`
167
+ `)})}};import{spawn as Mu}from"child_process";import{existsSync as ju}from"fs";import{lstat as Bu,readdir as Vu,writeFile as Za}from"fs/promises";import{dirname as Gu,join as $i}from"path";import Ri from"chalk";import{gte as Qa}from"semver";import{Result as Pu}from"@sapphire/result";import{execa as Ou}from"execa";var Nu=m(async(r,e,t)=>{let o=Ve(r);T("spawnPromised",{escapedCommand:o,args:e,opts:t});let s=Ou(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 Pu.fromAsync(s.catch(i=>{throw new Error(`${r} exited with code ${i.exitCode}`,{cause:i})}))},"spawnPromised");async function pe({cmd:r,args:e=[],opts:t={},overrideCommand:o}){Se({message:`${o||r} ${e.join(" ")}`});let s=await Nu(r,e,t);if(s.isErr()){let i=s.unwrapErr();if(f({message:i.message}),i.cause)throw i.cause}}m(pe,"execWithLog");import{execSync as za}from"child_process";import{existsSync as Lu,readFileSync as Du}from"fs";var je=z();function Fu(){return je.platform==="linux"?Lu("/etc/alpine-release"):!1}m(Fu,"isInstalledOnMusl");function Uu(){return je.platform==="darwin"&&je.arch==="x64"?!za("sysctl -a",{encoding:"utf-8"}).includes("AVX2"):je.platform==="linux"&&je.arch==="x64"?!Du("/proc/cpuinfo","utf-8").includes("avx2"):je.platform==="windows"?je.arch==="arm64"?!0:za(`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(Uu,"isInstalledOnBaseline");async function Xa(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":st}});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=Fu(),n=Uu(),a=s.assets.filter(c=>{let[d,l,u,p,g,h]=c.name.replace(e,"version").replace(".exe","").split("-");return u!==je.platform||p!==je.arch?!1:i?g==="musl":n?h==="baseline"||g==="baseline":!g&&!h});return T("useCLIVersionAssets","Fetched release",{version:s.tag_name,filteredAssets:a}),{assets:a,version:s.tag_name.replace(/^v(\d+)/,"$1")}}m(Xa,"useCLIVersionAssets");var ec={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")},Fo="1.0.1",tc="https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1",fr=class extends y{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 ta(!this.flags.internalAutomaticCall),{installMethod:t}=z();if(!e.shouldUpdate||e.currentVersion===Vs){T("[upgrade] no update needed",{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||v({message:`${this.cliName} is up to date \u{1F44D}
168
+ `});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion("latest");return}let o=ec[t]("latest",this.entrypoint).join(" ");R({message:""});let s=[`You are using an old version of ${this.cliName}. We strongly recommend you always use the latest available version.`,` \u21AA Run ${Ri.bgWhite(Ri.black(o))} to update! \u{1F44D}
169
+ `].join(`
170
+ `);x({message:s})}async handleInstallSpecificVersion(e){if(e!=="latest"&&!Qa(e,Fo)){f({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Fo}.`});return}let t=await Xa(e);if(!t){f({message:"The provided version does not exist. Please check the version number and try again."});return}let{assets:o,version:s}=t;if(!Qa(s,Fo)){f({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Fo}.`});return}let i=z();if(i.installMethod==="bundle"){if(!o.length){f({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(`
171
+ `)});return}let a=Gu(process.execPath);T("[upgrade] bundleDirectory",a);let c=await Vu(a);if(!c.some(d=>d.startsWith("apify")||d.startsWith("actor"))){T("[upgrade] directoryEntries",c),f({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(`
172
+ `)});return}if(i.platform==="windows")return this.startUpgradeProcess(a,s,o);await this.handleUnixUpgrade(a,s,o),this.successMessage(s);return}let n=ec[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){v({message:`Would run command: ${n.join(" ")}`});return}try{await pe({cmd:n[0],args:n.slice(1)}),this.successMessage(s)}catch{f({message:`Failed to upgrade the CLI. Please run the following command manually: ${n.join(" ")}`})}}successMessage(e){$({message:`Successfully upgraded to ${e} \u{1F44D}`})}async startUpgradeProcess(e,t,o){await this.upsertUpgradeScript(e);let s=["-ExecutionPolicy","Bypass","-File",`"${$i(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),v({message:"Starting upgrade process..."});let n=Mu("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=>{f({message:`Failed to start the upgrade process: ${a.message}`})})}async upsertUpgradeScript(e){let t=$i(e,"upgrade.ps1");if(ju(t))return;let o=z(),s=await fetch(tc,{headers:{"User-Agent":st}});s.ok||(f({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: ${tc}`,`- The status code of the response: ${s.status}`].join(`
173
+ `)}),process.exit(1));let i=await s.arrayBuffer();await Za(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=$i(e,n);v({message:`Downloading \`${n}\` binary of the Apify CLI...`});let c=await fetch(i.browser_download_url,{headers:{"User-Agent":st}});if(!c.ok){let l=await c.text();T("[upgrade] failed to fetch asset",{asset:i,status:c.status,body:l}),f({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: ${l}`].join(`
174
+ `)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){v({message:`Would write asset ${n} to ${a}`});continue}v({message:Ri.gray(`Writing ${n} to ${a}...`)});let d=await c.arrayBuffer();try{let l=await Bu(a).then(u=>u.mode).catch(()=>493);await Za(a,Buffer.from(d),{mode:l|448}),T(`[upgrade ${n}] wrote asset to`,a)}catch(l){T("[upgrade] failed to write asset",{error:l}),f({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: ${l.message}`].join(`
175
+ `)})}}}};import{mkdir as zu,readdir as Xu,stat as cc}from"fs/promises";import{join as mt}from"path";import lc from"process";import{gte as Zu,minVersion as Qu}from"semver";import{fetchManifest as ep,manifestUrl as tp}from"@apify/actor-templates";import{createWriteStream as Yu}from"fs";import{pipeline as Hu}from"stream/promises";import{Separator as oc}from"@inquirer/core";var rc=["JavaScript","TypeScript","Python"];async function xi(r){return r?(Xt(r),r):qu()}m(xi,"ensureValidActorName");async function sc(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 ac(t)}m(sc,"getTemplateDefinition");async function ic(r,e){let t=await e;if(t instanceof Error)throw t;try{let o=await _r(t.localReadmeSuffixUrl),s=Yu(r,{flags:"a"});s.write(`
176
+
177
+ `),await Hu(o,s)}catch(o){x({message:`Could not append local development instructions to README.md. Cause: ${o.message}`})}}m(ic,"enhanceReadmeWithLocalSuffix");function nc(r){let{actorName:e,dependenciesInstalled:t,postCreate:o,gitRepositoryInitialized:s,installCommandSuggestion:i}=r,n=`\u2705 Actor '${e}' created successfully!`;return t?n+=`
178
+
179
+ Next steps:
180
+
181
+ cd "${e}"
182
+ apify run`:n+=`
183
+
184
+ Next steps:
185
+
186
+ cd "${e}"
187
+ ${i||"install dependencies with your package manager"}
188
+ apify run`,n+=`
189
+
190
+ \u{1F4A1} Tip: Use 'apify push' to deploy your Actor to the Apify platform
191
+ \u{1F4D6} Docs: https://docs.apify.com/platform/actors/development`,s&&(n+=`
192
+ \u{1F331} Git repository initialized in '${e}'. You can now commit and push your Actor to Git.`),o&&(n+=`
193
+
194
+ ${o}`),n}m(nc,"formatCreateSuccessMessage");async function ac(r){let e=await Ju();for(;;){let t=await Ku(r,e);if(t){if(await Wu())return t}else return ac(r)}}m(ac,"executePrompts");async function qu(){return await it({message:"Name of your new Actor:",validate:m(e=>{try{Xt(e)}catch(t){return t.message}return!0},"validate")})}m(qu,"promptActorName");async function Ju(){return await Ke({message:"Choose the programming language of your new Actor:",choices:rc,loop:!1,default:rc[0]})}m(Ju,"promptProgrammingLanguage");async function Ku(r,e){let t=[...r.templates.filter(s=>s.category.toLowerCase()===e.toLowerCase()).map(s=>({name:s.label,value:s})),new oc,{name:"Go back",value:!1}];return await Ke({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(Ku,"promptTemplateDefinition");async function Wu(){let r=[{name:"Install dependencies",value:!0},new oc,{name:"Go back",value:!1}];return await Ke({message:"Almost done! Last step is to install dependencies.",default:r[0],choices:r,loop:!1})}m(Wu,"promptTemplateInstallation");var Uo=class extends y{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 ${tp} 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=ep().catch(C=>new Error(`Could not fetch template list from server. Cause: ${C?.message}`));e=await xi(e);let c=lc.cwd(),d=mt(c,e);for(;;){let C=await cc(d).catch(()=>null),k=C&&await Xu(d).then(N=>N.length>0).catch(()=>!1);if(C?.isDirectory()&&k){f({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 xi(),d=mt(c,e);continue}C||await zu(d,{recursive:!0});break}let l=null;if(this.telemetryData.fromArchiveUrl=!!i,!i){let C=await sc(t,a);({archiveUrl:i,messages:l}=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 Dr({url:i,pathTo:d});let u=le(mt(d,D));await kr(Object.assign(u||br,{name:e}),d),await Pr(d),await mo(d);let p=mt(d,"package.json"),g=mt(d,"README.md");await ic(g,a);let h=!1;o||await(await Oe({cwd:d})).inspectAsync(async k=>{let N=Qu(Te);if(!k.runtime){switch(k.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 ${rt} or higher to be able to run Python Actors locally.`});break}default:}return}let{runtime:O}=k;switch(k.type){case 0:{Lr(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 Xi(p,{name:e});let U=["install"];if(n)switch(O.pmName){case"npm":{Zu(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 pe({cmd:O.pmPath,args:U,opts:{cwd:d},overrideCommand:O.pmName}),h=!0;break}case 1:case 2:{if(!Nr(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=mt(d,".venv");v({message:`Python version ${O.version} detected.`}),v({message:`Creating a virtual environment in "${U}" and installing dependencies from "requirements.txt"...`}),lc.env.VIRTUAL_ENV||(await pe({cmd:O.executablePath,args:["-m","venv","--prompt",".",Ki],opts:{cwd:d}}),O=(await or({cwd:d,force:!0})).unwrap(),k.runtime=O),await pe({cmd:O.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","--upgrade","pip","setuptools","wheel"],opts:{cwd:d}}),await pe({cmd:O.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","-r","requirements.txt"],opts:{cwd:d}}),h=!0;break}default:}});let b={success:!0},S=await cc(mt(c,".git")).catch(()=>null);if(!s&&!S)try{await pe({cmd:"git",args:["init"],opts:{cwd:d}})}catch(C){b={success:!1,error:C}}let E=h?null:await $n(d);R({message:""}),$({message:nc({actorName:e,dependenciesInstalled:h,postCreate:l?.postCreate??null,gitRepositoryInitialized:!s&&!S&&b.success,installCommandSuggestion:E})}),!s&&!S&&!b.success&&(x({message:`Failed to initialize git repository: ${b.error.message}`}),x({message:'You can manually run "git init" in the Actor directory if needed.'}))}};import mc from"chalk";async function dc(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(dc,"tryToGetStorage");async function Fe(r,e){return dc(r,e,"dataset")}m(Fe,"tryToGetDataset");async function ne(r,e){return dc(r,e,"keyValueStore")}m(ne,"tryToGetKeyValueStore");var Mo=class extends y{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 Fe(t,e)){f({message:"A Dataset with this name already exists!"});return}let o=await t.datasets().getOrCreate(e);if(this.flags.json){L(o);return}$({message:`Dataset with ID ${mc.yellow(o.id)}${e?` (called ${mc.yellow(e)})`:""} was created.`,stdout:!0})}};import{DownloadItemsFormat as ze}from"apify-client";var uc={[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"},jo=class extends y{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(uc),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){f({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}),d=uc[o]??"application/octet-stream";R({message:d}),process.stdout.write(c),process.stdout.write(`
195
+ `)}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 Bo(r){let e=Reflect.get(r,"planPricing");return e?Reflect.get(e,"chargeableServiceUnitPricesUsd"):null}m(Bo,"getUserPlanPricing");var pc=new B({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),Vo=class extends y{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 Fe(t,e);if(!o){f({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 d=s.stats?.storageBytes||0,l=s.stats?.readCount||0,u=s.stats?.writeCount||0,p=(s.cleanItemCount||0).toLocaleString("en-US"),g=(s.itemCount||0).toLocaleString("en-US"),h=[`${G.bold(l.toLocaleString("en-US"))} ${G.gray(this.pluralString(l,"read","reads"))}`,`${G.bold(u.toLocaleString("en-US"))} ${G.gray(this.pluralString(u,"write","writes"))}`],b=`Items: ${G.bold(p)} ${G.gray("clean")} / ${G.bold(g)} ${G.gray("total")}
196
+ Operations: ${h.join(" / ")}`;if(i.plan){let F=Bo(i.plan);if(F){let re=F.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(d/1e9),ve=re*24*30,be=ve>1?`$${ve.toFixed(2)}`:`$${re.toFixed(3)}`;b+=`
197
+ Storage size: ${ee({bytes:d,shortBytes:!0,precision:1})} / ${G.gray(`${be} per month`)}`}}else b+=`
198
+ Storage size: ${ee({bytes:d,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(`
199
+ `),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 k=G.bold("\u2014");c&&(k=G.blue(c.title||c.name));let N=[`Run: ${E}`,`Actor: ${C}`,`Task: ${k}`].join(`
200
+ `);pc.pushRow({Row1:S,Row2:N});let U=pc.render(2).split(`
201
+ `).map(F=>F.trim());U.shift();let q=[`${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(`
202
+ `),"",b].join(`
203
+ `);R({message:q,stdout:!0})}};import fc from"chalk";var gc=new B({allColumns:["Dataset ID","Name","Items","Size","Created","Modified"],mandatoryColumns:["Dataset ID","Name","Items","Size"],columnAlignments:{Items:"right"}}),Go=class extends y{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){v({message:"You don't have any Datasets on your account",stdout:!0});return}for(let d of c.items){let l=Reflect.get(d.stats,"s3StorageBytes");gc.pushRow({"Dataset ID":d.id,Created:Y.display(d.createdAt),Items:`${d.itemCount}`,Modified:Y.display(d.modifiedAt),Name:d.name?`${a.username}/${d.name}`:"",Size:typeof l=="number"?ee({bytes:l,shortBytes:!0,colorFunc:fc.gray,precision:0}):fc.gray("N/A")})}R({message:gc.render(1),stdout:!0})}};import Yo from"chalk";var Ho=class extends y{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 Fe(o,e);if(!s){f({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:n}=s,a,c=t||$e;if(!c){f({message:"No items were provided."});return}try{a=JSON.parse(c.toString("utf8"))}catch(l){f({message:`Failed to parse data as JSON string: ${l.message}`});return}if(Array.isArray(a)&&a.length===0){f({message:"No items were provided."});return}let d=n.name?`Dataset named ${Yo.yellow(n.name)} (${Yo.gray("ID:")} ${Yo.yellow(n.id)})`:`Dataset with ID ${Yo.yellow(n.id)}`;try{await i.pushItems(a),$({message:`${this.pluralString(Array.isArray(a)?a.length:1,"Object","Objects")} pushed to ${d} successfully.`})}catch(l){let u=l;f({message:`Failed to push items into ${d}
204
+ ${u.message||u}`})}}};import Xe from"chalk";var qo=class extends y{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){f({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){f({message:"You cannot provide a new name and the --unname flag."});return}let s=await I(),i=await Fe(s,o);if(!i){f({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 ${Xe.yellow(n)} has been removed (was ${Xe.yellow(a)} previously).`:`The name of the dataset with ID ${Xe.yellow(n)} was changed from ${Xe.yellow(a)} to ${Xe.yellow(t)}.`:`The name of the dataset with ID ${Xe.yellow(n)} has been set to: ${Xe.yellow(t)}`;try{await i.datasetClient.update({name:e?null:t}),$({message:c,stdout:!0})}catch(d){let l=d;f({message:`Failed to rename dataset with ID ${Xe.yellow(n)}
205
+ ${l.message||l}`})}}};import _i from"chalk";var Jo=class extends y{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})};async run(){let{datasetNameOrId:e}=this.args,t=await I(),o=await Fe(t,e);if(!o){f({message:`Dataset with ID or name "${e}" not found.`});return}if(!await Z({message:"Are you sure you want to delete this Dataset?"})){v({message:"Dataset deletion has been aborted."});return}let{id:i,name:n}=o.dataset;try{await o.datasetClient.delete(),$({message:`Dataset with ID ${_i.yellow(i)}${n?` (called ${_i.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let c=a;f({message:`Failed to delete dataset with ID ${_i.yellow(i)}
206
+ ${c.message||c}`})}}};var Ko=class extends y{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=[Mo,jo,Go,Vo,Jo,qo,Ho];async run(){this.printHelp()}};import{existsSync as ki,mkdirSync as rp,readFileSync as op,writeFileSync as sp}from"fs";import{dirname as ip}from"path";import np from"cors";import ap from"detect-indent";import Pi from"express";import cp from"open";import{cryptoRandomObjectId as lp}from"@apify/utilities";var hc="https://apify.github.io/input-schema-editor-react/",dp=new URL(hc).origin,yc="v1",Wo=class extends y{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 bt({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.
207
+ `}),v({message:`Editing input schema at "${t}"...`});let o,s=Pi();s.use(np({origin:dp,allowedHeaders:["Content-Type","Authorization"]})),s.use((u,p,g)=>{p.set("Connection","close"),g()}),s.use(Pi.json());let i=lp();s.use((u,p,g)=>{let{token:h}=u.query;if(!h){let b=u.get("Authorization");if(b){let[S,E,...C]=b.trim().split(/\s+/);S.toLowerCase()==="bearer"&&E&&C.length===0&&(h=E)}}h!==i?(p.status(401),p.send("Authorization failed")):g()});let n=Pi.Router();s.use(`/api/${yc}`,n);let a=" ",c=!0;n.get("/input-schema",(u,p)=>{let g;try{g=ki(t)?op(t,{encoding:"utf-8"}):`{}
208
+ `,g.length>3&&(a=ap(g).indent||a),g&&(c=g[g.length-1]===`
209
+ `),ki(t)?v({message:`Input schema loaded from "${t}"`}):v({message:"Empty input schema initialized."})}catch(b){let S=`Reading input schema from disk failed with: ${b.message}`;f({message:S}),p.status(500),p.send(S);return}let h;try{h=JSON.parse(g||"{}")}catch(b){let S=`Parsing input schema failed with error: ${b.message}`;f({message:S}),p.status(500),p.send(S);return}p.send(h),v({message:"Input schema sent to editor."})}),n.post("/input-schema",(u,p)=>{try{v({message:"Got input schema from editor..."});let g=u.body,h=JSON.stringify(g,null,a);c&&(h+=`
210
+ `);let b=ip(t);ki(b)||rp(b,{recursive:!0}),sp(t,h,{encoding:"utf-8",flag:"w+"}),p.end(),v({message:"Input schema saved to disk."})}catch(g){let h=`Saving input schema failed with error: ${g.message}`;f({message:h}),p.status(500),p.send(h)}}),n.post("/exit",(u,p)=>{u.body.isWindowClosed?v({message:"Editor closed, finishing..."}):v({message:"Editing finished, you can close the editor."}),p.end(),o.close(()=>$({message:"Done."}))}),o=s.listen(0);let{port:d}=o.address();v({message:`Listening for messages from input schema editor on port ${d}...`});let l=`${hc}?localCliPort=${d}&localCliToken=${i}&localCliApiVersion=${yc}`;v({message:`Opening input schema editor at "${l}"...`}),await cp(l)}};import zo from"chalk";var gr=class extends y{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=eo(this.entrypoint);console.log(i);return}let t=e.toLowerCase(),o=W.get(t);if(!o){let i=oo(t),n=zo.gray(`Command ${zo.whiteBright(e)} not found`);i.length&&(n+=`
211
+ `,n+=zo.gray(`Did you mean: ${i.map(a=>zo.whiteBright(a)).join(", ")}?`)),f({message:n});return}let s=Zr(o);console.log(s)}};import wc from"chalk";var Xo=class extends y{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(`${wc.gray(o)}: ${wc.bold(t[o])}`)}}};import{basename as Ip}from"path";import Di from"process";import{appendFileSync as mp,copyFileSync as up,createWriteStream as pp,existsSync as Oi,mkdirSync as fp,readFileSync as Ac,rmSync as gp,writeFileSync as yp}from"fs";import{basename as hp,join as Ni,relative as vc,sep as Li}from"path";import{fileURLToPath as wp}from"url";import Ap from"@root/walk";import vp from"configparser";import bp from"handlebars";import{fetchManifest as Sp,wrapperManifestUrl as Tp}from"@apify/actor-templates";var Cp=[".dockerignore",".gitignore"],Zo=wp(new URL("./templates/python-scrapy",import.meta.url));async function bc(r,e,t={bindings:{}}){await Ap.walk(r,async(o,s,i)=>{if(s===r)return;let n=vc(r,s),a=n.split(Li).map(d=>{if(d.startsWith("{")&&d.endsWith("}")){d=d.replace("{","").replace("}","");let l=t.bindings[d];if(!l)throw new Error(`Binding for ${d} not found.`);return l}return d}).join(Li),c=Ni(e,a);if(i.isDirectory())return Oi(c)||fp(c),bc(s,c);n.includes(".template")?yp(Ni(e,a.replace(".template","")),bp.compile(Ac(s,"utf8"))(t.bindings)):Oi(c)&&Cp.includes(hp(a))?mp(c,Ac(s)):up(s,c)})}m(bc,"merge");async function Qo({projectPath:r}){r||(r=".");let e=new nt(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 Ke({message:"Pick the Scrapy spider you want to wrap:",choices:e.getAvailableSpiders().map((d,l)=>({name:`${d.class_name} (${d.pathname})`,value:l}))});function o(d){return`.${vc(r,d).split(Li).slice(1).join(".").replace(".py","")}`}m(o,"translatePathToRelativeModuleName");let s={botName:Or(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 Sp(Tp);v({message:"Downloading the latest Scrapy wrapper template..."});let{archiveUrl:n}=i.templates.find(({id:d})=>d==="python-scrapy");Oi(Zo)&&gp(Zo,{recursive:!0}),await Dr({url:n,pathTo:Zo}),v({message:"Wrapping the Scrapy project..."}),await bc(Zo,r,{bindings:s});let a=new vp;a.addSection("apify"),a.set("apify","mainpy_location",e.settings.BOT_NAME);let c=pp(Ni(r,"scrapy.cfg"),{flags:"a"});await new Promise(d=>{c.on("open",l=>{c.write(`
212
+ `,()=>{a.write(l),d()})})}),$({message:"The Scrapy project has been wrapped successfully."})}m(Qo,"wrapScrapyProject");var es=class extends y{static name="init";static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
213
+ If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
214
+ Creates the '${D}' file and the '${tt}' directory in the current directory, but does not touch any other existing files or directories.
215
+
216
+ WARNING: Overwrites existing '${tt}' 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={yes:w.boolean({char:"y",description:'Automatic yes to prompts; assume "yes" as answer to all prompts. Note that in some cases, the command may still ask for confirmation.',required:!1}),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=Di.cwd(),o=await Oe();o.isErr()&&(f({message:o.unwrapErr().message}),Di.exit(1));let s=o.unwrap();if(s.warnings?.length)for(let a of s.warnings)x({message:a});let i=Ip(t);if(s.type===1&&s.entrypoint?.path){let a=s.entrypoint.path,c=a.includes(".")?a.split(".").pop():a;i=Or(c)}if(s.type===2)return v({message:"The current directory looks like a Scrapy project. Using automatic project wrapping."}),this.telemetryData.actorWrapper="scrapy",Qo({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 Ne({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()){f({message:n.unwrapErr().message}),Di.exitCode=5;return}if(!e){let d=n.isOkAnd(l=>l.exists)?n.unwrap().config.name:null;for(;!d;)try{let l=await it({message:"Actor name:",default:i});Xt(l),d=l}catch(l){f({message:l.message})}e=d}let c={...{...br,...n.unwrap().config},name:e};this.flags.dockerfile&&(c.dockerfile=this.flags.dockerfile),await kr(c,t)}await Pr(t),await mo(t),$({message:"The Actor has been initialized in the current directory."})}};var ts=class extends y{static name="init-wrap-scrapy";static description=`Wraps your existing Scrapy project to work like an Apify Actor.
217
+
218
+ It adds the following features:
219
+ - Automatic retry of failed requests
220
+ - Automatic proxy rotation
221
+ - Automatic user agent rotation
222
+ ...
223
+ `;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 Qo({projectPath:this.args.path}),v({message:"Scrapy project wrapped successfully."})}};import Sc from"chalk";var rs=class extends y{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 ne(t,e)){f({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}$({message:`Key-value store with ID ${Sc.yellow(o.id)}${e?` (called ${Sc.yellow(e)})`:""} was created.`,stdout:!0})}};import Ep from"chalk";var os=class extends y{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})};async run(){let{storeId:e,itemKey:t}=this.args,o=await I(),s=await ne(o,e);if(!s){f({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:i}=s;if(!await i.getRecord(t)){f({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?"})){v({message:"Key-value store record deletion aborted.",stdout:!0});return}try{await i.deleteRecord(t),v({message:`Record with key "${Ep.yellow(t)}" deleted from the key-value store.`,stdout:!0})}catch(c){let d=c;f({message:`Failed to delete record with key "${t}" from the key-value store.
224
+ ${d.message||d}`})}}};var ss=class extends y{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 ne(s,t);if(!i){f({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.getRecord(o,{stream:!0});if(!a){f({message:`Item with key "${o}" not found in the key-value store.`});return}if(R({message:a.contentType??"application/octet-stream"}),e){a.value.destroy();return}if(a.contentType?.includes("application/json")){let{value:c}=a,d=[];for await(let u of c)d.push(u);let l=Buffer.concat(d).toString();try{let u=JSON.parse(l);R({message:JSON.stringify(u,null,2),stdout:!0})}catch{R({message:l,stdout:!0})}return}a.value.pipe(process.stdout)}};import V from"chalk";var Tc=new B({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),is=class extends y{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 ne(t,e);if(!o){f({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 d=s.stats?.storageBytes||0,l=s.stats?.readCount||0,u=s.stats?.writeCount||0,p=s.stats?.deleteCount||0,g=s.stats?.listCount||0,b=`Operations: ${[`${V.bold(l.toLocaleString("en-US"))} ${V.gray(this.pluralString(l,"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(g.toLocaleString("en-US"))} ${V.gray(this.pluralString(g,"list","lists"))}`].join(" / ")}`;if(i.plan){let F=Bo(i.plan);if(F){let re=F.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(d/1e9),ve=re*24*30,be=ve>1?`$${ve.toFixed(2)}`:`$${re.toFixed(3)}`;b+=`
225
+ Storage size: ${ee({bytes:d,shortBytes:!0,precision:1})} / ${V.gray(`${be} per month`)}`}}else b+=`
226
+ Storage size: ${ee({bytes:d,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(`
227
+ `),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 k=V.bold("\u2014");c&&(k=V.blue(c.title||c.name));let N=[`Run: ${E}`,`Actor: ${C}`,`Task: ${k}`].join(`
228
+ `);Tc.pushRow({Row1:S,Row2:N});let U=Tc.render(2).split(`
229
+ `).map(F=>F.trim());U.shift();let q=[`${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(`
230
+ `),"",b].join(`
231
+ `);R({message:q,stdout:!0})}};var Cc=new B({allColumns:["Key","Size"],mandatoryColumns:["Key","Size"]}),ns=class extends y{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 ne(s,e);if(!i){f({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)Cc.pushRow({Key:c.key,Size:ee({bytes:c.size,shortBytes:!0,precision:0})});R({message:Cc.render(1),stdout:!0})}};import Ic from"chalk";var Ec=new B({allColumns:["Store ID","Name","Size","Created","Modified"],mandatoryColumns:["Store ID","Name","Size"]}),as=class extends y{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){v({message:"You don't have any key-value stores on your account",stdout:!0});return}for(let d of c.items){let u=Reflect.get(d,"stats").s3StorageBytes;Ec.pushRow({"Store ID":d.id,Created:Y.display(d.createdAt),Modified:Y.display(d.modifiedAt),Name:d.name?`${a.username}/${d.name}`:"",Size:typeof u=="number"?ee({bytes:u,shortBytes:!0,colorFunc:Ic.gray,precision:0}):Ic.gray("N/A")})}R({message:Ec.render(1),stdout:!0})}};import Ze from"chalk";var cs=class extends y{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){f({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){f({message:"You cannot provide a new name and the --unname flag."});return}let s=await I(),i=await ne(s,o);if(!i){f({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 ${Ze.yellow(n)} has been removed (was ${Ze.yellow(a)} previously).`:`The name of the key-value store with ID ${Ze.yellow(n)} was changed from ${Ze.yellow(a)} to ${Ze.yellow(t)}.`:`The name of the key-value store with ID ${Ze.yellow(n)} has been set to: ${Ze.yellow(t)}`;try{await i.keyValueStoreClient.update({name:e?null:t}),$({message:c,stdout:!0})}catch(d){let l=d;f({message:`Failed to rename key-value store with ID ${Ze.yellow(n)}
232
+ ${l.message||l}`})}}};import Fi from"chalk";var ls=class extends y{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})};async run(){let{keyValueStoreNameOrId:e}=this.args,t=await I(),o=await ne(t,e);if(!o){f({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?"})){v({message:"Key-value store deletion has been aborted."});return}let{id:i,name:n}=o.keyValueStore;try{await o.keyValueStoreClient.delete(),$({message:`Key-value store with ID ${Fi.yellow(i)}${n?` (called ${Fi.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let c=a;f({message:`Failed to delete key-value store with ID ${Fi.yellow(i)}
233
+ ${c.message||c}`})}}};var ds=class extends y{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 ne(i,e);if(!n){f({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}),$({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(c){let d=c;f({message:`Failed to set value with key "${t}" in the key-value store.
234
+ ${d.message||d}`})}}};var ms=class extends y{static name="key-value-stores";static description=`Manage Apify key-value stores \u2014 create, list, rename, delete stores, and get/set/delete individual records.
235
+
236
+ Alias: kvs.`;static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores";static hiddenAliases=["kvs"];static subcommands=[rs,os,ss,is,ns,as,cs,ls,ds];async run(){this.printHelp()}};var us=class extends Ut{static name="login"};var ps=class extends Mt{static name="logout"};var fs=class extends Lt{static name="pull"};var gs=class extends Ft{static name="push"};var ys=class extends y{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 Rc,renameSync as kp}from"fs";import{mkdir as hs,readFile as Pp,stat as xc,writeFile as hr}from"fs/promises";import{dirname as ws,join as As}from"path";import Be from"process";import Op from"mime";import{minVersion as Np}from"semver";import{APIFY_ENV_VARS as vs}from"@apify/consts";import{validateInputSchema as Lp,validateInputUsingValidator as _c}from"@apify/input_schema";import{none as yr,some as $p}from"@sapphire/result";import{execa as Rp}from"execa";var Ui=m(r=>`
237
+ (async () => {
238
+ const [nodeModule, process, path, fs] = await Promise.all([
239
+ import('node:module'),
240
+ import('node:process'),
241
+ import('node:path'),
242
+ import('node:fs/promises'),
243
+ ]);
244
+
245
+ /* we fake a script file here because otherwise node AND deno will fail to resolve modules, but bun works -.- */
246
+ const dirname = path.join(process.cwd(), '__apify_cli_fetch_module_version__.js');
247
+
248
+ const _require = nodeModule.createRequire(dirname);
249
+
250
+ try {
251
+ const modulePath = _require.resolve('${r}');
252
+ const moduleDir = path.dirname(modulePath);
253
+
254
+ const packageJson = await fs.readFile(path.join(moduleDir, 'package.json'), 'utf8').catch(() => null);
255
+
256
+ if (!packageJson) {
257
+ console.log('n/a');
258
+ return;
259
+ }
260
+
261
+ const packageJsonObj = JSON.parse(packageJson);
262
+ console.log(packageJsonObj.version);
263
+ } catch {
264
+ console.log('n/a');
265
+ }
266
+ })();
267
+ `.replaceAll(`
268
+ `," ").replaceAll(" "," "),"jsScript"),xp=m(r=>`
269
+ try:
270
+ import ${r}
271
+ print(${r}.__version__)
272
+ except:
273
+ print('n/a')
274
+ `,"pyScript"),_p={node(r){return["-e",`"${Ui(r)}"`]},deno(r){return["eval",`"${Ui(r)}"`]},bun(r){return["--eval",`"${Ui(r)}"`]},python(r){return["-c",`"${xp(r)}"`]}};async function $c({moduleName:r,project:e}){if(!e.runtime)return T("useModuleVersion",{status:"no_runtime_found",project:e,moduleName:r}),yr;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}),yr;let o=_p[t]?.(r);if(!o)return T("useModuleVersion",{status:"no_version_script_found",project:e,moduleName:r}),yr;try{let s=await Rp(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}),yr):(T("useModuleVersion",{status:"success",project:e,moduleName:r,version:s.stdout.trim()}),$p(s.stdout.trim()))}catch(s){return T("useModuleVersion",{status:"failed_to_run_version_script",project:e,moduleName:r,error:s}),yr}}m($c,"useModuleVersion");var bs=class extends y{static name="run";static description=`Executes Actor locally with simulated Apify environment variables.
275
+ Stores data in local '${tt}' directory.
276
+
277
+ 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.",`
278
+ `,"For Python, it is the module name, or a path to a file.",`
279
+ `,"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=Be.cwd(),{proxy:t,id:o,token:s}=await M(),i=await Ne({cwd:e});if(i.isErr()){let{message:O,cause:U}=i.unwrapErr();f({message:`${O}${U?`
280
+ ${U.message}`:""}`}),Be.exitCode=5;return}let{config:n}=i.unwrap(),a=ye(),c=await Oe({cwd:e});if(c.isErr()){f({message:c.unwrapErr().message}),Be.exitCode=5;return}let d=c.unwrap(),{type:l,entrypoint:u,runtime:p}=d;if(d.warnings?.length)for(let O of d.warnings)x({message:O});if(l===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(l){case 0:f({message:`No Node.js detected! Please install Node.js ${Te} (or higher) to be able to run Node.js Actors locally.`});break;case 2:case 1:f({message:`No Python detected! Please install Python ${rt} (or higher) to be able to run Python Actors locally.`});break;default:f({message:`No runtime detected! Make sure you have Python ${rt} (or higher) or Node.js ${Te} (or higher) installed.`})}return}let g,h;if(this.flags.entrypoint){h=this.flags.entrypoint;let O=As(e,this.flags.entrypoint),U=await xc(O).catch(()=>null);U?.isDirectory()?g=1:U?.isFile()?g=0:g=2}else if(u?.script)g=2,h=u.script;else if(u?.path)g=l!==0?1:0,h=u.path;else{f({message:"No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint."});return}Rc(Gs)&&!Rc(a)&&(kp(Gs,a),x({message:`The legacy 'apify_storage' directory was renamed to '${a}' to align it with Apify SDK v3. Contents were left intact.`}));let b=await $c({moduleName:"crawlee",project:d}),S="0";this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(S="1",b.isNone()&&(await Promise.all([mn(),pn(),un()]),v({message:"All default local stores were purged."}))),this.flags.purge||!await fn()&&!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 Pt(e,this.flags.input,this.flags.inputFile);if(E===!1)return;let C=await this.validateAndStoreInput(E),k={[vs.LOCAL_STORAGE_DIR]:a,CRAWLEE_STORAGE_DIR:a,CRAWLEE_PURGE_ON_START:S};if(t&&t.password&&(k[vs.PROXY_PASSWORD]=t.password),o&&(k[vs.USER_ID]=o),s&&(k[vs.TOKEN]=s),n.environmentVariables){let O=Ua(n.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets});Object.assign(k,O)}let N=Object.assign(k,Be.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(l){case 0:{let O=Np(Te);if(Lr(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.`}),g===0||g===1)await pe({cmd:p.executablePath,args:[h],opts:{env:N,cwd:e}});else{let U=await Pp(As(e,"package.json"),"utf8").catch(()=>"{}"),q=JSON.parse(U);if(!q.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(!q.scripts[h])throw new Error(`The script "${h}" 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 pe({cmd:p.pmPath,args:["run",h],opts:{env:N,cwd:e},overrideCommand:p.pmName})}break}case 1:case 2:{if(!Nr(p.version)){f({message:`Python Actors require Python 3.9 or higher, but you have Python ${p.version}!`}),f({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}g===1?await pe({cmd:p.executablePath,args:["-m",h],opts:{env:N,cwd:e}}):await pe({cmd:p.executablePath,args:[h],opts:{env:N,cwd:e}});break}default:f({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 xc(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 hr(C.inputFilePath,C.existingInput.body)}else await Vt(C.inputFilePath)}}async validateAndStoreInput(e){let{inputSchema:t}=await bt({cwd:Be.cwd()});if(!t){if(!e)return null;let d=zt(Be.cwd()),l=As(Be.cwd(),ge(),d?.fileName??"INPUT.json");return await hs(ws(l),{recursive:!0}),await hr(l,JSON.stringify(e.input,null,2)),{existingInput:d,inputFilePath:l,writtenAt:Date.now()}}let o=new Jt({strict:!1,unicodeRegExp:!1});Lp(o,t);let s=ya(t),i=ha(t,o),n=zt(Be.cwd()),a=As(Be.cwd(),ge(),n?.fileName??"INPUT.json"),c;switch(e?.source){case"stdin":c=`The input provided through standard input is invalid. Please fix the following errors:
281
+ `;break;case"input":c=`The input provided through the --input flag is invalid. Please fix the following errors:
282
+ `;break;default:e?c=`The input provided through the ${e.source} file is invalid. Please fix the following errors:
283
+ `:c=`The input in your storage is invalid. Please fix the following errors:
284
+ `;break}if(e){let d={...s,...e.input},l=_c(i,t,d);if(l.length>0)throw new Error(`${c}${l.map(u=>` - ${u.message.replace("Field input.","Field ")}`).join(`
285
+ `)}`);return await hs(ws(a),{recursive:!0}),await hr(a,JSON.stringify(d,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}if(!n)return await hs(ws(a),{recursive:!0}),await hr(a,JSON.stringify(s,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()};if(Op.getExtension(n.contentType)==="json"){let d=JSON.parse(n.body.toString("utf-8"));if(Array.isArray(d))throw new Error("The input in your storage is invalid. It should be an object, not an array.");let l={...s,...d},u=_c(i,t,l);if(u.length>0)throw new Error(`${c}${u.map(p=>` - ${p.message.replace("Field input.","Field ")}`).join(`
286
+ `)}`);return await hs(ws(a),{recursive:!0}),await hr(a,JSON.stringify(l,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}return null}};import{ACTOR_JOB_STATUSES as Ss}from"@apify/consts";var Dp=[Ss.READY,Ss.RUNNING],Fp=[Ss.ABORTING,Ss.TIMING_OUT],Ts=class extends y{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){f({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Dp.includes(o.status)){Fp.includes(o.status)?f({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):f({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?$({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):$({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(s){let i=s;f({message:`Failed to abort run "${e}".
287
+ ${i.message||i}`,stdout:!0})}}};import _ from"chalk";var wr=new B({allColumns:["","Unit","USD Amount"],mandatoryColumns:["","Unit","USD Amount"],columnAlignments:{Unit:"right","USD Amount":"right"}}),kc={"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"},Cs=class extends y{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){f({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 d=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",l=[`${_.yellow("Actor")}: ${d} (${_.grey(o.actId)})`];n?l.push(`\u2514\u2500 ${_.yellow("Task")}: ${n.title??n.name} (${_.gray(o.actorTaskId)})`,""):o.actorTaskId?l.push(`\u2514\u2500 ${_.yellow("Task")}: unknown-task (${_.gray(o.actorTaskId)})`,""):l.push("");let u=` (exit code: ${_.gray(o.exitCode!==null?o.exitCode:"N/A")})`;l.push(`${_.yellow("Status")}: ${_e(o.status)}${u}`),o.statusMessage&&l.push(`\u2514\u2500 ${_.yellow("Status Message:")} ${o.statusMessage}`);let p=a?.itemCount??0;l.push(`${_.yellow("Results")}: ${_.cyan(p.toLocaleString("en-US"))}`),c?l.push(`${_.yellow("Requests")}: ${_.cyan(c.handledRequestCount.toLocaleString("en-US"))} out of ${_.cyan(c.totalRequestCount.toLocaleString("en-US"))} handled`):l.push(`${_.yellow("Requests")}: ${_.gray("unknown handled")}`);let g=this.flags.verbose?"":_.gray(` (run with ${_.yellow("--verbose")} for a detailed breakdown)`);if(o.usageTotalUsd?l.push(`${_.yellow("Usage")}: ${_.cyan(this.formatUsd(o.usageTotalUsd))}${g}`):l.push(`${_.yellow("Usage")}: $${_.gray("0.000")}${g}`),this.flags.verbose&&l.push(wr.render(0)),l.push(""),l.push(`${_.yellow("Started")}: ${Y.display(o.startedAt)}`),o.finishedAt)l.push(`${_.yellow("Finished")}: ${Y.display(o.finishedAt)} (took ${_.gray(de.format(o.stats.durationMillis))})`);else{let E=Date.now()-o.startedAt.getTime();l.push(`${_.yellow("Finished")}: ${_.gray(`Running for ${de.format(E)}`)}`)}if(l.push(""),o.stats.resurrectCount?l.push(`${_.yellow("Resurrected")}: Yes, ${_.cyan(o.stats.resurrectCount.toLocaleString("en-US"))} ${this.pluralString(o.stats.resurrectCount,"time","times")}`):l.push(`${_.yellow("Resurrected")}: No`),o.containerUrl&&l.push(`${_.yellow("Container URL")}: ${_.blue(o.containerUrl)}`),l.push(`${_.yellow("Origin")}: ${o.meta.origin}`),s){let E=o.buildNumber.split(".").slice(0,2).join("."),C=s.versions.find(O=>O.versionNumber===E),k=Object.entries(s.taggedBuilds??{}).find(([,O])=>O.buildNumber===o.buildNumber)?.[0],N=[`${_.yellow("Build")}:`,_.cyan(o.buildNumber)];k?N.push(`(${_.yellow(k)})`):N.push(`(${_.gray("N/A")})`),C&&N.push(`| ${_.gray("Actor version:")} ${_.cyan(C.versionNumber)} (${_.yellow(C.buildTag)})`),l.push(N.join(" "))}else l.push(`${_.yellow("Build")}: ${_.cyan(o.buildNumber)}`);l.push(`${_.yellow("Timeout")}: ${o.options.timeoutSecs.toLocaleString("en-US")} seconds`),l.push(`${_.yellow("Memory")}: ${o.options.memoryMbytes} MB`),l.push(""),l.push(`${_.yellow("CPU")}: ${_.gray("Average:")} ${o.stats.cpuAvgUsage.toFixed(2)}% | ${_.gray("Maximum:")} ${o.stats.cpuMaxUsage.toFixed(2)}%`),l.push(`${_.yellow("Memory")}: ${_.gray("Average:")} ${ee({bytes:o.stats.memAvgBytes,shortBytes:!0})} | ${_.gray("Maximum:")} ${ee({bytes:o.stats.memMaxBytes,shortBytes:!0})}`),l.push("");let h=`https://console.apify.com/actors/${o.actId}/runs/${o.id}`,b=`https://console.apify.com/storage/datasets/${o.defaultDatasetId}`,S=`https://console.apify.com/storage/key-value-stores/${o.defaultKeyValueStoreId}`;l.push(`${_.blue("Export results")}: ${b}`),l.push(`${_.blue("View saved items")}: ${S}`),l.push(`${_.blue("View in Apify Console")}: ${h}`),R({message:l.join(`
288
+ `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:o}=e;if(!t||!o){for(let s of Object.keys(kc))wr.pushRow({"":s,Unit:"N/A","USD Amount":"N/A"});return}for(let[s,i]of Object.entries(kc)){let n=t[i]??0,a=o[i]??0;switch(i){case"ACTOR_COMPUTE_UNITS":{wr.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":{wr.pushRow({"":s,Unit:ee({bytes:n*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break}default:wr.pushRow({"":s,Unit:n.toLocaleString("en-US"),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}};var Is=class extends y{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){f({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}v({message:`Log for run with ID "${e}":
289
+ `,stdout:!0});try{await ke({job:o,apifyClient:t})}catch(s){f({message:`Failed to get log for run with ID "${e}": ${s.message}`})}}};import Ae from"chalk";var Pc=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"}}),Es=class extends y{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 He({providedActorNameOrId:n,client:a});if(!c.valid){f({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let d=await a.actor(c.id).runs().list({desc:e,limit:t,offset:o});if(i){L(d);return}if(!d.items.length){R({message:"There are no recent runs found for this Actor."});return}let l=[`${Ae.reset("Showing")} ${Ae.yellow(d.items.length)} out of ${Ae.yellow(d.total)} runs for Actor ${Ae.yellow(c.userFriendlyId)} (${Ae.gray(c.id)})`],u=new Map(await Promise.all(d.items.map(async p=>a.dataset(p.defaultDatasetId).get().then(g=>[p.id,Ae.yellow(g?.itemCount??0)],()=>[p.id,Ae.gray("N/A")]))));for(let p of d.items){let g;if(p.finishedAt){let h=p.finishedAt.getTime()-p.startedAt.getTime();g=Ae.gray(`${de.format(h,void 0,{left:""})}`)}else{let h=Date.now()-p.startedAt.getTime();g=Ae.gray(`Running for ${de.format(h,void 0,{left:""})}`)}Pc.pushRow({ID:Ae.gray(p.id),Status:_e(p.status),Results:u.get(p.id)||Ae.gray("N/A"),Usage:Ae.cyan(`$${(p.usageTotalUsd??0).toFixed(3)}`),"Started At":Zt.display(p.startedAt),Took:g,"Build No.":p.buildNumber,Origin:p.meta.origin??"UNKNOWN"})}l.push(Pc.render(s?0:1)),R({message:l.join(`
290
+ `),stdout:!0})}};import{ACTOR_JOB_STATUSES as $s}from"@apify/consts";var Up=[$s.SUCCEEDED,$s.FAILED,$s.ABORTED,$s.TIMED_OUT],Rs=class extends y{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){f({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Up.includes(o.status)){f({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}$({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(s){let i=s;f({message:`Failed to resurrect run "${e}".
291
+ ${i.message||i}`,stdout:!0})}}};import{ACTOR_JOB_STATUSES as xs}from"@apify/consts";var Mp=[xs.SUCCEEDED,xs.FAILED,xs.ABORTED,xs.TIMED_OUT],_s=class extends y{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})};async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){f({message:`Run with ID "${e}" was not found on your account.`});return}if(!Mp.includes(o.status)){f({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?"})){v({message:`Deletion of run "${e}" was canceled.`});return}try{await t.run(e).delete(),$({message:`Run with ID "${e}" was deleted.`})}catch(i){let n=i;f({message:`Failed to delete run "${e}".
292
+ ${n.message||n}`})}}};var ks=class extends y{static name="runs";static description=`Inspect, abort, resurrect, or delete existing Actor runs.
293
+ 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=[Ts,Cs,Is,Es,Rs,_s];async run(){this.printHelp()}};var Ps=class extends y{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;La(e,t)}};import jp from"chalk";var Oc=new B({allColumns:["Secret Name"],mandatoryColumns:["Secret Name"],columnAlignments:{"Secret Name":"left"}}),Os=class extends y{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=Dt(),o=Object.keys(t);if(e){L({keys:o});return}if(o.length===0){v({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)Oc.pushRow({"Secret Name":jp.cyan(s)});R({message:Oc.render(1),stdout:!0})}};var Ns=class extends y{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;Da(e)}};var Ls=class extends y{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=[Ps,Os,Ns];async run(){this.printHelp()}};import Nc from"chalk";var Ds=class extends y{static name="run";static description=`Executes predefined Actor task remotely using local key-value store for input.
294
+ Customize with --memory and --timeout flags.
295
+ `;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=Nt("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,d,l=Ot(e,{actorOrTaskData:{id:s,userFriendlyId:i,title:n},runOptions:a,type:"Task",printRunLogs:!0});for await(let u of l)c=`https://console.apify.com/actors/${u.actId}/runs/${u.id}`,d=`https://console.apify.com/storage/datasets/${u.defaultDatasetId}`;R({message:["",`${Nc.blue("Export results")}: ${d}`,`${Nc.blue("View on Apify Console")}: ${c}`].join(`
296
+ `),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 Fs=class extends y{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=[Ds];async run(){this.printHelp()}};var Us=class extends y{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 me()).enabled?(await Mr(!1),$({message:"Telemetry disabled."})):v({message:"Telemetry is already disabled."})}};var Ms=class extends y{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 me()).enabled?v({message:"Telemetry is already enabled."}):(await Mr(!0),$({message:"Telemetry enabled."}))}};var Ar=class extends y{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=[Ms,Us];async run(){this.printHelp()}};import Bp from"process";var js=class extends y{static name="validate-schema";static description=`Validates Actor input schema from one of these locations (in priority order):
297
+ 1. Object in '${D}' under "input" key
298
+ 2. JSON file path in '${D}' "input" key
299
+ 3. .actor/INPUT_SCHEMA.json
300
+ 4. INPUT_SCHEMA.json
301
+
302
+ 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 co({forcePath:this.args.path,cwd:Bp.cwd(),getMessage:m(e=>e?`Validating input schema at ${e}`:`Validating input schema embedded in '${D}'`,"getMessage")}),$({message:"Input schema is valid."})}};var $O=[fo,Io,$o,Lo,Ko,ms,ys,ks,Ls,Fs,Ar,Do,fr,pr,Uo,Wo,Xo,ts,es,us,ps,fs,gs,bs,js,gr],RO=[_t,xt,Rt,$t,Et,vt,At,It,gr,fr,pr,Ar];export{dw as a,mw as b,$O as c,RO as d};
303
+ //# sourceMappingURL=chunk-B2LAUVVL.js.map