@cadenya/widgets 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -15,7 +15,7 @@ export interface ClientOptions {
15
15
  * Defaults to 60000; a non-finite or <= 0 value disables the deadline.
16
16
  */
17
17
  timeout?: number;
18
- /** Headers sent with every request. */
18
+ /** Additional request headers. Browsers supply their own User-Agent by default. */
19
19
  defaultHeaders?: Record<string, string>;
20
20
  /** Custom fetch implementation. */
21
21
  fetch?: typeof fetch;
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAE7D,MAAM,WAAW,aAAa;IAC5B,4EAA4E;IAC5E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,+CAA+C;IAC/C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mEAAmE;IACnE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,uCAAuC;IACvC,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,mCAAmC;IACnC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,uDAAuD;IACvD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,QAAQ,CAAC,EAAE,QAAQ,CAAC;CACrB;AAED,qBAAa,cAAc;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,aAAa,EAAE,aAAa,CAAC;IAEtC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAa;gBAEzB,OAAO,GAAE,aAAkB;CAuBxC"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAE7D,MAAM,WAAW,aAAa;IAC5B,4EAA4E;IAC5E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,+CAA+C;IAC/C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mEAAmE;IACnE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mFAAmF;IACnF,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,mCAAmC;IACnC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,uDAAuD;IACvD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,QAAQ,CAAC,EAAE,QAAQ,CAAC;CACrB;AAED,qBAAa,cAAc;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,aAAa,EAAE,aAAa,CAAC;IAEtC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAa;gBAEzB,OAAO,GAAE,aAAkB;CAuBxC"}
package/dist/client.js CHANGED
@@ -18,7 +18,7 @@ export class CadenyaWidgets {
18
18
  authHeader: () => ({ Authorization: `Bearer ${apiKey}` }),
19
19
  maxRetries: options.maxRetries ?? 0,
20
20
  timeout: options.timeout,
21
- defaultHeaders: { 'User-Agent': 'cadenyawidgets-typescript/1.1.0 (api 1.0)', ...options.defaultHeaders },
21
+ defaultHeaders: { ...nodeUserAgent('cadenyawidgets-typescript/1.1.1 (api 1.0)'), ...options.defaultHeaders },
22
22
  fetch: options.fetch,
23
23
  logger: options.logger,
24
24
  logLevel: options.logLevel,
@@ -28,6 +28,13 @@ export class CadenyaWidgets {
28
28
  this.conversations = new Conversations(this._client);
29
29
  }
30
30
  }
