Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .changeset/android-starter.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
"clerk": minor
---

`clerk init --starter` now creates an Android app: "Android (Jetpack Compose)" in the picker, or `--framework android` with `--name` and `--android-package`. It writes a project shaped like Android Studio's Empty Activity template (AGP 9.2.1, Kotlin 2.3.21, a Compose BOM, `minSdk` 24, an initial Git commit, and the embedded Gradle 9.4.1 wrapper), then runs the Android setup on it with the UI artifact by default, and with `--prebuilt-auth-ui` (or a yes to the prompt) replaces `MainActivity` with Clerk's prebuilt sign-in screen. `--json` reports `input-required`, `application-required`, and `setup-interrupted` with the new app's continuation, as for the Apple starters.
Add an Android (Jetpack Compose) starter to `clerk init --starter`, also selected with `--framework android`, that creates a new Android app, sets up Clerk in it, and adds Clerk's prebuilt sign-in screen with `--prebuilt-auth-ui`.
2 changes: 1 addition & 1 deletion packages/cli-core/src/commands/init/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ Express and Fastify share the server-entry scaffolding in [`node-server.ts`](./f

Once init has linked a Clerk application (the usual authenticated flow), it sets up the Gradle application module directly instead of scaffolding files or pulling keys into `.env`. It works on any OS: inspection reads Gradle scripts, the version catalog, and the manifest as text, never running Gradle, and the only tool it runs is `keytool`, to read the debug certificate. The engine lives in [`android/`](./android/) and mirrors the iOS one module for module (discovery, project inspection, plan, SDK, identity, remote, workflow, coordinator, handoff, doctor); what the two share (resolving the instance, idempotent registration, file snapshots, backups, and rollback, progress) lives in [`native/`](./native/).

- **New apps.** `clerk init --starter` offers Android (Jetpack Compose) everywhere, alongside the web frameworks and, on a Mac with Xcode, the Apple starters; `--framework android` selects it. It asks for the app name (an identifier such as `MyApp`) and the applicationId (default `com.example.<lowercased name>`), then writes a project shaped like Android Studio's Empty Activity template before signing in or choosing a Clerk application: `settings.gradle.kts`, the root build script, `gradle.properties`, a version catalog pinning AGP 9.2.1, Kotlin 2.3.21 (through the Compose compiler plugin alias, so AGP's built-in Kotlin isn't the 2.2.10 the SDK can't be consumed by), and a Compose BOM; `app/` with `minSdk` 24, the manifest, `MainActivity`, the theme, and a vector launcher icon; `.gitignore` and an initial Git commit (unless the folder is already inside a repository); and the Gradle wrapper. The wrapper's `gradlew`, `gradlew.bat`, and `gradle-wrapper.jar` (Gradle 9.4.1) are embedded in the CLI and copied in, with the distribution's checksum pinned in `gradle-wrapper.properties`, so the new project builds with `./gradlew :app:assembleDebug` without Gradle on PATH; the Android SDK and a JDK 17+ are still needed to build. Setup then runs as for an existing project, with no confirmation prompt and the UI artifact by default. The new app has no screens of its own, so its sign-in screen defaults to on, with `--yes` as at the prompt, unless `--android-sdk core` is chosen; an agent still adds it only with `--prebuilt-auth-ui`. `--android-module` and the accountless flags are rejected before anything is written. When an agent hasn't chosen a Clerk application yet, it's told to run `cd <app> && clerk init --app <app_id> --json`, carrying this run's Android options.
- **New apps.** `clerk init --starter` offers Android (Jetpack Compose) everywhere, alongside the web frameworks and, on a Mac with Xcode, the Apple starters; `--framework android` selects it, as does `--android-package` on its own. It asks for the app name (an identifier such as `MyApp`) and the applicationId (default `com.example.<lowercased name>`), refusing a Kotlin or Java keyword as the name or as an applicationId segment because the applicationId is also the Kotlin package and the namespace, then writes a project shaped like Android Studio's Empty Activity template before signing in or choosing a Clerk application: `settings.gradle.kts`, the root build script, `gradle.properties`, a version catalog pinning AGP 9.2.1, Kotlin 2.3.21 (through the Compose compiler plugin alias, so AGP's built-in Kotlin isn't the 2.2.10 the SDK can't be consumed by), and a Compose BOM; `app/` with `minSdk` 24, the manifest, `MainActivity`, the theme, and a vector launcher icon; `.gitignore` and an initial Git commit (unless the folder is already inside a repository; when Git can't make the commit, with no `user.name` and `user.email` for example, init warns and leaves the files staged); and the Gradle wrapper. The wrapper's `gradlew`, `gradlew.bat`, and `gradle-wrapper.jar` (Gradle 9.4.1) are embedded in the CLI and copied in, with the distribution's checksum pinned in `gradle-wrapper.properties`, so the new project builds with `./gradlew :app:assembleDebug` without Gradle on PATH; the Android SDK and a JDK 17+ are still needed to build. Setup then runs as for an existing project, with no confirmation prompt and the UI artifact by default. The new app has no screens of its own, so its sign-in screen defaults to on, with `--yes` as at the prompt, unless `--android-sdk core` is chosen; an agent still adds it only with `--prebuilt-auth-ui`. `--android-module` and the accountless flags are rejected before anything is written. When an agent hasn't chosen a Clerk application yet, it's told to run `cd <app> && clerk init --app <app_id> --json`, carrying this run's Android options.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small one: any Android flag selects the starter, not just --android-package (clerk init --starter --android-sdk ui picks Android too, via frameworkOverride). Maybe "as does any Android flag on its own, such as --android-package"?

- **New apps with `--json`.** `clerk init --starter --framework android --json` reports like the Apple starters: `--name` is required, an answer only the user can give stops before anything is written with `input-required` (`field` is `name` or `androidPackage`, with the flag and question), every status after the app is written carries `starter: { projectName, platform: "android", projectDir, continuation }`, and a setup error with no status of its own is `setup-interrupted`, so an agent continues inside the new app instead of rerunning `--starter`.
- **Prebuilt sign-in screen.** With the UI artifact, an unchanged starter's `MainActivity` is replaced by one that shows a progress indicator until `Clerk.isInitialized`, `AuthView(isDismissible = false)` until `Clerk.isAuthFlowCompleteFlow`, then `UserButton()` and the signed-in email, keeping the app's theme. Anything other than the unchanged template is left alone, and the handoff's `optional-sign-in-ui` task stays behind user intent. The starter's `MainActivity` is token for token Android Studio's Empty Activity template, so a project just created in Android Studio counts as an unchanged starter too, as a fresh Xcode SwiftUI project does on iOS: init then defaults to `clerk-android-ui` without asking, and offers the sign-in screen.
- **Discovery.** Finds application modules (a `src/main/AndroidManifest.xml` beside a build script that applies `com.android.application`, literally or through a catalog alias) up to three folders deep, and asks when there's more than one. `--android-module` selects explicitly, and selects Android setup even when the directory has no root manifest. Both Kotlin and Groovy DSL scripts are read, and `settings.gradle(.kts)` for `pluginManagement` versions and the module's Gradle project path (`include` and `projectDir` remaps), which the handoff's build task uses. Anything the inspection can't read as one plain value is refused rather than guessed: a computed or repeated `namespace` or `applicationId`, product flavors, an `applicationIdSuffix` outside the debug build type, a project where no module applies `com.android.application` in a way init can read (a convention plugin from `build-logic` applying it, for example), a manifest with several `<application>` elements, a debug manifest that sets `android:name` on `<application>` or replaces or removes it with `tools:node="replace"` or `tools:remove`, more than one top-level `dependencies` block, a `clerk.xml` or `clerk_publishable_key` resource it didn't write. A refused layout doesn't end init: it says why, then takes the path Android had before native setup, linking the app, pulling the publishable key into the env file, and printing the manual quickstart steps (with `--json`, a `manual-setup-required` status carrying `reason`, `envFile`, and `next`). A value that merely can't be read, such as `minSdk` set by a convention plugin or assigned twice, is noted and setup goes on without it. An `Application` whose `onCreate` has an expression body, or whose package name is a Kotlin keyword, is handled too: the first is left to the handoff, the second is spelled with backticks.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { mkdirSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { ERROR_CODE } from "../../../lib/errors.ts";
Expand Down Expand Up @@ -70,8 +70,10 @@ describe("promptAndroidStarter", () => {
test.each([
[{ name: "2fast" }, "name", "start with a letter"],
[{ name: "class" }, "name", "Kotlin keyword"],
[{ name: "Native" }, "name", "Java keyword"],
[{ name: "MyApp", applicationId: "myapp" }, "androidPackage", "reverse-DNS"],
[{ name: "MyApp", applicationId: "com.example.object" }, "androidPackage", "Kotlin keyword"],
[{ name: "MyApp", applicationId: "com.new.app" }, "androidPackage", '"new" is a Java keyword'],
])("refuses %j before writing anything", async (options, field, message) => {
const error = await run(options).catch((e: unknown) => e);
expect(error).toBeInstanceOf(StarterInputRequired);
Expand All @@ -82,7 +84,7 @@ describe("promptAndroidStarter", () => {
expect((error as StarterInputRequired).describe().flag).toBe(
field === "name" ? "--name" : "--android-package",
);
expect(await Bun.file(join(tmp, "MyApp/settings.gradle.kts")).exists()).toBe(false);
expect(readdirSync(tmp)).toEqual([]);
});

test("with --json, a missing --name is asked for with a suggestion", async () => {
Expand Down
59 changes: 54 additions & 5 deletions packages/cli-core/src/commands/init/android/starter-bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ export interface AndroidStarterOptions {
}

const DEFAULT_NAME = "MyClerkApp";
// Kotlin hard keywords can't be package segments; the lowercased name is the default's last one.
// The applicationId is the Kotlin package, which can't have a Kotlin hard keyword as a segment, and
// the namespace, which the Android Gradle Plugin refuses when a segment is a Java keyword. The
// lowercased name is the default's last segment, so a name is held to both as well.
const KOTLIN_KEYWORDS = new Set([
"as",
"break",
Expand Down Expand Up @@ -59,12 +61,56 @@ const KOTLIN_KEYWORDS = new Set([
"when",
"while",
]);
// Java's reserved words and literals that aren't Kotlin hard keywords too.
const JAVA_KEYWORDS = new Set([
"abstract",
"assert",
"boolean",
"byte",
"case",
"catch",
"char",
"const",
"default",
"double",
"enum",
"extends",
"final",
"finally",
"float",
"goto",
"implements",
"import",
"instanceof",
"int",
"long",
"native",
"new",
"private",
"protected",
"public",
"short",
"static",
"strictfp",
"switch",
"synchronized",
"throws",
"transient",
"void",
"volatile",
]);

function keywordLanguage(segment: string): "Kotlin" | "Java" | undefined {
if (KOTLIN_KEYWORDS.has(segment)) return "Kotlin";
return JAVA_KEYWORDS.has(segment) ? "Java" : undefined;
}

function nameProblem(name: string): string | undefined {
if (!ANDROID_APP_NAME.test(name))
return "App name must start with a letter and use only letters, numbers, and underscores, like MyApp.";
if (KOTLIN_KEYWORDS.has(name.toLowerCase()))
return `${name} is a Kotlin keyword, so it can't name the app's package. Pick a different name, like MyApp.`;
const language = keywordLanguage(name.toLowerCase());
if (language)
return `${name} is a ${language} keyword, so it can't name the app's package. Pick a different name, like MyApp.`;
return undefined;
}

Expand Down Expand Up @@ -111,8 +157,11 @@ async function chooseName(cwd: string, options: AndroidStarterOptions): Promise<
function packageProblem(value: string): string | undefined {
if (!PACKAGE_NAME.test(value))
return "Enter a reverse-DNS applicationId with at least two segments, like com.example.myapp.";
if (value.split(".").some((segment) => KOTLIN_KEYWORDS.has(segment)))
return "An applicationId segment can't be a Kotlin keyword, since it's also the Kotlin package.";
for (const segment of value.split(".")) {
const language = keywordLanguage(segment);
if (language)
return `"${segment}" is a ${language} keyword, which an applicationId segment can't be, since the applicationId is also the app's Kotlin package and namespace.`;
}
return undefined;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";
import { useCaptureLog } from "../../../test/lib/stubs.ts";
import { readdir, readFile, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
Expand Down Expand Up @@ -70,6 +71,39 @@ describe("starterProjectFiles", () => {
});

describe("writeAndroidStarter", () => {
const captured = useCaptureLog();
// Git needs an identity to commit and a CI runner has none; the starter passes process.env on.
const IDENTITY = {
GIT_AUTHOR_NAME: "t",
GIT_AUTHOR_EMAIL: "t@t",
GIT_COMMITTER_NAME: "t",
GIT_COMMITTER_EMAIL: "t@t",
};
const NO_IDENTITY = {
GIT_AUTHOR_NAME: undefined,
GIT_COMMITTER_NAME: undefined,
// An empty configured name is refused, and stops Git guessing one from the host.
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: "user.name",
GIT_CONFIG_VALUE_0: "",
};
let restoreEnv = () => {};
function setEnv(values: Record<string, string | undefined>) {
const saved = Object.entries(values).map(([key]) => [key, process.env[key]] as const);
const apply = (entries: Iterable<readonly [string, string | undefined]>) => {
for (const [key, value] of entries) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
};
apply(Object.entries(values));
return () => apply(saved);
}
beforeAll(() => {
restoreEnv = setEnv(IDENTITY);
});
afterAll(() => restoreEnv());

async function write(keep: string[] = roots) {
const cwd = await mkdtemp(join(tmpdir(), "clerk-android-starter-"));
keep.push(cwd);
Expand All @@ -94,20 +128,42 @@ describe("writeAndroidStarter", () => {
});
});

test("writes the executable wrapper and an initial commit", async () => {
// Windows has no executable bit to set or report.
test.skipIf(process.platform === "win32")(
"writes the wrapper executable, in the folder and in the initial commit",
async () => {
const dir = await write();
expect((await stat(join(dir, "gradlew"))).mode & 0o777).toBe(0o755);
expect((await stat(join(dir, "gradlew.bat"))).mode & 0o777).toBe(0o644);
// The initial commit records the executable bit, so a clone can run ./gradlew too.
const index = await Bun.$`git ls-files -s gradlew`.cwd(dir).quiet().nothrow();
expect(index.stdout.toString()).toStartWith("100755 ");
},
);

test("writes the wrapper files and an initial commit", async () => {
const dir = await write();
expect((await stat(join(dir, "gradlew"))).mode & 0o777).toBe(0o755);
expect((await stat(join(dir, "gradlew.bat"))).mode & 0o777).toBe(0o644);
// The initial commit records the executable bit, so a clone can run ./gradlew too.
const index = await Bun.$`git ls-files -s gradlew`.cwd(dir).quiet().nothrow();
expect(index.stdout.toString()).toStartWith("100755 ");
expect((await stat(join(dir, "gradle/wrapper/gradle-wrapper.jar"))).size).toBeGreaterThan(
40_000,
);
expect(await readFile(join(dir, "gradlew.bat"), "utf8")).toContain("gradle-wrapper.jar");
const log = await Bun.$`git log --oneline`.cwd(dir).quiet().nothrow();
expect(log.stdout.toString()).toContain("Initial commit");
expect((await Bun.$`git status --porcelain`.cwd(dir).quiet()).stdout.toString()).toBe("");
expect(captured.err).not.toContain("initial commit");
});

test("warns when Git can't make the initial commit, and still writes the project", async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this covers the warning nicely. Its counterpart is that a missing Git stays silent, as the PR says. Could the "without Git on PATH" test just below also assert expect(captured.err).not.toContain("initial commit") so the warning can't drift into the catch later?

const restore = setEnv(NO_IDENTITY);
try {
const dir = await write();
expect(await readdir(dir)).toContain("app");
expect(captured.err).toContain("Git couldn't make the new app's initial commit");
const log = await Bun.$`git log --oneline`.cwd(dir).quiet().nothrow();
expect(log.stdout.toString()).toBe("");
} finally {
restore();
}
});

test("writes the project without Git on PATH, just with no repository", async () => {
Expand Down
15 changes: 12 additions & 3 deletions packages/cli-core/src/commands/init/android/starter-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { dirname, join } from "node:path";
import wrapperJar from "./starter/gradle-wrapper.jar" with { type: "file" };
import gradlewScript from "./starter/gradlew" with { type: "file" };
import gradlewBatch from "./starter/gradlew.bat" with { type: "file" };
import { log } from "../../../lib/log.ts";
import { createFile } from "./files.ts";
import { CLERK_ANDROID_MIN_SDK } from "./sdk.ts";

Expand Down Expand Up @@ -477,15 +478,23 @@ async function initializeRepository(directory: string): Promise<void> {
cwd: directory,
env: process.env,
stdout: "ignore",
stderr: "ignore",
stderr: "pipe",
timeout: 15_000,
});
return (await child.exited) === 0;
const [code, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()]);
if (code !== 0)
log.debug(`git: ${args.join(" ")} exited ${code} in ${directory}: ${stderr.trim()}`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: with no identity, Git's stderr is the roughly 10-line "Please tell me who you are" block, so this one --verbose entry spans many lines. debug-logging.md asks for one line per message, so maybe collapse it with stderr.trim().replace(/\s*\n\s*/g, " ")?

return code === 0;
};
try {
if (!(await run(["init", "-q"]))) return;
if (!(await run(["add", "-A"]))) return;
await run(["-c", "commit.gpgsign=false", "commit", "-q", "-m", "Initial commit"]);
// Staged but uncommitted files aren't clean to the setup that follows, so it keeps backups of
// the ones it edits; say why, since nothing else does.
if (!(await run(["-c", "commit.gpgsign=false", "commit", "-q", "-m", "Initial commit"])))
log.warn(
"Git couldn't make the new app's initial commit, so its files are staged but not committed. If Git has no identity here, set user.name and user.email, then commit them.",
);
} catch {
// Git isn't installed.
}
Expand Down
28 changes: 28 additions & 0 deletions packages/cli-core/src/commands/init/index-android.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,34 @@ describe("clerk init --starter --framework android", () => {
});
});

// Android's own flags select the starter too, so the check can't depend on --framework.
test.each([
["--framework android", { framework: "android" }],
["--android-package alone", { androidPackage: "org.acme.app" }],
])(
"an agent's new app chosen by %s stops before writing instead of using the link it would inherit",
async (_label, flags) => {
starter({ isAgent: true });
spyOn(config, "resolveProfile").mockResolvedValue({
path: "/work",
profile: { appId: "app_P", appName: "Parent" },
} as never);

await expect(init({ starter: true, name: "MyApp", ...flags })).rejects.toThrow(
"is linked to Parent (app_P), so a new app here would use it too.",
);
expect(written).toBe(false);
},
);

test("--android-package alone refuses the accountless flags like --framework android", async () => {
starter();
await expect(
init({ starter: true, androidPackage: "org.acme.app", accountless: true }),
).rejects.toThrow("link a Clerk application instead");
expect(written).toBe(false);
});

test("refuses the accountless flags and --android-module before writing", async () => {
starter();
await expect(init({ starter: true, framework: "android", accountless: true })).rejects.toThrow(
Expand Down
Loading
Loading