@cadence-app/compiler 0.1.0 → 0.2.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 CHANGED
@@ -9,16 +9,30 @@ Ce paquet ne tourne jamais dans une WebView. Il travaille une fois, avant la liv
9
9
  ## Installation
10
10
 
11
11
  ```bash
12
- pnpm add -D @cadence-app/compiler
12
+ npm install --save-dev @cadence-app/compiler
13
+ ```
14
+
15
+ Avec pnpm, autorisez la compilation d'esbuild dans `pnpm-workspace.yaml` — sans quoi `pnpm exec`
16
+ refuse de démarrer :
17
+
18
+ ```yaml
19
+ allowBuilds:
20
+ esbuild: true
21
+ '@parcel/watcher': true
13
22
  ```
14
23
 
15
24
  ## La commande
16
25
 
17
26
  ```bash
18
- mini build mon-mini-programme --minify
19
- mini dev mon-mini-programme
27
+ npx mini init mon-mini-programme
28
+ npx mini build mon-mini-programme --minify
29
+ npx mini dev mon-mini-programme
20
30
  ```
21
31
 
32
+ `init` écrit un mini-programme qui se compile déjà, dans un dossier absent ou vide. Trois
33
+ squelettes, par `--template` : `page` (défaut), `onglets` pour une tab bar, `composant` pour un
34
+ composant à soi.
35
+
22
36
  `build` rend un dossier `dist` : `engine.js`, `app.js`, la feuille de thème, les pages, les icônes
23
37
  et une archive prête à distribuer. Le budget du moteur — 30 ko gzip — est vérifié à chaque
24
38
  construction, et un dépassement fait échouer la commande.
@@ -26,7 +40,7 @@ construction, et un dépassement fait échouer la commande.
26
40
  `dev` sert le mini-programme dans un navigateur, avec un hôte simulé : le geste retour tient à la
27
41
  touche Échap, et masquer l'onglet annonce l'arrière-plan.
28
42
 
29
- Deux commandes complètent l'ensemble : `mini publish`, `mini whoami` et `mini logout`, pour une
43
+ Trois commandes complètent l'ensemble : `mini publish`, `mini whoami` et `mini logout`, pour une
30
44
  distribution par backend.
31
45
 
32
46
  ## La bibliothèque
package/dist/cli.js CHANGED
@@ -4,13 +4,20 @@ import { parseArgs } from 'node:util';
4
4
  import { buildMiniApp } from "./build.js";
5
5
  import { startDevServer } from "./dev-server.js";
6
6
  import { ENGINE_GZIP_BUDGET_BYTES, engineBudgetVerdict } from "./engine-budget.js";
7
+ import { initProject } from "./init-project.js";
8
+ import { PROJECT_TEMPLATES, PROJECT_TEMPLATE_NAMES } from "./project-templates.js";
7
9
  import { clearCredentials, credentialsPath, normalizeRemoteUrl, readCredentials, writeCredentials, } from "./publish/credentials.js";
8
10
  import { DistributionClient } from "./publish/distribution-client.js";
9
11
  import { publishMiniApp } from "./publish/publish-bundle.js";
10
12
  import { readSecret } from "./publish/read-secret.js";
11
13
  const DEFAULT_DEV_PORT = 4173;
14
+ const TEMPLATE_LINES = PROJECT_TEMPLATE_NAMES.map((name) => ` ${name.padEnd(11)}${PROJECT_TEMPLATES[name].description}`).join('\n');
12
15
  const HELP = `mini — outillage des mini-programmes Cadence
13
16
 
17
+ Démarrer :
18
+ mini init <dossier> [--template <nom>]
19
+ ${TEMPLATE_LINES}
20
+
14
21
  Compiler :
15
22
  mini build <dossier-miniapp> [--out <dossier>] [--minify] [--no-zip]
16
23
  mini dev <dossier-miniapp> [--out <dossier>] [--port <n>]
@@ -32,6 +39,7 @@ async function main() {
32
39
  minify: { type: 'boolean', default: false },
33
40
  'no-zip': { type: 'boolean', default: false },
34
41
  port: { type: 'string' },
42
+ template: { type: 'string' },
35
43
  remote: { type: 'string' },
36
44
  token: { type: 'string' },
37
45
  'app-id': { type: 'string' },
@@ -47,6 +55,17 @@ async function main() {
47
55
  await runAccountCommand(command, values);
48
56
  return;
49
57
  }
58
+ if (command === 'init') {
59
+ if (miniappDirArg === undefined) {
60
+ exitWith(`le dossier à créer est requis\n\n mini init mon-miniapp`);
61
+ }
62
+ const report = await initProject({
63
+ targetDir: miniappDirArg,
64
+ ...(values.template === undefined ? {} : { template: values.template }),
65
+ });
66
+ printInitReport(report, miniappDirArg);
67
+ return;
68
+ }
50
69
  if (miniappDirArg === undefined) {
51
70
  exitWith(`le dossier du mini-programme est requis\n\n${HELP}`);
52
71
  }
@@ -123,6 +142,15 @@ async function runAccountCommand(command, values) {
123
142
  console.log(` jeton : ${maskToken(token)}`);
124
143
  console.log(` fichier : ${file} (lisible par vous seul)`);
125
144
  }
145
+ function printInitReport(report, requestedDir) {
146
+ console.log(`mini-programme « ${report.name} » créé → ${report.targetDir}`);
147
+ console.log(` template : ${report.template}`);
148
+ for (const file of report.files) {
149
+ console.log(` + ${file}`);
150
+ }
151
+ console.log('');
152
+ console.log(`Pour le voir tourner : mini dev ${requestedDir}`);
153
+ }
126
154
  function printPublishReport(report) {
127
155
  const sizeKo = (report.archiveBytes / 1024).toFixed(1);
128
156
  console.log(`publié « ${report.slug} » v${report.published.versionString} → ${report.remoteUrl}`);
package/dist/index.d.ts CHANGED
@@ -12,6 +12,10 @@ export type { MiniAppManifest, ManifestPage, ManifestTabBar, ManifestTabBarItem,
12
12
  export { stableHash } from './hash.js';
13
13
  export { buildMiniApp, BuildError } from './build.js';
14
14
  export type { BuildOptions, BuildSummary, SizeReport } from './build.js';
15
+ export { initProject, InitError } from './init-project.js';
16
+ export type { InitOptions, InitReport } from './init-project.js';
17
+ export { PROJECT_TEMPLATES, PROJECT_TEMPLATE_NAMES, isProjectTemplateName, } from './project-templates.js';
18
+ export type { ProjectTemplate, ProjectTemplateName } from './project-templates.js';
15
19
  export { startDevServer } from './dev-server.js';
16
20
  export type { DevServer, DevServerOptions } from './dev-server.js';
17
21
  export { credentialsPath, readCredentials, writeCredentials, clearCredentials, normalizeRemoteUrl, } from './publish/credentials.js';
package/dist/index.js CHANGED
@@ -7,6 +7,8 @@ export { buildThemeSheet } from "./style/theme-sheet.js";
7
7
  export { parseManifest, allManifestPages, ManifestError } from "./manifest.js";
8
8
  export { stableHash } from "./hash.js";
9
9
  export { buildMiniApp, BuildError } from "./build.js";
10
+ export { initProject, InitError } from "./init-project.js";
11
+ export { PROJECT_TEMPLATES, PROJECT_TEMPLATE_NAMES, isProjectTemplateName, } from "./project-templates.js";
10
12
  export { startDevServer } from "./dev-server.js";
11
13
  export { credentialsPath, readCredentials, writeCredentials, clearCredentials, normalizeRemoteUrl, } from "./publish/credentials.js";
12
14
  export { DistributionClient } from "./publish/distribution-client.js";
@@ -0,0 +1,18 @@
1
+ import type { ProjectTemplateName } from './project-templates.js';
2
+ export declare class InitError extends Error {
3
+ constructor(reason: string);
4
+ }
5
+ export interface InitOptions {
6
+ readonly targetDir: string;
7
+ readonly template?: string;
8
+ /** Par défaut, le nom du dossier créé. */
9
+ readonly name?: string;
10
+ }
11
+ export interface InitReport {
12
+ readonly targetDir: string;
13
+ readonly name: string;
14
+ readonly template: ProjectTemplateName;
15
+ /** Chemins relatifs, triés, tels qu'écrits sur le disque. */
16
+ readonly files: readonly string[];
17
+ }
18
+ export declare function initProject(options: InitOptions): Promise<InitReport>;
@@ -0,0 +1,55 @@
1
+ import { mkdir, readdir, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { PROJECT_TEMPLATES, PROJECT_TEMPLATE_NAMES, isProjectTemplateName, } from "./project-templates.js";
4
+ export class InitError extends Error {
5
+ constructor(reason) {
6
+ super(reason);
7
+ this.name = 'InitError';
8
+ }
9
+ }
10
+ const MANIFEST_FILE = 'manifest.json';
11
+ export async function initProject(options) {
12
+ const template = resolveTemplate(options.template);
13
+ const targetDir = path.resolve(options.targetDir);
14
+ const name = options.name ?? path.basename(targetDir);
15
+ if (name === '') {
16
+ throw new InitError('le nom du mini-programme ne peut pas être vide');
17
+ }
18
+ await requireEmptyDirectory(targetDir);
19
+ const manifest = PROJECT_TEMPLATES[template].manifestFor(name);
20
+ const contents = {
21
+ [MANIFEST_FILE]: `${JSON.stringify(manifest, null, 2)}\n`,
22
+ ...PROJECT_TEMPLATES[template].sources,
23
+ };
24
+ const files = Object.keys(contents).sort();
25
+ for (const file of files) {
26
+ const destination = path.join(targetDir, file);
27
+ await mkdir(path.dirname(destination), { recursive: true });
28
+ await writeFile(destination, contents[file] ?? '', 'utf8');
29
+ }
30
+ return { targetDir, name, template, files };
31
+ }
32
+ function resolveTemplate(requested) {
33
+ if (requested === undefined) {
34
+ return 'page';
35
+ }
36
+ if (!isProjectTemplateName(requested)) {
37
+ throw new InitError(`template inconnu : « ${requested} » — au choix ${PROJECT_TEMPLATE_NAMES.join(', ')}`);
38
+ }
39
+ return requested;
40
+ }
41
+ /* Écraser le travail de quelqu'un coûte plus cher que de refuser : on ne crée
42
+ que dans un dossier absent ou vide, et le message dit quoi faire. */
43
+ async function requireEmptyDirectory(targetDir) {
44
+ let entries;
45
+ try {
46
+ entries = await readdir(targetDir);
47
+ }
48
+ catch {
49
+ await mkdir(targetDir, { recursive: true });
50
+ return;
51
+ }
52
+ if (entries.length > 0) {
53
+ throw new InitError(`${targetDir} n'est pas vide — choisissez un autre dossier, ou videz celui-ci`);
54
+ }
55
+ }
@@ -0,0 +1,16 @@
1
+ import type { MiniAppManifest } from './manifest.js';
2
+ export type ProjectTemplateName = 'page' | 'onglets' | 'composant';
3
+ export interface ProjectTemplate {
4
+ /** Une ligne, affichée par `mini init --help`. */
5
+ readonly description: string;
6
+ /**
7
+ * Typé contre le schéma réel : un champ qui disparaîtrait du manifeste
8
+ * casserait la compilation du compilateur, pas le premier build d'un auteur.
9
+ */
10
+ readonly manifestFor: (name: string) => MiniAppManifest;
11
+ /** Chemin relatif au dossier créé → contenu du fichier. */
12
+ readonly sources: Readonly<Record<string, string>>;
13
+ }
14
+ export declare const PROJECT_TEMPLATES: Readonly<Record<ProjectTemplateName, ProjectTemplate>>;
15
+ export declare const PROJECT_TEMPLATE_NAMES: readonly ProjectTemplateName[];
16
+ export declare function isProjectTemplateName(value: string): value is ProjectTemplateName;
@@ -0,0 +1,208 @@
1
+ const HOME_LOGIC = `import { computed, signal } from '@cadence/core';
2
+
3
+ export default function HomePage(): Record<string, unknown> {
4
+ const name = signal('Cadence');
5
+ const isEmpty = computed(() => name().trim().length === 0);
6
+
7
+ function reset(): void {
8
+ name.set('');
9
+ }
10
+
11
+ return { name, isEmpty, reset };
12
+ }
13
+ `;
14
+ const HOME_TEMPLATE = `<view class="page">
15
+ <text class="title">Bonjour {{ name() }}</text>
16
+
17
+ <input [value]="name()" (input)="name.set($event.target.value)" placeholder="Votre nom" />
18
+ <button (tap)="reset()">Effacer</button>
19
+
20
+ @if (isEmpty()) {
21
+ <text class="hint">Dites-nous qui vous êtes.</text>
22
+ }
23
+ </view>
24
+ `;
25
+ const HOME_STYLE = `.page {
26
+ display: flex;
27
+ flex-direction: column;
28
+ gap: var(--cadence-spacing-lg);
29
+ padding: 32rpx;
30
+ }
31
+
32
+ .title {
33
+ font-size: var(--cadence-font-size-title);
34
+ font-weight: var(--cadence-font-weight-emphasis);
35
+ }
36
+
37
+ .hint {
38
+ color: var(--cadence-text-muted);
39
+ }
40
+ `;
41
+ const PROFILE_LOGIC = `import { signal } from '@cadence/core';
42
+
43
+ export default function ProfilePage(): Record<string, unknown> {
44
+ const notifications = signal(true);
45
+
46
+ return { notifications };
47
+ }
48
+ `;
49
+ const PROFILE_TEMPLATE = `<view class="page">
50
+ <text class="title">Profil</text>
51
+
52
+ <cell-group>
53
+ <cell title="Notifications" subtitle="Vous prévenir des nouveautés">
54
+ <icon slot="before" name="bell" />
55
+ <switch
56
+ slot="after"
57
+ [checked]="notifications()"
58
+ (change)="notifications.set($event.detail.checked)"
59
+ />
60
+ </cell>
61
+ </cell-group>
62
+ </view>
63
+ `;
64
+ const PROFILE_STYLE = `.page {
65
+ display: flex;
66
+ flex-direction: column;
67
+ gap: var(--cadence-spacing-lg);
68
+ padding: 32rpx;
69
+ }
70
+
71
+ .title {
72
+ font-size: var(--cadence-font-size-title);
73
+ font-weight: var(--cadence-font-weight-emphasis);
74
+ }
75
+ `;
76
+ const COUNTER_PAGE_LOGIC = `import { signal } from '@cadence/core';
77
+
78
+ export default function HomePage(): Record<string, unknown> {
79
+ const total = signal(0);
80
+
81
+ function add(step: number): void {
82
+ total.set(total() + step);
83
+ }
84
+
85
+ return { total, add };
86
+ }
87
+ `;
88
+ const COUNTER_PAGE_TEMPLATE = `<view class="page">
89
+ <text class="title">Total : {{ total() }}</text>
90
+
91
+ <counter-card [label]="'Un pas'" [step]="1" (tap)="add(1)" />
92
+ <counter-card [label]="'Dix pas'" [step]="10" (tap)="add(10)" />
93
+ </view>
94
+ `;
95
+ const COUNTER_PAGE_STYLE = `.page {
96
+ display: flex;
97
+ flex-direction: column;
98
+ gap: var(--cadence-spacing-lg);
99
+ padding: 32rpx;
100
+ }
101
+
102
+ .title {
103
+ font-size: var(--cadence-font-size-title);
104
+ font-weight: var(--cadence-font-weight-emphasis);
105
+ }
106
+ `;
107
+ const COUNTER_CARD_LOGIC = `import { computed } from '@cadence/core';
108
+
109
+ export const props = ['label', 'step'];
110
+
111
+ export default function CounterCard(
112
+ props: Record<string, () => unknown>,
113
+ ): Record<string, unknown> {
114
+ const badge = computed(() => \`+\${String(props['step']?.() ?? 0)}\`);
115
+
116
+ return { badge };
117
+ }
118
+ `;
119
+ const COUNTER_CARD_TEMPLATE = `<view class="card">
120
+ <text class="label">{{ label() }}</text>
121
+ <text class="badge">{{ badge() }}</text>
122
+ </view>
123
+ `;
124
+ const COUNTER_CARD_STYLE = `.card {
125
+ display: flex;
126
+ align-items: center;
127
+ justify-content: space-between;
128
+ gap: var(--cadence-spacing-md);
129
+ padding: var(--cadence-spacing-md);
130
+ background: var(--cadence-surface-raised);
131
+ border-radius: var(--cadence-radius-md);
132
+ }
133
+
134
+ .label {
135
+ color: var(--cadence-text-primary);
136
+ }
137
+
138
+ .badge {
139
+ color: var(--cadence-accent-background);
140
+ font-weight: var(--cadence-font-weight-emphasis);
141
+ }
142
+ `;
143
+ export const PROJECT_TEMPLATES = {
144
+ page: {
145
+ description: 'une page, un signal, une liaison — le strict nécessaire',
146
+ manifestFor: (name) => ({
147
+ name,
148
+ version: '0.1.0',
149
+ entry: 'pages/home',
150
+ language: 'fr',
151
+ pages: [{ path: 'pages/home', title: 'Accueil' }],
152
+ }),
153
+ sources: {
154
+ 'pages/home/template.html': HOME_TEMPLATE,
155
+ 'pages/home/logic.ts': HOME_LOGIC,
156
+ 'pages/home/style.scss': HOME_STYLE,
157
+ },
158
+ },
159
+ onglets: {
160
+ description: 'deux pages sous une tab bar',
161
+ manifestFor: (name) => ({
162
+ name,
163
+ version: '0.1.0',
164
+ entry: 'pages/home',
165
+ language: 'fr',
166
+ pages: [
167
+ { path: 'pages/home', title: 'Accueil' },
168
+ { path: 'pages/profile', title: 'Profil' },
169
+ ],
170
+ tabBar: {
171
+ items: [
172
+ { path: 'pages/home', title: 'Accueil', icon: 'home' },
173
+ { path: 'pages/profile', title: 'Profil', icon: 'user' },
174
+ ],
175
+ },
176
+ }),
177
+ sources: {
178
+ 'pages/home/template.html': HOME_TEMPLATE,
179
+ 'pages/home/logic.ts': HOME_LOGIC,
180
+ 'pages/home/style.scss': HOME_STYLE,
181
+ 'pages/profile/template.html': PROFILE_TEMPLATE,
182
+ 'pages/profile/logic.ts': PROFILE_LOGIC,
183
+ 'pages/profile/style.scss': PROFILE_STYLE,
184
+ },
185
+ },
186
+ composant: {
187
+ description: 'une page et un composant à soi, avec props et événement',
188
+ manifestFor: (name) => ({
189
+ name,
190
+ version: '0.1.0',
191
+ entry: 'pages/home',
192
+ language: 'fr',
193
+ pages: [{ path: 'pages/home', title: 'Accueil' }],
194
+ }),
195
+ sources: {
196
+ 'pages/home/template.html': COUNTER_PAGE_TEMPLATE,
197
+ 'pages/home/logic.ts': COUNTER_PAGE_LOGIC,
198
+ 'pages/home/style.scss': COUNTER_PAGE_STYLE,
199
+ 'components/counter-card/template.html': COUNTER_CARD_TEMPLATE,
200
+ 'components/counter-card/logic.ts': COUNTER_CARD_LOGIC,
201
+ 'components/counter-card/style.scss': COUNTER_CARD_STYLE,
202
+ },
203
+ },
204
+ };
205
+ export const PROJECT_TEMPLATE_NAMES = Object.keys(PROJECT_TEMPLATES);
206
+ export function isProjectTemplateName(value) {
207
+ return Object.hasOwn(PROJECT_TEMPLATES, value);
208
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cadence-app/compiler",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Compilation des templates en instructions, SCSS scopé, bundling",
5
5
  "keywords": [
6
6
  "compiler",