@adobe/helix-deploy 4.12.2 → 4.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,6 +14,7 @@ const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
14
14
  const path = require('path');
15
15
  const fs = require('fs');
16
16
  const semver = require('semver');
17
+ const chalk = require('chalk');
17
18
  const BaseDeployer = require('./BaseDeployer');
18
19
  const GoogleConfig = require('./GoogleConfig.js');
19
20
  const { filterActions } = require('../utils.js');
@@ -59,7 +60,7 @@ class GoogleDeployer extends BaseDeployer {
59
60
  projectId: this._cfg.projectID,
60
61
  });
61
62
  } catch (e) {
62
- this.log.error(`Unable to authenticate with Google: ${e.message}`);
63
+ this.log.error(chalk`{red error:} Unable to authenticate with Google: ${e.message}`);
63
64
  throw e;
64
65
  }
65
66
  }
@@ -82,9 +83,9 @@ class GoogleDeployer extends BaseDeployer {
82
83
  },
83
84
  secretId,
84
85
  });
85
- this.log.info(`Created secret ${secret.name}`);
86
+ this.log.info(`--: Created secret ${secret.name}`);
86
87
  } catch {
87
- this.log.info('Using existing secret');
88
+ this.log.info('--: Using existing secret');
88
89
  [secret] = await this._secretclient.getSecret({
89
90
  name: `${parent}/secrets/${secretId}`,
90
91
  });
@@ -98,7 +99,7 @@ class GoogleDeployer extends BaseDeployer {
98
99
  },
99
100
  });
100
101
 
101
- this.log.info(`Added secret version ${version.name}`);
102
+ this.log.info(chalk`{green ok}: Added secret version ${version.name}`);
102
103
 
103
104
  /*
104
105
  const [retversion] = await this._secretclient.accessSecretVersion({
@@ -191,23 +192,23 @@ class GoogleDeployer extends BaseDeployer {
191
192
  function: func,
192
193
  });
193
194
 
194
- this.log.info('updating existing function');
195
+ this.log.info('--: updating existing function');
195
196
  const [res] = await op.promise();
196
197
  this._function = res;
197
- this.log.info('function deployed');
198
+ this.log.info(chalk`{green ok:} function deployed`);
198
199
  } else {
199
200
  const [op] = await this._client.createFunction({
200
201
  location: `projects/${this._cfg.projectID}/locations/${this._cfg.region}`,
201
202
  function: func,
202
203
  });
203
204
 
204
- this.log.info('creating function, please wait (Google deployments are slow).');
205
+ this.log.info('--: creating function, please wait (Google deployments are slow).');
205
206
  const [res] = await op.promise();
206
207
  this._function = res;
207
- this.log.info('function deployed');
208
+ this.log.info(chalk`{green ok:} function deployed`);
208
209
  }
209
210
 
210
- this.log.info('enabling unauthenticated requests');
211
+ this.log.info('--: enabling unauthenticated requests');
211
212
  await this._client.setIamPolicy({
212
213
  resource: name,
213
214
  policy: {
@@ -222,11 +223,8 @@ class GoogleDeployer extends BaseDeployer {
222
223
  },
223
224
  });
224
225
  } catch (err) {
225
- this.log.error(err);
226
- // eslint-disable-next-line max-len
227
- this.log.error('bad request:', err.metadata.internalRepr.get('google.rpc.badrequest-bin').toString());
228
- // eslint-disable-next-line max-len
229
- this.log.error('details:', err.metadata.internalRepr.get('grpc-status-details-bin').toString());
226
+ this.log.error(chalk`{red error:} bad request: ${err.metadata.internalRepr.get('google.rpc.badrequest-bin').toString()}`);
227
+ this.log.error(chalk`{red error:} details: ${err.metadata.internalRepr.get('grpc-status-details-bin').toString()}`);
230
228
  throw err;
231
229
  }
232
230
 
@@ -239,8 +237,7 @@ class GoogleDeployer extends BaseDeployer {
239
237
  await this.createFunction();
240
238
  } catch (err) {
241
239
  const message = err.metadata ? err.metadata.get('grpc-status-details-bin')[0].toString() : err.message;
242
- this.log.error(`Unable to deploy Google Cloud function: ${message}`, err.metadata);
243
-
240
+ this.log.error(chalk`{red error:} Unable to deploy Google Cloud function: ${message}`, err.metadata);
244
241
  throw err;
245
242
  }
246
243
  }
@@ -299,15 +296,14 @@ class GoogleDeployer extends BaseDeployer {
299
296
  },
300
297
  versionspec,
301
298
  ).map((fn) => {
302
- this.log.info(`Cleaning up outdated function '${fn.fqName}`);
299
+ this.log.info(`--: Cleaning up outdated function '${fn.fqName}`);
303
300
 
304
301
  return this._client.deleteFunction({
305
302
  name: fn.fqName,
306
303
  });
307
304
  }));
308
305
  } catch (e) {
309
- this.log.error('Cleanup failed, proceeding anyway.');
310
- this.log.error(e);
306
+ this.log.error(chalk`{red error:} Cleanup failed, proceeding anyway.`, e);
311
307
  }
312
308
  }
313
309
 
@@ -10,6 +10,7 @@
10
10
  * governing permissions and limitations under the License.
11
11
  */
