@malloy-publisher/server 0.2.6 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/dist/app/api-doc.yaml +39 -1
  2. package/dist/app/assets/{EnvironmentPage-BAegPFOF.js → EnvironmentPage-D6kQraU3.js} +1 -1
  3. package/dist/app/assets/{HomePage-DpDWLD0m.js → HomePage-BZbuE5jv.js} +1 -1
  4. package/dist/app/assets/{LightMode-CAFl4Cvr.js → LightMode-BxZdPcNr.js} +1 -1
  5. package/dist/app/assets/{MainPage-DBHZF__d.js → MainPage-DrczCw4J.js} +2 -2
  6. package/dist/app/assets/{MaterializationsPage-DS5Wrhkc.js → MaterializationsPage-BFLHLEuk.js} +1 -1
  7. package/dist/app/assets/ModelPage-CFnfQ6BL.js +1 -0
  8. package/dist/app/assets/{PackagePage-D5gz7Abx.js → PackagePage-DHsVf_mP.js} +1 -1
  9. package/dist/app/assets/{RouteError-BE1pcxrx.js → RouteError-CHq8ubhy.js} +1 -1
  10. package/dist/app/assets/{ThemeEditorPage-CiRxkL1D.js → ThemeEditorPage-B2y8Y64Y.js} +1 -1
  11. package/dist/app/assets/core-B8oMW4sm.es-hOkwvru5.js +148 -0
  12. package/dist/app/assets/index-BVv6KQ93.js +557 -0
  13. package/dist/app/assets/{index-73xxtSWr.js → index-Bqrhk3ff.js} +1 -1
  14. package/dist/app/assets/{index-C22pKyUm.js → index-By-g8wiC.js} +1 -1
  15. package/dist/app/assets/{index-BVkVGR63.js → index-CawCwLK3.js} +1 -1
  16. package/dist/app/assets/index-DUqldpo0.css +1 -0
  17. package/dist/app/index.html +2 -2
  18. package/dist/instrumentation.mjs +62738 -42960
  19. package/dist/package_load_worker.mjs +1653 -1557
  20. package/dist/runtime/publisher.js +60 -14
  21. package/dist/server.mjs +61680 -40017
  22. package/package.json +1 -1
  23. package/dist/app/assets/ModelPage-BE19OgP9.js +0 -1
  24. package/dist/app/assets/WorkbookPage-Czc9IG0b.js +0 -1
  25. package/dist/app/assets/core-xdZbLgaF.es-BGrT15Sy.js +0 -148
  26. package/dist/app/assets/index-5eLCcNmP.css +0 -1
  27. package/dist/app/assets/index-DcYLvDJ2.js +0 -632
@@ -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
 
@@ -12270,20 +11810,187 @@ var require_stack_trace = __commonJS((exports) => {
12270
11810
  };
12271
11811
  });
12272
11812
 
