You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

@google-cloud/functions-framework

Package Overview
Dependencies
Maintainers
1
Versions
41
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@google-cloud/functions-framework - npm Package Compare versions

Comparing version

to
4.0.0

5

build/src/async_local_storage.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCurrentContext = exports.asyncLocalStorageMiddleware = void 0;
exports.asyncLocalStorageMiddleware = asyncLocalStorageMiddleware;
exports.getCurrentContext = getCurrentContext;
const semver = require("semver");

@@ -24,3 +25,2 @@ const options_1 = require("./options");

}
exports.asyncLocalStorageMiddleware = asyncLocalStorageMiddleware;
function getCurrentContext() {

@@ -32,3 +32,2 @@ if (!asyncLocalStorage) {

}
exports.getCurrentContext = getCurrentContext;
//# sourceMappingURL=async_local_storage.js.map

6

build/src/cloud_events.js

@@ -16,3 +16,5 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getBinaryCloudEventContext = exports.isBinaryCloudEvent = exports.CE_SERVICE = exports.EventConversionError = void 0;
exports.CE_SERVICE = exports.EventConversionError = void 0;
exports.isBinaryCloudEvent = isBinaryCloudEvent;
exports.getBinaryCloudEventContext = getBinaryCloudEventContext;
/**

@@ -49,3 +51,2 @@ * Custom exception class to represent errors durring event conversions.

}
exports.isBinaryCloudEvent = isBinaryCloudEvent;
/**

@@ -68,3 +69,2 @@ * Returns a CloudEvents context from the given CloudEvents request. Context

}
exports.getBinaryCloudEventContext = getBinaryCloudEventContext;
//# sourceMappingURL=cloud_events.js.map

@@ -21,3 +21,3 @@ "use strict";

const match = cloudTraceContext.match(TRACE_CONTEXT_PATTERN);
if (match === null || match === void 0 ? void 0 : match.groups) {
if (match?.groups) {
req.spanId = match.groups.spanId;

@@ -24,0 +24,0 @@ }

@@ -1,6 +0,6 @@

import { HttpFunction, CloudEventFunction, HandlerFunction, TypedFunction, CloudEventFunctionWithCallback } from './functions';
import { HttpFunction, CloudEventFunction, HandlerFunction, CloudEventFunctionWithCallback } from './functions';
import { SignatureType } from './types';
interface RegisteredFunction<T, U> {
interface RegisteredFunction<T> {
signatureType: SignatureType;
userFunction: HandlerFunction<T, U>;
userFunction: HandlerFunction<T>;
}

@@ -23,3 +23,3 @@ /**

*/
export declare const getRegisteredFunction: (functionName: string) => RegisteredFunction<any, any> | undefined;
export declare const getRegisteredFunction: (functionName: string) => RegisteredFunction<any> | undefined;
/**

@@ -39,10 +39,3 @@ * Register a function that responds to HTTP requests.

export declare const cloudEvent: <T = unknown>(functionName: string, handler: CloudEventFunction<T> | CloudEventFunctionWithCallback<T>) => void;
/**
* Register a function that handles strongly typed invocations.
* @param functionName - The name of the function
* @param handler - The function to trigger
* @internal
*/
export declare const typed: <T, U>(functionName: string, handler: TypedFunction<T, U> | ((req: T) => U | Promise<U>)) => void;
export {};
//# sourceMappingURL=function_registry.d.ts.map

@@ -16,4 +16,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.typed = exports.cloudEvent = exports.http = exports.getRegisteredFunction = exports.isValidFunctionName = void 0;
const functions_1 = require("./functions");
exports.cloudEvent = exports.http = exports.getRegisteredFunction = exports.isValidFunctionName = void 0;
/**

@@ -57,5 +56,3 @@ * Singleton map to hold the registered functions

*/
const getRegisteredFunction = (functionName
// eslint-disable-next-line @typescript-eslint/no-explicit-any
) => {
const getRegisteredFunction = (functionName) => {
return registrationContainer.get(functionName);

@@ -84,18 +81,2 @@ };

exports.cloudEvent = cloudEvent;
/**
* Register a function that handles strongly typed invocations.
* @param functionName - The name of the function
* @param handler - The function to trigger
* @internal
*/
const typed = (functionName, handler) => {
if (handler instanceof Function) {
handler = {
handler,
format: new functions_1.JsonInvocationFormat(),
};
}
register(functionName, 'typed', handler);
};
exports.typed = typed;
//# sourceMappingURL=function_registry.js.map

@@ -166,30 +166,2 @@ "use strict";

/**
* Wraps a typed function in an express style RequestHandler.
* @param userFunction - User's function
* @return An Express handler function that invokes the user function
*/
const wrapTypedFunction = (typedFunction) => {
const typedHandlerWrapper = async (req, res) => {
let reqTyped;
try {
reqTyped = typedFunction.format.deserializeRequest(new InvocationRequestImpl(req));
}
catch (err) {
(0, logger_1.sendCrashResponse)({
err,
res,
statusOverride: 400, // 400 Bad Request
});
return;
}
let resTyped = typedFunction.handler(reqTyped);
if (resTyped instanceof Promise) {
resTyped = await resTyped;
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
typedFunction.format.serializeResponse(new InvocationResponseImpl(res), resTyped);
};
return wrapHttpFunction(typedHandlerWrapper);
};
/**
* Wraps a user function with the provided signature type in an express

@@ -216,38 +188,5 @@ * RequestHandler.

return wrapCloudEventFunction(userFunction);
case 'typed':
return wrapTypedFunction(userFunction);
}
};
exports.wrapUserFunction = wrapUserFunction;
/**
* @private
*/
class InvocationRequestImpl {
constructor(req) {
this.req = req;
}
body() {
return this.req.body;
}
header(header) {
return this.req.header(header);
}
}
/**
* @private
*/
class InvocationResponseImpl {
constructor(res) {
this.res = res;
}
setHeader(key, value) {
this.res.set(key, value);
}
write(data) {
this.res.write(data);
}
end(data) {
this.res.end(data);
}
}
//# sourceMappingURL=function_wrappers.js.map

@@ -1,4 +0,1 @@

/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import { Request as ExpressRequest, Response } from 'express';

@@ -71,14 +68,6 @@ import { CloudEventV1 as CloudEvent } from 'cloudevents';

/**
* A Typed function handler that may return a value or a promise.
* @public
*/
export interface TypedFunction<T = unknown, U = unknown> {
handler: (req: T) => U | Promise<U>;
format: InvocationFormat<T, U>;
}
/**
* A function handler.
* @public
*/
export type HandlerFunction<T = unknown, U = unknown> = HttpFunction | EventFunction | EventFunctionWithCallback | CloudEventFunction<T> | CloudEventFunctionWithCallback<T> | TypedFunction<T, U>;
export type HandlerFunction<T = unknown> = HttpFunction | EventFunction | EventFunctionWithCallback | CloudEventFunction<T> | CloudEventFunctionWithCallback<T>;
/**

@@ -160,29 +149,2 @@ * A legacy event.

}
/**
* The contract for a request deserializer and response serializer.
* @public
*/
export interface InvocationFormat<T, U> {
/**
* Creates an instance of the request type from an invocation request.
*
* @param request - The request body as raw bytes
*/
deserializeRequest(request: InvocationRequest): T | Promise<T>;
/**
* Writes the response type to the invocation result.
*
* @param responseWriter - Interface for writing to the invocation result
* @param response - The response object
*/
serializeResponse(responseWriter: InvocationResponse, response: U): void | Promise<void>;
}
/**
* Default invocation format for JSON requests.
* @public
*/
export declare class JsonInvocationFormat<T, U> implements InvocationFormat<T, U> {
deserializeRequest(request: InvocationRequest): T;
serializeResponse(responseWriter: InvocationResponse, response: U): void;
}
//# sourceMappingURL=functions.d.ts.map

@@ -16,27 +16,2 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonInvocationFormat = void 0;
/**
* Default invocation format for JSON requests.
* @public
*/
class JsonInvocationFormat {
deserializeRequest(request) {
const body = request.body();
if (typeof body !== 'string') {
throw new Error('Unsupported Content-Type, expected application/json');
}
try {
return JSON.parse(body);
}
catch (e) {
throw new Error('Failed to parse malformatted JSON in request: ' +
e.message);
}
}
serializeResponse(responseWriter, response) {
responseWriter.setHeader('content-type', 'application/json');
responseWriter.end(JSON.stringify(response));
}
}
exports.JsonInvocationFormat = JsonInvocationFormat;
//# sourceMappingURL=functions.js.map

@@ -8,3 +8,3 @@ /**

*/
export { http, cloudEvent, typed } from './function_registry';
export { http, cloudEvent } from './function_registry';
//# sourceMappingURL=index.d.ts.map

@@ -30,3 +30,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.typed = exports.cloudEvent = exports.http = void 0;
exports.cloudEvent = exports.http = void 0;
/**

@@ -42,3 +42,2 @@ * @public

Object.defineProperty(exports, "cloudEvent", { enumerable: true, get: function () { return function_registry_1.cloudEvent; } });
Object.defineProperty(exports, "typed", { enumerable: true, get: function () { return function_registry_1.typed; } });
//# sourceMappingURL=index.js.map

@@ -1,2 +0,1 @@

/// <reference types="node" />
import * as express from 'express';

@@ -3,0 +2,0 @@ import * as http from 'http';

@@ -17,3 +17,4 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorHandler = exports.sendResponse = exports.setLatestRes = void 0;
exports.ErrorHandler = exports.setLatestRes = void 0;
exports.sendResponse = sendResponse;
const logger_1 = require("./logger");

@@ -66,3 +67,2 @@ /**

}
exports.sendResponse = sendResponse;
// Use an exit code which is unused by Node.js:

@@ -77,2 +77,3 @@ // https://nodejs.org/api/process.html#process_exit_codes

class ErrorHandler {
server;
constructor(server) {

@@ -79,0 +80,0 @@ this.server = server;

@@ -16,3 +16,4 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getUserFunction = exports.MIN_NODE_VERSION_ESMODULES = void 0;
exports.MIN_NODE_VERSION_ESMODULES = void 0;
exports.getUserFunction = getUserFunction;
// loader.ts

@@ -25,3 +26,2 @@ /**

const semver = require("semver");
const readPkgUp = require("read-pkg-up");
const url_1 = require("url");

@@ -57,3 +57,4 @@ const function_registry_1 = require("./function_registry");

}
const pkg = await readPkgUp({
const { readPackageUp } = await dynamicImport('read-package-up');
const pkg = await readPackageUp({
cwd: path.dirname(modulePath),

@@ -63,3 +64,3 @@ normalize: false,

// If package.json specifies type as 'module', it's an ES module.
return (pkg === null || pkg === void 0 ? void 0 : pkg.packageJson.type) === 'module';
return pkg?.packageJson.type === 'module';
}

@@ -72,5 +73,3 @@ /**

*/
const dynamicImport = new Function('modulePath', 'return import(modulePath)'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
);
const dynamicImport = new Function('modulePath', 'return import(modulePath)');
/**

@@ -150,3 +149,2 @@ * Returns user's function from function file.

}
exports.getUserFunction = getUserFunction;
/**

@@ -153,0 +151,0 @@ * Returns resolved path to the module containing the user function.

@@ -1,2 +0,1 @@

/// <reference types="node" />
import * as express from 'express';

@@ -25,3 +24,3 @@ export declare const EXECUTION_CONTEXT_LABELS_KEY = "logging.googleapis.com/labels";

};
export declare function getModifiedData(data: Uint8Array | string, encoding?: BufferEncoding, stderr?: boolean): string | Uint8Array;
export declare function getModifiedData(data: Uint8Array | string, encoding?: BufferEncoding, stderr?: boolean): string | Uint8Array<ArrayBufferLike>;
//# sourceMappingURL=logger.d.ts.map

@@ -16,3 +16,7 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getModifiedData = exports.splitArgs = exports.loggingHandlerAddExecutionContext = exports.sendCrashResponse = exports.EXECUTION_CONTEXT_SPAN_ID_KEY = exports.EXECUTION_CONTEXT_LABELS_KEY = void 0;
exports.EXECUTION_CONTEXT_SPAN_ID_KEY = exports.EXECUTION_CONTEXT_LABELS_KEY = void 0;
exports.sendCrashResponse = sendCrashResponse;
exports.loggingHandlerAddExecutionContext = loggingHandlerAddExecutionContext;
exports.splitArgs = splitArgs;
exports.getModifiedData = getModifiedData;
const types_1 = require("./types");

@@ -53,3 +57,2 @@ const async_local_storage_1 = require("./async_local_storage");

}
exports.sendCrashResponse = sendCrashResponse;
function loggingHandlerAddExecutionContext() {

@@ -59,3 +62,2 @@ interceptStdoutWrite();

}
exports.loggingHandlerAddExecutionContext = loggingHandlerAddExecutionContext;
function interceptStdoutWrite() {

@@ -90,3 +92,2 @@ const originalStdoutWrite = process.stdout.write;

}
exports.splitArgs = splitArgs;
function getModifiedData(data, encoding, stderr = false) {

@@ -110,3 +111,2 @@ const currentContext = (0, async_local_storage_1.getCurrentContext)();

}
exports.getModifiedData = getModifiedData;
function getTextWithContext(data, context) {

@@ -113,0 +113,0 @@ return {

@@ -74,3 +74,2 @@ "use strict";

const splitResource = (context) => {
var _a, _b;
let service = '';

@@ -84,3 +83,3 @@ let resource = '';

else if (context.resource !== undefined) {
resource = (_a = context.resource.name) !== null && _a !== void 0 ? _a : '';
resource = context.resource.name ?? '';
service = context.resource.service;

@@ -90,3 +89,3 @@ }

for (const [backgroundService, ceService] of Object.entries(SERVICE_BACKGROUND_TO_CE)) {
if ((_b = context.eventType) === null || _b === void 0 ? void 0 : _b.startsWith(backgroundService)) {
if (context.eventType?.startsWith(backgroundService)) {
service = ceService;

@@ -125,7 +124,6 @@ }

const backgroundEventToCloudEventMiddleware = (req, res, next) => {
var _a;
if (isConvertableBackgroundEvent(req)) {
// eslint-disable-next-line prefer-const
let { context, data } = getBackgroundEvent(req);
const newType = BACKGROUND_TO_CE_TYPE[(_a = context.eventType) !== null && _a !== void 0 ? _a : ''];
const newType = BACKGROUND_TO_CE_TYPE[context.eventType ?? ''];
if (!newType) {

@@ -132,0 +130,0 @@ throw new cloud_events_1.EventConversionError(`Unable to find equivalent CloudEvent type for ${context.eventType}`);

@@ -13,11 +13,9 @@ "use strict";

res.on('timeout', () => {
var _a;
// This event is triggered when the underlying socket times out due to inactivity.
if (!executionComplete) {
executionComplete = true;
(_a = req.abortController) === null || _a === void 0 ? void 0 : _a.abort('timeout');
req.abortController?.abort('timeout');
}
});
req.on('close', () => {
var _a;
// This event is triggered when the underlying HTTP connection is closed. This can

@@ -28,3 +26,3 @@ // happen if the data plane times out the request, the client disconnects or the

executionComplete = true;
(_a = req.abortController) === null || _a === void 0 ? void 0 : _a.abort('request closed');
req.abortController?.abort('request closed');
}

@@ -31,0 +29,0 @@ });

@@ -32,2 +32,6 @@ "use strict";

class ConfigurableOption {
cliOption;
envVar;
defaultValue;
validator;
constructor(

@@ -58,4 +62,3 @@ /**

parse(cliArgs, envVars) {
var _a, _b;
return this.validator((_b = (_a = cliArgs[this.cliOption]) !== null && _a !== void 0 ? _a : envVars[this.envVar]) !== null && _b !== void 0 ? _b : this.defaultValue);
return this.validator(cliArgs[this.cliOption] ?? envVars[this.envVar] ?? this.defaultValue);
}

@@ -81,4 +84,3 @@ }

});
const IgnoredRoutesOption = new ConfigurableOption('ignored-routes', 'IGNORED_ROUTES', null // null by default so we can detect if it is explicitly set to ""
);
const IgnoredRoutesOption = new ConfigurableOption('ignored-routes', 'IGNORED_ROUTES', null);
exports.requiredNodeJsVersionForLogExecutionID = '13.0.0';

@@ -85,0 +87,0 @@ const ExecutionIdOption = new ConfigurableOption('log-execution-id', 'LOG_EXECUTION_ID', false, x => {

@@ -1,2 +0,1 @@

/// <reference types="node" />
import * as http from 'http';

@@ -3,0 +2,0 @@ import { HandlerFunction } from './functions';

@@ -16,3 +16,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getServer = void 0;
exports.getServer = getServer;
const bodyParser = require("body-parser");

@@ -82,14 +82,4 @@ const express = require("express");

// Apply middleware
if (options.signatureType !== 'typed') {
// If the function is not typed then JSON parsing can be done automatically, otherwise the
// functions format must determine deserialization.
app.use(bodyParser.json(cloudEventsBodySavingOptions));
app.use(bodyParser.json(defaultBodySavingOptions));
}
else {
const jsonParserOptions = Object.assign({}, defaultBodySavingOptions, {
type: 'application/json',
});
app.use(bodyParser.text(jsonParserOptions));
}
app.use(bodyParser.json(cloudEventsBodySavingOptions));
app.use(bodyParser.json(defaultBodySavingOptions));
app.use(bodyParser.text(defaultBodySavingOptions));

@@ -161,3 +151,2 @@ app.use(bodyParser.urlencoded(urlEncodedOptions));

}
exports.getServer = getServer;
//# sourceMappingURL=server.js.map

@@ -27,4 +27,3 @@ "use strict";

const getFunction = (functionName) => {
var _a;
return (_a = (0, function_registry_1.getRegisteredFunction)(functionName)) === null || _a === void 0 ? void 0 : _a.userFunction;
return (0, function_registry_1.getRegisteredFunction)(functionName)?.userFunction;
};

@@ -31,0 +30,0 @@ exports.getFunction = getFunction;

@@ -5,3 +5,3 @@ export declare const FUNCTION_STATUS_HEADER_FIELD = "X-Google-Status";

*/
export declare const SignatureType: readonly ["http", "event", "cloudevent", "typed"];
export declare const SignatureType: readonly ["http", "event", "cloudevent"];
/**

@@ -16,3 +16,3 @@ * Union type of all valid function SignatureType values.

*/
export declare const isValidSignatureType: (x: any) => x is "http" | "cloudevent" | "event" | "typed";
export declare const isValidSignatureType: (x: any) => x is SignatureType;
//# sourceMappingURL=types.d.ts.map

@@ -23,3 +23,3 @@ "use strict";

*/
exports.SignatureType = ['http', 'event', 'cloudevent', 'typed'];
exports.SignatureType = ['http', 'event', 'cloudevent'];
/**

@@ -26,0 +26,0 @@ * Type guard to test if a provided value is valid SignatureType

{
"name": "@google-cloud/functions-framework",
"version": "3.5.1",
"version": "4.0.0",
"description": "FaaS (Function as a service) framework for writing portable Node.js functions",

@@ -23,3 +23,3 @@ "engines": {

"@types/express": "^4.17.21",
"body-parser": "^1.18.3",
"body-parser": "1.20.3",
"cloudevents": "^8.0.2",

@@ -29,4 +29,4 @@ "express": "^4.21.2",

"on-finished": "^2.3.0",
"read-pkg-up": "^7.0.1",
"semver": "^7.6.3"
"read-package-up": "^11.0.0",
"semver": "^7.7.1"
},

@@ -57,19 +57,19 @@ "scripts": {

"devDependencies": {
"@microsoft/api-extractor": "^7.48.0",
"@microsoft/api-extractor": "^7.52.2",
"@types/body-parser": "1.19.5",
"@types/minimist": "1.2.5",
"@types/mocha": "^10.0.0",
"@types/node": "^22.10.1",
"@types/node": "^22.13.14",
"@types/on-finished": "2.3.4",
"@types/semver": "^7.5.8",
"@types/sinon": "^17.0.3",
"@types/supertest": "6.0.2",
"gts": "5.3.1",
"mocha": "^9.2.2",
"nise": "5.1.4",
"pack-n-play": "2.0.0",
"sinon": "15.0.1",
"supertest": "^6.3.4",
"typescript": "5.0.3"
"@types/semver": "^7.7.0",
"@types/sinon": "^17.0.4",
"@types/supertest": "6.0.3",
"gts": "6.0.2",
"mocha": "^11.1 .0",
"nise": "6.1.1",
"pack-n-play": "3.0.0",
"sinon": "20.0.0",
"supertest": "^7.1.0",
"typescript": "5.8.2"
}
}