agentleFS
CloudflareKnown publishercloudflare/workerd/src/tests/events/eventsource/AGENTS.md

workerd / eventsource

AGENTS.md9.1k starsChanged 8 months agoApache-2.0View on GitHub

An informal specification of EventSource as implemented in workerd, derived from, and kept in lockstep with, the test suite in this directory. The tests are the normative artifact. Both the C++ implementation (src/workerd/api/eventsource.{h,c++}) and the TypeScript implementation (src/per_isolate/eventsource/eventsource.ts, behind the TS_EVENT_SOURCE autogate) are covered. The TypeScript class subclasses EventTarget through the seam in src/per_isolate/events/event-target-internals.ts and does its I/O through RequestIo (src/workerd/api/request-io.{h,c++}), so dispatch, fetch and request binding are shared; the divergences are in class shape, in event stream parsing, in…

Trending

More talk lately.about the whole repository

Dec 2025: 0 mentionsJan 2026: 3 mentionsFeb 2026: 0 mentionsMar 2026: 2 mentionsApr 2026: 3 mentionsMay 2026: 0 mentionsJun 2026: 0 mentionsJul 2026: 0 mentionsAug 2026: 6 mentionsSep 2026: 4 mentionsOct 2026: 4 mentionsNov 2026: 1 mention
Dec 2025Jun 2026Nov 2026
Mentions a month of the cloudflare/workerd repository that our weekly crawl found. There is no adoption data for this file yet.

Who's talking about cloudflare/workerd

The biggest 5 of 39 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 39

Talked about on GitHub, Bluesky, Hacker News and Stack Overflow (39 times).

On GitHub · 32

27 more on GitHub

On Hacker News · 2

On Stack Overflow · 1

The file

We split this AGENTS.md into the rules it gives an agent

1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every member is brand-checked and throws JSG's illegal-invocation TypeError for any other receiver.

    line 54

≈ “Common” is an estimate: at least 1 in 5 of the 40,246 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

EventSource

An informal specification of EventSource as implemented in workerd, derived from, and kept in lockstep with, the test suite in this directory. The tests are the normative artifact. Both the C++ implementation (src/workerd/api/eventsource.{h,c++}) and the TypeScript implementation (src/per_isolate/eventsource/eventsource.ts, behind the TS_EVENT_SOURCE autogate) are covered. The TypeScript class subclasses EventTarget through the seam in src/per_isolate/events/event-target-internals.ts and does its I/O through RequestIo (src/workerd/api/request-io.{h,c++}), so dispatch, fetch and request binding are shared; the divergences are in class shape, in event stream parsing, in the Last-Event-ID header, and in how reads are driven.

Interface

[Exposed=Worker]
interface EventSource : EventTarget {
  constructor(USVString url, optional EventSourceInit eventSourceInitDict = {});
  static EventSource from(ReadableStream stream);  // Workers extension

  readonly attribute USVString url;
  readonly attribute boolean withCredentials;  // always false

  const unsigned short CONNECTING = 0;
  const unsigned short OPEN = 1;
  const unsigned short CLOSED = 2;
  readonly attribute unsigned short readyState;

  attribute EventHandler onopen;
  attribute EventHandler onmessage;
  attribute EventHandler onerror;
  undefined close();
};

dictionary EventSourceInit {
  boolean withCredentials = false;  // a truthy value throws NotSupportedError
  Fetcher fetcher;                  // Workers extension
};
  • EventSource is always a global, with no compatibility flag.
  • An EventSource can only be created within a request: NotSupportedError, from the constructor and from() alike.
  • The URL must be absolute (SyntaxError); it is normalized as the URL parser does. Both arguments are converted, init's members in order, before anything is checked.
  • EventSource.from() takes a ReadableStream that is neither locked nor disturbed, needs no receiver, and returns an EventSource that is already OPEN, with url ''.
  • [Symbol.dispose] is a function of its own that calls close().
  • Every member is brand-checked and throws JSG's illegal-invocation TypeError for any other receiver. Members are enumerable, like every JSG member; names, lengths and constants' configurability follow spec_compliant_property_attributes.