12273
- // ../../node_modules/winston/lib/winston/exception-stream.js
12274
- var require_exception_stream = __commonJS((exports, module) => {
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.");
11821
+ }
11822
+ this.handleExceptions = true;
11823
+ this.transport = transport;
11824
+ }
11825
+ _write(info, enc, callback) {
11826
+ if (info.exception) {
11827
+ return this.transport.log(info, callback);
11828
+ }
11829
+ callback();
11830
+ return true;
11831
+ }
11832
+ };
11833
+ });
11834
+
11835
+ // ../../node_modules/winston/lib/winston/exception-handler.js
11836
+ var require_exception_handler = __commonJS((exports, module) => {
11837
+ var os2 = __require("os");
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");
11847
+ }
11848
+ this.logger = logger;
11849
+ this.handlers = new Map;
11850
+ }
11851
+ handle(...args) {
11852
+ args.forEach((arg) => {
11853
+ if (Array.isArray(arg)) {
11854
+ return arg.forEach((handler) => this._addHandler(handler));
11855
+ }
11856
+ this._addHandler(arg);
11857
+ });
11858
+ if (!this.catcher) {
11859
+ this.catcher = this._uncaughtException.bind(this);
11860
+ process.on("uncaughtException", this.catcher);
11861
+ }
11862
+ }
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
+ }
11869
+ }
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
+ };
11890
+ }
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
+ };
11902
+ }
11903
+ getOsInfo() {
11904
+ return {
11905
+ loadavg: os2.loadavg(),
11906
+ uptime: os2.uptime()
11907
+ };
11908
+ }
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
+ });
11921
+ }
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);
11928
+ }
11929
+ }
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
+ }
11970
+ }
11971
+ _getExceptionHandlers() {
11972
+ return this.logger.transports.filter((wrap) => {
11973
+ const transport = wrap.transport || wrap;
11974
+ return transport.handleExceptions;
11975
+ });
11976
+ }
11977
+ };
11978
+ });
11979
+
11980
+ // ../../node_modules/winston/lib/winston/rejection-stream.js
11981
+ var require_rejection_stream = __commonJS((exports, module) => {
12275
11982
  var { Writable } = require_readable();
12276
- module.exports = class ExceptionStream extends Writable {
11983
+ module.exports = class RejectionStream extends Writable {
12277
11984
  constructor(transport) {
12278
11985
  super({ objectMode: true });
12279
11986
  if (!transport) {
12280
- throw new Error("ExceptionStream requires a TransportStream instance.");
11987
+ throw new Error("RejectionStream requires a TransportStream instance.");
12281
11988
  }
12282
- this.handleExceptions = true;
11989
+ this.handleRejections = true;
12283
11990
  this.transport = transport;
12284
11991
  }
12285
11992
  _write(info, enc, callback) {
12286
- if (info.exception) {
11993
+ if (info.rejection) {
12287
11994
  return this.transport.log(info, callback);
12288
11995
  }
12289
11996
  callback();
@@ -12292,18 +11999,18 @@ var require_exception_stream = __commonJS((exports, module) => {
12292
11999
  };
12293
12000
  });
12294
12001
 
12295
- // ../../node_modules/winston/lib/winston/exception-handler.js
12296
- var require_exception_handler = __commonJS((exports, module) => {
12002
+ // ../../node_modules/winston/lib/winston/rejection-handler.js
12003
+ var require_rejection_handler = __commonJS((exports, module) => {
12297
12004
  var os2 = __require("os");
12298
12005
  var asyncForEach = require_forEach();
12299
- var debug = require_node3()("winston:exception");
12006
+ var debug = require_node3()("winston:rejection");
12300
12007
  var once = require_one_time();
12301
12008
  var stackTrace = require_stack_trace();
12302
- var ExceptionStream = require_exception_stream();
12303
- module.exports = class ExceptionHandler {
12009
+ var RejectionStream = require_rejection_stream();
12010
+ module.exports = class RejectionHandler {
12304
12011
  constructor(logger) {
12305
12012
  if (!logger) {
12306
- throw new Error("Logger is required to handle exceptions");
12013
+ throw new Error("Logger is required to handle rejections");
12307
12014
  }
12308
12015
  this.logger = logger;
12309
12016
  this.handlers = new Map;
@@ -12316,13 +12023,13 @@ var require_exception_handler = __commonJS((exports, module) => {
12316
12023
  this._addHandler(arg);
12317
12024
  });
12318
12025
  if (!this.catcher) {
12319
- this.catcher = this._uncaughtException.bind(this);
12320
- process.on("uncaughtException", this.catcher);
12026
+ this.catcher = this._unhandledRejection.bind(this);
12027
+ process.on("unhandledRejection", this.catcher);
12321
12028
  }
12322
12029
  }
12323
12030
  unhandle() {
12324
12031
  if (this.catcher) {
12325
- process.removeListener("uncaughtException", this.catcher);
12032
+ process.removeListener("unhandledRejection", this.catcher);
12326
12033
  this.catcher = false;
12327
12034
  Array.from(this.handlers.values()).forEach((wrapper) => this.logger.unpipe(wrapper));
12328
12035
  }
@@ -12336,12 +12043,12 @@ var require_exception_handler = __commonJS((exports, module) => {
12336
12043
  error: err,
12337
12044
  level: "error",
12338
12045
  message: [
12339
- `uncaughtException: ${message || "(no error message)"}`,
12046
+ `unhandledRejection: ${message || "(no error message)"}`,
12340
12047
  err && err.stack || " No stack trace"
12341
12048
  ].join(`
12342
12049
  `),
12343
12050
  stack: err && err.stack,
12344
- exception: true,
12051
+ rejection: true,
12345
12052
  date: new Date().toString(),
12346
12053
  process: this.getProcessInfo(),
12347
12054
  os: this.getOsInfo(),
@@ -12381,940 +12088,1254 @@ var require_exception_handler = __commonJS((exports, module) => {
12381
12088
  }
12382
12089
  _addHandler(handler) {
12383
12090
  if (!this.handlers.has(handler)) {
12384
- handler.handleExceptions = true;
12385
- const wrapper = new ExceptionStream(handler);
12091
+ handler.handleRejections = true;
12092
+ const wrapper = new RejectionStream(handler);
12386
12093
  this.handlers.set(handler, wrapper);
12387
12094
  this.logger.pipe(wrapper);
12388
12095
  }
12389
12096
  }
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;
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);
12113
+ }
12114
+ process.exit(1);
12115
+ }
12116
+ }
12117
+ if (!handlers || handlers.length === 0) {
12118
+ return process.nextTick(gracefulExit);
12119
+ }
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);
12136
+ }
12137
+ }
12138
+ _getRejectionHandlers() {
12139
+ return this.logger.transports.filter((wrap) => {
12140
+ const transport = wrap.transport || wrap;
12141
+ return transport.handleRejections;
12142
+ });
12143
+ }
12144
+ };
12145
+ });
12146
+
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();
12157
+ }
12158
+ }
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();
12163
+ }
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);
12168
+ }
12169
+ }
12170
+ module.exports = Profiler;
12171
+ });
12172
+
12173
+ // ../../node_modules/winston/lib/winston/logger.js
12174
+ var require_logger = __commonJS((exports, module) => {
12175
+ var { Stream, Transform } = require_readable();
12176
+ var asyncForEach = require_forEach();
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);
12259
+ }
12260
+ }
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;
12319
+ }
12320
+ }
12321
+ this.write(Object.assign({}, this.defaultMeta, {
12322
+ [LEVEL]: level,
12323
+ [SPLAT]: splat,
12324
+ level,
12325
+ message: msg
12326
+ }));
12327
+ return this;
12328
+ }
12329
+ _transform(info, enc, callback) {
12330
+ if (this.silent) {
12331
+ return callback();
12399
12332
  }
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);
12408
- }
12333
+ if (!info[LEVEL]) {
12334
+ info[LEVEL] = info.level;
12409
12335
  }
