Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/core/src/utils/worldwide.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@

/* eslint-disable @typescript-eslint/no-explicit-any */

import type { Integration } from '../types/integration';
import type { Carrier } from '../carrier';
import type { SdkSource } from './env';

Expand DownExpand Up@@ -63,6 +64,14 @@ export type InternalGlobal = {
runtime?: string[];
/** Empty array signifies bundler plugin ran */
bundler?: string[];
/**
* Channel-subscriber integration factories a bundler plugin's
* subscribe-injection stored here, keyed by export name (one per instrumented
* package actually bundled; the key dedupes packages split across several
* files). A bundler-only SDK (e.g. `@sentry/cloudflare`) reads these at
* `init()` and instantiates them.
*/
integrations?: Map<string, () => Integration>;
};
} & Carrier;

Expand Down
3 changes: 2 additions & 1 deletion packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,8 @@
"@apm-js-collab/code-transformer-bundler-plugins": "^0.7.1",
"@apm-js-collab/tracing-hooks": "^0.13.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"meriyah": "^6.1.4"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
31 changes: 29 additions & 2 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { InstrumentationConfig, CustomTransform } from '..';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import { subscribeInjectionOptions } from './subscribeInjection';
import type { CodeTransformerPluginOptions } from '@apm-js-collab/code-transformer-bundler-plugins/core';

