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

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