Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

easProjectId.ts

257 lines11.3 KB

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Option from "effect/Option";
4import * as Path from "effect/Path";
5import * as Schema from "effect/Schema";
6​
7const CONFIG_FILES = [
8 "app.config.ts",
9 "app.config.mts",
10 "app.config.js",
11 "app.config.mjs",
12 "app.config.cjs",
13];
14const JSON_CONFIG_FILES = ["app.config.json", "app.json"];
15const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
16// A `projectId` whose whole value is one quoted string: the entry ends at the
17// quote, then after any space and comments a separator or the end of the
18// file; an operator may follow a line break or a comment. A comment is
19// matched whole (a line comment through its line break), so a separator
20// inside one cannot end the entry. An EAS project id is a UUID; another
21// service's (Firebase's, say) is not, and names no EAS project.
22const QUOTED_PROJECT_ID =
23 /\bprojectId["']?\s*:\s*["'`]([^"'`\n]*)["'`](?=(?:\s|\/\/[^\n\r\u2028\u2029]*(?:[\n\r\u2028\u2029]|$)|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:[,;})\]]|$))/gi;
24const PROJECT_ID_MENTION = /\bprojectId\b/gi;
25// Reading a config is linear in its size per entry; one this large is not an
26// app config but a file made to keep the server busy.
27const MAX_CONFIG_LENGTH = 256 * 1024;
28// Each entry is read against the rest of the file, so a file with many is
29// quadratic; an app config mentions its project a few times at most.
30const MAX_MENTIONS = 32;
31​
32// A spread after an entry may replace it from elsewhere: anywhere after it,
33// at any depth, since a spread in an enclosing object replaces the entry
34// too, and a comment or string could hide a brace from a scan of the
35// entry's own object. An assignment over the config may replace it from
36// anywhere: `Object.assign(defaults, overrides)` names the call before
37// both arguments.
38const SPREAD_LATER = /\.\.\./;
39// Space, a comment, or an opening parenthesis: what may sit between `...`
40// and the thing spread. Sticky, so the scan moves through the file once.
41const SPREAD_FILLER = /(?:\s+|\/\/[^\n\r\u2028\u2029]*|\/\*(?:[^*]|\*(?!\/))*\*\/|\()/y;
42// `config`'s `extra` and `extra.eas` entries, the holders of the EAS id
43// (dotted, optional-chained or in brackets).
44const EXTRA_OF_CONFIG = String.raw`config(?:\s*\??\.\s*extra|\s*(?:\?\.)?\s*\[\s*["'\x60]extra["'\x60]\s*\])`;
45const EAS_OF_CONFIG =
46 EXTRA_OF_CONFIG + String.raw`(?:\s*\??\.\s*eas|\s*(?:\?\.)?\s*\[\s*["'\x60]eas["'\x60]\s*\])`;
47// The holder, and nothing more of it: no further property, call or operator
48// (`?? {}` keeps it, so it may follow).
49const HOLDER_END = String.raw`(?![\p{ID_Continue}$\u200c\u200d\\]|\s*(?:[.\[(]|\?(?!\?)))`;
50const HOLDER_AT = {
51 extra: new RegExp(EXTRA_OF_CONFIG + HOLDER_END, "uy"),
52 eas: new RegExp(EAS_OF_CONFIG + HOLDER_END, "uy"),
53};
54// `config` and no more of it: not an identifier continuing (`$`, Unicode
55// letters and a `\u` escape do, where `\b` would not), nor a property.
56const CONFIG_AT = new RegExp("config" + HOLDER_END, "uy");
57​
58/**
59 * How a dynamic config with no EAS id of its own relates to app.json's:
60 * `spreads` when it spreads `config`, the one Expo hands it (app.json's
61 * entry carries through), and nothing else but `config`'s own `extra` or
62 * `extra.eas`, which keep the entry wherever they land; `replaces` when it
63 * spreads anything else (`config.extra.preview` too), which may replace
64 * that entry; `unclear` when it spreads nothing,
65 * since it may return `config` changed, or a config of its own that Expo
66 * uses alone. A `...` inside a comment after a spread is skipped with the
67 * comment, so the scan is linear.
68 */
69const staticConfigUse = (source: string): "spreads" | "replaces" | "unclear" => {
70 let spreads = 0;
71 let at = 0;
72 for (;;) {
73 const next = source.indexOf("...", at);
74 if (next === -1) return spreads > 0 ? "spreads" : "unclear";
75 at = next + 3;
76 for (;;) {
77 SPREAD_FILLER.lastIndex = at;
78 const filler = SPREAD_FILLER.exec(source);
79 if (!filler) break;
80 at += filler[0].length;
81 }
82 CONFIG_AT.lastIndex = at;
83 if (CONFIG_AT.test(source)) {
84 spreads++;
85 continue;
86 }
87 HOLDER_AT.extra.lastIndex = at;
88 HOLDER_AT.eas.lastIndex = at;
89 if (!HOLDER_AT.extra.test(source) && !HOLDER_AT.eas.test(source)) return "replaces";
90 }
91};
92const ASSIGNS_OVER = /\bObject\s*\.\s*assign\b|\bassign\s*\(/;
93// A config may replace the object holding the entry, or the whole config,
94// from somewhere this scan cannot read: an assignment to `.extra` or `.eas`,
95// (as a property or in brackets), a `delete` of anything, or another file it
96// requires or imports.
97const REPLACES_HOLDER =
98 /(?:\.\s*(?:extra|eas)|\[\s*["'`](?:extra|eas)["'`]\s*\])\s*=(?!=)|\bdelete\b|\brequire\s*\(|\bimport\s*\(/;
99// An `extra:` or `eas:` entry in a config that takes its id from app.json:
100// unless its value is an object that starts by spreading that same entry
101// of `config` (`config.extra`, `config.extra.eas`; spreading the whole
102// config there puts the id elsewhere), it replaces app.json's (`extra: {}`
103// drops the id). The key may be quoted
104// or computed; a shorthand `extra` or `eas` entry replaces it too. More
105// entries than mentions are allowed are not read.
106const EXTRA_OR_EAS = /(?:\b(extra|eas)|["'`](extra|eas)["'`]\s*\]?)\s*:\s*/g;
107const SHORTHAND_EXTRA_OR_EAS = /(?<![.\p{ID_Continue}$])(?:extra|eas)\s*(?=[,}])/u;
108const keepsStaticExtra = (source: string): boolean => {
109 if (SHORTHAND_EXTRA_OR_EAS.test(source)) return false;
110 let entries = 0;
111 for (const entry of source.matchAll(EXTRA_OR_EAS)) {
112 if (++entries > MAX_MENTIONS) return false;
113 const holder = HOLDER_AT[(entry[1] ?? entry[2]) as "extra" | "eas"];
114 let at = entry.index + entry[0].length;
115 if (source[at] !== "{") return false;
116 at++;
117 for (;;) {
118 SPREAD_FILLER.lastIndex = at;
119 const filler = SPREAD_FILLER.exec(source);
120 if (!filler) break;
121 at += filler[0].length;
122 }
123 if (!source.startsWith("...", at)) return false;
124 at += 3;
125 for (;;) {
126 SPREAD_FILLER.lastIndex = at;
127 const filler = SPREAD_FILLER.exec(source);
128 if (!filler) break;
129 at += filler[0].length;
130 }
131 holder.lastIndex = at;
132 if (!holder.test(source)) return false;
133 }
134 return true;
135};
136​
137const Extra = Schema.optional(
138 Schema.Struct({
139 eas: Schema.optional(Schema.Struct({ projectId: Schema.optional(Schema.String) })),
140 }),
141);
142// Expo reads a static config wrapped in `expo` or not, and as JSON5; one
143// this cannot decode (comments, say) still names a project, unknown here.
144const decodeAppJson = Schema.decodeUnknownOption(
145 Schema.fromJsonString(
146 Schema.Struct({ expo: Schema.optional(Schema.Struct({ extra: Extra })), extra: Extra }),
147 ),
148);
149​
150/**
151 * The project ids a directory's app config names. Read, never run: a dynamic
152 * config is the project's own code, which an agent may have written. Its text
153 * is taken as it is, comments included, so an old id left in a comment makes
154 * the answer ambiguous rather than wrong. app.config.json or app.json count
155 * too: a dynamic config may only replace theirs on some builds. Null when
156 * the project is unknown: the config sets or changes it some other way than
157 * a literal, or a config cannot be read.
158 */
159const projectIdsOf = Effect.fn("easProjectId.projectIdsOf")(function* (dir: string) {
160 const fs = yield* FileSystem.FileSystem;
161 const path = yield* Path.Path;
162 const ids: Array<string> = [];
163 const configFile = yield* Effect.findFirst(CONFIG_FILES, (file) =>
164 fs.exists(path.join(dir, file)).pipe(Effect.orElseSucceed(() => false)),
165 );
166 if (Option.isSome(configFile)) {
167 const source = yield* fs
168 .readFileString(path.join(dir, configFile.value))
169 .pipe(Effect.orElseSucceed(() => "projectId"));
170 // Every mention of `projectId` must be a quoted entry: one set from a
171 // variable, or assigned later, could be any project, and makes the
172 // answer unknown.
173 if (source.length > MAX_CONFIG_LENGTH) return null;
174 const mentions = source.match(PROJECT_ID_MENTION)?.length ?? 0;
175 if (mentions > MAX_MENTIONS) return null;
176 const entries = [...source.matchAll(QUOTED_PROJECT_ID)];
177 const quoted = entries.map((match) => match[1]!);
178 // A template that interpolates could be any project too, and so could
179 // one a spread after the entry, or an assignment anywhere, replaces;
180 if (
181 quoted.length !== mentions ||
182 quoted.some((id) => id.includes("${")) ||
183 ASSIGNS_OVER.test(source) ||
184 REPLACES_HOLDER.test(source) ||
185 entries.some((match) => SPREAD_LATER.test(source.slice(match.index + match[0].length)))
186 ) {
187 return null;
188 }
189 // Only a config shown to spread `config` and nothing else carries app.json's
190 // entry through unchanged; any other shape could use or replace it.
191 if (
192 !quoted.some((id) => UUID.test(id)) &&
193 (staticConfigUse(source) !== "spreads" || !keepsStaticExtra(source))
194 ) {
195 return null;
196 }
197 ids.push(...quoted.filter((id) => UUID.test(id)).map((id) => id.toLowerCase()));
198 }
199 for (const file of JSON_CONFIG_FILES) {
200 const json = yield* fs.readFileString(path.join(dir, file)).pipe(
201 Effect.map(Option.some),
202 Effect.catch((error) =>
203 Effect.succeed(error.reason._tag === "NotFound" ? Option.none<string>() : null),
204 ),
205 );
206 // A config that is there but cannot be read could name any project.
207 if (json === null) return null;
208 if (Option.isNone(json)) continue;
209 const decoded = decodeAppJson(json.value);
210 if (Option.isNone(decoded)) return null;
211 const id = (decoded.value.expo ?? decoded.value).extra?.eas?.projectId;
212 if (id !== undefined && UUID.test(id)) ids.push(id.toLowerCase());
213 // Expo reads only the first static config it finds.
214 break;
215 }
216 return ids;
217});
218​
219/**
220 * The EAS project of a workspace's Expo app: its root, or one app below
221 * `apps/` or `packages/`. None when there is none, a config is ambiguous, or
222 * the apps disagree, so the caller asks for an explicit choice instead of
223 * billing the wrong project.
224 */
225export const findEasProjectId = Effect.fn("easProjectId.findEasProjectId")(function* (
226 workspaceRoot: string,
227) {
228 const fs = yield* FileSystem.FileSystem;
229 const path = yield* Path.Path;
230 const isDirectory = (child: string) =>
231 fs.stat(child).pipe(
232 Effect.map((info) => info.type === "Directory"),
233 Effect.orElseSucceed(() => false),
234 );
235 // Only a directory can be an app; a README or .DS_Store beside them is not one.
236 const children = (parent: string) =>
237 fs.readDirectory(path.join(workspaceRoot, parent)).pipe(
238 Effect.map((names) => names.map((name) => path.join(workspaceRoot, parent, name))),
239 Effect.flatMap((paths) =>
240 Effect.forEach(paths, (child) =>
241 Effect.map(isDirectory(child), (directory) => (directory ? [child] : [])),
242 ),
243 ),
244 Effect.map((kept) => kept.flat()),
245 Effect.orElseSucceed(() => []),
246 );
247 const directories = [
248 workspaceRoot,
249 ...(yield* children("apps")),
250 ...(yield* children("packages")),
251 ];
252 const ids = yield* Effect.forEach(directories, projectIdsOf, { concurrency: 4 });
253 // An app whose project is unknown could be the one the thread works on.
254 if (ids.some((found) => found === null)) return Option.none<string>();
255 const distinct = new Set(ids.flatMap((found) => found ?? []));
256 return distinct.size === 1 ? Option.some([...distinct][0]!) : Option.none<string>();
257});