Core semantics

  • Request: a GET through the init's fetcher, else the global fetch(), with Accept: text/event-stream, Cache-Control: no-cache, and Last-Event-ID on a reconnection that has one (whitespace trimmed in the TypeScript implementation, #16).
  • Response: a status other than 200, or a content type other than text/event-stream (parameters allowed), fails the EventSource for good with an AbortError. A redirect moves url and the messages' origin. A response without a body is retried once, as an end of the stream; a second in a row fails the EventSource. A rejected fetch() closes it without reconnecting.
  • Reconnection: the end of a connected EventSource's stream fires an 'error' (The server disconnected.) in CONNECTING and reconnects after the reconnection time, 2 seconds unless a retry field set it, clamped to 1 to 10 seconds. The end of an EventSource.from() stream closes it.
  • Parsing follows the HTML standard in the TypeScript implementation; the C++ parser departs from it in the cases of ledger #4 to #9. The stream is decoded as UTF-8 with replacement. A string chunk from a from() stream is read as its UTF-8 bytes, any buffer or view as its bytes; anything else fails the EventSource with the TypeError the streams implementation's byte reads throw.
  • Events: a trusted OpenEvent (whose class is not a global), trusted MessageEvents carrying lastEventId and the URL's origin (null for a from() source), and trusted ErrorEvents whose error says why. None bubbles or is cancelable.
  • Event handlers: onopen, onmessage and onerror are HTML event handler attributes, positioned at first assignment and kept across reassignment; any other on<type> property is called as EventTarget calls it.
  • close() is idempotent and fires nothing. Callbacks resumed by another request do nothing, and close() from another request throws.
  • Listener exceptions under spec_compliant_dispatch_exceptions: a throwing 'open' or 'message' listener's exception is reported, the remaining listeners run, then the EventSource errors out with it and the rest of the messages are dropped. A throwing 'error' listener's exception is only reported. Without the flag the first throwing 'message' listener ends the dispatch, unreported, and errors the EventSource out.
  • Lifetime: a pending read retains its EventSource; once the stream has ended, nothing does.
  • Prototype pollution: the TypeScript implementation reaches built-ins only through primordials. The C++ implementation calls no built-in either, except that reading the TypeScript streams, the native pump resolves a promise with another, which looks up Promise.prototype.then; pollution.js leaves that unpatched for the cpp-ts-streams cell.

Compatibility flags

Flag (enable date)SelectsUnflagged behavior tested by
set_tostring_tag (2024-09-26)[object EventSource] brandinglegacyToStringTag
spec_compliant_dispatch_exceptions (2026-09-15)reporting listener exceptionslegacyThrowingMessageListener
spec_compliant_property_attributes (dateless)accessor names; lengths; non-configurable constants; the global as an own propertythe main cells (the -opt-in cells enable it)
immutable_api_prototypes (dateless)C++ constructor's prototype non-writablethe main cells (the -opt-in cells enable it)
typescript_implemented_streams (experimental)the streams an EventSource readsthe main cells (the -ts-streams cells enable it)

The main cells pin the two dated flags on; the legacy cells pin them off by their disable names, so every cell keeps its @all-compat-flags variant. The main cells also pin nodejs_compat (node:assert, node:util), enable_weak_ref and rpc (for gc.js), and streams_enable_constructors.

Divergence ledger (C++ vs TypeScript)

