@sanity/workbench 0.1.0-alpha.2 → 0.1.0-alpha.3

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.
@@ -3,7 +3,12 @@
3
3
  *
4
4
  * @public
5
5
  */
6
- export declare type Config = undefined;
6
+ export declare type Config = {
7
+ /**
8
+ * The organization ID to use when rendering the workbench.
9
+ */
10
+ organizationId: string | undefined;
11
+ };
7
12
 
8
13
  /**
9
14
  * Creates a Module Federation instance, loads a remote workbench
package/dist/_internal.js CHANGED
@@ -1,36 +1,33 @@
1
1
  import { createInstance } from "@sanity/federation/runtime";
2
- const REMOTE_NAME = "workbench-remote", REMOTE_MODULE = "App";
2
+ import { log } from "@sanity/federation/runtime/plugins/log";
3
+ import { createLogger } from "./log.js";
4
+ const logger = createLogger({
5
+ namespace: "sanity-workbench",
6
+ logLevel: "debug"
7
+ }), REMOTE_NAME = "workbench-remote", REMOTE_MODULE = "App";
3
8
  async function renderWorkbench(rootElement, config, options) {
4
9
  if (!rootElement)
5
10
  throw new Error("Missing root element to mount application into");
6
11
  const remoteUrl = import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL;
7
12
  if (!remoteUrl)
8
13
  throw new Error("SANITY_INTERNAL_WORKBENCH_REMOTE_URL is not set");
9
- const mf = createInstance({
10
- name: "sanity-workbench"
11
- });
12
- mf.registerRemotes([
13
- {
14
- name: REMOTE_NAME,
15
- entry: remoteUrl
16
- }
17
- ]);
18
- let remoteModule;
19
- try {
20
- remoteModule = await mf.loadRemote(
21
- `${REMOTE_NAME}/${REMOTE_MODULE}`
22
- );
23
- } catch (error) {
24
- throw new Error(
25
- `Failed to load remote workbench module from "${remoteUrl}"`,
26
- { cause: error }
27
- );
28
- }
29
- if (!remoteModule || typeof remoteModule.render != "function")
14
+ let remoteModule = await createInstance({
15
+ name: "sanity-workbench",
16
+ plugins: [log(logger.debug)],
17
+ remotes: [
18
+ {
19
+ name: REMOTE_NAME,
20
+ entry: remoteUrl
21
+ }
22
+ ]
23
+ }).loadRemote(
24
+ `${REMOTE_NAME}/${REMOTE_MODULE}`
25
+ );
26
+ if (!remoteModule || typeof remoteModule.setup != "function")
30
27
  throw new Error(
31
- `Remote module from "${remoteUrl}" did not expose a render function`
28
+ `Remote module "${REMOTE_NAME}/${REMOTE_MODULE}" did not expose a setup function`
32
29
  );
33
- return remoteModule.render(rootElement, config, options);
30
+ return remoteModule.setup(config, options).render(rootElement);
34
31
  }
35
32
  export {
36
33
  renderWorkbench
@@ -1 +1 @@
1
- {"version":3,"file":"_internal.js","sources":["../src/_internal/render.ts"],"sourcesContent":["import { createInstance } from \"@sanity/federation/runtime\";\n\n/**\n * Workbench configuration.\n *\n * @public\n */\nexport type Config = undefined;\n\n/**\n * Options for rendering the workbench.\n *\n * @public\n */\nexport interface RenderWorkbenchOptions {\n reactStrictMode?: boolean;\n}\n\ndeclare global {\n interface ImportMetaEnv {\n readonly SANITY_INTERNAL_WORKBENCH_REMOTE_URL: string;\n }\n interface ImportMeta {\n readonly env: ImportMetaEnv;\n }\n}\n\nconst REMOTE_NAME = \"workbench-remote\";\nconst REMOTE_MODULE = \"App\";\n\ninterface RemoteModule {\n render(\n rootElement: HTMLElement,\n config?: Config,\n options?: RenderWorkbenchOptions,\n ): () => void;\n}\n\n/**\n * Creates a Module Federation instance, loads a remote workbench\n * application, and renders it into the provided root element.\n *\n * @param rootElement - The DOM element to render into\n * @param config - Workbench configuration (reserved for future use)\n * @param options - Rendering options forwarded to the remote\n * @returns A cleanup function that unmounts the remote application\n *\n * @public\n */\nexport async function renderWorkbench(\n rootElement: HTMLElement,\n config?: Config,\n options?: RenderWorkbenchOptions,\n): Promise<() => void> {\n if (!rootElement) {\n throw new Error(\"Missing root element to mount application into\");\n }\n\n const remoteUrl = import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL;\n\n if (!remoteUrl) {\n throw new Error(\"SANITY_INTERNAL_WORKBENCH_REMOTE_URL is not set\");\n }\n\n const mf = createInstance({\n name: \"sanity-workbench\",\n });\n\n mf.registerRemotes([\n {\n name: REMOTE_NAME,\n entry: remoteUrl,\n },\n ]);\n\n let remoteModule: RemoteModule | null;\n try {\n remoteModule = await mf.loadRemote<RemoteModule>(\n `${REMOTE_NAME}/${REMOTE_MODULE}`,\n );\n } catch (error) {\n throw new Error(\n `Failed to load remote workbench module from \"${remoteUrl}\"`,\n { cause: error },\n );\n }\n\n if (!remoteModule || typeof remoteModule.render !== \"function\") {\n throw new Error(\n `Remote module from \"${remoteUrl}\" did not expose a render function`,\n );\n }\n\n return remoteModule.render(rootElement, config, options);\n}\n"],"names":[],"mappings":";AA2BA,MAAM,cAAc,oBACd,gBAAgB;AAqBtB,eAAsB,gBACpB,aACA,QACA,SACqB;AACrB,MAAI,CAAC;AACH,UAAM,IAAI,MAAM,gDAAgD;AAGlE,QAAM,YAAY,YAAY,IAAI;AAElC,MAAI,CAAC;AACH,UAAM,IAAI,MAAM,iDAAiD;AAGnE,QAAM,KAAK,eAAe;AAAA,IACxB,MAAM;AAAA,EAAA,CACP;AAED,KAAG,gBAAgB;AAAA,IACjB;AAAA,MACE,MAAM;AAAA,MACN,OAAO;AAAA,IAAA;AAAA,EACT,CACD;AAED,MAAI;AACJ,MAAI;AACF,mBAAe,MAAM,GAAG;AAAA,MACtB,GAAG,WAAW,IAAI,aAAa;AAAA,IAAA;AAAA,EAEnC,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR,gDAAgD,SAAS;AAAA,MACzD,EAAE,OAAO,MAAA;AAAA,IAAM;AAAA,EAEnB;AAEA,MAAI,CAAC,gBAAgB,OAAO,aAAa,UAAW;AAClD,UAAM,IAAI;AAAA,MACR,uBAAuB,SAAS;AAAA,IAAA;AAIpC,SAAO,aAAa,OAAO,aAAa,QAAQ,OAAO;AACzD;"}
1
+ {"version":3,"file":"_internal.js","sources":["../src/_internal/render.ts"],"sourcesContent":["import { createInstance } from \"@sanity/federation/runtime\";\nimport { log } from \"@sanity/federation/runtime/plugins/log\";\nimport { createLogger } from \"../log\";\n\nconst logger = createLogger({\n namespace: \"sanity-workbench\",\n logLevel: \"debug\",\n});\n\n/**\n * Workbench configuration.\n *\n * @public\n */\nexport type Config = {\n /**\n * The organization ID to use when rendering the workbench.\n */\n organizationId: string | undefined;\n};\n\n/**\n * Options for rendering the workbench.\n *\n * @public\n */\nexport interface RenderWorkbenchOptions {\n reactStrictMode?: boolean;\n}\n\ndeclare global {\n interface ImportMetaEnv {\n readonly SANITY_INTERNAL_WORKBENCH_REMOTE_URL: string;\n }\n interface ImportMeta {\n readonly env: ImportMetaEnv;\n }\n}\n\n/**\n * Module defining the remote workbench application.\n *\n * @public\n */\ninterface WorkbenchRemoteModule {\n setup: (\n config?: Config,\n options?: RenderWorkbenchOptions,\n ) => {\n render(rootElement: HTMLElement): () => void;\n };\n}\n\nconst REMOTE_NAME = \"workbench-remote\";\nconst REMOTE_MODULE = \"App\";\n\n/**\n * Creates a Module Federation instance, loads a remote workbench\n * application, and renders it into the provided root element.\n *\n * @param rootElement - The DOM element to render into\n * @param config - Workbench configuration (reserved for future use)\n * @param options - Rendering options forwarded to the remote\n * @returns A cleanup function that unmounts the remote application\n *\n * @public\n */\nexport async function renderWorkbench(\n rootElement: HTMLElement,\n config?: Config,\n options?: RenderWorkbenchOptions,\n) {\n if (!rootElement) {\n throw new Error(\"Missing root element to mount application into\");\n }\n\n const remoteUrl = import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL;\n\n if (!remoteUrl) {\n throw new Error(\"SANITY_INTERNAL_WORKBENCH_REMOTE_URL is not set\");\n }\n\n const mf = createInstance({\n name: \"sanity-workbench\",\n plugins: [log(logger.debug)],\n\n remotes: [\n {\n name: REMOTE_NAME,\n entry: remoteUrl,\n },\n ],\n });\n\n let remoteModule = await mf.loadRemote<WorkbenchRemoteModule>(\n `${REMOTE_NAME}/${REMOTE_MODULE}`,\n );\n\n if (!remoteModule || typeof remoteModule.setup !== \"function\") {\n throw new Error(\n `Remote module \"${REMOTE_NAME}/${REMOTE_MODULE}\" did not expose a setup function`,\n );\n }\n\n const instance = remoteModule.setup(config, options);\n\n return instance.render(rootElement);\n}\n"],"names":[],"mappings":";;;AAIA,MAAM,SAAS,aAAa;AAAA,EAC1B,WAAW;AAAA,EACX,UAAU;AACZ,CAAC,GA8CK,cAAc,oBACd,gBAAgB;AAatB,eAAsB,gBACpB,aACA,QACA,SACA;AACA,MAAI,CAAC;AACH,UAAM,IAAI,MAAM,gDAAgD;AAGlE,QAAM,YAAY,YAAY,IAAI;AAElC,MAAI,CAAC;AACH,UAAM,IAAI,MAAM,iDAAiD;AAenE,MAAI,eAAe,MAZR,eAAe;AAAA,IACxB,MAAM;AAAA,IACN,SAAS,CAAC,IAAI,OAAO,KAAK,CAAC;AAAA,IAE3B,SAAS;AAAA,MACP;AAAA,QACE,MAAM;AAAA,QACN,OAAO;AAAA,MAAA;AAAA,IACT;AAAA,EACF,CACD,EAE2B;AAAA,IAC1B,GAAG,WAAW,IAAI,aAAa;AAAA,EAAA;AAGjC,MAAI,CAAC,gBAAgB,OAAO,aAAa,SAAU;AACjD,UAAM,IAAI;AAAA,MACR,kBAAkB,WAAW,IAAI,aAAa;AAAA,IAAA;AAMlD,SAFiB,aAAa,MAAM,QAAQ,OAAO,EAEnC,OAAO,WAAW;AACpC;"}
package/dist/log.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @public
3
+ */
4
+ export declare function createLogger({
5
+ namespace,
6
+ context: baseContext,
7
+ logLevel,
8
+ }?: LoggerOptions): Logger;
9
+
10
+ declare type LogContext = {
11
+ [key: string]: unknown;
12
+ };
13
+
14
+ /**
15
+ * @public
16
+ */
17
+ export declare interface Logger {
18
+ error: (message: string, context?: LogContext) => void;
19
+ warn: (message: string, context?: LogContext) => void;
20
+ info: (message: string, context?: LogContext) => void;
21
+ debug: (message: string, context?: LogContext) => void;
22
+ }
23
+
24
+ declare interface LoggerOptions {
25
+ namespace?: LogNamespace;
26
+ context?: LogContext;
27
+ logLevel?: LogLevel;
28
+ }
29
+
30
+ /**
31
+ * Log levels in order of verbosity (least to most)
32
+ * - none: Silent
33
+ * - error: Critical failures that prevent operation
34
+ * - warn: Issues that may cause problems but don't stop execution
35
+ * - info: High-level informational messages (default)
36
+ * - debug: Detailed debugging information (maintainer level)
37
+ * - trace: Very detailed tracing — sets `internal: true` on context
38
+ * @public
39
+ */
40
+ export declare type LogLevel = "none" | "error" | "warn" | "info" | "debug";
41
+
42
+ /**
43
+ * Namespaces organize logs by functional domain.
44
+ * @internal
45
+ */
46
+ export declare type LogNamespace = string;
47
+
48
+ export {};
package/dist/log.js ADDED
@@ -0,0 +1,29 @@
1
+ const LEVELS = ["none", "error", "warn", "info", "debug"];
2
+ function createLogger({
3
+ namespace,
4
+ context: baseContext,
5
+ logLevel = "info"
6
+ } = {}) {
7
+ function isLevelEnabled(level) {
8
+ return LEVELS.indexOf(level) <= LEVELS.indexOf(logLevel);
9
+ }
10
+ function logAtLevel(level, message, context) {
11
+ if (!isLevelEnabled(level)) return;
12
+ const merged = baseContext ?? context ? { ...baseContext, ...context } : void 0, args = [
13
+ ...namespace ? [`[${namespace}]`] : [],
14
+ message,
15
+ ...merged ? [merged] : []
16
+ ];
17
+ level === "error" ? console.error(...args) : level === "warn" ? console.warn(...args) : level === "info" ? console.info(...args) : console.debug(...args);
18
+ }
19
+ return {
20
+ error: (message, context) => logAtLevel("error", message, context),
21
+ warn: (message, context) => logAtLevel("warn", message, context),
22
+ info: (message, context) => logAtLevel("info", message, context),
23
+ debug: (message, context) => logAtLevel("debug", message, context)
24
+ };
25
+ }
26
+ export {
27
+ createLogger
28
+ };
29
+ //# sourceMappingURL=log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log.js","sources":["../src/log/index.ts"],"sourcesContent":["/**\n * Log levels in order of verbosity (least to most)\n * - none: Silent\n * - error: Critical failures that prevent operation\n * - warn: Issues that may cause problems but don't stop execution\n * - info: High-level informational messages (default)\n * - debug: Detailed debugging information (maintainer level)\n * - trace: Very detailed tracing — sets `internal: true` on context\n * @public\n */\nexport type LogLevel = \"none\" | \"error\" | \"warn\" | \"info\" | \"debug\";\n\n/**\n * Namespaces organize logs by functional domain.\n * @internal\n */\nexport type LogNamespace = string;\n\ntype LogContext = { [key: string]: unknown };\n\n/**\n * @public\n */\nexport interface Logger {\n error: (message: string, context?: LogContext) => void;\n warn: (message: string, context?: LogContext) => void;\n info: (message: string, context?: LogContext) => void;\n debug: (message: string, context?: LogContext) => void;\n}\n\nconst LEVELS: readonly LogLevel[] = [\"none\", \"error\", \"warn\", \"info\", \"debug\"];\n\ninterface LoggerOptions {\n namespace?: LogNamespace;\n context?: LogContext;\n logLevel?: LogLevel;\n}\n\n/**\n * @public\n */\nexport function createLogger({\n namespace,\n context: baseContext,\n logLevel = \"info\",\n}: LoggerOptions = {}): Logger {\n function isLevelEnabled(level: LogLevel): boolean {\n return LEVELS.indexOf(level) <= LEVELS.indexOf(logLevel);\n }\n\n function logAtLevel(\n level: LogLevel,\n message: string,\n context?: LogContext,\n ): void {\n if (!isLevelEnabled(level)) return;\n\n const merged =\n (baseContext ?? context) ? { ...baseContext, ...context } : undefined;\n const args: unknown[] = [\n ...(namespace ? [`[${namespace}]`] : []),\n message,\n ...(merged ? [merged] : []),\n ];\n\n if (level === \"error\") console.error(...args);\n else if (level === \"warn\") console.warn(...args);\n // oxlint-disable-next-line no-console\n else if (level === \"info\") console.info(...args);\n // oxlint-disable-next-line no-console\n else console.debug(...args);\n }\n\n return {\n error: (message, context) => logAtLevel(\"error\", message, context),\n warn: (message, context) => logAtLevel(\"warn\", message, context),\n info: (message, context) => logAtLevel(\"info\", message, context),\n debug: (message, context) => logAtLevel(\"debug\", message, context),\n };\n}\n"],"names":[],"mappings":"AA8BA,MAAM,SAA8B,CAAC,QAAQ,SAAS,QAAQ,QAAQ,OAAO;AAWtE,SAAS,aAAa;AAAA,EAC3B;AAAA,EACA,SAAS;AAAA,EACT,WAAW;AACb,IAAmB,IAAY;AAC7B,WAAS,eAAe,OAA0B;AAChD,WAAO,OAAO,QAAQ,KAAK,KAAK,OAAO,QAAQ,QAAQ;AAAA,EACzD;AAEA,WAAS,WACP,OACA,SACA,SACM;AACN,QAAI,CAAC,eAAe,KAAK,EAAG;AAE5B,UAAM,SACH,eAAe,UAAW,EAAE,GAAG,aAAa,GAAG,QAAA,IAAY,QACxD,OAAkB;AAAA,MACtB,GAAI,YAAY,CAAC,IAAI,SAAS,GAAG,IAAI,CAAA;AAAA,MACrC;AAAA,MACA,GAAI,SAAS,CAAC,MAAM,IAAI,CAAA;AAAA,IAAC;AAGvB,cAAU,UAAS,QAAQ,MAAM,GAAG,IAAI,IACnC,UAAU,SAAQ,QAAQ,KAAK,GAAG,IAAI,IAEtC,UAAU,SAAQ,QAAQ,KAAK,GAAG,IAAI,IAE1C,QAAQ,MAAM,GAAG,IAAI;AAAA,EAC5B;AAEA,SAAO;AAAA,IACL,OAAO,CAAC,SAAS,YAAY,WAAW,SAAS,SAAS,OAAO;AAAA,IACjE,MAAM,CAAC,SAAS,YAAY,WAAW,QAAQ,SAAS,OAAO;AAAA,IAC/D,MAAM,CAAC,SAAS,YAAY,WAAW,QAAQ,SAAS,OAAO;AAAA,IAC/D,OAAO,CAAC,SAAS,YAAY,WAAW,SAAS,SAAS,OAAO;AAAA,EAAA;AAErE;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/workbench",
3
- "version": "0.1.0-alpha.2",
3
+ "version": "0.1.0-alpha.3",
4
4
  "description": "Workbench component for the Sanity Content Operating System",
