@dereekb/nestjs 13.38.0 → 13.40.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.
Files changed (39) hide show
  1. package/eslint/package.json +7 -7
  2. package/mailgun/package.json +11 -11
  3. package/openai/package.json +11 -11
  4. package/openrouter/package.json +8 -8
  5. package/package.json +27 -35
  6. package/stripe/package.json +11 -11
  7. package/twilio/index.esm.js +18 -1
  8. package/twilio/package.json +11 -11
  9. package/twilio/src/lib/twilio.api.d.ts +1 -1
  10. package/twilio/src/lib/twilio.interop.d.ts +7 -0
  11. package/typeform/package.json +11 -11
  12. package/vapiai/package.json +11 -11
  13. package/eslint/index.cjs.default.js +0 -1
  14. package/eslint/index.cjs.js +0 -418
  15. package/eslint/index.cjs.mjs +0 -2
  16. package/index.cjs.default.js +0 -1
  17. package/index.cjs.js +0 -2789
  18. package/index.cjs.mjs +0 -2
  19. package/mailgun/index.cjs.default.js +0 -1
  20. package/mailgun/index.cjs.js +0 -1802
  21. package/mailgun/index.cjs.mjs +0 -2
  22. package/openai/index.cjs.default.js +0 -1
  23. package/openai/index.cjs.js +0 -1068
  24. package/openai/index.cjs.mjs +0 -2
  25. package/openrouter/index.cjs.default.js +0 -1
  26. package/openrouter/index.cjs.js +0 -1200
  27. package/openrouter/index.cjs.mjs +0 -2
  28. package/stripe/index.cjs.default.js +0 -1
  29. package/stripe/index.cjs.js +0 -780
  30. package/stripe/index.cjs.mjs +0 -2
  31. package/twilio/index.cjs.default.js +0 -1
  32. package/twilio/index.cjs.js +0 -2184
  33. package/twilio/index.cjs.mjs +0 -2
  34. package/typeform/index.cjs.default.js +0 -1
  35. package/typeform/index.cjs.js +0 -1182
  36. package/typeform/index.cjs.mjs +0 -2
  37. package/vapiai/index.cjs.default.js +0 -1
  38. package/vapiai/index.cjs.js +0 -1055
  39. package/vapiai/index.cjs.mjs +0 -2