export type PluginOptions = {
Expand All@@ -17,6 +18,26 @@ export type PluginOptions = {
* Defaults to `true`.
*/
shouldInjectDiagnostics?: boolean;
/**
* Inject a small marker-push into each instrumented module that imports only
* that package's channel-subscriber factory and pushes it onto
* `globalThis.__SENTRY_ORCHESTRION__.integrations`. A bundler-only SDK reads
* the marker at `init()` and instantiates the collected factories, so every
* transformed package's subscriber is wired up with no runtime module hook.
*
* Because each site imports a single named factory, it tree-shakes: a bundle
* carries subscriber code only for the packages actually transformed into it.
*
* This is what lets a bundler-only SDK (e.g. `@sentry/cloudflare`, which runs
* in workerd where requires can't be monkey-patched) record channel spans,
* but it is bundler-agnostic: any orchestrion bundler plugin can enable it.
* Leave it off for SDKs that wire the integrations up through a static import
* instead (e.g. `@sentry/node`'s `experimentalUseDiagnosticsChannelInjection()`),
* so the subscribers aren't registered twice.
*
* Defaults to `false`.
*/
injectChannelSubscribers?: boolean;
};

/**
Expand DownExpand Up@@ -53,8 +74,14 @@ export function externalizedModulesWarning(externalizedModules: string[]): strin
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): CodeTransformerPluginOptions {
const instrumentations = [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])];
const customTransforms = options.customTransforms;
const subscribeInjection = options.injectChannelSubscribers ? subscribeInjectionOptions() : undefined;

const instrumentations = [
...SENTRY_INSTRUMENTATIONS,
...(options.instrumentations || []),
...(subscribeInjection?.instrumentations || []),
];
const customTransforms = { ...options.customTransforms, ...subscribeInjection?.customTransforms };

if (options.shouldInjectDiagnostics === false) {
return {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
import type { CustomTransform } from '@apm-js-collab/code-transformer';
import { parse } from 'meriyah';
import { SUBSCRIBE_INJECTIONS } from '../config';
import { subscriberExportForModule } from '../config/channel-integration-definitions';
import { SUBSCRIBE_TRANSFORM_NAME } from '../config/subscribe-injection';
import type { PluginOptions } from './options';

// Tracks Program nodes we already injected into, so a package with several
// instrumented files (or several configs pointing at one file) is injected only
// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.
const injectedPrograms = new WeakSet<object>();

interface ProgramNode {
type: string;
body: Array<{ type: string; directive?: string }>;
}

/**
* Snippet injected into each instrumented module. It imports ONLY that package's
* channel-subscriber factory (plus the `registerOrchestrionChannelIntegration`
* helper) from `@sentry/server-utils/orchestrion`, and hands both to the helper,
* which stores the factory on the global marker and live-registers it on any
* existing client (see that helper for the load-order and dedup rationale).
*
* Importing the single named factory (rather than a central dispatch that pulls
* in every subscriber) is what makes this tree-shake: a bundle carries only the
* subscriber code for packages actually transformed into it. The same
* "only-active-when-bundled" property the runtime module hook gives unbundled
* Node, but without a hook (workerd can't monkey-patch requires). The helper is
* generic (references no factory), so importing it alongside doesn't pull siblings.
*/
function subscribeSnippet(exportName: string, esm: boolean): string {
const importStmt = esm
? `import { ${exportName}, registerOrchestrionChannelIntegration } from '@sentry/server-utils/orchestrion';`
: `const { ${exportName}, registerOrchestrionChannelIntegration } = require('@sentry/server-utils/orchestrion');`;

return `${importStmt}\nregisterOrchestrionChannelIntegration(${JSON.stringify(exportName)}, ${exportName});`;
}

/**
* The custom transform registered under {@link SUBSCRIBE_TRANSFORM_NAME}. It is
* invoked with the matched `Program` node and mutates it in place, splicing the
* marker-push snippet in after any `'use strict'` directive.
*
* `state` carries the matched config spread with `{ moduleType }`; the config's
* `channelName` carries the package name (see `toSubscribeInjections`), which
* maps to the subscriber's export name.
*/
const injectSubscribe: CustomTransform = (state, program) => {
const node = program as ProgramNode;
if (injectedPrograms.has(node)) {
return;
}

const { moduleType, channelName } = state as { moduleType?: string; channelName?: string };
const exportName = channelName ? subscriberExportForModule(channelName) : undefined;
if (!exportName) {
return;
}

injectedPrograms.add(node);

const statements = parse(subscribeSnippet(exportName, moduleType === 'esm'), {
module: moduleType === 'esm',
next: true,
}).body as ProgramNode['body'];

const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');
Comment thread
sentry[bot] marked this conversation as resolved.
node.body.splice(directiveIndex + 1, 0, ...statements);
Comment thread
sentry[bot] marked this conversation as resolved.
};

/**
* The `instrumentations` + `customTransforms` a bundler plugin passes to
* {@link orchestrionTransformOptions} to enable the marker-push subscribe
* injection used by bundler-only SDKs (e.g. `@sentry/cloudflare`).
*
* The `SUBSCRIBE_INJECTIONS` configs ride alongside the real channel-publishing
* configs, and `injectSubscribe` runs on each matched module, so every
* transformed package self-registers its subscriber on the global marker
* without a runtime module hook.
*/
export function subscribeInjectionOptions(): Pick<PluginOptions, 'instrumentations' | 'customTransforms'> {
return {
instrumentations: SUBSCRIBE_INJECTIONS,
customTransforms: { [SUBSCRIBE_TRANSFORM_NAME]: injectSubscribe },
};
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/amqplib.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `amqplib` splits its API across three files:
// - `lib/channel_model.js` holds `class Channel` (publish/consume/ack/nack/reject/…) and
Expand DownExpand Up@@ -87,3 +88,5 @@ export const amqplibChannels = {
AMQPLIB_NACK_ALL: 'orchestrion:amqplib:nackAll',
AMQPLIB_CONNECT: 'orchestrion:amqplib:connect',
} as const;

export const amqplibSubscribeInjection = toSubscribeInjections(amqplibConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/anthropic-ai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const anthropicAiConfig = [
// One entry each for CJS/ESM
Expand DownExpand Up@@ -38,3 +39,5 @@ export const anthropicAiChannels = {
ANTHROPIC_MODELS: 'orchestrion:@anthropic-ai/sdk:models',
ANTHROPIC_MESSAGES_STREAM: 'orchestrion:@anthropic-ai/sdk:messages-stream',
} as const;

export const anthropicAiSubscribeInjection = toSubscribeInjections(anthropicAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/aws-sdk.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { toSubscribeInjections } from './subscribe-injection';

// The AWS SDK (v3) routes every command through the smithy `Client.prototype.send` method. Which
// package hosts that `Client` class changed across versions, so we target all of them; only the one
Expand DownExpand Up@@ -32,3 +33,5 @@ export const awsSdkChannels = {
AWS_SMITHY_CLIENT_SEND: 'orchestrion:@smithy/smithy-client:send',
AWS_SDK_SMITHY_CLIENT_SEND: 'orchestrion:@aws-sdk/smithy-client:send',
} as const;

export const awsSdkSubscribeInjection = toSubscribeInjections(awsSdkConfig);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
/**
* Build-time metadata mapping each instrumented package (orchestrion
* `module.name`) to the channel-subscriber integration that consumes the
* channels injected into it — by the `exportName` it is published under from
* `@sentry/server-utils/orchestrion`.
*
* Kept in a separate, factory-free module on purpose: the subscribe-injection
* transform (reachable from every orchestrion bundler plugin) reads this to
* generate the tiny snippet it injects into each instrumented file, and must
* not drag any subscriber code — or its `@sentry/core` span machinery — into
* the plugin's own build to do so.
*
* `exportName` must be a named export of `@sentry/server-utils/orchestrion`.
* `modules` must match `module.name` values in `SENTRY_INSTRUMENTATIONS` — e.g.
* `postgresChannelIntegration` covers both `pg` and `pg-pool`, and
* `redisChannelIntegration` both `redis` and `@redis/client`.
*
* `redis`, `ioredis` and `dataloader` are included even though they're not in
* the node SDK's `channelIntegrations` (they only partially replace an OTel
* integration there): in a bundler-only runtime like Cloudflare Workers there
* is no OTel integration to coordinate with, so subscribing whenever the
* package is bundled is unconditionally correct.
*/
export const CHANNEL_INTEGRATION_DEFINITIONS = [
{ exportName: 'postgresChannelIntegration', modules: ['pg', 'pg-pool'] },
{ exportName: 'postgresJsChannelIntegration', modules: ['postgres'] },
{ exportName: 'mysqlChannelIntegration', modules: ['mysql'] },
{ exportName: 'mysql2ChannelIntegration', modules: ['mysql2'] },
{ exportName: 'genericPoolChannelIntegration', modules: ['generic-pool'] },
{ exportName: 'lruMemoizerChannelIntegration', modules: ['lru-memoizer'] },
{ exportName: 'openaiChannelIntegration', modules: ['openai'] },
{ exportName: 'anthropicChannelIntegration', modules: ['@anthropic-ai/sdk'] },
{ exportName: 'googleGenAIChannelIntegration', modules: ['@google/genai'] },
{ exportName: 'vercelAiChannelIntegration', modules: ['ai'] },
{ exportName: 'amqplibChannelIntegration', modules: ['amqplib'] },
{ exportName: 'hapiChannelIntegration', modules: ['@hapi/hapi'] },
{ exportName: 'expressChannelIntegration', modules: ['express', 'router'] },
{ exportName: 'graphqlChannelIntegration', modules: ['graphql'] },
{ exportName: 'kafkajsChannelIntegration', modules: ['kafkajs'] },
{ exportName: 'redisChannelIntegration', modules: ['redis', '@redis/client'] },
{ exportName: 'ioredisChannelIntegration', modules: ['ioredis'] },
{ exportName: 'dataloaderChannelIntegration', modules: ['dataloader'] },
] as const satisfies ReadonlyArray<{ exportName: string; modules: readonly string[] }>;
Comment thread
JPeer264 marked this conversation as resolved.
Comment thread
sentry[bot] marked this conversation as resolved.

/** Look up the subscriber export name for an instrumented package, if any. */
export function subscriberExportForModule(moduleName: string): string | undefined {
return CHANNEL_INTEGRATION_DEFINITIONS.find(d => (d.modules as readonly string[]).includes(moduleName))?.exportName;
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/dataloader.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `dataloader` ships a single transpiled CommonJS `index.js`. Its class methods are emitted as
// `_proto.<name> = function <name>() {}` (named function *expressions*), so they match on
Expand DownExpand Up@@ -53,3 +54,5 @@ export const dataloaderChannels = {
DATALOADER_CLEAR: 'orchestrion:dataloader:clear',
DATALOADER_CLEAR_ALL: 'orchestrion:dataloader:clearAll',
} as const;

export const dataloaderSubscribeInjection = toSubscribeInjections(dataloaderConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/express.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const expressConfig = [
// Express funnels every middleware/route handler through a single method on
Expand DownExpand Up@@ -72,3 +73,5 @@ export const expressChannels = {
EXPRESS_REGISTER: 'orchestrion:express:register',
ROUTER_REGISTER: 'orchestrion:router:register',
} as const;

export const expressSubscribeInjection = toSubscribeInjections(expressConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/firebase.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// TODO: Stub for the `firebase` orchestrion integration (ports `FirebaseInstrumentation`).
export const firebaseConfig: InstrumentationConfig[] = [];

export const firebaseChannels = {} as const;

export const firebaseSubscribeInjection = toSubscribeInjections(firebaseConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/generic-pool.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// Two shapes of `acquire`, both publishing to the same `orchestrion:generic-pool:acquire` channel:
// - v3+: `class Pool { acquire(priority) }` returns a promise, so `kind: 'Auto'` resolves to `wrapPromise`.
Expand All@@ -21,3 +22,5 @@ export const genericPoolConfig = [
export const genericPoolChannels = {
GENERIC_POOL_ACQUIRE: 'orchestrion:generic-pool:acquire',
} as const;

export const genericPoolSubscribeInjection = toSubscribeInjections(genericPoolConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/google-genai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `@google/genai` ships one bundled file per module format and the matcher compares `filePath` exactly,
// so we list every file the `node` export condition resolves to across the supported range: `index.js`
Expand DownExpand Up@@ -38,3 +39,5 @@ export const googleGenAiChannels = {
GOOGLE_GENAI_EMBED_CONTENT: 'orchestrion:@google/genai:embed-content',
GOOGLE_GENAI_CHAT: 'orchestrion:@google/genai:chat',
} as const;

export const googleGenAiSubscribeInjection = toSubscribeInjections(googleGenAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/graphql.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `parse`/`validate`/`execute` are top-level named `function` declarations in graphql's compiled
// files, stable across the supported majors, so `functionName` matches. `execute` returns
Expand DownExpand Up@@ -26,3 +27,5 @@ export const graphqlChannels = {
GRAPHQL_VALIDATE: 'orchestrion:graphql:validate',
GRAPHQL_EXECUTE: 'orchestrion:graphql:execute',
} as const;

export const graphqlSubscribeInjection = toSubscribeInjections(graphqlConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/hapi.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const hapiConfig = [
// hapi's `route`/`ext` live on an anonymous class (`internals.Server = class {}`),
Expand All@@ -21,3 +22,5 @@ export const hapiChannels = {
HAPI_ROUTE: 'orchestrion:@hapi/hapi:route',
HAPI_EXT: 'orchestrion:@hapi/hapi:ext',
} as const;

export const hapiSubscribeInjection = toSubscribeInjections(hapiConfig);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/core/src/utils/worldwide.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@

/* eslint-disable @typescript-eslint/no-explicit-any */

import type { Integration } from '../types/integration';
import type { Carrier } from '../carrier';
import type { SdkSource } from './env';

Expand DownExpand Up@@ -63,6 +64,14 @@ export type InternalGlobal = {
runtime?: string[];
/** Empty array signifies bundler plugin ran */
bundler?: string[];
/**
* Channel-subscriber integration factories a bundler plugin's
* subscribe-injection stored here, keyed by export name (one per instrumented
* package actually bundled; the key dedupes packages split across several
* files). A bundler-only SDK (e.g. `@sentry/cloudflare`) reads these at
* `init()` and instantiates them.
*/
integrations?: Map<string, () => Integration>;
};
} & Carrier;

Expand Down
3 changes: 2 additions & 1 deletion packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,8 @@
"@apm-js-collab/code-transformer-bundler-plugins": "^0.7.1",
"@apm-js-collab/tracing-hooks": "^0.13.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"meriyah": "^6.1.4"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
31 changes: 29 additions & 2 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { InstrumentationConfig, CustomTransform } from '..';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import { subscribeInjectionOptions } from './subscribeInjection';
import type { CodeTransformerPluginOptions } from '@apm-js-collab/code-transformer-bundler-plugins/core';

export type PluginOptions = {
Expand All@@ -17,6 +18,26 @@ export type PluginOptions = {
* Defaults to `true`.
*/
shouldInjectDiagnostics?: boolean;
/**
* Inject a small marker-push into each instrumented module that imports only
* that package's channel-subscriber factory and pushes it onto
* `globalThis.__SENTRY_ORCHESTRION__.integrations`. A bundler-only SDK reads
* the marker at `init()` and instantiates the collected factories, so every
* transformed package's subscriber is wired up with no runtime module hook.
*
* Because each site imports a single named factory, it tree-shakes: a bundle
* carries subscriber code only for the packages actually transformed into it.
*
* This is what lets a bundler-only SDK (e.g. `@sentry/cloudflare`, which runs
* in workerd where requires can't be monkey-patched) record channel spans,
* but it is bundler-agnostic: any orchestrion bundler plugin can enable it.
* Leave it off for SDKs that wire the integrations up through a static import
* instead (e.g. `@sentry/node`'s `experimentalUseDiagnosticsChannelInjection()`),
* so the subscribers aren't registered twice.
*
* Defaults to `false`.
*/
injectChannelSubscribers?: boolean;
};

/**
Expand DownExpand Up@@ -53,8 +74,14 @@ export function externalizedModulesWarning(externalizedModules: string[]): strin
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): CodeTransformerPluginOptions {
const instrumentations = [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])];
const customTransforms = options.customTransforms;
const subscribeInjection = options.injectChannelSubscribers ? subscribeInjectionOptions() : undefined;

const instrumentations = [
...SENTRY_INSTRUMENTATIONS,
...(options.instrumentations || []),
...(subscribeInjection?.instrumentations || []),
];
const customTransforms = { ...options.customTransforms, ...subscribeInjection?.customTransforms };

if (options.shouldInjectDiagnostics === false) {
return {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
import type { CustomTransform } from '@apm-js-collab/code-transformer';
import { parse } from 'meriyah';
import { SUBSCRIBE_INJECTIONS } from '../config';
import { subscriberExportForModule } from '../config/channel-integration-definitions';
import { SUBSCRIBE_TRANSFORM_NAME } from '../config/subscribe-injection';
import type { PluginOptions } from './options';

// Tracks Program nodes we already injected into, so a package with several
// instrumented files (or several configs pointing at one file) is injected only
// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.
const injectedPrograms = new WeakSet<object>();

interface ProgramNode {
type: string;
body: Array<{ type: string; directive?: string }>;
}

/**
* Snippet injected into each instrumented module. It imports ONLY that package's
* channel-subscriber factory (plus the `registerOrchestrionChannelIntegration`
* helper) from `@sentry/server-utils/orchestrion`, and hands both to the helper,
* which stores the factory on the global marker and live-registers it on any
* existing client (see that helper for the load-order and dedup rationale).
*
* Importing the single named factory (rather than a central dispatch that pulls
* in every subscriber) is what makes this tree-shake: a bundle carries only the
* subscriber code for packages actually transformed into it. The same
* "only-active-when-bundled" property the runtime module hook gives unbundled
* Node, but without a hook (workerd can't monkey-patch requires). The helper is
* generic (references no factory), so importing it alongside doesn't pull siblings.
*/
function subscribeSnippet(exportName: string, esm: boolean): string {
const importStmt = esm
? `import { ${exportName}, registerOrchestrionChannelIntegration } from '@sentry/server-utils/orchestrion';`
: `const { ${exportName}, registerOrchestrionChannelIntegration } = require('@sentry/server-utils/orchestrion');`;

return `${importStmt}\nregisterOrchestrionChannelIntegration(${JSON.stringify(exportName)}, ${exportName});`;
}

/**
* The custom transform registered under {@link SUBSCRIBE_TRANSFORM_NAME}. It is
* invoked with the matched `Program` node and mutates it in place, splicing the
* marker-push snippet in after any `'use strict'` directive.
*
* `state` carries the matched config spread with `{ moduleType }`; the config's
* `channelName` carries the package name (see `toSubscribeInjections`), which
* maps to the subscriber's export name.
*/
const injectSubscribe: CustomTransform = (state, program) => {
const node = program as ProgramNode;
if (injectedPrograms.has(node)) {
return;
}

const { moduleType, channelName } = state as { moduleType?: string; channelName?: string };
const exportName = channelName ? subscriberExportForModule(channelName) : undefined;
if (!exportName) {
return;
}

injectedPrograms.add(node);

const statements = parse(subscribeSnippet(exportName, moduleType === 'esm'), {
module: moduleType === 'esm',
next: true,
}).body as ProgramNode['body'];

const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');
Comment thread
sentry[bot] marked this conversation as resolved.
node.body.splice(directiveIndex + 1, 0, ...statements);
Comment thread
sentry[bot] marked this conversation as resolved.
};

/**
* The `instrumentations` + `customTransforms` a bundler plugin passes to
* {@link orchestrionTransformOptions} to enable the marker-push subscribe
* injection used by bundler-only SDKs (e.g. `@sentry/cloudflare`).
*
* The `SUBSCRIBE_INJECTIONS` configs ride alongside the real channel-publishing
* configs, and `injectSubscribe` runs on each matched module, so every
* transformed package self-registers its subscriber on the global marker
* without a runtime module hook.
*/
export function subscribeInjectionOptions(): Pick<PluginOptions, 'instrumentations' | 'customTransforms'> {
return {
instrumentations: SUBSCRIBE_INJECTIONS,
customTransforms: { [SUBSCRIBE_TRANSFORM_NAME]: injectSubscribe },
};
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/amqplib.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `amqplib` splits its API across three files:
// - `lib/channel_model.js` holds `class Channel` (publish/consume/ack/nack/reject/…) and
Expand DownExpand Up@@ -87,3 +88,5 @@ export const amqplibChannels = {
AMQPLIB_NACK_ALL: 'orchestrion:amqplib:nackAll',
AMQPLIB_CONNECT: 'orchestrion:amqplib:connect',
} as const;

export const amqplibSubscribeInjection = toSubscribeInjections(amqplibConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/anthropic-ai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const anthropicAiConfig = [
// One entry each for CJS/ESM
Expand DownExpand Up@@ -38,3 +39,5 @@ export const anthropicAiChannels = {
ANTHROPIC_MODELS: 'orchestrion:@anthropic-ai/sdk:models',
ANTHROPIC_MESSAGES_STREAM: 'orchestrion:@anthropic-ai/sdk:messages-stream',
} as const;

export const anthropicAiSubscribeInjection = toSubscribeInjections(anthropicAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/aws-sdk.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { toSubscribeInjections } from './subscribe-injection';

// The AWS SDK (v3) routes every command through the smithy `Client.prototype.send` method. Which
// package hosts that `Client` class changed across versions, so we target all of them; only the one
Expand DownExpand Up@@ -32,3 +33,5 @@ export const awsSdkChannels = {
AWS_SMITHY_CLIENT_SEND: 'orchestrion:@smithy/smithy-client:send',
AWS_SDK_SMITHY_CLIENT_SEND: 'orchestrion:@aws-sdk/smithy-client:send',
} as const;

export const awsSdkSubscribeInjection = toSubscribeInjections(awsSdkConfig);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
/**
* Build-time metadata mapping each instrumented package (orchestrion
* `module.name`) to the channel-subscriber integration that consumes the
* channels injected into it — by the `exportName` it is published under from
* `@sentry/server-utils/orchestrion`.
*
* Kept in a separate, factory-free module on purpose: the subscribe-injection
* transform (reachable from every orchestrion bundler plugin) reads this to
* generate the tiny snippet it injects into each instrumented file, and must
* not drag any subscriber code — or its `@sentry/core` span machinery — into
* the plugin's own build to do so.
*
* `exportName` must be a named export of `@sentry/server-utils/orchestrion`.
* `modules` must match `module.name` values in `SENTRY_INSTRUMENTATIONS` — e.g.
* `postgresChannelIntegration` covers both `pg` and `pg-pool`, and
* `redisChannelIntegration` both `redis` and `@redis/client`.
*
* `redis`, `ioredis` and `dataloader` are included even though they're not in
* the node SDK's `channelIntegrations` (they only partially replace an OTel
* integration there): in a bundler-only runtime like Cloudflare Workers there
* is no OTel integration to coordinate with, so subscribing whenever the
* package is bundled is unconditionally correct.
*/
export const CHANNEL_INTEGRATION_DEFINITIONS = [
{ exportName: 'postgresChannelIntegration', modules: ['pg', 'pg-pool'] },
{ exportName: 'postgresJsChannelIntegration', modules: ['postgres'] },
{ exportName: 'mysqlChannelIntegration', modules: ['mysql'] },
{ exportName: 'mysql2ChannelIntegration', modules: ['mysql2'] },
{ exportName: 'genericPoolChannelIntegration', modules: ['generic-pool'] },
{ exportName: 'lruMemoizerChannelIntegration', modules: ['lru-memoizer'] },
{ exportName: 'openaiChannelIntegration', modules: ['openai'] },
{ exportName: 'anthropicChannelIntegration', modules: ['@anthropic-ai/sdk'] },
{ exportName: 'googleGenAIChannelIntegration', modules: ['@google/genai'] },
{ exportName: 'vercelAiChannelIntegration', modules: ['ai'] },
{ exportName: 'amqplibChannelIntegration', modules: ['amqplib'] },
{ exportName: 'hapiChannelIntegration', modules: ['@hapi/hapi'] },
{ exportName: 'expressChannelIntegration', modules: ['express', 'router'] },
{ exportName: 'graphqlChannelIntegration', modules: ['graphql'] },
{ exportName: 'kafkajsChannelIntegration', modules: ['kafkajs'] },
{ exportName: 'redisChannelIntegration', modules: ['redis', '@redis/client'] },
{ exportName: 'ioredisChannelIntegration', modules: ['ioredis'] },
{ exportName: 'dataloaderChannelIntegration', modules: ['dataloader'] },
] as const satisfies ReadonlyArray<{ exportName: string; modules: readonly string[] }>;
Comment thread
JPeer264 marked this conversation as resolved.
Comment thread
sentry[bot] marked this conversation as resolved.

/** Look up the subscriber export name for an instrumented package, if any. */
export function subscriberExportForModule(moduleName: string): string | undefined {
return CHANNEL_INTEGRATION_DEFINITIONS.find(d => (d.modules as readonly string[]).includes(moduleName))?.exportName;
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/dataloader.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `dataloader` ships a single transpiled CommonJS `index.js`. Its class methods are emitted as
// `_proto.<name> = function <name>() {}` (named function *expressions*), so they match on
Expand DownExpand Up@@ -53,3 +54,5 @@ export const dataloaderChannels = {
DATALOADER_CLEAR: 'orchestrion:dataloader:clear',
DATALOADER_CLEAR_ALL: 'orchestrion:dataloader:clearAll',
} as const;

export const dataloaderSubscribeInjection = toSubscribeInjections(dataloaderConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/express.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const expressConfig = [
// Express funnels every middleware/route handler through a single method on
Expand DownExpand Up@@ -72,3 +73,5 @@ export const expressChannels = {
EXPRESS_REGISTER: 'orchestrion:express:register',
ROUTER_REGISTER: 'orchestrion:router:register',
} as const;

export const expressSubscribeInjection = toSubscribeInjections(expressConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/firebase.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// TODO: Stub for the `firebase` orchestrion integration (ports `FirebaseInstrumentation`).
export const firebaseConfig: InstrumentationConfig[] = [];

export const firebaseChannels = {} as const;

export const firebaseSubscribeInjection = toSubscribeInjections(firebaseConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/generic-pool.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// Two shapes of `acquire`, both publishing to the same `orchestrion:generic-pool:acquire` channel:
// - v3+: `class Pool { acquire(priority) }` returns a promise, so `kind: 'Auto'` resolves to `wrapPromise`.
Expand All@@ -21,3 +22,5 @@ export const genericPoolConfig = [
export const genericPoolChannels = {
GENERIC_POOL_ACQUIRE: 'orchestrion:generic-pool:acquire',
} as const;

export const genericPoolSubscribeInjection = toSubscribeInjections(genericPoolConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/google-genai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `@google/genai` ships one bundled file per module format and the matcher compares `filePath` exactly,
// so we list every file the `node` export condition resolves to across the supported range: `index.js`
Expand DownExpand Up@@ -38,3 +39,5 @@ export const googleGenAiChannels = {
GOOGLE_GENAI_EMBED_CONTENT: 'orchestrion:@google/genai:embed-content',
GOOGLE_GENAI_CHAT: 'orchestrion:@google/genai:chat',
} as const;

export const googleGenAiSubscribeInjection = toSubscribeInjections(googleGenAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/graphql.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `parse`/`validate`/`execute` are top-level named `function` declarations in graphql's compiled
// files, stable across the supported majors, so `functionName` matches. `execute` returns
Expand DownExpand Up@@ -26,3 +27,5 @@ export const graphqlChannels = {
GRAPHQL_VALIDATE: 'orchestrion:graphql:validate',
GRAPHQL_EXECUTE: 'orchestrion:graphql:execute',
} as const;

export const graphqlSubscribeInjection = toSubscribeInjections(graphqlConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/hapi.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const hapiConfig = [
// hapi's `route`/`ext` live on an anonymous class (`internals.Server = class {}`),
Expand All@@ -21,3 +22,5 @@ export const hapiChannels = {
HAPI_ROUTE: 'orchestrion:@hapi/hapi:route',
HAPI_EXT: 'orchestrion:@hapi/hapi:ext',
} as const;

export const hapiSubscribeInjection = toSubscribeInjections(hapiConfig);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/core/src/utils/worldwide.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@

/* eslint-disable @typescript-eslint/no-explicit-any */

import type { Integration } from '../types/integration';
import type { Carrier } from '../carrier';
import type { SdkSource } from './env';

Expand DownExpand Up@@ -63,6 +64,14 @@ export type InternalGlobal = {
runtime?: string[];
/** Empty array signifies bundler plugin ran */
bundler?: string[];
/**
* Channel-subscriber integration factories a bundler plugin's
* subscribe-injection stored here, keyed by export name (one per instrumented
* package actually bundled; the key dedupes packages split across several
* files). A bundler-only SDK (e.g. `@sentry/cloudflare`) reads these at
* `init()` and instantiates them.
*/
integrations?: Map<string, () => Integration>;
};
} & Carrier;

Expand Down
3 changes: 2 additions & 1 deletion packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,8 @@
"@apm-js-collab/code-transformer-bundler-plugins": "^0.7.1",
"@apm-js-collab/tracing-hooks": "^0.13.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"meriyah": "^6.1.4"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
31 changes: 29 additions & 2 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { InstrumentationConfig, CustomTransform } from '..';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import { subscribeInjectionOptions } from './subscribeInjection';
import type { CodeTransformerPluginOptions } from '@apm-js-collab/code-transformer-bundler-plugins/core';

export type PluginOptions = {
Expand All@@ -17,6 +18,26 @@ export type PluginOptions = {
* Defaults to `true`.
*/
shouldInjectDiagnostics?: boolean;
/**
* Inject a small marker-push into each instrumented module that imports only
* that package's channel-subscriber factory and pushes it onto
* `globalThis.__SENTRY_ORCHESTRION__.integrations`. A bundler-only SDK reads
* the marker at `init()` and instantiates the collected factories, so every
* transformed package's subscriber is wired up with no runtime module hook.
*
* Because each site imports a single named factory, it tree-shakes: a bundle
* carries subscriber code only for the packages actually transformed into it.
*
* This is what lets a bundler-only SDK (e.g. `@sentry/cloudflare`, which runs
* in workerd where requires can't be monkey-patched) record channel spans,
* but it is bundler-agnostic: any orchestrion bundler plugin can enable it.
* Leave it off for SDKs that wire the integrations up through a static import
* instead (e.g. `@sentry/node`'s `experimentalUseDiagnosticsChannelInjection()`),
* so the subscribers aren't registered twice.
*
* Defaults to `false`.
*/
injectChannelSubscribers?: boolean;
};

/**
Expand DownExpand Up@@ -53,8 +74,14 @@ export function externalizedModulesWarning(externalizedModules: string[]): strin
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): CodeTransformerPluginOptions {
const instrumentations = [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])];
const customTransforms = options.customTransforms;
const subscribeInjection = options.injectChannelSubscribers ? subscribeInjectionOptions() : undefined;

const instrumentations = [
...SENTRY_INSTRUMENTATIONS,
...(options.instrumentations || []),
...(subscribeInjection?.instrumentations || []),
];
const customTransforms = { ...options.customTransforms, ...subscribeInjection?.customTransforms };

if (options.shouldInjectDiagnostics === false) {
return {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
import type { CustomTransform } from '@apm-js-collab/code-transformer';
import { parse } from 'meriyah';
import { SUBSCRIBE_INJECTIONS } from '../config';
import { subscriberExportForModule } from '../config/channel-integration-definitions';
import { SUBSCRIBE_TRANSFORM_NAME } from '../config/subscribe-injection';
import type { PluginOptions } from './options';

// Tracks Program nodes we already injected into, so a package with several
// instrumented files (or several configs pointing at one file) is injected only
// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.
const injectedPrograms = new WeakSet<object>();

interface ProgramNode {
type: string;
body: Array<{ type: string; directive?: string }>;
}

/**
* Snippet injected into each instrumented module. It imports ONLY that package's
* channel-subscriber factory (plus the `registerOrchestrionChannelIntegration`
* helper) from `@sentry/server-utils/orchestrion`, and hands both to the helper,
* which stores the factory on the global marker and live-registers it on any
* existing client (see that helper for the load-order and dedup rationale).
*
* Importing the single named factory (rather than a central dispatch that pulls
* in every subscriber) is what makes this tree-shake: a bundle carries only the
* subscriber code for packages actually transformed into it. The same
* "only-active-when-bundled" property the runtime module hook gives unbundled
* Node, but without a hook (workerd can't monkey-patch requires). The helper is
* generic (references no factory), so importing it alongside doesn't pull siblings.
*/
function subscribeSnippet(exportName: string, esm: boolean): string {
const importStmt = esm
? `import { ${exportName}, registerOrchestrionChannelIntegration } from '@sentry/server-utils/orchestrion';`
: `const { ${exportName}, registerOrchestrionChannelIntegration } = require('@sentry/server-utils/orchestrion');`;

return `${importStmt}\nregisterOrchestrionChannelIntegration(${JSON.stringify(exportName)}, ${exportName});`;
}

/**
* The custom transform registered under {@link SUBSCRIBE_TRANSFORM_NAME}. It is
* invoked with the matched `Program` node and mutates it in place, splicing the
* marker-push snippet in after any `'use strict'` directive.
*
* `state` carries the matched config spread with `{ moduleType }`; the config's
* `channelName` carries the package name (see `toSubscribeInjections`), which
* maps to the subscriber's export name.
*/
const injectSubscribe: CustomTransform = (state, program) => {
const node = program as ProgramNode;
if (injectedPrograms.has(node)) {
return;
}

const { moduleType, channelName } = state as { moduleType?: string; channelName?: string };
const exportName = channelName ? subscriberExportForModule(channelName) : undefined;
if (!exportName) {
return;
}

injectedPrograms.add(node);

const statements = parse(subscribeSnippet(exportName, moduleType === 'esm'), {
module: moduleType === 'esm',
next: true,
}).body as ProgramNode['body'];

const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');
Comment thread
sentry[bot] marked this conversation as resolved.
node.body.splice(directiveIndex + 1, 0, ...statements);
Comment thread
sentry[bot] marked this conversation as resolved.
};

/**
* The `instrumentations` + `customTransforms` a bundler plugin passes to
* {@link orchestrionTransformOptions} to enable the marker-push subscribe
* injection used by bundler-only SDKs (e.g. `@sentry/cloudflare`).
*
* The `SUBSCRIBE_INJECTIONS` configs ride alongside the real channel-publishing
* configs, and `injectSubscribe` runs on each matched module, so every
* transformed package self-registers its subscriber on the global marker
* without a runtime module hook.
*/
export function subscribeInjectionOptions(): Pick<PluginOptions, 'instrumentations' | 'customTransforms'> {
return {
instrumentations: SUBSCRIBE_INJECTIONS,
customTransforms: { [SUBSCRIBE_TRANSFORM_NAME]: injectSubscribe },
};
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/amqplib.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `amqplib` splits its API across three files:
// - `lib/channel_model.js` holds `class Channel` (publish/consume/ack/nack/reject/…) and
Expand DownExpand Up@@ -87,3 +88,5 @@ export const amqplibChannels = {
AMQPLIB_NACK_ALL: 'orchestrion:amqplib:nackAll',
AMQPLIB_CONNECT: 'orchestrion:amqplib:connect',
} as const;

export const amqplibSubscribeInjection = toSubscribeInjections(amqplibConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/anthropic-ai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const anthropicAiConfig = [
// One entry each for CJS/ESM
Expand DownExpand Up@@ -38,3 +39,5 @@ export const anthropicAiChannels = {
ANTHROPIC_MODELS: 'orchestrion:@anthropic-ai/sdk:models',
ANTHROPIC_MESSAGES_STREAM: 'orchestrion:@anthropic-ai/sdk:messages-stream',
} as const;

export const anthropicAiSubscribeInjection = toSubscribeInjections(anthropicAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/aws-sdk.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { toSubscribeInjections } from './subscribe-injection';

// The AWS SDK (v3) routes every command through the smithy `Client.prototype.send` method. Which
// package hosts that `Client` class changed across versions, so we target all of them; only the one
Expand DownExpand Up@@ -32,3 +33,5 @@ export const awsSdkChannels = {
AWS_SMITHY_CLIENT_SEND: 'orchestrion:@smithy/smithy-client:send',
AWS_SDK_SMITHY_CLIENT_SEND: 'orchestrion:@aws-sdk/smithy-client:send',
} as const;

export const awsSdkSubscribeInjection = toSubscribeInjections(awsSdkConfig);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
/**
* Build-time metadata mapping each instrumented package (orchestrion
* `module.name`) to the channel-subscriber integration that consumes the
* channels injected into it — by the `exportName` it is published under from
* `@sentry/server-utils/orchestrion`.
*
* Kept in a separate, factory-free module on purpose: the subscribe-injection
* transform (reachable from every orchestrion bundler plugin) reads this to
* generate the tiny snippet it injects into each instrumented file, and must
* not drag any subscriber code — or its `@sentry/core` span machinery — into
* the plugin's own build to do so.
*
* `exportName` must be a named export of `@sentry/server-utils/orchestrion`.
* `modules` must match `module.name` values in `SENTRY_INSTRUMENTATIONS` — e.g.
* `postgresChannelIntegration` covers both `pg` and `pg-pool`, and
* `redisChannelIntegration` both `redis` and `@redis/client`.
*
* `redis`, `ioredis` and `dataloader` are included even though they're not in
* the node SDK's `channelIntegrations` (they only partially replace an OTel
* integration there): in a bundler-only runtime like Cloudflare Workers there
* is no OTel integration to coordinate with, so subscribing whenever the
* package is bundled is unconditionally correct.
*/
export const CHANNEL_INTEGRATION_DEFINITIONS = [
{ exportName: 'postgresChannelIntegration', modules: ['pg', 'pg-pool'] },
{ exportName: 'postgresJsChannelIntegration', modules: ['postgres'] },
{ exportName: 'mysqlChannelIntegration', modules: ['mysql'] },
{ exportName: 'mysql2ChannelIntegration', modules: ['mysql2'] },
{ exportName: 'genericPoolChannelIntegration', modules: ['generic-pool'] },
{ exportName: 'lruMemoizerChannelIntegration', modules: ['lru-memoizer'] },
{ exportName: 'openaiChannelIntegration', modules: ['openai'] },
{ exportName: 'anthropicChannelIntegration', modules: ['@anthropic-ai/sdk'] },
{ exportName: 'googleGenAIChannelIntegration', modules: ['@google/genai'] },
{ exportName: 'vercelAiChannelIntegration', modules: ['ai'] },
{ exportName: 'amqplibChannelIntegration', modules: ['amqplib'] },
{ exportName: 'hapiChannelIntegration', modules: ['@hapi/hapi'] },
{ exportName: 'expressChannelIntegration', modules: ['express', 'router'] },
{ exportName: 'graphqlChannelIntegration', modules: ['graphql'] },
{ exportName: 'kafkajsChannelIntegration', modules: ['kafkajs'] },
{ exportName: 'redisChannelIntegration', modules: ['redis', '@redis/client'] },
{ exportName: 'ioredisChannelIntegration', modules: ['ioredis'] },
{ exportName: 'dataloaderChannelIntegration', modules: ['dataloader'] },
] as const satisfies ReadonlyArray<{ exportName: string; modules: readonly string[] }>;
Comment thread
JPeer264 marked this conversation as resolved.
Comment thread
sentry[bot] marked this conversation as resolved.

/** Look up the subscriber export name for an instrumented package, if any. */
export function subscriberExportForModule(moduleName: string): string | undefined {
return CHANNEL_INTEGRATION_DEFINITIONS.find(d => (d.modules as readonly string[]).includes(moduleName))?.exportName;
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/dataloader.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `dataloader` ships a single transpiled CommonJS `index.js`. Its class methods are emitted as
// `_proto.<name> = function <name>() {}` (named function *expressions*), so they match on
Expand DownExpand Up@@ -53,3 +54,5 @@ export const dataloaderChannels = {
DATALOADER_CLEAR: 'orchestrion:dataloader:clear',
DATALOADER_CLEAR_ALL: 'orchestrion:dataloader:clearAll',
} as const;

export const dataloaderSubscribeInjection = toSubscribeInjections(dataloaderConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/express.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const expressConfig = [
// Express funnels every middleware/route handler through a single method on
Expand DownExpand Up@@ -72,3 +73,5 @@ export const expressChannels = {
EXPRESS_REGISTER: 'orchestrion:express:register',
ROUTER_REGISTER: 'orchestrion:router:register',
} as const;

export const expressSubscribeInjection = toSubscribeInjections(expressConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/firebase.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// TODO: Stub for the `firebase` orchestrion integration (ports `FirebaseInstrumentation`).
export const firebaseConfig: InstrumentationConfig[] = [];

export const firebaseChannels = {} as const;

export const firebaseSubscribeInjection = toSubscribeInjections(firebaseConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/generic-pool.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// Two shapes of `acquire`, both publishing to the same `orchestrion:generic-pool:acquire` channel:
// - v3+: `class Pool { acquire(priority) }` returns a promise, so `kind: 'Auto'` resolves to `wrapPromise`.
Expand All@@ -21,3 +22,5 @@ export const genericPoolConfig = [
export const genericPoolChannels = {
GENERIC_POOL_ACQUIRE: 'orchestrion:generic-pool:acquire',
} as const;

export const genericPoolSubscribeInjection = toSubscribeInjections(genericPoolConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/google-genai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `@google/genai` ships one bundled file per module format and the matcher compares `filePath` exactly,
// so we list every file the `node` export condition resolves to across the supported range: `index.js`
Expand DownExpand Up@@ -38,3 +39,5 @@ export const googleGenAiChannels = {
GOOGLE_GENAI_EMBED_CONTENT: 'orchestrion:@google/genai:embed-content',
GOOGLE_GENAI_CHAT: 'orchestrion:@google/genai:chat',
} as const;

export const googleGenAiSubscribeInjection = toSubscribeInjections(googleGenAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/graphql.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `parse`/`validate`/`execute` are top-level named `function` declarations in graphql's compiled
// files, stable across the supported majors, so `functionName` matches. `execute` returns
Expand DownExpand Up@@ -26,3 +27,5 @@ export const graphqlChannels = {
GRAPHQL_VALIDATE: 'orchestrion:graphql:validate',
GRAPHQL_EXECUTE: 'orchestrion:graphql:execute',
} as const;

export const graphqlSubscribeInjection = toSubscribeInjections(graphqlConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/hapi.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const hapiConfig = [
// hapi's `route`/`ext` live on an anonymous class (`internals.Server = class {}`),
Expand All@@ -21,3 +22,5 @@ export const hapiChannels = {
HAPI_ROUTE: 'orchestrion:@hapi/hapi:route',
HAPI_EXT: 'orchestrion:@hapi/hapi:ext',
} as const;

export const hapiSubscribeInjection = toSubscribeInjections(hapiConfig);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/core/src/utils/worldwide.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@

/* eslint-disable @typescript-eslint/no-explicit-any */

import type { Integration } from '../types/integration';
import type { Carrier } from '../carrier';
import type { SdkSource } from './env';

Expand DownExpand Up@@ -63,6 +64,14 @@ export type InternalGlobal = {
runtime?: string[];
/** Empty array signifies bundler plugin ran */
bundler?: string[];
/**
* Channel-subscriber integration factories a bundler plugin's
* subscribe-injection stored here, keyed by export name (one per instrumented
* package actually bundled; the key dedupes packages split across several
* files). A bundler-only SDK (e.g. `@sentry/cloudflare`) reads these at
* `init()` and instantiates them.
*/
integrations?: Map<string, () => Integration>;
};
} & Carrier;

Expand Down
3 changes: 2 additions & 1 deletion packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,8 @@
"@apm-js-collab/code-transformer-bundler-plugins": "^0.7.1",
"@apm-js-collab/tracing-hooks": "^0.13.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"meriyah": "^6.1.4"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
31 changes: 29 additions & 2 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { InstrumentationConfig, CustomTransform } from '..';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import { subscribeInjectionOptions } from './subscribeInjection';
import type { CodeTransformerPluginOptions } from '@apm-js-collab/code-transformer-bundler-plugins/core';

export type PluginOptions = {
Expand All@@ -17,6 +18,26 @@ export type PluginOptions = {
* Defaults to `true`.
*/
shouldInjectDiagnostics?: boolean;
/**
* Inject a small marker-push into each instrumented module that imports only
* that package's channel-subscriber factory and pushes it onto
* `globalThis.__SENTRY_ORCHESTRION__.integrations`. A bundler-only SDK reads
* the marker at `init()` and instantiates the collected factories, so every
* transformed package's subscriber is wired up with no runtime module hook.
*
* Because each site imports a single named factory, it tree-shakes: a bundle
* carries subscriber code only for the packages actually transformed into it.
*
* This is what lets a bundler-only SDK (e.g. `@sentry/cloudflare`, which runs
* in workerd where requires can't be monkey-patched) record channel spans,
* but it is bundler-agnostic: any orchestrion bundler plugin can enable it.
* Leave it off for SDKs that wire the integrations up through a static import
* instead (e.g. `@sentry/node`'s `experimentalUseDiagnosticsChannelInjection()`),
* so the subscribers aren't registered twice.
*
* Defaults to `false`.
*/
injectChannelSubscribers?: boolean;
};

/**
Expand DownExpand Up@@ -53,8 +74,14 @@ export function externalizedModulesWarning(externalizedModules: string[]): strin
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): CodeTransformerPluginOptions {
const instrumentations = [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])];
const customTransforms = options.customTransforms;
const subscribeInjection = options.injectChannelSubscribers ? subscribeInjectionOptions() : undefined;

const instrumentations = [
...SENTRY_INSTRUMENTATIONS,
...(options.instrumentations || []),
...(subscribeInjection?.instrumentations || []),
];
const customTransforms = { ...options.customTransforms, ...subscribeInjection?.customTransforms };

if (options.shouldInjectDiagnostics === false) {
return {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
import type { CustomTransform } from '@apm-js-collab/code-transformer';
import { parse } from 'meriyah';
import { SUBSCRIBE_INJECTIONS } from '../config';
import { subscriberExportForModule } from '../config/channel-integration-definitions';
import { SUBSCRIBE_TRANSFORM_NAME } from '../config/subscribe-injection';
import type { PluginOptions } from './options';

// Tracks Program nodes we already injected into, so a package with several
// instrumented files (or several configs pointing at one file) is injected only
// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.
const injectedPrograms = new WeakSet<object>();

interface ProgramNode {
type: string;
body: Array<{ type: string; directive?: string }>;
}

/**
* Snippet injected into each instrumented module. It imports ONLY that package's
* channel-subscriber factory (plus the `registerOrchestrionChannelIntegration`
* helper) from `@sentry/server-utils/orchestrion`, and hands both to the helper,
* which stores the factory on the global marker and live-registers it on any
* existing client (see that helper for the load-order and dedup rationale).
*
* Importing the single named factory (rather than a central dispatch that pulls
* in every subscriber) is what makes this tree-shake: a bundle carries only the
* subscriber code for packages actually transformed into it. The same
* "only-active-when-bundled" property the runtime module hook gives unbundled
* Node, but without a hook (workerd can't monkey-patch requires). The helper is
* generic (references no factory), so importing it alongside doesn't pull siblings.
*/
function subscribeSnippet(exportName: string, esm: boolean): string {
const importStmt = esm
? `import { ${exportName}, registerOrchestrionChannelIntegration } from '@sentry/server-utils/orchestrion';`
: `const { ${exportName}, registerOrchestrionChannelIntegration } = require('@sentry/server-utils/orchestrion');`;

return `${importStmt}\nregisterOrchestrionChannelIntegration(${JSON.stringify(exportName)}, ${exportName});`;
}

/**
* The custom transform registered under {@link SUBSCRIBE_TRANSFORM_NAME}. It is
* invoked with the matched `Program` node and mutates it in place, splicing the
* marker-push snippet in after any `'use strict'` directive.
*
* `state` carries the matched config spread with `{ moduleType }`; the config's
* `channelName` carries the package name (see `toSubscribeInjections`), which
* maps to the subscriber's export name.
*/
const injectSubscribe: CustomTransform = (state, program) => {
const node = program as ProgramNode;
if (injectedPrograms.has(node)) {
return;
}

const { moduleType, channelName } = state as { moduleType?: string; channelName?: string };
const exportName = channelName ? subscriberExportForModule(channelName) : undefined;
if (!exportName) {
return;
}

injectedPrograms.add(node);

const statements = parse(subscribeSnippet(exportName, moduleType === 'esm'), {
module: moduleType === 'esm',
next: true,
}).body as ProgramNode['body'];

const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');
Comment thread
sentry[bot] marked this conversation as resolved.
node.body.splice(directiveIndex + 1, 0, ...statements);
Comment thread
sentry[bot] marked this conversation as resolved.
};

/**
* The `instrumentations` + `customTransforms` a bundler plugin passes to
* {@link orchestrionTransformOptions} to enable the marker-push subscribe
* injection used by bundler-only SDKs (e.g. `@sentry/cloudflare`).
*
* The `SUBSCRIBE_INJECTIONS` configs ride alongside the real channel-publishing
* configs, and `injectSubscribe` runs on each matched module, so every
* transformed package self-registers its subscriber on the global marker
* without a runtime module hook.
*/
export function subscribeInjectionOptions(): Pick<PluginOptions, 'instrumentations' | 'customTransforms'> {
return {
instrumentations: SUBSCRIBE_INJECTIONS,
customTransforms: { [SUBSCRIBE_TRANSFORM_NAME]: injectSubscribe },
};
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/amqplib.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `amqplib` splits its API across three files:
// - `lib/channel_model.js` holds `class Channel` (publish/consume/ack/nack/reject/…) and
Expand DownExpand Up@@ -87,3 +88,5 @@ export const amqplibChannels = {
AMQPLIB_NACK_ALL: 'orchestrion:amqplib:nackAll',
AMQPLIB_CONNECT: 'orchestrion:amqplib:connect',
} as const;

export const amqplibSubscribeInjection = toSubscribeInjections(amqplibConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/anthropic-ai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const anthropicAiConfig = [
// One entry each for CJS/ESM
Expand DownExpand Up@@ -38,3 +39,5 @@ export const anthropicAiChannels = {
ANTHROPIC_MODELS: 'orchestrion:@anthropic-ai/sdk:models',
ANTHROPIC_MESSAGES_STREAM: 'orchestrion:@anthropic-ai/sdk:messages-stream',
} as const;

export const anthropicAiSubscribeInjection = toSubscribeInjections(anthropicAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/aws-sdk.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { toSubscribeInjections } from './subscribe-injection';

// The AWS SDK (v3) routes every command through the smithy `Client.prototype.send` method. Which
// package hosts that `Client` class changed across versions, so we target all of them; only the one
Expand DownExpand Up@@ -32,3 +33,5 @@ export const awsSdkChannels = {
AWS_SMITHY_CLIENT_SEND: 'orchestrion:@smithy/smithy-client:send',
AWS_SDK_SMITHY_CLIENT_SEND: 'orchestrion:@aws-sdk/smithy-client:send',
} as const;

export const awsSdkSubscribeInjection = toSubscribeInjections(awsSdkConfig);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
/**
* Build-time metadata mapping each instrumented package (orchestrion
* `module.name`) to the channel-subscriber integration that consumes the
* channels injected into it — by the `exportName` it is published under from
* `@sentry/server-utils/orchestrion`.
*
* Kept in a separate, factory-free module on purpose: the subscribe-injection
* transform (reachable from every orchestrion bundler plugin) reads this to
* generate the tiny snippet it injects into each instrumented file, and must
* not drag any subscriber code — or its `@sentry/core` span machinery — into
* the plugin's own build to do so.
*
* `exportName` must be a named export of `@sentry/server-utils/orchestrion`.
* `modules` must match `module.name` values in `SENTRY_INSTRUMENTATIONS` — e.g.
* `postgresChannelIntegration` covers both `pg` and `pg-pool`, and
* `redisChannelIntegration` both `redis` and `@redis/client`.
*
* `redis`, `ioredis` and `dataloader` are included even though they're not in
* the node SDK's `channelIntegrations` (they only partially replace an OTel
* integration there): in a bundler-only runtime like Cloudflare Workers there
* is no OTel integration to coordinate with, so subscribing whenever the
* package is bundled is unconditionally correct.
*/
export const CHANNEL_INTEGRATION_DEFINITIONS = [
{ exportName: 'postgresChannelIntegration', modules: ['pg', 'pg-pool'] },
{ exportName: 'postgresJsChannelIntegration', modules: ['postgres'] },
{ exportName: 'mysqlChannelIntegration', modules: ['mysql'] },
{ exportName: 'mysql2ChannelIntegration', modules: ['mysql2'] },
{ exportName: 'genericPoolChannelIntegration', modules: ['generic-pool'] },
{ exportName: 'lruMemoizerChannelIntegration', modules: ['lru-memoizer'] },
{ exportName: 'openaiChannelIntegration', modules: ['openai'] },
{ exportName: 'anthropicChannelIntegration', modules: ['@anthropic-ai/sdk'] },
{ exportName: 'googleGenAIChannelIntegration', modules: ['@google/genai'] },
{ exportName: 'vercelAiChannelIntegration', modules: ['ai'] },
{ exportName: 'amqplibChannelIntegration', modules: ['amqplib'] },
{ exportName: 'hapiChannelIntegration', modules: ['@hapi/hapi'] },
{ exportName: 'expressChannelIntegration', modules: ['express', 'router'] },
{ exportName: 'graphqlChannelIntegration', modules: ['graphql'] },
{ exportName: 'kafkajsChannelIntegration', modules: ['kafkajs'] },
{ exportName: 'redisChannelIntegration', modules: ['redis', '@redis/client'] },
{ exportName: 'ioredisChannelIntegration', modules: ['ioredis'] },
{ exportName: 'dataloaderChannelIntegration', modules: ['dataloader'] },
] as const satisfies ReadonlyArray<{ exportName: string; modules: readonly string[] }>;
Comment thread
JPeer264 marked this conversation as resolved.
Comment thread
sentry[bot] marked this conversation as resolved.

/** Look up the subscriber export name for an instrumented package, if any. */
export function subscriberExportForModule(moduleName: string): string | undefined {
return CHANNEL_INTEGRATION_DEFINITIONS.find(d => (d.modules as readonly string[]).includes(moduleName))?.exportName;
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/dataloader.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `dataloader` ships a single transpiled CommonJS `index.js`. Its class methods are emitted as
// `_proto.<name> = function <name>() {}` (named function *expressions*), so they match on
Expand DownExpand Up@@ -53,3 +54,5 @@ export const dataloaderChannels = {
DATALOADER_CLEAR: 'orchestrion:dataloader:clear',
DATALOADER_CLEAR_ALL: 'orchestrion:dataloader:clearAll',
} as const;

export const dataloaderSubscribeInjection = toSubscribeInjections(dataloaderConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/express.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const expressConfig = [
// Express funnels every middleware/route handler through a single method on
Expand DownExpand Up@@ -72,3 +73,5 @@ export const expressChannels = {
EXPRESS_REGISTER: 'orchestrion:express:register',
ROUTER_REGISTER: 'orchestrion:router:register',
} as const;

export const expressSubscribeInjection = toSubscribeInjections(expressConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/firebase.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// TODO: Stub for the `firebase` orchestrion integration (ports `FirebaseInstrumentation`).
export const firebaseConfig: InstrumentationConfig[] = [];

export const firebaseChannels = {} as const;

export const firebaseSubscribeInjection = toSubscribeInjections(firebaseConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/generic-pool.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// Two shapes of `acquire`, both publishing to the same `orchestrion:generic-pool:acquire` channel:
// - v3+: `class Pool { acquire(priority) }` returns a promise, so `kind: 'Auto'` resolves to `wrapPromise`.
Expand All@@ -21,3 +22,5 @@ export const genericPoolConfig = [
export const genericPoolChannels = {
GENERIC_POOL_ACQUIRE: 'orchestrion:generic-pool:acquire',
} as const;

export const genericPoolSubscribeInjection = toSubscribeInjections(genericPoolConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/google-genai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `@google/genai` ships one bundled file per module format and the matcher compares `filePath` exactly,
// so we list every file the `node` export condition resolves to across the supported range: `index.js`
Expand DownExpand Up@@ -38,3 +39,5 @@ export const googleGenAiChannels = {
GOOGLE_GENAI_EMBED_CONTENT: 'orchestrion:@google/genai:embed-content',
GOOGLE_GENAI_CHAT: 'orchestrion:@google/genai:chat',
} as const;

export const googleGenAiSubscribeInjection = toSubscribeInjections(googleGenAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/graphql.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `parse`/`validate`/`execute` are top-level named `function` declarations in graphql's compiled
// files, stable across the supported majors, so `functionName` matches. `execute` returns
Expand DownExpand Up@@ -26,3 +27,5 @@ export const graphqlChannels = {
GRAPHQL_VALIDATE: 'orchestrion:graphql:validate',
GRAPHQL_EXECUTE: 'orchestrion:graphql:execute',
} as const;

export const graphqlSubscribeInjection = toSubscribeInjections(graphqlConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/hapi.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const hapiConfig = [
// hapi's `route`/`ext` live on an anonymous class (`internals.Server = class {}`),
Expand All@@ -21,3 +22,5 @@ export const hapiChannels = {
HAPI_ROUTE: 'orchestrion:@hapi/hapi:route',
HAPI_EXT: 'orchestrion:@hapi/hapi:ext',
} as const;

export const hapiSubscribeInjection = toSubscribeInjections(hapiConfig);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/core/src/utils/worldwide.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@

/* eslint-disable @typescript-eslint/no-explicit-any */

import type { Integration } from '../types/integration';
import type { Carrier } from '../carrier';
import type { SdkSource } from './env';

Expand DownExpand Up@@ -63,6 +64,14 @@ export type InternalGlobal = {
runtime?: string[];
/** Empty array signifies bundler plugin ran */
bundler?: string[];
/**
* Channel-subscriber integration factories a bundler plugin's
* subscribe-injection stored here, keyed by export name (one per instrumented
* package actually bundled; the key dedupes packages split across several
* files). A bundler-only SDK (e.g. `@sentry/cloudflare`) reads these at
* `init()` and instantiates them.
*/
integrations?: Map<string, () => Integration>;
};
} & Carrier;

Expand Down
3 changes: 2 additions & 1 deletion packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,8 @@
"@apm-js-collab/code-transformer-bundler-plugins": "^0.7.1",
"@apm-js-collab/tracing-hooks": "^0.13.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"meriyah": "^6.1.4"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
31 changes: 29 additions & 2 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { InstrumentationConfig, CustomTransform } from '..';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import { subscribeInjectionOptions } from './subscribeInjection';
import type { CodeTransformerPluginOptions } from '@apm-js-collab/code-transformer-bundler-plugins/core';

export type PluginOptions = {
Expand All@@ -17,6 +18,26 @@ export type PluginOptions = {
* Defaults to `true`.
*/
shouldInjectDiagnostics?: boolean;
/**
* Inject a small marker-push into each instrumented module that imports only
* that package's channel-subscriber factory and pushes it onto
* `globalThis.__SENTRY_ORCHESTRION__.integrations`. A bundler-only SDK reads
* the marker at `init()` and instantiates the collected factories, so every
* transformed package's subscriber is wired up with no runtime module hook.
*
* Because each site imports a single named factory, it tree-shakes: a bundle
* carries subscriber code only for the packages actually transformed into it.
*
* This is what lets a bundler-only SDK (e.g. `@sentry/cloudflare`, which runs
* in workerd where requires can't be monkey-patched) record channel spans,
* but it is bundler-agnostic: any orchestrion bundler plugin can enable it.
* Leave it off for SDKs that wire the integrations up through a static import
* instead (e.g. `@sentry/node`'s `experimentalUseDiagnosticsChannelInjection()`),
* so the subscribers aren't registered twice.
*
* Defaults to `false`.
*/
injectChannelSubscribers?: boolean;
};

/**
Expand DownExpand Up@@ -53,8 +74,14 @@ export function externalizedModulesWarning(externalizedModules: string[]): strin
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): CodeTransformerPluginOptions {
const instrumentations = [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])];
const customTransforms = options.customTransforms;
const subscribeInjection = options.injectChannelSubscribers ? subscribeInjectionOptions() : undefined;

const instrumentations = [
...SENTRY_INSTRUMENTATIONS,
...(options.instrumentations || []),
...(subscribeInjection?.instrumentations || []),
];
const customTransforms = { ...options.customTransforms, ...subscribeInjection?.customTransforms };

if (options.shouldInjectDiagnostics === false) {
return {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
import type { CustomTransform } from '@apm-js-collab/code-transformer';
import { parse } from 'meriyah';
import { SUBSCRIBE_INJECTIONS } from '../config';
import { subscriberExportForModule } from '../config/channel-integration-definitions';
import { SUBSCRIBE_TRANSFORM_NAME } from '../config/subscribe-injection';
import type { PluginOptions } from './options';

// Tracks Program nodes we already injected into, so a package with several
// instrumented files (or several configs pointing at one file) is injected only
// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.
const injectedPrograms = new WeakSet<object>();

interface ProgramNode {
type: string;
body: Array<{ type: string; directive?: string }>;
}

/**
* Snippet injected into each instrumented module. It imports ONLY that package's
* channel-subscriber factory (plus the `registerOrchestrionChannelIntegration`
* helper) from `@sentry/server-utils/orchestrion`, and hands both to the helper,
* which stores the factory on the global marker and live-registers it on any
* existing client (see that helper for the load-order and dedup rationale).
*
* Importing the single named factory (rather than a central dispatch that pulls
* in every subscriber) is what makes this tree-shake: a bundle carries only the
* subscriber code for packages actually transformed into it. The same
* "only-active-when-bundled" property the runtime module hook gives unbundled
* Node, but without a hook (workerd can't monkey-patch requires). The helper is
* generic (references no factory), so importing it alongside doesn't pull siblings.
*/
function subscribeSnippet(exportName: string, esm: boolean): string {
const importStmt = esm
? `import { ${exportName}, registerOrchestrionChannelIntegration } from '@sentry/server-utils/orchestrion';`
: `const { ${exportName}, registerOrchestrionChannelIntegration } = require('@sentry/server-utils/orchestrion');`;

return `${importStmt}\nregisterOrchestrionChannelIntegration(${JSON.stringify(exportName)}, ${exportName});`;
}

/**
* The custom transform registered under {@link SUBSCRIBE_TRANSFORM_NAME}. It is
* invoked with the matched `Program` node and mutates it in place, splicing the
* marker-push snippet in after any `'use strict'` directive.
*
* `state` carries the matched config spread with `{ moduleType }`; the config's
* `channelName` carries the package name (see `toSubscribeInjections`), which
* maps to the subscriber's export name.
*/
const injectSubscribe: CustomTransform = (state, program) => {
const node = program as ProgramNode;
if (injectedPrograms.has(node)) {
return;
}

const { moduleType, channelName } = state as { moduleType?: string; channelName?: string };
const exportName = channelName ? subscriberExportForModule(channelName) : undefined;
if (!exportName) {
return;
}

injectedPrograms.add(node);

const statements = parse(subscribeSnippet(exportName, moduleType === 'esm'), {
module: moduleType === 'esm',
next: true,
}).body as ProgramNode['body'];

const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');
Comment thread
sentry[bot] marked this conversation as resolved.
node.body.splice(directiveIndex + 1, 0, ...statements);
Comment thread
sentry[bot] marked this conversation as resolved.
};

/**
* The `instrumentations` + `customTransforms` a bundler plugin passes to
* {@link orchestrionTransformOptions} to enable the marker-push subscribe
* injection used by bundler-only SDKs (e.g. `@sentry/cloudflare`).
*
* The `SUBSCRIBE_INJECTIONS` configs ride alongside the real channel-publishing
* configs, and `injectSubscribe` runs on each matched module, so every
* transformed package self-registers its subscriber on the global marker
* without a runtime module hook.
*/
export function subscribeInjectionOptions(): Pick<PluginOptions, 'instrumentations' | 'customTransforms'> {
return {
instrumentations: SUBSCRIBE_INJECTIONS,
customTransforms: { [SUBSCRIBE_TRANSFORM_NAME]: injectSubscribe },
};
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/amqplib.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `amqplib` splits its API across three files:
// - `lib/channel_model.js` holds `class Channel` (publish/consume/ack/nack/reject/…) and
Expand DownExpand Up@@ -87,3 +88,5 @@ export const amqplibChannels = {
AMQPLIB_NACK_ALL: 'orchestrion:amqplib:nackAll',
AMQPLIB_CONNECT: 'orchestrion:amqplib:connect',
} as const;

export const amqplibSubscribeInjection = toSubscribeInjections(amqplibConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/anthropic-ai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const anthropicAiConfig = [
// One entry each for CJS/ESM
Expand DownExpand Up@@ -38,3 +39,5 @@ export const anthropicAiChannels = {
ANTHROPIC_MODELS: 'orchestrion:@anthropic-ai/sdk:models',
ANTHROPIC_MESSAGES_STREAM: 'orchestrion:@anthropic-ai/sdk:messages-stream',
} as const;

export const anthropicAiSubscribeInjection = toSubscribeInjections(anthropicAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/aws-sdk.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { toSubscribeInjections } from './subscribe-injection';

// The AWS SDK (v3) routes every command through the smithy `Client.prototype.send` method. Which
// package hosts that `Client` class changed across versions, so we target all of them; only the one
Expand DownExpand Up@@ -32,3 +33,5 @@ export const awsSdkChannels = {
AWS_SMITHY_CLIENT_SEND: 'orchestrion:@smithy/smithy-client:send',
AWS_SDK_SMITHY_CLIENT_SEND: 'orchestrion:@aws-sdk/smithy-client:send',
} as const;

export const awsSdkSubscribeInjection = toSubscribeInjections(awsSdkConfig);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
/**
* Build-time metadata mapping each instrumented package (orchestrion
* `module.name`) to the channel-subscriber integration that consumes the
* channels injected into it — by the `exportName` it is published under from
* `@sentry/server-utils/orchestrion`.
*
* Kept in a separate, factory-free module on purpose: the subscribe-injection
* transform (reachable from every orchestrion bundler plugin) reads this to
* generate the tiny snippet it injects into each instrumented file, and must
* not drag any subscriber code — or its `@sentry/core` span machinery — into
* the plugin's own build to do so.
*
* `exportName` must be a named export of `@sentry/server-utils/orchestrion`.
* `modules` must match `module.name` values in `SENTRY_INSTRUMENTATIONS` — e.g.
* `postgresChannelIntegration` covers both `pg` and `pg-pool`, and
* `redisChannelIntegration` both `redis` and `@redis/client`.
*
* `redis`, `ioredis` and `dataloader` are included even though they're not in
* the node SDK's `channelIntegrations` (they only partially replace an OTel
* integration there): in a bundler-only runtime like Cloudflare Workers there
* is no OTel integration to coordinate with, so subscribing whenever the
* package is bundled is unconditionally correct.
*/
export const CHANNEL_INTEGRATION_DEFINITIONS = [
{ exportName: 'postgresChannelIntegration', modules: ['pg', 'pg-pool'] },
{ exportName: 'postgresJsChannelIntegration', modules: ['postgres'] },
{ exportName: 'mysqlChannelIntegration', modules: ['mysql'] },
{ exportName: 'mysql2ChannelIntegration', modules: ['mysql2'] },
{ exportName: 'genericPoolChannelIntegration', modules: ['generic-pool'] },
{ exportName: 'lruMemoizerChannelIntegration', modules: ['lru-memoizer'] },
{ exportName: 'openaiChannelIntegration', modules: ['openai'] },
{ exportName: 'anthropicChannelIntegration', modules: ['@anthropic-ai/sdk'] },
{ exportName: 'googleGenAIChannelIntegration', modules: ['@google/genai'] },
{ exportName: 'vercelAiChannelIntegration', modules: ['ai'] },
{ exportName: 'amqplibChannelIntegration', modules: ['amqplib'] },
{ exportName: 'hapiChannelIntegration', modules: ['@hapi/hapi'] },
{ exportName: 'expressChannelIntegration', modules: ['express', 'router'] },
{ exportName: 'graphqlChannelIntegration', modules: ['graphql'] },
{ exportName: 'kafkajsChannelIntegration', modules: ['kafkajs'] },
{ exportName: 'redisChannelIntegration', modules: ['redis', '@redis/client'] },
{ exportName: 'ioredisChannelIntegration', modules: ['ioredis'] },
{ exportName: 'dataloaderChannelIntegration', modules: ['dataloader'] },
] as const satisfies ReadonlyArray<{ exportName: string; modules: readonly string[] }>;
Comment thread
JPeer264 marked this conversation as resolved.
Comment thread
sentry[bot] marked this conversation as resolved.

/** Look up the subscriber export name for an instrumented package, if any. */
export function subscriberExportForModule(moduleName: string): string | undefined {
return CHANNEL_INTEGRATION_DEFINITIONS.find(d => (d.modules as readonly string[]).includes(moduleName))?.exportName;
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/dataloader.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `dataloader` ships a single transpiled CommonJS `index.js`. Its class methods are emitted as
// `_proto.<name> = function <name>() {}` (named function *expressions*), so they match on
Expand DownExpand Up@@ -53,3 +54,5 @@ export const dataloaderChannels = {
DATALOADER_CLEAR: 'orchestrion:dataloader:clear',
DATALOADER_CLEAR_ALL: 'orchestrion:dataloader:clearAll',
} as const;

export const dataloaderSubscribeInjection = toSubscribeInjections(dataloaderConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/express.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const expressConfig = [
// Express funnels every middleware/route handler through a single method on
Expand DownExpand Up@@ -72,3 +73,5 @@ export const expressChannels = {
EXPRESS_REGISTER: 'orchestrion:express:register',
ROUTER_REGISTER: 'orchestrion:router:register',
} as const;

export const expressSubscribeInjection = toSubscribeInjections(expressConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/firebase.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// TODO: Stub for the `firebase` orchestrion integration (ports `FirebaseInstrumentation`).
export const firebaseConfig: InstrumentationConfig[] = [];

export const firebaseChannels = {} as const;

export const firebaseSubscribeInjection = toSubscribeInjections(firebaseConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/generic-pool.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// Two shapes of `acquire`, both publishing to the same `orchestrion:generic-pool:acquire` channel:
// - v3+: `class Pool { acquire(priority) }` returns a promise, so `kind: 'Auto'` resolves to `wrapPromise`.
Expand All@@ -21,3 +22,5 @@ export const genericPoolConfig = [
export const genericPoolChannels = {
GENERIC_POOL_ACQUIRE: 'orchestrion:generic-pool:acquire',
} as const;

export const genericPoolSubscribeInjection = toSubscribeInjections(genericPoolConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/google-genai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `@google/genai` ships one bundled file per module format and the matcher compares `filePath` exactly,
// so we list every file the `node` export condition resolves to across the supported range: `index.js`
Expand DownExpand Up@@ -38,3 +39,5 @@ export const googleGenAiChannels = {
GOOGLE_GENAI_EMBED_CONTENT: 'orchestrion:@google/genai:embed-content',
GOOGLE_GENAI_CHAT: 'orchestrion:@google/genai:chat',
} as const;

export const googleGenAiSubscribeInjection = toSubscribeInjections(googleGenAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/graphql.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `parse`/`validate`/`execute` are top-level named `function` declarations in graphql's compiled
// files, stable across the supported majors, so `functionName` matches. `execute` returns
Expand DownExpand Up@@ -26,3 +27,5 @@ export const graphqlChannels = {
GRAPHQL_VALIDATE: 'orchestrion:graphql:validate',
GRAPHQL_EXECUTE: 'orchestrion:graphql:execute',
} as const;

export const graphqlSubscribeInjection = toSubscribeInjections(graphqlConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/hapi.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const hapiConfig = [
// hapi's `route`/`ext` live on an anonymous class (`internals.Server = class {}`),
Expand All@@ -21,3 +22,5 @@ export const hapiChannels = {
HAPI_ROUTE: 'orchestrion:@hapi/hapi:route',
HAPI_EXT: 'orchestrion:@hapi/hapi:ext',
} as const;

export const hapiSubscribeInjection = toSubscribeInjections(hapiConfig);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/core/src/utils/worldwide.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@

/* eslint-disable @typescript-eslint/no-explicit-any */

import type { Integration } from '../types/integration';
import type { Carrier } from '../carrier';
import type { SdkSource } from './env';

Expand DownExpand Up@@ -63,6 +64,14 @@ export type InternalGlobal = {
runtime?: string[];
/** Empty array signifies bundler plugin ran */
bundler?: string[];
/**
* Channel-subscriber integration factories a bundler plugin's
* subscribe-injection stored here, keyed by export name (one per instrumented
* package actually bundled; the key dedupes packages split across several
* files). A bundler-only SDK (e.g. `@sentry/cloudflare`) reads these at
* `init()` and instantiates them.
*/
integrations?: Map<string, () => Integration>;
};
} & Carrier;

Expand Down
3 changes: 2 additions & 1 deletion packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,8 @@
"@apm-js-collab/code-transformer-bundler-plugins": "^0.7.1",
"@apm-js-collab/tracing-hooks": "^0.13.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"meriyah": "^6.1.4"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
31 changes: 29 additions & 2 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { InstrumentationConfig, CustomTransform } from '..';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import { subscribeInjectionOptions } from './subscribeInjection';
import type { CodeTransformerPluginOptions } from '@apm-js-collab/code-transformer-bundler-plugins/core';

export type PluginOptions = {
Expand All@@ -17,6 +18,26 @@ export type PluginOptions = {
* Defaults to `true`.
*/
shouldInjectDiagnostics?: boolean;
/**
* Inject a small marker-push into each instrumented module that imports only
* that package's channel-subscriber factory and pushes it onto
* `globalThis.__SENTRY_ORCHESTRION__.integrations`. A bundler-only SDK reads
* the marker at `init()` and instantiates the collected factories, so every
* transformed package's subscriber is wired up with no runtime module hook.
*
* Because each site imports a single named factory, it tree-shakes: a bundle
* carries subscriber code only for the packages actually transformed into it.
*
* This is what lets a bundler-only SDK (e.g. `@sentry/cloudflare`, which runs
* in workerd where requires can't be monkey-patched) record channel spans,
* but it is bundler-agnostic: any orchestrion bundler plugin can enable it.
* Leave it off for SDKs that wire the integrations up through a static import
* instead (e.g. `@sentry/node`'s `experimentalUseDiagnosticsChannelInjection()`),
* so the subscribers aren't registered twice.
*
* Defaults to `false`.
*/
injectChannelSubscribers?: boolean;
};

/**
Expand DownExpand Up@@ -53,8 +74,14 @@ export function externalizedModulesWarning(externalizedModules: string[]): strin
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): CodeTransformerPluginOptions {
const instrumentations = [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])];
const customTransforms = options.customTransforms;
const subscribeInjection = options.injectChannelSubscribers ? subscribeInjectionOptions() : undefined;

const instrumentations = [
...SENTRY_INSTRUMENTATIONS,
...(options.instrumentations || []),
...(subscribeInjection?.instrumentations || []),
];
const customTransforms = { ...options.customTransforms, ...subscribeInjection?.customTransforms };

if (options.shouldInjectDiagnostics === false) {
return {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
import type { CustomTransform } from '@apm-js-collab/code-transformer';
import { parse } from 'meriyah';
import { SUBSCRIBE_INJECTIONS } from '../config';
import { subscriberExportForModule } from '../config/channel-integration-definitions';
import { SUBSCRIBE_TRANSFORM_NAME } from '../config/subscribe-injection';
import type { PluginOptions } from './options';

// Tracks Program nodes we already injected into, so a package with several
// instrumented files (or several configs pointing at one file) is injected only
// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.
const injectedPrograms = new WeakSet<object>();

interface ProgramNode {
type: string;
body: Array<{ type: string; directive?: string }>;
}

/**
* Snippet injected into each instrumented module. It imports ONLY that package's
* channel-subscriber factory (plus the `registerOrchestrionChannelIntegration`
* helper) from `@sentry/server-utils/orchestrion`, and hands both to the helper,
* which stores the factory on the global marker and live-registers it on any
* existing client (see that helper for the load-order and dedup rationale).
*
* Importing the single named factory (rather than a central dispatch that pulls
* in every subscriber) is what makes this tree-shake: a bundle carries only the
* subscriber code for packages actually transformed into it. The same
* "only-active-when-bundled" property the runtime module hook gives unbundled
* Node, but without a hook (workerd can't monkey-patch requires). The helper is
* generic (references no factory), so importing it alongside doesn't pull siblings.
*/
function subscribeSnippet(exportName: string, esm: boolean): string {
const importStmt = esm
? `import { ${exportName}, registerOrchestrionChannelIntegration } from '@sentry/server-utils/orchestrion';`
: `const { ${exportName}, registerOrchestrionChannelIntegration } = require('@sentry/server-utils/orchestrion');`;

return `${importStmt}\nregisterOrchestrionChannelIntegration(${JSON.stringify(exportName)}, ${exportName});`;
}

/**
* The custom transform registered under {@link SUBSCRIBE_TRANSFORM_NAME}. It is
* invoked with the matched `Program` node and mutates it in place, splicing the
* marker-push snippet in after any `'use strict'` directive.
*
* `state` carries the matched config spread with `{ moduleType }`; the config's
* `channelName` carries the package name (see `toSubscribeInjections`), which
* maps to the subscriber's export name.
*/
const injectSubscribe: CustomTransform = (state, program) => {
const node = program as ProgramNode;
if (injectedPrograms.has(node)) {
return;
}

const { moduleType, channelName } = state as { moduleType?: string; channelName?: string };
const exportName = channelName ? subscriberExportForModule(channelName) : undefined;
if (!exportName) {
return;
}

injectedPrograms.add(node);

const statements = parse(subscribeSnippet(exportName, moduleType === 'esm'), {
module: moduleType === 'esm',
next: true,
}).body as ProgramNode['body'];

const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');
Comment thread
sentry[bot] marked this conversation as resolved.
node.body.splice(directiveIndex + 1, 0, ...statements);
Comment thread
sentry[bot] marked this conversation as resolved.
};

/**
* The `instrumentations` + `customTransforms` a bundler plugin passes to
* {@link orchestrionTransformOptions} to enable the marker-push subscribe
* injection used by bundler-only SDKs (e.g. `@sentry/cloudflare`).
*
* The `SUBSCRIBE_INJECTIONS` configs ride alongside the real channel-publishing
* configs, and `injectSubscribe` runs on each matched module, so every
* transformed package self-registers its subscriber on the global marker
* without a runtime module hook.
*/
export function subscribeInjectionOptions(): Pick<PluginOptions, 'instrumentations' | 'customTransforms'> {
return {
instrumentations: SUBSCRIBE_INJECTIONS,
customTransforms: { [SUBSCRIBE_TRANSFORM_NAME]: injectSubscribe },
};
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/amqplib.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `amqplib` splits its API across three files:
// - `lib/channel_model.js` holds `class Channel` (publish/consume/ack/nack/reject/…) and
Expand DownExpand Up@@ -87,3 +88,5 @@ export const amqplibChannels = {
AMQPLIB_NACK_ALL: 'orchestrion:amqplib:nackAll',
AMQPLIB_CONNECT: 'orchestrion:amqplib:connect',
} as const;

export const amqplibSubscribeInjection = toSubscribeInjections(amqplibConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/anthropic-ai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const anthropicAiConfig = [
// One entry each for CJS/ESM
Expand DownExpand Up@@ -38,3 +39,5 @@ export const anthropicAiChannels = {
ANTHROPIC_MODELS: 'orchestrion:@anthropic-ai/sdk:models',
ANTHROPIC_MESSAGES_STREAM: 'orchestrion:@anthropic-ai/sdk:messages-stream',
} as const;

export const anthropicAiSubscribeInjection = toSubscribeInjections(anthropicAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/aws-sdk.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { toSubscribeInjections } from './subscribe-injection';

// The AWS SDK (v3) routes every command through the smithy `Client.prototype.send` method. Which
// package hosts that `Client` class changed across versions, so we target all of them; only the one
Expand DownExpand Up@@ -32,3 +33,5 @@ export const awsSdkChannels = {
AWS_SMITHY_CLIENT_SEND: 'orchestrion:@smithy/smithy-client:send',
AWS_SDK_SMITHY_CLIENT_SEND: 'orchestrion:@aws-sdk/smithy-client:send',
} as const;

export const awsSdkSubscribeInjection = toSubscribeInjections(awsSdkConfig);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
/**
* Build-time metadata mapping each instrumented package (orchestrion
* `module.name`) to the channel-subscriber integration that consumes the
* channels injected into it — by the `exportName` it is published under from
* `@sentry/server-utils/orchestrion`.
*
* Kept in a separate, factory-free module on purpose: the subscribe-injection
* transform (reachable from every orchestrion bundler plugin) reads this to
* generate the tiny snippet it injects into each instrumented file, and must
* not drag any subscriber code — or its `@sentry/core` span machinery — into
* the plugin's own build to do so.
*
* `exportName` must be a named export of `@sentry/server-utils/orchestrion`.
* `modules` must match `module.name` values in `SENTRY_INSTRUMENTATIONS` — e.g.
* `postgresChannelIntegration` covers both `pg` and `pg-pool`, and
* `redisChannelIntegration` both `redis` and `@redis/client`.
*
* `redis`, `ioredis` and `dataloader` are included even though they're not in
* the node SDK's `channelIntegrations` (they only partially replace an OTel
* integration there): in a bundler-only runtime like Cloudflare Workers there
* is no OTel integration to coordinate with, so subscribing whenever the
* package is bundled is unconditionally correct.
*/
export const CHANNEL_INTEGRATION_DEFINITIONS = [
{ exportName: 'postgresChannelIntegration', modules: ['pg', 'pg-pool'] },
{ exportName: 'postgresJsChannelIntegration', modules: ['postgres'] },
{ exportName: 'mysqlChannelIntegration', modules: ['mysql'] },
{ exportName: 'mysql2ChannelIntegration', modules: ['mysql2'] },
{ exportName: 'genericPoolChannelIntegration', modules: ['generic-pool'] },
{ exportName: 'lruMemoizerChannelIntegration', modules: ['lru-memoizer'] },
{ exportName: 'openaiChannelIntegration', modules: ['openai'] },
{ exportName: 'anthropicChannelIntegration', modules: ['@anthropic-ai/sdk'] },
{ exportName: 'googleGenAIChannelIntegration', modules: ['@google/genai'] },
{ exportName: 'vercelAiChannelIntegration', modules: ['ai'] },
{ exportName: 'amqplibChannelIntegration', modules: ['amqplib'] },
{ exportName: 'hapiChannelIntegration', modules: ['@hapi/hapi'] },
{ exportName: 'expressChannelIntegration', modules: ['express', 'router'] },
{ exportName: 'graphqlChannelIntegration', modules: ['graphql'] },
{ exportName: 'kafkajsChannelIntegration', modules: ['kafkajs'] },
{ exportName: 'redisChannelIntegration', modules: ['redis', '@redis/client'] },
{ exportName: 'ioredisChannelIntegration', modules: ['ioredis'] },
{ exportName: 'dataloaderChannelIntegration', modules: ['dataloader'] },
] as const satisfies ReadonlyArray<{ exportName: string; modules: readonly string[] }>;
Comment thread
JPeer264 marked this conversation as resolved.
Comment thread
sentry[bot] marked this conversation as resolved.

/** Look up the subscriber export name for an instrumented package, if any. */
export function subscriberExportForModule(moduleName: string): string | undefined {
return CHANNEL_INTEGRATION_DEFINITIONS.find(d => (d.modules as readonly string[]).includes(moduleName))?.exportName;
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/dataloader.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `dataloader` ships a single transpiled CommonJS `index.js`. Its class methods are emitted as
// `_proto.<name> = function <name>() {}` (named function *expressions*), so they match on
Expand DownExpand Up@@ -53,3 +54,5 @@ export const dataloaderChannels = {
DATALOADER_CLEAR: 'orchestrion:dataloader:clear',
DATALOADER_CLEAR_ALL: 'orchestrion:dataloader:clearAll',
} as const;

export const dataloaderSubscribeInjection = toSubscribeInjections(dataloaderConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/express.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const expressConfig = [
// Express funnels every middleware/route handler through a single method on
Expand DownExpand Up@@ -72,3 +73,5 @@ export const expressChannels = {
EXPRESS_REGISTER: 'orchestrion:express:register',
ROUTER_REGISTER: 'orchestrion:router:register',
} as const;

export const expressSubscribeInjection = toSubscribeInjections(expressConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/firebase.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// TODO: Stub for the `firebase` orchestrion integration (ports `FirebaseInstrumentation`).
export const firebaseConfig: InstrumentationConfig[] = [];

export const firebaseChannels = {} as const;

export const firebaseSubscribeInjection = toSubscribeInjections(firebaseConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/generic-pool.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// Two shapes of `acquire`, both publishing to the same `orchestrion:generic-pool:acquire` channel:
// - v3+: `class Pool { acquire(priority) }` returns a promise, so `kind: 'Auto'` resolves to `wrapPromise`.
Expand All@@ -21,3 +22,5 @@ export const genericPoolConfig = [
export const genericPoolChannels = {
GENERIC_POOL_ACQUIRE: 'orchestrion:generic-pool:acquire',
} as const;

export const genericPoolSubscribeInjection = toSubscribeInjections(genericPoolConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/google-genai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `@google/genai` ships one bundled file per module format and the matcher compares `filePath` exactly,
// so we list every file the `node` export condition resolves to across the supported range: `index.js`
Expand DownExpand Up@@ -38,3 +39,5 @@ export const googleGenAiChannels = {
GOOGLE_GENAI_EMBED_CONTENT: 'orchestrion:@google/genai:embed-content',
GOOGLE_GENAI_CHAT: 'orchestrion:@google/genai:chat',
} as const;

export const googleGenAiSubscribeInjection = toSubscribeInjections(googleGenAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/graphql.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `parse`/`validate`/`execute` are top-level named `function` declarations in graphql's compiled
// files, stable across the supported majors, so `functionName` matches. `execute` returns
Expand DownExpand Up@@ -26,3 +27,5 @@ export const graphqlChannels = {
GRAPHQL_VALIDATE: 'orchestrion:graphql:validate',
GRAPHQL_EXECUTE: 'orchestrion:graphql:execute',
} as const;

export const graphqlSubscribeInjection = toSubscribeInjections(graphqlConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/hapi.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const hapiConfig = [
// hapi's `route`/`ext` live on an anonymous class (`internals.Server = class {}`),
Expand All@@ -21,3 +22,5 @@ export const hapiChannels = {
HAPI_ROUTE: 'orchestrion:@hapi/hapi:route',
HAPI_EXT: 'orchestrion:@hapi/hapi:ext',
} as const;

export const hapiSubscribeInjection = toSubscribeInjections(hapiConfig);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/core/src/utils/worldwide.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@

/* eslint-disable @typescript-eslint/no-explicit-any */

import type { Integration } from '../types/integration';
import type { Carrier } from '../carrier';
import type { SdkSource } from './env';

Expand DownExpand Up@@ -63,6 +64,14 @@ export type InternalGlobal = {
runtime?: string[];
/** Empty array signifies bundler plugin ran */
bundler?: string[];
/**
* Channel-subscriber integration factories a bundler plugin's
* subscribe-injection stored here, keyed by export name (one per instrumented
* package actually bundled; the key dedupes packages split across several
* files). A bundler-only SDK (e.g. `@sentry/cloudflare`) reads these at
* `init()` and instantiates them.
*/
integrations?: Map<string, () => Integration>;
};
} & Carrier;

Expand Down
3 changes: 2 additions & 1 deletion packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,8 @@
"@apm-js-collab/code-transformer-bundler-plugins": "^0.7.1",
"@apm-js-collab/tracing-hooks": "^0.13.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"meriyah": "^6.1.4"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
31 changes: 29 additions & 2 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { InstrumentationConfig, CustomTransform } from '..';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import { subscribeInjectionOptions } from './subscribeInjection';
import type { CodeTransformerPluginOptions } from '@apm-js-collab/code-transformer-bundler-plugins/core';

export type PluginOptions = {
Expand All@@ -17,6 +18,26 @@ export type PluginOptions = {
* Defaults to `true`.
*/
shouldInjectDiagnostics?: boolean;
/**
* Inject a small marker-push into each instrumented module that imports only
* that package's channel-subscriber factory and pushes it onto
* `globalThis.__SENTRY_ORCHESTRION__.integrations`. A bundler-only SDK reads
* the marker at `init()` and instantiates the collected factories, so every
* transformed package's subscriber is wired up with no runtime module hook.
*
* Because each site imports a single named factory, it tree-shakes: a bundle
* carries subscriber code only for the packages actually transformed into it.
*
* This is what lets a bundler-only SDK (e.g. `@sentry/cloudflare`, which runs
* in workerd where requires can't be monkey-patched) record channel spans,
* but it is bundler-agnostic: any orchestrion bundler plugin can enable it.
* Leave it off for SDKs that wire the integrations up through a static import
* instead (e.g. `@sentry/node`'s `experimentalUseDiagnosticsChannelInjection()`),
* so the subscribers aren't registered twice.
*
* Defaults to `false`.
*/
injectChannelSubscribers?: boolean;
};

/**
Expand DownExpand Up@@ -53,8 +74,14 @@ export function externalizedModulesWarning(externalizedModules: string[]): strin
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): CodeTransformerPluginOptions {
const instrumentations = [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])];
const customTransforms = options.customTransforms;
const subscribeInjection = options.injectChannelSubscribers ? subscribeInjectionOptions() : undefined;

const instrumentations = [
...SENTRY_INSTRUMENTATIONS,
...(options.instrumentations || []),
...(subscribeInjection?.instrumentations || []),
];
const customTransforms = { ...options.customTransforms, ...subscribeInjection?.customTransforms };

if (options.shouldInjectDiagnostics === false) {
return {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
import type { CustomTransform } from '@apm-js-collab/code-transformer';
import { parse } from 'meriyah';
import { SUBSCRIBE_INJECTIONS } from '../config';
import { subscriberExportForModule } from '../config/channel-integration-definitions';
import { SUBSCRIBE_TRANSFORM_NAME } from '../config/subscribe-injection';
import type { PluginOptions } from './options';

// Tracks Program nodes we already injected into, so a package with several
// instrumented files (or several configs pointing at one file) is injected only
// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.
const injectedPrograms = new WeakSet<object>();

interface ProgramNode {
type: string;
body: Array<{ type: string; directive?: string }>;
}

/**
* Snippet injected into each instrumented module. It imports ONLY that package's
* channel-subscriber factory (plus the `registerOrchestrionChannelIntegration`
* helper) from `@sentry/server-utils/orchestrion`, and hands both to the helper,
* which stores the factory on the global marker and live-registers it on any
* existing client (see that helper for the load-order and dedup rationale).
*
* Importing the single named factory (rather than a central dispatch that pulls
* in every subscriber) is what makes this tree-shake: a bundle carries only the
* subscriber code for packages actually transformed into it. The same
* "only-active-when-bundled" property the runtime module hook gives unbundled
* Node, but without a hook (workerd can't monkey-patch requires). The helper is
* generic (references no factory), so importing it alongside doesn't pull siblings.
*/
function subscribeSnippet(exportName: string, esm: boolean): string {
const importStmt = esm
? `import { ${exportName}, registerOrchestrionChannelIntegration } from '@sentry/server-utils/orchestrion';`
: `const { ${exportName}, registerOrchestrionChannelIntegration } = require('@sentry/server-utils/orchestrion');`;

return `${importStmt}\nregisterOrchestrionChannelIntegration(${JSON.stringify(exportName)}, ${exportName});`;
}

/**
* The custom transform registered under {@link SUBSCRIBE_TRANSFORM_NAME}. It is
* invoked with the matched `Program` node and mutates it in place, splicing the
* marker-push snippet in after any `'use strict'` directive.
*
* `state` carries the matched config spread with `{ moduleType }`; the config's
* `channelName` carries the package name (see `toSubscribeInjections`), which
* maps to the subscriber's export name.
*/
const injectSubscribe: CustomTransform = (state, program) => {
const node = program as ProgramNode;
if (injectedPrograms.has(node)) {
return;
}

const { moduleType, channelName } = state as { moduleType?: string; channelName?: string };
const exportName = channelName ? subscriberExportForModule(channelName) : undefined;
if (!exportName) {
return;
}

injectedPrograms.add(node);

const statements = parse(subscribeSnippet(exportName, moduleType === 'esm'), {
module: moduleType === 'esm',
next: true,
}).body as ProgramNode['body'];

const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');
Comment thread
sentry[bot] marked this conversation as resolved.
node.body.splice(directiveIndex + 1, 0, ...statements);
Comment thread
sentry[bot] marked this conversation as resolved.
};

/**
* The `instrumentations` + `customTransforms` a bundler plugin passes to
* {@link orchestrionTransformOptions} to enable the marker-push subscribe
* injection used by bundler-only SDKs (e.g. `@sentry/cloudflare`).
*
* The `SUBSCRIBE_INJECTIONS` configs ride alongside the real channel-publishing
* configs, and `injectSubscribe` runs on each matched module, so every
* transformed package self-registers its subscriber on the global marker
* without a runtime module hook.
*/
export function subscribeInjectionOptions(): Pick<PluginOptions, 'instrumentations' | 'customTransforms'> {
return {
instrumentations: SUBSCRIBE_INJECTIONS,
customTransforms: { [SUBSCRIBE_TRANSFORM_NAME]: injectSubscribe },
};
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/amqplib.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `amqplib` splits its API across three files:
// - `lib/channel_model.js` holds `class Channel` (publish/consume/ack/nack/reject/…) and
Expand DownExpand Up@@ -87,3 +88,5 @@ export const amqplibChannels = {
AMQPLIB_NACK_ALL: 'orchestrion:amqplib:nackAll',
AMQPLIB_CONNECT: 'orchestrion:amqplib:connect',
} as const;

export const amqplibSubscribeInjection = toSubscribeInjections(amqplibConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/anthropic-ai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const anthropicAiConfig = [
// One entry each for CJS/ESM
Expand DownExpand Up@@ -38,3 +39,5 @@ export const anthropicAiChannels = {
ANTHROPIC_MODELS: 'orchestrion:@anthropic-ai/sdk:models',
ANTHROPIC_MESSAGES_STREAM: 'orchestrion:@anthropic-ai/sdk:messages-stream',
} as const;

export const anthropicAiSubscribeInjection = toSubscribeInjections(anthropicAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/aws-sdk.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { toSubscribeInjections } from './subscribe-injection';

// The AWS SDK (v3) routes every command through the smithy `Client.prototype.send` method. Which
// package hosts that `Client` class changed across versions, so we target all of them; only the one
Expand DownExpand Up@@ -32,3 +33,5 @@ export const awsSdkChannels = {
AWS_SMITHY_CLIENT_SEND: 'orchestrion:@smithy/smithy-client:send',
AWS_SDK_SMITHY_CLIENT_SEND: 'orchestrion:@aws-sdk/smithy-client:send',
} as const;

export const awsSdkSubscribeInjection = toSubscribeInjections(awsSdkConfig);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
/**
* Build-time metadata mapping each instrumented package (orchestrion
* `module.name`) to the channel-subscriber integration that consumes the
* channels injected into it — by the `exportName` it is published under from
* `@sentry/server-utils/orchestrion`.
*
* Kept in a separate, factory-free module on purpose: the subscribe-injection
* transform (reachable from every orchestrion bundler plugin) reads this to
* generate the tiny snippet it injects into each instrumented file, and must
* not drag any subscriber code — or its `@sentry/core` span machinery — into
* the plugin's own build to do so.
*
* `exportName` must be a named export of `@sentry/server-utils/orchestrion`.
* `modules` must match `module.name` values in `SENTRY_INSTRUMENTATIONS` — e.g.
* `postgresChannelIntegration` covers both `pg` and `pg-pool`, and
* `redisChannelIntegration` both `redis` and `@redis/client`.
*
* `redis`, `ioredis` and `dataloader` are included even though they're not in
* the node SDK's `channelIntegrations` (they only partially replace an OTel
* integration there): in a bundler-only runtime like Cloudflare Workers there
* is no OTel integration to coordinate with, so subscribing whenever the
* package is bundled is unconditionally correct.
*/
export const CHANNEL_INTEGRATION_DEFINITIONS = [
{ exportName: 'postgresChannelIntegration', modules: ['pg', 'pg-pool'] },
{ exportName: 'postgresJsChannelIntegration', modules: ['postgres'] },
{ exportName: 'mysqlChannelIntegration', modules: ['mysql'] },
{ exportName: 'mysql2ChannelIntegration', modules: ['mysql2'] },
{ exportName: 'genericPoolChannelIntegration', modules: ['generic-pool'] },
{ exportName: 'lruMemoizerChannelIntegration', modules: ['lru-memoizer'] },
{ exportName: 'openaiChannelIntegration', modules: ['openai'] },
{ exportName: 'anthropicChannelIntegration', modules: ['@anthropic-ai/sdk'] },
{ exportName: 'googleGenAIChannelIntegration', modules: ['@google/genai'] },
{ exportName: 'vercelAiChannelIntegration', modules: ['ai'] },
{ exportName: 'amqplibChannelIntegration', modules: ['amqplib'] },
{ exportName: 'hapiChannelIntegration', modules: ['@hapi/hapi'] },
{ exportName: 'expressChannelIntegration', modules: ['express', 'router'] },
{ exportName: 'graphqlChannelIntegration', modules: ['graphql'] },
{ exportName: 'kafkajsChannelIntegration', modules: ['kafkajs'] },
{ exportName: 'redisChannelIntegration', modules: ['redis', '@redis/client'] },
{ exportName: 'ioredisChannelIntegration', modules: ['ioredis'] },
{ exportName: 'dataloaderChannelIntegration', modules: ['dataloader'] },
] as const satisfies ReadonlyArray<{ exportName: string; modules: readonly string[] }>;
Comment thread
JPeer264 marked this conversation as resolved.
Comment thread
sentry[bot] marked this conversation as resolved.

/** Look up the subscriber export name for an instrumented package, if any. */
export function subscriberExportForModule(moduleName: string): string | undefined {
return CHANNEL_INTEGRATION_DEFINITIONS.find(d => (d.modules as readonly string[]).includes(moduleName))?.exportName;
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/dataloader.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `dataloader` ships a single transpiled CommonJS `index.js`. Its class methods are emitted as
// `_proto.<name> = function <name>() {}` (named function *expressions*), so they match on
Expand DownExpand Up@@ -53,3 +54,5 @@ export const dataloaderChannels = {
DATALOADER_CLEAR: 'orchestrion:dataloader:clear',
DATALOADER_CLEAR_ALL: 'orchestrion:dataloader:clearAll',
} as const;

export const dataloaderSubscribeInjection = toSubscribeInjections(dataloaderConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/express.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const expressConfig = [
// Express funnels every middleware/route handler through a single method on
Expand DownExpand Up@@ -72,3 +73,5 @@ export const expressChannels = {
EXPRESS_REGISTER: 'orchestrion:express:register',
ROUTER_REGISTER: 'orchestrion:router:register',
} as const;

export const expressSubscribeInjection = toSubscribeInjections(expressConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/firebase.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// TODO: Stub for the `firebase` orchestrion integration (ports `FirebaseInstrumentation`).
export const firebaseConfig: InstrumentationConfig[] = [];

export const firebaseChannels = {} as const;

export const firebaseSubscribeInjection = toSubscribeInjections(firebaseConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/generic-pool.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// Two shapes of `acquire`, both publishing to the same `orchestrion:generic-pool:acquire` channel:
// - v3+: `class Pool { acquire(priority) }` returns a promise, so `kind: 'Auto'` resolves to `wrapPromise`.
Expand All@@ -21,3 +22,5 @@ export const genericPoolConfig = [
export const genericPoolChannels = {
GENERIC_POOL_ACQUIRE: 'orchestrion:generic-pool:acquire',
} as const;

export const genericPoolSubscribeInjection = toSubscribeInjections(genericPoolConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/google-genai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `@google/genai` ships one bundled file per module format and the matcher compares `filePath` exactly,
// so we list every file the `node` export condition resolves to across the supported range: `index.js`
Expand DownExpand Up@@ -38,3 +39,5 @@ export const googleGenAiChannels = {
GOOGLE_GENAI_EMBED_CONTENT: 'orchestrion:@google/genai:embed-content',
GOOGLE_GENAI_CHAT: 'orchestrion:@google/genai:chat',
} as const;

export const googleGenAiSubscribeInjection = toSubscribeInjections(googleGenAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/graphql.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `parse`/`validate`/`execute` are top-level named `function` declarations in graphql's compiled
// files, stable across the supported majors, so `functionName` matches. `execute` returns
Expand DownExpand Up@@ -26,3 +27,5 @@ export const graphqlChannels = {
GRAPHQL_VALIDATE: 'orchestrion:graphql:validate',
GRAPHQL_EXECUTE: 'orchestrion:graphql:execute',
} as const;

export const graphqlSubscribeInjection = toSubscribeInjections(graphqlConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/hapi.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const hapiConfig = [
// hapi's `route`/`ext` live on an anonymous class (`internals.Server = class {}`),
Expand All@@ -21,3 +22,5 @@ export const hapiChannels = {
HAPI_ROUTE: 'orchestrion:@hapi/hapi:route',
HAPI_EXT: 'orchestrion:@hapi/hapi:ext',
} as const;

export const hapiSubscribeInjection = toSubscribeInjections(hapiConfig);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/core/src/utils/worldwide.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,7 @@

/* eslint-disable @typescript-eslint/no-explicit-any */

import type { Integration } from '../types/integration';
import type { Carrier } from '../carrier';
import type { SdkSource } from './env';

Expand DownExpand Up@@ -63,6 +64,14 @@ export type InternalGlobal = {
runtime?: string[];
/** Empty array signifies bundler plugin ran */
bundler?: string[];
/**
* Channel-subscriber integration factories a bundler plugin's
* subscribe-injection stored here, keyed by export name (one per instrumented
* package actually bundled; the key dedupes packages split across several
* files). A bundler-only SDK (e.g. `@sentry/cloudflare`) reads these at
* `init()` and instantiates them.
*/
integrations?: Map<string, () => Integration>;
};
} & Carrier;

Expand Down
3 changes: 2 additions & 1 deletion packages/server-utils/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,7 +119,8 @@
"@apm-js-collab/code-transformer-bundler-plugins": "^0.7.1",
"@apm-js-collab/tracing-hooks": "^0.13.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.67.0"
"@sentry/core": "10.67.0",
"meriyah": "^6.1.4"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
31 changes: 29 additions & 2 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
import type { InstrumentationConfig, CustomTransform } from '..';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import { subscribeInjectionOptions } from './subscribeInjection';
import type { CodeTransformerPluginOptions } from '@apm-js-collab/code-transformer-bundler-plugins/core';

export type PluginOptions = {
Expand All@@ -17,6 +18,26 @@ export type PluginOptions = {
* Defaults to `true`.
*/
shouldInjectDiagnostics?: boolean;
/**
* Inject a small marker-push into each instrumented module that imports only
* that package's channel-subscriber factory and pushes it onto
* `globalThis.__SENTRY_ORCHESTRION__.integrations`. A bundler-only SDK reads
* the marker at `init()` and instantiates the collected factories, so every
* transformed package's subscriber is wired up with no runtime module hook.
*
* Because each site imports a single named factory, it tree-shakes: a bundle
* carries subscriber code only for the packages actually transformed into it.
*
* This is what lets a bundler-only SDK (e.g. `@sentry/cloudflare`, which runs
* in workerd where requires can't be monkey-patched) record channel spans,
* but it is bundler-agnostic: any orchestrion bundler plugin can enable it.
* Leave it off for SDKs that wire the integrations up through a static import
* instead (e.g. `@sentry/node`'s `experimentalUseDiagnosticsChannelInjection()`),
* so the subscribers aren't registered twice.
*
* Defaults to `false`.
*/
injectChannelSubscribers?: boolean;
};

/**
Expand DownExpand Up@@ -53,8 +74,14 @@ export function externalizedModulesWarning(externalizedModules: string[]): strin
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): CodeTransformerPluginOptions {
const instrumentations = [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])];
const customTransforms = options.customTransforms;
const subscribeInjection = options.injectChannelSubscribers ? subscribeInjectionOptions() : undefined;

const instrumentations = [
...SENTRY_INSTRUMENTATIONS,
...(options.instrumentations || []),
...(subscribeInjection?.instrumentations || []),
];
const customTransforms = { ...options.customTransforms, ...subscribeInjection?.customTransforms };

if (options.shouldInjectDiagnostics === false) {
return {
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
import type { CustomTransform } from '@apm-js-collab/code-transformer';
import { parse } from 'meriyah';
import { SUBSCRIBE_INJECTIONS } from '../config';
import { subscriberExportForModule } from '../config/channel-integration-definitions';
import { SUBSCRIBE_TRANSFORM_NAME } from '../config/subscribe-injection';
import type { PluginOptions } from './options';

// Tracks Program nodes we already injected into, so a package with several
// instrumented files (or several configs pointing at one file) is injected only
// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.
const injectedPrograms = new WeakSet<object>();

interface ProgramNode {
type: string;
body: Array<{ type: string; directive?: string }>;
}

/**
* Snippet injected into each instrumented module. It imports ONLY that package's
* channel-subscriber factory (plus the `registerOrchestrionChannelIntegration`
* helper) from `@sentry/server-utils/orchestrion`, and hands both to the helper,
* which stores the factory on the global marker and live-registers it on any
* existing client (see that helper for the load-order and dedup rationale).
*
* Importing the single named factory (rather than a central dispatch that pulls
* in every subscriber) is what makes this tree-shake: a bundle carries only the
* subscriber code for packages actually transformed into it. The same
* "only-active-when-bundled" property the runtime module hook gives unbundled
* Node, but without a hook (workerd can't monkey-patch requires). The helper is
* generic (references no factory), so importing it alongside doesn't pull siblings.
*/
function subscribeSnippet(exportName: string, esm: boolean): string {
const importStmt = esm
? `import { ${exportName}, registerOrchestrionChannelIntegration } from '@sentry/server-utils/orchestrion';`
: `const { ${exportName}, registerOrchestrionChannelIntegration } = require('@sentry/server-utils/orchestrion');`;

return `${importStmt}\nregisterOrchestrionChannelIntegration(${JSON.stringify(exportName)}, ${exportName});`;
}

/**
* The custom transform registered under {@link SUBSCRIBE_TRANSFORM_NAME}. It is
* invoked with the matched `Program` node and mutates it in place, splicing the
* marker-push snippet in after any `'use strict'` directive.
*
* `state` carries the matched config spread with `{ moduleType }`; the config's
* `channelName` carries the package name (see `toSubscribeInjections`), which
* maps to the subscriber's export name.
*/
const injectSubscribe: CustomTransform = (state, program) => {
const node = program as ProgramNode;
if (injectedPrograms.has(node)) {
return;
}

const { moduleType, channelName } = state as { moduleType?: string; channelName?: string };
const exportName = channelName ? subscriberExportForModule(channelName) : undefined;
if (!exportName) {
return;
}

injectedPrograms.add(node);

const statements = parse(subscribeSnippet(exportName, moduleType === 'esm'), {
module: moduleType === 'esm',
next: true,
}).body as ProgramNode['body'];

const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');
Comment thread
sentry[bot] marked this conversation as resolved.
node.body.splice(directiveIndex + 1, 0, ...statements);
Comment thread
sentry[bot] marked this conversation as resolved.
};

/**
* The `instrumentations` + `customTransforms` a bundler plugin passes to
* {@link orchestrionTransformOptions} to enable the marker-push subscribe
* injection used by bundler-only SDKs (e.g. `@sentry/cloudflare`).
*
* The `SUBSCRIBE_INJECTIONS` configs ride alongside the real channel-publishing
* configs, and `injectSubscribe` runs on each matched module, so every
* transformed package self-registers its subscriber on the global marker
* without a runtime module hook.
*/
export function subscribeInjectionOptions(): Pick<PluginOptions, 'instrumentations' | 'customTransforms'> {
return {
instrumentations: SUBSCRIBE_INJECTIONS,
customTransforms: { [SUBSCRIBE_TRANSFORM_NAME]: injectSubscribe },
};
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/amqplib.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `amqplib` splits its API across three files:
// - `lib/channel_model.js` holds `class Channel` (publish/consume/ack/nack/reject/…) and
Expand DownExpand Up@@ -87,3 +88,5 @@ export const amqplibChannels = {
AMQPLIB_NACK_ALL: 'orchestrion:amqplib:nackAll',
AMQPLIB_CONNECT: 'orchestrion:amqplib:connect',
} as const;

export const amqplibSubscribeInjection = toSubscribeInjections(amqplibConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/anthropic-ai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const anthropicAiConfig = [
// One entry each for CJS/ESM
Expand DownExpand Up@@ -38,3 +39,5 @@ export const anthropicAiChannels = {
ANTHROPIC_MODELS: 'orchestrion:@anthropic-ai/sdk:models',
ANTHROPIC_MESSAGES_STREAM: 'orchestrion:@anthropic-ai/sdk:messages-stream',
} as const;

export const anthropicAiSubscribeInjection = toSubscribeInjections(anthropicAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/aws-sdk.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { toSubscribeInjections } from './subscribe-injection';

// The AWS SDK (v3) routes every command through the smithy `Client.prototype.send` method. Which
// package hosts that `Client` class changed across versions, so we target all of them; only the one
Expand DownExpand Up@@ -32,3 +33,5 @@ export const awsSdkChannels = {
AWS_SMITHY_CLIENT_SEND: 'orchestrion:@smithy/smithy-client:send',
AWS_SDK_SMITHY_CLIENT_SEND: 'orchestrion:@aws-sdk/smithy-client:send',
} as const;

export const awsSdkSubscribeInjection = toSubscribeInjections(awsSdkConfig);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
/**
* Build-time metadata mapping each instrumented package (orchestrion
* `module.name`) to the channel-subscriber integration that consumes the
* channels injected into it — by the `exportName` it is published under from
* `@sentry/server-utils/orchestrion`.
*
* Kept in a separate, factory-free module on purpose: the subscribe-injection
* transform (reachable from every orchestrion bundler plugin) reads this to
* generate the tiny snippet it injects into each instrumented file, and must
* not drag any subscriber code — or its `@sentry/core` span machinery — into
* the plugin's own build to do so.
*
* `exportName` must be a named export of `@sentry/server-utils/orchestrion`.
* `modules` must match `module.name` values in `SENTRY_INSTRUMENTATIONS` — e.g.
* `postgresChannelIntegration` covers both `pg` and `pg-pool`, and
* `redisChannelIntegration` both `redis` and `@redis/client`.
*
* `redis`, `ioredis` and `dataloader` are included even though they're not in
* the node SDK's `channelIntegrations` (they only partially replace an OTel
* integration there): in a bundler-only runtime like Cloudflare Workers there
* is no OTel integration to coordinate with, so subscribing whenever the
* package is bundled is unconditionally correct.
*/
export const CHANNEL_INTEGRATION_DEFINITIONS = [
{ exportName: 'postgresChannelIntegration', modules: ['pg', 'pg-pool'] },
{ exportName: 'postgresJsChannelIntegration', modules: ['postgres'] },
{ exportName: 'mysqlChannelIntegration', modules: ['mysql'] },
{ exportName: 'mysql2ChannelIntegration', modules: ['mysql2'] },
{ exportName: 'genericPoolChannelIntegration', modules: ['generic-pool'] },
{ exportName: 'lruMemoizerChannelIntegration', modules: ['lru-memoizer'] },
{ exportName: 'openaiChannelIntegration', modules: ['openai'] },
{ exportName: 'anthropicChannelIntegration', modules: ['@anthropic-ai/sdk'] },
{ exportName: 'googleGenAIChannelIntegration', modules: ['@google/genai'] },
{ exportName: 'vercelAiChannelIntegration', modules: ['ai'] },
{ exportName: 'amqplibChannelIntegration', modules: ['amqplib'] },
{ exportName: 'hapiChannelIntegration', modules: ['@hapi/hapi'] },
{ exportName: 'expressChannelIntegration', modules: ['express', 'router'] },
{ exportName: 'graphqlChannelIntegration', modules: ['graphql'] },
{ exportName: 'kafkajsChannelIntegration', modules: ['kafkajs'] },
{ exportName: 'redisChannelIntegration', modules: ['redis', '@redis/client'] },
{ exportName: 'ioredisChannelIntegration', modules: ['ioredis'] },
{ exportName: 'dataloaderChannelIntegration', modules: ['dataloader'] },
] as const satisfies ReadonlyArray<{ exportName: string; modules: readonly string[] }>;
Comment thread
JPeer264 marked this conversation as resolved.
Comment thread
sentry[bot] marked this conversation as resolved.

/** Look up the subscriber export name for an instrumented package, if any. */
export function subscriberExportForModule(moduleName: string): string | undefined {
return CHANNEL_INTEGRATION_DEFINITIONS.find(d => (d.modules as readonly string[]).includes(moduleName))?.exportName;
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/dataloader.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `dataloader` ships a single transpiled CommonJS `index.js`. Its class methods are emitted as
// `_proto.<name> = function <name>() {}` (named function *expressions*), so they match on
Expand DownExpand Up@@ -53,3 +54,5 @@ export const dataloaderChannels = {
DATALOADER_CLEAR: 'orchestrion:dataloader:clear',
DATALOADER_CLEAR_ALL: 'orchestrion:dataloader:clearAll',
} as const;

export const dataloaderSubscribeInjection = toSubscribeInjections(dataloaderConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/express.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const expressConfig = [
// Express funnels every middleware/route handler through a single method on
Expand DownExpand Up@@ -72,3 +73,5 @@ export const expressChannels = {
EXPRESS_REGISTER: 'orchestrion:express:register',
ROUTER_REGISTER: 'orchestrion:router:register',
} as const;

export const expressSubscribeInjection = toSubscribeInjections(expressConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/firebase.ts
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// TODO: Stub for the `firebase` orchestrion integration (ports `FirebaseInstrumentation`).
export const firebaseConfig: InstrumentationConfig[] = [];

export const firebaseChannels = {} as const;

export const firebaseSubscribeInjection = toSubscribeInjections(firebaseConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/generic-pool.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// Two shapes of `acquire`, both publishing to the same `orchestrion:generic-pool:acquire` channel:
// - v3+: `class Pool { acquire(priority) }` returns a promise, so `kind: 'Auto'` resolves to `wrapPromise`.
Expand All@@ -21,3 +22,5 @@ export const genericPoolConfig = [
export const genericPoolChannels = {
GENERIC_POOL_ACQUIRE: 'orchestrion:generic-pool:acquire',
} as const;

export const genericPoolSubscribeInjection = toSubscribeInjections(genericPoolConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/google-genai.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `@google/genai` ships one bundled file per module format and the matcher compares `filePath` exactly,
// so we list every file the `node` export condition resolves to across the supported range: `index.js`
Expand DownExpand Up@@ -38,3 +39,5 @@ export const googleGenAiChannels = {
GOOGLE_GENAI_EMBED_CONTENT: 'orchestrion:@google/genai:embed-content',
GOOGLE_GENAI_CHAT: 'orchestrion:@google/genai:chat',
} as const;

export const googleGenAiSubscribeInjection = toSubscribeInjections(googleGenAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/graphql.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `parse`/`validate`/`execute` are top-level named `function` declarations in graphql's compiled
// files, stable across the supported majors, so `functionName` matches. `execute` returns
Expand DownExpand Up@@ -26,3 +27,5 @@ export const graphqlChannels = {
GRAPHQL_VALIDATE: 'orchestrion:graphql:validate',
GRAPHQL_EXECUTE: 'orchestrion:graphql:execute',
} as const;

export const graphqlSubscribeInjection = toSubscribeInjections(graphqlConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/hapi.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const hapiConfig = [
// hapi's `route`/`ext` live on an anonymous class (`internals.Server = class {}`),
Expand All@@ -21,3 +22,5 @@ export const hapiChannels = {
HAPI_ROUTE: 'orchestrion:@hapi/hapi:route',
HAPI_EXT: 'orchestrion:@hapi/hapi:ext',
} as const;

export const hapiSubscribeInjection = toSubscribeInjections(hapiConfig);
Loading
Loading