Skip to content
Merged
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
1 change: 1 addition & 0 deletions src/clients/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const ProfileSchema = z.object({
z.object({
domain: z.string(),
name: z.optional(z.string()),
role: z.optional(z.string()),
}),
),
});
Expand Down
92 changes: 92 additions & 0 deletions src/clients/wroom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,98 @@ export async function deleteWriteToken(
});
}

export async function checkIsDomainAvailable(config: {
domain: string;
token: string | undefined;
host: string;
}): Promise<boolean> {
const { domain, token, host } = config;
const url = new URL(`app/dashboard/repositories/${domain}/exists`, getDashboardUrl(host));
const response = await request(url, {
credentials: { "prismic-auth": token },
schema: z.boolean(),
});
return response;
}

export async function createRepository(config: {
domain: string;
name: string;
framework: string;
token: string | undefined;
host: string;
}): Promise<void> {
const { domain, name, framework, token, host } = config;
const url = new URL("app/dashboard/repositories", getDashboardUrl(host));
await request(url, {
method: "POST",
body: { domain, name, framework, plan: "personal" },
credentials: { "prismic-auth": token },
});
}

const SyncStateSchema = z.object({
repository: z.object({
api_access: z.string(),
}),
});

export async function getRepositoryAccess(config: {
repo: string;
token: string | undefined;
host: string;
}): Promise<string> {
const { repo, token, host } = config;
const url = new URL("syncState", getWroomUrl(repo, host));
const response = await request(url, {
credentials: { "prismic-auth": token },
schema: SyncStateSchema,
});
return response.repository.api_access;
}

export type RepositoryAccessLevel = "private" | "public" | "open";

export async function setRepositoryAccess(
level: RepositoryAccessLevel,
config: { repo: string; token: string | undefined; host: string },
): Promise<void> {
const { repo, token, host } = config;
const url = new URL("settings/security/apiaccess", getWroomUrl(repo, host));
await request(url, {
method: "POST",
body: { api_access: level },
credentials: { "prismic-auth": token },
});
}

const SetNameResponseSchema = z.object({
repository: z.object({
name: z.string(),
}),
});

export async function setRepositoryName(
name: string,
config: { repo: string; token: string | undefined; host: string },
): Promise<string> {
const { repo, token, host } = config;
const url = new URL("app/settings/repository", getWroomUrl(repo, host));
const formData = new FormData();
formData.set("displayname", name);
const response = await request(url, {
method: "POST",
body: formData,
credentials: { "prismic-auth": token },
schema: SetNameResponseSchema,
});
return response.repository.name;
}

function getDashboardUrl(host: string): URL {
return new URL(`https://${host}/`);
}

function getWroomUrl(repo: string, host: string): URL {
return new URL(`https://${repo}.${host}/`);
}
60 changes: 60 additions & 0 deletions src/commands/repo-create.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { getAdapter } from "../adapters";
import { getHost, getToken } from "../auth";
import { checkIsDomainAvailable, createRepository } from "../clients/wroom";
import { CommandError, createCommand, type CommandConfig } from "../lib/command";
import { UnknownRequestError } from "../lib/request";

const MAX_DOMAIN_TRIES = 5;

const config = {
name: "prismic repo create",
description: "Create a new Prismic repository.",
options: {
name: { type: "string", short: "n", description: "Display name for the repository" },
},
} satisfies CommandConfig;