31
+ // Browser-authored User-Agent headers require CORS permission. Only Node-compatible
32
+ // runtimes receive the SDK default; browsers and workers use their native header.
33
+ function nodeUserAgent(value) {
34
+ const nodeVersion = globalThis
35
+ .process?.versions?.node;
36
+ return nodeVersion ? { 'User-Agent': value } : {};
37
+ }
31
38
  function readEnv(name) {
32
39
  const env = globalThis
33
40
  .process?.env;
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,6CAA6C;AAE7C,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AA0B7D,MAAM,OAAO,cAAc;IAChB,MAAM,CAAS;IACf,aAAa,CAAgB;IAErB,OAAO,CAAa;IAErC,YAAY,UAAyB,EAAE;QACrC,sEAAsE;QACtE,+CAA+C;QAC/C,MAAM,MAAM,GAAG,aAAa,CAAC,QAAQ,EAAE,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,wBAAwB,CAAC,CAAC,CAAC;QAC1F,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,IAAI,KAAK,CACb,wHAAwH,CACzH,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,OAAO,GAAG,IAAI,UAAU,CAAC;YAC5B,OAAO,EAAE,aAAa,CAAC,SAAS,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,yBAAyB,CAAC,CAAC,IAAI,EAAE;YAC5F,UAAU,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,aAAa,EAAE,UAAU,MAAM,EAAE,EAAE,CAAC;YACzD,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,CAAC;YACnC,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,cAAc,EAAE,EAAE,YAAY,EAAE,2CAA2C,EAAE,GAAG,OAAO,CAAC,cAAc,EAAE;YACxG,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,QAAQ,EAAE,EAAI;SACf,CAAC,CAAC;QACH,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACvC,IAAI,CAAC,aAAa,GAAG,IAAI,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACvD,CAAC;CACF;AAED,SAAS,OAAO,CAAC,IAAY;IAC3B,MAAM,GAAG,GAAI,UAAyE;SACnF,OAAO,EAAE,GAAG,CAAC;IAChB,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;AACrB,CAAC;AAED,2EAA2E;AAC3E,4EAA4E;AAC5E,sEAAsE;AACtE,SAAS,aAAa,CACpB,KAAa,EACb,QAA4B,EAC5B,GAAuB;IAEvB,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,KAAK,CACb,GAAG,KAAK,sFAAsF,CAC/F,CAAC;QACJ,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,GAAG,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;AAClC,CAAC","sourcesContent":["// Generated by redwood. Do not edit by hand.\n\nimport { HttpClient } from './core/http.js';\nimport type { Logger, LogLevel } from './core/http.js';\nimport { Config } from './resources/config.js';\nimport { Conversations } from './resources/conversations.js';\n\nexport interface ClientOptions {\n /** API key. Defaults to the CADENYAWIDGETS_API_KEY environment variable. */\n apiKey?: string;\n /** Override the API base URL. Defaults to . */\n baseURL?: string;\n /** Max automatic retries for retryable failures. Defaults to 0. */\n maxRetries?: number;\n /**\n * Deadline for ordinary (non-streaming) requests in milliseconds; override\n * per request with `options.timeout`. Streams bound only response-header\n * acquisition — body lifetime stays under the caller's AbortSignal.\n * Defaults to 60000; a non-finite or <= 0 value disables the deadline.\n */\n timeout?: number;\n /** Headers sent with every request. */\n defaultHeaders?: Record<string, string>;\n /** Custom fetch implementation. */\n fetch?: typeof fetch;\n /** Destination for SDK logs. Defaults to `console`. */\n logger?: Logger;\n /** 'debug' | 'warn' (default) | 'off'. Never logs headers or bodies. */\n logLevel?: LogLevel;\n}\n\nexport class CadenyaWidgets {\n readonly config: Config;\n readonly conversations: Conversations;\n\n private readonly _client: HttpClient;\n\n constructor(options: ClientOptions = {}) {\n // Presence is not validity: empty strings from options or environment\n // are configuration mistakes, not credentials.\n const apiKey = resolveOption('apiKey', options.apiKey, readEnv('CADENYAWIDGETS_API_KEY'));\n if (!apiKey) {\n throw new Error(\n \"Missing API key. Pass it with `new CadenyaWidgets({ apiKey })` or set the CADENYAWIDGETS_API_KEY environment variable.\",\n );\n }\n this._client = new HttpClient({\n baseURL: resolveOption('baseURL', options.baseURL, readEnv('CADENYAWIDGETS_BASE_URL')) ?? '',\n authHeader: () => ({ Authorization: `Bearer ${apiKey}` }),\n maxRetries: options.maxRetries ?? 0,\n timeout: options.timeout,\n defaultHeaders: { 'User-Agent': 'cadenyawidgets-typescript/1.1.0 (api 1.0)', ...options.defaultHeaders },\n fetch: options.fetch,\n logger: options.logger,\n logLevel: options.logLevel,\n defaults: { },\n });\n this.config = new Config(this._client);\n this.conversations = new Conversations(this._client);\n }\n}\n\nfunction readEnv(name: string): string | undefined {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env;\n return env?.[name];\n}\n\n// Presence is not validity: an explicitly provided option must be usable —\n// a blank value is a configuration mistake and never silently falls back to\n// the environment or a default. Only an OMITTED option reads the env.\nfunction resolveOption(\n label: string,\n explicit: string | undefined,\n env: string | undefined,\n): string | undefined {\n if (explicit !== undefined) {\n const value = explicit.trim();\n if (!value) {\n throw new Error(\n `${label} must not be blank when provided explicitly; omit it to use the environment instead.`,\n );\n }\n return value;\n }\n return env?.trim() || undefined;\n}\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,6CAA6C;AAE7C,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AA0B7D,MAAM,OAAO,cAAc;IAChB,MAAM,CAAS;IACf,aAAa,CAAgB;IAErB,OAAO,CAAa;IAErC,YAAY,UAAyB,EAAE;QACrC,sEAAsE;QACtE,+CAA+C;QAC/C,MAAM,MAAM,GAAG,aAAa,CAAC,QAAQ,EAAE,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,wBAAwB,CAAC,CAAC,CAAC;QAC1F,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,IAAI,KAAK,CACb,wHAAwH,CACzH,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,OAAO,GAAG,IAAI,UAAU,CAAC;YAC5B,OAAO,EAAE,aAAa,CAAC,SAAS,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,yBAAyB,CAAC,CAAC,IAAI,EAAE;YAC5F,UAAU,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,aAAa,EAAE,UAAU,MAAM,EAAE,EAAE,CAAC;YACzD,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,CAAC;YACnC,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,cAAc,EAAE,EAAE,GAAG,aAAa,CAAC,2CAA2C,CAAC,EAAE,GAAG,OAAO,CAAC,cAAc,EAAE;YAC5G,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,QAAQ,EAAE,EAAI;SACf,CAAC,CAAC;QACH,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACvC,IAAI,CAAC,aAAa,GAAG,IAAI,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACvD,CAAC;CACF;AAED,oFAAoF;AACpF,kFAAkF;AAClF,SAAS,aAAa,CAAC,KAAa;IAClC,MAAM,WAAW,GAAI,UAA6D;SAC/E,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC;IAC3B,OAAO,WAAW,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AACpD,CAAC;AAED,SAAS,OAAO,CAAC,IAAY;IAC3B,MAAM,GAAG,GAAI,UAAyE;SACnF,OAAO,EAAE,GAAG,CAAC;IAChB,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;AACrB,CAAC;AAED,2EAA2E;AAC3E,4EAA4E;AAC5E,sEAAsE;AACtE,SAAS,aAAa,CACpB,KAAa,EACb,QAA4B,EAC5B,GAAuB;IAEvB,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,KAAK,CACb,GAAG,KAAK,sFAAsF,CAC/F,CAAC;QACJ,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,GAAG,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;AAClC,CAAC","sourcesContent":["// Generated by redwood. Do not edit by hand.\n\nimport { HttpClient } from './core/http.js';\nimport type { Logger, LogLevel } from './core/http.js';\nimport { Config } from './resources/config.js';\nimport { Conversations } from './resources/conversations.js';\n\nexport interface ClientOptions {\n /** API key. Defaults to the CADENYAWIDGETS_API_KEY environment variable. */\n apiKey?: string;\n /** Override the API base URL. Defaults to . */\n baseURL?: string;\n /** Max automatic retries for retryable failures. Defaults to 0. */\n maxRetries?: number;\n /**\n * Deadline for ordinary (non-streaming) requests in milliseconds; override\n * per request with `options.timeout`. Streams bound only response-header\n * acquisition — body lifetime stays under the caller's AbortSignal.\n * Defaults to 60000; a non-finite or <= 0 value disables the deadline.\n */\n timeout?: number;\n /** Additional request headers. Browsers supply their own User-Agent by default. */\n defaultHeaders?: Record<string, string>;\n /** Custom fetch implementation. */\n fetch?: typeof fetch;\n /** Destination for SDK logs. Defaults to `console`. */\n logger?: Logger;\n /** 'debug' | 'warn' (default) | 'off'. Never logs headers or bodies. */\n logLevel?: LogLevel;\n}\n\nexport class CadenyaWidgets {\n readonly config: Config;\n readonly conversations: Conversations;\n\n private readonly _client: HttpClient;\n\n constructor(options: ClientOptions = {}) {\n // Presence is not validity: empty strings from options or environment\n // are configuration mistakes, not credentials.\n const apiKey = resolveOption('apiKey', options.apiKey, readEnv('CADENYAWIDGETS_API_KEY'));\n if (!apiKey) {\n throw new Error(\n \"Missing API key. Pass it with `new CadenyaWidgets({ apiKey })` or set the CADENYAWIDGETS_API_KEY environment variable.\",\n );\n }\n this._client = new HttpClient({\n baseURL: resolveOption('baseURL', options.baseURL, readEnv('CADENYAWIDGETS_BASE_URL')) ?? '',\n authHeader: () => ({ Authorization: `Bearer ${apiKey}` }),\n maxRetries: options.maxRetries ?? 0,\n timeout: options.timeout,\n defaultHeaders: { ...nodeUserAgent('cadenyawidgets-typescript/1.1.1 (api 1.0)'), ...options.defaultHeaders },\n fetch: options.fetch,\n logger: options.logger,\n logLevel: options.logLevel,\n defaults: { },\n });\n this.config = new Config(this._client);\n this.conversations = new Conversations(this._client);\n }\n}\n\n// Browser-authored User-Agent headers require CORS permission. Only Node-compatible\n// runtimes receive the SDK default; browsers and workers use their native header.\nfunction nodeUserAgent(value: string): Record<string, string> {\n const nodeVersion = (globalThis as { process?: { versions?: { node?: string } } })\n .process?.versions?.node;\n return nodeVersion ? { 'User-Agent': value } : {};\n}\n\nfunction readEnv(name: string): string | undefined {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env;\n return env?.[name];\n}\n\n// Presence is not validity: an explicitly provided option must be usable —\n// a blank value is a configuration mistake and never silently falls back to\n// the environment or a default. Only an OMITTED option reads the env.\nfunction resolveOption(\n label: string,\n explicit: string | undefined,\n env: string | undefined,\n): string | undefined {\n if (explicit !== undefined) {\n const value = explicit.trim();\n if (!value) {\n throw new Error(\n `${label} must not be blank when provided explicitly; omit it to use the environment instead.`,\n );\n }\n return value;\n }\n return env?.trim() || undefined;\n}\n"]}
@@ -26,7 +26,12 @@ export interface RequestOptions {
26
26
  lastEventId?: string;
27
27
  }
28
28
  export type QueryPrimitive = string | number | boolean;
29
- export type QueryValue = QueryPrimitive | QueryPrimitive[] | undefined | null;
29
+ /**
30
+ * Query objects are flattened to dot-delimited paths. `object` is used here
31
+ * deliberately so generated named interfaces (which do not declare an index
32
+ * signature) remain assignable as query parameter values.
33
+ */
34
+ export type QueryValue = QueryPrimitive | readonly QueryPrimitive[] | object | undefined | null;
30
35
  export interface RequestSpec {
31
36
  method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
32
37
  path: string;
@@ -1 +1 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/core/http.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAYH,MAAM,WAAW,cAAc;IAC7B;;;;;OAKG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,WAAW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,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAyB;IACxD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAe;IACvC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAW;IAEpC,yEAAyE;IACzE,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,OAAO;IAGf,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;gBAE1C,OAAO,EAAE,iBAAiB;IAwCtC;;;;;;OAMG;IACH,UAAU,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,WAAW,EAAE,OAAO,GAAE,cAAmB,GAAG,UAAU,CAAC,CAAC,CAAC;IAiDjF,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,CAAC,CAAC;IAsCvE,UAAU,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,QAAQ,CAAC;IA2IpF;;;;OAIG;IACH,OAAO,CAAC,QAAQ;IAoChB,OAAO,CAAC,QAAQ;CAQjB"}
package/dist/core/http.js CHANGED
@@ -473,17 +473,44 @@ export class HttpClient {
473
473
  }
474
474
  buildURL(path, query) {
475
475
  const url = new URL(this.baseURL + path);
476
+ const ancestors = new Set();
476
477
  for (const [key, value] of Object.entries(query ?? {})) {
477
- if (value === undefined || value === null)
478
- continue;
479
- // Arrays serialize as repeated params: ?state=a&state=b
480
- for (const item of Array.isArray(value) ? value : [value]) {
481
- url.searchParams.append(key, String(item));
482
- }
478
+ appendQueryValue(url.searchParams, key, value, ancestors);
483
479
  }
484
480
  return url.toString();
485
481
  }
486
482
  }
483
+ /**
484
+ * Flatten nested query objects to dot-delimited paths. Arrays retain the
485
+ * existing repeated-parameter behavior at whichever path they occur:
486
+ * `{ filters: { state: ['a', 'b'] } }` becomes
487
+ * `?filters.state=a&filters.state=b`.
488
+ */
489
+ function appendQueryValue(searchParams, key, value, ancestors) {
490
+ if (value === undefined || value === null)
491
+ return;
492
+ if (typeof value !== 'object') {
493
+ searchParams.append(key, String(value));
494
+ return;
495
+ }
496
+ if (ancestors.has(value)) {
497
+ throw new APIRequestError('query parameters contain a circular reference', undefined);
498
+ }
499
+ ancestors.add(value);
500
+ try {
501
+ if (Array.isArray(value)) {
502
+ for (const item of value)
503
+ appendQueryValue(searchParams, key, item, ancestors);
504
+ return;
505
+ }
506
+ for (const [childKey, childValue] of Object.entries(value)) {
507
+ appendQueryValue(searchParams, `${key}.${childKey}`, childValue, ancestors);
508
+ }
509
+ }
510
+ finally {
511
+ ancestors.delete(value);
512
+ }
513
+ }
487
514
  /** Retry counts must be bounded non-negative integers; anything else (NaN,
488
515
  * Infinity, negatives, fractions) is treated as the nearest sane value. */
489
516
  function normalizeRetries(value) {
@@ -1 +1 @@
1
- {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/core/http.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,kBAAkB,EAClB,QAAQ,EACR,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,iBAAiB,GAElB,MAAM,YAAY,CAAC;AAkEpB,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AAEtE,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAElC;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,KAAyB;IACjE,IAAI,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACvD,MAAM,IAAI,KAAK,CAAC,oCAAoC,IAAI,IAAI,CAAC,CAAC;IAChE,CAAC;IACD,OAAO,kBAAkB,CAAC,KAA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,OAAO,OAAO,EAAE,CAAC;QACtC,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YAC5B,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC9C,OAAO,EAAE,CAAC;QACZ,CAAC,EAAE,EAAE,CAAC,CAAC;QACP,MAAM,OAAO,GAAG,GAAG,EAAE;YACnB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC;QACF,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Minimal, dependency-less HTTP core built on global fetch (Node 18+,\n * browsers, Deno, Bun). Handles auth, query serialization, retries with\n * backoff, timeouts, and error mapping.\n */\n\nimport {\n APIConnectionError,\n APIError,\n APIRequestError,\n APIResponseError,\n APITimeoutError,\n APIUserAbortError,\n ErrorStatus,\n} from './error.js';\n\nexport interface RequestOptions {\n /**\n * Auto-reconnect for SSE streams (default true): a mid-stream transport\n * drop resumes from the last received event id, like EventSource. Clean\n * stream end, close(), and abort never reconnect. Set false to surface\n * drops as APIConnectionError instead.\n */\n reconnect?: boolean;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n maxRetries?: number;\n /**\n * Per-request deadline in milliseconds (overrides the client default).\n * Non-finite or <= 0 disables the deadline for this request.\n */\n timeout?: number;\n /**\n * For streaming (SSE) requests: resume after the event with this id by\n * sending it as the Last-Event-ID request header.\n */\n lastEventId?: string;\n}\n\nexport type QueryPrimitive = string | number | boolean;\nexport type QueryValue = QueryPrimitive | QueryPrimitive[] | undefined | null;\n\nexport interface RequestSpec {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n path: string;\n query?: Record<string, QueryValue>;\n body?: unknown;\n stream?: boolean;\n /** The operation declares no response body (void): 204/empty succeed. */\n void?: boolean;\n}\n\nexport type LogLevel = 'debug' | 'warn' | 'off';\n\n/** Minimal logger surface; `console` satisfies it. */\nexport interface Logger {\n debug(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n}\n\nexport interface HttpClientOptions {\n baseURL: string;\n authHeader: () => Record<string, string>;\n maxRetries?: number;\n /** Deadline for ordinary (non-streaming) requests in ms. Default 60000. */\n timeout?: number;\n defaultHeaders?: Record<string, string>;\n fetch?: typeof fetch;\n /** Client-level default values for prominent params (e.g. a tenant/scope id). */\n defaults?: Record<string, string | undefined>;\n /** Destination for SDK logs. Defaults to `console`. */\n logger?: Logger;\n /**\n * 'debug' logs every request/response line (method, path, status,\n * duration — never headers or bodies); 'warn' (default) logs only\n * retries; 'off' silences the SDK entirely.\n */\n logLevel?: LogLevel;\n}\n\nconst RETRYABLE_STATUS = new Set([408, 409, 429, 500, 502, 503, 504]);\n\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * Encode one path segment, rejecting empty/whitespace values at the boundary\n * — an empty segment would silently rewrite the route (/parents//children).\n */\nexport function pathSegment(name: string, value: string | undefined): string {\n if (value === undefined || String(value).trim() === '') {\n throw new Error(`Missing required path parameter '${name}'.`);\n }\n return encodeURIComponent(value);\n}\n\n/**\n * Snapshot list params at call time so pagination cannot observe later\n * caller mutations (array-valued filters are copied too). Auto-iteration\n * must never combine pages from different result sets.\n */\nexport function snapshotParams<T>(params: T): T {\n if (params === undefined || params === null || typeof params !== 'object') return params;\n const copy: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(params as Record<string, unknown>)) {\n copy[key] = Array.isArray(value) ? value.slice() : value;\n }\n return copy as T;\n}\n\n/**\n * Automatic retries apply only to idempotent methods. A POST/PATCH that\n * succeeds server-side but loses its response would be executed twice if\n * retried; callers can opt a specific mutation in via options.maxRetries.\n */\nconst IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'PUT', 'DELETE']);\n\n/**\n * Settle when the promise settles OR the signal aborts — a custom fetch (or\n * body reader) that ignores AbortSignal must not be able to hold a deadlined\n * request open forever. The orphaned promise's eventual rejection is\n * swallowed; its resolution is discarded.\n */\nfunction raceAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (!signal) return promise;\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => {\n promise.catch(() => {});\n reject(new APIUserAbortError());\n };\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener('abort', onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener('abort', onAbort);\n resolve(value);\n },\n (err) => {\n signal.removeEventListener('abort', onAbort);\n reject(err);\n },\n );\n });\n}\n\n/**\n * Deadline cleanup for streaming responses, handed from rawRequest to the\n * Stream that owns the body. The forwarding listener must survive until the\n * stream terminates (a caller abort has to unblock a pending read on a\n * silent socket), so the Stream — not rawRequest — releases it.\n */\nconst streamCleanups = new WeakMap<Response, () => void>();\n\n/** Claim (and remove) the cleanup registered for a streaming response. */\nexport function takeStreamCleanup(response: Response): (() => void) | undefined {\n const cleanup = streamCleanups.get(response);\n streamCleanups.delete(response);\n return cleanup;\n}\n\n/** Merged caller-signal + deadline state for one request. */\ninterface Deadline {\n signal: AbortSignal | undefined;\n /** Stop the timer (body may keep streaming under the caller's signal). */\n settle(): void;\n /**\n * Detach the abort-forwarding listener from the caller's signal. Call\n * only when the request (including any stream body) is finished — a\n * reused long-lived signal must not accumulate one listener per\n * completed call.\n */\n release(): void;\n timedOut(): boolean;\n ms: number;\n}\n\n/**\n * A lazily-parsing promise for one API call. Awaiting it (or `.then`) yields\n * the decoded value exactly like a plain promise; `withResponse()` yields the\n * decoded value together with the raw `Response` (status, headers); and\n * `asResponse()` yields the raw `Response` WITHOUT consuming the body, so\n * the caller owns reading it.\n */\nexport class APIPromise<T> implements Promise<T> {\n private parsed: Promise<T> | undefined;\n private observedRaw = false;\n\n constructor(\n private readonly responsePromise: Promise<Response>,\n private readonly parseFn: (response: Response) => Promise<T>,\n private readonly onRawAccess: () => void,\n ) {\n // A dropped return value must still reach terminal cleanup: the request\n // has already been sent, so unless raw access claims the body FIRST\n // (synchronously, before any await), parsing starts on the next\n // microtask — consuming the body and settling the deadline timer even\n // when the caller never observes the promise. Rejections on this\n // internal branch are swallowed; a caller who later awaits still gets\n // them from the memoized parse.\n queueMicrotask(() => {\n if (!this.observedRaw) this.parse().catch(() => {});\n });\n }\n\n /**\n * The raw `Response` after status checking and retries; the body is NOT\n * consumed. Reading the body (and its timing) becomes the caller's\n * responsibility — the request deadline stops at header acquisition.\n */\n asResponse(): Promise<Response> {\n // Must be called synchronously after the request (before any await):\n // it claims body ownership away from the auto-parse safety net. Mixing\n // a LATE asResponse() with parsed access yields a response whose body\n // was already consumed by parsing — status/headers stay usable.\n this.observedRaw = true;\n return this.responsePromise.then((response) => {\n this.onRawAccess();\n return response;\n });\n }\n\n /** The decoded value together with the `Response` its body came from. */\n async withResponse(): Promise<{ data: T; response: Response }> {\n const response = await this.responsePromise;\n const data = await this.parse();\n return { data, response };\n }\n\n private parse(): Promise<T> {\n this.parsed ??= this.responsePromise.then(this.parseFn);\n return this.parsed;\n }\n\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.parse().then(onfulfilled, onrejected);\n }\n\n catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,\n ): Promise<T | TResult> {\n return this.parse().catch(onrejected);\n }\n\n finally(onfinally?: (() => void) | null): Promise<T> {\n return this.parse().finally(onfinally);\n }\n\n readonly [Symbol.toStringTag] = 'APIPromise';\n}\n\nexport class HttpClient {\n private readonly baseURL: string;\n private readonly authHeader: () => Record<string, string>;\n private readonly maxRetries: number;\n private readonly timeout: number;\n private readonly defaultHeaders: Record<string, string>;\n private readonly fetchFn: typeof fetch;\n private readonly logger: Logger;\n private readonly logLevel: LogLevel;\n\n /** Method + path + status only — headers and bodies are never logged. */\n private logDebug(...args: unknown[]): void {\n if (this.logLevel === 'debug') this.logger.debug('[sdk]', ...args);\n }\n\n private logWarn(...args: unknown[]): void {\n if (this.logLevel !== 'off') this.logger.warn('[sdk]', ...args);\n }\n readonly defaults: Record<string, string | undefined>;\n\n constructor(options: HttpClientOptions) {\n this.defaults = options.defaults ?? {};\n this.logger = options.logger ?? console;\n this.logLevel = options.logLevel ?? 'warn';\n // Validate the STRUCTURE once: operation paths are appended to this\n // value, so a query/fragment/userinfo would silently swallow the\n // request path. Absolute http(s) with a host is required; a path\n // prefix is supported and kept.\n // A literal delimiter parses as an EMPTY search/hash and slips past\n // the checks below; reject the characters outright.\n if (options.baseURL.includes('?') || options.baseURL.includes('#')) {\n throw new Error(\n `baseURL '${options.baseURL}' must not carry userinfo, query, or fragment`,\n );\n }\n let parsed: URL;\n try {\n parsed = new URL(options.baseURL);\n } catch (err) {\n throw new Error(`baseURL '${options.baseURL}' is not an absolute URL`, { cause: err });\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`baseURL '${options.baseURL}' must use http or https`);\n }\n if (parsed.hostname === '') {\n throw new Error(`baseURL '${options.baseURL}' has no host`);\n }\n if (parsed.username !== '' || parsed.password !== '' || parsed.search !== '' || parsed.hash !== '') {\n throw new Error(\n `baseURL '${options.baseURL}' must not carry userinfo, query, or fragment`,\n );\n }\n this.baseURL = (parsed.origin + parsed.pathname).replace(/\\/+$/, '');\n this.authHeader = options.authHeader;\n this.maxRetries = options.maxRetries ?? 0;\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;\n this.defaultHeaders = options.defaultHeaders ?? {};\n this.fetchFn = options.fetch ?? fetch;\n }\n\n /**\n * The APIPromise pipeline for JSON and void operations. The spec thunk\n * runs inside the async context so synchronous setup failures (e.g. a\n * missing client-default param) surface as rejections, exactly like the\n * plain-promise path. The deadline spans fetch through decode; raw-access\n * consumers release it at header acquisition and own body timing.\n */\n requestAPI<T>(makeSpec: () => RequestSpec, options: RequestOptions = {}): APIPromise<T> {\n const deadline = this.deadline(options);\n let spec: RequestSpec;\n const responsePromise = (async () => {\n try {\n spec = makeSpec();\n return await this.rawRequest(spec, { ...options, signal: deadline.signal });\n } catch (err) {\n deadline.settle();\n deadline.release();\n if (deadline.timedOut()) throw new APITimeoutError(deadline.ms);\n throw err;\n }\n })();\n const parseFn = async (response: Response): Promise<T> => {\n try {\n if (spec.void) {\n void response.body?.cancel().catch(() => {});\n return undefined as T;\n }\n if (response.status === 204) {\n throw new APIResponseError(204, 'HTTP 204 where a JSON response was expected');\n }\n const text = await raceAbort(response.text(), deadline.signal);\n if (text.trim() === '' || text.trim() === 'null') {\n throw new APIResponseError(\n response.status,\n `HTTP ${response.status} with an empty or null body where a JSON response was expected`,\n );\n }\n try {\n return JSON.parse(text) as T;\n } catch (err) {\n throw new APIResponseError(response.status, 'response body is not valid JSON', err);\n }\n } catch (err) {\n if (deadline.timedOut()) throw new APITimeoutError(deadline.ms);\n throw err;\n } finally {\n deadline.settle();\n deadline.release();\n }\n };\n return new APIPromise<T>(responsePromise, parseFn, () => {\n deadline.settle();\n deadline.release();\n });\n }\n\n async request<T>(spec: RequestSpec, options: RequestOptions = {}): Promise<T> {\n // Ordinary JSON calls keep the deadline through body consumption and\n // decoding — a response that stalls mid-body still times out.\n const deadline = this.deadline(options);\n try {\n const response = await this.rawRequest(spec, { ...options, signal: deadline.signal });\n // Branch on the GENERATED expectation, not the HTTP status: a void\n // method accepts 204/empty, but an output-bearing method requires a\n // JSON document — empty/null would fabricate a resource outside the\n // declared contract, and malformed JSON must be a stable SDK error.\n if (spec.void) {\n void response.body?.cancel().catch(() => {});\n return undefined as T;\n }\n if (response.status === 204) {\n throw new APIResponseError(204, 'HTTP 204 where a JSON response was expected');\n }\n const text = await raceAbort(response.text(), deadline.signal);\n if (text.trim() === '' || text.trim() === 'null') {\n throw new APIResponseError(\n response.status,\n `HTTP ${response.status} with an empty or null body where a JSON response was expected`,\n );\n }\n try {\n return JSON.parse(text) as T;\n } catch (err) {\n throw new APIResponseError(response.status, 'response body is not valid JSON', err);\n }\n } catch (err) {\n if (deadline.timedOut()) throw new APITimeoutError(deadline.ms);\n throw err;\n } finally {\n deadline.settle();\n deadline.release();\n }\n }\n\n async rawRequest(spec: RequestSpec, options: RequestOptions = {}): Promise<Response> {\n const url = this.buildURL(spec.path, spec.query);\n\n // One Headers instance; `set` is case-insensitive, so later layers\n // OVERRIDE earlier ones regardless of spelling (object spread would keep\n // both `Authorization` and `authorization` and fetch would join the two\n // values into one corrupt header). Precedence: generated defaults →\n // client defaults → auth → per-request → Last-Event-ID (the semantic\n // option is the single source of resume state).\n const headers = new Headers();\n headers.set('Accept', spec.stream ? 'text/event-stream' : 'application/json');\n if (spec.body !== undefined) headers.set('Content-Type', 'application/json');\n for (const [key, value] of Object.entries(this.defaultHeaders)) headers.set(key, value);\n for (const [key, value] of Object.entries(this.authHeader())) headers.set(key, value);\n for (const [key, value] of Object.entries(options.headers ?? {})) headers.set(key, value);\n if (options.lastEventId !== undefined) {\n headers.set('Last-Event-ID', options.lastEventId);\n }\n\n // Serialize ONCE, before the transport/retry loop: a circular object or\n // BigInt is a caller bug, not a network failure — it must surface as a\n // stable request-construction error and never be retried.\n let bodyText: string | undefined;\n if (spec.body !== undefined) {\n try {\n bodyText = JSON.stringify(spec.body);\n } catch (err) {\n throw new APIRequestError('request body is not JSON-serializable', err);\n }\n if (bodyText === undefined) {\n throw new APIRequestError('request body serialized to undefined', undefined);\n }\n }\n\n // Streams bound only connection/response-header acquisition; the body's\n // lifetime stays under the caller's AbortSignal.\n const streamDeadline = spec.stream ? this.deadline(options) : undefined;\n const signal = streamDeadline ? streamDeadline.signal : options.signal;\n\n // An explicit per-request maxRetries opts in even for mutations.\n const maxRetries = normalizeRetries(\n options.maxRetries !== undefined\n ? options.maxRetries\n : IDEMPOTENT_METHODS.has(spec.method)\n ? this.maxRetries\n : 0,\n );\n\n const startedAt = Date.now();\n for (let attempt = 0; ; attempt++) {\n this.logDebug(`-> ${spec.method} ${spec.path}`, attempt > 0 ? `(attempt ${attempt + 1})` : '');\n let response: Response;\n try {\n response = await raceAbort(\n this.fetchFn(url, {\n method: spec.method,\n headers,\n body: bodyText,\n signal: signal ?? null,\n }),\n signal,\n );\n } catch (err) {\n if (streamDeadline?.timedOut()) {\n streamDeadline.settle();\n streamDeadline.release();\n throw new APITimeoutError(streamDeadline.ms);\n }\n if (signal?.aborted) {\n streamDeadline?.settle();\n streamDeadline?.release();\n throw new APIUserAbortError();\n }\n if (attempt < maxRetries) {\n this.logWarn(`retrying ${spec.method} ${spec.path} after connection error (attempt ${attempt + 1}/${maxRetries + 1})`);\n await sleep(backoffMs(attempt, undefined), signal);\n if (streamDeadline?.timedOut()) {\n streamDeadline.settle();\n streamDeadline.release();\n throw new APITimeoutError(streamDeadline.ms);\n }\n if (signal?.aborted) throw new APIUserAbortError();\n continue;\n }\n // Terminal connection failure: the deadline timer must not outlive\n // the reported error (an orphaned timer holds the process open).\n streamDeadline?.settle();\n streamDeadline?.release();\n throw new APIConnectionError(err);\n }\n\n if (response.ok) {\n this.logDebug(`<- ${response.status} ${spec.method} ${spec.path} (${Date.now() - startedAt}ms)`);\n // Response headers acquired: the stream body is now unbounded. The\n // forwarding listener stays attached (caller abort must reach the\n // body); the Stream releases it at its terminal state.\n if (streamDeadline) {\n streamDeadline.settle();\n streamCleanups.set(response, () => streamDeadline.release());\n }\n return response;\n }\n\n if (RETRYABLE_STATUS.has(response.status) && attempt < maxRetries) {\n this.logWarn(`retrying ${spec.method} ${spec.path} after HTTP ${response.status} (attempt ${attempt + 1}/${maxRetries + 1})`);\n // Release the discarded response so its connection can be reused.\n void response.body?.cancel().catch(() => {});\n await sleep(backoffMs(attempt, response.headers.get('retry-after')), signal);\n // A stream deadline that fired during backoff is a timeout, not a\n // user abort — rawRequest has no outer mapper to reclassify it.\n if (streamDeadline?.timedOut()) {\n streamDeadline.settle();\n streamDeadline.release();\n throw new APITimeoutError(streamDeadline.ms);\n }\n if (signal?.aborted) throw new APIUserAbortError();\n continue;\n }\n\n let body: ErrorStatus | undefined;\n try {\n body = (await response.json()) as ErrorStatus;\n } catch {\n body = undefined;\n }\n // The deadline stays active while consuming a non-2xx error body; if\n // it expired there, report the timeout rather than a truncated\n // APIError.\n if (streamDeadline?.timedOut()) {\n streamDeadline.settle();\n streamDeadline.release();\n throw new APITimeoutError(streamDeadline.ms);\n }\n streamDeadline?.settle();\n streamDeadline?.release();\n throw new APIError(response.status, body);\n }\n }\n\n /**\n * Merge the caller's signal with the configured deadline. The caller's\n * abort always forwards; the timer marks timedOut so the thrown error can\n * be classified as APITimeoutError rather than APIUserAbortError.\n */\n private deadline(options: RequestOptions): Deadline {\n const ms = options.timeout ?? this.timeout;\n if (!Number.isFinite(ms) || ms <= 0) {\n return { signal: options.signal, settle() {}, release() {}, timedOut: () => false, ms };\n }\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, ms);\n const forward = () => controller.abort();\n if (options.signal?.aborted) {\n controller.abort();\n } else {\n options.signal?.addEventListener('abort', forward, { once: true });\n }\n let settled = false;\n let released = false;\n return {\n signal: controller.signal,\n settle() {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n },\n release() {\n if (released) return;\n released = true;\n options.signal?.removeEventListener('abort', forward);\n },\n timedOut: () => timedOut,\n ms,\n };\n }\n\n private buildURL(path: string, query?: Record<string, QueryValue>): string {\n const url = new URL(this.baseURL + path);\n for (const [key, value] of Object.entries(query ?? {})) {\n if (value === undefined || value === null) continue;\n // Arrays serialize as repeated params: ?state=a&state=b\n for (const item of Array.isArray(value) ? value : [value]) {\n url.searchParams.append(key, String(item));\n }\n }\n return url.toString();\n }\n}\n\n/** Retry counts must be bounded non-negative integers; anything else (NaN,\n * Infinity, negatives, fractions) is treated as the nearest sane value. */\nfunction normalizeRetries(value: number): number {\n if (!Number.isFinite(value) || value <= 0) return 0;\n return Math.min(Math.floor(value), 10);\n}\n\nfunction backoffMs(attempt: number, retryAfter: string | null | undefined): number {\n if (retryAfter) {\n // Retry-After is either delta-seconds or an HTTP-date. A parsed zero is\n // a real answer (retry immediately), not a fall-through to backoff.\n const seconds = Number(retryAfter);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, 60_000);\n const date = Date.parse(retryAfter);\n if (Number.isFinite(date)) {\n return Math.min(Math.max(date - Date.now(), 0), 60_000);\n }\n }\n const base = 500 * 2 ** Math.min(attempt, 4);\n return Math.min(base + Math.random() * base, 8000);\n}\n\n/** Sleep that wakes early when the signal aborts (caller re-checks it). */\nfunction sleep(ms: number, signal?: AbortSignal | null): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) return resolve();\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n resolve();\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n"]}
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/core/http.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,kBAAkB,EAClB,QAAQ,EACR,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,iBAAiB,GAElB,MAAM,YAAY,CAAC;AAuEpB,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AAEtE,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAElC;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,KAAyB;IACjE,IAAI,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACvD,MAAM,IAAI,KAAK,CAAC,oCAAoC,IAAI,IAAI,CAAC,CAAC;IAChE,CA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AE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Minimal, dependency-less HTTP core built on global fetch (Node 18+,\n * browsers, Deno, Bun). Handles auth, query serialization, retries with\n * backoff, timeouts, and error mapping.\n */\n\nimport {\n APIConnectionError,\n APIError,\n APIRequestError,\n APIResponseError,\n APITimeoutError,\n APIUserAbortError,\n ErrorStatus,\n} from './error.js';\n\nexport interface RequestOptions {\n /**\n * Auto-reconnect for SSE streams (default true): a mid-stream transport\n * drop resumes from the last received event id, like EventSource. Clean\n * stream end, close(), and abort never reconnect. Set false to surface\n * drops as APIConnectionError instead.\n */\n reconnect?: boolean;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n maxRetries?: number;\n /**\n * Per-request deadline in milliseconds (overrides the client default).\n * Non-finite or <= 0 disables the deadline for this request.\n */\n timeout?: number;\n /**\n * For streaming (SSE) requests: resume after the event with this id by\n * sending it as the Last-Event-ID request header.\n */\n lastEventId?: string;\n}\n\nexport type QueryPrimitive = string | number | boolean;\n/**\n * Query objects are flattened to dot-delimited paths. `object` is used here\n * deliberately so generated named interfaces (which do not declare an index\n * signature) remain assignable as query parameter values.\n */\nexport type QueryValue = QueryPrimitive | readonly QueryPrimitive[] | object | undefined | null;\n\nexport interface RequestSpec {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n path: string;\n query?: Record<string, QueryValue>;\n body?: unknown;\n stream?: boolean;\n /** The operation declares no response body (void): 204/empty succeed. */\n void?: boolean;\n}\n\nexport type LogLevel = 'debug' | 'warn' | 'off';\n\n/** Minimal logger surface; `console` satisfies it. */\nexport interface Logger {\n debug(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n}\n\nexport interface HttpClientOptions {\n baseURL: string;\n authHeader: () => Record<string, string>;\n maxRetries?: number;\n /** Deadline for ordinary (non-streaming) requests in ms. Default 60000. */\n timeout?: number;\n defaultHeaders?: Record<string, string>;\n fetch?: typeof fetch;\n /** Client-level default values for prominent params (e.g. a tenant/scope id). */\n defaults?: Record<string, string | undefined>;\n /** Destination for SDK logs. Defaults to `console`. */\n logger?: Logger;\n /**\n * 'debug' logs every request/response line (method, path, status,\n * duration — never headers or bodies); 'warn' (default) logs only\n * retries; 'off' silences the SDK entirely.\n */\n logLevel?: LogLevel;\n}\n\nconst RETRYABLE_STATUS = new Set([408, 409, 429, 500, 502, 503, 504]);\n\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * Encode one path segment, rejecting empty/whitespace values at the boundary\n * — an empty segment would silently rewrite the route (/parents//children).\n */\nexport function pathSegment(name: string, value: string | undefined): string {\n if (value === undefined || String(value).trim() === '') {\n throw new Error(`Missing required path parameter '${name}'.`);\n }\n return encodeURIComponent(value);\n}\n\n/**\n * Snapshot list params at call time so pagination cannot observe later\n * caller mutations (array-valued filters are copied too). Auto-iteration\n * must never combine pages from different result sets.\n */\nexport function snapshotParams<T>(params: T): T {\n if (params === undefined || params === null || typeof params !== 'object') return params;\n const copy: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(params as Record<string, unknown>)) {\n copy[key] = Array.isArray(value) ? value.slice() : value;\n }\n return copy as T;\n}\n\n/**\n * Automatic retries apply only to idempotent methods. A POST/PATCH that\n * succeeds server-side but loses its response would be executed twice if\n * retried; callers can opt a specific mutation in via options.maxRetries.\n */\nconst IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'PUT', 'DELETE']);\n\n/**\n * Settle when the promise settles OR the signal aborts — a custom fetch (or\n * body reader) that ignores AbortSignal must not be able to hold a deadlined\n * request open forever. The orphaned promise's eventual rejection is\n * swallowed; its resolution is discarded.\n */\nfunction raceAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n if (!signal) return promise;\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => {\n promise.catch(() => {});\n reject(new APIUserAbortError());\n };\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener('abort', onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener('abort', onAbort);\n resolve(value);\n },\n (err) => {\n signal.removeEventListener('abort', onAbort);\n reject(err);\n },\n );\n });\n}\n\n/**\n * Deadline cleanup for streaming responses, handed from rawRequest to the\n * Stream that owns the body. The forwarding listener must survive until the\n * stream terminates (a caller abort has to unblock a pending read on a\n * silent socket), so the Stream — not rawRequest — releases it.\n */\nconst streamCleanups = new WeakMap<Response, () => void>();\n\n/** Claim (and remove) the cleanup registered for a streaming response. */\nexport function takeStreamCleanup(response: Response): (() => void) | undefined {\n const cleanup = streamCleanups.get(response);\n streamCleanups.delete(response);\n return cleanup;\n}\n\n/** Merged caller-signal + deadline state for one request. */\ninterface Deadline {\n signal: AbortSignal | undefined;\n /** Stop the timer (body may keep streaming under the caller's signal). */\n settle(): void;\n /**\n * Detach the abort-forwarding listener from the caller's signal. Call\n * only when the request (including any stream body) is finished — a\n * reused long-lived signal must not accumulate one listener per\n * completed call.\n */\n release(): void;\n timedOut(): boolean;\n ms: number;\n}\n\n/**\n * A lazily-parsing promise for one API call. Awaiting it (or `.then`) yields\n * the decoded value exactly like a plain promise; `withResponse()` yields the\n * decoded value together with the raw `Response` (status, headers); and\n * `asResponse()` yields the raw `Response` WITHOUT consuming the body, so\n * the caller owns reading it.\n */\nexport class APIPromise<T> implements Promise<T> {\n private parsed: Promise<T> | undefined;\n private observedRaw = false;\n\n constructor(\n private readonly responsePromise: Promise<Response>,\n private readonly parseFn: (response: Response) => Promise<T>,\n private readonly onRawAccess: () => void,\n ) {\n // A dropped return value must still reach terminal cleanup: the request\n // has already been sent, so unless raw access claims the body FIRST\n // (synchronously, before any await), parsing starts on the next\n // microtask — consuming the body and settling the deadline timer even\n // when the caller never observes the promise. Rejections on this\n // internal branch are swallowed; a caller who later awaits still gets\n // them from the memoized parse.\n queueMicrotask(() => {\n if (!this.observedRaw) this.parse().catch(() => {});\n });\n }\n\n /**\n * The raw `Response` after status checking and retries; the body is NOT\n * consumed. Reading the body (and its timing) becomes the caller's\n * responsibility — the request deadline stops at header acquisition.\n */\n asResponse(): Promise<Response> {\n // Must be called synchronously after the request (before any await):\n // it claims body ownership away from the auto-parse safety net. Mixing\n // a LATE asResponse() with parsed access yields a response whose body\n // was already consumed by parsing — status/headers stay usable.\n this.observedRaw = true;\n return this.responsePromise.then((response) => {\n this.onRawAccess();\n return response;\n });\n }\n\n /** The decoded value together with the `Response` its body came from. */\n async withResponse(): Promise<{ data: T; response: Response }> {\n const response = await this.responsePromise;\n const data = await this.parse();\n return { data, response };\n }\n\n private parse(): Promise<T> {\n this.parsed ??= this.responsePromise.then(this.parseFn);\n return this.parsed;\n }\n\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.parse().then(onfulfilled, onrejected);\n }\n\n catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,\n ): Promise<T | TResult> {\n return this.parse().catch(onrejected);\n }\n\n finally(onfinally?: (() => void) | null): Promise<T> {\n return this.parse().finally(onfinally);\n }\n\n readonly [Symbol.toStringTag] = 'APIPromise';\n}\n\nexport class HttpClient {\n private readonly baseURL: string;\n private readonly authHeader: () => Record<string, string>;\n private readonly maxRetries: number;\n private readonly timeout: number;\n private readonly defaultHeaders: Record<string, string>;\n private readonly fetchFn: typeof fetch;\n private readonly logger: Logger;\n private readonly logLevel: LogLevel;\n\n /** Method + path + status only — headers and bodies are never logged. */\n private logDebug(...args: unknown[]): void {\n if (this.logLevel === 'debug') this.logger.debug('[sdk]', ...args);\n }\n\n private logWarn(...args: unknown[]): void {\n if (this.logLevel !== 'off') this.logger.warn('[sdk]', ...args);\n }\n readonly defaults: Record<string, string | undefined>;\n\n constructor(options: HttpClientOptions) {\n this.defaults = options.defaults ?? {};\n this.logger = options.logger ?? console;\n this.logLevel = options.logLevel ?? 'warn';\n // Validate the STRUCTURE once: operation paths are appended to this\n // value, so a query/fragment/userinfo would silently swallow the\n // request path. Absolute http(s) with a host is required; a path\n // prefix is supported and kept.\n // A literal delimiter parses as an EMPTY search/hash and slips past\n // the checks below; reject the characters outright.\n if (options.baseURL.includes('?') || options.baseURL.includes('#')) {\n throw new Error(\n `baseURL '${options.baseURL}' must not carry userinfo, query, or fragment`,\n );\n }\n let parsed: URL;\n try {\n parsed = new URL(options.baseURL);\n } catch (err) {\n throw new Error(`baseURL '${options.baseURL}' is not an absolute URL`, { cause: err });\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`baseURL '${options.baseURL}' must use http or https`);\n }\n if (parsed.hostname === '') {\n throw new Error(`baseURL '${options.baseURL}' has no host`);\n }\n if (parsed.username !== '' || parsed.password !== '' || parsed.search !== '' || parsed.hash !== '') {\n throw new Error(\n `baseURL '${options.baseURL}' must not carry userinfo, query, or fragment`,\n );\n }\n this.baseURL = (parsed.origin + parsed.pathname).replace(/\\/+$/, '');\n this.authHeader = options.authHeader;\n this.maxRetries = options.maxRetries ?? 0;\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;\n this.defaultHeaders = options.defaultHeaders ?? {};\n this.fetchFn = options.fetch ?? fetch;\n }\n\n /**\n * The APIPromise pipeline for JSON and void operations. The spec thunk\n * runs inside the async context so synchronous setup failures (e.g. a\n * missing client-default param) surface as rejections, exactly like the\n * plain-promise path. The deadline spans fetch through decode; raw-access\n * consumers release it at header acquisition and own body timing.\n */\n requestAPI<T>(makeSpec: () => RequestSpec, options: RequestOptions = {}): APIPromise<T> {\n const deadline = this.deadline(options);\n let spec: RequestSpec;\n const responsePromise = (async () => {\n try {\n spec = makeSpec();\n return await this.rawRequest(spec, { ...options, signal: deadline.signal });\n } catch (err) {\n deadline.settle();\n deadline.release();\n if (deadline.timedOut()) throw new APITimeoutError(deadline.ms);\n throw err;\n }\n })();\n const parseFn = async (response: Response): Promise<T> => {\n try {\n if (spec.void) {\n void response.body?.cancel().catch(() => {});\n return undefined as T;\n }\n if (response.status === 204) {\n throw new APIResponseError(204, 'HTTP 204 where a JSON response was expected');\n }\n const text = await raceAbort(response.text(), deadline.signal);\n if (text.trim() === '' || text.trim() === 'null') {\n throw new APIResponseError(\n response.status,\n `HTTP ${response.status} with an empty or null body where a JSON response was expected`,\n );\n }\n try {\n return JSON.parse(text) as T;\n } catch (err) {\n throw new APIResponseError(response.status, 'response body is not valid JSON', err);\n }\n } catch (err) {\n if (deadline.timedOut()) throw new APITimeoutError(deadline.ms);\n throw err;\n } finally {\n deadline.settle();\n deadline.release();\n }\n };\n return new APIPromise<T>(responsePromise, parseFn, () => {\n deadline.settle();\n deadline.release();\n });\n }\n\n async request<T>(spec: RequestSpec, options: RequestOptions = {}): Promise<T> {\n // Ordinary JSON calls keep the deadline through body consumption and\n // decoding — a response that stalls mid-body still times out.\n const deadline = this.deadline(options);\n try {\n const response = await this.rawRequest(spec, { ...options, signal: deadline.signal });\n // Branch on the GENERATED expectation, not the HTTP status: a void\n // method accepts 204/empty, but an output-bearing method requires a\n // JSON document — empty/null would fabricate a resource outside the\n // declared contract, and malformed JSON must be a stable SDK error.\n if (spec.void) {\n void response.body?.cancel().catch(() => {});\n return undefined as T;\n }\n if (response.status === 204) {\n throw new APIResponseError(204, 'HTTP 204 where a JSON response was expected');\n }\n const text = await raceAbort(response.text(), deadline.signal);\n if (text.trim() === '' || text.trim() === 'null') {\n throw new APIResponseError(\n response.status,\n `HTTP ${response.status} with an empty or null body where a JSON response was expected`,\n );\n }\n try {\n return JSON.parse(text) as T;\n } catch (err) {\n throw new APIResponseError(response.status, 'response body is not valid JSON', err);\n }\n } catch (err) {\n if (deadline.timedOut()) throw new APITimeoutError(deadline.ms);\n throw err;\n } finally {\n deadline.settle();\n deadline.release();\n }\n }\n\n async rawRequest(spec: RequestSpec, options: RequestOptions = {}): Promise<Response> {\n const url = this.buildURL(spec.path, spec.query);\n\n // One Headers instance; `set` is case-insensitive, so later layers\n // OVERRIDE earlier ones regardless of spelling (object spread would keep\n // both `Authorization` and `authorization` and fetch would join the two\n // values into one corrupt header). Precedence: generated defaults →\n // client defaults → auth → per-request → Last-Event-ID (the semantic\n // option is the single source of resume state).\n const headers = new Headers();\n headers.set('Accept', spec.stream ? 'text/event-stream' : 'application/json');\n if (spec.body !== undefined) headers.set('Content-Type', 'application/json');\n for (const [key, value] of Object.entries(this.defaultHeaders)) headers.set(key, value);\n for (const [key, value] of Object.entries(this.authHeader())) headers.set(key, value);\n for (const [key, value] of Object.entries(options.headers ?? {})) headers.set(key, value);\n if (options.lastEventId !== undefined) {\n headers.set('Last-Event-ID', options.lastEventId);\n }\n\n // Serialize ONCE, before the transport/retry loop: a circular object or\n // BigInt is a caller bug, not a network failure — it must surface as a\n // stable request-construction error and never be retried.\n let bodyText: string | undefined;\n if (spec.body !== undefined) {\n try {\n bodyText = JSON.stringify(spec.body);\n } catch (err) {\n throw new APIRequestError('request body is not JSON-serializable', err);\n }\n if (bodyText === undefined) {\n throw new APIRequestError('request body serialized to undefined', undefined);\n }\n }\n\n // Streams bound only connection/response-header acquisition; the body's\n // lifetime stays under the caller's AbortSignal.\n const streamDeadline = spec.stream ? this.deadline(options) : undefined;\n const signal = streamDeadline ? streamDeadline.signal : options.signal;\n\n // An explicit per-request maxRetries opts in even for mutations.\n const maxRetries = normalizeRetries(\n options.maxRetries !== undefined\n ? options.maxRetries\n : IDEMPOTENT_METHODS.has(spec.method)\n ? this.maxRetries\n : 0,\n );\n\n const startedAt = Date.now();\n for (let attempt = 0; ; attempt++) {\n this.logDebug(`-> ${spec.method} ${spec.path}`, attempt > 0 ? `(attempt ${attempt + 1})` : '');\n let response: Response;\n try {\n response = await raceAbort(\n this.fetchFn(url, {\n method: spec.method,\n headers,\n body: bodyText,\n signal: signal ?? null,\n }),\n signal,\n );\n } catch (err) {\n if (streamDeadline?.timedOut()) {\n streamDeadline.settle();\n streamDeadline.release();\n throw new APITimeoutError(streamDeadline.ms);\n }\n if (signal?.aborted) {\n streamDeadline?.settle();\n streamDeadline?.release();\n throw new APIUserAbortError();\n }\n if (attempt < maxRetries) {\n this.logWarn(`retrying ${spec.method} ${spec.path} after connection error (attempt ${attempt + 1}/${maxRetries + 1})`);\n await sleep(backoffMs(attempt, undefined), signal);\n if (streamDeadline?.timedOut()) {\n streamDeadline.settle();\n streamDeadline.release();\n throw new APITimeoutError(streamDeadline.ms);\n }\n if (signal?.aborted) throw new APIUserAbortError();\n continue;\n }\n // Terminal connection failure: the deadline timer must not outlive\n // the reported error (an orphaned timer holds the process open).\n streamDeadline?.settle();\n streamDeadline?.release();\n throw new APIConnectionError(err);\n }\n\n if (response.ok) {\n this.logDebug(`<- ${response.status} ${spec.method} ${spec.path} (${Date.now() - startedAt}ms)`);\n // Response headers acquired: the stream body is now unbounded. The\n // forwarding listener stays attached (caller abort must reach the\n // body); the Stream releases it at its terminal state.\n if (streamDeadline) {\n streamDeadline.settle();\n streamCleanups.set(response, () => streamDeadline.release());\n }\n return response;\n }\n\n if (RETRYABLE_STATUS.has(response.status) && attempt < maxRetries) {\n this.logWarn(`retrying ${spec.method} ${spec.path} after HTTP ${response.status} (attempt ${attempt + 1}/${maxRetries + 1})`);\n // Release the discarded response so its connection can be reused.\n void response.body?.cancel().catch(() => {});\n await sleep(backoffMs(attempt, response.headers.get('retry-after')), signal);\n // A stream deadline that fired during backoff is a timeout, not a\n // user abort — rawRequest has no outer mapper to reclassify it.\n if (streamDeadline?.timedOut()) {\n streamDeadline.settle();\n streamDeadline.release();\n throw new APITimeoutError(streamDeadline.ms);\n }\n if (signal?.aborted) throw new APIUserAbortError();\n continue;\n }\n\n let body: ErrorStatus | undefined;\n try {\n body = (await response.json()) as ErrorStatus;\n } catch {\n body = undefined;\n }\n // The deadline stays active while consuming a non-2xx error body; if\n // it expired there, report the timeout rather than a truncated\n // APIError.\n if (streamDeadline?.timedOut()) {\n streamDeadline.settle();\n streamDeadline.release();\n throw new APITimeoutError(streamDeadline.ms);\n }\n streamDeadline?.settle();\n streamDeadline?.release();\n throw new APIError(response.status, body);\n }\n }\n\n /**\n * Merge the caller's signal with the configured deadline. The caller's\n * abort always forwards; the timer marks timedOut so the thrown error can\n * be classified as APITimeoutError rather than APIUserAbortError.\n */\n private deadline(options: RequestOptions): Deadline {\n const ms = options.timeout ?? this.timeout;\n if (!Number.isFinite(ms) || ms <= 0) {\n return { signal: options.signal, settle() {}, release() {}, timedOut: () => false, ms };\n }\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, ms);\n const forward = () => controller.abort();\n if (options.signal?.aborted) {\n controller.abort();\n } else {\n options.signal?.addEventListener('abort', forward, { once: true });\n }\n let settled = false;\n let released = false;\n return {\n signal: controller.signal,\n settle() {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n },\n release() {\n if (released) return;\n released = true;\n options.signal?.removeEventListener('abort', forward);\n },\n timedOut: () => timedOut,\n ms,\n };\n }\n\n private buildURL(path: string, query?: Record<string, QueryValue>): string {\n const url = new URL(this.baseURL + path);\n const ancestors = new Set<object>();\n for (const [key, value] of Object.entries(query ?? {})) {\n appendQueryValue(url.searchParams, key, value, ancestors);\n }\n return url.toString();\n }\n}\n\n/**\n * Flatten nested query objects to dot-delimited paths. Arrays retain the\n * existing repeated-parameter behavior at whichever path they occur:\n * `{ filters: { state: ['a', 'b'] } }` becomes\n * `?filters.state=a&filters.state=b`.\n */\nfunction appendQueryValue(\n searchParams: URLSearchParams,\n key: string,\n value: unknown,\n ancestors: Set<object>,\n): void {\n if (value === undefined || value === null) return;\n\n if (typeof value !== 'object') {\n searchParams.append(key, String(value));\n return;\n }\n\n if (ancestors.has(value)) {\n throw new APIRequestError('query parameters contain a circular reference', undefined);\n }\n ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n for (const item of value) appendQueryValue(searchParams, key, item, ancestors);\n return;\n }\n\n for (const [childKey, childValue] of Object.entries(value)) {\n appendQueryValue(searchParams, `${key}.${childKey}`, childValue, ancestors);\n }\n } finally {\n ancestors.delete(value);\n }\n}\n\n/** Retry counts must be bounded non-negative integers; anything else (NaN,\n * Infinity, negatives, fractions) is treated as the nearest sane value. */\nfunction normalizeRetries(value: number): number {\n if (!Number.isFinite(value) || value <= 0) return 0;\n return Math.min(Math.floor(value), 10);\n}\n\nfunction backoffMs(attempt: number, retryAfter: string | null | undefined): number {\n if (retryAfter) {\n // Retry-After is either delta-seconds or an HTTP-date. A parsed zero is\n // a real answer (retry immediately), not a fall-through to backoff.\n const seconds = Number(retryAfter);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, 60_000);\n const date = Date.parse(retryAfter);\n if (Number.isFinite(date)) {\n return Math.min(Math.max(date - Date.now(), 0), 60_000);\n }\n }\n const base = 500 * 2 ** Math.min(attempt, 4);\n return Math.min(base + Math.random() * base, 8000);\n}\n\n/** Sleep that wakes early when the signal aborts (caller re-checks it). */\nfunction sleep(ms: number, signal?: AbortSignal | null): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) return resolve();\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n resolve();\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -214,7 +214,7 @@ export interface WidgetErrorEvent {
214
214
  * strings. Tool arguments cross this boundary only when an enabled tool set
215
215
  * overlay explicitly opts the matching tool in.
216
216
  */
217
- export type WidgetEvent = WidgetEvent_UserMessage | WidgetEvent_AssistantMessage | WidgetEvent_ToolApprovalRequested | WidgetEvent_ToolApproved | WidgetEvent_ToolDenied | WidgetEvent_ToolCalled | WidgetEvent_ToolResult | WidgetEvent_ToolError | WidgetEvent_Error | WidgetEvent_Cancelled | WidgetEvent_TimedOut | WidgetEvent_Finalized;
217
+ export type WidgetEvent = WidgetEvent_UserMessage | WidgetEvent_AssistantMessage | WidgetEvent_ToolApprovalRequested | WidgetEvent_ToolApproved | WidgetEvent_ToolDenied | WidgetEvent_ToolCalled | WidgetEvent_ToolResult | WidgetEvent_ToolError | WidgetEvent_Error | WidgetEvent_Cancelled | WidgetEvent_TimedOut | WidgetEvent_Finalized | WidgetEvent_Heartbeat | WidgetEvent_StateChanged;
218
218
  /**
219
219
  * WidgetFinalizedEvent: the conversation's agent produced its structured
220
220
  * output and the objective reached its terminal state. Only agents with an
@@ -229,6 +229,23 @@ export interface WidgetFinalizedEvent {
229
229
  */
230
230
  output?: Record<string, unknown>;
231
231
  }
232
+ /**
233
+ * WidgetHeartbeatEvent mirrors objective heartbeat liveness. It is live-only,
234
+ * absent from history, and never a reconnect checkpoint or state transition.
235
+ */
236
+ export interface WidgetHeartbeatEvent {
237
+ }
238
+ export type WidgetObjectiveStateChangedEventFromState = 'WIDGET_OBJECTIVE_STATE_UNSPECIFIED' | 'WIDGET_OBJECTIVE_STATE_PENDING' | 'WIDGET_OBJECTIVE_STATE_RUNNING' | 'WIDGET_OBJECTIVE_STATE_WAITING' | 'WIDGET_OBJECTIVE_STATE_FAILED' | 'WIDGET_OBJECTIVE_STATE_CANCELLED' | 'WIDGET_OBJECTIVE_STATE_FINALIZED' | 'WIDGET_OBJECTIVE_STATE_TIMED_OUT';
239
+ export type WidgetObjectiveStateChangedEventToState = 'WIDGET_OBJECTIVE_STATE_UNSPECIFIED' | 'WIDGET_OBJECTIVE_STATE_PENDING' | 'WIDGET_OBJECTIVE_STATE_RUNNING' | 'WIDGET_OBJECTIVE_STATE_WAITING' | 'WIDGET_OBJECTIVE_STATE_FAILED' | 'WIDGET_OBJECTIVE_STATE_CANCELLED' | 'WIDGET_OBJECTIVE_STATE_FINALIZED' | 'WIDGET_OBJECTIVE_STATE_TIMED_OUT';
240
+ /**
241
+ * WidgetObjectiveStateChangedEvent mirrors a durable objective transition.
242
+ * Internal status messages are intentionally omitted. Pending/running maps
243
+ * to a responding conversation, waiting to open, and terminal states to closed.
244
+ */
245
+ export interface WidgetObjectiveStateChangedEvent {
246
+ fromState: WidgetObjectiveStateChangedEventFromState;
247
+ toState: WidgetObjectiveStateChangedEventToState;
248
+ }
232
249
  /**
233
250
  * WidgetTimedOutEvent: the conversation timed out after inactivity. Terminal.
234
251
  */
@@ -327,8 +344,9 @@ export interface WidgetEvent_UserMessage {
327
344
  type: 'userMessage';
328
345
  userMessage: WidgetUserMessageEvent;
329
346
  /**
330
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
331
- * `Last-Event-ID` on reconnect to resume without duplication.
347
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
348
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
349
+ * Transient heartbeats carry hb_ IDs in this payload only.
332
350
  */
333
351
  id: string;
334
352
  /**
@@ -341,8 +359,9 @@ export interface WidgetEvent_AssistantMessage {
341
359
  type: 'assistantMessage';
342
360
  assistantMessage: WidgetAssistantMessageEvent;
343
361
  /**
344
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
345
- * `Last-Event-ID` on reconnect to resume without duplication.
362
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
363
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
364
+ * Transient heartbeats carry hb_ IDs in this payload only.
346
365
  */
347
366
  id: string;
348
367
  /**
@@ -355,8 +374,9 @@ export interface WidgetEvent_ToolApprovalRequested {
355
374
  type: 'toolApprovalRequested';
356
375
  toolApprovalRequested: WidgetToolApprovalRequestedEvent;
357
376
  /**
358
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
359
- * `Last-Event-ID` on reconnect to resume without duplication.
377
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
378
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
379
+ * Transient heartbeats carry hb_ IDs in this payload only.
360
380
  */
361
381
  id: string;
362
382
  /**
@@ -369,8 +389,9 @@ export interface WidgetEvent_ToolApproved {
369
389
  type: 'toolApproved';
370
390
  toolApproved: WidgetToolApprovedEvent;
371
391
  /**
372
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
373
- * `Last-Event-ID` on reconnect to resume without duplication.
392
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
393
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
394
+ * Transient heartbeats carry hb_ IDs in this payload only.
374
395
  */
375
396
  id: string;
376
397
  /**
@@ -383,8 +404,9 @@ export interface WidgetEvent_ToolDenied {
383
404
  type: 'toolDenied';
384
405
  toolDenied: WidgetToolDeniedEvent;
385
406
  /**
386
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
387
- * `Last-Event-ID` on reconnect to resume without duplication.
407
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
408
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
409
+ * Transient heartbeats carry hb_ IDs in this payload only.
388
410
  */
389
411
  id: string;
390
412
  /**
@@ -397,8 +419,9 @@ export interface WidgetEvent_ToolCalled {
397
419
  type: 'toolCalled';
398
420
  toolCalled: WidgetToolCalledEvent;
399
421
  /**
400
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
401
- * `Last-Event-ID` on reconnect to resume without duplication.
422
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
423
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
424
+ * Transient heartbeats carry hb_ IDs in this payload only.
402
425
  */
403
426
  id: string;
404
427
  /**
@@ -411,8 +434,9 @@ export interface WidgetEvent_ToolResult {
411
434
  type: 'toolResult';
412
435
  toolResult: WidgetToolResultEvent;
413
436
  /**
414
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
415
- * `Last-Event-ID` on reconnect to resume without duplication.
437
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
438
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
439
+ * Transient heartbeats carry hb_ IDs in this payload only.
416
440
  */
417
441
  id: string;
418
442
  /**
@@ -425,8 +449,9 @@ export interface WidgetEvent_ToolError {
425
449
  type: 'toolError';
426
450
  toolError: WidgetToolErrorEvent;
427
451
  /**
428
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
429
- * `Last-Event-ID` on reconnect to resume without duplication.
452
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
453
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
454
+ * Transient heartbeats carry hb_ IDs in this payload only.
430
455
  */
431
456
  id: string;
432
457
  /**
@@ -439,8 +464,9 @@ export interface WidgetEvent_Error {
439
464
  type: 'error';
440
465
  error: WidgetErrorEvent;
441
466
  /**
442
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
443
- * `Last-Event-ID` on reconnect to resume without duplication.
467
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
468
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
469
+ * Transient heartbeats carry hb_ IDs in this payload only.
444
470
  */
445
471
  id: string;
446
472
  /**
@@ -453,8 +479,9 @@ export interface WidgetEvent_Cancelled {
453
479
  type: 'cancelled';
454
480
  cancelled: WidgetCancelledEvent;
455
481
  /**
456
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
457
- * `Last-Event-ID` on reconnect to resume without duplication.
482
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
483
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
484
+ * Transient heartbeats carry hb_ IDs in this payload only.
458
485
  */
459
486
  id: string;
460
487
  /**
@@ -467,8 +494,9 @@ export interface WidgetEvent_TimedOut {
467
494
  type: 'timedOut';
468
495
  timedOut: WidgetTimedOutEvent;
469
496
  /**
470
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
471
- * `Last-Event-ID` on reconnect to resume without duplication.
497
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
498
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
499
+ * Transient heartbeats carry hb_ IDs in this payload only.
472
500
  */
473
501
  id: string;
474
502
  /**
@@ -481,8 +509,39 @@ export interface WidgetEvent_Finalized {
481
509
  type: 'finalized';
482
510
  finalized: WidgetFinalizedEvent;
483
511
  /**
484
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
485
- * `Last-Event-ID` on reconnect to resume without duplication.
512
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
513
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
514
+ * Transient heartbeats carry hb_ IDs in this payload only.
515
+ */
516
+ id: string;
517
+ /**
518
+ * The conversation this event belongs to.
519
+ */
520
+ conversationId: string;
521
+ createdAt: string;
522
+ }
523
+ export interface WidgetEvent_Heartbeat {
524
+ type: 'heartbeat';
525
+ heartbeat: WidgetHeartbeatEvent;
526
+ /**
527
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
528
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
529
+ * Transient heartbeats carry hb_ IDs in this payload only.
530
+ */
531
+ id: string;
532
+ /**
533
+ * The conversation this event belongs to.
534
+ */
535
+ conversationId: string;
536
+ createdAt: string;
537
+ }
538
+ export interface WidgetEvent_StateChanged {
539
+ type: 'stateChanged';
540
+ stateChanged: WidgetObjectiveStateChangedEvent;
541
+ /**
542
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
543
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
544
+ * Transient heartbeats carry hb_ IDs in this payload only.
486
545
  */
487
546
  id: string;
488
547
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,2BAA2B;IAC1C;;OAEG;IACH,E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B;;;;OAIG;IACH,EAAE,EAAE,MAAM,CAAC;IACX;;OAEG;IACH,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,WAAW,CAAC;IAClB,SAAS,EAAE,oBAAoB,CAAC;IAChC;;;;OAIG;IACH,EAAE,EAAE,MAAM,CAAC;IACX;;OAEG;IACH,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,WAAW,CAAC;IAClB,SAAS,EAAE,oBAAoB,CAAC;IAChC;;;;OAIG;IACH,EAAE,EAAE,MAAM,CAAC;IACX;;OAEG;IACH,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,cAAc,CAAC;IACrB,YAAY,EAAE,gCAAgC,CAAC;IAC/C;;;;OAIG;IACH,EAAE,EAAE,MAAM,CAAC;IACX;;OAEG;IACH,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,6CAA6C","sourcesContent":["// Generated by redwood. Do not edit by hand.\n\n/**\n * Approve tool call request. Responds to a toolApprovalRequested event.\n */\nexport interface ApproveToolCallRequest {\n /**\n * Conversation ID.\n */\n id?: string;\n /**\n * The tool call awaiting a decision, from the toolApprovalRequested event.\n */\n toolCallId?: string;\n}\n\n/**\n * Continue conversation request.\n */\nexport interface ContinueConversationRequest {\n /**\n * Conversation ID.\n */\n id?: string;\n /**\n * The visitor's next message.\n */\n message: string;\n}\n\n/**\n * Create conversation request. The session, tenant, subject, secrets, labels,\n * and pinned parameters all come from the presenting token's session — the\n * browser asserts nothing.\n */\nexport interface CreateConversationRequest {\n /**\n * The visitor's opening message.\n */\n message: string;\n}\n\n/**\n * Deny tool call request. Responds to a toolApprovalRequested event.\n */\nexport interface DenyToolCallRequest {\n /**\n * Conversation ID.\n */\n id?: string;\n /**\n * The tool call awaiting a decision, from the toolApprovalRequested event.\n */\n toolCallId?: string;\n}\n\n/**\n * Contains an arbitrary serialized message along with a @type that describes the type of the serialized message.\n */\nexport interface GoogleProtobufAny {\n /**\n * The type of the serialized message.\n */\n '@type'?: string;\n}\n\n/**\n * Represents a dynamically typed value which can be either null, a number, a string, a boolean, a recursive struct value, or a list of values.\n */\nexport type GoogleProtobufValue = unknown;\n\n/**\n * List conversation events response. Ordered oldest first.\n */\nexport interface ListConversationEventsResponse {\n items?: Array<WidgetEvent>;\n pagination?: Page;\n}\n\n/**\n * List conversations response. Ordered by last activity, newest first.\n */\nexport interface ListConversationsResponse {\n items?: Array<WidgetConversation>;\n pagination?: Page;\n}\n\n/**\n * Page carries pagination data for list responses. A deliberate local\n * duplicate of the api module's Page — this package imports nothing from\n * cadenya.api.v1 (see the workspace README).\n */\nexport interface Page {\n /**\n * Cursor for the next page. Empty when there are no further results.\n */\n nextCursor?: string;\n /**\n * Total number of items matching the request.\n */\n total?: number;\n}\n\n/**\n * Set tool call content request. Lets the embedding page supply the result\n * of a bare tool call (one whose tool set has no execution adapter) — the\n * widget-session flavor of the reverse-harness pattern, where client-side\n * logic executes the tool and reports the result back. The result then\n * reaches the conversation as a toolResult event.\n */\nexport interface SetToolCallContentRequest {\n /**\n * Conversation ID.\n */\n id?: string;\n /**\n * The bare tool call to supply content for.\n */\n toolCallId?: string;\n /**\n * The tool call's result content.\n */\n content: string;\n}\n\n/**\n * The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).\n */\nexport interface Status {\n /**\n * The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code].\n */\n code?: number;\n /**\n * A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client.\n */\n message?: string;\n /**\n * A list of messages that carry the error details. There is a common set of message types for APIs to use.\n */\n details?: Array<GoogleProtobufAny>;\n}\n\n/**\n * Submit conversation feedback request — the visitor's rating of a\n * conversation, mirroring internal objective feedback in slimmed form. Flows\n * into the same feedback machinery that scores agent variations.\n */\nexport interface SubmitConversationFeedbackRequest {\n /**\n * Conversation ID.\n */\n id?: string;\n /**\n * A score between -1.0 and 1.0. -1.0 is the worst, 0.0 neutral, 1.0 the\n * best — a thumbs-down/up UI maps to -1.0/1.0.\n */\n score: number;\n /**\n * Optional comment explaining the feedback.\n */\n comment?: string;\n}\n\n/**\n * WidgetAssistantMessageEvent is a message from the agent. Content may\n * arrive incrementally: later events for the same turn replace earlier\n * partial content.\n */\nexport interface WidgetAssistantMessageEvent {\n content: string;\n}\n\n/**\n * WidgetCancelledEvent: the conversation was cancelled. Terminal.\n */\nexport interface WidgetCancelledEvent {\n}\n\n/**\n * WidgetConfig is the widget's presentation configuration, served to the\n * browser before any session exists. Contains nothing sensitive: the widget\n * is identified by the hostname, and the edge has already enforced the\n * origin allowlist by the time this is served.\n */\nexport interface WidgetConfig {\n /**\n * Display name shown in the widget header.\n */\n displayName: string;\n}\n\nexport type WidgetConversationState = 'STATE_UNSPECIFIED' | 'STATE_RESPONDING' | 'STATE_OPEN' | 'STATE_CLOSED';\n\n/**\n * WidgetConversation is one conversation between the session's visitor and\n * the widget's agent. Conversations are scoped by the presenting token to the\n * VISITOR: a session with a subject sees that subject's conversations on this\n * widget; a session without one sees only the conversations it created\n * itself. A conversation id from outside that scope is indistinguishable from\n * one that does not exist. Tenant is a management-side grouping only — it is\n * never a read scope on this surface.\n */\nexport interface WidgetConversation {\n id: string;\n state: WidgetConversationState;\n /**\n * Server-derived display title (e.g. from the opening message).\n */\n title?: string;\n createdAt: string;\n /**\n * When the conversation last saw a message or event.\n */\n lastActiveAt?: string;\n}\n\n/**\n * WidgetErrorEvent reports a visitor-safe conversation error. The message is\n * sanitized; internal error detail never reaches the widget.\n */\nexport interface WidgetErrorEvent {\n message: string;\n}\n\n/**\n * WidgetEvent is the visitor-facing event vocabulary. It MIRRORS the internal\n * conversation event variants — same granularity, same discriminator names —\n * with slimmed messages holding exactly what a widget UI needs. Internal\n * events map to these through an explicit, exhaustive server-side projection;\n * internal-only types (context compaction, memory reads, sub-agent\n * bookkeeping) have no widget variant and are dropped. Nothing here carries\n * tool configuration, server identities, operator details, or internal error\n * strings. Tool arguments cross this boundary only when an enabled tool set\n * overlay explicitly opts the matching tool in.\n */\nexport type WidgetEvent =\n | WidgetEvent_UserMessage\n | WidgetEvent_AssistantMessage\n | WidgetEvent_ToolApprovalRequested\n | WidgetEvent_ToolApproved\n | WidgetEvent_ToolDenied\n | WidgetEvent_ToolCalled\n | WidgetEvent_ToolResult\n | WidgetEvent_ToolError\n | WidgetEvent_Error\n | WidgetEvent_Cancelled\n | WidgetEvent_TimedOut\n | WidgetEvent_Finalized;\n\n/**\n * WidgetFinalizedEvent: the conversation's agent produced its structured\n * output and the objective reached its terminal state. Only agents with an\n * output definition finalize — such an agent ends the conversation after one\n * turn, so a widget bound to one should treat this as the answer, not a\n * message to keep chatting past.\n */\nexport interface WidgetFinalizedEvent {\n /**\n * The structured output the agent produced, matching the shape of the\n * agent's output definition schema.\n */\n output?: Record<string, unknown>;\n}\n\n/**\n * WidgetTimedOutEvent: the conversation timed out after inactivity. Terminal.\n */\nexport interface WidgetTimedOutEvent {\n}\n\n/**\n * WidgetToolApprovalRequestedEvent asks the visitor to approve or deny a\n * tool call before it runs. The tool reference lets the embedding UI render\n * a custom approval experience per tool; the visitor responds via the\n * approve/deny endpoints.\n */\nexport interface WidgetToolApprovalRequestedEvent {\n /**\n * The tool call awaiting a decision; pass it to the approve/deny endpoint.\n */\n toolCallId: string;\n tool: WidgetToolReference;\n}\n\n/**\n * WidgetToolApprovedEvent records that the pending tool call was approved.\n */\nexport interface WidgetToolApprovedEvent {\n toolCallId: string;\n}\n\n/**\n * WidgetToolCalledEvent reports that the agent invoked a tool.\n */\nexport interface WidgetToolCalledEvent {\n toolCallId: string;\n tool: WidgetToolReference;\n /**\n * The final arguments sent to the tool, after parameter actions were\n * applied. Present only when an enabled matching tool set overlay opts the\n * tool into exposing arguments in widget sessions. Arguments are omitted\n * by default because they may contain sensitive customer data.\n */\n arguments?: Record<string, unknown>;\n}\n\n/**\n * WidgetToolDeniedEvent records that the pending tool call was denied.\n */\nexport interface WidgetToolDeniedEvent {\n toolCallId: string;\n}\n\n/**\n * WidgetToolErrorEvent reports that a tool call failed. Internal error\n * detail never reaches the widget.\n */\nexport interface WidgetToolErrorEvent {\n toolCallId: string;\n tool: WidgetToolReference;\n}\n\n/**\n * WidgetToolReference identifies the tool involved in a tool event — enough\n * for the embedding UI to label the activity and to register custom\n * renderers keyed by the tool's id or the customer's own external id.\n * Deliberately omitted: tool configuration, adapter details, and any server\n * identity.\n */\nexport interface WidgetToolReference {\n /**\n * Cadenya's canonical tool id.\n */\n id: string;\n /**\n * The tool's external id in the customer's namespace, when set.\n */\n externalId?: string;\n /**\n * The tool's name as the workspace configured it (e.g. \"FetchOrderDetails\").\n */\n name: string;\n}\n\n/**\n * WidgetToolResultEvent reports that a tool call finished. Result content is\n * omitted by default and included only for tools the workspace has opted in\n * to sharing content with widget sessions.\n */\nexport interface WidgetToolResultEvent {\n toolCallId: string;\n tool: WidgetToolReference;\n /**\n * The tool's result, present only for tools opted in to sharing content\n * with widget sessions (a per-tool setting; default off). Arbitrary JSON\n * the embedding UI may render — chart data, cards, structured results.\n */\n content?: GoogleProtobufValue;\n}\n\n/**\n * WidgetUserMessageEvent is a message from the visitor.\n */\nexport interface WidgetUserMessageEvent {\n content: string;\n}\n\nexport interface WidgetEvent_UserMessage {\n type: 'userMessage';\n userMessage: WidgetUserMessageEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_AssistantMessage {\n type: 'assistantMessage';\n assistantMessage: WidgetAssistantMessageEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolApprovalRequested {\n type: 'toolApprovalRequested';\n toolApprovalRequested: WidgetToolApprovalRequestedEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolApproved {\n type: 'toolApproved';\n toolApproved: WidgetToolApprovedEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolDenied {\n type: 'toolDenied';\n toolDenied: WidgetToolDeniedEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolCalled {\n type: 'toolCalled';\n toolCalled: WidgetToolCalledEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolResult {\n type: 'toolResult';\n toolResult: WidgetToolResultEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolError {\n type: 'toolError';\n toolError: WidgetToolErrorEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_Error {\n type: 'error';\n error: WidgetErrorEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_Cancelled {\n type: 'cancelled';\n cancelled: WidgetCancelledEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_TimedOut {\n type: 'timedOut';\n timedOut: WidgetTimedOutEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_Finalized {\n type: 'finalized';\n finalized: WidgetFinalizedEvent;\n /**\n * Unique event id (ULID). Doubles as the SSE `id:` — replay it as\n * `Last-Event-ID` on reconnect to resume without duplication.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,6CAA6C","sourcesContent":["// Generated by redwood. Do not edit by hand.\n\n/**\n * Approve tool call request. Responds to a toolApprovalRequested event.\n */\nexport interface ApproveToolCallRequest {\n /**\n * Conversation ID.\n */\n id?: string;\n /**\n * The tool call awaiting a decision, from the toolApprovalRequested event.\n */\n toolCallId?: string;\n}\n\n/**\n * Continue conversation request.\n */\nexport interface ContinueConversationRequest {\n /**\n * Conversation ID.\n */\n id?: string;\n /**\n * The visitor's next message.\n */\n message: string;\n}\n\n/**\n * Create conversation request. The session, tenant, subject, secrets, labels,\n * and pinned parameters all come from the presenting token's session — the\n * browser asserts nothing.\n */\nexport interface CreateConversationRequest {\n /**\n * The visitor's opening message.\n */\n message: string;\n}\n\n/**\n * Deny tool call request. Responds to a toolApprovalRequested event.\n */\nexport interface DenyToolCallRequest {\n /**\n * Conversation ID.\n */\n id?: string;\n /**\n * The tool call awaiting a decision, from the toolApprovalRequested event.\n */\n toolCallId?: string;\n}\n\n/**\n * Contains an arbitrary serialized message along with a @type that describes the type of the serialized message.\n */\nexport interface GoogleProtobufAny {\n /**\n * The type of the serialized message.\n */\n '@type'?: string;\n}\n\n/**\n * Represents a dynamically typed value which can be either null, a number, a string, a boolean, a recursive struct value, or a list of values.\n */\nexport type GoogleProtobufValue = unknown;\n\n/**\n * List conversation events response. Ordered oldest first.\n */\nexport interface ListConversationEventsResponse {\n items?: Array<WidgetEvent>;\n pagination?: Page;\n}\n\n/**\n * List conversations response. Ordered by last activity, newest first.\n */\nexport interface ListConversationsResponse {\n items?: Array<WidgetConversation>;\n pagination?: Page;\n}\n\n/**\n * Page carries pagination data for list responses. A deliberate local\n * duplicate of the api module's Page — this package imports nothing from\n * cadenya.api.v1 (see the workspace README).\n */\nexport interface Page {\n /**\n * Cursor for the next page. Empty when there are no further results.\n */\n nextCursor?: string;\n /**\n * Total number of items matching the request.\n */\n total?: number;\n}\n\n/**\n * Set tool call content request. Lets the embedding page supply the result\n * of a bare tool call (one whose tool set has no execution adapter) — the\n * widget-session flavor of the reverse-harness pattern, where client-side\n * logic executes the tool and reports the result back. The result then\n * reaches the conversation as a toolResult event.\n */\nexport interface SetToolCallContentRequest {\n /**\n * Conversation ID.\n */\n id?: string;\n /**\n * The bare tool call to supply content for.\n */\n toolCallId?: string;\n /**\n * The tool call's result content.\n */\n content: string;\n}\n\n/**\n * The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).\n */\nexport interface Status {\n /**\n * The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code].\n */\n code?: number;\n /**\n * A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client.\n */\n message?: string;\n /**\n * A list of messages that carry the error details. There is a common set of message types for APIs to use.\n */\n details?: Array<GoogleProtobufAny>;\n}\n\n/**\n * Submit conversation feedback request — the visitor's rating of a\n * conversation, mirroring internal objective feedback in slimmed form. Flows\n * into the same feedback machinery that scores agent variations.\n */\nexport interface SubmitConversationFeedbackRequest {\n /**\n * Conversation ID.\n */\n id?: string;\n /**\n * A score between -1.0 and 1.0. -1.0 is the worst, 0.0 neutral, 1.0 the\n * best — a thumbs-down/up UI maps to -1.0/1.0.\n */\n score: number;\n /**\n * Optional comment explaining the feedback.\n */\n comment?: string;\n}\n\n/**\n * WidgetAssistantMessageEvent is a message from the agent. Content may\n * arrive incrementally: later events for the same turn replace earlier\n * partial content.\n */\nexport interface WidgetAssistantMessageEvent {\n content: string;\n}\n\n/**\n * WidgetCancelledEvent: the conversation was cancelled. Terminal.\n */\nexport interface WidgetCancelledEvent {\n}\n\n/**\n * WidgetConfig is the widget's presentation configuration, served to the\n * browser before any session exists. Contains nothing sensitive: the widget\n * is identified by the hostname, and the edge has already enforced the\n * origin allowlist by the time this is served.\n */\nexport interface WidgetConfig {\n /**\n * Display name shown in the widget header.\n */\n displayName: string;\n}\n\nexport type WidgetConversationState = 'STATE_UNSPECIFIED' | 'STATE_RESPONDING' | 'STATE_OPEN' | 'STATE_CLOSED';\n\n/**\n * WidgetConversation is one conversation between the session's visitor and\n * the widget's agent. Conversations are scoped by the presenting token to the\n * VISITOR: a session with a subject sees that subject's conversations on this\n * widget; a session without one sees only the conversations it created\n * itself. A conversation id from outside that scope is indistinguishable from\n * one that does not exist. Tenant is a management-side grouping only — it is\n * never a read scope on this surface.\n */\nexport interface WidgetConversation {\n id: string;\n state: WidgetConversationState;\n /**\n * Server-derived display title (e.g. from the opening message).\n */\n title?: string;\n createdAt: string;\n /**\n * When the conversation last saw a message or event.\n */\n lastActiveAt?: string;\n}\n\n/**\n * WidgetErrorEvent reports a visitor-safe conversation error. The message is\n * sanitized; internal error detail never reaches the widget.\n */\nexport interface WidgetErrorEvent {\n message: string;\n}\n\n/**\n * WidgetEvent is the visitor-facing event vocabulary. It MIRRORS the internal\n * conversation event variants — same granularity, same discriminator names —\n * with slimmed messages holding exactly what a widget UI needs. Internal\n * events map to these through an explicit, exhaustive server-side projection;\n * internal-only types (context compaction, memory reads, sub-agent\n * bookkeeping) have no widget variant and are dropped. Nothing here carries\n * tool configuration, server identities, operator details, or internal error\n * strings. Tool arguments cross this boundary only when an enabled tool set\n * overlay explicitly opts the matching tool in.\n */\nexport type WidgetEvent =\n | WidgetEvent_UserMessage\n | WidgetEvent_AssistantMessage\n | WidgetEvent_ToolApprovalRequested\n | WidgetEvent_ToolApproved\n | WidgetEvent_ToolDenied\n | WidgetEvent_ToolCalled\n | WidgetEvent_ToolResult\n | WidgetEvent_ToolError\n | WidgetEvent_Error\n | WidgetEvent_Cancelled\n | WidgetEvent_TimedOut\n | WidgetEvent_Finalized\n | WidgetEvent_Heartbeat\n | WidgetEvent_StateChanged;\n\n/**\n * WidgetFinalizedEvent: the conversation's agent produced its structured\n * output and the objective reached its terminal state. Only agents with an\n * output definition finalize — such an agent ends the conversation after one\n * turn, so a widget bound to one should treat this as the answer, not a\n * message to keep chatting past.\n */\nexport interface WidgetFinalizedEvent {\n /**\n * The structured output the agent produced, matching the shape of the\n * agent's output definition schema.\n */\n output?: Record<string, unknown>;\n}\n\n/**\n * WidgetHeartbeatEvent mirrors objective heartbeat liveness. It is live-only,\n * absent from history, and never a reconnect checkpoint or state transition.\n */\nexport interface WidgetHeartbeatEvent {\n}\n\nexport type WidgetObjectiveStateChangedEventFromState = 'WIDGET_OBJECTIVE_STATE_UNSPECIFIED' | 'WIDGET_OBJECTIVE_STATE_PENDING' | 'WIDGET_OBJECTIVE_STATE_RUNNING' | 'WIDGET_OBJECTIVE_STATE_WAITING' | 'WIDGET_OBJECTIVE_STATE_FAILED' | 'WIDGET_OBJECTIVE_STATE_CANCELLED' | 'WIDGET_OBJECTIVE_STATE_FINALIZED' | 'WIDGET_OBJECTIVE_STATE_TIMED_OUT';\n\nexport type WidgetObjectiveStateChangedEventToState = 'WIDGET_OBJECTIVE_STATE_UNSPECIFIED' | 'WIDGET_OBJECTIVE_STATE_PENDING' | 'WIDGET_OBJECTIVE_STATE_RUNNING' | 'WIDGET_OBJECTIVE_STATE_WAITING' | 'WIDGET_OBJECTIVE_STATE_FAILED' | 'WIDGET_OBJECTIVE_STATE_CANCELLED' | 'WIDGET_OBJECTIVE_STATE_FINALIZED' | 'WIDGET_OBJECTIVE_STATE_TIMED_OUT';\n\n/**\n * WidgetObjectiveStateChangedEvent mirrors a durable objective transition.\n * Internal status messages are intentionally omitted. Pending/running maps\n * to a responding conversation, waiting to open, and terminal states to closed.\n */\nexport interface WidgetObjectiveStateChangedEvent {\n fromState: WidgetObjectiveStateChangedEventFromState;\n toState: WidgetObjectiveStateChangedEventToState;\n}\n\n/**\n * WidgetTimedOutEvent: the conversation timed out after inactivity. Terminal.\n */\nexport interface WidgetTimedOutEvent {\n}\n\n/**\n * WidgetToolApprovalRequestedEvent asks the visitor to approve or deny a\n * tool call before it runs. The tool reference lets the embedding UI render\n * a custom approval experience per tool; the visitor responds via the\n * approve/deny endpoints.\n */\nexport interface WidgetToolApprovalRequestedEvent {\n /**\n * The tool call awaiting a decision; pass it to the approve/deny endpoint.\n */\n toolCallId: string;\n tool: WidgetToolReference;\n}\n\n/**\n * WidgetToolApprovedEvent records that the pending tool call was approved.\n */\nexport interface WidgetToolApprovedEvent {\n toolCallId: string;\n}\n\n/**\n * WidgetToolCalledEvent reports that the agent invoked a tool.\n */\nexport interface WidgetToolCalledEvent {\n toolCallId: string;\n tool: WidgetToolReference;\n /**\n * The final arguments sent to the tool, after parameter actions were\n * applied. Present only when an enabled matching tool set overlay opts the\n * tool into exposing arguments in widget sessions. Arguments are omitted\n * by default because they may contain sensitive customer data.\n */\n arguments?: Record<string, unknown>;\n}\n\n/**\n * WidgetToolDeniedEvent records that the pending tool call was denied.\n */\nexport interface WidgetToolDeniedEvent {\n toolCallId: string;\n}\n\n/**\n * WidgetToolErrorEvent reports that a tool call failed. Internal error\n * detail never reaches the widget.\n */\nexport interface WidgetToolErrorEvent {\n toolCallId: string;\n tool: WidgetToolReference;\n}\n\n/**\n * WidgetToolReference identifies the tool involved in a tool event — enough\n * for the embedding UI to label the activity and to register custom\n * renderers keyed by the tool's id or the customer's own external id.\n * Deliberately omitted: tool configuration, adapter details, and any server\n * identity.\n */\nexport interface WidgetToolReference {\n /**\n * Cadenya's canonical tool id.\n */\n id: string;\n /**\n * The tool's external id in the customer's namespace, when set.\n */\n externalId?: string;\n /**\n * The tool's name as the workspace configured it (e.g. \"FetchOrderDetails\").\n */\n name: string;\n}\n\n/**\n * WidgetToolResultEvent reports that a tool call finished. Result content is\n * omitted by default and included only for tools the workspace has opted in\n * to sharing content with widget sessions.\n */\nexport interface WidgetToolResultEvent {\n toolCallId: string;\n tool: WidgetToolReference;\n /**\n * The tool's result, present only for tools opted in to sharing content\n * with widget sessions (a per-tool setting; default off). Arbitrary JSON\n * the embedding UI may render — chart data, cards, structured results.\n */\n content?: GoogleProtobufValue;\n}\n\n/**\n * WidgetUserMessageEvent is a message from the visitor.\n */\nexport interface WidgetUserMessageEvent {\n content: string;\n}\n\nexport interface WidgetEvent_UserMessage {\n type: 'userMessage';\n userMessage: WidgetUserMessageEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_AssistantMessage {\n type: 'assistantMessage';\n assistantMessage: WidgetAssistantMessageEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolApprovalRequested {\n type: 'toolApprovalRequested';\n toolApprovalRequested: WidgetToolApprovalRequestedEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolApproved {\n type: 'toolApproved';\n toolApproved: WidgetToolApprovedEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolDenied {\n type: 'toolDenied';\n toolDenied: WidgetToolDeniedEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolCalled {\n type: 'toolCalled';\n toolCalled: WidgetToolCalledEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolResult {\n type: 'toolResult';\n toolResult: WidgetToolResultEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_ToolError {\n type: 'toolError';\n toolError: WidgetToolErrorEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_Error {\n type: 'error';\n error: WidgetErrorEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_Cancelled {\n type: 'cancelled';\n cancelled: WidgetCancelledEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_TimedOut {\n type: 'timedOut';\n timedOut: WidgetTimedOutEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_Finalized {\n type: 'finalized';\n finalized: WidgetFinalizedEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_Heartbeat {\n type: 'heartbeat';\n heartbeat: WidgetHeartbeatEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\nexport interface WidgetEvent_StateChanged {\n type: 'stateChanged';\n stateChanged: WidgetObjectiveStateChangedEvent;\n /**\n * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted\n * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.\n * Transient heartbeats carry hb_ IDs in this payload only.\n */\n id: string;\n /**\n * The conversation this event belongs to.\n */\n conversationId: string;\n createdAt: string;\n}\n\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cadenya/widgets",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "The official TypeScript SDK for the CadenyaWidgets API",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -13,12 +13,21 @@
13
13
  }
14
14
  },
15
15
  "sideEffects": false,
16
- "publishConfig": { "access": "public" },
17
- "repository": { "type": "git", "url": "https://github.com/cadenya/widgets-sdk" },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/cadenya/widgets-sdk"
22
+ },
18
23
  "engines": {
19
24
  "node": ">=18"
20
25
  },
21
- "files": ["dist", "src", "api.md"],
26
+ "files": [
27
+ "dist",
28
+ "src",
29
+ "api.md"
30
+ ],
22
31
  "scripts": {
23
32
  "build": "tsc",
24
33
  "typecheck": "tsc --noEmit"
package/src/client.ts CHANGED
@@ -19,7 +19,7 @@ export interface ClientOptions {
19
19
  * Defaults to 60000; a non-finite or <= 0 value disables the deadline.
20
20
  */
21
21
  timeout?: number;
22
- /** Headers sent with every request. */
22
+ /** Additional request headers. Browsers supply their own User-Agent by default. */
23
23
  defaultHeaders?: Record<string, string>;
24
24
  /** Custom fetch implementation. */
25
25
  fetch?: typeof fetch;
@@ -49,7 +49,7 @@ export class CadenyaWidgets {
49
49
  authHeader: () => ({ Authorization: `Bearer ${apiKey}` }),
50
50
  maxRetries: options.maxRetries ?? 0,
51
51
  timeout: options.timeout,
52
- defaultHeaders: { 'User-Agent': 'cadenyawidgets-typescript/1.1.0 (api 1.0)', ...options.defaultHeaders },
52
+ defaultHeaders: { ...nodeUserAgent('cadenyawidgets-typescript/1.1.1 (api 1.0)'), ...options.defaultHeaders },
53
53
  fetch: options.fetch,
54
54
  logger: options.logger,
55
55
  logLevel: options.logLevel,
@@ -60,6 +60,14 @@ export class CadenyaWidgets {
60
60
  }
61
61
  }
62
62
 
63
+ // Browser-authored User-Agent headers require CORS permission. Only Node-compatible
64
+ // runtimes receive the SDK default; browsers and workers use their native header.
65
+ function nodeUserAgent(value: string): Record<string, string> {
66
+ const nodeVersion = (globalThis as { process?: { versions?: { node?: string } } })
67
+ .process?.versions?.node;
68
+ return nodeVersion ? { 'User-Agent': value } : {};
69
+ }
70
+
63
71
  function readEnv(name: string): string | undefined {
64
72
  const env = (globalThis as { process?: { env?: Record<string, string | undefined> } })
65
73
  .process?.env;
package/src/core/http.ts CHANGED
@@ -38,7 +38,12 @@ export interface RequestOptions {
38
38
  }
39
39
 
40
40
  export type QueryPrimitive = string | number | boolean;
41
- export type QueryValue = QueryPrimitive | QueryPrimitive[] | undefined | null;
41
+ /**
42
+ * Query objects are flattened to dot-delimited paths. `object` is used here
43
+ * deliberately so generated named interfaces (which do not declare an index
44
+ * signature) remain assignable as query parameter values.
45
+ */
46
+ export type QueryValue = QueryPrimitive | readonly QueryPrimitive[] | object | undefined | null;
42
47
 
43
48
  export interface RequestSpec {
44
49
  method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
@@ -589,17 +594,51 @@ export class HttpClient {
589
594
 
590
595
  private buildURL(path: string, query?: Record<string, QueryValue>): string {
591
596
  const url = new URL(this.baseURL + path);
597
+ const ancestors = new Set<object>();
592
598
  for (const [key, value] of Object.entries(query ?? {})) {
593
- if (value === undefined || value === null) continue;
594
- // Arrays serialize as repeated params: ?state=a&state=b
595
- for (const item of Array.isArray(value) ? value : [value]) {
596
- url.searchParams.append(key, String(item));
597
- }
599
+ appendQueryValue(url.searchParams, key, value, ancestors);
598
600
  }
599
601
  return url.toString();
600
602
  }
601
603
  }
602
604
 
605
+ /**
606
+ * Flatten nested query objects to dot-delimited paths. Arrays retain the
607
+ * existing repeated-parameter behavior at whichever path they occur:
608
+ * `{ filters: { state: ['a', 'b'] } }` becomes
609
+ * `?filters.state=a&filters.state=b`.
610
+ */
611
+ function appendQueryValue(
612
+ searchParams: URLSearchParams,
613
+ key: string,
614
+ value: unknown,
615
+ ancestors: Set<object>,
616
+ ): void {
617
+ if (value === undefined || value === null) return;
618
+
619
+ if (typeof value !== 'object') {
620
+ searchParams.append(key, String(value));
621
+ return;
622
+ }
623
+
624
+ if (ancestors.has(value)) {
625
+ throw new APIRequestError('query parameters contain a circular reference', undefined);
626
+ }
627
+ ancestors.add(value);
628
+ try {
629
+ if (Array.isArray(value)) {
630
+ for (const item of value) appendQueryValue(searchParams, key, item, ancestors);
631
+ return;
632
+ }
633
+
634
+ for (const [childKey, childValue] of Object.entries(value)) {
635
+ appendQueryValue(searchParams, `${key}.${childKey}`, childValue, ancestors);
636
+ }
637
+ } finally {
638
+ ancestors.delete(value);
639
+ }
640
+ }
641
+
603
642
  /** Retry counts must be bounded non-negative integers; anything else (NaN,
604
643
  * Infinity, negatives, fractions) is treated as the nearest sane value. */
605
644
  function normalizeRetries(value: number): number {
package/src/types.ts CHANGED
@@ -246,7 +246,9 @@ export type WidgetEvent =
246
246
  | WidgetEvent_Error
247
247
  | WidgetEvent_Cancelled
248
248
  | WidgetEvent_TimedOut
249
- | WidgetEvent_Finalized;
249
+ | WidgetEvent_Finalized
250
+ | WidgetEvent_Heartbeat
251
+ | WidgetEvent_StateChanged;
250
252
 
251
253
  /**
252
254
  * WidgetFinalizedEvent: the conversation's agent produced its structured
@@ -263,6 +265,27 @@ export interface WidgetFinalizedEvent {
263
265
  output?: Record<string, unknown>;
264
266
  }
265
267
 
268
+ /**
269
+ * WidgetHeartbeatEvent mirrors objective heartbeat liveness. It is live-only,
270
+ * absent from history, and never a reconnect checkpoint or state transition.
271
+ */
272
+ export interface WidgetHeartbeatEvent {
273
+ }
274
+
275
+ export type WidgetObjectiveStateChangedEventFromState = 'WIDGET_OBJECTIVE_STATE_UNSPECIFIED' | 'WIDGET_OBJECTIVE_STATE_PENDING' | 'WIDGET_OBJECTIVE_STATE_RUNNING' | 'WIDGET_OBJECTIVE_STATE_WAITING' | 'WIDGET_OBJECTIVE_STATE_FAILED' | 'WIDGET_OBJECTIVE_STATE_CANCELLED' | 'WIDGET_OBJECTIVE_STATE_FINALIZED' | 'WIDGET_OBJECTIVE_STATE_TIMED_OUT';
276
+
277
+ export type WidgetObjectiveStateChangedEventToState = 'WIDGET_OBJECTIVE_STATE_UNSPECIFIED' | 'WIDGET_OBJECTIVE_STATE_PENDING' | 'WIDGET_OBJECTIVE_STATE_RUNNING' | 'WIDGET_OBJECTIVE_STATE_WAITING' | 'WIDGET_OBJECTIVE_STATE_FAILED' | 'WIDGET_OBJECTIVE_STATE_CANCELLED' | 'WIDGET_OBJECTIVE_STATE_FINALIZED' | 'WIDGET_OBJECTIVE_STATE_TIMED_OUT';
278
+
279
+ /**
280
+ * WidgetObjectiveStateChangedEvent mirrors a durable objective transition.
281
+ * Internal status messages are intentionally omitted. Pending/running maps
282
+ * to a responding conversation, waiting to open, and terminal states to closed.
283
+ */
284
+ export interface WidgetObjectiveStateChangedEvent {
285
+ fromState: WidgetObjectiveStateChangedEventFromState;
286
+ toState: WidgetObjectiveStateChangedEventToState;
287
+ }
288
+
266
289
  /**
267
290
  * WidgetTimedOutEvent: the conversation timed out after inactivity. Terminal.
268
291
  */
@@ -370,8 +393,9 @@ export interface WidgetEvent_UserMessage {
370
393
  type: 'userMessage';
371
394
  userMessage: WidgetUserMessageEvent;
372
395
  /**
373
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
374
- * `Last-Event-ID` on reconnect to resume without duplication.
396
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
397
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
398
+ * Transient heartbeats carry hb_ IDs in this payload only.
375
399
  */
376
400
  id: string;
377
401
  /**
@@ -385,8 +409,9 @@ export interface WidgetEvent_AssistantMessage {
385
409
  type: 'assistantMessage';
386
410
  assistantMessage: WidgetAssistantMessageEvent;
387
411
  /**
388
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
389
- * `Last-Event-ID` on reconnect to resume without duplication.
412
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
413
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
414
+ * Transient heartbeats carry hb_ IDs in this payload only.
390
415
  */
391
416
  id: string;
392
417
  /**
@@ -400,8 +425,9 @@ export interface WidgetEvent_ToolApprovalRequested {
400
425
  type: 'toolApprovalRequested';
401
426
  toolApprovalRequested: WidgetToolApprovalRequestedEvent;
402
427
  /**
403
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
404
- * `Last-Event-ID` on reconnect to resume without duplication.
428
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
429
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
430
+ * Transient heartbeats carry hb_ IDs in this payload only.
405
431
  */
406
432
  id: string;
407
433
  /**
@@ -415,8 +441,9 @@ export interface WidgetEvent_ToolApproved {
415
441
  type: 'toolApproved';
416
442
  toolApproved: WidgetToolApprovedEvent;
417
443
  /**
418
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
419
- * `Last-Event-ID` on reconnect to resume without duplication.
444
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
445
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
446
+ * Transient heartbeats carry hb_ IDs in this payload only.
420
447
  */
421
448
  id: string;
422
449
  /**
@@ -430,8 +457,9 @@ export interface WidgetEvent_ToolDenied {
430
457
  type: 'toolDenied';
431
458
  toolDenied: WidgetToolDeniedEvent;
432
459
  /**
433
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
434
- * `Last-Event-ID` on reconnect to resume without duplication.
460
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
461
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
462
+ * Transient heartbeats carry hb_ IDs in this payload only.
435
463
  */
436
464
  id: string;
437
465
  /**
@@ -445,8 +473,9 @@ export interface WidgetEvent_ToolCalled {
445
473
  type: 'toolCalled';
446
474
  toolCalled: WidgetToolCalledEvent;
447
475
  /**
448
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
449
- * `Last-Event-ID` on reconnect to resume without duplication.
476
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
477
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
478
+ * Transient heartbeats carry hb_ IDs in this payload only.
450
479
  */
451
480
  id: string;
452
481
  /**
@@ -460,8 +489,9 @@ export interface WidgetEvent_ToolResult {
460
489
  type: 'toolResult';
461
490
  toolResult: WidgetToolResultEvent;
462
491
  /**
463
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
464
- * `Last-Event-ID` on reconnect to resume without duplication.
492
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
493
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
494
+ * Transient heartbeats carry hb_ IDs in this payload only.
465
495
  */
466
496
  id: string;
467
497
  /**
@@ -475,8 +505,9 @@ export interface WidgetEvent_ToolError {
475
505
  type: 'toolError';
476
506
  toolError: WidgetToolErrorEvent;
477
507
  /**
478
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
479
- * `Last-Event-ID` on reconnect to resume without duplication.
508
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
509
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
510
+ * Transient heartbeats carry hb_ IDs in this payload only.
480
511
  */
481
512
  id: string;
482
513
  /**
@@ -490,8 +521,9 @@ export interface WidgetEvent_Error {
490
521
  type: 'error';
491
522
  error: WidgetErrorEvent;
492
523
  /**
493
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
494
- * `Last-Event-ID` on reconnect to resume without duplication.
524
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
525
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
526
+ * Transient heartbeats carry hb_ IDs in this payload only.
495
527
  */
496
528
  id: string;
497
529
  /**
@@ -505,8 +537,9 @@ export interface WidgetEvent_Cancelled {
505
537
  type: 'cancelled';
506
538
  cancelled: WidgetCancelledEvent;
507
539
  /**
508
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
509
- * `Last-Event-ID` on reconnect to resume without duplication.
540
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
541
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
542
+ * Transient heartbeats carry hb_ IDs in this payload only.
510
543
  */
511
544
  id: string;
512
545
  /**
@@ -520,8 +553,9 @@ export interface WidgetEvent_TimedOut {
520
553
  type: 'timedOut';
521
554
  timedOut: WidgetTimedOutEvent;
522
555
  /**
523
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
524
- * `Last-Event-ID` on reconnect to resume without duplication.
556
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
557
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
558
+ * Transient heartbeats carry hb_ IDs in this payload only.
525
559
  */
526
560
  id: string;
527
561
  /**
@@ -535,8 +569,41 @@ export interface WidgetEvent_Finalized {
535
569
  type: 'finalized';
536
570
  finalized: WidgetFinalizedEvent;
537
571
  /**
538
- * Unique event id (ULID). Doubles as the SSE `id:` — replay it as
539
- * `Last-Event-ID` on reconnect to resume without duplication.
572
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
573
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
574
+ * Transient heartbeats carry hb_ IDs in this payload only.
575
+ */
576
+ id: string;
577
+ /**
578
+ * The conversation this event belongs to.
579
+ */
580
+ conversationId: string;
581
+ createdAt: string;
582
+ }
583
+
584
+ export interface WidgetEvent_Heartbeat {
585
+ type: 'heartbeat';
586
+ heartbeat: WidgetHeartbeatEvent;
587
+ /**
588
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
589
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
590
+ * Transient heartbeats carry hb_ IDs in this payload only.
591
+ */
592
+ id: string;
593
+ /**
594
+ * The conversation this event belongs to.
595
+ */
596
+ conversationId: string;
597
+ createdAt: string;
598
+ }
599
+
600
+ export interface WidgetEvent_StateChanged {
601
+ type: 'stateChanged';
602
+ stateChanged: WidgetObjectiveStateChangedEvent;
603
+ /**
604
+ * Unique event id (prefixed ULID). Only durable objevt_ IDs are emitted
605
+ * as SSE `id:` fields and accepted as Last-Event-ID reconnect cursors.
606
+ * Transient heartbeats carry hb_ IDs in this payload only.
540
607
  */
541
608
  id: string;
542
609
  /**