apify-cli 1.4.2-beta.9 → 1.5.1-beta.0
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.
- package/CHANGELOG.md +9 -3
- package/dist/_register-DfdmUmaY.js +218 -0
- package/dist/_register-DfdmUmaY.js.map +1 -0
- package/dist/actor.js +1 -1
- package/dist/actor.js.map +1 -1
- package/dist/apify.js +1 -1
- package/dist/apify.js.map +1 -1
- package/dist/index.js +3 -1
- package/package.json +3 -3
- package/dist/.tsbuildinfo +0 -1
- package/dist/chunk-XLY3B6IF.js +0 -307
- package/dist/chunk-XLY3B6IF.js.map +0 -1
package/dist/chunk-XLY3B6IF.js
DELETED
|
@@ -1,307 +0,0 @@
|
|
|
1
|
-
var Hc=Object.defineProperty;var m=(r,e)=>Hc(r,"name",{value:e,configurable:!0});import xe from"process";import{parseArgs as ua}from"util";import lo from"chalk";import{satisfies as Zd}from"semver";import bt from"process";import gi from"chalk";import xd from"indent-string";import _d from"widest-line";import Pd from"wrap-ansi";import Ki from"ci-info";var Jc=[["CLAUDECODE","claude_code"],["CLAUDE_CODE_ENTRYPOINT","claude_code"],["CURSOR_AGENT","cursor"],["CLINE_ACTIVE","cline"],["CODEX_SANDBOX","codex_cli"],["CODEX_THREAD_ID","codex_cli"],["GEMINI_CLI","gemini_cli"],["OPENCODE","open_code"],["OPENCLAW_SHELL","openclaw"]];function Wi(){for(let[r,e]of Jc)if(process.env[r])return e}m(Wi,"detectAiAgent");function zi(){return Ki.isCI?{isCi:!0,ciProvider:Ki.id?.toLowerCase()??"unknown"}:{isCi:!1,ciProvider:void 0}}m(zi,"detectCi");function Xi(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}m(Xi,"detectIsInteractive");import qc from"chalk";function T(r,...e){process.env.APIFY_CLI_DEBUG&&console.error(qc.gray(`[${r}]`),...e)}m(T,"cliDebugPrint");import{realpathSync as Kc}from"fs";import{dirname as Wc}from"path";import gt from"chalk";function tt(r){r.stdoutOutput&&console.log(...r.stdoutOutput),r.stderrOutput&&console.error(...r.stderrOutput)}m(tt,"internalLog");function $(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[r.message]})}m($,"simpleLog");function g(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.red("Error:"),r.message]})}m(g,"error");function x(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.yellow.bold("Warning:"),r.message]})}m(x,"warning");function R(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.green("Success:"),r.message]})}m(R,"success");function Ce(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.gray("Run:"),r.message]})}m(Ce,"run");function b(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.white("Info:"),r.message]})}m(b,"info");function Js(r){tt({[r.stdout?"stdoutOutput":"stderrOutput"]:[gt.blue(r.message),r.url]})}m(Js,"link");var qs="0.0.0";var zc="1.4.2-beta.9",Xc="f7ed07ab108221c9f40a84149f1a8c43fe4a53f0";function Zc(){if(process.env.APIFY_CLI_MARKED_INSTALL_METHOD)return process.env.APIFY_CLI_MARKED_INSTALL_METHOD;if(process.env.APIFY_CLI_BUNDLE)return"bundle";let r=process.argv[1];if(!r)return x({message:"Failed to detect install method of CLI, assuming npm"}),"npm";let e=Kc(r);return process.env.VOLTA_HOME&&e.includes(process.env.VOLTA_HOME)?"volta":e.includes("homebrew/Cellar")||e.includes("linuxbrew/Cellar")?"homebrew":process.env.PNPM_HOME&&e.includes(process.env.PNPM_HOME)?"pnpm":process.env.BUN_INSTALL&&e.includes(process.env.BUN_INSTALL)?"bun":"npm"}m(Zc,"detectInstallMethod");function Qc(){return process.versions.bun?{runtime:"bun",version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:"deno",version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:"node",version:process.versions.node}}m(Qc,"getRuntimeInfo");var Gt=null;function z(){if(Gt)return Gt;let r=Zc(),e=Qc();return Gt={version:zc,hash:Xc,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===qs}},r==="bundle"&&(Gt.installPath=Wc(process.execPath)),Gt}m(z,"useCLIMetadata");import{existsSync as Ul,mkdirSync as Ml,readFileSync as jl,writeFileSync as Bl}from"fs";import{dirname as Vl}from"path";import{cryptoRandomObjectId as Gl}from"@apify/utilities";import{homedir as tl}from"os";import{join as rt}from"path";import{KEY_VALUE_STORE_KEYS as rl,META_ORIGINS as ol}from"@apify/consts";var Zi={name:"apify-cli",version:"1.4.2-beta.9",description:"Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",exports:"./dist/index.js",type:"module",scripts:{"dev:apify":"tsx ./src/entrypoints/apify.ts","dev:actor":"tsx ./src/entrypoints/actor.ts","test:all":"yarn test:local && yarn test:api","test:local":"vitest run --testNamePattern '^((?!\\[api]).)*$' --exclude ./test/api --exclude ./test/e2e","test:e2e":"vitest run --testNamePattern '\\[e2e\\]' --exclude ./test/api","test:e2e:local":"vitest run --testNamePattern '^(?=.*\\[e2e\\])(?!.*\\[api\\]).*$' --exclude ./test/api","test:api":"vitest run --testNamePattern '^(?=.*\\[api\\])(?!.*\\[e2e\\]).*$' --exclude ./test/e2e","test:python":"vitest run --testNamePattern '\\[python\\]'",lint:"eslint src test scripts --ext .ts,.cjs,.mjs","lint:fix":"eslint src test scripts --fix --ext .ts,.cjs,.mjs",format:'biome format . && prettier --check "**/*.{md,yml,yaml}"',"format:fix":'biome format --write . && prettier --write "**/*.{md,yml,yaml}"',clean:"rimraf dist",build:"yarn clean && tsc && tsup","build-bundles":"bun run scripts/build-cli-bundles.ts",prepack:"yarn insert-cli-metadata && yarn build && yarn update-docs","insert-cli-metadata":"tsx scripts/insert-cli-metadata.ts","update-docs":"tsx scripts/generate-cli-docs.ts",postinstall:`node -e "console.log('We have an active developer community on Discord. You can find it on https://discord.gg/crawlee-apify-801163717915574323.');"`,prepare:"husky"},files:["dist"],bin:{actor:"./dist/actor.js",apify:"./dist/apify.js","apify-cli":"./dist/apify.js"},contributors:["Jakub Drobn\xEDk <jakub.drobnik@apify.com>","Jan Curn <jan@apify.com>","Vlad Frangu <vlad.frangu@apify.com>"],repository:{type:"git",url:"git+https://github.com/apify/apify-cli.git"},keywords:["apify","client","node","command","line","bash"],author:{name:"Apify",email:"support@apify.com",url:"https://www.apify.com"},license:"Apache-2.0",bugs:{url:"https://github.com/apify/apify-cli/issues"},homepage:"https://github.com/apify/apify-cli#readme",engines:{node:">=20"},dependencies:{"@apify/actor-memory-expression":"^0.1.12","@apify/actor-templates":"^0.1.5","@apify/consts":"^2.36.0","@apify/input_schema":"^3.17.0","@apify/utilities":"^2.18.0","@crawlee/memory-storage":"^3.12.0","@inquirer/core":"^11.0.0","@inquirer/input":"^5.0.0","@inquirer/password":"^5.0.0","@inquirer/select":"^5.0.0","@root/walk":"~1.1.0","@sapphire/duration":"^1.1.2","@sapphire/result":"^2.7.2","@sapphire/timestamp":"^1.0.3","@skyra/jaro-winkler":"^1.1.1","adm-zip":"~0.5.15",ajv:"~8.18.0","apify-client":"^2.22.0",archiver:"~7.0.1",axios:"^1.15.0",chalk:"~5.6.0","ci-info":"~4.4.0","cli-table3":"^0.6.5","computer-name":"~0.1.0",configparser:"~0.3.10",cors:"~2.8.5","detect-indent":"~7.0.1","es-toolkit":"^1.45.1","escape-string-regexp":"~5.0.0",execa:"^9.5.2",express:"~5.2.0",handlebars:"~4.7.8",ignore:"^7.0.0","indent-string":"^5.0.0","is-ci":"~4.1.0",istextorbinary:"~9.5.0",jju:"~1.4.0","js-levenshtein":"^1.1.6","json-schema-to-typescript":"^15.0.4",mime:"~4.1.0",open:"~11.0.0",rimraf:"~6.1.0",semver:"~7.7.0","string-width":"^8.0.0","strip-ansi":"^7.1.0",tiged:"~2.12.7",tinyglobby:"^0.2.15",which:"^6.0.0","widest-line":"^6.0.0","wrap-ansi":"^10.0.0"},devDependencies:{"@apify/eslint-config":"^1.0.0","@apify/tsconfig":"^0.1.1","@biomejs/biome":"^2.0.0","@crawlee/types":"^3.11.1","@types/adm-zip":"^0.5.5","@types/archiver":"^7.0.0","@types/bun":"^1.2.5","@types/cors":"^2.8.17","@types/execa":"^2.0.2","@types/express":"^5.0.0","@types/jju":"^1.4.5","@types/js-levenshtein":"^1","@types/mime":"^4.0.0","@types/node":"^24.0.0","@types/semver":"^7.5.8","@types/which":"^3.0.4","@yarnpkg/core":"^4.1.2",apify:"^3.2.4","cross-env":"^10.0.0",eslint:"^9.25.1","eslint-config-prettier":"^10.1.2",husky:"^9","lint-staged":"^16.0.0","mock-stdin":"^1.0.0",prettier:"^3.5.3",tsup:"^8.5.0",tsx:"^4.16.5",typescript:"^6.0.0","typescript-eslint":"^8.31.0",vitest:"^4.0.0"},volta:{node:"24.14.1",yarn:"4.13.0"},packageManager:"yarn@4.13.0",devEngines:{runtime:[{name:"node",version:">= 20",onFail:"error"},{name:"bun",version:">= 1.2.5",onFail:"ignore"}],packageManager:{name:"yarn",version:">= 4",onFail:"warn"}},"lint-staged":{"*":"biome format --write --no-errors-on-unmatched","*.{mjs,js,ts}":"eslint --fix --ext mjs,js,ts","*.md":"prettier --write"},resolutions:{tar:"7.5.13"}};var ot="storage",Ks="apify_storage",Ws=1,Ir={actorSpecification:Ws,name:null,version:"0.0",buildTag:"latest",environmentVariables:{}},Qi=1440*60*1e3,ht=m(()=>{let r=rt(tl(),".apify");return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?rt(r,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):r},"GLOBAL_CONFIGS_FOLDER"),ge=m(()=>rt(ht(),"auth.json"),"AUTH_FILE_PATH"),Er=m(()=>rt(ht(),"secrets.json"),"SECRETS_FILE_PATH"),$r=m(()=>rt(ht(),"state.json"),"STATE_FILE_PATH"),Rr=m(()=>rt(ht(),"telemetry.json"),"TELEMETRY_FILE_PATH"),xr="apify.json",_r=".actor",sl="actor.json",D=rt(_r,sl),zs=new RegExp(`(^${rl.INPUT}(?:\\.[^.]+)?$)`),Ie=Zi.engines.node,Pr={"X-Apify-Request-Origin":ol.CLI},st="3.9.0",en=".venv";import{execSync as ul}from"child_process";import{createWriteStream as pl,existsSync as oe,mkdirSync as fl,readdirSync as an,readFileSync as Wt,writeFileSync as Or}from"fs";import{mkdir as gl,readFile as Nr}from"fs/promises";import{get as hl}from"https";import{homedir as Xs}from"os";import{dirname as yt,join as q,relative as yl}from"path";import X from"process";import{finished as wl}from"stream/promises";import{DurationFormatter as cn,TimeTypes as it}from"@sapphire/duration";import{Timestamp as Zs}from"@sapphire/timestamp";import Al from"adm-zip";import vl from"ajv/dist/2019.js";import{ApifyClient as ln}from"apify-client";import bl from"archiver";import{AxiosHeaders as Sl}from"axios";import Tl from"escape-string-regexp";import Cl from"ignore";import{getEncoding as Il}from"istextorbinary";import{Mime as El}from"mime";import $l from"mime/types/other.js";import Rl from"mime/types/standard.js";import{gte as xl,minVersion as _l,satisfies as Pl}from"semver";import{glob as Qs}from"tinyglobby";import{ACTOR_ENV_VARS as ei,ACTOR_JOB_TERMINAL_STATUSES as kl,ACTOR_NAME as qt,APIFY_ENV_VARS as Ol,KEY_VALUE_STORE_KEYS as nn,LOCAL_ACTOR_ENV_VARS as ti,LOCAL_STORAGE_SUBDIRS as ri,SOURCE_FILE_FORMATS as Jt}from"@apify/consts";import{existsSync as il,mkdirSync as nl}from"fs";import{readFile as al,stat as tn,unlink as cl,writeFile as ll}from"fs/promises";import{join as rn,sep as dl}from"path";import{rimraf as ml}from"rimraf";var on=m(async(r,e={},t=null)=>{let o=await al(r,"utf-8"),s=JSON.parse(o),i;t?(i=s,i[t]={...s[t],...e}):i={...s,...e},await ll(r,JSON.stringify(i,null," "))},"updateLocalJson"),kr=m((r,e)=>{e||(e=r,r="."),e.split(dl).reduce((o,s)=>(o=rn(o,s),il(o)||nl(o),o),r)},"ensureFolderExistsSync"),Yt=m(async r=>{await ml(r)},"rimrafPromised"),Ht=m(async r=>{(await tn(r)).isFile()&&await cl(r)},"deleteFile"),sn=m(async(r,e)=>(await Promise.all(r.map(async s=>tn(rn(e,s))))).map(s=>s.size).reduce((s,i)=>s+i,0),"sumFilesSizeInBytes");var Kt=Cl,zt=vl,Lr=m(async r=>new Promise((e,t)=>{hl(r,o=>{o.statusCode===301||o.statusCode===302?(e(Lr(o.headers.location)),o.destroy()):e(o)}).on("error",t)}),"httpsGet"),we=m(()=>{let r=Ol.LOCAL_STORAGE_DIR;return X.env[r]||X.env.CRAWLEE_STORAGE_DIR||ot},"getLocalStorageDir"),he=m(r=>{let e=ei.DEFAULT_KEY_VALUE_STORE_ID,t=r||X.env[e]||ti[e];return q(we(),ri.keyValueStores,t)},"getLocalKeyValueStorePath"),dn=m(r=>{let e=ei.DEFAULT_DATASET_ID,t=r||X.env[e]||ti[e];return q(we(),ri.datasets,t)},"getLocalDatasetPath"),mn=m(r=>{let e=ei.DEFAULT_REQUEST_QUEUE_ID,t=r||X.env[e]||ti[e];return q(we(),ri.requestQueues,t)},"getLocalRequestQueuePath"),M=m(async()=>{let r={};try{let e=await Nr(ge(),"utf-8");r=JSON.parse(e)}catch{return{}}if(!r.username&&!r.id)throw new Error('Corrupted local user info was found. Please run "apify login" to fix it.');return r},"getLocalUserInfo");async function I(){let r=await Zt();if(!r)throw X.exitCode=1,new Error('You are not logged in with your Apify account. Call "apify login" to fix that.');return r}m(I,"getLoggedClientOrThrow");var un=m(r=>{if(!r&&oe(ht())&&oe(ge())){let e=Wt(ge(),"utf-8");return JSON.parse(e).token}return r},"getTokenWithAuthFileFallback"),Xt=m((r,e)=>(r=un(r),{token:r,baseUrl:e||X.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[t=>{t.headers??=new Sl;for(let[o,s]of Object.entries(Pr))t.headers[o]=s;return t}]}),"getApifyClientOptions");async function Zt(r,e){r=un(r);let t=new ln(Xt(r,e)),o;try{o=await t.user("me").get()}catch(s){return T("[getLoggedClient] error getting user info",{error:s,apiBaseUrl:e}),null}return si(ge()),Or(ge(),JSON.stringify({token:t.token,...o},null," ")),t}m(Zt,"getLoggedClient");var oi=m(r=>q(r,D),"getLocalConfigPath"),de=m(r=>{if(oe(r))return JSON.parse(Wt(r,{encoding:"utf-8"}))},"getJsonFileContent"),Me=m(r=>de(oi(r)),"getLocalConfig"),Dr=m(async(r,e)=>{let t=q(e||X.cwd(),D);await gl(yt(t),{recursive:!0}),Or(t,JSON.stringify(r,null," "))},"setLocalConfig"),Nl=[we(),"node_modules",".venv"],Fr=m(async r=>{let e=he();kr(r,dn()),kr(r,mn()),kr(r,e);let t=q(r,".gitignore"),o="";oe(t)&&(o=Wt(t,{encoding:"utf-8"}));let s=[];for(let i of Nl)RegExp(`^${Tl(i)}$`,"mg").test(o)||s.push(i);s.length>0&&(o.length>0?(s.unshift("# Added by Apify CLI"),Or(t,`
|
|
2
|
-
${s.join(`
|
|
3
|
-
`)}
|
|
4
|
-
`,{flag:"a"})):Or(t,`${s.join(`
|
|
5
|
-
`)}
|
|
6
|
-
`,{flag:"w"}))},"setLocalEnv"),pn=new El(Rl,$l).define({"application/gzip":["tgz"],"text/typescript":["ts","tsx","mts"]},!0),Ll=m((r,e)=>{let t=pn.getType(r);return t?t.startsWith("text/")||t.includes("javascript")||t.includes("json")||t.includes("xml")||t.includes("application/node")||t.includes("application/toml")||t.includes("application/x-sh")||t.includes("application/x-httpd-php")?Jt.TEXT:Jt.BASE64:Il(e)==="binary"?Jt.BASE64:Jt.TEXT},"getSourceFileFormat"),fn=m(async(r,e)=>r.map(t=>{let o=Wt(q(e,t)),s=Ll(t,o);return{name:t,format:s,content:s===Jt.TEXT?o.toString("utf8"):o.toString("base64")}}),"createSourceFiles"),Dl=m(async r=>{let e=await Qs("**/.gitignore",{dot:!0,cwd:r,ignore:[".git/**"],expandDirectories:!1}),t=[];for(let s of e){let i=yt(s),n=await Nr(q(r,s),"utf-8");t.push({dir:i==="."?"":i,ig:Kt().add(n)})}let o=yt(r);for(;o!==yt(o)&&!oe(q(o,".git"));){let s=q(o,".gitignore");if(oe(s))try{let i=await Nr(s,"utf-8"),n=yl(o,r);t.push({dir:"",ig:Kt().add(i),ancestorPrefix:n})}catch{}o=yt(o)}return t.length===0?s=>s:s=>s.filter(i=>{for(let{dir:n,ig:a,ancestorPrefix:c}of t){let l;if(n?i.startsWith(`${n}/`)?l=i.slice(n.length+1):l=null:l=c?`${c}/${i}`:i,l!==null&&a.ignores(l))return!1}return!0})},"getGitignoreFallbackFilter"),Fl=m(async r=>{let e=q(r,".actorignore");if(!oe(e))return{excludeFilter:null,forceIncludePatterns:[]};let o=(await Nr(e,"utf-8")).split(`
|
|
7
|
-
`),s=[],i=[];for(let a of o){let c=a.trim();!c||c.startsWith("#")||(c.startsWith("!")?i.push(c.slice(1)):s.push(c))}return{excludeFilter:s.length>0?a=>{let c=Kt().add(s);return a.filter(l=>!c.ignores(l))}:null,forceIncludePatterns:i}},"parseActorIgnore"),gn=m(async r=>{let e=r??X.cwd(),t=[".git/**","apify_storage","node_modules","storage","crawlee_storage"],{excludeFilter:o,forceIncludePatterns:s}=await Fl(e),i=null;try{let l=ul("git ls-files --others --ignored --exclude-standard --directory",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
8
|
-
`).filter(Boolean);if(l.length>0){let d=Kt().add(l);i=m(u=>u.filter(p=>!d.ignores(p)),"gitIgnoreFilter")}}catch{i=await Dl(e)}let n=await Qs(["*","**/**"],{ignore:t,dot:!0,expandDirectories:!1,cwd:e}),a=i?i(n):n;if(o&&(a=o(a)),s.length>0){let l=Kt().add(s),d=n.filter(p=>l.ignores(p)),u=new Set(a);for(let p of d)u.add(p);a=[...u]}let c=n.filter(l=>l===".actor"||l.startsWith(".actor/"));if(c.length>0){let l=new Set(a);for(let d of c)l.add(d);a=[...l]}return a},"getActorLocalFilePaths"),hn=m(async(r,e,t)=>{oe(r)&&await Ht(r);let o=pl(r),s=bl("zip",{zlib:{level:6}});s.pipe(o),e.forEach(i=>s.file(q(t,i),{name:i})),await s.finalize()},"createActZip"),Qt=m(r=>{let e=he();if(!oe(q(r,e)))return;let s=an(q(r,e)).find(a=>!!a.match(zs));if(!s)return;let i=Wt(q(r,e,s)),n=pn.getType(s);return{body:i,contentType:n,fileName:s}},"getLocalInput"),yn=m(async()=>{let r=mn();oe(we())&&oe(r)&&await Yt(r)},"purgeDefaultQueue"),wn=m(async()=>{let r=dn();oe(we())&&oe(r)&&await Yt(r)},"purgeDefaultDataset"),An=m(async()=>{let r=he();if(!oe(we())||!oe(r))return;let e=an(r),t=[];e.forEach(o=>{o.match(zs)||t.push(Ht(q(r,o)))}),await Promise.all(t)},"purgeDefaultKeyValueStore"),ke=m(async({job:r,timeoutMillis:e,apifyClient:t})=>{let{id:o,status:s}=r,i=t||new ln({baseUrl:X.env.APIFY_CLIENT_BASE_URL});if(kl.includes(s)){if(X.env.APIFY_NO_LOGS_IN_TESTS)return;let n=await i.log(o).get();X.stderr.write(n);return}return new Promise(async n=>{let a=await i.log(o).stream();if(!a){n("no-logs");return}let c=null;a.on("data",l=>{X.env.APIFY_NO_LOGS_IN_TESTS||X.stderr.write(l.toString())}),a.once("end",()=>{n("finished"),c&&clearTimeout(c)}),e&&(c=setTimeout(()=>{a.destroy(),n("timeouts")},e))})},"outputJobLog");var vn=m(async()=>(await Qs([`${we()}/**`,`!${he()}/${nn.INPUT}.*`,`!${he()}/${nn.INPUT}_CLI-*`])).length===0,"checkIfStorageIsEmpty"),er=m(r=>{if(!qt.REGEX.test(r))throw new Error("The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).");if(r.length<qt.MIN_LENGTH)throw new Error("The Actor name must be at least 3 characters long.");if(r.length>qt.MAX_LENGTH)throw new Error("The Actor name must be a maximum of 30 characters long.")},"validateActorName"),Ur=m(r=>{let e=r.replaceAll(/[^a-zA-Z0-9-]/g,"-");return e.length<qt.MIN_LENGTH&&(e=`${e}-apify-actor`),e=e.replaceAll(/^-+/g,"").replaceAll(/-+$/g,""),e.slice(0,qt.MAX_LENGTH)},"sanitizeActorName"),Mr=m(r=>Pl(r,`^${st}`),"isPythonVersionSupported"),jr=m(r=>{let e=_l(Ie);return xl(r,e)},"isNodeVersionSupported"),Br=m(async({url:r,pathTo:e})=>{let t=await Lr(r),o=[];t.on("data",i=>o.push(i)),await wl(t),new Al(Buffer.concat(o)).extractAllTo(e,!0)},"downloadAndUnzip");function si(r){let e=yt(r);fl(e,{recursive:!0})}m(si,"ensureApifyDirectory");var Y=new Zs("YYYY-MM-DD [at] HH:mm:ss"),tr=new Zs(`YYYY-MM-DD[
|
|
9
|
-
]HH:mm:ss`),bn=new Zs("YYYY-MM-DD"),rr=new cn,me=new cn({[it.Day]:{DEFAULT:"d"},[it.Hour]:{DEFAULT:"h"},[it.Minute]:{DEFAULT:"m"},[it.Month]:{DEFAULT:"M"},[it.Second]:{DEFAULT:"s"},[it.Week]:{DEFAULT:"w"},[it.Year]:{DEFAULT:"y"}});function Vr(r,e){if("groupBy"in Object)return Object.groupBy(r,e);let t={},o=0;for(let s of r){let i=e(s,o++);t[i]||(t[i]=[]),t[i].push(s)}return t}m(Vr,"objectGroupBy");function L(r){console.log(JSON.stringify(r,null,2))}m(L,"printJsonToStdout");var le=m(r=>r.startsWith(Xs())?r.replace(Xs(),"~"):r,"tildify");function Sn(){let r=X.env.SHELL??"";return r.includes("zsh")?"zsh":r.includes("bash")?"bash":r.includes("fish")?"fish":"unknown"}m(Sn,"detectShell");function Tn(r,e){switch(e){case"bash":{let t=[q(r,".bashrc"),q(r,".bash_profile")];X.env.XDG_CONFIG_HOME&&t.push(q(X.env.XDG_CONFIG_HOME,".bashrc"),q(X.env.XDG_CONFIG_HOME,".bash_profile"),q(X.env.XDG_CONFIG_HOME,"bashrc"),q(X.env.XDG_CONFIG_HOME,"bash_profile"));for(let o of t)if(oe(o))return o;return null}case"zsh":{let t=X.env.ZDOTDIR||Xs();return q(t,".zshrc")}case"fish":return q(r,".config","fish","config.fish");case"unknown":return null}}m(Tn,"shellConfigFile");var Yl=["Apify collects telemetry data about general usage of Apify CLI to help us improve the product.",'This feature is enabled by default, and you can disable it by setting the "APIFY_CLI_DISABLE_TELEMETRY" environment variable to "1", or by running "apify telemetry disable".',"You can find more information about our telemetry in https://docs.apify.com/cli/docs/telemetry."].join(`
|
|
10
|
-
`);function Cn(){return`CLI:${Gl()}`}m(Cn,"createAnonymousId");async function Hl(r){if(r.version&&r.version>=1)return!1;let e=r,t=await M().catch(()=>({}));return or({version:1,enabled:!0},o=>{t.id&&e.distinctId===t.id?(o.anonymousId=Cn(),o.userId=t.id):o.anonymousId=e.distinctId}),!0}m(Hl,"migrateStateV0ToV1");async function ue(){let r=Rr();if(!Ul(r)){let s=await M().catch(()=>({}));return or({version:1,enabled:!0,anonymousId:Cn(),userId:s.id}),(!process.env.APIFY_CLI_DISABLE_TELEMETRY||["false","0"].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))&&b({message:Yl}),ue()}let t=JSON.parse(jl(r,"utf-8"));return await Hl(t)?ue():t}m(ue,"useTelemetryState");function or(r,e){let t={...r};e?.(t);let o=Rr(),s=Vl(o);Ml(s,{recursive:!0}),Bl(Rr(),JSON.stringify(t,null," "))}m(or,"updateTelemetryState");async function Gr(r){let e=await ue();or(e,t=>{t.userId=r})}m(Gr,"updateUserId");var Jl=1e4;async function In(r){try{let e=await ue(),t=Date.now(),o=e.lastCommand===r&&t-(e.lastCommandTimestamp??0)<Jl;return or(e,s=>{s.lastCommand=r,s.lastCommandTimestamp=t}),o}catch{return!1}}m(In,"checkAndUpdateLastCommand");async function Yr(r){let e=await ue();or(e,t=>{t.enabled=r})}m(Yr,"updateTelemetryEnabled");async function En(){if(process.env.APIFY_CLI_DISABLE_TELEMETRY&&!["false","0"].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))return T("telemetry","disabled by env variable"),!1;let r=await ue();return T("telemetry state",{telemetryState:r}),r.enabled}m(En,"useTelemetryEnabled");async function $n(){let r=await ue();return{anonymousId:r.anonymousId,userId:r.userId}}m($n,"useTelemetryIdentifiers");var sr=z(),ql="https://api.segment.io/v1/track",Kl=sr.isBeta?"rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC":"2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t";async function Rn(r,e){let t=await $n(),o={anonymousId:t.anonymousId,context:{app:{name:"apify-cli",version:sr.version,build:sr.hash},library:{name:"apify-cli",version:sr.version},os:{name:sr.platform},userAgent:nt,channel:"server"},event:r,properties:{...e,app:"cli"},timestamp:new Date().toISOString(),userId:t.userId,writeKey:Kl};if(T("trackEvent",o),!await En()){T("trackEvent","telemetry disabled");return}try{let i=await fetch(ql,{method:"POST",body:JSON.stringify(o)});if(!i.ok){T("trackEvent","failed to send event",await i.text());return}T("trackEvent","event sent")}catch(i){T("trackEvent","failed to send event",i)}}m(Rn,"trackEvent");import{access as li,readdir as wt,readFile as md,stat as ud}from"fs/promises";import{join as j,resolve as Gn}from"path";import pd from"process";import{err as fd,ok as ci}from"@sapphire/result";import{existsSync as kn,readdirSync as td}from"fs";import{join as Kr,resolve as rd}from"path";import od from"configparser";import Ql from"@inquirer/input";import Zl from"is-ci";import{constants as xn,fstat as Wl}from"fs";import _n from"process";import{promisify as zl}from"util";var Xl=zl(Wl),ii;async function Hr(){if(ii)return ii;let r=_n.stdin,e={isTTY:r.isTTY,hasData:!1,waitDelay:0,stream:r},t=await Xl(0).then(o=>{if(T("useStdin",{stat:o,isRegularFile:o.isFile(),isDirectory:o.isDirectory(),isBlockDevice:o.isBlockDevice(),isCharDevice:o.isCharacterDevice(),isSymbolicLink:o.isSymbolicLink(),isFIFO:o.isFIFO(),isSocket:o.isSocket()}),_n.platform==="win32"){if((o.mode&xn.S_IFIFO)===xn.S_IFIFO)return 100;if(o.isFile())return 50}return o.isFIFO()||o.isFile()||(o.isSocket()?50:!1)}).catch(()=>!1);return T("useStdin",{hasData:e.hasData,waitDelay:e.waitDelay,isTTY:e.isTTY,pipedIn:t,readableEnded:r.readableEnded}),(!r.isTTY||t!==!1&&(r.isTTY!==void 0||!r.readableEnded))&&(e.hasData=!0),typeof t=="number"&&(e.waitDelay=t),ii=e,e}m(Hr,"useStdin");var ni="confirm",Pn=`no-${ni}`;function Oe(r,{errorMessageForStdin:e=`Please use the --${ni}/--${Pn} flags to confirm the action.`}={}){return async(t,...o)=>{let{isTTY:s,hasData:i}=await Hr(),n=t;if(Zl||!s&&!i){if(typeof n.providedConfirmFromStdin>"u")throw new Error(n.errorMessageForStdin??e??`Please use the --${ni}/--${Pn} flags to confirm the action.`);return n.providedConfirmFromStdin}return await r(t,...o)}}m(Oe,"stdinCheckWrapper");var at=Oe(async({message:r,validate:e,default:t})=>await Ql({message:r,validate:e,default:t}),{errorMessageForStdin:"Please provide a valid input based on the command options."});import{readFileSync as ed}from"fs";var Jr=class{static{m(this,"Spider")}name;class_name;start_urls;pathname;constructor(e){this.name=e.name,this.class_name=e.class_name,this.start_urls=e.start_urls,this.pathname=e.pathname}};var qr=class{static{m(this,"SpiderFileAnalyzer")}pathname;constructor(e){this.pathname=e}getSpiders(){let e=ed(this.pathname,"utf8"),t=/class\s+(\w+)/g,o=[],s=t.exec(e);for(;s;)o.push(new Jr({class_name:s[1],pathname:this.pathname})),s=t.exec(e);return o}};var ct=class{static{m(this,"ScrapyProjectAnalyzer")}pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return kn(Kr(e,"scrapy.cfg"))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new od,t=rd(Kr(this.pathname,"scrapy.cfg"));if(!kn(t))throw new Error(`scrapy.cfg not found in "${t}".
|
|
11
|
-
Are you sure there is a Scrapy project there?`);e.read(t),this.configuration=e}async loadSettings(){let e=this.configuration.get("settings","default").split(".")[0],t=await at({message:"Enter the Scrapy BOT_NAME (see settings.py):",default:e}),o=await at({message:"What folder are the Scrapy spider modules stored in? (see SPIDER_MODULES in settings.py):",default:`${e}.spiders`});this.settings={BOT_NAME:t,SPIDER_MODULES:typeof o=="string"?[o]:o}}getName(){return this.settings?.BOT_NAME}getAvailableSpiders(){let e=this.settings?.SPIDER_MODULES;if(!e)throw new Error("SPIDER_MODULES path not found in settings.");let t=[];for(let o of e){let s=Kr(this.pathname,o.replaceAll(".","/")),i=td(s,{withFileTypes:!0});for(let n of i)n.isFile()&&n.name.endsWith(".py")&&n.name!=="__init__.py"&&t.push(...new qr(Kr(s,n.name)).getSpiders())}return t}};import ai from"process";import{none as Nn,some as Ln}from"@sapphire/result";import{execa as Fn}from"execa";import Dn from"which";import{stat as Wr}from"fs/promises";import{isAbsolute as sd,join as zr}from"path";function Ge(r){return r?r.startsWith('"')?r:sd(r)&&r.includes(" ")?`"${r}"`:r:null}m(Ge,"normalizeExecutablePath");async function On(r){let e=null;return await(await Ne({cwd:r})).inspectAsync(async o=>{if(o.type===0){let[s,i,n,a]=await Promise.all([Wr(zr(r,"yarn.lock")).then(()=>!0).catch(()=>!1),Wr(zr(r,"pnpm-lock.yaml")).then(()=>!0).catch(()=>!1),Wr(zr(r,"bun.lockb")).then(()=>!0).catch(()=>!1),Wr(zr(r,"bun.lock")).then(()=>!0).catch(()=>!1)]);s?e="yarn install":i?e="pnpm install":n||a||o.runtime?.pmName==="bun"?e="bun install":o.runtime?.pmName==="deno"?e="deno install --node-modules-dir":e="npm install"}else(o.type===1||o.type===2)&&(e="python -m pip install -r requirements.txt")}),e}m(On,"getInstallCommandSuggestion");var Xr=new Map,id={node:["--version"],deno:["eval",'"console.log(process.versions.node)"'],bun:["--eval",'"console.log(process.versions.node)"']};async function nd(r,e){try{let t=await Fn(r,e,{shell:!0,windowsHide:!0,verbose:ai.env.APIFY_CLI_DEBUG?"full":void 0});return t.stdout?t.stdout.trim().replace(/^v/,""):null}catch{return null}}m(nd,"getRuntimeVersion");async function ad(r){let e=await Fn(r,["--version"],{shell:!0,windowsHide:!0,verbose:ai.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim().replace(/^v/,""):null}m(ad,"getNpmVersion");async function Un(r=ai.cwd()){let e=Xr.get(r);if(e)return T("useJavaScriptRuntime",{cacheHit:!0,cwd:r,runtime:e.unwrapOr(null)}),e;for(let[t,o]of Object.entries(id))try{let s=Ge(await Dn(t)),i=await nd(s,o);if(i){let n={executablePath:s,version:i};if(t==="node"){let a=Ge(await Dn("npm").catch(()=>null));a&&(n.pmPath=a,n.pmVersion=await ad(a),n.pmName="npm")}else n.runtimeShorthand=t,n.pmPath=s,n.pmVersion=i,n.pmName=t;return Xr.set(r,Ln(n)),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:Xr.get(r)?.unwrap()}),Ln(n)}}catch{}return Xr.set(r,Nn),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:null}),Nn}m(Un,"useJavaScriptRuntime");import{platform as cd}from"os";import{join as Mn}from"path";import Zr from"process";import{none as jn,some as Bn}from"@sapphire/result";import{execa as ld}from"execa";import dd from"which";var Ye=new Map;async function Vn(r){try{let e=await ld(r,["-c",'"import platform; print(platform.python_version())"'],{shell:!0,windowsHide:!0,verbose:Zr.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim():null}catch{return null}}m(Vn,"getPythonVersion");async function nr({cwd:r=Zr.cwd(),force:e=!1}={}){let t=Ye.get(r);if(t&&!e)return T("usePythonRuntime",{cacheHit:!0,cwd:r,runtime:t.unwrapOr(null)}),t;let o=cd()==="win32",s=o?["Scripts","python.exe"]:["bin","python3"],i;Zr.env.VIRTUAL_ENV?i=Mn(Zr.env.VIRTUAL_ENV,...s):i=Mn(r,".venv",...s),i=Ge(i);try{let a=await Vn(i);if(a)return Ye.set(r,Bn({executablePath:i,version:a})),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ye.get(r)?.unwrap()}),Ye.get(r)}catch{}let n=["python3","python",...o?["python3.exe","python.exe"]:[]];for(let a of n)try{let c=Ge(await dd(a)),l=await Vn(c);if(l)return Ye.set(r,Bn({executablePath:c,version:l})),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ye.get(r)?.unwrap()}),Ye.get(r)}catch{}return Ye.set(r,jn),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:null}),jn}m(nr,"usePythonRuntime");var Yn=new Map;async function Ne({cwd:r=pd.cwd()}={}){let e=Yn.get(r);if(e)return T("useCwdProject",{cacheHit:!0,project:e}),ci(e);let t={type:3},s=await m(async()=>{if(await Ad(r)){t.type=2;let a=await nr({cwd:r});t.runtime=a.unwrapOr(void 0);let c=new ct(r);if(c.loadScrapyCfg(),c.configuration.hasKey("apify","mainpy_location"))t.entrypoint={path:c.configuration.get("apify","mainpy_location")};else try{let l=await qn(r);l&&(t.entrypoint={path:l})}catch{}return}let n=await gd(r);if(!n){let a=null;try{a=await qn(r)}catch(c){return fd({message:c instanceof Error?c.message:String(c)})}if(a){t.type=1;let c=await nr({cwd:r});t.entrypoint={path:a},t.runtime=c.unwrapOr(void 0);let l=j(r,a.replace(/\./g,"/"));await ar(j(l,"__main__.py"))||(t.warnings=[`The detected Python package "${a}" is missing __main__.py. Running with "python -m" will fail without it.`]);return}}if(n){t.type=0;let a=await Un();t.runtime=a.unwrapOr(void 0),n.type==="file"?t.entrypoint={path:n.path}:n.type==="script"&&(t.entrypoint={script:n.script});return}return ci(t)},"check")();return s?.isErr()?(T("useCwdProject",{cacheHit:!1,error:s}),s):(T("useCwdProject",{cacheHit:!1,project:t}),Yn.set(r,t),ci(t))}m(Ne,"useCwdProject");async function gd(r){let e=j(r,"package.json");try{let o=await md(e,"utf-8"),s=JSON.parse(o);if(s.scripts?.start)return{type:"script",script:"start"};if(s.main)try{return await li(Gn(r,s.main)),{path:Gn(r,s.main),type:"file"}}catch{}return{type:"unknown-entrypoint"}}catch{}let t=[j(r,"index.js"),j(r,"index.mjs"),j(r,"index.cjs"),j(r,"main.js"),j(r,"main.mjs"),j(r,"main.cjs"),j(r,"src","index.js"),j(r,"src","index.mjs"),j(r,"src","index.cjs"),j(r,"src","main.js"),j(r,"src","main.mjs"),j(r,"src","main.cjs"),j(r,"dist","index.js"),j(r,"dist","index.mjs"),j(r,"dist","index.cjs"),j(r,"dist","main.js"),j(r,"dist","main.mjs"),j(r,"dist","main.cjs")];for(let o of t)try{return await li(o),{path:o,type:"file"}}catch{}return null}m(gd,"checkNodeProject");async function ar(r){try{return await li(r),!0}catch{return!1}}m(ar,"fileExists");async function Kn(r){try{return(await ud(r)).isDirectory()}catch{return!1}}m(Kn,"dirExists");function Wn(r){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)}m(Wn,"isValidPythonIdentifier");async function hd(r){try{let e=await wt(r,{withFileTypes:!0});if(e.some(t=>t.isFile()&&t.name.endsWith(".py")))return!0;for(let t of e){if(!t.isDirectory()||t.name.startsWith(".")||t.name.startsWith("_"))continue;let o=j(r,t.name);try{let s=await wt(o,{withFileTypes:!0});if(s.some(i=>i.isFile()&&i.name.endsWith(".py")))return!0;if(t.name==="src"){for(let i of s)if(i.isDirectory()&&!(i.name.startsWith(".")||i.name.startsWith("_")))try{if((await wt(j(o,i.name),{withFileTypes:!0})).some(a=>a.isFile()&&a.name.endsWith(".py")))return!0}catch{}}}catch{}}return!1}catch{return!1}}m(hd,"hasPythonFilesInDirOrSubdirs");async function yd(r){try{return(await wt(r,{withFileTypes:!0})).some(t=>t.isFile()&&t.name.endsWith(".py")&&t.name!=="__init__.py")}catch{return!1}}m(yd,"dirHasPyFiles");async function Hn(r){try{let e=await wt(r,{withFileTypes:!0}),t=[];for(let o of e){if(!o.isDirectory()||o.name.startsWith(".")||o.name.startsWith("_"))continue;let s=Wn(o.name),i=await ar(j(r,o.name,"__init__.py")),n=i||await yd(j(r,o.name));s&&i||n&&t.push({name:o.name,needsRename:!s,needsInit:!i})}return t}catch{return[]}}m(Hn,"findNearMissPackagesInDir");async function Jn(r){try{let e=await wt(r,{withFileTypes:!0}),t=[];for(let o of e){if(!o.isDirectory())continue;let{name:s}=o;if(s.startsWith(".")||s.startsWith("_")||!Wn(s))continue;let i=j(r,s,"__init__.py");await ar(i)&&t.push({name:s,path:j(r,s)})}return t}catch{return[]}}m(Jn,"findPackagesInDir");async function wd(r){let e=[],t=await Jn(r);e.push(...t.map(i=>i.name));let o=j(r,"src"),s=await ar(j(o,"__init__.py"));if(await Kn(o)&&!s){let i=await Jn(o);e.push(...i.map(n=>`src.${n.name}`))}return e}m(wd,"discoverPythonPackages");async function qn(r){let e=await wd(r);if(e.length===1)return e[0];if(e.length>1){let c=e.map(l=>` - ${l}`).join(`
|
|
12
|
-
`);throw new Error(`Multiple Python packages found:
|
|
13
|
-
${c}
|
|
14
|
-
|
|
15
|
-
Apify CLI cannot determine which package to run.
|
|
16
|
-
Please specify the package using the --entrypoint flag, e.g.:
|
|
17
|
-
apify run --entrypoint <package_name>`)}let t=await Hn(r),o=j(r,"src"),i=!await ar(j(o,"__init__.py"))&&await Kn(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:l,prefix:d,needsRename:u,needsInit:p})=>{let f=[];return u&&f.push(`rename to "${d}${l.replace(/[^a-zA-Z0-9_]/g,"_")}/"`),p&&f.push("add __init__.py"),` - "${d}${l}/" \u2192 ${f.join(" and ")}`}).join(`
|
|
18
|
-
`);throw new Error(`Found directories that appear to be Python packages but have issues:
|
|
19
|
-
${c}
|
|
20
|
-
|
|
21
|
-
A valid Python package requires a directory with a valid identifier name (letters, numbers, underscores) and an __init__.py file.`)}if(await hd(r))throw new Error(`No Python package found. Found Python files, but no valid package structure detected.
|
|
22
|
-
A Python package requires:
|
|
23
|
-
- A directory with a valid Python identifier name (letters, numbers, underscores)
|
|
24
|
-
- An __init__.py file inside the directory
|
|
25
|
-
|
|
26
|
-
Common package structures:
|
|
27
|
-
my_package/
|
|
28
|
-
__init__.py
|
|
29
|
-
main.py
|
|
30
|
-
|
|
31
|
-
src/
|
|
32
|
-
my_package/
|
|
33
|
-
__init__.py
|
|
34
|
-
main.py`);return null}m(qn,"checkPythonProject");async function Ad(r){return ct.isApplicable(r)}m(Ad,"checkScrapyProject");import K from"chalk";import lt from"chalk";import Qn from"indent-string";import Id from"widest-line";import ea from"wrap-ansi";import Qr from"chalk";import ui from"indent-string";import vd from"string-width";import Xn from"strip-ansi";import Zn from"widest-line";import pi from"wrap-ansi";import At from"chalk";import di from"indent-string";import zn from"string-width";import mi from"wrap-ansi";var He;function se(){if(He)return He;let r=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(r))He=r;else if(!process.stdout.isTTY)He=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;e<1?He=80:e<40?He=40:He=e}return He}m(se,"getMaxLineWidth");var vt=class{static{m(this,"BaseCommandRenderer")}command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let t=this.command.interactive?`${At.yellow("[INTERACTIVE]")} `:"";this.command.shortDescription?e.push(`${t}${this.command.shortDescription}`,""):this.command.description&&e.push(`${t}${this.command.description.split(`
|
|
35
|
-
`)[0]}`,"")}pushDescription(e){if(!this.command.description)return;e.push(At.bold("DESCRIPTION"));let t=mi(this.command.description,se()-2,{trim:!1}),o=di(t,2);e.push(o),e.push("")}pushExamples(e){let{examples:t}=this.command;if(t?.length){e.push(At.bold("EXAMPLES"));for(let o of t){if(o.description){let i=mi(o.description,se()-4,{trim:!1}).split(`
|
|
36
|
-
`).map(a=>`# ${a}`).join(`
|
|
37
|
-
`),n=di(i,2);e.push(At.dim(n))}e.push(` $ ${this.normalizeExampleCommand(o.command)}`),e.push("")}}}normalizeExampleCommand(e){let t=this.entrypoint.split(" ");if(t.length<2)return e;let o=t[t.length-1],s=`${t.slice(0,-1).join(" ")} `,i=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=e;return n.startsWith(`${o} `)&&(n=`${s}${n}`),n=n.replace(new RegExp(`\\|\\s+${i}\\s`,"g"),`| ${s}${o} `),n}pushInteractiveNote(e){if(!this.command.interactive)return;e.push(At.bold("NOTE"));let o=this.command.interactiveNote||"This command prompts the user for input. To run non-interactively (e.g. in CI or from an AI agent), pass all required arguments and flags explicitly.",s=mi(o,se()-2,{trim:!1}),i=di(s,2);e.push(i),e.push("")}pushLearnMore(e){this.command.docsUrl&&(e.push(At.bold("LEARN MORE")),e.push(` ${this.command.docsUrl}`),e.push(""))}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:o}){let s=zn(e.join(" ").split(`
|
|
38
|
-
`).at(-1)||"")+o,i=zn(t);s+i>se()&&e.push(`
|
|
39
|
-
`),e.push(t)}kebabFlagName(e){return Ee($e(e)).toLowerCase()}makeFlagString(e,t){let o=this.kebabFlagName(e),s=t.char?`-${t.char}`:`--${o}`;switch(t.flagTag){case"boolean":return s;case"string":case"integer":{let i=t.choices?.length?`${t.choices.join("|")}`:"<value>";return`${s} ${i}`}default:throw new RangeError(`Unhandled flag type: ${t.flagTag}`)}}};var eo=class extends vt{static{m(this,"CommandHelp")}render(){let e=[];return this.pushShortDescription(e),this.pushUsageString(e),this.command.description&&this.pushDescription(e),this.pushExamples(e),this.pushInteractiveNote(e),this.pushLearnMore(e),e.join(`
|
|
40
|
-
`).trim()}selectiveRender(e){let t=[];return e.showShortDescription&&this.pushShortDescription(t),e.showUsageString&&this.pushUsageString(t),e.showDescription&&this.command.description&&this.pushDescription(t),e.showExamples&&this.pushExamples(t),e.showLearnMore&&this.pushLearnMore(t),t.join(`
|
|
41
|
-
`).trim()}pushUsageString(e){e.push(Qr.bold("USAGE"));let t=`$ ${this.entrypoint} ${this.command.name}`,o=2+vd(t),s=[t],i=Object.entries(this.command.args??{});if(i.length)for(let[u,p]of i){if(typeof p=="string")throw new RangeError("This is a type-check only value, do not actually use it");this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:p.required?`<${u}>`:`[${u}]`,indentSize:o})}let n=Object.entries(this.command.flags??{}).filter(([,u])=>{if(typeof u=="string")throw new RangeError("This is a type-check only value, do not actually use it");return!u.hidden});this.command.enableJsonFlag&&n.push(["json",{choices:null,flagTag:"boolean",hasDefault:!1,required:!1,stdin:null,builder:null,aliases:void 0,char:void 0,description:"Format the command output as JSON",hidden:void 0,exclusive:void 0}]);let a=new Map(n.sort((u,p)=>{if(typeof u[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(typeof p[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");return u[1].required&&!p[1].required?-1:!u[1].required&&p[1].required?1:u[0].localeCompare(p[0])})),c=new Set;if(n.length)for(let[u,p]of a){if(typeof p=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(c.has(u))continue;let f=p.required,v=[this.makeFlagString(u,p)];if(p.exclusive?.length)for(let S of p.exclusive){c.add(S);let E=a.get(S),C=this.makeFlagString(S,E);v.push(C),E.required&&(f=!0)}this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:f?v.join(" | "):`[${v.join(" | ")}]`,indentSize:o})}let l=pi(s.join(" "),se()-o),d=ui(l,o+1).trim();e.push(` ${d}`,""),i.length&&this.pushArguments(e,i),n.length&&this.pushFlags(e,a)}pushArguments(e,t){if(!t.length)return;e.push(Qr.bold("ARGUMENTS"));let o=Zn(t.map(([s])=>s).join(`
|
|
42
|
-
`));for(let[s,i]of t){let n=`${s.padEnd(o)} ${i.description}`,a=pi(n,se()-o-2),c=ui(a,o+2+2).trim();e.push(` ${c}`)}e.push("")}pushFlags(e,t){if(!t.size)return;e.push(Qr.bold("FLAGS"));let o=new Map;for(let[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)}=${Qr.underline(c)}`);break}default:throw new Error(`Unhandled flag tag: ${n.flagTag}`)}o.set(a.join(" "),n)}let s=Zn([...o.keys()].map(Xn).join(`
|
|
43
|
-
`));for(let[i,n]of o){let a=s-Xn(i).length,c=`${i}${" ".repeat(a)} ${n.description??""}`;n.choices?.length&&(c+=`
|
|
44
|
-
<options: ${n.choices.join("|")}>`);let l=pi(c,se()-s),d=ui(l,s).trim().split(`
|
|
45
|
-
`).map(u=>/^-[a-z]/.test(u.trim())?u:` ${u}`).join(`
|
|
46
|
-
`);e.push(` ${d}`)}e.push("")}};import bd from"chalk";import Sd from"indent-string";import Td from"widest-line";import Cd from"wrap-ansi";var to=class extends vt{static{m(this,"CommandWithSubcommandsHelp")}render(){let e=[];return this.pushShortDescription(e),this.command.description&&this.pushDescription(e),this.pushSubcommands(e),this.pushExamples(e),this.pushInteractiveNote(e),this.pushLearnMore(e),e.join(`
|
|
47
|
-
`).trim()}selectiveRender(e){let t=[];return e.showShortDescription&&this.pushShortDescription(t),e.showDescription&&this.command.description&&this.pushDescription(t),e.showSubcommands&&this.pushSubcommands(t),e.showExamples&&this.pushExamples(t),e.showLearnMore&&this.pushLearnMore(t),t.join(`
|
|
48
|
-
`).trim()}pushSubcommands(e){if(!this.command.subcommands?.length)return;e.push(bd.bold("SUBCOMMANDS"));let t=Td(this.command.subcommands.map(o=>`${this.command.name} ${o.name}`).join(`
|
|
49
|
-
`));for(let o of this.command.subcommands){let s=o.shortDescription||o.description?.split(`
|
|
50
|
-
`)[0]||"",i=`${this.command.name} ${o.name.padEnd(t-this.command.name.length-1)} ${s}`,n=Cd(i,se()-t-2),a=Sd(n,t+2+2).trim();e.push(` ${a}`)}e.push("")}};var cr=new Map;function fi(r,e){if(e.name.toLowerCase()!==e.name){g({message:`Command name "${e.name}" is not correctly set up internally. Make sure you fill out the "name" field in the command class extension.`});return}if(e.subcommands?.length){cr.set(e,new to(r,e));for(let t of e.subcommands)fi(`${r} ${e.name}`,t)}else cr.set(e,new eo(r,e))}m(fi,"registerCommandForHelpGeneration");function oo(r){let e=cr.get(r);if(!e)throw new Error(`No help renderer found for command ${r.name}`);return e.render()}m(oo,"renderHelpForCommand");function so(r,e){let t=cr.get(r);if(!t)throw new Error(`No help renderer found for command ${r.name}`);return t.selectiveRender(e)}m(so,"selectiveRenderHelpForCommand");function Ed(r,e){return r[0].name.localeCompare(e[0].name)}m(Ed,"sortByName");var ta=["Local Actor Development","Apify Console","Authentication","Utilities"],ro="Other",$d=[{command:"apify login"},{description:"Walks you interactively through the Actor creation flow.",command:"apify create"},{command:"apify run"},{command:"apify push"},{command:'apify actors search "web scraper"'}],Rd=[{command:"actor get-input"},{command:`actor push-data '{"url":"https://example.com"}'`},{command:`actor set-value OUTPUT '{"done":true}'`}];function io(r){let e=z(),t=[];r==="actor"?t.push("'actor' is the runtime CLI baked into Apify Actor Docker images. It exposes a reduced command set intended for use from inside a running Actor. When available, these commands are equivalent to 'apify actor <subcommand>'.",""):t.push("Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",""),t.push(lt.bold("VERSION")),t.push(` ${e.fullVersionString}`),t.push(""),t.push(lt.bold("USAGE")),t.push(` $ ${r} <command> [options]`),t.push("");let o=[];for(let[u,p]of cr)p.entrypoint.includes(" ")||u.hidden||o.push([u,p]);let s=new Map;for(let u of o){let[p]=u,f=p.group||ro;s.has(f)||s.set(f,[]),s.get(f).push(u)}for(let u of s.values())u.sort(Ed);let i=[];for(let u of ta)s.has(u)&&i.push(u);let n=[...s.keys()].filter(u=>!ta.includes(u)&&u!==ro).sort();i.push(...n),s.has(ro)&&i.push(ro);let a=o.map(([u])=>u.name).join(`
|
|
51
|
-
`),c=Id(a)||1,l=m(([u])=>{let p=u.shortDescription||u.description?.split(`
|
|
52
|
-
`)[0]||"",y=`${u.name.padEnd(c)} ${p}`,v=ea(y,se()-c-4);return` ${Qn(v,c+2+2).trim()}`},"renderEntry");for(let u of i){let p=s.get(u);p.length&&(t.push(lt.bold(u.toUpperCase())),t.push(...p.map(l),""))}let d=r==="actor"?Rd:$d;if(d.length){t.push(lt.bold("EXAMPLES"));for(let u=0;u<d.length;u++){let p=d[u];if(p.description){u>0&&t.push("");let y=ea(p.description,se()-4,{trim:!1}).split(`
|
|
53
|
-
`).map(v=>`# ${v}`).join(`
|
|
54
|
-
`);t.push(lt.dim(Qn(y,2)))}t.push(` $ ${p.command}`),p.description&&u<d.length-1&&t.push("")}t.push("")}return t.push(lt.bold("LEARN MORE"),` Use '${r} <command> --help' for more information about a command.`," Read the docs at https://docs.apify.com/cli.",""),t.push(lt.bold("TROUBLESHOOTING")," For general support, reach out to us at https://apify.com/contact."," If you believe you are encountering a bug, file it at https://github.com/apify/apify-cli/issues/new."),t.join(`
|
|
55
|
-
`).trim()}m(io,"renderMainHelpMenu");var no=(d=>(d[d.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]="NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE",d[d.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]="NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL",d[d.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]="NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION",d[d.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]="APIFY_FLAG_PROVIDED_MULTIPLE_TIMES",d[d.APIFY_INVALID_FLAG_INTEGER_VALUE=4]="APIFY_INVALID_FLAG_INTEGER_VALUE",d[d.APIFY_INVALID_CHOICE=5]="APIFY_INVALID_CHOICE",d[d.APIFY_MISSING_FLAG=6]="APIFY_MISSING_FLAG",d[d.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]="APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG",d[d.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]="APIFY_TOO_MANY_REQUESTERS_OF_STDIN",d[d.APIFY_UNKNOWN_ERROR=9]="APIFY_UNKNOWN_ERROR",d))(no||{}),pe=class r extends Error{static{m(this,"CommandError")}code;command;metadata;constructor({code:e,message:t="",metadata:o={},command:s}){super(t||String(no[e])),this.code=e,this.metadata=o,this.command=s}extractFlagNameFromMessage(){switch(this.code){case 0:{let e=/'(?:-[a-z], )?-?-(?<flagName>[a-zA-Z-]+)(?: <value>)?' (?<noArg>does not take)?(?<missingArg>argument missing)?(?<ambiguous>argument is ambiguous\.(?<ambiguousMessage>\s*.*\s*.*)?)?/gi.exec(this.message);if(!e)throw new Error(`Encountered unparsable error message from argument parser: ${this.message}.
|
|
56
|
-
|
|
57
|
-
Please report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.flagName,expectsValue:e.groups.noArg===void 0,ambiguousFlag:e.groups.ambiguous?e.groups.ambiguous:void 0,ambiguousMessage:e.groups.ambiguousMessage?e.groups.ambiguousMessage.trim():void 0}}case 2:{let e=/Unknown option '-(?<longForm>-)?(?<optionName>.+)'\.(?<nodeSuggestion>.*)/gi.exec(this.message);if(!e)throw new Error(`Encountered unparsable error message from argument parser: ${this.message}.
|
|
58
|
-
|
|
59
|
-
Please report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.optionName,expectsValue:!1,unknownOptionSuggestion:e.groups.nodeSuggestion,shortForm:!e.groups.longForm}}default:throw new Error("Not implemented")}}getPrettyMessage(){switch(this.code){case 0:{let e=this.extractFlagNameFromMessage();return r.buildMessageFromFlagData(e)}case 2:{let e=this.extractFlagNameFromMessage(),t=so(this.command,{showUsageString:!0});return[K.gray(`Unknown flag provided: ${K.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`),e.unknownOptionSuggestion?K.gray(` ${e.unknownOptionSuggestion.trim()}`):null,"",t].filter(o=>o!==null).join(`
|
|
60
|
-
`)}case 3:{let e=`--${this.metadata.flag}`;return K.gray(`Flag ${K.white.bold(e)} can only be specified once.`)}case 4:{let e=`--${this.metadata.flag}`,t=K.whiteBright(String(this.metadata.value));return K.gray(`The provided value for the '${K.white.bold(e)}' flag could not be processed as an integer. Received: ${t}.`)}case 6:{let{flag:e,matcher:t,providedButReceivedNoValue:o}=this.metadata,s=`'${K.white.bold(`--${e}`)}'`;return t&&(s=`${s} (alias used: '${K.white.bold(`--${t}`)}')`),o?K.gray(`Flag ${s} was provided, but no value was received. Did you mean to pass the value as an argument or through standard input?`):K.gray(`Flag ${s} is required, but was not provided.`)}case 7:{let{flagPairs:e}=this.metadata,t=[K.gray("The following errors occurred:")],o=K.red(" > ");for(let[s,i]of e)t.push(K.gray(`${o}${K.white.bold(s)} cannot also be provided when using ${K.white.bold(i)}`));return t.push(K.gray(`${o}See more help with ${K.white.bold("--help")}`)),t.join(`
|
|
61
|
-
`)}case 8:{let{firstUse:e,secondUse:t}=this.metadata;return K.gray(`Flag ${K.white.bold(`--${e}`)} and ${K.white.bold(`--${t}`)} cannot both request that their value comes from standard input at the same time.`)}default:{let e=z();return["The CLI encountered an unhandled argument parsing error!","Please report this issue at https://github.com/apify/apify-cli/issues, and provide the following information:","",`- Error code: ${this.code} (${no[this.code]})`,`- Error metadata: ${JSON.stringify(this.metadata)}`,"",`- Stack:
|
|
62
|
-
${this.stack}`,"","- Arguments (!!!only provide these as is if there is no sensitive information!!!):",` ${JSON.stringify(process.argv.slice(2))}`,"",`- CLI version: \`${e.fullVersionString}\``,`- CLI debug logs (process.env.APIFY_CLI_DEBUG): ${process.env.APIFY_CLI_DEBUG?"Enabled":"Disabled"}`,`- Stdin data? ${Re?"Yes":"No"}`].join(`
|
|
63
|
-
`)}}}static buildMessageFromFlagData(e){let t=[`Flag ${K.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`];return e.ambiguousFlag?(t.push("is ambiguous (meaning the provided value could be interpreted as a flag too)."),e.ambiguousMessage?t.push(`
|
|
64
|
-
${e.ambiguousMessage.split(`
|
|
65
|
-
`).map(o=>` ${o}`).join(`
|
|
66
|
-
`)}`):t.push(`To solve this, provide the flag like this: --${e.name}=<value>`)):e.expectsValue?t.push("expects a value"):t.push("does not take an argument"),t.map(o=>K.gray(o)).join(" ")}static into(e,t){if(e instanceof r)return e;if(e instanceof Error&&"code"in e){let o=e;switch(o.code){case"ERR_PARSE_ARGS_INVALID_OPTION_VALUE":return new r({code:0,message:o.message,command:t});case"ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL":return new r({code:1,message:o.message,command:t});case"ERR_PARSE_ARGS_UNKNOWN_OPTION":return new r({code:2,message:o.message,command:t});default:return new r({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}}return new r({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}};function ra(r){return r.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}m(ra,"camelCaseString");function Ee(r){return r.replace(/[\s_]+/g,"-")}m(Ee,"kebabCaseString");function $e(r){return r.replace(/([A-Z])/g,"-$1").toLowerCase()}m($e,"camelCaseToKebabCase");var kd={type:"boolean",multiple:!1,short:"h"},Od={type:"boolean",multiple:!1},Nd={type:"string",multiple:!1},oa="user-agent",Ld="APIFY_CLI_USER_AGENT",sa=256,ia=new Set(["apify"]);function na(r){if(typeof r!="string")return;let t=r.replace(/[\u0000-\u001f\u007f]/g,"").trim();if(t)return t.length>sa?t.slice(0,sa):t}m(na,"sanitizeUserAgentValue");function Dd(r,e){return na(r)??na(e)}m(Dd,"resolveUserAgentForTelemetry");var W=new Map,Fd=["init","run","push","actors push","pull","actors pull","call","actors call","actors start"],h=class{static args;static flags;static subcommands;static enableJsonFlag=!1;static name;static shortDescription;static description;static examples;static docsUrl;static interactive;static interactiveNote;static group;static aliases;static hidden;static hiddenAliases;telemetryData={};flags;args;entrypoint;commandString;aliasUsed;subcommandAliasUsed;skipTelemetry=!1;constructor(e,t,o,s){this.entrypoint=e,this.commandString=t,this.aliasUsed=o,this.subcommandAliasUsed=s;let i=z();this.telemetryData.installMethod=i.installMethod,this.telemetryData.osArch=i.arch,this.telemetryData.runtime=i.runtime.runtime,this.telemetryData.runtimeVersion=i.runtime.version,this.telemetryData.runtimeNodeVersion=i.runtime.nodeVersion??i.runtime.version,this.telemetryData.commandString=t,this.telemetryData.entrypoint=e;let n=zi();this.telemetryData.aiAgent=Wi(),this.telemetryData.isCi=n.isCi,this.telemetryData.ciProvider=n.ciProvider,this.telemetryData.isInteractive=Xi()}get ctor(){return this.constructor}pluralString(e,t,o){return e===1?t:o}static printHelp(){console.log(oo(this)),bt.exit(0)}printHelp(){return this.ctor.printHelp()}async _run(e){let t=Date.now(),{values:o,positionals:s,tokens:i}=e;if(o.help&&this.ctor.printHelp(),ia.has(this.entrypoint)){let a=o[oa],c=Dd(typeof a=="string"?a:void 0,bt.env[Ld]);c&&(this.telemetryData.userAgent=c)}this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof o.json=="boolean"?this.flags.json=o.json:this.flags.json=!1);let n=new Map;if(this.ctor.args){let a=0;for(let[c,l]of Object.entries(this.ctor.args)){if(typeof l=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let d=ra(c),u=s[a++];if(u)switch(l.argTag){default:this.args[d]=String(u),u==="-"&&l.stdin&&(this.args[d]=this._handleStdin(l.stdin)),l.catchAll&&(this.args[d]=s.slice(a-1).join(" "));break}else l.required&&n.set(c,l)}}if(n.size){bt.exitCode=1,this._printMissingRequiredArgs(n);return}this._parseFlags(o,i);try{await this.run()}catch(a){g({message:a.message}),bt.exitCode||=1}finally{!this.telemetryData.actorLanguage&&Fd.includes(this.commandString)&&(await Ne()).inspect(c=>{c.type===0?(this.telemetryData.actorLanguage="javascript",this.telemetryData.actorRuntime=c.runtime.runtimeShorthand||"node",this.telemetryData.actorRuntimeVersion=c.runtime.version):(c.type===1||c.type===2)&&(this.telemetryData.actorLanguage="python",this.telemetryData.actorRuntime="python",this.telemetryData.actorRuntimeVersion=c.runtime.version)}),this.skipTelemetry||(this.telemetryData.flagsUsed=Object.keys(this.flags),this.telemetryData.exitCode=typeof bt.exitCode=="number"?bt.exitCode:0,this.telemetryData.durationMs=Date.now()-t,this.telemetryData.wasRetried=await In(this.commandString),await Rn(`cli_command_${this.commandString.replaceAll(" ","_").toLowerCase()}`,this.telemetryData))}}_userFlagNameToRegisteredName(e,t){let o=Ee($e(e)).toLowerCase(),s=o;o.startsWith("no-")&&(s=o.slice(3));let i=new Set;for(let n of t.aliases??[])i.add(Ee($e(n)).toLowerCase());return{baseFlagName:s,rawBaseFlagName:o,allMatchers:[s,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=Ee($e(e)).toLowerCase();return t.startsWith("no-")&&(t=t.slice(3)),t}_parseFlags(e,t){if(!this.ctor.flags)return;let o=new Map,s;for(let[n,a]of Object.entries(this.ctor.flags)){if(typeof a=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let{allMatchers:c,baseFlagName:l,rawBaseFlagName:d}=this._userFlagNameToRegisteredName(n,a),u=ra(d),p=t.some(v=>v.kind==="option"&&v.name===l);if(a.exclusive?.length){let v=o.get(l)??new Set;for(let S of a.exclusive)v.add(this._commandFlagKeyToKebabCaseRegisteredName(S));o.set(l,v);for(let S of a.exclusive){let E=this._commandFlagKeyToKebabCaseRegisteredName(S),C=o.get(E)??new Set;C.add(l),o.set(E,C)}}let f=c.filter(v=>e[v]);if(f.length>1)throw new pe({code:3,command:this.ctor,metadata:{flag:l}});let y=e[f[0]];if(!y&&a.required)throw new pe({code:6,command:this.ctor,metadata:{flag:l,matcher:f[0]}});if(Array.isArray(y)){if(y.length>1)throw new pe({code:3,command:this.ctor,metadata:{flag:l}});y=y[0]}if(p&&typeof y=="string"&&y.startsWith("=")&&(y=y.slice(1)),typeof y<"u")switch(a.flagTag){case"boolean":{this.flags[u]=d.startsWith("no-")?!y:y;break}case"integer":{let v=Number(y);if(Number.isNaN(v)||!Number.isInteger(v))throw new pe({code:4,command:this.ctor,metadata:{flag:l,value:String(y)}});this.flags[u]=v;break}default:{if(this.flags[u]=y,y==="-"&&a.stdin){if(s)throw new pe({code:8,command:this.ctor,metadata:{firstUse:s,secondUse:l}});s=l,this.flags[u]=this._handleStdin(a.stdin)}break}}else typeof a.hasDefault<"u"&&(this.flags[u]=a.hasDefault);if(this.flags[u]&&a.choices&&!a.choices.includes(this.flags[u]))throw new pe({code:5,command:this.ctor,metadata:{flag:l,choices:a.choices.map(v=>gi.white.bold(v)).join(", ")}});if(this.flags[u]==null&&(a.required||y!=null))throw new pe({code:6,command:this.ctor,metadata:{flag:l,matcher:f[0],providedButReceivedNoValue:!!y}})}let i=[];for(let[n,a]of o)if(e[n]!=null)for(let c of a){if(e[c]==null)continue;let l=e[n][0],d=e[c][0],u=m((p,f)=>typeof f=="boolean"?f?`--${p}`:`--no-${p}`:`--${p}=${f}`,"flagRepresentation");i.push([u(n,l),u(c,d)]);break}if(i.length)throw new pe({code:7,command:this.ctor,metadata:{flagPairs:i}})}_printMissingRequiredArgs(e){let t;try{t=so(this.ctor,{showUsageString:!0})}catch{}let o=_d([...e.keys()].join(`
|
|
67
|
-
`)),s=[];for(let[n,a]of e){let c=`${n.padEnd(o)} ${a.description}`,l=Pd(c,se()-o-2),d=xd(l,o+2+2).trim();s.push(` ${gi.red(">")} ${d}`)}let i=[`Missing ${e.size} required ${this.pluralString(e.size,"argument","arguments")}:`,...s,gi.gray(" See more help with --help")];t&&i.push("",t),g({message:i.join(`
|
|
68
|
-
`)})}_handleStdin(e){return e===2?(Re?.toString("utf8")??"").trim():Re}_buildParseArgsOption(){let e={help:kd};ia.has(this.entrypoint)&&(e[oa]=Nd);let t={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:e};if(this.ctor.flags)for(let[o,s]of Object.entries(this.ctor.flags)){if(typeof s=="string")throw new RangeError("Do not provide the string for the json flag! It is a type level assertion!");if(o.toLowerCase()==="json")continue;let i=Ee($e(o)).toLowerCase();i.startsWith("no-")&&(i=i.slice(3));let n=s.builder(i);for(let{flagName:a,option:c}of n)t.options[a]=c}return this.ctor.enableJsonFlag&&(t.options.json=Od),t}static registerCommand(e){if(fi(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 aa(r,e,t){let o={positionals:[],values:{},tokens:[]},s=0;for(let[n,a]of Object.entries(t)){let[c,l]=n.split("_");if(c==="args")o.positionals[s++]=a;else{let d=Ee($e(l)).toLowerCase();d.startsWith("no-")?o.values[d.slice(3)]=!a:o.values[d]=a}}let i=new e(r,e.name,e.name);i.skipTelemetry=!0,await i._run(o)}m(aa,"internalRunCommand");import{once as Ud}from"events";async function ca(){let r=await Hr(),{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 Ud(o,"end",{signal:i.signal})}catch(c){if(c.name==="AbortError")return}n&&clearTimeout(n),r.hasData=!1;let a=Buffer.concat(s);if(a.length)return a}m(ca,"readStdin");import{gt as Jd}from"semver";import{existsSync as Md,mkdirSync as jd,readFileSync as Bd,writeFileSync as Vd}from"fs";import{dirname as Gd}from"path";function Yd(r){if(r.version&&r.version>=1)return!1;let e=r;if(e.latestNpmVersionCheckedAt){let t=new Date(e.latestNpmVersionCheckedAt).getTime(),o=e.latestNpmVersion;T("LocalStateV0ToV1","Migrating state from v0 to v1",{oldState:r,newState:{versionCheck:{lastChecked:t,lastVersion:o}}}),yi({version:1},s=>{s.versionCheck={lastChecked:t,lastVersion:o}})}return!0}m(Yd,"migrateStateV0ToV1");var Hd={version:1};function hi(){let r=$r();if(!Md(r))return Hd;let t=JSON.parse(Bd(r,"utf-8"));return Yd(t)?hi():t}m(hi,"useLocalState");function yi(r,e){let t={...r};e(t);let o=$r(),s=Gd(o);jd(s,{recursive:!0}),Vd($r(),JSON.stringify(t,null," "))}m(yi,"updateLocalState");var ao=z(),la=`Apify CLI/${ao.version} (https://github.com/apify/apify-cli)`,qd=["https://1.1.1.1","https://8.8.8.8"];async function Kd(r=500){let e=new AbortController,t=setTimeout(()=>{e.abort()},r),o=await Promise.any(qd.map(async s=>fetch(s,{signal:e.signal,headers:{"User-Agent":la},keepalive:!1}))).catch(()=>null);return clearTimeout(t),o?o.ok?(T("isOnline",{state:"online",site:o.url}),!0):(T("isOnline",{state:"offline"}),!1):(T("isOnline",{state:"timeout"}),!1)}m(Kd,"isOnline");async function Wd(r){let e=await fetch("https://api.github.com/repos/apify/apify-cli/releases/latest",{headers:{"User-Agent":la}});if(!e.ok)return T("useCLIVersionCheck","Failed to fetch latest version",{statusCode:e.status,body:await e.text()}),x({message:"Failed to fetch latest version of Apify CLI, using the cached version instead."}),null;let o=(await e.json()).tag_name.replace(/^v/,"");return T("useCLIVersionCheck","Fetched latest version",{version:o}),yi(r,s=>{s.versionCheck={lastChecked:Date.now(),lastVersion:o}}),o}m(Wd,"getLatestVersion");function da(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&!["0","false"].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}m(da,"shouldSkipVersionCheck");async function ma(r=!1){let e=hi(),t=!e.versionCheck||Date.now()-e.versionCheck.lastChecked>Qi,o=r||t&&await Kd(),s=o?await Wd(e):e.versionCheck?.lastVersion;if(!s)return{currentVersion:ao.version,latestVersion:"unknown",shouldUpdate:!1,cacheHit:!1};let i=Jd(s,ao.version);return{currentVersion:ao.version,latestVersion:s,shouldUpdate:i,cacheHit:!o}}m(ma,"useCLIVersionCheck");import{jaroWinkler as zd}from"@skyra/jaro-winkler";import Xd from"js-levenshtein";function co(r){let e=[...W.entries()].sort(([s],[i])=>s.localeCompare(i)),t=r.toLowerCase();return e.map(([s,i])=>{let n=s.toLowerCase(),a=s.split(" "),c=a[a.length-1].toLowerCase(),l=i.aliases?.includes(c)||i.hiddenAliases?.includes(c)||!1,d=Xd(t,n),u=zd(t,n),p=d<=2||u>=.975;return p?(T("useCommandSuggestions",{inputString:t,lowercased:n,matches:p,levenshtein:d,jaroWinkler:u}),l?{string:`${n} (alias for ${i.name})`,distance:u}:{string:`${n}`,distance:u}):null}).filter(s=>s!==null).sort((s,i)=>i.distance-s.distance).map(s=>s.string)}m(co,"useCommandSuggestions");var Re=await ca(),lr=z(),nt=`Apify CLI/${lr.version} (https://github.com/apify/apify-cli)`;function xw(r){lr.installMethod!=="bundle"&&(Zd(xe.version,Ie)||(g({message:`${r} CLI requires Node.js version ${Ie}. Your current version is ${xe.version}.`}),xe.exit(1)))}m(xw,"processVersionCheck");function Qd(r){r.values.version===!0&&r.positionals.length===0&&(console.log(lr.fullVersionString),xe.exit(0))}m(Qd,"printCLIVersionAndExitIfFlagUsed");function em(r,e){(r.values.help===!0&&r.positionals.length===0||r.positionals.length===0)&&(console.log(io(e)),xe.exit(0))}m(em,"printHelpAndExitIfFlagUsedOrNoCommandPassed");function pa(r){let e=co(String(r)),t=lo.gray(`Command ${lo.whiteBright(r)} not found`);e.length&&(t+=`
|
|
69
|
-
`,t+=lo.gray(`Did you mean: ${e.map(o=>lo.whiteBright(o)).join(", ")}?`)),g({message:t}),xe.exit(1)}m(pa,"handleCommandNotFound");async function tm(r,e){let t=W.get("upgrade");if([t.name,...t.aliases??[]].some(s=>e===s)){T("[VersionCheckMiddleware]","upgrade command detected, skipping version check");return}if(da()){T("[VersionCheckMiddleware]","skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set");return}await aa(r,t,{flags_internalAutomaticCall:!0})}m(tm,"runVersionCheck");async function _w(r){T("CLIMetadata",{...lr,fullVersionString:lr.fullVersionString,argv:xe.argv,cwd:xe.cwd(),execPath:xe.execPath});let e=xe.argv.slice(2);T("ProcessArgv",e);let t=ua({allowPositionals:!0,strict:!1,options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}},args:e});Qd(t),em(t,r),await tm(r,t.positionals[0]),T("TopLevelOptions",t);let o=t.positionals[0],s=-1;if(W.get(o)?.subcommands?.length){if(t.positionals[1]?.toLowerCase()==="help")s=1;else if(t.positionals[2]?.toLowerCase()==="help"){let y=W.get(`${o} ${t.positionals[1]}`);y&&!y.args&&(s=2)}}if(s!==-1){let y=t.positionals[s],v=e.indexOf(y);v!==-1&&e.splice(v,1),!e.includes("--help")&&!e.includes("-h")&&e.push("--help"),t.positionals.splice(s,1),t.values.help=!0}let n=t.positionals[1],a=!1,c=W.get(o);if(!c)return pa(o);let l=c;if(c.subcommands?.length){if(!n)return c.printHelp();a=!0,l=W.get(`${o} ${n}`)}if(!l)return pa(`${o} ${n}`);let d=[...e],u=d.indexOf(o);if(T("CommandNameIndex",u),d.splice(u,1),a){let y=d.indexOf(n);T("SubcommandNameIndex",y),d.splice(y,1)}T("RebuiltArgs",d),T("CommandToRun",l);let p=new l(r,a?`${c.name} ${n}`:c.name,o,a?n:void 0),f=p._buildParseArgsOption();T("ParserOptionsForCommand",f);try{let y=ua({...f,args:d});await p._run(y),T("CommandArgsResult",y)}catch(y){let v=pe.into(y,l);g({message:v.getPrettyMessage()}),xe.exit(1)}}m(_w,"runCLI");import{join as vm,resolve as bm}from"path";import Ai from"process";import{calculateRunDynamicMemory as Sm}from"@apify/actor-memory-expression";var w={string:rm,boolean:om,integer:sm};function ie(r='Automatic yes to prompts; assume "yes" as answer to all prompts.'){return{yes:w.boolean({char:"y",description:r,default:!1})}}m(ie,"YesFlag");function rm(r){return{flagTag:"string",builder:m(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"string",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Ee($e(s)).toLowerCase(),option:{type:"string",multiple:!0}});return o},"builder"),choices:r.choices,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??2,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}m(rm,"stringFlag");function om(r){return{flagTag:"boolean",builder:m(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"boolean",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Ee($e(s)).toLowerCase(),option:{type:"boolean",multiple:!0}});return o},"builder"),choices:null,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??1,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}m(om,"booleanFlag");function sm(r){return{flagTag:"integer",builder:m(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"string",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Ee($e(s)).toLowerCase(),option:{type:"string",multiple:!0}});return o},"builder"),choices:null,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??1,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}m(sm,"integerFlag");import{mkdir as dm,rename as wa,writeFile as mm}from"fs/promises";import{dirname as um,join as pm}from"path";import ya from"process";import{inspect as fm}from"util";import{err as mr,ok as uo}from"@sapphire/result";import{createPrompt as im,isEnterKey as nm,makeTheme as am,useKeypress as cm,usePrefix as lm,useState as fa}from"@inquirer/core";function wi(r,e){let t=e!==!1;return/^(y|yes)/i.test(r)?t=!0:/^(n|no)/i.test(r)&&(t=!1),t}m(wi,"getBooleanValue");function ga(r){return r?"Yes":"No"}m(ga,"boolToString");var ha=im((r,e)=>{let t=ga,[o,s]=fa("idle"),[i,n]=fa(""),a=am(),c=lm({status:o,theme:a});cm((p,f)=>{if(nm(p)){let y=wi(i,r.default);n(t(y)),s("done"),e(y);return}if(p.name==="tab"){let y=ga(!wi(i,r.default));f.clearLine(0),f.write(y),n(y);return}if(p.name==="y"||p.name==="n"){let y=wi(p.name,r.default);n(t(y)),s("done"),e(y);return}f.clearLine(0),f.write(i),n(f.line)});let l=i,d="";o==="done"?l=a.style.answer(i):d=` ${a.style.defaultAnswer(r.default===!1?"y/N":"Y/n")}`;let u=a.style.message(r.message,o);return`${c} ${u}${d} ${l}`});var Z=Oe(async({message:r,default:e})=>await ha({message:r,default:e}));var gm=m(r=>pm(r,xr),"getDeprecatedLocalConfigPath"),mo=new Map;async function Le({cwd:r=ya.cwd(),migrateConfig:e=!0,warnAboutOldConfig:t=!0}={cwd:ya.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let o=mo.get(r);if(o)return T("useActorConfig",{cacheHit:!0,config:o}),uo(o);let s=oi(r),i=gm(r),n,a;try{n=de(s)}catch(l){return mr({message:`Failed to read local config at path: '${s}':`,cause:l,exists:!1,config:{}})}try{a=de(i)}catch(l){return mr({message:`Failed to read local config at path: '${i}':`,cause:l,exists:!1,config:{}})}if(n&&a&&t&&await hm(i),!n&&!a)return mo.set(r,{exists:!1,migrated:!1,config:{}}),uo({exists:!1,migrated:!1,config:{}});let c=!1;if(!n&&a&&e){let l=await wm(a,i,s);if(l.isErr())return mr(l.unwrapErr());n=l.unwrap(),c=!0}return mo.set(r,{exists:!0,migrated:c,config:n||a||{}}),T("useActorConfig",{cacheHit:!1,config:mo.get(r)}),uo({exists:!0,migrated:c,config:n||a||{}})}m(Le,"useActorConfig");async function hm(r){if(!await Z({message:'The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Since we have found both files in your Actor directory, "apify.json" will be renamed to "apify.json.deprecated". Going forward, all commands will use ".actor/actor.json". You can read about the differences between the old and the new config at https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md. Do you want to continue?'})){x({message:'The "apify.json" file present in your Actor directory will be ignored, and the new ".actor/actor.json" file will be used instead. Please, either rename or remove the old file.'});return}try{await wa(r,`${r}.deprecated`),b({message:'The "apify.json" file has been renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted.'})}catch(t){t instanceof Error?g({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
|
|
70
|
-
${t.message||t}`}):g({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
|
|
71
|
-
${fm(t,{showHidden:!1})}`})}}m(hm,"handleBothConfigVersionsFound");var ym=["name","version","buildTag"];async function wm(r,e,t){let o={...r};if(typeof o.version=="object"&&(o=Am(o)),o={actorSpecification:Ws,environmentVariables:r?.env||void 0,...ym.reduce((i,n)=>(i[n]=r[n],i),{})},!await Z({message:'The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Your "apify.json" file will be automatically updated to the new format under ".actor/actor.json". The original file will be renamed by adding the ".deprecated" suffix. Do you want to continue?'}))return mr({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 dm(um(t),{recursive:!0}),await mm(t,JSON.stringify(o,null," "))}catch(i){let n=i;return mr({message:`Failed to write the new "actor.json" file to path: '${t}'.
|
|
72
|
-
${n.message||n}`,exists:!0,config:o})}try{await wa(e,`${e}.deprecated`)}catch(i){let n=i;x({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
|
|
73
|
-
${n.message||n}`})}return b({message:'The "apify.json" file has been migrated to ".actor/actor.json" and the original file renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted. Do not forget to commit the new file to your Git repository.'}),uo(o)}m(wm,"handleMigrationFlow");function Am(r){let e={name:r.name,template:r.template,version:r.version.versionNumber,buildTag:r.version.buildTag,env:null};if(r.version.envVars?.length){let t={};r.version.envVars.forEach(o=>{o.name&&o.value&&(t[o.name]=o.value)}),e.env=t}return e}m(Am,"updateLocalConfigStructure");var Tm=vm(he("default"),"INPUT.json"),St=class extends h{static name="calculate-memory";static description="Calculates the Actor\u2019s dynamic memory usage based on a memory expression from actor.json, input data, and run options.";static group="Actor Runtime";static examples=[{description:"Calculate memory using the expression and input defaults from actor.json.",command:"actor calculate-memory"},{description:"Override the memory expression and input file.",command:'actor calculate-memory --defaultMemoryMbytes "input.length * 128" --input ./my-input.json'}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-calculate-memory";static flags={input:w.string({description:"Path to the input JSON file used for the calculation.",required:!1,default:Tm}),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=bm(Ai.cwd(),e),a=de(n)??{};b({message:`Evaluating memory expression: ${t}`});try{let c=await Sm(t,{input:a,runOptions:i}),l=Math.min(Math.max(c,o),s);R({message:`Calculated memory: ${l} MB`,stdout:!0})}catch(c){g({message:`Memory calculation failed: ${c.message}`})}}async prepareMemoryArguments(){let{input:e,defaultMemoryMbytes:t,...o}=this.flags,s=t,i=0,n=1/0;return s||({defaultMemoryMbytes:s,minMemoryMbytes:i=i,maxMemoryMbytes:n=n}=await this.getExpressionFromConfig()),{memoryExpression:s,minMemory:i,maxMemory:n,input:e,runOptions:o}}async getExpressionFromConfig(){let e=Ai.cwd(),t=await Le({cwd:e});if(t.isErr()){let{message:s,cause:i}=t.unwrapErr();return g({message:`${s}${i?`
|
|
74
|
-
${i.message}`:""}`}),Ai.exitCode=5,{}}let{config:o}=t.unwrap();return{defaultMemoryMbytes:o?.defaultMemoryMbytes?.toString(),minMemoryMbytes:o?.minMemoryMbytes,maxMemoryMbytes:o?.maxMemoryMbytes}}};import{APIFY_ENV_VARS as _m}from"@apify/consts";import ur from"process";import{pipeline as Cm}from"stream/promises";import{MemoryStorage as Im}from"@crawlee/memory-storage";import{ApifyClient as Em}from"apify-client";import{ACTOR_ENV_VARS as Aa,APIFY_ENV_VARS as va,KEY_VALUE_STORE_KEYS as $m,LOCAL_ACTOR_ENV_VARS as Rm}from"@apify/consts";var pr={KEY_VALUE_STORE:"KEY_VALUE_STORE",DATASET:"DATASET",REQUEST_QUEUE:"REQUEST_QUEUE"},vi=m(async()=>{let r=ur.env[va.TOKEN];if(r)return r;let e=await M();if(!e||!e.token)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN or apify login command.");return e.token},"getApifyTokenFromEnvOrAuthFile"),dt=m(async(r={},e=Reflect.has(ur.env,va.IS_AT_HOME))=>{let t=we();if(t&&!e)return new Im({localDataDirectory:t,...r});let o=await vi();return new Em({...Xt(o),...r})},"getApifyStorageClient"),fr=m(r=>{let e=Aa[`DEFAULT_${r}_ID`];return ur.env[e]||Rm[e]},"getDefaultStorageId"),bi=m(async r=>{let e=await dt(),t=fr(pr.KEY_VALUE_STORE),o=await e.keyValueStore(t).getRecord(r,{stream:!0});o&&await Cm(o.value,ur.stdout,{end:!1})},"outputRecordFromDefaultStore"),ba=m(async()=>bi(ur.env[Aa.INPUT_KEY]||$m.INPUT),"outputInputFromDefaultStore");function xm(r){return{argTag:"string",required:r.required??!1,stdin:r.stdin??1,description:r.description,aliases:r.aliases,catchAll:r.catchAll??!1}}m(xm,"stringArg");var A={string:xm};var Tt=class extends h{static name="charge";static description="Charge for a specific event in a pay-per-event Actor run.";static group="Actor Runtime";static examples=[{description:"Charge one event of the given type.",command:"actor charge result-item"},{description:"Charge 5 events with an idempotency key.",command:"actor charge result-item --count 5 --idempotency-key req-123"},{description:"Test locally without actually charging.",command:"actor charge result-item --test-pay-per-event"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-charge";static args={eventName:A.string({description:"Name of the event to charge for.",required:!0})};static flags={count:w.integer({description:"Number of events to charge.",required:!1,default:1}),"idempotency-key":w.string({description:"Idempotency key for the charge request.",required:!1}),"test-pay-per-event":w.boolean({description:"Test pay-per-event charging without actually charging.",required:!1,default:!1})};async run(){let{eventName:e}=this.args,{count:t,testPayPerEvent:o,idempotencyKey:s}=this.flags;if(!!!process.env.APIFY_IS_AT_HOME){b({message:`No platform detected: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}if(o){b({message:`PPE test mode: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}let n=await vi(),a=await Zt(n);if(!a)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN.");let c=process.env[_m.ACTOR_RUN_ID];if(!c)throw new Error("Charge command must be executed in a running Actor. Run ID not found.");if((await a.run(c).get())?.pricingInfo?.pricingModel!=="PAY_PER_EVENT")throw new Error("Charge command can only be used with pay-per-event pricing model.");b({message:`Charging ${t} events of type "${e}" with idempotency key "${s??"not-provided"}" (runId: ${c}).`,stdout:!0}),await a.run(c).charge({eventName:e,count:t,idempotencyKey:s})}};import{mkdir as Lm,writeFile as ho}from"fs/promises";import $t from"path";import Pa from"process";import{compile as yo}from"json-schema-to-typescript";import{existsSync as Pm,writeFileSync as km}from"fs";import{join as gr}from"path";import{cloneDeep as Om}from"es-toolkit";import{KEY_VALUE_STORE_KEYS as Nm}from"@apify/consts";import{validateInputSchema as Ta}from"@apify/input_schema";var Sa=[".actor/INPUT_SCHEMA.json","./INPUT_SCHEMA.json",".actor/input_schema.json","./input_schema.json"],Ct=m(async({forcePath:r,cwd:e})=>{if(r)return{inputSchema:de(r),inputSchemaPath:r};let t=Me(e);if(typeof t?.input=="object")return{inputSchema:t.input,inputSchemaPath:null};if(typeof t?.input=="string"){let o=gr(e,_r,t.input);return{inputSchema:de(o),inputSchemaPath:o}}for(let o of Sa){let s=gr(e,o);if(Pm(s))return{inputSchema:de(s),inputSchemaPath:s}}return{inputSchema:null,inputSchemaPath:gr(e,Sa[0])}},"readInputSchema"),po=m(async({forcePath:r,cwd:e,getMessage:t})=>{let{inputSchema:o,inputSchemaPath:s}=await Ct({forcePath:r,cwd:e});if(!o)throw new Error(`Input schema has not been found at ${s}.`);b({message:t(s)});let i=new zt({strict:!1});return Ta(i,o),{inputSchema:o,inputSchemaPath:s}},"readAndValidateInputSchema"),fo=m(({cwd:r,key:e,label:t,getRef:o})=>{let s=Me(r),i=o?o(s):s?.storages?.[e];if(typeof i=="object"&&i!==null)return{schema:i,schemaPath:null};if(typeof i=="string"){let n=gr(r,_r,i),a=de(n);return a?{schema:a,schemaPath:n}:(x({message:`${t} schema file not found at ${n} (referenced in '${D}').`}),null)}return null},"readStorageSchema"),Ca=m(({cwd:r})=>{let e=fo({cwd:r,key:"dataset",label:"Dataset"});return e?{datasetSchema:e.schema,datasetSchemaPath:e.schemaPath}:null},"readDatasetSchema"),Ia=m(({cwd:r})=>{let e=fo({cwd:r,key:"output",label:"Output",getRef:m(t=>t?.output,"getRef")});return e?{outputSchema:e.schema,outputSchemaPath:e.schemaPath}:null},"readOutputSchema"),go=m(async r=>{let e={};try{let{inputSchema:t}=await Ct({cwd:r});if(t){let o=new zt({strict:!1});Ta(o,t),e=Object.entries(t.properties).reduce((s,[i,n])=>(s[i]=n.type==="boolean"||n.editor==="hidden"?n.default:n.prefill,s),{})}}catch(t){x({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${t.message}`})}finally{let t=he(),o=gr(r,t,`${Nm.INPUT}.json`);km(o,JSON.stringify(e,null," "))}},"createPrefilledInputFileFromInputSchema"),Ea=m(r=>{let e={};for(let[t,o]of Object.entries(r.properties))o.default!==void 0&&(e[t]=o.default);return e},"getDefaultsFromInputSchema"),$a=m((r,e)=>{let t=Om(r);t.required=[];for(let[o,s]of Object.entries(r.properties)){let i=r.required?.includes(o),n=s.default!==void 0;i&&!n&&(t.required.push(o),s.type==="array"&&(s.minItems=Math.max(1,s.minItems||0)))}return delete t.$schema,e.compile(t)},"getAjvValidator");import{cloneDeep as It}from"es-toolkit";function Si(r){let e=It(r);if(!e.properties||typeof e.properties!="object")return e;let t=e.properties,o=new Set(Array.isArray(e.required)?e.required:[]);for(let[s,i]of Object.entries(t))i.default!==void 0&&o.add(s),i.type==="object"&&i.properties&&(t[s]=Si(i));return e.required=Array.from(o),e}m(Si,"makePropertiesRequired");function Et(r){let e=It(r);if(delete e.required,e.properties&&typeof e.properties=="object"){let t=e.properties;for(let[o,s]of Object.entries(t))s.type==="object"&&s.properties&&(t[o]=Et(s))}return e}m(Et,"clearAllRequired");function Ae(r){let e=It(r);if(delete e.title,e.properties&&typeof e.properties=="object"){let t=e.properties;for(let[o,s]of Object.entries(t))s&&typeof s=="object"&&(t[o]=Ae(s))}e.items&&typeof e.items=="object"&&(e.items=Ae(e.items));for(let t of["allOf","anyOf","oneOf"])Array.isArray(e[t])&&(e[t]=e[t].map(o=>o&&typeof o=="object"?Ae(o):o));for(let t of["definitions","$defs"])if(e[t]&&typeof e[t]=="object"&&!Array.isArray(e[t])){let o=e[t];for(let[s,i]of Object.entries(o))i&&typeof i=="object"&&(o[s]=Ae(i))}e.additionalProperties&&typeof e.additionalProperties=="object"&&(e.additionalProperties=Ae(e.additionalProperties));for(let t of["if","then","else","not"])e[t]&&typeof e[t]=="object"&&(e[t]=Ae(e[t]));if(e.patternProperties&&typeof e.patternProperties=="object"&&!Array.isArray(e.patternProperties)){let t=e.patternProperties;for(let[o,s]of Object.entries(t))s&&typeof s=="object"&&(t[o]=Ae(s))}return e}m(Ae,"stripTitles");function Ra(r){let e=r.fields;if(!e||typeof e!="object"||!e.properties||typeof e.properties!="object")return null;let t=It(e);return t.type||(t.type="object"),t}m(Ra,"prepareFieldsSchemaForCompilation");function xa(r){let e=r.properties;if(!e||typeof e!="object"||Object.keys(e).length===0)return null;let t=It(e);for(let s of Object.values(t))s&&typeof s=="object"&&delete s.template;let o={type:r.type||"object",properties:t};return Array.isArray(r.required)&&(o.required=[...r.required]),o}m(xa,"prepareOutputSchemaForCompilation");function _a(r){let e=r.collections;if(!e||typeof e!="object")return[];let t=[];for(let[o,s]of Object.entries(e)){if(!s||typeof s!="object")continue;let i=s.jsonSchema;if(!i||typeof i!="object"||Object.keys(i).length===0)continue;let n=It(i);n.type||(n.type="object"),t.push({name:o,schema:n})}return t}m(_a,"prepareKvsCollectionsForCompilation");var Dm=`
|
|
75
|
-
// biome-ignore-all lint: generated
|
|
76
|
-
// biome-ignore-all format: generated
|
|
77
|
-
/* eslint-disable */
|
|
78
|
-
/* prettier-ignore-start */
|
|
79
|
-
/*
|
|
80
|
-
* This file was automatically generated by json-schema-to-typescript.
|
|
81
|
-
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
|
|
82
|
-
* and run apify actor generate-schema-types to regenerate this file.
|
|
83
|
-
*/
|
|
84
|
-
`,Rt=class extends h{static name="generate-schema-types";static hiddenAliases=["generate-types"];static description=`Generate TypeScript types from Actor schemas.
|
|
85
|
-
|
|
86
|
-
Generates types from the input schema and, when no custom path is provided,
|
|
87
|
-
also from the Dataset, Output (experimental), and Key-Value Store (experimental)
|
|
88
|
-
schemas defined in '${D}'.
|
|
89
|
-
|
|
90
|
-
Reads the input schema from one of these locations (in priority order):
|
|
91
|
-
1. Object in '${D}' under "input" key
|
|
92
|
-
2. JSON file path in '${D}' "input" key
|
|
93
|
-
3. .actor/INPUT_SCHEMA.json
|
|
94
|
-
4. INPUT_SCHEMA.json
|
|
95
|
-
|
|
96
|
-
Optionally specify custom schema path to use.`;static group="Actor Runtime";static examples=[{description:"Generate TypeScript types from the input schema into the default output directory.",command:"actor generate-schema-types"},{description:"Generate types from a custom schema path.",command:"actor generate-schema-types ./schemas/my-input.json"},{description:"Mark all generated properties as optional.",command:"actor generate-schema-types --all-optional"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-generate-schema-types";static flags={output:w.string({char:"o",description:"Directory where the generated files should be outputted. Defaults to src/.generated/actor/ to stay within the typical tsconfig rootDir.",required:!1,default:$t.join("src",".generated","actor")}),strict:w.boolean({description:"Whether generated interfaces should be strict (no index signature [key: string]: unknown).",required:!1,default:!0}),"all-optional":w.boolean({description:"Mark all properties as optional in generated types.",required:!1,default:!1})};static args={path:A.string({required:!1,description:"Optional path to the input schema file. If not provided, searches default locations."})};async run(){let e=Pa.cwd(),{inputSchema:t}=await po({forcePath:this.args.path,cwd:e,getMessage:m(l=>l?`Generating types from input schema at ${l}`:`Generating types from input schema embedded in '${D}'`,"getMessage")}),o="input",s=this.flags.allOptional?Et(t):Si(t),i={bannerComment:Dm,maxItems:-1,unknownAny:!0,format:!0,additionalProperties:!this.flags.strict,$refOptions:{resolve:{external:!1,file:!1,http:!1}}},n=await yo(Ae(s),o,i),a=$t.resolve(e,this.flags.output);await Lm(a,{recursive:!0});let c=$t.join(a,`${o}.ts`);if(await ho(c,n,"utf-8"),R({message:`Generated types written to ${c}`}),!this.args.path){let l=await Promise.allSettled([this.generateDatasetTypes({cwd:e,outputDir:a,compileOptions:i}),this.generateOutputTypes({cwd:e,outputDir:a,compileOptions:i}),this.generateKvsTypes({cwd:e,outputDir:a,compileOptions:i})]),d=["Dataset","Output","Key-Value Store"],u=!1;for(let[p,f]of l.entries())f.status==="rejected"&&(u=!0,g({message:`Failed to generate types for ${d[p]} schema: ${f.reason instanceof Error?f.reason.message:String(f.reason)}`}));u&&(Pa.exitCode=1)}}async generateDatasetTypes({cwd:e,outputDir:t,compileOptions:o}){let s=Ca({cwd:e});if(!s)return;let{datasetSchema:i,datasetSchemaPath:n}=s;n?b({message:`[experimental] Generating types from Dataset schema at ${n}`}):b({message:`[experimental] Generating types from Dataset schema embedded in '${D}'`});let a=Ra(i);if(!a){x({message:"Dataset schema has no fields defined, skipping type generation."});return}let c="dataset",l=this.flags.allOptional?Et(a):a,d=await yo(Ae(l),c,o),u=$t.join(t,`${c}.ts`);await ho(u,d,"utf-8"),R({message:`Generated types written to ${u}`})}async generateOutputTypes({cwd:e,outputDir:t,compileOptions:o}){let s=Ia({cwd:e});if(!s)return;let{outputSchema:i,outputSchemaPath:n}=s;n?b({message:`[experimental] Generating types from Output schema at ${n}`}):b({message:`[experimental] Generating types from Output schema embedded in '${D}'`});let a=xa(i);if(!a){x({message:"Output schema has no properties defined, skipping type generation."});return}let c="output",l=this.flags.allOptional?Et(a):a,d=await yo(Ae(l),c,o),u=$t.join(t,`${c}.ts`);await ho(u,d,"utf-8"),R({message:`Generated types written to ${u}`})}async generateKvsTypes({cwd:e,outputDir:t,compileOptions:o}){let s=fo({cwd:e,key:"keyValueStore",label:"Key-Value Store"});if(!s)return;let{schema:i,schemaPath:n}=s;n?b({message:`[experimental] Generating types from Key-Value Store schema at ${n}`}):b({message:`[experimental] Generating types from Key-Value Store schema embedded in '${D}'`});let a=_a(i);if(a.length===0){x({message:"Key-Value Store schema has no collections with JSON schemas, skipping type generation."});return}let c=[];for(let{name:d,schema:u}of a){let p=this.flags.allOptional?Et(u):u,f=await yo(Ae(p),d,{...o,bannerComment:c.length===0?o.bannerComment:""});c.push(f)}let l=$t.join(t,"key-value-store.ts");await ho(l,c.join(`
|
|
97
|
-
`),"utf-8"),R({message:`Generated types written to ${l}`})}};var xt=class extends h{static name="get-input";static description="Gets the Actor input value from the default key-value store associated with the Actor run.";static group="Actor Runtime";static examples=[{description:"Print the current Actor input to stdout.",command:"actor get-input"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-get-input";async run(){await ba()}};import{ACTOR_ENV_VARS as Ti,APIFY_ENV_VARS as Fm}from"@apify/consts";var _t=class extends h{static name="get-public-url";static description="Get an HTTP URL that allows public access to a key-value store item.";static group="Actor Runtime";static examples=[{description:"Get a public URL for the record stored under the given key.",command:"actor get-public-url OUTPUT"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-get-public-url";static args={key:A.string({required:!0,description:"Key of the record in the key-value store."})};async run(){let{key:e}=this.args;if([void 0,"false",""].includes(process.env[Fm.IS_AT_HOME])){g({message:"get-public-url is not yet implemented for local development"}),process.exitCode=255;return}let t=process.env[Ti.DEFAULT_KEY_VALUE_STORE_ID];if(!t){g({message:`Missing environment variable: ${Ti.DEFAULT_KEY_VALUE_STORE_ID}. Please set it before running the command.`}),process.exitCode=5;return}let o=await dt();if(!await o.keyValueStore(t).get()){g({message:`Key-Value store with ID '${t}' was not found. Ensure the store exists and that the correct ID is set in ${Ti.DEFAULT_KEY_VALUE_STORE_ID}.`}),process.exitCode=250;return}let i=await o.keyValueStore(t).getRecordPublicUrl(e);console.log(i)}};var Pt=class extends h{static name="get-value";static description="Gets a value from the default key-value store associated with the Actor run.";static group="Actor Runtime";static examples=[{description:'Read the record stored under the key "INPUT".',command:"actor get-value INPUT"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-get-value";static args={key:A.string({required:!0,description:"Key of the record in the key-value store."})};async run(){let{key:e}=this.args;await bi(e)}};var kt=class extends h{static name="push-data";static description="Saves data to Actor's run default dataset.";static group="Actor Runtime";static examples=[{description:"Push a single item as an inline JSON argument.",command:`actor push-data '{"key":"value"}'`},{description:"Push an array of items by piping from stdin.",command:"cat ./items.json | actor push-data"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-push-data";static args={item:A.string({description:"JSON string with one object or array of objects containing data to be stored in the default dataset."})};async run(){let{item:e}=this.args,t=e||Re;if(!t){g({message:"No item was provided."});return}let o=await dt(),s=fr(pr.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 Ot=class extends h{static name="set-value";static description="Sets or removes a record in the default key-value store associated with the Actor run.";static group="Actor Runtime";static examples=[{description:'Store a JSON value under the key "OUTPUT".',command:`actor set-value OUTPUT '{"status":"done"}'`},{description:"Store a file as a text record.",command:"cat ./report.txt | actor set-value REPORT --contentType text/plain"},{description:"Delete the record stored under the given key.",command:"actor set-value OUTPUT"}];static docsUrl="https://docs.apify.com/cli/docs/reference#actor-set-value";static args={key:A.string({required:!0,description:"Key of the record in key-value store."}),value:A.string({required:!1,description:`Record data, which can be one of the following values:
|
|
98
|
-
- If empty, the record in the key-value store is deleted.
|
|
99
|
-
- If no \`contentType\` flag is specified, value is expected to be any JSON string value.
|
|
100
|
-
- If options.contentType is set, value is taken as is.`})};static flags={contentType:w.string({char:"c",description:'Specifies a custom MIME content type of the record. By default "application/json" is used.',required:!1})};async run(){let{key:e,value:t}=this.args,{contentType:o="application/json; charset=utf-8"}=this.flags,s=t||process.stdin,n=(await dt()).keyValueStore(fr(pr.KEY_VALUE_STORE));s==null||s===""||s==="null"||s==="undefined"?await n.deleteRecord(e):await n.setRecord({key:e,value:s,contentType:o})}};var wo=class extends h{static name="actor";static description=`Runtime data operations intended to be called from inside a running Actor: read input, push data, get/set records in the default key-value store, charge pay-per-event, generate schema types.
|
|
101
|
-
|
|
102
|
-
For platform-level management (deploy, list, call Actors), see 'apify actors' (plural).`;static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actor";static subcommands=[Ot,kt,Pt,_t,xt,Tt,St,Rt];async run(){this.printHelp()}};import De from"chalk";import Um from"process";async function Je({providedActorNameOrId:r,client:e}){let t=await M(),o=t.username||t.id,s=Me(Um.cwd())||{};if(r?.includes("/")){let i=await e.actor(r).get();return i?{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id}:{valid:!1,reason:`Actor with ID "${r}" was not found`}}if(r){let i=await e.actor(r).get();if(i)return{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id};let n=await e.actor(`${o}/${r.toLowerCase()}`).get();return n?{valid:!0,userFriendlyId:`${n.username}/${n.name}`,id:n.id}:{valid:!1,reason:`Actor with name or ID "${r}" was not found`}}if(s.name){let i=await e.actor(`${o}/${s.name}`).get();return i?{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id}:{valid:!1,reason:`Actor with name "${s.name}" was not found`}}return{valid:!1,reason:"Unable to detect what Actor to create a build for"}}m(Je,"resolveActorContext");var Nt=class extends h{static name="create";static description="Creates a new build of the Actor.";static examples=[{description:'Build the Actor in the current directory with the default "latest" tag.',command:"apify builds create"},{description:"Build a specific Actor with a custom tag and stream the build log.",command:"apify builds create apify/hello-world --tag beta --log"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-create";static flags={tag:w.string({description:'Build tag to be applied to the successful Actor build. By default, this is "latest".'}),version:w.string({description:"Optional Actor Version to build. By default, this will be inferred from the tag, but this flag is required when multiple versions have the same tag.",required:!1}),log:w.boolean({description:"Whether to print out the build log after the build is triggered."})};static args={actorId:A.string({description:"Optional Actor ID or Name to trigger a build for. By default, it will use the Actor from the current directory."})};static enableJsonFlag=!0;async run(){let{tag:e,version:t,json:o,log:s}=this.flags,{actorId:i}=this.args,n=await I(),a=await Je({providedActorNameOrId:i,client:n});if(!a.valid){g({message:`${a.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let c=await n.actor(a.id).get(),d=Vr(c.versions,C=>C.buildTag??"latest")[e??"latest"],u=c.versions.find(C=>C.versionNumber===t),p,f=e;if(u){if(e&&(!d||!d.some(C=>C.versionNumber===t))){g({message:`The Actor Version "${t}" does not have the tag "${e}".`,stdout:!0});return}p=t,f=u.buildTag??"latest"}else if(d&&(p=d[0].versionNumber,f=e??"latest",d.length>1&&!t)){g({message:`Multiple Actor versions with the tag "${e}" found. Please specify the version number using the "--version" flag.
|
|
103
|
-
Available versions for this tag: ${d.map(C=>De.yellow(C.versionNumber)).join(", ")}`,stdout:!0});return}if(!p){g({message:`No Actor versions with the tag "${e}" found. You can push a new version with this tag by using "apify push --build-tag=${e}".`,stdout:!0});return}let y=await n.actor(a.id).build(p,{tag:e});if(o){L(y);return}let v=[`${De.yellow("Actor")}: ${c?.username?`${c.username}/`:""}${c?.name??"unknown-actor"} (${De.gray(y.actId)})`,` ${De.yellow("Version")}: ${p} (tagged with ${De.yellow(f)})`,"",`${De.greenBright("Build Started")} (ID: ${De.gray(y.id)})`,` ${De.yellow("Build Number")}: ${y.buildNumber} (will get tagged once finished)`,` ${De.yellow("Started")}: ${Y.display(y.startedAt)}`,""],S=`https://console.apify.com/actors/${y.actId}/builds/${y.buildNumber}`,E=`${De.blue("View in Apify Console")}: ${S}`;if($({message:v.join(`
|
|
104
|
-
`),stdout:!0}),s){try{await ke({job:y,apifyClient:n})}catch(C){g({message:`Failed to print log for build with ID "${y.id}": ${C.message}`,stdout:!0})}$({message:"",stdout:!0})}$({message:E,stdout:!0})}};var Ao=class extends Nt{static name="build"};import La from"process";import{DownloadItemsFormat as Gm}from"apify-client";import ce from"chalk";import{access as Mm,readFile as jm}from"fs/promises";import Bm,{resolve as ka}from"path";import Fe from"process";import Vm from"mime";function Oa(r,e){let t,o;if(e)t=e,o="application/json";else{let s=Qt(r);s&&(Vm.getExtension(s.contentType)==="json"?(t=JSON.parse(s.body.toString("utf8")),o="application/json"):(t=s.body,o=s.contentType))}return!t||!o?null:{inputToUse:t,contentType:o}}m(Oa,"resolveInput");async function Lt(r,e,t){let o,s;if(!e&&!t){let i=Re;if(i)try{let n=JSON.parse(i.toString("utf8"));if(Array.isArray(n))return g({message:"The provided input is invalid. It should be an object, not an array."}),Fe.exitCode=5,!1;o=n,s="stdin"}catch(n){return g({message:`Cannot parse JSON input from standard input.
|
|
105
|
-
${n.message}`}),Fe.exitCode=5,!1}}if(e)switch(e[0]){case"-":return g({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),Fe.exitCode=5,!1;default:{let i=await Mm(ka(r,e)).then(()=>!0).catch(()=>!1),n=e.endsWith(".json")||e.endsWith(".json5")||Bm.isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.includes("~")||e.startsWith(".\\")||e.startsWith("..\\");if(i||n)return g({message:'Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead'}),Fe.exitCode=5,!1;try{let a=JSON.parse(e);if(Array.isArray(a))return g({message:"The provided input is invalid. It should be an object, not an array."}),Fe.exitCode=5,!1;o=a,s="input"}catch(a){return g({message:`Cannot parse JSON input.
|
|
106
|
-
${a.message}`}),Fe.exitCode=5,!1}}}else if(t)switch(t[0]){case"-":return g({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),Fe.exitCode=5,!1;default:{let i=ka(r,t),n;try{let a=await jm(i,"utf8"),c=JSON.parse(a);if(Array.isArray(c))return g({message:"The provided input is invalid. It should be an object, not an array."}),Fe.exitCode=5,!1;o=c,s=t}catch(a){n=a}if(n)try{let a=JSON.parse(t);if(Array.isArray(a))return g({message:"The provided input is invalid. It should be an object, not an array."}),Fe.exitCode=5,!1;o=a,s=t}catch{return g({message:`Cannot read input file at path "${i}".
|
|
107
|
-
${n.message}`}),Fe.exitCode=5,!1}}}return o?{input:o,source:s}:void 0}m(Lt,"getInputOverride");import Ci from"process";import vo from"chalk";import{ACTOR_JOB_STATUSES as qe}from"@apify/consts";var Na=[qe.SUCCEEDED,qe.ABORTED,qe.FAILED,qe.TIMED_OUT];async function*Dt(r,e){let t=Ci.cwd(),{actorOrTaskData:o,runOptions:s,type:i,waitForFinishMillis:n,inputOverride:a,silent:c,waitForRunToFinish:l,printRunLogs:d}=e,u=i==="Actor"?"actor":"task",p=Oa(t,a);c||(i==="Actor"?Ce({message:`Calling ${i} ${o.userFriendlyId} (${vo.gray(o.id)})
|
|
108
|
-
`}):o.title?Ce({message:`Calling ${i} ${o.title} (${o.userFriendlyId}, ${vo.gray(o.id)})
|
|
109
|
-
`}):Ce({message:`Calling ${i} ${o.userFriendlyId} (${vo.gray(o.id)})
|
|
110
|
-
`}));let f;try{p&&i==="Actor"?f=await r[u](o.id).start(p.inputToUse,{...s,contentType:p.contentType}):f=await r[u](o.id).start(void 0,s)}catch(y){throw y.type==="record-not-found"?new Error(`${i} ${o.userFriendlyId} (${o.id}) not found!`):y}if(yield f,!c&&d)try{await ke({job:f,timeoutMillis:n,apifyClient:r})==="timeouts"?console.error(`
|
|
111
|
-
${vo.gray("Timeout for printing logs was hit, there may be future logs.")}
|
|
112
|
-
`):console.error()}catch(y){x({message:"Can not get log:"}),console.error(y)}if(f=await r.run(f.id).get(),l)for(;!Na.includes(f.status)&&(f=await r.run(f.id).get(),!Na.includes(f.status));)await new Promise(y=>{setTimeout(y,1e3)});c||(f.status===qe.SUCCEEDED?R({message:`${i} finished.`}):f.status===qe.RUNNING?x({message:`${i} is still running!`}):f.status===qe.ABORTED||f.status===qe.ABORTING?(x({message:`${i} was aborted!`}),Ci.exitCode=3):(g({message:`${i} failed!`}),Ci.exitCode=1)),yield f}m(Dt,"runActorOrTaskOnCloud");var Ft=m(r=>({build:w.string({char:"b",description:'Tag or number of the build to run (e.g. "latest" or "1.2.34").',required:!1}),timeout:w.integer({char:"t",description:`Timeout for the ${r} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:w.integer({char:"m",description:`Amount of memory allocated for the ${r} run, in megabytes.`,required:!1})}),"SharedRunOnCloudFlags");var Ke=class r extends h{static name="call";static description=`Executes Actor remotely using your authenticated account.
|
|
113
|
-
Reads input from local key-value store by default.`;static group="Apify Console";static examples=[{description:"Call the Actor defined in the current directory (from .actor/actor.json).",command:"apify call"},{description:"Call a specific Actor by its full name.",command:"apify call apify/hello-world"},{description:"Call an Actor with inline JSON input.",command:`apify call apify/hello-world --input '{"url":"https://example.com"}'`},{description:"Call an Actor with input from a file and print the dataset on success.",command:"apify call apify/web-scraper --input-file input.json --output-dataset"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-call";static flags={...Ft("Actor"),input:w.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":w.string({char:"f",description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]}),silent:w.boolean({char:"s",description:"Prevents printing the logs of the Actor run to the console.",default:!1}),"output-dataset":w.boolean({char:"o",description:"Prints out the entire default dataset on successful run of the Actor."})};static enableJsonFlag=!0;static args={actorId:A.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${D}' file.`})};async run(){let e=La.cwd(),t=Me(e)||{},o=await I(),s=await M(),i=s.username||s.id;if(this.flags.json&&this.flags.outputDataset){g({message:"You cannot use both the --json and --output-dataset flags when running this command."}),La.exitCode=5;return}let{id:n,userFriendlyId:a,actorData:c}=await r.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),l={waitForFinish:2};this.flags.build&&(l.build=this.flags.build),this.flags.timeout&&(l.timeout=this.flags.timeout),this.flags.memory&&(l.memory=this.flags.memory);let d=await Lt(e,this.flags.input,this.flags.inputFile);if(d===!1)return;let u=!1,p,f,y,v=Dt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:l,type:"Actor",inputOverride:d?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0});for await(let S of v)if(p=S,!u&&(u=!0,!this.flags.silent)){f=`https://console.apify.com/actors/${n}/runs/${S.id}`,y=`https://console.apify.com/storage/datasets/${S.defaultDatasetId}`;let E=[`${ce.yellow("Started")}: ${Y.display(S.startedAt)}`];S.containerUrl&&E.push(`${ce.yellow("Container URL")}: ${ce.blue(S.containerUrl)}`);let C=p.buildNumber.split(".").slice(0,2).join("."),P=c.versions.find(U=>U.versionNumber===C),N=Object.entries(c.taggedBuilds??{}).find(([,U])=>U.buildNumber===S.buildNumber)?.[0],O=[`${ce.yellow("Build")}:`,ce.cyan(p.buildNumber)];N?O.push(`(${ce.yellow(N)})`):O.push(`(${ce.gray("N/A")})`),P&&O.push(`| ${ce.gray("Actor version:")} ${ce.cyan(P.versionNumber)} (${ce.yellow(P.buildTag)})`),E.push(O.join(" ")),E.push(`${ce.yellow("Timeout")}: ${p.options.timeoutSecs.toLocaleString("en-US")} seconds`),E.push(`${ce.yellow("Memory")}: ${p.options.memoryMbytes} MB`),E.push(`${ce.blue("View on Apify Console")}: ${f}`,""),$({message:E.join(`
|
|
114
|
-
`),stdout:!this.flags.json})}if(this.flags.json){L(p);return}if(this.flags.silent||$({message:["",`${ce.blue("Export results")}: ${y}`,`${ce.blue("View on Apify Console")}: ${f}`].join(`
|
|
115
|
-
`),stdout:!0}),this.flags.outputDataset){let S=p.defaultDatasetId,E,C=4;do{if(E=await o.dataset(S).get(),E?.itemCount)break;await new Promise(N=>{setTimeout(N,250)})}while(C--);let P=await o.dataset(S).downloadItems(Gm.JSON,{clean:!0});console.log(P.toString())}}static async resolveActorId({client:e,localActorName:t,usernameOrId:o,providedActorNameOrId:s}){if(s?.includes("/")){let i=await e.actor(s).get();if(!i)throw new Error(`Cannot find Actor with ID '${s}' in your account.`);return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i}}if(s){let i=await e.actor(s).get();if(i)return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i};let n=await e.actor(`${o}/${s.toLowerCase()}`).get();if(n)return{userFriendlyId:`${n.username}/${n.name}`,id:n.id,actorData:n};throw new Error(`Cannot find Actor with name or ID '${s}' in your account.`)}if(t){let i=await e.actor(`${o}/${t}`).get();if(!i)throw new Error(`Cannot find Actor with ID '${o}/${t}' in your account. Call "apify push" to push this Actor to Apify platform.`);return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i}}throw new Error("Please provide an Actor ID or name, or run this command from a directory with a valid Apify Actor.")}};import k from"chalk";import Ym from"cli-table3";var Hm={mid:"","left-mid":"","mid-mid":"","right-mid":"",middle:" ","top-mid":"\u2500","bottom-mid":"\u2500"},Jm={middle:" ","top-mid":"\u2500","bottom-mid":"\u2500",top:"\u2500",bottom:"\u2500","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u2500","right-mid":"\u2524"},qm={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 Km={[-1]:void 0,0:Hm,1:Jm,2:qm};function Wm(r){return Array.from({length:r},()=>"cyan")}m(Wm,"generateHeaderColors");var zm=process.stdout.columns??100,bo=Symbol.for("@apify/cli:responsive-table:skip-column"),B=class r{static{m(this,"ResponsiveTable")}options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=r.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,o=Wm(t.length),s=e===0||e===2,i=Km[e],n=[],a=[],c=[];for(let d of t)this.options.hiddenColumns?.includes(d)||this.rows.some(u=>u[d]===bo)||(n.push(this.options.columnAlignments?.[d]||"left"),r.isSmallTerminal()?(a.push(this.options.breakpointOverrides?.small?.[d]?.label??d),c.push(this.options.breakpointOverrides?.small?.[d]?.valueFrom??d)):(a.push(d),c.push(d)));let l=new Ym({head:a,style:{head:o,compact:s},colAligns:n,chars:i});for(let d of this.rows){let u=c.map(p=>d[p]);l.push(u)}return l.toString()}static isSmallTerminal(){return zm<100}};var So="\u200B",To="\u200B\u200B",Da=new B({allColumns:[So,To],mandatoryColumns:[So,To],columnAlignments:{[So]:"left",[To]:"right"}}),Co=class extends h{static name="info";static description="Get information about an Actor.";static examples=[{description:"Print summary information about an Actor.",command:"apify actors info apify/hello-world"},{description:"Print the Actor README only.",command:"apify actors info apify/hello-world --readme"},{description:"Print the Actor input schema as JSON.",command:"apify actors info apify/hello-world --input"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors-info";static flags={readme:w.boolean({description:"Return the Actor README.",exclusive:["input"]}),input:w.boolean({description:"Return the Actor input schema.",exclusive:["readme"]})};static args={actorId:A.string({description:"The ID of the Actor to return information about.",required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:t,input:o,json:s}=this.flags,i=await I(),n=await Je({providedActorNameOrId:e,client:i});if(!n.valid){g({message:`${n.reason}. Please specify the Actor ID.`,stdout:!0});return}let a=await i.actor(n.id).get(),c=await i.user(a.userId).get();a.actorMaker=c;for(let p of Object.values(a.taggedBuilds??{})){if(!p.buildId)continue;let f=await i.build(p.buildId).get();p.build=f}if(s){L(a);return}let l=a.taggedBuilds?.latest;if(t){if(!l){g({message:"No README found for this Actor.",stdout:!0});return}if(!l.build?.readme){g({message:"No README found for this Actor.",stdout:!0});return}$({message:l.build.readme,stdout:!0})}if(o){if(!l){g({message:"No input schema found for this Actor.",stdout:!0});return}if(!l.build?.inputSchema){g({message:"No input schema found for this Actor.",stdout:!0});return}$({message:l.build.inputSchema,stdout:!0})}let d=[`Information about Actor ${k.yellow(`${a.username}/${a.name}`)} (${k.gray(a.id)})`,""];a.title&&d.push(`${k.yellow("Title:")} ${k.bold(a.title)}`),a.description&&d.push(`${k.yellow("Description:")} ${a.description}`),d.push(`${k.yellow("Created at:")} ${k.cyan(Y.display(a.createdAt))} ${k.gray("|")} ${k.yellow("Updated at:")} ${k.cyan(Y.display(a.modifiedAt))}`),a.actorMaker&&(d.push("",`${k.yellow("Made by:")} ${k.cyan(a.actorMaker.profile.name??a.actorMaker.username)}`),Reflect.get(a,"isCritical")&&(d[d.length-1]+=` ${k.bgGray("Maintained by Apify")}`)),a.isPublic?d.push("",`${k.yellow("Actor is")} ${k.green("PUBLIC")}`):d.push("",`${k.yellow("Actor is")} ${k.cyan("PRIVATE")}`),a.isDeprecated&&d.push("",`${k.yellow("Actor is")} ${k.red("DEPRECATED")}`);let u=Reflect.get(a,"pricingInfos");if(u?.length){let p=u.at(-1);switch(p.pricingModel){case"FLAT_PRICE_PER_MONTH":{if(d.push(`${k.yellow("Pricing information:")} ${k.bgGray(`$${p.pricePerUnitUsd}/month + usage`)}`),p.trialMinutes){let f=p.trialMinutes*60*1e3,y=rr.format(f);d.push(` ${k.yellow("Trial duration:")} ${k.bold(y)}`)}break}case"PRICE_PER_DATASET_ITEM":{let f=p.pricePerUnitUsd*1e3;d.push(`${k.yellow("Pricing information:")} ${k.bgGray(`$${f.toFixed(2)} / 1,000 results`)}`);break}case"PAY_PER_EVENT":{d.push(`${k.yellow("Pricing information:")} ${k.bgGray("Pay per event")}`);let f=Object.values(p.pricingPerEvent?.actorChargeEvents??{});for(let S of f)Da.pushRow({[So]:S.eventTitle,[To]:k.bold(`$${S.eventPriceUsd.toFixed(2)}`)});let v=Da.render(0).split(`
|
|
116
|
-
`);v.splice(1,1),d.push(v.join(`
|
|
117
|
-
`));break}case"FREE":{d.push(`${k.yellow("Pricing information:")} ${k.bgGray("Pay for usage")}`);break}default:d.push(`${k.yellow("Pricing information:")} ${k.bgGray(`Unknown pricing model (${k.yellow(p.pricingModel)})`)}`)}}else d.push(`${k.yellow("Pricing information:")} ${k.bgGray("Pay for usage")}`);if((a.seoTitle||a.seoDescription)&&(d.push("",k.yellow("SEO information:")),a.seoTitle&&d.push(` ${k.yellow("Title:")} ${a.seoTitle}`),a.seoDescription&&d.push(` ${k.yellow("Description:")} ${a.seoDescription}`)),a.taggedBuilds){d.push("",k.yellow("Builds:"));let p=a.taggedBuilds.latest;p&&d.push(` ${k.yellow("-")} ${k.cyan(p.buildNumber)} ${k.gray("/")} ${k.yellow("latest")}`);for(let[f,y]of Object.entries(a.taggedBuilds))f!=="latest"&&d.push(` ${k.yellow("-")} ${k.cyan(y.buildNumber)} ${k.gray("/")} ${k.yellow(f)}`)}$({message:d.join(`
|
|
118
|
-
`),stdout:!0})}};import{Time as Xm}from"@sapphire/duration";import Q from"chalk";import je from"chalk";function Pe(r){switch(r){case"READY":return je.green("Ready");case"RUNNING":return je.blue("Running");case"SUCCEEDED":return je.green("Succeeded");case"FAILED":return je.red("Failed");case"ABORTING":return je.yellow("Aborting");case"ABORTED":return je.red("Aborted");case"TIMING-OUT":return je.yellow("Timing Out");case"TIMED-OUT":return je.red("Timed Out");default:return je.gray(r.split("-").map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(" "))}}m(Pe,"prettyPrintStatus");var Zm={"TIMED-OUT":Q.gray("after"),"TIMING-OUT":Q.gray("after"),ABORTED:Q.gray("after"),ABORTING:Q.gray("after"),FAILED:Q.gray("after"),READY:Q.gray("for"),RUNNING:Q.gray("for"),SUCCEEDED:Q.gray("after")},Qm=new B({allColumns:["Name","Runs","Last run started at","Last run status","Last run duration","_Small_LastRunText"],mandatoryColumns:["Name","Runs","Last run status","Last run duration"],columnAlignments:{Runs:"right","Last run duration":"right",Name:"left","Last run status":"center"},hiddenColumns:["_Small_LastRunText"],breakpointOverrides:{small:{"Last run status":{label:"Last run",valueFrom:"_Small_LastRunText"}}}}),eu=new B({allColumns:["Name","Modified at","Builds","Default build","Runs","Last run","Last run status","Last run duration","_Small_LastRunText"],mandatoryColumns:["Name","Runs","Last run","Last run duration"],hiddenColumns:["_Small_LastRunText"],columnAlignments:{Builds:"right",Runs:"right","Last run duration":"right",Name:"left","Last run status":"center"},breakpointOverrides:{small:{"Last run":{label:"Last run",valueFrom:"_Small_LastRunText"}}}}),Io=class extends h{static name="ls";static description="Prints a list of recently executed Actors or Actors you own.";static examples=[{description:"List Actors you recently interacted with.",command:"apify actors ls"},{description:"List Actors you own, newest first.",command:"apify actors ls --my --desc"},{description:"List the next page of 50 Actors.",command:"apify actors ls --limit 50 --offset 50"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors-ls";static flags={my:w.boolean({description:"Whether to list Actors made by the logged in user.",default:!1}),offset:w.integer({description:"Number of Actors that will be skipped.",default:0}),limit:w.integer({description:"Number of Actors that will be listed.",default:20}),desc:w.boolean({description:"Sort Actors in descending order.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:t,offset:o,my:s,json:i}=this.flags,n=await I(),a=await n.actors().list({limit:t,offset:o,desc:e,my:s});if(a.count===0){if(i){L(a);return}b({message:s?"You don't have any Actors yet!":"There are no recent Actors used by you.",stdout:!0});return}let c={...a,items:await Promise.all(a.items.map(async u=>{let p=await n.actor(u.id).get(),f=await n.actor(u.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...u,actor:p??null,lastRun:f.items[0]??null}}))};if(c.items=s?this.sortByModifiedAt(c.items):this.sortByLastRun(c.items),i){L(c);return}let l=s?eu:Qm,d=c.items.reduce((u,p)=>{let f=`${p.username}/${p.name}`;return f.length>u?f.length:u},0)+2+6;for(let u of c.items){let p=u.stats.lastRunStartedAt?tr.display(u.stats.lastRunStartedAt):"",f=u.lastRun?(()=>{if(u.lastRun.finishedAt)return me.format(u.lastRun.finishedAt.getTime()-u.lastRun.startedAt.getTime());let S=Date.now()-u.lastRun.startedAt.getTime();return`${me.format(S)}\u2026`})():"",y=u.actor?(()=>{let S=Object.entries(u.actor.taggedBuilds??{}).find(([E,C])=>C.buildNumber===u.actor.defaultRunOptions.build||E===u.actor.defaultRunOptions.build);return S?`${Q.yellow(S[0])} / ${Q.cyan(S[1].buildNumber??u.actor.defaultRunOptions.build)}`:Q.gray("Unknown")})():Q.gray("Unknown"),v=(()=>{if(u.lastRun){let E=[Pe(u.lastRun.status)];if(f&&E.push(Zm[u.lastRun.status],Q.cyan(f)),u.lastRun.finishedAt){let C=Date.now()-u.lastRun.finishedAt.getTime();C<Xm.Week?E.push(`
|
|
119
|
-
`,Q.gray(`${me.format(C)} ago`)):E.push(`
|
|
120
|
-
`,Q.gray("On",bn.display(u.lastRun.finishedAt)))}return E.join(" ")}return""})();l.pushRow({Name:`${u.title}
|
|
121
|
-
${Q.gray(`${u.username}/${u.name}`)}`,Runs:B.isSmallTerminal()&&d>=56?bo:Q.cyan(`${u.stats?.totalRuns??0}`),"Last run started at":p,"Last run":p,"Last run status":u.lastRun?Pe(u.lastRun.status):"","Modified at":tr.display(u.modifiedAt),Builds:u.actor?Q.cyan(u.actor.stats.totalBuilds):Q.gray("Unknown"),"Last run duration":B.isSmallTerminal()?bo:Q.cyan(f),"Default build":y,_Small_LastRunText:v})}$({message:l.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((t,o)=>{let s=new Date(t.modifiedAt);return new Date(o.modifiedAt).getTime()-s.getTime()})}sortByLastRun(e){return e.sort((t,o)=>{let s=new Date(t.stats?.lastRunStartedAt??"1970-01-01T00:00Z");return new Date(o.stats?.lastRunStartedAt??"1970-01-01T00:00Z").getTime()-s.getTime()})}};import{mkdirSync as Fa,readdirSync as tu,writeFileSync as Ua}from"fs";import{dirname as ru,join as ou}from"path";import Ma from"process";import su from"adm-zip";import iu from"axios";import ja from"jju";import{gt as nu}from"semver";import au from"tiged";var Ba=m(async(r,e)=>{let{data:t}=await iu.get(r,{responseType:"arraybuffer"}),o=new su(Buffer.from(t,"binary"));o.extractEntryTo(o.getEntries()[0].entryName,e,!1)},"extractGitHubZip"),Ut=class extends h{static name="pull";static description="Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.";static group="Local Actor Development";static examples=[{description:"Pull the Actor linked to the current directory from the Apify platform.",command:"apify pull"},{description:"Pull a specific Actor by its full name into a target directory.",command:"apify pull apify/hello-world --dir ./hello-world"},{description:"Pull a specific version of an Actor.",command:"apify pull apify/hello-world --version 1.2"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-pull";static flags={version:w.string({char:"v",description:"Actor version number which will be pulled, e.g. 1.2. Default: the highest version.",required:!1}),dir:w.string({description:"Directory where the Actor should be pulled to.",required:!1})};static args={actorId:A.string({required:!1,description:'Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.'})};async run(){let e=Ma.cwd(),t=await Le({cwd:e});if(t.isErr()){g({message:t.unwrapErr().message}),Ma.exitCode=5;return}let{config:o}=t.unwrap(),s=await M(),i=await I(),n=!this.args.actorId,a=s.username||s.id,c=this.args?.actorId||o?.id||(o?.name?`${a}/${o.name}`:void 0);if(!c)throw new Error("Cannot find Actor in this directory.");let l;try{l=await i.actor(c).get()}catch{throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`)}if(!l)throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`);let{name:d,versions:u}=l,p=m(()=>{throw new Error("You cannot pull source code of this Actor because you do not have permission to do so.")},"throwMissingSourceCodeAccessError");if(!l.versions.length)throw new Error(`Actor ${c} has no versions.`);let f=null;if(this.flags.version&&(f=u.find(S=>S.versionNumber===this.flags.version),!f))throw new Error(`Cannot find version ${this.flags.version} of Actor ${c}.`);f||(f=u.reduce((S,E)=>nu(`${E.versionNumber}.0`,`${S.versionNumber}.0`)?E:S));let y=n?e:ou(e,this.flags.dir??d);if(Fa(y,{recursive:!0}),!n&&tu(y).length!==0){g({message:`Directory ${y} is not empty. Please empty it or choose another directory.`});return}let{sourceType:v}=f;switch(v){case"TARBALL":{f.tarballUrl||p(),await Ba(f.tarballUrl,y);break}case"SOURCE_FILES":{f.sourceFiles||p();let{sourceFiles:S}=f;for(let E of S){let C=ru(E.name);if(Fa(`${y}/${C}`,{recursive:!0}),!E.folder){let P=E.format==="BASE64"?Buffer.from(E.content,"base64").toString():E.content;if(E.name===D){let N=ja.parse(P);N.name=l.name,Ua(`${y}/${E.name}`,ja.update(P,N))}else Ua(`${y}/${E.name}`,P)}}break}case"GIT_REPO":{f.gitRepoUrl||p();let{gitRepoUrl:S}=f,[E,C]=S.split("#"),P,N;C&&([P,N]=C.split(":"));let O=E;N&&(O+=`/${N}`),P&&(O+=`#${P}`);let U=au(O);try{await U.clone(y)}catch(J){throw new Error(`Failed to pull Actor from ${S}. ${J.message}`)}break}case"GITHUB_GIST":{f.gitHubGistUrl||p(),await Ba(`${f.gitHubGistUrl}/archive/master.zip`,y);break}default:throw new Error(`Unknown source type: ${v}`)}R({message:n?`Actor ${d} updated at ${y}/`:`Pulled to ${y}/`})}};import{readFileSync as du,statSync as mu,unlinkSync as uu}from"fs";import{join as pu,resolve as fu}from"path";import mt from"process";import gu from"open";import{fetchManifest as hu}from"@apify/actor-templates";import{ACTOR_JOB_STATUSES as ut,ACTOR_SOURCE_TYPES as Ei,MAX_MULTIFILE_BYTES as za}from"@apify/consts";import{createHmacSignature as yu}from"@apify/utilities";import{readFileSync as cu,writeFileSync as lu}from"fs";var Ii="@",Va=100,Ga=5e4,Mt=m(()=>{try{return JSON.parse(cu(Er(),"utf-8"))||{}}catch{return{}}},"getSecretsFile"),Ya=m(r=>(si(Er()),lu(Er(),JSON.stringify(r,null," ")),r),"writeSecretsFile"),Ha=m((r,e)=>{let t=Mt();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>Va)throw new Error(`Secret name has to be string with maximum length ${Va}.`);if(typeof e!="string"||e.length>Ga)throw new Error(`Secret value has to be string with maximum length ${Ga}.`);return t[r]=e,Ya(t)},"addSecret"),Ja=m(r=>{let e=Mt();if(!e[r])throw new Error(`Secret with name ${r} doesn't exist.`);delete e[r],Ya(e)},"removeSecret"),qa=m(r=>new RegExp(`^${Ii}.{1}`).test(r),"isSecretKey"),Ka=m((r,e,{allowMissing:t=!1}={})=>{e=e||Mt();let o={},s=[];if(Object.keys(r).forEach(i=>{if(qa(r[i])){let n=r[i].replace(new RegExp(`^${Ii}`),"");e[n]?o[i]=e[n]:s.push(n)}else o[i]=r[i]}),s.length>0){let i=s.map(n=>` - ${n}`).join(`
|
|
122
|
-
`);if(t)for(let n of s)x({message:`Value for ${n} not found in local secrets. Set it by calling "apify secrets add ${n} [SECRET_VALUE]"`});else throw new Error(`The following secrets are missing:
|
|
123
|
-
${i}
|
|
124
|
-
|
|
125
|
-
Set them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
|
|
126
|
-
If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return o},"replaceSecretsValue"),Wa=m((r,e,{allowMissing:t=!1}={})=>{e=e||Mt();let o=[],s=[];if(Object.keys(r).forEach(i=>{if(qa(r[i])){let n=r[i].replace(new RegExp(`^${Ii}`),"");e[n]?o.push({name:i,value:e[n],isSecret:!0}):s.push(n)}else o.push({name:i,value:r[i]})}),s.length>0){let i=s.map(n=>` - ${n}`).join(`
|
|
127
|
-
`);if(t)for(let n of s)x({message:`Value for ${n} not found in local secrets. Set it by calling "apify secrets add ${n} [SECRET_VALUE]"`});else throw new Error(`The following secrets are missing:
|
|
128
|
-
${i}
|
|
129
|
-
|
|
130
|
-
Set them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
|
|
131
|
-
If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return o},"transformEnvToEnvVars");var $i="temp_file.zip",wu={build:"latest",memoryMbytes:4096,timeoutSecs:3600},Xa="0.0",Au="latest",jt=class extends h{static name="push";static description=`Deploys Actor to Apify platform using settings from '${D}'.
|
|
132
|
-
Files under '${za/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
|
|
133
|
-
Files matched by .gitignore and .actorignore are excluded. Use negation patterns (e.g. !dist/) in .actorignore to force-include git-ignored files.
|
|
134
|
-
Use --force to override newer remote versions.`;static group="Local Actor Development";static examples=[{description:"Deploy the current Actor to the Apify platform.",command:"apify push"},{description:"Deploy to a specific Actor by ID, overriding newer remote versions.",command:"apify push E2jjCZBezvAZnX8Rb --force"},{description:"Deploy without waiting for the build to finish.",command:"apify push --no-wait-for-finish"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-push";static enableJsonFlag=!0;static flags={version:w.string({char:"v",description:`Actor version number to which the files should be pushed. By default, it is taken from the '${D}' file.`,required:!1}),"build-tag":w.string({char:"b",description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${D}' file.`,required:!1}),"wait-for-finish":w.string({char:"w",description:"Seconds for waiting to build to finish, if no value passed, it waits forever.",required:!1}),open:w.boolean({description:"Whether to open the browser automatically to the Actor details page.",default:!1,required:!1}),force:w.boolean({char:"f",description:"Push an Actor even when the local files are older than the Actor on the platform.",default:!1,required:!1}),dir:w.string({description:"Directory where the Actor is located.",required:!1}),"allow-missing-secrets":w.boolean({description:"Allow the command to continue even when secret values are not found in the local secrets storage.",required:!1,default:!1})};static args={actorId:A.string({required:!1,description:`Name or ID of the Actor to push (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will create or modify the Actor with the name specified in '${D}' file.`})};async run(){let e=fu(mt.cwd(),this.flags.dir??"."),t=await gn(e);if(!t.length){g({message:"You need to call this command from a folder that has an Actor in it!"}),mt.exitCode=4;return}if(![xr,"actor.json",".actor/actor.json",".actor"].some(F=>t.some(re=>re===F||re.startsWith(F)))){g({message:["A valid Actor could not be found in the current directory. Please make sure you are in the correct directory.","You can also turn this directory into an Actor by running `apify init`."].join(`
|
|
135
|
-
`)}),mt.exitCode=4;return}let o=await I(),s=await Le({cwd:e});if(s.isErr()){g({message:s.unwrapErr().message}),mt.exitCode=5;return}let{config:i}=s.unwrap(),n=await M(),c=!!n.organizationOwnerUserId?`/organization/${n.id}`:"",l,d,u=!1,p=this.flags.version||i?.version||Xa,f=this.flags.buildTag||i?.buildTag;!f&&p===Xa&&(f=Au);let y=Number.isNaN(this.flags.waitForFinish)?void 0:Number.parseInt(this.flags.waitForFinish,10)*1e3,v=this.args.actorId;if(v){if(d=await o.actor(v).get(),!d)throw new Error(`Cannot find Actor with ID '${v}' in your account.`);l=d.id}else{let F=n.username||n.id;if(d=await o.actor(`${F}/${i.name}`).get(),d)l=d.id;else{let{templates:re}=await hu(),Te=re.find(Cr=>Cr.name===i.template)?.defaultRunOptions||wu,ft={name:i.name,title:i.title,description:i.description,defaultRunOptions:Te,versions:[{versionNumber:p,buildTag:f,sourceType:Ei.SOURCE_FILES,sourceFiles:[]}]};i.usesStandbyMode&&(ft.actorStandby={isEnabled:!0}),d=await o.actors().create(ft),l=d.id,u=!0,b({message:`Created Actor with name ${i.name} on Apify.`})}}let S=o.actor(l);b({message:`Deploying Actor '${i.name}' to Apify.`});let E=await sn(t,e),C,P,N;if(E<za){let F=await S.get();if(!u){let re=t.reduce((Te,ft)=>{let{mtimeMs:Cr,ctimeMs:Ji}=mu(pu(e,ft)),qi=Cr>Ji?Cr:Ji;return Te>qi?Te:qi},0),Se=F?.modifiedAt.valueOf();if(!this.flags.force&&Se&&re<Se&&(i?.name||v))throw new Error(`Actor with identifier "${i?.name||v}" is already on the platform and was modified there since modified locally.
|
|
136
|
-
Skipping push. Use --force to override.`)}P=await fn(t,e),C=Ei.SOURCE_FILES}else{Ce({message:"Zipping Actor files"}),await hn($i,t,e);let F=await o.keyValueStores().getOrCreate(`actor-${l}-source`),re=`version-${p}.zip`,Se=du($i);await o.keyValueStore(F.id).setRecord({key:re,value:Se,contentType:"application/zip"}),uu($i);let Te=new URL(`${o.baseUrl}/key-value-stores/${F.id}/records/${re}?disableRedirect=true`);if(F?.urlSigningSecretKey){let ft=yu(F.urlSigningSecretKey,re);Te.searchParams.set("signature",ft)}N=Te.toString(),C=Ei.TARBALL}let O=await S.version(p).get(),U=i.environmentVariables?Wa(i.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(O){let F={tarballUrl:N,sourceFiles:P,buildTag:f,sourceType:C,envVars:U};await S.version(p).update(F),Ce({message:`Updated version ${p} for Actor ${d.name}.`})}else{let F={versionNumber:p,tarballUrl:N,sourceFiles:P,buildTag:f,sourceType:C,envVars:U};await S.versions().create({...F}),Ce({message:`Created version ${p} for Actor ${d.name}.`})}if(!u&&!!i.usesStandbyMode!=!!d.actorStandby?.isEnabled){let F=!!i.usesStandbyMode;await S.update({actorStandby:{isEnabled:F}}),b({message:`${F?"Enabled":"Disabled"} standby mode for Actor ${d.name}.`})}Ce({message:`Building Actor ${d.name}`});let J=await S.build(p,{useCache:!0,waitForFinish:2});try{await ke({job:J,timeoutMillis:y,apifyClient:o})}catch(F){x({message:"Can not get log:"}),console.error(F)}if(J=await o.build(J.id).get(),this.flags.json){L(J);return}Js({message:"Actor build detail",url:`https://console.apify.com${c}/actors/${J.actId}#/builds/${J.buildNumber}`}),Js({message:"Actor detail",url:`https://console.apify.com${c}/actors/${J.actId}`}),this.flags.open&&await gu(`https://console.apify.com${c}/actors/${J.actId}`),J.status===ut.SUCCEEDED?R({message:"Actor was deployed to Apify cloud and built there."}):J.status===ut.READY?x({message:"Build is waiting for allocation."}):J.status===ut.RUNNING?x({message:"Build is still running."}):J.status===ut.ABORTED||J.status===ut.ABORTING?(x({message:"Build was aborted!"}),mt.exitCode=3):J.status===ut.TIMED_OUT||J.status===ut.TIMING_OUT?(x({message:"Build timed out!"}),mt.exitCode=2):(g({message:"Build failed!"}),mt.exitCode=1)}};var Eo=class extends h{static name="rm";static description="Permanently removes an Actor from your account.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.";static examples=[{description:"Delete an Actor by its full name (prompts for confirmation).",command:"apify actors rm my-username/my-actor"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors-rm";static args={actorId:A.string({description:"The Actor ID to delete.",required:!0})};static flags={...ie()};async run(){let{actorId:e}=this.args,{yes:t}=this.flags,o=await I();if(!await o.actor(e).get()){g({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await Z({message:"Are you sure you want to delete this Actor?",providedConfirmFromStdin:t||void 0})){b({message:`Deletion of Actor "${e}" was canceled.`});return}try{await o.actor(e).delete(),R({message:`Actor with ID "${e}" was deleted.`})}catch(n){let a=n;g({message:`Failed to delete Actor "${e}".
|
|
137
|
-
${a.message||a}`})}}};import{ApifyClient as vu}from"apify-client";import Ri from"chalk";var bu={FREE:"Free",FLAT_PRICE_PER_MONTH:"Subscription",PRICE_PER_DATASET_ITEM:"Pay per result",PAY_PER_EVENT:"Pay per event"};function Su(r){return r?bu[r]??r:Ri.gray("Unknown")}m(Su,"formatPricingModel");function Tu(r,e=60){return r?r.length<=e?r:`${r.slice(0,e-1)}\u2026`:""}m(Tu,"truncateDescription");var $o=class extends h{static name="search";static description=`Searches Actors in the Apify Store.
|
|
138
|
-
|
|
139
|
-
Searches the Apify Store for Actors matching the given query. Results can be filtered by category, author, pricing model, and more. This command does not require authentication.`;static examples=[{description:'Search the Apify Store for "web scraper" Actors.',command:'apify actors search "web scraper"'},{description:"Search for TikTok Actors sorted by popularity, limit to 5 results.",command:'apify actors search "tiktok" --limit 5 --sort-by popularity'},{description:"Find free AI Actors.",command:'apify actors search "ai" --category AI --pricing-model FREE'},{description:"Output results as JSON for scripting.",command:'apify actors search "web scraper" --json'}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors-search";static args={query:A.string({description:"Search query to find Actors by title, name, description, username, or readme.",required:!1})};static flags={"sort-by":w.string({description:"Sort order for the results.",options:["relevance","popularity","newest","lastUpdate"],default:"relevance"}),category:w.string({description:"Filter by category (e.g. AI)."}),username:w.string({description:"Filter by Actor author username."}),"pricing-model":w.string({description:"Filter by pricing model.",options:["FREE","FLAT_PRICE_PER_MONTH","PRICE_PER_DATASET_ITEM","PAY_PER_EVENT"]}),limit:w.integer({description:"Maximum number of results to return.",default:20}),offset:w.integer({description:"Number of results to skip for pagination.",default:0})};static enableJsonFlag=!0;async run(){let{query:e}=this.args,{json:t,sortBy:o,category:s,username:i,pricingModel:n,limit:a,offset:c}=this.flags,l=Xt();delete l.token;let d=new vu(l),u;try{u=await d.store().list({search:e,sortBy:o,category:s,username:i,pricingModel:n,limit:a,offset:c})}catch(f){process.exitCode=1,g({message:`Failed to search Apify Store: ${f instanceof Error?f.message:String(f)}`,stdout:!0});return}if(u.count===0){if(t){L(u);return}b({message:"No Actors found matching your search.",stdout:!0});return}if(t){L(u);return}let p=new B({allColumns:["Name","Description","Users (30d)","Pricing"],mandatoryColumns:["Name","Pricing"],columnAlignments:{"Users (30d)":"right",Name:"left"}});for(let f of u.items)p.pushRow({Name:`${f.title}
|
|
140
|
-
${Ri.gray(`${f.username}/${f.name}`)}`,Description:Tu(f.description),"Users (30d)":Ri.cyan(`${f.stats?.totalUsers30Days??0}`),Pricing:Su(f.currentPricingInfo?.pricingModel)});$({message:p.render(1),stdout:!0})}};import ne from"chalk";var Ro=class extends h{static name="start";static description=`Starts Actor remotely and returns run details immediately.
|
|
141
|
-
Uses authenticated account and local key-value store for input.`;static examples=[{description:"Start the Actor defined in the current directory and return immediately.",command:"apify actors start"},{description:"Start a specific Actor with inline JSON input.",command:`apify actors start apify/hello-world --input '{"url":"https://example.com"}'`},{description:"Start with input from a file and custom memory/timeout.",command:"apify actors start apify/web-scraper --input-file ./input.json --memory 4096 --timeout 600"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors-start";static flags={...Ft("Actor"),input:w.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":w.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]})};static enableJsonFlag=!0;static args={actorId:A.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${D}' file.`})};async run(){let e=process.cwd(),t=Me(e)||{},o=await I(),s=await M(),i=s.username||s.id,{id:n,userFriendlyId:a,actorData:c}=await Ke.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),l={};this.flags.build&&(l.build=this.flags.build),this.flags.timeout&&(l.timeout=this.flags.timeout),this.flags.memory&&(l.memory=this.flags.memory);let d=await Lt(e,this.flags.input,this.flags.inputFile);if(d===!1)return;let u=Dt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:l,type:"Actor",inputOverride:d?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),p;for await(let N of u)p=N;if(this.flags.json){L(p);return}let f=`https://console.apify.com/actors/${n}/runs/${p.id}`,y=`https://console.apify.com/storage/datasets/${p.defaultDatasetId}`,v=[`${ne.gray("Run:")} Calling Actor ${a} (${ne.gray(n)})`,"",`${ne.yellow("Started")}: ${Y.display(p.startedAt)}`];p.containerUrl&&v.push(`${ne.yellow("Container URL")}: ${ne.blue(p.containerUrl)}`);let S=p.buildNumber.split(".").slice(0,2).join("."),E=c.versions.find(N=>N.versionNumber===S),C=Object.entries(c.taggedBuilds??{}).find(([,N])=>N.buildNumber===p.buildNumber)?.[0],P=[`${ne.yellow("Build")}:`,ne.cyan(p.buildNumber)];C?P.push(`(${ne.yellow(C)})`):P.push(`(${ne.gray("N/A")})`),E&&P.push(`| ${ne.gray("Actor version:")} ${ne.cyan(E.versionNumber)} (${ne.yellow(E.buildTag)})`),v.push(P.join(" ")),v.push(`${ne.yellow("Timeout")}: ${p.options.timeoutSecs.toLocaleString("en-US")} seconds`),v.push(`${ne.yellow("Memory")}: ${p.options.memoryMbytes} MB`),v.push("",`${ne.blue("Export results")}: ${y}`,`${ne.blue("View on Apify Console")}: ${f}`),$({message:v.join(`
|
|
142
|
-
`),stdout:!0})}};var xo=class extends h{static name="actors";static description=`Search, list, deploy, and call Actors on the Apify platform.
|
|
143
|
-
For runtime operations inside a running Actor (push-data, get-input, set-value...), see 'apify actor' (singular).`;static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-actors";static subcommands=[Ro,Eo,$o,jt,Ut,Io,Co,Ke,Ao];async run(){this.printHelp()}};import Cu from"process";import We from"chalk";var _i=["GET","POST","PUT","PATCH","DELETE"],Iu=new Set(["GET","HEAD"]),xi="https://docs.apify.com/api/openapi.json";function Eu(r){if(!r)return"";let e;try{e=JSON.parse(r)}catch{throw new Error(`Invalid JSON in --params flag. Please provide a valid JSON object, e.g. '{"limit": 1}'.`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`--params must be a JSON object (e.g. '{"limit": 1}').`);let t=new URLSearchParams;for(let[o,s]of Object.entries(e))if(s!=null){if(typeof s=="object")throw new Error(`--params value for "${o}" must be a scalar (string, number, or boolean), got ${Array.isArray(s)?"array":"object"}. Query parameters cannot contain nested objects or arrays.`);t.append(o,String(s))}return t.toString()}m(Eu,"parseParams");function $u(r){if(!r)return{};let e=r.trim();if(e.startsWith("{")){let o;try{o=JSON.parse(e)}catch{throw new Error(`Invalid JSON in --header flag. Provide a JSON object like '{"X-Foo": "bar"}'.`)}if(o===null||typeof o!="object"||Array.isArray(o))throw new Error("--header JSON must be an object mapping header names to string values.");let s={};for(let[i,n]of Object.entries(o)){if(typeof n!="string")throw new Error(`--header value for "${i}" must be a string, got ${typeof n}.`);s[i.trim()]=n.trim()}return s}let t=e.indexOf(":");if(t===-1)throw new Error('Header must be in "key:value" format, or a JSON object for multiple headers.');return{[e.slice(0,t).trim()]:e.slice(t+1).trim()}}m($u,"parseHeaders");var _o=class extends h{static name="api";static description=`Makes an authenticated HTTP request to the Apify API and prints the response.
|
|
144
|
-
The endpoint can be a relative path (e.g. "acts", "v2/acts", or "/v2/acts"); the "v2/" prefix is added automatically if omitted.
|
|
145
|
-
|
|
146
|
-
Use --list-endpoints to see all available API endpoints.`;static examples=[{description:"Make a GET request to an API endpoint (defaults to GET).",command:"apify api users/me"},{description:"Pass the HTTP method as a positional argument before the endpoint.",command:"apify api GET /v2/actor-runs"},{description:"Create a resource by POSTing a JSON body.",command:`apify api POST acts -d '{"name":"my-actor"}'`},{description:"Pass query parameters as a JSON object.",command:`apify api actor-runs -p '{"limit":1,"desc":true}'`},{description:"Send one or more custom headers as a JSON object.",command:`apify api acts -H '{"X-Foo":"bar","X-Baz":"qux"}'`},{description:"List all available Apify API endpoints.",command:"apify api --list-endpoints"}];static docsUrl="https://docs.apify.com/api/v2";static args={methodOrEndpoint:A.string({required:!1,description:'The API endpoint path (e.g. "acts", "v2/acts", "/v2/users/me"), or an HTTP method followed by the endpoint (e.g. "GET /v2/users/me").'}),endpoint:A.string({required:!1,description:"The API endpoint path when the first argument is an HTTP method."})};static flags={method:w.string({char:"X",description:"The HTTP method to use. Defaults to GET.",choices:_i}),body:w.string({char:"d",description:'The request body (JSON string). Use "-" to read from stdin.',required:!1,stdin:2}),header:w.string({char:"H",description:`Additional HTTP header(s). Pass a single "key:value" string, or a JSON object like '{"X-Foo": "bar", "X-Baz": "qux"}' to send multiple headers. The flag can only be used once; use the JSON form for multiple headers.`,required:!1}),params:w.string({char:"p",description:`Query parameters as a JSON object, e.g. '{"limit": 1, "desc": true}'.`,required:!1}),"list-endpoints":w.boolean({char:"l",description:"List all available Apify API endpoints.",default:!1})};async run(){if(this.flags.listEndpoints){await this.printEndpoints();return}let e=this.flags.method?.toUpperCase(),t,o=this.args.methodOrEndpoint;if(o&&_i.includes(o.toUpperCase())){let f=o.toUpperCase();if(e&&e!==f)throw new Error(`Conflicting HTTP methods: positional "${f}" vs --method "${e}". Please specify the method only once.`);t=f,o=this.args.endpoint}else t=e;if(t??="GET",!o){this.printHelp();return}let s=Eu(this.flags.params),i=$u(this.flags.header);if(this.flags.body){if(Iu.has(t))throw new Error(`HTTP ${t} requests cannot have a request body. Use a different method (e.g. POST, PUT, PATCH) or omit --body.`);try{JSON.parse(this.flags.body)}catch{throw new Error("Invalid JSON in --body flag. Please provide a valid JSON string.")}}let n=await I(),a=n.token,c=o;c.startsWith("/")&&(c=c.slice(1)),c=c.replace(/^v2\//i,"");let l=`${n.baseUrl}/${c}`;if(s){let f=l.includes("?")?"&":"?";l=`${l}${f}${s}`}let d={...Pr,Authorization:`Bearer ${a}`};this.flags.body&&(d["Content-Type"]="application/json");for(let[f,y]of Object.entries(i)){for(let v of Object.keys(d))v.toLowerCase()===f.toLowerCase()&&delete d[v];d[f]=y}let u=await fetch(l,{method:t,headers:d,body:this.flags.body||void 0}),p=await u.text();if(!u.ok){if(Cu.exitCode=1,g({message:`${u.status} ${u.statusText}`}),p)try{let f=JSON.parse(p);$({message:JSON.stringify(f,null,2),stdout:!0})}catch{$({message:p,stdout:!0})}u.status===404&&$({message:`
|
|
147
|
-
Run ${We.cyan("apify api --list-endpoints")} to see all available Apify API endpoints.`,stdout:!1});return}if(p)try{let f=JSON.parse(p);$({message:JSON.stringify(f,null,2),stdout:!0})}catch{$({message:p,stdout:!0})}}async printEndpoints(){let e=await Ru(),t={GET:We.green,POST:We.yellow,PUT:We.blue,PATCH:We.cyan,DELETE:We.red};for(let{method:o,path:s,summary:i}of e){let a=(t[o]||We.white)(o.padEnd(7)),c=i?We.gray(` ${i}`):"";console.log(`${a} ${s}${c}`)}}};async function Ru(){let r;try{r=await fetch(xi)}catch(o){throw new Error(`Failed to download the Apify OpenAPI spec from ${xi}: ${o.message}`)}if(!r.ok)throw new Error(`Failed to download the Apify OpenAPI spec from ${xi}: ${r.status} ${r.statusText}`);let e=await r.json(),t=[];for(let[o,s]of Object.entries(e.paths))for(let[i,n]of Object.entries(s))_i.includes(i.toUpperCase())&&t.push({method:i.toUpperCase(),path:o,summary:n.summary||""});return t.sort((o,s)=>o.path.localeCompare(s.path)||o.method.localeCompare(s.method)),t}m(Ru,"fetchEndpoints");import Pu from"chalk";import ku from"computer-name";import Ou from"cors";import Pi from"express";import Nu from"open";import{cryptoRandomObjectId as Lu}from"@apify/utilities";import xu from"@inquirer/password";var Za=Oe(async({message:r,mask:e})=>await xu({message:r,mask:e??"*"}));import _u from"@inquirer/select";var ze=Oe(async({message:r,choices:e,pageSize:t,loop:o,default:s})=>await _u({message:r,choices:e,pageSize:t,loop:o,default:s}));var Oi="https://console.apify.com/settings/integrations",Du=new URL(Oi).origin,Fu=Oi.includes("localhost")?"http://localhost:3333":void 0,Qa="v1",ki=m(async r=>{let e=await Zt(r,Fu),t=await M();return e?(await Gr(t.id),R({message:`You are logged in to Apify as ${t.username||t.id}. ${Pu.gray(`Your token is stored at ${ge()}.`)}`})):g({message:"Login to Apify failed, the provided API token is not valid."}),e},"tryToLogin"),Bt=class extends h{static name="login";static description=`Authenticates your Apify account and saves credentials to '${le(ge())}'.
|
|
148
|
-
All other commands use these stored credentials.
|
|
149
|
-
|
|
150
|
-
Run 'apify logout' to remove authentication.`;static group="Authentication";static interactive=!0;static interactiveNote="Prompts for an API token if not provided. To run non-interactively, pass --token <api-token>.";static examples=[{description:"Log in interactively (prompts to choose a method, then completes the flow accordingly).",command:"apify login"},{description:"Log in non-interactively with an API token.",command:"apify login --token apify_api_xxxxx"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-login";static flags={token:w.string({char:"t",description:"Apify API token.",required:!1}),method:w.string({char:"m",description:"Method of logging in to Apify.",choices:["console","manual"],required:!1})};async run(){let{token:e,method:t}=this.flags;if(e){await ki(e);return}let o=t;if(t||(o=await ze({message:"Choose how you want to log in to Apify",choices:[{value:"console",name:"Through Apify Console in your default browser",short:"Through Apify Console"},{value:"manual",name:"Enter API token manually",short:"Manually"}],loop:!0})),o==="console"){let s,i=Pi();i.use(Ou({origin:Du,allowedHeaders:["Content-Type","Authorization"]})),i.use((d,u,p)=>{u.set("Connection","close"),p()}),i.use(Pi.json());let n=Lu();i.use((d,u,p)=>{let{token:f}=d.query;if(!f){let y=d.get("Authorization");if(y){let[v,S,...E]=y.trim().split(/\s+/);v.toLowerCase()==="bearer"&&S&&E.length===0&&(f=S)}}f!==n?(u.status(401),u.send("Authorization failed")):p()});let a=Pi.Router();i.use(`/api/${Qa}`,a),a.post("/login-token",async(d,u)=>{try{if(d.body.apiToken)await ki(d.body.apiToken);else throw new Error("Request did not contain API token");u.end()}catch(p){let f=`Login to Apify failed with error: ${p.message}`;g({message:f}),u.status(500),u.send(f)}s.close()}),a.post("/exit",(d,u)=>{d.body.isWindowClosed?g({message:"Login to Apify failed, the console window was closed."}):d.body.actionCanceled?g({message:"Login to Apify failed, the action was canceled in the Apify Console."}):g({message:"Login to Apify failed."}),u.end(),s.close()}),s=i.listen(0);let{port:c}=s.address(),l=new URL(Oi);l.searchParams.set("localCliCommand","login"),l.searchParams.set("localCliPort",`${c}`),l.searchParams.set("localCliToken",n),l.searchParams.set("localCliApiVersion",Qa);try{l.searchParams.set("localCliComputerName",encodeURIComponent(ku()))}catch{}b({message:`Opening Apify Console at "${l.href}"...`}),await Nu(l.href)}else{console.log("Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations");let s=await Za({message:"token:"});await ki(s)}}};var Vt=class extends h{static name="logout";static description=`Removes authentication by deleting your API token and account information from '${le(ge())}'.
|
|
151
|
-
Run 'apify login' to authenticate again.`;static group="Authentication";static examples=[{description:"Remove the stored Apify credentials.",command:"apify logout"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-logout";async run(){await Yt(ge()),await Gr(null),R({message:"You are logged out from your Apify account."})}};var Po=class extends h{static name="token";static description="Prints the current API token for the Apify CLI.";static examples=[{description:"Print the stored API token to stdout (use with care \u2014 it is a secret).",command:"apify auth token"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-auth-token";async run(){await I();let e=await M();e.token&&$({message:e.token,stdout:!0})}};var ko=class extends h{static name="auth";static description="Log in, log out, and inspect your stored Apify API token. Also available as `apify login` / `apify logout`.";static group="Authentication";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-auth";static subcommands=[Bt,Vt,Po];async run(){this.printHelp()}};import Oo from"chalk";var No=class extends h{static name="add-tag";static description="Adds a tag to a specific Actor build.";static examples=[{description:'Tag a successful build as "latest".',command:"apify builds add-tag --build <buildId> --tag latest"},{description:'Tag a build with a custom name like "beta".',command:"apify builds add-tag --build <buildId> --tag beta"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-add-tag";static flags={build:w.string({char:"b",description:"The build ID to tag.",required:!0}),tag:w.string({char:"t",description:"The tag to add to the build.",required:!0})};async run(){let{build:e,tag:t}=this.flags,o=await I(),s=await o.build(e).get();if(!s){g({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(s.status!=="SUCCEEDED"){g({message:`Build with ID "${e}" has status "${s.status}". Only successful builds can be tagged.`,stdout:!0});return}let i=await o.actor(s.actId).get();if(!i){g({message:`Actor with ID "${s.actId}" was not found.`,stdout:!0});return}let a=(i.taggedBuilds??{})[t];if(a?.buildId===e){x({message:`Build "${e}" is already tagged as "${t}".`,stdout:!0});return}try{await o.actor(s.actId).update({taggedBuilds:{[t]:{buildId:s.id}}});let c=a?.buildNumber?` (previously pointed to build ${Oo.gray(a.buildNumber)})`:"";R({message:`Tag "${Oo.yellow(t)}" added to build ${Oo.gray(s.buildNumber)} (${Oo.gray(e)})${c}`,stdout:!0})}catch(c){let l=c;g({message:`Failed to add tag "${t}" to build "${e}".
|
|
152
|
-
${l.message||l}`,stdout:!0})}}};import te from"chalk";var Uu=m(r=>r,"noColor");function ee({bytes:r,shortBytes:e=!1,colorFunc:t=Uu,precision:o=2}){let s=[e?"B":"Bytes","KB","MB","GB","TB"];if(r===0)return e?`${0 .toPrecision(o)} B`:`${0 .toPrecision(o)} Byte`;let i=Math.floor(Math.log(r)/Math.log(1e3));return`${(r/1e3**i).toFixed(o)} ${t(s[i])}`}m(ee,"prettyPrintBytes");var Lo=class extends h{static name="info";static description="Prints information about a specific build.";static examples=[{description:"Print information about a build.",command:"apify builds info <buildId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-info";static args={buildId:A.string({required:!0,description:"The build ID to get information about."})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,t=await I(),o=await t.build(e).get();if(!o){g({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){L(o);return}let s=await t.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[f,y]of Object.entries(s.taggedBuilds))if(y.buildId===o.id){i=f;break}}let n=Reflect.get(o,"exitCode"),a=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",c=i?` (tagged as ${te.yellow(i)})`:"",l=typeof n<"u"?` (exit code: ${te.gray(n)})`:"",d=[`${te.yellow("Actor")}: ${a} (${te.gray(o.actId)})`,"",`${te.yellow("Build Information")} (ID: ${te.gray(o.id)})`,` ${te.yellow("Build Number")}: ${o.buildNumber}${c}`,` ${te.yellow("Status")}: ${Pe(o.status)}${l}`,` ${te.yellow("Started")}: ${Y.display(o.startedAt)}`];if(o.finishedAt)d.push(` ${te.yellow("Finished")}: ${Y.display(o.finishedAt)} (took ${te.gray(rr.format(o.stats?.durationMillis??0))})`);else{let f=Date.now()-o.startedAt.getTime();d.push(` ${te.yellow("Finished")}: ${te.gray(`Running for ${rr.format(f)}`)}`)}o.stats?.computeUnits&&d.push(` ${te.yellow("Compute Units")}: ${o.stats.computeUnits.toFixed(3)}`);let u=Reflect.get(o.stats??{},"imageSizeBytes");u&&d.push(` ${te.yellow("Docker Image Size")}: ${ee({bytes:u})}`),d.push(` ${te.yellow("Origin")}: ${o.meta.origin??"UNKNOWN"}`),d.push("");let p=`https://console.apify.com/actors/${o.actId}/builds/${o.buildNumber}`;d.push(`${te.blue("View in Apify Console")}: ${p}`),$({message:d.join(`
|
|
153
|
-
`),stdout:!0})}};var Do=class extends h{static name="log";static description="Prints the log of a specific build.";static examples=[{description:"Print the build log.",command:"apify builds log <buildId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-log";static args={buildId:A.string({required:!0,description:"The build ID to get the log from."})};async run(){let{buildId:e}=this.args,t=await I(),o=await t.build(e).get();if(!o){g({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}b({message:`Log for build with ID "${e}":
|
|
154
|
-
`});try{await ke({job:o,apifyClient:t})}catch(s){g({message:`Failed to get log for build with ID "${e}": ${s.message}`,stdout:!0})}}};import ve from"chalk";var Mu=m(()=>new B({allColumns:["Number","ID","Status","Took"],mandatoryColumns:["Number","ID","Status","Took"],columnAlignments:{Took:"right"}}),"tableFactory"),Fo=class extends h{static name="ls";static description="Lists all builds of the Actor.";static examples=[{description:"List builds of the Actor in the current directory.",command:"apify builds ls"},{description:"List builds of a specific Actor.",command:"apify builds ls apify/hello-world"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-ls";static flags={offset:w.integer({description:"Number of builds that will be skipped.",default:0}),limit:w.integer({description:"Number of builds that will be listed.",default:10}),desc:w.boolean({description:"Sort builds in descending order.",default:!1}),compact:w.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:A.string({description:"Optional Actor ID or Name to list runs for. By default, it will use the Actor from the current directory."})};static enableJsonFlag=!0;async run(){let{desc:e,limit:t,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await I(),c=await Je({providedActorNameOrId:n,client:a});if(!c.valid){g({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let l=await a.actor(c.id).builds().list({desc:e,limit:t,offset:o}),d=await a.actor(c.id).get(),u=Vr(l.items,y=>{let v=Reflect.get(y,"buildNumber"),[S,E]=v.split(".");return`${S}.${E}`}),p=Object.entries(d.taggedBuilds??{}).reduce((y,[v,S])=>(y[S.buildNumber]=v,y),{});if(i){for(let y of l.items){let v=Reflect.get(y,"buildNumber"),S=p[v];S&&Reflect.set(y,"buildTag",S)}L(l);return}$({message:`${ve.reset("Showing")} ${ve.yellow(l.items.length)} out of ${ve.yellow(l.total)} builds for Actor ${ve.yellow(c.userFriendlyId)} (${ve.gray(c.id)})
|
|
155
|
-
`,stdout:!0});let f=Object.entries(u).sort((y,v)=>y[0].localeCompare(v[0]));for(let[y,v]of f){if(!v?.length){$({message:`No builds for version ${y}`,stdout:!0});continue}let S=d.versions.find(N=>N.versionNumber===y)?.buildTag,E=this.generateTableForActorVersion({buildsForVersion:v,buildTagToActorVersion:p}),C=S?` (latest build gets tagged with ${ve.yellow(S)})`:"",P=[ve.reset(`Builds for Actor Version ${ve.yellow(y)}${C}`),E.render(s?0:-1),""];$({message:P.join(`
|
|
156
|
-
`),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:t}){let o=Mu();for(let s of e){let i=Reflect.get(s,"buildNumber"),n=t[i]?` (${ve.yellow(t[i])})`:"",a;if(s.finishedAt){let c=s.finishedAt.getTime()-s.startedAt.getTime();a=ve.gray(`${me.format(c,void 0,{left:""})}`)}else{let c=Date.now()-s.startedAt.getTime();a=ve.gray(`Running for ${me.format(c,void 0,{left:""})}`)}o.pushRow({Number:`${i}${n}`,ID:ve.gray(s.id),Status:Pe(s.status),Took:a})}return o}};import hr from"chalk";var Uo=class extends h{static name="remove-tag";static description="Removes a tag from a specific Actor build.";static examples=[{description:"Remove a tag from a build (prompts for confirmation).",command:"apify builds remove-tag --build <buildId> --tag beta"},{description:"Remove a tag non-interactively.",command:"apify builds remove-tag --build <buildId> --tag beta --yes"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-remove-tag";static flags={build:w.string({char:"b",description:"The build ID to remove the tag from.",required:!0}),tag:w.string({char:"t",description:"The tag to remove from the build.",required:!0}),...ie()};async run(){let{build:e,tag:t,yes:o}=this.flags,s=await I(),i=await s.build(e).get();if(!i){g({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let n=await s.actor(i.actId).get();if(!n){g({message:`Actor with ID "${i.actId}" was not found.`,stdout:!0});return}let c=(n.taggedBuilds??{})[t];if(!c){g({message:`Tag "${t}" does not exist on Actor "${n.name}".`,stdout:!0});return}if(c.buildId!==e){g({message:`Tag "${t}" is not associated with build "${e}". It points to build "${c.buildNumber}" (${c.buildId}).`,stdout:!0});return}if(!await Z({message:`Are you sure you want to remove tag "${hr.yellow(t)}" from build ${hr.gray(i.buildNumber)}?`,providedConfirmFromStdin:o||void 0})){b({message:"Tag removal was canceled.",stdout:!0});return}try{await s.actor(i.actId).update({taggedBuilds:{[t]:null}}),R({message:`Tag "${hr.yellow(t)}" removed from build ${hr.gray(i.buildNumber)} (${hr.gray(e)})`,stdout:!0})}catch(d){let u=d;g({message:`Failed to remove tag "${t}" from build "${e}".
|
|
157
|
-
${u.message||u}`,stdout:!0})}}};import ju from"@inquirer/input";var ec=Oe(async({message:r,expectedValue:e,failureMessage:t})=>await ju({message:r,validate(s){return s===e?!0:t??"That is not the correct input!"}}));var Mo=class extends h{static name="rm";static description="Permanently removes an Actor build from the Apify platform.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting. Tagged builds additionally require typing the tag name.";static examples=[{description:"Delete a build (prompts for confirmation).",command:"apify builds rm <buildId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds-rm";static args={buildId:A.string({description:"The build ID to delete.",required:!0})};static flags={...ie()};async run(){let{buildId:e}=this.args,{yes:t}=this.flags,o=await I(),s=await o.build(e).get();if(!s){g({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let i=await o.actor(s.actId).get(),n;if(i?.taggedBuilds){for(let[c,l]of Object.entries(i.taggedBuilds))if(e===l.buildId){n=c;break}}let a;if(n?a=await ec({message:`Are you sure you want to delete this Actor Build? If so, please type in "${n}":`,expectedValue:n,failureMessage:"Your provided value does not match the build tag.",providedConfirmFromStdin:t?n:void 0}):a=await Z({message:"Are you sure you want to delete this Actor Build?",providedConfirmFromStdin:t||void 0}),!a){b({message:`Deletion of build "${e}" was canceled.`,stdout:!0});return}try{await o.build(e).delete(),R({message:`Build with ID "${e}" was deleted.`,stdout:!0})}catch(c){let l=c;g({message:`Failed to delete build "${e}".
|
|
158
|
-
${l.message||l}`,stdout:!0})}}};var jo=class extends h{static name="builds";static description="Create, inspect, tag, and delete Actor builds on the Apify platform.";static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-builds";static subcommands=[No,Uo,Mo,Fo,Do,Lo,Nt];async run(){this.printHelp()}};var Bo=class extends Ke{static name="call"};import Bu from"assert";import{existsSync as tc,openSync as Vu}from"fs";import{mkdir as rc,readFile as Gu,symlink as Yu,unlink as Hu,writeFile as oc}from"fs/promises";import{homedir as Ju}from"os";import{dirname as qu,join as Xe}from"path";import{ReadStream as Ku}from"tty";import H from"chalk";import sc from"which";var Wu=m(r=>Xe(r,".install-marker"),"pathToInstallMarker"),ic=m(()=>process.env.HOME??Ju(),"HOMEDIR"),yr=class extends h{static name="install";static description="Finalizes the first-time setup of Apify and Actor CLI.";static hidden=!0;async run(){let{installMethod:e,installPath:t,version:o}=z();if(e!=="bundle"){b({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}Bu(t,"When CLI is installed via bundles, the install path must be set");let s=Wu(t);if(tc(s)){b({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}if(process.platform!=="win32"){await this.symlinkToLocalBin(t);try{await this.promptAddToShell()}catch(i){g({message:i.message||"Failed to automatically handle shell integration"})}$({message:""})}await oc(s,o),T("[install] install marker written to",s),$({message:["",H.green("Apify and Actor CLI were installed successfully!"),"",H.gray(` Version: ${H.green(o)}`),H.gray(` Location: ${H.bold.white(le(Xe(t,"apify")))} and ${H.bold.white(le(Xe(t,"actor")))}`)].join(`
|
|
159
|
-
`)}),$({message:""}),R({message:"To get started, run:"}),$({message:H.white.bold(` apify --help
|
|
160
|
-
actor --help`)})}async symlinkToLocalBin(e){let t=ic();if(T("[install -> symlinkToLocalBin] user home directory",t),!t){T("[install -> symlinkToLocalBin] user home directory not found"),x({message:H.gray("User home directory not found, cannot symlink to ~/.local/bin")});return}let o=Xe(t,".local","bin");await rc(o,{recursive:!0});let s=["apify","actor","apify-cli"];for(let i of s){let n=Xe(e,i);if(!tc(n)){T("[install] file not found for symlinking",i,n),x({message:H.gray(`Bundle not found for symlinking: ${i}`)});continue}let a=Xe(o,i);await Hu(a).catch(()=>{}),await Yu(n,a),T("[install] symlink created for item",i,a)}b({message:H.gray(`Symlinked apify, actor, and apify-cli to ${le(o)}`)})}async confirmFromTty(e){let t,o,s=`${H.green("?")} ${H.bold(e)} ${H.dim("(Y/n)")} `,i=m(n=>{process.stdout.write(`\r\x1B[2K${H.green("?")} ${H.bold(e)} ${H.cyan(n)}
|
|
161
|
-
`)},"writeDone");try{return T("[install] opening /dev/tty for raw mode"),t=Vu("/dev/tty","r"),o=new Ku(t),process.stdout.write(s),o.setRawMode(!0),o.resume(),await new Promise(a=>{let c=m(l=>{let d=l.toString();d==="y"||d==="Y"||d==="\r"||d===`
|
|
162
|
-
`?(o.removeListener("data",c),i("Yes"),a(!0)):d==="n"||d==="N"?(o.removeListener("data",c),i("No"),a(!1)):(d===""||d==="")&&(o.removeListener("data",c),process.stdout.write(`
|
|
163
|
-
`),a(!1))},"onData");o.on("data",c)})}catch(n){return T("[install] failed to open /dev/tty for raw mode",n),!1}finally{o&&(o.setRawMode(!1),o.pause(),o.destroy())}}async promptAddToShell(){let[e,t]=await Promise.allSettled([sc("apify",{nothrow:!0}),sc("actor",{nothrow:!0})]);if(e.status==="fulfilled"&&t.status==="fulfilled"&&e.value&&t.value){T("[install -> promptAddToShell] already in PATH",{apifyCliPath:e,actorCliPath:t}),b({message:H.gray("Apify and Actor CLIs are already in PATH, skipping shell integration")});return}let o=ic();T("[install -> promptAddToShell] user home directory",o);let s=process.env.APIFY_CLI_INSTALL??Xe(o,".apify"),i=process.env.FINAL_BIN_DIR??Xe(s,"bin"),n=process.env.PROVIDED_INSTALL_DIR??s;if(!n){x({message:H.gray("Install directory not found, cannot add to shell")});return}let a=process.env.FINAL_BIN_DIR??i;$({message:""});let c="Should the CLI handle adding itself to your shell automatically?",l;process.env.APIFY_OPEN_TTY?l=await this.confirmFromTty(c):(T("[install] opening /dev/tty for raw mode not requested, falling back to normal flow"),l=await Z({message:c,providedConfirmFromStdin:!1}));let d=Sn(),u=Tn(o,d),p=`"${n.replaceAll('"','\\"')}"`,f=[],y=!0;switch(d){case"bash":case"zsh":{f.push(`export APIFY_CLI_INSTALL=${p}`),f.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"');break}case"fish":{f.push(`set --export APIFY_CLI_INSTALL ${p}`),f.push(`set --export PATH ${a} $PATH`);break}default:{f.push(`export APIFY_CLI_INSTALL=${p}`),f.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),l=!1,y=!1;break}}if($({message:""}),l&&u){let E=`${await Gu(u,"utf-8").catch(C=>{if(C.code==="ENOENT")return"";throw new Error(`Failed to read config file "${le(u)}". Received error code: ${C.code}; ${C.message}`)})}
|
|
164
|
-
|
|
165
|
-
# apify cli
|
|
166
|
-
${f.join(`
|
|
167
|
-
`)}
|
|
168
|
-
`;try{await rc(qu(u),{recursive:!0}),await oc(u,E)}catch(C){throw C.code==="EACCES"?new Error(`Failed to write to config file "${le(u)}", as the CLI does not have permission to write to it.`):new Error(`Failed to write to config file "${le(u)}". Received error code: ${C.code}; ${C.message}`)}b({message:[H.gray(`Added "${le(a)}" to your PATH in ${le(u)}.`),H.gray(` You may need to run ${H.white.bold(`source ${le(u)}`)} to reload your shell.`)].join(`
|
|
169
|
-
`)});return}let v=u??"your shell config file";if(y){let S=`echo -e '${f.join("\\n")}' >> "${v}" && source "${v}"`;b({message:[H.gray("The Apify & Actor CLIs are not in your PATH. Run:"),"",H.white.bold(` ${S}`)].join(`
|
|
170
|
-
`)});return}b({message:[H.gray(`Manually add the following lines to ${v} or similar:`),...f.map(S=>H.white.bold(` ${S}`))].join(`
|
|
171
|
-
`)})}};import{spawn as op}from"child_process";import{existsSync as sp}from"fs";import{lstat as ip,readdir as np,writeFile as cc}from"fs/promises";import{dirname as ap,join as Ni}from"path";import Li from"chalk";import{gte as lc}from"semver";import{Result as zu}from"@sapphire/result";import{execa as Xu}from"execa";var Zu=m(async(r,e,t)=>{let o=Ge(r);T("spawnPromised",{escapedCommand:o,args:e,opts:t});let s=Xu(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 zu.fromAsync(s.catch(i=>{throw new Error(`${r} exited with code ${i.exitCode}`,{cause:i})}))},"spawnPromised");async function fe({cmd:r,args:e=[],opts:t={},overrideCommand:o}){Ce({message:`${o||r} ${e.join(" ")}`});let s=await Zu(r,e,t);if(s.isErr()){let i=s.unwrapErr();if(g({message:i.message}),i.cause)throw i.cause}}m(fe,"execWithLog");import{execSync as nc}from"child_process";import{existsSync as Qu,readFileSync as ep}from"fs";var Be=z();function tp(){return Be.platform==="linux"?Qu("/etc/alpine-release"):!1}m(tp,"isInstalledOnMusl");function rp(){return Be.platform==="darwin"&&Be.arch==="x64"?!nc("sysctl -a",{encoding:"utf-8"}).includes("AVX2"):Be.platform==="linux"&&Be.arch==="x64"?!ep("/proc/cpuinfo","utf-8").includes("avx2"):Be.platform==="windows"?Be.arch==="arm64"?!0:nc(`pwsh -c "!(Add-Type -MemberDefinition '[DllImport(\\"kernel32.dll\\")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);' -Name 'Kernel32' -Namespace 'Win32' -PassThru)::IsProcessorFeaturePresent(40)"`,{encoding:"utf-8",windowsHide:!0}).trim().toLowerCase()==="true":!1}m(rp,"isInstalledOnBaseline");async function ac(r){let e=r.replace(/^v(\d+)/,"$1"),t=e==="latest"?"latest":`tags/v${e}`,o=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/${t}`,{headers:{"User-Agent":nt}});if(!o.ok)return T("useCLIVersionAssets","Failed to fetch release",{statusCode:o.status,body:await o.text(),version:r,tag:t}),null;let s=await o.json(),i=tp(),n=rp(),a=s.assets.filter(c=>{let[l,d,u,p,f,y]=c.name.replace(e,"version").replace(".exe","").split("-");return u!==Be.platform||p!==Be.arch?!1:i?f==="musl":n?y==="baseline"||f==="baseline":!f&&!y});return T("useCLIVersionAssets","Fetched release",{version:s.tag_name,filteredAssets:a}),{assets:a,version:s.tag_name.replace(/^v(\d+)/,"$1")}}m(ac,"useCLIVersionAssets");var dc={bundle:m((r,e)=>[`${e}`,"upgrade"],"bundle"),npm:m(r=>["npm","install","-g",`apify-cli@${r}`],"npm"),pnpm:m(r=>["pnpm","install","-g",`apify-cli@${r}`],"pnpm"),bun:m(r=>["bun","install","-g",`apify-cli@${r}`],"bun"),homebrew:m(()=>["brew","upgrade","apify-cli"],"homebrew"),volta:m(r=>["volta","install",`apify-cli@${r}`],"volta")},Vo="1.0.1",mc="https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1",wr=class extends h{static name="upgrade";static description="Checks that installed Apify CLI version is up to date.";static group="Utilities";static examples=[{description:"Check for a newer CLI version and upgrade if available.",command:"apify upgrade"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-upgrade";static hidden=!0;static aliases=["cv","check-version"];static flags={force:w.boolean({description:"[DEPRECATED] This flag is now ignored, as running the command manually will always check for the latest version.",required:!1,char:"f"}),version:w.string({description:"The version of the CLI to upgrade to. If not provided, the latest version will be used.",required:!1}),"internal-automatic-call":w.boolean({description:"Whether the command was called automatically by the CLI for a version check.",hidden:!0,default:!1})};get cliName(){return this.entrypoint==="apify"?"Apify CLI":"Actor CLI"}async run(){if(this.flags.version){await this.handleInstallSpecificVersion(this.flags.version);return}let e=await ma(!this.flags.internalAutomaticCall),{installMethod:t}=z();if(!e.shouldUpdate||e.currentVersion===qs){T("[upgrade] no update needed",{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||b({message:`${this.cliName} is up to date \u{1F44D}
|
|
172
|
-
`});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion("latest");return}let o=dc[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 ${Li.bgWhite(Li.black(o))} to update! \u{1F44D}
|
|
173
|
-
`].join(`
|
|
174
|
-
`);x({message:s})}async handleInstallSpecificVersion(e){if(e!=="latest"&&!lc(e,Vo)){g({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Vo}.`});return}let t=await ac(e);if(!t){g({message:"The provided version does not exist. Please check the version number and try again."});return}let{assets:o,version:s}=t;if(!lc(s,Vo)){g({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Vo}.`});return}let i=z();if(i.installMethod==="bundle"){if(!o.length){g({message:["Failed to find the assets for your system and the provided version. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:",`- The version you are trying to upgrade to: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`].join(`
|
|
175
|
-
`)});return}let a=ap(process.execPath);T("[upgrade] bundleDirectory",a);let c=await np(a);if(!c.some(l=>l.startsWith("apify")||l.startsWith("actor"))){T("[upgrade] directoryEntries",c),g({message:[`Failed to find the currently installed ${this.cliName} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${a}`].join(`
|
|
176
|
-
`)});return}if(i.platform==="windows")return this.startUpgradeProcess(a,s,o);await this.handleUnixUpgrade(a,s,o),this.successMessage(s);return}let n=dc[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){b({message:`Would run command: ${n.join(" ")}`});return}try{await fe({cmd:n[0],args:n.slice(1)}),this.successMessage(s)}catch{g({message:`Failed to upgrade the CLI. Please run the following command manually: ${n.join(" ")}`})}}successMessage(e){R({message:`Successfully upgraded to ${e} \u{1F44D}`})}async startUpgradeProcess(e,t,o){await this.upsertUpgradeScript(e);let s=["-ExecutionPolicy","Bypass","-File",`"${Ni(e,"upgrade.ps1")}"`,"-ProcessId",process.pid.toString(),"-InstallLocation",`"${e}"`,"-Version",`"${t}"`],i=o.map(a=>a.browser_download_url).join(",");s.push("-AllUrls",`"${i}"`),T("[upgrade] starting upgrade process with args",s),b({message:"Starting upgrade process..."});let n=op("powershell.exe",s,{detached:!0,shell:!0,stdio:"inherit",windowsHide:!1,windowsVerbatimArguments:!0});n.on("spawn",()=>{T("[upgrade] upgrade process spawned"),n.unref(),process.exit(0)}),n.on("error",a=>{g({message:`Failed to start the upgrade process: ${a.message}`})})}async upsertUpgradeScript(e){let t=Ni(e,"upgrade.ps1");if(sp(t))return;let o=z(),s=await fetch(mc,{headers:{"User-Agent":nt}});s.ok||(g({message:["Failed to fetch the upgrade script. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:",`- The system you are running on: ${o.platform} ${o.arch}`,`- The URL of the asset that failed to fetch: ${mc}`,`- The status code of the response: ${s.status}`].join(`
|
|
177
|
-
`)}),process.exit(1));let i=await s.arrayBuffer();await cc(t,Buffer.from(i)),T("[upgrade] downloaded upgrade script to",t)}async handleUnixUpgrade(e,t,o){let s=z();for(let i of o){let n=i.name.split("-")[0],a=Ni(e,n);b({message:`Downloading \`${n}\` binary of the Apify CLI...`});let c=await fetch(i.browser_download_url,{headers:{"User-Agent":nt}});if(!c.ok){let d=await c.text();T("[upgrade] failed to fetch asset",{asset:i,status:c.status,body:d}),g({message:[`Failed to fetch the ${n} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${t}`,`- The system you are running on: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The status code of the response: ${c.status}`,`- The body of the response: ${d}`].join(`
|
|
178
|
-
`)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){b({message:`Would write asset ${n} to ${a}`});continue}b({message:Li.gray(`Writing ${n} to ${a}...`)});let l=await c.arrayBuffer();try{let d=await ip(a).then(u=>u.mode).catch(()=>493);await cc(a,Buffer.from(l),{mode:d|448}),T(`[upgrade ${n}] wrote asset to`,a)}catch(d){T("[upgrade] failed to write asset",{error:d}),g({message:[`Failed to write the ${n} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${t}`,`- The system you are running on: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The error: ${d.message}`].join(`
|
|
179
|
-
`)})}}}};import{mkdir as fp,readdir as gp,stat as wc}from"fs/promises";import{join as pt}from"path";import Ac from"process";import{gte as hp,minVersion as yp}from"semver";import{fetchManifest as wp,manifestUrl as Ap}from"@apify/actor-templates";import{createWriteStream as cp}from"fs";import{pipeline as lp}from"stream/promises";import{Separator as pc}from"@inquirer/core";var uc=["JavaScript","TypeScript","Python"];async function Di(r){return r?(er(r),r):dp()}m(Di,"ensureValidActorName");async function fc(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 yc(t)}m(fc,"getTemplateDefinition");async function gc(r,e){let t=await e;if(t instanceof Error)throw t;try{let o=await Lr(t.localReadmeSuffixUrl),s=cp(r,{flags:"a"});s.write(`
|
|
180
|
-
|
|
181
|
-
`),await lp(o,s)}catch(o){x({message:`Could not append local development instructions to README.md. Cause: ${o.message}`})}}m(gc,"enhanceReadmeWithLocalSuffix");function hc(r){let{actorName:e,dependenciesInstalled:t,postCreate:o,gitRepositoryInitialized:s,installCommandSuggestion:i}=r,n=`\u2705 Actor '${e}' created successfully!`;return t?n+=`
|
|
182
|
-
|
|
183
|
-
Next steps:
|
|
184
|
-
|
|
185
|
-
cd "${e}"
|
|
186
|
-
apify run`:n+=`
|
|
187
|
-
|
|
188
|
-
Next steps:
|
|
189
|
-
|
|
190
|
-
cd "${e}"
|
|
191
|
-
${i||"install dependencies with your package manager"}
|
|
192
|
-
apify run`,n+=`
|
|
193
|
-
|
|
194
|
-
\u{1F4A1} Tip: Use 'apify push' to deploy your Actor to the Apify platform
|
|
195
|
-
\u{1F4D6} Docs: https://docs.apify.com/platform/actors/development`,s&&(n+=`
|
|
196
|
-
\u{1F331} Git repository initialized in '${e}'. You can now commit and push your Actor to Git.`),o&&(n+=`
|
|
197
|
-
|
|
198
|
-
${o}`),n}m(hc,"formatCreateSuccessMessage");async function yc(r){let e=await mp();for(;;){let t=await up(r,e);if(t){if(await pp())return t}else return yc(r)}}m(yc,"executePrompts");async function dp(){return await at({message:"Name of your new Actor:",validate:m(e=>{try{er(e)}catch(t){return t.message}return!0},"validate")})}m(dp,"promptActorName");async function mp(){return await ze({message:"Choose the programming language of your new Actor:",choices:uc,loop:!1,default:uc[0]})}m(mp,"promptProgrammingLanguage");async function up(r,e){let t=[...r.templates.filter(s=>s.category.toLowerCase()===e.toLowerCase()).map(s=>({name:s.label,value:s})),new pc,{name:"Go back",value:!1}];return await ze({message:"Choose a template for your new Actor. You can check more information at https://apify.com/templates.",default:t[0],choices:t,loop:!1,pageSize:8})}m(up,"promptTemplateDefinition");async function pp(){let r=[{name:"Install dependencies",value:!0},new pc,{name:"Go back",value:!1}];return await ze({message:"Almost done! Last step is to install dependencies.",default:r[0],choices:r,loop:!1})}m(pp,"promptTemplateInstallation");var Go=class extends h{static name="create";static description="Creates an Actor project from a template in a new directory. The command automatically initializes a git repository in the newly created Actor directory.";static group="Local Actor Development";static interactive=!0;static interactiveNote="Prompts for an Actor name and template if not provided. To run non-interactively, pass the name as a positional argument and --template.";static examples=[{description:"Create a new Actor project interactively (prompts for name and template).",command:"apify create"},{description:"Create non-interactively with explicit name and template.",command:"apify create my-actor --template js-crawlee-cheerio"},{description:"Create without installing dependencies (faster; run install yourself later).",command:"apify create my-actor --template python-start --skip-dependency-install"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-create";static flags={template:w.string({char:"t",description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${Ap} 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=wp().catch(C=>new Error(`Could not fetch template list from server. Cause: ${C?.message}`));e=await Di(e);let c=Ac.cwd(),l=pt(c,e);for(;;){let C=await wc(l).catch(()=>null),P=C&&await gp(l).then(N=>N.length>0).catch(()=>!1);if(C?.isDirectory()&&P){g({message:`Cannot create new Actor, directory '${e}' already exists. Please provide a different name. You can use "apify init" to create a local Actor environment inside an existing directory.`}),e=await Di(),l=pt(c,e);continue}C||await fp(l,{recursive:!0});break}let d=null;if(this.telemetryData.fromArchiveUrl=!!i,!i){let C=await fc(t,a);({archiveUrl:i,messages:d}=C),this.telemetryData.templateId=C.id,this.telemetryData.templateName=C.name,this.telemetryData.templateLanguage=C.category,"skipOptionalDeps"in C&&(n=C.skipOptionalDeps)}this.flags.omitOptionalDeps&&(n=!0),await Br({url:i,pathTo:l});let u=de(pt(l,D));await Dr(Object.assign(u||Ir,{name:e}),l),await Fr(l),await go(l);let p=pt(l,"package.json"),f=pt(l,"README.md");await gc(f,a);let y=!1;o||await(await Ne({cwd:l})).inspectAsync(async P=>{let N=yp(Ie);if(!P.runtime){switch(P.type){case 0:{x({message:`No Node.js detected! Please install Node.js ${N} or higher to be able to run Node.js Actors locally.`});break}case 2:case 1:{x({message:`No Python detected! Please install Python ${st} or higher to be able to run Python Actors locally.`});break}default:}return}let{runtime:O}=P;switch(P.type){case 0:{jr(O.version)||x({message:`You are running Node.js version ${O.version}, which is no longer supported. Please upgrade to Node.js version ${N} or later.`}),await on(p,{name:e});let U=["install"];if(n)switch(O.pmName){case"npm":{hp(O.pmVersion,"7.0.0")?U.push("--omit=optional"):U.push("--no-optional");break}case"bun":{U.push("--omit=optional");break}case"deno":{U.push("--node-modules-dir");break}default:}await fe({cmd:O.pmPath,args:U,opts:{cwd:l},overrideCommand:O.pmName}),y=!0;break}case 1:case 2:{if(!Mr(O.version)){x({message:`Python Actors require Python 3.9 or higher, but you have Python ${O.version}!`}),x({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}let U=pt(l,".venv");b({message:`Python version ${O.version} detected.`}),b({message:`Creating a virtual environment in "${U}" and installing dependencies from "requirements.txt"...`}),Ac.env.VIRTUAL_ENV||(await fe({cmd:O.executablePath,args:["-m","venv","--prompt",".",en],opts:{cwd:l}}),O=(await nr({cwd:l,force:!0})).unwrap(),P.runtime=O),await fe({cmd:O.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","--upgrade","pip","setuptools","wheel"],opts:{cwd:l}}),await fe({cmd:O.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","-r","requirements.txt"],opts:{cwd:l}}),y=!0;break}default:}});let v={success:!0},S=await wc(pt(c,".git")).catch(()=>null);if(!s&&!S)try{await fe({cmd:"git",args:["init"],opts:{cwd:l}})}catch(C){v={success:!1,error:C}}let E=y?null:await On(l);$({message:""}),R({message:hc({actorName:e,dependenciesInstalled:y,postCreate:d?.postCreate??null,gitRepositoryInitialized:!s&&!S&&v.success,installCommandSuggestion:E})}),!s&&!S&&!v.success&&(x({message:`Failed to initialize git repository: ${v.error.message}`}),x({message:'You can manually run "git init" in the Actor directory if needed.'}))}};import bc from"chalk";async function vc(r,e,t){let o=await r[t](e).get().catch(()=>{});if(o)return{[t]:o,[`${t}Client`]:r[t](o.id)};let s=await M(),i=await r[t](`${s.username}/${e}`).get().catch(()=>{});return i?{[t]:i,[`${t}Client`]:r[t](i.id)}:null}m(vc,"tryToGetStorage");async function Ue(r,e){return vc(r,e,"dataset")}m(Ue,"tryToGetDataset");async function ae(r,e){return vc(r,e,"keyValueStore")}m(ae,"tryToGetKeyValueStore");var Yo=class extends h{static name="create";static description="Creates a new dataset for storing structured data on your account.";static examples=[{description:"Create an unnamed dataset.",command:"apify datasets create"},{description:"Create a named dataset.",command:"apify datasets create my-dataset"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-create";static args={datasetName:A.string({description:"Optional name for the Dataset.",required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,t=await I();if(e&&await Ue(t,e)){g({message:"A Dataset with this name already exists!"});return}let o=await t.datasets().getOrCreate(e);if(this.flags.json){L(o);return}R({message:`Dataset with ID ${bc.yellow(o.id)}${e?` (called ${bc.yellow(e)})`:""} was created.`,stdout:!0})}};import{DownloadItemsFormat as Ze}from"apify-client";var Sc={[Ze.JSON]:"application/json",[Ze.JSONL]:"application/jsonl",[Ze.CSV]:"text/csv",[Ze.HTML]:"text/html",[Ze.RSS]:"application/rss+xml",[Ze.XML]:"application/xml",[Ze.XLSX]:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},Ho=class extends h{static name="get-items";static description="Retrieves dataset items in specified format (JSON, CSV, etc).";static examples=[{description:"Print all items from a dataset as JSON.",command:"apify datasets get-items <datasetId>"},{description:"Export the first 100 items as CSV to a file.",command:"apify datasets get-items <datasetId> --format csv --limit 100 > items.csv"},{description:"Paginate: skip the first 500 items, return the next 500.",command:"apify datasets get-items <datasetId> --offset 500 --limit 500"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-get-items";static flags={limit:w.integer({description:"The amount of elements to get from the dataset. By default, it will return all available items."}),offset:w.integer({description:"The offset in the dataset where to start getting items."}),format:w.string({description:"The format of the returned output. By default, it is set to 'json'.",choices:Object.keys(Sc),default:Ze.JSON})};static args={datasetId:A.string({description:"The ID of the Dataset to export the items for.",required:!0})};async run(){let{limit:e,offset:t,format:o}=this.flags,{datasetId:s}=this.args,i=await I(),n=await this.tryToGetDataset(i,s);if(!n){g({message:`Dataset with ID "${s}" not found.`});return}let{datasetClient:a}=n;process.stdout.write("");let c=await a.downloadItems(o,{limit:e,offset:t}),l=Sc[o]??"application/octet-stream";$({message:l}),process.stdout.write(c),process.stdout.write(`
|
|
199
|
-
`)}async tryToGetDataset(e,t){let o=await e.dataset(t).get().catch(()=>{});if(o)return{dataset:o,datasetClient:e.dataset(o.id)};let s=await M(),i=await e.dataset(`${s.username}/${t}`).get().catch(()=>{});return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};import G from"chalk";function Jo(r){let e=Reflect.get(r,"planPricing");return e?Reflect.get(e,"chargeableServiceUnitPricesUsd"):null}m(Jo,"getUserPlanPricing");var Tc=new B({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),qo=class extends h{static name="info";static description="Prints information about a specific dataset.";static examples=[{description:"Show dataset metadata (item count, size, timestamps).",command:"apify datasets info <datasetId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-info";static args={storeId:A.string({description:"The dataset store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,t=await I(),o=await Ue(t,e);if(!o){g({message:`Key-value store with ID or name "${e}" not found.`});return}let{dataset:s}=o,[i,n,a]=await Promise.all([t.user(s.userId).get().then(F=>F),s.actId?t.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?t.run(s.actRunId).get():Promise.resolve(void 0)]),c;if(a?.actorTaskId&&(c=await t.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){L({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let l=s.stats?.storageBytes||0,d=s.stats?.readCount||0,u=s.stats?.writeCount||0,p=(s.cleanItemCount||0).toLocaleString("en-US"),f=(s.itemCount||0).toLocaleString("en-US"),y=[`${G.bold(d.toLocaleString("en-US"))} ${G.gray(this.pluralString(d,"read","reads"))}`,`${G.bold(u.toLocaleString("en-US"))} ${G.gray(this.pluralString(u,"write","writes"))}`],v=`Items: ${G.bold(p)} ${G.gray("clean")} / ${G.bold(f)} ${G.gray("total")}
|
|
200
|
-
Operations: ${y.join(" / ")}`;if(i.plan){let F=Jo(i.plan);if(F){let re=F.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(l/1e9),Se=re*24*30,Te=Se>1?`$${Se.toFixed(2)}`:`$${re.toFixed(3)}`;v+=`
|
|
201
|
-
Storage size: ${ee({bytes:l,shortBytes:!0,precision:1})} / ${G.gray(`${Te} per month`)}`}}else v+=`
|
|
202
|
-
Storage size: ${ee({bytes:l,shortBytes:!0,precision:1})}`;let S=[`Dataset ID: ${G.bgGray(s.id)}`,`Name: ${s.name?G.bgGray(s.name):G.bold(G.italic("Unnamed"))}`,`Created: ${G.bold(Y.display(s.createdAt))}`,`Modified: ${G.bold(Y.display(s.modifiedAt))}`].join(`
|
|
203
|
-
`),E=G.bold("\u2014");s.actRunId&&(a?E=G.bgBlue(a.id):E=G.italic(G.gray("Run removed")));let C=G.bold("\u2014");n&&(C=G.blue(n.title||n.name));let P=G.bold("\u2014");c&&(P=G.blue(c.title||c.name));let N=[`Run: ${E}`,`Actor: ${C}`,`Task: ${P}`].join(`
|
|
204
|
-
`);Tc.pushRow({Row1:S,Row2:N});let U=Tc.render(2).split(`
|
|
205
|
-
`).map(F=>F.trim());U.shift();let J=[`${G.bold(s.name||G.italic("Unnamed"))}`,`${G.gray(s.name?`${i.username}/${s.name}`:s.id)} ${G.gray("Owned by")} ${G.blue(i.username)}`,"",U.join(`
|
|
206
|
-
`),"",v].join(`
|
|
207
|
-
`);$({message:J,stdout:!0})}};import Cc from"chalk";var Ic=new B({allColumns:["Dataset ID","Name","Items","Size","Created","Modified"],mandatoryColumns:["Dataset ID","Name","Items","Size"],columnAlignments:{Items:"right"}}),Ko=class extends h{static name="ls";static description="Prints all datasets on your account.";static examples=[{description:"List your datasets (most recently modified first).",command:"apify datasets ls --desc"},{description:"List only unnamed (auto-generated) datasets.",command:"apify datasets ls --unnamed"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-ls";static flags={offset:w.integer({description:"Number of datasets that will be skipped.",default:0}),limit:w.integer({description:"Number of datasets that will be listed.",default:20}),desc:w.boolean({description:"Sorts datasets in descending order.",default:!1}),unnamed:w.boolean({description:"Lists datasets that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:t,limit:o,json:s,unnamed:i}=this.flags,n=await I(),a=await M(),c=await n.datasets().list({desc:e,offset:t,limit:o,unnamed:i});if(s){L(c);return}if(c.count===0){b({message:"You don't have any Datasets on your account",stdout:!0});return}for(let l of c.items){let d=Reflect.get(l.stats,"s3StorageBytes");Ic.pushRow({"Dataset ID":l.id,Created:Y.display(l.createdAt),Items:`${l.itemCount}`,Modified:Y.display(l.modifiedAt),Name:l.name?`${a.username}/${l.name}`:"",Size:typeof d=="number"?ee({bytes:d,shortBytes:!0,colorFunc:Cc.gray,precision:0}):Cc.gray("N/A")})}$({message:Ic.render(1),stdout:!0})}};import Wo from"chalk";var zo=class extends h{static name="push-items";static description="Adds data items to specified dataset. Accepts single object or array of objects.";static examples=[{description:"Push a single item as an inline JSON argument.",command:`apify datasets push-items my-dataset '{"url":"https://example.com"}'`},{description:"Push an array of items from stdin.",command:"cat ./items.json | apify datasets push-items my-dataset"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-push-items";static args={nameOrId:A.string({required:!0,description:"The dataset ID or name to push the objects to.",ignoreStdin:!0}),item:A.string({description:"The object or array of objects to be pushed."})};async run(){let{nameOrId:e,item:t}=this.args,o=await I(),s=await Ue(o,e);if(!s){g({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:n}=s,a,c=t||Re;if(!c){g({message:"No items were provided."});return}try{a=JSON.parse(c.toString("utf8"))}catch(d){g({message:`Failed to parse data as JSON string: ${d.message}`});return}if(Array.isArray(a)&&a.length===0){g({message:"No items were provided."});return}let l=n.name?`Dataset named ${Wo.yellow(n.name)} (${Wo.gray("ID:")} ${Wo.yellow(n.id)})`:`Dataset with ID ${Wo.yellow(n.id)}`;try{await i.pushItems(a),R({message:`${this.pluralString(Array.isArray(a)?a.length:1,"Object","Objects")} pushed to ${l} successfully.`})}catch(d){let u=d;g({message:`Failed to push items into ${l}
|
|
208
|
-
${u.message||u}`})}}};import Qe from"chalk";var Xo=class extends h{static name="rename";static description="Change the dataset name or remove the name with --unname flag.";static examples=[{description:"Rename a dataset.",command:"apify datasets rename old-name new-name"},{description:"Remove the name from a dataset (makes it unnamed).",command:"apify datasets rename my-dataset --unname"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-rename";static flags={unname:w.boolean({description:"Removes the unique name of the dataset."})};static args={nameOrId:A.string({description:"The dataset ID or name to delete.",required:!0}),newName:A.string({description:"The new name for the dataset."})};async run(){let{unname:e}=this.flags,{newName:t,nameOrId:o}=this.args;if(!t&&!e){g({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){g({message:"You cannot provide a new name and the --unname flag."});return}let s=await I(),i=await Ue(s,o);if(!i){g({message:`Dataset with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.dataset,c=a?e?`The name of the dataset with ID ${Qe.yellow(n)} has been removed (was ${Qe.yellow(a)} previously).`:`The name of the dataset with ID ${Qe.yellow(n)} was changed from ${Qe.yellow(a)} to ${Qe.yellow(t)}.`:`The name of the dataset with ID ${Qe.yellow(n)} has been set to: ${Qe.yellow(t)}`;try{await i.datasetClient.update({name:e?null:t}),R({message:c,stdout:!0})}catch(l){let d=l;g({message:`Failed to rename dataset with ID ${Qe.yellow(n)}
|
|
209
|
-
${d.message||d}`})}}};import Fi from"chalk";var Zo=class extends h{static name="rm";static description="Permanently removes a dataset.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.";static examples=[{description:"Delete a dataset by name or ID (prompts for confirmation).",command:"apify datasets rm my-dataset"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets-rm";static args={datasetNameOrId:A.string({description:"The dataset ID or name to delete.",required:!0})};static flags={...ie()};async run(){let{datasetNameOrId:e}=this.args,{yes:t}=this.flags,o=await I(),s=await Ue(o,e);if(!s){g({message:`Dataset with ID or name "${e}" not found.`});return}if(!await Z({message:"Are you sure you want to delete this Dataset?",providedConfirmFromStdin:t||void 0})){b({message:"Dataset deletion has been aborted."});return}let{id:n,name:a}=s.dataset;try{await s.datasetClient.delete(),R({message:`Dataset with ID ${Fi.yellow(n)}${a?` (called ${Fi.yellow(a)})`:""} has been deleted.`,stdout:!0})}catch(c){let l=c;g({message:`Failed to delete dataset with ID ${Fi.yellow(n)}
|
|
210
|
-
${l.message||l}`})}}};var Qo=class extends h{static name="datasets";static description="Manage Apify datasets \u2014 create, list, rename, delete, push items, and download items in various formats.";static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-datasets";static subcommands=[Yo,Ho,Ko,qo,Zo,Xo,zo];async run(){this.printHelp()}};import{existsSync as Ui,mkdirSync as vp,readFileSync as bp,writeFileSync as Sp}from"fs";import{dirname as Tp}from"path";import Cp from"cors";import Ip from"detect-indent";import Mi from"express";import Ep from"open";import{cryptoRandomObjectId as $p}from"@apify/utilities";var $c="https://apify.github.io/input-schema-editor-react/",Rp=new URL($c).origin,Ec="v1",es=class extends h{static name="edit-input-schema";static description="Lets you edit your input schema that would be used on the platform in a visual input schema editor.";static group="Local Actor Development";static interactive=!0;static interactiveNote="Opens a browser-based schema editor. Requires a local display; cannot be run headlessly.";static examples=[{description:"Edit the input schema of the Actor in the current directory.",command:"apify edit-input-schema"},{description:"Edit a specific INPUT_SCHEMA.json file.",command:"apify edit-input-schema ./.actor/INPUT_SCHEMA.json"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-edit-input-schema";static args={path:A.string({required:!1,description:"Optional path to your INPUT_SCHEMA.json file. If not provided default platform location for input schema is used."})};static hidden=!0;static aliases=["eis"];async run(){let{inputSchema:e,inputSchemaPath:t}=await Ct({forcePath:this.args.path,cwd:process.cwd()});if(e&&!t)throw new Error(`Editing an input schema directly embedded in '${D}' is not yet supported.`);x({message:`This command is still experimental and might break at any time. Use at your own risk.
|
|
211
|
-
`}),b({message:`Editing input schema at "${t}"...`});let o,s=Mi();s.use(Cp({origin:Rp,allowedHeaders:["Content-Type","Authorization"]})),s.use((u,p,f)=>{p.set("Connection","close"),f()}),s.use(Mi.json());let i=$p();s.use((u,p,f)=>{let{token:y}=u.query;if(!y){let v=u.get("Authorization");if(v){let[S,E,...C]=v.trim().split(/\s+/);S.toLowerCase()==="bearer"&&E&&C.length===0&&(y=E)}}y!==i?(p.status(401),p.send("Authorization failed")):f()});let n=Mi.Router();s.use(`/api/${Ec}`,n);let a=" ",c=!0;n.get("/input-schema",(u,p)=>{let f;try{f=Ui(t)?bp(t,{encoding:"utf-8"}):`{}
|
|
212
|
-
`,f.length>3&&(a=Ip(f).indent||a),f&&(c=f[f.length-1]===`
|
|
213
|
-
`),Ui(t)?b({message:`Input schema loaded from "${t}"`}):b({message:"Empty input schema initialized."})}catch(v){let S=`Reading input schema from disk failed with: ${v.message}`;g({message:S}),p.status(500),p.send(S);return}let y;try{y=JSON.parse(f||"{}")}catch(v){let S=`Parsing input schema failed with error: ${v.message}`;g({message:S}),p.status(500),p.send(S);return}p.send(y),b({message:"Input schema sent to editor."})}),n.post("/input-schema",(u,p)=>{try{b({message:"Got input schema from editor..."});let f=u.body,y=JSON.stringify(f,null,a);c&&(y+=`
|
|
214
|
-
`);let v=Tp(t);Ui(v)||vp(v,{recursive:!0}),Sp(t,y,{encoding:"utf-8",flag:"w+"}),p.end(),b({message:"Input schema saved to disk."})}catch(f){let y=`Saving input schema failed with error: ${f.message}`;g({message:y}),p.status(500),p.send(y)}}),n.post("/exit",(u,p)=>{u.body.isWindowClosed?b({message:"Editor closed, finishing..."}):b({message:"Editing finished, you can close the editor."}),p.end(),o.close(()=>R({message:"Done."}))}),o=s.listen(0);let{port:l}=o.address();b({message:`Listening for messages from input schema editor on port ${l}...`});let d=`${$c}?localCliPort=${l}&localCliToken=${i}&localCliApiVersion=${Ec}`;b({message:`Opening input schema editor at "${d}"...`}),await Ep(d)}};import ts from"chalk";var Ar=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=io(this.entrypoint);console.log(i);return}let t=e.toLowerCase(),o=W.get(t);if(!o){let i=co(t),n=ts.gray(`Command ${ts.whiteBright(e)} not found`);i.length&&(n+=`
|
|
215
|
-
`,n+=ts.gray(`Did you mean: ${i.map(a=>ts.whiteBright(a)).join(", ")}?`)),g({message:n});return}let s=oo(o);console.log(s)}};import Rc from"chalk";var rs=class extends h{static name="info";static description="Prints details about your currently authenticated Apify account.";static group="Apify Console";static examples=[{description:"Print the currently logged-in account username and user ID.",command:"apify info"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-info";async run(){await I();let e=await M();if(e){let t={username:e.username,userId:e.id};for(let o of Object.keys(t))console.log(`${Rc.gray(o)}: ${Rc.bold(t[o])}`)}}};import{basename as Gp}from"path";import Gi from"process";import{appendFileSync as xp,copyFileSync as _p,createWriteStream as Pp,existsSync as ji,mkdirSync as kp,readFileSync as xc,rmSync as Op,writeFileSync as Np}from"fs";import{basename as Lp,join as Bi,relative as _c,sep as Vi}from"path";import{fileURLToPath as Dp}from"url";import Fp from"@root/walk";import Up from"configparser";import Mp from"handlebars";import{fetchManifest as jp,wrapperManifestUrl as Bp}from"@apify/actor-templates";var Vp=[".dockerignore",".gitignore"],os=Dp(new URL("./templates/python-scrapy",import.meta.url));async function Pc(r,e,t={bindings:{}}){await Fp.walk(r,async(o,s,i)=>{if(s===r)return;let n=_c(r,s),a=n.split(Vi).map(l=>{if(l.startsWith("{")&&l.endsWith("}")){l=l.replace("{","").replace("}","");let d=t.bindings[l];if(!d)throw new Error(`Binding for ${l} not found.`);return d}return l}).join(Vi),c=Bi(e,a);if(i.isDirectory())return ji(c)||kp(c),Pc(s,c);n.includes(".template")?Np(Bi(e,a.replace(".template","")),Mp.compile(xc(s,"utf8"))(t.bindings)):ji(c)&&Vp.includes(Lp(a))?xp(c,xc(s)):_p(s,c)})}m(Pc,"merge");async function ss({projectPath:r}){r||(r=".");let e=new ct(r);if(e.configuration.hasSection("apify"))throw new Error("The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?");await e.init();let t=await ze({message:"Pick the Scrapy spider you want to wrap:",choices:e.getAvailableSpiders().map((l,d)=>({name:`${l.class_name} (${l.pathname})`,value:d}))});function o(l){return`.${_c(r,l).split(Vi).slice(1).join(".").replace(".py","")}`}m(o,"translatePathToRelativeModuleName");let s={botName:Ur(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 jp(Bp);b({message:"Downloading the latest Scrapy wrapper template..."});let{archiveUrl:n}=i.templates.find(({id:l})=>l==="python-scrapy");ji(os)&&Op(os,{recursive:!0}),await Br({url:n,pathTo:os}),b({message:"Wrapping the Scrapy project..."}),await Pc(os,r,{bindings:s});let a=new Up;a.addSection("apify"),a.set("apify","mainpy_location",e.settings.BOT_NAME);let c=Pp(Bi(r,"scrapy.cfg"),{flags:"a"});await new Promise(l=>{c.on("open",d=>{c.write(`
|
|
216
|
-
`,()=>{a.write(d),l()})})}),R({message:"The Scrapy project has been wrapped successfully."})}m(ss,"wrapScrapyProject");var is=class extends h{static name="init";static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
|
|
217
|
-
If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
|
|
218
|
-
Creates the '${D}' file and the '${ot}' directory in the current directory, but does not touch any other existing files or directories.
|
|
219
|
-
|
|
220
|
-
WARNING: Overwrites existing '${ot}' directory.`;static group="Local Actor Development";static interactive=!0;static interactiveNote="Prompts for an Actor name if not provided. To run non-interactively, pass the Actor name as a positional argument, or pass --yes to accept the default (current directory name).";static examples=[{description:"Initialize an Actor in the current directory, prompting for a name.",command:"apify init"},{description:"Initialize non-interactively with an explicit Actor name.",command:"apify init my-actor"},{description:"Initialize non-interactively, accepting the default Actor name.",command:"apify init --yes"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-init";static args={actorName:A.string({required:!1,description:"Name of the Actor. If not provided, you will be prompted for it."})};static flags={...ie(),dockerfile:w.string({description:'Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").',required:!1})};async run(){let{actorName:e}=this.args,t=Gi.cwd(),o=await Ne();o.isErr()&&(g({message:o.unwrapErr().message}),Gi.exit(1));let s=o.unwrap();if(s.warnings?.length)for(let a of s.warnings)x({message:a});let i=Gp(t);if(s.type===1&&s.entrypoint?.path){let a=s.entrypoint.path,c=a.includes(".")?a.split(".").pop():a;i=Ur(c)}if(s.type===2)return b({message:"The current directory looks like a Scrapy project. Using automatic project wrapping."}),this.telemetryData.actorWrapper="scrapy",ss({projectPath:t});if(!this.flags.yes&&s.type===3&&(x({message:"The current directory does not look like a Node.js or Python project."}),!await Z({message:"Do you want to continue?",providedConfirmFromStdin:this.flags.yes})))return;let n=await Le({cwd:t});if(n.isOkAnd(a=>a.exists&&!a.migrated))x({message:`Skipping creation of '${D}', the file already exists in the current directory.`});else{if(n.isErr()){g({message:n.unwrapErr().message}),Gi.exitCode=5;return}if(!e){let l=n.isOkAnd(d=>d.exists)?n.unwrap().config.name:null;for(;!l;)try{let d=await at({message:"Actor name:",default:i});er(d),l=d}catch(d){g({message:d.message})}e=l}let c={...{...Ir,...n.unwrap().config},name:e};this.flags.dockerfile&&(c.dockerfile=this.flags.dockerfile),await Dr(c,t)}await Fr(t),await go(t),R({message:"The Actor has been initialized in the current directory."})}};var ns=class extends h{static name="init-wrap-scrapy";static description=`Wraps your existing Scrapy project to work like an Apify Actor.
|
|
221
|
-
|
|
222
|
-
It adds the following features:
|
|
223
|
-
- Automatic retry of failed requests
|
|
224
|
-
- Automatic proxy rotation
|
|
225
|
-
- Automatic user agent rotation
|
|
226
|
-
...
|
|
227
|
-
`;static args={path:A.string({required:!1,description:"Optional path to your scrapy project. If not provided, the current directory is used."})};static hidden=!0;async run(){await ss({projectPath:this.args.path}),b({message:"Scrapy project wrapped successfully."})}};import kc from"chalk";var as=class extends h{static name="create";static description="Creates a new key-value store on your account.";static examples=[{description:"Create an unnamed key-value store.",command:"apify key-value-stores create"},{description:"Create a named key-value store.",command:"apify key-value-stores create my-store"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-create";static args={"key-value store name":A.string({description:"Optional name for the key-value store.",required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,t=await I();if(e&&await ae(t,e)){g({message:"Cannot create a key-value store with the same name!"});return}let o=await t.keyValueStores().getOrCreate(e);if(this.flags.json){L(o);return}R({message:`Key-value store with ID ${kc.yellow(o.id)}${e?` (called ${kc.yellow(e)})`:""} was created.`,stdout:!0})}};import Yp from"chalk";var cs=class extends h{static name="delete-value";static description="Delete a value from a key-value store.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting the record. Cannot be bypassed; deletion is irreversible.";static examples=[{description:"Delete a single record by key.",command:"apify key-value-stores delete-value <storeId> OUTPUT"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-delete-value";static args={"store id":A.string({description:"The key-value store ID to delete the value from.",required:!0}),itemKey:A.string({description:"The key of the item in the key-value store.",required:!0})};static flags={...ie()};async run(){let{storeId:e,itemKey:t}=this.args,{yes:o}=this.flags,s=await I(),i=await ae(s,e);if(!i){g({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:n}=i;if(!await n.getRecord(t)){g({message:`Item with key "${t}" not found in the key-value store.`});return}if(!await Z({message:"Are you sure you want to delete this record?",providedConfirmFromStdin:o||void 0})){b({message:"Key-value store record deletion aborted.",stdout:!0});return}try{await n.deleteRecord(t),b({message:`Record with key "${Yp.yellow(t)}" deleted from the key-value store.`,stdout:!0})}catch(l){let d=l;g({message:`Failed to delete record with key "${t}" from the key-value store.
|
|
228
|
-
${d.message||d}`})}}};var ls=class extends h{static name="get-value";static description="Retrieves stored value for specified key. Use --only-content-type to check MIME type.";static examples=[{description:"Read a record value and print it to stdout.",command:"apify key-value-stores get-value <storeId> INPUT"},{description:"Print only the record content-type.",command:"apify key-value-stores get-value <storeId> INPUT --only-content-type"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-get-value";static flags={"only-content-type":w.boolean({description:"Only return the content type of the specified key.",default:!1})};static args={keyValueStoreId:A.string({description:"The key-value store ID to get the value from.",required:!0}),itemKey:A.string({description:"The key of the item in the key-value store.",required:!0})};async run(){let{onlyContentType:e}=this.flags,{keyValueStoreId:t,itemKey:o}=this.args,s=await I(),i=await ae(s,t);if(!i){g({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.getRecord(o,{stream:!0});if(!a){g({message:`Item with key "${o}" not found in the key-value store.`});return}if($({message:a.contentType??"application/octet-stream"}),e){a.value.destroy();return}if(a.contentType?.includes("application/json")){let{value:c}=a,l=[];for await(let u of c)l.push(u);let d=Buffer.concat(l).toString();try{let u=JSON.parse(d);$({message:JSON.stringify(u,null,2),stdout:!0})}catch{$({message:d,stdout:!0})}return}a.value.pipe(process.stdout)}};import V from"chalk";var Oc=new B({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),ds=class extends h{static name="info";static description="Shows information about a key-value store.";static examples=[{description:"Show metadata about a key-value store.",command:"apify key-value-stores info <storeId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-info";static args={storeId:A.string({description:"The key-value store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,t=await I(),o=await ae(t,e);if(!o){g({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStore:s}=o,[i,n,a]=await Promise.all([t.user(s.userId).get().then(F=>F),s.actId?t.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?t.run(s.actRunId).get():Promise.resolve(void 0)]),c;if(a?.actorTaskId&&(c=await t.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){L({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let l=s.stats?.storageBytes||0,d=s.stats?.readCount||0,u=s.stats?.writeCount||0,p=s.stats?.deleteCount||0,f=s.stats?.listCount||0,v=`Operations: ${[`${V.bold(d.toLocaleString("en-US"))} ${V.gray(this.pluralString(d,"read","reads"))}`,`${V.bold(u.toLocaleString("en-US"))} ${V.gray(this.pluralString(u,"write","writes"))}`,`${V.bold(p.toLocaleString("en-US"))} ${V.gray(this.pluralString(p,"delete","deletes"))}`,`${V.bold(f.toLocaleString("en-US"))} ${V.gray(this.pluralString(f,"list","lists"))}`].join(" / ")}`;if(i.plan){let F=Jo(i.plan);if(F){let re=F.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(l/1e9),Se=re*24*30,Te=Se>1?`$${Se.toFixed(2)}`:`$${re.toFixed(3)}`;v+=`
|
|
229
|
-
Storage size: ${ee({bytes:l,shortBytes:!0,precision:1})} / ${V.gray(`${Te} per month`)}`}}else v+=`
|
|
230
|
-
Storage size: ${ee({bytes:l,shortBytes:!0,precision:1})} / ${V.gray("$unknown per month")}`;let S=[`Store ID: ${V.bgGray(s.id)}`,`Name: ${s.name?V.bgGray(s.name):V.bold(V.italic("Unnamed"))}`,`Created: ${V.bold(Y.display(s.createdAt))}`,`Modified: ${V.bold(Y.display(s.modifiedAt))}`].join(`
|
|
231
|
-
`),E=V.bold("\u2014");s.actRunId&&(a?E=V.bgBlue(a.id):E=V.italic(V.gray("Run removed")));let C=V.bold("\u2014");n&&(C=V.blue(n.title||n.name));let P=V.bold("\u2014");c&&(P=V.blue(c.title||c.name));let N=[`Run: ${E}`,`Actor: ${C}`,`Task: ${P}`].join(`
|
|
232
|
-
`);Oc.pushRow({Row1:S,Row2:N});let U=Oc.render(2).split(`
|
|
233
|
-
`).map(F=>F.trim());U.shift();let J=[`${V.bold(s.name||V.italic("Unnamed"))}`,`${V.gray(s.name?`${i.username}/${s.name}`:s.id)} ${V.gray("Owned by")} ${V.blue(i.username)}`,"",U.join(`
|
|
234
|
-
`),"",v].join(`
|
|
235
|
-
`);$({message:J,stdout:!0})}};var Nc=new B({allColumns:["Key","Size"],mandatoryColumns:["Key","Size"]}),ms=class extends h{static name="keys";static description="Lists all keys in a key-value store.";static examples=[{description:"List the first 20 keys in a key-value store.",command:"apify key-value-stores keys <storeId>"},{description:"Paginate keys past an exclusive start key.",command:"apify key-value-stores keys <storeId> --exclusive-start-key last-seen-key --limit 100"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-keys";static flags={limit:w.integer({description:"The maximum number of keys to return.",default:20}),"exclusive-start-key":w.string({description:"The key to start the list from."})};static args={storeId:A.string({description:"The key-value store ID to list keys for.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,{limit:t,exclusiveStartKey:o}=this.flags,s=await I(),i=await ae(s,e);if(!i){g({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.listKeys({limit:t,exclusiveStartKey:o});if(this.flags.json){L(a);return}for(let c of a.items)Nc.pushRow({Key:c.key,Size:ee({bytes:c.size,shortBytes:!0,precision:0})});$({message:Nc.render(1),stdout:!0})}};import Lc from"chalk";var Dc=new B({allColumns:["Store ID","Name","Size","Created","Modified"],mandatoryColumns:["Store ID","Name","Size"]}),us=class extends h{static name="ls";static description="Lists all key-value stores on your account.";static examples=[{description:"List your key-value stores.",command:"apify key-value-stores ls"},{description:"List the next page of stores, sorted descending.",command:"apify key-value-stores ls --limit 50 --offset 50 --desc"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-ls";static flags={offset:w.integer({description:"Number of key-value stores that will be skipped.",default:0}),limit:w.integer({description:"Number of key-value stores that will be listed.",default:20}),desc:w.boolean({description:"Sorts key-value stores in descending order.",default:!1}),unnamed:w.boolean({description:"Lists key-value stores that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:t,limit:o,json:s,unnamed:i}=this.flags,n=await I(),a=await M(),c=await n.keyValueStores().list({desc:e,offset:t,limit:o,unnamed:i});if(s){L(c);return}if(c.count===0){b({message:"You don't have any key-value stores on your account",stdout:!0});return}for(let l of c.items){let u=Reflect.get(l,"stats").s3StorageBytes;Dc.pushRow({"Store ID":l.id,Created:Y.display(l.createdAt),Modified:Y.display(l.modifiedAt),Name:l.name?`${a.username}/${l.name}`:"",Size:typeof u=="number"?ee({bytes:u,shortBytes:!0,colorFunc:Lc.gray,precision:0}):Lc.gray("N/A")})}$({message:Dc.render(1),stdout:!0})}};import et from"chalk";var ps=class extends h{static name="rename";static description="Renames a key-value store, or removes its unique name.";static examples=[{description:"Rename a key-value store.",command:"apify key-value-stores rename old-name new-name"},{description:"Remove the name from a key-value store.",command:"apify key-value-stores rename my-store --unname"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rename";static flags={unname:w.boolean({description:"Removes the unique name of the key-value store."})};static args={keyValueStoreNameOrId:A.string({description:"The key-value store ID or name to delete.",required:!0}),newName:A.string({description:"The new name for the key-value store."})};async run(){let{unname:e}=this.flags,{newName:t,keyValueStoreNameOrId:o}=this.args;if(!t&&!e){g({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){g({message:"You cannot provide a new name and the --unname flag."});return}let s=await I(),i=await ae(s,o);if(!i){g({message:`Key-value store with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.keyValueStore,c=a?e?`The name of the key-value store with ID ${et.yellow(n)} has been removed (was ${et.yellow(a)} previously).`:`The name of the key-value store with ID ${et.yellow(n)} was changed from ${et.yellow(a)} to ${et.yellow(t)}.`:`The name of the key-value store with ID ${et.yellow(n)} has been set to: ${et.yellow(t)}`;try{await i.keyValueStoreClient.update({name:e?null:t}),R({message:c,stdout:!0})}catch(l){let d=l;g({message:`Failed to rename key-value store with ID ${et.yellow(n)}
|
|
236
|
-
${d.message||d}`})}}};import Yi from"chalk";var fs=class extends h{static name="rm";static description="Permanently removes a key-value store.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.";static examples=[{description:"Delete a key-value store (prompts for confirmation).",command:"apify key-value-stores rm my-store"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rm";static args={keyValueStoreNameOrId:A.string({description:"The key-value store ID or name to delete.",required:!0})};static flags={...ie()};async run(){let{keyValueStoreNameOrId:e}=this.args,{yes:t}=this.flags,o=await I(),s=await ae(o,e);if(!s){g({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await Z({message:"Are you sure you want to delete this Key-value store?",providedConfirmFromStdin:t||void 0})){b({message:"Key-value store deletion has been aborted."});return}let{id:n,name:a}=s.keyValueStore;try{await s.keyValueStoreClient.delete(),R({message:`Key-value store with ID ${Yi.yellow(n)}${a?` (called ${Yi.yellow(a)})`:""} has been deleted.`,stdout:!0})}catch(c){let l=c;g({message:`Failed to delete key-value store with ID ${Yi.yellow(n)}
|
|
237
|
-
${l.message||l}`})}}};var gs=class extends h{static name="set-value";static description="Stores value with specified key. Set content-type with --content-type flag.";static examples=[{description:"Store a JSON value under a key.",command:`apify key-value-stores set-value <storeId> OUTPUT '{"status":"done"}'`},{description:"Store a plain-text file read from stdin.",command:"cat ./report.txt | apify key-value-stores set-value <storeId> REPORT --content-type text/plain"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores-set-value";static flags={"content-type":w.string({description:'The MIME content type of the value. By default, "application/json" is assumed.',default:"application/json"})};static args={storeId:A.string({description:"The key-value store ID to set the value in.",required:!0}),itemKey:A.string({description:"The key of the item in the key-value store.",required:!0}),value:A.string({description:"The value to set."})};async run(){let{storeId:e,itemKey:t,value:o}=this.args,{contentType:s}=this.flags,i=await I(),n=await ae(i,e);if(!n){g({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=n;try{await a.setRecord({key:t,value:o||process.stdin,contentType:s}),R({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(c){let l=c;g({message:`Failed to set value with key "${t}" in the key-value store.
|
|
238
|
-
${l.message||l}`})}}};var hs=class extends h{static name="key-value-stores";static description=`Manage Apify key-value stores \u2014 create, list, rename, delete stores, and get/set/delete individual records.
|
|
239
|
-
|
|
240
|
-
Alias: kvs.`;static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-key-value-stores";static hiddenAliases=["kvs"];static subcommands=[as,cs,ls,ds,ms,us,ps,fs,gs];async run(){this.printHelp()}};var ys=class extends Bt{static name="login"};var ws=class extends Vt{static name="logout"};var As=class extends Ut{static name="pull"};var vs=class extends jt{static name="push"};var bs=class extends h{static name="request-queues";static description="Manage Apify request queues. No subcommands are available yet.";static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-request-queues";async run(){this.printHelp()}};import{existsSync as Uc,renameSync as Wp}from"fs";import{mkdir as Ss,readFile as zp,stat as Mc,writeFile as br}from"fs/promises";import{dirname as Ts,join as Cs}from"path";import Ve from"process";import Xp from"mime";import{minVersion as Zp}from"semver";import{APIFY_ENV_VARS as Is}from"@apify/consts";import{validateInputSchema as Qp,validateInputUsingValidator as jc}from"@apify/input_schema";import{none as vr,some as Hp}from"@sapphire/result";import{execa as Jp}from"execa";var Hi=m(r=>`
|
|
241
|
-
(async () => {
|
|
242
|
-
const [nodeModule, process, path, fs] = await Promise.all([
|
|
243
|
-
import('node:module'),
|
|
244
|
-
import('node:process'),
|
|
245
|
-
import('node:path'),
|
|
246
|
-
import('node:fs/promises'),
|
|
247
|
-
]);
|
|
248
|
-
|
|
249
|
-
/* we fake a script file here because otherwise node AND deno will fail to resolve modules, but bun works -.- */
|
|
250
|
-
const dirname = path.join(process.cwd(), '__apify_cli_fetch_module_version__.js');
|
|
251
|
-
|
|
252
|
-
const _require = nodeModule.createRequire(dirname);
|
|
253
|
-
|
|
254
|
-
try {
|
|
255
|
-
const modulePath = _require.resolve('${r}');
|
|
256
|
-
const moduleDir = path.dirname(modulePath);
|
|
257
|
-
|
|
258
|
-
const packageJson = await fs.readFile(path.join(moduleDir, 'package.json'), 'utf8').catch(() => null);
|
|
259
|
-
|
|
260
|
-
if (!packageJson) {
|
|
261
|
-
console.log('n/a');
|
|
262
|
-
return;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
const packageJsonObj = JSON.parse(packageJson);
|
|
266
|
-
console.log(packageJsonObj.version);
|
|
267
|
-
} catch {
|
|
268
|
-
console.log('n/a');
|
|
269
|
-
}
|
|
270
|
-
})();
|
|
271
|
-
`.replaceAll(`
|
|
272
|
-
`," ").replaceAll(" "," "),"jsScript"),qp=m(r=>`
|
|
273
|
-
try:
|
|
274
|
-
import ${r}
|
|
275
|
-
print(${r}.__version__)
|
|
276
|
-
except:
|
|
277
|
-
print('n/a')
|
|
278
|
-
`,"pyScript"),Kp={node(r){return["-e",`"${Hi(r)}"`]},deno(r){return["eval",`"${Hi(r)}"`]},bun(r){return["--eval",`"${Hi(r)}"`]},python(r){return["-c",`"${qp(r)}"`]}};async function Fc({moduleName:r,project:e}){if(!e.runtime)return T("useModuleVersion",{status:"no_runtime_found",project:e,moduleName:r}),vr;let t;if(e.type===0)t=e.runtime.runtimeShorthand||"node";else if(e.type===1||e.type===2)t="python";else return T("useModuleVersion",{status:"unsupported_project_type",project:e,moduleName:r}),vr;let o=Kp[t]?.(r);if(!o)return T("useModuleVersion",{status:"no_version_script_found",project:e,moduleName:r}),vr;try{let s=await Jp(e.runtime.executablePath,o,{shell:!0,windowsHide:!0,verbose:process.env.APIFY_CLI_DEBUG?"full":void 0});return s.stdout.trim()==="n/a"?(T("useModuleVersion",{status:"no_version_found",project:e,moduleName:r}),vr):(T("useModuleVersion",{status:"success",project:e,moduleName:r,version:s.stdout.trim()}),Hp(s.stdout.trim()))}catch(s){return T("useModuleVersion",{status:"failed_to_run_version_script",project:e,moduleName:r,error:s}),vr}}m(Fc,"useModuleVersion");var Es=class extends h{static name="run";static description=`Executes Actor locally with simulated Apify environment variables.
|
|
279
|
-
Stores data in local '${ot}' directory.
|
|
280
|
-
|
|
281
|
-
NOTE: For Node.js Actors, customize behavior by modifying the 'start' script in package.json file.`;static group="Local Actor Development";static examples=[{description:"Run the Actor in the current directory with the stored input.",command:"apify run"},{description:"Run and purge the default storage first (dataset, request queue, key-value store).",command:"apify run --purge"},{description:"Run with inline JSON input (overrides the stored INPUT).",command:`apify run --input '{"startUrls":[{"url":"https://example.com"}]}'`},{description:"Run with input from a file.",command:"apify run --input-file ./input.json"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-run";static flags={purge:w.boolean({char:"p",description:"Whether to purge the default request queue, dataset and key-value store before the run starts.\nFor crawlee projects, this is the default behavior, and the flag is optional.\nUse `--no-purge` to keep the storage folder intact.",required:!1,default:!0,exclusive:["resurrect"]}),resurrect:w.boolean({description:"Whether to keep the default request queue, dataset and key-value store before the run starts.",required:!1,default:!1,exclusive:["purge"]}),entrypoint:w.string({description:["Optional entrypoint for running with injected environment variables.",`
|
|
282
|
-
`,"For Python, it is the module name, or a path to a file.",`
|
|
283
|
-
`,"For Node.js, it is the npm script name, or a path to a JS/MJS file.",'You can also pass in a directory name, provided that directory contains an "index.js" file.'].join(" "),required:!1}),input:w.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":w.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]}),"allow-missing-secrets":w.boolean({description:"Allow the command to continue even when secret values are not found in the local secrets storage.",required:!1,default:!1})};async run(){let e=Ve.cwd(),{proxy:t,id:o,token:s}=await M(),i=await Le({cwd:e});if(i.isErr()){let{message:O,cause:U}=i.unwrapErr();g({message:`${O}${U?`
|
|
284
|
-
${U.message}`:""}`}),Ve.exitCode=5;return}let{config:n}=i.unwrap(),a=we(),c=await Ne({cwd:e});if(c.isErr()){g({message:c.unwrapErr().message}),Ve.exitCode=5;return}let l=c.unwrap(),{type:d,entrypoint:u,runtime:p}=l;if(l.warnings?.length)for(let O of l.warnings)x({message:O});if(d===3)throw new Error("Actor is of an unknown format. Make sure your project is supported by Apify CLI (either a package.json file is present, or a Python entrypoint could be found) or you are in a migrated Scrapy project.");if(!p){switch(d){case 0:g({message:`No Node.js detected! Please install Node.js ${Ie} (or higher) to be able to run Node.js Actors locally.`});break;case 2:case 1:g({message:`No Python detected! Please install Python ${st} (or higher) to be able to run Python Actors locally.`});break;default:g({message:`No runtime detected! Make sure you have Python ${st} (or higher) or Node.js ${Ie} (or higher) installed.`})}return}let f,y;if(this.flags.entrypoint){y=this.flags.entrypoint;let O=Cs(e,this.flags.entrypoint),U=await Mc(O).catch(()=>null);U?.isDirectory()?f=1:U?.isFile()?f=0:f=2}else if(u?.script)f=2,y=u.script;else if(u?.path)f=d!==0?1:0,y=u.path;else{g({message:"No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint."});return}Uc(Ks)&&!Uc(a)&&(Wp(Ks,a),x({message:`The legacy 'apify_storage' directory was renamed to '${a}' to align it with Apify SDK v3. Contents were left intact.`}));let v=await Fc({moduleName:"crawlee",project:l}),S="0";this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(S="1",v.isNone()&&(await Promise.all([yn(),An(),wn()]),b({message:"All default local stores were purged."}))),this.flags.purge||!await vn()&&!this.flags.resurrect&&x({message:"The storage directory contains a previous state, the Actor will continue where it left off. To start from the initial state, use --purge parameter to clean the storage directory."});let E=await Lt(e,this.flags.input,this.flags.inputFile);if(E===!1)return;let C=await this.validateAndStoreInput(E),P={[Is.LOCAL_STORAGE_DIR]:a,CRAWLEE_STORAGE_DIR:a,CRAWLEE_PURGE_ON_START:S};if(t&&t.password&&(P[Is.PROXY_PASSWORD]=t.password),o&&(P[Is.USER_ID]=o),s&&(P[Is.TOKEN]=s),n.environmentVariables){let O=Ka(n.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets});Object.assign(P,O)}let N=Object.assign(P,Ve.env);o||x({message:'You are not logged in with your Apify Account. Some features like Apify Proxy will not work. Call "apify login" to fix that.'});try{switch(d){case 0:{let O=Zp(Ie);if(jr(p.version)?N.NODE_OPTIONS=N.NODE_OPTIONS?`${N.NODE_OPTIONS} --max-http-header-size=80000`:"--max-http-header-size=80000":x({message:`You are running Node.js version ${p.version}, which is no longer supported. Please upgrade to Node.js version ${O} or later.`}),f===0||f===1)await fe({cmd:p.executablePath,args:[y],opts:{env:N,cwd:e}});else{let U=await zp(Cs(e,"package.json"),"utf8").catch(()=>"{}"),J=JSON.parse(U);if(!J.scripts)throw new Error('No scripts were found in package.json. Please set it up for your project. For more information about that call "apify help run".');if(!J.scripts[y])throw new Error(`The script "${y}" was not found in package.json. Please set it up for your project. For more information about that call "apify help run".`);if(!p.pmPath)throw new Error("No npm executable found! Please make sure your Node.js runtime has npm installed if you want to run package.json scripts locally.");await fe({cmd:p.pmPath,args:["run",y],opts:{env:N,cwd:e},overrideCommand:p.pmName})}break}case 1:case 2:{if(!Mr(p.version)){g({message:`Python Actors require Python 3.9 or higher, but you have Python ${p.version}!`}),g({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}f===1?await fe({cmd:p.executablePath,args:["-m",y],opts:{env:N,cwd:e}}):await fe({cmd:p.executablePath,args:[y],opts:{env:N,cwd:e}});break}default:g({message:"Failed to detect the language of your project. Please report this issue to the Apify team with your project structure over at https://github.com/apify/apify-cli/issues"})}}catch(O){let{stderr:U}=O}finally{if(C)if(C.existingInput){let O=await Mc(C.inputFilePath);if(Math.trunc(O.mtimeMs)-C.writtenAt>=5){x({message:`The "${C.inputFilePath}" file was overwritten during the run. The CLI will not undo the setting of missing default fields from your input schema.`});return}await br(C.inputFilePath,C.existingInput.body)}else await Ht(C.inputFilePath)}}async validateAndStoreInput(e){let{inputSchema:t}=await Ct({cwd:Ve.cwd()});if(!t){if(!e)return null;let l=Qt(Ve.cwd()),d=Cs(Ve.cwd(),he(),l?.fileName??"INPUT.json");return await Ss(Ts(d),{recursive:!0}),await br(d,JSON.stringify(e.input,null,2)),{existingInput:l,inputFilePath:d,writtenAt:Date.now()}}let o=new zt({strict:!1,unicodeRegExp:!1});Qp(o,t);let s=Ea(t),i=$a(t,o),n=Qt(Ve.cwd()),a=Cs(Ve.cwd(),he(),n?.fileName??"INPUT.json"),c;switch(e?.source){case"stdin":c=`The input provided through standard input is invalid. Please fix the following errors:
|
|
285
|
-
`;break;case"input":c=`The input provided through the --input flag is invalid. Please fix the following errors:
|
|
286
|
-
`;break;default:e?c=`The input provided through the ${e.source} file is invalid. Please fix the following errors:
|
|
287
|
-
`:c=`The input in your storage is invalid. Please fix the following errors:
|
|
288
|
-
`;break}if(e){let l={...s,...e.input},d=jc(i,t,l);if(d.length>0)throw new Error(`${c}${d.map(u=>` - ${u.message.replace("Field input.","Field ")}`).join(`
|
|
289
|
-
`)}`);return await Ss(Ts(a),{recursive:!0}),await br(a,JSON.stringify(l,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}if(!n)return await Ss(Ts(a),{recursive:!0}),await br(a,JSON.stringify(s,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()};if(Xp.getExtension(n.contentType)==="json"){let l=JSON.parse(n.body.toString("utf-8"));if(Array.isArray(l))throw new Error("The input in your storage is invalid. It should be an object, not an array.");let d={...s,...l},u=jc(i,t,d);if(u.length>0)throw new Error(`${c}${u.map(p=>` - ${p.message.replace("Field input.","Field ")}`).join(`
|
|
290
|
-
`)}`);return await Ss(Ts(a),{recursive:!0}),await br(a,JSON.stringify(d,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}return null}};import{ACTOR_JOB_STATUSES as $s}from"@apify/consts";var ef=[$s.READY,$s.RUNNING],tf=[$s.ABORTING,$s.TIMING_OUT],Rs=class extends h{static name="abort";static description="Aborts an Actor run.";static examples=[{description:"Abort a running Actor gracefully (up to 30s drain).",command:"apify runs abort <runId>"},{description:"Force-abort a running Actor immediately.",command:"apify runs abort <runId> --force"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-abort";static args={runId:A.string({required:!0,description:"The run ID to abort."})};static flags={force:w.boolean({description:"Whether to force the run to abort immediately, instead of gracefully.",default:!1,char:"f"})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){g({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!ef.includes(o.status)){tf.includes(o.status)?g({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):g({message:`Run with ID "${e}" is already aborted.`,stdout:!0});return}try{let s=await t.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){L(s);return}this.flags.force?R({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):R({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(s){let i=s;g({message:`Failed to abort run "${e}".
|
|
291
|
-
${i.message||i}`,stdout:!0})}}};import _ from"chalk";var Sr=new B({allColumns:["","Unit","USD Amount"],mandatoryColumns:["","Unit","USD Amount"],columnAlignments:{Unit:"right","USD Amount":"right"}}),Bc={"Actor compute units":"ACTOR_COMPUTE_UNITS","Dataset reads":"DATASET_READS","Dataset writes":"DATASET_WRITES","Key-value store reads":"KEY_VALUE_STORE_READS","Key-value store writes":"KEY_VALUE_STORE_WRITES","Key-value store lists":"KEY_VALUE_STORE_LISTS","Request queue reads":"REQUEST_QUEUE_READS","Request queue writes":"REQUEST_QUEUE_WRITES","Data transfer internal":"DATA_TRANSFER_INTERNAL_GBYTES","Data transfer external":"DATA_TRANSFER_EXTERNAL_GBYTES","Proxy residential data transfer":"PROXY_RESIDENTIAL_TRANSFER_GBYTES","Proxy SERPs":"PROXY_SERPS"},xs=class extends h{static name="info";static description="Prints information about an Actor run.";static examples=[{description:"Show a summary of a run.",command:"apify runs info <runId>"},{description:"Show verbose details including usage breakdown.",command:"apify runs info <runId> --verbose"},{description:"Emit the full run object as JSON.",command:"apify runs info <runId> --json"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-info";static args={runId:A.string({required:!0,description:"The run ID to print information about."})};static flags={verbose:w.boolean({char:"v",description:"Prints more in-depth information about the Actor run.",default:!1})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){g({message:`Run with ID "${e}" was not found on your account.`});return}let[s,i,n,a,c]=await Promise.all([t.actor(o.actId).get(),t.build(o.buildId).get(),o.actorTaskId?t.task(o.actorTaskId).get():Promise.resolve(void 0),t.dataset(o.defaultDatasetId).get(),t.requestQueue(o.defaultRequestQueueId).get()]);if(this.flags.json){L({...o,actor:s,build:i,task:n,defaultDataset:a,defaultRequestQueue:c});return}this.addDetailedUsage(o);let l=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",d=[`${_.yellow("Actor")}: ${l} (${_.grey(o.actId)})`];n?d.push(`\u2514\u2500 ${_.yellow("Task")}: ${n.title??n.name} (${_.gray(o.actorTaskId)})`,""):o.actorTaskId?d.push(`\u2514\u2500 ${_.yellow("Task")}: unknown-task (${_.gray(o.actorTaskId)})`,""):d.push("");let u=` (exit code: ${_.gray(o.exitCode!==null?o.exitCode:"N/A")})`;d.push(`${_.yellow("Status")}: ${Pe(o.status)}${u}`),o.statusMessage&&d.push(`\u2514\u2500 ${_.yellow("Status Message:")} ${o.statusMessage}`);let p=a?.itemCount??0;d.push(`${_.yellow("Results")}: ${_.cyan(p.toLocaleString("en-US"))}`),c?d.push(`${_.yellow("Requests")}: ${_.cyan(c.handledRequestCount.toLocaleString("en-US"))} out of ${_.cyan(c.totalRequestCount.toLocaleString("en-US"))} handled`):d.push(`${_.yellow("Requests")}: ${_.gray("unknown handled")}`);let f=this.flags.verbose?"":_.gray(` (run with ${_.yellow("--verbose")} for a detailed breakdown)`);if(o.usageTotalUsd?d.push(`${_.yellow("Usage")}: ${_.cyan(this.formatUsd(o.usageTotalUsd))}${f}`):d.push(`${_.yellow("Usage")}: $${_.gray("0.000")}${f}`),this.flags.verbose&&d.push(Sr.render(0)),d.push(""),d.push(`${_.yellow("Started")}: ${Y.display(o.startedAt)}`),o.finishedAt)d.push(`${_.yellow("Finished")}: ${Y.display(o.finishedAt)} (took ${_.gray(me.format(o.stats.durationMillis))})`);else{let E=Date.now()-o.startedAt.getTime();d.push(`${_.yellow("Finished")}: ${_.gray(`Running for ${me.format(E)}`)}`)}if(d.push(""),o.stats.resurrectCount?d.push(`${_.yellow("Resurrected")}: Yes, ${_.cyan(o.stats.resurrectCount.toLocaleString("en-US"))} ${this.pluralString(o.stats.resurrectCount,"time","times")}`):d.push(`${_.yellow("Resurrected")}: No`),o.containerUrl&&d.push(`${_.yellow("Container URL")}: ${_.blue(o.containerUrl)}`),d.push(`${_.yellow("Origin")}: ${o.meta.origin}`),s){let E=o.buildNumber.split(".").slice(0,2).join("."),C=s.versions.find(O=>O.versionNumber===E),P=Object.entries(s.taggedBuilds??{}).find(([,O])=>O.buildNumber===o.buildNumber)?.[0],N=[`${_.yellow("Build")}:`,_.cyan(o.buildNumber)];P?N.push(`(${_.yellow(P)})`):N.push(`(${_.gray("N/A")})`),C&&N.push(`| ${_.gray("Actor version:")} ${_.cyan(C.versionNumber)} (${_.yellow(C.buildTag)})`),d.push(N.join(" "))}else d.push(`${_.yellow("Build")}: ${_.cyan(o.buildNumber)}`);d.push(`${_.yellow("Timeout")}: ${o.options.timeoutSecs.toLocaleString("en-US")} seconds`),d.push(`${_.yellow("Memory")}: ${o.options.memoryMbytes} MB`),d.push(""),d.push(`${_.yellow("CPU")}: ${_.gray("Average:")} ${o.stats.cpuAvgUsage.toFixed(2)}% | ${_.gray("Maximum:")} ${o.stats.cpuMaxUsage.toFixed(2)}%`),d.push(`${_.yellow("Memory")}: ${_.gray("Average:")} ${ee({bytes:o.stats.memAvgBytes,shortBytes:!0})} | ${_.gray("Maximum:")} ${ee({bytes:o.stats.memMaxBytes,shortBytes:!0})}`),d.push("");let y=`https://console.apify.com/actors/${o.actId}/runs/${o.id}`,v=`https://console.apify.com/storage/datasets/${o.defaultDatasetId}`,S=`https://console.apify.com/storage/key-value-stores/${o.defaultKeyValueStoreId}`;d.push(`${_.blue("Export results")}: ${v}`),d.push(`${_.blue("View saved items")}: ${S}`),d.push(`${_.blue("View in Apify Console")}: ${y}`),$({message:d.join(`
|
|
292
|
-
`),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:o}=e;if(!t||!o){for(let s of Object.keys(Bc))Sr.pushRow({"":s,Unit:"N/A","USD Amount":"N/A"});return}for(let[s,i]of Object.entries(Bc)){let n=t[i]??0,a=o[i]??0;switch(i){case"ACTOR_COMPUTE_UNITS":{Sr.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":{Sr.pushRow({"":s,Unit:ee({bytes:n*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break}default:Sr.pushRow({"":s,Unit:n.toLocaleString("en-US"),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}};var _s=class extends h{static name="log";static description="Prints the log of a specific run.";static examples=[{description:"Print the log of a specific run to stdout.",command:"apify runs log <runId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-log";static args={runId:A.string({required:!0,description:"The run ID to get the log from."})};async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){g({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}b({message:`Log for run with ID "${e}":
|
|
293
|
-
`,stdout:!0});try{await ke({job:o,apifyClient:t})}catch(s){g({message:`Failed to get log for run with ID "${e}": ${s.message}`})}}};import be from"chalk";var Vc=new B({allColumns:["ID","Status","Results","Usage","Started At","Took","Build No.","Origin"],mandatoryColumns:["ID","Status","Results","Usage","Started At","Took"],columnAlignments:{Results:"right",Usage:"right",Took:"right","Build No.":"right"}}),Ps=class extends h{static name="ls";static description="Lists all runs of the Actor.";static examples=[{description:"List runs of the Actor in the current directory.",command:"apify runs ls"},{description:"List runs of a specific Actor.",command:"apify runs ls apify/hello-world"},{description:"List the 50 most recent runs in descending order.",command:"apify runs ls --limit 50 --desc"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-ls";static flags={offset:w.integer({description:"Number of runs that will be skipped.",default:0}),limit:w.integer({description:"Number of runs that will be listed.",default:10}),desc:w.boolean({description:"Sort runs in descending order.",default:!1}),compact:w.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:A.string({description:"Optional Actor ID or Name to list runs for. By default, it will use the Actor from the current directory."})};static enableJsonFlag=!0;async run(){let{desc:e,limit:t,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await I(),c=await Je({providedActorNameOrId:n,client:a});if(!c.valid){g({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let l=await a.actor(c.id).runs().list({desc:e,limit:t,offset:o});if(i){L(l);return}if(!l.items.length){$({message:"There are no recent runs found for this Actor."});return}let d=[`${be.reset("Showing")} ${be.yellow(l.items.length)} out of ${be.yellow(l.total)} runs for Actor ${be.yellow(c.userFriendlyId)} (${be.gray(c.id)})`],u=new Map(await Promise.all(l.items.map(async p=>a.dataset(p.defaultDatasetId).get().then(f=>[p.id,be.yellow(f?.itemCount??0)],()=>[p.id,be.gray("N/A")]))));for(let p of l.items){let f;if(p.finishedAt){let y=p.finishedAt.getTime()-p.startedAt.getTime();f=be.gray(`${me.format(y,void 0,{left:""})}`)}else{let y=Date.now()-p.startedAt.getTime();f=be.gray(`Running for ${me.format(y,void 0,{left:""})}`)}Vc.pushRow({ID:be.gray(p.id),Status:Pe(p.status),Results:u.get(p.id)||be.gray("N/A"),Usage:be.cyan(`$${(p.usageTotalUsd??0).toFixed(3)}`),"Started At":tr.display(p.startedAt),Took:f,"Build No.":p.buildNumber,Origin:p.meta.origin??"UNKNOWN"})}d.push(Vc.render(s?0:1)),$({message:d.join(`
|
|
294
|
-
`),stdout:!0})}};import{ACTOR_JOB_STATUSES as ks}from"@apify/consts";var rf=[ks.SUCCEEDED,ks.FAILED,ks.ABORTED,ks.TIMED_OUT],Os=class extends h{static name="resurrect";static description="Resurrects an aborted or finished Actor Run.";static examples=[{description:"Resurrect a finished or aborted run.",command:"apify runs resurrect <runId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-resurrect";static args={runId:A.string({required:!0,description:"The run ID to resurrect."})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){g({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!rf.includes(o.status)){g({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});return}try{let s=await t.run(e).resurrect();if(this.flags.json){L(s);return}R({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(s){let i=s;g({message:`Failed to resurrect run "${e}".
|
|
295
|
-
${i.message||i}`,stdout:!0})}}};import{ACTOR_JOB_STATUSES as Ns}from"@apify/consts";var of=[Ns.SUCCEEDED,Ns.FAILED,Ns.ABORTED,Ns.TIMED_OUT],Ls=class extends h{static name="rm";static description="Deletes an Actor Run.";static interactive=!0;static interactiveNote="Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.";static examples=[{description:"Delete a finished or aborted run (prompts for confirmation).",command:"apify runs rm <runId>"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs-rm";static args={runId:A.string({description:"The run ID to delete.",required:!0})};static flags={...ie()};async run(){let{runId:e}=this.args,{yes:t}=this.flags,o=await I(),s=await o.run(e).get();if(!s){g({message:`Run with ID "${e}" was not found on your account.`});return}if(!of.includes(s.status)){g({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await Z({message:"Are you sure you want to delete this Actor Run?",providedConfirmFromStdin:t||void 0})){b({message:`Deletion of run "${e}" was canceled.`});return}try{await o.run(e).delete(),R({message:`Run with ID "${e}" was deleted.`})}catch(n){let a=n;g({message:`Failed to delete run "${e}".
|
|
296
|
-
${a.message||a}`})}}};var Ds=class extends h{static name="runs";static description=`Inspect, abort, resurrect, or delete existing Actor runs.
|
|
297
|
-
Does not start new runs \u2014 use 'apify call' (synchronous) or 'apify actors start' (asynchronous) for that.`;static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-runs";static subcommands=[Rs,xs,_s,Ps,Os,Ls];async run(){this.printHelp()}};var Fs=class extends h{static name="add";static description="Adds a new secret to '~/.apify' for use in Actor environment variables.";static examples=[{description:'Add a secret named "mySecret". Reference it in .actor/actor.json as "@mySecret".',command:"apify secrets add mySecret TopSecretValue123"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-secrets-add";static args={name:A.string({required:!0,description:"Name of the secret."}),value:A.string({required:!0,description:"Value of the secret."})};async run(){let{name:e,value:t}=this.args;Ha(e,t)}};import sf from"chalk";var Gc=new B({allColumns:["Secret Name"],mandatoryColumns:["Secret Name"],columnAlignments:{"Secret Name":"left"}}),Us=class extends h{static name="ls";static description="Lists all secret keys stored in your local configuration.";static examples=[{description:"List the names of all locally stored secrets.",command:"apify secrets ls"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-secrets-ls";static enableJsonFlag=!0;async run(){let{json:e}=this.flags,t=Mt(),o=Object.keys(t);if(e){L({keys:o});return}if(o.length===0){b({message:"You don't have any secrets stored locally. Use 'apify secrets add' to add a secret.",stdout:!0});return}for(let s of o)Gc.pushRow({"Secret Name":sf.cyan(s)});$({message:Gc.render(1),stdout:!0})}};var Ms=class extends h{static name="rm";static description="Permanently deletes a secret from your stored credentials.";static examples=[{description:"Delete a locally stored secret by name.",command:"apify secrets rm mySecret"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-secrets-rm";static args={name:A.string({required:!0,description:"Name of the secret."})};async run(){let{name:e}=this.args;Ja(e)}};var js=class extends h{static name="secrets";static description=`Manage locally stored secrets that can be referenced from '${D}' environment variables using the "@" prefix (e.g. "@mySecret"). Secrets are uploaded alongside the Actor and stored encrypted on the Apify platform.`;static group="Authentication";static examples=[{description:'Store a secret called "mySecret".',command:"apify secrets add mySecret TopSecretValue123"},{description:'Reference the secret from .actor/actor.json using the "@" prefix, e.g. "environmentVariables": { "SECRET_ENV_VAR": "@mySecret" }, then push as usual.',command:"apify push"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-secrets";static subcommands=[Fs,Us,Ms];async run(){this.printHelp()}};import Yc from"chalk";var Bs=class extends h{static name="run";static description=`Executes predefined Actor task remotely using local key-value store for input.
|
|
298
|
-
Customize with --memory and --timeout flags.
|
|
299
|
-
`;static examples=[{description:"Run a task by name.",command:"apify task run my-task"},{description:"Run a task by full ID with custom memory and timeout.",command:"apify task run username/my-task --memory 4096 --timeout 600"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-task-run";static flags=Ft("Task");static args={taskId:A.string({required:!0,description:'Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").'})};async run(){let e=await I(),t=await M(),o=t.username||t.id,{id:s,userFriendlyId:i,title:n}=await this.resolveTaskId(e,o),a={waitForFinish:2};this.flags.build&&(a.build=this.flags.build),this.flags.timeout&&(a.timeout=this.flags.timeout),this.flags.memory&&(a.memory=this.flags.memory);let c,l,d=Dt(e,{actorOrTaskData:{id:s,userFriendlyId:i,title:n},runOptions:a,type:"Task",printRunLogs:!0});for await(let u of d)c=`https://console.apify.com/actors/${u.actId}/runs/${u.id}`,l=`https://console.apify.com/storage/datasets/${u.defaultDatasetId}`;$({message:["",`${Yc.blue("Export results")}: ${l}`,`${Yc.blue("View on Apify Console")}: ${c}`].join(`
|
|
300
|
-
`),stdout:!0})}async resolveTaskId(e,t){let{taskId:o}=this.args;if(o?.includes("/")){let s=await e.task(o).get();if(!s)throw new Error(`Cannot find Task with ID '${o}' in your account.`);return{id:s.id,userFriendlyId:`${t}/${s.name}`,title:s.title,task:s}}if(o){let s=await e.task(`${t}/${o.toLowerCase()}`).get();if(!s)throw new Error(`Cannot find Task with name '${o}' in your account.`);return{id:s.id,userFriendlyId:`${t}/${s.name}`,title:s.title,task:s}}throw new Error("Please provide a valid Task ID or name.")}};var Vs=class extends h{static name="task";static description="Run saved Apify tasks (named Actor configurations). Only 'task run' is available; create and manage tasks in Apify Console.";static group="Apify Console";static docsUrl="https://docs.apify.com/cli/docs/reference#apify-task";static subcommands=[Bs];async run(){this.printHelp()}};var Gs=class extends h{static name="disable";static description="Disables telemetry.";static examples=[{description:"Opt out of anonymous telemetry.",command:"apify telemetry disable"}];static docsUrl="https://docs.apify.com/cli/docs/telemetry";async run(){(await ue()).enabled?(await Yr(!1),R({message:"Telemetry disabled."})):b({message:"Telemetry is already disabled."})}};var Ys=class extends h{static name="enable";static description="Enables telemetry.";static examples=[{description:"Opt in to anonymous telemetry.",command:"apify telemetry enable"}];static docsUrl="https://docs.apify.com/cli/docs/telemetry";async run(){(await ue()).enabled?b({message:"Telemetry is already enabled."}):(await Yr(!0),R({message:"Telemetry enabled."}))}};var Tr=class extends h{static name="telemetry";static description="Enable or disable anonymous telemetry. We use this data to improve the CLI and the Apify platform.";static group="Utilities";static docsUrl="https://docs.apify.com/cli/docs/telemetry";static subcommands=[Ys,Gs];async run(){this.printHelp()}};import nf from"process";var Hs=class extends h{static name="validate-schema";static description=`Validates Actor input schema from one of these locations (in priority order):
|
|
301
|
-
1. Object in '${D}' under "input" key
|
|
302
|
-
2. JSON file path in '${D}' "input" key
|
|
303
|
-
3. .actor/INPUT_SCHEMA.json
|
|
304
|
-
4. INPUT_SCHEMA.json
|
|
305
|
-
|
|
306
|
-
Optionally specify custom schema path to validate.`;static group="Local Actor Development";static examples=[{description:"Validate the input schema discovered from the default locations.",command:"apify validate-schema"},{description:"Validate a specific INPUT_SCHEMA.json file.",command:"apify validate-schema ./my-schema.json"}];static docsUrl="https://docs.apify.com/cli/docs/reference#apify-validate-schema";static args={path:A.string({required:!1,description:"Optional path to your INPUT_SCHEMA.json file. If not provided ./INPUT_SCHEMA.json is used."})};static hiddenAliases=["vis"];async run(){await po({forcePath:this.args.path,cwd:nf.cwd(),getMessage:m(e=>e?`Validating input schema at ${e}`:`Validating input schema embedded in '${D}'`,"getMessage")}),R({message:"Input schema is valid."})}};var lN=[wo,xo,ko,jo,Qo,hs,bs,Ds,js,Vs,Tr,_o,Bo,wr,yr,Go,es,rs,ns,is,ys,ws,As,vs,Es,Hs,Ar],dN=[Ot,kt,Pt,_t,xt,Tt,St,Rt,Ar,wr,yr,Tr];export{xw as a,_w as b,lN as c,dN as d};
|
|
307
|
-
//# sourceMappingURL=chunk-XLY3B6IF.js.map
|