Skip to content

fix(core): keep winston out of the published browser build by splitting the logger by platform - #813

Merged
kalenkevich merged 2 commits into
google:mainfrom
AmaadMartin:fix/core-logger-platform-split-winston-node
Sep 9, 2026
Merged

kalenkevich merged 2 commits into
google:mainfrom
AmaadMartin:fix/core-logger-platform-split-winston-node

Conversation

@AmaadMartin

Copy link
Copy Markdown
Collaborator

Link to Issue or Description of Change

  1. Link to an existing issue (if applicable):
    Part of: Web build leaks Node-only deps: the async_hooks shim is gated behind --bundle (never applied), and winston has no shim #611
    Related: Tracking: @google/adk cannot be bundled for the browser (5 build-level defects) #607, perf(core): make winston an optional peer, ~26 fewer packages on install #785

⚠️ Reviewer note — this is not #617. #617 proposed deleting winston and was correctly closed with "No, we need to keep winston!". This PR keeps winston. It stays a core dependency, it stays the logger on Node, and its implementation is moved byte-for-byte unchanged. The only thing that changes is that the browser build stops naming the package. Verification that winston is still the Node logger is in the Testing Plan below.


  1. Or, if no issue exists, describe the change:

Problem: core/src/utils/logger.ts imports winston, and the browser entry point reaches that module through common.ts (which re-exports LogLevel, getLogger, setLogLevel, setLogger). The published web build is transpile-only, so esbuild passes the specifier through unchanged. core/dist/web/utils/logger.js therefore ships import * as winston from "winston", which no browser bundler can resolve.

Solution: split the logger by platform.

  • utils/logger.ts now writes through console, so it works in both runtimes and names no package at all.
  • The winston implementation moves into the new utils/logger_node.ts, unchanged — the class body is byte-for-byte the one that was in logger.ts; only the class name differs (SimpleLogger → WinstonLogger).
  • core/src/index.ts (the Node entry point) installs it through the existing setLogger seam.

core/package.json is untouched: "winston": "^3.19.0" stays in dependencies.

An esbuild alias cannot solve this: esbuild rejects alias without bundle, and the published web build does not bundle. So the platform === 'browser' && bundle gate and the rest of core/build.js are left as they are.

Call-site change: load_artifacts_tool.ts and vertex_ai_search_tool.ts held const logger = getLogger() at module scope. installNodeLogger() runs after index.ts evaluates its re-exports, so those two modules would have captured the console logger for the process lifetime, out of reach of setLogLevel(). Both now log through the logger facade that the other importers already use. That is the only call-site change here.

