dsh-open-in-dsh 0.2.0 → 0.3.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/lib/client.js CHANGED
@@ -4,7 +4,8 @@ window.__ModuleLoader__.load({
4
4
  var module = { exports: {} };
5
5
  var exports = module.exports;
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
- // ---- client/index.js ----
7
+ // ---- client/index.ts (compiled to .client-build/index.js) ----
8
+ "use strict";
8
9
  /**
9
10
  * `dsh-open-in-dsh` browser half.
10
11
  *
@@ -29,37 +30,32 @@ window.__ModuleLoader__.load({
29
30
  *
30
31
  * @module dsh-open-in-dsh/client
31
32
  */
32
-
33
33
  /**
34
34
  * Parse one SSE `data:` payload.
35
35
  * @param text - raw frame data.
36
36
  * @returns the parsed object, or null when the frame is not readable JSON.
37
37
  */
38
38
  function parseFrame(text) {
39
- try {
40
- const value = JSON.parse(text)
41
- return value !== null && typeof value === 'object' ? value : null
42
- } catch {
43
- return null
44
- }
39
+ try {
40
+ const value = JSON.parse(text);
41
+ return value !== null && typeof value === 'object' ? value : null;
42
+ }
43
+ catch {
44
+ return null;
45
+ }
45
46
  }
46
-
47
47
  /** Dictionary namespace owned by this plugin. */
48
- const NS = 'dsh-open-in-dsh'
49
-
48
+ const NS = 'dsh-open-in-dsh';
50
49
  /**
51
- * Menu labels. scripts/build-client.mjs replaces the marker below with the
50
+ * Menu labels. scripts/build-client.mts replaces the marker below with the
52
51
  * "menu" objects from locale/zh.json and locale/en.json, so the shipped bundle
53
52
  * and the package's locale files cannot drift.
54
53
  */
55
- const MENU_DICTIONARIES = /* @menu-dictionaries */ {"zh":{"menu.qspace":"用 QSpace Pro 打开","menu.finder":"在 Finder 中显示","menu.vscode":"用 VS Code 打开","menu.warp":"用 Warp 打开","menu.terminal":"在终端中打开","menu.explorer":"在资源管理器中显示","menu.qspaceDocument":"用 QSpace 打开所在目录","menu.qspaceSession":"在 QSpace 中显示","menu.sessionNoCwd":"会话没有工作目录","menu.failed":"无法打开,请重试"},"en":{"menu.qspace":"Open in QSpace Pro","menu.finder":"Show in Finder","menu.vscode":"Open in VS Code","menu.warp":"Open in Warp","menu.terminal":"Open in Terminal","menu.explorer":"Show in Explorer","menu.qspaceDocument":"Open folder in QSpace","menu.qspaceSession":"Show in QSpace","menu.sessionNoCwd":"No workspace folder","menu.failed":"Could not open. Try again."}}
56
-
54
+ const MENU_DICTIONARIES = /* @menu-dictionaries */ {"zh":{"menu.qspace":"用 QSpace Pro 打开","menu.finder":"在 Finder 中显示","menu.vscode":"用 VS Code 打开","menu.warp":"用 Warp 打开","menu.terminal":"在终端中打开","menu.explorer":"在资源管理器中显示","menu.qspaceDocument":"用 QSpace 打开所在目录","menu.qspaceSession":"在 QSpace 中显示","menu.sessionNoCwd":"会话没有工作目录","menu.failed":"无法打开,请重试"},"en":{"menu.qspace":"Open in QSpace Pro","menu.finder":"Show in Finder","menu.vscode":"Open in VS Code","menu.warp":"Open in Warp","menu.terminal":"Open in Terminal","menu.explorer":"Show in Explorer","menu.qspaceDocument":"Open folder in QSpace","menu.qspaceSession":"Show in QSpace","menu.sessionNoCwd":"No workspace folder","menu.failed":"Could not open. Try again."}};
57
55
  /** The Host's open-with route; carried by hand in lib/index.js. */
58
- const ROUTE_OPEN_WITH = '/dsh-open-in-dsh/api/v1/open-with'
59
-
56
+ const ROUTE_OPEN_WITH = '/dsh-open-in-dsh/api/v1/open-with';
60
57
  /** The Host's availability route; carried by hand in lib/index.js. */
61
- const ROUTE_APPS = '/dsh-open-in-dsh/api/v1/apps'
62
-
58
+ const ROUTE_APPS = '/dsh-open-in-dsh/api/v1/apps';
63
59
  /**
64
60
  * The Host's Session route; carried by hand in lib/index.js.
65
61
  *
@@ -67,25 +63,24 @@ window.__ModuleLoader__.load({
67
63
  * id. This route is where the Host turns that id into a directory, so the
68
64
  * browser half never guesses a cwd and never sends one.
69
65
  */
70
- const ROUTE_OPEN_SESSION = '/dsh-open-in-dsh/api/v1/open-session'
71
-
66
+ const ROUTE_OPEN_SESSION = '/dsh-open-in-dsh/api/v1/open-session';
72
67
  /**
73
68
  * Menu order. The Host reports the subset this platform can launch; this list
74
69
  * decides how the actions stack when it reports several.
75
70
  */
76
- const MENU_APP_ORDER = ['qspace', 'finder', 'vscode', 'warp', 'terminal', 'explorer']
77
-
71
+ const MENU_APP_ORDER = ['qspace', 'finder', 'vscode', 'warp', 'terminal', 'explorer'];
78
72
  /**
79
73
  * Whether a path is absolute in either spelling the Host accepts.
80
74
  * @param value - the path to classify.
81
75
  * @returns true for a POSIX, drive-letter or UNC absolute path.
82
76
  */
83
77
  function isAbsolutePath(value) {
84
- if (value.startsWith('/')) return true
85
- if (value.length >= 3 && value[1] === ':' && (value[2] === '/' || value[2] === '\\')) return true
86
- return value.startsWith('\\\\')
78
+ if (value.startsWith('/'))
79
+ return true;
80
+ if (value.length >= 3 && value[1] === ':' && (value[2] === '/' || value[2] === '\\'))
81
+ return true;
82
+ return value.startsWith('\\\\');
87
83
  }
88
-
89
84
  /**
90
85
  * Resolve a Workspace-relative path against the Session directory.
91
86
  * @param cwd - the Session's workspace root, when known.
@@ -93,12 +88,13 @@ window.__ModuleLoader__.load({
93
88
  * @returns an absolute path, or null when a relative path has no root.
94
89
  */
95
90
  function resolveWorkspacePath(cwd, path) {
96
- if (isAbsolutePath(path)) return path
97
- if (typeof cwd !== 'string' || cwd === '') return null
98
- const separator = cwd.includes('\\') ? '\\' : '/'
99
- return cwd.replace(/[/\\]+$/, '') + separator + path.replace(/^(?:\.?[/\\])+/, '')
91
+ if (isAbsolutePath(path))
92
+ return path;
93
+ if (typeof cwd !== 'string' || cwd === '')
94
+ return null;
95
+ const separator = cwd.includes('\\') ? '\\' : '/';
96
+ return cwd.replace(/[/\\]+$/, '') + separator + path.replace(/^(?:\.?[/\\])+/, '');
100
97
  }
101
-
102
98
  /**
103
99
  * The directory that contains a file, in either path spelling.
104
100
  *
@@ -110,19 +106,23 @@ window.__ModuleLoader__.load({
110
106
  * @returns the containing directory, or null when there is none to name.
111
107
  */
112
108
  function parentDirectory(path) {
113
- if (typeof path !== 'string') return null
114
- const text = path.trim().replace(/[/\\]+$/, '')
115
- if (text === '') return null
116
- const cut = Math.max(text.lastIndexOf('/'), text.lastIndexOf('\\'))
117
- if (cut < 0) return null
118
- // '/a.md' belongs to '/', not to ''.
119
- if (cut === 0) return text.slice(0, 1)
120
- const head = text.slice(0, cut)
121
- // 'C:\a.md' belongs to 'C:\', not to 'C:'.
122
- if (/^[A-Za-z]:$/.test(head)) return head + '\\'
123
- return head
109
+ if (typeof path !== 'string')
110
+ return null;
111
+ const text = path.trim().replace(/[/\\]+$/, '');
112
+ if (text === '')
113
+ return null;
114
+ const cut = Math.max(text.lastIndexOf('/'), text.lastIndexOf('\\'));
115
+ if (cut < 0)
116
+ return null;
117
+ // '/a.md' belongs to '/', not to ''.
118
+ if (cut === 0)
119
+ return text.slice(0, 1);
120
+ const head = text.slice(0, cut);
121
+ // 'C:\a.md' belongs to 'C:\', not to 'C:'.
122
+ if (/^[A-Za-z]:$/.test(head))
123
+ return head + '\\';
124
+ return head;
124
125
  }
125
-
126
126
  /**
127
127
  * Read one external module the way the Client module table offers it.
128
128
  *
@@ -137,14 +137,14 @@ window.__ModuleLoader__.load({
137
137
  * @returns the module, or null when it is unavailable.
138
138
  */
139
139
  function tryRequire(require, id) {
140
- try {
141
- const value = typeof require === 'function' ? require(id) : null
142
- return value === null || value === undefined ? null : value
143
- } catch {
144
- return null
145
- }
140
+ try {
141
+ const value = typeof require === 'function' ? require(id) : null;
142
+ return value === null || value === undefined ? null : value;
143
+ }
144
+ catch {
145
+ return null;
146
+ }
146
147
  }
147
-
148
148
  /**
149
149
  * Read the injected availability hook. A composition that did not bind it (a
150
150
  * slot rendered outside this plugin's inject face) hides the control instead
@@ -153,33 +153,31 @@ window.__ModuleLoader__.load({
153
153
  * @returns true when QSpace can be launched here.
154
154
  */
155
155
  function readAvailability(props) {
156
- if (typeof props.useQspaceAvailable !== 'function') return false
157
- return props.useQspaceAvailable((value) => value) === true
156
+ if (typeof props.useQspaceAvailable !== 'function')
157
+ return false;
158
+ return props.useQspaceAvailable((value) => value) === true;
158
159
  }
159
-
160
160
  /** The element factory a usable React ships; null when the seed has none. */
161
161
  function elementFactory(React) {
162
- return React !== null && typeof React.createElement === 'function' ? React.createElement : null
162
+ return React !== null && typeof React.createElement === 'function' ? React.createElement : null;
163
163
  }
164
-
165
164
  /** Shared look for the two buttons; DSH theme variables only, no stylesheet. */
166
165
  const QSPACE_BUTTON_STYLE = Object.freeze({
167
- display: 'inline-flex',
168
- alignItems: 'center',
169
- flex: 'none',
170
- height: '22px',
171
- padding: '0 6px',
172
- font: 'inherit',
173
- fontSize: '11px',
174
- lineHeight: '16px',
175
- color: 'var(--dsw-alias-label-secondary)',
176
- background: 'transparent',
177
- border: '0.5px solid var(--dsw-alias-border-l4)',
178
- borderRadius: 'var(--dsw-radius-sm, 4px)',
179
- cursor: 'pointer',
180
- whiteSpace: 'nowrap',
181
- })
182
-
166
+ display: 'inline-flex',
167
+ alignItems: 'center',
168
+ flex: 'none',
169
+ height: '22px',
170
+ padding: '0 6px',
171
+ font: 'inherit',
172
+ fontSize: '11px',
173
+ lineHeight: '16px',
174
+ color: 'var(--dsw-alias-label-secondary)',
175
+ background: 'transparent',
176
+ border: '0.5px solid var(--dsw-alias-border-l4)',
177
+ borderRadius: 'var(--dsw-radius-sm, 4px)',
178
+ cursor: 'pointer',
179
+ whiteSpace: 'nowrap',
180
+ });
183
181
  /**
184
182
  * Page-lifetime "is QSpace installed" answer, bound as a slot hook.
185
183
  *
@@ -191,62 +189,65 @@ window.__ModuleLoader__.load({
191
189
  * @returns an observable source for `inject({ hooks: { qspaceAvailable } })`.
192
190
  */
