@sanity/workbench 0.1.0-alpha.1 → 0.1.0-alpha.10

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.
@@ -0,0 +1,34 @@
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
+ const logger = createLogger({
27
+ namespace: "sanity-workbench",
28
+ logLevel: "debug"
29
+ });
30
+ export {
31
+ createLogger,
32
+ logger
33
+ };
34
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../src/core/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\n/**\n * Shared workbench logger instance. Use this from both the workbench host\n * and its remotes so lifecycle and diagnostic logs appear under a single\n * namespace.\n *\n * @public\n */\nexport const logger: Logger = createLogger({\n namespace: \"sanity-workbench\",\n logLevel: \"debug\",\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;AASO,MAAM,SAAiB,aAAa;AAAA,EACzC,WAAW;AAAA,EACX,UAAU;AACZ,CAAC;"}
@@ -1,7 +1,41 @@
1
1
  /**
2
+ * Workbench configuration.
3
+ *
4
+ * @public
5
+ */
6
+ export declare interface Config {
7
+ /**
8
+ * The organization ID to use when rendering the workbench.
9
+ */
10
+ organizationId?: string;
11
+ }
12
+
13
+ /**
14
+ * Returns the API host based on the `__SANITY_STAGING__` build-time flag.
15
+ * If the flag is set to `true`, the staging API host is returned.
16
+ * Otherwise, the production API host is returned.
17
+ *
18
+ * @internal
19
+ */
20
+ export declare function getApiHost(): string | undefined;
21
+
22
+ /**
23
+ * Returns the current Sanity environment based on the `__SANITY_STAGING__` build-time flag.
24
+ * If the flag is set to `true`, "staging" is returned.
25
+ * Otherwise, "production" is returned.
26
+ *
27
+ * @internal
28
+ */
29
+ export declare function getSanityEnv(): "staging" | "production";
30
+
31
+ /**
32
+ * Options for rendering a remote module, such as a user application.
33
+ *
2
34
  * @public
3
35
  */
4
- export declare type Config = undefined;
36
+ declare interface RemoteModuleRenderOptions {
37
+ reactStrictMode?: boolean;
38
+ }
5
39
 
6
40
  /**
7
41
  * Creates a Module Federation instance, loads a remote workbench
@@ -21,10 +55,10 @@ export declare function renderWorkbench(
21
55
  ): Promise<() => void>;
22
56
 
23
57
  /**
58
+ * Options for rendering the workbench.
59
+ *
24
60
  * @public
25
61
  */
26
- export declare interface RenderWorkbenchOptions {
27
- reactStrictMode?: boolean;
28
- }
62
+ export declare interface RenderWorkbenchOptions extends RemoteModuleRenderOptions {}
29
63
 
30
64
  export {};
package/dist/_internal.js CHANGED
@@ -1,38 +1,54 @@
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 { BehaviorSubject } from "rxjs";
4
+ import { logger } from "./_chunks-es/index.js";
5
+ const REMOTE_NAME = "workbench-remote", REMOTE_MODULE = "App", LOCAL_APPS_HMR_EVENT = "sanity:workbench:local-applications", LOCAL_APPS_HMR_REQUEST = "sanity:workbench:get-local-applications";
3
6
  async function renderWorkbench(rootElement, config, options) {
4
7
  if (!rootElement)
5
8
  throw new Error("Missing root element to mount application into");
6
- const remoteUrl = import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL;
7
- if (!remoteUrl)
8
- 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
- }
9
+ const remoteUrl = import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL ?? "https://workbench-remote.sanity.dev/mf-manifest.json";
10
+ let remoteModule = await createInstance({
11
+ name: "sanity-workbench",
12
+ plugins: [log(logger.debug)],
13
+ remotes: [
14
+ {
15
+ name: REMOTE_NAME,
16
+ entry: remoteUrl
17
+ }
18
+ ]
19
+ }).loadRemote(
20
+ `${REMOTE_NAME}/${REMOTE_MODULE}`
21
+ );
29
22
  if (!remoteModule || typeof remoteModule.render != "function")
30
23
  throw new Error(
31
- `Remote module from "${remoteUrl}" did not expose a render function`
24
+ `Remote module "${REMOTE_NAME}/${REMOTE_MODULE}" did not expose a render function`
32
25
  );
33
- return remoteModule.render(rootElement, config, options);
26
+ let localApplications, cleanupHmr = () => {
27
+ };
28
+ if (import.meta.hot) {
29
+ const localApps$ = new BehaviorSubject([]), handler = (payload) => {
30
+ localApps$.next(payload.applications);
31
+ };
32
+ import.meta.hot.on(LOCAL_APPS_HMR_EVENT, handler), import.meta.hot.send(LOCAL_APPS_HMR_REQUEST), localApplications = localApps$, cleanupHmr = () => import.meta.hot?.off(LOCAL_APPS_HMR_EVENT, handler);
33
+ }
34
+ const unmount = remoteModule.render(
35
+ rootElement,
36
+ { config, localApplications },
37
+ options
38
+ );
39
+ return () => {
40
+ cleanupHmr(), unmount();
41
+ };
42
+ }
43
+ function getApiHost() {
44
+ return getSanityEnv() === "staging" ? "https://api.sanity.work" : "https://api.sanity.io";
45
+ }
46
+ function getSanityEnv() {
47
+ return typeof __SANITY_STAGING__ < "u" && __SANITY_STAGING__ === !0 ? "staging" : "production";
34
48
  }