12410
- if (!handlers || handlers.length === 0) {
12411
- return process.nextTick(gracefulExit);
12336
+ if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) {
12337
+ console.error("[winston] Unknown logger level: %s", info[LEVEL]);
12412
12338
  }
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);
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();
12429
12347
  }
12430
12348
  }
12431
- _getExceptionHandlers() {
12432
- return this.logger.transports.filter((wrap) => {
12433
- const transport = wrap.transport || wrap;
12434
- return transport.handleExceptions;
12435
- });
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);
12436
12357
  }
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.");
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 }.");
12448
12362
  }
12449
- this.handleRejections = true;
12450
- this.transport = transport;
12451
- }
12452
- _write(info, enc, callback) {
12453
- if (info.rejection) {
12454
- return this.transport.log(info, callback);
12363
+ this._onEvent("error", target);
12364
+ this._onEvent("warn", target);
12365
+ this.pipe(target);
12366
+ if (transport.handleExceptions) {
12367
+ this.exceptions.handle();
12455
12368
  }
12456
- callback();
12457
- return true;
12458
- }
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");
12369
+ if (transport.handleRejections) {
12370
+ this.rejections.handle();
12474
12371
  }
12475
- this.logger = logger;
12476
- this.handlers = new Map;
12372
+ return this;
12477
12373
  }