193
191
  function createAvailability(read) {
194
- let state = null
195
- let loading = null
196
- const listeners = new Set()
197
- const publish = (next) => {
198
- if (next === state) return
199
- state = next
200
- for (const listener of [...listeners]) {
201
- try {
202
- listener()
203
- } catch {
204
- // A throwing subscriber is a renderer problem, not an availability one.
205
- }
206
- }
207
- }
208
- const refresh = () => {
209
- if (state !== null) return loading ?? Promise.resolve()
210
- if (loading === null) {
211
- loading = Promise.resolve()
212
- .then(read)
213
- .then((ids) => {
214
- if (Array.isArray(ids)) publish(ids.includes('qspace'))
215
- })
216
- .catch(() => {})
217
- .finally(() => {
218
- loading = null
219
- })
220
- }
221
- return loading
222
- }
223
- return {
224
- getSnapshot: () => state === true,
225
- subscribe(listener) {
226
- listeners.add(listener)
227
- refresh()
228
- return () => {
229
- listeners.delete(listener)
230
- }
231
- },
232
- refresh,
233
- close() {
234
- listeners.clear()
235
- },
236
- }
192
+ let state = null;
193
+ let loading = null;
194
+ const listeners = new Set();
195
+ const publish = (next) => {
196
+ if (next === state)
197
+ return;
198
+ state = next;
199
+ for (const listener of [...listeners]) {
200
+ try {
201
+ listener();
202
+ }
203
+ catch {
204
+ // A throwing subscriber is a renderer problem, not an availability one.
205
+ }
206
+ }
207
+ };
208
+ const refresh = () => {
209
+ if (state !== null)
210
+ return loading ?? Promise.resolve();
211
+ if (loading === null) {
212
+ loading = Promise.resolve()
213
+ .then(read)
214
+ .then((ids) => {
215
+ if (Array.isArray(ids))
216
+ publish(ids.includes('qspace'));
217
+ })
218
+ .catch(() => { })
219
+ .finally(() => {
220
+ loading = null;
221
+ });
222
+ }
223
+ return loading;
224
+ };
225
+ return {
226
+ getSnapshot: () => state === true,
227
+ subscribe(listener) {
228
+ listeners.add(listener);
229
+ refresh();
230
+ return () => {
231
+ listeners.delete(listener);
232
+ };
233
+ },
234
+ refresh,
235
+ close() {
236
+ listeners.clear();
237
+ },
238
+ };
237
239
  }
