forked from firebase/firebase-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsdk.ts
240 lines (225 loc) · 8.85 KB
/
sdk.ts
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
import * as yaml from "yaml";
import * as fs from "fs";
import * as clc from "colorette";
import * as path from "path";
import { dirExistsSync } from "../../../fsutils";
import { promptForDirectory, promptOnce, prompt } from "../../../prompt";
import {
readFirebaseJson,
getPlatformFromFolder,
getFrameworksFromPackageJson,
resolvePackageJson,
SUPPORTED_FRAMEWORKS,
} from "../../../dataconnect/fileUtils";
import { Config } from "../../../config";
import { Setup } from "../..";
import { load } from "../../../dataconnect/load";
import {
ConnectorInfo,
ConnectorYaml,
DartSDK,
JavascriptSDK,
KotlinSDK,
Platform,
SupportedFrameworks,
} from "../../../dataconnect/types";
import { DataConnectEmulator } from "../../../emulator/dataconnectEmulator";
import { FirebaseError } from "../../../error";
import { camelCase, snakeCase, upperFirst } from "lodash";
import { logSuccess, logBullet } from "../../../utils";
export const FDC_APP_FOLDER = "_FDC_APP_FOLDER";
export type SDKInfo = {
connectorYamlContents: string;
connectorInfo: ConnectorInfo;
displayIOSWarning: boolean;
};
export async function doSetup(setup: Setup, config: Config): Promise<void> {
const sdkInfo = await askQuestions(setup, config);
await actuate(sdkInfo);
logSuccess(
`If you'd like to add more generated SDKs to your app your later, run ${clc.bold("firebase init dataconnect:sdk")} again`,
);
}
async function askQuestions(setup: Setup, config: Config): Promise<SDKInfo> {
const serviceCfgs = readFirebaseJson(config);
// TODO: This current approach removes comments from YAML files. Consider a different approach that won't.
const serviceInfos = await Promise.all(
serviceCfgs.map((c) => load(setup.projectId || "", config, c.source)),
);
const connectorChoices: { name: string; value: ConnectorInfo }[] = serviceInfos
.map((si) => {
return si.connectorInfo.map((ci) => {
return {
name: `${si.dataConnectYaml.serviceId}/${ci.connectorYaml.connectorId}`,
value: ci,
};
});
})
.flat();
if (!connectorChoices.length) {
throw new FirebaseError(
`Your config has no connectors to set up SDKs for. Run ${clc.bold(
"firebase init dataconnect",
)} to set up a service and connectors.`,
);
}
// First, lets check if we are in an app directory
let appDir = process.env[FDC_APP_FOLDER] || process.cwd();
let targetPlatform = await getPlatformFromFolder(appDir);
if (targetPlatform === Platform.NONE && !process.env[FDC_APP_FOLDER]?.length) {
// If we aren't in an app directory, ask the user where their app is, and try to autodetect from there.
appDir = await promptForDirectory({
config,
message:
"Where is your app directory? Leave blank to set up a generated SDK in your current directory.",
});
targetPlatform = await getPlatformFromFolder(appDir);
}
if (targetPlatform === Platform.NONE || targetPlatform === Platform.MULTIPLE) {
if (targetPlatform === Platform.NONE) {
logBullet(`Couldn't automatically detect app your in directory ${appDir}.`);
} else {
logSuccess(`Detected multiple app platforms in directory ${appDir}`);
// Can only setup one platform at a time, just ask the user
}
const platforms = [
{ name: "iOS (Swift)", value: Platform.IOS },
{ name: "Web (JavaScript)", value: Platform.WEB },
{ name: "Android (Kotlin)", value: Platform.ANDROID },
{ name: "Flutter (Dart)", value: Platform.FLUTTER },
];
targetPlatform = await promptOnce({
message: "Which platform do you want to set up a generated SDK for?",
type: "list",
choices: platforms,
});
} else {
logSuccess(`Detected ${targetPlatform} app in directory ${appDir}`);
}
const connectorInfo: ConnectorInfo = await promptOnce({
message: "Which connector do you want set up a generated SDK for?",
type: "list",
choices: connectorChoices,
});
const connectorYaml = JSON.parse(JSON.stringify(connectorInfo.connectorYaml)) as ConnectorYaml;
const newConnectorYaml = await generateSdkYaml(
targetPlatform,
connectorYaml,
connectorInfo.directory,
appDir,
);
if (targetPlatform === Platform.WEB) {
const unusedFrameworks = SUPPORTED_FRAMEWORKS.filter(
(framework) => !newConnectorYaml!.generate?.javascriptSdk![framework],
);
if (unusedFrameworks.length > 0) {
const additionalFrameworks: { fdcFrameworks: (keyof SupportedFrameworks)[] } = await prompt(
setup,
[
{
type: "checkbox",
name: "fdcFrameworks",
message:
"Which framework would you like to generate SDKs for? " +
"Press Space to select features, then Enter to confirm your choices.",
choices: unusedFrameworks.map((frameworkStr) => ({
value: frameworkStr,
name: frameworkStr,
checked: false,
})),
},
],
);
for (const framework of additionalFrameworks.fdcFrameworks) {
newConnectorYaml!.generate!.javascriptSdk![framework] = true;
}
}
}
// TODO: Prompt user about adding generated paths to .gitignore
const connectorYamlContents = yaml.stringify(newConnectorYaml);
connectorInfo.connectorYaml = newConnectorYaml;
const displayIOSWarning = targetPlatform === Platform.IOS;
return { connectorYamlContents, connectorInfo, displayIOSWarning };
}
export async function generateSdkYaml(
targetPlatform: Platform,
connectorYaml: ConnectorYaml,
connectorDir: string,
appDir: string,
): Promise<ConnectorYaml> {
if (!connectorYaml.generate) {
connectorYaml.generate = {};
}
if (targetPlatform === Platform.IOS) {
const swiftSdk = {
outputDir: path.relative(connectorDir, path.join(appDir, `dataconnect-generated/swift`)),
package: upperFirst(camelCase(connectorYaml.connectorId)) + "Connector",
};
connectorYaml.generate.swiftSdk = swiftSdk;
}
if (targetPlatform === Platform.WEB) {
const pkg = `${connectorYaml.connectorId}-connector`;
const packageJsonDir = path.relative(connectorDir, appDir);
const javascriptSdk: JavascriptSDK = {
outputDir: path.relative(connectorDir, path.join(appDir, `dataconnect-generated/js/${pkg}`)),
package: `@firebasegen/${pkg}`,
// If appDir has package.json, Emulator would add Generated JS SDK to `package.json`.
// Otherwise, emulator would ignore it. Always add it here in case `package.json` is added later.
// TODO: Explore other platforms that can be automatically installed. Dart? Android?
packageJsonDir,
};
const packageJson = await resolvePackageJson(appDir);
if (packageJson) {
const frameworksUsed = getFrameworksFromPackageJson(packageJson);
for (const framework of frameworksUsed) {
javascriptSdk[framework] = true;
}
}
connectorYaml.generate.javascriptSdk = javascriptSdk;
}
if (targetPlatform === Platform.FLUTTER) {
const pkg = `${snakeCase(connectorYaml.connectorId)}_connector`;
const dartSdk: DartSDK = {
outputDir: path.relative(
connectorDir,
path.join(appDir, `dataconnect-generated/dart/${pkg}`),
),
package: pkg,
};
connectorYaml.generate.dartSdk = dartSdk;
}
if (targetPlatform === Platform.ANDROID) {
const kotlinSdk: KotlinSDK = {
outputDir: path.relative(connectorDir, path.join(appDir, `dataconnect-generated/kotlin`)),
package: `connectors.${snakeCase(connectorYaml.connectorId)}`,
};
// app/src/main/kotlin and app/src/main/java are conventional for Android,
// but not required or enforced. If one of them is present (preferring the
// "kotlin" directory), use it. Otherwise, fall back to the dataconnect-generated dir.
for (const candidateSubdir of ["app/src/main/java", "app/src/main/kotlin"]) {
const candidateDir = path.join(appDir, candidateSubdir);
if (dirExistsSync(candidateDir)) {
kotlinSdk.outputDir = path.relative(connectorDir, candidateDir);
}
}
connectorYaml.generate.kotlinSdk = kotlinSdk;
}
return connectorYaml;
}
export async function actuate(sdkInfo: SDKInfo) {
const connectorYamlPath = `${sdkInfo.connectorInfo.directory}/connector.yaml`;
fs.writeFileSync(connectorYamlPath, sdkInfo.connectorYamlContents, "utf8");
logBullet(`Wrote new config to ${connectorYamlPath}`);
await DataConnectEmulator.generate({
configDir: sdkInfo.connectorInfo.directory,
connectorId: sdkInfo.connectorInfo.connectorYaml.connectorId,
});
logBullet(`Generated SDK code for ${sdkInfo.connectorInfo.connectorYaml.connectorId}`);
if (sdkInfo.connectorInfo.connectorYaml.generate?.swiftSdk && sdkInfo.displayIOSWarning) {
logBullet(
clc.bold(
"Please follow the instructions here to add your generated sdk to your XCode project:\n\thttps://firebase.google.com/docs/data-connect/ios-sdk#set-client",
),
);
}
}