-
-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathhost-docks.ts
More file actions
209 lines (189 loc) · 6.72 KB
/
Copy pathhost-docks.ts
File metadata and controls
209 lines (189 loc) · 6.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import type { DevToolsNodeContext } from 'devframe/types'
import type { SharedState } from 'devframe/utils/shared-state'
import type {
DevToolsDockEntry,
DevToolsDockHost as DevToolsDockHostType,
DevToolsDockUserEntry,
DevToolsViewBuiltin,
DevToolsViewIframe,
RemoteConnectionInfo,
RemoteDockOptions,
} from '../types/docks'
import type { DevToolsDocksUserSettings } from '../types/settings'
import type { KitNodeContext } from './context'
import { REMOTE_CONNECTION_KEY } from 'devframe/constants'
import { createStorage } from 'devframe/node'
import { getInternalContext } from 'devframe/node/internal'
import { createEventEmitter } from 'devframe/utils/events'
import { join } from 'pathe'
import { DEFAULT_STATE_USER_SETTINGS } from '../constants'
import { diagnostics } from './diagnostics'
interface RemoteDockRecord {
token: string
options: Required<RemoteDockOptions>
}
function normaliseRemoteOptions(remote: true | RemoteDockOptions): Required<RemoteDockOptions> {
const opts = remote === true ? {} : remote
return {
transport: opts.transport ?? 'fragment',
originLock: opts.originLock ?? true,
}
}
function base64UrlEncode(value: string): string {
// URL-safe base64 without padding so the descriptor is compact and safe to
// drop into a URL without escaping.
const bytes = new TextEncoder().encode(value)
let binary = ''
for (const byte of bytes)
binary += String.fromCharCode(byte)
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
function buildRemoteUrl(baseUrl: string, payload: RemoteConnectionInfo, transport: 'fragment' | 'query'): string {
const encoded = base64UrlEncode(JSON.stringify(payload))
const param = `${REMOTE_CONNECTION_KEY}=${encoded}`
if (transport === 'fragment') {
// Replace any existing fragment bearing our key; otherwise append.
const hashIdx = baseUrl.indexOf('#')
if (hashIdx === -1)
return `${baseUrl}#${param}`
const before = baseUrl.slice(0, hashIdx)
return `${before}#${param}`
}
// query
const qIdx = baseUrl.indexOf('?')
const hashIdx = baseUrl.indexOf('#')
const hash = hashIdx === -1 ? '' : baseUrl.slice(hashIdx)
const beforeHash = hashIdx === -1 ? baseUrl : baseUrl.slice(0, hashIdx)
const sep = qIdx === -1 || qIdx >= (hashIdx === -1 ? beforeHash.length : hashIdx) ? '?' : '&'
return `${beforeHash}${sep}${param}${hash}`
}
export class DevToolsDockHost implements DevToolsDockHostType {
public readonly views: DevToolsDockHostType['views'] = new Map()
public readonly events: DevToolsDockHostType['events'] = createEventEmitter()
public userSettings: SharedState<DevToolsDocksUserSettings> = undefined!
/** Dock-id → allocated remote token + resolved options. */
private readonly remoteDocks = new Map<string, RemoteDockRecord>()
constructor(
public readonly context: KitNodeContext,
) {
}
async init() {
this.userSettings = await this.context.rpc.sharedState.get('devframe:user-settings', {
sharedState: createStorage({
filepath: join(this.context.host.getStorageDir('workspace'), 'settings.json'),
initialValue: DEFAULT_STATE_USER_SETTINGS(),
}),
})
}
values({
includeBuiltin = true,
}: {
includeBuiltin?: boolean
} = {}): DevToolsDockEntry[] {
const context = this.context
const builtinDocksEntries: DevToolsViewBuiltin[] = [
{
type: '~builtin',
id: '~terminals',
title: 'Terminals',
icon: 'ph:terminal-duotone',
category: '~builtin',
get when() {
return context.terminals.sessions.size === 0 ? 'false' : undefined
},
},
{
type: '~builtin',
id: '~messages',
title: 'Messages & Notifications',
icon: 'ph:notification-duotone',
category: '~builtin',
get badge() {
const size = context.messages.entries.size
return size > 0 ? String(size) : undefined
},
},
{
type: '~builtin',
id: '~settings',
title: 'Settings',
category: '~builtin',
icon: 'ph:gear-duotone',
},
]
return [
...Array.from(this.views.values(), view => this.projectView(view)),
...(includeBuiltin ? builtinDocksEntries : []),
]
}
private projectView(view: DevToolsDockUserEntry): DevToolsDockUserEntry {
if (view.type !== 'iframe' || !view.remote)
return view
const record = this.remoteDocks.get(view.id)
const endpoint = getInternalContext(this.context as DevToolsNodeContext).wsEndpoint
if (!record || !endpoint)
return view
const payload: RemoteConnectionInfo = {
v: 1,
backend: 'websocket',
websocket: endpoint.url,
authToken: record.token,
origin: this.resolveDevServerOrigin(),
}
return {
...view,
url: buildRemoteUrl(view.url, payload, record.options.transport),
} satisfies DevToolsViewIframe
}
private resolveDevServerOrigin(): string {
return this.context.host.resolveOrigin()
}
register<T extends DevToolsDockUserEntry>(view: T, force?: boolean): {
update: (patch: Partial<T>) => void
} {
if (this.views.has(view.id) && !force) {
throw diagnostics.DTK0050({ id: view.id })
}
this.prepareRemoteRegistration(view)
this.views.set(view.id, view)
this.events.emit('dock:entry:updated', view)
return {
update: (patch) => {
if (patch.id && patch.id !== view.id) {
throw diagnostics.DTK0051()
}
this.update(Object.assign(this.views.get(view.id)!, patch))
},
}
}
update(view: DevToolsDockUserEntry): void {
if (!this.views.has(view.id)) {
throw diagnostics.DTK0052({ id: view.id })
}
this.prepareRemoteRegistration(view)
this.views.set(view.id, view)
this.events.emit('dock:entry:updated', view)
}
private prepareRemoteRegistration(view: DevToolsDockUserEntry): void {
const internal = getInternalContext(this.context as DevToolsNodeContext)
// Always revoke any previously allocated token for this dock id — covers
// force re-registration and update() paths.
internal.revokeRemoteTokensForDock(view.id)
this.remoteDocks.delete(view.id)
if (view.type !== 'iframe' || !view.remote)
return
const options = normaliseRemoteOptions(view.remote)
let dockOrigin: string
try {
dockOrigin = new URL(view.url).origin
}
catch {
// Relative/invalid URL — origin-lock can't be enforced. Fall back to the
// dev-server origin; this still works because the iframe loads in the
// same browser anyway.
dockOrigin = this.resolveDevServerOrigin()
}
const token = internal.allocateRemoteToken(view.id, dockOrigin, options.originLock)
this.remoteDocks.set(view.id, { token, options })
}
}