@browserbasehq/sdk-functions 0.0.3 → 0.0.6

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.
package/dist/index.cjs CHANGED
@@ -8,7 +8,7 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
8
 
9
9
  var a__default = /*#__PURE__*/_interopDefault(a);
10
10
 
11
- var b=Object.defineProperty;var M=(n,t,e)=>t in n?b(n,t,{enumerable:true,configurable:true,writable:true,value:e}):n[t]=e;var s=(n,t,e)=>M(n,typeof t!="symbol"?t+"":t,e);var m=class extends Error{constructor(t){super(t);}},f=class extends Error{constructor(t){super(t);}},l=class extends Error{constructor(t){super(t);}},d=class extends Error{constructor(t){super(t);}};var N=a__default.default.object({id:a__default.default.string(),connectUrl:a__default.default.string()}),w=a__default.default.object({session:N});var x=a__default.default.object({functionName:a__default.default.string().min(1),params:a__default.default.looseObject({}),context:w});a__default.default.object({requestId:a__default.default.string().min(1),event:x});a__default.default.object({errorMessage:a__default.default.string().min(1),errorType:a__default.default.string().min(1),stackTrace:a__default.default.array(a__default.default.string().min(1))});var y=class{constructor(t,e){s(this,"runtimeApi");s(this,"baseUrl");s(this,"registry");this.runtimeApi=e,this.baseUrl=`http://${this.runtimeApi}/2018-06-01/runtime`,this.registry=t;}async waitForNextInvocation(){let t=await fetch(`${this.baseUrl}/invocation/next`);if(!t.ok)throw new f(`Next invocation failed: ${t.status} ${t.statusText}`);let e=t.headers.get("Lambda-Runtime-Aws-Request-Id")||"unknown",o=t.headers.get("Lambda-Runtime-Trace-Id");o&&(process.env._X_AMZN_TRACE_ID=o);let i=await t.text(),r=JSON.parse(i),c=x.safeParse(r);if(!c.success)throw new Error("Failed to parse event into runtime event");let p=c.data;return {requestId:e,event:p}}getFunctionDefinitionByName(t){return this.registry.getByName(t)}executeFunction(t){return this.registry.execute(t.functionName,t.params??{},t.context)}async handleSuccess(t,e){let o=await fetch(`${this.baseUrl}/invocation/${encodeURIComponent(t)}/response`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new l(`Failed to post response: ${o.status} ${o.statusText}`)}async handleFailure(t,e){let o=E(e),i=await fetch(`${this.baseUrl}/invocation/${encodeURIComponent(t)}/error`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new d(`Failed to post error: ${i.status} ${i.statusText}`)}};function E(n){if(n instanceof Error)return {errorMessage:n.message,errorType:n.name,stackTrace:n.stack?.split("/n")??[]};let t="An unknown error occurred",e="UnknownError",o=[];return typeof n=="string"?{errorMessage:n,errorType:e,stackTrace:o}:typeof n!="object"||n===null?{errorMessage:String(n),errorType:e,stackTrace:o}:("message"in n&&typeof n.message=="string"&&(t=n.message),"name"in n&&typeof n.name=="string"&&(e=n.name),"stack"in n&&Array.isArray(n.stack)&&typeof n.stack[0]=="string"&&(o=n.stack),{errorMessage:t,errorType:e,stackTrace:o})}async function P(n,t){try{let{requestId:e,event:o}=await n.waitForNextInvocation();console.log(`Received invocation with requestId: ${e}`);let{functionName:i}=o,r=n.getFunctionDefinitionByName(i);if(console.log(`Found definition for "${i}": ${JSON.stringify(r)}`),!r)throw new Error(`Function "${i}" not found in registry`);let c;try{console.log(`Executing function: ${i}`),c=await n.executeFunction(o),console.log(`Received result: ${JSON.stringify(c)}`);}catch(p){console.error("Handler error:",p),await n.handleFailure(e,p);return}await n.handleSuccess(e,c),console.log(`Function "${i}" completed successfully`);}catch(e){console.error("Fatal error in runtime loop:",e),t(e);}}async function I(n,t){for(;;)await P(n,t);}var h=class{constructor(){s(this,"_functions",new Map);}register(t,e,o){this._functions.set(t,{name:t,handler:e,config:o});}getByName(t){return this._functions.get(t)??null}async execute(t,e,o){let i=this._functions.get(t);if(!i)throw new m(`Couldn't find function with name "${t}" in registry`);let r=await i.handler(o,e);return console.log("handlerResult",r),r}get size(){return this._functions.size}};var v=class{constructor(t){s(this,"_environment");s(this,"_runtimeApi");s(this,"_phase");this._environment=S(t,"NODE_ENV","local"),this._runtimeApi=S(t,"AWS_LAMBDA_RUNTIME_API","127.0.0.1:14113"),this._phase=S(t,"BB_FUNCTIONS_PHASE","runtime");}get environment(){return this._environment}get runtimeApi(){return this._runtimeApi}get phase(){return this._phase}};function S(n,t,e){let o=n[t];return o||e}function k(n,t,e){e&&(fs.existsSync(t)&&fs.rmSync(t,{recursive:true}),fs.mkdirSync(t,{recursive:true}));let o=A(n);fs.writeFileSync(path.join(t,`${n.name}.json`),JSON.stringify(o,null,2));}function A(n){let{name:t,config:e}=n,{parametersSchema:o,...i}=e,r={...i};return o&&(r.parametersSchema=$(o)),{name:t,config:r}}function $(n){return n instanceof a__default.default.ZodObject?a__default.default.toJSONSchema(n):{}}function D(n,t,e={}){if(F.register(n,t,e),u.phase==="introspect"||u.environment==="local"){let o=path.join(process.cwd(),".browserbase","functions","manifests"),i=F.size===1;k({name:n,config:e},o,i);}}var u=new v(process.env),F=new h,z=new y(F,u.runtimeApi);function H(n){console.error("Received fatal error from invocation loop",n),process.exit(1);}u.phase==="runtime"&&I(z,H).catch(n=>{console.error("Fatal runtime error:",n),process.exit(1);});
11
+ var b=Object.defineProperty;var M=(n,t,e)=>t in n?b(n,t,{enumerable:true,configurable:true,writable:true,value:e}):n[t]=e;var s=(n,t,e)=>M(n,typeof t!="symbol"?t+"":t,e);var m=class extends Error{constructor(t){super(t);}},f=class extends Error{constructor(t){super(t);}},l=class extends Error{constructor(t){super(t);}},d=class extends Error{constructor(t){super(t);}};var N=a__default.default.looseObject({id:a__default.default.string(),connectUrl:a__default.default.string()}),w=a__default.default.looseObject({session:N});var x=a__default.default.object({functionName:a__default.default.string().min(1),params:a__default.default.looseObject({}),context:w});a__default.default.object({requestId:a__default.default.string().min(1),event:x});a__default.default.object({errorMessage:a__default.default.string().min(1),errorType:a__default.default.string().min(1),stackTrace:a__default.default.array(a__default.default.string().min(1))});var y=class{constructor(t,e){s(this,"runtimeApi");s(this,"baseUrl");s(this,"registry");this.runtimeApi=e,this.baseUrl=`http://${this.runtimeApi}/2018-06-01/runtime`,this.registry=t;}async waitForNextInvocation(){let t=await fetch(`${this.baseUrl}/invocation/next`);if(!t.ok)throw new f(`Next invocation failed: ${t.status} ${t.statusText}`);let e=t.headers.get("Lambda-Runtime-Aws-Request-Id")||"unknown",o=t.headers.get("Lambda-Runtime-Trace-Id");o&&(process.env._X_AMZN_TRACE_ID=o);let i=await t.text(),r=JSON.parse(i),c=x.safeParse(r);if(!c.success)throw new Error("Failed to parse event into runtime event");let p=c.data;return {requestId:e,event:p}}getFunctionDefinitionByName(t){return this.registry.getByName(t)}executeFunction(t){return this.registry.execute(t.functionName,t.params??{},t.context)}async handleSuccess(t,e){let o=await fetch(`${this.baseUrl}/invocation/${encodeURIComponent(t)}/response`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new l(`Failed to post response: ${o.status} ${o.statusText}`)}async handleFailure(t,e){let o=E(e),i=await fetch(`${this.baseUrl}/invocation/${encodeURIComponent(t)}/error`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new d(`Failed to post error: ${i.status} ${i.statusText}`)}};function E(n){if(n instanceof Error)return {errorMessage:n.message,errorType:n.name,stackTrace:n.stack?.split("/n")??[]};let t="An unknown error occurred",e="UnknownError",o=[];return typeof n=="string"?{errorMessage:n,errorType:e,stackTrace:o}:typeof n!="object"||n===null?{errorMessage:String(n),errorType:e,stackTrace:o}:("message"in n&&typeof n.message=="string"&&(t=n.message),"name"in n&&typeof n.name=="string"&&(e=n.name),"stack"in n&&Array.isArray(n.stack)&&typeof n.stack[0]=="string"&&(o=n.stack),{errorMessage:t,errorType:e,stackTrace:o})}async function P(n,t){try{let{requestId:e,event:o}=await n.waitForNextInvocation();console.log(`Received invocation with requestId: ${e}`);let{functionName:i}=o,r=n.getFunctionDefinitionByName(i);if(console.log(`Found definition for "${i}": ${JSON.stringify(r)}`),!r)throw new Error(`Function "${i}" not found in registry`);let c;try{console.log(`Executing function: ${i}`),c=await n.executeFunction(o),console.log(`Received result: ${JSON.stringify(c)}`);}catch(p){console.error("Handler error:",p),await n.handleFailure(e,p);return}await n.handleSuccess(e,c),console.log(`Function "${i}" completed successfully`);}catch(e){console.error("Fatal error in runtime loop:",e),t(e);}}async function I(n,t){for(;;)await P(n,t);}var h=class{constructor(){s(this,"_functions",new Map);}register(t,e,o){this._functions.set(t,{name:t,handler:e,config:o});}getByName(t){return this._functions.get(t)??null}async execute(t,e,o){let i=this._functions.get(t);if(!i)throw new m(`Couldn't find function with name "${t}" in registry`);let r=await i.handler(o,e);return console.log("handlerResult",r),r}get size(){return this._functions.size}};var v=class{constructor(t){s(this,"_environment");s(this,"_runtimeApi");s(this,"_phase");this._environment=S(t,"NODE_ENV","local"),this._runtimeApi=S(t,"AWS_LAMBDA_RUNTIME_API","127.0.0.1:14113"),this._phase=S(t,"BB_FUNCTIONS_PHASE","runtime");}get environment(){return this._environment}get runtimeApi(){return this._runtimeApi}get phase(){return this._phase}};function S(n,t,e){let o=n[t];return o||e}function k(n,t,e){e&&(fs.existsSync(t)&&fs.rmSync(t,{recursive:true}),fs.mkdirSync(t,{recursive:true}));let o=A(n);fs.writeFileSync(path.join(t,`${n.name}.json`),JSON.stringify(o,null,2));}function A(n){let{name:t,config:e}=n,{parametersSchema:o,...i}=e,r={...i};return o&&(r.parametersSchema=$(o)),{name:t,config:r}}function $(n){return n instanceof a__default.default.ZodObject?a__default.default.toJSONSchema(n):{}}function D(n,t,e={}){if(F.register(n,t,e),u.phase==="introspect"||u.environment==="local"){let o=path.join(process.cwd(),".browserbase","functions","manifests"),i=F.size===1;k({name:n,config:e},o,i);}}var u=new v(process.env),F=new h,z=new y(F,u.runtimeApi);function H(n){console.error("Received fatal error from invocation loop",n),process.exit(1);}u.phase==="runtime"&&I(z,H).catch(n=>{console.error("Fatal runtime error:",n),process.exit(1);});
12
12
 
13
13
  exports.defineFn = D;
14
14
  exports.environmentManager = u;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/errors.ts","../src/schemas/invocation.ts","../src/schemas/events.ts","../src/runtime/index.ts","../src/runtime/loop.ts","../src/runtime/registry.ts","../src/utils/env.ts","../src/define/helpers.ts","../src/define/index.ts","../src/index.ts"],"names":["FunctionNotFoundInRegistryError","message","GetNextInvocationError","PostResultError","PostErrorError","FunctionInvocationContextSessionDetails","z","FunctionInvocationContext","RuntimeEventPayload","RuntimeClient","registry","runtimeApi","__publicField","response","requestId","traceId","text","parsedData","safeParseResult","event","name","result","error","runtimeError","formatRuntimeError","type","stack","waitForAndHandleInvocation","runtimeClient","handleFatalError","functionName","functionDefinition","runInvocationLoop","handleProductionFailure","FunctionRegistry","handler","config","params","context","foundDefinition","handlerResult","EnvironmentManager","processEnv","getOrDefault","env","key","dflt","val","writeManifestToDisk","manifest","manifestsDir","isFirstInvocation","existsSync","rmSync","mkdirSync","persistedManifest","buildPersistedFunctionManifest","writeFileSync","join","parametersSchema","configWithoutSchema","processedConfig","buildPersistedJsonSchema","input","defineFn","functionsRegistry","environmentManager","handleInvocationLoopFailure"],"mappings":";;;;;;;;;;0KAAO,IAAMA,CAAAA,CAAN,cAA8C,KAAM,CACzD,WAAA,CAAYC,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaC,CAAAA,CAAN,cAAqC,KAAM,CAChD,WAAA,CAAYD,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaE,CAAAA,CAAN,cAA8B,KAAM,CACzC,WAAA,CAAYF,EAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaG,CAAAA,CAAN,cAA6B,KAAM,CACxC,WAAA,CAAYH,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CCpBO,IAAMI,CAAAA,CAA0CC,kBAAAA,CAAE,MAAA,CAAO,CAC9D,EAAA,CAAIA,mBAAE,MAAA,EAAO,CACb,UAA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,IAAA,CAAK,CAAC,EAChB,CACF,CAAA","file":"index.cjs","sourcesContent":["export class FunctionNotFoundInRegistryError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class GetNextInvocationError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class PostResultError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class PostErrorError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n","import z from \"zod\";\n\nexport const FunctionInvocationContextSessionDetails = z.object({\n id: z.string(),\n connectUrl: z.string(),\n});\n\nexport type FunctionInvocationContextSessionDetails = z.infer<\n typeof FunctionInvocationContextSessionDetails\n>;\n\nexport const FunctionInvocationContext = z.object({\n session: FunctionInvocationContextSessionDetails,\n});\n\nexport type FunctionInvocationContext = z.infer<\n typeof FunctionInvocationContext\n>;\n","import z from \"zod\";\nimport { FunctionInvocationContext } from \"./invocation.js\";\n\nexport const RuntimeEventPayload = z.object({\n functionName: z.string().min(1),\n params: z.looseObject({}), // Allow passthrough of unknown (all) keys\n context: FunctionInvocationContext,\n});\n\nexport type RuntimeEventPayload = z.infer<typeof RuntimeEventPayload>;\n\nexport const RuntimeEvent = z.object({\n requestId: z.string().min(1),\n event: RuntimeEventPayload,\n});\n\nexport type RuntimeEvent = z.infer<typeof RuntimeEvent>;\n\nexport const RuntimeError = z.object({\n errorMessage: z.string().min(1),\n errorType: z.string().min(1),\n stackTrace: z.array(z.string().min(1)),\n});\n\nexport type RuntimeError = z.infer<typeof RuntimeError>;\n","import type { FunctionRegistry } from \"../runtime/registry.js\";\nimport {\n GetNextInvocationError,\n PostErrorError,\n PostResultError,\n} from \"../utils/errors.js\";\nimport {\n RuntimeError,\n RuntimeEvent,\n RuntimeEventPayload,\n} from \"../schemas/events.js\";\nimport type { FunctionManifest } from \"../types/definition.js\";\nimport type { FunctionHandlerCallbackReturnValue } from \"../types/handler.js\";\n\nexport interface IRuntimeClient {\n waitForNextInvocation(): Promise<RuntimeEvent>;\n getFunctionDefinitionByName(name: string): FunctionManifest<unknown> | null;\n\n executeFunction(\n event: RuntimeEventPayload,\n ): Promise<FunctionHandlerCallbackReturnValue>;\n\n handleSuccess(\n requestId: string,\n result: FunctionHandlerCallbackReturnValue,\n ): Promise<void>;\n\n handleFailure(requestId: string, error: unknown): Promise<void>;\n}\n\nexport class RuntimeClient implements IRuntimeClient {\n private runtimeApi: string;\n private baseUrl: string;\n private registry: FunctionRegistry;\n\n constructor(registry: FunctionRegistry, runtimeApi: string) {\n this.runtimeApi = runtimeApi;\n this.baseUrl = `http://${this.runtimeApi}/2018-06-01/runtime`;\n this.registry = registry;\n }\n\n public async waitForNextInvocation(): Promise<RuntimeEvent> {\n const response = await fetch(`${this.baseUrl}/invocation/next`);\n if (!response.ok) {\n throw new GetNextInvocationError(\n `Next invocation failed: ${response.status} ${response.statusText}`,\n );\n }\n\n const requestId =\n response.headers.get(\"Lambda-Runtime-Aws-Request-Id\") || \"unknown\";\n const traceId = response.headers.get(\"Lambda-Runtime-Trace-Id\");\n\n // This is to allow the X-Ray SDK to trace across invocations\n if (traceId) {\n process.env[\"_X_AMZN_TRACE_ID\"] = traceId;\n }\n\n const text = await response.text();\n const parsedData = JSON.parse(text);\n\n const safeParseResult = RuntimeEventPayload.safeParse(parsedData);\n if (!safeParseResult.success) {\n // TODO: type error\n throw new Error(\"Failed to parse event into runtime event\");\n }\n\n const event = safeParseResult.data;\n return { requestId, event };\n }\n\n public getFunctionDefinitionByName(\n name: string,\n ): FunctionManifest<unknown> | null {\n return this.registry.getByName(name);\n }\n\n public executeFunction(\n event: RuntimeEventPayload,\n ): Promise<FunctionHandlerCallbackReturnValue> {\n return this.registry.execute(\n event.functionName,\n event.params ?? {},\n event.context,\n );\n }\n\n public async handleSuccess(\n requestId: string,\n result: FunctionHandlerCallbackReturnValue,\n ): Promise<void> {\n const response = await fetch(\n `${this.baseUrl}/invocation/${encodeURIComponent(requestId)}/response`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(result),\n },\n );\n\n if (!response.ok) {\n throw new PostResultError(\n `Failed to post response: ${response.status} ${response.statusText}`,\n );\n }\n }\n\n public async handleFailure(requestId: string, error: unknown): Promise<void> {\n const runtimeError = formatRuntimeError(error);\n\n const response = await fetch(\n `${this.baseUrl}/invocation/${encodeURIComponent(requestId)}/error`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(runtimeError),\n },\n );\n\n if (!response.ok) {\n throw new PostErrorError(\n `Failed to post error: ${response.status} ${response.statusText}`,\n );\n }\n }\n}\n\nfunction formatRuntimeError(error: unknown): RuntimeError {\n if (error instanceof Error) {\n return {\n errorMessage: error.message,\n errorType: error.name,\n stackTrace: error.stack?.split(\"/n\") ?? [],\n };\n }\n\n let message = \"An unknown error occurred\";\n let type = \"UnknownError\";\n let stack = [] as string[];\n\n if (typeof error === \"string\") {\n return {\n errorMessage: error,\n errorType: type,\n stackTrace: stack,\n };\n }\n\n if (typeof error !== \"object\" || error === null) {\n return {\n errorMessage: String(error),\n errorType: type,\n stackTrace: stack,\n };\n }\n\n if (\"message\" in error && typeof error.message === \"string\") {\n message = error.message;\n }\n\n if (\"name\" in error && typeof error.name === \"string\") {\n type = error.name;\n }\n\n if (\n \"stack\" in error &&\n Array.isArray(error.stack) &&\n typeof error.stack[0] === \"string\"\n ) {\n stack = error.stack;\n }\n\n return {\n errorMessage: message,\n errorType: type,\n stackTrace: stack,\n };\n}\n","import type { IRuntimeClient } from \"./index.js\";\n\nexport async function waitForAndHandleInvocation(\n runtimeClient: IRuntimeClient,\n handleFatalError: (error: unknown) => void,\n) {\n // Any errors caught by this block will be considered fatal system errors\n try {\n const { requestId, event } = await runtimeClient.waitForNextInvocation();\n console.log(`Received invocation with requestId: ${requestId}`);\n const { functionName } = event;\n\n // Validate that the specified function is in the registry.\n // If not, throw a system error as this means we've set up the DB wrong\n // and that the system thinks that function is here when it's not.\n // NOTE: If the user finds a way to circumvent the SDK setup intentionally,\n // NOTE: we could see this error when the DB is correct.\n const functionDefinition =\n runtimeClient.getFunctionDefinitionByName(functionName);\n\n console.log(\n `Found definition for \"${functionName}\": ${JSON.stringify(functionDefinition)}`,\n );\n\n // TODO: type this error\n if (!functionDefinition) {\n throw new Error(`Function \"${functionName}\" not found in registry`);\n }\n\n // Any errors caught by this block will be considered user code errors\n let result;\n try {\n console.log(`Executing function: ${functionName}`);\n result = await runtimeClient.executeFunction(event);\n console.log(`Received result: ${JSON.stringify(result)}`);\n } catch (error: unknown) {\n console.error(\"Handler error:\", error);\n await runtimeClient.handleFailure(requestId, error);\n return; // This invocation is done - don't call handleSuccess\n }\n\n await runtimeClient.handleSuccess(requestId, result);\n console.log(`Function \"${functionName}\" completed successfully`);\n } catch (error: unknown) {\n console.error(\"Fatal error in runtime loop:\", error);\n handleFatalError(error);\n }\n}\n\nexport async function runInvocationLoop(\n runtimeClient: IRuntimeClient,\n handleProductionFailure: (error: unknown) => void,\n): Promise<void> {\n while (true) {\n await waitForAndHandleInvocation(runtimeClient, handleProductionFailure);\n }\n}\n","import { FunctionNotFoundInRegistryError } from \"../utils/errors.js\";\n\nimport type { FunctionInvocationContext } from \"../schemas/invocation.js\";\nimport type { FunctionManifest } from \"../types/definition.js\";\nimport type { FunctionHandlerCallbackReturnValue } from \"../types/handler.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nexport interface IFunctionRegistry {\n register<S extends JSONSchemaInput>(\n name: FunctionManifest<S>[\"name\"],\n handler: FunctionManifest<S>[\"handler\"],\n config: FunctionManifest<S>[\"config\"],\n ): void;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- this would need to be generic based on the `register` call\n getByName(name: string): FunctionManifest<any> | null;\n\n execute(\n name: string,\n params: object,\n context: FunctionInvocationContext,\n ): Promise<FunctionHandlerCallbackReturnValue>;\n\n get size(): number;\n}\n\nexport class FunctionRegistry implements IFunctionRegistry {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- this would need to be generic based on the `register` call\n private _functions = new Map<string, FunctionManifest<any>>();\n\n register<S extends JSONSchemaInput>(\n name: FunctionManifest<S>[\"name\"],\n handler: FunctionManifest<S>[\"handler\"],\n config: FunctionManifest<S>[\"config\"],\n ) {\n this._functions.set(name, {\n name,\n handler,\n config,\n });\n }\n\n public getByName(name: string): FunctionManifest<unknown> | null {\n return this._functions.get(name) ?? null;\n }\n\n async execute(\n name: string,\n params: object,\n context: FunctionInvocationContext,\n ) {\n const foundDefinition = this._functions.get(name);\n if (!foundDefinition) {\n throw new FunctionNotFoundInRegistryError(\n `Couldn't find function with name \"${name}\" in registry`,\n );\n }\n\n const handlerResult = await foundDefinition.handler(context, params);\n\n // TODO: Remove when we have a better structured logging story\n console.log(\"handlerResult\", handlerResult);\n\n return handlerResult;\n }\n\n get size() {\n return this._functions.size;\n }\n}\n","export interface IEnvironmentManager {\n get environment(): string;\n get runtimeApi(): string;\n get phase(): string;\n}\n\nexport class EnvironmentManager {\n /// Whether we're running these locally or deployed (\"production\").\n /// Locally we are more forgiving on failures, and will change logging.\n private _environment: \"local\" | \"production\";\n\n /// The URL that is used to alert the runtime to the status of the invocation.\n /// Locally this will point to the URL of the dev server being run, in prod this\n /// will point to the runtime's internal endpoints.\n private _runtimeApi: string;\n\n /// We need to handle running a function differently than we handle\n /// deploying a function. The \"runtime\" phase is when we're trying to\n /// run a function by name (either locally or in prod). The \"build\"\n /// phase is when we're generating local manifest files to send to\n /// the Browserbase API. Defaults to runtime phase.\n private _phase: \"runtime\" | \"introspect\";\n\n constructor(processEnv: NodeJS.ProcessEnv) {\n this._environment = getOrDefault<typeof this._environment>(\n processEnv,\n \"NODE_ENV\",\n \"local\",\n );\n\n this._runtimeApi = getOrDefault<typeof this._runtimeApi>(\n processEnv,\n \"AWS_LAMBDA_RUNTIME_API\",\n \"127.0.0.1:14113\",\n );\n\n this._phase = getOrDefault<typeof this._phase>(\n processEnv,\n \"BB_FUNCTIONS_PHASE\",\n \"runtime\",\n );\n }\n\n get environment() {\n return this._environment;\n }\n\n get runtimeApi() {\n return this._runtimeApi;\n }\n\n get phase() {\n return this._phase;\n }\n}\n\nfunction getOrDefault<T>(env: NodeJS.ProcessEnv, key: string, dflt: T): T {\n const val = env[key];\n if (!val) {\n return dflt;\n }\n return val as T;\n}\n","import { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport z from \"zod\";\n\nimport type {\n FunctionManifest,\n PersistedFunctionManifest,\n} from \"../types/definition.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nexport function writeManifestToDisk<S extends JSONSchemaInput>(\n manifest: FunctionManifest<S>,\n manifestsDir: string,\n isFirstInvocation: boolean,\n) {\n if (isFirstInvocation) {\n // Clear manifests directory if it exists to remove stale menifests\n if (existsSync(manifestsDir)) {\n rmSync(manifestsDir, { recursive: true });\n }\n\n mkdirSync(manifestsDir, { recursive: true });\n }\n\n const persistedManifest = buildPersistedFunctionManifest(manifest);\n\n writeFileSync(\n join(manifestsDir, `${manifest.name}.json`),\n JSON.stringify(persistedManifest, null, 2),\n );\n}\n\nexport function buildPersistedFunctionManifest<S extends JSONSchemaInput>(\n manifest: FunctionManifest<S>,\n): PersistedFunctionManifest<S> {\n const { name, config } = manifest;\n const { parametersSchema, ...configWithoutSchema } = config;\n\n const processedConfig: PersistedFunctionManifest<S>[\"config\"] = {\n ...configWithoutSchema,\n };\n\n if (parametersSchema) {\n processedConfig.parametersSchema =\n buildPersistedJsonSchema(parametersSchema);\n }\n\n const processedManifest: PersistedFunctionManifest<S> = {\n name,\n config: processedConfig,\n };\n\n return processedManifest;\n}\n\nexport function buildPersistedJsonSchema(input: JSONSchemaInput): object {\n if (input instanceof z.ZodObject) {\n return z.toJSONSchema(input);\n }\n\n return {};\n}\n","import { join } from \"node:path\";\n\nimport type { FunctionConfiguration } from \"../types/definition.js\";\nimport type { FunctionHandler } from \"../types/handler.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nimport { writeManifestToDisk } from \"./helpers.js\";\n\n// Singleton imports\nimport { environmentManager, functionsRegistry } from \"../index.js\";\n\n/// TODO: Write good documentation here\nexport function defineFn<S extends JSONSchemaInput = unknown>(\n name: string,\n handler: FunctionHandler<S>,\n config: FunctionConfiguration<S> = {},\n): void {\n functionsRegistry.register(name, handler, config);\n\n if (\n // The CLI needs \"local\" to know how to create sessions with\n // non-default configurations during the local dev flow\n environmentManager.phase === \"introspect\" ||\n environmentManager.environment === \"local\"\n ) {\n const manifestsDir = join(\n process.cwd(),\n \".browserbase\",\n \"functions\",\n \"manifests\",\n );\n\n const isFirstInvocation = functionsRegistry.size === 1;\n\n writeManifestToDisk(\n { name, handler, config },\n manifestsDir,\n isFirstInvocation,\n );\n }\n}\n","import { RuntimeClient } from \"./runtime/index.js\";\nimport { runInvocationLoop } from \"./runtime/loop.js\";\nimport { FunctionRegistry } from \"./runtime/registry.js\";\nimport { EnvironmentManager } from \"./utils/env.js\";\n\nexport { defineFn } from \"./define/index.js\";\n\nexport const environmentManager = new EnvironmentManager(process.env);\nexport const functionsRegistry = new FunctionRegistry();\nexport const runtimeClient = new RuntimeClient(\n functionsRegistry,\n environmentManager.runtimeApi,\n);\n\nfunction handleInvocationLoopFailure(error: unknown): void {\n console.error(\"Received fatal error from invocation loop\", error);\n process.exit(1);\n}\n// We only want to listen for invocations iff we're in the \"runtime\" phase\nif (environmentManager.phase === \"runtime\") {\n runInvocationLoop(runtimeClient, handleInvocationLoopFailure).catch(\n (error: unknown) => {\n console.error(\"Fatal runtime error:\", error);\n process.exit(1);\n },\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/utils/errors.ts","../src/schemas/invocation.ts","../src/schemas/events.ts","../src/runtime/index.ts","../src/runtime/loop.ts","../src/runtime/registry.ts","../src/utils/env.ts","../src/define/helpers.ts","../src/define/index.ts","../src/index.ts"],"names":["FunctionNotFoundInRegistryError","message","GetNextInvocationError","PostResultError","PostErrorError","FunctionInvocationContextSessionDetails","z","FunctionInvocationContext","RuntimeEventPayload","RuntimeClient","registry","runtimeApi","__publicField","response","requestId","traceId","text","parsedData","safeParseResult","event","name","result","error","runtimeError","formatRuntimeError","type","stack","waitForAndHandleInvocation","runtimeClient","handleFatalError","functionName","functionDefinition","runInvocationLoop","handleProductionFailure","FunctionRegistry","handler","config","params","context","foundDefinition","handlerResult","EnvironmentManager","processEnv","getOrDefault","env","key","dflt","val","writeManifestToDisk","manifest","manifestsDir","isFirstInvocation","existsSync","rmSync","mkdirSync","persistedManifest","buildPersistedFunctionManifest","writeFileSync","join","parametersSchema","configWithoutSchema","processedConfig","buildPersistedJsonSchema","input","defineFn","functionsRegistry","environmentManager","handleInvocationLoopFailure"],"mappings":";;;;;;;;;;0KAAO,IAAMA,CAAAA,CAAN,cAA8C,KAAM,CACzD,WAAA,CAAYC,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaC,CAAAA,CAAN,cAAqC,KAAM,CAChD,WAAA,CAAYD,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaE,CAAAA,CAAN,cAA8B,KAAM,CACzC,WAAA,CAAYF,EAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaG,CAAAA,CAAN,cAA6B,KAAM,CACxC,WAAA,CAAYH,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CCnBO,IAAMI,CAAAA,CAA0CC,kBAAAA,CAAE,WAAA,CAAY,CACnE,EAAA,CAAIA,mBAAE,MAAA,EAAO,CACb,UAAA,CAAYA,kBAAAA,CAAE,MAAA,EAChB,CAAC,CAAA,CAOYC,CAAAA,CAA4BD,kBAAAA,CAAE,WAAA,CAAY,CACrD,OAAA,CAASD,CACX,CAAC,CAAA,CCZM,IAAMG,CAAAA,CAAsBF,kBAAAA,CAAE,MAAA,CAAO,CAC1C,YAAA,CAAcA,kBAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAA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AkB,QAAA,CAAS7C,CAAAA,CAAMe,CAAAA,CAASC,CAAM,CAAA,CAK9C8B,CAAAA,CAAmB,KAAA,GAAU,YAAA,EAC7BA,CAAAA,CAAmB,WAAA,GAAgB,OAAA,CACnC,CACA,IAAMhB,CAAAA,CAAeQ,SAAAA,CACnB,OAAA,CAAQ,GAAA,EAAI,CACZ,cAAA,CACA,WAAA,CACA,WACF,CAAA,CAEMP,CAAAA,CAAoBc,CAAAA,CAAkB,IAAA,GAAS,CAAA,CAErDjB,CAAAA,CACE,CAAE,IAAA,CAAA5B,EAAe,MAAA,CAAAgB,CAAO,CAAA,CACxBc,CAAAA,CACAC,CACF,EACF,CACF,CCjCO,IAAMe,CAAAA,CAAqB,IAAIzB,CAAAA,CAAmB,OAAA,CAAQ,GAAG,CAAA,CACvDwB,CAAAA,CAAoB,IAAI/B,CAAAA,CACxBN,CAAAA,CAAgB,IAAInB,CAAAA,CAC/BwD,CAAAA,CACAC,CAAAA,CAAmB,UACrB,EAEA,SAASC,CAAAA,CAA4B7C,CAAAA,CAAsB,CACzD,OAAA,CAAQ,KAAA,CAAM,2CAAA,CAA6CA,CAAK,CAAA,CAChE,OAAA,CAAQ,IAAA,CAAK,CAAC,EAChB,CAEI4C,CAAAA,CAAmB,KAAA,GAAU,SAAA,EAC/BlC,CAAAA,CAAkBJ,CAAAA,CAAeuC,CAA2B,CAAA,CAAE,KAAA,CAC3D7C,CAAAA,EAAmB,CAClB,OAAA,CAAQ,KAAA,CAAM,sBAAA,CAAwBA,CAAK,CAAA,CAC3C,OAAA,CAAQ,IAAA,CAAK,CAAC,EAChB,CACF,CAAA","file":"index.cjs","sourcesContent":["export class FunctionNotFoundInRegistryError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class GetNextInvocationError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class PostResultError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class PostErrorError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n","import z from \"zod\";\n\n// Allow in additional fields without needing to update the SDK version\nexport const FunctionInvocationContextSessionDetails = z.looseObject({\n id: z.string(),\n connectUrl: z.string(),\n});\n\nexport type FunctionInvocationContextSessionDetails = z.infer<\n typeof FunctionInvocationContextSessionDetails\n>;\n\n// Allow in additional fields without needing to update the SDK version\nexport const FunctionInvocationContext = z.looseObject({\n session: FunctionInvocationContextSessionDetails,\n});\n\nexport type FunctionInvocationContext = z.infer<\n typeof FunctionInvocationContext\n>;\n","import z from \"zod\";\nimport { FunctionInvocationContext } from \"./invocation.js\";\n\nexport const RuntimeEventPayload = z.object({\n functionName: z.string().min(1),\n params: z.looseObject({}), // Allow passthrough of unknown (all) keys\n context: FunctionInvocationContext,\n});\n\nexport type RuntimeEventPayload = z.infer<typeof RuntimeEventPayload>;\n\nexport const RuntimeEvent = z.object({\n requestId: z.string().min(1),\n event: RuntimeEventPayload,\n});\n\nexport type RuntimeEvent = z.infer<typeof RuntimeEvent>;\n\nexport const RuntimeError = z.object({\n errorMessage: z.string().min(1),\n errorType: z.string().min(1),\n stackTrace: z.array(z.string().min(1)),\n});\n\nexport type RuntimeError = z.infer<typeof RuntimeError>;\n","import type { FunctionRegistry } from \"../runtime/registry.js\";\nimport {\n GetNextInvocationError,\n PostErrorError,\n PostResultError,\n} from \"../utils/errors.js\";\nimport {\n RuntimeError,\n RuntimeEvent,\n RuntimeEventPayload,\n} from \"../schemas/events.js\";\nimport type { FunctionManifest } from \"../types/definition.js\";\nimport type { FunctionHandlerCallbackReturnValue } from \"../types/handler.js\";\n\nexport interface IRuntimeClient {\n waitForNextInvocation(): Promise<RuntimeEvent>;\n getFunctionDefinitionByName(name: string): FunctionManifest<unknown> | null;\n\n executeFunction(\n event: RuntimeEventPayload,\n ): Promise<FunctionHandlerCallbackReturnValue>;\n\n handleSuccess(\n requestId: string,\n result: FunctionHandlerCallbackReturnValue,\n ): Promise<void>;\n\n handleFailure(requestId: string, error: unknown): Promise<void>;\n}\n\nexport class RuntimeClient implements IRuntimeClient {\n private runtimeApi: string;\n private baseUrl: string;\n private registry: FunctionRegistry;\n\n constructor(registry: FunctionRegistry, runtimeApi: string) {\n this.runtimeApi = runtimeApi;\n this.baseUrl = `http://${this.runtimeApi}/2018-06-01/runtime`;\n this.registry = registry;\n }\n\n public async waitForNextInvocation(): Promise<RuntimeEvent> {\n const response = await fetch(`${this.baseUrl}/invocation/next`);\n if (!response.ok) {\n throw new GetNextInvocationError(\n `Next invocation failed: ${response.status} ${response.statusText}`,\n );\n }\n\n const requestId =\n response.headers.get(\"Lambda-Runtime-Aws-Request-Id\") || \"unknown\";\n const traceId = response.headers.get(\"Lambda-Runtime-Trace-Id\");\n\n // This is to allow the X-Ray SDK to trace across invocations\n if (traceId) {\n process.env[\"_X_AMZN_TRACE_ID\"] = traceId;\n }\n\n const text = await response.text();\n const parsedData = JSON.parse(text);\n\n const safeParseResult = RuntimeEventPayload.safeParse(parsedData);\n if (!safeParseResult.success) {\n // TODO: type error\n throw new Error(\"Failed to parse event into runtime event\");\n }\n\n const event = safeParseResult.data;\n return { requestId, event };\n }\n\n public getFunctionDefinitionByName(\n name: string,\n ): FunctionManifest<unknown> | null {\n return this.registry.getByName(name);\n }\n\n public executeFunction(\n event: RuntimeEventPayload,\n ): Promise<FunctionHandlerCallbackReturnValue> {\n return this.registry.execute(\n event.functionName,\n event.params ?? {},\n event.context,\n );\n }\n\n public async handleSuccess(\n requestId: string,\n result: FunctionHandlerCallbackReturnValue,\n ): Promise<void> {\n const response = await fetch(\n `${this.baseUrl}/invocation/${encodeURIComponent(requestId)}/response`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(result),\n },\n );\n\n if (!response.ok) {\n throw new PostResultError(\n `Failed to post response: ${response.status} ${response.statusText}`,\n );\n }\n }\n\n public async handleFailure(requestId: string, error: unknown): Promise<void> {\n const runtimeError = formatRuntimeError(error);\n\n const response = await fetch(\n `${this.baseUrl}/invocation/${encodeURIComponent(requestId)}/error`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(runtimeError),\n },\n );\n\n if (!response.ok) {\n throw new PostErrorError(\n `Failed to post error: ${response.status} ${response.statusText}`,\n );\n }\n }\n}\n\nfunction formatRuntimeError(error: unknown): RuntimeError {\n if (error instanceof Error) {\n return {\n errorMessage: error.message,\n errorType: error.name,\n stackTrace: error.stack?.split(\"/n\") ?? [],\n };\n }\n\n let message = \"An unknown error occurred\";\n let type = \"UnknownError\";\n let stack = [] as string[];\n\n if (typeof error === \"string\") {\n return {\n errorMessage: error,\n errorType: type,\n stackTrace: stack,\n };\n }\n\n if (typeof error !== \"object\" || error === null) {\n return {\n errorMessage: String(error),\n errorType: type,\n stackTrace: stack,\n };\n }\n\n if (\"message\" in error && typeof error.message === \"string\") {\n message = error.message;\n }\n\n if (\"name\" in error && typeof error.name === \"string\") {\n type = error.name;\n }\n\n if (\n \"stack\" in error &&\n Array.isArray(error.stack) &&\n typeof error.stack[0] === \"string\"\n ) {\n stack = error.stack;\n }\n\n return {\n errorMessage: message,\n errorType: type,\n stackTrace: stack,\n };\n}\n","import type { IRuntimeClient } from \"./index.js\";\n\nexport async function waitForAndHandleInvocation(\n runtimeClient: IRuntimeClient,\n handleFatalError: (error: unknown) => void,\n) {\n // Any errors caught by this block will be considered fatal system errors\n try {\n const { requestId, event } = await runtimeClient.waitForNextInvocation();\n console.log(`Received invocation with requestId: ${requestId}`);\n const { functionName } = event;\n\n // Validate that the specified function is in the registry.\n // If not, throw a system error as this means we've set up the DB wrong\n // and that the system thinks that function is here when it's not.\n // NOTE: If the user finds a way to circumvent the SDK setup intentionally,\n // NOTE: we could see this error when the DB is correct.\n const functionDefinition =\n runtimeClient.getFunctionDefinitionByName(functionName);\n\n console.log(\n `Found definition for \"${functionName}\": ${JSON.stringify(functionDefinition)}`,\n );\n\n // TODO: type this error\n if (!functionDefinition) {\n throw new Error(`Function \"${functionName}\" not found in registry`);\n }\n\n // Any errors caught by this block will be considered user code errors\n let result;\n try {\n console.log(`Executing function: ${functionName}`);\n result = await runtimeClient.executeFunction(event);\n console.log(`Received result: ${JSON.stringify(result)}`);\n } catch (error: unknown) {\n console.error(\"Handler error:\", error);\n await runtimeClient.handleFailure(requestId, error);\n return; // This invocation is done - don't call handleSuccess\n }\n\n await runtimeClient.handleSuccess(requestId, result);\n console.log(`Function \"${functionName}\" completed successfully`);\n } catch (error: unknown) {\n console.error(\"Fatal error in runtime loop:\", error);\n handleFatalError(error);\n }\n}\n\nexport async function runInvocationLoop(\n runtimeClient: IRuntimeClient,\n handleProductionFailure: (error: unknown) => void,\n): Promise<void> {\n while (true) {\n await waitForAndHandleInvocation(runtimeClient, handleProductionFailure);\n }\n}\n","import { FunctionNotFoundInRegistryError } from \"../utils/errors.js\";\n\nimport type { FunctionInvocationContext } from \"../schemas/invocation.js\";\nimport type { FunctionManifest } from \"../types/definition.js\";\nimport type { FunctionHandlerCallbackReturnValue } from \"../types/handler.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nexport interface IFunctionRegistry {\n register<S extends JSONSchemaInput>(\n name: FunctionManifest<S>[\"name\"],\n handler: FunctionManifest<S>[\"handler\"],\n config: FunctionManifest<S>[\"config\"],\n ): void;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- this would need to be generic based on the `register` call\n getByName(name: string): FunctionManifest<any> | null;\n\n execute(\n name: string,\n params: object,\n context: FunctionInvocationContext,\n ): Promise<FunctionHandlerCallbackReturnValue>;\n\n get size(): number;\n}\n\nexport class FunctionRegistry implements IFunctionRegistry {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- this would need to be generic based on the `register` call\n private _functions = new Map<string, FunctionManifest<any>>();\n\n register<S extends JSONSchemaInput>(\n name: FunctionManifest<S>[\"name\"],\n handler: FunctionManifest<S>[\"handler\"],\n config: FunctionManifest<S>[\"config\"],\n ) {\n this._functions.set(name, {\n name,\n handler,\n config,\n });\n }\n\n public getByName(name: string): FunctionManifest<unknown> | null {\n return this._functions.get(name) ?? null;\n }\n\n async execute(\n name: string,\n params: object,\n context: FunctionInvocationContext,\n ) {\n const foundDefinition = this._functions.get(name);\n if (!foundDefinition) {\n throw new FunctionNotFoundInRegistryError(\n `Couldn't find function with name \"${name}\" in registry`,\n );\n }\n\n const handlerResult = await foundDefinition.handler(context, params);\n\n // TODO: Remove when we have a better structured logging story\n console.log(\"handlerResult\", handlerResult);\n\n return handlerResult;\n }\n\n get size() {\n return this._functions.size;\n }\n}\n","export interface IEnvironmentManager {\n get environment(): string;\n get runtimeApi(): string;\n get phase(): string;\n}\n\nexport class EnvironmentManager {\n /// Whether we're running these locally or deployed (\"production\").\n /// Locally we are more forgiving on failures, and will change logging.\n private _environment: \"local\" | \"production\";\n\n /// The URL that is used to alert the runtime to the status of the invocation.\n /// Locally this will point to the URL of the dev server being run, in prod this\n /// will point to the runtime's internal endpoints.\n private _runtimeApi: string;\n\n /// We need to handle running a function differently than we handle\n /// deploying a function. The \"runtime\" phase is when we're trying to\n /// run a function by name (either locally or in prod). The \"build\"\n /// phase is when we're generating local manifest files to send to\n /// the Browserbase API. Defaults to runtime phase.\n private _phase: \"runtime\" | \"introspect\";\n\n constructor(processEnv: NodeJS.ProcessEnv) {\n this._environment = getOrDefault<typeof this._environment>(\n processEnv,\n \"NODE_ENV\",\n \"local\",\n );\n\n this._runtimeApi = getOrDefault<typeof this._runtimeApi>(\n processEnv,\n \"AWS_LAMBDA_RUNTIME_API\",\n \"127.0.0.1:14113\",\n );\n\n this._phase = getOrDefault<typeof this._phase>(\n processEnv,\n \"BB_FUNCTIONS_PHASE\",\n \"runtime\",\n );\n }\n\n get environment() {\n return this._environment;\n }\n\n get runtimeApi() {\n return this._runtimeApi;\n }\n\n get phase() {\n return this._phase;\n }\n}\n\nfunction getOrDefault<T>(env: NodeJS.ProcessEnv, key: string, dflt: T): T {\n const val = env[key];\n if (!val) {\n return dflt;\n }\n return val as T;\n}\n","import { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport z from \"zod\";\n\nimport type {\n FunctionManifest,\n PersistedFunctionManifest,\n} from \"../types/definition.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nexport function writeManifestToDisk<S extends JSONSchemaInput>(\n manifest: FunctionManifest<S>,\n manifestsDir: string,\n isFirstInvocation: boolean,\n) {\n if (isFirstInvocation) {\n // Clear manifests directory if it exists to remove stale menifests\n if (existsSync(manifestsDir)) {\n rmSync(manifestsDir, { recursive: true });\n }\n\n mkdirSync(manifestsDir, { recursive: true });\n }\n\n const persistedManifest = buildPersistedFunctionManifest(manifest);\n\n writeFileSync(\n join(manifestsDir, `${manifest.name}.json`),\n JSON.stringify(persistedManifest, null, 2),\n );\n}\n\nexport function buildPersistedFunctionManifest<S extends JSONSchemaInput>(\n manifest: FunctionManifest<S>,\n): PersistedFunctionManifest<S> {\n const { name, config } = manifest;\n const { parametersSchema, ...configWithoutSchema } = config;\n\n const processedConfig: PersistedFunctionManifest<S>[\"config\"] = {\n ...configWithoutSchema,\n };\n\n if (parametersSchema) {\n processedConfig.parametersSchema =\n buildPersistedJsonSchema(parametersSchema);\n }\n\n const processedManifest: PersistedFunctionManifest<S> = {\n name,\n config: processedConfig,\n };\n\n return processedManifest;\n}\n\nexport function buildPersistedJsonSchema(input: JSONSchemaInput): object {\n if (input instanceof z.ZodObject) {\n return z.toJSONSchema(input);\n }\n\n return {};\n}\n","import { join } from \"node:path\";\n\nimport type { FunctionConfiguration } from \"../types/definition.js\";\nimport type { FunctionHandler } from \"../types/handler.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nimport { writeManifestToDisk } from \"./helpers.js\";\n\n// Singleton imports\nimport { environmentManager, functionsRegistry } from \"../index.js\";\n\n/// TODO: Write good documentation here\nexport function defineFn<S extends JSONSchemaInput = unknown>(\n name: string,\n handler: FunctionHandler<S>,\n config: FunctionConfiguration<S> = {},\n): void {\n functionsRegistry.register(name, handler, config);\n\n if (\n // The CLI needs \"local\" to know how to create sessions with\n // non-default configurations during the local dev flow\n environmentManager.phase === \"introspect\" ||\n environmentManager.environment === \"local\"\n ) {\n const manifestsDir = join(\n process.cwd(),\n \".browserbase\",\n \"functions\",\n \"manifests\",\n );\n\n const isFirstInvocation = functionsRegistry.size === 1;\n\n writeManifestToDisk(\n { name, handler, config },\n manifestsDir,\n isFirstInvocation,\n );\n }\n}\n","import { RuntimeClient } from \"./runtime/index.js\";\nimport { runInvocationLoop } from \"./runtime/loop.js\";\nimport { FunctionRegistry } from \"./runtime/registry.js\";\nimport { EnvironmentManager } from \"./utils/env.js\";\n\nexport { defineFn } from \"./define/index.js\";\n\nexport const environmentManager = new EnvironmentManager(process.env);\nexport const functionsRegistry = new FunctionRegistry();\nexport const runtimeClient = new RuntimeClient(\n functionsRegistry,\n environmentManager.runtimeApi,\n);\n\nfunction handleInvocationLoopFailure(error: unknown): void {\n console.error(\"Received fatal error from invocation loop\", error);\n process.exit(1);\n}\n// We only want to listen for invocations iff we're in the \"runtime\" phase\nif (environmentManager.phase === \"runtime\") {\n runInvocationLoop(runtimeClient, handleInvocationLoopFailure).catch(\n (error: unknown) => {\n console.error(\"Fatal runtime error:\", error);\n process.exit(1);\n },\n );\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -6,8 +6,8 @@ declare const FunctionInvocationContext: z__default.ZodObject<{
6
6
  session: z__default.ZodObject<{
7
7
  id: z__default.ZodString;
8
8
  connectUrl: z__default.ZodString;
9
- }, z__default.z.core.$strip>;
10
- }, z__default.z.core.$strip>;
9
+ }, z__default.z.core.$loose>;
10
+ }, z__default.z.core.$loose>;
11
11
  type FunctionInvocationContext = z__default.infer<typeof FunctionInvocationContext>;
12
12
 
13
13
  type JSONValue = string | number | boolean | null | JSONValue[] | {
@@ -55,8 +55,8 @@ declare const RuntimeEventPayload: z__default.ZodObject<{
55
55
  session: z__default.ZodObject<{
56
56
  id: z__default.ZodString;
57
57
  connectUrl: z__default.ZodString;
58
- }, z__default.z.core.$strip>;
59
- }, z__default.z.core.$strip>;
58
+ }, z__default.z.core.$loose>;
59
+ }, z__default.z.core.$loose>;
60
60
  }, z__default.z.core.$strip>;
