UNPKG

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