Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
213 lines (185 loc) · 5.53 KB
/
Copy pathindex.ts
File metadata and controls
213 lines (185 loc) · 5.53 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
210
211
212
213
import {
EvaluateResponse,
StartEvaluationRequest,
EvaluationResult,
StopEvaluationRequest,
EvaluationError,
MissingSources,
EvaluateRequest
} from "@jsheets/protocol/src/jsheets/api/snippet_runtime_pb";
import * as SheetProtocol from "@jsheets/protocol/src/jsheets/api/sheet_pb";
import {Sheet} from '../sheet'
export interface EvaluationListener {
onEnd(): void
onResult(result: EvaluationResult): void
onError(error: EvaluationError): void
onMissingSources(sources: MissingSources): void
}
export interface Evaluation {
stop(): void
}
export interface Location {
host: string
protocol: string
}
export default class Client {
static create(): Client {
return Client.forHost(window.location)
}
static forHost(location: Location): Client {
return new Client(
`${location.protocol}//${location.host}`,
this.resolveWebSocketHost(location)
)
}
private static resolveWebSocketHost(location: Location): string {
const uri = location.protocol === "https:" ? "wss:" : "ws:"
return `${uri}//${location.host}`
}
private readonly sheets_: SheetClient
private constructor(
private readonly baseUrl: string,
private readonly webSocketUrl: string
) {
this.sheets_ = new SheetClient(baseUrl)
}
evaluate(start: StartEvaluationRequest, listener: EvaluationListener): Evaluation {
const client = new WebSocket(`${this.webSocketUrl}/api/v1/evaluate`)
client.onerror = error => {
console.log({error})
}
client.onopen = () => {
const request = new EvaluateRequest()
request.setStart(start)
client.send(request.serializeBinary())
}
client.onmessage = async (message) => {
const blob = message.data as Blob
if (blob === undefined) {
return
}
const bytes = await blob.arrayBuffer()
let response
try {
response = EvaluateResponse.deserializeBinary(new Uint8Array(bytes))
} catch (error) {
throw new Error(JSON.stringify({error, note: 'received invalid message', message: message.data}))
}
response.getErrorList()?.forEach(listener.onError)
response.getMissingSourcesList()?.forEach(listener.onMissingSources)
response.getResultList()?.forEach(listener.onResult)
}
client.onclose = event => {
listener.onEnd()
console.log({event})
}
return new WebSocketEvaluation(client)
}
sheets(): SheetClient {
return this.sheets_
}
}
class WebSocketEvaluation implements Evaluation {
constructor(private readonly connection: WebSocket) {}
stop() {
const request = new EvaluateRequest()
request.setStop(new StopEvaluationRequest())
this.connection.send(request.serializeBinary())
}
}
export class SheetClient {
constructor(private readonly baseUrl: string) { }
async find(id: string): Promise<Sheet> {
const call = await fetch(`${this.baseUrl}/api/v1/sheets/${id}`)
if (call.ok) {
const body = await call.json()
return createSheetFromResponse(body)
}
throw new Error(`${call.status}`)
}
async post(snippet: Partial<SheetProtocol.Sheet.AsObject>): Promise<Sheet> {
convertRequest(snippet)
const call = await fetch(`${this.baseUrl}/api/v1/sheets`, {
method: 'POST',
body: JSON.stringify(snippet)
})
if (call.ok) {
const body = await call.json()
return createSheetFromResponse(body)
}
throw new Error(`${call.status}`)
}
}
function createSheetFromResponse(response: Record<string, any>): Sheet {
convertResponse(response)
const message = response as SheetProtocol.Sheet.AsObject
return {
id: message.id,
title: message.title,
description: message.description,
snippets: message.snippetsList.map(snippet => ({
id: snippet.id,
order: snippet.order,
title: snippet.name,
components: snippet.componentsList.map(component => {
const kind = (component.kind as unknown) as string
return {
id: component.id,
order: component.order,
type: kind.toLowerCase(),
content: component.content
}
})
}))
} as Sheet
}
function convertResponse(object: Record<string, any>) {
return process(object, '', convertResponseKey(['snippets', 'snippets.components']))
}
function convertResponseKey(listKeys: string[]) {
return (key: string, path: string) => {
const converted = convertSnakeCaseToCamelCase(key)
return listKeys.includes(path)
? `${converted}List`
: converted
}
}
function convertRequest(object: Record<string, any>) {
return process(object, '', convertRequestKey)
}
function process(
object: Record<string, any>,
path: string,
mapKey: (key: string, path: string) => string
) {
if (typeof object !== 'object') {
return
}
for (const [key, value] of Object.entries(object)) {
const childPath = path === '' ? key : path + '.' + key
const fixedKey = mapKey(key, childPath)
if (fixedKey !== key) {
object[fixedKey] = value
delete object[key]
}
if (value == null) {
continue
}
if (Array.isArray(value)) {
for (const element of value) {
process(element, childPath, mapKey)
}
} else {
process(value, childPath, mapKey)
}
}
}
function convertRequestKey(key: string) {
return convertCamelCaseToSnakeCase(key).replace(/_list$/, "")
}
function convertSnakeCaseToCamelCase(input: string) {
return input.replace(/_([a-z])?/, match => match?.toUpperCase() || '')
}
function convertCamelCaseToSnakeCase(input: string) {
return input.split(/(?=[A-Z])/).join('_').toLowerCase()
}