12478
- handle(...args) {
12479
- args.forEach((arg) => {
12480
- if (Array.isArray(arg)) {
12481
- return arg.forEach((handler) => this._addHandler(handler));
12482
- }
12483
- this._addHandler(arg);
12484
- });
12485
- if (!this.catcher) {
12486
- this.catcher = this._unhandledRejection.bind(this);
12487
- process.on("unhandledRejection", this.catcher);
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];
12488
12380
  }
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));
12381
+ if (target) {
12382
+ this.unpipe(target);
12495
12383
  }
12384
+ return this;
12496
12385
  }
12497
- getAllInfo(err) {
12498
- let message = null;
12499
- if (err) {
12500
- message = typeof err === "string" ? err : err.message;
12501
- }
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
- };
12386
+ clear() {
12387
+ this.unpipe();
12388
+ return this;
12517
12389
  }
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
- };
12390
+ close() {
12391
+ this.exceptions.unhandle();
12392
+ this.rejections.unhandle();
12393
+ this.clear();
12394
+ this.emit("close");
12395
+ return this;
12529
12396
  }
12530
- getOsInfo() {
12531
- return {
12532
- loadavg: os2.loadavg(),
12533
- uptime: os2.uptime()
12397
+ setLevels() {
12398
+ warn.deprecated("setLevels");
12399
+ }
12400
+ query(options, callback) {
12401
+ if (typeof options === "function") {
12402
+ callback = options;
12403
+ options = {};
12404
+ }
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);
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
+ });
12421
+ }
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
+ });
12433
+ }
12434
+ asyncForEach(this.transports.filter((transport) => !!transport.query), addResults, () => callback(null, results));
12435
+ }
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
+ }
12534
12445
  };
12535
- }
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
- };
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
+ });
12547
12462
  });
12463
+ return out;
12548
12464
  }
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);
12555
- }
12465
+ startTimer() {
12466
+ return new Profiler(this);
12556
12467
  }
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;
12566
- }
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);
12575
- }
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
- };
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();
12588
12476
  }
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);
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);
12596
12482
  }
12483
+ this.profilers[id] = time;
12484
+ return this;
12597
12485
  }
12598
- _getRejectionHandlers() {
12599
- return this.logger.transports.filter((wrap) => {
12600
- const transport = wrap.transport || wrap;
12601
- return transport.handleRejections;
12602
- });
12486
+ handleExceptions(...args) {
12487
+ console.warn("Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()");
12488
+ this.exceptions.handle(...args);
12603
12489
  }
12604
- };
12605
- });
12606
-
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();
12490
+ unhandleExceptions(...args) {
12491
+ console.warn("Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()");
12492
+ this.exceptions.unhandle(...args);
12493
+ }
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);
12506
+ }
12507
+ this.emit(event, err, transport);
12508
+ }
12509
+ if (!transport["__winston" + event]) {
12510
+ transport["__winston" + event] = transportEvent.bind(this);
12511
+ transport.on(event, transport["__winston" + event]);
12617
12512
  }
12618
12513
  }
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();
12514
+ _addDefaultMeta(msg) {
12515
+ if (this.defaultMeta) {
12516
+ Object.assign(msg, this.defaultMeta);
12623
12517
  }
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);
12628
12518
  }
12629
12519
  }
12630
- module.exports = Profiler;
12631
- });
12632
-
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();
12643
- 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);
12520
+ function getLevelValue(levels, level) {
12521
+ const value = levels[level];
12522
+ if (!value && value !== 0) {
12523
+ return null;
12651
12524
  }
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
- });
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;
12666
12533
  }
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);
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);
12719
12553
  }
12720
12554
  }
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;
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;
12732
12561
  }
12733
- const index = this.transports.findIndex((transport) => {
12734
- let transportLevelValue = getLevelValue(this.levels, transport.level);
12735
- if (transportLevelValue === null) {
12736
- transportLevelValue = configuredLevelValue;
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;
12737
12571
  }
12738
- return transportLevelValue >= givenLevelValue;
12739
- });
12740
- return index !== -1;
12741
- }
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;
12572
+ if (args.length === 0) {
12573
+ self2.log(level, "");
12574
+ return self2;
12755
12575
  }
