@sanity/workbench-cli 2.10.0 → 2.11.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/_exports/_internal_worker_bus.d.ts +1 -1
- package/dist/_exports/{defineService-C1MhDwmh.d.ts → defineService-DUaxVpWq.d.ts} +32 -10
- package/dist/_exports/index.d.ts +1 -1
- package/dist/actions/build/services/workerBus.js +98 -20
- package/dist/actions/build/services/workerBus.js.map +1 -1
- package/dist/defineService.js +24 -3
- package/dist/defineService.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as ServiceBus } from "./defineService-
|
|
1
|
+
import { n as ServiceBus } from "./defineService-DUaxVpWq.js";
|
|
2
2
|
/**
|
|
3
3
|
* The worker's side of the `workbench.bus.*` wire contract. The host relays
|
|
4
4
|
* each request to the Dashboard bus and stamps it with the worker's identity,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { l as SERVICE_CONTRACT_VERSION, u as ServiceType } from "./contract-D_HnLQtT.js";
|
|
2
|
-
import { MessageBus, MessageBusAbortOptions, StateTopic, ValueOf } from "@sanity/sdk/dashboard";
|
|
2
|
+
import { EventTopic, MessageBus, MessageBusAbortOptions, MessageBusMessage, PayloadOf, ReplyOf, StateTopic, ValueOf } from "@sanity/sdk/dashboard";
|
|
3
3
|
/**
|
|
4
4
|
* The service's own declaration, surfaced to the callback.
|
|
5
5
|
* @public
|
|
@@ -9,14 +9,15 @@ interface ServiceInfo {
|
|
|
9
9
|
readonly type: string;
|
|
10
10
|
}
|
|
11
11
|
/**
|
|
12
|
-
* The message bus as a service sees it:
|
|
13
|
-
* `subscribe`
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* worker.
|
|
12
|
+
* The message bus as a service sees it: the SDK's `MessageBus` without the
|
|
13
|
+
* `subscribe` forms that return observables, which would make the service's
|
|
14
|
+
* project install rxjs. There is no `disconnect`: Dashboard owns the connection
|
|
15
|
+
* and ends it when it stops the worker.
|
|
17
16
|
* @public
|
|
18
17
|
*/
|
|
19
18
|
interface ServiceBus extends Omit<MessageBus, 'subscribe'> {
|
|
19
|
+
/** Runs a responder for each event until its signal aborts. */
|
|
20
|
+
subscribe<K extends EventTopic>(type: K, handler: (message: MessageBusMessage<PayloadOf<K>, ReplyOf<K>, K>) => void, options?: MessageBusAbortOptions): void;
|
|
20
21
|
/** Runs a handler for each state value until its signal aborts. */
|
|
21
22
|
subscribe<K extends StateTopic>(type: K, handler: (value: ValueOf<K>) => void, options?: MessageBusAbortOptions): void;
|
|
22
23
|
}
|
|
@@ -57,9 +58,30 @@ interface DefinedService<TType extends ServiceType = ServiceType> {
|
|
|
57
58
|
* The callback receives `bus`, its connection to the Dashboard message bus:
|
|
58
59
|
* `bus.emit` sends an event (such as a dock-badge update), `bus.query` reads the
|
|
59
60
|
* current value of a state topic, and `bus.subscribe` runs a handler on each
|
|
60
|
-
* new value of a state topic
|
|
61
|
-
* or timed-out
|
|
62
|
-
* `code` says why; it is not an
|
|
61
|
+
* new value of a state topic, or on each event of an event topic, until its
|
|
62
|
+
* `signal` aborts. A refused, unanswered or timed-out `emit` or `query` rejects
|
|
63
|
+
* with an `Error` named `MessageBusError` whose `code` says why; it is not an
|
|
64
|
+
* instance of the SDK's `MessageBusError` class.
|
|
65
|
+
*
|
|
66
|
+
* An event handler answers the sender with `message.reply(value)` or refuses
|
|
67
|
+
* with `message.reject(reason)`; one that throws refuses with code
|
|
68
|
+
* `HANDLER_THREW`. For example, a service that keeps a snapshot for its app's
|
|
69
|
+
* views, which listen with `useWorker` first and then post to it. A view's post
|
|
70
|
+
* arrives on `workers.post` as `{name, payload}`, and `workers.message` reaches
|
|
71
|
+
* only this app's views:
|
|
72
|
+
*
|
|
73
|
+
* ```ts
|
|
74
|
+
* export default unstable_defineService('worker', ({bus}) => {
|
|
75
|
+
* const controller = new AbortController()
|
|
76
|
+
* bus.subscribe('workers.post', (message) => message.reply(snapshot), {
|
|
77
|
+
* signal: controller.signal,
|
|
78
|
+
* })
|
|
79
|
+
* // Views that are already listening post again.
|
|
80
|
+
* bus.emit('workers.message', {type: 'welcome'})
|
|
81
|
+
* return () => controller.abort()
|
|
82
|
+
* })
|
|
83
|
+
* ```
|
|
84
|
+
*
|
|
63
85
|
* The callback can return a disposer, which runs when Dashboard stops the
|
|
64
86
|
* worker. By then the bus is closed: subscriptions have ended, `emit` and
|
|
65
87
|
* `query` reject with code `ABORTED`, and `subscribe` throws that error.
|
|
@@ -71,4 +93,4 @@ interface DefinedService<TType extends ServiceType = ServiceType> {
|
|
|
71
93
|
*/
|
|
72
94
|
declare function unstable_defineService<TType extends ServiceType>(type: TType, run: ServiceCallbacksByType[TType]): DefinedService<TType>;
|
|
73
95
|
export { ServiceInfo as a, ServiceContext as i, ServiceBus as n, unstable_defineService as o, ServiceCallback as r, DefinedService as t };
|
|
74
|
-
//# sourceMappingURL=defineService-
|
|
96
|
+
//# sourceMappingURL=defineService-DUaxVpWq.d.ts.map
|
package/dist/_exports/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { C as defineTileView, S as definePanelView, T as defineWindowView, _ as ViewSurface, a as DefineWebWorkerInput, c as PanelView, d as TileSize, f as TileView, g as ViewDeclaration, h as ViewComponentBaseProps, i as DefineTileViewInput, m as ViewComponent, n as DefineAssetSourceViewInput, o as DefineWindowViewInput, p as VIEW_CONTRACT_VERSION, r as DefinePanelViewInput, s as DockGroup, t as AssetSourceView, u as ServiceType, v as WebWorker, w as defineWebWorker, x as defineAssetSourceView, y as WindowView } from "./contract-D_HnLQtT.js";
|
|
2
|
-
import { a as ServiceInfo, i as ServiceContext, n as ServiceBus, o as unstable_defineService, r as ServiceCallback, t as DefinedService } from "./defineService-
|
|
2
|
+
import { a as ServiceInfo, i as ServiceContext, n as ServiceBus, o as unstable_defineService, r as ServiceCallback, t as DefinedService } from "./defineService-DUaxVpWq.js";
|
|
3
3
|
import { a as WorkbenchApp, c as isWorkbenchApp, i as MediaLibraryField, l as isWorkbenchConfig, n as DefineAppResult, o as WorkbenchConfig, r as DefineMediaLibraryInput, s as defineApplication, t as DefineAppInput, u as unstable_defineMediaLibrary } from "./defineApp-4hImcIIe.js";
|
|
4
4
|
import { AssetSourceComponentProps } from "@sanity/types";
|
|
5
5
|
/** @public */
|
|
@@ -15,7 +15,10 @@ const busError = (code, message)=>Object.assign(new Error(message || code), {
|
|
|
15
15
|
* @internal
|
|
16
16
|
*/ export function createWorkerBus() {
|
|
17
17
|
const pending = new Map();
|
|
18
|
+
// The worker can't tell a state topic from an event topic, so it stores every
|
|
19
|
+
// handler alike; the host's `value` or `message` decides how it is called.
|
|
18
20
|
const subscriptions = new Map();
|
|
21
|
+
const inFlight = new Map();
|
|
19
22
|
let nextId = 0;
|
|
20
23
|
let closed = false;
|
|
21
24
|
// Posts a request and returns a function that creates its promise on first
|
|
@@ -78,6 +81,56 @@ const busError = (code, message)=>Object.assign(new Error(message || code), {
|
|
|
78
81
|
if (outcome) onOutcome(outcome);
|
|
79
82
|
});
|
|
80
83
|
}
|
|
84
|
+
// Matches the SDK's `invokeResponder`, so a responder behaves the same in a
|
|
85
|
+
// worker as on the page.
|
|
86
|
+
function respond(handler, { messageId, meta, payload, type }) {
|
|
87
|
+
const controller = new AbortController();
|
|
88
|
+
inFlight.set(messageId, controller);
|
|
89
|
+
const answer = (result)=>{
|
|
90
|
+
if (inFlight.get(messageId) !== controller) return false;
|
|
91
|
+
inFlight.delete(messageId);
|
|
92
|
+
self.postMessage({
|
|
93
|
+
...result,
|
|
94
|
+
kind: 'workbench.bus.answer',
|
|
95
|
+
messageId
|
|
96
|
+
});
|
|
97
|
+
return true;
|
|
98
|
+
};
|
|
99
|
+
const warnIfIgnored = (answered, action)=>{
|
|
100
|
+
if (answered) return;
|
|
101
|
+
// eslint-disable-next-line no-console -- the worker's console is bridged to the host logger
|
|
102
|
+
console.warn(`Message bus ${action} ignored for "${type}": no waiting caller or already replied`);
|
|
103
|
+
};
|
|
104
|
+
const fail = ()=>answer({
|
|
105
|
+
error: {
|
|
106
|
+
code: 'HANDLER_THREW',
|
|
107
|
+
message: 'HANDLER_THREW'
|
|
108
|
+
},
|
|
109
|
+
ok: false
|
|
110
|
+
});
|
|
111
|
+
try {
|
|
112
|
+
const result = handler({
|
|
113
|
+
meta,
|
|
114
|
+
payload,
|
|
115
|
+
reject: (reason)=>warnIfIgnored(answer({
|
|
116
|
+
error: {
|
|
117
|
+
code: 'REFUSED',
|
|
118
|
+
message: reason ?? 'REFUSED'
|
|
119
|
+
},
|
|
120
|
+
ok: false
|
|
121
|
+
}), 'reject'),
|
|
122
|
+
reply: (value)=>warnIfIgnored(answer({
|
|
123
|
+
ok: true,
|
|
124
|
+
value
|
|
125
|
+
}), 'reply'),
|
|
126
|
+
signal: controller.signal,
|
|
127
|
+
type
|
|
128
|
+
});
|
|
129
|
+
if (result instanceof Promise) result.catch(fail);
|
|
130
|
+
} catch {
|
|
131
|
+
fail();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
81
134
|
const bus = {
|
|
82
135
|
emit: (topic, payload, options)=>{
|
|
83
136
|
const awaitReply = request({
|
|
@@ -124,6 +177,11 @@ const busError = (code, message)=>Object.assign(new Error(message || code), {
|
|
|
124
177
|
close: ()=>{
|
|
125
178
|
closed = true;
|
|
126
179
|
subscriptions.clear();
|
|
180
|
+
const controllers = [
|
|
181
|
+
...inFlight.values()
|
|
182
|
+
];
|
|
183
|
+
inFlight.clear();
|
|
184
|
+
for (const controller of controllers)controller.abort();
|
|
127
185
|
for (const settle of pending.values())settle({
|
|
128
186
|
error: busError('ABORTED'),
|
|
129
187
|
ok: false
|
|
@@ -131,26 +189,46 @@ const busError = (code, message)=>Object.assign(new Error(message || code), {
|
|
|
131
189
|
},
|
|
132
190
|
receive: (data)=>{
|
|
133
191
|
const message = data;
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
192
|
+
switch(message.kind){
|
|
193
|
+
case 'workbench.bus.cancel':
|
|
194
|
+
{
|
|
195
|
+
const controller = inFlight.get(message.messageId);
|
|
196
|
+
// Forget it first so an abort listener's reply is ignored.
|
|
197
|
+
inFlight.delete(message.messageId);
|
|
198
|
+
controller?.abort();
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
case 'workbench.bus.message':
|
|
202
|
+
{
|
|
203
|
+
const handler = subscriptions.get(message.id);
|
|
204
|
+
if (handler) respond(handler, message);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
case 'workbench.bus.reply':
|
|
208
|
+
{
|
|
209
|
+
const settle = pending.get(message.id);
|
|
210
|
+
if (message.ok) {
|
|
211
|
+
settle?.({
|
|
212
|
+
ok: true,
|
|
213
|
+
value: message.value
|
|
214
|
+
});
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
// A refused subscription has no promise to reject, so tell the author through the host logger.
|
|
218
|
+
if (subscriptions.delete(message.id)) {
|
|
219
|
+
// eslint-disable-next-line no-console -- the worker's console is bridged to the host logger
|
|
220
|
+
console.error(`Message bus subscription refused: ${message.error.code}: ${message.error.message}`);
|
|
221
|
+
}
|
|
222
|
+
settle?.({
|
|
223
|
+
error: busError(message.error.code, message.error.message),
|
|
224
|
+
ok: false
|
|
225
|
+
});
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
case 'workbench.bus.value':
|
|
229
|
+
{
|
|
230
|
+
subscriptions.get(message.id)?.(message.value);
|
|
231
|
+
}
|
|
154
232
|
}
|
|
155
233
|
}
|
|
156
234
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/build/services/workerBus.ts"],"sourcesContent":["// Runs inside the service's Web Worker, bundled by Vite from the generated\n// `worker.js`. Keep it free of Node and of runtime imports: `@sanity/sdk` is\n// only ever imported for types.\nimport {type MessageBusEmitResult, type MessageBusErrorCode} from '@sanity/sdk/dashboard'\n\nimport {type ServiceBus} from '../../../defineService.js'\n\nconst DEFAULT_TIMEOUT_MS = 5000\n\ninterface RequestOptions {\n signal?: AbortSignal\n timeout?: number | null\n}\n\ntype Outcome = {error: Error; ok: false} | {ok: true; value: unknown}\n\ntype HostMessage =\n | {\n error: {code: MessageBusErrorCode; message: string}\n id: number\n kind: 'workbench.bus.reply'\n ok: false\n }\n | {id: number; kind: 'workbench.bus.reply'; ok: true; value: unknown}\n | {id: number; kind: 'workbench.bus.value'; value: unknown}\n\n// Mirrors the SDK's MessageBusError: importing the class would pull the SDK\n// runtime into the worker bundle.\nconst busError = (code: MessageBusErrorCode, message?: string): Error =>\n Object.assign(new Error(message || code), {code, name: 'MessageBusError'})\n\n/**\n * The worker's side of the `workbench.bus.*` wire contract. The host relays\n * each request to the Dashboard bus and stamps it with the worker's identity,\n * so the client only tracks ids.\n * @internal\n */\nexport function createWorkerBus(): {\n /**\n * The service author's API. The host owns the connection, opening it and ending it when\n * it terminates the worker, so the worker cannot end it.\n */\n bus: ServiceBus\n /**\n * The generated entry's terminate hook, not the author's. It sends nothing to\n * the host, which has already disconnected; it only marks the client closed so\n * the disposer's bus calls reject `ABORTED` at once instead of waiting out the\n * local timeout. Hence not `disconnect`.\n */\n close: () => void\n /**\n * The generated `worker.js` is the single `message` listener on `self` and\n * routes every kind (terminate to the disposer, `workbench.bus.*` here), the\n * way the host's `runWorker` routes to its relay.\n */\n receive: (data: unknown) => void\n} {\n const pending = new Map<number, (outcome: Outcome) => void>()\n const subscriptions = new Map<number, (value: unknown) => void>()\n let nextId = 0\n let closed = false\n\n // Posts a request and returns a function that creates its promise on first\n // call. Until then a reply, even an error, is only held: a rejected promise\n // nobody awaits would reach the worker's 'unhandledrejection' forwarder as a crash.\n function request(message: Record<string, unknown>, options: RequestOptions = {}) {\n const {signal, timeout} = options\n const id = ++nextId\n let outcome: Outcome | undefined\n let onOutcome: ((result: Outcome) => void) | undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const settle = (result: Outcome) => {\n if (outcome) return\n outcome = result\n clearTimeout(timer)\n pending.delete(id)\n signal?.removeEventListener('abort', onAbort)\n onOutcome?.(result)\n }\n const onAbort = () => {\n self.postMessage({id, kind: 'workbench.bus.abort'})\n settle({error: busError('ABORTED'), ok: false})\n }\n\n if (closed || signal?.aborted) {\n outcome = {error: busError('ABORTED'), ok: false}\n } else {\n // An omitted timeout must stay absent on the wire, so the host applies its default.\n self.postMessage(timeout === undefined ? {...message, id} : {...message, id, timeout})\n pending.set(id, settle)\n // A host that predates the bus never replies; time out here too so the call still settles.\n if (timeout !== null) {\n timer = setTimeout(\n () => settle({error: busError('TIMEOUT'), ok: false}),\n timeout ?? DEFAULT_TIMEOUT_MS,\n )\n }\n signal?.addEventListener('abort', onAbort, {once: true})\n }\n\n let promise: Promise<unknown> | undefined\n return () =>\n (promise ??= new Promise((resolve, reject) => {\n onOutcome = (result) => (result.ok ? resolve(result.value) : reject(result.error))\n if (outcome) onOutcome(outcome)\n }))\n }\n\n const bus = {\n emit: (topic: string, payload?: unknown, options?: RequestOptions) => {\n const awaitReply = request({kind: 'workbench.bus.emit', payload, topic}, options)\n const result: MessageBusEmitResult<unknown> = {\n catch: (onRejected) => awaitReply().then(undefined, onRejected),\n finally: (onFinally) => awaitReply().finally(onFinally),\n // eslint-disable-next-line unicorn/no-thenable -- awaiting arms reply failure handling; fire-and-forget does not.\n then: (onFulfilled, onRejected) => awaitReply().then(onFulfilled, onRejected),\n }\n return result\n },\n query: (topic: string, options?: RequestOptions) =>\n request({kind: 'workbench.bus.query', topic}, options)(),\n subscribe: (topic: string, handler: (value: unknown) => void, options?: RequestOptions) => {\n if (closed) throw busError('ABORTED')\n const signal = options?.signal\n if (signal?.aborted) return\n const id = ++nextId\n self.postMessage({id, kind: 'workbench.bus.subscribe', topic})\n subscriptions.set(id, handler)\n signal?.addEventListener(\n 'abort',\n () => {\n if (subscriptions.delete(id)) self.postMessage({id, kind: 'workbench.bus.abort'})\n },\n {once: true},\n )\n },\n }\n\n return {\n // The topic generics only exist at the call site; the wire carries plain strings.\n bus: bus as unknown as ServiceBus,\n close: () => {\n closed = true\n subscriptions.clear()\n for (const settle of pending.values()) settle({error: busError('ABORTED'), ok: false})\n },\n receive: (data) => {\n const message = data as HostMessage\n if (message.kind === 'workbench.bus.value') {\n subscriptions.get(message.id)?.(message.value)\n } else if (message.kind === 'workbench.bus.reply') {\n const settle = pending.get(message.id)\n if (message.ok) {\n settle?.({ok: true, value: message.value})\n return\n }\n // A refused subscription has no promise to reject, so tell the author through the host logger.\n if (subscriptions.delete(message.id)) {\n // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger\n console.error(\n `Message bus subscription refused: ${message.error.code}: ${message.error.message}`,\n )\n }\n settle?.({error: busError(message.error.code, message.error.message), ok: false})\n }\n },\n }\n}\n"],"names":["DEFAULT_TIMEOUT_MS","busError","code","message","Object","assign","Error","name","createWorkerBus","pending","Map","subscriptions","nextId","closed","request","options","signal","timeout","id","outcome","onOutcome","timer","settle","result","clearTimeout","delete","removeEventListener","onAbort","self","postMessage","kind","error","ok","aborted","undefined","set","setTimeout","addEventListener","once","promise","Promise","resolve","reject","value","bus","emit","topic","payload","awaitReply","catch","onRejected","then","finally","onFinally","onFulfilled","query","subscribe","handler","close","clear","values","receive","data","get","console"],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,gCAAgC;AAKhC,MAAMA,qBAAqB;AAmB3B,4EAA4E;AAC5E,kCAAkC;AAClC,MAAMC,WAAW,CAACC,MAA2BC,UAC3CC,OAAOC,MAAM,CAAC,IAAIC,MAAMH,WAAWD,OAAO;QAACA;QAAMK,MAAM;IAAiB;AAE1E;;;;;CAKC,GACD,OAAO,SAASC;IAoBd,MAAMC,UAAU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C,KAAK;YAC/C,OAAO,IAAIxC,QAAQ2B,IAAI,KAAK,uBAAuB;gBACjD,MAAMR,SAASb,QAAQsD,GAAG,CAAC5D,QAAQe,EAAE;gBACrC,IAAIf,QAAQ6B,EAAE,EAAE;oBACdV,SAAS;wBAACU,IAAI;wBAAMW,OAAOxC,QAAQwC,KAAK;oBAAA;oBACxC;gBACF;gBACA,+FAA+F;gBAC/F,IAAIhC,cAAcc,MAAM,CAACtB,QAAQe,EAAE,GAAG;oBACpC,4FAA4F;oBAC5F8C,QAAQjC,KAAK,CACX,CAAC,kCAAkC,EAAE5B,QAAQ4B,KAAK,CAAC7B,IAAI,CAAC,EAAE,EAAEC,QAAQ4B,KAAK,CAAC5B,OAAO,EAAE;gBAEvF;gBACAmB,SAAS;oBAACS,OAAO9B,SAASE,QAAQ4B,KAAK,CAAC7B,IAAI,EAAEC,QAAQ4B,KAAK,CAAC5B,OAAO;oBAAG6B,IAAI;gBAAK;YACjF;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/build/services/workerBus.ts"],"sourcesContent":["// Runs inside the service's Web Worker, bundled by Vite from the generated\n// `worker.js`. Keep it free of Node and of runtime imports: `@sanity/sdk` is\n// only ever imported for types.\nimport {\n type MessageBusEmitResult,\n type MessageBusErrorCode,\n type MessageBusMessage,\n type MessageBusMeta,\n} from '@sanity/sdk/dashboard'\n\nimport {type ServiceBus} from '../../../defineService.js'\n\nconst DEFAULT_TIMEOUT_MS = 5000\n\ninterface RequestOptions {\n signal?: AbortSignal\n timeout?: number | null\n}\n\ntype Outcome = {error: Error; ok: false} | {ok: true; value: unknown}\n\ntype Answer =\n | {error: {code: 'HANDLER_THREW' | 'REFUSED'; message: string}; ok: false}\n | {ok: true; value: unknown}\n\ntype HostMessage =\n | {\n error: {code: MessageBusErrorCode; message: string}\n id: number\n kind: 'workbench.bus.reply'\n ok: false\n }\n | {id: number; kind: 'workbench.bus.reply'; ok: true; value: unknown}\n | {id: number; kind: 'workbench.bus.value'; value: unknown}\n | {\n id: number\n kind: 'workbench.bus.message'\n messageId: number\n meta: MessageBusMeta\n payload: unknown\n type: string\n }\n | {kind: 'workbench.bus.cancel'; messageId: number}\n\n// Mirrors the SDK's MessageBusError: importing the class would pull the SDK\n// runtime into the worker bundle.\nconst busError = (code: MessageBusErrorCode, message?: string): Error =>\n Object.assign(new Error(message || code), {code, name: 'MessageBusError'})\n\n/**\n * The worker's side of the `workbench.bus.*` wire contract. The host relays\n * each request to the Dashboard bus and stamps it with the worker's identity,\n * so the client only tracks ids.\n * @internal\n */\nexport function createWorkerBus(): {\n /**\n * The service author's API. The host owns the connection, opening it and ending it when\n * it terminates the worker, so the worker cannot end it.\n */\n bus: ServiceBus\n /**\n * The generated entry's terminate hook, not the author's. It sends nothing to\n * the host, which has already disconnected; it only marks the client closed so\n * the disposer's bus calls reject `ABORTED` at once instead of waiting out the\n * local timeout. Hence not `disconnect`.\n */\n close: () => void\n /**\n * The generated `worker.js` is the single `message` listener on `self` and\n * routes every kind (terminate to the disposer, `workbench.bus.*` here), the\n * way the host's `runWorker` routes to its relay.\n */\n receive: (data: unknown) => void\n} {\n const pending = new Map<number, (outcome: Outcome) => void>()\n // The worker can't tell a state topic from an event topic, so it stores every\n // handler alike; the host's `value` or `message` decides how it is called.\n const subscriptions = new Map<number, (value: unknown) => unknown>()\n const inFlight = new Map<number, AbortController>()\n let nextId = 0\n let closed = false\n\n // Posts a request and returns a function that creates its promise on first\n // call. Until then a reply, even an error, is only held: a rejected promise\n // nobody awaits would reach the worker's 'unhandledrejection' forwarder as a crash.\n function request(message: Record<string, unknown>, options: RequestOptions = {}) {\n const {signal, timeout} = options\n const id = ++nextId\n let outcome: Outcome | undefined\n let onOutcome: ((result: Outcome) => void) | undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const settle = (result: Outcome) => {\n if (outcome) return\n outcome = result\n clearTimeout(timer)\n pending.delete(id)\n signal?.removeEventListener('abort', onAbort)\n onOutcome?.(result)\n }\n const onAbort = () => {\n self.postMessage({id, kind: 'workbench.bus.abort'})\n settle({error: busError('ABORTED'), ok: false})\n }\n\n if (closed || signal?.aborted) {\n outcome = {error: busError('ABORTED'), ok: false}\n } else {\n // An omitted timeout must stay absent on the wire, so the host applies its default.\n self.postMessage(timeout === undefined ? {...message, id} : {...message, id, timeout})\n pending.set(id, settle)\n // A host that predates the bus never replies; time out here too so the call still settles.\n if (timeout !== null) {\n timer = setTimeout(\n () => settle({error: busError('TIMEOUT'), ok: false}),\n timeout ?? DEFAULT_TIMEOUT_MS,\n )\n }\n signal?.addEventListener('abort', onAbort, {once: true})\n }\n\n let promise: Promise<unknown> | undefined\n return () =>\n (promise ??= new Promise((resolve, reject) => {\n onOutcome = (result) => (result.ok ? resolve(result.value) : reject(result.error))\n if (outcome) onOutcome(outcome)\n }))\n }\n\n // Matches the SDK's `invokeResponder`, so a responder behaves the same in a\n // worker as on the page.\n function respond(\n handler: (message: MessageBusMessage<unknown, unknown, string>) => unknown,\n {messageId, meta, payload, type}: Extract<HostMessage, {kind: 'workbench.bus.message'}>,\n ) {\n const controller = new AbortController()\n inFlight.set(messageId, controller)\n const answer = (result: Answer) => {\n if (inFlight.get(messageId) !== controller) return false\n inFlight.delete(messageId)\n self.postMessage({...result, kind: 'workbench.bus.answer', messageId})\n return true\n }\n const warnIfIgnored = (answered: boolean, action: string) => {\n if (answered) return\n // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger\n console.warn(\n `Message bus ${action} ignored for \"${type}\": no waiting caller or already replied`,\n )\n }\n const fail = () => answer({error: {code: 'HANDLER_THREW', message: 'HANDLER_THREW'}, ok: false})\n\n try {\n const result = handler({\n meta,\n payload,\n reject: (reason) =>\n warnIfIgnored(\n answer({error: {code: 'REFUSED', message: reason ?? 'REFUSED'}, ok: false}),\n 'reject',\n ),\n reply: (value) => warnIfIgnored(answer({ok: true, value}), 'reply'),\n signal: controller.signal,\n type,\n })\n if (result instanceof Promise) result.catch(fail)\n } catch {\n fail()\n }\n }\n\n const bus = {\n emit: (topic: string, payload?: unknown, options?: RequestOptions) => {\n const awaitReply = request({kind: 'workbench.bus.emit', payload, topic}, options)\n const result: MessageBusEmitResult<unknown> = {\n catch: (onRejected) => awaitReply().then(undefined, onRejected),\n finally: (onFinally) => awaitReply().finally(onFinally),\n // eslint-disable-next-line unicorn/no-thenable -- awaiting arms reply failure handling; fire-and-forget does not.\n then: (onFulfilled, onRejected) => awaitReply().then(onFulfilled, onRejected),\n }\n return result\n },\n query: (topic: string, options?: RequestOptions) =>\n request({kind: 'workbench.bus.query', topic}, options)(),\n subscribe: (topic: string, handler: (value: unknown) => unknown, options?: RequestOptions) => {\n if (closed) throw busError('ABORTED')\n const signal = options?.signal\n if (signal?.aborted) return\n const id = ++nextId\n self.postMessage({id, kind: 'workbench.bus.subscribe', topic})\n subscriptions.set(id, handler)\n signal?.addEventListener(\n 'abort',\n () => {\n if (subscriptions.delete(id)) self.postMessage({id, kind: 'workbench.bus.abort'})\n },\n {once: true},\n )\n },\n }\n\n return {\n // The topic generics only exist at the call site; the wire carries plain strings.\n bus: bus as unknown as ServiceBus,\n close: () => {\n closed = true\n subscriptions.clear()\n const controllers = [...inFlight.values()]\n inFlight.clear()\n for (const controller of controllers) controller.abort()\n for (const settle of pending.values()) settle({error: busError('ABORTED'), ok: false})\n },\n receive: (data) => {\n const message = data as HostMessage\n switch (message.kind) {\n case 'workbench.bus.cancel': {\n const controller = inFlight.get(message.messageId)\n // Forget it first so an abort listener's reply is ignored.\n inFlight.delete(message.messageId)\n controller?.abort()\n return\n }\n case 'workbench.bus.message': {\n const handler = subscriptions.get(message.id)\n if (handler) respond(handler, message)\n return\n }\n case 'workbench.bus.reply': {\n const settle = pending.get(message.id)\n if (message.ok) {\n settle?.({ok: true, value: message.value})\n return\n }\n // A refused subscription has no promise to reject, so tell the author through the host logger.\n if (subscriptions.delete(message.id)) {\n // eslint-disable-next-line no-console -- the worker's console is bridged to the host logger\n console.error(\n `Message bus subscription refused: ${message.error.code}: ${message.error.message}`,\n )\n }\n settle?.({error: busError(message.error.code, message.error.message), ok: false})\n return\n }\n case 'workbench.bus.value': {\n subscriptions.get(message.id)?.(message.value)\n }\n }\n },\n }\n}\n"],"names":["DEFAULT_TIMEOUT_MS","busError","code","message","Object","assign","Error","name","createWorkerBus","pending","Map","subscriptions","inFlight","nextId","closed","request","options","signal","timeout","id","outcome","onOutcome","timer","settle","result","clearTimeout","delete","removeEventListener","onAbort","self","postMessage","kind","error","ok","aborted","undefined","set","setTimeout","addEventListener","once","promise","Promise","resolve","reject","value","respond","handler","messageId","meta","payload","type","controller","AbortController","answer","get","warnIfIgnored","answered","action","console","warn","fail","reason","reply","catch","bus","emit","topic","awaitReply","onRejected","then","finally","onFinally","onFulfilled","query","subscribe","close","clear","controllers","values","abort","receive","data"],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,gCAAgC;AAUhC,MAAMA,qBAAqB;AAgC3B,4EAA4E;AAC5E,kCAAkC;AAClC,MAAMC,WAAW,CAACC,MAA2BC,UAC3CC,OAAOC,MAAM,CAAC,IAAIC,MAAMH,WAAWD,OAAO;QAACA;QAAMK,MAAM;IAAiB;AAE1E;;;;;CAKC,GACD,OAAO,SAASC;IAoBd,MAAMC,UAAU,IAAIC;IACpB,8EAA8E;IAC9E,2EAA2E;IAC3E,MAAMC,gBAAgB,IAAID;IAC1B,MAAME,WAAW,IAAIF;IACrB,IAAIG,SAAS;IACb,IAAIC,SAAS;IAEb,2EAA2E;IAC3E,4EAA4E;IAC5E,oFAAoF;IACpF,SAASC,QAAQZ,OAAgC,EAAEa,UAA0B,CAAC,CAAC;QAC7E,MAAM,EAACC,MAAM,EAAEC,OAAO,EAAC,GAAGF;QAC1B,MAAMG,KAAK,EAAEN;QACb,IAAIO;QACJ,IAAIC;QACJ,IAAIC;QAEJ,MAAMC,SAAS,CAACC;YACd,IAAIJ,SAAS;YACbA,UAAUI;YACVC,aAAaH;YACbb,QAAQiB,MAAM,CAACP;YACfF,QAA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,IAAIjC,cAAce,MAAM,CAACvB,QAAQgB,EAAE,GAAG;4BACpC,4FAA4F;4BAC5FuC,QAAQ1B,KAAK,CACX,CAAC,kCAAkC,EAAE7B,QAAQ6B,KAAK,CAAC9B,IAAI,CAAC,EAAE,EAAEC,QAAQ6B,KAAK,CAAC7B,OAAO,EAAE;wBAEvF;wBACAoB,SAAS;4BAACS,OAAO/B,SAASE,QAAQ6B,KAAK,CAAC9B,IAAI,EAAEC,QAAQ6B,KAAK,CAAC7B,OAAO;4BAAG8B,IAAI;wBAAK;wBAC/E;oBACF;gBACA,KAAK;oBAAuB;wBAC1BtB,cAAc2C,GAAG,CAACnD,QAAQgB,EAAE,IAAIhB,QAAQyC,KAAK;oBAC/C;YACF;QACF;IACF;AACF"}
|
package/dist/defineService.js
CHANGED
|
@@ -6,9 +6,30 @@ import { SERVICE_CONTRACT_VERSION } from './contract.js';
|
|
|
6
6
|
* The callback receives `bus`, its connection to the Dashboard message bus:
|
|
7
7
|
* `bus.emit` sends an event (such as a dock-badge update), `bus.query` reads the
|
|
8
8
|
* current value of a state topic, and `bus.subscribe` runs a handler on each
|
|
9
|
-
* new value of a state topic
|
|
10
|
-
* or timed-out
|
|
11
|
-
* `code` says why; it is not an
|
|
9
|
+
* new value of a state topic, or on each event of an event topic, until its
|
|
10
|
+
* `signal` aborts. A refused, unanswered or timed-out `emit` or `query` rejects
|
|
11
|
+
* with an `Error` named `MessageBusError` whose `code` says why; it is not an
|
|
12
|
+
* instance of the SDK's `MessageBusError` class.
|
|
13
|
+
*
|
|
14
|
+
* An event handler answers the sender with `message.reply(value)` or refuses
|
|
15
|
+
* with `message.reject(reason)`; one that throws refuses with code
|
|
16
|
+
* `HANDLER_THREW`. For example, a service that keeps a snapshot for its app's
|
|
17
|
+
* views, which listen with `useWorker` first and then post to it. A view's post
|
|
18
|
+
* arrives on `workers.post` as `{name, payload}`, and `workers.message` reaches
|
|
19
|
+
* only this app's views:
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* export default unstable_defineService('worker', ({bus}) => {
|
|
23
|
+
* const controller = new AbortController()
|
|
24
|
+
* bus.subscribe('workers.post', (message) => message.reply(snapshot), {
|
|
25
|
+
* signal: controller.signal,
|
|
26
|
+
* })
|
|
27
|
+
* // Views that are already listening post again.
|
|
28
|
+
* bus.emit('workers.message', {type: 'welcome'})
|
|
29
|
+
* return () => controller.abort()
|
|
30
|
+
* })
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
12
33
|
* The callback can return a disposer, which runs when Dashboard stops the
|
|
13
34
|
* worker. By then the bus is closed: subscriptions have ended, `emit` and
|
|
14
35
|
* `query` reject with code `ABORTED`, and `subscribe` throws that error.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/defineService.ts"],"sourcesContent":["import {\n type MessageBus,\n type MessageBusAbortOptions,\n type StateTopic,\n type ValueOf,\n} from '@sanity/sdk/dashboard'\n\nimport {SERVICE_CONTRACT_VERSION, type ServiceType} from './contract.js'\n\n/**\n * The service's own declaration, surfaced to the callback.\n * @public\n */\nexport interface ServiceInfo {\n readonly name: string\n readonly type: string\n}\n\n/**\n * The message bus as a service sees it:
|
|
1
|
+
{"version":3,"sources":["../src/defineService.ts"],"sourcesContent":["import {\n type EventTopic,\n type MessageBus,\n type MessageBusAbortOptions,\n type MessageBusMessage,\n type PayloadOf,\n type ReplyOf,\n type StateTopic,\n type ValueOf,\n} from '@sanity/sdk/dashboard'\n\nimport {SERVICE_CONTRACT_VERSION, type ServiceType} from './contract.js'\n\n/**\n * The service's own declaration, surfaced to the callback.\n * @public\n */\nexport interface ServiceInfo {\n readonly name: string\n readonly type: string\n}\n\n/**\n * The message bus as a service sees it: the SDK's `MessageBus` without the\n * `subscribe` forms that return observables, which would make the service's\n * project install rxjs. There is no `disconnect`: Dashboard owns the connection\n * and ends it when it stops the worker.\n * @public\n */\nexport interface ServiceBus extends Omit<MessageBus, 'subscribe'> {\n /** Runs a responder for each event until its signal aborts. */\n subscribe<K extends EventTopic>(\n type: K,\n handler: (message: MessageBusMessage<PayloadOf<K>, ReplyOf<K>, K>) => void,\n options?: MessageBusAbortOptions,\n ): void\n /** Runs a handler for each state value until its signal aborts. */\n subscribe<K extends StateTopic>(\n type: K,\n handler: (value: ValueOf<K>) => void,\n options?: MessageBusAbortOptions,\n ): void\n}\n\n/**\n * Context every service callback receives when its worker starts. Mirrors how a\n * view component receives its `view` — the service receives its own `service`.\n * @public\n */\nexport interface ServiceContext {\n readonly bus: ServiceBus\n readonly service: ServiceInfo\n}\n\n/**\n * A service callback. Runs once inside the worker on start; returns an optional\n * disposer the host calls before terminating the worker.\n * @public\n */\nexport type ServiceCallback = (context: ServiceContext) => (() => void) | void\n\n/** The callback shape each service type defines, keyed by type. */\ninterface ServiceCallbacksByType {\n worker: ServiceCallback\n}\n\n/**\n * The result of `unstable_defineService`: the author's callback, the service\n * type, and the internal contract version the worker artifact targets.\n * @public\n */\nexport interface DefinedService<TType extends ServiceType = ServiceType> {\n readonly run: ServiceCallbacksByType[TType]\n readonly type: TType\n /** @internal */\n readonly version: typeof SERVICE_CONTRACT_VERSION\n}\n\n/**\n * Define a Sanity Dashboard background service. The first argument narrows the\n * callback shape — `\"worker\"` runs the callback inside a Web Worker.\n *\n * The callback receives `bus`, its connection to the Dashboard message bus:\n * `bus.emit` sends an event (such as a dock-badge update), `bus.query` reads the\n * current value of a state topic, and `bus.subscribe` runs a handler on each\n * new value of a state topic, or on each event of an event topic, until its\n * `signal` aborts. A refused, unanswered or timed-out `emit` or `query` rejects\n * with an `Error` named `MessageBusError` whose `code` says why; it is not an\n * instance of the SDK's `MessageBusError` class.\n *\n * An event handler answers the sender with `message.reply(value)` or refuses\n * with `message.reject(reason)`; one that throws refuses with code\n * `HANDLER_THREW`. For example, a service that keeps a snapshot for its app's\n * views, which listen with `useWorker` first and then post to it. A view's post\n * arrives on `workers.post` as `{name, payload}`, and `workers.message` reaches\n * only this app's views:\n *\n * ```ts\n * export default unstable_defineService('worker', ({bus}) => {\n * const controller = new AbortController()\n * bus.subscribe('workers.post', (message) => message.reply(snapshot), {\n * signal: controller.signal,\n * })\n * // Views that are already listening post again.\n * bus.emit('workers.message', {type: 'welcome'})\n * return () => controller.abort()\n * })\n * ```\n *\n * The callback can return a disposer, which runs when Dashboard stops the\n * worker. By then the bus is closed: subscriptions have ended, `emit` and\n * `query` reject with code `ABORTED`, and `subscribe` throws that error.\n *\n * Identity at runtime: returns the callback tagged with its type and the contract\n * version, for the CLI build to generate a worker artifact from. Used as the\n * default export of a service's `src` file.\n * @public\n */\nexport function unstable_defineService<TType extends ServiceType>(\n type: TType,\n run: ServiceCallbacksByType[TType],\n): DefinedService<TType> {\n return {run, type, version: SERVICE_CONTRACT_VERSION}\n}\n"],"names":["SERVICE_CONTRACT_VERSION","unstable_defineService","type","run","version"],"mappings":"AAWA,SAAQA,wBAAwB,QAAyB,gBAAe;AAmExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GACD,OAAO,SAASC,uBACdC,IAAW,EACXC,GAAkC;IAElC,OAAO;QAACA;QAAKD;QAAME,SAASJ;IAAwB;AACtD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/workbench-cli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.11.0",
|
|
4
4
|
"description": "Internal implementation detail of the Sanity CLI's unstable workbench support. Not intended for direct use.",
|
|
5
5
|
"homepage": "https://github.com/sanity-io/cli",
|
|
6
6
|
"bugs": "https://github.com/sanity-io/cli/issues",
|