create-eigen-game 0.12.1 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,833 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { appendFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, relative, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ //#region src/engine-range.ts
6
+ /**
7
+ * Where the engine range emitted into a scaffolded project comes from.
8
+ *
9
+ * Its own module because the two branches below execute in different worlds,
10
+ * one only inside this repository and the other only inside a published tarball,
11
+ * and a function whose published-only path never runs in CI is a function that
12
+ * is not tested. `src/index.ts` uses it; the package `exports` map does not
13
+ * expose it, so it is internal despite being importable by the tests.
14
+ */
15
+ /** The dependency whose version the scaffolder emits into the generated server. */
16
+ const ENGINE_PACKAGE = "@eigeninteractive/server";
17
+ /**
18
+ * The engine range for a scaffolded project, from this package's own
19
+ * `@eigeninteractive/server` devDependency.
20
+ *
21
+ * That number is not maintained by anyone: it is the version CI compiled the
22
+ * templates against, because `pnpm -r typecheck` runs
23
+ * `tsc -p templates/worker/tsconfig.json` inside this workspace. Emitting
24
+ * anything else would mean shipping templates paired with an engine no build
25
+ * ever saw.
26
+ *
27
+ * It replaced a derivation from this package's OWN version, which was correct
28
+ * only while `create-eigen-game` sat in the `fixed` changesets group, and that
29
+ * membership is what forced an engine-wide release for every scaffolder-only
30
+ * change. Reading the dependency keeps the guarantee and drops the coupling.
31
+ *
32
+ * Two branches, because the same manifest reads differently in the two places
33
+ * this runs:
34
+ *
35
+ * - **Published tarball**: pnpm rewrites `workspace:*` to the exact version
36
+ * while packing, so the manifest already states it (`"0.2.0"`), and no
37
+ * sibling package exists on disk to consult.
38
+ * - **This workspace**: the manifest still says `workspace:*`, which names no
39
+ * version, so the sibling package is read directly.
40
+ *
41
+ * @param declared the raw `@eigeninteractive/server` devDependency value
42
+ * @param readSiblingVersion consulted only for the `workspace:` protocol
43
+ */
44
+ function engineRange(declared, readSiblingVersion) {
45
+ if (!declared) throw new Error(`create-eigen-game has no ${ENGINE_PACKAGE} devDependency, which is where the engine range it emits comes from`);
46
+ const version = declared.startsWith("workspace:") ? readSiblingVersion() : declared;
47
+ if (!version) throw new Error(`create-eigen-game declares ${ENGINE_PACKAGE} as "${declared}" but the workspace package could not be read, so there is no engine version to emit`);
48
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) throw new Error(`expected an exact ${ENGINE_PACKAGE} version to build a range from, got "${version}"`);
49
+ return `^${version}`;
50
+ }
51
+ //#endregion
52
+ //#region src/link-firebase.ts
53
+ /**
54
+ * Reads the two deployment values that exist only once a Firebase project
55
+ * does, so the closing summary can name what is still missing.
56
+ *
57
+ * Reading only. `configure_firebase` writes them, into `wrangler.jsonc` and
58
+ * `app-config.json`, because it is also what a project runs later when
59
+ * reconfiguring, and one implementation is what keeps the scaffold-time path
60
+ * and the re-run path identical. This module exists so the summary can tell
61
+ * the difference between "filled in" and "still owed", not to do it again.
62
+ *
63
+ * Its own module for the same reason `summary.ts` is: `index.ts` runs a
64
+ * scaffold, and this is worth asserting without one. The package `exports` map
65
+ * does not expose it.
66
+ */
67
+ function readJson(path) {
68
+ if (!existsSync(path)) return void 0;
69
+ try {
70
+ return JSON.parse(readFileSync(path, "utf8"));
71
+ } catch {
72
+ return;
73
+ }
74
+ }
75
+ /**
76
+ * The project FlutterFire recorded for the Dart output this app uses.
77
+ *
78
+ * `firebase.json` is FlutterFire's own record rather than something this
79
+ * scaffold writes, so it is read defensively: a shape that does not match is
80
+ * treated as "not configured", which is the same answer as a run that never
81
+ * happened.
82
+ */
83
+ function configuredProject(appRoot) {
84
+ const projectId = readJson(resolve(appRoot, "firebase.json"))?.flutter?.platforms?.dart?.["lib/firebase_options.dart"]?.projectId;
85
+ return typeof projectId === "string" && projectId !== "" ? projectId : null;
86
+ }
87
+ /**
88
+ * The OAuth web client id that `configure_firebase` copied into
89
+ * `app-config.json`, when there was one to copy.
90
+ *
91
+ * Empty is an ordinary outcome rather than a failure. Firebase creates that
92
+ * client when the Google sign-in provider is enabled, which is a console
93
+ * action no CLI can perform, so a project that has never had it enabled has
94
+ * nothing to offer here.
95
+ */
96
+ function configuredWebClientId(appRoot) {
97
+ const value = readJson(resolve(appRoot, "app-config.json"))?.GOOGLE_WEB_CLIENT_ID;
98
+ return typeof value === "string" && value !== "" ? value : null;
99
+ }
100
+ /** What the Firebase step settled, for the summary to report. */
101
+ function readFirebaseLink(root) {
102
+ const appRoot = resolve(root, "app");
103
+ return {
104
+ projectId: configuredProject(appRoot),
105
+ googleWebClientId: configuredWebClientId(appRoot)
106
+ };
107
+ }
108
+ //#endregion
109
+ //#region src/index.ts
110
+ /**
111
+ * Gives a terminal that reports no width the width clack would have assumed.
112
+ *
113
+ * A pty can report itself as a TTY and set `columns` to 0. `script` does, and
114
+ * so do some container terminals. clack falls back to 80 for a stream with no
115
+ * `columns` at all, but `0` is a number and satisfies that check, so the width
116
+ * it draws its rules from goes negative and a scaffold dies partway through
117
+ * with `RangeError: Invalid string length`. Supplying the default its check
118
+ * misses is better than giving up the drawing.
119
+ */
120
+ function normaliseTerminalWidth(stream) {
121
+ if (stream.isTTY === true && (stream.columns ?? 0) < 1) stream.columns = 80;
122
+ }
123
+ /** Runs every step plainly, which is what a library caller gets by default. */
124
+ const plainReporter = {
125
+ step: (_label, body) => body(),
126
+ handOver: (_label, body) => body(),
127
+ emit: (output) => process.stdout.write(output),
128
+ warn: (message) => console.warn(`create-eigen-game: ${message}`),
129
+ interactive: true
130
+ };
131
+ /**
132
+ * The runner a scaffold uses when the caller has not supplied one: it asks the
133
+ * reporter whether the terminal is spoken for.
134
+ *
135
+ * `interactive` inherits, which is the only way FlutterFire can put a question
136
+ * on screen and read the answer. Otherwise both streams are captured and
137
+ * handed to the reporter: on success so it can discard them, and on failure
138
+ * so the reason survives.
139
+ */
140
+ function capturingRunner(reporter) {
141
+ return (command, args, cwd) => {
142
+ if (reporter.interactive) {
143
+ execFileSync(command, args, {
144
+ cwd,
145
+ stdio: "inherit"
146
+ });
147
+ return;
148
+ }
149
+ try {
150
+ reporter.emit(execFileSync(command, args, {
151
+ cwd,
152
+ encoding: "utf8",
153
+ stdio: [
154
+ "ignore",
155
+ "pipe",
156
+ "pipe"
157
+ ]
158
+ }));
159
+ } catch (error) {
160
+ const { stdout, stderr } = error;
161
+ reporter.emit(`${stdout ?? ""}${stderr ?? ""}`);
162
+ throw error;
163
+ }
164
+ };
165
+ }
166
+ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
167
+ const templatesRoot = resolve(packageRoot, "templates");
168
+ /**
169
+ * The engine range emitted into a scaffolded project's package.json.
170
+ *
171
+ * Read from this package's `@eigeninteractive/server` devDependency rather than
172
+ * from its own version. See `engine-range.ts` for why that is the version the
173
+ * templates are known to compile against, and what it replaced.
174
+ */
175
+ const engineVersion = engineRange(JSON.parse(readFileSync(resolve(packageRoot, "package.json"), "utf8")).devDependencies?.[ENGINE_PACKAGE], () => {
176
+ const sibling = resolve(packageRoot, "../server/package.json");
177
+ return existsSync(sibling) ? JSON.parse(readFileSync(sibling, "utf8")).version : void 0;
178
+ });
179
+ /**
180
+ * The Flutter client range installed into the app half.
181
+ *
182
+ * A stated version, not a derived or resolved one. The Dart templates import
183
+ * `package:eigen_flutter/eigen_flutter.dart` and
184
+ * `package:eigen_flutter/testing/twin_fixtures.dart` and are written against a
185
+ * specific Dart API. `eigen_flutter` is published and versioned separately from
186
+ * this package even though both now live in the platform monorepo, so a source
187
+ * location cannot compute which released version the template should request.
188
+ * Only compiling a scaffolded app establishes it, which the platform gate does
189
+ * on every change.
190
+ *
191
+ * This briefly resolved from pub.dev instead: "the newest `eigen_flutter` whose
192
+ * own `eigen_api` constraint targets the engine line being scaffolded". That
193
+ * predicate is wrong. The `eigen_api` constraint describes the WIRE the shell
194
+ * speaks, not the Dart API these templates call, and the two move
195
+ * independently: a future `eigen_flutter` may legitimately keep `eigen_api:
196
+ * ^0.2.0` while renaming everything the templates touch. It would have been
197
+ * selected, and the generated app would not compile.
198
+ *
199
+ * A caret RANGE rather than an exact version, so it still improves without a
200
+ * republish: `flutter pub add eigen_flutter@^0.4.0` already picks the newest
201
+ * 0.4.x at scaffold time, which is the part the pub.dev lookup was duplicating.
202
+ * What it deliberately cannot do is cross to 0.5.x, the one move that needs a
203
+ * human to confirm the templates still compile.
204
+ *
205
+ * Staleness is therefore a failing check rather than a broken scaffold: this is
206
+ * only ever a release behind, never wrong.
207
+ *
208
+ * Raised to 0.4.0 with the engine's session-snapshot wire. This is the one kind
209
+ * of bump that is not merely an improvement: a scaffold writes both halves, and
210
+ * the worker half is this repository's own line, so the shell it installs has to
211
+ * speak that line's socket. `eigen_flutter` 0.4.0 is the first that does, and
212
+ * every 0.3.x pins `eigen_api: ^0.2.0`, which cannot read a 0.3.x engine at all.
213
+ * A scaffold pinning 0.3.x would therefore resolve, compile, and then fail to
214
+ * render a game, which is the worst of the three.
215
+ *
216
+ * Raised to 0.4.1 for `EngineConfig.authDomain`, which the generated
217
+ * `main.dart` passes. Additive, so pre-1.0 it is a patch and `^0.4.0` would
218
+ * still resolve it, but `^0.4.0` also still resolves 0.4.0, where the parameter
219
+ * does not exist and the scaffold would not compile. The floor is what makes
220
+ * the generated code and the installed shell agree.
221
+ *
222
+ * Raised to 0.6.0 with the engine's opaque pagination cursors, and this is the
223
+ * same *required* kind of bump the 0.4.0 note describes rather than an
224
+ * improvement. The 0.4.x engine line takes `cursor` as an opaque string and
225
+ * returns `nextCursor` on every paged response; `eigen_flutter` 0.6.0 is the
226
+ * first shell that pins `eigen_api: ^0.4.0` and can read it. Everything below
227
+ * that pins `eigen_api: ^0.3.0` or older, so a scaffold left on `^0.4.1` would
228
+ * install the engine's current line beside a shell that cannot read a single
229
+ * paged list from it: it resolves, it compiles, and then the lobby and history
230
+ * are empty. 0.5.0 is skipped for the same reason, being a web-design release
231
+ * that still speaks the 0.3.x wire.
232
+ *
233
+ * Raised to 0.7.0 for the 0.5.x engine line and the `PlayerLimits` client API.
234
+ * vNext later simplified the wire again: versions are a contiguous prefix and
235
+ * generic mutation identities are gone. The next Flutter release must raise
236
+ * this floor before the corresponding scaffolder is published.
237
+ *
238
+ * Note that this floor and the engine range are raised in one commit on
239
+ * purpose. The scaffolder writes both halves, and `updateInternalDependencies`
240
+ * republishes this package whenever the engine version moves, so between an
241
+ * engine line crossing and this line moving there is a published scaffolder
242
+ * that pairs a new worker with an old shell. That window is real and this is
243
+ * what closes it.
244
+ *
245
+ * The 0.7.0 raise is the exception that shows where that promise cannot hold. A
246
+ * floor names a *published* `eigen_flutter`, and `eigen_flutter` publishes at the
247
+ * end of the release chain, after the npm packages this scaffolder ships with --
248
+ * so at the moment the engine crossed to 0.5.x there was no 0.7.0 to point at,
249
+ * and `create-eigen-game@0.12.0` went out pairing a `^0.5.0` worker with a 0.6.0
250
+ * shell. A Flutter line move therefore costs a follow-up scaffolder patch, and
251
+ * `scripts/scaffold-e2e.mjs` is what refuses to let it be forgotten: it resolves
252
+ * both halves for real and compares the wire lines they land on.
253
+ */
254
+ const flutterClientVersion = "^0.8.0";
255
+ /** Optional Firebase adapter installed by the standard app scaffold. */
256
+ const firebaseAdapterVersion = "^0.1.0";
257
+ /** Development-only contract compiler installed into the generated app. */
258
+ const dartCodegenVersion = "^0.1.0";
259
+ const gameSlug = (value) => {
260
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value)) throw new Error("destination directory name must be a lowercase kebab-case slug, for example my-game");
261
+ return value;
262
+ };
263
+ const dartName = (value) => value.replaceAll("-", "_");
264
+ /**
265
+ * The Android `applicationId`, and iOS bundle id, a scaffold at `directory`
266
+ * will produce, so the CLI can show it rather than describe it.
267
+ *
268
+ * `flutter create --org X --project-name Y` derives `X.Y`. The organization is
269
+ * the *prefix*, not the whole identifier, which is the part worth seeing
270
+ * before answering: Google Play makes it permanent at first upload.
271
+ */
272
+ function applicationId(directory, org) {
273
+ return `${org?.trim() || "com.example"}.${dartName(gameSlug(basename(resolve(directory))))}`;
274
+ }
275
+ const title = (value) => value.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" ");
276
+ const identifier = (value) => {
277
+ const pascal = value.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join("");
278
+ return /^[0-9]/.test(pascal) ? `Game${pascal}` : pascal;
279
+ };
280
+ function detectPackageManager(userAgent = process.env.npm_config_user_agent) {
281
+ if (userAgent?.startsWith("pnpm/")) return "pnpm";
282
+ if (userAgent?.startsWith("npm/")) return "npm";
283
+ }
284
+ /**
285
+ * Substitutes the scaffold's tokens, of which there are two deliberate kinds.
286
+ *
287
+ * `{{BRACED}}` for values that have no valid example: a package manager,
288
+ * an engine version, an Android package id. They appear only in manifests,
289
+ * READMEs, workflows and the `Appfile`: files nothing compiles.
290
+ *
291
+ * Bare words (`ExampleGame`, `example-game`, …) for names a real example game
292
+ * genuinely has. This is what keeps `templates/worker` and the Dart templates
293
+ * VALID, COMPILING SOURCE rather than text with holes in it, which the rest of
294
+ * this package leans on hard: `typecheck` runs `tsc` over `templates/worker`,
295
+ * the tests `import` its game module directly and build a real contract from
296
+ * it, and the `scaffold` job compiles the Dart templates. Bracing these would
297
+ * trade all of that for a marker.
298
+ *
299
+ * The cost, and the one rule for template authors: a template file cannot
300
+ * contain the literal string `example-game`, `Example Game`, `ExampleGame` or
301
+ * `example_game` and keep it; every occurrence is rewritten, in prose and in
302
+ * code alike. Write around it, or brace a new token instead.
303
+ *
304
+ * Note this means the set of files carrying a token changes whenever someone
305
+ * writes one into an existing file. Nothing needs to track that: `renderTree`
306
+ * decides what to rewrite from the bytes, not from a list of paths.
307
+ */
308
+ function render(contents, name, manager, packageId) {
309
+ return [
310
+ ["@game/example-game-server", `@game/${name}-server`],
311
+ ["{{PACKAGE_MANAGER}}", manager],
312
+ ["{{PACKAGE_ID}}", packageId],
313
+ ["{{ENGINE_VERSION}}", engineVersion],
314
+ ["ExampleGame", identifier(name)],
315
+ ["Example Game", title(name)],
316
+ ["example_game", dartName(name)],
317
+ ["example-game", name]
318
+ ].reduce((result, [from, to]) => result.replaceAll(from, to), contents);
319
+ }
320
+ /**
321
+ * True when the bytes are valid UTF-8.
322
+ *
323
+ * This is not a guess at whether a file is "binary"; it is the precondition
324
+ * of the operation. Token substitution is `String.replaceAll`, so a file that
325
+ * cannot be decoded cannot take part, and one that can is safe to rewrite.
326
+ *
327
+ * Deliberately not an extension list. A DENY list (`.png`, `.jar`, …) fails
328
+ * silently in the dangerous direction: the day someone adds a `.webp`, it is
329
+ * corrupted with no error. An ALLOW list fails the safe way but fits this tree
330
+ * badly: `Gemfile`, `Fastfile`, `.nvmrc`, `.fvmrc` and `.ruby-version` all
331
+ * need rendering and none carry a usable extension, so it would have to be a
332
+ * list of extensions *and* a list of bare filenames, both drifting.
333
+ *
334
+ * `.template` is not the signal either, despite the name: it marks files a
335
+ * language server must not claim before they have an enclosing package. Five
336
+ * of them contain no token at all, and nine token-bearing files are not
337
+ * marked, so the two concepts are orthogonal here.
338
+ *
339
+ * `renderTree`'s test pins the resulting classification for the whole tree, so
340
+ * this stays a reviewed decision rather than an invisible one.
341
+ */
342
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
343
+ function decodeUtf8(bytes) {
344
+ try {
345
+ return utf8.decode(bytes);
346
+ } catch {
347
+ return;
348
+ }
349
+ }
350
+ function renderTree(source, destination, name, manager, packageId) {
351
+ cpSync(source, destination, { recursive: true });
352
+ const visit = (directory) => {
353
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
354
+ const templatePath = resolve(directory, entry.name);
355
+ if (entry.isDirectory()) {
356
+ visit(templatePath);
357
+ continue;
358
+ }
359
+ if (!entry.isFile()) continue;
360
+ const rendered = resolve(destination, relative(source, templatePath));
361
+ const text = decodeUtf8(readFileSync(templatePath));
362
+ if (text !== void 0) writeFileSync(rendered, render(text, name, manager, packageId));
363
+ if (entry.name.endsWith(".template")) renameSync(rendered, rendered.slice(0, -9));
364
+ }
365
+ };
366
+ visit(source);
367
+ const packagedGitignore = resolve(templatesRoot, "scaffold", `${basename(source)}.gitignore`);
368
+ if (existsSync(packagedGitignore)) writeFileSync(resolve(destination, ".gitignore"), render(readFileSync(packagedGitignore, "utf8"), name, manager, packageId));
369
+ }
370
+ function packageCommand(manager, operation) {
371
+ if (operation === "install") return [manager, ["install"]];
372
+ return [manager, ["run", operation]];
373
+ }
374
+ /**
375
+ * Appends `block` to a file this scaffolder does not own, as its own paragraph.
376
+ *
377
+ * **Append, never insert.** That is the rule the three callers below follow, and
378
+ * it is what keeps them from competing with `flutter create` and `flutterfire
379
+ * configure` for position in the same files. A pure append cannot collide with
380
+ * whatever those tools write above it; the one edit here that ever needed a
381
+ * position, prepending a Kotlin `import`, was broken by an AGP upgrade and has
382
+ * since been rewritten away. See MAINTAINERS.md for the whole doctrine, including
383
+ * why FlutterFire's `// START:`/`// END:` marker comments are deliberately not
384
+ * copied.
385
+ *
386
+ * `contents` is passed in rather than read here because every caller has already
387
+ * read the file to decide whether its block is present, and two of them assert
388
+ * on the shape of what they found. This owns the whitespace and nothing else.
389
+ *
390
+ * That is worth one function because it was previously written three times with
391
+ * two different answers, so the desugaring block got a blank line before it and
392
+ * the other two did not, and the two Gradle blocks ended up flush against each
393
+ * other in every generated project. Separation belongs to the append, so the
394
+ * block constants carry no leading or trailing newline of their own.
395
+ */
396
+ function appendBlock(path, contents, block) {
397
+ appendFileSync(path, `${contents.endsWith("\n") ? "" : "\n"}\n${block}\n`);
398
+ }
399
+ const androidDesugaring = `// flutter_local_notifications requires desugaring in the application module.
400
+ // A library plugin cannot enable this compiler setting transitively.
401
+ android {
402
+ compileOptions {
403
+ isCoreLibraryDesugaringEnabled = true
404
+ }
405
+ }
406
+
407
+ dependencies {
408
+ coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
409
+ }`;
410
+ function enableAndroidCoreLibraryDesugaring(appRoot) {
411
+ const gradlePath = resolve(appRoot, "android/app/build.gradle.kts");
412
+ const gradle = readFileSync(gradlePath, "utf8");
413
+ if (!gradle.includes("id(\"com.android.application\")")) throw new Error(`Flutter created an unexpected Android application build file: ${gradlePath}`);
414
+ const settingExists = gradle.includes("isCoreLibraryDesugaringEnabled");
415
+ const dependencyExists = gradle.includes("coreLibraryDesugaring(");
416
+ if (settingExists && dependencyExists) return;
417
+ if (settingExists || dependencyExists) throw new Error(`Flutter created an incomplete Android core library desugaring configuration: ${gradlePath}`);
418
+ appendBlock(gradlePath, gradle, androidDesugaring);
419
+ }
420
+ const androidReleaseSigning = `val releaseKeyProperties: Map<String, String> =
421
+ rootProject.file("key.properties")
422
+ .takeIf { it.exists() }
423
+ ?.readLines()
424
+ ?.map { it.trim() }
425
+ ?.filter { it.isNotEmpty() && !it.startsWith("#") && it.contains("=") }
426
+ ?.associate { it.substringBefore("=").trim() to it.substringAfter("=").trim() }
427
+ .orEmpty()
428
+
429
+ android {
430
+ signingConfigs {
431
+ create("release") {
432
+ storeFile = releaseKeyProperties["storeFile"]?.let { file(it) }
433
+ storePassword = releaseKeyProperties["storePassword"]
434
+ keyAlias = releaseKeyProperties["keyAlias"]
435
+ keyPassword = releaseKeyProperties["keyPassword"]
436
+ }
437
+ }
438
+ buildTypes {
439
+ release {
440
+ signingConfig = if (releaseKeyProperties["storeFile"] != null)
441
+ signingConfigs.getByName("release")
442
+ else
443
+ signingConfigs.getByName("debug")
444
+ isMinifyEnabled = true
445
+ isShrinkResources = true
446
+ proguardFiles(
447
+ getDefaultProguardFile("proguard-android-optimize.txt"),
448
+ "proguard-rules.pro",
449
+ )
450
+ }
451
+ }
452
+ }`;
453
+ function enableAndroidReleaseSigning(appRoot) {
454
+ const gradlePath = resolve(appRoot, "android/app/build.gradle.kts");
455
+ const gradle = readFileSync(gradlePath, "utf8");
456
+ if (gradle.includes("releaseKeyProperties")) return;
457
+ appendBlock(gradlePath, gradle, androidReleaseSigning);
458
+ }
459
+ const launcherIconsAndSplashConfig = `flutter_launcher_icons:
460
+ android: true
461
+ web:
462
+ generate: true
463
+ image_path: "assets/icon/icon.png"
464
+ image_path: "assets/icon/icon.png"
465
+ adaptive_icon_background: "#1B1E24"
466
+ adaptive_icon_foreground: "assets/icon/icon_foreground.png"
467
+ min_sdk_android: 21
468
+
469
+ flutter_native_splash:
470
+ color: "#F4F1EA"
471
+ color_dark: "#1B1E24"
472
+ image: assets/icon/splash.png
473
+ image_dark: assets/icon/splash_dark.png
474
+ fullscreen: true
475
+ android_12:
476
+ color: "#F4F1EA"
477
+ color_dark: "#1B1E24"
478
+ image: assets/icon/splash.png
479
+ image_dark: assets/icon/splash_dark.png
480
+ icon_background_color: "#F4F1EA"
481
+ icon_background_color_dark: "#1B1E24"
482
+ web: true`;
483
+ function configureLauncherIconsAndSplash(appRoot) {
484
+ const pubspecPath = resolve(appRoot, "pubspec.yaml");
485
+ const pubspec = readFileSync(pubspecPath, "utf8");
486
+ if (pubspec.includes("flutter_launcher_icons:")) return;
487
+ appendBlock(pubspecPath, pubspec, launcherIconsAndSplashConfig);
488
+ }
489
+ /**
490
+ * Adds the GitHub Actions workflows to an existing generated project.
491
+ *
492
+ * The companion to `ci: false`: a game can be built and played locally for as
493
+ * long as its author likes, then gain the same PR gate and signed release
494
+ * pipeline a `--ci` scaffold would have produced.
495
+ */
496
+ function addContinuousIntegration(options) {
497
+ const root = resolve(options.directory);
498
+ const manifestPath = resolve(root, "package.json");
499
+ if (!existsSync(manifestPath) || !existsSync(resolve(root, "server")) || !existsSync(resolve(root, "app"))) throw new Error(`not an EigenInteractive game project (expected package.json, server/ and app/): ${root}`);
500
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
501
+ const name = gameSlug(manifest.name ?? basename(root));
502
+ const recorded = manifest.scripts?.contract?.includes("pnpm ") ? "pnpm" : manifest.scripts?.contract?.includes("npm ") ? "npm" : void 0;
503
+ const manager = options.packageManager ?? recorded ?? detectPackageManager() ?? "pnpm";
504
+ const appfile = resolve(root, "app/fastlane/Appfile");
505
+ const packageId = existsSync(appfile) ? /package_name\("([^"]+)"\)/.exec(readFileSync(appfile, "utf8"))?.[1] ?? `com.example.${dartName(name)}` : `com.example.${dartName(name)}`;
506
+ const workflows = resolve(root, ".github/workflows");
507
+ const existing = existsSync(workflows) ? readdirSync(workflows).filter((f) => f === "checks.yml" || f === "release.yml") : [];
508
+ if (existing.length > 0) throw new Error(`refusing to overwrite existing workflows: ${existing.join(", ")}`);
509
+ renderTree(resolve(templatesRoot, "ci"), root, name, manager, packageId);
510
+ return {
511
+ root,
512
+ files: [".github/workflows/checks.yml", ".github/workflows/release.yml"]
513
+ };
514
+ }
515
+ const probeCommand = (command, args) => {
516
+ try {
517
+ return {
518
+ ok: true,
519
+ stdout: execFileSync(command, args, {
520
+ encoding: "utf8",
521
+ stdio: [
522
+ "ignore",
523
+ "pipe",
524
+ "ignore"
525
+ ]
526
+ })
527
+ };
528
+ } catch {
529
+ return {
530
+ ok: false,
531
+ stdout: ""
532
+ };
533
+ }
534
+ };
535
+ /**
536
+ * Whether this machine can configure Firebase, asked *before* the scaffold
537
+ * rather than after it.
538
+ *
539
+ * `configure_firebase` runs the same three checks and is the authority on
540
+ * them; this one exists only to move the answer earlier. Learning that
541
+ * `flutterfire` is missing costs nothing here and costs two minutes of Flutter
542
+ * and pub at the far end, which is where the step actually runs.
543
+ *
544
+ * Every problem, not the first one. The checks are independent (two CLIs from
545
+ * two ecosystems, plus a sign-in) so short-circuiting turns one setup into a
546
+ * sequence of runs that each reveal the next missing piece. Reported in the
547
+ * order they have to be fixed in: the CLI, then the sign-in it stores, then
548
+ * the bridge that consumes both.
549
+ *
550
+ * The sign-in check fails open, for the same reason it does there: only an
551
+ * answer that positively reports no accounts counts as "no", so a `firebase`
552
+ * that errors or grows a different output shape is left to the command that
553
+ * actually needs the credentials.
554
+ */
555
+ function firebaseReadiness(probe = probeCommand) {
556
+ const problems = [];
557
+ if (probe("firebase", ["--version"]).ok) {
558
+ if (signedOut(probe)) problems.push({
559
+ reason: "no Google account is signed in to the Firebase CLI",
560
+ fix: "firebase login"
561
+ });
562
+ } else problems.push({
563
+ reason: "the `firebase` CLI is not installed",
564
+ fix: "curl -sL https://firebase.tools | bash"
565
+ });
566
+ if (!probe("flutterfire", ["--version"]).ok) problems.push({
567
+ reason: "the `flutterfire` CLI is not installed",
568
+ fix: "dart pub global activate flutterfire_cli"
569
+ });
570
+ return problems.length === 0 ? { ready: true } : {
571
+ ready: false,
572
+ problems
573
+ };
574
+ }
575
+ /**
576
+ * Whether the Firebase CLI holds no credentials.
577
+ *
578
+ * `login:list --json` prints the stored refresh and access tokens along with
579
+ * the account list. Read the shape, count the entries, and never surface the
580
+ * output: not in a warning, not in a captured stream, not on the failure
581
+ * path. That is why this returns a boolean rather than the response.
582
+ */
583
+ function signedOut(probe) {
584
+ const accounts = probe("firebase", ["login:list", "--json"]);
585
+ if (!accounts.ok) return false;
586
+ try {
587
+ const { result } = JSON.parse(accounts.stdout);
588
+ return Array.isArray(result) && result.length === 0;
589
+ } catch {
590
+ return false;
591
+ }
592
+ }
593
+ /**
594
+ * Whether the scaffold would land inside a repository that already exists.
595
+ *
596
+ * Asked of the nearest ancestor that exists, because the destination does not
597
+ * yet. The point is not to change what {@link scaffoldGame} does, which already
598
+ * declines to nest a repository, but to stop the CLI asking a question whose
599
+ * answer cannot matter.
600
+ */
601
+ /**
602
+ * Why this destination cannot be scaffolded into, said as a whole message, or
603
+ * `undefined` when there is nothing in the way.
604
+ *
605
+ * A directory that exists and is *empty* is not in the way, since people make
606
+ * one out of habit, so it is removed and rewritten rather than refused over
607
+ * nothing. Anything with contents in it is refused, and a cloned repository is
608
+ * not an exception: `.git` is in the way like any other entry, and the message
609
+ * names it. Publishing into one would mean parking `.git`, renaming staging
610
+ * over the top and putting it back, with a failure in the middle able to
611
+ * orphan a remote, which is a lot of care to spend on a flow that has a
612
+ * one-line alternative.
613
+ *
614
+ * Refused, and deliberately not offered as a "remove it and continue?"
615
+ * question, which is where several scaffolders in this family go. This one
616
+ * writes ninety-odd files and runs `flutter create`; the cost of getting that
617
+ * answer wrong against a mistyped path has no upper bound, and `rm -rf` is one
618
+ * command that belongs to the person who can see what is in there. Every other
619
+ * question this CLI asks is reversible. This one would not be.
620
+ *
621
+ * Exported so the CLI can ask it before the first question rather than after
622
+ * the last one. {@link scaffoldGame} asks it again, for callers that are not
623
+ * the CLI.
624
+ */
625
+ function destinationProblem(directory) {
626
+ const root = resolve(directory);
627
+ if (!existsSync(root)) return void 0;
628
+ if (!statSync(root).isDirectory()) return `${root} already exists, and is a file.`;
629
+ const entries = readdirSync(root);
630
+ if (entries.length === 0) return void 0;
631
+ return `${root} already exists, and is not empty: it holds ${entries.slice(0, 3).sort().join(", ")}${entries.length > 3 ? `, and ${entries.length - 3} more` : ""}.\n\nScaffold somewhere else, or clear it out yourself. This will not delete a directory you already had.`;
632
+ }
633
+ function insideWorkTree(directory, probe = probeCommand) {
634
+ let candidate = resolve(directory);
635
+ while (!existsSync(candidate)) {
636
+ const parent = dirname(candidate);
637
+ if (parent === candidate) return false;
638
+ candidate = parent;
639
+ }
640
+ return probe("git", [
641
+ "-C",
642
+ candidate,
643
+ "rev-parse",
644
+ "--is-inside-work-tree"
645
+ ]).ok;
646
+ }
647
+ /**
648
+ * Runs the Flutter client's `configure_firebase` against the generated app.
649
+ *
650
+ * The command owns everything about how Firebase is configured: which
651
+ * platforms, which CLIs must exist, whether anyone is signed in, and what to
652
+ * do when no project has been chosen yet. This only decides *when*: before the
653
+ * scaffold commit, so a configured project is committed configured.
654
+ *
655
+ * Not fatal. Every failure here (a missing `flutterfire`, no Google login, a
656
+ * cancelled picker) leaves a complete and usable project that is exactly what
657
+ * a scaffold without `--firebase` produces, so it warns with the command to
658
+ * re-run and lets the commit happen.
659
+ */
660
+ function configureFirebase(appRoot, project, run, reporter) {
661
+ const placeholder = resolve(appRoot, "lib/firebase_options.dart");
662
+ const parked = `${placeholder}.placeholder`;
663
+ const parking = existsSync(placeholder);
664
+ if (parking) renameSync(placeholder, parked);
665
+ try {
666
+ reporter.step("Preparing the Firebase configurator", () => run("dart", [
667
+ "run",
668
+ "eigen_firebase:configure_firebase",
669
+ "--help"
670
+ ], appRoot));
671
+ reporter.handOver("Configuring Firebase", () => run("dart", [
672
+ "run",
673
+ "eigen_firebase:configure_firebase",
674
+ "--worker",
675
+ "../server",
676
+ ...typeof project === "string" ? ["--project", project] : []
677
+ ], appRoot));
678
+ if (parking) rmSync(parked, { force: true });
679
+ return "configured";
680
+ } catch {
681
+ if (parking) {
682
+ if (existsSync(placeholder)) rmSync(parked, { force: true });
683
+ else renameSync(parked, placeholder);
684
+ }
685
+ reporter.warn("Could not configure Firebase. The project is complete. Run `firebase:configure` yourself, then commit what it writes.");
686
+ return "failed";
687
+ }
688
+ }
689
+ /**
690
+ * Commits the scaffold, so the first `git diff` is the first game change.
691
+ *
692
+ * This matters more here than in a scaffolder that only writes source. The
693
+ * bootstrap runs `flutter_launcher_icons` and `flutter_native_splash`, which
694
+ * write generated-but-committed files across `android/`, `web/` and
695
+ * `assets/`; without a baseline the first branding change is indistinguishable
696
+ * from the ninety files the scaffolder happened to produce.
697
+ *
698
+ * Nothing here is fatal. The project is complete and valid before this runs,
699
+ * so a missing `git`, or the unconfigured `user.email` that a fresh CI image
700
+ * has, warns and leaves the tree alone rather than discarding a scaffold that
701
+ * took two minutes of Flutter and pub to produce.
702
+ */
703
+ function initialiseRepository(root, name, run, reporter) {
704
+ try {
705
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
706
+ cwd: root,
707
+ stdio: "ignore"
708
+ });
709
+ return "existing";
710
+ } catch {}
711
+ try {
712
+ run("git", ["init", "--quiet"], root);
713
+ run("git", ["add", "--all"], root);
714
+ } catch {
715
+ reporter.warn("Could not initialise a git repository. The project is complete. Run `git init` yourself when ready.");
716
+ return "failed";
717
+ }
718
+ try {
719
+ run("git", [
720
+ "commit",
721
+ "--quiet",
722
+ "--message",
723
+ `Scaffold ${name}`
724
+ ], root);
725
+ } catch {
726
+ reporter.warn(`Initialised a repository and staged the scaffold, but could not commit it. Set \`user.name\` and \`user.email\`, then \`git commit -m "Scaffold ${name}"\`.`);
727
+ return "failed";
728
+ }
729
+ return "committed";
730
+ }
731
+ function scaffoldGame(options) {
732
+ const root = resolve(options.directory);
733
+ const name = gameSlug(basename(root));
734
+ const manager = options.packageManager ?? detectPackageManager() ?? "pnpm";
735
+ const org = options.org?.trim() || "com.example";
736
+ const packageId = applicationId(root, org);
737
+ const bootstrap = options.bootstrap ?? true;
738
+ const reporter = options.reporter ?? plainReporter;
739
+ const run = options.run ?? capturingRunner(reporter);
740
+ const occupied = destinationProblem(root);
741
+ if (occupied !== void 0) throw new Error(occupied);
742
+ if (existsSync(root)) rmdirSync(root);
743
+ mkdirSync(dirname(root), { recursive: true });
744
+ const stagingRoot = mkdtempSync(resolve(dirname(root), `.${basename(root)}-`));
745
+ try {
746
+ const serverRoot = resolve(stagingRoot, "server");
747
+ const appRoot = resolve(stagingRoot, "app");
748
+ renderTree(resolve(templatesRoot, "worker"), serverRoot, name, manager, packageId);
749
+ renderTree(resolve(templatesRoot, "project"), stagingRoot, name, manager, packageId);
750
+ if (options.ci) renderTree(resolve(templatesRoot, "ci"), stagingRoot, name, manager, packageId);
751
+ if (bootstrap) reporter.step("Creating the Flutter app", () => {
752
+ run("flutter", [
753
+ "create",
754
+ "--empty",
755
+ "--platforms",
756
+ "android,web",
757
+ "--project-name",
758
+ dartName(name),
759
+ "--org",
760
+ org,
761
+ appRoot
762
+ ], stagingRoot);
763
+ enableAndroidCoreLibraryDesugaring(appRoot);
764
+ enableAndroidReleaseSigning(appRoot);
765
+ });
766
+ else mkdirSync(appRoot, { recursive: true });
767
+ renderTree(resolve(templatesRoot, "app-overlay"), appRoot, name, manager, packageId);
768
+ if (bootstrap) {
769
+ reporter.step("Adding the Flutter packages", () => {
770
+ configureLauncherIconsAndSplash(appRoot);
771
+ run("flutter", [
772
+ "pub",
773
+ "add",
774
+ `eigen_flutter@${flutterClientVersion}`,
775
+ `eigen_firebase@${firebaseAdapterVersion}`,
776
+ "firebase_core@^4.9.0"
777
+ ], appRoot);
778
+ run("flutter", [
779
+ "pub",
780
+ "add",
781
+ `dev:eigen_codegen@${dartCodegenVersion}`,
782
+ "dev:flutter_launcher_icons",
783
+ "dev:flutter_native_splash"
784
+ ], appRoot);
785
+ });
786
+ reporter.step("Generating the icons and splash", () => {
787
+ run("dart", ["run", "flutter_launcher_icons"], appRoot);
788
+ run("dart", ["run", "flutter_native_splash:create"], appRoot);
789
+ });
790
+ const [install, installArgs] = packageCommand(manager, "install");
791
+ const [typegen, typegenArgs] = packageCommand(manager, "cf-typegen");
792
+ reporter.step("Installing the Worker packages", () => {
793
+ run(install, installArgs, serverRoot);
794
+ run(typegen, typegenArgs, serverRoot);
795
+ run(install, installArgs, stagingRoot);
796
+ });
797
+ const [contract, contractArgs] = packageCommand(manager, "contract");
798
+ reporter.step("Generating the contract and payloads", () => {
799
+ run(contract, contractArgs, serverRoot);
800
+ run("dart", [
801
+ "run",
802
+ "eigen_codegen:generate_payloads",
803
+ "--contract",
804
+ "../server/game-contract.json",
805
+ "--output",
806
+ "lib/game/generated/payloads.dart",
807
+ "--fixtures-output",
808
+ "test/fixtures"
809
+ ], appRoot);
810
+ });
811
+ }
812
+ renameSync(stagingRoot, root);
813
+ } catch (error) {
814
+ rmSync(stagingRoot, {
815
+ recursive: true,
816
+ force: true
817
+ });
818
+ throw error;
819
+ }
820
+ const firebase = options.firebase ? configureFirebase(resolve(root, "app"), options.firebase, run, reporter) : "skipped";
821
+ const link = firebase === "configured" ? readFirebaseLink(root) : void 0;
822
+ return {
823
+ root,
824
+ name,
825
+ git: options.git ?? bootstrap ? initialiseRepository(root, name, run, reporter) : "skipped",
826
+ firebase,
827
+ link
828
+ };
829
+ }
830
+ //#endregion
831
+ export { destinationProblem as a, insideWorkTree as c, scaffoldGame as d, decodeUtf8 as i, normaliseTerminalWidth as l, applicationId as n, detectPackageManager as o, capturingRunner as r, firebaseReadiness as s, addContinuousIntegration as t, plainReporter as u };
832
+
833
+ //# sourceMappingURL=src-q9BxESYC.js.map