@walkeros/server-source-express 4.6.0 → 4.7.0-next-1790187973605
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/CHANGELOG.md +30 -0
- package/README.md +9 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/walkerOS.json +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# @walkeros/server-source-express
|
|
2
2
|
|
|
3
|
+
## 4.7.0-next-1790187973605
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 8f8aea6: POST bodies sent as `text/plain` that are not JSON, such as GA4 gtag
|
|
8
|
+
batches, no longer fail with 400. They reach `ingest.body` as the raw string,
|
|
9
|
+
so `@walkeros/transformer-ga4` now decodes batched hits. sendBeacon JSON is
|
|
10
|
+
parsed as before, and malformed `application/json` is still rejected with 400.
|
|
11
|
+
- Updated dependencies [57788bc]
|
|
12
|
+
- Updated dependencies [2aebc53]
|
|
13
|
+
- Updated dependencies [f5a1cfd]
|
|
14
|
+
- Updated dependencies [ef02916]
|
|
15
|
+
- Updated dependencies [ef02916]
|
|
16
|
+
- Updated dependencies [2aebc53]
|
|
17
|
+
- Updated dependencies [f5a1cfd]
|
|
18
|
+
- Updated dependencies [f5a1cfd]
|
|
19
|
+
- Updated dependencies [2aebc53]
|
|
20
|
+
- Updated dependencies [8f8aea6]
|
|
21
|
+
- Updated dependencies [2aebc53]
|
|
22
|
+
- Updated dependencies [2aebc53]
|
|
23
|
+
- @walkeros/core@4.7.0-next-1790187973605
|
|
24
|
+
- @walkeros/collector@4.7.0-next-1790187973605
|
|
25
|
+
|
|
26
|
+
## 4.6.1
|
|
27
|
+
|
|
28
|
+
### Patch Changes
|
|
29
|
+
|
|
30
|
+
- @walkeros/collector@4.6.1
|
|
31
|
+
- @walkeros/core@4.6.1
|
|
32
|
+
|
|
3
33
|
## 4.6.0
|
|
4
34
|
|
|
5
35
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -7,9 +7,17 @@
|
|
|
7
7
|
# @walkeros/server-source-express
|
|
8
8
|
|
|
9
9
|
Turn-key HTTP event collection server with Express.js. Runs standalone or embeds
|
|
10
|
-
inside an existing Express app, handles JSON POST events
|
|
10
|
+
inside an existing Express app, handles JSON POST events (including
|
|
11
|
+
`navigator.sendBeacon` payloads sent as `text/plain`), raw `text/plain` bodies
|
|
12
|
+
for request decoders such as `@walkeros/transformer-ga4`, pixel tracking via
|
|
11
13
|
GET, and configurable CORS.
|
|
12
14
|
|
|
15
|
+
A `text/plain` POST body is parsed as JSON when it is JSON
|
|
16
|
+
(`navigator.sendBeacon` sends JSON as `text/plain`) and otherwise kept as the
|
|
17
|
+
raw string on `ingest.body`, so a `before` transformer can decode it, for
|
|
18
|
+
example batched gtag.js hits with `@walkeros/transformer-ga4`. An
|
|
19
|
+
`application/json` body must parse, or the request is answered with 400.
|
|
20
|
+
|
|
13
21
|
[Documentation](https://www.walkeros.io/docs/sources/server/express) •
|
|
14
22
|
[NPM Package](https://www.npmjs.com/package/@walkeros/server-source-express)
|
|
15
23
|
•
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var mod,__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__copyProps=(to,from,except,desc)=>{if(from&&"object"==typeof from||"function"==typeof from)for(let key of __getOwnPropNames(from))__hasOwnProp.call(to,key)||key===except||__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=null!=mod?__create(__getProtoOf(mod)):{},__copyProps(!isNodeMode&&mod&&mod.__esModule?target:__defProp(target,"default",{value:mod,enumerable:!0}),mod)),index_exports={};((target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})})(index_exports,{TRANSPARENT_GIF:()=>TRANSPARENT_GIF,default:()=>index_default,setCorsHeaders:()=>setCorsHeaders,sourceExpress:()=>sourceExpress}),module.exports=(mod=index_exports,__copyProps(__defProp({},"__esModule",{value:!0}),mod));var import_express=__toESM(require("express")),import_cors=__toESM(require("cors")),import_core2=require("@walkeros/core");function setCorsHeaders(res,corsConfig=!0){if(!1!==corsConfig)if(!0===corsConfig)res.set("Access-Control-Allow-Origin","*"),res.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),res.set("Access-Control-Allow-Headers","Content-Type");else{if(corsConfig.origin){const origin=Array.isArray(corsConfig.origin)?corsConfig.origin.join(", "):corsConfig.origin;res.set("Access-Control-Allow-Origin",origin)}corsConfig.methods&&res.set("Access-Control-Allow-Methods",corsConfig.methods.join(", ")),corsConfig.headers&&res.set("Access-Control-Allow-Headers",corsConfig.headers.join(", ")),corsConfig.credentials&&res.set("Access-Control-Allow-Credentials","true"),corsConfig.maxAge&&res.set("Access-Control-Max-Age",String(corsConfig.maxAge))}}var TRANSPARENT_GIF=Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","base64"),import_core=require("@walkeros/core");var METHOD_DEFAULTS={GET:!1,POST:!0};function resolveRespondFirst(asyncConfig,method){return void 0===asyncConfig?METHOD_DEFAULTS[method]:"boolean"==typeof asyncConfig?asyncConfig:asyncConfig[method]??METHOD_DEFAULTS[method]}var toError=value=>value instanceof Error?value:new Error(String(value)),settleAfterAck=(result,logger)=>{result.then(settled=>{!1===settled?.ok&&!0!==settled.invalid&&logger.warn("Event not processed after ack",{failed:settled.failed?Object.keys(settled.failed):[]})},err=>{logger.error(toError(err))}).catch(()=>{})},REQUEST_BODY_ERROR_TYPES=new Set(["entity.parse.failed","entity.verify.failed","entity.too.large","charset.unsupported","encoding.unsupported","request.aborted","request.size.invalid"]),sourceExpress=async context=>{const{config:config={},env:env}=context,expressLib=env.express??import_express.default,corsLib=env.cors??import_cors.default,userSettings=config.settings||{},settings={...userSettings,cors:userSettings.cors??!0,paths:userSettings.paths??(userSettings.path?[userSettings.path]:["/collect"]),maxBatchSize:userSettings.maxBatchSize??100},maxBatchSize=settings.maxBatchSize,app=expressLib();app.disable("x-powered-by");const jsonParser=expressLib.json({limit:"1mb",type:
|
|
1
|
+
"use strict";var mod,__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__copyProps=(to,from,except,desc)=>{if(from&&"object"==typeof from||"function"==typeof from)for(let key of __getOwnPropNames(from))__hasOwnProp.call(to,key)||key===except||__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=null!=mod?__create(__getProtoOf(mod)):{},__copyProps(!isNodeMode&&mod&&mod.__esModule?target:__defProp(target,"default",{value:mod,enumerable:!0}),mod)),index_exports={};((target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})})(index_exports,{TRANSPARENT_GIF:()=>TRANSPARENT_GIF,default:()=>index_default,setCorsHeaders:()=>setCorsHeaders,sourceExpress:()=>sourceExpress}),module.exports=(mod=index_exports,__copyProps(__defProp({},"__esModule",{value:!0}),mod));var import_express=__toESM(require("express")),import_cors=__toESM(require("cors")),import_core2=require("@walkeros/core");function setCorsHeaders(res,corsConfig=!0){if(!1!==corsConfig)if(!0===corsConfig)res.set("Access-Control-Allow-Origin","*"),res.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),res.set("Access-Control-Allow-Headers","Content-Type");else{if(corsConfig.origin){const origin=Array.isArray(corsConfig.origin)?corsConfig.origin.join(", "):corsConfig.origin;res.set("Access-Control-Allow-Origin",origin)}corsConfig.methods&&res.set("Access-Control-Allow-Methods",corsConfig.methods.join(", ")),corsConfig.headers&&res.set("Access-Control-Allow-Headers",corsConfig.headers.join(", ")),corsConfig.credentials&&res.set("Access-Control-Allow-Credentials","true"),corsConfig.maxAge&&res.set("Access-Control-Max-Age",String(corsConfig.maxAge))}}var TRANSPARENT_GIF=Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","base64"),import_core=require("@walkeros/core");var METHOD_DEFAULTS={GET:!1,POST:!0};function resolveRespondFirst(asyncConfig,method){return void 0===asyncConfig?METHOD_DEFAULTS[method]:"boolean"==typeof asyncConfig?asyncConfig:asyncConfig[method]??METHOD_DEFAULTS[method]}var toError=value=>value instanceof Error?value:new Error(String(value)),settleAfterAck=(result,logger)=>{result.then(settled=>{!1===settled?.ok&&!0!==settled.invalid&&logger.warn("Event not processed after ack",{failed:settled.failed?Object.keys(settled.failed):[]})},err=>{logger.error(toError(err))}).catch(()=>{})},REQUEST_BODY_ERROR_TYPES=new Set(["entity.parse.failed","entity.verify.failed","entity.too.large","charset.unsupported","encoding.unsupported","request.aborted","request.size.invalid"]),sourceExpress=async context=>{const{config:config={},env:env}=context,expressLib=env.express??import_express.default,corsLib=env.cors??import_cors.default,userSettings=config.settings||{},settings={...userSettings,cors:userSettings.cors??!0,paths:userSettings.paths??(userSettings.path?[userSettings.path]:["/collect"]),maxBatchSize:userSettings.maxBatchSize??100},maxBatchSize=settings.maxBatchSize,app=expressLib();app.disable("x-powered-by");const jsonParser=expressLib.json({limit:"1mb",type:"application/json"}),textParser=expressLib.text({limit:"1mb",type:"text/plain"});if(app.use((_req,res,next)=>{res.setHeader("X-Content-Type-Options","nosniff"),next()}),!1!==settings.cors){const corsOptions=!0===settings.cors?{}:settings.cors;app.use(corsLib(corsOptions))}const push=async(req,res)=>{try{if("OPTIONS"===req.method)return setCorsHeaders(res,settings.cors),void res.status(204).send();const respond=(0,import_core2.createRespond)(options=>{const status=options.status??200;if(options.headers)for(const[key,value]of Object.entries(options.headers))res.set(key,value);res.status(status);const body=options.body;"string"==typeof body||Buffer.isBuffer(body)?res.send(body):body instanceof Uint8Array?res.send(Buffer.from(body)):res.json(body)}),scope=function(req){return(0,import_core.buildScopeFromNodeRequest)(req,{body:(0,import_core.normalizeBody)(req.body),defaultProtocol:"http"})}(req);await context.withScope(scope,respond,async env2=>{if("GET"===req.method){const parsedData=(0,import_core2.requestToData)(req.url),respondGif=()=>respond({body:TRANSPARENT_GIF,headers:{"Content-Type":"image/gif","Cache-Control":"no-cache, no-store, must-revalidate"}});return void(parsedData&&"object"==typeof parsedData?resolveRespondFirst(config.async,"GET")?(respondGif(),settleAfterAck(env2.push(parsedData),env2.logger)):(await env2.push(parsedData),respondGif()):respondGif())}if("POST"===req.method){const events=(0,import_core2.toEventList)(scope.body),batched=(0,import_core2.isBatchBody)(scope.body);if(batched&&events.length>maxBatchSize)return void respond({status:400,body:{success:!1,error:`Batch too large. Maximum size: ${maxBatchSize} events`,timestamp:Date.now()}});if(resolveRespondFirst(config.async,"POST")){respond({body:{success:!0,timestamp:Date.now()}});let chain=Promise.resolve();return void events.forEach((event,index)=>{const deliver=()=>{const pushed=env2.push(event);return settleAfterAck(pushed,env2.logger),pushed.catch(()=>{})};chain=0===index?deliver():chain.then(deliver)})}const results=[];for(const event of events)results.push(await env2.push(event));if(batched){const{status:status,body:body}=(0,import_core2.batchResponse)(results.map(import_core2.pushResultToOutcome));return void respond(200===status?{body:body}:{status:status,body:body})}const result=results[0];if(!1===result?.ok){const invalid=!0===result.invalid;respond({status:invalid?400:500,body:{success:!1,error:result.error??(invalid?"Invalid event":"Event was not processed"),timestamp:Date.now()}})}else respond({body:{success:!0,timestamp:Date.now()}});return}res.status(405).json({success:!1,error:"Method not allowed. Use POST, GET, or OPTIONS."})})}catch(error){env.logger.error(toError(error)),res.headersSent||res.status(500).json({success:!1,error:"Internal server error"})}},resolvedPaths=settings.paths.map(entry=>"string"==typeof entry?{path:entry,methods:["GET","POST"]}:{path:entry.path,methods:entry.methods||["GET","POST"]});for(const route of resolvedPaths)route.methods.includes("POST")&&app.post(route.path,jsonParser,textParser,push),route.methods.includes("GET")&&app.get(route.path,push),app.options(route.path,push);let server;app.use((err,_req,res,next)=>res.headersSent?(env.logger.error(toError(err)),next(err)):(err=>{if(!(err instanceof Error))return!1;if(!("status"in err)||!("type"in err))return!1;const candidate=err;return"number"==typeof candidate.status&&candidate.status>=400&&candidate.status<500&&"string"==typeof candidate.type&&REQUEST_BODY_ERROR_TYPES.has(candidate.type)})(err)?((()=>{const sources=context.collector.status?.sources;if(!sources)return;sources[context.id]||(sources[context.id]={count:0,duration:0});const sourceStatus=sources[context.id];sourceStatus.rejected=(sourceStatus.rejected??0)+1})(),env.logger.debug("Request body rejected",{status:err.status,type:err.type,error:err.message,sample:"string"==typeof err.body?err.body.slice(0,200):void 0}),void res.status(err.status).json({success:!1,error:err.message})):(env.logger.error(toError(err)),void res.status(500).json({success:!1,error:"Internal server error"}))),void 0!==settings.port&&(server=app.listen(settings.port,()=>{const routeLines=resolvedPaths.map(r=>` ${[...r.methods,"OPTIONS"].join(", ")} ${r.path}`).join("\n");env.logger.info(`Express source listening on port ${settings.port}\n`+routeLines)}));return{type:"express",config:{...config,settings:settings},push:push,httpHandler:app,app:app,server:server,destroy:_context=>new Promise((resolve,reject)=>{if(!server)return resolve();server.close(err=>err?reject(err):resolve())})}},index_default=sourceExpress;//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/scope.ts","../src/respond-mode.ts"],"sourcesContent":["import express, {\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\nimport cors from 'cors';\nimport {\n requestToData,\n createRespond,\n toEventList,\n isBatchBody,\n batchResponse,\n pushResultToOutcome,\n} from '@walkeros/core';\nimport type { Elb, Logger, Source } from '@walkeros/core';\nimport type { ExpressSource, Types, EventRequest } from './types';\nimport { setCorsHeaders, TRANSPARENT_GIF } from './utils';\nimport { buildScope } from './scope';\nimport { resolveRespondFirst } from './respond-mode';\n\n/**\n * Normalize an unknown rejection reason into an Error for the logger.\n * A fire-and-forget push can reject with any value; the logger accepts\n * `string | Error`, so non-Error reasons are wrapped.\n */\nconst toError = (value: unknown): Error =>\n value instanceof Error ? value : new Error(String(value));\n\n/**\n * Settle handler for respond-first pushes: the HTTP ack already went out,\n * so a pipeline decline (ok:false) or a rejection can only surface here.\n * Warn on decline; the collector has already error-logged a thrown pipeline\n * failure, this line ties the outcome to the request that was acked.\n * Invalid-input rejections stay silent here: the collector already warned\n * and counted them at the pipeline gate.\n */\nconst settleAfterAck = (\n result: Promise<Elb.PushResult>,\n logger: Logger.Instance,\n): void => {\n result\n .then(\n (settled) => {\n if (settled?.ok === false && settled.invalid !== true) {\n logger.warn('Event not processed after ack', {\n failed: settled.failed ? Object.keys(settled.failed) : [],\n });\n }\n },\n (err: unknown) => {\n logger.error(toError(err));\n },\n )\n // The derived promise would otherwise float: a throw inside the\n // handlers above (e.g. a faulty logger) must not surface as an\n // unhandled rejection on a fire-and-forget path.\n .catch(() => undefined);\n};\n\n/**\n * Client-caused body failure raised by the route-scoped JSON parser:\n * unparseable JSON, oversized payload, unsupported charset or encoding,\n * an aborted request, or a content-length mismatch. Identified by the\n * error type marker the parser attaches, so unrelated middleware errors\n * that happen to carry a 4xx status are never treated as body rejections.\n * Carries the HTTP status to answer with and, for parse failures, the raw\n * body for debug diagnostics.\n */\ninterface RequestBodyError extends Error {\n status: number;\n type: string;\n body?: unknown;\n}\n\n// Type markers body-parser and raw-body attach to client-caused body\n// failures (see body-parser lib/read.js and raw-body index.js).\nconst REQUEST_BODY_ERROR_TYPES = new Set([\n 'entity.parse.failed',\n 'entity.verify.failed',\n 'entity.too.large',\n 'charset.unsupported',\n 'encoding.unsupported',\n 'request.aborted',\n 'request.size.invalid',\n]);\n\nconst isRequestBodyError = (err: unknown): err is RequestBodyError => {\n if (!(err instanceof Error)) return false;\n if (!('status' in err) || !('type' in err)) return false;\n const candidate: { status?: unknown; type?: unknown } = err;\n return (\n typeof candidate.status === 'number' &&\n candidate.status >= 400 &&\n candidate.status < 500 &&\n typeof candidate.type === 'string' &&\n REQUEST_BODY_ERROR_TYPES.has(candidate.type)\n );\n};\n\n/**\n * Express source initialization\n *\n * This source OWNS its HTTP server infrastructure:\n * - Creates Express application\n * - Sets up middleware (JSON parsing, CORS)\n * - Registers event collection endpoints (POST, GET, OPTIONS)\n * - Starts HTTP server (if port configured)\n * - Provides destroy() for graceful shutdown (called by runner)\n *\n * @param context Source context with config, env, logger, id\n * @returns Express source instance with app and push handler\n */\nexport const sourceExpress = async (\n context: Source.Context<Types>,\n): Promise<ExpressSource> => {\n const { config = {}, env } = context;\n const expressLib = env.express ?? express;\n const corsLib = env.cors ?? cors;\n\n // Apply defaults (no runtime validation — flow.json is developer-controlled).\n const userSettings = config.settings || {};\n const settings = {\n ...userSettings,\n cors: userSettings.cors ?? true,\n paths:\n userSettings.paths ??\n (userSettings.path ? [userSettings.path] : ['/collect']),\n maxBatchSize: userSettings.maxBatchSize ?? 100,\n };\n\n const maxBatchSize = settings.maxBatchSize;\n\n // Rejection volume belongs in collector.status, not in per-request logs.\n // Lazy entry creation mirrors the collector's own sources bookkeeping.\n // Guarded: unit harnesses may run the handler with a bare collector stub.\n const countRejected = (): void => {\n const sources = context.collector.status?.sources;\n if (!sources) return;\n if (!sources[context.id]) {\n sources[context.id] = { count: 0, duration: 0 };\n }\n const sourceStatus = sources[context.id];\n sourceStatus.rejected = (sourceStatus.rejected ?? 0) + 1;\n };\n\n const app = expressLib();\n\n // The framework identity is of no use to callers and only helps someone\n // probing the endpoint pick an exploit.\n app.disable('x-powered-by');\n\n // Body parsing per configured POST route: JSON content-type plus text/plain\n // so navigator.sendBeacon payloads (which the browser forces to\n // text/plain;charset=UTF-8) are also parsed as JSON. 1mb default limit.\n // Route-scoped so unmatched paths (scanner noise) fall through to the\n // default 404 without ever touching the parser.\n const jsonParser = expressLib.json({\n limit: '1mb',\n type: ['application/json', 'text/plain'],\n });\n\n // Content-Type on some responses is flow-controlled (a cache or asset step\n // can set it through respond({ headers })), so sniffing stays off. Registered\n // before CORS and unconditionally, so it also covers the default 404 and the\n // body-rejection responses.\n app.use((_req, res, next) => {\n res.setHeader('X-Content-Type-Options', 'nosniff');\n next();\n });\n\n // CORS middleware (enabled by default)\n if (settings.cors !== false) {\n const corsOptions = settings.cors === true ? {} : settings.cors;\n app.use(corsLib(corsOptions));\n }\n\n /**\n * Request handler - transforms HTTP requests into walker events\n * Supports POST (JSON body), GET (query params), and OPTIONS (CORS preflight)\n *\n * Each inbound request gets its own `withScope` invocation. The per-scope\n * env carries this request's `ingest` and `respond` end to end, so\n * concurrent requests never crosstalk through source-factory state.\n */\n const push = async (req: Request, res: Response): Promise<void> => {\n try {\n // Handle OPTIONS for CORS preflight (no scope needed: no event, no ingest)\n if (req.method === 'OPTIONS') {\n setCorsHeaders(res, settings.cors);\n res.status(204).send();\n return;\n }\n\n // Create per-request respond — first call wins (idempotent)\n const respond = createRespond((options) => {\n const status = options.status ?? 200;\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n res.set(key, value);\n }\n }\n res.status(status);\n const body = options.body;\n if (typeof body === 'string' || Buffer.isBuffer(body)) {\n res.send(body);\n } else if (body instanceof Uint8Array) {\n // A decoded cache value surfaces binary as a plain Uint8Array,\n // not a Node Buffer; send it as bytes (res.json would corrupt it).\n res.send(Buffer.from(body));\n } else {\n res.json(body);\n }\n });\n\n const scope = buildScope(req);\n\n await context.withScope(scope, respond, async (env) => {\n // Handle GET requests (pixel tracking)\n if (req.method === 'GET') {\n // Parse query parameters to event data using requestToData\n const parsedData = requestToData(req.url);\n\n // Default GIF body (idempotent fallback; skipped if a step already\n // called respond, e.g. a cache/asset destination serving real bytes).\n const respondGif = () =>\n respond({\n body: TRANSPARENT_GIF,\n headers: {\n 'Content-Type': 'image/gif',\n 'Cache-Control': 'no-cache, no-store, must-revalidate',\n },\n });\n\n if (parsedData && typeof parsedData === 'object') {\n if (resolveRespondFirst(config.async, 'GET')) {\n // Respond-first: the tracking pixel must return instantly and\n // never block on backend delivery. Fire the push without\n // awaiting; a rejected push and a settled non-invalid decline\n // are logged (destination errors are DLQ'd inside the\n // collector). A 2xx means \"accepted\", not \"delivered\".\n respondGif();\n settleAfterAck(env.push(parsedData), env.logger);\n } else {\n // Synchronous: await the push so a step (e.g. a cache/asset\n // destination) can respond with real content before the GIF\n // fallback applies.\n await env.push(parsedData);\n respondGif();\n }\n } else {\n respondGif();\n }\n return;\n }\n\n // Handle POST requests (standard event ingestion)\n if (req.method === 'POST') {\n const events = toEventList(scope.body);\n const batched = isBatchBody(scope.body);\n\n if (batched && events.length > maxBatchSize) {\n respond({\n status: 400,\n body: {\n success: false,\n error: `Batch too large. Maximum size: ${maxBatchSize} events`,\n timestamp: Date.now(),\n },\n });\n return;\n }\n\n if (resolveRespondFirst(config.async, 'POST')) {\n // Respond-first (\"accepted\"), then deliver asynchronously. A\n // rejected push and a settled non-invalid decline are logged, not\n // surfaced to the client and not left unhandled (destination\n // errors are DLQ'd inside the collector). In this mode a batch is\n // acknowledged as accepted; per-index outcomes are not knowable\n // yet, so they surface through collector.status and logs.\n respond({ body: { success: true, timestamp: Date.now() } });\n // Ack first, then deliver in submission order. The first push\n // starts immediately, so a single event is delivered exactly as\n // before; the rest are chained so a batch keeps the order every\n // other batch path guarantees, without the client waiting.\n let chain: Promise<unknown> = Promise.resolve();\n events.forEach((event, index) => {\n const deliver = () => {\n const pushed = env.push(event);\n settleAfterAck(pushed, env.logger);\n // The chain only sequences; failures are already logged and\n // must not stop the siblings behind them.\n return pushed.catch(() => undefined);\n };\n chain = index === 0 ? deliver() : chain.then(deliver);\n });\n return;\n }\n\n // Synchronous ack: wait for delivery to settle before responding,\n // and reflect the outcome. Invalid input is the client's fault\n // (400 with the reason); anything else that failed is ours (500).\n const results = [];\n for (const event of events) {\n results.push(await env.push(event));\n }\n\n if (batched) {\n const { status, body } = batchResponse(\n results.map(pushResultToOutcome),\n );\n respond(status === 200 ? { body } : { status, body });\n return;\n }\n\n const result = results[0];\n if (result?.ok === false) {\n const invalid = result.invalid === true;\n respond({\n status: invalid ? 400 : 500,\n body: {\n success: false,\n error:\n result.error ??\n (invalid ? 'Invalid event' : 'Event was not processed'),\n timestamp: Date.now(),\n },\n });\n } else {\n respond({ body: { success: true, timestamp: Date.now() } });\n }\n return;\n }\n\n // Unsupported method\n res.status(405).json({\n success: false,\n error: 'Method not allowed. Use POST, GET, or OPTIONS.',\n });\n });\n } catch (error) {\n // The reason is logged, not returned: an unexpected fault's message can\n // carry paths, dependency names or config details, and the caller can do\n // nothing with it. Matches the error-boundary middleware's answer for the\n // same class of fault.\n env.logger.error(toError(error));\n if (!res.headersSent) {\n res.status(500).json({\n success: false,\n error: 'Internal server error',\n });\n }\n }\n };\n\n // Register handlers per route config\n const resolvedPaths = settings.paths.map((entry) =>\n typeof entry === 'string'\n ? { path: entry, methods: ['GET', 'POST'] as const }\n : {\n path: entry.path,\n methods: entry.methods || (['GET', 'POST'] as const),\n },\n );\n\n for (const route of resolvedPaths) {\n if (route.methods.includes('POST')) app.post(route.path, jsonParser, push);\n if (route.methods.includes('GET')) app.get(route.path, push);\n app.options(route.path, push); // Always register OPTIONS for CORS\n }\n\n // Error boundary for the middleware chain. Client-caused body errors are\n // expected ambient noise on a public endpoint: answer deliberately, count,\n // and keep them out of the error channel. Anything else is a real fault\n // and stays loud.\n app.use((err: unknown, _req: Request, res: Response, next: NextFunction) => {\n if (res.headersSent) {\n // The response is already on the wire, so this fault cannot be\n // answered. Give it a structured home before re-raising; express\n // needs the re-raise to destroy the socket.\n env.logger.error(toError(err));\n return next(err);\n }\n if (isRequestBodyError(err)) {\n countRejected();\n env.logger.debug('Request body rejected', {\n status: err.status,\n type: err.type,\n error: err.message,\n sample:\n typeof err.body === 'string' ? err.body.slice(0, 200) : undefined,\n });\n res.status(err.status).json({ success: false, error: err.message });\n return;\n }\n env.logger.error(toError(err));\n res.status(500).json({ success: false, error: 'Internal server error' });\n });\n\n // Source owns the HTTP server (if port configured)\n let server: ReturnType<typeof app.listen> | undefined;\n\n if (settings.port !== undefined) {\n server = app.listen(settings.port, () => {\n const routeLines = resolvedPaths\n .map((r) => {\n const methods = [...r.methods, 'OPTIONS'].join(', ');\n return ` ${methods} ${r.path}`;\n })\n .join('\\n');\n env.logger.info(\n `Express source listening on port ${settings.port}\\n` + routeLines,\n );\n });\n }\n\n const instance: ExpressSource = {\n type: 'express',\n config: {\n ...config,\n settings,\n },\n push,\n httpHandler: app,\n app,\n server,\n destroy: (_context) =>\n new Promise<void>((resolve, reject) => {\n if (!server) return resolve();\n server.close((err) => (err ? reject(err) : resolve()));\n }),\n };\n\n return instance;\n};\n\n// Export types (avoid re-exporting duplicates from schemas)\nexport type {\n ExpressSource,\n Config,\n PartialConfig,\n Types,\n EventRequest,\n EventResponse,\n RequestBody,\n ResponseBody,\n Push,\n Env,\n Mapping,\n InitSettings,\n Settings,\n RouteConfig,\n RouteMethod,\n AsyncByMethod,\n} from './types';\n\n// Export utils\nexport { setCorsHeaders, TRANSPARENT_GIF } from './utils';\n\nexport default sourceExpress;\n","import type { Response } from 'express';\nimport type { CorsOptions } from './schemas';\n\n/**\n * Set CORS headers on response\n *\n * @param res Express response object\n * @param corsConfig CORS configuration (false = disabled, true = allow all, object = custom)\n */\nexport function setCorsHeaders(\n res: Response,\n corsConfig: boolean | CorsOptions = true,\n): void {\n if (corsConfig === false) return;\n\n if (corsConfig === true) {\n // Simple CORS - allow all\n res.set('Access-Control-Allow-Origin', '*');\n res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.set('Access-Control-Allow-Headers', 'Content-Type');\n } else {\n // Custom CORS configuration\n if (corsConfig.origin) {\n const origin = Array.isArray(corsConfig.origin)\n ? corsConfig.origin.join(', ')\n : corsConfig.origin;\n res.set('Access-Control-Allow-Origin', origin);\n }\n\n if (corsConfig.methods) {\n res.set('Access-Control-Allow-Methods', corsConfig.methods.join(', '));\n }\n\n if (corsConfig.headers) {\n res.set('Access-Control-Allow-Headers', corsConfig.headers.join(', '));\n }\n\n if (corsConfig.credentials) {\n res.set('Access-Control-Allow-Credentials', 'true');\n }\n\n if (corsConfig.maxAge) {\n res.set('Access-Control-Max-Age', String(corsConfig.maxAge));\n }\n }\n}\n\n/**\n * 1x1 transparent GIF for pixel tracking\n * Base64-encoded GIF (43 bytes)\n */\nexport const TRANSPARENT_GIF = Buffer.from(\n 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',\n 'base64',\n);\n","import { buildScopeFromNodeRequest } from '@walkeros/core';\nimport type { Source } from '@walkeros/core';\nimport type { Request } from 'express';\n\n/**\n * Builds the normalized scope from an Express request.\n *\n * The body is taken as-is: the route's JSON parser has already parsed it,\n * including `text/plain` beacons, so no second parse belongs here.\n *\n * @param req The Express request.\n * @returns The normalized scope.\n */\nexport function buildScope(req: Request): Source.Scope {\n return buildScopeFromNodeRequest(req, {\n body: req.body,\n defaultProtocol: 'http',\n });\n}\n","import type { RouteMethod } from './types';\n\n/**\n * Per-method respond-first defaults. GET is synchronous so a step (a file\n * transformer, a cache destination) can respond with real content before\n * the GIF fallback applies; POST is respond-first so ingestion acks fast\n * and delivers asynchronously.\n */\nconst METHOD_DEFAULTS: Record<RouteMethod, boolean> = {\n GET: false,\n POST: true,\n};\n\n/**\n * Resolves the effective respond-first flag for one request method from\n * `config.async`. A boolean applies to both methods; a record overrides per\n * method, with unset methods falling back to the method default; undefined\n * yields the method default.\n *\n * @param asyncConfig The source's `config.async` value.\n * @param method The request method to resolve for.\n * @returns Whether the handler responds before the push settles.\n */\nexport function resolveRespondFirst(\n asyncConfig: boolean | Record<string, boolean> | undefined,\n method: RouteMethod,\n): boolean {\n if (asyncConfig === undefined) return METHOD_DEFAULTS[method];\n if (typeof asyncConfig === 'boolean') return async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;AAGD,MAAI;AAEJ,MAAI,SAAS,SAAS,QAAW;AAC/B,aAAS,IAAI,OAAO,SAAS,MAAM,MAAM;AACvC,YAAM,aAAa,cAChB,IAAI,CAAC,MAAM;AACV,cAAM,UAAU,CAAC,GAAG,EAAE,SAAS,SAAS,EAAE,KAAK,IAAI;AACnD,eAAO,MAAM,OAAO,IAAI,EAAE,IAAI;AAAA,MAChC,CAAC,EACA,KAAK,IAAI;AACZ,UAAI,OAAO;AAAA,QACT,oCAAoC,SAAS,IAAI;AAAA,IAAO;AAAA,MAC1D;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,WAA0B;AAAA,IAC9B,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,GAAG;AAAA,MACH;AAAA,IACF;AAAA,IACA;AAAA,IACA,aAAa;AAAA,IACb;AAAA,IACA;AAAA,IACA,SAAS,CAAC,aACR,IAAI,QAAc,CAAC,SAAS,WAAW;AACrC,UAAI,CAAC,OAAQ,QAAO,QAAQ;AAC5B,aAAO,MAAM,CAAC,QAAS,MAAM,OAAO,GAAG,IAAI,QAAQ,CAAE;AAAA,IACvD,CAAC;AAAA,EACL;AAEA,SAAO;AACT;AAyBA,IAAO,gBAAQ;","names":["import_core","express","cors","env"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/scope.ts","../src/respond-mode.ts"],"sourcesContent":["import express, {\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\nimport cors from 'cors';\nimport {\n requestToData,\n createRespond,\n toEventList,\n isBatchBody,\n batchResponse,\n pushResultToOutcome,\n} from '@walkeros/core';\nimport type { Elb, Logger, Source } from '@walkeros/core';\nimport type { ExpressSource, Types, EventRequest } from './types';\nimport { BODY_LIMIT, setCorsHeaders, TRANSPARENT_GIF } from './utils';\nimport { buildScope } from './scope';\nimport { resolveRespondFirst } from './respond-mode';\n\n/**\n * Normalize an unknown rejection reason into an Error for the logger.\n * A fire-and-forget push can reject with any value; the logger accepts\n * `string | Error`, so non-Error reasons are wrapped.\n */\nconst toError = (value: unknown): Error =>\n value instanceof Error ? value : new Error(String(value));\n\n/**\n * Settle handler for respond-first pushes: the HTTP ack already went out,\n * so a pipeline decline (ok:false) or a rejection can only surface here.\n * Warn on decline; the collector has already error-logged a thrown pipeline\n * failure, this line ties the outcome to the request that was acked.\n * Invalid-input rejections stay silent here: the collector already warned\n * and counted them at the pipeline gate.\n */\nconst settleAfterAck = (\n result: Promise<Elb.PushResult>,\n logger: Logger.Instance,\n): void => {\n result\n .then(\n (settled) => {\n if (settled?.ok === false && settled.invalid !== true) {\n logger.warn('Event not processed after ack', {\n failed: settled.failed ? Object.keys(settled.failed) : [],\n });\n }\n },\n (err: unknown) => {\n logger.error(toError(err));\n },\n )\n // The derived promise would otherwise float: a throw inside the\n // handlers above (e.g. a faulty logger) must not surface as an\n // unhandled rejection on a fire-and-forget path.\n .catch(() => undefined);\n};\n\n/**\n * Client-caused body failure raised by the route-scoped body parsers:\n * an unparseable application/json body, oversized payload, unsupported\n * charset or encoding, an aborted request, or a content-length mismatch.\n * Identified by the error type marker the parser attaches, so unrelated\n * middleware errors that happen to carry a 4xx status are never treated as\n * body rejections. Carries the HTTP status to answer with and, for parse\n * failures, the raw body for debug diagnostics.\n */\ninterface RequestBodyError extends Error {\n status: number;\n type: string;\n body?: unknown;\n}\n\n// Type markers body-parser and raw-body attach to client-caused body\n// failures (see body-parser lib/read.js and raw-body index.js).\nconst REQUEST_BODY_ERROR_TYPES = new Set([\n 'entity.parse.failed',\n 'entity.verify.failed',\n 'entity.too.large',\n 'charset.unsupported',\n 'encoding.unsupported',\n 'request.aborted',\n 'request.size.invalid',\n]);\n\nconst isRequestBodyError = (err: unknown): err is RequestBodyError => {\n if (!(err instanceof Error)) return false;\n if (!('status' in err) || !('type' in err)) return false;\n const candidate: { status?: unknown; type?: unknown } = err;\n return (\n typeof candidate.status === 'number' &&\n candidate.status >= 400 &&\n candidate.status < 500 &&\n typeof candidate.type === 'string' &&\n REQUEST_BODY_ERROR_TYPES.has(candidate.type)\n );\n};\n\n/**\n * Express source initialization\n *\n * This source OWNS its HTTP server infrastructure:\n * - Creates Express application\n * - Sets up middleware (JSON parsing, CORS)\n * - Registers event collection endpoints (POST, GET, OPTIONS)\n * - Starts HTTP server (if port configured)\n * - Provides destroy() for graceful shutdown (called by runner)\n *\n * @param context Source context with config, env, logger, id\n * @returns Express source instance with app and push handler\n */\nexport const sourceExpress = async (\n context: Source.Context<Types>,\n): Promise<ExpressSource> => {\n const { config = {}, env } = context;\n const expressLib = env.express ?? express;\n const corsLib = env.cors ?? cors;\n\n // Apply defaults (no runtime validation — flow.json is developer-controlled).\n const userSettings = config.settings || {};\n const settings = {\n ...userSettings,\n cors: userSettings.cors ?? true,\n paths:\n userSettings.paths ??\n (userSettings.path ? [userSettings.path] : ['/collect']),\n maxBatchSize: userSettings.maxBatchSize ?? 100,\n };\n\n const maxBatchSize = settings.maxBatchSize;\n\n // Rejection volume belongs in collector.status, not in per-request logs.\n // Lazy entry creation mirrors the collector's own sources bookkeeping.\n // Guarded: unit harnesses may run the handler with a bare collector stub.\n const countRejected = (): void => {\n const sources = context.collector.status?.sources;\n if (!sources) return;\n if (!sources[context.id]) {\n sources[context.id] = { count: 0, duration: 0 };\n }\n const sourceStatus = sources[context.id];\n sourceStatus.rejected = (sourceStatus.rejected ?? 0) + 1;\n };\n\n const app = expressLib();\n\n // The framework identity is of no use to callers and only helps someone\n // probing the endpoint pick an exploit.\n app.disable('x-powered-by');\n\n // Body parsing per configured POST route. application/json must parse, or\n // the request is rejected. text/plain is read as a string and resolved in\n // buildScope: JSON when it parses (navigator.sendBeacon forces\n // text/plain;charset=UTF-8 on JSON payloads), raw input otherwise, so a\n // source.before chain can decode it (e.g. batched gtag.js hits).\n // Route-scoped so unmatched paths (scanner noise) fall through to the\n // default 404 without ever touching a parser.\n const jsonParser = expressLib.json({\n limit: BODY_LIMIT,\n type: 'application/json',\n });\n const textParser = expressLib.text({\n limit: BODY_LIMIT,\n type: 'text/plain',\n });\n\n // Content-Type on some responses is flow-controlled (a cache or asset step\n // can set it through respond({ headers })), so sniffing stays off. Registered\n // before CORS and unconditionally, so it also covers the default 404 and the\n // body-rejection responses.\n app.use((_req, res, next) => {\n res.setHeader('X-Content-Type-Options', 'nosniff');\n next();\n });\n\n // CORS middleware (enabled by default)\n if (settings.cors !== false) {\n const corsOptions = settings.cors === true ? {} : settings.cors;\n app.use(corsLib(corsOptions));\n }\n\n /**\n * Request handler - transforms HTTP requests into walker events\n * Supports POST (JSON or text body), GET (query params), and OPTIONS (CORS\n * preflight)\n *\n * Each inbound request gets its own `withScope` invocation. The per-scope\n * env carries this request's `ingest` and `respond` end to end, so\n * concurrent requests never crosstalk through source-factory state.\n */\n const push = async (req: Request, res: Response): Promise<void> => {\n try {\n // Handle OPTIONS for CORS preflight (no scope needed: no event, no ingest)\n if (req.method === 'OPTIONS') {\n setCorsHeaders(res, settings.cors);\n res.status(204).send();\n return;\n }\n\n // Create per-request respond — first call wins (idempotent)\n const respond = createRespond((options) => {\n const status = options.status ?? 200;\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n res.set(key, value);\n }\n }\n res.status(status);\n const body = options.body;\n if (typeof body === 'string' || Buffer.isBuffer(body)) {\n res.send(body);\n } else if (body instanceof Uint8Array) {\n // A decoded cache value surfaces binary as a plain Uint8Array,\n // not a Node Buffer; send it as bytes (res.json would corrupt it).\n res.send(Buffer.from(body));\n } else {\n res.json(body);\n }\n });\n\n const scope = buildScope(req);\n\n await context.withScope(scope, respond, async (env) => {\n // Handle GET requests (pixel tracking)\n if (req.method === 'GET') {\n // Parse query parameters to event data using requestToData\n const parsedData = requestToData(req.url);\n\n // Default GIF body (idempotent fallback; skipped if a step already\n // called respond, e.g. a cache/asset destination serving real bytes).\n const respondGif = () =>\n respond({\n body: TRANSPARENT_GIF,\n headers: {\n 'Content-Type': 'image/gif',\n 'Cache-Control': 'no-cache, no-store, must-revalidate',\n },\n });\n\n if (parsedData && typeof parsedData === 'object') {\n if (resolveRespondFirst(config.async, 'GET')) {\n // Respond-first: the tracking pixel must return instantly and\n // never block on backend delivery. Fire the push without\n // awaiting; a rejected push and a settled non-invalid decline\n // are logged (destination errors are DLQ'd inside the\n // collector). A 2xx means \"accepted\", not \"delivered\".\n respondGif();\n settleAfterAck(env.push(parsedData), env.logger);\n } else {\n // Synchronous: await the push so a step (e.g. a cache/asset\n // destination) can respond with real content before the GIF\n // fallback applies.\n await env.push(parsedData);\n respondGif();\n }\n } else {\n respondGif();\n }\n return;\n }\n\n // Handle POST requests (standard event ingestion)\n if (req.method === 'POST') {\n const events = toEventList(scope.body);\n const batched = isBatchBody(scope.body);\n\n if (batched && events.length > maxBatchSize) {\n respond({\n status: 400,\n body: {\n success: false,\n error: `Batch too large. Maximum size: ${maxBatchSize} events`,\n timestamp: Date.now(),\n },\n });\n return;\n }\n\n if (resolveRespondFirst(config.async, 'POST')) {\n // Respond-first (\"accepted\"), then deliver asynchronously. A\n // rejected push and a settled non-invalid decline are logged, not\n // surfaced to the client and not left unhandled (destination\n // errors are DLQ'd inside the collector). In this mode a batch is\n // acknowledged as accepted; per-index outcomes are not knowable\n // yet, so they surface through collector.status and logs.\n respond({ body: { success: true, timestamp: Date.now() } });\n // Ack first, then deliver in submission order. The first push\n // starts immediately, so a single event is delivered exactly as\n // before; the rest are chained so a batch keeps the order every\n // other batch path guarantees, without the client waiting.\n let chain: Promise<unknown> = Promise.resolve();\n events.forEach((event, index) => {\n const deliver = () => {\n const pushed = env.push(event);\n settleAfterAck(pushed, env.logger);\n // The chain only sequences; failures are already logged and\n // must not stop the siblings behind them.\n return pushed.catch(() => undefined);\n };\n chain = index === 0 ? deliver() : chain.then(deliver);\n });\n return;\n }\n\n // Synchronous ack: wait for delivery to settle before responding,\n // and reflect the outcome. Invalid input is the client's fault\n // (400 with the reason); anything else that failed is ours (500).\n const results = [];\n for (const event of events) {\n results.push(await env.push(event));\n }\n\n if (batched) {\n const { status, body } = batchResponse(\n results.map(pushResultToOutcome),\n );\n respond(status === 200 ? { body } : { status, body });\n return;\n }\n\n const result = results[0];\n if (result?.ok === false) {\n const invalid = result.invalid === true;\n respond({\n status: invalid ? 400 : 500,\n body: {\n success: false,\n error:\n result.error ??\n (invalid ? 'Invalid event' : 'Event was not processed'),\n timestamp: Date.now(),\n },\n });\n } else {\n respond({ body: { success: true, timestamp: Date.now() } });\n }\n return;\n }\n\n // Unsupported method\n res.status(405).json({\n success: false,\n error: 'Method not allowed. Use POST, GET, or OPTIONS.',\n });\n });\n } catch (error) {\n // The reason is logged, not returned: an unexpected fault's message can\n // carry paths, dependency names or config details, and the caller can do\n // nothing with it. Matches the error-boundary middleware's answer for the\n // same class of fault.\n env.logger.error(toError(error));\n if (!res.headersSent) {\n res.status(500).json({\n success: false,\n error: 'Internal server error',\n });\n }\n }\n };\n\n // Register handlers per route config\n const resolvedPaths = settings.paths.map((entry) =>\n typeof entry === 'string'\n ? { path: entry, methods: ['GET', 'POST'] as const }\n : {\n path: entry.path,\n methods: entry.methods || (['GET', 'POST'] as const),\n },\n );\n\n for (const route of resolvedPaths) {\n if (route.methods.includes('POST'))\n app.post(route.path, jsonParser, textParser, push);\n if (route.methods.includes('GET')) app.get(route.path, push);\n app.options(route.path, push); // Always register OPTIONS for CORS\n }\n\n // Error boundary for the middleware chain. Client-caused body errors are\n // expected ambient noise on a public endpoint: answer deliberately, count,\n // and keep them out of the error channel. Anything else is a real fault\n // and stays loud.\n app.use((err: unknown, _req: Request, res: Response, next: NextFunction) => {\n if (res.headersSent) {\n // The response is already on the wire, so this fault cannot be\n // answered. Give it a structured home before re-raising; express\n // needs the re-raise to destroy the socket.\n env.logger.error(toError(err));\n return next(err);\n }\n if (isRequestBodyError(err)) {\n countRejected();\n env.logger.debug('Request body rejected', {\n status: err.status,\n type: err.type,\n error: err.message,\n sample:\n typeof err.body === 'string' ? err.body.slice(0, 200) : undefined,\n });\n res.status(err.status).json({ success: false, error: err.message });\n return;\n }\n env.logger.error(toError(err));\n res.status(500).json({ success: false, error: 'Internal server error' });\n });\n\n // Source owns the HTTP server (if port configured)\n let server: ReturnType<typeof app.listen> | undefined;\n\n if (settings.port !== undefined) {\n server = app.listen(settings.port, () => {\n const routeLines = resolvedPaths\n .map((r) => {\n const methods = [...r.methods, 'OPTIONS'].join(', ');\n return ` ${methods} ${r.path}`;\n })\n .join('\\n');\n env.logger.info(\n `Express source listening on port ${settings.port}\\n` + routeLines,\n );\n });\n }\n\n const instance: ExpressSource = {\n type: 'express',\n config: {\n ...config,\n settings,\n },\n push,\n httpHandler: app,\n app,\n server,\n destroy: (_context) =>\n new Promise<void>((resolve, reject) => {\n if (!server) return resolve();\n server.close((err) => (err ? reject(err) : resolve()));\n }),\n };\n\n return instance;\n};\n\n// Export types (avoid re-exporting duplicates from schemas)\nexport type {\n ExpressSource,\n Config,\n PartialConfig,\n Types,\n EventRequest,\n EventResponse,\n RequestBody,\n ResponseBody,\n Push,\n Env,\n Mapping,\n InitSettings,\n Settings,\n RouteConfig,\n RouteMethod,\n AsyncByMethod,\n} from './types';\n\n// Export utils\nexport { setCorsHeaders, TRANSPARENT_GIF } from './utils';\n\nexport default sourceExpress;\n","import type { Response } from 'express';\nimport type { CorsOptions } from './schemas';\n\n/**\n * Set CORS headers on response\n *\n * @param res Express response object\n * @param corsConfig CORS configuration (false = disabled, true = allow all, object = custom)\n */\nexport function setCorsHeaders(\n res: Response,\n corsConfig: boolean | CorsOptions = true,\n): void {\n if (corsConfig === false) return;\n\n if (corsConfig === true) {\n // Simple CORS - allow all\n res.set('Access-Control-Allow-Origin', '*');\n res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.set('Access-Control-Allow-Headers', 'Content-Type');\n } else {\n // Custom CORS configuration\n if (corsConfig.origin) {\n const origin = Array.isArray(corsConfig.origin)\n ? corsConfig.origin.join(', ')\n : corsConfig.origin;\n res.set('Access-Control-Allow-Origin', origin);\n }\n\n if (corsConfig.methods) {\n res.set('Access-Control-Allow-Methods', corsConfig.methods.join(', '));\n }\n\n if (corsConfig.headers) {\n res.set('Access-Control-Allow-Headers', corsConfig.headers.join(', '));\n }\n\n if (corsConfig.credentials) {\n res.set('Access-Control-Allow-Credentials', 'true');\n }\n\n if (corsConfig.maxAge) {\n res.set('Access-Control-Max-Age', String(corsConfig.maxAge));\n }\n }\n}\n\n/**\n * Maximum POST body size, shared by every route body parser.\n */\nexport const BODY_LIMIT = '1mb';\n\n/**\n * 1x1 transparent GIF for pixel tracking\n * Base64-encoded GIF (43 bytes)\n */\nexport const TRANSPARENT_GIF = Buffer.from(\n 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',\n 'base64',\n);\n","import { buildScopeFromNodeRequest, normalizeBody } from '@walkeros/core';\nimport type { Source } from '@walkeros/core';\nimport type { Request } from 'express';\n\n/**\n * Builds the normalized scope from an Express request.\n *\n * The route parsers leave an application/json body parsed and a text/plain\n * body as a string. The string is resolved here, once: JSON when it parses\n * (sendBeacon payloads), otherwise kept raw for a `source.before` chain to\n * decode, as on the other server sources.\n *\n * @param req The Express request.\n * @returns The normalized scope.\n */\nexport function buildScope(req: Request): Source.Scope {\n return buildScopeFromNodeRequest(req, {\n body: normalizeBody(req.body),\n defaultProtocol: 'http',\n });\n}\n","import type { RouteMethod } from './types';\n\n/**\n * Per-method respond-first defaults. GET is synchronous so a step (a file\n * transformer, a cache destination) can respond with real content before\n * the GIF fallback applies; POST is respond-first so ingestion acks fast\n * and delivers asynchronously.\n */\nconst METHOD_DEFAULTS: Record<RouteMethod, boolean> = {\n GET: false,\n POST: true,\n};\n\n/**\n * Resolves the effective respond-first flag for one request method from\n * `config.async`. A boolean applies to both methods; a record overrides per\n * method, with unset methods falling back to the method default; undefined\n * yields the method default.\n *\n * @param asyncConfig The source's `config.async` value.\n * @param method The request method to resolve for.\n * @returns Whether the handler responds before the push settles.\n */\nexport function resolveRespondFirst(\n asyncConfig: boolean | Record<string, boolean> | undefined,\n method: RouteMethod,\n): boolean {\n if (asyncConfig === undefined) return METHOD_DEFAULTS[method];\n if (typeof asyncConfig === 'boolean') return asyncConfig;\n return asyncConfig[method] ?? METHOD_DEFAULTS[method];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAIO;AACP,kBAAiB;AACjB,IAAAA,eAOO;;;ACJA,SAAS,eACd,KACA,aAAoC,MAC9B;AACN,MAAI,eAAe,MAAO;AAE1B,MAAI,eAAe,MAAM;AAEvB,QAAI,IAAI,+BAA+B,GAAG;AAC1C,QAAI,IAAI,gCAAgC,oBAAoB;AAC5D,QAAI,IAAI,gCAAgC,cAAc;AAAA,EACxD,OAAO;AAEL,QAAI,WAAW,QAAQ;AACrB,YAAM,SAAS,MAAM,QAAQ,WAAW,MAAM,IAC1C,WAAW,OAAO,KAAK,IAAI,IAC3B,WAAW;AACf,UAAI,IAAI,+BAA+B,MAAM;AAAA,IAC/C;AAEA,QAAI,WAAW,SAAS;AACtB,UAAI,IAAI,gCAAgC,WAAW,QAAQ,KAAK,IAAI,CAAC;AAAA,IACvE;AAEA,QAAI,WAAW,SAAS;AACtB,UAAI,IAAI,gCAAgC,WAAW,QAAQ,KAAK,IAAI,CAAC;AAAA,IACvE;AAEA,QAAI,WAAW,aAAa;AAC1B,UAAI,IAAI,oCAAoC,MAAM;AAAA,IACpD;AAEA,QAAI,WAAW,QAAQ;AACrB,UAAI,IAAI,0BAA0B,OAAO,WAAW,MAAM,CAAC;AAAA,IAC7D;AAAA,EACF;AACF;AAKO,IAAM,aAAa;AAMnB,IAAM,kBAAkB,OAAO;AAAA,EACpC;AAAA,EACA;AACF;;;AC3DA,kBAAyD;AAelD,SAAS,WAAW,KAA4B;AACrD,aAAO,uCAA0B,KAAK;AAAA,IACpC,UAAM,2BAAc,IAAI,IAAI;AAAA,IAC5B,iBAAiB;AAAA,EACnB,CAAC;AACH;;;ACZA,IAAM,kBAAgD;A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IAAI,QAAQ,CAAC;AAClE;AAAA,IACF;AACA,QAAI,OAAO,MAAM,QAAQ,GAAG,CAAC;AAC7B,QAAI,OAAO,GAAG,EAAE,KAAK,EAAE,SAAS,OAAO,OAAO,wBAAwB,CAAC;AAAA,EACzE,CAAC;AAGD,MAAI;AAEJ,MAAI,SAAS,SAAS,QAAW;AAC/B,aAAS,IAAI,OAAO,SAAS,MAAM,MAAM;AACvC,YAAM,aAAa,cAChB,IAAI,CAAC,MAAM;AACV,cAAM,UAAU,CAAC,GAAG,EAAE,SAAS,SAAS,EAAE,KAAK,IAAI;AACnD,eAAO,MAAM,OAAO,IAAI,EAAE,IAAI;AAAA,MAChC,CAAC,EACA,KAAK,IAAI;AACZ,UAAI,OAAO;AAAA,QACT,oCAAoC,SAAS,IAAI;AAAA,IAAO;AAAA,MAC1D;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,WAA0B;AAAA,IAC9B,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,GAAG;AAAA,MACH;AAAA,IACF;AAAA,IACA;AAAA,IACA,aAAa;AAAA,IACb;AAAA,IACA;AAAA,IACA,SAAS,CAAC,aACR,IAAI,QAAc,CAAC,SAAS,WAAW;AACrC,UAAI,CAAC,OAAQ,QAAO,QAAQ;AAC5B,aAAO,MAAM,CAAC,QAAS,MAAM,OAAO,GAAG,IAAI,QAAQ,CAAE;AAAA,IACvD,CAAC;AAAA,EACL;AAEA,SAAO;AACT;AAyBA,IAAO,gBAAQ;","names":["import_core","express","cors","env"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import express from"express";import cors from"cors";import{requestToData,createRespond,toEventList,isBatchBody,batchResponse,pushResultToOutcome}from"@walkeros/core";function setCorsHeaders(res,corsConfig=!0){if(!1!==corsConfig)if(!0===corsConfig)res.set("Access-Control-Allow-Origin","*"),res.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),res.set("Access-Control-Allow-Headers","Content-Type");else{if(corsConfig.origin){const origin=Array.isArray(corsConfig.origin)?corsConfig.origin.join(", "):corsConfig.origin;res.set("Access-Control-Allow-Origin",origin)}corsConfig.methods&&res.set("Access-Control-Allow-Methods",corsConfig.methods.join(", ")),corsConfig.headers&&res.set("Access-Control-Allow-Headers",corsConfig.headers.join(", ")),corsConfig.credentials&&res.set("Access-Control-Allow-Credentials","true"),corsConfig.maxAge&&res.set("Access-Control-Max-Age",String(corsConfig.maxAge))}}var TRANSPARENT_GIF=Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","base64");import{buildScopeFromNodeRequest}from"@walkeros/core";var METHOD_DEFAULTS={GET:!1,POST:!0};function resolveRespondFirst(asyncConfig,method){return void 0===asyncConfig?METHOD_DEFAULTS[method]:"boolean"==typeof asyncConfig?asyncConfig:asyncConfig[method]??METHOD_DEFAULTS[method]}var toError=value=>value instanceof Error?value:new Error(String(value)),settleAfterAck=(result,logger)=>{result.then(settled=>{!1===settled?.ok&&!0!==settled.invalid&&logger.warn("Event not processed after ack",{failed:settled.failed?Object.keys(settled.failed):[]})},err=>{logger.error(toError(err))}).catch(()=>{})},REQUEST_BODY_ERROR_TYPES=new Set(["entity.parse.failed","entity.verify.failed","entity.too.large","charset.unsupported","encoding.unsupported","request.aborted","request.size.invalid"]),sourceExpress=async context=>{const{config:config={},env:env}=context,expressLib=env.express??express,corsLib=env.cors??cors,userSettings=config.settings||{},settings={...userSettings,cors:userSettings.cors??!0,paths:userSettings.paths??(userSettings.path?[userSettings.path]:["/collect"]),maxBatchSize:userSettings.maxBatchSize??100},maxBatchSize=settings.maxBatchSize,app=expressLib();app.disable("x-powered-by");const jsonParser=expressLib.json({limit:"1mb",type:
|
|
1
|
+
import express from"express";import cors from"cors";import{requestToData,createRespond,toEventList,isBatchBody,batchResponse,pushResultToOutcome}from"@walkeros/core";function setCorsHeaders(res,corsConfig=!0){if(!1!==corsConfig)if(!0===corsConfig)res.set("Access-Control-Allow-Origin","*"),res.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),res.set("Access-Control-Allow-Headers","Content-Type");else{if(corsConfig.origin){const origin=Array.isArray(corsConfig.origin)?corsConfig.origin.join(", "):corsConfig.origin;res.set("Access-Control-Allow-Origin",origin)}corsConfig.methods&&res.set("Access-Control-Allow-Methods",corsConfig.methods.join(", ")),corsConfig.headers&&res.set("Access-Control-Allow-Headers",corsConfig.headers.join(", ")),corsConfig.credentials&&res.set("Access-Control-Allow-Credentials","true"),corsConfig.maxAge&&res.set("Access-Control-Max-Age",String(corsConfig.maxAge))}}var TRANSPARENT_GIF=Buffer.from("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","base64");import{buildScopeFromNodeRequest,normalizeBody}from"@walkeros/core";var METHOD_DEFAULTS={GET:!1,POST:!0};function resolveRespondFirst(asyncConfig,method){return void 0===asyncConfig?METHOD_DEFAULTS[method]:"boolean"==typeof asyncConfig?asyncConfig:asyncConfig[method]??METHOD_DEFAULTS[method]}var toError=value=>value instanceof Error?value:new Error(String(value)),settleAfterAck=(result,logger)=>{result.then(settled=>{!1===settled?.ok&&!0!==settled.invalid&&logger.warn("Event not processed after ack",{failed:settled.failed?Object.keys(settled.failed):[]})},err=>{logger.error(toError(err))}).catch(()=>{})},REQUEST_BODY_ERROR_TYPES=new Set(["entity.parse.failed","entity.verify.failed","entity.too.large","charset.unsupported","encoding.unsupported","request.aborted","request.size.invalid"]),sourceExpress=async context=>{const{config:config={},env:env}=context,expressLib=env.express??express,corsLib=env.cors??cors,userSettings=config.settings||{},settings={...userSettings,cors:userSettings.cors??!0,paths:userSettings.paths??(userSettings.path?[userSettings.path]:["/collect"]),maxBatchSize:userSettings.maxBatchSize??100},maxBatchSize=settings.maxBatchSize,app=expressLib();app.disable("x-powered-by");const jsonParser=expressLib.json({limit:"1mb",type:"application/json"}),textParser=expressLib.text({limit:"1mb",type:"text/plain"});if(app.use((_req,res,next)=>{res.setHeader("X-Content-Type-Options","nosniff"),next()}),!1!==settings.cors){const corsOptions=!0===settings.cors?{}:settings.cors;app.use(corsLib(corsOptions))}const push=async(req,res)=>{try{if("OPTIONS"===req.method)return setCorsHeaders(res,settings.cors),void res.status(204).send();const respond=createRespond(options=>{const status=options.status??200;if(options.headers)for(const[key,value]of Object.entries(options.headers))res.set(key,value);res.status(status);const body=options.body;"string"==typeof body||Buffer.isBuffer(body)?res.send(body):body instanceof Uint8Array?res.send(Buffer.from(body)):res.json(body)}),scope=function(req){return buildScopeFromNodeRequest(req,{body:normalizeBody(req.body),defaultProtocol:"http"})}(req);await context.withScope(scope,respond,async env2=>{if("GET"===req.method){const parsedData=requestToData(req.url),respondGif=()=>respond({body:TRANSPARENT_GIF,headers:{"Content-Type":"image/gif","Cache-Control":"no-cache, no-store, must-revalidate"}});return void(parsedData&&"object"==typeof parsedData?resolveRespondFirst(config.async,"GET")?(respondGif(),settleAfterAck(env2.push(parsedData),env2.logger)):(await env2.push(parsedData),respondGif()):respondGif())}if("POST"===req.method){const events=toEventList(scope.body),batched=isBatchBody(scope.body);if(batched&&events.length>maxBatchSize)return void respond({status:400,body:{success:!1,error:`Batch too large. Maximum size: ${maxBatchSize} events`,timestamp:Date.now()}});if(resolveRespondFirst(config.async,"POST")){respond({body:{success:!0,timestamp:Date.now()}});let chain=Promise.resolve();return void events.forEach((event,index)=>{const deliver=()=>{const pushed=env2.push(event);return settleAfterAck(pushed,env2.logger),pushed.catch(()=>{})};chain=0===index?deliver():chain.then(deliver)})}const results=[];for(const event of events)results.push(await env2.push(event));if(batched){const{status:status,body:body}=batchResponse(results.map(pushResultToOutcome));return void respond(200===status?{body:body}:{status:status,body:body})}const result=results[0];if(!1===result?.ok){const invalid=!0===result.invalid;respond({status:invalid?400:500,body:{success:!1,error:result.error??(invalid?"Invalid event":"Event was not processed"),timestamp:Date.now()}})}else respond({body:{success:!0,timestamp:Date.now()}});return}res.status(405).json({success:!1,error:"Method not allowed. Use POST, GET, or OPTIONS."})})}catch(error){env.logger.error(toError(error)),res.headersSent||res.status(500).json({success:!1,error:"Internal server error"})}},resolvedPaths=settings.paths.map(entry=>"string"==typeof entry?{path:entry,methods:["GET","POST"]}:{path:entry.path,methods:entry.methods||["GET","POST"]});for(const route of resolvedPaths)route.methods.includes("POST")&&app.post(route.path,jsonParser,textParser,push),route.methods.includes("GET")&&app.get(route.path,push),app.options(route.path,push);let server;app.use((err,_req,res,next)=>res.headersSent?(env.logger.error(toError(err)),next(err)):(err=>{if(!(err instanceof Error))return!1;if(!("status"in err)||!("type"in err))return!1;const candidate=err;return"number"==typeof candidate.status&&candidate.status>=400&&candidate.status<500&&"string"==typeof candidate.type&&REQUEST_BODY_ERROR_TYPES.has(candidate.type)})(err)?((()=>{const sources=context.collector.status?.sources;if(!sources)return;sources[context.id]||(sources[context.id]={count:0,duration:0});const sourceStatus=sources[context.id];sourceStatus.rejected=(sourceStatus.rejected??0)+1})(),env.logger.debug("Request body rejected",{status:err.status,type:err.type,error:err.message,sample:"string"==typeof err.body?err.body.slice(0,200):void 0}),void res.status(err.status).json({success:!1,error:err.message})):(env.logger.error(toError(err)),void res.status(500).json({success:!1,error:"Internal server error"}))),void 0!==settings.port&&(server=app.listen(settings.port,()=>{const routeLines=resolvedPaths.map(r=>` ${[...r.methods,"OPTIONS"].join(", ")} ${r.path}`).join("\n");env.logger.info(`Express source listening on port ${settings.port}\n`+routeLines)}));return{type:"express",config:{...config,settings:settings},push:push,httpHandler:app,app:app,server:server,destroy:_context=>new Promise((resolve,reject)=>{if(!server)return resolve();server.close(err=>err?reject(err):resolve())})}},index_default=sourceExpress;export{TRANSPARENT_GIF,index_default as default,setCorsHeaders,sourceExpress};//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/scope.ts","../src/respond-mode.ts"],"sourcesContent":["import express, {\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\nimport cors from 'cors';\nimport {\n requestToData,\n createRespond,\n toEventList,\n isBatchBody,\n batchResponse,\n pushResultToOutcome,\n} from '@walkeros/core';\nimport type { Elb, Logger, Source } from '@walkeros/core';\nimport type { ExpressSource, Types, EventRequest } from './types';\nimport { setCorsHeaders, TRANSPARENT_GIF } from './utils';\nimport { buildScope } from './scope';\nimport { resolveRespondFirst } from './respond-mode';\n\n/**\n * Normalize an unknown rejection reason into an Error for the logger.\n * A fire-and-forget push can reject with any value; the logger accepts\n * `string | Error`, so non-Error reasons are wrapped.\n */\nconst toError = (value: unknown): Error =>\n value instanceof Error ? value : new Error(String(value));\n\n/**\n * Settle handler for respond-first pushes: the HTTP ack already went out,\n * so a pipeline decline (ok:false) or a rejection can only surface here.\n * Warn on decline; the collector has already error-logged a thrown pipeline\n * failure, this line ties the outcome to the request that was acked.\n * Invalid-input rejections stay silent here: the collector already warned\n * and counted them at the pipeline gate.\n */\nconst settleAfterAck = (\n result: Promise<Elb.PushResult>,\n logger: Logger.Instance,\n): void => {\n result\n .then(\n (settled) => {\n if (settled?.ok === false && settled.invalid !== true) {\n logger.warn('Event not processed after ack', {\n failed: settled.failed ? Object.keys(settled.failed) : [],\n });\n }\n },\n (err: unknown) => {\n logger.error(toError(err));\n },\n )\n // The derived promise would otherwise float: a throw inside the\n // handlers above (e.g. a faulty logger) must not surface as an\n // unhandled rejection on a fire-and-forget path.\n .catch(() => undefined);\n};\n\n/**\n * Client-caused body failure raised by the route-scoped JSON parser:\n * unparseable JSON, oversized payload, unsupported charset or encoding,\n * an aborted request, or a content-length mismatch. Identified by the\n * error type marker the parser attaches, so unrelated middleware errors\n * that happen to carry a 4xx status are never treated as body rejections.\n * Carries the HTTP status to answer with and, for parse failures, the raw\n * body for debug diagnostics.\n */\ninterface RequestBodyError extends Error {\n status: number;\n type: string;\n body?: unknown;\n}\n\n// Type markers body-parser and raw-body attach to client-caused body\n// failures (see body-parser lib/read.js and raw-body index.js).\nconst REQUEST_BODY_ERROR_TYPES = new Set([\n 'entity.parse.failed',\n 'entity.verify.failed',\n 'entity.too.large',\n 'charset.unsupported',\n 'encoding.unsupported',\n 'request.aborted',\n 'request.size.invalid',\n]);\n\nconst isRequestBodyError = (err: unknown): err is RequestBodyError => {\n if (!(err instanceof Error)) return false;\n if (!('status' in err) || !('type' in err)) return false;\n const candidate: { status?: unknown; type?: unknown } = err;\n return (\n typeof candidate.status === 'number' &&\n candidate.status >= 400 &&\n candidate.status < 500 &&\n typeof candidate.type === 'string' &&\n REQUEST_BODY_ERROR_TYPES.has(candidate.type)\n );\n};\n\n/**\n * Express source initialization\n *\n * This source OWNS its HTTP server infrastructure:\n * - Creates Express application\n * - Sets up middleware (JSON parsing, CORS)\n * - Registers event collection endpoints (POST, GET, OPTIONS)\n * - Starts HTTP server (if port configured)\n * - Provides destroy() for graceful shutdown (called by runner)\n *\n * @param context Source context with config, env, logger, id\n * @returns Express source instance with app and push handler\n */\nexport const sourceExpress = async (\n context: Source.Context<Types>,\n): Promise<ExpressSource> => {\n const { config = {}, env } = context;\n const expressLib = env.express ?? express;\n const corsLib = env.cors ?? cors;\n\n // Apply defaults (no runtime validation — flow.json is developer-controlled).\n const userSettings = config.settings || {};\n const settings = {\n ...userSettings,\n cors: userSettings.cors ?? true,\n paths:\n userSettings.paths ??\n (userSettings.path ? [userSettings.path] : ['/collect']),\n maxBatchSize: userSettings.maxBatchSize ?? 100,\n };\n\n const maxBatchSize = settings.maxBatchSize;\n\n // Rejection volume belongs in collector.status, not in per-request logs.\n // Lazy entry creation mirrors the collector's own sources bookkeeping.\n // Guarded: unit harnesses may run the handler with a bare collector stub.\n const countRejected = (): void => {\n const sources = context.collector.status?.sources;\n if (!sources) return;\n if (!sources[context.id]) {\n sources[context.id] = { count: 0, duration: 0 };\n }\n const sourceStatus = sources[context.id];\n sourceStatus.rejected = (sourceStatus.rejected ?? 0) + 1;\n };\n\n const app = expressLib();\n\n // The framework identity is of no use to callers and only helps someone\n // probing the endpoint pick an exploit.\n app.disable('x-powered-by');\n\n // Body parsing per configured POST route: JSON content-type plus text/plain\n // so navigator.sendBeacon payloads (which the browser forces to\n // text/plain;charset=UTF-8) are also parsed as JSON. 1mb default limit.\n // Route-scoped so unmatched paths (scanner noise) fall through to the\n // default 404 without ever touching the parser.\n const jsonParser = expressLib.json({\n limit: '1mb',\n type: ['application/json', 'text/plain'],\n });\n\n // Content-Type on some responses is flow-controlled (a cache or asset step\n // can set it through respond({ headers })), so sniffing stays off. Registered\n // before CORS and unconditionally, so it also covers the default 404 and the\n // body-rejection responses.\n app.use((_req, res, next) => {\n res.setHeader('X-Content-Type-Options', 'nosniff');\n next();\n });\n\n // CORS middleware (enabled by default)\n if (settings.cors !== false) {\n const corsOptions = settings.cors === true ? {} : settings.cors;\n app.use(corsLib(corsOptions));\n }\n\n /**\n * Request handler - transforms HTTP requests into walker events\n * Supports POST (JSON body), GET (query params), and OPTIONS (CORS preflight)\n *\n * Each inbound request gets its own `withScope` invocation. The per-scope\n * env carries this request's `ingest` and `respond` end to end, so\n * concurrent requests never crosstalk through source-factory state.\n */\n const push = async (req: Request, res: Response): Promise<void> => {\n try {\n // Handle OPTIONS for CORS preflight (no scope needed: no event, no ingest)\n if (req.method === 'OPTIONS') {\n setCorsHeaders(res, settings.cors);\n res.status(204).send();\n return;\n }\n\n // Create per-request respond — first call wins (idempotent)\n const respond = createRespond((options) => {\n const status = options.status ?? 200;\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n res.set(key, value);\n }\n }\n res.status(status);\n const body = options.body;\n if (typeof body === 'string' || Buffer.isBuffer(body)) {\n res.send(body);\n } else if (body instanceof Uint8Array) {\n // A decoded cache value surfaces binary as a plain Uint8Array,\n // not a Node Buffer; send it as bytes (res.json would corrupt it).\n res.send(Buffer.from(body));\n } else {\n res.json(body);\n }\n });\n\n const scope = buildScope(req);\n\n await context.withScope(scope, respond, async (env) => {\n // Handle GET requests (pixel tracking)\n if (req.method === 'GET') {\n // Parse query parameters to event data using requestToData\n const parsedData = requestToData(req.url);\n\n // Default GIF body (idempotent fallback; skipped if a step already\n // called respond, e.g. a cache/asset destination serving real bytes).\n const respondGif = () =>\n respond({\n body: TRANSPARENT_GIF,\n headers: {\n 'Content-Type': 'image/gif',\n 'Cache-Control': 'no-cache, no-store, must-revalidate',\n },\n });\n\n if (parsedData && typeof parsedData === 'object') {\n if (resolveRespondFirst(config.async, 'GET')) {\n // Respond-first: the tracking pixel must return instantly and\n // never block on backend delivery. Fire the push without\n // awaiting; a rejected push and a settled non-invalid decline\n // are logged (destination errors are DLQ'd inside the\n // collector). A 2xx means \"accepted\", not \"delivered\".\n respondGif();\n settleAfterAck(env.push(parsedData), env.logger);\n } else {\n // Synchronous: await the push so a step (e.g. a cache/asset\n // destination) can respond with real content before the GIF\n // fallback applies.\n await env.push(parsedData);\n respondGif();\n }\n } else {\n respondGif();\n }\n return;\n }\n\n // Handle POST requests (standard event ingestion)\n if (req.method === 'POST') {\n const events = toEventList(scope.body);\n const batched = isBatchBody(scope.body);\n\n if (batched && events.length > maxBatchSize) {\n respond({\n status: 400,\n body: {\n success: false,\n error: `Batch too large. Maximum size: ${maxBatchSize} events`,\n timestamp: Date.now(),\n },\n });\n return;\n }\n\n if (resolveRespondFirst(config.async, 'POST')) {\n // Respond-first (\"accepted\"), then deliver asynchronously. A\n // rejected push and a settled non-invalid decline are logged, not\n // surfaced to the client and not left unhandled (destination\n // errors are DLQ'd inside the collector). In this mode a batch is\n // acknowledged as accepted; per-index outcomes are not knowable\n // yet, so they surface through collector.status and logs.\n respond({ body: { success: true, timestamp: Date.now() } });\n // Ack first, then deliver in submission order. The first push\n // starts immediately, so a single event is delivered exactly as\n // before; the rest are chained so a batch keeps the order every\n // other batch path guarantees, without the client waiting.\n let chain: Promise<unknown> = Promise.resolve();\n events.forEach((event, index) => {\n const deliver = () => {\n const pushed = env.push(event);\n settleAfterAck(pushed, env.logger);\n // The chain only sequences; failures are already logged and\n // must not stop the siblings behind them.\n return pushed.catch(() => undefined);\n };\n chain = index === 0 ? deliver() : chain.then(deliver);\n });\n return;\n }\n\n // Synchronous ack: wait for delivery to settle before responding,\n // and reflect the outcome. Invalid input is the client's fault\n // (400 with the reason); anything else that failed is ours (500).\n const results = [];\n for (const event of events) {\n results.push(await env.push(event));\n }\n\n if (batched) {\n const { status, body } = batchResponse(\n results.map(pushResultToOutcome),\n );\n respond(status === 200 ? { body } : { status, body });\n return;\n }\n\n const result = results[0];\n if (result?.ok === false) {\n const invalid = result.invalid === true;\n respond({\n status: invalid ? 400 : 500,\n body: {\n success: false,\n error:\n result.error ??\n (invalid ? 'Invalid event' : 'Event was not processed'),\n timestamp: Date.now(),\n },\n });\n } else {\n respond({ body: { success: true, timestamp: Date.now() } });\n }\n return;\n }\n\n // Unsupported method\n res.status(405).json({\n success: false,\n error: 'Method not allowed. Use POST, GET, or OPTIONS.',\n });\n });\n } catch (error) {\n // The reason is logged, not returned: an unexpected fault's message can\n // carry paths, dependency names or config details, and the caller can do\n // nothing with it. Matches the error-boundary middleware's answer for the\n // same class of fault.\n env.logger.error(toError(error));\n if (!res.headersSent) {\n res.status(500).json({\n success: false,\n error: 'Internal server error',\n });\n }\n }\n };\n\n // Register handlers per route config\n const resolvedPaths = settings.paths.map((entry) =>\n typeof entry === 'string'\n ? { path: entry, methods: ['GET', 'POST'] as const }\n : {\n path: entry.path,\n methods: entry.methods || (['GET', 'POST'] as const),\n },\n );\n\n for (const route of resolvedPaths) {\n if (route.methods.includes('POST')) app.post(route.path, jsonParser, push);\n if (route.methods.includes('GET')) app.get(route.path, push);\n app.options(route.path, push); // Always register OPTIONS for CORS\n }\n\n // Error boundary for the middleware chain. Client-caused body errors are\n // expected ambient noise on a public endpoint: answer deliberately, count,\n // and keep them out of the error channel. Anything else is a real fault\n // and stays loud.\n app.use((err: unknown, _req: Request, res: Response, next: NextFunction) => {\n if (res.headersSent) {\n // The response is already on the wire, so this fault cannot be\n // answered. Give it a structured home before re-raising; express\n // needs the re-raise to destroy the socket.\n env.logger.error(toError(err));\n return next(err);\n }\n if (isRequestBodyError(err)) {\n countRejected();\n env.logger.debug('Request body rejected', {\n status: err.status,\n type: err.type,\n error: err.message,\n sample:\n typeof err.body === 'string' ? err.body.slice(0, 200) : undefined,\n });\n res.status(err.status).json({ success: false, error: err.message });\n return;\n }\n env.logger.error(toError(err));\n res.status(500).json({ success: false, error: 'Internal server error' });\n });\n\n // Source owns the HTTP server (if port configured)\n let server: ReturnType<typeof app.listen> | undefined;\n\n if (settings.port !== undefined) {\n server = app.listen(settings.port, () => {\n const routeLines = resolvedPaths\n .map((r) => {\n const methods = [...r.methods, 'OPTIONS'].join(', ');\n return ` ${methods} ${r.path}`;\n })\n .join('\\n');\n env.logger.info(\n `Express source listening on port ${settings.port}\\n` + routeLines,\n );\n });\n }\n\n const instance: ExpressSource = {\n type: 'express',\n config: {\n ...config,\n settings,\n },\n push,\n httpHandler: app,\n app,\n server,\n destroy: (_context) =>\n new Promise<void>((resolve, reject) => {\n if (!server) return resolve();\n server.close((err) => (err ? reject(err) : resolve()));\n }),\n };\n\n return instance;\n};\n\n// Export types (avoid re-exporting duplicates from schemas)\nexport type {\n ExpressSource,\n Config,\n PartialConfig,\n Types,\n EventRequest,\n EventResponse,\n RequestBody,\n ResponseBody,\n Push,\n Env,\n Mapping,\n InitSettings,\n Settings,\n RouteConfig,\n RouteMethod,\n AsyncByMethod,\n} from './types';\n\n// Export utils\nexport { setCorsHeaders, TRANSPARENT_GIF } from './utils';\n\nexport default sourceExpress;\n","import type { Response } from 'express';\nimport type { CorsOptions } from './schemas';\n\n/**\n * Set CORS headers on response\n *\n * @param res Express response object\n * @param corsConfig CORS configuration (false = disabled, true = allow all, object = custom)\n */\nexport function setCorsHeaders(\n res: Response,\n corsConfig: boolean | CorsOptions = true,\n): void {\n if (corsConfig === false) return;\n\n if (corsConfig === true) {\n // Simple CORS - allow all\n res.set('Access-Control-Allow-Origin', '*');\n res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.set('Access-Control-Allow-Headers', 'Content-Type');\n } else {\n // Custom CORS configuration\n if (corsConfig.origin) {\n const origin = Array.isArray(corsConfig.origin)\n ? corsConfig.origin.join(', ')\n : corsConfig.origin;\n res.set('Access-Control-Allow-Origin', origin);\n }\n\n if (corsConfig.methods) {\n res.set('Access-Control-Allow-Methods', corsConfig.methods.join(', '));\n }\n\n if (corsConfig.headers) {\n res.set('Access-Control-Allow-Headers', corsConfig.headers.join(', '));\n }\n\n if (corsConfig.credentials) {\n res.set('Access-Control-Allow-Credentials', 'true');\n }\n\n if (corsConfig.maxAge) {\n res.set('Access-Control-Max-Age', String(corsConfig.maxAge));\n }\n }\n}\n\n/**\n * 1x1 transparent GIF for pixel tracking\n * Base64-encoded GIF (43 bytes)\n */\nexport const TRANSPARENT_GIF = Buffer.from(\n 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',\n 'base64',\n);\n","import { buildScopeFromNodeRequest } from '@walkeros/core';\nimport type { Source } from '@walkeros/core';\nimport type { Request } from 'express';\n\n/**\n * Builds the normalized scope from an Express request.\n *\n * The body is taken as-is: the route's JSON parser has already parsed it,\n * including `text/plain` beacons, so no second parse belongs here.\n *\n * @param req The Express request.\n * @returns The normalized scope.\n */\nexport function buildScope(req: Request): Source.Scope {\n return buildScopeFromNodeRequest(req, {\n body: req.body,\n defaultProtocol: 'http',\n });\n}\n","import type { RouteMethod } from './types';\n\n/**\n * Per-method respond-first defaults. GET is synchronous so a step (a file\n * transformer, a cache destination) can respond with real content before\n * the GIF fallback applies; POST is respond-first so ingestion acks fast\n * and delivers asynchronously.\n */\nconst METHOD_DEFAULTS: Record<RouteMethod, boolean> = {\n GET: false,\n POST: true,\n};\n\n/**\n * Resolves the effective respond-first flag for one request method from\n * `config.async`. A boolean applies to both methods; a record overrides per\n * method, with unset methods falling back to the method default; undefined\n * yields the method default.\n *\n * @param asyncConfig The source's `config.async` value.\n * @param method The request method to resolve for.\n * @returns Whether the handler responds before the push settles.\n */\nexport function resolveRespondFirst(\n asyncConfig: boolean | Record<string, boolean> | undefined,\n method: RouteMethod,\n): boolean {\n if (asyncConfig === undefined) return METHOD_DEFAULTS[method];\n if (typeof asyncConfig === 'boolean') return asyncConfig;\n return asyncConfig[method] ?? METHOD_DEFAULTS[method];\n}\n"],"mappings":";AAAA,OAAO,aAIA;AACP,OAAO,UAAU;AACjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACJA,SAAS,eACd,KACA,aAAoC,MAC9B;AACN,MAAI,eAAe,MAAO;AAE1B,MAAI,eAAe,MAAM;AAEvB,QAAI,IAAI,+BAA+B,GAAG;AAC1C,QAAI,IAAI,gCAAgC,oBAAoB;AAC5D,QAAI,IAAI,gCAAgC,cAAc;AAAA,EACxD,OAAO;AAEL,QAAI,WAAW,QAAQ;AACrB,YAAM,SAAS,MAAM,QAAQ,WAAW,MAAM,IAC1C,WAAW,OAAO,KAAK,IAAI,IAC3B,WAAW;AACf,UAAI,IAAI,+BAA+B,MAAM;AAAA,IAC/C;AAEA,QAAI,WAAW,SAAS;AACtB,UAAI,IAAI,gCAAgC,WAAW,QAAQ,KAAK,IAAI,CAAC;AAAA,IACvE;AAEA,QAAI,WAAW,SAAS;AACtB,UAAI,IAAI,gCAAgC,WAAW,QAAQ,KAAK,IAAI,CAAC;AAAA,IACvE;AAEA,QAAI,WAAW,aAAa;AAC1B,UAAI,IAAI,oCAAoC,MAAM;AAAA,IACpD;AAEA,QAAI,WAAW,QAAQ;AACrB,UAAI,IAAI,0BAA0B,OAAO,WAAW,MAAM,CAAC;AAAA,IAC7D;AAAA,EACF;AACF;AAMO,IAAM,kBAAkB,OAAO;AAAA,EACpC;AAAA,EACA;AACF;;;ACtDA,SAAS,iCAAiC;AAanC,SAAS,WAAW,KAA4B;AACrD,SAAO,0BAA0B,KAAK;AAAA,IACpC,MAAM,IAAI;AAAA,IACV,iBAAiB;AAAA,EACnB,CAAC;AACH;;;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,GAAG,CAAC;AAC7B,QAAI,OAAO,GAAG,EAAE,KAAK,EAAE,SAAS,OAAO,OAAO,wBAAwB,CAAC;AAAA,EACzE,CAAC;AAGD,MAAI;AAEJ,MAAI,SAAS,SAAS,QAAW;AAC/B,aAAS,IAAI,OAAO,SAAS,MAAM,MAAM;AACvC,YAAM,aAAa,cAChB,IAAI,CAAC,MAAM;AACV,cAAM,UAAU,CAAC,GAAG,EAAE,SAAS,SAAS,EAAE,KAAK,IAAI;AACnD,eAAO,MAAM,OAAO,IAAI,EAAE,IAAI;AAAA,MAChC,CAAC,EACA,KAAK,IAAI;AACZ,UAAI,OAAO;AAAA,QACT,oCAAoC,SAAS,IAAI;AAAA,IAAO;AAAA,MAC1D;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,WAA0B;AAAA,IAC9B,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,GAAG;AAAA,MACH;AAAA,IACF;AAAA,IACA;AAAA,IACA,aAAa;AAAA,IACb;AAAA,IACA;AAAA,IACA,SAAS,CAAC,aACR,IAAI,QAAc,CAAC,SAAS,WAAW;AACrC,UAAI,CAAC,OAAQ,QAAO,QAAQ;AAC5B,aAAO,MAAM,CAAC,QAAS,MAAM,OAAO,GAAG,IAAI,QAAQ,CAAE;AAAA,IACvD,CAAC;AAAA,EACL;AAEA,SAAO;AACT;AAyBA,IAAO,gBAAQ;","names":["env"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/scope.ts","../src/respond-mode.ts"],"sourcesContent":["import express, {\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\nimport cors from 'cors';\nimport {\n requestToData,\n createRespond,\n toEventList,\n isBatchBody,\n batchResponse,\n pushResultToOutcome,\n} from '@walkeros/core';\nimport type { Elb, Logger, Source } from '@walkeros/core';\nimport type { ExpressSource, Types, EventRequest } from './types';\nimport { BODY_LIMIT, setCorsHeaders, TRANSPARENT_GIF } from './utils';\nimport { buildScope } from './scope';\nimport { resolveRespondFirst } from './respond-mode';\n\n/**\n * Normalize an unknown rejection reason into an Error for the logger.\n * A fire-and-forget push can reject with any value; the logger accepts\n * `string | Error`, so non-Error reasons are wrapped.\n */\nconst toError = (value: unknown): Error =>\n value instanceof Error ? value : new Error(String(value));\n\n/**\n * Settle handler for respond-first pushes: the HTTP ack already went out,\n * so a pipeline decline (ok:false) or a rejection can only surface here.\n * Warn on decline; the collector has already error-logged a thrown pipeline\n * failure, this line ties the outcome to the request that was acked.\n * Invalid-input rejections stay silent here: the collector already warned\n * and counted them at the pipeline gate.\n */\nconst settleAfterAck = (\n result: Promise<Elb.PushResult>,\n logger: Logger.Instance,\n): void => {\n result\n .then(\n (settled) => {\n if (settled?.ok === false && settled.invalid !== true) {\n logger.warn('Event not processed after ack', {\n failed: settled.failed ? Object.keys(settled.failed) : [],\n });\n }\n },\n (err: unknown) => {\n logger.error(toError(err));\n },\n )\n // The derived promise would otherwise float: a throw inside the\n // handlers above (e.g. a faulty logger) must not surface as an\n // unhandled rejection on a fire-and-forget path.\n .catch(() => undefined);\n};\n\n/**\n * Client-caused body failure raised by the route-scoped body parsers:\n * an unparseable application/json body, oversized payload, unsupported\n * charset or encoding, an aborted request, or a content-length mismatch.\n * Identified by the error type marker the parser attaches, so unrelated\n * middleware errors that happen to carry a 4xx status are never treated as\n * body rejections. Carries the HTTP status to answer with and, for parse\n * failures, the raw body for debug diagnostics.\n */\ninterface RequestBodyError extends Error {\n status: number;\n type: string;\n body?: unknown;\n}\n\n// Type markers body-parser and raw-body attach to client-caused body\n// failures (see body-parser lib/read.js and raw-body index.js).\nconst REQUEST_BODY_ERROR_TYPES = new Set([\n 'entity.parse.failed',\n 'entity.verify.failed',\n 'entity.too.large',\n 'charset.unsupported',\n 'encoding.unsupported',\n 'request.aborted',\n 'request.size.invalid',\n]);\n\nconst isRequestBodyError = (err: unknown): err is RequestBodyError => {\n if (!(err instanceof Error)) return false;\n if (!('status' in err) || !('type' in err)) return false;\n const candidate: { status?: unknown; type?: unknown } = err;\n return (\n typeof candidate.status === 'number' &&\n candidate.status >= 400 &&\n candidate.status < 500 &&\n typeof candidate.type === 'string' &&\n REQUEST_BODY_ERROR_TYPES.has(candidate.type)\n );\n};\n\n/**\n * Express source initialization\n *\n * This source OWNS its HTTP server infrastructure:\n * - Creates Express application\n * - Sets up middleware (JSON parsing, CORS)\n * - Registers event collection endpoints (POST, GET, OPTIONS)\n * - Starts HTTP server (if port configured)\n * - Provides destroy() for graceful shutdown (called by runner)\n *\n * @param context Source context with config, env, logger, id\n * @returns Express source instance with app and push handler\n */\nexport const sourceExpress = async (\n context: Source.Context<Types>,\n): Promise<ExpressSource> => {\n const { config = {}, env } = context;\n const expressLib = env.express ?? express;\n const corsLib = env.cors ?? cors;\n\n // Apply defaults (no runtime validation — flow.json is developer-controlled).\n const userSettings = config.settings || {};\n const settings = {\n ...userSettings,\n cors: userSettings.cors ?? true,\n paths:\n userSettings.paths ??\n (userSettings.path ? [userSettings.path] : ['/collect']),\n maxBatchSize: userSettings.maxBatchSize ?? 100,\n };\n\n const maxBatchSize = settings.maxBatchSize;\n\n // Rejection volume belongs in collector.status, not in per-request logs.\n // Lazy entry creation mirrors the collector's own sources bookkeeping.\n // Guarded: unit harnesses may run the handler with a bare collector stub.\n const countRejected = (): void => {\n const sources = context.collector.status?.sources;\n if (!sources) return;\n if (!sources[context.id]) {\n sources[context.id] = { count: 0, duration: 0 };\n }\n const sourceStatus = sources[context.id];\n sourceStatus.rejected = (sourceStatus.rejected ?? 0) + 1;\n };\n\n const app = expressLib();\n\n // The framework identity is of no use to callers and only helps someone\n // probing the endpoint pick an exploit.\n app.disable('x-powered-by');\n\n // Body parsing per configured POST route. application/json must parse, or\n // the request is rejected. text/plain is read as a string and resolved in\n // buildScope: JSON when it parses (navigator.sendBeacon forces\n // text/plain;charset=UTF-8 on JSON payloads), raw input otherwise, so a\n // source.before chain can decode it (e.g. batched gtag.js hits).\n // Route-scoped so unmatched paths (scanner noise) fall through to the\n // default 404 without ever touching a parser.\n const jsonParser = expressLib.json({\n limit: BODY_LIMIT,\n type: 'application/json',\n });\n const textParser = expressLib.text({\n limit: BODY_LIMIT,\n type: 'text/plain',\n });\n\n // Content-Type on some responses is flow-controlled (a cache or asset step\n // can set it through respond({ headers })), so sniffing stays off. Registered\n // before CORS and unconditionally, so it also covers the default 404 and the\n // body-rejection responses.\n app.use((_req, res, next) => {\n res.setHeader('X-Content-Type-Options', 'nosniff');\n next();\n });\n\n // CORS middleware (enabled by default)\n if (settings.cors !== false) {\n const corsOptions = settings.cors === true ? {} : settings.cors;\n app.use(corsLib(corsOptions));\n }\n\n /**\n * Request handler - transforms HTTP requests into walker events\n * Supports POST (JSON or text body), GET (query params), and OPTIONS (CORS\n * preflight)\n *\n * Each inbound request gets its own `withScope` invocation. The per-scope\n * env carries this request's `ingest` and `respond` end to end, so\n * concurrent requests never crosstalk through source-factory state.\n */\n const push = async (req: Request, res: Response): Promise<void> => {\n try {\n // Handle OPTIONS for CORS preflight (no scope needed: no event, no ingest)\n if (req.method === 'OPTIONS') {\n setCorsHeaders(res, settings.cors);\n res.status(204).send();\n return;\n }\n\n // Create per-request respond — first call wins (idempotent)\n const respond = createRespond((options) => {\n const status = options.status ?? 200;\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n res.set(key, value);\n }\n }\n res.status(status);\n const body = options.body;\n if (typeof body === 'string' || Buffer.isBuffer(body)) {\n res.send(body);\n } else if (body instanceof Uint8Array) {\n // A decoded cache value surfaces binary as a plain Uint8Array,\n // not a Node Buffer; send it as bytes (res.json would corrupt it).\n res.send(Buffer.from(body));\n } else {\n res.json(body);\n }\n });\n\n const scope = buildScope(req);\n\n await context.withScope(scope, respond, async (env) => {\n // Handle GET requests (pixel tracking)\n if (req.method === 'GET') {\n // Parse query parameters to event data using requestToData\n const parsedData = requestToData(req.url);\n\n // Default GIF body (idempotent fallback; skipped if a step already\n // called respond, e.g. a cache/asset destination serving real bytes).\n const respondGif = () =>\n respond({\n body: TRANSPARENT_GIF,\n headers: {\n 'Content-Type': 'image/gif',\n 'Cache-Control': 'no-cache, no-store, must-revalidate',\n },\n });\n\n if (parsedData && typeof parsedData === 'object') {\n if (resolveRespondFirst(config.async, 'GET')) {\n // Respond-first: the tracking pixel must return instantly and\n // never block on backend delivery. Fire the push without\n // awaiting; a rejected push and a settled non-invalid decline\n // are logged (destination errors are DLQ'd inside the\n // collector). A 2xx means \"accepted\", not \"delivered\".\n respondGif();\n settleAfterAck(env.push(parsedData), env.logger);\n } else {\n // Synchronous: await the push so a step (e.g. a cache/asset\n // destination) can respond with real content before the GIF\n // fallback applies.\n await env.push(parsedData);\n respondGif();\n }\n } else {\n respondGif();\n }\n return;\n }\n\n // Handle POST requests (standard event ingestion)\n if (req.method === 'POST') {\n const events = toEventList(scope.body);\n const batched = isBatchBody(scope.body);\n\n if (batched && events.length > maxBatchSize) {\n respond({\n status: 400,\n body: {\n success: false,\n error: `Batch too large. Maximum size: ${maxBatchSize} events`,\n timestamp: Date.now(),\n },\n });\n return;\n }\n\n if (resolveRespondFirst(config.async, 'POST')) {\n // Respond-first (\"accepted\"), then deliver asynchronously. A\n // rejected push and a settled non-invalid decline are logged, not\n // surfaced to the client and not left unhandled (destination\n // errors are DLQ'd inside the collector). In this mode a batch is\n // acknowledged as accepted; per-index outcomes are not knowable\n // yet, so they surface through collector.status and logs.\n respond({ body: { success: true, timestamp: Date.now() } });\n // Ack first, then deliver in submission order. The first push\n // starts immediately, so a single event is delivered exactly as\n // before; the rest are chained so a batch keeps the order every\n // other batch path guarantees, without the client waiting.\n let chain: Promise<unknown> = Promise.resolve();\n events.forEach((event, index) => {\n const deliver = () => {\n const pushed = env.push(event);\n settleAfterAck(pushed, env.logger);\n // The chain only sequences; failures are already logged and\n // must not stop the siblings behind them.\n return pushed.catch(() => undefined);\n };\n chain = index === 0 ? deliver() : chain.then(deliver);\n });\n return;\n }\n\n // Synchronous ack: wait for delivery to settle before responding,\n // and reflect the outcome. Invalid input is the client's fault\n // (400 with the reason); anything else that failed is ours (500).\n const results = [];\n for (const event of events) {\n results.push(await env.push(event));\n }\n\n if (batched) {\n const { status, body } = batchResponse(\n results.map(pushResultToOutcome),\n );\n respond(status === 200 ? { body } : { status, body });\n return;\n }\n\n const result = results[0];\n if (result?.ok === false) {\n const invalid = result.invalid === true;\n respond({\n status: invalid ? 400 : 500,\n body: {\n success: false,\n error:\n result.error ??\n (invalid ? 'Invalid event' : 'Event was not processed'),\n timestamp: Date.now(),\n },\n });\n } else {\n respond({ body: { success: true, timestamp: Date.now() } });\n }\n return;\n }\n\n // Unsupported method\n res.status(405).json({\n success: false,\n error: 'Method not allowed. Use POST, GET, or OPTIONS.',\n });\n });\n } catch (error) {\n // The reason is logged, not returned: an unexpected fault's message can\n // carry paths, dependency names or config details, and the caller can do\n // nothing with it. Matches the error-boundary middleware's answer for the\n // same class of fault.\n env.logger.error(toError(error));\n if (!res.headersSent) {\n res.status(500).json({\n success: false,\n error: 'Internal server error',\n });\n }\n }\n };\n\n // Register handlers per route config\n const resolvedPaths = settings.paths.map((entry) =>\n typeof entry === 'string'\n ? { path: entry, methods: ['GET', 'POST'] as const }\n : {\n path: entry.path,\n methods: entry.methods || (['GET', 'POST'] as const),\n },\n );\n\n for (const route of resolvedPaths) {\n if (route.methods.includes('POST'))\n app.post(route.path, jsonParser, textParser, push);\n if (route.methods.includes('GET')) app.get(route.path, push);\n app.options(route.path, push); // Always register OPTIONS for CORS\n }\n\n // Error boundary for the middleware chain. Client-caused body errors are\n // expected ambient noise on a public endpoint: answer deliberately, count,\n // and keep them out of the error channel. Anything else is a real fault\n // and stays loud.\n app.use((err: unknown, _req: Request, res: Response, next: NextFunction) => {\n if (res.headersSent) {\n // The response is already on the wire, so this fault cannot be\n // answered. Give it a structured home before re-raising; express\n // needs the re-raise to destroy the socket.\n env.logger.error(toError(err));\n return next(err);\n }\n if (isRequestBodyError(err)) {\n countRejected();\n env.logger.debug('Request body rejected', {\n status: err.status,\n type: err.type,\n error: err.message,\n sample:\n typeof err.body === 'string' ? err.body.slice(0, 200) : undefined,\n });\n res.status(err.status).json({ success: false, error: err.message });\n return;\n }\n env.logger.error(toError(err));\n res.status(500).json({ success: false, error: 'Internal server error' });\n });\n\n // Source owns the HTTP server (if port configured)\n let server: ReturnType<typeof app.listen> | undefined;\n\n if (settings.port !== undefined) {\n server = app.listen(settings.port, () => {\n const routeLines = resolvedPaths\n .map((r) => {\n const methods = [...r.methods, 'OPTIONS'].join(', ');\n return ` ${methods} ${r.path}`;\n })\n .join('\\n');\n env.logger.info(\n `Express source listening on port ${settings.port}\\n` + routeLines,\n );\n });\n }\n\n const instance: ExpressSource = {\n type: 'express',\n config: {\n ...config,\n settings,\n },\n push,\n httpHandler: app,\n app,\n server,\n destroy: (_context) =>\n new Promise<void>((resolve, reject) => {\n if (!server) return resolve();\n server.close((err) => (err ? reject(err) : resolve()));\n }),\n };\n\n return instance;\n};\n\n// Export types (avoid re-exporting duplicates from schemas)\nexport type {\n ExpressSource,\n Config,\n PartialConfig,\n Types,\n EventRequest,\n EventResponse,\n RequestBody,\n ResponseBody,\n Push,\n Env,\n Mapping,\n InitSettings,\n Settings,\n RouteConfig,\n RouteMethod,\n AsyncByMethod,\n} from './types';\n\n// Export utils\nexport { setCorsHeaders, TRANSPARENT_GIF } from './utils';\n\nexport default sourceExpress;\n","import type { Response } from 'express';\nimport type { CorsOptions } from './schemas';\n\n/**\n * Set CORS headers on response\n *\n * @param res Express response object\n * @param corsConfig CORS configuration (false = disabled, true = allow all, object = custom)\n */\nexport function setCorsHeaders(\n res: Response,\n corsConfig: boolean | CorsOptions = true,\n): void {\n if (corsConfig === false) return;\n\n if (corsConfig === true) {\n // Simple CORS - allow all\n res.set('Access-Control-Allow-Origin', '*');\n res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.set('Access-Control-Allow-Headers', 'Content-Type');\n } else {\n // Custom CORS configuration\n if (corsConfig.origin) {\n const origin = Array.isArray(corsConfig.origin)\n ? corsConfig.origin.join(', ')\n : corsConfig.origin;\n res.set('Access-Control-Allow-Origin', origin);\n }\n\n if (corsConfig.methods) {\n res.set('Access-Control-Allow-Methods', corsConfig.methods.join(', '));\n }\n\n if (corsConfig.headers) {\n res.set('Access-Control-Allow-Headers', corsConfig.headers.join(', '));\n }\n\n if (corsConfig.credentials) {\n res.set('Access-Control-Allow-Credentials', 'true');\n }\n\n if (corsConfig.maxAge) {\n res.set('Access-Control-Max-Age', String(corsConfig.maxAge));\n }\n }\n}\n\n/**\n * Maximum POST body size, shared by every route body parser.\n */\nexport const BODY_LIMIT = '1mb';\n\n/**\n * 1x1 transparent GIF for pixel tracking\n * Base64-encoded GIF (43 bytes)\n */\nexport const TRANSPARENT_GIF = Buffer.from(\n 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',\n 'base64',\n);\n","import { buildScopeFromNodeRequest, normalizeBody } from '@walkeros/core';\nimport type { Source } from '@walkeros/core';\nimport type { Request } from 'express';\n\n/**\n * Builds the normalized scope from an Express request.\n *\n * The route parsers leave an application/json body parsed and a text/plain\n * body as a string. The string is resolved here, once: JSON when it parses\n * (sendBeacon payloads), otherwise kept raw for a `source.before` chain to\n * decode, as on the other server sources.\n *\n * @param req The Express request.\n * @returns The normalized scope.\n */\nexport function buildScope(req: Request): Source.Scope {\n return buildScopeFromNodeRequest(req, {\n body: normalizeBody(req.body),\n defaultProtocol: 'http',\n });\n}\n","import type { RouteMethod } from './types';\n\n/**\n * Per-method respond-first defaults. GET is synchronous so a step (a file\n * transformer, a cache destination) can respond with real content before\n * the GIF fallback applies; POST is respond-first so ingestion acks fast\n * and delivers asynchronously.\n */\nconst METHOD_DEFAULTS: Record<RouteMethod, boolean> = {\n GET: false,\n POST: true,\n};\n\n/**\n * Resolves the effective respond-first flag for one request method from\n * `config.async`. A boolean applies to both methods; a record overrides per\n * method, with unset methods falling back to the method default; undefined\n * yields the method default.\n *\n * @param asyncConfig The source's `config.async` value.\n * @param method The request method to resolve for.\n * @returns Whether the handler responds before the push settles.\n */\nexport function resolveRespondFirst(\n asyncConfig: boolean | Record<string, boolean> | undefined,\n method: RouteMethod,\n): boolean {\n if (asyncConfig === undefined) return METHOD_DEFAULTS[method];\n if (typeof asyncConfig === 'boolean') return asyncConfig;\n return asyncConfig[method] ?? METHOD_DEFAULTS[method];\n}\n"],"mappings":";AAAA,OAAO,aAIA;AACP,OAAO,UAAU;AACjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACJA,SAAS,eACd,KACA,aAAoC,MAC9B;AACN,MAAI,eAAe,MAAO;AAE1B,MAAI,eAAe,MAAM;AAEvB,QAAI,IAAI,+BAA+B,GAAG;AAC1C,QAAI,IAAI,gCAAgC,oBAAoB;AAC5D,QAAI,IAAI,gCAAgC,cAAc;AAAA,EACxD,OAAO;AAEL,QAAI,WAAW,QAAQ;AACrB,YAAM,SAAS,MAAM,QAAQ,WAAW,MAAM,IAC1C,WAAW,OAAO,KAAK,IAAI,IAC3B,WAAW;AACf,UAAI,IAAI,+BAA+B,MAAM;AAAA,IAC/C;AAEA,QAAI,WAAW,SAAS;AACtB,UAAI,IAAI,gCAAgC,WAAW,QAAQ,KAAK,IAAI,CAAC;AAAA,IACvE;AAEA,QAAI,WAAW,SAAS;AACtB,UAAI,IAAI,gCAAgC,WAAW,QAAQ,KAAK,IAAI,CAAC;AAAA,IACvE;AAEA,QAAI,WAAW,aAAa;AAC1B,UAAI,IAAI,oCAAoC,MAAM;AAAA,IACpD;AAEA,QAAI,WAAW,QAAQ;AACrB,UAAI,IAAI,0BAA0B,OAAO,WAAW,MAAM,CAAC;AAAA,IAC7D;AAAA,EACF;AACF;AAKO,IAAM,aAAa;AAMnB,IAAM,kBAAkB,OAAO;AAAA,EACpC;AAAA,EACA;AACF;;;AC3DA,SAAS,2BAA2B,qBAAqB;AAelD,SAAS,WAAW,KAA4B;AACrD,SAAO,0BAA0B,KAAK;AAAA,IAC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C5D,CAAC;AACD,UAAI,OAAO,IAAI,MAAM,EAAE,KAAK,EAAE,SAAS,OAAO,OAAO,IAAI,QAAQ,CAAC;AAClE;AAAA,IACF;AACA,QAAI,OAAO,MAAM,QAAQ,GAAG,CAAC;AAC7B,QAAI,OAAO,GAAG,EAAE,KAAK,EAAE,SAAS,OAAO,OAAO,wBAAwB,CAAC;AAAA,EACzE,CAAC;AAGD,MAAI;AAEJ,MAAI,SAAS,SAAS,QAAW;AAC/B,aAAS,IAAI,OAAO,SAAS,MAAM,MAAM;AACvC,YAAM,aAAa,cAChB,IAAI,CAAC,MAAM;AACV,cAAM,UAAU,CAAC,GAAG,EAAE,SAAS,SAAS,EAAE,KAAK,IAAI;AACnD,eAAO,MAAM,OAAO,IAAI,EAAE,IAAI;AAAA,MAChC,CAAC,EACA,KAAK,IAAI;AACZ,UAAI,OAAO;AAAA,QACT,oCAAoC,SAAS,IAAI;AAAA,IAAO;AAAA,MAC1D;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,WAA0B;AAAA,IAC9B,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,GAAG;AAAA,MACH;AAAA,IACF;AAAA,IACA;AAAA,IACA,aAAa;AAAA,IACb;AAAA,IACA;AAAA,IACA,SAAS,CAAC,aACR,IAAI,QAAc,CAAC,SAAS,WAAW;AACrC,UAAI,CAAC,OAAQ,QAAO,QAAQ;AAC5B,aAAO,MAAM,CAAC,QAAS,MAAM,OAAO,GAAG,IAAI,QAAQ,CAAE;AAAA,IACvD,CAAC;AAAA,EACL;AAEA,SAAO;AACT;AAyBA,IAAO,gBAAQ;","names":["env"]}
|
package/dist/walkerOS.json
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@walkeros/server-source-express",
|
|
3
3
|
"description": "Express server source for walkerOS",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.7.0-next-1790187973605",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"module": "./dist/index.mjs",
|
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
"update": "npx npm-check-updates -u && npm update"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@walkeros/collector": "4.
|
|
24
|
-
"@walkeros/core": "4.
|
|
23
|
+
"@walkeros/collector": "4.7.0-next-1790187973605",
|
|
24
|
+
"@walkeros/core": "4.7.0-next-1790187973605",
|
|
25
25
|
"express": "^5.2.1",
|
|
26
26
|
"cors": "^2.8.5"
|
|
27
27
|
},
|