12756
- msg = { [LEVEL]: level, level, message: msg };
12757
- this._addDefaultMeta(msg);
12758
- this.write(msg);
12759
- return this;
12760
- }
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;
12576
+ return self2.log(level, ...args);
12577
+ };
12578
+ DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function() {
12579
+ return (this || logger).isLevelEnabled(level);
12580
+ };
12581
+ });
12582
+ return logger;
12583
+ };
12584
+ });
12585
+
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 = [];
12779
12602
  }
12603
+ const logger = createLogger(options);
12604
+ logger.on("close", () => this._delete(id));
12605
+ this.loggers.set(id, logger);
12780
12606
  }
12781
- this.write(Object.assign({}, this.defaultMeta, {
12782
- [LEVEL]: level,
12783
- [SPLAT]: splat,
12784
- level,
12785
- message: msg
12786
- }));
12787
- return this;
12607
+ return this.loggers.get(id);
12788
12608
  }
12789
- _transform(info, enc, callback) {
12790
- if (this.silent) {
12791
- return callback();
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);
12792
12618
  }
12793
- if (!info[LEVEL]) {
12794
- info[LEVEL] = info.level;
12619
+ this.loggers.forEach((val, key) => this._removeLogger(key));
12620
+ }
12621
+ _removeLogger(id) {
12622
+ if (!this.loggers.has(id)) {
12623
+ return;
12795
12624
  }
12796
- if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) {
12797
- console.error("[winston] Unknown logger level: %s", info[LEVEL]);
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
+ };
12633
+ });
12634
+
12635
+ // ../../node_modules/winston/lib/winston.js
12636
+ var require_winston = __commonJS((exports) => {
12637
+ var logform = require_logform();
12638
+ var { warn } = require_common();
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;
12674
+ }
12675
+ });
12676
+ Object.defineProperty(exports, "exceptions", {
12677
+ get() {
12678
+ return defaultLogger.exceptions;
12679
+ }
12680
+ });
12681
+ Object.defineProperty(exports, "rejections", {
12682
+ get() {
12683
+ return defaultLogger.rejections;
12684
+ }
12685
+ });
12686
+ ["exitOnError"].forEach((prop) => {
12687
+ Object.defineProperty(exports, prop, {
12688
+ get() {
12689
+ return defaultLogger[prop];
12690
+ },
12691
+ set(val) {
12692
+ defaultLogger[prop] = val;
12798
12693
  }
12799
- if (!this._readableState.pipes) {
12800
- console.error("[winston] Attempt to write logs with no transports, which can increase memory usage: %j", info);
12694
+ });
12695
+ });
12696
+ Object.defineProperty(exports, "default", {
12697
+ get() {
12698
+ return {
12699
+ exceptionHandlers: defaultLogger.exceptionHandlers,
12700
+ rejectionHandlers: defaultLogger.rejectionHandlers,
12701
+ transports: defaultLogger.transports
12702
+ };
12703
+ }
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)
12801
12762
  }
12802
- try {
12803
- this.push(this.format.transform(info, this.format.options));
12804
- } finally {
12805
- this._writableState.sync = false;
12806
- callback();
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
12807
12772
  }
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".`);
12808
12787
  }
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);
12817
- }
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;
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);
12833
12811
  }
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;
12812
+ if (traceId) {
12813
+ logMetadata.traceId = traceId;
12845
12814
  }
12846
- clear() {
12847
- this.unpipe();
12848
- 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);
12849
12817
  }
12850
- close() {
12851
- this.exceptions.unhandle();
12852
- this.rejections.unhandle();
12853
- this.clear();
12854
- this.emit("close");
12855
- 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)
12856
12872
  }
12857
- setLevels() {
12858
- warn.deprecated("setLevels");
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);
12859
12911
  }
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));
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 } : {}
12895
12940
  }
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;
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);
12924
12950
  }
