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,WAAY,IACL,EACH,MAAO,eAAe,uBACtB,IAAM,IAEF,MAAM,EAAoB,GAAiB,IACrC,EAAgB,IAAI,GACpB,EACN,OAAO,KAAK,gBAAgB,EAAkB,GAGtD,UAAW,IAAM,eAAe,yBAExC,EAgCJ,SAAS,2BAA2B,EAAS,GACzC,OAAO,IAAI,eAAe,EAAS,GAAwB,iBAC/D,CACA,QAAQ,UAAY,CAChB,8CACA","file":"/npm/@google-cloud/pino-logging-gcp-config@1.3.1/build/src/pino_gcp_config.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/@google-cloud/pino-logging-gcp-config@1.3.1/build/src/pino_gcp_config.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","\"use strict\";\n/**\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TEST_ONLY = void 0;\nexports.createGcpLoggingPinoConfig = createGcpLoggingPinoConfig;\n/**\n * @fileoverview Create a default LoggerConfig for pino structured logging.\n *\n * @see https://cloud.google.com/logging/docs/structured-logging\n */\nconst pino = require(\"pino\");\nconst eventid_1 = require(\"eventid\");\nconst logging_1 = require(\"@google-cloud/logging\");\nconst instrumentation_1 = require(\"@google-cloud/logging/build/src/utils/instrumentation\");\n/** Monotonically increasing ID for insertId. */\nconst eventId = new eventid_1.EventId();\n/*\n * Uses release-please annotations to update with latest version.\n * See\n * https://github.com/googleapis/release-please/blob/main/docs/customizing.md#updating-arbitrary-files\n */\nconst NODEJS_GCP_PINO_LIBRARY_VERSION = '1.3.1'; // {x-release-please-version}\nconst NODEJS_GCP_PINO_LIBRARY_NAME = 'nodejs-gcppino';\nconst PINO_TO_GCP_LOG_LEVELS = Object.freeze(Object.fromEntries([\n    ['trace', 'DEBUG'],\n    ['debug', 'DEBUG'],\n    ['info', 'INFO'],\n    ['warn', 'WARNING'],\n    ['error', 'ERROR'],\n    ['fatal', 'CRITICAL'],\n]));\n/**\n * Encapsulates configuration and methods for formatting pino logs for Google\n * Cloud Logging.\n */\nclass GcpLoggingPino {\n    constructor(options, pinoLoggerOptionsMixin) {\n        this.serviceContext = null;\n        this.traceGoogleCloudProjectId = null;\n        this.pendingInit = null;\n        if (options?.serviceContext) {\n            if (typeof options.serviceContext?.service !== 'string' ||\n                !options.serviceContext?.service?.length) {\n                throw new Error('options.serviceContext.service must be specified.');\n            }\n        }\n        this.pinoLoggerOptions = this.buidPinoLoggerOptions(pinoLoggerOptionsMixin);\n        const promises = this.initializeOptions(options);\n        if (!options?.inihibitDiagnosticMessage) {\n            if (promises.length > 0) {\n                // Some async actions pending, wait for them then log diagnostic.\n                const pinoDestinationStream = options?.pinoDestinationStream;\n                this.pendingInit = Promise.all(promises).then(() => {\n                    this.outputDiagnosticEntry(pinoDestinationStream);\n                });\n            }\n            else {\n                // no async options pending, directly log diagnostic.\n                this.outputDiagnosticEntry(options?.pinoDestinationStream);\n            }\n        }\n    }\n    /**\n     * Resolves and initializes the configuration options for the logger.\n     *\n     * This function sets up the `serviceContext` and `traceGoogleCloudProjectId`\n     * properties for the logger. It uses the provided options or attempts to\n     * auto-detect values from the environment if they are not specified.\n     *\n     * @param options Configuration options for GCP logging.\n     * @return an array of promises for async init actions.\n     */\n    initializeOptions(options) {\n        let auth = options?.auth;\n        const promises = [];\n        if (options?.serviceContext) {\n            this.serviceContext = { ...options.serviceContext };\n        }\n        else {\n            if (!auth) {\n                // Get default auth via logging library.\n                auth = new logging_1.Logging().auth;\n            }\n            promises.push(\n            // Use detectServiceContext to asynchronously return the ServiceContext\n            (0, logging_1.detectServiceContext)(auth).then(serviceContext => {\n                this.serviceContext = serviceContext;\n            }, () => { } // ignore any raised errors.\n            ));\n        }\n        if (options?.traceGoogleCloudProjectId !== undefined &&\n            options?.traceGoogleCloudProjectId !== null) {\n            if (options?.traceGoogleCloudProjectId.length > 0) {\n                // empty string keeps project ID as null\n                this.traceGoogleCloudProjectId = options.traceGoogleCloudProjectId;\n            }\n        }\n        else {\n            if (!auth) {\n                // Get default auth from logging library.\n                auth = new logging_1.Logging().auth;\n            }\n            promises.push(\n            // Using GoogleAuth to get the projectId from the environment.\n            auth.getProjectId().then(projectId => {\n                this.traceGoogleCloudProjectId = projectId;\n            }, () => { } // ignore any raised errors.\n            ));\n        }\n        return promises;\n    }\n    /**\n     * Outputs a single log line once per process containing the diagnostic info\n     * for this logger.\n     *\n     * Note that it is not possible for this package to perform API level logging\n     * with a line of the form cloud-solutions/pino-logging-gcp-config-v1.0.0\n     */\n    outputDiagnosticEntry(pinoDestinationStream) {\n        try {\n            const diagEntry = (0, instrumentation_1.createDiagnosticEntry)(NODEJS_GCP_PINO_LIBRARY_NAME, NODEJS_GCP_PINO_LIBRARY_VERSION);\n            diagEntry.data[instrumentation_1.DIAGNOSTIC_INFO_KEY].runtime = process.version;\n            const [entries, isInfoAdded] = (0, instrumentation_1.populateInstrumentationInfo)(diagEntry);\n            if (!isInfoAdded || entries.length === 0) {\n                return;\n            }\n            // Create a temp pino logger instance just to log this diagnostic entry.\n            pino\n                .pino({\n                ...this.pinoLoggerOptions,\n                level: 'info',\n            }, pinoDestinationStream)\n                .info({\n                ...diagEntry.data,\n            });\n        }\n        catch {\n            // ignore any errors.\n        }\n    }\n    /**\n     * Creates a JSON fragment string containing the timestamp in GCP logging\n     * format.\n     *\n     * @example ', \"timestamp\": { \"seconds\": 123456789, \"nanos\": 123000000 }'\n     *\n     * Creating a string with seconds/nanos is ~10x faster than formatting the\n     * timestamp as an ISO string.\n     *\n     * @see https://cloud.google.com/logging/docs/agent/logging/configuration#timestamp-processing\n     *\n     * As Javascript Date uses millisecond precision, in\n     * {@link formatLogObject} the logger adds a monotonically increasing insertId\n     * into the log object to preserve log order inside GCP logging.\n     *\n     * @see https://github.com/googleapis/nodejs-logging/blob/main/src/entry.ts#L189\n     */\n    static getGcpLoggingTimestamp() {\n        const seconds = Date.now() / 1000;\n        const secondsRounded = Math.floor(seconds);\n        // The following line is 2x as fast as seconds % 1000\n        // Uses Math.round, not Math.floor due to JS floating point...\n        // eg for a Date.now()=1713024754120\n        // (seconds-secondsRounded)*1000 => 119.99988555908203\n        const millis = Math.round((seconds - secondsRounded) * 1000);\n        if (millis !== 0) {\n            return `,\"timestamp\":{\"seconds\":${secondsRounded},\"nanos\":${millis}000000}`;\n        }\n        else {\n            return `,\"timestamp\":{\"seconds\":${secondsRounded},\"nanos\":0}`;\n        }\n    }\n    /**\n     * Converts pino log level to Google severity level.\n     *\n     * @see pino.LoggerOptions.formatters.level\n     */\n    static pinoLevelToGcpSeverity(pinoSeverityLabel, pinoSeverityLevel) {\n        const pinoLevel = pinoSeverityLabel;\n        const severity = PINO_TO_GCP_LOG_LEVELS[pinoLevel] ?? 'INFO';\n        return {\n            severity,\n            level: pinoSeverityLevel,\n        };\n    }\n    /**\n     * Reformats log entry record for GCP.\n     *\n     * * Adds OpenTelemetry properties with correct key.\n     * * Adds stack_trace if an Error is given in the err property.\n     * * Adds serviceContext\n     * * Adds sequential insertId to preserve logging order.\n     */\n    formatLogObject(input) {\n        // OpenTelemetry adds properties trace_id, span_id, trace_flags. If these\n        // are present, not null and not blank, convert them to the property keys\n        // specified by GCP logging.\n        //\n        // @see https://cloud.google.com/logging/docs/structured-logging#special-payload-fields\n        // @see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/data-model.md#trace-context-fields\n        const entry = { ...input };\n        if (entry.trace_id?.length) {\n            entry['logging.googleapis.com/trace'] = this.traceGoogleCloudProjectId\n                ? `projects/${this.traceGoogleCloudProjectId}/traces/${entry.trace_id}`\n                : entry.trace_id;\n            delete entry.trace_id;\n        }\n        if (entry.span_id?.length) {\n            entry['logging.googleapis.com/spanId'] = entry.span_id;\n            delete entry.span_id;\n        }\n        // Trace flags is a bit field even though there is one on defined bit,\n        // so lets convert it to an int and test against a bitmask.\n        // @see https://www.w3.org/TR/trace-context/#trace-flags\n        const trace_flags_bits = parseInt(entry.trace_flags);\n        if (!!trace_flags_bits && (trace_flags_bits & 0x1) === 1) {\n            entry['logging.googleapis.com/trace_sampled'] = true;\n        }\n        delete entry.trace_flags;\n        if (this.serviceContext) {\n            entry.serviceContext = this.serviceContext;\n        }\n        // If there is an Error, add the stack trace for Event Reporting.\n        if (entry.err instanceof Error && entry.err.stack) {\n            entry.stack_trace = entry.err.stack;\n        }\n        // Add a sequential EventID.\n        //\n        // This is required because Javascript Date has a very coarse granularity\n        // (millisecond), which makes it quite likely that multiple log entries\n        // would have the same timestamp.\n        //\n        // The GCP Logging API doesn't guarantee to preserve insertion order for\n        // entries with the same timestamp. The service does use `insertId` as a\n        // secondary ordering for entries with the same timestamp. `insertId` needs\n        // to be globally unique (within the project) however.\n        //\n        // We use a globally unique monotonically increasing EventId as the\n        // insertId.\n        //\n        // @see https://github.com/googleapis/nodejs-logging/blob/main/src/entry.ts#L189\n        entry['logging.googleapis.com/insertId'] = eventId.new();\n        return entry;\n    }\n    /**\n     * Creates a pino.LoggerOptions configured for GCP structured logging.\n     */\n    buidPinoLoggerOptions(pinoOptionsMixin) {\n        const formattersMixin = pinoOptionsMixin?.formatters;\n        return {\n            ...pinoOptionsMixin,\n            // Use 'message' instead of 'msg' as log entry message key.\n            messageKey: 'message',\n            formatters: {\n                ...formattersMixin,\n                level: GcpLoggingPino.pinoLevelToGcpSeverity,\n                log: (entry) => {\n                    // If a formattersMixin.log function is provided, call it first to allow user preprocessing\n                    const preprocessedEntry = formattersMixin?.log\n                        ? formattersMixin.log(entry)\n                        : entry;\n                    return this.formatLogObject(preprocessedEntry);\n                },\n            },\n            timestamp: () => GcpLoggingPino.getGcpLoggingTimestamp(),\n        };\n    }\n}\n/**\n * Creates a {@link pino.LoggerOptions} object which configures pino to output\n * JSON records compatible with\n * {@link https://cloud.google.com/logging/docs/structured-logging|Google Cloud structured Logging}.\n *\n * @param pinoLoggerOptionsMixin Additional Pino Logger settings that will be added to\n * the returned value.\n *\n * @throws {Error} If `serviceContext.service` is provided but is not a valid\n * string or is empty.\n *\n * @example\n *      const logger = pino.pino(\n *        createGcpLoggingPinoConfig(\n *          {\n *            serviceContext: {\n *              service: 'my-service',\n *              version: '1.2.3',\n *            },\n *          },\n *          {\n *            // Set Pino log level to 'debug'.\n *            level: 'debug',\n *          }\n *        )\n *      );\n *\n *      logger.info('hello world');\n *      logger.error(err, 'failure: ' + err);\n */\nfunction createGcpLoggingPinoConfig(options, pinoLoggerOptionsMixin) {\n    return new GcpLoggingPino(options, pinoLoggerOptionsMixin).pinoLoggerOptions;\n}\nexports.TEST_ONLY = {\n    PINO_TO_GCP_LOG_LEVELS,\n    GcpLoggingPino,\n};\n"]}