61
61
  type RuntimeEventPayload = z__default.infer<typeof RuntimeEventPayload>;
62
62
  declare const RuntimeEvent: z__default.ZodObject<{
@@ -68,8 +68,8 @@ declare const RuntimeEvent: z__default.ZodObject<{
68
68
  session: z__default.ZodObject<{
69
69
  id: z__default.ZodString;
70
70
  connectUrl: z__default.ZodString;
71
- }, z__default.z.core.$strip>;
72
- }, z__default.z.core.$strip>;
71
+ }, z__default.z.core.$loose>;
72
+ }, z__default.z.core.$loose>;
73
73
  }, z__default.z.core.$strip>;
74
74
  }, z__default.z.core.$strip>;
75
75
  type RuntimeEvent = z__default.infer<typeof RuntimeEvent>;
package/dist/index.d.ts CHANGED
@@ -6,8 +6,8 @@ declare const FunctionInvocationContext: z__default.ZodObject<{
6
6
  session: z__default.ZodObject<{
7
7
  id: z__default.ZodString;
8
8
  connectUrl: z__default.ZodString;
9
- }, z__default.z.core.$strip>;
10
- }, z__default.z.core.$strip>;
9
+ }, z__default.z.core.$loose>;
10
+ }, z__default.z.core.$loose>;
11
11
  type FunctionInvocationContext = z__default.infer<typeof FunctionInvocationContext>;