#AreaC++TypeScriptPinned in
1Constructor static inheritancegetPrototypeOf(EventSource) === Function.prototype=== EventTargetprototypeChains
2Constructor's prototypewritable unless immutable_api_prototypesnever writableconstructorAttributes
3Calling the constructor without newJSG's TypeErrorthe language's TypeErrorconstructorRequiresNew
4Empty event fieldan event of type ''a 'message'emptyEventField
5BOM split across chunksnot strippedstrippedbomSplitAcrossChunks
6id field containing U+0000takenignoredidWithNullIsIgnored
7data field with an empty valuedispatches nothingdispatches empty dataformatFieldData
8CRLF split across chunksends two linesends onecrlfSplitAcrossChunks
9Last event ID across a reconnectionthe last id field parsedthe last dispatched event'sformatDataBeforeFinalEmptyLine
10A listener closes the EventSourcethe rest of the messages read with that one are dispatcheddroppedcloseFromAListener
11close() of a from() sourcegoes on reading the streamcancels itcloseCancelsAFromStream
12retry valueanything KJ parses as a uint32_t; larger values ignoredASCII digits only; any length, clampednot pinned: observable only through reconnection timing
13Message dispatchfrom a task per writefrom the reaction to each readnot pinned: no cheap observable. Both are held by a Durable Object's input gate: a native body's read resumes through IoContext::run(), and a JavaScript stream's chunks are enqueued under the input lock
14A from() source closed while a read is pendingretained until the read settlescollectable (its read is cancelled, #11)not pinned: the C++ side is a leak
15Collection after the last eventon the next major GCone major GC later: an event wrapped before dispatch keeps its target alive until it is sweptnot pinned: gc.js allows three collections
16Last-Event-ID with leading or trailing whitespacesent as parsedtrimmed, as Headers trims valueslastEventIdWhitespace

The C++ implementation also logs a from() stream's non-byte chunk error twice; the TypeScript one, once. Not in the ledger, as only the logs see it.

Assertion catalogue

ModuleAsserts
api-surface.jsstatic and prototype members, attributes, names and lengths; key order; prototype chains (#1); constructor attributes (#2); runtime class marks; toStringTag branding; dispose member; no own instance properties; the global
inspect.jsutil.inspect() of an EventSource and of EventSource.prototype
construction.jsnew required (#3); URL conversion and errors; absolute URLs; init, withCredentials and fetcher checks; conversion order; initial state; module scope refused
illegal-invocation.jsevery member brand-checked against every non-EventSource receiver
from.jsargument checks; locked and disturbed streams; no receiver; synchronous open; reading to the end; chunk kinds; string chunks; non-byte chunks
parser.jsdata joining; ignored lines; leading space; line endings; unterminated events; BOMs; UTF-8; named events; last event ID; #4 to #8; WPT format cases
request.jsrequest headers; a rejected fetch() closes
response.jsstatus; content type; redirects; responses without a body
reconnection.jsend of stream reconnects; Last-Event-ID; #16; #9; retry
event-shapes.jsOpenEvent, MessageEvent and ErrorEvent shapes
handlers.jsdefault null; positional ordering; on<type> for a named event
close.jsidempotent and silent; dispose, which ignores a patched close(); closing from a listener (#10); cancelling a from() stream (#11)
listener-exceptions.jsthrowing 'message', 'open' and 'error' listeners
context.jscross-request callbacks and close(), with and without handle_cross_request_promise_resolution; close during reconnection; same-request delivery
gc.jspending reads retain, ended streams release, for native and JavaScript sources and in a Durable Object
pollution.jsfrom() and connected delivery under patched built-ins
legacy-shape.js[object Object]
legacy-listener-exceptions.jsthe first throwing listener ends the dispatch, unreported
server.jsthe event streams connected EventSources fetch, through subrequest
context-worker.jscontext.js's fixture services
which-impl.jsthe cell's implementation and the flags the suite branches on
helpers.jsdescriptor attribute strings; streams; event waiting and recording

Web Platform Tests

src/wpt runs the eventsource WPTs, but most need a base URL to resolve relative URLs, which workerd lacks, or browser features (workers, CORS, credentials). The format cases are adapted here instead, through EventSource.from() or server.js: format-bom-2, format-data-before-final-empty-line, format-field-data, format-field-event-empty, format-field-parsing, format-leading-space, format-newlines and format-null-character.

Tests that live elsewhere (by design)

  • src/workerd/api/eventsource-test.c++: a unit test of the C++ implementation's native pump, removed with it.
  • eventSourceLegacyError in src/workerd/api/tests/legacy-dispatch-exceptions-test.js, which pins the legacy dispatch policy across several APIs at once.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.