238
-
239
240
  /**
240
241
  * Read the Host's availability answer into an ordered id list.
241
242
  * @param payload - the Host response body.
242
243
  * @returns allowlisted ids the Host reported, in menu order.
243
244
  */
244
245
  function appIdsFrom(payload) {
245
- if (payload === null || typeof payload !== 'object' || !Array.isArray(payload.apps)) return []
246
- const reported = payload.apps.filter((id) => typeof id === 'string')
247
- return MENU_APP_ORDER.filter((id) => reported.includes(id))
246
+ if (payload === null || typeof payload !== 'object' || !Array.isArray(payload.apps))
247
+ return [];
248
+ const reported = payload.apps.filter((id) => typeof id === 'string');
249
+ return MENU_APP_ORDER.filter((id) => reported.includes(id));
248
250
  }
249
-
250
251
  /**
251
252
  * Lazy, page-lifetime availability reader.
252
253
  *
@@ -256,43 +257,46 @@ window.__ModuleLoader__.load({
256
257
  * @returns a function resolving the allowlisted ids for this platform.
257
258
  */
258
259
  function createAppsReader() {
259
- let cached = null
260
- let pending = null
261
- return async () => {
262
- if (cached !== null) return cached
263
- if (pending === null) {
264
- pending = (async () => {
265
- try {
266
- const response = await fetch(ROUTE_APPS, { headers: { accept: 'application/json' }, cache: 'no-store' })
267
- if (!response.ok) return []
268
- const ids = appIdsFrom(await response.json())
269
- if (ids.length > 0) cached = ids
270
- return ids
271
- } catch {
272
- return []
273
- } finally {
274
- pending = null
260
+ let cached = null;
261
+ let pending = null;
262
+ return async () => {
263
+ if (cached !== null)
264
+ return cached;
265
+ if (pending === null) {
266
+ pending = (async () => {
267
+ try {
268
+ const response = await fetch(ROUTE_APPS, { headers: { accept: 'application/json' }, cache: 'no-store' });
269
+ if (!response.ok)
270
+ return [];
271
+ const ids = appIdsFrom(await response.json());
272
+ if (ids.length > 0)
273
+ cached = ids;
274
+ return ids;
275
+ }
276
+ catch {
277
+ return [];
278
+ }
279
+ finally {
280
+ pending = null;
281
+ }
282
+ })();
275
283
  }
276
- })()
277
- }
278
- return pending
279
- }
284
+ return pending;
285
+ };
280
286
  }
281
-
282
287
  /**
283
288
  * Build the localized open-with actions for one target.
284
289
  * @param options - resolved app ids, absolute path, translate seat and launcher.
285
290
  * @returns the context-menu action array.
286
291
  */
287
292
  function createMenuActions(options) {
288
- return options.apps.map((app) => ({
289
- id: 'open-with.' + app,
290
- label: options.translate('menu.' + app),
291
- failureLabel: options.translate('menu.failed'),
292
- run: () => options.launch(app, options.absolutePath),
293
- }))
293
+ return options.apps.map((app) => ({
294
+ id: 'open-with.' + app,
295
+ label: options.translate('menu.' + app),
296
+ failureLabel: options.translate('menu.failed'),
297
+ run: () => options.launch(app, options.absolutePath),
298
+ }));
294
299
  }
295
-
296
300
  /**
297
301
  * Build the document-preview action: "open the folder that holds this file in
298
302
  * QSpace".
@@ -307,52 +311,49 @@ window.__ModuleLoader__.load({
307
311
  * @returns the slot component for `sidebar.right.tab.document.actions`.
308
312
  */
309
313
  function createDocumentAction(React, deps) {
310
- const h = elementFactory(React)
311
- /**
312
- * @param props - slot props: `absolutePath`, `useQspaceAvailable`, `t`.
313
- * @returns the action button, or null when there is nothing to open.
314
- */
315
- function QspaceDocumentAction(props) {
316
- if (h === null) return null
317
- const available = readAvailability(props)
318
- const path = typeof props.absolutePath === 'string' ? props.absolutePath : ''
319
- if (available !== true || path === '') return null
320
- const directory = parentDirectory(path)
321
- if (directory === null) return null
322
- const label = props.t('menu.qspaceDocument')
323
- return h(
324
- 'button',
325
- {
326
- type: 'button',
327
- 'data-dsh-open-in-dsh': 'document',
328
- // The title says which folder, because the label has to stay short.
329
- title: directory,
330
- 'aria-label': label,
331
- style: QSPACE_BUTTON_STYLE,
332
- onClick: () => {
333
- Promise.resolve()
334
- .then(() => deps.openWith('qspace', directory))
335
- .catch(() => deps.fail())
336
- },
337
- },
338
- label,
339
- )
340
- }
341
- return QspaceDocumentAction
314
+ const h = elementFactory(React);
315
+ /**
316
+ * @param props - slot props: `absolutePath`, `useQspaceAvailable`, `t`.
317
+ * @returns the action button, or null when there is nothing to open.
318
+ */
319
+ function QspaceDocumentAction(props) {
320
+ if (h === null)
321
+ return null;
322
+ const available = readAvailability(props);
323
+ const path = typeof props.absolutePath === 'string' ? props.absolutePath : '';
324
+ if (available !== true || path === '')
325
+ return null;
326
+ const directory = parentDirectory(path);
327
+ if (directory === null)
328
+ return null;
329
+ const label = props.t('menu.qspaceDocument');
330
+ return h('button', {
331
+ type: 'button',
332
+ 'data-dsh-open-in-dsh': 'document',
333
+ // The title says which folder, because the label has to stay short.
334
+ title: directory,
335
+ 'aria-label': label,
336
+ style: QSPACE_BUTTON_STYLE,
337
+ onClick: () => {
338
+ Promise.resolve()
339
+ .then(() => deps.openWith('qspace', directory))
340
+ .catch(() => deps.fail());
341
+ },
342
+ }, label);
343
+ }
344
+ return QspaceDocumentAction;
342
345
  }
343
-
344
346
  /** Test and troubleshooting surface; not part of the plugin API. */
345
347
  const __internals = {
346
- appIdsFrom,
347
- createMenuActions,
348
- resolveWorkspacePath,
349
- isAbsolutePath,
350
- parentDirectory,
351
- createAvailability,
352
- createDocumentAction,
353
- MENU_APP_ORDER,
354
- }
355
-
348
+ appIdsFrom,
349
+ createMenuActions,
350
+ resolveWorkspacePath,
351
+ isAbsolutePath,
352
+ parentDirectory,
353
+ createAvailability,
354
+ createDocumentAction,
355
+ MENU_APP_ORDER,
356
+ };
356
357
  /**
357
358
  * Build the browser plugin.
358
359
  * @param require - the Client module table's require, for the platform seed
@@ -361,341 +362,316 @@ window.__ModuleLoader__.load({
361
362
  * @returns the Cordis plugin export (`inject` + `apply`).
362
363
  */