12
12
 
13
13
  type JSONValue = string | number | boolean | null | JSONValue[] | {
@@ -55,8 +55,8 @@ declare const RuntimeEventPayload: z__default.ZodObject<{
55
55
  session: z__default.ZodObject<{
56
56
  id: z__default.ZodString;
57
57
  connectUrl: z__default.ZodString;
58
- }, z__default.z.core.$strip>;
59
- }, z__default.z.core.$strip>;
58
+ }, z__default.z.core.$loose>;
59
+ }, z__default.z.core.$loose>;
60
60
  }, z__default.z.core.$strip>;
61
61
  type RuntimeEventPayload = z__default.infer<typeof RuntimeEventPayload>;
62
62
  declare const RuntimeEvent: z__default.ZodObject<{
@@ -68,8 +68,8 @@ declare const RuntimeEvent: z__default.ZodObject<{
68
68
  session: z__default.ZodObject<{
69
69
  id: z__default.ZodString;
70
70
  connectUrl: z__default.ZodString;
71
- }, z__default.z.core.$strip>;
72
- }, z__default.z.core.$strip>;
71
+ }, z__default.z.core.$loose>;
72
+ }, z__default.z.core.$loose>;
73
73
  }, z__default.z.core.$strip>;
74
74
  }, z__default.z.core.$strip>;
