apify-cli 1.10.1-beta.4 → 1.10.1-beta.6

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,7 +1,7 @@
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 a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,constants as w,copyFileSync as T,createWriteStream as E,existsSync as D,fstat as O,mkdirSync as k,openSync as A,readFileSync as j,readdirSync as M,realpathSync as ee,renameSync as te,rmSync as N,statSync as ne,unlinkSync as re,writeFileSync as P}from"node:fs";import ie from"string-width";import ae from"strip-ansi";import{once as oe}from"node:events";import{homedir as se,platform as ce}from"node:os";import le,{isCI as ue}from"ci-info";import{ACTOR_ENV_VARS as F,ACTOR_JOB_STATUSES as I,ACTOR_JOB_TERMINAL_STATUSES as de,ACTOR_NAME as fe,ACTOR_SOURCE_TYPES as pe,APIFY_ENV_VARS as L,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{Result as Se,err as Ce,none as we,ok as Te,some as Ee}from"@sapphire/result";import{execa as De}from"execa";import{access as Oe,appendFile as ke,mkdir as R,readFile as z,readdir as Ae,rename as je,rm as Me,stat as B,symlink as Ne,unlink as Pe,writeFile as V}from"node:fs/promises";import Fe from"configparser";import Ie from"@inquirer/input";import Le from"which";import{createHmacSignature as Re,cryptoRandomObjectId as ze}from"@apify/utilities";import{execSync as Be,spawn as Ve}from"node:child_process";import{DurationFormatter as He,Time as Ue,TimeTypes as We}from"@sapphire/duration";import{Timestamp as Ge}from"@sapphire/timestamp";import Ke from"adm-zip";import qe from"ajv/dist/2019.js";import{ApifyClient as Je,DownloadItemsFormat as H}from"apify-client";import{ZipArchive as Ye}from"archiver";import Xe,{AxiosHeaders as Ze}from"axios";import Qe from"escape-string-regexp";import $e from"ignore";import{getEncoding as et}from"istextorbinary";import tt,{Mime as nt}from"mime";import rt from"mime/types/other.js";import it from"mime/types/standard.js";import{glob as at}from"tinyglobby";import{calculateRunDynamicMemory as ot}from"@apify/actor-memory-expression";import{Separator as st,createPrompt as ct,isEnterKey as lt,makeTheme as ut,useKeypress as dt,usePrefix as ft,useState as pt}from"@inquirer/core";import{pipeline as mt}from"node:stream/promises";import{MemoryStorage as ht}from"@crawlee/memory-storage";import{compile as gt}from"json-schema-to-typescript";import{validateInputSchema as _t,validateInputUsingValidator as vt}from"@apify/input_schema";import{getDatasetSchemaValidator as yt,getKeyValueStoreSchemaValidator as bt,getOutputSchemaValidator as xt}from"@apify/json_schemas";import St from"cli-table3";import{downloadTemplate as Ct}from"giget";import wt from"jju";import Tt from"open";import{fetchManifest as Et,manifestUrl as Dt,wrapperManifestUrl as Ot}from"@apify/actor-templates";import kt from"computer-name";import At from"@inquirer/password";import jt from"@inquirer/select";import{createServer as Mt}from"node:http";import Nt from"node:assert";import{ReadStream as Pt}from"node:tty";import{setTimeout as Ft}from"node:timers/promises";import It from"detect-indent";import{fileURLToPath as Lt}from"node:url";import Rt from"@root/walk";import zt 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 detectInstallMethod(){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 Bt=null;function useCLIMetadata(){if(Bt)return Bt;let e=detectInstallMethod(),t=getRuntimeInfo();return Bt={version:`1.10.1-beta.4`,hash:`c047a3769b6f35756640d175d08e3544bd3c8711`,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`&&(Bt.installPath=c(process.execPath)),Bt}function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Vt=[`apify`,`actor`];function unixWrapperScript(e){return[`#!/bin/sh`,`DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"`,`APIFY_CLI_ENTRYPOINT=${e} exec "$DIR/apify-cli" "$@"`,``].join(`
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 a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,constants as w,copyFileSync as T,createWriteStream as E,existsSync as D,fstat as ee,mkdirSync as O,openSync as k,readFileSync as A,readdirSync as te,realpathSync as j,renameSync as M,rmSync as N,statSync as ne,unlinkSync as re,writeFileSync as P}from"node:fs";import ie from"string-width";import ae from"strip-ansi";import{once as oe}from"node:events";import{homedir as se,platform as ce}from"node:os";import le,{isCI as ue}from"ci-info";import{ACTOR_ENV_VARS as F,ACTOR_JOB_STATUSES as I,ACTOR_JOB_TERMINAL_STATUSES as de,ACTOR_NAME as fe,ACTOR_SOURCE_TYPES as pe,APIFY_ENV_VARS as L,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{Result as Se,err as Ce,none as we,ok as Te,some as Ee}from"@sapphire/result";import{execa as De}from"execa";import{access as Oe,appendFile as ke,mkdir as R,readFile as z,readdir as Ae,rename as je,rm as Me,stat as B,symlink as Ne,unlink as Pe,writeFile as V}from"node:fs/promises";import Fe from"configparser";import Ie from"@inquirer/input";import Le from"which";import{createHmacSignature as Re,cryptoRandomObjectId as ze}from"@apify/utilities";import{execSync as Be,spawn as Ve}from"node:child_process";import{DurationFormatter as He,Time as Ue,TimeTypes as We}from"@sapphire/duration";import{Timestamp as Ge}from"@sapphire/timestamp";import Ke from"adm-zip";import qe from"ajv/dist/2019.js";import{ApifyClient as Je,DownloadItemsFormat as H}from"apify-client";import{ZipArchive as Ye}from"archiver";import Xe,{AxiosHeaders as Ze}from"axios";import Qe from"escape-string-regexp";import $e from"ignore";import{getEncoding as et}from"istextorbinary";import tt,{Mime as nt}from"mime";import rt from"mime/types/other.js";import it from"mime/types/standard.js";import{glob as at}from"tinyglobby";import{calculateRunDynamicMemory as ot}from"@apify/actor-memory-expression";import{Separator as st,createPrompt as ct,isEnterKey as lt,makeTheme as ut,useKeypress as dt,usePrefix as ft,useState as pt}from"@inquirer/core";import{pipeline as mt}from"node:stream/promises";import{MemoryStorage as ht}from"@crawlee/memory-storage";import{compile as gt}from"json-schema-to-typescript";import{validateInputSchema as _t,validateInputUsingValidator as vt}from"@apify/input_schema";import{getDatasetSchemaValidator as yt,getKeyValueStoreSchemaValidator as bt,getOutputSchemaValidator as xt}from"@apify/json_schemas";import St from"cli-table3";import{downloadTemplate as Ct}from"giget";import wt from"jju";import Tt from"open";import{fetchManifest as Et,manifestUrl as Dt,wrapperManifestUrl as Ot}from"@apify/actor-templates";import kt from"computer-name";import At from"@inquirer/password";import jt from"@inquirer/select";import{createServer as Mt}from"node:http";import Nt from"node:assert";import{ReadStream as Pt}from"node:tty";import{setTimeout as Ft}from"node:timers/promises";import It from"detect-indent";import{fileURLToPath as Lt}from"node:url";import Rt from"@root/walk";import zt 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 detectInstallMethod(){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=j(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 Bt=null;function useCLIMetadata(){if(Bt)return Bt;let e=detectInstallMethod(),t=getRuntimeInfo();return Bt={version:`1.10.1-beta.6`,hash:`216cc155ecbcabcc750b124a9f56ff8a9f3fd930`,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`&&(Bt.installPath=c(process.execPath)),Bt}function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Vt=[`apify`,`actor`];function unixWrapperScript(e){return[`#!/bin/sh`,`DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"`,`APIFY_CLI_ENTRYPOINT=${e} exec "$DIR/apify-cli" "$@"`,``].join(`
2
2
  `)}function windowsCmdWrapperScript(e){return[`@echo off`,`setlocal`,`set "APIFY_CLI_ENTRYPOINT=${e}"`,`"%~dp0apify-cli.exe" %*`,``].join(`\r
3
3
  `)}function windowsPowershellWrapperScript(e){return[`#!/usr/bin/env pwsh`,`$prev = $env:APIFY_CLI_ENTRYPOINT`,`$env:APIFY_CLI_ENTRYPOINT = "${e}"`,`try {`,` & "$PSScriptRoot\\apify-cli.exe" @args`,`} finally {`,` $env:APIFY_CLI_ENTRYPOINT = $prev`,`}`,`exit $LASTEXITCODE`,``].join(`\r
4
- `)}function atomicWriteSync(t,n,r){let i=`${t}.${e.pid}.tmp`;try{P(i,n),r!==void 0&&C(i,r),te(i,t)}catch(e){try{N(i,{force:!0})}catch{}throw e}}function atomicCopySync(t,n,r){let i=`${n}.${e.pid}.tmp`;try{T(t,i),r!==void 0&&C(i,r),te(i,n)}catch(e){try{N(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Vt)atomicWriteSync(u(e,n),unixWrapperScript(n),493),t&&(atomicWriteSync(u(e,`${n}.cmd`),windowsCmdWrapperScript(n)),atomicWriteSync(u(e,`${n}.ps1`),windowsPowershellWrapperScript(n)))}function migrateLegacyBundleInstallIfNeeded(){let t=useCLIMetadata();if(t.installMethod!==`bundle`)return;let n=t.platform===`windows`,r=c(e.execPath),i=s(e.execPath).replace(/\.exe$/i,``).toLowerCase();if(n)for(let e of Vt){let t=u(r,`${e}.exe.old`);if(D(t))try{N(t,{force:!0}),cliDebugPrint(`[migration] removed stale legacy binary`,t)}catch(e){cliDebugPrint(`[migration] failed to remove stale legacy binary`,{stalePath:t,err:e})}}if(i===`apify-cli`||!Vt.includes(i))return;cliDebugPrint(`[migration] legacy multi-bundle install detected, migrating to single bundle`,{binDir:r,selfName:i});let a=u(r,`apify-cli${n?`.exe`:``}`);try{atomicCopySync(e.execPath,a,n?void 0:493),cliDebugPrint(`[migration] copied current bundle to`,a)}catch(e){cliDebugPrint(`[migration] failed to copy current bundle, will retry on next run`,{err:e});return}try{writeEntrypointShims(r,n),cliDebugPrint(`[migration] wrote entrypoint shims`)}catch(e){cliDebugPrint(`[migration] failed to write entrypoint shims, will retry on next run`,{err:e})}if(n){for(let t of Vt){let n=u(r,`${t}.exe`);if(D(n))try{p(n)===p(e.execPath)?(te(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):N(n,{force:!0})}catch(e){try{te(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}let t=u(r,`upgrade.ps1`);try{N(t,{force:!0}),cliDebugPrint(`[migration] removed upgrade script, it will be re-downloaded on the next upgrade`)}catch(e){cliDebugPrint(`[migration] failed to remove upgrade script`,{upgradeScriptPath:t,err:e})}}cliDebugPrint(`[migration] migration to single bundle complete`)}let Ht;function getMaxLineWidth(){if(Ht)return Ht;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Ht=e;else if(!process.stdout.isTTY)Ht=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Ht=e<1?80:e<40?40:e}return Ht}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(`
4
+ `)}function atomicWriteSync(t,n,r){let i=`${t}.${e.pid}.tmp`;try{P(i,n),r!==void 0&&C(i,r),M(i,t)}catch(e){try{N(i,{force:!0})}catch{}throw e}}function atomicCopySync(t,n,r){let i=`${n}.${e.pid}.tmp`;try{T(t,i),r!==void 0&&C(i,r),M(i,n)}catch(e){try{N(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Vt)atomicWriteSync(u(e,n),unixWrapperScript(n),493),t&&(atomicWriteSync(u(e,`${n}.cmd`),windowsCmdWrapperScript(n)),atomicWriteSync(u(e,`${n}.ps1`),windowsPowershellWrapperScript(n)))}function migrateLegacyBundleInstallIfNeeded(){let t=useCLIMetadata();if(t.installMethod!==`bundle`)return;let n=t.platform===`windows`,r=c(e.execPath),i=s(e.execPath).replace(/\.exe$/i,``).toLowerCase();if(n)for(let e of Vt){let t=u(r,`${e}.exe.old`);if(D(t))try{N(t,{force:!0}),cliDebugPrint(`[migration] removed stale legacy binary`,t)}catch(e){cliDebugPrint(`[migration] failed to remove stale legacy binary`,{stalePath:t,err:e})}}if(i===`apify-cli`||!Vt.includes(i))return;cliDebugPrint(`[migration] legacy multi-bundle install detected, migrating to single bundle`,{binDir:r,selfName:i});let a=u(r,`apify-cli${n?`.exe`:``}`);try{atomicCopySync(e.execPath,a,n?void 0:493),cliDebugPrint(`[migration] copied current bundle to`,a)}catch(e){cliDebugPrint(`[migration] failed to copy current bundle, will retry on next run`,{err:e});return}try{writeEntrypointShims(r,n),cliDebugPrint(`[migration] wrote entrypoint shims`)}catch(e){cliDebugPrint(`[migration] failed to write entrypoint shims, will retry on next run`,{err:e})}if(n){for(let t of Vt){let n=u(r,`${t}.exe`);if(D(n))try{p(n)===p(e.execPath)?(M(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):N(n,{force:!0})}catch(e){try{M(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}let t=u(r,`upgrade.ps1`);try{N(t,{force:!0}),cliDebugPrint(`[migration] removed upgrade script, it will be re-downloaded on the next upgrade`)}catch(e){cliDebugPrint(`[migration] failed to remove upgrade script`,{upgradeScriptPath:t,err:e})}}cliDebugPrint(`[migration] migration to single bundle complete`)}let Ht;function getMaxLineWidth(){if(Ht)return Ht;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Ht=e;else if(!process.stdout.isTTY)Ht=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Ht=e<1?80:e<40?40:e}return Ht}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(`
5
5
  `)[0]}`,``)}pushDescription(e){if(!this.command.description)return;e.push(t.bold(`DESCRIPTION`));let r=i(this.command.description,getMaxLineWidth()-2,{trim:!1}),a=n(r,2);e.push(a),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=i(a.description,getMaxLineWidth()-4,{trim:!1}).split(`
6
6
  `).map(e=>`# ${e}`).join(`
7
7
  `),s=n(r,2);e.push(t.dim(s))}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=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.`,a=i(r,getMaxLineWidth()-2,{trim:!1}),s=n(a,2);e.push(s),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}){ie(e.join(` `).split(`
@@ -26,9 +26,9 @@ import e from"node:process";import t from"chalk";import n from"indent-string";im
26
26
  `)}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.`)}case 5:{let e=`--${this.metadata.flag}`,n=this.metadata.choices;return t.gray(`Invalid value for flag ${t.white.bold(e)}. Expected one of: ${n}`)}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} (${Jt[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(`
27
27
  `)}}}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(`
28
28
  `).map(e=>` ${e}`).join(`
29
- `)}`):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})}};const Yt=_(O);let Xt;async function useStdin(){if(Xt)return Xt;let t=e.stdin,n={isTTY:t.isTTY,hasData:!1,waitDelay:0,stream:t},r=await Yt(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&w.S_IFIFO)===w.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),Xt=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());let onData=e=>{i.push(e),s&&=(clearTimeout(s),null)};r.on(`data`,onData);try{await oe(r,`end`,{signal:a.signal})}catch(e){if(e.name===`AbortError`)return}finally{r.off(`data`,onData),r.pause()}s&&clearTimeout(s),e.hasData=!1;let c=Buffer.concat(i);if(c.length)return c}var Zt={node:`>=20`};const Qt=`storage`,$t={actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},en=Date.UTC(2026,9,1),tn=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let t=u(se(),`.apify`);return e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?u(t,e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):t},AUTH_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),nn=`.actor`,W=u(nn,`actor.json`),rn=Zt.node,an=le.GITHUB_ACTIONS?`${e.env.GITHUB_SERVER_URL}/${e.env.GITHUB_REPOSITORY}/actions/runs/${e.env.GITHUB_RUN_ID}`:void 0,on={"X-Apify-Request-Origin":le.isCI?ve.CI:ve.CLI,...an&&{"X-Apify-Github-Actions-Run-Url":an}},sn=`3.11.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(!D(e))return cn;let t=JSON.parse(j(e,`utf-8`));return migrateStateV0ToV1$1(t)?useLocalState():t}function updateLocalState(e,t){let n={...e};t(n);let r=STATE_FILE_PATH(),i=c(r);k(i,{recursive:!0}),P(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=v(i,ln.version);return{currentVersion:ln.version,latestVersion:i,shouldUpdate:a,cacheHit:!r}}function useCommandSuggestions(e){let t=[...q.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 fn=await readStdin(),pn=useCLIMetadata(),mn=`Apify CLI/${pn.version} (https://github.com/apify/apify-cli)`;function processVersionCheck(t){pn.installMethod!==`bundle`&&(x(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(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+=`
30
- `,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=q.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){migrateLegacyBundleInstallIfNeeded(),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=g({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(q.get(i)?.subcommands?.length){if(r.positionals[1]?.toLowerCase()===`help`)a=1;else if(r.positionals[2]?.toLowerCase()===`help`){let e=q.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 s=r.positionals[1],c=!1,l=q.get(i);if(!l)return handleCommandNotFound(i);let u=l;if(l.subcommands?.length){if(!s)return l.printHelp();c=!0,u=q.get(`${i} ${s}`)}if(!u)return handleCommandNotFound(`${i} ${s}`);let f=[...n],p=f.indexOf(i);if(cliDebugPrint(`CommandNameIndex`,p),f.splice(p,1),c){let e=f.indexOf(s);cliDebugPrint(`SubcommandNameIndex`,e),f.splice(e,1)}cliDebugPrint(`RebuiltArgs`,f),cliDebugPrint(`CommandToRun`,u);let m=new u(t,c?`${l.name} ${s}`:l.name,i,c?s:void 0),h=m._buildParseArgsOption();cliDebugPrint(`ParserOptionsForCommand`,h);try{let e=g({...h,args:f});await m._run(e),cliDebugPrint(`CommandArgsResult`,e)}catch(t){error({message:U.into(t,u).getPrettyMessage()}),e.exit(1)}}const hn={output:e.stderr},gn=`confirm`,_n=`no-${gn}`;function stdinCheckWrapper(e,{errorMessageForStdin:t=`Please use the --${gn}/--${_n} flags to confirm the action.`}={}){return async(n,...r)=>{let{isTTY:i,hasData:a}=await useStdin(),s=n;if(ue||!i&&!a){if(s.providedConfirmFromStdin===void 0)throw Error(s.errorMessageForStdin??t);return s.providedConfirmFromStdin}return await e(n,...r)}}const vn=stdinCheckWrapper(async({message:e,validate:t,default:n})=>await Ie({message:e,validate:t,default:n},hn),{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=j(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 D(u(e,`scrapy.cfg`))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new Fe,t=p(u(this.pathname,`scrapy.cfg`));if(!D(t))throw Error(`scrapy.cfg not found in "${t}".
31
- 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 vn({message:`Enter the Scrapy BOT_NAME (see settings.py):`,default:e}),n=await vn({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=u(this.pathname,n.replaceAll(`.`,`/`)),r=M(e,{withFileTypes:!0});for(let n of r)n.isFile()&&n.name.endsWith(`.py`)&&n.name!==`__init__.py`&&t.push(...new SpiderFileAnalyzer(u(e,n.name)).getSpiders())}return t}};const yn=new Map,bn={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 De(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 De(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=yn.get(t);if(n)return cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!0,cwd:t,runtime:n.unwrapOr(null)}),n;for(let[e,n]of Object.entries(bn))try{let r=normalizeExecutablePath(await Le(e)),i=await getRuntimeVersion(r,n);if(i){let n={executablePath:r,version:i};if(e===`node`){let e=normalizeExecutablePath(await Le(`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 yn.set(t,Ee(n)),cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!1,cwd:t,runtime:yn.get(t)?.unwrap()}),Ee(n)}}catch{}return yn.set(t,we),cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!1,cwd:t,runtime:null}),we}const xn=new Map;async function getPythonVersion(t){try{let n=await De(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=xn.get(t);if(r&&!n)return cliDebugPrint(`usePythonRuntime`,{cacheHit:!0,cwd:t,runtime:r.unwrapOr(null)}),r;let i=ce()===`win32`,a=i?[`Scripts`,`python.exe`]:[`bin`,`python3`],s;s=e.env.VIRTUAL_ENV?u(e.env.VIRTUAL_ENV,...a):u(t,`.venv`,...a),s=normalizeExecutablePath(s);try{let e=await getPythonVersion(s);if(e)return xn.set(t,Ee({executablePath:s,version:e})),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:xn.get(t)?.unwrap()}),xn.get(t)}catch{}let c=[`python3`,`python`,...i?[`python3.exe`,`python.exe`]:[]];for(let e of c)try{let n=normalizeExecutablePath(await Le(e)),r=await getPythonVersion(n);if(r)return xn.set(t,Ee({executablePath:n,version:r})),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:xn.get(t)?.unwrap()}),xn.get(t)}catch{}return xn.set(t,we),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:null}),we}const Sn=new Map;async function useCwdProject({cwd:t=e.cwd()}={}){let n=Sn.get(t);if(n)return cliDebugPrint(`useCwdProject`,{cacheHit:!0,project:n}),Te(n);let r={type:3},check=async()=>{if(await checkScrapyProject(t)){r.type=2;let e=await usePythonRuntime({cwd:t});r.runtime=e.unwrapOr(void 0),await fileExists(u(t,`uv.lock`))&&(r.packageManager=`uv`);let n=new ScrapyProjectAnalyzer(t);if(n.loadScrapyCfg(),n.configuration.hasKey(`apify`,`mainpy_location`))r.entrypoint={path:n.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 Ce({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(u(t,`uv.lock`))&&(r.packageManager=`uv`);let i=u(t,e.replace(/\./g,`/`));await fileExists(u(i,`__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;let t=await useJavaScriptRuntime();r.runtime=t.unwrapOr(void 0),e.type===`file`?r.entrypoint={path:e.path}:e.type===`script`&&(r.entrypoint={script:e.script});return}return Te(r)},i=await check();return i?.isErr()?(cliDebugPrint(`useCwdProject`,{cacheHit:!1,error:i}),i):(cliDebugPrint(`useCwdProject`,{cacheHit:!1,project:r}),Sn.set(t,r),Te(r))}async function checkNodeProject(e){let t=u(e,`package.json`);try{let n=await z(t,`utf-8`),r=JSON.parse(n);if(r.scripts?.start)return{type:`script`,script:`start`};if(r.main)try{return await Oe(p(e,r.main)),{path:p(e,r.main),type:`file`}}catch{}return{type:`unknown-entrypoint`}}catch{}let n=[u(e,`index.js`),u(e,`index.mjs`),u(e,`index.cjs`),u(e,`main.js`),u(e,`main.mjs`),u(e,`main.cjs`),u(e,`src`,`index.js`),u(e,`src`,`index.mjs`),u(e,`src`,`index.cjs`),u(e,`src`,`main.js`),u(e,`src`,`main.mjs`),u(e,`src`,`main.cjs`),u(e,`dist`,`index.js`),u(e,`dist`,`index.mjs`),u(e,`dist`,`index.cjs`),u(e,`dist`,`main.js`),u(e,`dist`,`main.mjs`),u(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 B(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 Ae(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=u(e,n.name);try{let e=await Ae(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 Ae(u(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 Ae(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 Ae(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(u(e,r.name,`__init__.py`)),a=i||await dirHasPyFiles(u(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 Ae(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(u(e,t,`__init__.py`))&&n.push({name:t,path:u(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=u(e,`src`),i=await fileExists(u(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(`
29
+ `)}`):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})}};const Yt=_(ee);let Xt;async function useStdin(){if(Xt)return Xt;let t=e.stdin,n={isTTY:t.isTTY,hasData:!1,waitDelay:0,stream:t},r=await Yt(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&w.S_IFIFO)===w.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),Xt=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());let onData=e=>{i.push(e),s&&=(clearTimeout(s),null)};r.on(`data`,onData);try{await oe(r,`end`,{signal:a.signal})}catch(e){if(e.name===`AbortError`)return}finally{r.off(`data`,onData),r.pause()}s&&clearTimeout(s),e.hasData=!1;let c=Buffer.concat(i);if(c.length)return c}var Zt={node:`>=22`};const Qt=`storage`,$t={actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},en=Date.UTC(2026,9,1),tn=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let t=u(se(),`.apify`);return e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?u(t,e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):t},AUTH_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),nn=`.actor`,W=u(nn,`actor.json`),rn=Zt.node,an=le.GITHUB_ACTIONS?`${e.env.GITHUB_SERVER_URL}/${e.env.GITHUB_REPOSITORY}/actions/runs/${e.env.GITHUB_RUN_ID}`:void 0,on={"X-Apify-Request-Origin":le.isCI?ve.CI:ve.CLI,...an&&{"X-Apify-Github-Actions-Run-Url":an}},sn=`3.11.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(!D(e))return cn;let t=JSON.parse(A(e,`utf-8`));return migrateStateV0ToV1$1(t)?useLocalState():t}function updateLocalState(e,t){let n={...e};t(n);let r=STATE_FILE_PATH(),i=c(r);O(i,{recursive:!0}),P(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=v(i,ln.version);return{currentVersion:ln.version,latestVersion:i,shouldUpdate:a,cacheHit:!r}}function useCommandSuggestions(e){let t=[...q.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 fn=await readStdin(),pn=useCLIMetadata(),mn=`Apify CLI/${pn.version} (https://github.com/apify/apify-cli)`;function processVersionCheck(t){pn.installMethod!==`bundle`&&(x(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(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+=`
30
+ `,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=q.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){migrateLegacyBundleInstallIfNeeded(),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=g({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(q.get(i)?.subcommands?.length){if(r.positionals[1]?.toLowerCase()===`help`)a=1;else if(r.positionals[2]?.toLowerCase()===`help`){let e=q.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 s=r.positionals[1],c=!1,l=q.get(i);if(!l)return handleCommandNotFound(i);let u=l;if(l.subcommands?.length){if(!s)return l.printHelp();c=!0,u=q.get(`${i} ${s}`)}if(!u)return handleCommandNotFound(`${i} ${s}`);let f=[...n],p=f.indexOf(i);if(cliDebugPrint(`CommandNameIndex`,p),f.splice(p,1),c){let e=f.indexOf(s);cliDebugPrint(`SubcommandNameIndex`,e),f.splice(e,1)}cliDebugPrint(`RebuiltArgs`,f),cliDebugPrint(`CommandToRun`,u);let m=new u(t,c?`${l.name} ${s}`:l.name,i,c?s:void 0),h=m._buildParseArgsOption();cliDebugPrint(`ParserOptionsForCommand`,h);try{let e=g({...h,args:f});await m._run(e),cliDebugPrint(`CommandArgsResult`,e)}catch(t){error({message:U.into(t,u).getPrettyMessage()}),e.exit(1)}}const hn={output:e.stderr},gn=`confirm`,_n=`no-${gn}`;function stdinCheckWrapper(e,{errorMessageForStdin:t=`Please use the --${gn}/--${_n} flags to confirm the action.`}={}){return async(n,...r)=>{let{isTTY:i,hasData:a}=await useStdin(),s=n;if(ue||!i&&!a){if(s.providedConfirmFromStdin===void 0)throw Error(s.errorMessageForStdin??t);return s.providedConfirmFromStdin}return await e(n,...r)}}const vn=stdinCheckWrapper(async({message:e,validate:t,default:n})=>await Ie({message:e,validate:t,default:n},hn),{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=A(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 D(u(e,`scrapy.cfg`))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new Fe,t=p(u(this.pathname,`scrapy.cfg`));if(!D(t))throw Error(`scrapy.cfg not found in "${t}".
31
+ 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 vn({message:`Enter the Scrapy BOT_NAME (see settings.py):`,default:e}),n=await vn({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=u(this.pathname,n.replaceAll(`.`,`/`)),r=te(e,{withFileTypes:!0});for(let n of r)n.isFile()&&n.name.endsWith(`.py`)&&n.name!==`__init__.py`&&t.push(...new SpiderFileAnalyzer(u(e,n.name)).getSpiders())}return t}};const yn=new Map,bn={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 De(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 De(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=yn.get(t);if(n)return cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!0,cwd:t,runtime:n.unwrapOr(null)}),n;for(let[e,n]of Object.entries(bn))try{let r=normalizeExecutablePath(await Le(e)),i=await getRuntimeVersion(r,n);if(i){let n={executablePath:r,version:i};if(e===`node`){let e=normalizeExecutablePath(await Le(`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 yn.set(t,Ee(n)),cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!1,cwd:t,runtime:yn.get(t)?.unwrap()}),Ee(n)}}catch{}return yn.set(t,we),cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!1,cwd:t,runtime:null}),we}const xn=new Map;async function getPythonVersion(t){try{let n=await De(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=xn.get(t);if(r&&!n)return cliDebugPrint(`usePythonRuntime`,{cacheHit:!0,cwd:t,runtime:r.unwrapOr(null)}),r;let i=ce()===`win32`,a=i?[`Scripts`,`python.exe`]:[`bin`,`python3`],s;s=e.env.VIRTUAL_ENV?u(e.env.VIRTUAL_ENV,...a):u(t,`.venv`,...a),s=normalizeExecutablePath(s);try{let e=await getPythonVersion(s);if(e)return xn.set(t,Ee({executablePath:s,version:e})),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:xn.get(t)?.unwrap()}),xn.get(t)}catch{}let c=[`python3`,`python`,...i?[`python3.exe`,`python.exe`]:[]];for(let e of c)try{let n=normalizeExecutablePath(await Le(e)),r=await getPythonVersion(n);if(r)return xn.set(t,Ee({executablePath:n,version:r})),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:xn.get(t)?.unwrap()}),xn.get(t)}catch{}return xn.set(t,we),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:null}),we}const Sn=new Map;async function useCwdProject({cwd:t=e.cwd()}={}){let n=Sn.get(t);if(n)return cliDebugPrint(`useCwdProject`,{cacheHit:!0,project:n}),Te(n);let r={type:3},check=async()=>{if(await checkScrapyProject(t)){r.type=2;let e=await usePythonRuntime({cwd:t});r.runtime=e.unwrapOr(void 0),await fileExists(u(t,`uv.lock`))&&(r.packageManager=`uv`);let n=new ScrapyProjectAnalyzer(t);if(n.loadScrapyCfg(),n.configuration.hasKey(`apify`,`mainpy_location`))r.entrypoint={path:n.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 Ce({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(u(t,`uv.lock`))&&(r.packageManager=`uv`);let i=u(t,e.replace(/\./g,`/`));await fileExists(u(i,`__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;let t=await useJavaScriptRuntime();r.runtime=t.unwrapOr(void 0),e.type===`file`?r.entrypoint={path:e.path}:e.type===`script`&&(r.entrypoint={script:e.script});return}return Te(r)},i=await check();return i?.isErr()?(cliDebugPrint(`useCwdProject`,{cacheHit:!1,error:i}),i):(cliDebugPrint(`useCwdProject`,{cacheHit:!1,project:r}),Sn.set(t,r),Te(r))}async function checkNodeProject(e){let t=u(e,`package.json`);try{let n=await z(t,`utf-8`),r=JSON.parse(n);if(r.scripts?.start)return{type:`script`,script:`start`};if(r.main)try{return await Oe(p(e,r.main)),{path:p(e,r.main),type:`file`}}catch{}return{type:`unknown-entrypoint`}}catch{}let n=[u(e,`index.js`),u(e,`index.mjs`),u(e,`index.cjs`),u(e,`main.js`),u(e,`main.mjs`),u(e,`main.cjs`),u(e,`src`,`index.js`),u(e,`src`,`index.mjs`),u(e,`src`,`index.cjs`),u(e,`src`,`main.js`),u(e,`src`,`main.mjs`),u(e,`src`,`main.cjs`),u(e,`dist`,`index.js`),u(e,`dist`,`index.mjs`),u(e,`dist`,`index.cjs`),u(e,`dist`,`main.js`),u(e,`dist`,`main.mjs`),u(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 B(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 Ae(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=u(e,n.name);try{let e=await Ae(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 Ae(u(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 Ae(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 Ae(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(u(e,r.name,`__init__.py`)),a=i||await dirHasPyFiles(u(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 Ae(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(u(e,t,`__init__.py`))&&n.push({name:t,path:u(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=u(e,`src`),i=await fileExists(u(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(`
32
32
  `);throw Error(`Multiple Python packages found:\n${e}\n\nApify CLI cannot determine which package to run.
33
33
  Please specify the package using the --entrypoint flag, e.g.:
34
34
  apify run --entrypoint <package_name>`)}let n=await findNearMissPackagesInDir(e),r=u(e,`src`),i=!await fileExists(u(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(`
@@ -45,14 +45,14 @@ Common package structures:
45
45
  src/
46
46
  my_package/
47
47
  __init__.py
48
- main.py`);return null}async function checkScrapyProject(e){return ScrapyProjectAnalyzer.isApplicable(e)}function normalizeExecutablePath(e){return e?e.startsWith(`"`)?e:l(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([B(u(e,`yarn.lock`)).then(()=>!0).catch(()=>!1),B(u(e,`pnpm-lock.yaml`)).then(()=>!0).catch(()=>!1),B(u(e,`bun.lockb`)).then(()=>!0).catch(()=>!1),B(u(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=n.packageManager===`uv`?`uv sync`:`python -m pip install -r requirements.txt`)}),t}let Cn=`inherit`;function keepStdoutClean(){Cn=e.stderr}const spawnPromised=async(t,n,r,{forwardSignals:i}={})=>{let a=normalizeExecutablePath(t);cliDebugPrint(`spawnPromised`,{escapedCommand:a,args:n,opts:r,forwardSignals:i});let s=De(a,n,{shell:!0,windowsHide:!0,env:r.env,cwd:r.cwd,stdout:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,Cn],stderr:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0}),c=[];if(i?.length)for(let t of i){let handler=()=>{s.kill(t)};e.on(t,handler),c.push(()=>e.off(t,handler))}try{return await Se.fromAsync(s.catch(e=>{let n;throw n=e.exitCode==null?e.signal?`${t} exited due to signal ${e.signal}`:e.shortMessage:`${t} exited with code ${e.exitCode}`,Error(n,{cause:e})}))}finally{for(let e of c)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 wn=[[`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 wn)if(process.env[e])return t}function detectCi(){return le.isCI?{isCi:!0,ciProvider:le.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 z(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await V(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(m).reduce((e,t)=>(e=u(e,t),D(e)||k(e),e),e)},rimrafPromised=async e=>{let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async e=>Me(e,{recursive:!0,force:!0})))},deleteFile=async e=>{(await B(e)).isFile()&&await Pe(e)};function ensureApifyDirectory(e){let t=c(e);k(t,{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>B(u(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0),Tn=`token`,En=`proxy-password`;let Dn,On,kn;async function loadKeyringModule(){return Dn===void 0&&(Dn=await importKeyringModule()),Dn}async function importKeyringModule(){if(useCLIMetadata().installMethod===`bundle`)try{let e=await import(`__APIFY_KEYRING_NATIVE_SUBPACKAGE__`),t=e.Entry??e.default?.Entry;return t?{Entry:t}:null}catch(e){return cliDebugPrint(`credentials`,`failed to load bundled keyring`,e),null}try{return await import(`@napi-rs/keyring`)}catch(e){return cliDebugPrint(`credentials`,`failed to load @napi-rs/keyring`,e),null}}async function getBackend(){return On||(On=(async()=>e.env.APIFY_DISABLE_KEYRING===`1`||readAuthFile().secretsBackend===`file`?`file`:await loadKeyringModule()?`keyring`:`file`)(),On)}function downgradeBackendToFile(){On=Promise.resolve(`file`)}function readAuthFile(){if(!D(AUTH_FILE_PATH()))return{};try{let e=j(AUTH_FILE_PATH(),`utf-8`);return JSON.parse(e)}catch{return{}}}function writeAuthFile(e){ensureApifyDirectory(AUTH_FILE_PATH()),P(AUTH_FILE_PATH(),JSON.stringify(e,null,` `),{mode:384})}async function getKeyringEntry(e){let t=await loadKeyringModule();return t?new t.Entry(`com.apify.cli`,e):null}async function readKeyring(e){try{let t=await getKeyringEntry(e);return t?t.getPassword()??void 0:void 0}catch(t){cliDebugPrint(`credentials`,`failed to read ${e} from keyring`,t);return}}async function writeKeyring(e,t){let n=await getKeyringEntry(e);if(!n)throw Error(`OS keyring is not available.`);n.setPassword(t)}async function deleteKeyring(e){try{let t=await getKeyringEntry(e);if(!t)return;t.deletePassword()}catch(t){cliDebugPrint(`credentials`,`failed to delete ${e} from keyring`,t)}}async function getToken(){return await getBackend()===`keyring`?readKeyring(Tn):readAuthFile().token}async function getProxyPassword(){return await getBackend()===`keyring`?readKeyring(En):readAuthFile().proxy?.password}async function setToken(e,t={}){let n=await getBackend();if(t.skipIfUnchanged&&(n===`keyring`?await readKeyring(Tn):readAuthFile().token)===e)return;if(n===`keyring`)try{await writeKeyring(Tn,e);return}catch(e){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,e),downgradeBackendToFile()}let r=readAuthFile();r.token=e,r.secretsBackend=`file`,writeAuthFile(r)}async function setProxyPassword(e,t={}){let n=await getBackend();if(t.skipIfUnchanged&&(n===`keyring`?await readKeyring(En):readAuthFile().proxy?.password)===e)return;if(n===`keyring`)try{await writeKeyring(En,e);return}catch(e){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,e),downgradeBackendToFile()}let r=readAuthFile();r.proxy={...r.proxy,password:e},r.secretsBackend=`file`,writeAuthFile(r)}async function clearKeyringSecrets(){await deleteKeyring(Tn),await deleteKeyring(En)}async function ensureMigrated(){return kn||(kn=(async()=>{try{let e=readAuthFile();if(e.secretsBackend||!e.token&&!e.proxy?.password)return;if(await getBackend()===`file`){e.secretsBackend=`file`,writeAuthFile(e);return}try{e.token&&await writeKeyring(Tn,e.token),e.proxy?.password&&await writeKeyring(En,e.proxy.password)}catch(t){cliDebugPrint(`credentials`,`keyring write failed during migration; falling back to file`,t),downgradeBackendToFile(),e.secretsBackend=`file`,writeAuthFile(e);return}delete e.token,e.proxy&&(delete e.proxy.password,Object.keys(e.proxy).length===0&&delete e.proxy),e.secretsBackend=`keyring`,writeAuthFile(e)}catch(e){cliDebugPrint(`credentials`,`migration failed`,e)}})(),kn)}const An=`__CLI_`;function resolveInputKey(){return process.env[F.INPUT_KEY]||process.env[L.INPUT_KEY]||process.env.CRAWLEE_INPUT_KEY||`INPUT`}function inputFileRegExp(e){return RegExp(`(^${Qe(e)}(?:\\.[^.]+)?$)`)}const jn=$e,Mn=qe,getLocalStorageDir=()=>{let t=L.LOCAL_STORAGE_DIR;return e.env[t]||e.env.CRAWLEE_STORAGE_DIR||`storage`},getLocalKeyValueStorePath=t=>{let n=F.DEFAULT_KEY_VALUE_STORE_ID,r=t||e.env[n]||he[n];return u(getLocalStorageDir(),ge.keyValueStores,r)},getLocalDatasetPath=t=>{let n=F.DEFAULT_DATASET_ID,r=t||e.env[n]||he[n];return u(getLocalStorageDir(),ge.datasets,r)},getLocalRequestQueuePath=t=>{let n=F.DEFAULT_REQUEST_QUEUE_ID,r=t||e.env[n]||he[n];return u(getLocalStorageDir(),ge.requestQueues,r)},getLocalUserInfo=async()=>{await ensureMigrated();let e={};try{let t=await z(AUTH_FILE_PATH(),`utf-8`);e=JSON.parse(t)}catch{}if(await getBackend()===`keyring`){let t=await getToken();t&&(e.token=t);let n=await getProxyPassword();n&&(e.proxy={...e.proxy,password:n})}let t=!!(e.username||e.id);if(!(t||e.token))return{};if(!t)throw Error(`Stale credentials found without user metadata. Please run "apify login" again.`);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 resolveToken=async e=>e||(await ensureMigrated(),getToken()),getApifyClientOptions=async(t,n)=>({token:await resolveToken(t),baseUrl:n||e.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[e=>{e.headers??=new Ze;for(let[t,n]of Object.entries(on))e.headers[t]=n;return e}]});async function getLoggedClient(e,t){let n=await resolveToken(e),r=new Je(await getApifyClientOptions(n,t)),i;try{i=await r.user(`me`).get()}catch(e){return cliDebugPrint(`[getLoggedClient] error getting user info`,{error:e,apiBaseUrl:t}),null}r.token&&await setToken(r.token,{skipIfUnchanged:!0});let a=i.proxy?.password;a&&await setProxyPassword(a,{skipIfUnchanged:!0}),ensureApifyDirectory(AUTH_FILE_PATH());let s=(()=>{try{return JSON.parse(j(AUTH_FILE_PATH(),`utf-8`))}catch{return{}}})(),c=await getBackend(),l={...s,...i,secretsBackend:c};if(c===`keyring`&&(delete l.token,l.proxy&&typeof l.proxy==`object`)){let{password:e,...t}=l.proxy;Object.keys(t).length>0?l.proxy=t:delete l.proxy}return P(AUTH_FILE_PATH(),JSON.stringify(l,null,` `),{mode:384}),r}const getLocalConfigPath=e=>u(e,W),getJsonFileContent=e=>{if(D(e))return JSON.parse(j(e,{encoding:`utf-8`}))},getLocalConfig=e=>getJsonFileContent(getLocalConfigPath(e)),setLocalConfig=async(t,n)=>{let r=u(n||e.cwd(),W);await R(c(r),{recursive:!0}),P(r,JSON.stringify(t,null,` `))},Nn=[getLocalStorageDir(),`node_modules`,`.venv`],setLocalEnv=async e=>{let t=getLocalKeyValueStorePath();ensureFolderExistsSync(e,getLocalDatasetPath()),ensureFolderExistsSync(e,getLocalRequestQueuePath()),ensureFolderExistsSync(e,t);let n=u(e,`.gitignore`),r=``;D(n)&&(r=j(n,{encoding:`utf-8`}));let i=[];for(let e of Nn)RegExp(`^${Qe(e)}$`,`mg`).test(r)||i.push(e);i.length>0&&(r.length>0?(i.unshift(`# Added by Apify CLI`),P(n,`\n${i.join(`
48
+ main.py`);return null}async function checkScrapyProject(e){return ScrapyProjectAnalyzer.isApplicable(e)}function normalizeExecutablePath(e){return e?e.startsWith(`"`)?e:l(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([B(u(e,`yarn.lock`)).then(()=>!0).catch(()=>!1),B(u(e,`pnpm-lock.yaml`)).then(()=>!0).catch(()=>!1),B(u(e,`bun.lockb`)).then(()=>!0).catch(()=>!1),B(u(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=n.packageManager===`uv`?`uv sync`:`python -m pip install -r requirements.txt`)}),t}let Cn=`inherit`;function keepStdoutClean(){Cn=e.stderr}const spawnPromised=async(t,n,r,{forwardSignals:i}={})=>{let a=normalizeExecutablePath(t);cliDebugPrint(`spawnPromised`,{escapedCommand:a,args:n,opts:r,forwardSignals:i});let s=De(a,n,{shell:!0,windowsHide:!0,env:r.env,cwd:r.cwd,stdout:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,Cn],stderr:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0}),c=[];if(i?.length)for(let t of i){let handler=()=>{s.kill(t)};e.on(t,handler),c.push(()=>e.off(t,handler))}try{return await Se.fromAsync(s.catch(e=>{let n;throw n=e.exitCode==null?e.signal?`${t} exited due to signal ${e.signal}`:e.shortMessage:`${t} exited with code ${e.exitCode}`,Error(n,{cause:e})}))}finally{for(let e of c)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 wn=[[`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 wn)if(process.env[e])return t}function detectCi(){return le.isCI?{isCi:!0,ciProvider:le.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 z(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await V(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(m).reduce((e,t)=>(e=u(e,t),D(e)||O(e),e),e)},rimrafPromised=async e=>{let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async e=>Me(e,{recursive:!0,force:!0})))},deleteFile=async e=>{(await B(e)).isFile()&&await Pe(e)};function ensureApifyDirectory(e){let t=c(e);O(t,{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>B(u(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0),Tn=`token`,En=`proxy-password`;let Dn,On,kn;async function loadKeyringModule(){return Dn===void 0&&(Dn=await importKeyringModule()),Dn}async function importKeyringModule(){if(useCLIMetadata().installMethod===`bundle`)try{let e=await import(`__APIFY_KEYRING_NATIVE_SUBPACKAGE__`),t=e.Entry??e.default?.Entry;return t?{Entry:t}:null}catch(e){return cliDebugPrint(`credentials`,`failed to load bundled keyring`,e),null}try{return await import(`@napi-rs/keyring`)}catch(e){return cliDebugPrint(`credentials`,`failed to load @napi-rs/keyring`,e),null}}async function getBackend(){return On||(On=(async()=>e.env.APIFY_DISABLE_KEYRING===`1`||readAuthFile().secretsBackend===`file`?`file`:await loadKeyringModule()?`keyring`:`file`)(),On)}function downgradeBackendToFile(){On=Promise.resolve(`file`)}function readAuthFile(){if(!D(AUTH_FILE_PATH()))return{};try{let e=A(AUTH_FILE_PATH(),`utf-8`);return JSON.parse(e)}catch{return{}}}function writeAuthFile(e){ensureApifyDirectory(AUTH_FILE_PATH()),P(AUTH_FILE_PATH(),JSON.stringify(e,null,` `),{mode:384})}async function getKeyringEntry(e){let t=await loadKeyringModule();return t?new t.Entry(`com.apify.cli`,e):null}async function readKeyring(e){try{let t=await getKeyringEntry(e);return t?t.getPassword()??void 0:void 0}catch(t){cliDebugPrint(`credentials`,`failed to read ${e} from keyring`,t);return}}async function writeKeyring(e,t){let n=await getKeyringEntry(e);if(!n)throw Error(`OS keyring is not available.`);n.setPassword(t)}async function deleteKeyring(e){try{let t=await getKeyringEntry(e);if(!t)return;t.deletePassword()}catch(t){cliDebugPrint(`credentials`,`failed to delete ${e} from keyring`,t)}}async function getToken(){return await getBackend()===`keyring`?readKeyring(Tn):readAuthFile().token}async function getProxyPassword(){return await getBackend()===`keyring`?readKeyring(En):readAuthFile().proxy?.password}async function setToken(e,t={}){let n=await getBackend();if(t.skipIfUnchanged&&(n===`keyring`?await readKeyring(Tn):readAuthFile().token)===e)return;if(n===`keyring`)try{await writeKeyring(Tn,e);return}catch(e){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,e),downgradeBackendToFile()}let r=readAuthFile();r.token=e,r.secretsBackend=`file`,writeAuthFile(r)}async function setProxyPassword(e,t={}){let n=await getBackend();if(t.skipIfUnchanged&&(n===`keyring`?await readKeyring(En):readAuthFile().proxy?.password)===e)return;if(n===`keyring`)try{await writeKeyring(En,e);return}catch(e){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,e),downgradeBackendToFile()}let r=readAuthFile();r.proxy={...r.proxy,password:e},r.secretsBackend=`file`,writeAuthFile(r)}async function clearKeyringSecrets(){await deleteKeyring(Tn),await deleteKeyring(En)}async function ensureMigrated(){return kn||(kn=(async()=>{try{let e=readAuthFile();if(e.secretsBackend||!e.token&&!e.proxy?.password)return;if(await getBackend()===`file`){e.secretsBackend=`file`,writeAuthFile(e);return}try{e.token&&await writeKeyring(Tn,e.token),e.proxy?.password&&await writeKeyring(En,e.proxy.password)}catch(t){cliDebugPrint(`credentials`,`keyring write failed during migration; falling back to file`,t),downgradeBackendToFile(),e.secretsBackend=`file`,writeAuthFile(e);return}delete e.token,e.proxy&&(delete e.proxy.password,Object.keys(e.proxy).length===0&&delete e.proxy),e.secretsBackend=`keyring`,writeAuthFile(e)}catch(e){cliDebugPrint(`credentials`,`migration failed`,e)}})(),kn)}const An=`__CLI_`;function resolveInputKey(){return process.env[F.INPUT_KEY]||process.env[L.INPUT_KEY]||process.env.CRAWLEE_INPUT_KEY||`INPUT`}function inputFileRegExp(e){return RegExp(`(^${Qe(e)}(?:\\.[^.]+)?$)`)}const jn=$e,Mn=qe,getLocalStorageDir=()=>{let t=L.LOCAL_STORAGE_DIR;return e.env[t]||e.env.CRAWLEE_STORAGE_DIR||`storage`},getLocalKeyValueStorePath=t=>{let n=F.DEFAULT_KEY_VALUE_STORE_ID,r=t||e.env[n]||he[n];return u(getLocalStorageDir(),ge.keyValueStores,r)},getLocalDatasetPath=t=>{let n=F.DEFAULT_DATASET_ID,r=t||e.env[n]||he[n];return u(getLocalStorageDir(),ge.datasets,r)},getLocalRequestQueuePath=t=>{let n=F.DEFAULT_REQUEST_QUEUE_ID,r=t||e.env[n]||he[n];return u(getLocalStorageDir(),ge.requestQueues,r)},getLocalUserInfo=async()=>{await ensureMigrated();let e={};try{let t=await z(AUTH_FILE_PATH(),`utf-8`);e=JSON.parse(t)}catch{}if(await getBackend()===`keyring`){let t=await getToken();t&&(e.token=t);let n=await getProxyPassword();n&&(e.proxy={...e.proxy,password:n})}let t=!!(e.username||e.id);if(!(t||e.token))return{};if(!t)throw Error(`Stale credentials found without user metadata. Please run "apify login" again.`);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 resolveToken=async e=>e||(await ensureMigrated(),getToken()),getApifyClientOptions=async(t,n)=>({token:await resolveToken(t),baseUrl:n||e.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[e=>{e.headers??=new Ze;for(let[t,n]of Object.entries(on))e.headers[t]=n;return e}]});async function getLoggedClient(e,t){let n=await resolveToken(e),r=new Je(await getApifyClientOptions(n,t)),i;try{i=await r.user(`me`).get()}catch(e){return cliDebugPrint(`[getLoggedClient] error getting user info`,{error:e,apiBaseUrl:t}),null}r.token&&await setToken(r.token,{skipIfUnchanged:!0});let a=i.proxy?.password;a&&await setProxyPassword(a,{skipIfUnchanged:!0}),ensureApifyDirectory(AUTH_FILE_PATH());let s=(()=>{try{return JSON.parse(A(AUTH_FILE_PATH(),`utf-8`))}catch{return{}}})(),c=await getBackend(),l={...s,...i,secretsBackend:c};if(c===`keyring`&&(delete l.token,l.proxy&&typeof l.proxy==`object`)){let{password:e,...t}=l.proxy;Object.keys(t).length>0?l.proxy=t:delete l.proxy}return P(AUTH_FILE_PATH(),JSON.stringify(l,null,` `),{mode:384}),r}const getLocalConfigPath=e=>u(e,W),getJsonFileContent=e=>{if(D(e))return JSON.parse(A(e,{encoding:`utf-8`}))},getLocalConfig=e=>getJsonFileContent(getLocalConfigPath(e)),setLocalConfig=async(t,n)=>{let r=u(n||e.cwd(),W);await R(c(r),{recursive:!0}),P(r,JSON.stringify(t,null,` `))},Nn=[getLocalStorageDir(),`node_modules`,`.venv`],setLocalEnv=async e=>{let t=getLocalKeyValueStorePath();ensureFolderExistsSync(e,getLocalDatasetPath()),ensureFolderExistsSync(e,getLocalRequestQueuePath()),ensureFolderExistsSync(e,t);let n=u(e,`.gitignore`),r=``;D(n)&&(r=A(n,{encoding:`utf-8`}));let i=[];for(let e of Nn)RegExp(`^${Qe(e)}$`,`mg`).test(r)||i.push(e);i.length>0&&(r.length>0?(i.unshift(`# Added by Apify CLI`),P(n,`\n${i.join(`
49
49
  `)}\n`,{flag:`a`})):P(n,`${i.join(`
50
- `)}\n`,{flag:`w`}))},Pn=new nt(it,rt).define({"application/gzip":[`tgz`],"text/typescript":[`ts`,`tsx`,`mts`]},!0),getSourceFileFormat=(e,t)=>{let n=Pn.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:et(t)===`binary`?ye.BASE64:ye.TEXT},createSourceFiles=async(e,t)=>e.map(e=>{let n=j(u(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 at(`**/.gitignore`,{dot:!0,cwd:e,ignore:[`.git/**`],expandDirectories:!1}),n=[];for(let r of t){let t=c(r),i=await z(u(e,r),`utf-8`);n.push({dir:t===`.`?``:t,ig:jn().add(i)})}let r=c(e);for(;r!==c(r)&&!D(u(r,`.git`));){let t=u(r,`.gitignore`);if(D(t))try{let i=await z(t,`utf-8`),a=f(r,e);n.push({dir:``,ig:jn().add(i),ancestorPrefix:a})}catch{}r=c(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=u(e,`.actorignore`);if(!D(t))return{excludeFilter:null,forceIncludePatterns:[]};let n=(await z(t,`utf-8`)).split(`
50
+ `)}\n`,{flag:`w`}))},Pn=new nt(it,rt).define({"application/gzip":[`tgz`],"text/typescript":[`ts`,`tsx`,`mts`]},!0),getSourceFileFormat=(e,t)=>{let n=Pn.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:et(t)===`binary`?ye.BASE64:ye.TEXT},createSourceFiles=async(e,t)=>e.map(e=>{let n=A(u(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 at(`**/.gitignore`,{dot:!0,cwd:e,ignore:[`.git/**`],expandDirectories:!1}),n=[];for(let r of t){let t=c(r),i=await z(u(e,r),`utf-8`);n.push({dir:t===`.`?``:t,ig:jn().add(i)})}let r=c(e);for(;r!==c(r)&&!D(u(r,`.git`));){let t=u(r,`.gitignore`);if(D(t))try{let i=await z(t,`utf-8`),a=f(r,e);n.push({dir:``,ig:jn().add(i),ancestorPrefix:a})}catch{}r=c(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=u(e,`.actorignore`);if(!D(t))return{excludeFilter:null,forceIncludePatterns:[]};let n=(await z(t,`utf-8`)).split(`
51
51
  `),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=jn().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=Be(`git ls-files --others --ignored --exclude-standard --directory`,{cwd:n,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).split(`
52
- `).filter(Boolean);if(e.length>0){let t=jn().add(e);gitIgnoreFilter=e=>e.filter(e=>!t.ignores(e))}}catch{gitIgnoreFilter=await getGitignoreFallbackFilter(n)}let s=await at([`*`,`**/**`],{ignore:r,dot:!0,expandDirectories:!1,cwd:n}),c=gitIgnoreFilter?gitIgnoreFilter(s):s;if(i&&(c=i(c)),a.length>0){let e=jn().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)=>{D(e)&&await deleteFile(e);let r=E(e),i=new Ye({zlib:{level:6}});i.pipe(r),t.forEach(e=>i.file(u(n,e),{name:e})),await i.finalize()},getLocalInput=(e,t)=>{let n=getLocalKeyValueStorePath();if(!D(u(e,n)))return;let r=M(u(e,n)).find(e=>!!e.match(inputFileRegExp(t??`INPUT`)));return r?{body:j(u(e,n,r)),contentType:Pn.getType(r),fileName:r}:void 0},purgeDefaultQueue=async()=>{let e=getLocalRequestQueuePath();D(getLocalStorageDir())&&D(e)&&await rimrafPromised(e)},purgeDefaultDataset=async()=>{let e=getLocalDatasetPath();D(getLocalStorageDir())&&D(e)&&await rimrafPromised(e)},purgeDefaultKeyValueStore=async(...e)=>{let t=getLocalKeyValueStorePath();if(!D(getLocalStorageDir())||!D(t))return;let n=M(t),r=(e.length>0?e:[`INPUT`]).map(inputFileRegExp),i=[];n.forEach(e=>{r.some(t=>t.test(e))||i.push(deleteFile(u(t,e)))}),await Promise.all(i)},outputJobLog=async({job:t,timeoutMillis:n,apifyClient:r})=>{let{id:i,status:a}=t,s=r||new Je({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!==void 0&&(a=setTimeout(()=>{r.destroy(),t(`timeouts`)},n))})},checkIfStorageIsEmpty=async e=>{let t=e||me.INPUT;return(await at([`${getLocalStorageDir()}/**`,`!${getLocalKeyValueStorePath()}/${t}.*`,`!${getLocalKeyValueStorePath()}/${An}${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=>x(e,`^${sn}`),isNodeVersionSupported=e=>{let t=b(rn);return y(e,t)},downloadZip=async e=>{let t=await Xe.get(e,{responseType:`arraybuffer`,validateStatus:()=>!0,headers:{"User-Agent":`Apify CLI/${useCLIMetadata().version} (https://github.com/apify/apify-cli)`}});if(t.status<200||t.status>=300){let n=Buffer.from(t.data).toString(`utf8`).trim().slice(0,500);throw Error(`Failed to download the archive from ${e} (HTTP ${t.status}).${n?`\nServer response: ${n}`:``}`)}let n=Buffer.from(t.data);if(n.subarray(0,2).toString()!==`PK`)throw Error(`The file downloaded from ${e} is not a valid zip archive - a proxy or firewall likely intercepted the download. Check your network or try a different one.`);return new Ke(n)},downloadAndUnzip=async({url:e,pathTo:t})=>{(await downloadZip(e)).extractAllTo(t,!0)},G=new Ge(`YYYY-MM-DD [at] HH:mm:ss`),Fn=new Ge(`YYYY-MM-DD[
52
+ `).filter(Boolean);if(e.length>0){let t=jn().add(e);gitIgnoreFilter=e=>e.filter(e=>!t.ignores(e))}}catch{gitIgnoreFilter=await getGitignoreFallbackFilter(n)}let s=await at([`*`,`**/**`],{ignore:r,dot:!0,expandDirectories:!1,cwd:n}),c=gitIgnoreFilter?gitIgnoreFilter(s):s;if(i&&(c=i(c)),a.length>0){let e=jn().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)=>{D(e)&&await deleteFile(e);let r=E(e),i=new Ye({zlib:{level:6}});i.pipe(r),t.forEach(e=>i.file(u(n,e),{name:e})),await i.finalize()},getLocalInput=(e,t)=>{let n=getLocalKeyValueStorePath(),r=p(e,n);if(!D(r))return;let i=te(r).find(e=>!!e.match(inputFileRegExp(t??`INPUT`)));return i?{body:A(u(r,i)),contentType:Pn.getType(i),fileName:i}:void 0},purgeDefaultQueue=async()=>{await rimrafPromised(p(e.cwd(),getLocalRequestQueuePath()))},purgeDefaultDataset=async()=>{await rimrafPromised(p(e.cwd(),getLocalDatasetPath()))},purgeDefaultKeyValueStore=async(...t)=>{let n=p(e.cwd(),getLocalKeyValueStorePath());if(!D(n))return;let r=te(n),i=(t.length>0?t:[`INPUT`]).map(inputFileRegExp),a=[];r.forEach(e=>{i.some(t=>t.test(e))||a.push(deleteFile(u(n,e)))}),await Promise.all(a)},outputJobLog=async({job:t,timeoutMillis:n,apifyClient:r})=>{let{id:i,status:a}=t,s=r||new Je({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!==void 0&&(a=setTimeout(()=>{r.destroy(),t(`timeouts`)},n))})},checkIfStorageIsEmpty=async t=>{let n=t||me.INPUT,r=getLocalStorageDir().replaceAll(`\\`,`/`),i=getLocalKeyValueStorePath().replaceAll(`\\`,`/`);return(await at([`${r}/**`,`!${i}/${n}.*`,`!${i}/${An}${n}.*`],{cwd:e.cwd()})).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=>x(e,`^${sn}`),isNodeVersionSupported=e=>{let t=b(rn);return y(e,t)},downloadZip=async e=>{let t=await Xe.get(e,{responseType:`arraybuffer`,validateStatus:()=>!0,headers:{"User-Agent":`Apify CLI/${useCLIMetadata().version} (https://github.com/apify/apify-cli)`}});if(t.status<200||t.status>=300){let n=Buffer.from(t.data).toString(`utf8`).trim().slice(0,500);throw Error(`Failed to download the archive from ${e} (HTTP ${t.status}).${n?`\nServer response: ${n}`:``}`)}let n=Buffer.from(t.data);if(n.subarray(0,2).toString()!==`PK`)throw Error(`The file downloaded from ${e} is not a valid zip archive - a proxy or firewall likely intercepted the download. Check your network or try a different one.`);return new Ke(n)},downloadAndUnzip=async({url:e,pathTo:t})=>{(await downloadZip(e)).extractAllTo(t,!0)},G=new Ge(`YYYY-MM-DD [at] HH:mm:ss`),Fn=new Ge(`YYYY-MM-DD[
53
53
  ]HH:mm:ss`),In=new Ge(`YYYY-MM-DD`),Ln=new He,K=new He({[We.Day]:{DEFAULT:`d`},[We.Hour]:{DEFAULT:`h`},[We.Minute]:{DEFAULT:`m`},[We.Month]:{DEFAULT:`M`},[We.Second]:{DEFAULT:`s`},[We.Week]:{DEFAULT:`w`},[We.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 userHomeDir=()=>e.env.HOME??se(),tildify=e=>{let t=userHomeDir();return t&&e.startsWith(t)?e.replace(t,`~`):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=[u(t,`.bashrc`),u(t,`.bash_profile`)];e.env.XDG_CONFIG_HOME&&n.push(u(e.env.XDG_CONFIG_HOME,`.bashrc`),u(e.env.XDG_CONFIG_HOME,`.bash_profile`),u(e.env.XDG_CONFIG_HOME,`bashrc`),u(e.env.XDG_CONFIG_HOME,`bash_profile`));for(let e of n)if(D(e))return e;return null}case`zsh`:{let n=e.env.ZDOTDIR||t||userHomeDir();return u(n,`.zshrc`)}case`fish`:return u(t,`.config`,`fish`,`config.fish`);case`unknown`:return null}}function parseWaitForFinishMillis(e){if(e===void 0)return;let t=Number.parseInt(e,10);if(!(!Number.isFinite(t)||t<0))return t*1e3}const Rn=[`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(`
54
- `);function createAnonymousId(){return`CLI:${ze()}`}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(!D(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:Rn}),useTelemetryState()}let t=JSON.parse(j(e,`utf-8`));return await migrateStateV0ToV1(t)?useTelemetryState():t}function updateTelemetryState(e,t){let n={...e};t?.(n);let r=TELEMETRY_FILE_PATH(),i=c(r);k(i,{recursive:!0}),P(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 zn=useCLIMetadata(),Bn=zn.isBeta?`rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC`:`2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t`;async function trackEvent(e,t){let n=await useTelemetryIdentifiers(),r={anonymousId:n.anonymousId,context:{app:{name:`apify-cli`,version:zn.version,build:zn.hash},library:{name:`apify-cli`,version:zn.version},os:{name:zn.platform},userAgent:mn,channel:`server`},event:e,properties:{...t,app:`cli`},timestamp:new Date().toISOString(),userId:n.userId,writeKey:Bn};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)}}function shouldSkipRentalSunsetNotice({now:e,isCi:t,skipEnvValue:n}){return!!(n&&![`0`,`false`].includes(n)||t||e>=en)}function wasNotifiedRecently(e,t,n){return!e?.lastNotifiedAt||e.username!==t?!1:n-e.lastNotifiedAt<864e5}function renderRentalSunsetNotice(e){let n=e===1?`rental Actor`:`rental Actors`;return[t.bold(`Rental model sunset`),``,`You have ${e} ${n} published in Apify Store. Apify is sunsetting the rental pricing model.`,``,` ${t.bold(`April 1, 2026`)} Publishing new rental Actors and pricing changes on existing ones were disabled.`,` ${t.bold(`October 1, 2026`)} Rental Actors are fully retired. All remaining Actors move to pay-per-usage pricing.`,``,`Switch your ${n} to pay-per-event before October 1 to keep control over what you charge.`,`This guide walks through picking events, setting prices, and shipping the change:`,` ${t.cyan(`https://blog.apify.com/migrating-to-pay-per-event-pricing/`)}`,``,`Questions? Ask in the ${t.cyan(`#project-rentals`)} channel on Apify Discord:`,` ${t.cyan(`https://apify.com/discord`)}`,``,t.dim(`To silence this notice, set APIFY_CLI_SKIP_RENTAL_SUNSET_NOTICE=1.`),``].join(`
55
- `)}async function getLocalUsername(){try{let e=await z(AUTH_FILE_PATH(),`utf-8`);return JSON.parse(e).username}catch{return}}async function fetchRentalActorCount(t){let n=useCLIMetadata(),r=new URL(`/v2/store`,e.env.APIFY_CLIENT_BASE_URL||`https://api.apify.com`);try{let{data:e}=await Xe.get(r.href,{params:{username:t,pricingModel:`FLAT_PRICE_PER_MONTH`,limit:1},timeout:3e3,headers:{...on,"User-Agent":`Apify CLI/${n.version} (https://github.com/apify/apify-cli)`}});return typeof e?.data?.total==`number`?e.data.total:(cliDebugPrint(`useRentalSunsetNotice`,`Store response has no data.total`,{body:e}),null)}catch(e){return cliDebugPrint(`useRentalSunsetNotice`,`Failed to look up rental Actors`,e),null}}async function resolveRentalActorCount(e,t,n){let r=e?.username===t?e:void 0;return r&&n-r.lastChecked<864e5?{rentalActorCount:r.rentalActorCount,lastChecked:r.lastChecked,fromCache:!0}:{rentalActorCount:await fetchRentalActorCount(t)??r?.rentalActorCount??0,lastChecked:n,fromCache:!1}}async function useRentalSunsetNotice(){try{let t=Date.now(),n=useLocalState();if(shouldSkipRentalSunsetNotice({now:t,isCi:ue,skipEnvValue:e.env.APIFY_CLI_SKIP_RENTAL_SUNSET_NOTICE}))return;let r=await getLocalUsername();if(!r){cliDebugPrint(`useRentalSunsetNotice`,`Not logged in, skipping the check`);return}if(wasNotifiedRecently(n.rentalSunset,r,t))return;let{rentalActorCount:i,lastChecked:a,fromCache:s}=await resolveRentalActorCount(n.rentalSunset,r,t),c=i>0;if(s&&!c||(updateLocalState(n,e=>{e.rentalSunset={lastChecked:a,username:r,rentalActorCount:i,...c?{lastNotifiedAt:t}:{}}}),!c))return;simpleLog({message:``}),warning({message:renderRentalSunsetNotice(i)})}catch(e){cliDebugPrint(`useRentalSunsetNotice`,`Failed to run the rental sunset check`,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 Vn={type:`boolean`,multiple:!1,short:`h`},Hn={type:`boolean`,multiple:!1},Un={type:`string`,multiple:!1},Wn=`user-agent`,Gn=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 q=new Map,Kn=[`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;skipNotices=!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(),Gn.has(this.entrypoint)){let t=r[Wn],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,this.flags.json&&keepStdoutClean());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++];a?(n.argTag,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(` `))):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&&Kn.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.telemetryData)),!this.skipNotices&&!e.exitCode&&await useRentalSunsetNotice()}}_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=>Object.hasOwn(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)}}else s.hasDefault!==void 0&&(this.flags[f]=s.hasDefault);if(this.flags[f]!=null&&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(`
54
+ `);function createAnonymousId(){return`CLI:${ze()}`}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(!D(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:Rn}),useTelemetryState()}let t=JSON.parse(A(e,`utf-8`));return await migrateStateV0ToV1(t)?useTelemetryState():t}function updateTelemetryState(e,t){let n={...e};t?.(n);let r=TELEMETRY_FILE_PATH(),i=c(r);O(i,{recursive:!0}),P(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 zn=useCLIMetadata(),Bn=zn.isBeta?`rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC`:`2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t`;async function trackEvent(e,t){let n=await useTelemetryIdentifiers(),r={anonymousId:n.anonymousId,context:{app:{name:`apify-cli`,version:zn.version,build:zn.hash},library:{name:`apify-cli`,version:zn.version},os:{name:zn.platform},userAgent:mn,channel:`server`},event:e,properties:{...t,app:`cli`},timestamp:new Date().toISOString(),userId:n.userId,writeKey:Bn};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)}}function shouldSkipRentalSunsetNotice({now:e,isCi:t,skipEnvValue:n}){return!!(n&&![`0`,`false`].includes(n)||t||e>=en)}function wasNotifiedRecently(e,t,n){return!e?.lastNotifiedAt||e.username!==t?!1:n-e.lastNotifiedAt<864e5}function renderRentalSunsetNotice(e){let n=e===1?`rental Actor`:`rental Actors`;return[t.bold(`Rental model sunset`),``,`You have ${e} ${n} published in Apify Store. Apify is sunsetting the rental pricing model.`,``,` ${t.bold(`April 1, 2026`)} Publishing new rental Actors and pricing changes on existing ones were disabled.`,` ${t.bold(`October 1, 2026`)} Rental Actors are fully retired. All remaining Actors move to pay-per-usage pricing.`,``,`Switch your ${n} to pay-per-event before October 1 to keep control over what you charge.`,`This guide walks through picking events, setting prices, and shipping the change:`,` ${t.cyan(`https://blog.apify.com/migrating-to-pay-per-event-pricing/`)}`,``,`Questions? Ask in the ${t.cyan(`#project-rentals`)} channel on Apify Discord:`,` ${t.cyan(`https://apify.com/discord`)}`,``,t.dim(`To silence this notice, set APIFY_CLI_SKIP_RENTAL_SUNSET_NOTICE=1.`),``].join(`
55
+ `)}async function getLocalUsername(){try{let e=await z(AUTH_FILE_PATH(),`utf-8`);return JSON.parse(e).username}catch{return}}async function fetchRentalActorCount(t){let n=useCLIMetadata(),r=new URL(`/v2/store`,e.env.APIFY_CLIENT_BASE_URL||`https://api.apify.com`);try{let{data:e}=await Xe.get(r.href,{params:{username:t,pricingModel:`FLAT_PRICE_PER_MONTH`,limit:1},timeout:3e3,headers:{...on,"User-Agent":`Apify CLI/${n.version} (https://github.com/apify/apify-cli)`}});return typeof e?.data?.total==`number`?e.data.total:(cliDebugPrint(`useRentalSunsetNotice`,`Store response has no data.total`,{body:e}),null)}catch(e){return cliDebugPrint(`useRentalSunsetNotice`,`Failed to look up rental Actors`,e),null}}async function resolveRentalActorCount(e,t,n){let r=e?.username===t?e:void 0;return r&&n-r.lastChecked<864e5?{rentalActorCount:r.rentalActorCount,lastChecked:r.lastChecked,fromCache:!0}:{rentalActorCount:await fetchRentalActorCount(t)??r?.rentalActorCount??0,lastChecked:n,fromCache:!1}}async function useRentalSunsetNotice(){try{let t=Date.now(),n=useLocalState();if(shouldSkipRentalSunsetNotice({now:t,isCi:ue,skipEnvValue:e.env.APIFY_CLI_SKIP_RENTAL_SUNSET_NOTICE}))return;let r=await getLocalUsername();if(!r){cliDebugPrint(`useRentalSunsetNotice`,`Not logged in, skipping the check`);return}if(wasNotifiedRecently(n.rentalSunset,r,t))return;let{rentalActorCount:i,lastChecked:a,fromCache:s}=await resolveRentalActorCount(n.rentalSunset,r,t),c=i>0;if(s&&!c||(updateLocalState(n,e=>{e.rentalSunset={lastChecked:a,username:r,rentalActorCount:i,...c?{lastNotifiedAt:t}:{}}}),!c))return;simpleLog({message:``}),warning({message:renderRentalSunsetNotice(i)})}catch(e){cliDebugPrint(`useRentalSunsetNotice`,`Failed to run the rental sunset check`,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 Vn={type:`boolean`,multiple:!1,short:`h`},Hn={type:`boolean`,multiple:!1},Un={type:`string`,multiple:!1},Wn=`user-agent`,Gn=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 q=new Map,Kn=[`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;skipNotices=!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(),Gn.has(this.entrypoint)){let t=r[Wn],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,this.flags.json&&keepStdoutClean());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++];a?(n.argTag,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(` `))):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&&Kn.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.telemetryData)),!this.skipNotices&&!e.exitCode&&await useRentalSunsetNotice()}}_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=>Object.hasOwn(e,t));if(m.length>1)throw new U({code:3,command:this.ctor,metadata:{flag:l}});let h=e[m[0]];if(h===void 0&&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)}}else s.hasDefault!==void 0&&(this.flags[f]=s.hasDefault);if(this.flags[f]!=null&&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(`
56
56
  `)),c=[];for(let[r,a]of e){let e=`${r.padEnd(s)} ${a.description}`,l=i(e,getMaxLineWidth()-s-2),u=n(l,s+2+2).trim();c.push(` ${t.red(`>`)} ${u}`)}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(`
57
57
  `)})}_handleStdin(e){switch(e){case 2:return(fn?.toString(`utf8`)??``).trim();default:return fn}}_buildParseArgsOption(){let e={help:Vn};Gn.has(this.entrypoint)&&(e[Wn]=Un);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=Hn),t}static registerCommand(e){if(registerCommandForHelpGeneration(e,this),q.set(this.name,this),this.aliases?.length)for(let e of this.aliases)q.set(e,this);if(this.hiddenAliases?.length)for(let e of this.hiddenAliases)q.set(e,this);if(this.subcommands?.length)for(let e of this.subcommands){if(q.set(`${this.name} ${e.name}`,e),this.aliases?.length)for(let t of this.aliases)q.set(`${t} ${e.name}`,e);if(this.hiddenAliases?.length)for(let t of this.hiddenAliases)q.set(`${t} ${e.name}`,e);if(e.aliases?.length)for(let t of e.aliases){if(q.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)q.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)q.set(`${n} ${t}`,e)}if(e.hiddenAliases?.length)for(let t of e.hiddenAliases){if(q.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)q.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)q.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);return a.skipTelemetry=!0,a.skipNotices=!0,await a._run(r),a}const J={string:stringFlag,boolean:booleanFlag,integer:integerFlag};function YesFlag(e=`Automatic yes to prompts; assume "yes" as answer to all prompts.`){return{yes:J.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`}const qn=ct((e,t)=>{let n=boolToString,[r,i]=pt(`idle`),[a,s]=pt(``),c=ut(),l=ft({status:r,theme:c});dt((r,c)=>{if(lt(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}`}),Y=stdinCheckWrapper(async({message:e,default:t})=>await qn({message:e,default:t},hn)),getDeprecatedLocalConfigPath=e=>u(e,`apify.json`),Jn=new Map;async function useActorConfig({cwd:t=e.cwd(),migrateConfig:n=!0,warnAboutOldConfig:r=!0}={cwd:e.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let i=Jn.get(t);if(i)return cliDebugPrint(`useActorConfig`,{cacheHit:!0,config:i}),Te(i);let a=getLocalConfigPath(t),s=getDeprecatedLocalConfigPath(t),c,l;try{c=getJsonFileContent(a)}catch(e){return Ce({message:`Failed to read local config at path: '${a}':`,cause:e,exists:!1,config:{}})}try{l=getJsonFileContent(s)}catch(e){return Ce({message:`Failed to read local config at path: '${s}':`,cause:e,exists:!1,config:{}})}if(c&&l&&r&&await handleBothConfigVersionsFound(s),!c&&!l)return Jn.set(t,{exists:!1,migrated:!1,config:{}}),Te({exists:!1,migrated:!1,config:{}});let u=!1;if(!c&&l&&n){let e=await handleMigrationFlow(l,s,a);if(e.isErr())return Ce(e.unwrapErr());c=e.unwrap(),u=!0}return Jn.set(t,{exists:!0,migrated:u,config:c||l||{}}),cliDebugPrint(`useActorConfig`,{cacheHit:!1,config:Jn.get(t)}),Te({exists:!0,migrated:u,config:c||l||{}})}async function handleBothConfigVersionsFound(e){if(!await Y({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 je(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 ${h(e,{showHidden:!1})}`})}}const Yn=[`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,...Yn.reduce((t,n)=>(t[n]=e[n],t),{})},!await Y({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 Ce({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 R(c(n),{recursive:!0}),await V(n,JSON.stringify(r,null,` `))}catch(e){let t=e;return Ce({message:`Failed to write the new "actor.json" file to path: '${n}'.\n ${t.message||t}`,exists:!0,config:r})}try{await je(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.`}),Te(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 Xn=u(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:J.string({description:`Path to the input JSON file used for the calculation.`,required:!1,default:Xn}),defaultMemoryMbytes:J.string({description:`Memory-calculation expression (in MB). If omitted, the value is loaded from the actor.json file.`,required:!1}),build:J.string({description:`Actor build version or build tag to evaluate the expression with.`,required:!1}),timeoutSecs:J.integer({description:`Maximum run timeout, in seconds.`,required:!1}),maxItems:J.integer({description:`Maximum number of items Actor can output.`,required:!1}),maxTotalChargeUsd:J.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=p(e.cwd(),t),c=getJsonFileContent(s)??{};info({message:`Evaluating memory expression: ${n}`});try{let e=await ot(n,{input:c,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 Zn={KEY_VALUE_STORE:`KEY_VALUE_STORE`,DATASET:`DATASET`,REQUEST_QUEUE:`REQUEST_QUEUE`},getApifyTokenFromEnvOrAuthFile=async()=>{let t=e.env[L.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,L.IS_AT_HOME))=>{let r=getLocalStorageDir();if(r&&!n)return new ht({localDataDirectory:r,...t});let i=await getApifyTokenFromEnvOrAuthFile();return new Je({...await getApifyClientOptions(i),...t})},getDefaultStorageId=t=>{let n=F[`DEFAULT_${t}_ID`];return e.env[n]||he[n]},outputRecordFromDefaultStore=async t=>{let n=await getApifyStorageClient(),r=getDefaultStorageId(Zn.KEY_VALUE_STORE),i=await n.keyValueStore(r).getRecord(t,{stream:!0});i&&await mt(i.value,e.stdout,{end:!1})},outputInputFromDefaultStore=async()=>outputRecordFromDefaultStore(e.env[F.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 X={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:X.string({description:`Name of the event to charge for.`,required:!0})};static flags={count:J.integer({description:`Number of events to charge.`,required:!1,default:1}),"idempotency-key":J.string({description:`Idempotency key for the charge request.`,required:!1}),"test-pay-per-event":J.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[L.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 Qn=[`.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=u(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 Qn){let n=u(t,e);if(D(n))return{inputSchema:getJsonFileContent(n),inputSchemaPath:n}}return{inputSchema:null,inputSchemaPath:u(t,Qn[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}.`);info({message:n(i)});let a=new Mn({strict:!1});return _t(a,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=u(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});if(n){let e=new Mn({strict:!1});_t(e,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{let n=getLocalKeyValueStorePath(),r=u(e,n,`${me.INPUT}.json`);P(r,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(`
58
58
  `)}`}function validateDatasetSchema(e){let t=yt();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Dataset`))}function validateOutputSchema(e){let t=xt();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Output`))}function validateKvsSchema(e){let t=bt();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Key-Value Store`))}const getAjvValidator=(e,t)=>{let n=structuredClone(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=structuredClone(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=structuredClone(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=structuredClone(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=structuredClone(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=structuredClone(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=structuredClone(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.
@@ -99,18 +99,18 @@ To inspect the input schema before creating a JSON input, use "apify actors info
99
99
  `));break}case`FREE`:u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);break;default:{let n=e.pricingModel;u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Unknown pricing model (${t.yellow(n)})`)}`)}}}else u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);(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}`));let{stats:p}=c;if(u.push(``,t.yellow(`Actor stats:`),` ${t.yellow(`Total users:`)} ${t.cyan(`${p.totalUsers}`)}`,` ${t.yellow(`Users (30d):`)} ${t.cyan(`${p.totalUsers30Days}`)}`,` ${t.yellow(`Total runs:`)} ${t.cyan(`${p.totalRuns}`)}`),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(`
100
100
  `),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 cr={"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`)},lr=new Z({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`}}}}),ur=new Z({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:J.boolean({description:`Whether to list Actors made by the logged in user.`,default:!1}),offset:J.integer({description:`Number of Actors that will be skipped.`,default:0}),limit:J.integer({description:`Number of Actors that will be listed.`,default:20}),desc:J.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?ur:lr,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?Fn.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(cr[e.lastRun.status],t.cyan(r)),e.lastRun.finishedAt){let r=Date.now()-e.lastRun.finishedAt.getTime();r<Ue.Week?n.push(`
101
101
  `,t.gray(`${K.format(r)} ago`)):n.push(`
102
- `,t.gray(`On`,In.display(e.lastRun.finishedAt)))}return n.join(` `)}return``})();u.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Runs:Z.isSmallTerminal()&&f>=56?ar: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":Fn.display(e.modifiedAt),Builds:e.actor?t.cyan(e.actor.stats.totalBuilds):t.gray(`Unknown`),"Last run duration":Z.isSmallTerminal()?ar: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 n=await downloadZip(e);n.extractEntryTo(n.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:J.string({char:`v`,description:`Actor version number which will be pulled, e.g. 1.2. Default: the highest version.`,required:!1}),dir:J.string({description:`Directory where the Actor should be pulled to.`,required:!1})};static args={actorId:X.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,l=i.username||i.id,f=this.args?.actorId||r?.id||(r?.name?`${l}/${r.name}`:void 0);if(!f)throw Error(`Cannot find Actor in this directory.`);let p;try{p=await a.actor(f).get()}catch{throw Error(`Cannot find Actor with ID/name '${f}' in your account.`)}if(!p)throw Error(`Cannot find Actor with ID/name '${f}' in your account.`);let{name:m,versions:h}=p,throwMissingSourceCodeAccessError=()=>{throw Error(`You cannot pull source code of this Actor because you do not have permission to do so.`)};if(!p.versions.length)throw Error(`Actor ${f} has no versions.`);let g=null;if(this.flags.version&&(g=h.find(e=>e.versionNumber===this.flags.version),!g))throw Error(`Cannot find version ${this.flags.version} of Actor ${f}.`);g||=h.reduce((e,t)=>v(`${t.versionNumber}.0`,`${e.versionNumber}.0`)?t:e);let _=s?t:u(t,this.flags.dir??m);if(k(_,{recursive:!0}),!s&&M(_).length!==0){error({message:`Directory ${_} is not empty. Please empty it or choose another directory.`});return}let{sourceType:y}=g;switch(y){case`TARBALL`:g.tarballUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(g.tarballUrl,_);break;case`SOURCE_FILES`:{g.sourceFiles||throwMissingSourceCodeAccessError();let{sourceFiles:e}=g;for(let t of e){let e=c(t.name);if(k(`${_}/${e}`,{recursive:!0}),!t.folder){let e=t.format===`BASE64`?Buffer.from(t.content,`base64`).toString():t.content;if(t.name===W){let n=wt.parse(e);n.name=p.name,P(`${_}/${t.name}`,wt.update(e,n))}else P(`${_}/${t.name}`,e)}}break}case`GIT_REPO`:{g.gitRepoUrl||throwMissingSourceCodeAccessError();let{gitRepoUrl:e}=g;try{await Ct(`git:${e}`,{dir:_})}catch(t){throw Error(`Failed to pull Actor from ${e}. ${t.message}`)}break}case`GITHUB_GIST`:g.gitHubGistUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(`${g.gitHubGistUrl}/archive/master.zip`,_);break;default:throw Error(`Unknown source type: ${y}`)}success({message:s?`Actor ${m} updated at ${_}/`:`Pulled to ${_}/`})}};const dr=5e4,getSecretsFile=()=>{try{return JSON.parse(j(SECRETS_FILE_PATH(),`utf-8`))||{}}catch{return{}}},writeSecretsFile=e=>(ensureApifyDirectory(SECRETS_FILE_PATH()),P(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>dr)throw Error(`Secret value has to be string with maximum length ${dr}.`);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(`
102
+ `,t.gray(`On`,In.display(e.lastRun.finishedAt)))}return n.join(` `)}return``})();u.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Runs:Z.isSmallTerminal()&&f>=56?ar: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":Fn.display(e.modifiedAt),Builds:e.actor?t.cyan(e.actor.stats.totalBuilds):t.gray(`Unknown`),"Last run duration":Z.isSmallTerminal()?ar: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 n=await downloadZip(e);n.extractEntryTo(n.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:J.string({char:`v`,description:`Actor version number which will be pulled, e.g. 1.2. Default: the highest version.`,required:!1}),dir:J.string({description:`Directory where the Actor should be pulled to.`,required:!1})};static args={actorId:X.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,l=i.username||i.id,f=this.args?.actorId||r?.id||(r?.name?`${l}/${r.name}`:void 0);if(!f)throw Error(`Cannot find Actor in this directory.`);let p;try{p=await a.actor(f).get()}catch{throw Error(`Cannot find Actor with ID/name '${f}' in your account.`)}if(!p)throw Error(`Cannot find Actor with ID/name '${f}' in your account.`);let{name:m,versions:h}=p,throwMissingSourceCodeAccessError=()=>{throw Error(`You cannot pull source code of this Actor because you do not have permission to do so.`)};if(!p.versions.length)throw Error(`Actor ${f} has no versions.`);let g=null;if(this.flags.version&&(g=h.find(e=>e.versionNumber===this.flags.version),!g))throw Error(`Cannot find version ${this.flags.version} of Actor ${f}.`);g||=h.reduce((e,t)=>v(`${t.versionNumber}.0`,`${e.versionNumber}.0`)?t:e);let _=s?t:u(t,this.flags.dir??m);if(O(_,{recursive:!0}),!s&&te(_).length!==0){error({message:`Directory ${_} is not empty. Please empty it or choose another directory.`});return}let{sourceType:y}=g;switch(y){case`TARBALL`:g.tarballUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(g.tarballUrl,_);break;case`SOURCE_FILES`:{g.sourceFiles||throwMissingSourceCodeAccessError();let{sourceFiles:e}=g;for(let t of e){let e=c(t.name);if(O(`${_}/${e}`,{recursive:!0}),!t.folder){let e=t.format===`BASE64`?Buffer.from(t.content,`base64`).toString():t.content;if(t.name===W){let n=wt.parse(e);n.name=p.name,P(`${_}/${t.name}`,wt.update(e,n))}else P(`${_}/${t.name}`,e)}}break}case`GIT_REPO`:{g.gitRepoUrl||throwMissingSourceCodeAccessError();let{gitRepoUrl:e}=g;try{await Ct(`git:${e}`,{dir:_})}catch(t){throw Error(`Failed to pull Actor from ${e}. ${t.message}`)}break}case`GITHUB_GIST`:g.gitHubGistUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(`${g.gitHubGistUrl}/archive/master.zip`,_);break;default:throw Error(`Unknown source type: ${y}`)}success({message:s?`Actor ${m} updated at ${_}/`:`Pulled to ${_}/`})}};const dr=5e4,getSecretsFile=()=>{try{return JSON.parse(A(SECRETS_FILE_PATH(),`utf-8`))||{}}catch{return{}}},writeSecretsFile=e=>(ensureApifyDirectory(SECRETS_FILE_PATH()),P(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>dr)throw Error(`Secret value has to be string with maximum length ${dr}.`);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(`
103
103
  `);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.
104
104
  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(`
105
105
  `);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.
106
106
  If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},fr=`temp_file.zip`,pr={build:`latest`,memoryMbytes:4096,timeoutSecs:3600};function resolvePushOutcome(e){switch(e){case I.SUCCEEDED:return{resultLabel:`SUCCEEDED`,exitCode:0,ok:!0};case I.READY:return{resultLabel:`PENDING`,ok:!0};case I.RUNNING:return{resultLabel:`RUNNING`,ok:!0};case I.ABORTING:return{resultLabel:`ABORTING`,exitCode:3,ok:!1,errorMessage:`Build is aborting`};case I.ABORTED:return{resultLabel:`ABORTED`,exitCode:3,ok:!1,errorMessage:`Build aborted`};case I.TIMING_OUT:return{resultLabel:`TIMING_OUT`,exitCode:2,ok:!1,errorMessage:`Build is timing out`};case I.TIMED_OUT:return{resultLabel:`TIMED_OUT`,exitCode:2,ok:!1,errorMessage:`Build timed out`};case I.FAILED:return{resultLabel:`FAILED`,exitCode:1,ok:!1,errorMessage:`Build failed`};default:return{resultLabel:`UNKNOWN`,exitCode:1,ok:!1,errorMessage:`Build finished with unexpected status "${e}"`}}}const confirmGitSourceSwitch=async({actorName:e,gitRepoUrl:t,force:n})=>(warning({message:[`Actor ${e} builds from a Git repository: ${t}`,`A push replaces that source with the local files and drops the Git connection.`,`To build from the repository, run git push instead. The platform builds on push when automated builds are on.`].join(`
107
107
  `)}),n?!0:Y({message:`Switch the source to the local files?`,default:!1,errorMessageForStdin:`Actor ${e} builds from a Git repository. To switch the source to the local files, use --force.`}));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.
108
108
  Files matched by .gitignore and .actorignore are excluded. Use negation patterns (e.g. !dist/) in .actorignore to force-include git-ignored files.
109
- 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:J.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":J.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":J.string({char:`w`,description:`In seconds, how long to wait for the build to finish. If no value passed, it waits forever. To return as soon as the build is queued (fire-and-forget), pass 0. The exit code reflects the build outcome only — if the wait elapses with the build still running, the command exits 0; check status via the printed link or --json output.`,required:!1}),open:J.boolean({description:`Whether to open the browser automatically to the Actor details page.`,default:!1,required:!1}),force:J.boolean({char:`f`,description:`Push an Actor even when the local files are older than the Actor on the platform, or when the Actor builds from a Git repository.`,default:!1,required:!1}),dir:J.string({description:`Directory where the Actor is located.`,required:!1}),"allow-missing-secrets":J.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:X.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(){try{var t=_usingCtx();let n=p(e.cwd(),this.flags.dir??`.`),r=await getActorLocalFilePaths(n);if(!r.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=>r.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(`
109
+ 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:J.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":J.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":J.string({char:`w`,description:`In seconds, how long to wait for the build to finish. If no value passed, it waits forever. To return as soon as the build is queued (fire-and-forget), pass 0. The exit code reflects the build outcome only — if the wait elapses with the build still running, the command exits 0; check status via the printed link or --json output.`,required:!1}),open:J.boolean({description:`Whether to open the browser automatically to the Actor details page.`,default:!1,required:!1}),force:J.boolean({char:`f`,description:`Push an Actor even when the local files are older than the Actor on the platform, or when the Actor builds from a Git repository.`,default:!1,required:!1}),dir:J.string({description:`Directory where the Actor is located.`,required:!1}),"allow-missing-secrets":J.boolean({description:`Allow the command to continue even when secret values are not found in the local secrets storage.`,required:!1,default:!1}),"apply-env-vars-to-build":J.boolean({description:`Make the environment variables also available to the Actor build process. Use --no-apply-env-vars-to-build to turn the setting off. When omitted, the setting currently stored on the platform is kept.`,required:!1})};static args={actorId:X.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(){try{var t=_usingCtx();let n=p(e.cwd(),this.flags.dir??`.`),r=await getActorLocalFilePaths(n);if(!r.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=>r.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(`
110
110
  `)}),e.exitCode=4;return}let i=await getLoggedClientOrThrow(),a=await useActorConfig({cwd:n});if(a.isErr()){error({message:a.unwrapErr().message}),e.exitCode=5;return}let{config:s}=a.unwrap(),c=await getLocalUserInfo(),l=c.organizationOwnerUserId?`/organization/${c.id}`:``,f,m,h=!1,g=this.flags.version||s?.version||`0.0`,_=this.flags.buildTag||s?.buildTag;!_&&g===`0.0`&&(_=`latest`);let v=parseWaitForFinishMillis(this.flags.waitForFinish),y=this.args.actorId;if(y){if(m=await i.actor(y).get(),!m)throw Error(`Cannot find Actor with ID '${y}' in your account.`);f=m.id}else{let e=c.username||c.id;if(m=await i.actor(`${e}/${s.name}`).get(),m)f=m.id;else{let{templates:e}=await Et(),t=e.find(e=>e.name===s.template)?.defaultRunOptions||pr,n={name:s.name,title:s.title,description:s.description,defaultRunOptions:t,versions:[{versionNumber:g,buildTag:_,sourceType:pe.SOURCE_FILES,sourceFiles:[]}]};s.usesStandbyMode&&(n.actorStandby={isEnabled:!0}),m=await i.actors().create(n),f=m.id,h=!0,info({message:`Created Actor with name ${s.name} on Apify.`})}}this.telemetryData.push={actorId:f,wasCreated:h};let b=i.actor(f);info({message:`Deploying Actor '${s.name}' to Apify.`});let x=await sumFilesSizeInBytes(r,n);if(x<_e&&!h){let e=await b.get(),t=r.reduce((e,t)=>{let{mtimeMs:r,ctimeMs:i}=ne(u(n,t)),a=r>i?r:i;return e>a?e:a},0),i=e?.modifiedAt.valueOf();if(!this.flags.force&&i&&t<i&&(s?.name||y))throw Error(`Actor with identifier "${s?.name||y}" already exists on the platform and has newer changes than your local copy.
111
- Skipping push. Use --force to override.`)}let S=await b.version(g).get();if(S?.sourceType===pe.GIT_REPO&&!await confirmGitSourceSwitch({actorName:m.name,gitRepoUrl:S.gitRepoUrl,force:this.flags.force})){info({message:`Push aborted. Actor ${m.name} still builds from its Git repository.`});return}let C,w,T;if(x<_e)w=await createSourceFiles(r,n),C=pe.SOURCE_FILES;else{run({message:`Zipping Actor files`}),await createActZip(fr,r,n);let e=await i.keyValueStores().getOrCreate(`actor-${f}-source`),t=`version-${g}.zip`,a=j(fr);await i.keyValueStore(e.id).setRecord({key:t,value:a,contentType:`application/zip`}),re(fr);let s=new URL(`${i.baseUrl}/key-value-stores/${e.id}/records/${t}?disableRedirect=true`);if(e?.urlSigningSecretKey){let n=Re(e.urlSigningSecretKey,t);s.searchParams.set(`signature`,n)}T=s.toString(),C=pe.TARBALL}let E=s.environmentVariables?transformEnvToEnvVars(s.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(S){let e={tarballUrl:T,sourceFiles:w,buildTag:_,sourceType:C,envVars:E};await b.version(g).update(e),run({message:`Updated version ${g} for Actor ${m.name}.`})}else{let e={versionNumber:g,tarballUrl:T,sourceFiles:w,buildTag:_,sourceType:C,envVars:E};await b.versions().create({...e}),run({message:`Created version ${g} for Actor ${m.name}.`})}if(!h&&!!s.usesStandbyMode!=!!m.actorStandby?.isEnabled){let e=!!s.usesStandbyMode;await b.update({actorStandby:{isEnabled:e}}),info({message:`${e?`Enabled`:`Disabled`} standby mode for Actor ${m.name}.`})}run({message:`Building Actor ${m.name}`});let D=v===void 0?1/0:Date.now()+v,O=await b.build(g,{useCache:!0,waitForFinish:2});t.u(useAbortJobOnSignal({apifyClient:i,kind:`build`,jobId:O.id}));try{let e=Number.isFinite(D)?Math.max(0,D-Date.now()):void 0;await outputJobLog({job:O,timeoutMillis:e,apifyClient:i})}catch(e){warning({message:`Can not get log:`}),console.error(e)}let k=await i.build(O.id).get();if(!k){error({message:`Could not fetch build with ID "${O.id}" after deployment.`}),e.exitCode=1;return}for(O=k;!de.includes(O.status)&&Date.now()<D;)await new Promise(e=>setTimeout(e,1e3)),O=await i.build(O.id).get();if(O.status===I.SUCCEEDED&&_&&v!==0){run({message:`Applying build tag "${_}"...`});let e=Date.now()+5e3,t=!1;for(;Date.now()<e;){if((await b.get())?.taggedBuilds?.[_]?.buildId===O.id){t=!0;break}await new Promise(e=>setTimeout(e,1e3))}t||warning({message:`Build succeeded but tag "${_}" was not set after 5 seconds; subsequent calls referencing this tag may not find it.`})}let A=O.status,M=resolvePushOutcome(A),ee=`${getConsoleUrl()}${l}/actors/${O.actId}`,te=`${ee}#/builds/${O.buildNumber}`,N=[];if(M.errorMessage)try{let e=await i.log(O.id).get();e&&(N=e.split(`
112
- `).map(e=>e.trimEnd()).filter(e=>e.length>0).slice(-10))}catch{}M.exitCode&&(e.exitCode=M.exitCode);let P={ok:M.ok,operation:`push`,actor:{id:O.actId,url:ee},build:{id:O.id,number:O.buildNumber,status:A,url:te}};if(M.exitCode!==void 0&&(P.exitCode=M.exitCode),M.errorMessage&&(P.error={phase:`build`,message:M.errorMessage,logTail:N}),this.flags.json){printJsonToStdout(P);return}simpleLog({stdout:!0,message:[`Apify push result: ${M.resultLabel}`,``,`Upload: SUCCEEDED`,`Build: ${A}`,`Actor ID: ${O.actId}`,`Build ID: ${O.id}`,`Build number: ${O.buildNumber}`,...M.exitCode?[`Exit code: ${M.exitCode}`]:[],``,`Actor URL: ${ee}`,`Build URL: ${te}`,...M.errorMessage&&N.length?[``,`Reason:`,...N]:[]].join(`
113
- `)}),this.flags.open&&await Tt(ee)}catch(e){t.e=e}finally{t.d()}}},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:X.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 Y({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 mr={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?mr[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.
111
+ Skipping push. Use --force to override.`)}let S=await b.version(g).get();if(S?.sourceType===pe.GIT_REPO&&!await confirmGitSourceSwitch({actorName:m.name,gitRepoUrl:S.gitRepoUrl,force:this.flags.force})){info({message:`Push aborted. Actor ${m.name} still builds from its Git repository.`});return}let C,w,T;if(x<_e)w=await createSourceFiles(r,n),C=pe.SOURCE_FILES;else{run({message:`Zipping Actor files`}),await createActZip(fr,r,n);let e=await i.keyValueStores().getOrCreate(`actor-${f}-source`),t=`version-${g}.zip`,a=A(fr);await i.keyValueStore(e.id).setRecord({key:t,value:a,contentType:`application/zip`}),re(fr);let s=new URL(`${i.baseUrl}/key-value-stores/${e.id}/records/${t}?disableRedirect=true`);if(e?.urlSigningSecretKey){let n=Re(e.urlSigningSecretKey,t);s.searchParams.set(`signature`,n)}T=s.toString(),C=pe.TARBALL}let E=s.environmentVariables?transformEnvToEnvVars(s.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0,{applyEnvVarsToBuild:D}=this.flags;if(S){let e={tarballUrl:T,sourceFiles:w,buildTag:_,sourceType:C,envVars:E,applyEnvVarsToBuild:D};await b.version(g).update(e),run({message:`Updated version ${g} for Actor ${m.name}.`})}else{let e={versionNumber:g,tarballUrl:T,sourceFiles:w,buildTag:_,sourceType:C,envVars:E,applyEnvVarsToBuild:D};await b.versions().create({...e}),run({message:`Created version ${g} for Actor ${m.name}.`})}if(!h&&!!s.usesStandbyMode!=!!m.actorStandby?.isEnabled){let e=!!s.usesStandbyMode;await b.update({actorStandby:{isEnabled:e}}),info({message:`${e?`Enabled`:`Disabled`} standby mode for Actor ${m.name}.`})}run({message:`Building Actor ${m.name}`});let ee=v===void 0?1/0:Date.now()+v,O=await b.build(g,{useCache:!0,waitForFinish:2});t.u(useAbortJobOnSignal({apifyClient:i,kind:`build`,jobId:O.id}));try{let e=Number.isFinite(ee)?Math.max(0,ee-Date.now()):void 0;await outputJobLog({job:O,timeoutMillis:e,apifyClient:i})}catch(e){warning({message:`Can not get log:`}),console.error(e)}let k=await i.build(O.id).get();if(!k){error({message:`Could not fetch build with ID "${O.id}" after deployment.`}),e.exitCode=1;return}for(O=k;!de.includes(O.status)&&Date.now()<ee;)await new Promise(e=>setTimeout(e,1e3)),O=await i.build(O.id).get();if(O.status===I.SUCCEEDED&&_&&v!==0){run({message:`Applying build tag "${_}"...`});let e=Date.now()+5e3,t=!1;for(;Date.now()<e;){if((await b.get())?.taggedBuilds?.[_]?.buildId===O.id){t=!0;break}await new Promise(e=>setTimeout(e,1e3))}t||warning({message:`Build succeeded but tag "${_}" was not set after 5 seconds; subsequent calls referencing this tag may not find it.`})}let te=O.status,j=resolvePushOutcome(te),M=`${getConsoleUrl()}${l}/actors/${O.actId}`,N=`${M}#/builds/${O.buildNumber}`,P=[];if(j.errorMessage)try{let e=await i.log(O.id).get();e&&(P=e.split(`
112
+ `).map(e=>e.trimEnd()).filter(e=>e.length>0).slice(-10))}catch{}j.exitCode&&(e.exitCode=j.exitCode);let ie={ok:j.ok,operation:`push`,actor:{id:O.actId,url:M},build:{id:O.id,number:O.buildNumber,status:te,url:N}};if(j.exitCode!==void 0&&(ie.exitCode=j.exitCode),j.errorMessage&&(ie.error={phase:`build`,message:j.errorMessage,logTail:P}),this.flags.json){printJsonToStdout(ie);return}simpleLog({stdout:!0,message:[`Apify push result: ${j.resultLabel}`,``,`Upload: SUCCEEDED`,`Build: ${te}`,`Actor ID: ${O.actId}`,`Build ID: ${O.id}`,`Build number: ${O.buildNumber}`,...j.exitCode?[`Exit code: ${j.exitCode}`]:[],``,`Actor URL: ${M}`,`Build URL: ${N}`,...j.errorMessage&&P.length?[``,`Reason:`,...P]:[]].join(`
113
+ `)}),this.flags.open&&await Tt(M)}catch(e){t.e=e}finally{t.d()}}},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:X.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 Y({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 mr={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?mr[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.
114
114
 
115
115
  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:X.string({description:`Search query to find Actors by title, name, description, username, or readme.`,required:!1})};static flags={"sort-by":J.string({description:`Sort order for the results.`,choices:[`relevance`,`popularity`,`newest`,`lastUpdate`],default:`relevance`}),category:J.string({description:`Filter by category (e.g. AI).`}),username:J.string({description:`Filter by Actor author username.`}),"pricing-model":J.string({description:`Filter by pricing model.`,choices:[`FREE`,`FLAT_PRICE_PER_MONTH`,`PRICE_PER_DATASET_ITEM`,`PAY_PER_EVENT`]}),limit:J.integer({description:`Maximum number of results to return.`,default:20}),offset:J.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=await getApifyClientOptions();delete u.token;let f=new Je(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 Z({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.
116
116
  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:J.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":J.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:X.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,{id:c,userFriendlyId:l,actorData:u}=await nr.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={};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=runActorOrTaskOnCloud(i,{actorOrTaskData:{id:c,userFriendlyId:l},runOptions:f,type:`Actor`,inputOverride:p?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),h;for await(let e of m)h=e;if(!h){simpleLog({message:`Actor run did not start.`,stdout:!1}),e.exitCode=1;return}let g=consoleRunUrl(c,h.id);if(this.flags.json){printJsonToStdout({ok:!0,operation:`actors.start`,waited:!1,actor:{id:c,url:`${getConsoleUrl()}/actors/${c}`},run:{id:h.id,status:h.status,url:g},next:{wait:`apify runs wait ${h.id} --json`,log:`apify runs log ${h.id}`,info:`apify runs info ${h.id} --json`},exitCode:0});return}simpleLog({message:[t.greenBright(`Run started.`),``,`${t.yellow(`Actor`)}: ${u.name} (${t.gray(c)})`,`${t.yellow(`Run ID`)}: ${h.id}`,`${t.yellow(`Status`)}: ${h.status}`,``,t.gray(`This command does not wait for the run to finish.`),``,`To wait for the final status:`,` apify runs wait ${h.id} --json`,``,`To stream or inspect logs:`,` apify runs log ${h.id}`,``,`To inspect run metadata:`,` apify runs info ${h.id} --json`].join(`
@@ -126,13 +126,13 @@ Run 'apify logout' to remove authentication.`;static group=`Authentication`;stat
126
126
  `),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:J.string({char:`b`,description:`The build ID to remove the tag from.`,required:!0}),tag:J.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 Y({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 Sr=stdinCheckWrapper(async({message:e,expectedValue:t,failureMessage:n})=>await Ie({message:e,validate(e){return e===t?!0:n??`That is not the correct input!`}},hn));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:X.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 Sr({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 Y({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})}},BuildsWaitCommand=class extends ApifyCommand{static name=`wait`;static description=`Waits for an Actor build to reach a terminal status (SUCCEEDED, FAILED, ABORTED, TIMED-OUT).
127
127
  Returns exit code 0 only when the build SUCCEEDED. Designed for CI and agentic workflows.`;static examples=[{description:`Wait for a build to finish and return a non-zero exit code on failure.`,command:`apify builds wait <buildId>`},{description:`Wait for a build and emit a structured JSON result.`,command:`apify builds wait <buildId> --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-wait`;static enableJsonFlag=!0;static args={buildId:X.string({required:!0,description:`The build ID to wait for.`})};static flags={timeout:J.integer({char:`t`,description:`In seconds, how long to wait before giving up. If skipped, it waits indefinitely.`,required:!1}),"poll-interval":J.integer({description:`In seconds, how often to poll the platform. Defaults to 2.`,required:!1})};async run(){let{buildId:t}=this.args,{timeout:n,pollInterval:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),{job:s,timedOutWaiting:c}=await waitForTerminalStatus({apifyClient:a,jobId:t,kind:`build`,maxWaitMillis:n?n*1e3:void 0,pollIntervalMillis:r?r*1e3:void 0}),l=s,u=consoleBuildUrl(l.actId,l.buildNumber),f=l.status===`SUCCEEDED`,p=exitCodeForWaitResult({job:s,timedOutWaiting:c},`build`),m=`Gave up waiting after ${n}s; build is still ${l.status}`,h=[];if(f||(h=await fetchLogTail(a,l.id)),i){printJsonToStdout({ok:f,operation:`builds.wait`,timedOutWaiting:c,build:{id:l.id,status:l.status,number:l.buildNumber,url:u},...f?{}:{error:{phase:`build`,message:c?m:`Actor build did not succeed`,logTail:h}},exitCode:p}),e.exitCode=p;return}let g=[{label:`Build`,value:l.status},{label:`Build ID`,value:l.id},{label:`Build number`,value:l.buildNumber},{label:`Actor ID`,value:l.actId}],_=[{label:`Build URL`,url:u}];simpleLog({message:formatResultSummary({resultLabel:`Apify build result`,overallStatus:l.status,lines:g,links:_,errorReason:f?void 0:h}),stdout:!0}),c?error({message:`${m}.`}):f||error({message:`Build ended with status ${l.status}.`}),e.exitCode=p}},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,BuildsWaitCommand];async run(){this.printHelp()}},TopLevelCallCommand=class extends nr{static name=`call`};const pathToInstallMarker=e=>u(e,`.install-marker`);var InstallCommand=class extends ApifyCommand{static name=`install`;static description=`Finalizes the first-time setup of Apify and Actor CLI.`;static hidden=!0;static flags={"shims-only":J.boolean({description:`Only (re)create the apify/actor wrapper scripts next to the bundle, then exit. Used by the install/upgrade scripts.`,hidden:!0,default:!1})};async run(){let{installMethod:n,installPath:r,version:i}=useCLIMetadata();if(n!==`bundle`){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}if(Nt(r,`When CLI is installed via bundles, the install path must be set`),writeEntrypointShims(r,e.platform===`win32`),cliDebugPrint(`[install] wrote entrypoint shims to`,r),this.flags.shimsOnly)return;let a=pathToInstallMarker(r);if(D(a)){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}if(e.platform!==`win32`){await this.symlinkToLocalBin(r);try{await this.promptAddToShell()}catch(e){error({message:e.message||`Failed to automatically handle shell integration`})}simpleLog({message:``})}await V(a,i),cliDebugPrint(`[install] install marker written to`,a),simpleLog({message:[``,t.green(`Apify and Actor CLI were installed successfully!`),``,t.gray(` Version: ${t.green(i)}`),t.gray(` Location: ${t.bold.white(tildify(u(r,`apify`)))} and ${t.bold.white(tildify(u(r,`actor`)))}`)].join(`
128
128
  `)}),simpleLog({message:``}),success({message:`To get started, run:`}),simpleLog({message:t.white.bold(` apify --help
129
- actor --help`)})}async symlinkToLocalBin(e){let n=userHomeDir();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=u(n,`.local`,`bin`);await R(r,{recursive:!0});for(let n of[`apify`,`actor`,`apify-cli`]){let i=u(e,n);if(!D(i)){cliDebugPrint(`[install] file not found for symlinking`,n,i),warning({message:t.gray(`Bundle not found for symlinking: ${n}`)});continue}let a=u(r,n);await Pe(a).catch(()=>{}),await Ne(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(n){let r,i,a=`${t.green(`?`)} ${t.bold(n)} ${t.dim(`(Y/n)`)} `,writeDone=r=>{e.stdout.write(`\r\x1b[2K${t.green(`?`)} ${t.bold(n)} ${t.cyan(r)}\n`)};try{return cliDebugPrint(`[install] opening /dev/tty for raw mode`),r=A(`/dev/tty`,`r`),i=new Pt(r),e.stdout.write(a),i.setRawMode(!0),i.resume(),await new Promise(t=>{let onData=n=>{let r=n.toString();r===`y`||r===`Y`||r===`\r`||r===`
129
+ actor --help`)})}async symlinkToLocalBin(e){let n=userHomeDir();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=u(n,`.local`,`bin`);await R(r,{recursive:!0});for(let n of[`apify`,`actor`,`apify-cli`]){let i=u(e,n);if(!D(i)){cliDebugPrint(`[install] file not found for symlinking`,n,i),warning({message:t.gray(`Bundle not found for symlinking: ${n}`)});continue}let a=u(r,n);await Pe(a).catch(()=>{}),await Ne(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(n){let r,i,a=`${t.green(`?`)} ${t.bold(n)} ${t.dim(`(Y/n)`)} `,writeDone=r=>{e.stdout.write(`\r\x1b[2K${t.green(`?`)} ${t.bold(n)} ${t.cyan(r)}\n`)};try{return cliDebugPrint(`[install] opening /dev/tty for raw mode`),r=k(`/dev/tty`,`r`),i=new Pt(r),e.stdout.write(a),i.setRawMode(!0),i.resume(),await new Promise(t=>{let onData=n=>{let r=n.toString();r===`y`||r===`Y`||r===`\r`||r===`
130
130
  `?(i.removeListener(`data`,onData),writeDone(`Yes`),t(!0)):r===`n`||r===`N`?(i.removeListener(`data`,onData),writeDone(`No`),t(!1)):(r===``||r===``)&&(i.removeListener(`data`,onData),e.stdout.write(`
131
131
  `),t(!1))};i.on(`data`,onData)})}catch(e){return cliDebugPrint(`[install] failed to open /dev/tty for raw mode`,e),!1}finally{i&&(i.setRawMode(!1),i.pause(),i.destroy())}}async promptAddToShell(){let[n,r]=await Promise.allSettled([Le(`apify`,{nothrow:!0}),Le(`actor`,{nothrow:!0})]);if(n.status===`fulfilled`&&r.status===`fulfilled`&&n.value&&r.value){cliDebugPrint(`[install -> promptAddToShell] already in PATH`,{apifyCliPath:n,actorCliPath:r}),info({message:t.gray(`Apify and Actor CLIs are already in PATH, skipping shell integration`)});return}let i=userHomeDir();cliDebugPrint(`[install -> promptAddToShell] user home directory`,i);let a=e.env.APIFY_CLI_INSTALL??u(i,`.apify`),s=e.env.FINAL_BIN_DIR??u(a,`bin`),l=e.env.PROVIDED_INSTALL_DIR??a;if(!l){warning({message:t.gray(`Install directory not found, cannot add to shell`)});return}let f=e.env.FINAL_BIN_DIR??s;simpleLog({message:``});let p=`Should the CLI handle adding itself to your shell automatically?`,m;e.env.APIFY_OPEN_TTY?m=await this.confirmFromTty(p):(cliDebugPrint(`[install] opening /dev/tty for raw mode not requested, falling back to normal flow`),m=await Y({message:p,providedConfirmFromStdin:!1}));let h=detectShell(),g=shellConfigFile(i,h),_=`"${l.replaceAll(`"`,`\\"`)}"`,v=[],y=!0;switch(h){case`bash`:case`zsh`:v.push(`export APIFY_CLI_INSTALL=${_}`),v.push(`export PATH="$APIFY_CLI_INSTALL/bin:$PATH"`);break;case`fish`:v.push(`set --export APIFY_CLI_INSTALL ${_}`),v.push(`set --export PATH ${f} $PATH`);break;default:v.push(`export APIFY_CLI_INSTALL=${_}`),v.push(`export PATH="$APIFY_CLI_INSTALL/bin:$PATH"`),m=!1,y=!1}if(simpleLog({message:``}),m&&g){let e=`${await z(g,`utf-8`).catch(e=>{if(e.code===`ENOENT`)return``;throw Error(`Failed to read config file "${tildify(g)}". Received error code: ${e.code}; ${e.message}`)})}\n\n# apify cli\n${v.join(`
132
132
  `)}\n`;try{await R(c(g),{recursive:!0}),await V(g,e)}catch(e){throw e.code===`EACCES`?Error(`Failed to write to config file "${tildify(g)}", as the CLI does not have permission to write to it.`):Error(`Failed to write to config file "${tildify(g)}". Received error code: ${e.code}; ${e.message}`)}info({message:[t.gray(`Added "${tildify(f)}" to your PATH in ${tildify(g)}.`),t.gray(` You may need to run ${t.white.bold(`source ${tildify(g)}`)} to reload your shell.`)].join(`
133
133
  `)});return}let b=g??`your shell config file`;if(y){let e=`echo -e '${v.join(`\\n`)}' >> "${b}" && source "${b}"`;info({message:[t.gray(`The Apify & Actor CLIs are not in your PATH. Run:`),``,t.white.bold(` ${e}`)].join(`
134
134
  `)});return}info({message:[t.gray(`Manually add the following lines to ${b} or similar:`),...v.map(e=>t.white.bold(` ${e}`))].join(`
135
- `)})}};const Q=useCLIMetadata();function isInstalledOnMusl(){return Q.platform===`linux`&&D(`/etc/alpine-release`)}function isInstalledOnBaseline(){return Q.platform===`darwin`&&Q.arch===`x64`?!Be(`sysctl -a`,{encoding:`utf-8`}).includes(`AVX2`):Q.platform===`linux`&&Q.arch===`x64`?!j(`/proc/cpuinfo`,`utf-8`).includes(`avx2`):Q.platform===`windows`&&Q.arch!==`arm64`&&Be(`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`}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=>{if(!e.name.startsWith(`apify-cli-`))return!1;let[n,r,i,...c]=e.name.slice(10).replace(t,`version`).replace(`.exe`,``).split(`-`);return r===Q.platform&&i===Q.arch&&c.includes(`musl`)===a&&c.includes(`baseline`)===s});return cliDebugPrint(`useCLIVersionAssets`,`Fetched release`,{version:i.tag_name,filteredAssets:c}),{assets:c,version:i.tag_name.replace(/^v(\d+)/,`$1`)}}const Cr={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}`]},wr=`1.0.1`,Tr=`https://raw.githubusercontent.com/apify/apify-cli/refs/heads/master/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:J.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:J.string({description:`The version of the CLI to upgrade to. If not provided, the latest version will be used.`,required:!1}),"internal-automatic-call":J.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=Cr[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(`
135
+ `)})}};const Q=useCLIMetadata();function isInstalledOnMusl(){return Q.platform===`linux`&&D(`/etc/alpine-release`)}function isInstalledOnBaseline(){return Q.platform===`darwin`&&Q.arch===`x64`?!Be(`sysctl -a`,{encoding:`utf-8`}).includes(`AVX2`):Q.platform===`linux`&&Q.arch===`x64`?!A(`/proc/cpuinfo`,`utf-8`).includes(`avx2`):Q.platform===`windows`&&Q.arch!==`arm64`&&Be(`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`}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=>{if(!e.name.startsWith(`apify-cli-`))return!1;let[n,r,i,...c]=e.name.slice(10).replace(t,`version`).replace(`.exe`,``).split(`-`);return r===Q.platform&&i===Q.arch&&c.includes(`musl`)===a&&c.includes(`baseline`)===s});return cliDebugPrint(`useCLIVersionAssets`,`Fetched release`,{version:i.tag_name,filteredAssets:c}),{assets:c,version:i.tag_name.replace(/^v(\d+)/,`$1`)}}const Cr={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}`]},wr=`1.0.1`,Tr=`https://raw.githubusercontent.com/apify/apify-cli/refs/heads/master/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:J.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:J.string({description:`The version of the CLI to upgrade to. If not provided, the latest version will be used.`,required:!1}),"internal-automatic-call":J.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=Cr[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(`
136
136
  `)})}async handleInstallSpecificVersion(t){if(t!==`latest`&&!y(t,wr)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${wr}.`});return}let n=await useCLIVersionAssets(t);if(!n){error({message:`The provided version does not exist. Please check the version number and try again.`});return}let{assets:r,version:i}=n;if(!y(i,wr)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${wr}.`});return}let a=useCLIMetadata();if(a.installMethod===`bundle`){if(!r.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: ${i}`,`- The system you are running on: ${a.platform} ${a.arch}`].join(`
137
137
  `)});return}let t=c(e.execPath);cliDebugPrint(`[upgrade] bundleDirectory`,t);let n=await Ae(t);if(!n.some(e=>e.startsWith(`apify`)||e.startsWith(`actor`))){cliDebugPrint(`[upgrade] directoryEntries`,n),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: ${i}`,`- The system you are running on: ${a.platform} ${a.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${t}`].join(`
138
138
  `)});return}if(a.platform===`windows`)return this.startUpgradeProcess(t,i,r);await this.handleUnixUpgrade(t,i,r),this.successMessage(i);return}let s=Cr[a.installMethod](t,this.entrypoint);if(e.env.APIFY_CLI_DEBUG){info({message:`Would run command: ${s.join(` `)}`});return}try{await execWithLog({cmd:s[0],args:s.slice(1)}),this.successMessage(i)}catch{error({message:`Failed to upgrade the CLI. Please run the following command manually: ${s.join(` `)}`})}}successMessage(e){success({message:`Successfully upgraded to ${e} 👍`})}async startUpgradeProcess(t,n,r){await this.upsertUpgradeScript(t);let i=[`-ExecutionPolicy`,`Bypass`,`-File`,`"${u(t,`upgrade.ps1`)}"`,`-ProcessId`,e.pid.toString(),`-InstallLocation`,`"${t}"`,`-Version`,`"${n}"`],a=r.map(e=>e.browser_download_url).join(`,`);i.push(`-AllUrls`,`"${a}"`),cliDebugPrint(`[upgrade] starting upgrade process with args`,i),info({message:`Starting upgrade process...`});let s=Ve(`powershell.exe`,i,{detached:!0,shell:!0,stdio:`inherit`,windowsHide:!1,windowsVerbatimArguments:!0});s.on(`spawn`,()=>{cliDebugPrint(`[upgrade] upgrade process spawned`),s.unref(),e.exit(0)}),s.on(`error`,e=>{error({message:`Failed to start the upgrade process: ${e.message}`})})}async upsertUpgradeScript(t){let n=u(t,`upgrade.ps1`);if(D(n))return;let r=useCLIMetadata(),i=await fetch(Tr,{headers:{"User-Agent":mn}});i.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: ${r.platform} ${r.arch}`,`- The URL of the asset that failed to fetch: ${Tr}`,`- The status code of the response: ${i.status}`].join(`
@@ -145,18 +145,18 @@ Returns exit code 0 only when the build SUCCEEDED. Designed for CI and agentic w
145
145
 
146
146
  💡 Tip: Use 'apify push' to deploy your Actor to the Apify platform`,i&&(c+=`\n🌱 Git repository initialized in '${t}'. You can now commit and push your Actor to Git.`)),c+=`
147
147
  📖 Docs: https://docs.apify.com/platform/actors/development`,r&&(c+=`\n\n${r}`),c}async function executePrompts(e,t){return promptTemplate(e,t.useCase?useCaseFlagToTag(t.useCase)??`any-use-case`:await promptUseCase(),t.language?languageFlagToTag(t.language)??t.language:await promptLanguage())}async function promptActorName(){return await vn({message:`Name of your new Actor:`,validate:e=>{try{validateActorName(e)}catch(e){return e.message}return!0}})}async function promptUseCase(){let e=[...jr.map(e=>({name:e.label,value:e.templateTag})),new st,{name:`Any use case`,value:Or}];return xr({message:`What do you want to build?`,choices:e,default:jr[0].templateTag,loop:!1})}async function promptLanguage(){let e=[...Mr.map(e=>({name:e.label,value:e.templateTag})),new st,{name:`Any language`,value:Dr}];return xr({message:`Choose the programming language of your new Actor:`,choices:e,default:Mr[0].templateTag,loop:!1})}async function promptTemplate(e,t,n){let{rows:r,separatorIndex:i,noExactMatchHint:a}=buildTemplateChoiceList(getTemplateRecommendation(e.templates,t,n),t,n);if(r.length===0)throw Error(`No Actor templates are available right now. Please try again later.`);let s=[];return r.forEach((e,t)=>{t===i&&s.push(new st(`── The templates below don't exactly match your selection ──`)),s.push({name:e.label,value:e.template})}),a&&info({message:a,stdout:!1}),xr({message:`Choose a template for your new Actor. More info at https://apify.com/templates`,choices:s,default:r[0].template,loop:!1,pageSize:8})}const Fr=3e5,connectViaConsole=async(e,t,{abortSignal:n,account:r}={})=>{let i=getConsoleUrl(),a=ze(),s,c=new Promise(e=>{s=e}),l=createLocalApiServer({corsOrigin:new URL(i).origin,authToken:a,routes:{"POST /api/v1/git-provider-connected":(e,t)=>{t.end(),cliDebugPrint(`git-source`,`connected`,e),s({connected:!0})},"POST /api/v1/exit":(e,n)=>{n.end(),s({stopReason:`connectCancelled`,message:e.isWindowClosed?`Connecting your ${t} account stopped: the Apify Console window was closed.`:`Connecting your ${t} account was canceled in Apify Console.`})}}}),u=setTimeout(()=>s({stopReason:`connectTimedOut`,message:`Connecting your ${t} account did not finish within ${Fr/6e4} minutes.`}),Fr);n?.addEventListener(`abort`,()=>s({abandoned:!0}),{once:!0}),l.listen(0);let{port:f}=l.address(),p=new URL(getConsoleIntegrationsUrl(r));p.searchParams.set(`localCliCommand`,`connect-git-provider`),p.searchParams.set(`gitProvider`,e),p.searchParams.set(`localCliPort`,`${f}`),p.searchParams.set(`localCliToken`,a),p.searchParams.set(`localCliApiVersion`,`v1`);try{p.searchParams.set(`localCliComputerName`,encodeURIComponent(kt()))}catch{}info({message:`Connect your ${t} account to Apify: ${p.href}`}),Tt(p.href).catch(()=>void 0),info({message:`Waiting for the connection to complete in your browser...`});try{return await c}finally{clearTimeout(u),l.closeAllConnections(),l.close()}},Ir=[`apify`,`github`,`gitlab`,`bitbucket`],Lr={github:{label:`GitHub`,authorize:{endpoint:`https://github.com/login/oauth/authorize`,defaultClientId:`Iv1.e39b3ed87e74885f`,clientIdEnvVar:`APIFY_GITHUB_APP_CLIENT_ID`,defaultAppName:`apify`,appNameEnvVar:`APIFY_GITHUB_APP_NAME`,appInstallUrl:`https://github.com/apps/{app}/installations/new`,redirectPath:`/actors/new/git/connected?service=github`}},gitlab:{label:`GitLab`},bitbucket:{label:`Bitbucket`}},isGitProvider=e=>Object.hasOwn(Lr,e),toGitAccount=({id:e,username:t,organizationOwnerUserId:n})=>({id:e,username:t,organizationOwnerUserId:n}),getGitConnectUrl=(t,n)=>{let{authorize:r}=Lr[t];if(!r)return getConsoleIntegrationsUrl(n);let i=new URL(r.redirectPath,getConsoleUrl()),a=getConsoleRoutePrefix(n);a&&i.searchParams.set(`routePrefix`,encodeURIComponent(a));let s=new URL(r.endpoint);return s.searchParams.set(`client_id`,e.env[r.clientIdEnvVar]||r.defaultClientId),s.searchParams.set(`redirect_uri`,i.href),s.href},getAddWorkspaceUrl=(t,n)=>{let{authorize:r}=Lr[t];return r?r.appInstallUrl.replace(`{app}`,e.env[r.appNameEnvVar]||r.defaultAppName):getConsoleIntegrationsUrl(n)},promptGitSource=async()=>xr({message:`Where will the source code live?`,choices:[{name:`Apify`,value:`apify`,description:`Deploy with "apify push". No Git provider involved.`},...Ir.filter(isGitProvider).map(e=>({name:Lr[e].label,value:e,description:`Apify creates a private repository on ${Lr[e].label} and builds the Actor from it.`}))],default:`apify`,loop:!1}),parseGitRepoFlag=(e,t)=>{if(!e)return{workspace:void 0,repoName:t};let n=e.lastIndexOf(`/`);if(n===-1)return{workspace:void 0,repoName:e};let r=e.slice(0,n),i=e.slice(n+1);if(!r||!i)throw Error(`Invalid --git-repo "${e}". Use "workspace/name" or just "name".`);return{workspace:r,repoName:i}},apiUrl=({client:e},t)=>`${e.baseUrl}/${t}`,authHeader=({client:e})=>({Authorization:`Bearer ${e.token}`}),fetchGitIntegrations=async e=>{let t=apiUrl(e,`integrations/git`);cliDebugPrint(`git-source`,`GET`,t);let n=await fetch(t,{headers:authHeader(e)}),r=await n.text();if(cliDebugPrint(`git-source`,`GET`,t,`->`,n.status,r.slice(0,400)),!n.ok)throw Error(`Could not read your Git integrations (${n.status} ${n.statusText}).`);return(()=>{try{return JSON.parse(r)}catch{return null}})()?.data??[]},readProviderState=(e,t)=>{let n=e.filter(e=>e.provider===t);return{connected:n.length>0,workspaces:n.flatMap(e=>e.workspaces.map(t=>({...t,providerId:e.id}))),addWorkspaceUrl:n.find(({addWorkspaceUrl:e})=>e)?.addWorkspaceUrl}},Rr=2e3,zr=18e4,pollForWorkspaces=async(e,{timeoutMs:t,abortSignal:n,onState:r})=>{let i=Date.now()+t,a=Rr,s=null;for(;Date.now()<i;){try{await Ft(a,void 0,{signal:n})}catch{return s}a=Math.min(Math.round(a*1.5),1e4);try{s=await e()}catch(e){cliDebugPrint(`git-source`,`poll failed:`,e);continue}if(s.workspaces.length)return s;await r?.(s)}return s},ensureUsableIntegration=async(e,{client:t,isInteractive:n,account:r})=>{let load=async()=>readProviderState(await fetchGitIntegrations({client:t}),e),i=await load();if(cliDebugPrint(`git-source`,`integrations:`,e,i.connected,`workspaces=${i.workspaces.length}`),i.workspaces.length||!n)return i;let{label:a,authorize:s}=Lr[e];if(!i.connected&&!s){let t=new AbortController,n=Date.now(),s=connectViaConsole(e,a,{abortSignal:t.signal,account:r}),c;try{c=await Promise.race([s.then(()=>null),pollForWorkspaces(load,{timeoutMs:Fr,abortSignal:t.signal})])}finally{t.abort()}if(c?.workspaces.length)return c;let l=await s;if(`stopReason`in l)return warning({message:l.message}),i;if(i=await load(),i.workspaces.length)return i;let u=Math.min(zr,Fr-(Date.now()-n));return u<Rr?i:(info({message:`Waiting for Apify to finish connecting your ${a} account...`}),await pollForWorkspaces(load,{timeoutMs:u})??i)}let c=null,offer=async t=>{let n=t.connected?t.addWorkspaceUrl??getAddWorkspaceUrl(e,r):getGitConnectUrl(e,r);n!==c&&(c=n,info({message:`${t.connected?`Give Apify access to a ${a} account`:`Connect your ${a} account to Apify`}: ${n}`}),await Tt(n).catch(()=>void 0),info({message:r?.username?`Waiting for authorization to complete in your browser. It connects ${a} to the Apify account ${r.username}.`:`Waiting for authorization to complete in your browser...`}))};return await offer(i),await pollForWorkspaces(load,{timeoutMs:zr,onState:offer})??i},chooseWorkspace=async(e,t,n)=>{if(t){let n=t.toLowerCase(),r=e.find(({id:e,label:t})=>e.toLowerCase()===n||t.toLowerCase()===n);return r?{workspace:r}:{stopReason:`unknownWorkspace`}}return e.length===1?{workspace:e[0]}:n?{workspace:await xr({message:`Which account should own the repository?`,choices:e.map(e=>({name:e.label,value:e})),loop:!1})}:{stopReason:`ambiguousWorkspace`}};var CreateRemoteRepoError=class extends Error{stopReason;constructor(e,t){super(e),this.stopReason=t,this.name=`CreateRemoteRepoError`}};const Br=new Set([`integration-auth-error`,`invalid-git-auth-token`]),withoutUserInfo=e=>{if(!URL.canParse(e))return e;let t=new URL(e);return t.username=``,t.password=``,t.href},createRemoteRepo=async e=>{let{providerId:t,workspace:n,repoName:r,isPrivate:i,templateArchiveUrl:a}=e,s=apiUrl(e,`integrations/git/${t}/create-repo`),c=JSON.stringify({workspace:n,repoName:r,isPrivate:i,templateArchiveUrl:a});cliDebugPrint(`git-source`,`POST`,s,c);let l=await fetch(s,{method:`POST`,headers:{...authHeader(e),"Content-Type":`application/json`},body:c}),u=await l.text();cliDebugPrint(`git-source`,`POST`,s,`->`,l.status,u.slice(0,400));let f=(()=>{try{return JSON.parse(u)}catch{return null}})();if(l.ok&&f?.data)return{...f.data,httpsUrl:withoutUserInfo(f.data.httpsUrl)};let p=f?.error?.type,m=f?.error?.message||`${l.status} ${l.statusText}`;throw p&&Br.has(p)?new CreateRemoteRepoError(m,`notAuthorized`):p===`invalid-parameter`?new CreateRemoteRepoError(m,`repoNameRejected`):new CreateRemoteRepoError(m,`repoCreateFailed`)},cloneRepo=async(e,t,n)=>{await De(`git`,[`clone`,t,e],{env:n?void 0:{GIT_TERMINAL_PROMPT:`0`,GIT_SSH_COMMAND:`ssh -o BatchMode=yes`}})},createGitActor=async({client:e,actorName:t,gitRepoUrl:n})=>e.actors().create({name:t,versions:[{versionNumber:`0.0`,sourceType:pe.GIT_REPO,gitRepoUrl:n}]}),registerDeploymentKey=async({client:e,providerId:t,actorId:n,repoUrl:r})=>{let i=apiUrl({client:e},`integrations/git/${t}/register-deployment-key`),a=JSON.stringify({actorId:n,repoName:r});cliDebugPrint(`git-source`,`POST`,i,a);let s=await fetch(i,{method:`POST`,headers:{...authHeader({client:e}),"Content-Type":`application/json`},body:a}),c=await s.text();if(cliDebugPrint(`git-source`,`POST`,i,`->`,s.status,c.slice(0,400)),s.ok)return;let l=(()=>{try{return JSON.parse(c).error?.message}catch{return null}})();throw Error(l||`${s.status} ${s.statusText}`)},enableAutomaticBuilds=async({client:e,providerId:t,actorId:n})=>{let r=apiUrl({client:e},`actors/${n}/versions/0.0/build-on-push`),i=JSON.stringify({providerId:t,enabled:!0});cliDebugPrint(`git-source`,`PUT`,r,i);let a=await fetch(r,{method:`PUT`,headers:{...authHeader({client:e}),"Content-Type":`application/json`},body:i}),s=await a.text();if(cliDebugPrint(`git-source`,`PUT`,r,`->`,a.status,s.slice(0,400)),a.ok)return;let c=(()=>{try{return JSON.parse(s).error?.message}catch{return null}})();throw Error(c||`${a.status} ${a.statusText}`)},runGitSourceFlow=async({client:e,provider:t,actorDir:n,actorName:r,workspace:i,repoName:a,isPrivate:s,templateArchiveUrl:c,isInteractive:l,account:u,autoBuild:f,customize:p})=>{let m=!1,stopped=(e,t,n={})=>({remoteUrl:null,httpsUrl:null,actorId:null,workspaces:null,scaffolded:m,automaticBuilds:`off`,...n,stopReason:e,error:t instanceof Error?t.message:String(t)}),h;try{h=await ensureUsableIntegration(t,{client:e,isInteractive:l,account:u})}catch(e){return stopped(`lookupFailed`,e)}let{label:g}=Lr[t],_=u?.username?`The Apify account ${u.username}`:`Apify`;if(!h.connected)return stopped(`notAuthorized`,Error(`${_} is not authorized to access your ${g} account.`));if(!h.workspaces.length)return stopped(`noWorkspace`,Error(`${_} has no ${g} account to create the repository in.`));let v=h.workspaces.map(({label:e})=>e),y=v.join(`, `),b=await chooseWorkspace(h.workspaces,i,l);if(`stopReason`in b)return stopped(b.stopReason,Error(b.stopReason===`unknownWorkspace`?`"${i}" is not one of your connected accounts (${y}).`:`Several accounts are connected (${y}); pick one with --git-repo <account>/<name>.`),{workspaces:v});let{workspace:x}=b,S;for(;;)try{info({message:`Creating ${s?`private`:`public`} repository ${x.label}/${a} from the template...`}),S=await createRemoteRepo({client:e,providerId:x.providerId,workspace:x.id,repoName:a,isPrivate:s,templateArchiveUrl:c});break}catch(e){if(e instanceof CreateRemoteRepoError&&e.stopReason===`repoNameRejected`&&l){warning({message:e.message}),a=await vn({message:`Choose a different repository name:`,validate:e=>e.trim().length>0||`Enter a repository name.`});continue}return stopped(e instanceof CreateRemoteRepoError?e.stopReason:`repoCreateFailed`,e,{workspaces:v})}let C=null;try{info({message:`Cloning ${S.httpsUrl}...`}),await cloneRepo(n,S.httpsUrl,l),m=!0,await p(n)}catch(e){let t=e.stderr?.trim();C=t?Error(t):e}let w;try{let t=await createGitActor({client:e,actorName:r,gitRepoUrl:S.sshUrl});info({message:`Created Actor ${t.name} on Apify.`}),w=t.id}catch(e){return stopped(`actorCreateFailed`,e,{workspaces:v,remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl})}try{await registerDeploymentKey({client:e,providerId:x.providerId,actorId:w,repoUrl:S.htmlUrl})}catch(e){return stopped(`deploymentKeyFailed`,e,{workspaces:v,remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl,actorId:w})}let T=`off`;if(f)try{await enableAutomaticBuilds({client:e,providerId:x.providerId,actorId:w}),T=`on`,info({message:`Turned on automatic builds.`})}catch(e){T=`failed`,warning({message:`Automatic builds stay off: ${e instanceof Error?e.message:String(e)}`})}else info({message:`Automatic builds stay off, so a push does not rebuild the Actor.`});return C?stopped(`gitSetupFailed`,C,{workspaces:v,remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl,actorId:w,automaticBuilds:T}):{remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl,actorId:w,workspaces:v,stopReason:null,error:null,scaffolded:!0,automaticBuilds:T}},getGitStopUrl=(e,t,n)=>t===`notAuthorized`?getGitConnectUrl(e,n):t===`noWorkspace`?getAddWorkspaceUrl(e,n):null,buildGitSourceNextSteps=({actorName:e,stopReason:t,provider:n,remoteUrl:r,httpsUrl:i,repoName:a,scaffolded:s,actorId:c,account:l})=>{let u=`cd "${e}"`;switch(t){case`lookupFailed`:return[`Re-run with APIFY_CLI_DEBUG=1 to see the failing request`];case`notAuthorized`:return[`Connect your ${Lr[n].label} account to Apify: ${getGitConnectUrl(n,l)}`,`then re-run apify create`];case`noWorkspace`:return[`Give Apify access to a ${Lr[n].label} account: ${getAddWorkspaceUrl(n,l)}`,`then re-run apify create`];case`unknownWorkspace`:case`ambiguousWorkspace`:return[`Re-run naming the account: --git-repo <account>/${a}`];case`repoNameRejected`:return[`Re-run with a different repository name: --git-repo <account>/<other-name>`,`The name has to be free, and to use only letters, numbers, hyphens and underscores`];case`repoCreateFailed`:return[`Re-run apify create to try again`];case`gitSetupFailed`:return s?[u,`Apply the local configuration by hand: the error above says what failed`]:[`git clone ${i} "${e}"`,`Or clone over SSH, if you have a key for the provider: git clone ${r} "${e}"`,u];case`actorCreateFailed`:return[u,`Create an Actor from ${r} in Apify Console`];case`deploymentKeyFailed`:return[...s?[u]:[`git clone ${i} "${e}"`,u],`Add the Apify deploy key in the Actor's Source settings before building: ${getConsoleUrl()}/actors/${c}`]}},logGitSourceOutcome=(e,t)=>{e.stopReason&&(warning({message:`${e.scaffolded?`Actor scaffolded, but the Git setup did not finish`:e.actorId?`Actor created, but the clone failed`:`The Actor was not created: the Git setup stopped`}: ${e.error}`}),info({message:`Next steps:\n${t.map(e=>` ${e}`).join(`
148
- `)}`}))};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, then guides you through what you want to build, a language, a template, and where the source code lives when they are not provided. To run non-interactively, pass the name and --template; --source defaults to "apify". Use --use-case and --language to narrow the template list.`;static examples=[{description:`Create a new Actor project interactively (guided name, use case, language, and template prompts).`,command:`apify create`},{description:`Narrow the guided template list by use case and language.`,command:`apify create my-actor --use-case web-scraper --language python`},{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`},{description:`Host the source code on GitHub. Apify creates the repository and builds the Actor from it.`,command:`apify create my-actor --template js-crawlee-cheerio --source github`},{description:`Name the account and the repository to create, instead of being asked.`,command:`apify create my-actor --template js-crawlee-cheerio --source github --git-repo my-org/my-scraper`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-create`;static flags={template:J.string({char:`t`,description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${Dt} to find available template names.`,required:!1}),"use-case":J.string({char:`u`,description:`Filter templates by use case. Ignored when --template is provided. To see the use cases each template supports, run "apify templates ls".`,choices:Pr,required:!1}),language:J.string({char:`l`,description:`Filter templates by programming language. Ignored when --template is provided.`,choices:Nr,required:!1}),"skip-dependency-install":J.boolean({description:`Skip installing Actor dependencies.`,required:!1}),"template-archive-url":J.string({description:`Actor template archive url. Useful for developing new templates.`,required:!1,hidden:!0}),"omit-optional-deps":J.boolean({aliases:[`no-optional`],description:`Skip installing optional dependencies.`,required:!1}),"skip-git-init":J.boolean({description:`Skip initializing a git repository in the Actor directory.`,required:!1}),source:J.string({description:`Where the Actor source code will live. With a Git provider, Apify creates the repository on your connected account from the template, clones it here, and creates an Actor that builds from it.`,choices:[...Ir],required:!1}),"git-repo":J.string({description:`Repository to create, as "workspace/name" — a workspace being an account or organization you have given Apify access to. A bare value is read as the name, not the workspace. The name defaults to the Actor name, and the workspace is asked for when you have more than one. List yours with "apify api integrations/git". Only used when --source is a Git provider.`,required:!1}),"auto-build":J.string({description:`Whether a push to the repository rebuilds the Actor. On by default. Turning it on registers a push webhook on the new repository, which needs admin rights on it. Only used when --source is a Git provider.`,choices:[`on`,`off`],required:!1}),origin:J.string({description:`Where the command was invoked from. Used for funnel telemetry.`,choices:[`console`,`cli`],default:`cli`,required:!1,hidden:!0})};static args={actorName:X.string({required:!1,description:`Name of the Actor and its directory.`})};static enableJsonFlag=!0;async run(){let{actorName:t}=this.args,{template:n,useCase:r,language:i,skipDependencyInstall:a,skipGitInit:s,origin:c,json:l,gitRepo:f}=this.flags,{templateArchiveUrl:p}=this.flags,m=!1,h=!n&&!p;if(l&&(!t||h)){let e=[...t?[]:[`the Actor name as an argument`],...h?[`--template <name>`]:[]],n=h?` Run "apify templates ls" to list template names.`:``;throw Error(`--json runs non-interactively. Pass ${e.join(` and `)}.${n}`)}let g=this.flags.source,_=Et().catch(e=>Error(`Could not fetch template list from server. Cause: ${e?.message}`));t=await ensureValidActorName(t);let v=e.cwd(),x=u(v,t);for(;;){let e=await B(x).catch(()=>null),n=e&&await Ae(x).then(e=>e.length>0).catch(()=>!1);if(e?.isDirectory()&&n){let e=`Cannot create new Actor, directory '${t}' already exists. Provide a different name. To create a local Actor environment inside an existing directory, use "apify init".`;if(l)throw Error(e);error({message:e}),t=await ensureValidActorName(),x=u(v,t);continue}e||await R(x,{recursive:!0});break}let S=null,C=null;if(this.telemetryData.create={fromArchiveUrl:!!p,origin:c},!p){let e=await getTemplateDefinition(n,_,{useCase:r,language:i});({archiveUrl:p,messages:S}=e),C=e.id,this.telemetryData.create.templateId=e.id,this.telemetryData.create.templateName=e.name,this.telemetryData.create.templateLanguage=e.category,`skipOptionalDeps`in e&&(m=e.skipOptionalDeps)}this.flags.omitOptionalDeps&&(m=!0);let{isTTY:w}=await useStdin(),T=w&&!ue&&!l;g??=T?await promptGitSource():`apify`;let E=isGitProvider(g)?g:null;if(this.telemetryData.create.source=g,E&&s)throw Error(`--source ${g} clones a git repository, so --skip-git-init cannot apply.`);if(!E&&f)throw Error(`--git-repo only applies to a Git source, so add --source github|gitlab|bitbucket or drop it.`);if(!E&&this.flags.autoBuild)throw Error(`--auto-build only applies to a Git source, so add --source github|gitlab|bitbucket or drop it.`);if(E&&this.flags.templateArchiveUrl)throw Error(`--template-archive-url is not supported with --source ${g}.`);let D=E?{provider:E,client:await getLoggedClientOrThrow(),account:toGitAccount(await getLocalUserInfo()),autoBuild:this.flags.autoBuild!==`off`,...parseGitRepoFlag(f,t)}:null,applyLocalConfig=async e=>{let n=getJsonFileContent(u(e,W));await setLocalConfig(Object.assign(n||$t,{name:t}),e),await setLocalEnv(e),await createPrefilledInputFileFromInputSchema(e)};E||(await downloadAndUnzip({url:p,pathTo:x}),await applyLocalConfig(x),await enhanceReadmeWithLocalSuffix(u(x,`README.md`),_));let O=u(x,`package.json`),k=null;D&&(k=await runGitSourceFlow({provider:D.provider,actorDir:x,actorName:t,workspace:D.workspace,repoName:D.repoName,isPrivate:!0,templateArchiveUrl:p,client:D.client,isInteractive:T,account:D.account,autoBuild:D.autoBuild,customize:applyLocalConfig}));let A=!1;a||await(await useCwdProject({cwd:x})).inspectAsync(async n=>{let r=b(rn);if((n.type===1||n.type===2)&&n.packageManager===`uv`){let e=await Le(`uv`,{nothrow:!0});if(!e){warning({message:`This Actor uses uv to manage its dependencies, but the uv executable was not found. Install uv (https://docs.astral.sh/uv/getting-started/installation/), then run "uv sync" in the Actor directory.`});return}info({message:`Installing dependencies with "uv sync"...`}),await execWithLog({cmd:e,args:[`sync`],opts:{cwd:x}}),A=!0;return}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.`})}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(O,{name:t});let e=[`install`];if(m)switch(i.pmName){case`npm`:y(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`)}await execWithLog({cmd:i.pmPath,args:e,opts:{cwd:x},overrideCommand:i.pmName}),A=!0;break}case 1:case 2:{if(!isPythonVersionSupported(i.version)){warning({message:`Python Actors require Python ${sn} or higher, but you have Python ${i.version}!`}),warning({message:`Please install Python ${sn} or higher to be able to run Python Actors locally.`});return}let t=u(x,`.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:x}}),i=(await usePythonRuntime({cwd:x,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:x}}),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`-r`,`requirements.txt`],opts:{cwd:x}}),A=!0;break}}});let j={success:!0},M=await B(u(v,`.git`)).catch(()=>null),ee=await B(u(x,`.git`)).catch(()=>null),te=k!==null&&!k.scaffolded,N=!s&&!M&&!ee&&!te;if(N)try{await execWithLog({cmd:`git`,args:[`init`],opts:{cwd:x}})}catch(e){j={success:!1,error:e}}let ne=A?null:await getInstallCommandSuggestion(x),re=N&&j.success||!!ee;k?.stopReason&&(e.exitCode=1);let P=D&&k?.stopReason?buildGitSourceNextSteps({actorName:t,stopReason:k.stopReason,provider:D.provider,remoteUrl:k.remoteUrl,httpsUrl:k.httpsUrl,repoName:D.repoName,scaffolded:k.scaffolded,actorId:k.actorId,account:D.account}):buildNextSteps({actorName:t,dependenciesInstalled:A,installCommandSuggestion:ne}),ie=!k?.stopReason;l?printJsonToStdout({dir:x,actorJsonPath:u(x,W),template:C,source:g,nextSteps:P,postCreate:S?.postCreate??null,gitRepositoryInitialized:re,remote:k?.remoteUrl??null,automaticBuilds:k?.automaticBuilds??null,actorId:k?.actorId??null,stopReason:k?.stopReason??null,error:k?.error??null,gitConnectUrl:E?getGitStopUrl(E,k?.stopReason??null,D?.account):null,workspaces:k?.workspaces??null}):ie&&(simpleLog({message:``}),success({message:formatCreateSuccessMessage({actorName:t,dependenciesInstalled:A,postCreate:S?.postCreate??null,gitRepositoryInitialized:re,installCommandSuggestion:ne,gitRemote:k?.remoteUrl&&k.actorId?{remoteUrl:k.remoteUrl,actorId:k.actorId,automaticBuilds:k.automaticBuilds}:null})})),N&&!j.success&&(warning({message:`Failed to initialize git repository: ${j.error.message}`}),warning({message:`You can manually run "git init" in the Actor directory if needed.`})),k&&!l&&logGitSourceOutcome(k,P)}};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:X.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 Vr={[H.JSON]:`application/json`,[H.JSONL]:`application/jsonl`,[H.CSV]:`text/csv`,[H.HTML]:`text/html`,[H.RSS]:`application/rss+xml`,[H.XML]:`application/xml`,[H.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:J.integer({description:`The amount of elements to get from the dataset. By default, it will return all available items.`}),offset:J.integer({description:`The offset in the dataset where to start getting items.`}),format:J.string({description:`The format of the returned output. By default, it is set to 'json'.`,choices:Object.keys(Vr),default:H.JSON})};static args={datasetId:X.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:Vr[n]??`application/octet-stream`}),process.stdout.write(c),process.stdout.write(`
148
+ `)}`}))};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, then guides you through what you want to build, a language, a template, and where the source code lives when they are not provided. To run non-interactively, pass the name and --template; --source defaults to "apify". Use --use-case and --language to narrow the template list.`;static examples=[{description:`Create a new Actor project interactively (guided name, use case, language, and template prompts).`,command:`apify create`},{description:`Narrow the guided template list by use case and language.`,command:`apify create my-actor --use-case web-scraper --language python`},{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`},{description:`Host the source code on GitHub. Apify creates the repository and builds the Actor from it.`,command:`apify create my-actor --template js-crawlee-cheerio --source github`},{description:`Name the account and the repository to create, instead of being asked.`,command:`apify create my-actor --template js-crawlee-cheerio --source github --git-repo my-org/my-scraper`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-create`;static flags={template:J.string({char:`t`,description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${Dt} to find available template names.`,required:!1}),"use-case":J.string({char:`u`,description:`Filter templates by use case. Ignored when --template is provided. To see the use cases each template supports, run "apify templates ls".`,choices:Pr,required:!1}),language:J.string({char:`l`,description:`Filter templates by programming language. Ignored when --template is provided.`,choices:Nr,required:!1}),"skip-dependency-install":J.boolean({description:`Skip installing Actor dependencies.`,required:!1}),"template-archive-url":J.string({description:`Actor template archive url. Useful for developing new templates.`,required:!1,hidden:!0}),"omit-optional-deps":J.boolean({aliases:[`no-optional`],description:`Skip installing optional dependencies.`,required:!1}),"skip-git-init":J.boolean({description:`Skip initializing a git repository in the Actor directory.`,required:!1}),source:J.string({description:`Where the Actor source code will live. With a Git provider, Apify creates the repository on your connected account from the template, clones it here, and creates an Actor that builds from it.`,choices:[...Ir],required:!1}),"git-repo":J.string({description:`Repository to create, as "workspace/name" — a workspace being an account or organization you have given Apify access to. A bare value is read as the name, not the workspace. The name defaults to the Actor name, and the workspace is asked for when you have more than one. List yours with "apify api integrations/git". Only used when --source is a Git provider.`,required:!1}),"auto-build":J.string({description:`Whether a push to the repository rebuilds the Actor. On by default. Turning it on registers a push webhook on the new repository, which needs admin rights on it. Only used when --source is a Git provider.`,choices:[`on`,`off`],required:!1}),origin:J.string({description:`Where the command was invoked from. Used for funnel telemetry.`,choices:[`console`,`cli`],default:`cli`,required:!1,hidden:!0})};static args={actorName:X.string({required:!1,description:`Name of the Actor and its directory.`})};static enableJsonFlag=!0;async run(){let{actorName:t}=this.args,{template:n,useCase:r,language:i,skipDependencyInstall:a,skipGitInit:s,origin:c,json:l,gitRepo:f}=this.flags,{templateArchiveUrl:p}=this.flags,m=!1,h=!n&&!p;if(l&&(!t||h)){let e=[...t?[]:[`the Actor name as an argument`],...h?[`--template <name>`]:[]],n=h?` Run "apify templates ls" to list template names.`:``;throw Error(`--json runs non-interactively. Pass ${e.join(` and `)}.${n}`)}let g=this.flags.source,_=Et().catch(e=>Error(`Could not fetch template list from server. Cause: ${e?.message}`));t=await ensureValidActorName(t);let v=e.cwd(),x=u(v,t);for(;;){let e=await B(x).catch(()=>null),n=e&&await Ae(x).then(e=>e.length>0).catch(()=>!1);if(e?.isDirectory()&&n){let e=`Cannot create new Actor, directory '${t}' already exists. Provide a different name. To create a local Actor environment inside an existing directory, use "apify init".`;if(l)throw Error(e);error({message:e}),t=await ensureValidActorName(),x=u(v,t);continue}e||await R(x,{recursive:!0});break}let S=null,C=null;if(this.telemetryData.create={fromArchiveUrl:!!p,origin:c},!p){let e=await getTemplateDefinition(n,_,{useCase:r,language:i});({archiveUrl:p,messages:S}=e),C=e.id,this.telemetryData.create.templateId=e.id,this.telemetryData.create.templateName=e.name,this.telemetryData.create.templateLanguage=e.category,`skipOptionalDeps`in e&&(m=e.skipOptionalDeps)}this.flags.omitOptionalDeps&&(m=!0);let{isTTY:w}=await useStdin(),T=w&&!ue&&!l;g??=T?await promptGitSource():`apify`;let E=isGitProvider(g)?g:null;if(this.telemetryData.create.source=g,E&&s)throw Error(`--source ${g} clones a git repository, so --skip-git-init cannot apply.`);if(!E&&f)throw Error(`--git-repo only applies to a Git source, so add --source github|gitlab|bitbucket or drop it.`);if(!E&&this.flags.autoBuild)throw Error(`--auto-build only applies to a Git source, so add --source github|gitlab|bitbucket or drop it.`);if(E&&this.flags.templateArchiveUrl)throw Error(`--template-archive-url is not supported with --source ${g}.`);let D=E?{provider:E,client:await getLoggedClientOrThrow(),account:toGitAccount(await getLocalUserInfo()),autoBuild:this.flags.autoBuild!==`off`,...parseGitRepoFlag(f,t)}:null,applyLocalConfig=async e=>{let n=getJsonFileContent(u(e,W));await setLocalConfig(Object.assign(n||$t,{name:t}),e),await setLocalEnv(e),await createPrefilledInputFileFromInputSchema(e)};E||(await downloadAndUnzip({url:p,pathTo:x}),await applyLocalConfig(x),await enhanceReadmeWithLocalSuffix(u(x,`README.md`),_));let ee=u(x,`package.json`),O=null;D&&(O=await runGitSourceFlow({provider:D.provider,actorDir:x,actorName:t,workspace:D.workspace,repoName:D.repoName,isPrivate:!0,templateArchiveUrl:p,client:D.client,isInteractive:T,account:D.account,autoBuild:D.autoBuild,customize:applyLocalConfig}));let k=!1;a||await(await useCwdProject({cwd:x})).inspectAsync(async n=>{let r=b(rn);if((n.type===1||n.type===2)&&n.packageManager===`uv`){let e=await Le(`uv`,{nothrow:!0});if(!e){warning({message:`This Actor uses uv to manage its dependencies, but the uv executable was not found. Install uv (https://docs.astral.sh/uv/getting-started/installation/), then run "uv sync" in the Actor directory.`});return}info({message:`Installing dependencies with "uv sync"...`}),await execWithLog({cmd:e,args:[`sync`],opts:{cwd:x}}),k=!0;return}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.`})}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(ee,{name:t});let e=[`install`];if(m)switch(i.pmName){case`npm`:y(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`)}await execWithLog({cmd:i.pmPath,args:e,opts:{cwd:x},overrideCommand:i.pmName}),k=!0;break}case 1:case 2:{if(!isPythonVersionSupported(i.version)){warning({message:`Python Actors require Python ${sn} or higher, but you have Python ${i.version}!`}),warning({message:`Please install Python ${sn} or higher to be able to run Python Actors locally.`});return}let t=u(x,`.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:x}}),i=(await usePythonRuntime({cwd:x,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:x}}),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`-r`,`requirements.txt`],opts:{cwd:x}}),k=!0;break}}});let A={success:!0},te=await B(u(v,`.git`)).catch(()=>null),j=await B(u(x,`.git`)).catch(()=>null),M=O!==null&&!O.scaffolded,N=!s&&!te&&!j&&!M;if(N)try{await execWithLog({cmd:`git`,args:[`init`],opts:{cwd:x}})}catch(e){A={success:!1,error:e}}let ne=k?null:await getInstallCommandSuggestion(x),re=N&&A.success||!!j;O?.stopReason&&(e.exitCode=1);let P=D&&O?.stopReason?buildGitSourceNextSteps({actorName:t,stopReason:O.stopReason,provider:D.provider,remoteUrl:O.remoteUrl,httpsUrl:O.httpsUrl,repoName:D.repoName,scaffolded:O.scaffolded,actorId:O.actorId,account:D.account}):buildNextSteps({actorName:t,dependenciesInstalled:k,installCommandSuggestion:ne}),ie=!O?.stopReason;l?printJsonToStdout({dir:x,actorJsonPath:u(x,W),template:C,source:g,nextSteps:P,postCreate:S?.postCreate??null,gitRepositoryInitialized:re,remote:O?.remoteUrl??null,automaticBuilds:O?.automaticBuilds??null,actorId:O?.actorId??null,stopReason:O?.stopReason??null,error:O?.error??null,gitConnectUrl:E?getGitStopUrl(E,O?.stopReason??null,D?.account):null,workspaces:O?.workspaces??null}):ie&&(simpleLog({message:``}),success({message:formatCreateSuccessMessage({actorName:t,dependenciesInstalled:k,postCreate:S?.postCreate??null,gitRepositoryInitialized:re,installCommandSuggestion:ne,gitRemote:O?.remoteUrl&&O.actorId?{remoteUrl:O.remoteUrl,actorId:O.actorId,automaticBuilds:O.automaticBuilds}:null})})),N&&!A.success&&(warning({message:`Failed to initialize git repository: ${A.error.message}`}),warning({message:`You can manually run "git init" in the Actor directory if needed.`})),O&&!l&&logGitSourceOutcome(O,P)}};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:X.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 Vr={[H.JSON]:`application/json`,[H.JSONL]:`application/jsonl`,[H.CSV]:`text/csv`,[H.HTML]:`text/html`,[H.RSS]:`application/rss+xml`,[H.XML]:`application/xml`,[H.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:J.integer({description:`The amount of elements to get from the dataset. By default, it will return all available items.`}),offset:J.integer({description:`The offset in the dataset where to start getting items.`}),format:J.string({description:`The format of the returned output. By default, it is set to 'json'.`,choices:Object.keys(Vr),default:H.JSON})};static args={datasetId:X.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:Vr[n]??`application/octet-stream`}),process.stdout.write(c),process.stdout.write(`
149
149
  `)}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 Hr=new Z({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:X.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(`
150
150
  `),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(`
151
151
  `);Hr.pushRow({Row1:v,Row2:S});let C=Hr.render(2).split(`
152
152
  `).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(`
153
153
  `),``,_].join(`
154
154
  `),stdout:!0})}};const Ur=new Z({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:J.integer({description:`Number of datasets that will be skipped.`,default:0}),limit:J.integer({description:`Number of datasets that will be listed.`,default:20}),desc:J.boolean({description:`Sorts datasets in descending order.`,default:!1}),unnamed:J.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`);Ur.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:Ur.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:X.string({required:!0,description:`The dataset ID or name to push the objects to.`,ignoreStdin:!0}),item:X.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:J.boolean({description:`Removes the unique name of the dataset.`})};static args={nameOrId:X.string({description:`The dataset ID or name to delete.`,required:!0}),newName:X.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:X.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 Y({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 Wr=`https://apify.github.io/input-schema-editor-react/`,Gr=new URL(Wr).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:X.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.
155
- `}),info({message:`Editing input schema at "${t}"...`});let n=ze(),r=` `,i=!0,a=createLocalApiServer({corsOrigin:Gr,authToken:n,routes:{"GET /api/v1/input-schema":(e,n)=>{let a;try{a=D(t)?j(t,{encoding:`utf-8`}):`{}
155
+ `}),info({message:`Editing input schema at "${t}"...`});let n=ze(),r=` `,i=!0,a=createLocalApiServer({corsOrigin:Gr,authToken:n,routes:{"GET /api/v1/input-schema":(e,n)=>{let a;try{a=D(t)?A(t,{encoding:`utf-8`}):`{}
156
156
  `,a.length>3&&(r=It(a).indent||r),a&&(i=a[a.length-1]===`
157
157
  `),D(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 s;try{s=JSON.parse(a||`{}`)}catch(e){let t=`Parsing input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t);return}n.send(s),info({message:`Input schema sent to editor.`})},"POST /api/v1/input-schema":(e,n)=>{try{info({message:`Got input schema from editor...`});let a=JSON.stringify(e,null,r);i&&(a+=`
158
- `);let s=c(t);D(s)||k(s,{recursive:!0}),P(t,a,{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)}},"POST /api/v1/exit":(e,t)=>{e.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),a.close(()=>success({message:`Done.`}))}}});a.listen(0);let{port:s}=a.address();info({message:`Listening for messages from input schema editor on port ${s}...`});let l=`${Wr}?localCliPort=${s}&localCliToken=${n}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${l}"...`}),await Tt(l)}};const Kr=u(`skills`,`apify`,`SKILL.md`);function readApifySkill(){if(typeof __APIFY_CLI_SKILL__==`string`&&__APIFY_CLI_SKILL__)return __APIFY_CLI_SKILL__;let e=c(Lt(import.meta.url));for(;;){let t=u(e,Kr);if(D(t))return j(t,`utf-8`);let n=c(e);if(n===e)return null;e=n}}var 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:X.string({required:!1,description:`The command to get help for.`,catchAll:!0})};static flags={skill:J.boolean({description:"Print the Apify CLI agent skill (guidance for driving `apify` from agents).",default:!1})};async run(){let{commandString:e}=this.args;if(this.flags.skill){let e=readApifySkill();if(!e){error({message:`Could not find the Apify CLI skill file.`});return}simpleLog({stdout:!0,message:e.trimEnd()});return}if(!e||e.toLowerCase().startsWith(`help`)){let e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=q.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
159
- `,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 qr=[`.dockerignore`,`.gitignore`],Jr=Lt(new URL(`./templates/python-scrapy`,import.meta.url));async function merge(e,t,n={bindings:{}}){await Rt.walk(e,async(r,i,a)=>{if(i===e)return;let c=f(e,i),l=c.split(m).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(m),p=u(t,l);if(a.isDirectory())return D(p)||k(p),merge(i,p);c.includes(`.template`)?P(u(t,l.replace(`.template`,``)),zt.compile(j(i,`utf8`))(n.bindings)):D(p)&&qr.includes(s(l))?S(p,j(i)):T(i,p)})}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 xr({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`.${f(e,t).split(m).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 Et(Ot);info({message:`Downloading the latest Scrapy wrapper template...`});let{archiveUrl:a}=i.templates.find(({id:e})=>e===`python-scrapy`);D(Jr)&&N(Jr,{recursive:!0}),await downloadAndUnzip({url:a,pathTo:Jr}),info({message:`Wrapping the Scrapy project...`}),await merge(Jr,e,{bindings:r});let s=new Fe;s.addSection(`apify`),s.set(`apify`,`mainpy_location`,t.settings.BOT_NAME);let c=E(u(e,`scrapy.cfg`),{flags:`a`});await new Promise(e=>{c.on(`open`,t=>{c.write(`
158
+ `);let s=c(t);D(s)||O(s,{recursive:!0}),P(t,a,{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)}},"POST /api/v1/exit":(e,t)=>{e.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),a.close(()=>success({message:`Done.`}))}}});a.listen(0);let{port:s}=a.address();info({message:`Listening for messages from input schema editor on port ${s}...`});let l=`${Wr}?localCliPort=${s}&localCliToken=${n}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${l}"...`}),await Tt(l)}};const Kr=u(`skills`,`apify`,`SKILL.md`);function readApifySkill(){if(typeof __APIFY_CLI_SKILL__==`string`&&__APIFY_CLI_SKILL__)return __APIFY_CLI_SKILL__;let e=c(Lt(import.meta.url));for(;;){let t=u(e,Kr);if(D(t))return A(t,`utf-8`);let n=c(e);if(n===e)return null;e=n}}var 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:X.string({required:!1,description:`The command to get help for.`,catchAll:!0})};static flags={skill:J.boolean({description:"Print the Apify CLI agent skill (guidance for driving `apify` from agents).",default:!1})};async run(){let{commandString:e}=this.args;if(this.flags.skill){let e=readApifySkill();if(!e){error({message:`Could not find the Apify CLI skill file.`});return}simpleLog({stdout:!0,message:e.trimEnd()});return}if(!e||e.toLowerCase().startsWith(`help`)){let e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=q.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
159
+ `,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 qr=[`.dockerignore`,`.gitignore`],Jr=Lt(new URL(`./templates/python-scrapy`,import.meta.url));async function merge(e,t,n={bindings:{}}){await Rt.walk(e,async(r,i,a)=>{if(i===e)return;let c=f(e,i),l=c.split(m).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(m),p=u(t,l);if(a.isDirectory())return D(p)||O(p),merge(i,p);c.includes(`.template`)?P(u(t,l.replace(`.template`,``)),zt.compile(A(i,`utf8`))(n.bindings)):D(p)&&qr.includes(s(l))?S(p,A(i)):T(i,p)})}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 xr({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`.${f(e,t).split(m).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 Et(Ot);info({message:`Downloading the latest Scrapy wrapper template...`});let{archiveUrl:a}=i.templates.find(({id:e})=>e===`python-scrapy`);D(Jr)&&N(Jr,{recursive:!0}),await downloadAndUnzip({url:a,pathTo:Jr}),info({message:`Wrapping the Scrapy project...`}),await merge(Jr,e,{bindings:r});let s=new Fe;s.addSection(`apify`),s.set(`apify`,`mainpy_location`,t.settings.BOT_NAME);let c=E(u(e,`scrapy.cfg`),{flags:`a`});await new Promise(e=>{c.on(`open`,t=>{c.write(`
160
160
  `,()=>{s.write(t),e()})})}),success({message:`The Scrapy project has been wrapped successfully.`})}var WrapScrapyCommand=class extends ApifyCommand{static name=`init-wrap-scrapy`;static description=`Wraps your existing Scrapy project to work like an Apify Actor.
161
161
 
162
162
  It adds the following features:
@@ -214,17 +214,17 @@ try:
214
214
  print(${e}.__version__)
215
215
  except:
216
216
  print('n/a')
217
- `,ni={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}),we;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}),we;let r=ni[n]?.(e);if(!r)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:t,moduleName:e}),we;try{let n=await De(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}),we):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:t,moduleName:e,version:n.stdout.trim()}),Ee(n.stdout.trim()))}catch(n){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:t,moduleName:e,error:n}),we}}var RunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes Actor locally with simulated Apify environment variables.
217
+ `,ni={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:t,project:n}){if(!n.runtime)return cliDebugPrint(`useModuleVersion`,{status:`no_runtime_found`,project:n,moduleName:t}),we;let r;if(n.type===0)r=n.runtime.runtimeShorthand||`node`;else if(n.type===1||n.type===2)r=`python`;else return cliDebugPrint(`useModuleVersion`,{status:`unsupported_project_type`,project:n,moduleName:t}),we;let i=ni[r]?.(t);if(!i)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:n,moduleName:t}),we;try{let r=await De(n.runtime.executablePath,i,{cwd:e.cwd(),shell:!0,windowsHide:!0,verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0});return r.stdout.trim()===`n/a`?(cliDebugPrint(`useModuleVersion`,{status:`no_version_found`,project:n,moduleName:t}),we):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:n,moduleName:t,version:r.stdout.trim()}),Ee(r.stdout.trim()))}catch(e){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:n,moduleName:t,error:e}),we}}var RunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes Actor locally with simulated Apify environment variables.
218
218
  Stores data in local '${Qt}' 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:J.boolean({char:`p`,description:`Whether to purge the default request queue, dataset and key-value store before the run starts.
219
219
  For crawlee projects, this is the default behavior, and the flag is optional.
220
220
  Use \`--no-purge\` to keep the storage folder intact.`,required:!1,default:!0,exclusive:[`resurrect`]}),resurrect:J.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:J.string({description:[`Optional entrypoint for running with injected environment variables.`,`
221
221
  `,`For Python, it is the module name, or a path to a file.`,`
222
- `,`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:J.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":J.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":J.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(),f=await useCwdProject({cwd:t});if(f.isErr()){error({message:f.unwrapErr().message}),e.exitCode=5;return}let p=f.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 ${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 ${rn} (or higher) installed.`})}return}let _,v;if(this.flags.entrypoint){v=this.flags.entrypoint;let e=u(t,this.flags.entrypoint),n=await B(e).catch(()=>null);_=n?.isDirectory()?1:n?.isFile()?0:2}else if(h?.script)_=2,v=h.script;else if(h?.path)_=m===0?0:1,v=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}D(`apify_storage`)&&!D(c)&&(te(`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:p}),x=`0`;this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(x=`1`,y.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),w=l;C&&`tempInputKey`in C&&(this.flags.purge&&y.isSome()&&await Promise.all([purgeDefaultQueue(),purgeDefaultKeyValueStore(l,C.tempInputKey),purgeDefaultDataset()]),x=`0`,w=C.tempInputKey);let T={[L.LOCAL_STORAGE_DIR]:c,CRAWLEE_STORAGE_DIR:c,CRAWLEE_PURGE_ON_START:x,[F.INPUT_KEY]:w,[L.INPUT_KEY]:w,CRAWLEE_INPUT_KEY:w};if(n&&n.password&&(T[L.PROXY_PASSWORD]=n.password),r&&(T[L.USER_ID]=r),i&&(T[L.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=b(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:[v],opts:{env:E,cwd:t},forwardSignals:tn});else{let e=await z(u(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[v])throw Error(`The script "${v}" 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`,v],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 ${sn} or higher, but you have Python ${g.version}!`}),error({message:`Please install Python ${sn} or higher to be able to run Python Actors locally.`});return}_===1?await execWithLog({cmd:g.executablePath,args:[`-m`,v],opts:{env:E,cwd:t},forwardSignals:tn}):await execWithLog({cmd:g.executablePath,args:[v],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(t){e.exitCode=t.exitCode??1}finally{if(C)if(`tempInputKey`in C)await deleteFile(C.tempInputFilePath);else if(C.existingInput){let e=await B(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 V(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=u(e.cwd(),getLocalKeyValueStorePath());await R(r,{recursive:!0});let i=`${An}${n}`,a=u(r,`${i}.json`);return await V(a,JSON.stringify(t.input,null,2)),{tempInputKey:i,tempInputFilePath:a}}let i=new Mn({strict:!1,unicodeRegExp:!1});_t(i,r);let a=getDefaultsFromInputSchema(r),s=getAjvValidator(r,i),l=getLocalInput(e.cwd(),n),f=u(e.cwd(),getLocalKeyValueStorePath(),l?.fileName??`${n}.json`),p;switch(t?.source){case`stdin`:p=`The input provided through standard input is invalid. Please fix the following errors:
223
- `;break;case`input`:p=`The input provided through the --input flag is invalid. Please fix the following errors:
224
- `;break;default:p=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:
225
- `}if(t){let e={...a,...t.input},i=vt(s,r,e);if(i.length>0)throw Error(`${p}${i.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
226
- `)}`);let l=`${An}${n}`,m=u(c(f),`${l}.json`);return await R(c(f),{recursive:!0}),await V(m,JSON.stringify(e,null,2)),{tempInputKey:l,tempInputFilePath:m}}if(!l)return await R(c(f),{recursive:!0}),await V(f,JSON.stringify(a,null,2)),{existingInput:l,inputFilePath:f,writtenAt:Date.now()};if(tt.getExtension(l.contentType)===`json`){let e=JSON.parse(l.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=vt(s,r,t);if(i.length>0)throw Error(`${p}${i.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
227
- `)}`);let m=`${An}${n}`,h=u(c(f),`${m}.json`);return await V(h,JSON.stringify(t,null,2)),{tempInputKey:m,tempInputFilePath:h}}return null}};const ri=[I.READY,I.RUNNING],ii=[I.ABORTING,I.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:X.string({required:!0,description:`The run ID to abort.`})};static flags={force:J.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(!ri.includes(n.status)){ii.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 ai=new Z({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),oi={"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:X.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:J.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(ai.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=getConsoleUrl(),_=`${g}/actors/${r.actId}/runs/${r.id}`,v=`${g}/storage/datasets/${r.defaultDatasetId}`,y=`${g}/storage/key-value-stores/${r.defaultKeyValueStoreId}`;f.push(`${t.blue(`Export results`)}: ${v}`),f.push(`${t.blue(`View saved items`)}: ${y}`),f.push(`${t.blue(`View in Apify Console`)}: ${_}`),simpleLog({message:f.join(`
222
+ `,`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:J.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":J.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":J.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(),f=await useCwdProject({cwd:t});if(f.isErr()){error({message:f.unwrapErr().message}),e.exitCode=5;return}let m=f.unwrap(),{type:h,entrypoint:g,runtime:_}=m;if(m.warnings?.length)for(let e of m.warnings)warning({message:e});if(h===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(!_){switch(h){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 ${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 ${rn} (or higher) installed.`})}return}let v,y;if(this.flags.entrypoint){y=this.flags.entrypoint;let e=u(t,this.flags.entrypoint),n=await B(e).catch(()=>null);v=n?.isDirectory()?1:n?.isFile()?0:2}else if(g?.script)v=2,y=g.script;else if(g?.path)v=h===0?0:1,y=g.path;else{error({message:`No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint.`});return}let x=p(t,`apify_storage`),S=p(t,c);D(x)&&!D(S)&&(M(x,S),warning({message:`The legacy 'apify_storage' directory was renamed to '${c}' to align it with Apify SDK v3. Contents were left intact.`}));let C=await useModuleVersion({moduleName:`crawlee`,project:m}),w=`0`;this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(w=`1`,C.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 T=await getInputOverride(t,this.flags.input,this.flags.inputFile);if(T===!1)return;let E=await this.validateAndStoreInput(T,l),ee=l;E&&`tempInputKey`in E&&(this.flags.purge&&C.isSome()&&await Promise.all([purgeDefaultQueue(),purgeDefaultKeyValueStore(l,E.tempInputKey),purgeDefaultDataset()]),w=`0`,ee=E.tempInputKey);let O={[L.LOCAL_STORAGE_DIR]:c,CRAWLEE_STORAGE_DIR:c,CRAWLEE_PURGE_ON_START:w,[F.INPUT_KEY]:ee,[L.INPUT_KEY]:ee,CRAWLEE_INPUT_KEY:ee};if(n&&n.password&&(O[L.PROXY_PASSWORD]=n.password),r&&(O[L.USER_ID]=r),i&&(O[L.TOKEN]=i),s.environmentVariables){let e=replaceSecretsValue(s.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets});Object.assign(O,e)}let k={...e.env,...O};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(h){case 0:{let e=b(rn);if(isNodeVersionSupported(_.version)?k.NODE_OPTIONS=k.NODE_OPTIONS?`${k.NODE_OPTIONS} --max-http-header-size=80000`:`--max-http-header-size=80000`:warning({message:`You are running Node.js version ${_.version}, which is no longer supported. Please upgrade to Node.js version ${e} or later.`}),v===0||v===1)await execWithLog({cmd:_.executablePath,args:[y],opts:{env:k,cwd:t},forwardSignals:tn});else{let e=await z(u(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(!_.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:_.pmPath,args:[`run`,y],opts:{env:k,cwd:t},overrideCommand:_.pmName,forwardSignals:tn})}break}case 1:case 2:if(!isPythonVersionSupported(_.version)){error({message:`Python Actors require Python ${sn} or higher, but you have Python ${_.version}!`}),error({message:`Please install Python ${sn} or higher to be able to run Python Actors locally.`});return}v===1?await execWithLog({cmd:_.executablePath,args:[`-m`,y],opts:{env:k,cwd:t},forwardSignals:tn}):await execWithLog({cmd:_.executablePath,args:[y],opts:{env:k,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(t){e.exitCode=t.exitCode??1}finally{if(E)if(`tempInputKey`in E)await deleteFile(E.tempInputFilePath);else if(E.existingInput){let e=await B(E.inputFilePath);if(Math.trunc(e.mtimeMs)-E.writtenAt>=5){warning({message:`The "${E.inputFilePath}" file was overwritten during the run. The CLI will not undo the setting of missing default fields from your input schema.`});return}await V(E.inputFilePath,E.existingInput.body)}else await deleteFile(E.inputFilePath)}}async validateAndStoreInput(t,n=`INPUT`){let{inputSchema:r}=await readInputSchema({cwd:e.cwd()}),i=p(e.cwd(),getLocalKeyValueStorePath());if(!r){if(!t)return null;await R(i,{recursive:!0});let e=`${An}${n}`,r=u(i,`${e}.json`);return await V(r,JSON.stringify(t.input,null,2)),{tempInputKey:e,tempInputFilePath:r}}let a=new Mn({strict:!1,unicodeRegExp:!1});_t(a,r);let s=getDefaultsFromInputSchema(r),c=getAjvValidator(r,a),l=getLocalInput(e.cwd(),n),f=u(i,l?.fileName??`${n}.json`),m;switch(t?.source){case`stdin`:m=`The input provided through standard input is invalid. Please fix the following errors:
223
+ `;break;case`input`:m=`The input provided through the --input flag is invalid. Please fix the following errors:
224
+ `;break;default:m=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:
225
+ `}if(t){let e={...s,...t.input},a=vt(c,r,e);if(a.length>0)throw Error(`${m}${a.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
226
+ `)}`);let l=`${An}${n}`,f=u(i,`${l}.json`);return await R(i,{recursive:!0}),await V(f,JSON.stringify(e,null,2)),{tempInputKey:l,tempInputFilePath:f}}if(!l)return await R(i,{recursive:!0}),await V(f,JSON.stringify(s,null,2)),{existingInput:l,inputFilePath:f,writtenAt:Date.now()};if(tt.getExtension(l.contentType)===`json`){let e=JSON.parse(l.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={...s,...e},a=vt(c,r,t);if(a.length>0)throw Error(`${m}${a.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
227
+ `)}`);let f=`${An}${n}`,p=u(i,`${f}.json`);return await V(p,JSON.stringify(t,null,2)),{tempInputKey:f,tempInputFilePath:p}}return null}};const ri=[I.READY,I.RUNNING],ii=[I.ABORTING,I.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:X.string({required:!0,description:`The run ID to abort.`})};static flags={force:J.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(!ri.includes(n.status)){ii.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 ai=new Z({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),oi={"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:X.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:J.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(ai.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=getConsoleUrl(),_=`${g}/actors/${r.actId}/runs/${r.id}`,v=`${g}/storage/datasets/${r.defaultDatasetId}`,y=`${g}/storage/key-value-stores/${r.defaultKeyValueStoreId}`;f.push(`${t.blue(`Export results`)}: ${v}`),f.push(`${t.blue(`View saved items`)}: ${y}`),f.push(`${t.blue(`View in Apify Console`)}: ${_}`),simpleLog({message:f.join(`
228
228
  `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n){for(let e of Object.keys(oi))ai.pushRow({"":e,Unit:`N/A`,"USD Amount":`N/A`});return}for(let[e,r]of Object.entries(oi)){let i=t[r]??0,a=n[r]??0;switch(r){case`ACTOR_COMPUTE_UNITS`:ai.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`:ai.pushRow({"":e,Unit:prettyPrintBytes({bytes:i*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break;default:ai.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:X.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 si=new Z({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:J.integer({description:`Number of runs that will be skipped.`,default:0}),limit:J.integer({description:`Number of runs that will be listed.`,default:10}),desc:J.boolean({description:`Sort runs in descending order.`,default:!1}),compact:J.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:X.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:``})}`)}si.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":Fn.display(e.startedAt),Took:n,"Build No.":e.buildNumber,Origin:e.meta.origin??`UNKNOWN`})}f.push(si.render(+!i)),simpleLog({message:f.join(`
229
229
  `),stdout:!0})}};const ci=[I.SUCCEEDED,I.FAILED,I.ABORTED,I.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:X.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(!ci.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 li=[I.SUCCEEDED,I.FAILED,I.ABORTED,I.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:X.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(!li.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 Y({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}`})}}},RunsWaitCommand=class extends ApifyCommand{static name=`wait`;static description=`Waits for an Actor run to reach a terminal status (SUCCEEDED, FAILED, ABORTED, TIMED-OUT).
230
230
  Returns exit code 0 only when the run SUCCEEDED. Designed for CI and agentic workflows.`;static examples=[{description:`Wait for a run to finish and return a non-zero exit code on failure.`,command:`apify runs wait <runId>`},{description:`Wait for a run and emit a structured JSON result.`,command:`apify runs wait <runId> --json`},{description:`Give up waiting after 5 minutes. Reports the real current status and exits with code 6 if the run is still running.`,command:`apify runs wait <runId> --timeout 300`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-wait`;static enableJsonFlag=!0;static args={runId:X.string({required:!0,description:`The run ID to wait for.`})};static flags={timeout:J.integer({char:`t`,description:`Maximum seconds to wait before giving up. Without this flag the command waits indefinitely.`,required:!1}),"poll-interval":J.integer({description:`How often to poll the platform, in seconds. Defaults to 2.`,required:!1})};async run(){let{runId:t}=this.args,{timeout:n,pollInterval:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),{job:s,timedOutWaiting:c}=await waitForTerminalStatus({apifyClient:a,jobId:t,kind:`run`,maxWaitMillis:n?n*1e3:void 0,pollIntervalMillis:r?r*1e3:void 0}),l=s,u=consoleRunUrl(l.actId,l.id),f=l.status===`SUCCEEDED`,p=exitCodeForWaitResult({job:s,timedOutWaiting:c},`run`),m=`Gave up waiting after ${n}s; run is still ${l.status}`,h=[];if(f||(h=await fetchLogTail(a,l.id)),i){printJsonToStdout({ok:f,operation:`runs.wait`,timedOutWaiting:c,run:{id:l.id,status:l.status,exitCode:l.exitCode??null,url:u},...f?{}:{error:{phase:`run`,message:c?m:`Actor run did not succeed`,logTail:h}},exitCode:p}),e.exitCode=p;return}let g=[{label:`Run`,value:l.status},{label:`Run ID`,value:l.id},{label:`Actor ID`,value:l.actId}];l.buildNumber&&g.push({label:`Build number`,value:l.buildNumber}),typeof l.exitCode==`number`&&g.push({label:`Exit code`,value:String(l.exitCode)});let _=[{label:`Run URL`,url:u}];simpleLog({message:formatResultSummary({resultLabel:`Apify run result`,overallStatus:l.status,lines:g,links:_,errorReason:f?void 0:h}),stdout:!0}),c?error({message:`${m}.`}):f||error({message:`Run ended with status ${l.status}.`}),e.exitCode=p}},RunsIndexCommand=class extends ApifyCommand{static name=`runs`;static description=`Inspect, abort, resurrect, or delete existing Actor runs.
@@ -241,4 +241,4 @@ When no path is provided, validates all schemas found in '${W}':
241
241
  - Dataset schema (from "storages.dataset")
242
242
  - Output schema (from "output")
243
243
  - 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:X.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});if(e){n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${W}'`}`});let t=new Mn({strict:!1});_t(t,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 fi=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,TemplatesIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],pi=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,fi as n,processVersionCheck as r,pi as t};
244
- //# sourceMappingURL=_register-D1MQ_qDt.js.map
244
+ //# sourceMappingURL=_register-BQMrI9Mz.js.map