apify-cli 1.8.1-beta.3 → 1.8.1-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,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 a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,constants as w,copyFileSync as T,createWriteStream as E,existsSync as D,fstat as O,mkdirSync as k,openSync as ee,readFileSync as A,readdirSync as j,realpathSync as te,renameSync as ne,rmSync as M,statSync as re,unlinkSync as ie,writeFileSync as N}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}from"node:os";import ue,{isCI as de}from"ci-info";import{ACTOR_ENV_VARS as P,ACTOR_JOB_STATUSES as F,ACTOR_JOB_TERMINAL_STATUSES as fe,ACTOR_NAME as pe,ACTOR_SOURCE_TYPES as me,APIFY_ENV_VARS as I,KEY_VALUE_STORE_KEYS as he,LOCAL_ACTOR_ENV_VARS as ge,LOCAL_STORAGE_SUBDIRS as _e,MAX_MULTIFILE_BYTES as ve,META_ORIGINS as ye,SOURCE_FILE_FORMATS as be}from"@apify/consts";import{jaroWinkler as xe}from"@skyra/jaro-winkler";import Se from"js-levenshtein";import{Result as Ce,err as we,none as L,ok as Te,some as Ee}from"@sapphire/result";import{execa as De}from"execa";import{access as Oe,appendFile as ke,mkdir as R,readFile as z,readdir as Ae,rename as je,rm as Me,stat as B,symlink as Ne,unlink as Pe,writeFile as V}from"node:fs/promises";import Fe from"configparser";import Ie from"@inquirer/input";import Le from"which";import{createHmacSignature as Re,cryptoRandomObjectId as ze}from"@apify/utilities";import{execSync as Be,spawn as Ve}from"node:child_process";import{DurationFormatter as He,Time as Ue,TimeTypes as We}from"@sapphire/duration";import{Timestamp as Ge}from"@sapphire/timestamp";import Ke from"adm-zip";import qe from"ajv/dist/2019.js";import{ApifyClient as Je,DownloadItemsFormat as H}from"apify-client";import{ZipArchive as Ye}from"archiver";import Xe,{AxiosHeaders as Ze}from"axios";import Qe from"escape-string-regexp";import $e from"ignore";import{getEncoding as et}from"istextorbinary";import tt,{Mime as nt}from"mime";import rt from"mime/types/other.js";import it from"mime/types/standard.js";import{glob as at}from"tinyglobby";import{calculateRunDynamicMemory as ot}from"@apify/actor-memory-expression";import{Separator as st,createPrompt as ct,isEnterKey as lt,makeTheme as ut,useKeypress as dt,usePrefix as ft,useState as pt}from"@inquirer/core";import{pipeline as mt}from"node:stream/promises";import{MemoryStorage as ht}from"@crawlee/memory-storage";import{compile as gt}from"json-schema-to-typescript";import{validateInputSchema as _t,validateInputUsingValidator as vt}from"@apify/input_schema";import{getDatasetSchemaValidator as yt,getKeyValueStoreSchemaValidator as bt,getOutputSchemaValidator as xt}from"@apify/json_schemas";import St from"cli-table3";import{downloadTemplate as Ct}from"giget";import wt from"jju";import Tt from"open";import{fetchManifest as Et,manifestUrl as Dt,wrapperManifestUrl as Ot}from"@apify/actor-templates";import kt from"computer-name";import At from"@inquirer/password";import jt from"@inquirer/select";import{createServer as Mt}from"node:http";import Nt from"node:assert";import{ReadStream as Pt}from"node:tty";import Ft from"detect-indent";import{fileURLToPath as It}from"node:url";import Lt from"@root/walk";import Rt 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=te(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 zt=null;function useCLIMetadata(){if(zt)return zt;let e=detectInstallMethod(),t=getRuntimeInfo();return zt={version:`1.8.1-beta.
|
|
1
|
+
import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,constants as w,copyFileSync as T,createWriteStream as E,existsSync as D,fstat as O,mkdirSync as k,openSync as ee,readFileSync as A,readdirSync as j,realpathSync as te,renameSync as ne,rmSync as M,statSync as re,unlinkSync as ie,writeFileSync as N}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}from"node:os";import ue,{isCI as de}from"ci-info";import{ACTOR_ENV_VARS as P,ACTOR_JOB_STATUSES as F,ACTOR_JOB_TERMINAL_STATUSES as fe,ACTOR_NAME as pe,ACTOR_SOURCE_TYPES as me,APIFY_ENV_VARS as I,KEY_VALUE_STORE_KEYS as he,LOCAL_ACTOR_ENV_VARS as ge,LOCAL_STORAGE_SUBDIRS as _e,MAX_MULTIFILE_BYTES as ve,META_ORIGINS as ye,SOURCE_FILE_FORMATS as be}from"@apify/consts";import{jaroWinkler as xe}from"@skyra/jaro-winkler";import Se from"js-levenshtein";import{Result as Ce,err as we,none as L,ok as Te,some as Ee}from"@sapphire/result";import{execa as De}from"execa";import{access as Oe,appendFile as ke,mkdir as R,readFile as z,readdir as Ae,rename as je,rm as Me,stat as B,symlink as Ne,unlink as Pe,writeFile as V}from"node:fs/promises";import Fe from"configparser";import Ie from"@inquirer/input";import Le from"which";import{createHmacSignature as Re,cryptoRandomObjectId as ze}from"@apify/utilities";import{execSync as Be,spawn as Ve}from"node:child_process";import{DurationFormatter as He,Time as Ue,TimeTypes as We}from"@sapphire/duration";import{Timestamp as Ge}from"@sapphire/timestamp";import Ke from"adm-zip";import qe from"ajv/dist/2019.js";import{ApifyClient as Je,DownloadItemsFormat as H}from"apify-client";import{ZipArchive as Ye}from"archiver";import Xe,{AxiosHeaders as Ze}from"axios";import Qe from"escape-string-regexp";import $e from"ignore";import{getEncoding as et}from"istextorbinary";import tt,{Mime as nt}from"mime";import rt from"mime/types/other.js";import it from"mime/types/standard.js";import{glob as at}from"tinyglobby";import{calculateRunDynamicMemory as ot}from"@apify/actor-memory-expression";import{Separator as st,createPrompt as ct,isEnterKey as lt,makeTheme as ut,useKeypress as dt,usePrefix as ft,useState as pt}from"@inquirer/core";import{pipeline as mt}from"node:stream/promises";import{MemoryStorage as ht}from"@crawlee/memory-storage";import{compile as gt}from"json-schema-to-typescript";import{validateInputSchema as _t,validateInputUsingValidator as vt}from"@apify/input_schema";import{getDatasetSchemaValidator as yt,getKeyValueStoreSchemaValidator as bt,getOutputSchemaValidator as xt}from"@apify/json_schemas";import St from"cli-table3";import{downloadTemplate as Ct}from"giget";import wt from"jju";import Tt from"open";import{fetchManifest as Et,manifestUrl as Dt,wrapperManifestUrl as Ot}from"@apify/actor-templates";import kt from"computer-name";import At from"@inquirer/password";import jt from"@inquirer/select";import{createServer as Mt}from"node:http";import Nt from"node:assert";import{ReadStream as Pt}from"node:tty";import Ft from"detect-indent";import{fileURLToPath as It}from"node:url";import Lt from"@root/walk";import Rt 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=te(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 zt=null;function useCLIMetadata(){if(zt)return zt;let e=detectInstallMethod(),t=getRuntimeInfo();return zt={version:`1.8.1-beta.4`,hash:`99f3cc18f1cfa8d6ff22f91f6f3bb917cbdf3e4b`,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`&&(zt.installPath=c(process.execPath)),zt}function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Bt=[`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
4
|
`)}function atomicWriteSync(t,n,r){let i=`${t}.${e.pid}.tmp`;try{N(i,n),r!==void 0&&C(i,r),ne(i,t)}catch(e){try{M(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),ne(i,n)}catch(e){try{M(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Bt)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 Bt){let t=u(r,`${e}.exe.old`);if(D(t))try{M(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`||!Bt.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 Bt){let n=u(r,`${t}.exe`);if(D(n))try{p(n)===p(e.execPath)?(ne(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):M(n,{force:!0})}catch(e){try{ne(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}let t=u(r,`upgrade.ps1`);try{M(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 Vt;function getMaxLineWidth(){if(Vt)return Vt;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Vt=e;else if(!process.stdout.isTTY)Vt=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Vt=e<1?80:e<40?40:e}return Vt}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(`
|
|
@@ -87,7 +87,7 @@ just as if the command were run from that directory with no argument.`;static gr
|
|
|
87
87
|
For platform-level management (deploy, list, call Actors), see 'apify actors' (plural).`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actor`;static subcommands=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand];async run(){this.printHelp()}};function OverrideClassName(e){return e}function getConsoleUrl(){let t=e.env.APIFY_CONSOLE_URL;if(t){let e=stripTrailingSlash(t);if(!URL.canParse(e))throw Error(`Invalid APIFY_CONSOLE_URL environment variable: "${t}" is not a valid URL.`);return e}return`https://console.apify.com`}function stripTrailingSlash(e){return e.replace(/\/+$/,``)}const Zn=new Set(fe);function isTerminalStatus(e){return!!e&&Zn.has(e)}function exitCodeForJobStatus(e,t){switch(e){case`SUCCEEDED`:return 0;case`TIMED-OUT`:case`TIMING-OUT`:return 2;case`ABORTED`:case`ABORTING`:return 3;default:return 1}}function exitCodeForWaitResult(e,t){return e.timedOutWaiting?6:exitCodeForJobStatus(e.job.status,t)}async function waitForTerminalStatus(e){let{apifyClient:t,jobId:n,kind:r,pollIntervalMillis:i=2e3,maxWaitMillis:a}=e,s=Date.now();for(;;){let e=r===`build`?await t.build(n).get():await t.run(n).get();if(!e)throw Error(`${r===`build`?`Build`:`Run`} with ID "${n}" was not found.`);if(isTerminalStatus(e.status))return{job:e,timedOutWaiting:!1};if(a&&Date.now()-s>=a)return{job:e,timedOutWaiting:!0};let c=a?Math.min(i,a-(Date.now()-s)):i;await new Promise(e=>setTimeout(e,Math.max(0,c)))}}async function fetchLogTail(e,t,n=20){try{let r=await e.log(t).get();return r?r.split(`
|
|
88
88
|
`).filter(e=>e.length>0).slice(-n):[]}catch{return[]}}function consoleRunUrl(e,t){return`${getConsoleUrl()}/actors/${e}/runs/${t}`}function consoleBuildUrl(e,t){return`${getConsoleUrl()}/actors/${e}#/builds/${t}`}function statusColor(e){return e===`SUCCEEDED`?t.green(e):e===`RUNNING`||e===`READY`?t.blue(e):t.red(e)}function formatResultSummary(e){let n=[];n.push(`${t.bold(e.resultLabel)}: ${statusColor(e.overallStatus)}`),n.push(``);for(let t of e.lines)n.push(`${t.label}: ${t.value}`);if(e.links?.length){n.push(``);for(let r of e.links)n.push(`${r.label}: ${t.blue(r.url)}`)}if(e.errorReason?.length){n.push(``),n.push(t.red(`Reason:`));for(let t of e.errorReason)n.push(t)}return n.join(`
|
|
89
89
|
`)}async function resolveActorContext({providedActorNameOrId:t,client:n}){let r=await getLocalUserInfo(),i=r.username||r.id,a=getLocalConfig(e.cwd())||{};if(t?.includes(`/`)){let e=await n.actor(t).get();return e?{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id}:{valid:!1,reason:`Actor with ID "${t}" was not found`}}if(t){let e=await n.actor(t).get();if(e)return{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id};let r=await n.actor(`${i}/${t.toLowerCase()}`).get();return r?{valid:!0,userFriendlyId:`${r.username}/${r.name}`,id:r.id}:{valid:!1,reason:`Actor with name or ID "${t}" was not found`}}if(a.name){let e=await n.actor(`${i}/${a.name}`).get();return e?{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id}:{valid:!1,reason:`Actor with name "${a.name}" was not found`}}return{valid:!1,reason:`Unable to detect what Actor to create a build for`}}function useSignalHandler({signals:e,handler:t,cleanTerminalLine:n=!0,once:r=!0}){let i=!1,wrapped=a=>{if(!i){if(r){i=!0;for(let t of e)process.off(t,wrapped)}n&&process.stderr.isTTY&&process.stderr.write(`\r\x1B[2K\x1B[0m`),cliDebugPrint(`useSignalHandler`,{event:`fired`,signal:a,once:r}),(async()=>{try{await t(a)}catch(e){cliDebugPrint(`useSignalHandler`,{event:`handler-threw`,signal:a,err:e})}})()}};for(let t of e)process.on(t,wrapped);return cliDebugPrint(`useSignalHandler`,{event:`registered`,signals:e,once:r}),{[Symbol.dispose](){if(!i){i=!0;for(let t of e)process.off(t,wrapped);cliDebugPrint(`useSignalHandler`,{event:`disposed`,signals:e})}}}}function useAbortJobOnSignal(e){let{apifyClient:n,silent:r=!1}=e,i=0;return useSignalHandler({signals:$t,once:!1,handler:async a=>{if(i+=1,e.kind===`build`){if(i>1)return;r||info({message:t.gray(`Received ${t.yellow(a)}, aborting build "${t.yellow(e.jobId)}" on the Apify platform...`),stdout:!0});try{await n.build(e.jobId).abort()}catch(t){error({message:`Failed to abort build "${e.jobId}": ${t.message}`,stdout:!0})}return}if(i>2)return;let s=i===1,c=`${e.runType.toLowerCase()} run`;if(!r){let n=s?`Received ${t.yellow(a)}, gracefully aborting ${c} "${t.yellow(e.jobId)}" on the Apify platform... ${t.dim(`(press Ctrl+C again to abort immediately)`)}`:`Received ${t.yellow(a)} again, aborting ${c} "${t.yellow(e.jobId)}" immediately...`;info({message:t.gray(n),stdout:!0})}try{await n.run(e.jobId).abort({gracefully:s})}catch(t){error({message:`Failed to abort run "${e.jobId}": ${t.message}`,stdout:!0})}}})}function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function o(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function d(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}var BuildsCreateCommand=class extends ApifyCommand{static name=`create`;static description=`Creates a new build of the Actor.`;static examples=[{description:`Build the Actor in the current directory with the default "latest" tag.`,command:`apify builds create`},{description:`Build a specific Actor with a custom tag and stream the build log.`,command:`apify builds create apify/hello-world --tag beta --log`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-create`;static flags={tag:J.string({description:`Build tag to be applied to the successful Actor build. By default, this is "latest".`}),version:J.string({description:`Optional Actor Version to build. By default, this will be inferred from the tag, but this flag is required when multiple versions have the same tag.`,required:!1}),log:J.boolean({description:`Whether to print out the build log after the build is triggered.`}),wait:J.boolean({description:`Wait for the build to reach a terminal status. Returns exit code 0 only when the build SUCCEEDED.`,default:!1})};static args={actorId:X.string({description:`Optional Actor ID or Name to trigger a build for. By default, it will use the Actor from the current directory.`})};static enableJsonFlag=!0;async run(){let{tag:n,version:r,json:i,log:a,wait:s}=this.flags,{actorId:c}=this.args;if(a&&s){error({message:`The --log and --wait flags cannot be used together. --log already waits for the build to finish while streaming its log.`}),e.exitCode=5;return}let l=await getLoggedClientOrThrow(),u=await resolveActorContext({providedActorNameOrId:c,client:l});if(!u.valid){error({message:`${u.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let f=await l.actor(u.id).get(),p=objectGroupBy(f.versions,e=>e.buildTag??`latest`)[n??`latest`],m=f.versions.find(e=>e.versionNumber===r),h;if(m){if(n&&(!p||!p.some(e=>e.versionNumber===r))){error({message:`The Actor Version "${r}" does not have the tag "${n}".`,stdout:!0});return}h=r}else if(p&&(h=p[0].versionNumber,p.length>1&&!r)){error({message:`Multiple Actor versions with the tag "${n}" found. Please specify the version number using the "--version" flag.\n Available versions for this tag: ${p.map(e=>t.yellow(e.versionNumber)).join(`, `)}`,stdout:!0});return}if(!h){error({message:`No Actor versions with the tag "${n}" found. You can push a new version with this tag by using "apify push --build-tag=${n}".`,stdout:!0});return}let g=await l.actor(u.id).build(h,{tag:n}),_=f?.name??`unknown-actor`,v=consoleBuildUrl(g.actId,g.buildNumber);if(a||s)try{var y=_usingCtx();if(y.u(useAbortJobOnSignal({apifyClient:l,kind:`build`,jobId:g.id})),a)try{await outputJobLog({job:g,apifyClient:l})}catch(e){error({message:`Failed to print log for build with ID "${g.id}": ${e.message}`,stdout:!0})}let{job:e}=await waitForTerminalStatus({apifyClient:l,jobId:g.id,kind:`build`});g=e}catch(e){y.e=e}finally{y.d()}if(a||s){let t=g.status===`SUCCEEDED`,n=exitCodeForJobStatus(g.status,`build`),r=t?[]:await fetchLogTail(l,g.id);if(i){printJsonToStdout({ok:t,operation:`builds.create`,waited:!0,actor:{id:g.actId,name:_},build:{id:g.id,number:g.buildNumber,status:g.status,url:v},...t?{}:{error:{phase:`build`,message:`Actor build did not succeed`,logTail:r}},exitCode:n}),e.exitCode=n;return}simpleLog({message:formatResultSummary({resultLabel:`Apify build result`,overallStatus:g.status,lines:[{label:`Build`,value:g.status},{label:`Build ID`,value:g.id},{label:`Build number`,value:g.buildNumber},{label:`Actor ID`,value:g.actId}],links:[{label:`Build URL`,url:v}],errorReason:t?void 0:r}),stdout:!0}),e.exitCode=n;return}if(i){printJsonToStdout({ok:!0,operation:`builds.create`,waited:!1,actor:{id:g.actId,name:_},build:{id:g.id,number:g.buildNumber,status:g.status,url:v},next:{wait:`apify builds wait ${g.id} --json`,log:`apify builds log ${g.id}`,info:`apify builds info ${g.id} --json`},exitCode:0});return}simpleLog({message:[t.greenBright(`Build started.`),``,`${t.yellow(`Actor`)}: ${_} (${t.gray(g.actId)})`,`${t.yellow(`Build ID`)}: ${g.id}`,`${t.yellow(`Build number`)}: ${g.buildNumber}`,`${t.yellow(`Status`)}: ${g.status}`,``,t.gray(`This command does not wait for the build to finish.`),``,`To wait for the final status:`,` apify builds wait ${g.id} --json`,``,`To inspect logs:`,` apify builds log ${g.id}`,``,`To inspect build metadata:`,` apify builds info ${g.id} --json`].join(`
|
|
90
|
-
`),stdout:!0})}},ActorsBuildCommand=class extends OverrideClassName(BuildsCreateCommand){static name=`build`};function withSchemaHint(e,t){return t?`${e}\n${t}`:e}function resolveInput(e,t){let n,r;if(t)n=t,r=`application/json`;else{let t=getLocalInput(e);t&&(tt.getExtension(t.contentType)===`json`?(n=JSON.parse(t.body.toString(`utf8`)),r=`application/json`):(n=t.body,r=t.contentType))}return!n||!r?null:{inputToUse:n,contentType:r}}async function getInputOverride(t,n,r,i={}){let s,c,{schemaHint:l}=i;if(!n&&!r){let t=un;if(t)try{let n=JSON.parse(t.toString(`utf8`));if(Array.isArray(n))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,l)}),e.exitCode=5,!1;s=n,c=`stdin`}catch(t){return error({message:withSchemaHint(`Cannot parse JSON input from standard input.\n ${t.message}`,l)}),e.exitCode=5,!1}}if(n)switch(n[0]){case`-`:return error({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),e.exitCode=5,!1;default:{let r=await Oe(p(t,n)).then(()=>!0).catch(()=>!1),i=n.endsWith(`.json`)||n.endsWith(`.json5`)||a.isAbsolute(n)||n.startsWith(`./`)||n.startsWith(`../`)||n.
|
|
90
|
+
`),stdout:!0})}},ActorsBuildCommand=class extends OverrideClassName(BuildsCreateCommand){static name=`build`};function withSchemaHint(e,t){return t?`${e}\n${t}`:e}function resolveInput(e,t){let n,r;if(t)n=t,r=`application/json`;else{let t=getLocalInput(e);t&&(tt.getExtension(t.contentType)===`json`?(n=JSON.parse(t.body.toString(`utf8`)),r=`application/json`):(n=t.body,r=t.contentType))}return!n||!r?null:{inputToUse:n,contentType:r}}async function getInputOverride(t,n,r,i={}){let s,c,{schemaHint:l}=i;if(!n&&!r){let t=un;if(t)try{let n=JSON.parse(t.toString(`utf8`));if(Array.isArray(n))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,l)}),e.exitCode=5,!1;s=n,c=`stdin`}catch(t){return error({message:withSchemaHint(`Cannot parse JSON input from standard input.\n ${t.message}`,l)}),e.exitCode=5,!1}}if(n)switch(n[0]){case`-`:return error({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),e.exitCode=5,!1;default:{let r=await Oe(p(t,n)).then(()=>!0).catch(()=>!1),i=n.endsWith(`.json`)||n.endsWith(`.json5`)||a.isAbsolute(n)||n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`~`)||n.startsWith(`.\\`)||n.startsWith(`..\\`);if(r||i)return error({message:`Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead`}),e.exitCode=5,!1;try{let t=JSON.parse(n);if(Array.isArray(t))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,l)}),e.exitCode=5,!1;s=t,c=`input`}catch(t){return error({message:withSchemaHint(`Cannot parse JSON input.\n ${t.message}`,l)}),e.exitCode=5,!1}}}else if(r)switch(r[0]){case`-`:return error({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),e.exitCode=5,!1;default:{let n=p(t,r),i;try{let t=await z(n,`utf8`),i=JSON.parse(t);if(Array.isArray(i))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,l)}),e.exitCode=5,!1;s=i,c=r}catch(e){i=e}if(i)try{let t=JSON.parse(r);if(Array.isArray(t))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,l)}),e.exitCode=5,!1;s=t,c=r}catch{return error({message:withSchemaHint(`Cannot read input file at path "${n}".\n ${i.message}`,i instanceof SyntaxError?l:void 0)}),e.exitCode=5,!1}}}return s?{input:s,source:c}:void 0}const Qn=[F.SUCCEEDED,F.ABORTED,F.FAILED,F.TIMED_OUT];async function*runActorOrTaskOnCloud(n,r){try{var i=_usingCtx();let a=e.cwd(),{actorOrTaskData:s,runOptions:c,type:l,waitForFinishMillis:u,inputOverride:f,silent:p,waitForRunToFinish:m,printRunLogs:h,suppressFinalStatus:g}=r,_=l===`Actor`?`actor`:`task`,v=resolveInput(a,f);p||(l===`Actor`?run({message:`Calling ${l} ${s.userFriendlyId} (${t.gray(s.id)})\n`}):s.title?run({message:`Calling ${l} ${s.title} (${s.userFriendlyId}, ${t.gray(s.id)})\n`}):run({message:`Calling ${l} ${s.userFriendlyId} (${t.gray(s.id)})\n`}));let y;try{y=v&&l===`Actor`?await n[_](s.id).start(v.inputToUse,{...c,contentType:v.contentType}):await n[_](s.id).start(void 0,c)}catch(e){if(e.type===`record-not-found`)throw Error(`${l} ${s.userFriendlyId} (${s.id}) not found!`);if(e.type===`full-permission-actor-not-approved`){let n=e.data?.approvalUrl,r=[`${l} ${s.userFriendlyId} requires full access to your Apify account and has not been approved yet.`];throw n&&r.push(``,`Approve here: ${t.blue(n)}`),Error(r.join(`
|
|
91
91
|
`))}throw e}if(i.u(useAbortJobOnSignal({apifyClient:n,kind:`run`,jobId:y.id,runType:l,silent:p})),yield y,!p&&h)try{await outputJobLog({job:y,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(y=await n.run(y.id).get(),m)for(;!Qn.includes(y.status)&&(y=await n.run(y.id).get(),!Qn.includes(y.status));)await new Promise(e=>{setTimeout(e,1e3)});g||(y.status===F.SUCCEEDED?p||success({message:`${l} finished.`}):y.status===F.RUNNING?p||warning({message:`${l} is still running!`}):y.status===F.ABORTED||y.status===F.ABORTING?(p||warning({message:`${l} was aborted!`}),e.exitCode=3):(p||error({message:`${l} failed!`}),e.exitCode=1)),yield y}catch(e){i.e=e}finally{i.d()}}const SharedRunOnCloudFlags=e=>({build:J.string({char:`b`,description:`Tag or number of the build to run (e.g. "latest" or "1.2.34").`,required:!1}),timeout:J.integer({char:`t`,description:`Timeout for the ${e} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:J.integer({char:`m`,description:`Amount of memory allocated for the ${e} run, in megabytes.`,required:!1})}),$n={call:`Apify call`,"task-run":`Apify task run`};function actorUrl(e){return`${getConsoleUrl()}/actors/${e}`}function runUrl(e,t){return`${getConsoleUrl()}/actors/${e}/runs/${t}`}function datasetUrl(e){return`${getConsoleUrl()}/storage/datasets/${e}`}function isSucceeded(e){return e.status===F.SUCCEEDED}function getRunExitCode(e){switch(e.status){case F.SUCCEEDED:return 0;case F.ABORTED:case F.ABORTING:return 3;case F.TIMED_OUT:case F.TIMING_OUT:return 2;default:return e.exitCode&&e.exitCode!==0?e.exitCode:1}}function genericReason(e){switch(e.status){case F.ABORTED:case F.ABORTING:return`Actor run was aborted`;case F.TIMED_OUT:case F.TIMING_OUT:return`Actor run timed out`;default:return`Actor run failed`}}async function fetchRunLogTail(e,t){if(isSucceeded(t))return[];let n;try{n=await e.log(t.id).get()}catch{return[]}return n?n.split(`
|
|
92
92
|
`).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=[`${$n[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(`
|
|
93
93
|
`),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})}var er=class ActorsCallCommand extends ApifyCommand{static name=`call`;static description=`Executes Actor remotely using your authenticated account.
|
|
@@ -236,4 +236,4 @@ When no path is provided, validates all schemas found in '${W}':
|
|
|
236
236
|
- Dataset schema (from "storages.dataset")
|
|
237
237
|
- Output schema (from "output")
|
|
238
238
|
- Key-Value Store schema (from "storages.keyValueStore")`;static group=`Local Actor Development`;static examples=[{description:`Validate the input schema discovered from the default locations.`,command:`apify validate-schema`},{description:`Validate a specific INPUT_SCHEMA.json file.`,command:`apify validate-schema ./my-schema.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-validate-schema`;static args={path:X.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${W}'.`})};static hiddenAliases=[`vis`];async run(){if(this.args.path){await this.validateInputSchemaAtPath(this.args.path);return}await this.validateAllSchemas()}async validateInputSchemaAtPath(t){await readAndValidateInputSchema({forcePath:t,cwd:e.cwd(),getMessage:e=>`Validating input schema at ${e??t}`}),success({message:`Input schema is valid.`})}async validateAllSchemas(){let t=e.cwd(),n=!1,r=!1;try{let{inputSchema:e,inputSchemaPath:r}=await readInputSchema({cwd:t,throwOnMissing:!0});if(e){n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${W}'`}`});let t=new An({strict:!1});_t(t,e),success({message:`Input schema is valid.`})}}catch(e){n=!0,r=!0,error({message:e.message})}let i=[{label:`Dataset`,read:()=>readStorageSchema({cwd:t,key:`dataset`,label:`Dataset`,throwOnMissing:!0}),validate:validateDatasetSchema},{label:`Output`,read:()=>readStorageSchema({cwd:t,key:`output`,label:`Output`,getRef:e=>e?.output,throwOnMissing:!0}),validate:validateOutputSchema},{label:`Key-Value Store`,read:()=>readStorageSchema({cwd:t,key:`keyValueStore`,label:`Key-Value Store`,throwOnMissing:!0}),validate:validateKvsSchema}];for(let{label:e,read:t,validate:a}of i)try{let r=t();r&&(n=!0,info({message:`Validating ${e} schema ${r.schemaPath?`at ${r.schemaPath}`:`embedded in '${W}'`}`}),a(r.schema),success({message:`${e} schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}if(!n)throw Error(`No schemas found. Make sure '${W}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const ii=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,TemplatesIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],ai=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,ii as n,processVersionCheck as r,ai as t};
|
|
239
|
-
//# sourceMappingURL=_register-
|
|
239
|
+
//# sourceMappingURL=_register-DQYT7x0e.js.map
|