@botpress/cli 4.20.3 → 4.21.0

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,36 +1,36 @@
1
1
 
2
- > @botpress/cli@4.20.3 build /home/runner/work/botpress/botpress/packages/cli
2
+ > @botpress/cli@4.21.0 build /home/runner/work/botpress/botpress/packages/cli
3
3
  > pnpm run build:types && pnpm run bundle && pnpm run template:gen
4
4
 
5
5
 
6
- > @botpress/cli@4.20.3 build:types /home/runner/work/botpress/botpress/packages/cli
6
+ > @botpress/cli@4.21.0 build:types /home/runner/work/botpress/botpress/packages/cli
7
7
  > tsc -p ./tsconfig.build.json
8
8
 
9
9
 
10
- > @botpress/cli@4.20.3 bundle /home/runner/work/botpress/botpress/packages/cli
10
+ > @botpress/cli@4.21.0 bundle /home/runner/work/botpress/botpress/packages/cli
11
11
  > ts-node -T build.ts
12
12
 
13
13
 
14
- > @botpress/cli@4.20.3 template:gen /home/runner/work/botpress/botpress/packages/cli
14
+ > @botpress/cli@4.21.0 template:gen /home/runner/work/botpress/botpress/packages/cli
15
15
  > pnpm -r --stream -F @bp-templates/* exec bp gen
16
16
 
17
- 🤖 Botpress CLI v4.20.3
18
- 🤖 Botpress CLI v4.20.3
19
- 🤖 Botpress CLI v4.20.3
20
- 🤖 Botpress CLI v4.20.3
21
- ○ Generating typings for integration empty-integration...
22
- ✓ Typings available at .botpress
23
-
17
+ 🤖 Botpress CLI v4.21.0
18
+ 🤖 Botpress CLI v4.21.0
19
+ 🤖 Botpress CLI v4.21.0
20
+ 🤖 Botpress CLI v4.21.0
24
21
  ○ Generating typings for bot...
25
22
  ✓ Typings available at .botpress
26
23
 
27
- ○ Generating typings for integration hello-world...
28
24
  ○ Generating typings for plugin empty-plugin...
25
+ ○ Generating typings for integration hello-world...
26
+ ✓ Typings available at .botpress
27
+
29
28
  ✓ Typings available at .botpress
30
29
 
30
+ ○ Generating typings for integration empty-integration...
31
31
  ✓ Typings available at .botpress
32
32
 
33
- 🤖 Botpress CLI v4.20.3
33
+ 🤖 Botpress CLI v4.21.0
34
34
  ○ Generating typings for integration webhook-message...
35
35
  ✓ Typings available at .botpress
36
36
 
@@ -47,4 +47,5 @@ export declare class ApiClient {
47
47
  findPreviousIntegrationVersion(ref: NamePackageRef): Promise<PublicOrPrivateIntegration | undefined>;
48
48
  findBotByName(name: string): Promise<BotSummary | undefined>;
49
49
  private _returnUndefinedOnError;
50
+ getOrGenerateShareableId(botId: string, integrationId: string, integrationAlias: string): Promise<string>;
50
51
  }
@@ -225,6 +225,22 @@ class ApiClient {
225
225
  }
226
226
  throw thrown;
227
227
  };
228
+ async getOrGenerateShareableId(botId, integrationId, integrationAlias) {
229
+ const { shareableId, isExpired } = await this.client.getIntegrationShareableId({
230
+ botId,
231
+ integrationId,
232
+ integrationInstanceAlias: integrationAlias
233
+ }).catch(() => ({ shareableId: void 0, isExpired: true }));
234
+ if (shareableId && !isExpired) {
235
+ return shareableId;
236
+ }
237
+ const { shareableId: newShareableId } = await this.client.createIntegrationShareableId({
238
+ botId,
239
+ integrationId,
240
+ integrationInstanceAlias: integrationAlias
241
+ });
242
+ return newShareableId;
243
+ }
228
244
  }
229
245
  // Annotate the CommonJS export names for ESM import in node:
230
246
  0 && (module.exports = {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/api/client.ts"],
4
- "sourcesContent": ["import * as client from '@botpress/client'\nimport semver from 'semver'\nimport yn from 'yn'\nimport * as errors from '../errors'\nimport type { Logger } from '../logger'\nimport { formatPackageRef, ApiPackageRef, NamePackageRef } from '../package-ref'\nimport * as utils from '../utils'\nimport * as paging from './paging'\nimport * as retry from './retry'\n\nimport {\n ApiClientProps,\n PublicOrUnlistedIntegration,\n PrivateIntegration,\n PublicOrPrivateIntegration,\n PublicInterface,\n PrivateInterface,\n PublicOrPrivateInterface,\n PrivatePlugin,\n PublicPlugin,\n PublicOrPrivatePlugin,\n BotSummary,\n} from './types'\n\nexport * from './types'\n\n/**\n * This class is used to wrap the Botpress API and provide a more convenient way to interact with it.\n */\nexport class ApiClient {\n public readonly client: client.Client\n public readonly url: string\n public readonly token: string\n public readonly workspaceId: string\n public readonly botId?: string\n\n public static newClient = (props: ApiClientProps, logger: Logger) => new ApiClient(props, logger)\n\n public constructor(\n props: ApiClientProps,\n private _logger: Logger\n ) {\n const { apiUrl, token, workspaceId, botId } = props\n this.client = new client.Client({\n apiUrl,\n token,\n workspaceId,\n botId,\n retry: retry.config,\n headers: { 'x-multiple-integrations': 'true' },\n })\n this.url = apiUrl\n this.token = token\n this.workspaceId = workspaceId\n this.botId = botId\n }\n\n public get isBotpressWorkspace(): boolean {\n // this environment variable is undocumented and only used internally for dev purposes\n const isBotpressWorkspace = yn(process.env.BP_IS_BOTPRESS_WORKSPACE)\n if (isBotpressWorkspace !== undefined) {\n return isBotpressWorkspace\n }\n return [\n '6a76fa10-e150-4ff6-8f59-a300feec06c1',\n '95de33eb-1551-4af9-9088-e5dcb02efd09',\n '11111111-1111-1111-aaaa-111111111111',\n ].includes(this.workspaceId)\n }\n\n public async safeListTables(req: client.ClientInputs['listTables']): Promise<\n | {\n success: true\n tables: client.ClientOutputs['listTables']['tables']\n }\n | {\n success: false\n error: Error\n }\n > {\n try {\n const result = await this.client.listTables(req)\n return { success: true, tables: result.tables }\n } catch (thrown) {\n const error = thrown instanceof Error ? thrown : new Error(String(thrown))\n return { success: false, error }\n }\n }\n\n public async getWorkspace(): Promise<client.ClientOutputs['getWorkspace']> {\n return this.client.getWorkspace({ id: this.workspaceId })\n }\n\n public async findWorkspaceByHandle(handle: string): Promise<client.ClientOutputs['getWorkspace'] | undefined> {\n const { workspaces } = await this.client.listWorkspaces({ handle })\n return workspaces[0] // There should be only one workspace with a given handle\n }\n\n public switchWorkspace(workspaceId: string): ApiClient {\n return ApiClient.newClient({ apiUrl: this.url, token: this.token, workspaceId }, this._logger)\n }\n\n public switchBot(botId: string): ApiClient {\n return ApiClient.newClient(\n { apiUrl: this.url, token: this.token, botId, workspaceId: this.workspaceId },\n this._logger\n )\n }\n\n public async updateWorkspace(\n props: utils.types.SafeOmit<client.ClientInputs['updateWorkspace'], 'id'>\n ): Promise<client.ClientOutputs['updateWorkspace']> {\n return this.client.updateWorkspace({ id: this.workspaceId, ...props })\n }\n\n public async getPublicOrPrivateIntegration(ref: ApiPackageRef): Promise<PublicOrPrivateIntegration> {\n const integration = await this.findPublicOrPrivateIntegration(ref)\n if (!integration) {\n throw new Error(`Integration \"${formatPackageRef(ref)}\" not found`)\n }\n return integration\n }\n\n public async findPublicOrPrivateIntegration(ref: ApiPackageRef): Promise<PublicOrPrivateIntegration | undefined> {\n const formatted = formatPackageRef(ref)\n\n const privateIntegration = await this.findPrivateIntegration(ref)\n if (privateIntegration) {\n this._logger.debug(`Found integration \"${formatted}\" in workspace`)\n return privateIntegration\n }\n\n const publicIntegration = await this.findPublicIntegration(ref)\n if (publicIntegration) {\n this._logger.debug(`Found integration \"${formatted}\" in hub`)\n return publicIntegration\n }\n\n return\n }\n\n public async findPrivateIntegration(ref: ApiPackageRef): Promise<PrivateIntegration | undefined> {\n const { workspaceId } = this\n if (ref.type === 'id') {\n return this.client\n .getIntegration(ref)\n .then((r) => ({ ...r.integration, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n return this.client\n .getIntegrationByName(ref)\n .then((r) => ({ ...r.integration, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async findPublicIntegration(ref: ApiPackageRef): Promise<PublicOrUnlistedIntegration | undefined> {\n if (ref.type === 'id') {\n return this.client\n .getPublicIntegrationById(ref)\n .then((r) => ({ ...r.integration, visibility: r.integration.visibility as 'public' | 'unlisted' }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n return this.client\n .getPublicIntegration(ref)\n .then((r) => ({ ...r.integration, visibility: r.integration.visibility as 'public' | 'unlisted' }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async findPublicOrPrivateInterface(ref: ApiPackageRef): Promise<PublicOrPrivateInterface | undefined> {\n const formatted = formatPackageRef(ref)\n\n const privateInterface = await this.findPrivateInterface(ref)\n if (privateInterface) {\n this._logger.debug(`Found interface \"${formatted}\" in workspace`)\n return privateInterface\n }\n\n const publicInterface = await this.findPublicInterface(ref)\n if (publicInterface) {\n this._logger.debug(`Found interface \"${formatted}\" in hub`)\n return publicInterface\n }\n\n return\n }\n\n public async findPrivateInterface(ref: ApiPackageRef): Promise<PrivateInterface | undefined> {\n const { workspaceId } = this\n if (ref.type === 'id') {\n return this.client\n .getInterface(ref)\n .then((r) => ({ ...r.interface, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n return this.client\n .getInterfaceByName(ref)\n .then((r) => ({ ...r.interface, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async getPublicInterface(ref: ApiPackageRef): Promise<PublicInterface> {\n const intrface = await this.findPublicInterface(ref)\n if (!intrface) {\n throw new Error(`Interface \"${formatPackageRef(ref)}\" not found`)\n }\n return intrface\n }\n\n public async findPublicInterface(ref: ApiPackageRef): Promise<PublicInterface | undefined> {\n if (ref.type === 'id') {\n return this.client\n .getPublicInterfaceById(ref)\n .then((r) => ({ ...r.interface, public: true }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n return this.client\n .getPublicInterface(ref)\n .then((r) => ({ ...r.interface, public: true }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async findPublicPlugin(ref: ApiPackageRef): Promise<PublicPlugin | undefined> {\n if (ref.type === 'id') {\n return this.client\n .getPublicPluginById(ref)\n .then((r) => ({ ...r.plugin, public: true }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n return this.client\n .getPublicPlugin(ref)\n .then((r) => ({ ...r.plugin, public: true }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async getPublicOrPrivatePlugin(ref: ApiPackageRef): Promise<PublicOrPrivatePlugin> {\n const plugin = await this.findPublicOrPrivatePlugin(ref)\n if (!plugin) {\n throw new Error(`Plugin \"${formatPackageRef(ref)}\" not found`)\n }\n return plugin\n }\n\n public async findPublicOrPrivatePlugin(ref: ApiPackageRef): Promise<PublicOrPrivatePlugin | undefined> {\n const formatted = formatPackageRef(ref)\n\n const privatePlugin = await this.findPrivatePlugin(ref)\n if (privatePlugin) {\n this._logger.debug(`Found plugin \"${formatted}\" in workspace`)\n return privatePlugin\n }\n\n const publicPlugin = await this.findPublicPlugin(ref)\n if (publicPlugin) {\n this._logger.debug(`Found plugin \"${formatted}\" in hub`)\n return publicPlugin\n }\n\n return\n }\n\n public async findPrivatePlugin(ref: ApiPackageRef): Promise<PrivatePlugin | undefined> {\n const { workspaceId } = this\n if (ref.type === 'id') {\n return this.client\n .getPlugin(ref)\n .then((r) => ({ ...r.plugin, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n return this.client\n .getPluginByName(ref)\n .then((r) => ({ ...r.plugin, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async testLogin(): Promise<void> {\n await this.client.listBots({})\n }\n\n public listAllPages = paging.listAllPages\n\n public async findPreviousIntegrationVersion(ref: NamePackageRef): Promise<PublicOrPrivateIntegration | undefined> {\n const isValidSemverVersion = semver.valid(ref.version)\n\n // Sanity check (this should never happen):\n if (!isValidSemverVersion) {\n throw new errors.BotpressCLIError(`Invalid version \"${ref.version}\" for integration \"${ref.name}\"`)\n }\n\n return this.findPublicOrPrivateIntegration({ ...ref, version: `<${ref.version}` })\n }\n\n public async findBotByName(name: string): Promise<BotSummary | undefined> {\n // api does not allow filtering bots by name\n const allBots = await this.listAllPages(this.client.listBots, (r) => r.bots)\n return allBots.find((b) => b.name === name)\n }\n\n private _returnUndefinedOnError =\n (type: client.ApiError['type']) =>\n (thrown: any): undefined => {\n if (client.isApiError(thrown) && thrown.type ===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IAAI,OAAO,sBAAsB,IAAI,IAAI,GAAG;AAAA,IACpG;AAEA,WAAO,KAAK,+BAA+B,EAAE,GAAG,KAAK,SAAS,IAAI,IAAI,OAAO,GAAG,CAAC;AAAA,EACnF;AAAA,EAEA,MAAa,cAAc,MAA+C;AAExE,UAAM,UAAU,MAAM,KAAK,aAAa,KAAK,OAAO,UAAU,CAAC,MAAM,EAAE,IAAI;AAC3E,WAAO,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI;AAAA,EAC5C;AAAA,EAEQ,0BACN,CAAC,SACD,CAAC,WAA2B;AAC1B,QAAI,OAAO,WAAW,MAAM,KAAK,OAAO,SAAS,MAAM;AACrD;AAAA,IACF;AACA,UAAM;AAAA,EACR;AACJ;",
4
+ "sourcesContent": ["import * as client from '@botpress/client'\nimport semver from 'semver'\nimport yn from 'yn'\nimport * as errors from '../errors'\nimport type { Logger } from '../logger'\nimport { formatPackageRef, ApiPackageRef, NamePackageRef } from '../package-ref'\nimport * as utils from '../utils'\nimport * as paging from './paging'\nimport * as retry from './retry'\n\nimport {\n ApiClientProps,\n PublicOrUnlistedIntegration,\n PrivateIntegration,\n PublicOrPrivateIntegration,\n PublicInterface,\n PrivateInterface,\n PublicOrPrivateInterface,\n PrivatePlugin,\n PublicPlugin,\n PublicOrPrivatePlugin,\n BotSummary,\n} from './types'\n\nexport * from './types'\n\n/**\n * This class is used to wrap the Botpress API and provide a more convenient way to interact with it.\n */\nexport class ApiClient {\n public readonly client: client.Client\n public readonly url: string\n public readonly token: string\n public readonly workspaceId: string\n public readonly botId?: string\n\n public static newClient = (props: ApiClientProps, logger: Logger) => new ApiClient(props, logger)\n\n public constructor(\n props: ApiClientProps,\n private _logger: Logger\n ) {\n const { apiUrl, token, workspaceId, botId } = props\n this.client = new client.Client({\n apiUrl,\n token,\n workspaceId,\n botId,\n retry: retry.config,\n headers: { 'x-multiple-integrations': 'true' },\n })\n this.url = apiUrl\n this.token = token\n this.workspaceId = workspaceId\n this.botId = botId\n }\n\n public get isBotpressWorkspace(): boolean {\n // this environment variable is undocumented and only used internally for dev purposes\n const isBotpressWorkspace = yn(process.env.BP_IS_BOTPRESS_WORKSPACE)\n if (isBotpressWorkspace !== undefined) {\n return isBotpressWorkspace\n }\n return [\n '6a76fa10-e150-4ff6-8f59-a300feec06c1',\n '95de33eb-1551-4af9-9088-e5dcb02efd09',\n '11111111-1111-1111-aaaa-111111111111',\n ].includes(this.workspaceId)\n }\n\n public async safeListTables(req: client.ClientInputs['listTables']): Promise<\n | {\n success: true\n tables: client.ClientOutputs['listTables']['tables']\n }\n | {\n success: false\n error: Error\n }\n > {\n try {\n const result = await this.client.listTables(req)\n return { success: true, tables: result.tables }\n } catch (thrown) {\n const error = thrown instanceof Error ? thrown : new Error(String(thrown))\n return { success: false, error }\n }\n }\n\n public async getWorkspace(): Promise<client.ClientOutputs['getWorkspace']> {\n return this.client.getWorkspace({ id: this.workspaceId })\n }\n\n public async findWorkspaceByHandle(handle: string): Promise<client.ClientOutputs['getWorkspace'] | undefined> {\n const { workspaces } = await this.client.listWorkspaces({ handle })\n return workspaces[0] // There should be only one workspace with a given handle\n }\n\n public switchWorkspace(workspaceId: string): ApiClient {\n return ApiClient.newClient({ apiUrl: this.url, token: this.token, workspaceId }, this._logger)\n }\n\n public switchBot(botId: string): ApiClient {\n return ApiClient.newClient(\n { apiUrl: this.url, token: this.token, botId, workspaceId: this.workspaceId },\n this._logger\n )\n }\n\n public async updateWorkspace(\n props: utils.types.SafeOmit<client.ClientInputs['updateWorkspace'], 'id'>\n ): Promise<client.ClientOutputs['updateWorkspace']> {\n return this.client.updateWorkspace({ id: this.workspaceId, ...props })\n }\n\n public async getPublicOrPrivateIntegration(ref: ApiPackageRef): Promise<PublicOrPrivateIntegration> {\n const integration = await this.findPublicOrPrivateIntegration(ref)\n if (!integration) {\n throw new Error(`Integration \"${formatPackageRef(ref)}\" not found`)\n }\n return integration\n }\n\n public async findPublicOrPrivateIntegration(ref: ApiPackageRef): Promise<PublicOrPrivateIntegration | undefined> {\n const formatted = formatPackageRef(ref)\n\n const privateIntegration = await this.findPrivateIntegration(ref)\n if (privateIntegration) {\n this._logger.debug(`Found integration \"${formatted}\" in workspace`)\n return privateIntegration\n }\n\n const publicIntegration = await this.findPublicIntegration(ref)\n if (publicIntegration) {\n this._logger.debug(`Found integration \"${formatted}\" in hub`)\n return publicIntegration\n }\n\n return\n }\n\n public async findPrivateIntegration(ref: ApiPackageRef): Promise<PrivateIntegration | undefined> {\n const { workspaceId } = this\n if (ref.type === 'id') {\n return this.client\n .getIntegration(ref)\n .then((r) => ({ ...r.integration, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n return this.client\n .getIntegrationByName(ref)\n .then((r) => ({ ...r.integration, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async findPublicIntegration(ref: ApiPackageRef): Promise<PublicOrUnlistedIntegration | undefined> {\n if (ref.type === 'id') {\n return this.client\n .getPublicIntegrationById(ref)\n .then((r) => ({ ...r.integration, visibility: r.integration.visibility as 'public' | 'unlisted' }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n return this.client\n .getPublicIntegration(ref)\n .then((r) => ({ ...r.integration, visibility: r.integration.visibility as 'public' | 'unlisted' }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async findPublicOrPrivateInterface(ref: ApiPackageRef): Promise<PublicOrPrivateInterface | undefined> {\n const formatted = formatPackageRef(ref)\n\n const privateInterface = await this.findPrivateInterface(ref)\n if (privateInterface) {\n this._logger.debug(`Found interface \"${formatted}\" in workspace`)\n return privateInterface\n }\n\n const publicInterface = await this.findPublicInterface(ref)\n if (publicInterface) {\n this._logger.debug(`Found interface \"${formatted}\" in hub`)\n return publicInterface\n }\n\n return\n }\n\n public async findPrivateInterface(ref: ApiPackageRef): Promise<PrivateInterface | undefined> {\n const { workspaceId } = this\n if (ref.type === 'id') {\n return this.client\n .getInterface(ref)\n .then((r) => ({ ...r.interface, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n return this.client\n .getInterfaceByName(ref)\n .then((r) => ({ ...r.interface, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async getPublicInterface(ref: ApiPackageRef): Promise<PublicInterface> {\n const intrface = await this.findPublicInterface(ref)\n if (!intrface) {\n throw new Error(`Interface \"${formatPackageRef(ref)}\" not found`)\n }\n return intrface\n }\n\n public async findPublicInterface(ref: ApiPackageRef): Promise<PublicInterface | undefined> {\n if (ref.type === 'id') {\n return this.client\n .getPublicInterfaceById(ref)\n .then((r) => ({ ...r.interface, public: true }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n return this.client\n .getPublicInterface(ref)\n .then((r) => ({ ...r.interface, public: true }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async findPublicPlugin(ref: ApiPackageRef): Promise<PublicPlugin | undefined> {\n if (ref.type === 'id') {\n return this.client\n .getPublicPluginById(ref)\n .then((r) => ({ ...r.plugin, public: true }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n return this.client\n .getPublicPlugin(ref)\n .then((r) => ({ ...r.plugin, public: true }) as const)\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async getPublicOrPrivatePlugin(ref: ApiPackageRef): Promise<PublicOrPrivatePlugin> {\n const plugin = await this.findPublicOrPrivatePlugin(ref)\n if (!plugin) {\n throw new Error(`Plugin \"${formatPackageRef(ref)}\" not found`)\n }\n return plugin\n }\n\n public async findPublicOrPrivatePlugin(ref: ApiPackageRef): Promise<PublicOrPrivatePlugin | undefined> {\n const formatted = formatPackageRef(ref)\n\n const privatePlugin = await this.findPrivatePlugin(ref)\n if (privatePlugin) {\n this._logger.debug(`Found plugin \"${formatted}\" in workspace`)\n return privatePlugin\n }\n\n const publicPlugin = await this.findPublicPlugin(ref)\n if (publicPlugin) {\n this._logger.debug(`Found plugin \"${formatted}\" in hub`)\n return publicPlugin\n }\n\n return\n }\n\n public async findPrivatePlugin(ref: ApiPackageRef): Promise<PrivatePlugin | undefined> {\n const { workspaceId } = this\n if (ref.type === 'id') {\n return this.client\n .getPlugin(ref)\n .then((r) => ({ ...r.plugin, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n return this.client\n .getPluginByName(ref)\n .then((r) => ({ ...r.plugin, workspaceId }))\n .catch(this._returnUndefinedOnError('ResourceNotFound'))\n }\n\n public async testLogin(): Promise<void> {\n await this.client.listBots({})\n }\n\n public listAllPages = paging.listAllPages\n\n public async findPreviousIntegrationVersion(ref: NamePackageRef): Promise<PublicOrPrivateIntegration | undefined> {\n const isValidSemverVersion = semver.valid(ref.version)\n\n // Sanity check (this should never happen):\n if (!isValidSemverVersion) {\n throw new errors.BotpressCLIError(`Invalid version \"${ref.version}\" for integration \"${ref.name}\"`)\n }\n\n return this.findPublicOrPrivateIntegration({ ...ref, version: `<${ref.version}` })\n }\n\n public async findBotByName(name: string): Promise<BotSummary | undefined> {\n // api does not allow filtering bots by name\n const allBots = await this.listAllPages(this.client.listBots, (r) => r.bots)\n return allBots.find((b) => b.name === name)\n }\n\n private _returnUndefinedOnError =\n (type: client.ApiError['type']) =>\n (thrown: any): undefined => {\n if (client.isApiError(thrown) && thrown.type === type) {\n return\n }\n throw thrown\n }\n\n public async getOrGenerateShareableId(\n botId: string,\n integrationId: string,\n integrationAlias: string\n ): Promise<string> {\n const { shareableId, isExpired } = await this.client\n .getIntegrationShareableId({\n botId,\n integrationId,\n integrationInstanceAlias: integrationAlias,\n })\n .catch(() => ({ shareableId: undefined, isExpired: true }))\n if (shareableId && !isExpired) {\n return shareableId\n }\n const { shareableId: newShareableId } = await this.client.createIntegrationShareableId({\n botId,\n integrationId,\n integrationInstanceAlias: integrationAlias,\n })\n return newShareableId\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AA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G,KAAK,SAAS,IAAI,IAAI,OAAO,GAAG,CAAC;AAAA,EACnF;AAAA,EAEA,MAAa,cAAc,MAA+C;AAExE,UAAM,UAAU,MAAM,KAAK,aAAa,KAAK,OAAO,UAAU,CAAC,MAAM,EAAE,IAAI;AAC3E,WAAO,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI;AAAA,EAC5C;AAAA,EAEQ,0BACN,CAAC,SACD,CAAC,WAA2B;AAC1B,QAAI,OAAO,WAAW,MAAM,KAAK,OAAO,SAAS,MAAM;AACrD;AAAA,IACF;AACA,UAAM;AAAA,EACR;AAAA,EAEF,MAAa,yBACX,OACA,eACA,kBACiB;AACjB,UAAM,EAAE,aAAa,UAAU,IAAI,MAAM,KAAK,OAC3C,0BAA0B;AAAA,MACzB;AAAA,MACA;AAAA,MACA,0BAA0B;AAAA,IAC5B,CAAC,EACA,MAAM,OAAO,EAAE,aAAa,QAAW,WAAW,KAAK,EAAE;AAC5D,QAAI,eAAe,CAAC,WAAW;AAC7B,aAAO;AAAA,IACT;AACA,UAAM,EAAE,aAAa,eAAe,IAAI,MAAM,KAAK,OAAO,6BAA6B;AAAA,MACrF;AAAA,MACA;AAAA,MACA,0BAA0B;AAAA,IAC5B,CAAC;AACD,WAAO;AAAA,EACT;AACF;",
6
6
  "names": ["yn", "semver"]
7
7
  }
@@ -409,7 +409,7 @@ ${Object.entries(failedIntegrations).map(([key, int]) => `\u2022 ${key}: ${int.s
409
409
  const tablesPublisher = new tables.TablesPublisher({ api, logger: this.logger, prompt: this.prompt });
410
410
  await tablesPublisher.deployTables({ botId: updatedBot.id, botDefinition });
411
411
  line.success("Bot deployed");
412
- this.displayWebhookUrls(updatedBot);
412
+ await this.displayIntegrationUrls({ api, bot: updatedBot });
413
413
  }
414
414
  async _createNewBot(api) {
415
415
  const line = this.logger.line();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/command-implementations/deploy-command.ts"],
4
- "sourcesContent": ["import type * as client from '@botpress/client'\nimport * as sdk from '@botpress/sdk'\nimport chalk from 'chalk'\nimport * as fs from 'fs'\nimport semver from 'semver'\nimport * as apiUtils from '../api'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as tables from '../tables'\nimport * as utils from '../utils'\nimport { BuildCommand } from './build-command'\nimport { ProjectCommand } from './project-command'\n\nexport type DeployCommandDefinition = typeof commandDefinitions.deploy\nexport class DeployCommand extends ProjectCommand<DeployCommandDefinition> {\n public async run(): Promise<void> {\n const api = await this.ensureLoginAndCreateClient(this.argv)\n\n if (!this.argv.noBuild) {\n await this._runBuild() // This ensures the bundle is always synced with source code\n }\n\n const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n\n if (projectType === 'integration') {\n const projectDef = await resolveProjectDefinition()\n return this._deployIntegration(api, projectDef.definition)\n }\n if (projectType === 'interface') {\n const projectDef = await resolveProjectDefinition()\n return this._deployInterface(api, projectDef.definition)\n }\n if (projectType === 'plugin') {\n const projectDef = await resolveProjectDefinition()\n return this._deployPlugin(api, projectDef.definition)\n }\n if (projectType === 'bot') {\n const projectDef = await resolveProjectDefinition()\n return this._deployBot(api, projectDef.definition, this.argv.botId, this.argv.createNewBot)\n }\n throw new errors.UnsupportedProjectType()\n }\n\n private async _runBuild() {\n return new BuildCommand(this.api, this.prompt, this.logger, this.argv).setProjectContext(this.projectContext).run()\n }\n\n private get _visibility(): 'public' | 'private' | 'unlisted' {\n if (this.argv.public && this.argv.visibility === 'private') {\n this.logger.warn('The --public flag is deprecated. Please use \"--visibility public\" instead.')\n return 'public'\n }\n\n if (this.argv.public && this.argv.visibility !== 'private') {\n this.logger.warn('The --public flag and --visibility option are both present. Ignoring the --public flag...')\n }\n\n return this.argv.visibility\n }\n\n private async _deployIntegration(api: apiUtils.ApiClient, integrationDef: sdk.IntegrationDefinition) {\n const res = await this._manageWorkspaceHandle(api, integrationDef)\n if (!res) return\n const { integration: updatedIntegrationDef, workspaceId } = res\n integrationDef = updatedIntegrationDef\n if (workspaceId) {\n api = api.switchWorkspace(workspaceId)\n }\n\n const { name, version } = integrationDef\n\n if (integrationDef.icon && !integrationDef.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (integrationDef.readme && !integrationDef.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const integration = await api.findPublicOrPrivateIntegration({ type: 'name', name, version })\n if (integration && integration.workspaceId !== api.workspaceId) {\n throw new errors.BotpressCLIError(\n `Public integration ${name} v${version} is already deployed in another workspace.`\n )\n }\n\n if (integration && integration.visibility !== 'private' && !api.isBotpressWorkspace) {\n throw new errors.BotpressCLIError(\n `Integration ${name} v${version} is already deployed publicly and cannot be updated. Please bump the version.`\n )\n }\n\n let message: string\n if (integration) {\n this.logger.warn('Integration already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override integration ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy integration ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n this.logger.debug('Preparing integration request body...')\n\n const createBody = {\n ...(await this.prepareCreateIntegrationBody(integrationDef)),\n ...(await this.prepareIntegrationDependencies(integrationDef, api)),\n visibility: this._visibility,\n }\n\n const startedMessage = `Deploying integration ${chalk.bold(name)} v${version}...`\n const successMessage = 'Integration deployed'\n if (integration) {\n const updateBody = apiUtils.prepareUpdateIntegrationBody(\n {\n id: integration.id,\n ...createBody,\n },\n integration\n )\n\n const { secrets: knownSecrets } = integration\n updateBody.secrets = await this.promptSecrets(integrationDef, this.argv, { knownSecrets })\n this._detectDeprecatedFeatures(integrationDef, { allowDeprecated: true })\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.log('Dry-run mode is active. Simulating integration update...')\n\n await api.client.validateIntegrationUpdate(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update integration \"${name}\"`)\n })\n } else {\n await api.client.updateIntegration(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update integration \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n this.logger.debug(`looking for previous version of integration \"${name}\"`)\n const previousVersion = await api.findPreviousIntegrationVersion({ type: 'name', name, version })\n\n if (previousVersion) {\n this.logger.debug(`previous version found: ${previousVersion.version}`)\n } else {\n this.logger.debug('no previous version found')\n }\n\n const knownSecrets = previousVersion?.secrets\n\n createBody.secrets = await this.promptSecrets(integrationDef, this.argv, { knownSecrets })\n this._detectDeprecatedFeatures(integrationDef, {\n allowDeprecated: this._allowDeprecatedFeatures(integrationDef, previousVersion),\n })\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.log('Dry-run mode is active. Simulating integration creation...')\n\n await api.client.validateIntegrationCreation(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create integration \"${name}\"`)\n })\n } else {\n await api.client.createIntegration(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create integration \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private async _deployInterface(api: apiUtils.ApiClient, interfaceDeclaration: sdk.InterfaceDefinition) {\n if (this._visibility === 'unlisted') {\n throw new errors.BotpressCLIError(\n 'Unlisted visibility is not supported for interfaces. Please use \"public\" or \"private\".'\n )\n }\n\n if (interfaceDeclaration.icon && !interfaceDeclaration.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (interfaceDeclaration.readme && !interfaceDeclaration.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const { name, version } = interfaceDeclaration\n const intrface = await api.findPublicOrPrivateInterface({ type: 'name', name, version })\n\n let message: string\n if (intrface) {\n this.logger.warn('Interface already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override interface ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy interface ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n const icon = await this.readProjectFile(interfaceDeclaration.icon, 'base64')\n const readme = await this.readProjectFile(interfaceDeclaration.readme, 'base64')\n\n if (this._visibility !== 'public') {\n this.logger.warn(\n 'You are currently publishing a private interface, which cannot be used by integrations and plugins. To fix this, change the visibility to \"public\"'\n )\n }\n\n const createBody = {\n ...(await apiUtils.prepareCreateInterfaceBody(interfaceDeclaration)),\n public: this._visibility === 'public',\n icon,\n readme,\n }\n\n const startedMessage = `Deploying interface ${chalk.bold(name)} v${version}...`\n const successMessage = 'Interface deployed'\n if (intrface) {\n const updateBody = apiUtils.prepareUpdateInterfaceBody(\n {\n id: intrface.id,\n ...createBody,\n },\n intrface\n )\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for interface updates. Skipping deployment...')\n } else {\n await api.client.updateInterface(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update interface \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for interface creation. Skipping deployment...')\n } else {\n await api.client.createInterface(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create interface \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private async _deployPlugin(api: apiUtils.ApiClient, pluginDef: sdk.PluginDefinition) {\n if (this._visibility === 'unlisted') {\n throw new errors.BotpressCLIError(\n 'Unlisted visibility is not supported for plugins. Please use \"public\" or \"private\".'\n )\n }\n\n const codeCJS = await fs.promises.readFile(this.projectPaths.abs.outFileCJS, 'utf-8')\n const codeESM = await fs.promises.readFile(this.projectPaths.abs.outFileESM, 'utf-8')\n\n const { name, version } = pluginDef\n\n if (pluginDef.icon && !pluginDef.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (pluginDef.readme && !pluginDef.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const plugin = await api.findPublicOrPrivatePlugin({ type: 'name', name, version })\n\n let message: string\n if (plugin) {\n this.logger.warn('Plugin already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override plugin ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy plugin ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n this.logger.debug('Preparing plugin request body...')\n\n const icon = await this.readProjectFile(pluginDef.icon, 'base64')\n const readme = await this.readProjectFile(pluginDef.readme, 'base64')\n\n const createBody = {\n ...(await apiUtils.prepareCreatePluginBody(pluginDef)),\n ...(await this.preparePluginDependencies(pluginDef, api)),\n public: this._visibility === 'public',\n icon,\n readme,\n code: {\n node: codeCJS,\n browser: codeESM,\n },\n }\n\n const startedMessage = `Deploying plugin ${chalk.bold(name)} v${version}...`\n const successMessage = 'Plugin deployed'\n if (plugin) {\n const updateBody = apiUtils.prepareUpdatePluginBody(\n {\n id: plugin.id,\n ...createBody,\n },\n plugin\n )\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for plugin updates. Skipping deployment...')\n } else {\n await api.client.updatePlugin(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update plugin \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for plugin creation. Skipping deployment...')\n } else {\n await api.client.createPlugin(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create plugin \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private _allowDeprecatedFeatures(\n integrationDef: sdk.IntegrationDefinition,\n previousVersion: client.Integration | undefined\n ): boolean {\n if (this.argv.allowDeprecated) {\n return true\n }\n\n if (!previousVersion) {\n return false\n }\n\n const versionDiff = semver.diff(integrationDef.version, previousVersion.version)\n if (!versionDiff) {\n return false\n }\n\n return utils.semver.releases.lt(versionDiff, 'major')\n }\n\n private _detectDeprecatedFeatures(\n integrationDef: sdk.IntegrationDefinition,\n opts: { allowDeprecated?: boolean } = {}\n ) {\n const deprecatedFields: string[] = []\n const { user, channels } = integrationDef\n if (user?.creation?.enabled) {\n deprecatedFields.push('user.creation')\n }\n\n for (const [channelName, channel] of Object.entries(channels ?? {})) {\n if (channel?.conversation?.creation?.enabled) {\n deprecatedFields.push(`channels.${channelName}.creation`)\n }\n }\n\n if (!deprecatedFields.length) {\n return\n }\n\n const errorMessage = `The following fields of the integration's definition are deprecated: ${deprecatedFields.join(\n ', '\n )}`\n\n if (opts.allowDeprecated) {\n this.logger.warn(errorMessage)\n } else {\n throw new errors.BotpressCLIError(errorMessage)\n }\n }\n\n private async _deployBot(\n api: apiUtils.ApiClient,\n botDefinition: sdk.BotDefinition,\n argvBotId: string | undefined,\n argvCreateNew: boolean | undefined\n ) {\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for bot deployments. Skipping deployment...')\n return\n }\n\n const outfile = this.projectPaths.abs.outFileCJS\n const code = await fs.promises.readFile(outfile, 'utf-8')\n\n let bot: client.Bot\n if (argvBotId && argvCreateNew) {\n throw new errors.BotpressCLIError('Cannot specify both --botId and --createNew')\n } else if (argvCreateNew) {\n const confirm = await this.prompt.confirm('Are you sure you want to create a new bot ?')\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n bot = await this._createNewBot(api)\n } else {\n bot = await this._getExistingBot(api, argvBotId)\n\n const confirm = await this.prompt.confirm(`Are you sure you want to deploy the bot \"${bot.name}\"?`)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n }\n\n const line = this.logger.line()\n line.started(`Deploying bot ${chalk.bold(bot.name)}...`)\n\n const updateBotBody = apiUtils.prepareUpdateBotBody(\n {\n ...(await apiUtils.prepareCreateBotBody(botDefinition)),\n ...(await this.prepareBotDependencies(botDefinition, api)),\n id: bot.id,\n code,\n },\n bot\n )\n\n const { bot: updatedBot } = await api.client.updateBot(updateBotBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update bot \"${bot.name}\"`)\n })\n\n this.validateIntegrationRegistration(updatedBot, (failedIntegrations) =>\n this.logger.warn(\n `Some integrations failed to register:\\n${Object.entries(failedIntegrations)\n .map(([key, int]) => `\u2022 ${key}: ${int.statusReason}`)\n .join('\\n')}`\n )\n )\n\n const tablesPublisher = new tables.TablesPublisher({ api, logger: this.logger, prompt: this.prompt })\n await tablesPublisher.deployTables({ botId: updatedBot.id, botDefinition })\n\n line.success('Bot deployed')\n this.displayWebhookUrls(updatedBot)\n }\n\n private async _createNewBot(api: apiUtils.ApiClient): Promise<client.Bot> {\n const line = this.logger.line()\n const { bot: createdBot } = await api.client.createBot({}).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not create bot')\n })\n line.success(`Bot created with ID \"${createdBot.id}\" and name \"${createdBot.name}\"`)\n await this.projectCache.set('botId', createdBot.id)\n return createdBot\n }\n\n private async _getExistingBot(api: apiUtils.ApiClient, botId: string | undefined): Promise<client.Bot> {\n const promptedBotId = await this.projectCache.sync('botId', botId, async (defaultId) => {\n const userBots = await api\n .listAllPages(api.client.listBots, (r) => r.bots)\n .catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not fetch existing bots')\n })\n\n if (!userBots.length) {\n throw new errors.NoBotsFoundError()\n }\n\n const initial = userBots.find((bot) => bot.id === defaultId)\n\n const prompted = await this.prompt.select('Which bot do you want to deploy?', {\n initial: initial && { title: initial.name, value: initial.id },\n choices: userBots.map((bot) => ({ title: bot.name, value: bot.id })),\n })\n\n if (!prompted) {\n throw new errors.ParamRequiredError('Bot Id')\n }\n\n return prompted\n })\n\n const { bot: fetchedBot } = await api.client.getBot({ id: promptedBotId }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not get bot info')\n })\n\n return fetchedBot\n }\n\n private async _manageWorkspaceHandle(\n api: apiUtils.ApiClient,\n integration: sdk.IntegrationDefinition\n ): Promise<\n | {\n integration: sdk.IntegrationDefinition\n workspaceId?: string // Set if user opted to deploy on another available workspace\n }\n | undefined\n > {\n const { name: localName, workspaceHandle: localHandle } = this._parseIntegrationName(integration.name)\n if (!localHandle && api.isBotpressWorkspace) {\n this.logger.debug('Botpress workspace detected; workspace handle omitted')\n return { integration } // botpress has the right to omit workspace handle\n }\n\n const { handle: remoteHandle, name: workspaceName } = await api.getWorkspace().catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not fetch workspace')\n })\n\n if (localHandle && remoteHandle) {\n let workspaceId: string | undefined = undefined\n if (localHandle !== remoteHandle) {\n const remoteWorkspace = await api.findWorkspaceByHandle(localHandle).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not list workspaces')\n })\n if (!remoteWorkspace) {\n throw new errors.BotpressCLIError(\n `The integration handle \"${localHandle}\" is not associated with any of your workspaces.`\n )\n }\n this.logger.warn(\n `Your are logged in to workspace \"${workspaceName}\" but integration handle \"${localHandle}\" belongs to \"${remoteWorkspace.name}\".`\n )\n const confirmUseAlternateWorkspace = await this.prompt.confirm(\n 'Do you want to deploy integration on this workspace instead?'\n )\n if (!confirmUseAlternateWorkspace) {\n throw new errors.BotpressCLIError(\n `Cannot deploy integration with handle \"${localHandle}\" on workspace \"${workspaceName}\"`\n )\n }\n\n workspaceId = remoteWorkspace.id\n }\n return { integration, workspaceId }\n }\n\n const workspaceHandleIsMandatoryMsg = 'Cannot deploy integration without workspace handle'\n\n if (!localHandle && remoteHandle) {\n const confirmAddHandle = await this.prompt.confirm(\n `Your current workspace handle is \"${remoteHandle}\". Do you want to use the name \"${remoteHandle}/${localName}\"?`\n )\n if (!confirmAddHandle) {\n this.logger.log('Aborted')\n return\n }\n const newName = `${remoteHandle}/${localName}`\n return { integration: new sdk.IntegrationDefinition({ ...integration, name: newName }) }\n }\n\n if (localHandle && !remoteHandle) {\n const { available } = await api.client.checkHandleAvailability({ handle: localHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not check handle availability')\n })\n\n if (!available) {\n throw new errors.BotpressCLIError(`Handle \"${localHandle}\" is not yours and is not available`)\n }\n\n const confirmClaimHandle = await this.prompt.confirm(\n `Handle \"${localHandle}\" is available. Do you want to claim it for your workspace ${workspaceName}?`\n )\n if (!confirmClaimHandle) {\n throw new errors.BotpressCLIError(workspaceHandleIsMandatoryMsg)\n }\n\n await api.updateWorkspace({ handle: localHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not claim handle \"${localHandle}\"`)\n })\n\n this.logger.success(`Handle \"${localHandle}\" is now yours!`)\n return { integration }\n }\n\n this.logger.warn(\"It seems you don't have a workspace handle yet.\")\n let claimedHandle: string | undefined = undefined\n do {\n const prompted = await this.prompt.text('Please enter a workspace handle')\n if (!prompted) {\n throw new errors.BotpressCLIError(workspaceHandleIsMandatoryMsg)\n }\n\n const { available, suggestions } = await api.client.checkHandleAvailability({ handle: prompted })\n if (!available) {\n this.logger.warn(`Handle \"${prompted}\" is not available. Suggestions: ${suggestions.join(', ')}`)\n continue\n }\n\n claimedHandle = prompted\n await api.updateWorkspace({ handle: claimedHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not claim handle \"${claimedHandle}\"`)\n })\n } while (!claimedHandle)\n\n this.logger.success(`Handle \"${claimedHandle}\" is yours!`)\n const newName = `${claimedHandle}/${localName}`\n return { integration: new sdk.IntegrationDefinition({ ...integration, name: newName }) }\n }\n\n private _parseIntegrationName = (integrationName: string): { name: string; workspaceHandle?: string } => {\n const parts = integrationName.split('/')\n if (parts.length > 2) {\n throw new errors.BotpressCLIError(\n `Invalid integration name \"${integrationName}\": a single forward slash is allowed`\n )\n }\n if (parts.length === 2) {\n const [workspaceHandle, name] = parts as [string, string]\n return { name, workspaceHandle }\n }\n const [name] = parts as [string]\n return { name }\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,UAAqB;AACrB,mBAAkB;AAClB,SAAoB;AACpB,oBAAmB;AACnB,eAA0B;AAE1B,aAAwB;AACxB,aAAwB;AACxB,YAAuB;AACvB,2BAA6B;AAC7B,6BAA+B;AAGxB,MAAM,sBAAsB,sCAAwC;AAAA,EACzE,MAAa,MAAqB;AAChC,UAAM,MAAM,MAAM,KAAK,2BAA2B,KAAK,IAAI;AAE3D,QAAI,CAAC,KAAK,KAAK,SAAS;AACtB,YAAM,KAAK,UAAU;AAAA,IACvB;AAEA,UAAM,EAAE,aAAa,yBAAyB,IAAI,KAAK,4BAA4B;AAEnF,QAAI,gBAAgB,eAAe;AACjC,YAAM,aAAa,MAAM,yBAAyB;AAClD,aAAO,KAAK,mBAAmB,KAAK,WAAW,UAAU;AAAA,IAC3D;AACA,QAAI,gBAAgB,aAAa;AAC/B,YAAM,aAAa,MAAM,yBAAyB;AAClD,aAAO,KAAK,iBAAiB,KAAK,WAAW,UAAU;AAAA,IACzD;AACA,QAAI,gBAAgB,UAAU;AAC5B,YAAM,aAAa,MAAM,yBAAyB;AAClD,aAAO,KAAK,cAAc,KAAK,WAAW,UAAU;AAAA,IACtD;AACA,QAAI,gBAAgB,OAAO;AACzB,YAAM,aAAa,MAAM,yBAAyB;AAClD,aAAO,KAAK,WAAW,KAAK,WAAW,YAAY,KAAK,KAAK,OAAO,KAAK,KAAK,YAAY;AAAA,IAC5F;AACA,UAAM,IAAI,OAAO,uBAAuB;AAAA,EAC1C;AAAA,EAEA,MAAc,YAAY;AACxB,WAAO,IAAI,k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,YAAM,CAAC,iBAAiBC,KAAI,IAAI;AAChC,aAAO,EAAE,MAAAA,OAAM,gBAAgB;AAAA,IACjC;AACA,UAAM,CAAC,IAAI,IAAI;AACf,WAAO,EAAE,KAAK;AAAA,EAChB;AACF;",
4
+ "sourcesContent": ["import type * as client from '@botpress/client'\nimport * as sdk from '@botpress/sdk'\nimport chalk from 'chalk'\nimport * as fs from 'fs'\nimport semver from 'semver'\nimport * as apiUtils from '../api'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as tables from '../tables'\nimport * as utils from '../utils'\nimport { BuildCommand } from './build-command'\nimport { ProjectCommand } from './project-command'\n\nexport type DeployCommandDefinition = typeof commandDefinitions.deploy\nexport class DeployCommand extends ProjectCommand<DeployCommandDefinition> {\n public async run(): Promise<void> {\n const api = await this.ensureLoginAndCreateClient(this.argv)\n\n if (!this.argv.noBuild) {\n await this._runBuild() // This ensures the bundle is always synced with source code\n }\n\n const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n\n if (projectType === 'integration') {\n const projectDef = await resolveProjectDefinition()\n return this._deployIntegration(api, projectDef.definition)\n }\n if (projectType === 'interface') {\n const projectDef = await resolveProjectDefinition()\n return this._deployInterface(api, projectDef.definition)\n }\n if (projectType === 'plugin') {\n const projectDef = await resolveProjectDefinition()\n return this._deployPlugin(api, projectDef.definition)\n }\n if (projectType === 'bot') {\n const projectDef = await resolveProjectDefinition()\n return this._deployBot(api, projectDef.definition, this.argv.botId, this.argv.createNewBot)\n }\n throw new errors.UnsupportedProjectType()\n }\n\n private async _runBuild() {\n return new BuildCommand(this.api, this.prompt, this.logger, this.argv).setProjectContext(this.projectContext).run()\n }\n\n private get _visibility(): 'public' | 'private' | 'unlisted' {\n if (this.argv.public && this.argv.visibility === 'private') {\n this.logger.warn('The --public flag is deprecated. Please use \"--visibility public\" instead.')\n return 'public'\n }\n\n if (this.argv.public && this.argv.visibility !== 'private') {\n this.logger.warn('The --public flag and --visibility option are both present. Ignoring the --public flag...')\n }\n\n return this.argv.visibility\n }\n\n private async _deployIntegration(api: apiUtils.ApiClient, integrationDef: sdk.IntegrationDefinition) {\n const res = await this._manageWorkspaceHandle(api, integrationDef)\n if (!res) return\n const { integration: updatedIntegrationDef, workspaceId } = res\n integrationDef = updatedIntegrationDef\n if (workspaceId) {\n api = api.switchWorkspace(workspaceId)\n }\n\n const { name, version } = integrationDef\n\n if (integrationDef.icon && !integrationDef.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (integrationDef.readme && !integrationDef.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const integration = await api.findPublicOrPrivateIntegration({ type: 'name', name, version })\n if (integration && integration.workspaceId !== api.workspaceId) {\n throw new errors.BotpressCLIError(\n `Public integration ${name} v${version} is already deployed in another workspace.`\n )\n }\n\n if (integration && integration.visibility !== 'private' && !api.isBotpressWorkspace) {\n throw new errors.BotpressCLIError(\n `Integration ${name} v${version} is already deployed publicly and cannot be updated. Please bump the version.`\n )\n }\n\n let message: string\n if (integration) {\n this.logger.warn('Integration already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override integration ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy integration ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n this.logger.debug('Preparing integration request body...')\n\n const createBody = {\n ...(await this.prepareCreateIntegrationBody(integrationDef)),\n ...(await this.prepareIntegrationDependencies(integrationDef, api)),\n visibility: this._visibility,\n }\n\n const startedMessage = `Deploying integration ${chalk.bold(name)} v${version}...`\n const successMessage = 'Integration deployed'\n if (integration) {\n const updateBody = apiUtils.prepareUpdateIntegrationBody(\n {\n id: integration.id,\n ...createBody,\n },\n integration\n )\n\n const { secrets: knownSecrets } = integration\n updateBody.secrets = await this.promptSecrets(integrationDef, this.argv, { knownSecrets })\n this._detectDeprecatedFeatures(integrationDef, { allowDeprecated: true })\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.log('Dry-run mode is active. Simulating integration update...')\n\n await api.client.validateIntegrationUpdate(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update integration \"${name}\"`)\n })\n } else {\n await api.client.updateIntegration(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update integration \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n this.logger.debug(`looking for previous version of integration \"${name}\"`)\n const previousVersion = await api.findPreviousIntegrationVersion({ type: 'name', name, version })\n\n if (previousVersion) {\n this.logger.debug(`previous version found: ${previousVersion.version}`)\n } else {\n this.logger.debug('no previous version found')\n }\n\n const knownSecrets = previousVersion?.secrets\n\n createBody.secrets = await this.promptSecrets(integrationDef, this.argv, { knownSecrets })\n this._detectDeprecatedFeatures(integrationDef, {\n allowDeprecated: this._allowDeprecatedFeatures(integrationDef, previousVersion),\n })\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.log('Dry-run mode is active. Simulating integration creation...')\n\n await api.client.validateIntegrationCreation(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create integration \"${name}\"`)\n })\n } else {\n await api.client.createIntegration(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create integration \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private async _deployInterface(api: apiUtils.ApiClient, interfaceDeclaration: sdk.InterfaceDefinition) {\n if (this._visibility === 'unlisted') {\n throw new errors.BotpressCLIError(\n 'Unlisted visibility is not supported for interfaces. Please use \"public\" or \"private\".'\n )\n }\n\n if (interfaceDeclaration.icon && !interfaceDeclaration.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (interfaceDeclaration.readme && !interfaceDeclaration.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const { name, version } = interfaceDeclaration\n const intrface = await api.findPublicOrPrivateInterface({ type: 'name', name, version })\n\n let message: string\n if (intrface) {\n this.logger.warn('Interface already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override interface ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy interface ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n const icon = await this.readProjectFile(interfaceDeclaration.icon, 'base64')\n const readme = await this.readProjectFile(interfaceDeclaration.readme, 'base64')\n\n if (this._visibility !== 'public') {\n this.logger.warn(\n 'You are currently publishing a private interface, which cannot be used by integrations and plugins. To fix this, change the visibility to \"public\"'\n )\n }\n\n const createBody = {\n ...(await apiUtils.prepareCreateInterfaceBody(interfaceDeclaration)),\n public: this._visibility === 'public',\n icon,\n readme,\n }\n\n const startedMessage = `Deploying interface ${chalk.bold(name)} v${version}...`\n const successMessage = 'Interface deployed'\n if (intrface) {\n const updateBody = apiUtils.prepareUpdateInterfaceBody(\n {\n id: intrface.id,\n ...createBody,\n },\n intrface\n )\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for interface updates. Skipping deployment...')\n } else {\n await api.client.updateInterface(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update interface \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for interface creation. Skipping deployment...')\n } else {\n await api.client.createInterface(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create interface \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private async _deployPlugin(api: apiUtils.ApiClient, pluginDef: sdk.PluginDefinition) {\n if (this._visibility === 'unlisted') {\n throw new errors.BotpressCLIError(\n 'Unlisted visibility is not supported for plugins. Please use \"public\" or \"private\".'\n )\n }\n\n const codeCJS = await fs.promises.readFile(this.projectPaths.abs.outFileCJS, 'utf-8')\n const codeESM = await fs.promises.readFile(this.projectPaths.abs.outFileESM, 'utf-8')\n\n const { name, version } = pluginDef\n\n if (pluginDef.icon && !pluginDef.icon.toLowerCase().endsWith('.svg')) {\n throw new errors.BotpressCLIError('Icon must be an SVG file')\n }\n\n if (pluginDef.readme && !pluginDef.readme.toLowerCase().endsWith('.md')) {\n throw new errors.BotpressCLIError('Readme must be a Markdown file')\n }\n\n const plugin = await api.findPublicOrPrivatePlugin({ type: 'name', name, version })\n\n let message: string\n if (plugin) {\n this.logger.warn('Plugin already exists. If you decide to deploy, it will override the existing one.')\n message = `Are you sure you want to override plugin ${name} v${version}?`\n } else {\n message = `Are you sure you want to deploy plugin ${name} v${version}?`\n }\n\n const confirm = await this.prompt.confirm(message)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n this.logger.debug('Preparing plugin request body...')\n\n const icon = await this.readProjectFile(pluginDef.icon, 'base64')\n const readme = await this.readProjectFile(pluginDef.readme, 'base64')\n\n const createBody = {\n ...(await apiUtils.prepareCreatePluginBody(pluginDef)),\n ...(await this.preparePluginDependencies(pluginDef, api)),\n public: this._visibility === 'public',\n icon,\n readme,\n code: {\n node: codeCJS,\n browser: codeESM,\n },\n }\n\n const startedMessage = `Deploying plugin ${chalk.bold(name)} v${version}...`\n const successMessage = 'Plugin deployed'\n if (plugin) {\n const updateBody = apiUtils.prepareUpdatePluginBody(\n {\n id: plugin.id,\n ...createBody,\n },\n plugin\n )\n\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for plugin updates. Skipping deployment...')\n } else {\n await api.client.updatePlugin(updateBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update plugin \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n } else {\n const line = this.logger.line()\n line.started(startedMessage)\n\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for plugin creation. Skipping deployment...')\n } else {\n await api.client.createPlugin(createBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not create plugin \"${name}\"`)\n })\n }\n\n line.success(successMessage)\n }\n }\n\n private _allowDeprecatedFeatures(\n integrationDef: sdk.IntegrationDefinition,\n previousVersion: client.Integration | undefined\n ): boolean {\n if (this.argv.allowDeprecated) {\n return true\n }\n\n if (!previousVersion) {\n return false\n }\n\n const versionDiff = semver.diff(integrationDef.version, previousVersion.version)\n if (!versionDiff) {\n return false\n }\n\n return utils.semver.releases.lt(versionDiff, 'major')\n }\n\n private _detectDeprecatedFeatures(\n integrationDef: sdk.IntegrationDefinition,\n opts: { allowDeprecated?: boolean } = {}\n ) {\n const deprecatedFields: string[] = []\n const { user, channels } = integrationDef\n if (user?.creation?.enabled) {\n deprecatedFields.push('user.creation')\n }\n\n for (const [channelName, channel] of Object.entries(channels ?? {})) {\n if (channel?.conversation?.creation?.enabled) {\n deprecatedFields.push(`channels.${channelName}.creation`)\n }\n }\n\n if (!deprecatedFields.length) {\n return\n }\n\n const errorMessage = `The following fields of the integration's definition are deprecated: ${deprecatedFields.join(\n ', '\n )}`\n\n if (opts.allowDeprecated) {\n this.logger.warn(errorMessage)\n } else {\n throw new errors.BotpressCLIError(errorMessage)\n }\n }\n\n private async _deployBot(\n api: apiUtils.ApiClient,\n botDefinition: sdk.BotDefinition,\n argvBotId: string | undefined,\n argvCreateNew: boolean | undefined\n ) {\n if (this.argv.dryRun) {\n this.logger.warn('Dry-run mode is not supported for bot deployments. Skipping deployment...')\n return\n }\n\n const outfile = this.projectPaths.abs.outFileCJS\n const code = await fs.promises.readFile(outfile, 'utf-8')\n\n let bot: client.Bot\n if (argvBotId && argvCreateNew) {\n throw new errors.BotpressCLIError('Cannot specify both --botId and --createNew')\n } else if (argvCreateNew) {\n const confirm = await this.prompt.confirm('Are you sure you want to create a new bot ?')\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n\n bot = await this._createNewBot(api)\n } else {\n bot = await this._getExistingBot(api, argvBotId)\n\n const confirm = await this.prompt.confirm(`Are you sure you want to deploy the bot \"${bot.name}\"?`)\n if (!confirm) {\n this.logger.log('Aborted')\n return\n }\n }\n\n const line = this.logger.line()\n line.started(`Deploying bot ${chalk.bold(bot.name)}...`)\n\n const updateBotBody = apiUtils.prepareUpdateBotBody(\n {\n ...(await apiUtils.prepareCreateBotBody(botDefinition)),\n ...(await this.prepareBotDependencies(botDefinition, api)),\n id: bot.id,\n code,\n },\n bot\n )\n\n const { bot: updatedBot } = await api.client.updateBot(updateBotBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update bot \"${bot.name}\"`)\n })\n\n this.validateIntegrationRegistration(updatedBot, (failedIntegrations) =>\n this.logger.warn(\n `Some integrations failed to register:\\n${Object.entries(failedIntegrations)\n .map(([key, int]) => `\u2022 ${key}: ${int.statusReason}`)\n .join('\\n')}`\n )\n )\n\n const tablesPublisher = new tables.TablesPublisher({ api, logger: this.logger, prompt: this.prompt })\n await tablesPublisher.deployTables({ botId: updatedBot.id, botDefinition })\n\n line.success('Bot deployed')\n await this.displayIntegrationUrls({ api, bot: updatedBot })\n }\n\n private async _createNewBot(api: apiUtils.ApiClient): Promise<client.Bot> {\n const line = this.logger.line()\n const { bot: createdBot } = await api.client.createBot({}).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not create bot')\n })\n line.success(`Bot created with ID \"${createdBot.id}\" and name \"${createdBot.name}\"`)\n await this.projectCache.set('botId', createdBot.id)\n return createdBot\n }\n\n private async _getExistingBot(api: apiUtils.ApiClient, botId: string | undefined): Promise<client.Bot> {\n const promptedBotId = await this.projectCache.sync('botId', botId, async (defaultId) => {\n const userBots = await api\n .listAllPages(api.client.listBots, (r) => r.bots)\n .catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not fetch existing bots')\n })\n\n if (!userBots.length) {\n throw new errors.NoBotsFoundError()\n }\n\n const initial = userBots.find((bot) => bot.id === defaultId)\n\n const prompted = await this.prompt.select('Which bot do you want to deploy?', {\n initial: initial && { title: initial.name, value: initial.id },\n choices: userBots.map((bot) => ({ title: bot.name, value: bot.id })),\n })\n\n if (!prompted) {\n throw new errors.ParamRequiredError('Bot Id')\n }\n\n return prompted\n })\n\n const { bot: fetchedBot } = await api.client.getBot({ id: promptedBotId }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not get bot info')\n })\n\n return fetchedBot\n }\n\n private async _manageWorkspaceHandle(\n api: apiUtils.ApiClient,\n integration: sdk.IntegrationDefinition\n ): Promise<\n | {\n integration: sdk.IntegrationDefinition\n workspaceId?: string // Set if user opted to deploy on another available workspace\n }\n | undefined\n > {\n const { name: localName, workspaceHandle: localHandle } = this._parseIntegrationName(integration.name)\n if (!localHandle && api.isBotpressWorkspace) {\n this.logger.debug('Botpress workspace detected; workspace handle omitted')\n return { integration } // botpress has the right to omit workspace handle\n }\n\n const { handle: remoteHandle, name: workspaceName } = await api.getWorkspace().catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not fetch workspace')\n })\n\n if (localHandle && remoteHandle) {\n let workspaceId: string | undefined = undefined\n if (localHandle !== remoteHandle) {\n const remoteWorkspace = await api.findWorkspaceByHandle(localHandle).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not list workspaces')\n })\n if (!remoteWorkspace) {\n throw new errors.BotpressCLIError(\n `The integration handle \"${localHandle}\" is not associated with any of your workspaces.`\n )\n }\n this.logger.warn(\n `Your are logged in to workspace \"${workspaceName}\" but integration handle \"${localHandle}\" belongs to \"${remoteWorkspace.name}\".`\n )\n const confirmUseAlternateWorkspace = await this.prompt.confirm(\n 'Do you want to deploy integration on this workspace instead?'\n )\n if (!confirmUseAlternateWorkspace) {\n throw new errors.BotpressCLIError(\n `Cannot deploy integration with handle \"${localHandle}\" on workspace \"${workspaceName}\"`\n )\n }\n\n workspaceId = remoteWorkspace.id\n }\n return { integration, workspaceId }\n }\n\n const workspaceHandleIsMandatoryMsg = 'Cannot deploy integration without workspace handle'\n\n if (!localHandle && remoteHandle) {\n const confirmAddHandle = await this.prompt.confirm(\n `Your current workspace handle is \"${remoteHandle}\". Do you want to use the name \"${remoteHandle}/${localName}\"?`\n )\n if (!confirmAddHandle) {\n this.logger.log('Aborted')\n return\n }\n const newName = `${remoteHandle}/${localName}`\n return { integration: new sdk.IntegrationDefinition({ ...integration, name: newName }) }\n }\n\n if (localHandle && !remoteHandle) {\n const { available } = await api.client.checkHandleAvailability({ handle: localHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not check handle availability')\n })\n\n if (!available) {\n throw new errors.BotpressCLIError(`Handle \"${localHandle}\" is not yours and is not available`)\n }\n\n const confirmClaimHandle = await this.prompt.confirm(\n `Handle \"${localHandle}\" is available. Do you want to claim it for your workspace ${workspaceName}?`\n )\n if (!confirmClaimHandle) {\n throw new errors.BotpressCLIError(workspaceHandleIsMandatoryMsg)\n }\n\n await api.updateWorkspace({ handle: localHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not claim handle \"${localHandle}\"`)\n })\n\n this.logger.success(`Handle \"${localHandle}\" is now yours!`)\n return { integration }\n }\n\n this.logger.warn(\"It seems you don't have a workspace handle yet.\")\n let claimedHandle: string | undefined = undefined\n do {\n const prompted = await this.prompt.text('Please enter a workspace handle')\n if (!prompted) {\n throw new errors.BotpressCLIError(workspaceHandleIsMandatoryMsg)\n }\n\n const { available, suggestions } = await api.client.checkHandleAvailability({ handle: prompted })\n if (!available) {\n this.logger.warn(`Handle \"${prompted}\" is not available. Suggestions: ${suggestions.join(', ')}`)\n continue\n }\n\n claimedHandle = prompted\n await api.updateWorkspace({ handle: claimedHandle }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not claim handle \"${claimedHandle}\"`)\n })\n } while (!claimedHandle)\n\n this.logger.success(`Handle \"${claimedHandle}\" is yours!`)\n const newName = `${claimedHandle}/${localName}`\n return { integration: new sdk.IntegrationDefinition({ ...integration, name: newName }) }\n }\n\n private _parseIntegrationName = (integrationName: string): { name: string; workspaceHandle?: string } => {\n const parts = integrationName.split('/')\n if (parts.length > 2) {\n throw new errors.BotpressCLIError(\n `Invalid integration name \"${integrationName}\": a single forward slash is allowed`\n )\n }\n if (parts.length === 2) {\n const [workspaceHandle, name] = parts as [string, string]\n return { name, workspaceHandle }\n }\n const [name] = parts as [string]\n return { name }\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,UAAqB;AACrB,mBAAkB;AAClB,SAAoB;AACpB,oBAAmB;AACnB,eAA0B;AAE1B,aAAwB;AACxB,aAAwB;AACxB,YAAuB;AACvB,2BAA6B;AAC7B,6BAA+B;AAGxB,MAAM,sBAAsB,sCAAwC;AAAA,EACzE,MAAa,MAAqB;AAChC,UAAM,MAAM,MAAM,KAAK,2BAA2B,KAAK,IAAI;AAE3D,QAAI,CAAC,KAAK,KAAK,SAAS;AACtB,YAAM,KAAK,UAAU;AAAA,IACvB;AAEA,UAAM,EAAE,aAAa,yBAAyB,IAAI,KAAK,4BAA4B;AAEnF,QAAI,gBAAgB,eAAe;AACjC,YAAM,aAAa,MAAM,yBAAyB;AAClD,aAAO,KAAK,mBAAmB,KAAK,WAAW,UAAU;AAAA,IAC3D;AACA,QAAI,gBAAgB,aAAa;AAC/B,YAAM,aAAa,MAAM,yBAAyB;AAClD,aAAO,KAAK,iBAAiB,KAAK,WAAW,UAAU;AAAA,IACzD;AACA,QAAI,gBAAgB,UAAU;AAC5B,YAAM,aAAa,MAAM,yBAAyB;AAClD,aAAO,KAAK,cAAc,KAAK,WAAW,UAAU;AAAA,IACtD;AACA,QAAI,gBAAgB,OAAO;AACzB,YAAM,aAAa,MAAM,yB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zF;AAAA,EAEQ,wBAAwB,CAAC,oBAAwE;AACvG,UAAM,QAAQ,gBAAgB,MAAM,GAAG;AACvC,QAAI,MAAM,SAAS,GAAG;AACpB,YAAM,IAAI,OAAO;AAAA,QACf,6BAA6B,eAAe;AAAA,MAC9C;AAAA,IACF;AACA,QAAI,MAAM,WAAW,GAAG;AACtB,YAAM,CAAC,iBAAiBC,KAAI,IAAI;AAChC,aAAO,EAAE,MAAAA,OAAM,gBAAgB;AAAA,IACjC;AACA,UAAM,CAAC,IAAI,IAAI;AACf,WAAO,EAAE,KAAK;AAAA,EAChB;AACF;",
6
6
  "names": ["chalk", "semver", "newName", "name"]
7
7
  }
@@ -329,7 +329,7 @@ ${Object.entries(failedIntegrations).map(([key, int]) => `\u2022 ${key}: ${int.s
329
329
  updateLine.commit();
330
330
  const tablesPublisher = new tables.TablesPublisher({ api, logger: this.logger, prompt: this.prompt });
331
331
  await tablesPublisher.deployTables({ botId: updatedBot.id, botDefinition: botDef });
332
- this.displayWebhookUrls(updatedBot);
332
+ await this.displayIntegrationUrls({ api, bot: updatedBot });
333
333
  }
334
334
  async _didDefinitionChange(body) {
335
335
  const didChange = !(0, import_lodash.isEqual)(body, this._cacheDevRequestBody);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/command-implementations/dev-command.ts"],
4
- "sourcesContent": ["import type * as client from '@botpress/client'\nimport type * as sdk from '@botpress/sdk'\nimport { TunnelRequest, TunnelResponse } from '@bpinternal/tunnel'\nimport axios, { AxiosRequestConfig, AxiosResponse } from 'axios'\nimport chalk from 'chalk'\nimport { isEqual } from 'lodash'\nimport * as pathlib from 'path'\nimport * as uuid from 'uuid'\nimport * as apiUtils from '../api'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as tables from '../tables'\nimport * as utils from '../utils'\nimport { Worker } from '../worker'\nimport { BuildCommand } from './build-command'\nimport { ProjectCommand, ProjectDefinition } from './project-command'\n\nconst DEFAULT_BOT_PORT = 8075\nconst DEFAULT_INTEGRATION_PORT = 8076\nconst TUNNEL_HELLO_INTERVAL = 5000\nconst FILEWATCHER_DEBOUNCE_MS = 500\n\nexport type DevCommandDefinition = typeof commandDefinitions.dev\nexport class DevCommand extends ProjectCommand<DevCommandDefinition> {\n private _initialDef: ProjectDefinition | undefined = undefined\n private _cacheDevRequestBody: apiUtils.UpdateBotRequestBody | apiUtils.UpdateIntegrationRequestBody | undefined\n private _buildContext: utils.esbuild.BuildCodeContext\n\n public constructor(...args: ConstructorParameters<typeof ProjectCommand<DevCommandDefinition>>) {\n super(...args)\n this._buildContext = new utils.esbuild.BuildCodeContext()\n }\n\n public async run(): Promise<void> {\n this.logger.warn('This command is experimental and subject to breaking changes without notice.')\n\n const api = await this.ensureLoginAndCreateClient(this.argv)\n\n const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n if (projectType === 'interface') {\n throw new errors.BotpressCLIError('This feature is not available for interfaces.')\n }\n const projectDef = await resolveProjectDefinition()\n this._initialDef = projectDef\n\n let env: Record<string, string> = {\n ...process.env,\n BP_API_URL: api.url,\n BP_TOKEN: api.token,\n }\n\n let defaultPort = DEFAULT_BOT_PORT\n if (this._initialDef.type === 'integration') {\n defaultPort = DEFAULT_INTEGRATION_PORT\n // TODO: store secrets in local cache to avoid prompting every time\n const secretEnvVariables = await this.promptSecrets(this._initialDef.definition, this.argv, { formatEnv: true })\n const nonNullSecretEnvVariables = utils.records.filterValues(secretEnvVariables, utils.guards.is.notNull)\n env = { ...env, ...nonNullSecretEnvVariables }\n }\n\n const port = this.argv.port ?? defaultPort\n\n const urlParseResult = utils.url.parse(this.argv.tunnelUrl)\n if (urlParseResult.status === 'error') {\n throw new errors.BotpressCLIError(`Invalid tunnel URL: ${urlParseResult.error}`)\n }\n\n const cachedTunnelId = await this.projectCache.get('tunnelId')\n\n let tunnelId: string\n if (this.argv.tunnelId) {\n tunnelId = this.argv.tunnelId\n } else if (cachedTunnelId) {\n tunnelId = cachedTunnelId\n } else {\n tunnelId = uuid.v4()\n }\n\n if (cachedTunnelId !== tunnelId) {\n await this.projectCache.set('tunnelId', tunnelId)\n }\n\n const { url: parsedTunnelUrl } = urlParseResult\n const isSecured = parsedTunnelUrl.protocol === 'https' || parsedTunnelUrl.protocol === 'wss'\n\n const wsTunnelUrl: string = utils.url.format({ ...parsedTunnelUrl, protocol: isSecured ? 'wss' : 'ws' })\n const httpTunnelUrl: string = utils.url.format({\n ...parsedTunnelUrl,\n protocol: isSecured ? 'https' : 'http',\n path: `/${tunnelId}`,\n })\n\n let worker: Worker | undefined = undefined\n\n const supervisor = new utils.tunnel.TunnelSupervisor(wsTunnelUrl, tunnelId, this.logger)\n supervisor.events.on('connected', ({ tunnel }) => {\n // prevents the tunnel from closing due to inactivity\n const timer = setInterval(() => {\n if (tunnel.closed) {\n return handleClose()\n }\n tunnel.hello()\n }, TUNNEL_HELLO_INTERVAL)\n const handleClose = (): void => clearInterval(timer)\n tunnel.events.on('close', handleClose)\n\n tunnel.events.on('request', (req) => {\n if (!worker) {\n this.logger.debug('Worker not ready yet, ignoring request')\n tunnel.send({ requestId: req.id, status: 503, body: 'Worker not ready yet' })\n return\n }\n\n void this._forwardTunnelRequest(`http://localhost:${port}`, req)\n .then((res) => {\n tunnel.send(res)\n })\n .catch((thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, 'An error occurred while handling request')\n this.logger.error(err.message)\n tunnel.send({\n requestId: req.id,\n status: 500,\n body: err.message,\n })\n })\n })\n })\n\n supervisor.events.on('manuallyClosed', () => {\n this.logger.debug('Tunnel manually closed')\n })\n\n await supervisor.start()\n\n await this._runBuild()\n await this._deploy(api, httpTunnelUrl)\n worker = await this._spawnWorker(env, port)\n\n try {\n const watcher = await utils.filewatcher.FileWatcher.watch(\n this.argv.workDir,\n async (events) => {\n if (!worker) {\n this.logger.debug('Worker not ready yet, ignoring file change event')\n return\n }\n\n const typescriptEvents = events\n .filter((e) => !e.path.startsWith(this.projectPaths.abs.outDir))\n .filter((e) => pathlib.extname(e.path) === '.ts')\n\n const distEvents = events.filter((e) => e.path.startsWith(this.projectPaths.abs.distDir))\n\n if (typescriptEvents.length > 0) {\n this.logger.log('Changes detected, rebuilding')\n await this._restart(api, worker, httpTunnelUrl)\n } else if (distEvents.length > 0) {\n this.logger.log('Changes detected in output directory, reloading worker')\n await worker.reload()\n }\n },\n {\n debounceMs: FILEWATCHER_DEBOUNCE_MS,\n }\n )\n\n await Promise.race([worker.wait(), watcher.wait(), supervisor.wait()])\n\n if (worker.running) {\n await worker.kill()\n }\n await watcher.close()\n supervisor.close()\n } catch (thrown) {\n throw errors.BotpressCLIError.wrap(thrown, 'An error occurred while running the dev server')\n } finally {\n if (worker.running) {\n await worker.kill()\n }\n }\n }\n\n private _restart = async (api: apiUtils.ApiClient, worker: Worker, tunnelUrl: string) => {\n try {\n await this._runBuild()\n } catch (thrown) {\n const error = errors.BotpressCLIError.wrap(thrown, 'Build failed')\n this.logger.error(error.message)\n return\n }\n\n await this._deploy(api, tunnelUrl)\n await worker.reload()\n }\n\n private _deploy = async (api: apiUtils.ApiClient, tunnelUrl: string) => {\n const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n\n if (projectType === 'interface') {\n throw new errors.BotpressCLIError('This feature is not available for interfaces.')\n }\n if (projectType === 'integration') {\n const projectDef = await resolveProjectDefinition()\n this._checkSecrets(projectDef.definition)\n return await this._deployDevIntegration(api, tunnelUrl, projectDef.definition)\n }\n if (projectType === 'bot') {\n const projectDef = await resolveProjectDefinition()\n return await this._deployDevBot(api, tunnelUrl, projectDef.definition)\n }\n throw new errors.UnsupportedProjectType()\n }\n\n private _checkSecrets(integrationDef: sdk.IntegrationDefinition) {\n if (this._initialDef?.type !== 'integration') {\n return\n }\n const initialSecrets = this._initialDef?.definition.secrets ?? {}\n const currentSecrets = integrationDef.secrets ?? {}\n const newSecrets = Object.keys(currentSecrets).filter((s) => !initialSecrets[s])\n if (newSecrets.length > 0) {\n throw new errors.BotpressCLIError('Secrets were added while the server was running. A restart is required.')\n }\n }\n\n private _spawnWorker = async (env: Record<string, string>, port: number) => {\n const outfile = this.projectPaths.abs.outFileCJS\n const importPath = utils.path.toUnix(outfile)\n const code = `require('${importPath}').default.start(${port})`\n const worker = await Worker.spawn(\n {\n type: 'code',\n code,\n env,\n },\n this.logger\n ).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not start dev worker')\n })\n\n return worker\n }\n\n private _runBuild() {\n return new BuildCommand(this.api, this.prompt, this.logger, this.argv)\n .setProjectContext(this.projectContext)\n .run(this._buildContext)\n }\n\n private async _deployDevIntegration(\n api: apiUtils.ApiClient,\n externalUrl: string,\n integrationDef: sdk.IntegrationDefinition\n ): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let integration: client.Integration | undefined = undefined\n\n if (devId) {\n const resp = await api.client.getIntegration({ id: devId }).catch(async (thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, `Could not find existing dev integration with id \"${devId}\"`)\n this.logger.warn(err.message)\n return { integration: undefined }\n })\n\n if (resp.integration?.dev) {\n integration = resp.integration\n } else {\n await this.projectCache.rm('devId')\n }\n }\n\n const line = this.logger.line()\n line.started(`Deploying dev integration ${chalk.bold(integrationDef.name)}...`)\n\n const createIntegrationBody = {\n ...(await this.prepareCreateIntegrationBody(integrationDef)),\n ...(await this.prepareIntegrationDependencies(integrationDef, api)),\n url: externalUrl,\n }\n\n if (integration) {\n const updateIntegrationBody = apiUtils.prepareUpdateIntegrationBody(\n { ...createIntegrationBody, id: integration.id },\n integration\n )\n\n const resp = await api.client.updateIntegration(updateIntegrationBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update dev integration \"${integrationDef.name}\"`)\n })\n integration = resp.integration\n } else {\n const resp = await api.client.createIntegration({ ...createIntegrationBody, dev: true }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not deploy dev integration \"${integrationDef.name}\"`)\n })\n integration = resp.integration\n }\n\n line.success(`Dev Integration deployed with id \"${integration.id}\" at \"${externalUrl}\"`)\n line.commit()\n\n await this.projectCache.set('devId', integration.id)\n }\n\n private async _deployDevBot(api: apiUtils.ApiClient, externalUrl: string, botDef: sdk.BotDefinition): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let bot: client.Bot | undefined = undefined\n\n if (devId) {\n const resp = await api.client.getBot({ id: devId }).catch(async (thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, `Could not find existing dev bot with id \"${devId}\"`)\n this.logger.warn(err.message)\n return { bot: undefined }\n })\n\n if (resp.bot?.dev) {\n bot = resp.bot\n } else {\n await this.projectCache.rm('devId')\n }\n }\n\n if (!bot) {\n const createLine = this.logger.line()\n createLine.started('Creating dev bot...')\n const resp = await api.client\n .createBot({\n dev: true,\n url: externalUrl,\n })\n .catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not deploy dev bot')\n })\n\n bot = resp.bot\n createLine.log('Dev Bot created')\n createLine.commit()\n await this.projectCache.set('devId', bot.id)\n }\n\n const updateBotBody = apiUtils.prepareUpdateBotBody(\n {\n ...(await apiUtils.prepareCreateBotBody(botDef)),\n ...(await this.prepareBotDependencies(botDef, api)),\n id: bot.id,\n url: externalUrl,\n },\n bot\n )\n\n if (!(await this._didDefinitionChange(updateBotBody))) {\n this.logger.log('Skipping deployment step. No changes found in bot.definition.ts')\n return\n }\n const updateLine = this.logger.line()\n updateLine.started('Deploying dev bot...')\n\n const { bot: updatedBot } = await api.client.updateBot(updateBotBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not deploy dev bot')\n })\n\n this.validateIntegrationRegistration(updatedBot, (failedIntegrations) => {\n throw new errors.BotpressCLIError(\n `Some integrations failed to register:\\n${Object.entries(failedIntegrations)\n .map(([key, int]) => `\u2022 ${key}: ${int.statusReason}`)\n .join('\\n')}`\n )\n })\n\n updateLine.success(`Dev Bot deployed with id \"${updatedBot.id}\" at \"${externalUrl}\"`)\n updateLine.commit()\n\n const tablesPublisher = new tables.TablesPublisher({ api, logger: this.logger, prompt: this.prompt })\n await tablesPublisher.deployTables({ botId: updatedBot.id, botDefinition: botDef })\n\n this.displayWebhookUrls(updatedBot)\n }\n\n private async _didDefinitionChange(body: apiUtils.UpdateBotRequestBody | apiUtils.UpdateIntegrationRequestBody) {\n const didChange = !isEqual(body, this._cacheDevRequestBody)\n this._cacheDevRequestBody = { ...body }\n return didChange\n }\n\n private _forwardTunnelRequest = async (baseUrl: string, request: TunnelRequest): Promise<TunnelResponse> => {\n const axiosConfig = {\n method: request.method,\n url: this._formatLocalUrl(baseUrl, request),\n headers: request.headers,\n data: request.body,\n responseType: 'text',\n validateStatus: () => true,\n } satisfies AxiosRequestConfig\n\n this.logger.debug(`Forwarding request to ${axiosConfig.url}`)\n const response = await axios(axiosConfig)\n this.logger.debug('Sending back response up the tunnel')\n\n return {\n requestId: request.id,\n status: response.status,\n headers: this._getHeaders(response.headers),\n body: response.data,\n }\n }\n\n private _formatLocalUrl = (baseUrl: string, req: TunnelRequest): string => {\n if (req.query) {\n return `${baseUrl}${req.path}?${req.query}`\n }\n return `${baseUrl}${req.path}`\n }\n\n private _getHeaders = (res: AxiosResponse['headers']): TunnelResponse['headers'] => {\n const headers: TunnelResponse['headers'] = {}\n for (const key in res) {\n if (typeof res[key] === 'string' || typeof res[key] === 'number') {\n headers[key] = String(res[key])\n }\n }\n return headers\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAyD;AACzD,mBAAkB;AAClB,oBAAwB;AACxB,cAAyB;AACzB,WAAsB;AACtB,eAA0B;AAE1B,aAAwB;AACxB,aAAwB;AACxB,YAAuB;AACvB,oBAAuB;AACvB,2BAA6B;AAC7B,6BAAkD;AAElD,MAAM,mBAAmB;AACzB,MAAM,2BAA2B;AACjC,MAAM,wBAAwB;AAC9B,MAAM,0BAA0B;AAGzB,MAAM,mBAAmB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UAAM,UAAqC,CAAC;AAC5C,eAAW,OAAO,KAAK;AACrB,UAAI,OAAO,IAAI,GAAG,MAAM,YAAY,OAAO,IAAI,GAAG,MAAM,UAAU;AAChE,gBAAQ,GAAG,IAAI,OAAO,IAAI,GAAG,CAAC;AAAA,MAChC;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["import type * as client from '@botpress/client'\nimport type * as sdk from '@botpress/sdk'\nimport { TunnelRequest, TunnelResponse } from '@bpinternal/tunnel'\nimport axios, { AxiosRequestConfig, AxiosResponse } from 'axios'\nimport chalk from 'chalk'\nimport { isEqual } from 'lodash'\nimport * as pathlib from 'path'\nimport * as uuid from 'uuid'\nimport * as apiUtils from '../api'\nimport type commandDefinitions from '../command-definitions'\nimport * as errors from '../errors'\nimport * as tables from '../tables'\nimport * as utils from '../utils'\nimport { Worker } from '../worker'\nimport { BuildCommand } from './build-command'\nimport { ProjectCommand, ProjectDefinition } from './project-command'\n\nconst DEFAULT_BOT_PORT = 8075\nconst DEFAULT_INTEGRATION_PORT = 8076\nconst TUNNEL_HELLO_INTERVAL = 5000\nconst FILEWATCHER_DEBOUNCE_MS = 500\n\nexport type DevCommandDefinition = typeof commandDefinitions.dev\nexport class DevCommand extends ProjectCommand<DevCommandDefinition> {\n private _initialDef: ProjectDefinition | undefined = undefined\n private _cacheDevRequestBody: apiUtils.UpdateBotRequestBody | apiUtils.UpdateIntegrationRequestBody | undefined\n private _buildContext: utils.esbuild.BuildCodeContext\n\n public constructor(...args: ConstructorParameters<typeof ProjectCommand<DevCommandDefinition>>) {\n super(...args)\n this._buildContext = new utils.esbuild.BuildCodeContext()\n }\n\n public async run(): Promise<void> {\n this.logger.warn('This command is experimental and subject to breaking changes without notice.')\n\n const api = await this.ensureLoginAndCreateClient(this.argv)\n\n const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n if (projectType === 'interface') {\n throw new errors.BotpressCLIError('This feature is not available for interfaces.')\n }\n const projectDef = await resolveProjectDefinition()\n this._initialDef = projectDef\n\n let env: Record<string, string> = {\n ...process.env,\n BP_API_URL: api.url,\n BP_TOKEN: api.token,\n }\n\n let defaultPort = DEFAULT_BOT_PORT\n if (this._initialDef.type === 'integration') {\n defaultPort = DEFAULT_INTEGRATION_PORT\n // TODO: store secrets in local cache to avoid prompting every time\n const secretEnvVariables = await this.promptSecrets(this._initialDef.definition, this.argv, { formatEnv: true })\n const nonNullSecretEnvVariables = utils.records.filterValues(secretEnvVariables, utils.guards.is.notNull)\n env = { ...env, ...nonNullSecretEnvVariables }\n }\n\n const port = this.argv.port ?? defaultPort\n\n const urlParseResult = utils.url.parse(this.argv.tunnelUrl)\n if (urlParseResult.status === 'error') {\n throw new errors.BotpressCLIError(`Invalid tunnel URL: ${urlParseResult.error}`)\n }\n\n const cachedTunnelId = await this.projectCache.get('tunnelId')\n\n let tunnelId: string\n if (this.argv.tunnelId) {\n tunnelId = this.argv.tunnelId\n } else if (cachedTunnelId) {\n tunnelId = cachedTunnelId\n } else {\n tunnelId = uuid.v4()\n }\n\n if (cachedTunnelId !== tunnelId) {\n await this.projectCache.set('tunnelId', tunnelId)\n }\n\n const { url: parsedTunnelUrl } = urlParseResult\n const isSecured = parsedTunnelUrl.protocol === 'https' || parsedTunnelUrl.protocol === 'wss'\n\n const wsTunnelUrl: string = utils.url.format({ ...parsedTunnelUrl, protocol: isSecured ? 'wss' : 'ws' })\n const httpTunnelUrl: string = utils.url.format({\n ...parsedTunnelUrl,\n protocol: isSecured ? 'https' : 'http',\n path: `/${tunnelId}`,\n })\n\n let worker: Worker | undefined = undefined\n\n const supervisor = new utils.tunnel.TunnelSupervisor(wsTunnelUrl, tunnelId, this.logger)\n supervisor.events.on('connected', ({ tunnel }) => {\n // prevents the tunnel from closing due to inactivity\n const timer = setInterval(() => {\n if (tunnel.closed) {\n return handleClose()\n }\n tunnel.hello()\n }, TUNNEL_HELLO_INTERVAL)\n const handleClose = (): void => clearInterval(timer)\n tunnel.events.on('close', handleClose)\n\n tunnel.events.on('request', (req) => {\n if (!worker) {\n this.logger.debug('Worker not ready yet, ignoring request')\n tunnel.send({ requestId: req.id, status: 503, body: 'Worker not ready yet' })\n return\n }\n\n void this._forwardTunnelRequest(`http://localhost:${port}`, req)\n .then((res) => {\n tunnel.send(res)\n })\n .catch((thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, 'An error occurred while handling request')\n this.logger.error(err.message)\n tunnel.send({\n requestId: req.id,\n status: 500,\n body: err.message,\n })\n })\n })\n })\n\n supervisor.events.on('manuallyClosed', () => {\n this.logger.debug('Tunnel manually closed')\n })\n\n await supervisor.start()\n\n await this._runBuild()\n await this._deploy(api, httpTunnelUrl)\n worker = await this._spawnWorker(env, port)\n\n try {\n const watcher = await utils.filewatcher.FileWatcher.watch(\n this.argv.workDir,\n async (events) => {\n if (!worker) {\n this.logger.debug('Worker not ready yet, ignoring file change event')\n return\n }\n\n const typescriptEvents = events\n .filter((e) => !e.path.startsWith(this.projectPaths.abs.outDir))\n .filter((e) => pathlib.extname(e.path) === '.ts')\n\n const distEvents = events.filter((e) => e.path.startsWith(this.projectPaths.abs.distDir))\n\n if (typescriptEvents.length > 0) {\n this.logger.log('Changes detected, rebuilding')\n await this._restart(api, worker, httpTunnelUrl)\n } else if (distEvents.length > 0) {\n this.logger.log('Changes detected in output directory, reloading worker')\n await worker.reload()\n }\n },\n {\n debounceMs: FILEWATCHER_DEBOUNCE_MS,\n }\n )\n\n await Promise.race([worker.wait(), watcher.wait(), supervisor.wait()])\n\n if (worker.running) {\n await worker.kill()\n }\n await watcher.close()\n supervisor.close()\n } catch (thrown) {\n throw errors.BotpressCLIError.wrap(thrown, 'An error occurred while running the dev server')\n } finally {\n if (worker.running) {\n await worker.kill()\n }\n }\n }\n\n private _restart = async (api: apiUtils.ApiClient, worker: Worker, tunnelUrl: string) => {\n try {\n await this._runBuild()\n } catch (thrown) {\n const error = errors.BotpressCLIError.wrap(thrown, 'Build failed')\n this.logger.error(error.message)\n return\n }\n\n await this._deploy(api, tunnelUrl)\n await worker.reload()\n }\n\n private _deploy = async (api: apiUtils.ApiClient, tunnelUrl: string) => {\n const { projectType, resolveProjectDefinition } = this.readProjectDefinitionFromFS()\n\n if (projectType === 'interface') {\n throw new errors.BotpressCLIError('This feature is not available for interfaces.')\n }\n if (projectType === 'integration') {\n const projectDef = await resolveProjectDefinition()\n this._checkSecrets(projectDef.definition)\n return await this._deployDevIntegration(api, tunnelUrl, projectDef.definition)\n }\n if (projectType === 'bot') {\n const projectDef = await resolveProjectDefinition()\n return await this._deployDevBot(api, tunnelUrl, projectDef.definition)\n }\n throw new errors.UnsupportedProjectType()\n }\n\n private _checkSecrets(integrationDef: sdk.IntegrationDefinition) {\n if (this._initialDef?.type !== 'integration') {\n return\n }\n const initialSecrets = this._initialDef?.definition.secrets ?? {}\n const currentSecrets = integrationDef.secrets ?? {}\n const newSecrets = Object.keys(currentSecrets).filter((s) => !initialSecrets[s])\n if (newSecrets.length > 0) {\n throw new errors.BotpressCLIError('Secrets were added while the server was running. A restart is required.')\n }\n }\n\n private _spawnWorker = async (env: Record<string, string>, port: number) => {\n const outfile = this.projectPaths.abs.outFileCJS\n const importPath = utils.path.toUnix(outfile)\n const code = `require('${importPath}').default.start(${port})`\n const worker = await Worker.spawn(\n {\n type: 'code',\n code,\n env,\n },\n this.logger\n ).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not start dev worker')\n })\n\n return worker\n }\n\n private _runBuild() {\n return new BuildCommand(this.api, this.prompt, this.logger, this.argv)\n .setProjectContext(this.projectContext)\n .run(this._buildContext)\n }\n\n private async _deployDevIntegration(\n api: apiUtils.ApiClient,\n externalUrl: string,\n integrationDef: sdk.IntegrationDefinition\n ): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let integration: client.Integration | undefined = undefined\n\n if (devId) {\n const resp = await api.client.getIntegration({ id: devId }).catch(async (thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, `Could not find existing dev integration with id \"${devId}\"`)\n this.logger.warn(err.message)\n return { integration: undefined }\n })\n\n if (resp.integration?.dev) {\n integration = resp.integration\n } else {\n await this.projectCache.rm('devId')\n }\n }\n\n const line = this.logger.line()\n line.started(`Deploying dev integration ${chalk.bold(integrationDef.name)}...`)\n\n const createIntegrationBody = {\n ...(await this.prepareCreateIntegrationBody(integrationDef)),\n ...(await this.prepareIntegrationDependencies(integrationDef, api)),\n url: externalUrl,\n }\n\n if (integration) {\n const updateIntegrationBody = apiUtils.prepareUpdateIntegrationBody(\n { ...createIntegrationBody, id: integration.id },\n integration\n )\n\n const resp = await api.client.updateIntegration(updateIntegrationBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not update dev integration \"${integrationDef.name}\"`)\n })\n integration = resp.integration\n } else {\n const resp = await api.client.createIntegration({ ...createIntegrationBody, dev: true }).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not deploy dev integration \"${integrationDef.name}\"`)\n })\n integration = resp.integration\n }\n\n line.success(`Dev Integration deployed with id \"${integration.id}\" at \"${externalUrl}\"`)\n line.commit()\n\n await this.projectCache.set('devId', integration.id)\n }\n\n private async _deployDevBot(api: apiUtils.ApiClient, externalUrl: string, botDef: sdk.BotDefinition): Promise<void> {\n const devId = await this.projectCache.get('devId')\n\n let bot: client.Bot | undefined = undefined\n\n if (devId) {\n const resp = await api.client.getBot({ id: devId }).catch(async (thrown) => {\n const err = errors.BotpressCLIError.wrap(thrown, `Could not find existing dev bot with id \"${devId}\"`)\n this.logger.warn(err.message)\n return { bot: undefined }\n })\n\n if (resp.bot?.dev) {\n bot = resp.bot\n } else {\n await this.projectCache.rm('devId')\n }\n }\n\n if (!bot) {\n const createLine = this.logger.line()\n createLine.started('Creating dev bot...')\n const resp = await api.client\n .createBot({\n dev: true,\n url: externalUrl,\n })\n .catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not deploy dev bot')\n })\n\n bot = resp.bot\n createLine.log('Dev Bot created')\n createLine.commit()\n await this.projectCache.set('devId', bot.id)\n }\n\n const updateBotBody = apiUtils.prepareUpdateBotBody(\n {\n ...(await apiUtils.prepareCreateBotBody(botDef)),\n ...(await this.prepareBotDependencies(botDef, api)),\n id: bot.id,\n url: externalUrl,\n },\n bot\n )\n\n if (!(await this._didDefinitionChange(updateBotBody))) {\n this.logger.log('Skipping deployment step. No changes found in bot.definition.ts')\n return\n }\n const updateLine = this.logger.line()\n updateLine.started('Deploying dev bot...')\n\n const { bot: updatedBot } = await api.client.updateBot(updateBotBody).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, 'Could not deploy dev bot')\n })\n\n this.validateIntegrationRegistration(updatedBot, (failedIntegrations) => {\n throw new errors.BotpressCLIError(\n `Some integrations failed to register:\\n${Object.entries(failedIntegrations)\n .map(([key, int]) => `\u2022 ${key}: ${int.statusReason}`)\n .join('\\n')}`\n )\n })\n\n updateLine.success(`Dev Bot deployed with id \"${updatedBot.id}\" at \"${externalUrl}\"`)\n updateLine.commit()\n\n const tablesPublisher = new tables.TablesPublisher({ api, logger: this.logger, prompt: this.prompt })\n await tablesPublisher.deployTables({ botId: updatedBot.id, botDefinition: botDef })\n\n await this.displayIntegrationUrls({ api, bot: updatedBot })\n }\n\n private async _didDefinitionChange(body: apiUtils.UpdateBotRequestBody | apiUtils.UpdateIntegrationRequestBody) {\n const didChange = !isEqual(body, this._cacheDevRequestBody)\n this._cacheDevRequestBody = { ...body }\n return didChange\n }\n\n private _forwardTunnelRequest = async (baseUrl: string, request: TunnelRequest): Promise<TunnelResponse> => {\n const axiosConfig = {\n method: request.method,\n url: this._formatLocalUrl(baseUrl, request),\n headers: request.headers,\n data: request.body,\n responseType: 'text',\n validateStatus: () => true,\n } satisfies AxiosRequestConfig\n\n this.logger.debug(`Forwarding request to ${axiosConfig.url}`)\n const response = await axios(axiosConfig)\n this.logger.debug('Sending back response up the tunnel')\n\n return {\n requestId: request.id,\n status: response.status,\n headers: this._getHeaders(response.headers),\n body: response.data,\n }\n }\n\n private _formatLocalUrl = (baseUrl: string, req: TunnelRequest): string => {\n if (req.query) {\n return `${baseUrl}${req.path}?${req.query}`\n }\n return `${baseUrl}${req.path}`\n }\n\n private _getHeaders = (res: AxiosResponse['headers']): TunnelResponse['headers'] => {\n const headers: TunnelResponse['headers'] = {}\n for (const key in res) {\n if (typeof res[key] === 'string' || typeof res[key] === 'number') {\n headers[key] = String(res[key])\n }\n }\n return headers\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAyD;AACzD,mBAAkB;AAClB,oBAAwB;AACxB,cAAyB;AACzB,WAAsB;AACtB,eAA0B;AAE1B,aAAwB;AACxB,aAAwB;AACxB,YAAuB;AACvB,oBAAuB;AACvB,2BAA6B;AAC7B,6BAAkD;AAElD,MAAM,mBAAmB;AACzB,MAAM,2BAA2B;AACjC,MAAM,wBAAwB;AAC9B,MAAM,0BAA0B;AAGzB,MAAM,mBAAmB,sCAAqC;AAAA,EAC3D,cAA6C;AAAA,EAC7C;AAAA,EACA;AAAA,EAED,eAAe,MAA0E;AAC9F,UAAM,GAAG,IAAI;AACb,SAAK,gBAAgB,IAAI,MAAM,QAAQ,iBAAiB;AAAA,EAC1D;AAAA,EAEA,MAAa,MAAqB;AAChC,SAAK,OAAO,KAAK,8EAA8E;AAE/F,UAAM,MAAM,MAAM,KAAK,2BAA2B,KAAK,IAAI;AAE3D,UAAM,EAAE,aAAa,yBAAyB,IAAI,KAAK,4BAA4B;AACnF,QAAI,gBAAgB,aAAa;AAC/B,YAAM,IAAI,OAAO,iBAAiB,+CAA+C;AAAA,IACnF;AACA,UAAM,aAAa,MAAM,yBAAyB;AAClD,SAAK,cAAc;AAEnB,QAAI,MAA8B;AAAA,MAChC,GAAG,QAAQ;AAAA,MACX,YAAY,IAAI;AAAA,MAChB,UAAU,IAAI;AAAA,IAChB;AAEA,QAAI,cAAc;AAClB,QAAI,KAAK,YAAY,S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A,MAChB,KAAK,KAAK,gBAAgB,SAAS,OAAO;AAAA,MAC1C,SAAS,QAAQ;AAAA,MACjB,MAAM,QAAQ;AAAA,MACd,cAAc;AAAA,MACd,gBAAgB,MAAM;AAAA,IACxB;AAEA,SAAK,OAAO,MAAM,yBAAyB,YAAY,GAAG,EAAE;AAC5D,UAAM,WAAW,UAAM,aAAAC,SAAM,WAAW;AACxC,SAAK,OAAO,MAAM,qCAAqC;AAEvD,WAAO;AAAA,MACL,WAAW,QAAQ;AAAA,MACnB,QAAQ,SAAS;AAAA,MACjB,SAAS,KAAK,YAAY,SAAS,OAAO;AAAA,MAC1C,MAAM,SAAS;AAAA,IACjB;AAAA,EACF;AAAA,EAEQ,kBAAkB,CAAC,SAAiB,QAA+B;AACzE,QAAI,IAAI,OAAO;AACb,aAAO,GAAG,OAAO,GAAG,IAAI,IAAI,IAAI,IAAI,KAAK;AAAA,IAC3C;AACA,WAAO,GAAG,OAAO,GAAG,IAAI,IAAI;AAAA,EAC9B;AAAA,EAEQ,cAAc,CAAC,QAA6D;AAClF,UAAM,UAAqC,CAAC;AAC5C,eAAW,OAAO,KAAK;AACrB,UAAI,OAAO,IAAI,GAAG,MAAM,YAAY,OAAO,IAAI,GAAG,MAAM,UAAU;AAChE,gBAAQ,GAAG,IAAI,OAAO,IAAI,GAAG,CAAC;AAAA,MAChC;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;",
6
6
  "names": ["chalk", "axios"]
7
7
  }
@@ -84,7 +84,17 @@ export declare abstract class ProjectCommand<C extends ProjectCommandDefinition>
84
84
  private _readBotDefinitionFromFS;
85
85
  private _readPluginDefinitionFromFS;
86
86
  private _isBpLintDisabled;
87
- protected displayWebhookUrls(bot: client.Bot): void;
87
+ protected displayIntegrationUrls({ api, bot }: {
88
+ api: apiUtils.ApiClient;
89
+ bot: client.Bot;
90
+ }): Promise<void>;
91
+ private _getLinkTemplateScript;
92
+ private _displayWebhookUrl;
93
+ private _displayAuthorizationLink;
94
+ private _getLinkTemplateArgs;
95
+ private _getAuthorizationLink;
96
+ private _getSandboxLink;
97
+ private _displaySandboxLinkAndCode;
88
98
  protected promptSecrets(integrationDef: sdk.IntegrationDefinition, argv: YargsConfig<typeof config.schemas.secrets>, opts?: {
89
99
  formatEnv?: boolean;
90
100
  knownSecrets?: string[];
@@ -223,22 +223,143 @@ class ProjectCommand extends import_global_command.GlobalCommand {
223
223
  const regex = /\/\* bplint-disable \*\//;
224
224
  return regex.test(tsContent);
225
225
  }
226
- displayWebhookUrls(bot) {
226
+ async displayIntegrationUrls({ api, bot }) {
227
227
  if (!import_lodash.default.keys(bot.integrations).length) {
228
228
  this.logger.debug("No integrations in bot");
229
229
  return;
230
230
  }
231
+ const integrationDefinitions = await utils.records.mapValuesAsync(
232
+ bot.integrations,
233
+ async (integration) => api.getPublicOrPrivateIntegration({
234
+ type: "id",
235
+ id: integration.id
236
+ })
237
+ );
231
238
  this.logger.log("Integrations:");
232
- for (const integration of Object.values(bot.integrations).filter(utils.guards.is.defined)) {
233
- if (!integration.enabled) {
234
- this.logger.log(`${import_chalk.default.grey(integration.name)} ${import_chalk.default.italic("(disabled)")}: ${integration.webhookUrl}`, {
235
- prefix: { symbol: "\u25CB", indent: 2 }
236
- });
239
+ for (const [alias, integration] of Object.entries(bot.integrations)) {
240
+ if (integration.enabled) {
241
+ this.logger.log(`${alias}:`, { prefix: { symbol: "\u2192", indent: 2 } });
237
242
  } else {
238
- this.logger.log(`${import_chalk.default.bold(integration.name)} : ${integration.webhookUrl}`, {
239
- prefix: { symbol: "\u25CF", indent: 2 }
243
+ this.logger.log(`${alias} ${import_chalk.default.italic("(disabled)")}:`, {
244
+ prefix: { symbol: "\u2192", indent: 2 }
240
245
  });
241
246
  }
247
+ const integrationDefinition = integrationDefinitions[alias];
248
+ const linkTemplateScript = integrationDefinition ? this._getLinkTemplateScript({ integration, integrationDefinition }) : void 0;
249
+ this._displayWebhookUrl({ integration, integrationDefinition, linkTemplateScript });
250
+ if (!integrationDefinition) {
251
+ this.logger.debug(
252
+ `No integration definition for integration ${alias} (${integration.name}, ${integration.id}), skipping OAuth or Sandbox links`
253
+ );
254
+ this.logger.line().commit();
255
+ continue;
256
+ }
257
+ const isSandbox = integration.configurationType === "sandbox" && !!integrationDefinition.sandbox?.identifierExtractScript;
258
+ const showLink = !!linkTemplateScript && (isSandbox || !!integrationDefinition.identifier?.extractScript);
259
+ if (showLink && isSandbox) {
260
+ await this._displaySandboxLinkAndCode({ integration, alias, bot, api, linkTemplateScript });
261
+ } else if (showLink) {
262
+ this._displayAuthorizationLink({ integration, api, linkTemplateScript });
263
+ }
264
+ this.logger.line().commit();
265
+ }
266
+ }
267
+ _getLinkTemplateScript({
268
+ integration,
269
+ integrationDefinition
270
+ }) {
271
+ const config2 = integration.configurationType === null ? integrationDefinition?.configuration : integrationDefinition?.configurations[integration.configurationType];
272
+ return config2?.identifier?.linkTemplateScript;
273
+ }
274
+ _displayWebhookUrl({
275
+ integration,
276
+ integrationDefinition,
277
+ linkTemplateScript
278
+ }) {
279
+ const needsWebhook = !(integrationDefinition?.identifier && linkTemplateScript);
280
+ const logFn = (needsWebhook ? this.logger.log : this.logger.debug).bind(this.logger);
281
+ if (integration.enabled) {
282
+ logFn(`${import_chalk.default.bold("Webhook")}: ${integration.webhookUrl}`, {
283
+ prefix: { symbol: "\u25CF", indent: 4 }
284
+ });
285
+ } else {
286
+ logFn(`Webhook: ${integration.webhookUrl}`, {
287
+ prefix: { symbol: "\u25CB", indent: 4 }
288
+ });
289
+ }
290
+ }
291
+ _displayAuthorizationLink({
292
+ integration,
293
+ api,
294
+ linkTemplateScript
295
+ }) {
296
+ const authorizationLink = this._getAuthorizationLink({ integration, api, linkTemplateScript });
297
+ const isAuthorized = !!integration.identifier;
298
+ const authorizationStatus = integration.identifier ? "Authorized \u2713" : "Authorize";
299
+ if (integration.enabled && isAuthorized) {
300
+ this.logger.log(`${import_chalk.default.bold(authorizationStatus)} : ${authorizationLink}`, {
301
+ prefix: { symbol: "\u25CF", indent: 4 }
302
+ });
303
+ } else {
304
+ this.logger.log(`${authorizationStatus}: ${authorizationLink}`, {
305
+ prefix: { symbol: "\u25CB", indent: 4 }
306
+ });
307
+ }
308
+ }
309
+ _getLinkTemplateArgs({ integration, api }) {
310
+ let env;
311
+ if (api.url.includes(consts.stagingBotpressDomain)) {
312
+ env = "preview";
313
+ } else if (api.url.includes(consts.productionBotpressDomain)) {
314
+ env = "production";
315
+ } else {
316
+ env = "development";
317
+ }
318
+ return {
319
+ env,
320
+ webhookId: integration.webhookId,
321
+ webhookUrl: api.url.replace("api", "webhook")
322
+ };
323
+ }
324
+ _getAuthorizationLink({
325
+ integration,
326
+ api,
327
+ linkTemplateScript
328
+ }) {
329
+ return utils.vrl.getStringResult({
330
+ code: linkTemplateScript,
331
+ data: this._getLinkTemplateArgs({ integration, api })
332
+ });
333
+ }
334
+ _getSandboxLink({
335
+ shareableId,
336
+ integration,
337
+ api,
338
+ linkTemplateScript
339
+ }) {
340
+ return utils.vrl.getStringResult({
341
+ code: linkTemplateScript,
342
+ data: { shareableId, ...this._getLinkTemplateArgs({ integration, api }) }
343
+ });
344
+ }
345
+ async _displaySandboxLinkAndCode({
346
+ integration,
347
+ alias,
348
+ bot,
349
+ api,
350
+ linkTemplateScript
351
+ }) {
352
+ const shareableId = await api.getOrGenerateShareableId(bot.id, integration.id, alias);
353
+ const sandboxLink = this._getSandboxLink({ shareableId, integration, api, linkTemplateScript });
354
+ const sandboxInstruction = `Send '${shareableId}' to ${sandboxLink}`;
355
+ if (integration.enabled) {
356
+ this.logger.log(`${import_chalk.default.bold("Sandbox")}: ${sandboxInstruction}`, {
357
+ prefix: { symbol: "\u25CF", indent: 4 }
358
+ });
359
+ } else {
360
+ this.logger.log(`Sandbox: ${sandboxInstruction}`, {
361
+ prefix: { symbol: "\u25CB", indent: 4 }
362
+ });
242
363
  }
243
364
  }
244
365
  async promptSecrets(integrationDef, argv, opts = {}) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/command-implementations/project-command.ts"],
4
- "sourcesContent": ["import type * as client from '@botpress/client'\nimport type * as sdk from '@botpress/sdk'\nimport type { YargsConfig } from '@bpinternal/yargs-extra'\nimport chalk from 'chalk'\nimport fs from 'fs'\nimport _ from 'lodash'\nimport semver from 'semver'\nimport * as apiUtils from '../api'\nimport * as codegen from '../code-generation'\nimport * as config from '../config'\nimport * as consts from '../consts'\nimport * as errors from '../errors'\nimport { validateIntegrationDefinition, validateBotDefinition } from '../sdk'\nimport type { CommandArgv, CommandDefinition } from '../typings'\nimport * as utils from '../utils'\nimport { GlobalCommand } from './global-command'\n\nexport type ProjectCommandDefinition = CommandDefinition<typeof config.schemas.project>\nexport type ProjectCache = { botId: string; devId: string; tunnelId: string }\n\ntype ConfigurableProjectPaths = { workDir: string }\ntype ConstantProjectPaths = typeof consts.fromWorkDir\ntype AllProjectPaths = ConfigurableProjectPaths & ConstantProjectPaths\n\ntype LintIgnoredConfig = { bpLintDisabled?: boolean }\n\nexport type ProjectType = ProjectDefinition['type']\nexport type ProjectDefinition = LintIgnoredConfig &\n (\n | { type: 'integration'; definition: sdk.IntegrationDefinition }\n | { type: 'interface'; definition: sdk.InterfaceDefinition }\n | { type: 'bot'; definition: sdk.BotDefinition }\n | { type: 'plugin'; definition: sdk.PluginDefinition }\n )\n\ntype ProjectDefinitionResolver<T> = () => Promise<LintIgnoredConfig & T>\n\nexport type ProjectDefinitionLazy =\n | {\n projectType: 'integration'\n resolveProjectDefinition: ProjectDefinitionResolver<{\n type: 'integration'\n definition: sdk.IntegrationDefinition\n }>\n }\n | {\n projectType: 'bot'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'bot'; definition: sdk.BotDefinition }>\n }\n | {\n projectType: 'interface'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'interface'; definition: sdk.InterfaceDefinition }>\n }\n | {\n projectType: 'plugin'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'plugin'; definition: sdk.PluginDefinition }>\n }\n\ntype UpdatedBot = client.Bot\n\nclass ProjectPaths extends utils.path.PathStore<keyof AllProjectPaths> {\n public constructor(argv: CommandArgv<ProjectCommandDefinition>) {\n const absWorkDir = utils.path.absoluteFrom(utils.path.cwd(), argv.workDir)\n super({\n workDir: absWorkDir,\n ..._.mapValues(consts.fromWorkDir, (p) => utils.path.absoluteFrom(absWorkDir, p)),\n })\n }\n}\n\nexport class ProjectDefinitionContext {\n private _codeCache: Map<string, object> = new Map()\n private _buildContext: utils.esbuild.BuildEntrypointContext = new utils.esbuild.BuildEntrypointContext()\n\n public getOrResolveDefinition<T extends object>(code: string): T {\n const definition = this._codeCache.get(code)\n if (definition) {\n return definition as T\n }\n const result = utils.require.requireJsCode<{ default: object }>(code)\n this._codeCache.set(code, result.default)\n return result.default as T\n }\n\n public rebuildEntrypoint(...args: Parameters<utils.esbuild.BuildEntrypointContext['rebuild']>) {\n return this._buildContext.rebuild(...args)\n }\n}\n\nexport abstract class ProjectCommand<C extends ProjectCommandDefinition> extends GlobalCommand<C> {\n protected projectContext: ProjectDefinitionContext = new ProjectDefinitionContext()\n\n public setProjectContext(projectContext: ProjectDefinitionContext) {\n this.projectContext = projectContext\n return this\n }\n\n protected override async bootstrap() {\n await super.bootstrap()\n await this._notifyUpdateSdk()\n }\n\n protected get projectPaths() {\n return new ProjectPaths(this.argv)\n }\n\n protected get projectCache() {\n return new utils.cache.FSKeyValueCache<ProjectCache>(this.projectPaths.abs.projectCacheFile)\n }\n\n private _readProjectType(projectPaths: ProjectPaths): ProjectType {\n const abs = projectPaths.abs\n if (fs.existsSync(abs.integrationDefinition)) {\n return 'integration'\n }\n if (fs.existsSync(abs.interfaceDefinition)) {\n return 'interface'\n }\n if (fs.existsSync(abs.botDefinition)) {\n return 'bot'\n }\n if (fs.existsSync(abs.pluginDefinition)) {\n return 'plugin'\n }\n throw new errors.UnsupportedProjectType()\n }\n\n protected readProjectDefinitionFromFS(): ProjectDefinitionLazy {\n try {\n const type = this._readProjectType(this.projectPaths)\n if (type === 'integration') {\n return {\n projectType: 'integration',\n resolveProjectDefinition: async () => ({\n type: 'integration',\n ...(await this._readIntegrationDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'plugin') {\n return {\n projectType: 'plugin',\n resolveProjectDefinition: async () => ({\n type: 'plugin',\n ...(await this._readPluginDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'interface') {\n return {\n projectType: 'interface',\n resolveProjectDefinition: async () => ({\n type: 'interface',\n ...(await this._readInterfaceDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'bot') {\n return {\n projectType: 'bot',\n resolveProjectDefinition: async () => ({\n type: 'bot',\n ...(await this._readBotDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n } catch (thrown: unknown) {\n throw errors.BotpressCLIError.wrap(thrown, 'Error while reading project definition')\n }\n throw new errors.ProjectDefinitionNotFoundError(this.projectPaths.abs.workDir)\n }\n\n private async _readIntegrationDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'integrationDefinition'>\n ): Promise<{ definition: sdk.IntegrationDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.integrationDefinition)) {\n throw new errors.BotpressCLIError('Could not read integration definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.integrationDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.integrationDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read integration definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.IntegrationDefinition>(artifact.text)\n validateIntegrationDefinition(definition)\n return { definition, bpLintDisabled }\n }\n\n private async _readInterfaceDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'interfaceDefinition'>\n ): Promise<{ definition: sdk.InterfaceDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.interfaceDefinition)) {\n throw new errors.BotpressCLIError('Could not read interface definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.interfaceDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.interfaceDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read interface definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.InterfaceDefinition>(artifact.text)\n\n return { definition, bpLintDisabled }\n }\n\n private async _readBotDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'botDefinition'>\n ): Promise<{ definition: sdk.BotDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.botDefinition)) {\n throw new errors.BotpressCLIError('Could not read bot definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.botDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.botDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read bot definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.BotDefinition>(artifact.text)\n validateBotDefinition(definition)\n return { definition, bpLintDisabled }\n }\n\n private async _readPluginDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'pluginDefinition'>\n ): Promise<{ definition: sdk.PluginDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.pluginDefinition)) {\n throw new errors.BotpressCLIError('Could not read plugin definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.pluginDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.pluginDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read plugin definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.PluginDefinition>(artifact.text)\n // TODO: validate plugin definition\n return { definition, bpLintDisabled }\n }\n\n private async _isBpLintDisabled(definitionPath: string): Promise<boolean> {\n const tsContent = await fs.promises.readFile(definitionPath, 'utf-8')\n const regex = /\\/\\* bplint-disable \\*\\//\n return regex.test(tsContent)\n }\n\n protected displayWebhookUrls(bot: client.Bot) {\n if (!_.keys(bot.integrations).length) {\n this.logger.debug('No integrations in bot')\n return\n }\n\n this.logger.log('Integrations:')\n for (const integration of Object.values(bot.integrations).filter(utils.guards.is.defined)) {\n if (!integration.enabled) {\n this.logger.log(`${chalk.grey(integration.name)} ${chalk.italic('(disabled)')}: ${integration.webhookUrl}`, {\n prefix: { symbol: '\u25CB', indent: 2 },\n })\n } else {\n this.logger.log(`${chalk.bold(integration.name)} : ${integration.webhookUrl}`, {\n prefix: { symbol: '\u25CF', indent: 2 },\n })\n }\n }\n }\n\n protected async promptSecrets(\n integrationDef: sdk.IntegrationDefinition,\n argv: YargsConfig<typeof config.schemas.secrets>,\n opts: { formatEnv?: boolean; knownSecrets?: string[] } = {}\n ): Promise<Record<string, string | null>> {\n const formatEnv = opts.formatEnv ?? false\n const knownSecrets = opts.knownSecrets ?? []\n\n const { secrets: secretDefinitions } = integrationDef\n if (!secretDefinitions) {\n return {}\n }\n\n const secretArgv = this._parseArgvSecrets(argv.secrets)\n const invalidSecret = Object.keys(secretArgv).find((s) => !secretDefinitions[s])\n if (invalidSecret) {\n throw new errors.BotpressCLIError(`Secret ${invalidSecret} is not defined in integration definition`)\n }\n\n const values: Record<string, string | null> = {}\n for (const [secretName, { optional }] of Object.entries(secretDefinitions)) {\n const argvSecret = secretArgv[secretName]\n if (argvSecret) {\n this.logger.debug(`Using secret \"${secretName}\" from argv`)\n values[secretName] = argvSecret\n continue\n }\n\n const alreadyKnown = knownSecrets.includes(secretName)\n let mode: string\n if (alreadyKnown) {\n mode = 'already set'\n } else if (optional) {\n mode = 'optional'\n } else {\n mode = 'required'\n }\n\n const prompted = await this.prompt.text(`Enter value for secret \"${secretName}\" (${mode})`)\n if (prompted) {\n values[secretName] = prompted\n continue\n }\n\n if (alreadyKnown) {\n this.logger.log(`Secret \"${secretName}\" is unchanged`)\n } else if (optional) {\n this.logger.warn(`Secret \"${secretName}\" is unassigned`)\n } else {\n throw new errors.BotpressCLIError(`Secret \"${secretName}\" is required`)\n }\n }\n\n for (const secretName of knownSecrets) {\n const isDefined = secretName in secretDefinitions\n if (isDefined) {\n continue\n }\n const prompted = await this.prompt.confirm(`Secret \"${secretName}\" was removed. Do you wish to delete it?`)\n if (prompted) {\n this.logger.log(`Deleting secret \"${secretName}\"`, { prefix: { symbol: '\u00D7', fg: 'red' } })\n values[secretName] = null\n }\n }\n\n if (!formatEnv) {\n return values\n }\n\n const envVariables = _.mapKeys(values, (_v, k) => codegen.secretEnvVariableName(k))\n return envVariables\n }\n\n protected async prepareCreateIntegrationBody(\n integrationDef: sdk.IntegrationDefinition\n ): Promise<apiUtils.CreateIntegrationRequestBody> {\n const partialBody = await apiUtils.prepareCreateIntegrationBody(integrationDef)\n\n let code: string | undefined = undefined\n if (fs.existsSync(this.projectPaths.abs.outFileCJS)) {\n code = await this.readProjectFile(this.projectPaths.abs.outFileCJS)\n }\n\n const icon = await this.readProjectFile(integrationDef.icon, 'base64')\n const readme = await this.readProjectFile(integrationDef.readme, 'base64')\n const extractScript = await this.readProjectFile(integrationDef.identifier?.extractScript)\n const fallbackHandlerScript = await this.readProjectFile(integrationDef.identifier?.fallbackHandlerScript)\n return {\n ...partialBody,\n code,\n icon,\n readme,\n identifier: {\n extractScript,\n fallbackHandlerScript,\n },\n configuration: integrationDef.configuration\n ? {\n schema: await utils.schema.mapZodToJsonSchema(integrationDef.configuration, {\n useLegacyZuiTransformer: integrationDef.__advanced?.useLegacyZuiTransformer,\n }),\n identifier: {\n required: integrationDef.configuration.identifier?.required,\n linkTemplateScript: await this.readProjectFile(\n integrationDef.configuration.identifier?.linkTemplateScript\n ),\n },\n }\n : undefined,\n configurations: integrationDef.configurations\n ? await utils.records.mapValuesAsync(integrationDef.configurations, async (configuration) => ({\n title: configuration.title,\n description: configuration.description,\n schema: await utils.schema.mapZodToJsonSchema(configuration, {\n useLegacyZuiTransformer: integrationDef.__advanced?.useLegacyZuiTransformer,\n }),\n identifier: {\n required: configuration.identifier?.required,\n linkTemplateScript: await this.readProjectFile(configuration.identifier?.linkTemplateScript),\n },\n }))\n : undefined,\n }\n }\n\n protected async prepareBotDependencies(\n botDef: sdk.BotDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.UpdateBotRequestBody>> {\n const integrations = await this._fetchDependencies(botDef.integrations ?? {}, ({ name, version }) =>\n api.getPublicOrPrivateIntegration({ type: 'name', name, version })\n )\n\n const plugins = await this._fetchDependencies(\n botDef.plugins ?? {},\n async ({ name, version }) => await api.getPublicOrPrivatePlugin({ type: 'name', name, version })\n )\n\n const pluginsWithBackingIntegrations = await utils.records.mapValuesAsync(plugins, async (plugin) => ({\n ...plugin,\n interfaces: await this._fetchDependencies(\n plugin.interfaces ?? {},\n async (interfaceExtension) => await api.getPublicOrPrivateIntegration({ ...interfaceExtension, type: 'name' })\n ),\n }))\n\n return {\n integrations: utils.records.mapValues(\n integrations,\n ({ enabled, configurationType, configuration, disabledChannels, id }) =>\n ({\n enabled,\n configurationType,\n configuration,\n disabledChannels,\n integrationId: id,\n }) satisfies NonNullable<apiUtils.UpdateBotRequestBody['integrations']>[string]\n ),\n plugins: utils.records.mapValues(pluginsWithBackingIntegrations, (plugin) => ({\n ...plugin,\n interfaces: utils.records.mapValues(plugin.interfaces ?? {}, (iface) => ({\n ...iface,\n integrationId: iface.id,\n })),\n })),\n }\n }\n\n protected async prepareIntegrationDependencies(\n integrationDef: sdk.IntegrationDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.CreateIntegrationRequestBody>> {\n const interfaces = await this._fetchDependencies(integrationDef.interfaces ?? {}, ({ name, version }) =>\n api.getPublicInterface({ type: 'name', name, version })\n )\n return { interfaces }\n }\n\n protected async preparePluginDependencies(\n pluginDef: sdk.PluginDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.CreatePluginRequestBody>> {\n const integrations = await this._fetchDependencies(pluginDef.integrations ?? {}, ({ name, version }) =>\n api.getPublicOrPrivateIntegration({ type: 'name', name, version })\n )\n const interfaces = await this._fetchDependencies(pluginDef.interfaces ?? {}, ({ name, version }) =>\n api.getPublicInterface({ type: 'name', name, version })\n )\n return {\n dependencies: {\n integrations,\n interfaces,\n },\n }\n }\n\n private _fetchDependencies = async <T extends { id?: string; name: string; version: string }>(\n deps: Record<string, T>,\n fetcher: (dep: T) => Promise<{ id: string }>\n ): Promise<Record<string, T & { id: string }>> => {\n const isRemote = (dep: T): dep is T & { id: string } => dep.id !== undefined\n return utils.records.mapValuesAsync(deps, async (dep): Promise<T & { id: string }> => {\n if (isRemote(dep)) {\n return dep\n }\n const { id } = await fetcher(dep)\n return { ...dep, id }\n })\n }\n\n protected readProjectFile = async (\n filePath: string | undefined,\n encoding: BufferEncoding = 'utf-8'\n ): Promise<string | undefined> => {\n if (!filePath) {\n return undefined\n }\n const absoluteFilePath = utils.path.absoluteFrom(this.projectPaths.abs.workDir, filePath)\n return fs.promises.readFile(absoluteFilePath, encoding).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not read file \"${absoluteFilePath}\"`)\n })\n }\n\n private _parseArgvSecrets(argvSecrets: string[]): Record<string, string> {\n const parsed: Record<string, string> = {}\n for (const secret of argvSecrets) {\n const [key, value] = utils.string.splitOnce(secret, '=')\n if (!value) {\n throw new errors.BotpressCLIError(\n `Secret \"${key}\" is missing a value. Expected format: \"SECRET_NAME=secretValue\"`\n )\n }\n parsed[key!] = value\n }\n\n return parsed\n }\n\n private _notifyUpdateSdk = async (): Promise<void> => {\n try {\n this.logger.debug('Checking if sdk is up to date')\n\n const { workDir } = this.projectPaths.abs\n const projectPkgJson = await utils.pkgJson.readPackageJson(workDir)\n if (!projectPkgJson) {\n this.logger.debug(`Could not find package.json at \"${workDir}\"`)\n return\n }\n\n const sdkPackageName = '@botpress/sdk'\n const actualSdkVersion = utils.pkgJson.findDependency(projectPkgJson, sdkPackageName)\n if (!actualSdkVersion) {\n this.logger.debug(`Could not find dependency \"${sdkPackageName}\" in project package.json`)\n return\n }\n\n if (actualSdkVersion.startsWith('workspace:')) {\n return\n }\n\n const actualCleanedSdkVersion = semver.valid(semver.coerce(actualSdkVersion))\n if (!actualCleanedSdkVersion) {\n this.logger.debug(`Invalid sdk version \"${actualSdkVersion}\" in project package.json`)\n return\n }\n\n const cliPkgJson = await this.readPkgJson()\n const expectedSdkVersion = utils.pkgJson.findDependency(cliPkgJson, sdkPackageName)\n if (!expectedSdkVersion) {\n this.logger.debug(`Could not find dependency \"${sdkPackageName}\" in cli package.json`)\n return\n }\n\n const expectedCleanedSdkVersion = semver.valid(semver.coerce(expectedSdkVersion))\n if (!expectedCleanedSdkVersion) {\n this.logger.debug(`Invalid sdk version \"${expectedSdkVersion}\" in cli package.json`)\n return\n }\n\n if (semver.eq(actualCleanedSdkVersion, expectedCleanedSdkVersion)) {\n return\n }\n\n const diff = semver.diff(actualCleanedSdkVersion, expectedCleanedSdkVersion)\n if (!diff) {\n this.logger.debug(`Could not compare versions \"${actualCleanedSdkVersion}\" and \"${expectedCleanedSdkVersion}\"`)\n return\n }\n\n const errorMsg = `Project SDK version is \"${actualCleanedSdkVersion}\", but expected \"${expectedCleanedSdkVersion}\"`\n if (utils.semver.releases.lt(diff, 'minor')) {\n this.logger.debug(`${errorMsg}. This may cause compatibility issues.`)\n return\n }\n\n this.logger.warn(chalk.bold(`${errorMsg}. This will cause compatibility issues.`))\n } catch (thrown) {\n const err = errors.BotpressCLIError.map(thrown)\n this.logger.debug(`Failed to check if sdk is up to date: ${err.message}`)\n }\n }\n protected validateIntegrationRegistration(\n updatedBot: UpdatedBot,\n onFailCallback: (failedIntegrations: UpdatedBot['integrations']) => void\n ) {\n let failedIntegrations: UpdatedBot['integrations'] = {}\n for (const [integrationName, integration] of Object.entries(updatedBot.integrations)) {\n if (integration.status === 'registration_failed') {\n failedIntegrations = { ...failedIntegrations, [integrationName]: integration }\n }\n }\n if (Object.keys(failedIntegrations).length > 0) {\n onFailCallback(failedIntegrations)\n }\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAkB;AAClB,gBAAe;AACf,oBAAc;AACd,oBAAmB;AACnB,eAA0B;AAC1B,cAAyB;AAEzB,aAAwB;AACxB,aAAwB;AACxB,iBAAqE;AAErE,YAAuB;AACvB,4BAA8B;AA6C9B,MAAM,qBAAqB,MAAM,KAAK,UAAiC;AAAA,EAC9D,YAAY,MAA6C;AAC9D,UAAM,aAAa,MAAM,KAAK,aAAa,MAAM,KAAK,IAAI,GAAG,KAAK,OAAO;AACzE,UAAM;AAAA,MACJ,SAAS;AAAA,MACT,GAAG,cAAAA,QAAE,UAAU,OAAO,aAAa,CAAC,MAAM,MAAM,KAAK,aAAa,YAAY,CAAC,CAAC;AAAA,IAClF,CAAC;AAAA,EACH;AACF;AAEO,MAAM,yBAAyB;AAAA,EAC5B,aAAkC,oBAAI,IAAI;AAAA,EAC1C,gBAAsD,IAAI,MAAM,QAAQ,uBAAuB;AAAA,EAEhG,uBAAyC,MAAiB;AAC/D,UAAM,aAAa,KAAK,WAAW,IAAI,IAAI;AAC3C,QAAI,YAAY;AACd,aAAO;AAAA,IACT;AACA,UAAM,SAAS,MAAM,QAAQ,cAAmC,IAAI;AACpE,SAAK,WAAW,IAAI,MAAM,OAAO,OAAO;AACxC,WAAO,OAAO;AAAA,EAChB;AAAA,EAEO,qBAAqB,MAAmE;AAC7F,WAAO,KA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tD,eAAW,CAAC,iBAAiB,WAAW,KAAK,OAAO,QAAQ,WAAW,YAAY,GAAG;AACpF,UAAI,YAAY,WAAW,uBAAuB;AAChD,6BAAqB,EAAE,GAAG,oBAAoB,CAAC,eAAe,GAAG,YAAY;AAAA,MAC/E;AAAA,IACF;AACA,QAAI,OAAO,KAAK,kBAAkB,EAAE,SAAS,GAAG;AAC9C,qBAAe,kBAAkB;AAAA,IACnC;AAAA,EACF;AACF;",
6
- "names": ["_", "fs", "chalk", "semver"]
4
+ "sourcesContent": ["import type * as client from '@botpress/client'\nimport type * as sdk from '@botpress/sdk'\nimport type { YargsConfig } from '@bpinternal/yargs-extra'\nimport chalk from 'chalk'\nimport fs from 'fs'\nimport _ from 'lodash'\nimport semver from 'semver'\nimport * as apiUtils from '../api'\nimport * as codegen from '../code-generation'\nimport * as config from '../config'\nimport * as consts from '../consts'\nimport * as errors from '../errors'\nimport { validateIntegrationDefinition, validateBotDefinition } from '../sdk'\nimport type { CommandArgv, CommandDefinition } from '../typings'\nimport * as utils from '../utils'\nimport { GlobalCommand } from './global-command'\n\nexport type ProjectCommandDefinition = CommandDefinition<typeof config.schemas.project>\nexport type ProjectCache = { botId: string; devId: string; tunnelId: string }\n\ntype ConfigurableProjectPaths = { workDir: string }\ntype ConstantProjectPaths = typeof consts.fromWorkDir\ntype AllProjectPaths = ConfigurableProjectPaths & ConstantProjectPaths\n\ntype LintIgnoredConfig = { bpLintDisabled?: boolean }\n\nexport type ProjectType = ProjectDefinition['type']\nexport type ProjectDefinition = LintIgnoredConfig &\n (\n | { type: 'integration'; definition: sdk.IntegrationDefinition }\n | { type: 'interface'; definition: sdk.InterfaceDefinition }\n | { type: 'bot'; definition: sdk.BotDefinition }\n | { type: 'plugin'; definition: sdk.PluginDefinition }\n )\n\ntype ProjectDefinitionResolver<T> = () => Promise<LintIgnoredConfig & T>\n\nexport type ProjectDefinitionLazy =\n | {\n projectType: 'integration'\n resolveProjectDefinition: ProjectDefinitionResolver<{\n type: 'integration'\n definition: sdk.IntegrationDefinition\n }>\n }\n | {\n projectType: 'bot'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'bot'; definition: sdk.BotDefinition }>\n }\n | {\n projectType: 'interface'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'interface'; definition: sdk.InterfaceDefinition }>\n }\n | {\n projectType: 'plugin'\n resolveProjectDefinition: ProjectDefinitionResolver<{ type: 'plugin'; definition: sdk.PluginDefinition }>\n }\n\ntype UpdatedBot = client.Bot\n\ntype ClientIntegrationDefinitions = Record<string, client.Integration>\ntype ClientIntegration = client.Bot['integrations'][string]\n\nclass ProjectPaths extends utils.path.PathStore<keyof AllProjectPaths> {\n public constructor(argv: CommandArgv<ProjectCommandDefinition>) {\n const absWorkDir = utils.path.absoluteFrom(utils.path.cwd(), argv.workDir)\n super({\n workDir: absWorkDir,\n ..._.mapValues(consts.fromWorkDir, (p) => utils.path.absoluteFrom(absWorkDir, p)),\n })\n }\n}\n\nexport class ProjectDefinitionContext {\n private _codeCache: Map<string, object> = new Map()\n private _buildContext: utils.esbuild.BuildEntrypointContext = new utils.esbuild.BuildEntrypointContext()\n\n public getOrResolveDefinition<T extends object>(code: string): T {\n const definition = this._codeCache.get(code)\n if (definition) {\n return definition as T\n }\n const result = utils.require.requireJsCode<{ default: object }>(code)\n this._codeCache.set(code, result.default)\n return result.default as T\n }\n\n public rebuildEntrypoint(...args: Parameters<utils.esbuild.BuildEntrypointContext['rebuild']>) {\n return this._buildContext.rebuild(...args)\n }\n}\n\nexport abstract class ProjectCommand<C extends ProjectCommandDefinition> extends GlobalCommand<C> {\n protected projectContext: ProjectDefinitionContext = new ProjectDefinitionContext()\n\n public setProjectContext(projectContext: ProjectDefinitionContext) {\n this.projectContext = projectContext\n return this\n }\n\n protected override async bootstrap() {\n await super.bootstrap()\n await this._notifyUpdateSdk()\n }\n\n protected get projectPaths() {\n return new ProjectPaths(this.argv)\n }\n\n protected get projectCache() {\n return new utils.cache.FSKeyValueCache<ProjectCache>(this.projectPaths.abs.projectCacheFile)\n }\n\n private _readProjectType(projectPaths: ProjectPaths): ProjectType {\n const abs = projectPaths.abs\n if (fs.existsSync(abs.integrationDefinition)) {\n return 'integration'\n }\n if (fs.existsSync(abs.interfaceDefinition)) {\n return 'interface'\n }\n if (fs.existsSync(abs.botDefinition)) {\n return 'bot'\n }\n if (fs.existsSync(abs.pluginDefinition)) {\n return 'plugin'\n }\n throw new errors.UnsupportedProjectType()\n }\n\n protected readProjectDefinitionFromFS(): ProjectDefinitionLazy {\n try {\n const type = this._readProjectType(this.projectPaths)\n if (type === 'integration') {\n return {\n projectType: 'integration',\n resolveProjectDefinition: async () => ({\n type: 'integration',\n ...(await this._readIntegrationDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'plugin') {\n return {\n projectType: 'plugin',\n resolveProjectDefinition: async () => ({\n type: 'plugin',\n ...(await this._readPluginDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'interface') {\n return {\n projectType: 'interface',\n resolveProjectDefinition: async () => ({\n type: 'interface',\n ...(await this._readInterfaceDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n if (type === 'bot') {\n return {\n projectType: 'bot',\n resolveProjectDefinition: async () => ({\n type: 'bot',\n ...(await this._readBotDefinitionFromFS(this.projectPaths)),\n }),\n }\n }\n } catch (thrown: unknown) {\n throw errors.BotpressCLIError.wrap(thrown, 'Error while reading project definition')\n }\n throw new errors.ProjectDefinitionNotFoundError(this.projectPaths.abs.workDir)\n }\n\n private async _readIntegrationDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'integrationDefinition'>\n ): Promise<{ definition: sdk.IntegrationDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.integrationDefinition)) {\n throw new errors.BotpressCLIError('Could not read integration definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.integrationDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.integrationDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read integration definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.IntegrationDefinition>(artifact.text)\n validateIntegrationDefinition(definition)\n return { definition, bpLintDisabled }\n }\n\n private async _readInterfaceDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'interfaceDefinition'>\n ): Promise<{ definition: sdk.InterfaceDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.interfaceDefinition)) {\n throw new errors.BotpressCLIError('Could not read interface definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.interfaceDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.interfaceDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read interface definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.InterfaceDefinition>(artifact.text)\n\n return { definition, bpLintDisabled }\n }\n\n private async _readBotDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'botDefinition'>\n ): Promise<{ definition: sdk.BotDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.botDefinition)) {\n throw new errors.BotpressCLIError('Could not read bot definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.botDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.botDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read bot definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.BotDefinition>(artifact.text)\n validateBotDefinition(definition)\n return { definition, bpLintDisabled }\n }\n\n private async _readPluginDefinitionFromFS(\n projectPaths: utils.path.PathStore<'workDir' | 'pluginDefinition'>\n ): Promise<{ definition: sdk.PluginDefinition } & LintIgnoredConfig> {\n const abs = projectPaths.abs\n const rel = projectPaths.rel('workDir')\n\n if (!fs.existsSync(abs.pluginDefinition)) {\n throw new errors.BotpressCLIError('Could not read plugin definition')\n }\n\n const bpLintDisabled = await this._isBpLintDisabled(abs.pluginDefinition)\n\n const { outputFiles } = await this.projectContext.rebuildEntrypoint({\n absWorkingDir: abs.workDir,\n entrypoint: rel.pluginDefinition,\n })\n\n const artifact = outputFiles?.[0]\n if (!artifact) {\n throw new errors.BotpressCLIError('Could not read plugin definition')\n }\n\n const definition = this.projectContext.getOrResolveDefinition<sdk.PluginDefinition>(artifact.text)\n // TODO: validate plugin definition\n return { definition, bpLintDisabled }\n }\n\n private async _isBpLintDisabled(definitionPath: string): Promise<boolean> {\n const tsContent = await fs.promises.readFile(definitionPath, 'utf-8')\n const regex = /\\/\\* bplint-disable \\*\\//\n return regex.test(tsContent)\n }\n\n protected async displayIntegrationUrls({ api, bot }: { api: apiUtils.ApiClient; bot: client.Bot }) {\n if (!_.keys(bot.integrations).length) {\n this.logger.debug('No integrations in bot')\n return\n }\n\n const integrationDefinitions = await utils.records.mapValuesAsync(bot.integrations, async (integration) =>\n api.getPublicOrPrivateIntegration({\n type: 'id',\n id: integration.id,\n })\n )\n\n this.logger.log('Integrations:')\n for (const [alias, integration] of Object.entries(bot.integrations)) {\n if (integration.enabled) {\n this.logger.log(`${alias}:`, { prefix: { symbol: '\u2192', indent: 2 } })\n } else {\n this.logger.log(`${alias} ${chalk.italic('(disabled)')}:`, {\n prefix: { symbol: '\u2192', indent: 2 },\n })\n }\n\n const integrationDefinition = integrationDefinitions[alias]\n const linkTemplateScript = integrationDefinition\n ? this._getLinkTemplateScript({ integration, integrationDefinition })\n : undefined\n this._displayWebhookUrl({ integration, integrationDefinition, linkTemplateScript })\n if (!integrationDefinition) {\n this.logger.debug(\n `No integration definition for integration ${alias} (${integration.name}, ${integration.id}), skipping OAuth or Sandbox links`\n )\n this.logger.line().commit()\n continue\n }\n const isSandbox =\n integration.configurationType === 'sandbox' && !!integrationDefinition.sandbox?.identifierExtractScript\n const showLink = !!linkTemplateScript && (isSandbox || !!integrationDefinition.identifier?.extractScript)\n if (showLink && isSandbox) {\n await this._displaySandboxLinkAndCode({ integration, alias, bot, api, linkTemplateScript })\n } else if (showLink) {\n this._displayAuthorizationLink({ integration, api, linkTemplateScript })\n }\n this.logger.line().commit()\n }\n }\n\n private _getLinkTemplateScript({\n integration,\n integrationDefinition,\n }: {\n integration: ClientIntegration\n integrationDefinition?: ClientIntegrationDefinitions[string]\n }) {\n const config =\n integration.configurationType === null\n ? integrationDefinition?.configuration\n : integrationDefinition?.configurations[integration.configurationType]\n return config?.identifier?.linkTemplateScript\n }\n\n private _displayWebhookUrl({\n integration,\n integrationDefinition,\n linkTemplateScript,\n }: {\n integration: ClientIntegration\n integrationDefinition?: ClientIntegrationDefinitions[string]\n linkTemplateScript?: string\n }) {\n const needsWebhook = !(integrationDefinition?.identifier && linkTemplateScript)\n const logFn = (needsWebhook ? this.logger.log : this.logger.debug).bind(this.logger)\n\n if (integration.enabled) {\n logFn(`${chalk.bold('Webhook')}: ${integration.webhookUrl}`, {\n prefix: { symbol: '\u25CF', indent: 4 },\n })\n } else {\n logFn(`Webhook: ${integration.webhookUrl}`, {\n prefix: { symbol: '\u25CB', indent: 4 },\n })\n }\n }\n\n private _displayAuthorizationLink({\n integration,\n api,\n linkTemplateScript,\n }: {\n integration: ClientIntegration\n api: apiUtils.ApiClient\n linkTemplateScript: string\n }) {\n const authorizationLink = this._getAuthorizationLink({ integration, api, linkTemplateScript })\n const isAuthorized = !!integration.identifier\n const authorizationStatus = integration.identifier ? 'Authorized \u2713' : 'Authorize'\n if (integration.enabled && isAuthorized) {\n this.logger.log(`${chalk.bold(authorizationStatus)} : ${authorizationLink}`, {\n prefix: { symbol: '\u25CF', indent: 4 },\n })\n } else {\n this.logger.log(`${authorizationStatus}: ${authorizationLink}`, {\n prefix: { symbol: '\u25CB', indent: 4 },\n })\n }\n }\n\n private _getLinkTemplateArgs({ integration, api }: { integration: ClientIntegration; api: apiUtils.ApiClient }) {\n // These are the values used by the studio\n let env: 'development' | 'preview' | 'production'\n if (api.url.includes(consts.stagingBotpressDomain)) {\n env = 'preview'\n } else if (api.url.includes(consts.productionBotpressDomain)) {\n env = 'production'\n } else {\n env = 'development'\n }\n return {\n env,\n webhookId: integration.webhookId,\n webhookUrl: api.url.replace('api', 'webhook'),\n }\n }\n\n private _getAuthorizationLink({\n integration,\n api,\n linkTemplateScript,\n }: {\n integration: client.Bot['integrations'][string]\n api: apiUtils.ApiClient\n linkTemplateScript: string\n }) {\n return utils.vrl.getStringResult({\n code: linkTemplateScript,\n data: this._getLinkTemplateArgs({ integration, api }),\n })\n }\n\n private _getSandboxLink({\n shareableId,\n integration,\n api,\n linkTemplateScript,\n }: {\n shareableId: string\n integration: ClientIntegration\n api: apiUtils.ApiClient\n linkTemplateScript: string\n }) {\n return utils.vrl.getStringResult({\n code: linkTemplateScript,\n data: { shareableId, ...this._getLinkTemplateArgs({ integration, api }) },\n })\n }\n\n private async _displaySandboxLinkAndCode({\n integration,\n alias,\n bot,\n api,\n linkTemplateScript,\n }: {\n integration: ClientIntegration\n alias: string\n bot: client.Bot\n api: apiUtils.ApiClient\n linkTemplateScript: string\n }) {\n const shareableId = await api.getOrGenerateShareableId(bot.id, integration.id, alias)\n const sandboxLink = this._getSandboxLink({ shareableId, integration, api, linkTemplateScript })\n const sandboxInstruction = `Send '${shareableId}' to ${sandboxLink}`\n if (integration.enabled) {\n this.logger.log(`${chalk.bold('Sandbox')}: ${sandboxInstruction}`, {\n prefix: { symbol: '\u25CF', indent: 4 },\n })\n } else {\n this.logger.log(`Sandbox: ${sandboxInstruction}`, {\n prefix: { symbol: '\u25CB', indent: 4 },\n })\n }\n }\n\n protected async promptSecrets(\n integrationDef: sdk.IntegrationDefinition,\n argv: YargsConfig<typeof config.schemas.secrets>,\n opts: { formatEnv?: boolean; knownSecrets?: string[] } = {}\n ): Promise<Record<string, string | null>> {\n const formatEnv = opts.formatEnv ?? false\n const knownSecrets = opts.knownSecrets ?? []\n\n const { secrets: secretDefinitions } = integrationDef\n if (!secretDefinitions) {\n return {}\n }\n\n const secretArgv = this._parseArgvSecrets(argv.secrets)\n const invalidSecret = Object.keys(secretArgv).find((s) => !secretDefinitions[s])\n if (invalidSecret) {\n throw new errors.BotpressCLIError(`Secret ${invalidSecret} is not defined in integration definition`)\n }\n\n const values: Record<string, string | null> = {}\n for (const [secretName, { optional }] of Object.entries(secretDefinitions)) {\n const argvSecret = secretArgv[secretName]\n if (argvSecret) {\n this.logger.debug(`Using secret \"${secretName}\" from argv`)\n values[secretName] = argvSecret\n continue\n }\n\n const alreadyKnown = knownSecrets.includes(secretName)\n let mode: string\n if (alreadyKnown) {\n mode = 'already set'\n } else if (optional) {\n mode = 'optional'\n } else {\n mode = 'required'\n }\n\n const prompted = await this.prompt.text(`Enter value for secret \"${secretName}\" (${mode})`)\n if (prompted) {\n values[secretName] = prompted\n continue\n }\n\n if (alreadyKnown) {\n this.logger.log(`Secret \"${secretName}\" is unchanged`)\n } else if (optional) {\n this.logger.warn(`Secret \"${secretName}\" is unassigned`)\n } else {\n throw new errors.BotpressCLIError(`Secret \"${secretName}\" is required`)\n }\n }\n\n for (const secretName of knownSecrets) {\n const isDefined = secretName in secretDefinitions\n if (isDefined) {\n continue\n }\n const prompted = await this.prompt.confirm(`Secret \"${secretName}\" was removed. Do you wish to delete it?`)\n if (prompted) {\n this.logger.log(`Deleting secret \"${secretName}\"`, { prefix: { symbol: '\u00D7', fg: 'red' } })\n values[secretName] = null\n }\n }\n\n if (!formatEnv) {\n return values\n }\n\n const envVariables = _.mapKeys(values, (_v, k) => codegen.secretEnvVariableName(k))\n return envVariables\n }\n\n protected async prepareCreateIntegrationBody(\n integrationDef: sdk.IntegrationDefinition\n ): Promise<apiUtils.CreateIntegrationRequestBody> {\n const partialBody = await apiUtils.prepareCreateIntegrationBody(integrationDef)\n\n let code: string | undefined = undefined\n if (fs.existsSync(this.projectPaths.abs.outFileCJS)) {\n code = await this.readProjectFile(this.projectPaths.abs.outFileCJS)\n }\n\n const icon = await this.readProjectFile(integrationDef.icon, 'base64')\n const readme = await this.readProjectFile(integrationDef.readme, 'base64')\n const extractScript = await this.readProjectFile(integrationDef.identifier?.extractScript)\n const fallbackHandlerScript = await this.readProjectFile(integrationDef.identifier?.fallbackHandlerScript)\n return {\n ...partialBody,\n code,\n icon,\n readme,\n identifier: {\n extractScript,\n fallbackHandlerScript,\n },\n configuration: integrationDef.configuration\n ? {\n schema: await utils.schema.mapZodToJsonSchema(integrationDef.configuration, {\n useLegacyZuiTransformer: integrationDef.__advanced?.useLegacyZuiTransformer,\n }),\n identifier: {\n required: integrationDef.configuration.identifier?.required,\n linkTemplateScript: await this.readProjectFile(\n integrationDef.configuration.identifier?.linkTemplateScript\n ),\n },\n }\n : undefined,\n configurations: integrationDef.configurations\n ? await utils.records.mapValuesAsync(integrationDef.configurations, async (configuration) => ({\n title: configuration.title,\n description: configuration.description,\n schema: await utils.schema.mapZodToJsonSchema(configuration, {\n useLegacyZuiTransformer: integrationDef.__advanced?.useLegacyZuiTransformer,\n }),\n identifier: {\n required: configuration.identifier?.required,\n linkTemplateScript: await this.readProjectFile(configuration.identifier?.linkTemplateScript),\n },\n }))\n : undefined,\n }\n }\n\n protected async prepareBotDependencies(\n botDef: sdk.BotDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.UpdateBotRequestBody>> {\n const integrations = await this._fetchDependencies(botDef.integrations ?? {}, ({ name, version }) =>\n api.getPublicOrPrivateIntegration({ type: 'name', name, version })\n )\n\n const plugins = await this._fetchDependencies(\n botDef.plugins ?? {},\n async ({ name, version }) => await api.getPublicOrPrivatePlugin({ type: 'name', name, version })\n )\n\n const pluginsWithBackingIntegrations = await utils.records.mapValuesAsync(plugins, async (plugin) => ({\n ...plugin,\n interfaces: await this._fetchDependencies(\n plugin.interfaces ?? {},\n async (interfaceExtension) => await api.getPublicOrPrivateIntegration({ ...interfaceExtension, type: 'name' })\n ),\n }))\n\n return {\n integrations: utils.records.mapValues(\n integrations,\n ({ enabled, configurationType, configuration, disabledChannels, id }) =>\n ({\n enabled,\n configurationType,\n configuration,\n disabledChannels,\n integrationId: id,\n }) satisfies NonNullable<apiUtils.UpdateBotRequestBody['integrations']>[string]\n ),\n plugins: utils.records.mapValues(pluginsWithBackingIntegrations, (plugin) => ({\n ...plugin,\n interfaces: utils.records.mapValues(plugin.interfaces ?? {}, (iface) => ({\n ...iface,\n integrationId: iface.id,\n })),\n })),\n }\n }\n\n protected async prepareIntegrationDependencies(\n integrationDef: sdk.IntegrationDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.CreateIntegrationRequestBody>> {\n const interfaces = await this._fetchDependencies(integrationDef.interfaces ?? {}, ({ name, version }) =>\n api.getPublicInterface({ type: 'name', name, version })\n )\n return { interfaces }\n }\n\n protected async preparePluginDependencies(\n pluginDef: sdk.PluginDefinition,\n api: apiUtils.ApiClient\n ): Promise<Partial<apiUtils.CreatePluginRequestBody>> {\n const integrations = await this._fetchDependencies(pluginDef.integrations ?? {}, ({ name, version }) =>\n api.getPublicOrPrivateIntegration({ type: 'name', name, version })\n )\n const interfaces = await this._fetchDependencies(pluginDef.interfaces ?? {}, ({ name, version }) =>\n api.getPublicInterface({ type: 'name', name, version })\n )\n return {\n dependencies: {\n integrations,\n interfaces,\n },\n }\n }\n\n private _fetchDependencies = async <T extends { id?: string; name: string; version: string }>(\n deps: Record<string, T>,\n fetcher: (dep: T) => Promise<{ id: string }>\n ): Promise<Record<string, T & { id: string }>> => {\n const isRemote = (dep: T): dep is T & { id: string } => dep.id !== undefined\n return utils.records.mapValuesAsync(deps, async (dep): Promise<T & { id: string }> => {\n if (isRemote(dep)) {\n return dep\n }\n const { id } = await fetcher(dep)\n return { ...dep, id }\n })\n }\n\n protected readProjectFile = async (\n filePath: string | undefined,\n encoding: BufferEncoding = 'utf-8'\n ): Promise<string | undefined> => {\n if (!filePath) {\n return undefined\n }\n const absoluteFilePath = utils.path.absoluteFrom(this.projectPaths.abs.workDir, filePath)\n return fs.promises.readFile(absoluteFilePath, encoding).catch((thrown) => {\n throw errors.BotpressCLIError.wrap(thrown, `Could not read file \"${absoluteFilePath}\"`)\n })\n }\n\n private _parseArgvSecrets(argvSecrets: string[]): Record<string, string> {\n const parsed: Record<string, string> = {}\n for (const secret of argvSecrets) {\n const [key, value] = utils.string.splitOnce(secret, '=')\n if (!value) {\n throw new errors.BotpressCLIError(\n `Secret \"${key}\" is missing a value. Expected format: \"SECRET_NAME=secretValue\"`\n )\n }\n parsed[key!] = value\n }\n\n return parsed\n }\n\n private _notifyUpdateSdk = async (): Promise<void> => {\n try {\n this.logger.debug('Checking if sdk is up to date')\n\n const { workDir } = this.projectPaths.abs\n const projectPkgJson = await utils.pkgJson.readPackageJson(workDir)\n if (!projectPkgJson) {\n this.logger.debug(`Could not find package.json at \"${workDir}\"`)\n return\n }\n\n const sdkPackageName = '@botpress/sdk'\n const actualSdkVersion = utils.pkgJson.findDependency(projectPkgJson, sdkPackageName)\n if (!actualSdkVersion) {\n this.logger.debug(`Could not find dependency \"${sdkPackageName}\" in project package.json`)\n return\n }\n\n if (actualSdkVersion.startsWith('workspace:')) {\n return\n }\n\n const actualCleanedSdkVersion = semver.valid(semver.coerce(actualSdkVersion))\n if (!actualCleanedSdkVersion) {\n this.logger.debug(`Invalid sdk version \"${actualSdkVersion}\" in project package.json`)\n return\n }\n\n const cliPkgJson = await this.readPkgJson()\n const expectedSdkVersion = utils.pkgJson.findDependency(cliPkgJson, sdkPackageName)\n if (!expectedSdkVersion) {\n this.logger.debug(`Could not find dependency \"${sdkPackageName}\" in cli package.json`)\n return\n }\n\n const expectedCleanedSdkVersion = semver.valid(semver.coerce(expectedSdkVersion))\n if (!expectedCleanedSdkVersion) {\n this.logger.debug(`Invalid sdk version \"${expectedSdkVersion}\" in cli package.json`)\n return\n }\n\n if (semver.eq(actualCleanedSdkVersion, expectedCleanedSdkVersion)) {\n return\n }\n\n const diff = semver.diff(actualCleanedSdkVersion, expectedCleanedSdkVersion)\n if (!diff) {\n this.logger.debug(`Could not compare versions \"${actualCleanedSdkVersion}\" and \"${expectedCleanedSdkVersion}\"`)\n return\n }\n\n const errorMsg = `Project SDK version is \"${actualCleanedSdkVersion}\", but expected \"${expectedCleanedSdkVersion}\"`\n if (utils.semver.releases.lt(diff, 'minor')) {\n this.logger.debug(`${errorMsg}. This may cause compatibility issues.`)\n return\n }\n\n this.logger.warn(chalk.bold(`${errorMsg}. This will cause compatibility issues.`))\n } catch (thrown) {\n const err = errors.BotpressCLIError.map(thrown)\n this.logger.debug(`Failed to check if sdk is up to date: ${err.message}`)\n }\n }\n protected validateIntegrationRegistration(\n updatedBot: UpdatedBot,\n onFailCallback: (failedIntegrations: UpdatedBot['integrations']) => void\n ) {\n let failedIntegrations: UpdatedBot['integrations'] = {}\n for (const [integrationName, integration] of Object.entries(updatedBot.integrations)) {\n if (integration.status === 'registration_failed') {\n failedIntegrations = { ...failedIntegrations, [integrationName]: integration }\n }\n }\n if (Object.keys(failedIntegrations).length > 0) {\n onFailCallback(failedIntegrations)\n }\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAkB;AAClB,gBAAe;AACf,oBAAc;AACd,oBAAmB;AACnB,eAA0B;AAC1B,cAAyB;AAEzB,aAAwB;AACxB,aAAwB;AACxB,iBAAqE;AAErE,YAAuB;AACvB,4BAA8B;AAgD9B,MAAM,qBAAqB,MAAM,KAAK,UAAiC;AAAA,EAC9D,YAAY,MAA6C;AAC9D,UAAM,aAAa,MAAM,KAAK,aAAa,MAAM,KAAK,IAAI,GAAG,KAAK,OAAO;AACzE,UA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,KAAK,aAAAF,QAAM,KAAK,GAAG,QAAQ,yCAAyC,CAAC;AAAA,IACnF,SAAS,QAAQ;AACf,YAAM,MAAM,OAAO,iBAAiB,IAAI,MAAM;AAC9C,WAAK,OAAO,MAAM,yCAAyC,IAAI,OAAO,EAAE;AAAA,IAC1E;AAAA,EACF;AAAA,EACU,gCACR,YACA,gBACA;AACA,QAAI,qBAAiD,CAAC;AACtD,eAAW,CAAC,iBAAiB,WAAW,KAAK,OAAO,QAAQ,WAAW,YAAY,GAAG;AACpF,UAAI,YAAY,WAAW,uBAAuB;AAChD,6BAAqB,EAAE,GAAG,oBAAoB,CAAC,eAAe,GAAG,YAAY;AAAA,MAC/E;AAAA,IACF;AACA,QAAI,OAAO,KAAK,kBAAkB,EAAE,SAAS,GAAG;AAC9C,qBAAe,kBAAkB;AAAA,IACnC;AAAA,EACF;AACF;",
6
+ "names": ["_", "fs", "chalk", "config", "semver"]
7
7
  }
package/dist/consts.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export declare const productionBotpressDomain = "botpress.cloud";
2
+ export declare const stagingBotpressDomain = "botpress.dev";
1
3
  export declare const defaultBotpressHome: string;
2
4
  export declare const defaultWorkDir: string;
3
5
  export declare const defaultInstallPath: string;
package/dist/consts.js CHANGED
@@ -44,19 +44,23 @@ __export(consts_exports, {
44
44
  fromWorkDir: () => fromWorkDir,
45
45
  installDirName: () => installDirName,
46
46
  outDirName: () => outDirName,
47
- profileFileName: () => profileFileName
47
+ productionBotpressDomain: () => productionBotpressDomain,
48
+ profileFileName: () => profileFileName,
49
+ stagingBotpressDomain: () => stagingBotpressDomain
48
50
  });
49
51
  module.exports = __toCommonJS(consts_exports);
50
52
  var import_os = __toESM(require("os"));
51
53
  var import_path = __toESM(require("path"));
52
54
  var import_root = require("./root");
55
+ const productionBotpressDomain = "botpress.cloud";
56
+ const stagingBotpressDomain = "botpress.dev";
53
57
  const defaultBotpressHome = import_path.default.join(import_os.default.homedir(), ".botpress");
54
58
  const defaultWorkDir = process.cwd();
55
59
  const defaultInstallPath = process.cwd();
56
- const defaultBotpressApiUrl = "https://api.botpress.cloud";
57
- const defaultBotpressAppUrl = "https://app.botpress.cloud";
58
- const defaultTunnelUrl = "https://tunnel.botpress.cloud";
59
- const defaultChatApiUrl = "https://chat.botpress.cloud";
60
+ const defaultBotpressApiUrl = `https://api.${productionBotpressDomain}`;
61
+ const defaultBotpressAppUrl = `https://app.${productionBotpressDomain}`;
62
+ const defaultTunnelUrl = `https://tunnel.${productionBotpressDomain}`;
63
+ const defaultChatApiUrl = `https://chat.${productionBotpressDomain}`;
60
64
  const cliRootDir = import_root.CLI_ROOT_DIR;
61
65
  const installDirName = "bp_modules";
62
66
  const outDirName = ".botpress";
@@ -109,6 +113,8 @@ const fromWorkDir = {
109
113
  fromWorkDir,
110
114
  installDirName,
111
115
  outDirName,
112
- profileFileName
116
+ productionBotpressDomain,
117
+ profileFileName,
118
+ stagingBotpressDomain
113
119
  });
114
120
  //# sourceMappingURL=consts.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/consts.ts"],
4
- "sourcesContent": ["import os from 'os'\nimport pathlib from 'path'\nimport { CLI_ROOT_DIR } from './root'\n\n// configurable\n\nexport const defaultBotpressHome = pathlib.join(os.homedir(), '.botpress')\nexport const defaultWorkDir = process.cwd()\nexport const defaultInstallPath = process.cwd()\nexport const defaultBotpressApiUrl = 'https://api.botpress.cloud'\nexport const defaultBotpressAppUrl = 'https://app.botpress.cloud'\nexport const defaultTunnelUrl = 'https://tunnel.botpress.cloud'\nexport const defaultChatApiUrl = 'https://chat.botpress.cloud'\n\n// not configurable\n\nexport const cliRootDir = CLI_ROOT_DIR\nexport const installDirName = 'bp_modules'\nexport const outDirName = '.botpress'\nexport const distDirName = 'dist'\nexport const profileFileName = 'profiles.json'\nexport const defaultProfileName = 'default'\n\nexport const fromCliRootDir = {}\n\nexport const fromHomeDir = {\n globalCacheFile: 'global.cache.json',\n}\n\nexport const fromOutDir = {\n distDir: distDirName,\n outFileCJS: pathlib.join(distDirName, 'index.cjs'),\n outFileESM: pathlib.join(distDirName, 'index.mjs'),\n implementationDir: 'implementation',\n pluginsDir: 'plugins',\n secretsDir: 'secrets',\n projectCacheFile: 'project.cache.json',\n}\n\nexport const fromWorkDir = {\n integrationDefinition: 'integration.definition.ts',\n interfaceDefinition: 'interface.definition.ts',\n botDefinition: 'bot.definition.ts',\n pluginDefinition: 'plugin.definition.ts',\n entryPoint: pathlib.join('src', 'index.ts'),\n outDir: outDirName,\n distDir: pathlib.join(outDirName, fromOutDir.distDir),\n outFileCJS: pathlib.join(outDirName, fromOutDir.outFileCJS),\n outFileESM: pathlib.join(outDirName, fromOutDir.outFileESM),\n implementationDir: pathlib.join(outDirName, fromOutDir.implementationDir),\n pluginsDir: pathlib.join(outDirName, fromOutDir.pluginsDir),\n secretsDir: pathlib.join(outDirName, fromOutDir.secretsDir),\n projectCacheFile: pathlib.join(outDirName, fromOutDir.projectCacheFile),\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAe;AACf,kBAAoB;AACpB,kBAA6B;AAItB,MAAM,sBAAsB,YAAAA,QAAQ,KAAK,UAAAC,QAAG,QAAQ,GAAG,WAAW;AAClE,MAAM,iBAAiB,QAAQ,IAAI;AACnC,MAAM,qBAAqB,QAAQ,IAAI;AACvC,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAI1B,MAAM,aAAa;AACnB,MAAM,iBAAiB;AACvB,MAAM,aAAa;AACnB,MAAM,cAAc;AACpB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAE3B,MAAM,iBAAiB,CAAC;AAExB,MAAM,cAAc;AAAA,EACzB,iBAAiB;AACnB;AAEO,MAAM,aAAa;AAAA,EACxB,SAAS;AAAA,EACT,YAAY,YAAAD,QAAQ,KAAK,aAAa,WAAW;AAAA,EACjD,YAAY,YAAAA,QAAQ,KAAK,aAAa,WAAW;AAAA,EACjD,mBAAmB;AAAA,EACnB,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,kBAAkB;AACpB;AAEO,MAAM,cAAc;AAAA,EACzB,uBAAuB;AAAA,EACvB,qBAAqB;AAAA,EACrB,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB,YAAY,YAAAA,QAAQ,KAAK,OAAO,UAAU;AAAA,EAC1C,QAAQ;AAAA,EACR,SAAS,YAAAA,QAAQ,KAAK,YAAY,WAAW,OAAO;AAAA,EACpD,YAAY,YAAAA,QAAQ,KAAK,YAAY,WAAW,UAAU;AAAA,EAC1D,YAAY,YAAAA,QAAQ,KAAK,YAAY,WAAW,UAAU;AAAA,EAC1D,mBAAmB,YAAAA,QAAQ,KAAK,YAAY,WAAW,iBAAiB;AAAA,EACxE,YAAY,YAAAA,QAAQ,KAAK,YAAY,WAAW,UAAU;AAAA,EAC1D,YAAY,YAAAA,QAAQ,KAAK,YAAY,WAAW,UAAU;AAAA,EAC1D,kBAAkB,YAAAA,QAAQ,KAAK,YAAY,WAAW,gBAAgB;AACxE;",
4
+ "sourcesContent": ["import os from 'os'\nimport pathlib from 'path'\nimport { CLI_ROOT_DIR } from './root'\n\n// configurable\nexport const productionBotpressDomain = 'botpress.cloud'\nexport const stagingBotpressDomain = 'botpress.dev'\n\nexport const defaultBotpressHome = pathlib.join(os.homedir(), '.botpress')\nexport const defaultWorkDir = process.cwd()\nexport const defaultInstallPath = process.cwd()\nexport const defaultBotpressApiUrl = `https://api.${productionBotpressDomain}`\nexport const defaultBotpressAppUrl = `https://app.${productionBotpressDomain}`\nexport const defaultTunnelUrl = `https://tunnel.${productionBotpressDomain}`\nexport const defaultChatApiUrl = `https://chat.${productionBotpressDomain}`\n\n// not configurable\n\nexport const cliRootDir = CLI_ROOT_DIR\nexport const installDirName = 'bp_modules'\nexport const outDirName = '.botpress'\nexport const distDirName = 'dist'\nexport const profileFileName = 'profiles.json'\nexport const defaultProfileName = 'default'\n\nexport const fromCliRootDir = {}\n\nexport const fromHomeDir = {\n globalCacheFile: 'global.cache.json',\n}\n\nexport const fromOutDir = {\n distDir: distDirName,\n outFileCJS: pathlib.join(distDirName, 'index.cjs'),\n outFileESM: pathlib.join(distDirName, 'index.mjs'),\n implementationDir: 'implementation',\n pluginsDir: 'plugins',\n secretsDir: 'secrets',\n projectCacheFile: 'project.cache.json',\n}\n\nexport const fromWorkDir = {\n integrationDefinition: 'integration.definition.ts',\n interfaceDefinition: 'interface.definition.ts',\n botDefinition: 'bot.definition.ts',\n pluginDefinition: 'plugin.definition.ts',\n entryPoint: pathlib.join('src', 'index.ts'),\n outDir: outDirName,\n distDir: pathlib.join(outDirName, fromOutDir.distDir),\n outFileCJS: pathlib.join(outDirName, fromOutDir.outFileCJS),\n outFileESM: pathlib.join(outDirName, fromOutDir.outFileESM),\n implementationDir: pathlib.join(outDirName, fromOutDir.implementationDir),\n pluginsDir: pathlib.join(outDirName, fromOutDir.pluginsDir),\n secretsDir: pathlib.join(outDirName, fromOutDir.secretsDir),\n projectCacheFile: pathlib.join(outDirName, fromOutDir.projectCacheFile),\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAe;AACf,kBAAoB;AACpB,kBAA6B;AAGtB,MAAM,2BAA2B;AACjC,MAAM,wBAAwB;AAE9B,MAAM,sBAAsB,YAAAA,QAAQ,KAAK,UAAAC,QAAG,QAAQ,GAAG,WAAW;AAClE,MAAM,iBAAiB,QAAQ,IAAI;AACnC,MAAM,qBAA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odeJS.WriteStream;
5
5
  errStream: NodeJS.WriteStream;
6
6
  };
7
- type Symbol = '✓' | '⚠' | '×' | '●' | ' ' | '○';
7
+ type Symbol = '✓' | '⚠' | '×' | '●' | ' ' | '○' | '→';
8
8
  type Color = 'blue' | 'green' | 'yellow' | 'red' | 'pink' | 'white' | 'orange' | 'purple';
9
9
  type LogPrefix = {
10
10
  symbol: Symbol;
@@ -80,13 +80,15 @@ const danger = { default: "\u26A0" };
80
80
  const circle = { default: "\u25CB" };
81
81
  const disc = { default: "\u25CF" };
82
82
  const space = { default: " " };
83
+ const arrow = { default: "\u2192" };
83
84
  const renderers = {
84
85
  "\u2713": checkmark,
85
86
  "\xD7": cross,
86
87
  "\u26A0": danger,
87
88
  "\u25CB": circle,
88
89
  "\u25CF": disc,
89
- " ": space
90
+ " ": space,
91
+ "\u2192": arrow
90
92
  };
91
93
  const BOX_OPTIONS = {
92
94
  padding: 1,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/logger/base-logger.ts"],
4
- "sourcesContent": ["import boxen from 'boxen'\nimport chalk from 'chalk'\nimport _ from 'lodash'\nimport util from 'util'\nimport * as utils from '../utils'\n\nexport type LoggerOptions = {\n verbose: boolean\n json: boolean // prevents loggin anything else than json\n outStream: NodeJS.WriteStream\n errStream: NodeJS.WriteStream\n}\n\nconst STDOUT_CHUNK_SIZE = 100\nconst DEFAULT_OPTIONS: LoggerOptions = {\n verbose: false,\n json: false,\n outStream: process.stdout,\n errStream: process.stderr,\n}\n\ntype ChalkColor = (str: string) => string\nconst NO_COLOR: ChalkColor = (str: string) => str\n\nconst PINK = [255, 100, 255] as const\nconst ORANGE = [255, 165, 0] as const\nconst PURPLE = [128, 0, 128] as const\n\nconst BG_COLORS: Record<Color, ChalkColor> = {\n blue: chalk.bgBlueBright,\n green: chalk.bgGreenBright,\n yellow: chalk.bgYellowBright,\n red: chalk.bgRedBright,\n white: chalk.bgWhite,\n pink: (str: string) => chalk.bgRgb(...PINK)(str),\n orange: (str: string) => chalk.bgRgb(...ORANGE)(str),\n purple: (str: string) => chalk.bgRgb(...PURPLE)(str),\n}\n\nconst FG_COLORS: Record<Color, ChalkColor> = {\n blue: chalk.blueBright,\n green: chalk.green,\n yellow: chalk.yellowBright,\n red: chalk.red,\n white: chalk.white,\n pink: (str: string) => chalk.rgb(...PINK)(str),\n orange: (str: string) => chalk.rgb(...ORANGE)(str),\n purple: (str: string) => chalk.rgb(...PURPLE)(str),\n}\n\ntype Symbol = '\u2713' | '\u26A0' | '\u00D7' | '\u25CF' | ' ' | '\u25CB'\ntype Color = 'blue' | 'green' | 'yellow' | 'red' | 'pink' | 'white' | 'orange' | 'purple'\ntype LogPrefix = { symbol: Symbol; fg?: Color; bg?: Color; indent?: number } | string\ntype SymbolRenderer<T extends Symbol> = { default: T; windows?: string; mac?: string }\n\ntype LogProps = {\n prefix: LogPrefix\n stderr?: boolean\n}\n\ntype PrintProps = {\n metadata: any\n prefix: string\n stderr?: boolean\n}\n\nconst checkmark: SymbolRenderer<'\u2713'> = {\n default: '\u2713',\n windows: '\u221A',\n mac: '\u2714',\n}\n\nconst cross: SymbolRenderer<'\u00D7'> = {\n default: '\u00D7',\n mac: '\u2716',\n}\n\nconst danger: SymbolRenderer<'\u26A0'> = { default: '\u26A0' }\nconst circle: SymbolRenderer<'\u25CB'> = { default: '\u25CB' }\nconst disc: SymbolRenderer<'\u25CF'> = { default: '\u25CF' }\nconst space: SymbolRenderer<' '> = { default: ' ' }\n\nconst renderers: Record<Symbol, SymbolRenderer<Symbol>> = {\n '\u2713': checkmark,\n '\u00D7': cross,\n '\u26A0': danger,\n '\u25CB': circle,\n '\u25CF': disc,\n ' ': space,\n}\n\nconst BOX_OPTIONS: boxen.Options = {\n padding: 1,\n margin: 1,\n borderStyle: 'round',\n borderColor: 'yellow',\n}\n\nexport type StreamType = 'out' | 'err'\n\nexport abstract class BaseLogger {\n protected opts: LoggerOptions\n\n public constructor(opts: Partial<LoggerOptions> = {}) {\n this.opts = { ...DEFAULT_OPTIONS, ...opts }\n }\n\n public log(message: string, props: Partial<LogProps> = {}): void {\n if (this.opts.json && !props.stderr) {\n return\n }\n\n const prefix = this._resolvePrefix(props.prefix)\n this.print(message, { ...props, prefix })\n }\n\n public json(data: any, opts: Partial<{ depth: number }> = { depth: Infinity }): void {\n if (this.opts.json) {\n this.print(JSON.stringify(data, undefined, 2))\n return\n }\n\n const { depth } = opts\n const msg = util.inspect(data, { colors: true, depth })\n this.log(msg)\n }\n\n public debug(message: string): void {\n if (!this.opts.verbose) {\n return\n }\n this.log(chalk.grey(message), { prefix: { symbol: '\u25CF', fg: 'blue' } })\n }\n\n public started(message: string): void {\n this.log(message, { prefix: { symbol: '\u25CB', fg: 'purple' } })\n }\n\n public success(message: string): void {\n this.log(message, { prefix: { symbol: '\u2713', fg: 'green' } })\n }\n\n public warn(message: string): void {\n this.log(message, { prefix: { symbol: '\u26A0', fg: 'yellow' } })\n }\n\n public error(message: string): void {\n this.log(message, { prefix: { symbol: '\u00D7', fg: 'red' }, stderr: true })\n }\n\n public box(message: string): void {\n const box = boxen(message, BOX_OPTIONS)\n this.log(box)\n }\n\n protected abstract print(message: string, props?: Partial<PrintProps>): void\n\n private _resolvePrefix(prefix: LogPrefix | undefined): string | undefined {\n if (!prefix) {\n return\n }\n\n if (_.isString(prefix)) {\n return prefix\n }\n\n const { symbol, fg, bg, indent } = prefix\n const renderedSymbol = this._renderSymbol(symbol)\n const fgcolor = fg ? FG_COLORS[fg] : NO_COLOR\n const bgcolor = bg ? BG_COLORS[bg] : NO_COLOR\n const indentStr = indent ? ' '.repeat(indent) : ''\n const symbolStr = fgcolor(bgcolor(renderedSymbol))\n return `${indentStr}${symbolStr}`\n }\n\n private _renderSymbol(symbol: Symbol): string {\n const renderer = renderers[symbol]\n if (process.platform === 'win32') {\n return renderer.windows || renderer.default\n } else if (process.platform === 'darwin') {\n return renderer.mac || renderer.default\n } else {\n return renderer.default\n }\n }\n\n protected render(message: string, streamType: StreamType = 'out'): void {\n // chunking the message ensures that the process won't exit before the message is fully written\n const stream = streamType === 'err' ? this.opts.errStream : this.opts.outStream\n for (const chunk of utils.string.chunkString(message, STDOUT_CHUNK_SIZE)) {\n stream.write(chunk)\n }\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAClB,mBAAkB;AAClB,oBAAc;AACd,kBAAiB;AACjB,YAAuB;AASvB,MAAM,oBAAoB;AAC1B,MAAM,kBAAiC;AAAA,EACrC,SAAS;AAAA,EACT,MAAM;AAAA,EACN,WAAW,QAAQ;AAAA,EACnB,WAAW,QAAQ;AACrB;AAGA,MAAM,WAAuB,CAAC,QAAgB;AAE9C,MAAM,OAAO,CAAC,KAAK,KAAK,GAAG;AAC3B,MAAM,SAAS,CAAC,KAAK,KAAK,CAAC;AAC3B,MAAM,SAAS,CAAC,KAAK,GAAG,GAAG;AAE3B,MAAM,YAAuC;AAAA,EAC3C,MAAM,aAAAA,QAAM;AAAA,EACZ,OAAO,aAAAA,QAAM;AAAA,EACb,QAAQ,aAAAA,QAAM;AAAA,EACd,KAAK,aAAAA,QAAM;AAAA,EACX,OAAO,aAAAA,QAAM;AAAA,EACb,MAAM,CAAC,QAAgB,aAAAA,QAAM,MAAM,GAAG,IAAI,EAAE,GAAG;AAAA,EAC/C,QAAQ,CAAC,QAAgB,aAAAA,QAAM,MAAM,GAAG,MAAM,EAAE,GAAG;AAAA,EACnD,QAAQ,CAAC,QAAgB,aAAAA,QAAM,MAAM,GAAG,MAAM,EAAE,GAAG;AACrD;AAEA,MAAM,YAAuC;AAAA,EAC3C,MAAM,aAAAA,QAAM;AAAA,EACZ,OAAO,aAAAA,QAAM;AAAA,EACb,QAAQ,aAAAA,QAAM;AAAA,EACd,KAAK,aAAAA,QAAM;AAAA,EACX,OAAO,aAAAA,QAAM;AAAA,EACb,MAAM,CAAC,QAAgB,aAAAA,QAAM,I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S,IAAI,OAAO,MAAM,IAAI;AAChD,UAAM,YAAY,QAAQ,QAAQ,cAAc,CAAC;AACjD,WAAO,GAAG,SAAS,GAAG,SAAS;AAAA,EACjC;AAAA,EAEQ,cAAc,QAAwB;AAC5C,UAAM,WAAW,UAAU,MAAM;AACjC,QAAI,QAAQ,aAAa,SAAS;AAChC,aAAO,SAAS,WAAW,SAAS;AAAA,IACtC,WAAW,QAAQ,aAAa,UAAU;AACxC,aAAO,SAAS,OAAO,SAAS;AAAA,IAClC,OAAO;AACL,aAAO,SAAS;AAAA,IAClB;AAAA,EACF;AAAA,EAEU,OAAO,SAAiB,aAAyB,OAAa;AAEtE,UAAM,SAAS,eAAe,QAAQ,KAAK,KAAK,YAAY,KAAK,KAAK;AACtE,eAAW,SAAS,MAAM,OAAO,YAAY,SAAS,iBAAiB,GAAG;AACxE,aAAO,MAAM,KAAK;AAAA,IACpB;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import boxen from 'boxen'\nimport chalk from 'chalk'\nimport _ from 'lodash'\nimport util from 'util'\nimport * as utils from '../utils'\n\nexport type LoggerOptions = {\n verbose: boolean\n json: boolean // prevents loggin anything else than json\n outStream: NodeJS.WriteStream\n errStream: NodeJS.WriteStream\n}\n\nconst STDOUT_CHUNK_SIZE = 100\nconst DEFAULT_OPTIONS: LoggerOptions = {\n verbose: false,\n json: false,\n outStream: process.stdout,\n errStream: process.stderr,\n}\n\ntype ChalkColor = (str: string) => string\nconst NO_COLOR: ChalkColor = (str: string) => str\n\nconst PINK = [255, 100, 255] as const\nconst ORANGE = [255, 165, 0] as const\nconst PURPLE = [128, 0, 128] as const\n\nconst BG_COLORS: Record<Color, ChalkColor> = {\n blue: chalk.bgBlueBright,\n green: chalk.bgGreenBright,\n yellow: chalk.bgYellowBright,\n red: chalk.bgRedBright,\n white: chalk.bgWhite,\n pink: (str: string) => chalk.bgRgb(...PINK)(str),\n orange: (str: string) => chalk.bgRgb(...ORANGE)(str),\n purple: (str: string) => chalk.bgRgb(...PURPLE)(str),\n}\n\nconst FG_COLORS: Record<Color, ChalkColor> = {\n blue: chalk.blueBright,\n green: chalk.green,\n yellow: chalk.yellowBright,\n red: chalk.red,\n white: chalk.white,\n pink: (str: string) => chalk.rgb(...PINK)(str),\n orange: (str: string) => chalk.rgb(...ORANGE)(str),\n purple: (str: string) => chalk.rgb(...PURPLE)(str),\n}\n\ntype Symbol = '\u2713' | '\u26A0' | '\u00D7' | '\u25CF' | ' ' | '\u25CB' | '\u2192'\ntype Color = 'blue' | 'green' | 'yellow' | 'red' | 'pink' | 'white' | 'orange' | 'purple'\ntype LogPrefix = { symbol: Symbol; fg?: Color; bg?: Color; indent?: number } | string\ntype SymbolRenderer<T extends Symbol> = { default: T; windows?: string; mac?: string }\n\ntype LogProps = {\n prefix: LogPrefix\n stderr?: boolean\n}\n\ntype PrintProps = {\n metadata: any\n prefix: string\n stderr?: boolean\n}\n\nconst checkmark: SymbolRenderer<'\u2713'> = {\n default: '\u2713',\n windows: '\u221A',\n mac: '\u2714',\n}\n\nconst cross: SymbolRenderer<'\u00D7'> = {\n default: '\u00D7',\n mac: '\u2716',\n}\n\nconst danger: SymbolRenderer<'\u26A0'> = { default: '\u26A0' }\nconst circle: SymbolRenderer<'\u25CB'> = { default: '\u25CB' }\nconst disc: SymbolRenderer<'\u25CF'> = { default: '\u25CF' }\nconst space: SymbolRenderer<' '> = { default: ' ' }\nconst arrow: SymbolRenderer<'\u2192'> = { default: '\u2192' }\n\nconst renderers: Record<Symbol, SymbolRenderer<Symbol>> = {\n '\u2713': checkmark,\n '\u00D7': cross,\n '\u26A0': danger,\n '\u25CB': circle,\n '\u25CF': disc,\n ' ': space,\n '\u2192': arrow,\n}\n\nconst BOX_OPTIONS: boxen.Options = {\n padding: 1,\n margin: 1,\n borderStyle: 'round',\n borderColor: 'yellow',\n}\n\nexport type StreamType = 'out' | 'err'\n\nexport abstract class BaseLogger {\n protected opts: LoggerOptions\n\n public constructor(opts: Partial<LoggerOptions> = {}) {\n this.opts = { ...DEFAULT_OPTIONS, ...opts }\n }\n\n public log(message: string, props: Partial<LogProps> = {}): void {\n if (this.opts.json && !props.stderr) {\n return\n }\n\n const prefix = this._resolvePrefix(props.prefix)\n this.print(message, { ...props, prefix })\n }\n\n public json(data: any, opts: Partial<{ depth: number }> = { depth: Infinity }): void {\n if (this.opts.json) {\n this.print(JSON.stringify(data, undefined, 2))\n return\n }\n\n const { depth } = opts\n const msg = util.inspect(data, { colors: true, depth })\n this.log(msg)\n }\n\n public debug(message: string): void {\n if (!this.opts.verbose) {\n return\n }\n this.log(chalk.grey(message), { prefix: { symbol: '\u25CF', fg: 'blue' } })\n }\n\n public started(message: string): void {\n this.log(message, { prefix: { symbol: '\u25CB', fg: 'purple' } })\n }\n\n public success(message: string): void {\n this.log(message, { prefix: { symbol: '\u2713', fg: 'green' } })\n }\n\n public warn(message: string): void {\n this.log(message, { prefix: { symbol: '\u26A0', fg: 'yellow' } })\n }\n\n public error(message: string): void {\n this.log(message, { prefix: { symbol: '\u00D7', fg: 'red' }, stderr: true })\n }\n\n public box(message: string): void {\n const box = boxen(message, BOX_OPTIONS)\n this.log(box)\n }\n\n protected abstract print(message: string, props?: Partial<PrintProps>): void\n\n private _resolvePrefix(prefix: LogPrefix | undefined): string | undefined {\n if (!prefix) {\n return\n }\n\n if (_.isString(prefix)) {\n return prefix\n }\n\n const { symbol, fg, bg, indent } = prefix\n const renderedSymbol = this._renderSymbol(symbol)\n const fgcolor = fg ? FG_COLORS[fg] : NO_COLOR\n const bgcolor = bg ? BG_COLORS[bg] : NO_COLOR\n const indentStr = indent ? ' '.repeat(indent) : ''\n const symbolStr = fgcolor(bgcolor(renderedSymbol))\n return `${indentStr}${symbolStr}`\n }\n\n private _renderSymbol(symbol: Symbol): string {\n const renderer = renderers[symbol]\n if (process.platform === 'win32') {\n return renderer.windows || renderer.default\n } else if (process.platform === 'darwin') {\n return renderer.mac || renderer.default\n } else {\n return renderer.default\n }\n }\n\n protected render(message: string, streamType: StreamType = 'out'): void {\n // chunking the message ensures that the process won't exit before the message is fully written\n const stream = streamType === 'err' ? this.opts.errStream : this.opts.outStream\n for (const chunk of utils.string.chunkString(message, STDOUT_CHUNK_SIZE)) {\n stream.write(chunk)\n }\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAClB,mBAAkB;AAClB,oBAAc;AACd,kBAAiB;AACjB,YAAuB;AASvB,MAAM,oBAAoB;AAC1B,MAAM,kBAAiC;AAAA,EACrC,SAAS;AAAA,EACT,MAAM;AAAA,EACN,WAAW,QAAQ;AAAA,EACnB,WAAW,QAAQ;AACrB;AAGA,MAAM,WAAuB,CAAC,QAAgB;AAE9C,MAAM,OAAO,CAAC,KAAK,KAAK,GAAG;AAC3B,MAAM,SAAS,CAAC,KAAK,KAAK,CAAC;AAC3B,MAAM,SAAS,CAAC,KAAK,GAAG,GAAG;AAE3B,MAAM,YAAuC;AAAA,EAC3C,MAAM,aAAAA,QAAM;AAAA,EACZ,OAAO,aAAAA,QAAM;AAAA,EACb,QAAQ,aAAAA,QAAM;AAAA,EACd,KAAK,aAAAA,QAAM;AAAA,EACX,OAAO,aAAAA,QAAM;AAAA,EACb,MAAM,CAAC,QAAgB,aAAAA,QAAM,MAAM,GAAG,IAAI,EAAE,GAAG;AAAA,EAC/C,QAAQ,CAAC,QAAgB,aAAAA,QAAM,MAAM,GAAG,MAAM,EAAE,GAAG;AAAA,EACnD,QAAQ,CAAC,QAAgB,aAAAA,QAAM,MAAM,GAAG,MAAM,EAAE,GAAG;AACrD;AAEA,MAAM,YAAuC;AAAA,EAC3C,MAAM,aAAAA,QAAM;AAAA,EACZ,OAAO,aAAAA,QAAM;AAAA,EACb,QAAQ,aAAAA,QAAM;AAAA,EACd,KAAK,aAAAA,QAAM;AAAA,EACX,OAAO,aAAAA,QAAM;AAAA,EACb,MAAM,CAAC,QAAgB,aAAAA,QAAM,IAAI,G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U,KAAK,UAAU,EAAE,IAAI;AACrC,UAAM,YAAY,SAAS,IAAI,OAAO,MAAM,IAAI;AAChD,UAAM,YAAY,QAAQ,QAAQ,cAAc,CAAC;AACjD,WAAO,GAAG,SAAS,GAAG,SAAS;AAAA,EACjC;AAAA,EAEQ,cAAc,QAAwB;AAC5C,UAAM,WAAW,UAAU,MAAM;AACjC,QAAI,QAAQ,aAAa,SAAS;AAChC,aAAO,SAAS,WAAW,SAAS;AAAA,IACtC,WAAW,QAAQ,aAAa,UAAU;AACxC,aAAO,SAAS,OAAO,SAAS;AAAA,IAClC,OAAO;AACL,aAAO,SAAS;AAAA,IAClB;AAAA,EACF;AAAA,EAEU,OAAO,SAAiB,aAAyB,OAAa;AAEtE,UAAM,SAAS,eAAe,QAAQ,KAAK,KAAK,YAAY,KAAK,KAAK;AACtE,eAAW,SAAS,MAAM,OAAO,YAAY,SAAS,iBAAiB,GAAG;AACxE,aAAO,MAAM,KAAK;AAAA,IACpB;AAAA,EACF;AACF;",
6
6
  "names": ["chalk", "util", "boxen", "_"]
7
7
  }
@@ -20,3 +20,4 @@ export * as template from './template-utils';
20
20
  export * as tunnel from './tunnel-utils';
21
21
  export * as types from './type-utils';
22
22
  export * as url from './url-utils';
23
+ export * as vrl from './vrl-utils';
@@ -49,7 +49,8 @@ __export(utils_exports, {
49
49
  template: () => template,
50
50
  tunnel: () => tunnel,
51
51
  types: () => types,
52
- url: () => url
52
+ url: () => url,
53
+ vrl: () => vrl
53
54
  });
54
55
  module.exports = __toCommonJS(utils_exports);
55
56
  var attributes = __toESM(require("./attribute-utils"));
@@ -74,6 +75,7 @@ var template = __toESM(require("./template-utils"));
74
75
  var tunnel = __toESM(require("./tunnel-utils"));
75
76
  var types = __toESM(require("./type-utils"));
76
77
  var url = __toESM(require("./url-utils"));
78
+ var vrl = __toESM(require("./vrl-utils"));
77
79
  // Annotate the CommonJS export names for ESM import in node:
78
80
  0 && (module.exports = {
79
81
  attributes,
@@ -97,6 +99,7 @@ var url = __toESM(require("./url-utils"));
97
99
  template,
98
100
  tunnel,
99
101
  types,
100
- url
102
+ url,
103
+ vrl
101
104
  });
102
105
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/utils/index.ts"],
4
- "sourcesContent": ["export * as attributes from './attribute-utils'\nexport * as cache from './cache-utils'\nexport * as casing from './case-utils'\nexport * as emitter from './event-emitter'\nexport * as esbuild from './esbuild-utils'\nexport * as filewatcher from './file-watcher'\nexport * as guards from './guard-utils'\nexport * as id from './id-utils'\nexport * as object from './object-utils'\nexport * as path from './path-utils'\nexport * as pkgJson from './pkgjson-utils'\nexport * as promises from './promise-utils'\nexport * as prompt from './prompt-utils'\nexport * as records from './record-utils'\nexport * as require from './require-utils'\nexport * as schema from './schema-utils'\nexport * as semver from './semver-utils'\nexport * as string from './string-utils'\nexport * as template from './template-utils'\nexport * as tunnel from './tunnel-utils'\nexport * as types from './type-utils'\nexport * as url from './url-utils'\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAA4B;AAC5B,YAAuB;AACvB,aAAwB;AACxB,cAAyB;AACzB,cAAyB;AACzB,kBAA6B;AAC7B,aAAwB;AACxB,SAAoB;AACpB,aAAwB;AACxB,WAAsB;AACtB,cAAyB;AACzB,eAA0B;AAC1B,aAAwB;AACxB,cAAyB;AACzB,IAAAA,WAAyB;AACzB,aAAwB;AACxB,aAAwB;AACxB,aAAwB;AACxB,eAA0B;AAC1B,aAAwB;AACxB,YAAuB;AACvB,UAAqB;",
4
+ "sourcesContent": ["export * as attributes from './attribute-utils'\nexport * as cache from './cache-utils'\nexport * as casing from './case-utils'\nexport * as emitter from './event-emitter'\nexport * as esbuild from './esbuild-utils'\nexport * as filewatcher from './file-watcher'\nexport * as guards from './guard-utils'\nexport * as id from './id-utils'\nexport * as object from './object-utils'\nexport * as path from './path-utils'\nexport * as pkgJson from './pkgjson-utils'\nexport * as promises from './promise-utils'\nexport * as prompt from './prompt-utils'\nexport * as records from './record-utils'\nexport * as require from './require-utils'\nexport * as schema from './schema-utils'\nexport * as semver from './semver-utils'\nexport * as string from './string-utils'\nexport * as template from './template-utils'\nexport * as tunnel from './tunnel-utils'\nexport * as types from './type-utils'\nexport * as url from './url-utils'\nexport * as vrl from './vrl-utils'\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAA4B;AAC5B,YAAuB;AACvB,aAAwB;AACxB,cAAyB;AACzB,cAAyB;AACzB,kBAA6B;AAC7B,aAAwB;AACxB,SAAoB;AACpB,aAAwB;AACxB,WAAsB;AACtB,cAAyB;AACzB,eAA0B;AAC1B,aAAwB;AACxB,cAAyB;AACzB,IAAAA,WAAyB;AACzB,aAAwB;AACxB,aAAwB;AACxB,aAAwB;AACxB,eAA0B;AAC1B,aAAwB;AACxB,YAAuB;AACvB,UAAqB;AACrB,UAAqB;",
6
6
  "names": ["require"]
7
7
  }
@@ -0,0 +1,4 @@
1
+ export declare const getStringResult: ({ code, data }: {
2
+ code: string;
3
+ data: Record<string, any>;
4
+ }) => string;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var vrl_utils_exports = {};
30
+ __export(vrl_utils_exports, {
31
+ getStringResult: () => getStringResult
32
+ });
33
+ module.exports = __toCommonJS(vrl_utils_exports);
34
+ var verel = __toESM(require("@bpinternal/verel"));
35
+ var errors = __toESM(require("../errors"));
36
+ const getStringResult = ({ code, data }) => {
37
+ const { result } = verel.execute(code, data);
38
+ if (typeof result !== "string") {
39
+ throw new errors.BotpressCLIError("VRL returned an invalid string result");
40
+ }
41
+ return result;
42
+ };
43
+ // Annotate the CommonJS export names for ESM import in node:
44
+ 0 && (module.exports = {
45
+ getStringResult
46
+ });
47
+ //# sourceMappingURL=vrl-utils.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/utils/vrl-utils.ts"],
4
+ "sourcesContent": ["import * as verel from '@bpinternal/verel'\nimport * as errors from '../errors'\n\nexport const getStringResult = ({ code, data }: { code: string; data: Record<string, any> }) => {\n const { result } = verel.execute(code, data)\n\n if (typeof result !== 'string') {\n throw new errors.BotpressCLIError('VRL returned an invalid string result')\n }\n\n return result\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAAuB;AACvB,aAAwB;AAEjB,MAAM,kBAAkB,CAAC,EAAE,MAAM,KAAK,MAAmD;AAC9F,QAAM,EAAE,OAAO,IAAI,MAAM,QAAQ,MAAM,IAAI;AAE3C,MAAI,OAAO,WAAW,UAAU;AAC9B,UAAM,IAAI,OAAO,iBAAiB,uCAAuC;AAAA,EAC3E;AAEA,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -6,12 +6,12 @@ export declare const configSchema: import("@botpress/sdk").ZodUnion<[import("@bo
6
6
  code: import("@botpress/sdk").ZodString;
7
7
  env: import("@botpress/sdk").ZodOptional<import("@botpress/sdk").ZodRecord<import("@botpress/sdk").ZodString, import("@botpress/sdk").ZodString>>;
8
8
  }, "strip", {
9
- type: "code";
10
9
  code: string;
10
+ type: "code";
11
11
  env?: Record<string, string> | undefined;
12
12
  }, {
13
- type: "code";
14
13
  code: string;
14
+ type: "code";
15
15
  env?: Record<string, string> | undefined;
16
16
  }>, import("@botpress/sdk").ZodObject<{
17
17
  type: import("@botpress/sdk").ZodLiteral<"file">;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botpress/cli",
3
- "version": "4.20.3",
3
+ "version": "4.21.0",
4
4
  "description": "Botpress CLI",
5
5
  "scripts": {
6
6
  "build": "pnpm run build:types && pnpm run bundle && pnpm run template:gen",
@@ -30,6 +30,7 @@
30
30
  "@botpress/sdk": "4.17.3",
31
31
  "@bpinternal/const": "^0.1.0",
32
32
  "@bpinternal/tunnel": "^0.1.1",
33
+ "@bpinternal/verel": "^0.2.0",
33
34
  "@bpinternal/yargs-extra": "^0.0.3",
34
35
  "@parcel/watcher": "^2.1.0",
35
36
  "@stoplight/spectral-core": "^1.19.1",