75
75
  type RuntimeEvent = z__default.infer<typeof RuntimeEvent>;
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import a from 'zod';
2
2
  import { join } from 'path';
3
3
  import { existsSync, rmSync, mkdirSync, writeFileSync } from 'fs';
4
4
 
5
- var b=Object.defineProperty;var M=(n,t,e)=>t in n?b(n,t,{enumerable:true,configurable:true,writable:true,value:e}):n[t]=e;var s=(n,t,e)=>M(n,typeof t!="symbol"?t+"":t,e);var m=class extends Error{constructor(t){super(t);}},f=class extends Error{constructor(t){super(t);}},l=class extends Error{constructor(t){super(t);}},d=class extends Error{constructor(t){super(t);}};var N=a.object({id:a.string(),connectUrl:a.string()}),w=a.object({session:N});var x=a.object({functionName:a.string().min(1),params:a.looseObject({}),context:w});a.object({requestId:a.string().min(1),event:x});a.object({errorMessage:a.string().min(1),errorType:a.string().min(1),stackTrace:a.array(a.string().min(1))});var y=class{constructor(t,e){s(this,"runtimeApi");s(this,"baseUrl");s(this,"registry");this.runtimeApi=e,this.baseUrl=`http://${this.runtimeApi}/2018-06-01/runtime`,this.registry=t;}async waitForNextInvocation(){let t=await fetch(`${this.baseUrl}/invocation/next`);if(!t.ok)throw new f(`Next invocation failed: ${t.status} ${t.statusText}`);let e=t.headers.get("Lambda-Runtime-Aws-Request-Id")||"unknown",o=t.headers.get("Lambda-Runtime-Trace-Id");o&&(process.env._X_AMZN_TRACE_ID=o);let i=await t.text(),r=JSON.parse(i),c=x.safeParse(r);if(!c.success)throw new Error("Failed to parse event into runtime event");let p=c.data;return {requestId:e,event:p}}getFunctionDefinitionByName(t){return this.registry.getByName(t)}executeFunction(t){return this.registry.execute(t.functionName,t.params??{},t.context)}async handleSuccess(t,e){let o=await fetch(`${this.baseUrl}/invocation/${encodeURIComponent(t)}/response`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new l(`Failed to post response: ${o.status} ${o.statusText}`)}async handleFailure(t,e){let o=E(e),i=await fetch(`${this.baseUrl}/invocation/${encodeURIComponent(t)}/error`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new d(`Failed to post error: ${i.status} ${i.statusText}`)}};function E(n){if(n instanceof Error)return {errorMessage:n.message,errorType:n.name,stackTrace:n.stack?.split("/n")??[]};let t="An unknown error occurred",e="UnknownError",o=[];return typeof n=="string"?{errorMessage:n,errorType:e,stackTrace:o}:typeof n!="object"||n===null?{errorMessage:String(n),errorType:e,stackTrace:o}:("message"in n&&typeof n.message=="string"&&(t=n.message),"name"in n&&typeof n.name=="string"&&(e=n.name),"stack"in n&&Array.isArray(n.stack)&&typeof n.stack[0]=="string"&&(o=n.stack),{errorMessage:t,errorType:e,stackTrace:o})}async function P(n,t){try{let{requestId:e,event:o}=await n.waitForNextInvocation();console.log(`Received invocation with requestId: ${e}`);let{functionName:i}=o,r=n.getFunctionDefinitionByName(i);if(console.log(`Found definition for "${i}": ${JSON.stringify(r)}`),!r)throw new Error(`Function "${i}" not found in registry`);let c;try{console.log(`Executing function: ${i}`),c=await n.executeFunction(o),console.log(`Received result: ${JSON.stringify(c)}`);}catch(p){console.error("Handler error:",p),await n.handleFailure(e,p);return}await n.handleSuccess(e,c),console.log(`Function "${i}" completed successfully`);}catch(e){console.error("Fatal error in runtime loop:",e),t(e);}}async function I(n,t){for(;;)await P(n,t);}var h=class{constructor(){s(this,"_functions",new Map);}register(t,e,o){this._functions.set(t,{name:t,handler:e,config:o});}getByName(t){return this._functions.get(t)??null}async execute(t,e,o){let i=this._functions.get(t);if(!i)throw new m(`Couldn't find function with name "${t}" in registry`);let r=await i.handler(o,e);return console.log("handlerResult",r),r}get size(){return this._functions.size}};var v=class{constructor(t){s(this,"_environment");s(this,"_runtimeApi");s(this,"_phase");this._environment=S(t,"NODE_ENV","local"),this._runtimeApi=S(t,"AWS_LAMBDA_RUNTIME_API","127.0.0.1:14113"),this._phase=S(t,"BB_FUNCTIONS_PHASE","runtime");}get environment(){return this._environment}get runtimeApi(){return this._runtimeApi}get phase(){return this._phase}};function S(n,t,e){let o=n[t];return o||e}function k(n,t,e){e&&(existsSync(t)&&rmSync(t,{recursive:true}),mkdirSync(t,{recursive:true}));let o=A(n);writeFileSync(join(t,`${n.name}.json`),JSON.stringify(o,null,2));}function A(n){let{name:t,config:e}=n,{parametersSchema:o,...i}=e,r={...i};return o&&(r.parametersSchema=$(o)),{name:t,config:r}}function $(n){return n instanceof a.ZodObject?a.toJSONSchema(n):{}}function D(n,t,e={}){if(F.register(n,t,e),u.phase==="introspect"||u.environment==="local"){let o=join(process.cwd(),".browserbase","functions","manifests"),i=F.size===1;k({name:n,config:e},o,i);}}var u=new v(process.env),F=new h,z=new y(F,u.runtimeApi);function H(n){console.error("Received fatal error from invocation loop",n),process.exit(1);}u.phase==="runtime"&&I(z,H).catch(n=>{console.error("Fatal runtime error:",n),process.exit(1);});
5
+ var b=Object.defineProperty;var M=(n,t,e)=>t in n?b(n,t,{enumerable:true,configurable:true,writable:true,value:e}):n[t]=e;var s=(n,t,e)=>M(n,typeof t!="symbol"?t+"":t,e);var m=class extends Error{constructor(t){super(t);}},f=class extends Error{constructor(t){super(t);}},l=class extends Error{constructor(t){super(t);}},d=class extends Error{constructor(t){super(t);}};var N=a.looseObject({id:a.string(),connectUrl:a.string()}),w=a.looseObject({session:N});var x=a.object({functionName:a.string().min(1),params:a.looseObject({}),context:w});a.object({requestId:a.string().min(1),event:x});a.object({errorMessage:a.string().min(1),errorType:a.string().min(1),stackTrace:a.array(a.string().min(1))});var y=class{constructor(t,e){s(this,"runtimeApi");s(this,"baseUrl");s(this,"registry");this.runtimeApi=e,this.baseUrl=`http://${this.runtimeApi}/2018-06-01/runtime`,this.registry=t;}async waitForNextInvocation(){let t=await fetch(`${this.baseUrl}/invocation/next`);if(!t.ok)throw new f(`Next invocation failed: ${t.status} ${t.statusText}`);let e=t.headers.get("Lambda-Runtime-Aws-Request-Id")||"unknown",o=t.headers.get("Lambda-Runtime-Trace-Id");o&&(process.env._X_AMZN_TRACE_ID=o);let i=await t.text(),r=JSON.parse(i),c=x.safeParse(r);if(!c.success)throw new Error("Failed to parse event into runtime event");let p=c.data;return {requestId:e,event:p}}getFunctionDefinitionByName(t){return this.registry.getByName(t)}executeFunction(t){return this.registry.execute(t.functionName,t.params??{},t.context)}async handleSuccess(t,e){let o=await fetch(`${this.baseUrl}/invocation/${encodeURIComponent(t)}/response`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new l(`Failed to post response: ${o.status} ${o.statusText}`)}async handleFailure(t,e){let o=E(e),i=await fetch(`${this.baseUrl}/invocation/${encodeURIComponent(t)}/error`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new d(`Failed to post error: ${i.status} ${i.statusText}`)}};function E(n){if(n instanceof Error)return {errorMessage:n.message,errorType:n.name,stackTrace:n.stack?.split("/n")??[]};let t="An unknown error occurred",e="UnknownError",o=[];return typeof n=="string"?{errorMessage:n,errorType:e,stackTrace:o}:typeof n!="object"||n===null?{errorMessage:String(n),errorType:e,stackTrace:o}:("message"in n&&typeof n.message=="string"&&(t=n.message),"name"in n&&typeof n.name=="string"&&(e=n.name),"stack"in n&&Array.isArray(n.stack)&&typeof n.stack[0]=="string"&&(o=n.stack),{errorMessage:t,errorType:e,stackTrace:o})}async function P(n,t){try{let{requestId:e,event:o}=await n.waitForNextInvocation();console.log(`Received invocation with requestId: ${e}`);let{functionName:i}=o,r=n.getFunctionDefinitionByName(i);if(console.log(`Found definition for "${i}": ${JSON.stringify(r)}`),!r)throw new Error(`Function "${i}" not found in registry`);let c;try{console.log(`Executing function: ${i}`),c=await n.executeFunction(o),console.log(`Received result: ${JSON.stringify(c)}`);}catch(p){console.error("Handler error:",p),await n.handleFailure(e,p);return}await n.handleSuccess(e,c),console.log(`Function "${i}" completed successfully`);}catch(e){console.error("Fatal error in runtime loop:",e),t(e);}}async function I(n,t){for(;;)await P(n,t);}var h=class{constructor(){s(this,"_functions",new Map);}register(t,e,o){this._functions.set(t,{name:t,handler:e,config:o});}getByName(t){return this._functions.get(t)??null}async execute(t,e,o){let i=this._functions.get(t);if(!i)throw new m(`Couldn't find function with name "${t}" in registry`);let r=await i.handler(o,e);return console.log("handlerResult",r),r}get size(){return this._functions.size}};var v=class{constructor(t){s(this,"_environment");s(this,"_runtimeApi");s(this,"_phase");this._environment=S(t,"NODE_ENV","local"),this._runtimeApi=S(t,"AWS_LAMBDA_RUNTIME_API","127.0.0.1:14113"),this._phase=S(t,"BB_FUNCTIONS_PHASE","runtime");}get environment(){return this._environment}get runtimeApi(){return this._runtimeApi}get phase(){return this._phase}};function S(n,t,e){let o=n[t];return o||e}function k(n,t,e){e&&(existsSync(t)&&rmSync(t,{recursive:true}),mkdirSync(t,{recursive:true}));let o=A(n);writeFileSync(join(t,`${n.name}.json`),JSON.stringify(o,null,2));}function A(n){let{name:t,config:e}=n,{parametersSchema:o,...i}=e,r={...i};return o&&(r.parametersSchema=$(o)),{name:t,config:r}}function $(n){return n instanceof a.ZodObject?a.toJSONSchema(n):{}}function D(n,t,e={}){if(F.register(n,t,e),u.phase==="introspect"||u.environment==="local"){let o=join(process.cwd(),".browserbase","functions","manifests"),i=F.size===1;k({name:n,config:e},o,i);}}var u=new v(process.env),F=new h,z=new y(F,u.runtimeApi);function H(n){console.error("Received fatal error from invocation loop",n),process.exit(1);}u.phase==="runtime"&&I(z,H).catch(n=>{console.error("Fatal runtime error:",n),process.exit(1);});
6
6
 
7
7
  export { D as defineFn, u as environmentManager, F as functionsRegistry, z as runtimeClient };
8
8
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/errors.ts","../src/schemas/invocation.ts","../src/schemas/events.ts","../src/runtime/index.ts","../src/runtime/loop.ts","../src/runtime/registry.ts","../src/utils/env.ts","../src/define/helpers.ts","../src/define/index.ts","../src/index.ts"],"names":["FunctionNotFoundInRegistryError","message","GetNextInvocationError","PostResultError","PostErrorError","FunctionInvocationContextSessionDetails","z","FunctionInvocationContext","RuntimeEventPayload","RuntimeClient","registry","runtimeApi","__publicField","response","requestId","traceId","text","parsedData","safeParseResult","event","name","result","error","runtimeError","formatRuntimeError","type","stack","waitForAndHandleInvocation","runtimeClient","handleFatalError","functionName","functionDefinition","runInvocationLoop","handleProductionFailure","FunctionRegistry","handler","config","params","context","foundDefinition","handlerResult","EnvironmentManager","processEnv","getOrDefault","env","key","dflt","val","writeManifestToDisk","manifest","manifestsDir","isFirstInvocation","existsSync","rmSync","mkdirSync","persistedManifest","buildPersistedFunctionManifest","writeFileSync","join","parametersSchema","configWithoutSchema","processedConfig","buildPersistedJsonSchema","input","defineFn","functionsRegistry","environmentManager","handleInvocationLoopFailure"],"mappings":";;;;0KAAO,IAAMA,CAAAA,CAAN,cAA8C,KAAM,CACzD,WAAA,CAAYC,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaC,CAAAA,CAAN,cAAqC,KAAM,CAChD,WAAA,CAAYD,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaE,CAAAA,CAAN,cAA8B,KAAM,CACzC,WAAA,CAAYF,EAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaG,CAAAA,CAAN,cAA6B,KAAM,CACxC,WAAA,CAAYH,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CCpBO,IAAMI,CAAAA,CAA0CC,CAAAA,CAAE,MAAA,CAAO,CAC9D,EAAA,CAAIA,EAAE,MAAA,EAAO,CACb,UAAA,CAAYA,CAAAA,CAAE,MAAA,EAChB,CAAC,CAAA,CAMYC,CAAAA,CAA4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ructor(message: string) {\n super(message);\n }\n}\n\nexport class GetNextInvocationError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class PostResultError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class PostErrorError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n","import z from \"zod\";\n\nexport const FunctionInvocationContextSessionDetails = z.object({\n id: z.string(),\n connectUrl: z.string(),\n});\n\nexport type FunctionInvocationContextSessionDetails = z.infer<\n typeof FunctionInvocationContextSessionDetails\n>;\n\nexport const FunctionInvocationContext = z.object({\n session: FunctionInvocationContextSessionDetails,\n});\n\nexport type FunctionInvocationContext = z.infer<\n typeof FunctionInvocationContext\n>;\n","import z from \"zod\";\nimport { FunctionInvocationContext } from \"./invocation.js\";\n\nexport const RuntimeEventPayload = z.object({\n functionName: z.string().min(1),\n params: z.looseObject({}), // Allow passthrough of unknown (all) keys\n context: FunctionInvocationContext,\n});\n\nexport type RuntimeEventPayload = z.infer<typeof RuntimeEventPayload>;\n\nexport const RuntimeEvent = z.object({\n requestId: z.string().min(1),\n event: RuntimeEventPayload,\n});\n\nexport type RuntimeEvent = z.infer<typeof RuntimeEvent>;\n\nexport const RuntimeError = z.object({\n errorMessage: z.string().min(1),\n errorType: z.string().min(1),\n stackTrace: z.array(z.string().min(1)),\n});\n\nexport type RuntimeError = z.infer<typeof RuntimeError>;\n","import type { FunctionRegistry } from \"../runtime/registry.js\";\nimport {\n GetNextInvocationError,\n PostErrorError,\n PostResultError,\n} from \"../utils/errors.js\";\nimport {\n RuntimeError,\n RuntimeEvent,\n RuntimeEventPayload,\n} from \"../schemas/events.js\";\nimport type { FunctionManifest } from \"../types/definition.js\";\nimport type { FunctionHandlerCallbackReturnValue } from \"../types/handler.js\";\n\nexport interface IRuntimeClient {\n waitForNextInvocation(): Promise<RuntimeEvent>;\n getFunctionDefinitionByName(name: string): FunctionManifest<unknown> | null;\n\n executeFunction(\n event: RuntimeEventPayload,\n ): Promise<FunctionHandlerCallbackReturnValue>;\n\n handleSuccess(\n requestId: string,\n result: FunctionHandlerCallbackReturnValue,\n ): Promise<void>;\n\n handleFailure(requestId: string, error: unknown): Promise<void>;\n}\n\nexport class RuntimeClient implements IRuntimeClient {\n private runtimeApi: string;\n private baseUrl: string;\n private registry: FunctionRegistry;\n\n constructor(registry: FunctionRegistry, runtimeApi: string) {\n this.runtimeApi = runtimeApi;\n this.baseUrl = `http://${this.runtimeApi}/2018-06-01/runtime`;\n this.registry = registry;\n }\n\n public async waitForNextInvocation(): Promise<RuntimeEvent> {\n const response = await fetch(`${this.baseUrl}/invocation/next`);\n if (!response.ok) {\n throw new GetNextInvocationError(\n `Next invocation failed: ${response.status} ${response.statusText}`,\n );\n }\n\n const requestId =\n response.headers.get(\"Lambda-Runtime-Aws-Request-Id\") || \"unknown\";\n const traceId = response.headers.get(\"Lambda-Runtime-Trace-Id\");\n\n // This is to allow the X-Ray SDK to trace across invocations\n if (traceId) {\n process.env[\"_X_AMZN_TRACE_ID\"] = traceId;\n }\n\n const text = await response.text();\n const parsedData = JSON.parse(text);\n\n const safeParseResult = RuntimeEventPayload.safeParse(parsedData);\n if (!safeParseResult.success) {\n // TODO: type error\n throw new Error(\"Failed to parse event into runtime event\");\n }\n\n const event = safeParseResult.data;\n return { requestId, event };\n }\n\n public getFunctionDefinitionByName(\n name: string,\n ): FunctionManifest<unknown> | null {\n return this.registry.getByName(name);\n }\n\n public executeFunction(\n event: RuntimeEventPayload,\n ): Promise<FunctionHandlerCallbackReturnValue> {\n return this.registry.execute(\n event.functionName,\n event.params ?? {},\n event.context,\n );\n }\n\n public async handleSuccess(\n requestId: string,\n result: FunctionHandlerCallbackReturnValue,\n ): Promise<void> {\n const response = await fetch(\n `${this.baseUrl}/invocation/${encodeURIComponent(requestId)}/response`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(result),\n },\n );\n\n if (!response.ok) {\n throw new PostResultError(\n `Failed to post response: ${response.status} ${response.statusText}`,\n );\n }\n }\n\n public async handleFailure(requestId: string, error: unknown): Promise<void> {\n const runtimeError = formatRuntimeError(error);\n\n const response = await fetch(\n `${this.baseUrl}/invocation/${encodeURIComponent(requestId)}/error`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(runtimeError),\n },\n );\n\n if (!response.ok) {\n throw new PostErrorError(\n `Failed to post error: ${response.status} ${response.statusText}`,\n );\n }\n }\n}\n\nfunction formatRuntimeError(error: unknown): RuntimeError {\n if (error instanceof Error) {\n return {\n errorMessage: error.message,\n errorType: error.name,\n stackTrace: error.stack?.split(\"/n\") ?? [],\n };\n }\n\n let message = \"An unknown error occurred\";\n let type = \"UnknownError\";\n let stack = [] as string[];\n\n if (typeof error === \"string\") {\n return {\n errorMessage: error,\n errorType: type,\n stackTrace: stack,\n };\n }\n\n if (typeof error !== \"object\" || error === null) {\n return {\n errorMessage: String(error),\n errorType: type,\n stackTrace: stack,\n };\n }\n\n if (\"message\" in error && typeof error.message === \"string\") {\n message = error.message;\n }\n\n if (\"name\" in error && typeof error.name === \"string\") {\n type = error.name;\n }\n\n if (\n \"stack\" in error &&\n Array.isArray(error.stack) &&\n typeof error.stack[0] === \"string\"\n ) {\n stack = error.stack;\n }\n\n return {\n errorMessage: message,\n errorType: type,\n stackTrace: stack,\n };\n}\n","import type { IRuntimeClient } from \"./index.js\";\n\nexport async function waitForAndHandleInvocation(\n runtimeClient: IRuntimeClient,\n handleFatalError: (error: unknown) => void,\n) {\n // Any errors caught by this block will be considered fatal system errors\n try {\n const { requestId, event } = await runtimeClient.waitForNextInvocation();\n console.log(`Received invocation with requestId: ${requestId}`);\n const { functionName } = event;\n\n // Validate that the specified function is in the registry.\n // If not, throw a system error as this means we've set up the DB wrong\n // and that the system thinks that function is here when it's not.\n // NOTE: If the user finds a way to circumvent the SDK setup intentionally,\n // NOTE: we could see this error when the DB is correct.\n const functionDefinition =\n runtimeClient.getFunctionDefinitionByName(functionName);\n\n console.log(\n `Found definition for \"${functionName}\": ${JSON.stringify(functionDefinition)}`,\n );\n\n // TODO: type this error\n if (!functionDefinition) {\n throw new Error(`Function \"${functionName}\" not found in registry`);\n }\n\n // Any errors caught by this block will be considered user code errors\n let result;\n try {\n console.log(`Executing function: ${functionName}`);\n result = await runtimeClient.executeFunction(event);\n console.log(`Received result: ${JSON.stringify(result)}`);\n } catch (error: unknown) {\n console.error(\"Handler error:\", error);\n await runtimeClient.handleFailure(requestId, error);\n return; // This invocation is done - don't call handleSuccess\n }\n\n await runtimeClient.handleSuccess(requestId, result);\n console.log(`Function \"${functionName}\" completed successfully`);\n } catch (error: unknown) {\n console.error(\"Fatal error in runtime loop:\", error);\n handleFatalError(error);\n }\n}\n\nexport async function runInvocationLoop(\n runtimeClient: IRuntimeClient,\n handleProductionFailure: (error: unknown) => void,\n): Promise<void> {\n while (true) {\n await waitForAndHandleInvocation(runtimeClient, handleProductionFailure);\n }\n}\n","import { FunctionNotFoundInRegistryError } from \"../utils/errors.js\";\n\nimport type { FunctionInvocationContext } from \"../schemas/invocation.js\";\nimport type { FunctionManifest } from \"../types/definition.js\";\nimport type { FunctionHandlerCallbackReturnValue } from \"../types/handler.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nexport interface IFunctionRegistry {\n register<S extends JSONSchemaInput>(\n name: FunctionManifest<S>[\"name\"],\n handler: FunctionManifest<S>[\"handler\"],\n config: FunctionManifest<S>[\"config\"],\n ): void;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- this would need to be generic based on the `register` call\n getByName(name: string): FunctionManifest<any> | null;\n\n execute(\n name: string,\n params: object,\n context: FunctionInvocationContext,\n ): Promise<FunctionHandlerCallbackReturnValue>;\n\n get size(): number;\n}\n\nexport class FunctionRegistry implements IFunctionRegistry {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- this would need to be generic based on the `register` call\n private _functions = new Map<string, FunctionManifest<any>>();\n\n register<S extends JSONSchemaInput>(\n name: FunctionManifest<S>[\"name\"],\n handler: FunctionManifest<S>[\"handler\"],\n config: FunctionManifest<S>[\"config\"],\n ) {\n this._functions.set(name, {\n name,\n handler,\n config,\n });\n }\n\n public getByName(name: string): FunctionManifest<unknown> | null {\n return this._functions.get(name) ?? null;\n }\n\n async execute(\n name: string,\n params: object,\n context: FunctionInvocationContext,\n ) {\n const foundDefinition = this._functions.get(name);\n if (!foundDefinition) {\n throw new FunctionNotFoundInRegistryError(\n `Couldn't find function with name \"${name}\" in registry`,\n );\n }\n\n const handlerResult = await foundDefinition.handler(context, params);\n\n // TODO: Remove when we have a better structured logging story\n console.log(\"handlerResult\", handlerResult);\n\n return handlerResult;\n }\n\n get size() {\n return this._functions.size;\n }\n}\n","export interface IEnvironmentManager {\n get environment(): string;\n get runtimeApi(): string;\n get phase(): string;\n}\n\nexport class EnvironmentManager {\n /// Whether we're running these locally or deployed (\"production\").\n /// Locally we are more forgiving on failures, and will change logging.\n private _environment: \"local\" | \"production\";\n\n /// The URL that is used to alert the runtime to the status of the invocation.\n /// Locally this will point to the URL of the dev server being run, in prod this\n /// will point to the runtime's internal endpoints.\n private _runtimeApi: string;\n\n /// We need to handle running a function differently than we handle\n /// deploying a function. The \"runtime\" phase is when we're trying to\n /// run a function by name (either locally or in prod). The \"build\"\n /// phase is when we're generating local manifest files to send to\n /// the Browserbase API. Defaults to runtime phase.\n private _phase: \"runtime\" | \"introspect\";\n\n constructor(processEnv: NodeJS.ProcessEnv) {\n this._environment = getOrDefault<typeof this._environment>(\n processEnv,\n \"NODE_ENV\",\n \"local\",\n );\n\n this._runtimeApi = getOrDefault<typeof this._runtimeApi>(\n processEnv,\n \"AWS_LAMBDA_RUNTIME_API\",\n \"127.0.0.1:14113\",\n );\n\n this._phase = getOrDefault<typeof this._phase>(\n processEnv,\n \"BB_FUNCTIONS_PHASE\",\n \"runtime\",\n );\n }\n\n get environment() {\n return this._environment;\n }\n\n get runtimeApi() {\n return this._runtimeApi;\n }\n\n get phase() {\n return this._phase;\n }\n}\n\nfunction getOrDefault<T>(env: NodeJS.ProcessEnv, key: string, dflt: T): T {\n const val = env[key];\n if (!val) {\n return dflt;\n }\n return val as T;\n}\n","import { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport z from \"zod\";\n\nimport type {\n FunctionManifest,\n PersistedFunctionManifest,\n} from \"../types/definition.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nexport function writeManifestToDisk<S extends JSONSchemaInput>(\n manifest: FunctionManifest<S>,\n manifestsDir: string,\n isFirstInvocation: boolean,\n) {\n if (isFirstInvocation) {\n // Clear manifests directory if it exists to remove stale menifests\n if (existsSync(manifestsDir)) {\n rmSync(manifestsDir, { recursive: true });\n }\n\n mkdirSync(manifestsDir, { recursive: true });\n }\n\n const persistedManifest = buildPersistedFunctionManifest(manifest);\n\n writeFileSync(\n join(manifestsDir, `${manifest.name}.json`),\n JSON.stringify(persistedManifest, null, 2),\n );\n}\n\nexport function buildPersistedFunctionManifest<S extends JSONSchemaInput>(\n manifest: FunctionManifest<S>,\n): PersistedFunctionManifest<S> {\n const { name, config } = manifest;\n const { parametersSchema, ...configWithoutSchema } = config;\n\n const processedConfig: PersistedFunctionManifest<S>[\"config\"] = {\n ...configWithoutSchema,\n };\n\n if (parametersSchema) {\n processedConfig.parametersSchema =\n buildPersistedJsonSchema(parametersSchema);\n }\n\n const processedManifest: PersistedFunctionManifest<S> = {\n name,\n config: processedConfig,\n };\n\n return processedManifest;\n}\n\nexport function buildPersistedJsonSchema(input: JSONSchemaInput): object {\n if (input instanceof z.ZodObject) {\n return z.toJSONSchema(input);\n }\n\n return {};\n}\n","import { join } from \"node:path\";\n\nimport type { FunctionConfiguration } from \"../types/definition.js\";\nimport type { FunctionHandler } from \"../types/handler.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nimport { writeManifestToDisk } from \"./helpers.js\";\n\n// Singleton imports\nimport { environmentManager, functionsRegistry } from \"../index.js\";\n\n/// TODO: Write good documentation here\nexport function defineFn<S extends JSONSchemaInput = unknown>(\n name: string,\n handler: FunctionHandler<S>,\n config: FunctionConfiguration<S> = {},\n): void {\n functionsRegistry.register(name, handler, config);\n\n if (\n // The CLI needs \"local\" to know how to create sessions with\n // non-default configurations during the local dev flow\n environmentManager.phase === \"introspect\" ||\n environmentManager.environment === \"local\"\n ) {\n const manifestsDir = join(\n process.cwd(),\n \".browserbase\",\n \"functions\",\n \"manifests\",\n );\n\n const isFirstInvocation = functionsRegistry.size === 1;\n\n writeManifestToDisk(\n { name, handler, config },\n manifestsDir,\n isFirstInvocation,\n );\n }\n}\n","import { RuntimeClient } from \"./runtime/index.js\";\nimport { runInvocationLoop } from \"./runtime/loop.js\";\nimport { FunctionRegistry } from \"./runtime/registry.js\";\nimport { EnvironmentManager } from \"./utils/env.js\";\n\nexport { defineFn } from \"./define/index.js\";\n\nexport const environmentManager = new EnvironmentManager(process.env);\nexport const functionsRegistry = new FunctionRegistry();\nexport const runtimeClient = new RuntimeClient(\n functionsRegistry,\n environmentManager.runtimeApi,\n);\n\nfunction handleInvocationLoopFailure(error: unknown): void {\n console.error(\"Received fatal error from invocation loop\", error);\n process.exit(1);\n}\n// We only want to listen for invocations iff we're in the \"runtime\" phase\nif (environmentManager.phase === \"runtime\") {\n runInvocationLoop(runtimeClient, handleInvocationLoopFailure).catch(\n (error: unknown) => {\n console.error(\"Fatal runtime error:\", error);\n process.exit(1);\n },\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/utils/errors.ts","../src/schemas/invocation.ts","../src/schemas/events.ts","../src/runtime/index.ts","../src/runtime/loop.ts","../src/runtime/registry.ts","../src/utils/env.ts","../src/define/helpers.ts","../src/define/index.ts","../src/index.ts"],"names":["FunctionNotFoundInRegistryError","message","GetNextInvocationError","PostResultError","PostErrorError","FunctionInvocationContextSessionDetails","z","FunctionInvocationContext","RuntimeEventPayload","RuntimeClient","registry","runtimeApi","__publicField","response","requestId","traceId","text","parsedData","safeParseResult","event","name","result","error","runtimeError","formatRuntimeError","type","stack","waitForAndHandleInvocation","runtimeClient","handleFatalError","functionName","functionDefinition","runInvocationLoop","handleProductionFailure","FunctionRegistry","handler","config","params","context","foundDefinition","handlerResult","EnvironmentManager","processEnv","getOrDefault","env","key","dflt","val","writeManifestToDisk","manifest","manifestsDir","isFirstInvocation","existsSync","rmSync","mkdirSync","persistedManifest","buildPersistedFunctionManifest","writeFileSync","join","parametersSchema","configWithoutSchema","processedConfig","buildPersistedJsonSchema","input","defineFn","functionsRegistry","environmentManager","handleInvocationLoopFailure"],"mappings":";;;;0KAAO,IAAMA,CAAAA,CAAN,cAA8C,KAAM,CACzD,WAAA,CAAYC,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaC,CAAAA,CAAN,cAAqC,KAAM,CAChD,WAAA,CAAYD,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaE,CAAAA,CAAN,cAA8B,KAAM,CACzC,WAAA,CAAYF,EAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CAEaG,CAAAA,CAAN,cAA6B,KAAM,CACxC,WAAA,CAAYH,CAAAA,CAAiB,CAC3B,KAAA,CAAMA,CAAO,EACf,CACF,CAAA,CCnBO,IAAMI,CAAAA,CAA0CC,CAAAA,CAAE,WAAA,CAAY,CACnE,EAAA,CAAIA,EAAE,MAAA,EAAO,CACb,UAAA,CAAYA,CAAAA,CAAE,MAAA,EAChB,CAAC,CAAA,CAOYC,CAAAA,CAA4BD,CAAAA,CAAE,WAAA,CAAY,CACrD,OAAA,CAASD,CACX,CAAC,CAAA,CCZM,IAAMG,CAAAA,CAAsBF,CAAAA,CAAE,MAAA,CAAO,CAC1C,YAAA,CAAcA,CAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CAC9B,MAAA,CAAQA,CAAAA,CAAE,WAAA,CAAY,EAAE,CAAA,CACxB,OAAA,CAASC,CACX,CAAC,CAAA,CAI2B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A,CAAmB,WAAA,GAAgB,OAAA,CACnC,CACA,IAAMhB,CAAAA,CAAeQ,IAAAA,CACnB,OAAA,CAAQ,GAAA,EAAI,CACZ,cAAA,CACA,WAAA,CACA,WACF,CAAA,CAEMP,CAAAA,CAAoBc,CAAAA,CAAkB,IAAA,GAAS,CAAA,CAErDjB,CAAAA,CACE,CAAE,IAAA,CAAA5B,EAAe,MAAA,CAAAgB,CAAO,CAAA,CACxBc,CAAAA,CACAC,CACF,EACF,CACF,CCjCO,IAAMe,CAAAA,CAAqB,IAAIzB,CAAAA,CAAmB,OAAA,CAAQ,GAAG,CAAA,CACvDwB,CAAAA,CAAoB,IAAI/B,CAAAA,CACxBN,CAAAA,CAAgB,IAAInB,CAAAA,CAC/BwD,CAAAA,CACAC,CAAAA,CAAmB,UACrB,EAEA,SAASC,CAAAA,CAA4B7C,CAAAA,CAAsB,CACzD,OAAA,CAAQ,KAAA,CAAM,2CAAA,CAA6CA,CAAK,CAAA,CAChE,OAAA,CAAQ,IAAA,CAAK,CAAC,EAChB,CAEI4C,CAAAA,CAAmB,KAAA,GAAU,SAAA,EAC/BlC,CAAAA,CAAkBJ,CAAAA,CAAeuC,CAA2B,CAAA,CAAE,KAAA,CAC3D7C,CAAAA,EAAmB,CAClB,OAAA,CAAQ,KAAA,CAAM,sBAAA,CAAwBA,CAAK,CAAA,CAC3C,OAAA,CAAQ,IAAA,CAAK,CAAC,EAChB,CACF,CAAA","file":"index.js","sourcesContent":["export class FunctionNotFoundInRegistryError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class GetNextInvocationError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class PostResultError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class PostErrorError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n","import z from \"zod\";\n\n// Allow in additional fields without needing to update the SDK version\nexport const FunctionInvocationContextSessionDetails = z.looseObject({\n id: z.string(),\n connectUrl: z.string(),\n});\n\nexport type FunctionInvocationContextSessionDetails = z.infer<\n typeof FunctionInvocationContextSessionDetails\n>;\n\n// Allow in additional fields without needing to update the SDK version\nexport const FunctionInvocationContext = z.looseObject({\n session: FunctionInvocationContextSessionDetails,\n});\n\nexport type FunctionInvocationContext = z.infer<\n typeof FunctionInvocationContext\n>;\n","import z from \"zod\";\nimport { FunctionInvocationContext } from \"./invocation.js\";\n\nexport const RuntimeEventPayload = z.object({\n functionName: z.string().min(1),\n params: z.looseObject({}), // Allow passthrough of unknown (all) keys\n context: FunctionInvocationContext,\n});\n\nexport type RuntimeEventPayload = z.infer<typeof RuntimeEventPayload>;\n\nexport const RuntimeEvent = z.object({\n requestId: z.string().min(1),\n event: RuntimeEventPayload,\n});\n\nexport type RuntimeEvent = z.infer<typeof RuntimeEvent>;\n\nexport const RuntimeError = z.object({\n errorMessage: z.string().min(1),\n errorType: z.string().min(1),\n stackTrace: z.array(z.string().min(1)),\n});\n\nexport type RuntimeError = z.infer<typeof RuntimeError>;\n","import type { FunctionRegistry } from \"../runtime/registry.js\";\nimport {\n GetNextInvocationError,\n PostErrorError,\n PostResultError,\n} from \"../utils/errors.js\";\nimport {\n RuntimeError,\n RuntimeEvent,\n RuntimeEventPayload,\n} from \"../schemas/events.js\";\nimport type { FunctionManifest } from \"../types/definition.js\";\nimport type { FunctionHandlerCallbackReturnValue } from \"../types/handler.js\";\n\nexport interface IRuntimeClient {\n waitForNextInvocation(): Promise<RuntimeEvent>;\n getFunctionDefinitionByName(name: string): FunctionManifest<unknown> | null;\n\n executeFunction(\n event: RuntimeEventPayload,\n ): Promise<FunctionHandlerCallbackReturnValue>;\n\n handleSuccess(\n requestId: string,\n result: FunctionHandlerCallbackReturnValue,\n ): Promise<void>;\n\n handleFailure(requestId: string, error: unknown): Promise<void>;\n}\n\nexport class RuntimeClient implements IRuntimeClient {\n private runtimeApi: string;\n private baseUrl: string;\n private registry: FunctionRegistry;\n\n constructor(registry: FunctionRegistry, runtimeApi: string) {\n this.runtimeApi = runtimeApi;\n this.baseUrl = `http://${this.runtimeApi}/2018-06-01/runtime`;\n this.registry = registry;\n }\n\n public async waitForNextInvocation(): Promise<RuntimeEvent> {\n const response = await fetch(`${this.baseUrl}/invocation/next`);\n if (!response.ok) {\n throw new GetNextInvocationError(\n `Next invocation failed: ${response.status} ${response.statusText}`,\n );\n }\n\n const requestId =\n response.headers.get(\"Lambda-Runtime-Aws-Request-Id\") || \"unknown\";\n const traceId = response.headers.get(\"Lambda-Runtime-Trace-Id\");\n\n // This is to allow the X-Ray SDK to trace across invocations\n if (traceId) {\n process.env[\"_X_AMZN_TRACE_ID\"] = traceId;\n }\n\n const text = await response.text();\n const parsedData = JSON.parse(text);\n\n const safeParseResult = RuntimeEventPayload.safeParse(parsedData);\n if (!safeParseResult.success) {\n // TODO: type error\n throw new Error(\"Failed to parse event into runtime event\");\n }\n\n const event = safeParseResult.data;\n return { requestId, event };\n }\n\n public getFunctionDefinitionByName(\n name: string,\n ): FunctionManifest<unknown> | null {\n return this.registry.getByName(name);\n }\n\n public executeFunction(\n event: RuntimeEventPayload,\n ): Promise<FunctionHandlerCallbackReturnValue> {\n return this.registry.execute(\n event.functionName,\n event.params ?? {},\n event.context,\n );\n }\n\n public async handleSuccess(\n requestId: string,\n result: FunctionHandlerCallbackReturnValue,\n ): Promise<void> {\n const response = await fetch(\n `${this.baseUrl}/invocation/${encodeURIComponent(requestId)}/response`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(result),\n },\n );\n\n if (!response.ok) {\n throw new PostResultError(\n `Failed to post response: ${response.status} ${response.statusText}`,\n );\n }\n }\n\n public async handleFailure(requestId: string, error: unknown): Promise<void> {\n const runtimeError = formatRuntimeError(error);\n\n const response = await fetch(\n `${this.baseUrl}/invocation/${encodeURIComponent(requestId)}/error`,\n {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(runtimeError),\n },\n );\n\n if (!response.ok) {\n throw new PostErrorError(\n `Failed to post error: ${response.status} ${response.statusText}`,\n );\n }\n }\n}\n\nfunction formatRuntimeError(error: unknown): RuntimeError {\n if (error instanceof Error) {\n return {\n errorMessage: error.message,\n errorType: error.name,\n stackTrace: error.stack?.split(\"/n\") ?? [],\n };\n }\n\n let message = \"An unknown error occurred\";\n let type = \"UnknownError\";\n let stack = [] as string[];\n\n if (typeof error === \"string\") {\n return {\n errorMessage: error,\n errorType: type,\n stackTrace: stack,\n };\n }\n\n if (typeof error !== \"object\" || error === null) {\n return {\n errorMessage: String(error),\n errorType: type,\n stackTrace: stack,\n };\n }\n\n if (\"message\" in error && typeof error.message === \"string\") {\n message = error.message;\n }\n\n if (\"name\" in error && typeof error.name === \"string\") {\n type = error.name;\n }\n\n if (\n \"stack\" in error &&\n Array.isArray(error.stack) &&\n typeof error.stack[0] === \"string\"\n ) {\n stack = error.stack;\n }\n\n return {\n errorMessage: message,\n errorType: type,\n stackTrace: stack,\n };\n}\n","import type { IRuntimeClient } from \"./index.js\";\n\nexport async function waitForAndHandleInvocation(\n runtimeClient: IRuntimeClient,\n handleFatalError: (error: unknown) => void,\n) {\n // Any errors caught by this block will be considered fatal system errors\n try {\n const { requestId, event } = await runtimeClient.waitForNextInvocation();\n console.log(`Received invocation with requestId: ${requestId}`);\n const { functionName } = event;\n\n // Validate that the specified function is in the registry.\n // If not, throw a system error as this means we've set up the DB wrong\n // and that the system thinks that function is here when it's not.\n // NOTE: If the user finds a way to circumvent the SDK setup intentionally,\n // NOTE: we could see this error when the DB is correct.\n const functionDefinition =\n runtimeClient.getFunctionDefinitionByName(functionName);\n\n console.log(\n `Found definition for \"${functionName}\": ${JSON.stringify(functionDefinition)}`,\n );\n\n // TODO: type this error\n if (!functionDefinition) {\n throw new Error(`Function \"${functionName}\" not found in registry`);\n }\n\n // Any errors caught by this block will be considered user code errors\n let result;\n try {\n console.log(`Executing function: ${functionName}`);\n result = await runtimeClient.executeFunction(event);\n console.log(`Received result: ${JSON.stringify(result)}`);\n } catch (error: unknown) {\n console.error(\"Handler error:\", error);\n await runtimeClient.handleFailure(requestId, error);\n return; // This invocation is done - don't call handleSuccess\n }\n\n await runtimeClient.handleSuccess(requestId, result);\n console.log(`Function \"${functionName}\" completed successfully`);\n } catch (error: unknown) {\n console.error(\"Fatal error in runtime loop:\", error);\n handleFatalError(error);\n }\n}\n\nexport async function runInvocationLoop(\n runtimeClient: IRuntimeClient,\n handleProductionFailure: (error: unknown) => void,\n): Promise<void> {\n while (true) {\n await waitForAndHandleInvocation(runtimeClient, handleProductionFailure);\n }\n}\n","import { FunctionNotFoundInRegistryError } from \"../utils/errors.js\";\n\nimport type { FunctionInvocationContext } from \"../schemas/invocation.js\";\nimport type { FunctionManifest } from \"../types/definition.js\";\nimport type { FunctionHandlerCallbackReturnValue } from \"../types/handler.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nexport interface IFunctionRegistry {\n register<S extends JSONSchemaInput>(\n name: FunctionManifest<S>[\"name\"],\n handler: FunctionManifest<S>[\"handler\"],\n config: FunctionManifest<S>[\"config\"],\n ): void;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- this would need to be generic based on the `register` call\n getByName(name: string): FunctionManifest<any> | null;\n\n execute(\n name: string,\n params: object,\n context: FunctionInvocationContext,\n ): Promise<FunctionHandlerCallbackReturnValue>;\n\n get size(): number;\n}\n\nexport class FunctionRegistry implements IFunctionRegistry {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- this would need to be generic based on the `register` call\n private _functions = new Map<string, FunctionManifest<any>>();\n\n register<S extends JSONSchemaInput>(\n name: FunctionManifest<S>[\"name\"],\n handler: FunctionManifest<S>[\"handler\"],\n config: FunctionManifest<S>[\"config\"],\n ) {\n this._functions.set(name, {\n name,\n handler,\n config,\n });\n }\n\n public getByName(name: string): FunctionManifest<unknown> | null {\n return this._functions.get(name) ?? null;\n }\n\n async execute(\n name: string,\n params: object,\n context: FunctionInvocationContext,\n ) {\n const foundDefinition = this._functions.get(name);\n if (!foundDefinition) {\n throw new FunctionNotFoundInRegistryError(\n `Couldn't find function with name \"${name}\" in registry`,\n );\n }\n\n const handlerResult = await foundDefinition.handler(context, params);\n\n // TODO: Remove when we have a better structured logging story\n console.log(\"handlerResult\", handlerResult);\n\n return handlerResult;\n }\n\n get size() {\n return this._functions.size;\n }\n}\n","export interface IEnvironmentManager {\n get environment(): string;\n get runtimeApi(): string;\n get phase(): string;\n}\n\nexport class EnvironmentManager {\n /// Whether we're running these locally or deployed (\"production\").\n /// Locally we are more forgiving on failures, and will change logging.\n private _environment: \"local\" | \"production\";\n\n /// The URL that is used to alert the runtime to the status of the invocation.\n /// Locally this will point to the URL of the dev server being run, in prod this\n /// will point to the runtime's internal endpoints.\n private _runtimeApi: string;\n\n /// We need to handle running a function differently than we handle\n /// deploying a function. The \"runtime\" phase is when we're trying to\n /// run a function by name (either locally or in prod). The \"build\"\n /// phase is when we're generating local manifest files to send to\n /// the Browserbase API. Defaults to runtime phase.\n private _phase: \"runtime\" | \"introspect\";\n\n constructor(processEnv: NodeJS.ProcessEnv) {\n this._environment = getOrDefault<typeof this._environment>(\n processEnv,\n \"NODE_ENV\",\n \"local\",\n );\n\n this._runtimeApi = getOrDefault<typeof this._runtimeApi>(\n processEnv,\n \"AWS_LAMBDA_RUNTIME_API\",\n \"127.0.0.1:14113\",\n );\n\n this._phase = getOrDefault<typeof this._phase>(\n processEnv,\n \"BB_FUNCTIONS_PHASE\",\n \"runtime\",\n );\n }\n\n get environment() {\n return this._environment;\n }\n\n get runtimeApi() {\n return this._runtimeApi;\n }\n\n get phase() {\n return this._phase;\n }\n}\n\nfunction getOrDefault<T>(env: NodeJS.ProcessEnv, key: string, dflt: T): T {\n const val = env[key];\n if (!val) {\n return dflt;\n }\n return val as T;\n}\n","import { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport z from \"zod\";\n\nimport type {\n FunctionManifest,\n PersistedFunctionManifest,\n} from \"../types/definition.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nexport function writeManifestToDisk<S extends JSONSchemaInput>(\n manifest: FunctionManifest<S>,\n manifestsDir: string,\n isFirstInvocation: boolean,\n) {\n if (isFirstInvocation) {\n // Clear manifests directory if it exists to remove stale menifests\n if (existsSync(manifestsDir)) {\n rmSync(manifestsDir, { recursive: true });\n }\n\n mkdirSync(manifestsDir, { recursive: true });\n }\n\n const persistedManifest = buildPersistedFunctionManifest(manifest);\n\n writeFileSync(\n join(manifestsDir, `${manifest.name}.json`),\n JSON.stringify(persistedManifest, null, 2),\n );\n}\n\nexport function buildPersistedFunctionManifest<S extends JSONSchemaInput>(\n manifest: FunctionManifest<S>,\n): PersistedFunctionManifest<S> {\n const { name, config } = manifest;\n const { parametersSchema, ...configWithoutSchema } = config;\n\n const processedConfig: PersistedFunctionManifest<S>[\"config\"] = {\n ...configWithoutSchema,\n };\n\n if (parametersSchema) {\n processedConfig.parametersSchema =\n buildPersistedJsonSchema(parametersSchema);\n }\n\n const processedManifest: PersistedFunctionManifest<S> = {\n name,\n config: processedConfig,\n };\n\n return processedManifest;\n}\n\nexport function buildPersistedJsonSchema(input: JSONSchemaInput): object {\n if (input instanceof z.ZodObject) {\n return z.toJSONSchema(input);\n }\n\n return {};\n}\n","import { join } from \"node:path\";\n\nimport type { FunctionConfiguration } from \"../types/definition.js\";\nimport type { FunctionHandler } from \"../types/handler.js\";\nimport type { JSONSchemaInput } from \"../types/schema.js\";\n\nimport { writeManifestToDisk } from \"./helpers.js\";\n\n// Singleton imports\nimport { environmentManager, functionsRegistry } from \"../index.js\";\n\n/// TODO: Write good documentation here\nexport function defineFn<S extends JSONSchemaInput = unknown>(\n name: string,\n handler: FunctionHandler<S>,\n config: FunctionConfiguration<S> = {},\n): void {\n functionsRegistry.register(name, handler, config);\n\n if (\n // The CLI needs \"local\" to know how to create sessions with\n // non-default configurations during the local dev flow\n environmentManager.phase === \"introspect\" ||\n environmentManager.environment === \"local\"\n ) {\n const manifestsDir = join(\n process.cwd(),\n \".browserbase\",\n \"functions\",\n \"manifests\",\n );\n\n const isFirstInvocation = functionsRegistry.size === 1;\n\n writeManifestToDisk(\n { name, handler, config },\n manifestsDir,\n isFirstInvocation,\n );\n }\n}\n","import { RuntimeClient } from \"./runtime/index.js\";\nimport { runInvocationLoop } from \"./runtime/loop.js\";\nimport { FunctionRegistry } from \"./runtime/registry.js\";\nimport { EnvironmentManager } from \"./utils/env.js\";\n\nexport { defineFn } from \"./define/index.js\";\n\nexport const environmentManager = new EnvironmentManager(process.env);\nexport const functionsRegistry = new FunctionRegistry();\nexport const runtimeClient = new RuntimeClient(\n functionsRegistry,\n environmentManager.runtimeApi,\n);\n\nfunction handleInvocationLoopFailure(error: unknown): void {\n console.error(\"Received fatal error from invocation loop\", error);\n process.exit(1);\n}\n// We only want to listen for invocations iff we're in the \"runtime\" phase\nif (environmentManager.phase === \"runtime\") {\n runInvocationLoop(runtimeClient, handleInvocationLoopFailure).catch(\n (error: unknown) => {\n console.error(\"Fatal runtime error:\", error);\n process.exit(1);\n },\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@browserbasehq/sdk-functions",
3
- "version": "0.0.3",
3
+ "version": "0.0.6",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "exports": {
@@ -14,7 +14,7 @@
14
14
  "module": "./dist/index.js",
15
15
  "types": "./dist/index.d.ts",
16
16
  "bin": {
17
- "bb": "./dist/cli.js"
17
+ "bb": "dist/cli.js"
18
18
  },
19
19
  "files": [
20
20
  "dist"
@@ -23,7 +23,7 @@
23
23
  "./dist/index.js"
24
24
  ],
25
25
  "scripts": {
26
- "build": "$npm_execpath run lint && rm -rf dist && tsup",
26
+ "build": "rm -rf dist && tsup",
27
27
  "build:tests": "tsc --project tsconfig.test.json",
28
28
  "eslint": "eslint ./src",
29
29
  "eslint:fix": "eslint --fix ./src",
@@ -32,6 +32,13 @@
32
32
  "prettier:fix": "prettier . --write --cache",
33
33
  "test": "$npm_execpath build:tests && node --test dist-test/**/*.test.js",
34
34
  "test:only": "$npm_execpath build:tests && node --test-only --test dist-test/**/*.test.js",
35
+ "build:integration": "tsc --project tsconfig.integration.json",
36
+ "pretest:integration": "$npm_execpath run build && pnpm pack",
37
+ "test:integration": "$npm_execpath run build:integration && node --test --test-timeout 120000 dist-integration-test/tests/integration/**/*.test.js",
38
+ "posttest:integration": "rm -f browserbasehq-sdk-functions-*.tgz",
39
+ "pretest:e2e": "$npm_execpath run build && pnpm pack",
40
+ "test:e2e": "$npm_execpath run build:integration && node --test --test-timeout 300000 dist-integration-test/tests/e2e/**/*.test.js",
41
+ "posttest:e2e": "rm -f browserbasehq-sdk-functions-*.tgz",
35
42
  "typecheck": "tsc --noEmit"
36
43
  },
37
44
  "keywords": [],