@mochabug/adaptkit 0.1.0-alpha.1

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.
package/bin/index.js ADDED
@@ -0,0 +1,1363 @@
1
+ #!/usr/bin/env node
2
+ import { ChannelCredentials } from '@grpc/grpc-js';
3
+ import { GrpcTransport } from '@protobuf-ts/grpc-transport';
4
+ import chalk from 'chalk';
5
+ import { execSync } from 'child_process';
6
+ import { program } from 'commander';
7
+ import figlet from 'figlet';
8
+ import fs from 'fs';
9
+ import { glob } from 'glob';
10
+ import inquirer from 'inquirer';
11
+ import { mkdirp } from 'mkdirp';
12
+ import path from 'path';
13
+ import sharp from 'sharp';
14
+ import { ServiceType, stackIntercept } from '@protobuf-ts/runtime-rpc';
15
+ import { MessageType, reflectionMergePartial, UnknownFieldHandler, WireType, MESSAGE_TYPE } from '@protobuf-ts/runtime';
16
+
17
+ /******************************************************************************
18
+ Copyright (c) Microsoft Corporation.
19
+
20
+ Permission to use, copy, modify, and/or distribute this software for any
21
+ purpose with or without fee is hereby granted.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
24
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
25
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
26
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
27
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
28
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
29
+ PERFORMANCE OF THIS SOFTWARE.
30
+ ***************************************************************************** */
31
+ /* global Reflect, Promise */
32
+
33
+
34
+ function __awaiter(thisArg, _arguments, P, generator) {
35
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
36
+ return new (P || (P = Promise))(function (resolve, reject) {
37
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
38
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
39
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
40
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
41
+ });
42
+ }
43
+
44
+ var actionTemplate = "import { ExecutorApi } from '@mochabug/adapt-plugin-toolkit';\n\n/**\n * Represents an action executor for a vertex in a flow graph.\n * This task is responsible for executing the main logic of the vertex\n * during the runtime of the flow graph, processing incoming requests\n * and generating appropriate responses based on the environment and context.\n * The internal entrypoint is called by the runtime and is never exposed to the outside world.\n * See the executor API specifications for details on how to interact with the flow graph.\n *\n * POST: /start\n * - When the vertex starts executing this endpoint is called with the \"application/json\".\n * - Contains the instance's Bearer token in the Authorization Header\n * POST: /streams/<name>\n * - If a stream has been started by the vertex, stream responses on this endpoint as \"application/json\"\n * - Contains the instance's Bearer token in the Authorization Header\n * POST: /procedures/<name>\n * - If a procedure has been executed by the vertex, procedure response on this endpoint as \"application/json\"\n * - Contains the instance's Bearer token in the Authorization Header\n * @property {Function} fetch - A function that takes a Request, ExecutorEnvironment, and ExecutionContext\n * and returns a Promise resolving to a Response.\n */\nconst internal = {\n async fetch(\n req: Request,\n env: ExecutorEnvironment,\n ctx: ExecutionContext\n ): Promise<Response> {\n const api = new ExecutorApi(env, req.headers.get(\"Authorization\"));\n\n // Do your thing here\n\n // Mark the execution as completed like this\n api.complete(\"output\", []);\n\n return new Response();\n },\n};\n\nexport { internal };";
45
+
46
+ var baseSchema = "// Copyright 2023, mochabug AB\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\npackage v1\n\nimport (\n\t\"list\"\n\t\"strings\"\n)\n\n// PluginConfig represents the configuration for an entire plugin\n#PluginConfig: {\n\t// 'complete' indicates whether the vertex has been fully configured\n\tcomplete: bool\n\t// 'signals' are the global signals that the vertex relies on\n\tsignals?: #InputSignalsArray\n}\n\n// VertexConfig represents a vertex's configuration\n#VertexConfig: {\n\t// 'complete' indicates whether the vertex has been fully configured. Defaults to 'false'\n\tcomplete: bool\n\t// 'receivers' are the vertex's input points. Must have at least 1 and at most 10\n\treceivers: [#Receiver, ...#Receiver] & list.MaxItems(10) & list.MinItems(1)\n\t// 'transmitters' are the vertex's output points. Max limit: 10\n\ttransmitters: [...#Transmitter] & list.MaxItems(10)\n\t// 'procedures' are the exchanges that are initiated on a transmitter and responded to on a receiver\n\tprocedures?: #ExchangeArray\n\t// 'streams' are the exchanges that commence by making a request on one of the receivers\n\tstreams?: #ExchangeArray\n\t// 'signals' are the global signals that the vertex relies on\n\tsignals?: #InputSignalsArray\n}\n\n// Name serves as the identifier for an object. It should conform to the ECMA regex and be under 50 characters\n#Name: =~\"^[_$a-z][_$a-z0-9]*$\" & strings.MaxRunes(50)\n\n// Description is a field providing optional information about an object's purpose. Max length: 250 characters\n#Description: string & strings.MaxRunes(250)\n\n// SignalArray is an array of SignalDescriptors. Max length: 512\n#SignalArray: [...#SignalDescriptor] & list.MaxItems(512)\n\n// InputSignalsArray is an array of global signals. Max length: 512\n#InputSignalsArray: [...#InputSignalDescriptor] & list.MaxItems(512)\n\n// ExchangeArray is an array of exchanges. Max length: 10\n#ExchangeArray: [...#Exchange] & list.MaxItems(10)\n\n// Receiver represents a vertex's input point\n#Receiver: {\n\tname: #Name\n\tdescription?: #Description\n\tsignals?: #InputSignalsArray\n}\n\n// Transmitter represents a vertex's output point\n#Transmitter: {\n\tname: #Name\n\tdescription?: #Description\n\tsignals?: #SignalArray\n\t// 'failure' is a flag that indicates whether the transmitter is emitting failure signals\n\tfailure: bool\n}\n\n// Transceiver is an entity that can both emit and receive signals\n#Transceiver: {\n\tname: #Name\n\tdescription?: #Description\n\tsignals?: #SignalArray\n}\n\n// Exchange represents an interaction between emitters and receivers\n#Exchange: {\n\tname: #Name\n\tdescription?: #Description\n\t// 'emitters' are the inputs to the exchange\n\temitters: [#Transceiver, ...#Transceiver] & list.MinItems(1) & list.MaxItems(10)\n\t// 'receivers' are the outputs from the exchange\n\treceivers?: [...#Transceiver] & list.MaxItems(10)\n}\n\n// SignalDescriptor represents a signal, excluding the signal data itself\n#SignalDescriptor: {\n\tname: #Name\n\tdescription?: #Description\n\t// 'schema' is the CUE schema that defines the signal\n\tschema: string\n\t// 'optional' is a flag indicating whether the signal is not mandatory\n\toptional?: bool\n}\n\n// InputSignalDescriptor is a SignalDescriptor that comes with a binding\n#InputSignalDescriptor: {\n\t// 'definition' is the SignalDescriptor of the input signal\n\tdefinition: #SignalDescriptor\n\t// 'binding' is the signal to which the input signal is bound\n\tbinding?: string\n}\n";
47
+
48
+ var browserTemplate = "import { ExecutorApi } from '@mochabug/adapt-plugin-toolkit';\n\n/**\n * Represents a browser executor for a vertex in a flow graph.\n * All requests coming from an external source (i.e. browsers) are\n * getting routed onto this endpoint. See the executor API specification\n * for details and best practices regarding authorization and security.\n * See the executor API specification on how to interact with the flow graph\n *\n * @property {Function} fetch - A function that takes a Request, ExecutorEnvironment, and ExecutionContext\n * and returns a Promise resolving to a Response.\n */\nconst external = {\n async fetch(\n req: Request,\n env: ExecutorEnvironment,\n ctx: ExecutionContext\n ): Promise<Response> {\n const api = new ExecutorApi(env, req.headers.get(\"Authorization\"));\n\n // Do your thing here\n\n // Mark the execution as completed like this\n api.complete(\"output\", []);\n\n return new Response(\"Hello World!\");\n },\n};\n\n/**\n * Represents a executor for a vertex in a flow graph.\n * The internal entrypoint is called by the Executor of the flow graph.\n * See the executor API specifications for details on how to interact with the flow graph\n * and requests coming from the browser.\n *\n * POST: /start\n * - When the vertex starts executing this endpoint is called with the \"application/json\".\n * - Contains the instance's Bearer token in the Authorization Header\n * POST: /streams/<name>\n * - If a stream has been started by the vertex, stream responses on this endpoint as \"application/json\"\n * - Contains the instance's Bearer token in the Authorization Header\n * POST: /procedures/<name>\n * - If a procedure has been executed by the vertex, procedure response on this endpoint as \"application/json\"\n * - Contains the instance's Bearer token in the Authorization Header\n * @property {Function} fetch - A function that takes a Request, ExecutorEnvironment, and ExecutionContext\n * and returns a Promise resolving to a Response.\n */\nconst internal = {\n async fetch(\n req: Request,\n env: ExecutorEnvironment,\n ctx: ExecutionContext\n ): Promise<Response> {\n const api = new ExecutorApi(env, req.headers.get(\"Authorization\"));\n\n // Do your thing here\n\n return new Response();\n },\n};\n\nexport { external, internal };";
49
+
50
+ var configTemplate = "import { ConfiguratorApi } from '@mochabug/adapt-plugin-toolkit';\n\n/**\n * Represents a configurator for a vertex in a flow graph.\n * This configurator is responsible for configuring the vertex\n * based on the user-provided configuration and environment.\n * The entrypoint is always external for a configuration since it's the \n * backend of a browser app.\n *\n * @property {Function} fetch - A function that takes a Request, ConfiguratorEnvironment, and ExecutionContext\n * and returns a Promise resolving to a Response.\n */\nconst external = {\n async fetch(\n req: Request,\n env: ConfiguratorEnvironment,\n ctx: ExecutionContext\n ): Promise<Response> {\n return new Response(\"Hello World!\");\n },\n};\n\n/**\n * The internal endpoint of a configurator fires events from the platform\n * during configuration.\n * TODO: this is a work in progress\n */\nconst internal = {\n async fetch(\n req: Request,\n env: ConfiguratorEnvironment,\n ctx: ExecutionContext\n ): Promise<Response> {\n const api = new ConfiguratorApi(env, req.headers.get(\"Authorization\"));\n return new Response();\n },\n};\n\nexport { external, internal };\n";
51
+
52
+ var gitignoreTemplate = "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n.pnpm-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nreport.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# Snowpack dependency directory (https://snowpack.dev/)\nweb_modules/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional stylelint cache\n.stylelintcache\n\n# Microbundle cache\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variable files\n.env\n.env.development.local\n.env.test.local\n.env.production.local\n.env.local\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n.parcel-cache\n\n# Next.js build output\n.next\nout\n\n# Nuxt.js build / generate output\n.nuxt\ndist\nbuild\n\n# Gatsby files\n.cache/\n# Comment in the public line in if your project uses Gatsby and not Next.js\n# https://nextjs.org/blog/next-9-1#public-directory-support\n# public\n\n# vuepress build output\n.vuepress/dist\n\n# vuepress v2.x temp and cache directory\n.temp\n.cache\n\n# Stores VSCode versions used for testing VSCode extensions\n.vscode-test\n\n# yarn v2\n.yarn/cache\n.yarn/unplugged\n.yarn/build-state.yml\n.yarn/install-state.gz\n.pnp.*";
53
+
54
+ var jestTemplate = "import type { Config } from \"@jest/types\"\n\nconst config: Config.InitialOptions = {\n preset: \"ts-jest\",\n testEnvironment: \"node\",\n verbose: true,\n automock: true,\n}\nexport default config";
55
+
56
+ var licenseTemplate = "## ISC License\n\nCopyright (c) [year] [fullname]\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.";
57
+
58
+ var pluginSchema = "package v1\n\n#PluginConfig\n\n// Create a generous amount of comments and details in this schema";
59
+
60
+ var readmeTemplate = "# 🐞 Mochabug Adapt's Magnificent Plugin 🐞\n\n[![Version](https://img.shields.io/badge/version-PLUGIN_VERSION-blue)](PLUGIN_REPOSITORY_URL)\n[![License: ISC](https://img.shields.io/badge/License-ISC-yellow.svg)](https://opensource.org/licenses/ISC)\n\n## 📝 Description\n\nWelcome to the Magnificent Plugin for Mochabug Adapt! Developed by a talented third-party developer, this plugin promises to bring extra flavor to your Mochabug Adapt cloud platform experience. PLUGIN_DESCRIPTION\n\nThis plugin consists of one or more vertices. Each vertex is made up of an Executor and may optionally include a Configurator to help you tailor its behavior.\n\n## 📚 Table of Contents\n\n- [🐞 Mochabug Adapt's Magnificent Plugin 🐞](#-mochabug-adapts-magnificent-plugin-)\n - [📝 Description](#-description)\n - [📚 Table of Contents](#-table-of-contents)\n - [🚀 Getting Started](#-getting-started)\n - [🎯 Usage](#-usage)\n - [⚙️ Configuration](#️-configuration)\n - [📖 Documentation](#-documentation)\n - [🤝 Contributing](#-contributing)\n - [📜 License](#-license)\n - [👤 Author](#-author)\n\n## 🚀 Getting Started\n\nTo begin using Mochabug Adapt's Magnificent Plugin, simply start incorporating its vertices into your workflows within the Mochabug Adapt platform. No installation is required.\n\n## 🎯 Usage\n\nYou can start using the vertices by incorporating them into your workflows on the Mochabug Adapt platform. Each vertex will delight you with a specific task, and the usage will vary depending on your requirements. Consult the plugin documentation for a comprehensive guide on each vertex's usage.\n\n## ⚙️ Configuration\n\nEach vertex in the plugin may have a Configurator, which allows you to tailor the vertex's behavior to your liking. Configuration options may include settings for the Executor, input/output data formats, and other essential options.\n\n## 📖 Documentation\n\nFor more insights into the plugin, its vertices, and their features, visit the [homepage](PLUGIN_HOMEPAGE) and the [repository](PLUGIN_REPOSITORY_URL).\n\n## 🤝 Contributing\n\nReady to make the Magnificent Plugin for Mochabug Adapt even more magical? Contributions are welcome! Check the [repository](PLUGIN_REPOSITORY_URL) for open issues and guidelines on how to contribute.\n\n## 📜 License\n\nThis plugin is licensed under the [ISC License](https://opensource.org/licenses/ISC).\n\n## 👤 Author\n\nPLUGIN_AUTHOR\n";
61
+
62
+ var rollupTemplate = "import typescript from '@rollup/plugin-typescript';\nimport { nodeResolve } from '@rollup/plugin-node-resolve';\nimport terser from '@rollup/plugin-terser';\nimport commonjs from '@rollup/plugin-commonjs';\n\nexport default [\n {\n input: 'src/executors.ts',\n output: {\n file: 'dist/executors.js',\n format: 'esm'\n },\n plugins: [typescript(), nodeResolve(), commonjs(), terser()]\n },\n {\n input: 'src/configurators.ts',\n output: {\n file: 'dist/configurators.js',\n format: 'esm'\n },\n plugins: [typescript(), nodeResolve(), commonjs(), terser()]\n }\n];";
63
+
64
+ var triggerTemplate = "import { ExecutorApi } from '@mochabug/adapt-plugin-toolkit';\n\n/**\n * Represents a trigger executor for a vertex in a flow graph.\n * Depending on what type of trigger has been configured, the Request that\n * is routed here is either a Cron trigger or from an external soruce.\n * It's upp to the author to handle the case the trigger was configured for.\n * See the executor API specification on how to interact with the flow graph and best\n * practices for security.\n *\n * For a CRON trigger:\n * POST: /\n * Authroization Bearer <token>\n * <no-content>\n *\n * For a EXTERNAL trigger:\n * <Contains no bearer token>\n * <Defined by the external endpoint>\n *\n * REMARK: for an external trigger the external endpoint is unprotected. It's up to the\n * plugin to make sure that the request is handled in a safe way. See the executor API documentation\n * for examples\n *\n * @property {Function} fetch - A function that takes a Request, ExecutorEnvironment, and ExecutionContext\n * and returns a Promise resolving to a Response.\n */\nconst trigger = {\n async fetch(\n req: Request,\n env: ExecutorEnvironment,\n ctx: ExecutionContext\n ): Promise<Response> {\n const api = new ExecutorApi(env, req.headers.get(\"Authorization\"));\n\n // Do your thing here\n\n // Mark the execution as complete. This will trigger downstream tasks\n api.complete(\"output\", []);\n\n return new Response(\"Hello World!\");\n },\n};\n\n/**\n * Represents a executor for a vertex in a flow graph.\n * The internal entrypoint is called by the Executor of the flow graph.\n * See the executor API specifications for details on how to interact with the flow graph\n * and requests coming from the trigger endpoint.\n *\n * POST: /start\n * - When the vertex starts executing this endpoint is called with the \"application/json\".\n * - Contains the instance's Bearer token in the Authorization Header\n * POST: /streams/<name>\n * - If a stream has been started by the vertex, stream responses on this endpoint as \"application/json\"\n * - Contains the instance's Bearer token in the Authorization Header\n * POST: /procedures/<name>\n * - If a procedure has been executed by the vertex, procedure response on this endpoint as \"application/json\"\n * - Contains the instance's Bearer token in the Authorization Header\n * @property {Function} fetch - A function that takes a Request, ExecutorEnvironment, and ExecutionContext\n * and returns a Promise resolving to a Response.\n */\nconst internal = {\n async fetch(\n req: Request,\n env: ExecutorEnvironment,\n ctx: ExecutionContext\n ): Promise<Response> {\n const api = new ExecutorApi(env, req.headers.get(\"Authorization\"));\n\n // Do your thing here\n\n return new Response();\n },\n};\n\nexport { trigger, internal };";
65
+
66
+ var tsconfig = "{\n \"exclude\": [\n \"**/*.test.*\",\n \"**/__mocks__/*\",\n \"**/__tests__/*\"\n ],\n \"compilerOptions\": {\n \"rootDir\": \"src\",\n \"target\": \"es2021\",\n \"lib\": [\n \"es2021\"\n ],\n \"jsx\": \"react\",\n \"module\": \"es2022\",\n \"moduleResolution\": \"node\",\n \"types\": [\n \"@mochabug/adapt-plugin-typings\",\n \"jest\"\n ],\n \"resolveJsonModule\": true,\n \"allowJs\": true,\n \"checkJs\": false,\n \"noEmit\": true,\n \"isolatedModules\": true,\n \"allowSyntheticDefaultImports\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"strict\": true,\n \"skipLibCheck\": true\n }\n}";
67
+
68
+ var vertexSchema = "package v1\n\n#VertexConfig\n\n// Create a generous amount of comments and details in this schema";
69
+
70
+ // @generated by protobuf-ts 2.9.0
71
+ // @generated from protobuf file "adapt/apis/plugins/v1/plugins.proto" (package "adapt.apis.plugins.v1", syntax proto3)
72
+ // tslint:disable
73
+ //
74
+ // Copyright 2023, mochabug AB
75
+ //
76
+ // Licensed under the Apache License, Version 2.0 (the "License");
77
+ // you may not use this file except in compliance with the License.
78
+ // You may obtain a copy of the License at
79
+ //
80
+ // http://www.apache.org/licenses/LICENSE-2.0
81
+ //
82
+ // Unless required by applicable law or agreed to in writing, software
83
+ // distributed under the License is distributed on an "AS IS" BASIS,
84
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
85
+ // See the License for the specific language governing permissions and
86
+ // limitations under the License.
87
+ //
88
+ /**
89
+ * GrantType represents the supported OAuth2 grant types.
90
+ *
91
+ * @generated from protobuf enum adapt.apis.plugins.v1.OAuth2Service.GrantType
92
+ */
93
+ var OAuth2Service_GrantType;
94
+ (function (OAuth2Service_GrantType) {
95
+ /**
96
+ * GRANT_TYPE_UNSPECIFIED indicates an unspecified or invalid grant type.
97
+ *
98
+ * @generated from protobuf enum value: GRANT_TYPE_UNSPECIFIED = 0;
99
+ */
100
+ OAuth2Service_GrantType[OAuth2Service_GrantType["UNSPECIFIED"] = 0] = "UNSPECIFIED";
101
+ /**
102
+ * GRANT_TYPE_CODE represents the authorization code grant type.
103
+ * Access tokens are issued on a per-user basis.
104
+ *
105
+ * @generated from protobuf enum value: GRANT_TYPE_CODE = 1;
106
+ */
107
+ OAuth2Service_GrantType[OAuth2Service_GrantType["CODE"] = 1] = "CODE";
108
+ /**
109
+ * GRANT_TYPE_CLIENT_CREDENTIALS represents the client credentials grant
110
+ * type. Access tokens are issued globally for the plugin.
111
+ *
112
+ * @generated from protobuf enum value: GRANT_TYPE_CLIENT_CREDENTIALS = 2;
113
+ */
114
+ OAuth2Service_GrantType[OAuth2Service_GrantType["CLIENT_CREDENTIALS"] = 2] = "CLIENT_CREDENTIALS";
115
+ })(OAuth2Service_GrantType || (OAuth2Service_GrantType = {}));
116
+ /**
117
+ * VertexType represents the type of a vertex.
118
+ *
119
+ * @generated from protobuf enum adapt.apis.plugins.v1.Vertex.VertexType
120
+ */
121
+ var Vertex_VertexType;
122
+ (function (Vertex_VertexType) {
123
+ /**
124
+ * Unspecified type (default value, should not be used).
125
+ *
126
+ * @generated from protobuf enum value: VERTEX_TYPE_UNSPECIFIED = 0;
127
+ */
128
+ Vertex_VertexType[Vertex_VertexType["UNSPECIFIED"] = 0] = "UNSPECIFIED";
129
+ /**
130
+ * Action type, available in all contexts and not exposed to the outside
131
+ * world. This type has a lower security risk.
132
+ *
133
+ * @generated from protobuf enum value: VERTEX_TYPE_ACTION = 1;
134
+ */
135
+ Vertex_VertexType[Vertex_VertexType["ACTION"] = 1] = "ACTION";
136
+ /**
137
+ * Browser type, available only in a browser context.
138
+ * The configuration always runs inside a browser context.
139
+ * Security implications: be cautious about potentially sensitive data
140
+ * exposure.
141
+ *
142
+ * @generated from protobuf enum value: VERTEX_TYPE_BROWSER = 2;
143
+ */
144
+ Vertex_VertexType[Vertex_VertexType["BROWSER"] = 2] = "BROWSER";
145
+ /**
146
+ * CronTrigger type, available only in a trigger context.
147
+ * Triggered at specific intervals.
148
+ *
149
+ * @generated from protobuf enum value: VERTEX_TYPE_CRON_TRIGGER = 3;
150
+ */
151
+ Vertex_VertexType[Vertex_VertexType["CRON_TRIGGER"] = 3] = "CRON_TRIGGER";
152
+ /**
153
+ * ExternalTrigger type, available only in a trigger context.
154
+ * Accessible via a publicly routable address.
155
+ * Security implications: be cautious about exposing sensitive data or
156
+ * functionality.
157
+ *
158
+ * @generated from protobuf enum value: VERTEX_TYPE_EXTERNAL_TRIGGER = 4;
159
+ */
160
+ Vertex_VertexType[Vertex_VertexType["EXTERNAL_TRIGGER"] = 4] = "EXTERNAL_TRIGGER";
161
+ })(Vertex_VertexType || (Vertex_VertexType = {}));
162
+ // @generated message type with reflection information, may provide speed optimized methods
163
+ class UploadPluginRequest$Type extends MessageType {
164
+ constructor() {
165
+ super("adapt.apis.plugins.v1.UploadPluginRequest", [
166
+ { no: 1, name: "manifest", kind: "message", oneof: "data", T: () => Manifest },
167
+ { no: 2, name: "file", kind: "message", oneof: "data", T: () => File }
168
+ ]);
169
+ }
170
+ create(value) {
171
+ const message = { data: { oneofKind: undefined } };
172
+ globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
173
+ if (value !== undefined)
174
+ reflectionMergePartial(this, message, value);
175
+ return message;
176
+ }
177
+ internalBinaryRead(reader, length, options, target) {
178
+ let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
179
+ while (reader.pos < end) {
180
+ let [fieldNo, wireType] = reader.tag();
181
+ switch (fieldNo) {
182
+ case /* adapt.apis.plugins.v1.Manifest manifest */ 1:
183
+ message.data = {
184
+ oneofKind: "manifest",
185
+ manifest: Manifest.internalBinaryRead(reader, reader.uint32(), options, message.data.manifest)
186
+ };
187
+ break;
188
+ case /* adapt.apis.plugins.v1.File file */ 2:
189
+ message.data = {
190
+ oneofKind: "file",
191
+ file: File.internalBinaryRead(reader, reader.uint32(), options, message.data.file)
192
+ };
193
+ break;
194
+ default:
195
+ let u = options.readUnknownField;
196
+ if (u === "throw")
197
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
198
+ let d = reader.skip(wireType);
199
+ if (u !== false)
200
+ (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
201
+ }
202
+ }
203
+ return message;
204
+ }
205
+ internalBinaryWrite(message, writer, options) {
206
+ /* adapt.apis.plugins.v1.Manifest manifest = 1; */
207
+ if (message.data.oneofKind === "manifest")
208
+ Manifest.internalBinaryWrite(message.data.manifest, writer.tag(1, WireType.LengthDelimited).fork(), options).join();
209
+ /* adapt.apis.plugins.v1.File file = 2; */
210
+ if (message.data.oneofKind === "file")
211
+ File.internalBinaryWrite(message.data.file, writer.tag(2, WireType.LengthDelimited).fork(), options).join();
212
+ let u = options.writeUnknownFields;
213
+ if (u !== false)
214
+ (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
215
+ return writer;
216
+ }
217
+ }
218
+ /**
219
+ * @generated MessageType for protobuf message adapt.apis.plugins.v1.UploadPluginRequest
220
+ */
221
+ const UploadPluginRequest = new UploadPluginRequest$Type();
222
+ // @generated message type with reflection information, may provide speed optimized methods
223
+ class UploadPluginResponse$Type extends MessageType {
224
+ constructor() {
225
+ super("adapt.apis.plugins.v1.UploadPluginResponse", []);
226
+ }
227
+ create(value) {
228
+ const message = {};
229
+ globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
230
+ if (value !== undefined)
231
+ reflectionMergePartial(this, message, value);
232
+ return message;
233
+ }
234
+ internalBinaryRead(reader, length, options, target) {
235
+ return target !== null && target !== void 0 ? target : this.create();
236
+ }
237
+ internalBinaryWrite(message, writer, options) {
238
+ let u = options.writeUnknownFields;
239
+ if (u !== false)
240
+ (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
241
+ return writer;
242
+ }
243
+ }
244
+ /**
245
+ * @generated MessageType for protobuf message adapt.apis.plugins.v1.UploadPluginResponse
246
+ */
247
+ const UploadPluginResponse = new UploadPluginResponse$Type();
248
+ // @generated message type with reflection information, may provide speed optimized methods
249
+ class File$Type extends MessageType {
250
+ constructor() {
251
+ super("adapt.apis.plugins.v1.File", [
252
+ { no: 1, name: "path", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
253
+ { no: 2, name: "data", kind: "scalar", T: 12 /*ScalarType.BYTES*/ }
254
+ ]);
255
+ }
256
+ create(value) {
257
+ const message = { path: "", data: new Uint8Array(0) };
258
+ globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
259
+ if (value !== undefined)
260
+ reflectionMergePartial(this, message, value);
261
+ return message;
262
+ }
263
+ internalBinaryRead(reader, length, options, target) {
264
+ let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
265
+ while (reader.pos < end) {
266
+ let [fieldNo, wireType] = reader.tag();
267
+ switch (fieldNo) {
268
+ case /* string path */ 1:
269
+ message.path = reader.string();
270
+ break;
271
+ case /* bytes data */ 2:
272
+ message.data = reader.bytes();
273
+ break;
274
+ default:
275
+ let u = options.readUnknownField;
276
+ if (u === "throw")
277
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
278
+ let d = reader.skip(wireType);
279
+ if (u !== false)
280
+ (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
281
+ }
282
+ }
283
+ return message;
284
+ }
285
+ internalBinaryWrite(message, writer, options) {
286
+ /* string path = 1; */
287
+ if (message.path !== "")
288
+ writer.tag(1, WireType.LengthDelimited).string(message.path);
289
+ /* bytes data = 2; */
290
+ if (message.data.length)
291
+ writer.tag(2, WireType.LengthDelimited).bytes(message.data);
292
+ let u = options.writeUnknownFields;
293
+ if (u !== false)
294
+ (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
295
+ return writer;
296
+ }
297
+ }
298
+ /**
299
+ * @generated MessageType for protobuf message adapt.apis.plugins.v1.File
300
+ */
301
+ const File = new File$Type();
302
+ // @generated message type with reflection information, may provide speed optimized methods
303
+ class Manifest$Type extends MessageType {
304
+ constructor() {
305
+ super("adapt.apis.plugins.v1.Manifest", [
306
+ { no: 1, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
307
+ { no: 2, name: "version", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
308
+ { no: 3, name: "label", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
309
+ { no: 4, name: "description", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
310
+ { no: 5, name: "homepage", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
311
+ { no: 6, name: "repository", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
312
+ { no: 7, name: "bugs", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
313
+ { no: 8, name: "author", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
314
+ { no: 9, name: "logo", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
315
+ { no: 10, name: "task_esm", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
316
+ { no: 11, name: "config_esm", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
317
+ { no: 12, name: "assets_dir", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
318
+ { no: 13, name: "config", kind: "message", T: () => Config },
319
+ { no: 14, name: "vertices", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => Vertex },
320
+ { no: 15, name: "user_secrets", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => Secret },
321
+ { no: 16, name: "user_mtls", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => MTLSService },
322
+ { no: 17, name: "plugin_mtls", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => MTLSService },
323
+ { no: 18, name: "plugin_secrets", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => Secret },
324
+ { no: 19, name: "oauth2", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => OAuth2Service }
325
+ ]);
326
+ }
327
+ create(value) {
328
+ const message = { name: "", version: "", label: "", description: "", taskEsm: "", vertices: [], userSecrets: [], userMtls: [], pluginMtls: [], pluginSecrets: [], oauth2: [] };
329
+ globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
330
+ if (value !== undefined)
331
+ reflectionMergePartial(this, message, value);
332
+ return message;
333
+ }
334
+ internalBinaryRead(reader, length, options, target) {
335
+ let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
336
+ while (reader.pos < end) {
337
+ let [fieldNo, wireType] = reader.tag();
338
+ switch (fieldNo) {
339
+ case /* string name */ 1:
340
+ message.name = reader.string();
341
+ break;
342
+ case /* string version */ 2:
343
+ message.version = reader.string();
344
+ break;
345
+ case /* string label */ 3:
346
+ message.label = reader.string();
347
+ break;
348
+ case /* string description */ 4:
349
+ message.description = reader.string();
350
+ break;
351
+ case /* optional string homepage */ 5:
352
+ message.homepage = reader.string();
353
+ break;
354
+ case /* optional string repository */ 6:
355
+ message.repository = reader.string();
356
+ break;
357
+ case /* optional string bugs */ 7:
358
+ message.bugs = reader.string();
359
+ break;
360
+ case /* optional string author */ 8:
361
+ message.author = reader.string();
362
+ break;
363
+ case /* optional string logo */ 9:
364
+ message.logo = reader.string();
365
+ break;
366
+ case /* string task_esm */ 10:
367
+ message.taskEsm = reader.string();
368
+ break;
369
+ case /* optional string config_esm */ 11:
370
+ message.configEsm = reader.string();
371
+ break;
372
+ case /* optional string assets_dir */ 12:
373
+ message.assetsDir = reader.string();
374
+ break;
375
+ case /* optional adapt.apis.plugins.v1.Config config */ 13:
376
+ message.config = Config.internalBinaryRead(reader, reader.uint32(), options, message.config);
377
+ break;
378
+ case /* repeated adapt.apis.plugins.v1.Vertex vertices */ 14:
379
+ message.vertices.push(Vertex.internalBinaryRead(reader, reader.uint32(), options));
380
+ break;
381
+ case /* repeated adapt.apis.plugins.v1.Secret user_secrets */ 15:
382
+ message.userSecrets.push(Secret.internalBinaryRead(reader, reader.uint32(), options));
383
+ break;
384
+ case /* repeated adapt.apis.plugins.v1.MTLSService user_mtls */ 16:
385
+ message.userMtls.push(MTLSService.internalBinaryRead(reader, reader.uint32(), options));
386
+ break;
387
+ case /* repeated adapt.apis.plugins.v1.MTLSService plugin_mtls */ 17:
388
+ message.pluginMtls.push(MTLSService.internalBinaryRead(reader, reader.uint32(), options));
389
+ break;
390
+ case /* repeated adapt.apis.plugins.v1.Secret plugin_secrets */ 18:
391
+ message.pluginSecrets.push(Secret.internalBinaryRead(reader, reader.uint32(), options));
392
+ break;
393
+ case /* repeated adapt.apis.plugins.v1.OAuth2Service oauth2 */ 19:
394
+ message.oauth2.push(OAuth2Service.internalBinaryRead(reader, reader.uint32(), options));
395
+ break;
396
+ default:
397
+ let u = options.readUnknownField;
398
+ if (u === "throw")
399
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
400
+ let d = reader.skip(wireType);
401
+ if (u !== false)
402
+ (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
403
+ }
404
+ }
405
+ return message;
406
+ }
407
+ internalBinaryWrite(message, writer, options) {
408
+ /* string name = 1; */
409
+ if (message.name !== "")
410
+ writer.tag(1, WireType.LengthDelimited).string(message.name);
411
+ /* string version = 2; */
412
+ if (message.version !== "")
413
+ writer.tag(2, WireType.LengthDelimited).string(message.version);
414
+ /* string label = 3; */
415
+ if (message.label !== "")
416
+ writer.tag(3, WireType.LengthDelimited).string(message.label);
417
+ /* string description = 4; */
418
+ if (message.description !== "")
419
+ writer.tag(4, WireType.LengthDelimited).string(message.description);
420
+ /* optional string homepage = 5; */
421
+ if (message.homepage !== undefined)
422
+ writer.tag(5, WireType.LengthDelimited).string(message.homepage);
423
+ /* optional string repository = 6; */
424
+ if (message.repository !== undefined)
425
+ writer.tag(6, WireType.LengthDelimited).string(message.repository);
426
+ /* optional string bugs = 7; */
427
+ if (message.bugs !== undefined)
428
+ writer.tag(7, WireType.LengthDelimited).string(message.bugs);
429
+ /* optional string author = 8; */
430
+ if (message.author !== undefined)
431
+ writer.tag(8, WireType.LengthDelimited).string(message.author);
432
+ /* optional string logo = 9; */
433
+ if (message.logo !== undefined)
434
+ writer.tag(9, WireType.LengthDelimited).string(message.logo);
435
+ /* string task_esm = 10; */
436
+ if (message.taskEsm !== "")
437
+ writer.tag(10, WireType.LengthDelimited).string(message.taskEsm);
438
+ /* optional string config_esm = 11; */
439
+ if (message.configEsm !== undefined)
440
+ writer.tag(11, WireType.LengthDelimited).string(message.configEsm);
441
+ /* optional string assets_dir = 12; */
442
+ if (message.assetsDir !== undefined)
443
+ writer.tag(12, WireType.LengthDelimited).string(message.assetsDir);
444
+ /* optional adapt.apis.plugins.v1.Config config = 13; */
445
+ if (message.config)
446
+ Config.internalBinaryWrite(message.config, writer.tag(13, WireType.LengthDelimited).fork(), options).join();
447
+ /* repeated adapt.apis.plugins.v1.Vertex vertices = 14; */
448
+ for (let i = 0; i < message.vertices.length; i++)
449
+ Vertex.internalBinaryWrite(message.vertices[i], writer.tag(14, WireType.LengthDelimited).fork(), options).join();
450
+ /* repeated adapt.apis.plugins.v1.Secret user_secrets = 15; */
451
+ for (let i = 0; i < message.userSecrets.length; i++)
452
+ Secret.internalBinaryWrite(message.userSecrets[i], writer.tag(15, WireType.LengthDelimited).fork(), options).join();
453
+ /* repeated adapt.apis.plugins.v1.MTLSService user_mtls = 16; */
454
+ for (let i = 0; i < message.userMtls.length; i++)
455
+ MTLSService.internalBinaryWrite(message.userMtls[i], writer.tag(16, WireType.LengthDelimited).fork(), options).join();
456
+ /* repeated adapt.apis.plugins.v1.MTLSService plugin_mtls = 17; */
457
+ for (let i = 0; i < message.pluginMtls.length; i++)
458
+ MTLSService.internalBinaryWrite(message.pluginMtls[i], writer.tag(17, WireType.LengthDelimited).fork(), options).join();
459
+ /* repeated adapt.apis.plugins.v1.Secret plugin_secrets = 18; */
460
+ for (let i = 0; i < message.pluginSecrets.length; i++)
461
+ Secret.internalBinaryWrite(message.pluginSecrets[i], writer.tag(18, WireType.LengthDelimited).fork(), options).join();
462
+ /* repeated adapt.apis.plugins.v1.OAuth2Service oauth2 = 19; */
463
+ for (let i = 0; i < message.oauth2.length; i++)
464
+ OAuth2Service.internalBinaryWrite(message.oauth2[i], writer.tag(19, WireType.LengthDelimited).fork(), options).join();
465
+ let u = options.writeUnknownFields;
466
+ if (u !== false)
467
+ (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
468
+ return writer;
469
+ }
470
+ }
471
+ /**
472
+ * @generated MessageType for protobuf message adapt.apis.plugins.v1.Manifest
473
+ */
474
+ const Manifest = new Manifest$Type();
475
+ // @generated message type with reflection information, may provide speed optimized methods
476
+ class MTLSService$Type extends MessageType {
477
+ constructor() {
478
+ super("adapt.apis.plugins.v1.MTLSService", [
479
+ { no: 1, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
480
+ { no: 2, name: "optional", kind: "scalar", T: 8 /*ScalarType.BOOL*/ },
481
+ { no: 3, name: "server_cert", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
482
+ { no: 4, name: "trusted_ca", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
483
+ { no: 5, name: "label", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
484
+ { no: 6, name: "description", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ }
485
+ ]);
486
+ }
487
+ create(value) {
488
+ const message = { name: "", optional: false, serverCert: "", trustedCa: "" };
489
+ globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
490
+ if (value !== undefined)
491
+ reflectionMergePartial(this, message, value);
492
+ return message;
493
+ }
494
+ internalBinaryRead(reader, length, options, target) {
495
+ let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
496
+ while (reader.pos < end) {
497
+ let [fieldNo, wireType] = reader.tag();
498
+ switch (fieldNo) {
499
+ case /* string name */ 1:
500
+ message.name = reader.string();
501
+ break;
502
+ case /* bool optional */ 2:
503
+ message.optional = reader.bool();
504
+ break;
505
+ case /* string server_cert */ 3:
506
+ message.serverCert = reader.string();
507
+ break;
508
+ case /* string trusted_ca */ 4:
509
+ message.trustedCa = reader.string();
510
+ break;
511
+ case /* optional string label */ 5:
512
+ message.label = reader.string();
513
+ break;
514
+ case /* optional string description */ 6:
515
+ message.description = reader.string();
516
+ break;
517
+ default:
518
+ let u = options.readUnknownField;
519
+ if (u === "throw")
520
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
521
+ let d = reader.skip(wireType);
522
+ if (u !== false)
523
+ (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
524
+ }
525
+ }
526
+ return message;
527
+ }
528
+ internalBinaryWrite(message, writer, options) {
529
+ /* string name = 1; */
530
+ if (message.name !== "")
531
+ writer.tag(1, WireType.LengthDelimited).string(message.name);
532
+ /* bool optional = 2; */
533
+ if (message.optional !== false)
534
+ writer.tag(2, WireType.Varint).bool(message.optional);
535
+ /* string server_cert = 3; */
536
+ if (message.serverCert !== "")
537
+ writer.tag(3, WireType.LengthDelimited).string(message.serverCert);
538
+ /* string trusted_ca = 4; */
539
+ if (message.trustedCa !== "")
540
+ writer.tag(4, WireType.LengthDelimited).string(message.trustedCa);
541
+ /* optional string label = 5; */
542
+ if (message.label !== undefined)
543
+ writer.tag(5, WireType.LengthDelimited).string(message.label);
544
+ /* optional string description = 6; */
545
+ if (message.description !== undefined)
546
+ writer.tag(6, WireType.LengthDelimited).string(message.description);
547
+ let u = options.writeUnknownFields;
548
+ if (u !== false)
549
+ (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
550
+ return writer;
551
+ }
552
+ }
553
+ /**
554
+ * @generated MessageType for protobuf message adapt.apis.plugins.v1.MTLSService
555
+ */
556
+ const MTLSService = new MTLSService$Type();
557
+ // @generated message type with reflection information, may provide speed optimized methods
558
+ class OAuth2Service$Type extends MessageType {
559
+ constructor() {
560
+ super("adapt.apis.plugins.v1.OAuth2Service", [
561
+ { no: 1, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
562
+ { no: 2, name: "optional", kind: "scalar", T: 8 /*ScalarType.BOOL*/ },
563
+ { no: 3, name: "grant_type", kind: "enum", T: () => ["adapt.apis.plugins.v1.OAuth2Service.GrantType", OAuth2Service_GrantType, "GRANT_TYPE_"] },
564
+ { no: 4, name: "label", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
565
+ { no: 5, name: "description", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ }
566
+ ]);
567
+ }
568
+ create(value) {
569
+ const message = { name: "", optional: false, grantType: 0 };
570
+ globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
571
+ if (value !== undefined)
572
+ reflectionMergePartial(this, message, value);
573
+ return message;
574
+ }
575
+ internalBinaryRead(reader, length, options, target) {
576
+ let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
577
+ while (reader.pos < end) {
578
+ let [fieldNo, wireType] = reader.tag();
579
+ switch (fieldNo) {
580
+ case /* string name */ 1:
581
+ message.name = reader.string();
582
+ break;
583
+ case /* bool optional */ 2:
584
+ message.optional = reader.bool();
585
+ break;
586
+ case /* adapt.apis.plugins.v1.OAuth2Service.GrantType grant_type */ 3:
587
+ message.grantType = reader.int32();
588
+ break;
589
+ case /* optional string label */ 4:
590
+ message.label = reader.string();
591
+ break;
592
+ case /* optional string description */ 5:
593
+ message.description = reader.string();
594
+ break;
595
+ default:
596
+ let u = options.readUnknownField;
597
+ if (u === "throw")
598
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
599
+ let d = reader.skip(wireType);
600
+ if (u !== false)
601
+ (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
602
+ }
603
+ }
604
+ return message;
605
+ }
606
+ internalBinaryWrite(message, writer, options) {
607
+ /* string name = 1; */
608
+ if (message.name !== "")
609
+ writer.tag(1, WireType.LengthDelimited).string(message.name);
610
+ /* bool optional = 2; */
611
+ if (message.optional !== false)
612
+ writer.tag(2, WireType.Varint).bool(message.optional);
613
+ /* adapt.apis.plugins.v1.OAuth2Service.GrantType grant_type = 3; */
614
+ if (message.grantType !== 0)
615
+ writer.tag(3, WireType.Varint).int32(message.grantType);
616
+ /* optional string label = 4; */
617
+ if (message.label !== undefined)
618
+ writer.tag(4, WireType.LengthDelimited).string(message.label);
619
+ /* optional string description = 5; */
620
+ if (message.description !== undefined)
621
+ writer.tag(5, WireType.LengthDelimited).string(message.description);
622
+ let u = options.writeUnknownFields;
623
+ if (u !== false)
624
+ (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
625
+ return writer;
626
+ }
627
+ }
628
+ /**
629
+ * @generated MessageType for protobuf message adapt.apis.plugins.v1.OAuth2Service
630
+ */
631
+ const OAuth2Service = new OAuth2Service$Type();
632
+ // @generated message type with reflection information, may provide speed optimized methods
633
+ class Secret$Type extends MessageType {
634
+ constructor() {
635
+ super("adapt.apis.plugins.v1.Secret", [
636
+ { no: 1, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
637
+ { no: 2, name: "optional", kind: "scalar", T: 8 /*ScalarType.BOOL*/ },
638
+ { no: 3, name: "label", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
639
+ { no: 4, name: "description", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ }
640
+ ]);
641
+ }
642
+ create(value) {
643
+ const message = { name: "", optional: false };
644
+ globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
645
+ if (value !== undefined)
646
+ reflectionMergePartial(this, message, value);
647
+ return message;
648
+ }
649
+ internalBinaryRead(reader, length, options, target) {
650
+ let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
651
+ while (reader.pos < end) {
652
+ let [fieldNo, wireType] = reader.tag();
653
+ switch (fieldNo) {
654
+ case /* string name */ 1:
655
+ message.name = reader.string();
656
+ break;
657
+ case /* bool optional */ 2:
658
+ message.optional = reader.bool();
659
+ break;
660
+ case /* optional string label */ 3:
661
+ message.label = reader.string();
662
+ break;
663
+ case /* optional string description */ 4:
664
+ message.description = reader.string();
665
+ break;
666
+ default:
667
+ let u = options.readUnknownField;
668
+ if (u === "throw")
669
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
670
+ let d = reader.skip(wireType);
671
+ if (u !== false)
672
+ (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
673
+ }
674
+ }
675
+ return message;
676
+ }
677
+ internalBinaryWrite(message, writer, options) {
678
+ /* string name = 1; */
679
+ if (message.name !== "")
680
+ writer.tag(1, WireType.LengthDelimited).string(message.name);
681
+ /* bool optional = 2; */
682
+ if (message.optional !== false)
683
+ writer.tag(2, WireType.Varint).bool(message.optional);
684
+ /* optional string label = 3; */
685
+ if (message.label !== undefined)
686
+ writer.tag(3, WireType.LengthDelimited).string(message.label);
687
+ /* optional string description = 4; */
688
+ if (message.description !== undefined)
689
+ writer.tag(4, WireType.LengthDelimited).string(message.description);
690
+ let u = options.writeUnknownFields;
691
+ if (u !== false)
692
+ (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
693
+ return writer;
694
+ }
695
+ }
696
+ /**
697
+ * @generated MessageType for protobuf message adapt.apis.plugins.v1.Secret
698
+ */
699
+ const Secret = new Secret$Type();
700
+ // @generated message type with reflection information, may provide speed optimized methods
701
+ class Config$Type extends MessageType {
702
+ constructor() {
703
+ super("adapt.apis.plugins.v1.Config", [
704
+ { no: 1, name: "schema", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
705
+ { no: 2, name: "default_config", kind: "scalar", T: 9 /*ScalarType.STRING*/ }
706
+ ]);
707
+ }
708
+ create(value) {
709
+ const message = { defaultConfig: "" };
710
+ globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
711
+ if (value !== undefined)
712
+ reflectionMergePartial(this, message, value);
713
+ return message;
714
+ }
715
+ internalBinaryRead(reader, length, options, target) {
716
+ let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
717
+ while (reader.pos < end) {
718
+ let [fieldNo, wireType] = reader.tag();
719
+ switch (fieldNo) {
720
+ case /* optional string schema */ 1:
721
+ message.schema = reader.string();
722
+ break;
723
+ case /* string default_config */ 2:
724
+ message.defaultConfig = reader.string();
725
+ break;
726
+ default:
727
+ let u = options.readUnknownField;
728
+ if (u === "throw")
729
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
730
+ let d = reader.skip(wireType);
731
+ if (u !== false)
732
+ (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
733
+ }
734
+ }
735
+ return message;
736
+ }
737
+ internalBinaryWrite(message, writer, options) {
738
+ /* optional string schema = 1; */
739
+ if (message.schema !== undefined)
740
+ writer.tag(1, WireType.LengthDelimited).string(message.schema);
741
+ /* string default_config = 2; */
742
+ if (message.defaultConfig !== "")
743
+ writer.tag(2, WireType.LengthDelimited).string(message.defaultConfig);
744
+ let u = options.writeUnknownFields;
745
+ if (u !== false)
746
+ (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
747
+ return writer;
748
+ }
749
+ }
750
+ /**
751
+ * @generated MessageType for protobuf message adapt.apis.plugins.v1.Config
752
+ */
753
+ const Config = new Config$Type();
754
+ // @generated message type with reflection information, may provide speed optimized methods
755
+ class Vertex$Type extends MessageType {
756
+ constructor() {
757
+ super("adapt.apis.plugins.v1.Vertex", [
758
+ { no: 1, name: "name", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
759
+ { no: 2, name: "label", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
760
+ { no: 3, name: "description", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
761
+ { no: 4, name: "logo", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
762
+ { no: 5, name: "type", kind: "enum", T: () => ["adapt.apis.plugins.v1.Vertex.VertexType", Vertex_VertexType, "VERTEX_TYPE_"] },
763
+ { no: 6, name: "config", kind: "message", T: () => Config },
764
+ { no: 7, name: "cron_interval", kind: "scalar", opt: true, T: 13 /*ScalarType.UINT32*/ },
765
+ { no: 8, name: "require_plugin_config", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ }
766
+ ]);
767
+ }
768
+ create(value) {
769
+ const message = { name: "", label: "", type: 0 };
770
+ globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
771
+ if (value !== undefined)
772
+ reflectionMergePartial(this, message, value);
773
+ return message;
774
+ }
775
+ internalBinaryRead(reader, length, options, target) {
776
+ let message = target !== null && target !== void 0 ? target : this.create(), end = reader.pos + length;
777
+ while (reader.pos < end) {
778
+ let [fieldNo, wireType] = reader.tag();
779
+ switch (fieldNo) {
780
+ case /* string name */ 1:
781
+ message.name = reader.string();
782
+ break;
783
+ case /* string label */ 2:
784
+ message.label = reader.string();
785
+ break;
786
+ case /* optional string description */ 3:
787
+ message.description = reader.string();
788
+ break;
789
+ case /* optional string logo */ 4:
790
+ message.logo = reader.string();
791
+ break;
792
+ case /* adapt.apis.plugins.v1.Vertex.VertexType type */ 5:
793
+ message.type = reader.int32();
794
+ break;
795
+ case /* adapt.apis.plugins.v1.Config config */ 6:
796
+ message.config = Config.internalBinaryRead(reader, reader.uint32(), options, message.config);
797
+ break;
798
+ case /* optional uint32 cron_interval */ 7:
799
+ message.cronInterval = reader.uint32();
800
+ break;
801
+ case /* optional bool require_plugin_config */ 8:
802
+ message.requirePluginConfig = reader.bool();
803
+ break;
804
+ default:
805
+ let u = options.readUnknownField;
806
+ if (u === "throw")
807
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
808
+ let d = reader.skip(wireType);
809
+ if (u !== false)
810
+ (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
811
+ }
812
+ }
813
+ return message;
814
+ }
815
+ internalBinaryWrite(message, writer, options) {
816
+ /* string name = 1; */
817
+ if (message.name !== "")
818
+ writer.tag(1, WireType.LengthDelimited).string(message.name);
819
+ /* string label = 2; */
820
+ if (message.label !== "")
821
+ writer.tag(2, WireType.LengthDelimited).string(message.label);
822
+ /* optional string description = 3; */
823
+ if (message.description !== undefined)
824
+ writer.tag(3, WireType.LengthDelimited).string(message.description);
825
+ /* optional string logo = 4; */
826
+ if (message.logo !== undefined)
827
+ writer.tag(4, WireType.LengthDelimited).string(message.logo);
828
+ /* adapt.apis.plugins.v1.Vertex.VertexType type = 5; */
829
+ if (message.type !== 0)
830
+ writer.tag(5, WireType.Varint).int32(message.type);
831
+ /* adapt.apis.plugins.v1.Config config = 6; */
832
+ if (message.config)
833
+ Config.internalBinaryWrite(message.config, writer.tag(6, WireType.LengthDelimited).fork(), options).join();
834
+ /* optional uint32 cron_interval = 7; */
835
+ if (message.cronInterval !== undefined)
836
+ writer.tag(7, WireType.Varint).uint32(message.cronInterval);
837
+ /* optional bool require_plugin_config = 8; */
838
+ if (message.requirePluginConfig !== undefined)
839
+ writer.tag(8, WireType.Varint).bool(message.requirePluginConfig);
840
+ let u = options.writeUnknownFields;
841
+ if (u !== false)
842
+ (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
843
+ return writer;
844
+ }
845
+ }
846
+ /**
847
+ * @generated MessageType for protobuf message adapt.apis.plugins.v1.Vertex
848
+ */
849
+ const Vertex = new Vertex$Type();
850
+ /**
851
+ * @generated ServiceType for protobuf service adapt.apis.plugins.v1.PluginService
852
+ */
853
+ const PluginService = new ServiceType("adapt.apis.plugins.v1.PluginService", [
854
+ { name: "UploadPlugin", clientStreaming: true, options: { "google.api.http": { post: "/v1/plugins/upload", body: "*" } }, I: UploadPluginRequest, O: UploadPluginResponse }
855
+ ], { "google.api.default_host": "adapt.mochabugapis.com", "google.api.oauth_scopes": "https://www.mochabugapis.com/auth/adapt.plugins" });
856
+
857
+ /**
858
+ * PluginService provides a service for uploading a plugin.
859
+ *
860
+ * @generated from protobuf service adapt.apis.plugins.v1.PluginService
861
+ */
862
+ class PluginServiceClient {
863
+ constructor(_transport) {
864
+ this._transport = _transport;
865
+ this.typeName = PluginService.typeName;
866
+ this.methods = PluginService.methods;
867
+ this.options = PluginService.options;
868
+ }
869
+ /**
870
+ * UploadPlugin is a streaming RPC method that allows uploading a plugin in
871
+ * chunks. The client can send multiple UploadPluginRequest messages, and the
872
+ * server will respond with a single UploadPluginResponse after processing all
873
+ * requests.
874
+ *
875
+ * @generated from protobuf rpc: UploadPlugin(stream adapt.apis.plugins.v1.UploadPluginRequest) returns (adapt.apis.plugins.v1.UploadPluginResponse);
876
+ */
877
+ uploadPlugin(options) {
878
+ const method = this.methods[0], opt = this._transport.mergeOptions(options);
879
+ return stackIntercept("clientStreaming", this._transport, method, opt);
880
+ }
881
+ }
882
+
883
+ // Copyright 2023, mochabug AB
884
+ //
885
+ // Licensed under the Apache License, Version 2.0 (the "License");
886
+ // you may not use this file except in compliance with the License.
887
+ // You may obtain a copy of the License at
888
+ //
889
+ // http://www.apache.org/licenses/LICENSE-2.0
890
+ //
891
+ // Unless required by applicable law or agreed to in writing, software
892
+ // distributed under the License is distributed on an "AS IS" BASIS,
893
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
894
+ // See the License for the specific language governing permissions and
895
+ // limitations under the License.
896
+ function writeFile(filePath, content) {
897
+ const dir = path.dirname(filePath);
898
+ mkdirp.sync(dir);
899
+ fs.writeFileSync(filePath, content);
900
+ }
901
+ function readManifest() {
902
+ const manifestData = fs.readFileSync('manifest.json').toString();
903
+ return Manifest.fromJsonString(manifestData);
904
+ }
905
+ function capitilize(val) {
906
+ return val.charAt(0).toUpperCase() + val.substring(1);
907
+ }
908
+ function resize(filepath, height, width) {
909
+ return __awaiter(this, void 0, void 0, function* () {
910
+ const extname = path.extname(filepath);
911
+ switch (extname) {
912
+ case '.avif':
913
+ return yield sharp(filepath)
914
+ .resize(height, width)
915
+ .avif()
916
+ .toBuffer();
917
+ case '.gif':
918
+ return yield sharp(filepath)
919
+ .resize(height, width)
920
+ .gif()
921
+ .toBuffer();
922
+ case '.jpg':
923
+ case '.jpeg':
924
+ case '.jfif':
925
+ case '.pjpeg':
926
+ case '.pjp':
927
+ return yield sharp(filepath)
928
+ .resize(height, width)
929
+ .jpeg()
930
+ .toBuffer();
931
+ case '.png':
932
+ return yield sharp(filepath)
933
+ .resize(height, width)
934
+ .png()
935
+ .toBuffer();
936
+ case '.svg':
937
+ return fs.readFileSync(filepath);
938
+ case '.webp':
939
+ return yield sharp(filepath)
940
+ .resize(height, width)
941
+ .webp()
942
+ .toBuffer();
943
+ }
944
+ throw new Error("Invalid logotype");
945
+ });
946
+ }
947
+ function convertVertexType(type) {
948
+ switch (type) {
949
+ case "action":
950
+ return Vertex_VertexType.ACTION;
951
+ case "cron-trigger":
952
+ return Vertex_VertexType.CRON_TRIGGER;
953
+ case "external-trigger":
954
+ return Vertex_VertexType.EXTERNAL_TRIGGER;
955
+ case "browser":
956
+ return Vertex_VertexType.BROWSER;
957
+ default:
958
+ throw new Error('The node type is invalid');
959
+ }
960
+ }
961
+ function addVertex(cwd, name, type, hasTaskConfig) {
962
+ const relPathTask = path.join('src', `${name}.executor.ts`);
963
+ const taskFile = path.join(cwd, relPathTask);
964
+ const relPathConfig = path.join('src', `${name}.configurator.ts`);
965
+ const configFile = path.join(cwd, relPathConfig);
966
+ const vertex = {
967
+ name,
968
+ label: capitilize(name),
969
+ description: `Performing ${name} very well`,
970
+ type: convertVertexType(type),
971
+ requirePluginConfig: false,
972
+ config: {
973
+ defaultConfig: path.join('src', `${name}_vertex.json`)
974
+ }
975
+ };
976
+ // 5 seconds is a nice default
977
+ if (vertex.type === Vertex_VertexType.CRON_TRIGGER) {
978
+ vertex.cronInterval = 5000;
979
+ }
980
+ // Write the new task
981
+ let importFile = `./${name}.executor`;
982
+ let exportFile = path.join(cwd, 'src', 'executors.ts');
983
+ let importString;
984
+ let exportString;
985
+ switch (vertex.type) {
986
+ case Vertex_VertexType.ACTION:
987
+ writeFile(taskFile, actionTemplate);
988
+ importString = `import { internal as ${name}InternalExecutor} from "${importFile}";`;
989
+ exportString = `export { ${name}InternalExecutor }`;
990
+ break;
991
+ case Vertex_VertexType.BROWSER:
992
+ writeFile(taskFile, browserTemplate);
993
+ importString = `import { external as ${name}ExternalExecutor, internal as ${name}InternalExecutor } from "${importFile}";`;
994
+ exportString = `export { ${name}ExternalExecutor, ${name}InternalExecutor }`;
995
+ break;
996
+ case Vertex_VertexType.EXTERNAL_TRIGGER:
997
+ case Vertex_VertexType.CRON_TRIGGER:
998
+ writeFile(taskFile, triggerTemplate);
999
+ importString = `import { trigger as ${name}TriggerExecutor, internal as ${name}InternalExecutor } from "${importFile}";`;
1000
+ exportString = `export { ${name}TriggerExecutor, ${name}InternalExecutor }`;
1001
+ break;
1002
+ default:
1003
+ throw new Error('The vertex type is invalid');
1004
+ }
1005
+ // Append or create src/executors.ts
1006
+ if (fs.existsSync(exportFile)) {
1007
+ let exports = fs.readFileSync(exportFile).toString();
1008
+ exports = `${importString}\n` + exports + `\n${exportString}`;
1009
+ fs.writeFileSync(exportFile, exports);
1010
+ }
1011
+ else {
1012
+ const exports = `${importString}\n\n${exportString}`;
1013
+ fs.writeFileSync(exportFile, exports);
1014
+ }
1015
+ const vertex_config = {
1016
+ complete: true,
1017
+ receivers: [{
1018
+ name: "input",
1019
+ description: "Default input receiver",
1020
+ signals: []
1021
+ }],
1022
+ transmitters: [{
1023
+ name: "output",
1024
+ description: "Default output transmitter",
1025
+ signals: []
1026
+ }],
1027
+ procedures: [],
1028
+ streams: [],
1029
+ signals: []
1030
+ };
1031
+ if (hasTaskConfig) {
1032
+ writeFile(configFile, configTemplate);
1033
+ vertex_config.complete = false;
1034
+ fs.writeFileSync(path.join(cwd, 'src', `${name}_vertex.cue`), vertexSchema);
1035
+ if (!vertex.config) {
1036
+ throw new Error("Impossible");
1037
+ }
1038
+ vertex.config.schema = path.join('src', `${name}_vertex.cue`);
1039
+ const internalName = `${name}InternalConfigurator`;
1040
+ const externalName = `${name}ExternalConfigurator`;
1041
+ importFile = `./${name}.configurator`;
1042
+ exportFile = path.join(cwd, 'src', 'configurators.ts');
1043
+ if (fs.existsSync(exportFile)) {
1044
+ let exports = fs.readFileSync(exportFile).toString();
1045
+ exports = `import { external as ${externalName}, internal as ${internalName} } from "${importFile}";\n` + exports +
1046
+ `\nexport { ${externalName}, ${internalName} }`;
1047
+ fs.writeFileSync(exportFile, exports);
1048
+ }
1049
+ else {
1050
+ const exports = `import { external as ${externalName}, internal as ${internalName} } from "${importFile}";\n\nexport { ${externalName}, ${internalName} }`;
1051
+ fs.writeFileSync(exportFile, exports);
1052
+ }
1053
+ }
1054
+ // Write the config json file
1055
+ fs.writeFileSync(path.join(cwd, 'src', `${name}_vertex.json`), JSON.stringify(vertex_config, null, 2));
1056
+ return vertex;
1057
+ }
1058
+ function init(dir) {
1059
+ return __awaiter(this, void 0, void 0, function* () {
1060
+ const ans = yield inquirer.prompt([
1061
+ {
1062
+ type: 'input',
1063
+ name: 'name',
1064
+ message: 'Type plugin name',
1065
+ filter: (val) => {
1066
+ return val.trim().toLowerCase();
1067
+ },
1068
+ validate: (val) => {
1069
+ return /[a-zA-Z][0-9a-zA-Z_]*/.test(val);
1070
+ }
1071
+ },
1072
+ {
1073
+ type: 'list',
1074
+ name: 'vertexType',
1075
+ message: 'Choose vertex type',
1076
+ choices: ['action', 'browser', 'cron-trigger', 'external-trigger']
1077
+ },
1078
+ {
1079
+ type: 'input',
1080
+ name: 'vertexName',
1081
+ message: 'Write the vertex name',
1082
+ filter: (val) => {
1083
+ return val.trim().toLowerCase();
1084
+ },
1085
+ validate: (val) => {
1086
+ return /[a-zA-Z][0-9a-zA-Z_]*/.test(val);
1087
+ }
1088
+ },
1089
+ {
1090
+ type: 'confirm',
1091
+ name: 'hasConfigurator',
1092
+ message: 'Need a configurator for the vertex?'
1093
+ }
1094
+ ]);
1095
+ mkdirp.sync(dir);
1096
+ const cwd = !path.isAbsolute(dir) ? path.join(process.cwd(), dir) : dir;
1097
+ // Creating a minimal npm package
1098
+ console.log(chalk.magenta('Creating package.json...'));
1099
+ const defPackage = {
1100
+ name: ans.name,
1101
+ version: "",
1102
+ private: true,
1103
+ type: "module",
1104
+ scripts: {
1105
+ "test": "jest --collectCoverage --passWithNoTests",
1106
+ "rollup": "rollup -c rollup.config.js",
1107
+ "build": "run-p rollup",
1108
+ "add": "adaptkit --add",
1109
+ "publish": "npm run build && adaptkit --publish",
1110
+ "emulate": "npm run build && adaptkit --emulate",
1111
+ }
1112
+ };
1113
+ writeFile(path.join(cwd, 'package.json'), JSON.stringify(defPackage, null, 2));
1114
+ writeFile(path.join(cwd, 'README.md'), readmeTemplate);
1115
+ writeFile(path.join(cwd, 'LICENSE.md'), licenseTemplate);
1116
+ execSync('npm install --save-dev @mochabug/adapt-plugin-typings typescript jest @jest/globals ts-jest @types/jest ts-node tslib rollup @rollup/plugin-typescript @rollup/plugin-terser @rollup/plugin-node-resolve @rollup/plugin-commonjs npm-run-all', {
1117
+ cwd: cwd,
1118
+ stdio: 'inherit'
1119
+ });
1120
+ execSync('npm install @mochabug/adapt-plugin-toolkit', {
1121
+ cwd: cwd,
1122
+ stdio: 'inherit'
1123
+ });
1124
+ console.log(chalk.magenta('Setting up project structure...'));
1125
+ writeFile(path.join(cwd, 'tsconfig.json'), tsconfig);
1126
+ writeFile(path.join(cwd, 'jest.config.ts'), jestTemplate);
1127
+ writeFile(path.join(cwd, '.gitignore'), gitignoreTemplate);
1128
+ writeFile(path.join(cwd, 'rollup.config.js'), rollupTemplate);
1129
+ const vertex = addVertex(cwd, ans.vertexName, ans.vertexType, ans.hasConfigurator);
1130
+ writeFile(path.join(cwd, 'src', 'base_schema.cue'), baseSchema);
1131
+ console.log(chalk.magenta('Creating manifest...'));
1132
+ mkdirp.sync(path.join(cwd, 'assets'));
1133
+ const manifest = {
1134
+ name: ans.name,
1135
+ version: "0.0.1-beta.1",
1136
+ label: capitilize(ans.name),
1137
+ description: `A nice description of what ${ans.name} does`,
1138
+ author: "John Doe",
1139
+ bugs: "mailto:bugs@foobar.com",
1140
+ homepage: `https://www.foobar.com`,
1141
+ repository: `https://github.com`,
1142
+ vertices: [vertex],
1143
+ userSecrets: [],
1144
+ userMtls: [],
1145
+ assetsDir: "assets",
1146
+ taskEsm: "dist/executors.js",
1147
+ pluginSecrets: [],
1148
+ pluginMtls: [],
1149
+ oauth2: []
1150
+ };
1151
+ if (!vertex.config) {
1152
+ throw new Error("This cannot happen");
1153
+ }
1154
+ // Add the esm if we have a schema => this means that it has a configurator
1155
+ if (vertex.config.schema) {
1156
+ manifest.configEsm = "dist/configurators.js";
1157
+ }
1158
+ // Write out the actual manifest and we're done
1159
+ fs.writeFileSync(path.join(cwd, 'manifest.json'), Manifest.toJsonString(manifest, { enumAsInteger: false, prettySpaces: 2, emitDefaultValues: true }));
1160
+ console.log(chalk.bgGreen('Success'));
1161
+ });
1162
+ }
1163
+ function add(manifest) {
1164
+ var _a;
1165
+ return __awaiter(this, void 0, void 0, function* () {
1166
+ const ans = yield inquirer.prompt([
1167
+ {
1168
+ type: 'input',
1169
+ name: 'vertexName',
1170
+ message: 'Type a new unused vertex name',
1171
+ filter: (val) => {
1172
+ return val.trim();
1173
+ },
1174
+ validate: (val) => {
1175
+ val = val.trim();
1176
+ if (manifest.vertices.filter(item => item.name === val).length > 0) {
1177
+ return false;
1178
+ }
1179
+ return /[a-zA-Z][0-9a-zA-Z_]*/.test(val);
1180
+ }
1181
+ },
1182
+ {
1183
+ type: 'list',
1184
+ name: 'vertexType',
1185
+ message: 'Choose your vertex type',
1186
+ choices: ['action', 'browser', 'cron-trigger', 'external-trigger']
1187
+ },
1188
+ {
1189
+ type: 'confirm',
1190
+ name: 'hasConfigurator',
1191
+ message: 'Need a configurator for the vertex?'
1192
+ }
1193
+ ]);
1194
+ console.log(chalk.magenta('Creating new vertex templates...'));
1195
+ const vertex = addVertex('.', ans.vertexName, ans.vertexType, ans.hasConfigurator);
1196
+ manifest.vertices.push(vertex);
1197
+ if (!manifest.configEsm && ((_a = vertex.config) === null || _a === void 0 ? void 0 : _a.schema)) {
1198
+ manifest.configEsm = "dist/configurators.js";
1199
+ }
1200
+ console.log(chalk.magenta('Updating manifest...'));
1201
+ fs.writeFileSync('manifest.json', Manifest.toJsonString(manifest, { enumAsInteger: false, prettySpaces: 2, emitDefaultValues: true }));
1202
+ console.log(chalk.bgGreen('Success'));
1203
+ });
1204
+ }
1205
+ function addPluginConfig(manifest) {
1206
+ return __awaiter(this, void 0, void 0, function* () {
1207
+ if (manifest.config) {
1208
+ console.log(chalk.bgRed("Already contains a configuration in manifest.json"));
1209
+ return;
1210
+ }
1211
+ // Write the default config
1212
+ const schemaPath = path.join('src', `plugin.cue`);
1213
+ const configPath = path.join('src', `plugin.json`);
1214
+ fs.writeFileSync(schemaPath, pluginSchema);
1215
+ console.log(chalk.green("plugin.cue has been written"));
1216
+ fs.writeFileSync(configPath, JSON.stringify({ complete: false, signals: [] }, null, 2));
1217
+ console.log(chalk.green("plugin.json has been written"));
1218
+ manifest.config = {
1219
+ defaultConfig: configPath,
1220
+ schema: schemaPath
1221
+ };
1222
+ console.log(chalk.magenta('Updating manifest...'));
1223
+ fs.writeFileSync('manifest.json', Manifest.toJsonString(manifest, { enumAsInteger: false, prettySpaces: 2, emitDefaultValues: true }));
1224
+ console.log(chalk.bgGreen('Success'));
1225
+ });
1226
+ }
1227
+ function publish(manifest, address) {
1228
+ var _a, _b;
1229
+ return __awaiter(this, void 0, void 0, function* () {
1230
+ const transport = new GrpcTransport({
1231
+ host: address,
1232
+ channelCredentials: ChannelCredentials.createInsecure(),
1233
+ });
1234
+ const client = new PluginServiceClient(transport);
1235
+ const stream = client.uploadPlugin();
1236
+ function send(filePath, imgOpts) {
1237
+ return __awaiter(this, void 0, void 0, function* () {
1238
+ if (!filePath || !fs.existsSync(filePath)) {
1239
+ return;
1240
+ }
1241
+ // If image file, we need to compress it
1242
+ let buffer;
1243
+ if (imgOpts) {
1244
+ buffer = yield resize(filePath, imgOpts[0], imgOpts[1]);
1245
+ console.log(`Compressed: ${filePath} to ${imgOpts[0]}x${imgOpts[1]} size`);
1246
+ }
1247
+ else {
1248
+ buffer = fs.readFileSync(filePath);
1249
+ }
1250
+ console.log(`Sending: ${filePath}`);
1251
+ const message = {
1252
+ data: {
1253
+ oneofKind: 'file',
1254
+ file: {
1255
+ data: buffer,
1256
+ path: filePath
1257
+ }
1258
+ }
1259
+ };
1260
+ yield stream.requests.send(message);
1261
+ });
1262
+ }
1263
+ // The first message must be the manifest
1264
+ // All the other messages must be files and must be described in the manifest
1265
+ const request = {
1266
+ data: {
1267
+ oneofKind: 'manifest',
1268
+ manifest: manifest
1269
+ }
1270
+ };
1271
+ yield stream.requests.send(request);
1272
+ yield send('README.md');
1273
+ yield send('LICENSE.md');
1274
+ yield send(manifest.taskEsm);
1275
+ yield send(manifest.configEsm);
1276
+ yield send(manifest.logo, [80, 80]);
1277
+ yield send((_a = manifest.config) === null || _a === void 0 ? void 0 : _a.defaultConfig);
1278
+ yield send((_b = manifest.config) === null || _b === void 0 ? void 0 : _b.schema);
1279
+ // Send everything inside the asset directory as assets
1280
+ if (manifest.assetsDir && fs.existsSync(manifest.assetsDir)) {
1281
+ const paths = yield glob(path.join(manifest.assetsDir, '**', '*'));
1282
+ console.log('Found in assets directory:');
1283
+ console.log(paths);
1284
+ for (let filepath of paths) {
1285
+ if (fs.statSync(filepath).isFile()) {
1286
+ yield send(filepath);
1287
+ }
1288
+ }
1289
+ }
1290
+ // Send everything related to the vertices. Logos, schemas and configs
1291
+ for (let vertex of manifest.vertices) {
1292
+ yield send(vertex.logo, [40, 40]);
1293
+ if (!vertex.config) {
1294
+ throw new Error("This should never happen");
1295
+ }
1296
+ yield send(vertex.config.defaultConfig);
1297
+ yield send(vertex.config.schema);
1298
+ }
1299
+ stream.requests.complete();
1300
+ const result = yield stream;
1301
+ console.log(result);
1302
+ if (result.status.code === "OK") {
1303
+ console.log(chalk.green('Publishing done'));
1304
+ console.log(chalk.bgGreen('SUCCESS'));
1305
+ }
1306
+ else {
1307
+ console.log('The publishing failed. See log messages for error');
1308
+ console.log(chalk.bgRed('FAILURE'));
1309
+ }
1310
+ });
1311
+ }
1312
+ function main() {
1313
+ return __awaiter(this, void 0, void 0, function* () {
1314
+ program
1315
+ .name("Adaptkit")
1316
+ .version("1.0.0")
1317
+ .description("A CLI util to create, manage and publish plugins for mochabug adapt.")
1318
+ .option("-i, --init [dir]", "initialize a new plugin project in the specified directory (default './')", undefined)
1319
+ .option("-a, --add", "add a new vertex to the plugin. Working directory need to contain a manifest.json file")
1320
+ .option("-c, --plugin", "add a plugin configuration. Working directory need to contain a manifest.json file")
1321
+ .option("-p, --publish [url]", "publish the plugin to your organization (default [HERE])", undefined)
1322
+ .option("-e, --emulate [url]", "run the plugin in the emulator on the given url (default [HERE]", undefined)
1323
+ .parse(process.argv);
1324
+ const options = program.opts();
1325
+ if (options.init) {
1326
+ console.log(chalk.blueBright(figlet.textSync("Adaptkit")));
1327
+ let dir = '.';
1328
+ if (typeof options.init !== "boolean") {
1329
+ dir = options.init;
1330
+ }
1331
+ yield init(dir);
1332
+ }
1333
+ else if (options.add) {
1334
+ console.log(chalk.blueBright(figlet.textSync("Adaptkit")));
1335
+ yield add(readManifest());
1336
+ }
1337
+ else if (options.plugin) {
1338
+ console.log(chalk.blueBright(figlet.textSync("Adaptkit")));
1339
+ yield addPluginConfig(readManifest());
1340
+ }
1341
+ else if (options.publish) {
1342
+ let address = "localhost:50010";
1343
+ if (typeof options.publish !== "boolean") {
1344
+ address = options.publish;
1345
+ }
1346
+ yield publish(readManifest(), address);
1347
+ }
1348
+ else if (options.emulate) {
1349
+ let address = "localhost:51000";
1350
+ if (typeof options.emulate !== "boolean") {
1351
+ address = options.emulate;
1352
+ }
1353
+ yield publish(readManifest(), address);
1354
+ }
1355
+ else {
1356
+ console.log(chalk.blueBright(figlet.textSync("Adaptkit")));
1357
+ program.outputHelp();
1358
+ }
1359
+ process.exit();
1360
+ });
1361
+ }
1362
+ main();
1363
+ //# sourceMappingURL=index.js.map