5
5
  "keywords": [],
6
6
  "homepage": "https://github.com/sanity-io/workbench/packages/@sanity/workbench#readme",
@@ -24,6 +24,10 @@
24
24
  "source": "./src/_exports/_internal.ts",
25
25
  "default": "./dist/_internal.js"
26
26
  },
27
+ "./log": {
28
+ "source": "./src/_exports/log.ts",
29
+ "default": "./dist/log.js"
30
+ },
27
31
  "./package.json": "./package.json"
28
32
  },
29
33
  "dependencies": {
@@ -31,7 +35,7 @@
31
35
  },
32
36
  "devDependencies": {
33
37
  "@sanity/pkg-utils": "^9.2.3",
34
- "typescript": "^5.9.2",
38
+ "typescript": "^6.0.2",
35
39
  "@repo/oxc-config": "0.0.0",
36
40
  "@repo/tsconfig": "0.0.1"
37
41
  },
@@ -0,0 +1 @@
1
+ export * from "../log";
@@ -1,11 +1,23 @@
1
1
  import { createInstance } from "@sanity/federation/runtime";
2
+ import { log } from "@sanity/federation/runtime/plugins/log";
3
+ import { createLogger } from "../log";
4
+
5
+ const logger = createLogger({
6
+ namespace: "sanity-workbench",
7
+ logLevel: "debug",
8
+ });
2
9
 