12925
- startTimer() {
12926
- return new Profiler(this);
12951
+ };
12952
+ BadRequestError = class BadRequestError extends Error {
12953
+ constructor(message) {
12954
+ super(message);
12927
12955
  }
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;
12956
+ };
12957
+ InvalidArgumentError = class InvalidArgumentError extends BadRequestError {
12958
+ };
12959
+ EnvironmentNotFoundError = class EnvironmentNotFoundError extends Error {
12960
+ constructor(message) {
12961
+ super(message);
12945
12962
  }
12946
- handleExceptions(...args) {
12947
- console.warn("Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()");
12948
- this.exceptions.handle(...args);
12963
+ };
12964
+ PackageNotFoundError = class PackageNotFoundError extends Error {
12965
+ constructor(message) {
12966
+ super(message);
12949
12967
  }
12950
- unhandleExceptions(...args) {
12951
- console.warn("Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()");
12952
- this.exceptions.unhandle(...args);
12968
+ };
12969
+ ModelNotFoundError = class ModelNotFoundError extends Error {
12970
+ constructor(message) {
12971
+ super(message);
12953
12972
  }
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
- `));
12973
+ };
12974
+ DashboardNotFoundError = class DashboardNotFoundError extends Error {
12975
+ constructor(message) {
12976
+ super(message);
12961
12977
  }
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
- }
12978
+ };
12979
+ ConnectionNotFoundError = class ConnectionNotFoundError extends Error {
12980
+ constructor(message) {
12981
+ super(message);
12973
12982
  }
12974
- _addDefaultMeta(msg) {
12975
- if (this.defaultMeta) {
12976
- Object.assign(msg, this.defaultMeta);
12977
- }
12983
+ };
12984
+ TableNotFoundError = class TableNotFoundError extends Error {
12985
+ constructor(message) {
12986
+ super(message);
12978
12987
  }
12979
- }
12980
- function getLevelValue(levels, level) {
12981
- const value = levels[level];
12982
- if (!value && value !== 0) {
12983
- return null;
12988
+ };
12989
+ ConnectionError = class ConnectionError extends Error {
12990
+ callerSafe;
12991
+ constructor(message, options) {
12992
+ super(message);
12993
+ this.callerSafe = options?.callerSafe ?? false;
12984
12994
  }
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;
12995
+ };
12996
+ DestinationNotFoundError = class DestinationNotFoundError extends Error {
12997
+ constructor(message) {
12998
+ super(message);
12993
12999
  }
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
- }
13000
+ };
13001
+ ConnectionAuthError = class ConnectionAuthError extends Error {
13002
+ constructor(message) {
13003
+ super(message);
13014
13004
  }
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
13005
  };
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;
13006
+ UnsupportedCatalogFormatError = class UnsupportedCatalogFormatError extends Error {
13007
+ constructor(message) {
13008
+ super(message);
13053
13009
  }
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);
13010
+ };
13011
+ ModelCompilationError = class ModelCompilationError extends Error {
13012
+ constructor(error) {
13013
+ super(error.message);
13068
13014
  }
13069
- get(id, options) {
13070
- return this.add(id, options);
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;
13071
13022
  }
13072
- has(id) {
13073
- return !!this.loggers.has(id);
13023
+ };
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;
13029
+ }
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);
13034
+ }
13035
+ };
13036
+ AccessDeniedError = class AccessDeniedError extends Error {
13037
+ constructor(message) {
13038
+ super(message);
13039
+ this.name = "AccessDeniedError";
13040
+ }
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;
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.");
13102
+ }
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]);
13181
13117
  }
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;
13118
+ return found;
13119
+ }
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
+ }
13186
13159
  }
13187
- return;
13160
+ return names;
13188
13161
  }
13189
- function formatDuration(durationMs) {
13190
- if (durationMs >= 1000) {
13191
- const seconds = durationMs / 1000;
13192
- return `${seconds.toFixed(2)}s`;
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`);
13172
+ }
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 ?? ""}"`);
13176
+ }
13177
+ if (!lifted.isSourceFilter) {
13178
+ throw new Error(`${label} carries a condition that is not a source filter`);
13179
+ }
13180
+ return lifted;
13181
+ }
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
+ });
13210
+ }
13211
+ options.onOwnRowLevelConditionCompiled?.(sourceName, condition);
13212
+ }
13193
13213
  }
13194
- return `${durationMs.toFixed(2)}ms`;
13195
13214
  }
