@foliwake/next 0.9.0 → 0.10.2
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.
- package/CHANGELOG.md +92 -0
- package/README.md +215 -12
- package/dist/config.d.ts +17 -8
- package/dist/config.js +50 -26
- package/dist/handler.d.ts +33 -0
- package/dist/handler.js +32 -0
- package/dist/init/apply.d.ts +19 -0
- package/dist/init/apply.js +91 -0
- package/dist/init/bin.d.ts +2 -0
- package/dist/init/bin.js +21 -0
- package/dist/init/check.d.ts +9 -0
- package/dist/init/check.js +78 -0
- package/dist/init/detect.d.ts +30 -0
- package/dist/init/detect.js +85 -0
- package/dist/init/next-config.d.ts +30 -0
- package/dist/init/next-config.js +99 -0
- package/dist/init/options.d.ts +22 -0
- package/dist/init/options.js +73 -0
- package/dist/init/plan.d.ts +29 -0
- package/dist/init/plan.js +64 -0
- package/dist/init/report.d.ts +24 -0
- package/dist/init/report.js +43 -0
- package/dist/init/run.d.ts +12 -0
- package/dist/init/run.js +95 -0
- package/dist/init/site.d.ts +15 -0
- package/dist/init/site.js +35 -0
- package/dist/init/templates.d.ts +14 -0
- package/dist/init/templates.js +29 -0
- package/dist/page-route.d.ts +21 -0
- package/dist/page-route.js +55 -0
- package/dist/ready-page.d.ts +42 -0
- package/dist/ready-page.js +51 -0
- package/dist/revalidate.js +5 -3
- package/dist/settings.d.ts +10 -0
- package/dist/settings.js +20 -10
- package/dist/version.d.ts +1 -0
- package/dist/version.js +2 -0
- package/package.json +21 -6
- package/schemas/remote-2.schema.json +110 -0
- package/schemas/remote-3.schema.json +204 -0
- package/dist/revalidate-core.d.ts +0 -33
- package/dist/revalidate-core.js +0 -144
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Carries out a plan, or (dry run) says what it would do. Never overwrites a file it did not generate; adds only
|
|
2
|
+
// env names that are missing; edits next.config once.
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { addCacheComponents, CACHE_COMPONENTS_LINE, editNextConfig, MANUAL_STEPS, } from './next-config.js';
|
|
6
|
+
import { GENERATED } from './templates.js';
|
|
7
|
+
const ENV_NAME = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/gm;
|
|
8
|
+
function read(file) {
|
|
9
|
+
return existsSync(file) ? readFileSync(file, 'utf8') : null;
|
|
10
|
+
}
|
|
11
|
+
function write(file, text, opts) {
|
|
12
|
+
if (opts.dryRun)
|
|
13
|
+
return;
|
|
14
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
15
|
+
writeFileSync(file, text);
|
|
16
|
+
}
|
|
17
|
+
function applyFile(step, opts) {
|
|
18
|
+
const file = path.join(opts.cwd, step.path);
|
|
19
|
+
const current = read(file);
|
|
20
|
+
const base = { path: step.path, what: step.what };
|
|
21
|
+
if (current === step.content)
|
|
22
|
+
return { ...base, outcome: 'exists' };
|
|
23
|
+
if (current !== null && !(opts.force && current.startsWith(GENERATED))) {
|
|
24
|
+
const note = current.startsWith(GENERATED) ? 'exists; --force rewrites it' : 'exists and is yours; left alone';
|
|
25
|
+
return { ...base, outcome: 'skipped', note };
|
|
26
|
+
}
|
|
27
|
+
write(file, step.content, opts);
|
|
28
|
+
return { ...base, outcome: current === null ? 'created' : 'updated' };
|
|
29
|
+
}
|
|
30
|
+
function envNames(text) {
|
|
31
|
+
return new Set([...text.matchAll(ENV_NAME)].map((match) => match[1]));
|
|
32
|
+
}
|
|
33
|
+
function applyEnv(step, opts) {
|
|
34
|
+
const file = path.join(opts.cwd, step.path);
|
|
35
|
+
const current = read(file);
|
|
36
|
+
if (current === null && step.onlyIfExists)
|
|
37
|
+
return null;
|
|
38
|
+
const known = envNames(current ?? '');
|
|
39
|
+
const missing = step.lines.filter((line) => !known.has(line.split('=')[0]));
|
|
40
|
+
const base = { path: step.path, what: step.what };
|
|
41
|
+
if (missing.length === 0)
|
|
42
|
+
return { ...base, outcome: 'exists' };
|
|
43
|
+
const separator = current && !current.endsWith('\n') ? '\n' : '';
|
|
44
|
+
write(file, `${current ?? ''}${separator}${missing.join('\n')}\n`, opts);
|
|
45
|
+
return { ...base, outcome: current === null ? 'created' : 'updated', note: missing.map(nameOf).join(', ') };
|
|
46
|
+
}
|
|
47
|
+
const nameOf = (line) => line.split('=')[0];
|
|
48
|
+
const CACHE_WHAT = 'cacheComponents: true (the page route needs it)';
|
|
49
|
+
function cacheStep(file, cache) {
|
|
50
|
+
const base = { path: file, what: CACHE_WHAT };
|
|
51
|
+
if (cache.kind === 'manual') {
|
|
52
|
+
return { ...base, outcome: 'manual', note: `${cache.reason}; add \`${CACHE_COMPONENTS_LINE}\` to the config` };
|
|
53
|
+
}
|
|
54
|
+
return { ...base, outcome: cache.kind === 'added' ? 'updated' : 'exists' };
|
|
55
|
+
}
|
|
56
|
+
// Two results: the withFoliwake() wrap, then cacheComponents; the file is written once, when either changed it.
|
|
57
|
+
function applyConfig(step, opts) {
|
|
58
|
+
const file = path.join(opts.cwd, step.path);
|
|
59
|
+
const base = { path: step.path, what: step.what };
|
|
60
|
+
if (step.create !== null) {
|
|
61
|
+
write(file, step.create, opts);
|
|
62
|
+
return [{ ...base, outcome: 'created' }];
|
|
63
|
+
}
|
|
64
|
+
const original = readFileSync(file, 'utf8');
|
|
65
|
+
const wrap = editNextConfig(original, step.path);
|
|
66
|
+
if (wrap.kind === 'manual') {
|
|
67
|
+
return [{ ...base, outcome: 'manual', note: `${wrap.reason}. ${MANUAL_STEPS.join(' ')}` }];
|
|
68
|
+
}
|
|
69
|
+
const wrapped = wrap.kind === 'wrapped' ? wrap.text : original;
|
|
70
|
+
const cache = addCacheComponents(wrapped);
|
|
71
|
+
const final = cache.kind === 'added' ? cache.text : wrapped;
|
|
72
|
+
if (final !== original)
|
|
73
|
+
write(file, final, opts);
|
|
74
|
+
return [{ ...base, outcome: wrap.kind === 'present' ? 'exists' : 'updated' }, cacheStep(step.path, cache)];
|
|
75
|
+
}
|
|
76
|
+
/** Applies every step in order. */
|
|
77
|
+
export function applySteps(steps, opts) {
|
|
78
|
+
const results = [];
|
|
79
|
+
for (const step of steps) {
|
|
80
|
+
if (step.kind === 'file')
|
|
81
|
+
results.push(applyFile(step, opts));
|
|
82
|
+
else if (step.kind === 'next-config')
|
|
83
|
+
results.push(...applyConfig(step, opts));
|
|
84
|
+
else {
|
|
85
|
+
const result = applyEnv(step, opts);
|
|
86
|
+
if (result)
|
|
87
|
+
results.push(result);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return results;
|
|
91
|
+
}
|
package/dist/init/bin.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The `foliwake-next` command (`npx @foliwake/next init`): runInit on the process's arguments and streams.
|
|
3
|
+
import { createInterface } from 'node:readline/promises';
|
|
4
|
+
import { runInit } from './run.js';
|
|
5
|
+
async function ask(question) {
|
|
6
|
+
const terminal = createInterface({ input: process.stdin, output: process.stdout });
|
|
7
|
+
try {
|
|
8
|
+
return await terminal.question(question);
|
|
9
|
+
}
|
|
10
|
+
finally {
|
|
11
|
+
terminal.close();
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const io = {
|
|
15
|
+
stdout: (text) => process.stdout.write(text),
|
|
16
|
+
stderr: (text) => process.stderr.write(text),
|
|
17
|
+
env: process.env,
|
|
18
|
+
cwd: process.cwd(),
|
|
19
|
+
...(process.stdin.isTTY ? { ask } : {}),
|
|
20
|
+
};
|
|
21
|
+
process.exitCode = await runInit(process.argv.slice(2), io);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Project } from './detect.js';
|
|
2
|
+
/** One check. */
|
|
3
|
+
export interface CheckResult {
|
|
4
|
+
name: string;
|
|
5
|
+
ok: boolean;
|
|
6
|
+
detail: string;
|
|
7
|
+
}
|
|
8
|
+
/** Every check of an existing setup. */
|
|
9
|
+
export declare function checkSetup(project: Project, env: NodeJS.ProcessEnv, doFetch?: typeof fetch): Promise<CheckResult[]>;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// `init --check`: is this app set up? Reads files and asks the site; prints variable names, never values.
|
|
2
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { verifySite } from './site.js';
|
|
5
|
+
const PACKAGES = ['@foliwake/next', '@foliwake/server', '@foliwake/react'];
|
|
6
|
+
function read(file) {
|
|
7
|
+
return existsSync(file) ? readFileSync(file, 'utf8') : null;
|
|
8
|
+
}
|
|
9
|
+
/** Files under `dir` (relative to cwd) whose text mentions `needle`, depth ≤ 4. */
|
|
10
|
+
function filesMentioning(cwd, dir, needle, depth = 4) {
|
|
11
|
+
const full = path.join(cwd, dir);
|
|
12
|
+
if (depth < 0 || !existsSync(full))
|
|
13
|
+
return [];
|
|
14
|
+
return readdirSync(full, { withFileTypes: true }).flatMap((entry) => {
|
|
15
|
+
const relative = path.posix.join(dir, entry.name);
|
|
16
|
+
if (entry.isDirectory())
|
|
17
|
+
return filesMentioning(cwd, relative, needle, depth - 1);
|
|
18
|
+
return /\.(t|j)sx?$/.test(entry.name) && read(path.join(cwd, relative))?.includes(needle) ? [relative] : [];
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
/** Env names set in the environment or in .env.local (values are never read out). */
|
|
22
|
+
function envNames(cwd, env) {
|
|
23
|
+
const local = read(path.join(cwd, '.env.local')) ?? '';
|
|
24
|
+
const filled = [...local.matchAll(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(\S+)/gm)].map((m) => m[1]);
|
|
25
|
+
return new Set([...filled, ...Object.keys(env).filter((name) => env[name])]);
|
|
26
|
+
}
|
|
27
|
+
function urlOf(cwd, env) {
|
|
28
|
+
const local = read(path.join(cwd, '.env.local')) ?? '';
|
|
29
|
+
return env.FOLIWAKE_URL || (/^\s*FOLIWAKE_URL\s*=\s*(\S+)/m.exec(local)?.[1] ?? null);
|
|
30
|
+
}
|
|
31
|
+
function fileChecks(project) {
|
|
32
|
+
const config = project.nextConfig ? read(path.join(project.cwd, project.nextConfig)) : null;
|
|
33
|
+
const handler = filesMentioning(project.cwd, project.appDir, '@foliwake/next/handler');
|
|
34
|
+
const page = filesMentioning(project.cwd, project.appDir, '@foliwake/next/page');
|
|
35
|
+
const wrapped = config?.includes('withFoliwake') ?? false;
|
|
36
|
+
return [
|
|
37
|
+
{ name: 'next.config uses withFoliwake()', ok: wrapped, detail: project.nextConfig ?? 'no next.config' },
|
|
38
|
+
{ name: 'route handler', ok: handler.length > 0, detail: handler.join(', ') || 'no route uses the handler' },
|
|
39
|
+
{ name: 'page route', ok: page.length > 0, detail: page.join(', ') || 'no page uses @foliwake/next/page' },
|
|
40
|
+
];
|
|
41
|
+
}
|
|
42
|
+
function envChecks(project, env) {
|
|
43
|
+
const names = envNames(project.cwd, env);
|
|
44
|
+
const preview = filesMentioning(project.cwd, project.appDir, "channel: 'preview'").length > 0;
|
|
45
|
+
const checks = [{ name: 'FOLIWAKE_URL is set', ok: names.has('FOLIWAKE_URL'), detail: 'env or .env.local' }];
|
|
46
|
+
if (preview) {
|
|
47
|
+
const ok = names.has('FOLIWAKE_PREVIEW_TOKEN');
|
|
48
|
+
checks.push({ name: 'FOLIWAKE_PREVIEW_TOKEN is set (preview route found)', ok, detail: 'value not shown' });
|
|
49
|
+
}
|
|
50
|
+
return checks;
|
|
51
|
+
}
|
|
52
|
+
function versionChecks(project) {
|
|
53
|
+
const versions = PACKAGES.map((name) => {
|
|
54
|
+
const manifest = read(path.join(project.cwd, 'node_modules', name, 'package.json'));
|
|
55
|
+
return `${name}@${manifest ? JSON.parse(manifest).version : 'missing'}`;
|
|
56
|
+
});
|
|
57
|
+
const distinct = new Set(versions.map((v) => v.split('@').at(-1)));
|
|
58
|
+
const ok = distinct.size === 1 && !distinct.has('missing');
|
|
59
|
+
return [{ name: '@foliwake packages share one version', ok, detail: versions.join(', ') }];
|
|
60
|
+
}
|
|
61
|
+
async function siteChecks(project, env, doFetch) {
|
|
62
|
+
const url = urlOf(project.cwd, env);
|
|
63
|
+
if (url === null)
|
|
64
|
+
return [];
|
|
65
|
+
try {
|
|
66
|
+
const facts = await verifySite(url, doFetch);
|
|
67
|
+
const detail = facts.note ?? `site ${facts.site}, X-Code-Release present`;
|
|
68
|
+
return [{ name: `${url} answers discovery and plain/2`, ok: facts.note === null, detail }];
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
return [{ name: `${url} answers discovery and plain/2`, ok: false, detail: error.message }];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Every check of an existing setup. */
|
|
75
|
+
export async function checkSetup(project, env, doFetch) {
|
|
76
|
+
const local = [...fileChecks(project), ...envChecks(project, env), ...versionChecks(project)];
|
|
77
|
+
return [...local, ...(await siteChecks(project, env, doFetch))];
|
|
78
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Lang } from './templates.js';
|
|
2
|
+
/** The oldest Next the package supports. */
|
|
3
|
+
export declare const MIN_NEXT: readonly [16, 2];
|
|
4
|
+
/** The app as found. */
|
|
5
|
+
export interface Project {
|
|
6
|
+
cwd: string;
|
|
7
|
+
/** `app` or `src/app`, relative to cwd. */
|
|
8
|
+
appDir: string;
|
|
9
|
+
/** `.` or `src`: where the generated helper module goes. */
|
|
10
|
+
sourceDir: string;
|
|
11
|
+
lang: Lang;
|
|
12
|
+
/** next.config file name, or null. */
|
|
13
|
+
nextConfig: string | null;
|
|
14
|
+
packageManager: string;
|
|
15
|
+
/** The Next version as declared or installed, or null when it is not a version number. */
|
|
16
|
+
nextVersion: string | null;
|
|
17
|
+
hasFoliwakeNext: boolean;
|
|
18
|
+
/** true clean, false dirty, null not a git checkout. */
|
|
19
|
+
gitClean: boolean | null;
|
|
20
|
+
}
|
|
21
|
+
/** A problem that stops init before it writes anything. */
|
|
22
|
+
export declare class InitError extends Error {
|
|
23
|
+
name: string;
|
|
24
|
+
}
|
|
25
|
+
/** `16.2.12`, `^16.2.0`, `~16.3` → [major, minor]; null for tags and ranges it cannot read. */
|
|
26
|
+
export declare function majorMinor(version: string | null): [number, number] | null;
|
|
27
|
+
/** Whether a version is at least MIN_NEXT; null when unknown. */
|
|
28
|
+
export declare function supportsNext(version: string | null): boolean | null;
|
|
29
|
+
/** Reads the app at `cwd`. Throws InitError when it is not a Next App Router app. */
|
|
30
|
+
export declare function detectProject(cwd: string): Project;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// What `init` learns about the app before it writes anything: Next and its version, the app folder, TypeScript,
|
|
2
|
+
// next.config, the package manager, @foliwake/next, git. Reads only; nothing here writes.
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
/** The oldest Next the package supports. */
|
|
7
|
+
export const MIN_NEXT = [16, 2];
|
|
8
|
+
const CONFIG_NAMES = ['next.config.ts', 'next.config.mjs', 'next.config.js', 'next.config.cjs'];
|
|
9
|
+
const LOCKFILES = [
|
|
10
|
+
['pnpm-lock.yaml', 'pnpm'],
|
|
11
|
+
['yarn.lock', 'yarn'],
|
|
12
|
+
['bun.lock', 'bun'],
|
|
13
|
+
['bun.lockb', 'bun'],
|
|
14
|
+
['package-lock.json', 'npm'],
|
|
15
|
+
];
|
|
16
|
+
/** A problem that stops init before it writes anything. */
|
|
17
|
+
export class InitError extends Error {
|
|
18
|
+
name = 'InitError';
|
|
19
|
+
}
|
|
20
|
+
function readJson(file) {
|
|
21
|
+
try {
|
|
22
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function dependencies(manifest) {
|
|
29
|
+
return { ...(manifest.devDependencies ?? {}), ...(manifest.dependencies ?? {}) };
|
|
30
|
+
}
|
|
31
|
+
function installedVersion(cwd, name) {
|
|
32
|
+
const manifest = readJson(path.join(cwd, 'node_modules', name, 'package.json'));
|
|
33
|
+
return typeof manifest?.version === 'string' ? manifest.version : null;
|
|
34
|
+
}
|
|
35
|
+
/** `16.2.12`, `^16.2.0`, `~16.3` → [major, minor]; null for tags and ranges it cannot read. */
|
|
36
|
+
export function majorMinor(version) {
|
|
37
|
+
const match = version === null ? null : /^[\^~>=v\s]*(\d+)\.(\d+)/.exec(version);
|
|
38
|
+
return match ? [Number(match[1]), Number(match[2])] : null;
|
|
39
|
+
}
|
|
40
|
+
/** Whether a version is at least MIN_NEXT; null when unknown. */
|
|
41
|
+
export function supportsNext(version) {
|
|
42
|
+
const parsed = majorMinor(version);
|
|
43
|
+
if (parsed === null)
|
|
44
|
+
return null;
|
|
45
|
+
return parsed[0] > MIN_NEXT[0] || (parsed[0] === MIN_NEXT[0] && parsed[1] >= MIN_NEXT[1]);
|
|
46
|
+
}
|
|
47
|
+
function appDirOf(cwd) {
|
|
48
|
+
if (existsSync(path.join(cwd, 'app')))
|
|
49
|
+
return 'app';
|
|
50
|
+
if (existsSync(path.join(cwd, 'src/app')))
|
|
51
|
+
return 'src/app';
|
|
52
|
+
throw new InitError('No app/ or src/app/ folder: @foliwake/next needs the App Router.');
|
|
53
|
+
}
|
|
54
|
+
function packageManagerOf(cwd) {
|
|
55
|
+
const agent = process.env.npm_config_user_agent?.split('/')[0];
|
|
56
|
+
const locked = LOCKFILES.find(([file]) => existsSync(path.join(cwd, file)));
|
|
57
|
+
return locked?.[1] ?? agent ?? 'npm';
|
|
58
|
+
}
|
|
59
|
+
function gitCleanOf(cwd) {
|
|
60
|
+
const status = spawnSync('git', ['status', '--porcelain'], { cwd, encoding: 'utf8' });
|
|
61
|
+
if (status.status !== 0)
|
|
62
|
+
return null;
|
|
63
|
+
return status.stdout.trim() === '';
|
|
64
|
+
}
|
|
65
|
+
/** Reads the app at `cwd`. Throws InitError when it is not a Next App Router app. */
|
|
66
|
+
export function detectProject(cwd) {
|
|
67
|
+
const manifest = readJson(path.join(cwd, 'package.json'));
|
|
68
|
+
if (manifest === null)
|
|
69
|
+
throw new InitError(`No package.json in ${cwd}: run init in the Next app's folder.`);
|
|
70
|
+
const deps = dependencies(manifest);
|
|
71
|
+
if (deps.next === undefined)
|
|
72
|
+
throw new InitError('This package.json has no "next" dependency.');
|
|
73
|
+
const appDir = appDirOf(cwd);
|
|
74
|
+
return {
|
|
75
|
+
cwd,
|
|
76
|
+
appDir,
|
|
77
|
+
sourceDir: appDir === 'src/app' ? 'src' : '.',
|
|
78
|
+
lang: existsSync(path.join(cwd, 'tsconfig.json')) ? 'ts' : 'js',
|
|
79
|
+
nextConfig: CONFIG_NAMES.find((name) => existsSync(path.join(cwd, name))) ?? null,
|
|
80
|
+
packageManager: packageManagerOf(cwd),
|
|
81
|
+
nextVersion: installedVersion(cwd, 'next') ?? deps.next ?? null,
|
|
82
|
+
hasFoliwakeNext: deps['@foliwake/next'] !== undefined,
|
|
83
|
+
gitClean: gitCleanOf(cwd),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** What init does with next.config. */
|
|
2
|
+
export type ConfigEdit = {
|
|
3
|
+
kind: 'wrapped';
|
|
4
|
+
text: string;
|
|
5
|
+
} | {
|
|
6
|
+
kind: 'present';
|
|
7
|
+
} | {
|
|
8
|
+
kind: 'manual';
|
|
9
|
+
reason: string;
|
|
10
|
+
};
|
|
11
|
+
/** The lines a person adds when the file is not one of the two forms. */
|
|
12
|
+
export declare const MANUAL_STEPS: string[];
|
|
13
|
+
/** The edit of a next.config text (an ES module). */
|
|
14
|
+
export declare function editNextConfig(text: string, file: string): ConfigEdit;
|
|
15
|
+
/** Whether the config text turns on cacheComponents. */
|
|
16
|
+
export declare function hasCacheComponents(text: string): boolean;
|
|
17
|
+
/** The line init adds to the config object, and prints when it cannot. */
|
|
18
|
+
export declare const CACHE_COMPONENTS_LINE = "cacheComponents: true,";
|
|
19
|
+
/** What init does with cacheComponents. */
|
|
20
|
+
export type CacheEdit = {
|
|
21
|
+
kind: 'added';
|
|
22
|
+
text: string;
|
|
23
|
+
} | {
|
|
24
|
+
kind: 'present';
|
|
25
|
+
} | {
|
|
26
|
+
kind: 'manual';
|
|
27
|
+
reason: string;
|
|
28
|
+
};
|
|
29
|
+
/** The cacheComponents edit of a next.config text (an ES module). */
|
|
30
|
+
export declare function addCacheComponents(text: string): CacheEdit;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// The conservative next.config edits, for two ESM forms only, `export default <name>;` and `export default { … };`
|
|
2
|
+
// (each also once wrapped in withFoliwake): wrap the default export in withFoliwake(), and turn on
|
|
3
|
+
// cacheComponents in the config object literal. Anything else (CommonJS, a function, a config built elsewhere) is
|
|
4
|
+
// left alone and init prints the lines to add by hand.
|
|
5
|
+
const IMPORT = "import { withFoliwake } from '@foliwake/next/config';";
|
|
6
|
+
const BY_NAME = /^export default ([A-Za-z_$][\w$]*);?[ \t]*$/m;
|
|
7
|
+
const OBJECT_START = /^export default \{/m;
|
|
8
|
+
/** The lines a person adds when the file is not one of the two forms. */
|
|
9
|
+
export const MANUAL_STEPS = [
|
|
10
|
+
IMPORT,
|
|
11
|
+
'Wrap the exported config: export default withFoliwake(yourConfig);',
|
|
12
|
+
'Turn on cacheComponents in it (the page route needs it): cacheComponents: true,',
|
|
13
|
+
];
|
|
14
|
+
function withImport(text) {
|
|
15
|
+
const imports = [...text.matchAll(/^import .*;[ \t]*$/gm)];
|
|
16
|
+
const last = imports.at(-1);
|
|
17
|
+
if (!last)
|
|
18
|
+
return `${IMPORT}\n${text}`;
|
|
19
|
+
const end = last.index + last[0].length;
|
|
20
|
+
return `${text.slice(0, end)}\n${IMPORT}${text.slice(end)}`;
|
|
21
|
+
}
|
|
22
|
+
function wrapByName(text, match) {
|
|
23
|
+
return text.replace(match[0], `export default withFoliwake(${match[1]});`);
|
|
24
|
+
}
|
|
25
|
+
// `export default {` … the last `}` of the file, followed only by `;` and whitespace.
|
|
26
|
+
function wrapObject(text, start) {
|
|
27
|
+
const end = text.lastIndexOf('}');
|
|
28
|
+
if (end < start || !/^;?\s*$/.test(text.slice(end + 1)))
|
|
29
|
+
return null;
|
|
30
|
+
const object = text.slice(start + 'export default '.length, end + 1);
|
|
31
|
+
return `${text.slice(0, start)}export default withFoliwake(${object});\n`;
|
|
32
|
+
}
|
|
33
|
+
/** The edit of a next.config text (an ES module). */
|
|
34
|
+
export function editNextConfig(text, file) {
|
|
35
|
+
if (text.includes('withFoliwake'))
|
|
36
|
+
return { kind: 'present' };
|
|
37
|
+
if (file.endsWith('.cjs') || /\bmodule\.exports\s*=/.test(text)) {
|
|
38
|
+
return { kind: 'manual', reason: 'CommonJS: @foliwake/next is an ES module; use next.config.mjs or .ts' };
|
|
39
|
+
}
|
|
40
|
+
const byName = BY_NAME.exec(text);
|
|
41
|
+
if (byName)
|
|
42
|
+
return { kind: 'wrapped', text: withImport(wrapByName(text, byName)) };
|
|
43
|
+
const object = OBJECT_START.exec(text);
|
|
44
|
+
const wrapped = object ? wrapObject(text, object.index) : null;
|
|
45
|
+
if (wrapped !== null)
|
|
46
|
+
return { kind: 'wrapped', text: withImport(wrapped) };
|
|
47
|
+
return { kind: 'manual', reason: 'the default export is not a name or an object literal' };
|
|
48
|
+
}
|
|
49
|
+
/** Whether the config text turns on cacheComponents. */
|
|
50
|
+
export function hasCacheComponents(text) {
|
|
51
|
+
return /cacheComponents\s*:\s*true/.test(text);
|
|
52
|
+
}
|
|
53
|
+
/** The line init adds to the config object, and prints when it cannot. */
|
|
54
|
+
export const CACHE_COMPONENTS_LINE = 'cacheComponents: true,';
|
|
55
|
+
const DEFAULT_OBJECT = /^export default (?:withFoliwake\()?\{/m;
|
|
56
|
+
const DEFAULT_NAME = /^export default (?:withFoliwake\()?([A-Za-z_$][\w$]*)\)?;?[ \t]*$/m;
|
|
57
|
+
function escaped(name) {
|
|
58
|
+
return name.replace(/\$/g, '\\$');
|
|
59
|
+
}
|
|
60
|
+
/** Where the `{` of `const <name>[: Type] = {` is, or null. */
|
|
61
|
+
function declaredObjectBrace(text, name) {
|
|
62
|
+
const declaration = new RegExp(`^(?:const|let|var) ${escaped(name)}(?:\\s*:\\s*[\\w.]+)?\\s*=\\s*\\{`, 'm');
|
|
63
|
+
const match = declaration.exec(text);
|
|
64
|
+
return match ? match.index + match[0].length - 1 : null;
|
|
65
|
+
}
|
|
66
|
+
/** Where the `{` of the exported config object literal is, or null when the export is another form. */
|
|
67
|
+
function configObjectBrace(text) {
|
|
68
|
+
const object = DEFAULT_OBJECT.exec(text);
|
|
69
|
+
if (object)
|
|
70
|
+
return object.index + object[0].length - 1;
|
|
71
|
+
const byName = DEFAULT_NAME.exec(text);
|
|
72
|
+
return byName ? declaredObjectBrace(text, byName[1]) : null;
|
|
73
|
+
}
|
|
74
|
+
/** The indentation of the first non-blank line after `at`, or two spaces. */
|
|
75
|
+
function indentAfter(text, at) {
|
|
76
|
+
const next = /\n([ \t]*)\S/.exec(text.slice(at));
|
|
77
|
+
return next && next[1] ? next[1] : ' ';
|
|
78
|
+
}
|
|
79
|
+
// `{\n a: 1,` gets a line of its own; `{}` becomes `{ cacheComponents: true }`; `{ a: 1 }` gets it first.
|
|
80
|
+
function insertAfterBrace(text, brace) {
|
|
81
|
+
const head = text.slice(0, brace + 1);
|
|
82
|
+
const rest = text.slice(brace + 1);
|
|
83
|
+
if (rest.startsWith('\n'))
|
|
84
|
+
return `${head}\n${indentAfter(text, brace)}${CACHE_COMPONENTS_LINE}${rest}`;
|
|
85
|
+
if (/^\s*\}/.test(rest))
|
|
86
|
+
return `${head} cacheComponents: true ${rest.trimStart()}`;
|
|
87
|
+
return `${head} ${CACHE_COMPONENTS_LINE} ${rest.trimStart()}`;
|
|
88
|
+
}
|
|
89
|
+
/** The cacheComponents edit of a next.config text (an ES module). */
|
|
90
|
+
export function addCacheComponents(text) {
|
|
91
|
+
if (hasCacheComponents(text))
|
|
92
|
+
return { kind: 'present' };
|
|
93
|
+
if (/\bcacheComponents\b/.test(text))
|
|
94
|
+
return { kind: 'manual', reason: 'cacheComponents is set to another value' };
|
|
95
|
+
const brace = configObjectBrace(text);
|
|
96
|
+
if (brace === null)
|
|
97
|
+
return { kind: 'manual', reason: 'the exported config is not an object literal init can find' };
|
|
98
|
+
return { kind: 'added', text: insertAfterBrace(text, brace) };
|
|
99
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** What the person asked for. */
|
|
2
|
+
export interface InitOptions {
|
|
3
|
+
command: 'init' | 'help';
|
|
4
|
+
url: string | null;
|
|
5
|
+
yes: boolean;
|
|
6
|
+
preview: boolean;
|
|
7
|
+
hook: boolean;
|
|
8
|
+
mount: string | null;
|
|
9
|
+
dryRun: boolean;
|
|
10
|
+
json: boolean;
|
|
11
|
+
check: boolean;
|
|
12
|
+
force: boolean;
|
|
13
|
+
cwd: string;
|
|
14
|
+
ignoreGitChanges: boolean;
|
|
15
|
+
}
|
|
16
|
+
/** Bad flags: exit 1 with the message. */
|
|
17
|
+
export declare class UsageError extends Error {
|
|
18
|
+
name: string;
|
|
19
|
+
}
|
|
20
|
+
export declare const USAGE = "Usage: npx @foliwake/next init [options]\n\nSets up Foliwake pages in this Next.js app: FOLIWAKE_URL in .env.local, withFoliwake() in next.config,\napp/foliwake/[...path]/route.ts (code, media, hook) and app/[...path]/page.tsx (site pages).\n\n --url <https://site> the site's live URL (FOLIWAKE_INIT_URL)\n --preview add a preview route behind a dev-only isAuthor() (FOLIWAKE_INIT_PREVIEW=1)\n --hook add FOLIWAKE_HOOK_SECRET= to .env.local (FOLIWAKE_INIT_HOOK=1)\n --mount </pages> serve pages under this path instead of the root (FOLIWAKE_INIT_MOUNT)\n --yes ask nothing (CI=1 too); needs --url\n --dry-run show the plan, write nothing\n --json print the result as JSON\n --check check an existing setup instead of writing\n --force overwrite files that init generated before\n --ignore-git-changes run on a working tree with uncommitted changes\n --cwd <dir> the app's folder (default: the current one)\n\nExit codes: 0 done, 1 error, 2 input needed (no --url with --yes or without a terminal).";
|
|
21
|
+
/** The options of `argv` (without node and the script) and `env`. Throws UsageError. */
|
|
22
|
+
export declare function parseOptions(argv: string[], env: NodeJS.ProcessEnv, cwd: string): InitOptions;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// The flags of `npx @foliwake/next init`, each with an environment equivalent (FOLIWAKE_INIT_*) for CI.
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
/** Bad flags: exit 1 with the message. */
|
|
4
|
+
export class UsageError extends Error {
|
|
5
|
+
name = 'UsageError';
|
|
6
|
+
}
|
|
7
|
+
export const USAGE = `Usage: npx @foliwake/next init [options]
|
|
8
|
+
|
|
9
|
+
Sets up Foliwake pages in this Next.js app: FOLIWAKE_URL in .env.local, withFoliwake() in next.config,
|
|
10
|
+
app/foliwake/[...path]/route.ts (code, media, hook) and app/[...path]/page.tsx (site pages).
|
|
11
|
+
|
|
12
|
+
--url <https://site> the site's live URL (FOLIWAKE_INIT_URL)
|
|
13
|
+
--preview add a preview route behind a dev-only isAuthor() (FOLIWAKE_INIT_PREVIEW=1)
|
|
14
|
+
--hook add FOLIWAKE_HOOK_SECRET= to .env.local (FOLIWAKE_INIT_HOOK=1)
|
|
15
|
+
--mount </pages> serve pages under this path instead of the root (FOLIWAKE_INIT_MOUNT)
|
|
16
|
+
--yes ask nothing (CI=1 too); needs --url
|
|
17
|
+
--dry-run show the plan, write nothing
|
|
18
|
+
--json print the result as JSON
|
|
19
|
+
--check check an existing setup instead of writing
|
|
20
|
+
--force overwrite files that init generated before
|
|
21
|
+
--ignore-git-changes run on a working tree with uncommitted changes
|
|
22
|
+
--cwd <dir> the app's folder (default: the current one)
|
|
23
|
+
|
|
24
|
+
Exit codes: 0 done, 1 error, 2 input needed (no --url with --yes or without a terminal).`;
|
|
25
|
+
const FLAGS = {
|
|
26
|
+
url: { type: 'string' },
|
|
27
|
+
yes: { type: 'boolean' },
|
|
28
|
+
preview: { type: 'boolean' },
|
|
29
|
+
hook: { type: 'boolean' },
|
|
30
|
+
mount: { type: 'string' },
|
|
31
|
+
'dry-run': { type: 'boolean' },
|
|
32
|
+
json: { type: 'boolean' },
|
|
33
|
+
check: { type: 'boolean' },
|
|
34
|
+
force: { type: 'boolean' },
|
|
35
|
+
cwd: { type: 'string' },
|
|
36
|
+
'ignore-git-changes': { type: 'boolean' },
|
|
37
|
+
help: { type: 'boolean', short: 'h' },
|
|
38
|
+
};
|
|
39
|
+
const truthy = (value) => value !== undefined && /^(1|true|yes)$/i.test(value);
|
|
40
|
+
function commandOf(positionals, help) {
|
|
41
|
+
if (help || positionals.length === 0 || positionals[0] === 'help')
|
|
42
|
+
return 'help';
|
|
43
|
+
if (positionals[0] !== 'init' || positionals.length > 1) {
|
|
44
|
+
throw new UsageError(`Unknown command "${positionals.join(' ')}". ${USAGE.split('\n')[0]}`);
|
|
45
|
+
}
|
|
46
|
+
return 'init';
|
|
47
|
+
}
|
|
48
|
+
function parsedArgs(argv) {
|
|
49
|
+
try {
|
|
50
|
+
return parseArgs({ args: argv, options: FLAGS, allowPositionals: true, strict: true });
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
throw new UsageError(error.message);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** The options of `argv` (without node and the script) and `env`. Throws UsageError. */
|
|
57
|
+
export function parseOptions(argv, env, cwd) {
|
|
58
|
+
const { values, positionals } = parsedArgs(argv);
|
|
59
|
+
return {
|
|
60
|
+
command: commandOf(positionals, values.help),
|
|
61
|
+
url: values.url ?? env.FOLIWAKE_INIT_URL ?? null,
|
|
62
|
+
yes: values.yes ?? (truthy(env.FOLIWAKE_INIT_YES) || truthy(env.CI)),
|
|
63
|
+
preview: values.preview ?? truthy(env.FOLIWAKE_INIT_PREVIEW),
|
|
64
|
+
hook: values.hook ?? truthy(env.FOLIWAKE_INIT_HOOK),
|
|
65
|
+
mount: values.mount ?? env.FOLIWAKE_INIT_MOUNT ?? null,
|
|
66
|
+
dryRun: values['dry-run'] ?? false,
|
|
67
|
+
json: values.json ?? false,
|
|
68
|
+
check: values.check ?? false,
|
|
69
|
+
force: values.force ?? false,
|
|
70
|
+
cwd: values.cwd ?? cwd,
|
|
71
|
+
ignoreGitChanges: values['ignore-git-changes'] ?? false,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Project } from './detect.js';
|
|
2
|
+
/** One step of the plan. */
|
|
3
|
+
export type Step = {
|
|
4
|
+
kind: 'file';
|
|
5
|
+
path: string;
|
|
6
|
+
content: string;
|
|
7
|
+
what: string;
|
|
8
|
+
} | {
|
|
9
|
+
kind: 'env';
|
|
10
|
+
path: string;
|
|
11
|
+
lines: string[];
|
|
12
|
+
onlyIfExists: boolean;
|
|
13
|
+
what: string;
|
|
14
|
+
} | {
|
|
15
|
+
kind: 'next-config';
|
|
16
|
+
path: string;
|
|
17
|
+
create: string | null;
|
|
18
|
+
what: string;
|
|
19
|
+
};
|
|
20
|
+
/** The choices init works with. */
|
|
21
|
+
export interface PlanInput {
|
|
22
|
+
url: string;
|
|
23
|
+
preview: boolean;
|
|
24
|
+
hook: boolean;
|
|
25
|
+
/** `/pages`, or null for the root. */
|
|
26
|
+
mount: string | null;
|
|
27
|
+
}
|
|
28
|
+
/** Every step, in the order they are printed. */
|
|
29
|
+
export declare function planSteps(project: Project, input: PlanInput): Step[];
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// What init will do, computed before anything is written: the files, the env lines and the next.config change.
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { isAuthorFile, livePageFile, nextConfigFile, previewPageFile, routeFile } from './templates.js';
|
|
4
|
+
const posix = path.posix;
|
|
5
|
+
/** The author check module, without its extension (as imports name it). */
|
|
6
|
+
function helperModule(project) {
|
|
7
|
+
return posix.join(project.sourceDir, 'foliwake', 'is-author');
|
|
8
|
+
}
|
|
9
|
+
/** The relative import of the author check from a file of the app. */
|
|
10
|
+
function authorImportFrom(project, file) {
|
|
11
|
+
return posix.relative(posix.dirname(file), helperModule(project));
|
|
12
|
+
}
|
|
13
|
+
function pageDir(mount) {
|
|
14
|
+
return mount === null ? '[...path]' : posix.join(mount.slice(1), '[[...path]]');
|
|
15
|
+
}
|
|
16
|
+
function envLines(input) {
|
|
17
|
+
return [
|
|
18
|
+
`FOLIWAKE_URL=${input.url}`,
|
|
19
|
+
...(input.preview ? ['FOLIWAKE_PREVIEW_TOKEN='] : []),
|
|
20
|
+
...(input.hook ? ['FOLIWAKE_HOOK_SECRET='] : []),
|
|
21
|
+
];
|
|
22
|
+
}
|
|
23
|
+
function fileStep(file, content, what) {
|
|
24
|
+
return { kind: 'file', path: file, content, what };
|
|
25
|
+
}
|
|
26
|
+
function routeStep(project, input) {
|
|
27
|
+
const file = posix.join(project.appDir, 'foliwake/[...path]', `route.${project.lang}`);
|
|
28
|
+
const author = input.preview ? authorImportFrom(project, file) : null;
|
|
29
|
+
return fileStep(file, routeFile(author), 'code, media and hook routes');
|
|
30
|
+
}
|
|
31
|
+
function pageExtension(project) {
|
|
32
|
+
return project.lang === 'ts' ? 'tsx' : 'jsx';
|
|
33
|
+
}
|
|
34
|
+
function livePageStep(project, input) {
|
|
35
|
+
const file = posix.join(project.appDir, pageDir(input.mount), `page.${pageExtension(project)}`);
|
|
36
|
+
return fileStep(file, livePageFile(input.mount), 'site pages (your own routes win)');
|
|
37
|
+
}
|
|
38
|
+
function previewSteps(project) {
|
|
39
|
+
const page = posix.join(project.appDir, 'preview/[[...path]]', `page.${pageExtension(project)}`);
|
|
40
|
+
const helper = `${helperModule(project)}.${project.lang}`;
|
|
41
|
+
return [
|
|
42
|
+
fileStep(page, previewPageFile(authorImportFrom(project, page)), 'preview pages, behind isAuthor()'),
|
|
43
|
+
fileStep(helper, isAuthorFile(project.lang), 'isAuthor(): development only; replace it with your sign-in'),
|
|
44
|
+
];
|
|
45
|
+
}
|
|
46
|
+
function configStep(project) {
|
|
47
|
+
if (project.nextConfig !== null) {
|
|
48
|
+
return { kind: 'next-config', path: project.nextConfig, create: null, what: 'wrapped in withFoliwake()' };
|
|
49
|
+
}
|
|
50
|
+
const file = project.lang === 'ts' ? 'next.config.ts' : 'next.config.mjs';
|
|
51
|
+
return { kind: 'next-config', path: file, create: nextConfigFile(), what: 'withFoliwake({ cacheComponents: true })' };
|
|
52
|
+
}
|
|
53
|
+
/** Every step, in the order they are printed. */
|
|
54
|
+
export function planSteps(project, input) {
|
|
55
|
+
const lines = envLines(input);
|
|
56
|
+
return [
|
|
57
|
+
{ kind: 'env', path: '.env.local', lines, onlyIfExists: false, what: 'FOLIWAKE_URL (secrets: names only)' },
|
|
58
|
+
{ kind: 'env', path: '.env.example', lines, onlyIfExists: true, what: 'the same names' },
|
|
59
|
+
configStep(project),
|
|
60
|
+
routeStep(project, input),
|
|
61
|
+
livePageStep(project, input),
|
|
62
|
+
...(input.preview ? previewSteps(project) : []),
|
|
63
|
+
];
|
|
64
|
+
}
|