@monetizationos/proxy 1.0.3 → 1.2.0

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/README.md CHANGED
@@ -29,6 +29,7 @@ const proxy = new MOSProxyBuilder()
29
29
  mosEndpointsPrefix: "/mos-endpoints/",
30
30
  anonymousSessionCookieName: "anon-session-id",
31
31
  authenticatedUserJwtCookieName: "__session",
32
+ createAnonymousIdentifierFallback: true,
32
33
  injectScriptUrl: "https://assets.monetizationos.com/web-components-latest.js",
33
34
  originRequestHeaders: { "X-Api-Key": process.env.ORIGIN_API_KEY! },
34
35
  })
@@ -1,6 +1,7 @@
1
1
  import type { ClientMetadataProvider } from './adapters/ClientMetadataProvider';
2
2
  import type { Fetcher } from './adapters/Fetcher';
3
3
  import type { HtmlRewriterAdapter } from './adapters/HtmlRewriterAdapter';
4
+ import type { IdentityProvider } from './adapters/IdentityProvider';
4
5
  import { type MOSProxyLogger } from './logger';
5
6
  import type { MOSConfigInput } from './types';
6
7
  export type MOSProxyHtmlPipelineStage = 'origin-response' | 'link-rewriting' | 'surface-decisions' | 'surface-behavior' | 'surface-components';