363
364
  function createPlugin(require) {
364
- const React = tryRequire(require, 'react')
365
- /** Hand-mirrored in `lib/index.js`; the two halves cannot import each other. */
366
- const EVENTS_PATH = '/dsh-open-in-dsh/api/v1/events'
367
-
368
- /**
369
- * Highest request sequence this window already handled.
370
- *
371
- * Kept in `sessionStorage` so a reload does not re-open the folder the user
372
- * opened a moment ago, and scoped to the window so a second DSH window is
373
- * free to handle the same backlog.
374
- */
375
- const SEQ_KEY = 'dsh-open-in-dsh:seq'
376
-
377
- /**
378
- * Read the stored sequence.
379
- * @returns the stored sequence, or 0.
380
- */
381
- function readSeq() {
382
- try {
383
- const value = Number.parseInt(window.sessionStorage.getItem(SEQ_KEY) ?? '', 10)
384
- return Number.isFinite(value) && value > 0 ? value : 0
385
- } catch {
386
- return 0
387
- }
388
- }
389
-
390
- /**
391
- * Store the sequence.
392
- * @param value - the sequence to remember.
393
- */
394
- function writeSeq(value) {
395
- try {
396
- window.sessionStorage.setItem(SEQ_KEY, String(value))
397
- } catch {
398
- // A browser with storage disabled still works: it just replays on reload.
399
- }
400
- }
401
-
402
- /** Ask the OS for the foreground. Usually ignored without a user gesture. */
403
- function focusWindow() {
404
- try {
405
- window.focus()
406
- } catch {
407
- // Nothing to do; the folder is open either way.
408
- }
409
- }
410
-
411
- /**
412
- * Mount the plugin.
413
- * @param ctx - browser plugin context, with `workspaces` and `sessions`.
414
- */
415
- function apply(ctx) {
416
- const settings = { alwaysNewSession: true }
417
- let lastSeq = readSeq()
418
- let source = null
419
- let uiWorkspace = null
420
-
421
- // Soft dependency: navigation is the last step, and a composition without
422
- // `dsh-client-ui-workspace` should still register the Workspace and Session
423
- // rather than refuse to load. `ctx.get` alone would not be dependable here,
424
- // so the instance is captured through an injection of its own.
425
- ctx.inject(['uiWorkspace'], (scoped) => {
426
- uiWorkspace = scoped.get('uiWorkspace')
427
- })
428
-
429
- // Menu labels come from the package's locale files, inlined into this
430
- // bundle at build time: a right-click never waits on a dictionary fetch.
431
- ctx.effect(() => ctx.locale.register(NS, MENU_DICTIONARIES), 'dsh-open-in-dsh: menu dictionaries')
432
- const t = ctx.locale.bind(NS)
433
-
434
- /** Availability: one probe per page (the Host caches per process life). */
435
- const apps = createAppsReader()
436
-
365
+ const React = tryRequire(require, 'react');
366
+ /** Hand-mirrored in `lib/index.js`; the two halves cannot import each other. */
367
+ const EVENTS_PATH = '/dsh-open-in-dsh/api/v1/events';
437
368
  /**
438
- * Absolute path for a captured file or directory target.
439
- * @param target - the menu target value: { sessionId, path }.
440
- * @returns the absolute path, or null when it cannot be resolved.
441
- */
442
- const absolutePathFor = (target) => {
443
- const path = target !== null && typeof target === 'object' && typeof target.path === 'string' ? target.path : ''
444
- if (path === '') return null
445
- const cwd = ctx.sessions.list.getSnapshot().byId[target.sessionId]?.cwd
446
- return resolveWorkspacePath(cwd, path)
447
- }
448
-
449
- /**
450
- * Ask the Host to launch one allowlisted app on a path.
369
+ * Highest request sequence this window already handled.
451
370
  *
452
- * The Host owns the command: this half can only name an id it received from
453
- * the availability route, and the Host revalidates both the id and the path
454
- * before spawning anything.
455
- *
456
- * @param app - allowlisted app id.
457
- * @param path - absolute, validated path.
458
- * @returns completion; rejects when the Host refuses or cannot launch.
459
- */
460
- const launch = async (app, path) => {
461
- const response = await fetch(ROUTE_OPEN_WITH, {
462
- method: 'POST',
463
- headers: { 'content-type': 'application/json' },
464
- body: JSON.stringify({ path: path, app: app }),
465
- })
466
- let payload = null
467
- try {
468
- payload = await response.json()
469
- } catch {
470
- payload = null
471
- }
472
- if (!response.ok || payload === null || payload.ok !== true) {
473
- const reason = payload !== null && typeof payload.reason === 'string' ? payload.reason : 'http-' + String(response.status)
474
- throw new Error('dsh-open-in-dsh: open-with ' + app + ' failed (' + reason + ')')
475
- }
476
- }
477
-
478
- /**
479
- * Resolve the open-with actions for one captured file or directory.
480
- * @param target - the menu target value: { sessionId, path }.
481
- * @param signal - the provider's cancellation signal.
482
- * @returns the action array; empty when there is nothing to offer.
371
+ * Kept in `sessionStorage` so a reload does not re-open the folder the user
372
+ * opened a moment ago, and scoped to the window so a second DSH window is
373
+ * free to handle the same backlog.
483
374
  */
484
- const resolveActions = async (target, signal) => {
485
- const absolutePath = absolutePathFor(target)
486
- if (absolutePath === null) return []
487
- const ids = await apps()
488
- if (signal?.aborted) return []
489
- return createMenuActions({ apps: ids, absolutePath: absolutePath, translate: t, launch: launch })
490
- }
491
-
492
- ctx.effect(
493
- () => ctx.contextMenus.register({ id: 'open-with.file', target: 'file', order: 200, resolve: resolveActions }),
494
- 'dsh-open-in-dsh: file menu',
495
- )
496
- ctx.effect(
497
- () => ctx.contextMenus.register({ id: 'open-with.directory', target: 'directory', order: 200, resolve: resolveActions }),
498
- 'dsh-open-in-dsh: directory menu',
499
- )
500
-
501
- /** One QSpace availability answer per page, shared by the rendered controls. */
502
- const qspace = createAvailability(apps)
503
- ctx.effect(() => () => qspace.close(), 'dsh-open-in-dsh: qspace availability')
504
-
505
- /** The failure toast; the same string the menu actions use as `failureLabel`. */
506
- const notifyFailure = () => {
507
- try {
508
- ctx.contextMenus.notify(t('menu.failed'))
509
- } catch {
510
- // No menu overlay in this composition; the rejection is already logged.
511
- }
512
- }
513
-
375
+ const SEQ_KEY = 'dsh-open-in-dsh:seq';
514
376
  /**
515
- * Ask the Host to open one Session's working directory.
516
- *
517
- * The session id is all this half sends: the Host owns the id-to-cwd
518
- * resolution so the browser never invents a path for a Session it is not
519
- * currently showing.
520
- *
521
- * @param app - allowlisted app id.
522
- * @param sessionId - the Session to open.
523
- * @returns completion; rejects when the Host has no cwd or cannot launch.
377
+ * Read the stored sequence.
378
+ * @returns the stored sequence, or 0.
524
379
  */
525
- const openSession = async (app, sessionId) => {
526
- const response = await fetch(ROUTE_OPEN_SESSION, {
527
- method: 'POST',
528
- headers: { 'content-type': 'application/json' },
529
- body: JSON.stringify({ sessionId: sessionId, app: app }),
530
- })
531
- let payload = null
532
- try {
533
- payload = await response.json()
534
- } catch {
535
- payload = null
536
- }
537
- if (!response.ok || payload === null || payload.ok !== true) {
538
- const reason = payload !== null && typeof payload.reason === 'string' ? payload.reason : 'http-' + String(response.status)
539
- throw new Error('dsh-open-in-dsh: open-session ' + app + ' failed (' + reason + ')')
540
- }
380
+ function readSeq() {
381
+ try {
382
+ const value = Number.parseInt(window.sessionStorage.getItem(SEQ_KEY) ?? '', 10);
383
+ return Number.isFinite(value) && value > 0 ? value : 0;
384
+ }
385
+ catch {
386
+ return 0;
387
+ }
541
388
  }
542
-
543
389
  /**
544
- * Resolve the Session row menu's contribution.
545
- *
546
- * Nothing is offered when QSpace cannot be launched; a Session the Client
547
- * knows no cwd for still gets a row, disabled with the reason, because a
548
- * disappearing item reads as a broken menu.
549
- *
550
- * @param target - the menu target value: `{sessionId, displayTitle}`.
551
- * @param signal - the provider's cancellation signal.
552
- * @returns the action array; empty when there is nothing to offer.
390
+ * Store the sequence.
391
+ * @param value - the sequence to remember.
553
392
  */
554
- const resolveSessionActions = async (target, signal) => {
555
- const sessionId =
556
- target !== null && typeof target === 'object' && typeof target.sessionId === 'string' ? target.sessionId : ''
557
- if (sessionId === '') return []
558
- const ids = await apps()
559
- if (signal?.aborted) return []
560
- if (!ids.includes('qspace')) return []
561
- const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd
562
- if (typeof cwd !== 'string' || cwd === '') {
563
- return [{ id: 'qspace', label: t('menu.sessionNoCwd'), disabled: true }]
564
- }
565
- return [
566
- {
567
- id: 'qspace',
568
- label: t('menu.qspaceSession'),
569
- failureLabel: t('menu.failed'),
570
- run: () => openSession('qspace', sessionId),
571
- },
572
- ]
573
- }
574
-
575
- ctx.effect(
576
- () =>
577
- ctx.contextMenus.register({
578
- id: 'open-with.session',
579
- target: 'session',
580
- // Below the workspace plugin's own rows, above its footer actions.
581
- order: 510,
582
- // A Session's cwd and the active locale both decide what this row
583
- // says, so a row already on screen must not keep a stale answer.
584
- observe: () => [ctx.sessions.list, ctx.locale],
585
- resolve: resolveSessionActions,
586
- }),
587
- 'dsh-open-in-dsh: session menu',
588
- )
589
-
590
- // The one rendered entry. `slots.inject` waits for the declaration, so a
591
- // composition without the document preview simply never asks for it.
592
- const documentAction = createDocumentAction(React, { openWith: launch, fail: notifyFailure })
593
- ctx.slots.inject('sidebar.right.tab.document.actions', () =>
594
- ctx.slots.register(
595
- {
596
- name: 'sidebar.right.tab.document.actions',
597
- id: 'open-with.qspace',
598
- order: 10,
599
- locale: NS,
600
- inject: () => ({ hooks: { qspaceAvailable: qspace } }),
601
- },
602
- documentAction,
603
- ),
604
- )
605
- /**
606
- * Apply one announced folder.
607
- *
608
- * Order matters: the Workspace must exist on the Host before a Session can
609
- * name it, and `sessions.create` is what publishes the sidebar row, so the
610
- * Session is created through the Client rather than assumed.
611
- *
612
- * @param path - the canonical directory path.
613
- * @returns completion.
614
- */
615
- const openFolder = async (path) => {
616
- const workspace = await ctx.workspaces.create({ path })
617
-
618
- if (settings.alwaysNewSession === false) {
619
- if (uiWorkspace !== null) await uiWorkspace.openWorkspace(workspace.workspaceId)
620
- return
621
- }
622
-
623
- const sessionId = await ctx.sessions.create({ workspaceId: workspace.workspaceId })
624
- if (uiWorkspace !== null) uiWorkspace.openSession(sessionId)
393
+ function writeSeq(value) {
394
+ try {
395
+ window.sessionStorage.setItem(SEQ_KEY, String(value));
396
+ }
397
+ catch {
398
+ // A browser with storage disabled still works: it just replays on reload.
399
+ }
625
400
  }
626
-
627
- /**
628
- * Handle one request frame.
629
- *
630
- * `seq <= lastSeq` is the whole de-duplication: the stream replays what a
631
- * page missed, and EventSource reconnects with the same URL, so the same
632
- * frame can arrive twice.
633
- *
634
- * @param payload - the parsed frame.
635
- */
636
- const handle = (payload) => {
637
- if (payload === null) return
638
- if (!Number.isInteger(payload.seq) || payload.seq <= lastSeq) return
639
- if (typeof payload.path !== 'string' || payload.path.length === 0) return
640
- lastSeq = payload.seq
641
- writeSeq(lastSeq)
642
- openFolder(payload.path)
643
- .then(focusWindow)
644
- .catch((reason) => {
645
- // A refused path is the user's to see, and the Workspace notice is
646
- // the Client's channel for it; this half only logs.
647
- console.warn('dsh-open-in-dsh: could not open', payload.path, reason)
648
- })
401
+ /** Ask the OS for the foreground. Usually ignored without a user gesture. */
402
+ function focusWindow() {
403
+ try {
404
+ window.focus();
405
+ }
406
+ catch {
407
+ // Nothing to do; the folder is open either way.
408
+ }
649
409
  }
650
-
651
410
  /**
652
- * Open the stream, replaying only what this window has not handled.
653
- *
654
- * `since` travels in the URL, so a reconnect after a host restart would
655
- * still carry a sequence the new host has already passed — and would then
656
- * miss every backlog row published in the gap. `hello` reports that rewind,
657
- * and the stream is rebuilt from zero when it happens.
411
+ * Mount the plugin.
412
+ * @param ctx - browser plugin context, with `workspaces` and `sessions`.
658
413
  */
659
- const connect = () => {
660
- source = new EventSource(`${EVENTS_PATH}?since=${lastSeq}`)
661
-
662
- source.addEventListener('hello', (event) => {
663
- const payload = parseFrame(event.data)
664
- if (payload === null) return
665
- if (payload.settings !== undefined && payload.settings !== null) Object.assign(settings, payload.settings)
666
-
667
- if (Number.isInteger(payload.seq) && payload.seq < lastSeq) {
668
- lastSeq = 0
669
- writeSeq(0)
670
- source.close()
671
- connect()
672
- }
673
- })
674
-
675
- // Not `open`: EventSource owns that event name for connection state.
676
- source.addEventListener('request', (event) => handle(parseFrame(event.data)))
677
- }
678
-
679
- connect()
680
- ctx.effect(() => () => source?.close(), 'dsh-open-in-dsh: request stream')
681
-
682
- // Troubleshooting hook, callable from the devtools console:
683
- // await __dshOpenIn.open('D:\\project')
684
- // __dshOpenIn.status()
685
- window.__dshOpenIn = {
686
- route: EVENTS_PATH,
687
- open: openFolder,
688
- openWith: launch,
689
- status: () => ({
690
- lastSeq,
691
- settings: { ...settings },
692
- uiWorkspace: uiWorkspace !== null,
693
- readyState: source === null ? null : source.readyState,
694
- }),
414
+ function apply(ctx) {
415
+ const settings = { alwaysNewSession: true };
416
+ let lastSeq = readSeq();
417
+ let source = null;
418
+ let uiWorkspace = null;
419
+ // Soft dependency: navigation is the last step, and a composition without
420
+ // `dsh-client-ui-workspace` should still register the Workspace and Session
421
+ // rather than refuse to load. `ctx.get` alone would not be dependable here,
422
+ // so the instance is captured through an injection of its own.
423
+ ctx.inject(['uiWorkspace'], (scoped) => {
424
+ uiWorkspace = scoped.get('uiWorkspace');
425
+ });
426
+ // Menu labels come from the package's locale files, inlined into this
427
+ // bundle at build time: a right-click never waits on a dictionary fetch.
428
+ ctx.effect(() => ctx.locale.register(NS, MENU_DICTIONARIES), 'dsh-open-in-dsh: menu dictionaries');
429
+ const t = ctx.locale.bind(NS);
430
+ /** Availability: one probe per page (the Host caches per process life). */
431
+ const apps = createAppsReader();
432
+ /**
433
+ * Absolute path for a captured file or directory target.
434
+ * @param target - the menu target value: { sessionId, path }.
435
+ * @returns the absolute path, or null when it cannot be resolved.
436
+ */
437
+ const absolutePathFor = (target) => {
438
+ const path = target !== null && typeof target === 'object' && typeof target.path === 'string' ? target.path : '';
439
+ if (path === '')
440
+ return null;
441
+ const cwd = ctx.sessions.list.getSnapshot().byId[target.sessionId]?.cwd;
442
+ return resolveWorkspacePath(cwd, path);
443
+ };
444
+ /**
445
+ * Ask the Host to launch one allowlisted app on a path.
446
+ *
447
+ * The Host owns the command: this half can only name an id it received from
448
+ * the availability route, and the Host revalidates both the id and the path
449
+ * before spawning anything.
450
+ *
451
+ * @param app - allowlisted app id.
452
+ * @param path - absolute, validated path.
453
+ * @returns completion; rejects when the Host refuses or cannot launch.
454
+ */
455
+ const launch = async (app, path) => {
456
+ const response = await fetch(ROUTE_OPEN_WITH, {
457
+ method: 'POST',
458
+ headers: { 'content-type': 'application/json' },
459
+ body: JSON.stringify({ path: path, app: app }),
460
+ });
461
+ let payload = null;
462
+ try {
463
+ payload = await response.json();
464
+ }
465
+ catch {
466
+ payload = null;
467
+ }
468
+ if (!response.ok || payload === null || payload.ok !== true) {
469
+ const reason = payload !== null && typeof payload.reason === 'string' ? payload.reason : 'http-' + String(response.status);
470
+ throw new Error('dsh-open-in-dsh: open-with ' + app + ' failed (' + reason + ')');
471
+ }
472
+ };
473
+ /**
474
+ * Resolve the open-with actions for one captured file or directory.
475
+ * @param target - the menu target value: { sessionId, path }.
476
+ * @param signal - the provider's cancellation signal.
477
+ * @returns the action array; empty when there is nothing to offer.
478
+ */
479
+ const resolveActions = async (target, signal) => {
480
+ const absolutePath = absolutePathFor(target);
481
+ if (absolutePath === null)
482
+ return [];
483
+ const ids = await apps();
484
+ if (signal?.aborted)
485
+ return [];
486
+ return createMenuActions({ apps: ids, absolutePath: absolutePath, translate: t, launch: launch });
487
+ };
488
+ ctx.effect(() => ctx.contextMenus.register({ id: 'open-with.file', target: 'file', order: 200, resolve: resolveActions }), 'dsh-open-in-dsh: file menu');
489
+ ctx.effect(() => ctx.contextMenus.register({ id: 'open-with.directory', target: 'directory', order: 200, resolve: resolveActions }), 'dsh-open-in-dsh: directory menu');
490
+ /** One QSpace availability answer per page, shared by the rendered controls. */
491
+ const qspace = createAvailability(apps);
492
+ ctx.effect(() => () => qspace.close(), 'dsh-open-in-dsh: qspace availability');
493
+ /** The failure toast; the same string the menu actions use as `failureLabel`. */
494
+ const notifyFailure = () => {
495
+ try {
496
+ ctx.contextMenus.notify(t('menu.failed'));
497
+ }
498
+ catch {
499
+ // No menu overlay in this composition; the rejection is already logged.
500
+ }
501
+ };
502
+ /**
503
+ * Ask the Host to open one Session's working directory.
504
+ *
505
+ * The session id is all this half sends: the Host owns the id-to-cwd
506
+ * resolution so the browser never invents a path for a Session it is not
507
+ * currently showing.
508
+ *
509
+ * @param app - allowlisted app id.
510
+ * @param sessionId - the Session to open.
511
+ * @returns completion; rejects when the Host has no cwd or cannot launch.
512
+ */
513
+ const openSession = async (app, sessionId) => {
514
+ const response = await fetch(ROUTE_OPEN_SESSION, {
515
+ method: 'POST',
516
+ headers: { 'content-type': 'application/json' },
517
+ body: JSON.stringify({ sessionId: sessionId, app: app }),
518
+ });
519
+ let payload = null;
520
+ try {
521
+ payload = await response.json();
522
+ }
523
+ catch {
524
+ payload = null;
525
+ }
526
+ if (!response.ok || payload === null || payload.ok !== true) {
527
+ const reason = payload !== null && typeof payload.reason === 'string' ? payload.reason : 'http-' + String(response.status);
528
+ throw new Error('dsh-open-in-dsh: open-session ' + app + ' failed (' + reason + ')');
529
+ }
530
+ };
531
+ /**
532
+ * Resolve the Session row menu's contribution.
533
+ *
534
+ * Nothing is offered when QSpace cannot be launched; a Session the Client
535
+ * knows no cwd for still gets a row, disabled with the reason, because a
536
+ * disappearing item reads as a broken menu.
537
+ *
538
+ * @param target - the menu target value: `{sessionId, displayTitle}`.
539
+ * @param signal - the provider's cancellation signal.
540
+ * @returns the action array; empty when there is nothing to offer.
541
+ */
542
+ const resolveSessionActions = async (target, signal) => {
543
+ const sessionId = target !== null && typeof target === 'object' && typeof target.sessionId === 'string' ? target.sessionId : '';
544
+ if (sessionId === '')
545
+ return [];
546
+ const ids = await apps();
547
+ if (signal?.aborted)
548
+ return [];
549
+ if (!ids.includes('qspace'))
550
+ return [];
551
+ const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd;
552
+ if (typeof cwd !== 'string' || cwd === '') {
553
+ return [{ id: 'qspace', label: t('menu.sessionNoCwd'), disabled: true }];
554
+ }
555
+ return [
556
+ {
557
+ id: 'qspace',
558
+ label: t('menu.qspaceSession'),
559
+ failureLabel: t('menu.failed'),
560
+ run: () => openSession('qspace', sessionId),
561
+ },
562
+ ];
563
+ };
564
+ ctx.effect(() => ctx.contextMenus.register({
565
+ id: 'open-with.session',
566
+ target: 'session',
567
+ // Below the workspace plugin's own rows, above its footer actions.
568
+ order: 510,
569
+ // A Session's cwd and the active locale both decide what this row
570
+ // says, so a row already on screen must not keep a stale answer.
571
+ observe: () => [ctx.sessions.list, ctx.locale],
572
+ resolve: resolveSessionActions,
573
+ }), 'dsh-open-in-dsh: session menu');
574
+ // The one rendered entry. `slots.inject` waits for the declaration, so a
575
+ // composition without the document preview simply never asks for it.
576
+ const documentAction = createDocumentAction(React, { openWith: launch, fail: notifyFailure });
577
+ ctx.slots.inject('sidebar.right.tab.document.actions', () => ctx.slots.register({
578
+ name: 'sidebar.right.tab.document.actions',
579
+ id: 'open-with.qspace',
580
+ order: 10,
581
+ locale: NS,
582
+ inject: () => ({ hooks: { qspaceAvailable: qspace } }),
583
+ }, documentAction));
584
+ /**
585
+ * Apply one announced folder.
586
+ *
587
+ * Order matters: the Workspace must exist on the Host before a Session can
588
+ * name it, and `sessions.create` is what publishes the sidebar row, so the
589
+ * Session is created through the Client rather than assumed.
590
+ *
591
+ * @param path - the canonical directory path.
592
+ * @returns completion.
593
+ */
594
+ const openFolder = async (path) => {
595
+ const workspace = await ctx.workspaces.create({ path });
596
+ if (settings.alwaysNewSession === false) {
597
+ if (uiWorkspace !== null)
598
+ await uiWorkspace.openWorkspace(workspace.workspaceId);
599
+ return;
600
+ }
601
+ const sessionId = await ctx.sessions.create({ workspaceId: workspace.workspaceId });
602
+ if (uiWorkspace !== null)
603
+ uiWorkspace.openSession(sessionId);
604
+ };
605
+ /**
606
+ * Handle one request frame.
607
+ *
608
+ * `seq <= lastSeq` is the whole de-duplication: the stream replays what a
609
+ * page missed, and EventSource reconnects with the same URL, so the same
610
+ * frame can arrive twice.
611
+ *
612
+ * @param payload - the parsed frame.
613
+ */
614
+ const handle = (payload) => {
615
+ if (payload === null)
616
+ return;
617
+ if (!Number.isInteger(payload.seq) || payload.seq <= lastSeq)
618
+ return;
619
+ if (typeof payload.path !== 'string' || payload.path.length === 0)
620
+ return;
621
+ lastSeq = payload.seq;
622
+ writeSeq(lastSeq);
623
+ openFolder(payload.path)
624
+ .then(focusWindow)
625
+ .catch((reason) => {
626
+ // A refused path is the user's to see, and the Workspace notice is
627
+ // the Client's channel for it; this half only logs.
628
+ console.warn('dsh-open-in-dsh: could not open', payload.path, reason);
629
+ });
630
+ };
631
+ /**
632
+ * Open the stream, replaying only what this window has not handled.
633
+ *
634
+ * `since` travels in the URL, so a reconnect after a host restart would
635
+ * still carry a sequence the new host has already passed — and would then
636
+ * miss every backlog row published in the gap. `hello` reports that rewind,
637
+ * and the stream is rebuilt from zero when it happens.
638
+ */
639
+ const connect = () => {
640
+ source = new EventSource(`${EVENTS_PATH}?since=${lastSeq}`);
641
+ source.addEventListener('hello', (event) => {
642
+ const payload = parseFrame(event.data);
643
+ if (payload === null)
644
+ return;
645
+ if (payload.settings !== undefined && payload.settings !== null)
646
+ Object.assign(settings, payload.settings);
647
+ if (Number.isInteger(payload.seq) && payload.seq < lastSeq) {
648
+ lastSeq = 0;
649
+ writeSeq(0);
650
+ source.close();
651
+ connect();
652
+ }
653
+ });
654
+ // Not `open`: EventSource owns that event name for connection state.
655
+ source.addEventListener('request', (event) => handle(parseFrame(event.data)));
656
+ };
657
+ connect();
658
+ ctx.effect(() => () => source?.close(), 'dsh-open-in-dsh: request stream');
659
+ // Troubleshooting hook, callable from the devtools console:
660
+ // await __dshOpenIn.open('D:\\project')
661
+ // __dshOpenIn.status()
662
+ window.__dshOpenIn = {
663
+ route: EVENTS_PATH,
664
+ open: openFolder,
665
+ openWith: launch,
666
+ status: () => ({
667
+ lastSeq,
668
+ settings: { ...settings },
669
+ uiWorkspace: uiWorkspace !== null,
670
+ readyState: source === null ? null : source.readyState,
671
+ }),
672
+ };
695
673
  }
696
- }
697
-
698
- return { inject: ['workspaces', 'sessions', 'contextMenus', 'locale', 'slots'], apply }
674
+ return { inject: ['workspaces', 'sessions', 'contextMenus', 'locale', 'slots'], apply };
699
675
  }
700
676
 
701
677
  const plugin = createPlugin(require);