35
49
  export {
50
+ getApiHost,
51
+ getSanityEnv,
36
52
  renderWorkbench
37
53
  };
38
54
  //# sourceMappingURL=_internal.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_internal.js","sources":["../src/_internal/render.ts"],"sourcesContent":["import { createInstance } from \"@sanity/federation/runtime\";\n\nconst REMOTE_NAME = \"workbench-remote\";\nconst REMOTE_MODULE = \"./App\";\n\n/**\n * @public\n */\nexport type Config = undefined;\n\n/**\n * @public\n */\nexport interface RenderWorkbenchOptions {\n reactStrictMode?: boolean;\n}\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 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":";AAEA,MAAM,cAAc,oBACd,gBAAgB;AAiCtB,eAAsB,gBACpB,aACA,QACA,SACqB;AACrB,MAAI,CAAC;AACH,UAAM,IAAI,MAAM,gDAAgD;AAGlE,QAAM,YAAY,YAAY,IAAI;AAClC,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","../src/_internal/env.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\n\nimport { createInstance } from \"@sanity/federation/runtime\";\nimport { log } from \"@sanity/federation/runtime/plugins/log\";\nimport { BehaviorSubject, type Observable } from \"rxjs\";\n\nimport type { Config, RemoteModuleRenderOptions } from \"../core/config\";\nimport { logger } from \"../core/log\";\nimport type { LocalUserApplication } from \"../core/user-applications/user-application\";\n\n/**\n * Options for rendering the workbench.\n *\n * @public\n */\nexport interface RenderWorkbenchOptions extends RemoteModuleRenderOptions {}\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\ntype RemoteModule<TProps extends any> = {\n render: (\n rootElement: HTMLElement,\n props: TProps,\n options?: RenderWorkbenchOptions,\n ) => () => void;\n};\n\n/**\n * Module defining the remote workbench application.\n *\n * @internal\n */\ntype WorkbenchRemoteModule = RemoteModule<{\n config?: Config;\n localApplications?: Observable<LocalUserApplication[]>;\n}>;\n\nconst REMOTE_NAME = \"workbench-remote\";\nconst REMOTE_MODULE = \"App\";\n\nconst LOCAL_APPS_HMR_EVENT = \"sanity:workbench:local-applications\";\nconst LOCAL_APPS_HMR_REQUEST = \"sanity:workbench:get-local-applications\";\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 =\n import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL ??\n \"https://workbench-remote.sanity.dev/mf-manifest.json\";\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.render !== \"function\") {\n throw new Error(\n `Remote module \"${REMOTE_NAME}/${REMOTE_MODULE}\" did not expose a render function`,\n );\n }\n\n let localApplications = undefined;\n let cleanupHmr = () => {};\n\n if (import.meta.hot) {\n const localApps$ = new BehaviorSubject<LocalUserApplication[]>([]);\n\n const handler = (payload: { applications: LocalUserApplication[] }) => {\n localApps$.next(payload.applications);\n };\n\n import.meta.hot.on(LOCAL_APPS_HMR_EVENT, handler);\n import.meta.hot.send(LOCAL_APPS_HMR_REQUEST);\n\n localApplications = localApps$;\n\n cleanupHmr = () => import.meta.hot?.off(LOCAL_APPS_HMR_EVENT, handler);\n }\n\n const unmount = remoteModule.render(\n rootElement,\n { config, localApplications },\n options,\n );\n\n return () => {\n cleanupHmr();\n unmount();\n };\n}\n","declare const __SANITY_STAGING__: boolean | undefined;\n\n/**\n * Returns the API host based on the `__SANITY_STAGING__` build-time flag.\n * If the flag is set to `true`, the staging API host is returned.\n * Otherwise, the production API host is returned.\n *\n * @internal\n */\nexport function getApiHost(): string | undefined {\n if (getSanityEnv() === \"staging\") {\n return \"https://api.sanity.work\";\n }\n return \"https://api.sanity.io\";\n}\n\n/**\n * Returns the current Sanity environment based on the `__SANITY_STAGING__` build-time flag.\n * If the flag is set to `true`, \"staging\" is returned.\n * Otherwise, \"production\" is returned.\n *\n * @internal\n */\nexport function getSanityEnv(): \"staging\" | \"production\" {\n if (\n typeof __SANITY_STAGING__ !== \"undefined\" &&\n __SANITY_STAGING__ === true\n ) {\n return \"staging\";\n }\n return \"production\";\n}\n"],"names":[],"mappings":";;;;AA4CA,MAAM,cAAc,oBACd,gBAAgB,OAEhB,uBAAuB,uCACvB,yBAAyB;AAa/B,eAAsB,gBACpB,aACA,QACA,SACA;AACA,MAAI,CAAC;AACH,UAAM,IAAI,MAAM,gDAAgD;AAGlE,QAAM,YACJ,YAAY,IAAI,wCAChB;AAcF,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,UAAW;AAClD,UAAM,IAAI;AAAA,MACR,kBAAkB,WAAW,IAAI,aAAa;AAAA,IAAA;AAIlD,MAAI,mBACA,aAAa,MAAM;AAAA,EAAC;AAExB,MAAI,YAAY,KAAK;AACnB,UAAM,aAAa,IAAI,gBAAwC,CAAA,CAAE,GAE3D,UAAU,CAAC,YAAsD;AACrE,iBAAW,KAAK,QAAQ,YAAY;AAAA,IACtC;AAEA,gBAAY,IAAI,GAAG,sBAAsB,OAAO,GAChD,YAAY,IAAI,KAAK,sBAAsB,GAE3C,oBAAoB,YAEpB,aAAa,MAAM,YAAY,KAAK,IAAI,sBAAsB,OAAO;AAAA,EACvE;AAEA,QAAM,UAAU,aAAa;AAAA,IAC3B;AAAA,IACA,EAAE,QAAQ,kBAAA;AAAA,IACV;AAAA,EAAA;AAGF,SAAO,MAAM;AACX,eAAA,GACA,QAAA;AAAA,EACF;AACF;ACnHO,SAAS,aAAiC;AAC/C,SAAI,aAAA,MAAmB,YACd,4BAEF;AACT;AASO,SAAS,eAAyC;AACvD,SACE,OAAO,qBAAuB,OAC9B,uBAAuB,KAEhB,YAEF;AACT;"}