@malloy-publisher/server 0.2.6 → 0.2.7

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.
@@ -2354,725 +2354,265 @@ var init_telemetry = __esm(() => {
2354
2354
  import_api = __toESM(require_src(), 1);
2355
2355
  });
2356
2356
 
2357
- // src/errors.ts
2358
- import { MalloyError } from "@malloydata/malloy";
2359
- function internalErrorToHttpError(error) {
2360
- if (error instanceof BadRequestError) {
2361
- return httpError(400, error.message);
2362
- } else if (error instanceof FrozenConfigError) {
2363
- return httpError(403, error.message);
2364
- } else if (error instanceof AccessDeniedError) {
2365
- return httpError(403, error.message);
2366
- } else if (error instanceof EnvironmentNotFoundError) {
2367
- return httpError(404, error.message);
2368
- } else if (error instanceof PackageNotFoundError) {
2369
- return httpError(404, error.message);
2370
- } else if (error instanceof ModelNotFoundError) {
2371
- return httpError(404, error.message);
2372
- } else if (error instanceof DashboardNotFoundError) {
2373
- return httpError(404, error.message);
2374
- } else if (error instanceof NotQueryableError) {
2375
- return httpError(404, error.message);
2376
- } else if (error instanceof MalloyError) {
2377
- return httpError(400, error.message);
2378
- } else if (error instanceof TableNotFoundError) {
2379
- return httpError(404, error.message, "TABLE_NOT_FOUND");
2380
- } else if (error instanceof ConnectionNotFoundError) {
2381
- return httpError(404, error.message);
2382
- } else if (error instanceof DestinationNotFoundError) {
2383
- return httpError(422, error.message);
2384
- } else if (error instanceof ConnectionAuthError) {
2385
- return httpError(422, error.message);
2386
- } else if (error instanceof UnsupportedCatalogFormatError) {
2387
- return httpError(422, error.message);
2388
- } else if (error instanceof MaterializationEligibilityError) {
2389
- return httpError(422, error.message);
2390
- } else if (error instanceof ModelCompilationError) {
2391
- return httpError(424, error.message);
2392
- } else if (error instanceof ConnectionError) {
2393
- return httpError(502, error.message);
2394
- } else if (error instanceof MaterializationNotFoundError) {
2395
- return httpError(404, error.message);
2396
- } else if (error instanceof MaterializationConflictError) {
2397
- return httpError(409, error.message);
2398
- } else if (error instanceof InvalidStateTransitionError) {
2399
- return httpError(409, error.message);
2400
- } else if (error instanceof ServiceUnavailableError) {
2401
- return httpError(503, error.message);
2402
- } else if (error instanceof PayloadTooLargeError) {
2403
- return httpError(413, error.message);
2404
- } else if (error instanceof QueryTimeoutError) {
2405
- return httpError(504, error.message);
2406
- } else if (error instanceof NotImplementedError) {
2407
- return httpError(501, error.message);
2408
- } else {
2409
- return httpError(500, error.message);
2357
+ // ../../node_modules/logform/format.js
2358
+ var require_format = __commonJS((exports, module) => {
2359
+ class InvalidFormatError extends Error {
2360
+ constructor(formatFn) {
2361
+ super(`Format functions must be synchronous taking a two arguments: (info, opts)
2362
+ Found: ${formatFn.toString().split(`
2363
+ `)[0]}
2364
+ `);
2365
+ Error.captureStackTrace(this, InvalidFormatError);
2366
+ }
2410
2367
  }
2411
- }
2412
- function httpError(code, message, reason) {
2413
- return {
2414
- status: code,
2415
- json: {
2416
- code,
2417
- message,
2418
- ...reason ? { reason } : {}
2368
+ module.exports = (formatFn) => {
2369
+ if (formatFn.length > 2) {
2370
+ throw new InvalidFormatError(formatFn);
2419
2371
  }
2420
- };
2421
- }
2422
- var NotImplementedError, BadRequestError, InvalidArgumentError, EnvironmentNotFoundError, PackageNotFoundError, ModelNotFoundError, DashboardNotFoundError, ConnectionNotFoundError, TableNotFoundError, ConnectionError, DestinationNotFoundError, ConnectionAuthError, UnsupportedCatalogFormatError, ModelCompilationError, MaterializationEligibilityError, PublisherConfigError, FrozenConfigError, AccessDeniedError, NotQueryableError, MaterializationNotFoundError, MaterializationConflictError, InvalidStateTransitionError, ServiceUnavailableError, PayloadTooLargeError, ResponseUnserializableError, QueryTimeoutError;
2423
- var init_errors = __esm(() => {
2424
- init_constants();
2425
- NotImplementedError = class NotImplementedError extends Error {
2426
- constructor(message) {
2427
- super(message);
2372
+ function Format(options = {}) {
2373
+ this.options = options;
2428
2374
  }
2429
- };
2430
- BadRequestError = class BadRequestError extends Error {
2431
- constructor(message) {
2432
- super(message);
2375
+ Format.prototype.transform = formatFn;
2376
+ function createFormatWrap(opts) {
2377
+ return new Format(opts);
2433
2378
  }
2379
+ createFormatWrap.Format = Format;
2380
+ return createFormatWrap;
2434
2381
  };
2435
- InvalidArgumentError = class InvalidArgumentError extends BadRequestError {
2436
- };
2437
- EnvironmentNotFoundError = class EnvironmentNotFoundError extends Error {
2438
- constructor(message) {
2439
- super(message);
2440
- }
2382
+ });
2383
+
2384
+ // ../../node_modules/@colors/colors/lib/styles.js
2385
+ var require_styles = __commonJS((exports, module) => {
2386
+ var styles = {};
2387
+ module["exports"] = styles;
2388
+ var codes = {
2389
+ reset: [0, 0],
2390
+ bold: [1, 22],
2391
+ dim: [2, 22],
2392
+ italic: [3, 23],
2393
+ underline: [4, 24],
2394
+ inverse: [7, 27],
2395
+ hidden: [8, 28],
2396
+ strikethrough: [9, 29],
2397
+ black: [30, 39],
2398
+ red: [31, 39],
2399
+ green: [32, 39],
2400
+ yellow: [33, 39],
2401
+ blue: [34, 39],
2402
+ magenta: [35, 39],
2403
+ cyan: [36, 39],
2404
+ white: [37, 39],
2405
+ gray: [90, 39],
2406
+ grey: [90, 39],
2407
+ brightRed: [91, 39],
2408
+ brightGreen: [92, 39],
2409
+ brightYellow: [93, 39],
2410
+ brightBlue: [94, 39],
2411
+ brightMagenta: [95, 39],
2412
+ brightCyan: [96, 39],
2413
+ brightWhite: [97, 39],
2414
+ bgBlack: [40, 49],
2415
+ bgRed: [41, 49],
2416
+ bgGreen: [42, 49],
2417
+ bgYellow: [43, 49],
2418
+ bgBlue: [44, 49],
2419
+ bgMagenta: [45, 49],
2420
+ bgCyan: [46, 49],
2421
+ bgWhite: [47, 49],
2422
+ bgGray: [100, 49],
2423
+ bgGrey: [100, 49],
2424
+ bgBrightRed: [101, 49],
2425
+ bgBrightGreen: [102, 49],
2426
+ bgBrightYellow: [103, 49],
2427
+ bgBrightBlue: [104, 49],
2428
+ bgBrightMagenta: [105, 49],
2429
+ bgBrightCyan: [106, 49],
2430
+ bgBrightWhite: [107, 49],
2431
+ blackBG: [40, 49],
2432
+ redBG: [41, 49],
2433
+ greenBG: [42, 49],
2434
+ yellowBG: [43, 49],
2435
+ blueBG: [44, 49],
2436
+ magentaBG: [45, 49],
2437
+ cyanBG: [46, 49],
2438
+ whiteBG: [47, 49]
2441
2439
  };
2442
- PackageNotFoundError = class PackageNotFoundError extends Error {
2443
- constructor(message) {
2444
- super(message);
2445
- }
2440
+ Object.keys(codes).forEach(function(key) {
2441
+ var val = codes[key];
2442
+ var style = styles[key] = [];
2443
+ style.open = "\x1B[" + val[0] + "m";
2444
+ style.close = "\x1B[" + val[1] + "m";
2445
+ });
2446
+ });
2447
+
2448
+ // ../../node_modules/@colors/colors/lib/system/has-flag.js
2449
+ var require_has_flag = __commonJS((exports, module) => {
2450
+ module.exports = function(flag, argv) {
2451
+ argv = argv || process.argv || [];
2452
+ var terminatorPos = argv.indexOf("--");
2453
+ var prefix = /^-{1,2}/.test(flag) ? "" : "--";
2454
+ var pos = argv.indexOf(prefix + flag);
2455
+ return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
2446
2456
  };
2447
- ModelNotFoundError = class ModelNotFoundError extends Error {
2448
- constructor(message) {
2449
- super(message);
2457
+ });
2458
+
2459
+ // ../../node_modules/@colors/colors/lib/system/supports-colors.js
2460
+ var require_supports_colors = __commonJS((exports, module) => {
2461
+ var os2 = __require("os");
2462
+ var hasFlag = require_has_flag();
2463
+ var env = process.env;
2464
+ var forceColor = undefined;
2465
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false")) {
2466
+ forceColor = false;
2467
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
2468
+ forceColor = true;
2469
+ }
2470
+ if ("FORCE_COLOR" in env) {
2471
+ forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
2472
+ }
2473
+ function translateLevel(level) {
2474
+ if (level === 0) {
2475
+ return false;
2450
2476
  }
2451
- };
2452
- DashboardNotFoundError = class DashboardNotFoundError extends Error {
2453
- constructor(message) {
2454
- super(message);
2477
+ return {
2478
+ level,
2479
+ hasBasic: true,
2480
+ has256: level >= 2,
2481
+ has16m: level >= 3
2482
+ };
2483
+ }
2484
+ function supportsColor(stream) {
2485
+ if (forceColor === false) {
2486
+ return 0;
2455
2487
  }
2456
- };
2457
- ConnectionNotFoundError = class ConnectionNotFoundError extends Error {
2458
- constructor(message) {
2459
- super(message);
2488
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
2489
+ return 3;
2460
2490
  }
2461
- };
2462
- TableNotFoundError = class TableNotFoundError extends Error {
2463
- constructor(message) {
2464
- super(message);
2491
+ if (hasFlag("color=256")) {
2492
+ return 2;
2465
2493
  }
2466
- };
2467
- ConnectionError = class ConnectionError extends Error {
2468
- constructor(message) {
2469
- super(message);
2494
+ if (stream && !stream.isTTY && forceColor !== true) {
2495
+ return 0;
2470
2496
  }
2471
- };
2472
- DestinationNotFoundError = class DestinationNotFoundError extends Error {
2473
- constructor(message) {
2474
- super(message);
2497
+ var min = forceColor ? 1 : 0;
2498
+ if (process.platform === "win32") {
2499
+ var osRelease = os2.release().split(".");
2500
+ if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
2501
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
2502
+ }
2503
+ return 1;
2475
2504
  }
2476
- };
2477
- ConnectionAuthError = class ConnectionAuthError extends Error {
2478
- constructor(message) {
2479
- super(message);
2505
+ if ("CI" in env) {
2506
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) {
2507
+ return sign in env;
2508
+ }) || env.CI_NAME === "codeship") {
2509
+ return 1;
2510
+ }
2511
+ return min;
2480
2512
  }
2481
- };
2482
- UnsupportedCatalogFormatError = class UnsupportedCatalogFormatError extends Error {
2483
- constructor(message) {
2484
- super(message);
2513
+ if ("TEAMCITY_VERSION" in env) {
2514
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2485
2515
  }
2486
- };
2487
- ModelCompilationError = class ModelCompilationError extends Error {
2488
- constructor(error) {
2489
- super(error.message);
2490
- }
2491
- };
2492
- MaterializationEligibilityError = class MaterializationEligibilityError extends Error {
2493
- reason;
2494
- constructor(error) {
2495
- super(error.message);
2496
- this.name = "MaterializationEligibilityError";
2497
- this.reason = error.reason;
2498
- }
2499
- };
2500
- PublisherConfigError = class PublisherConfigError extends Error {
2501
- constructor(configName, cause) {
2502
- super(`Could not read ${configName}: ${cause instanceof Error ? cause.message : String(cause)}. Fix the file, or move it aside to fall back to the bundled default.`);
2503
- this.name = "PublisherConfigError";
2504
- this.cause = cause;
2505
- }
2506
- };
2507
- FrozenConfigError = class FrozenConfigError extends Error {
2508
- constructor(message = `Publisher config can't be updated when ${PUBLISHER_CONFIG_NAME} has { "frozenConfig": true }`) {
2509
- super(message);
2510
- }
2511
- };
2512
- AccessDeniedError = class AccessDeniedError extends Error {
2513
- constructor(message) {
2514
- super(message);
2515
- this.name = "AccessDeniedError";
2516
- }
2517
- };
2518
- NotQueryableError = class NotQueryableError extends Error {
2519
- constructor(message) {
2520
- super(message);
2521
- this.name = "NotQueryableError";
2522
- }
2523
- };
2524
- MaterializationNotFoundError = class MaterializationNotFoundError extends Error {
2525
- constructor(message) {
2526
- super(message);
2527
- }
2528
- };
2529
- MaterializationConflictError = class MaterializationConflictError extends Error {
2530
- constructor(message) {
2531
- super(message);
2516
+ if ("TERM_PROGRAM" in env) {
2517
+ var version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
2518
+ switch (env.TERM_PROGRAM) {
2519
+ case "iTerm.app":
2520
+ return version >= 3 ? 3 : 2;
2521
+ case "Hyper":
2522
+ return 3;
2523
+ case "Apple_Terminal":
2524
+ return 2;
2525
+ }
2532
2526
  }
2533
- };
2534
- InvalidStateTransitionError = class InvalidStateTransitionError extends Error {
2535
- constructor(message) {
2536
- super(message);
2527
+ if (/-256(color)?$/i.test(env.TERM)) {
2528
+ return 2;
2537
2529
  }
2538
- };
2539
- ServiceUnavailableError = class ServiceUnavailableError extends Error {
2540
- constructor(message) {
2541
- super(message);
2530
+ if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
2531
+ return 1;
2542
2532
  }
2543
- };
2544
- PayloadTooLargeError = class PayloadTooLargeError extends Error {
2545
- constructor(message) {
2546
- super(message);
2547
- this.name = "PayloadTooLargeError";
2533
+ if ("COLORTERM" in env) {
2534
+ return 1;
2548
2535
  }
2549
- };
2550
- ResponseUnserializableError = class ResponseUnserializableError extends PayloadTooLargeError {
2551
- constructor(message) {
2552
- super(message);
2553
- this.name = "ResponseUnserializableError";
2536
+ if (env.TERM === "dumb") {
2537
+ return min;
2554
2538
  }
2539
+ return min;
2540
+ }
2541
+ function getSupportLevel(stream) {
2542
+ var level = supportsColor(stream);
2543
+ return translateLevel(level);
2544
+ }
2545
+ module.exports = {
2546
+ supportsColor: getSupportLevel,
2547
+ stdout: getSupportLevel(process.stdout),
2548
+ stderr: getSupportLevel(process.stderr)
2555
2549
  };
2556
- QueryTimeoutError = class QueryTimeoutError extends Error {
2557
- constructor(message) {
2558
- super(message);
2559
- }
2560
- };
2561
- });
2562
-
2563
- // src/service/authorize.ts
2564
- import { payloadOf, routeOf } from "@malloydata/malloy";
2565
- function noteRoute(text) {
2566
- return routeOf({ value: text.trimStart() });
2567
- }
2568
- function notePayload(text) {
2569
- return payloadOf({ value: text.trimStart() }) ?? "";
2570
- }
2571
- function authorizeNoteContent(text) {
2572
- return noteRoute(text) === AUTHORIZE_ROUTE ? notePayload(text) : undefined;
2573
- }
2574
- function assertNoCallerAuthorizeAnnotation(callerText) {
2575
- if (!AUTHORIZE_ANNOTATION_ANYWHERE.test(callerText))
2576
- return;
2577
- throw new BadRequestError("An `authorize` annotation is not permitted in caller-submitted Malloy " + "text. Access gates are declared by the model author on the source; a " + "request cannot introduce, replace, or relax one. To validate a gate " + "you are authoring, save it to the package's model file and reload the " + "package — model load validates every `#(authorize)` annotation it " + "declares.");
2578
- }
2579
- function containsAuthorizeAnnotationTag(texts) {
2580
- return texts.some((text) => authorizeNoteContent(text) !== undefined);
2581
- }
2582
- function collectAuthorizeNearMisses(texts) {
2583
- const found = [];
2584
- for (const text of texts) {
2585
- const trimmed = text.trimStart();
2586
- const route = noteRoute(trimmed);
2587
- if (route === AUTHORIZE_ROUTE)
2588
- continue;
2589
- const nearMiss = route === undefined ? MALFORMED_AUTHORIZE_ATTEMPT.test(trimmed) : route === "" ? MOTLY_AUTHORIZE_PAYLOAD.test(notePayload(trimmed)) : route.toLowerCase() === AUTHORIZE_ROUTE;
2590
- if (!nearMiss)
2591
- continue;
2592
- found.push(trimmed.split(/[\r\n]/, 1)[0]);
2593
- }
2594
- return found;
2595
- }
2596
- function assertNoAuthorizeNearMisses(found) {
2597
- if (found.length === 0)
2598
- return;
2599
- const unique = [...new Set(found)];
2600
- throw new ModelCompilationError({
2601
- message: `These annotations are not \`authorize\` gates and nothing enforces ` + `them:
2602
- ${unique.map((t) => ` - \`${t}\``).join(`
2603
- `)}
2604
- ` + `Malloy routes an annotation by its prefix, and only ` + `\`#(authorize)\` (or \`##(authorize)\`, or the block form ` + `\`#|(authorize)\`) reaches the authorize route — a space after the ` + `\`#\`, spaces inside the brackets, or anything trailing the closing ` + `bracket makes it a plain tag Malloy hands to something else. Write ` + `\`#(authorize) <expression>\` on its own line directly above the ` + `\`source:\` statement you mean to protect (unquoted — the quoted ` + `string form is retired). This is refused rather than interpreted: ` + `guessing at the ` + `intent would let publisher start enforcing a filter on a package that ` + `has been serving every row.`
2605
- });
2606
- }
2607
- function describeMisplacedAuthorizeAnnotation(f) {
2608
- if (f.kind === "query")
2609
- return `on query "${f.name}"`;
2610
- if (f.kind === "file")
2611
- return "at the file level (`##(authorize)`)";
2612
- return `on field "${f.fieldName}" of source "${f.name}"`;
2613
- }
2614
- function assertNoMisplacedAuthorizeAnnotations(found) {
2615
- if (found.length === 0)
2616
- return;
2617
- const positions = found.map((f) => ` - ${describeMisplacedAuthorizeAnnotation(f)}`).join(`
2618
- `);
2619
- throw new ModelCompilationError({
2620
- message: `An \`#(authorize)\` annotation is never enforced at:
2621
- ${positions}
2622
- ` + `A gate only applies where model load looks for one — a \`source:\`'s ` + `own annotation, or one it inherits from an \`extend\`/query-source ` + `base. File-level \`##(authorize)\` is deprecated and no longer ` + `enforced anywhere, so it always lands here: declare \`#(authorize)\` ` + `on each \`source:\` it was meant to protect instead. Every other ` + `position above should move to the \`source:\` statement it is meant ` + `to protect.`
2623
- });
2624
- }
2625
- function referencedGivenNames(expr) {
2626
- const scanned = expr.replace(STRING_LITERAL_PATTERN, "''");
2627
- const names = [];
2628
- const seen = new Set;
2629
- for (const match of scanned.matchAll(GIVEN_REF_PATTERN)) {
2630
- const name = match[1];
2631
- if (!seen.has(name)) {
2632
- seen.add(name);
2633
- names.push(name);
2634
- }
2635
- }
2636
- return names;
2637
- }
2638
- function quoteMalloyIdentifier(name) {
2639
- return "`" + name.replace(/\\/g, "\\\\").replace(/`/g, "\\`") + "`";
2640
- }
2641
- function buildRowLevelProbe(graftTarget, filterText) {
2642
- return `run: ${quoteMalloyIdentifier(graftTarget)} extend { where: ${filterText} } -> { select: __authorize_probe is 1; limit: 1 }`;
2643
- }
2644
- function liftProbeFilterCondition(prepared, label, filterText) {
2645
- const filterList = prepared._query?.structRef?.filterList;
2646
- if (!Array.isArray(filterList) || filterList.length === 0) {
2647
- throw new Error(`${label} carries no filter condition`);
2648
- }
2649
- const lifted = filterList[filterList.length - 1];
2650
- if (lifted.code !== filterText) {
2651
- throw new Error(`${label} carries the wrong condition — expected "${filterText}", got "${lifted.code ?? ""}"`);
2652
- }
2653
- if (!lifted.isSourceFilter) {
2654
- throw new Error(`${label} carries a condition that is not a source filter`);
2655
- }
2656
- return lifted;
2657
- }
2658
- function gateFilterText(exprs) {
2659
- return exprs.map((e) => `(${e})`).join(" or ");
2660
- }
2661
- async function liftRowLevelCondition(compiler, sourceName, exprs) {
2662
- const filterText = gateFilterText(exprs);
2663
- const prepared = await compiler.loadQuery(buildRowLevelProbe(sourceName, filterText)).getPreparedQuery();
2664
- return liftProbeFilterCondition(prepared, `row-level probe for "${sourceName}"`, filterText);
2665
- }
2666
- async function validateAuthorizeProbes(compiler, options) {
2667
- const ownNotesOf = options.authorizeOwnNotes ?? new Map;
2668
- for (const [sourceName, groups] of options.authorizeMap ?? []) {
2669
- for (const exprs of groups) {
2670
- if (exprs.length === 0)
2671
- continue;
2672
- let condition;
2673
- try {
2674
- condition = await liftRowLevelCondition(compiler, sourceName, exprs);
2675
- } catch (err) {
2676
- const detail = err instanceof Error ? err.message : String(err);
2677
- const ownNotes = ownNotesOf.get(sourceName) ?? [];
2678
- if (ownNotes.length === 0) {
2679
- options.onRowLevelGateRejected?.("entry_point_unexpressible");
2680
- options.onRowLevelGateUnexpressible?.(sourceName, detail);
2681
- continue;
2682
- }
2683
- throw new ModelCompilationError({
2684
- message: `Invalid #(authorize) annotation on source "${sourceName}" ` + `[${exprs.join(" | ")}]: ${detail}`
2685
- });
2686
- }
2687
- options.onOwnRowLevelConditionCompiled?.(sourceName, condition);
2688
- }
2689
- }
2690
- }
2691
- function isLegacyQuotedPayload(payload) {
2692
- const trimmed = payload.trim();
2693
- return WHOLE_BODY_QUOTED_STRING.test(trimmed) || WHOLE_BODY_SINGLE_QUOTED_STRING.test(trimmed);
2694
- }
2695
- function unquoteLegacyGatePayload(payload) {
2696
- const trimmed = payload.trim();
2697
- const inner = trimmed.slice(1, -1);
2698
- return trimmed[0] === "'" ? inner.replace(SINGLE_QUOTE_ESCAPE, "$1") : inner.replace(DOUBLE_QUOTE_ESCAPE, "$1");
2699
- }
2700
- function parseAuthorizeAnnotation(annotation) {
2701
- const content = authorizeNoteContent(annotation);
2702
- if (content === undefined)
2703
- return null;
2704
- const trimmed = content.trim();
2705
- if (trimmed.length === 0) {
2706
- throw new Error("authorize annotation has an empty expression body");
2707
- }
2708
- return trimmed;
2709
- }
2710
- function collectAuthorizeExprs(annotations) {
2711
- const exprs = [];
2712
- for (const annotation of annotations) {
2713
- const expr = parseAuthorizeAnnotation(annotation);
2714
- if (expr !== null) {
2715
- exprs.push(expr);
2716
- }
2717
- }
2718
- return exprs;
2719
- }
2720
- function findMultipleAuthorizeGates(authorizeOwnNotes) {
2721
- const found = [];
2722
- for (const [sourceName, notes] of authorizeOwnNotes) {
2723
- if (notes.length > 1) {
2724
- found.push({ sourceName, texts: notes.map((note) => note.text) });
2725
- }
2726
- }
2727
- return found;
2728
- }
2729
- function assertAtMostOneAuthorizeGate(found) {
2730
- if (found.length === 0)
2731
- return;
2732
- const positions = found.map(({ sourceName, texts }) => ` - source "${sourceName}" declares ${texts.length}:
2733
- ` + texts.map((t) => ` \`${t.trim().split(/[\r\n]/, 1)[0]}\``).join(`
2734
- `)).join(`
2735
- `);
2736
- throw new ModelCompilationError({
2737
- message: `A source may declare at most one \`#(authorize)\` annotation:
2738
- ${positions}
2739
- ` + `Combine multiple conditions into one expression with \`or\` instead of ` + `repeating the annotation, e.g. ` + "`#(authorize) $ROLE = 'admin' or org_id in $GROUPS`."
2740
- });
2741
- }
2742
- function findLegacyStringGates(authorizeOwnNotes) {
2743
- const found = [];
2744
- for (const [sourceName, notes] of authorizeOwnNotes) {
2745
- const legacyNotes = notes.filter((note) => {
2746
- const content = authorizeNoteContent(note.text);
2747
- return content !== undefined && isLegacyQuotedPayload(content);
2748
- });
2749
- if (legacyNotes.length === 0)
2750
- continue;
2751
- const exprs = collectAuthorizeExprs(legacyNotes.map((note) => note.text));
2752
- if (exprs.length > 0) {
2753
- found.push({ sourceName, exprs });
2754
- }
2755
- }
2756
- return found;
2757
- }
2758
- function assertNoLegacyStringGate(found) {
2759
- if (found.length === 0)
2760
- return;
2761
- const rewrites = found.flatMap(({ sourceName, exprs }) => exprs.map((expr) => ` - source "${sourceName}": replace \`#(authorize) ${expr}\`` + ` with
2762
- #(authorize) ${unquoteLegacyGatePayload(expr)}`)).join(`
2763
- `);
2764
- throw new ModelCompilationError({
2765
- message: `The string form of \`#(authorize)\` (a Malloy-quoted expression on ` + `the \`source:\` line) is no longer accepted. Replace it with the ` + `unquoted expression, carried by an \`#(authorize)\` annotation on ` + `its own line directly above the \`source:\` line:
2766
- ${rewrites}
2767
- ` + `Test that the rewrite gates the same rows and check the row count ` + `matches what the string form served.`
2768
- });
2769
- }
2770
- var AUTHORIZE_ROUTE = "authorize", AUTHORIZE_TAG_LIKE, AUTHORIZE_ANNOTATION_ANYWHERE, MOTLY_AUTHORIZE_PAYLOAD, MALFORMED_AUTHORIZE_ATTEMPT, GIVEN_REF_PATTERN, SINGLE_QUOTE_ESCAPE, DOUBLE_QUOTE_ESCAPE, STRING_LITERAL_PATTERN, everyMemberOf = () => (...members) => members, ROW_LEVEL_GATE_REJECTION_CAUSES, WHOLE_BODY_QUOTED_STRING, WHOLE_BODY_SINGLE_QUOTED_STRING;
2771
- var init_authorize = __esm(() => {
2772
- init_errors();
2773
- AUTHORIZE_TAG_LIKE = String.raw`##?\|?[ \t]*[([{<]?[ \t]*authorize(?=[)\]}>]|[ \t]|$)`;
2774
- AUTHORIZE_ANNOTATION_ANYWHERE = new RegExp(AUTHORIZE_TAG_LIKE, "iu");
2775
- MOTLY_AUTHORIZE_PAYLOAD = /^[ \t]*[([{<][ \t]*authorize[ \t]*[)\]}>]/iu;
2776
- MALFORMED_AUTHORIZE_ATTEMPT = /^##?\|?[ \t]*[([{<]?[ \t]*authorize/iu;
2777
- GIVEN_REF_PATTERN = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
2778
- SINGLE_QUOTE_ESCAPE = /\\(['\\])/g;
2779
- DOUBLE_QUOTE_ESCAPE = /\\(["\\])/g;
2780
- STRING_LITERAL_PATTERN = /'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"/g;
2781
- ROW_LEVEL_GATE_REJECTION_CAUSES = everyMemberOf()("unreachable_given", "entry_point_unexpressible", "source_line_gate_no_given_reference", "source_line_gate_negated_membership", "legacy_string_gate", "given_usage_unresolvable", "unclassifiable_condition");
2782
- WHOLE_BODY_QUOTED_STRING = /^"(?:\\.|[^"\\])*"$/;
2783
- WHOLE_BODY_SINGLE_QUOTED_STRING = /^'(?:\\.|[^'\\])*'$/;
2784
- });
2785
-
2786
- // src/authorize_metrics.ts
2787
- function recordAuthorizeGuardRejection(field) {
2788
- guardRejectionCounter ??= publisherMeter().createCounter("publisher_authorize_guard_rejected_total", {
2789
- description: "Requests rejected with 400 for declaring an `#(authorize)` annotation in caller-submitted Malloy text. Label: field ('query'|'source_name'|'query_name'|'compile_source')."
2790
- });
2791
- guardRejectionCounter.add(1, { field });
2792
- }
2793
- function recordAuthorizeBypass(entryPoint) {
2794
- bypassCounter ??= publisherMeter().createCounter("publisher_authorize_bypass_total", {
2795
- description: "Gate evaluations skipped because the request carried an authorize bypass (private data-management path). Label: entry_point ('source'|'runnable'). Any nonzero value on a path that should not use the bypass is a finding — see the paired `authorize bypass` audit log line for org/package/model/source."
2796
- });
2797
- bypassCounter.add(1, { entry_point: entryPoint });
2798
- }
2799
- function recordRowLevelGateDecision(decision) {
2800
- rowLevelDecisionCounter ??= publisherMeter().createCounter("publisher_authorize_row_level_total", {
2801
- description: "How a row-level `#(authorize)` gate resolved a request. Label: decision ('denied_by_gate'|'empty_after_filter'). 'denied_by_gate' is the fail-closed refusal when the gate could not be applied; 'empty_after_filter' is a successful response with zero rows after the filter matched none, which is NOT an error."
2802
- });
2803
- rowLevelDecisionCounter.add(1, { decision });
2804
- }
2805
- function recordRowLevelGateRejected(cause) {
2806
- rowLevelRejectionCounter ??= publisherMeter().createCounter("publisher_authorize_row_level_rejected_total", {
2807
- description: "Row-level `#(authorize)` gates that were refused, warned about, or could not be resolved. Label: cause (" + ROW_LEVEL_GATE_REJECTION_CAUSES.map((c) => `'${c}'`).join("|") + "). Only 'legacy_string_gate' fails the whole model load. 'entry_point_unexpressible', 'source_line_gate_no_given_reference' and 'source_line_gate_negated_membership' warn at load and leave the model servable. 'unreachable_given', 'given_usage_unresolvable' and 'unclassifiable_condition' are request-time only — that entry point denies every request. Alert on any nonzero value since the last publish; the request-time causes also make this a rate signal, so see the doc above before writing an alert."
2808
- });
2809
- rowLevelRejectionCounter.add(1, { cause });
2810
- }
2811
- var guardRejectionCounter = null, bypassCounter = null, rowLevelDecisionCounter = null, rowLevelRejectionCounter = null;
2812
- var init_authorize_metrics = __esm(() => {
2813
- init_telemetry();
2814
- init_authorize();
2815
- });
2816
-
2817
- // ../../node_modules/logform/format.js
2818
- var require_format = __commonJS((exports, module) => {
2819
- class InvalidFormatError extends Error {
2820
- constructor(formatFn) {
2821
- super(`Format functions must be synchronous taking a two arguments: (info, opts)
2822
- Found: ${formatFn.toString().split(`
2823
- `)[0]}
2824
- `);
2825
- Error.captureStackTrace(this, InvalidFormatError);
2826
- }
2827
- }
2828
- module.exports = (formatFn) => {
2829
- if (formatFn.length > 2) {
2830
- throw new InvalidFormatError(formatFn);
2831
- }
2832
- function Format(options = {}) {
2833
- this.options = options;
2834
- }
2835
- Format.prototype.transform = formatFn;
2836
- function createFormatWrap(opts) {
2837
- return new Format(opts);
2838
- }
2839
- createFormatWrap.Format = Format;
2840
- return createFormatWrap;
2841
- };
2842
- });
2843
-
2844
- // ../../node_modules/@colors/colors/lib/styles.js
2845
- var require_styles = __commonJS((exports, module) => {
2846
- var styles = {};
2847
- module["exports"] = styles;
2848
- var codes = {
2849
- reset: [0, 0],
2850
- bold: [1, 22],
2851
- dim: [2, 22],
2852
- italic: [3, 23],
2853
- underline: [4, 24],
2854
- inverse: [7, 27],
2855
- hidden: [8, 28],
2856
- strikethrough: [9, 29],
2857
- black: [30, 39],
2858
- red: [31, 39],
2859
- green: [32, 39],
2860
- yellow: [33, 39],
2861
- blue: [34, 39],
2862
- magenta: [35, 39],
2863
- cyan: [36, 39],
2864
- white: [37, 39],
2865
- gray: [90, 39],
2866
- grey: [90, 39],
2867
- brightRed: [91, 39],
2868
- brightGreen: [92, 39],
2869
- brightYellow: [93, 39],
2870
- brightBlue: [94, 39],
2871
- brightMagenta: [95, 39],
2872
- brightCyan: [96, 39],
2873
- brightWhite: [97, 39],
2874
- bgBlack: [40, 49],
2875
- bgRed: [41, 49],
2876
- bgGreen: [42, 49],
2877
- bgYellow: [43, 49],
2878
- bgBlue: [44, 49],
2879
- bgMagenta: [45, 49],
2880
- bgCyan: [46, 49],
2881
- bgWhite: [47, 49],
2882
- bgGray: [100, 49],
2883
- bgGrey: [100, 49],
2884
- bgBrightRed: [101, 49],
2885
- bgBrightGreen: [102, 49],
2886
- bgBrightYellow: [103, 49],
2887
- bgBrightBlue: [104, 49],
2888
- bgBrightMagenta: [105, 49],
2889
- bgBrightCyan: [106, 49],
2890
- bgBrightWhite: [107, 49],
2891
- blackBG: [40, 49],
2892
- redBG: [41, 49],
2893
- greenBG: [42, 49],
2894
- yellowBG: [43, 49],
2895
- blueBG: [44, 49],
2896
- magentaBG: [45, 49],
2897
- cyanBG: [46, 49],
2898
- whiteBG: [47, 49]
2899
- };
2900
- Object.keys(codes).forEach(function(key) {
2901
- var val = codes[key];
2902
- var style = styles[key] = [];
2903
- style.open = "\x1B[" + val[0] + "m";
2904
- style.close = "\x1B[" + val[1] + "m";
2905
- });
2906
- });
2907
-
2908
- // ../../node_modules/@colors/colors/lib/system/has-flag.js
2909
- var require_has_flag = __commonJS((exports, module) => {
2910
- module.exports = function(flag, argv) {
2911
- argv = argv || process.argv || [];
2912
- var terminatorPos = argv.indexOf("--");
2913
- var prefix = /^-{1,2}/.test(flag) ? "" : "--";
2914
- var pos = argv.indexOf(prefix + flag);
2915
- return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
2916
- };
2917
- });
2918
-
2919
- // ../../node_modules/@colors/colors/lib/system/supports-colors.js
2920
- var require_supports_colors = __commonJS((exports, module) => {
2921
- var os2 = __require("os");
2922
- var hasFlag = require_has_flag();
2923
- var env = process.env;
2924
- var forceColor = undefined;
2925
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false")) {
2926
- forceColor = false;
2927
- } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
2928
- forceColor = true;
2929
- }
2930
- if ("FORCE_COLOR" in env) {
2931
- forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
2932
- }
2933
- function translateLevel(level) {
2934
- if (level === 0) {
2935
- return false;
2936
- }
2937
- return {
2938
- level,
2939
- hasBasic: true,
2940
- has256: level >= 2,
2941
- has16m: level >= 3
2942
- };
2943
- }
2944
- function supportsColor(stream) {
2945
- if (forceColor === false) {
2946
- return 0;
2947
- }
2948
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
2949
- return 3;
2950
- }
2951
- if (hasFlag("color=256")) {
2952
- return 2;
2953
- }
2954
- if (stream && !stream.isTTY && forceColor !== true) {
2955
- return 0;
2956
- }
2957
- var min = forceColor ? 1 : 0;
2958
- if (process.platform === "win32") {
2959
- var osRelease = os2.release().split(".");
2960
- if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
2961
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
2962
- }
2963
- return 1;
2964
- }
2965
- if ("CI" in env) {
2966
- if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) {
2967
- return sign in env;
2968
- }) || env.CI_NAME === "codeship") {
2969
- return 1;
2970
- }
2971
- return min;
2972
- }
2973
- if ("TEAMCITY_VERSION" in env) {
2974
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2975
- }
2976
- if ("TERM_PROGRAM" in env) {
2977
- var version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
2978
- switch (env.TERM_PROGRAM) {
2979
- case "iTerm.app":
2980
- return version >= 3 ? 3 : 2;
2981
- case "Hyper":
2982
- return 3;
2983
- case "Apple_Terminal":
2984
- return 2;
2985
- }
2986
- }
2987
- if (/-256(color)?$/i.test(env.TERM)) {
2988
- return 2;
2989
- }
2990
- if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
2991
- return 1;
2992
- }
2993
- if ("COLORTERM" in env) {
2994
- return 1;
2995
- }
2996
- if (env.TERM === "dumb") {
2997
- return min;
2998
- }
2999
- return min;
3000
- }
3001
- function getSupportLevel(stream) {
3002
- var level = supportsColor(stream);
3003
- return translateLevel(level);
3004
- }
3005
- module.exports = {
3006
- supportsColor: getSupportLevel,
3007
- stdout: getSupportLevel(process.stdout),
3008
- stderr: getSupportLevel(process.stderr)
3009
- };
3010
- });
3011
-
3012
- // ../../node_modules/@colors/colors/lib/custom/trap.js
3013
- var require_trap = __commonJS((exports, module) => {
3014
- module["exports"] = function runTheTrap(text, options) {
3015
- var result = "";
3016
- text = text || "Run the trap, drop the bass";
3017
- text = text.split("");
3018
- var trap = {
3019
- a: ["@", "Ą", "Ⱥ", "Ʌ", "Δ", "Λ", "Д"],
3020
- b: ["ß", "Ɓ", "Ƀ", "ɮ", "β", "฿"],
3021
- c: ["©", "Ȼ", "Ͼ"],
3022
- d: ["Ð", "Ɗ", "Ԁ", "ԁ", "Ԃ", "ԃ"],
3023
- e: [
3024
- "Ë",
3025
- "ĕ",
3026
- "Ǝ",
3027
- "ɘ",
3028
- "Σ",
3029
- "ξ",
3030
- "Ҽ",
3031
- "੬"
3032
- ],
3033
- f: ["Ӻ"],
3034
- g: ["ɢ"],
3035
- h: ["Ħ", "ƕ", "Ң", "Һ", "Ӈ", "Ԋ"],
3036
- i: ["༏"],
3037
- j: ["Ĵ"],
3038
- k: ["ĸ", "Ҡ", "Ӄ", "Ԟ"],
3039
- l: ["Ĺ"],
3040
- m: ["ʍ", "Ӎ", "ӎ", "Ԡ", "ԡ", "൩"],
3041
- n: ["Ñ", "ŋ", "Ɲ", "Ͷ", "Π", "Ҋ"],
3042
- o: [
3043
- "Ø",
3044
- "õ",
3045
- "ø",
3046
- "Ǿ",
3047
- "ʘ",
3048
- "Ѻ",
3049
- "ם",
3050
- "۝",
3051
- "๏"
3052
- ],
3053
- p: ["Ƿ", "Ҏ"],
3054
- q: ["্"],
3055
- r: ["®", "Ʀ", "Ȑ", "Ɍ", "ʀ", "Я"],
3056
- s: ["§", "Ϟ", "ϟ", "Ϩ"],
3057
- t: ["Ł", "Ŧ", "ͳ"],
3058
- u: ["Ʊ", "Ս"],
3059
- v: ["ט"],
3060
- w: ["Ш", "Ѡ", "Ѽ", "൰"],
3061
- x: ["Ҳ", "Ӿ", "Ӽ", "ӽ"],
3062
- y: ["¥", "Ұ", "Ӌ"],
3063
- z: ["Ƶ", "ɀ"]
3064
- };
3065
- text.forEach(function(c) {
3066
- c = c.toLowerCase();
3067
- var chars = trap[c] || [" "];
3068
- var rand = Math.floor(Math.random() * chars.length);
3069
- if (typeof trap[c] !== "undefined") {
3070
- result += trap[c][rand];
3071
- } else {
3072
- result += c;
3073
- }
3074
- });
3075
- return result;
2550
+ });
2551
+
2552
+ // ../../node_modules/@colors/colors/lib/custom/trap.js
2553
+ var require_trap = __commonJS((exports, module) => {
2554
+ module["exports"] = function runTheTrap(text, options) {
2555
+ var result = "";
2556
+ text = text || "Run the trap, drop the bass";
2557
+ text = text.split("");
2558
+ var trap = {
2559
+ a: ["@", "Ą", "Ⱥ", "Ʌ", "Δ", "Λ", "Д"],
2560
+ b: ["ß", "Ɓ", "Ƀ", "ɮ", "β", "฿"],
2561
+ c: ["©", "Ȼ", "Ͼ"],
2562
+ d: ["Ð", "Ɗ", "Ԁ", "ԁ", "Ԃ", "ԃ"],
2563
+ e: [
2564
+ "Ë",
2565
+ "ĕ",
2566
+ "Ǝ",
2567
+ "ɘ",
2568
+ "Σ",
2569
+ "ξ",
2570
+ "Ҽ",
2571
+ ""
2572
+ ],
2573
+ f: ["Ӻ"],
2574
+ g: ["ɢ"],
2575
+ h: ["Ħ", "ƕ", "Ң", "Һ", "Ӈ", "Ԋ"],
2576
+ i: ["༏"],
2577
+ j: ["Ĵ"],
2578
+ k: ["ĸ", "Ҡ", "Ӄ", "Ԟ"],
2579
+ l: ["Ĺ"],
2580
+ m: ["ʍ", "Ӎ", "ӎ", "Ԡ", "ԡ", "൩"],
2581
+ n: ["Ñ", "ŋ", "Ɲ", "Ͷ", "Π", "Ҋ"],
2582
+ o: [
2583
+ "Ø",
2584
+ "õ",
2585
+ "ø",
2586
+ "Ǿ",
2587
+ "ʘ",
2588
+ "Ѻ",
2589
+ "ם",
2590
+ "۝",
2591
+ "๏"
2592
+ ],
2593
+ p: ["Ƿ", "Ҏ"],
2594
+ q: ["্"],
2595
+ r: ["®", "Ʀ", "Ȑ", "Ɍ", "ʀ", "Я"],
2596
+ s: ["§", "Ϟ", "ϟ", "Ϩ"],
2597
+ t: ["Ł", "Ŧ", "ͳ"],
2598
+ u: ["Ʊ", "Ս"],
2599
+ v: ["ט"],
2600
+ w: ["Ш", "Ѡ", "Ѽ", "൰"],
2601
+ x: ["Ҳ", "Ӿ", "Ӽ", "ӽ"],
2602
+ y: ["¥", "Ұ", "Ӌ"],
2603
+ z: ["Ƶ", "ɀ"]
2604
+ };
2605
+ text.forEach(function(c) {
2606
+ c = c.toLowerCase();
2607
+ var chars = trap[c] || [" "];
2608
+ var rand = Math.floor(Math.random() * chars.length);
2609
+ if (typeof trap[c] !== "undefined") {
2610
+ result += trap[c][rand];
2611
+ } else {
2612
+ result += c;
2613
+ }
2614
+ });
2615
+ return result;
3076
2616
  };
3077
2617
  });
3078
2618
 
@@ -11717,1604 +11257,2085 @@ var require_file = __commonJS((exports, module) => {
11717
11257
  if (!this.maxFiles || this._created < this.maxFiles) {
11718
11258
  return setImmediate(callback);
11719
11259
  }
11720
- const oldest = this._created - this.maxFiles;
11721
- const isOldest = oldest !== 0 ? oldest : "";
11722
- const isZipped = this.zippedArchive ? ".gz" : "";
11723
- const filePath = `${basename}${isOldest}${ext}${isZipped}`;
11724
- const target = path.join(this.dirname, filePath);
11725
- fs.unlink(target, callback);
11260
+ const oldest = this._created - this.maxFiles;
11261
+ const isOldest = oldest !== 0 ? oldest : "";
11262
+ const isZipped = this.zippedArchive ? ".gz" : "";
11263
+ const filePath = `${basename}${isOldest}${ext}${isZipped}`;
11264
+ const target = path.join(this.dirname, filePath);
11265
+ fs.unlink(target, callback);
11266
+ }
11267
+ _checkMaxFilesTailable(ext, basename, callback) {
11268
+ const tasks = [];
11269
+ if (!this.maxFiles) {
11270
+ return;
11271
+ }
11272
+ const isZipped = this.zippedArchive ? ".gz" : "";
11273
+ for (let x = this.maxFiles - 1;x > 1; x--) {
11274
+ tasks.push(function(i, cb) {
11275
+ let fileName = `${basename}${i - 1}${ext}${isZipped}`;
11276
+ const tmppath = path.join(this.dirname, fileName);
11277
+ fs.exists(tmppath, (exists) => {
11278
+ if (!exists) {
11279
+ return cb(null);
11280
+ }
11281
+ fileName = `${basename}${i}${ext}${isZipped}`;
11282
+ fs.rename(tmppath, path.join(this.dirname, fileName), cb);
11283
+ });
11284
+ }.bind(this, x));
11285
+ }
11286
+ asyncSeries(tasks, () => {
11287
+ fs.rename(path.join(this.dirname, `${basename}${ext}${isZipped}`), path.join(this.dirname, `${basename}1${ext}${isZipped}`), callback);
11288
+ });
11289
+ }
11290
+ _compressFile(src, dest, callback) {
11291
+ fs.access(src, fs.F_OK, (err) => {
11292
+ if (err) {
11293
+ return callback();
11294
+ }
11295
+ var gzip = zlib.createGzip();
11296
+ var inp = fs.createReadStream(src);
11297
+ var out = fs.createWriteStream(dest);
11298
+ out.on("finish", () => {
11299
+ fs.unlink(src, callback);
11300
+ });
11301
+ inp.pipe(gzip).pipe(out);
11302
+ });
11303
+ }
11304
+ _createLogDirIfNotExist(dirPath) {
11305
+ if (!fs.existsSync(dirPath)) {
11306
+ fs.mkdirSync(dirPath, { recursive: true });
11307
+ }
11308
+ }
11309
+ };
11310
+ });
11311
+
11312
+ // ../../node_modules/winston/lib/winston/transports/http.js
11313
+ var require_http = __commonJS((exports, module) => {
11314
+ var http = __require("http");
11315
+ var https = __require("https");
11316
+ var { Stream } = require_readable();
11317
+ var TransportStream = require_winston_transport();
11318
+ var { configure } = require_safe_stable_stringify();
11319
+ module.exports = class Http extends TransportStream {
11320
+ constructor(options = {}) {
11321
+ super(options);
11322
+ this.options = options;
11323
+ this.name = options.name || "http";
11324
+ this.ssl = !!options.ssl;
11325
+ this.host = options.host || "localhost";
11326
+ this.port = options.port;
11327
+ this.auth = options.auth;
11328
+ this.path = options.path || "";
11329
+ this.maximumDepth = options.maximumDepth;
11330
+ this.agent = options.agent;
11331
+ this.headers = options.headers || {};
11332
+ this.headers["content-type"] = "application/json";
11333
+ this.batch = options.batch || false;
11334
+ this.batchInterval = options.batchInterval || 5000;
11335
+ this.batchCount = options.batchCount || 10;
11336
+ this.batchOptions = [];
11337
+ this.batchTimeoutID = -1;
11338
+ this.batchCallback = {};
11339
+ if (!this.port) {
11340
+ this.port = this.ssl ? 443 : 80;
11341
+ }
11342
+ }
11343
+ log(info, callback) {
11344
+ this._request(info, null, null, (err, res) => {
11345
+ if (res && res.statusCode !== 200) {
11346
+ err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);
11347
+ }
11348
+ if (err) {
11349
+ this.emit("warn", err);
11350
+ } else {
11351
+ this.emit("logged", info);
11352
+ }
11353
+ });
11354
+ if (callback) {
11355
+ setImmediate(callback);
11356
+ }
11357
+ }
11358
+ query(options, callback) {
11359
+ if (typeof options === "function") {
11360
+ callback = options;
11361
+ options = {};
11362
+ }
11363
+ options = {
11364
+ method: "query",
11365
+ params: this.normalizeQuery(options)
11366
+ };
11367
+ const auth = options.params.auth || null;
11368
+ delete options.params.auth;
11369
+ const path = options.params.path || null;
11370
+ delete options.params.path;
11371
+ this._request(options, auth, path, (err, res, body) => {
11372
+ if (res && res.statusCode !== 200) {
11373
+ err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);
11374
+ }
11375
+ if (err) {
11376
+ return callback(err);
11377
+ }
11378
+ if (typeof body === "string") {
11379
+ try {
11380
+ body = JSON.parse(body);
11381
+ } catch (e) {
11382
+ return callback(e);
11383
+ }
11384
+ }
11385
+ callback(null, body);
11386
+ });
11387
+ }
11388
+ stream(options = {}) {
11389
+ const stream = new Stream;
11390
+ options = {
11391
+ method: "stream",
11392
+ params: options
11393
+ };
11394
+ const path = options.params.path || null;
11395
+ delete options.params.path;
11396
+ const auth = options.params.auth || null;
11397
+ delete options.params.auth;
11398
+ let buff = "";
11399
+ const req = this._request(options, auth, path);
11400
+ stream.destroy = () => req.destroy();
11401
+ req.on("data", (data) => {
11402
+ data = (buff + data).split(/\n+/);
11403
+ const l = data.length - 1;
11404
+ let i = 0;
11405
+ for (;i < l; i++) {
11406
+ try {
11407
+ stream.emit("log", JSON.parse(data[i]));
11408
+ } catch (e) {
11409
+ stream.emit("error", e);
11410
+ }
11411
+ }
11412
+ buff = data[l];
11413
+ });
11414
+ req.on("error", (err) => stream.emit("error", err));
11415
+ return stream;
11416
+ }
11417
+ _request(options, auth, path, callback) {
11418
+ options = options || {};
11419
+ auth = auth || this.auth;
11420
+ path = path || this.path || "";
11421
+ if (this.batch) {
11422
+ this._doBatch(options, callback, auth, path);
11423
+ } else {
11424
+ this._doRequest(options, callback, auth, path);
11425
+ }
11426
+ }
11427
+ _doBatch(options, callback, auth, path) {
11428
+ this.batchOptions.push(options);
11429
+ if (this.batchOptions.length === 1) {
11430
+ const me = this;
11431
+ this.batchCallback = callback;
11432
+ this.batchTimeoutID = setTimeout(function() {
11433
+ me.batchTimeoutID = -1;
11434
+ me._doBatchRequest(me.batchCallback, auth, path);
11435
+ }, this.batchInterval);
11436
+ }
11437
+ if (this.batchOptions.length === this.batchCount) {
11438
+ this._doBatchRequest(this.batchCallback, auth, path);
11439
+ }
11440
+ }
11441
+ _doBatchRequest(callback, auth, path) {
11442
+ if (this.batchTimeoutID > 0) {
11443
+ clearTimeout(this.batchTimeoutID);
11444
+ this.batchTimeoutID = -1;
11445
+ }
11446
+ const batchOptionsCopy = this.batchOptions.slice();
11447
+ this.batchOptions = [];
11448
+ this._doRequest(batchOptionsCopy, callback, auth, path);
11449
+ }
11450
+ _doRequest(options, callback, auth, path) {
11451
+ const headers = Object.assign({}, this.headers);
11452
+ if (auth && auth.bearer) {
11453
+ headers.Authorization = `Bearer ${auth.bearer}`;
11454
+ }
11455
+ const req = (this.ssl ? https : http).request({
11456
+ ...this.options,
11457
+ method: "POST",
11458
+ host: this.host,
11459
+ port: this.port,
11460
+ path: `/${path.replace(/^\//, "")}`,
11461
+ headers,
11462
+ auth: auth && auth.username && auth.password ? `${auth.username}:${auth.password}` : "",
11463
+ agent: this.agent
11464
+ });
11465
+ req.on("error", callback);
11466
+ req.on("response", (res) => res.on("end", () => callback(null, res)).resume());
11467
+ const jsonStringify = configure({
11468
+ ...this.maximumDepth && { maximumDepth: this.maximumDepth }
11469
+ });
11470
+ req.end(Buffer.from(jsonStringify(options, this.options.replacer), "utf8"));
11471
+ }
11472
+ };
11473
+ });
11474
+
11475
+ // ../../node_modules/is-stream/index.js
11476
+ var require_is_stream = __commonJS((exports, module) => {
11477
+ var isStream = (stream) => stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
11478
+ isStream.writable = (stream) => isStream(stream) && stream.writable !== false && typeof stream._write === "function" && typeof stream._writableState === "object";
11479
+ isStream.readable = (stream) => isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
11480
+ isStream.duplex = (stream) => isStream.writable(stream) && isStream.readable(stream);
11481
+ isStream.transform = (stream) => isStream.duplex(stream) && typeof stream._transform === "function";
11482
+ module.exports = isStream;
11483
+ });
11484
+
11485
+ // ../../node_modules/winston/lib/winston/transports/stream.js
11486
+ var require_stream = __commonJS((exports, module) => {
11487
+ var isStream = require_is_stream();
11488
+ var { MESSAGE } = require_triple_beam();
11489
+ var os2 = __require("os");
11490
+ var TransportStream = require_winston_transport();
11491
+ module.exports = class Stream extends TransportStream {
11492
+ constructor(options = {}) {
11493
+ super(options);
11494
+ if (!options.stream || !isStream(options.stream)) {
11495
+ throw new Error("options.stream is required.");
11496
+ }
11497
+ this._stream = options.stream;
11498
+ this._stream.setMaxListeners(Infinity);
11499
+ this.isObjectMode = options.stream._writableState.objectMode;
11500
+ this.eol = typeof options.eol === "string" ? options.eol : os2.EOL;
11726
11501
  }
11727
- _checkMaxFilesTailable(ext, basename, callback) {
11728
- const tasks = [];
11729
- if (!this.maxFiles) {
11502
+ log(info, callback) {
11503
+ setImmediate(() => this.emit("logged", info));
11504
+ if (this.isObjectMode) {
11505
+ this._stream.write(info);
11506
+ if (callback) {
11507
+ callback();
11508
+ }
11730
11509
  return;
11731
11510
  }
11732
- const isZipped = this.zippedArchive ? ".gz" : "";
11733
- for (let x = this.maxFiles - 1;x > 1; x--) {
11734
- tasks.push(function(i, cb) {
11735
- let fileName = `${basename}${i - 1}${ext}${isZipped}`;
11736
- const tmppath = path.join(this.dirname, fileName);
11737
- fs.exists(tmppath, (exists) => {
11738
- if (!exists) {
11739
- return cb(null);
11740
- }
11741
- fileName = `${basename}${i}${ext}${isZipped}`;
11742
- fs.rename(tmppath, path.join(this.dirname, fileName), cb);
11743
- });
11744
- }.bind(this, x));
11511
+ this._stream.write(`${info[MESSAGE]}${this.eol}`);
11512
+ if (callback) {
11513
+ callback();
11745
11514
  }
11746
- asyncSeries(tasks, () => {
11747
- fs.rename(path.join(this.dirname, `${basename}${ext}${isZipped}`), path.join(this.dirname, `${basename}1${ext}${isZipped}`), callback);
11748
- });
11515
+ return;
11749
11516
  }
11750
- _compressFile(src, dest, callback) {
11751
- fs.access(src, fs.F_OK, (err) => {
11752
- if (err) {
11753
- return callback();
11754
- }
11755
- var gzip = zlib.createGzip();
11756
- var inp = fs.createReadStream(src);
11757
- var out = fs.createWriteStream(dest);
11758
- out.on("finish", () => {
11759
- fs.unlink(src, callback);
11760
- });
11761
- inp.pipe(gzip).pipe(out);
11762
- });
11517
+ };
11518
+ });
11519
+
11520
+ // ../../node_modules/winston/lib/winston/transports/index.js
11521
+ var require_transports = __commonJS((exports) => {
11522
+ Object.defineProperty(exports, "Console", {
11523
+ configurable: true,
11524
+ enumerable: true,
11525
+ get() {
11526
+ return require_console();
11763
11527
  }
11764
- _createLogDirIfNotExist(dirPath) {
11765
- if (!fs.existsSync(dirPath)) {
11766
- fs.mkdirSync(dirPath, { recursive: true });
11528
+ });
11529
+ Object.defineProperty(exports, "File", {
11530
+ configurable: true,
11531
+ enumerable: true,
11532
+ get() {
11533
+ return require_file();
11534
+ }
11535
+ });
11536
+ Object.defineProperty(exports, "Http", {
11537
+ configurable: true,
11538
+ enumerable: true,
11539
+ get() {
11540
+ return require_http();
11541
+ }
11542
+ });
11543
+ Object.defineProperty(exports, "Stream", {
11544
+ configurable: true,
11545
+ enumerable: true,
11546
+ get() {
11547
+ return require_stream();
11548
+ }
11549
+ });
11550
+ });
11551
+
11552
+ // ../../node_modules/winston/lib/winston/config/index.js
11553
+ var require_config2 = __commonJS((exports) => {
11554
+ var logform = require_logform();
11555
+ var { configs } = require_triple_beam();
11556
+ exports.cli = logform.levels(configs.cli);
11557
+ exports.npm = logform.levels(configs.npm);
11558
+ exports.syslog = logform.levels(configs.syslog);
11559
+ exports.addColors = logform.levels;
11560
+ });
11561
+
11562
+ // ../../node_modules/async/eachOf.js
11563
+ var require_eachOf = __commonJS((exports, module) => {
11564
+ Object.defineProperty(exports, "__esModule", {
11565
+ value: true
11566
+ });
11567
+ var _isArrayLike = require_isArrayLike();
11568
+ var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
11569
+ var _breakLoop = require_breakLoop();
11570
+ var _breakLoop2 = _interopRequireDefault(_breakLoop);
11571
+ var _eachOfLimit = require_eachOfLimit2();
11572
+ var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
11573
+ var _once = require_once();
11574
+ var _once2 = _interopRequireDefault(_once);
11575
+ var _onlyOnce = require_onlyOnce();
11576
+ var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
11577
+ var _wrapAsync = require_wrapAsync();
11578
+ var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
11579
+ var _awaitify = require_awaitify();
11580
+ var _awaitify2 = _interopRequireDefault(_awaitify);
11581
+ function _interopRequireDefault(obj) {
11582
+ return obj && obj.__esModule ? obj : { default: obj };
11583
+ }
11584
+ function eachOfArrayLike(coll, iteratee, callback) {
11585
+ callback = (0, _once2.default)(callback);
11586
+ var index = 0, completed = 0, { length } = coll, canceled = false;
11587
+ if (length === 0) {
11588
+ callback(null);
11589
+ }
11590
+ function iteratorCallback(err, value) {
11591
+ if (err === false) {
11592
+ canceled = true;
11593
+ }
11594
+ if (canceled === true)
11595
+ return;
11596
+ if (err) {
11597
+ callback(err);
11598
+ } else if (++completed === length || value === _breakLoop2.default) {
11599
+ callback(null);
11767
11600
  }
11768
11601
  }
11602
+ for (;index < length; index++) {
11603
+ iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback));
11604
+ }
11605
+ }
11606
+ function eachOfGeneric(coll, iteratee, callback) {
11607
+ return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback);
11608
+ }
11609
+ function eachOf(coll, iteratee, callback) {
11610
+ var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric;
11611
+ return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback);
11612
+ }
11613
+ exports.default = (0, _awaitify2.default)(eachOf, 3);
11614
+ module.exports = exports.default;
11615
+ });
11616
+
11617
+ // ../../node_modules/async/internal/withoutIndex.js
11618
+ var require_withoutIndex = __commonJS((exports, module) => {
11619
+ Object.defineProperty(exports, "__esModule", {
11620
+ value: true
11621
+ });
11622
+ exports.default = _withoutIndex;
11623
+ function _withoutIndex(iteratee) {
11624
+ return (value, index, callback) => iteratee(value, callback);
11625
+ }
11626
+ module.exports = exports.default;
11627
+ });
11628
+
11629
+ // ../../node_modules/async/forEach.js
11630
+ var require_forEach = __commonJS((exports, module) => {
11631
+ Object.defineProperty(exports, "__esModule", {
11632
+ value: true
11633
+ });
11634
+ var _eachOf = require_eachOf();
11635
+ var _eachOf2 = _interopRequireDefault(_eachOf);
11636
+ var _withoutIndex = require_withoutIndex();
11637
+ var _withoutIndex2 = _interopRequireDefault(_withoutIndex);
11638
+ var _wrapAsync = require_wrapAsync();
11639
+ var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
11640
+ var _awaitify = require_awaitify();
11641
+ var _awaitify2 = _interopRequireDefault(_awaitify);
11642
+ function _interopRequireDefault(obj) {
11643
+ return obj && obj.__esModule ? obj : { default: obj };
11644
+ }
11645
+ function eachLimit(coll, iteratee, callback) {
11646
+ return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback);
11647
+ }
11648
+ exports.default = (0, _awaitify2.default)(eachLimit, 3);
11649
+ module.exports = exports.default;
11650
+ });
11651
+
11652
+ // ../../node_modules/fn.name/index.js
11653
+ var require_fn = __commonJS((exports, module) => {
11654
+ var toString = Object.prototype.toString;
11655
+ module.exports = function name(fn) {
11656
+ if (typeof fn.displayName === "string" && fn.constructor.name) {
11657
+ return fn.displayName;
11658
+ } else if (typeof fn.name === "string" && fn.name) {
11659
+ return fn.name;
11660
+ }
11661
+ if (typeof fn === "object" && fn.constructor && typeof fn.constructor.name === "string")
11662
+ return fn.constructor.name;
11663
+ var named = fn.toString(), type = toString.call(fn).slice(8, -1);
11664
+ if (type === "Function") {
11665
+ named = named.substring(named.indexOf("(") + 1, named.indexOf(")"));
11666
+ } else {
11667
+ named = type;
11668
+ }
11669
+ return named || "anonymous";
11769
11670
  };
11770
11671
  });
11771
11672
 
11772
- // ../../node_modules/winston/lib/winston/transports/http.js
11773
- var require_http = __commonJS((exports, module) => {
11774
- var http = __require("http");
11775
- var https = __require("https");
11776
- var { Stream } = require_readable();
11777
- var TransportStream = require_winston_transport();
11778
- var { configure } = require_safe_stable_stringify();
11779
- module.exports = class Http extends TransportStream {
11780
- constructor(options = {}) {
11781
- super(options);
11782
- this.options = options;
11783
- this.name = options.name || "http";
11784
- this.ssl = !!options.ssl;
11785
- this.host = options.host || "localhost";
11786
- this.port = options.port;
11787
- this.auth = options.auth;
11788
- this.path = options.path || "";
11789
- this.maximumDepth = options.maximumDepth;
11790
- this.agent = options.agent;
11791
- this.headers = options.headers || {};
11792
- this.headers["content-type"] = "application/json";
11793
- this.batch = options.batch || false;
11794
- this.batchInterval = options.batchInterval || 5000;
11795
- this.batchCount = options.batchCount || 10;
11796
- this.batchOptions = [];
11797
- this.batchTimeoutID = -1;
11798
- this.batchCallback = {};
11799
- if (!this.port) {
11800
- this.port = this.ssl ? 443 : 80;
11801
- }
11673
+ // ../../node_modules/one-time/index.js
11674
+ var require_one_time = __commonJS((exports, module) => {
11675
+ var name = require_fn();
11676
+ module.exports = function one(fn) {
11677
+ var called = 0, value;
11678
+ function onetime() {
11679
+ if (called)
11680
+ return value;
11681
+ called = 1;
11682
+ value = fn.apply(this, arguments);
11683
+ fn = null;
11684
+ return value;
11685
+ }
11686
+ onetime.displayName = name(fn);
11687
+ return onetime;
11688
+ };
11689
+ });
11690
+
11691
+ // ../../node_modules/stack-trace/lib/stack-trace.js
11692
+ var require_stack_trace = __commonJS((exports) => {
11693
+ exports.get = function(belowFn) {
11694
+ var oldLimit = Error.stackTraceLimit;
11695
+ Error.stackTraceLimit = Infinity;
11696
+ var dummyObject = {};
11697
+ var v8Handler = Error.prepareStackTrace;
11698
+ Error.prepareStackTrace = function(dummyObject2, v8StackTrace2) {
11699
+ return v8StackTrace2;
11700
+ };
11701
+ Error.captureStackTrace(dummyObject, belowFn || exports.get);
11702
+ var v8StackTrace = dummyObject.stack;
11703
+ Error.prepareStackTrace = v8Handler;
11704
+ Error.stackTraceLimit = oldLimit;
11705
+ return v8StackTrace;
11706
+ };
11707
+ exports.parse = function(err) {
11708
+ if (!err.stack) {
11709
+ return [];
11802
11710
  }
11803
- log(info, callback) {
11804
- this._request(info, null, null, (err, res) => {
11805
- if (res && res.statusCode !== 200) {
11806
- err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);
11807
- }
11808
- if (err) {
11809
- this.emit("warn", err);
11810
- } else {
11811
- this.emit("logged", info);
11812
- }
11813
- });
11814
- if (callback) {
11815
- setImmediate(callback);
11711
+ var self2 = this;
11712
+ var lines = err.stack.split(`
11713
+ `).slice(1);
11714
+ return lines.map(function(line) {
11715
+ if (line.match(/^\s*[-]{4,}$/)) {
11716
+ return self2._createParsedCallSite({
11717
+ fileName: line,
11718
+ lineNumber: null,
11719
+ functionName: null,
11720
+ typeName: null,
11721
+ methodName: null,
11722
+ columnNumber: null,
11723
+ native: null
11724
+ });
11816
11725
  }
11817
- }
11818
- query(options, callback) {
11819
- if (typeof options === "function") {
11820
- callback = options;
11821
- options = {};
11726
+ var lineMatch = line.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/);
11727
+ if (!lineMatch) {
11728
+ return;
11822
11729
  }
11823
- options = {
11824
- method: "query",
11825
- params: this.normalizeQuery(options)
11826
- };
11827
- const auth = options.params.auth || null;
11828
- delete options.params.auth;
11829
- const path = options.params.path || null;
11830
- delete options.params.path;
11831
- this._request(options, auth, path, (err, res, body) => {
11832
- if (res && res.statusCode !== 200) {
11833
- err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);
11834
- }
11835
- if (err) {
11836
- return callback(err);
11837
- }
11838
- if (typeof body === "string") {
11839
- try {
11840
- body = JSON.parse(body);
11841
- } catch (e) {
11842
- return callback(e);
11843
- }
11844
- }
11845
- callback(null, body);
11846
- });
11847
- }
11848
- stream(options = {}) {
11849
- const stream = new Stream;
11850
- options = {
11851
- method: "stream",
11852
- params: options
11853
- };
11854
- const path = options.params.path || null;
11855
- delete options.params.path;
11856
- const auth = options.params.auth || null;
11857
- delete options.params.auth;
11858
- let buff = "";
11859
- const req = this._request(options, auth, path);
11860
- stream.destroy = () => req.destroy();
11861
- req.on("data", (data) => {
11862
- data = (buff + data).split(/\n+/);
11863
- const l = data.length - 1;
11864
- let i = 0;
11865
- for (;i < l; i++) {
11866
- try {
11867
- stream.emit("log", JSON.parse(data[i]));
11868
- } catch (e) {
11869
- stream.emit("error", e);
11730
+ var object = null;
11731
+ var method = null;
11732
+ var functionName = null;
11733
+ var typeName = null;
11734
+ var methodName = null;
11735
+ var isNative = lineMatch[5] === "native";
11736
+ if (lineMatch[1]) {
11737
+ functionName = lineMatch[1];
11738
+ var methodStart = functionName.lastIndexOf(".");
11739
+ if (functionName[methodStart - 1] == ".")
11740
+ methodStart--;
11741
+ if (methodStart > 0) {
11742
+ object = functionName.substr(0, methodStart);
11743
+ method = functionName.substr(methodStart + 1);
11744
+ var objectEnd = object.indexOf(".Module");
11745
+ if (objectEnd > 0) {
11746
+ functionName = functionName.substr(objectEnd + 1);
11747
+ object = object.substr(0, objectEnd);
11870
11748
  }
11871
11749
  }
11872
- buff = data[l];
11873
- });
11874
- req.on("error", (err) => stream.emit("error", err));
11875
- return stream;
11876
- }
11877
- _request(options, auth, path, callback) {
11878
- options = options || {};
11879
- auth = auth || this.auth;
11880
- path = path || this.path || "";
11881
- if (this.batch) {
11882
- this._doBatch(options, callback, auth, path);
11883
- } else {
11884
- this._doRequest(options, callback, auth, path);
11750
+ typeName = null;
11885
11751
  }
11886
- }
11887
- _doBatch(options, callback, auth, path) {
11888
- this.batchOptions.push(options);
11889
- if (this.batchOptions.length === 1) {
11890
- const me = this;
11891
- this.batchCallback = callback;
11892
- this.batchTimeoutID = setTimeout(function() {
11893
- me.batchTimeoutID = -1;
11894
- me._doBatchRequest(me.batchCallback, auth, path);
11895
- }, this.batchInterval);
11752
+ if (method) {
11753
+ typeName = object;
11754
+ methodName = method;
11896
11755
  }
11897
- if (this.batchOptions.length === this.batchCount) {
11898
- this._doBatchRequest(this.batchCallback, auth, path);
11756
+ if (method === "<anonymous>") {
11757
+ methodName = null;
11758
+ functionName = null;
11899
11759
  }
11760
+ var properties = {
11761
+ fileName: lineMatch[2] || null,
11762
+ lineNumber: parseInt(lineMatch[3], 10) || null,
11763
+ functionName,
11764
+ typeName,
11765
+ methodName,
11766
+ columnNumber: parseInt(lineMatch[4], 10) || null,
11767
+ native: isNative
11768
+ };
11769
+ return self2._createParsedCallSite(properties);
11770
+ }).filter(function(callSite) {
11771
+ return !!callSite;
11772
+ });
11773
+ };
11774
+ function CallSite(properties) {
11775
+ for (var property in properties) {
11776
+ this[property] = properties[property];
11900
11777
  }
11901
- _doBatchRequest(callback, auth, path) {
11902
- if (this.batchTimeoutID > 0) {
11903
- clearTimeout(this.batchTimeoutID);
11904
- this.batchTimeoutID = -1;
11778
+ }
11779
+ var strProperties = [
11780
+ "this",
11781
+ "typeName",
11782
+ "functionName",
11783
+ "methodName",
11784
+ "fileName",
11785
+ "lineNumber",
11786
+ "columnNumber",
11787
+ "function",
11788
+ "evalOrigin"
11789
+ ];
11790
+ var boolProperties = [
11791
+ "topLevel",
11792
+ "eval",
11793
+ "native",
11794
+ "constructor"
11795
+ ];
11796
+ strProperties.forEach(function(property) {
11797
+ CallSite.prototype[property] = null;
11798
+ CallSite.prototype["get" + property[0].toUpperCase() + property.substr(1)] = function() {
11799
+ return this[property];
11800
+ };
11801
+ });
11802
+ boolProperties.forEach(function(property) {
11803
+ CallSite.prototype[property] = false;
11804
+ CallSite.prototype["is" + property[0].toUpperCase() + property.substr(1)] = function() {
11805
+ return this[property];
11806
+ };
11807
+ });
11808
+ exports._createParsedCallSite = function(properties) {
11809
+ return new CallSite(properties);
11810
+ };
11811
+ });
11812
+
11813
+ // ../../node_modules/winston/lib/winston/exception-stream.js
11814
+ var require_exception_stream = __commonJS((exports, module) => {
11815
+ var { Writable } = require_readable();
11816
+ module.exports = class ExceptionStream extends Writable {
11817
+ constructor(transport) {
11818
+ super({ objectMode: true });
11819
+ if (!transport) {
11820
+ throw new Error("ExceptionStream requires a TransportStream instance.");
11905
11821
  }
11906
- const batchOptionsCopy = this.batchOptions.slice();
11907
- this.batchOptions = [];
11908
- this._doRequest(batchOptionsCopy, callback, auth, path);
11822
+ this.handleExceptions = true;
11823
+ this.transport = transport;
11909
11824
  }
11910
- _doRequest(options, callback, auth, path) {
11911
- const headers = Object.assign({}, this.headers);
11912
- if (auth && auth.bearer) {
11913
- headers.Authorization = `Bearer ${auth.bearer}`;
11825
+ _write(info, enc, callback) {
11826
+ if (info.exception) {
11827
+ return this.transport.log(info, callback);
11914
11828
  }
11915
- const req = (this.ssl ? https : http).request({
11916
- ...this.options,
11917
- method: "POST",
11918
- host: this.host,
11919
- port: this.port,
11920
- path: `/${path.replace(/^\//, "")}`,
11921
- headers,
11922
- auth: auth && auth.username && auth.password ? `${auth.username}:${auth.password}` : "",
11923
- agent: this.agent
11924
- });
11925
- req.on("error", callback);
11926
- req.on("response", (res) => res.on("end", () => callback(null, res)).resume());
11927
- const jsonStringify = configure({
11928
- ...this.maximumDepth && { maximumDepth: this.maximumDepth }
11929
- });
11930
- req.end(Buffer.from(jsonStringify(options, this.options.replacer), "utf8"));
11829
+ callback();
11830
+ return true;
11931
11831
  }
11932
11832
  };
11933
11833
  });
11934
11834
 
11935
- // ../../node_modules/is-stream/index.js
11936
- var require_is_stream = __commonJS((exports, module) => {
11937
- var isStream = (stream) => stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
11938
- isStream.writable = (stream) => isStream(stream) && stream.writable !== false && typeof stream._write === "function" && typeof stream._writableState === "object";
11939
- isStream.readable = (stream) => isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
11940
- isStream.duplex = (stream) => isStream.writable(stream) && isStream.readable(stream);
11941
- isStream.transform = (stream) => isStream.duplex(stream) && typeof stream._transform === "function";
11942
- module.exports = isStream;
11943
- });
11944
-
11945
- // ../../node_modules/winston/lib/winston/transports/stream.js
11946
- var require_stream = __commonJS((exports, module) => {
11947
- var isStream = require_is_stream();
11948
- var { MESSAGE } = require_triple_beam();
11835
+ // ../../node_modules/winston/lib/winston/exception-handler.js
11836
+ var require_exception_handler = __commonJS((exports, module) => {
11949
11837
  var os2 = __require("os");
11950
- var TransportStream = require_winston_transport();
11951
- module.exports = class Stream extends TransportStream {
11952
- constructor(options = {}) {
11953
- super(options);
11954
- if (!options.stream || !isStream(options.stream)) {
11955
- throw new Error("options.stream is required.");
11838
+ var asyncForEach = require_forEach();
11839
+ var debug = require_node3()("winston:exception");
11840
+ var once = require_one_time();
11841
+ var stackTrace = require_stack_trace();
11842
+ var ExceptionStream = require_exception_stream();
11843
+ module.exports = class ExceptionHandler {
11844
+ constructor(logger) {
11845
+ if (!logger) {
11846
+ throw new Error("Logger is required to handle exceptions");
11956
11847
  }
11957
- this._stream = options.stream;
11958
- this._stream.setMaxListeners(Infinity);
11959
- this.isObjectMode = options.stream._writableState.objectMode;
11960
- this.eol = typeof options.eol === "string" ? options.eol : os2.EOL;
11848
+ this.logger = logger;
11849
+ this.handlers = new Map;
11961
11850
  }
11962
- log(info, callback) {
11963
- setImmediate(() => this.emit("logged", info));
11964
- if (this.isObjectMode) {
11965
- this._stream.write(info);
11966
- if (callback) {
11967
- callback();
11851
+ handle(...args) {
11852
+ args.forEach((arg) => {
11853
+ if (Array.isArray(arg)) {
11854
+ return arg.forEach((handler) => this._addHandler(handler));
11968
11855
  }
11969
- return;
11970
- }
11971
- this._stream.write(`${info[MESSAGE]}${this.eol}`);
11972
- if (callback) {
11973
- callback();
11856
+ this._addHandler(arg);
11857
+ });
11858
+ if (!this.catcher) {
11859
+ this.catcher = this._uncaughtException.bind(this);
11860
+ process.on("uncaughtException", this.catcher);
11974
11861
  }
11975
- return;
11976
11862
  }
11977
- };
11978
- });
11979
-
11980
- // ../../node_modules/winston/lib/winston/transports/index.js
11981
- var require_transports = __commonJS((exports) => {
11982
- Object.defineProperty(exports, "Console", {
11983
- configurable: true,
11984
- enumerable: true,
11985
- get() {
11986
- return require_console();
11863
+ unhandle() {
11864
+ if (this.catcher) {
11865
+ process.removeListener("uncaughtException", this.catcher);
11866
+ this.catcher = false;
11867
+ Array.from(this.handlers.values()).forEach((wrapper) => this.logger.unpipe(wrapper));
11868
+ }
11987
11869
  }
11988
- });
11989
- Object.defineProperty(exports, "File", {
11990
- configurable: true,
11991
- enumerable: true,
11992
- get() {
11993
- return require_file();
11870
+ getAllInfo(err) {
11871
+ let message = null;
11872
+ if (err) {
11873
+ message = typeof err === "string" ? err : err.message;
11874
+ }
11875
+ return {
11876
+ error: err,
11877
+ level: "error",
11878
+ message: [
11879
+ `uncaughtException: ${message || "(no error message)"}`,
11880
+ err && err.stack || " No stack trace"
11881
+ ].join(`
11882
+ `),
11883
+ stack: err && err.stack,
11884
+ exception: true,
11885
+ date: new Date().toString(),
11886
+ process: this.getProcessInfo(),
11887
+ os: this.getOsInfo(),
11888
+ trace: this.getTrace(err)
11889
+ };
11994
11890
  }
11995
- });
11996
- Object.defineProperty(exports, "Http", {
11997
- configurable: true,
11998
- enumerable: true,
11999
- get() {
12000
- return require_http();
11891
+ getProcessInfo() {
11892
+ return {
11893
+ pid: process.pid,
11894
+ uid: process.getuid ? process.getuid() : null,
11895
+ gid: process.getgid ? process.getgid() : null,
11896
+ cwd: process.cwd(),
11897
+ execPath: process.execPath,
11898
+ version: process.version,
11899
+ argv: process.argv,
11900
+ memoryUsage: process.memoryUsage()
11901
+ };
12001
11902
  }
12002
- });
12003
- Object.defineProperty(exports, "Stream", {
12004
- configurable: true,
12005
- enumerable: true,
12006
- get() {
12007
- return require_stream();
11903
+ getOsInfo() {
11904
+ return {
11905
+ loadavg: os2.loadavg(),
11906
+ uptime: os2.uptime()
11907
+ };
12008
11908
  }
12009
- });
12010
- });
12011
-
12012
- // ../../node_modules/winston/lib/winston/config/index.js
12013
- var require_config2 = __commonJS((exports) => {
12014
- var logform = require_logform();
12015
- var { configs } = require_triple_beam();
12016
- exports.cli = logform.levels(configs.cli);
12017
- exports.npm = logform.levels(configs.npm);
12018
- exports.syslog = logform.levels(configs.syslog);
12019
- exports.addColors = logform.levels;
12020
- });
12021
-
12022
- // ../../node_modules/async/eachOf.js
12023
- var require_eachOf = __commonJS((exports, module) => {
12024
- Object.defineProperty(exports, "__esModule", {
12025
- value: true
12026
- });
12027
- var _isArrayLike = require_isArrayLike();
12028
- var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
12029
- var _breakLoop = require_breakLoop();
12030
- var _breakLoop2 = _interopRequireDefault(_breakLoop);
12031
- var _eachOfLimit = require_eachOfLimit2();
12032
- var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
12033
- var _once = require_once();
12034
- var _once2 = _interopRequireDefault(_once);
12035
- var _onlyOnce = require_onlyOnce();
12036
- var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
12037
- var _wrapAsync = require_wrapAsync();
12038
- var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
12039
- var _awaitify = require_awaitify();
12040
- var _awaitify2 = _interopRequireDefault(_awaitify);
12041
- function _interopRequireDefault(obj) {
12042
- return obj && obj.__esModule ? obj : { default: obj };
12043
- }
12044
- function eachOfArrayLike(coll, iteratee, callback) {
12045
- callback = (0, _once2.default)(callback);
12046
- var index = 0, completed = 0, { length } = coll, canceled = false;
12047
- if (length === 0) {
12048
- callback(null);
11909
+ getTrace(err) {
11910
+ const trace = err ? stackTrace.parse(err) : stackTrace.get();
11911
+ return trace.map((site) => {
11912
+ return {
11913
+ column: site.getColumnNumber(),
11914
+ file: site.getFileName(),
11915
+ function: site.getFunctionName(),
11916
+ line: site.getLineNumber(),
11917
+ method: site.getMethodName(),
11918
+ native: site.isNative()
11919
+ };
11920
+ });
12049
11921
  }
12050
- function iteratorCallback(err, value) {
12051
- if (err === false) {
12052
- canceled = true;
12053
- }
12054
- if (canceled === true)
12055
- return;
12056
- if (err) {
12057
- callback(err);
12058
- } else if (++completed === length || value === _breakLoop2.default) {
12059
- callback(null);
11922
+ _addHandler(handler) {
11923
+ if (!this.handlers.has(handler)) {
11924
+ handler.handleExceptions = true;
11925
+ const wrapper = new ExceptionStream(handler);
11926
+ this.handlers.set(handler, wrapper);
11927
+ this.logger.pipe(wrapper);
12060
11928
  }
12061
11929
  }
12062
- for (;index < length; index++) {
12063
- iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback));
12064
- }
12065
- }
12066
- function eachOfGeneric(coll, iteratee, callback) {
12067
- return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback);
12068
- }
12069
- function eachOf(coll, iteratee, callback) {
12070
- var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric;
12071
- return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback);
12072
- }
12073
- exports.default = (0, _awaitify2.default)(eachOf, 3);
12074
- module.exports = exports.default;
12075
- });
12076
-
12077
- // ../../node_modules/async/internal/withoutIndex.js
12078
- var require_withoutIndex = __commonJS((exports, module) => {
12079
- Object.defineProperty(exports, "__esModule", {
12080
- value: true
12081
- });
12082
- exports.default = _withoutIndex;
12083
- function _withoutIndex(iteratee) {
12084
- return (value, index, callback) => iteratee(value, callback);
12085
- }
12086
- module.exports = exports.default;
12087
- });
12088
-
12089
- // ../../node_modules/async/forEach.js
12090
- var require_forEach = __commonJS((exports, module) => {
12091
- Object.defineProperty(exports, "__esModule", {
12092
- value: true
12093
- });
12094
- var _eachOf = require_eachOf();
12095
- var _eachOf2 = _interopRequireDefault(_eachOf);
12096
- var _withoutIndex = require_withoutIndex();
12097
- var _withoutIndex2 = _interopRequireDefault(_withoutIndex);
12098
- var _wrapAsync = require_wrapAsync();
12099
- var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
12100
- var _awaitify = require_awaitify();
12101
- var _awaitify2 = _interopRequireDefault(_awaitify);
12102
- function _interopRequireDefault(obj) {
12103
- return obj && obj.__esModule ? obj : { default: obj };
12104
- }
12105
- function eachLimit(coll, iteratee, callback) {
12106
- return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback);
12107
- }
12108
- exports.default = (0, _awaitify2.default)(eachLimit, 3);
12109
- module.exports = exports.default;
12110
- });
12111
-
12112
- // ../../node_modules/fn.name/index.js
12113
- var require_fn = __commonJS((exports, module) => {
12114
- var toString = Object.prototype.toString;
12115
- module.exports = function name(fn) {
12116
- if (typeof fn.displayName === "string" && fn.constructor.name) {
12117
- return fn.displayName;
12118
- } else if (typeof fn.name === "string" && fn.name) {
12119
- return fn.name;
11930
+ _uncaughtException(err) {
11931
+ const info = this.getAllInfo(err);
11932
+ const handlers = this._getExceptionHandlers();
11933
+ let doExit = typeof this.logger.exitOnError === "function" ? this.logger.exitOnError(err) : this.logger.exitOnError;
11934
+ let timeout;
11935
+ if (!handlers.length && doExit) {
11936
+ console.warn("winston: exitOnError cannot be true with no exception handlers.");
11937
+ console.warn("winston: not exiting process.");
11938
+ doExit = false;
11939
+ }
11940
+ function gracefulExit() {
11941
+ debug("doExit", doExit);
11942
+ debug("process._exiting", process._exiting);
11943
+ if (doExit && !process._exiting) {
11944
+ if (timeout) {
11945
+ clearTimeout(timeout);
11946
+ }
11947
+ process.exit(1);
11948
+ }
11949
+ }
11950
+ if (!handlers || handlers.length === 0) {
11951
+ return process.nextTick(gracefulExit);
11952
+ }
11953
+ asyncForEach(handlers, (handler, next) => {
11954
+ const done = once(next);
11955
+ const transport = handler.transport || handler;
11956
+ function onDone(event) {
11957
+ return () => {
11958
+ debug(event);
11959
+ done();
11960
+ };
11961
+ }
11962
+ transport._ending = true;
11963
+ transport.once("finish", onDone("finished"));
11964
+ transport.once("error", onDone("error"));
11965
+ }, () => doExit && gracefulExit());
11966
+ this.logger.log(info);
11967
+ if (doExit) {
11968
+ timeout = setTimeout(gracefulExit, 3000);
11969
+ }
12120
11970
  }
12121
- if (typeof fn === "object" && fn.constructor && typeof fn.constructor.name === "string")
12122
- return fn.constructor.name;
12123
- var named = fn.toString(), type = toString.call(fn).slice(8, -1);
12124
- if (type === "Function") {
12125
- named = named.substring(named.indexOf("(") + 1, named.indexOf(")"));
12126
- } else {
12127
- named = type;
11971
+ _getExceptionHandlers() {
11972
+ return this.logger.transports.filter((wrap) => {
11973
+ const transport = wrap.transport || wrap;
11974
+ return transport.handleExceptions;
11975
+ });
12128
11976
  }
12129
- return named || "anonymous";
12130
11977
  };
12131
11978
  });
12132
11979
 
12133
- // ../../node_modules/one-time/index.js
12134
- var require_one_time = __commonJS((exports, module) => {
12135
- var name = require_fn();
12136
- module.exports = function one(fn) {
12137
- var called = 0, value;
12138
- function onetime() {
12139
- if (called)
12140
- return value;
12141
- called = 1;
12142
- value = fn.apply(this, arguments);
12143
- fn = null;
12144
- return value;
11980
+ // ../../node_modules/winston/lib/winston/rejection-stream.js
11981
+ var require_rejection_stream = __commonJS((exports, module) => {
11982
+ var { Writable } = require_readable();
11983
+ module.exports = class RejectionStream extends Writable {
11984
+ constructor(transport) {
11985
+ super({ objectMode: true });
11986
+ if (!transport) {
11987
+ throw new Error("RejectionStream requires a TransportStream instance.");
11988
+ }
11989
+ this.handleRejections = true;
11990
+ this.transport = transport;
11991
+ }
11992
+ _write(info, enc, callback) {
11993
+ if (info.rejection) {
11994
+ return this.transport.log(info, callback);
11995
+ }
11996
+ callback();
11997
+ return true;
12145
11998
  }
12146
- onetime.displayName = name(fn);
12147
- return onetime;
12148
11999
  };
12149
12000
  });
12150
12001
 
12151
- // ../../node_modules/stack-trace/lib/stack-trace.js
12152
- var require_stack_trace = __commonJS((exports) => {
12153
- exports.get = function(belowFn) {
12154
- var oldLimit = Error.stackTraceLimit;
12155
- Error.stackTraceLimit = Infinity;
12156
- var dummyObject = {};
12157
- var v8Handler = Error.prepareStackTrace;
12158
- Error.prepareStackTrace = function(dummyObject2, v8StackTrace2) {
12159
- return v8StackTrace2;
12160
- };
12161
- Error.captureStackTrace(dummyObject, belowFn || exports.get);
12162
- var v8StackTrace = dummyObject.stack;
12163
- Error.prepareStackTrace = v8Handler;
12164
- Error.stackTraceLimit = oldLimit;
12165
- return v8StackTrace;
12166
- };
12167
- exports.parse = function(err) {
12168
- if (!err.stack) {
12169
- return [];
12002
+ // ../../node_modules/winston/lib/winston/rejection-handler.js
12003
+ var require_rejection_handler = __commonJS((exports, module) => {
12004
+ var os2 = __require("os");
12005
+ var asyncForEach = require_forEach();
12006
+ var debug = require_node3()("winston:rejection");
12007
+ var once = require_one_time();
12008
+ var stackTrace = require_stack_trace();
12009
+ var RejectionStream = require_rejection_stream();
12010
+ module.exports = class RejectionHandler {
12011
+ constructor(logger) {
12012
+ if (!logger) {
12013
+ throw new Error("Logger is required to handle rejections");
12014
+ }
12015
+ this.logger = logger;
12016
+ this.handlers = new Map;
12170
12017
  }
12171
- var self2 = this;
12172
- var lines = err.stack.split(`
12173
- `).slice(1);
12174
- return lines.map(function(line) {
12175
- if (line.match(/^\s*[-]{4,}$/)) {
12176
- return self2._createParsedCallSite({
12177
- fileName: line,
12178
- lineNumber: null,
12179
- functionName: null,
12180
- typeName: null,
12181
- methodName: null,
12182
- columnNumber: null,
12183
- native: null
12184
- });
12018
+ handle(...args) {
12019
+ args.forEach((arg) => {
12020
+ if (Array.isArray(arg)) {
12021
+ return arg.forEach((handler) => this._addHandler(handler));
12022
+ }
12023
+ this._addHandler(arg);
12024
+ });
12025
+ if (!this.catcher) {
12026
+ this.catcher = this._unhandledRejection.bind(this);
12027
+ process.on("unhandledRejection", this.catcher);
12185
12028
  }
12186
- var lineMatch = line.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/);
12187
- if (!lineMatch) {
12188
- return;
12029
+ }
12030
+ unhandle() {
12031
+ if (this.catcher) {
12032
+ process.removeListener("unhandledRejection", this.catcher);
12033
+ this.catcher = false;
12034
+ Array.from(this.handlers.values()).forEach((wrapper) => this.logger.unpipe(wrapper));
12189
12035
  }
12190
- var object = null;
12191
- var method = null;
12192
- var functionName = null;
12193
- var typeName = null;
12194
- var methodName = null;
12195
- var isNative = lineMatch[5] === "native";
12196
- if (lineMatch[1]) {
12197
- functionName = lineMatch[1];
12198
- var methodStart = functionName.lastIndexOf(".");
12199
- if (functionName[methodStart - 1] == ".")
12200
- methodStart--;
12201
- if (methodStart > 0) {
12202
- object = functionName.substr(0, methodStart);
12203
- method = functionName.substr(methodStart + 1);
12204
- var objectEnd = object.indexOf(".Module");
12205
- if (objectEnd > 0) {
12206
- functionName = functionName.substr(objectEnd + 1);
12207
- object = object.substr(0, objectEnd);
12036
+ }
12037
+ getAllInfo(err) {
12038
+ let message = null;
12039
+ if (err) {
12040
+ message = typeof err === "string" ? err : err.message;
12041
+ }
12042
+ return {
12043
+ error: err,
12044
+ level: "error",
12045
+ message: [
12046
+ `unhandledRejection: ${message || "(no error message)"}`,
12047
+ err && err.stack || " No stack trace"
12048
+ ].join(`
12049
+ `),
12050
+ stack: err && err.stack,
12051
+ rejection: true,
12052
+ date: new Date().toString(),
12053
+ process: this.getProcessInfo(),
12054
+ os: this.getOsInfo(),
12055
+ trace: this.getTrace(err)
12056
+ };
12057
+ }
12058
+ getProcessInfo() {
12059
+ return {
12060
+ pid: process.pid,
12061
+ uid: process.getuid ? process.getuid() : null,
12062
+ gid: process.getgid ? process.getgid() : null,
12063
+ cwd: process.cwd(),
12064
+ execPath: process.execPath,
12065
+ version: process.version,
12066
+ argv: process.argv,
12067
+ memoryUsage: process.memoryUsage()
12068
+ };
12069
+ }
12070
+ getOsInfo() {
12071
+ return {
12072
+ loadavg: os2.loadavg(),
12073
+ uptime: os2.uptime()
12074
+ };
12075
+ }
12076
+ getTrace(err) {
12077
+ const trace = err ? stackTrace.parse(err) : stackTrace.get();
12078
+ return trace.map((site) => {
12079
+ return {
12080
+ column: site.getColumnNumber(),
12081
+ file: site.getFileName(),
12082
+ function: site.getFunctionName(),
12083
+ line: site.getLineNumber(),
12084
+ method: site.getMethodName(),
12085
+ native: site.isNative()
12086
+ };
12087
+ });
12088
+ }
12089
+ _addHandler(handler) {
12090
+ if (!this.handlers.has(handler)) {
12091
+ handler.handleRejections = true;
12092
+ const wrapper = new RejectionStream(handler);
12093
+ this.handlers.set(handler, wrapper);
12094
+ this.logger.pipe(wrapper);
12095
+ }
12096
+ }
12097
+ _unhandledRejection(err) {
12098
+ const info = this.getAllInfo(err);
12099
+ const handlers = this._getRejectionHandlers();
12100
+ let doExit = typeof this.logger.exitOnError === "function" ? this.logger.exitOnError(err) : this.logger.exitOnError;
12101
+ let timeout;
12102
+ if (!handlers.length && doExit) {
12103
+ console.warn("winston: exitOnError cannot be true with no rejection handlers.");
12104
+ console.warn("winston: not exiting process.");
12105
+ doExit = false;
12106
+ }
12107
+ function gracefulExit() {
12108
+ debug("doExit", doExit);
12109
+ debug("process._exiting", process._exiting);
12110
+ if (doExit && !process._exiting) {
12111
+ if (timeout) {
12112
+ clearTimeout(timeout);
12208
12113
  }
12114
+ process.exit(1);
12209
12115
  }
12210
- typeName = null;
12211
12116
  }
12212
- if (method) {
12213
- typeName = object;
12214
- methodName = method;
12117
+ if (!handlers || handlers.length === 0) {
12118
+ return process.nextTick(gracefulExit);
12215
12119
  }
12216
- if (method === "<anonymous>") {
12217
- methodName = null;
12218
- functionName = null;
12120
+ asyncForEach(handlers, (handler, next) => {
12121
+ const done = once(next);
12122
+ const transport = handler.transport || handler;
12123
+ function onDone(event) {
12124
+ return () => {
12125
+ debug(event);
12126
+ done();
12127
+ };
12128
+ }
12129
+ transport._ending = true;
12130
+ transport.once("finish", onDone("finished"));
12131
+ transport.once("error", onDone("error"));
12132
+ }, () => doExit && gracefulExit());
12133
+ this.logger.log(info);
12134
+ if (doExit) {
12135
+ timeout = setTimeout(gracefulExit, 3000);
12219
12136
  }
12220
- var properties = {
12221
- fileName: lineMatch[2] || null,
12222
- lineNumber: parseInt(lineMatch[3], 10) || null,
12223
- functionName,
12224
- typeName,
12225
- methodName,
12226
- columnNumber: parseInt(lineMatch[4], 10) || null,
12227
- native: isNative
12228
- };
12229
- return self2._createParsedCallSite(properties);
12230
- }).filter(function(callSite) {
12231
- return !!callSite;
12232
- });
12233
- };
12234
- function CallSite(properties) {
12235
- for (var property in properties) {
12236
- this[property] = properties[property];
12237
12137
  }
12238
- }
12239
- var strProperties = [
12240
- "this",
12241
- "typeName",
12242
- "functionName",
12243
- "methodName",
12244
- "fileName",
12245
- "lineNumber",
12246
- "columnNumber",
12247
- "function",
12248
- "evalOrigin"
12249
- ];
12250
- var boolProperties = [
12251
- "topLevel",
12252
- "eval",
12253
- "native",
12254
- "constructor"
12255
- ];
12256
- strProperties.forEach(function(property) {
12257
- CallSite.prototype[property] = null;
12258
- CallSite.prototype["get" + property[0].toUpperCase() + property.substr(1)] = function() {
12259
- return this[property];
12260
- };
12261
- });
12262
- boolProperties.forEach(function(property) {
12263
- CallSite.prototype[property] = false;
12264
- CallSite.prototype["is" + property[0].toUpperCase() + property.substr(1)] = function() {
12265
- return this[property];
12266
- };
12267
- });
12268
- exports._createParsedCallSite = function(properties) {
12269
- return new CallSite(properties);
12138
+ _getRejectionHandlers() {
12139
+ return this.logger.transports.filter((wrap) => {
12140
+ const transport = wrap.transport || wrap;
12141
+ return transport.handleRejections;
12142
+ });
12143
+ }
12270
12144
  };
12271
12145
  });
12272
12146
 
12273
- // ../../node_modules/winston/lib/winston/exception-stream.js
12274
- var require_exception_stream = __commonJS((exports, module) => {
12275
- var { Writable } = require_readable();
12276
- module.exports = class ExceptionStream extends Writable {
12277
- constructor(transport) {
12278
- super({ objectMode: true });
12279
- if (!transport) {
12280
- throw new Error("ExceptionStream requires a TransportStream instance.");
12147
+ // ../../node_modules/winston/lib/winston/profiler.js
12148
+ var require_profiler = __commonJS((exports, module) => {
12149
+ class Profiler {
12150
+ constructor(logger) {
12151
+ const Logger = require_logger();
12152
+ if (typeof logger !== "object" || Array.isArray(logger) || !(logger instanceof Logger)) {
12153
+ throw new Error("Logger is required for profiling");
12154
+ } else {
12155
+ this.logger = logger;
12156
+ this.start = Date.now();
12281
12157
  }
12282
- this.handleExceptions = true;
12283
- this.transport = transport;
12284
12158
  }
12285
- _write(info, enc, callback) {
12286
- if (info.exception) {
12287
- return this.transport.log(info, callback);
12159
+ done(...args) {
12160
+ if (typeof args[args.length - 1] === "function") {
12161
+ console.warn("Callback function no longer supported as of winston@3.0.0");
12162
+ args.pop();
12288
12163
  }
12289
- callback();
12290
- return true;
12164
+ const info = typeof args[args.length - 1] === "object" ? args.pop() : {};
12165
+ info.level = info.level || "info";
12166
+ info.durationMs = Date.now() - this.start;
12167
+ return this.logger.write(info);
12291
12168
  }
12292
- };
12169
+ }
12170
+ module.exports = Profiler;
12293
12171
  });
12294
12172
 
12295
- // ../../node_modules/winston/lib/winston/exception-handler.js
12296
- var require_exception_handler = __commonJS((exports, module) => {
12297
- var os2 = __require("os");
12173
+ // ../../node_modules/winston/lib/winston/logger.js
12174
+ var require_logger = __commonJS((exports, module) => {
12175
+ var { Stream, Transform } = require_readable();
12298
12176
  var asyncForEach = require_forEach();
12299
- var debug = require_node3()("winston:exception");
12300
- var once = require_one_time();
12301
- var stackTrace = require_stack_trace();
12302
- var ExceptionStream = require_exception_stream();
12303
- module.exports = class ExceptionHandler {
12304
- constructor(logger) {
12305
- if (!logger) {
12306
- throw new Error("Logger is required to handle exceptions");
12177
+ var { LEVEL, SPLAT } = require_triple_beam();
12178
+ var isStream = require_is_stream();
12179
+ var ExceptionHandler = require_exception_handler();
12180
+ var RejectionHandler = require_rejection_handler();
12181
+ var LegacyTransportStream = require_legacy();
12182
+ var Profiler = require_profiler();
12183
+ var { warn } = require_common();
12184
+ var config = require_config2();
12185
+ var formatRegExp = /%[scdjifoO%]/g;
12186
+
12187
+ class Logger extends Transform {
12188
+ constructor(options) {
12189
+ super({ objectMode: true });
12190
+ this.configure(options);
12191
+ }
12192
+ child(defaultRequestMetadata) {
12193
+ const logger = this;
12194
+ return Object.create(logger, {
12195
+ write: {
12196
+ value: function(info) {
12197
+ const infoClone = Object.assign({}, defaultRequestMetadata, info);
12198
+ if (info instanceof Error) {
12199
+ infoClone.stack = info.stack;
12200
+ infoClone.message = info.message;
12201
+ }
12202
+ logger.write(infoClone);
12203
+ }
12204
+ }
12205
+ });
12206
+ }
12207
+ configure({
12208
+ silent,
12209
+ format,
12210
+ defaultMeta,
12211
+ levels,
12212
+ level = "info",
12213
+ exitOnError = true,
12214
+ transports,
12215
+ colors,
12216
+ emitErrs,
12217
+ formatters,
12218
+ padLevels,
12219
+ rewriters,
12220
+ stripColors,
12221
+ exceptionHandlers,
12222
+ rejectionHandlers
12223
+ } = {}) {
12224
+ if (this.transports.length) {
12225
+ this.clear();
12226
+ }
12227
+ this.silent = silent;
12228
+ this.format = format || this.format || require_json()();
12229
+ this.defaultMeta = defaultMeta || null;
12230
+ this.levels = levels || this.levels || config.npm.levels;
12231
+ this.level = level;
12232
+ if (this.exceptions) {
12233
+ this.exceptions.unhandle();
12234
+ }
12235
+ if (this.rejections) {
12236
+ this.rejections.unhandle();
12237
+ }
12238
+ this.exceptions = new ExceptionHandler(this);
12239
+ this.rejections = new RejectionHandler(this);
12240
+ this.profilers = {};
12241
+ this.exitOnError = exitOnError;
12242
+ if (transports) {
12243
+ transports = Array.isArray(transports) ? transports : [transports];
12244
+ transports.forEach((transport) => this.add(transport));
12245
+ }
12246
+ if (colors || emitErrs || formatters || padLevels || rewriters || stripColors) {
12247
+ throw new Error([
12248
+ "{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.",
12249
+ "Use a custom winston.format(function) instead.",
12250
+ "See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"
12251
+ ].join(`
12252
+ `));
12253
+ }
12254
+ if (exceptionHandlers) {
12255
+ this.exceptions.handle(exceptionHandlers);
12256
+ }
12257
+ if (rejectionHandlers) {
12258
+ this.rejections.handle(rejectionHandlers);
12307
12259
  }
12308
- this.logger = logger;
12309
- this.handlers = new Map;
12310
12260
  }
12311
- handle(...args) {
12312
- args.forEach((arg) => {
12313
- if (Array.isArray(arg)) {
12314
- return arg.forEach((handler) => this._addHandler(handler));
12261
+ isLevelEnabled(level) {
12262
+ const givenLevelValue = getLevelValue(this.levels, level);
12263
+ if (givenLevelValue === null) {
12264
+ return false;
12265
+ }
12266
+ const configuredLevelValue = getLevelValue(this.levels, this.level);
12267
+ if (configuredLevelValue === null) {
12268
+ return false;
12269
+ }
12270
+ if (!this.transports || this.transports.length === 0) {
12271
+ return configuredLevelValue >= givenLevelValue;
12272
+ }
12273
+ const index = this.transports.findIndex((transport) => {
12274
+ let transportLevelValue = getLevelValue(this.levels, transport.level);
12275
+ if (transportLevelValue === null) {
12276
+ transportLevelValue = configuredLevelValue;
12277
+ }
12278
+ return transportLevelValue >= givenLevelValue;
12279
+ });
12280
+ return index !== -1;
12281
+ }
12282
+ log(level, msg, ...splat) {
12283
+ if (arguments.length === 1) {
12284
+ level[LEVEL] = level.level;
12285
+ this._addDefaultMeta(level);
12286
+ this.write(level);
12287
+ return this;
12288
+ }
12289
+ if (arguments.length === 2) {
12290
+ if (msg && typeof msg === "object") {
12291
+ msg[LEVEL] = msg.level = level;
12292
+ this._addDefaultMeta(msg);
12293
+ this.write(msg);
12294
+ return this;
12295
+ }
12296
+ msg = { [LEVEL]: level, level, message: msg };
12297
+ this._addDefaultMeta(msg);
12298
+ this.write(msg);
12299
+ return this;
12300
+ }
12301
+ const [meta] = splat;
12302
+ if (typeof meta === "object" && meta !== null) {
12303
+ const tokens = msg && msg.match && msg.match(formatRegExp);
12304
+ if (!tokens) {
12305
+ const info = Object.assign({}, this.defaultMeta, meta, {
12306
+ [LEVEL]: level,
12307
+ [SPLAT]: splat,
12308
+ level,
12309
+ message: msg
12310
+ });
12311
+ if (meta.message)
12312
+ info.message = `${info.message} ${meta.message}`;
12313
+ if (meta.stack)
12314
+ info.stack = meta.stack;
12315
+ if (meta.cause)
12316
+ info.cause = meta.cause;
12317
+ this.write(info);
12318
+ return this;
12315
12319
  }
12316
- this._addHandler(arg);
12317
- });
12318
- if (!this.catcher) {
12319
- this.catcher = this._uncaughtException.bind(this);
12320
- process.on("uncaughtException", this.catcher);
12321
12320
  }
12321
+ this.write(Object.assign({}, this.defaultMeta, {
12322
+ [LEVEL]: level,
12323
+ [SPLAT]: splat,
12324
+ level,
12325
+ message: msg
12326
+ }));
12327
+ return this;
12322
12328
  }
12323
- unhandle() {
12324
- if (this.catcher) {
12325
- process.removeListener("uncaughtException", this.catcher);
12326
- this.catcher = false;
12327
- Array.from(this.handlers.values()).forEach((wrapper) => this.logger.unpipe(wrapper));
12329
+ _transform(info, enc, callback) {
12330
+ if (this.silent) {
12331
+ return callback();
12332
+ }
12333
+ if (!info[LEVEL]) {
12334
+ info[LEVEL] = info.level;
12335
+ }
12336
+ if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) {
12337
+ console.error("[winston] Unknown logger level: %s", info[LEVEL]);
12338
+ }
12339
+ if (!this._readableState.pipes) {
12340
+ console.error("[winston] Attempt to write logs with no transports, which can increase memory usage: %j", info);
12341
+ }
12342
+ try {
12343
+ this.push(this.format.transform(info, this.format.options));
12344
+ } finally {
12345
+ this._writableState.sync = false;
12346
+ callback();
12328
12347
  }
12329
12348
  }
12330
- getAllInfo(err) {
12331
- let message = null;
12332
- if (err) {
12333
- message = typeof err === "string" ? err : err.message;
12349
+ _final(callback) {
12350
+ const transports = this.transports.slice();
12351
+ asyncForEach(transports, (transport, next) => {
12352
+ if (!transport || transport.finished)
12353
+ return setImmediate(next);
12354
+ transport.once("finish", next);
12355
+ transport.end();
12356
+ }, callback);
12357
+ }
12358
+ add(transport) {
12359
+ const target = !isStream(transport) || transport.log.length > 2 ? new LegacyTransportStream({ transport }) : transport;
12360
+ if (!target._writableState || !target._writableState.objectMode) {
12361
+ throw new Error("Transports must WritableStreams in objectMode. Set { objectMode: true }.");
12334
12362
  }
12335
- return {
12336
- error: err,
12337
- level: "error",
12338
- message: [
12339
- `uncaughtException: ${message || "(no error message)"}`,
12340
- err && err.stack || " No stack trace"
12341
- ].join(`
12342
- `),
12343
- stack: err && err.stack,
12344
- exception: true,
12345
- date: new Date().toString(),
12346
- process: this.getProcessInfo(),
12347
- os: this.getOsInfo(),
12348
- trace: this.getTrace(err)
12349
- };
12363
+ this._onEvent("error", target);
12364
+ this._onEvent("warn", target);
12365
+ this.pipe(target);
12366
+ if (transport.handleExceptions) {
12367
+ this.exceptions.handle();
12368
+ }
12369
+ if (transport.handleRejections) {
12370
+ this.rejections.handle();
12371
+ }
12372
+ return this;
12350
12373
  }
12351
- getProcessInfo() {
12352
- return {
12353
- pid: process.pid,
12354
- uid: process.getuid ? process.getuid() : null,
12355
- gid: process.getgid ? process.getgid() : null,
12356
- cwd: process.cwd(),
12357
- execPath: process.execPath,
12358
- version: process.version,
12359
- argv: process.argv,
12360
- memoryUsage: process.memoryUsage()
12361
- };
12374
+ remove(transport) {
12375
+ if (!transport)
12376
+ return this;
12377
+ let target = transport;
12378
+ if (!isStream(transport) || transport.log.length > 2) {
12379
+ target = this.transports.filter((match) => match.transport === transport)[0];
12380
+ }
12381
+ if (target) {
12382
+ this.unpipe(target);
12383
+ }
12384
+ return this;
12362
12385
  }
12363
- getOsInfo() {
12364
- return {
12365
- loadavg: os2.loadavg(),
12366
- uptime: os2.uptime()
12367
- };
12386
+ clear() {
12387
+ this.unpipe();
12388
+ return this;
12368
12389
  }
12369
- getTrace(err) {
12370
- const trace = err ? stackTrace.parse(err) : stackTrace.get();
12371
- return trace.map((site) => {
12372
- return {
12373
- column: site.getColumnNumber(),
12374
- file: site.getFileName(),
12375
- function: site.getFunctionName(),
12376
- line: site.getLineNumber(),
12377
- method: site.getMethodName(),
12378
- native: site.isNative()
12379
- };
12380
- });
12390
+ close() {
12391
+ this.exceptions.unhandle();
12392
+ this.rejections.unhandle();
12393
+ this.clear();
12394
+ this.emit("close");
12395
+ return this;
12381
12396
  }
12382
- _addHandler(handler) {
12383
- if (!this.handlers.has(handler)) {
12384
- handler.handleExceptions = true;
12385
- const wrapper = new ExceptionStream(handler);
12386
- this.handlers.set(handler, wrapper);
12387
- this.logger.pipe(wrapper);
12388
- }
12397
+ setLevels() {
12398
+ warn.deprecated("setLevels");
12389
12399
  }
12390
- _uncaughtException(err) {
12391
- const info = this.getAllInfo(err);
12392
- const handlers = this._getExceptionHandlers();
12393
- let doExit = typeof this.logger.exitOnError === "function" ? this.logger.exitOnError(err) : this.logger.exitOnError;
12394
- let timeout;
12395
- if (!handlers.length && doExit) {
12396
- console.warn("winston: exitOnError cannot be true with no exception handlers.");
12397
- console.warn("winston: not exiting process.");
12398
- doExit = false;
12400
+ query(options, callback) {
12401
+ if (typeof options === "function") {
12402
+ callback = options;
12403
+ options = {};
12399
12404
  }
12400
- function gracefulExit() {
12401
- debug("doExit", doExit);
12402
- debug("process._exiting", process._exiting);
12403
- if (doExit && !process._exiting) {
12404
- if (timeout) {
12405
- clearTimeout(timeout);
12406
- }
12407
- process.exit(1);
12405
+ options = options || {};
12406
+ const results = {};
12407
+ const queryObject = Object.assign({}, options.query || {});
12408
+ function queryTransport(transport, next) {
12409
+ if (options.query && typeof transport.formatQuery === "function") {
12410
+ options.query = transport.formatQuery(queryObject);
12408
12411
  }
12412
+ transport.query(options, (err, res) => {
12413
+ if (err) {
12414
+ return next(err);
12415
+ }
12416
+ if (typeof transport.formatResults === "function") {
12417
+ res = transport.formatResults(res, options.format);
12418
+ }
12419
+ next(null, res);
12420
+ });
12409
12421
  }
12410
- if (!handlers || handlers.length === 0) {
12411
- return process.nextTick(gracefulExit);
12412
- }
12413
- asyncForEach(handlers, (handler, next) => {
12414
- const done = once(next);
12415
- const transport = handler.transport || handler;
12416
- function onDone(event) {
12417
- return () => {
12418
- debug(event);
12419
- done();
12420
- };
12421
- }
12422
- transport._ending = true;
12423
- transport.once("finish", onDone("finished"));
12424
- transport.once("error", onDone("error"));
12425
- }, () => doExit && gracefulExit());
12426
- this.logger.log(info);
12427
- if (doExit) {
12428
- timeout = setTimeout(gracefulExit, 3000);
12422
+ function addResults(transport, next) {
12423
+ queryTransport(transport, (err, result) => {
12424
+ if (next) {
12425
+ result = err || result;
12426
+ if (result) {
12427
+ results[transport.name] = result;
12428
+ }
12429
+ next();
12430
+ }
12431
+ next = null;
12432
+ });
12429
12433
  }
12434
+ asyncForEach(this.transports.filter((transport) => !!transport.query), addResults, () => callback(null, results));
12430
12435
  }
12431
- _getExceptionHandlers() {
12432
- return this.logger.transports.filter((wrap) => {
12433
- const transport = wrap.transport || wrap;
12434
- return transport.handleExceptions;
12436
+ stream(options = {}) {
12437
+ const out = new Stream;
12438
+ const streams = [];
12439
+ out._streams = streams;
12440
+ out.destroy = () => {
12441
+ let i = streams.length;
12442
+ while (i--) {
12443
+ streams[i].destroy();
12444
+ }
12445
+ };
12446
+ this.transports.filter((transport) => !!transport.stream).forEach((transport) => {
12447
+ const str = transport.stream(options);
12448
+ if (!str) {
12449
+ return;
12450
+ }
12451
+ streams.push(str);
12452
+ str.on("log", (log) => {
12453
+ log.transport = log.transport || [];
12454
+ log.transport.push(transport.name);
12455
+ out.emit("log", log);
12456
+ });
12457
+ str.on("error", (err) => {
12458
+ err.transport = err.transport || [];
12459
+ err.transport.push(transport.name);
12460
+ out.emit("error", err);
12461
+ });
12435
12462
  });
12463
+ return out;
12436
12464
  }
12437
- };
12438
- });
12439
-
12440
- // ../../node_modules/winston/lib/winston/rejection-stream.js
12441
- var require_rejection_stream = __commonJS((exports, module) => {
12442
- var { Writable } = require_readable();
12443
- module.exports = class RejectionStream extends Writable {
12444
- constructor(transport) {
12445
- super({ objectMode: true });
12446
- if (!transport) {
12447
- throw new Error("RejectionStream requires a TransportStream instance.");
12465
+ startTimer() {
12466
+ return new Profiler(this);
12467
+ }
12468
+ profile(id, ...args) {
12469
+ const time = Date.now();
12470
+ if (this.profilers[id]) {
12471
+ const timeEnd = this.profilers[id];
12472
+ delete this.profilers[id];
12473
+ if (typeof args[args.length - 2] === "function") {
12474
+ console.warn("Callback function no longer supported as of winston@3.0.0");
12475
+ args.pop();
12476
+ }
12477
+ const info = typeof args[args.length - 1] === "object" ? args.pop() : {};
12478
+ info.level = info.level || "info";
12479
+ info.durationMs = time - timeEnd;
12480
+ info.message = info.message || id;
12481
+ return this.write(info);
12448
12482
  }
12449
- this.handleRejections = true;
12450
- this.transport = transport;
12483
+ this.profilers[id] = time;
12484
+ return this;
12451
12485
  }
12452
- _write(info, enc, callback) {
12453
- if (info.rejection) {
12454
- return this.transport.log(info, callback);
12455
- }
12456
- callback();
12457
- return true;
12486
+ handleExceptions(...args) {
12487
+ console.warn("Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()");
12488
+ this.exceptions.handle(...args);
12458
12489
  }
12459
- };
12460
- });
12461
-
12462
- // ../../node_modules/winston/lib/winston/rejection-handler.js
12463
- var require_rejection_handler = __commonJS((exports, module) => {
12464
- var os2 = __require("os");
12465
- var asyncForEach = require_forEach();
12466
- var debug = require_node3()("winston:rejection");
12467
- var once = require_one_time();
12468
- var stackTrace = require_stack_trace();
12469
- var RejectionStream = require_rejection_stream();
12470
- module.exports = class RejectionHandler {
12471
- constructor(logger) {
12472
- if (!logger) {
12473
- throw new Error("Logger is required to handle rejections");
12474
- }
12475
- this.logger = logger;
12476
- this.handlers = new Map;
12490
+ unhandleExceptions(...args) {
12491
+ console.warn("Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()");
12492
+ this.exceptions.unhandle(...args);
12477
12493
  }
12478
- handle(...args) {
12479
- args.forEach((arg) => {
12480
- if (Array.isArray(arg)) {
12481
- return arg.forEach((handler) => this._addHandler(handler));
12494
+ cli() {
12495
+ throw new Error([
12496
+ "Logger.cli() was removed in winston@3.0.0",
12497
+ "Use a custom winston.formats.cli() instead.",
12498
+ "See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"
12499
+ ].join(`
12500
+ `));
12501
+ }
12502
+ _onEvent(event, transport) {
12503
+ function transportEvent(err) {
12504
+ if (event === "error" && !this.transports.includes(transport)) {
12505
+ this.add(transport);
12482
12506
  }
12483
- this._addHandler(arg);
12484
- });
12485
- if (!this.catcher) {
12486
- this.catcher = this._unhandledRejection.bind(this);
12487
- process.on("unhandledRejection", this.catcher);
12507
+ this.emit(event, err, transport);
12488
12508
  }
12489
- }
12490
- unhandle() {
12491
- if (this.catcher) {
12492
- process.removeListener("unhandledRejection", this.catcher);
12493
- this.catcher = false;
12494
- Array.from(this.handlers.values()).forEach((wrapper) => this.logger.unpipe(wrapper));
12509
+ if (!transport["__winston" + event]) {
12510
+ transport["__winston" + event] = transportEvent.bind(this);
12511
+ transport.on(event, transport["__winston" + event]);
12495
12512
  }
12496
12513
  }
12497
- getAllInfo(err) {
12498
- let message = null;
12499
- if (err) {
12500
- message = typeof err === "string" ? err : err.message;
12514
+ _addDefaultMeta(msg) {
12515
+ if (this.defaultMeta) {
12516
+ Object.assign(msg, this.defaultMeta);
12501
12517
  }
12502
- return {
12503
- error: err,
12504
- level: "error",
12505
- message: [
12506
- `unhandledRejection: ${message || "(no error message)"}`,
12507
- err && err.stack || " No stack trace"
12508
- ].join(`
12509
- `),
12510
- stack: err && err.stack,
12511
- rejection: true,
12512
- date: new Date().toString(),
12513
- process: this.getProcessInfo(),
12514
- os: this.getOsInfo(),
12515
- trace: this.getTrace(err)
12516
- };
12517
- }
12518
- getProcessInfo() {
12519
- return {
12520
- pid: process.pid,
12521
- uid: process.getuid ? process.getuid() : null,
12522
- gid: process.getgid ? process.getgid() : null,
12523
- cwd: process.cwd(),
12524
- execPath: process.execPath,
12525
- version: process.version,
12526
- argv: process.argv,
12527
- memoryUsage: process.memoryUsage()
12528
- };
12529
12518
  }
12530
- getOsInfo() {
12531
- return {
12532
- loadavg: os2.loadavg(),
12533
- uptime: os2.uptime()
12534
- };
12519
+ }
12520
+ function getLevelValue(levels, level) {
12521
+ const value = levels[level];
12522
+ if (!value && value !== 0) {
12523
+ return null;
12535
12524
  }
12536
- getTrace(err) {
12537
- const trace = err ? stackTrace.parse(err) : stackTrace.get();
12538
- return trace.map((site) => {
12539
- return {
12540
- column: site.getColumnNumber(),
12541
- file: site.getFileName(),
12542
- function: site.getFunctionName(),
12543
- line: site.getLineNumber(),
12544
- method: site.getMethodName(),
12545
- native: site.isNative()
12546
- };
12547
- });
12525
+ return value;
12526
+ }
12527
+ Object.defineProperty(Logger.prototype, "transports", {
12528
+ configurable: false,
12529
+ enumerable: true,
12530
+ get() {
12531
+ const { pipes } = this._readableState;
12532
+ return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes;
12548
12533
  }
12549
- _addHandler(handler) {
12550
- if (!this.handlers.has(handler)) {
12551
- handler.handleRejections = true;
12552
- const wrapper = new RejectionStream(handler);
12553
- this.handlers.set(handler, wrapper);
12554
- this.logger.pipe(wrapper);
12534
+ });
12535
+ module.exports = Logger;
12536
+ });
12537
+
12538
+ // ../../node_modules/winston/lib/winston/create-logger.js
12539
+ var require_create_logger = __commonJS((exports, module) => {
12540
+ var { LEVEL } = require_triple_beam();
12541
+ var config = require_config2();
12542
+ var Logger = require_logger();
12543
+ var debug = require_node3()("winston:create-logger");
12544
+ function isLevelEnabledFunctionName(level) {
12545
+ return "is" + level.charAt(0).toUpperCase() + level.slice(1) + "Enabled";
12546
+ }
12547
+ module.exports = function(opts = {}) {
12548
+ opts.levels = opts.levels || config.npm.levels;
12549
+
12550
+ class DerivedLogger extends Logger {
12551
+ constructor(options) {
12552
+ super(options);
12555
12553
  }
12556
12554
  }
12557
- _unhandledRejection(err) {
12558
- const info = this.getAllInfo(err);
12559
- const handlers = this._getRejectionHandlers();
12560
- let doExit = typeof this.logger.exitOnError === "function" ? this.logger.exitOnError(err) : this.logger.exitOnError;
12561
- let timeout;
12562
- if (!handlers.length && doExit) {
12563
- console.warn("winston: exitOnError cannot be true with no rejection handlers.");
12564
- console.warn("winston: not exiting process.");
12565
- doExit = false;
12555
+ const logger = new DerivedLogger(opts);
12556
+ Object.keys(opts.levels).forEach(function(level) {
12557
+ debug('Define prototype method for "%s"', level);
12558
+ if (level === "log") {
12559
+ console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.');
12560
+ return;
12566
12561
  }
12567
- function gracefulExit() {
12568
- debug("doExit", doExit);
12569
- debug("process._exiting", process._exiting);
12570
- if (doExit && !process._exiting) {
12571
- if (timeout) {
12572
- clearTimeout(timeout);
12573
- }
12574
- process.exit(1);
12562
+ DerivedLogger.prototype[level] = function(...args) {
12563
+ const self2 = this || logger;
12564
+ if (args.length === 1) {
12565
+ const [msg] = args;
12566
+ const info = msg && msg.message && msg || { message: msg };
12567
+ info.level = info[LEVEL] = level;
12568
+ self2._addDefaultMeta(info);
12569
+ self2.write(info);
12570
+ return this || logger;
12575
12571
  }
12576
- }
12577
- if (!handlers || handlers.length === 0) {
12578
- return process.nextTick(gracefulExit);
12579
- }
12580
- asyncForEach(handlers, (handler, next) => {
12581
- const done = once(next);
12582
- const transport = handler.transport || handler;
12583
- function onDone(event) {
12584
- return () => {
12585
- debug(event);
12586
- done();
12587
- };
12572
+ if (args.length === 0) {
12573
+ self2.log(level, "");
12574
+ return self2;
12588
12575
  }
12589
- transport._ending = true;
12590
- transport.once("finish", onDone("finished"));
12591
- transport.once("error", onDone("error"));
12592
- }, () => doExit && gracefulExit());
12593
- this.logger.log(info);
12594
- if (doExit) {
12595
- timeout = setTimeout(gracefulExit, 3000);
12596
- }
12597
- }
12598
- _getRejectionHandlers() {
12599
- return this.logger.transports.filter((wrap) => {
12600
- const transport = wrap.transport || wrap;
12601
- return transport.handleRejections;
12602
- });
12603
- }
12576
+ return self2.log(level, ...args);
12577
+ };
12578
+ DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function() {
12579
+ return (this || logger).isLevelEnabled(level);
12580
+ };
12581
+ });
12582
+ return logger;
12604
12583
  };
12605
12584
  });
12606
12585
 
12607
- // ../../node_modules/winston/lib/winston/profiler.js
12608
- var require_profiler = __commonJS((exports, module) => {
12609
- class Profiler {
12610
- constructor(logger) {
12611
- const Logger = require_logger();
12612
- if (typeof logger !== "object" || Array.isArray(logger) || !(logger instanceof Logger)) {
12613
- throw new Error("Logger is required for profiling");
12614
- } else {
12615
- this.logger = logger;
12616
- this.start = Date.now();
12586
+ // ../../node_modules/winston/lib/winston/container.js
12587
+ var require_container = __commonJS((exports, module) => {
12588
+ var createLogger = require_create_logger();
12589
+ module.exports = class Container {
12590
+ constructor(options = {}) {
12591
+ this.loggers = new Map;
12592
+ this.options = options;
12593
+ }
12594
+ add(id, options) {
12595
+ if (!this.loggers.has(id)) {
12596
+ options = Object.assign({}, options || this.options);
12597
+ const existing = options.transports || this.options.transports;
12598
+ if (existing) {
12599
+ options.transports = Array.isArray(existing) ? existing.slice() : [existing];
12600
+ } else {
12601
+ options.transports = [];
12602
+ }
12603
+ const logger = createLogger(options);
12604
+ logger.on("close", () => this._delete(id));
12605
+ this.loggers.set(id, logger);
12617
12606
  }
12607
+ return this.loggers.get(id);
12618
12608
  }
12619
- done(...args) {
12620
- if (typeof args[args.length - 1] === "function") {
12621
- console.warn("Callback function no longer supported as of winston@3.0.0");
12622
- args.pop();
12609
+ get(id, options) {
12610
+ return this.add(id, options);
12611
+ }
12612
+ has(id) {
12613
+ return !!this.loggers.has(id);
12614
+ }
12615
+ close(id) {
12616
+ if (id) {
12617
+ return this._removeLogger(id);
12623
12618
  }
12624
- const info = typeof args[args.length - 1] === "object" ? args.pop() : {};
12625
- info.level = info.level || "info";
12626
- info.durationMs = Date.now() - this.start;
12627
- return this.logger.write(info);
12619
+ this.loggers.forEach((val, key) => this._removeLogger(key));
12628
12620
  }
12629
- }
12630
- module.exports = Profiler;
12621
+ _removeLogger(id) {
12622
+ if (!this.loggers.has(id)) {
12623
+ return;
12624
+ }
12625
+ const logger = this.loggers.get(id);
12626
+ logger.close();
12627
+ this._delete(id);
12628
+ }
12629
+ _delete(id) {
12630
+ this.loggers.delete(id);
12631
+ }
12632
+ };
12631
12633
  });
12632
12634
 
12633
- // ../../node_modules/winston/lib/winston/logger.js
12634
- var require_logger = __commonJS((exports, module) => {
12635
- var { Stream, Transform } = require_readable();
12636
- var asyncForEach = require_forEach();
12637
- var { LEVEL, SPLAT } = require_triple_beam();
12638
- var isStream = require_is_stream();
12639
- var ExceptionHandler = require_exception_handler();
12640
- var RejectionHandler = require_rejection_handler();
12641
- var LegacyTransportStream = require_legacy();
12642
- var Profiler = require_profiler();
12635
+ // ../../node_modules/winston/lib/winston.js
12636
+ var require_winston = __commonJS((exports) => {
12637
+ var logform = require_logform();
12643
12638
  var { warn } = require_common();
12644
- var config = require_config2();
12645
- var formatRegExp = /%[scdjifoO%]/g;
12646
-
12647
- class Logger extends Transform {
12648
- constructor(options) {
12649
- super({ objectMode: true });
12650
- this.configure(options);
12639
+ exports.version = require_package().version;
12640
+ exports.transports = require_transports();
12641
+ exports.config = require_config2();
12642
+ exports.addColors = logform.levels;
12643
+ exports.format = logform.format;
12644
+ exports.createLogger = require_create_logger();
12645
+ exports.Logger = require_logger();
12646
+ exports.ExceptionHandler = require_exception_handler();
12647
+ exports.RejectionHandler = require_rejection_handler();
12648
+ exports.Container = require_container();
12649
+ exports.Transport = require_winston_transport();
12650
+ exports.loggers = new exports.Container;
12651
+ var defaultLogger = exports.createLogger();
12652
+ Object.keys(exports.config.npm.levels).concat([
12653
+ "log",
12654
+ "query",
12655
+ "stream",
12656
+ "add",
12657
+ "remove",
12658
+ "clear",
12659
+ "profile",
12660
+ "startTimer",
12661
+ "handleExceptions",
12662
+ "unhandleExceptions",
12663
+ "handleRejections",
12664
+ "unhandleRejections",
12665
+ "configure",
12666
+ "child"
12667
+ ]).forEach((method) => exports[method] = (...args) => defaultLogger[method](...args));
12668
+ Object.defineProperty(exports, "level", {
12669
+ get() {
12670
+ return defaultLogger.level;
12671
+ },
12672
+ set(val) {
12673
+ defaultLogger.level = val;
12651
12674
  }
12652
- child(defaultRequestMetadata) {
12653
- const logger = this;
12654
- return Object.create(logger, {
12655
- write: {
12656
- value: function(info) {
12657
- const infoClone = Object.assign({}, defaultRequestMetadata, info);
12658
- if (info instanceof Error) {
12659
- infoClone.stack = info.stack;
12660
- infoClone.message = info.message;
12661
- }
12662
- logger.write(infoClone);
12663
- }
12664
- }
12665
- });
12675
+ });
12676
+ Object.defineProperty(exports, "exceptions", {
12677
+ get() {
12678
+ return defaultLogger.exceptions;
12666
12679
  }
12667
- configure({
12668
- silent,
12669
- format,
12670
- defaultMeta,
12671
- levels,
12672
- level = "info",
12673
- exitOnError = true,
12674
- transports,
12675
- colors,
12676
- emitErrs,
12677
- formatters,
12678
- padLevels,
12679
- rewriters,
12680
- stripColors,
12681
- exceptionHandlers,
12682
- rejectionHandlers
12683
- } = {}) {
12684
- if (this.transports.length) {
12685
- this.clear();
12686
- }
12687
- this.silent = silent;
12688
- this.format = format || this.format || require_json()();
12689
- this.defaultMeta = defaultMeta || null;
12690
- this.levels = levels || this.levels || config.npm.levels;
12691
- this.level = level;
12692
- if (this.exceptions) {
12693
- this.exceptions.unhandle();
12694
- }
12695
- if (this.rejections) {
12696
- this.rejections.unhandle();
12697
- }
12698
- this.exceptions = new ExceptionHandler(this);
12699
- this.rejections = new RejectionHandler(this);
12700
- this.profilers = {};
12701
- this.exitOnError = exitOnError;
12702
- if (transports) {
12703
- transports = Array.isArray(transports) ? transports : [transports];
12704
- transports.forEach((transport) => this.add(transport));
12705
- }
12706
- if (colors || emitErrs || formatters || padLevels || rewriters || stripColors) {
12707
- throw new Error([
12708
- "{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.",
12709
- "Use a custom winston.format(function) instead.",
12710
- "See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"
12711
- ].join(`
12712
- `));
12713
- }
12714
- if (exceptionHandlers) {
12715
- this.exceptions.handle(exceptionHandlers);
12716
- }
12717
- if (rejectionHandlers) {
12718
- this.rejections.handle(rejectionHandlers);
12719
- }
12680
+ });
12681
+ Object.defineProperty(exports, "rejections", {
12682
+ get() {
12683
+ return defaultLogger.rejections;
12720
12684
  }
12721
- isLevelEnabled(level) {
12722
- const givenLevelValue = getLevelValue(this.levels, level);
12723
- if (givenLevelValue === null) {
12724
- return false;
12725
- }
12726
- const configuredLevelValue = getLevelValue(this.levels, this.level);
12727
- if (configuredLevelValue === null) {
12728
- return false;
12729
- }
12730
- if (!this.transports || this.transports.length === 0) {
12731
- return configuredLevelValue >= givenLevelValue;
12685
+ });
12686
+ ["exitOnError"].forEach((prop) => {
12687
+ Object.defineProperty(exports, prop, {
12688
+ get() {
12689
+ return defaultLogger[prop];
12690
+ },
12691
+ set(val) {
12692
+ defaultLogger[prop] = val;
12732
12693
  }
12733
- const index = this.transports.findIndex((transport) => {
12734
- let transportLevelValue = getLevelValue(this.levels, transport.level);
12735
- if (transportLevelValue === null) {
12736
- transportLevelValue = configuredLevelValue;
12737
- }
12738
- return transportLevelValue >= givenLevelValue;
12739
- });
12740
- return index !== -1;
12694
+ });
12695
+ });
12696
+ Object.defineProperty(exports, "default", {
12697
+ get() {
12698
+ return {
12699
+ exceptionHandlers: defaultLogger.exceptionHandlers,
12700
+ rejectionHandlers: defaultLogger.rejectionHandlers,
12701
+ transports: defaultLogger.transports
12702
+ };
12741
12703
  }
12742
- log(level, msg, ...splat) {
12743
- if (arguments.length === 1) {
12744
- level[LEVEL] = level.level;
12745
- this._addDefaultMeta(level);
12746
- this.write(level);
12747
- return this;
12748
- }
12749
- if (arguments.length === 2) {
12750
- if (msg && typeof msg === "object") {
12751
- msg[LEVEL] = msg.level = level;
12752
- this._addDefaultMeta(msg);
12753
- this.write(msg);
12754
- return this;
12755
- }
12756
- msg = { [LEVEL]: level, level, message: msg };
12757
- this._addDefaultMeta(msg);
12758
- this.write(msg);
12759
- return this;
12704
+ });
12705
+ warn.deprecated(exports, "setLevels");
12706
+ warn.forFunctions(exports, "useFormat", ["cli"]);
12707
+ warn.forProperties(exports, "useFormat", ["padLevels", "stripColors"]);
12708
+ warn.forFunctions(exports, "deprecated", [
12709
+ "addRewriter",
12710
+ "addFilter",
12711
+ "clone",
12712
+ "extend"
12713
+ ]);
12714
+ warn.forProperties(exports, "deprecated", ["emitErrs", "levelLength"]);
12715
+ });
12716
+
12717
+ // src/logger.ts
12718
+ function extractTraceIdFromTraceparent(traceparent) {
12719
+ if (!traceparent) {
12720
+ return;
12721
+ }
12722
+ const parts = traceparent.split("-");
12723
+ const traceId = parts.length >= 2 ? parts[1] : parts.length == 1 ? parts[0] : undefined;
12724
+ if (traceId && traceId.length === 32 && /^[0-9a-fA-F]{32}$/.test(traceId)) {
12725
+ return traceId;
12726
+ }
12727
+ return;
12728
+ }
12729
+ function formatDuration(durationMs) {
12730
+ if (durationMs >= 1000) {
12731
+ const seconds = durationMs / 1000;
12732
+ return `${seconds.toFixed(2)}s`;
12733
+ }
12734
+ return `${durationMs.toFixed(2)}ms`;
12735
+ }
12736
+ function redactSensitive(value, seen = new WeakSet) {
12737
+ if (value === null || typeof value !== "object" || value instanceof Date) {
12738
+ return value;
12739
+ }
12740
+ if (seen.has(value)) {
12741
+ return "[Circular]";
12742
+ }
12743
+ seen.add(value);
12744
+ if (Array.isArray(value)) {
12745
+ return value.map((item) => redactSensitive(item, seen));
12746
+ }
12747
+ const result = {};
12748
+ for (const [key, val] of Object.entries(value)) {
12749
+ result[key] = SENSITIVE_KEYS.has(key.toLowerCase()) ? REDACTED : redactSensitive(val, seen);
12750
+ }
12751
+ return result;
12752
+ }
12753
+ function buildAxiosErrorLog(error) {
12754
+ if (error.response) {
12755
+ return {
12756
+ message: "Axios server-side error",
12757
+ meta: {
12758
+ url: error.response.config.url,
12759
+ status: error.response.status,
12760
+ headers: redactSensitive(error.response.headers),
12761
+ data: redactSensitive(error.response.data)
12760
12762
  }
12761
- const [meta] = splat;
12762
- if (typeof meta === "object" && meta !== null) {
12763
- const tokens = msg && msg.match && msg.match(formatRegExp);
12764
- if (!tokens) {
12765
- const info = Object.assign({}, this.defaultMeta, meta, {
12766
- [LEVEL]: level,
12767
- [SPLAT]: splat,
12768
- level,
12769
- message: msg
12770
- });
12771
- if (meta.message)
12772
- info.message = `${info.message} ${meta.message}`;
12773
- if (meta.stack)
12774
- info.stack = meta.stack;
12775
- if (meta.cause)
12776
- info.cause = meta.cause;
12777
- this.write(info);
12778
- return this;
12779
- }
12763
+ };
12764
+ }
12765
+ if (error.request) {
12766
+ return {
12767
+ message: "Axios client-side error",
12768
+ meta: {
12769
+ method: error.config?.method,
12770
+ url: error.config?.url,
12771
+ code: error.code
12780
12772
  }
12781
- this.write(Object.assign({}, this.defaultMeta, {
12782
- [LEVEL]: level,
12783
- [SPLAT]: splat,
12784
- level,
12785
- message: msg
12786
- }));
12787
- return this;
12773
+ };
12774
+ }
12775
+ return {
12776
+ message: "Axios unknown error",
12777
+ meta: { message: error.message }
12778
+ };
12779
+ }
12780
+ var import_winston, isTelemetryEnabled, VALID_LOG_LEVELS, getLogLevel = () => {
12781
+ if (process.env.LOG_LEVEL) {
12782
+ const logLevel = process.env.LOG_LEVEL.toLowerCase();
12783
+ if (VALID_LOG_LEVELS.includes(logLevel)) {
12784
+ return logLevel;
12785
+ } else {
12786
+ console.error(`Invalid log level: ${process.env.LOG_LEVEL}. Valid log levels are: ${VALID_LOG_LEVELS.join(", ")}. Defaulting to "debug".`);
12788
12787
  }
12789
- _transform(info, enc, callback) {
12790
- if (this.silent) {
12791
- return callback();
12792
- }
12793
- if (!info[LEVEL]) {
12794
- info[LEVEL] = info.level;
12795
- }
12796
- if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) {
12797
- console.error("[winston] Unknown logger level: %s", info[LEVEL]);
12798
- }
12799
- if (!this._readableState.pipes) {
12800
- console.error("[winston] Attempt to write logs with no transports, which can increase memory usage: %j", info);
12801
- }
12802
- try {
12803
- this.push(this.format.transform(info, this.format.options));
12804
- } finally {
12805
- this._writableState.sync = false;
12806
- callback();
12807
- }
12788
+ }
12789
+ return "debug";
12790
+ }, logger, DISABLE_RESPONSE_LOGGING, SENSITIVE_KEY_NAMES, SENSITIVE_KEYS, REDACTED = "[REDACTED]", loggerMiddleware = (req, res, next) => {
12791
+ const startTime = performance.now();
12792
+ const resJson = res.json;
12793
+ res.json = (body) => {
12794
+ res.locals.body = body;
12795
+ return resJson.call(res, body);
12796
+ };
12797
+ res.on("finish", () => {
12798
+ const endTime = performance.now();
12799
+ const durationMs = endTime - startTime;
12800
+ const traceparent = req.headers["traceparent"];
12801
+ const traceId = extractTraceIdFromTraceparent(traceparent);
12802
+ const logMetadata = {
12803
+ statusCode: res.statusCode,
12804
+ duration: formatDuration(durationMs),
12805
+ payload: redactSensitive(req.body),
12806
+ params: req.params,
12807
+ query: req.query
12808
+ };
12809
+ if (!DISABLE_RESPONSE_LOGGING) {
12810
+ logMetadata.response = redactSensitive(res.locals.body);
12808
12811
  }
12809
- _final(callback) {
12810
- const transports = this.transports.slice();
12811
- asyncForEach(transports, (transport, next) => {
12812
- if (!transport || transport.finished)
12813
- return setImmediate(next);
12814
- transport.once("finish", next);
12815
- transport.end();
12816
- }, callback);
12812
+ if (traceId) {
12813
+ logMetadata.traceId = traceId;
12817
12814
  }
12818
- add(transport) {
12819
- const target = !isStream(transport) || transport.log.length > 2 ? new LegacyTransportStream({ transport }) : transport;
12820
- if (!target._writableState || !target._writableState.objectMode) {
12821
- throw new Error("Transports must WritableStreams in objectMode. Set { objectMode: true }.");
12822
- }
12823
- this._onEvent("error", target);
12824
- this._onEvent("warn", target);
12825
- this.pipe(target);
12826
- if (transport.handleExceptions) {
12827
- this.exceptions.handle();
12828
- }
12829
- if (transport.handleRejections) {
12830
- this.rejections.handle();
12831
- }
12832
- return this;
12815
+ if (req.url !== "/metrics" && req.url !== "/health" && req.url !== "/health/liveness" && req.url !== "/health/readiness") {
12816
+ logger.info(`${req.method} ${req.url}`, logMetadata);
12833
12817
  }
12834
- remove(transport) {
12835
- if (!transport)
12836
- return this;
12837
- let target = transport;
12838
- if (!isStream(transport) || transport.log.length > 2) {
12839
- target = this.transports.filter((match) => match.transport === transport)[0];
12840
- }
12841
- if (target) {
12842
- this.unpipe(target);
12843
- }
12844
- return this;
12818
+ });
12819
+ next();
12820
+ }, logAxiosError = (error) => {
12821
+ const { message, meta } = buildAxiosErrorLog(error);
12822
+ logger.error(message, meta);
12823
+ };
12824
+ var init_logger = __esm(() => {
12825
+ import_winston = __toESM(require_winston(), 1);
12826
+ isTelemetryEnabled = Boolean(process.env.OTEL_EXPORTER_OTLP_ENDPOINT);
12827
+ VALID_LOG_LEVELS = ["error", "warn", "info", "verbose", "debug", "silly"];
12828
+ logger = import_winston.default.createLogger({
12829
+ level: getLogLevel(),
12830
+ format: isTelemetryEnabled ? import_winston.default.format.combine(import_winston.default.format.uncolorize(), import_winston.default.format.timestamp(), import_winston.default.format.errors({ stack: true }), import_winston.default.format.json()) : import_winston.default.format.combine(import_winston.default.format.colorize(), import_winston.default.format.simple()),
12831
+ transports: [new import_winston.default.transports.Console]
12832
+ });
12833
+ DISABLE_RESPONSE_LOGGING = process.env.DISABLE_RESPONSE_LOGGING === "true" || process.env.DISABLE_RESPONSE_LOGGING === "1";
12834
+ SENSITIVE_KEY_NAMES = [
12835
+ "password",
12836
+ "connectionString",
12837
+ "serviceAccountKeyJson",
12838
+ "privateKey",
12839
+ "privateKeyPass",
12840
+ "secret",
12841
+ "secretAccessKey",
12842
+ "sessionToken",
12843
+ "sasUrl",
12844
+ "clientSecret",
12845
+ "oauthClientSecret",
12846
+ "peakaKey",
12847
+ "token",
12848
+ "accessToken",
12849
+ "apiKey",
12850
+ "api_key",
12851
+ "authorization",
12852
+ "proxy-authorization",
12853
+ "cookie",
12854
+ "set-cookie",
12855
+ "x-api-key"
12856
+ ];
12857
+ SENSITIVE_KEYS = new Set(SENSITIVE_KEY_NAMES.map((name) => name.toLowerCase()));
12858
+ });
12859
+
12860
+ // src/errors.ts
12861
+ import { MalloyError } from "@malloydata/malloy";
12862
+ function logInternalFailure(summary, error, level = "error") {
12863
+ const strip = (value) => value.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ");
12864
+ const message = error.message ?? "";
12865
+ const stack = error.stack ?? "";
12866
+ const framesOnly = stack.startsWith(`${error.name}: ${message}`) ? stack.slice(`${error.name}: ${message}`.length).replace(/^\r?\n/, "") : stack;
12867
+ logger[level](summary, {
12868
+ error: {
12869
+ name: error.name,
12870
+ message: strip(message).slice(0, MAX_LOGGED_DETAIL_CHARS),
12871
+ stack: strip(framesOnly).slice(0, MAX_LOGGED_DETAIL_CHARS)
12845
12872
  }
12846
- clear() {
12847
- this.unpipe();
12848
- return this;
12873
+ });
12874
+ }
12875
+ function internalErrorToHttpError(error) {
12876
+ if (error instanceof BadRequestError) {
12877
+ return httpError(400, error.message);
12878
+ } else if (error instanceof FrozenConfigError) {
12879
+ return httpError(403, error.message);
12880
+ } else if (error instanceof AccessDeniedError) {
12881
+ return httpError(403, error.message);
12882
+ } else if (error instanceof EnvironmentNotFoundError) {
12883
+ return httpError(404, error.message);
12884
+ } else if (error instanceof PackageNotFoundError) {
12885
+ return httpError(404, error.message);
12886
+ } else if (error instanceof ModelNotFoundError) {
12887
+ return httpError(404, error.message);
12888
+ } else if (error instanceof DashboardNotFoundError) {
12889
+ return httpError(404, error.message);
12890
+ } else if (error instanceof NotQueryableError) {
12891
+ return httpError(404, error.message);
12892
+ } else if (error instanceof MalloyError) {
12893
+ return httpError(400, error.message);
12894
+ } else if (error instanceof TableNotFoundError) {
12895
+ return httpError(404, error.message, "TABLE_NOT_FOUND");
12896
+ } else if (error instanceof ConnectionNotFoundError) {
12897
+ return httpError(404, error.message);
12898
+ } else if (error instanceof DestinationNotFoundError) {
12899
+ return httpError(422, error.message);
12900
+ } else if (error instanceof ConnectionAuthError) {
12901
+ return httpError(422, error.message);
12902
+ } else if (error instanceof UnsupportedCatalogFormatError) {
12903
+ return httpError(422, error.message);
12904
+ } else if (error instanceof MaterializationEligibilityError) {
12905
+ return httpError(422, error.message);
12906
+ } else if (error instanceof ModelCompilationError) {
12907
+ return httpError(424, error.message);
12908
+ } else if (error instanceof ConnectionError) {
12909
+ if (error.callerSafe) {
12910
+ return httpError(502, error.message);
12911
+ }
12912
+ logInternalFailure("Upstream connection error", error, "warn");
12913
+ return httpError(502, GENERIC_UPSTREAM_MESSAGE);
12914
+ } else if (error instanceof MaterializationNotFoundError) {
12915
+ return httpError(404, error.message);
12916
+ } else if (error instanceof MaterializationConflictError) {
12917
+ return httpError(409, error.message);
12918
+ } else if (error instanceof InvalidStateTransitionError) {
12919
+ return httpError(409, error.message);
12920
+ } else if (error instanceof ServiceUnavailableError) {
12921
+ return httpError(503, error.message);
12922
+ } else if (error instanceof PayloadTooLargeError) {
12923
+ return httpError(413, error.message);
12924
+ } else if (error instanceof QueryTimeoutError) {
12925
+ return httpError(504, error.message);
12926
+ } else if (error instanceof NotImplementedError) {
12927
+ return httpError(501, error.message);
12928
+ } else {
12929
+ logInternalFailure("Unhandled internal error", error);
12930
+ return httpError(500, GENERIC_INTERNAL_MESSAGE);
12931
+ }
12932
+ }
12933
+ function httpError(code, message, reason) {
12934
+ return {
12935
+ status: code,
12936
+ json: {
12937
+ code,
12938
+ message,
12939
+ ...reason ? { reason } : {}
12849
12940
  }
12850
- close() {
12851
- this.exceptions.unhandle();
12852
- this.rejections.unhandle();
12853
- this.clear();
12854
- this.emit("close");
12855
- return this;
12941
+ };
12942
+ }
12943
+ var GENERIC_INTERNAL_MESSAGE = "Internal server error.", GENERIC_UPSTREAM_MESSAGE = "Upstream connection error.", MAX_LOGGED_DETAIL_CHARS = 2000, NotImplementedError, BadRequestError, InvalidArgumentError, EnvironmentNotFoundError, PackageNotFoundError, ModelNotFoundError, DashboardNotFoundError, ConnectionNotFoundError, TableNotFoundError, ConnectionError, DestinationNotFoundError, ConnectionAuthError, UnsupportedCatalogFormatError, ModelCompilationError, MaterializationEligibilityError, PublisherConfigError, FrozenConfigError, AccessDeniedError, NotQueryableError, MaterializationNotFoundError, MaterializationConflictError, InvalidStateTransitionError, ServiceUnavailableError, PayloadTooLargeError, ResponseUnserializableError, QueryTimeoutError;
12944
+ var init_errors = __esm(() => {
12945
+ init_constants();
12946
+ init_logger();
12947
+ NotImplementedError = class NotImplementedError extends Error {
12948
+ constructor(message) {
12949
+ super(message);
12856
12950
  }
12857
- setLevels() {
12858
- warn.deprecated("setLevels");
12951
+ };
12952
+ BadRequestError = class BadRequestError extends Error {
12953
+ constructor(message) {
12954
+ super(message);
12859
12955
  }
12860
- query(options, callback) {
12861
- if (typeof options === "function") {
12862
- callback = options;
12863
- options = {};
12864
- }
12865
- options = options || {};
12866
- const results = {};
12867
- const queryObject = Object.assign({}, options.query || {});
12868
- function queryTransport(transport, next) {
12869
- if (options.query && typeof transport.formatQuery === "function") {
12870
- options.query = transport.formatQuery(queryObject);
12871
- }
12872
- transport.query(options, (err, res) => {
12873
- if (err) {
12874
- return next(err);
12875
- }
12876
- if (typeof transport.formatResults === "function") {
12877
- res = transport.formatResults(res, options.format);
12878
- }
12879
- next(null, res);
12880
- });
12881
- }
12882
- function addResults(transport, next) {
12883
- queryTransport(transport, (err, result) => {
12884
- if (next) {
12885
- result = err || result;
12886
- if (result) {
12887
- results[transport.name] = result;
12888
- }
12889
- next();
12890
- }
12891
- next = null;
12892
- });
12893
- }
12894
- asyncForEach(this.transports.filter((transport) => !!transport.query), addResults, () => callback(null, results));
12956
+ };
12957
+ InvalidArgumentError = class InvalidArgumentError extends BadRequestError {
12958
+ };
12959
+ EnvironmentNotFoundError = class EnvironmentNotFoundError extends Error {
12960
+ constructor(message) {
12961
+ super(message);
12895
12962
  }
12896
- stream(options = {}) {
12897
- const out = new Stream;
12898
- const streams = [];
12899
- out._streams = streams;
12900
- out.destroy = () => {
12901
- let i = streams.length;
12902
- while (i--) {
12903
- streams[i].destroy();
12904
- }
12905
- };
12906
- this.transports.filter((transport) => !!transport.stream).forEach((transport) => {
12907
- const str = transport.stream(options);
12908
- if (!str) {
12909
- return;
12910
- }
12911
- streams.push(str);
12912
- str.on("log", (log) => {
12913
- log.transport = log.transport || [];
12914
- log.transport.push(transport.name);
12915
- out.emit("log", log);
12916
- });
12917
- str.on("error", (err) => {
12918
- err.transport = err.transport || [];
12919
- err.transport.push(transport.name);
12920
- out.emit("error", err);
12921
- });
12922
- });
12923
- return out;
12963
+ };
12964
+ PackageNotFoundError = class PackageNotFoundError extends Error {
12965
+ constructor(message) {
12966
+ super(message);
12924
12967
  }
12925
- startTimer() {
12926
- return new Profiler(this);
12968
+ };
12969
+ ModelNotFoundError = class ModelNotFoundError extends Error {
12970
+ constructor(message) {
12971
+ super(message);
12927
12972
  }
12928
- profile(id, ...args) {
12929
- const time = Date.now();
12930
- if (this.profilers[id]) {
12931
- const timeEnd = this.profilers[id];
12932
- delete this.profilers[id];
12933
- if (typeof args[args.length - 2] === "function") {
12934
- console.warn("Callback function no longer supported as of winston@3.0.0");
12935
- args.pop();
12936
- }
12937
- const info = typeof args[args.length - 1] === "object" ? args.pop() : {};
12938
- info.level = info.level || "info";
12939
- info.durationMs = time - timeEnd;
12940
- info.message = info.message || id;
12941
- return this.write(info);
12942
- }
12943
- this.profilers[id] = time;
12944
- return this;
12973
+ };
12974
+ DashboardNotFoundError = class DashboardNotFoundError extends Error {
12975
+ constructor(message) {
12976
+ super(message);
12945
12977
  }
12946
- handleExceptions(...args) {
12947
- console.warn("Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()");
12948
- this.exceptions.handle(...args);
12978
+ };
12979
+ ConnectionNotFoundError = class ConnectionNotFoundError extends Error {
12980
+ constructor(message) {
12981
+ super(message);
12949
12982
  }
12950
- unhandleExceptions(...args) {
12951
- console.warn("Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()");
12952
- this.exceptions.unhandle(...args);
12983
+ };
12984
+ TableNotFoundError = class TableNotFoundError extends Error {
12985
+ constructor(message) {
12986
+ super(message);
12953
12987
  }
12954
- cli() {
12955
- throw new Error([
12956
- "Logger.cli() was removed in winston@3.0.0",
12957
- "Use a custom winston.formats.cli() instead.",
12958
- "See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"
12959
- ].join(`
12960
- `));
12988
+ };
12989
+ ConnectionError = class ConnectionError extends Error {
12990
+ callerSafe;
12991
+ constructor(message, options) {
12992
+ super(message);
12993
+ this.callerSafe = options?.callerSafe ?? false;
12961
12994
  }
12962
- _onEvent(event, transport) {
12963
- function transportEvent(err) {
12964
- if (event === "error" && !this.transports.includes(transport)) {
12965
- this.add(transport);
12966
- }
12967
- this.emit(event, err, transport);
12968
- }
12969
- if (!transport["__winston" + event]) {
12970
- transport["__winston" + event] = transportEvent.bind(this);
12971
- transport.on(event, transport["__winston" + event]);
12972
- }
12995
+ };
12996
+ DestinationNotFoundError = class DestinationNotFoundError extends Error {
12997
+ constructor(message) {
12998
+ super(message);
12973
12999
  }
12974
- _addDefaultMeta(msg) {
12975
- if (this.defaultMeta) {
12976
- Object.assign(msg, this.defaultMeta);
12977
- }
13000
+ };
13001
+ ConnectionAuthError = class ConnectionAuthError extends Error {
13002
+ constructor(message) {
13003
+ super(message);
12978
13004
  }
12979
- }
12980
- function getLevelValue(levels, level) {
12981
- const value = levels[level];
12982
- if (!value && value !== 0) {
12983
- return null;
13005
+ };
13006
+ UnsupportedCatalogFormatError = class UnsupportedCatalogFormatError extends Error {
13007
+ constructor(message) {
13008
+ super(message);
12984
13009
  }
12985
- return value;
12986
- }
12987
- Object.defineProperty(Logger.prototype, "transports", {
12988
- configurable: false,
12989
- enumerable: true,
12990
- get() {
12991
- const { pipes } = this._readableState;
12992
- return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes;
13010
+ };
13011
+ ModelCompilationError = class ModelCompilationError extends Error {
13012
+ constructor(error) {
13013
+ super(error.message);
12993
13014
  }
12994
- });
12995
- module.exports = Logger;
12996
- });
12997
-
12998
- // ../../node_modules/winston/lib/winston/create-logger.js
12999
- var require_create_logger = __commonJS((exports, module) => {
13000
- var { LEVEL } = require_triple_beam();
13001
- var config = require_config2();
13002
- var Logger = require_logger();
13003
- var debug = require_node3()("winston:create-logger");
13004
- function isLevelEnabledFunctionName(level) {
13005
- return "is" + level.charAt(0).toUpperCase() + level.slice(1) + "Enabled";
13006
- }
13007
- module.exports = function(opts = {}) {
13008
- opts.levels = opts.levels || config.npm.levels;
13009
-
13010
- class DerivedLogger extends Logger {
13011
- constructor(options) {
13012
- super(options);
13013
- }
13015
+ };
13016
+ MaterializationEligibilityError = class MaterializationEligibilityError extends Error {
13017
+ reason;
13018
+ constructor(error) {
13019
+ super(error.message);
13020
+ this.name = "MaterializationEligibilityError";
13021
+ this.reason = error.reason;
13014
13022
  }
13015
- const logger = new DerivedLogger(opts);
13016
- Object.keys(opts.levels).forEach(function(level) {
13017
- debug('Define prototype method for "%s"', level);
13018
- if (level === "log") {
13019
- console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.');
13020
- return;
13021
- }
13022
- DerivedLogger.prototype[level] = function(...args) {
13023
- const self2 = this || logger;
13024
- if (args.length === 1) {
13025
- const [msg] = args;
13026
- const info = msg && msg.message && msg || { message: msg };
13027
- info.level = info[LEVEL] = level;
13028
- self2._addDefaultMeta(info);
13029
- self2.write(info);
13030
- return this || logger;
13031
- }
13032
- if (args.length === 0) {
13033
- self2.log(level, "");
13034
- return self2;
13035
- }
13036
- return self2.log(level, ...args);
13037
- };
13038
- DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function() {
13039
- return (this || logger).isLevelEnabled(level);
13040
- };
13041
- });
13042
- return logger;
13043
13023
  };
13044
- });
13045
-
13046
- // ../../node_modules/winston/lib/winston/container.js
13047
- var require_container = __commonJS((exports, module) => {
13048
- var createLogger = require_create_logger();
13049
- module.exports = class Container {
13050
- constructor(options = {}) {
13051
- this.loggers = new Map;
13052
- this.options = options;
13024
+ PublisherConfigError = class PublisherConfigError extends Error {
13025
+ constructor(configName, cause) {
13026
+ super(`Could not read ${configName}: ${cause instanceof Error ? cause.message : String(cause)}. Fix the file, or move it aside to fall back to the bundled default.`);
13027
+ this.name = "PublisherConfigError";
13028
+ this.cause = cause;
13053
13029
  }
13054
- add(id, options) {
13055
- if (!this.loggers.has(id)) {
13056
- options = Object.assign({}, options || this.options);
13057
- const existing = options.transports || this.options.transports;
13058
- if (existing) {
13059
- options.transports = Array.isArray(existing) ? existing.slice() : [existing];
13060
- } else {
13061
- options.transports = [];
13062
- }
13063
- const logger = createLogger(options);
13064
- logger.on("close", () => this._delete(id));
13065
- this.loggers.set(id, logger);
13066
- }
13067
- return this.loggers.get(id);
13030
+ };
13031
+ FrozenConfigError = class FrozenConfigError extends Error {
13032
+ constructor(message = `Publisher config can't be updated when ${PUBLISHER_CONFIG_NAME} has { "frozenConfig": true }`) {
13033
+ super(message);
13068
13034
  }
13069
- get(id, options) {
13070
- return this.add(id, options);
13035
+ };
13036
+ AccessDeniedError = class AccessDeniedError extends Error {
13037
+ constructor(message) {
13038
+ super(message);
13039
+ this.name = "AccessDeniedError";
13071
13040
  }
13072
- has(id) {
13073
- return !!this.loggers.has(id);
13041
+ };
13042
+ NotQueryableError = class NotQueryableError extends Error {
13043
+ constructor(message) {
13044
+ super(message);
13045
+ this.name = "NotQueryableError";
13074
13046
  }
13075
- close(id) {
13076
- if (id) {
13077
- return this._removeLogger(id);
13078
- }
13079
- this.loggers.forEach((val, key) => this._removeLogger(key));
13047
+ };
13048
+ MaterializationNotFoundError = class MaterializationNotFoundError extends Error {
13049
+ constructor(message) {
13050
+ super(message);
13080
13051
  }
13081
- _removeLogger(id) {
13082
- if (!this.loggers.has(id)) {
13083
- return;
13084
- }
13085
- const logger = this.loggers.get(id);
13086
- logger.close();
13087
- this._delete(id);
13052
+ };
13053
+ MaterializationConflictError = class MaterializationConflictError extends Error {
13054
+ constructor(message) {
13055
+ super(message);
13088
13056
  }
13089
- _delete(id) {
13090
- this.loggers.delete(id);
13057
+ };
13058
+ InvalidStateTransitionError = class InvalidStateTransitionError extends Error {
13059
+ constructor(message) {
13060
+ super(message);
13091
13061
  }
13092
13062
  };
13093
- });
13094
-
13095
- // ../../node_modules/winston/lib/winston.js
13096
- var require_winston = __commonJS((exports) => {
13097
- var logform = require_logform();
13098
- var { warn } = require_common();
13099
- exports.version = require_package().version;
13100
- exports.transports = require_transports();
13101
- exports.config = require_config2();
13102
- exports.addColors = logform.levels;
13103
- exports.format = logform.format;
13104
- exports.createLogger = require_create_logger();
13105
- exports.Logger = require_logger();
13106
- exports.ExceptionHandler = require_exception_handler();
13107
- exports.RejectionHandler = require_rejection_handler();
13108
- exports.Container = require_container();
13109
- exports.Transport = require_winston_transport();
13110
- exports.loggers = new exports.Container;
13111
- var defaultLogger = exports.createLogger();
13112
- Object.keys(exports.config.npm.levels).concat([
13113
- "log",
13114
- "query",
13115
- "stream",
13116
- "add",
13117
- "remove",
13118
- "clear",
13119
- "profile",
13120
- "startTimer",
13121
- "handleExceptions",
13122
- "unhandleExceptions",
13123
- "handleRejections",
13124
- "unhandleRejections",
13125
- "configure",
13126
- "child"
13127
- ]).forEach((method) => exports[method] = (...args) => defaultLogger[method](...args));
13128
- Object.defineProperty(exports, "level", {
13129
- get() {
13130
- return defaultLogger.level;
13131
- },
13132
- set(val) {
13133
- defaultLogger.level = val;
13063
+ ServiceUnavailableError = class ServiceUnavailableError extends Error {
13064
+ constructor(message) {
13065
+ super(message);
13134
13066
  }
13135
- });
13136
- Object.defineProperty(exports, "exceptions", {
13137
- get() {
13138
- return defaultLogger.exceptions;
13067
+ };
13068
+ PayloadTooLargeError = class PayloadTooLargeError extends Error {
13069
+ constructor(message) {
13070
+ super(message);
13071
+ this.name = "PayloadTooLargeError";
13139
13072
  }
13140
- });
13141
- Object.defineProperty(exports, "rejections", {
13142
- get() {
13143
- return defaultLogger.rejections;
13073
+ };
13074
+ ResponseUnserializableError = class ResponseUnserializableError extends PayloadTooLargeError {
13075
+ constructor(message) {
13076
+ super(message);
13077
+ this.name = "ResponseUnserializableError";
13144
13078
  }
13145
- });
13146
- ["exitOnError"].forEach((prop) => {
13147
- Object.defineProperty(exports, prop, {
13148
- get() {
13149
- return defaultLogger[prop];
13150
- },
13151
- set(val) {
13152
- defaultLogger[prop] = val;
13153
- }
13154
- });
13155
- });
13156
- Object.defineProperty(exports, "default", {
13157
- get() {
13158
- return {
13159
- exceptionHandlers: defaultLogger.exceptionHandlers,
13160
- rejectionHandlers: defaultLogger.rejectionHandlers,
13161
- transports: defaultLogger.transports
13162
- };
13079
+ };
13080
+ QueryTimeoutError = class QueryTimeoutError extends Error {
13081
+ constructor(message) {
13082
+ super(message);
13163
13083
  }
13164
- });
13165
- warn.deprecated(exports, "setLevels");
13166
- warn.forFunctions(exports, "useFormat", ["cli"]);
13167
- warn.forProperties(exports, "useFormat", ["padLevels", "stripColors"]);
13168
- warn.forFunctions(exports, "deprecated", [
13169
- "addRewriter",
13170
- "addFilter",
13171
- "clone",
13172
- "extend"
13173
- ]);
13174
- warn.forProperties(exports, "deprecated", ["emitErrs", "levelLength"]);
13084
+ };
13175
13085
  });
13176
13086
 
13177
- // src/logger.ts
13178
- function extractTraceIdFromTraceparent(traceparent) {
13179
- if (!traceparent) {
13087
+ // src/service/authorize.ts
13088
+ import { payloadOf, routeOf } from "@malloydata/malloy";
13089
+ function noteRoute(text) {
13090
+ return routeOf({ value: text.trimStart() });
13091
+ }
13092
+ function notePayload(text) {
13093
+ return payloadOf({ value: text.trimStart() }) ?? "";
13094
+ }
13095
+ function authorizeNoteContent(text) {
13096
+ return noteRoute(text) === AUTHORIZE_ROUTE ? notePayload(text) : undefined;
13097
+ }
13098
+ function assertNoCallerAuthorizeAnnotation(callerText) {
13099
+ if (!AUTHORIZE_ANNOTATION_ANYWHERE.test(callerText))
13180
13100
  return;
13181
- }
13182
- const parts = traceparent.split("-");
13183
- const traceId = parts.length >= 2 ? parts[1] : parts.length == 1 ? parts[0] : undefined;
13184
- if (traceId && traceId.length === 32 && /^[0-9a-fA-F]{32}$/.test(traceId)) {
13185
- return traceId;
13186
- }
13187
- return;
13101
+ throw new BadRequestError("An `authorize` annotation is not permitted in caller-submitted Malloy " + "text. Access gates are declared by the model author on the source; a " + "request cannot introduce, replace, or relax one. To validate a gate " + "you are authoring, save it to the package's model file and reload the " + "package — model load validates every `#(authorize)` annotation it " + "declares.");
13188
13102
  }
13189
- function formatDuration(durationMs) {
13190
- if (durationMs >= 1000) {
13191
- const seconds = durationMs / 1000;
13192
- return `${seconds.toFixed(2)}s`;
13103
+ function containsAuthorizeAnnotationTag(texts) {
13104
+ return texts.some((text) => authorizeNoteContent(text) !== undefined);
13105
+ }
13106
+ function collectAuthorizeNearMisses(texts) {
13107
+ const found = [];
13108
+ for (const text of texts) {
13109
+ const trimmed = text.trimStart();
13110
+ const route = noteRoute(trimmed);
13111
+ if (route === AUTHORIZE_ROUTE)
13112
+ continue;
13113
+ const nearMiss = route === undefined ? MALFORMED_AUTHORIZE_ATTEMPT.test(trimmed) : route === "" ? MOTLY_AUTHORIZE_PAYLOAD.test(notePayload(trimmed)) : route.toLowerCase() === AUTHORIZE_ROUTE;
13114
+ if (!nearMiss)
13115
+ continue;
13116
+ found.push(trimmed.split(/[\r\n]/, 1)[0]);
13193
13117
  }
13194
- return `${durationMs.toFixed(2)}ms`;
13118
+ return found;
13195
13119
  }
13196
- function redactSensitive(value, seen = new WeakSet) {
13197
- if (value === null || typeof value !== "object" || value instanceof Date) {
13198
- return value;
13120
+ function assertNoAuthorizeNearMisses(found) {
13121
+ if (found.length === 0)
13122
+ return;
13123
+ const unique = [...new Set(found)];
13124
+ throw new ModelCompilationError({
13125
+ message: `These annotations are not \`authorize\` gates and nothing enforces ` + `them:
13126
+ ${unique.map((t) => ` - \`${t}\``).join(`
13127
+ `)}
13128
+ ` + `Malloy routes an annotation by its prefix, and only ` + `\`#(authorize)\` (or \`##(authorize)\`, or the block form ` + `\`#|(authorize)\`) reaches the authorize route — a space after the ` + `\`#\`, spaces inside the brackets, or anything trailing the closing ` + `bracket makes it a plain tag Malloy hands to something else. Write ` + `\`#(authorize) <expression>\` on its own line directly above the ` + `\`source:\` statement you mean to protect (unquoted — the quoted ` + `string form is retired). This is refused rather than interpreted: ` + `guessing at the ` + `intent would let publisher start enforcing a filter on a package that ` + `has been serving every row.`
13129
+ });
13130
+ }
13131
+ function describeMisplacedAuthorizeAnnotation(f) {
13132
+ if (f.kind === "query")
13133
+ return `on query "${f.name}"`;
13134
+ if (f.kind === "file")
13135
+ return "at the file level (`##(authorize)`)";
13136
+ return `on field "${f.fieldName}" of source "${f.name}"`;
13137
+ }
13138
+ function assertNoMisplacedAuthorizeAnnotations(found) {
13139
+ if (found.length === 0)
13140
+ return;
13141
+ const positions = found.map((f) => ` - ${describeMisplacedAuthorizeAnnotation(f)}`).join(`
13142
+ `);
13143
+ throw new ModelCompilationError({
13144
+ message: `An \`#(authorize)\` annotation is never enforced at:
13145
+ ${positions}
13146
+ ` + `A gate only applies where model load looks for one — a \`source:\`'s ` + `own annotation, or one it inherits from an \`extend\`/query-source ` + `base. File-level \`##(authorize)\` is deprecated and no longer ` + `enforced anywhere, so it always lands here: declare \`#(authorize)\` ` + `on each \`source:\` it was meant to protect instead. Every other ` + `position above should move to the \`source:\` statement it is meant ` + `to protect.`
13147
+ });
13148
+ }
13149
+ function referencedGivenNames(expr) {
13150
+ const scanned = expr.replace(STRING_LITERAL_PATTERN, "''");
13151
+ const names = [];
13152
+ const seen = new Set;
13153
+ for (const match of scanned.matchAll(GIVEN_REF_PATTERN)) {
13154
+ const name = match[1];
13155
+ if (!seen.has(name)) {
13156
+ seen.add(name);
13157
+ names.push(name);
13158
+ }
13199
13159
  }
13200
- if (seen.has(value)) {
13201
- return "[Circular]";
13160
+ return names;
13161
+ }
13162
+ function quoteMalloyIdentifier(name) {
13163
+ return "`" + name.replace(/\\/g, "\\\\").replace(/`/g, "\\`") + "`";
13164
+ }
13165
+ function buildRowLevelProbe(graftTarget, filterText) {
13166
+ return `run: ${quoteMalloyIdentifier(graftTarget)} extend { where: ${filterText} } -> { select: __authorize_probe is 1; limit: 1 }`;
13167
+ }
13168
+ function liftProbeFilterCondition(prepared, label, filterText) {
13169
+ const filterList = prepared._query?.structRef?.filterList;
13170
+ if (!Array.isArray(filterList) || filterList.length === 0) {
13171
+ throw new Error(`${label} carries no filter condition`);
13202
13172
  }
13203
- seen.add(value);
13204
- if (Array.isArray(value)) {
13205
- return value.map((item) => redactSensitive(item, seen));
13173
+ const lifted = filterList[filterList.length - 1];
13174
+ if (lifted.code !== filterText) {
13175
+ throw new Error(`${label} carries the wrong condition — expected "${filterText}", got "${lifted.code ?? ""}"`);
13206
13176
  }
13207
- const result = {};
13208
- for (const [key, val] of Object.entries(value)) {
13209
- result[key] = SENSITIVE_KEYS.has(key.toLowerCase()) ? REDACTED : redactSensitive(val, seen);
13177
+ if (!lifted.isSourceFilter) {
13178
+ throw new Error(`${label} carries a condition that is not a source filter`);
13210
13179
  }
13211
- return result;
13180
+ return lifted;
13212
13181
  }
13213
- function buildAxiosErrorLog(error) {
13214
- if (error.response) {
13215
- return {
13216
- message: "Axios server-side error",
13217
- meta: {
13218
- url: error.response.config.url,
13219
- status: error.response.status,
13220
- headers: redactSensitive(error.response.headers),
13221
- data: redactSensitive(error.response.data)
13182
+ function gateFilterText(exprs) {
13183
+ return exprs.map((e) => `(${e})`).join(" or ");
13184
+ }
13185
+ async function liftRowLevelCondition(compiler, sourceName, exprs) {
13186
+ const filterText = gateFilterText(exprs);
13187
+ const prepared = await compiler.loadQuery(buildRowLevelProbe(sourceName, filterText)).getPreparedQuery();
13188
+ return liftProbeFilterCondition(prepared, `row-level probe for "${sourceName}"`, filterText);
13189
+ }
13190
+ async function validateAuthorizeProbes(compiler, options) {
13191
+ const ownNotesOf = options.authorizeOwnNotes ?? new Map;
13192
+ for (const [sourceName, groups] of options.authorizeMap ?? []) {
13193
+ for (const exprs of groups) {
13194
+ if (exprs.length === 0)
13195
+ continue;
13196
+ let condition;
13197
+ try {
13198
+ condition = await liftRowLevelCondition(compiler, sourceName, exprs);
13199
+ } catch (err) {
13200
+ const detail = err instanceof Error ? err.message : String(err);
13201
+ const ownNotes = ownNotesOf.get(sourceName) ?? [];
13202
+ if (ownNotes.length === 0) {
13203
+ options.onRowLevelGateRejected?.("entry_point_unexpressible");
13204
+ options.onRowLevelGateUnexpressible?.(sourceName, detail);
13205
+ continue;
13206
+ }
13207
+ throw new ModelCompilationError({
13208
+ message: `Invalid #(authorize) annotation on source "${sourceName}" ` + `[${exprs.join(" | ")}]: ${detail}`
13209
+ });
13222
13210
  }
13223
- };
13211
+ options.onOwnRowLevelConditionCompiled?.(sourceName, condition);
13212
+ }
13224
13213
  }
13225
- if (error.request) {
13226
- return {
13227
- message: "Axios client-side error",
13228
- meta: {
13229
- method: error.config?.method,
13230
- url: error.config?.url,
13231
- code: error.code
13232
- }
13233
- };
13214
+ }
13215
+ function isLegacyQuotedPayload(payload) {
13216
+ const trimmed = payload.trim();
13217
+ return WHOLE_BODY_QUOTED_STRING.test(trimmed) || WHOLE_BODY_SINGLE_QUOTED_STRING.test(trimmed);
13218
+ }
13219
+ function unquoteLegacyGatePayload(payload) {
13220
+ const trimmed = payload.trim();
13221
+ const inner = trimmed.slice(1, -1);
13222
+ return trimmed[0] === "'" ? inner.replace(SINGLE_QUOTE_ESCAPE, "$1") : inner.replace(DOUBLE_QUOTE_ESCAPE, "$1");
13223
+ }
13224
+ function parseAuthorizeAnnotation(annotation) {
13225
+ const content = authorizeNoteContent(annotation);
13226
+ if (content === undefined)
13227
+ return null;
13228
+ const trimmed = content.trim();
13229
+ if (trimmed.length === 0) {
13230
+ throw new Error("authorize annotation has an empty expression body");
13234
13231
  }
13235
- return {
13236
- message: "Axios unknown error",
13237
- meta: { message: error.message }
13238
- };
13232
+ return trimmed;
13239
13233
  }
13240
- var import_winston, isTelemetryEnabled, VALID_LOG_LEVELS, getLogLevel = () => {
13241
- if (process.env.LOG_LEVEL) {
13242
- const logLevel = process.env.LOG_LEVEL.toLowerCase();
13243
- if (VALID_LOG_LEVELS.includes(logLevel)) {
13244
- return logLevel;
13245
- } else {
13246
- console.error(`Invalid log level: ${process.env.LOG_LEVEL}. Valid log levels are: ${VALID_LOG_LEVELS.join(", ")}. Defaulting to "debug".`);
13234
+ function collectAuthorizeExprs(annotations) {
13235
+ const exprs = [];
13236
+ for (const annotation of annotations) {
13237
+ const expr = parseAuthorizeAnnotation(annotation);
13238
+ if (expr !== null) {
13239
+ exprs.push(expr);
13247
13240
  }
13248
13241
  }
13249
- return "debug";
13250
- }, logger, DISABLE_RESPONSE_LOGGING, SENSITIVE_KEY_NAMES, SENSITIVE_KEYS, REDACTED = "[REDACTED]", loggerMiddleware = (req, res, next) => {
13251
- const startTime = performance.now();
13252
- const resJson = res.json;
13253
- res.json = (body) => {
13254
- res.locals.body = body;
13255
- return resJson.call(res, body);
13256
- };
13257
- res.on("finish", () => {
13258
- const endTime = performance.now();
13259
- const durationMs = endTime - startTime;
13260
- const traceparent = req.headers["traceparent"];
13261
- const traceId = extractTraceIdFromTraceparent(traceparent);
13262
- const logMetadata = {
13263
- statusCode: res.statusCode,
13264
- duration: formatDuration(durationMs),
13265
- payload: redactSensitive(req.body),
13266
- params: req.params,
13267
- query: req.query
13268
- };
13269
- if (!DISABLE_RESPONSE_LOGGING) {
13270
- logMetadata.response = redactSensitive(res.locals.body);
13271
- }
13272
- if (traceId) {
13273
- logMetadata.traceId = traceId;
13242
+ return exprs;
13243
+ }
13244
+ function findMultipleAuthorizeGates(authorizeOwnNotes) {
13245
+ const found = [];
13246
+ for (const [sourceName, notes] of authorizeOwnNotes) {
13247
+ if (notes.length > 1) {
13248
+ found.push({ sourceName, texts: notes.map((note) => note.text) });
13274
13249
  }
13275
- if (req.url !== "/metrics" && req.url !== "/health" && req.url !== "/health/liveness" && req.url !== "/health/readiness") {
13276
- logger.info(`${req.method} ${req.url}`, logMetadata);
13250
+ }
13251
+ return found;
13252
+ }
13253
+ function assertAtMostOneAuthorizeGate(found) {
13254
+ if (found.length === 0)
13255
+ return;
13256
+ const positions = found.map(({ sourceName, texts }) => ` - source "${sourceName}" declares ${texts.length}:
13257
+ ` + texts.map((t) => ` \`${t.trim().split(/[\r\n]/, 1)[0]}\``).join(`
13258
+ `)).join(`
13259
+ `);
13260
+ throw new ModelCompilationError({
13261
+ message: `A source may declare at most one \`#(authorize)\` annotation:
13262
+ ${positions}
13263
+ ` + `Combine multiple conditions into one expression with \`or\` instead of ` + `repeating the annotation, e.g. ` + "`#(authorize) $ROLE = 'admin' or org_id in $GROUPS`."
13264
+ });
13265
+ }
13266
+ function findLegacyStringGates(authorizeOwnNotes) {
13267
+ const found = [];
13268
+ for (const [sourceName, notes] of authorizeOwnNotes) {
13269
+ const legacyNotes = notes.filter((note) => {
13270
+ const content = authorizeNoteContent(note.text);
13271
+ return content !== undefined && isLegacyQuotedPayload(content);
13272
+ });
13273
+ if (legacyNotes.length === 0)
13274
+ continue;
13275
+ const exprs = collectAuthorizeExprs(legacyNotes.map((note) => note.text));
13276
+ if (exprs.length > 0) {
13277
+ found.push({ sourceName, exprs });
13277
13278
  }
13279
+ }
13280
+ return found;
13281
+ }
13282
+ function assertNoLegacyStringGate(found) {
13283
+ if (found.length === 0)
13284
+ return;
13285
+ const rewrites = found.flatMap(({ sourceName, exprs }) => exprs.map((expr) => ` - source "${sourceName}": replace \`#(authorize) ${expr}\`` + ` with
13286
+ #(authorize) ${unquoteLegacyGatePayload(expr)}`)).join(`
13287
+ `);
13288
+ throw new ModelCompilationError({
13289
+ message: `The string form of \`#(authorize)\` (a Malloy-quoted expression on ` + `the \`source:\` line) is no longer accepted. Replace it with the ` + `unquoted expression, carried by an \`#(authorize)\` annotation on ` + `its own line directly above the \`source:\` line:
13290
+ ${rewrites}
13291
+ ` + `Test that the rewrite gates the same rows and check the row count ` + `matches what the string form served.`
13278
13292
  });
13279
- next();
13280
- }, logAxiosError = (error) => {
13281
- const { message, meta } = buildAxiosErrorLog(error);
13282
- logger.error(message, meta);
13283
- };
13284
- var init_logger = __esm(() => {
13285
- import_winston = __toESM(require_winston(), 1);
13286
- isTelemetryEnabled = Boolean(process.env.OTEL_EXPORTER_OTLP_ENDPOINT);
13287
- VALID_LOG_LEVELS = ["error", "warn", "info", "verbose", "debug", "silly"];
13288
- logger = import_winston.default.createLogger({
13289
- level: getLogLevel(),
13290
- format: isTelemetryEnabled ? import_winston.default.format.combine(import_winston.default.format.uncolorize(), import_winston.default.format.timestamp(), import_winston.default.format.errors({ stack: true }), import_winston.default.format.json()) : import_winston.default.format.combine(import_winston.default.format.colorize(), import_winston.default.format.simple()),
13291
- transports: [new import_winston.default.transports.Console]
13293
+ }
13294
+ var AUTHORIZE_ROUTE = "authorize", AUTHORIZE_TAG_LIKE, AUTHORIZE_ANNOTATION_ANYWHERE, MOTLY_AUTHORIZE_PAYLOAD, MALFORMED_AUTHORIZE_ATTEMPT, GIVEN_REF_PATTERN, SINGLE_QUOTE_ESCAPE, DOUBLE_QUOTE_ESCAPE, STRING_LITERAL_PATTERN, everyMemberOf = () => (...members) => members, ROW_LEVEL_GATE_REJECTION_CAUSES, WHOLE_BODY_QUOTED_STRING, WHOLE_BODY_SINGLE_QUOTED_STRING;
13295
+ var init_authorize = __esm(() => {
13296
+ init_errors();
13297
+ AUTHORIZE_TAG_LIKE = String.raw`##?\|?[ \t]*[([{<]?[ \t]*authorize(?=[)\]}>]|[ \t]|$)`;
13298
+ AUTHORIZE_ANNOTATION_ANYWHERE = new RegExp(AUTHORIZE_TAG_LIKE, "iu");
13299
+ MOTLY_AUTHORIZE_PAYLOAD = /^[ \t]*[([{<][ \t]*authorize[ \t]*[)\]}>]/iu;
13300
+ MALFORMED_AUTHORIZE_ATTEMPT = /^##?\|?[ \t]*[([{<]?[ \t]*authorize/iu;
13301
+ GIVEN_REF_PATTERN = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
13302
+ SINGLE_QUOTE_ESCAPE = /\\(['\\])/g;
13303
+ DOUBLE_QUOTE_ESCAPE = /\\(["\\])/g;
13304
+ STRING_LITERAL_PATTERN = /'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"/g;
13305
+ ROW_LEVEL_GATE_REJECTION_CAUSES = everyMemberOf()("unreachable_given", "entry_point_unexpressible", "source_line_gate_no_given_reference", "source_line_gate_negated_membership", "legacy_string_gate", "given_usage_unresolvable", "unclassifiable_condition");
13306
+ WHOLE_BODY_QUOTED_STRING = /^"(?:\\.|[^"\\])*"$/;
13307
+ WHOLE_BODY_SINGLE_QUOTED_STRING = /^'(?:\\.|[^'\\])*'$/;
13308
+ });
13309
+
13310
+ // src/authorize_metrics.ts
13311
+ function recordAuthorizeGuardRejection(field) {
13312
+ guardRejectionCounter ??= publisherMeter().createCounter("publisher_authorize_guard_rejected_total", {
13313
+ description: "Requests rejected with 400 for declaring an `#(authorize)` annotation in caller-submitted Malloy text. Label: field ('query'|'source_name'|'query_name'|'compile_source')."
13292
13314
  });
13293
- DISABLE_RESPONSE_LOGGING = process.env.DISABLE_RESPONSE_LOGGING === "true" || process.env.DISABLE_RESPONSE_LOGGING === "1";
13294
- SENSITIVE_KEY_NAMES = [
13295
- "password",
13296
- "connectionString",
13297
- "serviceAccountKeyJson",
13298
- "privateKey",
13299
- "privateKeyPass",
13300
- "secret",
13301
- "secretAccessKey",
13302
- "sessionToken",
13303
- "sasUrl",
13304
- "clientSecret",
13305
- "oauthClientSecret",
13306
- "peakaKey",
13307
- "token",
13308
- "accessToken",
13309
- "apiKey",
13310
- "api_key",
13311
- "authorization",
13312
- "proxy-authorization",
13313
- "cookie",
13314
- "set-cookie",
13315
- "x-api-key"
13316
- ];
13317
- SENSITIVE_KEYS = new Set(SENSITIVE_KEY_NAMES.map((name) => name.toLowerCase()));
13315
+ guardRejectionCounter.add(1, { field });
13316
+ }
13317
+ function recordAuthorizeBypass(entryPoint) {
13318
+ bypassCounter ??= publisherMeter().createCounter("publisher_authorize_bypass_total", {
13319
+ description: "Gate evaluations skipped because the request carried an authorize bypass (private data-management path). Label: entry_point ('source'|'runnable'). Any nonzero value on a path that should not use the bypass is a finding — see the paired `authorize bypass` audit log line for org/package/model/source."
13320
+ });
13321
+ bypassCounter.add(1, { entry_point: entryPoint });
13322
+ }
13323
+ function recordRowLevelGateDecision(decision) {
13324
+ rowLevelDecisionCounter ??= publisherMeter().createCounter("publisher_authorize_row_level_total", {
13325
+ description: "How a row-level `#(authorize)` gate resolved a request. Label: decision ('denied_by_gate'|'empty_after_filter'). 'denied_by_gate' is the fail-closed refusal when the gate could not be applied; 'empty_after_filter' is a successful response with zero rows after the filter matched none, which is NOT an error."
13326
+ });
13327
+ rowLevelDecisionCounter.add(1, { decision });
13328
+ }
13329
+ function recordRowLevelGateRejected(cause) {
13330
+ rowLevelRejectionCounter ??= publisherMeter().createCounter("publisher_authorize_row_level_rejected_total", {
13331
+ description: "Row-level `#(authorize)` gates that were refused, warned about, or could not be resolved. Label: cause (" + ROW_LEVEL_GATE_REJECTION_CAUSES.map((c) => `'${c}'`).join("|") + "). Only 'legacy_string_gate' fails the whole model load. 'entry_point_unexpressible', 'source_line_gate_no_given_reference' and 'source_line_gate_negated_membership' warn at load and leave the model servable. 'unreachable_given', 'given_usage_unresolvable' and 'unclassifiable_condition' are request-time only — that entry point denies every request. Alert on any nonzero value since the last publish; the request-time causes also make this a rate signal, so see the doc above before writing an alert."
13332
+ });
13333
+ rowLevelRejectionCounter.add(1, { cause });
13334
+ }
13335
+ var guardRejectionCounter = null, bypassCounter = null, rowLevelDecisionCounter = null, rowLevelRejectionCounter = null;
13336
+ var init_authorize_metrics = __esm(() => {
13337
+ init_telemetry();
13338
+ init_authorize();
13318
13339
  });
13319
13340
 
13320
13341
  // src/data_styles.ts