export default createCommand(config, async ({ values }) => {
const { name } = values;

const token = await getToken();
const host = await getHost();

const domain = await findAvailableDomain({ token, host });
if (!domain) {
throw new CommandError("Failed to create a repository. Please try again.");
}

const adapter = await getAdapter().catch(() => undefined);
const framework = adapter?.id ?? "other";

try {
await createRepository({ domain, name: name ?? domain, framework, token, host });
} catch (error) {
if (error instanceof UnknownRequestError) {
const message = await error.text();
throw new CommandError(`Failed to create repository: ${message}`);
}
throw error;
}

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

async function findAvailableDomain(config: {
token: string | undefined;
host: string;
}): Promise<string | undefined> {
const { token, host } = config;
let domain;
for (let i = 0; i < MAX_DOMAIN_TRIES; i++) {
const candidate = crypto.randomUUID().replace(/-/g, "").slice(0, 8);
const available = await checkIsDomainAvailable({ domain: candidate, token, host });
if (available) {
domain = candidate;
break;
}
}
return domain;
}
58 changes: 58 additions & 0 deletions src/commands/repo-list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { getHost, getToken } from "../auth";
import { getProfile } from "../clients/user";
import { CommandError, createCommand, type CommandConfig } from "../lib/command";
import { stringify } from "../lib/json";
import { UnknownRequestError } from "../lib/request";

const config = {
name: "prismic repo list",
description: "List all Prismic repositories associated with your account.",
options: {
json: { type: "boolean", description: "Output as JSON" },
},
} satisfies CommandConfig;

export default createCommand(config, async ({ values }) => {
const { json } = values;

const token = await getToken();
const host = await getHost();

let profile;
try {
profile = await getProfile({ token, host });
} catch (error) {
if (error instanceof UnknownRequestError) {
const message = await error.text();
throw new CommandError(`Failed to list repositories: ${message}`);
}
throw error;
}

const repos = profile.repositories;

if (json) {
console.info(
stringify(
repos.map((repo) => ({
domain: repo.domain,
name: repo.name ?? null,
role: repo.role ?? null,
url: `https://${repo.domain}.${host}/`,
})),
),
);
return;
}

if (repos.length === 0) {
console.info("No repositories found.");
return;
}

for (const repo of repos) {
const name = repo.name || "(no name)";
const role = repo.role ? ` ${repo.role}` : "";
console.info(`${repo.domain} ${name}${role}`);
}
});
53 changes: 53 additions & 0 deletions src/commands/repo-set-api-access.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { getHost, getToken } from "../auth";
import { type RepositoryAccessLevel, setRepositoryAccess } from "../clients/wroom";
import { CommandError, createCommand, type CommandConfig } from "../lib/command";
import { UnknownRequestError } from "../lib/request";
import { getRepositoryName } from "../project";

const VALID_LEVELS: RepositoryAccessLevel[] = ["private", "public", "open"];

const config = {
name: "prismic repo set-api-access",
description: `
Set the Content API access level of a Prismic repository.

By default, this command reads the repository from prismic.config.json at the
project root.
`,
positionals: {
level: { description: `Access level (${VALID_LEVELS.join(", ")})` },
},
options: {
repo: { type: "string", short: "r", description: "Repository domain" },
},
} satisfies CommandConfig;

export default createCommand(config, async ({ positionals, values }) => {
const [level] = positionals;
const { repo = await getRepositoryName() } = values;

if (!level) {
throw new CommandError("Missing required argument: <level>");
}

if (!VALID_LEVELS.includes(level as RepositoryAccessLevel)) {
throw new CommandError(
`Invalid access level: ${level}. Must be one of: ${VALID_LEVELS.join(", ")}`,
);
}

const token = await getToken();
const host = await getHost();

try {
await setRepositoryAccess(level as RepositoryAccessLevel, { repo, token, host });
} catch (error) {
if (error instanceof UnknownRequestError) {
const message = await error.text();
throw new CommandError(`Failed to set repository access: ${message}`);
}
throw error;
}

console.info(`Repository access set to: ${level}`);
});
46 changes: 46 additions & 0 deletions src/commands/repo-set-name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { getHost, getToken } from "../auth";
import { setRepositoryName } from "../clients/wroom";
import { CommandError, createCommand, type CommandConfig } from "../lib/command";
import { UnknownRequestError } from "../lib/request";
import { getRepositoryName } from "../project";

const config = {
name: "prismic repo set-name",
description: `
Set the display name of a Prismic repository.

By default, this command reads the repository from prismic.config.json at the
project root.
`,
positionals: {
name: { description: "Display name for the repository" },
},
options: {
repo: { type: "string", short: "r", description: "Repository domain" },
},
} satisfies CommandConfig;

export default createCommand(config, async ({ positionals, values }) => {
const [displayName] = positionals;
const { repo = await getRepositoryName() } = values;

if (!displayName) {
throw new CommandError("Missing required argument: <name>");
}

const token = await getToken();
const host = await getHost();

let confirmedName;
try {
confirmedName = await setRepositoryName(displayName, { repo, token, host });
} catch (error) {
if (error instanceof UnknownRequestError) {
const message = await error.text();
throw new CommandError(`Failed to set repository name: ${message}`);
}
throw error;
}

console.info(`Repository name set to: ${confirmedName}`);
});
Loading