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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,40 +1,40 @@
1
- import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import{inspect as a,parseArgs as s,promisify as c}from"node:util";import{gt as l,gte as u,minVersion as f,satisfies as p}from"semver";import{appendFileSync as m,constants as h,copyFileSync as g,createWriteStream as _,existsSync as v,fstat as y,mkdirSync as b,openSync as x,readFileSync as S,readdirSync as C,realpathSync as w,renameSync as T,rmSync as ee,statSync as te,unlinkSync as ne,writeFileSync as E}from"node:fs";import D,{basename as re,dirname as O,isAbsolute as ie,join as k,relative as ae,resolve as A,sep as oe}from"node:path";import se from"string-width";import ce from"strip-ansi";import{once as le}from"node:events";import{homedir as ue,platform as de}from"node:os";import{ACTOR_ENV_VARS as j,ACTOR_JOB_STATUSES as M,ACTOR_JOB_TERMINAL_STATUSES as fe,ACTOR_NAME as pe,ACTOR_SOURCE_TYPES as me,APIFY_ENV_VARS as N,KEY_VALUE_STORE_KEYS as he,LOCAL_ACTOR_ENV_VARS as ge,LOCAL_STORAGE_SUBDIRS as _e,MAX_MULTIFILE_BYTES as ve,META_ORIGINS as ye,SOURCE_FILE_FORMATS as be}from"@apify/consts";import{jaroWinkler as xe}from"@skyra/jaro-winkler";import Se from"js-levenshtein";import Ce from"ci-info";import{createHmacSignature as we,cryptoRandomObjectId as Te}from"@apify/utilities";import{execSync as Ee,spawn as De}from"node:child_process";import{access as Oe,lstat as ke,mkdir as P,readFile as F,readdir as I,rename as Ae,stat as L,symlink as je,unlink as Me,writeFile as R}from"node:fs/promises";import{get as Ne}from"node:https";import{finished as Pe,pipeline as Fe}from"node:stream/promises";import{DurationFormatter as Ie,Time as Le,TimeTypes as Re}from"@sapphire/duration";import{Timestamp as ze}from"@sapphire/timestamp";import Be from"adm-zip";import Ve from"ajv/dist/2019.js";import{ApifyClient as He,DownloadItemsFormat as z}from"apify-client";import Ue from"archiver";import We,{AxiosHeaders as Ge}from"axios";import Ke from"escape-string-regexp";import qe from"ignore";import{getEncoding as Je}from"istextorbinary";import Ye,{Mime as Xe}from"mime";import Ze from"mime/types/other.js";import Qe from"mime/types/standard.js";import{glob as $e}from"tinyglobby";import{rimraf as et}from"rimraf";import{Result as tt,err as nt,none as B,ok as rt,some as it}from"@sapphire/result";import at from"configparser";import ot from"@inquirer/input";import st from"is-ci";import{execa as ct}from"execa";import lt from"which";import{calculateRunDynamicMemory as ut}from"@apify/actor-memory-expression";import{Separator as dt,createPrompt as ft,isEnterKey as pt,makeTheme as mt,useKeypress as ht,usePrefix as gt,useState as _t}from"@inquirer/core";import{MemoryStorage as vt}from"@crawlee/memory-storage";import{compile as yt}from"json-schema-to-typescript";import{cloneDeep as V}from"es-toolkit";import{validateInputSchema as bt,validateInputUsingValidator as xt}from"@apify/input_schema";import{getDatasetSchemaValidator as St,getKeyValueStoreSchemaValidator as Ct,getOutputSchemaValidator as wt}from"@apify/json_schemas";import Tt from"cli-table3";import Et from"jju";import Dt from"tiged";import Ot from"open";import{fetchManifest as kt,manifestUrl as At,wrapperManifestUrl as jt}from"@apify/actor-templates";import Mt from"computer-name";import Nt from"cors";import Pt from"express";import Ft from"@inquirer/password";import It from"@inquirer/select";import Lt from"node:assert";import{ReadStream as Rt}from"node:tty";import zt from"detect-indent";import{fileURLToPath as Bt}from"node:url";import Vt from"@root/walk";import Ht from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function link(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.blue(e.message),e.url]})}function detectInstallMethod(){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 e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=w(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){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}}let Ut=null;function useCLIMetadata(){if(Ut)return Ut;let e=detectInstallMethod(),t=getRuntimeInfo();return Ut={version:`1.5.1-beta.2`,hash:`25c2728196d0ed44199228e2049d9333f1985d13`,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform===`win32`?`windows`:process.platform,runtime:t,extraRuntimeData:t.nodeVersion?`(emulating node ${t.nodeVersion})`:``,installMethod:e,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${t.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:``}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes(`beta`)||this.version===`0.0.0`}},e===`bundle`&&(Ut.installPath=O(process.execPath)),Ut}let Wt;function getMaxLineWidth(){if(Wt)return Wt;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Wt=e;else if(!process.stdout.isTTY)Wt=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Wt=e<1?80:e<40?40:e}return Wt}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=this.command.interactive?`${t.yellow(`[INTERACTIVE]`)} `:``;this.command.shortDescription?e.push(`${n}${this.command.shortDescription}`,``):this.command.description&&e.push(`${n}${this.command.description.split(`
1
+ import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import{inspect as a,parseArgs as s,promisify as c}from"node:util";import{gt as l,gte as u,minVersion as f,satisfies as p}from"semver";import{appendFileSync as m,constants as h,copyFileSync as g,createWriteStream as _,existsSync as v,fstat as y,mkdirSync as b,openSync as x,readFileSync as S,readdirSync as C,realpathSync as ee,renameSync as w,rmSync as T,statSync as E,unlinkSync as te,writeFileSync as D}from"node:fs";import O,{basename as ne,dirname as k,isAbsolute as re,join as A,relative as ie,resolve as j,sep as ae}from"node:path";import oe from"string-width";import se from"strip-ansi";import{once as ce}from"node:events";import{homedir as le,platform as ue}from"node:os";import{ACTOR_ENV_VARS as M,ACTOR_JOB_STATUSES as N,ACTOR_JOB_TERMINAL_STATUSES as de,ACTOR_NAME as fe,ACTOR_SOURCE_TYPES as pe,APIFY_ENV_VARS as P,KEY_VALUE_STORE_KEYS as me,LOCAL_ACTOR_ENV_VARS as he,LOCAL_STORAGE_SUBDIRS as ge,MAX_MULTIFILE_BYTES as _e,META_ORIGINS as ve,SOURCE_FILE_FORMATS as ye}from"@apify/consts";import{jaroWinkler as be}from"@skyra/jaro-winkler";import xe from"js-levenshtein";import Se from"ci-info";import{createHmacSignature as Ce,cryptoRandomObjectId as we}from"@apify/utilities";import{execSync as Te,spawn as Ee}from"node:child_process";import{access as De,lstat as Oe,mkdir as F,readFile as I,readdir as L,rename as ke,stat as R,symlink as Ae,unlink as je,writeFile as z}from"node:fs/promises";import{get as Me}from"node:https";import{finished as Ne,pipeline as Pe}from"node:stream/promises";import{DurationFormatter as Fe,Time as Ie,TimeTypes as B}from"@sapphire/duration";import{Timestamp as Le}from"@sapphire/timestamp";import Re from"adm-zip";import ze from"ajv/dist/2019.js";import{ApifyClient as Be,DownloadItemsFormat as V}from"apify-client";import Ve from"archiver";import He,{AxiosHeaders as Ue}from"axios";import We from"escape-string-regexp";import Ge from"ignore";import{getEncoding as Ke}from"istextorbinary";import qe,{Mime as Je}from"mime";import Ye from"mime/types/other.js";import Xe from"mime/types/standard.js";import{glob as Ze}from"tinyglobby";import{rimraf as Qe}from"rimraf";import{Result as $e,err as et,none as H,ok as tt,some as nt}from"@sapphire/result";import rt from"configparser";import it from"@inquirer/input";import at from"is-ci";import{execa as ot}from"execa";import st from"which";import{calculateRunDynamicMemory as ct}from"@apify/actor-memory-expression";import{Separator as lt,createPrompt as ut,isEnterKey as dt,makeTheme as ft,useKeypress as pt,usePrefix as mt,useState as ht}from"@inquirer/core";import{MemoryStorage as gt}from"@crawlee/memory-storage";import{compile as _t}from"json-schema-to-typescript";import{cloneDeep as vt}from"es-toolkit";import{validateInputSchema as yt,validateInputUsingValidator as bt}from"@apify/input_schema";import{getDatasetSchemaValidator as xt,getKeyValueStoreSchemaValidator as St,getOutputSchemaValidator as Ct}from"@apify/json_schemas";import wt from"cli-table3";import Tt from"jju";import Et from"tiged";import Dt from"open";import{fetchManifest as Ot,manifestUrl as kt,wrapperManifestUrl as At}from"@apify/actor-templates";import jt from"computer-name";import Mt from"cors";import Nt from"express";import Pt from"@inquirer/password";import Ft from"@inquirer/select";import It from"node:assert";import{ReadStream as Lt}from"node:tty";import Rt from"detect-indent";import{fileURLToPath as zt}from"node:url";import Bt from"@root/walk";import Vt from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function link(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.blue(e.message),e.url]})}function detectInstallMethod(){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 e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=ee(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){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}}let Ht=null;function useCLIMetadata(){if(Ht)return Ht;let e=detectInstallMethod(),t=getRuntimeInfo();return Ht={version:`1.5.1-beta.4`,hash:`66abc660e17ed867eeb73bce91e33e054a6bbb42`,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform===`win32`?`windows`:process.platform,runtime:t,extraRuntimeData:t.nodeVersion?`(emulating node ${t.nodeVersion})`:``,installMethod:e,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${t.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:``}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes(`beta`)||this.version===`0.0.0`}},e===`bundle`&&(Ht.installPath=k(process.execPath)),Ht}let Ut;function getMaxLineWidth(){if(Ut)return Ut;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Ut=e;else if(!process.stdout.isTTY)Ut=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Ut=e<1?80:e<40?40:e}return Ut}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=this.command.interactive?`${t.yellow(`[INTERACTIVE]`)} `:``;this.command.shortDescription?e.push(`${n}${this.command.shortDescription}`,``):this.command.description&&e.push(`${n}${this.command.description.split(`
2
2
  `)[0]}`,``)}pushDescription(e){if(!this.command.description)return;e.push(t.bold(`DESCRIPTION`));let r=n(i(this.command.description,getMaxLineWidth()-2,{trim:!1}),2);e.push(r),e.push(``)}pushExamples(e){let{examples:r}=this.command;if(r?.length){e.push(t.bold(`EXAMPLES`));for(let a of r){if(a.description){let r=n(i(a.description,getMaxLineWidth()-4,{trim:!1}).split(`
3
3
  `).map(e=>`# ${e}`).join(`
4
- `),2);e.push(t.dim(r))}e.push(` $ ${this.normalizeExampleCommand(a.command)}`),e.push(``)}}}normalizeExampleCommand(e){let t=this.entrypoint.split(` `);if(t.length<2)return e;let n=t[t.length-1],r=`${t.slice(0,-1).join(` `)} `,i=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=e;return a.startsWith(`${n} `)&&(a=`${r}${a}`),a=a.replace(RegExp(`\\|\\s+${i}\\s`,`g`),`| ${r}${n} `),a}pushInteractiveNote(e){if(!this.command.interactive)return;e.push(t.bold(`NOTE`));let r=n(i(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.`,getMaxLineWidth()-2,{trim:!1}),2);e.push(r),e.push(``)}pushLearnMore(e){this.command.docsUrl&&(e.push(t.bold(`LEARN MORE`)),e.push(` ${this.command.docsUrl}`),e.push(``))}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:n}){se(e.join(` `).split(`
5
- `).at(-1)||``)+n+se(t)>getMaxLineWidth()&&e.push(`
4
+ `),2);e.push(t.dim(r))}e.push(` $ ${this.normalizeExampleCommand(a.command)}`),e.push(``)}}}normalizeExampleCommand(e){let t=this.entrypoint.split(` `);if(t.length<2)return e;let n=t[t.length-1],r=`${t.slice(0,-1).join(` `)} `,i=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=e;return a.startsWith(`${n} `)&&(a=`${r}${a}`),a=a.replace(RegExp(`\\|\\s+${i}\\s`,`g`),`| ${r}${n} `),a}pushInteractiveNote(e){if(!this.command.interactive)return;e.push(t.bold(`NOTE`));let r=n(i(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.`,getMaxLineWidth()-2,{trim:!1}),2);e.push(r),e.push(``)}pushLearnMore(e){this.command.docsUrl&&(e.push(t.bold(`LEARN MORE`)),e.push(` ${this.command.docsUrl}`),e.push(``))}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:n}){oe(e.join(` `).split(`
5
+ `).at(-1)||``)+n+oe(t)>getMaxLineWidth()&&e.push(`
6
6
  `),e.push(t)}kebabFlagName(e){return kebabCaseString(camelCaseToKebabCase(e)).toLowerCase()}makeFlagString(e,t){let n=this.kebabFlagName(e),r=t.char?`-${t.char}`:`--${n}`;switch(t.flagTag){case`boolean`:return r;case`string`:case`integer`:return`${r} ${t.choices?.length?`${t.choices.join(`|`)}`:`<value>`}`;default:throw RangeError(`Unhandled flag type: ${t.flagTag}`)}}},CommandHelp=class extends BaseCommandRenderer{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(`
7
7
  `).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(`
8
- `).trim()}pushUsageString(e){e.push(t.bold(`USAGE`));let r=`$ ${this.entrypoint} ${this.command.name}`,a=2+se(r),s=[r],c=Object.entries(this.command.args??{});if(c.length)for(let[e,t]of c){if(typeof t==`string`)throw RangeError(`This is a type-check only value, do not actually use it`);this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:t.required?`<${e}>`:`[${e}]`,indentSize:a})}let l=Object.entries(this.command.flags??{}).filter(([,e])=>{if(typeof e==`string`)throw RangeError(`This is a type-check only value, do not actually use it`);return!e.hidden});this.command.enableJsonFlag&&l.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 u=new Map(l.sort((e,t)=>{if(typeof e[1]==`string`||typeof t[1]==`string`)throw RangeError(`This is a type-check only value, do not actually use it`);return e[1].required&&!t[1].required?-1:!e[1].required&&t[1].required?1:e[0].localeCompare(t[0])})),f=new Set;if(l.length)for(let[e,t]of u){if(typeof t==`string`)throw RangeError(`This is a type-check only value, do not actually use it`);if(f.has(e))continue;let n=t.required,r=[this.makeFlagString(e,t)];if(t.exclusive?.length)for(let e of t.exclusive){f.add(e);let t=u.get(e),i=this.makeFlagString(e,t);r.push(i),t.required&&(n=!0)}this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:n?r.join(` | `):`[${r.join(` | `)}]`,indentSize:a})}let p=n(i(s.join(` `),getMaxLineWidth()-a),a+1).trim();e.push(` ${p}`,``),c.length&&this.pushArguments(e,c),l.length&&this.pushFlags(e,u)}pushArguments(e,a){if(!a.length)return;e.push(t.bold(`ARGUMENTS`));let s=r(a.map(([e])=>e).join(`
9
- `));for(let[t,r]of a){let a=n(i(`${t.padEnd(s)} ${r.description}`,getMaxLineWidth()-s-2),s+2+2).trim();e.push(` ${a}`)}e.push(``)}pushFlags(e,a){if(!a.size)return;e.push(t.bold(`FLAGS`));let s=new Map;for(let[e,n]of a){let r=[];switch(n.char?r.push(`-${n.char},`):r.push(` `.repeat(3)),n.flagTag){case`boolean`:r.push(`--${this.kebabFlagName(e)}`);break;case`string`:case`integer`:{let i=n.choices?`<option>`:`<value>`;r.push(`--${this.kebabFlagName(e)}=${t.underline(i)}`);break}default:throw Error(`Unhandled flag tag: ${n.flagTag}`)}s.set(r.join(` `),n)}let c=r([...s.keys()].map(ce).join(`
10
- `));for(let[t,r]of s){let a=c-ce(t).length,s=`${t}${` `.repeat(a)} ${r.description??``}`;r.choices?.length&&(s+=`\n<options: ${r.choices.join(`|`)}>`);let l=n(i(s,getMaxLineWidth()-c),c).trim().split(`
8
+ `).trim()}pushUsageString(e){e.push(t.bold(`USAGE`));let r=`$ ${this.entrypoint} ${this.command.name}`,a=2+oe(r),s=[r],c=Object.entries(this.command.args??{});if(c.length)for(let[e,t]of c){if(typeof t==`string`)throw RangeError(`This is a type-check only value, do not actually use it`);this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:t.required?`<${e}>`:`[${e}]`,indentSize:a})}let l=Object.entries(this.command.flags??{}).filter(([,e])=>{if(typeof e==`string`)throw RangeError(`This is a type-check only value, do not actually use it`);return!e.hidden});this.command.enableJsonFlag&&l.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 u=new Map(l.sort((e,t)=>{if(typeof e[1]==`string`||typeof t[1]==`string`)throw RangeError(`This is a type-check only value, do not actually use it`);return e[1].required&&!t[1].required?-1:!e[1].required&&t[1].required?1:e[0].localeCompare(t[0])})),f=new Set;if(l.length)for(let[e,t]of u){if(typeof t==`string`)throw RangeError(`This is a type-check only value, do not actually use it`);if(f.has(e))continue;let n=t.required,r=[this.makeFlagString(e,t)];if(t.exclusive?.length)for(let e of t.exclusive){f.add(e);let t=u.get(e),i=this.makeFlagString(e,t);r.push(i),t.required&&(n=!0)}this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:n?r.join(` | `):`[${r.join(` | `)}]`,indentSize:a})}let p=n(i(s.join(` `),getMaxLineWidth()-a),a+1).trim();e.push(` ${p}`,``),c.length&&this.pushArguments(e,c),l.length&&this.pushFlags(e,u)}pushArguments(e,a){if(!a.length)return;e.push(t.bold(`ARGUMENTS`));let s=r(a.map(([e])=>e).join(`
9
+ `));for(let[t,r]of a){let a=n(i(`${t.padEnd(s)} ${r.description}`,getMaxLineWidth()-s-2),s+2+2).trim();e.push(` ${a}`)}e.push(``)}pushFlags(e,a){if(!a.size)return;e.push(t.bold(`FLAGS`));let s=new Map;for(let[e,n]of a){let r=[];switch(n.char?r.push(`-${n.char},`):r.push(` `.repeat(3)),n.flagTag){case`boolean`:r.push(`--${this.kebabFlagName(e)}`);break;case`string`:case`integer`:{let i=n.choices?`<option>`:`<value>`;r.push(`--${this.kebabFlagName(e)}=${t.underline(i)}`);break}default:throw Error(`Unhandled flag tag: ${n.flagTag}`)}s.set(r.join(` `),n)}let c=r([...s.keys()].map(se).join(`
10
+ `));for(let[t,r]of s){let a=c-se(t).length,s=`${t}${` `.repeat(a)} ${r.description??``}`;r.choices?.length&&(s+=`\n<options: ${r.choices.join(`|`)}>`);let l=n(i(s,getMaxLineWidth()-c),c).trim().split(`
11
11
  `).map(e=>/^-[a-z]/.test(e.trim())?e:` ${e}`).join(`
12
12
  `);e.push(` ${l}`)}e.push(``)}},CommandWithSubcommandsHelp=class extends BaseCommandRenderer{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(`
13
13
  `).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(`
14
14
  `).trim()}pushSubcommands(e){if(!this.command.subcommands?.length)return;e.push(t.bold(`SUBCOMMANDS`));let a=r(this.command.subcommands.map(e=>`${this.command.name} ${e.name}`).join(`
15
15
  `));for(let t of this.command.subcommands){let r=t.shortDescription||t.description?.split(`
16
- `)[0]||``,s=n(i(`${this.command.name} ${t.name.padEnd(a-this.command.name.length-1)} ${r}`,getMaxLineWidth()-a-2),a+2+2).trim();e.push(` ${s}`)}e.push(``)}};const Gt=new Map;function registerCommandForHelpGeneration(e,t){if(t.name.toLowerCase()!==t.name){error({message:`Command name "${t.name}" is not correctly set up internally. Make sure you fill out the "name" field in the command class extension.`});return}if(t.subcommands?.length){Gt.set(t,new CommandWithSubcommandsHelp(e,t));for(let n of t.subcommands)registerCommandForHelpGeneration(`${e} ${t.name}`,n)}else Gt.set(t,new CommandHelp(e,t))}function renderHelpForCommand(e){let t=Gt.get(e);if(!t)throw Error(`No help renderer found for command ${e.name}`);return t.render()}function selectiveRenderHelpForCommand(e,t){let n=Gt.get(e);if(!n)throw Error(`No help renderer found for command ${e.name}`);return n.selectiveRender(t)}function sortByName(e,t){return e[0].name.localeCompare(t[0].name)}const Kt=[`Local Actor Development`,`Apify Console`,`Authentication`,`Utilities`],qt=`Other`,Jt=[{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"`}],Yt=[{command:`actor get-input`},{command:`actor push-data '{"url":"https://example.com"}'`},{command:`actor set-value OUTPUT '{"done":true}'`}];function renderMainHelpMenu(e){let a=useCLIMetadata(),s=[];e===`actor`?s.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>'.`,``):s.push(`Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.`,``),s.push(t.bold(`VERSION`)),s.push(` ${a.fullVersionString}`),s.push(``),s.push(t.bold(`USAGE`)),s.push(` $ ${e} <command> [options]`),s.push(``);let c=[];for(let[e,t]of Gt)t.entrypoint.includes(` `)||e.hidden||c.push([e,t]);let l=new Map;for(let e of c){let[t]=e,n=t.group||qt;l.has(n)||l.set(n,[]),l.get(n).push(e)}for(let e of l.values())e.sort(sortByName);let u=[];for(let e of Kt)l.has(e)&&u.push(e);let f=[...l.keys()].filter(e=>!Kt.includes(e)&&e!==qt).sort();u.push(...f),l.has(qt)&&u.push(qt);let p=r(c.map(([e])=>e.name).join(`
16
+ `)[0]||``,s=n(i(`${this.command.name} ${t.name.padEnd(a-this.command.name.length-1)} ${r}`,getMaxLineWidth()-a-2),a+2+2).trim();e.push(` ${s}`)}e.push(``)}};const Wt=new Map;function registerCommandForHelpGeneration(e,t){if(t.name.toLowerCase()!==t.name){error({message:`Command name "${t.name}" is not correctly set up internally. Make sure you fill out the "name" field in the command class extension.`});return}if(t.subcommands?.length){Wt.set(t,new CommandWithSubcommandsHelp(e,t));for(let n of t.subcommands)registerCommandForHelpGeneration(`${e} ${t.name}`,n)}else Wt.set(t,new CommandHelp(e,t))}function renderHelpForCommand(e){let t=Wt.get(e);if(!t)throw Error(`No help renderer found for command ${e.name}`);return t.render()}function selectiveRenderHelpForCommand(e,t){let n=Wt.get(e);if(!n)throw Error(`No help renderer found for command ${e.name}`);return n.selectiveRender(t)}function sortByName(e,t){return e[0].name.localeCompare(t[0].name)}const Gt=[`Local Actor Development`,`Apify Console`,`Authentication`,`Utilities`],Kt=`Other`,qt=[{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"`}],Jt=[{command:`actor get-input`},{command:`actor push-data '{"url":"https://example.com"}'`},{command:`actor set-value OUTPUT '{"done":true}'`}];function renderMainHelpMenu(e){let a=useCLIMetadata(),s=[];e===`actor`?s.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>'.`,``):s.push(`Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.`,``),s.push(t.bold(`VERSION`)),s.push(` ${a.fullVersionString}`),s.push(``),s.push(t.bold(`USAGE`)),s.push(` $ ${e} <command> [options]`),s.push(``);let c=[];for(let[e,t]of Wt)t.entrypoint.includes(` `)||e.hidden||c.push([e,t]);let l=new Map;for(let e of c){let[t]=e,n=t.group||Kt;l.has(n)||l.set(n,[]),l.get(n).push(e)}for(let e of l.values())e.sort(sortByName);let u=[];for(let e of Gt)l.has(e)&&u.push(e);let f=[...l.keys()].filter(e=>!Gt.includes(e)&&e!==Kt).sort();u.push(...f),l.has(Kt)&&u.push(Kt);let p=r(c.map(([e])=>e.name).join(`
17
17
  `))||1,renderEntry=([e])=>{let t=e.shortDescription||e.description?.split(`
18
- `)[0]||``;return` ${n(i(`${e.name.padEnd(p)} ${t}`,getMaxLineWidth()-p-4),p+2+2).trim()}`};for(let e of u){let n=l.get(e);n.length&&(s.push(t.bold(e.toUpperCase())),s.push(...n.map(renderEntry),``))}let m=e===`actor`?Yt:Jt;if(m.length){s.push(t.bold(`EXAMPLES`));for(let e=0;e<m.length;e++){let r=m[e];if(r.description){e>0&&s.push(``);let a=i(r.description,getMaxLineWidth()-4,{trim:!1}).split(`
18
+ `)[0]||``;return` ${n(i(`${e.name.padEnd(p)} ${t}`,getMaxLineWidth()-p-4),p+2+2).trim()}`};for(let e of u){let n=l.get(e);n.length&&(s.push(t.bold(e.toUpperCase())),s.push(...n.map(renderEntry),``))}let m=e===`actor`?Jt:qt;if(m.length){s.push(t.bold(`EXAMPLES`));for(let e=0;e<m.length;e++){let r=m[e];if(r.description){e>0&&s.push(``);let a=i(r.description,getMaxLineWidth()-4,{trim:!1}).split(`
19
19
  `).map(e=>`# ${e}`).join(`
20
20
  `);s.push(t.dim(n(a,2)))}s.push(` $ ${r.command}`),r.description&&e<m.length-1&&s.push(``)}s.push(``)}return s.push(t.bold(`LEARN MORE`),` Use '${e} <command> --help' for more information about a command.`,` Read the docs at https://docs.apify.com/cli.`,``),s.push(t.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.`),s.join(`
21
- `).trim()}let Xt=function(e){return e[e.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]=`NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE`,e[e.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]=`NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL`,e[e.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]=`NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION`,e[e.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]=`APIFY_FLAG_PROVIDED_MULTIPLE_TIMES`,e[e.APIFY_INVALID_FLAG_INTEGER_VALUE=4]=`APIFY_INVALID_FLAG_INTEGER_VALUE`,e[e.APIFY_INVALID_CHOICE=5]=`APIFY_INVALID_CHOICE`,e[e.APIFY_MISSING_FLAG=6]=`APIFY_MISSING_FLAG`,e[e.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]=`APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG`,e[e.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]=`APIFY_TOO_MANY_REQUESTERS_OF_STDIN`,e[e.APIFY_UNKNOWN_ERROR=9]=`APIFY_UNKNOWN_ERROR`,e}({});var H=class CommandError extends Error{code;command;metadata;constructor({code:e,message:t=``,metadata:n={},command:r}){super(t||String(Xt[e])),this.code=e,this.metadata=n,this.command=r}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 Error(`Encountered unparsable error message from argument parser: ${this.message}.\n\nPlease 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 Error(`Encountered unparsable error message from argument parser: ${this.message}.\n\nPlease 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 Error(`Not implemented`)}}getPrettyMessage(){switch(this.code){case 0:{let e=this.extractFlagNameFromMessage();return CommandError.buildMessageFromFlagData(e)}case 2:{let e=this.extractFlagNameFromMessage(),n=selectiveRenderHelpForCommand(this.command,{showUsageString:!0});return[t.gray(`Unknown flag provided: ${t.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`),e.unknownOptionSuggestion?t.gray(` ${e.unknownOptionSuggestion.trim()}`):null,``,n].filter(e=>e!==null).join(`
21
+ `).trim()}let Yt=function(e){return e[e.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]=`NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE`,e[e.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]=`NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL`,e[e.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]=`NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION`,e[e.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]=`APIFY_FLAG_PROVIDED_MULTIPLE_TIMES`,e[e.APIFY_INVALID_FLAG_INTEGER_VALUE=4]=`APIFY_INVALID_FLAG_INTEGER_VALUE`,e[e.APIFY_INVALID_CHOICE=5]=`APIFY_INVALID_CHOICE`,e[e.APIFY_MISSING_FLAG=6]=`APIFY_MISSING_FLAG`,e[e.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]=`APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG`,e[e.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]=`APIFY_TOO_MANY_REQUESTERS_OF_STDIN`,e[e.APIFY_UNKNOWN_ERROR=9]=`APIFY_UNKNOWN_ERROR`,e}({});var U=class CommandError extends Error{code;command;metadata;constructor({code:e,message:t=``,metadata:n={},command:r}){super(t||String(Yt[e])),this.code=e,this.metadata=n,this.command=r}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 Error(`Encountered unparsable error message from argument parser: ${this.message}.\n\nPlease 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 Error(`Encountered unparsable error message from argument parser: ${this.message}.\n\nPlease 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 Error(`Not implemented`)}}getPrettyMessage(){switch(this.code){case 0:{let e=this.extractFlagNameFromMessage();return CommandError.buildMessageFromFlagData(e)}case 2:{let e=this.extractFlagNameFromMessage(),n=selectiveRenderHelpForCommand(this.command,{showUsageString:!0});return[t.gray(`Unknown flag provided: ${t.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`),e.unknownOptionSuggestion?t.gray(` ${e.unknownOptionSuggestion.trim()}`):null,``,n].filter(e=>e!==null).join(`
22
22
  `)}case 3:{let e=`--${this.metadata.flag}`;return t.gray(`Flag ${t.white.bold(e)} can only be specified once.`)}case 4:{let e=`--${this.metadata.flag}`,n=t.whiteBright(String(this.metadata.value));return t.gray(`The provided value for the '${t.white.bold(e)}' flag could not be processed as an integer. Received: ${n}.`)}case 6:{let{flag:e,matcher:n,providedButReceivedNoValue:r}=this.metadata,i=`'${t.white.bold(`--${e}`)}'`;return n&&(i=`${i} (alias used: '${t.white.bold(`--${n}`)}')`),r?t.gray(`Flag ${i} was provided, but no value was received. Did you mean to pass the value as an argument or through standard input?`):t.gray(`Flag ${i} is required, but was not provided.`)}case 7:{let{flagPairs:e}=this.metadata,n=[t.gray(`The following errors occurred:`)],r=t.red(` > `);for(let[i,a]of e)n.push(t.gray(`${r}${t.white.bold(i)} cannot also be provided when using ${t.white.bold(a)}`));return n.push(t.gray(`${r}See more help with ${t.white.bold(`--help`)}`)),n.join(`
23
- `)}case 8:{let{firstUse:e,secondUse:n}=this.metadata;return t.gray(`Flag ${t.white.bold(`--${e}`)} and ${t.white.bold(`--${n}`)} cannot both request that their value comes from standard input at the same time.`)}default:{let e=useCLIMetadata();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} (${Xt[this.code]})`,`- Error metadata: ${JSON.stringify(this.metadata)}`,``,`- Stack:\n${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? ${fn?`Yes`:`No`}`].join(`
23
+ `)}case 8:{let{firstUse:e,secondUse:n}=this.metadata;return t.gray(`Flag ${t.white.bold(`--${e}`)} and ${t.white.bold(`--${n}`)} cannot both request that their value comes from standard input at the same time.`)}default:{let e=useCLIMetadata();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} (${Yt[this.code]})`,`- Error metadata: ${JSON.stringify(this.metadata)}`,``,`- Stack:\n${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? ${dn?`Yes`:`No`}`].join(`
24
24
  `)}}}static buildMessageFromFlagData(e){let n=[`Flag ${t.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`];return e.ambiguousFlag?(n.push(`is ambiguous (meaning the provided value could be interpreted as a flag too).`),e.ambiguousMessage?n.push(`\n${e.ambiguousMessage.split(`
25
25
  `).map(e=>` ${e}`).join(`
26
- `)}`):n.push(`To solve this, provide the flag like this: --${e.name}=<value>`)):e.expectsValue?n.push(`expects a value`):n.push(`does not take an argument`),n.map(e=>t.gray(e)).join(` `)}static into(e,t){if(e instanceof CommandError)return e;if(e instanceof Error&&`code`in e){let n=e;switch(n.code){case`ERR_PARSE_ARGS_INVALID_OPTION_VALUE`:return new CommandError({code:0,message:n.message,command:t});case`ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL`:return new CommandError({code:1,message:n.message,command:t});case`ERR_PARSE_ARGS_UNKNOWN_OPTION`:return new CommandError({code:2,message:n.message,command:t});default:return new CommandError({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}}return new CommandError({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}};function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Zt=c(y);let Qt;async function useStdin(){if(Qt)return Qt;let t=e.stdin,n={isTTY:t.isTTY,hasData:!1,waitDelay:0,stream:t},r=await Zt(0).then(t=>{if(cliDebugPrint(`useStdin`,{stat:t,isRegularFile:t.isFile(),isDirectory:t.isDirectory(),isBlockDevice:t.isBlockDevice(),isCharDevice:t.isCharacterDevice(),isSymbolicLink:t.isSymbolicLink(),isFIFO:t.isFIFO(),isSocket:t.isSocket()}),e.platform===`win32`){if((t.mode&h.S_IFIFO)===h.S_IFIFO)return 100;if(t.isFile())return 50}return t.isFIFO()||t.isFile()||(t.isSocket()?50:!1)}).catch(()=>!1);return cliDebugPrint(`useStdin`,{hasData:n.hasData,waitDelay:n.waitDelay,isTTY:n.isTTY,pipedIn:r,readableEnded:t.readableEnded}),(!t.isTTY||r!==!1&&(t.isTTY!==void 0||!t.readableEnded))&&(n.hasData=!0),typeof r==`number`&&(n.waitDelay=r),Qt=n,n}async function readStdin(){let e=await useStdin(),{hasData:t,waitDelay:n,stream:r}=e;if(!t)return;let i=[],a=new AbortController,s=null;n&&(s=setTimeout(()=>{a.abort()},n).unref()),r.on(`data`,e=>{i.push(e),s&&=(clearTimeout(s),null)});try{await le(r,`end`,{signal:a.signal})}catch(e){if(e.name===`AbortError`)return}s&&clearTimeout(s),e.hasData=!1;let c=Buffer.concat(i);if(c.length)return c}var $t={node:`>=20`};const en=`storage`,tn={actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},nn=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let e=k(ue(),`.apify`);return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?k(e,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):e},AUTH_FILE_PATH=()=>k(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>k(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>k(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>k(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),rn=`.actor`,U=k(rn,`actor.json`),an=RegExp(`(^${he.INPUT}(?:\\.[^.]+)?$)`),W=$t.node,on={"X-Apify-Request-Origin":ye.CLI},sn=`3.9.0`;function migrateStateV0ToV1$1(e){if(e.version&&e.version>=1)return!1;let t=e;if(t.latestNpmVersionCheckedAt){let n=new Date(t.latestNpmVersionCheckedAt).getTime(),r=t.latestNpmVersion;cliDebugPrint(`LocalStateV0ToV1`,`Migrating state from v0 to v1`,{oldState:e,newState:{versionCheck:{lastChecked:n,lastVersion:r}}}),updateLocalState({version:1},e=>{e.versionCheck={lastChecked:n,lastVersion:r}})}return!0}const cn={version:1};function useLocalState(){let e=STATE_FILE_PATH();if(!v(e))return cn;let t=JSON.parse(S(e,`utf-8`));return migrateStateV0ToV1$1(t)?useLocalState():t}function updateLocalState(e,t){let n={...e};t(n),b(O(STATE_FILE_PATH()),{recursive:!0}),E(STATE_FILE_PATH(),JSON.stringify(n,null,` `))}const ln=useCLIMetadata(),un=`Apify CLI/${ln.version} (https://github.com/apify/apify-cli)`,dn=[`https://1.1.1.1`,`https://8.8.8.8`];async function isOnline(e=500){let t=new AbortController,n=setTimeout(()=>{t.abort()},e),r=await Promise.any(dn.map(async e=>fetch(e,{signal:t.signal,headers:{"User-Agent":un},keepalive:!1}))).catch(()=>null);return clearTimeout(n),r?r.ok?(cliDebugPrint(`isOnline`,{state:`online`,site:r.url}),!0):(cliDebugPrint(`isOnline`,{state:`offline`}),!1):(cliDebugPrint(`isOnline`,{state:`timeout`}),!1)}async function getLatestVersion(e){let t=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/latest`,{headers:{"User-Agent":un}});if(!t.ok)return cliDebugPrint(`useCLIVersionCheck`,`Failed to fetch latest version`,{statusCode:t.status,body:await t.text()}),warning({message:`Failed to fetch latest version of Apify CLI, using the cached version instead.`}),null;let n=(await t.json()).tag_name.replace(/^v/,``);return cliDebugPrint(`useCLIVersionCheck`,`Fetched latest version`,{version:n}),updateLocalState(e,e=>{e.versionCheck={lastChecked:Date.now(),lastVersion:n}}),n}function shouldSkipVersionCheck(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&![`0`,`false`].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}async function useCLIVersionCheck(e=!1){let t=useLocalState(),n=!t.versionCheck||Date.now()-t.versionCheck.lastChecked>864e5,r=e||n&&await isOnline(),i=r?await getLatestVersion(t):t.versionCheck?.lastVersion;if(!i)return{currentVersion:ln.version,latestVersion:`unknown`,shouldUpdate:!1,cacheHit:!1};let a=l(i,ln.version);return{currentVersion:ln.version,latestVersion:i,shouldUpdate:a,cacheHit:!r}}function useCommandSuggestions(e){let t=[...J.entries()].sort(([e],[t])=>e.localeCompare(t)),n=e.toLowerCase();return t.map(([e,t])=>{let r=e.toLowerCase(),i=e.split(` `),a=i[i.length-1].toLowerCase(),s=t.aliases?.includes(a)||t.hiddenAliases?.includes(a)||!1,c=Se(n,r),l=xe(n,r),u=c<=2||l>=.975;return u?(cliDebugPrint(`useCommandSuggestions`,{inputString:n,lowercased:r,matches:u,levenshtein:c,jaroWinkler:l}),s?{string:`${r} (alias for ${t.name})`,distance:l}:{string:`${r}`,distance:l}):null}).filter(e=>e!==null).sort((e,t)=>t.distance-e.distance).map(e=>e.string)}const fn=await readStdin(),pn=useCLIMetadata(),mn=`Apify CLI/${pn.version} (https://github.com/apify/apify-cli)`;function processVersionCheck(t){pn.installMethod!==`bundle`&&(p(e.version,W)||(error({message:`${t} CLI requires Node.js version ${W}. Your current version is ${e.version}.`}),e.exit(1)))}function printCLIVersionAndExitIfFlagUsed(t){t.values.version===!0&&t.positionals.length===0&&(console.log(pn.fullVersionString),e.exit(0))}function printHelpAndExitIfFlagUsedOrNoCommandPassed(t,n){(t.values.help===!0&&t.positionals.length===0||t.positionals.length===0)&&(console.log(renderMainHelpMenu(n)),e.exit(0))}function handleCommandNotFound(n){let r=useCommandSuggestions(String(n)),i=t.gray(`Command ${t.whiteBright(n)} not found`);r.length&&(i+=`
27
- `,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i}),e.exit(1)}async function runVersionCheck(e,t){let n=J.get(`upgrade`);if([n.name,...n.aliases??[]].some(e=>t===e)){cliDebugPrint(`[VersionCheckMiddleware]`,`upgrade command detected, skipping version check`);return}if(shouldSkipVersionCheck()){cliDebugPrint(`[VersionCheckMiddleware]`,`skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set`);return}await internalRunCommand(e,n,{flags_internalAutomaticCall:!0})}async function runCLI(t){cliDebugPrint(`CLIMetadata`,{...pn,fullVersionString:pn.fullVersionString,argv:e.argv,cwd:e.cwd(),execPath:e.execPath});let n=e.argv.slice(2);cliDebugPrint(`ProcessArgv`,n);let r=s({allowPositionals:!0,strict:!1,options:{help:{type:`boolean`,short:`h`},version:{type:`boolean`,short:`v`}},args:n});printCLIVersionAndExitIfFlagUsed(r),printHelpAndExitIfFlagUsedOrNoCommandPassed(r,t),await runVersionCheck(t,r.positionals[0]),cliDebugPrint(`TopLevelOptions`,r);let i=r.positionals[0],a=-1;if(J.get(i)?.subcommands?.length){if(r.positionals[1]?.toLowerCase()===`help`)a=1;else if(r.positionals[2]?.toLowerCase()===`help`){let e=J.get(`${i} ${r.positionals[1]}`);e&&!e.args&&(a=2)}}if(a!==-1){let e=r.positionals[a],t=n.indexOf(e);t!==-1&&n.splice(t,1),!n.includes(`--help`)&&!n.includes(`-h`)&&n.push(`--help`),r.positionals.splice(a,1),r.values.help=!0}let c=r.positionals[1],l=!1,u=J.get(i);if(!u)return handleCommandNotFound(i);let f=u;if(u.subcommands?.length){if(!c)return u.printHelp();l=!0,f=J.get(`${i} ${c}`)}if(!f)return handleCommandNotFound(`${i} ${c}`);let p=[...n],m=p.indexOf(i);if(cliDebugPrint(`CommandNameIndex`,m),p.splice(m,1),l){let e=p.indexOf(c);cliDebugPrint(`SubcommandNameIndex`,e),p.splice(e,1)}cliDebugPrint(`RebuiltArgs`,p),cliDebugPrint(`CommandToRun`,f);let h=new f(t,l?`${u.name} ${c}`:u.name,i,l?c:void 0),g=h._buildParseArgsOption();cliDebugPrint(`ParserOptionsForCommand`,g);try{let e=s({...g,args:p});await h._run(e),cliDebugPrint(`CommandArgsResult`,e)}catch(t){error({message:H.into(t,f).getPrettyMessage()}),e.exit(1)}}const hn=[[`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 detectAiAgent(){for(let[e,t]of hn)if(process.env[e])return t}function detectCi(){return Ce.isCI?{isCi:!0,ciProvider:Ce.id?.toLowerCase()??`unknown`}:{isCi:!1,ciProvider:void 0}}function detectIsInteractive(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}const updateLocalJson=async(e,t={},n=null)=>{let r=await F(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await R(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(oe).reduce((e,t)=>(e=k(e,t),v(e)||b(e),e),e)},rimrafPromised=async e=>{await et(e)},deleteFile=async e=>{(await L(e)).isFile()&&await Me(e)},sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>L(k(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0),gn=qe,_n=Ve,httpsGet=async e=>new Promise((t,n)=>{Ne(e,e=>{e.statusCode===301||e.statusCode===302?(t(httpsGet(e.headers.location)),e.destroy()):t(e)}).on(`error`,n)}),getLocalStorageDir=()=>{let t=N.LOCAL_STORAGE_DIR;return e.env[t]||e.env.CRAWLEE_STORAGE_DIR||`storage`},getLocalKeyValueStorePath=t=>{let n=j.DEFAULT_KEY_VALUE_STORE_ID,r=t||e.env[n]||ge[n];return k(getLocalStorageDir(),_e.keyValueStores,r)},getLocalDatasetPath=t=>{let n=j.DEFAULT_DATASET_ID,r=t||e.env[n]||ge[n];return k(getLocalStorageDir(),_e.datasets,r)},getLocalRequestQueuePath=t=>{let n=j.DEFAULT_REQUEST_QUEUE_ID,r=t||e.env[n]||ge[n];return k(getLocalStorageDir(),_e.requestQueues,r)},getLocalUserInfo=async()=>{let e={};try{let t=await F(AUTH_FILE_PATH(),`utf-8`);e=JSON.parse(t)}catch{return{}}if(!e.username&&!e.id)throw Error(`Corrupted local user info was found. Please run "apify login" to fix it.`);return e};async function getLoggedClientOrThrow(){let t=await getLoggedClient();if(!t)throw e.exitCode=1,Error(`You are not logged in with your Apify account. Call "apify login" to fix that.`);return t}const getTokenWithAuthFileFallback=e=>{if(!e&&v(GLOBAL_CONFIGS_FOLDER())&&v(AUTH_FILE_PATH())){let e=S(AUTH_FILE_PATH(),`utf-8`);return JSON.parse(e).token}return e},getApifyClientOptions=(t,n)=>(t=getTokenWithAuthFileFallback(t),{token:t,baseUrl:n||e.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[e=>{e.headers??=new Ge;for(let[t,n]of Object.entries(on))e.headers[t]=n;return e}]});async function getLoggedClient(e,t){e=getTokenWithAuthFileFallback(e);let n=new He(getApifyClientOptions(e,t)),r;try{r=await n.user(`me`).get()}catch(e){return cliDebugPrint(`[getLoggedClient] error getting user info`,{error:e,apiBaseUrl:t}),null}return ensureApifyDirectory(AUTH_FILE_PATH()),E(AUTH_FILE_PATH(),JSON.stringify({token:n.token,...r},null,` `)),n}const getLocalConfigPath=e=>k(e,U),getJsonFileContent=e=>{if(v(e))return JSON.parse(S(e,{encoding:`utf-8`}))},getLocalConfig=e=>getJsonFileContent(getLocalConfigPath(e)),setLocalConfig=async(t,n)=>{let r=k(n||e.cwd(),U);await P(O(r),{recursive:!0}),E(r,JSON.stringify(t,null,` `))},vn=[getLocalStorageDir(),`node_modules`,`.venv`],setLocalEnv=async e=>{let t=getLocalKeyValueStorePath();ensureFolderExistsSync(e,getLocalDatasetPath()),ensureFolderExistsSync(e,getLocalRequestQueuePath()),ensureFolderExistsSync(e,t);let n=k(e,`.gitignore`),r=``;v(n)&&(r=S(n,{encoding:`utf-8`}));let i=[];for(let e of vn)RegExp(`^${Ke(e)}$`,`mg`).test(r)||i.push(e);i.length>0&&(r.length>0?(i.unshift(`# Added by Apify CLI`),E(n,`\n${i.join(`
28
- `)}\n`,{flag:`a`})):E(n,`${i.join(`
29
- `)}\n`,{flag:`w`}))},yn=new Xe(Qe,Ze).define({"application/gzip":[`tgz`],"text/typescript":[`ts`,`tsx`,`mts`]},!0),getSourceFileFormat=(e,t)=>{let n=yn.getType(e);return n?n.startsWith(`text/`)||n.includes(`javascript`)||n.includes(`json`)||n.includes(`xml`)||n.includes(`application/node`)||n.includes(`application/toml`)||n.includes(`application/x-sh`)||n.includes(`application/x-httpd-php`)?be.TEXT:be.BASE64:Je(t)===`binary`?be.BASE64:be.TEXT},createSourceFiles=async(e,t)=>e.map(e=>{let n=S(k(t,e)),r=getSourceFileFormat(e,n);return{name:e,format:r,content:r===be.TEXT?n.toString(`utf8`):n.toString(`base64`)}}),getGitignoreFallbackFilter=async e=>{let t=await $e(`**/.gitignore`,{dot:!0,cwd:e,ignore:[`.git/**`],expandDirectories:!1}),n=[];for(let r of t){let t=O(r),i=await F(k(e,r),`utf-8`);n.push({dir:t===`.`?``:t,ig:gn().add(i)})}let r=O(e);for(;r!==O(r)&&!v(k(r,`.git`));){let t=k(r,`.gitignore`);if(v(t))try{let i=await F(t,`utf-8`),a=ae(r,e);n.push({dir:``,ig:gn().add(i),ancestorPrefix:a})}catch{}r=O(r)}return n.length===0?e=>e:e=>e.filter(e=>{for(let{dir:t,ig:r,ancestorPrefix:i}of n){let n;if(n=t?e.startsWith(`${t}/`)?e.slice(t.length+1):null:i?`${i}/${e}`:e,n!==null&&r.ignores(n))return!1}return!0})},parseActorIgnore=async e=>{let t=k(e,`.actorignore`);if(!v(t))return{excludeFilter:null,forceIncludePatterns:[]};let n=(await F(t,`utf-8`)).split(`
30
- `),r=[],i=[];for(let e of n){let t=e.trim();!t||t.startsWith(`#`)||(t.startsWith(`!`)?i.push(t.slice(1)):r.push(t))}return{excludeFilter:r.length>0?e=>{let t=gn().add(r);return e.filter(e=>!t.ignores(e))}:null,forceIncludePatterns:i}},getActorLocalFilePaths=async t=>{let n=t??e.cwd(),r=[`.git/**`,`apify_storage`,`node_modules`,`storage`,`crawlee_storage`],{excludeFilter:i,forceIncludePatterns:a}=await parseActorIgnore(n),gitIgnoreFilter=null;try{let e=Ee(`git ls-files --others --ignored --exclude-standard --directory`,{cwd:n,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).split(`
31
- `).filter(Boolean);if(e.length>0){let t=gn().add(e);gitIgnoreFilter=e=>e.filter(e=>!t.ignores(e))}}catch{gitIgnoreFilter=await getGitignoreFallbackFilter(n)}let s=await $e([`*`,`**/**`],{ignore:r,dot:!0,expandDirectories:!1,cwd:n}),c=gitIgnoreFilter?gitIgnoreFilter(s):s;if(i&&(c=i(c)),a.length>0){let e=gn().add(a),t=s.filter(t=>e.ignores(t)),n=new Set(c);for(let e of t)n.add(e);c=[...n]}let l=s.filter(e=>e===`.actor`||e.startsWith(`.actor/`));if(l.length>0){let e=new Set(c);for(let t of l)e.add(t);c=[...e]}return c},createActZip=async(e,t,n)=>{v(e)&&await deleteFile(e);let r=_(e),i=Ue(`zip`,{zlib:{level:6}});i.pipe(r),t.forEach(e=>i.file(k(n,e),{name:e})),await i.finalize()},getLocalInput=e=>{let t=getLocalKeyValueStorePath();if(!v(k(e,t)))return;let n=C(k(e,t)).find(e=>!!e.match(an));return n?{body:S(k(e,t,n)),contentType:yn.getType(n),fileName:n}:void 0},purgeDefaultQueue=async()=>{let e=getLocalRequestQueuePath();v(getLocalStorageDir())&&v(e)&&await rimrafPromised(e)},purgeDefaultDataset=async()=>{let e=getLocalDatasetPath();v(getLocalStorageDir())&&v(e)&&await rimrafPromised(e)},purgeDefaultKeyValueStore=async()=>{let e=getLocalKeyValueStorePath();if(!v(getLocalStorageDir())||!v(e))return;let t=C(e),n=[];t.forEach(t=>{t.match(an)||n.push(deleteFile(k(e,t)))}),await Promise.all(n)},outputJobLog=async({job:t,timeoutMillis:n,apifyClient:r})=>{let{id:i,status:a}=t,s=r||new He({baseUrl:e.env.APIFY_CLIENT_BASE_URL});if(fe.includes(a)){if(e.env.APIFY_NO_LOGS_IN_TESTS)return;let t=await s.log(i).get();e.stderr.write(t);return}return new Promise(async t=>{let r=await s.log(i).stream();if(!r){t(`no-logs`);return}let a=null;r.on(`data`,t=>{e.env.APIFY_NO_LOGS_IN_TESTS||e.stderr.write(t.toString())}),r.once(`end`,()=>{t(`finished`),a&&clearTimeout(a)}),n&&(a=setTimeout(()=>{r.destroy(),t(`timeouts`)},n))})},checkIfStorageIsEmpty=async()=>(await $e([`${getLocalStorageDir()}/**`,`!${getLocalKeyValueStorePath()}/${he.INPUT}.*`,`!${getLocalKeyValueStorePath()}/${he.INPUT}_CLI-*`])).length===0,validateActorName=e=>{if(!pe.REGEX.test(e))throw Error(`The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).`);if(e.length<pe.MIN_LENGTH)throw Error(`The Actor name must be at least 3 characters long.`);if(e.length>pe.MAX_LENGTH)throw Error(`The Actor name must be a maximum of 30 characters long.`)},sanitizeActorName=e=>{let t=e.replaceAll(/[^a-zA-Z0-9-]/g,`-`);return t.length<pe.MIN_LENGTH&&(t=`${t}-apify-actor`),t=t.replaceAll(/^-+/g,``).replaceAll(/-+$/g,``),t.slice(0,pe.MAX_LENGTH)},isPythonVersionSupported=e=>p(e,`^${sn}`),isNodeVersionSupported=e=>u(e,f(W)),downloadAndUnzip=async({url:e,pathTo:t})=>{let n=await httpsGet(e),r=[];n.on(`data`,e=>r.push(e)),await Pe(n),new Be(Buffer.concat(r)).extractAllTo(t,!0)};function ensureApifyDirectory(e){b(O(e),{recursive:!0})}const G=new ze(`YYYY-MM-DD [at] HH:mm:ss`),bn=new ze(`YYYY-MM-DD[
32
- ]HH:mm:ss`),xn=new ze(`YYYY-MM-DD`),Sn=new Ie,K=new Ie({[Re.Day]:{DEFAULT:`d`},[Re.Hour]:{DEFAULT:`h`},[Re.Minute]:{DEFAULT:`m`},[Re.Month]:{DEFAULT:`M`},[Re.Second]:{DEFAULT:`s`},[Re.Week]:{DEFAULT:`w`},[Re.Year]:{DEFAULT:`y`}});function objectGroupBy(e,t){if(`groupBy`in Object)return Object.groupBy(e,t);let n={},r=0;for(let i of e){let e=t(i,r++);n[e]||(n[e]=[]),n[e].push(i)}return n}function printJsonToStdout(e){console.log(JSON.stringify(e,null,2))}const tildify=e=>e.startsWith(ue())?e.replace(ue(),`~`):e;function detectShell(){let t=e.env.SHELL??``;return t.includes(`zsh`)?`zsh`:t.includes(`bash`)?`bash`:t.includes(`fish`)?`fish`:`unknown`}function shellConfigFile(t,n){switch(n){case`bash`:{let n=[k(t,`.bashrc`),k(t,`.bash_profile`)];e.env.XDG_CONFIG_HOME&&n.push(k(e.env.XDG_CONFIG_HOME,`.bashrc`),k(e.env.XDG_CONFIG_HOME,`.bash_profile`),k(e.env.XDG_CONFIG_HOME,`bashrc`),k(e.env.XDG_CONFIG_HOME,`bash_profile`));for(let e of n)if(v(e))return e;return null}case`zsh`:return k(e.env.ZDOTDIR||ue(),`.zshrc`);case`fish`:return k(t,`.config`,`fish`,`config.fish`);case`unknown`:return null}}const Cn=[`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(`
33
- `);function createAnonymousId(){return`CLI:${Te()}`}async function migrateStateV0ToV1(e){if(e.version&&e.version>=1)return!1;let t=e,n=await getLocalUserInfo().catch(()=>({}));return updateTelemetryState({version:1,enabled:!0},e=>{n.id&&t.distinctId===n.id?(e.anonymousId=createAnonymousId(),e.userId=n.id):e.anonymousId=t.distinctId}),!0}async function useTelemetryState(){let e=TELEMETRY_FILE_PATH();if(!v(e)){let e=await getLocalUserInfo().catch(()=>({}));return updateTelemetryState({version:1,enabled:!0,anonymousId:createAnonymousId(),userId:e.id}),(!process.env.APIFY_CLI_DISABLE_TELEMETRY||[`false`,`0`].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))&&info({message:Cn}),useTelemetryState()}let t=JSON.parse(S(e,`utf-8`));return await migrateStateV0ToV1(t)?useTelemetryState():t}function updateTelemetryState(e,t){let n={...e};t?.(n),b(O(TELEMETRY_FILE_PATH()),{recursive:!0}),E(TELEMETRY_FILE_PATH(),JSON.stringify(n,null,` `))}async function updateUserId(e){updateTelemetryState(await useTelemetryState(),t=>{t.userId=e})}async function checkAndUpdateLastCommand(e){try{let t=await useTelemetryState(),n=Date.now(),r=t.lastCommand===e&&n-(t.lastCommandTimestamp??0)<1e4;return updateTelemetryState(t,t=>{t.lastCommand=e,t.lastCommandTimestamp=n}),r}catch{return!1}}async function updateTelemetryEnabled(e){updateTelemetryState(await useTelemetryState(),t=>{t.enabled=e})}async function useTelemetryEnabled(){if(process.env.APIFY_CLI_DISABLE_TELEMETRY&&![`false`,`0`].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))return cliDebugPrint(`telemetry`,`disabled by env variable`),!1;let e=await useTelemetryState();return cliDebugPrint(`telemetry state`,{telemetryState:e}),e.enabled}async function useTelemetryIdentifiers(){let e=await useTelemetryState();return{anonymousId:e.anonymousId,userId:e.userId}}const wn=useCLIMetadata(),Tn=wn.isBeta?`rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC`:`2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t`;async function trackEvent(e,t){let n=await useTelemetryIdentifiers(),r={anonymousId:n.anonymousId,context:{app:{name:`apify-cli`,version:wn.version,build:wn.hash},library:{name:`apify-cli`,version:wn.version},os:{name:wn.platform},userAgent:mn,channel:`server`},event:e,properties:{...t,app:`cli`},timestamp:new Date().toISOString(),userId:n.userId,writeKey:Tn};if(cliDebugPrint(`trackEvent`,r),!await useTelemetryEnabled()){cliDebugPrint(`trackEvent`,`telemetry disabled`);return}try{let e=await fetch(`https://api.segment.io/v1/track`,{method:`POST`,body:JSON.stringify(r)});if(!e.ok){cliDebugPrint(`trackEvent`,`failed to send event`,await e.text());return}cliDebugPrint(`trackEvent`,`event sent`)}catch(e){cliDebugPrint(`trackEvent`,`failed to send event`,e)}}const En=`confirm`,Dn=`no-${En}`;function stdinCheckWrapper(e,{errorMessageForStdin:t=`Please use the --${En}/--${Dn} flags to confirm the action.`}={}){return async(n,...r)=>{let{isTTY:i,hasData:a}=await useStdin(),s=n;if(st||!i&&!a){if(s.providedConfirmFromStdin===void 0)throw Error(s.errorMessageForStdin??t??`Please use the --${En}/--${Dn} flags to confirm the action.`);return s.providedConfirmFromStdin}return await e(n,...r)}}const On=stdinCheckWrapper(async({message:e,validate:t,default:n})=>await ot({message:e,validate:t,default:n}),{errorMessageForStdin:`Please provide a valid input based on the command options.`});var Spider=class{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}},SpiderFileAnalyzer=class{pathname;constructor(e){this.pathname=e}getSpiders(){let e=S(this.pathname,`utf8`),t=/class\s+(\w+)/g,n=[],r=t.exec(e);for(;r;)n.push(new Spider({class_name:r[1],pathname:this.pathname})),r=t.exec(e);return n}},ScrapyProjectAnalyzer=class{pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return v(k(e,`scrapy.cfg`))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new at,t=A(k(this.pathname,`scrapy.cfg`));if(!v(t))throw Error(`scrapy.cfg not found in "${t}".
34
- 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 On({message:`Enter the Scrapy BOT_NAME (see settings.py):`,default:e}),n=await On({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 n==`string`?[n]:n}}getName(){return this.settings?.BOT_NAME}getAvailableSpiders(){let e=this.settings?.SPIDER_MODULES;if(!e)throw Error(`SPIDER_MODULES path not found in settings.`);let t=[];for(let n of e){let e=k(this.pathname,n.replaceAll(`.`,`/`)),r=C(e,{withFileTypes:!0});for(let n of r)n.isFile()&&n.name.endsWith(`.py`)&&n.name!==`__init__.py`&&t.push(...new SpiderFileAnalyzer(k(e,n.name)).getSpiders())}return t}};function normalizeExecutablePath(e){return e?e.startsWith(`"`)?e:ie(e)&&e.includes(` `)?`"${e}"`:e:null}async function getInstallCommandSuggestion(e){let t=null;return await(await useCwdProject({cwd:e})).inspectAsync(async n=>{if(n.type===0){let[r,i,a,s]=await Promise.all([L(k(e,`yarn.lock`)).then(()=>!0).catch(()=>!1),L(k(e,`pnpm-lock.yaml`)).then(()=>!0).catch(()=>!1),L(k(e,`bun.lockb`)).then(()=>!0).catch(()=>!1),L(k(e,`bun.lock`)).then(()=>!0).catch(()=>!1)]);t=r?`yarn install`:i?`pnpm install`:a||s||n.runtime?.pmName===`bun`?`bun install`:n.runtime?.pmName===`deno`?`deno install --node-modules-dir`:`npm install`}else (n.type===1||n.type===2)&&(t=`python -m pip install -r requirements.txt`)}),t}const kn=new Map,An={node:[`--version`],deno:[`eval`,`"console.log(process.versions.node)"`],bun:[`--eval`,`"console.log(process.versions.node)"`]};async function getRuntimeVersion(t,n){try{let r=await ct(t,n,{shell:!0,windowsHide:!0,verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0});return r.stdout?r.stdout.trim().replace(/^v/,``):null}catch{return null}}async function getNpmVersion(t){let n=await ct(t,[`--version`],{shell:!0,windowsHide:!0,verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0});return n.stdout?n.stdout.trim().replace(/^v/,``):null}async function useJavaScriptRuntime(t=e.cwd()){let n=kn.get(t);if(n)return cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!0,cwd:t,runtime:n.unwrapOr(null)}),n;for(let[e,n]of Object.entries(An))try{let r=normalizeExecutablePath(await lt(e)),i=await getRuntimeVersion(r,n);if(i){let n={executablePath:r,version:i};if(e===`node`){let e=normalizeExecutablePath(await lt(`npm`).catch(()=>null));e&&(n.pmPath=e,n.pmVersion=await getNpmVersion(e),n.pmName=`npm`)}else n.runtimeShorthand=e,n.pmPath=r,n.pmVersion=i,n.pmName=e;return kn.set(t,it(n)),cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!1,cwd:t,runtime:kn.get(t)?.unwrap()}),it(n)}}catch{}return kn.set(t,B),cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!1,cwd:t,runtime:null}),B}const q=new Map;async function getPythonVersion(t){try{let n=await ct(t,[`-c`,`"import platform; print(platform.python_version())"`],{shell:!0,windowsHide:!0,verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0});return n.stdout?n.stdout.trim():null}catch{return null}}async function usePythonRuntime({cwd:t=e.cwd(),force:n=!1}={}){let r=q.get(t);if(r&&!n)return cliDebugPrint(`usePythonRuntime`,{cacheHit:!0,cwd:t,runtime:r.unwrapOr(null)}),r;let i=de()===`win32`,a=i?[`Scripts`,`python.exe`]:[`bin`,`python3`],s;s=e.env.VIRTUAL_ENV?k(e.env.VIRTUAL_ENV,...a):k(t,`.venv`,...a),s=normalizeExecutablePath(s);try{let e=await getPythonVersion(s);if(e)return q.set(t,it({executablePath:s,version:e})),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:q.get(t)?.unwrap()}),q.get(t)}catch{}let c=[`python3`,`python`,...i?[`python3.exe`,`python.exe`]:[]];for(let e of c)try{let n=normalizeExecutablePath(await lt(e)),r=await getPythonVersion(n);if(r)return q.set(t,it({executablePath:n,version:r})),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:q.get(t)?.unwrap()}),q.get(t)}catch{}return q.set(t,B),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:null}),B}const jn=new Map;async function useCwdProject({cwd:t=e.cwd()}={}){let n=jn.get(t);if(n)return cliDebugPrint(`useCwdProject`,{cacheHit:!0,project:n}),rt(n);let r={type:3},check=async()=>{if(await checkScrapyProject(t)){r.type=2,r.runtime=(await usePythonRuntime({cwd:t})).unwrapOr(void 0);let e=new ScrapyProjectAnalyzer(t);if(e.loadScrapyCfg(),e.configuration.hasKey(`apify`,`mainpy_location`))r.entrypoint={path:e.configuration.get(`apify`,`mainpy_location`)};else try{let e=await checkPythonProject(t);e&&(r.entrypoint={path:e})}catch{}return}let e=await checkNodeProject(t);if(!e){let e=null;try{e=await checkPythonProject(t)}catch(e){return nt({message:e instanceof Error?e.message:String(e)})}if(e){r.type=1;let n=await usePythonRuntime({cwd:t});r.entrypoint={path:e},r.runtime=n.unwrapOr(void 0),await fileExists(k(k(t,e.replace(/\./g,`/`)),`__main__.py`))||(r.warnings=[`The detected Python package "${e}" is missing __main__.py. Running with "python -m" will fail without it.`]);return}}if(e){r.type=0,r.runtime=(await useJavaScriptRuntime()).unwrapOr(void 0),e.type===`file`?r.entrypoint={path:e.path}:e.type===`script`&&(r.entrypoint={script:e.script});return}return rt(r)},i=await check();return i?.isErr()?(cliDebugPrint(`useCwdProject`,{cacheHit:!1,error:i}),i):(cliDebugPrint(`useCwdProject`,{cacheHit:!1,project:r}),jn.set(t,r),rt(r))}async function checkNodeProject(e){let t=k(e,`package.json`);try{let n=await F(t,`utf-8`),r=JSON.parse(n);if(r.scripts?.start)return{type:`script`,script:`start`};if(r.main)try{return await Oe(A(e,r.main)),{path:A(e,r.main),type:`file`}}catch{}return{type:`unknown-entrypoint`}}catch{}let n=[k(e,`index.js`),k(e,`index.mjs`),k(e,`index.cjs`),k(e,`main.js`),k(e,`main.mjs`),k(e,`main.cjs`),k(e,`src`,`index.js`),k(e,`src`,`index.mjs`),k(e,`src`,`index.cjs`),k(e,`src`,`main.js`),k(e,`src`,`main.mjs`),k(e,`src`,`main.cjs`),k(e,`dist`,`index.js`),k(e,`dist`,`index.mjs`),k(e,`dist`,`index.cjs`),k(e,`dist`,`main.js`),k(e,`dist`,`main.mjs`),k(e,`dist`,`main.cjs`)];for(let e of n)try{return await Oe(e),{path:e,type:`file`}}catch{}return null}async function fileExists(e){try{return await Oe(e),!0}catch{return!1}}async function dirExists(e){try{return(await L(e)).isDirectory()}catch{return!1}}function isValidPythonIdentifier(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}async function hasPythonFilesInDirOrSubdirs(e){try{let t=await I(e,{withFileTypes:!0});if(t.some(e=>e.isFile()&&e.name.endsWith(`.py`)))return!0;for(let n of t){if(!n.isDirectory()||n.name.startsWith(`.`)||n.name.startsWith(`_`))continue;let t=k(e,n.name);try{let e=await I(t,{withFileTypes:!0});if(e.some(e=>e.isFile()&&e.name.endsWith(`.py`)))return!0;if(n.name===`src`){for(let n of e)if(n.isDirectory()&&!(n.name.startsWith(`.`)||n.name.startsWith(`_`)))try{if((await I(k(t,n.name),{withFileTypes:!0})).some(e=>e.isFile()&&e.name.endsWith(`.py`)))return!0}catch{}}}catch{}}return!1}catch{return!1}}async function dirHasPyFiles(e){try{return(await I(e,{withFileTypes:!0})).some(e=>e.isFile()&&e.name.endsWith(`.py`)&&e.name!==`__init__.py`)}catch{return!1}}async function findNearMissPackagesInDir(e){try{let t=await I(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory()||r.name.startsWith(`.`)||r.name.startsWith(`_`))continue;let t=isValidPythonIdentifier(r.name),i=await fileExists(k(e,r.name,`__init__.py`)),a=i||await dirHasPyFiles(k(e,r.name));t&&i||a&&n.push({name:r.name,needsRename:!t,needsInit:!i})}return n}catch{return[]}}async function findPackagesInDir(e){try{let t=await I(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let{name:t}=r;t.startsWith(`.`)||t.startsWith(`_`)||!isValidPythonIdentifier(t)||await fileExists(k(e,t,`__init__.py`))&&n.push({name:t,path:k(e,t)})}return n}catch{return[]}}async function discoverPythonPackages(e){let t=[],n=await findPackagesInDir(e);t.push(...n.map(e=>e.name));let r=k(e,`src`),i=await fileExists(k(r,`__init__.py`));if(await dirExists(r)&&!i){let e=await findPackagesInDir(r);t.push(...e.map(e=>`src.${e.name}`))}return t}async function checkPythonProject(e){let t=await discoverPythonPackages(e);if(t.length===1)return t[0];if(t.length>1){let e=t.map(e=>` - ${e}`).join(`
26
+ `)}`):n.push(`To solve this, provide the flag like this: --${e.name}=<value>`)):e.expectsValue?n.push(`expects a value`):n.push(`does not take an argument`),n.map(e=>t.gray(e)).join(` `)}static into(e,t){if(e instanceof CommandError)return e;if(e instanceof Error&&`code`in e){let n=e;switch(n.code){case`ERR_PARSE_ARGS_INVALID_OPTION_VALUE`:return new CommandError({code:0,message:n.message,command:t});case`ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL`:return new CommandError({code:1,message:n.message,command:t});case`ERR_PARSE_ARGS_UNKNOWN_OPTION`:return new CommandError({code:2,message:n.message,command:t});default:return new CommandError({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}}return new CommandError({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}};function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Xt=c(y);let Zt;async function useStdin(){if(Zt)return Zt;let t=e.stdin,n={isTTY:t.isTTY,hasData:!1,waitDelay:0,stream:t},r=await Xt(0).then(t=>{if(cliDebugPrint(`useStdin`,{stat:t,isRegularFile:t.isFile(),isDirectory:t.isDirectory(),isBlockDevice:t.isBlockDevice(),isCharDevice:t.isCharacterDevice(),isSymbolicLink:t.isSymbolicLink(),isFIFO:t.isFIFO(),isSocket:t.isSocket()}),e.platform===`win32`){if((t.mode&h.S_IFIFO)===h.S_IFIFO)return 100;if(t.isFile())return 50}return t.isFIFO()||t.isFile()||(t.isSocket()?50:!1)}).catch(()=>!1);return cliDebugPrint(`useStdin`,{hasData:n.hasData,waitDelay:n.waitDelay,isTTY:n.isTTY,pipedIn:r,readableEnded:t.readableEnded}),(!t.isTTY||r!==!1&&(t.isTTY!==void 0||!t.readableEnded))&&(n.hasData=!0),typeof r==`number`&&(n.waitDelay=r),Zt=n,n}async function readStdin(){let e=await useStdin(),{hasData:t,waitDelay:n,stream:r}=e;if(!t)return;let i=[],a=new AbortController,s=null;n&&(s=setTimeout(()=>{a.abort()},n).unref()),r.on(`data`,e=>{i.push(e),s&&=(clearTimeout(s),null)});try{await ce(r,`end`,{signal:a.signal})}catch(e){if(e.name===`AbortError`)return}s&&clearTimeout(s),e.hasData=!1;let c=Buffer.concat(i);if(c.length)return c}var Qt={node:`>=20`};const $t=`storage`,en={actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},tn=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let e=A(le(),`.apify`);return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?A(e,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):e},AUTH_FILE_PATH=()=>A(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>A(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>A(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>A(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),nn=`.actor`,W=A(nn,`actor.json`),rn=Qt.node,an={"X-Apify-Request-Origin":ve.CLI},on=`3.9.0`;function migrateStateV0ToV1$1(e){if(e.version&&e.version>=1)return!1;let t=e;if(t.latestNpmVersionCheckedAt){let n=new Date(t.latestNpmVersionCheckedAt).getTime(),r=t.latestNpmVersion;cliDebugPrint(`LocalStateV0ToV1`,`Migrating state from v0 to v1`,{oldState:e,newState:{versionCheck:{lastChecked:n,lastVersion:r}}}),updateLocalState({version:1},e=>{e.versionCheck={lastChecked:n,lastVersion:r}})}return!0}const sn={version:1};function useLocalState(){let e=STATE_FILE_PATH();if(!v(e))return sn;let t=JSON.parse(S(e,`utf-8`));return migrateStateV0ToV1$1(t)?useLocalState():t}function updateLocalState(e,t){let n={...e};t(n),b(k(STATE_FILE_PATH()),{recursive:!0}),D(STATE_FILE_PATH(),JSON.stringify(n,null,` `))}const cn=useCLIMetadata(),ln=`Apify CLI/${cn.version} (https://github.com/apify/apify-cli)`,un=[`https://1.1.1.1`,`https://8.8.8.8`];async function isOnline(e=500){let t=new AbortController,n=setTimeout(()=>{t.abort()},e),r=await Promise.any(un.map(async e=>fetch(e,{signal:t.signal,headers:{"User-Agent":ln},keepalive:!1}))).catch(()=>null);return clearTimeout(n),r?r.ok?(cliDebugPrint(`isOnline`,{state:`online`,site:r.url}),!0):(cliDebugPrint(`isOnline`,{state:`offline`}),!1):(cliDebugPrint(`isOnline`,{state:`timeout`}),!1)}async function getLatestVersion(e){let t=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/latest`,{headers:{"User-Agent":ln}});if(!t.ok)return cliDebugPrint(`useCLIVersionCheck`,`Failed to fetch latest version`,{statusCode:t.status,body:await t.text()}),warning({message:`Failed to fetch latest version of Apify CLI, using the cached version instead.`}),null;let n=(await t.json()).tag_name.replace(/^v/,``);return cliDebugPrint(`useCLIVersionCheck`,`Fetched latest version`,{version:n}),updateLocalState(e,e=>{e.versionCheck={lastChecked:Date.now(),lastVersion:n}}),n}function shouldSkipVersionCheck(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&![`0`,`false`].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}async function useCLIVersionCheck(e=!1){let t=useLocalState(),n=!t.versionCheck||Date.now()-t.versionCheck.lastChecked>864e5,r=e||n&&await isOnline(),i=r?await getLatestVersion(t):t.versionCheck?.lastVersion;if(!i)return{currentVersion:cn.version,latestVersion:`unknown`,shouldUpdate:!1,cacheHit:!1};let a=l(i,cn.version);return{currentVersion:cn.version,latestVersion:i,shouldUpdate:a,cacheHit:!r}}function useCommandSuggestions(e){let t=[...J.entries()].sort(([e],[t])=>e.localeCompare(t)),n=e.toLowerCase();return t.map(([e,t])=>{let r=e.toLowerCase(),i=e.split(` `),a=i[i.length-1].toLowerCase(),s=t.aliases?.includes(a)||t.hiddenAliases?.includes(a)||!1,c=xe(n,r),l=be(n,r),u=c<=2||l>=.975;return u?(cliDebugPrint(`useCommandSuggestions`,{inputString:n,lowercased:r,matches:u,levenshtein:c,jaroWinkler:l}),s?{string:`${r} (alias for ${t.name})`,distance:l}:{string:`${r}`,distance:l}):null}).filter(e=>e!==null).sort((e,t)=>t.distance-e.distance).map(e=>e.string)}const dn=await readStdin(),fn=useCLIMetadata(),pn=`Apify CLI/${fn.version} (https://github.com/apify/apify-cli)`;function processVersionCheck(t){fn.installMethod!==`bundle`&&(p(e.version,rn)||(error({message:`${t} CLI requires Node.js version ${rn}. Your current version is ${e.version}.`}),e.exit(1)))}function printCLIVersionAndExitIfFlagUsed(t){t.values.version===!0&&t.positionals.length===0&&(console.log(fn.fullVersionString),e.exit(0))}function printHelpAndExitIfFlagUsedOrNoCommandPassed(t,n){(t.values.help===!0&&t.positionals.length===0||t.positionals.length===0)&&(console.log(renderMainHelpMenu(n)),e.exit(0))}function handleCommandNotFound(n){let r=useCommandSuggestions(String(n)),i=t.gray(`Command ${t.whiteBright(n)} not found`);r.length&&(i+=`
27
+ `,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i}),e.exit(1)}async function runVersionCheck(e,t){let n=J.get(`upgrade`);if([n.name,...n.aliases??[]].some(e=>t===e)){cliDebugPrint(`[VersionCheckMiddleware]`,`upgrade command detected, skipping version check`);return}if(shouldSkipVersionCheck()){cliDebugPrint(`[VersionCheckMiddleware]`,`skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set`);return}await internalRunCommand(e,n,{flags_internalAutomaticCall:!0})}async function runCLI(t){cliDebugPrint(`CLIMetadata`,{...fn,fullVersionString:fn.fullVersionString,argv:e.argv,cwd:e.cwd(),execPath:e.execPath});let n=e.argv.slice(2);cliDebugPrint(`ProcessArgv`,n);let r=s({allowPositionals:!0,strict:!1,options:{help:{type:`boolean`,short:`h`},version:{type:`boolean`,short:`v`}},args:n});printCLIVersionAndExitIfFlagUsed(r),printHelpAndExitIfFlagUsedOrNoCommandPassed(r,t),await runVersionCheck(t,r.positionals[0]),cliDebugPrint(`TopLevelOptions`,r);let i=r.positionals[0],a=-1;if(J.get(i)?.subcommands?.length){if(r.positionals[1]?.toLowerCase()===`help`)a=1;else if(r.positionals[2]?.toLowerCase()===`help`){let e=J.get(`${i} ${r.positionals[1]}`);e&&!e.args&&(a=2)}}if(a!==-1){let e=r.positionals[a],t=n.indexOf(e);t!==-1&&n.splice(t,1),!n.includes(`--help`)&&!n.includes(`-h`)&&n.push(`--help`),r.positionals.splice(a,1),r.values.help=!0}let c=r.positionals[1],l=!1,u=J.get(i);if(!u)return handleCommandNotFound(i);let f=u;if(u.subcommands?.length){if(!c)return u.printHelp();l=!0,f=J.get(`${i} ${c}`)}if(!f)return handleCommandNotFound(`${i} ${c}`);let p=[...n],m=p.indexOf(i);if(cliDebugPrint(`CommandNameIndex`,m),p.splice(m,1),l){let e=p.indexOf(c);cliDebugPrint(`SubcommandNameIndex`,e),p.splice(e,1)}cliDebugPrint(`RebuiltArgs`,p),cliDebugPrint(`CommandToRun`,f);let h=new f(t,l?`${u.name} ${c}`:u.name,i,l?c:void 0),g=h._buildParseArgsOption();cliDebugPrint(`ParserOptionsForCommand`,g);try{let e=s({...g,args:p});await h._run(e),cliDebugPrint(`CommandArgsResult`,e)}catch(t){error({message:U.into(t,f).getPrettyMessage()}),e.exit(1)}}const mn=[[`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 detectAiAgent(){for(let[e,t]of mn)if(process.env[e])return t}function detectCi(){return Se.isCI?{isCi:!0,ciProvider:Se.id?.toLowerCase()??`unknown`}:{isCi:!1,ciProvider:void 0}}function detectIsInteractive(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}const updateLocalJson=async(e,t={},n=null)=>{let r=await I(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await z(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(ae).reduce((e,t)=>(e=A(e,t),v(e)||b(e),e),e)},rimrafPromised=async e=>{await Qe(e)},deleteFile=async e=>{(await R(e)).isFile()&&await je(e)},sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>R(A(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0),hn=`__CLI_`;function resolveInputKey(){return process.env[M.INPUT_KEY]||process.env[P.INPUT_KEY]||process.env.CRAWLEE_INPUT_KEY||`INPUT`}function inputFileRegExp(e){return RegExp(`(^${We(e)}(?:\\.[^.]+)?$)`)}const gn=Ge,_n=ze,httpsGet=async e=>new Promise((t,n)=>{Me(e,e=>{e.statusCode===301||e.statusCode===302?(t(httpsGet(e.headers.location)),e.destroy()):t(e)}).on(`error`,n)}),getLocalStorageDir=()=>{let t=P.LOCAL_STORAGE_DIR;return e.env[t]||e.env.CRAWLEE_STORAGE_DIR||`storage`},getLocalKeyValueStorePath=t=>{let n=M.DEFAULT_KEY_VALUE_STORE_ID,r=t||e.env[n]||he[n];return A(getLocalStorageDir(),ge.keyValueStores,r)},getLocalDatasetPath=t=>{let n=M.DEFAULT_DATASET_ID,r=t||e.env[n]||he[n];return A(getLocalStorageDir(),ge.datasets,r)},getLocalRequestQueuePath=t=>{let n=M.DEFAULT_REQUEST_QUEUE_ID,r=t||e.env[n]||he[n];return A(getLocalStorageDir(),ge.requestQueues,r)},getLocalUserInfo=async()=>{let e={};try{let t=await I(AUTH_FILE_PATH(),`utf-8`);e=JSON.parse(t)}catch{return{}}if(!e.username&&!e.id)throw Error(`Corrupted local user info was found. Please run "apify login" to fix it.`);return e};async function getLoggedClientOrThrow(){let t=await getLoggedClient();if(!t)throw e.exitCode=1,Error(`You are not logged in with your Apify account. Call "apify login" to fix that.`);return t}const getTokenWithAuthFileFallback=e=>{if(!e&&v(GLOBAL_CONFIGS_FOLDER())&&v(AUTH_FILE_PATH())){let e=S(AUTH_FILE_PATH(),`utf-8`);return JSON.parse(e).token}return e},getApifyClientOptions=(t,n)=>(t=getTokenWithAuthFileFallback(t),{token:t,baseUrl:n||e.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[e=>{e.headers??=new Ue;for(let[t,n]of Object.entries(an))e.headers[t]=n;return e}]});async function getLoggedClient(e,t){e=getTokenWithAuthFileFallback(e);let n=new Be(getApifyClientOptions(e,t)),r;try{r=await n.user(`me`).get()}catch(e){return cliDebugPrint(`[getLoggedClient] error getting user info`,{error:e,apiBaseUrl:t}),null}return ensureApifyDirectory(AUTH_FILE_PATH()),D(AUTH_FILE_PATH(),JSON.stringify({token:n.token,...r},null,` `)),n}const getLocalConfigPath=e=>A(e,W),getJsonFileContent=e=>{if(v(e))return JSON.parse(S(e,{encoding:`utf-8`}))},getLocalConfig=e=>getJsonFileContent(getLocalConfigPath(e)),setLocalConfig=async(t,n)=>{let r=A(n||e.cwd(),W);await F(k(r),{recursive:!0}),D(r,JSON.stringify(t,null,` `))},vn=[getLocalStorageDir(),`node_modules`,`.venv`],setLocalEnv=async e=>{let t=getLocalKeyValueStorePath();ensureFolderExistsSync(e,getLocalDatasetPath()),ensureFolderExistsSync(e,getLocalRequestQueuePath()),ensureFolderExistsSync(e,t);let n=A(e,`.gitignore`),r=``;v(n)&&(r=S(n,{encoding:`utf-8`}));let i=[];for(let e of vn)RegExp(`^${We(e)}$`,`mg`).test(r)||i.push(e);i.length>0&&(r.length>0?(i.unshift(`# Added by Apify CLI`),D(n,`\n${i.join(`
28
+ `)}\n`,{flag:`a`})):D(n,`${i.join(`
29
+ `)}\n`,{flag:`w`}))},yn=new Je(Xe,Ye).define({"application/gzip":[`tgz`],"text/typescript":[`ts`,`tsx`,`mts`]},!0),getSourceFileFormat=(e,t)=>{let n=yn.getType(e);return n?n.startsWith(`text/`)||n.includes(`javascript`)||n.includes(`json`)||n.includes(`xml`)||n.includes(`application/node`)||n.includes(`application/toml`)||n.includes(`application/x-sh`)||n.includes(`application/x-httpd-php`)?ye.TEXT:ye.BASE64:Ke(t)===`binary`?ye.BASE64:ye.TEXT},createSourceFiles=async(e,t)=>e.map(e=>{let n=S(A(t,e)),r=getSourceFileFormat(e,n);return{name:e,format:r,content:r===ye.TEXT?n.toString(`utf8`):n.toString(`base64`)}}),getGitignoreFallbackFilter=async e=>{let t=await Ze(`**/.gitignore`,{dot:!0,cwd:e,ignore:[`.git/**`],expandDirectories:!1}),n=[];for(let r of t){let t=k(r),i=await I(A(e,r),`utf-8`);n.push({dir:t===`.`?``:t,ig:gn().add(i)})}let r=k(e);for(;r!==k(r)&&!v(A(r,`.git`));){let t=A(r,`.gitignore`);if(v(t))try{let i=await I(t,`utf-8`),a=ie(r,e);n.push({dir:``,ig:gn().add(i),ancestorPrefix:a})}catch{}r=k(r)}return n.length===0?e=>e:e=>e.filter(e=>{for(let{dir:t,ig:r,ancestorPrefix:i}of n){let n;if(n=t?e.startsWith(`${t}/`)?e.slice(t.length+1):null:i?`${i}/${e}`:e,n!==null&&r.ignores(n))return!1}return!0})},parseActorIgnore=async e=>{let t=A(e,`.actorignore`);if(!v(t))return{excludeFilter:null,forceIncludePatterns:[]};let n=(await I(t,`utf-8`)).split(`
30
+ `),r=[],i=[];for(let e of n){let t=e.trim();!t||t.startsWith(`#`)||(t.startsWith(`!`)?i.push(t.slice(1)):r.push(t))}return{excludeFilter:r.length>0?e=>{let t=gn().add(r);return e.filter(e=>!t.ignores(e))}:null,forceIncludePatterns:i}},getActorLocalFilePaths=async t=>{let n=t??e.cwd(),r=[`.git/**`,`apify_storage`,`node_modules`,`storage`,`crawlee_storage`],{excludeFilter:i,forceIncludePatterns:a}=await parseActorIgnore(n),gitIgnoreFilter=null;try{let e=Te(`git ls-files --others --ignored --exclude-standard --directory`,{cwd:n,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).split(`
31
+ `).filter(Boolean);if(e.length>0){let t=gn().add(e);gitIgnoreFilter=e=>e.filter(e=>!t.ignores(e))}}catch{gitIgnoreFilter=await getGitignoreFallbackFilter(n)}let s=await Ze([`*`,`**/**`],{ignore:r,dot:!0,expandDirectories:!1,cwd:n}),c=gitIgnoreFilter?gitIgnoreFilter(s):s;if(i&&(c=i(c)),a.length>0){let e=gn().add(a),t=s.filter(t=>e.ignores(t)),n=new Set(c);for(let e of t)n.add(e);c=[...n]}let l=s.filter(e=>e===`.actor`||e.startsWith(`.actor/`));if(l.length>0){let e=new Set(c);for(let t of l)e.add(t);c=[...e]}return c},createActZip=async(e,t,n)=>{v(e)&&await deleteFile(e);let r=_(e),i=Ve(`zip`,{zlib:{level:6}});i.pipe(r),t.forEach(e=>i.file(A(n,e),{name:e})),await i.finalize()},getLocalInput=(e,t)=>{let n=getLocalKeyValueStorePath();if(!v(A(e,n)))return;let r=C(A(e,n)).find(e=>!!e.match(inputFileRegExp(t??`INPUT`)));return r?{body:S(A(e,n,r)),contentType:yn.getType(r),fileName:r}:void 0},purgeDefaultQueue=async()=>{let e=getLocalRequestQueuePath();v(getLocalStorageDir())&&v(e)&&await rimrafPromised(e)},purgeDefaultDataset=async()=>{let e=getLocalDatasetPath();v(getLocalStorageDir())&&v(e)&&await rimrafPromised(e)},purgeDefaultKeyValueStore=async(...e)=>{let t=getLocalKeyValueStorePath();if(!v(getLocalStorageDir())||!v(t))return;let n=C(t),r=(e.length>0?e:[`INPUT`]).map(inputFileRegExp),i=[];n.forEach(e=>{r.some(t=>t.test(e))||i.push(deleteFile(A(t,e)))}),await Promise.all(i)},outputJobLog=async({job:t,timeoutMillis:n,apifyClient:r})=>{let{id:i,status:a}=t,s=r||new Be({baseUrl:e.env.APIFY_CLIENT_BASE_URL});if(de.includes(a)){if(e.env.APIFY_NO_LOGS_IN_TESTS)return;let t=await s.log(i).get();e.stderr.write(t);return}return new Promise(async t=>{let r=await s.log(i).stream();if(!r){t(`no-logs`);return}let a=null;r.on(`data`,t=>{e.env.APIFY_NO_LOGS_IN_TESTS||e.stderr.write(t.toString())}),r.once(`end`,()=>{t(`finished`),a&&clearTimeout(a)}),n&&(a=setTimeout(()=>{r.destroy(),t(`timeouts`)},n))})},checkIfStorageIsEmpty=async e=>{let t=e||me.INPUT;return(await Ze([`${getLocalStorageDir()}/**`,`!${getLocalKeyValueStorePath()}/${t}.*`,`!${getLocalKeyValueStorePath()}/${hn}${t}.*`])).length===0},validateActorName=e=>{if(!fe.REGEX.test(e))throw Error(`The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).`);if(e.length<fe.MIN_LENGTH)throw Error(`The Actor name must be at least 3 characters long.`);if(e.length>fe.MAX_LENGTH)throw Error(`The Actor name must be a maximum of 30 characters long.`)},sanitizeActorName=e=>{let t=e.replaceAll(/[^a-zA-Z0-9-]/g,`-`);return t.length<fe.MIN_LENGTH&&(t=`${t}-apify-actor`),t=t.replaceAll(/^-+/g,``).replaceAll(/-+$/g,``),t.slice(0,fe.MAX_LENGTH)},isPythonVersionSupported=e=>p(e,`^${on}`),isNodeVersionSupported=e=>u(e,f(rn)),downloadAndUnzip=async({url:e,pathTo:t})=>{let n=await httpsGet(e),r=[];n.on(`data`,e=>r.push(e)),await Ne(n),new Re(Buffer.concat(r)).extractAllTo(t,!0)};function ensureApifyDirectory(e){b(k(e),{recursive:!0})}const G=new Le(`YYYY-MM-DD [at] HH:mm:ss`),bn=new Le(`YYYY-MM-DD[
32
+ ]HH:mm:ss`),xn=new Le(`YYYY-MM-DD`),Sn=new Fe,K=new Fe({[B.Day]:{DEFAULT:`d`},[B.Hour]:{DEFAULT:`h`},[B.Minute]:{DEFAULT:`m`},[B.Month]:{DEFAULT:`M`},[B.Second]:{DEFAULT:`s`},[B.Week]:{DEFAULT:`w`},[B.Year]:{DEFAULT:`y`}});function objectGroupBy(e,t){if(`groupBy`in Object)return Object.groupBy(e,t);let n={},r=0;for(let i of e){let e=t(i,r++);n[e]||(n[e]=[]),n[e].push(i)}return n}function printJsonToStdout(e){console.log(JSON.stringify(e,null,2))}const tildify=e=>e.startsWith(le())?e.replace(le(),`~`):e;function detectShell(){let t=e.env.SHELL??``;return t.includes(`zsh`)?`zsh`:t.includes(`bash`)?`bash`:t.includes(`fish`)?`fish`:`unknown`}function shellConfigFile(t,n){switch(n){case`bash`:{let n=[A(t,`.bashrc`),A(t,`.bash_profile`)];e.env.XDG_CONFIG_HOME&&n.push(A(e.env.XDG_CONFIG_HOME,`.bashrc`),A(e.env.XDG_CONFIG_HOME,`.bash_profile`),A(e.env.XDG_CONFIG_HOME,`bashrc`),A(e.env.XDG_CONFIG_HOME,`bash_profile`));for(let e of n)if(v(e))return e;return null}case`zsh`:return A(e.env.ZDOTDIR||le(),`.zshrc`);case`fish`:return A(t,`.config`,`fish`,`config.fish`);case`unknown`:return null}}const Cn=[`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(`
33
+ `);function createAnonymousId(){return`CLI:${we()}`}async function migrateStateV0ToV1(e){if(e.version&&e.version>=1)return!1;let t=e,n=await getLocalUserInfo().catch(()=>({}));return updateTelemetryState({version:1,enabled:!0},e=>{n.id&&t.distinctId===n.id?(e.anonymousId=createAnonymousId(),e.userId=n.id):e.anonymousId=t.distinctId}),!0}async function useTelemetryState(){let e=TELEMETRY_FILE_PATH();if(!v(e)){let e=await getLocalUserInfo().catch(()=>({}));return updateTelemetryState({version:1,enabled:!0,anonymousId:createAnonymousId(),userId:e.id}),(!process.env.APIFY_CLI_DISABLE_TELEMETRY||[`false`,`0`].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))&&info({message:Cn}),useTelemetryState()}let t=JSON.parse(S(e,`utf-8`));return await migrateStateV0ToV1(t)?useTelemetryState():t}function updateTelemetryState(e,t){let n={...e};t?.(n),b(k(TELEMETRY_FILE_PATH()),{recursive:!0}),D(TELEMETRY_FILE_PATH(),JSON.stringify(n,null,` `))}async function updateUserId(e){updateTelemetryState(await useTelemetryState(),t=>{t.userId=e})}async function checkAndUpdateLastCommand(e){try{let t=await useTelemetryState(),n=Date.now(),r=t.lastCommand===e&&n-(t.lastCommandTimestamp??0)<1e4;return updateTelemetryState(t,t=>{t.lastCommand=e,t.lastCommandTimestamp=n}),r}catch{return!1}}async function updateTelemetryEnabled(e){updateTelemetryState(await useTelemetryState(),t=>{t.enabled=e})}async function useTelemetryEnabled(){if(process.env.APIFY_CLI_DISABLE_TELEMETRY&&![`false`,`0`].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))return cliDebugPrint(`telemetry`,`disabled by env variable`),!1;let e=await useTelemetryState();return cliDebugPrint(`telemetry state`,{telemetryState:e}),e.enabled}async function useTelemetryIdentifiers(){let e=await useTelemetryState();return{anonymousId:e.anonymousId,userId:e.userId}}const wn=useCLIMetadata(),Tn=wn.isBeta?`rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC`:`2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t`;async function trackEvent(e,t){let n=await useTelemetryIdentifiers(),r={anonymousId:n.anonymousId,context:{app:{name:`apify-cli`,version:wn.version,build:wn.hash},library:{name:`apify-cli`,version:wn.version},os:{name:wn.platform},userAgent:pn,channel:`server`},event:e,properties:{...t,app:`cli`},timestamp:new Date().toISOString(),userId:n.userId,writeKey:Tn};if(cliDebugPrint(`trackEvent`,r),!await useTelemetryEnabled()){cliDebugPrint(`trackEvent`,`telemetry disabled`);return}try{let e=await fetch(`https://api.segment.io/v1/track`,{method:`POST`,body:JSON.stringify(r)});if(!e.ok){cliDebugPrint(`trackEvent`,`failed to send event`,await e.text());return}cliDebugPrint(`trackEvent`,`event sent`)}catch(e){cliDebugPrint(`trackEvent`,`failed to send event`,e)}}const En=`confirm`,Dn=`no-${En}`;function stdinCheckWrapper(e,{errorMessageForStdin:t=`Please use the --${En}/--${Dn} flags to confirm the action.`}={}){return async(n,...r)=>{let{isTTY:i,hasData:a}=await useStdin(),s=n;if(at||!i&&!a){if(s.providedConfirmFromStdin===void 0)throw Error(s.errorMessageForStdin??t??`Please use the --${En}/--${Dn} flags to confirm the action.`);return s.providedConfirmFromStdin}return await e(n,...r)}}const On=stdinCheckWrapper(async({message:e,validate:t,default:n})=>await it({message:e,validate:t,default:n}),{errorMessageForStdin:`Please provide a valid input based on the command options.`});var Spider=class{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}},SpiderFileAnalyzer=class{pathname;constructor(e){this.pathname=e}getSpiders(){let e=S(this.pathname,`utf8`),t=/class\s+(\w+)/g,n=[],r=t.exec(e);for(;r;)n.push(new Spider({class_name:r[1],pathname:this.pathname})),r=t.exec(e);return n}},ScrapyProjectAnalyzer=class{pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return v(A(e,`scrapy.cfg`))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new rt,t=j(A(this.pathname,`scrapy.cfg`));if(!v(t))throw Error(`scrapy.cfg not found in "${t}".
34
+ 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 On({message:`Enter the Scrapy BOT_NAME (see settings.py):`,default:e}),n=await On({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 n==`string`?[n]:n}}getName(){return this.settings?.BOT_NAME}getAvailableSpiders(){let e=this.settings?.SPIDER_MODULES;if(!e)throw Error(`SPIDER_MODULES path not found in settings.`);let t=[];for(let n of e){let e=A(this.pathname,n.replaceAll(`.`,`/`)),r=C(e,{withFileTypes:!0});for(let n of r)n.isFile()&&n.name.endsWith(`.py`)&&n.name!==`__init__.py`&&t.push(...new SpiderFileAnalyzer(A(e,n.name)).getSpiders())}return t}};function normalizeExecutablePath(e){return e?e.startsWith(`"`)?e:re(e)&&e.includes(` `)?`"${e}"`:e:null}async function getInstallCommandSuggestion(e){let t=null;return await(await useCwdProject({cwd:e})).inspectAsync(async n=>{if(n.type===0){let[r,i,a,s]=await Promise.all([R(A(e,`yarn.lock`)).then(()=>!0).catch(()=>!1),R(A(e,`pnpm-lock.yaml`)).then(()=>!0).catch(()=>!1),R(A(e,`bun.lockb`)).then(()=>!0).catch(()=>!1),R(A(e,`bun.lock`)).then(()=>!0).catch(()=>!1)]);t=r?`yarn install`:i?`pnpm install`:a||s||n.runtime?.pmName===`bun`?`bun install`:n.runtime?.pmName===`deno`?`deno install --node-modules-dir`:`npm install`}else (n.type===1||n.type===2)&&(t=`python -m pip install -r requirements.txt`)}),t}const kn=new Map,An={node:[`--version`],deno:[`eval`,`"console.log(process.versions.node)"`],bun:[`--eval`,`"console.log(process.versions.node)"`]};async function getRuntimeVersion(t,n){try{let r=await ot(t,n,{shell:!0,windowsHide:!0,verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0});return r.stdout?r.stdout.trim().replace(/^v/,``):null}catch{return null}}async function getNpmVersion(t){let n=await ot(t,[`--version`],{shell:!0,windowsHide:!0,verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0});return n.stdout?n.stdout.trim().replace(/^v/,``):null}async function useJavaScriptRuntime(t=e.cwd()){let n=kn.get(t);if(n)return cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!0,cwd:t,runtime:n.unwrapOr(null)}),n;for(let[e,n]of Object.entries(An))try{let r=normalizeExecutablePath(await st(e)),i=await getRuntimeVersion(r,n);if(i){let n={executablePath:r,version:i};if(e===`node`){let e=normalizeExecutablePath(await st(`npm`).catch(()=>null));e&&(n.pmPath=e,n.pmVersion=await getNpmVersion(e),n.pmName=`npm`)}else n.runtimeShorthand=e,n.pmPath=r,n.pmVersion=i,n.pmName=e;return kn.set(t,nt(n)),cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!1,cwd:t,runtime:kn.get(t)?.unwrap()}),nt(n)}}catch{}return kn.set(t,H),cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!1,cwd:t,runtime:null}),H}const q=new Map;async function getPythonVersion(t){try{let n=await ot(t,[`-c`,`"import platform; print(platform.python_version())"`],{shell:!0,windowsHide:!0,verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0});return n.stdout?n.stdout.trim():null}catch{return null}}async function usePythonRuntime({cwd:t=e.cwd(),force:n=!1}={}){let r=q.get(t);if(r&&!n)return cliDebugPrint(`usePythonRuntime`,{cacheHit:!0,cwd:t,runtime:r.unwrapOr(null)}),r;let i=ue()===`win32`,a=i?[`Scripts`,`python.exe`]:[`bin`,`python3`],s;s=e.env.VIRTUAL_ENV?A(e.env.VIRTUAL_ENV,...a):A(t,`.venv`,...a),s=normalizeExecutablePath(s);try{let e=await getPythonVersion(s);if(e)return q.set(t,nt({executablePath:s,version:e})),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:q.get(t)?.unwrap()}),q.get(t)}catch{}let c=[`python3`,`python`,...i?[`python3.exe`,`python.exe`]:[]];for(let e of c)try{let n=normalizeExecutablePath(await st(e)),r=await getPythonVersion(n);if(r)return q.set(t,nt({executablePath:n,version:r})),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:q.get(t)?.unwrap()}),q.get(t)}catch{}return q.set(t,H),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:null}),H}const jn=new Map;async function useCwdProject({cwd:t=e.cwd()}={}){let n=jn.get(t);if(n)return cliDebugPrint(`useCwdProject`,{cacheHit:!0,project:n}),tt(n);let r={type:3},check=async()=>{if(await checkScrapyProject(t)){r.type=2,r.runtime=(await usePythonRuntime({cwd:t})).unwrapOr(void 0);let e=new ScrapyProjectAnalyzer(t);if(e.loadScrapyCfg(),e.configuration.hasKey(`apify`,`mainpy_location`))r.entrypoint={path:e.configuration.get(`apify`,`mainpy_location`)};else try{let e=await checkPythonProject(t);e&&(r.entrypoint={path:e})}catch{}return}let e=await checkNodeProject(t);if(!e){let e=null;try{e=await checkPythonProject(t)}catch(e){return et({message:e instanceof Error?e.message:String(e)})}if(e){r.type=1;let n=await usePythonRuntime({cwd:t});r.entrypoint={path:e},r.runtime=n.unwrapOr(void 0),await fileExists(A(A(t,e.replace(/\./g,`/`)),`__main__.py`))||(r.warnings=[`The detected Python package "${e}" is missing __main__.py. Running with "python -m" will fail without it.`]);return}}if(e){r.type=0,r.runtime=(await useJavaScriptRuntime()).unwrapOr(void 0),e.type===`file`?r.entrypoint={path:e.path}:e.type===`script`&&(r.entrypoint={script:e.script});return}return tt(r)},i=await check();return i?.isErr()?(cliDebugPrint(`useCwdProject`,{cacheHit:!1,error:i}),i):(cliDebugPrint(`useCwdProject`,{cacheHit:!1,project:r}),jn.set(t,r),tt(r))}async function checkNodeProject(e){let t=A(e,`package.json`);try{let n=await I(t,`utf-8`),r=JSON.parse(n);if(r.scripts?.start)return{type:`script`,script:`start`};if(r.main)try{return await De(j(e,r.main)),{path:j(e,r.main),type:`file`}}catch{}return{type:`unknown-entrypoint`}}catch{}let n=[A(e,`index.js`),A(e,`index.mjs`),A(e,`index.cjs`),A(e,`main.js`),A(e,`main.mjs`),A(e,`main.cjs`),A(e,`src`,`index.js`),A(e,`src`,`index.mjs`),A(e,`src`,`index.cjs`),A(e,`src`,`main.js`),A(e,`src`,`main.mjs`),A(e,`src`,`main.cjs`),A(e,`dist`,`index.js`),A(e,`dist`,`index.mjs`),A(e,`dist`,`index.cjs`),A(e,`dist`,`main.js`),A(e,`dist`,`main.mjs`),A(e,`dist`,`main.cjs`)];for(let e of n)try{return await De(e),{path:e,type:`file`}}catch{}return null}async function fileExists(e){try{return await De(e),!0}catch{return!1}}async function dirExists(e){try{return(await R(e)).isDirectory()}catch{return!1}}function isValidPythonIdentifier(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}async function hasPythonFilesInDirOrSubdirs(e){try{let t=await L(e,{withFileTypes:!0});if(t.some(e=>e.isFile()&&e.name.endsWith(`.py`)))return!0;for(let n of t){if(!n.isDirectory()||n.name.startsWith(`.`)||n.name.startsWith(`_`))continue;let t=A(e,n.name);try{let e=await L(t,{withFileTypes:!0});if(e.some(e=>e.isFile()&&e.name.endsWith(`.py`)))return!0;if(n.name===`src`){for(let n of e)if(n.isDirectory()&&!(n.name.startsWith(`.`)||n.name.startsWith(`_`)))try{if((await L(A(t,n.name),{withFileTypes:!0})).some(e=>e.isFile()&&e.name.endsWith(`.py`)))return!0}catch{}}}catch{}}return!1}catch{return!1}}async function dirHasPyFiles(e){try{return(await L(e,{withFileTypes:!0})).some(e=>e.isFile()&&e.name.endsWith(`.py`)&&e.name!==`__init__.py`)}catch{return!1}}async function findNearMissPackagesInDir(e){try{let t=await L(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory()||r.name.startsWith(`.`)||r.name.startsWith(`_`))continue;let t=isValidPythonIdentifier(r.name),i=await fileExists(A(e,r.name,`__init__.py`)),a=i||await dirHasPyFiles(A(e,r.name));t&&i||a&&n.push({name:r.name,needsRename:!t,needsInit:!i})}return n}catch{return[]}}async function findPackagesInDir(e){try{let t=await L(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let{name:t}=r;t.startsWith(`.`)||t.startsWith(`_`)||!isValidPythonIdentifier(t)||await fileExists(A(e,t,`__init__.py`))&&n.push({name:t,path:A(e,t)})}return n}catch{return[]}}async function discoverPythonPackages(e){let t=[],n=await findPackagesInDir(e);t.push(...n.map(e=>e.name));let r=A(e,`src`),i=await fileExists(A(r,`__init__.py`));if(await dirExists(r)&&!i){let e=await findPackagesInDir(r);t.push(...e.map(e=>`src.${e.name}`))}return t}async function checkPythonProject(e){let t=await discoverPythonPackages(e);if(t.length===1)return t[0];if(t.length>1){let e=t.map(e=>` - ${e}`).join(`
35
35
  `);throw Error(`Multiple Python packages found:\n${e}\n\nApify CLI cannot determine which package to run.
36
36
  Please specify the package using the --entrypoint flag, e.g.:
37
- apify run --entrypoint <package_name>`)}let n=await findNearMissPackagesInDir(e),r=k(e,`src`),i=!await fileExists(k(r,`__init__.py`))&&await dirExists(r)?await findNearMissPackagesInDir(r):[],a=[...n.map(e=>({...e,prefix:``})),...i.map(e=>({...e,prefix:`src/`}))];if(a.length>0){let e=a.map(({name:e,prefix:t,needsRename:n,needsInit:r})=>{let i=[];return n&&i.push(`rename to "${t}${e.replace(/[^a-zA-Z0-9_]/g,`_`)}/"`),r&&i.push(`add __init__.py`),` - "${t}${e}/" → ${i.join(` and `)}`}).join(`
37
+ apify run --entrypoint <package_name>`)}let n=await findNearMissPackagesInDir(e),r=A(e,`src`),i=!await fileExists(A(r,`__init__.py`))&&await dirExists(r)?await findNearMissPackagesInDir(r):[],a=[...n.map(e=>({...e,prefix:``})),...i.map(e=>({...e,prefix:`src/`}))];if(a.length>0){let e=a.map(({name:e,prefix:t,needsRename:n,needsInit:r})=>{let i=[];return n&&i.push(`rename to "${t}${e.replace(/[^a-zA-Z0-9_]/g,`_`)}/"`),r&&i.push(`add __init__.py`),` - "${t}${e}/" → ${i.join(` and `)}`}).join(`
38
38
  `);throw Error(`Found directories that appear to be Python packages but have issues:\n${e}\n\nA valid Python package requires a directory with a valid identifier name (letters, numbers, underscores) and an __init__.py file.`)}if(await hasPythonFilesInDirOrSubdirs(e))throw Error(`No Python package found. Found Python files, but no valid package structure detected.
39
39
  A Python package requires:
40
40
  - A directory with a valid Python identifier name (letters, numbers, underscores)
@@ -48,24 +48,24 @@ Common package structures:
48
48
  src/
49
49
  my_package/
50
50
  __init__.py
51
- main.py`);return null}async function checkScrapyProject(e){return ScrapyProjectAnalyzer.isApplicable(e)}function camelCaseString(e){return e.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}function kebabCaseString(e){return e.replace(/[\s_]+/g,`-`)}function camelCaseToKebabCase(e){return e.replace(/([A-Z])/g,`-$1`).toLowerCase()}const Mn={type:`boolean`,multiple:!1,short:`h`},Nn={type:`boolean`,multiple:!1},Pn={type:`string`,multiple:!1},Fn=`user-agent`,In=new Set([`apify`]);function sanitizeUserAgentValue(e){if(typeof e!=`string`)return;let t=e.replace(/[\u0000-\u001f\u007f]/g,``).trim();if(t)return t.length>256?t.slice(0,256):t}function resolveUserAgentForTelemetry(e,t){return sanitizeUserAgentValue(e)??sanitizeUserAgentValue(t)}const J=new Map,Ln=[`init`,`run`,`push`,`actors push`,`pull`,`actors pull`,`call`,`actors call`,`actors start`];var ApifyCommand=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,n,r){this.entrypoint=e,this.commandString=t,this.aliasUsed=n,this.subcommandAliasUsed=r;let i=useCLIMetadata();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 a=detectCi();this.telemetryData.aiAgent=detectAiAgent(),this.telemetryData.isCi=a.isCi,this.telemetryData.ciProvider=a.ciProvider,this.telemetryData.isInteractive=detectIsInteractive()}get ctor(){return this.constructor}pluralString(e,t,n){return e===1?t:n}static printHelp(){console.log(renderHelpForCommand(this)),e.exit(0)}printHelp(){return this.ctor.printHelp()}async _run(t){let n=Date.now(),{values:r,positionals:i,tokens:a}=t;if(r.help&&this.ctor.printHelp(),In.has(this.entrypoint)){let t=r[Fn],n=resolveUserAgentForTelemetry(typeof t==`string`?t:void 0,e.env.APIFY_CLI_USER_AGENT);n&&(this.telemetryData.userAgent=n)}this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof r.json==`boolean`?this.flags.json=r.json:this.flags.json=!1);let s=new Map;if(this.ctor.args){let e=0;for(let[t,n]of Object.entries(this.ctor.args)){if(typeof n==`string`)throw RangeError(`Do not provide the string for the json arg! It is a type level assertion!`);let r=camelCaseString(t),a=i[e++];if(a)switch(n.argTag){default:this.args[r]=String(a),a===`-`&&n.stdin&&(this.args[r]=this._handleStdin(n.stdin)),n.catchAll&&(this.args[r]=i.slice(e-1).join(` `));break}else n.required&&s.set(t,n)}}if(s.size){e.exitCode=1,this._printMissingRequiredArgs(s);return}this._parseFlags(r,a);try{await this.run()}catch(t){error({message:t.message}),e.exitCode||=1}finally{!this.telemetryData.actorLanguage&&Ln.includes(this.commandString)&&(await useCwdProject()).inspect(e=>{e.type===0?(this.telemetryData.actorLanguage=`javascript`,this.telemetryData.actorRuntime=e.runtime.runtimeShorthand||`node`,this.telemetryData.actorRuntimeVersion=e.runtime.version):(e.type===1||e.type===2)&&(this.telemetryData.actorLanguage=`python`,this.telemetryData.actorRuntime=`python`,this.telemetryData.actorRuntimeVersion=e.runtime.version)}),this.skipTelemetry||(this.telemetryData.flagsUsed=Object.keys(this.flags),this.telemetryData.exitCode=typeof e.exitCode==`number`?e.exitCode:0,this.telemetryData.durationMs=Date.now()-n,this.telemetryData.wasRetried=await checkAndUpdateLastCommand(this.commandString),await trackEvent(`cli_command_${this.commandString.replaceAll(` `,`_`).toLowerCase()}`,this.telemetryData))}}_userFlagNameToRegisteredName(e,t){let n=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),r=n;n.startsWith(`no-`)&&(r=n.slice(3));let i=new Set;for(let e of t.aliases??[])i.add(kebabCaseString(camelCaseToKebabCase(e)).toLowerCase());return{baseFlagName:r,rawBaseFlagName:n,allMatchers:[r,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase();return t.startsWith(`no-`)&&(t=t.slice(3)),t}_parseFlags(e,n){if(!this.ctor.flags)return;let r=new Map,i;for(let[a,s]of Object.entries(this.ctor.flags)){if(typeof s==`string`)throw RangeError(`Do not provide the string for the json arg! It is a type level assertion!`);let{allMatchers:c,baseFlagName:l,rawBaseFlagName:u}=this._userFlagNameToRegisteredName(a,s),f=camelCaseString(u),p=n.some(e=>e.kind===`option`&&e.name===l);if(s.exclusive?.length){let e=r.get(l)??new Set;for(let t of s.exclusive)e.add(this._commandFlagKeyToKebabCaseRegisteredName(t));r.set(l,e);for(let e of s.exclusive){let t=this._commandFlagKeyToKebabCaseRegisteredName(e),n=r.get(t)??new Set;n.add(l),r.set(t,n)}}let m=c.filter(t=>e[t]);if(m.length>1)throw new H({code:3,command:this.ctor,metadata:{flag:l}});let h=e[m[0]];if(!h&&s.required)throw new H({code:6,command:this.ctor,metadata:{flag:l,matcher:m[0]}});if(Array.isArray(h)){if(h.length>1)throw new H({code:3,command:this.ctor,metadata:{flag:l}});h=h[0]}if(p&&typeof h==`string`&&h.startsWith(`=`)&&(h=h.slice(1)),h!==void 0)switch(s.flagTag){case`boolean`:this.flags[f]=u.startsWith(`no-`)?!h:h;break;case`integer`:{let e=Number(h);if(Number.isNaN(e)||!Number.isInteger(e))throw new H({code:4,command:this.ctor,metadata:{flag:l,value:String(h)}});this.flags[f]=e;break}default:if(this.flags[f]=h,h===`-`&&s.stdin){if(i)throw new H({code:8,command:this.ctor,metadata:{firstUse:i,secondUse:l}});i=l,this.flags[f]=this._handleStdin(s.stdin)}break}else s.hasDefault!==void 0&&(this.flags[f]=s.hasDefault);if(this.flags[f]&&s.choices&&!s.choices.includes(this.flags[f]))throw new H({code:5,command:this.ctor,metadata:{flag:l,choices:s.choices.map(e=>t.white.bold(e)).join(`, `)}});if(this.flags[f]==null&&(s.required||h!=null))throw new H({code:6,command:this.ctor,metadata:{flag:l,matcher:m[0],providedButReceivedNoValue:!!h}})}let a=[];for(let[t,n]of r)if(e[t]!=null)for(let r of n){if(e[r]==null)continue;let n=e[t][0],i=e[r][0],flagRepresentation=(e,t)=>typeof t==`boolean`?t?`--${e}`:`--no-${e}`:`--${e}=${t}`;a.push([flagRepresentation(t,n),flagRepresentation(r,i)]);break}if(a.length)throw new H({code:7,command:this.ctor,metadata:{flagPairs:a}})}_printMissingRequiredArgs(e){let a;try{a=selectiveRenderHelpForCommand(this.ctor,{showUsageString:!0})}catch{}let s=r([...e.keys()].join(`
51
+ main.py`);return null}async function checkScrapyProject(e){return ScrapyProjectAnalyzer.isApplicable(e)}function camelCaseString(e){return e.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}function kebabCaseString(e){return e.replace(/[\s_]+/g,`-`)}function camelCaseToKebabCase(e){return e.replace(/([A-Z])/g,`-$1`).toLowerCase()}const Mn={type:`boolean`,multiple:!1,short:`h`},Nn={type:`boolean`,multiple:!1},Pn={type:`string`,multiple:!1},Fn=`user-agent`,In=new Set([`apify`]);function sanitizeUserAgentValue(e){if(typeof e!=`string`)return;let t=e.replace(/[\u0000-\u001f\u007f]/g,``).trim();if(t)return t.length>256?t.slice(0,256):t}function resolveUserAgentForTelemetry(e,t){return sanitizeUserAgentValue(e)??sanitizeUserAgentValue(t)}const J=new Map,Ln=[`init`,`run`,`push`,`actors push`,`pull`,`actors pull`,`call`,`actors call`,`actors start`];var ApifyCommand=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,n,r){this.entrypoint=e,this.commandString=t,this.aliasUsed=n,this.subcommandAliasUsed=r;let i=useCLIMetadata();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 a=detectCi();this.telemetryData.aiAgent=detectAiAgent(),this.telemetryData.isCi=a.isCi,this.telemetryData.ciProvider=a.ciProvider,this.telemetryData.isInteractive=detectIsInteractive()}get ctor(){return this.constructor}pluralString(e,t,n){return e===1?t:n}static printHelp(){console.log(renderHelpForCommand(this)),e.exit(0)}printHelp(){return this.ctor.printHelp()}async _run(t){let n=Date.now(),{values:r,positionals:i,tokens:a}=t;if(r.help&&this.ctor.printHelp(),In.has(this.entrypoint)){let t=r[Fn],n=resolveUserAgentForTelemetry(typeof t==`string`?t:void 0,e.env.APIFY_CLI_USER_AGENT);n&&(this.telemetryData.userAgent=n)}this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof r.json==`boolean`?this.flags.json=r.json:this.flags.json=!1);let s=new Map;if(this.ctor.args){let e=0;for(let[t,n]of Object.entries(this.ctor.args)){if(typeof n==`string`)throw RangeError(`Do not provide the string for the json arg! It is a type level assertion!`);let r=camelCaseString(t),a=i[e++];if(a)switch(n.argTag){default:this.args[r]=String(a),a===`-`&&n.stdin&&(this.args[r]=this._handleStdin(n.stdin)),n.catchAll&&(this.args[r]=i.slice(e-1).join(` `));break}else n.required&&s.set(t,n)}}if(s.size){e.exitCode=1,this._printMissingRequiredArgs(s);return}this._parseFlags(r,a);try{await this.run()}catch(t){error({message:t.message}),e.exitCode||=1}finally{!this.telemetryData.actorLanguage&&Ln.includes(this.commandString)&&(await useCwdProject()).inspect(e=>{e.type===0?(this.telemetryData.actorLanguage=`javascript`,this.telemetryData.actorRuntime=e.runtime.runtimeShorthand||`node`,this.telemetryData.actorRuntimeVersion=e.runtime.version):(e.type===1||e.type===2)&&(this.telemetryData.actorLanguage=`python`,this.telemetryData.actorRuntime=`python`,this.telemetryData.actorRuntimeVersion=e.runtime.version)}),this.skipTelemetry||(this.telemetryData.flagsUsed=Object.keys(this.flags),this.telemetryData.exitCode=typeof e.exitCode==`number`?e.exitCode:0,this.telemetryData.durationMs=Date.now()-n,this.telemetryData.wasRetried=await checkAndUpdateLastCommand(this.commandString),await trackEvent(`cli_command_${this.commandString.replaceAll(` `,`_`).toLowerCase()}`,this.telemetryData))}}_userFlagNameToRegisteredName(e,t){let n=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),r=n;n.startsWith(`no-`)&&(r=n.slice(3));let i=new Set;for(let e of t.aliases??[])i.add(kebabCaseString(camelCaseToKebabCase(e)).toLowerCase());return{baseFlagName:r,rawBaseFlagName:n,allMatchers:[r,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase();return t.startsWith(`no-`)&&(t=t.slice(3)),t}_parseFlags(e,n){if(!this.ctor.flags)return;let r=new Map,i;for(let[a,s]of Object.entries(this.ctor.flags)){if(typeof s==`string`)throw RangeError(`Do not provide the string for the json arg! It is a type level assertion!`);let{allMatchers:c,baseFlagName:l,rawBaseFlagName:u}=this._userFlagNameToRegisteredName(a,s),f=camelCaseString(u),p=n.some(e=>e.kind===`option`&&e.name===l);if(s.exclusive?.length){let e=r.get(l)??new Set;for(let t of s.exclusive)e.add(this._commandFlagKeyToKebabCaseRegisteredName(t));r.set(l,e);for(let e of s.exclusive){let t=this._commandFlagKeyToKebabCaseRegisteredName(e),n=r.get(t)??new Set;n.add(l),r.set(t,n)}}let m=c.filter(t=>e[t]);if(m.length>1)throw new U({code:3,command:this.ctor,metadata:{flag:l}});let h=e[m[0]];if(!h&&s.required)throw new U({code:6,command:this.ctor,metadata:{flag:l,matcher:m[0]}});if(Array.isArray(h)){if(h.length>1)throw new U({code:3,command:this.ctor,metadata:{flag:l}});h=h[0]}if(p&&typeof h==`string`&&h.startsWith(`=`)&&(h=h.slice(1)),h!==void 0)switch(s.flagTag){case`boolean`:this.flags[f]=u.startsWith(`no-`)?!h:h;break;case`integer`:{let e=Number(h);if(Number.isNaN(e)||!Number.isInteger(e))throw new U({code:4,command:this.ctor,metadata:{flag:l,value:String(h)}});this.flags[f]=e;break}default:if(this.flags[f]=h,h===`-`&&s.stdin){if(i)throw new U({code:8,command:this.ctor,metadata:{firstUse:i,secondUse:l}});i=l,this.flags[f]=this._handleStdin(s.stdin)}break}else s.hasDefault!==void 0&&(this.flags[f]=s.hasDefault);if(this.flags[f]&&s.choices&&!s.choices.includes(this.flags[f]))throw new U({code:5,command:this.ctor,metadata:{flag:l,choices:s.choices.map(e=>t.white.bold(e)).join(`, `)}});if(this.flags[f]==null&&(s.required||h!=null))throw new U({code:6,command:this.ctor,metadata:{flag:l,matcher:m[0],providedButReceivedNoValue:!!h}})}let a=[];for(let[t,n]of r)if(e[t]!=null)for(let r of n){if(e[r]==null)continue;let n=e[t][0],i=e[r][0],flagRepresentation=(e,t)=>typeof t==`boolean`?t?`--${e}`:`--no-${e}`:`--${e}=${t}`;a.push([flagRepresentation(t,n),flagRepresentation(r,i)]);break}if(a.length)throw new U({code:7,command:this.ctor,metadata:{flagPairs:a}})}_printMissingRequiredArgs(e){let a;try{a=selectiveRenderHelpForCommand(this.ctor,{showUsageString:!0})}catch{}let s=r([...e.keys()].join(`
52
52
  `)),c=[];for(let[r,a]of e){let e=n(i(`${r.padEnd(s)} ${a.description}`,getMaxLineWidth()-s-2),s+2+2).trim();c.push(` ${t.red(`>`)} ${e}`)}let l=[`Missing ${e.size} required ${this.pluralString(e.size,`argument`,`arguments`)}:`,...c,t.gray(` See more help with --help`)];a&&l.push(``,a),error({message:l.join(`
53
- `)})}_handleStdin(e){switch(e){case 2:return(fn?.toString(`utf8`)??``).trim();default:return fn}}_buildParseArgsOption(){let e={help:Mn};In.has(this.entrypoint)&&(e[Fn]=Pn);let t={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:e};if(this.ctor.flags)for(let[e,n]of Object.entries(this.ctor.flags)){if(typeof n==`string`)throw RangeError(`Do not provide the string for the json flag! It is a type level assertion!`);if(e.toLowerCase()===`json`)continue;let r=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase();r.startsWith(`no-`)&&(r=r.slice(3));let i=n.builder(r);for(let{flagName:e,option:n}of i)t.options[e]=n}return this.ctor.enableJsonFlag&&(t.options.json=Nn),t}static registerCommand(e){if(registerCommandForHelpGeneration(e,this),J.set(this.name,this),this.aliases?.length)for(let e of this.aliases)J.set(e,this);if(this.hiddenAliases?.length)for(let e of this.hiddenAliases)J.set(e,this);if(this.subcommands?.length)for(let e of this.subcommands){if(J.set(`${this.name} ${e.name}`,e),this.aliases?.length)for(let t of this.aliases)J.set(`${t} ${e.name}`,e);if(this.hiddenAliases?.length)for(let t of this.hiddenAliases)J.set(`${t} ${e.name}`,e);if(e.aliases?.length)for(let t of e.aliases){if(J.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)J.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)J.set(`${n} ${t}`,e)}if(e.hiddenAliases?.length)for(let t of e.hiddenAliases){if(J.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)J.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)J.set(`${n} ${t}`,e)}}}};async function internalRunCommand(e,t,n){let r={positionals:[],values:{},tokens:[]},i=0;for(let[e,t]of Object.entries(n)){let[n,a]=e.split(`_`);if(n===`args`)r.positionals[i++]=t;else{let e=kebabCaseString(camelCaseToKebabCase(a)).toLowerCase();e.startsWith(`no-`)?r.values[e.slice(3)]=!t:r.values[e]=t}}let a=new t(e,t.name,t.name);a.skipTelemetry=!0,await a._run(r)}const Y={string:stringFlag,boolean:booleanFlag,integer:integerFlag};function YesFlag(e=`Automatic yes to prompts; assume "yes" as answer to all prompts.`){return{yes:Y.boolean({char:`y`,description:e,default:!1})}}function stringFlag(e){return{flagTag:`string`,builder:t=>{let n=new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`string`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`string`,multiple:!0}});return r},choices:e.choices,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??2,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function booleanFlag(e){return{flagTag:`boolean`,builder:t=>{let n=new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`boolean`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`boolean`,multiple:!0}});return r},choices:null,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??1,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function integerFlag(e){return{flagTag:`integer`,builder:t=>{let n=new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`string`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`string`,multiple:!0}});return r},choices:null,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??1,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function getBooleanValue(e,t){let n=t!==!1;return/^(y|yes)/i.test(e)?n=!0:/^(n|no)/i.test(e)&&(n=!1),n}function boolToString(e){return e?`Yes`:`No`}var Rn=ft((e,t)=>{let n=boolToString,[r,i]=_t(`idle`),[a,s]=_t(``),c=mt(),l=gt({status:r,theme:c});ht((r,c)=>{if(pt(r)){let r=getBooleanValue(a,e.default);s(n(r)),i(`done`),t(r);return}if(r.name===`tab`){let t=boolToString(!getBooleanValue(a,e.default));c.clearLine(0),c.write(t),s(t);return}if(r.name===`y`||r.name===`n`){let a=getBooleanValue(r.name,e.default);s(n(a)),i(`done`),t(a);return}c.clearLine(0),c.write(a),s(c.line)});let u=a,f=``;return r===`done`?u=c.style.answer(a):f=` ${c.style.defaultAnswer(e.default===!1?`y/N`:`Y/n`)}`,`${l} ${c.style.message(e.message,r)}${f} ${u}`});const X=stdinCheckWrapper(async({message:e,default:t})=>await Rn({message:e,default:t})),getDeprecatedLocalConfigPath=e=>k(e,`apify.json`),zn=new Map;async function useActorConfig({cwd:t=e.cwd(),migrateConfig:n=!0,warnAboutOldConfig:r=!0}={cwd:e.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let i=zn.get(t);if(i)return cliDebugPrint(`useActorConfig`,{cacheHit:!0,config:i}),rt(i);let a=getLocalConfigPath(t),s=getDeprecatedLocalConfigPath(t),c,l;try{c=getJsonFileContent(a)}catch(e){return nt({message:`Failed to read local config at path: '${a}':`,cause:e,exists:!1,config:{}})}try{l=getJsonFileContent(s)}catch(e){return nt({message:`Failed to read local config at path: '${s}':`,cause:e,exists:!1,config:{}})}if(c&&l&&r&&await handleBothConfigVersionsFound(s),!c&&!l)return zn.set(t,{exists:!1,migrated:!1,config:{}}),rt({exists:!1,migrated:!1,config:{}});let u=!1;if(!c&&l&&n){let e=await handleMigrationFlow(l,s,a);if(e.isErr())return nt(e.unwrapErr());c=e.unwrap(),u=!0}return zn.set(t,{exists:!0,migrated:u,config:c||l||{}}),cliDebugPrint(`useActorConfig`,{cacheHit:!1,config:zn.get(t)}),rt({exists:!0,migrated:u,config:c||l||{}})}async function handleBothConfigVersionsFound(e){if(!await X({message:`The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Since we have found both files in your Actor directory, "apify.json" will be renamed to "apify.json.deprecated". Going forward, all commands will use ".actor/actor.json". You can read about the differences between the old and the new config at https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md. Do you want to continue?`})){warning({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 Ae(e,`${e}.deprecated`),info({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(e){e instanceof Error?error({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${e.message||e}`}):error({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${a(e,{showHidden:!1})}`})}}const Bn=[`name`,`version`,`buildTag`];async function handleMigrationFlow(e,t,n){let r={...e};if(typeof r.version==`object`&&(r=updateLocalConfigStructure(r)),r={actorSpecification:1,environmentVariables:e?.env||void 0,...Bn.reduce((t,n)=>(t[n]=e[n],t),{})},!await X({message:`The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Your "apify.json" file will be automatically updated to the new format under ".actor/actor.json". The original file will be renamed by adding the ".deprecated" suffix. Do you want to continue?`}))return nt({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:r});try{await P(O(n),{recursive:!0}),await R(n,JSON.stringify(r,null,` `))}catch(e){let t=e;return nt({message:`Failed to write the new "actor.json" file to path: '${n}'.\n ${t.message||t}`,exists:!0,config:r})}try{await Ae(t,`${t}.deprecated`)}catch(e){let t=e;warning({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${t.message||t}`})}return info({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.`}),rt(r)}function updateLocalConfigStructure(e){let t={name:e.name,template:e.template,version:e.version.versionNumber,buildTag:e.version.buildTag,env:null};if(e.version.envVars?.length){let n={};e.version.envVars.forEach(e=>{e.name&&e.value&&(n[e.name]=e.value)}),t.env=n}return t}const Vn=k(getLocalKeyValueStorePath(`default`),`INPUT.json`);var ActorCalculateMemoryCommand=class extends ApifyCommand{static name=`calculate-memory`;static description=`Calculates the Actor’s 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:Y.string({description:`Path to the input JSON file used for the calculation.`,required:!1,default:Vn}),defaultMemoryMbytes:Y.string({description:`Memory-calculation expression (in MB). If omitted, the value is loaded from the actor.json file.`,required:!1}),build:Y.string({description:`Actor build version or build tag to evaluate the expression with.`,required:!1}),timeoutSecs:Y.integer({description:`Maximum run timeout, in seconds.`,required:!1}),maxItems:Y.integer({description:`Maximum number of items Actor can output.`,required:!1}),maxTotalChargeUsd:Y.integer({description:`Maximum total charge in USD.`,required:!1})};async run(){let{input:t,memoryExpression:n,minMemory:r,maxMemory:i,runOptions:a}=await this.prepareMemoryArguments();if(!n)throw Error(`No memory-calculation expression found. Provide it via the --default-memory-mbytes flag or define defaultMemoryMbytes in actor.json.`);let s=getJsonFileContent(A(e.cwd(),t))??{};info({message:`Evaluating memory expression: ${n}`});try{let e=await ut(n,{input:s,runOptions:a});success({message:`Calculated memory: ${Math.min(Math.max(e,r),i)} MB`,stdout:!0})}catch(e){error({message:`Memory calculation failed: ${e.message}`})}}async prepareMemoryArguments(){let{input:e,defaultMemoryMbytes:t,...n}=this.flags,r=t,i=0,a=1/0;return r||({defaultMemoryMbytes:r,minMemoryMbytes:i=i,maxMemoryMbytes:a=a}=await this.getExpressionFromConfig()),{memoryExpression:r,minMemory:i,maxMemory:a,input:e,runOptions:n}}async getExpressionFromConfig(){let t=await useActorConfig({cwd:e.cwd()});if(t.isErr()){let{message:n,cause:r}=t.unwrapErr();return error({message:`${n}${r?`\n ${r.message}`:``}`}),e.exitCode=5,{}}let{config:n}=t.unwrap();return{defaultMemoryMbytes:n?.defaultMemoryMbytes?.toString(),minMemoryMbytes:n?.minMemoryMbytes,maxMemoryMbytes:n?.maxMemoryMbytes}}};const Hn={KEY_VALUE_STORE:`KEY_VALUE_STORE`,DATASET:`DATASET`,REQUEST_QUEUE:`REQUEST_QUEUE`},getApifyTokenFromEnvOrAuthFile=async()=>{let t=e.env[N.TOKEN];if(t)return t;let n=await getLocalUserInfo();if(!n||!n.token)throw Error(`Apify token is not set. Please set it using the environment variable APIFY_TOKEN or apify login command.`);return n.token},getApifyStorageClient=async(t={},n=Reflect.has(e.env,N.IS_AT_HOME))=>{let r=getLocalStorageDir();return r&&!n?new vt({localDataDirectory:r,...t}):new He({...getApifyClientOptions(await getApifyTokenFromEnvOrAuthFile()),...t})},getDefaultStorageId=t=>{let n=j[`DEFAULT_${t}_ID`];return e.env[n]||ge[n]},outputRecordFromDefaultStore=async t=>{let n=await getApifyStorageClient(),r=getDefaultStorageId(Hn.KEY_VALUE_STORE),i=await n.keyValueStore(r).getRecord(t,{stream:!0});i&&await Fe(i.value,e.stdout,{end:!1})},outputInputFromDefaultStore=async()=>outputRecordFromDefaultStore(e.env[j.INPUT_KEY]||he.INPUT);function stringArg(e){return{argTag:`string`,required:e.required??!1,stdin:e.stdin??1,description:e.description,aliases:e.aliases,catchAll:e.catchAll??!1}}const Z={string:stringArg};var ActorChargeCommand=class extends ApifyCommand{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:Z.string({description:`Name of the event to charge for.`,required:!0})};static flags={count:Y.integer({description:`Number of events to charge.`,required:!1,default:1}),"idempotency-key":Y.string({description:`Idempotency key for the charge request.`,required:!1}),"test-pay-per-event":Y.boolean({description:`Test pay-per-event charging without actually charging.`,required:!1,default:!1})};async run(){let{eventName:e}=this.args,{count:t,testPayPerEvent:n,idempotencyKey:r}=this.flags;if(!process.env.APIFY_IS_AT_HOME){info({message:`No platform detected: would charge ${t} events of type "${e}" with idempotency key "${r??`not-provided`}".`,stdout:!0});return}if(n){info({message:`PPE test mode: would charge ${t} events of type "${e}" with idempotency key "${r??`not-provided`}".`,stdout:!0});return}let i=await getLoggedClient(await getApifyTokenFromEnvOrAuthFile());if(!i)throw Error(`Apify token is not set. Please set it using the environment variable APIFY_TOKEN.`);let a=process.env[N.ACTOR_RUN_ID];if(!a)throw Error(`Charge command must be executed in a running Actor. Run ID not found.`);if((await i.run(a).get())?.pricingInfo?.pricingModel!==`PAY_PER_EVENT`)throw Error(`Charge command can only be used with pay-per-event pricing model.`);info({message:`Charging ${t} events of type "${e}" with idempotency key "${r??`not-provided`}" (runId: ${a}).`,stdout:!0}),await i.run(a).charge({eventName:e,count:t,idempotencyKey:r})}};const Un=[`.actor/INPUT_SCHEMA.json`,`./INPUT_SCHEMA.json`,`.actor/input_schema.json`,`./input_schema.json`],readInputSchema=async({forcePath:e,cwd:t,throwOnMissing:n=!1})=>{if(e)return{inputSchema:getJsonFileContent(e),inputSchemaPath:e};let r=getLocalConfig(t);if(typeof r?.input==`object`&&r.input!==null)return{inputSchema:r.input,inputSchemaPath:null};if(typeof r?.input==`string`){let e=k(t,rn,r.input),i=getJsonFileContent(e);if(!i){if(n)throw Error(`Input schema file not found at ${e} (referenced in '${U}').`);return warning({message:`Input schema file not found at ${e} (referenced in '${U}').`}),{inputSchema:null,inputSchemaPath:e}}return{inputSchema:i,inputSchemaPath:e}}for(let e of Un){let n=k(t,e);if(v(n))return{inputSchema:getJsonFileContent(n),inputSchemaPath:n}}return{inputSchema:null,inputSchemaPath:k(t,Un[0])}},readAndValidateInputSchema=async({forcePath:e,cwd:t,getMessage:n})=>{let{inputSchema:r,inputSchemaPath:i}=await readInputSchema({forcePath:e,cwd:t});if(!r)throw Error(`Input schema has not been found at ${i}.`);return info({message:n(i)}),bt(new _n({strict:!1}),r),{inputSchema:r,inputSchemaPath:i}},readStorageSchema=({cwd:e,key:t,label:n,getRef:r,throwOnMissing:i=!1})=>{let a=getLocalConfig(e),s=r?r(a):a?.storages?.[t];if(typeof s==`object`&&s)return{schema:s,schemaPath:null};if(typeof s==`string`){let t=k(e,rn,s),r=getJsonFileContent(t);if(!r){if(i)throw Error(`${n} schema file not found at ${t} (referenced in '${U}').`);return warning({message:`${n} schema file not found at ${t} (referenced in '${U}').`}),null}return{schema:r,schemaPath:t}}return null},readDatasetSchema=({cwd:e})=>{let t=readStorageSchema({cwd:e,key:`dataset`,label:`Dataset`});return t?{datasetSchema:t.schema,datasetSchemaPath:t.schemaPath}:null},readOutputSchema=({cwd:e})=>{let t=readStorageSchema({cwd:e,key:`output`,label:`Output`,getRef:e=>e?.output});return t?{outputSchema:t.schema,outputSchemaPath:t.schemaPath}:null},createPrefilledInputFileFromInputSchema=async e=>{let t={};try{let{inputSchema:n}=await readInputSchema({cwd:e});n&&(bt(new _n({strict:!1}),n),t=Object.entries(n.properties).reduce((e,[t,n])=>(e[t]=n.type===`boolean`||n.editor===`hidden`?n.default:n.prefill,e),{}))}catch(e){warning({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${e.message}`})}finally{E(k(e,getLocalKeyValueStorePath(),`${he.INPUT}.json`),JSON.stringify(t,null,` `))}},getDefaultsFromInputSchema=e=>{let t={};for(let[n,r]of Object.entries(e.properties))r.default!==void 0&&(t[n]=r.default);return t};function formatSchemaValidationErrors(e,t){return`${t} schema is not valid:\n${e.map(e=>{let t=e.instancePath?` at ${e.instancePath}`:``;return` - ${e.message}${t}`}).join(`
54
- `)}`}function validateDatasetSchema(e){let t=St();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Dataset`))}function validateOutputSchema(e){let t=wt();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Output`))}function validateKvsSchema(e){let t=Ct();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Key-Value Store`))}const getAjvValidator=(e,t)=>{let n=V(e);n.required=[];for(let[t,r]of Object.entries(e.properties)){let i=e.required?.includes(t),a=r.default!==void 0;i&&!a&&(n.required.push(t),r.type===`array`&&(r.minItems=Math.max(1,r.minItems||0)))}return delete n.$schema,t.compile(n)};function makePropertiesRequired(e){let t=V(e);if(!t.properties||typeof t.properties!=`object`)return t;let n=t.properties,r=new Set(Array.isArray(t.required)?t.required:[]);for(let[e,t]of Object.entries(n))t.default!==void 0&&r.add(e),t.type===`object`&&t.properties&&(n[e]=makePropertiesRequired(t));return t.required=Array.from(r),t}function clearAllRequired(e){let t=V(e);if(delete t.required,t.properties&&typeof t.properties==`object`){let e=t.properties;for(let[t,n]of Object.entries(e))n.type===`object`&&n.properties&&(e[t]=clearAllRequired(n))}return t}function stripTitles(e){let t=V(e);if(delete t.title,t.properties&&typeof t.properties==`object`){let e=t.properties;for(let[t,n]of Object.entries(e))n&&typeof n==`object`&&(e[t]=stripTitles(n))}t.items&&typeof t.items==`object`&&(t.items=stripTitles(t.items));for(let e of[`allOf`,`anyOf`,`oneOf`])Array.isArray(t[e])&&(t[e]=t[e].map(e=>e&&typeof e==`object`?stripTitles(e):e));for(let e of[`definitions`,`$defs`])if(t[e]&&typeof t[e]==`object`&&!Array.isArray(t[e])){let n=t[e];for(let[e,t]of Object.entries(n))t&&typeof t==`object`&&(n[e]=stripTitles(t))}t.additionalProperties&&typeof t.additionalProperties==`object`&&(t.additionalProperties=stripTitles(t.additionalProperties));for(let e of[`if`,`then`,`else`,`not`])t[e]&&typeof t[e]==`object`&&(t[e]=stripTitles(t[e]));if(t.patternProperties&&typeof t.patternProperties==`object`&&!Array.isArray(t.patternProperties)){let e=t.patternProperties;for(let[t,n]of Object.entries(e))n&&typeof n==`object`&&(e[t]=stripTitles(n))}return t}function prepareFieldsSchemaForCompilation(e){let t=e.fields;if(!t||typeof t!=`object`||!t.properties||typeof t.properties!=`object`)return null;let n=V(t);return n.type||=`object`,n}function prepareOutputSchemaForCompilation(e){let t=e.properties;if(!t||typeof t!=`object`||Object.keys(t).length===0)return null;let n=V(t);for(let e of Object.values(n))e&&typeof e==`object`&&delete e.template;let r={type:e.type||`object`,properties:n};return Array.isArray(e.required)&&(r.required=[...e.required]),r}function prepareKvsCollectionsForCompilation(e){let t=e.collections;if(!t||typeof t!=`object`)return[];let n=[];for(let[e,r]of Object.entries(t)){if(!r||typeof r!=`object`)continue;let t=r.jsonSchema;if(!t||typeof t!=`object`||Object.keys(t).length===0)continue;let i=V(t);i.type||=`object`,n.push({name:e,schema:i})}return n}var ActorGenerateSchemaTypesCommand=class extends ApifyCommand{static name=`generate-schema-types`;static hiddenAliases=[`generate-types`];static description=`Generate TypeScript types from Actor schemas.
53
+ `)})}_handleStdin(e){switch(e){case 2:return(dn?.toString(`utf8`)??``).trim();default:return dn}}_buildParseArgsOption(){let e={help:Mn};In.has(this.entrypoint)&&(e[Fn]=Pn);let t={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:e};if(this.ctor.flags)for(let[e,n]of Object.entries(this.ctor.flags)){if(typeof n==`string`)throw RangeError(`Do not provide the string for the json flag! It is a type level assertion!`);if(e.toLowerCase()===`json`)continue;let r=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase();r.startsWith(`no-`)&&(r=r.slice(3));let i=n.builder(r);for(let{flagName:e,option:n}of i)t.options[e]=n}return this.ctor.enableJsonFlag&&(t.options.json=Nn),t}static registerCommand(e){if(registerCommandForHelpGeneration(e,this),J.set(this.name,this),this.aliases?.length)for(let e of this.aliases)J.set(e,this);if(this.hiddenAliases?.length)for(let e of this.hiddenAliases)J.set(e,this);if(this.subcommands?.length)for(let e of this.subcommands){if(J.set(`${this.name} ${e.name}`,e),this.aliases?.length)for(let t of this.aliases)J.set(`${t} ${e.name}`,e);if(this.hiddenAliases?.length)for(let t of this.hiddenAliases)J.set(`${t} ${e.name}`,e);if(e.aliases?.length)for(let t of e.aliases){if(J.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)J.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)J.set(`${n} ${t}`,e)}if(e.hiddenAliases?.length)for(let t of e.hiddenAliases){if(J.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)J.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)J.set(`${n} ${t}`,e)}}}};async function internalRunCommand(e,t,n){let r={positionals:[],values:{},tokens:[]},i=0;for(let[e,t]of Object.entries(n)){let[n,a]=e.split(`_`);if(n===`args`)r.positionals[i++]=t;else{let e=kebabCaseString(camelCaseToKebabCase(a)).toLowerCase();e.startsWith(`no-`)?r.values[e.slice(3)]=!t:r.values[e]=t}}let a=new t(e,t.name,t.name);a.skipTelemetry=!0,await a._run(r)}const Y={string:stringFlag,boolean:booleanFlag,integer:integerFlag};function YesFlag(e=`Automatic yes to prompts; assume "yes" as answer to all prompts.`){return{yes:Y.boolean({char:`y`,description:e,default:!1})}}function stringFlag(e){return{flagTag:`string`,builder:t=>{let n=new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`string`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`string`,multiple:!0}});return r},choices:e.choices,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??2,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function booleanFlag(e){return{flagTag:`boolean`,builder:t=>{let n=new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`boolean`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`boolean`,multiple:!0}});return r},choices:null,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??1,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function integerFlag(e){return{flagTag:`integer`,builder:t=>{let n=new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`string`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`string`,multiple:!0}});return r},choices:null,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??1,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function getBooleanValue(e,t){let n=t!==!1;return/^(y|yes)/i.test(e)?n=!0:/^(n|no)/i.test(e)&&(n=!1),n}function boolToString(e){return e?`Yes`:`No`}var Rn=ut((e,t)=>{let n=boolToString,[r,i]=ht(`idle`),[a,s]=ht(``),c=ft(),l=mt({status:r,theme:c});pt((r,c)=>{if(dt(r)){let r=getBooleanValue(a,e.default);s(n(r)),i(`done`),t(r);return}if(r.name===`tab`){let t=boolToString(!getBooleanValue(a,e.default));c.clearLine(0),c.write(t),s(t);return}if(r.name===`y`||r.name===`n`){let a=getBooleanValue(r.name,e.default);s(n(a)),i(`done`),t(a);return}c.clearLine(0),c.write(a),s(c.line)});let u=a,f=``;return r===`done`?u=c.style.answer(a):f=` ${c.style.defaultAnswer(e.default===!1?`y/N`:`Y/n`)}`,`${l} ${c.style.message(e.message,r)}${f} ${u}`});const X=stdinCheckWrapper(async({message:e,default:t})=>await Rn({message:e,default:t})),getDeprecatedLocalConfigPath=e=>A(e,`apify.json`),zn=new Map;async function useActorConfig({cwd:t=e.cwd(),migrateConfig:n=!0,warnAboutOldConfig:r=!0}={cwd:e.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let i=zn.get(t);if(i)return cliDebugPrint(`useActorConfig`,{cacheHit:!0,config:i}),tt(i);let a=getLocalConfigPath(t),s=getDeprecatedLocalConfigPath(t),c,l;try{c=getJsonFileContent(a)}catch(e){return et({message:`Failed to read local config at path: '${a}':`,cause:e,exists:!1,config:{}})}try{l=getJsonFileContent(s)}catch(e){return et({message:`Failed to read local config at path: '${s}':`,cause:e,exists:!1,config:{}})}if(c&&l&&r&&await handleBothConfigVersionsFound(s),!c&&!l)return zn.set(t,{exists:!1,migrated:!1,config:{}}),tt({exists:!1,migrated:!1,config:{}});let u=!1;if(!c&&l&&n){let e=await handleMigrationFlow(l,s,a);if(e.isErr())return et(e.unwrapErr());c=e.unwrap(),u=!0}return zn.set(t,{exists:!0,migrated:u,config:c||l||{}}),cliDebugPrint(`useActorConfig`,{cacheHit:!1,config:zn.get(t)}),tt({exists:!0,migrated:u,config:c||l||{}})}async function handleBothConfigVersionsFound(e){if(!await X({message:`The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Since we have found both files in your Actor directory, "apify.json" will be renamed to "apify.json.deprecated". Going forward, all commands will use ".actor/actor.json". You can read about the differences between the old and the new config at https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md. Do you want to continue?`})){warning({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 ke(e,`${e}.deprecated`),info({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(e){e instanceof Error?error({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${e.message||e}`}):error({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${a(e,{showHidden:!1})}`})}}const Bn=[`name`,`version`,`buildTag`];async function handleMigrationFlow(e,t,n){let r={...e};if(typeof r.version==`object`&&(r=updateLocalConfigStructure(r)),r={actorSpecification:1,environmentVariables:e?.env||void 0,...Bn.reduce((t,n)=>(t[n]=e[n],t),{})},!await X({message:`The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Your "apify.json" file will be automatically updated to the new format under ".actor/actor.json". The original file will be renamed by adding the ".deprecated" suffix. Do you want to continue?`}))return et({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:r});try{await F(k(n),{recursive:!0}),await z(n,JSON.stringify(r,null,` `))}catch(e){let t=e;return et({message:`Failed to write the new "actor.json" file to path: '${n}'.\n ${t.message||t}`,exists:!0,config:r})}try{await ke(t,`${t}.deprecated`)}catch(e){let t=e;warning({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${t.message||t}`})}return info({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.`}),tt(r)}function updateLocalConfigStructure(e){let t={name:e.name,template:e.template,version:e.version.versionNumber,buildTag:e.version.buildTag,env:null};if(e.version.envVars?.length){let n={};e.version.envVars.forEach(e=>{e.name&&e.value&&(n[e.name]=e.value)}),t.env=n}return t}const Vn=A(getLocalKeyValueStorePath(`default`),`INPUT.json`);var ActorCalculateMemoryCommand=class extends ApifyCommand{static name=`calculate-memory`;static description=`Calculates the Actor’s 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:Y.string({description:`Path to the input JSON file used for the calculation.`,required:!1,default:Vn}),defaultMemoryMbytes:Y.string({description:`Memory-calculation expression (in MB). If omitted, the value is loaded from the actor.json file.`,required:!1}),build:Y.string({description:`Actor build version or build tag to evaluate the expression with.`,required:!1}),timeoutSecs:Y.integer({description:`Maximum run timeout, in seconds.`,required:!1}),maxItems:Y.integer({description:`Maximum number of items Actor can output.`,required:!1}),maxTotalChargeUsd:Y.integer({description:`Maximum total charge in USD.`,required:!1})};async run(){let{input:t,memoryExpression:n,minMemory:r,maxMemory:i,runOptions:a}=await this.prepareMemoryArguments();if(!n)throw Error(`No memory-calculation expression found. Provide it via the --default-memory-mbytes flag or define defaultMemoryMbytes in actor.json.`);let s=getJsonFileContent(j(e.cwd(),t))??{};info({message:`Evaluating memory expression: ${n}`});try{let e=await ct(n,{input:s,runOptions:a});success({message:`Calculated memory: ${Math.min(Math.max(e,r),i)} MB`,stdout:!0})}catch(e){error({message:`Memory calculation failed: ${e.message}`})}}async prepareMemoryArguments(){let{input:e,defaultMemoryMbytes:t,...n}=this.flags,r=t,i=0,a=1/0;return r||({defaultMemoryMbytes:r,minMemoryMbytes:i=i,maxMemoryMbytes:a=a}=await this.getExpressionFromConfig()),{memoryExpression:r,minMemory:i,maxMemory:a,input:e,runOptions:n}}async getExpressionFromConfig(){let t=await useActorConfig({cwd:e.cwd()});if(t.isErr()){let{message:n,cause:r}=t.unwrapErr();return error({message:`${n}${r?`\n ${r.message}`:``}`}),e.exitCode=5,{}}let{config:n}=t.unwrap();return{defaultMemoryMbytes:n?.defaultMemoryMbytes?.toString(),minMemoryMbytes:n?.minMemoryMbytes,maxMemoryMbytes:n?.maxMemoryMbytes}}};const Hn={KEY_VALUE_STORE:`KEY_VALUE_STORE`,DATASET:`DATASET`,REQUEST_QUEUE:`REQUEST_QUEUE`},getApifyTokenFromEnvOrAuthFile=async()=>{let t=e.env[P.TOKEN];if(t)return t;let n=await getLocalUserInfo();if(!n||!n.token)throw Error(`Apify token is not set. Please set it using the environment variable APIFY_TOKEN or apify login command.`);return n.token},getApifyStorageClient=async(t={},n=Reflect.has(e.env,P.IS_AT_HOME))=>{let r=getLocalStorageDir();return r&&!n?new gt({localDataDirectory:r,...t}):new Be({...getApifyClientOptions(await getApifyTokenFromEnvOrAuthFile()),...t})},getDefaultStorageId=t=>{let n=M[`DEFAULT_${t}_ID`];return e.env[n]||he[n]},outputRecordFromDefaultStore=async t=>{let n=await getApifyStorageClient(),r=getDefaultStorageId(Hn.KEY_VALUE_STORE),i=await n.keyValueStore(r).getRecord(t,{stream:!0});i&&await Pe(i.value,e.stdout,{end:!1})},outputInputFromDefaultStore=async()=>outputRecordFromDefaultStore(e.env[M.INPUT_KEY]||me.INPUT);function stringArg(e){return{argTag:`string`,required:e.required??!1,stdin:e.stdin??1,description:e.description,aliases:e.aliases,catchAll:e.catchAll??!1}}const Z={string:stringArg};var ActorChargeCommand=class extends ApifyCommand{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:Z.string({description:`Name of the event to charge for.`,required:!0})};static flags={count:Y.integer({description:`Number of events to charge.`,required:!1,default:1}),"idempotency-key":Y.string({description:`Idempotency key for the charge request.`,required:!1}),"test-pay-per-event":Y.boolean({description:`Test pay-per-event charging without actually charging.`,required:!1,default:!1})};async run(){let{eventName:e}=this.args,{count:t,testPayPerEvent:n,idempotencyKey:r}=this.flags;if(!process.env.APIFY_IS_AT_HOME){info({message:`No platform detected: would charge ${t} events of type "${e}" with idempotency key "${r??`not-provided`}".`,stdout:!0});return}if(n){info({message:`PPE test mode: would charge ${t} events of type "${e}" with idempotency key "${r??`not-provided`}".`,stdout:!0});return}let i=await getLoggedClient(await getApifyTokenFromEnvOrAuthFile());if(!i)throw Error(`Apify token is not set. Please set it using the environment variable APIFY_TOKEN.`);let a=process.env[P.ACTOR_RUN_ID];if(!a)throw Error(`Charge command must be executed in a running Actor. Run ID not found.`);if((await i.run(a).get())?.pricingInfo?.pricingModel!==`PAY_PER_EVENT`)throw Error(`Charge command can only be used with pay-per-event pricing model.`);info({message:`Charging ${t} events of type "${e}" with idempotency key "${r??`not-provided`}" (runId: ${a}).`,stdout:!0}),await i.run(a).charge({eventName:e,count:t,idempotencyKey:r})}};const Un=[`.actor/INPUT_SCHEMA.json`,`./INPUT_SCHEMA.json`,`.actor/input_schema.json`,`./input_schema.json`],readInputSchema=async({forcePath:e,cwd:t,throwOnMissing:n=!1})=>{if(e)return{inputSchema:getJsonFileContent(e),inputSchemaPath:e};let r=getLocalConfig(t);if(typeof r?.input==`object`&&r.input!==null)return{inputSchema:r.input,inputSchemaPath:null};if(typeof r?.input==`string`){let e=A(t,nn,r.input),i=getJsonFileContent(e);if(!i){if(n)throw Error(`Input schema file not found at ${e} (referenced in '${W}').`);return warning({message:`Input schema file not found at ${e} (referenced in '${W}').`}),{inputSchema:null,inputSchemaPath:e}}return{inputSchema:i,inputSchemaPath:e}}for(let e of Un){let n=A(t,e);if(v(n))return{inputSchema:getJsonFileContent(n),inputSchemaPath:n}}return{inputSchema:null,inputSchemaPath:A(t,Un[0])}},readAndValidateInputSchema=async({forcePath:e,cwd:t,getMessage:n})=>{let{inputSchema:r,inputSchemaPath:i}=await readInputSchema({forcePath:e,cwd:t});if(!r)throw Error(`Input schema has not been found at ${i}.`);return info({message:n(i)}),yt(new _n({strict:!1}),r),{inputSchema:r,inputSchemaPath:i}},readStorageSchema=({cwd:e,key:t,label:n,getRef:r,throwOnMissing:i=!1})=>{let a=getLocalConfig(e),s=r?r(a):a?.storages?.[t];if(typeof s==`object`&&s)return{schema:s,schemaPath:null};if(typeof s==`string`){let t=A(e,nn,s),r=getJsonFileContent(t);if(!r){if(i)throw Error(`${n} schema file not found at ${t} (referenced in '${W}').`);return warning({message:`${n} schema file not found at ${t} (referenced in '${W}').`}),null}return{schema:r,schemaPath:t}}return null},readDatasetSchema=({cwd:e})=>{let t=readStorageSchema({cwd:e,key:`dataset`,label:`Dataset`});return t?{datasetSchema:t.schema,datasetSchemaPath:t.schemaPath}:null},readOutputSchema=({cwd:e})=>{let t=readStorageSchema({cwd:e,key:`output`,label:`Output`,getRef:e=>e?.output});return t?{outputSchema:t.schema,outputSchemaPath:t.schemaPath}:null},createPrefilledInputFileFromInputSchema=async e=>{let t={};try{let{inputSchema:n}=await readInputSchema({cwd:e});n&&(yt(new _n({strict:!1}),n),t=Object.entries(n.properties).reduce((e,[t,n])=>(e[t]=n.type===`boolean`||n.editor===`hidden`?n.default:n.prefill,e),{}))}catch(e){warning({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${e.message}`})}finally{D(A(e,getLocalKeyValueStorePath(),`${me.INPUT}.json`),JSON.stringify(t,null,` `))}},getDefaultsFromInputSchema=e=>{let t={};for(let[n,r]of Object.entries(e.properties))r.default!==void 0&&(t[n]=r.default);return t};function formatSchemaValidationErrors(e,t){return`${t} schema is not valid:\n${e.map(e=>{let t=e.instancePath?` at ${e.instancePath}`:``;return` - ${e.message}${t}`}).join(`
54
+ `)}`}function validateDatasetSchema(e){let t=xt();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Dataset`))}function validateOutputSchema(e){let t=Ct();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Output`))}function validateKvsSchema(e){let t=St();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Key-Value Store`))}const getAjvValidator=(e,t)=>{let n=vt(e);n.required=[];for(let[t,r]of Object.entries(e.properties)){let i=e.required?.includes(t),a=r.default!==void 0;i&&!a&&(n.required.push(t),r.type===`array`&&(r.minItems=Math.max(1,r.minItems||0)))}return delete n.$schema,t.compile(n)};function makePropertiesRequired(e){let t=vt(e);if(!t.properties||typeof t.properties!=`object`)return t;let n=t.properties,r=new Set(Array.isArray(t.required)?t.required:[]);for(let[e,t]of Object.entries(n))t.default!==void 0&&r.add(e),t.type===`object`&&t.properties&&(n[e]=makePropertiesRequired(t));return t.required=Array.from(r),t}function clearAllRequired(e){let t=vt(e);if(delete t.required,t.properties&&typeof t.properties==`object`){let e=t.properties;for(let[t,n]of Object.entries(e))n.type===`object`&&n.properties&&(e[t]=clearAllRequired(n))}return t}function stripTitles(e){let t=vt(e);if(delete t.title,t.properties&&typeof t.properties==`object`){let e=t.properties;for(let[t,n]of Object.entries(e))n&&typeof n==`object`&&(e[t]=stripTitles(n))}t.items&&typeof t.items==`object`&&(t.items=stripTitles(t.items));for(let e of[`allOf`,`anyOf`,`oneOf`])Array.isArray(t[e])&&(t[e]=t[e].map(e=>e&&typeof e==`object`?stripTitles(e):e));for(let e of[`definitions`,`$defs`])if(t[e]&&typeof t[e]==`object`&&!Array.isArray(t[e])){let n=t[e];for(let[e,t]of Object.entries(n))t&&typeof t==`object`&&(n[e]=stripTitles(t))}t.additionalProperties&&typeof t.additionalProperties==`object`&&(t.additionalProperties=stripTitles(t.additionalProperties));for(let e of[`if`,`then`,`else`,`not`])t[e]&&typeof t[e]==`object`&&(t[e]=stripTitles(t[e]));if(t.patternProperties&&typeof t.patternProperties==`object`&&!Array.isArray(t.patternProperties)){let e=t.patternProperties;for(let[t,n]of Object.entries(e))n&&typeof n==`object`&&(e[t]=stripTitles(n))}return t}function prepareFieldsSchemaForCompilation(e){let t=e.fields;if(!t||typeof t!=`object`||!t.properties||typeof t.properties!=`object`)return null;let n=vt(t);return n.type||=`object`,n}function prepareOutputSchemaForCompilation(e){let t=e.properties;if(!t||typeof t!=`object`||Object.keys(t).length===0)return null;let n=vt(t);for(let e of Object.values(n))e&&typeof e==`object`&&delete e.template;let r={type:e.type||`object`,properties:n};return Array.isArray(e.required)&&(r.required=[...e.required]),r}function prepareKvsCollectionsForCompilation(e){let t=e.collections;if(!t||typeof t!=`object`)return[];let n=[];for(let[e,r]of Object.entries(t)){if(!r||typeof r!=`object`)continue;let t=r.jsonSchema;if(!t||typeof t!=`object`||Object.keys(t).length===0)continue;let i=vt(t);i.type||=`object`,n.push({name:e,schema:i})}return n}var ActorGenerateSchemaTypesCommand=class extends ApifyCommand{static name=`generate-schema-types`;static hiddenAliases=[`generate-types`];static description=`Generate TypeScript types from Actor schemas.
55
55
 
56
56
  Generates types from the input schema and, when no custom path is provided,
57
57
  also from the Dataset, Output (experimental), and Key-Value Store (experimental)
58
- schemas defined in '${U}'.
58
+ schemas defined in '${W}'.
59
59
 
60
60
  Reads the input schema from one of these locations (in priority order):
61
- 1. Object in '${U}' under "input" key
62
- 2. JSON file path in '${U}' "input" key
61
+ 1. Object in '${W}' under "input" key
62
+ 2. JSON file path in '${W}' "input" key
63
63
  3. .actor/INPUT_SCHEMA.json
64
64
  4. INPUT_SCHEMA.json
65
65
 
66
66
  Optionally specify a custom schema file path, or a directory path.
67
67
  When a directory is provided, all schemas are discovered from it
68
- just as if the command were run from that directory with no argument.`;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:Y.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:D.join(`src`,`__generated__`,`actor`)}),strict:Y.boolean({description:`Whether generated interfaces should be strict (no index signature [key: string]: unknown).`,required:!1,default:!0}),"all-optional":Y.boolean({description:`Mark all properties as optional in generated types.`,required:!1,default:!1})};static args={path:Z.string({required:!1,description:`Optional path to an input schema file or a directory containing Actor schemas. If a directory is given, all schema types are generated from it. If not provided, searches default locations in the current directory.`})};async run(){let t=e.cwd(),n,r=t;if(this.args.path){let e=D.resolve(t,this.args.path);await L(e).then(e=>e.isDirectory()).catch(()=>!1)?r=e:n=e}let{inputSchema:i}=await readAndValidateInputSchema({forcePath:n,cwd:r,getMessage:e=>e?`Generating types from input schema at ${e}`:`Generating types from input schema embedded in '${U}'`}),a=`input`,s=this.flags.allOptional?clearAllRequired(i):makePropertiesRequired(i),c={bannerComment:`
68
+ just as if the command were run from that directory with no argument.`;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:Y.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:O.join(`src`,`__generated__`,`actor`)}),strict:Y.boolean({description:`Whether generated interfaces should be strict (no index signature [key: string]: unknown).`,required:!1,default:!0}),"all-optional":Y.boolean({description:`Mark all properties as optional in generated types.`,required:!1,default:!1})};static args={path:Z.string({required:!1,description:`Optional path to an input schema file or a directory containing Actor schemas. If a directory is given, all schema types are generated from it. If not provided, searches default locations in the current directory.`})};async run(){let t=e.cwd(),n,r=t;if(this.args.path){let e=O.resolve(t,this.args.path);await R(e).then(e=>e.isDirectory()).catch(()=>!1)?r=e:n=e}let{inputSchema:i}=await readAndValidateInputSchema({forcePath:n,cwd:r,getMessage:e=>e?`Generating types from input schema at ${e}`:`Generating types from input schema embedded in '${W}'`}),a=`input`,s=this.flags.allOptional?clearAllRequired(i):makePropertiesRequired(i),c={bannerComment:`
69
69
  // biome-ignore-all lint: generated
70
70
  // biome-ignore-all format: generated
71
71
  /* eslint-disable */
@@ -75,75 +75,75 @@ just as if the command were run from that directory with no argument.`;static gr
75
75
  * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
76
76
  * and run apify actor generate-schema-types to regenerate this file.
77
77
  */
78
- `,maxItems:-1,unknownAny:!0,format:!0,additionalProperties:!this.flags.strict,$refOptions:{resolve:{external:!1,file:!1,http:!1}}},l=await yt(stripTitles(s),a,c),u=D.resolve(r,this.flags.output);await P(u,{recursive:!0});let f=D.join(u,`${a}.ts`);if(await R(f,l,`utf-8`),success({message:`Generated types written to ${f}`}),!n){let t=await Promise.allSettled([this.generateDatasetTypes({cwd:r,outputDir:u,compileOptions:c}),this.generateOutputTypes({cwd:r,outputDir:u,compileOptions:c}),this.generateKvsTypes({cwd:r,outputDir:u,compileOptions:c})]),n=[`Dataset`,`Output`,`Key-Value Store`],i=!1;for(let[e,r]of t.entries())r.status===`rejected`&&(i=!0,error({message:`Failed to generate types for ${n[e]} schema: ${r.reason instanceof Error?r.reason.message:String(r.reason)}`}));i&&(e.exitCode=1)}}async generateDatasetTypes({cwd:e,outputDir:t,compileOptions:n}){let r=readDatasetSchema({cwd:e});if(!r)return;let{datasetSchema:i,datasetSchemaPath:a}=r;info(a?{message:`[experimental] Generating types from Dataset schema at ${a}`}:{message:`[experimental] Generating types from Dataset schema embedded in '${U}'`});let s=prepareFieldsSchemaForCompilation(i);if(!s){warning({message:`Dataset schema has no fields defined, skipping type generation.`});return}let c=`dataset`,l=await yt(stripTitles(this.flags.allOptional?clearAllRequired(s):s),c,n),u=D.join(t,`${c}.ts`);await R(u,l,`utf-8`),success({message:`Generated types written to ${u}`})}async generateOutputTypes({cwd:e,outputDir:t,compileOptions:n}){let r=readOutputSchema({cwd:e});if(!r)return;let{outputSchema:i,outputSchemaPath:a}=r;info(a?{message:`[experimental] Generating types from Output schema at ${a}`}:{message:`[experimental] Generating types from Output schema embedded in '${U}'`});let s=prepareOutputSchemaForCompilation(i);if(!s){warning({message:`Output schema has no properties defined, skipping type generation.`});return}let c=`output`,l=await yt(stripTitles(this.flags.allOptional?clearAllRequired(s):s),c,n),u=D.join(t,`${c}.ts`);await R(u,l,`utf-8`),success({message:`Generated types written to ${u}`})}async generateKvsTypes({cwd:e,outputDir:t,compileOptions:n}){let r=readStorageSchema({cwd:e,key:`keyValueStore`,label:`Key-Value Store`});if(!r)return;let{schema:i,schemaPath:a}=r;info(a?{message:`[experimental] Generating types from Key-Value Store schema at ${a}`}:{message:`[experimental] Generating types from Key-Value Store schema embedded in '${U}'`});let s=prepareKvsCollectionsForCompilation(i);if(s.length===0){warning({message:`Key-Value Store schema has no collections with JSON schemas, skipping type generation.`});return}let c=[];for(let{name:e,schema:t}of s){let r=await yt(stripTitles(this.flags.allOptional?clearAllRequired(t):t),e,{...n,bannerComment:c.length===0?n.bannerComment:``});c.push(r)}let l=D.join(t,`key-value-store.ts`);await R(l,c.join(`
79
- `),`utf-8`),success({message:`Generated types written to ${l}`})}},ActorGetInputCommand=class extends ApifyCommand{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 outputInputFromDefaultStore()}},ActorGetPublicUrlCommand=class extends ApifyCommand{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:Z.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[N.IS_AT_HOME])){error({message:`get-public-url is not yet implemented for local development`}),process.exitCode=255;return}let t=process.env[j.DEFAULT_KEY_VALUE_STORE_ID];if(!t){error({message:`Missing environment variable: ${j.DEFAULT_KEY_VALUE_STORE_ID}. Please set it before running the command.`}),process.exitCode=5;return}let n=await getApifyStorageClient();if(!await n.keyValueStore(t).get()){error({message:`Key-Value store with ID '${t}' was not found. Ensure the store exists and that the correct ID is set in ${j.DEFAULT_KEY_VALUE_STORE_ID}.`}),process.exitCode=250;return}let r=await n.keyValueStore(t).getRecordPublicUrl(e);console.log(r)}},ActorGetValueCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`Key of the record in the key-value store.`})};async run(){let{key:e}=this.args;await outputRecordFromDefaultStore(e)}},ActorPushDataCommand=class extends ApifyCommand{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:Z.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||fn;if(!t){error({message:`No item was provided.`});return}let n=await getApifyStorageClient(),r=getDefaultStorageId(Hn.DATASET),i;try{i=JSON.parse(t.toString(`utf8`))}catch(e){throw Error(`Failed to parse data as JSON string: ${e.message}`)}await n.dataset(r).pushItems(i)}},ActorSetValueCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`Key of the record in key-value store.`}),value:Z.string({required:!1,description:`Record data, which can be one of the following values:
78
+ `,maxItems:-1,unknownAny:!0,format:!0,additionalProperties:!this.flags.strict,$refOptions:{resolve:{external:!1,file:!1,http:!1}}},l=await _t(stripTitles(s),a,c),u=O.resolve(r,this.flags.output);await F(u,{recursive:!0});let f=O.join(u,`${a}.ts`);if(await z(f,l,`utf-8`),success({message:`Generated types written to ${f}`}),!n){let t=await Promise.allSettled([this.generateDatasetTypes({cwd:r,outputDir:u,compileOptions:c}),this.generateOutputTypes({cwd:r,outputDir:u,compileOptions:c}),this.generateKvsTypes({cwd:r,outputDir:u,compileOptions:c})]),n=[`Dataset`,`Output`,`Key-Value Store`],i=!1;for(let[e,r]of t.entries())r.status===`rejected`&&(i=!0,error({message:`Failed to generate types for ${n[e]} schema: ${r.reason instanceof Error?r.reason.message:String(r.reason)}`}));i&&(e.exitCode=1)}}async generateDatasetTypes({cwd:e,outputDir:t,compileOptions:n}){let r=readDatasetSchema({cwd:e});if(!r)return;let{datasetSchema:i,datasetSchemaPath:a}=r;info(a?{message:`[experimental] Generating types from Dataset schema at ${a}`}:{message:`[experimental] Generating types from Dataset schema embedded in '${W}'`});let s=prepareFieldsSchemaForCompilation(i);if(!s){warning({message:`Dataset schema has no fields defined, skipping type generation.`});return}let c=`dataset`,l=await _t(stripTitles(this.flags.allOptional?clearAllRequired(s):s),c,n),u=O.join(t,`${c}.ts`);await z(u,l,`utf-8`),success({message:`Generated types written to ${u}`})}async generateOutputTypes({cwd:e,outputDir:t,compileOptions:n}){let r=readOutputSchema({cwd:e});if(!r)return;let{outputSchema:i,outputSchemaPath:a}=r;info(a?{message:`[experimental] Generating types from Output schema at ${a}`}:{message:`[experimental] Generating types from Output schema embedded in '${W}'`});let s=prepareOutputSchemaForCompilation(i);if(!s){warning({message:`Output schema has no properties defined, skipping type generation.`});return}let c=`output`,l=await _t(stripTitles(this.flags.allOptional?clearAllRequired(s):s),c,n),u=O.join(t,`${c}.ts`);await z(u,l,`utf-8`),success({message:`Generated types written to ${u}`})}async generateKvsTypes({cwd:e,outputDir:t,compileOptions:n}){let r=readStorageSchema({cwd:e,key:`keyValueStore`,label:`Key-Value Store`});if(!r)return;let{schema:i,schemaPath:a}=r;info(a?{message:`[experimental] Generating types from Key-Value Store schema at ${a}`}:{message:`[experimental] Generating types from Key-Value Store schema embedded in '${W}'`});let s=prepareKvsCollectionsForCompilation(i);if(s.length===0){warning({message:`Key-Value Store schema has no collections with JSON schemas, skipping type generation.`});return}let c=[];for(let{name:e,schema:t}of s){let r=await _t(stripTitles(this.flags.allOptional?clearAllRequired(t):t),e,{...n,bannerComment:c.length===0?n.bannerComment:``});c.push(r)}let l=O.join(t,`key-value-store.ts`);await z(l,c.join(`
79
+ `),`utf-8`),success({message:`Generated types written to ${l}`})}},ActorGetInputCommand=class extends ApifyCommand{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 outputInputFromDefaultStore()}},ActorGetPublicUrlCommand=class extends ApifyCommand{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:Z.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[P.IS_AT_HOME])){error({message:`get-public-url is not yet implemented for local development`}),process.exitCode=255;return}let t=process.env[M.DEFAULT_KEY_VALUE_STORE_ID];if(!t){error({message:`Missing environment variable: ${M.DEFAULT_KEY_VALUE_STORE_ID}. Please set it before running the command.`}),process.exitCode=5;return}let n=await getApifyStorageClient();if(!await n.keyValueStore(t).get()){error({message:`Key-Value store with ID '${t}' was not found. Ensure the store exists and that the correct ID is set in ${M.DEFAULT_KEY_VALUE_STORE_ID}.`}),process.exitCode=250;return}let r=await n.keyValueStore(t).getRecordPublicUrl(e);console.log(r)}},ActorGetValueCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`Key of the record in the key-value store.`})};async run(){let{key:e}=this.args;await outputRecordFromDefaultStore(e)}},ActorPushDataCommand=class extends ApifyCommand{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:Z.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||dn;if(!t){error({message:`No item was provided.`});return}let n=await getApifyStorageClient(),r=getDefaultStorageId(Hn.DATASET),i;try{i=JSON.parse(t.toString(`utf8`))}catch(e){throw Error(`Failed to parse data as JSON string: ${e.message}`)}await n.dataset(r).pushItems(i)}},ActorSetValueCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`Key of the record in key-value store.`}),value:Z.string({required:!1,description:`Record data, which can be one of the following values:
80
80
  - If empty, the record in the key-value store is deleted.
81
81
  - If no \`contentType\` flag is specified, value is expected to be any JSON string value.
82
82
  - If options.contentType is set, value is taken as is.`})};static flags={contentType:Y.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:n=`application/json; charset=utf-8`}=this.flags,r=t||process.stdin,i=(await getApifyStorageClient()).keyValueStore(getDefaultStorageId(Hn.KEY_VALUE_STORE));r==null||r===``||r===`null`||r===`undefined`?await i.deleteRecord(e):await i.setRecord({key:e,value:r,contentType:n})}},ActorIndexCommand=class extends ApifyCommand{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.
83
83
 
84
- 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=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand];async run(){this.printHelp()}};function OverrideClassName(e){return e}async function resolveActorContext({providedActorNameOrId:t,client:n}){let r=await getLocalUserInfo(),i=r.username||r.id,a=getLocalConfig(e.cwd())||{};if(t?.includes(`/`)){let e=await n.actor(t).get();return e?{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id}:{valid:!1,reason:`Actor with ID "${t}" was not found`}}if(t){let e=await n.actor(t).get();if(e)return{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id};let r=await n.actor(`${i}/${t.toLowerCase()}`).get();return r?{valid:!0,userFriendlyId:`${r.username}/${r.name}`,id:r.id}:{valid:!1,reason:`Actor with name or ID "${t}" was not found`}}if(a.name){let e=await n.actor(`${i}/${a.name}`).get();return e?{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id}:{valid:!1,reason:`Actor with name "${a.name}" was not found`}}return{valid:!1,reason:`Unable to detect what Actor to create a build for`}}function useSignalHandler({signals:e,handler:t,cleanTerminalLine:n=!0,once:r=!0}){let i=!1,wrapped=a=>{if(!i){if(r){i=!0;for(let t of e)process.off(t,wrapped)}n&&process.stderr.isTTY&&process.stderr.write(`\r\x1B[2K\x1B[0m`),cliDebugPrint(`useSignalHandler`,{event:`fired`,signal:a,once:r}),(async()=>{try{await t(a)}catch(e){cliDebugPrint(`useSignalHandler`,{event:`handler-threw`,signal:a,err:e})}})()}};for(let t of e)process.on(t,wrapped);return cliDebugPrint(`useSignalHandler`,{event:`registered`,signals:e,once:r}),{[Symbol.dispose](){if(!i){i=!0;for(let t of e)process.off(t,wrapped);cliDebugPrint(`useSignalHandler`,{event:`disposed`,signals:e})}}}}function useAbortJobOnSignal(e){let{apifyClient:n,silent:r=!1}=e,i=0;return useSignalHandler({signals:nn,once:!1,handler:async a=>{if(i+=1,e.kind===`build`){if(i>1)return;r||info({message:t.gray(`Received ${t.yellow(a)}, aborting build "${t.yellow(e.jobId)}" on the Apify platform...`),stdout:!0});try{await n.build(e.jobId).abort()}catch(t){error({message:`Failed to abort build "${e.jobId}": ${t.message}`,stdout:!0})}return}if(i>2)return;let s=i===1,c=`${e.runType.toLowerCase()} run`;if(!r){let n=s?`Received ${t.yellow(a)}, gracefully aborting ${c} "${t.yellow(e.jobId)}" on the Apify platform... ${t.dim(`(press Ctrl+C again to abort immediately)`)}`:`Received ${t.yellow(a)} again, aborting ${c} "${t.yellow(e.jobId)}" immediately...`;info({message:t.gray(n),stdout:!0})}try{await n.run(e.jobId).abort({gracefully:s})}catch(t){error({message:`Failed to abort run "${e.jobId}": ${t.message}`,stdout:!0})}}})}function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function o(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function d(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}var BuildsCreateCommand=class extends ApifyCommand{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:Y.string({description:`Build tag to be applied to the successful Actor build. By default, this is "latest".`}),version:Y.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:Y.boolean({description:`Whether to print out the build log after the build is triggered.`})};static args={actorId:Z.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:n,json:r,log:i}=this.flags,{actorId:a}=this.args,s=await getLoggedClientOrThrow(),c=await resolveActorContext({providedActorNameOrId:a,client:s});if(!c.valid){error({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let l=await s.actor(c.id).get(),u=objectGroupBy(l.versions,e=>e.buildTag??`latest`)[e??`latest`],f=l.versions.find(e=>e.versionNumber===n),p,m=e;if(f){if(e&&(!u||!u.some(e=>e.versionNumber===n))){error({message:`The Actor Version "${n}" does not have the tag "${e}".`,stdout:!0});return}p=n,m=f.buildTag??`latest`}else if(u&&(p=u[0].versionNumber,m=e??`latest`,u.length>1&&!n)){error({message:`Multiple Actor versions with the tag "${e}" found. Please specify the version number using the "--version" flag.\n Available versions for this tag: ${u.map(e=>t.yellow(e.versionNumber)).join(`, `)}`,stdout:!0});return}if(!p){error({message:`No Actor versions with the tag "${e}" found. You can push a new version with this tag by using "apify push --build-tag=${e}".`,stdout:!0});return}let h=await s.actor(c.id).build(p,{tag:e});if(r){printJsonToStdout(h);return}let g=[`${t.yellow(`Actor`)}: ${l?.username?`${l.username}/`:``}${l?.name??`unknown-actor`} (${t.gray(h.actId)})`,` ${t.yellow(`Version`)}: ${p} (tagged with ${t.yellow(m)})`,``,`${t.greenBright(`Build Started`)} (ID: ${t.gray(h.id)})`,` ${t.yellow(`Build Number`)}: ${h.buildNumber} (will get tagged once finished)`,` ${t.yellow(`Started`)}: ${G.display(h.startedAt)}`,``],_=`https://console.apify.com/actors/${h.actId}/builds/${h.buildNumber}`,v=`${t.blue(`View in Apify Console`)}: ${_}`;if(simpleLog({message:g.join(`
85
- `),stdout:!0}),i)try{var y=_usingCtx();y.u(useAbortJobOnSignal({apifyClient:s,kind:`build`,jobId:h.id}));try{await outputJobLog({job:h,apifyClient:s})}catch(e){error({message:`Failed to print log for build with ID "${h.id}": ${e.message}`,stdout:!0})}simpleLog({message:``,stdout:!0})}catch(e){y.e=e}finally{y.d()}simpleLog({message:v,stdout:!0})}},ActorsBuildCommand=class extends OverrideClassName(BuildsCreateCommand){static name=`build`};function resolveInput(e,t){let n,r;if(t)n=t,r=`application/json`;else{let t=getLocalInput(e);t&&(Ye.getExtension(t.contentType)===`json`?(n=JSON.parse(t.body.toString(`utf8`)),r=`application/json`):(n=t.body,r=t.contentType))}return!n||!r?null:{inputToUse:n,contentType:r}}async function getInputOverride(t,n,r){let i,a;if(!n&&!r){let t=fn;if(t)try{let n=JSON.parse(t.toString(`utf8`));if(Array.isArray(n))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=n,a=`stdin`}catch(t){return error({message:`Cannot parse JSON input from standard input.\n ${t.message}`}),e.exitCode=5,!1}}if(n)switch(n[0]){case`-`:return error({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),e.exitCode=5,!1;default:{let r=await Oe(A(t,n)).then(()=>!0).catch(()=>!1),s=n.endsWith(`.json`)||n.endsWith(`.json5`)||D.isAbsolute(n)||n.startsWith(`./`)||n.startsWith(`../`)||n.includes(`~`)||n.startsWith(`.\\`)||n.startsWith(`..\\`);if(r||s)return error({message:`Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead`}),e.exitCode=5,!1;try{let t=JSON.parse(n);if(Array.isArray(t))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=t,a=`input`}catch(t){return error({message:`Cannot parse JSON input.\n ${t.message}`}),e.exitCode=5,!1}}}else if(r)switch(r[0]){case`-`:return error({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),e.exitCode=5,!1;default:{let n=A(t,r),s;try{let t=await F(n,`utf8`),s=JSON.parse(t);if(Array.isArray(s))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=s,a=r}catch(e){s=e}if(s)try{let t=JSON.parse(r);if(Array.isArray(t))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=t,a=r}catch{return error({message:`Cannot read input file at path "${n}".\n ${s.message}`}),e.exitCode=5,!1}}}return i?{input:i,source:a}:void 0}const Wn=[M.SUCCEEDED,M.ABORTED,M.FAILED,M.TIMED_OUT];async function*runActorOrTaskOnCloud(n,r){try{var i=_usingCtx();let a=e.cwd(),{actorOrTaskData:s,runOptions:c,type:l,waitForFinishMillis:u,inputOverride:f,silent:p,waitForRunToFinish:m,printRunLogs:h}=r,g=l===`Actor`?`actor`:`task`,_=resolveInput(a,f);p||(l===`Actor`?run({message:`Calling ${l} ${s.userFriendlyId} (${t.gray(s.id)})\n`}):s.title?run({message:`Calling ${l} ${s.title} (${s.userFriendlyId}, ${t.gray(s.id)})\n`}):run({message:`Calling ${l} ${s.userFriendlyId} (${t.gray(s.id)})\n`}));let v;try{v=_&&l===`Actor`?await n[g](s.id).start(_.inputToUse,{...c,contentType:_.contentType}):await n[g](s.id).start(void 0,c)}catch(e){throw e.type===`record-not-found`?Error(`${l} ${s.userFriendlyId} (${s.id}) not found!`):e}if(i.u(useAbortJobOnSignal({apifyClient:n,kind:`run`,jobId:v.id,runType:l,silent:p})),yield v,!p&&h)try{await outputJobLog({job:v,timeoutMillis:u,apifyClient:n})===`timeouts`?console.error(`\n${t.gray(`Timeout for printing logs was hit, there may be future logs.`)}\n`):console.error()}catch(e){warning({message:`Can not get log:`}),console.error(e)}if(v=await n.run(v.id).get(),m)for(;!Wn.includes(v.status)&&(v=await n.run(v.id).get(),!Wn.includes(v.status));)await new Promise(e=>{setTimeout(e,1e3)});p||(v.status===M.SUCCEEDED?success({message:`${l} finished.`}):v.status===M.RUNNING?warning({message:`${l} is still running!`}):v.status===M.ABORTED||v.status===M.ABORTING?(warning({message:`${l} was aborted!`}),e.exitCode=3):(error({message:`${l} failed!`}),e.exitCode=1)),yield v}catch(e){i.e=e}finally{i.d()}}const SharedRunOnCloudFlags=e=>({build:Y.string({char:`b`,description:`Tag or number of the build to run (e.g. "latest" or "1.2.34").`,required:!1}),timeout:Y.integer({char:`t`,description:`Timeout for the ${e} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:Y.integer({char:`m`,description:`Amount of memory allocated for the ${e} run, in megabytes.`,required:!1})});var Gn=class ActorsCallCommand extends ApifyCommand{static name=`call`;static description=`Executes Actor remotely using your authenticated account.
86
- 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={...SharedRunOnCloudFlags(`Actor`),input:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.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:Y.boolean({char:`s`,description:`Prevents printing the logs of the Actor run to the console.`,default:!1}),"output-dataset":Y.boolean({char:`o`,description:`Prints out the entire default dataset on successful run of the Actor.`})};static enableJsonFlag=!0;static args={actorId:Z.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 '${U}' file.`})};async run(){let n=e.cwd(),r=getLocalConfig(n)||{},i=await getLoggedClientOrThrow(),a=await getLocalUserInfo(),s=a.username||a.id;if(this.flags.json&&this.flags.outputDataset){error({message:`You cannot use both the --json and --output-dataset flags when running this command.`}),e.exitCode=5;return}let{id:c,userFriendlyId:l,actorData:u}=await ActorsCallCommand.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={waitForFinish:2};this.flags.build&&(f.build=this.flags.build),this.flags.timeout&&(f.timeout=this.flags.timeout),this.flags.memory&&(f.memory=this.flags.memory);let p=await getInputOverride(n,this.flags.input,this.flags.inputFile);if(p===!1)return;let m=!1,h,g,_,v=runActorOrTaskOnCloud(i,{actorOrTaskData:{id:c,userFriendlyId:l},runOptions:f,type:`Actor`,inputOverride:p?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0});for await(let e of v)if(h=e,!m&&(m=!0,!this.flags.silent)){g=`https://console.apify.com/actors/${c}/runs/${e.id}`,_=`https://console.apify.com/storage/datasets/${e.defaultDatasetId}`;let n=[`${t.yellow(`Started`)}: ${G.display(e.startedAt)}`];e.containerUrl&&n.push(`${t.yellow(`Container URL`)}: ${t.blue(e.containerUrl)}`);let r=h.buildNumber.split(`.`).slice(0,2).join(`.`),i=u.versions.find(e=>e.versionNumber===r),a=Object.entries(u.taggedBuilds??{}).find(([,t])=>t.buildNumber===e.buildNumber)?.[0],s=[`${t.yellow(`Build`)}:`,t.cyan(h.buildNumber)];a?s.push(`(${t.yellow(a)})`):s.push(`(${t.gray(`N/A`)})`),i&&s.push(`| ${t.gray(`Actor version:`)} ${t.cyan(i.versionNumber)} (${t.yellow(i.buildTag)})`),n.push(s.join(` `)),n.push(`${t.yellow(`Timeout`)}: ${h.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),n.push(`${t.yellow(`Memory`)}: ${h.options.memoryMbytes} MB`),n.push(`${t.blue(`View on Apify Console`)}: ${g}`,``),simpleLog({message:n.join(`
84
+ 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=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand];async run(){this.printHelp()}};function OverrideClassName(e){return e}async function resolveActorContext({providedActorNameOrId:t,client:n}){let r=await getLocalUserInfo(),i=r.username||r.id,a=getLocalConfig(e.cwd())||{};if(t?.includes(`/`)){let e=await n.actor(t).get();return e?{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id}:{valid:!1,reason:`Actor with ID "${t}" was not found`}}if(t){let e=await n.actor(t).get();if(e)return{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id};let r=await n.actor(`${i}/${t.toLowerCase()}`).get();return r?{valid:!0,userFriendlyId:`${r.username}/${r.name}`,id:r.id}:{valid:!1,reason:`Actor with name or ID "${t}" was not found`}}if(a.name){let e=await n.actor(`${i}/${a.name}`).get();return e?{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id}:{valid:!1,reason:`Actor with name "${a.name}" was not found`}}return{valid:!1,reason:`Unable to detect what Actor to create a build for`}}function useSignalHandler({signals:e,handler:t,cleanTerminalLine:n=!0,once:r=!0}){let i=!1,wrapped=a=>{if(!i){if(r){i=!0;for(let t of e)process.off(t,wrapped)}n&&process.stderr.isTTY&&process.stderr.write(`\r\x1B[2K\x1B[0m`),cliDebugPrint(`useSignalHandler`,{event:`fired`,signal:a,once:r}),(async()=>{try{await t(a)}catch(e){cliDebugPrint(`useSignalHandler`,{event:`handler-threw`,signal:a,err:e})}})()}};for(let t of e)process.on(t,wrapped);return cliDebugPrint(`useSignalHandler`,{event:`registered`,signals:e,once:r}),{[Symbol.dispose](){if(!i){i=!0;for(let t of e)process.off(t,wrapped);cliDebugPrint(`useSignalHandler`,{event:`disposed`,signals:e})}}}}function useAbortJobOnSignal(e){let{apifyClient:n,silent:r=!1}=e,i=0;return useSignalHandler({signals:tn,once:!1,handler:async a=>{if(i+=1,e.kind===`build`){if(i>1)return;r||info({message:t.gray(`Received ${t.yellow(a)}, aborting build "${t.yellow(e.jobId)}" on the Apify platform...`),stdout:!0});try{await n.build(e.jobId).abort()}catch(t){error({message:`Failed to abort build "${e.jobId}": ${t.message}`,stdout:!0})}return}if(i>2)return;let s=i===1,c=`${e.runType.toLowerCase()} run`;if(!r){let n=s?`Received ${t.yellow(a)}, gracefully aborting ${c} "${t.yellow(e.jobId)}" on the Apify platform... ${t.dim(`(press Ctrl+C again to abort immediately)`)}`:`Received ${t.yellow(a)} again, aborting ${c} "${t.yellow(e.jobId)}" immediately...`;info({message:t.gray(n),stdout:!0})}try{await n.run(e.jobId).abort({gracefully:s})}catch(t){error({message:`Failed to abort run "${e.jobId}": ${t.message}`,stdout:!0})}}})}function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function o(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function d(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}var BuildsCreateCommand=class extends ApifyCommand{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:Y.string({description:`Build tag to be applied to the successful Actor build. By default, this is "latest".`}),version:Y.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:Y.boolean({description:`Whether to print out the build log after the build is triggered.`})};static args={actorId:Z.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:n,json:r,log:i}=this.flags,{actorId:a}=this.args,s=await getLoggedClientOrThrow(),c=await resolveActorContext({providedActorNameOrId:a,client:s});if(!c.valid){error({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let l=await s.actor(c.id).get(),u=objectGroupBy(l.versions,e=>e.buildTag??`latest`)[e??`latest`],f=l.versions.find(e=>e.versionNumber===n),p,m=e;if(f){if(e&&(!u||!u.some(e=>e.versionNumber===n))){error({message:`The Actor Version "${n}" does not have the tag "${e}".`,stdout:!0});return}p=n,m=f.buildTag??`latest`}else if(u&&(p=u[0].versionNumber,m=e??`latest`,u.length>1&&!n)){error({message:`Multiple Actor versions with the tag "${e}" found. Please specify the version number using the "--version" flag.\n Available versions for this tag: ${u.map(e=>t.yellow(e.versionNumber)).join(`, `)}`,stdout:!0});return}if(!p){error({message:`No Actor versions with the tag "${e}" found. You can push a new version with this tag by using "apify push --build-tag=${e}".`,stdout:!0});return}let h=await s.actor(c.id).build(p,{tag:e});if(r){printJsonToStdout(h);return}let g=[`${t.yellow(`Actor`)}: ${l?.username?`${l.username}/`:``}${l?.name??`unknown-actor`} (${t.gray(h.actId)})`,` ${t.yellow(`Version`)}: ${p} (tagged with ${t.yellow(m)})`,``,`${t.greenBright(`Build Started`)} (ID: ${t.gray(h.id)})`,` ${t.yellow(`Build Number`)}: ${h.buildNumber} (will get tagged once finished)`,` ${t.yellow(`Started`)}: ${G.display(h.startedAt)}`,``],_=`https://console.apify.com/actors/${h.actId}/builds/${h.buildNumber}`,v=`${t.blue(`View in Apify Console`)}: ${_}`;if(simpleLog({message:g.join(`
85
+ `),stdout:!0}),i)try{var y=_usingCtx();y.u(useAbortJobOnSignal({apifyClient:s,kind:`build`,jobId:h.id}));try{await outputJobLog({job:h,apifyClient:s})}catch(e){error({message:`Failed to print log for build with ID "${h.id}": ${e.message}`,stdout:!0})}simpleLog({message:``,stdout:!0})}catch(e){y.e=e}finally{y.d()}simpleLog({message:v,stdout:!0})}},ActorsBuildCommand=class extends OverrideClassName(BuildsCreateCommand){static name=`build`};function resolveInput(e,t){let n,r;if(t)n=t,r=`application/json`;else{let t=getLocalInput(e);t&&(qe.getExtension(t.contentType)===`json`?(n=JSON.parse(t.body.toString(`utf8`)),r=`application/json`):(n=t.body,r=t.contentType))}return!n||!r?null:{inputToUse:n,contentType:r}}async function getInputOverride(t,n,r){let i,a;if(!n&&!r){let t=dn;if(t)try{let n=JSON.parse(t.toString(`utf8`));if(Array.isArray(n))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=n,a=`stdin`}catch(t){return error({message:`Cannot parse JSON input from standard input.\n ${t.message}`}),e.exitCode=5,!1}}if(n)switch(n[0]){case`-`:return error({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),e.exitCode=5,!1;default:{let r=await De(j(t,n)).then(()=>!0).catch(()=>!1),s=n.endsWith(`.json`)||n.endsWith(`.json5`)||O.isAbsolute(n)||n.startsWith(`./`)||n.startsWith(`../`)||n.includes(`~`)||n.startsWith(`.\\`)||n.startsWith(`..\\`);if(r||s)return error({message:`Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead`}),e.exitCode=5,!1;try{let t=JSON.parse(n);if(Array.isArray(t))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=t,a=`input`}catch(t){return error({message:`Cannot parse JSON input.\n ${t.message}`}),e.exitCode=5,!1}}}else if(r)switch(r[0]){case`-`:return error({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),e.exitCode=5,!1;default:{let n=j(t,r),s;try{let t=await I(n,`utf8`),s=JSON.parse(t);if(Array.isArray(s))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=s,a=r}catch(e){s=e}if(s)try{let t=JSON.parse(r);if(Array.isArray(t))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=t,a=r}catch{return error({message:`Cannot read input file at path "${n}".\n ${s.message}`}),e.exitCode=5,!1}}}return i?{input:i,source:a}:void 0}const Wn=[N.SUCCEEDED,N.ABORTED,N.FAILED,N.TIMED_OUT];async function*runActorOrTaskOnCloud(n,r){try{var i=_usingCtx();let a=e.cwd(),{actorOrTaskData:s,runOptions:c,type:l,waitForFinishMillis:u,inputOverride:f,silent:p,waitForRunToFinish:m,printRunLogs:h}=r,g=l===`Actor`?`actor`:`task`,_=resolveInput(a,f);p||(l===`Actor`?run({message:`Calling ${l} ${s.userFriendlyId} (${t.gray(s.id)})\n`}):s.title?run({message:`Calling ${l} ${s.title} (${s.userFriendlyId}, ${t.gray(s.id)})\n`}):run({message:`Calling ${l} ${s.userFriendlyId} (${t.gray(s.id)})\n`}));let v;try{v=_&&l===`Actor`?await n[g](s.id).start(_.inputToUse,{...c,contentType:_.contentType}):await n[g](s.id).start(void 0,c)}catch(e){throw e.type===`record-not-found`?Error(`${l} ${s.userFriendlyId} (${s.id}) not found!`):e}if(i.u(useAbortJobOnSignal({apifyClient:n,kind:`run`,jobId:v.id,runType:l,silent:p})),yield v,!p&&h)try{await outputJobLog({job:v,timeoutMillis:u,apifyClient:n})===`timeouts`?console.error(`\n${t.gray(`Timeout for printing logs was hit, there may be future logs.`)}\n`):console.error()}catch(e){warning({message:`Can not get log:`}),console.error(e)}if(v=await n.run(v.id).get(),m)for(;!Wn.includes(v.status)&&(v=await n.run(v.id).get(),!Wn.includes(v.status));)await new Promise(e=>{setTimeout(e,1e3)});p||(v.status===N.SUCCEEDED?success({message:`${l} finished.`}):v.status===N.RUNNING?warning({message:`${l} is still running!`}):v.status===N.ABORTED||v.status===N.ABORTING?(warning({message:`${l} was aborted!`}),e.exitCode=3):(error({message:`${l} failed!`}),e.exitCode=1)),yield v}catch(e){i.e=e}finally{i.d()}}const SharedRunOnCloudFlags=e=>({build:Y.string({char:`b`,description:`Tag or number of the build to run (e.g. "latest" or "1.2.34").`,required:!1}),timeout:Y.integer({char:`t`,description:`Timeout for the ${e} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:Y.integer({char:`m`,description:`Amount of memory allocated for the ${e} run, in megabytes.`,required:!1})});var Gn=class ActorsCallCommand extends ApifyCommand{static name=`call`;static description=`Executes Actor remotely using your authenticated account.
86
+ 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={...SharedRunOnCloudFlags(`Actor`),input:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.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:Y.boolean({char:`s`,description:`Prevents printing the logs of the Actor run to the console.`,default:!1}),"output-dataset":Y.boolean({char:`o`,description:`Prints out the entire default dataset on successful run of the Actor.`})};static enableJsonFlag=!0;static args={actorId:Z.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 '${W}' file.`})};async run(){let n=e.cwd(),r=getLocalConfig(n)||{},i=await getLoggedClientOrThrow(),a=await getLocalUserInfo(),s=a.username||a.id;if(this.flags.json&&this.flags.outputDataset){error({message:`You cannot use both the --json and --output-dataset flags when running this command.`}),e.exitCode=5;return}let{id:c,userFriendlyId:l,actorData:u}=await ActorsCallCommand.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={waitForFinish:2};this.flags.build&&(f.build=this.flags.build),this.flags.timeout&&(f.timeout=this.flags.timeout),this.flags.memory&&(f.memory=this.flags.memory);let p=await getInputOverride(n,this.flags.input,this.flags.inputFile);if(p===!1)return;let m=!1,h,g,_,v=runActorOrTaskOnCloud(i,{actorOrTaskData:{id:c,userFriendlyId:l},runOptions:f,type:`Actor`,inputOverride:p?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0});for await(let e of v)if(h=e,!m&&(m=!0,!this.flags.silent)){g=`https://console.apify.com/actors/${c}/runs/${e.id}`,_=`https://console.apify.com/storage/datasets/${e.defaultDatasetId}`;let n=[`${t.yellow(`Started`)}: ${G.display(e.startedAt)}`];e.containerUrl&&n.push(`${t.yellow(`Container URL`)}: ${t.blue(e.containerUrl)}`);let r=h.buildNumber.split(`.`).slice(0,2).join(`.`),i=u.versions.find(e=>e.versionNumber===r),a=Object.entries(u.taggedBuilds??{}).find(([,t])=>t.buildNumber===e.buildNumber)?.[0],s=[`${t.yellow(`Build`)}:`,t.cyan(h.buildNumber)];a?s.push(`(${t.yellow(a)})`):s.push(`(${t.gray(`N/A`)})`),i&&s.push(`| ${t.gray(`Actor version:`)} ${t.cyan(i.versionNumber)} (${t.yellow(i.buildTag)})`),n.push(s.join(` `)),n.push(`${t.yellow(`Timeout`)}: ${h.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),n.push(`${t.yellow(`Memory`)}: ${h.options.memoryMbytes} MB`),n.push(`${t.blue(`View on Apify Console`)}: ${g}`,``),simpleLog({message:n.join(`
87
87
  `),stdout:!this.flags.json})}if(this.flags.json){printJsonToStdout(h);return}if(this.flags.silent||simpleLog({message:[``,`${t.blue(`Export results`)}: ${_}`,`${t.blue(`View on Apify Console`)}: ${g}`].join(`
88
- `),stdout:!0}),this.flags.outputDataset){let e=h.defaultDatasetId,t,n=4;do{if(t=await i.dataset(e).get(),t?.itemCount)break;await new Promise(e=>{setTimeout(e,250)})}while(n--);let r=await i.dataset(e).downloadItems(z.JSON,{clean:!0});console.log(r.toString())}}static async resolveActorId({client:e,localActorName:t,usernameOrId:n,providedActorNameOrId:r}){if(r?.includes(`/`)){let t=await e.actor(r).get();if(!t)throw Error(`Cannot find Actor with ID '${r}' in your account.`);return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t}}if(r){let t=await e.actor(r).get();if(t)return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t};let i=await e.actor(`${n}/${r.toLowerCase()}`).get();if(i)return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i};throw Error(`Cannot find Actor with name or ID '${r}' in your account.`)}if(t){let r=await e.actor(`${n}/${t}`).get();if(!r)throw Error(`Cannot find Actor with ID '${n}/${t}' in your account. Call "apify push" to push this Actor to Apify platform.`);return{userFriendlyId:`${r.username}/${r.name}`,id:r.id,actorData:r}}throw Error(`Please provide an Actor ID or name, or run this command from a directory with a valid Apify Actor.`)}};const Kn={[-1]:void 0,0:{mid:``,"left-mid":``,"mid-mid":``,"right-mid":``,middle:` `,"top-mid":`─`,"bottom-mid":`─`},1:{middle:` `,"top-mid":`─`,"bottom-mid":`─`,top:`─`,bottom:`─`,"left-mid":`├`,mid:`─`,"mid-mid":`─`,"right-mid":`┤`},2:{left:``,right:``,mid:``,"bottom-left":``,"bottom-mid":``,"bottom-right":``,top:``,"top-left":``,"top-mid":``,"top-right":``,"left-mid":``,"mid-mid":``,"right-mid":``,bottom:``,middle:` `}};function generateHeaderColors(e){return Array.from({length:e},()=>`cyan`)}const qn=process.stdout.columns??100,Jn=Symbol.for(`@apify/cli:responsive-table:skip-column`);var Q=class ResponsiveTable{options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=ResponsiveTable.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,n=generateHeaderColors(t.length),r=e===0||e===2,i=Kn[e],a=[],s=[],c=[];for(let e of t)this.options.hiddenColumns?.includes(e)||this.rows.some(t=>t[e]===Jn)||(a.push(this.options.columnAlignments?.[e]||`left`),ResponsiveTable.isSmallTerminal()?(s.push(this.options.breakpointOverrides?.small?.[e]?.label??e),c.push(this.options.breakpointOverrides?.small?.[e]?.valueFrom??e)):(s.push(e),c.push(e)));let l=new Tt({head:s,style:{head:n,compact:r},colAligns:a,chars:i});for(let e of this.rows){let t=c.map(t=>e[t]);l.push(t)}return l.toString()}static isSmallTerminal(){return qn<100}};const Yn=`​​`,Xn=new Q({allColumns:[`​`,Yn],mandatoryColumns:[`​`,Yn],columnAlignments:{"​":`left`,[Yn]:`right`}});var ActorsInfoCommand=class extends ApifyCommand{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:Y.boolean({description:`Return the Actor README.`,exclusive:[`input`]}),input:Y.boolean({description:`Return the Actor input schema.`,exclusive:[`readme`]})};static args={actorId:Z.string({description:`The ID of the Actor to return information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:n,input:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),s=await resolveActorContext({providedActorNameOrId:e,client:a});if(!s.valid){error({message:`${s.reason}. Please specify the Actor ID.`,stdout:!0});return}let c=await a.actor(s.id).get();c.actorMaker=await a.user(c.userId).get();for(let e of Object.values(c.taggedBuilds??{}))e.buildId&&(e.build=await a.build(e.buildId).get());if(i){printJsonToStdout(c);return}let l=c.taggedBuilds?.latest;if(n){if(!l){error({message:`No README found for this Actor.`,stdout:!0});return}if(!l.build?.readme){error({message:`No README found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.readme,stdout:!0});return}if(r){if(!l){error({message:`No input schema found for this Actor.`,stdout:!0});return}if(!l.build?.inputSchema){error({message:`No input schema found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.inputSchema,stdout:!0});return}let u=[`Information about Actor ${t.yellow(`${c.username}/${c.name}`)} (${t.gray(c.id)})`,``];c.title&&u.push(`${t.yellow(`Title:`)} ${t.bold(c.title)}`),c.description&&u.push(`${t.yellow(`Description:`)} ${c.description}`),u.push(`${t.yellow(`Created at:`)} ${t.cyan(G.display(c.createdAt))} ${t.gray(`|`)} ${t.yellow(`Updated at:`)} ${t.cyan(G.display(c.modifiedAt))}`),c.actorMaker&&(u.push(``,`${t.yellow(`Made by:`)} ${t.cyan(c.actorMaker.profile.name??c.actorMaker.username)}`),Reflect.get(c,`isCritical`)&&(u[u.length-1]+=` ${t.bgGray(`Maintained by Apify`)}`)),c.isPublic?u.push(``,`${t.yellow(`Actor is`)} ${t.green(`PUBLIC`)}`):u.push(``,`${t.yellow(`Actor is`)} ${t.cyan(`PRIVATE`)}`),c.isDeprecated&&u.push(``,`${t.yellow(`Actor is`)} ${t.red(`DEPRECATED`)}`);let f=Reflect.get(c,`pricingInfos`);if(f?.length){let e=f.at(-1);switch(e.pricingModel){case`FLAT_PRICE_PER_MONTH`:if(u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${e.pricePerUnitUsd}/month + usage`)}`),e.trialMinutes){let n=e.trialMinutes*60*1e3,r=Sn.format(n);u.push(` ${t.yellow(`Trial duration:`)} ${t.bold(r)}`)}break;case`PRICE_PER_DATASET_ITEM`:{let n=e.pricePerUnitUsd*1e3;u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${n.toFixed(2)} / 1,000 results`)}`);break}case`PAY_PER_EVENT`:{u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay per event`)}`);let n=Object.values(e.pricingPerEvent?.actorChargeEvents??{});for(let e of n)Xn.pushRow({"​":e.eventTitle,[Yn]:t.bold(`$${e.eventPriceUsd.toFixed(2)}`)});let r=Xn.render(0).split(`
88
+ `),stdout:!0}),this.flags.outputDataset){let e=h.defaultDatasetId,t,n=4;do{if(t=await i.dataset(e).get(),t?.itemCount)break;await new Promise(e=>{setTimeout(e,250)})}while(n--);let r=await i.dataset(e).downloadItems(V.JSON,{clean:!0});console.log(r.toString())}}static async resolveActorId({client:e,localActorName:t,usernameOrId:n,providedActorNameOrId:r}){if(r?.includes(`/`)){let t=await e.actor(r).get();if(!t)throw Error(`Cannot find Actor with ID '${r}' in your account.`);return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t}}if(r){let t=await e.actor(r).get();if(t)return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t};let i=await e.actor(`${n}/${r.toLowerCase()}`).get();if(i)return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i};throw Error(`Cannot find Actor with name or ID '${r}' in your account.`)}if(t){let r=await e.actor(`${n}/${t}`).get();if(!r)throw Error(`Cannot find Actor with ID '${n}/${t}' in your account. Call "apify push" to push this Actor to Apify platform.`);return{userFriendlyId:`${r.username}/${r.name}`,id:r.id,actorData:r}}throw Error(`Please provide an Actor ID or name, or run this command from a directory with a valid Apify Actor.`)}};const Kn={[-1]:void 0,0:{mid:``,"left-mid":``,"mid-mid":``,"right-mid":``,middle:` `,"top-mid":`─`,"bottom-mid":`─`},1:{middle:` `,"top-mid":`─`,"bottom-mid":`─`,top:`─`,bottom:`─`,"left-mid":`├`,mid:`─`,"mid-mid":`─`,"right-mid":`┤`},2:{left:``,right:``,mid:``,"bottom-left":``,"bottom-mid":``,"bottom-right":``,top:``,"top-left":``,"top-mid":``,"top-right":``,"left-mid":``,"mid-mid":``,"right-mid":``,bottom:``,middle:` `}};function generateHeaderColors(e){return Array.from({length:e},()=>`cyan`)}const qn=process.stdout.columns??100,Jn=Symbol.for(`@apify/cli:responsive-table:skip-column`);var Q=class ResponsiveTable{options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=ResponsiveTable.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,n=generateHeaderColors(t.length),r=e===0||e===2,i=Kn[e],a=[],s=[],c=[];for(let e of t)this.options.hiddenColumns?.includes(e)||this.rows.some(t=>t[e]===Jn)||(a.push(this.options.columnAlignments?.[e]||`left`),ResponsiveTable.isSmallTerminal()?(s.push(this.options.breakpointOverrides?.small?.[e]?.label??e),c.push(this.options.breakpointOverrides?.small?.[e]?.valueFrom??e)):(s.push(e),c.push(e)));let l=new wt({head:s,style:{head:n,compact:r},colAligns:a,chars:i});for(let e of this.rows){let t=c.map(t=>e[t]);l.push(t)}return l.toString()}static isSmallTerminal(){return qn<100}};const Yn=`​​`,Xn=new Q({allColumns:[`​`,Yn],mandatoryColumns:[`​`,Yn],columnAlignments:{"​":`left`,[Yn]:`right`}});var ActorsInfoCommand=class extends ApifyCommand{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:Y.boolean({description:`Return the Actor README.`,exclusive:[`input`]}),input:Y.boolean({description:`Return the Actor input schema.`,exclusive:[`readme`]})};static args={actorId:Z.string({description:`The ID of the Actor to return information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:n,input:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),s=await resolveActorContext({providedActorNameOrId:e,client:a});if(!s.valid){error({message:`${s.reason}. Please specify the Actor ID.`,stdout:!0});return}let c=await a.actor(s.id).get();c.actorMaker=await a.user(c.userId).get();for(let e of Object.values(c.taggedBuilds??{}))e.buildId&&(e.build=await a.build(e.buildId).get());if(i){printJsonToStdout(c);return}let l=c.taggedBuilds?.latest;if(n){if(!l){error({message:`No README found for this Actor.`,stdout:!0});return}if(!l.build?.readme){error({message:`No README found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.readme,stdout:!0});return}if(r){if(!l){error({message:`No input schema found for this Actor.`,stdout:!0});return}if(!l.build?.inputSchema){error({message:`No input schema found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.inputSchema,stdout:!0});return}let u=[`Information about Actor ${t.yellow(`${c.username}/${c.name}`)} (${t.gray(c.id)})`,``];c.title&&u.push(`${t.yellow(`Title:`)} ${t.bold(c.title)}`),c.description&&u.push(`${t.yellow(`Description:`)} ${c.description}`),u.push(`${t.yellow(`Created at:`)} ${t.cyan(G.display(c.createdAt))} ${t.gray(`|`)} ${t.yellow(`Updated at:`)} ${t.cyan(G.display(c.modifiedAt))}`),c.actorMaker&&(u.push(``,`${t.yellow(`Made by:`)} ${t.cyan(c.actorMaker.profile.name??c.actorMaker.username)}`),Reflect.get(c,`isCritical`)&&(u[u.length-1]+=` ${t.bgGray(`Maintained by Apify`)}`)),c.isPublic?u.push(``,`${t.yellow(`Actor is`)} ${t.green(`PUBLIC`)}`):u.push(``,`${t.yellow(`Actor is`)} ${t.cyan(`PRIVATE`)}`),c.isDeprecated&&u.push(``,`${t.yellow(`Actor is`)} ${t.red(`DEPRECATED`)}`);let f=Reflect.get(c,`pricingInfos`);if(f?.length){let e=f.at(-1);switch(e.pricingModel){case`FLAT_PRICE_PER_MONTH`:if(u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${e.pricePerUnitUsd}/month + usage`)}`),e.trialMinutes){let n=e.trialMinutes*60*1e3,r=Sn.format(n);u.push(` ${t.yellow(`Trial duration:`)} ${t.bold(r)}`)}break;case`PRICE_PER_DATASET_ITEM`:{let n=e.pricePerUnitUsd*1e3;u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${n.toFixed(2)} / 1,000 results`)}`);break}case`PAY_PER_EVENT`:{u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay per event`)}`);let n=Object.values(e.pricingPerEvent?.actorChargeEvents??{});for(let e of n)Xn.pushRow({"​":e.eventTitle,[Yn]:t.bold(`$${e.eventPriceUsd.toFixed(2)}`)});let r=Xn.render(0).split(`
89
89
  `);r.splice(1,1),u.push(r.join(`
90
90
  `));break}case`FREE`:u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);break;default:u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Unknown pricing model (${t.yellow(e.pricingModel)})`)}`)}}else u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);if((c.seoTitle||c.seoDescription)&&(u.push(``,t.yellow(`SEO information:`)),c.seoTitle&&u.push(` ${t.yellow(`Title:`)} ${c.seoTitle}`),c.seoDescription&&u.push(` ${t.yellow(`Description:`)} ${c.seoDescription}`)),c.taggedBuilds){u.push(``,t.yellow(`Builds:`));let e=c.taggedBuilds.latest;e&&u.push(` ${t.yellow(`-`)} ${t.cyan(e.buildNumber)} ${t.gray(`/`)} ${t.yellow(`latest`)}`);for(let[e,n]of Object.entries(c.taggedBuilds))e!==`latest`&&u.push(` ${t.yellow(`-`)} ${t.cyan(n.buildNumber)} ${t.gray(`/`)} ${t.yellow(e)}`)}simpleLog({message:u.join(`
91
- `),stdout:!0})}};function prettyPrintStatus(e){switch(e){case`READY`:return t.green(`Ready`);case`RUNNING`:return t.blue(`Running`);case`SUCCEEDED`:return t.green(`Succeeded`);case`FAILED`:return t.red(`Failed`);case`ABORTING`:return t.yellow(`Aborting`);case`ABORTED`:return t.red(`Aborted`);case`TIMING-OUT`:return t.yellow(`Timing Out`);case`TIMED-OUT`:return t.red(`Timed Out`);default:return t.gray(e.split(`-`).map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(` `))}}const Zn={"TIMED-OUT":t.gray(`after`),"TIMING-OUT":t.gray(`after`),ABORTED:t.gray(`after`),ABORTING:t.gray(`after`),FAILED:t.gray(`after`),READY:t.gray(`for`),RUNNING:t.gray(`for`),SUCCEEDED:t.gray(`after`)},Qn=new Q({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`}}}}),$n=new Q({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`}}}});var ActorsLsCommand=class extends ApifyCommand{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:Y.boolean({description:`Whether to list Actors made by the logged in user.`,default:!1}),offset:Y.integer({description:`Number of Actors that will be skipped.`,default:0}),limit:Y.integer({description:`Number of Actors that will be listed.`,default:20}),desc:Y.boolean({description:`Sort Actors in descending order.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,my:i,json:a}=this.flags,s=await getLoggedClientOrThrow(),c=await s.actors().list({limit:n,offset:r,desc:e,my:i});if(c.count===0){if(a){printJsonToStdout(c);return}info({message:i?`You don't have any Actors yet!`:`There are no recent Actors used by you.`,stdout:!0});return}let l={...c,items:await Promise.all(c.items.map(async e=>{let t=await s.actor(e.id).get(),n=await s.actor(e.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...e,actor:t??null,lastRun:n.items[0]??null}}))};if(l.items=i?this.sortByModifiedAt(l.items):this.sortByLastRun(l.items),a){printJsonToStdout(l);return}let u=i?$n:Qn,f=l.items.reduce((e,t)=>{let n=`${t.username}/${t.name}`;return n.length>e?n.length:e},0)+2+6;for(let e of l.items){let n=e.stats.lastRunStartedAt?bn.display(e.stats.lastRunStartedAt):``,r=e.lastRun?(()=>{if(e.lastRun.finishedAt)return K.format(e.lastRun.finishedAt.getTime()-e.lastRun.startedAt.getTime());let t=Date.now()-e.lastRun.startedAt.getTime();return`${K.format(t)}…`})():``,i=e.actor?(()=>{let n=Object.entries(e.actor.taggedBuilds??{}).find(([t,n])=>n.buildNumber===e.actor.defaultRunOptions.build||t===e.actor.defaultRunOptions.build);return n?`${t.yellow(n[0])} / ${t.cyan(n[1].buildNumber??e.actor.defaultRunOptions.build)}`:t.gray(`Unknown`)})():t.gray(`Unknown`),a=(()=>{if(e.lastRun){let n=[prettyPrintStatus(e.lastRun.status)];if(r&&n.push(Zn[e.lastRun.status],t.cyan(r)),e.lastRun.finishedAt){let r=Date.now()-e.lastRun.finishedAt.getTime();r<Le.Week?n.push(`
91
+ `),stdout:!0})}};function prettyPrintStatus(e){switch(e){case`READY`:return t.green(`Ready`);case`RUNNING`:return t.blue(`Running`);case`SUCCEEDED`:return t.green(`Succeeded`);case`FAILED`:return t.red(`Failed`);case`ABORTING`:return t.yellow(`Aborting`);case`ABORTED`:return t.red(`Aborted`);case`TIMING-OUT`:return t.yellow(`Timing Out`);case`TIMED-OUT`:return t.red(`Timed Out`);default:return t.gray(e.split(`-`).map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(` `))}}const Zn={"TIMED-OUT":t.gray(`after`),"TIMING-OUT":t.gray(`after`),ABORTED:t.gray(`after`),ABORTING:t.gray(`after`),FAILED:t.gray(`after`),READY:t.gray(`for`),RUNNING:t.gray(`for`),SUCCEEDED:t.gray(`after`)},Qn=new Q({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`}}}}),$n=new Q({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`}}}});var ActorsLsCommand=class extends ApifyCommand{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:Y.boolean({description:`Whether to list Actors made by the logged in user.`,default:!1}),offset:Y.integer({description:`Number of Actors that will be skipped.`,default:0}),limit:Y.integer({description:`Number of Actors that will be listed.`,default:20}),desc:Y.boolean({description:`Sort Actors in descending order.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,my:i,json:a}=this.flags,s=await getLoggedClientOrThrow(),c=await s.actors().list({limit:n,offset:r,desc:e,my:i});if(c.count===0){if(a){printJsonToStdout(c);return}info({message:i?`You don't have any Actors yet!`:`There are no recent Actors used by you.`,stdout:!0});return}let l={...c,items:await Promise.all(c.items.map(async e=>{let t=await s.actor(e.id).get(),n=await s.actor(e.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...e,actor:t??null,lastRun:n.items[0]??null}}))};if(l.items=i?this.sortByModifiedAt(l.items):this.sortByLastRun(l.items),a){printJsonToStdout(l);return}let u=i?$n:Qn,f=l.items.reduce((e,t)=>{let n=`${t.username}/${t.name}`;return n.length>e?n.length:e},0)+2+6;for(let e of l.items){let n=e.stats.lastRunStartedAt?bn.display(e.stats.lastRunStartedAt):``,r=e.lastRun?(()=>{if(e.lastRun.finishedAt)return K.format(e.lastRun.finishedAt.getTime()-e.lastRun.startedAt.getTime());let t=Date.now()-e.lastRun.startedAt.getTime();return`${K.format(t)}…`})():``,i=e.actor?(()=>{let n=Object.entries(e.actor.taggedBuilds??{}).find(([t,n])=>n.buildNumber===e.actor.defaultRunOptions.build||t===e.actor.defaultRunOptions.build);return n?`${t.yellow(n[0])} / ${t.cyan(n[1].buildNumber??e.actor.defaultRunOptions.build)}`:t.gray(`Unknown`)})():t.gray(`Unknown`),a=(()=>{if(e.lastRun){let n=[prettyPrintStatus(e.lastRun.status)];if(r&&n.push(Zn[e.lastRun.status],t.cyan(r)),e.lastRun.finishedAt){let r=Date.now()-e.lastRun.finishedAt.getTime();r<Ie.Week?n.push(`
92
92
  `,t.gray(`${K.format(r)} ago`)):n.push(`
93
- `,t.gray(`On`,xn.display(e.lastRun.finishedAt)))}return n.join(` `)}return``})();u.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Runs:Q.isSmallTerminal()&&f>=56?Jn:t.cyan(`${e.stats?.totalRuns??0}`),"Last run started at":n,"Last run":n,"Last run status":e.lastRun?prettyPrintStatus(e.lastRun.status):``,"Modified at":bn.display(e.modifiedAt),Builds:e.actor?t.cyan(e.actor.stats.totalBuilds):t.gray(`Unknown`),"Last run duration":Q.isSmallTerminal()?Jn:t.cyan(r),"Default build":i,_Small_LastRunText:a})}simpleLog({message:u.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((e,t)=>{let n=new Date(e.modifiedAt);return new Date(t.modifiedAt).getTime()-n.getTime()})}sortByLastRun(e){return e.sort((e,t)=>{let n=new Date(e.stats?.lastRunStartedAt??`1970-01-01T00:00Z`);return new Date(t.stats?.lastRunStartedAt??`1970-01-01T00:00Z`).getTime()-n.getTime()})}};const extractGitHubZip=async(e,t)=>{let{data:n}=await We.get(e,{responseType:`arraybuffer`}),r=new Be(Buffer.from(n,`binary`));r.extractEntryTo(r.getEntries()[0].entryName,t,!1)};var ActorsPullCommand=class extends ApifyCommand{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:Y.string({char:`v`,description:`Actor version number which will be pulled, e.g. 1.2. Default: the highest version.`,required:!1}),dir:Y.string({description:`Directory where the Actor should be pulled to.`,required:!1})};static args={actorId:Z.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 t=e.cwd(),n=await useActorConfig({cwd:t});if(n.isErr()){error({message:n.unwrapErr().message}),e.exitCode=5;return}let{config:r}=n.unwrap(),i=await getLocalUserInfo(),a=await getLoggedClientOrThrow(),s=!this.args.actorId,c=i.username||i.id,u=this.args?.actorId||r?.id||(r?.name?`${c}/${r.name}`:void 0);if(!u)throw Error(`Cannot find Actor in this directory.`);let f;try{f=await a.actor(u).get()}catch{throw Error(`Cannot find Actor with ID/name '${u}' in your account.`)}if(!f)throw Error(`Cannot find Actor with ID/name '${u}' in your account.`);let{name:p,versions:m}=f,throwMissingSourceCodeAccessError=()=>{throw Error(`You cannot pull source code of this Actor because you do not have permission to do so.`)};if(!f.versions.length)throw Error(`Actor ${u} has no versions.`);let h=null;if(this.flags.version&&(h=m.find(e=>e.versionNumber===this.flags.version),!h))throw Error(`Cannot find version ${this.flags.version} of Actor ${u}.`);h||=m.reduce((e,t)=>l(`${t.versionNumber}.0`,`${e.versionNumber}.0`)?t:e);let g=s?t:k(t,this.flags.dir??p);if(b(g,{recursive:!0}),!s&&C(g).length!==0){error({message:`Directory ${g} is not empty. Please empty it or choose another directory.`});return}let{sourceType:_}=h;switch(_){case`TARBALL`:h.tarballUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(h.tarballUrl,g);break;case`SOURCE_FILES`:{h.sourceFiles||throwMissingSourceCodeAccessError();let{sourceFiles:e}=h;for(let t of e)if(b(`${g}/${O(t.name)}`,{recursive:!0}),!t.folder){let e=t.format===`BASE64`?Buffer.from(t.content,`base64`).toString():t.content;if(t.name===U){let n=Et.parse(e);n.name=f.name,E(`${g}/${t.name}`,Et.update(e,n))}else E(`${g}/${t.name}`,e)}break}case`GIT_REPO`:{h.gitRepoUrl||throwMissingSourceCodeAccessError();let{gitRepoUrl:e}=h,[t,n]=e.split(`#`),r,i;n&&([r,i]=n.split(`:`));let a=t;i&&(a+=`/${i}`),r&&(a+=`#${r}`);let s=Dt(a);try{await s.clone(g)}catch(t){throw Error(`Failed to pull Actor from ${e}. ${t.message}`)}break}case`GITHUB_GIST`:h.gitHubGistUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(`${h.gitHubGistUrl}/archive/master.zip`,g);break;default:throw Error(`Unknown source type: ${_}`)}success({message:s?`Actor ${p} updated at ${g}/`:`Pulled to ${g}/`})}};const er=5e4,getSecretsFile=()=>{try{return JSON.parse(S(SECRETS_FILE_PATH(),`utf-8`))||{}}catch{return{}}},writeSecretsFile=e=>(ensureApifyDirectory(SECRETS_FILE_PATH()),E(SECRETS_FILE_PATH(),JSON.stringify(e,null,` `)),e),addSecret=(e,t)=>{let n=getSecretsFile();if(n[e])throw Error(`Secret with name ${e} already exists. Call "apify secrets rm ${e}" to remove it.`);if(typeof e!=`string`||e.length>100)throw Error(`Secret name has to be string with maximum length 100.`);if(typeof t!=`string`||t.length>er)throw Error(`Secret value has to be string with maximum length ${er}.`);return n[e]=t,writeSecretsFile(n)},removeSecret=e=>{let t=getSecretsFile();if(!t[e])throw Error(`Secret with name ${e} doesn't exist.`);delete t[e],writeSecretsFile(t)},isSecretKey=e=>RegExp(`^@.{1}`).test(e),replaceSecretsValue=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r={},i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(RegExp(`^@`),``);t[a]?r[n]=t[a]:i.push(a)}else r[n]=e[n]}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
93
+ `,t.gray(`On`,xn.display(e.lastRun.finishedAt)))}return n.join(` `)}return``})();u.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Runs:Q.isSmallTerminal()&&f>=56?Jn:t.cyan(`${e.stats?.totalRuns??0}`),"Last run started at":n,"Last run":n,"Last run status":e.lastRun?prettyPrintStatus(e.lastRun.status):``,"Modified at":bn.display(e.modifiedAt),Builds:e.actor?t.cyan(e.actor.stats.totalBuilds):t.gray(`Unknown`),"Last run duration":Q.isSmallTerminal()?Jn:t.cyan(r),"Default build":i,_Small_LastRunText:a})}simpleLog({message:u.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((e,t)=>{let n=new Date(e.modifiedAt);return new Date(t.modifiedAt).getTime()-n.getTime()})}sortByLastRun(e){return e.sort((e,t)=>{let n=new Date(e.stats?.lastRunStartedAt??`1970-01-01T00:00Z`);return new Date(t.stats?.lastRunStartedAt??`1970-01-01T00:00Z`).getTime()-n.getTime()})}};const extractGitHubZip=async(e,t)=>{let{data:n}=await He.get(e,{responseType:`arraybuffer`}),r=new Re(Buffer.from(n,`binary`));r.extractEntryTo(r.getEntries()[0].entryName,t,!1)};var ActorsPullCommand=class extends ApifyCommand{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:Y.string({char:`v`,description:`Actor version number which will be pulled, e.g. 1.2. Default: the highest version.`,required:!1}),dir:Y.string({description:`Directory where the Actor should be pulled to.`,required:!1})};static args={actorId:Z.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 t=e.cwd(),n=await useActorConfig({cwd:t});if(n.isErr()){error({message:n.unwrapErr().message}),e.exitCode=5;return}let{config:r}=n.unwrap(),i=await getLocalUserInfo(),a=await getLoggedClientOrThrow(),s=!this.args.actorId,c=i.username||i.id,u=this.args?.actorId||r?.id||(r?.name?`${c}/${r.name}`:void 0);if(!u)throw Error(`Cannot find Actor in this directory.`);let f;try{f=await a.actor(u).get()}catch{throw Error(`Cannot find Actor with ID/name '${u}' in your account.`)}if(!f)throw Error(`Cannot find Actor with ID/name '${u}' in your account.`);let{name:p,versions:m}=f,throwMissingSourceCodeAccessError=()=>{throw Error(`You cannot pull source code of this Actor because you do not have permission to do so.`)};if(!f.versions.length)throw Error(`Actor ${u} has no versions.`);let h=null;if(this.flags.version&&(h=m.find(e=>e.versionNumber===this.flags.version),!h))throw Error(`Cannot find version ${this.flags.version} of Actor ${u}.`);h||=m.reduce((e,t)=>l(`${t.versionNumber}.0`,`${e.versionNumber}.0`)?t:e);let g=s?t:A(t,this.flags.dir??p);if(b(g,{recursive:!0}),!s&&C(g).length!==0){error({message:`Directory ${g} is not empty. Please empty it or choose another directory.`});return}let{sourceType:_}=h;switch(_){case`TARBALL`:h.tarballUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(h.tarballUrl,g);break;case`SOURCE_FILES`:{h.sourceFiles||throwMissingSourceCodeAccessError();let{sourceFiles:e}=h;for(let t of e)if(b(`${g}/${k(t.name)}`,{recursive:!0}),!t.folder){let e=t.format===`BASE64`?Buffer.from(t.content,`base64`).toString():t.content;if(t.name===W){let n=Tt.parse(e);n.name=f.name,D(`${g}/${t.name}`,Tt.update(e,n))}else D(`${g}/${t.name}`,e)}break}case`GIT_REPO`:{h.gitRepoUrl||throwMissingSourceCodeAccessError();let{gitRepoUrl:e}=h,[t,n]=e.split(`#`),r,i;n&&([r,i]=n.split(`:`));let a=t;i&&(a+=`/${i}`),r&&(a+=`#${r}`);let s=Et(a);try{await s.clone(g)}catch(t){throw Error(`Failed to pull Actor from ${e}. ${t.message}`)}break}case`GITHUB_GIST`:h.gitHubGistUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(`${h.gitHubGistUrl}/archive/master.zip`,g);break;default:throw Error(`Unknown source type: ${_}`)}success({message:s?`Actor ${p} updated at ${g}/`:`Pulled to ${g}/`})}};const er=5e4,getSecretsFile=()=>{try{return JSON.parse(S(SECRETS_FILE_PATH(),`utf-8`))||{}}catch{return{}}},writeSecretsFile=e=>(ensureApifyDirectory(SECRETS_FILE_PATH()),D(SECRETS_FILE_PATH(),JSON.stringify(e,null,` `)),e),addSecret=(e,t)=>{let n=getSecretsFile();if(n[e])throw Error(`Secret with name ${e} already exists. Call "apify secrets rm ${e}" to remove it.`);if(typeof e!=`string`||e.length>100)throw Error(`Secret name has to be string with maximum length 100.`);if(typeof t!=`string`||t.length>er)throw Error(`Secret value has to be string with maximum length ${er}.`);return n[e]=t,writeSecretsFile(n)},removeSecret=e=>{let t=getSecretsFile();if(!t[e])throw Error(`Secret with name ${e} doesn't exist.`);delete t[e],writeSecretsFile(t)},isSecretKey=e=>RegExp(`^@.{1}`).test(e),replaceSecretsValue=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r={},i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(RegExp(`^@`),``);t[a]?r[n]=t[a]:i.push(a)}else r[n]=e[n]}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
94
94
  `);if(n)for(let e of i)warning({message:`Value for ${e} not found in local secrets. Set it by calling "apify secrets add ${e} [SECRET_VALUE]"`});else throw Error(`The following secrets are missing:\n${e}\n\nSet them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
95
95
  If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},transformEnvToEnvVars=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r=[],i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(RegExp(`^@`),``);t[a]?r.push({name:n,value:t[a],isSecret:!0}):i.push(a)}else r.push({name:n,value:e[n]})}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
96
96
  `);if(n)for(let e of i)warning({message:`Value for ${e} not found in local secrets. Set it by calling "apify secrets add ${e} [SECRET_VALUE]"`});else throw Error(`The following secrets are missing:\n${e}\n\nSet them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
97
- If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},tr=`temp_file.zip`,nr={build:`latest`,memoryMbytes:4096,timeoutSecs:3600};var ActorsPushCommand=class extends ApifyCommand{static name=`push`;static description=`Deploys Actor to Apify platform using settings from '${U}'.\nFiles under '${ve/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
97
+ If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},tr=`temp_file.zip`,nr={build:`latest`,memoryMbytes:4096,timeoutSecs:3600};var ActorsPushCommand=class extends ApifyCommand{static name=`push`;static description=`Deploys Actor to Apify platform using settings from '${W}'.\nFiles under '${_e/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
98
98
  Files matched by .gitignore and .actorignore are excluded. Use negation patterns (e.g. !dist/) in .actorignore to force-include git-ignored files.
99
- 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:Y.string({char:`v`,description:`Actor version number to which the files should be pushed. By default, it is taken from the '${U}' file.`,required:!1}),"build-tag":Y.string({char:`b`,description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${U}' file.`,required:!1}),"wait-for-finish":Y.string({char:`w`,description:`Seconds for waiting to build to finish, if no value passed, it waits forever.`,required:!1}),open:Y.boolean({description:`Whether to open the browser automatically to the Actor details page.`,default:!1,required:!1}),force:Y.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:Y.string({description:`Directory where the Actor is located.`,required:!1}),"allow-missing-secrets":Y.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:Z.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 '${U}' file.`})};async run(){let t=A(e.cwd(),this.flags.dir??`.`),n=await getActorLocalFilePaths(t);if(!n.length){error({message:`You need to call this command from a folder that has an Actor in it!`}),e.exitCode=4;return}if(![`apify.json`,`actor.json`,`.actor/actor.json`,`.actor`].some(e=>n.some(t=>t===e||t.startsWith(e)))){error({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(`
100
- `)}),e.exitCode=4;return}let r=await getLoggedClientOrThrow(),i=await useActorConfig({cwd:t});if(i.isErr()){error({message:i.unwrapErr().message}),e.exitCode=5;return}let{config:a}=i.unwrap(),s=await getLocalUserInfo(),c=s.organizationOwnerUserId?`/organization/${s.id}`:``,l,u,f=!1,p=this.flags.version||a?.version||`0.0`,m=this.flags.buildTag||a?.buildTag;!m&&p===`0.0`&&(m=`latest`);let h=Number.isNaN(this.flags.waitForFinish)?void 0:Number.parseInt(this.flags.waitForFinish,10)*1e3,g=this.args.actorId;if(g){if(u=await r.actor(g).get(),!u)throw Error(`Cannot find Actor with ID '${g}' in your account.`);l=u.id}else{let e=s.username||s.id;if(u=await r.actor(`${e}/${a.name}`).get(),u)l=u.id;else{let{templates:e}=await kt(),t=e.find(e=>e.name===a.template)?.defaultRunOptions||nr,n={name:a.name,title:a.title,description:a.description,defaultRunOptions:t,versions:[{versionNumber:p,buildTag:m,sourceType:me.SOURCE_FILES,sourceFiles:[]}]};a.usesStandbyMode&&(n.actorStandby={isEnabled:!0}),u=await r.actors().create(n),l=u.id,f=!0,info({message:`Created Actor with name ${a.name} on Apify.`})}}let _=r.actor(l);info({message:`Deploying Actor '${a.name}' to Apify.`});let v=await sumFilesSizeInBytes(n,t),y,b,x;if(v<ve){let e=await _.get();if(!f){let r=n.reduce((e,n)=>{let{mtimeMs:r,ctimeMs:i}=te(k(t,n)),a=r>i?r:i;return e>a?e:a},0),i=e?.modifiedAt.valueOf();if(!this.flags.force&&i&&r<i&&(a?.name||g))throw Error(`Actor with identifier "${a?.name||g}" is already on the platform and was modified there since modified locally.
101
- Skipping push. Use --force to override.`)}b=await createSourceFiles(n,t),y=me.SOURCE_FILES}else{run({message:`Zipping Actor files`}),await createActZip(tr,n,t);let e=await r.keyValueStores().getOrCreate(`actor-${l}-source`),i=`version-${p}.zip`,a=S(tr);await r.keyValueStore(e.id).setRecord({key:i,value:a,contentType:`application/zip`}),ne(tr);let s=new URL(`${r.baseUrl}/key-value-stores/${e.id}/records/${i}?disableRedirect=true`);if(e?.urlSigningSecretKey){let t=we(e.urlSigningSecretKey,i);s.searchParams.set(`signature`,t)}x=s.toString(),y=me.TARBALL}let C=await _.version(p).get(),w=a.environmentVariables?transformEnvToEnvVars(a.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(C){let e={tarballUrl:x,sourceFiles:b,buildTag:m,sourceType:y,envVars:w};await _.version(p).update(e),run({message:`Updated version ${p} for Actor ${u.name}.`})}else{let e={versionNumber:p,tarballUrl:x,sourceFiles:b,buildTag:m,sourceType:y,envVars:w};await _.versions().create({...e}),run({message:`Created version ${p} for Actor ${u.name}.`})}if(!f&&!!a.usesStandbyMode!=!!u.actorStandby?.isEnabled){let e=!!a.usesStandbyMode;await _.update({actorStandby:{isEnabled:e}}),info({message:`${e?`Enabled`:`Disabled`} standby mode for Actor ${u.name}.`})}run({message:`Building Actor ${u.name}`});let T=await _.build(p,{useCache:!0,waitForFinish:2});try{try{var ee=_usingCtx();ee.u(useAbortJobOnSignal({apifyClient:r,kind:`build`,jobId:T.id})),await outputJobLog({job:T,timeoutMillis:h,apifyClient:r})}catch(e){ee.e=e}finally{ee.d()}}catch(e){warning({message:`Can not get log:`}),console.error(e)}if(T=await r.build(T.id).get(),this.flags.json){printJsonToStdout(T);return}link({message:`Actor build detail`,url:`https://console.apify.com${c}/actors/${T.actId}#/builds/${T.buildNumber}`}),link({message:`Actor detail`,url:`https://console.apify.com${c}/actors/${T.actId}`}),this.flags.open&&await Ot(`https://console.apify.com${c}/actors/${T.actId}`),T.status===M.SUCCEEDED?success({message:`Actor was deployed to Apify cloud and built there.`}):T.status===M.READY?warning({message:`Build is waiting for allocation.`}):T.status===M.RUNNING?warning({message:`Build is still running.`}):T.status===M.ABORTED||T.status===M.ABORTING?(warning({message:`Build was aborted!`}),e.exitCode=3):T.status===M.TIMED_OUT||T.status===M.TIMING_OUT?(warning({message:`Build timed out!`}),e.exitCode=2):(error({message:`Build failed!`}),e.exitCode=1)}},ActorsRmCommand=class extends ApifyCommand{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:Z.string({description:`The Actor ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{actorId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow();if(!await n.actor(e).get()){error({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await X({message:`Are you sure you want to delete this Actor?`,providedConfirmFromStdin:t||void 0})){info({message:`Deletion of Actor "${e}" was canceled.`});return}try{await n.actor(e).delete(),success({message:`Actor with ID "${e}" was deleted.`})}catch(t){let n=t;error({message:`Failed to delete Actor "${e}".\n ${n.message||n}`})}}};const rr={FREE:`Free`,FLAT_PRICE_PER_MONTH:`Subscription`,PRICE_PER_DATASET_ITEM:`Pay per result`,PAY_PER_EVENT:`Pay per event`};function formatPricingModel(e){return e?rr[e]??e:t.gray(`Unknown`)}function truncateDescription(e,t=60){return e?e.length<=t?e:`${e.slice(0,t-1)}…`:``}var ActorsSearchCommand=class extends ApifyCommand{static name=`search`;static description=`Searches Actors in the Apify Store.
99
+ 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:Y.string({char:`v`,description:`Actor version number to which the files should be pushed. By default, it is taken from the '${W}' file.`,required:!1}),"build-tag":Y.string({char:`b`,description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${W}' file.`,required:!1}),"wait-for-finish":Y.string({char:`w`,description:`Seconds for waiting to build to finish, if no value passed, it waits forever.`,required:!1}),open:Y.boolean({description:`Whether to open the browser automatically to the Actor details page.`,default:!1,required:!1}),force:Y.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:Y.string({description:`Directory where the Actor is located.`,required:!1}),"allow-missing-secrets":Y.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:Z.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 '${W}' file.`})};async run(){let t=j(e.cwd(),this.flags.dir??`.`),n=await getActorLocalFilePaths(t);if(!n.length){error({message:`You need to call this command from a folder that has an Actor in it!`}),e.exitCode=4;return}if(![`apify.json`,`actor.json`,`.actor/actor.json`,`.actor`].some(e=>n.some(t=>t===e||t.startsWith(e)))){error({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(`
100
+ `)}),e.exitCode=4;return}let r=await getLoggedClientOrThrow(),i=await useActorConfig({cwd:t});if(i.isErr()){error({message:i.unwrapErr().message}),e.exitCode=5;return}let{config:a}=i.unwrap(),s=await getLocalUserInfo(),c=s.organizationOwnerUserId?`/organization/${s.id}`:``,l,u,f=!1,p=this.flags.version||a?.version||`0.0`,m=this.flags.buildTag||a?.buildTag;!m&&p===`0.0`&&(m=`latest`);let h=Number.isNaN(this.flags.waitForFinish)?void 0:Number.parseInt(this.flags.waitForFinish,10)*1e3,g=this.args.actorId;if(g){if(u=await r.actor(g).get(),!u)throw Error(`Cannot find Actor with ID '${g}' in your account.`);l=u.id}else{let e=s.username||s.id;if(u=await r.actor(`${e}/${a.name}`).get(),u)l=u.id;else{let{templates:e}=await Ot(),t=e.find(e=>e.name===a.template)?.defaultRunOptions||nr,n={name:a.name,title:a.title,description:a.description,defaultRunOptions:t,versions:[{versionNumber:p,buildTag:m,sourceType:pe.SOURCE_FILES,sourceFiles:[]}]};a.usesStandbyMode&&(n.actorStandby={isEnabled:!0}),u=await r.actors().create(n),l=u.id,f=!0,info({message:`Created Actor with name ${a.name} on Apify.`})}}let _=r.actor(l);info({message:`Deploying Actor '${a.name}' to Apify.`});let v=await sumFilesSizeInBytes(n,t),y,b,x;if(v<_e){let e=await _.get();if(!f){let r=n.reduce((e,n)=>{let{mtimeMs:r,ctimeMs:i}=E(A(t,n)),a=r>i?r:i;return e>a?e:a},0),i=e?.modifiedAt.valueOf();if(!this.flags.force&&i&&r<i&&(a?.name||g))throw Error(`Actor with identifier "${a?.name||g}" is already on the platform and was modified there since modified locally.
101
+ Skipping push. Use --force to override.`)}b=await createSourceFiles(n,t),y=pe.SOURCE_FILES}else{run({message:`Zipping Actor files`}),await createActZip(tr,n,t);let e=await r.keyValueStores().getOrCreate(`actor-${l}-source`),i=`version-${p}.zip`,a=S(tr);await r.keyValueStore(e.id).setRecord({key:i,value:a,contentType:`application/zip`}),te(tr);let s=new URL(`${r.baseUrl}/key-value-stores/${e.id}/records/${i}?disableRedirect=true`);if(e?.urlSigningSecretKey){let t=Ce(e.urlSigningSecretKey,i);s.searchParams.set(`signature`,t)}x=s.toString(),y=pe.TARBALL}let C=await _.version(p).get(),ee=a.environmentVariables?transformEnvToEnvVars(a.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(C){let e={tarballUrl:x,sourceFiles:b,buildTag:m,sourceType:y,envVars:ee};await _.version(p).update(e),run({message:`Updated version ${p} for Actor ${u.name}.`})}else{let e={versionNumber:p,tarballUrl:x,sourceFiles:b,buildTag:m,sourceType:y,envVars:ee};await _.versions().create({...e}),run({message:`Created version ${p} for Actor ${u.name}.`})}if(!f&&!!a.usesStandbyMode!=!!u.actorStandby?.isEnabled){let e=!!a.usesStandbyMode;await _.update({actorStandby:{isEnabled:e}}),info({message:`${e?`Enabled`:`Disabled`} standby mode for Actor ${u.name}.`})}run({message:`Building Actor ${u.name}`});let w=await _.build(p,{useCache:!0,waitForFinish:2});try{try{var T=_usingCtx();T.u(useAbortJobOnSignal({apifyClient:r,kind:`build`,jobId:w.id})),await outputJobLog({job:w,timeoutMillis:h,apifyClient:r})}catch(e){T.e=e}finally{T.d()}}catch(e){warning({message:`Can not get log:`}),console.error(e)}if(w=await r.build(w.id).get(),this.flags.json){printJsonToStdout(w);return}link({message:`Actor build detail`,url:`https://console.apify.com${c}/actors/${w.actId}#/builds/${w.buildNumber}`}),link({message:`Actor detail`,url:`https://console.apify.com${c}/actors/${w.actId}`}),this.flags.open&&await Dt(`https://console.apify.com${c}/actors/${w.actId}`),w.status===N.SUCCEEDED?success({message:`Actor was deployed to Apify cloud and built there.`}):w.status===N.READY?warning({message:`Build is waiting for allocation.`}):w.status===N.RUNNING?warning({message:`Build is still running.`}):w.status===N.ABORTED||w.status===N.ABORTING?(warning({message:`Build was aborted!`}),e.exitCode=3):w.status===N.TIMED_OUT||w.status===N.TIMING_OUT?(warning({message:`Build timed out!`}),e.exitCode=2):(error({message:`Build failed!`}),e.exitCode=1)}},ActorsRmCommand=class extends ApifyCommand{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:Z.string({description:`The Actor ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{actorId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow();if(!await n.actor(e).get()){error({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await X({message:`Are you sure you want to delete this Actor?`,providedConfirmFromStdin:t||void 0})){info({message:`Deletion of Actor "${e}" was canceled.`});return}try{await n.actor(e).delete(),success({message:`Actor with ID "${e}" was deleted.`})}catch(t){let n=t;error({message:`Failed to delete Actor "${e}".\n ${n.message||n}`})}}};const rr={FREE:`Free`,FLAT_PRICE_PER_MONTH:`Subscription`,PRICE_PER_DATASET_ITEM:`Pay per result`,PAY_PER_EVENT:`Pay per event`};function formatPricingModel(e){return e?rr[e]??e:t.gray(`Unknown`)}function truncateDescription(e,t=60){return e?e.length<=t?e:`${e.slice(0,t-1)}…`:``}var ActorsSearchCommand=class extends ApifyCommand{static name=`search`;static description=`Searches Actors in the Apify Store.
102
102
 
103
- 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:Z.string({description:`Search query to find Actors by title, name, description, username, or readme.`,required:!1})};static flags={"sort-by":Y.string({description:`Sort order for the results.`,options:[`relevance`,`popularity`,`newest`,`lastUpdate`],default:`relevance`}),category:Y.string({description:`Filter by category (e.g. AI).`}),username:Y.string({description:`Filter by Actor author username.`}),"pricing-model":Y.string({description:`Filter by pricing model.`,options:[`FREE`,`FLAT_PRICE_PER_MONTH`,`PRICE_PER_DATASET_ITEM`,`PAY_PER_EVENT`]}),limit:Y.integer({description:`Maximum number of results to return.`,default:20}),offset:Y.integer({description:`Number of results to skip for pagination.`,default:0})};static enableJsonFlag=!0;async run(){let{query:e}=this.args,{json:n,sortBy:r,category:i,username:a,pricingModel:s,limit:c,offset:l}=this.flags,u=getApifyClientOptions();delete u.token;let f=new He(u),p;try{p=await f.store().list({search:e,sortBy:r,category:i,username:a,pricingModel:s,limit:c,offset:l})}catch(e){process.exitCode=1,error({message:`Failed to search Apify Store: ${e instanceof Error?e.message:String(e)}`,stdout:!0});return}if(p.count===0){if(n){printJsonToStdout(p);return}info({message:`No Actors found matching your search.`,stdout:!0});return}if(n){printJsonToStdout(p);return}let m=new Q({allColumns:[`Name`,`Description`,`Users (30d)`,`Pricing`],mandatoryColumns:[`Name`,`Pricing`],columnAlignments:{"Users (30d)":`right`,Name:`left`}});for(let e of p.items)m.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Description:truncateDescription(e.description),"Users (30d)":t.cyan(`${e.stats?.totalUsers30Days??0}`),Pricing:formatPricingModel(e.currentPricingInfo?.pricingModel)});simpleLog({message:m.render(1),stdout:!0})}},ActorsStartCommand=class extends ApifyCommand{static name=`start`;static description=`Starts Actor remotely and returns run details immediately.
104
- 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={...SharedRunOnCloudFlags(`Actor`),input:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.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:Z.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 '${U}' file.`})};async run(){let e=process.cwd(),n=getLocalConfig(e)||{},r=await getLoggedClientOrThrow(),i=await getLocalUserInfo(),a=i.username||i.id,{id:s,userFriendlyId:c,actorData:l}=await Gn.resolveActorId({client:r,localActorName:n.name,usernameOrId:a,providedActorNameOrId:this.args.actorId}),u={};this.flags.build&&(u.build=this.flags.build),this.flags.timeout&&(u.timeout=this.flags.timeout),this.flags.memory&&(u.memory=this.flags.memory);let f=await getInputOverride(e,this.flags.input,this.flags.inputFile);if(f===!1)return;let p=runActorOrTaskOnCloud(r,{actorOrTaskData:{id:s,userFriendlyId:c},runOptions:u,type:`Actor`,inputOverride:f?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),m;for await(let e of p)m=e;if(this.flags.json){printJsonToStdout(m);return}let h=`https://console.apify.com/actors/${s}/runs/${m.id}`,g=`https://console.apify.com/storage/datasets/${m.defaultDatasetId}`,_=[`${t.gray(`Run:`)} Calling Actor ${c} (${t.gray(s)})`,``,`${t.yellow(`Started`)}: ${G.display(m.startedAt)}`];m.containerUrl&&_.push(`${t.yellow(`Container URL`)}: ${t.blue(m.containerUrl)}`);let v=m.buildNumber.split(`.`).slice(0,2).join(`.`),y=l.versions.find(e=>e.versionNumber===v),b=Object.entries(l.taggedBuilds??{}).find(([,e])=>e.buildNumber===m.buildNumber)?.[0],x=[`${t.yellow(`Build`)}:`,t.cyan(m.buildNumber)];b?x.push(`(${t.yellow(b)})`):x.push(`(${t.gray(`N/A`)})`),y&&x.push(`| ${t.gray(`Actor version:`)} ${t.cyan(y.versionNumber)} (${t.yellow(y.buildTag)})`),_.push(x.join(` `)),_.push(`${t.yellow(`Timeout`)}: ${m.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),_.push(`${t.yellow(`Memory`)}: ${m.options.memoryMbytes} MB`),_.push(``,`${t.blue(`Export results`)}: ${g}`,`${t.blue(`View on Apify Console`)}: ${h}`),simpleLog({message:_.join(`
103
+ 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:Z.string({description:`Search query to find Actors by title, name, description, username, or readme.`,required:!1})};static flags={"sort-by":Y.string({description:`Sort order for the results.`,options:[`relevance`,`popularity`,`newest`,`lastUpdate`],default:`relevance`}),category:Y.string({description:`Filter by category (e.g. AI).`}),username:Y.string({description:`Filter by Actor author username.`}),"pricing-model":Y.string({description:`Filter by pricing model.`,options:[`FREE`,`FLAT_PRICE_PER_MONTH`,`PRICE_PER_DATASET_ITEM`,`PAY_PER_EVENT`]}),limit:Y.integer({description:`Maximum number of results to return.`,default:20}),offset:Y.integer({description:`Number of results to skip for pagination.`,default:0})};static enableJsonFlag=!0;async run(){let{query:e}=this.args,{json:n,sortBy:r,category:i,username:a,pricingModel:s,limit:c,offset:l}=this.flags,u=getApifyClientOptions();delete u.token;let f=new Be(u),p;try{p=await f.store().list({search:e,sortBy:r,category:i,username:a,pricingModel:s,limit:c,offset:l})}catch(e){process.exitCode=1,error({message:`Failed to search Apify Store: ${e instanceof Error?e.message:String(e)}`,stdout:!0});return}if(p.count===0){if(n){printJsonToStdout(p);return}info({message:`No Actors found matching your search.`,stdout:!0});return}if(n){printJsonToStdout(p);return}let m=new Q({allColumns:[`Name`,`Description`,`Users (30d)`,`Pricing`],mandatoryColumns:[`Name`,`Pricing`],columnAlignments:{"Users (30d)":`right`,Name:`left`}});for(let e of p.items)m.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Description:truncateDescription(e.description),"Users (30d)":t.cyan(`${e.stats?.totalUsers30Days??0}`),Pricing:formatPricingModel(e.currentPricingInfo?.pricingModel)});simpleLog({message:m.render(1),stdout:!0})}},ActorsStartCommand=class extends ApifyCommand{static name=`start`;static description=`Starts Actor remotely and returns run details immediately.
104
+ 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={...SharedRunOnCloudFlags(`Actor`),input:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.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:Z.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 '${W}' file.`})};async run(){let e=process.cwd(),n=getLocalConfig(e)||{},r=await getLoggedClientOrThrow(),i=await getLocalUserInfo(),a=i.username||i.id,{id:s,userFriendlyId:c,actorData:l}=await Gn.resolveActorId({client:r,localActorName:n.name,usernameOrId:a,providedActorNameOrId:this.args.actorId}),u={};this.flags.build&&(u.build=this.flags.build),this.flags.timeout&&(u.timeout=this.flags.timeout),this.flags.memory&&(u.memory=this.flags.memory);let f=await getInputOverride(e,this.flags.input,this.flags.inputFile);if(f===!1)return;let p=runActorOrTaskOnCloud(r,{actorOrTaskData:{id:s,userFriendlyId:c},runOptions:u,type:`Actor`,inputOverride:f?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),m;for await(let e of p)m=e;if(this.flags.json){printJsonToStdout(m);return}let h=`https://console.apify.com/actors/${s}/runs/${m.id}`,g=`https://console.apify.com/storage/datasets/${m.defaultDatasetId}`,_=[`${t.gray(`Run:`)} Calling Actor ${c} (${t.gray(s)})`,``,`${t.yellow(`Started`)}: ${G.display(m.startedAt)}`];m.containerUrl&&_.push(`${t.yellow(`Container URL`)}: ${t.blue(m.containerUrl)}`);let v=m.buildNumber.split(`.`).slice(0,2).join(`.`),y=l.versions.find(e=>e.versionNumber===v),b=Object.entries(l.taggedBuilds??{}).find(([,e])=>e.buildNumber===m.buildNumber)?.[0],x=[`${t.yellow(`Build`)}:`,t.cyan(m.buildNumber)];b?x.push(`(${t.yellow(b)})`):x.push(`(${t.gray(`N/A`)})`),y&&x.push(`| ${t.gray(`Actor version:`)} ${t.cyan(y.versionNumber)} (${t.yellow(y.buildTag)})`),_.push(x.join(` `)),_.push(`${t.yellow(`Timeout`)}: ${m.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),_.push(`${t.yellow(`Memory`)}: ${m.options.memoryMbytes} MB`),_.push(``,`${t.blue(`Export results`)}: ${g}`,`${t.blue(`View on Apify Console`)}: ${h}`),simpleLog({message:_.join(`
105
105
  `),stdout:!0})}},ActorsIndexCommand=class extends ApifyCommand{static name=`actors`;static description=`Search, list, deploy, and call Actors on the Apify platform.
106
106
  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=[ActorsStartCommand,ActorsRmCommand,ActorsSearchCommand,ActorsPushCommand,ActorsPullCommand,ActorsLsCommand,ActorsInfoCommand,Gn,ActorsBuildCommand];async run(){this.printHelp()}};const ir=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],ar=new Set([`GET`,`HEAD`]),or=`https://docs.apify.com/api/openapi.json`;function parseParams(e){if(!e)return``;let t;try{t=JSON.parse(e)}catch{throw Error(`Invalid JSON in --params flag. Please provide a valid JSON object, e.g. '{"limit": 1}'.`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`--params must be a JSON object (e.g. '{"limit": 1}').`);let n=new URLSearchParams;for(let[e,r]of Object.entries(t))if(r!=null){if(typeof r==`object`)throw Error(`--params value for "${e}" must be a scalar (string, number, or boolean), got ${Array.isArray(r)?`array`:`object`}. Query parameters cannot contain nested objects or arrays.`);n.append(e,String(r))}return n.toString()}function parseHeaders(e){if(!e)return{};let t=e.trim();if(t.startsWith(`{`)){let e;try{e=JSON.parse(t)}catch{throw Error(`Invalid JSON in --header flag. Provide a JSON object like '{"X-Foo": "bar"}'.`)}if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`--header JSON must be an object mapping header names to string values.`);let n={};for(let[t,r]of Object.entries(e)){if(typeof r!=`string`)throw Error(`--header value for "${t}" must be a string, got ${typeof r}.`);n[t.trim()]=r.trim()}return n}let n=t.indexOf(`:`);if(n===-1)throw Error(`Header must be in "key:value" format, or a JSON object for multiple headers.`);return{[t.slice(0,n).trim()]:t.slice(n+1).trim()}}var ApiCommand=class extends ApifyCommand{static name=`api`;static description=`Makes an authenticated HTTP request to the Apify API and prints the response.
107
107
  The endpoint can be a relative path (e.g. "acts", "v2/acts", or "/v2/acts"); the "v2/" prefix is added automatically if omitted.
108
108
 
109
- 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:Z.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:Z.string({required:!1,description:`The API endpoint path when the first argument is an HTTP method.`})};static flags={method:Y.string({char:`X`,description:`The HTTP method to use. Defaults to GET.`,choices:ir}),body:Y.string({char:`d`,description:`The request body (JSON string). Use "-" to read from stdin.`,required:!1,stdin:2}),header:Y.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:Y.string({char:`p`,description:`Query parameters as a JSON object, e.g. '{"limit": 1, "desc": true}'.`,required:!1}),"list-endpoints":Y.boolean({char:`l`,description:`List all available Apify API endpoints.`,default:!1})};async run(){if(this.flags.listEndpoints){await this.printEndpoints();return}let n=this.flags.method?.toUpperCase(),r,i=this.args.methodOrEndpoint;if(i&&ir.includes(i.toUpperCase())){let e=i.toUpperCase();if(n&&n!==e)throw Error(`Conflicting HTTP methods: positional "${e}" vs --method "${n}". Please specify the method only once.`);r=e,i=this.args.endpoint}else r=n;if(r??=`GET`,!i){this.printHelp();return}let a=parseParams(this.flags.params),s=parseHeaders(this.flags.header);if(this.flags.body){if(ar.has(r))throw Error(`HTTP ${r} 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 Error(`Invalid JSON in --body flag. Please provide a valid JSON string.`)}}let c=await getLoggedClientOrThrow(),l=c.token,u=i;u.startsWith(`/`)&&(u=u.slice(1)),u=u.replace(/^v2\//i,``);let f=`${c.baseUrl}/${u}`;if(a){let e=f.includes(`?`)?`&`:`?`;f=`${f}${e}${a}`}let p={...on,Authorization:`Bearer ${l}`};this.flags.body&&(p[`Content-Type`]=`application/json`);for(let[e,t]of Object.entries(s)){for(let t of Object.keys(p))t.toLowerCase()===e.toLowerCase()&&delete p[t];p[e]=t}let m=await fetch(f,{method:r,headers:p,body:this.flags.body||void 0}),h=await m.text();if(!m.ok){if(e.exitCode=1,error({message:`${m.status} ${m.statusText}`}),h)try{let e=JSON.parse(h);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:h,stdout:!0})}m.status===404&&simpleLog({message:`\nRun ${t.cyan(`apify api --list-endpoints`)} to see all available Apify API endpoints.`,stdout:!1});return}if(h)try{let e=JSON.parse(h);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:h,stdout:!0})}}async printEndpoints(){let e=await fetchEndpoints(),n={GET:t.green,POST:t.yellow,PUT:t.blue,PATCH:t.cyan,DELETE:t.red};for(let{method:r,path:i,summary:a}of e){let e=(n[r]||t.white)(r.padEnd(7)),s=a?t.gray(` ${a}`):``;console.log(`${e} ${i}${s}`)}}};async function fetchEndpoints(){let e;try{e=await fetch(or)}catch(e){throw Error(`Failed to download the Apify OpenAPI spec from ${or}: ${e.message}`)}if(!e.ok)throw Error(`Failed to download the Apify OpenAPI spec from ${or}: ${e.status} ${e.statusText}`);let t=await e.json(),n=[];for(let[e,r]of Object.entries(t.paths))for(let[t,i]of Object.entries(r))ir.includes(t.toUpperCase())&&n.push({method:t.toUpperCase(),path:e,summary:i.summary||``});return n.sort((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)),n}const sr=stdinCheckWrapper(async({message:e,mask:t})=>await Ft({message:e,mask:t??`*`})),cr=stdinCheckWrapper(async({message:e,choices:t,pageSize:n,loop:r,default:i})=>await It({message:e,choices:t,pageSize:n,loop:r,default:i})),lr=`https://console.apify.com/settings/integrations`,ur=new URL(lr).origin,dr=lr.includes(`localhost`)?`http://localhost:3333`:void 0,tryToLogin=async e=>{let n=await getLoggedClient(e,dr),r=await getLocalUserInfo();return n?(await updateUserId(r.id),success({message:`You are logged in to Apify as ${r.username||r.id}. ${t.gray(`Your token is stored at ${AUTH_FILE_PATH()}.`)}`})):error({message:`Login to Apify failed, the provided API token is not valid.`}),n};var AuthLoginCommand=class extends ApifyCommand{static name=`login`;static description=`Authenticates your Apify account and saves credentials to '${tildify(AUTH_FILE_PATH())}'.\nAll other commands use these stored credentials.
109
+ 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:Z.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:Z.string({required:!1,description:`The API endpoint path when the first argument is an HTTP method.`})};static flags={method:Y.string({char:`X`,description:`The HTTP method to use. Defaults to GET.`,choices:ir}),body:Y.string({char:`d`,description:`The request body (JSON string). Use "-" to read from stdin.`,required:!1,stdin:2}),header:Y.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:Y.string({char:`p`,description:`Query parameters as a JSON object, e.g. '{"limit": 1, "desc": true}'.`,required:!1}),"list-endpoints":Y.boolean({char:`l`,description:`List all available Apify API endpoints.`,default:!1})};async run(){if(this.flags.listEndpoints){await this.printEndpoints();return}let n=this.flags.method?.toUpperCase(),r,i=this.args.methodOrEndpoint;if(i&&ir.includes(i.toUpperCase())){let e=i.toUpperCase();if(n&&n!==e)throw Error(`Conflicting HTTP methods: positional "${e}" vs --method "${n}". Please specify the method only once.`);r=e,i=this.args.endpoint}else r=n;if(r??=`GET`,!i){this.printHelp();return}let a=parseParams(this.flags.params),s=parseHeaders(this.flags.header);if(this.flags.body){if(ar.has(r))throw Error(`HTTP ${r} 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 Error(`Invalid JSON in --body flag. Please provide a valid JSON string.`)}}let c=await getLoggedClientOrThrow(),l=c.token,u=i;u.startsWith(`/`)&&(u=u.slice(1)),u=u.replace(/^v2\//i,``);let f=`${c.baseUrl}/${u}`;if(a){let e=f.includes(`?`)?`&`:`?`;f=`${f}${e}${a}`}let p={...an,Authorization:`Bearer ${l}`};this.flags.body&&(p[`Content-Type`]=`application/json`);for(let[e,t]of Object.entries(s)){for(let t of Object.keys(p))t.toLowerCase()===e.toLowerCase()&&delete p[t];p[e]=t}let m=await fetch(f,{method:r,headers:p,body:this.flags.body||void 0}),h=await m.text();if(!m.ok){if(e.exitCode=1,error({message:`${m.status} ${m.statusText}`}),h)try{let e=JSON.parse(h);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:h,stdout:!0})}m.status===404&&simpleLog({message:`\nRun ${t.cyan(`apify api --list-endpoints`)} to see all available Apify API endpoints.`,stdout:!1});return}if(h)try{let e=JSON.parse(h);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:h,stdout:!0})}}async printEndpoints(){let e=await fetchEndpoints(),n={GET:t.green,POST:t.yellow,PUT:t.blue,PATCH:t.cyan,DELETE:t.red};for(let{method:r,path:i,summary:a}of e){let e=(n[r]||t.white)(r.padEnd(7)),s=a?t.gray(` ${a}`):``;console.log(`${e} ${i}${s}`)}}};async function fetchEndpoints(){let e;try{e=await fetch(or)}catch(e){throw Error(`Failed to download the Apify OpenAPI spec from ${or}: ${e.message}`)}if(!e.ok)throw Error(`Failed to download the Apify OpenAPI spec from ${or}: ${e.status} ${e.statusText}`);let t=await e.json(),n=[];for(let[e,r]of Object.entries(t.paths))for(let[t,i]of Object.entries(r))ir.includes(t.toUpperCase())&&n.push({method:t.toUpperCase(),path:e,summary:i.summary||``});return n.sort((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)),n}const sr=stdinCheckWrapper(async({message:e,mask:t})=>await Pt({message:e,mask:t??`*`})),cr=stdinCheckWrapper(async({message:e,choices:t,pageSize:n,loop:r,default:i})=>await Ft({message:e,choices:t,pageSize:n,loop:r,default:i})),lr=`https://console.apify.com/settings/integrations`,ur=new URL(lr).origin,dr=lr.includes(`localhost`)?`http://localhost:3333`:void 0,tryToLogin=async e=>{let n=await getLoggedClient(e,dr),r=await getLocalUserInfo();return n?(await updateUserId(r.id),success({message:`You are logged in to Apify as ${r.username||r.id}. ${t.gray(`Your token is stored at ${AUTH_FILE_PATH()}.`)}`})):error({message:`Login to Apify failed, the provided API token is not valid.`}),n};var AuthLoginCommand=class extends ApifyCommand{static name=`login`;static description=`Authenticates your Apify account and saves credentials to '${tildify(AUTH_FILE_PATH())}'.\nAll other commands use these stored credentials.
110
110
 
111
- 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:Y.string({char:`t`,description:`Apify API token.`,required:!1}),method:Y.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 tryToLogin(e);return}let n=t;if(t||(n=await cr({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})),n===`console`){let e,t=Pt();t.use(Nt({origin:ur,allowedHeaders:[`Content-Type`,`Authorization`]})),t.use((e,t,n)=>{t.set(`Connection`,`close`),n()}),t.use(Pt.json());let n=Te();t.use((e,t,r)=>{let{token:i}=e.query;if(!i){let t=e.get(`Authorization`);if(t){let[e,n,...r]=t.trim().split(/\s+/);e.toLowerCase()===`bearer`&&n&&r.length===0&&(i=n)}}i===n?r():(t.status(401),t.send(`Authorization failed`))});let r=Pt.Router();t.use(`/api/v1`,r),r.post(`/login-token`,async(t,n)=>{try{if(t.body.apiToken)await tryToLogin(t.body.apiToken);else throw Error(`Request did not contain API token`);n.end()}catch(e){let t=`Login to Apify failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}e.close()}),r.post(`/exit`,(t,n)=>{t.body.isWindowClosed?error({message:`Login to Apify failed, the console window was closed.`}):t.body.actionCanceled?error({message:`Login to Apify failed, the action was canceled in the Apify Console.`}):error({message:`Login to Apify failed.`}),n.end(),e.close()}),e=t.listen(0);let{port:i}=e.address(),a=new URL(lr);a.searchParams.set(`localCliCommand`,`login`),a.searchParams.set(`localCliPort`,`${i}`),a.searchParams.set(`localCliToken`,n),a.searchParams.set(`localCliApiVersion`,`v1`);try{a.searchParams.set(`localCliComputerName`,encodeURIComponent(Mt()))}catch{}info({message:`Opening Apify Console at "${a.href}"...`}),await Ot(a.href)}else console.log(`Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations`),await tryToLogin(await sr({message:`token:`}))}},AuthLogoutCommand=class extends ApifyCommand{static name=`logout`;static description=`Removes authentication by deleting your API token and account information from '${tildify(AUTH_FILE_PATH())}'.\nRun '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 rimrafPromised(AUTH_FILE_PATH()),await updateUserId(null),success({message:`You are logged out from your Apify account.`})}},AuthTokenCommand=class extends ApifyCommand{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 — it is a secret).`,command:`apify auth token`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-auth-token`;async run(){await getLoggedClientOrThrow();let e=await getLocalUserInfo();e.token&&simpleLog({message:e.token,stdout:!0})}},AuthIndexCommand=class extends ApifyCommand{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=[AuthLoginCommand,AuthLogoutCommand,AuthTokenCommand];async run(){this.printHelp()}},BuildsAddTagCommand=class extends ApifyCommand{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:Y.string({char:`b`,description:`The build ID to tag.`,required:!0}),tag:Y.string({char:`t`,description:`The tag to add to the build.`,required:!0})};async run(){let{build:e,tag:n}=this.flags,r=await getLoggedClientOrThrow(),i=await r.build(e).get();if(!i){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(i.status!==`SUCCEEDED`){error({message:`Build with ID "${e}" has status "${i.status}". Only successful builds can be tagged.`,stdout:!0});return}let a=await r.actor(i.actId).get();if(!a){error({message:`Actor with ID "${i.actId}" was not found.`,stdout:!0});return}let s=(a.taggedBuilds??{})[n];if(s?.buildId===e){warning({message:`Build "${e}" is already tagged as "${n}".`,stdout:!0});return}try{await r.actor(i.actId).update({taggedBuilds:{[n]:{buildId:i.id}}});let a=s?.buildNumber?` (previously pointed to build ${t.gray(s.buildNumber)})`:``;success({message:`Tag "${t.yellow(n)}" added to build ${t.gray(i.buildNumber)} (${t.gray(e)})${a}`,stdout:!0})}catch(t){let r=t;error({message:`Failed to add tag "${n}" to build "${e}".\n ${r.message||r}`,stdout:!0})}}};const noColor=e=>e;function prettyPrintBytes({bytes:e,shortBytes:t=!1,colorFunc:n=noColor,precision:r=2}){let i=[t?`B`:`Bytes`,`KB`,`MB`,`GB`,`TB`];if(e===0)return t?`${0 .toPrecision(r)} B`:`${0 .toPrecision(r)} Byte`;let a=Math.floor(Math.log(e)/Math.log(1e3));return`${(e/1e3**a).toFixed(r)} ${n(i[a])}`}var BuildsInfoCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The build ID to get information about.`})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,n=await getLoggedClientOrThrow(),r=await n.build(e).get();if(!r){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){printJsonToStdout(r);return}let i=await n.actor(r.actId).get(),a;if(i?.taggedBuilds){for(let[e,t]of Object.entries(i.taggedBuilds))if(t.buildId===r.id){a=e;break}}let s=Reflect.get(r,`exitCode`),c=i?.username?`${i.username}/${i.name}`:i?.name??`unknown-actor`,l=a?` (tagged as ${t.yellow(a)})`:``,u=s===void 0?``:` (exit code: ${t.gray(s)})`,f=[`${t.yellow(`Actor`)}: ${c} (${t.gray(r.actId)})`,``,`${t.yellow(`Build Information`)} (ID: ${t.gray(r.id)})`,` ${t.yellow(`Build Number`)}: ${r.buildNumber}${l}`,` ${t.yellow(`Status`)}: ${prettyPrintStatus(r.status)}${u}`,` ${t.yellow(`Started`)}: ${G.display(r.startedAt)}`];if(r.finishedAt)f.push(` ${t.yellow(`Finished`)}: ${G.display(r.finishedAt)} (took ${t.gray(Sn.format(r.stats?.durationMillis??0))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(` ${t.yellow(`Finished`)}: ${t.gray(`Running for ${Sn.format(e)}`)}`)}r.stats?.computeUnits&&f.push(` ${t.yellow(`Compute Units`)}: ${r.stats.computeUnits.toFixed(3)}`);let p=Reflect.get(r.stats??{},`imageSizeBytes`);p&&f.push(` ${t.yellow(`Docker Image Size`)}: ${prettyPrintBytes({bytes:p})}`),f.push(` ${t.yellow(`Origin`)}: ${r.meta.origin??`UNKNOWN`}`),f.push(``);let m=`https://console.apify.com/actors/${r.actId}/builds/${r.buildNumber}`;f.push(`${t.blue(`View in Apify Console`)}: ${m}`),simpleLog({message:f.join(`
111
+ 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:Y.string({char:`t`,description:`Apify API token.`,required:!1}),method:Y.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 tryToLogin(e);return}let n=t;if(t||(n=await cr({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})),n===`console`){let e,t=Nt();t.use(Mt({origin:ur,allowedHeaders:[`Content-Type`,`Authorization`]})),t.use((e,t,n)=>{t.set(`Connection`,`close`),n()}),t.use(Nt.json());let n=we();t.use((e,t,r)=>{let{token:i}=e.query;if(!i){let t=e.get(`Authorization`);if(t){let[e,n,...r]=t.trim().split(/\s+/);e.toLowerCase()===`bearer`&&n&&r.length===0&&(i=n)}}i===n?r():(t.status(401),t.send(`Authorization failed`))});let r=Nt.Router();t.use(`/api/v1`,r),r.post(`/login-token`,async(t,n)=>{try{if(t.body.apiToken)await tryToLogin(t.body.apiToken);else throw Error(`Request did not contain API token`);n.end()}catch(e){let t=`Login to Apify failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}e.close()}),r.post(`/exit`,(t,n)=>{t.body.isWindowClosed?error({message:`Login to Apify failed, the console window was closed.`}):t.body.actionCanceled?error({message:`Login to Apify failed, the action was canceled in the Apify Console.`}):error({message:`Login to Apify failed.`}),n.end(),e.close()}),e=t.listen(0);let{port:i}=e.address(),a=new URL(lr);a.searchParams.set(`localCliCommand`,`login`),a.searchParams.set(`localCliPort`,`${i}`),a.searchParams.set(`localCliToken`,n),a.searchParams.set(`localCliApiVersion`,`v1`);try{a.searchParams.set(`localCliComputerName`,encodeURIComponent(jt()))}catch{}info({message:`Opening Apify Console at "${a.href}"...`}),await Dt(a.href)}else console.log(`Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations`),await tryToLogin(await sr({message:`token:`}))}},AuthLogoutCommand=class extends ApifyCommand{static name=`logout`;static description=`Removes authentication by deleting your API token and account information from '${tildify(AUTH_FILE_PATH())}'.\nRun '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 rimrafPromised(AUTH_FILE_PATH()),await updateUserId(null),success({message:`You are logged out from your Apify account.`})}},AuthTokenCommand=class extends ApifyCommand{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 — it is a secret).`,command:`apify auth token`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-auth-token`;async run(){await getLoggedClientOrThrow();let e=await getLocalUserInfo();e.token&&simpleLog({message:e.token,stdout:!0})}},AuthIndexCommand=class extends ApifyCommand{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=[AuthLoginCommand,AuthLogoutCommand,AuthTokenCommand];async run(){this.printHelp()}},BuildsAddTagCommand=class extends ApifyCommand{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:Y.string({char:`b`,description:`The build ID to tag.`,required:!0}),tag:Y.string({char:`t`,description:`The tag to add to the build.`,required:!0})};async run(){let{build:e,tag:n}=this.flags,r=await getLoggedClientOrThrow(),i=await r.build(e).get();if(!i){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(i.status!==`SUCCEEDED`){error({message:`Build with ID "${e}" has status "${i.status}". Only successful builds can be tagged.`,stdout:!0});return}let a=await r.actor(i.actId).get();if(!a){error({message:`Actor with ID "${i.actId}" was not found.`,stdout:!0});return}let s=(a.taggedBuilds??{})[n];if(s?.buildId===e){warning({message:`Build "${e}" is already tagged as "${n}".`,stdout:!0});return}try{await r.actor(i.actId).update({taggedBuilds:{[n]:{buildId:i.id}}});let a=s?.buildNumber?` (previously pointed to build ${t.gray(s.buildNumber)})`:``;success({message:`Tag "${t.yellow(n)}" added to build ${t.gray(i.buildNumber)} (${t.gray(e)})${a}`,stdout:!0})}catch(t){let r=t;error({message:`Failed to add tag "${n}" to build "${e}".\n ${r.message||r}`,stdout:!0})}}};const noColor=e=>e;function prettyPrintBytes({bytes:e,shortBytes:t=!1,colorFunc:n=noColor,precision:r=2}){let i=[t?`B`:`Bytes`,`KB`,`MB`,`GB`,`TB`];if(e===0)return t?`${0 .toPrecision(r)} B`:`${0 .toPrecision(r)} Byte`;let a=Math.floor(Math.log(e)/Math.log(1e3));return`${(e/1e3**a).toFixed(r)} ${n(i[a])}`}var BuildsInfoCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The build ID to get information about.`})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,n=await getLoggedClientOrThrow(),r=await n.build(e).get();if(!r){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){printJsonToStdout(r);return}let i=await n.actor(r.actId).get(),a;if(i?.taggedBuilds){for(let[e,t]of Object.entries(i.taggedBuilds))if(t.buildId===r.id){a=e;break}}let s=Reflect.get(r,`exitCode`),c=i?.username?`${i.username}/${i.name}`:i?.name??`unknown-actor`,l=a?` (tagged as ${t.yellow(a)})`:``,u=s===void 0?``:` (exit code: ${t.gray(s)})`,f=[`${t.yellow(`Actor`)}: ${c} (${t.gray(r.actId)})`,``,`${t.yellow(`Build Information`)} (ID: ${t.gray(r.id)})`,` ${t.yellow(`Build Number`)}: ${r.buildNumber}${l}`,` ${t.yellow(`Status`)}: ${prettyPrintStatus(r.status)}${u}`,` ${t.yellow(`Started`)}: ${G.display(r.startedAt)}`];if(r.finishedAt)f.push(` ${t.yellow(`Finished`)}: ${G.display(r.finishedAt)} (took ${t.gray(Sn.format(r.stats?.durationMillis??0))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(` ${t.yellow(`Finished`)}: ${t.gray(`Running for ${Sn.format(e)}`)}`)}r.stats?.computeUnits&&f.push(` ${t.yellow(`Compute Units`)}: ${r.stats.computeUnits.toFixed(3)}`);let p=Reflect.get(r.stats??{},`imageSizeBytes`);p&&f.push(` ${t.yellow(`Docker Image Size`)}: ${prettyPrintBytes({bytes:p})}`),f.push(` ${t.yellow(`Origin`)}: ${r.meta.origin??`UNKNOWN`}`),f.push(``);let m=`https://console.apify.com/actors/${r.actId}/builds/${r.buildNumber}`;f.push(`${t.blue(`View in Apify Console`)}: ${m}`),simpleLog({message:f.join(`
112
112
  `),stdout:!0})}},BuildsLogCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The build ID to get the log from.`})};async run(){let{buildId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.build(e).get();if(!n)throw Error(`Build with ID "${e}" was not found on your account.`);info({message:`Log for build with ID "${e}":\n`}),await outputJobLog({job:n,apifyClient:t})}};const tableFactory=()=>new Q({allColumns:[`Number`,`ID`,`Status`,`Took`],mandatoryColumns:[`Number`,`ID`,`Status`,`Took`],columnAlignments:{Took:`right`}});var BuildsLsCommand=class extends ApifyCommand{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:Y.integer({description:`Number of builds that will be skipped.`,default:0}),limit:Y.integer({description:`Number of builds that will be listed.`,default:10}),desc:Y.boolean({description:`Sort builds in descending order.`,default:!1}),compact:Y.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:Z.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:n,offset:r,compact:i,json:a}=this.flags,{actorId:s}=this.args,c=await getLoggedClientOrThrow(),l=await resolveActorContext({providedActorNameOrId:s,client:c});if(!l.valid){error({message:`${l.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let u=await c.actor(l.id).builds().list({desc:e,limit:n,offset:r}),f=await c.actor(l.id).get(),p=objectGroupBy(u.items,e=>{let[t,n]=Reflect.get(e,`buildNumber`).split(`.`);return`${t}.${n}`}),m=Object.entries(f.taggedBuilds??{}).reduce((e,[t,n])=>(e[n.buildNumber]=t,e),{});if(a){for(let e of u.items){let t=m[Reflect.get(e,`buildNumber`)];t&&Reflect.set(e,`buildTag`,t)}printJsonToStdout(u);return}simpleLog({message:`${t.reset(`Showing`)} ${t.yellow(u.items.length)} out of ${t.yellow(u.total)} builds for Actor ${t.yellow(l.userFriendlyId)} (${t.gray(l.id)})\n`,stdout:!0});let h=Object.entries(p).sort((e,t)=>e[0].localeCompare(t[0]));for(let[e,n]of h){if(!n?.length){simpleLog({message:`No builds for version ${e}`,stdout:!0});continue}let r=f.versions.find(t=>t.versionNumber===e)?.buildTag,a=this.generateTableForActorVersion({buildsForVersion:n,buildTagToActorVersion:m}),s=r?` (latest build gets tagged with ${t.yellow(r)})`:``;simpleLog({message:[t.reset(`Builds for Actor Version ${t.yellow(e)}${s}`),a.render(i?0:-1),``].join(`
113
- `),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:n}){let r=tableFactory();for(let i of e){let e=Reflect.get(i,`buildNumber`),a=n[e]?` (${t.yellow(n[e])})`:``,s;if(i.finishedAt){let e=i.finishedAt.getTime()-i.startedAt.getTime();s=t.gray(`${K.format(e,void 0,{left:``})}`)}else{let e=Date.now()-i.startedAt.getTime();s=t.gray(`Running for ${K.format(e,void 0,{left:``})}`)}r.pushRow({Number:`${e}${a}`,ID:t.gray(i.id),Status:prettyPrintStatus(i.status),Took:s})}return r}},BuildsRemoveTagCommand=class extends ApifyCommand{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:Y.string({char:`b`,description:`The build ID to remove the tag from.`,required:!0}),tag:Y.string({char:`t`,description:`The tag to remove from the build.`,required:!0}),...YesFlag()};async run(){let{build:e,tag:n,yes:r}=this.flags,i=await getLoggedClientOrThrow(),a=await i.build(e).get();if(!a){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let s=await i.actor(a.actId).get();if(!s){error({message:`Actor with ID "${a.actId}" was not found.`,stdout:!0});return}let c=(s.taggedBuilds??{})[n];if(!c){error({message:`Tag "${n}" does not exist on Actor "${s.name}".`,stdout:!0});return}if(c.buildId!==e){error({message:`Tag "${n}" is not associated with build "${e}". It points to build "${c.buildNumber}" (${c.buildId}).`,stdout:!0});return}if(!await X({message:`Are you sure you want to remove tag "${t.yellow(n)}" from build ${t.gray(a.buildNumber)}?`,providedConfirmFromStdin:r||void 0})){info({message:`Tag removal was canceled.`,stdout:!0});return}try{await i.actor(a.actId).update({taggedBuilds:{[n]:null}}),success({message:`Tag "${t.yellow(n)}" removed from build ${t.gray(a.buildNumber)} (${t.gray(e)})`,stdout:!0})}catch(t){let r=t;error({message:`Failed to remove tag "${n}" from build "${e}".\n ${r.message||r}`,stdout:!0})}}};const fr=stdinCheckWrapper(async({message:e,expectedValue:t,failureMessage:n})=>await ot({message:e,validate(e){return e===t?!0:n??`That is not the correct input!`}}));var BuildsRmCommand=class extends ApifyCommand{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:Z.string({description:`The build ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{buildId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow(),r=await n.build(e).get();if(!r)throw Error(`Build with ID "${e}" was not found on your account.`);let i=await n.actor(r.actId).get(),a;if(i?.taggedBuilds){for(let[t,n]of Object.entries(i.taggedBuilds))if(e===n.buildId){a=t;break}}let s;if(s=a?await fr({message:`Are you sure you want to delete this Actor Build? If so, please type in "${a}":`,expectedValue:a,failureMessage:`Your provided value does not match the build tag.`,providedConfirmFromStdin:t?a:void 0}):await X({message:`Are you sure you want to delete this Actor Build?`,providedConfirmFromStdin:t||void 0}),!s){info({message:`Deletion of build "${e}" was canceled.`,stdout:!0});return}await n.build(e).delete(),success({message:`Build with ID "${e}" was deleted.`,stdout:!0})}},BuildsIndexCommand=class extends ApifyCommand{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=[BuildsAddTagCommand,BuildsRemoveTagCommand,BuildsRmCommand,BuildsLsCommand,BuildsLogCommand,BuildsInfoCommand,BuildsCreateCommand];async run(){this.printHelp()}},TopLevelCallCommand=class extends Gn{static name=`call`};const pathToInstallMarker=e=>k(e,`.install-marker`),HOMEDIR=()=>process.env.HOME??ue();var InstallCommand=class extends ApifyCommand{static name=`install`;static description=`Finalizes the first-time setup of Apify and Actor CLI.`;static hidden=!0;async run(){let{installMethod:e,installPath:n,version:r}=useCLIMetadata();if(e!==`bundle`){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}Lt(n,`When CLI is installed via bundles, the install path must be set`);let i=pathToInstallMarker(n);if(v(i)){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}if(process.platform!==`win32`){await this.symlinkToLocalBin(n);try{await this.promptAddToShell()}catch(e){error({message:e.message||`Failed to automatically handle shell integration`})}simpleLog({message:``})}await R(i,r),cliDebugPrint(`[install] install marker written to`,i),simpleLog({message:[``,t.green(`Apify and Actor CLI were installed successfully!`),``,t.gray(` Version: ${t.green(r)}`),t.gray(` Location: ${t.bold.white(tildify(k(n,`apify`)))} and ${t.bold.white(tildify(k(n,`actor`)))}`)].join(`
113
+ `),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:n}){let r=tableFactory();for(let i of e){let e=Reflect.get(i,`buildNumber`),a=n[e]?` (${t.yellow(n[e])})`:``,s;if(i.finishedAt){let e=i.finishedAt.getTime()-i.startedAt.getTime();s=t.gray(`${K.format(e,void 0,{left:``})}`)}else{let e=Date.now()-i.startedAt.getTime();s=t.gray(`Running for ${K.format(e,void 0,{left:``})}`)}r.pushRow({Number:`${e}${a}`,ID:t.gray(i.id),Status:prettyPrintStatus(i.status),Took:s})}return r}},BuildsRemoveTagCommand=class extends ApifyCommand{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:Y.string({char:`b`,description:`The build ID to remove the tag from.`,required:!0}),tag:Y.string({char:`t`,description:`The tag to remove from the build.`,required:!0}),...YesFlag()};async run(){let{build:e,tag:n,yes:r}=this.flags,i=await getLoggedClientOrThrow(),a=await i.build(e).get();if(!a){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let s=await i.actor(a.actId).get();if(!s){error({message:`Actor with ID "${a.actId}" was not found.`,stdout:!0});return}let c=(s.taggedBuilds??{})[n];if(!c){error({message:`Tag "${n}" does not exist on Actor "${s.name}".`,stdout:!0});return}if(c.buildId!==e){error({message:`Tag "${n}" is not associated with build "${e}". It points to build "${c.buildNumber}" (${c.buildId}).`,stdout:!0});return}if(!await X({message:`Are you sure you want to remove tag "${t.yellow(n)}" from build ${t.gray(a.buildNumber)}?`,providedConfirmFromStdin:r||void 0})){info({message:`Tag removal was canceled.`,stdout:!0});return}try{await i.actor(a.actId).update({taggedBuilds:{[n]:null}}),success({message:`Tag "${t.yellow(n)}" removed from build ${t.gray(a.buildNumber)} (${t.gray(e)})`,stdout:!0})}catch(t){let r=t;error({message:`Failed to remove tag "${n}" from build "${e}".\n ${r.message||r}`,stdout:!0})}}};const fr=stdinCheckWrapper(async({message:e,expectedValue:t,failureMessage:n})=>await it({message:e,validate(e){return e===t?!0:n??`That is not the correct input!`}}));var BuildsRmCommand=class extends ApifyCommand{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:Z.string({description:`The build ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{buildId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow(),r=await n.build(e).get();if(!r)throw Error(`Build with ID "${e}" was not found on your account.`);let i=await n.actor(r.actId).get(),a;if(i?.taggedBuilds){for(let[t,n]of Object.entries(i.taggedBuilds))if(e===n.buildId){a=t;break}}let s;if(s=a?await fr({message:`Are you sure you want to delete this Actor Build? If so, please type in "${a}":`,expectedValue:a,failureMessage:`Your provided value does not match the build tag.`,providedConfirmFromStdin:t?a:void 0}):await X({message:`Are you sure you want to delete this Actor Build?`,providedConfirmFromStdin:t||void 0}),!s){info({message:`Deletion of build "${e}" was canceled.`,stdout:!0});return}await n.build(e).delete(),success({message:`Build with ID "${e}" was deleted.`,stdout:!0})}},BuildsIndexCommand=class extends ApifyCommand{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=[BuildsAddTagCommand,BuildsRemoveTagCommand,BuildsRmCommand,BuildsLsCommand,BuildsLogCommand,BuildsInfoCommand,BuildsCreateCommand];async run(){this.printHelp()}},TopLevelCallCommand=class extends Gn{static name=`call`};const pathToInstallMarker=e=>A(e,`.install-marker`),HOMEDIR=()=>process.env.HOME??le();var InstallCommand=class extends ApifyCommand{static name=`install`;static description=`Finalizes the first-time setup of Apify and Actor CLI.`;static hidden=!0;async run(){let{installMethod:e,installPath:n,version:r}=useCLIMetadata();if(e!==`bundle`){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}It(n,`When CLI is installed via bundles, the install path must be set`);let i=pathToInstallMarker(n);if(v(i)){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}if(process.platform!==`win32`){await this.symlinkToLocalBin(n);try{await this.promptAddToShell()}catch(e){error({message:e.message||`Failed to automatically handle shell integration`})}simpleLog({message:``})}await z(i,r),cliDebugPrint(`[install] install marker written to`,i),simpleLog({message:[``,t.green(`Apify and Actor CLI were installed successfully!`),``,t.gray(` Version: ${t.green(r)}`),t.gray(` Location: ${t.bold.white(tildify(A(n,`apify`)))} and ${t.bold.white(tildify(A(n,`actor`)))}`)].join(`
114
114
  `)}),simpleLog({message:``}),success({message:`To get started, run:`}),simpleLog({message:t.white.bold(` apify --help
115
- actor --help`)})}async symlinkToLocalBin(e){let n=HOMEDIR();if(cliDebugPrint(`[install -> symlinkToLocalBin] user home directory`,n),!n){cliDebugPrint(`[install -> symlinkToLocalBin] user home directory not found`),warning({message:t.gray(`User home directory not found, cannot symlink to ~/.local/bin`)});return}let r=k(n,`.local`,`bin`);await P(r,{recursive:!0});for(let n of[`apify`,`actor`,`apify-cli`]){let i=k(e,n);if(!v(i)){cliDebugPrint(`[install] file not found for symlinking`,n,i),warning({message:t.gray(`Bundle not found for symlinking: ${n}`)});continue}let a=k(r,n);await Me(a).catch(()=>{}),await je(i,a),cliDebugPrint(`[install] symlink created for item`,n,a)}info({message:t.gray(`Symlinked apify, actor, and apify-cli to ${tildify(r)}`)})}async confirmFromTty(e){let n,r,i=`${t.green(`?`)} ${t.bold(e)} ${t.dim(`(Y/n)`)} `,writeDone=n=>{process.stdout.write(`\r\x1b[2K${t.green(`?`)} ${t.bold(e)} ${t.cyan(n)}\n`)};try{return cliDebugPrint(`[install] opening /dev/tty for raw mode`),n=x(`/dev/tty`,`r`),r=new Rt(n),process.stdout.write(i),r.setRawMode(!0),r.resume(),await new Promise(e=>{let onData=t=>{let n=t.toString();n===`y`||n===`Y`||n===`\r`||n===`
115
+ actor --help`)})}async symlinkToLocalBin(e){let n=HOMEDIR();if(cliDebugPrint(`[install -> symlinkToLocalBin] user home directory`,n),!n){cliDebugPrint(`[install -> symlinkToLocalBin] user home directory not found`),warning({message:t.gray(`User home directory not found, cannot symlink to ~/.local/bin`)});return}let r=A(n,`.local`,`bin`);await F(r,{recursive:!0});for(let n of[`apify`,`actor`,`apify-cli`]){let i=A(e,n);if(!v(i)){cliDebugPrint(`[install] file not found for symlinking`,n,i),warning({message:t.gray(`Bundle not found for symlinking: ${n}`)});continue}let a=A(r,n);await je(a).catch(()=>{}),await Ae(i,a),cliDebugPrint(`[install] symlink created for item`,n,a)}info({message:t.gray(`Symlinked apify, actor, and apify-cli to ${tildify(r)}`)})}async confirmFromTty(e){let n,r,i=`${t.green(`?`)} ${t.bold(e)} ${t.dim(`(Y/n)`)} `,writeDone=n=>{process.stdout.write(`\r\x1b[2K${t.green(`?`)} ${t.bold(e)} ${t.cyan(n)}\n`)};try{return cliDebugPrint(`[install] opening /dev/tty for raw mode`),n=x(`/dev/tty`,`r`),r=new Lt(n),process.stdout.write(i),r.setRawMode(!0),r.resume(),await new Promise(e=>{let onData=t=>{let n=t.toString();n===`y`||n===`Y`||n===`\r`||n===`
116
116
  `?(r.removeListener(`data`,onData),writeDone(`Yes`),e(!0)):n===`n`||n===`N`?(r.removeListener(`data`,onData),writeDone(`No`),e(!1)):(n===``||n===``)&&(r.removeListener(`data`,onData),process.stdout.write(`
117
- `),e(!1))};r.on(`data`,onData)})}catch(e){return cliDebugPrint(`[install] failed to open /dev/tty for raw mode`,e),!1}finally{r&&(r.setRawMode(!1),r.pause(),r.destroy())}}async promptAddToShell(){let[e,n]=await Promise.allSettled([lt(`apify`,{nothrow:!0}),lt(`actor`,{nothrow:!0})]);if(e.status===`fulfilled`&&n.status===`fulfilled`&&e.value&&n.value){cliDebugPrint(`[install -> promptAddToShell] already in PATH`,{apifyCliPath:e,actorCliPath:n}),info({message:t.gray(`Apify and Actor CLIs are already in PATH, skipping shell integration`)});return}let r=HOMEDIR();cliDebugPrint(`[install -> promptAddToShell] user home directory`,r);let i=process.env.APIFY_CLI_INSTALL??k(r,`.apify`),a=process.env.FINAL_BIN_DIR??k(i,`bin`),s=process.env.PROVIDED_INSTALL_DIR??i;if(!s){warning({message:t.gray(`Install directory not found, cannot add to shell`)});return}let c=process.env.FINAL_BIN_DIR??a;simpleLog({message:``});let l=`Should the CLI handle adding itself to your shell automatically?`,u;process.env.APIFY_OPEN_TTY?u=await this.confirmFromTty(l):(cliDebugPrint(`[install] opening /dev/tty for raw mode not requested, falling back to normal flow`),u=await X({message:l,providedConfirmFromStdin:!1}));let f=detectShell(),p=shellConfigFile(r,f),m=`"${s.replaceAll(`"`,`\\"`)}"`,h=[],g=!0;switch(f){case`bash`:case`zsh`:h.push(`export APIFY_CLI_INSTALL=${m}`),h.push(`export PATH="$APIFY_CLI_INSTALL/bin:$PATH"`);break;case`fish`:h.push(`set --export APIFY_CLI_INSTALL ${m}`),h.push(`set --export PATH ${c} $PATH`);break;default:h.push(`export APIFY_CLI_INSTALL=${m}`),h.push(`export PATH="$APIFY_CLI_INSTALL/bin:$PATH"`),u=!1,g=!1;break}if(simpleLog({message:``}),u&&p){let e=`${await F(p,`utf-8`).catch(e=>{if(e.code===`ENOENT`)return``;throw Error(`Failed to read config file "${tildify(p)}". Received error code: ${e.code}; ${e.message}`)})}\n\n# apify cli\n${h.join(`
118
- `)}\n`;try{await P(O(p),{recursive:!0}),await R(p,e)}catch(e){throw e.code===`EACCES`?Error(`Failed to write to config file "${tildify(p)}", as the CLI does not have permission to write to it.`):Error(`Failed to write to config file "${tildify(p)}". Received error code: ${e.code}; ${e.message}`)}info({message:[t.gray(`Added "${tildify(c)}" to your PATH in ${tildify(p)}.`),t.gray(` You may need to run ${t.white.bold(`source ${tildify(p)}`)} to reload your shell.`)].join(`
117
+ `),e(!1))};r.on(`data`,onData)})}catch(e){return cliDebugPrint(`[install] failed to open /dev/tty for raw mode`,e),!1}finally{r&&(r.setRawMode(!1),r.pause(),r.destroy())}}async promptAddToShell(){let[e,n]=await Promise.allSettled([st(`apify`,{nothrow:!0}),st(`actor`,{nothrow:!0})]);if(e.status===`fulfilled`&&n.status===`fulfilled`&&e.value&&n.value){cliDebugPrint(`[install -> promptAddToShell] already in PATH`,{apifyCliPath:e,actorCliPath:n}),info({message:t.gray(`Apify and Actor CLIs are already in PATH, skipping shell integration`)});return}let r=HOMEDIR();cliDebugPrint(`[install -> promptAddToShell] user home directory`,r);let i=process.env.APIFY_CLI_INSTALL??A(r,`.apify`),a=process.env.FINAL_BIN_DIR??A(i,`bin`),s=process.env.PROVIDED_INSTALL_DIR??i;if(!s){warning({message:t.gray(`Install directory not found, cannot add to shell`)});return}let c=process.env.FINAL_BIN_DIR??a;simpleLog({message:``});let l=`Should the CLI handle adding itself to your shell automatically?`,u;process.env.APIFY_OPEN_TTY?u=await this.confirmFromTty(l):(cliDebugPrint(`[install] opening /dev/tty for raw mode not requested, falling back to normal flow`),u=await X({message:l,providedConfirmFromStdin:!1}));let f=detectShell(),p=shellConfigFile(r,f),m=`"${s.replaceAll(`"`,`\\"`)}"`,h=[],g=!0;switch(f){case`bash`:case`zsh`:h.push(`export APIFY_CLI_INSTALL=${m}`),h.push(`export PATH="$APIFY_CLI_INSTALL/bin:$PATH"`);break;case`fish`:h.push(`set --export APIFY_CLI_INSTALL ${m}`),h.push(`set --export PATH ${c} $PATH`);break;default:h.push(`export APIFY_CLI_INSTALL=${m}`),h.push(`export PATH="$APIFY_CLI_INSTALL/bin:$PATH"`),u=!1,g=!1;break}if(simpleLog({message:``}),u&&p){let e=`${await I(p,`utf-8`).catch(e=>{if(e.code===`ENOENT`)return``;throw Error(`Failed to read config file "${tildify(p)}". Received error code: ${e.code}; ${e.message}`)})}\n\n# apify cli\n${h.join(`
118
+ `)}\n`;try{await F(k(p),{recursive:!0}),await z(p,e)}catch(e){throw e.code===`EACCES`?Error(`Failed to write to config file "${tildify(p)}", as the CLI does not have permission to write to it.`):Error(`Failed to write to config file "${tildify(p)}". Received error code: ${e.code}; ${e.message}`)}info({message:[t.gray(`Added "${tildify(c)}" to your PATH in ${tildify(p)}.`),t.gray(` You may need to run ${t.white.bold(`source ${tildify(p)}`)} to reload your shell.`)].join(`
119
119
  `)});return}let _=p??`your shell config file`;if(g){let e=`echo -e '${h.join(`\\n`)}' >> "${_}" && source "${_}"`;info({message:[t.gray(`The Apify & Actor CLIs are not in your PATH. Run:`),``,t.white.bold(` ${e}`)].join(`
120
120
  `)});return}info({message:[t.gray(`Manually add the following lines to ${_} or similar:`),...h.map(e=>t.white.bold(` ${e}`))].join(`
121
- `)})}};const spawnPromised=async(e,t,n,{forwardSignals:r}={})=>{let i=normalizeExecutablePath(e);cliDebugPrint(`spawnPromised`,{escapedCommand:i,args:t,opts:n,forwardSignals:r});let a=ct(i,t,{shell:!0,windowsHide:!0,env:n.env,cwd:n.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}),s=[];if(r?.length)for(let e of r){let handler=()=>{a.kill(e)};process.on(e,handler),s.push(()=>process.off(e,handler))}try{return await tt.fromAsync(a.catch(t=>{let n;throw n=t.exitCode==null?t.signal?`${e} exited due to signal ${t.signal}`:t.shortMessage:`${e} exited with code ${t.exitCode}`,Error(n,{cause:t})}))}finally{for(let e of s)e()}};async function execWithLog({cmd:e,args:t=[],opts:n={},overrideCommand:r,forwardSignals:i}){run({message:`${r||e} ${t.join(` `)}`});let a=await spawnPromised(e,t,n,{forwardSignals:i});if(a.isErr()){let e=a.unwrapErr();if(error({message:e.message}),e.cause)throw e.cause}}const $=useCLIMetadata();function isInstalledOnMusl(){return $.platform===`linux`?v(`/etc/alpine-release`):!1}function isInstalledOnBaseline(){return $.platform===`darwin`&&$.arch===`x64`?!Ee(`sysctl -a`,{encoding:`utf-8`}).includes(`AVX2`):$.platform===`linux`&&$.arch===`x64`?!S(`/proc/cpuinfo`,`utf-8`).includes(`avx2`):$.platform===`windows`?$.arch===`arm64`?!0:Ee(`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}async function useCLIVersionAssets(e){let t=e.replace(/^v(\d+)/,`$1`),n=t===`latest`?`latest`:`tags/v${t}`,r=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/${n}`,{headers:{"User-Agent":mn}});if(!r.ok)return cliDebugPrint(`useCLIVersionAssets`,`Failed to fetch release`,{statusCode:r.status,body:await r.text(),version:e,tag:n}),null;let i=await r.json(),a=isInstalledOnMusl(),s=isInstalledOnBaseline(),c=i.assets.filter(e=>{let[n,r,i,c,l,u]=e.name.replace(t,`version`).replace(`.exe`,``).split(`-`);return i!==$.platform||c!==$.arch?!1:a?l===`musl`:s?u===`baseline`||l===`baseline`:!l&&!u});return cliDebugPrint(`useCLIVersionAssets`,`Fetched release`,{version:i.tag_name,filteredAssets:c}),{assets:c,version:i.tag_name.replace(/^v(\d+)/,`$1`)}}const pr={bundle:(e,t)=>[`${t}`,`upgrade`],npm:e=>[`npm`,`install`,`-g`,`apify-cli@${e}`],pnpm:e=>[`pnpm`,`install`,`-g`,`apify-cli@${e}`],bun:e=>[`bun`,`install`,`-g`,`apify-cli@${e}`],homebrew:()=>[`brew`,`upgrade`,`apify-cli`],volta:e=>[`volta`,`install`,`apify-cli@${e}`]},mr=`1.0.1`,hr=`https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1`;var UpgradeCommand=class extends ApifyCommand{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:Y.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:Y.string({description:`The version of the CLI to upgrade to. If not provided, the latest version will be used.`,required:!1}),"internal-automatic-call":Y.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 useCLIVersionCheck(!this.flags.internalAutomaticCall),{installMethod:n}=useCLIMetadata();if(!e.shouldUpdate||e.currentVersion===`0.0.0`){cliDebugPrint(`[upgrade] no update needed`,{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||info({message:`${this.cliName} is up to date 👍 \n`});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion(`latest`);return}let r=pr[n](`latest`,this.entrypoint).join(` `);simpleLog({message:``}),warning({message:[`You are using an old version of ${this.cliName}. We strongly recommend you always use the latest available version.`,` ↪ Run ${t.bgWhite(t.black(r))} to update! 👍 \n`].join(`
121
+ `)})}};const spawnPromised=async(e,t,n,{forwardSignals:r}={})=>{let i=normalizeExecutablePath(e);cliDebugPrint(`spawnPromised`,{escapedCommand:i,args:t,opts:n,forwardSignals:r});let a=ot(i,t,{shell:!0,windowsHide:!0,env:n.env,cwd:n.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}),s=[];if(r?.length)for(let e of r){let handler=()=>{a.kill(e)};process.on(e,handler),s.push(()=>process.off(e,handler))}try{return await $e.fromAsync(a.catch(t=>{let n;throw n=t.exitCode==null?t.signal?`${e} exited due to signal ${t.signal}`:t.shortMessage:`${e} exited with code ${t.exitCode}`,Error(n,{cause:t})}))}finally{for(let e of s)e()}};async function execWithLog({cmd:e,args:t=[],opts:n={},overrideCommand:r,forwardSignals:i}){run({message:`${r||e} ${t.join(` `)}`});let a=await spawnPromised(e,t,n,{forwardSignals:i});if(a.isErr()){let e=a.unwrapErr();if(error({message:e.message}),e.cause)throw e.cause}}const $=useCLIMetadata();function isInstalledOnMusl(){return $.platform===`linux`?v(`/etc/alpine-release`):!1}function isInstalledOnBaseline(){return $.platform===`darwin`&&$.arch===`x64`?!Te(`sysctl -a`,{encoding:`utf-8`}).includes(`AVX2`):$.platform===`linux`&&$.arch===`x64`?!S(`/proc/cpuinfo`,`utf-8`).includes(`avx2`):$.platform===`windows`?$.arch===`arm64`?!0:Te(`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}async function useCLIVersionAssets(e){let t=e.replace(/^v(\d+)/,`$1`),n=t===`latest`?`latest`:`tags/v${t}`,r=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/${n}`,{headers:{"User-Agent":pn}});if(!r.ok)return cliDebugPrint(`useCLIVersionAssets`,`Failed to fetch release`,{statusCode:r.status,body:await r.text(),version:e,tag:n}),null;let i=await r.json(),a=isInstalledOnMusl(),s=isInstalledOnBaseline(),c=i.assets.filter(e=>{let[n,r,i,c,l,u]=e.name.replace(t,`version`).replace(`.exe`,``).split(`-`);return i!==$.platform||c!==$.arch?!1:a?l===`musl`:s?u===`baseline`||l===`baseline`:!l&&!u});return cliDebugPrint(`useCLIVersionAssets`,`Fetched release`,{version:i.tag_name,filteredAssets:c}),{assets:c,version:i.tag_name.replace(/^v(\d+)/,`$1`)}}const pr={bundle:(e,t)=>[`${t}`,`upgrade`],npm:e=>[`npm`,`install`,`-g`,`apify-cli@${e}`],pnpm:e=>[`pnpm`,`install`,`-g`,`apify-cli@${e}`],bun:e=>[`bun`,`install`,`-g`,`apify-cli@${e}`],homebrew:()=>[`brew`,`upgrade`,`apify-cli`],volta:e=>[`volta`,`install`,`apify-cli@${e}`]},mr=`1.0.1`,hr=`https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1`;var UpgradeCommand=class extends ApifyCommand{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:Y.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:Y.string({description:`The version of the CLI to upgrade to. If not provided, the latest version will be used.`,required:!1}),"internal-automatic-call":Y.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 useCLIVersionCheck(!this.flags.internalAutomaticCall),{installMethod:n}=useCLIMetadata();if(!e.shouldUpdate||e.currentVersion===`0.0.0`){cliDebugPrint(`[upgrade] no update needed`,{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||info({message:`${this.cliName} is up to date 👍 \n`});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion(`latest`);return}let r=pr[n](`latest`,this.entrypoint).join(` `);simpleLog({message:``}),warning({message:[`You are using an old version of ${this.cliName}. We strongly recommend you always use the latest available version.`,` ↪ Run ${t.bgWhite(t.black(r))} to update! 👍 \n`].join(`
122
122
  `)})}async handleInstallSpecificVersion(e){if(e!==`latest`&&!u(e,mr)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${mr}.`});return}let t=await useCLIVersionAssets(e);if(!t){error({message:`The provided version does not exist. Please check the version number and try again.`});return}let{assets:n,version:r}=t;if(!u(r,mr)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${mr}.`});return}let i=useCLIMetadata();if(i.installMethod===`bundle`){if(!n.length){error({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: ${r}`,`- The system you are running on: ${i.platform} ${i.arch}`].join(`
123
- `)});return}let e=O(process.execPath);cliDebugPrint(`[upgrade] bundleDirectory`,e);let t=await I(e);if(!t.some(e=>e.startsWith(`apify`)||e.startsWith(`actor`))){cliDebugPrint(`[upgrade] directoryEntries`,t),error({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: ${r}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${e}`].join(`
124
- `)});return}if(i.platform===`windows`)return this.startUpgradeProcess(e,r,n);await this.handleUnixUpgrade(e,r,n),this.successMessage(r);return}let a=pr[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){info({message:`Would run command: ${a.join(` `)}`});return}try{await execWithLog({cmd:a[0],args:a.slice(1)}),this.successMessage(r)}catch{error({message:`Failed to upgrade the CLI. Please run the following command manually: ${a.join(` `)}`})}}successMessage(e){success({message:`Successfully upgraded to ${e} 👍`})}async startUpgradeProcess(e,t,n){await this.upsertUpgradeScript(e);let r=[`-ExecutionPolicy`,`Bypass`,`-File`,`"${k(e,`upgrade.ps1`)}"`,`-ProcessId`,process.pid.toString(),`-InstallLocation`,`"${e}"`,`-Version`,`"${t}"`],i=n.map(e=>e.browser_download_url).join(`,`);r.push(`-AllUrls`,`"${i}"`),cliDebugPrint(`[upgrade] starting upgrade process with args`,r),info({message:`Starting upgrade process...`});let a=De(`powershell.exe`,r,{detached:!0,shell:!0,stdio:`inherit`,windowsHide:!1,windowsVerbatimArguments:!0});a.on(`spawn`,()=>{cliDebugPrint(`[upgrade] upgrade process spawned`),a.unref(),process.exit(0)}),a.on(`error`,e=>{error({message:`Failed to start the upgrade process: ${e.message}`})})}async upsertUpgradeScript(e){let t=k(e,`upgrade.ps1`);if(v(t))return;let n=useCLIMetadata(),r=await fetch(hr,{headers:{"User-Agent":mn}});r.ok||(error({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: ${n.platform} ${n.arch}`,`- The URL of the asset that failed to fetch: ${hr}`,`- The status code of the response: ${r.status}`].join(`
125
- `)}),process.exit(1));let i=await r.arrayBuffer();await R(t,Buffer.from(i)),cliDebugPrint(`[upgrade] downloaded upgrade script to`,t)}async handleUnixUpgrade(e,n,r){let i=useCLIMetadata();for(let a of r){let r=a.name.split(`-`)[0],s=k(e,r);info({message:`Downloading \`${r}\` binary of the Apify CLI...`});let c=await fetch(a.browser_download_url,{headers:{"User-Agent":mn}});if(!c.ok){let e=await c.text();cliDebugPrint(`[upgrade] failed to fetch asset`,{asset:a,status:c.status,body:e}),error({message:[`Failed to fetch the ${r} 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: ${n}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The URL of the asset that failed to fetch: ${a.browser_download_url}`,`- The status code of the response: ${c.status}`,`- The body of the response: ${e}`].join(`
126
- `)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){info({message:`Would write asset ${r} to ${s}`});continue}info({message:t.gray(`Writing ${r} to ${s}...`)});let l=await c.arrayBuffer();try{let e=await ke(s).then(e=>e.mode).catch(()=>493);await R(s,Buffer.from(l),{mode:e|448}),cliDebugPrint(`[upgrade ${r}] wrote asset to`,s)}catch(e){cliDebugPrint(`[upgrade] failed to write asset`,{error:e}),error({message:[`Failed to write the ${r} 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: ${n}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The URL of the asset that failed to fetch: ${a.browser_download_url}`,`- The error: ${e.message}`].join(`
123
+ `)});return}let e=k(process.execPath);cliDebugPrint(`[upgrade] bundleDirectory`,e);let t=await L(e);if(!t.some(e=>e.startsWith(`apify`)||e.startsWith(`actor`))){cliDebugPrint(`[upgrade] directoryEntries`,t),error({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: ${r}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${e}`].join(`
124
+ `)});return}if(i.platform===`windows`)return this.startUpgradeProcess(e,r,n);await this.handleUnixUpgrade(e,r,n),this.successMessage(r);return}let a=pr[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){info({message:`Would run command: ${a.join(` `)}`});return}try{await execWithLog({cmd:a[0],args:a.slice(1)}),this.successMessage(r)}catch{error({message:`Failed to upgrade the CLI. Please run the following command manually: ${a.join(` `)}`})}}successMessage(e){success({message:`Successfully upgraded to ${e} 👍`})}async startUpgradeProcess(e,t,n){await this.upsertUpgradeScript(e);let r=[`-ExecutionPolicy`,`Bypass`,`-File`,`"${A(e,`upgrade.ps1`)}"`,`-ProcessId`,process.pid.toString(),`-InstallLocation`,`"${e}"`,`-Version`,`"${t}"`],i=n.map(e=>e.browser_download_url).join(`,`);r.push(`-AllUrls`,`"${i}"`),cliDebugPrint(`[upgrade] starting upgrade process with args`,r),info({message:`Starting upgrade process...`});let a=Ee(`powershell.exe`,r,{detached:!0,shell:!0,stdio:`inherit`,windowsHide:!1,windowsVerbatimArguments:!0});a.on(`spawn`,()=>{cliDebugPrint(`[upgrade] upgrade process spawned`),a.unref(),process.exit(0)}),a.on(`error`,e=>{error({message:`Failed to start the upgrade process: ${e.message}`})})}async upsertUpgradeScript(e){let t=A(e,`upgrade.ps1`);if(v(t))return;let n=useCLIMetadata(),r=await fetch(hr,{headers:{"User-Agent":pn}});r.ok||(error({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: ${n.platform} ${n.arch}`,`- The URL of the asset that failed to fetch: ${hr}`,`- The status code of the response: ${r.status}`].join(`
125
+ `)}),process.exit(1));let i=await r.arrayBuffer();await z(t,Buffer.from(i)),cliDebugPrint(`[upgrade] downloaded upgrade script to`,t)}async handleUnixUpgrade(e,n,r){let i=useCLIMetadata();for(let a of r){let r=a.name.split(`-`)[0],s=A(e,r);info({message:`Downloading \`${r}\` binary of the Apify CLI...`});let c=await fetch(a.browser_download_url,{headers:{"User-Agent":pn}});if(!c.ok){let e=await c.text();cliDebugPrint(`[upgrade] failed to fetch asset`,{asset:a,status:c.status,body:e}),error({message:[`Failed to fetch the ${r} 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: ${n}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The URL of the asset that failed to fetch: ${a.browser_download_url}`,`- The status code of the response: ${c.status}`,`- The body of the response: ${e}`].join(`
126
+ `)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){info({message:`Would write asset ${r} to ${s}`});continue}info({message:t.gray(`Writing ${r} to ${s}...`)});let l=await c.arrayBuffer();try{let e=await Oe(s).then(e=>e.mode).catch(()=>493);await z(s,Buffer.from(l),{mode:e|448}),cliDebugPrint(`[upgrade ${r}] wrote asset to`,s)}catch(e){cliDebugPrint(`[upgrade] failed to write asset`,{error:e}),error({message:[`Failed to write the ${r} 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: ${n}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The URL of the asset that failed to fetch: ${a.browser_download_url}`,`- The error: ${e.message}`].join(`
127
127
  `)})}}}};const gr=[`JavaScript`,`TypeScript`,`Python`];async function ensureValidActorName(e){return e?(validateActorName(e),e):promptActorName()}async function getTemplateDefinition(e,t){let n=await t;if(n instanceof Error)throw n;if(e){let t=n.templates.find(t=>t.name===e);if(!t)throw Error(`Could not find the selected template: ${e} in the list of templates.`);return t}return executePrompts(n)}async function enhanceReadmeWithLocalSuffix(e,t){let n=await t;if(n instanceof Error)throw n;try{let t=await httpsGet(n.localReadmeSuffixUrl),r=_(e,{flags:`a`});r.write(`
128
128
 
129
- `),await Fe(t,r)}catch(e){warning({message:`Could not append local development instructions to README.md. Cause: ${e.message}`})}}function formatCreateSuccessMessage(e){let{actorName:t,dependenciesInstalled:n,postCreate:r,gitRepositoryInitialized:i,installCommandSuggestion:a}=e,s=`✅ Actor '${t}' created successfully!`;return n?s+=`\n\nNext steps:\n\ncd "${t}"\napify run`:s+=`\n\nNext steps:\n\ncd "${t}"\n${a||`install dependencies with your package manager`}\napify run`,s+=`
129
+ `),await Pe(t,r)}catch(e){warning({message:`Could not append local development instructions to README.md. Cause: ${e.message}`})}}function formatCreateSuccessMessage(e){let{actorName:t,dependenciesInstalled:n,postCreate:r,gitRepositoryInitialized:i,installCommandSuggestion:a}=e,s=`✅ Actor '${t}' created successfully!`;return n?s+=`\n\nNext steps:\n\ncd "${t}"\napify run`:s+=`\n\nNext steps:\n\ncd "${t}"\n${a||`install dependencies with your package manager`}\napify run`,s+=`
130
130
 
131
131
  💡 Tip: Use 'apify push' to deploy your Actor to the Apify platform
132
- 📖 Docs: https://docs.apify.com/platform/actors/development`,i&&(s+=`\n🌱 Git repository initialized in '${t}'. You can now commit and push your Actor to Git.`),r&&(s+=`\n\n${r}`),s}async function executePrompts(e){let t=await promptProgrammingLanguage();for(;;){let n=await promptTemplateDefinition(e,t);if(n){if(await promptTemplateInstallation())return n}else return executePrompts(e)}}async function promptActorName(){return await On({message:`Name of your new Actor:`,validate:e=>{try{validateActorName(e)}catch(e){return e.message}return!0}})}async function promptProgrammingLanguage(){return await cr({message:`Choose the programming language of your new Actor:`,choices:gr,loop:!1,default:gr[0]})}async function promptTemplateDefinition(e,t){let n=[...e.templates.filter(e=>e.category.toLowerCase()===t.toLowerCase()).map(e=>({name:e.label,value:e})),new dt,{name:`Go back`,value:!1}];return await cr({message:`Choose a template for your new Actor. You can check more information at https://apify.com/templates.`,default:n[0],choices:n,loop:!1,pageSize:8})}async function promptTemplateInstallation(){let e=[{name:`Install dependencies`,value:!0},new dt,{name:`Go back`,value:!1}];return await cr({message:`Almost done! Last step is to install dependencies.`,default:e[0],choices:e,loop:!1})}var CreateCommand=class extends ApifyCommand{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:Y.string({char:`t`,description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${At} to find available template names.`,required:!1}),"skip-dependency-install":Y.boolean({description:`Skip installing Actor dependencies.`,required:!1}),"template-archive-url":Y.string({description:`Actor template archive url. Useful for developing new templates.`,required:!1,hidden:!0}),"omit-optional-deps":Y.boolean({aliases:[`no-optional`],description:`Skip installing optional dependencies.`,required:!1}),"skip-git-init":Y.boolean({description:`Skip initializing a git repository in the Actor directory.`,required:!1})};static args={actorName:Z.string({required:!1,description:`Name of the Actor and its directory.`})};async run(){let{actorName:t}=this.args,{template:n,skipDependencyInstall:r,skipGitInit:i}=this.flags,{templateArchiveUrl:a}=this.flags,s=!1,c=kt().catch(e=>Error(`Could not fetch template list from server. Cause: ${e?.message}`));t=await ensureValidActorName(t);let l=e.cwd(),p=k(l,t);for(;;){let e=await L(p).catch(()=>null),n=e&&await I(p).then(e=>e.length>0).catch(()=>!1);if(e?.isDirectory()&&n){error({message:`Cannot create new Actor, directory '${t}' already exists. Please provide a different name. You can use "apify init" to create a local Actor environment inside an existing directory.`}),t=await ensureValidActorName(),p=k(l,t);continue}e||await P(p,{recursive:!0});break}let m=null;if(this.telemetryData.fromArchiveUrl=!!a,!a){let e=await getTemplateDefinition(n,c);({archiveUrl:a,messages:m}=e),this.telemetryData.templateId=e.id,this.telemetryData.templateName=e.name,this.telemetryData.templateLanguage=e.category,`skipOptionalDeps`in e&&(s=e.skipOptionalDeps)}this.flags.omitOptionalDeps&&(s=!0),await downloadAndUnzip({url:a,pathTo:p});let h=getJsonFileContent(k(p,U));await setLocalConfig(Object.assign(h||tn,{name:t}),p),await setLocalEnv(p),await createPrefilledInputFileFromInputSchema(p);let g=k(p,`package.json`);await enhanceReadmeWithLocalSuffix(k(p,`README.md`),c);let _=!1;r||await(await useCwdProject({cwd:p})).inspectAsync(async n=>{let r=f(W);if(!n.runtime){switch(n.type){case 0:warning({message:`No Node.js detected! Please install Node.js ${r} or higher to be able to run Node.js Actors locally.`});break;case 2:case 1:warning({message:`No Python detected! Please install Python ${sn} or higher to be able to run Python Actors locally.`});break;default:}return}let{runtime:i}=n;switch(n.type){case 0:{isNodeVersionSupported(i.version)||warning({message:`You are running Node.js version ${i.version}, which is no longer supported. Please upgrade to Node.js version ${r} or later.`}),await updateLocalJson(g,{name:t});let e=[`install`];if(s)switch(i.pmName){case`npm`:u(i.pmVersion,`7.0.0`)?e.push(`--omit=optional`):e.push(`--no-optional`);break;case`bun`:e.push(`--omit=optional`);break;case`deno`:e.push(`--node-modules-dir`);break;default:}await execWithLog({cmd:i.pmPath,args:e,opts:{cwd:p},overrideCommand:i.pmName}),_=!0;break}case 1:case 2:{if(!isPythonVersionSupported(i.version)){warning({message:`Python Actors require Python 3.9 or higher, but you have Python ${i.version}!`}),warning({message:`Please install Python 3.9 or higher to be able to run Python Actors locally.`});return}let t=k(p,`.venv`);info({message:`Python version ${i.version} detected.`}),info({message:`Creating a virtual environment in "${t}" and installing dependencies from "requirements.txt"...`}),e.env.VIRTUAL_ENV||(await execWithLog({cmd:i.executablePath,args:[`-m`,`venv`,`--prompt`,`.`,`.venv`],opts:{cwd:p}}),i=(await usePythonRuntime({cwd:p,force:!0})).unwrap(),n.runtime=i),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`--upgrade`,`pip`,`setuptools`,`wheel`],opts:{cwd:p}}),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`-r`,`requirements.txt`],opts:{cwd:p}}),_=!0;break}default:}});let v={success:!0},y=await L(k(l,`.git`)).catch(()=>null);if(!i&&!y)try{await execWithLog({cmd:`git`,args:[`init`],opts:{cwd:p}})}catch(e){v={success:!1,error:e}}let b=_?null:await getInstallCommandSuggestion(p);simpleLog({message:``}),success({message:formatCreateSuccessMessage({actorName:t,dependenciesInstalled:_,postCreate:m?.postCreate??null,gitRepositoryInitialized:!i&&!y&&v.success,installCommandSuggestion:b})}),!i&&!y&&!v.success&&(warning({message:`Failed to initialize git repository: ${v.error.message}`}),warning({message:`You can manually run "git init" in the Actor directory if needed.`}))}};async function tryToGetStorage(e,t,n){let r=await e[n](t).get().catch(()=>void 0);if(r)return{[n]:r,[`${n}Client`]:e[n](r.id)};let i=await getLocalUserInfo(),a=await e[n](`${i.username}/${t}`).get().catch(()=>void 0);return a?{[n]:a,[`${n}Client`]:e[n](a.id)}:null}async function tryToGetDataset(e,t){return tryToGetStorage(e,t,`dataset`)}async function tryToGetKeyValueStore(e,t){return tryToGetStorage(e,t,`keyValueStore`)}var DatasetsCreateCommand=class extends ApifyCommand{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:Z.string({description:`Optional name for the Dataset.`,required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetDataset(n,e)){error({message:`A Dataset with this name already exists!`});return}let r=await n.datasets().getOrCreate(e);if(this.flags.json){printJsonToStdout(r);return}success({message:`Dataset with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}};const _r={[z.JSON]:`application/json`,[z.JSONL]:`application/jsonl`,[z.CSV]:`text/csv`,[z.HTML]:`text/html`,[z.RSS]:`application/rss+xml`,[z.XML]:`application/xml`,[z.XLSX]:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};var DatasetsGetItems=class extends ApifyCommand{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:Y.integer({description:`The amount of elements to get from the dataset. By default, it will return all available items.`}),offset:Y.integer({description:`The offset in the dataset where to start getting items.`}),format:Y.string({description:`The format of the returned output. By default, it is set to 'json'.`,choices:Object.keys(_r),default:z.JSON})};static args={datasetId:Z.string({description:`The ID of the Dataset to export the items for.`,required:!0})};async run(){let{limit:e,offset:t,format:n}=this.flags,{datasetId:r}=this.args,i=await getLoggedClientOrThrow(),a=await this.tryToGetDataset(i,r);if(!a){error({message:`Dataset with ID "${r}" not found.`});return}let{datasetClient:s}=a;process.stdout.write(``);let c=await s.downloadItems(n,{limit:e,offset:t});simpleLog({message:_r[n]??`application/octet-stream`}),process.stdout.write(c),process.stdout.write(`
132
+ 📖 Docs: https://docs.apify.com/platform/actors/development`,i&&(s+=`\n🌱 Git repository initialized in '${t}'. You can now commit and push your Actor to Git.`),r&&(s+=`\n\n${r}`),s}async function executePrompts(e){let t=await promptProgrammingLanguage();for(;;){let n=await promptTemplateDefinition(e,t);if(n){if(await promptTemplateInstallation())return n}else return executePrompts(e)}}async function promptActorName(){return await On({message:`Name of your new Actor:`,validate:e=>{try{validateActorName(e)}catch(e){return e.message}return!0}})}async function promptProgrammingLanguage(){return await cr({message:`Choose the programming language of your new Actor:`,choices:gr,loop:!1,default:gr[0]})}async function promptTemplateDefinition(e,t){let n=[...e.templates.filter(e=>e.category.toLowerCase()===t.toLowerCase()).map(e=>({name:e.label,value:e})),new lt,{name:`Go back`,value:!1}];return await cr({message:`Choose a template for your new Actor. You can check more information at https://apify.com/templates.`,default:n[0],choices:n,loop:!1,pageSize:8})}async function promptTemplateInstallation(){let e=[{name:`Install dependencies`,value:!0},new lt,{name:`Go back`,value:!1}];return await cr({message:`Almost done! Last step is to install dependencies.`,default:e[0],choices:e,loop:!1})}var CreateCommand=class extends ApifyCommand{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:Y.string({char:`t`,description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${kt} to find available template names.`,required:!1}),"skip-dependency-install":Y.boolean({description:`Skip installing Actor dependencies.`,required:!1}),"template-archive-url":Y.string({description:`Actor template archive url. Useful for developing new templates.`,required:!1,hidden:!0}),"omit-optional-deps":Y.boolean({aliases:[`no-optional`],description:`Skip installing optional dependencies.`,required:!1}),"skip-git-init":Y.boolean({description:`Skip initializing a git repository in the Actor directory.`,required:!1})};static args={actorName:Z.string({required:!1,description:`Name of the Actor and its directory.`})};async run(){let{actorName:t}=this.args,{template:n,skipDependencyInstall:r,skipGitInit:i}=this.flags,{templateArchiveUrl:a}=this.flags,s=!1,c=Ot().catch(e=>Error(`Could not fetch template list from server. Cause: ${e?.message}`));t=await ensureValidActorName(t);let l=e.cwd(),p=A(l,t);for(;;){let e=await R(p).catch(()=>null),n=e&&await L(p).then(e=>e.length>0).catch(()=>!1);if(e?.isDirectory()&&n){error({message:`Cannot create new Actor, directory '${t}' already exists. Please provide a different name. You can use "apify init" to create a local Actor environment inside an existing directory.`}),t=await ensureValidActorName(),p=A(l,t);continue}e||await F(p,{recursive:!0});break}let m=null;if(this.telemetryData.fromArchiveUrl=!!a,!a){let e=await getTemplateDefinition(n,c);({archiveUrl:a,messages:m}=e),this.telemetryData.templateId=e.id,this.telemetryData.templateName=e.name,this.telemetryData.templateLanguage=e.category,`skipOptionalDeps`in e&&(s=e.skipOptionalDeps)}this.flags.omitOptionalDeps&&(s=!0),await downloadAndUnzip({url:a,pathTo:p});let h=getJsonFileContent(A(p,W));await setLocalConfig(Object.assign(h||en,{name:t}),p),await setLocalEnv(p),await createPrefilledInputFileFromInputSchema(p);let g=A(p,`package.json`);await enhanceReadmeWithLocalSuffix(A(p,`README.md`),c);let _=!1;r||await(await useCwdProject({cwd:p})).inspectAsync(async n=>{let r=f(rn);if(!n.runtime){switch(n.type){case 0:warning({message:`No Node.js detected! Please install Node.js ${r} or higher to be able to run Node.js Actors locally.`});break;case 2:case 1:warning({message:`No Python detected! Please install Python ${on} or higher to be able to run Python Actors locally.`});break;default:}return}let{runtime:i}=n;switch(n.type){case 0:{isNodeVersionSupported(i.version)||warning({message:`You are running Node.js version ${i.version}, which is no longer supported. Please upgrade to Node.js version ${r} or later.`}),await updateLocalJson(g,{name:t});let e=[`install`];if(s)switch(i.pmName){case`npm`:u(i.pmVersion,`7.0.0`)?e.push(`--omit=optional`):e.push(`--no-optional`);break;case`bun`:e.push(`--omit=optional`);break;case`deno`:e.push(`--node-modules-dir`);break;default:}await execWithLog({cmd:i.pmPath,args:e,opts:{cwd:p},overrideCommand:i.pmName}),_=!0;break}case 1:case 2:{if(!isPythonVersionSupported(i.version)){warning({message:`Python Actors require Python 3.9 or higher, but you have Python ${i.version}!`}),warning({message:`Please install Python 3.9 or higher to be able to run Python Actors locally.`});return}let t=A(p,`.venv`);info({message:`Python version ${i.version} detected.`}),info({message:`Creating a virtual environment in "${t}" and installing dependencies from "requirements.txt"...`}),e.env.VIRTUAL_ENV||(await execWithLog({cmd:i.executablePath,args:[`-m`,`venv`,`--prompt`,`.`,`.venv`],opts:{cwd:p}}),i=(await usePythonRuntime({cwd:p,force:!0})).unwrap(),n.runtime=i),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`--upgrade`,`pip`,`setuptools`,`wheel`],opts:{cwd:p}}),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`-r`,`requirements.txt`],opts:{cwd:p}}),_=!0;break}default:}});let v={success:!0},y=await R(A(l,`.git`)).catch(()=>null);if(!i&&!y)try{await execWithLog({cmd:`git`,args:[`init`],opts:{cwd:p}})}catch(e){v={success:!1,error:e}}let b=_?null:await getInstallCommandSuggestion(p);simpleLog({message:``}),success({message:formatCreateSuccessMessage({actorName:t,dependenciesInstalled:_,postCreate:m?.postCreate??null,gitRepositoryInitialized:!i&&!y&&v.success,installCommandSuggestion:b})}),!i&&!y&&!v.success&&(warning({message:`Failed to initialize git repository: ${v.error.message}`}),warning({message:`You can manually run "git init" in the Actor directory if needed.`}))}};async function tryToGetStorage(e,t,n){let r=await e[n](t).get().catch(()=>void 0);if(r)return{[n]:r,[`${n}Client`]:e[n](r.id)};let i=await getLocalUserInfo(),a=await e[n](`${i.username}/${t}`).get().catch(()=>void 0);return a?{[n]:a,[`${n}Client`]:e[n](a.id)}:null}async function tryToGetDataset(e,t){return tryToGetStorage(e,t,`dataset`)}async function tryToGetKeyValueStore(e,t){return tryToGetStorage(e,t,`keyValueStore`)}var DatasetsCreateCommand=class extends ApifyCommand{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:Z.string({description:`Optional name for the Dataset.`,required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetDataset(n,e)){error({message:`A Dataset with this name already exists!`});return}let r=await n.datasets().getOrCreate(e);if(this.flags.json){printJsonToStdout(r);return}success({message:`Dataset with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}};const _r={[V.JSON]:`application/json`,[V.JSONL]:`application/jsonl`,[V.CSV]:`text/csv`,[V.HTML]:`text/html`,[V.RSS]:`application/rss+xml`,[V.XML]:`application/xml`,[V.XLSX]:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};var DatasetsGetItems=class extends ApifyCommand{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:Y.integer({description:`The amount of elements to get from the dataset. By default, it will return all available items.`}),offset:Y.integer({description:`The offset in the dataset where to start getting items.`}),format:Y.string({description:`The format of the returned output. By default, it is set to 'json'.`,choices:Object.keys(_r),default:V.JSON})};static args={datasetId:Z.string({description:`The ID of the Dataset to export the items for.`,required:!0})};async run(){let{limit:e,offset:t,format:n}=this.flags,{datasetId:r}=this.args,i=await getLoggedClientOrThrow(),a=await this.tryToGetDataset(i,r);if(!a){error({message:`Dataset with ID "${r}" not found.`});return}let{datasetClient:s}=a;process.stdout.write(``);let c=await s.downloadItems(n,{limit:e,offset:t});simpleLog({message:_r[n]??`application/octet-stream`}),process.stdout.write(c),process.stdout.write(`
133
133
  `)}async tryToGetDataset(e,t){let n=await e.dataset(t).get().catch(()=>void 0);if(n)return{dataset:n,datasetClient:e.dataset(n.id)};let r=await getLocalUserInfo(),i=await e.dataset(`${r.username}/${t}`).get().catch(()=>void 0);return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};function getUserPlanPricing(e){let t=Reflect.get(e,`planPricing`);return t?Reflect.get(t,`chargeableServiceUnitPricesUsd`):null}const vr=new Q({allColumns:[`Row1`,`Row2`],mandatoryColumns:[`Row1`,`Row2`]});var DatasetsInfoCommand=class extends ApifyCommand{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:Z.string({description:`The dataset store ID to print information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,n=await getLoggedClientOrThrow(),r=await tryToGetDataset(n,e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{dataset:i}=r,[a,s,c]=await Promise.all([n.user(i.userId).get().then(e=>e),i.actId?n.actor(i.actId).get():Promise.resolve(void 0),i.actRunId?n.run(i.actRunId).get():Promise.resolve(void 0)]),l;if(c?.actorTaskId&&(l=await n.task(c.actorTaskId).get().catch(()=>void 0)),this.flags.json){printJsonToStdout({...i,user:a,actor:s||null,run:c||null,task:l||null});return}let u=i.stats?.storageBytes||0,f=i.stats?.readCount||0,p=i.stats?.writeCount||0,m=(i.cleanItemCount||0).toLocaleString(`en-US`),h=(i.itemCount||0).toLocaleString(`en-US`),g=[`${t.bold(f.toLocaleString(`en-US`))} ${t.gray(this.pluralString(f,`read`,`reads`))}`,`${t.bold(p.toLocaleString(`en-US`))} ${t.gray(this.pluralString(p,`write`,`writes`))}`],_=`Items: ${t.bold(m)} ${t.gray(`clean`)} / ${t.bold(h)} ${t.gray(`total`)}\nOperations: ${g.join(` / `)}`;if(a.plan){let e=getUserPlanPricing(a.plan);if(e){let n=e.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(u/1e3**3),r=n*24*30,i=r>1?`$${r.toFixed(2)}`:`$${n.toFixed(3)}`;_+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`${i} per month`)}`}}else _+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})}`;let v=[`Dataset ID: ${t.bgGray(i.id)}`,`Name: ${i.name?t.bgGray(i.name):t.bold(t.italic(`Unnamed`))}`,`Created: ${t.bold(G.display(i.createdAt))}`,`Modified: ${t.bold(G.display(i.modifiedAt))}`].join(`
134
134
  `),y=t.bold(`—`);i.actRunId&&(y=c?t.bgBlue(c.id):t.italic(t.gray(`Run removed`)));let b=t.bold(`—`);s&&(b=t.blue(s.title||s.name));let x=t.bold(`—`);l&&(x=t.blue(l.title||l.name));let S=[`Run: ${y}`,`Actor: ${b}`,`Task: ${x}`].join(`
135
135
  `);vr.pushRow({Row1:v,Row2:S});let C=vr.render(2).split(`
136
136
  `).map(e=>e.trim());C.shift(),simpleLog({message:[`${t.bold(i.name||t.italic(`Unnamed`))}`,`${t.gray(i.name?`${a.username}/${i.name}`:i.id)} ${t.gray(`Owned by`)} ${t.blue(a.username)}`,``,C.join(`
137
137
  `),``,_].join(`
138
- `),stdout:!0})}};const yr=new Q({allColumns:[`Dataset ID`,`Name`,`Items`,`Size`,`Created`,`Modified`],mandatoryColumns:[`Dataset ID`,`Name`,`Items`,`Size`],columnAlignments:{Items:`right`}});var DatasetsLsCommand=class extends ApifyCommand{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:Y.integer({description:`Number of datasets that will be skipped.`,default:0}),limit:Y.integer({description:`Number of datasets that will be listed.`,default:20}),desc:Y.boolean({description:`Sorts datasets in descending order.`,default:!1}),unnamed:Y.boolean({description:`Lists datasets that don't have a name set.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:n,limit:r,json:i,unnamed:a}=this.flags,s=await getLoggedClientOrThrow(),c=await getLocalUserInfo(),l=await s.datasets().list({desc:e,offset:n,limit:r,unnamed:a});if(i){printJsonToStdout(l);return}if(l.count===0){info({message:`You don't have any Datasets on your account`,stdout:!0});return}for(let e of l.items){let n=Reflect.get(e.stats,`s3StorageBytes`);yr.pushRow({"Dataset ID":e.id,Created:G.display(e.createdAt),Items:`${e.itemCount}`,Modified:G.display(e.modifiedAt),Name:e.name?`${c.username}/${e.name}`:``,Size:typeof n==`number`?prettyPrintBytes({bytes:n,shortBytes:!0,colorFunc:t.gray,precision:0}):t.gray(`N/A`)})}simpleLog({message:yr.render(1),stdout:!0})}},DatasetsPushDataCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The dataset ID or name to push the objects to.`,ignoreStdin:!0}),item:Z.string({description:`The object or array of objects to be pushed.`})};async run(){let{nameOrId:e,item:n}=this.args,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:a}=r,s,c=n||fn;if(!c){error({message:`No items were provided.`});return}try{s=JSON.parse(c.toString(`utf8`))}catch(e){error({message:`Failed to parse data as JSON string: ${e.message}`});return}if(Array.isArray(s)&&s.length===0){error({message:`No items were provided.`});return}let l=a.name?`Dataset named ${t.yellow(a.name)} (${t.gray(`ID:`)} ${t.yellow(a.id)})`:`Dataset with ID ${t.yellow(a.id)}`;try{await i.pushItems(s),success({message:`${this.pluralString(Array.isArray(s)?s.length:1,`Object`,`Objects`)} pushed to ${l} successfully.`})}catch(e){let t=e;error({message:`Failed to push items into ${l}\n ${t.message||t}`})}}},DatasetsRenameCommand=class extends ApifyCommand{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:Y.boolean({description:`Removes the unique name of the dataset.`})};static args={nameOrId:Z.string({description:`The dataset ID or name to delete.`,required:!0}),newName:Z.string({description:`The new name for the dataset.`})};async run(){let{unname:e}=this.flags,{newName:n,nameOrId:r}=this.args;if(!n&&!e){error({message:`You must provide either a new name or the --unname flag.`});return}if(n&&e){error({message:`You cannot provide a new name and the --unname flag.`});return}let i=await tryToGetDataset(await getLoggedClientOrThrow(),r);if(!i){error({message:`Dataset with ID or name "${r}" not found.`});return}let{id:a,name:s}=i.dataset,c=s?e?`The name of the dataset with ID ${t.yellow(a)} has been removed (was ${t.yellow(s)} previously).`:`The name of the dataset with ID ${t.yellow(a)} was changed from ${t.yellow(s)} to ${t.yellow(n)}.`:`The name of the dataset with ID ${t.yellow(a)} has been set to: ${t.yellow(n)}`;try{await i.datasetClient.update({name:e?null:n}),success({message:c,stdout:!0})}catch(e){let n=e;error({message:`Failed to rename dataset with ID ${t.yellow(a)}\n ${n.message||n}`})}}},DatasetsRmCommand=class extends ApifyCommand{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:Z.string({description:`The dataset ID or name to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{datasetNameOrId:e}=this.args,{yes:n}=this.flags,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}if(!await X({message:`Are you sure you want to delete this Dataset?`,providedConfirmFromStdin:n||void 0})){info({message:`Dataset deletion has been aborted.`});return}let{id:i,name:a}=r.dataset;try{await r.datasetClient.delete(),success({message:`Dataset with ID ${t.yellow(i)}${a?` (called ${t.yellow(a)})`:``} has been deleted.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to delete dataset with ID ${t.yellow(i)}\n ${n.message||n}`})}}},DatasetsIndexCommand=class extends ApifyCommand{static name=`datasets`;static description=`Manage Apify datasets — 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=[DatasetsCreateCommand,DatasetsGetItems,DatasetsLsCommand,DatasetsInfoCommand,DatasetsRmCommand,DatasetsRenameCommand,DatasetsPushDataCommand];async run(){this.printHelp()}};const br=`https://apify.github.io/input-schema-editor-react/`,xr=new URL(br).origin;var EditInputSchemaCommand=class extends ApifyCommand{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:Z.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 readInputSchema({forcePath:this.args.path,cwd:process.cwd()});if(e&&!t)throw Error(`Editing an input schema directly embedded in '${U}' is not yet supported.`);warning({message:`This command is still experimental and might break at any time. Use at your own risk.
139
- `}),info({message:`Editing input schema at "${t}"...`});let n,r=Pt();r.use(Nt({origin:xr,allowedHeaders:[`Content-Type`,`Authorization`]})),r.use((e,t,n)=>{t.set(`Connection`,`close`),n()}),r.use(Pt.json());let i=Te();r.use((e,t,n)=>{let{token:r}=e.query;if(!r){let t=e.get(`Authorization`);if(t){let[e,n,...i]=t.trim().split(/\s+/);e.toLowerCase()===`bearer`&&n&&i.length===0&&(r=n)}}r===i?n():(t.status(401),t.send(`Authorization failed`))});let a=Pt.Router();r.use(`/api/v1`,a);let s=` `,c=!0;a.get(`/input-schema`,(e,n)=>{let r;try{r=v(t)?S(t,{encoding:`utf-8`}):`{}
140
- `,r.length>3&&(s=zt(r).indent||s),r&&(c=r[r.length-1]===`
138
+ `),stdout:!0})}};const yr=new Q({allColumns:[`Dataset ID`,`Name`,`Items`,`Size`,`Created`,`Modified`],mandatoryColumns:[`Dataset ID`,`Name`,`Items`,`Size`],columnAlignments:{Items:`right`}});var DatasetsLsCommand=class extends ApifyCommand{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:Y.integer({description:`Number of datasets that will be skipped.`,default:0}),limit:Y.integer({description:`Number of datasets that will be listed.`,default:20}),desc:Y.boolean({description:`Sorts datasets in descending order.`,default:!1}),unnamed:Y.boolean({description:`Lists datasets that don't have a name set.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:n,limit:r,json:i,unnamed:a}=this.flags,s=await getLoggedClientOrThrow(),c=await getLocalUserInfo(),l=await s.datasets().list({desc:e,offset:n,limit:r,unnamed:a});if(i){printJsonToStdout(l);return}if(l.count===0){info({message:`You don't have any Datasets on your account`,stdout:!0});return}for(let e of l.items){let n=Reflect.get(e.stats,`s3StorageBytes`);yr.pushRow({"Dataset ID":e.id,Created:G.display(e.createdAt),Items:`${e.itemCount}`,Modified:G.display(e.modifiedAt),Name:e.name?`${c.username}/${e.name}`:``,Size:typeof n==`number`?prettyPrintBytes({bytes:n,shortBytes:!0,colorFunc:t.gray,precision:0}):t.gray(`N/A`)})}simpleLog({message:yr.render(1),stdout:!0})}},DatasetsPushDataCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The dataset ID or name to push the objects to.`,ignoreStdin:!0}),item:Z.string({description:`The object or array of objects to be pushed.`})};async run(){let{nameOrId:e,item:n}=this.args,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:a}=r,s,c=n||dn;if(!c){error({message:`No items were provided.`});return}try{s=JSON.parse(c.toString(`utf8`))}catch(e){error({message:`Failed to parse data as JSON string: ${e.message}`});return}if(Array.isArray(s)&&s.length===0){error({message:`No items were provided.`});return}let l=a.name?`Dataset named ${t.yellow(a.name)} (${t.gray(`ID:`)} ${t.yellow(a.id)})`:`Dataset with ID ${t.yellow(a.id)}`;try{await i.pushItems(s),success({message:`${this.pluralString(Array.isArray(s)?s.length:1,`Object`,`Objects`)} pushed to ${l} successfully.`})}catch(e){let t=e;error({message:`Failed to push items into ${l}\n ${t.message||t}`})}}},DatasetsRenameCommand=class extends ApifyCommand{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:Y.boolean({description:`Removes the unique name of the dataset.`})};static args={nameOrId:Z.string({description:`The dataset ID or name to delete.`,required:!0}),newName:Z.string({description:`The new name for the dataset.`})};async run(){let{unname:e}=this.flags,{newName:n,nameOrId:r}=this.args;if(!n&&!e){error({message:`You must provide either a new name or the --unname flag.`});return}if(n&&e){error({message:`You cannot provide a new name and the --unname flag.`});return}let i=await tryToGetDataset(await getLoggedClientOrThrow(),r);if(!i){error({message:`Dataset with ID or name "${r}" not found.`});return}let{id:a,name:s}=i.dataset,c=s?e?`The name of the dataset with ID ${t.yellow(a)} has been removed (was ${t.yellow(s)} previously).`:`The name of the dataset with ID ${t.yellow(a)} was changed from ${t.yellow(s)} to ${t.yellow(n)}.`:`The name of the dataset with ID ${t.yellow(a)} has been set to: ${t.yellow(n)}`;try{await i.datasetClient.update({name:e?null:n}),success({message:c,stdout:!0})}catch(e){let n=e;error({message:`Failed to rename dataset with ID ${t.yellow(a)}\n ${n.message||n}`})}}},DatasetsRmCommand=class extends ApifyCommand{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:Z.string({description:`The dataset ID or name to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{datasetNameOrId:e}=this.args,{yes:n}=this.flags,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}if(!await X({message:`Are you sure you want to delete this Dataset?`,providedConfirmFromStdin:n||void 0})){info({message:`Dataset deletion has been aborted.`});return}let{id:i,name:a}=r.dataset;try{await r.datasetClient.delete(),success({message:`Dataset with ID ${t.yellow(i)}${a?` (called ${t.yellow(a)})`:``} has been deleted.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to delete dataset with ID ${t.yellow(i)}\n ${n.message||n}`})}}},DatasetsIndexCommand=class extends ApifyCommand{static name=`datasets`;static description=`Manage Apify datasets — 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=[DatasetsCreateCommand,DatasetsGetItems,DatasetsLsCommand,DatasetsInfoCommand,DatasetsRmCommand,DatasetsRenameCommand,DatasetsPushDataCommand];async run(){this.printHelp()}};const br=`https://apify.github.io/input-schema-editor-react/`,xr=new URL(br).origin;var EditInputSchemaCommand=class extends ApifyCommand{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:Z.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 readInputSchema({forcePath:this.args.path,cwd:process.cwd()});if(e&&!t)throw Error(`Editing an input schema directly embedded in '${W}' is not yet supported.`);warning({message:`This command is still experimental and might break at any time. Use at your own risk.
139
+ `}),info({message:`Editing input schema at "${t}"...`});let n,r=Nt();r.use(Mt({origin:xr,allowedHeaders:[`Content-Type`,`Authorization`]})),r.use((e,t,n)=>{t.set(`Connection`,`close`),n()}),r.use(Nt.json());let i=we();r.use((e,t,n)=>{let{token:r}=e.query;if(!r){let t=e.get(`Authorization`);if(t){let[e,n,...i]=t.trim().split(/\s+/);e.toLowerCase()===`bearer`&&n&&i.length===0&&(r=n)}}r===i?n():(t.status(401),t.send(`Authorization failed`))});let a=Nt.Router();r.use(`/api/v1`,a);let s=` `,c=!0;a.get(`/input-schema`,(e,n)=>{let r;try{r=v(t)?S(t,{encoding:`utf-8`}):`{}
140
+ `,r.length>3&&(s=Rt(r).indent||s),r&&(c=r[r.length-1]===`
141
141
  `),v(t)?info({message:`Input schema loaded from "${t}"`}):info({message:`Empty input schema initialized.`})}catch(e){let t=`Reading input schema from disk failed with: ${e.message}`;error({message:t}),n.status(500),n.send(t);return}let i;try{i=JSON.parse(r||`{}`)}catch(e){let t=`Parsing input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t);return}n.send(i),info({message:`Input schema sent to editor.`})}),a.post(`/input-schema`,(e,n)=>{try{info({message:`Got input schema from editor...`});let r=e.body,i=JSON.stringify(r,null,s);c&&(i+=`
142
- `);let a=O(t);v(a)||b(a,{recursive:!0}),E(t,i,{encoding:`utf-8`,flag:`w+`}),n.end(),info({message:`Input schema saved to disk.`})}catch(e){let t=`Saving input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}}),a.post(`/exit`,(e,t)=>{e.body.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),n.close(()=>success({message:`Done.`}))}),n=r.listen(0);let{port:l}=n.address();info({message:`Listening for messages from input schema editor on port ${l}...`});let u=`${br}?localCliPort=${l}&localCliToken=${i}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${u}"...`}),await Ot(u)}},HelpCommand=class extends ApifyCommand{static name=`help`;static description=`Prints out help about a command, or all available commands.`;static hidden=!0;static args={commandString:Z.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 e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=J.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
143
- `,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i});return}let i=renderHelpForCommand(r);console.log(i)}},InfoCommand=class extends ApifyCommand{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 getLoggedClientOrThrow();let e=await getLocalUserInfo();if(e){let n={username:e.username,userId:e.id};for(let e of Object.keys(n))console.log(`${t.gray(e)}: ${t.bold(n[e])}`)}}};const Sr=[`.dockerignore`,`.gitignore`],Cr=Bt(new URL(`./templates/python-scrapy`,import.meta.url));async function merge(e,t,n={bindings:{}}){await Vt.walk(e,async(r,i,a)=>{if(i===e)return;let s=ae(e,i),c=s.split(oe).map(e=>{if(e.startsWith(`{`)&&e.endsWith(`}`)){e=e.replace(`{`,``).replace(`}`,``);let t=n.bindings[e];if(!t)throw Error(`Binding for ${e} not found.`);return t}return e}).join(oe),l=k(t,c);if(a.isDirectory())return v(l)||b(l),merge(i,l);s.includes(`.template`)?E(k(t,c.replace(`.template`,``)),Ht.compile(S(i,`utf8`))(n.bindings)):v(l)&&Sr.includes(re(c))?m(l,S(i)):g(i,l)})}async function wrapScrapyProject({projectPath:e}){e||=`.`;let t=new ScrapyProjectAnalyzer(e);if(t.configuration.hasSection(`apify`))throw Error(`The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?`);await t.init();let n=await cr({message:`Pick the Scrapy spider you want to wrap:`,choices:t.getAvailableSpiders().map((e,t)=>({name:`${e.class_name} (${e.pathname})`,value:t}))});function translatePathToRelativeModuleName(t){return`.${ae(e,t).split(oe).slice(1).join(`.`).replace(`.py`,``)}`}let r={botName:sanitizeActorName(t.settings.BOT_NAME),scrapy_settings_module:t.configuration.get(`settings`,`default`),apify_module_path:`${t.settings.BOT_NAME}.apify`,spider_class_name:t.getAvailableSpiders()[n].class_name,spider_module_name:`${translatePathToRelativeModuleName(t.getAvailableSpiders()[n].pathname)}`,projectFolder:t.settings.BOT_NAME},i=await kt(jt);info({message:`Downloading the latest Scrapy wrapper template...`});let{archiveUrl:a}=i.templates.find(({id:e})=>e===`python-scrapy`);v(Cr)&&ee(Cr,{recursive:!0}),await downloadAndUnzip({url:a,pathTo:Cr}),info({message:`Wrapping the Scrapy project...`}),await merge(Cr,e,{bindings:r});let s=new at;s.addSection(`apify`),s.set(`apify`,`mainpy_location`,t.settings.BOT_NAME);let c=_(k(e,`scrapy.cfg`),{flags:`a`});await new Promise(e=>{c.on(`open`,t=>{c.write(`
142
+ `);let a=k(t);v(a)||b(a,{recursive:!0}),D(t,i,{encoding:`utf-8`,flag:`w+`}),n.end(),info({message:`Input schema saved to disk.`})}catch(e){let t=`Saving input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}}),a.post(`/exit`,(e,t)=>{e.body.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),n.close(()=>success({message:`Done.`}))}),n=r.listen(0);let{port:l}=n.address();info({message:`Listening for messages from input schema editor on port ${l}...`});let u=`${br}?localCliPort=${l}&localCliToken=${i}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${u}"...`}),await Dt(u)}},HelpCommand=class extends ApifyCommand{static name=`help`;static description=`Prints out help about a command, or all available commands.`;static hidden=!0;static args={commandString:Z.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 e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=J.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
143
+ `,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i});return}let i=renderHelpForCommand(r);console.log(i)}},InfoCommand=class extends ApifyCommand{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 getLoggedClientOrThrow();let e=await getLocalUserInfo();if(e){let n={username:e.username,userId:e.id};for(let e of Object.keys(n))console.log(`${t.gray(e)}: ${t.bold(n[e])}`)}}};const Sr=[`.dockerignore`,`.gitignore`],Cr=zt(new URL(`./templates/python-scrapy`,import.meta.url));async function merge(e,t,n={bindings:{}}){await Bt.walk(e,async(r,i,a)=>{if(i===e)return;let s=ie(e,i),c=s.split(ae).map(e=>{if(e.startsWith(`{`)&&e.endsWith(`}`)){e=e.replace(`{`,``).replace(`}`,``);let t=n.bindings[e];if(!t)throw Error(`Binding for ${e} not found.`);return t}return e}).join(ae),l=A(t,c);if(a.isDirectory())return v(l)||b(l),merge(i,l);s.includes(`.template`)?D(A(t,c.replace(`.template`,``)),Vt.compile(S(i,`utf8`))(n.bindings)):v(l)&&Sr.includes(ne(c))?m(l,S(i)):g(i,l)})}async function wrapScrapyProject({projectPath:e}){e||=`.`;let t=new ScrapyProjectAnalyzer(e);if(t.configuration.hasSection(`apify`))throw Error(`The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?`);await t.init();let n=await cr({message:`Pick the Scrapy spider you want to wrap:`,choices:t.getAvailableSpiders().map((e,t)=>({name:`${e.class_name} (${e.pathname})`,value:t}))});function translatePathToRelativeModuleName(t){return`.${ie(e,t).split(ae).slice(1).join(`.`).replace(`.py`,``)}`}let r={botName:sanitizeActorName(t.settings.BOT_NAME),scrapy_settings_module:t.configuration.get(`settings`,`default`),apify_module_path:`${t.settings.BOT_NAME}.apify`,spider_class_name:t.getAvailableSpiders()[n].class_name,spider_module_name:`${translatePathToRelativeModuleName(t.getAvailableSpiders()[n].pathname)}`,projectFolder:t.settings.BOT_NAME},i=await Ot(At);info({message:`Downloading the latest Scrapy wrapper template...`});let{archiveUrl:a}=i.templates.find(({id:e})=>e===`python-scrapy`);v(Cr)&&T(Cr,{recursive:!0}),await downloadAndUnzip({url:a,pathTo:Cr}),info({message:`Wrapping the Scrapy project...`}),await merge(Cr,e,{bindings:r});let s=new rt;s.addSection(`apify`),s.set(`apify`,`mainpy_location`,t.settings.BOT_NAME);let c=_(A(e,`scrapy.cfg`),{flags:`a`});await new Promise(e=>{c.on(`open`,t=>{c.write(`
144
144
  `,()=>{s.write(t),e()})})}),success({message:`The Scrapy project has been wrapped successfully.`})}var InitCommand=class extends ApifyCommand{static name=`init`;static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
145
145
  If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
146
- Creates the '${U}' file and the '${en}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${en}' 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:Z.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:Y.string({description:`Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").`,required:!1})};async run(){let{actorName:t}=this.args,n=e.cwd(),r=await useCwdProject();r.isErr()&&(error({message:r.unwrapErr().message}),e.exit(1));let i=r.unwrap();if(i.warnings?.length)for(let e of i.warnings)warning({message:e});let a=re(n);if(i.type===1&&i.entrypoint?.path){let e=i.entrypoint.path;a=sanitizeActorName(e.includes(`.`)?e.split(`.`).pop():e)}if(i.type===2)return info({message:`The current directory looks like a Scrapy project. Using automatic project wrapping.`}),this.telemetryData.actorWrapper=`scrapy`,wrapScrapyProject({projectPath:n});if(!this.flags.yes&&i.type===3&&(warning({message:`The current directory does not look like a Node.js or Python project.`}),!await X({message:`Do you want to continue?`,providedConfirmFromStdin:this.flags.yes})))return;let s=await useActorConfig({cwd:n});if(s.isOkAnd(e=>e.exists&&!e.migrated))warning({message:`Skipping creation of '${U}', the file already exists in the current directory.`});else{if(s.isErr()){error({message:s.unwrapErr().message}),e.exitCode=5;return}if(!t){let e=s.isOkAnd(e=>e.exists)?s.unwrap().config.name:null;for(;!e;)try{let t=await On({message:`Actor name:`,default:a});validateActorName(t),e=t}catch(e){error({message:e.message})}t=e}let r={...tn,...s.unwrap().config,name:t};this.flags.dockerfile&&(r.dockerfile=this.flags.dockerfile),await setLocalConfig(r,n)}await setLocalEnv(n),await createPrefilledInputFileFromInputSchema(n),success({message:`The Actor has been initialized in the current directory.`})}},WrapScrapyCommand=class extends ApifyCommand{static name=`init-wrap-scrapy`;static description=`Wraps your existing Scrapy project to work like an Apify Actor.
146
+ Creates the '${W}' file and the '${$t}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${$t}' 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:Z.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:Y.string({description:`Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").`,required:!1})};async run(){let{actorName:t}=this.args,n=e.cwd(),r=await useCwdProject();r.isErr()&&(error({message:r.unwrapErr().message}),e.exit(1));let i=r.unwrap();if(i.warnings?.length)for(let e of i.warnings)warning({message:e});let a=ne(n);if(i.type===1&&i.entrypoint?.path){let e=i.entrypoint.path;a=sanitizeActorName(e.includes(`.`)?e.split(`.`).pop():e)}if(i.type===2)return info({message:`The current directory looks like a Scrapy project. Using automatic project wrapping.`}),this.telemetryData.actorWrapper=`scrapy`,wrapScrapyProject({projectPath:n});if(!this.flags.yes&&i.type===3&&(warning({message:`The current directory does not look like a Node.js or Python project.`}),!await X({message:`Do you want to continue?`,providedConfirmFromStdin:this.flags.yes})))return;let s=await useActorConfig({cwd:n});if(s.isOkAnd(e=>e.exists&&!e.migrated))warning({message:`Skipping creation of '${W}', the file already exists in the current directory.`});else{if(s.isErr()){error({message:s.unwrapErr().message}),e.exitCode=5;return}if(!t){let e=s.isOkAnd(e=>e.exists)?s.unwrap().config.name:null;for(;!e;)try{let t=await On({message:`Actor name:`,default:a});validateActorName(t),e=t}catch(e){error({message:e.message})}t=e}let r={...en,...s.unwrap().config,name:t};this.flags.dockerfile&&(r.dockerfile=this.flags.dockerfile),await setLocalConfig(r,n)}await setLocalEnv(n),await createPrefilledInputFileFromInputSchema(n),success({message:`The Actor has been initialized in the current directory.`})}},WrapScrapyCommand=class extends ApifyCommand{static name=`init-wrap-scrapy`;static description=`Wraps your existing Scrapy project to work like an Apify Actor.
147
147
 
148
148
  It adds the following features:
149
149
  - Automatic retry of failed requests
@@ -195,29 +195,29 @@ try:
195
195
  print(${e}.__version__)
196
196
  except:
197
197
  print('n/a')
198
- `,Dr={node(e){return[`-e`,`"${jsScript(e)}"`]},deno(e){return[`eval`,`"${jsScript(e)}"`]},bun(e){return[`--eval`,`"${jsScript(e)}"`]},python(e){return[`-c`,`"${pyScript(e)}"`]}};async function useModuleVersion({moduleName:e,project:t}){if(!t.runtime)return cliDebugPrint(`useModuleVersion`,{status:`no_runtime_found`,project:t,moduleName:e}),B;let n;if(t.type===0)n=t.runtime.runtimeShorthand||`node`;else if(t.type===1||t.type===2)n=`python`;else return cliDebugPrint(`useModuleVersion`,{status:`unsupported_project_type`,project:t,moduleName:e}),B;let r=Dr[n]?.(e);if(!r)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:t,moduleName:e}),B;try{let n=await ct(t.runtime.executablePath,r,{shell:!0,windowsHide:!0,verbose:process.env.APIFY_CLI_DEBUG?`full`:void 0});return n.stdout.trim()===`n/a`?(cliDebugPrint(`useModuleVersion`,{status:`no_version_found`,project:t,moduleName:e}),B):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:t,moduleName:e,version:n.stdout.trim()}),it(n.stdout.trim()))}catch(n){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:t,moduleName:e,error:n}),B}}var Or=function(e){return e[e.DirectFile=0]=`DirectFile`,e[e.Module=1]=`Module`,e[e.Script=2]=`Script`,e}(Or||{}),RunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes Actor locally with simulated Apify environment variables.
199
- Stores data in local '${en}' directory.\n\nNOTE: 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:Y.boolean({char:`p`,description:`Whether to purge the default request queue, dataset and key-value store before the run starts.
198
+ `,Dr={node(e){return[`-e`,`"${jsScript(e)}"`]},deno(e){return[`eval`,`"${jsScript(e)}"`]},bun(e){return[`--eval`,`"${jsScript(e)}"`]},python(e){return[`-c`,`"${pyScript(e)}"`]}};async function useModuleVersion({moduleName:e,project:t}){if(!t.runtime)return cliDebugPrint(`useModuleVersion`,{status:`no_runtime_found`,project:t,moduleName:e}),H;let n;if(t.type===0)n=t.runtime.runtimeShorthand||`node`;else if(t.type===1||t.type===2)n=`python`;else return cliDebugPrint(`useModuleVersion`,{status:`unsupported_project_type`,project:t,moduleName:e}),H;let r=Dr[n]?.(e);if(!r)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:t,moduleName:e}),H;try{let n=await ot(t.runtime.executablePath,r,{shell:!0,windowsHide:!0,verbose:process.env.APIFY_CLI_DEBUG?`full`:void 0});return n.stdout.trim()===`n/a`?(cliDebugPrint(`useModuleVersion`,{status:`no_version_found`,project:t,moduleName:e}),H):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:t,moduleName:e,version:n.stdout.trim()}),nt(n.stdout.trim()))}catch(n){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:t,moduleName:e,error:n}),H}}var Or=function(e){return e[e.DirectFile=0]=`DirectFile`,e[e.Module=1]=`Module`,e[e.Script=2]=`Script`,e}(Or||{}),RunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes Actor locally with simulated Apify environment variables.
199
+ Stores data in local '${$t}' directory.\n\nNOTE: 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:Y.boolean({char:`p`,description:`Whether to purge the default request queue, dataset and key-value store before the run starts.
200
200
  For crawlee projects, this is the default behavior, and the flag is optional.
201
201
  Use \`--no-purge\` to keep the storage folder intact.`,required:!1,default:!0,exclusive:[`resurrect`]}),resurrect:Y.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:Y.string({description:[`Optional entrypoint for running with injected environment variables.`,`
202
202
  `,`For Python, it is the module name, or a path to a file.`,`
203
- `,`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:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.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":Y.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 t=e.cwd(),{proxy:n,id:r,token:i}=await getLocalUserInfo(),a=await useActorConfig({cwd:t});if(a.isErr()){let{message:t,cause:n}=a.unwrapErr();error({message:`${t}${n?`\n ${n.message}`:``}`}),e.exitCode=5;return}let{config:s}=a.unwrap(),c=getLocalStorageDir(),l=await useCwdProject({cwd:t});if(l.isErr()){error({message:l.unwrapErr().message}),e.exitCode=5;return}let u=l.unwrap(),{type:p,entrypoint:m,runtime:h}=u;if(u.warnings?.length)for(let e of u.warnings)warning({message:e});if(p===3)throw 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(!h){switch(p){case 0:error({message:`No Node.js detected! Please install Node.js ${W} (or higher) to be able to run Node.js Actors locally.`});break;case 2:case 1:error({message:`No Python detected! Please install Python ${sn} (or higher) to be able to run Python Actors locally.`});break;default:error({message:`No runtime detected! Make sure you have Python ${sn} (or higher) or Node.js ${W} (or higher) installed.`})}return}let g,_;if(this.flags.entrypoint){_=this.flags.entrypoint;let e=await L(k(t,this.flags.entrypoint)).catch(()=>null);g=e?.isDirectory()?1:e?.isFile()?0:2}else if(m?.script)g=2,_=m.script;else if(m?.path)g=p===0?0:1,_=m.path;else{error({message:`No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint.`});return}v(`apify_storage`)&&!v(c)&&(T(`apify_storage`,c),warning({message:`The legacy 'apify_storage' directory was renamed to '${c}' to align it with Apify SDK v3. Contents were left intact.`}));let y=await useModuleVersion({moduleName:`crawlee`,project:u}),b=`0`;this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(b=`1`,y.isNone()&&(await Promise.all([purgeDefaultQueue(),purgeDefaultKeyValueStore(),purgeDefaultDataset()]),info({message:`All default local stores were purged.`}))),this.flags.purge||!await checkIfStorageIsEmpty()&&!this.flags.resurrect&&warning({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 x=await getInputOverride(t,this.flags.input,this.flags.inputFile);if(x===!1)return;let S=await this.validateAndStoreInput(x),C={[N.LOCAL_STORAGE_DIR]:c,CRAWLEE_STORAGE_DIR:c,CRAWLEE_PURGE_ON_START:b};if(n&&n.password&&(C[N.PROXY_PASSWORD]=n.password),r&&(C[N.USER_ID]=r),i&&(C[N.TOKEN]=i),s.environmentVariables){let e=replaceSecretsValue(s.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets});Object.assign(C,e)}let w=Object.assign(C,e.env);r||warning({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(p){case 0:{let e=f(W);if(isNodeVersionSupported(h.version)?w.NODE_OPTIONS=w.NODE_OPTIONS?`${w.NODE_OPTIONS} --max-http-header-size=80000`:`--max-http-header-size=80000`:warning({message:`You are running Node.js version ${h.version}, which is no longer supported. Please upgrade to Node.js version ${e} or later.`}),g===0||g===1)await execWithLog({cmd:h.executablePath,args:[_],opts:{env:w,cwd:t},forwardSignals:nn});else{let e=await F(k(t,`package.json`),`utf8`).catch(()=>`{}`),n=JSON.parse(e);if(!n.scripts)throw 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(!n.scripts[_])throw Error(`The script "${_}" was not found in package.json. Please set it up for your project. For more information about that call "apify help run".`);if(!h.pmPath)throw 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 execWithLog({cmd:h.pmPath,args:[`run`,_],opts:{env:w,cwd:t},overrideCommand:h.pmName,forwardSignals:nn})}break}case 1:case 2:if(!isPythonVersionSupported(h.version)){error({message:`Python Actors require Python 3.9 or higher, but you have Python ${h.version}!`}),error({message:`Please install Python 3.9 or higher to be able to run Python Actors locally.`});return}g===1?await execWithLog({cmd:h.executablePath,args:[`-m`,_],opts:{env:w,cwd:t},forwardSignals:nn}):await execWithLog({cmd:h.executablePath,args:[_],opts:{env:w,cwd:t},forwardSignals:nn});break;default:error({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(e){let{stderr:t}=e}finally{if(S)if(S.existingInput){let e=await L(S.inputFilePath);if(Math.trunc(e.mtimeMs)-S.writtenAt>=5){warning({message:`The "${S.inputFilePath}" file was overwritten during the run. The CLI will not undo the setting of missing default fields from your input schema.`});return}await R(S.inputFilePath,S.existingInput.body)}else await deleteFile(S.inputFilePath)}}async validateAndStoreInput(t){let{inputSchema:n}=await readInputSchema({cwd:e.cwd()});if(!n){if(!t)return null;let n=getLocalInput(e.cwd()),r=k(e.cwd(),getLocalKeyValueStorePath(),n?.fileName??`INPUT.json`);return await P(O(r),{recursive:!0}),await R(r,JSON.stringify(t.input,null,2)),{existingInput:n,inputFilePath:r,writtenAt:Date.now()}}let r=new _n({strict:!1,unicodeRegExp:!1});bt(r,n);let i=getDefaultsFromInputSchema(n),a=getAjvValidator(n,r),s=getLocalInput(e.cwd()),c=k(e.cwd(),getLocalKeyValueStorePath(),s?.fileName??`INPUT.json`),l;switch(t?.source){case`stdin`:l=`The input provided through standard input is invalid. Please fix the following errors:
204
- `;break;case`input`:l=`The input provided through the --input flag is invalid. Please fix the following errors:
205
- `;break;default:l=t?`The input provided through the ${t.source} file is invalid. Please fix the following errors:\n`:`The input in your storage is invalid. Please fix the following errors:
206
- `;break}if(t){let e={...i,...t.input},r=xt(a,n,e);if(r.length>0)throw Error(`${l}${r.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
207
- `)}`);return await P(O(c),{recursive:!0}),await R(c,JSON.stringify(e,null,2)),{existingInput:s,inputFilePath:c,writtenAt:Date.now()}}if(!s)return await P(O(c),{recursive:!0}),await R(c,JSON.stringify(i,null,2)),{existingInput:s,inputFilePath:c,writtenAt:Date.now()};if(Ye.getExtension(s.contentType)===`json`){let e=JSON.parse(s.body.toString(`utf-8`));if(Array.isArray(e))throw Error(`The input in your storage is invalid. It should be an object, not an array.`);let t={...i,...e},r=xt(a,n,t);if(r.length>0)throw Error(`${l}${r.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
208
- `)}`);return await P(O(c),{recursive:!0}),await R(c,JSON.stringify(t,null,2)),{existingInput:s,inputFilePath:c,writtenAt:Date.now()}}return null}};const kr=[M.READY,M.RUNNING],Ar=[M.ABORTING,M.TIMING_OUT];var RunsAbortCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The run ID to abort.`})};static flags={force:Y.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 getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!kr.includes(n.status)){Ar.includes(n.status)?error({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):error({message:`Run with ID "${e}" is already aborted.`,stdout:!0});return}try{let n=await t.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){printJsonToStdout(n);return}this.flags.force?success({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):success({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to abort run "${e}".\n ${n.message||n}`,stdout:!0})}}};const jr=new Q({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),Mr={"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`};var RunsInfoCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:Y.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,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r){error({message:`Run with ID "${e}" was not found on your account.`});return}let[i,a,s,c,l]=await Promise.all([n.actor(r.actId).get(),n.build(r.buildId).get(),r.actorTaskId?n.task(r.actorTaskId).get():Promise.resolve(void 0),n.dataset(r.defaultDatasetId).get(),n.requestQueue(r.defaultRequestQueueId).get()]);if(this.flags.json){printJsonToStdout({...r,actor:i,build:a,task:s,defaultDataset:c,defaultRequestQueue:l});return}this.addDetailedUsage(r);let u=i?.username?`${i.username}/${i.name}`:i?.name??`unknown-actor`,f=[`${t.yellow(`Actor`)}: ${u} (${t.grey(r.actId)})`];s?f.push(`└─ ${t.yellow(`Task`)}: ${s.title??s.name} (${t.gray(r.actorTaskId)})`,``):r.actorTaskId?f.push(`└─ ${t.yellow(`Task`)}: unknown-task (${t.gray(r.actorTaskId)})`,``):f.push(``);let p=` (exit code: ${t.gray(r.exitCode===null?`N/A`:r.exitCode)})`;f.push(`${t.yellow(`Status`)}: ${prettyPrintStatus(r.status)}${p}`),r.statusMessage&&f.push(`└─ ${t.yellow(`Status Message:`)} ${r.statusMessage}`);let m=c?.itemCount??0;f.push(`${t.yellow(`Results`)}: ${t.cyan(m.toLocaleString(`en-US`))}`),l?f.push(`${t.yellow(`Requests`)}: ${t.cyan(l.handledRequestCount.toLocaleString(`en-US`))} out of ${t.cyan(l.totalRequestCount.toLocaleString(`en-US`))} handled`):f.push(`${t.yellow(`Requests`)}: ${t.gray(`unknown handled`)}`);let h=this.flags.verbose?``:t.gray(` (run with ${t.yellow(`--verbose`)} for a detailed breakdown)`);if(r.usageTotalUsd?f.push(`${t.yellow(`Usage`)}: ${t.cyan(this.formatUsd(r.usageTotalUsd))}${h}`):f.push(`${t.yellow(`Usage`)}: $${t.gray(`0.000`)}${h}`),this.flags.verbose&&f.push(jr.render(0)),f.push(``),f.push(`${t.yellow(`Started`)}: ${G.display(r.startedAt)}`),r.finishedAt)f.push(`${t.yellow(`Finished`)}: ${G.display(r.finishedAt)} (took ${t.gray(K.format(r.stats.durationMillis))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(`${t.yellow(`Finished`)}: ${t.gray(`Running for ${K.format(e)}`)}`)}if(f.push(``),r.stats.resurrectCount?f.push(`${t.yellow(`Resurrected`)}: Yes, ${t.cyan(r.stats.resurrectCount.toLocaleString(`en-US`))} ${this.pluralString(r.stats.resurrectCount,`time`,`times`)}`):f.push(`${t.yellow(`Resurrected`)}: No`),r.containerUrl&&f.push(`${t.yellow(`Container URL`)}: ${t.blue(r.containerUrl)}`),f.push(`${t.yellow(`Origin`)}: ${r.meta.origin}`),i){let e=r.buildNumber.split(`.`).slice(0,2).join(`.`),n=i.versions.find(t=>t.versionNumber===e),a=Object.entries(i.taggedBuilds??{}).find(([,e])=>e.buildNumber===r.buildNumber)?.[0],s=[`${t.yellow(`Build`)}:`,t.cyan(r.buildNumber)];a?s.push(`(${t.yellow(a)})`):s.push(`(${t.gray(`N/A`)})`),n&&s.push(`| ${t.gray(`Actor version:`)} ${t.cyan(n.versionNumber)} (${t.yellow(n.buildTag)})`),f.push(s.join(` `))}else f.push(`${t.yellow(`Build`)}: ${t.cyan(r.buildNumber)}`);f.push(`${t.yellow(`Timeout`)}: ${r.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),f.push(`${t.yellow(`Memory`)}: ${r.options.memoryMbytes} MB`),f.push(``),f.push(`${t.yellow(`CPU`)}: ${t.gray(`Average:`)} ${r.stats.cpuAvgUsage.toFixed(2)}% | ${t.gray(`Maximum:`)} ${r.stats.cpuMaxUsage.toFixed(2)}%`),f.push(`${t.yellow(`Memory`)}: ${t.gray(`Average:`)} ${prettyPrintBytes({bytes:r.stats.memAvgBytes,shortBytes:!0})} | ${t.gray(`Maximum:`)} ${prettyPrintBytes({bytes:r.stats.memMaxBytes,shortBytes:!0})}`),f.push(``);let g=`https://console.apify.com/actors/${r.actId}/runs/${r.id}`,_=`https://console.apify.com/storage/datasets/${r.defaultDatasetId}`,v=`https://console.apify.com/storage/key-value-stores/${r.defaultKeyValueStoreId}`;f.push(`${t.blue(`Export results`)}: ${_}`),f.push(`${t.blue(`View saved items`)}: ${v}`),f.push(`${t.blue(`View in Apify Console`)}: ${g}`),simpleLog({message:f.join(`
203
+ `,`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:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.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":Y.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 t=e.cwd(),{proxy:n,id:r,token:i}=await getLocalUserInfo(),a=await useActorConfig({cwd:t});if(a.isErr()){let{message:t,cause:n}=a.unwrapErr();error({message:`${t}${n?`\n ${n.message}`:``}`}),e.exitCode=5;return}let{config:s}=a.unwrap(),c=getLocalStorageDir(),l=resolveInputKey(),u=await useCwdProject({cwd:t});if(u.isErr()){error({message:u.unwrapErr().message}),e.exitCode=5;return}let p=u.unwrap(),{type:m,entrypoint:h,runtime:g}=p;if(p.warnings?.length)for(let e of p.warnings)warning({message:e});if(m===3)throw 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(!g){switch(m){case 0:error({message:`No Node.js detected! Please install Node.js ${rn} (or higher) to be able to run Node.js Actors locally.`});break;case 2:case 1:error({message:`No Python detected! Please install Python ${on} (or higher) to be able to run Python Actors locally.`});break;default:error({message:`No runtime detected! Make sure you have Python ${on} (or higher) or Node.js ${rn} (or higher) installed.`})}return}let _,y;if(this.flags.entrypoint){y=this.flags.entrypoint;let e=await R(A(t,this.flags.entrypoint)).catch(()=>null);_=e?.isDirectory()?1:e?.isFile()?0:2}else if(h?.script)_=2,y=h.script;else if(h?.path)_=m===0?0:1,y=h.path;else{error({message:`No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint.`});return}v(`apify_storage`)&&!v(c)&&(w(`apify_storage`,c),warning({message:`The legacy 'apify_storage' directory was renamed to '${c}' to align it with Apify SDK v3. Contents were left intact.`}));let b=await useModuleVersion({moduleName:`crawlee`,project:p}),x=`0`;this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(x=`1`,b.isNone()&&(await Promise.all([purgeDefaultQueue(),purgeDefaultKeyValueStore(l),purgeDefaultDataset()]),info({message:`All default local stores were purged.`}))),this.flags.purge||!await checkIfStorageIsEmpty(l)&&!this.flags.resurrect&&warning({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 S=await getInputOverride(t,this.flags.input,this.flags.inputFile);if(S===!1)return;let C=await this.validateAndStoreInput(S,l),ee=l;C&&`tempInputKey`in C&&(this.flags.purge&&b.isSome()&&await Promise.all([purgeDefaultQueue(),purgeDefaultKeyValueStore(l,C.tempInputKey),purgeDefaultDataset()]),x=`0`,ee=C.tempInputKey);let T={[P.LOCAL_STORAGE_DIR]:c,CRAWLEE_STORAGE_DIR:c,CRAWLEE_PURGE_ON_START:x,[M.INPUT_KEY]:ee,[P.INPUT_KEY]:ee,CRAWLEE_INPUT_KEY:ee};if(n&&n.password&&(T[P.PROXY_PASSWORD]=n.password),r&&(T[P.USER_ID]=r),i&&(T[P.TOKEN]=i),s.environmentVariables){let e=replaceSecretsValue(s.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets});Object.assign(T,e)}let E={...e.env,...T};r||warning({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(m){case 0:{let e=f(rn);if(isNodeVersionSupported(g.version)?E.NODE_OPTIONS=E.NODE_OPTIONS?`${E.NODE_OPTIONS} --max-http-header-size=80000`:`--max-http-header-size=80000`:warning({message:`You are running Node.js version ${g.version}, which is no longer supported. Please upgrade to Node.js version ${e} or later.`}),_===0||_===1)await execWithLog({cmd:g.executablePath,args:[y],opts:{env:E,cwd:t},forwardSignals:tn});else{let e=await I(A(t,`package.json`),`utf8`).catch(()=>`{}`),n=JSON.parse(e);if(!n.scripts)throw 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(!n.scripts[y])throw 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(!g.pmPath)throw 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 execWithLog({cmd:g.pmPath,args:[`run`,y],opts:{env:E,cwd:t},overrideCommand:g.pmName,forwardSignals:tn})}break}case 1:case 2:if(!isPythonVersionSupported(g.version)){error({message:`Python Actors require Python 3.9 or higher, but you have Python ${g.version}!`}),error({message:`Please install Python 3.9 or higher to be able to run Python Actors locally.`});return}_===1?await execWithLog({cmd:g.executablePath,args:[`-m`,y],opts:{env:E,cwd:t},forwardSignals:tn}):await execWithLog({cmd:g.executablePath,args:[y],opts:{env:E,cwd:t},forwardSignals:tn});break;default:error({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(e){let{stderr:t}=e}finally{if(C)if(`tempInputKey`in C)await deleteFile(C.tempInputFilePath);else if(C.existingInput){let e=await R(C.inputFilePath);if(Math.trunc(e.mtimeMs)-C.writtenAt>=5){warning({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 z(C.inputFilePath,C.existingInput.body)}else await deleteFile(C.inputFilePath)}}async validateAndStoreInput(t,n=`INPUT`){let{inputSchema:r}=await readInputSchema({cwd:e.cwd()});if(!r){if(!t)return null;let r=A(e.cwd(),getLocalKeyValueStorePath());await F(r,{recursive:!0});let i=`${hn}${n}`,a=A(r,`${i}.json`);return await z(a,JSON.stringify(t.input,null,2)),{tempInputKey:i,tempInputFilePath:a}}let i=new _n({strict:!1,unicodeRegExp:!1});yt(i,r);let a=getDefaultsFromInputSchema(r),s=getAjvValidator(r,i),c=getLocalInput(e.cwd(),n),l=A(e.cwd(),getLocalKeyValueStorePath(),c?.fileName??`${n}.json`),u;switch(t?.source){case`stdin`:u=`The input provided through standard input is invalid. Please fix the following errors:
204
+ `;break;case`input`:u=`The input provided through the --input flag is invalid. Please fix the following errors:
205
+ `;break;default:u=t?`The input provided through the ${t.source} file is invalid. Please fix the following errors:\n`:`The input in your storage is invalid. Please fix the following errors:
206
+ `;break}if(t){let e={...a,...t.input},i=bt(s,r,e);if(i.length>0)throw Error(`${u}${i.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
207
+ `)}`);let c=`${hn}${n}`,f=A(k(l),`${c}.json`);return await F(k(l),{recursive:!0}),await z(f,JSON.stringify(e,null,2)),{tempInputKey:c,tempInputFilePath:f}}if(!c)return await F(k(l),{recursive:!0}),await z(l,JSON.stringify(a,null,2)),{existingInput:c,inputFilePath:l,writtenAt:Date.now()};if(qe.getExtension(c.contentType)===`json`){let e=JSON.parse(c.body.toString(`utf-8`));if(Array.isArray(e))throw Error(`The input in your storage is invalid. It should be an object, not an array.`);let t={...a,...e},i=bt(s,r,t);if(i.length>0)throw Error(`${u}${i.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
208
+ `)}`);let f=`${hn}${n}`,p=A(k(l),`${f}.json`);return await z(p,JSON.stringify(t,null,2)),{tempInputKey:f,tempInputFilePath:p}}return null}};const kr=[N.READY,N.RUNNING],Ar=[N.ABORTING,N.TIMING_OUT];var RunsAbortCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The run ID to abort.`})};static flags={force:Y.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 getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!kr.includes(n.status)){Ar.includes(n.status)?error({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):error({message:`Run with ID "${e}" is already aborted.`,stdout:!0});return}try{let n=await t.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){printJsonToStdout(n);return}this.flags.force?success({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):success({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to abort run "${e}".\n ${n.message||n}`,stdout:!0})}}};const jr=new Q({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),Mr={"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`};var RunsInfoCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:Y.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,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r){error({message:`Run with ID "${e}" was not found on your account.`});return}let[i,a,s,c,l]=await Promise.all([n.actor(r.actId).get(),n.build(r.buildId).get(),r.actorTaskId?n.task(r.actorTaskId).get():Promise.resolve(void 0),n.dataset(r.defaultDatasetId).get(),n.requestQueue(r.defaultRequestQueueId).get()]);if(this.flags.json){printJsonToStdout({...r,actor:i,build:a,task:s,defaultDataset:c,defaultRequestQueue:l});return}this.addDetailedUsage(r);let u=i?.username?`${i.username}/${i.name}`:i?.name??`unknown-actor`,f=[`${t.yellow(`Actor`)}: ${u} (${t.grey(r.actId)})`];s?f.push(`└─ ${t.yellow(`Task`)}: ${s.title??s.name} (${t.gray(r.actorTaskId)})`,``):r.actorTaskId?f.push(`└─ ${t.yellow(`Task`)}: unknown-task (${t.gray(r.actorTaskId)})`,``):f.push(``);let p=` (exit code: ${t.gray(r.exitCode===null?`N/A`:r.exitCode)})`;f.push(`${t.yellow(`Status`)}: ${prettyPrintStatus(r.status)}${p}`),r.statusMessage&&f.push(`└─ ${t.yellow(`Status Message:`)} ${r.statusMessage}`);let m=c?.itemCount??0;f.push(`${t.yellow(`Results`)}: ${t.cyan(m.toLocaleString(`en-US`))}`),l?f.push(`${t.yellow(`Requests`)}: ${t.cyan(l.handledRequestCount.toLocaleString(`en-US`))} out of ${t.cyan(l.totalRequestCount.toLocaleString(`en-US`))} handled`):f.push(`${t.yellow(`Requests`)}: ${t.gray(`unknown handled`)}`);let h=this.flags.verbose?``:t.gray(` (run with ${t.yellow(`--verbose`)} for a detailed breakdown)`);if(r.usageTotalUsd?f.push(`${t.yellow(`Usage`)}: ${t.cyan(this.formatUsd(r.usageTotalUsd))}${h}`):f.push(`${t.yellow(`Usage`)}: $${t.gray(`0.000`)}${h}`),this.flags.verbose&&f.push(jr.render(0)),f.push(``),f.push(`${t.yellow(`Started`)}: ${G.display(r.startedAt)}`),r.finishedAt)f.push(`${t.yellow(`Finished`)}: ${G.display(r.finishedAt)} (took ${t.gray(K.format(r.stats.durationMillis))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(`${t.yellow(`Finished`)}: ${t.gray(`Running for ${K.format(e)}`)}`)}if(f.push(``),r.stats.resurrectCount?f.push(`${t.yellow(`Resurrected`)}: Yes, ${t.cyan(r.stats.resurrectCount.toLocaleString(`en-US`))} ${this.pluralString(r.stats.resurrectCount,`time`,`times`)}`):f.push(`${t.yellow(`Resurrected`)}: No`),r.containerUrl&&f.push(`${t.yellow(`Container URL`)}: ${t.blue(r.containerUrl)}`),f.push(`${t.yellow(`Origin`)}: ${r.meta.origin}`),i){let e=r.buildNumber.split(`.`).slice(0,2).join(`.`),n=i.versions.find(t=>t.versionNumber===e),a=Object.entries(i.taggedBuilds??{}).find(([,e])=>e.buildNumber===r.buildNumber)?.[0],s=[`${t.yellow(`Build`)}:`,t.cyan(r.buildNumber)];a?s.push(`(${t.yellow(a)})`):s.push(`(${t.gray(`N/A`)})`),n&&s.push(`| ${t.gray(`Actor version:`)} ${t.cyan(n.versionNumber)} (${t.yellow(n.buildTag)})`),f.push(s.join(` `))}else f.push(`${t.yellow(`Build`)}: ${t.cyan(r.buildNumber)}`);f.push(`${t.yellow(`Timeout`)}: ${r.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),f.push(`${t.yellow(`Memory`)}: ${r.options.memoryMbytes} MB`),f.push(``),f.push(`${t.yellow(`CPU`)}: ${t.gray(`Average:`)} ${r.stats.cpuAvgUsage.toFixed(2)}% | ${t.gray(`Maximum:`)} ${r.stats.cpuMaxUsage.toFixed(2)}%`),f.push(`${t.yellow(`Memory`)}: ${t.gray(`Average:`)} ${prettyPrintBytes({bytes:r.stats.memAvgBytes,shortBytes:!0})} | ${t.gray(`Maximum:`)} ${prettyPrintBytes({bytes:r.stats.memMaxBytes,shortBytes:!0})}`),f.push(``);let g=`https://console.apify.com/actors/${r.actId}/runs/${r.id}`,_=`https://console.apify.com/storage/datasets/${r.defaultDatasetId}`,v=`https://console.apify.com/storage/key-value-stores/${r.defaultKeyValueStoreId}`;f.push(`${t.blue(`Export results`)}: ${_}`),f.push(`${t.blue(`View saved items`)}: ${v}`),f.push(`${t.blue(`View in Apify Console`)}: ${g}`),simpleLog({message:f.join(`
209
209
  `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n){for(let e of Object.keys(Mr))jr.pushRow({"":e,Unit:`N/A`,"USD Amount":`N/A`});return}for(let[e,r]of Object.entries(Mr)){let i=t[r]??0,a=n[r]??0;switch(r){case`ACTOR_COMPUTE_UNITS`:jr.pushRow({"":e,Unit:i.toFixed(4),"USD Amount":this.formatUsd(a)});break;case`DATA_TRANSFER_INTERNAL_GBYTES`:case`DATA_TRANSFER_EXTERNAL_GBYTES`:case`PROXY_RESIDENTIAL_TRANSFER_GBYTES`:jr.pushRow({"":e,Unit:prettyPrintBytes({bytes:i*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break;default:jr.pushRow({"":e,Unit:i.toLocaleString(`en-US`),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}},RunsLogCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The run ID to get the log from.`})};async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}info({message:`Log for run with ID "${e}":\n`,stdout:!0});try{await outputJobLog({job:n,apifyClient:t})}catch(t){error({message:`Failed to get log for run with ID "${e}": ${t.message}`})}}};const Nr=new Q({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`}});var RunsLsCommand=class extends ApifyCommand{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:Y.integer({description:`Number of runs that will be skipped.`,default:0}),limit:Y.integer({description:`Number of runs that will be listed.`,default:10}),desc:Y.boolean({description:`Sort runs in descending order.`,default:!1}),compact:Y.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:Z.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:n,offset:r,compact:i,json:a}=this.flags,{actorId:s}=this.args,c=await getLoggedClientOrThrow(),l=await resolveActorContext({providedActorNameOrId:s,client:c});if(!l.valid){error({message:`${l.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let u=await c.actor(l.id).runs().list({desc:e,limit:n,offset:r});if(a){printJsonToStdout(u);return}if(!u.items.length){simpleLog({message:`There are no recent runs found for this Actor.`});return}let f=[`${t.reset(`Showing`)} ${t.yellow(u.items.length)} out of ${t.yellow(u.total)} runs for Actor ${t.yellow(l.userFriendlyId)} (${t.gray(l.id)})`],p=new Map(await Promise.all(u.items.map(async e=>c.dataset(e.defaultDatasetId).get().then(n=>[e.id,t.yellow(n?.itemCount??0)],()=>[e.id,t.gray(`N/A`)]))));for(let e of u.items){let n;if(e.finishedAt){let r=e.finishedAt.getTime()-e.startedAt.getTime();n=t.gray(`${K.format(r,void 0,{left:``})}`)}else{let r=Date.now()-e.startedAt.getTime();n=t.gray(`Running for ${K.format(r,void 0,{left:``})}`)}Nr.pushRow({ID:t.gray(e.id),Status:prettyPrintStatus(e.status),Results:p.get(e.id)||t.gray(`N/A`),Usage:t.cyan(`$${(e.usageTotalUsd??0).toFixed(3)}`),"Started At":bn.display(e.startedAt),Took:n,"Build No.":e.buildNumber,Origin:e.meta.origin??`UNKNOWN`})}f.push(Nr.render(+!i)),simpleLog({message:f.join(`
210
- `),stdout:!0})}};const Pr=[M.SUCCEEDED,M.FAILED,M.ABORTED,M.TIMED_OUT];var RunsResurrectCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The run ID to resurrect.`})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Pr.includes(n.status)){error({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});return}try{let n=await t.run(e).resurrect();if(this.flags.json){printJsonToStdout(n);return}success({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to resurrect run "${e}".\n ${n.message||n}`,stdout:!0})}}};const Fr=[M.SUCCEEDED,M.FAILED,M.ABORTED,M.TIMED_OUT];var RunsRmCommand=class extends ApifyCommand{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:Z.string({description:`The run ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{runId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r){error({message:`Run with ID "${e}" was not found on your account.`});return}if(!Fr.includes(r.status)){error({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await X({message:`Are you sure you want to delete this Actor Run?`,providedConfirmFromStdin:t||void 0})){info({message:`Deletion of run "${e}" was canceled.`});return}try{await n.run(e).delete(),success({message:`Run with ID "${e}" was deleted.`})}catch(t){let n=t;error({message:`Failed to delete run "${e}".\n ${n.message||n}`})}}},RunsIndexCommand=class extends ApifyCommand{static name=`runs`;static description=`Inspect, abort, resurrect, or delete existing Actor runs.
211
- Does not start new runs — 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=[RunsAbortCommand,RunsInfoCommand,RunsLogCommand,RunsLsCommand,RunsResurrectCommand,RunsRmCommand];async run(){this.printHelp()}},SecretsAddCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`Name of the secret.`}),value:Z.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const Ir=new Q({allColumns:[`Secret Name`],mandatoryColumns:[`Secret Name`],columnAlignments:{"Secret Name":`left`}});var SecretsLsCommand=class extends ApifyCommand{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,n=getSecretsFile(),r=Object.keys(n);if(e){printJsonToStdout({keys:r});return}if(r.length===0){info({message:`You don't have any secrets stored locally. Use 'apify secrets add' to add a secret.`,stdout:!0});return}for(let e of r)Ir.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:Ir.render(1),stdout:!0})}},SecretsRmCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`Name of the secret.`})};async run(){let{name:e}=this.args;removeSecret(e)}},SecretsIndexCommand=class extends ApifyCommand{static name=`secrets`;static description=`Manage locally stored secrets that can be referenced from '${U}' 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=[SecretsAddCommand,SecretsLsCommand,SecretsRmCommand];async run(){this.printHelp()}},TaskRunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes predefined Actor task remotely using local key-value store for input.
210
+ `),stdout:!0})}};const Pr=[N.SUCCEEDED,N.FAILED,N.ABORTED,N.TIMED_OUT];var RunsResurrectCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`The run ID to resurrect.`})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Pr.includes(n.status)){error({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});return}try{let n=await t.run(e).resurrect();if(this.flags.json){printJsonToStdout(n);return}success({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to resurrect run "${e}".\n ${n.message||n}`,stdout:!0})}}};const Fr=[N.SUCCEEDED,N.FAILED,N.ABORTED,N.TIMED_OUT];var RunsRmCommand=class extends ApifyCommand{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:Z.string({description:`The run ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{runId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r){error({message:`Run with ID "${e}" was not found on your account.`});return}if(!Fr.includes(r.status)){error({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await X({message:`Are you sure you want to delete this Actor Run?`,providedConfirmFromStdin:t||void 0})){info({message:`Deletion of run "${e}" was canceled.`});return}try{await n.run(e).delete(),success({message:`Run with ID "${e}" was deleted.`})}catch(t){let n=t;error({message:`Failed to delete run "${e}".\n ${n.message||n}`})}}},RunsIndexCommand=class extends ApifyCommand{static name=`runs`;static description=`Inspect, abort, resurrect, or delete existing Actor runs.
211
+ Does not start new runs — 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=[RunsAbortCommand,RunsInfoCommand,RunsLogCommand,RunsLsCommand,RunsResurrectCommand,RunsRmCommand];async run(){this.printHelp()}},SecretsAddCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`Name of the secret.`}),value:Z.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const Ir=new Q({allColumns:[`Secret Name`],mandatoryColumns:[`Secret Name`],columnAlignments:{"Secret Name":`left`}});var SecretsLsCommand=class extends ApifyCommand{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,n=getSecretsFile(),r=Object.keys(n);if(e){printJsonToStdout({keys:r});return}if(r.length===0){info({message:`You don't have any secrets stored locally. Use 'apify secrets add' to add a secret.`,stdout:!0});return}for(let e of r)Ir.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:Ir.render(1),stdout:!0})}},SecretsRmCommand=class extends ApifyCommand{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:Z.string({required:!0,description:`Name of the secret.`})};async run(){let{name:e}=this.args;removeSecret(e)}},SecretsIndexCommand=class extends ApifyCommand{static name=`secrets`;static description=`Manage locally stored secrets that can be referenced from '${W}' 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=[SecretsAddCommand,SecretsLsCommand,SecretsRmCommand];async run(){this.printHelp()}},TaskRunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes predefined Actor task remotely using local key-value store for input.
212
212
  Customize with --memory and --timeout flags.
213
213
  `;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=SharedRunOnCloudFlags(`Task`);static args={taskId:Z.string({required:!0,description:`Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").`})};async run(){let e=await getLoggedClientOrThrow(),n=await getLocalUserInfo(),r=n.username||n.id,{id:i,userFriendlyId:a,title:s}=await this.resolveTaskId(e,r),c={waitForFinish:2};this.flags.build&&(c.build=this.flags.build),this.flags.timeout&&(c.timeout=this.flags.timeout),this.flags.memory&&(c.memory=this.flags.memory);let l,u,f=runActorOrTaskOnCloud(e,{actorOrTaskData:{id:i,userFriendlyId:a,title:s},runOptions:c,type:`Task`,printRunLogs:!0});for await(let e of f)l=`https://console.apify.com/actors/${e.actId}/runs/${e.id}`,u=`https://console.apify.com/storage/datasets/${e.defaultDatasetId}`;simpleLog({message:[``,`${t.blue(`Export results`)}: ${u}`,`${t.blue(`View on Apify Console`)}: ${l}`].join(`
214
214
  `),stdout:!0})}async resolveTaskId(e,t){let{taskId:n}=this.args;if(n?.includes(`/`)){let r=await e.task(n).get();if(!r)throw Error(`Cannot find Task with ID '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}if(n){let r=await e.task(`${t}/${n.toLowerCase()}`).get();if(!r)throw Error(`Cannot find Task with name '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}throw Error(`Please provide a valid Task ID or name.`)}},TasksIndexCommand=class extends ApifyCommand{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=[TaskRunCommand];async run(){this.printHelp()}},TelemetryDisableCommand=class extends ApifyCommand{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 useTelemetryState()).enabled?(await updateTelemetryEnabled(!1),success({message:`Telemetry disabled.`})):info({message:`Telemetry is already disabled.`})}},TelemetryEnableCommand=class extends ApifyCommand{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 useTelemetryState()).enabled?info({message:`Telemetry is already enabled.`}):(await updateTelemetryEnabled(!0),success({message:`Telemetry enabled.`}))}},TelemetryIndexCommand=class extends ApifyCommand{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=[TelemetryEnableCommand,TelemetryDisableCommand];async run(){this.printHelp()}},ValidateSchemaCommand=class extends ApifyCommand{static name=`validate-schema`;static description=`Validates Actor schemas.
215
215
 
216
216
  When a path argument is provided, validates only the input schema at that path.
217
217
 
218
- When no path is provided, validates all schemas found in '${U}':
218
+ When no path is provided, validates all schemas found in '${W}':
219
219
  - Input schema (from "input" key or default locations)
220
220
  - Dataset schema (from "storages.dataset")
221
221
  - Output schema (from "output")
222
- - Key-Value Store schema (from "storages.keyValueStore")`;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:Z.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${U}'.`})};static hiddenAliases=[`vis`];async run(){if(this.args.path){await this.validateInputSchemaAtPath(this.args.path);return}await this.validateAllSchemas()}async validateInputSchemaAtPath(t){await readAndValidateInputSchema({forcePath:t,cwd:e.cwd(),getMessage:e=>`Validating input schema at ${e??t}`}),success({message:`Input schema is valid.`})}async validateAllSchemas(){let t=e.cwd(),n=!1,r=!1;try{let{inputSchema:e,inputSchemaPath:r}=await readInputSchema({cwd:t,throwOnMissing:!0});e&&(n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${U}'`}`}),bt(new _n({strict:!1}),e),success({message:`Input schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}let i=[{label:`Dataset`,read:()=>readStorageSchema({cwd:t,key:`dataset`,label:`Dataset`,throwOnMissing:!0}),validate:validateDatasetSchema},{label:`Output`,read:()=>readStorageSchema({cwd:t,key:`output`,label:`Output`,getRef:e=>e?.output,throwOnMissing:!0}),validate:validateOutputSchema},{label:`Key-Value Store`,read:()=>readStorageSchema({cwd:t,key:`keyValueStore`,label:`Key-Value Store`,throwOnMissing:!0}),validate:validateKvsSchema}];for(let{label:e,read:t,validate:a}of i)try{let r=t();r&&(n=!0,info({message:`Validating ${e} schema ${r.schemaPath?`at ${r.schemaPath}`:`embedded in '${U}'`}`}),a(r.schema),success({message:`${e} schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}if(!n)throw Error(`No schemas found. Make sure '${U}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const Lr=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],Rr=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Lr as n,processVersionCheck as r,Rr as t};
223
- //# sourceMappingURL=_register-CVxv0CO9.js.map
222
+ - Key-Value Store schema (from "storages.keyValueStore")`;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:Z.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${W}'.`})};static hiddenAliases=[`vis`];async run(){if(this.args.path){await this.validateInputSchemaAtPath(this.args.path);return}await this.validateAllSchemas()}async validateInputSchemaAtPath(t){await readAndValidateInputSchema({forcePath:t,cwd:e.cwd(),getMessage:e=>`Validating input schema at ${e??t}`}),success({message:`Input schema is valid.`})}async validateAllSchemas(){let t=e.cwd(),n=!1,r=!1;try{let{inputSchema:e,inputSchemaPath:r}=await readInputSchema({cwd:t,throwOnMissing:!0});e&&(n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${W}'`}`}),yt(new _n({strict:!1}),e),success({message:`Input schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}let i=[{label:`Dataset`,read:()=>readStorageSchema({cwd:t,key:`dataset`,label:`Dataset`,throwOnMissing:!0}),validate:validateDatasetSchema},{label:`Output`,read:()=>readStorageSchema({cwd:t,key:`output`,label:`Output`,getRef:e=>e?.output,throwOnMissing:!0}),validate:validateOutputSchema},{label:`Key-Value Store`,read:()=>readStorageSchema({cwd:t,key:`keyValueStore`,label:`Key-Value Store`,throwOnMissing:!0}),validate:validateKvsSchema}];for(let{label:e,read:t,validate:a}of i)try{let r=t();r&&(n=!0,info({message:`Validating ${e} schema ${r.schemaPath?`at ${r.schemaPath}`:`embedded in '${W}'`}`}),a(r.schema),success({message:`${e} schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}if(!n)throw Error(`No schemas found. Make sure '${W}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const Lr=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],Rr=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Lr as n,processVersionCheck as r,Rr as t};
223
+ //# sourceMappingURL=_register-DXCYKaA1.js.map