libretto 0.1.5 → 0.2.1

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.
Files changed (168) hide show
  1. package/README.md +215 -17
  2. package/bin/libretto.mjs +18 -0
  3. package/dist/cli/cli.js +203 -0
  4. package/dist/cli/commands/ai.js +21 -0
  5. package/dist/cli/commands/browser.js +59 -0
  6. package/dist/cli/commands/execution.js +422 -0
  7. package/dist/cli/commands/logs.js +93 -0
  8. package/dist/cli/commands/snapshot.js +106 -0
  9. package/dist/cli/core/ai-config.js +149 -0
  10. package/dist/cli/core/browser.js +523 -0
  11. package/dist/cli/core/context.js +113 -0
  12. package/dist/cli/core/pause-signals.js +29 -0
  13. package/dist/cli/core/session-telemetry.js +491 -0
  14. package/dist/cli/core/session.js +183 -0
  15. package/dist/cli/core/snapshot-analyzer.js +492 -0
  16. package/dist/cli/core/telemetry.js +362 -0
  17. package/dist/cli/index.js +13 -0
  18. package/dist/cli/workers/run-integration-runtime.js +222 -0
  19. package/dist/cli/workers/run-integration-worker-protocol.js +0 -0
  20. package/dist/cli/workers/run-integration-worker.js +83 -0
  21. package/dist/index.cjs +123 -0
  22. package/dist/index.d.cts +19 -0
  23. package/dist/index.d.ts +19 -0
  24. package/dist/index.js +107 -0
  25. package/dist/runtime/download/download.cjs +70 -0
  26. package/dist/runtime/download/download.d.cts +35 -0
  27. package/dist/runtime/download/download.d.ts +35 -0
  28. package/dist/runtime/download/download.js +45 -0
  29. package/dist/runtime/download/index.cjs +30 -0
  30. package/dist/runtime/download/index.d.cts +3 -0
  31. package/dist/runtime/download/index.d.ts +3 -0
  32. package/dist/runtime/download/index.js +8 -0
  33. package/dist/runtime/extract/extract.cjs +88 -0
  34. package/dist/runtime/extract/extract.d.cts +23 -0
  35. package/dist/runtime/extract/extract.d.ts +23 -0
  36. package/dist/runtime/extract/extract.js +64 -0
  37. package/dist/runtime/extract/index.cjs +28 -0
  38. package/dist/runtime/extract/index.d.cts +5 -0
  39. package/dist/runtime/extract/index.d.ts +5 -0
  40. package/dist/runtime/extract/index.js +4 -0
  41. package/dist/runtime/network/index.cjs +28 -0
  42. package/dist/runtime/network/index.d.cts +4 -0
  43. package/dist/runtime/network/index.d.ts +4 -0
  44. package/dist/runtime/network/index.js +6 -0
  45. package/dist/runtime/network/network.cjs +91 -0
  46. package/dist/runtime/network/network.d.cts +28 -0
  47. package/dist/runtime/network/network.d.ts +28 -0
  48. package/dist/runtime/network/network.js +67 -0
  49. package/dist/runtime/recovery/agent.cjs +223 -0
  50. package/dist/runtime/recovery/agent.d.cts +13 -0
  51. package/dist/runtime/recovery/agent.d.ts +13 -0
  52. package/dist/runtime/recovery/agent.js +199 -0
  53. package/dist/runtime/recovery/errors.cjs +124 -0
  54. package/dist/runtime/recovery/errors.d.cts +31 -0
  55. package/dist/runtime/recovery/errors.d.ts +31 -0
  56. package/dist/runtime/recovery/errors.js +100 -0
  57. package/dist/runtime/recovery/index.cjs +34 -0
  58. package/dist/runtime/recovery/index.d.cts +7 -0
  59. package/dist/runtime/recovery/index.d.ts +7 -0
  60. package/dist/runtime/recovery/index.js +10 -0
  61. package/dist/runtime/recovery/recovery.cjs +55 -0
  62. package/dist/runtime/recovery/recovery.d.cts +12 -0
  63. package/dist/runtime/recovery/recovery.d.ts +12 -0
  64. package/dist/runtime/recovery/recovery.js +31 -0
  65. package/dist/shared/config/config.cjs +44 -0
  66. package/dist/shared/config/config.d.cts +10 -0
  67. package/dist/shared/config/config.d.ts +10 -0
  68. package/dist/shared/config/config.js +18 -0
  69. package/dist/shared/config/index.cjs +32 -0
  70. package/dist/shared/config/index.d.cts +1 -0
  71. package/dist/shared/config/index.d.ts +1 -0
  72. package/dist/shared/config/index.js +10 -0
  73. package/dist/shared/debug/index.cjs +32 -0
  74. package/dist/shared/debug/index.d.cts +2 -0
  75. package/dist/shared/debug/index.d.ts +2 -0
  76. package/dist/shared/debug/index.js +10 -0
  77. package/dist/shared/debug/pause.cjs +56 -0
  78. package/dist/shared/debug/pause.d.cts +23 -0
  79. package/dist/shared/debug/pause.d.ts +23 -0
  80. package/dist/shared/debug/pause.js +30 -0
  81. package/dist/shared/instrumentation/errors.cjs +81 -0
  82. package/dist/shared/instrumentation/errors.d.cts +12 -0
  83. package/dist/shared/instrumentation/errors.d.ts +12 -0
  84. package/dist/shared/instrumentation/errors.js +57 -0
  85. package/dist/shared/instrumentation/index.cjs +35 -0
  86. package/dist/shared/instrumentation/index.d.cts +6 -0
  87. package/dist/shared/instrumentation/index.d.ts +6 -0
  88. package/dist/shared/instrumentation/index.js +12 -0
  89. package/dist/shared/instrumentation/instrument.cjs +206 -0
  90. package/dist/shared/instrumentation/instrument.d.cts +32 -0
  91. package/dist/shared/instrumentation/instrument.d.ts +32 -0
  92. package/dist/shared/instrumentation/instrument.js +190 -0
  93. package/dist/shared/llm/client.cjs +139 -0
  94. package/dist/shared/llm/client.d.cts +6 -0
  95. package/dist/shared/llm/client.d.ts +6 -0
  96. package/dist/shared/llm/client.js +115 -0
  97. package/dist/shared/llm/index.cjs +28 -0
  98. package/dist/shared/llm/index.d.cts +3 -0
  99. package/dist/shared/llm/index.d.ts +3 -0
  100. package/dist/shared/llm/index.js +4 -0
  101. package/dist/shared/llm/types.cjs +16 -0
  102. package/dist/shared/llm/types.d.cts +34 -0
  103. package/dist/shared/llm/types.d.ts +34 -0
  104. package/dist/shared/llm/types.js +0 -0
  105. package/dist/shared/logger/index.cjs +37 -0
  106. package/dist/shared/logger/index.d.cts +2 -0
  107. package/dist/shared/logger/index.d.ts +2 -0
  108. package/dist/shared/logger/index.js +13 -0
  109. package/dist/shared/logger/logger.cjs +213 -0
  110. package/dist/shared/logger/logger.d.cts +82 -0
  111. package/dist/shared/logger/logger.d.ts +82 -0
  112. package/dist/shared/logger/logger.js +188 -0
  113. package/dist/shared/logger/sinks.cjs +160 -0
  114. package/dist/shared/logger/sinks.d.cts +9 -0
  115. package/dist/shared/logger/sinks.d.ts +9 -0
  116. package/dist/shared/logger/sinks.js +124 -0
  117. package/dist/shared/paths/paths.cjs +104 -0
  118. package/dist/shared/paths/paths.d.cts +10 -0
  119. package/dist/shared/paths/paths.d.ts +10 -0
  120. package/dist/shared/paths/paths.js +73 -0
  121. package/dist/shared/run/api.cjs +35 -0
  122. package/dist/shared/run/api.d.cts +3 -0
  123. package/dist/shared/run/api.d.ts +3 -0
  124. package/dist/shared/run/api.js +12 -0
  125. package/dist/shared/run/browser.cjs +98 -0
  126. package/dist/shared/run/browser.d.cts +22 -0
  127. package/dist/shared/run/browser.d.ts +22 -0
  128. package/dist/shared/run/browser.js +74 -0
  129. package/dist/shared/state/index.cjs +38 -0
  130. package/dist/shared/state/index.d.cts +2 -0
  131. package/dist/shared/state/index.d.ts +2 -0
  132. package/dist/shared/state/index.js +16 -0
  133. package/dist/shared/state/session-state.cjs +85 -0
  134. package/dist/shared/state/session-state.d.cts +34 -0
  135. package/dist/shared/state/session-state.d.ts +34 -0
  136. package/dist/shared/state/session-state.js +56 -0
  137. package/dist/shared/visualization/ghost-cursor.cjs +174 -0
  138. package/dist/shared/visualization/ghost-cursor.d.cts +37 -0
  139. package/dist/shared/visualization/ghost-cursor.d.ts +37 -0
  140. package/dist/shared/visualization/ghost-cursor.js +145 -0
  141. package/dist/shared/visualization/highlight.cjs +134 -0
  142. package/dist/shared/visualization/highlight.d.cts +22 -0
  143. package/dist/shared/visualization/highlight.d.ts +22 -0
  144. package/dist/shared/visualization/highlight.js +108 -0
  145. package/dist/shared/visualization/index.cjs +45 -0
  146. package/dist/shared/visualization/index.d.cts +3 -0
  147. package/dist/shared/visualization/index.d.ts +3 -0
  148. package/dist/shared/visualization/index.js +24 -0
  149. package/dist/shared/workflow/workflow.cjs +47 -0
  150. package/dist/shared/workflow/workflow.d.cts +33 -0
  151. package/dist/shared/workflow/workflow.d.ts +33 -0
  152. package/dist/shared/workflow/workflow.js +21 -0
  153. package/package.json +125 -26
  154. package/.npmignore +0 -2
  155. package/bin/libretto +0 -31
  156. package/lib/connect.js +0 -34
  157. package/lib/export.js +0 -224
  158. package/lib/import.js +0 -166
  159. package/lib/index.js +0 -8
  160. package/lib/log.js +0 -9
  161. package/lib/validate.js +0 -20
  162. package/makefile +0 -8
  163. package/src/connect.coffee +0 -25
  164. package/src/export.coffee +0 -222
  165. package/src/import.coffee +0 -166
  166. package/src/index.coffee +0 -3
  167. package/src/log.coffee +0 -3
  168. package/src/validate.coffee +0 -10
