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
3 changes: 2 additions & 1 deletion src/adapters/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ export async function getAdapter(): Promise<Adapter> {
}

export class NoSupportedFrameworkError extends Error {
message = "No supported framework found (Next.js, Nuxt, or SvelteKit required)";
name = "NoSupportedFrameworkError";
Comment thread
cursor[bot] marked this conversation as resolved.
message = "No supported framework found. Run this command in a Next.js, Nuxt, or SvelteKit project.";
}

export abstract class Adapter {
Expand Down
42 changes: 24 additions & 18 deletions src/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,18 @@ import {
UnknownProjectRootError,
} from "../project";
import { checkIsTypeBuilderEnabled, TypeBuilderRequiredError } from "../project";
import { createRepo } from "./repo-create";

const config = {
name: "prismic init",
description: `
Initialize a Prismic project by creating a prismic.config.json file.
Initialize a new Prismic project by creating a repository and
prismic.config.json file. Detects the project framework, installs
dependencies, and syncs models from Prismic.

Detects the project framework, installs dependencies, and syncs models
from Prismic. If a slicemachine.config.json exists, it will be migrated.
Use --repo to connect to an existing repository instead. If a
slicemachine.config.json exists, its repository and settings will be
migrated.
`,
options: {
repo: { type: "string", short: "r", description: "Repository name" },
Expand Down Expand Up @@ -63,12 +67,6 @@ export default createCommand(config, async ({ values }) => {
}
}

const repo = explicitRepo ?? legacySliceMachineConfig?.repositoryName;
if (!repo) {
throw new CommandError("Missing required flag: --repo");
}

// Validate repo membership
let token = await getToken();
const host = await getHost();
let profile: Profile;
Expand Down Expand Up @@ -96,20 +94,28 @@ export default createCommand(config, async ({ values }) => {
}
}

const repoMeta = profile.repositories.find((repository) => repository.domain === repo);
if (!repoMeta) {
throw new CommandError(
`Repository "${repo}" not found in your account. Check the name or request access to the repository.`,
);
}
let repo = explicitRepo ?? legacySliceMachineConfig?.repositoryName;
if (repo) {
const hasRepoAccess = profile.repositories.some((repository) => repository.domain === repo);
if (!hasRepoAccess) {
throw new CommandError(
`Repository "${repo}" not found in your account. Check the name or request access to the repository.`,
);
}

const isTypeBuilderEnabled = await checkIsTypeBuilderEnabled(repo, { token, host });
if (!isTypeBuilderEnabled) {
throw new TypeBuilderRequiredError();
const isTypeBuilderEnabled = await checkIsTypeBuilderEnabled(repo, { token, host });
if (!isTypeBuilderEnabled) {
throw new TypeBuilderRequiredError();
}
}

const adapter = await getAdapter();

if (!repo) {
repo = await createRepo({ token, host });
console.info(`Created repository: ${repo}`);
}

// Create prismic.config.json
try {
const documentAPIEndpoint =
Expand Down
18 changes: 14 additions & 4 deletions src/commands/repo-create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ export default createCommand(config, async ({ values }) => {

const token = await getToken();
const host = await getHost();
const domain = await createRepo({ name, token, host });

console.info(`Repository created: ${domain}`);
console.info(`URL: https://${domain}.${host}/`);
});

export async function createRepo(config: {
name?: string;
token: string | undefined;
host: string;
}): Promise<string> {
const { name, token, host } = config;

const domain = await findAvailableDomain({ token, host });
if (!domain) {
Expand All @@ -38,10 +50,8 @@ export default createCommand(config, async ({ values }) => {
throw error;
}

console.info(`Repository created: ${domain}`);
console.info(`URL: https://${domain}.${host}/`);
console.info(`Run \`prismic init --repo ${domain}\` to initialize a project.`);
});
return domain;
}

async function findAvailableDomain(config: {
token: string | undefined;
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import webhook from "./commands/webhook";
import whoami from "./commands/whoami";
import { UPDATE_NOTIFIER_STATE_PATH } from "./config";
import { CommandError, createCommandRouter } from "./lib/command";
import { decodePayload } from "./lib/jwt";
import {
ForbiddenRequestError,
NotFoundRequestError,
Expand All @@ -42,7 +43,6 @@ import {
sentrySetUser,
setupSentry,
} from "./lib/sentry";
import { decodePayload } from "./lib/jwt";
import { dedent } from "./lib/string";
import { initUpdateNotifier } from "./lib/update-notifier";
import { InvalidPrismicConfigError, MissingPrismicConfigError } from "./project";
Expand Down
15 changes: 10 additions & 5 deletions test/init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,21 @@ it("fails if prismic.config.json already exists", async ({ expect, prismic }) =>
expect(stderr).toContain("already initialized");
});

it("fails if --repo is not provided and no legacy config exists", async ({
it("creates a repo if --repo is not provided and no legacy config exists", async ({
expect,
project,
prismic,
}) => {
await rm(new URL("prismic.config.json", project));
const { exitCode, stderr } = await prismic("init");
expect(exitCode).toBe(1);
expect(stderr).toContain("Missing required flag");
});
const { exitCode, stdout } = await prismic("init");
expect(exitCode).toBe(0);
expect(stdout).toContain("Created repository:");
expect(stdout).toContain("Initialized Prismic for repository");

const configRaw = await readFile(new URL("prismic.config.json", project), "utf-8");
const config = JSON.parse(configRaw);
expect(config.repositoryName).toMatch(/^[a-f0-9]{8}$/);
}, 60_000);

it("initializes a project with --repo when logged in", async ({
expect,
Expand Down