@@ -24,6 +25,7 @@ export interface MOSProxyOptions {
24
25
  apiFetcher: Fetcher | null;
25
26
  htmlRewriter: HtmlRewriterAdapter | null;
26
27
  clientMetadataProvider: ClientMetadataProvider | null;
28
+ identityProvider: IdentityProvider | null;
27
29
  logger?: MOSProxyLogger;
28
30
  onHtmlPipelineError?: MOSProxyHtmlPipelineErrorHandler;
29
31
  customEndpointsEnabled: boolean;
package/dist/MOSProxy.js CHANGED
@@ -20,7 +20,7 @@ export class MOSProxy {
20
20
  this.config = normalizeMOSConfig(opts.config, opts.logger ?? consoleLogger);
21
21
  }
22
22
  async handle(request) {
23
- const { originFetcher, apiFetcher, htmlRewriter, clientMetadataProvider, onHtmlPipelineError } = this.opts;
23
+ const { originFetcher, apiFetcher, htmlRewriter, clientMetadataProvider, identityProvider, onHtmlPipelineError } = this.opts;
24
24
  const logger = this.opts.logger ?? consoleLogger;
25
25
  const ctx = { config: this.config, logger };
26
26
  // Stage 1a: custom endpoint routing
@@ -61,7 +61,7 @@ export class MOSProxy {
61
61
  throw new Error('MOSProxy: surfaceDecisions is enabled but no API fetcher is configured');
62
62
  }
63
63
  stage = 'surface-decisions';
64
- const [modifiedResponse, surfaceDecisions] = await getSurfaceDecisions(ctx, request, rewrittenResponse, apiFetcher, htmlRewriter, clientMetadataProvider);
64
+ const [modifiedResponse, surfaceDecisions] = await getSurfaceDecisions(ctx, request, rewrittenResponse, apiFetcher, htmlRewriter, clientMetadataProvider, identityProvider);
65
65
  if (!surfaceDecisions) {
66
66
  return modifiedResponse;
67
67
  }
@@ -1 +1 @@
1
- {"version":3,"file":"MOSProxy.js","sourceRoot":"","sources":["../src/MOSProxy.ts"],"names":[],"mappings":"AAGA,OAAO,EAAkB,kBAAkB,EAAE,MAAM,UAAU,CAAA;AAE7D,OAAO,EAAE,aAAa,EAAuB,MAAM,UAAU,CAAA;AAC7D,OAAO,qBAAqB,MAAM,yBAAyB,CAAA;AAC3D,OAAO,kBAAkB,MAAM,6BAA6B,CAAA;AAC5D,OAAO,qBAAqB,MAAM,wBAAwB,CAAA;AAC1D,OAAO,oBAAoB,MAAM,wBAAwB,CAAA;AACzD,OAAO,gBAAgB,MAAM,2BAA2B,CAAA;AACxD,OAAO,qBAAqB,MAAM,0BAA0B,CAAA;AAC5D,OAAO,uBAAuB,MAAM,4BAA4B,CAAA;AAChE,OAAO,mBAAmB,MAAM,2BAA2B,CAAA;AAwC3D;;;GAGG;AACH,MAAM,OAAO,QAAQ;IAGY;IAFZ,MAAM,CAAW;IAElC,YAA6B,IAAqB;QAArB,SAAI,GAAJ,IAAI,CAAiB;QAC9C,IAAI,CAAC,MAAM,GAAG,kBAAkB,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,aAAa,CAAC,CAAA;IAC/E,CAAC;IAED,KAAK,CAAC,MAAM,CA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AAA;YAC3B,CAAC;QACL,CAAC;IACL,CAAC;CACJ;AAED,MAAM,wBAAwB,GAAG,CAAC,QAAkB,EAAE,MAAsB,EAAE,KAAgC,EAAY,EAAE;IACxH,IAAI,CAAC;QACD,OAAO,QAAQ,CAAC,KAAK,EAAE,CAAA;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,MAAM,CAAC,GAAG,CAAC;YACP,KAAK,EAAE,MAAM;YACb,IAAI,EAAE,uBAAuB;YAC7B,OAAO,EAAE,kDAAkD;YAC3D,OAAO,EAAE,EAAE,KAAK,EAAE;YAClB,KAAK;SACR,CAAC,CAAA;QACF,OAAO,QAAQ,CAAA;IACnB,CAAC;AACL,CAAC,CAAA","sourcesContent":["import type { ClientMetadataProvider } from './adapters/ClientMetadataProvider'\nimport type { Fetcher } from './adapters/Fetcher'\nimport type { HtmlRewriterAdapter } from './adapters/HtmlRewriterAdapter'\nimport { type MOSConfig, normalizeMOSConfig } from './config'\nimport type { PipelineContext } from './context'\nimport { consoleLogger, type MOSProxyLogger } from './logger'\nimport customEndpointRequest from './stages/customEndpoint'\nimport isRedirectResponse from './stages/isRedirectResponse'\nimport rewriteOriginResponse from './stages/linkRewriting'\nimport performOriginRequest from './stages/originRequest'\nimport shouldIgnorePath from './stages/shouldIgnorePath'\nimport handleSurfaceBehavior from './stages/surfaceBehavior'\nimport handleSurfaceComponents from './stages/surfaceComponents'\nimport getSurfaceDecisions from './stages/surfaceDecisions'\nimport type { MOSConfigInput } from './types'\n\nexport type MOSProxyHtmlPipelineStage =\n | 'origin-response'\n | 'link-rewriting'\n | 'surface-decisions'\n | 'surface-behavior'\n | 'surface-components'\n\nexport interface MOSProxyHtmlPipelineErrorContext {\n error: unknown\n stage: MOSProxyHtmlPipelineStage\n request: Request\n lastSafeResponse: Response\n}\n\n/**\n * Called when the HTML pipeline throws. Return a `Response` to fully control the proxy's reply, or\n * re-throw to surface the error to the platform handler. If omitted, the proxy fails open and\n * returns `lastSafeResponse`. If the callback itself throws or returns a non-Response value, the\n * proxy logs a warning and falls back to `lastSafeResponse` so the site cannot be taken down by a\n * bug in the handler.\n */\nexport type MOSProxyHtmlPipelineErrorHandler = (ctx: MOSProxyHtmlPipelineErrorContext) => Response | Promise<Response>\n\nexport interface MOSProxyOptions {\n config: MOSConfigInput\n originFetcher: Fetcher\n apiFetcher: Fetcher | null\n htmlRewriter: HtmlRewriterAdapter | null\n clientMetadataProvider: ClientMetadataProvider | null\n logger?: MOSProxyLogger\n onHtmlPipelineError?: MOSProxyHtmlPipelineErrorHandler\n customEndpointsEnabled: boolean\n linkRewritingEnabled: boolean\n surfaceDecisionsEnabled: boolean\n htmlTransformationEnabled: boolean\n}\n\n/**\n * Platform-agnostic MonetizationOS proxy. Build one with `MOSProxyBuilder`, then call\n * `proxy.handle(request)` from your platform's fetch entry point.\n */\nexport class MOSProxy {\n private readonly config: MOSConfig\n\n constructor(private readonly opts: MOSProxyOptions) {\n this.config = normalizeMOSConfig(opts.config, opts.logger ?? consoleLogger)\n }\n\n async handle(request: Request): Promise<Response> {\n const { originFetcher, apiFetcher, htmlRewriter, clientMetadataProvider, onHtmlPipelineError } = this.opts\n const logger = this.opts.logger ?? consoleLogger\n const ctx: PipelineContext = { config: this.config, logger }\n\n // Stage 1a: custom endpoint routing\n if (this.opts.customEndpointsEnabled) {\n if (!apiFetcher) {\n throw new Error('MOSProxy: customEndpoints is enabled but no API fetcher is configured')\n }\n const customEndpointResponse = await customEndpointRequest(ctx, request, apiFetcher)\n if (customEndpointResponse) {\n return customEndpointResponse\n }\n }\n\n // Stage 1b: origin fetch\n const originResponse = await performOriginRequest(ctx, request, originFetcher)\n\n // Auto-skip HTML pipeline for non-HTML content, or when HTML transformation is disabled entirely\n const isHtml = originResponse.headers.get('Content-Type')?.startsWith('text/html') ?? false\n if (!isHtml || !this.opts.htmlTransformationEnabled) {\n return originResponse\n }\n\n let stage: MOSProxyHtmlPipelineStage = 'origin-response'\n let failOpenResponse = cloneResponseForFallback(originResponse, logger, stage)\n\n try {\n // Stage 2: rewrite origin links (optional)\n let rewrittenResponse: Response = originResponse\n if (this.opts.linkRewritingEnabled) {\n stage = 'link-rewriting'\n rewrittenResponse = await rewriteOriginResponse(ctx, request, originResponse)\n failOpenResponse = cloneResponseForFallback(rewrittenResponse, logger, stage)\n }\n\n // Stage 3: surface decisions (optional)\n if (!this.opts.surfaceDecisionsEnabled) {\n return rewrittenResponse\n }\n if (shouldIgnorePath(ctx, request) || isRedirectResponse(rewrittenResponse)) {\n return rewrittenResponse\n }\n\n if (!apiFetcher) {\n throw new Error('MOSProxy: surfaceDecisions is enabled but no API fetcher is configured')\n }\n\n stage = 'surface-decisions'\n const [modifiedResponse, surfaceDecisions] = await getSurfaceDecisions(\n ctx,\n request,\n rewrittenResponse,\n apiFetcher,\n htmlRewriter,\n clientMetadataProvider,\n )\n if (!surfaceDecisions) {\n return modifiedResponse\n }\n failOpenResponse = cloneResponseForFallback(modifiedResponse, logger, stage)\n\n // Stage 4: surface behavior (HTTP-level)\n stage = 'surface-behavior'\n const [surfaceDecisionResponse, returnImmediately] = handleSurfaceBehavior(modifiedResponse, surfaceDecisions)\n if (returnImmediately) {\n return surfaceDecisionResponse\n }\n failOpenResponse = cloneResponseForFallback(surfaceDecisionResponse, logger, stage)\n\n // Stage 5: surface components (HTML-level) — requires an HTML rewriter\n if (!htmlRewriter) {\n return surfaceDecisionResponse\n }\n stage = 'surface-components'\n return await handleSurfaceComponents(ctx, surfaceDecisionResponse, surfaceDecisions, htmlRewriter)\n } catch (error) {\n logger.log({\n level: 'error',\n code: 'html-pipeline-failed',\n message: 'HTML pipeline failed.',\n context: { stage, hasErrorHandler: Boolean(onHtmlPipelineError) },\n error,\n })\n\n if (!onHtmlPipelineError) {\n return failOpenResponse\n }\n\n try {\n const handlerResponse = await onHtmlPipelineError({\n error,\n stage,\n request,\n lastSafeResponse: failOpenResponse,\n })\n if (!(handlerResponse instanceof Response)) {\n logger.log({\n level: 'warn',\n code: 'html-pipeline-error-handler-invalid',\n message: 'onHtmlPipelineError did not return a Response; falling back to the last safe response.',\n context: { stage },\n })\n return failOpenResponse\n }\n return handlerResponse\n } catch (handlerError) {\n logger.log({\n level: 'warn',\n code: 'html-pipeline-error-handler-threw',\n message: 'onHtmlPipelineError threw; falling back to the last safe response.',\n context: { stage },\n error: handlerError,\n })\n return failOpenResponse\n }\n }\n }\n}\n\nconst cloneResponseForFallback = (response: Response, logger: MOSProxyLogger, stage: MOSProxyHtmlPipelineStage): Response => {\n try {\n return response.clone()\n } catch (error) {\n logger.log({\n level: 'warn',\n code: 'response-clone-failed',\n message: 'Could not clone response for fail-open fallback.',\n context: { stage },\n error,\n })\n return response\n }\n}\n"]}
1
+ {"version":3,"file":"MOSProxy.js","sourceRoot":"","sources":["../src/MOSProxy.ts"],"names":[],"mappings":"AAIA,OAAO,EAAkB,kBAAkB,EAAE,MAAM,UAAU,CAAA;AAE7D,OAAO,EAAE,aAAa,EAAuB,MAAM,UAAU,CAAA;AAC7D,OAAO,qBAAqB,MAAM,yBAAyB,CAAA;AAC3D,OAAO,kBAAkB,MAAM,6BAA6B,CAAA;AAC5D,OAAO,qBAAqB,MAAM,wBAAwB,CAAA;AAC1D,OAAO,oBAAoB,MAAM,wBAAwB,CAAA;AACzD,OAAO,gBAAgB,MAAM,2BAA2B,CAAA;AACxD,OAAO,qBAAqB,MAAM,0BAA0B,CAAA;AAC5D,OAAO,uBAAuB,MAAM,4BAA4B,CAAA;AAChE,OAAO,mBAAmB,MAAM,2BAA2B,CAAA;AAyC3D;;;GAGG;AACH,MAAM,OAAO,QAAQ;IAGY;IAFZ,MAAM,CAAW;IAElC,YAA6B,IAAqB;QAArB,SAAI,GAAJ,IAAI,CAAiB;QAC9C,IAAI,CAAC,MAAM,GAAG,kBAAkB,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,aAAa,CAAC,CAAA;IAC/E,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,OAAgB;QACzB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AO,gBAAgB,CAAA;YAC3B,CAAC;QACL,CAAC;IACL,CAAC;CACJ;AAED,MAAM,wBAAwB,GAAG,CAAC,QAAkB,EAAE,MAAsB,EAAE,KAAgC,EAAY,EAAE;IACxH,IAAI,CAAC;QACD,OAAO,QAAQ,CAAC,KAAK,EAAE,CAAA;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,MAAM,CAAC,GAAG,CAAC;YACP,KAAK,EAAE,MAAM;YACb,IAAI,EAAE,uBAAuB;YAC7B,OAAO,EAAE,kDAAkD;YAC3D,OAAO,EAAE,EAAE,KAAK,EAAE;YAClB,KAAK;SACR,CAAC,CAAA;QACF,OAAO,QAAQ,CAAA;IACnB,CAAC;AACL,CAAC,CAAA","sourcesContent":["import type { ClientMetadataProvider } from './adapters/ClientMetadataProvider'\nimport type { Fetcher } from './adapters/Fetcher'\nimport type { HtmlRewriterAdapter } from './adapters/HtmlRewriterAdapter'\nimport type { IdentityProvider } from './adapters/IdentityProvider'\nimport { type MOSConfig, normalizeMOSConfig } from './config'\nimport type { PipelineContext } from './context'\nimport { consoleLogger, type MOSProxyLogger } from './logger'\nimport customEndpointRequest from './stages/customEndpoint'\nimport isRedirectResponse from './stages/isRedirectResponse'\nimport rewriteOriginResponse from './stages/linkRewriting'\nimport performOriginRequest from './stages/originRequest'\nimport shouldIgnorePath from './stages/shouldIgnorePath'\nimport handleSurfaceBehavior from './stages/surfaceBehavior'\nimport handleSurfaceComponents from './stages/surfaceComponents'\nimport getSurfaceDecisions from './stages/surfaceDecisions'\nimport type { MOSConfigInput } from './types'\n\nexport type MOSProxyHtmlPipelineStage =\n | 'origin-response'\n | 'link-rewriting'\n | 'surface-decisions'\n | 'surface-behavior'\n | 'surface-components'\n\nexport interface MOSProxyHtmlPipelineErrorContext {\n error: unknown\n stage: MOSProxyHtmlPipelineStage\n request: Request\n lastSafeResponse: Response\n}\n\n/**\n * Called when the HTML pipeline throws. Return a `Response` to fully control the proxy's reply, or\n * re-throw to surface the error to the platform handler. If omitted, the proxy fails open and\n * returns `lastSafeResponse`. If the callback itself throws or returns a non-Response value, the\n * proxy logs a warning and falls back to `lastSafeResponse` so the site cannot be taken down by a\n * bug in the handler.\n */\nexport type MOSProxyHtmlPipelineErrorHandler = (ctx: MOSProxyHtmlPipelineErrorContext) => Response | Promise<Response>\n\nexport interface MOSProxyOptions {\n config: MOSConfigInput\n originFetcher: Fetcher\n apiFetcher: Fetcher | null\n htmlRewriter: HtmlRewriterAdapter | null\n clientMetadataProvider: ClientMetadataProvider | null\n identityProvider: IdentityProvider | null\n logger?: MOSProxyLogger\n onHtmlPipelineError?: MOSProxyHtmlPipelineErrorHandler\n customEndpointsEnabled: boolean\n linkRewritingEnabled: boolean\n surfaceDecisionsEnabled: boolean\n htmlTransformationEnabled: boolean\n}\n\n/**\n * Platform-agnostic MonetizationOS proxy. Build one with `MOSProxyBuilder`, then call\n * `proxy.handle(request)` from your platform's fetch entry point.\n */\nexport class MOSProxy {\n private readonly config: MOSConfig\n\n constructor(private readonly opts: MOSProxyOptions) {\n this.config = normalizeMOSConfig(opts.config, opts.logger ?? consoleLogger)\n }\n\n async handle(request: Request): Promise<Response> {\n const { originFetcher, apiFetcher, htmlRewriter, clientMetadataProvider, identityProvider, onHtmlPipelineError } = this.opts\n const logger = this.opts.logger ?? consoleLogger\n const ctx: PipelineContext = { config: this.config, logger }\n\n // Stage 1a: custom endpoint routing\n if (this.opts.customEndpointsEnabled) {\n if (!apiFetcher) {\n throw new Error('MOSProxy: customEndpoints is enabled but no API fetcher is configured')\n }\n const customEndpointResponse = await customEndpointRequest(ctx, request, apiFetcher)\n if (customEndpointResponse) {\n return customEndpointResponse\n }\n }\n\n // Stage 1b: origin fetch\n const originResponse = await performOriginRequest(ctx, request, originFetcher)\n\n // Auto-skip HTML pipeline for non-HTML content, or when HTML transformation is disabled entirely\n const isHtml = originResponse.headers.get('Content-Type')?.startsWith('text/html') ?? false\n if (!isHtml || !this.opts.htmlTransformationEnabled) {\n return originResponse\n }\n\n let stage: MOSProxyHtmlPipelineStage = 'origin-response'\n let failOpenResponse = cloneResponseForFallback(originResponse, logger, stage)\n\n try {\n // Stage 2: rewrite origin links (optional)\n let rewrittenResponse: Response = originResponse\n if (this.opts.linkRewritingEnabled) {\n stage = 'link-rewriting'\n rewrittenResponse = await rewriteOriginResponse(ctx, request, originResponse)\n failOpenResponse = cloneResponseForFallback(rewrittenResponse, logger, stage)\n }\n\n // Stage 3: surface decisions (optional)\n if (!this.opts.surfaceDecisionsEnabled) {\n return rewrittenResponse\n }\n if (shouldIgnorePath(ctx, request) || isRedirectResponse(rewrittenResponse)) {\n return rewrittenResponse\n }\n\n if (!apiFetcher) {\n throw new Error('MOSProxy: surfaceDecisions is enabled but no API fetcher is configured')\n }\n\n stage = 'surface-decisions'\n const [modifiedResponse, surfaceDecisions] = await getSurfaceDecisions(\n ctx,\n request,\n rewrittenResponse,\n apiFetcher,\n htmlRewriter,\n clientMetadataProvider,\n identityProvider,\n )\n if (!surfaceDecisions) {\n return modifiedResponse\n }\n failOpenResponse = cloneResponseForFallback(modifiedResponse, logger, stage)\n\n // Stage 4: surface behavior (HTTP-level)\n stage = 'surface-behavior'\n const [surfaceDecisionResponse, returnImmediately] = handleSurfaceBehavior(modifiedResponse, surfaceDecisions)\n if (returnImmediately) {\n return surfaceDecisionResponse\n }\n failOpenResponse = cloneResponseForFallback(surfaceDecisionResponse, logger, stage)\n\n // Stage 5: surface components (HTML-level) — requires an HTML rewriter\n if (!htmlRewriter) {\n return surfaceDecisionResponse\n }\n stage = 'surface-components'\n return await handleSurfaceComponents(ctx, surfaceDecisionResponse, surfaceDecisions, htmlRewriter)\n } catch (error) {\n logger.log({\n level: 'error',\n code: 'html-pipeline-failed',\n message: 'HTML pipeline failed.',\n context: { stage, hasErrorHandler: Boolean(onHtmlPipelineError) },\n error,\n })\n\n if (!onHtmlPipelineError) {\n return failOpenResponse\n }\n\n try {\n const handlerResponse = await onHtmlPipelineError({\n error,\n stage,\n request,\n lastSafeResponse: failOpenResponse,\n })\n if (!(handlerResponse instanceof Response)) {\n logger.log({\n level: 'warn',\n code: 'html-pipeline-error-handler-invalid',\n message: 'onHtmlPipelineError did not return a Response; falling back to the last safe response.',\n context: { stage },\n })\n return failOpenResponse\n }\n return handlerResponse\n } catch (handlerError) {\n logger.log({\n level: 'warn',\n code: 'html-pipeline-error-handler-threw',\n message: 'onHtmlPipelineError threw; falling back to the last safe response.',\n context: { stage },\n error: handlerError,\n })\n return failOpenResponse\n }\n }\n }\n}\n\nconst cloneResponseForFallback = (response: Response, logger: MOSProxyLogger, stage: MOSProxyHtmlPipelineStage): Response => {\n try {\n return response.clone()\n } catch (error) {\n logger.log({\n level: 'warn',\n code: 'response-clone-failed',\n message: 'Could not clone response for fail-open fallback.',\n context: { stage },\n error,\n })\n return response\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import type { ClientMetadataProvider } from './adapters/ClientMetadataProvider';
2
2
  import type { Fetcher } from './adapters/Fetcher';
3
3
  import type { HtmlRewriterAdapter } from './adapters/HtmlRewriterAdapter';
4
+ import type { IdentityProvider } from './adapters/IdentityProvider';
4
5
  import type { MOSProxyLogger } from './logger';
5
6
  import { MOSProxy, type MOSProxyHtmlPipelineErrorHandler } from './MOSProxy';
6
7
  import type { MOSConfigInput } from './types';
@@ -28,6 +29,7 @@ import type { MOSConfigInput } from './types';
28
29
  * injectScriptUrl: 'https://assets.monetizationos.com/web-components-latest.js',
29
30
  * surfaceDecisionsIgnorePaths: '',
30
31
  * originRequestHeaders: { 'X-Api-Key': process.env.ORIGIN_API_KEY! },
32
+ * createAnonymousIdentifierFallback: true,
31
33
  * })
32
34
  * .withHtmlRewriter(myHtmlRewriterAdapter)
33
35
  * .build()
@@ -41,6 +43,7 @@ export declare class MOSProxyBuilder {
41
43
  private _apiFetcher;
42
44
  private _htmlRewriter;
43
45
  private _clientMetadataProvider;
46
+ private _identityProvider;
44
47
  private _logger;
45
48
  private _onHtmlPipelineError;
46
49
  private _customEndpoints;
@@ -52,6 +55,14 @@ export declare class MOSProxyBuilder {
52
55
  withApiFetcher(fetcher: Fetcher): this;
53
56
  withHtmlRewriter(rewriter: HtmlRewriterAdapter): this;
54
57
  withClientMetadata(provider: ClientMetadataProvider): this;
58
+ /**
59
+ * Override identity provision for the surface-decisions API. Provide `resolve` to control the
60
+ * identity payload sent to the API (e.g. resolved from a request header instead of cookies),
61
+ * and/or `persist` to control how identity is recorded back on the response (e.g. suppress the
62
+ * default anonymous-session cookie or write it elsewhere). Either method is optional; omitted
63
+ * methods fall back to the built-in defaults.
64
+ */
65
+ withIdentityProvider(provider: IdentityProvider): this;
55
66
  withLogger(logger: MOSProxyLogger): this;
56
67
  /**
57
68
  * Register a callback to handle HTML pipeline errors. The proxy fails open by default and
@@ -23,6 +23,7 @@ import { MOSProxy } from './MOSProxy';
23
23
  * injectScriptUrl: 'https://assets.monetizationos.com/web-components-latest.js',
24
24
  * surfaceDecisionsIgnorePaths: '',
25
25
  * originRequestHeaders: { 'X-Api-Key': process.env.ORIGIN_API_KEY! },
26
+ * createAnonymousIdentifierFallback: true,
26
27
  * })
27
28
  * .withHtmlRewriter(myHtmlRewriterAdapter)
28
29
  * .build()
@@ -36,6 +37,7 @@ export class MOSProxyBuilder {
36
37
  _apiFetcher = globalThis.fetch;
37
38
  _htmlRewriter = null;
38
39
  _clientMetadataProvider = null;
40
+ _identityProvider = null;
39
41
  _logger = null;
40
42
  _onHtmlPipelineError = null;
41
43
  _customEndpoints = true;
@@ -62,6 +64,17 @@ export class MOSProxyBuilder {
62
64
  this._clientMetadataProvider = provider;
63
65
  return this;
64
66
  }
67
+ /**
68
+ * Override identity provision for the surface-decisions API. Provide `resolve` to control the
69
+ * identity payload sent to the API (e.g. resolved from a request header instead of cookies),
70
+ * and/or `persist` to control how identity is recorded back on the response (e.g. suppress the
71
+ * default anonymous-session cookie or write it elsewhere). Either method is optional; omitted
72
+ * methods fall back to the built-in defaults.
73
+ */
74
+ withIdentityProvider(provider) {
75
+ this._identityProvider = provider;
76
+ return this;
77
+ }
65
78
  withLogger(logger) {
66
79
  this._logger = logger;
67
80
  return this;
@@ -113,6 +126,7 @@ export class MOSProxyBuilder {
113
126
  apiFetcher: this._apiFetcher,
114
127
  htmlRewriter: this._htmlRewriter,
115
128
  clientMetadataProvider: this._clientMetadataProvider,
129
+ identityProvider: this._identityProvider,
116
130
  logger: this._logger ?? undefined,
117
131
  onHtmlPipelineError: this._onHtmlPipelineError ?? undefined,
118
132
  customEndpointsEnabled: this._customEndpoints,
@@ -1 +1 @@
1
- {"version":3,"file":"MOSProxyBuilder.js","sourceRoot":"","sources":["../src/MOSProxyBuilder.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,QAAQ,EAA+D,MAAM,YAAY,CAAA;AAGlG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,OAAO,eAAe;IAChB,OAAO,GAA0B,IAAI,CAAA;IACrC,cAAc,GAAY,UAAU,CAAC,KAAK,CAAA;IAC1C,WAAW,GAAY,UAAU,CAAC,KAAK,CAAA;IACvC,aAAa,GAA+B,IAAI,CAAA;IAChD,uBAAuB,GAAkC,IAAI,CAAA;IAC7D,OAAO,GAA0B,IAAI,CAAA;IACrC,oBAAoB,GAA4C,IAAI,CAAA;IACpE,gBAAgB,GAAG,IAAI,CAAA;IACvB,cAAc,GAAG,IAAI,CAAA;IACrB,iBAAiB,GAAG,IAAI,CAAA;IACxB,mBAAmB,GAAG,IAAI,CAAA;IAElC,UAAU,CAAC,MAAsB;QAC7B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;QACrB,OAAO,IAAI,CAAA;IACf,CAAC;IAED,iBAAiB,CAAC,OAAgB;QAC9B,IAAI,CAAC,cAAc,GAAG,OAAO,CAAA;QAC7B,OAAO,IAAI,CAAA;IACf,CAAC;IAED,cAAc,CAAC,OAAgB;QAC3B,IAAI,CAAC,WAAW,GAAG,OAAO,CAAA;QAC1B,OAAO,IAAI,CAAA;IACf,C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AAE,IAAI,CAAC,cAAc;YAClC,UAAU,EAAE,IAAI,CAAC,WAAW;YAC5B,YAAY,EAAE,IAAI,CAAC,aAAa;YAChC,sBAAsB,EAAE,IAAI,CAAC,uBAAuB;YACpD,MAAM,EAAE,IAAI,CAAC,OAAO,IAAI,SAAS;YACjC,mBAAmB,EAAE,IAAI,CAAC,oBAAoB,IAAI,SAAS;YAC3D,sBAAsB,EAAE,IAAI,CAAC,gBAAgB;YAC7C,oBAAoB,EAAE,IAAI,CAAC,cAAc;YACzC,uBAAuB,EAAE,IAAI,CAAC,iBAAiB;YAC/C,yBAAyB,EAAE,IAAI,CAAC,mBAAmB;SACtD,CAAA;QACD,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAA;IAC7B,CAAC;CACJ","sourcesContent":["import type { ClientMetadataProvider } from './adapters/ClientMetadataProvider'\nimport type { Fetcher } from './adapters/Fetcher'\nimport type { HtmlRewriterAdapter } from './adapters/HtmlRewriterAdapter'\nimport type { MOSProxyLogger } from './logger'\nimport { MOSProxy, type MOSProxyHtmlPipelineErrorHandler, type MOSProxyOptions } from './MOSProxy'\nimport type { MOSConfigInput } from './types'\n\n/**\n * Fluent builder for `MOSProxy`. Provide configuration and platform adapters, then `build()`.\n *\n * Defaults:\n * - custom endpoint routing: enabled\n * - link rewriting: enabled\n * - surface decisions: enabled\n * - HTML transformation: enabled (auto-skipped per request for non-HTML responses)\n * - origin/API fetcher: `globalThis.fetch` (override on runtimes that need a backend binding, e.g. Fastly)\n *\n * @example\n * ```ts\n * const proxy = new MOSProxyBuilder()\n * .withConfig({\n * originUrl: 'https://news.example.com',\n * surfaceSlug: 'web',\n * mosHost: 'https://api.monetizationos.com',\n * mosSecretKey: process.env.MONETIZATION_OS_SECRET_KEY!,\n * mosEndpointsPrefix: '/mos-endpoints/',\n * anonymousSessionCookieName: 'anon-session-id',\n * authenticatedUserJwtCookieName: '__session',\n * injectScriptUrl: 'https://assets.monetizationos.com/web-components-latest.js',\n * surfaceDecisionsIgnorePaths: '',\n * originRequestHeaders: { 'X-Api-Key': process.env.ORIGIN_API_KEY! },\n * })\n * .withHtmlRewriter(myHtmlRewriterAdapter)\n * .build()\n *\n * export default { fetch: (request: Request) => proxy.handle(request) }\n * ```\n */\nexport class MOSProxyBuilder {\n private _config: MOSConfigInput | null = null\n private _originFetcher: Fetcher = globalThis.fetch\n private _apiFetcher: Fetcher = globalThis.fetch\n private _htmlRewriter: HtmlRewriterAdapter | null = null\n private _clientMetadataProvider: ClientMetadataProvider | null = null\n private _logger: MOSProxyLogger | null = null\n private _onHtmlPipelineError: MOSProxyHtmlPipelineErrorHandler | null = null\n private _customEndpoints = true\n private _linkRewriting = true\n private _surfaceDecisions = true\n private _htmlTransformation = true\n\n withConfig(config: MOSConfigInput): this {\n this._config = config\n return this\n }\n\n withOriginFetcher(fetcher: Fetcher): this {\n this._originFetcher = fetcher\n return this\n }\n\n withApiFetcher(fetcher: Fetcher): this {\n this._apiFetcher = fetcher\n return this\n }\n\n withHtmlRewriter(rewriter: HtmlRewriterAdapter): this {\n this._htmlRewriter = rewriter\n return this\n }\n\n withClientMetadata(provider: ClientMetadataProvider): this {\n this._clientMetadataProvider = provider\n return this\n }\n\n withLogger(logger: MOSProxyLogger): this {\n this._logger = logger\n return this\n }\n\n /**\n * Register a callback to handle HTML pipeline errors. The proxy fails open by default and\n * returns the last safe (unconsumed) response — provide this if you want to shape that\n * response yourself (e.g. render a custom error page, return a 503, or re-throw so your\n * platform's error middleware handles it). If the callback throws or returns a non-Response\n * value, the proxy logs a warning and falls back to the last safe response.\n */\n withHtmlPipelineErrorHandler(handler: MOSProxyHtmlPipelineErrorHandler): this {\n this._onHtmlPipelineError = handler\n return this\n }\n\n withoutCustomEndpoints(): this {\n this._customEndpoints = false\n return this\n }\n\n withoutLinkRewriting(): this {\n this._linkRewriting = false\n return this\n }\n\n withoutSurfaceDecisions(): this {\n this._surfaceDecisions = false\n return this\n }\n\n /**\n * Disable the HTML transformation pipeline entirely (stages 3–6).\n *\n * Use for API-only proxies: neither an HTML rewriter adapter nor an API fetcher is required\n * if custom endpoints and surface decisions are both disabled alongside this.\n */\n withoutHtmlTransformation(): this {\n this._htmlTransformation = false\n return this\n }\n\n build(): MOSProxy {\n if (!this._config) {\n throw new Error('MOSProxyBuilder: withConfig(...) is required')\n }\n\n const needsHtmlRewriter = this._htmlTransformation && this._surfaceDecisions\n if (needsHtmlRewriter && !this._htmlRewriter) {\n throw new Error(\n 'MOSProxyBuilder: withHtmlRewriter(...) is required when surface decisions is enabled; call withoutSurfaceDecisions() or withoutHtmlTransformation() if you do not need it',\n )\n }\n\n const opts: MOSProxyOptions = {\n config: this._config,\n originFetcher: this._originFetcher,\n apiFetcher: this._apiFetcher,\n htmlRewriter: this._htmlRewriter,\n clientMetadataProvider: this._clientMetadataProvider,\n logger: this._logger ?? undefined,\n onHtmlPipelineError: this._onHtmlPipelineError ?? undefined,\n customEndpointsEnabled: this._customEndpoints,\n linkRewritingEnabled: this._linkRewriting,\n surfaceDecisionsEnabled: this._surfaceDecisions,\n htmlTransformationEnabled: this._htmlTransformation,\n }\n return new MOSProxy(opts)\n }\n}\n"]}
1
+ {"version":3,"file":"MOSProxyBuilder.js","sourceRoot":"","sources":["../src/MOSProxyBuilder.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,QAAQ,EAA+D,MAAM,YAAY,CAAA;AAGlG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,OAAO,eAAe;IAChB,OAAO,GAA0B,IAAI,CAAA;IACrC,cAAc,GAAY,UAAU,CAAC,KAAK,CAAA;IAC1C,WAAW,GAAY,UAAU,CAAC,KAAK,CAAA;IACvC,aAAa,GAA+B,IAAI,CAAA;IAChD,uBAAuB,GAAkC,IAAI,CAAA;IAC7D,iBAAiB,GAA4B,IAAI,CAAA;IACjD,OAAO,GAA0B,IAAI,CAAA;IACrC,oBAAoB,GAA4C,IAAI,CAAA;IACpE,gBAAgB,GAAG,IAAI,CAAA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AAI,CAAA;IACf,CAAC;IAED;;;;;OAKG;IACH,yBAAyB;QACrB,IAAI,CAAC,mBAAmB,GAAG,KAAK,CAAA;QAChC,OAAO,IAAI,CAAA;IACf,CAAC;IAED,KAAK;QACD,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAA;QACnE,CAAC;QAED,MAAM,iBAAiB,GAAG,IAAI,CAAC,mBAAmB,IAAI,IAAI,CAAC,iBAAiB,CAAA;QAC5E,IAAI,iBAAiB,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YAC3C,MAAM,IAAI,KAAK,CACX,2KAA2K,CAC9K,CAAA;QACL,CAAC;QAED,MAAM,IAAI,GAAoB;YAC1B,MAAM,EAAE,IAAI,CAAC,OAAO;YACpB,aAAa,EAAE,IAAI,CAAC,cAAc;YAClC,UAAU,EAAE,IAAI,CAAC,WAAW;YAC5B,YAAY,EAAE,IAAI,CAAC,aAAa;YAChC,sBAAsB,EAAE,IAAI,CAAC,uBAAuB;YACpD,gBAAgB,EAAE,IAAI,CAAC,iBAAiB;YACxC,MAAM,EAAE,IAAI,CAAC,OAAO,IAAI,SAAS;YACjC,mBAAmB,EAAE,IAAI,CAAC,oBAAoB,IAAI,SAAS;YAC3D,sBAAsB,EAAE,IAAI,CAAC,gBAAgB;YAC7C,oBAAoB,EAAE,IAAI,CAAC,cAAc;YACzC,uBAAuB,EAAE,IAAI,CAAC,iBAAiB;YAC/C,yBAAyB,EAAE,IAAI,CAAC,mBAAmB;SACtD,CAAA;QACD,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAA;IAC7B,CAAC;CACJ","sourcesContent":["import type { ClientMetadataProvider } from './adapters/ClientMetadataProvider'\nimport type { Fetcher } from './adapters/Fetcher'\nimport type { HtmlRewriterAdapter } from './adapters/HtmlRewriterAdapter'\nimport type { IdentityProvider } from './adapters/IdentityProvider'\nimport type { MOSProxyLogger } from './logger'\nimport { MOSProxy, type MOSProxyHtmlPipelineErrorHandler, type MOSProxyOptions } from './MOSProxy'\nimport type { MOSConfigInput } from './types'\n\n/**\n * Fluent builder for `MOSProxy`. Provide configuration and platform adapters, then `build()`.\n *\n * Defaults:\n * - custom endpoint routing: enabled\n * - link rewriting: enabled\n * - surface decisions: enabled\n * - HTML transformation: enabled (auto-skipped per request for non-HTML responses)\n * - origin/API fetcher: `globalThis.fetch` (override on runtimes that need a backend binding, e.g. Fastly)\n *\n * @example\n * ```ts\n * const proxy = new MOSProxyBuilder()\n * .withConfig({\n * originUrl: 'https://news.example.com',\n * surfaceSlug: 'web',\n * mosHost: 'https://api.monetizationos.com',\n * mosSecretKey: process.env.MONETIZATION_OS_SECRET_KEY!,\n * mosEndpointsPrefix: '/mos-endpoints/',\n * anonymousSessionCookieName: 'anon-session-id',\n * authenticatedUserJwtCookieName: '__session',\n * injectScriptUrl: 'https://assets.monetizationos.com/web-components-latest.js',\n * surfaceDecisionsIgnorePaths: '',\n * originRequestHeaders: { 'X-Api-Key': process.env.ORIGIN_API_KEY! },\n * createAnonymousIdentifierFallback: true,\n * })\n * .withHtmlRewriter(myHtmlRewriterAdapter)\n * .build()\n *\n * export default { fetch: (request: Request) => proxy.handle(request) }\n * ```\n */\nexport class MOSProxyBuilder {\n private _config: MOSConfigInput | null = null\n private _originFetcher: Fetcher = globalThis.fetch\n private _apiFetcher: Fetcher = globalThis.fetch\n private _htmlRewriter: HtmlRewriterAdapter | null = null\n private _clientMetadataProvider: ClientMetadataProvider | null = null\n private _identityProvider: IdentityProvider | null = null\n private _logger: MOSProxyLogger | null = null\n private _onHtmlPipelineError: MOSProxyHtmlPipelineErrorHandler | null = null\n private _customEndpoints = true\n private _linkRewriting = true\n private _surfaceDecisions = true\n private _htmlTransformation = true\n\n withConfig(config: MOSConfigInput): this {\n this._config = config\n return this\n }\n\n withOriginFetcher(fetcher: Fetcher): this {\n this._originFetcher = fetcher\n return this\n }\n\n withApiFetcher(fetcher: Fetcher): this {\n this._apiFetcher = fetcher\n return this\n }\n\n withHtmlRewriter(rewriter: HtmlRewriterAdapter): this {\n this._htmlRewriter = rewriter\n return this\n }\n\n withClientMetadata(provider: ClientMetadataProvider): this {\n this._clientMetadataProvider = provider\n return this\n }\n\n /**\n * Override identity provision for the surface-decisions API. Provide `resolve` to control the\n * identity payload sent to the API (e.g. resolved from a request header instead of cookies),\n * and/or `persist` to control how identity is recorded back on the response (e.g. suppress the\n * default anonymous-session cookie or write it elsewhere). Either method is optional; omitted\n * methods fall back to the built-in defaults.\n */\n withIdentityProvider(provider: IdentityProvider): this {\n this._identityProvider = provider\n return this\n }\n\n withLogger(logger: MOSProxyLogger): this {\n this._logger = logger\n return this\n }\n\n /**\n * Register a callback to handle HTML pipeline errors. The proxy fails open by default and\n * returns the last safe (unconsumed) response — provide this if you want to shape that\n * response yourself (e.g. render a custom error page, return a 503, or re-throw so your\n * platform's error middleware handles it). If the callback throws or returns a non-Response\n * value, the proxy logs a warning and falls back to the last safe response.\n */\n withHtmlPipelineErrorHandler(handler: MOSProxyHtmlPipelineErrorHandler): this {\n this._onHtmlPipelineError = handler\n return this\n }\n\n withoutCustomEndpoints(): this {\n this._customEndpoints = false\n return this\n }\n\n withoutLinkRewriting(): this {\n this._linkRewriting = false\n return this\n }\n\n withoutSurfaceDecisions(): this {\n this._surfaceDecisions = false\n return this\n }\n\n /**\n * Disable the HTML transformation pipeline entirely (stages 3–6).\n *\n * Use for API-only proxies: neither an HTML rewriter adapter nor an API fetcher is required\n * if custom endpoints and surface decisions are both disabled alongside this.\n */\n withoutHtmlTransformation(): this {\n this._htmlTransformation = false\n return this\n }\n\n build(): MOSProxy {\n if (!this._config) {\n throw new Error('MOSProxyBuilder: withConfig(...) is required')\n }\n\n const needsHtmlRewriter = this._htmlTransformation && this._surfaceDecisions\n if (needsHtmlRewriter && !this._htmlRewriter) {\n throw new Error(\n 'MOSProxyBuilder: withHtmlRewriter(...) is required when surface decisions is enabled; call withoutSurfaceDecisions() or withoutHtmlTransformation() if you do not need it',\n )\n }\n\n const opts: MOSProxyOptions = {\n config: this._config,\n originFetcher: this._originFetcher,\n apiFetcher: this._apiFetcher,\n htmlRewriter: this._htmlRewriter,\n clientMetadataProvider: this._clientMetadataProvider,\n identityProvider: this._identityProvider,\n logger: this._logger ?? undefined,\n onHtmlPipelineError: this._onHtmlPipelineError ?? undefined,\n customEndpointsEnabled: this._customEndpoints,\n linkRewritingEnabled: this._linkRewriting,\n surfaceDecisionsEnabled: this._surfaceDecisions,\n htmlTransformationEnabled: this._htmlTransformation,\n }\n return new MOSProxy(opts)\n }\n}\n"]}
@@ -0,0 +1,44 @@
1
+ import type { MOSConfig } from '../config';
2
+ import type { MOSProxyLogger } from '../logger';
3
+ import type { SurfaceDecisionResponse } from '../types';
4
+ export type Identity = {
5
+ createAnonymousIdentifier: true;
6
+ } | {
7
+ userJwt: string;
8
+ createAnonymousIdentifierFallback?: true;
9
+ } | {
10
+ anonymousIdentifier: string;
11
+ };
12
+ export interface ResolveIdentityArgs {
13
+ request: Request;
14
+ originResponse: Response;
15
+ config: MOSConfig;
16
+ logger: MOSProxyLogger;
17
+ }
18
+ export interface PersistIdentityArgs {
19
+ resolved: Identity;
20
+ decisions: SurfaceDecisionResponse;
21
+ response: Response;
22
+ request: Request;
23
+ config: MOSConfig;
24
+ logger: MOSProxyLogger;
25
+ }
26
+ /**
27
+ * Either method is optional; omitted methods use the built-in defaults. Both fail open: a throwing
28
+ * `resolve` skips surface decisions; a throwing `persist` keeps the pre-persist response.
29
+ */
30
+ export interface IdentityProvider {
31
+ resolve?(args: ResolveIdentityArgs): Identity | Promise<Identity>;
32
+ persist?(args: PersistIdentityArgs): Response | Promise<Response>;
33
+ }
34
+ export declare const getExistingCookies: (request: Request, originResponse: Response, config: MOSConfig) => {
35
+ anonymousIdentifier?: string;
36
+ userJwt?: string;
37
+ };
38
+ export declare const buildIdentity: ({ anonymousIdentifier, userJwt, createAnonymousIdentifierFallback, }: {
39
+ anonymousIdentifier?: string;
40
+ userJwt?: string;
41
+ createAnonymousIdentifierFallback?: boolean;
42
+ }) => Identity;
43
+ export declare const defaultResolveIdentity: (args: ResolveIdentityArgs) => Identity;
44
+ export declare const defaultPersistIdentity: (args: PersistIdentityArgs) => Response;
@@ -0,0 +1,51 @@
1
+ import { parse, parseSetCookie } from 'cookie';
2
+ export const getExistingCookies = (request, originResponse, config) => {
3
+ const setCookies = originResponse.headers.getSetCookie().map((header) => parseSetCookie(header));
4
+ const originAnonymousCookie = setCookies.find((s) => s.name === config.anonymousSessionCookieName);
5
+ const originUserJwtCookie = setCookies.find((s) => s.name === config.authenticatedUserJwtCookieName);
6
+ if (originAnonymousCookie || originUserJwtCookie) {
7
+ return { anonymousIdentifier: originAnonymousCookie?.value, userJwt: originUserJwtCookie?.value };
8
+ }
9
+ const cookies = parse(request.headers.get('Cookie') || '');
10
+ const anonymousIdentifier = cookies[config.anonymousSessionCookieName];
11
+ const userJwt = cookies[config.authenticatedUserJwtCookieName];
12
+ return { anonymousIdentifier, userJwt };
13
+ };
14
+ export const buildIdentity = ({ anonymousIdentifier, userJwt, createAnonymousIdentifierFallback = false, }) => {
15
+ if (userJwt) {
16
+ return createAnonymousIdentifierFallback ? { userJwt, createAnonymousIdentifierFallback: true } : { userJwt };
17
+ }
18
+ if (anonymousIdentifier) {
19
+ return { anonymousIdentifier };
20
+ }
21
+ return { createAnonymousIdentifier: true };
22
+ };
23
+ export const defaultResolveIdentity = (args) => buildIdentity({
24
+ ...getExistingCookies(args.request, args.originResponse, args.config),
25
+ createAnonymousIdentifierFallback: args.config.createAnonymousIdentifierFallback,
26
+ });
27
+ export const defaultPersistIdentity = (args) => {
28
+ const { resolved, decisions, response, request, config } = args;
29
+ const identifier = decisions.identity?.identifier;
30
+ if (!identifier) {
31
+ return response;
32
+ }
33
+ const minted = 'createAnonymousIdentifier' in resolved && resolved.createAnonymousIdentifier === true;
34
+ // A JWT resolved with the fallback flag mints a fresh anonymous identifier only when the API reports the
35
+ // JWT as unauthenticated, and only when the request did not already carry an anonymous session cookie.
36
+ const jwtFallback = 'createAnonymousIdentifierFallback' in resolved &&
37
+ resolved.createAnonymousIdentifierFallback === true &&
38
+ !decisions.identity?.isAuthenticated &&
39
+ !getExistingCookies(request, response, config).anonymousIdentifier;
40
+ if (!minted && !jwtFallback) {
41
+ return response;
42
+ }
43
+ const headers = new Headers(response.headers);
44
+ headers.append('Set-Cookie', `${config.anonymousSessionCookieName}=${identifier}; Path=/`);
45
+ return new Response(response.body, {
46
+ status: response.status,
47
+ statusText: response.statusText,
48
+ headers,
49
+ });
50
+ };
51
+ //# sourceMappingURL=IdentityProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IdentityProvider.js","sourceRoot":"","sources":["../../src/adapters/IdentityProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAA;AAmC9C,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAC9B,OAAgB,EAChB,cAAwB,EACxB,MAAiB,EACiC,EAAE;IACpD,MAAM,UAAU,GAAG,cAAc,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAA;IAChG,MAAM,qBAAqB,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,0BAA0B,CAAC,CAAA;IAClG,MAAM,mBAAmB,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,8BAA8B,CAAC,CAAA;IACpG,IAAI,qBAAqB,IAAI,mBAAmB,EAAE,CAAC;QAC/C,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,KAAK,EAAE,OAAO,EAAE,mBAAmB,EAAE,KAAK,EAAE,CAAA;IAC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A;IACjD,IAAI,CAAC,UAAU,EAAE,CAAC;QACd,OAAO,QAAQ,CAAA;IACnB,CAAC;IAED,MAAM,MAAM,GAAG,2BAA2B,IAAI,QAAQ,IAAI,QAAQ,CAAC,yBAAyB,KAAK,IAAI,CAAA;IACrG,yGAAyG;IACzG,uGAAuG;IACvG,MAAM,WAAW,GACb,mCAAmC,IAAI,QAAQ;QAC/C,QAAQ,CAAC,iCAAiC,KAAK,IAAI;QACnD,CAAC,SAAS,CAAC,QAAQ,EAAE,eAAe;QACpC,CAAC,kBAAkB,CAAC,OAAO,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,mBAAmB,CAAA;IAEtE,IAAI,CAAC,MAAM,IAAI,CAAC,WAAW,EAAE,CAAC;QAC1B,OAAO,QAAQ,CAAA;IACnB,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAA;IAC7C,OAAO,CAAC,MAAM,CAAC,YAAY,EAAE,GAAG,MAAM,CAAC,0BAA0B,IAAI,UAAU,UAAU,CAAC,CAAA;IAC1F,OAAO,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE;QAC/B,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,UAAU,EAAE,QAAQ,CAAC,UAAU;QAC/B,OAAO;KACV,CAAC,CAAA;AACN,CAAC,CAAA","sourcesContent":["import { parse, parseSetCookie } from 'cookie'\nimport type { MOSConfig } from '../config'\nimport type { MOSProxyLogger } from '../logger'\nimport type { SurfaceDecisionResponse } from '../types'\n\nexport type Identity =\n | { createAnonymousIdentifier: true }\n | { userJwt: string; createAnonymousIdentifierFallback?: true }\n | { anonymousIdentifier: string }\n\nexport interface ResolveIdentityArgs {\n request: Request\n originResponse: Response\n config: MOSConfig\n logger: MOSProxyLogger\n}\n\nexport interface PersistIdentityArgs {\n resolved: Identity\n decisions: SurfaceDecisionResponse\n response: Response\n request: Request\n config: MOSConfig\n logger: MOSProxyLogger\n}\n\n/**\n * Either method is optional; omitted methods use the built-in defaults. Both fail open: a throwing\n * `resolve` skips surface decisions; a throwing `persist` keeps the pre-persist response.\n */\nexport interface IdentityProvider {\n resolve?(args: ResolveIdentityArgs): Identity | Promise<Identity>\n persist?(args: PersistIdentityArgs): Response | Promise<Response>\n}\n\nexport const getExistingCookies = (\n request: Request,\n originResponse: Response,\n config: MOSConfig,\n): { anonymousIdentifier?: string; userJwt?: string } => {\n const setCookies = originResponse.headers.getSetCookie().map((header) => parseSetCookie(header))\n const originAnonymousCookie = setCookies.find((s) => s.name === config.anonymousSessionCookieName)\n const originUserJwtCookie = setCookies.find((s) => s.name === config.authenticatedUserJwtCookieName)\n if (originAnonymousCookie || originUserJwtCookie) {\n return { anonymousIdentifier: originAnonymousCookie?.value, userJwt: originUserJwtCookie?.value }\n }\n\n const cookies = parse(request.headers.get('Cookie') || '')\n const anonymousIdentifier = cookies[config.anonymousSessionCookieName]\n const userJwt = cookies[config.authenticatedUserJwtCookieName]\n return { anonymousIdentifier, userJwt }\n}\n\nexport const buildIdentity = ({\n anonymousIdentifier,\n userJwt,\n createAnonymousIdentifierFallback = false,\n}: {\n anonymousIdentifier?: string\n userJwt?: string\n createAnonymousIdentifierFallback?: boolean\n}): Identity => {\n if (userJwt) {\n return createAnonymousIdentifierFallback ? { userJwt, createAnonymousIdentifierFallback: true } : { userJwt }\n }\n\n if (anonymousIdentifier) {\n return { anonymousIdentifier }\n }\n\n return { createAnonymousIdentifier: true }\n}\n\nexport const defaultResolveIdentity = (args: ResolveIdentityArgs): Identity =>\n buildIdentity({\n ...getExistingCookies(args.request, args.originResponse, args.config),\n createAnonymousIdentifierFallback: args.config.createAnonymousIdentifierFallback,\n })\n\nexport const defaultPersistIdentity = (args: PersistIdentityArgs): Response => {\n const { resolved, decisions, response, request, config } = args\n const identifier = decisions.identity?.identifier\n if (!identifier) {\n return response\n }\n\n const minted = 'createAnonymousIdentifier' in resolved && resolved.createAnonymousIdentifier === true\n // A JWT resolved with the fallback flag mints a fresh anonymous identifier only when the API reports the\n // JWT as unauthenticated, and only when the request did not already carry an anonymous session cookie.\n const jwtFallback =\n 'createAnonymousIdentifierFallback' in resolved &&\n resolved.createAnonymousIdentifierFallback === true &&\n !decisions.identity?.isAuthenticated &&\n !getExistingCookies(request, response, config).anonymousIdentifier\n\n if (!minted && !jwtFallback) {\n return response\n }\n\n const headers = new Headers(response.headers)\n headers.append('Set-Cookie', `${config.anonymousSessionCookieName}=${identifier}; Path=/`)\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n}\n"]}
@@ -1,3 +1,5 @@
1
1
  export type { ClientMetadataProvider } from './ClientMetadataProvider';
2
2
  export type { Fetcher } from './Fetcher';
3
3
  export type { ContentOptions, ElementHandlers, HtmlRewriterAdapter, HtmlRewriterCapabilities, HtmlRewriterSession, RewriterElement, RewriterText, } from './HtmlRewriterAdapter';
4
+ export type { Identity, IdentityProvider, PersistIdentityArgs, ResolveIdentityArgs } from './IdentityProvider';
5
+ export { buildIdentity, defaultPersistIdentity, defaultResolveIdentity, getExistingCookies, } from './IdentityProvider';
@@ -1,2 +1,2 @@
1
- export {};
1
+ export { buildIdentity, defaultPersistIdentity, defaultResolveIdentity, getExistingCookies, } from './IdentityProvider';
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/adapters/index.ts"],"names":[],"mappings":"","sourcesContent":["export type { ClientMetadataProvider } from './ClientMetadataProvider'\nexport type { Fetcher } from './Fetcher'\nexport type {\n ContentOptions,\n ElementHandlers,\n HtmlRewriterAdapter,\n HtmlRewriterCapabilities,\n HtmlRewriterSession,\n RewriterElement,\n RewriterText,\n} from './HtmlRewriterAdapter'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/adapters/index.ts"],"names":[],"mappings":"AAYA,OAAO,EACH,aAAa,EACb,sBAAsB,EACtB,sBAAsB,EACtB,kBAAkB,GACrB,MAAM,oBAAoB,CAAA","sourcesContent":["export type { ClientMetadataProvider } from './ClientMetadataProvider'\nexport type { Fetcher } from './Fetcher'\nexport type {\n ContentOptions,\n ElementHandlers,\n HtmlRewriterAdapter,\n HtmlRewriterCapabilities,\n HtmlRewriterSession,\n RewriterElement,\n RewriterText,\n} from './HtmlRewriterAdapter'\nexport type { Identity, IdentityProvider, PersistIdentityArgs, ResolveIdentityArgs } from './IdentityProvider'\nexport {\n buildIdentity,\n defaultPersistIdentity,\n defaultResolveIdentity,\n getExistingCookies,\n} from './IdentityProvider'\n"]}
@@ -1,5 +1,5 @@
1
1
  export declare const MOS_PROXY_VERSION_HEADER = "X-MOS-Proxy-Version";
2
2
  export declare const MOS_PROXY_CLIENT_HEADER = "X-MOS-Proxy-Client";
3
- export declare const MOS_PROXY_PACKAGE_VERSION = "1.0.3";
3
+ export declare const MOS_PROXY_PACKAGE_VERSION = "1.2.0";
4
4
  export declare const setMosProxyHeaders: (headers: Headers) => void;
5
5
  export declare const withMosProxyHeaders: (headers?: HeadersInit) => Headers;
@@ -1,7 +1,7 @@
1
1
  import { formatClientRuntimeHeader } from './clientRuntime';
2
2
  export const MOS_PROXY_VERSION_HEADER = 'X-MOS-Proxy-Version';
3
3
  export const MOS_PROXY_CLIENT_HEADER = 'X-MOS-Proxy-Client';
4
- export const MOS_PROXY_PACKAGE_VERSION = '1.0.3';
4
+ export const MOS_PROXY_PACKAGE_VERSION = '1.2.0';
5
5
  export const setMosProxyHeaders = (headers) => {
6
6
  headers.set(MOS_PROXY_VERSION_HEADER, MOS_PROXY_PACKAGE_VERSION);
7
7
  headers.set(MOS_PROXY_CLIENT_HEADER, formatClientRuntimeHeader());
@@ -1 +1 @@
1
- {"version":3,"file":"apiRequestHeaders.js","sourceRoot":"","sources":["../src/apiRequestHeaders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAA;AAE3D,MAAM,CAAC,MAAM,wBAAwB,GAAG,qBAAqB,CAAA;AAC7D,MAAM,CAAC,MAAM,uBAAuB,GAAG,oBAAoB,CAAA;AAC3D,MAAM,CAAC,MAAM,yBAAyB,GAAG,OAAO,CAAA;AAEhD,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,OAAgB,EAAQ,EAAE;IACzD,OAAO,CAAC,GAAG,CAAC,wBAAwB,EAAE,yBAAyB,CAAC,CAAA;IAChE,OAAO,CAAC,GAAG,CAAC,uBAAuB,EAAE,yBAAyB,EAAE,CAAC,CAAA;AACrE,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,OAAqB,EAAW,EAAE;IAClE,MAAM,IAAI,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,CAAA;IACjC,kBAAkB,CAAC,IAAI,CAAC,CAAA;IACxB,OAAO,IAAI,CAAA;AACf,CAAC,CAAA","sourcesContent":["import { formatClientRuntimeHeader } from './clientRuntime'\n\nexport const MOS_PROXY_VERSION_HEADER = 'X-MOS-Proxy-Version'\nexport const MOS_PROXY_CLIENT_HEADER = 'X-MOS-Proxy-Client'\nexport const MOS_PROXY_PACKAGE_VERSION = '1.0.3'\n\nexport const setMosProxyHeaders = (headers: Headers): void => {\n headers.set(MOS_PROXY_VERSION_HEADER, MOS_PROXY_PACKAGE_VERSION)\n headers.set(MOS_PROXY_CLIENT_HEADER, formatClientRuntimeHeader())\n}\n\nexport const withMosProxyHeaders = (headers?: HeadersInit): Headers => {\n const next = new Headers(headers)\n setMosProxyHeaders(next)\n return next\n}\n"]}
1
+ {"version":3,"file":"apiRequestHeaders.js","sourceRoot":"","sources":["../src/apiRequestHeaders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAA;AAE3D,MAAM,CAAC,MAAM,wBAAwB,GAAG,qBAAqB,CAAA;AAC7D,MAAM,CAAC,MAAM,uBAAuB,GAAG,oBAAoB,CAAA;AAC3D,MAAM,CAAC,MAAM,yBAAyB,GAAG,OAAO,CAAA;AAEhD,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,OAAgB,EAAQ,EAAE;IACzD,OAAO,CAAC,GAAG,CAAC,wBAAwB,EAAE,yBAAyB,CAAC,CAAA;IAChE,OAAO,CAAC,GAAG,CAAC,uBAAuB,EAAE,yBAAyB,EAAE,CAAC,CAAA;AACrE,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,OAAqB,EAAW,EAAE;IAClE,MAAM,IAAI,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,CAAA;IACjC,kBAAkB,CAAC,IAAI,CAAC,CAAA;IACxB,OAAO,IAAI,CAAA;AACf,CAAC,CAAA","sourcesContent":["import { formatClientRuntimeHeader } from './clientRuntime'\n\nexport const MOS_PROXY_VERSION_HEADER = 'X-MOS-Proxy-Version'\nexport const MOS_PROXY_CLIENT_HEADER = 'X-MOS-Proxy-Client'\nexport const MOS_PROXY_PACKAGE_VERSION = '1.2.0'\n\nexport const setMosProxyHeaders = (headers: Headers): void => {\n headers.set(MOS_PROXY_VERSION_HEADER, MOS_PROXY_PACKAGE_VERSION)\n headers.set(MOS_PROXY_CLIENT_HEADER, formatClientRuntimeHeader())\n}\n\nexport const withMosProxyHeaders = (headers?: HeadersInit): Headers => {\n const next = new Headers(headers)\n setMosProxyHeaders(next)\n return next\n}\n"]}
package/dist/config.d.ts CHANGED
@@ -12,5 +12,6 @@ export interface MOSConfig {
12
12
  injectScriptUrl: string | undefined;
13
13
  surfaceDecisionsIgnorePathPatterns: RegExp[];
14
14
  originRequestHeaders: Record<string, string>;
15
+ createAnonymousIdentifierFallback: boolean;
15
16
  }
16
17
  export declare function normalizeMOSConfig(config: MOSConfigInput, logger?: MOSProxyLogger): MOSConfig;
package/dist/config.js CHANGED
@@ -34,6 +34,7 @@ export function normalizeMOSConfig(config, logger = consoleLogger) {
34
34
  injectScriptUrl: config.injectScriptUrl,
35
35
  surfaceDecisionsIgnorePathPatterns: ignorePathPatterns,
36
36
  originRequestHeaders: { ...(config.originRequestHeaders ?? {}) },
37
+ createAnonymousIdentifierFallback: config.createAnonymousIdentifierFallback !== false,
37
38
  };
38
39
  }
39
40
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAuB,MAAM,UAAU,CAAA;AAG7D,MAAM,wBAAwB,GAAG,iBAAiB,CAAA;AAgBlD,MAAM,UAAU,kBAAkB,CAAC,MAAsB,EAAE,SAAyB,aAAa;IAC7F,MAAM,kBAAkB,GAAa,EAAE,CAAA;IACvC,IAAI,MAAM,CAAC,2BAA2B,EAAE,CAAC;QACrC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,2BAA2B,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;YAC9D,MAAM,OAAO,GAAG,GAAG,CAAC,IAAI,EAAE,CAAA;YAC1B,IAAI,CAAC,OAAO;gBAAE,SAAQ;YACtB,IAAI,CAAC;gBACD,kBAAkB,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC,CAAA;YAChD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,MAAM,CAAC,GAAG,CAAC;oBACP,KAAK,EAAE,MAAM;oBACb,IAAI,EAAE,6BAA6B;oBACnC,OAAO,EAAE,sDAAsD,OAAO,EAAE;oBACxE,OAAO,EAAE,EAAE,OAAO,EAAE;oBACpB,KAAK;iBACR,CAAC,CAAA;YACN,CAAC;QACL,CAAC;IACL,CAAC;IAED,MAAM,cAAc,GAAG,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAErD,OAAO;QACH,SAAS,EAAE,IAAI,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC;QACpC,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,OAAO,EAAE,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC;QAChC,YAAY,EAAE,MAAM,CAAC,YAAY;QACjC,cAAc,EAAE,GAAG,cAAc,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,cAAc,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE;QACvE,kBAAkB,EAAE,MAAM,CAAC,kBAAkB,IAAI,wBAAwB;QACzE,0BAA0B,EAAE,MAAM,CAAC,0BAA0B;QAC7D,8BAA8B,EAAE,MAAM,CAAC,8BAA8B;QACrE,eAAe,EAAE,MAAM,CAAC,eAAe;QACvC,kCAAkC,EAAE,kBAAkB;QACtD,oBAAoB,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,oBAAoB,IAAI,EAAE,CAAC,EAAE;KACnE,CAAA;AACL,CAAC","sourcesContent":["import { consoleLogger, type MOSProxyLogger } from './logger'\nimport type { MOSConfigInput } from './types'\n\nconst DEFAULT_ENDPOINTS_PREFIX = '/mos-endpoints/'\n\nexport interface MOSConfig {\n originUrl: URL\n surfaceSlug: string\n mosHost: URL\n mosSecretKey: string\n mosEnvironment: string\n mosEndpointsPrefix: string\n anonymousSessionCookieName: string\n authenticatedUserJwtCookieName: string\n injectScriptUrl: string | undefined\n surfaceDecisionsIgnorePathPatterns: RegExp[]\n originRequestHeaders: Record<string, string>\n}\n\nexport function normalizeMOSConfig(config: MOSConfigInput, logger: MOSProxyLogger = consoleLogger): MOSConfig {\n const ignorePathPatterns: RegExp[] = []\n if (config.surfaceDecisionsIgnorePaths) {\n for (const raw of config.surfaceDecisionsIgnorePaths.split(',')) {\n const pattern = raw.trim()\n if (!pattern) continue\n try {\n ignorePathPatterns.push(new RegExp(pattern))\n } catch (error) {\n logger.log({\n level: 'warn',\n code: 'invalid-ignore-path-pattern',\n message: `Invalid surfaceDecisionsIgnorePaths regex pattern: ${pattern}`,\n context: { pattern },\n error,\n })\n }\n }\n }\n\n const secretKeyParts = config.mosSecretKey.split('_')\n\n return {\n originUrl: new URL(config.originUrl),\n surfaceSlug: config.surfaceSlug,\n mosHost: new URL(config.mosHost),\n mosSecretKey: config.mosSecretKey,\n mosEnvironment: `${secretKeyParts[1] ?? ''}_${secretKeyParts[2] ?? ''}`,\n mosEndpointsPrefix: config.mosEndpointsPrefix || DEFAULT_ENDPOINTS_PREFIX,\n anonymousSessionCookieName: config.anonymousSessionCookieName,\n authenticatedUserJwtCookieName: config.authenticatedUserJwtCookieName,\n injectScriptUrl: config.injectScriptUrl,\n surfaceDecisionsIgnorePathPatterns: ignorePathPatterns,\n originRequestHeaders: { ...(config.originRequestHeaders ?? {}) },\n }\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAuB,MAAM,UAAU,CAAA;AAG7D,MAAM,wBAAwB,GAAG,iBAAiB,CAAA;AAiBlD,MAAM,UAAU,kBAAkB,CAAC,MAAsB,EAAE,SAAyB,aAAa;IAC7F,MAAM,kBAAkB,GAAa,EAAE,CAAA;IACvC,IAAI,MAAM,CAAC,2BAA2B,EAAE,CAAC;QACrC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,2BAA2B,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;YAC9D,MAAM,OAAO,GAAG,GAAG,CAAC,IAAI,EAAE,CAAA;YAC1B,IAAI,CAAC,OAAO;gBAAE,SAAQ;YACtB,IAAI,CAAC;gBACD,kBAAkB,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC,CAAA;YAChD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,MAAM,CAAC,GAAG,CAAC;oBACP,KAAK,EAAE,MAAM;oBACb,IAAI,EAAE,6BAA6B;oBACnC,OAAO,EAAE,sDAAsD,OAAO,EAAE;oBACxE,OAAO,EAAE,EAAE,OAAO,EAAE;oBACpB,KAAK;iBACR,CAAC,CAAA;YACN,CAAC;QACL,CAAC;IACL,CAAC;IAED,MAAM,cAAc,GAAG,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAErD,OAAO;QACH,SAAS,EAAE,IAAI,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC;QACpC,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,OAAO,EAAE,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC;QAChC,YAAY,EAAE,MAAM,CAAC,YAAY;QACjC,cAAc,EAAE,GAAG,cAAc,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,cAAc,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE;QACvE,kBAAkB,EAAE,MAAM,CAAC,kBAAkB,IAAI,wBAAwB;QACzE,0BAA0B,EAAE,MAAM,CAAC,0BAA0B;QAC7D,8BAA8B,EAAE,MAAM,CAAC,8BAA8B;QACrE,eAAe,EAAE,MAAM,CAAC,eAAe;QACvC,kCAAkC,EAAE,kBAAkB;QACtD,oBAAoB,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,oBAAoB,IAAI,EAAE,CAAC,EAAE;QAChE,iCAAiC,EAAE,MAAM,CAAC,iCAAiC,KAAK,KAAK;KACxF,CAAA;AACL,CAAC","sourcesContent":["import { consoleLogger, type MOSProxyLogger } from './logger'\nimport type { MOSConfigInput } from './types'\n\nconst DEFAULT_ENDPOINTS_PREFIX = '/mos-endpoints/'\n\nexport interface MOSConfig {\n originUrl: URL\n surfaceSlug: string\n mosHost: URL\n mosSecretKey: string\n mosEnvironment: string\n mosEndpointsPrefix: string\n anonymousSessionCookieName: string\n authenticatedUserJwtCookieName: string\n injectScriptUrl: string | undefined\n surfaceDecisionsIgnorePathPatterns: RegExp[]\n originRequestHeaders: Record<string, string>\n createAnonymousIdentifierFallback: boolean\n}\n\nexport function normalizeMOSConfig(config: MOSConfigInput, logger: MOSProxyLogger = consoleLogger): MOSConfig {\n const ignorePathPatterns: RegExp[] = []\n if (config.surfaceDecisionsIgnorePaths) {\n for (const raw of config.surfaceDecisionsIgnorePaths.split(',')) {\n const pattern = raw.trim()\n if (!pattern) continue\n try {\n ignorePathPatterns.push(new RegExp(pattern))\n } catch (error) {\n logger.log({\n level: 'warn',\n code: 'invalid-ignore-path-pattern',\n message: `Invalid surfaceDecisionsIgnorePaths regex pattern: ${pattern}`,\n context: { pattern },\n error,\n })\n }\n }\n }\n\n const secretKeyParts = config.mosSecretKey.split('_')\n\n return {\n originUrl: new URL(config.originUrl),\n surfaceSlug: config.surfaceSlug,\n mosHost: new URL(config.mosHost),\n mosSecretKey: config.mosSecretKey,\n mosEnvironment: `${secretKeyParts[1] ?? ''}_${secretKeyParts[2] ?? ''}`,\n mosEndpointsPrefix: config.mosEndpointsPrefix || DEFAULT_ENDPOINTS_PREFIX,\n anonymousSessionCookieName: config.anonymousSessionCookieName,\n authenticatedUserJwtCookieName: config.authenticatedUserJwtCookieName,\n injectScriptUrl: config.injectScriptUrl,\n surfaceDecisionsIgnorePathPatterns: ignorePathPatterns,\n originRequestHeaders: { ...(config.originRequestHeaders ?? {}) },\n createAnonymousIdentifierFallback: config.createAnonymousIdentifierFallback !== false,\n }\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
- export type { ClientMetadataProvider, ContentOptions, ElementHandlers, Fetcher, HtmlRewriterAdapter, HtmlRewriterCapabilities, HtmlRewriterSession, RewriterElement, RewriterText, } from './adapters';
1
+ export type { ClientMetadataProvider, ContentOptions, ElementHandlers, Fetcher, HtmlRewriterAdapter, HtmlRewriterCapabilities, HtmlRewriterSession, Identity, IdentityProvider, PersistIdentityArgs, ResolveIdentityArgs, RewriterElement, RewriterText, } from './adapters';
2
+ export { buildIdentity, defaultPersistIdentity, defaultResolveIdentity, getExistingCookies, } from './adapters';
3
+ export type { MOSConfig } from './config';
2
4
  export type { MOSProxyLogCode, MOSProxyLogEvent, MOSProxyLogger, MOSProxyLogLevel } from './logger';
3
5
  export { MOSProxy, type MOSProxyHtmlPipelineErrorContext, type MOSProxyHtmlPipelineErrorHandler, type MOSProxyHtmlPipelineStage, type MOSProxyOptions, } from './MOSProxy';
4
6
  export { MOSProxyBuilder } from './MOSProxyBuilder';
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export { buildIdentity, defaultPersistIdentity, defaultResolveIdentity, getExistingCookies, } from './adapters';
1
2
  export { MOSProxy, } from './MOSProxy';
2
3
  export { MOSProxyBuilder } from './MOSProxyBuilder';
3
4
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAYA,OAAO,EACH,QAAQ,GAKX,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA","sourcesContent":["export type {\n ClientMetadataProvider,\n ContentOptions,\n ElementHandlers,\n Fetcher,\n HtmlRewriterAdapter,\n HtmlRewriterCapabilities,\n HtmlRewriterSession,\n RewriterElement,\n RewriterText,\n} from './adapters'\nexport type { MOSProxyLogCode, MOSProxyLogEvent, MOSProxyLogger, MOSProxyLogLevel } from './logger'\nexport {\n MOSProxy,\n type MOSProxyHtmlPipelineErrorContext,\n type MOSProxyHtmlPipelineErrorHandler,\n type MOSProxyHtmlPipelineStage,\n type MOSProxyOptions,\n} from './MOSProxy'\nexport { MOSProxyBuilder } from './MOSProxyBuilder'\nexport type {\n Feature,\n FeatureMeterableProperty,\n FeatureNumberProperty,\n MOSConfigInput,\n ModifyHttpResponse,\n PageMetadata,\n SetHttpResponse,\n SubSurfaceBehaviorApi,\n SubSurfaceMetadataApi,\n SurfaceBehaviorApi,\n SurfaceDecisionError,\n SurfaceDecisionResponse,\n WebComponentElement,\n WebComponentRangeReplacement,\n WebContentSurfaceBehavior,\n WebElement,\n} from './types'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAeA,OAAO,EACH,aAAa,EACb,sBAAsB,EACtB,sBAAsB,EACtB,kBAAkB,GACrB,MAAM,YAAY,CAAA;AAGnB,OAAO,EACH,QAAQ,GAKX,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA","sourcesContent":["export type {\n ClientMetadataProvider,\n ContentOptions,\n ElementHandlers,\n Fetcher,\n HtmlRewriterAdapter,\n HtmlRewriterCapabilities,\n HtmlRewriterSession,\n Identity,\n IdentityProvider,\n PersistIdentityArgs,\n ResolveIdentityArgs,\n RewriterElement,\n RewriterText,\n} from './adapters'\nexport {\n buildIdentity,\n defaultPersistIdentity,\n defaultResolveIdentity,\n getExistingCookies,\n} from './adapters'\nexport type { MOSConfig } from './config'\nexport type { MOSProxyLogCode, MOSProxyLogEvent, MOSProxyLogger, MOSProxyLogLevel } from './logger'\nexport {\n MOSProxy,\n type MOSProxyHtmlPipelineErrorContext,\n type MOSProxyHtmlPipelineErrorHandler,\n type MOSProxyHtmlPipelineStage,\n type MOSProxyOptions,\n} from './MOSProxy'\nexport { MOSProxyBuilder } from './MOSProxyBuilder'\nexport type {\n Feature,\n FeatureMeterableProperty,\n FeatureNumberProperty,\n MOSConfigInput,\n ModifyHttpResponse,\n PageMetadata,\n SetHttpResponse,\n SubSurfaceBehaviorApi,\n SubSurfaceMetadataApi,\n SurfaceBehaviorApi,\n SurfaceDecisionError,\n SurfaceDecisionResponse,\n WebComponentElement,\n WebComponentRangeReplacement,\n WebContentSurfaceBehavior,\n WebElement,\n} from './types'\n"]}
package/dist/logger.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export type MOSProxyLogLevel = 'warn' | 'error';
2
- export type MOSProxyLogCode = 'html-pipeline-failed' | 'html-pipeline-error-handler-invalid' | 'html-pipeline-error-handler-threw' | 'invalid-ignore-path-pattern' | 'response-clone-failed' | 'surface-decisions-api-failed' | 'link-rewriting-header-failed' | 'link-rewriting-body-failed' | 'marker-pass-invalid-state' | 'marker-pass-selector-failed' | 'replacement-markers-identical' | 'replacement-state-missing' | 'element-render-failed' | 'element-type-unsupported' | 'page-metadata-parse-failed' | 'component-selector-unsupported' | 'component-range-replacement-skipped' | 'component-transform-failed';
2
+ export type MOSProxyLogCode = 'html-pipeline-failed' | 'html-pipeline-error-handler-invalid' | 'html-pipeline-error-handler-threw' | 'invalid-ignore-path-pattern' | 'response-clone-failed' | 'surface-decisions-api-failed' | 'identity-resolve-failed' | 'identity-persist-failed' | 'link-rewriting-header-failed' | 'link-rewriting-body-failed' | 'marker-pass-invalid-state' | 'marker-pass-selector-failed' | 'replacement-markers-identical' | 'replacement-state-missing' | 'element-render-failed' | 'element-type-unsupported' | 'page-metadata-parse-failed' | 'component-selector-unsupported' | 'component-range-replacement-skipped' | 'component-transform-failed';
3
3
  export interface MOSProxyLogEvent {
4
4
  level: MOSProxyLogLevel;
5
5
  code: MOSProxyLogCode;
@@ -1 +1 @@
1
- {"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAkCA,MAAM,CAAC,MAAM,aAAa,GAAmB;IACzC,GAAG,CAAC,KAAK;QACL,MAAM,OAAO,GAAc,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;QAClF,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YACd,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QAC7B,CAAC;QAED,IAAI,KAAK,CAAC,KAAK,KAAK,OAAO,EAAE,CAAC;YAC1B,OAAO,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,CAAA;YACzB,OAAM;QACV,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAA;IAC5B,CAAC;CACJ,CAAA","sourcesContent":["export type MOSProxyLogLevel = 'warn' | 'error'\n\nexport type MOSProxyLogCode =\n | 'html-pipeline-failed'\n | 'html-pipeline-error-handler-invalid'\n | 'html-pipeline-error-handler-threw'\n | 'invalid-ignore-path-pattern'\n | 'response-clone-failed'\n | 'surface-decisions-api-failed'\n | 'link-rewriting-header-failed'\n | 'link-rewriting-body-failed'\n | 'marker-pass-invalid-state'\n | 'marker-pass-selector-failed'\n | 'replacement-markers-identical'\n | 'replacement-state-missing'\n | 'element-render-failed'\n | 'element-type-unsupported'\n | 'page-metadata-parse-failed'\n | 'component-selector-unsupported'\n | 'component-range-replacement-skipped'\n | 'component-transform-failed'\n\nexport interface MOSProxyLogEvent {\n level: MOSProxyLogLevel\n code: MOSProxyLogCode\n message: string\n context?: Record<string, unknown>\n error?: unknown\n}\n\nexport interface MOSProxyLogger {\n log(event: MOSProxyLogEvent): void\n}\n\nexport const consoleLogger: MOSProxyLogger = {\n log(event) {\n const details: unknown[] = [event.message, { code: event.code, ...event.context }]\n if (event.error) {\n details.push(event.error)\n }\n\n if (event.level === 'error') {\n console.error(...details)\n return\n }\n\n console.warn(...details)\n },\n}\n"]}
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAoCA,MAAM,CAAC,MAAM,aAAa,GAAmB;IACzC,GAAG,CAAC,KAAK;QACL,MAAM,OAAO,GAAc,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;QAClF,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YACd,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QAC7B,CAAC;QAED,IAAI,KAAK,CAAC,KAAK,KAAK,OAAO,EAAE,CAAC;YAC1B,OAAO,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,CAAA;YACzB,OAAM;QACV,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAA;IAC5B,CAAC;CACJ,CAAA","sourcesContent":["export type MOSProxyLogLevel = 'warn' | 'error'\n\nexport type MOSProxyLogCode =\n | 'html-pipeline-failed'\n | 'html-pipeline-error-handler-invalid'\n | 'html-pipeline-error-handler-threw'\n | 'invalid-ignore-path-pattern'\n | 'response-clone-failed'\n | 'surface-decisions-api-failed'\n | 'identity-resolve-failed'\n | 'identity-persist-failed'\n | 'link-rewriting-header-failed'\n | 'link-rewriting-body-failed'\n | 'marker-pass-invalid-state'\n | 'marker-pass-selector-failed'\n | 'replacement-markers-identical'\n | 'replacement-state-missing'\n | 'element-render-failed'\n | 'element-type-unsupported'\n | 'page-metadata-parse-failed'\n | 'component-selector-unsupported'\n | 'component-range-replacement-skipped'\n | 'component-transform-failed'\n\nexport interface MOSProxyLogEvent {\n level: MOSProxyLogLevel\n code: MOSProxyLogCode\n message: string\n context?: Record<string, unknown>\n error?: unknown\n}\n\nexport interface MOSProxyLogger {\n log(event: MOSProxyLogEvent): void\n}\n\nexport const consoleLogger: MOSProxyLogger = {\n log(event) {\n const details: unknown[] = [event.message, { code: event.code, ...event.context }]\n if (event.error) {\n details.push(event.error)\n }\n\n if (event.level === 'error') {\n console.error(...details)\n return\n }\n\n console.warn(...details)\n },\n}\n"]}
@@ -1,9 +1,9 @@
1
1
  import type { Fetcher } from '../adapters/Fetcher';
2
+ import type { Identity } from '../adapters/IdentityProvider';
2
3
  import type { PipelineContext } from '../context';
3
4
  import type { PageMetadata, SurfaceDecisionResponse } from '../types';
4
5
  export type FetchSurfaceDecisionsArgs = {
5
- anonymousIdentifier?: string | undefined;
6
- userJwt?: string | undefined;
6
+ identity: Identity;
7
7
  path: string;
8
8
  url: string;
9
9
  clientMetadata: Record<string, unknown>;
@@ -22,4 +22,4 @@ export type FetchSurfaceDecisionsResult = {
22
22
  status?: number;
23
23
  statusCode?: number;
24
24
  };
25
- export default function fetchSurfaceDecisions(ctx: PipelineContext, { anonymousIdentifier, userJwt, path, url, clientMetadata, pageMetadata, userAgent, originStatus }: FetchSurfaceDecisionsArgs, apiFetcher: Fetcher): Promise<FetchSurfaceDecisionsResult>;
25
+ export default function fetchSurfaceDecisions(ctx: PipelineContext, { identity, path, url, clientMetadata, pageMetadata, userAgent, originStatus }: FetchSurfaceDecisionsArgs, apiFetcher: Fetcher): Promise<FetchSurfaceDecisionsResult>;
@@ -1,10 +1,10 @@
1
1
  import { withMosProxyHeaders } from '../apiRequestHeaders';
2
- export default async function fetchSurfaceDecisions(ctx, { anonymousIdentifier, userJwt, path, url, clientMetadata, pageMetadata, userAgent, originStatus }, apiFetcher) {
2
+ export default async function fetchSurfaceDecisions(ctx, { identity, path, url, clientMetadata, pageMetadata, userAgent, originStatus }, apiFetcher) {
3
3
  const { config } = ctx;
4
4
  const body = JSON.stringify({
5
5
  ...clientMetadata,
6
6
  surfaceSlug: config.surfaceSlug,
7
- identity: buildIdentity({ anonymousIdentifier, userJwt }),
7
+ identity,
8
8
  resource: {
9
9
  id: path,
10
10
  meta: pageMetadata,
@@ -67,12 +67,6 @@ export default async function fetchSurfaceDecisions(ctx, { anonymousIdentifier,
67
67
  return { ok: true, data };
68
68
  }
69
69
  const isRecord = (value) => typeof value === 'object' && value !== null;
70
- const buildIdentity = ({ anonymousIdentifier, userJwt }) => {
71
- if (!anonymousIdentifier && !userJwt) {
72
- return { createAnonymousIdentifier: true };
73
- }
74
- return userJwt ? { userJwt } : { anonymousIdentifier };
75
- };
76
70
  const isSurfaceDecisionError = (value) => isRecord(value) && value.status === 'error' && typeof value.message === 'string' && typeof value.statusCode === 'number';
77
71
  const isSurfaceDecisionResponse = (value) => isRecord(value) &&
78
72
  value.status === 'success' &&
@@ -1 +1 @@
1
- {"version":3,"file":"fetchSurfaceDecisions.js","sourceRoot":"","sources":["../../src/stages/fetchSurfaceDecisions.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAA;AA8B1D,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,qBAAqB,CAC/C,GAAoB,EACpB,EAAE,mBAAmB,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,cAAc,EAAE,YAAY,EA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A;AAED,MAAM,sBAAsB,GAAG,CAAC,KAAc,EAAiC,EAAE,CAC7E,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,KAAK,OAAO,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ,CAAA;AAE5H,MAAM,yBAAyB,GAAG,CAAC,KAAc,EAAoC,EAAE,CACnF,QAAQ,CAAC,KAAK,CAAC;IACf,KAAK,CAAC,MAAM,KAAK,SAAS;IAC1B,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC;IACxB,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC;IACxB,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC;IACxB,QAAQ,CAAC,KAAK,CAAC,eAAe,CAAC;IAC/B,OAAO,KAAK,CAAC,iBAAiB,KAAK,SAAS;IAC5C,QAAQ,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAA","sourcesContent":["import type { Fetcher } from '../adapters/Fetcher'\nimport { withMosProxyHeaders } from '../apiRequestHeaders'\nimport type { PipelineContext } from '../context'\nimport type { PageMetadata, SurfaceDecisionError, SurfaceDecisionResponse } from '../types'\n\nexport type FetchSurfaceDecisionsArgs = {\n anonymousIdentifier?: string | undefined\n userJwt?: string | undefined\n path: string\n url: string\n clientMetadata: Record<string, unknown>\n pageMetadata?: PageMetadata\n userAgent?: string | undefined\n originStatus: number\n}\n\nexport type FetchSurfaceDecisionsFailureReason = 'request-failed' | 'invalid-json' | 'api-error' | 'http-error' | 'invalid-response'\n\nexport type FetchSurfaceDecisionsResult =\n | {\n ok: true\n data: SurfaceDecisionResponse\n }\n | {\n ok: false\n reason: FetchSurfaceDecisionsFailureReason\n error: unknown\n status?: number\n statusCode?: number\n }\n\nexport default async function fetchSurfaceDecisions(\n ctx: PipelineContext,\n { anonymousIdentifier, userJwt, path, url, clientMetadata, pageMetadata, userAgent, originStatus }: FetchSurfaceDecisionsArgs,\n apiFetcher: Fetcher,\n): Promise<FetchSurfaceDecisionsResult> {\n const { config } = ctx\n const body = JSON.stringify({\n ...clientMetadata,\n surfaceSlug: config.surfaceSlug,\n identity: buildIdentity({ anonymousIdentifier, userJwt }),\n resource: {\n id: path,\n meta: pageMetadata,\n },\n http: {\n url,\n userAgent,\n proxyOrigin: {\n status: originStatus,\n },\n },\n })\n\n const request = new Request(new URL('/api/v1/surface-decisions', config.mosHost), {\n method: 'POST',\n body,\n headers: withMosProxyHeaders({\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.mosSecretKey}`,\n }),\n })\n\n let response: Response\n try {\n response = await apiFetcher(request)\n } catch (error) {\n return { ok: false, reason: 'request-failed', error }\n }\n\n let data: unknown\n try {\n data = await response.json()\n } catch (error) {\n return { ok: false, reason: 'invalid-json', error, status: response.status }\n }\n\n if (isSurfaceDecisionError(data)) {\n return {\n ok: false,\n reason: 'api-error',\n error: new Error(data.message),\n status: response.status,\n statusCode: data.statusCode,\n }\n }\n\n if (!response.ok) {\n return {\n ok: false,\n reason: 'http-error',\n error: new Error(`Surface decisions API returned HTTP ${response.status}`),\n status: response.status,\n }\n }\n\n if (!isSurfaceDecisionResponse(data)) {\n return {\n ok: false,\n reason: 'invalid-response',\n error: new Error('Surface decisions API returned an invalid response shape'),\n status: response.status,\n }\n }\n\n return { ok: true, data }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null\n\nconst buildIdentity = ({ anonymousIdentifier, userJwt }: Pick<FetchSurfaceDecisionsArgs, 'anonymousIdentifier' | 'userJwt'>) => {\n if (!anonymousIdentifier && !userJwt) {\n return { createAnonymousIdentifier: true }\n }\n return userJwt ? { userJwt } : { anonymousIdentifier }\n}\n\nconst isSurfaceDecisionError = (value: unknown): value is SurfaceDecisionError =>\n isRecord(value) && value.status === 'error' && typeof value.message === 'string' && typeof value.statusCode === 'number'\n\nconst isSurfaceDecisionResponse = (value: unknown): value is SurfaceDecisionResponse =>\n isRecord(value) &&\n value.status === 'success' &&\n isRecord(value.identity) &&\n isRecord(value.features) &&\n isRecord(value.customer) &&\n isRecord(value.surfaceBehavior) &&\n typeof value.componentsSkipped === 'boolean' &&\n isRecord(value.componentBehaviors)\n"]}
1
+ {"version":3,"file":"fetchSurfaceDecisions.js","sourceRoot":"","sources":["../../src/stages/fetchSurfaceDecisions.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAA;AA6B1D,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,qBAAqB,CAC/C,GAAoB,EACpB,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,EAAE,cAAc,EAAE,YAAY,EAAE,SAAS,EAAE,YAAY,EAA6B,EACzG,UAAmB;IAEnB,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAA;IACtB,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC;QACxB,GAAG,cAAc;QACjB,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,QAAQ;QACR,QAAQ,EAAE;YACN,EAAE,EAAE,IAAI;YACR,IAAI,EAAE,YAAY;SACrB;QACD,IAAI,EAAE;YACF,GAAG;YACH,SAAS;YACT,WAAW,EAAE;gBACT,MAAM,EAAE,YAAY;aACvB;SACJ;KACJ,CAAC,CAAA;IAEF,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,GAAG,CAAC,2BAA2B,EAAE,MAAM,CAAC,OAAO,CAAC,EAAE;QAC9E,MAAM,EAAE,MAAM;QACd,IAAI;QACJ,OAAO,EAAE,mBAAmB,CAAC;YACzB,cAAc,EAAE,kBAAkB;YAClC,aAAa,EAAE,UAAU,MAAM,CAAC,YAAY,EAAE;SACjD,CAAC;KACL,CAAC,CAAA;IAEF,IAAI,QAAkB,CAAA;IACtB,IAAI,CAAC;QACD,QAAQ,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,CAAA;IACxC,CAAC;IAAC,OAAO,KAAK,EAAE,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E,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAA;AAElH,MAAM,sBAAsB,GAAG,CAAC,KAAc,EAAiC,EAAE,CAC7E,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,KAAK,OAAO,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ,CAAA;AAE5H,MAAM,yBAAyB,GAAG,CAAC,KAAc,EAAoC,EAAE,CACnF,QAAQ,CAAC,KAAK,CAAC;IACf,KAAK,CAAC,MAAM,KAAK,SAAS;IAC1B,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC;IACxB,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC;IACxB,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC;IACxB,QAAQ,CAAC,KAAK,CAAC,eAAe,CAAC;IAC/B,OAAO,KAAK,CAAC,iBAAiB,KAAK,SAAS;IAC5C,QAAQ,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAA","sourcesContent":["import type { Fetcher } from '../adapters/Fetcher'\nimport type { Identity } from '../adapters/IdentityProvider'\nimport { withMosProxyHeaders } from '../apiRequestHeaders'\nimport type { PipelineContext } from '../context'\nimport type { PageMetadata, SurfaceDecisionError, SurfaceDecisionResponse } from '../types'\n\nexport type FetchSurfaceDecisionsArgs = {\n identity: Identity\n path: string\n url: string\n clientMetadata: Record<string, unknown>\n pageMetadata?: PageMetadata\n userAgent?: string | undefined\n originStatus: number\n}\n\nexport type FetchSurfaceDecisionsFailureReason = 'request-failed' | 'invalid-json' | 'api-error' | 'http-error' | 'invalid-response'\n\nexport type FetchSurfaceDecisionsResult =\n | {\n ok: true\n data: SurfaceDecisionResponse\n }\n | {\n ok: false\n reason: FetchSurfaceDecisionsFailureReason\n error: unknown\n status?: number\n statusCode?: number\n }\n\nexport default async function fetchSurfaceDecisions(\n ctx: PipelineContext,\n { identity, path, url, clientMetadata, pageMetadata, userAgent, originStatus }: FetchSurfaceDecisionsArgs,\n apiFetcher: Fetcher,\n): Promise<FetchSurfaceDecisionsResult> {\n const { config } = ctx\n const body = JSON.stringify({\n ...clientMetadata,\n surfaceSlug: config.surfaceSlug,\n identity,\n resource: {\n id: path,\n meta: pageMetadata,\n },\n http: {\n url,\n userAgent,\n proxyOrigin: {\n status: originStatus,\n },\n },\n })\n\n const request = new Request(new URL('/api/v1/surface-decisions', config.mosHost), {\n method: 'POST',\n body,\n headers: withMosProxyHeaders({\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.mosSecretKey}`,\n }),\n })\n\n let response: Response\n try {\n response = await apiFetcher(request)\n } catch (error) {\n return { ok: false, reason: 'request-failed', error }\n }\n\n let data: unknown\n try {\n data = await response.json()\n } catch (error) {\n return { ok: false, reason: 'invalid-json', error, status: response.status }\n }\n\n if (isSurfaceDecisionError(data)) {\n return {\n ok: false,\n reason: 'api-error',\n error: new Error(data.message),\n status: response.status,\n statusCode: data.statusCode,\n }\n }\n\n if (!response.ok) {\n return {\n ok: false,\n reason: 'http-error',\n error: new Error(`Surface decisions API returned HTTP ${response.status}`),\n status: response.status,\n }\n }\n\n if (!isSurfaceDecisionResponse(data)) {\n return {\n ok: false,\n reason: 'invalid-response',\n error: new Error('Surface decisions API returned an invalid response shape'),\n status: response.status,\n }\n }\n\n return { ok: true, data }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null\n\nconst isSurfaceDecisionError = (value: unknown): value is SurfaceDecisionError =>\n isRecord(value) && value.status === 'error' && typeof value.message === 'string' && typeof value.statusCode === 'number'\n\nconst isSurfaceDecisionResponse = (value: unknown): value is SurfaceDecisionResponse =>\n isRecord(value) &&\n value.status === 'success' &&\n isRecord(value.identity) &&\n isRecord(value.features) &&\n isRecord(value.customer) &&\n isRecord(value.surfaceBehavior) &&\n typeof value.componentsSkipped === 'boolean' &&\n isRecord(value.componentBehaviors)\n"]}
@@ -1,6 +1,7 @@
1
1
  import type { ClientMetadataProvider } from '../adapters/ClientMetadataProvider';
2
2
  import type { Fetcher } from '../adapters/Fetcher';
3
3
  import type { HtmlRewriterAdapter } from '../adapters/HtmlRewriterAdapter';
4
+ import { type IdentityProvider } from '../adapters/IdentityProvider';
4
5
  import type { PipelineContext } from '../context';
5
6
  import type { SurfaceDecisionResponse } from '../types';
6
- export default function getSurfaceDecisions(ctx: PipelineContext, request: Request, response: Response, apiFetcher: Fetcher, rewriter: HtmlRewriterAdapter | null, clientMetadataProvider: ClientMetadataProvider | null): Promise<[Response, SurfaceDecisionResponse | null]>;
7
+ export default function getSurfaceDecisions(ctx: PipelineContext, request: Request, response: Response, apiFetcher: Fetcher, rewriter: HtmlRewriterAdapter | null, clientMetadataProvider: ClientMetadataProvider | null, identityProvider: IdentityProvider | null): Promise<[Response, SurfaceDecisionResponse | null]>;
@@ -1,16 +1,28 @@
1
- import { parse, parseSetCookie } from 'cookie';
1
+ import { defaultPersistIdentity, defaultResolveIdentity } from '../adapters/IdentityProvider';
2
2
  import fetchSurfaceDecisions from './fetchSurfaceDecisions';
3
3
  import { parsePageMetadata } from './pageMetadata';
4
- export default async function getSurfaceDecisions(ctx, request, response, apiFetcher, rewriter, clientMetadataProvider) {
4
+ export default async function getSurfaceDecisions(ctx, request, response, apiFetcher, rewriter, clientMetadataProvider, identityProvider) {
5
5
  const { config, logger } = ctx;
6
- const { anonymousIdentifier, userJwt } = getExistingCookies(request, response, config);
6
+ const resolve = identityProvider?.resolve ?? defaultResolveIdentity;
7
+ let identity;
8
+ try {
9
+ identity = await resolve({ request, originResponse: response, config, logger });
10
+ }
11
+ catch (error) {
12
+ logger.log({
13
+ level: 'warn',
14
+ code: 'identity-resolve-failed',
15
+ message: 'Identity provider resolve threw; skipping surface decisions and returning origin response.',
16
+ error,
17
+ });
18
+ return [response, null];
19
+ }
7
20
  const [metadataStream, passThroughStream] = response.body?.tee() ?? [null, null];
8
21
  const pageMetadata = metadataStream && rewriter ? await parsePageMetadata(ctx, new Response(metadataStream, response), rewriter) : {};
9
22
  let modifiedResponse = passThroughStream ? new Response(passThroughStream, response) : response;
10
23
  const clientMetadata = clientMetadataProvider?.build(request) ?? {};
11
24
  const result = await fetchSurfaceDecisions(ctx, {
12
- anonymousIdentifier,
13
- userJwt,
25
+ identity,
14
26
  path: new URL(request.url).pathname,
15
27
  url: request.url,
16
28
  clientMetadata,
@@ -33,27 +45,25 @@ export default async function getSurfaceDecisions(ctx, request, response, apiFet
33
45
  return [modifiedResponse, null];
34
46
  }
35
47
  const surfaceDecisions = result.data;
36
- if (!anonymousIdentifier && !userJwt && surfaceDecisions?.identity?.identifier) {
37
- const headers = new Headers(modifiedResponse.headers);
38
- headers.append('Set-Cookie', `${config.anonymousSessionCookieName}=${surfaceDecisions.identity.identifier}; Path=/`);
39
- modifiedResponse = new Response(modifiedResponse.body, {
40
- status: modifiedResponse.status,
41
- statusText: modifiedResponse.statusText,
42
- headers,
48
+ const persist = identityProvider?.persist ?? defaultPersistIdentity;
49
+ try {
50
+ modifiedResponse = await persist({
51
+ resolved: identity,
52
+ decisions: surfaceDecisions,
53
+ response: modifiedResponse,
54
+ request,
55
+ config,
56
+ logger,
57
+ });
58
+ }
59
+ catch (error) {
60
+ logger.log({
61
+ level: 'warn',
62
+ code: 'identity-persist-failed',
63
+ message: 'Identity provider persist threw; keeping pre-persist response.',
64
+ error,
43
65
  });
44
66
  }
45
67
  return [modifiedResponse, surfaceDecisions];
46
68
  }
47
- const getExistingCookies = (request, originResponse, config) => {
48
- const setCookies = originResponse.headers.getSetCookie().map((header) => parseSetCookie(header));
49
- const originAnonymousCookie = setCookies.find((s) => s.name === config.anonymousSessionCookieName);
50
- const originUserJwtCookie = setCookies.find((s) => s.name === config.authenticatedUserJwtCookieName);
51
- if (originAnonymousCookie || originUserJwtCookie) {
52
- return { anonymousIdentifier: originAnonymousCookie?.value, userJwt: originUserJwtCookie?.value };
53
- }
54
- const cookies = parse(request.headers.get('Cookie') || '');
55
- const anonymousIdentifier = cookies[config.anonymousSessionCookieName];
56
- const userJwt = cookies[config.authenticatedUserJwtCookieName];
57
- return { anonymousIdentifier, userJwt };
58
- };
59
69
  //# sourceMappingURL=surfaceDecisions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"surfaceDecisions.js","sourceRoot":"","sources":["../../src/stages/surfaceDecisions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAA;AAO9C,OAAO,qBAAqB,MAAM,yBAAyB,CAAA;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAElD,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,mBAAmB,CAC7C,GAAoB,EACpB,OAAgB,EAChB,QAAkB,EAClB,UAAmB,EACnB,QAAoC,EACpC,sBAAqD;IAErD,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAA;IAC9B,MAAM,EAAE,mBAAmB,EAAE,OAAO,EAAE,GAAG,kBAAkB,CAAC,OAAO,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;IAEtF,MAAM,CAAC,cAAc,EAAE,iBAAiB,CAAC,GAAG,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IAChF,MAAM,YAAY,GAAG,cAAc,IAAI,QAAQ,CAAC,CAAC,CAAC,MAAM,iBAAiB,CAAC,GAAG,EAAE,IAAI,QAAQ,CAAC,cAAc,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;IACrI,IAAI,gBAAgB,GAAG,iBAAiB,CAAC,CAAC,CAAC,IAAI,QAAQ,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAA;IAE/F,MAAM,cAAc,GAAG,sBAAsB,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAA;I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AgB,CAAC,UAAU;YACvC,OAAO;SACV,CAAC,CAAA;IACN,CAAC;IAED,OAAO,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,CAAA;AAC/C,CAAC;AAED,MAAM,kBAAkB,GAAG,CAAC,OAAgB,EAAE,cAAwB,EAAE,MAAiB,EAAE,EAAE;IACzF,MAAM,UAAU,GAAG,cAAc,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAA;IAChG,MAAM,qBAAqB,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,0BAA0B,CAAC,CAAA;IAClG,MAAM,mBAAmB,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,8BAA8B,CAAC,CAAA;IACpG,IAAI,qBAAqB,IAAI,mBAAmB,EAAE,CAAC;QAC/C,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,KAAK,EAAE,OAAO,EAAE,mBAAmB,EAAE,KAAK,EAAE,CAAA;IACrG,CAAC;IAED,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAA;IAC1D,MAAM,mBAAmB,GAAG,OAAO,CAAC,MAAM,CAAC,0BAA0B,CAAC,CAAA;IACtE,MAAM,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,8BAA8B,CAAC,CAAA;IAC9D,OAAO,EAAE,mBAAmB,EAAE,OAAO,EAAE,CAAA;AAC3C,CAAC,CAAA","sourcesContent":["import { parse, parseSetCookie } from 'cookie'\nimport type { ClientMetadataProvider } from '../adapters/ClientMetadataProvider'\nimport type { Fetcher } from '../adapters/Fetcher'\nimport type { HtmlRewriterAdapter } from '../adapters/HtmlRewriterAdapter'\nimport type { MOSConfig } from '../config'\nimport type { PipelineContext } from '../context'\nimport type { SurfaceDecisionResponse } from '../types'\nimport fetchSurfaceDecisions from './fetchSurfaceDecisions'\nimport { parsePageMetadata } from './pageMetadata'\n\nexport default async function getSurfaceDecisions(\n ctx: PipelineContext,\n request: Request,\n response: Response,\n apiFetcher: Fetcher,\n rewriter: HtmlRewriterAdapter | null,\n clientMetadataProvider: ClientMetadataProvider | null,\n): Promise<[Response, SurfaceDecisionResponse | null]> {\n const { config, logger } = ctx\n const { anonymousIdentifier, userJwt } = getExistingCookies(request, response, config)\n\n const [metadataStream, passThroughStream] = response.body?.tee() ?? [null, null]\n const pageMetadata = metadataStream && rewriter ? await parsePageMetadata(ctx, new Response(metadataStream, response), rewriter) : {}\n let modifiedResponse = passThroughStream ? new Response(passThroughStream, response) : response\n\n const clientMetadata = clientMetadataProvider?.build(request) ?? {}\n\n const result = await fetchSurfaceDecisions(\n ctx,\n {\n anonymousIdentifier,\n userJwt,\n path: new URL(request.url).pathname,\n url: request.url,\n clientMetadata,\n pageMetadata,\n userAgent: request.headers.get('User-Agent') ?? undefined,\n originStatus: response.status,\n },\n apiFetcher,\n )\n\n if (!result.ok) {\n logger.log({\n level: 'warn',\n code: 'surface-decisions-api-failed',\n message: 'Surface decisions API failed; continuing with the origin response.',\n context: {\n reason: result.reason,\n status: result.status,\n statusCode: result.statusCode,\n },\n error: result.error,\n })\n return [modifiedResponse, null]\n }\n\n const surfaceDecisions = result.data\n\n if (!anonymousIdentifier && !userJwt && surfaceDecisions?.identity?.identifier) {\n const headers = new Headers(modifiedResponse.headers)\n headers.append('Set-Cookie', `${config.anonymousSessionCookieName}=${surfaceDecisions.identity.identifier}; Path=/`)\n modifiedResponse = new Response(modifiedResponse.body, {\n status: modifiedResponse.status,\n statusText: modifiedResponse.statusText,\n headers,\n })\n }\n\n return [modifiedResponse, surfaceDecisions]\n}\n\nconst getExistingCookies = (request: Request, originResponse: Response, config: MOSConfig) => {\n const setCookies = originResponse.headers.getSetCookie().map((header) => parseSetCookie(header))\n const originAnonymousCookie = setCookies.find((s) => s.name === config.anonymousSessionCookieName)\n const originUserJwtCookie = setCookies.find((s) => s.name === config.authenticatedUserJwtCookieName)\n if (originAnonymousCookie || originUserJwtCookie) {\n return { anonymousIdentifier: originAnonymousCookie?.value, userJwt: originUserJwtCookie?.value }\n }\n\n const cookies = parse(request.headers.get('Cookie') || '')\n const anonymousIdentifier = cookies[config.anonymousSessionCookieName]\n const userJwt = cookies[config.authenticatedUserJwtCookieName]\n return { anonymousIdentifier, userJwt }\n}\n"]}
1
+ {"version":3,"file":"surfaceDecisions.js","sourceRoot":"","sources":["../../src/stages/surfaceDecisions.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAwC,MAAM,8BAA8B,CAAA;AAGnI,OAAO,qBAAqB,MAAM,yBAAyB,CAAA;AAC3D,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAElD,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,mBAAmB,CAC7C,GAAoB,EACpB,OAAgB,EAChB,QAAkB,EAClB,UAAmB,EACnB,QAAoC,EACpC,sBAAqD,EACrD,gBAAyC;IAEzC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAA;IAE9B,MAAM,OAAO,GAAG,gBAAgB,EAAE,OAAO,IAAI,sBAAsB,CAAA;IACnE,IAAI,QAAkB,CAAA;IACtB,IAAI,CAAC;QACD,QAAQ,GAAG,MAAM,OAAO,CAAC,EAAE,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAA;IACnF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,MAAM,CAAC,GAAG,CAAC;YACP,KAAK,EAAE,MAAM;YACb,IAAI,EAAE,yBAAyB;YAC/B,OAAO,EAAE,4FAA4F;YACrG,KAAK;SACR,CAAC,C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AK,EAAE,MAAM,CAAC,KAAK;SACtB,CAAC,CAAA;QACF,OAAO,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;IAED,MAAM,gBAAgB,GAAG,MAAM,CAAC,IAAI,CAAA;IAEpC,MAAM,OAAO,GAAG,gBAAgB,EAAE,OAAO,IAAI,sBAAsB,CAAA;IACnE,IAAI,CAAC;QACD,gBAAgB,GAAG,MAAM,OAAO,CAAC;YAC7B,QAAQ,EAAE,QAAQ;YAClB,SAAS,EAAE,gBAAgB;YAC3B,QAAQ,EAAE,gBAAgB;YAC1B,OAAO;YACP,MAAM;YACN,MAAM;SACT,CAAC,CAAA;IACN,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,MAAM,CAAC,GAAG,CAAC;YACP,KAAK,EAAE,MAAM;YACb,IAAI,EAAE,yBAAyB;YAC/B,OAAO,EAAE,gEAAgE;YACzE,KAAK;SACR,CAAC,CAAA;IACN,CAAC;IAED,OAAO,CAAC,gBAAgB,EAAE,gBAAgB,CAAC,CAAA;AAC/C,CAAC","sourcesContent":["import type { ClientMetadataProvider } from '../adapters/ClientMetadataProvider'\nimport type { Fetcher } from '../adapters/Fetcher'\nimport type { HtmlRewriterAdapter } from '../adapters/HtmlRewriterAdapter'\nimport { defaultPersistIdentity, defaultResolveIdentity, type Identity, type IdentityProvider } from '../adapters/IdentityProvider'\nimport type { PipelineContext } from '../context'\nimport type { SurfaceDecisionResponse } from '../types'\nimport fetchSurfaceDecisions from './fetchSurfaceDecisions'\nimport { parsePageMetadata } from './pageMetadata'\n\nexport default async function getSurfaceDecisions(\n ctx: PipelineContext,\n request: Request,\n response: Response,\n apiFetcher: Fetcher,\n rewriter: HtmlRewriterAdapter | null,\n clientMetadataProvider: ClientMetadataProvider | null,\n identityProvider: IdentityProvider | null,\n): Promise<[Response, SurfaceDecisionResponse | null]> {\n const { config, logger } = ctx\n\n const resolve = identityProvider?.resolve ?? defaultResolveIdentity\n let identity: Identity\n try {\n identity = await resolve({ request, originResponse: response, config, logger })\n } catch (error) {\n logger.log({\n level: 'warn',\n code: 'identity-resolve-failed',\n message: 'Identity provider resolve threw; skipping surface decisions and returning origin response.',\n error,\n })\n return [response, null]\n }\n\n const [metadataStream, passThroughStream] = response.body?.tee() ?? [null, null]\n const pageMetadata = metadataStream && rewriter ? await parsePageMetadata(ctx, new Response(metadataStream, response), rewriter) : {}\n let modifiedResponse = passThroughStream ? new Response(passThroughStream, response) : response\n\n const clientMetadata = clientMetadataProvider?.build(request) ?? {}\n\n const result = await fetchSurfaceDecisions(\n ctx,\n {\n identity,\n path: new URL(request.url).pathname,\n url: request.url,\n clientMetadata,\n pageMetadata,\n userAgent: request.headers.get('User-Agent') ?? undefined,\n originStatus: response.status,\n },\n apiFetcher,\n )\n\n if (!result.ok) {\n logger.log({\n level: 'warn',\n code: 'surface-decisions-api-failed',\n message: 'Surface decisions API failed; continuing with the origin response.',\n context: {\n reason: result.reason,\n status: result.status,\n statusCode: result.statusCode,\n },\n error: result.error,\n })\n return [modifiedResponse, null]\n }\n\n const surfaceDecisions = result.data\n\n const persist = identityProvider?.persist ?? defaultPersistIdentity\n try {\n modifiedResponse = await persist({\n resolved: identity,\n decisions: surfaceDecisions,\n response: modifiedResponse,\n request,\n config,\n logger,\n })\n } catch (error) {\n logger.log({\n level: 'warn',\n code: 'identity-persist-failed',\n message: 'Identity provider persist threw; keeping pre-persist response.',\n error,\n })\n }\n\n return [modifiedResponse, surfaceDecisions]\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -113,4 +113,10 @@ export interface MOSConfigInput {
113
113
  surfaceDecisionsIgnorePaths?: string;
114
114
  /** Optional headers added to or replacing client headers on every origin request. */
115
115
  originRequestHeaders?: Record<string, string>;
116
+ /**
117
+ * When true (default), JWT surface-decision requests include `createAnonymousIdentifierFallback: true`
118
+ * so MonetizationOS can mint an anonymous identifier if JWT authentication fails.
119
+ * Set to `false` to opt out.
120
+ */
121
+ createAnonymousIdentifierFallback?: boolean;
116
122
  }
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["export type PageMetadata = Record<string, string>\n\nexport interface FeatureMeterableProperty {\n type: 'meterable'\n hasAccess: boolean\n remainingUnits?: number\n}\n\nexport interface FeatureNumberProperty {\n type: 'number'\n value: number\n}\n\nexport interface Feature {\n featureSlug: string\n properties: Record<string, FeatureMeterableProperty | FeatureNumberProperty>\n sideEffects: unknown[]\n}\n\nexport interface SubSurfaceMetadataApi {\n cssSelector?: string | null\n}\n\nexport type SetHttpResponse = {\n headers?: Record<string, string>\n cookies?: string[]\n status: number\n statusText?: string\n body: string | null\n}\n\nexport type ModifyHttpResponse = {\n addHeaders?: { name: string; value: string }[]\n removeHeaders?: string[]\n addCookies?: string[]\n status?: number\n statusText?: string\n body?: string | null\n}\n\nexport type SurfaceBehaviorApi = {\n http?: ModifyHttpResponse | SetHttpResponse\n properties?: Record<string, unknown>\n} & Record<string, unknown>\n\nexport type WebComponentElement<T = Record<string, unknown>> = {\n schema: string\n props: T\n}\n\nexport type WebElement =\n | {\n type: 'html'\n content: string\n }\n | {\n type: 'text'\n content: string\n }\n | ({\n type: 'element'\n } & WebComponentElement)\n | ({\n type: 'custom'\n } & Record<string, unknown>)\n\nexport type WebComponentRangeReplacement = {\n fromMarker?: string\n toMarker?: string\n replaceWith?: WebElement[] | null\n}\n\nexport type WebContentSurfaceBehavior = {\n before?: WebElement[]\n prepend?: WebElement[]\n remove?: boolean\n replaceRange?: WebComponentRangeReplacement | null\n append?: WebElement[]\n after?: WebElement[]\n}\n\nexport type SubSurfaceBehaviorApi = {\n content?: WebContentSurfaceBehavior\n properties?: Record<string, unknown>\n metadata: SubSurfaceMetadataApi\n} & Record<string, unknown>\n\nexport interface SurfaceDecisionResponse {\n status: 'success'\n identity: {\n identifier: string\n isAuthenticated: boolean\n authType: string\n jwtClaims: Record<string, unknown>\n }\n features: Record<string, Feature>\n customer: {\n hasProducts: boolean\n }\n surfaceBehavior: SurfaceBehaviorApi\n componentsSkipped: boolean\n componentBehaviors: Record<string, SubSurfaceBehaviorApi>\n}\n\nexport interface SurfaceDecisionError {\n message: string\n status: 'error'\n statusCode: number\n}\n\nexport interface MOSConfigInput {\n /** Origin website base URL, e.g. `https://news.example.com`. */\n originUrl: string\n /** Surface slug identifying the MonetizationOS surface. */\n surfaceSlug: string\n /** MonetizationOS API base URL. */\n mosHost: string\n /** MonetizationOS secret key; expected format `sk_<env>_<suffix>` */\n mosSecretKey: string\n /** Path prefix routed to the MonetizationOS endpoint proxy. Default: `/mos-endpoints/`. */\n mosEndpointsPrefix?: string\n /** Cookie name storing the anonymous session id. */\n anonymousSessionCookieName: string\n /** Cookie name storing the authenticated user JWT. */\n authenticatedUserJwtCookieName: string\n /** Optional script URL injected into the `<head>` of HTML responses. */\n injectScriptUrl?: string\n /** Comma-separated regex patterns; matching pathnames skip surface decisions. */\n surfaceDecisionsIgnorePaths?: string\n /** Optional headers added to or replacing client headers on every origin request. */\n originRequestHeaders?: Record<string, string>\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["export type PageMetadata = Record<string, string>\n\nexport interface FeatureMeterableProperty {\n type: 'meterable'\n hasAccess: boolean\n remainingUnits?: number\n}\n\nexport interface FeatureNumberProperty {\n type: 'number'\n value: number\n}\n\nexport interface Feature {\n featureSlug: string\n properties: Record<string, FeatureMeterableProperty | FeatureNumberProperty>\n sideEffects: unknown[]\n}\n\nexport interface SubSurfaceMetadataApi {\n cssSelector?: string | null\n}\n\nexport type SetHttpResponse = {\n headers?: Record<string, string>\n cookies?: string[]\n status: number\n statusText?: string\n body: string | null\n}\n\nexport type ModifyHttpResponse = {\n addHeaders?: { name: string; value: string }[]\n removeHeaders?: string[]\n addCookies?: string[]\n status?: number\n statusText?: string\n body?: string | null\n}\n\nexport type SurfaceBehaviorApi = {\n http?: ModifyHttpResponse | SetHttpResponse\n properties?: Record<string, unknown>\n} & Record<string, unknown>\n\nexport type WebComponentElement<T = Record<string, unknown>> = {\n schema: string\n props: T\n}\n\nexport type WebElement =\n | {\n type: 'html'\n content: string\n }\n | {\n type: 'text'\n content: string\n }\n | ({\n type: 'element'\n } & WebComponentElement)\n | ({\n type: 'custom'\n } & Record<string, unknown>)\n\nexport type WebComponentRangeReplacement = {\n fromMarker?: string\n toMarker?: string\n replaceWith?: WebElement[] | null\n}\n\nexport type WebContentSurfaceBehavior = {\n before?: WebElement[]\n prepend?: WebElement[]\n remove?: boolean\n replaceRange?: WebComponentRangeReplacement | null\n append?: WebElement[]\n after?: WebElement[]\n}\n\nexport type SubSurfaceBehaviorApi = {\n content?: WebContentSurfaceBehavior\n properties?: Record<string, unknown>\n metadata: SubSurfaceMetadataApi\n} & Record<string, unknown>\n\nexport interface SurfaceDecisionResponse {\n status: 'success'\n identity: {\n identifier: string\n isAuthenticated: boolean\n authType: string\n jwtClaims: Record<string, unknown>\n }\n features: Record<string, Feature>\n customer: {\n hasProducts: boolean\n }\n surfaceBehavior: SurfaceBehaviorApi\n componentsSkipped: boolean\n componentBehaviors: Record<string, SubSurfaceBehaviorApi>\n}\n\nexport interface SurfaceDecisionError {\n message: string\n status: 'error'\n statusCode: number\n}\n\nexport interface MOSConfigInput {\n /** Origin website base URL, e.g. `https://news.example.com`. */\n originUrl: string\n /** Surface slug identifying the MonetizationOS surface. */\n surfaceSlug: string\n /** MonetizationOS API base URL. */\n mosHost: string\n /** MonetizationOS secret key; expected format `sk_<env>_<suffix>` */\n mosSecretKey: string\n /** Path prefix routed to the MonetizationOS endpoint proxy. Default: `/mos-endpoints/`. */\n mosEndpointsPrefix?: string\n /** Cookie name storing the anonymous session id. */\n anonymousSessionCookieName: string\n /** Cookie name storing the authenticated user JWT. */\n authenticatedUserJwtCookieName: string\n /** Optional script URL injected into the `<head>` of HTML responses. */\n injectScriptUrl?: string\n /** Comma-separated regex patterns; matching pathnames skip surface decisions. */\n surfaceDecisionsIgnorePaths?: string\n /** Optional headers added to or replacing client headers on every origin request. */\n originRequestHeaders?: Record<string, string>\n /**\n * When true (default), JWT surface-decision requests include `createAnonymousIdentifierFallback: true`\n * so MonetizationOS can mint an anonymous identifier if JWT authentication fails.\n * Set to `false` to opt out.\n */\n createAnonymousIdentifierFallback?: boolean\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monetizationos/proxy",
3
- "version": "1.0.3",
3
+ "version": "1.2.0",
4
4
  "description": "Platform-agnostic MonetizationOS proxy core",
5
5
  "license": "MIT",
6
6
  "type": "module",