apify-cli 1.6.2-beta.15 → 1.6.2-beta.17

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,4 +1,4 @@
1
- import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import{inspect as a,parseArgs as s,promisify as c}from"node:util";import{gt as l,gte as u,minVersion as f,satisfies as p}from"semver";import{appendFileSync as m,constants as h,copyFileSync as g,createWriteStream as _,existsSync as v,fstat as y,mkdirSync as b,openSync as x,readFileSync as S,readdirSync as C,realpathSync as ee,renameSync as w,rmSync as T,statSync as E,unlinkSync as te,writeFileSync as D}from"node:fs";import O,{basename as ne,dirname as k,isAbsolute as re,join as A,relative as ie,resolve as ae,sep as oe}from"node:path";import se from"string-width";import ce from"strip-ansi";import{once as le}from"node:events";import{homedir as ue,platform as de}from"node:os";import fe from"ci-info";import{ACTOR_ENV_VARS as j,ACTOR_JOB_STATUSES as M,ACTOR_JOB_TERMINAL_STATUSES as pe,ACTOR_NAME as me,ACTOR_SOURCE_TYPES as he,APIFY_ENV_VARS as N,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{createHmacSignature as we,cryptoRandomObjectId as Te}from"@apify/utilities";import{execSync as Ee,spawn as De}from"node:child_process";import{access as Oe,lstat as ke,mkdir as P,readFile as F,readdir as I,rename as Ae,stat as L,symlink as je,unlink as Me,writeFile as R}from"node:fs/promises";import{get as Ne}from"node:https";import{finished as Pe,pipeline as Fe}from"node:stream/promises";import{DurationFormatter as Ie,Time as Le,TimeTypes as z}from"@sapphire/duration";import{Timestamp as Re}from"@sapphire/timestamp";import ze from"adm-zip";import Be from"ajv/dist/2019.js";import{ApifyClient as Ve,DownloadItemsFormat as B}from"apify-client";import He from"archiver";import Ue,{AxiosHeaders as We}from"axios";import Ge from"escape-string-regexp";import Ke from"ignore";import{getEncoding as qe}from"istextorbinary";import Je,{Mime as Ye}from"mime";import Xe from"mime/types/other.js";import Ze from"mime/types/standard.js";import{glob as Qe}from"tinyglobby";import{rimraf as $e}from"rimraf";import{Result as et,err as tt,none as V,ok as H,some as nt}from"@sapphire/result";import rt from"configparser";import it from"@inquirer/input";import at from"is-ci";import{execa as ot}from"execa";import st from"which";import{calculateRunDynamicMemory as ct}from"@apify/actor-memory-expression";import{Separator as lt,createPrompt as ut,isEnterKey as dt,makeTheme as ft,useKeypress as pt,usePrefix as mt,useState as ht}from"@inquirer/core";import{MemoryStorage as gt}from"@crawlee/memory-storage";import{compile as _t}from"json-schema-to-typescript";import{cloneDeep as vt}from"es-toolkit";import{validateInputSchema as yt,validateInputUsingValidator as bt}from"@apify/input_schema";import{getDatasetSchemaValidator as xt,getKeyValueStoreSchemaValidator as St,getOutputSchemaValidator as Ct}from"@apify/json_schemas";import wt from"cli-table3";import Tt from"jju";import Et from"tiged";import Dt from"open";import{fetchManifest as Ot,manifestUrl as kt,wrapperManifestUrl as At}from"@apify/actor-templates";import jt from"computer-name";import Mt from"cors";import Nt from"express";import Pt from"@inquirer/password";import Ft from"@inquirer/select";import It from"node:assert";import{ReadStream as Lt}from"node:tty";import Rt from"detect-indent";import{fileURLToPath as zt}from"node:url";import Bt from"@root/walk";import Vt from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function link(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.blue(e.message),e.url]})}function detectInstallMethod(){if(process.env.APIFY_CLI_MARKED_INSTALL_METHOD)return process.env.APIFY_CLI_MARKED_INSTALL_METHOD;if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=ee(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){return process.versions.bun?{runtime:`bun`,version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:`deno`,version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:`node`,version:process.versions.node}}let Ht=null;function useCLIMetadata(){if(Ht)return Ht;let e=detectInstallMethod(),t=getRuntimeInfo();return Ht={version:`1.6.2-beta.15`,hash:`8756c2295095bdfd9757174a18b82051e1faddd3`,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform===`win32`?`windows`:process.platform,runtime:t,extraRuntimeData:t.nodeVersion?`(emulating node ${t.nodeVersion})`:``,installMethod:e,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${t.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:``}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes(`beta`)||this.version===`0.0.0`}},e===`bundle`&&(Ht.installPath=k(process.execPath)),Ht}let Ut;function getMaxLineWidth(){if(Ut)return Ut;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Ut=e;else if(!process.stdout.isTTY)Ut=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Ut=e<1?80:e<40?40:e}return Ut}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=this.command.interactive?`${t.yellow(`[INTERACTIVE]`)} `:``;this.command.shortDescription?e.push(`${n}${this.command.shortDescription}`,``):this.command.description&&e.push(`${n}${this.command.description.split(`
1
+ import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import{inspect as a,parseArgs as s,promisify as c}from"node:util";import{gt as l,gte as u,minVersion as f,satisfies as p}from"semver";import{appendFileSync as m,constants as h,copyFileSync as g,createWriteStream as _,existsSync as v,fstat as y,mkdirSync as b,openSync as x,readFileSync as S,readdirSync as C,realpathSync as ee,renameSync as w,rmSync as T,statSync as E,unlinkSync as te,writeFileSync as D}from"node:fs";import O,{basename as ne,dirname as k,isAbsolute as re,join as A,relative as ie,resolve as ae,sep as oe}from"node:path";import se from"string-width";import ce from"strip-ansi";import{once as le}from"node:events";import{homedir as ue,platform as de}from"node:os";import fe from"ci-info";import{ACTOR_ENV_VARS as j,ACTOR_JOB_STATUSES as M,ACTOR_JOB_TERMINAL_STATUSES as pe,ACTOR_NAME as me,ACTOR_SOURCE_TYPES as he,APIFY_ENV_VARS as N,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{createHmacSignature as we,cryptoRandomObjectId as Te}from"@apify/utilities";import{execSync as Ee,spawn as De}from"node:child_process";import{access as Oe,lstat as ke,mkdir as P,readFile as F,readdir as I,rename as Ae,stat as L,symlink as je,unlink as Me,writeFile as R}from"node:fs/promises";import{get as Ne}from"node:https";import{finished as Pe,pipeline as Fe}from"node:stream/promises";import{DurationFormatter as Ie,Time as Le,TimeTypes as z}from"@sapphire/duration";import{Timestamp as Re}from"@sapphire/timestamp";import ze from"adm-zip";import Be from"ajv/dist/2019.js";import{ApifyClient as Ve,DownloadItemsFormat as B}from"apify-client";import He from"archiver";import Ue,{AxiosHeaders as We}from"axios";import Ge from"escape-string-regexp";import Ke from"ignore";import{getEncoding as qe}from"istextorbinary";import Je,{Mime as Ye}from"mime";import Xe from"mime/types/other.js";import Ze from"mime/types/standard.js";import{glob as Qe}from"tinyglobby";import{rimraf as $e}from"rimraf";import{Result as et,err as tt,none as V,ok as H,some as nt}from"@sapphire/result";import rt from"configparser";import it from"@inquirer/input";import at from"is-ci";import{execa as ot}from"execa";import st from"which";import{calculateRunDynamicMemory as ct}from"@apify/actor-memory-expression";import{Separator as lt,createPrompt as ut,isEnterKey as dt,makeTheme as ft,useKeypress as pt,usePrefix as mt,useState as ht}from"@inquirer/core";import{MemoryStorage as gt}from"@crawlee/memory-storage";import{compile as _t}from"json-schema-to-typescript";import{cloneDeep as vt}from"es-toolkit";import{validateInputSchema as yt,validateInputUsingValidator as bt}from"@apify/input_schema";import{getDatasetSchemaValidator as xt,getKeyValueStoreSchemaValidator as St,getOutputSchemaValidator as Ct}from"@apify/json_schemas";import wt from"cli-table3";import Tt from"jju";import Et from"tiged";import Dt from"open";import{fetchManifest as Ot,manifestUrl as kt,wrapperManifestUrl as At}from"@apify/actor-templates";import jt from"computer-name";import Mt from"cors";import Nt from"express";import Pt from"@inquirer/password";import Ft from"@inquirer/select";import It from"node:assert";import{ReadStream as Lt}from"node:tty";import Rt from"detect-indent";import{fileURLToPath as zt}from"node:url";import Bt from"@root/walk";import Vt from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function link(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.blue(e.message),e.url]})}function detectInstallMethod(){if(process.env.APIFY_CLI_MARKED_INSTALL_METHOD)return process.env.APIFY_CLI_MARKED_INSTALL_METHOD;if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=ee(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){return process.versions.bun?{runtime:`bun`,version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:`deno`,version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:`node`,version:process.versions.node}}let Ht=null;function useCLIMetadata(){if(Ht)return Ht;let e=detectInstallMethod(),t=getRuntimeInfo();return Ht={version:`1.6.2-beta.17`,hash:`a4ac91501fd190d267c5883cd8b40b0ec2ee0230`,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform===`win32`?`windows`:process.platform,runtime:t,extraRuntimeData:t.nodeVersion?`(emulating node ${t.nodeVersion})`:``,installMethod:e,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${t.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:``}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes(`beta`)||this.version===`0.0.0`}},e===`bundle`&&(Ht.installPath=k(process.execPath)),Ht}let Ut;function getMaxLineWidth(){if(Ut)return Ut;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Ut=e;else if(!process.stdout.isTTY)Ut=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Ut=e<1?80:e<40?40:e}return Ut}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=this.command.interactive?`${t.yellow(`[INTERACTIVE]`)} `:``;this.command.shortDescription?e.push(`${n}${this.command.shortDescription}`,``):this.command.description&&e.push(`${n}${this.command.description.split(`
2
2
  `)[0]}`,``)}pushDescription(e){if(!this.command.description)return;e.push(t.bold(`DESCRIPTION`));let r=n(i(this.command.description,getMaxLineWidth()-2,{trim:!1}),2);e.push(r),e.push(``)}pushExamples(e){let{examples:r}=this.command;if(r?.length){e.push(t.bold(`EXAMPLES`));for(let a of r){if(a.description){let r=n(i(a.description,getMaxLineWidth()-4,{trim:!1}).split(`
3
3
  `).map(e=>`# ${e}`).join(`
4
4
  `),2);e.push(t.dim(r))}e.push(` $ ${this.normalizeExampleCommand(a.command)}`),e.push(``)}}}normalizeExampleCommand(e){let t=this.entrypoint.split(` `);if(t.length<2)return e;let n=t[t.length-1],r=`${t.slice(0,-1).join(` `)} `,i=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=e;return a.startsWith(`${n} `)&&(a=`${r}${a}`),a=a.replace(RegExp(`\\|\\s+${i}\\s`,`g`),`| ${r}${n} `),a}pushInteractiveNote(e){if(!this.command.interactive)return;e.push(t.bold(`NOTE`));let r=n(i(this.command.interactiveNote||`This command prompts the user for input. To run non-interactively (e.g. in CI or from an AI agent), pass all required arguments and flags explicitly.`,getMaxLineWidth()-2,{trim:!1}),2);e.push(r),e.push(``)}pushLearnMore(e){this.command.docsUrl&&(e.push(t.bold(`LEARN MORE`)),e.push(` ${this.command.docsUrl}`),e.push(``))}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:n}){se(e.join(` `).split(`
@@ -86,9 +86,9 @@ For platform-level management (deploy, list, call Actors), see 'apify actors' (p
86
86
  `))}throw e}if(i.u(useAbortJobOnSignal({apifyClient:n,kind:`run`,jobId:v.id,runType:l,silent:p})),yield v,!p&&h)try{await outputJobLog({job:v,timeoutMillis:u,apifyClient:n})===`timeouts`?console.error(`\n${t.gray(`Timeout for printing logs was hit, there may be future logs.`)}\n`):console.error()}catch(e){warning({message:`Can not get log:`}),console.error(e)}if(v=await n.run(v.id).get(),m)for(;!Gn.includes(v.status)&&(v=await n.run(v.id).get(),!Gn.includes(v.status));)await new Promise(e=>{setTimeout(e,1e3)});p||(v.status===M.SUCCEEDED?success({message:`${l} finished.`}):v.status===M.RUNNING?warning({message:`${l} is still running!`}):v.status===M.ABORTED||v.status===M.ABORTING?(warning({message:`${l} was aborted!`}),e.exitCode=3):(error({message:`${l} failed!`}),e.exitCode=1)),yield v}catch(e){i.e=e}finally{i.d()}}const SharedRunOnCloudFlags=e=>({build:Y.string({char:`b`,description:`Tag or number of the build to run (e.g. "latest" or "1.2.34").`,required:!1}),timeout:Y.integer({char:`t`,description:`Timeout for the ${e} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:Y.integer({char:`m`,description:`Amount of memory allocated for the ${e} run, in megabytes.`,required:!1})});var Kn=class ActorsCallCommand extends ApifyCommand{static name=`call`;static description=`Executes Actor remotely using your authenticated account.
87
87
  Reads input from local key-value store by default.`;static group=`Apify Console`;static examples=[{description:`Call the Actor defined in the current directory (from .actor/actor.json).`,command:`apify call`},{description:`Call a specific Actor by its full name.`,command:`apify call apify/hello-world`},{description:`Call an Actor with inline JSON input.`,command:`apify call apify/hello-world --input '{"url":"https://example.com"}'`},{description:`Call an Actor with input from a file and print the dataset on success.`,command:`apify call apify/web-scraper --input-file input.json --output-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-call`;static flags={...SharedRunOnCloudFlags(`Actor`),input:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.string({char:`f`,description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:[`input`]}),silent:Y.boolean({char:`s`,description:`Prevents printing the logs of the Actor run to the console.`,default:!1}),"output-dataset":Y.boolean({char:`o`,description:`Prints out the entire default dataset on successful run of the Actor.`})};static enableJsonFlag=!0;static args={actorId:Z.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${W}' file.`})};async run(){let n=e.cwd(),r=getLocalConfig(n)||{},i=await getLoggedClientOrThrow(),a=await getLocalUserInfo(),s=a.username||a.id;if(this.flags.json&&this.flags.outputDataset){error({message:`You cannot use both the --json and --output-dataset flags when running this command.`}),e.exitCode=5;return}let{id:c,userFriendlyId:l,actorData:u}=await ActorsCallCommand.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={waitForFinish:2};this.flags.build&&(f.build=this.flags.build),this.flags.timeout&&(f.timeout=this.flags.timeout),this.flags.memory&&(f.memory=this.flags.memory);let p=await getInputOverride(n,this.flags.input,this.flags.inputFile);if(p===!1)return;let m=!1,h,g,_,v=runActorOrTaskOnCloud(i,{actorOrTaskData:{id:c,userFriendlyId:l},runOptions:f,type:`Actor`,inputOverride:p?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0});for await(let e of v)if(h=e,!m&&(m=!0,!this.flags.silent)){g=`https://console.apify.com/actors/${c}/runs/${e.id}`,_=`https://console.apify.com/storage/datasets/${e.defaultDatasetId}`;let n=[`${t.yellow(`Started`)}: ${G.display(e.startedAt)}`];e.containerUrl&&n.push(`${t.yellow(`Container URL`)}: ${t.blue(e.containerUrl)}`);let r=h.buildNumber.split(`.`).slice(0,2).join(`.`),i=u.versions.find(e=>e.versionNumber===r),a=Object.entries(u.taggedBuilds??{}).find(([,t])=>t.buildNumber===e.buildNumber)?.[0],s=[`${t.yellow(`Build`)}:`,t.cyan(h.buildNumber)];a?s.push(`(${t.yellow(a)})`):s.push(`(${t.gray(`N/A`)})`),i&&s.push(`| ${t.gray(`Actor version:`)} ${t.cyan(i.versionNumber)} (${t.yellow(i.buildTag)})`),n.push(s.join(` `)),n.push(`${t.yellow(`Timeout`)}: ${h.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),n.push(`${t.yellow(`Memory`)}: ${h.options.memoryMbytes} MB`),n.push(`${t.blue(`View on Apify Console`)}: ${g}`,``),simpleLog({message:n.join(`
88
88
  `),stdout:!this.flags.json})}if(this.flags.json){printJsonToStdout(h);return}if(this.flags.silent||simpleLog({message:[``,`${t.blue(`Export results`)}: ${_}`,`${t.blue(`View on Apify Console`)}: ${g}`].join(`
89
- `),stdout:!0}),this.flags.outputDataset){let e=h.defaultDatasetId,t,n=4;do{if(t=await i.dataset(e).get(),t?.itemCount)break;await new Promise(e=>{setTimeout(e,250)})}while(n--);let r=await i.dataset(e).downloadItems(B.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 qn={[-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 Jn=process.stdout.columns??100,Yn=Symbol.for(`@apify/cli:responsive-table:skip-column`);var Q=class ResponsiveTable{options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=ResponsiveTable.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,n=generateHeaderColors(t.length),r=e===0||e===2,i=qn[e],a=[],s=[],c=[];for(let e of t)this.options.hiddenColumns?.includes(e)||this.rows.some(t=>t[e]===Yn)||(a.push(this.options.columnAlignments?.[e]||`left`),ResponsiveTable.isSmallTerminal()?(s.push(this.options.breakpointOverrides?.small?.[e]?.label??e),c.push(this.options.breakpointOverrides?.small?.[e]?.valueFrom??e)):(s.push(e),c.push(e)));let l=new wt({head:s,style:{head:n,compact:r},colAligns:a,chars:i});for(let e of this.rows){let t=c.map(t=>e[t]);l.push(t)}return l.toString()}static isSmallTerminal(){return Jn<100}};const Xn=`​​`,Zn=new Q({allColumns:[`​`,Xn],mandatoryColumns:[`​`,Xn],columnAlignments:{"​":`left`,[Xn]:`right`}});var ActorsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Get information about an Actor.`;static examples=[{description:`Print summary information about an Actor.`,command:`apify actors info apify/hello-world`},{description:`Print the Actor README only.`,command:`apify actors info apify/hello-world --readme`},{description:`Print the Actor input schema as JSON.`,command:`apify actors info apify/hello-world --input`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-info`;static flags={readme:Y.boolean({description:`Return the Actor README.`,exclusive:[`input`]}),input:Y.boolean({description:`Return the Actor input schema.`,exclusive:[`readme`]})};static args={actorId:Z.string({description:`The ID of the Actor to return information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:n,input:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),s=await resolveActorContext({providedActorNameOrId:e,client:a});if(!s.valid){error({message:`${s.reason}. Please specify the Actor ID.`,stdout:!0});return}let c=await a.actor(s.id).get();c.actorMaker=await a.user(c.userId).get();for(let e of Object.values(c.taggedBuilds??{}))e.buildId&&(e.build=await a.build(e.buildId).get());if(i){printJsonToStdout(c);return}let l=c.taggedBuilds?.latest;if(n){if(!l){error({message:`No README found for this Actor.`,stdout:!0});return}if(!l.build?.readme){error({message:`No README found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.readme,stdout:!0});return}if(r){if(!l){error({message:`No input schema found for this Actor.`,stdout:!0});return}if(!l.build?.inputSchema){error({message:`No input schema found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.inputSchema,stdout:!0});return}let u=[`Information about Actor ${t.yellow(`${c.username}/${c.name}`)} (${t.gray(c.id)})`,``];c.title&&u.push(`${t.yellow(`Title:`)} ${t.bold(c.title)}`),c.description&&u.push(`${t.yellow(`Description:`)} ${c.description}`),u.push(`${t.yellow(`Created at:`)} ${t.cyan(G.display(c.createdAt))} ${t.gray(`|`)} ${t.yellow(`Updated at:`)} ${t.cyan(G.display(c.modifiedAt))}`),c.actorMaker&&(u.push(``,`${t.yellow(`Made by:`)} ${t.cyan(c.actorMaker.profile.name??c.actorMaker.username)}`),Reflect.get(c,`isCritical`)&&(u[u.length-1]+=` ${t.bgGray(`Maintained by Apify`)}`)),c.isPublic?u.push(``,`${t.yellow(`Actor is`)} ${t.green(`PUBLIC`)}`):u.push(``,`${t.yellow(`Actor is`)} ${t.cyan(`PRIVATE`)}`),c.isDeprecated&&u.push(``,`${t.yellow(`Actor is`)} ${t.red(`DEPRECATED`)}`);let f=Reflect.get(c,`pricingInfos`);if(f?.length){let e=f.at(-1);switch(e.pricingModel){case`FLAT_PRICE_PER_MONTH`:if(u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${e.pricePerUnitUsd}/month + usage`)}`),e.trialMinutes){let n=e.trialMinutes*60*1e3,r=Cn.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)Zn.pushRow({"​":e.eventTitle,[Xn]:t.bold(`$${e.eventPriceUsd.toFixed(2)}`)});let r=Zn.render(0).split(`
89
+ `),stdout:!0}),this.flags.outputDataset){let e=h.defaultDatasetId,t,n=4;do{if(t=await i.dataset(e).get(),t?.itemCount)break;await new Promise(e=>{setTimeout(e,250)})}while(n--);let r=await i.dataset(e).downloadItems(B.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 qn={[-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 Jn=process.stdout.columns??100,Yn=Symbol.for(`@apify/cli:responsive-table:skip-column`);var Q=class ResponsiveTable{options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=ResponsiveTable.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,n=generateHeaderColors(t.length),r=e===0||e===2,i=qn[e],a=[],s=[],c=[];for(let e of t)this.options.hiddenColumns?.includes(e)||this.rows.some(t=>t[e]===Yn)||(a.push(this.options.columnAlignments?.[e]||`left`),ResponsiveTable.isSmallTerminal()?(s.push(this.options.breakpointOverrides?.small?.[e]?.label??e),c.push(this.options.breakpointOverrides?.small?.[e]?.valueFrom??e)):(s.push(e),c.push(e)));let l=new wt({head:s,style:{head:n,compact:r},colAligns:a,chars:i});for(let e of this.rows){let t=c.map(t=>e[t]);l.push(t)}return l.toString()}static isSmallTerminal(){return Jn<100}};function formatEventPrice(e){return e===0?`$0.00`:e>=.01?`$${e.toFixed(2)}`:`$${Number(e.toPrecision(2))}`}const Xn=`​​`,Zn=new Q({allColumns:[`​`,Xn],mandatoryColumns:[`​`,Xn],columnAlignments:{"​":`left`,[Xn]:`right`}});var ActorsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Get information about an Actor.`;static examples=[{description:`Print summary information about an Actor.`,command:`apify actors info apify/hello-world`},{description:`Print the Actor README only.`,command:`apify actors info apify/hello-world --readme`},{description:`Print the Actor input schema as JSON.`,command:`apify actors info apify/hello-world --input`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-info`;static flags={readme:Y.boolean({description:`Return the Actor README.`,exclusive:[`input`]}),input:Y.boolean({description:`Return the Actor input schema.`,exclusive:[`readme`]})};static args={actorId:Z.string({description:`The ID of the Actor to return information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:n,input:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),s=await resolveActorContext({providedActorNameOrId:e,client:a});if(!s.valid){error({message:`${s.reason}. Please specify the Actor ID.`,stdout:!0});return}let c=await a.actor(s.id).get();c.actorMaker=await a.user(c.userId).get();for(let e of Object.values(c.taggedBuilds??{}))e.buildId&&(e.build=await a.build(e.buildId).get());if(i){printJsonToStdout(c);return}let l=c.taggedBuilds?.latest;if(n){if(!l){error({message:`No README found for this Actor.`,stdout:!0});return}if(!l.build?.readme){error({message:`No README found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.readme,stdout:!0});return}if(r){if(!l){error({message:`No input schema found for this Actor.`,stdout:!0});return}if(!l.build?.inputSchema){error({message:`No input schema found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.inputSchema,stdout:!0});return}let u=[`Information about Actor ${t.yellow(`${c.username}/${c.name}`)} (${t.gray(c.id)})`,``];c.title&&u.push(`${t.yellow(`Title:`)} ${t.bold(c.title)}`),c.description&&u.push(`${t.yellow(`Description:`)} ${c.description}`),u.push(`${t.yellow(`Created at:`)} ${t.cyan(G.display(c.createdAt))} ${t.gray(`|`)} ${t.yellow(`Updated at:`)} ${t.cyan(G.display(c.modifiedAt))}`),c.actorMaker&&(u.push(``,`${t.yellow(`Made by:`)} ${t.cyan(c.actorMaker.profile.name??c.actorMaker.username)}`),Reflect.get(c,`isCritical`)&&(u[u.length-1]+=` ${t.bgGray(`Maintained by Apify`)}`)),c.isPublic?u.push(``,`${t.yellow(`Actor is`)} ${t.green(`PUBLIC`)}`):u.push(``,`${t.yellow(`Actor is`)} ${t.cyan(`PRIVATE`)}`),c.isDeprecated&&u.push(``,`${t.yellow(`Actor is`)} ${t.red(`DEPRECATED`)}`);let f=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=Cn.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`,Zn.pushRow({"​":e.eventTitle,[Xn]:t.bold(i)})}let r=Zn.render(0).split(`
90
90
  `);r.splice(1,1),u.push(r.join(`
91
- `));break}case`FREE`:u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);break;default:u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Unknown pricing model (${t.yellow(e.pricingModel)})`)}`)}}else u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);if((c.seoTitle||c.seoDescription)&&(u.push(``,t.yellow(`SEO information:`)),c.seoTitle&&u.push(` ${t.yellow(`Title:`)} ${c.seoTitle}`),c.seoDescription&&u.push(` ${t.yellow(`Description:`)} ${c.seoDescription}`)),c.taggedBuilds){u.push(``,t.yellow(`Builds:`));let e=c.taggedBuilds.latest;e&&u.push(` ${t.yellow(`-`)} ${t.cyan(e.buildNumber)} ${t.gray(`/`)} ${t.yellow(`latest`)}`);for(let[e,n]of Object.entries(c.taggedBuilds))e!==`latest`&&u.push(` ${t.yellow(`-`)} ${t.cyan(n.buildNumber)} ${t.gray(`/`)} ${t.yellow(e)}`)}simpleLog({message:u.join(`
91
+ `));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`)}`);if((c.seoTitle||c.seoDescription)&&(u.push(``,t.yellow(`SEO information:`)),c.seoTitle&&u.push(` ${t.yellow(`Title:`)} ${c.seoTitle}`),c.seoDescription&&u.push(` ${t.yellow(`Description:`)} ${c.seoDescription}`)),c.taggedBuilds){u.push(``,t.yellow(`Builds:`));let e=c.taggedBuilds.latest;e&&u.push(` ${t.yellow(`-`)} ${t.cyan(e.buildNumber)} ${t.gray(`/`)} ${t.yellow(`latest`)}`);for(let[e,n]of Object.entries(c.taggedBuilds))e!==`latest`&&u.push(` ${t.yellow(`-`)} ${t.cyan(n.buildNumber)} ${t.gray(`/`)} ${t.yellow(e)}`)}simpleLog({message:u.join(`
92
92
  `),stdout:!0})}};function prettyPrintStatus(e){switch(e){case`READY`:return t.green(`Ready`);case`RUNNING`:return t.blue(`Running`);case`SUCCEEDED`:return t.green(`Succeeded`);case`FAILED`:return t.red(`Failed`);case`ABORTING`:return t.yellow(`Aborting`);case`ABORTED`:return t.red(`Aborted`);case`TIMING-OUT`:return t.yellow(`Timing Out`);case`TIMED-OUT`:return t.red(`Timed Out`);default:return t.gray(e.split(`-`).map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(` `))}}const Qn={"TIMED-OUT":t.gray(`after`),"TIMING-OUT":t.gray(`after`),ABORTED:t.gray(`after`),ABORTING:t.gray(`after`),FAILED:t.gray(`after`),READY:t.gray(`for`),RUNNING:t.gray(`for`),SUCCEEDED:t.gray(`after`)},$n=new Q({allColumns:[`Name`,`Runs`,`Last run started at`,`Last run status`,`Last run duration`,`_Small_LastRunText`],mandatoryColumns:[`Name`,`Runs`,`Last run status`,`Last run duration`],columnAlignments:{Runs:`right`,"Last run duration":`right`,Name:`left`,"Last run status":`center`},hiddenColumns:[`_Small_LastRunText`],breakpointOverrides:{small:{"Last run status":{label:`Last run`,valueFrom:`_Small_LastRunText`}}}}),er=new Q({allColumns:[`Name`,`Modified at`,`Builds`,`Default build`,`Runs`,`Last run`,`Last run status`,`Last run duration`,`_Small_LastRunText`],mandatoryColumns:[`Name`,`Runs`,`Last run`,`Last run duration`],hiddenColumns:[`_Small_LastRunText`],columnAlignments:{Builds:`right`,Runs:`right`,"Last run duration":`right`,Name:`left`,"Last run status":`center`},breakpointOverrides:{small:{"Last run":{label:`Last run`,valueFrom:`_Small_LastRunText`}}}});var ActorsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Prints a list of recently executed Actors or Actors you own.`;static examples=[{description:`List Actors you recently interacted with.`,command:`apify actors ls`},{description:`List Actors you own, newest first.`,command:`apify actors ls --my --desc`},{description:`List the next page of 50 Actors.`,command:`apify actors ls --limit 50 --offset 50`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-ls`;static flags={my:Y.boolean({description:`Whether to list Actors made by the logged in user.`,default:!1}),offset:Y.integer({description:`Number of Actors that will be skipped.`,default:0}),limit:Y.integer({description:`Number of Actors that will be listed.`,default:20}),desc:Y.boolean({description:`Sort Actors in descending order.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,my:i,json:a}=this.flags,s=await getLoggedClientOrThrow(),c=await s.actors().list({limit:n,offset:r,desc:e,my:i});if(c.count===0){if(a){printJsonToStdout(c);return}info({message:i?`You don't have any Actors yet!`:`There are no recent Actors used by you.`,stdout:!0});return}let l={...c,items:await Promise.all(c.items.map(async e=>{let t=await s.actor(e.id).get(),n=await s.actor(e.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...e,actor:t??null,lastRun:n.items[0]??null}}))};if(l.items=i?this.sortByModifiedAt(l.items):this.sortByLastRun(l.items),a){printJsonToStdout(l);return}let u=i?er:$n,f=l.items.reduce((e,t)=>{let n=`${t.username}/${t.name}`;return n.length>e?n.length:e},0)+2+6;for(let e of l.items){let n=e.stats.lastRunStartedAt?xn.display(e.stats.lastRunStartedAt):``,r=e.lastRun?(()=>{if(e.lastRun.finishedAt)return K.format(e.lastRun.finishedAt.getTime()-e.lastRun.startedAt.getTime());let t=Date.now()-e.lastRun.startedAt.getTime();return`${K.format(t)}…`})():``,i=e.actor?(()=>{let n=Object.entries(e.actor.taggedBuilds??{}).find(([t,n])=>n.buildNumber===e.actor.defaultRunOptions.build||t===e.actor.defaultRunOptions.build);return n?`${t.yellow(n[0])} / ${t.cyan(n[1].buildNumber??e.actor.defaultRunOptions.build)}`:t.gray(`Unknown`)})():t.gray(`Unknown`),a=(()=>{if(e.lastRun){let n=[prettyPrintStatus(e.lastRun.status)];if(r&&n.push(Qn[e.lastRun.status],t.cyan(r)),e.lastRun.finishedAt){let r=Date.now()-e.lastRun.finishedAt.getTime();r<Le.Week?n.push(`
93
93
  `,t.gray(`${K.format(r)} ago`)):n.push(`
94
94
  `,t.gray(`On`,Sn.display(e.lastRun.finishedAt)))}return n.join(` `)}return``})();u.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Runs:Q.isSmallTerminal()&&f>=56?Yn:t.cyan(`${e.stats?.totalRuns??0}`),"Last run started at":n,"Last run":n,"Last run status":e.lastRun?prettyPrintStatus(e.lastRun.status):``,"Modified at":xn.display(e.modifiedAt),Builds:e.actor?t.cyan(e.actor.stats.totalBuilds):t.gray(`Unknown`),"Last run duration":Q.isSmallTerminal()?Yn:t.cyan(r),"Default build":i,_Small_LastRunText:a})}simpleLog({message:u.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((e,t)=>{let n=new Date(e.modifiedAt);return new Date(t.modifiedAt).getTime()-n.getTime()})}sortByLastRun(e){return e.sort((e,t)=>{let n=new Date(e.stats?.lastRunStartedAt??`1970-01-01T00:00Z`);return new Date(t.stats?.lastRunStartedAt??`1970-01-01T00:00Z`).getTime()-n.getTime()})}};const extractGitHubZip=async(e,t)=>{let{data:n}=await Ue.get(e,{responseType:`arraybuffer`}),r=new ze(Buffer.from(n,`binary`));r.extractEntryTo(r.getEntries()[0].entryName,t,!1)};var ActorsPullCommand=class extends ApifyCommand{static name=`pull`;static description=`Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.`;static group=`Local Actor Development`;static examples=[{description:`Pull the Actor linked to the current directory from the Apify platform.`,command:`apify pull`},{description:`Pull a specific Actor by its full name into a target directory.`,command:`apify pull apify/hello-world --dir ./hello-world`},{description:`Pull a specific version of an Actor.`,command:`apify pull apify/hello-world --version 1.2`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-pull`;static flags={version:Y.string({char:`v`,description:`Actor version number which will be pulled, e.g. 1.2. Default: the highest version.`,required:!1}),dir:Y.string({description:`Directory where the Actor should be pulled to.`,required:!1})};static args={actorId:Z.string({required:!1,description:`Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.`})};async run(){let t=e.cwd(),n=await useActorConfig({cwd:t});if(n.isErr()){error({message:n.unwrapErr().message}),e.exitCode=5;return}let{config:r}=n.unwrap(),i=await getLocalUserInfo(),a=await getLoggedClientOrThrow(),s=!this.args.actorId,c=i.username||i.id,u=this.args?.actorId||r?.id||(r?.name?`${c}/${r.name}`:void 0);if(!u)throw Error(`Cannot find Actor in this directory.`);let f;try{f=await a.actor(u).get()}catch{throw Error(`Cannot find Actor with ID/name '${u}' in your account.`)}if(!f)throw Error(`Cannot find Actor with ID/name '${u}' in your account.`);let{name:p,versions:m}=f,throwMissingSourceCodeAccessError=()=>{throw Error(`You cannot pull source code of this Actor because you do not have permission to do so.`)};if(!f.versions.length)throw Error(`Actor ${u} has no versions.`);let h=null;if(this.flags.version&&(h=m.find(e=>e.versionNumber===this.flags.version),!h))throw Error(`Cannot find version ${this.flags.version} of Actor ${u}.`);h||=m.reduce((e,t)=>l(`${t.versionNumber}.0`,`${e.versionNumber}.0`)?t:e);let g=s?t:A(t,this.flags.dir??p);if(b(g,{recursive:!0}),!s&&C(g).length!==0){error({message:`Directory ${g} is not empty. Please empty it or choose another directory.`});return}let{sourceType:_}=h;switch(_){case`TARBALL`:h.tarballUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(h.tarballUrl,g);break;case`SOURCE_FILES`:{h.sourceFiles||throwMissingSourceCodeAccessError();let{sourceFiles:e}=h;for(let t of e)if(b(`${g}/${k(t.name)}`,{recursive:!0}),!t.folder){let e=t.format===`BASE64`?Buffer.from(t.content,`base64`).toString():t.content;if(t.name===W){let n=Tt.parse(e);n.name=f.name,D(`${g}/${t.name}`,Tt.update(e,n))}else D(`${g}/${t.name}`,e)}break}case`GIT_REPO`:{h.gitRepoUrl||throwMissingSourceCodeAccessError();let{gitRepoUrl:e}=h,[t,n]=e.split(`#`),r,i;n&&([r,i]=n.split(`:`));let a=t;i&&(a+=`/${i}`),r&&(a+=`#${r}`);let s=Et(a);try{await s.clone(g)}catch(t){throw Error(`Failed to pull Actor from ${e}. ${t.message}`)}break}case`GITHUB_GIST`:h.gitHubGistUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(`${h.gitHubGistUrl}/archive/master.zip`,g);break;default:throw Error(`Unknown source type: ${_}`)}success({message:s?`Actor ${p} updated at ${g}/`:`Pulled to ${g}/`})}};const tr=5e4,getSecretsFile=()=>{try{return JSON.parse(S(SECRETS_FILE_PATH(),`utf-8`))||{}}catch{return{}}},writeSecretsFile=e=>(ensureApifyDirectory(SECRETS_FILE_PATH()),D(SECRETS_FILE_PATH(),JSON.stringify(e,null,` `)),e),addSecret=(e,t)=>{let n=getSecretsFile();if(n[e])throw Error(`Secret with name ${e} already exists. Call "apify secrets rm ${e}" to remove it.`);if(typeof e!=`string`||e.length>100)throw Error(`Secret name has to be string with maximum length 100.`);if(typeof t!=`string`||t.length>tr)throw Error(`Secret value has to be string with maximum length ${tr}.`);return n[e]=t,writeSecretsFile(n)},removeSecret=e=>{let t=getSecretsFile();if(!t[e])throw Error(`Secret with name ${e} doesn't exist.`);delete t[e],writeSecretsFile(t)},isSecretKey=e=>RegExp(`^@.{1}`).test(e),replaceSecretsValue=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r={},i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(RegExp(`^@`),``);t[a]?r[n]=t[a]:i.push(a)}else r[n]=e[n]}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
@@ -222,4 +222,4 @@ When no path is provided, validates all schemas found in '${W}':
222
222
  - Dataset schema (from "storages.dataset")
223
223
  - Output schema (from "output")
224
224
  - Key-Value Store schema (from "storages.keyValueStore")`;static group=`Local Actor Development`;static examples=[{description:`Validate the input schema discovered from the default locations.`,command:`apify validate-schema`},{description:`Validate a specific INPUT_SCHEMA.json file.`,command:`apify validate-schema ./my-schema.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-validate-schema`;static args={path:Z.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${W}'.`})};static hiddenAliases=[`vis`];async run(){if(this.args.path){await this.validateInputSchemaAtPath(this.args.path);return}await this.validateAllSchemas()}async validateInputSchemaAtPath(t){await readAndValidateInputSchema({forcePath:t,cwd:e.cwd(),getMessage:e=>`Validating input schema at ${e??t}`}),success({message:`Input schema is valid.`})}async validateAllSchemas(){let t=e.cwd(),n=!1,r=!1;try{let{inputSchema:e,inputSchemaPath:r}=await readInputSchema({cwd:t,throwOnMissing:!0});e&&(n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${W}'`}`}),yt(new vn({strict:!1}),e),success({message:`Input schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}let i=[{label:`Dataset`,read:()=>readStorageSchema({cwd:t,key:`dataset`,label:`Dataset`,throwOnMissing:!0}),validate:validateDatasetSchema},{label:`Output`,read:()=>readStorageSchema({cwd:t,key:`output`,label:`Output`,getRef:e=>e?.output,throwOnMissing:!0}),validate:validateOutputSchema},{label:`Key-Value Store`,read:()=>readStorageSchema({cwd:t,key:`keyValueStore`,label:`Key-Value Store`,throwOnMissing:!0}),validate:validateKvsSchema}];for(let{label:e,read:t,validate:a}of i)try{let r=t();r&&(n=!0,info({message:`Validating ${e} schema ${r.schemaPath?`at ${r.schemaPath}`:`embedded in '${W}'`}`}),a(r.schema),success({message:`${e} schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}if(!n)throw Error(`No schemas found. Make sure '${W}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const Br=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],Vr=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Br as n,processVersionCheck as r,Vr as t};
225
- //# sourceMappingURL=_register-CxHLE5TF.js.map
225
+ //# sourceMappingURL=_register-De7oftjb.js.map