@cadence-app/compiler 0.1.0 → 0.3.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,31 @@ 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. Il pose aussi un `package.json` et un `tsconfig.json`, sans lesquels un éditeur
35
+ souligne en rouge des imports que le build résout très bien — reste à lancer `npm install`.
36
+
22
37
  `build` rend un dossier `dist` : `engine.js`, `app.js`, la feuille de thème, les pages, les icônes
23
38
  et une archive prête à distribuer. Le budget du moteur — 30 ko gzip — est vérifié à chaque
24
39
  construction, et un dépassement fait échouer la commande.
@@ -26,7 +41,7 @@ construction, et un dépassement fait échouer la commande.
26
41
  `dev` sert le mini-programme dans un navigateur, avec un hôte simulé : le geste retour tient à la
27
42
  touche Échap, et masquer l'onglet annonce l'arrière-plan.
28
43
 
29
- Deux commandes complètent l'ensemble : `mini publish`, `mini whoami` et `mini logout`, pour une
44
+ Trois commandes complètent l'ensemble : `mini publish`, `mini whoami` et `mini logout`, pour une
30
45
  distribution par backend.
31
46
 
32
47
  ## 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,17 @@ 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 :');
153
+ console.log(` cd ${requestedDir} && npm install`);
154
+ console.log(' npx mini dev .');
155
+ }
126
156
  function printPublishReport(report) {
127
157
  const sizeKo = (report.archiveBytes / 1024).toFixed(1);
128
158
  console.log(`publié « ${report.slug} » v${report.published.versionString} → ${report.remoteUrl}`);
package/dist/index.d.ts CHANGED
@@ -12,6 +12,11 @@ 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 { projectToolingFiles } from './project-tooling.js';
17
+ export type { InitOptions, InitReport } from './init-project.js';
18
+ export { PROJECT_TEMPLATES, PROJECT_TEMPLATE_NAMES, isProjectTemplateName, } from './project-templates.js';
19
+ export type { ProjectTemplate, ProjectTemplateName } from './project-templates.js';
15
20
  export { startDevServer } from './dev-server.js';
16
21
  export type { DevServer, DevServerOptions } from './dev-server.js';
17
22
  export { credentialsPath, readCredentials, writeCredentials, clearCredentials, normalizeRemoteUrl, } from './publish/credentials.js';
package/dist/index.js CHANGED
@@ -7,6 +7,9 @@ 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 { projectToolingFiles } from "./project-tooling.js";
12
+ export { PROJECT_TEMPLATES, PROJECT_TEMPLATE_NAMES, isProjectTemplateName, } from "./project-templates.js";
10
13
  export { startDevServer } from "./dev-server.js";
11
14
  export { credentialsPath, readCredentials, writeCredentials, clearCredentials, normalizeRemoteUrl, } from "./publish/credentials.js";
12
15
  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,57 @@
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
+ import { projectToolingFiles } from "./project-tooling.js";
5
+ export class InitError extends Error {
6
+ constructor(reason) {
7
+ super(reason);
8
+ this.name = 'InitError';
9
+ }
10
+ }
11
+ const MANIFEST_FILE = 'manifest.json';
12
+ export async function initProject(options) {
13
+ const template = resolveTemplate(options.template);
14
+ const targetDir = path.resolve(options.targetDir);
15
+ const name = options.name ?? path.basename(targetDir);
16
+ if (name === '') {
17
+ throw new InitError('le nom du mini-programme ne peut pas être vide');
18
+ }
19
+ await requireEmptyDirectory(targetDir);
20
+ const manifest = PROJECT_TEMPLATES[template].manifestFor(name);
21
+ const contents = {
22
+ [MANIFEST_FILE]: `${JSON.stringify(manifest, null, 2)}\n`,
23
+ ...(await projectToolingFiles(name)),
24
+ ...PROJECT_TEMPLATES[template].sources,
25
+ };
26
+ const files = Object.keys(contents).sort();
27
+ for (const file of files) {
28
+ const destination = path.join(targetDir, file);
29
+ await mkdir(path.dirname(destination), { recursive: true });
30
+ await writeFile(destination, contents[file] ?? '', 'utf8');
31
+ }
32
+ return { targetDir, name, template, files };
33
+ }
34
+ function resolveTemplate(requested) {
35
+ if (requested === undefined) {
36
+ return 'page';
37
+ }
38
+ if (!isProjectTemplateName(requested)) {
39
+ throw new InitError(`template inconnu : « ${requested} » — au choix ${PROJECT_TEMPLATE_NAMES.join(', ')}`);
40
+ }
41
+ return requested;
42
+ }
43
+ /* Écraser le travail de quelqu'un coûte plus cher que de refuser : on ne crée
44
+ que dans un dossier absent ou vide, et le message dit quoi faire. */
45
+ async function requireEmptyDirectory(targetDir) {
46
+ let entries;
47
+ try {
48
+ entries = await readdir(targetDir);
49
+ }
50
+ catch {
51
+ await mkdir(targetDir, { recursive: true });
52
+ return;
53
+ }
54
+ if (entries.length > 0) {
55
+ throw new InitError(`${targetDir} n'est pas vide — choisissez un autre dossier, ou videz celui-ci`);
56
+ }
57
+ }
@@ -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
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Les deux fichiers qui font comprendre le projet à un éditeur : `@cadence/core`
3
+ * n'existe pas sur npm, donc TypeScript ne le résout qu'avec un `paths` vers le
4
+ * paquet publié.
5
+ */
6
+ export declare function projectToolingFiles(name: string): Promise<Readonly<Record<string, string>>>;
@@ -0,0 +1,54 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ /** Les quatre noms que le shim du compilateur fournit à un mini-programme (ADR-031). */
5
+ const VIRTUAL_MODULES = ['core', 'runtime', 'bridge', 'router'];
6
+ /* `src` dans le dépôt, `dist` une fois publié : le manifeste du compilateur est
7
+ à la même hauteur dans les deux, un cran au-dessus de ce module. */
8
+ const OWN_MANIFEST = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
9
+ const TSCONFIG = {
10
+ compilerOptions: {
11
+ target: 'ES2022',
12
+ lib: ['ES2022', 'DOM'],
13
+ module: 'ESNext',
14
+ moduleResolution: 'bundler',
15
+ strict: true,
16
+ noEmit: true,
17
+ types: [],
18
+ paths: Object.fromEntries(VIRTUAL_MODULES.map((module) => [
19
+ `@cadence/${module}`,
20
+ [`./node_modules/@cadence-app/${module}`],
21
+ ])),
22
+ },
23
+ include: ['pages/**/*.ts', 'components/**/*.ts', 'app.ts'],
24
+ };
25
+ /**
26
+ * Les deux fichiers qui font comprendre le projet à un éditeur : `@cadence/core`
27
+ * n'existe pas sur npm, donc TypeScript ne le résout qu'avec un `paths` vers le
28
+ * paquet publié.
29
+ */
30
+ export async function projectToolingFiles(name) {
31
+ const own = JSON.parse(await readFile(OWN_MANIFEST, 'utf8'));
32
+ return {
33
+ 'package.json': `${JSON.stringify(packageJsonFor(name, own), null, 2)}\n`,
34
+ 'tsconfig.json': `${JSON.stringify(TSCONFIG, null, 2)}\n`,
35
+ };
36
+ }
37
+ /*
38
+ * Les quatre paquets du moteur sont déclarés un par un, et non laissés en
39
+ * dépendances transitives du compilateur : pnpm ne les remonterait pas à la
40
+ * racine de `node_modules`, où `paths` va les chercher.
41
+ */
42
+ function packageJsonFor(name, own) {
43
+ const devDependencies = { [own.name]: `^${own.version}` };
44
+ for (const module of VIRTUAL_MODULES) {
45
+ const dependency = `@cadence-app/${module}`;
46
+ devDependencies[dependency] = rangeFor(own.dependencies?.[dependency]);
47
+ }
48
+ return { name, private: true, type: 'module', devDependencies };
49
+ }
50
+ /* Le dépôt déclare ses paquets en `workspace:*`, que pnpm remplace par une
51
+ version à la publication. Lancé depuis un clone, `init` n'a donc rien à citer. */
52
+ function rangeFor(declared) {
53
+ return declared === undefined || declared.startsWith('workspace:') ? '*' : `^${declared}`;
54
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cadence-app/compiler",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Compilation des templates en instructions, SCSS scopé, bundling",
5
5
  "keywords": [
6
6
  "compiler",