UNPKG

11.7 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.Probot = void 0;
7const deprecation_1 = require("deprecation");
8const express_1 = __importDefault(require("express"));
9const lru_cache_1 = __importDefault(require("lru-cache"));
10const alias_log_1 = require("./helpers/alias-log");
11const auth_1 = require("./auth");
12const create_server_1 = require("./server/create-server");
13const webhook_proxy_1 = require("./helpers/webhook-proxy");
14const get_error_handler_1 = require("./helpers/get-error-handler");
15const get_log_1 = require("./helpers/get-log");
16const get_probot_octokit_with_defaults_1 = require("./octokit/get-probot-octokit-with-defaults");
17const get_router_1 = require("./get-router");
18const get_webhooks_1 = require("./octokit/get-webhooks");
19const load_1 = require("./load");
20const probot_octokit_1 = require("./octokit/probot-octokit");
21const run_1 = require("./run");
22const version_1 = require("./version");
23const webhook_event_check_1 = require("./helpers/webhook-event-check");
24const default_1 = require("./apps/default");
25const defaultAppFns = [default_1.defaultApp];
26class Probot {
27 constructor(options = {}) {
28 options.webhookPath = options.webhookPath || "/";
29 options.secret = options.secret || "development";
30 let logEnvVariableDeprecation;
31 let level = options.logLevel;
32 if (!options.log && !level && process.env.LOG_LEVEL) {
33 logEnvVariableDeprecation =
34 '[probot] "LOG_LEVEL" environment variable is deprecated. Use "new Probot({ logLevel })" instead';
35 level = process.env.LOG_LEVEL;
36 }
37 this.log = alias_log_1.aliasLog(options.log || get_log_1.getLog({ level }));
38 if (logEnvVariableDeprecation) {
39 this.log.warn(new deprecation_1.Deprecation(logEnvVariableDeprecation));
40 }
41 if (options.id) {
42 this.log.warn(new deprecation_1.Deprecation(`[probot] "id" option is deprecated. Use "appId" instead`));
43 options.appId = options.appId || options.id;
44 }
45 if (options.cert) {
46 this.log.warn(new deprecation_1.Deprecation(`[probot] "cert" option is deprecated. Use "privateKey" instead`));
47 options.privateKey = options.privateKey || options.cert;
48 }
49 if (process.env.INSTALLATION_TOKEN_TTL) {
50 this.log.warn('[probot] "INSTALLATION_TOKEN_TTL" environment variable is no longer used. Tokens are renewed as needed at the time of the request now.');
51 }
52 // TODO: support redis backend for access token cache if `options.redisConfig || process.env.REDIS_URL`
53 const cache = new lru_cache_1.default({
54 // cache max. 15000 tokens, that will use less than 10mb memory
55 max: 15000,
56 // Cache for 1 minute less than GitHub expiry
57 maxAge: 1000 * 60 * 59,
58 });
59 const Octokit = get_probot_octokit_with_defaults_1.getProbotOctokitWithDefaults({
60 githubToken: options.githubToken,
61 Octokit: options.Octokit || probot_octokit_1.ProbotOctokit,
62 appId: Number(options.appId),
63 privateKey: options.privateKey,
64 cache,
65 log: this.log,
66 redisConfig: options.redisConfig,
67 throttleOptions: options.throttleOptions,
68 baseUrl: options.baseUrl,
69 });
70 const octokit = new Octokit();
71 this.state = {
72 cache,
73 githubToken: options.githubToken,
74 log: this.log,
75 Octokit,
76 octokit,
77 webhooks: {
78 path: options.webhookPath,
79 secret: options.secret,
80 },
81 appId: Number(options.appId),
82 privateKey: options.privateKey,
83 host: options.host,
84 port: options.port,
85 webhookProxy: options.webhookProxy,
86 };
87 this.auth = auth_1.auth.bind(null, this.state);
88 this.webhooks = get_webhooks_1.getWebhooks(this.state);
89 this.on = (eventNameOrNames, callback) => {
90 // when an app subscribes to an event using `app.on(event, callback)`, Probot sends a request to `GET /app` and
91 // verifies if the app is subscribed to the event and logs a warning if it is not.
92 //
93 // This feature will be moved out of Probot core as it has side effects and does not work in a stateless environment.
94 webhook_event_check_1.webhookEventCheck(this.state, eventNameOrNames);
95 if (eventNameOrNames === "*") {
96 // @ts-ignore this workaround is only to surpress a warning. The `.on()` method will be deprecated soon anyway.
97 return this.webhooks.onAny(callback);
98 }
99 return this.webhooks.on(eventNameOrNames, callback);
100 };
101 this.server = create_server_1.createServer({
102 webhook: this.webhooks.middleware,
103 logger: this.log,
104 });
105 this.version = version_1.VERSION;
106 // TODO: remove once Application class was removed
107 this.internalRouter = express_1.default.Router();
108 }
109 static async run(appFn) {
110 const log = get_log_1.getLog({
111 level: process.env.LOG_LEVEL,
112 logFormat: process.env.LOG_FORMAT,
113 logLevelInString: process.env.LOG_LEVEL_IN_STRING === "true",
114 sentryDsn: process.env.SENTRY_DSN,
115 });
116 log.warn(new deprecation_1.Deprecation('[probot] "Probot.run" is deprecate. Import { run } from "probot" instead'));
117 return run_1.run(appFn);
118 }
119 static defaults(defaults) {
120 const ProbotWithDefaults = class extends this {
121 constructor(...args) {
122 const options = args[0] || {};
123 super(Object.assign({}, defaults, options));
124 }
125 };
126 return ProbotWithDefaults;
127 }
128 /**
129 * @deprecated `probot.webhook` is deprecated. Use `probot.webhooks` instead
130 */
131 get webhook() {
132 this.log.warn(new deprecation_1.Deprecation(`[probot] "probot.webhook" is deprecated. Use "probot.webhooks" instead`));
133 return this.webhooks;
134 }
135 receive(event) {
136 this.log.debug({ event }, "Webhook received");
137 return this.webhooks.receive(event);
138 }
139 load(appFn) {
140 if (typeof appFn === "string") {
141 this.log.warn(new deprecation_1.Deprecation(`[probot] passing a string to "probot.load()" is deprecated. Pass the function from "${appFn}" instead.`));
142 }
143 const router = express_1.default.Router();
144 // Connect the router from the app to the server
145 this.server.use(router);
146 // Initialize the ApplicationFunction
147 load_1.load(this, router, appFn);
148 return this;
149 }
150 setup(appFns) {
151 this.log.warn(new deprecation_1.Deprecation(`[probot] "probot.setup()" is deprecated. Use the new "Server" class instead:
152
153 const { Server, Probot } = require("probot")
154 const server = new Server({
155 // optional:
156 host,
157 port,
158 webhookPath,
159 webhookProxy,
160 Probot: Probot.defaults({ id, privateKey, ... })
161 })
162
163 // load probot app function
164 await server.load(({ app }) => {})
165
166 // start listening to requests
167 await server.start()
168 // stop server with: await server.stop()
169
170If you have more than one app function, combine them in a function instead
171
172 const app1 = require("./app1")
173 const app2 = require("./app2")
174
175 module.exports = function app ({ probot, getRouter }) {
176 await app1({ probot, getRouter })
177 await app2({ probot, getRouter })
178 }
179`));
180 // Log all unhandled rejections
181 process.on("unhandledRejection", get_error_handler_1.getErrorHandler(this.log));
182 // Load the given appFns along with the default ones
183 appFns.concat(defaultAppFns).forEach((appFn) => this.load(appFn));
184 }
185 start() {
186 this.log.warn(new deprecation_1.Deprecation(`[probot] "probot.start()" is deprecated. Use the new "Server" class instead:
187
188 const { Server, Probot } = require("probot")
189 const server = new Server({
190 // optional:
191 host,
192 port,
193 webhookPath,
194 webhookProxy,
195 Probot: Probot.defaults({ id, privateKey, ... })
196 })
197
198 // load probot app function
199 await server.load(({ app }) => {})
200
201 // start listening to requests
202 await server.start()
203 // stop server with: await server.stop()
204`));
205 this.log.info(`Running Probot v${this.version} (Node.js: ${process.version})`);
206 const port = this.state.port || 3000;
207 const { host, webhookProxy } = this.state;
208 const webhookPath = this.state.webhooks.path;
209 const printableHost = host !== null && host !== void 0 ? host : "localhost";
210 this.httpServer = this.server
211 .listen(port, ...(host ? [host] : []), () => {
212 if (webhookProxy) {
213 webhook_proxy_1.createWebhookProxy({
214 logger: this.log,
215 path: webhookPath,
216 port: port,
217 url: webhookProxy,
218 });
219 }
220 this.log.info(`Listening on http://${printableHost}:${port}`);
221 })
222 .on("error", (error) => {
223 if (error.code === "EADDRINUSE") {
224 this.log.error(`Port ${port} is already in use. You can define the PORT environment variable to use a different port.`);
225 }
226 else {
227 this.log.error(error);
228 }
229 process.exit(1);
230 });
231 return this.httpServer;
232 }
233 stop() {
234 if (!this.httpServer)
235 return;
236 this.httpServer.close();
237 }
238 /**
239 * Get an {@link http://expressjs.com|express} router that can be used to
240 * expose HTTP endpoints
241 *
242 * ```
243 * module.exports = ({ app, getRouter }) => {
244 * // Get an express router to expose new HTTP endpoints
245 * const router = getRouter('/my-app');
246 *
247 * // Use any middleware
248 * router.use(require('express').static(__dirname + '/public'));
249 *
250 * // Add a new route
251 * router.get('/hello-world', (req, res) => {
252 * res.end('Hello World');
253 * });
254 * };
255 * ```
256 *
257 * @param path - the prefix for the routes* @param path
258 *
259 * @deprecated "app.route()" is deprecated, use the "getRouter()" argument from the app function instead: "({ app, getRouter }) => { ... }"
260 */
261 route(path) {
262 this.log.warn(new deprecation_1.Deprecation(`[probot] "app.route()" is deprecated, use the "getRouter()" argument from the app function instead: "({ app, getRouter }) => { ... }"`));
263 return get_router_1.getRouter(this.internalRouter, path);
264 }
265 /**
266 * @deprecated use probot.log instead
267 */
268 get logger() {
269 this.log.warn(new deprecation_1.Deprecation(`[probot] "probot.logger" is deprecated. Use "probot.log" instead`));
270 return this.log;
271 }
272 /**
273 * @deprecated "app.router" is deprecated, use "getRouter()" from the app function instead: "({ app, getRouter }) => { ... }"
274 */
275 get router() {
276 this.log.warn(new deprecation_1.Deprecation(`[probot] "app.router" is deprecated, use "getRouter()" from the app function instead: "({ app, getRouter }) => { ... }"`));
277 return this.internalRouter;
278 }
279}
280exports.Probot = Probot;
281Probot.version = version_1.VERSION;
282//# sourceMappingURL=probot.js.map
\No newline at end of file