apify-cli 1.10.1-runtime.10 → 1.10.1-runtime.12
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 ee,lstatSync as O,mkdirSync as k,openSync as te,readFileSync as A,readdirSync as j,readlinkSync as ne,realpathSync as M,renameSync as N,rmSync as P,statSync as re,unlinkSync as ie,writeFileSync as F}from"node:fs";import ae from"string-width";import oe from"strip-ansi";import{once as se}from"node:events";import{homedir as ce,platform as le,tmpdir as ue}from"node:os";import de,{isCI as fe}from"ci-info";import{ACTOR_ENV_VARS as I,ACTOR_JOB_STATUSES as L,ACTOR_JOB_TERMINAL_STATUSES as pe,ACTOR_NAME as me,ACTOR_SOURCE_TYPES as he,APIFY_ENV_VARS as R,KEY_VALUE_STORE_KEYS as ge,LOCAL_ACTOR_ENV_VARS as _e,LOCAL_STORAGE_SUBDIRS as ve,MAX_MULTIFILE_BYTES as ye,META_ORIGINS as be,SOURCE_FILE_FORMATS as xe}from"@apify/consts";import{jaroWinkler as Se}from"@skyra/jaro-winkler";import Ce from"js-levenshtein";import{ApifyApiError as we,ApifyClient as Te,DownloadItemsFormat as Ee}from"apify-client";import De,{AxiosHeaders as Oe}from"axios";import{createHmacSignature as ke,cryptoRandomObjectId as Ae}from"@apify/utilities";import{access as je,appendFile as Me,mkdir as z,mkdtemp as Ne,readFile as B,readdir as Pe,rename as Fe,rm as Ie,stat as V,symlink as Le,unlink as Re,writeFile as H}from"node:fs/promises";import{execa as U}from"execa";import ze from"which";import{Result as Be,err as Ve,none as W,ok as He,some as Ue}from"@sapphire/result";import We from"configparser";import Ge from"@inquirer/input";import{execFileSync as Ke,execSync as qe,spawn as Je}from"node:child_process";import{DurationFormatter as Ye,Time as Xe,TimeTypes as Ze}from"@sapphire/duration";import{Timestamp as Qe}from"@sapphire/timestamp";import $e from"adm-zip";import et from"ajv/dist/2019.js";import{TarArchive as tt,ZipArchive as nt}from"archiver";import rt from"escape-string-regexp";import it from"ignore";import{getEncoding as at}from"istextorbinary";import ot,{Mime as st}from"mime";import ct from"mime/types/other.js";import lt from"mime/types/standard.js";import{glob as ut}from"tinyglobby";import{calculateRunDynamicMemory as dt}from"@apify/actor-memory-expression";import{Separator as ft,createPrompt as pt,isEnterKey as mt,makeTheme as ht,useKeypress as gt,usePrefix as _t,useState as vt}from"@inquirer/core";import{compile as yt}from"json-schema-to-typescript";import{validateInputSchema as bt,validateInputUsingValidator as xt}from"@apify/input_schema";import{getDatasetSchemaValidator as St,getKeyValueStoreSchemaValidator as Ct,getOutputSchemaValidator as wt}from"@apify/json_schemas";import{pipeline as Tt}from"node:stream/promises";import{MemoryStorage as Et}from"@crawlee/memory-storage";import Dt from"cli-table3";import{downloadTemplate as Ot}from"giget";import kt from"jju";import At from"open";import{fetchManifest as jt,manifestUrl as Mt,wrapperManifestUrl as Nt}from"@apify/actor-templates";import Pt from"computer-name";import Ft from"@inquirer/password";import It from"@inquirer/select";import{createServer as Lt}from"node:http";import Rt from"node:assert";import{ReadStream as zt}from"node:tty";import{setTimeout as Bt}from"node:timers/promises";import Vt from"detect-indent";import{fileURLToPath as Ht}from"node:url";import Ut from"@root/walk";import Wt 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=M(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 Gt=null;function useCLIMetadata(){if(Gt)return Gt;let e=detectInstallMethod(),t=getRuntimeInfo();return Gt={version:`1.10.1-runtime.
|
|
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,lstatSync as O,mkdirSync as k,openSync as te,readFileSync as A,readdirSync as j,readlinkSync as ne,realpathSync as M,renameSync as N,rmSync as P,statSync as re,unlinkSync as ie,writeFileSync as F}from"node:fs";import ae from"string-width";import oe from"strip-ansi";import{once as se}from"node:events";import{homedir as ce,platform as le,tmpdir as ue}from"node:os";import de,{isCI as fe}from"ci-info";import{ACTOR_ENV_VARS as I,ACTOR_JOB_STATUSES as L,ACTOR_JOB_TERMINAL_STATUSES as pe,ACTOR_NAME as me,ACTOR_SOURCE_TYPES as he,APIFY_ENV_VARS as R,KEY_VALUE_STORE_KEYS as ge,LOCAL_ACTOR_ENV_VARS as _e,LOCAL_STORAGE_SUBDIRS as ve,MAX_MULTIFILE_BYTES as ye,META_ORIGINS as be,SOURCE_FILE_FORMATS as xe}from"@apify/consts";import{jaroWinkler as Se}from"@skyra/jaro-winkler";import Ce from"js-levenshtein";import{ApifyApiError as we,ApifyClient as Te,DownloadItemsFormat as Ee}from"apify-client";import De,{AxiosHeaders as Oe}from"axios";import{createHmacSignature as ke,cryptoRandomObjectId as Ae}from"@apify/utilities";import{access as je,appendFile as Me,mkdir as z,mkdtemp as Ne,readFile as B,readdir as Pe,rename as Fe,rm as Ie,stat as V,symlink as Le,unlink as Re,writeFile as H}from"node:fs/promises";import{execa as U}from"execa";import ze from"which";import{Result as Be,err as Ve,none as W,ok as He,some as Ue}from"@sapphire/result";import We from"configparser";import Ge from"@inquirer/input";import{execFileSync as Ke,execSync as qe,spawn as Je}from"node:child_process";import{DurationFormatter as Ye,Time as Xe,TimeTypes as Ze}from"@sapphire/duration";import{Timestamp as Qe}from"@sapphire/timestamp";import $e from"adm-zip";import et from"ajv/dist/2019.js";import{TarArchive as tt,ZipArchive as nt}from"archiver";import rt from"escape-string-regexp";import it from"ignore";import{getEncoding as at}from"istextorbinary";import ot,{Mime as st}from"mime";import ct from"mime/types/other.js";import lt from"mime/types/standard.js";import{glob as ut}from"tinyglobby";import{calculateRunDynamicMemory as dt}from"@apify/actor-memory-expression";import{Separator as ft,createPrompt as pt,isEnterKey as mt,makeTheme as ht,useKeypress as gt,usePrefix as _t,useState as vt}from"@inquirer/core";import{compile as yt}from"json-schema-to-typescript";import{validateInputSchema as bt,validateInputUsingValidator as xt}from"@apify/input_schema";import{getDatasetSchemaValidator as St,getKeyValueStoreSchemaValidator as Ct,getOutputSchemaValidator as wt}from"@apify/json_schemas";import{pipeline as Tt}from"node:stream/promises";import{MemoryStorage as Et}from"@crawlee/memory-storage";import Dt from"cli-table3";import{downloadTemplate as Ot}from"giget";import kt from"jju";import At from"open";import{fetchManifest as jt,manifestUrl as Mt,wrapperManifestUrl as Nt}from"@apify/actor-templates";import Pt from"computer-name";import Ft from"@inquirer/password";import It from"@inquirer/select";import{createServer as Lt}from"node:http";import Rt from"node:assert";import{ReadStream as zt}from"node:tty";import{setTimeout as Bt}from"node:timers/promises";import Vt from"detect-indent";import{fileURLToPath as Ht}from"node:url";import Ut from"@root/walk";import Wt 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=M(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 Gt=null;function useCLIMetadata(){if(Gt)return Gt;let e=detectInstallMethod(),t=getRuntimeInfo();return Gt={version:`1.10.1-runtime.12`,hash:`e22a7c1ec75b4c45cf857abf06ddae0e2bbad8b6`,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`&&(Gt.installPath=c(process.execPath)),Gt}function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Kt=[`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{F(i,n),r!==void 0&&C(i,r),N(i,t)}catch(e){try{P(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),N(i,n)}catch(e){try{P(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Kt)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 Kt){let t=u(r,`${e}.exe.old`);if(D(t))try{P(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`||!Kt.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 Kt){let n=u(r,`${t}.exe`);if(D(n))try{p(n)===p(e.execPath)?(N(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):P(n,{force:!0})}catch(e){try{N(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}let t=u(r,`upgrade.ps1`);try{P(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 qt;function getMaxLineWidth(){if(qt)return qt;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))qt=e;else if(!process.stdout.isTTY)qt=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;qt=e<1?80:e<40?40:e}return qt}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n
|
|
4
|
+
`)}function atomicWriteSync(t,n,r){let i=`${t}.${e.pid}.tmp`;try{F(i,n),r!==void 0&&C(i,r),N(i,t)}catch(e){try{P(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),N(i,n)}catch(e){try{P(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Kt)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 Kt){let t=u(r,`${e}.exe.old`);if(D(t))try{P(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`||!Kt.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 Kt){let n=u(r,`${t}.exe`);if(D(n))try{p(n)===p(e.execPath)?(N(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):P(n,{force:!0})}catch(e){try{N(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}let t=u(r,`upgrade.ps1`);try{P(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 qt;function getMaxLineWidth(){if(qt)return qt;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))qt=e;else if(!process.stdout.isTTY)qt=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;qt=e<1?80:e<40?40:e}return qt}function experimentalLabel(e){return e.experimental?`${t.yellow(`[EXPERIMENTAL]`)} `:``}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=`${experimentalLabel(this.command)}${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}){ae(e.join(` `).split(`
|
|
@@ -16,9 +16,9 @@ import e from"node:process";import t from"chalk";import n from"indent-string";im
|
|
|
16
16
|
`).trim()}selectiveRender(e){let t=[];return e.showShortDescription&&this.pushShortDescription(t),e.showDescription&&this.command.description&&this.pushDescription(t),e.showSubcommands&&this.pushSubcommands(t),e.showExamples&&this.pushExamples(t),e.showLearnMore&&this.pushLearnMore(t),t.join(`
|
|
17
17
|
`).trim()}pushSubcommands(e){if(!this.command.subcommands?.length)return;e.push(t.bold(`SUBCOMMANDS`));let a=r(this.command.subcommands.map(e=>`${this.command.name} ${e.name}`).join(`
|
|
18
18
|
`));for(let t of this.command.subcommands){let r=t.shortDescription||t.description?.split(`
|
|
19
|
-
`)[0]||``,s=`${this.command.name} ${t.name.padEnd(a-this.command.name.length-1)} ${r}`,c=i(s,getMaxLineWidth()-a-2),l=n(c,a+2+2).trim();e.push(` ${l}`)}e.push(``)}};const Jt=/* @__PURE__ */ new Map;function registerCommandForHelpGeneration(e,t){if(t.name.toLowerCase()!==t.name){error({message:`Command name "${t.name}" is not correctly set up internally. Make sure you fill out the "name" field in the command class extension.`});return}if(t.subcommands?.length){Jt.set(t,new CommandWithSubcommandsHelp(e,t));for(let n of t.subcommands)registerCommandForHelpGeneration(`${e} ${t.name}`,n)}else Jt.set(t,new CommandHelp(e,t))}function renderHelpForCommand(e){let t=Jt.get(e);if(!t)throw Error(`No help renderer found for command ${e.name}`);return t.render()}function selectiveRenderHelpForCommand(e,t){let n=Jt.get(e);if(!n)throw Error(`No help renderer found for command ${e.name}`);return n.selectiveRender(t)}function sortByName(e,t){return e[0].name.localeCompare(t[0].name)}const Yt=[`Local Actor Development`,`Apify Console`,`Authentication`,`Utilities`],Xt=`Other`,Zt=[{command:`apify login`},{description:`Walks you interactively through the Actor creation flow.`,command:`apify create`},{command:`apify run`},{command:`apify push`},{command:`apify actors search "web scraper"`}],Qt=[{command:`actor get-input`},{command:`actor push-data '{"url":"https://example.com"}'`},{command:`actor set-value OUTPUT '{"done":true}'`}];function renderMainHelpMenu(e){let a=useCLIMetadata(),s=[];e===`actor`?s.push(`'actor' is the runtime CLI baked into Apify Actor Docker images. It exposes a reduced command set intended for use from inside a running Actor. When available, these commands are equivalent to 'apify actor <subcommand>'.`,``):s.push(`Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.`,``),s.push(t.bold(`VERSION`)),s.push(` ${a.fullVersionString}`),s.push(``),s.push(t.bold(`USAGE`)),s.push(` $ ${e} <command> [options]`),s.push(``);let c=[];for(let[e,t]of Jt)t.entrypoint.includes(` `)||e.hidden||c.push([e,t]);let l=/* @__PURE__ */ new Map;for(let e of c){let[t]=e,n=t.group||Xt;l.has(n)||l.set(n,[]),l.get(n).push(e)}for(let e of l.values())e.sort(sortByName);let u=[];for(let e of Yt)l.has(e)&&u.push(e);let f=[...l.keys()].filter(e=>!Yt.includes(e)&&e!==Xt).sort();u.push(...f),l.has(Xt)&&u.push(Xt);let p=c.map(([e])=>e.name).join(`
|
|
19
|
+
`)[0]||``,s=`${this.command.name} ${t.name.padEnd(a-this.command.name.length-1)} ${r}`,c=i(s,getMaxLineWidth()-a-2),l=n(c,a+2+2).trim();e.push(` ${l}`)}e.push(``)}};const Jt=/* @__PURE__ */ new Map;function registerCommandForHelpGeneration(e,t){if(t.name.toLowerCase()!==t.name){error({message:`Command name "${t.name}" is not correctly set up internally. Make sure you fill out the "name" field in the command class extension.`});return}if(t.subcommands?.length){Jt.set(t,new CommandWithSubcommandsHelp(e,t));for(let n of t.subcommands)n.experimental??=t.experimental,registerCommandForHelpGeneration(`${e} ${t.name}`,n)}else Jt.set(t,new CommandHelp(e,t))}function renderHelpForCommand(e){let t=Jt.get(e);if(!t)throw Error(`No help renderer found for command ${e.name}`);return t.render()}function selectiveRenderHelpForCommand(e,t){let n=Jt.get(e);if(!n)throw Error(`No help renderer found for command ${e.name}`);return n.selectiveRender(t)}function sortByName(e,t){return e[0].name.localeCompare(t[0].name)}const Yt=[`Local Actor Development`,`Apify Console`,`Authentication`,`Utilities`],Xt=`Other`,Zt=[{command:`apify login`},{description:`Walks you interactively through the Actor creation flow.`,command:`apify create`},{command:`apify run`},{command:`apify push`},{command:`apify actors search "web scraper"`}],Qt=[{command:`actor get-input`},{command:`actor push-data '{"url":"https://example.com"}'`},{command:`actor set-value OUTPUT '{"done":true}'`}];function renderMainHelpMenu(e){let a=useCLIMetadata(),s=[];e===`actor`?s.push(`'actor' is the runtime CLI baked into Apify Actor Docker images. It exposes a reduced command set intended for use from inside a running Actor. When available, these commands are equivalent to 'apify actor <subcommand>'.`,``):s.push(`Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.`,``),s.push(t.bold(`VERSION`)),s.push(` ${a.fullVersionString}`),s.push(``),s.push(t.bold(`USAGE`)),s.push(` $ ${e} <command> [options]`),s.push(``);let c=[];for(let[e,t]of Jt)t.entrypoint.includes(` `)||e.hidden||c.push([e,t]);let l=/* @__PURE__ */ new Map;for(let e of c){let[t]=e,n=t.group||Xt;l.has(n)||l.set(n,[]),l.get(n).push(e)}for(let e of l.values())e.sort(sortByName);let u=[];for(let e of Yt)l.has(e)&&u.push(e);let f=[...l.keys()].filter(e=>!Yt.includes(e)&&e!==Xt).sort();u.push(...f),l.has(Xt)&&u.push(Xt);let p=c.map(([e])=>e.name).join(`
|
|
20
20
|
`),m=r(p)||1,renderEntry=([e])=>{let t=e.shortDescription||e.description?.split(`
|
|
21
|
-
`)[0]||``,r=`${e.name.padEnd(m)} ${t}`,a=i(r,getMaxLineWidth()-m-4);return` ${n(a,m+2+2).trim()}`};for(let e of u){let n=l.get(e);n.length&&(s.push(t.bold(e.toUpperCase())),s.push(...n.map(renderEntry),``))}let h=e===`actor`?Qt:Zt;if(h.length){s.push(t.bold(`EXAMPLES`));for(let e=0;e<h.length;e++){let r=h[e];if(r.description){e>0&&s.push(``);let a=i(r.description,getMaxLineWidth()-4,{trim:!1}).split(`
|
|
21
|
+
`)[0]||``,r=`${e.name.padEnd(m)} ${experimentalLabel(e)}${t}`,a=i(r,getMaxLineWidth()-m-4);return` ${n(a,m+2+2).trim()}`};for(let e of u){let n=l.get(e);n.length&&(s.push(t.bold(e.toUpperCase())),s.push(...n.map(renderEntry),``))}let h=e===`actor`?Qt:Zt;if(h.length){s.push(t.bold(`EXAMPLES`));for(let e=0;e<h.length;e++){let r=h[e];if(r.description){e>0&&s.push(``);let a=i(r.description,getMaxLineWidth()-4,{trim:!1}).split(`
|
|
22
22
|
`).map(e=>`# ${e}`).join(`
|
|
23
23
|
`);s.push(t.dim(n(a,2)))}s.push(` $ ${r.command}`),r.description&&e<h.length-1&&s.push(``)}s.push(``)}return s.push(t.bold(`LEARN MORE`),` Use '${e} <command> --help' for more information about a command.`,` Read the docs at https://docs.apify.com/cli.`,` Run '${e} help --skill' to print the Apify CLI agent skill (guidance for driving 'apify' from agents).`,``),s.push(t.bold(`TROUBLESHOOTING`),` For general support, reach out to us at https://apify.com/contact.`,` If you believe you are encountering a bug, file it at https://github.com/apify/apify-cli/issues/new.`),s.join(`
|
|
24
24
|
`).trim()}let $t=/* @__PURE__ */ function(e){return e[e.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]=`NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE`,e[e.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]=`NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL`,e[e.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]=`NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION`,e[e.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]=`APIFY_FLAG_PROVIDED_MULTIPLE_TIMES`,e[e.APIFY_INVALID_FLAG_INTEGER_VALUE=4]=`APIFY_INVALID_FLAG_INTEGER_VALUE`,e[e.APIFY_INVALID_CHOICE=5]=`APIFY_INVALID_CHOICE`,e[e.APIFY_MISSING_FLAG=6]=`APIFY_MISSING_FLAG`,e[e.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]=`APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG`,e[e.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]=`APIFY_TOO_MANY_REQUESTERS_OF_STDIN`,e[e.APIFY_UNKNOWN_ERROR=9]=`APIFY_UNKNOWN_ERROR`,e}({});var en=class CommandError extends Error{code;command;metadata;constructor({code:e,message:t=``,metadata:n={},command:r}){super(t||String($t[e])),this.code=e,this.metadata=n,this.command=r}extractFlagNameFromMessage(){switch(this.code){case 0:{let e=/'(?:-[a-z], )?-?-(?<flagName>[a-zA-Z-]+)(?: <value>)?' (?<noArg>does not take)?(?<missingArg>argument missing)?(?<ambiguous>argument is ambiguous\.(?<ambiguousMessage>\s*.*\s*.*)?)?/gi.exec(this.message);if(!e)throw Error(`Encountered unparsable error message from argument parser: ${this.message}.\n\nPlease report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.flagName,expectsValue:e.groups.noArg===void 0,ambiguousFlag:e.groups.ambiguous?e.groups.ambiguous:void 0,ambiguousMessage:e.groups.ambiguousMessage?e.groups.ambiguousMessage.trim():void 0}}case 2:{let e=/Unknown option '-(?<longForm>-)?(?<optionName>.+)'\.(?<nodeSuggestion>.*)/gi.exec(this.message);if(!e)throw Error(`Encountered unparsable error message from argument parser: ${this.message}.\n\nPlease report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.optionName,expectsValue:!1,unknownOptionSuggestion:e.groups.nodeSuggestion,shortForm:!e.groups.longForm}}default:throw Error(`Not implemented`)}}getPrettyMessage(){switch(this.code){case 0:{let e=this.extractFlagNameFromMessage();return CommandError.buildMessageFromFlagData(e)}case 2:{let e=this.extractFlagNameFromMessage(),n=selectiveRenderHelpForCommand(this.command,{showUsageString:!0});return[t.gray(`Unknown flag provided: ${t.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`),e.unknownOptionSuggestion?t.gray(` ${e.unknownOptionSuggestion.trim()}`):null,``,n].filter(e=>e!==null).join(`
|
|
@@ -52,7 +52,7 @@ Common package structures:
|
|
|
52
52
|
`).filter(Boolean);if(e.length>0){let t=sr().add(e);gitIgnoreFilter=e=>e.filter(e=>!t.ignores(e))}}catch{gitIgnoreFilter=await getGitignoreFallbackFilter(n)}let s=await ut([`*`,`**/**`],{ignore:r,dot:!0,expandDirectories:!1,cwd:n}),c=gitIgnoreFilter?gitIgnoreFilter(s):s;if(i&&(c=i(c)),a.length>0){let e=sr().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 nt({zlib:{level:6}});i.pipe(r),t.forEach(e=>i.file(u(n,e),{name:e})),await i.finalize()},getLocalInput=(e,t)=>{let n=t??ge.INPUT,r=p(e,getLocalKeyValueStorePath());if(!D(r))return;let i=readKvsRecordMetadata(r,n);if(i){let e=i.filename??encodeRecordKey(n);if(D(u(r,e)))return{body:A(u(r,e)),contentType:i.contentType,fileName:e}}let a=j(r).find(e=>!!e.match(inputFileRegExp(n)));return a?{body:A(u(r,a)),contentType:dr.getType(a),fileName:a}: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=j(n),i=t.length>0?t:[ge.INPUT],a=i.map(inputFileRegExp),s=new Set(i.flatMap(e=>[recordMetadataFileName(e),readKvsRecordMetadata(n,e)?.filename])),c=[];r.forEach(e=>{!s.has(e)&&!a.some(t=>t.test(e))&&c.push(deleteFile(u(n,e)))}),await Promise.all(c)},outputJobLog=async({job:t,timeoutMillis:n,apifyClient:r})=>{let{id:i,status:a}=t,s=r||new Te({baseUrl:resolveApiBaseUrl()});if(pe.includes(a)){if(e.env.APIFY_NO_LOGS_IN_TESTS)return;let t=await s.log(i).get();t&&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||ge.INPUT,r=getLocalStorageDir().replaceAll(`\\`,`/`),i=getLocalKeyValueStorePath().replaceAll(`\\`,`/`);return(await ut([`${r}/**`,...[n,`${ir}${n}`].flatMap(e=>[`!${i}/${e}`,`!${i}/${e}.*`])],{cwd:e.cwd()})).length===0},validateActorName=e=>{if(!me.REGEX.test(e))throw Error(`The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).`);if(e.length<me.MIN_LENGTH)throw Error(`The Actor name must be at least 3 characters long.`);if(e.length>me.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<me.MIN_LENGTH&&(t=`${t}-apify-actor`),t=t.replaceAll(/^-+/g,``).replaceAll(/-+$/g,``),t.slice(0,me.MAX_LENGTH)},isPythonVersionSupported=e=>x(e,`^${pn}`),isNodeVersionSupported=e=>{let t=b(un);return y(e,t)},downloadZip=async e=>{let t=await De.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 $e(n)},downloadAndUnzip=async({url:e,pathTo:t})=>{(await downloadZip(e)).extractAllTo(t,!0)},K=new Qe(`YYYY-MM-DD [at] HH:mm:ss`),fr=new Qe(`YYYY-MM-DD[
|
|
53
53
|
]HH:mm:ss`),pr=new Qe(`YYYY-MM-DD`),mr=new Ye,hr=new Ye({[Ze.Day]:{DEFAULT:`d`},[Ze.Hour]:{DEFAULT:`h`},[Ze.Minute]:{DEFAULT:`m`},[Ze.Month]:{DEFAULT:`M`},[Ze.Second]:{DEFAULT:`s`},[Ze.Week]:{DEFAULT:`w`},[Ze.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??ce(),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 gr=[`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
54
|
`);function createAnonymousId(){return`CLI:${Ae()}`}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:gr}),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);k(i,{recursive:!0}),F(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 _r=useCLIMetadata(),vr=_r.isBeta?`rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC`:`2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t`;async function trackEvent(e,t){let n=await useTelemetryIdentifiers(),r={anonymousId:n.anonymousId,context:{app:{name:`apify-cli`,version:_r.version,build:_r.hash},library:{name:`apify-cli`,version:_r.version},os:{name:_r.platform},userAgent:bn,channel:`server`},event:e,properties:{...t,app:`cli`},timestamp:(/* @__PURE__ */ new Date()).toISOString(),userId:n.userId,writeKey:vr};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>=sn)}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
|
-
`)}function getLocalUsername(){return getCurrentProfile()?.username}async function fetchRentalActorCount(e){let t=useCLIMetadata(),n=new URL(`/v2/store`,resolveApiBaseUrl()||`https://api.apify.com`);try{let{data:r}=await De.get(n.href,{params:{username:e,pricingModel:`FLAT_PRICE_PER_MONTH`,limit:1},timeout:3e3,headers:{...fn,"User-Agent":`Apify CLI/${t.version} (https://github.com/apify/apify-cli)`}});return typeof r?.data?.total==`number`?r.data.total:(cliDebugPrint(`useRentalSunsetNotice`,`Store response has no data.total`,{body:r}),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:fe,skipEnvValue:e.env.APIFY_CLI_SKIP_RENTAL_SUNSET_NOTICE}))return;let r=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 yr={type:`boolean`,multiple:!1,short:`h`},br={type:`boolean`,multiple:!1},xr={type:`string`,multiple:!1},Sr={type:`string`,multiple:!1},Cr=`user-agent`,wr=/* @__PURE__ */ 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=/* @__PURE__ */ new Map,Tr=[`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 enableProfileFlag=!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(),wr.has(this.entrypoint)){let t=r[Cr],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=/* @__PURE__ */ 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{this.ctor.enableProfileFlag&&typeof r.profile==`string`&&(this.flags.profile=r.profile,await selectProfile(r.profile)),await this.run()}catch(t){error({message:t.message}),e.exitCode||=1}finally{!this.telemetryData.actorLanguage&&Tr.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=/* @__PURE__ */ 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=/* @__PURE__ */ 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)??/* @__PURE__ */ 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)??/* @__PURE__ */ new Set;n.add(l),r.set(t,n)}}let m=c.filter(t=>Object.hasOwn(e,t));if(m.length>1)throw new en({code:3,command:this.ctor,metadata:{flag:l}});let h=e[m[0]];if(h===void 0&&s.required)throw new en({code:6,command:this.ctor,metadata:{flag:l,matcher:m[0]}});if(Array.isArray(h)){if(h.length>1)throw new en({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 en({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 en({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 en({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 en({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 en({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(`
|
|
55
|
+
`)}function getLocalUsername(){return getCurrentProfile()?.username}async function fetchRentalActorCount(e){let t=useCLIMetadata(),n=new URL(`/v2/store`,resolveApiBaseUrl()||`https://api.apify.com`);try{let{data:r}=await De.get(n.href,{params:{username:e,pricingModel:`FLAT_PRICE_PER_MONTH`,limit:1},timeout:3e3,headers:{...fn,"User-Agent":`Apify CLI/${t.version} (https://github.com/apify/apify-cli)`}});return typeof r?.data?.total==`number`?r.data.total:(cliDebugPrint(`useRentalSunsetNotice`,`Store response has no data.total`,{body:r}),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:fe,skipEnvValue:e.env.APIFY_CLI_SKIP_RENTAL_SUNSET_NOTICE}))return;let r=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 yr={type:`boolean`,multiple:!1,short:`h`},br={type:`boolean`,multiple:!1},xr={type:`string`,multiple:!1},Sr={type:`string`,multiple:!1},Cr=`user-agent`,wr=/* @__PURE__ */ 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=/* @__PURE__ */ new Map,Tr=[`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 enableProfileFlag=!1;static name;static shortDescription;static description;static examples;static docsUrl;static interactive;static interactiveNote;static experimental;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(),wr.has(this.entrypoint)){let t=r[Cr],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=/* @__PURE__ */ 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{this.ctor.enableProfileFlag&&typeof r.profile==`string`&&(this.flags.profile=r.profile,await selectProfile(r.profile)),await this.run()}catch(t){error({message:t.message}),e.exitCode||=1}finally{!this.telemetryData.actorLanguage&&Tr.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=/* @__PURE__ */ 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=/* @__PURE__ */ 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)??/* @__PURE__ */ 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)??/* @__PURE__ */ new Set;n.add(l),r.set(t,n)}}let m=c.filter(t=>Object.hasOwn(e,t));if(m.length>1)throw new en({code:3,command:this.ctor,metadata:{flag:l}});let h=e[m[0]];if(h===void 0&&s.required)throw new en({code:6,command:this.ctor,metadata:{flag:l,matcher:m[0]}});if(Array.isArray(h)){if(h.length>1)throw new en({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 en({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 en({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 en({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 en({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 en({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(vn?.toString(`utf8`)??``).trim();default:return vn}}_buildParseArgsOption(){let e={help:yr};wr.has(this.entrypoint)&&(e[Cr]=Sr);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=br),this.ctor.enableProfileFlag&&(t.options.profile=xr),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=/* @__PURE__ */ 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=/* @__PURE__ */ 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=/* @__PURE__ */ 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 Er=pt((e,t)=>{let n=boolToString,[r,i]=vt(`idle`),[a,s]=vt(``),c=ht(),l=_t({status:r,theme:c});gt((r,c)=>{if(mt(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 Er({message:e,default:t},Jn)),getDeprecatedLocalConfigPath=e=>u(e,`apify.json`),Dr=/* @__PURE__ */ new Map;async function useActorConfig({cwd:t=e.cwd(),migrateConfig:n=!0,warnAboutOldConfig:r=!0}={cwd:e.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let i=Dr.get(t);if(i)return cliDebugPrint(`useActorConfig`,{cacheHit:!0,config:i}),He(i);let a=getLocalConfigPath(t),s=getDeprecatedLocalConfigPath(t),c,l;try{c=getJsonFileContent(a)}catch(e){return Ve({message:`Failed to read local config at path: '${a}':`,cause:e,exists:!1,config:{}})}try{l=getJsonFileContent(s)}catch(e){return Ve({message:`Failed to read local config at path: '${s}':`,cause:e,exists:!1,config:{}})}if(c&&l&&r&&await handleBothConfigVersionsFound(s),!c&&!l)return Dr.set(t,{exists:!1,migrated:!1,config:{}}),He({exists:!1,migrated:!1,config:{}});let u=!1;if(!c&&l&&n){let e=await handleMigrationFlow(l,s,a);if(e.isErr())return Ve(e.unwrapErr());c=e.unwrap(),u=!0}return Dr.set(t,{exists:!0,migrated:u,config:c||l||{}}),cliDebugPrint(`useActorConfig`,{cacheHit:!1,config:Dr.get(t)}),He({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 Fe(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 Or=[`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,...Or.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 Ve({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 z(c(n),{recursive:!0}),await H(n,JSON.stringify(r,null,` `))}catch(e){let t=e;return Ve({message:`Failed to write the new "actor.json" file to path: '${n}'.\n ${t.message||t}`,exists:!0,config:r})}try{await Fe(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.`}),He(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 kr=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:kr}),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 dt(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}}};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 getLoggedClientOrThrow(),a=process.env[R.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 Ar=[`.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,ln,r.input),i=getJsonFileContent(e);if(!i){if(n)throw Error(`Input schema file not found at ${e} (referenced in '${G}').`);return warning({message:`Input schema file not found at ${e} (referenced in '${G}').`}),{inputSchema:null,inputSchemaPath:e}}return{inputSchema:i,inputSchemaPath:e}}for(let e of Ar){let n=u(t,e);if(D(n))return{inputSchema:getJsonFileContent(n),inputSchemaPath:n}}return{inputSchema:null,inputSchemaPath:u(t,Ar[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 cr({strict:!1});return bt(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,ln,s),r=getJsonFileContent(t);if(!r){if(i)throw Error(`${n} schema file not found at ${t} (referenced in '${G}').`);return warning({message:`${n} schema file not found at ${t} (referenced in '${G}').`}),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 cr({strict:!1});bt(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{await writeKvsRecord({storePath:u(e,getLocalKeyValueStorePath()),key:ge.INPUT,fileName:`${ge.INPUT}.json`,contentType:`application/json; charset=utf-8`,body: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=St();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Dataset`))}function validateOutputSchema(e){let t=wt();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Output`))}function validateKvsSchema(e){let t=Ct();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Key-Value Store`))}const getAjvValidator=(e,t)=>{let n=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.
|
|
@@ -93,7 +93,7 @@ For platform-level management (deploy, list, call Actors), see 'apify actors' (p
|
|
|
93
93
|
`).map(e=>e.trimEnd()).filter(e=>e.length>0).slice(-10):[]}function buildRunResultJson({run:e,operation:t,logTail:n}){let r=isSucceeded(e),i={ok:r,operation:t,actor:{id:e.actId,url:actorUrl(e.actId)},run:{id:e.id,status:e.status,url:runUrl(e.actId,e.id)},storage:{defaultDatasetId:e.defaultDatasetId,defaultKeyValueStoreId:e.defaultKeyValueStoreId,datasetUrl:datasetUrl(e.defaultDatasetId)},exitCode:getRunExitCode(e)};return r||(i.error={phase:`run`,message:e.statusMessage||genericReason(e),logTail:n}),i}function printRunResultSummary({run:e,operation:n,logTail:r}){let i=isSucceeded(e),a=i?t.green:t.red,s=[`${Pr[n]} result: ${a(e.status)}`,``,`${t.yellow(`Run`)}: ${a(e.status)}`,`${t.yellow(`Actor ID`)}: ${e.actId}`,`${t.yellow(`Run ID`)}: ${e.id}`,`${t.yellow(`Build number`)}: ${e.buildNumber}`];!i&&e.exitCode!=null&&s.push(`${t.yellow(`Exit code`)}: ${e.exitCode}`),s.push(`${t.yellow(`Dataset ID`)}: ${e.defaultDatasetId}`,`${t.yellow(`Key-value store ID`)}: ${e.defaultKeyValueStoreId}`,``,`${t.blue(`Run URL`)}: ${runUrl(e.actId,e.id)}`,`${t.blue(`Dataset URL`)}: ${datasetUrl(e.defaultDatasetId)}`),i||s.push(``,`${t.yellow(`Reason`)}:`,e.statusMessage||genericReason(e),...r),simpleLog({message:s.join(`
|
|
94
94
|
`),stdout:!0})}async function finalizeRun({apifyClient:t,run:n,operation:r,json:i,silent:a}){if(e.exitCode=getRunExitCode(n),a)return;let s=await fetchRunLogTail(t,n);if(i){printJsonToStdout(buildRunResultJson({run:n,operation:r,logTail:s}));return}printRunResultSummary({run:n,operation:r,logTail:s})}function mayTargetActorRuntime(e){try{let{hostname:t}=new URL(e.baseUrl);return t!==`apify.com`&&!t.endsWith(`.apify.com`)}catch{return!1}}async function registerActorRuntimeDevFolder(e,t,n){try{let r=await fetch(`${e.baseUrl}/actor-runtime/dev-folder/${t}`,{method:`POST`,headers:{...fn,Authorization:`Bearer ${e.token}`,"Content-Type":`application/json`},body:JSON.stringify(n)});return r.ok?{ok:!0}:r.status===404?{ok:!1}:{ok:!1,error:(await r.json().catch(()=>null))?.error?.message??`${r.status} ${r.statusText}`}}catch(e){return{ok:!1,error:e.message}}}var Fr=class ActorsCallCommand extends ApifyCommand{static name=`call`;static enableProfileFlag=!0;static description=`Executes Actor remotely using your authenticated account.
|
|
95
95
|
Reads input from local key-value store by default.
|
|
96
|
-
To inspect the input schema before creating a JSON input, use "apify actors info <actor> --input".`;static group=`Apify Console`;static examples=[{description:`Call the Actor defined in the current directory (from .actor/actor.json).`,command:`apify call`},{description:`Call a specific Actor by its full name.`,command:`apify call apify/hello-world`},{description:`Inspect the Actor input schema before preparing JSON input.`,command:`apify actors info apify/hello-world --input`},{description:`Call an Actor with inline JSON input.`,command:`apify call apify/hello-world --input '{"url":"https://example.com"}'`},{description:`Call an Actor with input from a file and print the dataset on success.`,command:`apify call apify/web-scraper --input-file input.json --output-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-call`;static flags={...SharedRunOnCloudFlags(`Actor`),input:J.string({char:`i`,description:`Optional inline JSON object input for the Actor. To avoid shell parsing issues, wrap the JSON in quotes. For JSON files, use --input-file.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":J.string({char:`f`,description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:[`input`]}),silent:J.boolean({char:`s`,description:`Prevents printing the logs of the Actor run to the console.`,default:!1}),"output-dataset":J.boolean({char:`o`,description:`Prints out the entire default dataset on successful run of the Actor.`}),"dev-folder":J.boolean({description:`
|
|
96
|
+
To inspect the input schema before creating a JSON input, use "apify actors info <actor> --input".`;static group=`Apify Console`;static examples=[{description:`Call the Actor defined in the current directory (from .actor/actor.json).`,command:`apify call`},{description:`Call a specific Actor by its full name.`,command:`apify call apify/hello-world`},{description:`Inspect the Actor input schema before preparing JSON input.`,command:`apify actors info apify/hello-world --input`},{description:`Call an Actor with inline JSON input.`,command:`apify call apify/hello-world --input '{"url":"https://example.com"}'`},{description:`Call an Actor with input from a file and print the dataset on success.`,command:`apify call apify/web-scraper --input-file input.json --output-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-call`;static flags={...SharedRunOnCloudFlags(`Actor`),input:J.string({char:`i`,description:`Optional inline JSON object input for the Actor. To avoid shell parsing issues, wrap the JSON in quotes. For JSON files, use --input-file.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":J.string({char:`f`,description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:[`input`]}),silent:J.boolean({char:`s`,description:`Prevents printing the logs of the Actor run to the console.`,default:!1}),"output-dataset":J.boolean({char:`o`,description:`Prints out the entire default dataset on successful run of the Actor.`}),"dev-folder":J.boolean({description:`Experimental, local Actor runtime only: mount the Actor's registered live dev folder into the run, so it picks up local edits (the default). Use --no-dev-folder to run from the built image alone this once; the registration itself stays. Ignored when calling on the Apify platform.`,default:!0})};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 '${G}' file.`})};async run(){let n=e.cwd(),r=getLocalConfig(n)||{},i=await getLoggedClientOrThrow(),a=await getCurrentUserInfo(),s=a.username||a.id;if(this.flags.json&&this.flags.outputDataset){error({message:`You cannot use both --json and --output-dataset. Use --json for run details or --output-dataset for dataset items.`}),e.exitCode=5;return}let{id:c,userFriendlyId:l,actorData:u}=await ActorsCallCommand.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={waitForFinish:2};this.flags.build&&(f.build=this.flags.build),this.flags.timeout&&(f.timeout=this.flags.timeout),this.flags.memory&&(f.memory=this.flags.memory);let p;this.flags.devFolder||(mayTargetActorRuntime(i)?p={devFolder:`false`}:warning({message:`--no-dev-folder only applies to runs on a local Actor runtime; the Apify platform has no live dev folder to skip. Ignoring it.`}));let m=await getInputOverride(n,this.flags.input,this.flags.inputFile,{schemaHint:`Run "apify actors info ${l} --input" to inspect the Actor input schema.`});if(m===!1)return;let h=!1,g,_=runActorOrTaskOnCloud(i,{actorOrTaskData:{id:c,userFriendlyId:l},runOptions:f,type:`Actor`,inputOverride:m?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0,suppressFinalStatus:!0,extraStartParams:p});for await(let e of _)if(g=e,!h&&(h=!0,!this.flags.silent)){let n=runUrl(c,e.id),r=[`${t.yellow(`Started`)}: ${K.display(e.startedAt)}`];e.containerUrl&&r.push(`${t.yellow(`Container URL`)}: ${t.blue(e.containerUrl)}`);let i=g.buildNumber.split(`.`).slice(0,2).join(`.`),a=u.versions.find(e=>e.versionNumber===i),s=Object.entries(u.taggedBuilds??{}).find(([,t])=>t.buildNumber===e.buildNumber)?.[0],l=[`${t.yellow(`Build`)}:`,t.cyan(g.buildNumber)];s?l.push(`(${t.yellow(s)})`):l.push(`(${t.gray(`N/A`)})`),a&&l.push(`| ${t.gray(`Actor version:`)} ${t.cyan(a.versionNumber)} (${t.yellow(a.buildTag)})`),r.push(l.join(` `)),r.push(`${t.yellow(`Timeout`)}: ${g.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),r.push(`${t.yellow(`Memory`)}: ${g.options.memoryMbytes} MB`),r.push(`${t.blue(`View on Apify Console`)}: ${n}`,``),simpleLog({message:r.join(`
|
|
97
97
|
`),stdout:!this.flags.json})}if(await finalizeRun({apifyClient:i,run:g,operation:`call`,json:this.flags.json,silent:this.flags.silent}),!this.flags.json&&this.flags.outputDataset&&g.status===L.SUCCEEDED){let e=g.defaultDatasetId,t,n=4;do{if(t=await i.dataset(e).get(),t?.itemCount)break;await new Promise(e=>{setTimeout(e,250)})}while(n--);let r=await i.dataset(e).downloadItems(Ee.JSON,{clean:!0});console.log(r.toString())}}static async resolveActorId({client:e,localActorName:t,usernameOrId:n,providedActorNameOrId:r}){if(r?.includes(`/`)){let t=await e.actor(r).get();if(!t)throw Error(`Cannot find Actor with ID '${r}' in your account.`);return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t}}if(r){let t=await e.actor(r).get();if(t)return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t};let i=await e.actor(`${n}/${r.toLowerCase()}`).get();if(i)return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i};throw Error(`Cannot find Actor with name or ID '${r}' in your account.`)}if(t){let r=await e.actor(`${n}/${t}`).get();if(!r)throw Error(`Cannot find Actor with ID '${n}/${t}' in your account. Call "apify push" to push this Actor to Apify platform.`);return{userFriendlyId:`${r.username}/${r.name}`,id:r.id,actorData:r}}throw Error(`Please provide an Actor ID or name, or run this command from a directory with a valid Apify Actor.`)}};const Ir={[-1]:void 0,0:{mid:``,"left-mid":``,"mid-mid":``,"right-mid":``,middle:` `,"top-mid":`─`,"bottom-mid":`─`},1:{middle:` `,"top-mid":`─`,"bottom-mid":`─`,top:`─`,bottom:`─`,"left-mid":`├`,mid:`─`,"mid-mid":`─`,"right-mid":`┤`},2:{left:``,right:``,mid:``,"bottom-left":``,"bottom-mid":``,"bottom-right":``,top:``,"top-left":``,"top-mid":``,"top-right":``,"left-mid":``,"mid-mid":``,"right-mid":``,bottom:``,middle:` `}};function generateHeaderColors(e){return Array.from({length:e},()=>`cyan`)}const Lr=process.stdout.columns??100,Rr=Symbol.for(`@apify/cli:responsive-table:skip-column`);var Z=class ResponsiveTable{options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=ResponsiveTable.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,n=generateHeaderColors(t.length),r=e===0||e===2,i=Ir[e],a=[],s=[],c=[];for(let e of t)this.options.hiddenColumns?.includes(e)||this.rows.some(t=>t[e]===Rr)||(a.push(this.options.columnAlignments?.[e]||`left`),ResponsiveTable.isSmallTerminal()?(s.push(this.options.breakpointOverrides?.small?.[e]?.label??e),c.push(this.options.breakpointOverrides?.small?.[e]?.valueFrom??e)):(s.push(e),c.push(e)));let l=new Dt({head:s,style:{head:n,compact:r},colAligns:a,chars:i});for(let e of this.rows){let t=c.map(t=>e[t]);l.push(t)}return l.toString()}static isSmallTerminal(){return Lr<100}};function formatEventPrice(e){return e===0?`$0.00`:e>=.01?`$${e.toFixed(2)}`:`$${Number(e.toPrecision(2))}`}const zr=``,Br=new Z({allColumns:[``,zr],mandatoryColumns:[``,zr],columnAlignments:{"":`left`,[zr]:`right`}});var ActorsInfoCommand=class extends ApifyCommand{static name=`info`;static enableProfileFlag=!0;static description=`Get information about an Actor.`;static examples=[{description:`Print summary information about an Actor.`,command:`apify actors info apify/hello-world`},{description:`Print the Actor README only.`,command:`apify actors info apify/hello-world --readme`},{description:`Print the Actor input schema as JSON.`,command:`apify actors info apify/hello-world --input`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-info`;static flags={readme:J.boolean({description:`Return the Actor README.`,exclusive:[`input`]}),input:J.boolean({description:`Return the Actor input schema.`,exclusive:[`readme`]})};static args={actorId:X.string({description:`The ID of the Actor to return information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:n,input:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),s=await resolveActorContext({providedActorNameOrId:e,client:a});if(!s.valid){error({message:`${s.reason}. Please specify the Actor ID.`,stdout:!0});return}let c=await a.actor(s.id).get();c.actorMaker=await a.user(c.userId).get();for(let e of Object.values(c.taggedBuilds??{}))e.buildId&&(e.build=await a.build(e.buildId).get());if(i){printJsonToStdout(c);return}let l=c.taggedBuilds?.latest;if(n){if(!l){error({message:`No README found for this Actor.`,stdout:!0});return}if(!l.build?.readme){error({message:`No README found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.readme,stdout:!0});return}if(r){if(!l){error({message:`No input schema found for this Actor.`,stdout:!0});return}if(!l.build?.inputSchema){error({message:`No input schema found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.inputSchema,stdout:!0});return}let u=[`Information about Actor ${t.yellow(`${c.username}/${c.name}`)} (${t.gray(c.id)})`,``];c.title&&u.push(`${t.yellow(`Title:`)} ${t.bold(c.title)}`),c.description&&u.push(`${t.yellow(`Description:`)} ${c.description}`),u.push(`${t.yellow(`Created at:`)} ${t.cyan(K.display(c.createdAt))} ${t.gray(`|`)} ${t.yellow(`Updated at:`)} ${t.cyan(K.display(c.modifiedAt))}`),c.actorMaker&&(u.push(``,`${t.yellow(`Made by:`)} ${t.cyan(c.actorMaker.profile.name??c.actorMaker.username)}`),Reflect.get(c,`isCritical`)&&(u[u.length-1]+=` ${t.bgGray(`Maintained by Apify`)}`)),c.isPublic?u.push(``,`${t.yellow(`Actor is`)} ${t.green(`PUBLIC`)}`):u.push(``,`${t.yellow(`Actor is`)} ${t.cyan(`PRIVATE`)}`),c.isDeprecated&&u.push(``,`${t.yellow(`Actor is`)} ${t.red(`DEPRECATED`)}`);let f=c.pricingInfos;if(f?.length){let e=f.at(-1);switch(e.pricingModel){case`FLAT_PRICE_PER_MONTH`:if(u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${e.pricePerUnitUsd}/month + usage`)}`),e.trialMinutes){let n=e.trialMinutes*60*1e3,r=mr.format(n);u.push(` ${t.yellow(`Trial duration:`)} ${t.bold(r)}`)}break;case`PRICE_PER_DATASET_ITEM`:{let n=e.pricePerUnitUsd*1e3;u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${n.toFixed(2)} / 1,000 results`)}`);break}case`PAY_PER_EVENT`:{u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay per event`)}`);let n=Object.values(e.pricingPerEvent?.actorChargeEvents??{});for(let e of n){let n=e.eventPriceUsd,r=e.eventTieredPricingUsd,i;i=typeof n==`number`?formatEventPrice(n):r&&Object.keys(r).length>0?`from ${formatEventPrice(Math.min(...Object.values(r).map(e=>e.tieredEventPriceUsd)))} (tiered)`:`N/A`,Br.pushRow({"":e.eventTitle,[zr]:t.bold(i)})}let r=Br.render(0).split(`
|
|
98
98
|
`);r.splice(1,1),u.push(r.join(`
|
|
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(`
|
|
@@ -108,7 +108,7 @@ If you want to skip missing secrets, run the command with the --allow-missing-se
|
|
|
108
108
|
If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},qr=`temp_file.zip`,Jr={build:`latest`,memoryMbytes:4096,timeoutSecs:3600};function resolvePushOutcome(e){switch(e){case L.SUCCEEDED:return{resultLabel:`SUCCEEDED`,exitCode:0,ok:!0};case L.READY:return{resultLabel:`PENDING`,ok:!0};case L.RUNNING:return{resultLabel:`RUNNING`,ok:!0};case L.ABORTING:return{resultLabel:`ABORTING`,exitCode:3,ok:!1,errorMessage:`Build is aborting`};case L.ABORTED:return{resultLabel:`ABORTED`,exitCode:3,ok:!1,errorMessage:`Build aborted`};case L.TIMING_OUT:return{resultLabel:`TIMING_OUT`,exitCode:2,ok:!1,errorMessage:`Build is timing out`};case L.TIMED_OUT:return{resultLabel:`TIMED_OUT`,exitCode:2,ok:!1,errorMessage:`Build timed out`};case L.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(`
|
|
109
109
|
`)}),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 enableProfileFlag=!0;static description=`Deploys Actor to Apify platform using settings from '${G}'.\nFiles under '${ye/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
|
|
110
110
|
Files matched by .gitignore and .actorignore are excluded. Use negation patterns (e.g. !dist/) in .actorignore to force-include git-ignored files.
|
|
111
|
-
|
|
111
|
+
Experimental: an Actor whose '${G}' sets "dockerContextDir" (a monorepo Actor) pushes that whole Docker context; this works only against a local Actor runtime for now.
|
|
112
112
|
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 '${G}' 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 '${G}' 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. Overrides the value of the 'applyEnvVarsToBuild' field in the '${G}' file. When both the field and the flag are 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 '${G}' 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(`
|
|
113
113
|
`)}),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=resolveDockerContext(n,s?.dockerContextDir);if(c.kind===`invalid`){error({message:c.message}),e.exitCode=5;return}if(c.kind===`context`&&!mayTargetActorRuntime(i)){error({message:monorepoUnsupportedMessage(s.name)}),e.exitCode=255;return}let l=c.kind===`context`?c.sourceRoot:n,f=c.kind===`context`?await getContextFilePaths(c.sourceRoot):r,m=await getCurrentUserInfo(),h=m.organizationOwnerUserId?`/organization/${m.id}`:``,g,_,v=!1,y=this.flags.version||s?.version||`0.0`,b=this.flags.buildTag||s?.buildTag;!b&&y===`0.0`&&(b=`latest`);let x=parseWaitForFinishMillis(this.flags.waitForFinish),S=this.args.actorId;if(S){if(_=await i.actor(S).get(),!_)throw Error(`Cannot find Actor with ID '${S}' in your account.`);g=_.id}else{let e=m.username||m.id;if(_=await i.actor(`${e}/${s.name}`).get(),_)g=_.id;else{let{templates:e}=await jt(),t=e.find(e=>e.name===s.template)?.defaultRunOptions||Jr,n={name:s.name,title:s.title,description:s.description,defaultRunOptions:t,versions:[{versionNumber:y,buildTag:b,sourceType:he.SOURCE_FILES,sourceFiles:[]}]};s.usesStandbyMode&&(n.actorStandby={isEnabled:!0}),_=await i.actors().create(n),g=_.id,v=!0,info({message:`Created Actor with name ${s.name} on Apify.`})}}this.telemetryData.push={actorId:g,wasCreated:v};let C=i.actor(g);info({message:`Deploying Actor '${s.name}' to Apify.`});let w=c.kind===`context`?0:await sumFilesSizeInBytes(f,l);if(w<ye&&!v){let e=await C.get(),t=f.reduce((e,t)=>{let{mtimeMs:n,ctimeMs:r}=re(u(l,t)),i=n>r?n:r;return e>i?e:i},0),n=e?.modifiedAt.valueOf();if(!this.flags.force&&n&&t<n&&(s?.name||S))throw Error(`Actor with identifier "${s?.name||S}" already exists on the platform and has newer changes than your local copy.
|
|
114
114
|
Skipping push. Use --force to override.`)}let T=await C.version(y).get();if(T?.sourceType===he.GIT_REPO&&!await confirmGitSourceSwitch({actorName:_.name,gitRepoUrl:T.gitRepoUrl,force:this.flags.force})){info({message:`Push aborted. Actor ${_.name} still builds from its Git repository.`});return}let E,D,ee;if(c.kind===`context`)E=he.SOURCE_FILES;else if(w<ye)D=await createSourceFiles(r,n),E=he.SOURCE_FILES;else{run({message:`Zipping Actor files`}),await createActZip(qr,r,n);let e=await i.keyValueStores().getOrCreate(`actor-${g}-source`),t=`version-${y}.zip`,a=A(qr);await i.keyValueStore(e.id).setRecord({key:t,value:a,contentType:`application/zip`}),ie(qr);let s=new URL(`${i.baseUrl}/key-value-stores/${e.id}/records/${t}?disableRedirect=true`);if(e?.urlSigningSecretKey){let n=ke(e.urlSigningSecretKey,t);s.searchParams.set(`signature`,n)}ee=s.toString(),E=he.TARBALL}let O=s.environmentVariables?transformEnvToEnvVars(s.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0,k=this.flags.applyEnvVarsToBuild??s.applyEnvVarsToBuild,pushDockerContext=async()=>{if(c.kind!==`context`)return!0;run({message:`Pushing ${l} (${f.length} files) with the Actor in ${c.actorPath}; the build takes its Docker context ${c.contextRoot} from it.`});let t=readGitProvenance(l);t.dirty&&warning({message:`The Docker context has changes that are not committed. They are built here, but the Apify platform builds only what is committed and pushed to Git.`});let n=await pushActorRuntimeSourceContext(i,g,y,{actorPath:c.actorPath,tarball:await createContextTarball(f,l),git:t});return n.ok?!0:(error({message:n.unsupported?monorepoOutdatedRuntimeMessage(i.baseUrl):`Could not push the Docker context of Actor ${_.name}: ${n.error}`}),e.exitCode=n.unsupported?255:1,!1)};if(T&&!await pushDockerContext()){v&&await C.delete();return}if(T){let e={tarballUrl:ee,sourceFiles:D,buildTag:b,sourceType:E,envVars:O,applyEnvVarsToBuild:k};await C.version(y).update(e),run({message:`Updated version ${y} for Actor ${_.name}.`})}else{let e={versionNumber:y,tarballUrl:ee,sourceFiles:D,buildTag:b,sourceType:E,envVars:O,applyEnvVarsToBuild:k};if(await C.versions().create({...e}),run({message:`Created version ${y} for Actor ${_.name}.`}),!await pushDockerContext()){await C.version(y).delete();return}}if(!v&&!!s.usesStandbyMode!=!!_.actorStandby?.isEnabled){let e=!!s.usesStandbyMode;await C.update({actorStandby:{isEnabled:e}}),info({message:`${e?`Enabled`:`Disabled`} standby mode for Actor ${_.name}.`})}await registerDevFolderOnActorRuntime(i,g,_.name,c.kind===`context`?c.contextRoot:n),run({message:`Building Actor ${_.name}`});let te=x===void 0?1/0:Date.now()+x,j=await C.build(y,{useCache:!0,waitForFinish:2});t.u(useAbortJobOnSignal({apifyClient:i,kind:`build`,jobId:j.id}));try{let e=Number.isFinite(te)?Math.max(0,te-Date.now()):void 0;await outputJobLog({job:j,timeoutMillis:e,apifyClient:i})}catch(e){warning({message:`Can not get log:`}),console.error(e)}let ne=await i.build(j.id).get();if(!ne){error({message:`Could not fetch build with ID "${j.id}" after deployment.`}),e.exitCode=1;return}for(j=ne;!pe.includes(j.status)&&Date.now()<te;)await new Promise(e=>setTimeout(e,1e3)),j=await i.build(j.id).get();if(j.status===L.SUCCEEDED&&b&&x!==0){run({message:`Applying build tag "${b}"...`});let e=Date.now()+5e3,t=!1;for(;Date.now()<e;){if((await C.get())?.taggedBuilds?.[b]?.buildId===j.id){t=!0;break}await new Promise(e=>setTimeout(e,1e3))}t||warning({message:`Build succeeded but tag "${b}" was not set after 5 seconds; subsequent calls referencing this tag may not find it.`})}let M=j.status,N=resolvePushOutcome(M),P=`${getConsoleUrl()}${h}/actors/${j.actId}`,F=`${P}#/builds/${j.buildNumber}`,ae=[];if(N.errorMessage)try{let e=await i.log(j.id).get();e&&(ae=e.split(`
|
|
@@ -252,8 +252,8 @@ Agents pick it up on their next start. Re-run this after upgrading the runtime i
|
|
|
252
252
|
Installs the runtime first when needed (like 'apify runtime install'). The runtime API listens on ${In} and the console on ${Ln} unless moved with --api-port and --console-port, which are remembered for later starts and for 'apify runtime connect'. Run 'apify runtime -h' for the environment variables that point the CLI at it.`;static group=`Local Actor Development`;static examples=[{description:`Start the Actor runtime in the foreground (Ctrl+C stops it).`,command:`apify runtime start`},{description:`Start the Actor runtime in the background.`,command:`apify runtime start --detach`},{description:`Start with runtime data stored in a custom directory.`,command:`apify runtime start --data-dir ./data`},{description:`Start on other ports when 3333 or 3000 is already taken.`,command:`apify runtime start --api-port 4333 --console-port 4000`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runtime-start`;static flags={"data-dir":J.string({description:`Host directory mounted as the runtime data directory (storages, builds and run records). Defaults to ~/.apify/actor-runtime/data.`}),detach:J.boolean({char:`d`,description:`Run the runtime container in the background. Stop it with 'apify runtime stop'.`,default:!1}),"api-port":J.integer({description:`Host port for the runtime API. Defaults to the port of the previous start, else ${Nn}.`}),"console-port":J.integer({description:`Host port for the runtime console. Defaults to the port of the previous start, else ${Pn}.`})};async run(){if(await findRunningRuntimeEngine()){error({message:`The Actor runtime is already running (container '${An}'). Stop it with 'apify runtime stop' first.`}),e.exitCode=1;return}let n=configuredRuntimePorts(),r={api:this.flags.apiPort??n.api,console:this.flags.consolePort??n.console};if(!isValidPort(r.api)||!isValidPort(r.console)){error({message:`Ports must be integers between 1 and 65535.`}),e.exitCode=1;return}if(r.api===r.console){error({message:`The API and console need different ports, both are ${r.api}.`}),e.exitCode=1;return}let i=installedActorRuntimeImage(),a=await ensureActorRuntimeImage({image:i});if(!a)return;let s=await resolveEngineSocketPath(a),c=a===`podman`?await podmanInfo():void 0,l=runtimeNetworkMode(a,c),u=runtimeSecurityOptions(a,c),f=p(this.flags.dataDir??defaultDataDir());await z(f,{recursive:!0}),updateActorRuntimeConfig({apiPort:r.api,consolePort:r.console}),info({message:[`Starting the Actor runtime (data directory: ${f})...`,``,` API: ${runtimeApiUrl(r.api)}`,` Console: ${runtimeConsoleUrl(r.console)}`,``,`Point the Apify CLI at the runtime with:`,...runtimeEnvExportLines(r).map(e=>t.white.bold(` ${e}`)),``,...runtimeSkillHintLines()].join(`
|
|
253
253
|
`)});let m=buildRuntimeRunArgs({image:i,dataDir:f,detach:this.flags.detach,hostSocketPath:s,ports:r,networkMode:l,securityOptions:u});run({message:`${a} ${m.join(` `)}`});let h=U(a,m,{stdio:`inherit`}),g=!1,_=cn.map(t=>{let handler=()=>{g=!0,h.kill(t)};return e.on(t,handler),()=>e.off(t,handler)});try{await h}catch(t){if(!g){error({message:`The Actor runtime exited with an error: ${t.shortMessage??t}`}),e.exitCode=1;return}}finally{for(let e of _)e()}this.flags.detach&&info({message:`The Actor runtime is running in the background. Stop it with 'apify runtime stop'.`})}};function portRole(e,t){return e===t.api?`API`:e===t.console?`Console`:``}function portLine({containerPort:e,protocol:t,hostAddress:n},r){let i=portRole(e,r);return` ${`${e}/${t}`.padEnd(10)} -> ${n}${i?` (${i})`:``}`}var RuntimeStatusCommand=class extends ApifyCommand{static name=`status`;static description=`Prints whether the Actor runtime is running, the ports it publishes, the host directory it keeps its data in, and which API the Apify CLI currently talks to.
|
|
254
254
|
Exits with code 1 when the runtime is not running, so scripts can test for it.`;static group=`Local Actor Development`;static examples=[{description:`Show what the Actor runtime is doing.`,command:`apify runtime status`},{description:`Read the status as JSON.`,command:`apify runtime status --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runtime-status`;static enableJsonFlag=!0;async run(){let n=await findRunningRuntimeEngine(),r=n?await inspectRuntimeContainer(n):null,i=isConnectedToActorRuntime(),a=overridingRuntimeEnvVars();if(this.flags.json){n||(e.exitCode=1),printJsonToStdout({running:!!n,engine:n,container:n?An:void 0,image:r?.image??(n?void 0:installedActorRuntimeImage()),status:r?.status,startedAt:r?.startedAt,dataDir:r?.dataDir,ports:r?.ports??[],connected:i,apiBaseUrl:resolveApiBaseUrl()??null,envOverrides:Object.fromEntries(a)});return}let s=[];if(!n)s.push(`Actor runtime: ${t.yellow(`not running`)}`,``,` Installed image: ${installedActorRuntimeImage()}`,``,`Start it with ${t.white.bold(`apify runtime start --detach`)}.`);else{s.push(`Actor runtime: ${t.green(r?.status??`running`)} on ${n} (container '${An}')`,``,` Image: ${r?.image??installedActorRuntimeImage()}`,` Data directory: ${r?.dataDir??`unknown`}`),r?.startedAt&&s.push(` Started at: ${r.startedAt}`),s.push(``,r?.ports.length?`Published ports:`:`Published ports: none`);let e=configuredRuntimePorts();s.push(...(r?.ports??[]).map(t=>portLine(t,e)))}s.push(``,`Apify CLI target:`),s.push(` ${i?`the Actor runtime (${t.white.bold(`apify runtime connect`)})`:`the Apify platform (connect with ${t.white.bold(`apify runtime connect`)})`}`),s.push(` API base URL: ${resolveApiBaseUrl()??`https://api.apify.com (default)`}`),a.length&&s.push(``,`Set in this shell, taking precedence over the connection above:`,...a.map(([e,t])=>` ${e}=${t}`)),n&&s.push(``,...runtimeSkillHintLines()),simpleLog({message:s.join(`
|
|
255
|
-
`)}),n||(e.exitCode=1)}},RuntimeStopCommand=class extends ApifyCommand{static name=`stop`;static description=`Stops the Actor runtime container started with 'apify runtime start --detach'.`;static group=`Local Actor Development`;static examples=[{description:`Stop the running Actor runtime.`,command:`apify runtime stop`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runtime-stop`;async run(){let t=await findRunningRuntimeEngine();if(!t){info({message:`The Actor runtime is not running.`});return}try{await execWithLog({cmd:t,args:[`stop`,An]})}catch{e.exitCode=1;return}success({message:`The Actor runtime was stopped.`})}},RuntimeIndexCommand=class extends ApifyCommand{static name=`runtime`;static description=[`Manages the Actor runtime, a self-contained local Apify platform running as a container on Docker or Podman.`,``,`Prerequisite: Docker or Podman must be installed and running. Follow the official documentation to set one up:`,``,` Docker Desktop (macOS, Windows, Linux desktop):`,` ${jn}`,` Docker Engine (Linux servers, headless):`,` https://docs.docker.com/engine/install/`,` Podman (rootful or rootless; its API socket must be served, e.g. via the podman.socket systemd unit):`,` ${Mn}`,``,`The first engine found on PATH is used, Docker before Podman. Set ${Bn}=docker or =podman to choose.`,``,`'apify runtime install' checks that the engine is available and pulls the runtime image, 'apify runtime start' runs it, and 'apify runtime status' says whether it is up.`,``,`The runtime publishes two ports on localhost, by default (move them with 'apify runtime start --api-port <port> --console-port <port>'):`,``,` ${`3333`.padEnd(5)} API ${In} (Apify API compatible endpoint)`,` ${`3000`.padEnd(5)} Console ${Ln} (web UI)`,``,`Run 'apify runtime connect' to send every Apify CLI command to the runtime instead of the Apify cloud, and 'apify runtime disconnect' to go back. The connection is remembered across terminals and does not touch your login.`,``,`These environment variables point the CLI (and the Apify SDKs and API clients that honour them) at the runtime for one shell only, and take precedence over the connection wherever they are set (shown for the default ports):`,``,...runtimeEnvExportLines().map(e=>` ${e}`),``,`Unset them to let 'apify runtime connect' decide where commands go.`,``,`Pointed at the runtime, 'apify push' also registers the pushed directory as the Actor's live dev folder, so runs pick up local edits without another push; 'apify call --no-dev-folder' runs from the built image alone.`].join(`
|
|
256
|
-
`);static group=`Local Actor Development`;static examples=[{description:`Start the runtime in the background.`,command:`apify runtime start --detach`},{description:`Point the CLI at the runtime and list the Actors it knows about.`,command:`apify runtime connect && apify actors ls`},{description:`Point the CLI at the runtime for a single command instead.`,command:`APIFY_CLIENT_BASE_URL=${In} apify actors ls`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runtime`;static subcommands=[RuntimeInstallCommand,RuntimeStartCommand,RuntimeStopCommand,RuntimeStatusCommand,RuntimeConnectCommand,RuntimeDisconnectCommand,RuntimeSkillCommand];async run(){this.printHelp()}},SecretsAddCommand=class extends ApifyCommand{static name=`add`;static description=`Adds a new secret to '~/.apify' for use in Actor environment variables.`;static examples=[{description:`Add a secret named "mySecret". Reference it in .actor/actor.json as "@mySecret".`,command:`apify secrets add mySecret TopSecretValue123`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-add`;static args={name:X.string({required:!0,description:`Name of the secret.`}),value:X.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const Yi=new Z({allColumns:[`Secret Name`],mandatoryColumns:[`Secret Name`],columnAlignments:{"Secret Name":`left`}});var SecretsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all secret keys stored in your local configuration.`;static examples=[{description:`List the names of all locally stored secrets.`,command:`apify secrets ls`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-ls`;static enableJsonFlag=!0;async run(){let{json:e}=this.flags,n=getSecretsFile(),r=Object.keys(n);if(e){printJsonToStdout({keys:r});return}if(r.length===0){info({message:`You don't have any secrets stored locally. Use 'apify secrets add' to add a secret.`,stdout:!0});return}for(let e of r)Yi.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:Yi.render(1),stdout:!0})}},SecretsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently deletes a secret from your stored credentials.`;static examples=[{description:`Delete a locally stored secret by name.`,command:`apify secrets rm mySecret`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-rm`;static args={name:X.string({required:!0,description:`Name of the secret.`})};async run(){let{name:e}=this.args;removeSecret(e)}},SecretsIndexCommand=class extends ApifyCommand{static name=`secrets`;static description=`Manage locally stored secrets that can be referenced from '${G}' environment variables using the "@" prefix (e.g. "@mySecret"). Secrets are uploaded alongside the Actor and stored encrypted on the Apify platform.`;static group=`Authentication`;static examples=[{description:`Store a secret called "mySecret".`,command:`apify secrets add mySecret TopSecretValue123`},{description:`Reference the secret from .actor/actor.json using the "@" prefix, e.g. "environmentVariables": { "SECRET_ENV_VAR": "@mySecret" }, then push as usual.`,command:`apify push`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets`;static subcommands=[SecretsAddCommand,SecretsLsCommand,SecretsRmCommand];async run(){this.printHelp()}},TaskPublishCommand=class extends ApifyCommand{static name=`publish`;static enableProfileFlag=!0;static description=`Publishes the task on its public landing page.
|
|
255
|
+
`)}),n||(e.exitCode=1)}},RuntimeStopCommand=class extends ApifyCommand{static name=`stop`;static description=`Stops the Actor runtime container started with 'apify runtime start --detach'.`;static group=`Local Actor Development`;static examples=[{description:`Stop the running Actor runtime.`,command:`apify runtime stop`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runtime-stop`;async run(){let t=await findRunningRuntimeEngine();if(!t){info({message:`The Actor runtime is not running.`});return}try{await execWithLog({cmd:t,args:[`stop`,An]})}catch{e.exitCode=1;return}success({message:`The Actor runtime was stopped.`})}},RuntimeIndexCommand=class extends ApifyCommand{static name=`runtime`;static description=[`Manages the Actor runtime, a self-contained local Apify platform running as a container on Docker or Podman.`,``,`The Actor runtime is experimental: these commands, and what they add to other commands, may change in any release.`,``,`Prerequisite: Docker or Podman must be installed and running. Follow the official documentation to set one up:`,``,` Docker Desktop (macOS, Windows, Linux desktop):`,` ${jn}`,` Docker Engine (Linux servers, headless):`,` https://docs.docker.com/engine/install/`,` Podman (rootful or rootless; its API socket must be served, e.g. via the podman.socket systemd unit):`,` ${Mn}`,``,`The first engine found on PATH is used, Docker before Podman. Set ${Bn}=docker or =podman to choose.`,``,`'apify runtime install' checks that the engine is available and pulls the runtime image, 'apify runtime start' runs it, and 'apify runtime status' says whether it is up.`,``,`The runtime publishes two ports on localhost, by default (move them with 'apify runtime start --api-port <port> --console-port <port>'):`,``,` ${`3333`.padEnd(5)} API ${In} (Apify API compatible endpoint)`,` ${`3000`.padEnd(5)} Console ${Ln} (web UI)`,``,`Run 'apify runtime connect' to send every Apify CLI command to the runtime instead of the Apify cloud, and 'apify runtime disconnect' to go back. The connection is remembered across terminals and does not touch your login.`,``,`These environment variables point the CLI (and the Apify SDKs and API clients that honour them) at the runtime for one shell only, and take precedence over the connection wherever they are set (shown for the default ports):`,``,...runtimeEnvExportLines().map(e=>` ${e}`),``,`Unset them to let 'apify runtime connect' decide where commands go.`,``,`Pointed at the runtime, 'apify push' also registers the pushed directory as the Actor's live dev folder, so runs pick up local edits without another push; 'apify call --no-dev-folder' runs from the built image alone.`].join(`
|
|
256
|
+
`);static group=`Local Actor Development`;static experimental=!0;static examples=[{description:`Start the runtime in the background.`,command:`apify runtime start --detach`},{description:`Point the CLI at the runtime and list the Actors it knows about.`,command:`apify runtime connect && apify actors ls`},{description:`Point the CLI at the runtime for a single command instead.`,command:`APIFY_CLIENT_BASE_URL=${In} apify actors ls`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runtime`;static subcommands=[RuntimeInstallCommand,RuntimeStartCommand,RuntimeStopCommand,RuntimeStatusCommand,RuntimeConnectCommand,RuntimeDisconnectCommand,RuntimeSkillCommand];async run(){this.printHelp()}},SecretsAddCommand=class extends ApifyCommand{static name=`add`;static description=`Adds a new secret to '~/.apify' for use in Actor environment variables.`;static examples=[{description:`Add a secret named "mySecret". Reference it in .actor/actor.json as "@mySecret".`,command:`apify secrets add mySecret TopSecretValue123`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-add`;static args={name:X.string({required:!0,description:`Name of the secret.`}),value:X.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const Yi=new Z({allColumns:[`Secret Name`],mandatoryColumns:[`Secret Name`],columnAlignments:{"Secret Name":`left`}});var SecretsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all secret keys stored in your local configuration.`;static examples=[{description:`List the names of all locally stored secrets.`,command:`apify secrets ls`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-ls`;static enableJsonFlag=!0;async run(){let{json:e}=this.flags,n=getSecretsFile(),r=Object.keys(n);if(e){printJsonToStdout({keys:r});return}if(r.length===0){info({message:`You don't have any secrets stored locally. Use 'apify secrets add' to add a secret.`,stdout:!0});return}for(let e of r)Yi.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:Yi.render(1),stdout:!0})}},SecretsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently deletes a secret from your stored credentials.`;static examples=[{description:`Delete a locally stored secret by name.`,command:`apify secrets rm mySecret`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-rm`;static args={name:X.string({required:!0,description:`Name of the secret.`})};async run(){let{name:e}=this.args;removeSecret(e)}},SecretsIndexCommand=class extends ApifyCommand{static name=`secrets`;static description=`Manage locally stored secrets that can be referenced from '${G}' environment variables using the "@" prefix (e.g. "@mySecret"). Secrets are uploaded alongside the Actor and stored encrypted on the Apify platform.`;static group=`Authentication`;static examples=[{description:`Store a secret called "mySecret".`,command:`apify secrets add mySecret TopSecretValue123`},{description:`Reference the secret from .actor/actor.json using the "@" prefix, e.g. "environmentVariables": { "SECRET_ENV_VAR": "@mySecret" }, then push as usual.`,command:`apify push`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets`;static subcommands=[SecretsAddCommand,SecretsLsCommand,SecretsRmCommand];async run(){this.printHelp()}},TaskPublishCommand=class extends ApifyCommand{static name=`publish`;static enableProfileFlag=!0;static description=`Publishes the task on its public landing page.
|
|
257
257
|
The task must belong to a public Actor and have its public display configuration set up on the task Publication tab in Apify Console. Requires write access to the task and to its Actor.`;static examples=[{description:`Publish a task by name.`,command:`apify task publish my-task`},{description:`Publish a task by full name.`,command:`apify task publish username/my-task`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-publish`;static args={taskId:X.string({required:!0,description:`Name of the task to publish. For example, "my-task" or "username/my-task".`})};async run(){let n=await getLoggedClientOrThrow(),r=await getCurrentUserInfo(),i=r.username||r.id,{taskId:a}=this.args,s=a.includes(`/`)?a:`${i}/${a.toLowerCase()}`,c=n.task(s),l=await c.get();if(!l){error({message:`Cannot find Task with name '${a}' in your account.`}),e.exitCode=250;return}try{await c.publish(),success({message:`Task ${t.yellow(l.name)} has been published.`,stdout:!0})}catch(n){let r=n;error({message:`Failed to publish task ${t.yellow(l.name)}\n ${r.message||r}`}),e.exitCode=1}}},TaskRunCommand=class extends ApifyCommand{static name=`run`;static enableProfileFlag=!0;static description=`Executes predefined Actor task remotely using local key-value store for input.
|
|
258
258
|
Customize with --memory and --timeout flags.
|
|
259
259
|
`;static examples=[{description:`Run a task by name.`,command:`apify task run my-task`},{description:`Run a task by full ID with custom memory and timeout.`,command:`apify task run username/my-task --memory 4096 --timeout 600`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-run`;static flags=SharedRunOnCloudFlags(`Task`);static enableJsonFlag=!0;static args={taskId:X.string({required:!0,description:`Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").`})};async run(){let e=await getLoggedClientOrThrow(),t=await getCurrentUserInfo(),n=t.username||t.id,{id:r,userFriendlyId:i,title:a}=await this.resolveTaskId(e,n),s={waitForFinish:2};this.flags.build&&(s.build=this.flags.build),this.flags.timeout&&(s.timeout=this.flags.timeout),this.flags.memory&&(s.memory=this.flags.memory);let c,l=runActorOrTaskOnCloud(e,{actorOrTaskData:{id:r,userFriendlyId:i,title:a},runOptions:s,type:`Task`,waitForRunToFinish:!0,printRunLogs:!0,suppressFinalStatus:!0});for await(let e of l)c=e;await finalizeRun({apifyClient:e,run:c,operation:`task-run`,json:this.flags.json})}async resolveTaskId(e,t){let{taskId:n}=this.args;if(n?.includes(`/`)){let r=await e.task(n).get();if(!r)throw Error(`Cannot find Task with ID '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}if(n){let r=await e.task(`${t}/${n.toLowerCase()}`).get();if(!r)throw Error(`Cannot find Task with name '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}throw Error(`Please provide a valid Task ID or name.`)}},TaskUnpublishCommand=class extends ApifyCommand{static name=`unpublish`;static enableProfileFlag=!0;static description=`Unpublishes the task from its public landing page.
|
|
@@ -266,4 +266,4 @@ When no path is provided, validates all schemas found in '${G}':
|
|
|
266
266
|
- Dataset schema (from "storages.dataset")
|
|
267
267
|
- Output schema (from "output")
|
|
268
268
|
- 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 '${G}'.`})};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 '${G}'`}`});let t=new cr({strict:!1});bt(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 '${G}'`}`}),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 '${G}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const Zi=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,RuntimeIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,TemplatesIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],Qi=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Zi as n,processVersionCheck as r,Qi as t};
|
|
269
|
-
//# sourceMappingURL=_register-
|
|
269
|
+
//# sourceMappingURL=_register-DE0cvC47.js.map
|