13196
- function redactSensitive(value, seen = new WeakSet) {
13197
- if (value === null || typeof value !== "object" || value instanceof Date) {
13198
- return value;
13199
- }
13200
- if (seen.has(value)) {
13201
- return "[Circular]";
13202
- }
13203
- seen.add(value);
13204
- if (Array.isArray(value)) {
13205
- return value.map((item) => redactSensitive(item, seen));
13206
- }
13207
- const result = {};
13208
- for (const [key, val] of Object.entries(value)) {
13209
- result[key] = SENSITIVE_KEYS.has(key.toLowerCase()) ? REDACTED : redactSensitive(val, seen);
13210
- }
13211
- return result;
13215
+ function isLegacyQuotedPayload(payload) {
13216
+ const trimmed = payload.trim();
13217
+ return WHOLE_BODY_QUOTED_STRING.test(trimmed) || WHOLE_BODY_SINGLE_QUOTED_STRING.test(trimmed);
13212
13218
  }
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)
13222
- }
13223
- };
13224
- }
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
- };
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
@@ -14799,6 +14820,9 @@ var init_motly = __esm(() => {
14799
14820
  });
14800
14821
 
14801
14822
  // src/service/given.ts
14823
+ import {
14824
+ isSourceDef as isSourceDef5
14825
+ } from "@malloydata/malloy";
14802
14826
  function presentText(tag, ...path) {
14803
14827
  const raw = tagText(tag, ...path);
14804
14828
  return raw !== undefined && raw.trim() !== "" ? raw : undefined;
@@ -14854,8 +14878,78 @@ function malloyGivenToApi(given) {
14854
14878
  default: given._internal?.defaultText
14855
14879
  };
14856
14880
  }
14881
+ function collectGivenRefs(value, into) {
14882
+ if (Array.isArray(value)) {
14883
+ for (const item of value)
14884
+ collectGivenRefs(item, into);
14885
+ return;
14886
+ }
14887
+ if (value === null || typeof value !== "object")
14888
+ return;
14889
+ const node = value;
14890
+ if (node.node === "given" && typeof node.refName === "string") {
14891
+ into.add(node.refName);
14892
+ }
14893
+ for (const child of Object.values(node))
14894
+ collectGivenRefs(child, into);
14895
+ }
14896
+ function suggestGivenLookup(modelDef, authorizeBySource, surfaced) {
14897
+ const registry = modelDef.givens ?? {};
14898
+ const bySource = new Map;
14899
+ const byQuery = new Map;
14900
+ for (const obj of Object.values(modelDef.contents)) {
14901
+ if (isSourceDef5(obj)) {
14902
+ const name = obj.as || obj.name;
14903
+ const refs = new Set;
14904
+ collectGivenRefs(obj.filterList, refs);
14905
+ for (const expr of authorizeBySource(name) ?? []) {
14906
+ for (const given of referencedGivenNames(expr))
14907
+ refs.add(given);
14908
+ }
14909
+ bySource.set(name, Array.from(refs));
14910
+ } else if (obj.type === "query") {
14911
+ const query = obj;
14912
+ byQuery.set(query.as || query.name, {
14913
+ own: (query.givenUsage ?? []).map((usage) => registry[usage.id]?.name).filter((n) => n !== undefined),
14914
+ source: typeof query.structRef === "string" ? query.structRef : undefined
14915
+ });
14916
+ }
14917
+ }
14918
+ const narrow = (names) => Array.from(new Set(names)).filter((name) => surfaced === undefined || surfaced.has(name));
14919
+ return {
14920
+ forSource: (name) => {
14921
+ const found = bySource.get(name);
14922
+ return found && narrow(found);
14923
+ },
14924
+ forQuery: (name) => {
14925
+ const found = byQuery.get(name);
14926
+ if (!found)
14927
+ return;
14928
+ return narrow([
14929
+ ...found.own,
14930
+ ...found.source ? bySource.get(found.source) ?? [] : []
14931
+ ]);
14932
+ }
14933
+ };
14934
+ }
14935
+ function suggestGivenNames(suggest, lookup) {
14936
+ const names = suggest.query !== undefined ? lookup.forQuery(suggest.query) : suggest.source !== undefined ? lookup.forSource(suggest.source) : undefined;
14937
+ return names && names.length > 0 ? names : undefined;
14938
+ }
14939
+ function attachSuggestGivenNames(givens, lookup) {
14940
+ for (const given of givens ?? []) {
14941
+ if (!given.suggest)
14942
+ continue;
14943
+ const names = suggestGivenNames(given.suggest, lookup);
14944
+ if (names)
14945
+ given.suggest.givenNames = names;
14946
+ else
14947
+ delete given.suggest.givenNames;
14948
+ }
14949
+ }
14857
14950
  var init_given = __esm(() => {
14858
14951
  init_annotations();
14952
+ init_authorize();
14859
14953
  init_motly();
14860
14954
  });
