@google-cloud/functions-framework
Advanced tools
Comparing version 3.3.0 to 3.4.0
@@ -20,5 +20,5 @@ import * as express from 'express'; | ||
* | ||
* {@link https://github.com/cloudevents/spec/blob/master/http-protocol-binding.md#3-http-message-mapping} | ||
* {@link https://github.com/cloudevents/spec/blob/main/http-protocol-binding.md#3-http-message-mapping} | ||
* | ||
* @param req - Express request object. | ||
* @param req - Express request object | ||
* @return True if the request is a CloudEvents event in binary content mode, | ||
@@ -32,6 +32,6 @@ * false otherwise. | ||
* | ||
* @param req Express request object. | ||
* @return CloudEvents context. | ||
* @param req - Express request object | ||
* @return CloudEvents context | ||
*/ | ||
export declare function getBinaryCloudEventContext(req: express.Request): CloudEvent<unknown>; | ||
//# sourceMappingURL=cloud_events.d.ts.map |
@@ -36,5 +36,5 @@ "use strict"; | ||
* | ||
* {@link https://github.com/cloudevents/spec/blob/master/http-protocol-binding.md#3-http-message-mapping} | ||
* {@link https://github.com/cloudevents/spec/blob/main/http-protocol-binding.md#3-http-message-mapping} | ||
* | ||
* @param req - Express request object. | ||
* @param req - Express request object | ||
* @return True if the request is a CloudEvents event in binary content mode, | ||
@@ -54,4 +54,4 @@ * false otherwise. | ||
* | ||
* @param req Express request object. | ||
* @return CloudEvents context. | ||
* @param req - Express request object | ||
* @return CloudEvents context | ||
*/ | ||
@@ -58,0 +58,0 @@ function getBinaryCloudEventContext(req) { |
@@ -13,3 +13,3 @@ import { HttpFunction, CloudEventFunction, HandlerFunction, TypedFunction } from './functions'; | ||
* - must end with a letter or number | ||
* @param functionName the function name | ||
* @param functionName - The function name | ||
* @returns true if the function name is valid | ||
@@ -20,5 +20,5 @@ */ | ||
* Get a declaratively registered function | ||
* @param functionName the name with which the function was registered | ||
* @returns the registered function and signature type or undefined no function matching | ||
* the provided name has been registered. | ||
* @param functionName - The name with which the function was registered | ||
* @returns The registered function and signature type or undefined no function matching | ||
* the provided name has been registered | ||
*/ | ||
@@ -28,4 +28,4 @@ export declare const getRegisteredFunction: (functionName: string) => RegisteredFunction<any, any> | undefined; | ||
* Register a function that responds to HTTP requests. | ||
* @param functionName - the name of the function | ||
* @param handler - the function to invoke when handling HTTP requests | ||
* @param functionName - The name of the function | ||
* @param handler - The function to invoke when handling HTTP requests | ||
* @public | ||
@@ -36,4 +36,4 @@ */ | ||
* Register a function that handles CloudEvents. | ||
* @param functionName - the name of the function | ||
* @param handler - the function to trigger when handling CloudEvents | ||
* @param functionName - The name of the function | ||
* @param handler - The function to trigger when handling CloudEvents | ||
* @public | ||
@@ -44,4 +44,5 @@ */ | ||
* Register a function that handles strongly typed invocations. | ||
* @param functionName - the name of the function | ||
* @param handler - the function to trigger | ||
* @param functionName - The name of the function | ||
* @param handler - The function to trigger | ||
* @internal | ||
*/ | ||
@@ -48,0 +49,0 @@ export declare const typed: <T, U>(functionName: string, handler: TypedFunction<T, U> | ((req: T) => U | Promise<U>)) => void; |
@@ -41,3 +41,3 @@ "use strict"; | ||
* - must end with a letter or number | ||
* @param functionName the function name | ||
* @param functionName - The function name | ||
* @returns true if the function name is valid | ||
@@ -53,5 +53,5 @@ */ | ||
* Get a declaratively registered function | ||
* @param functionName the name with which the function was registered | ||
* @returns the registered function and signature type or undefined no function matching | ||
* the provided name has been registered. | ||
* @param functionName - The name with which the function was registered | ||
* @returns The registered function and signature type or undefined no function matching | ||
* the provided name has been registered | ||
*/ | ||
@@ -66,4 +66,4 @@ const getRegisteredFunction = (functionName | ||
* Register a function that responds to HTTP requests. | ||
* @param functionName - the name of the function | ||
* @param handler - the function to invoke when handling HTTP requests | ||
* @param functionName - The name of the function | ||
* @param handler - The function to invoke when handling HTTP requests | ||
* @public | ||
@@ -77,4 +77,4 @@ */ | ||
* Register a function that handles CloudEvents. | ||
* @param functionName - the name of the function | ||
* @param handler - the function to trigger when handling CloudEvents | ||
* @param functionName - The name of the function | ||
* @param handler - The function to trigger when handling CloudEvents | ||
* @public | ||
@@ -88,4 +88,5 @@ */ | ||
* Register a function that handles strongly typed invocations. | ||
* @param functionName - the name of the function | ||
* @param handler - the function to trigger | ||
* @param functionName - The name of the function | ||
* @param handler - The function to trigger | ||
* @internal | ||
*/ | ||
@@ -92,0 +93,0 @@ const typed = (functionName, handler) => { |
@@ -24,6 +24,7 @@ "use strict"; | ||
* Get a completion handler that can be used to signal completion of an event function. | ||
* @param res the response object of the request the completion handler is for. | ||
* @returns an OnDoneCallback for the provided request. | ||
* @param res - The response object of the request the completion handler is for | ||
* @returns An OnDoneCallback for the provided request. | ||
*/ | ||
const getOnDoneCallback = (res) => { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
return process.domain.bind((err, result) => { | ||
@@ -41,4 +42,4 @@ if (res.locals.functionExecutionFinished) { | ||
* Helper function to parse a CloudEvent object from an HTTP request. | ||
* @param req an Express HTTP request | ||
* @returns a CloudEvent parsed from the request | ||
* @param req - An Express HTTP request | ||
* @returns A CloudEvent parsed from the request | ||
*/ | ||
@@ -60,4 +61,4 @@ const parseCloudEventRequest = (req) => { | ||
* request. | ||
* @param req an Express HTTP request | ||
* @returns the data playload and event context parsed from the request | ||
* @param req - An Express HTTP request | ||
* @returns The data playload and event context parsed from the request | ||
*/ | ||
@@ -83,4 +84,4 @@ const parseBackgroundEvent = (req) => { | ||
* instrumentation logic. | ||
* @param execute Runs user's function. | ||
* @return An Express handler function. | ||
* @param execute - Runs user's function | ||
* @return An Express handler function | ||
*/ | ||
@@ -114,4 +115,4 @@ const wrapHttpFunction = (execute) => { | ||
* Wraps an async CloudEvent function in an express RequestHandler. | ||
* @param userFunction User's function. | ||
* @return An Express hander function that invokes the user function. | ||
* @param userFunction - User's function | ||
* @return An Express hander function that invokes the user function | ||
*/ | ||
@@ -130,4 +131,4 @@ const wrapCloudEventFunction = (userFunction) => { | ||
* Wraps callback style CloudEvent function in an express RequestHandler. | ||
* @param userFunction User's function. | ||
* @return An Express hander function that invokes the user function. | ||
* @param userFunction - User's function | ||
* @return An Express hander function that invokes the user function | ||
*/ | ||
@@ -144,4 +145,4 @@ const wrapCloudEventFunctionWithCallback = (userFunction) => { | ||
* Wraps an async event function in an express RequestHandler. | ||
* @param userFunction User's function. | ||
* @return An Express hander function that invokes the user function. | ||
* @param userFunction - User's function | ||
* @return An Express hander function that invokes the user function | ||
*/ | ||
@@ -160,4 +161,4 @@ const wrapEventFunction = (userFunction) => { | ||
* Wraps a callback style event function in an express RequestHandler. | ||
* @param userFunction User's function. | ||
* @return An Express hander function that invokes the user function. | ||
* @param userFunction - User's function | ||
* @return An Express hander function that invokes the user function | ||
*/ | ||
@@ -174,3 +175,3 @@ const wrapEventFunctionWithCallback = (userFunction) => { | ||
* Wraps a typed function in an express style RequestHandler. | ||
* @param userFunction User's function | ||
* @param userFunction - User's function | ||
* @return An Express handler function that invokes the user function | ||
@@ -177,0 +178,0 @@ */ |
@@ -16,2 +16,18 @@ /// <reference types="node" /> | ||
rawBody?: Buffer; | ||
/** | ||
* Request-specified execution ID. | ||
*/ | ||
executionId?: string; | ||
/** | ||
* Cloud Trace trace ID. | ||
*/ | ||
traceId?: string; | ||
/** | ||
* Cloud Trace span ID. | ||
*/ | ||
spanId?: string; | ||
/** | ||
* An AbortController used to signal cancellation of a function invocation (e.g. in case of time out). | ||
*/ | ||
abortController?: AbortController; | ||
} | ||
@@ -154,3 +170,3 @@ /** | ||
* | ||
* @param request the request body as raw bytes | ||
* @param request - The request body as raw bytes | ||
*/ | ||
@@ -161,4 +177,4 @@ deserializeRequest(request: InvocationRequest): T | Promise<T>; | ||
* | ||
* @param responseWriter interface for writing to the invocation result | ||
* @param response the response object | ||
* @param responseWriter - Interface for writing to the invocation result | ||
* @param response - The response object | ||
*/ | ||
@@ -165,0 +181,0 @@ serializeResponse(responseWriter: InvocationResponse, response: U): void | Promise<void>; |
@@ -7,5 +7,5 @@ /// <reference types="node" /> | ||
* Sends back a response to the incoming request. | ||
* @param result Output from function execution. | ||
* @param err Error from function execution. | ||
* @param res Express response object. | ||
* @param result - Output from function execution | ||
* @param err - Error from function execution | ||
* @param res - Express response object | ||
*/ | ||
@@ -15,3 +15,3 @@ export declare function sendResponse(result: any, err: Error | null, res: express.Response): void; | ||
* Enables registration of error handlers. | ||
* @param server HTTP server which invokes user's function. | ||
* @param server - HTTP server which invokes user's function | ||
* @constructor | ||
@@ -18,0 +18,0 @@ */ |
@@ -29,5 +29,5 @@ "use strict"; | ||
* Sends back a response to the incoming request. | ||
* @param result Output from function execution. | ||
* @param err Error from function execution. | ||
* @param res Express response object. | ||
* @param result - Output from function execution | ||
* @param err - Error from function execution | ||
* @param res - Express response object | ||
*/ | ||
@@ -71,3 +71,3 @@ function sendResponse( | ||
* Enables registration of error handlers. | ||
* @param server HTTP server which invokes user's function. | ||
* @param server - HTTP server which invokes user's function | ||
* @constructor | ||
@@ -92,3 +92,6 @@ */ | ||
}); | ||
process.on('exit', code => { | ||
process.on('exit', (code) => { | ||
if (typeof code === 'string') { | ||
code = parseInt(code); | ||
} | ||
(0, logger_1.sendCrashResponse)({ | ||
@@ -95,0 +98,0 @@ err: new Error(`Process exited with code ${code}`), |
@@ -149,3 +149,3 @@ "use strict"; | ||
* Returns null if the module can not be identified. | ||
* @param codeLocation Directory with user's code. | ||
* @param codeLocation - Directory with user's code | ||
* @return Resolved path or null. | ||
@@ -152,0 +152,0 @@ */ |
@@ -0,8 +1,12 @@ | ||
/// <reference types="node" /> | ||
import * as express from 'express'; | ||
export declare const EXECUTION_CONTEXT_LABELS_KEY = "logging.googleapis.com/labels"; | ||
export declare const EXECUTION_CONTEXT_TRACE_KEY = "logging.googleapis.com/trace"; | ||
export declare const EXECUTION_CONTEXT_SPAN_ID_KEY = "logging.googleapis.com/spanId"; | ||
/** | ||
* Logs an error message and sends back an error response to the incoming | ||
* request. | ||
* @param err Error to be logged and sent. | ||
* @param res Express response object. | ||
* @param callback A function to be called synchronously. | ||
* @param err - Error to be logged and sent | ||
* @param res - Express response object | ||
* @param callback - A function to be called synchronously | ||
*/ | ||
@@ -17,2 +21,9 @@ export declare function sendCrashResponse({ err, res, callback, silent, statusHeader, statusOverride, }: { | ||
}): void; | ||
export declare function loggingHandlerAddExecutionContext(): void; | ||
export declare const errorHandler: (err: Error | any, req: express.Request, res: express.Response, next: express.NextFunction) => void; | ||
export declare function splitArgs(args: any[]): { | ||
encoding: BufferEncoding | undefined; | ||
cb: any; | ||
}; | ||
export declare function getModifiedData(data: Uint8Array | string, encoding?: BufferEncoding, stderr?: boolean): string | Uint8Array; | ||
//# sourceMappingURL=logger.d.ts.map |
@@ -16,10 +16,16 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.sendCrashResponse = void 0; | ||
exports.getModifiedData = exports.splitArgs = exports.errorHandler = exports.loggingHandlerAddExecutionContext = exports.sendCrashResponse = exports.EXECUTION_CONTEXT_SPAN_ID_KEY = exports.EXECUTION_CONTEXT_TRACE_KEY = exports.EXECUTION_CONTEXT_LABELS_KEY = void 0; | ||
const types_1 = require("./types"); | ||
const async_local_storage_1 = require("./async_local_storage"); | ||
const buffer_1 = require("buffer"); | ||
exports.EXECUTION_CONTEXT_LABELS_KEY = 'logging.googleapis.com/labels'; | ||
exports.EXECUTION_CONTEXT_TRACE_KEY = 'logging.googleapis.com/trace'; | ||
exports.EXECUTION_CONTEXT_SPAN_ID_KEY = 'logging.googleapis.com/spanId'; | ||
const SEVERITY = 'severity'; | ||
/** | ||
* Logs an error message and sends back an error response to the incoming | ||
* request. | ||
* @param err Error to be logged and sent. | ||
* @param res Express response object. | ||
* @param callback A function to be called synchronously. | ||
* @param err - Error to be logged and sent | ||
* @param res - Express response object | ||
* @param callback - A function to be called synchronously | ||
*/ | ||
@@ -49,2 +55,103 @@ function sendCrashResponse({ err, res, callback, silent = false, statusHeader = 'crash', statusOverride = 500, }) { | ||
exports.sendCrashResponse = sendCrashResponse; | ||
function loggingHandlerAddExecutionContext() { | ||
interceptStdoutWrite(); | ||
interceptStderrWrite(); | ||
} | ||
exports.loggingHandlerAddExecutionContext = loggingHandlerAddExecutionContext; | ||
function interceptStdoutWrite() { | ||
const originalStdoutWrite = process.stdout.write; | ||
process.stdout.write = (data, ...args) => { | ||
const { encoding, cb } = splitArgs(args); | ||
const modifiedData = getModifiedData(data, encoding); | ||
return originalStdoutWrite.apply(process.stdout, [modifiedData, cb]); | ||
}; | ||
} | ||
function interceptStderrWrite() { | ||
const originalStderrWrite = process.stderr.write; | ||
process.stderr.write = (data, ...args) => { | ||
const { encoding, cb } = splitArgs(args); | ||
const modifiedData = getModifiedData(data, encoding, true); | ||
return originalStderrWrite.apply(process.stderr, [modifiedData, cb]); | ||
}; | ||
} | ||
const errorHandler = (err, req, res, next) => { | ||
interceptStderrWrite(); | ||
res.status(500); | ||
res.render('error', { error: err }); | ||
}; | ||
exports.errorHandler = errorHandler; | ||
function splitArgs(args) { | ||
let encoding, cb; | ||
if (args.length > 0 && | ||
(buffer_1.Buffer.isEncoding(args[0]) || typeof args[0] === 'undefined')) { | ||
encoding = args[0]; | ||
args.shift(); | ||
} | ||
if (args.length > 0 && typeof args[0] === 'function') { | ||
cb = args[0]; | ||
} | ||
return { encoding: encoding, cb: cb }; | ||
} | ||
exports.splitArgs = splitArgs; | ||
function getModifiedData(data, encoding, stderr = false) { | ||
const currentContext = (0, async_local_storage_1.getCurrentContext)(); | ||
if (!currentContext) { | ||
return data; | ||
} | ||
const { isJSON, processedData } = processData(data, encoding); | ||
let dataWithContext; | ||
if (isJSON) { | ||
dataWithContext = getJSONWithContext(processedData, currentContext); | ||
} | ||
else { | ||
dataWithContext = getTextWithContext(processedData, currentContext); | ||
} | ||
if (stderr) { | ||
dataWithContext[SEVERITY] = 'ERROR'; | ||
} | ||
return JSON.stringify(dataWithContext) + '\n'; | ||
} | ||
exports.getModifiedData = getModifiedData; | ||
function getTextWithContext(data, context) { | ||
return { | ||
message: data, | ||
[exports.EXECUTION_CONTEXT_LABELS_KEY]: { execution_id: context.executionId }, | ||
[exports.EXECUTION_CONTEXT_TRACE_KEY]: context.traceId, | ||
[exports.EXECUTION_CONTEXT_SPAN_ID_KEY]: context.spanId, | ||
}; | ||
} | ||
function getJSONWithContext(json, context) { | ||
if (exports.EXECUTION_CONTEXT_LABELS_KEY in json) { | ||
json[exports.EXECUTION_CONTEXT_LABELS_KEY]['execution_id'] = context.executionId; | ||
} | ||
else { | ||
json[exports.EXECUTION_CONTEXT_LABELS_KEY] = { execution_id: context.executionId }; | ||
} | ||
return { | ||
...json, | ||
[exports.EXECUTION_CONTEXT_TRACE_KEY]: context.traceId, | ||
[exports.EXECUTION_CONTEXT_SPAN_ID_KEY]: context.spanId, | ||
}; | ||
} | ||
function processData(data, encoding) { | ||
let decodedData; | ||
try { | ||
if (data instanceof Uint8Array) { | ||
decodedData = buffer_1.Buffer.from(data.buffer).toString(); | ||
} | ||
else { | ||
decodedData = buffer_1.Buffer.from(data, encoding).toString(); | ||
} | ||
} | ||
catch (e) { | ||
// Failed to decode, treat it as simple text. | ||
return { isJSON: false, processedData: data }; | ||
} | ||
try { | ||
return { isJSON: true, processedData: JSON.parse(decodedData) }; | ||
} | ||
catch (e) { | ||
return { isJSON: false, processedData: decodedData }; | ||
} | ||
} | ||
//# sourceMappingURL=logger.js.map |
@@ -24,2 +24,3 @@ #!/usr/bin/env node | ||
const options_1 = require("./options"); | ||
const logger_1 = require("./logger"); | ||
/** | ||
@@ -36,2 +37,5 @@ * Main entrypoint for the functions framework that loads the user's function | ||
} | ||
if (options.enableExecutionId) { | ||
(0, logger_1.loggingHandlerAddExecutionContext)(); | ||
} | ||
const loadedFunction = await (0, loader_1.getUserFunction)(options.sourceLocation, options.target, options.signatureType); | ||
@@ -44,3 +48,6 @@ if (!loadedFunction) { | ||
const { userFunction, signatureType } = loadedFunction; | ||
const server = (0, server_1.getServer)(userFunction, signatureType); | ||
// It is possible to overwrite the configured signature type in code so we | ||
// reset it here based on what we loaded. | ||
options.signatureType = signatureType; | ||
const server = (0, server_1.getServer)(userFunction, options); | ||
const errorHandler = new invoker_1.ErrorHandler(server); | ||
@@ -47,0 +54,0 @@ server |
@@ -13,4 +13,4 @@ import { Request, Response, NextFunction } from 'express'; | ||
* Splits a background event's resource into a CloudEvent service, resource, and subject. | ||
* @param context the GCF event context to parse. | ||
* @returns the CloudEvent service, resource and subject fields for the given GCF event context. | ||
* @param context - The GCF event context to parse | ||
* @returns The CloudEvent service, resource and subject fields for the given GCF event context | ||
*/ | ||
@@ -21,5 +21,5 @@ export declare const splitResource: (context: CloudFunctionsContext) => ParsedResource; | ||
* using the "cloudevent" signature type to accept requests from a background event producer. | ||
* @param req express request object | ||
* @param res express response object | ||
* @param next function used to pass control to the next middleware function in the stack | ||
* @param req - Express request object | ||
* @param res - Express response object | ||
* @param next - Function used to pass control to the next middleware function in the stack | ||
*/ | ||
@@ -26,0 +26,0 @@ export declare const backgroundEventToCloudEventMiddleware: (req: Request, res: Response, next: NextFunction) => void; |
@@ -41,4 +41,4 @@ "use strict"; | ||
* Is this request a known GCF event that can be converted to a cloud event. | ||
* @param req the express request object | ||
* @returns true if this request can be converted to a CloudEvent | ||
* @param req - The express request object | ||
* @returns True if this request can be converted to a CloudEvent | ||
*/ | ||
@@ -56,4 +56,4 @@ const isConvertableBackgroundEvent = (req) => { | ||
* Convert the given HTTP request into the GCF Background Event data / context format. | ||
* @param body the express request object | ||
* @returns a marshalled background event | ||
* @param body - The express request object | ||
* @returns A marshalled background event | ||
*/ | ||
@@ -72,4 +72,4 @@ const getBackgroundEvent = (request) => { | ||
* Splits a background event's resource into a CloudEvent service, resource, and subject. | ||
* @param context the GCF event context to parse. | ||
* @returns the CloudEvent service, resource and subject fields for the given GCF event context. | ||
* @param context - The GCF event context to parse | ||
* @returns The CloudEvent service, resource and subject fields for the given GCF event context | ||
*/ | ||
@@ -120,5 +120,5 @@ const splitResource = (context) => { | ||
* using the "cloudevent" signature type to accept requests from a background event producer. | ||
* @param req express request object | ||
* @param res express response object | ||
* @param next function used to pass control to the next middleware function in the stack | ||
* @param req - Express request object | ||
* @param res - Express response object | ||
* @param next - Function used to pass control to the next middleware function in the stack | ||
*/ | ||
@@ -125,0 +125,0 @@ const backgroundEventToCloudEventMiddleware = (req, res, next) => { |
@@ -7,4 +7,4 @@ import { Request, Response, NextFunction } from 'express'; | ||
* Splits a CloudEvent source string into resource and subject components. | ||
* @param source the cloud event source | ||
* @returns the parsed service and name components of the CE source string | ||
* @param source - The cloud event source | ||
* @returns The parsed service and name components of the CE source string | ||
*/ | ||
@@ -18,7 +18,7 @@ export declare const parseSource: (source: string) => { | ||
* functions using the "EVENT" signature type to accept requests from a cloud event producer. | ||
* @param req express request object | ||
* @param res express response object | ||
* @param next function used to pass control to the next middle middleware function in the stack | ||
* @param req - Express request object | ||
* @param res - Express response object | ||
* @param next - Function used to pass control to the next middle middleware function in the stack | ||
*/ | ||
export declare const cloudEventToBackgroundEventMiddleware: (req: Request, res: Response, next: NextFunction) => void; | ||
//# sourceMappingURL=cloud_event_to_background_event.d.ts.map |
@@ -31,4 +31,4 @@ "use strict"; | ||
* Is the given request a known CloudEvent that can be converted to a legacy event. | ||
* @param request express request object | ||
* @returns true if the request can be converted | ||
* @param request - Express request object | ||
* @returns True if the request can be converted | ||
*/ | ||
@@ -44,4 +44,4 @@ const isConvertableCloudEvent = (request) => { | ||
* Splits a CloudEvent source string into resource and subject components. | ||
* @param source the cloud event source | ||
* @returns the parsed service and name components of the CE source string | ||
* @param source - The cloud event source | ||
* @returns The parsed service and name components of the CE source string | ||
*/ | ||
@@ -61,4 +61,4 @@ const parseSource = (source) => { | ||
* Marshal a known GCP CloudEvent request the equivalent context/data legacy event format. | ||
* @param req express request object | ||
* @returns the request body of the equivalent legacy event request | ||
* @param req - Express request object | ||
* @returns The request body of the equivalent legacy event request | ||
*/ | ||
@@ -134,5 +134,5 @@ const marshalConvertableCloudEvent = (req) => { | ||
* functions using the "EVENT" signature type to accept requests from a cloud event producer. | ||
* @param req express request object | ||
* @param res express response object | ||
* @param next function used to pass control to the next middle middleware function in the stack | ||
* @param req - Express request object | ||
* @param res - Express response object | ||
* @param next - Function used to pass control to the next middle middleware function in the stack | ||
*/ | ||
@@ -139,0 +139,0 @@ const cloudEventToBackgroundEventMiddleware = (req, res, next) => { |
@@ -33,3 +33,12 @@ import { SignatureType } from './types'; | ||
printHelp: boolean; | ||
/** | ||
* Whether or not to enable execution id support. | ||
*/ | ||
enableExecutionId: boolean; | ||
/** | ||
* The request timeout. | ||
*/ | ||
timeoutMilliseconds: number; | ||
} | ||
export declare const requiredNodeJsVersionForLogExecutionID = "13.0.0"; | ||
export declare const helpText = "Example usage:\n functions-framework --target=helloWorld --port=8080\nDocumentation:\n https://github.com/GoogleCloudPlatform/functions-framework-nodejs"; | ||
@@ -39,7 +48,7 @@ /** | ||
* environment variables. | ||
* @param cliArgs the raw command line arguments | ||
* @param envVars the environment variables to parse options from | ||
* @returns the parsed options that should be used to configure the framework. | ||
* @param cliArgs - The raw command line arguments | ||
* @param envVars - The environment variables to parse options from | ||
* @returns The parsed options that should be used to configure the framework | ||
*/ | ||
export declare const parseOptions: (cliArgs?: string[], envVars?: NodeJS.ProcessEnv) => FrameworkOptions; | ||
//# sourceMappingURL=options.d.ts.map |
@@ -16,4 +16,5 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.parseOptions = exports.helpText = exports.OptionsError = void 0; | ||
exports.parseOptions = exports.helpText = exports.requiredNodeJsVersionForLogExecutionID = exports.OptionsError = void 0; | ||
const minimist = require("minimist"); | ||
const semver = require("semver"); | ||
const path_1 = require("path"); | ||
@@ -69,2 +70,22 @@ const types_1 = require("./types"); | ||
}); | ||
const TimeoutOption = new ConfigurableOption('timeout', 'CLOUD_RUN_TIMEOUT_SECONDS', 0, (x) => { | ||
if (typeof x === 'string') { | ||
x = parseInt(x, 10); | ||
} | ||
if (isNaN(x) || x < 0) { | ||
throw new OptionsError('Timeout must be a positive integer'); | ||
} | ||
return x * 1000; | ||
}); | ||
exports.requiredNodeJsVersionForLogExecutionID = '13.0.0'; | ||
const ExecutionIdOption = new ConfigurableOption('log-execution-id', 'LOG_EXECUTION_ID', false, x => { | ||
const nodeVersion = process.versions.node; | ||
const isVersionSatisfied = semver.gte(nodeVersion, exports.requiredNodeJsVersionForLogExecutionID); | ||
const isTrue = (typeof x === 'boolean' && x) || | ||
(typeof x === 'string' && x.toLowerCase() === 'true'); | ||
if (isTrue && !isVersionSatisfied) { | ||
throw new OptionsError(`Execution id is only supported with Node.js versions ${exports.requiredNodeJsVersionForLogExecutionID} and above. Your current version is ${nodeVersion}. Please upgrade.`); | ||
} | ||
return isTrue; | ||
}); | ||
exports.helpText = `Example usage: | ||
@@ -77,5 +98,5 @@ functions-framework --target=helloWorld --port=8080 | ||
* environment variables. | ||
* @param cliArgs the raw command line arguments | ||
* @param envVars the environment variables to parse options from | ||
* @returns the parsed options that should be used to configure the framework. | ||
* @param cliArgs - The raw command line arguments | ||
* @param envVars - The environment variables to parse options from | ||
* @returns The parsed options that should be used to configure the framework | ||
*/ | ||
@@ -89,2 +110,3 @@ const parseOptions = (cliArgs = process.argv, envVars = process.env) => { | ||
SourceLocationOption.cliOption, | ||
TimeoutOption.cliOption, | ||
], | ||
@@ -97,3 +119,5 @@ }); | ||
signatureType: SignatureOption.parse(argv, envVars), | ||
timeoutMilliseconds: TimeoutOption.parse(argv, envVars), | ||
printHelp: cliArgs[2] === '-h' || cliArgs[2] === '--help', | ||
enableExecutionId: ExecutionIdOption.parse(argv, envVars), | ||
}; | ||
@@ -100,0 +124,0 @@ }; |
@@ -78,5 +78,5 @@ import { Request, Response, NextFunction } from 'express'; | ||
* Pub/Sub subscription into the format that is expected downstream by wrapEventFunction | ||
* @param req express request object | ||
* @param res express response object | ||
* @param next function used to pass control to the next middle middleware function in the stack | ||
* @param req - Express request object | ||
* @param res - Express response object | ||
* @param next - Function used to pass control to the next middle middleware function in the stack | ||
*/ | ||
@@ -83,0 +83,0 @@ export declare const legacyPubSubEventMiddleware: (req: Request, res: Response, next: NextFunction) => void; |
@@ -10,3 +10,3 @@ "use strict"; | ||
* Type predicate that checks if a given Request is a RawPubSubRequest | ||
* @param request a Request object to typecheck | ||
* @param request - A Request object to typecheck | ||
* @returns true if this Request is a RawPubSubRequest | ||
@@ -25,3 +25,3 @@ */ | ||
* Extract the Pub/Sub topic name from the HTTP request path. | ||
* @param path the URL path of the http request | ||
* @param path - The URL path of the http request | ||
* @returns the Pub/Sub topic name if the path matches the expected format, | ||
@@ -41,4 +41,4 @@ * null otherwise | ||
* Marshal the body of an HTTP request from a Pub/Sub subscription | ||
* @param body an unmarshalled http request body from a Pub/Sub push subscription | ||
* @param path the HTTP request path | ||
* @param body - An unmarshalled http request body from a Pub/Sub push subscription | ||
* @param path - The HTTP request path | ||
* @returns the marshalled request body expected by wrapEventFunction | ||
@@ -66,5 +66,5 @@ */ | ||
* Pub/Sub subscription into the format that is expected downstream by wrapEventFunction | ||
* @param req express request object | ||
* @param res express response object | ||
* @param next function used to pass control to the next middle middleware function in the stack | ||
* @param req - Express request object | ||
* @param res - Express response object | ||
* @param next - Function used to pass control to the next middle middleware function in the stack | ||
*/ | ||
@@ -71,0 +71,0 @@ const legacyPubSubEventMiddleware = (req, res, next) => { |
/// <reference types="node" /> | ||
import * as http from 'http'; | ||
import { HandlerFunction } from './functions'; | ||
import { SignatureType } from './types'; | ||
import { FrameworkOptions } from './options'; | ||
/** | ||
* Creates and configures an Express application and returns an HTTP server | ||
* which will run it. | ||
* @param userFunction User's function. | ||
* @param functionSignatureType Type of user's function signature. | ||
* @return HTTP server. | ||
* @param userFunction - User's function | ||
* @param options - The configured Function Framework options | ||
* @return HTTP server | ||
*/ | ||
export declare function getServer(userFunction: HandlerFunction, functionSignatureType: SignatureType): http.Server; | ||
export declare function getServer(userFunction: HandlerFunction, options: FrameworkOptions): http.Server; | ||
//# sourceMappingURL=server.d.ts.map |
@@ -25,11 +25,15 @@ "use strict"; | ||
const background_event_to_cloud_event_1 = require("./middleware/background_event_to_cloud_event"); | ||
const timeout_1 = require("./middleware/timeout"); | ||
const function_wrappers_1 = require("./function_wrappers"); | ||
const async_local_storage_1 = require("./async_local_storage"); | ||
const execution_context_1 = require("./execution_context"); | ||
const logger_1 = require("./logger"); | ||
/** | ||
* Creates and configures an Express application and returns an HTTP server | ||
* which will run it. | ||
* @param userFunction User's function. | ||
* @param functionSignatureType Type of user's function signature. | ||
* @return HTTP server. | ||
* @param userFunction - User's function | ||
* @param options - The configured Function Framework options | ||
* @return HTTP server | ||
*/ | ||
function getServer(userFunction, functionSignatureType) { | ||
function getServer(userFunction, options) { | ||
// App to use for function executions. | ||
@@ -48,5 +52,5 @@ const app = express(); | ||
* function in body-parser options. | ||
* @param req Express request object. | ||
* @param res Express response object. | ||
* @param buf Buffer to be saved. | ||
* @param req - Express request object | ||
* @param res - Express response object | ||
* @param buf - Buffer to be saved | ||
*/ | ||
@@ -80,3 +84,3 @@ function rawBodySaver(req, res, buf) { | ||
// Apply middleware | ||
if (functionSignatureType !== 'typed') { | ||
if (options.signatureType !== 'typed') { | ||
// If the function is not typed then JSON parsing can be done automatically, otherwise the | ||
@@ -103,5 +107,9 @@ // functions format must determine deserialization. | ||
// Disable Express eTag response header | ||
app.disable('etag'); | ||
if (functionSignatureType === 'event' || | ||
functionSignatureType === 'cloudevent') { | ||
app.set('etag', false); | ||
// Get execution context. | ||
app.use(execution_context_1.executionContextMiddleware); | ||
// Store execution context to async local storge. | ||
app.use(async_local_storage_1.asyncLocalStorageMiddleware); | ||
if (options.signatureType === 'event' || | ||
options.signatureType === 'cloudevent') { | ||
// If a Pub/Sub subscription is configured to invoke a user's function directly, the request body | ||
@@ -112,9 +120,9 @@ // needs to be marshalled into the structure that wrapEventFunction expects. This unblocks local | ||
} | ||
if (functionSignatureType === 'event') { | ||
if (options.signatureType === 'event') { | ||
app.use(cloud_event_to_background_event_1.cloudEventToBackgroundEventMiddleware); | ||
} | ||
if (functionSignatureType === 'cloudevent') { | ||
if (options.signatureType === 'cloudevent') { | ||
app.use(background_event_to_cloud_event_1.backgroundEventToCloudEventMiddleware); | ||
} | ||
if (functionSignatureType === 'http') { | ||
if (options.signatureType === 'http') { | ||
app.use('/favicon.ico|/robots.txt', (req, res) => { | ||
@@ -132,5 +140,6 @@ // Neither crawlers nor browsers attempting to pull the icon find the body | ||
} | ||
app.use((0, timeout_1.timeoutMiddleware)(options.timeoutMilliseconds)); | ||
// Set up the routes for the user's function | ||
const requestHandler = (0, function_wrappers_1.wrapUserFunction)(userFunction, functionSignatureType); | ||
if (functionSignatureType === 'http') { | ||
const requestHandler = (0, function_wrappers_1.wrapUserFunction)(userFunction, options.signatureType); | ||
if (options.signatureType === 'http') { | ||
app.all('/*', requestHandler); | ||
@@ -141,2 +150,6 @@ } | ||
} | ||
// Error Handler | ||
if (options.enableExecutionId) { | ||
app.use(logger_1.errorHandler); | ||
} | ||
return http.createServer(app); | ||
@@ -143,0 +156,0 @@ } |
@@ -5,4 +5,4 @@ import { Server } from 'http'; | ||
* Testing utility for retrieving a function registered with the Functions Framework | ||
* @param functionName the name of the function to get | ||
* @returns a function that was registered with the Functions Framework | ||
* @param functionName - The name of the function to get | ||
* @returns A function that was registered with the Functions Framework | ||
* | ||
@@ -16,4 +16,4 @@ * @beta | ||
* using [supertest](https://www.npmjs.com/package/supertest). | ||
* @param functionName the name of the function to wrap in the test server | ||
* @returns a function that was registered with the Functions Framework | ||
* @param functionName - The name of the function to wrap in the test server | ||
* @returns A function that was registered with the Functions Framework | ||
* | ||
@@ -20,0 +20,0 @@ * @beta |
@@ -21,4 +21,4 @@ "use strict"; | ||
* Testing utility for retrieving a function registered with the Functions Framework | ||
* @param functionName the name of the function to get | ||
* @returns a function that was registered with the Functions Framework | ||
* @param functionName - The name of the function to get | ||
* @returns A function that was registered with the Functions Framework | ||
* | ||
@@ -36,4 +36,4 @@ * @beta | ||
* using [supertest](https://www.npmjs.com/package/supertest). | ||
* @param functionName the name of the function to wrap in the test server | ||
* @returns a function that was registered with the Functions Framework | ||
* @param functionName - The name of the function to wrap in the test server | ||
* @returns A function that was registered with the Functions Framework | ||
* | ||
@@ -47,5 +47,13 @@ * @beta | ||
} | ||
return (0, server_1.getServer)(registeredFunction.userFunction, registeredFunction.signatureType); | ||
return (0, server_1.getServer)(registeredFunction.userFunction, { | ||
signatureType: registeredFunction.signatureType, | ||
enableExecutionId: false, | ||
timeoutMilliseconds: 0, | ||
port: '0', | ||
target: '', | ||
sourceLocation: '', | ||
printHelp: false, | ||
}); | ||
}; | ||
exports.getTestServer = getTestServer; | ||
//# sourceMappingURL=testing.js.map |
@@ -9,9 +9,9 @@ export declare const FUNCTION_STATUS_HEADER_FIELD = "X-Google-Status"; | ||
*/ | ||
export type SignatureType = typeof SignatureType[number]; | ||
export type SignatureType = (typeof SignatureType)[number]; | ||
/** | ||
* Type guard to test if a provided value is valid SignatureType | ||
* @param x the value to test | ||
* @returns true if the provided value is a valid SignatureType | ||
* @param x - The value to test | ||
* @returns True if the provided value is a valid SignatureType | ||
*/ | ||
export declare const isValidSignatureType: (x: any) => x is "event" | "http" | "cloudevent" | "typed"; | ||
//# sourceMappingURL=types.d.ts.map |
@@ -26,4 +26,4 @@ "use strict"; | ||
* Type guard to test if a provided value is valid SignatureType | ||
* @param x the value to test | ||
* @returns true if the provided value is a valid SignatureType | ||
* @param x - The value to test | ||
* @returns True if the provided value is a valid SignatureType | ||
*/ | ||
@@ -30,0 +30,0 @@ // eslint-disable-next-line @typescript-eslint/no-explicit-any |
{ | ||
"name": "@google-cloud/functions-framework", | ||
"version": "3.3.0", | ||
"version": "3.4.0", | ||
"description": "FaaS (Function as a service) framework for writing portable Node.js functions", | ||
@@ -22,5 +22,5 @@ "engines": { | ||
"dependencies": { | ||
"@types/express": "4.17.17", | ||
"@types/express": "4.17.21", | ||
"body-parser": "^1.18.3", | ||
"cloudevents": "^7.0.0", | ||
"cloudevents": "^8.0.0", | ||
"express": "^4.16.4", | ||
@@ -56,18 +56,18 @@ "minimist": "^1.2.7", | ||
"devDependencies": { | ||
"@microsoft/api-extractor": "^7.18.20", | ||
"@types/body-parser": "1.19.2", | ||
"@types/minimist": "1.2.2", | ||
"@microsoft/api-extractor": "^7.43.1", | ||
"@types/body-parser": "1.19.5", | ||
"@types/minimist": "1.2.5", | ||
"@types/mocha": "9.1.1", | ||
"@types/node": "14.18.52", | ||
"@types/on-finished": "2.3.1", | ||
"@types/node": "^20.11.24", | ||
"@types/on-finished": "2.3.4", | ||
"@types/semver": "^7.3.6", | ||
"@types/sinon": "^10.0.0", | ||
"@types/supertest": "2.0.12", | ||
"gts": "3.1.1", | ||
"@types/supertest": "2.0.16", | ||
"gts": "5.3.0", | ||
"mocha": "9.2.2", | ||
"pack-n-play": "^1.0.0-2", | ||
"sinon": "^15.0.0", | ||
"supertest": "6.3.3", | ||
"supertest": "6.3.4", | ||
"typescript": "5.0.4" | ||
} | ||
} |
@@ -193,2 +193,3 @@ # Functions Framework for Node.js | ||
| `--source` | `FUNCTION_SOURCE` | The path to the directory of your function. Default: `cwd` (the current working directory) | | ||
| `--log-execution-id`| `LOG_EXECUTION_ID` | Enables execution IDs in logs, either `true` or `false`. When not specified, default to disable. Requires Node.js 13.0.0 or later. | | ||
@@ -256,7 +257,7 @@ You can set command-line flags in your `package.json` via the `start` script. | ||
[ff_node_unit_img]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/workflows/Node.js%20Unit%20CI/badge.svg | ||
[ff_node_unit_link]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/actions?query=workflow%3A"Node.js+Unit+CI" | ||
[ff_node_lint_img]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/workflows/Node.js%20Lint%20CI/badge.svg | ||
[ff_node_lint_link]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/actions?query=workflow%3A"Node.js+Lint+CI" | ||
[ff_node_conformance_img]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/workflows/Node.js%20Conformance%20CI/badge.svg | ||
[ff_node_conformance_link]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/actions?query=workflow%3A"Node.js+Conformance+CI" | ||
[ff_node_unit_img]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/actions/workflows/unit.yml/badge.svg | ||
[ff_node_unit_link]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/actions/workflows/unit.yml | ||
[ff_node_lint_img]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/actions/workflows/lint.yml/badge.svg | ||
[ff_node_lint_link]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/actions/workflows/lint.yml | ||
[ff_node_conformance_img]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/actions/workflows/conformance.yml/badge.svg | ||
[ff_node_conformance_link]: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/actions/workflows/conformance.yml |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
121650
41
2470
262
+ Added@types/express@4.17.21(transitive)
+ Addedcloudevents@8.0.2(transitive)
- Removed@types/express@4.17.17(transitive)
- Removedcloudevents@7.0.2(transitive)
Updated@types/express@4.17.21
Updatedcloudevents@^8.0.0