@@ -0,0 +1,115 @@
1
+ import { createVertex } from "@ai-sdk/google-vertex";
2
+ import { createAnthropic } from "@ai-sdk/anthropic";
3
+ import { createOpenAI } from "@ai-sdk/openai";
4
+ import { generateObject } from "ai";
5
+ function parseModel(model) {
6
+ const slashIndex = model.indexOf("/");
7
+ if (slashIndex === -1) {
8
+ throw new Error(
9
+ `Invalid model string "${model}". Expected format: "provider/model-id" (e.g. "google/gemini-3-flash-preview").`
10
+ );
11
+ }
12
+ const provider = model.slice(0, slashIndex);
13
+ const modelId = model.slice(slashIndex + 1);
14
+ if (!["google", "anthropic", "openai"].includes(provider)) {
15
+ throw new Error(
16
+ `Unsupported provider "${provider}". Supported providers: google, anthropic, openai.`
17
+ );
18
+ }
19
+ return { provider, modelId };
20
+ }
21
+ function getProviderModel(provider, modelId) {
22
+ switch (provider) {
23
+ case "google": {
24
+ const project = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT;
25
+ if (!project) {
26
+ throw new Error(
27
+ "Missing GCP project for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable and ensure application default credentials are configured (gcloud auth application-default login)."
28
+ );
29
+ }
30
+ const vertex = createVertex({
31
+ project,
32
+ location: process.env.GOOGLE_CLOUD_LOCATION || "global"
33
+ });
34
+ return vertex(modelId);
35
+ }
36
+ case "anthropic": {
37
+ const apiKey = process.env.ANTHROPIC_API_KEY;
38
+ if (!apiKey) {
39
+ throw new Error(
40
+ "Missing API key for Anthropic. Set ANTHROPIC_API_KEY environment variable."
41
+ );
42
+ }
43
+ const anthropic = createAnthropic({ apiKey });
44
+ return anthropic(modelId);
45
+ }
46
+ case "openai": {
47
+ const apiKey = process.env.OPENAI_API_KEY;
48
+ if (!apiKey) {
49
+ throw new Error(
50
+ "Missing API key for OpenAI. Set OPENAI_API_KEY environment variable."
51
+ );
52
+ }
53
+ const openai = createOpenAI({ apiKey });
54
+ return openai(modelId);
55
+ }
56
+ }
57
+ }
58
+ function convertUserContentParts(parts) {
59
+ return parts.map((part) => {
60
+ if (part.type === "text") {
61
+ return { type: "text", text: part.text };
62
+ }
63
+ return { type: "image", image: part.image };
64
+ });
65
+ }
66
+ function convertAssistantContentParts(parts) {
67
+ return parts.filter((part) => part.type === "text").map((part) => ({ type: "text", text: part.text }));
68
+ }
69
+ function convertMessages(messages) {
70
+ return messages.map((msg) => {
71
+ if (msg.role === "user") {
72
+ if (typeof msg.content === "string") {
73
+ return { role: "user", content: msg.content };
74
+ }
75
+ return {
76
+ role: "user",
77
+ content: convertUserContentParts(msg.content)
78
+ };
79
+ }
80
+ if (typeof msg.content === "string") {
81
+ return { role: "assistant", content: msg.content };
82
+ }
83
+ return {
84
+ role: "assistant",
85
+ content: convertAssistantContentParts(msg.content)
86
+ };
87
+ });
88
+ }
89
+ function createLLMClient(model) {
90
+ const { provider, modelId } = parseModel(model);
91
+ const aiModel = getProviderModel(provider, modelId);
92
+ return {
93
+ async generateObject(opts) {
94
+ const result = await generateObject({
95
+ model: aiModel,
96
+ prompt: opts.prompt,
97
+ schema: opts.schema,
98
+ temperature: opts.temperature ?? 0
99
+ });
100
+ return result.object;
101
+ },
102
+ async generateObjectFromMessages(opts) {
103
+ const result = await generateObject({
104
+ model: aiModel,
105
+ messages: convertMessages(opts.messages),
106
+ schema: opts.schema,
107
+ temperature: opts.temperature ?? 0
108
+ });
109
+ return result.object;
110
+ }
111
+ };
112
+ }
113
+ export {
114
+ createLLMClient
115
+ };
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var llm_exports = {};
20
+ __export(llm_exports, {
21
+ createLLMClient: () => import_client.createLLMClient
22
+ });
23
+ module.exports = __toCommonJS(llm_exports);
24
+ var import_client = require("./client.js");
25
+ // Annotate the CommonJS export names for ESM import in node:
26
+ 0 && (module.exports = {
27
+ createLLMClient
28
+ });
@@ -0,0 +1,3 @@
1
+ export { LLMClient, Message, MessageContentPart } from './types.cjs';
2
+ export { createLLMClient } from './client.cjs';
3
+ import 'zod';
@@ -0,0 +1,3 @@
1
+ export { LLMClient, Message, MessageContentPart } from './types.js';
2
+ export { createLLMClient } from './client.js';
3
+ import 'zod';
@@ -0,0 +1,4 @@
1
+ import { createLLMClient } from "./client.js";
2
+ export {
3
+ createLLMClient
4
+ };
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var types_exports = {};
16
+ module.exports = __toCommonJS(types_exports);
@@ -0,0 +1,34 @@
1
+ import z from 'zod';
2
+
3
+ type MessageContentPart = {
4
+ type: "text";
5
+ text: string;
6
+ } | {
7
+ type: "image";
8
+ image: string;
9
+ };
10
+ type Message = {
11
+ role: "user" | "assistant";
12
+ content: string | MessageContentPart[];
13
+ };
14
+ /**
15
+ * Pluggable LLM client interface.
16
+ *
17
+ * Users provide their own implementation backed by any LLM provider
18
+ * (OpenAI, Anthropic, etc.). Libretto uses this interface for AI extraction,
19
+ * recovery agents, and error detection.
20
+ */
21
+ interface LLMClient {
22
+ generateObject<T extends z.ZodType>(opts: {
23
+ prompt: string;
24
+ schema: T;
25
+ temperature?: number;
26
+ }): Promise<z.infer<T>>;
27
+ generateObjectFromMessages<T extends z.ZodType>(opts: {
28
+ messages: Message[];
29
+ schema: T;
30
+ temperature?: number;
31
+ }): Promise<z.infer<T>>;
32
+ }
33
+
34
+ export type { LLMClient, Message, MessageContentPart };
@@ -0,0 +1,34 @@
1
+ import z from 'zod';
2
+
3
+ type MessageContentPart = {
4
+ type: "text";
5
+ text: string;
6
+ } | {
7
+ type: "image";
8
+ image: string;
9
+ };
10
+ type Message = {
11
+ role: "user" | "assistant";
12
+ content: string | MessageContentPart[];
13
+ };
14
+ /**
15
+ * Pluggable LLM client interface.
16
+ *
17
+ * Users provide their own implementation backed by any LLM provider
18
+ * (OpenAI, Anthropic, etc.). Libretto uses this interface for AI extraction,
19
+ * recovery agents, and error detection.
20
+ */
21
+ interface LLMClient {
22
+ generateObject<T extends z.ZodType>(opts: {
23
+ prompt: string;
24
+ schema: T;
25
+ temperature?: number;
26
+ }): Promise<z.infer<T>>;
27
+ generateObjectFromMessages<T extends z.ZodType>(opts: {
28
+ messages: Message[];
29
+ schema: T;
30
+ temperature?: number;
31
+ }): Promise<z.infer<T>>;
32
+ }
33
+
34
+ export type { LLMClient, Message, MessageContentPart };
File without changes
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var logger_exports = {};
20
+ __export(logger_exports, {
21
+ Logger: () => import_logger.Logger,
22
+ createFileLogSink: () => import_sinks.createFileLogSink,
23
+ defaultLogger: () => import_logger.defaultLogger,
24
+ jsonlConsoleSink: () => import_sinks.jsonlConsoleSink,
25
+ prettyConsoleSink: () => import_sinks.prettyConsoleSink
26
+ });
27
+ module.exports = __toCommonJS(logger_exports);
28
+ var import_logger = require("./logger.js");
29
+ var import_sinks = require("./sinks.js");
30
+ // Annotate the CommonJS export names for ESM import in node:
31
+ 0 && (module.exports = {
32
+ Logger,
33
+ createFileLogSink,
34
+ defaultLogger,
35
+ jsonlConsoleSink,
36
+ prettyConsoleSink
37
+ });
@@ -0,0 +1,2 @@
1
+ export { LogOptions, Logger, LoggerApi, LoggerSink, MinimalLogger, defaultLogger } from './logger.cjs';
2
+ export { createFileLogSink, jsonlConsoleSink, prettyConsoleSink } from './sinks.cjs';
@@ -0,0 +1,2 @@
1
+ export { LogOptions, Logger, LoggerApi, LoggerSink, MinimalLogger, defaultLogger } from './logger.js';
2
+ export { createFileLogSink, jsonlConsoleSink, prettyConsoleSink } from './sinks.js';
@@ -0,0 +1,13 @@
1
+ import { Logger, defaultLogger } from "./logger.js";
2
+ import {
3
+ createFileLogSink,
4
+ prettyConsoleSink,
5
+ jsonlConsoleSink
6
+ } from "./sinks.js";
7
+ export {
8
+ Logger,
9
+ createFileLogSink,
10
+ defaultLogger,
11
+ jsonlConsoleSink,
12
+ prettyConsoleSink
13
+ };
@@ -0,0 +1,213 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var logger_exports = {};
20
+ __export(logger_exports, {
21
+ Logger: () => Logger,
22
+ defaultLogger: () => defaultLogger
23
+ });
24
+ module.exports = __toCommonJS(logger_exports);
25
+ function generateId() {
26
+ return Math.random().toString(36).substring(2, 15);
27
+ }
28
+ const defaultLogger = {
29
+ info(event, data) {
30
+ console.log(`[INFO] ${event}`, data ?? "");
31
+ },
32
+ warn(event, data) {
33
+ console.warn(`[WARN] ${event}`, data ?? "");
34
+ },
35
+ error(event, data) {
36
+ console.error(`[ERROR] ${event}`, data ?? "");
37
+ }
38
+ };
39
+ const sinkLifecycleState = /* @__PURE__ */ new WeakMap();
40
+ function getSinkLifecycleState(sink) {
41
+ const existingState = sinkLifecycleState.get(sink);
42
+ if (existingState) {
43
+ return existingState;
44
+ }
45
+ const initialState = { closed: false };
46
+ sinkLifecycleState.set(sink, initialState);
47
+ return initialState;
48
+ }
49
+ function isSinkClosedOrClosing(sink) {
50
+ const state = sinkLifecycleState.get(sink);
51
+ return Boolean(state?.closed || state?.closing);
52
+ }
53
+ async function closeSinkOnce(sink) {
54
+ if (!sink.close) {
55
+ return;
56
+ }
57
+ const state = getSinkLifecycleState(sink);
58
+ if (state.closed) {
59
+ return;
60
+ }
61
+ if (state.closing) {
62
+ return state.closing;
63
+ }
64
+ state.closing = (async () => {
65
+ try {
66
+ await sink.close?.();
67
+ } catch {
68
+ } finally {
69
+ state.closed = true;
70
+ state.closing = void 0;
71
+ }
72
+ })();
73
+ return state.closing;
74
+ }
75
+ function isObject(value) {
76
+ return typeof value === "object" && value !== null;
77
+ }
78
+ function removeUndefined(data) {
79
+ if (typeof data === "object" && data !== null) {
80
+ return Object.fromEntries(
81
+ Object.entries(data).filter(([_, value]) => value !== void 0)
82
+ );
83
+ }
84
+ return data;
85
+ }
86
+ class Logger {
87
+ constructor(scopes = [], sinks = [], scopeData = {}) {
88
+ this.scopes = scopes;
89
+ this.sinks = sinks;
90
+ this.scopeData = scopeData;
91
+ this.prefix = scopes.join(".");
92
+ }
93
+ prefix;
94
+ entry(entry) {
95
+ this.sinks.forEach((sink) => {
96
+ if (isSinkClosedOrClosing(sink)) {
97
+ return;
98
+ }
99
+ sink.write({
100
+ id: generateId(),
101
+ scope: this.prefix,
102
+ level: entry.level,
103
+ event: entry.event,
104
+ data: removeUndefined({ ...this.scopeData, ...entry.data }),
105
+ options: entry.options
106
+ });
107
+ });
108
+ }
109
+ log(event, data, options) {
110
+ this.entry({ level: "log", event, data, options });
111
+ }
112
+ error(event, dataOrError, options) {
113
+ const data = dataOrError instanceof Error ? {
114
+ error: {
115
+ type: dataOrError.constructor.name,
116
+ message: dataOrError.message,
117
+ stack: dataOrError.stack || null
118
+ }
119
+ } : isObject(dataOrError) && dataOrError.error instanceof Error ? {
120
+ ...dataOrError,
121
+ error: {
122
+ type: dataOrError.error.constructor.name,
123
+ message: dataOrError.error.message,
124
+ stack: dataOrError.error.stack || null
125
+ }
126
+ } : isObject(dataOrError) ? dataOrError : dataOrError !== void 0 ? { error: dataOrError } : void 0;
127
+ this.entry({
128
+ level: "error",
129
+ event,
130
+ data,
131
+ options
132
+ });
133
+ if (dataOrError instanceof Error) {
134
+ return dataOrError;
135
+ }
136
+ if (isObject(dataOrError) && dataOrError.error instanceof Error) {
137
+ return dataOrError.error;
138
+ }
139
+ let message = event;
140
+ if (data !== void 0) {
141
+ try {
142
+ message += "\n" + JSON.stringify(data, void 0, 2);
143
+ } catch {
144
+ message += "\n[Unserializable error data]";
145
+ }
146
+ }
147
+ return new Error(message);
148
+ }
149
+ warn(event, dataOrError, options) {
150
+ const data = dataOrError instanceof Error ? {
151
+ error: {
152
+ type: dataOrError.constructor.name,
153
+ message: dataOrError.message,
154
+ stack: dataOrError.stack || null
155
+ }
156
+ } : isObject(dataOrError) && dataOrError.error instanceof Error ? {
157
+ ...dataOrError,
158
+ error: {
159
+ type: dataOrError.error.constructor.name,
160
+ message: dataOrError.error.message,
161
+ stack: dataOrError.error.stack || null
162
+ }
163
+ } : isObject(dataOrError) ? dataOrError : dataOrError !== void 0 ? { error: dataOrError } : void 0;
164
+ this.entry({
165
+ level: "warn",
166
+ event,
167
+ data,
168
+ options
169
+ });
170
+ }
171
+ info(event, data, options) {
172
+ this.entry({ level: "info", event, data, options });
173
+ }
174
+ withScope(scope, context = {}) {
175
+ return new Logger([...this.scopes, scope], this.sinks, {
176
+ ...this.scopeData,
177
+ ...context
178
+ });
179
+ }
180
+ withContext(context) {
181
+ return new Logger(this.scopes, this.sinks, {
182
+ ...this.scopeData,
183
+ ...context
184
+ });
185
+ }
186
+ withSink(sink) {
187
+ return new Logger(this.scopes, [...this.sinks, sink]);
188
+ }
189
+ async flush() {
190
+ for (let i = this.sinks.length - 1; i >= 0; i--) {
191
+ const sink = this.sinks[i];
192
+ if (!sink) continue;
193
+ if (isSinkClosedOrClosing(sink)) continue;
194
+ try {
195
+ await sink.flush?.();
196
+ } catch {
197
+ }
198
+ }
199
+ }
200
+ async close() {
201
+ await this.flush();
202
+ for (let i = this.sinks.length - 1; i >= 0; i--) {
203
+ const sink = this.sinks[i];
204
+ if (!sink) continue;
205
+ await closeSinkOnce(sink);
206
+ }
207
+ }
208
+ }
209
+ // Annotate the CommonJS export names for ESM import in node:
210
+ 0 && (module.exports = {
211
+ Logger,
212
+ defaultLogger
213
+ });
@@ -0,0 +1,82 @@
1
+ type LogOptions = {
2
+ timestamp?: Date;
3
+ };
4
+ /**
5
+ * Minimal logger interface accepted by public-facing runtime functions.
6
+ * Any logger with info/warn/error methods satisfies this — no need to
7
+ * implement withScope, withContext, flush, etc.
8
+ */
9
+ type MinimalLogger = {
10
+ info: (event: string, data?: Record<string, any>) => void;
11
+ warn: (event: string, data?: any) => void;
12
+ error: (event: string, data?: any) => any;
13
+ };
14
+ /** Default console logger used when callers omit the logger option. */
15
+ declare const defaultLogger: MinimalLogger;
16
+ type LoggerApi = {
17
+ log: (event: string, data?: Record<string, any>, options?: LogOptions) => void;
18
+ /**
19
+ * Logs an error and returns an Error object that can be thrown
20
+ *
21
+ * either pass in an Error directly as data or as { error: Error, ...other_data }
22
+ */
23
+ error: (event: string, data?: Error | ({
24
+ error: Error;
25
+ } & Record<string, any>) | unknown, options?: LogOptions) => Error;
26
+ warn: (event: string, data?: Error | ({
27
+ error: Error;
28
+ } & Record<string, any>) | unknown, options?: LogOptions) => void;
29
+ info: (event: string, data?: Record<string, any>, options?: LogOptions) => void;
30
+ /**
31
+ * Context passed in will be attached to all entries in this scope.
32
+ */
33
+ withScope: (scope: string, context?: Record<string, any>) => LoggerApi;
34
+ /**
35
+ * Context passed in will be attached to all entries.
36
+ */
37
+ withContext: (context: Record<string, any>) => LoggerApi;
38
+ /**
39
+ * Flushes all sinks in reverse order (most recently added first).
40
+ */
41
+ flush: () => Promise<void>;
42
+ };
43
+ type LoggerSink = {
44
+ write: (args: {
45
+ id: string;
46
+ scope: string;
47
+ level: "log" | "error" | "warn" | "info";
48
+ event: string;
49
+ data: Record<string, any>;
50
+ options?: LogOptions;
51
+ }) => void;
52
+ flush?: () => Promise<void>;
53
+ close?: () => Promise<void>;
54
+ };
55
+ declare class Logger implements LoggerApi {
56
+ private readonly scopes;
57
+ private readonly sinks;
58
+ private readonly scopeData;
59
+ private readonly prefix;
60
+ constructor(scopes?: string[], sinks?: LoggerSink[], scopeData?: Record<string, any>);
61
+ entry(entry: {
62
+ level: "log" | "error" | "warn" | "info";
63
+ event: string;
64
+ data?: Record<string, any>;
65
+ options?: LogOptions;
66
+ }): void;
67
+ log(event: string, data?: Record<string, any>, options?: LogOptions): void;
68
+ error(event: string, dataOrError?: Error | ({
69
+ error: Error;
70
+ } & Record<string, any>) | unknown, options?: LogOptions): Error;
71
+ warn(event: string, dataOrError?: Error | ({
72
+ error: Error;
73
+ } & Record<string, any>) | unknown, options?: LogOptions): void;
74
+ info(event: string, data?: Record<string, any>, options?: LogOptions): void;
75
+ withScope(scope: string, context?: Record<string, any>): LoggerApi;
76
+ withContext(context: Record<string, any>): LoggerApi;
77
+ withSink(sink: LoggerSink): Logger;
78
+ flush(): Promise<void>;
79
+ close(): Promise<void>;
80
+ }
81
+
82
+ export { type LogOptions, Logger, type LoggerApi, type LoggerSink, type MinimalLogger, defaultLogger };
@@ -0,0 +1,82 @@
1
+ type LogOptions = {
2
+ timestamp?: Date;
3
+ };
4
+ /**
5
+ * Minimal logger interface accepted by public-facing runtime functions.
6
+ * Any logger with info/warn/error methods satisfies this — no need to
7
+ * implement withScope, withContext, flush, etc.
8
+ */
9
+ type MinimalLogger = {
10
+ info: (event: string, data?: Record<string, any>) => void;
11
+ warn: (event: string, data?: any) => void;
12
+ error: (event: string, data?: any) => any;
13
+ };
14
+ /** Default console logger used when callers omit the logger option. */
15
+ declare const defaultLogger: MinimalLogger;
16
+ type LoggerApi = {
17
+ log: (event: string, data?: Record<string, any>, options?: LogOptions) => void;
18
+ /**
19
+ * Logs an error and returns an Error object that can be thrown
20
+ *
21
+ * either pass in an Error directly as data or as { error: Error, ...other_data }
22
+ */
23
+ error: (event: string, data?: Error | ({
24
+ error: Error;
25
+ } & Record<string, any>) | unknown, options?: LogOptions) => Error;
26
+ warn: (event: string, data?: Error | ({
27
+ error: Error;
28
+ } & Record<string, any>) | unknown, options?: LogOptions) => void;
29
+ info: (event: string, data?: Record<string, any>, options?: LogOptions) => void;
30
+ /**
31
+ * Context passed in will be attached to all entries in this scope.
32
+ */
33
+ withScope: (scope: string, context?: Record<string, any>) => LoggerApi;
34
+ /**
35
+ * Context passed in will be attached to all entries.
36
+ */
37
+ withContext: (context: Record<string, any>) => LoggerApi;
38
+ /**
39
+ * Flushes all sinks in reverse order (most recently added first).
40
+ */
41
+ flush: () => Promise<void>;
42
+ };
43
+ type LoggerSink = {
44
+ write: (args: {
45
+ id: string;
46
+ scope: string;
47
+ level: "log" | "error" | "warn" | "info";
48
+ event: string;
49
+ data: Record<string, any>;
50
+ options?: LogOptions;
51
+ }) => void;
52
+ flush?: () => Promise<void>;
53
+ close?: () => Promise<void>;
54
+ };
55
+ declare class Logger implements LoggerApi {
56
+ private readonly scopes;
57
+ private readonly sinks;
58
+ private readonly scopeData;
59
+ private readonly prefix;
60
+ constructor(scopes?: string[], sinks?: LoggerSink[], scopeData?: Record<string, any>);
61
+ entry(entry: {
62
+ level: "log" | "error" | "warn" | "info";
63
+ event: string;
64
+ data?: Record<string, any>;
65
+ options?: LogOptions;
66
+ }): void;
67
+ log(event: string, data?: Record<string, any>, options?: LogOptions): void;
68
+ error(event: string, dataOrError?: Error | ({
69
+ error: Error;
70
+ } & Record<string, any>) | unknown, options?: LogOptions): Error;
71
+ warn(event: string, dataOrError?: Error | ({
72
+ error: Error;
73
+ } & Record<string, any>) | unknown, options?: LogOptions): void;
74
+ info(event: string, data?: Record<string, any>, options?: LogOptions): void;
75
+ withScope(scope: string, context?: Record<string, any>): LoggerApi;
76
+ withContext(context: Record<string, any>): LoggerApi;
77
+ withSink(sink: LoggerSink): Logger;
78
+ flush(): Promise<void>;
79
+ close(): Promise<void>;
80
+ }
81
+
82
+ export { type LogOptions, Logger, type LoggerApi, type LoggerSink, type MinimalLogger, defaultLogger };