-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathconfig.ts
More file actions
347 lines (300 loc) · 10.3 KB
/
config.ts
File metadata and controls
347 lines (300 loc) · 10.3 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import { isPathInside } from "./file-utils";
import { DeepReadOnly } from "../metaprogramming";
import { ConnectorYaml, DataConnectYaml, mainSchemaYaml } from "../../../src/dataconnect/types";
import { Result, ResultValue } from "../result";
import { computed, effect, signal } from "@preact/signals-core";
import {
_createWatcher as createWatcher,
firebaseConfig,
getConfigPath,
} from "../core/config";
import * as vscode from "vscode";
import * as promise from "../utils/promise";
import {
readConnectorYaml,
readDataConnectYaml,
readFirebaseJson as readFdcFirebaseJson,
} from "../../../src/dataconnect/load";
import { Config } from "../config";
import { DataConnectMultiple } from "../firebaseConfig";
import path from "path";
import { ExtensionBrokerImpl } from "../extension-broker";
import * as fs from "fs";
import { EmulatorHub } from "../../../src/emulator/hub";
export * from "../core/config";
export type DataConnectConfigsValue = ResolvedDataConnectConfigs | undefined;
export type DataConnectConfigsError = {
path?: string;
error: Error | unknown;
range: vscode.Range;
};
export const dataConnectConfigs = signal<
| Result<DataConnectConfigsValue | undefined, DataConnectConfigsError>
| undefined
>(undefined);
export class ErrorWithPath extends Error {
constructor(
readonly path: string,
readonly error: unknown,
readonly range: vscode.Range,
) {
super(error instanceof Error ? error.message : `${error}`);
}
}
export async function registerDataConnectConfigs(
context: vscode.ExtensionContext,
broker: ExtensionBrokerImpl,
) {
function handleResult(
firebaseConfig: Result<Config | undefined> | undefined,
): undefined | (() => void) {
// While waiting for the promise to resolve, we clear the configs, to tell anything that depends
// on it that it's loading.
dataConnectConfigs.value = undefined;
const configs = firebaseConfig?.followAsync<
ResolvedDataConnectConfigs | undefined,
DataConnectConfigsError
>(
async (config) => {
const configs = await _readDataConnectConfigs(
readFdcFirebaseJson(config),
);
return new ResultValue<
ResolvedDataConnectConfigs | undefined,
DataConnectConfigsError
>(configs.requireValue);
},
(err) => {
if (err instanceof ErrorWithPath) {
return { path: err.path, error: err.error, range: err.range };
}
return {
path: undefined,
error: err,
range: new vscode.Range(0, 0, 0, 0),
};
},
);
const operation =
configs &&
promise.cancelableThen(configs, (configs) => {
return (dataConnectConfigs.value = configs);
});
return operation?.cancel;
}
context.subscriptions.push({
dispose: effect(() => handleResult(firebaseConfig.value)),
});
const dataConnectWatcher = await createWatcher(
"**/{dataconnect,connector}.yaml",
);
if (dataConnectWatcher) {
context.subscriptions.push(dataConnectWatcher);
dataConnectWatcher.onDidChange(() => handleResult(firebaseConfig.value));
dataConnectWatcher.onDidCreate(() => handleResult(firebaseConfig.value));
dataConnectWatcher.onDidDelete(() => handleResult(firebaseConfig.value));
}
const hasConfigs = computed(
() => !!dataConnectConfigs.value?.tryReadValue?.values.length,
);
context.subscriptions.push({
dispose: effect(() => {
broker.send("notifyHasFdcConfigs", hasConfigs.value);
}),
});
context.subscriptions.push({
dispose: broker.on("getInitialHasFdcConfigs", () => {
broker.send("notifyHasFdcConfigs", hasConfigs.value);
}),
});
}
/** @internal */
export async function _readDataConnectConfigs(
fdcConfig: DataConnectMultiple,
): Promise<Result<ResolvedDataConnectConfigs | undefined>> {
async function mapConnector(connectorDirPath: string) {
const connectorYaml = await readConnectorYaml(connectorDirPath).catch(
(err: unknown) => {
const connectorPath = path.normalize(
path.join(connectorDirPath, "connector.yaml"),
);
throw new ErrorWithPath(
connectorPath,
err,
new vscode.Range(0, 0, 0, 0),
);
},
);
return new ResolvedConnectorYaml(connectorDirPath, connectorYaml);
}
async function mapDataConnect(absoluteLocation: string) {
const dataConnectYaml = await readDataConnectYaml(absoluteLocation);
const connectorDirs = dataConnectYaml.connectorDirs;
if (!Array.isArray(connectorDirs)) {
throw new ErrorWithPath(
path.join(absoluteLocation, "dataconnect.yaml"),
`Expected 'connectorDirs' to be an array, but got ${connectorDirs}`,
// TODO(rrousselGit): Decode Yaml using AST to have the error message point to the `connectorDirs:` line
new vscode.Range(0, 0, 0, 0),
);
}
const resolvedConnectors = await Promise.all(
connectorDirs.map((relativeConnector) => {
const absoluteConnector = asAbsolutePath(
relativeConnector,
absoluteLocation,
);
const connectorPath = path.join(absoluteConnector, "connector.yaml");
try {
// Check if the file exists
if (!fs.existsSync(connectorPath)) {
throw new ErrorWithPath(
path.join(absoluteLocation, "dataconnect.yaml"),
`No connector.yaml found at ${relativeConnector}`,
// TODO(rrousselGit): Decode Yaml using AST to have the error message point to the `connectorDirs:` line
new vscode.Range(0, 0, 0, 0),
);
}
return mapConnector(absoluteConnector);
} catch (error) {
if (error instanceof ErrorWithPath) {
throw error;
}
throw new ErrorWithPath(
connectorPath,
error,
new vscode.Range(0, 0, 0, 0),
);
}
}),
);
return new ResolvedDataConnectConfig(
absoluteLocation,
dataConnectYaml,
resolvedConnectors,
dataConnectYaml.location,
);
}
return Result.guard(async () => {
const dataConnects = await Promise.all(
fdcConfig
// Paths may be relative to the firebase.json file.
.map((relative) => asAbsolutePath(relative.source, getConfigPath()!))
.map(async (absolutePath) => {
try {
return await mapDataConnect(absolutePath);
} catch (error) {
if (error instanceof ErrorWithPath) {
throw error;
}
throw new ErrorWithPath(
path.join(absolutePath, "dataconnect.yaml"),
error,
new vscode.Range(0, 0, 0, 0),
);
}
}),
);
return new ResolvedDataConnectConfigs(dataConnects);
});
}
function asAbsolutePath(relativePath: string, from: string): string {
return path.normalize(path.join(from, relativePath));
}
export class ResolvedConnectorYaml {
constructor(
readonly path: string,
readonly value: DeepReadOnly<ConnectorYaml>,
) {}
containsPath(path: string) {
return isPathInside(path, this.path);
}
}
export class ResolvedDataConnectConfig {
constructor(
readonly path: string,
readonly value: DeepReadOnly<DataConnectYaml>,
readonly resolvedConnectors: ResolvedConnectorYaml[],
readonly dataConnectLocation: string,
) {}
get connectorIds(): string[] {
const result: string[] = [];
for (const connector of this.resolvedConnectors) {
const id = connector.value.connectorId;
if (id) {
result.push(id);
}
}
return result;
}
get connectorDirs(): string[] {
return this.value.connectorDirs;
}
get schemaDir(): string {
return mainSchemaYaml(this.value).source;
}
get relativePath(): string {
if (!getConfigPath()) {
return this.path.split("/").pop()!;
}
return path.relative(getConfigPath()!, this.path);
}
get relativeSchemaPath(): string {
return this.schemaDir.replace(".", this.relativePath);
}
get relativeConnectorPaths(): string[] {
return this.connectorDirs.map((connectorDir) =>
connectorDir.replace(".", this.relativePath),
);
}
findConnectorById(connectorId: string): ResolvedConnectorYaml | undefined {
return this.resolvedConnectors.find(
(connector) => connector.value.connectorId === connectorId,
);
}
containsPath(path: string) {
return isPathInside(path, this.path);
}
findEnclosingConnectorForPath(filePath: string) {
return this.resolvedConnectors.find(
(connector) => connector?.containsPath(filePath) ?? false,
);
}
}
/** The fully resolved `dataconnect.yaml` and its connectors */
export class ResolvedDataConnectConfigs {
constructor(readonly values: DeepReadOnly<ResolvedDataConnectConfig[]>) {}
get serviceIds(): string[] {
return this.values.map((config) => config.value.serviceId);
}
get allConnectors(): ResolvedConnectorYaml[] {
return this.values.flatMap((dc) => dc.resolvedConnectors);
}
findById(serviceId: string): ResolvedDataConnectConfig {
const dc = this.values.find((dc) => dc.value.serviceId === serviceId);
if (!dc) {
throw new Error(`No dataconnect.yaml with serviceId ${serviceId}. Available: ${this.serviceIds.join(", ")}`);
}
return dc;
}
findEnclosingServiceForPath(filePath: string): ResolvedDataConnectConfig {
const dc = this.values.find((dc) => dc.containsPath(filePath));
if (!dc) {
throw new Error(`No enclosing dataconnect.yaml found for path ${filePath}. Available Paths: ${this.values.map((dc) => dc.path).join(", ")}`);
}
return dc;
}
getApiServicePathByPath(projectId: string | undefined, path: string): string {
const dataConnectConfig = this.findEnclosingServiceForPath(path);
const serviceId = dataConnectConfig?.value.serviceId;
const locationId = dataConnectConfig?.dataConnectLocation;
// FDC emulator can service multiple services keyed by serviceId.
// ${projectId} and ${locationId} aren't used to resolve emulator service.
projectId = projectId || EmulatorHub.MISSING_PROJECT_PLACEHOLDER;
return `projects/${projectId}/locations/${locationId}/services/${serviceId}`;
}
}
// TODO: Expand this into a VSCode env config object/class
export enum VSCODE_ENV_VARS {
DATA_CONNECT_ORIGIN = "FIREBASE_DATACONNECT_URL",
}