3
10
  /**
4
11
  * Workbench configuration.
5
12
  *
6
13
  * @public
7
14
  */
8
- export type Config = undefined;
15
+ export type Config = {
16
+ /**
17
+ * The organization ID to use when rendering the workbench.
18
+ */
19
+ organizationId: string | undefined;
20
+ };
9
21
 
10
22
  /**
11
23
  * Options for rendering the workbench.
@@ -25,17 +37,23 @@ declare global {
25
37
  }
26
38
  }
27
39
 
28
- const REMOTE_NAME = "workbench-remote";
29
- const REMOTE_MODULE = "App";
30
-
31
- interface RemoteModule {
32
- render(
33
- rootElement: HTMLElement,
40
+ /**
41
+ * Module defining the remote workbench application.
42
+ *
43
+ * @public
44
+ */
45
+ interface WorkbenchRemoteModule {
46
+ setup: (
34
47
  config?: Config,
35
48
  options?: RenderWorkbenchOptions,
36
- ): () => void;
49
+ ) => {
50
+ render(rootElement: HTMLElement): () => void;
51
+ };
37
52
  }
38
53
 
54
+ const REMOTE_NAME = "workbench-remote";
55
+ const REMOTE_MODULE = "App";
56
+
39
57
  /**
40
58
  * Creates a Module Federation instance, loads a remote workbench
41
59
  * application, and renders it into the provided root element.
@@ -51,7 +69,7 @@ export async function renderWorkbench(
51
69
  rootElement: HTMLElement,
52
70
  config?: Config,
53
71
  options?: RenderWorkbenchOptions,
54
- ): Promise<() => void> {
72
+ ) {
55
73
  if (!rootElement) {
56
74
  throw new Error("Missing root element to mount application into");
57
75
  }
@@ -64,32 +82,27 @@ export async function renderWorkbench(
64
82
 
65
83
  const mf = createInstance({
66
84
  name: "sanity-workbench",
85
+ plugins: [log(logger.debug)],
86
+
87
+ remotes: [
88
+ {
89
+ name: REMOTE_NAME,
90
+ entry: remoteUrl,
91
+ },
92
+ ],
67
93
  });
68
94
 
69
- mf.registerRemotes([
70
- {
71
- name: REMOTE_NAME,
72
- entry: remoteUrl,
73
- },
74
- ]);
95
+ let remoteModule = await mf.loadRemote<WorkbenchRemoteModule>(
96
+ `${REMOTE_NAME}/${REMOTE_MODULE}`,
97
+ );
75
98
 
76
- let remoteModule: RemoteModule | null;
77
- try {
78
- remoteModule = await mf.loadRemote<RemoteModule>(
79
- `${REMOTE_NAME}/${REMOTE_MODULE}`,
80
- );
81
- } catch (error) {
99
+ if (!remoteModule || typeof remoteModule.setup !== "function") {
82
100
  throw new Error(
83
- `Failed to load remote workbench module from "${remoteUrl}"`,
84
- { cause: error },
101
+ `Remote module "${REMOTE_NAME}/${REMOTE_MODULE}" did not expose a setup function`,
85
102
  );
86
103
  }
87
104
 
88
- if (!remoteModule || typeof remoteModule.render !== "function") {
89
- throw new Error(
90
- `Remote module from "${remoteUrl}" did not expose a render function`,
91
- );
92
- }
105
+ const instance = remoteModule.setup(config, options);
93
106
 
94
- return remoteModule.render(rootElement, config, options);
107
+ return instance.render(rootElement);
95
108
  }
@@ -0,0 +1,133 @@
1
+ import {
2
+ type MockInstance,
3
+ afterEach,
4
+ beforeEach,
5
+ describe,
6
+ expect,
7
+ it,
8
+ vi,
9
+ } from "vitest";
10
+
11
+ import { createLogger } from ".";
12
+
13
+ describe("createLogger", () => {
14
+ let error: MockInstance;
15
+ let warn: MockInstance;
16
+ let info: MockInstance;
17
+ let debug: MockInstance;
18
+
19
+ beforeEach(() => {
20
+ error = vi.spyOn(console, "error").mockImplementation(() => undefined);
21
+ warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
22
+ info = vi.spyOn(console, "info").mockImplementation(() => undefined);
23
+ debug = vi.spyOn(console, "debug").mockImplementation(() => undefined);
24
+ });
25
+
26
+ afterEach(() => vi.restoreAllMocks());
27
+
28
+ it("'none': logs nothing", () => {
29
+ const logger = createLogger({ logLevel: "none" });
30
+
31
+ logger.error("e");
32
+ logger.warn("w");
33
+ logger.info("i");
34
+ logger.debug("d");
35
+
36
+ expect(error).not.toHaveBeenCalled();
37
+ expect(warn).not.toHaveBeenCalled();
38
+ expect(info).not.toHaveBeenCalled();
39
+ expect(debug).not.toHaveBeenCalled();
40
+ });
41
+
42
+ it("'error': logs only error", () => {
43
+ const logger = createLogger({ logLevel: "error" });
44
+
45
+ logger.error("e");
46
+ logger.warn("w");
47
+ logger.info("i");
48
+ logger.debug("d");
49
+
50
+ expect(error).toHaveBeenCalledOnce();
51
+ expect(warn).not.toHaveBeenCalled();
52
+ expect(info).not.toHaveBeenCalled();
53
+ expect(debug).not.toHaveBeenCalled();
54
+ });
55
+
56
+ it("'warn': logs error and warn", () => {
57
+ const logger = createLogger({ logLevel: "warn" });
58
+
59
+ logger.error("e");
60
+ logger.warn("w");
61
+ logger.info("i");
62
+ logger.debug("d");
63
+
64
+ expect(error).toHaveBeenCalledOnce();
65
+ expect(warn).toHaveBeenCalledOnce();
66
+ expect(info).not.toHaveBeenCalled();
67
+ expect(debug).not.toHaveBeenCalled();
68
+ });
69
+
70
+ it("'info' (default): logs error, warn, and info", () => {
71
+ const logger = createLogger();
72
+
73
+ logger.error("e");
74
+ logger.warn("w");
75
+ logger.info("i");
76
+ logger.debug("d");
77
+
78
+ expect(error).toHaveBeenCalledOnce();
79
+ expect(warn).toHaveBeenCalledOnce();
80
+ expect(info).toHaveBeenCalledOnce();
81
+ expect(debug).not.toHaveBeenCalled();
82
+ });
83
+
84
+ it("'debug': logs everything", () => {
85
+ const logger = createLogger({ logLevel: "debug" });
86
+
87
+ logger.error("e");
88
+ logger.warn("w");
89
+ logger.info("i");
90
+ logger.debug("d");
91
+
92
+ expect(error).toHaveBeenCalledOnce();
93
+ expect(warn).toHaveBeenCalledOnce();
94
+ expect(info).toHaveBeenCalledOnce();
95
+ expect(debug).toHaveBeenCalledOnce();
96
+ });
97
+
98
+ it("prepends [namespace] to all messages", () => {
99
+ const logger = createLogger({ namespace: "myns", logLevel: "debug" });
100
+
101
+ logger.error("msg");
102
+ logger.warn("msg");
103
+ logger.info("msg");
104
+ logger.debug("msg");
105
+
106
+ expect(error).toHaveBeenCalledWith("[myns]", "msg");
107
+ expect(warn).toHaveBeenCalledWith("[myns]", "msg");
108
+ expect(info).toHaveBeenCalledWith("[myns]", "msg");
109
+ expect(debug).toHaveBeenCalledWith("[myns]", "msg");
110
+ });
111
+
112
+ it("passes context as a third argument when provided", () => {
113
+ const logger = createLogger({ namespace: "ns", logLevel: "debug" });
114
+ const ctx = { requestId: "123" };
115
+ logger.error("msg", ctx);
116
+ expect(error).toHaveBeenCalledWith("[ns]", "msg", ctx);
117
+ });
118
+
119
+ it("merges base context with call-site context", () => {
120
+ const logger = createLogger({
121
+ namespace: "ns",
122
+ context: { service: "workbench" },
123
+ logLevel: "debug",
124
+ });
125
+
126
+ logger.debug("msg", { requestId: "42" });
127
+
128
+ expect(debug).toHaveBeenCalledWith("[ns]", "msg", {
129
+ service: "workbench",
130
+ requestId: "42",
131
+ });
132
+ });
133
+ });
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Log levels in order of verbosity (least to most)
3
+ * - none: Silent
4
+ * - error: Critical failures that prevent operation
5
+ * - warn: Issues that may cause problems but don't stop execution
6
+ * - info: High-level informational messages (default)
7
+ * - debug: Detailed debugging information (maintainer level)
8
+ * - trace: Very detailed tracing — sets `internal: true` on context
9
+ * @public
10
+ */
11
+ export type LogLevel = "none" | "error" | "warn" | "info" | "debug";
12
+
13
+ /**
14
+ * Namespaces organize logs by functional domain.
15
+ * @internal
16
+ */
17
+ export type LogNamespace = string;
18
+
19
+ type LogContext = { [key: string]: unknown };
20
+
21
+ /**
22
+ * @public
23
+ */
24
+ export interface Logger {
25
+ error: (message: string, context?: LogContext) => void;
26
+ warn: (message: string, context?: LogContext) => void;
27
+ info: (message: string, context?: LogContext) => void;
28
+ debug: (message: string, context?: LogContext) => void;
29
+ }
30
+
31
+ const LEVELS: readonly LogLevel[] = ["none", "error", "warn", "info", "debug"];
32
+
33
+ interface LoggerOptions {
34
+ namespace?: LogNamespace;
35
+ context?: LogContext;
36
+ logLevel?: LogLevel;
37
+ }
38
+
39
+ /**
40
+ * @public
41
+ */
42
+ export function createLogger({
43
+ namespace,
44
+ context: baseContext,
45
+ logLevel = "info",
46
+ }: LoggerOptions = {}): Logger {
47
+ function isLevelEnabled(level: LogLevel): boolean {
48
+ return LEVELS.indexOf(level) <= LEVELS.indexOf(logLevel);
49
+ }
50
+
51
+ function logAtLevel(
52
+ level: LogLevel,
53
+ message: string,
54
+ context?: LogContext,
55
+ ): void {
56
+ if (!isLevelEnabled(level)) return;
57
+
58
+ const merged =
59
+ (baseContext ?? context) ? { ...baseContext, ...context } : undefined;
60
+ const args: unknown[] = [
61
+ ...(namespace ? [`[${namespace}]`] : []),
62
+ message,
63
+ ...(merged ? [merged] : []),
64
+ ];
65
+
66
+ if (level === "error") console.error(...args);
67
+ else if (level === "warn") console.warn(...args);
68
+ // oxlint-disable-next-line no-console
69
+ else if (level === "info") console.info(...args);
70
+ // oxlint-disable-next-line no-console
71
+ else console.debug(...args);
72
+ }
73
+
74
+ return {
75
+ error: (message, context) => logAtLevel("error", message, context),
76
+ warn: (message, context) => logAtLevel("warn", message, context),
77
+ info: (message, context) => logAtLevel("info", message, context),
78
+ debug: (message, context) => logAtLevel("debug", message, context),
79
+ };
80
+ }