-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcommand-runner.ts
More file actions
271 lines (238 loc) · 7.14 KB
/
command-runner.ts
File metadata and controls
271 lines (238 loc) · 7.14 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import { registerDestructor } from '@ember/destroyable';
import { getOwner, setOwner } from '@ember/owner';
import Route from '@ember/routing/route';
import type RouterService from '@ember/routing/router-service';
import { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import type {
Command,
CommandContext,
CommandInvocation,
ResolvedCodeRef,
} from '@cardstack/runtime-common';
import {
CommandContextStamp,
getClass,
parseBoxelHostCommandSpecifier,
} from '@cardstack/runtime-common';
import type {
CardDef,
CardDefConstructor,
} from 'https://cardstack.com/base/card-api';
import { registerBoxelTransitionTo } from '../utils/register-boxel-transition';
import type CardService from '../services/card-service';
import type LoaderService from '../services/loader-service';
import type RealmService from '../services/realm';
const commandRequestStorageKeyPrefix = 'boxel-command-request:';
const commandRequestTtlMs = 5 * 60 * 1000;
interface StoredCommandRequest {
command: string;
input?: unknown;
nonce?: string;
createdAt?: number;
}
type GenericCommand = Command<
CardDefConstructor | undefined,
CardDefConstructor
>;
type GenericCommandConstructor = {
new (context: CommandContext): GenericCommand;
};
class CommandRunState implements CommandInvocation<CardDefConstructor> {
@tracked status: CommandInvocation<CardDefConstructor>['status'] = 'pending';
@tracked cardResult: CardDef | null = null;
@tracked error: Error | null = null;
@tracked cardResultString: string | null = null;
constructor(readonly nonce: string) {}
get isSuccess() {
return this.status === 'success';
}
get isLoading() {
return this.status === 'pending';
}
get prerenderStatus(): 'ready' | 'error' | undefined {
if (this.status === 'success') {
return 'ready';
}
if (this.status === 'error') {
return 'error';
}
return undefined;
}
}
export type CommandRunnerModel = CommandRunState;
export default class CommandRunnerRoute extends Route<CommandRunnerModel> {
@service declare router: RouterService;
@service declare loaderService: LoaderService;
@service declare cardService: CardService;
@service declare realm: RealmService;
async beforeModel() {
registerBoxelTransitionTo(this.router, this);
(globalThis as any).__boxelRenderContext = true;
registerDestructor(this, () => {
(globalThis as any).__boxelRenderContext = undefined;
});
this.realm.restoreSessionsFromStorage();
}
deactivate() {
(globalThis as any).__boxelRenderContext = undefined;
}
model(params: { request_id: string; nonce: string }): CommandRunnerModel {
let model = new CommandRunState(params.nonce);
let request = this.#consumeStoredCommandRequest(
params.request_id,
params.nonce,
);
let command = parseCommandParam(request?.command);
let commandInput = parseCommandInputValue(request?.input);
if (!command) {
model.status = 'error';
model.error = new Error('Missing, expired, or invalid command request');
return model;
}
void this.#runCommand(model, command, commandInput);
return model;
}
get commandContext(): CommandContext {
let result = {
[CommandContextStamp]: true,
} as CommandContext;
setOwner(result, getOwner(this)!);
return result;
}
async #runCommand(
model: CommandRunState,
command: ResolvedCodeRef,
commandInput: Record<string, unknown> | undefined,
) {
try {
let CommandConstructor = (await getClass(
command,
this.loaderService.loader,
)) as GenericCommandConstructor | undefined;
if (!CommandConstructor) {
throw new Error('Command not found for provided CodeRef');
}
let commandInstance = new CommandConstructor(this.commandContext);
let resultCard: CardDef | undefined;
if (commandInput) {
resultCard = await commandInstance.execute(commandInput);
} else {
resultCard = await commandInstance.execute();
}
model.cardResult = resultCard ?? null;
let serialized = resultCard
? await this.cardService.serializeCard(resultCard)
: null;
model.cardResultString = serialized
? JSON.stringify(serialized, null, 2)
: '';
model.status = 'success';
} catch (error) {
console.error('Command runner failed', {
command,
error,
});
model.error = error instanceof Error ? error : new Error(String(error));
model.status = 'error';
}
}
#consumeStoredCommandRequest(
requestId: string | undefined,
expectedNonce: string,
): StoredCommandRequest | undefined {
if (typeof window === 'undefined' || !window.localStorage) {
return undefined;
}
if (!requestId || typeof requestId !== 'string') {
return undefined;
}
let key = `${commandRequestStorageKeyPrefix}${requestId}`;
let raw = window.localStorage.getItem(key);
if (!raw) {
return undefined;
}
window.localStorage.removeItem(key);
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return undefined;
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return undefined;
}
let request = parsed as StoredCommandRequest;
if (
typeof request.nonce === 'string' &&
request.nonce.trim() !== expectedNonce
) {
return undefined;
}
if (typeof request.createdAt === 'number') {
let ageMs = Date.now() - request.createdAt;
if (ageMs > commandRequestTtlMs) {
return undefined;
}
}
return request;
}
}
function parseCommandParam(
raw: string | undefined | unknown,
): ResolvedCodeRef | undefined {
if (typeof raw !== 'string') {
return undefined;
}
let value = safeDecodeURIComponent(raw).trim();
if (!value) {
return undefined;
}
let specifier = parseBoxelHostCommandSpecifier(value);
if (specifier) {
return specifier;
}
if (isBoxelHostCommandSpecifierWithoutExport(value)) {
return undefined;
}
try {
let url = new URL(value);
let pathname = url.pathname.replace(/\/+$/, '');
let index = pathname.lastIndexOf('/');
if (index <= 0 || index >= pathname.length - 1) {
return undefined;
}
return {
module: `${url.origin}${pathname.slice(0, index)}`,
name: pathname.slice(index + 1),
};
} catch {
// Accept module specifier forms like "<module>/<exportName>".
}
let index = value.lastIndexOf('/');
if (index <= 0 || index >= value.length - 1) {
return undefined;
}
return {
module: value.slice(0, index),
name: value.slice(index + 1),
};
}
function isBoxelHostCommandSpecifierWithoutExport(value: string): boolean {
return /^@?cardstack\/boxel-host\/commands\/[^/?#\s]+$/.test(value);
}
function safeDecodeURIComponent(value: string): string {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function parseCommandInputValue(
parsed: unknown,
): Record<string, unknown> | undefined {
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return undefined;
}
return parsed as Record<string, unknown>;
}