kuza-lang 0.3.0 → 0.5.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/README.md +121 -62
- package/dist/ask.js +108 -0
- package/dist/config.js +56 -0
- package/dist/index.js +355 -79
- package/dist/scaffold.js +82 -0
- package/package.json +5 -2
- package/scripts/postinstall.mjs +39 -0
- package/templates/START.md +133 -0
- package/templates/index.html +19 -0
- package/templates/main-script.kuza +14 -0
- package/templates/main.kuza +36 -0
- package/templates/public/favicon.svg +4 -0
package/README.md
CHANGED
|
@@ -1,98 +1,157 @@
|
|
|
1
1
|
# kuza-lang
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
`kuza-lang` — пакет с командой `kuza`: создание проектов, запуск сайта на
|
|
4
|
+
localhost, сборка, проверка, сервер, ИИ-помощник и REPL. Компилятор живёт в
|
|
5
|
+
отдельном пакете `kuza-core`, который уже входит в зависимости.
|
|
6
6
|
|
|
7
|
-
## Установка
|
|
7
|
+
## Установка и первый сайт
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
|
-
|
|
10
|
+
mkdir my-site && cd my-site
|
|
11
|
+
npm install kuza-lang
|
|
12
|
+
npm run dev
|
|
11
13
|
```
|
|
12
14
|
|
|
13
|
-
|
|
14
|
-
Пакет называется `kuza-lang`, потому что имя `kuza` реестр npm не принимает
|
|
15
|
-
(слишком похоже на существующий пакет `koa`) — на саму команду это не влияет.
|
|
15
|
+
`postinstall` в пустой папке создаст:
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
```text
|
|
18
|
+
index.html каркас страницы с Tailwind и меткой {main.kuza}
|
|
19
|
+
main.kuza приложение (счётчик, иконка и ссылка на документацию)
|
|
20
|
+
public/favicon.svg иконка сайта
|
|
21
|
+
START.md инструкция: CLI, ИИ, плагины, бэкенд, VS Code
|
|
22
|
+
README.md
|
|
23
|
+
.gitignore
|
|
24
|
+
```
|
|
18
25
|
|
|
19
|
-
|
|
26
|
+
`npm install` в существующем проекте (React, Next.js и т.п.) **не** перезаписывает
|
|
27
|
+
файлы — скаффолд срабатывает только когда нет `index.html`, `src/`, `app/`,
|
|
28
|
+
`pages/` и других зависимостей, кроме `kuza-lang`.
|
|
20
29
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
30
|
+
Без установки: `npx kuza-lang new my-site`.
|
|
31
|
+
|
|
32
|
+
## Команды CLI
|
|
33
|
+
|
|
34
|
+
| Команда | Что делает |
|
|
35
|
+
| --- | --- |
|
|
36
|
+
| `kuza new <dir>` (`init`, `create`) | создать проект; `--script` — консольная программа, `--force` — перезаписать |
|
|
37
|
+
| `kuza start` (`dev`) | dev-сервер на `http://localhost:5173`; `--port=3000` |
|
|
38
|
+
| `kuza build` | собрать `dist/index.html` и `dist/<страница>/index.html` |
|
|
39
|
+
| `kuza check` (`doctor`) | проверить все `.kuza` файлы без запуска |
|
|
40
|
+
| `kuza serve server.kuza` | поднять HTTP-сервер, описанный на Kuza |
|
|
41
|
+
| `kuza ai "вопрос" --file main.kuza` | ИИ, который читает файлы проекта |
|
|
42
|
+
| `kuza run main.kuza` | выполнить файл в Node.js |
|
|
43
|
+
| `kuza build main.kuza` | собрать самостоятельный `.js` |
|
|
44
|
+
| `kuza watch main.kuza --web` | пересобирать HTML при изменениях |
|
|
45
|
+
| `kuza docs` | путь к `START.md` или ссылка на документацию |
|
|
46
|
+
| `kuza help` | справка |
|
|
47
|
+
|
|
48
|
+
`npm start` в созданном проекте — алиас `npm run dev`.
|
|
28
49
|
|
|
29
|
-
##
|
|
50
|
+
## Сайт на Kuza
|
|
30
51
|
|
|
31
52
|
```kuza
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
53
|
+
:count = 0;
|
|
54
|
+
|
|
55
|
+
view App<> >> [
|
|
56
|
+
page >> "Hello, Kuza!";
|
|
35
57
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
58
|
+
body<"mx-auto max-w-2xl p-8"> >> [
|
|
59
|
+
heading >> <"Hello, Kuza!", "text-4xl font-bold">;
|
|
60
|
+
para >> <"Count: {count}", "text-orange-400">;
|
|
61
|
+
button >> <"Add one", increase, "rounded bg-orange-500 px-4 py-2">;
|
|
62
|
+
];
|
|
39
63
|
|
|
40
|
-
|
|
41
|
-
|
|
64
|
+
render;
|
|
65
|
+
];
|
|
42
66
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
67
|
+
func increase<> >> [
|
|
68
|
+
count = count + 1; // view перерисуется сам
|
|
69
|
+
];
|
|
46
70
|
```
|
|
47
71
|
|
|
48
|
-
|
|
72
|
+
`view` — один экран. Переменные, которые он использует, становятся
|
|
73
|
+
реактивными: достаточно присваивания, ручного `draw<>()` не нужно.
|
|
74
|
+
Классы внутри `<"..." >` — Tailwind; `index.html` шаблона уже подключает его.
|
|
49
75
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
- 100+ встроенных команд: строки, массивы, JSON, файлы, HTTP, время, DOM;
|
|
54
|
-
- таблицы: `table<...>`, `select`, `update`, `delete`, сохранение в JSON;
|
|
55
|
-
- сайты: `page`, `heading`, `para`, `button`, `field`, `list`, `link`, `image`, `render`;
|
|
56
|
-
- модули `use math;`, `use time;`, `use "./helpers.kuza";`.
|
|
76
|
+
Контейнеры: `body`, `section`, `nav`, `row`, `column`, `card`, `box`. Внутри —
|
|
77
|
+
`heading`, `para`, `button`, `field`, `list`, `link`, `image`. `render` рисует
|
|
78
|
+
собранное дерево.
|
|
57
79
|
|
|
58
|
-
|
|
80
|
+
### Многостраничность
|
|
59
81
|
|
|
60
|
-
|
|
82
|
+
`main.kuza` — главная страница. Файл `pages/about.kuza` становится `/about`
|
|
83
|
+
в dev-сервере и `dist/about/index.html` после сборки. Статика из `public/`
|
|
84
|
+
копируется в `dist/`.
|
|
61
85
|
|
|
62
|
-
|
|
86
|
+
## Хранилище и бэкенд
|
|
63
87
|
|
|
64
88
|
```kuza
|
|
65
|
-
|
|
89
|
+
storeSet >> <"visits", 3>;
|
|
90
|
+
:visits = storeGet >> <"visits", 0>;
|
|
91
|
+
```
|
|
66
92
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
para >> "Один файл — весь сайт.";
|
|
71
|
-
heading >> "Кликов: {count}";
|
|
72
|
-
button >> <"Прибавить", increase>;
|
|
73
|
-
field >> <"Как тебя зовут?", "name">;
|
|
74
|
-
render;
|
|
93
|
+
```kuza
|
|
94
|
+
func home<> >> [
|
|
95
|
+
respond >> <{ ok: true, name: query >> "name" }, 200>;
|
|
75
96
|
];
|
|
76
97
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
];
|
|
98
|
+
route >> <"GET", "/", home>;
|
|
99
|
+
listen >> 3000;
|
|
100
|
+
```
|
|
81
101
|
|
|
82
|
-
|
|
102
|
+
Запуск: `kuza serve server.kuza`. Маршруты поддерживают параметры
|
|
103
|
+
`/users/:id`; запрос читают `param`, `query`, `requestBody`, `header`, `method`,
|
|
104
|
+
`serverPath`.
|
|
105
|
+
|
|
106
|
+
## Плагины
|
|
107
|
+
|
|
108
|
+
`kuza.config.js` рядом с `package.json`:
|
|
109
|
+
|
|
110
|
+
```js
|
|
111
|
+
export default {
|
|
112
|
+
commands: [
|
|
113
|
+
{
|
|
114
|
+
id: "shout", name: "shout", aliases: [], category: "output",
|
|
115
|
+
args: "single", params: ["text"],
|
|
116
|
+
description: "Верхний регистр", example: 'shout >> "hi";',
|
|
117
|
+
codegen: "console.log(String({0}).toUpperCase())",
|
|
118
|
+
},
|
|
119
|
+
],
|
|
120
|
+
plugins: [
|
|
121
|
+
{
|
|
122
|
+
name: "example",
|
|
123
|
+
setup(api) {
|
|
124
|
+
api.onCompile(({ source }) => source);
|
|
125
|
+
api.onBuild(({ code }) => code);
|
|
126
|
+
api.onRun(({ result }) => result);
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
],
|
|
130
|
+
};
|
|
83
131
|
```
|
|
84
132
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
133
|
+
Команда плагина становится доступной в `.kuza` файлах и в подсветке после
|
|
134
|
+
перезапуска CLI.
|
|
135
|
+
|
|
136
|
+
## ИИ
|
|
137
|
+
|
|
138
|
+
Ключ берётся из `.env` или окружения:
|
|
139
|
+
|
|
140
|
+
```dotenv
|
|
141
|
+
KUZA_AI_KEY=sk-...
|
|
142
|
+
KUZA_AI_PROVIDER=openai
|
|
143
|
+
KUZA_AI_MODEL=gpt-4o-mini
|
|
144
|
+
KUZA_AI_BASE_URL=https://api.openai.com/v1
|
|
88
145
|
```
|
|
89
146
|
|
|
90
|
-
|
|
91
|
-
`
|
|
147
|
+
Поддерживаются OpenAI, OpenRouter, Groq, Ollama, Freebuff и Anthropic
|
|
148
|
+
(`ANTHROPIC_API_KEY`). Команда `kuza ai` читает файлы проекта и ошибки
|
|
149
|
+
компиляции; ключ никогда не печатается.
|
|
92
150
|
|
|
93
|
-
##
|
|
151
|
+
## Ссылки
|
|
94
152
|
|
|
95
|
-
|
|
96
|
-
|
|
153
|
+
- Все команды: `docs/commands.md` в репозитории.
|
|
154
|
+
- Компилятор как библиотека: `kuza-core`.
|
|
155
|
+
- Расширение: `kuza-vscode`.
|
|
97
156
|
|
|
98
157
|
Лицензия: MIT.
|
package/dist/ask.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** Одноразовый вызов ИИ из CLI: kuza ai "вопрос" --file main.kuza */
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { extname, join, relative, resolve } from "node:path";
|
|
4
|
+
import { compile, formatDiagnostic } from "kuza-core";
|
|
5
|
+
import { askAi, resolveAiConfig, systemPrompt } from "./ai.js";
|
|
6
|
+
import { bold, danger, dim, primary } from "./ui.js";
|
|
7
|
+
const ALLOWED = new Set([".kuza", ".html", ".js", ".ts", ".json", ".md", ".css", ".txt", ".mjs"]);
|
|
8
|
+
const SKIP = new Set(["node_modules", "dist", ".git", ".vsix"]);
|
|
9
|
+
const MAX_FILES = 24;
|
|
10
|
+
const MAX_CHARS = 60000;
|
|
11
|
+
function collectFiles(root, explicit) {
|
|
12
|
+
if (explicit.length > 0) {
|
|
13
|
+
return explicit
|
|
14
|
+
.map((name) => resolve(root, name))
|
|
15
|
+
.filter((path) => existsSync(path) && statSync(path).isFile());
|
|
16
|
+
}
|
|
17
|
+
const found = [];
|
|
18
|
+
const walk = (dir, depth) => {
|
|
19
|
+
if (depth > 2 || found.length >= MAX_FILES)
|
|
20
|
+
return;
|
|
21
|
+
let entries = [];
|
|
22
|
+
try {
|
|
23
|
+
entries = readdirSync(dir);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
for (const entry of entries) {
|
|
29
|
+
if (SKIP.has(entry) || entry.startsWith("."))
|
|
30
|
+
continue;
|
|
31
|
+
const path = join(dir, entry);
|
|
32
|
+
if (!existsSync(path))
|
|
33
|
+
continue;
|
|
34
|
+
if (statSync(path).isDirectory()) {
|
|
35
|
+
walk(path, depth + 1);
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (ALLOWED.has(extname(entry)))
|
|
39
|
+
found.push(path);
|
|
40
|
+
if (found.length >= MAX_FILES)
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
walk(root, 0);
|
|
45
|
+
// Сначала самые важные файлы проекта.
|
|
46
|
+
const priority = ["main.kuza", "index.kuza", "index.html", "START.md", "package.json"];
|
|
47
|
+
found.sort((a, b) => {
|
|
48
|
+
const nameA = relative(root, a).replace(/\\/g, "/");
|
|
49
|
+
const nameB = relative(root, b).replace(/\\/g, "/");
|
|
50
|
+
const rankA = priority.indexOf(nameA);
|
|
51
|
+
const rankB = priority.indexOf(nameB);
|
|
52
|
+
return (rankA === -1 ? 99 : rankA) - (rankB === -1 ? 99 : rankB);
|
|
53
|
+
});
|
|
54
|
+
return found.slice(0, MAX_FILES);
|
|
55
|
+
}
|
|
56
|
+
function diagnostics(root) {
|
|
57
|
+
for (const name of ["main.kuza", "index.kuza"]) {
|
|
58
|
+
const path = join(root, name);
|
|
59
|
+
if (!existsSync(path))
|
|
60
|
+
continue;
|
|
61
|
+
const source = readFileSync(path, "utf8");
|
|
62
|
+
const result = compile(source, { filename: path });
|
|
63
|
+
if (!result.ok) {
|
|
64
|
+
return `\nОшибка компиляции ${name}:\n${formatDiagnostic(result.errors[0], source)}`;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return "";
|
|
68
|
+
}
|
|
69
|
+
export async function runAiQuestion(question, explicitFiles = []) {
|
|
70
|
+
const config = resolveAiConfig();
|
|
71
|
+
if (!config) {
|
|
72
|
+
console.log(danger("ИИ не настроен. Добавь KUZA_AI_KEY в .env или окружение."));
|
|
73
|
+
console.log(dim("Подробности: START.md → раздел «AI assistant»"));
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const root = process.cwd();
|
|
77
|
+
const files = collectFiles(root, explicitFiles);
|
|
78
|
+
const parts = [`Проект в ${root}. Файлы:`];
|
|
79
|
+
let total = 0;
|
|
80
|
+
for (const path of files) {
|
|
81
|
+
const name = relative(root, path).replace(/\\/g, "/");
|
|
82
|
+
let text = readFileSync(path, "utf8");
|
|
83
|
+
if (text.length > 12000)
|
|
84
|
+
text = text.slice(0, 12000) + "\n… [обрезано]";
|
|
85
|
+
if (total + text.length > MAX_CHARS)
|
|
86
|
+
break;
|
|
87
|
+
total += text.length;
|
|
88
|
+
parts.push(`\n--- ${name} ---\n${text}`);
|
|
89
|
+
}
|
|
90
|
+
if (files.length === 0)
|
|
91
|
+
parts.push("(в папке не найдены текстовые файлы проекта)");
|
|
92
|
+
parts.push(diagnostics(root));
|
|
93
|
+
const messages = [
|
|
94
|
+
{
|
|
95
|
+
role: "user",
|
|
96
|
+
content: `${parts.join("\n")}\n\nЗадача: ${question}`,
|
|
97
|
+
},
|
|
98
|
+
];
|
|
99
|
+
console.log(dim(`ИИ читает ${files.length} файл(ов)…`));
|
|
100
|
+
try {
|
|
101
|
+
const answer = await askAi(config, messages, systemPrompt());
|
|
102
|
+
console.log("");
|
|
103
|
+
console.log(bold(primary("Kuza AI")) + "\n" + answer);
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
console.log(danger(`Ошибка ИИ: ${error instanceof Error ? error.message : String(error)}`));
|
|
107
|
+
}
|
|
108
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Поддержка kuza.config.js: плагины, хуки и свои команды.
|
|
3
|
+
*
|
|
4
|
+
* Файл лежит рядом с package.json и подключается перед компиляцией.
|
|
5
|
+
* Ошибка в конфиге не должна ломать CLI — показываем предупреждение.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { pathToFileURL } from "node:url";
|
|
10
|
+
import { defineCommand } from "kuza-core";
|
|
11
|
+
export async function loadProjectConfig(dir = process.cwd()) {
|
|
12
|
+
const loaded = { compile: [], build: [], run: [], warnings: [] };
|
|
13
|
+
const path = join(dir, "kuza.config.js");
|
|
14
|
+
if (!existsSync(path))
|
|
15
|
+
return loaded;
|
|
16
|
+
try {
|
|
17
|
+
const module = (await import(pathToFileURL(path).href + "?t=" + Date.now()));
|
|
18
|
+
const config = module.default ?? module;
|
|
19
|
+
for (const command of config.commands ?? [])
|
|
20
|
+
defineCommand(command);
|
|
21
|
+
const api = {
|
|
22
|
+
defineCommand,
|
|
23
|
+
onCompile: (hook) => loaded.compile.push(hook),
|
|
24
|
+
onBuild: (hook) => loaded.build.push(hook),
|
|
25
|
+
onRun: (hook) => loaded.run.push(hook),
|
|
26
|
+
};
|
|
27
|
+
for (const plugin of config.plugins ?? []) {
|
|
28
|
+
await plugin.setup(api);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
loaded.warnings.push(`kuza.config.js: ${error instanceof Error ? error.message : String(error)}`);
|
|
33
|
+
}
|
|
34
|
+
return loaded;
|
|
35
|
+
}
|
|
36
|
+
export function applyCompileHooks(config, context) {
|
|
37
|
+
let source = context.source;
|
|
38
|
+
for (const hook of config.compile) {
|
|
39
|
+
source = hook({ ...context, source }) ?? source;
|
|
40
|
+
}
|
|
41
|
+
return source;
|
|
42
|
+
}
|
|
43
|
+
export function applyBuildHooks(config, context) {
|
|
44
|
+
let code = context.code;
|
|
45
|
+
for (const hook of config.build) {
|
|
46
|
+
code = hook({ ...context, code }) ?? code;
|
|
47
|
+
}
|
|
48
|
+
return code;
|
|
49
|
+
}
|
|
50
|
+
export function applyRunHooks(config, context) {
|
|
51
|
+
let result = context.result;
|
|
52
|
+
for (const hook of config.run) {
|
|
53
|
+
result = hook({ ...context, result }) ?? result;
|
|
54
|
+
}
|
|
55
|
+
return result;
|
|
56
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -2,22 +2,41 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* ТОЧКА ВХОДА CLI.
|
|
4
4
|
*
|
|
5
|
-
* kuza
|
|
6
|
-
* kuza
|
|
7
|
-
* kuza
|
|
8
|
-
* kuza build
|
|
9
|
-
* kuza
|
|
10
|
-
* kuza
|
|
11
|
-
* kuza
|
|
12
|
-
* kuza
|
|
5
|
+
* kuza / kuza repl консоль
|
|
6
|
+
* kuza new <dir> новый проект (alias: init, create)
|
|
7
|
+
* kuza start / dev localhost
|
|
8
|
+
* kuza build dist/
|
|
9
|
+
* kuza check проверка без запуска
|
|
10
|
+
* kuza serve server.kuza backend
|
|
11
|
+
* kuza ai "вопрос" --file ... ИИ, который читает файлы проекта
|
|
12
|
+
* kuza help справка
|
|
13
13
|
*/
|
|
14
|
-
import { existsSync, readFileSync, watchFile, writeFileSync } from "node:fs";
|
|
15
|
-
import { basename, dirname, extname, join, resolve } from "node:path";
|
|
16
|
-
import {
|
|
14
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, watchFile, writeFileSync, } from "node:fs";
|
|
15
|
+
import { basename, dirname, extname, join, relative, resolve } from "node:path";
|
|
16
|
+
import { createServer } from "node:http";
|
|
17
|
+
import { FILE_EXT, NAME, VERSION, compile, formatDiagnostic, run } from "kuza-core";
|
|
18
|
+
import { applyBuildHooks, applyCompileHooks, applyRunHooks, loadProjectConfig, } from "./config.js";
|
|
19
|
+
import { runAiQuestion } from "./ask.js";
|
|
17
20
|
import { startRepl } from "./repl.js";
|
|
18
21
|
import { t } from "./i18n.js";
|
|
19
22
|
import { bold, code, danger, dim, primary, printBanner, success, warning, } from "./ui.js";
|
|
23
|
+
import { scaffoldProject } from "./scaffold.js";
|
|
20
24
|
const argv = process.argv.slice(2);
|
|
25
|
+
let cachedConfig;
|
|
26
|
+
const MIME = {
|
|
27
|
+
".html": "text/html; charset=utf-8",
|
|
28
|
+
".js": "text/javascript; charset=utf-8",
|
|
29
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
30
|
+
".css": "text/css; charset=utf-8",
|
|
31
|
+
".json": "application/json; charset=utf-8",
|
|
32
|
+
".svg": "image/svg+xml",
|
|
33
|
+
".png": "image/png",
|
|
34
|
+
".jpg": "image/jpeg",
|
|
35
|
+
".jpeg": "image/jpeg",
|
|
36
|
+
".ico": "image/x-icon",
|
|
37
|
+
".woff2": "font/woff2",
|
|
38
|
+
".txt": "text/plain; charset=utf-8",
|
|
39
|
+
};
|
|
21
40
|
function printEntry(entry) {
|
|
22
41
|
switch (entry.type) {
|
|
23
42
|
case "error":
|
|
@@ -39,33 +58,52 @@ function usage() {
|
|
|
39
58
|
console.log(bold(`${NAME} ${VERSION}`) + dim(` — ${t("running")} ${NAME}-программы`));
|
|
40
59
|
console.log("");
|
|
41
60
|
console.log(` ${primary("kuza")} ${dim("открыть консоль (REPL)")}`);
|
|
42
|
-
console.log(` ${primary("kuza")}
|
|
43
|
-
console.log(` ${primary("kuza")}
|
|
44
|
-
console.log(` ${primary("kuza")} build
|
|
45
|
-
console.log(` ${primary("kuza")}
|
|
46
|
-
console.log(` ${primary("kuza")}
|
|
61
|
+
console.log(` ${primary("kuza")} new my-site ${dim("создать сайт в ./my-site")}`);
|
|
62
|
+
console.log(` ${primary("kuza")} start ${dim("localhost (алиас: dev)")}`);
|
|
63
|
+
console.log(` ${primary("kuza")} build ${dim("собрать сайт в dist/")}`);
|
|
64
|
+
console.log(` ${primary("kuza")} check ${dim("проверить все .kuza-файлы")}`);
|
|
65
|
+
console.log(` ${primary("kuza")} serve ${ex} ${dim("запустить HTTP-сервер")}`);
|
|
66
|
+
console.log(` ${primary("kuza")} ai "вопрос" ${dim("ИИ, который читает файлы проекта")}`);
|
|
67
|
+
console.log(` ${primary("kuza")} run ${ex} ${dim("выполнить файл")}`);
|
|
68
|
+
console.log(` ${primary("kuza")} build ${ex} ${dim("собрать консольную программу")}`);
|
|
47
69
|
console.log(` ${primary("kuza")} help ${dim("эта справка")}`);
|
|
48
70
|
console.log("");
|
|
49
|
-
console.log(dim("
|
|
71
|
+
console.log(dim("Первый сайт: ") + code("npm install kuza-lang && npm run dev"));
|
|
72
|
+
console.log(dim("Документация: ") + code("START.md") + dim(" после установки"));
|
|
50
73
|
console.log("");
|
|
51
74
|
}
|
|
52
75
|
function fail(text) {
|
|
53
76
|
console.error(danger(text));
|
|
54
77
|
process.exitCode = 1;
|
|
55
78
|
}
|
|
56
|
-
|
|
79
|
+
async function config() {
|
|
80
|
+
if (!cachedConfig)
|
|
81
|
+
cachedConfig = await loadProjectConfig(process.cwd());
|
|
82
|
+
for (const warningText of cachedConfig.warnings)
|
|
83
|
+
console.log(warning(warningText));
|
|
84
|
+
return cachedConfig;
|
|
85
|
+
}
|
|
86
|
+
/** Читать use "./helpers.kuza" относительно запускаемого файла. */
|
|
57
87
|
function moduleResolver(entryPath) {
|
|
58
88
|
return (specifier) => readFileSync(resolve(dirname(entryPath), specifier), "utf8");
|
|
59
89
|
}
|
|
90
|
+
function compileSource(source, filename, cfg, standalone = true) {
|
|
91
|
+
const prepared = applyCompileHooks(cfg, { source, filename });
|
|
92
|
+
return compile(prepared, {
|
|
93
|
+
standalone,
|
|
94
|
+
filename,
|
|
95
|
+
resolveModule: moduleResolver(filename),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
60
98
|
async function runFile(file) {
|
|
61
99
|
const path = resolve(file);
|
|
62
100
|
if (!existsSync(path)) {
|
|
63
101
|
fail(`${t("fileNotFound")}: ${file}`);
|
|
64
102
|
return;
|
|
65
103
|
}
|
|
104
|
+
const cfg = await config();
|
|
66
105
|
const source = readFileSync(path, "utf8");
|
|
67
|
-
const
|
|
68
|
-
const compiled = compile(source, compileOptions);
|
|
106
|
+
const compiled = compileSource(source, path, cfg);
|
|
69
107
|
if (!compiled.ok) {
|
|
70
108
|
console.error(danger(`${t("compileError")}: ${basename(path)}`));
|
|
71
109
|
console.error(danger(formatDiagnostic(compiled.errors[0], source)));
|
|
@@ -73,27 +111,128 @@ async function runFile(file) {
|
|
|
73
111
|
return;
|
|
74
112
|
}
|
|
75
113
|
console.log(dim(`${t("running")} ${basename(path)}`));
|
|
76
|
-
const result = await run(source,
|
|
114
|
+
const result = (await run(source, {
|
|
115
|
+
filename: path,
|
|
116
|
+
resolveModule: moduleResolver(path),
|
|
117
|
+
}));
|
|
118
|
+
applyRunHooks(cfg, { result, filename: path });
|
|
77
119
|
for (const entry of result.output)
|
|
78
120
|
printEntry(entry);
|
|
79
121
|
process.exitCode = result.ok ? 0 : 1;
|
|
80
122
|
}
|
|
81
|
-
/**
|
|
82
|
-
|
|
83
|
-
|
|
123
|
+
/**
|
|
124
|
+
* Вставить скомпилированный код в index.html. Метка {main.kuza} — обычный
|
|
125
|
+
* HTML-комментарий/плейсхолдер, поэтому каркас остаётся нормальной страницей.
|
|
126
|
+
*/
|
|
127
|
+
function pageHtml(code, dir, scriptName) {
|
|
128
|
+
const tag = `<script>\n// ${NAME} ${VERSION}: собрано из ${scriptName}. Правь .kuza-файл, а не этот файл.\n${code}</script>`;
|
|
129
|
+
const shellPath = join(dir, "index.html");
|
|
130
|
+
if (existsSync(shellPath)) {
|
|
131
|
+
let shell = readFileSync(shellPath, "utf8");
|
|
132
|
+
for (const marker of [`{${scriptName}}`, `{main${FILE_EXT}}`, "{kuza}"]) {
|
|
133
|
+
if (shell.includes(marker))
|
|
134
|
+
return shell.split(marker).join(tag);
|
|
135
|
+
}
|
|
136
|
+
if (shell.includes("</body>"))
|
|
137
|
+
return shell.replace("</body>", `${tag}\n</body>`);
|
|
138
|
+
return `${shell}\n${tag}\n`;
|
|
139
|
+
}
|
|
140
|
+
return `<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n<title>${NAME}</title>\n<script src="https://cdn.tailwindcss.com"></script>\n</head>\n<body>\n${tag}\n</body>\n</html>\n`;
|
|
141
|
+
}
|
|
142
|
+
const LIVE_RELOAD = '<script>(function(){let last=null;async function check(){try{const r=await fetch("/__kuza/reload?path="+encodeURIComponent(location.pathname),{cache:"no-store"});const d=await r.json();if(last!==null&&d.mtime!==last)location.reload();last=d.mtime;}catch(e){}}setInterval(check,700);check();})();</script>';
|
|
143
|
+
/** Все страницы проекта: главная + pages/*.kuza. */
|
|
144
|
+
function projectPages(dir) {
|
|
145
|
+
const pages = new Map();
|
|
146
|
+
for (const name of [`main${FILE_EXT}`, `index${FILE_EXT}`]) {
|
|
147
|
+
const path = join(dir, name);
|
|
148
|
+
if (existsSync(path)) {
|
|
149
|
+
pages.set("/", path);
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const pagesDir = join(dir, "pages");
|
|
154
|
+
if (existsSync(pagesDir)) {
|
|
155
|
+
for (const name of readdirSync(pagesDir)) {
|
|
156
|
+
if (!name.endsWith(FILE_EXT))
|
|
157
|
+
continue;
|
|
158
|
+
const route = name === `index${FILE_EXT}` ? "index" : name.slice(0, -FILE_EXT.length);
|
|
159
|
+
pages.set(`/${route}`, join(pagesDir, name));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return pages;
|
|
163
|
+
}
|
|
164
|
+
function projectEntry(dir = process.cwd()) {
|
|
165
|
+
return projectPages(dir).get("/");
|
|
166
|
+
}
|
|
167
|
+
function relativeEntries(dir = process.cwd()) {
|
|
168
|
+
return [...projectPages(dir).entries()].map(([route, path]) => `${route} → ${relative(dir, path)}`);
|
|
169
|
+
}
|
|
170
|
+
function mtimeOf(path) {
|
|
171
|
+
try {
|
|
172
|
+
return statSync(path).mtimeMs;
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return 0;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function startDevServer(file, portArg) {
|
|
179
|
+
const dir = file ? dirname(resolve(file)) : process.cwd();
|
|
180
|
+
const pages = projectPages(dir);
|
|
181
|
+
const cfg = await config();
|
|
182
|
+
const port = Number(portArg ?? process.env.PORT ?? 5173);
|
|
183
|
+
const server = createServer((request, response) => {
|
|
184
|
+
const urlPath = decodeURIComponent((request.url || "/").split("?")[0] || "/");
|
|
185
|
+
if (urlPath === "/__kuza/reload") {
|
|
186
|
+
const raw = (request.url || "").split("?")[1] || "";
|
|
187
|
+
const wanted = new URLSearchParams(raw).get("path") || "/";
|
|
188
|
+
const source = pages.get(wanted) ?? pages.get(wanted.replace(/\.html$/, "")) ?? pages.get("/");
|
|
189
|
+
response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
190
|
+
response.end(JSON.stringify({ mtime: source ? mtimeOf(source) : 0 }));
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const pageKey = urlPath.replace(/\.html$/, "");
|
|
194
|
+
const sourcePath = pages.get(pageKey) ?? (pageKey === "/" ? pages.get("/") : undefined);
|
|
195
|
+
if (sourcePath) {
|
|
196
|
+
const source = readFileSync(sourcePath, "utf8");
|
|
197
|
+
const compiled = compileSource(source, sourcePath, cfg);
|
|
198
|
+
if (!compiled.ok) {
|
|
199
|
+
response.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
|
200
|
+
response.end(formatDiagnostic(compiled.errors[0], source));
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const html = pageHtml(compiled.code, dir, basename(sourcePath)).replace("</body>", `${LIVE_RELOAD}\n</body>`);
|
|
204
|
+
response.writeHead(200, {
|
|
205
|
+
"content-type": "text/html; charset=utf-8",
|
|
206
|
+
"cache-control": "no-store",
|
|
207
|
+
});
|
|
208
|
+
response.end(html);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const asset = [resolve(dir, `.${urlPath}`), resolve(dir, "public", `.${urlPath}`)].find((candidate) => candidate.startsWith(dir) && existsSync(candidate) && statSync(candidate).isFile());
|
|
212
|
+
if (asset) {
|
|
213
|
+
response.writeHead(200, {
|
|
214
|
+
"content-type": MIME[extname(asset)] ?? "application/octet-stream",
|
|
215
|
+
});
|
|
216
|
+
response.end(readFileSync(asset));
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
|
|
220
|
+
response.end("Not found");
|
|
221
|
+
});
|
|
222
|
+
server.listen(port, "127.0.0.1", () => {
|
|
223
|
+
console.log(success(`Kuza dev server: http://localhost:${port}`));
|
|
224
|
+
console.log(dim("Страницы: " + relativeEntries(dir).join(", ")));
|
|
225
|
+
console.log(dim("Измени .kuza — браузер обновится сам. Ctrl+C — остановить."));
|
|
226
|
+
});
|
|
84
227
|
}
|
|
85
|
-
function buildFile(file, web) {
|
|
228
|
+
function buildFile(file, web, cfg, outputFile) {
|
|
86
229
|
const path = resolve(file);
|
|
87
230
|
if (!existsSync(path)) {
|
|
88
231
|
fail(`${t("fileNotFound")}: ${file}`);
|
|
89
232
|
return;
|
|
90
233
|
}
|
|
91
234
|
const source = readFileSync(path, "utf8");
|
|
92
|
-
const compiled =
|
|
93
|
-
standalone: true,
|
|
94
|
-
filename: path,
|
|
95
|
-
resolveModule: moduleResolver(path),
|
|
96
|
-
});
|
|
235
|
+
const compiled = compileSource(source, path, cfg);
|
|
97
236
|
if (!compiled.ok) {
|
|
98
237
|
console.error(danger(`${t("compileError")}: ${basename(path)}`));
|
|
99
238
|
console.error(danger(formatDiagnostic(compiled.errors[0], source)));
|
|
@@ -101,15 +240,69 @@ function buildFile(file, web) {
|
|
|
101
240
|
return;
|
|
102
241
|
}
|
|
103
242
|
const base = path.slice(0, path.length - extname(path).length);
|
|
104
|
-
const outPath = web ? `${base}.html` : `${base}.js
|
|
105
|
-
|
|
243
|
+
const outPath = outputFile ?? (web ? `${base}.html` : `${base}.js`);
|
|
244
|
+
mkdirSync(dirname(outPath), { recursive: true });
|
|
245
|
+
const code = applyBuildHooks(cfg, { code: compiled.code, filename: path, output: outPath });
|
|
246
|
+
if (web) {
|
|
247
|
+
const page = pageHtml(code, dirname(path), basename(path));
|
|
248
|
+
writeFileSync(outPath, page, "utf8");
|
|
249
|
+
console.log(success(`✓ ${t("built")} ${outPath}`));
|
|
250
|
+
console.log(dim(`${t("openInBrowser")}: `) + code2(`"${relative(process.cwd(), outPath)}"`));
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
writeFileSync(outPath, code, "utf8");
|
|
106
254
|
console.log(success(`✓ ${t("built")} ${outPath}`));
|
|
107
|
-
console.log(
|
|
108
|
-
|
|
109
|
-
|
|
255
|
+
console.log(dim(`${t("runWithNode")}: `) + code2(`node "${relative(process.cwd(), outPath)}"`));
|
|
256
|
+
}
|
|
257
|
+
function code2(value) {
|
|
258
|
+
return code(value);
|
|
110
259
|
}
|
|
111
|
-
|
|
112
|
-
|
|
260
|
+
function copyDir(from, to) {
|
|
261
|
+
if (!existsSync(from))
|
|
262
|
+
return;
|
|
263
|
+
mkdirSync(to, { recursive: true });
|
|
264
|
+
for (const entry of readdirSync(from)) {
|
|
265
|
+
const source = join(from, entry);
|
|
266
|
+
const target = join(to, entry);
|
|
267
|
+
if (statSync(source).isDirectory())
|
|
268
|
+
copyDir(source, target);
|
|
269
|
+
else
|
|
270
|
+
copyFileSync(source, target);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
async function buildProject() {
|
|
274
|
+
const dir = process.cwd();
|
|
275
|
+
const cfg = await config();
|
|
276
|
+
const pages = projectPages(dir);
|
|
277
|
+
if (pages.size === 0) {
|
|
278
|
+
fail(`Не найден main${FILE_EXT}. Запусти kuza new.`);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
const dist = join(dir, "dist");
|
|
282
|
+
mkdirSync(dist, { recursive: true });
|
|
283
|
+
for (const [route, sourcePath] of pages) {
|
|
284
|
+
const source = readFileSync(sourcePath, "utf8");
|
|
285
|
+
const compiled = compileSource(source, sourcePath, cfg);
|
|
286
|
+
if (!compiled.ok) {
|
|
287
|
+
console.error(danger(`${t("compileError")}: ${relative(dir, sourcePath)}`));
|
|
288
|
+
console.error(danger(formatDiagnostic(compiled.errors[0], source)));
|
|
289
|
+
process.exitCode = 1;
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
const output = route === "/" ? join(dist, "index.html") : join(dist, route, "index.html");
|
|
293
|
+
mkdirSync(dirname(output), { recursive: true });
|
|
294
|
+
const js = applyBuildHooks(cfg, {
|
|
295
|
+
code: compiled.code,
|
|
296
|
+
filename: sourcePath,
|
|
297
|
+
output,
|
|
298
|
+
});
|
|
299
|
+
writeFileSync(output, pageHtml(js, dir, basename(sourcePath)), "utf8");
|
|
300
|
+
console.log(success(`✓ ${output}`));
|
|
301
|
+
}
|
|
302
|
+
copyDir(join(dir, "public"), dist);
|
|
303
|
+
console.log(dim("Готово. Открой dist/index.html или запусти kuza start."));
|
|
304
|
+
}
|
|
305
|
+
function watchProject(file, web, cfg) {
|
|
113
306
|
const path = resolve(file);
|
|
114
307
|
if (!existsSync(path)) {
|
|
115
308
|
fail(`${t("fileNotFound")}: ${file}`);
|
|
@@ -117,7 +310,7 @@ function watchProject(file, web) {
|
|
|
117
310
|
}
|
|
118
311
|
const rebuild = () => {
|
|
119
312
|
process.exitCode = 0;
|
|
120
|
-
buildFile(file, web);
|
|
313
|
+
buildFile(file, web, cfg);
|
|
121
314
|
};
|
|
122
315
|
rebuild();
|
|
123
316
|
watchFile(path, { interval: 400 }, (current, previous) => {
|
|
@@ -128,41 +321,76 @@ function watchProject(file, web) {
|
|
|
128
321
|
});
|
|
129
322
|
console.log(dim(t("watching")));
|
|
130
323
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
324
|
+
async function checkProject() {
|
|
325
|
+
const dir = process.cwd();
|
|
326
|
+
const cfg = await config();
|
|
327
|
+
const files = [];
|
|
328
|
+
const collect = (folder) => {
|
|
329
|
+
if (!existsSync(folder))
|
|
330
|
+
return;
|
|
331
|
+
for (const name of readdirSync(folder)) {
|
|
332
|
+
const path = join(folder, name);
|
|
333
|
+
if (statSync(path).isDirectory())
|
|
334
|
+
collect(path);
|
|
335
|
+
else if (name.endsWith(FILE_EXT))
|
|
336
|
+
files.push(path);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
collect(dir);
|
|
340
|
+
const filtered = files.filter((path) => !path.includes(`${dirname(dir)}\\`));
|
|
341
|
+
if (filtered.length === 0)
|
|
342
|
+
filtered.push(...projectPages(dir).values());
|
|
343
|
+
let errors = 0;
|
|
344
|
+
for (const path of filtered) {
|
|
345
|
+
const source = readFileSync(path, "utf8");
|
|
346
|
+
const result = compileSource(source, path, cfg, false);
|
|
347
|
+
if (result.ok) {
|
|
348
|
+
console.log(success(`✓ ${relative(dir, path)}`));
|
|
349
|
+
}
|
|
350
|
+
else {
|
|
351
|
+
errors++;
|
|
352
|
+
console.error(danger(`✕ ${relative(dir, path)}`));
|
|
353
|
+
console.error(danger(formatDiagnostic(result.errors[0], source)));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
console.log(errors === 0 ? success("✓ Всё компилируется") : danger(`Ошибок: ${errors}`));
|
|
357
|
+
if (errors > 0)
|
|
358
|
+
process.exitCode = 1;
|
|
359
|
+
}
|
|
360
|
+
async function serveCommand(file) {
|
|
361
|
+
const path = resolve(file);
|
|
362
|
+
if (!existsSync(path)) {
|
|
363
|
+
fail(`${t("fileNotFound")}: ${file}`);
|
|
151
364
|
return;
|
|
152
365
|
}
|
|
153
|
-
|
|
154
|
-
|
|
366
|
+
const cfg = await config();
|
|
367
|
+
const source = readFileSync(path, "utf8");
|
|
368
|
+
const compiled = compileSource(source, path, cfg);
|
|
369
|
+
if (!compiled.ok) {
|
|
370
|
+
console.error(danger(formatDiagnostic(compiled.errors[0], source)));
|
|
371
|
+
process.exitCode = 1;
|
|
372
|
+
return;
|
|
155
373
|
}
|
|
156
|
-
|
|
157
|
-
|
|
374
|
+
const result = await run(source, { filename: path, resolveModule: moduleResolver(path) });
|
|
375
|
+
for (const entry of result.output)
|
|
376
|
+
printEntry(entry);
|
|
377
|
+
applyRunHooks(cfg, { result, filename: path });
|
|
378
|
+
// Даём динамическому import("node:http") момент на запуск слушателя.
|
|
379
|
+
await new Promise((done) => setTimeout(done, 100));
|
|
380
|
+
}
|
|
381
|
+
function scaffoldCommand(target, web, force) {
|
|
382
|
+
const dir = target ? resolve(target) : process.cwd();
|
|
383
|
+
const created = scaffoldProject(dir, { scriptOnly: !web, force });
|
|
384
|
+
if (created.length === 0) {
|
|
385
|
+
console.log(warning("Файлы уже есть — ничего не перезаписано."));
|
|
158
386
|
return;
|
|
159
387
|
}
|
|
160
|
-
console.log(success(`✓ ${
|
|
161
|
-
console.log(dim(
|
|
388
|
+
console.log(success(`✓ Создано: ${created.join(", ")}`));
|
|
389
|
+
console.log(dim("Дальше: ") + code("cd " + relative(process.cwd(), dir) + " && npm install && npm run dev"));
|
|
162
390
|
}
|
|
163
391
|
async function main() {
|
|
164
392
|
const [first, ...rest] = argv;
|
|
165
|
-
if (!first) {
|
|
393
|
+
if (!first || first === "repl") {
|
|
166
394
|
printBanner();
|
|
167
395
|
await startRepl();
|
|
168
396
|
return;
|
|
@@ -175,22 +403,74 @@ async function main() {
|
|
|
175
403
|
usage();
|
|
176
404
|
return;
|
|
177
405
|
}
|
|
178
|
-
if (first === "
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
406
|
+
if (first === "new" || first === "create" || first === "init") {
|
|
407
|
+
scaffoldCommand(rest.find((arg) => !arg.startsWith("--")), !rest.includes("--script"), rest.includes("--force"));
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
if (first === "start" || first === "dev") {
|
|
411
|
+
const target = rest.find((arg) => !arg.startsWith("--") && !arg.startsWith("--port="));
|
|
412
|
+
const portArg = rest.find((arg) => arg.startsWith("--port="))?.slice("--port=".length);
|
|
413
|
+
const file = target ?? projectEntry();
|
|
414
|
+
if (!file && !target)
|
|
415
|
+
return fail(`Не найден main${FILE_EXT}. Запусти kuza new.`);
|
|
416
|
+
await startDevServer(file, portArg);
|
|
184
417
|
return;
|
|
185
418
|
}
|
|
186
419
|
if (first === "build") {
|
|
187
|
-
const web = rest.includes("--web");
|
|
188
420
|
const target = rest.find((arg) => !arg.startsWith("--"));
|
|
189
421
|
if (!target) {
|
|
190
|
-
|
|
422
|
+
await buildProject();
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
await buildFile(target, rest.includes("--web"), await config());
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
if (first === "check" || first === "doctor") {
|
|
429
|
+
await checkProject();
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
if (first === "serve") {
|
|
433
|
+
const target = rest.find((arg) => !arg.startsWith("--")) || projectEntry();
|
|
434
|
+
if (!target)
|
|
435
|
+
return fail(`Укажи серверный файл: kuza serve server${FILE_EXT}`);
|
|
436
|
+
await serveCommand(target);
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
if (first === "ai" || first === "ask") {
|
|
440
|
+
const files = [];
|
|
441
|
+
const words = [];
|
|
442
|
+
for (let index = 0; index < rest.length; index++) {
|
|
443
|
+
const arg = rest[index];
|
|
444
|
+
if (arg === "--file" || arg === "-f") {
|
|
445
|
+
const next = rest[++index];
|
|
446
|
+
if (next)
|
|
447
|
+
files.push(next);
|
|
448
|
+
}
|
|
449
|
+
else if (!arg.startsWith("--")) {
|
|
450
|
+
words.push(arg);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
if (words.length === 0) {
|
|
454
|
+
fail('Спроси что-нибудь: kuza ai "объясни main.kuza"');
|
|
191
455
|
return;
|
|
192
456
|
}
|
|
193
|
-
|
|
457
|
+
await runAiQuestion(words.join(" "), files);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (first === "docs") {
|
|
461
|
+
const start = join(process.cwd(), "START.md");
|
|
462
|
+
if (existsSync(start))
|
|
463
|
+
console.log(start);
|
|
464
|
+
else
|
|
465
|
+
console.log("https://github.com/kuza-lang/kuza/blob/main/docs/commands.md");
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
if (first === "run") {
|
|
469
|
+
if (!rest[0]) {
|
|
470
|
+
fail(`Укажи файл: ${NAME.toLowerCase()} run main${FILE_EXT}`);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
await runFile(rest[0]);
|
|
194
474
|
return;
|
|
195
475
|
}
|
|
196
476
|
if (first === "watch") {
|
|
@@ -200,11 +480,7 @@ async function main() {
|
|
|
200
480
|
fail(`Укажи файл: ${NAME.toLowerCase()} watch main${FILE_EXT}`);
|
|
201
481
|
return;
|
|
202
482
|
}
|
|
203
|
-
watchProject(target, web);
|
|
204
|
-
return;
|
|
205
|
-
}
|
|
206
|
-
if (first === "init") {
|
|
207
|
-
initProject(rest[0]);
|
|
483
|
+
watchProject(target, web, await config());
|
|
208
484
|
return;
|
|
209
485
|
}
|
|
210
486
|
if (first.endsWith(FILE_EXT)) {
|
package/dist/scaffold.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Единый генератор проектов: используется и `kuza new/init`, и postinstall.
|
|
3
|
+
* Шаблоны лежат в packages/cli/templates и попадают в npm-пакет целиком.
|
|
4
|
+
*/
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
7
|
+
import { FILE_EXT, VERSION } from "kuza-core";
|
|
8
|
+
const TEMPLATES = new URL("../templates/", import.meta.url);
|
|
9
|
+
function template(name) {
|
|
10
|
+
return readFileSync(new URL(name, TEMPLATES), "utf8");
|
|
11
|
+
}
|
|
12
|
+
function packageName(dir) {
|
|
13
|
+
const raw = basename(dir).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
14
|
+
return raw || "kuza-app";
|
|
15
|
+
}
|
|
16
|
+
function patchPackageJson(dir, created, force) {
|
|
17
|
+
const path = join(dir, "package.json");
|
|
18
|
+
const scripts = {
|
|
19
|
+
dev: "kuza dev",
|
|
20
|
+
start: "kuza dev",
|
|
21
|
+
build: "kuza build",
|
|
22
|
+
check: "kuza check",
|
|
23
|
+
};
|
|
24
|
+
let data;
|
|
25
|
+
if (existsSync(path)) {
|
|
26
|
+
try {
|
|
27
|
+
data = JSON.parse(readFileSync(path, "utf8"));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
if (!force)
|
|
31
|
+
return;
|
|
32
|
+
data = {};
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
data = {};
|
|
37
|
+
}
|
|
38
|
+
if (!data.name)
|
|
39
|
+
data.name = packageName(dir);
|
|
40
|
+
if (!data.private)
|
|
41
|
+
data.private = true;
|
|
42
|
+
if (!data.type)
|
|
43
|
+
data.type = "module";
|
|
44
|
+
data.scripts = { ...scripts, ...data.scripts };
|
|
45
|
+
const deps = (data.dependencies ?? {});
|
|
46
|
+
if (!deps["kuza-lang"])
|
|
47
|
+
deps["kuza-lang"] = `^${VERSION}`;
|
|
48
|
+
data.dependencies = deps;
|
|
49
|
+
if (!existsSync(path) || force)
|
|
50
|
+
created.push("package.json");
|
|
51
|
+
writeFileSync(path, JSON.stringify(data, null, 2) + "\n", "utf8");
|
|
52
|
+
}
|
|
53
|
+
/** Создать базовый проект. Возвращает список созданных файлов. */
|
|
54
|
+
export function scaffoldProject(target, options = {}) {
|
|
55
|
+
const dir = resolve(target ?? process.cwd());
|
|
56
|
+
const force = options.force ?? false;
|
|
57
|
+
mkdirSync(dir, { recursive: true });
|
|
58
|
+
const created = [];
|
|
59
|
+
const write = (name, content) => {
|
|
60
|
+
const path = join(dir, name);
|
|
61
|
+
if (existsSync(path) && !force)
|
|
62
|
+
return;
|
|
63
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
64
|
+
writeFileSync(path, content, { encoding: "utf8", flag: force ? "w" : "wx" });
|
|
65
|
+
created.push(name);
|
|
66
|
+
};
|
|
67
|
+
if (options.scriptOnly) {
|
|
68
|
+
write(`main${FILE_EXT}`, template("main-script.kuza"));
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
write("index.html", template("index.html"));
|
|
72
|
+
write("public/favicon.svg", template("public/favicon.svg"));
|
|
73
|
+
write(`main${FILE_EXT}`, template("main.kuza"));
|
|
74
|
+
write("START.md", template("START.md"));
|
|
75
|
+
write("README.md", `# ${packageName(dir)}\n\nA website built with Kuza.\n\n` +
|
|
76
|
+
"```bash\nnpm install\nnpm run dev\n```\n\n" +
|
|
77
|
+
"Open `START.md` for commands, AI, plugins, backend and VS Code setup.\n");
|
|
78
|
+
write(".gitignore", "node_modules/\ndist/\n.env\n");
|
|
79
|
+
}
|
|
80
|
+
patchPackageJson(dir, created, force);
|
|
81
|
+
return created;
|
|
82
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kuza-lang",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Kuza — консоль языка: запуск, сборка, REPL и ИИ-помощник",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
"main": "./dist/index.js",
|
|
11
11
|
"files": [
|
|
12
12
|
"dist",
|
|
13
|
+
"templates",
|
|
14
|
+
"scripts/postinstall.mjs",
|
|
13
15
|
"README.md"
|
|
14
16
|
],
|
|
15
17
|
"engines": {
|
|
@@ -24,10 +26,11 @@
|
|
|
24
26
|
],
|
|
25
27
|
"scripts": {
|
|
26
28
|
"build": "tsc -p tsconfig.json",
|
|
29
|
+
"postinstall": "node scripts/postinstall.mjs",
|
|
27
30
|
"start": "node dist/index.js"
|
|
28
31
|
},
|
|
29
32
|
"dependencies": {
|
|
30
|
-
"kuza-core": "^0.
|
|
33
|
+
"kuza-core": "^0.5.0",
|
|
31
34
|
"boxen": "^8.0.1",
|
|
32
35
|
"chalk": "^5.3.0",
|
|
33
36
|
"gradient-string": "^3.0.0"
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* postinstall для kuza-lang.
|
|
3
|
+
*
|
|
4
|
+
* npm вызывает его из папки самого пакета, поэтому настоящую папку проекта
|
|
5
|
+
* берём из INIT_CWD. Скаффолдим только «свежий» проект: если уже есть другой
|
|
6
|
+
* код или зависимости, молча ничего не трогаем.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
10
|
+
import { join, resolve } from "node:path";
|
|
11
|
+
|
|
12
|
+
const cwd = process.env.INIT_CWD ? resolve(process.env.INIT_CWD) : process.cwd();
|
|
13
|
+
|
|
14
|
+
if (process.env.npm_config_global === "true") process.exit(0);
|
|
15
|
+
|
|
16
|
+
const has = (name) => existsSync(join(cwd, name));
|
|
17
|
+
if (has("index.html") || has("src") || has("app") || has("pages") || has("main.kuza")) {
|
|
18
|
+
process.exit(0);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
try {
|
|
22
|
+
const pkg = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
|
|
23
|
+
const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
|
|
24
|
+
const other = Object.keys(deps).filter((name) => name !== "kuza-lang");
|
|
25
|
+
if (other.length > 0 || /kuza-monorepo/.test(String(pkg.name || ""))) process.exit(0);
|
|
26
|
+
} catch {
|
|
27
|
+
// package.json ещё нет — это тоже свежий проект, создадим его.
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
const { scaffoldProject } = await import(new URL("../dist/scaffold.js", import.meta.url));
|
|
32
|
+
const created = scaffoldProject(cwd);
|
|
33
|
+
if (created.length > 0) {
|
|
34
|
+
console.log("\nKuza: created " + created.join(", "));
|
|
35
|
+
console.log("Kuza: run `npm run dev` → http://localhost:5173\n");
|
|
36
|
+
}
|
|
37
|
+
} catch {
|
|
38
|
+
// postinstall никогда не должен ломать установку.
|
|
39
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# Kuza — start here
|
|
2
|
+
|
|
3
|
+
You already have a working Kuza project.
|
|
4
|
+
|
|
5
|
+
```text
|
|
6
|
+
index.html — page shell (Tailwind is already connected)
|
|
7
|
+
main.kuza — the whole application
|
|
8
|
+
public/favicon.svg — the site icon
|
|
9
|
+
START.md — this instruction
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
> Kuza files use `.kuza`. `index.qza` / `main.qza` are not used — the language is
|
|
13
|
+
> **Kuza**, so the extension is `.kuza`.
|
|
14
|
+
|
|
15
|
+
## 1. Run it
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm run dev # http://localhost:5173
|
|
19
|
+
npm run build # production site in dist/
|
|
20
|
+
npm run check # compile without running
|
|
21
|
+
npm test # if you add tests
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`npm start` is an alias for `npm run dev`.
|
|
25
|
+
|
|
26
|
+
## 2. Change it
|
|
27
|
+
|
|
28
|
+
Open `main.kuza`. The `view` block is the screen:
|
|
29
|
+
|
|
30
|
+
```kuza
|
|
31
|
+
:count = 0;
|
|
32
|
+
|
|
33
|
+
view App<> >> [
|
|
34
|
+
body<"p-8"> >> [
|
|
35
|
+
heading >> <"Count: {count}", "text-2xl font-bold">;
|
|
36
|
+
button >> <"Add one", increase, "rounded bg-orange-500 px-4 py-2">;
|
|
37
|
+
];
|
|
38
|
+
render;
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
func increase<> >> [
|
|
42
|
+
count = count + 1; // the screen updates automatically
|
|
43
|
+
];
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Classes are Tailwind classes, written right in Kuza. Containers also accept
|
|
47
|
+
classes: `card >> <"p-4">` or `card<"p-4"> >> [ ... ]`.
|
|
48
|
+
|
|
49
|
+
## 3. More pages
|
|
50
|
+
|
|
51
|
+
Create `pages/about.kuza`. It becomes available at `/about` in dev and
|
|
52
|
+
`dist/about/index.html` after build. `main.kuza` stays the home page.
|
|
53
|
+
|
|
54
|
+
## 4. CLI
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
npx kuza-lang new my-site # create a project in ./my-site
|
|
58
|
+
kuza start # same as kuza dev
|
|
59
|
+
kuza build # build into dist/
|
|
60
|
+
kuza check # check syntax
|
|
61
|
+
kuza ai "explain main.kuza" # AI assistant reads your files
|
|
62
|
+
kuza help # all commands
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## 5. AI assistant
|
|
66
|
+
|
|
67
|
+
The assistant can read `.kuza`, `.html`, `.js`, `.ts`, `.json` and `.md` files
|
|
68
|
+
from the current folder. Set a key in `.env` or in the environment:
|
|
69
|
+
|
|
70
|
+
```dotenv
|
|
71
|
+
KUZA_AI_PROVIDER=openai
|
|
72
|
+
KUZA_AI_KEY=sk-...
|
|
73
|
+
KUZA_AI_MODEL=gpt-4o-mini
|
|
74
|
+
# or for Anthropic:
|
|
75
|
+
# ANTHROPIC_API_KEY=...
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
OpenAI-compatible services (OpenRouter, Groq, Ollama, Freebuff) work through
|
|
79
|
+
`KUZA_AI_BASE_URL`. The key is never printed.
|
|
80
|
+
|
|
81
|
+
## 6. Backend
|
|
82
|
+
|
|
83
|
+
```kuza
|
|
84
|
+
func home<> >> [
|
|
85
|
+
respond >> <{ ok: true, message: "Hello" }, 200>;
|
|
86
|
+
];
|
|
87
|
+
|
|
88
|
+
route >> <"GET", "/", home>;
|
|
89
|
+
listen >> 3000;
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Run with `kuza serve server.kuza`, then open `http://localhost:3000`.
|
|
93
|
+
`param`, `query`, `requestBody`, `header`, `method` and `serverPath` read the
|
|
94
|
+
current request.
|
|
95
|
+
|
|
96
|
+
## 7. Plugins
|
|
97
|
+
|
|
98
|
+
Create `kuza.config.js` next to `package.json`:
|
|
99
|
+
|
|
100
|
+
```js
|
|
101
|
+
export default {
|
|
102
|
+
commands: [
|
|
103
|
+
{
|
|
104
|
+
id: "shout", name: "shout", aliases: [], category: "output",
|
|
105
|
+
args: "single", params: ["text"],
|
|
106
|
+
description: "Uppercase output", example: 'shout >> "hi";',
|
|
107
|
+
codegen: "console.log(String({0}).toUpperCase())",
|
|
108
|
+
},
|
|
109
|
+
],
|
|
110
|
+
plugins: [
|
|
111
|
+
{
|
|
112
|
+
name: "my-plugin",
|
|
113
|
+
setup(api) {
|
|
114
|
+
api.onCompile(({ source }) => source);
|
|
115
|
+
api.onBuild(({ code }) => code);
|
|
116
|
+
api.onRun(({ result }) => result);
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
],
|
|
120
|
+
};
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## 8. VS Code
|
|
124
|
+
|
|
125
|
+
Search for **Kuza** in the Extensions panel, or install the local
|
|
126
|
+
`packages/vscode/*.vsix` via **Install from VSIX…**. The extension gives
|
|
127
|
+
syntax highlighting, completion, diagnostics and Run/Build/Dev buttons.
|
|
128
|
+
|
|
129
|
+
## Links
|
|
130
|
+
|
|
131
|
+
- All commands: https://github.com/kuza-lang/kuza/blob/main/docs/commands.md
|
|
132
|
+
- Compiler API: `import { compile, run } from "kuza-core"`
|
|
133
|
+
- Package with CLI: `kuza-lang`
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
+
<meta name="theme-color" content="#101417" />
|
|
7
|
+
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
8
|
+
<meta
|
|
9
|
+
name="description"
|
|
10
|
+
content="A Kuza website. Edit main.kuza and the screen updates automatically."
|
|
11
|
+
/>
|
|
12
|
+
<title>My Kuza app</title>
|
|
13
|
+
<script src="https://cdn.tailwindcss.com"></script>
|
|
14
|
+
</head>
|
|
15
|
+
<body class="min-h-screen bg-slate-950">
|
|
16
|
+
<!-- Kuza mounts the application here. Do not remove this marker. -->
|
|
17
|
+
{main.kuza}
|
|
18
|
+
</body>
|
|
19
|
+
</html>
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
## main.kuza — first console program on Kuza
|
|
2
|
+
## Run: npx kuza-lang run main.kuza
|
|
3
|
+
|
|
4
|
+
:name = "world";
|
|
5
|
+
log >> "Hello, {name}!";
|
|
6
|
+
|
|
7
|
+
:numbers = [1, 2, 3, 4, 5];
|
|
8
|
+
log >> "Sum: {sum >> numbers}";
|
|
9
|
+
|
|
10
|
+
?len >> numbers > 3 >> [
|
|
11
|
+
log >> "More than three numbers";
|
|
12
|
+
] || [
|
|
13
|
+
log >> "Too few numbers";
|
|
14
|
+
]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
## main.kuza — your first Kuza website
|
|
2
|
+
## npm run dev → http://localhost:5173
|
|
3
|
+
## npm run build → dist/index.html
|
|
4
|
+
## Edit this file. The view updates automatically when count changes.
|
|
5
|
+
|
|
6
|
+
:count = 0;
|
|
7
|
+
|
|
8
|
+
view App<> >> [
|
|
9
|
+
page >> "Hello, Kuza!";
|
|
10
|
+
|
|
11
|
+
body<"mx-auto max-w-2xl px-6 py-16"> >> [
|
|
12
|
+
card<"rounded-2xl border border-white/10 bg-white/5 p-8 shadow-xl"> >> [
|
|
13
|
+
image >> <"/favicon.svg", "Kuza icon">;
|
|
14
|
+
heading >> <"Hello, Kuza!", "mt-4 text-4xl font-bold tracking-tight text-white">;
|
|
15
|
+
para >> <"Your first website. Change main.kuza — no manual redraw needed.", "mt-3 text-slate-300">;
|
|
16
|
+
para >> <"Count: {count}", "mt-8 text-2xl font-semibold text-orange-400">;
|
|
17
|
+
|
|
18
|
+
row<"mt-5 flex flex-wrap gap-3"> >> [
|
|
19
|
+
button >> <"Add one", increase, "rounded-lg bg-orange-500 px-4 py-2 font-semibold text-slate-950 hover:bg-orange-400">;
|
|
20
|
+
button >> <"Reset", reset, "rounded-lg border border-white/20 px-4 py-2 text-slate-200 hover:bg-white/10">;
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
link >> <"Read the docs", "https://github.com/kuza-lang/kuza/blob/main/docs/commands.md", "mt-6 inline-block text-orange-400 underline underline-offset-4">;
|
|
24
|
+
];
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
render;
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
func increase<> >> [
|
|
31
|
+
count = count + 1;
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
func reset<> >> [
|
|
35
|
+
count = 0;
|
|
36
|
+
];
|