apify-cli 1.2.2-beta.21 → 1.2.2-beta.22

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