Behaviour notes

  • Sub-path entry points get the console logger. @google/adk/a2a, @google/adk/tools/mcp, @google/adk/artifacts/gcs and @google/adk/telemetry/gcp deliberately do not evaluate the main barrel, so they do not run installNodeLogger(). A consumer importing only a sub-path on Node gets the console logger rather than winston. Both emit the same line — LEVEL: [ADK] <ISO timestamp> <message> — so the only observable difference is winston's ANSI colouring. I left this alone rather than sprinkling install calls across five modules, which would also let a late sub-path import clobber a user's setLogger(). Happy to wire the sub-paths up in a follow-up if you'd prefer them to match.
  • resetLogger() now installs the console logger on Node too. It is internal: it is not exported from index.ts, common.ts or index_web.ts, and only core's own tests call it.
  • A deep import of dist/esm/utils/logger.js would get the console logger, but the exports map does not expose that path.
  • dist/web still contains an emitted utils/logger_node.js, and it still names winston. It is an orphan — nothing in the dist/web graph imports it (measured below). Excluding it from the transpile-only build would hide the day a *_node.ts module does become reachable, so the build is left alone. Note it is technically fetchable via the ./dist/web/* export wildcard, but only by explicitly deep-importing a _node file.
  • logger.log(level, ...) on Node still throws inside winston, because it passes the numeric enum value as the level name. That is pre-existing behaviour, preserved here and pinned by logger_node_test.ts. The console logger emits normally.
  • The public API surface is unchanged. common.ts is untouched and no symbol is added or removed.

Testing Plan

Unit Tests:
[x] I have added or updated unit tests for my change.
[x] All unit tests pass locally.

vitest run --project unit:core — 233 files, 3456 tests, all passing.

The four files this PR touches: logger_test.ts, logger_node_test.ts, logger_node_wiring_test.ts, tool_logging_test.ts — 30 passed.

  • logger_test.ts gains the console SimpleLogger cases and a browser safety block. That block reads both sources: logger.ts must contain no import, and logger_node.ts must still import winston — so the first assertion cannot be satisfied by deleting the dependency, which is what makes this different from Fix: replace winston with a console logger in core to unbreak the web build #617 at the test level.
  • logger_node_test.ts (new) captures the Console transport output and checks the line format, the colorized level, level gating and argument joining.
  • logger_node_wiring_test.ts (new) imports @google/adk and asserts the entry point installed the winston logger.
  • tool_logging_test.ts (new) drives LoadArtifactsTool and VertexAiSearchTool against real in-memory session and artifact services, no mocks.

npm run lint, npm run format:check — clean. tsc --noEmit reports the same 4 pre-existing errors on this branch and on main (all Cannot find module '@google/adk-devtools', an unbuilt workspace package), with an identical breakdown.

Evidence 1 — winston leaves the browser graph

Bundling the browser entry point lists every bare specifier a browser bundler would have to resolve. Same command on main and on this branch:

npx esbuild ./src/index_web.ts --bundle --platform=browser --format=esm \
  --packages=external --outfile=/dev/null --metafile=/tmp/meta.json

Both reach 193 modules. The external lists are identical except for one entry:

externals
main @google-cloud/vertexai, @google/genai, @opentelemetry/api, adm-zip, google-auth-library, js-yaml, jsonpath-plus, lodash-es, node:async_hooks, node:buffer, node:crypto, node:dns/promises, node:fs/promises, node:net, node:os, node:path, uuid, **winston**, zod, zod-to-json-schema, zod/v4
this branch @google-cloud/vertexai, @google/genai, @opentelemetry/api, adm-zip, google-auth-library, js-yaml, jsonpath-plus, lodash-es, node:async_hooks, node:buffer, node:crypto, node:dns/promises, node:fs/promises, node:net, node:os, node:path, uuid, zod, zod-to-json-schema, zod/v4

winston is the single-variable difference. The remaining node: specifiers are the other half of #611 and are out of scope here.

Walking the published dist/web output after npm run build confirms the same on the shipped artifact:

modules reached from dist/web/index_web.js : 193
winston imported                           : False
logger_node reached                        : False

files under dist/web naming winston        : ['dist/web/utils/logger_node.js']
  ...of those, reachable from the entry    : NONE (orphan, not in the graph)

Evidence 2 — winston stays on Node

$ node -p "require('./core/package.json').dependencies.winston"
^3.19.0

$ grep -rln winston core/dist/esm core/dist/cjs
core/dist/esm/utils/logger_node.js
core/dist/cjs/utils/logger_node.js

$ grep -rn "from 'winston'" core/src
core/src/utils/logger_node.ts:17:import * as winston from 'winston';

The active logger on Node is still winston:

$ node --input-type=module -e "
  const {getLogger} = await import('./core/dist/esm/index.js');
  const n = await import('./core/dist/esm/utils/logger_node.js');
  console.log(getLogger().constructor.name, getLogger() instanceof n.WinstonLogger);
"
WinstonLogger true

And Node output is unchanged. The same script on main and on this branch, timestamps normalized, diff clean — including winston's ANSI colour codes:

^[[34mDEBUG^[[39m: [ADK] <ts> d
^[[32mINFO^[[39m:  [ADK] <ts> i
^[[33mWARN^[[39m:  [ADK] <ts> w
^[[31mERROR^[[39m: [ADK] <ts> e

dist/esm, dist/cjs and dist/web still mirror core/src file for file, as before.

Checklist

[x] I have read the CONTRIBUTING.md document.
[x] I have performed a self-review of my own code.
[x] I have commented my code, particularly in hard-to-understand areas.
[x] I have added tests that prove my fix is effective or that my feature works.
[x] New and existing unit tests pass locally with my changes.

`core/src/utils/logger.ts` imported `winston`, and the browser entry point
reaches that module through `common.ts`. The published web build is
transpile-only, so esbuild passes the specifier through unchanged and
`core/dist/web/utils/logger.js` shipped `import * as winston from "winston"`,
which no browser bundler can resolve.

Split the logger by platform instead. `utils/logger.ts` now writes through
`console`, so it works in both runtimes, and the winston implementation moves
unchanged into the new `utils/logger_node.ts`. The Node entry point installs it
through the existing `setLogger` seam.

winston stays a `core` dependency and stays the logger on Node: the class body
in `logger_node.ts` is byte-for-byte the one that was in `logger.ts`, so Node
output is unchanged down to the ANSI colour codes. Only the browser build stops
naming the package.

`load_artifacts_tool.ts` and `vertex_ai_search_tool.ts` held
`const logger = getLogger()` at module scope. `installNodeLogger()` runs after
`index.ts` evaluates its re-exports, so those two modules would have captured
the console logger for the process lifetime, out of reach of `setLogLevel()`.
Both now log through the `logger` facade that the other importers already use.

Part of: #611
Related: #607
@AmaadMartin AmaadMartin changed the title Fix: keep winston out of the published browser build by splitting the logger by platform fix(core): keep winston out of the published browser build by splitting the logger by platform Aug 25, 2026
Comment thread core/src/utils/logger.ts

this.logger.log(level.toString(), messages.join(' '));
const timestamp = new Date().toISOString();
const line = `${LogLevel[level]}: [ADK] ${timestamp} ${messages.join(' ')}`;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to support color as well

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in e353c41. The new BrowserLogger colours the level with a %c CSS directive, which browser dev consoles render (winston still colours the Node side with ANSI).

Comment thread core/src/utils/logger.ts

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it make sense to create BrowserLogger and installBrowserLogger util function in the same manner you did for Node env.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in e353c41. BrowserLogger and installBrowserLogger() now live in core/src/utils/logger_browser.ts, wired into index_web.ts — the same split as WinstonLogger / installNodeLogger on Node.

…entry

Mirror the Node logger split: a dedicated BrowserLogger class plus an
installBrowserLogger() wired into index_web.ts, in the same manner as
WinstonLogger / installNodeLogger. The browser logger colours the level
with a %c CSS directive, which browser dev consoles render.
@kalenkevich
kalenkevich merged commit c2c2ecb into google:main Sep 9, 2026
13 checks passed
@kalenkevich kalenkevich mentioned this pull request Sep 9, 2026
AmaadMartin pushed a commit that referenced this pull request Sep 10, 2026
… platform

Rebasing onto main brought in #813, which keeps winston out of the
browser build by splitting the logger into logger_node (winston) and
logger_browser (console). The browser entry installs logger_browser and
never imports winston, so this PR's winston->shim alias and
winston_shim.ts are dead code and are removed.

node_build_test now reads utils/logger_node.js, where winston lives after
the split, instead of utils/logger.js.
AmaadMartin added a commit that referenced this pull request Sep 10, 2026
* Fix: make dist/web parseable and free of the Node createRequire banner

Two defects in the browser build output, both invisible to the existing
suite because it runs against src rather than the built artifacts.

1. `models/apigee_llm.js` did not parse. The browser target named
   chrome58/safari11, which predate native async generators, so esbuild
   downlevelled `yield* super.generateContentAsync(...)` into an
   __asyncGenerator closure and emitted `super` inside it. Raising the
   target to chrome63/safari12 keeps async generators native. This was a
   hard blocker: LlmAgent -> models/registry -> apigee_llm, so no browser
   consumer could avoid it, and no bundler configuration can parse invalid
   syntax.

2. Every file in dist/web carried the Node `createRequire` banner, because
   the banner was gated on `format === 'esm'` and the web build is also
   ESM. 187 files imported `module`; none ever called require().

Bundling dist/web/agents/llm_agent.js for the browser goes from 86 errors
to 21, and dist/web/index_web.js from 346 to 198. The remainder is winston
and node:async_hooks, tracked separately.

Adds a regression test over the build output, which is currently unguarded.
Verified it fails without this change, reporting all 198 bannered files and
naming models/apigee_llm.js as unparseable.

Fixes #608
Fixes #609
Part of #607

* test: bundle and execute the compiled web output, not just parse it

Addresses review feedback asking for a test that loads compiled ADK and
checks it actually works.

Parsing is necessary but not sufficient: it would not catch output that
bundles and then throws on import, or a primitive that is broken once
compiled for the browser. This bundles entry points from dist/web with
--platform=browser and runs them — constructing a FunctionTool, checking
the declaration a model would receive, and executing it.

The entry-point list is short because most of dist/web still cannot be
bundled: the barrel pulls skills/loader (node:fs, node:path) and the
logger pulls winston. agents/llm_agent.js and runner/runner.js are the
two worth adding next and are one dependency away each.

Verified all three new tests fail against an unpatched build.

* Fix: make the whole web build bundle and run in a browser

Follows review feedback asking that the entire ADK TS web bundle be
tested, not a subset. Getting there needed the remaining two defects
fixed rather than deferred.

Bundle the web target always. esbuild rejects `alias` unless bundling,
so the existing node:async_hooks shim never reached published output --
`npm run build` does not pass --bundle. Bundling the web target makes
the alias mechanism work, and the emitted filename now follows the entry
so package.json's "browser" field still resolves.

Add a browser stand-in for winston. utils/logger.ts pulls winston into
every module that logs, and winston needs os/fs/util/zlib/http. The shim
implements only the surface logger.ts uses and writes to the console,
which is what a browser transport does.

Keep Node-only modules out of the web barrel. index.ts already holds the
Node-only exports and index_web.ts is common.ts alone, so common.ts is
meant to be the browser-safe surface -- but exports reaching node:fs,
node:dns, adm-zip, google-auth-library and @google-cloud/vertexai had
leaked into it. Those move to index.ts alongside the ones already there.
The set was derived by bundling all 199 source modules for the browser
and recording which reach a Node-only dependency, not chosen by hand.

core/dist/web/index_web.js now bundles for --platform=browser with zero
errors, down from 346. The bundle imports and drives the public API:
LlmAgent, ParallelAgent, SequentialAgent, LoopAgent, FunctionTool,
Runner, InMemorySessionService and BaseLlm are all present and working.

The Node public API is unchanged -- 206 exports from dist/esm/index.js
before and after, verified by diffing the resolved export lists.

Mutation check: reverting only the common.ts hunk makes the bundle step
fail with 173 unresolved Node imports, vitest exits 1 and reports the
file as failed.

* test: run ADK in a real headless browser, and ship a self-contained web bundle

Replaces the synthetic bundle test with the real thing, per review.

tests/integration/build_setup/web_app/ is a small chat page -- message
list, prompt input, send button -- that imports core/dist/web/index_web.js
directly, with no build step of its own. web_app_test.ts drives it in
headless Chromium with Playwright: types a message, clicks send, and
asserts the user message and the agent reply both render, then runs a
second turn on the same session. The model is a BaseLlm subclass
returning a canned response, matching the mock in the existing
build_setup fixtures. Page errors and console errors fail the test, so a
DOM or module-loading failure surfaces instead of passing silently.

Making that possible meant the web target had to become genuinely
self-contained. It was bundled but kept `packages: 'external'`, so the
output still imported '@google/genai', 'zod' and friends as bare
specifiers, which a browser cannot resolve. The web target now bundles
its dependencies; Node keeps packages external as before. 972 KB.

Splits the build-output tests as requested: web_build_test.ts covers
dist/web only, and the Node ESM/CJS assertions move to node_build_test.ts.
Drops the assertions that re-bundled dist/web inside the test -- the
shipped artifact is already a bundle, and the browser test now exercises
it directly.

Adds playwright-chromium and a CI step to install the browser.

* fix: drop the winston browser shim now that main splits the logger by platform

Rebasing onto main brought in #813, which keeps winston out of the
browser build by splitting the logger into logger_node (winston) and
logger_browser (console). The browser entry installs logger_browser and
never imports winston, so this PR's winston->shim alias and
winston_shim.ts are dead code and are removed.

node_build_test now reads utils/logger_node.js, where winston lives after
the split, instead of utils/logger.js.

---------

Co-authored-by: Amaad Martin <[email protected]>
prasanna8585 pushed a commit to prasanna8585/adk-js that referenced this pull request Nov 10, 2026
…ng the logger by platform (google#813)

* fix(core): keep winston out of the published browser build

`core/src/utils/logger.ts` imported `winston`, and the browser entry point
reaches that module through `common.ts`. The published web build is
transpile-only, so esbuild passes the specifier through unchanged and
`core/dist/web/utils/logger.js` shipped `import * as winston from "winston"`,
which no browser bundler can resolve.

Split the logger by platform instead. `utils/logger.ts` now writes through
`console`, so it works in both runtimes, and the winston implementation moves
unchanged into the new `utils/logger_node.ts`. The Node entry point installs it
through the existing `setLogger` seam.

winston stays a `core` dependency and stays the logger on Node: the class body
in `logger_node.ts` is byte-for-byte the one that was in `logger.ts`, so Node
output is unchanged down to the ANSI colour codes. Only the browser build stops
naming the package.

`load_artifacts_tool.ts` and `vertex_ai_search_tool.ts` held
`const logger = getLogger()` at module scope. `installNodeLogger()` runs after
`index.ts` evaluates its re-exports, so those two modules would have captured
the console logger for the process lifetime, out of reach of `setLogLevel()`.
Both now log through the `logger` facade that the other importers already use.

Part of: google#611
Related: google#607

* fix(core): add a colour-aware BrowserLogger installed by the browser entry

Mirror the Node logger split: a dedicated BrowserLogger class plus an
installBrowserLogger() wired into index_web.ts, in the same manner as
WinstonLogger / installNodeLogger. The browser logger colours the level
with a %c CSS directive, which browser dev consoles render.

---------

Co-authored-by: Amaad Martin <[email protected]>
prasanna8585 pushed a commit to prasanna8585/adk-js that referenced this pull request Nov 10, 2026
* Fix: make dist/web parseable and free of the Node createRequire banner

Two defects in the browser build output, both invisible to the existing
suite because it runs against src rather than the built artifacts.

1. `models/apigee_llm.js` did not parse. The browser target named
   chrome58/safari11, which predate native async generators, so esbuild
   downlevelled `yield* super.generateContentAsync(...)` into an
   __asyncGenerator closure and emitted `super` inside it. Raising the
   target to chrome63/safari12 keeps async generators native. This was a
   hard blocker: LlmAgent -> models/registry -> apigee_llm, so no browser
   consumer could avoid it, and no bundler configuration can parse invalid
   syntax.

2. Every file in dist/web carried the Node `createRequire` banner, because
   the banner was gated on `format === 'esm'` and the web build is also
   ESM. 187 files imported `module`; none ever called require().

Bundling dist/web/agents/llm_agent.js for the browser goes from 86 errors
to 21, and dist/web/index_web.js from 346 to 198. The remainder is winston
and node:async_hooks, tracked separately.

Adds a regression test over the build output, which is currently unguarded.
Verified it fails without this change, reporting all 198 bannered files and
naming models/apigee_llm.js as unparseable.

Fixes google#608
Fixes google#609
Part of google#607

* test: bundle and execute the compiled web output, not just parse it

Addresses review feedback asking for a test that loads compiled ADK and
checks it actually works.

Parsing is necessary but not sufficient: it would not catch output that
bundles and then throws on import, or a primitive that is broken once
compiled for the browser. This bundles entry points from dist/web with
--platform=browser and runs them — constructing a FunctionTool, checking
the declaration a model would receive, and executing it.

The entry-point list is short because most of dist/web still cannot be
bundled: the barrel pulls skills/loader (node:fs, node:path) and the
logger pulls winston. agents/llm_agent.js and runner/runner.js are the
two worth adding next and are one dependency away each.

Verified all three new tests fail against an unpatched build.

* Fix: make the whole web build bundle and run in a browser

Follows review feedback asking that the entire ADK TS web bundle be
tested, not a subset. Getting there needed the remaining two defects
fixed rather than deferred.

Bundle the web target always. esbuild rejects `alias` unless bundling,
so the existing node:async_hooks shim never reached published output --
`npm run build` does not pass --bundle. Bundling the web target makes
the alias mechanism work, and the emitted filename now follows the entry
so package.json's "browser" field still resolves.

Add a browser stand-in for winston. utils/logger.ts pulls winston into
every module that logs, and winston needs os/fs/util/zlib/http. The shim
implements only the surface logger.ts uses and writes to the console,
which is what a browser transport does.

Keep Node-only modules out of the web barrel. index.ts already holds the
Node-only exports and index_web.ts is common.ts alone, so common.ts is
meant to be the browser-safe surface -- but exports reaching node:fs,
node:dns, adm-zip, google-auth-library and @google-cloud/vertexai had
leaked into it. Those move to index.ts alongside the ones already there.
The set was derived by bundling all 199 source modules for the browser
and recording which reach a Node-only dependency, not chosen by hand.

core/dist/web/index_web.js now bundles for --platform=browser with zero
errors, down from 346. The bundle imports and drives the public API:
LlmAgent, ParallelAgent, SequentialAgent, LoopAgent, FunctionTool,
Runner, InMemorySessionService and BaseLlm are all present and working.

The Node public API is unchanged -- 206 exports from dist/esm/index.js
before and after, verified by diffing the resolved export lists.

Mutation check: reverting only the common.ts hunk makes the bundle step
fail with 173 unresolved Node imports, vitest exits 1 and reports the
file as failed.

* test: run ADK in a real headless browser, and ship a self-contained web bundle

Replaces the synthetic bundle test with the real thing, per review.

tests/integration/build_setup/web_app/ is a small chat page -- message
list, prompt input, send button -- that imports core/dist/web/index_web.js
directly, with no build step of its own. web_app_test.ts drives it in
headless Chromium with Playwright: types a message, clicks send, and
asserts the user message and the agent reply both render, then runs a
second turn on the same session. The model is a BaseLlm subclass
returning a canned response, matching the mock in the existing
build_setup fixtures. Page errors and console errors fail the test, so a
DOM or module-loading failure surfaces instead of passing silently.

Making that possible meant the web target had to become genuinely
self-contained. It was bundled but kept `packages: 'external'`, so the
output still imported '@google/genai', 'zod' and friends as bare
specifiers, which a browser cannot resolve. The web target now bundles
its dependencies; Node keeps packages external as before. 972 KB.

Splits the build-output tests as requested: web_build_test.ts covers
dist/web only, and the Node ESM/CJS assertions move to node_build_test.ts.
Drops the assertions that re-bundled dist/web inside the test -- the
shipped artifact is already a bundle, and the browser test now exercises
it directly.

Adds playwright-chromium and a CI step to install the browser.

* fix: drop the winston browser shim now that main splits the logger by platform

Rebasing onto main brought in google#813, which keeps winston out of the
browser build by splitting the logger into logger_node (winston) and
logger_browser (console). The browser entry installs logger_browser and
never imports winston, so this PR's winston->shim alias and
winston_shim.ts are dead code and are removed.

node_build_test now reads utils/logger_node.js, where winston lives after
the split, instead of utils/logger.js.

---------

Co-authored-by: Amaad Martin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants