Skip to content
Draft
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
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
"./dist"
],
"type": "module",
"exports": {
"./env": "./dist/env.mjs",
"./env/register": "./dist/env/register.mjs"
},
"publishConfig": {
"access": "public"
},
Expand Down
96 changes: 96 additions & 0 deletions src/active-environment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";

import { getConfigDir } from "./lib/config-dir";
import { findUpwardSync } from "./lib/file";
import { stringify } from "./lib/json";

// The active environment lives in the CLI, keyed by project so nothing lands in
// the repo. Reads are synchronous so a framework config can set the environment
// variable before the framework reads it at build time. This module is published
// as `prismic/env`, so it stays dependency-light.

const CONFIG_FILENAME = "prismic.config.json";

const ENVIRONMENTS_PATH = new URL(
"environments.json",
getConfigDir("prismic", process.env.PRISMIC_CONFIG_DIR),
);

const FRAMEWORK_ENV_VARS: Record<string, string> = {
next: "NEXT_PUBLIC_PRISMIC_ENVIRONMENT",
nuxt: "NUXT_PUBLIC_PRISMIC_ENVIRONMENT",
"@sveltejs/kit": "VITE_PRISMIC_ENVIRONMENT",
};

export function getActiveEnvironment(): string | undefined {
const project = findProjectRoot();
if (!project) return undefined;
return readState()[project];
}

export function setActiveEnvironment(domain: string): void {
const project = findProjectRoot();
if (!project) return;
const state = readState();
state[project] = domain;
writeState(state);
}

export function unsetActiveEnvironment(): void {
const project = findProjectRoot();
if (!project) return;
const state = readState();
if (!(project in state)) return;
delete state[project];
writeState(state);
}

export function getFrameworkEnvVar(): string | undefined {
const packageJson = readPackageJson();
if (!packageJson) return undefined;
const dependencies = {
...packageJson.dependencies,
...packageJson.devDependencies,
...packageJson.peerDependencies,
};
for (const dependency in FRAMEWORK_ENV_VARS) {
if (dependency in dependencies) return FRAMEWORK_ENV_VARS[dependency];
}
return undefined;
}

function readState(): Record<string, string> {
try {
return JSON.parse(readFileSync(ENVIRONMENTS_PATH, "utf8"));
} catch {
return {};
}
}

function writeState(state: Record<string, string>): void {
mkdirSync(new URL(".", ENVIRONMENTS_PATH), { recursive: true });
writeFileSync(ENVIRONMENTS_PATH, stringify(state));
}

function findProjectRoot(): string | undefined {
const configPath = findUpwardSync(CONFIG_FILENAME);
if (!configPath) return undefined;
return realpathSync(fileURLToPath(new URL(".", configPath)));
}

type PackageJson = {
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
};

function readPackageJson(): PackageJson | undefined {
Comment thread
angeloashmore marked this conversation as resolved.
const packageJsonPath = findUpwardSync("package.json");
if (!packageJsonPath) return undefined;
try {
return JSON.parse(readFileSync(packageJsonPath, "utf8"));
} catch {
return undefined;
}
}
19 changes: 17 additions & 2 deletions src/adapters/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { CustomType, SharedSlice } from "@prismicio/types-internal/lib/customtypes";

import { pascalCase } from "change-case";
import { rm } from "node:fs/promises";
import { readFile, rm, writeFile } from "node:fs/promises";
import { pathToFileURL } from "node:url";
import { generateTypes } from "prismic-ts-codegen";
import { glob } from "tinyglobby";

import { readJsonFile, writeFileRecursive } from "../lib/file";
import { exists, readJsonFile, writeFileRecursive } from "../lib/file";
import { stringify } from "../lib/json";
import { readPackageJson } from "../lib/packageJson";
import { appendTrailingSlash } from "../lib/url";
Expand Down Expand Up @@ -42,6 +42,21 @@ export class NoSupportedFrameworkError extends Error {
"No supported framework found. Run this command in a Next.js, Nuxt, or SvelteKit project.";
}

// Adds `import "prismic/env/register"` to the first existing framework config so
// the active environment is applied at build time.
export async function addEnvRegisterImport(candidates: string[]): Promise<void> {
const projectRoot = await findProjectRoot();
for (const candidate of candidates) {
const configUrl = new URL(candidate, projectRoot);
if (!(await exists(configUrl))) continue;
const contents = await readFile(configUrl, "utf8");
if (!contents.includes("prismic/env/register")) {
await writeFile(configUrl, `import "prismic/env/register";\n\n${contents}`);
}
return;
}
}

