apify-cli 1.3.1-beta.2 → 1.3.1-beta.3

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