package/index.cjs.js DELETED
@@ -1,2789 +0,0 @@
1
- 'use strict';
2
-
3
- var rxjs = require('@dereekb/rxjs');
4
- var promises = require('node:fs/promises');
5
- var node_path = require('node:path');
6
- var common = require('@nestjs/common');
7
- var rawbody = require('raw-body');
8
- var node_querystring = require('node:querystring');
9
- var bodyParser = require('body-parser');
10
- var util = require('@dereekb/util');
11
- var config = require('@nestjs/config');
12
- var node_fs = require('node:fs');
13
- var node_crypto = require('node:crypto');
14
-
15
- function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
16
- try {
17
- var info = gen[key](arg);
18
- var value = info.value;
19
- } catch (error) {
20
- reject(error);
21
- return;
22
- }
23
- if (info.done) {
24
- resolve(value);
25
- } else {
26
- Promise.resolve(value).then(_next, _throw);
27
- }
28
- }
29
- function _async_to_generator$2(fn) {
30
- return function() {
31
- var self = this, args = arguments;
32
- return new Promise(function(resolve, reject) {
33
- var gen = fn.apply(self, args);
34
- function _next(value) {
35
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
36
- }
37
- function _throw(err) {
38
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
39
- }
40
- _next(undefined);
41
- });
42
- };
43
- }
44
- function _ts_generator$2(thisArg, body) {
45
- var f, y, t, _ = {
46
- label: 0,
47
- sent: function() {
48
- if (t[0] & 1) throw t[1];
49
- return t[1];
50
- },
51
- trys: [],
52
- ops: []
53
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
54
- return d(g, "next", {
55
- value: verb(0)
56
- }), d(g, "throw", {
57
- value: verb(1)
58
- }), d(g, "return", {
59
- value: verb(2)
60
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
61
- value: function() {
62
- return this;
63
- }
64
- }), g;
65
- function verb(n) {
66
- return function(v) {
67
- return step([
68
- n,
69
- v
70
- ]);
71
- };
72
- }
73
- function step(op) {
74
- if (f) throw new TypeError("Generator is already executing.");
75
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
76
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
77
- if (y = 0, t) op = [
78
- op[0] & 2,
79
- t.value
80
- ];
81
- switch(op[0]){
82
- case 0:
83
- case 1:
84
- t = op;
85
- break;
86
- case 4:
87
- _.label++;
88
- return {
89
- value: op[1],
90
- done: false
91
- };
92
- case 5:
93
- _.label++;
94
- y = op[1];
95
- op = [
96
- 0
97
- ];
98
- continue;
99
- case 7:
100
- op = _.ops.pop();
101
- _.trys.pop();
102
- continue;
103
- default:
104
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
105
- _ = 0;
106
- continue;
107
- }
108
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
109
- _.label = op[1];
110
- break;
111
- }
112
- if (op[0] === 6 && _.label < t[1]) {
113
- _.label = t[1];
114
- t = op;
115
- break;
116
- }
117
- if (t && _.label < t[2]) {
118
- _.label = t[2];
119
- _.ops.push(op);
120
- break;
121
- }
122
- if (t[2]) _.ops.pop();
123
- _.trys.pop();
124
- continue;
125
- }
126
- op = body.call(thisArg, _);
127
- } catch (e) {
128
- op = [
129
- 6,
130
- e
131
- ];
132
- y = 0;
133
- } finally{
134
- f = t = 0;
135
- }
136
- if (op[0] & 5) throw op[1];
137
- return {
138
- value: op[0] ? op[1] : void 0,
139
- done: true
140
- };
141
- }
142
- }
143
- /**
144
- * Creates an {@link AssetLoader} that reads local assets from the
145
- * filesystem using Node.js `fs/promises`.
146
- *
147
- * The ref's {@link AssetLocalPathRef.path} is resolved relative
148
- * to the configured {@link NodeJsLocalAssetLoaderConfig.basePath}.
149
- *
150
- * @param config - Filesystem configuration with base path.
151
- * @returns An {@link AssetLoader} backed by the local filesystem.
152
- *
153
- * @example
154
- * ```ts
155
- * const loader = nodeJsLocalAssetLoader({ basePath: './assets' });
156
- * loader.get(localAsset('data/districts.json')).load().subscribe((buffer) => {
157
- * // reads from ./assets/data/districts.json
158
- * });
159
- * ```
160
- */ function nodeJsLocalAssetLoader(config) {
161
- var basePath = config.basePath;
162
- var getFn = function getFn(ref) {
163
- return _async_to_generator$2(function() {
164
- var localRef, fullPath, buffer;
165
- return _ts_generator$2(this, function(_state) {
166
- switch(_state.label){
167
- case 0:
168
- localRef = ref;
169
- fullPath = node_path.resolve(basePath, localRef.path);
170
- return [
171
- 4,
172
- promises.readFile(fullPath)
173
- ];
174
- case 1:
175
- buffer = _state.sent();
176
- return [
177
- 2,
178
- buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)
179
- ];
180
- }
181
- });
182
- })();
183
- };
184
- return rxjs.assetLoaderFromGetFn(getFn);
185
- }
186
-
187
- /**
188
- * Creates NestJS module metadata that provides an {@link AssetLoader}
189
- * using {@link delegatedAssetLoader} with Node.js-specific leaf loaders.
190
- *
191
- * Local assets are loaded from the filesystem. Remote assets (which always
192
- * have absolute URLs) are loaded via `fetch`.
193
- *
194
- * @param config - Local filesystem config and optional remote fetch config.
195
- * @returns NestJS {@link ModuleMetadata} that provides an {@link AssetLoader}.
196
- *
197
- * @Module (appAssetLoaderModuleMetadata({
198
- * local: { basePath: './assets' }
199
- * }))
200
- * export class AppAssetLoaderModule {}
201
- * ```
202
- *
203
- * @example
204
- * ```ts
205
- */ function appAssetLoaderModuleMetadata(config) {
206
- var local = nodeJsLocalAssetLoader(config.local);
207
- var remote = rxjs.fetchAssetLoader(config.remote);
208
- var loader = rxjs.delegatedAssetLoader({
209
- local: local,
210
- remote: remote
211
- });
212
- var providers = [
213
- {
214
- provide: rxjs.AssetLoader,
215
- useValue: loader
216
- }
217
- ];
218
- return {
219
- providers: providers,
220
- exports: [
221
- rxjs.AssetLoader
222
- ]
223
- };
224
- }
225
-
226
- /**
227
- * Returns true if the request is from localhost.
228
- */ var IsRequestFromLocalHost = common.createParamDecorator(function(data, context) {
229
- return isLocalhost(context);
230
- });
231
- /**
232
- * Returns true if the request's origin header indicates the request came from localhost.
233
- *
234
- * Checks for both http://localhost and https://localhost origins.
235
- *
236
- * @param context - The NestJS execution context containing the HTTP request.
237
- * @returns True if the request origin is localhost.
238
- */ function isLocalhost(context) {
239
- var _req_headers_origin;
240
- var req = context.switchToHttp().getRequest();
241
- var origin = (_req_headers_origin = req.headers['origin']) !== null && _req_headers_origin !== void 0 ? _req_headers_origin : '';
242
- return origin.startsWith('http://localhost') || origin.startsWith('https://localhost');
243
- }
244
-
245
- function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
246
- try {
247
- var info = gen[key](arg);
248
- var value = info.value;
249
- } catch (error) {
250
- reject(error);
251
- return;
252
- }
253
- if (info.done) {
254
- resolve(value);
255
- } else {
256
- Promise.resolve(value).then(_next, _throw);
257
- }
258
- }
259
- function _async_to_generator$1(fn) {
260
- return function() {
261
- var self = this, args = arguments;
262
- return new Promise(function(resolve, reject) {
263
- var gen = fn.apply(self, args);
264
- function _next(value) {
265
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
266
- }
267
- function _throw(err) {
268
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
269
- }
270
- _next(undefined);
271
- });
272
- };
273
- }
274
- function _ts_generator$1(thisArg, body) {
275
- var f, y, t, _ = {
276
- label: 0,
277
- sent: function() {
278
- if (t[0] & 1) throw t[1];
279
- return t[1];
280
- },
281
- trys: [],
282
- ops: []
283
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
284
- return d(g, "next", {
285
- value: verb(0)
286
- }), d(g, "throw", {
287
- value: verb(1)
288
- }), d(g, "return", {
289
- value: verb(2)
290
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
291
- value: function() {
292
- return this;
293
- }
294
- }), g;
295
- function verb(n) {
296
- return function(v) {
297
- return step([
298
- n,
299
- v
300
- ]);
301
- };
302
- }
303
- function step(op) {
304
- if (f) throw new TypeError("Generator is already executing.");
305
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
306
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
307
- if (y = 0, t) op = [
308
- op[0] & 2,
309
- t.value
310
- ];
311
- switch(op[0]){
312
- case 0:
313
- case 1:
314
- t = op;
315
- break;
316
- case 4:
317
- _.label++;
318
- return {
319
- value: op[1],
320
- done: false
321
- };
322
- case 5:
323
- _.label++;
324
- y = op[1];
325
- op = [
326
- 0
327
- ];
328
- continue;
329
- case 7:
330
- op = _.ops.pop();
331
- _.trys.pop();
332
- continue;
333
- default:
334
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
335
- _ = 0;
336
- continue;
337
- }
338
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
339
- _.label = op[1];
340
- break;
341
- }
342
- if (op[0] === 6 && _.label < t[1]) {
343
- _.label = t[1];
344
- t = op;
345
- break;
346
- }
347
- if (t && _.label < t[2]) {
348
- _.label = t[2];
349
- _.ops.push(op);
350
- break;
351
- }
352
- if (t[2]) _.ops.pop();
353
- _.trys.pop();
354
- continue;
355
- }
356
- op = body.call(thisArg, _);
357
- } catch (e) {
358
- op = [
359
- 6,
360
- e
361
- ];
362
- y = 0;
363
- } finally{
364
- f = t = 0;
365
- }
366
- if (op[0] & 5) throw op[1];
367
- return {
368
- value: op[0] ? op[1] : void 0,
369
- done: true
370
- };
371
- }
372
- }
373
- /**
374
- * NestJS parameter decorator that reads the raw request body directly from the incoming stream.
375
- *
376
- * Requires the request to still be readable (i.e., no prior body-parsing middleware has consumed it).
377
- *
378
- * @throws {BadRequestException} When the request stream is not readable
379
- *
380
- * @example
381
- * ```typescript
382
- * @Post('webhook')
383
- * handleWebhook(@ParseRawBody() body: RawBodyBuffer) { ... }
384
- * ```
385
- */ var rawBodyLogger = new common.Logger('RawBody');
386
- var ParseRawBody = common.createParamDecorator(function(_, context) {
387
- return _async_to_generator$1(function() {
388
- var req;
389
- return _ts_generator$1(this, function(_state) {
390
- req = context.switchToHttp().getRequest();
391
- if (!req.readable) {
392
- rawBodyLogger.error('RawBody request was not readable. This is generally due to bad configuration.');
393
- throw new common.BadRequestException('Invalid body');
394
- }
395
- return [
396
- 2,
397
- rawbody(req)
398
- ];
399
- });
400
- })();
401
- });
402
- /**
403
- * NestJS parameter decorator that retrieves the already-parsed raw body buffer from `req.body`.
404
- *
405
- * Expects that a prior middleware (e.g., raw body middleware) has already set `req.body` to a Buffer.
406
- *
407
- * @throws {InternalServerErrorException} When `req.body` is not a Buffer
408
- *
409
- * @example
410
- * ```typescript
411
- * @Post('webhook')
412
- * handleWebhook(@RawBody() body: RawBodyBuffer) { ... }
413
- * ```
414
- */ var RawBody = common.createParamDecorator(function(_, context) {
415
- return _async_to_generator$1(function() {
416
- var req, body;
417
- return _ts_generator$1(this, function(_state) {
418
- req = context.switchToHttp().getRequest();
419
- body = req.body;
420
- if (!Buffer.isBuffer(body)) {
421
- rawBodyLogger.error('RawBody expected a buffer set to req.body.');
422
- throw new common.InternalServerErrorException('failed parsing body');
423
- }
424
- return [
425
- 2,
426
- body
427
- ];
428
- });
429
- })();
430
- });
431
- /**
432
- * NestJS parameter decorator that parses the raw body buffer as a URL-encoded query string
433
- * and replaces `req.body` with the parsed result.
434
- *
435
- * @example
436
- * ```typescript
437
- * @Post('form')
438
- * handleForm(@ParsedQueryRawBody() body: ParsedUrlQuery) { ... }
439
- * ```
440
- */ var ParsedQueryRawBody = common.createParamDecorator(function(_, context) {
441
- return _async_to_generator$1(function() {
442
- var req;
443
- return _ts_generator$1(this, function(_state) {
444
- req = context.switchToHttp().getRequest();
445
- req.body = RawBodyToParsedQueryString(req.body);
446
- return [
447
- 2,
448
- req.body
449
- ];
450
- });
451
- })();
452
- });
453
- /**
454
- * Parses a raw body buffer as JSON.
455
- *
456
- * @param rawBody - The raw body buffer to parse.
457
- * @returns The parsed JSON object.
458
- * @throws {SyntaxError} When the body is not valid JSON.
459
- *
460
- * @example
461
- * ```typescript
462
- * const data = RawBodyToJson<{ id: string }>(rawBody);
463
- * ```
464
- */ function RawBodyToJson(rawBody) {
465
- var string = RawBodyToString(rawBody);
466
- return JSON.parse(string);
467
- }
468
- /**
469
- * Parses a raw body buffer as a URL-encoded query string.
470
- *
471
- * @param rawBody - The raw body buffer to parse.
472
- * @returns The parsed query parameters.
473
- *
474
- * @example
475
- * ```typescript
476
- * const params = RawBodyToParsedQueryString(rawBody); // { key: "value" }
477
- * ```
478
- */ function RawBodyToParsedQueryString(rawBody) {
479
- var string = RawBodyToString(rawBody);
480
- return node_querystring.parse(string);
481
- }
482
- /**
483
- * Converts a raw body buffer to a trimmed UTF-8 string.
484
- *
485
- * @param rawBody - The raw body buffer to convert.
486
- * @returns The decoded and trimmed string content.
487
- *
488
- * @example
489
- * ```typescript
490
- * const text = RawBodyToString(rawBody);
491
- * ```
492
- */ function RawBodyToString(rawBody) {
493
- return rawBody.toString('utf8').trim();
494
- }
495
-
496
- function _type_of$2(obj) {
497
- "@swc/helpers - typeof";
498
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
499
- }
500
- function __decorate(decorators, target, key, desc) {
501
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
502
- if ((typeof Reflect === "undefined" ? "undefined" : _type_of$2(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
503
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
504
- return c > 3 && r && Object.defineProperty(target, key, r), r;
505
- }
506
- function __param(paramIndex, decorator) {
507
- return function(target, key) {
508
- decorator(target, key, paramIndex);
509
- };
510
- }
511
- typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
512
- var e = new Error(message);
513
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
514
- };
515
-
516
- function _class_call_check$7(instance, Constructor) {
517
- if (!(instance instanceof Constructor)) {
518
- throw new TypeError("Cannot call a class as a function");
519
- }
520
- }
521
- function _defineProperties$5(target, props) {
522
- for(var i = 0; i < props.length; i++){
523
- var descriptor = props[i];
524
- descriptor.enumerable = descriptor.enumerable || false;
525
- descriptor.configurable = true;
526
- if ("value" in descriptor) descriptor.writable = true;
527
- Object.defineProperty(target, descriptor.key, descriptor);
528
- }
529
- }
530
- function _create_class$5(Constructor, protoProps, staticProps) {
531
- if (protoProps) _defineProperties$5(Constructor.prototype, protoProps);
532
- return Constructor;
533
- }
534
- /**
535
- * NestJS middleware that applies JSON body parsing to incoming requests using `body-parser`.
536
- *
537
- * Useful when the global body parser is disabled and JSON parsing needs to be applied selectively to specific routes.
538
- *
539
- * @example
540
- * ```typescript
541
- * consumer.apply(JsonBodyMiddleware).forRoutes('api');
542
- * ```
543
- */ exports.JsonBodyMiddleware = /*#__PURE__*/ function() {
544
- function JsonBodyMiddleware() {
545
- _class_call_check$7(this, JsonBodyMiddleware);
546
- }
547
- _create_class$5(JsonBodyMiddleware, [
548
- {
549
- key: "use",
550
- value: function use(req, res, next) {
551
- bodyParser.json()(req, res, next);
552
- }
553
- }
554
- ]);
555
- return JsonBodyMiddleware;
556
- }();
557
- exports.JsonBodyMiddleware = __decorate([
558
- common.Injectable()
559
- ], exports.JsonBodyMiddleware);
560
-
561
- function _class_call_check$6(instance, Constructor) {
562
- if (!(instance instanceof Constructor)) {
563
- throw new TypeError("Cannot call a class as a function");
564
- }
565
- }
566
- function _defineProperties$4(target, props) {
567
- for(var i = 0; i < props.length; i++){
568
- var descriptor = props[i];
569
- descriptor.enumerable = descriptor.enumerable || false;
570
- descriptor.configurable = true;
571
- if ("value" in descriptor) descriptor.writable = true;
572
- Object.defineProperty(target, descriptor.key, descriptor);
573
- }
574
- }
575
- function _create_class$4(Constructor, protoProps, staticProps) {
576
- if (protoProps) _defineProperties$4(Constructor.prototype, protoProps);
577
- return Constructor;
578
- }
579
- exports.RawBodyMiddleware = /*#__PURE__*/ function() {
580
- function RawBodyMiddleware() {
581
- _class_call_check$6(this, RawBodyMiddleware);
582
- }
583
- _create_class$4(RawBodyMiddleware, [
584
- {
585
- key: "use",
586
- value: function use(req, res, next) {
587
- bodyParser.raw({
588
- type: '*/*'
589
- })(req, res, next);
590
- }
591
- }
592
- ]);
593
- return RawBodyMiddleware;
594
- }();
595
- exports.RawBodyMiddleware = __decorate([
596
- common.Injectable()
597
- ], exports.RawBodyMiddleware);
598
-
599
- function _assert_this_initialized(self) {
600
- if (self === void 0) {
601
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
602
- }
603
- return self;
604
- }
605
- function _call_super(_this, derived, args) {
606
- derived = _get_prototype_of(derived);
607
- return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
608
- }
609
- function _class_call_check$5(instance, Constructor) {
610
- if (!(instance instanceof Constructor)) {
611
- throw new TypeError("Cannot call a class as a function");
612
- }
613
- }
614
- function _defineProperties$3(target, props) {
615
- for(var i = 0; i < props.length; i++){
616
- var descriptor = props[i];
617
- descriptor.enumerable = descriptor.enumerable || false;
618
- descriptor.configurable = true;
619
- if ("value" in descriptor) descriptor.writable = true;
620
- Object.defineProperty(target, descriptor.key, descriptor);
621
- }
622
- }
623
- function _create_class$3(Constructor, protoProps, staticProps) {
624
- if (protoProps) _defineProperties$3(Constructor.prototype, protoProps);
625
- return Constructor;
626
- }
627
- function _define_property$4(obj, key, value) {
628
- if (key in obj) {
629
- Object.defineProperty(obj, key, {
630
- value: value,
631
- enumerable: true,
632
- configurable: true,
633
- writable: true
634
- });
635
- } else {
636
- obj[key] = value;
637
- }
638
- return obj;
639
- }
640
- function _get(target, property, receiver) {
641
- if (typeof Reflect !== "undefined" && Reflect.get) {
642
- _get = Reflect.get;
643
- } else {
644
- _get = function get(target, property, receiver) {
645
- var base = _super_prop_base(target, property);
646
- if (!base) return;
647
- var desc = Object.getOwnPropertyDescriptor(base, property);
648
- if (desc.get) {
649
- return desc.get.call(receiver || target);
650
- }
651
- return desc.value;
652
- };
653
- }
654
- return _get(target, property, receiver || target);
655
- }
656
- function _get_prototype_of(o) {
657
- _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
658
- return o.__proto__ || Object.getPrototypeOf(o);
659
- };
660
- return _get_prototype_of(o);
661
- }
662
- function _inherits(subClass, superClass) {
663
- if (typeof superClass !== "function" && superClass !== null) {
664
- throw new TypeError("Super expression must either be null or a function");
665
- }
666
- subClass.prototype = Object.create(superClass && superClass.prototype, {
667
- constructor: {
668
- value: subClass,
669
- writable: true,
670
- configurable: true
671
- }
672
- });
673
- if (superClass) _set_prototype_of(subClass, superClass);
674
- }
675
- function _possible_constructor_return(self, call) {
676
- if (call && (_type_of$1(call) === "object" || typeof call === "function")) {
677
- return call;
678
- }
679
- return _assert_this_initialized(self);
680
- }
681
- function _set_prototype_of(o, p) {
682
- _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
683
- o.__proto__ = p;
684
- return o;
685
- };
686
- return _set_prototype_of(o, p);
687
- }
688
- function _super_prop_base(object, property) {
689
- while(!Object.prototype.hasOwnProperty.call(object, property)){
690
- object = _get_prototype_of(object);
691
- if (object === null) break;
692
- }
693
- return object;
694
- }
695
- function _type_of$1(obj) {
696
- "@swc/helpers - typeof";
697
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
698
- }
699
- function _is_native_reflect_construct() {
700
- try {
701
- var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
702
- } catch (_) {}
703
- return (_is_native_reflect_construct = function() {
704
- return !!result;
705
- })();
706
- }
707
- var DEFAULT_BASE_WEBHOOK_PATH = '/webhook';
708
- var DEFAULT_WEBHOOK_MIDDLEWARE_ROUTE_INFO = {
709
- path: "".concat(DEFAULT_BASE_WEBHOOK_PATH, "/{*path}"),
710
- method: common.RequestMethod.POST
711
- };
712
- /**
713
- * Convenience class that configures a nestjs module (typically the root app module) to apply the proper middleware for handling webhooks.
714
- */ var AppModuleWithWebhooksEnabled = /*#__PURE__*/ function() {
715
- function AppModuleWithWebhooksEnabled() {
716
- _class_call_check$5(this, AppModuleWithWebhooksEnabled);
717
- }
718
- _create_class$3(AppModuleWithWebhooksEnabled, [
719
- {
720
- key: "configure",
721
- value: function configure(consumer) {
722
- consumeWebhooksWithRawBodyMiddleware(consumer);
723
- }
724
- }
725
- ]);
726
- return AppModuleWithWebhooksEnabled;
727
- }();
728
- /**
729
- * Convenience class that extends AppWithWebhooksEnabled.
730
- */ exports.ConfigureWebhookMiddlewareModule = /*#__PURE__*/ function(AppModuleWithWebhooksEnabled) {
731
- _inherits(ConfigureWebhookMiddlewareModule, AppModuleWithWebhooksEnabled);
732
- function ConfigureWebhookMiddlewareModule() {
733
- _class_call_check$5(this, ConfigureWebhookMiddlewareModule);
734
- var _this;
735
- _this = _call_super(this, ConfigureWebhookMiddlewareModule, arguments), _define_property$4(_this, "logger", new common.Logger('ConfigureWebhookMiddlewareModule'));
736
- return _this;
737
- }
738
- _create_class$3(ConfigureWebhookMiddlewareModule, [
739
- {
740
- key: "configure",
741
- value: function configure(consumer) {
742
- _get(_get_prototype_of(ConfigureWebhookMiddlewareModule.prototype), "configure", this).call(this, consumer);
743
- this.logger.debug('Configured webhook routes with proper middleware.');
744
- }
745
- }
746
- ]);
747
- return ConfigureWebhookMiddlewareModule;
748
- }(AppModuleWithWebhooksEnabled);
749
- exports.ConfigureWebhookMiddlewareModule = __decorate([
750
- common.Module({})
751
- ], exports.ConfigureWebhookMiddlewareModule);
752
- /**
753
- * Configures a MiddlewareConsumer to use RawBodyMiddleware for all POST requests to /webhook/{*path}. All other routes are consumed with the JsonBodyMiddleware.
754
- *
755
- * This is required for various webhooks that require the full body to properly parse content.
756
- *
757
- * Be sure to also set bodyParsing: false in the nest app options.
758
- *
759
- * @param consumer
760
- */ function consumeWebhooksWithRawBodyMiddleware(consumer) {
761
- // Configure the app to not parse the body for our webhook routes.
762
- // https://stackoverflow.com/questions/54346465/access-raw-body-of-stripe-webhook-in-nest-js
763
- consumer.apply(exports.RawBodyMiddleware).forRoutes(DEFAULT_WEBHOOK_MIDDLEWARE_ROUTE_INFO).apply(exports.JsonBodyMiddleware).forRoutes('{*path}');
764
- }
765
-
766
- function _type_of(obj) {
767
- "@swc/helpers - typeof";
768
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
769
- }
770
- /**
771
- * Merges two module metadata entries together.
772
- *
773
- * @param base - The base module metadata.
774
- * @param additional - Additional metadata to merge in.
775
- * @returns The merged module metadata.
776
- */ function mergeModuleMetadata(base) {
777
- var additional = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
778
- return {
779
- controllers: util.mergeArrays([
780
- base.controllers,
781
- additional.controllers
782
- ]),
783
- imports: util.mergeArrays([
784
- base.imports,
785
- additional.imports
786
- ]),
787
- exports: util.mergeArrays([
788
- base.exports,
789
- additional.exports
790
- ]),
791
- providers: util.mergeArrays([
792
- base.providers,
793
- additional.providers
794
- ])
795
- };
796
- }
797
- /**
798
- * Extracts the injection tokens from an array (or single value) of NestJS Providers.
799
- *
800
- * For class providers, returns the class itself; for object providers, returns the provide token.
801
- *
802
- * @param providers - Providers to extract tokens from.
803
- * @returns Injection tokens collected from each provider.
804
- */ function injectionTokensFromProviders(providers) {
805
- return util.asArray(providers).map(function(x) {
806
- return (typeof x === "undefined" ? "undefined" : _type_of(x)) === 'object' ? x.provide : x;
807
- });
808
- }
809
-
810
- /**
811
- * Environment variable that specfies the ClientWebAppUrl for your application
812
- */ var CLIENT_WEB_APP_URL_ENV_VAR = 'CLIENT_WEB_APP_URL';
813
-
814
- function _class_call_check$4(instance, Constructor) {
815
- if (!(instance instanceof Constructor)) {
816
- throw new TypeError("Cannot call a class as a function");
817
- }
818
- }
819
- function _defineProperties$2(target, props) {
820
- for(var i = 0; i < props.length; i++){
821
- var descriptor = props[i];
822
- descriptor.enumerable = descriptor.enumerable || false;
823
- descriptor.configurable = true;
824
- if ("value" in descriptor) descriptor.writable = true;
825
- Object.defineProperty(target, descriptor.key, descriptor);
826
- }
827
- }
828
- function _create_class$2(Constructor, protoProps, staticProps) {
829
- if (staticProps) _defineProperties$2(Constructor, staticProps);
830
- return Constructor;
831
- }
832
- function _define_property$3(obj, key, value) {
833
- if (key in obj) {
834
- Object.defineProperty(obj, key, {
835
- value: value,
836
- enumerable: true,
837
- configurable: true,
838
- writable: true
839
- });
840
- } else {
841
- obj[key] = value;
842
- }
843
- return obj;
844
- }
845
- /**
846
- * Abstract service configuration that provides access to the client application config.
847
- *
848
- * Subclass this to supply environment-specific client URLs to NestJS services.
849
- */ var ClientAppServiceConfig = /*#__PURE__*/ function() {
850
- function ClientAppServiceConfig() {
851
- _class_call_check$4(this, ClientAppServiceConfig);
852
- _define_property$3(this, "client", void 0);
853
- }
854
- _create_class$2(ClientAppServiceConfig, null, [
855
- {
856
- key: "assertValidConfig",
857
- value: /**
858
- * Validates that the configuration contains a non-empty client web app URL.
859
- *
860
- * @param config - The configuration to validate.
861
- * @throws {Error} When `clientWebAppUrl` is not specified.
862
- */ function assertValidConfig(config) {
863
- if (!config.client.clientWebAppUrl) {
864
- throw new Error('No client app url specified.');
865
- }
866
- }
867
- }
868
- ]);
869
- return ClientAppServiceConfig;
870
- }
871
- ();
872
-
873
- function _class_call_check$3(instance, Constructor) {
874
- if (!(instance instanceof Constructor)) {
875
- throw new TypeError("Cannot call a class as a function");
876
- }
877
- }
878
- function _defineProperties$1(target, props) {
879
- for(var i = 0; i < props.length; i++){
880
- var descriptor = props[i];
881
- descriptor.enumerable = descriptor.enumerable || false;
882
- descriptor.configurable = true;
883
- if ("value" in descriptor) descriptor.writable = true;
884
- Object.defineProperty(target, descriptor.key, descriptor);
885
- }
886
- }
887
- function _create_class$1(Constructor, protoProps, staticProps) {
888
- if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
889
- return Constructor;
890
- }
891
- function _define_property$2(obj, key, value) {
892
- if (key in obj) {
893
- Object.defineProperty(obj, key, {
894
- value: value,
895
- enumerable: true,
896
- configurable: true,
897
- writable: true
898
- });
899
- } else {
900
- obj[key] = value;
901
- }
902
- return obj;
903
- }
904
- /**
905
- * Provides information about companion apps and websites for the project.
906
- */ exports.ClientAppService = /*#__PURE__*/ function() {
907
- function ClientAppService(config) {
908
- _class_call_check$3(this, ClientAppService);
909
- _define_property$2(this, "_config", void 0);
910
- this._config = config;
911
- }
912
- _create_class$1(ClientAppService, [
913
- {
914
- key: "config",
915
- get: function get() {
916
- return this._config;
917
- }
918
- },
919
- {
920
- key: "webAppUrl",
921
- get: function get() {
922
- return this.config.client.clientWebAppUrl;
923
- }
924
- },
925
- {
926
- key: "webAppHost",
927
- get: function get() {
928
- return this.webAppUrl.split('://', 2)[1];
929
- }
930
- }
931
- ]);
932
- return ClientAppService;
933
- }();
934
- exports.ClientAppService = __decorate([
935
- common.Injectable(),
936
- __param(0, common.Inject(ClientAppServiceConfig))
937
- ], exports.ClientAppService);
938
-
939
- function _class_call_check$2(instance, Constructor) {
940
- if (!(instance instanceof Constructor)) {
941
- throw new TypeError("Cannot call a class as a function");
942
- }
943
- }
944
- /**
945
- * Factory that creates a ClientAppServiceConfig from environment variables.
946
- *
947
- * Reads the client web app URL from the CLIENT_WEB_APP_URL environment variable.
948
- *
949
- * @param configService - NestJS config service for reading environment variables.
950
- * @returns A validated ClientAppServiceConfig.
951
- *
952
- * @__NO_SIDE_EFFECTS__
953
- */ function clientAppConfigFactory(configService) {
954
- var config = {
955
- client: {
956
- clientWebAppUrl: configService.get(CLIENT_WEB_APP_URL_ENV_VAR)
957
- }
958
- };
959
- ClientAppServiceConfig.assertValidConfig(config);
960
- return config;
961
- }
962
- /**
963
- * NestJS module that provides the ClientAppService for accessing client application configuration.
964
- *
965
- * Reads the client web app URL from environment variables and makes it available via ClientAppService.
966
- */ exports.ClientAppModule = function ClientAppModule() {
967
- _class_call_check$2(this, ClientAppModule);
968
- };
969
- exports.ClientAppModule = __decorate([
970
- common.Module({
971
- imports: [
972
- config.ConfigModule
973
- ],
974
- providers: [
975
- {
976
- provide: ClientAppServiceConfig,
977
- inject: [
978
- config.ConfigService
979
- ],
980
- useFactory: clientAppConfigFactory
981
- },
982
- exports.ClientAppService
983
- ],
984
- exports: [
985
- exports.ClientAppService
986
- ]
987
- })
988
- ], exports.ClientAppModule);
989
-
990
- function _class_call_check$1(instance, Constructor) {
991
- if (!(instance instanceof Constructor)) {
992
- throw new TypeError("Cannot call a class as a function");
993
- }
994
- }
995
- /**
996
- * A server environment configuration.
997
- *
998
- * Explicitly states whether or not this is a production environment, and optionally some other config.
999
- *
1000
- * This config is not meant to replace other typical configurations, like .env files, but instead is part of the build system.
1001
- */ var ServerEnvironmentConfig = function ServerEnvironmentConfig() {
1002
- _class_call_check$1(this, ServerEnvironmentConfig);
1003
- }
1004
- ;
1005
-
1006
- // MARK: Tokens
1007
- /**
1008
- * Token to access a configured ServerEnvironmentServiceConfig for the app.
1009
- */ var SERVER_ENV_TOKEN = 'SERVER_ENV_TOKEN';
1010
- /**
1011
- * Creates a NestJS Provider that supplies a ServerEnvironmentConfig under the SERVER_ENV_TOKEN injection token.
1012
- *
1013
- * Use this to register a server environment configuration instance with the NestJS dependency injection container.
1014
- *
1015
- * @param env - The server environment config to provide.
1016
- * @returns A NestJS Provider that supplies the config under SERVER_ENV_TOKEN.
1017
- */ function serverEnvTokenProvider(env) {
1018
- return {
1019
- provide: SERVER_ENV_TOKEN,
1020
- useValue: env
1021
- };
1022
- }
1023
-
1024
- /**
1025
- * Checks process.env.NODE_ENV for "test".
1026
- *
1027
- * @returns True if the current Node environment is "test", false otherwise.
1028
- */ function isTestNodeEnv() {
1029
- return process.env['NODE_ENV'] === 'test';
1030
- }
1031
-
1032
- function _class_call_check(instance, Constructor) {
1033
- if (!(instance instanceof Constructor)) {
1034
- throw new TypeError("Cannot call a class as a function");
1035
- }
1036
- }
1037
- function _defineProperties(target, props) {
1038
- for(var i = 0; i < props.length; i++){
1039
- var descriptor = props[i];
1040
- descriptor.enumerable = descriptor.enumerable || false;
1041
- descriptor.configurable = true;
1042
- if ("value" in descriptor) descriptor.writable = true;
1043
- Object.defineProperty(target, descriptor.key, descriptor);
1044
- }
1045
- }
1046
- function _create_class(Constructor, protoProps, staticProps) {
1047
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1048
- return Constructor;
1049
- }
1050
- function _define_property$1(obj, key, value) {
1051
- if (key in obj) {
1052
- Object.defineProperty(obj, key, {
1053
- value: value,
1054
- enumerable: true,
1055
- configurable: true,
1056
- writable: true
1057
- });
1058
- } else {
1059
- obj[key] = value;
1060
- }
1061
- return obj;
1062
- }
1063
- exports.ServerEnvironmentService = /*#__PURE__*/ function() {
1064
- function ServerEnvironmentService(env) {
1065
- _class_call_check(this, ServerEnvironmentService);
1066
- _define_property$1(this, "env", void 0);
1067
- this.env = env;
1068
- }
1069
- _create_class(ServerEnvironmentService, [
1070
- {
1071
- key: "isTestingEnv",
1072
- get: function get() {
1073
- return isTestNodeEnv();
1074
- }
1075
- },
1076
- {
1077
- key: "isProduction",
1078
- get: function get() {
1079
- return this.env.production;
1080
- }
1081
- },
1082
- {
1083
- key: "isStaging",
1084
- get: function get() {
1085
- return Boolean(this.env.staging);
1086
- }
1087
- },
1088
- {
1089
- key: "developerToolsEnabled",
1090
- get: function get() {
1091
- return Boolean(!this.isProduction && this.env.developerToolsEnabled);
1092
- }
1093
- },
1094
- {
1095
- key: "appUrl",
1096
- get: function get() {
1097
- return this.env.appUrl;
1098
- }
1099
- },
1100
- {
1101
- key: "appApiUrl",
1102
- get: function get() {
1103
- return this.env.appApiUrl;
1104
- }
1105
- }
1106
- ]);
1107
- return ServerEnvironmentService;
1108
- }();
1109
- exports.ServerEnvironmentService = __decorate([
1110
- common.Injectable(),
1111
- __param(0, common.Inject(SERVER_ENV_TOKEN))
1112
- ], exports.ServerEnvironmentService);
1113
-
1114
- /**
1115
- * Reads JSON from disk, resolving `undefined` when the file is missing (ENOENT) or its
1116
- * contents fail to parse as JSON. Other I/O errors (permission denied, busy handles) are
1117
- * forwarded to the caller — silently swallowing them masks real failures.
1118
- *
1119
- * @param filePath - Absolute path to the JSON file to read.
1120
- * @returns The parsed JSON cast to `T`, or `undefined` when the file does not exist or its contents are not valid JSON.
1121
- */ function readJsonFile(filePath) {
1122
- return new Promise(function(resolve, reject) {
1123
- node_fs.readFile(filePath, {
1124
- encoding: 'utf-8'
1125
- }, function(err, data) {
1126
- if (err) {
1127
- if (err.code === 'ENOENT') {
1128
- resolve(undefined);
1129
- } else {
1130
- reject(err);
1131
- }
1132
- return;
1133
- }
1134
- try {
1135
- resolve(JSON.parse(data));
1136
- } catch (unused) {
1137
- resolve(undefined);
1138
- }
1139
- });
1140
- });
1141
- }
1142
- /**
1143
- * Writes a value to disk as JSON. Creates the parent directory if it does not exist.
1144
- *
1145
- * The `mode` option is enforced via an explicit `chmod` after the write — `writeFile`'s `mode`
1146
- * parameter is ignored when the file already exists, which would otherwise leave a
1147
- * pre-existing file at its original (potentially world-readable) permissions.
1148
- *
1149
- * @param input - Configuration describing the destination, payload, and optional file mode.
1150
- * @param input.filePath - Absolute path to the file to write.
1151
- * @param input.dirPath - Absolute path to the parent directory; created (recursively) when missing.
1152
- * @param input.data - Value to serialize as JSON (pretty-printed with two-space indentation).
1153
- * @param input.mode - Optional numeric file mode (e.g. `0o600`) applied via `chmod` after the write.
1154
- * @returns Resolves once the JSON has been written and the optional `chmod` has completed.
1155
- */ function writeJsonFile(input) {
1156
- node_fs.mkdirSync(input.dirPath, {
1157
- recursive: true
1158
- });
1159
- return new Promise(function(resolve, reject) {
1160
- node_fs.writeFile(input.filePath, JSON.stringify(input.data, null, 2), {
1161
- mode: input.mode
1162
- }, function(err) {
1163
- if (err) {
1164
- reject(err);
1165
- } else if (input.mode == null) {
1166
- resolve();
1167
- } else {
1168
- node_fs.chmod(input.filePath, input.mode, function(chmodErr) {
1169
- if (chmodErr) reject(chmodErr);
1170
- else resolve();
1171
- });
1172
- }
1173
- });
1174
- });
1175
- }
1176
- /**
1177
- * Removes the file at the given path.
1178
- *
1179
- * Resolves silently when the file does not exist (`force: true`); other errors
1180
- * (permission denied, busy file handles) are forwarded to the caller — silently
1181
- * swallowing them masks real failures and makes operations appear to have succeeded.
1182
- *
1183
- * @param filePath - Absolute path to the file to remove.
1184
- * @returns Resolves once the file is removed (or was already absent).
1185
- */ function removeFile(filePath) {
1186
- return promises.rm(filePath, {
1187
- force: true
1188
- });
1189
- }
1190
-
1191
- function _array_like_to_array$1(arr, len) {
1192
- if (len == null || len > arr.length) len = arr.length;
1193
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1194
- return arr2;
1195
- }
1196
- function _array_with_holes$1(arr) {
1197
- if (Array.isArray(arr)) return arr;
1198
- }
1199
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1200
- try {
1201
- var info = gen[key](arg);
1202
- var value = info.value;
1203
- } catch (error) {
1204
- reject(error);
1205
- return;
1206
- }
1207
- if (info.done) {
1208
- resolve(value);
1209
- } else {
1210
- Promise.resolve(value).then(_next, _throw);
1211
- }
1212
- }
1213
- function _async_to_generator(fn) {
1214
- return function() {
1215
- var self = this, args = arguments;
1216
- return new Promise(function(resolve, reject) {
1217
- var gen = fn.apply(self, args);
1218
- function _next(value) {
1219
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
1220
- }
1221
- function _throw(err) {
1222
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
1223
- }
1224
- _next(undefined);
1225
- });
1226
- };
1227
- }
1228
- function _define_property(obj, key, value) {
1229
- if (key in obj) {
1230
- Object.defineProperty(obj, key, {
1231
- value: value,
1232
- enumerable: true,
1233
- configurable: true,
1234
- writable: true
1235
- });
1236
- } else {
1237
- obj[key] = value;
1238
- }
1239
- return obj;
1240
- }
1241
- function _iterable_to_array_limit$1(arr, i) {
1242
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
1243
- if (_i == null) return;
1244
- var _arr = [];
1245
- var _n = true;
1246
- var _d = false;
1247
- var _s, _e;
1248
- try {
1249
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
1250
- _arr.push(_s.value);
1251
- if (i && _arr.length === i) break;
1252
- }
1253
- } catch (err) {
1254
- _d = true;
1255
- _e = err;
1256
- } finally{
1257
- try {
1258
- if (!_n && _i["return"] != null) _i["return"]();
1259
- } finally{
1260
- if (_d) throw _e;
1261
- }
1262
- }
1263
- return _arr;
1264
- }
1265
- function _non_iterable_rest$1() {
1266
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1267
- }
1268
- function _object_spread(target) {
1269
- for(var i = 1; i < arguments.length; i++){
1270
- var source = arguments[i] != null ? arguments[i] : {};
1271
- var ownKeys = Object.keys(source);
1272
- if (typeof Object.getOwnPropertySymbols === "function") {
1273
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1274
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1275
- }));
1276
- }
1277
- ownKeys.forEach(function(key) {
1278
- _define_property(target, key, source[key]);
1279
- });
1280
- }
1281
- return target;
1282
- }
1283
- function ownKeys(object, enumerableOnly) {
1284
- var keys = Object.keys(object);
1285
- if (Object.getOwnPropertySymbols) {
1286
- var symbols = Object.getOwnPropertySymbols(object);
1287
- keys.push.apply(keys, symbols);
1288
- }
1289
- return keys;
1290
- }
1291
- function _object_spread_props(target, source) {
1292
- source = source != null ? source : {};
1293
- if (Object.getOwnPropertyDescriptors) {
1294
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1295
- } else {
1296
- ownKeys(Object(source)).forEach(function(key) {
1297
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1298
- });
1299
- }
1300
- return target;
1301
- }
1302
- function _sliced_to_array$1(arr, i) {
1303
- return _array_with_holes$1(arr) || _iterable_to_array_limit$1(arr, i) || _unsupported_iterable_to_array$1(arr, i) || _non_iterable_rest$1();
1304
- }
1305
- function _unsupported_iterable_to_array$1(o, minLen) {
1306
- if (!o) return;
1307
- if (typeof o === "string") return _array_like_to_array$1(o, minLen);
1308
- var n = Object.prototype.toString.call(o).slice(8, -1);
1309
- if (n === "Object" && o.constructor) n = o.constructor.name;
1310
- if (n === "Map" || n === "Set") return Array.from(n);
1311
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
1312
- }
1313
- function _ts_generator(thisArg, body) {
1314
- var f, y, t, _ = {
1315
- label: 0,
1316
- sent: function() {
1317
- if (t[0] & 1) throw t[1];
1318
- return t[1];
1319
- },
1320
- trys: [],
1321
- ops: []
1322
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1323
- return d(g, "next", {
1324
- value: verb(0)
1325
- }), d(g, "throw", {
1326
- value: verb(1)
1327
- }), d(g, "return", {
1328
- value: verb(2)
1329
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1330
- value: function() {
1331
- return this;
1332
- }
1333
- }), g;
1334
- function verb(n) {
1335
- return function(v) {
1336
- return step([
1337
- n,
1338
- v
1339
- ]);
1340
- };
1341
- }
1342
- function step(op) {
1343
- if (f) throw new TypeError("Generator is already executing.");
1344
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1345
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1346
- if (y = 0, t) op = [
1347
- op[0] & 2,
1348
- t.value
1349
- ];
1350
- switch(op[0]){
1351
- case 0:
1352
- case 1:
1353
- t = op;
1354
- break;
1355
- case 4:
1356
- _.label++;
1357
- return {
1358
- value: op[1],
1359
- done: false
1360
- };
1361
- case 5:
1362
- _.label++;
1363
- y = op[1];
1364
- op = [
1365
- 0
1366
- ];
1367
- continue;
1368
- case 7:
1369
- op = _.ops.pop();
1370
- _.trys.pop();
1371
- continue;
1372
- default:
1373
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1374
- _ = 0;
1375
- continue;
1376
- }
1377
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1378
- _.label = op[1];
1379
- break;
1380
- }
1381
- if (op[0] === 6 && _.label < t[1]) {
1382
- _.label = t[1];
1383
- t = op;
1384
- break;
1385
- }
1386
- if (t && _.label < t[2]) {
1387
- _.label = t[2];
1388
- _.ops.push(op);
1389
- break;
1390
- }
1391
- if (t[2]) _.ops.pop();
1392
- _.trys.pop();
1393
- continue;
1394
- }
1395
- op = body.call(thisArg, _);
1396
- } catch (e) {
1397
- op = [
1398
- 6,
1399
- e
1400
- ];
1401
- y = 0;
1402
- } finally{
1403
- f = t = 0;
1404
- }
1405
- if (op[0] & 5) throw op[1];
1406
- return {
1407
- value: op[0] ? op[1] : void 0,
1408
- done: true
1409
- };
1410
- }
1411
- }
1412
- /**
1413
- * Default file mode used by the JSON-file caches when none is provided.
1414
- *
1415
- * 0o600 restricts the file to read/write for the owning user only — appropriate for
1416
- * secrets like cached access/refresh tokens.
1417
- */ var DEFAULT_JSON_FILE_CACHE_MODE = 384;
1418
- /**
1419
- * Creates an {@link AsyncValueCache} backed by a single JSON file on disk.
1420
- *
1421
- * Reads always touch disk; wrap with {@link memoizeAsyncValueCache} (or use
1422
- * {@link createMemoizedJsonFileAsyncValueCache}) to add per-process memoization.
1423
- *
1424
- * Multi-process invalidation is not provided. Two processes writing to the same file
1425
- * will last-writer-wins; once memoized, a long-running process will not observe writes
1426
- * from another process.
1427
- *
1428
- * @param input - Configuration bag describing the backing file and optional JSON revive/replace hooks.
1429
- * @param input.filePath - Absolute path to the JSON file that backs the cache.
1430
- * @param input.mode - Optional file mode applied on write; defaults to {@link DEFAULT_JSON_FILE_CACHE_MODE} (0o600).
1431
- * @param input.reviver - Optional transform applied to the raw JSON-parsed payload before it is returned from `load()` (e.g. revive `Date` fields).
1432
- * @param input.replacer - Optional transform applied to the value before it is stringified to JSON on `update()`.
1433
- * @returns An {@link AsyncValueCache} that persists the value to the configured JSON file.
1434
- * @__NO_SIDE_EFFECTS__
1435
- */ function createJsonFileAsyncValueCache(input) {
1436
- var filePath = input.filePath, mode = input.mode, reviver = input.reviver, replacer = input.replacer;
1437
- var fileMode = mode !== null && mode !== void 0 ? mode : DEFAULT_JSON_FILE_CACHE_MODE;
1438
- return {
1439
- load: function load() {
1440
- return _async_to_generator(function() {
1441
- var raw, result;
1442
- return _ts_generator(this, function(_state) {
1443
- switch(_state.label){
1444
- case 0:
1445
- return [
1446
- 4,
1447
- readJsonFile(filePath)
1448
- ];
1449
- case 1:
1450
- raw = _state.sent();
1451
- if (raw == null) {
1452
- result = undefined;
1453
- } else {
1454
- result = reviver == null ? raw : reviver(raw);
1455
- }
1456
- return [
1457
- 2,
1458
- result
1459
- ];
1460
- }
1461
- });
1462
- })();
1463
- },
1464
- update: function update(value) {
1465
- return _async_to_generator(function() {
1466
- var data;
1467
- return _ts_generator(this, function(_state) {
1468
- switch(_state.label){
1469
- case 0:
1470
- data = replacer == null ? value : replacer(value);
1471
- return [
1472
- 4,
1473
- writeJsonFile({
1474
- filePath: filePath,
1475
- dirPath: node_path.dirname(filePath),
1476
- data: data,
1477
- mode: fileMode
1478
- })
1479
- ];
1480
- case 1:
1481
- _state.sent();
1482
- return [
1483
- 2
1484
- ];
1485
- }
1486
- });
1487
- })();
1488
- },
1489
- clear: function clear() {
1490
- return _async_to_generator(function() {
1491
- return _ts_generator(this, function(_state) {
1492
- switch(_state.label){
1493
- case 0:
1494
- return [
1495
- 4,
1496
- removeFile(filePath)
1497
- ];
1498
- case 1:
1499
- _state.sent();
1500
- return [
1501
- 2
1502
- ];
1503
- }
1504
- });
1505
- })();
1506
- }
1507
- };
1508
- }
1509
- /**
1510
- * Convenience wrapper around {@link createJsonFileAsyncValueCache} composed with
1511
- * {@link memoizeAsyncValueCache}.
1512
- *
1513
- * @param input - Same configuration accepted by {@link createJsonFileAsyncValueCache}; see {@link CreateJsonFileAsyncValueCacheInput}.
1514
- * @returns An {@link AsyncValueCache} backed by the JSON file with a per-process single-load memoization layer in front.
1515
- * @__NO_SIDE_EFFECTS__
1516
- */ function createMemoizedJsonFileAsyncValueCache(input) {
1517
- return util.memoizeAsyncValueCache(createJsonFileAsyncValueCache(input));
1518
- }
1519
- /**
1520
- * Creates an {@link AsyncKeyedValueCache} backed by a single JSON file holding a `Record<string, T>`.
1521
- *
1522
- * Reads/writes always touch disk; wrap with {@link memoizeAsyncKeyedValueCache} (or use
1523
- * {@link createMemoizedJsonFileAsyncKeyedValueCache}) to add per-process memoization of the
1524
- * entire record.
1525
- *
1526
- * Multi-process invalidation is not provided; see {@link createJsonFileAsyncValueCache} for caveats.
1527
- *
1528
- * Concurrent `set`/`remove`/`clear` calls are serialized through a per-instance promise chain so
1529
- * the read-modify-write of the entire record file does not race within the same process.
1530
- *
1531
- * @param input - Configuration bag describing the backing file and optional per-entry revive/replace hooks.
1532
- * @param input.filePath - Absolute path to the JSON file that holds the entire `Record<string, T>`.
1533
- * @param input.mode - Optional file mode applied on write; defaults to {@link DEFAULT_JSON_FILE_CACHE_MODE} (0o600).
1534
- * @param input.reviver - Optional transform applied to each entry after it is JSON-parsed on `load()`/`get()`. Returning null/undefined drops the entry.
1535
- * @param input.replacer - Optional transform applied to each entry before it is stringified on `set()`.
1536
- * @returns An {@link AsyncKeyedValueCache} that persists all entries in the configured JSON file.
1537
- * @__NO_SIDE_EFFECTS__
1538
- */ function createJsonFileAsyncKeyedValueCache(input) {
1539
- var filePath = input.filePath, mode = input.mode, reviver = input.reviver, replacer = input.replacer;
1540
- var fileMode = mode !== null && mode !== void 0 ? mode : DEFAULT_JSON_FILE_CACHE_MODE;
1541
- function readEntries() {
1542
- return _async_to_generator(function() {
1543
- var raw, result, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, key, revived;
1544
- return _ts_generator(this, function(_state) {
1545
- switch(_state.label){
1546
- case 0:
1547
- return [
1548
- 4,
1549
- readJsonFile(filePath)
1550
- ];
1551
- case 1:
1552
- raw = _state.sent();
1553
- if (raw == null) {
1554
- result = {};
1555
- } else if (reviver == null) {
1556
- result = raw;
1557
- } else {
1558
- result = {};
1559
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1560
- try {
1561
- for(_iterator = Object.keys(raw)[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1562
- key = _step.value;
1563
- revived = reviver(raw[key]);
1564
- if (revived != null) {
1565
- result[key] = revived;
1566
- }
1567
- }
1568
- } catch (err) {
1569
- _didIteratorError = true;
1570
- _iteratorError = err;
1571
- } finally{
1572
- try {
1573
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1574
- _iterator.return();
1575
- }
1576
- } finally{
1577
- if (_didIteratorError) {
1578
- throw _iteratorError;
1579
- }
1580
- }
1581
- }
1582
- }
1583
- return [
1584
- 2,
1585
- result
1586
- ];
1587
- }
1588
- });
1589
- })();
1590
- }
1591
- function writeEntries(entries) {
1592
- return _async_to_generator(function() {
1593
- var data;
1594
- return _ts_generator(this, function(_state) {
1595
- switch(_state.label){
1596
- case 0:
1597
- data = replacer == null ? entries : Object.fromEntries(Object.entries(entries).map(function(param) {
1598
- var _param = _sliced_to_array$1(param, 2), key = _param[0], value = _param[1];
1599
- return [
1600
- key,
1601
- replacer(value)
1602
- ];
1603
- }));
1604
- return [
1605
- 4,
1606
- writeJsonFile({
1607
- filePath: filePath,
1608
- dirPath: node_path.dirname(filePath),
1609
- data: data,
1610
- mode: fileMode
1611
- })
1612
- ];
1613
- case 1:
1614
- _state.sent();
1615
- return [
1616
- 2
1617
- ];
1618
- }
1619
- });
1620
- })();
1621
- }
1622
- // Serialize set/remove through a per-instance promise chain. Without this, two concurrent
1623
- // mutations would race on the read-modify-write of the entire record file and the second
1624
- // writer's snapshot of the entries would clobber the first.
1625
- var mutationQueue = Promise.resolve();
1626
- function enqueueMutation(fn) {
1627
- var next = mutationQueue.then(fn, fn);
1628
- mutationQueue = next.catch(function() {
1629
- return undefined;
1630
- });
1631
- return next;
1632
- }
1633
- return {
1634
- load: readEntries,
1635
- get: function get(key) {
1636
- return _async_to_generator(function() {
1637
- return _ts_generator(this, function(_state) {
1638
- switch(_state.label){
1639
- case 0:
1640
- return [
1641
- 4,
1642
- readEntries()
1643
- ];
1644
- case 1:
1645
- return [
1646
- 2,
1647
- _state.sent()[key]
1648
- ];
1649
- }
1650
- });
1651
- })();
1652
- },
1653
- set: function set(key, value) {
1654
- return enqueueMutation(function() {
1655
- return _async_to_generator(function() {
1656
- var current;
1657
- return _ts_generator(this, function(_state) {
1658
- switch(_state.label){
1659
- case 0:
1660
- return [
1661
- 4,
1662
- readEntries()
1663
- ];
1664
- case 1:
1665
- current = _state.sent();
1666
- return [
1667
- 4,
1668
- writeEntries(_object_spread_props(_object_spread({}, current), _define_property({}, key, value)))
1669
- ];
1670
- case 2:
1671
- _state.sent();
1672
- return [
1673
- 2
1674
- ];
1675
- }
1676
- });
1677
- })();
1678
- });
1679
- },
1680
- remove: function remove(key) {
1681
- return enqueueMutation(function() {
1682
- return _async_to_generator(function() {
1683
- var current, next;
1684
- return _ts_generator(this, function(_state) {
1685
- switch(_state.label){
1686
- case 0:
1687
- return [
1688
- 4,
1689
- readEntries()
1690
- ];
1691
- case 1:
1692
- current = _state.sent();
1693
- next = _object_spread({}, current);
1694
- delete next[key];
1695
- return [
1696
- 4,
1697
- writeEntries(next)
1698
- ];
1699
- case 2:
1700
- _state.sent();
1701
- return [
1702
- 2
1703
- ];
1704
- }
1705
- });
1706
- })();
1707
- });
1708
- },
1709
- clear: function clear() {
1710
- return enqueueMutation(function() {
1711
- return _async_to_generator(function() {
1712
- return _ts_generator(this, function(_state) {
1713
- switch(_state.label){
1714
- case 0:
1715
- return [
1716
- 4,
1717
- removeFile(filePath)
1718
- ];
1719
- case 1:
1720
- _state.sent();
1721
- return [
1722
- 2
1723
- ];
1724
- }
1725
- });
1726
- })();
1727
- });
1728
- }
1729
- };
1730
- }
1731
- /**
1732
- * Convenience wrapper around {@link createJsonFileAsyncKeyedValueCache} composed with
1733
- * {@link memoizeAsyncKeyedValueCache}.
1734
- *
1735
- * @param input - Same configuration accepted by {@link createJsonFileAsyncKeyedValueCache}; see {@link CreateJsonFileAsyncKeyedValueCacheInput}.
1736
- * @returns An {@link AsyncKeyedValueCache} backed by the JSON file with a per-process record-level memoization layer in front.
1737
- * @__NO_SIDE_EFFECTS__
1738
- */ function createMemoizedJsonFileAsyncKeyedValueCache(input) {
1739
- return util.memoizeAsyncKeyedValueCache(createJsonFileAsyncKeyedValueCache(input));
1740
- }
1741
-
1742
- // MARK: Constants
1743
- /**
1744
- * AES-256-GCM encryption constants.
1745
- */ var ENCRYPTED_FIELD_ALGORITHM = 'aes-256-gcm';
1746
- var ENCRYPTED_FIELD_IV_LENGTH = 12;
1747
- var ENCRYPTED_FIELD_AUTH_TAG_LENGTH = 16;
1748
- var ENCRYPTED_FIELD_KEY_LENGTH = 32;
1749
- /**
1750
- * Validates that the given secret is a 64-character hexadecimal string (32 bytes for AES-256).
1751
- *
1752
- * @param secret - The hex-encoded secret key string to validate.
1753
- * @returns True if the secret is exactly 64 valid hex characters, false otherwise.
1754
- *
1755
- * @example
1756
- * ```typescript
1757
- * isValidAES256GCMEncryptionSecret('a'.repeat(64)); // true
1758
- * isValidAES256GCMEncryptionSecret('too-short'); // false
1759
- * ```
1760
- */ function isValidAES256GCMEncryptionSecret(secret) {
1761
- return secret.length === ENCRYPTED_FIELD_KEY_LENGTH * 2 && util.isHex(secret);
1762
- }
1763
- // MARK: Key Resolution
1764
- /**
1765
- * Factory that eagerly resolves and validates the encryption key from a secret source.
1766
- *
1767
- * The getter is called immediately and the key is validated on creation. The returned
1768
- * function provides the resolved Buffer without re-resolving or re-validating.
1769
- *
1770
- * @param source - The secret source configuration.
1771
- * @returns A getter that returns the resolved 32-byte Buffer for AES-256 encryption.
1772
- * @throws {Error} When the resolved key is not 64 hex characters.
1773
- *
1774
- * @example
1775
- * ```typescript
1776
- * const getKey = resolveEncryptionKey('a'.repeat(64));
1777
- * const key: Buffer = getKey();
1778
- * ```
1779
- */ function resolveEncryptionKey(source) {
1780
- var hex = util.getValueFromGetter(source);
1781
- if (!isValidAES256GCMEncryptionSecret(hex)) {
1782
- throw new Error("resolveEncryptionKey: expected a ".concat(ENCRYPTED_FIELD_KEY_LENGTH * 2, "-character hexadecimal key, got ").concat(hex.length, " characters. Ensure the key contains only hex characters (0-9, a-f)."));
1783
- }
1784
- var key = Buffer.from(hex, 'hex');
1785
- return function() {
1786
- return key;
1787
- };
1788
- }
1789
- /**
1790
- * Creates an `AES256GCMEncryption` instance that captures the resolved key in a closure.
1791
- *
1792
- * @param source - The hex-encoded secret or getter for the AES-256 key.
1793
- * @returns An `AES256GCMEncryption` instance.
1794
- * @throws {Error} When the resolved key is not 64 hex characters.
1795
- *
1796
- * @example
1797
- * ```typescript
1798
- * const encryption = createAES256GCMEncryption('a'.repeat(64));
1799
- *
1800
- * const encrypted = encryption.encryptValue({ sensitive: 'data' });
1801
- * const decrypted = encryption.decryptValue<{ sensitive: string }>(encrypted);
1802
- *
1803
- * const encryptedStr = encryption.encryptString('hello');
1804
- * const decryptedStr = encryption.decryptString(encryptedStr);
1805
- * // decryptedStr === 'hello'
1806
- * ```
1807
- *
1808
- * @__NO_SIDE_EFFECTS__
1809
- */ function createAES256GCMEncryption(source) {
1810
- var getKey = resolveEncryptionKey(source);
1811
- function encryptStringFn(plaintext) {
1812
- var key = getKey();
1813
- var iv = node_crypto.randomBytes(ENCRYPTED_FIELD_IV_LENGTH);
1814
- var cipher = node_crypto.createCipheriv(ENCRYPTED_FIELD_ALGORITHM, key, iv);
1815
- var encrypted = Buffer.concat([
1816
- cipher.update(plaintext, 'utf8'),
1817
- cipher.final()
1818
- ]);
1819
- var authTag = cipher.getAuthTag();
1820
- var combined = Buffer.concat([
1821
- iv,
1822
- encrypted,
1823
- authTag
1824
- ]);
1825
- return combined.toString('base64');
1826
- }
1827
- function decryptStringFn(encoded) {
1828
- var key = getKey();
1829
- var combined = Buffer.from(encoded, 'base64');
1830
- var iv = combined.subarray(0, ENCRYPTED_FIELD_IV_LENGTH);
1831
- var authTag = combined.subarray(combined.length - ENCRYPTED_FIELD_AUTH_TAG_LENGTH);
1832
- var ciphertext = combined.subarray(ENCRYPTED_FIELD_IV_LENGTH, combined.length - ENCRYPTED_FIELD_AUTH_TAG_LENGTH);
1833
- var decipher = node_crypto.createDecipheriv(ENCRYPTED_FIELD_ALGORITHM, key, iv);
1834
- decipher.setAuthTag(authTag);
1835
- var decrypted = Buffer.concat([
1836
- decipher.update(ciphertext),
1837
- decipher.final()
1838
- ]);
1839
- return decrypted.toString('utf8');
1840
- }
1841
- var result = {
1842
- encryptString: encryptStringFn,
1843
- decryptString: decryptStringFn,
1844
- encryptValue: function encryptValue(value) {
1845
- return encryptStringFn(JSON.stringify(value));
1846
- },
1847
- decryptValue: function decryptValue(encoded) {
1848
- return JSON.parse(decryptStringFn(encoded));
1849
- }
1850
- };
1851
- return result;
1852
- }
1853
- // MARK: Standalone Functions (backwards compatibility)
1854
- /**
1855
- * Encrypts a JSON-serializable value to a base64-encoded string using AES-256-GCM.
1856
- *
1857
- * Format: base64(IV (12 bytes) + ciphertext + authTag (16 bytes))
1858
- *
1859
- * @param value - The value to encrypt (must be JSON-serializable).
1860
- * @param key - The 32-byte encryption key from `resolveEncryptionKey()`.
1861
- * @returns The encrypted value as a base64 string.
1862
- *
1863
- * @example
1864
- * ```typescript
1865
- * const getKey = resolveEncryptionKey(mySecret);
1866
- * const encrypted = encryptValue({ sensitive: 'data' }, getKey());
1867
- * const decrypted = decryptValue<{ sensitive: string }>(encrypted, getKey());
1868
- * ```
1869
- */ function encryptValue(value, key) {
1870
- var iv = node_crypto.randomBytes(ENCRYPTED_FIELD_IV_LENGTH);
1871
- var cipher = node_crypto.createCipheriv(ENCRYPTED_FIELD_ALGORITHM, key, iv);
1872
- var plaintext = JSON.stringify(value);
1873
- var encrypted = Buffer.concat([
1874
- cipher.update(plaintext, 'utf8'),
1875
- cipher.final()
1876
- ]);
1877
- var authTag = cipher.getAuthTag();
1878
- var combined = Buffer.concat([
1879
- iv,
1880
- encrypted,
1881
- authTag
1882
- ]);
1883
- return combined.toString('base64');
1884
- }
1885
- /**
1886
- * Decrypts a base64-encoded string back to the original value.
1887
- *
1888
- * @param encoded - The base64-encoded encrypted string (IV + ciphertext + authTag).
1889
- * @param key - The 32-byte encryption key Buffer from calling the getter returned by `resolveEncryptionKey()`.
1890
- * @returns The decrypted JSON-parsed value.
1891
- */ function decryptValue(encoded, key) {
1892
- var combined = Buffer.from(encoded, 'base64');
1893
- var iv = combined.subarray(0, ENCRYPTED_FIELD_IV_LENGTH);
1894
- var authTag = combined.subarray(combined.length - ENCRYPTED_FIELD_AUTH_TAG_LENGTH);
1895
- var ciphertext = combined.subarray(ENCRYPTED_FIELD_IV_LENGTH, combined.length - ENCRYPTED_FIELD_AUTH_TAG_LENGTH);
1896
- var decipher = node_crypto.createDecipheriv(ENCRYPTED_FIELD_ALGORITHM, key, iv);
1897
- decipher.setAuthTag(authTag);
1898
- var decrypted = Buffer.concat([
1899
- decipher.update(ciphertext),
1900
- decipher.final()
1901
- ]);
1902
- return JSON.parse(decrypted.toString('utf8'));
1903
- }
1904
- // MARK: StringEncryptionProvider
1905
- /**
1906
- * Creates a `StringEncryptionProvider` backed by AES-256-GCM from a secret source.
1907
- *
1908
- * The key is resolved and validated eagerly at creation time. The provider encrypts/decrypts
1909
- * raw strings (no JSON serialization) — suitable for use with `selectiveFieldEncryptor`.
1910
- *
1911
- * @param source - The hex-encoded secret or getter for the AES-256 key.
1912
- * @returns A `StringEncryptionProvider` that encrypts/decrypts strings via AES-256-GCM.
1913
- * @throws {Error} When the resolved key is not 64 hex characters.
1914
- *
1915
- * @example
1916
- * ```typescript
1917
- * const provider = createAesStringEncryptionProvider('a'.repeat(64));
1918
- * const encrypted = provider.encrypt('sensitive data');
1919
- * const decrypted = provider.decrypt(encrypted);
1920
- * // decrypted === 'sensitive data'
1921
- * ```
1922
- *
1923
- * @__NO_SIDE_EFFECTS__
1924
- */ function createAesStringEncryptionProvider(source) {
1925
- var encryption = createAES256GCMEncryption(source);
1926
- var result = {
1927
- encrypt: function encrypt(plaintext) {
1928
- return encryption.encryptString(plaintext);
1929
- },
1930
- decrypt: function decrypt(ciphertext) {
1931
- return encryption.decryptString(ciphertext);
1932
- }
1933
- };
1934
- return result;
1935
- }
1936
-
1937
- function _array_like_to_array(arr, len) {
1938
- if (len == null || len > arr.length) len = arr.length;
1939
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1940
- return arr2;
1941
- }
1942
- function _array_with_holes(arr) {
1943
- if (Array.isArray(arr)) return arr;
1944
- }
1945
- function _iterable_to_array_limit(arr, i) {
1946
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
1947
- if (_i == null) return;
1948
- var _arr = [];
1949
- var _n = true;
1950
- var _d = false;
1951
- var _s, _e;
1952
- try {
1953
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
1954
- _arr.push(_s.value);
1955
- if (i && _arr.length === i) break;
1956
- }
1957
- } catch (err) {
1958
- _d = true;
1959
- _e = err;
1960
- } finally{
1961
- try {
1962
- if (!_n && _i["return"] != null) _i["return"]();
1963
- } finally{
1964
- if (_d) throw _e;
1965
- }
1966
- }
1967
- return _arr;
1968
- }
1969
- function _non_iterable_rest() {
1970
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1971
- }
1972
- function _sliced_to_array(arr, i) {
1973
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
1974
- }
1975
- function _tagged_template_literal(strings, raw) {
1976
- if (!raw) {
1977
- raw = strings.slice(0);
1978
- }
1979
- return Object.freeze(Object.defineProperties(strings, {
1980
- raw: {
1981
- value: Object.freeze(raw)
1982
- }
1983
- }));
1984
- }
1985
- function _unsupported_iterable_to_array(o, minLen) {
1986
- if (!o) return;
1987
- if (typeof o === "string") return _array_like_to_array(o, minLen);
1988
- var n = Object.prototype.toString.call(o).slice(8, -1);
1989
- if (n === "Object" && o.constructor) n = o.constructor.name;
1990
- if (n === "Map" || n === "Set") return Array.from(n);
1991
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1992
- }
1993
- function _templateObject() {
1994
- var data = _tagged_template_literal([
1995
- "(?:^|[\r\ns])",
1996
- "s+",
1997
- "s+obj\b"
1998
- ], [
1999
- "(?:^|[\\r\\n\\s])",
2000
- "\\s+",
2001
- "\\s+obj\\b"
2002
- ]);
2003
- _templateObject = function _templateObject() {
2004
- return data;
2005
- };
2006
- return data;
2007
- }
2008
- /**
2009
- * 32-byte password padding string defined by ISO 32000 §7.6.3.3 (Algorithm 2).
2010
- * Used to pad short or empty user/owner passwords for the standard security handler.
2011
- */ var PDF_PASSWORD_PADDING = Buffer.from([
2012
- 0x28,
2013
- 0xbf,
2014
- 0x4e,
2015
- 0x5e,
2016
- 0x4e,
2017
- 0x75,
2018
- 0x8a,
2019
- 0x41,
2020
- 0x64,
2021
- 0x00,
2022
- 0x4e,
2023
- 0x56,
2024
- 0xff,
2025
- 0xfa,
2026
- 0x01,
2027
- 0x08,
2028
- 0x2e,
2029
- 0x2e,
2030
- 0x00,
2031
- 0xb6,
2032
- 0xd0,
2033
- 0x68,
2034
- 0x3e,
2035
- 0x80,
2036
- 0x2f,
2037
- 0x0c,
2038
- 0xa9,
2039
- 0xfe,
2040
- 0x64,
2041
- 0x53,
2042
- 0x69,
2043
- 0x7a
2044
- ]);
2045
- /**
2046
- * Detects whether a PDF is unencrypted, write-protected (openable without a password
2047
- * but restricted from editing/printing), or fully encrypted (requires a password to open).
2048
- *
2049
- * Implements the user-password validation algorithms from ISO 32000-1 §7.6.3 (R≤4) and
2050
- * ISO 32000-2 §7.6.4.4 (R=5/6) using only the empty password. If the empty password
2051
- * validates successfully, the PDF is openable by anyone and only its modify/print/copy
2052
- * permissions are restricted; otherwise a non-empty user password is required.
2053
- *
2054
- * Supported security handlers:
2055
- * - Standard security handler, R=2,3,4 (RC4-40, RC4-128, AES-128 with crypt filters).
2056
- * - Standard security handler, R=5 (AES-256, deprecated Adobe extension).
2057
- * - Standard security handler, R=6 (AES-256, ISO 32000-2 / PDF 2.0).
2058
- *
2059
- * Unrecognised security handlers (e.g. PubSec, custom handlers) return
2060
- * `unknown_encrypted` so callers can choose whether to treat them as fully encrypted.
2061
- *
2062
- * Lives in `@dereekb/nestjs` (rather than `@dereekb/util`) because it uses Node's
2063
- * built-in `node:crypto` module, which isn't available in the browser.
2064
- *
2065
- * @param buffer - PDF file contents.
2066
- * @returns The encryption status of the PDF.
2067
- *
2068
- * @example
2069
- * ```ts
2070
- * const status = detectPdfEncryption(buffer);
2071
- *
2072
- * if (status === 'fully_encrypted') {
2073
- * throw new Error('PDF requires a password to open.');
2074
- * }
2075
- * if (status === 'write_protected_only') {
2076
- * // Safe to read, but not to mutate without the owner password.
2077
- * }
2078
- * ```
2079
- */ function detectPdfEncryption(buffer) {
2080
- var result = 'unknown_encrypted';
2081
- var encryptIndex = findEncryptKeywordIndex(buffer);
2082
- if (encryptIndex < 0) {
2083
- result = 'none';
2084
- } else {
2085
- var dict = extractEncryptionDictionary(buffer, encryptIndex);
2086
- var info = dict ? parseEncryptionInfo(dict) : null;
2087
- if ((info === null || info === void 0 ? void 0 : info.filter) === 'Standard') {
2088
- var opensWithEmptyPassword = checkStandardHandlerEmptyPassword(info, buffer);
2089
- if (opensWithEmptyPassword !== null) {
2090
- result = opensWithEmptyPassword ? 'write_protected_only' : 'fully_encrypted';
2091
- }
2092
- }
2093
- }
2094
- return result;
2095
- }
2096
- function checkStandardHandlerEmptyPassword(info, buffer) {
2097
- var result = null;
2098
- if (info.R >= 2 && info.R <= 4) {
2099
- var fileId = extractFirstFileId(buffer);
2100
- if (fileId && info.O.length >= 32 && info.U.length >= 32) {
2101
- result = validateEmptyPasswordR2to4(info, fileId);
2102
- }
2103
- } else if (info.R === 5 && info.U.length >= 48) {
2104
- result = validateEmptyPasswordR5(info);
2105
- } else if (info.R === 6 && info.U.length >= 48) {
2106
- result = validateEmptyPasswordR6(info);
2107
- }
2108
- return result;
2109
- }
2110
- function isPdfWhitespaceByte(b) {
2111
- return b === 0x00 || b === 0x09 || b === 0x0a || b === 0x0c || b === 0x0d || b === 0x20;
2112
- }
2113
- function isPdfDelimiterByte(b) {
2114
- return b === 0x28 || b === 0x29 || b === 0x3c || b === 0x3e || b === 0x5b || b === 0x5d || b === 0x7b || b === 0x7d || b === 0x2f || b === 0x25;
2115
- }
2116
- function isPdfWhitespaceOrDelimiter(b) {
2117
- return isPdfWhitespaceByte(b) || isPdfDelimiterByte(b);
2118
- }
2119
- function skipPdfWhitespaceAndComments(buffer, start) {
2120
- var i = start;
2121
- while(i < buffer.length){
2122
- var b = buffer[i];
2123
- if (isPdfWhitespaceByte(b)) {
2124
- i++;
2125
- } else if (b === 0x25 /* % */ ) {
2126
- while(i < buffer.length && buffer[i] !== 0x0a && buffer[i] !== 0x0d)i++;
2127
- } else {
2128
- break;
2129
- }
2130
- }
2131
- return i;
2132
- }
2133
- function skipPdfLiteralString(buffer, start) {
2134
- var depth = 1;
2135
- var i = start + 1;
2136
- while(i < buffer.length && depth > 0){
2137
- var b = buffer[i];
2138
- if (b === 0x5c /* \ */ ) {
2139
- i += 2;
2140
- } else if (b === 0x28 /* ( */ ) {
2141
- depth++;
2142
- i++;
2143
- } else if (b === 0x29 /* ) */ ) {
2144
- depth--;
2145
- i++;
2146
- } else {
2147
- i++;
2148
- }
2149
- }
2150
- return i;
2151
- }
2152
- function skipPdfHexString(buffer, start) {
2153
- var i = start + 1;
2154
- while(i < buffer.length && buffer[i] !== 0x3e /* > */ )i++;
2155
- return i < buffer.length ? i + 1 : i;
2156
- }
2157
- function findDictEnd(buffer, start) {
2158
- var depth = 1;
2159
- var i = start;
2160
- var endIndex = -1;
2161
- while(i < buffer.length && endIndex < 0){
2162
- var b = buffer[i];
2163
- if (b === 0x3c && buffer[i + 1] === 0x3c) {
2164
- depth++;
2165
- i += 2;
2166
- } else if (b === 0x3e && buffer[i + 1] === 0x3e) {
2167
- depth--;
2168
- if (depth === 0) {
2169
- endIndex = i;
2170
- } else {
2171
- i += 2;
2172
- }
2173
- } else if (b === 0x28) {
2174
- i = skipPdfLiteralString(buffer, i);
2175
- } else if (b === 0x3c) {
2176
- i = skipPdfHexString(buffer, i);
2177
- } else if (b === 0x25) {
2178
- while(i < buffer.length && buffer[i] !== 0x0a && buffer[i] !== 0x0d)i++;
2179
- } else {
2180
- i++;
2181
- }
2182
- }
2183
- return endIndex >= 0 ? endIndex : i;
2184
- }
2185
- function decodePdfLiteralString(content) {
2186
- var out = [];
2187
- var i = 0;
2188
- while(i < content.length){
2189
- var b = content[i];
2190
- if (b !== 0x5c /* \ */ ) {
2191
- out.push(b);
2192
- i++;
2193
- continue;
2194
- }
2195
- i++;
2196
- if (i >= content.length) break;
2197
- var c = content[i];
2198
- if (c >= 0x30 && c <= 0x37) {
2199
- var oct = c - 0x30;
2200
- i++;
2201
- if (i < content.length && content[i] >= 0x30 && content[i] <= 0x37) {
2202
- oct = oct * 8 + (content[i] - 0x30);
2203
- i++;
2204
- if (i < content.length && content[i] >= 0x30 && content[i] <= 0x37) {
2205
- oct = oct * 8 + (content[i] - 0x30);
2206
- i++;
2207
- }
2208
- }
2209
- out.push(oct & 0xff);
2210
- } else if (c === 0x6e /* n */ ) {
2211
- out.push(0x0a);
2212
- i++;
2213
- } else if (c === 0x72 /* r */ ) {
2214
- out.push(0x0d);
2215
- i++;
2216
- } else if (c === 0x74 /* t */ ) {
2217
- out.push(0x09);
2218
- i++;
2219
- } else if (c === 0x62 /* b */ ) {
2220
- out.push(0x08);
2221
- i++;
2222
- } else if (c === 0x66 /* f */ ) {
2223
- out.push(0x0c);
2224
- i++;
2225
- } else if (c === 0x0a) {
2226
- i++;
2227
- } else if (c === 0x0d) {
2228
- i++;
2229
- if (i < content.length && content[i] === 0x0a) i++;
2230
- } else {
2231
- out.push(c);
2232
- i++;
2233
- }
2234
- }
2235
- return Buffer.from(out);
2236
- }
2237
- function decodePdfHexString(content) {
2238
- var hex = [];
2239
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2240
- try {
2241
- for(var _iterator = content[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2242
- var b = _step.value;
2243
- if (isPdfWhitespaceByte(b)) continue;
2244
- if (b >= 0x30 && b <= 0x39 || b >= 0x41 && b <= 0x46 || b >= 0x61 && b <= 0x66) hex.push(b);
2245
- }
2246
- } catch (err) {
2247
- _didIteratorError = true;
2248
- _iteratorError = err;
2249
- } finally{
2250
- try {
2251
- if (!_iteratorNormalCompletion && _iterator.return != null) {
2252
- _iterator.return();
2253
- }
2254
- } finally{
2255
- if (_didIteratorError) {
2256
- throw _iteratorError;
2257
- }
2258
- }
2259
- }
2260
- if (hex.length % 2 === 1) hex.push(0x30);
2261
- var out = Buffer.alloc(hex.length / 2);
2262
- for(var i = 0; i < out.length; i++){
2263
- out[i] = Number.parseInt(String.fromCodePoint(hex[i * 2], hex[i * 2 + 1]), 16);
2264
- }
2265
- return out;
2266
- }
2267
- function readPdfNumber(buffer, start) {
2268
- var i = start;
2269
- while(i < buffer.length && !isPdfWhitespaceOrDelimiter(buffer[i]))i++;
2270
- var result = null;
2271
- if (i > start) {
2272
- var text = buffer.toString('latin1', start, i);
2273
- var value = Number(text);
2274
- if (!Number.isNaN(value)) {
2275
- result = {
2276
- value: value,
2277
- end: i
2278
- };
2279
- }
2280
- }
2281
- return result;
2282
- }
2283
- function parsePdfDict(buffer, dictStart) {
2284
- // dictStart is the byte after `<<`.
2285
- var entries = new Map();
2286
- var i = skipPdfWhitespaceAndComments(buffer, dictStart);
2287
- var result = null;
2288
- var aborted = false;
2289
- while(i < buffer.length && !aborted && result === null){
2290
- if (buffer[i] === 0x3e && buffer[i + 1] === 0x3e) {
2291
- result = {
2292
- entries: entries,
2293
- end: i + 2
2294
- };
2295
- } else if (buffer[i] === 0x2f /* / */ ) {
2296
- var nameStart = i + 1;
2297
- var nameEnd = nameStart;
2298
- while(nameEnd < buffer.length && !isPdfWhitespaceOrDelimiter(buffer[nameEnd]))nameEnd++;
2299
- var name = buffer.toString('latin1', nameStart, nameEnd);
2300
- i = skipPdfWhitespaceAndComments(buffer, nameEnd);
2301
- if (i >= buffer.length) {
2302
- aborted = true;
2303
- } else {
2304
- var valueResult = readPdfValue(buffer, i);
2305
- if (valueResult) {
2306
- entries.set(name, valueResult.entry);
2307
- i = skipPdfWhitespaceAndComments(buffer, valueResult.end);
2308
- } else {
2309
- aborted = true;
2310
- }
2311
- }
2312
- } else {
2313
- aborted = true;
2314
- }
2315
- }
2316
- return result;
2317
- }
2318
- function readPdfValue(buffer, start) {
2319
- var b = buffer[start];
2320
- var result;
2321
- if (b === 0x3c && buffer[start + 1] === 0x3c) {
2322
- result = readPdfDictValue(buffer, start);
2323
- } else if (b === 0x3c) {
2324
- result = readPdfHexStringValue(buffer, start);
2325
- } else if (b === 0x28) {
2326
- result = readPdfLiteralStringValue(buffer, start);
2327
- } else if (b === 0x5b /* [ */ ) {
2328
- result = readPdfArrayValue(buffer, start);
2329
- } else if (b === 0x2f /* / */ ) {
2330
- result = readPdfNameValue(buffer, start);
2331
- } else {
2332
- result = readPdfTokenOrRefValue(buffer, start);
2333
- }
2334
- return result;
2335
- }
2336
- function readPdfDictValue(buffer, start) {
2337
- var dictEnd = findDictEnd(buffer, start + 2);
2338
- var end = dictEnd < buffer.length && buffer[dictEnd] === 0x3e && buffer[dictEnd + 1] === 0x3e ? dictEnd + 2 : dictEnd;
2339
- return {
2340
- entry: {
2341
- type: 'dict',
2342
- raw: buffer.subarray(start, end)
2343
- },
2344
- end: end
2345
- };
2346
- }
2347
- function readPdfHexStringValue(buffer, start) {
2348
- var end = skipPdfHexString(buffer, start);
2349
- return {
2350
- entry: {
2351
- type: 'string',
2352
- raw: decodePdfHexString(buffer.subarray(start + 1, end - 1))
2353
- },
2354
- end: end
2355
- };
2356
- }
2357
- function readPdfLiteralStringValue(buffer, start) {
2358
- var end = skipPdfLiteralString(buffer, start);
2359
- return {
2360
- entry: {
2361
- type: 'string',
2362
- raw: decodePdfLiteralString(buffer.subarray(start + 1, end - 1))
2363
- },
2364
- end: end
2365
- };
2366
- }
2367
- function readPdfArrayValue(buffer, start) {
2368
- var depth = 1;
2369
- var i = start + 1;
2370
- while(i < buffer.length && depth > 0){
2371
- var c = buffer[i];
2372
- if (c === 0x5b) {
2373
- depth++;
2374
- i++;
2375
- } else if (c === 0x5d) {
2376
- depth--;
2377
- i++;
2378
- } else if (c === 0x28) {
2379
- i = skipPdfLiteralString(buffer, i);
2380
- } else if (c === 0x3c && buffer[i + 1] === 0x3c) {
2381
- var e = findDictEnd(buffer, i + 2);
2382
- i = e < buffer.length && buffer[e] === 0x3e && buffer[e + 1] === 0x3e ? e + 2 : e;
2383
- } else if (c === 0x3c) {
2384
- i = skipPdfHexString(buffer, i);
2385
- } else if (c === 0x25) {
2386
- while(i < buffer.length && buffer[i] !== 0x0a && buffer[i] !== 0x0d)i++;
2387
- } else {
2388
- i++;
2389
- }
2390
- }
2391
- return {
2392
- entry: {
2393
- type: 'array',
2394
- raw: buffer.subarray(start, i)
2395
- },
2396
- end: i
2397
- };
2398
- }
2399
- function readPdfNameValue(buffer, start) {
2400
- var i = start + 1;
2401
- while(i < buffer.length && !isPdfWhitespaceOrDelimiter(buffer[i]))i++;
2402
- return {
2403
- entry: {
2404
- type: 'name',
2405
- raw: buffer.subarray(start + 1, i)
2406
- },
2407
- end: i
2408
- };
2409
- }
2410
- function readPdfTokenOrRefValue(buffer, start) {
2411
- // Number, boolean, null, or indirect reference like `12 0 R`.
2412
- var i = start;
2413
- while(i < buffer.length && !isPdfWhitespaceOrDelimiter(buffer[i]))i++;
2414
- var tokenEnd = i;
2415
- var token = buffer.toString('latin1', start, tokenEnd);
2416
- var referenceEnd = readIndirectReferenceEnd(buffer, tokenEnd);
2417
- var result;
2418
- if (referenceEnd != null) {
2419
- result = {
2420
- entry: {
2421
- type: 'ref',
2422
- raw: buffer.subarray(start, referenceEnd)
2423
- },
2424
- end: referenceEnd
2425
- };
2426
- } else if (token === 'true' || token === 'false') {
2427
- result = {
2428
- entry: {
2429
- type: 'boolean',
2430
- raw: buffer.subarray(start, tokenEnd)
2431
- },
2432
- end: tokenEnd
2433
- };
2434
- } else if (token === 'null') {
2435
- result = {
2436
- entry: {
2437
- type: 'null',
2438
- raw: buffer.subarray(start, tokenEnd)
2439
- },
2440
- end: tokenEnd
2441
- };
2442
- } else {
2443
- result = {
2444
- entry: {
2445
- type: 'number',
2446
- raw: buffer.subarray(start, tokenEnd)
2447
- },
2448
- end: tokenEnd
2449
- };
2450
- }
2451
- return result;
2452
- }
2453
- function readIndirectReferenceEnd(buffer, tokenEnd) {
2454
- // Probe ahead for `GEN R` after a leading object number to detect `N G R`.
2455
- var result = null;
2456
- var probe = skipPdfWhitespaceAndComments(buffer, tokenEnd);
2457
- if (probe < buffer.length) {
2458
- var c = buffer[probe];
2459
- if (c >= 0x30 && c <= 0x39) {
2460
- var secondEnd = probe;
2461
- while(secondEnd < buffer.length && !isPdfWhitespaceOrDelimiter(buffer[secondEnd]))secondEnd++;
2462
- var probe2 = skipPdfWhitespaceAndComments(buffer, secondEnd);
2463
- if (probe2 < buffer.length && buffer[probe2] === 0x52 /* R */ && (probe2 + 1 === buffer.length || isPdfWhitespaceOrDelimiter(buffer[probe2 + 1]))) {
2464
- result = probe2 + 1;
2465
- }
2466
- }
2467
- }
2468
- return result;
2469
- }
2470
- function findEncryptKeywordIndex(buffer) {
2471
- var marker = util.PDF_ENCRYPT_MARKER;
2472
- var last = -1;
2473
- var pos = 0;
2474
- while(true){
2475
- var found = buffer.indexOf(marker, pos);
2476
- if (found < 0) break;
2477
- var next = buffer[found + marker.length];
2478
- // Avoid matching `/EncryptMetadata` (a different name).
2479
- var isAlpha = next >= 0x41 && next <= 0x5a || next >= 0x61 && next <= 0x7a;
2480
- if (!isAlpha) last = found;
2481
- pos = found + marker.length;
2482
- }
2483
- return last;
2484
- }
2485
- function extractEncryptionDictionary(buffer, encryptIndex) {
2486
- var result = null;
2487
- var i = encryptIndex + util.PDF_ENCRYPT_MARKER.length;
2488
- i = skipPdfWhitespaceAndComments(buffer, i);
2489
- if (i < buffer.length) {
2490
- if (buffer[i] === 0x3c && buffer[i + 1] === 0x3c) {
2491
- // Inline dictionary.
2492
- var dictEnd = findDictEnd(buffer, i + 2);
2493
- result = buffer.subarray(i, dictEnd + 2);
2494
- } else {
2495
- // Indirect reference: `N G R`.
2496
- result = resolveIndirectEncryptionDictionary(buffer, i);
2497
- }
2498
- }
2499
- return result;
2500
- }
2501
- function resolveIndirectEncryptionDictionary(buffer, start) {
2502
- var result = null;
2503
- var numResult = readPdfNumber(buffer, start);
2504
- if (numResult) {
2505
- var afterFirst = skipPdfWhitespaceAndComments(buffer, numResult.end);
2506
- var genResult = readPdfNumber(buffer, afterFirst);
2507
- if (genResult) {
2508
- var afterSecond = skipPdfWhitespaceAndComments(buffer, genResult.end);
2509
- if (buffer[afterSecond] === 0x52 /* R */ ) {
2510
- var objStart = findIndirectObjectStart(buffer, numResult.value, genResult.value);
2511
- if (objStart >= 0) {
2512
- var dictStart = buffer.indexOf('<<', objStart);
2513
- if (dictStart >= 0) {
2514
- var dictEnd = findDictEnd(buffer, dictStart + 2);
2515
- result = buffer.subarray(dictStart, dictEnd + 2);
2516
- }
2517
- }
2518
- }
2519
- }
2520
- }
2521
- return result;
2522
- }
2523
- function findIndirectObjectStart(buffer, objNum, objGen) {
2524
- var text = buffer.toString('latin1');
2525
- var re = new RegExp(String.raw(_templateObject(), objNum, objGen));
2526
- var match = re.exec(text);
2527
- return match ? match.index + match[0].length : -1;
2528
- }
2529
- function parseEncryptionInfo(dictBuffer) {
2530
- // `dictBuffer` is the full `<< ... >>`; pass the body to parsePdfDict.
2531
- var result = null;
2532
- var isDict = dictBuffer.length >= 4 && dictBuffer[0] === 0x3c && dictBuffer[1] === 0x3c;
2533
- var parsed = isDict ? parsePdfDict(dictBuffer, 2) : null;
2534
- if (parsed) {
2535
- var _readNameValue, _readNumberValue, _readNumberValue1, _readNumberValue2, _readStringValue, _readStringValue1, _readNumberValue3, _readBooleanValue;
2536
- var entries = parsed.entries;
2537
- var filter = (_readNameValue = readNameValue(entries.get('Filter'))) !== null && _readNameValue !== void 0 ? _readNameValue : '';
2538
- var V = (_readNumberValue = readNumberValue(entries.get('V'))) !== null && _readNumberValue !== void 0 ? _readNumberValue : 0;
2539
- var R = (_readNumberValue1 = readNumberValue(entries.get('R'))) !== null && _readNumberValue1 !== void 0 ? _readNumberValue1 : 0;
2540
- var Length = (_readNumberValue2 = readNumberValue(entries.get('Length'))) !== null && _readNumberValue2 !== void 0 ? _readNumberValue2 : V >= 5 ? 256 : 40;
2541
- var O = (_readStringValue = readStringValue(entries.get('O'))) !== null && _readStringValue !== void 0 ? _readStringValue : Buffer.alloc(0);
2542
- var U = (_readStringValue1 = readStringValue(entries.get('U'))) !== null && _readStringValue1 !== void 0 ? _readStringValue1 : Buffer.alloc(0);
2543
- var P = (_readNumberValue3 = readNumberValue(entries.get('P'))) !== null && _readNumberValue3 !== void 0 ? _readNumberValue3 : 0;
2544
- var encryptMetadataEntry = entries.get('EncryptMetadata');
2545
- var encryptMetadata = encryptMetadataEntry ? (_readBooleanValue = readBooleanValue(encryptMetadataEntry)) !== null && _readBooleanValue !== void 0 ? _readBooleanValue : true : true;
2546
- if (R !== 0 && V !== 0) {
2547
- result = {
2548
- filter: filter,
2549
- V: V,
2550
- R: R,
2551
- Length: Length,
2552
- O: O,
2553
- U: U,
2554
- P: P,
2555
- encryptMetadata: encryptMetadata
2556
- };
2557
- }
2558
- }
2559
- return result;
2560
- }
2561
- function readNumberValue(entry) {
2562
- var result = null;
2563
- if ((entry === null || entry === void 0 ? void 0 : entry.type) === 'number') {
2564
- var value = Number(entry.raw.toString('latin1'));
2565
- if (!Number.isNaN(value)) {
2566
- result = value;
2567
- }
2568
- }
2569
- return result;
2570
- }
2571
- function readNameValue(entry) {
2572
- return (entry === null || entry === void 0 ? void 0 : entry.type) === 'name' ? entry.raw.toString('latin1') : null;
2573
- }
2574
- function readStringValue(entry) {
2575
- return (entry === null || entry === void 0 ? void 0 : entry.type) === 'string' ? entry.raw : null;
2576
- }
2577
- function readBooleanValue(entry) {
2578
- return entry.type === 'boolean' ? entry.raw.toString('latin1') === 'true' : null;
2579
- }
2580
- function extractFirstFileId(buffer) {
2581
- // The /ID array lives in the trailer or the cross-reference stream dictionary.
2582
- // Walk the buffer right-to-left to find the most recent /ID array.
2583
- var result = null;
2584
- var pos = buffer.length;
2585
- var done = false;
2586
- while(pos > 0 && !done){
2587
- var found = buffer.lastIndexOf('/ID', pos);
2588
- if (found < 0) {
2589
- done = true;
2590
- } else {
2591
- var after = found + 3;
2592
- var isExactName = after >= buffer.length || isPdfWhitespaceOrDelimiter(buffer[after]);
2593
- if (isExactName) {
2594
- var i = skipPdfWhitespaceAndComments(buffer, after);
2595
- if (buffer[i] === 0x5b /* [ */ ) {
2596
- i = skipPdfWhitespaceAndComments(buffer, i + 1);
2597
- var valueResult = readPdfValue(buffer, i);
2598
- if ((valueResult === null || valueResult === void 0 ? void 0 : valueResult.entry.type) === 'string') {
2599
- result = valueResult.entry.raw;
2600
- done = true;
2601
- }
2602
- }
2603
- }
2604
- if (!done) {
2605
- pos = found - 1;
2606
- }
2607
- }
2608
- }
2609
- return result;
2610
- }
2611
- // MARK: Standard security handler — empty-password validation
2612
- function rc4(key, data) {
2613
- var S = new Uint8Array(256);
2614
- for(var i = 0; i < 256; i++)S[i] = i;
2615
- var j = 0;
2616
- for(var i1 = 0; i1 < 256; i1++){
2617
- j = j + S[i1] + key[i1 % key.length] & 0xff;
2618
- var t = S[i1];
2619
- S[i1] = S[j];
2620
- S[j] = t;
2621
- }
2622
- var out = Buffer.alloc(data.length);
2623
- var ii = 0;
2624
- var jj = 0;
2625
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2626
- try {
2627
- for(var _iterator = data.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2628
- var _step_value = _sliced_to_array(_step.value, 2), n = _step_value[0], byte = _step_value[1];
2629
- ii = ii + 1 & 0xff;
2630
- jj = jj + S[ii] & 0xff;
2631
- var t1 = S[ii];
2632
- S[ii] = S[jj];
2633
- S[jj] = t1;
2634
- out[n] = byte ^ S[S[ii] + S[jj] & 0xff];
2635
- }
2636
- } catch (err) {
2637
- _didIteratorError = true;
2638
- _iteratorError = err;
2639
- } finally{
2640
- try {
2641
- if (!_iteratorNormalCompletion && _iterator.return != null) {
2642
- _iterator.return();
2643
- }
2644
- } finally{
2645
- if (_didIteratorError) {
2646
- throw _iteratorError;
2647
- }
2648
- }
2649
- }
2650
- return out;
2651
- }
2652
- function computeFileEncryptionKeyR2to4(info, password, fileId) {
2653
- var padded = Buffer.alloc(32);
2654
- password.copy(padded, 0, 0, Math.min(password.length, 32));
2655
- if (password.length < 32) PDF_PASSWORD_PADDING.copy(padded, password.length, 0, 32 - password.length);
2656
- var md5 = node_crypto.createHash('md5');
2657
- md5.update(padded);
2658
- md5.update(info.O);
2659
- var pBytes = Buffer.alloc(4);
2660
- pBytes.writeInt32LE(Math.trunc(info.P), 0);
2661
- md5.update(pBytes);
2662
- md5.update(fileId);
2663
- if (info.R >= 4 && !info.encryptMetadata) md5.update(Buffer.from([
2664
- 0xff,
2665
- 0xff,
2666
- 0xff,
2667
- 0xff
2668
- ]));
2669
- var key = md5.digest();
2670
- var keyBytes = Math.min(Math.floor(info.Length / 8), key.length);
2671
- if (info.R >= 3) {
2672
- for(var i = 0; i < 50; i++){
2673
- key = node_crypto.createHash('md5').update(key.subarray(0, keyBytes)).digest();
2674
- }
2675
- }
2676
- return key.subarray(0, keyBytes);
2677
- }
2678
- function validateEmptyPasswordR2to4(info, fileId) {
2679
- var password = Buffer.alloc(0);
2680
- var key = computeFileEncryptionKeyR2to4(info, password, fileId);
2681
- var matches;
2682
- if (info.R === 2) {
2683
- var expected = rc4(key, PDF_PASSWORD_PADDING);
2684
- matches = constantTimeEquals(expected, info.U.subarray(0, 32));
2685
- } else {
2686
- var computed = node_crypto.createHash('md5').update(PDF_PASSWORD_PADDING).update(fileId).digest();
2687
- computed = rc4(key, computed);
2688
- for(var i = 1; i <= 19; i++){
2689
- var xorKey = Buffer.alloc(key.length);
2690
- for(var j = 0; j < key.length; j++)xorKey[j] = key[j] ^ i;
2691
- computed = rc4(xorKey, computed);
2692
- }
2693
- matches = constantTimeEquals(computed, info.U.subarray(0, 16));
2694
- }
2695
- return matches;
2696
- }
2697
- function validateEmptyPasswordR5(info) {
2698
- var validationSalt = info.U.subarray(32, 40);
2699
- var computed = node_crypto.createHash('sha256').update(validationSalt).digest();
2700
- return constantTimeEquals(computed, info.U.subarray(0, 32));
2701
- }
2702
- function validateEmptyPasswordR6(info) {
2703
- var validationSalt = info.U.subarray(32, 40);
2704
- var password = Buffer.alloc(0);
2705
- var computed = pdfAlgorithm2B(Buffer.concat([
2706
- password,
2707
- validationSalt
2708
- ]), password, Buffer.alloc(0));
2709
- return constantTimeEquals(computed, info.U.subarray(0, 32));
2710
- }
2711
- function pdfAlgorithm2B(input, password, userKey) {
2712
- var K = node_crypto.createHash('sha256').update(input).digest();
2713
- var round = 0;
2714
- var lastE;
2715
- while(true){
2716
- var part = Buffer.concat([
2717
- password,
2718
- K,
2719
- userKey
2720
- ]);
2721
- var K1 = Buffer.alloc(part.length * 64);
2722
- for(var i = 0; i < 64; i++)part.copy(K1, i * part.length);
2723
- // PDF 1.7 spec (Algorithm 2.B) requires AES-128-CBC with autoPadding disabled
2724
- // NOSONAR (typescript:S5542): cipher mode is dictated by the PDF standard
2725
- var cipher = node_crypto.createCipheriv('aes-128-cbc', K.subarray(0, 16), K.subarray(16, 32));
2726
- cipher.setAutoPadding(false);
2727
- var E = Buffer.concat([
2728
- cipher.update(K1),
2729
- cipher.final()
2730
- ]);
2731
- lastE = E;
2732
- var n = 0;
2733
- for(var i1 = 0; i1 < 16; i1++)n = (n * 256 + E[i1]) % 3;
2734
- if (n === 0) K = node_crypto.createHash('sha256').update(E).digest();
2735
- else if (n === 1) K = node_crypto.createHash('sha384').update(E).digest();
2736
- else K = node_crypto.createHash('sha512').update(E).digest();
2737
- round++;
2738
- if (round >= 64 && lastE[lastE.length - 1] <= round - 32) break;
2739
- }
2740
- return K.subarray(0, 32);
2741
- }
2742
- function constantTimeEquals(a, b) {
2743
- var result = false;
2744
- if (a.length === b.length) {
2745
- var diff = 0;
2746
- for(var i = 0; i < a.length; i++)diff |= a[i] ^ b[i];
2747
- result = diff === 0;
2748
- }
2749
- return result;
2750
- }
2751
-
2752
- exports.AppModuleWithWebhooksEnabled = AppModuleWithWebhooksEnabled;
2753
- exports.CLIENT_WEB_APP_URL_ENV_VAR = CLIENT_WEB_APP_URL_ENV_VAR;
2754
- exports.ClientAppServiceConfig = ClientAppServiceConfig;
2755
- exports.DEFAULT_BASE_WEBHOOK_PATH = DEFAULT_BASE_WEBHOOK_PATH;
2756
- exports.DEFAULT_JSON_FILE_CACHE_MODE = DEFAULT_JSON_FILE_CACHE_MODE;
2757
- exports.DEFAULT_WEBHOOK_MIDDLEWARE_ROUTE_INFO = DEFAULT_WEBHOOK_MIDDLEWARE_ROUTE_INFO;
2758
- exports.IsRequestFromLocalHost = IsRequestFromLocalHost;
2759
- exports.ParseRawBody = ParseRawBody;
2760
- exports.ParsedQueryRawBody = ParsedQueryRawBody;
2761
- exports.RawBody = RawBody;
2762
- exports.RawBodyToJson = RawBodyToJson;
2763
- exports.RawBodyToParsedQueryString = RawBodyToParsedQueryString;
2764
- exports.RawBodyToString = RawBodyToString;
2765
- exports.SERVER_ENV_TOKEN = SERVER_ENV_TOKEN;
2766
- exports.ServerEnvironmentConfig = ServerEnvironmentConfig;
2767
- exports.appAssetLoaderModuleMetadata = appAssetLoaderModuleMetadata;
2768
- exports.clientAppConfigFactory = clientAppConfigFactory;
2769
- exports.consumeWebhooksWithRawBodyMiddleware = consumeWebhooksWithRawBodyMiddleware;
2770
- exports.createAES256GCMEncryption = createAES256GCMEncryption;
2771
- exports.createAesStringEncryptionProvider = createAesStringEncryptionProvider;
2772
- exports.createJsonFileAsyncKeyedValueCache = createJsonFileAsyncKeyedValueCache;
2773
- exports.createJsonFileAsyncValueCache = createJsonFileAsyncValueCache;
2774
- exports.createMemoizedJsonFileAsyncKeyedValueCache = createMemoizedJsonFileAsyncKeyedValueCache;
2775
- exports.createMemoizedJsonFileAsyncValueCache = createMemoizedJsonFileAsyncValueCache;
2776
- exports.decryptValue = decryptValue;
2777
- exports.detectPdfEncryption = detectPdfEncryption;
2778
- exports.encryptValue = encryptValue;
2779
- exports.injectionTokensFromProviders = injectionTokensFromProviders;
2780
- exports.isLocalhost = isLocalhost;
2781
- exports.isTestNodeEnv = isTestNodeEnv;
2782
- exports.isValidAES256GCMEncryptionSecret = isValidAES256GCMEncryptionSecret;
2783
- exports.mergeModuleMetadata = mergeModuleMetadata;
2784
- exports.nodeJsLocalAssetLoader = nodeJsLocalAssetLoader;
2785
- exports.readJsonFile = readJsonFile;
2786
- exports.removeFile = removeFile;
2787
- exports.resolveEncryptionKey = resolveEncryptionKey;
2788
- exports.serverEnvTokenProvider = serverEnvTokenProvider;
2789
- exports.writeJsonFile = writeJsonFile;