12
12
  const Fastly = require('@adobe/fastly-native-promises');
13
+ const chalk = require('chalk');
13
14
  const {
14
15
  toString, vcl, time, req, res, str, concat,
15
16
  } = require('@adobe/fastly-native-promises').loghelpers;
@@ -29,20 +30,15 @@ class FastlyGateway {
29
30
  }
30
31
 
31
32
  ready() {
32
- return !!this._cfg.service && !!this._cfg.auth && !!this._cfg.checkpath;
33
+ return !!this._cfg.service && !!this._cfg.auth;
33
34
  }
34
35
 
35
- /**
36
- * A weaker version of `ready` that works without a check path
37
- * and checks whether links can be updated.
38
- * @returns boolean true if links can be updated
39
- */
40
- updateable() {
41
- return !!this._cfg.service && !!this._cfg.auth;
36
+ canDeploy() {
37
+ return this.ready() && this._deployers.length > 0;
42
38
  }
43
39
 
44
40
  async updateLinks(links, version) {
45
- this.log.info(`Updating links on the Gateway for version ${version}`);
41
+ this.log.info(`--: updating links on the Gateway for version ${version}...`);
46
42
  const fakeDeployer = new BaseDeployer({
47
43
  links, version, log: this.log,
48
44
  });
@@ -58,6 +54,7 @@ class FastlyGateway {
58
54
 
59
55
  await this._fastly.bulkUpdateDictItems(undefined, 'aliases', ...versionstrings);
60
56
  this._fastly.discard();
57
+ this.log.info(chalk`{green ok:} updated links on the Gateway for version ${version}.`);
61
58
  }
62
59
 
63
60
  init() {
@@ -75,6 +72,25 @@ class FastlyGateway {
75
72
  return this.cfg.log;
76
73
  }
77
74
 
75
+ async updatePackage() {
76
+ this.log.info('--: updating app (package) parameters on Fastly gateway ...');
77
+
78
+ const packageparams = Object
79
+ .entries(this.cfg.packageParams)
80
+ .map(([key, value]) => ({
81
+ item_key: `${this.cfg.packageName}.${key}`,
82
+ item_value: value,
83
+ op: 'update',
84
+ }));
85
+
86
+ if (packageparams.length !== 0) {
87
+ await this._fastly.bulkUpdateDictItems(undefined, 'packageparams', ...packageparams);
88
+ }
89
+ await this._fastly.updateDictItem(undefined, 'tokens', this.cfg.packageToken, `${Math.floor(Date.now() / 1000) + (365 * 24 * 3600)}`);
90
+ this._fastly.discard();
91
+ this.log.info(chalk`{green ok:} updating app (package) parameters on Fastly gateway.`);
92
+ }
93
+
78
94
  selectBackendVCL() {
79
95
  // declare a local variable for each backend
80
96
  const init = this._deployers.map((deployer) => `declare local var.${deployer.name.toLowerCase()} INTEGER;`);
@@ -109,6 +125,28 @@ class FastlyGateway {
109
125
  return [...init, ...set, ...increment].join('\n') + [backendvcl, ...middle, fallback].join(' else ');
110
126
  }
111
127
 
128
+ /**
129
+ * Generates a VCL snippet (for each package deployed) that lists all package parameter
130
+ * names and looks up their values from the secret edge dictionary.
131
+ * @returns {string} VCL snippet to look up package parameters from edge dict
132
+ */
133
+ listPackageParamsVCL() {
134
+ const pre = `
135
+ if (obj.status == 600 && req.url.path ~ "^/${this.cfg.packageName}/") {
136
+ set obj.status = 200;
137
+ set obj.response = "OK";
138
+ set obj.http.content-type = "application/json";
139
+ synthetic "{" + `;
140
+ const post = `+ "}";
141
+ return(deliver);
142
+ }`;
143
+ const middle = Object
144
+ .keys(this.cfg.packageParams)
145
+ .map((paramname, index) => `"%22${paramname}%22:%22" json.escape(table.lookup(packageparams, "${this.cfg.packageName}.${paramname}")) "%22${(index + 1) < Object.keys(this.cfg.packageParams).length ? ',' : ''}"`).join(' + ');
146
+
147
+ return pre + middle + post;
148
+ }
149
+
112
150
  setURLVCL() {
113
151
  const pre = `
114
152
  declare local var.package STRING;
@@ -150,7 +188,7 @@ if (req.url ~ "^/([^/]+)/([^/@_]+)([@_]([^/@_?]+)+)?(.*$)") {
150
188
 
151
189
  async enableLogging(version) {
152
190
  if (this._cfg.coralogixToken) {
153
- this.log.info('Set up Gateway logging to Coralogix');
191
+ this.log.info(chalk`--: Set up Gateway logging to {yellow Coralogix}`);
154
192
  await this._fastly.writeHttps(version, 'helix-coralogix', {
155
193
  name: 'helix-coralogix',
156
194
  format: toString({
@@ -263,165 +301,206 @@ if (req.url ~ "^/([^/]+)/([^/@_]+)([@_]([^/@_?]+)+)?(.*$)") {
263
301
  }
264
302
 
265
303
  async deploy() {
266
- this.log.info('Set up Fastly Gateway');
267
-
268
- await this._fastly.transact(async (newversion) => {
269
- await this.enableLogging(newversion);
270
-
271
- this.log.info('create condition');
272
- await this._fastly.writeCondition(newversion, 'false', {
273
- name: 'false',
274
- statement: 'false',
275
- type: 'request',
276
- });
277
-
278
- await this._fastly.writeDictionary(newversion, 'priorities', {
279
- name: 'priorities',
280
- write_only: 'false',
281
- });
282
-
283
- await this._fastly.writeDictionary(newversion, 'aliases', {
284
- name: 'aliases',
285
- write_only: 'false',
286
- });
287
-
288
- if (this._cfg.checkinterval > 0) {
289
- // set up health checks
304
+ this.log.info(chalk`--: Set up {yellow Fastly} Gateway`);
305
+ try {
306
+ await this._fastly.transact(async (newversion) => {
307
+ await this.enableLogging(newversion);
308
+
309
+ this.log.info('--: create condition');
310
+ await this._fastly.writeCondition(newversion, 'false', {
311
+ name: 'false',
312
+ statement: 'false',
313
+ type: 'request',
314
+ });
315
+
316
+ this.log.info('--: create dictionaries');
317
+ await this._fastly.writeDictionary(newversion, 'priorities', {
318
+ name: 'priorities',
319
+ write_only: 'false',
320
+ });
321
+
322
+ await this._fastly.writeDictionary(newversion, 'aliases', {
323
+ name: 'aliases',
324
+ write_only: 'false',
325
+ });
326
+
327
+ await this._fastly.writeDictionary(newversion, 'tokens', {
328
+ name: 'tokens',
329
+ write_only: 'false',
330
+ });
331
+
332
+ await this._fastly.writeDictionary(newversion, 'packageparams', {
333
+ name: 'packageparams',
334
+ write_only: 'true',
335
+ });
336
+
337
+ if (this._cfg.checkinterval > 0 && this._cfg.checkpath) {
338
+ this.log.info('--: setup health-check');
339
+ // set up health checks
340
+ await Promise.all(this._deployers
341
+ .map((deployer) => ({
342
+ check_interval: this._cfg.checkinterval,
343
+ expected_response: 200,
344
+ host: deployer.host,
345
+ http_version: '1.1',
346
+ method: 'GET',
347
+ initial: 1,
348
+ name: `${deployer.name}Check`,
349
+ path: `${deployer.basePath}${this._cfg.checkpath}`,
350
+ threshold: 2,
351
+ timeout: 5000,
352
+ window: 3,
353
+ }))
354
+ .map((healthcheck) => this._fastly
355
+ .writeHealthcheck(newversion, healthcheck.name, healthcheck)));
356
+ }
357
+
358
+ // set up backends
290
359
  await Promise.all(this._deployers
291
360
  .map((deployer) => ({
292
- check_interval: this._cfg.checkinterval,
293
- expected_response: 200,
294
- host: deployer.host,
295
- http_version: '1.1',
296
- method: 'GET',
297
- initial: 1,
298
- name: `${deployer.name}Check`,
299
- path: deployer.basePath + this._cfg.checkpath,
300
- threshold: 2,
301
- timeout: 5000,
302
- window: 3,
361
+ hostname: deployer.host,
362
+ ssl_cert_hostname: deployer.host,
363
+ ssl_sni_hostname: deployer.host,
364
+ address: deployer.host,
365
+ override_host: deployer.host,
366
+ name: deployer.name,
367
+ error_threshold: 0,
368
+ first_byte_timeout: 60000,
369
+ weight: 100,
370
+ connect_timeout: 5000,
371
+ port: 443,
372
+ between_bytes_timeout: 10000,
373
+ shield: '', // 'bwi-va-us',
374
+ max_conn: 200,
375
+ use_ssl: true,
376
+ request_condition: 'false',
303
377
  }))
304
- .map((healthcheck) => this._fastly
305
- .writeHealthcheck(newversion, healthcheck.name, healthcheck)));
306
- }
307
-
308
- // set up backends
309
- await Promise.all(this._deployers
310
- .map((deployer) => ({
311
- hostname: deployer.host,
312
- ssl_cert_hostname: deployer.host,
313
- ssl_sni_hostname: deployer.host,
314
- address: deployer.host,
315
- override_host: deployer.host,
316
- name: deployer.name,
317
- error_threshold: 0,
318
- first_byte_timeout: 60000,
319
- weight: 100,
320
- connect_timeout: 5000,
321
- port: 443,
322
- between_bytes_timeout: 10000,
323
- shield: '', // 'bwi-va-us',
324
- max_conn: 200,
325
- use_ssl: true,
326
- request_condition: 'false',
327
- }))
328
- .map((backend) => {
329
- const retval = backend;
330
- if (this._cfg.checkinterval > 0) {
331
- retval.healthcheck = `${backend.name}Check`;
332
- }
333
- return retval;
334
- })
335
- .map(async (backend) => {
336
- try {
337
- return await this._fastly.createBackend(newversion, backend);
338
- } catch (e) {
339
- return this._fastly.updateBackend(newversion, backend.name, backend);
340
- }
341
- }));
342
-
343
- await this._fastly.writeSnippet(newversion, 'backend', {
344
- name: 'backend',
345
- priority: 10,
346
- dynamic: 0,
347
- type: 'recv',
348
- content: this.selectBackendVCL(),
349
- });
350
-
351
- await this._fastly.writeSnippet(newversion, 'missurl', {
352
- name: 'missurl',
353
- priority: 10,
354
- dynamic: 0,
355
- type: 'miss',
356
- content: this.setURLVCL(),
357
- });
358
-
359
- await this._fastly.writeSnippet(newversion, 'passurl', {
360
- name: 'passurl',
361
- priority: 10,
362
- dynamic: 0,
363
- type: 'pass',
364
- content: this.setURLVCL(),
365
- });
366
-
367
- await this._fastly.writeSnippet(newversion, 'logurl', {
368
- name: 'logurl',
369
- priority: 10,
370
- dynamic: 0,
371
- type: 'fetch',
372
- content: `set beresp.http.X-Backend-URL = bereq.url;
373
- set beresp.http.X-Backend-Name = req.backend;
374
- set beresp.http.X-Backend-Health = req.http.X-Backend-Health;
375
- set beresp.cacheable = false;`,
376
- });
377
-
378
- await this._fastly.writeSnippet(newversion, 'stashsurrogates', {
379
- name: 'stashsurrogates',
380
- priority: 10,
381
- dynamic: 0,
382
- type: 'fetch',
383
- content: `
384
- set beresp.http.X-Surrogate-Key = beresp.http.Surrogate-Key;
385
- set beresp.http.X-Surrogate-Control = beresp.http.Surrogate-Control;`,
386
- });
387
-
388
- let restartcontent = `
389
- # restart the request in case of flakiness
390
- if (req.restarts < 2 && (resp.status == 503 || resp.status == 504) && (req.request == "GET" || req.request == "HEAD" || req.request == "PUT" || req.request == "DELETE")) {
391
- restart;
392
- }
393
- set resp.http.x-gateway-restarts = req.restarts;
394
- unset resp.http.Fastly-Restarts;`;
395
-
396
- if (this._deployers.find((deployer) => deployer.name === 'Google')) {
397
- restartcontent += `
398
- # If Google can't find a function, it sends a redirect to the login page instead
399
- # of a 404. This fixes it.
400
- if (resp.status == 302 && req.backend == F_Google && resp.http.Location ~ "^https://accounts.google.com/ServiceLogin") {
401
- set resp.status = 404;
402
- }
403
- `;
404
- }
405
- await this._fastly.writeSnippet(newversion, 'restart', {
406
- name: 'restart',
407
- priority: 10,
408
- dynamic: 0,
409
- type: 'deliver',
410
- content: restartcontent,
411
- });
412
-
413
- await this._fastly.writeSnippet(newversion, 'restoresurrogates', {
414
- name: 'restoresurrogates',
415
- priority: 10,
416
- dynamic: 0,
417
- type: 'deliver',
418
- content: `
419
- set resp.http.Surrogate-Key = resp.http.X-Surrogate-Key;
420
- set resp.http.Surrogate-Control = resp.http.X-Surrogate-Control;`,
421
- });
422
- }, true);
423
-
424
- this._fastly.discard();
378
+ .map((backend) => {
379
+ const retval = backend;
380
+ if (this._cfg.checkinterval > 0 && this._cfg.checkpath) {
381
+ retval.healthcheck = `${backend.name}Check`;
382
+ }
383
+ return retval;
384
+ })
385
+ .map(async (backend) => {
386
+ this.log.info(`--: create backend ${backend.name} -> ${backend.hostname}`);
387
+ try {
388
+ return await this._fastly.createBackend(newversion, backend);
389
+ } catch (e) {
390
+ return this._fastly.updateBackend(newversion, backend.name, backend);
391
+ }
392
+ }));
393
+
394
+ this.log.info('--: write VLC snippets');
395
+ await this._fastly.writeSnippet(newversion, 'packageparams.auth', {
396
+ name: 'packageparams.auth',
397
+ priority: 9,
398
+ dynamic: 0,
399
+ type: 'recv',
400
+ content: `
401
+ if (req.http.Authorization) {
402
+ if(time.is_after(std.time(table.lookup(tokens, regsub(req.http.Authorization, "^Bearer ", ""), "expired"), std.integer2time(0)), time.start)) {
403
+ error 600 "Get Package Params";
404
+ }
405
+ }`,
406
+ });
407
+
408
+ await this._fastly.writeSnippet(newversion, `${this.cfg.packageName}.params`, {
409
+ name: `${this.cfg.packageName}.params`,
410
+ priority: 10,
411
+ dynamic: 0,
412
+ type: 'error',
413
+ content: this.listPackageParamsVCL(),
414
+ });
415
+
416
+ await this._fastly.writeSnippet(newversion, 'backend', {
417
+ name: 'backend',
418
+ priority: 10,
419
+ dynamic: 0,
420
+ type: 'recv',
421
+ content: this.selectBackendVCL(),
422
+ });
423
+
424
+ await this._fastly.writeSnippet(newversion, 'missurl', {
425
+ name: 'missurl',
426
+ priority: 10,
427
+ dynamic: 0,
428
+ type: 'miss',
429
+ content: this.setURLVCL(),
430
+ });
431
+
432
+ await this._fastly.writeSnippet(newversion, 'passurl', {
433
+ name: 'passurl',
434
+ priority: 10,
435
+ dynamic: 0,
436
+ type: 'pass',
437
+ content: this.setURLVCL(),
438
+ });
439
+
440
+ await this._fastly.writeSnippet(newversion, 'logurl', {
441
+ name: 'logurl',
442
+ priority: 10,
443
+ dynamic: 0,
444
+ type: 'fetch',
445
+ content: `set beresp.http.X-Backend-URL = bereq.url;
446
+ set beresp.http.X-Backend-Name = req.backend;
447
+ set beresp.http.X-Backend-Health = req.http.X-Backend-Health;
448
+ set beresp.cacheable = false;`,
449
+ });
450
+
451
+ await this._fastly.writeSnippet(newversion, 'stashsurrogates', {
452
+ name: 'stashsurrogates',
453
+ priority: 10,
454
+ dynamic: 0,
455
+ type: 'fetch',
456
+ content: `
457
+ set beresp.http.X-Surrogate-Key = beresp.http.Surrogate-Key;
458
+ set beresp.http.X-Surrogate-Control = beresp.http.Surrogate-Control;`,
459
+ });
460
+
461
+ let restartcontent = `
462
+ # restart the request in case of flakiness
463
+ if (req.restarts < 2 && (resp.status == 503 || resp.status == 504) && (req.request == "GET" || req.request == "HEAD" || req.request == "PUT" || req.request == "DELETE")) {
464
+ restart;
465
+ }
466
+ set resp.http.x-gateway-restarts = req.restarts;
467
+ unset resp.http.Fastly-Restarts;`;
468
+
469
+ if (this._deployers.find((deployer) => deployer.name === 'Google')) {
470
+ restartcontent += `
471
+ # If Google can't find a function, it sends a redirect to the login page instead
472
+ # of a 404. This fixes it.
473
+ if (resp.status == 302 && req.backend == F_Google && resp.http.Location ~ "^https://accounts.google.com/ServiceLogin") {
474
+ set resp.status = 404;
475
+ }
476
+ `;
477
+ }
478
+ await this._fastly.writeSnippet(newversion, 'restart', {
479
+ name: 'restart',
480
+ priority: 10,
481
+ dynamic: 0,
482
+ type: 'deliver',
483
+ content: restartcontent,
484
+ });
485
+
486
+ await this._fastly.writeSnippet(newversion, 'restoresurrogates', {
487
+ name: 'restoresurrogates',
488
+ priority: 10,
489
+ dynamic: 0,
490
+ type: 'deliver',
491
+ content: `
492
+ set resp.http.Surrogate-Key = resp.http.X-Surrogate-Key;
493
+ set resp.http.Surrogate-Control = resp.http.X-Surrogate-Control;`,
494
+ });
495
+ }, true);
496
+
497
+ this.log.info(chalk`{green ok}: Set up {yellow Fastly} Gateway done.`);
498
+ } catch (e) {
499
+ this.log.error(chalk`{red error}: failed to setup gateway: ${e.message}`);
500
+ throw e;
501
+ } finally {
502
+ this._fastly.discard();
503
+ }
425
504
  }
426
505
  }
427
506
 
@@ -0,0 +1,20 @@
1
+ /*
2
+ * Copyright 2021 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ 'use strict';
14
+
15
+ const index = import('../index.js');
16
+
17
+ exports.handler = async (...args) => {
18
+ const { default: { lambda } } = await index;
19
+ return lambda(...args);
20
+ };
@@ -0,0 +1,62 @@
1
+ /*
2
+ * Copyright 2021 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+ /* eslint-env serviceworker */
13
+
14
+ async function handler(event) {
15
+ // console.log(event);
16
+ const { request } = event;
17
+ // eslint-disable-next-line import/no-unresolved,global-require
18
+ const { main } = require('./main.js');
19
+ const context = {
20
+ resolver: null,
21
+ pathInfo: {
22
+ suffix: request.url.replace(/\?.*/, ''),
23
+ },
24
+ runtime: {
25
+ name: 'cloudflare-workers',
26
+ region: request.cf.colo,
27
+ },
28
+ func: {
29
+ name: null,
30
+ package: null,
31
+ version: null,
32
+ fqn: null,
33
+ app: null,
34
+ },
35
+ invocation: {
36
+ id: null,
37
+ deadline: null,
38
+ transactionId: null,
39
+ requestId: null,
40
+ },
41
+ env: new Proxy(globalThis, {
42
+ get: (target, prop) => target[prop] || target.PACKAGE.get(prop),
43
+ }),
44
+ storage: null,
45
+ };
46
+ const response = await main(request, context);
47
+ return response;
48
+ }
49
+
50
+ function cloudflare() {
51
+ console.log('checking for cloudflare environment');
52
+ try {
53
+ if (caches && caches.default) {
54
+ return handler;
55
+ }
56
+ } catch {
57
+ return false;
58
+ }
59
+ return false;
60
+ }
61
+
62
+ module.exports = cloudflare;