14861
14955
 
@@ -14893,7 +14987,7 @@ init_gate_dimension();
14893
14987
  var import_recursive_readdir = __toESM(require_recursive_readdir(), 1);
14894
14988
  import {
14895
14989
  contextOverlay,
14896
- isSourceDef as isSourceDef5,
14990
+ isSourceDef as isSourceDef6,
14897
14991
  MalloyConfig,
14898
14992
  MalloyError as MalloyError2,
14899
14993
  modelDefToModelInfo,
@@ -15394,6 +15488,7 @@ async function compileMalloyModel(job, malloyConfig, modelPath) {
15394
15488
  authorizeOwnNotes,
15395
15489
  attributedAuthorizeOwnNotes
15396
15490
  } = extractSources(modelDef, givens);
15491
+ attachSuggestGivenNames(givens, suggestGivenLookup(modelDef, (name) => sources.find((source) => source.name === name)?.authorize, new Set((givens ?? []).map((given) => given.name))));
15397
15492
  const queryResult = extractQueries(modelDef);
15398
15493
  const queries = queryResult.queries;
15399
15494
  assertPartitionAnnotationsValid(modelDef);
@@ -15413,7 +15508,7 @@ async function compileMalloyModel(job, malloyConfig, modelPath) {
15413
15508
  onRowLevelGateUnexpressible: authorizeWarningCollection.onRowLevelGateUnexpressible,
15414
15509
  onOwnRowLevelConditionCompiled: (sourceName, condition) => {
15415
15510
  const struct = modelDef.contents[sourceName];
15416
- if (!struct || !isSourceDef5(struct))
15511
+ if (!struct || !isSourceDef6(struct))
15417
15512
  return;
15418
15513
  validateSourceLineGateGivenUsage(sourceName, struct, condition.refSummary, condition.e, modelDef, (cause, detail) => {
15419
15514
  recordRowLevelGateRejected(cause);
@@ -15532,6 +15627,7 @@ async function compileNotebookModel(job, malloyConfig, modelPath) {
15532
15627
  finalSourceInfos = collected.sourceInfos;
15533
15628
  const extracted = extractSources(finalModelDef, finalGivens);
15534
15629
  finalSources = extracted.sources;
15630
+ attachSuggestGivenNames(finalGivens, suggestGivenLookup(finalModelDef, (name) => extracted.sources.find((source) => source.name === name)?.authorize, new Set((finalGivens ?? []).map((given) => given.name))));
15535
15631
  finalFilterMap = extracted.filterMap;
15536
15632
  const finalQueryResult = extractQueries(finalModelDef);
15537
15633
  finalQueries = finalQueryResult.queries;
@@ -15552,7 +15648,7 @@ async function compileNotebookModel(job, malloyConfig, modelPath) {
15552
15648
  onRowLevelGateUnexpressible: authorizeWarningCollection.onRowLevelGateUnexpressible,
15553
15649
  onOwnRowLevelConditionCompiled: (sourceName, condition) => {
15554
15650
  const struct = finalCompiledModelDef.contents[sourceName];
15555
- if (!struct || !isSourceDef5(struct))
15651
+ if (!struct || !isSourceDef6(struct))
15556
15652
  return;
15557
15653
  validateSourceLineGateGivenUsage(sourceName, struct, condition.refSummary, condition.e, finalCompiledModelDef, (cause, detail) => {
15558
15654
  recordRowLevelGateRejected(cause);