This repository has been archived by the owner on Jan 18, 2024. It is now read-only.
/
Exp.ts
304 lines (264 loc) · 9.65 KB
/
Exp.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
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
import { AppJSONConfig, BareAppConfig, configFilename, readConfigJsonAsync } from '@expo/config';
import { getEntryPoint } from '@expo/config/paths';
import fs from 'fs-extra';
import merge from 'lodash/merge';
import path from 'path';
import spawnAsync from '@expo/spawn-async';
import JsonFile from '@expo/json-file';
import Minipass from 'minipass';
import pacote, { PackageSpec } from 'pacote';
import tar from 'tar';
import Api from './Api';
import ApiV2 from './ApiV2';
import Logger from './Logger';
import NotificationCode from './NotificationCode';
import UserManager from './User';
import * as UrlUtils from './UrlUtils';
import UserSettings from './UserSettings';
import * as ProjectSettings from './ProjectSettings';
// TODO(ville): update when this has landed: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/36598
type ReadEntry = any;
const supportedPlatforms = ['ios', 'android', 'web'];
export function determineEntryPoint(projectRoot: string, platform?: string): string {
if (platform && !supportedPlatforms.includes(platform)) {
throw new Error(
`Failed to resolve the project's entry file: The platform "${platform}" is not supported.`
);
}
// TODO: Bacon: support platform extension resolution like .ios, .native
// const platforms = [platform, 'native'].filter(Boolean) as string[];
const platforms: string[] = [];
const entry = getEntryPoint(projectRoot, ['./index'], platforms);
if (!entry)
throw new Error(
`The project entry file could not be resolved. Please either define it in the \`package.json\` (main), \`app.json\` (expo.entryPoint), create an \`index.js\`, or install the \`expo\` package.`
);
return path.relative(projectRoot, entry);
}
class Transformer extends Minipass {
data: string;
config: AppJSONConfig | BareAppConfig;
constructor(config: AppJSONConfig | BareAppConfig) {
super();
this.data = '';
this.config = config;
}
write(data: string) {
this.data += data;
return true;
}
end() {
let replaced = this.data
.replace(/Hello App Display Name/g, this.config.displayName || this.config.name)
.replace(/HelloWorld/g, this.config.name)
.replace(/helloworld/g, this.config.name.toLowerCase());
super.write(replaced);
return super.end();
}
}
// Binary files, don't process these (avoid decoding as utf8)
const binaryExtensions = ['.png', '.jar'];
function createFileTransform(config: AppJSONConfig | BareAppConfig) {
return function transformFile(entry: ReadEntry) {
if (!binaryExtensions.includes(path.extname(entry.path)) && config.name) {
return new Transformer(config);
}
return undefined;
};
}
export async function extractAndInitializeTemplateApp(
templateSpec: PackageSpec,
projectRoot: string,
packageManager: 'yarn' | 'npm' = 'npm',
config: AppJSONConfig | BareAppConfig
) {
Logger.notifications.info({ code: NotificationCode.PROGRESS }, 'Extracting project files...');
await extractTemplateAppAsync(templateSpec, projectRoot, config);
// Update files
Logger.notifications.info({ code: NotificationCode.PROGRESS }, 'Customizing project...');
let appFile = new JsonFile(path.join(projectRoot, 'app.json'));
let appJson = merge(await appFile.readAsync(), config);
await appFile.writeAsync(appJson);
let packageFile = new JsonFile(path.join(projectRoot, 'package.json'));
let packageJson = await packageFile.readAsync();
// Adding `private` stops npm from complaining about missing `name` and `version` fields.
// We don't add a `name` field because it also exists in `app.json`.
packageJson = { ...packageJson, private: true };
// These are metadata fields related to the template package, let's remove them from the package.json.
delete packageJson.name;
delete packageJson.version;
delete packageJson.description;
delete packageJson.tags;
delete packageJson.repository;
// pacote adds these, but we don't want them in the package.json of the project.
delete packageJson._resolved;
delete packageJson._integrity;
delete packageJson._from;
await packageFile.writeAsync(packageJson);
await initGitRepoAsync(projectRoot);
await installDependenciesAsync(projectRoot, packageManager);
return projectRoot;
}
export async function extractTemplateAppAsync(
templateSpec: PackageSpec,
targetPath: string,
config: AppJSONConfig | BareAppConfig
) {
let tarStream = await pacote.tarball.stream(templateSpec, {
cache: path.join(UserSettings.dotExpoHomeDirectory(), 'template-cache'),
});
await fs.mkdirp(targetPath);
await new Promise((resolve, reject) => {
const extractStream = tar.x({
cwd: targetPath,
strip: 1,
// TODO(ville): pending https://github.com/DefinitelyTyped/DefinitelyTyped/pull/36598
// @ts-ignore property missing from the type definition
transform: createFileTransform(config),
onentry(entry: ReadEntry) {
if (config.name) {
// Rewrite paths for bare workflow
entry.path = entry.path
.replace(/HelloWorld/g, config.name)
.replace(/helloworld/g, config.name.toLowerCase());
}
if (/^file$/i.test(entry.type) && path.basename(entry.path) === 'gitignore') {
// Rename `gitignore` because npm ignores files named `.gitignore` when publishing.
// See: https://github.com/npm/npm/issues/1862
entry.path = entry.path.replace(/gitignore$/, '.gitignore');
}
},
});
tarStream.on('error', reject);
extractStream.on('error', reject);
extractStream.on('close', resolve);
tarStream.pipe(extractStream);
});
return targetPath;
}
async function initGitRepoAsync(root: string) {
// let's see if we're in a git tree
let insideGit = true;
try {
await spawnAsync('git', ['rev-parse', '--is-inside-work-tree'], {
cwd: root,
});
Logger.global.debug('New project is already inside of a git repo, skipping git init.');
} catch (e) {
if (e.errno == 'ENOENT') {
Logger.global.warn('Unable to initialize git repo. `git` not in PATH.');
}
insideGit = false;
}
if (!insideGit) {
try {
await spawnAsync('git', ['init'], { cwd: root });
Logger.global.info('Initialized a git repository.');
} catch (e) {
// no-op -- this is just a convenience and we don't care if it fails
}
}
}
async function installDependenciesAsync(projectRoot: string, packageManager: 'yarn' | 'npm') {
Logger.global.info('Installing dependencies...');
if (packageManager === 'yarn') {
await spawnAsync('yarnpkg', ['install'], {
cwd: projectRoot,
stdio: 'inherit',
});
} else {
await spawnAsync('npm', ['install'], {
cwd: projectRoot,
stdio: 'inherit',
});
}
}
export async function saveRecentExpRootAsync(root: string) {
root = path.resolve(root);
// Write the recent Exps JSON file
const recentExpsJsonFile = UserSettings.recentExpsJsonFile();
let recentExps = await recentExpsJsonFile.readAsync();
// Filter out copies of this so we don't get dupes in this list
recentExps = recentExps.filter((dir: string) => dir !== root);
recentExps.unshift(root);
return await recentExpsJsonFile.writeAsync(recentExps.slice(0, 100));
}
type PublishInfo = {
args: {
username: string;
remoteUsername: string;
remotePackageName: string;
remoteFullPackageName: string;
sdkVersion: string;
iosBundleIdentifier?: string | null;
androidPackage?: string | null;
};
};
// TODO: remove / change, no longer publishInfo, this is just used for signing
export async function getPublishInfoAsync(root: string): Promise<PublishInfo> {
const user = await UserManager.ensureLoggedInAsync();
if (!user) {
throw new Error('Attempted to login in offline mode. This is a bug.');
}
let { username } = user;
const { exp } = await readConfigJsonAsync(root);
const name = exp.slug;
const { version, sdkVersion } = exp;
const configName = configFilename(root);
if (!sdkVersion) {
throw new Error(`sdkVersion is missing from ${configName}`);
}
if (!name) {
// slug is made programmatically for app.json
throw new Error(`slug field is missing from exp.json.`);
}
if (!version) {
throw new Error(`Can't get version of package.`);
}
const remotePackageName = name;
const remoteUsername = username;
const remoteFullPackageName = `@${remoteUsername}/${remotePackageName}`;
const iosBundleIdentifier = exp.ios ? exp.ios.bundleIdentifier : null;
const androidPackage = exp.android ? exp.android.package : null;
return {
args: {
username,
remoteUsername,
remotePackageName,
remoteFullPackageName,
sdkVersion,
iosBundleIdentifier,
androidPackage,
},
};
}
export async function sendAsync(recipient: string, url_: string, allowUnauthed: boolean = true) {
let result;
if (process.env.EXPO_NEXT_API) {
const user = await UserManager.ensureLoggedInAsync();
const api = ApiV2.clientForUser(user);
result = await api.postAsync('send-project', {
emailOrPhone: recipient,
url: url_,
includeExpoLinks: allowUnauthed,
});
} else {
result = await Api.callMethodAsync('send', [recipient, url_, allowUnauthed]);
}
return result;
}
// TODO: figure out where these functions should live
export async function getProjectRandomnessAsync(projectRoot: string) {
let ps = await ProjectSettings.readAsync(projectRoot);
let randomness = ps.urlRandomness;
if (randomness) {
return randomness;
} else {
return resetProjectRandomnessAsync(projectRoot);
}
}
export async function resetProjectRandomnessAsync(projectRoot: string) {
let randomness = UrlUtils.someRandomness();
ProjectSettings.setAsync(projectRoot, { urlRandomness: randomness });
return randomness;
}