export abstract class Adapter {
abstract readonly id: string;

Expand Down
4 changes: 2 additions & 2 deletions src/adapters/nextjs.templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ export function prismicIOFileTemplate(args: {
/**
* The project's Prismic repository name.
*/
export const repositoryName = prismicConfig.repositoryName;
export const repositoryName = process.env.NEXT_PUBLIC_PRISMIC_ENVIRONMENT || prismicConfig.repositoryName;

${createClientContents}
`;
Expand All @@ -369,7 +369,7 @@ export function prismicIOFileTemplate(args: {
/**
* The project's Prismic repository name.
*/
export const repositoryName = prismicConfig.repositoryName;
export const repositoryName = process.env.NEXT_PUBLIC_PRISMIC_ENVIRONMENT || prismicConfig.repositoryName;

${createClientContents}
`;
Expand Down
4 changes: 3 additions & 1 deletion src/adapters/nextjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { createRequire } from "node:module";
import { relative } from "node:path";
import { fileURLToPath } from "node:url";

import { Adapter } from ".";
import { Adapter, addEnvRegisterImport } from ".";
import { getHost, getToken } from "../auth";
import { addPreview, getPreviews, getSimulatorUrl, setSimulatorUrl } from "../clients/core";
import { exists, writeFileRecursive } from "../lib/file";
Expand All @@ -29,6 +29,7 @@ export class NextJsAdapter extends Adapter {

async setupProject(): Promise<void> {
await addDependencies({
prismic: `^${await getNpmPackageVersion("prismic")}`,
"@prismicio/client": `^${await getNpmPackageVersion("@prismicio/client")}`,
"@prismicio/react": `^${await getNpmPackageVersion("@prismicio/react")}`,
"@prismicio/next": `^${await getNpmPackageVersion("@prismicio/next")}`,
Expand All @@ -38,6 +39,7 @@ export class NextJsAdapter extends Adapter {
await createPreviewRoute();
await createExitPreviewRoute();
await createRevalidateRoute();
await addEnvRegisterImport(["next.config.ts", "next.config.mjs", "next.config.js"]);
}

async onProjectInitialized(): Promise<void> {
Expand Down
4 changes: 2 additions & 2 deletions src/adapters/sveltekit.templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export function prismicIOFileTemplate(args: { typescript: boolean }): string {
/**
* The project's Prismic repository name.
*/
export const repositoryName = prismicConfig.repositoryName;
export const repositoryName = import.meta.env.VITE_PRISMIC_ENVIRONMENT || prismicConfig.repositoryName;

/**
* Creates a Prismic client for the project's repository. The client is used to
Expand Down Expand Up @@ -45,7 +45,7 @@ export function prismicIOFileTemplate(args: { typescript: boolean }): string {
/**
* The project's Prismic repository name.
*/
export const repositoryName = prismicConfig.repositoryName;
export const repositoryName = import.meta.env.VITE_PRISMIC_ENVIRONMENT || prismicConfig.repositoryName;

/**
* Creates a Prismic client for the project's repository. The client is used to
Expand Down
4 changes: 3 additions & 1 deletion src/adapters/sveltekit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { createRequire } from "node:module";
import { relative } from "node:path";
import { fileURLToPath } from "node:url";

import { Adapter } from ".";
import { Adapter, addEnvRegisterImport } from ".";
import { getHost, getToken } from "../auth";
import { addPreview, getPreviews, getSimulatorUrl, setSimulatorUrl } from "../clients/core";
import { exists, writeFileRecursive } from "../lib/file";
Expand All @@ -31,6 +31,7 @@ export class SvelteKitAdapter extends Adapter {

async setupProject(): Promise<void> {
await addDependencies({
prismic: `^${await getNpmPackageVersion("prismic")}`,
"@prismicio/client": `^${await getNpmPackageVersion("@prismicio/client")}`,
"@prismicio/svelte": `^${await getNpmPackageVersion("@prismicio/svelte")}`,
});
Expand All @@ -42,6 +43,7 @@ export class SvelteKitAdapter extends Adapter {
await createRootLayoutServerFile();
await createRootLayoutFile();
await modifyViteConfig();
await addEnvRegisterImport(["vite.config.ts", "vite.config.js"]);
}

async onProjectInitialized(): Promise<void> {
Expand Down
15 changes: 15 additions & 0 deletions src/commands/env-active.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { createCommand, type CommandConfig } from "../lib/command";
import { getRepositoryName } from "../project";

const config = {
name: "prismic env active",
description: `
Print the active environment.

Prints the production environment when no environment is active.
`,
} satisfies CommandConfig;

export default createCommand(config, async () => {
console.info(await getRepositoryName());
});
50 changes: 50 additions & 0 deletions src/commands/env-list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { getActiveEnvironment } from "../active-environment";
import { getHost, getToken } from "../auth";
import { getUserEnvironments } from "../environments";
import { createCommand, type CommandConfig } from "../lib/command";
import { stringify } from "../lib/json";
import { formatTable } from "../lib/string";
import { readConfig } from "../project";

const config = {
name: "prismic env list",
description: `
List the environments available for the project, marking the active one.
`,
options: {
json: { type: "boolean", description: "Output as JSON" },
},
} satisfies CommandConfig;

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

const { repositoryName } = await readConfig();
const token = await getToken();
const host = await getHost();

const environments = await getUserEnvironments({ repo: repositoryName, token, host });
const activeEnvironment = getActiveEnvironment() ?? repositoryName;

if (json) {
const results = environments.map((environment) => ({
kind: environment.kind,
name: environment.name,
domain: environment.domain,
active: environment.domain === activeEnvironment,
}));
console.info(stringify(results));
return;
}

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

const rows = environments.map((environment) => {
const activeLabel = environment.domain === activeEnvironment ? " (active)" : "";
return [environment.domain, `${environment.name}${activeLabel}`];
});
console.info(formatTable(rows, { headers: ["DOMAIN", "NAME"] }));
});
38 changes: 38 additions & 0 deletions src/commands/env-set.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { setActiveEnvironment, unsetActiveEnvironment } from "../active-environment";
import { getHost, getToken } from "../auth";
import { resolveEnvironment } from "../environments";
import { createCommand, type CommandConfig } from "../lib/command";
import { readConfig } from "../project";

const config = {
name: "prismic env set",
description: `
Set the active environment for the project.

The active environment is stored by the CLI and used by every command and by
the project at build time. Setting the production environment is the same as
\`prismic env unset\`.
`,
positionals: {
name: { description: "Environment domain", required: true },
},
} satisfies CommandConfig;

export default createCommand(config, async ({ positionals }) => {
const [name] = positionals;

const { repositoryName } = await readConfig();
const token = await getToken();
const host = await getHost();

const domain = await resolveEnvironment(name, { repo: repositoryName, token, host });
Comment thread
angeloashmore marked this conversation as resolved.

if (domain === repositoryName) {
unsetActiveEnvironment();
console.info(`Reset to the production environment "${repositoryName}".`);
return;
}

setActiveEnvironment(domain);
console.info(`Set the active environment to "${domain}".`);
});
18 changes: 18 additions & 0 deletions src/commands/env-unset.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { unsetActiveEnvironment } from "../active-environment";
import { createCommand, type CommandConfig } from "../lib/command";
import { readConfig } from "../project";

const config = {
name: "prismic env unset",
description: `
Reset the active environment to the production environment.
`,
} satisfies CommandConfig;

export default createCommand(config, async () => {
const { repositoryName } = await readConfig();

unsetActiveEnvironment();

console.info(`Reset to the production environment "${repositoryName}".`);
});
28 changes: 28 additions & 0 deletions src/commands/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { createCommandRouter } from "../lib/command";
import envActive from "./env-active";
import envList from "./env-list";
import envSet from "./env-set";
import envUnset from "./env-unset";

export default createCommandRouter({
name: "prismic env",
description: "Manage the active environment for a Prismic project.",
commands: {
set: {
handler: envSet,
description: "Set the active environment",
},
unset: {
handler: envUnset,
description: "Reset to the production environment",
},
active: {
handler: envActive,
description: "Print the active environment",
},
list: {
handler: envList,
description: "List environments",
},
},
});
Loading
Loading