@clegra/sdk 0.0.0-stage → 0.1.0-next.0
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 +152 -0
- package/LICENSE +21 -0
- package/NOTICE.md +25 -0
- package/README.md +258 -2
- package/dist/spec/kinds.json +211 -0
- package/dist/spec/schema/clegra.schema.json +1249 -0
- package/dist/spec/src/cli.d.ts +2 -0
- package/dist/spec/src/cli.js +21 -0
- package/dist/spec/src/cli.js.map +1 -0
- package/dist/spec/src/conformance.d.ts +34 -0
- package/dist/spec/src/conformance.js +703 -0
- package/dist/spec/src/conformance.js.map +1 -0
- package/dist/spec/src/init/index.d.ts +31 -0
- package/dist/spec/src/init/index.js +151 -0
- package/dist/spec/src/init/index.js.map +1 -0
- package/dist/spec/src/init/next-config.d.ts +19 -0
- package/dist/spec/src/init/next-config.js +77 -0
- package/dist/spec/src/init/next-config.js.map +1 -0
- package/dist/spec/src/init/project.d.ts +44 -0
- package/dist/spec/src/init/project.js +141 -0
- package/dist/spec/src/init/project.js.map +1 -0
- package/dist/spec/src/init/templates.d.ts +20 -0
- package/dist/spec/src/init/templates.js +166 -0
- package/dist/spec/src/init/templates.js.map +1 -0
- package/dist/spec/src/init/ui.d.ts +30 -0
- package/dist/spec/src/init/ui.js +82 -0
- package/dist/spec/src/init/ui.js.map +1 -0
- package/dist/spec/src/kinds.d.ts +89 -0
- package/dist/spec/src/kinds.js +319 -0
- package/dist/spec/src/kinds.js.map +1 -0
- package/dist/spec/src/protocol.d.ts +50 -0
- package/dist/spec/src/protocol.js +52 -0
- package/dist/spec/src/protocol.js.map +1 -0
- package/dist/spec/src/rules.d.ts +132 -0
- package/dist/spec/src/rules.js +282 -0
- package/dist/spec/src/rules.js.map +1 -0
- package/dist/src/auth.d.ts +371 -0
- package/dist/src/auth.js +964 -0
- package/dist/src/auth.js.map +1 -0
- package/dist/src/define.d.ts +249 -0
- package/dist/src/define.js +83 -0
- package/dist/src/define.js.map +1 -0
- package/dist/src/embed.d.ts +98 -0
- package/dist/src/embed.js +256 -0
- package/dist/src/embed.js.map +1 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.js +11 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/labels.d.ts +10 -0
- package/dist/src/labels.js +22 -0
- package/dist/src/labels.js.map +1 -0
- package/dist/src/manifest.d.ts +499 -0
- package/dist/src/manifest.js +188 -0
- package/dist/src/manifest.js.map +1 -0
- package/dist/src/meaning.d.ts +64 -0
- package/dist/src/meaning.js +116 -0
- package/dist/src/meaning.js.map +1 -0
- package/dist/src/next/index.d.ts +101 -0
- package/dist/src/next/index.js +187 -0
- package/dist/src/next/index.js.map +1 -0
- package/dist/src/node.d.ts +14 -0
- package/dist/src/node.js +64 -0
- package/dist/src/node.js.map +1 -0
- package/dist/src/server.d.ts +229 -0
- package/dist/src/server.js +2256 -0
- package/dist/src/server.js.map +1 -0
- package/dist/src/store.d.ts +129 -0
- package/dist/src/store.js +213 -0
- package/dist/src/store.js.map +1 -0
- package/dist/src/testing.d.ts +133 -0
- package/dist/src/testing.js +81 -0
- package/dist/src/testing.js.map +1 -0
- package/dist/src/types.d.ts +352 -0
- package/dist/src/types.js +2 -0
- package/dist/src/types.js.map +1 -0
- package/dist/src/view.d.ts +35 -0
- package/dist/src/view.js +442 -0
- package/dist/src/view.js.map +1 -0
- package/docs/quickstart.md +350 -0
- package/docs/spec.md +997 -0
- package/package.json +89 -4
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What `clegra init` needs to know of an existing Next.js project, read from its files: never guessed.
|
|
3
|
+
* A project that isn't a Next.js App Router project is an `InitError` with what is missing.
|
|
4
|
+
*/
|
|
5
|
+
export declare class InitError extends Error {
|
|
6
|
+
constructor(message: string);
|
|
7
|
+
}
|
|
8
|
+
export type Project = {
|
|
9
|
+
root: string;
|
|
10
|
+
/** The version of `next` installed (node_modules), else the range in package.json. */
|
|
11
|
+
nextVersion: string;
|
|
12
|
+
/** The App Router directory, relative to root: `app` or `src/app`. */
|
|
13
|
+
appDir: "app" | "src/app";
|
|
14
|
+
/** TypeScript (a tsconfig.json) or plain JavaScript. */
|
|
15
|
+
ts: boolean;
|
|
16
|
+
/** The existing next.config file, relative to root, or null. */
|
|
17
|
+
nextConfig: string | null;
|
|
18
|
+
/** The `paths` alias that points at the folder of clegra.ts (`@/*` → `@/`), or null: then imports are relative. */
|
|
19
|
+
alias: string | null;
|
|
20
|
+
/** The package name, made a valid Clegra app id. */
|
|
21
|
+
appName: string;
|
|
22
|
+
appTitle: string;
|
|
23
|
+
/** Dependencies the generated files import that package.json lacks. */
|
|
24
|
+
missing: string[];
|
|
25
|
+
/** The installed zod's major version when it is not 4 (@clegra/sdk needs zod 4), else null. */
|
|
26
|
+
oldZod: string | null;
|
|
27
|
+
/** The port `next dev` uses (from the dev script's -p/--port), default 3000. */
|
|
28
|
+
port: number;
|
|
29
|
+
/** The proxy (or deprecated middleware) file, which may stand in front of /mcp. */
|
|
30
|
+
proxy: string | null;
|
|
31
|
+
/** Whether .gitignore keeps .env.local out of git. */
|
|
32
|
+
envIgnored: boolean;
|
|
33
|
+
};
|
|
34
|
+
/** JSON with comments and trailing commas (tsconfig.json), read as JSON. */
|
|
35
|
+
export declare function parseJsonc(text: string): unknown;
|
|
36
|
+
/** A package name as a Clegra app id: `[a-z][a-z0-9-]{1,39}`. */
|
|
37
|
+
export declare function appNameOf(packageName: unknown): string;
|
|
38
|
+
export declare function titleOf(name: string): string;
|
|
39
|
+
export declare function detectProject(root: string): Project;
|
|
40
|
+
/** Where clegra.ts goes (beside app/: the project root, or src/), relative to root. */
|
|
41
|
+
export declare function clegraPath(project: Project): string;
|
|
42
|
+
export declare function routePath(project: Project): string;
|
|
43
|
+
/** How the route imports clegra.ts: through the alias, else a relative path. */
|
|
44
|
+
export declare function importPathFor(project: Project): string;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, posix, relative, resolve, sep } from "node:path";
|
|
3
|
+
/**
|
|
4
|
+
* What `clegra init` needs to know of an existing Next.js project, read from its files: never guessed.
|
|
5
|
+
* A project that isn't a Next.js App Router project is an `InitError` with what is missing.
|
|
6
|
+
*/
|
|
7
|
+
export class InitError extends Error {
|
|
8
|
+
constructor(message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "InitError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
const CONFIG_FILES = ["next.config.ts", "next.config.mts", "next.config.mjs", "next.config.js"];
|
|
14
|
+
/** JSON with comments and trailing commas (tsconfig.json), read as JSON. */
|
|
15
|
+
export function parseJsonc(text) {
|
|
16
|
+
let out = "";
|
|
17
|
+
for (let i = 0; i < text.length; i++) {
|
|
18
|
+
const c = text[i];
|
|
19
|
+
if (c === '"') {
|
|
20
|
+
const start = i;
|
|
21
|
+
for (i++; i < text.length && text[i] !== '"'; i++)
|
|
22
|
+
if (text[i] === "\\")
|
|
23
|
+
i++;
|
|
24
|
+
out += text.slice(start, i + 1);
|
|
25
|
+
}
|
|
26
|
+
else if (c === "/" && text[i + 1] === "/") {
|
|
27
|
+
while (i < text.length && text[i] !== "\n")
|
|
28
|
+
i++;
|
|
29
|
+
out += "\n";
|
|
30
|
+
}
|
|
31
|
+
else if (c === "/" && text[i + 1] === "*") {
|
|
32
|
+
i = text.indexOf("*/", i + 2);
|
|
33
|
+
if (i < 0)
|
|
34
|
+
break;
|
|
35
|
+
i++;
|
|
36
|
+
}
|
|
37
|
+
else
|
|
38
|
+
out += c;
|
|
39
|
+
}
|
|
40
|
+
return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
|
|
41
|
+
}
|
|
42
|
+
function readJson(path, jsonc = false) {
|
|
43
|
+
if (!existsSync(path))
|
|
44
|
+
return null;
|
|
45
|
+
const text = readFileSync(path, "utf8");
|
|
46
|
+
try {
|
|
47
|
+
return (jsonc ? parseJsonc(text) : JSON.parse(text));
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
throw new InitError(`${path} is not valid JSON${jsonc ? " (comments and trailing commas are fine)" : ""}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** A package name as a Clegra app id: `[a-z][a-z0-9-]{1,39}`. */
|
|
54
|
+
export function appNameOf(packageName) {
|
|
55
|
+
const base = typeof packageName === "string" ? packageName.replace(/^@[^/]+\//, "") : "";
|
|
56
|
+
const name = base.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+/g, "-").slice(0, 40).replace(/-+$/, "");
|
|
57
|
+
return /^[a-z][a-z0-9-]{1,39}$/.test(name) ? name : "my-app";
|
|
58
|
+
}
|
|
59
|
+
export function titleOf(name) {
|
|
60
|
+
return name.split("-").filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join(" ");
|
|
61
|
+
}
|
|
62
|
+
/** The alias in tsconfig/jsconfig `paths` whose target is `dir` (`"@/*": ["./src/*"]` for src/), or null. */
|
|
63
|
+
function aliasFor(root, dir, config) {
|
|
64
|
+
const options = (config?.compilerOptions ?? {});
|
|
65
|
+
const base = resolve(root, options.baseUrl ?? ".");
|
|
66
|
+
for (const [key, targets] of Object.entries(options.paths ?? {})) {
|
|
67
|
+
if (!key.endsWith("/*") || !Array.isArray(targets))
|
|
68
|
+
continue;
|
|
69
|
+
const target = targets[0];
|
|
70
|
+
if (typeof target !== "string" || !target.endsWith("*"))
|
|
71
|
+
continue;
|
|
72
|
+
if (resolve(base, target.slice(0, -1)) === resolve(dir))
|
|
73
|
+
return key.slice(0, -1);
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
function portOf(devScript) {
|
|
78
|
+
const m = typeof devScript === "string" ? /(?:^|\s)(?:-p|--port)[ =](\d{2,5})\b/.exec(devScript) : null;
|
|
79
|
+
return m ? Number(m[1]) : 3000;
|
|
80
|
+
}
|
|
81
|
+
function ignoresEnvLocal(root) {
|
|
82
|
+
const path = join(root, ".gitignore");
|
|
83
|
+
if (!existsSync(path))
|
|
84
|
+
return false;
|
|
85
|
+
const lines = readFileSync(path, "utf8").split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith("#"));
|
|
86
|
+
return lines.some((l) => [".env*", ".env.local", "/.env.local", ".env*.local", "*.local", ".env.*", "/.env*"].includes(l));
|
|
87
|
+
}
|
|
88
|
+
export function detectProject(root) {
|
|
89
|
+
const pkg = readJson(join(root, "package.json"));
|
|
90
|
+
if (!pkg)
|
|
91
|
+
throw new InitError(`no package.json in ${root}: run clegra init in the folder of an existing Next.js app`);
|
|
92
|
+
const deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
|
|
93
|
+
if (!deps.next)
|
|
94
|
+
throw new InitError(`${join(root, "package.json")} has no "next" dependency: clegra init adds @clegra/sdk to an existing Next.js app (for another server, see listen() in @clegra/sdk/node)`);
|
|
95
|
+
const installed = readJson(join(root, "node_modules", "next", "package.json"));
|
|
96
|
+
const nextVersion = typeof installed?.version === "string" ? installed.version : deps.next;
|
|
97
|
+
const appDir = existsSync(join(root, "app")) ? "app" : existsSync(join(root, "src", "app")) ? "src/app" : null;
|
|
98
|
+
if (!appDir)
|
|
99
|
+
throw new InitError(`no app/ or src/app/ folder in ${root}: clegra init needs the App Router (a Pages Router app can mount app.fetch in an API route by hand)`);
|
|
100
|
+
const ts = existsSync(join(root, "tsconfig.json"));
|
|
101
|
+
const nextConfig = CONFIG_FILES.find((f) => existsSync(join(root, f))) ?? null;
|
|
102
|
+
const clegraDir = appDir === "src/app" ? join(root, "src") : root;
|
|
103
|
+
const alias = aliasFor(root, clegraDir, readJson(join(root, ts ? "tsconfig.json" : "jsconfig.json"), true));
|
|
104
|
+
const appName = appNameOf(pkg.name);
|
|
105
|
+
const missing = ["@clegra/sdk", "zod"].filter((d) => !deps[d]);
|
|
106
|
+
const zod = readJson(join(root, "node_modules", "zod", "package.json"));
|
|
107
|
+
const zodMajor = typeof zod?.version === "string" ? zod.version.split(".")[0] : null;
|
|
108
|
+
const proxy = ["proxy", "middleware"].flatMap((n) => ["ts", "js", "mjs"].flatMap((e) => [`${n}.${e}`, `src/${n}.${e}`])).find((f) => existsSync(join(root, f))) ?? null;
|
|
109
|
+
return {
|
|
110
|
+
root,
|
|
111
|
+
nextVersion,
|
|
112
|
+
appDir,
|
|
113
|
+
ts,
|
|
114
|
+
nextConfig,
|
|
115
|
+
alias,
|
|
116
|
+
appName,
|
|
117
|
+
appTitle: titleOf(appName),
|
|
118
|
+
missing,
|
|
119
|
+
oldZod: zodMajor && zodMajor !== "4" ? zod.version : null,
|
|
120
|
+
port: portOf(pkg.scripts?.dev),
|
|
121
|
+
proxy,
|
|
122
|
+
envIgnored: ignoresEnvLocal(root),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/** Where clegra.ts goes (beside app/: the project root, or src/), relative to root. */
|
|
126
|
+
export function clegraPath(project) {
|
|
127
|
+
return posix.join(project.appDir === "src/app" ? "src" : ".", `clegra.${project.ts ? "ts" : "js"}`).replace(/^\.\//, "");
|
|
128
|
+
}
|
|
129
|
+
export function routePath(project) {
|
|
130
|
+
return `${project.appDir}/api/clegra/[...path]/route.${project.ts ? "ts" : "js"}`;
|
|
131
|
+
}
|
|
132
|
+
/** How the route imports clegra.ts: through the alias, else a relative path. */
|
|
133
|
+
export function importPathFor(project) {
|
|
134
|
+
if (project.alias)
|
|
135
|
+
return `${project.alias}clegra`;
|
|
136
|
+
const from = dirname(join(project.root, routePath(project)));
|
|
137
|
+
const to = join(project.root, clegraPath(project)).replace(/\.(ts|js)$/, "");
|
|
138
|
+
const rel = relative(from, to).split(sep).join("/");
|
|
139
|
+
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
140
|
+
}
|
|
141
|
+
//# sourceMappingURL=project.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"project.js","sourceRoot":"","sources":["../../../../spec/src/init/project.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,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAA;IAC5E,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IACnD,OAAO,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAA;AAC/C,CAAC","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\"\nimport { dirname, join, posix, relative, resolve, sep } from \"node:path\"\n\n/**\n * What `clegra init` needs to know of an existing Next.js project, read from its files: never guessed.\n * A project that isn't a Next.js App Router project is an `InitError` with what is missing.\n */\n\nexport class InitError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"InitError\"\n }\n}\n\nexport type Project = {\n root: string\n /** The version of `next` installed (node_modules), else the range in package.json. */\n nextVersion: string\n /** The App Router directory, relative to root: `app` or `src/app`. */\n appDir: \"app\" | \"src/app\"\n /** TypeScript (a tsconfig.json) or plain JavaScript. */\n ts: boolean\n /** The existing next.config file, relative to root, or null. */\n nextConfig: string | null\n /** The `paths` alias that points at the folder of clegra.ts (`@/*` → `@/`), or null: then imports are relative. */\n alias: string | null\n /** The package name, made a valid Clegra app id. */\n appName: string\n appTitle: string\n /** Dependencies the generated files import that package.json lacks. */\n missing: string[]\n /** The installed zod's major version when it is not 4 (@clegra/sdk needs zod 4), else null. */\n oldZod: string | null\n /** The port `next dev` uses (from the dev script's -p/--port), default 3000. */\n port: number\n /** The proxy (or deprecated middleware) file, which may stand in front of /mcp. */\n proxy: string | null\n /** Whether .gitignore keeps .env.local out of git. */\n envIgnored: boolean\n}\n\nconst CONFIG_FILES = [\"next.config.ts\", \"next.config.mts\", \"next.config.mjs\", \"next.config.js\"]\n\n/** JSON with comments and trailing commas (tsconfig.json), read as JSON. */\nexport function parseJsonc(text: string): unknown {\n let out = \"\"\n for (let i = 0; i < text.length; i++) {\n const c = text[i]!\n if (c === '\"') {\n const start = i\n for (i++; i < text.length && text[i] !== '\"'; i++) if (text[i] === \"\\\\\") i++\n out += text.slice(start, i + 1)\n } else if (c === \"/\" && text[i + 1] === \"/\") {\n while (i < text.length && text[i] !== \"\\n\") i++\n out += \"\\n\"\n } else if (c === \"/\" && text[i + 1] === \"*\") {\n i = text.indexOf(\"*/\", i + 2)\n if (i < 0) break\n i++\n } else out += c\n }\n return JSON.parse(out.replace(/,(\\s*[}\\]])/g, \"$1\"))\n}\n\nfunction readJson(path: string, jsonc = false): Record<string, unknown> | null {\n if (!existsSync(path)) return null\n const text = readFileSync(path, \"utf8\")\n try {\n return (jsonc ? parseJsonc(text) : JSON.parse(text)) as Record<string, unknown>\n } catch {\n throw new InitError(`${path} is not valid JSON${jsonc ? \" (comments and trailing commas are fine)\" : \"\"}`)\n }\n}\n\n/** A package name as a Clegra app id: `[a-z][a-z0-9-]{1,39}`. */\nexport function appNameOf(packageName: unknown): string {\n const base = typeof packageName === \"string\" ? packageName.replace(/^@[^/]+\\//, \"\") : \"\"\n const name = base.toLowerCase().replace(/[^a-z0-9-]+/g, \"-\").replace(/^[^a-z]+/, \"\").replace(/-+/g, \"-\").slice(0, 40).replace(/-+$/, \"\")\n return /^[a-z][a-z0-9-]{1,39}$/.test(name) ? name : \"my-app\"\n}\n\nexport function titleOf(name: string): string {\n return name.split(\"-\").filter(Boolean).map((w) => w[0]!.toUpperCase() + w.slice(1)).join(\" \")\n}\n\n/** The alias in tsconfig/jsconfig `paths` whose target is `dir` (`\"@/*\": [\"./src/*\"]` for src/), or null. */\nfunction aliasFor(root: string, dir: string, config: Record<string, unknown> | null): string | null {\n const options = (config?.compilerOptions ?? {}) as { baseUrl?: string; paths?: Record<string, string[]> }\n const base = resolve(root, options.baseUrl ?? \".\")\n for (const [key, targets] of Object.entries(options.paths ?? {})) {\n if (!key.endsWith(\"/*\") || !Array.isArray(targets)) continue\n const target = targets[0]\n if (typeof target !== \"string\" || !target.endsWith(\"*\")) continue\n if (resolve(base, target.slice(0, -1)) === resolve(dir)) return key.slice(0, -1)\n }\n return null\n}\n\nfunction portOf(devScript: unknown): number {\n const m = typeof devScript === \"string\" ? /(?:^|\\s)(?:-p|--port)[ =](\\d{2,5})\\b/.exec(devScript) : null\n return m ? Number(m[1]) : 3000\n}\n\nfunction ignoresEnvLocal(root: string): boolean {\n const path = join(root, \".gitignore\")\n if (!existsSync(path)) return false\n const lines = readFileSync(path, \"utf8\").split(/\\r?\\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith(\"#\"))\n return lines.some((l) => [\".env*\", \".env.local\", \"/.env.local\", \".env*.local\", \"*.local\", \".env.*\", \"/.env*\"].includes(l))\n}\n\nexport function detectProject(root: string): Project {\n const pkg = readJson(join(root, \"package.json\"))\n if (!pkg) throw new InitError(`no package.json in ${root}: run clegra init in the folder of an existing Next.js app`)\n const deps = { ...((pkg.dependencies ?? {}) as Record<string, string>), ...((pkg.devDependencies ?? {}) as Record<string, string>) }\n if (!deps.next) throw new InitError(`${join(root, \"package.json\")} has no \"next\" dependency: clegra init adds @clegra/sdk to an existing Next.js app (for another server, see listen() in @clegra/sdk/node)`)\n const installed = readJson(join(root, \"node_modules\", \"next\", \"package.json\"))\n const nextVersion = typeof installed?.version === \"string\" ? installed.version : deps.next\n const appDir = existsSync(join(root, \"app\")) ? \"app\" : existsSync(join(root, \"src\", \"app\")) ? \"src/app\" : null\n if (!appDir) throw new InitError(`no app/ or src/app/ folder in ${root}: clegra init needs the App Router (a Pages Router app can mount app.fetch in an API route by hand)`)\n const ts = existsSync(join(root, \"tsconfig.json\"))\n const nextConfig = CONFIG_FILES.find((f) => existsSync(join(root, f))) ?? null\n const clegraDir = appDir === \"src/app\" ? join(root, \"src\") : root\n const alias = aliasFor(root, clegraDir, readJson(join(root, ts ? \"tsconfig.json\" : \"jsconfig.json\"), true))\n const appName = appNameOf(pkg.name)\n const missing = [\"@clegra/sdk\", \"zod\"].filter((d) => !deps[d])\n const zod = readJson(join(root, \"node_modules\", \"zod\", \"package.json\"))\n const zodMajor = typeof zod?.version === \"string\" ? zod.version.split(\".\")[0]! : null\n const proxy = [\"proxy\", \"middleware\"].flatMap((n) => [\"ts\", \"js\", \"mjs\"].flatMap((e) => [`${n}.${e}`, `src/${n}.${e}`])).find((f) => existsSync(join(root, f))) ?? null\n return {\n root,\n nextVersion,\n appDir,\n ts,\n nextConfig,\n alias,\n appName,\n appTitle: titleOf(appName),\n missing,\n oldZod: zodMajor && zodMajor !== \"4\" ? zod!.version as string : null,\n port: portOf((pkg.scripts as Record<string, unknown> | undefined)?.dev),\n proxy,\n envIgnored: ignoresEnvLocal(root),\n }\n}\n\n/** Where clegra.ts goes (beside app/: the project root, or src/), relative to root. */\nexport function clegraPath(project: Project): string {\n return posix.join(project.appDir === \"src/app\" ? \"src\" : \".\", `clegra.${project.ts ? \"ts\" : \"js\"}`).replace(/^\\.\\//, \"\")\n}\n\nexport function routePath(project: Project): string {\n return `${project.appDir}/api/clegra/[...path]/route.${project.ts ? \"ts\" : \"js\"}`\n}\n\n/** How the route imports clegra.ts: through the alias, else a relative path. */\nexport function importPathFor(project: Project): string {\n if (project.alias) return `${project.alias}clegra`\n const from = dirname(join(project.root, routePath(project)))\n const to = join(project.root, clegraPath(project)).replace(/\\.(ts|js)$/, \"\")\n const rel = relative(from, to).split(sep).join(\"/\")\n return rel.startsWith(\".\") ? rel : `./${rel}`\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The files `clegra init` writes. Plain strings: no template engine. Each takes `ts` (TypeScript or plain
|
|
3
|
+
* JavaScript, as the project is written) and gives the file's text.
|
|
4
|
+
*/
|
|
5
|
+
/** The environment variable of the local bearer (`.env.local`): accepted by the generated `resolve` outside production only. */
|
|
6
|
+
export declare const LOCAL_TOKEN_ENV = "CLEGRA_LOCAL_TOKEN";
|
|
7
|
+
/** `clegra.ts`: a small working app on in-file sample data, with the places to plug the database and the sign-in marked TODO. */
|
|
8
|
+
export declare function clegraFile(input: {
|
|
9
|
+
name: string;
|
|
10
|
+
title: string;
|
|
11
|
+
ts: boolean;
|
|
12
|
+
}): string;
|
|
13
|
+
/** `app/api/clegra/[...path]/route.ts`: the one route that serves MCP, the manifest and the OAuth metadata. */
|
|
14
|
+
export declare function routeFile(input: {
|
|
15
|
+
importPath: string;
|
|
16
|
+
}): string;
|
|
17
|
+
/** A next.config for a project without one. */
|
|
18
|
+
export declare function nextConfigFile(ts: boolean): string;
|
|
19
|
+
/** The lines added to `.env.local`. */
|
|
20
|
+
export declare function envLines(token: string): string;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The files `clegra init` writes. Plain strings: no template engine. Each takes `ts` (TypeScript or plain
|
|
3
|
+
* JavaScript, as the project is written) and gives the file's text.
|
|
4
|
+
*/
|
|
5
|
+
/** The environment variable of the local bearer (`.env.local`): accepted by the generated `resolve` outside production only. */
|
|
6
|
+
export const LOCAL_TOKEN_ENV = "CLEGRA_LOCAL_TOKEN";
|
|
7
|
+
/** `clegra.ts`: a small working app on in-file sample data, with the places to plug the database and the sign-in marked TODO. */
|
|
8
|
+
export function clegraFile(input) {
|
|
9
|
+
const { name, title, ts } = input;
|
|
10
|
+
const T = (typed, plain) => (ts ? typed : plain);
|
|
11
|
+
return `// Your app as a Clegra app (Clegra apps): one defineApp object that becomes a manifest for workspace hosts
|
|
12
|
+
// and a plain MCP server for ChatGPT, Claude and any MCP client. Served by app/api/clegra/[...path]/route${ts ? ".ts" : ".js"};
|
|
13
|
+
// next.config's withClegra puts it at /mcp and /.well-known/clegra.json. Written by \`npx @clegra/sdk init\`.
|
|
14
|
+
import { timingSafeEqual } from "node:crypto"
|
|
15
|
+
|
|
16
|
+
import { AppError, defineApp${T(", type ResolvedCaller", "")} } from "@clegra/sdk"
|
|
17
|
+
import { z } from "zod"
|
|
18
|
+
|
|
19
|
+
// ------------------------------------------------------------------ data
|
|
20
|
+
// TODO(your data): replace the sample tasks with your database (any database, ORM or API). Scope every read and
|
|
21
|
+
// write by ctx.installation: the tenant your resolve() below names (an organization, a workspace, an account).
|
|
22
|
+
${T('type Task = { id: string; title: string; status: "open" | "done"; due: string }\n', "")}const sample${T(": Task[]", "")} = [
|
|
23
|
+
{ id: "t1", title: "Send the spring catalog to the printer", status: "open", due: "2026-03-02" },
|
|
24
|
+
{ id: "t2", title: "Renew the domain name", status: "open", due: "2026-03-15" },
|
|
25
|
+
{ id: "t3", title: "Archive last year's invoices", status: "done", due: "2026-01-31" },
|
|
26
|
+
]
|
|
27
|
+
const tasksByInstallation = new Map${T("<string, Task[]>", "")}()
|
|
28
|
+
function tasksOf(installation${T(": string", "")})${T(": Task[]", "")} {
|
|
29
|
+
let tasks = tasksByInstallation.get(installation)
|
|
30
|
+
if (!tasks) tasksByInstallation.set(installation, (tasks = sample.map((t) => ({ ...t }))))
|
|
31
|
+
return tasks
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ------------------------------------------------------------------ auth
|
|
35
|
+
// The public origin (CLEGRA_PUBLIC_URL, like https://app.example.com): its /mcp is the only audience tokens are
|
|
36
|
+
// accepted for. Required in production; unset locally, the app answers at whatever address you reach it by.
|
|
37
|
+
const site = process.env.CLEGRA_PUBLIC_URL?.replace(/\\/+$/, "")
|
|
38
|
+
const resource = site ? \`\${site}/mcp\` : undefined
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Local first: the bearer in .env.local (${LOCAL_TOKEN_ENV}, written by init), so you can see the app before your
|
|
42
|
+
* sign-in issues tokens. Never in production: NODE_ENV is "production" in \`next build\`, \`next start\` and every
|
|
43
|
+
* deployment, and then this answers null whatever the environment holds.
|
|
44
|
+
*/
|
|
45
|
+
function localCaller(token${T(": string", "")})${T(": ResolvedCaller | null", "")} {
|
|
46
|
+
const expected = process.env.${LOCAL_TOKEN_ENV}
|
|
47
|
+
if (process.env.NODE_ENV === "production" || !expected) return null
|
|
48
|
+
const given = Buffer.from(token)
|
|
49
|
+
const wanted = Buffer.from(expected)
|
|
50
|
+
if (given.length !== wanted.length || !timingSafeEqual(given, wanted)) return null
|
|
51
|
+
return { installation: "local", person: { id: "local-developer", name: "Local developer" }, permissions: "all" }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// ------------------------------------------------------------------ the app
|
|
55
|
+
|
|
56
|
+
export const app = defineApp({
|
|
57
|
+
name: ${JSON.stringify(name)},
|
|
58
|
+
title: ${JSON.stringify(title)},
|
|
59
|
+
version: "0.1.0",
|
|
60
|
+
auth: {
|
|
61
|
+
...(resource ? { resource } : {}),
|
|
62
|
+
// TODO(your sign-in): the OAuth authorization server that issues your users' tokens to MCP clients, named in the
|
|
63
|
+
// protected-resource metadata (better-auth: \`\${site}/api/auth\`). Until then \`clegra check\` says it is missing.
|
|
64
|
+
authorizationServers: [],
|
|
65
|
+
resolve: async (token, _request, _info) => {
|
|
66
|
+
const local = localCaller(token)
|
|
67
|
+
if (local) return local
|
|
68
|
+
// TODO(your sign-in): verify your sign-in's access token (signature, expiry, and aud === _info.resource, this
|
|
69
|
+
// server's MCP address) and say who is calling, from your own users and roles:
|
|
70
|
+
// return { installation: user.organizationId, person: { id: user.id, name: user.name }, permissions: ["tasks.edit"] }
|
|
71
|
+
// Recipes for better-auth, Clerk, Auth0 and WorkOS: auth.md in the @clegra/sdk docs. null refuses the token (401).
|
|
72
|
+
return null
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
|
|
76
|
+
permissions: {
|
|
77
|
+
"tasks.edit": { label: "Complete tasks", default: true },
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
entities: {
|
|
81
|
+
task: {
|
|
82
|
+
label: "Task",
|
|
83
|
+
plural: "Tasks",
|
|
84
|
+
icon: "check-square",
|
|
85
|
+
schema: z.object({
|
|
86
|
+
id: z.string(),
|
|
87
|
+
title: z.string().meta({ role: "title", label: "Title", search: true, sort: true }),
|
|
88
|
+
status: z.enum(["open", "done"]).meta({ role: "status", label: "Status", filter: true, labels: { open: "Open", done: "Done" }, tones: { done: "success" } }),
|
|
89
|
+
due: z.string().meta({ role: "date", label: "Due", sort: true }),
|
|
90
|
+
}),
|
|
91
|
+
get: (id, ctx) => tasksOf(ctx.installation).find((t) => t.id === id) ?? null,
|
|
92
|
+
list: (query, ctx) => {
|
|
93
|
+
let rows = tasksOf(ctx.installation)
|
|
94
|
+
if (typeof query.filters.status === "string") rows = rows.filter((t) => t.status === query.filters.status)
|
|
95
|
+
// Search only in query.textFields: the search fields this caller may see.
|
|
96
|
+
const text = query.text?.toLowerCase()
|
|
97
|
+
if (text) rows = rows.filter((t) => (query.textFields ?? []).some((f) => String(t[f${T(" as keyof Task", "")}] ?? "").toLowerCase().includes(text)))
|
|
98
|
+
if (query.sort) {
|
|
99
|
+
const { field, dir } = query.sort
|
|
100
|
+
rows = [...rows].sort((a, b) => String(a[field${T(" as keyof Task", "")}]).localeCompare(String(b[field${T(" as keyof Task", "")}])) * (dir === "asc" ? 1 : -1))
|
|
101
|
+
}
|
|
102
|
+
return { rows: rows.slice(0, query.limit), total: rows.length }
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
|
|
107
|
+
actions: {
|
|
108
|
+
complete: {
|
|
109
|
+
on: "task",
|
|
110
|
+
title: "Complete",
|
|
111
|
+
description: "Marks an open task as done",
|
|
112
|
+
input: z.object({}),
|
|
113
|
+
permission: "tasks.edit",
|
|
114
|
+
// Writes ask the person first (confirm defaults to always); plain MCP clients see them only with plain: true.
|
|
115
|
+
expose: { plain: true },
|
|
116
|
+
run: (_input, ctx, task) => {
|
|
117
|
+
const stored = tasksOf(ctx.installation).find((t) => t.id === task.id)
|
|
118
|
+
if (!stored || stored.status === "done") throw new AppError("conflict", "The task is already done.")
|
|
119
|
+
stored.status = "done"
|
|
120
|
+
return { message: \`\${task.title}: done.\`, record: task.id }
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
|
|
125
|
+
pages: {
|
|
126
|
+
tasks: { title: "Tasks", icon: "check-square", list: "task", columns: ["title", "status", "due"] },
|
|
127
|
+
},
|
|
128
|
+
})
|
|
129
|
+
`;
|
|
130
|
+
}
|
|
131
|
+
/** `app/api/clegra/[...path]/route.ts`: the one route that serves MCP, the manifest and the OAuth metadata. */
|
|
132
|
+
export function routeFile(input) {
|
|
133
|
+
return `import { toNextHandlers } from "@clegra/sdk/next"
|
|
134
|
+
|
|
135
|
+
import { app } from ${JSON.stringify(input.importPath)}
|
|
136
|
+
|
|
137
|
+
// MCP (/mcp), the manifest and the OAuth metadata (/.well-known/…), rewritten here by withClegra in next.config.
|
|
138
|
+
export const { GET, POST, DELETE, OPTIONS } = toNextHandlers(app)
|
|
139
|
+
`;
|
|
140
|
+
}
|
|
141
|
+
/** A next.config for a project without one. */
|
|
142
|
+
export function nextConfigFile(ts) {
|
|
143
|
+
return ts
|
|
144
|
+
? `import type { NextConfig } from "next"
|
|
145
|
+
import { withClegra } from "@clegra/sdk/next"
|
|
146
|
+
|
|
147
|
+
const nextConfig: NextConfig = {}
|
|
148
|
+
|
|
149
|
+
export default withClegra(nextConfig)
|
|
150
|
+
`
|
|
151
|
+
: `import { withClegra } from "@clegra/sdk/next"
|
|
152
|
+
|
|
153
|
+
/** @type {import("next").NextConfig} */
|
|
154
|
+
const nextConfig = {}
|
|
155
|
+
|
|
156
|
+
export default withClegra(nextConfig)
|
|
157
|
+
`;
|
|
158
|
+
}
|
|
159
|
+
/** The lines added to `.env.local`. */
|
|
160
|
+
export function envLines(token) {
|
|
161
|
+
return `# clegra: a local bearer for MCP clients and \`clegra check\` while your sign-in is not wired yet.
|
|
162
|
+
# Accepted only outside production (see localCaller in clegra.ts). Keep this file out of git.
|
|
163
|
+
${LOCAL_TOKEN_ENV}=${token}
|
|
164
|
+
`;
|
|
165
|
+
}
|
|
166
|
+
//# sourceM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E,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BzI,CAAA;AACD,CAAC;AAED,+GAA+G;AAC/G,MAAM,UAAU,SAAS,CAAC,KAA6B;IACrD,OAAO;;sBAEa,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,UAAU,CAAC;;;;CAIrD,CAAA;AACD,CAAC;AAED,+CAA+C;AAC/C,MAAM,UAAU,cAAc,CAAC,EAAW;IACxC,OAAO,EAAE;QACP,CAAC,CAAC;;;;;;CAML;QACG,CAAC,CAAC;;;;;;CAML,CAAA;AACD,CAAC;AAED,uCAAuC;AACvC,MAAM,UAAU,QAAQ,CAAC,KAAa;IACpC,OAAO;;EAEP,eAAe,IAAI,KAAK;CACzB,CAAA;AACD,CAAC","sourcesContent":["/**\n * The files `clegra init` writes. Plain strings: no template engine. Each takes `ts` (TypeScript or plain\n * JavaScript, as the project is written) and gives the file's text.\n */\n\n/** The environment variable of the local bearer (`.env.local`): accepted by the generated `resolve` outside production only. */\nexport const LOCAL_TOKEN_ENV = \"CLEGRA_LOCAL_TOKEN\"\n\n/** `clegra.ts`: a small working app on in-file sample data, with the places to plug the database and the sign-in marked TODO. */\nexport function clegraFile(input: { name: string; title: string; ts: boolean }): string {\n const { name, title, ts } = input\n const T = (typed: string, plain: string) => (ts ? typed : plain)\n return `// Your app as a Clegra app (Clegra apps): one defineApp object that becomes a manifest for workspace hosts\n// and a plain MCP server for ChatGPT, Claude and any MCP client. Served by app/api/clegra/[...path]/route${ts ? \".ts\" : \".js\"};\n// next.config's withClegra puts it at /mcp and /.well-known/clegra.json. Written by \\`npx @clegra/sdk init\\`.\nimport { timingSafeEqual } from \"node:crypto\"\n\nimport { AppError, defineApp${T(\", type ResolvedCaller\", \"\")} } from \"@clegra/sdk\"\nimport { z } from \"zod\"\n\n// ------------------------------------------------------------------ data\n// TODO(your data): replace the sample tasks with your database (any database, ORM or API). Scope every read and\n// write by ctx.installation: the tenant your resolve() below names (an organization, a workspace, an account).\n${T('type Task = { id: string; title: string; status: \"open\" | \"done\"; due: string }\\n', \"\")}const sample${T(\": Task[]\", \"\")} = [\n { id: \"t1\", title: \"Send the spring catalog to the printer\", status: \"open\", due: \"2026-03-02\" },\n { id: \"t2\", title: \"Renew the domain name\", status: \"open\", due: \"2026-03-15\" },\n { id: \"t3\", title: \"Archive last year's invoices\", status: \"done\", due: \"2026-01-31\" },\n]\nconst tasksByInstallation = new Map${T(\"<string, Task[]>\", \"\")}()\nfunction tasksOf(installation${T(\": string\", \"\")})${T(\": Task[]\", \"\")} {\n let tasks = tasksByInstallation.get(installation)\n if (!tasks) tasksByInstallation.set(installation, (tasks = sample.map((t) => ({ ...t }))))\n return tasks\n}\n\n// ------------------------------------------------------------------ auth\n// The public origin (CLEGRA_PUBLIC_URL, like https://app.example.com): its /mcp is the only audience tokens are\n// accepted for. Required in production; unset locally, the app answers at whatever address you reach it by.\nconst site = process.env.CLEGRA_PUBLIC_URL?.replace(/\\\\/+$/, \"\")\nconst resource = site ? \\`\\${site}/mcp\\` : undefined\n\n/**\n * Local first: the bearer in .env.local (${LOCAL_TOKEN_ENV}, written by init), so you can see the app before your\n * sign-in issues tokens. Never in production: NODE_ENV is \"production\" in \\`next build\\`, \\`next start\\` and every\n * deployment, and then this answers null whatever the environment holds.\n */\nfunction localCaller(token${T(\": string\", \"\")})${T(\": ResolvedCaller | null\", \"\")} {\n const expected = process.env.${LOCAL_TOKEN_ENV}\n if (process.env.NODE_ENV === \"production\" || !expected) return null\n const given = Buffer.from(token)\n const wanted = Buffer.from(expected)\n if (given.length !== wanted.length || !timingSafeEqual(given, wanted)) return null\n return { installation: \"local\", person: { id: \"local-developer\", name: \"Local developer\" }, permissions: \"all\" }\n}\n\n// ------------------------------------------------------------------ the app\n\nexport const app = defineApp({\n name: ${JSON.stringify(name)},\n title: ${JSON.stringify(title)},\n version: \"0.1.0\",\n auth: {\n ...(resource ? { resource } : {}),\n // TODO(your sign-in): the OAuth authorization server that issues your users' tokens to MCP clients, named in the\n // protected-resource metadata (better-auth: \\`\\${site}/api/auth\\`). Until then \\`clegra check\\` says it is missing.\n authorizationServers: [],\n resolve: async (token, _request, _info) => {\n const local = localCaller(token)\n if (local) return local\n // TODO(your sign-in): verify your sign-in's access token (signature, expiry, and aud === _info.resource, this\n // server's MCP address) and say who is calling, from your own users and roles:\n // return { installation: user.organizationId, person: { id: user.id, name: user.name }, permissions: [\"tasks.edit\"] }\n // Recipes for better-auth, Clerk, Auth0 and WorkOS: auth.md in the @clegra/sdk docs. null refuses the token (401).\n return null\n },\n },\n\n permissions: {\n \"tasks.edit\": { label: \"Complete tasks\", default: true },\n },\n\n entities: {\n task: {\n label: \"Task\",\n plural: \"Tasks\",\n icon: \"check-square\",\n schema: z.object({\n id: z.string(),\n title: z.string().meta({ role: \"title\", label: \"Title\", search: true, sort: true }),\n status: z.enum([\"open\", \"done\"]).meta({ role: \"status\", label: \"Status\", filter: true, labels: { open: \"Open\", done: \"Done\" }, tones: { done: \"success\" } }),\n due: z.string().meta({ role: \"date\", label: \"Due\", sort: true }),\n }),\n get: (id, ctx) => tasksOf(ctx.installation).find((t) => t.id === id) ?? null,\n list: (query, ctx) => {\n let rows = tasksOf(ctx.installation)\n if (typeof query.filters.status === \"string\") rows = rows.filter((t) => t.status === query.filters.status)\n // Search only in query.textFields: the search fields this caller may see.\n const text = query.text?.toLowerCase()\n if (text) rows = rows.filter((t) => (query.textFields ?? []).some((f) => String(t[f${T(\" as keyof Task\", \"\")}] ?? \"\").toLowerCase().includes(text)))\n if (query.sort) {\n const { field, dir } = query.sort\n rows = [...rows].sort((a, b) => String(a[field${T(\" as keyof Task\", \"\")}]).localeCompare(String(b[field${T(\" as keyof Task\", \"\")}])) * (dir === \"asc\" ? 1 : -1))\n }\n return { rows: rows.slice(0, query.limit), total: rows.length }\n },\n },\n },\n\n actions: {\n complete: {\n on: \"task\",\n title: \"Complete\",\n description: \"Marks an open task as done\",\n input: z.object({}),\n permission: \"tasks.edit\",\n // Writes ask the person first (confirm defaults to always); plain MCP clients see them only with plain: true.\n expose: { plain: true },\n run: (_input, ctx, task) => {\n const stored = tasksOf(ctx.installation).find((t) => t.id === task.id)\n if (!stored || stored.status === \"done\") throw new AppError(\"conflict\", \"The task is already done.\")\n stored.status = \"done\"\n return { message: \\`\\${task.title}: done.\\`, record: task.id }\n },\n },\n },\n\n pages: {\n tasks: { title: \"Tasks\", icon: \"check-square\", list: \"task\", columns: [\"title\", \"status\", \"due\"] },\n },\n})\n`\n}\n\n/** `app/api/clegra/[...path]/route.ts`: the one route that serves MCP, the manifest and the OAuth metadata. */\nexport function routeFile(input: { importPath: string }): string {\n return `import { toNextHandlers } from \"@clegra/sdk/next\"\n\nimport { app } from ${JSON.stringify(input.importPath)}\n\n// MCP (/mcp), the manifest and the OAuth metadata (/.well-known/…), rewritten here by withClegra in next.config.\nexport const { GET, POST, DELETE, OPTIONS } = toNextHandlers(app)\n`\n}\n\n/** A next.config for a project without one. */\nexport function nextConfigFile(ts: boolean): string {\n return ts\n ? `import type { NextConfig } from \"next\"\nimport { withClegra } from \"@clegra/sdk/next\"\n\nconst nextConfig: NextConfig = {}\n\nexport default withClegra(nextConfig)\n`\n : `import { withClegra } from \"@clegra/sdk/next\"\n\n/** @type {import(\"next\").NextConfig} */\nconst nextConfig = {}\n\nexport default withClegra(nextConfig)\n`\n}\n\n/** The lines added to `.env.local`. */\nexport function envLines(token: string): string {\n return `# clegra: a local bearer for MCP clients and \\`clegra check\\` while your sign-in is not wired yet.\n# Accepted only outside production (see localCaller in clegra.ts). Keep this file out of git.\n${LOCAL_TOKEN_ENV}=${token}\n`\n}\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Project } from "./project.js";
|
|
2
|
+
/**
|
|
3
|
+
* `clegra init --ui`: @clegra/ui added to the app. It is its own package (its repository, its version); its libraries
|
|
4
|
+
* are its optional peer dependencies, so the web ones go into the app's package.json `dependencies` beside it, at the
|
|
5
|
+
* ranges @clegra/ui declares, and the app's global stylesheet gets @clegra/ui's after Tailwind 4. Nothing already
|
|
6
|
+
* there is changed. @clegra/sdk does not depend on @clegra/ui: the generated MCP Apps view is plain HTML.
|
|
7
|
+
*/
|
|
8
|
+
/** The package and the range init adds: the @clegra/ui this SDK is checked with (`npm run pack:check`). */
|
|
9
|
+
export declare const UI_PACKAGE = "@clegra/ui";
|
|
10
|
+
export declare const UI_RANGE = "^0.1.0-next.0";
|
|
11
|
+
/**
|
|
12
|
+
* The libraries @clegra/ui's web components import, at @clegra/ui's ranges: its peer dependencies without React
|
|
13
|
+
* itself (a Next app has it), React Native's and Tailwind (the app's choice). The pack check compares this list with
|
|
14
|
+
* the peer dependencies of the @clegra/ui tarball it installs.
|
|
15
|
+
*/
|
|
16
|
+
export declare const UI_WEB_LIBRARIES: Readonly<Record<string, string>>;
|
|
17
|
+
/** What `--ui` puts in dependencies: @clegra/ui and its web libraries. */
|
|
18
|
+
export declare function uiDependencies(): Record<string, string>;
|
|
19
|
+
export declare const UI_IMPORT = "@import \"@clegra/ui/styles.css\";";
|
|
20
|
+
export type UiStep = {
|
|
21
|
+
verb: "edit" | "skip" | "by hand";
|
|
22
|
+
path: string;
|
|
23
|
+
note?: string;
|
|
24
|
+
how?: string;
|
|
25
|
+
};
|
|
26
|
+
export declare function initUi(project: Project, write: boolean, peers?: Record<string, string>): {
|
|
27
|
+
steps: UiStep[];
|
|
28
|
+
warnings: string[];
|
|
29
|
+
install: boolean;
|
|
30
|
+
};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
/**
|
|
4
|
+
* `clegra init --ui`: @clegra/ui added to the app. It is its own package (its repository, its version); its libraries
|
|
5
|
+
* are its optional peer dependencies, so the web ones go into the app's package.json `dependencies` beside it, at the
|
|
6
|
+
* ranges @clegra/ui declares, and the app's global stylesheet gets @clegra/ui's after Tailwind 4. Nothing already
|
|
7
|
+
* there is changed. @clegra/sdk does not depend on @clegra/ui: the generated MCP Apps view is plain HTML.
|
|
8
|
+
*/
|
|
9
|
+
/** The package and the range init adds: the @clegra/ui this SDK is checked with (`npm run pack:check`). */
|
|
10
|
+
export const UI_PACKAGE = "@clegra/ui";
|
|
11
|
+
export const UI_RANGE = "^0.1.0-next.0";
|
|
12
|
+
/**
|
|
13
|
+
* The libraries @clegra/ui's web components import, at @clegra/ui's ranges: its peer dependencies without React
|
|
14
|
+
* itself (a Next app has it), React Native's and Tailwind (the app's choice). The pack check compares this list with
|
|
15
|
+
* the peer dependencies of the @clegra/ui tarball it installs.
|
|
16
|
+
*/
|
|
17
|
+
export const UI_WEB_LIBRARIES = {
|
|
18
|
+
"@base-ui/react": "^1.9.0",
|
|
19
|
+
"@shadcn/react": "^0.3.1",
|
|
20
|
+
"class-variance-authority": "^0.7.1",
|
|
21
|
+
cmdk: "^1.1.1",
|
|
22
|
+
cn: "^0.5.0",
|
|
23
|
+
"date-fns": "^4.4.0",
|
|
24
|
+
"embla-carousel-react": "^8.6.0",
|
|
25
|
+
"input-otp": "^1.5.0",
|
|
26
|
+
"lucide-react": "^1.60.0",
|
|
27
|
+
"next-themes": "^0.4.6",
|
|
28
|
+
"react-day-picker": "^10.0.2",
|
|
29
|
+
"react-resizable-panels": "^4.16.1",
|
|
30
|
+
recharts: "^3.10.1",
|
|
31
|
+
sonner: "^2.0.8",
|
|
32
|
+
"tw-animate-css": "^1.4.0",
|
|
33
|
+
};
|
|
34
|
+
/** What `--ui` puts in dependencies: @clegra/ui and its web libraries. */
|
|
35
|
+
export function uiDependencies() {
|
|
36
|
+
return { [UI_PACKAGE]: UI_RANGE, ...UI_WEB_LIBRARIES };
|
|
37
|
+
}
|
|
38
|
+
export const UI_IMPORT = '@import "@clegra/ui/styles.css";';
|
|
39
|
+
export function initUi(project, write, peers = uiDependencies()) {
|
|
40
|
+
const steps = [];
|
|
41
|
+
const warnings = [];
|
|
42
|
+
const root = project.root;
|
|
43
|
+
// 1. The web UI's libraries in package.json.
|
|
44
|
+
const pkgPath = join(root, "package.json");
|
|
45
|
+
const text = readFileSync(pkgPath, "utf8");
|
|
46
|
+
const pkg = JSON.parse(text);
|
|
47
|
+
const has = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
|
|
48
|
+
const add = Object.entries(peers).filter(([name]) => !has[name]);
|
|
49
|
+
if (add.length) {
|
|
50
|
+
pkg.dependencies = Object.fromEntries(Object.entries({ ...(pkg.dependencies ?? {}), ...Object.fromEntries(add) }).sort(([a], [b]) => a.localeCompare(b)));
|
|
51
|
+
const indent = /^\{\n(\s+)"/.exec(text)?.[1] ?? " ";
|
|
52
|
+
if (write)
|
|
53
|
+
writeFileSync(pkgPath, `${JSON.stringify(pkg, null, indent)}\n`);
|
|
54
|
+
steps.push({ verb: "edit", path: "package.json", note: `added @clegra/ui and its web libraries to dependencies: ${add.map(([n]) => n).join(", ")}` });
|
|
55
|
+
}
|
|
56
|
+
else
|
|
57
|
+
steps.push({ verb: "skip", path: "package.json", note: "@clegra/ui and its web libraries are already there" });
|
|
58
|
+
// 2. The stylesheet: @clegra/ui's after Tailwind 4 in the global stylesheet.
|
|
59
|
+
const tailwind = has.tailwindcss;
|
|
60
|
+
if (tailwind && !/(^|[\^~>=\s])4(\.|$)|^latest$/.test(tailwind))
|
|
61
|
+
warnings.push(`tailwindcss ${tailwind} is in package.json: @clegra/ui/styles.css needs Tailwind 4 (or use @clegra/ui/prebuilt.css)`);
|
|
62
|
+
const css = [`${project.appDir}/globals.css`, "styles/globals.css", "src/styles/globals.css"].find((p) => existsSync(join(root, p))) ?? null;
|
|
63
|
+
const byHand = `Tailwind 4: after @import "tailwindcss"; in your global stylesheet add ${UI_IMPORT}\nNo Tailwind: import "@clegra/ui/prebuilt.css" in ${project.appDir}/layout.${project.ts ? "tsx" : "js"}`;
|
|
64
|
+
if (!css)
|
|
65
|
+
steps.push({ verb: "by hand", path: `${project.appDir}/globals.css`, note: "no global stylesheet found", how: byHand });
|
|
66
|
+
else {
|
|
67
|
+
const sheet = readFileSync(join(root, css), "utf8");
|
|
68
|
+
const tw = /^@import\s+["']tailwindcss["'][^;\n]*;[^\n]*$/m.exec(sheet);
|
|
69
|
+
if (sheet.includes("@clegra/ui/styles.css") || sheet.includes("@clegra/ui/prebuilt.css"))
|
|
70
|
+
steps.push({ verb: "skip", path: css, note: "already imports @clegra/ui's stylesheet" });
|
|
71
|
+
else if (!tw)
|
|
72
|
+
steps.push({ verb: "by hand", path: css, note: 'no @import "tailwindcss" in it', how: byHand });
|
|
73
|
+
else {
|
|
74
|
+
const at = tw.index + tw[0].length;
|
|
75
|
+
if (write)
|
|
76
|
+
writeFileSync(join(root, css), `${sheet.slice(0, at)}\n${UI_IMPORT}${sheet.slice(at)}`);
|
|
77
|
+
steps.push({ verb: "edit", path: css, note: "@clegra/ui's stylesheet after Tailwind (the theme, light and dark; it lets Tailwind see the components' classes)" });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return { steps, warnings, install: add.length > 0 };
|
|
81
|
+
}
|
|
82
|
+
//# sourceMappingURL=ui.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ui.js","sourceRoot":"","sources":["../../../../spec/src/init/ui.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AACjE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAIhC;;;;;GAKG;AAEH,2GAA2G;AAC3G,MAAM,CAAC,MAAM,UAAU,GAAG,YAAY,CAAA;AACtC,MAAM,CAAC,MAAM,QAAQ,GAAG,eAAe,CAAA;AAEvC;;;;GAIG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAqC;IAChE,gBAAgB,EAAE,QAAQ;IAC1B,eAAe,EAAE,QAAQ;IACzB,0BAA0B,EAAE,QAAQ;IACpC,IAAI,EAAE,QAAQ;IACd,EAAE,EAAE,QAAQ;IACZ,UAAU,EAAE,QA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CAAC,EAAE,EAAE,CAAC,KAAK,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC,CAAA;YAClG,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,kHAAkH,EAAE,CAAC,CAAA;QACnK,CAAC;IACH,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAA;AACrD,CAAC","sourcesContent":["import { existsSync, readFileSync, writeFileSync } from \"node:fs\"\nimport { join } from \"node:path\"\n\nimport type { Project } from \"./project\"\n\n/**\n * `clegra init --ui`: @clegra/ui added to the app. It is its own package (its repository, its version); its libraries\n * are its optional peer dependencies, so the web ones go into the app's package.json `dependencies` beside it, at the\n * ranges @clegra/ui declares, and the app's global stylesheet gets @clegra/ui's after Tailwind 4. Nothing already\n * there is changed. @clegra/sdk does not depend on @clegra/ui: the generated MCP Apps view is plain HTML.\n */\n\n/** The package and the range init adds: the @clegra/ui this SDK is checked with (`npm run pack:check`). */\nexport const UI_PACKAGE = \"@clegra/ui\"\nexport const UI_RANGE = \"^0.1.0-next.0\"\n\n/**\n * The libraries @clegra/ui's web components import, at @clegra/ui's ranges: its peer dependencies without React\n * itself (a Next app has it), React Native's and Tailwind (the app's choice). The pack check compares this list with\n * the peer dependencies of the @clegra/ui tarball it installs.\n */\nexport const UI_WEB_LIBRARIES: Readonly<Record<string, string>> = {\n \"@base-ui/react\": \"^1.9.0\",\n \"@shadcn/react\": \"^0.3.1\",\n \"class-variance-authority\": \"^0.7.1\",\n cmdk: \"^1.1.1\",\n cn: \"^0.5.0\",\n \"date-fns\": \"^4.4.0\",\n \"embla-carousel-react\": \"^8.6.0\",\n \"input-otp\": \"^1.5.0\",\n \"lucide-react\": \"^1.60.0\",\n \"next-themes\": \"^0.4.6\",\n \"react-day-picker\": \"^10.0.2\",\n \"react-resizable-panels\": \"^4.16.1\",\n recharts: \"^3.10.1\",\n sonner: \"^2.0.8\",\n \"tw-animate-css\": \"^1.4.0\",\n}\n\n/** What `--ui` puts in dependencies: @clegra/ui and its web libraries. */\nexport function uiDependencies(): Record<string, string> {\n return { [UI_PACKAGE]: UI_RANGE, ...UI_WEB_LIBRARIES }\n}\n\nexport const UI_IMPORT = '@import \"@clegra/ui/styles.css\";'\n\nexport type UiStep = { verb: \"edit\" | \"skip\" | \"by hand\"; path: string; note?: string; how?: string }\n\nexport function initUi(project: Project, write: boolean, peers: Record<string, string> = uiDependencies()): { steps: UiStep[]; warnings: string[]; install: boolean } {\n const steps: UiStep[] = []\n const warnings: string[] = []\n const root = project.root\n\n // 1. The web UI's libraries in package.json.\n const pkgPath = join(root, \"package.json\")\n const text = readFileSync(pkgPath, \"utf8\")\n const pkg = JSON.parse(text) as { dependencies?: Record<string, string>; devDependencies?: Record<string, string> }\n const has = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) }\n const add = Object.entries(peers).filter(([name]) => !has[name])\n if (add.length) {\n pkg.dependencies = Object.fromEntries(Object.entries({ ...(pkg.dependencies ?? {}), ...Object.fromEntries(add) }).sort(([a], [b]) => a.localeCompare(b)))\n const indent = /^\\{\\n(\\s+)\"/.exec(text)?.[1] ?? \" \"\n if (write) writeFileSync(pkgPath, `${JSON.stringify(pkg, null, indent)}\\n`)\n steps.push({ verb: \"edit\", path: \"package.json\", note: `added @clegra/ui and its web libraries to dependencies: ${add.map(([n]) => n).join(\", \")}` })\n } else steps.push({ verb: \"skip\", path: \"package.json\", note: \"@clegra/ui and its web libraries are already there\" })\n\n // 2. The stylesheet: @clegra/ui's after Tailwind 4 in the global stylesheet.\n const tailwind = has.tailwindcss\n if (tailwind && !/(^|[\\^~>=\\s])4(\\.|$)|^latest$/.test(tailwind)) warnings.push(`tailwindcss ${tailwind} is in package.json: @clegra/ui/styles.css needs Tailwind 4 (or use @clegra/ui/prebuilt.css)`)\n const css = [`${project.appDir}/globals.css`, \"styles/globals.css\", \"src/styles/globals.css\"].find((p) => existsSync(join(root, p))) ?? null\n const byHand = `Tailwind 4: after @import \"tailwindcss\"; in your global stylesheet add ${UI_IMPORT}\\nNo Tailwind: import \"@clegra/ui/prebuilt.css\" in ${project.appDir}/layout.${project.ts ? \"tsx\" : \"js\"}`\n if (!css) steps.push({ verb: \"by hand\", path: `${project.appDir}/globals.css`, note: \"no global stylesheet found\", how: byHand })\n else {\n const sheet = readFileSync(join(root, css), \"utf8\")\n const tw = /^@import\\s+[\"']tailwindcss[\"'][^;\\n]*;[^\\n]*$/m.exec(sheet)\n if (sheet.includes(\"@clegra/ui/styles.css\") || sheet.includes(\"@clegra/ui/prebuilt.css\")) steps.push({ verb: \"skip\", path: css, note: \"already imports @clegra/ui's stylesheet\" })\n else if (!tw) steps.push({ verb: \"by hand\", path: css, note: 'no @import \"tailwindcss\" in it', how: byHand })\n else {\n const at = tw.index + tw[0].length\n if (write) writeFileSync(join(root, css), `${sheet.slice(0, at)}\\n${UI_IMPORT}${sheet.slice(at)}`)\n steps.push({ verb: \"edit\", path: css, note: \"@clegra/ui's stylesheet after Tailwind (the theme, light and dark; it lets Tailwind see the components' classes)\" })\n }\n }\n return { steps, warnings, install: add.length > 0 }\n}\n"]}
|