@cadence-app/compiler 0.1.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/LICENSE +21 -0
- package/README.md +54 -0
- package/dist/build.d.ts +31 -0
- package/dist/build.js +437 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +180 -0
- package/dist/dev-server.d.ts +16 -0
- package/dist/dev-server.js +81 -0
- package/dist/engine-budget.d.ts +9 -0
- package/dist/engine-budget.js +8 -0
- package/dist/hash.d.ts +2 -0
- package/dist/hash.js +12 -0
- package/dist/host/browser-mock-host.d.ts +1 -0
- package/dist/host/browser-mock-host.js +175 -0
- package/dist/host/dev-client.d.ts +1 -0
- package/dist/host/dev-client.js +6 -0
- package/dist/host/engine-entry.d.ts +1 -0
- package/dist/host/engine-entry.js +199 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +14 -0
- package/dist/manifest.d.ts +47 -0
- package/dist/manifest.js +202 -0
- package/dist/publish/credentials.d.ts +17 -0
- package/dist/publish/credentials.js +87 -0
- package/dist/publish/distribution-client.d.ts +45 -0
- package/dist/publish/distribution-client.js +113 -0
- package/dist/publish/publish-bundle.d.ts +27 -0
- package/dist/publish/publish-bundle.js +44 -0
- package/dist/publish/publish-errors.d.ts +41 -0
- package/dist/publish/publish-errors.js +60 -0
- package/dist/publish/read-secret.d.ts +7 -0
- package/dist/publish/read-secret.js +30 -0
- package/dist/style/compile-style.d.ts +13 -0
- package/dist/style/compile-style.js +135 -0
- package/dist/style/theme-sheet.d.ts +6 -0
- package/dist/style/theme-sheet.js +8 -0
- package/dist/template/ast.d.ts +47 -0
- package/dist/template/ast.js +1 -0
- package/dist/template/codegen.d.ts +8 -0
- package/dist/template/codegen.js +220 -0
- package/dist/template/entities.d.ts +12 -0
- package/dist/template/entities.js +103 -0
- package/dist/template/expression.d.ts +16 -0
- package/dist/template/expression.js +196 -0
- package/dist/template/parser.d.ts +10 -0
- package/dist/template/parser.js +437 -0
- package/package.json +62 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dickode78
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# @cadence-app/compiler
|
|
2
|
+
|
|
3
|
+
La chaîne de construction de [Cadence](https://github.com/issadicko/cadence) : templates compilés
|
|
4
|
+
en instructions, SCSS scopé par composant, manifeste validé, bundling par esbuild, serveur de
|
|
5
|
+
développement et publication d'un bundle.
|
|
6
|
+
|
|
7
|
+
Ce paquet ne tourne jamais dans une WebView. Il travaille une fois, avant la livraison.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pnpm add -D @cadence-app/compiler
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## La commande
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
mini build mon-mini-programme --minify
|
|
19
|
+
mini dev mon-mini-programme
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`build` rend un dossier `dist` : `engine.js`, `app.js`, la feuille de thème, les pages, les icônes
|
|
23
|
+
et une archive prête à distribuer. Le budget du moteur — 30 ko gzip — est vérifié à chaque
|
|
24
|
+
construction, et un dépassement fait échouer la commande.
|
|
25
|
+
|
|
26
|
+
`dev` sert le mini-programme dans un navigateur, avec un hôte simulé : le geste retour tient à la
|
|
27
|
+
touche Échap, et masquer l'onglet annonce l'arrière-plan.
|
|
28
|
+
|
|
29
|
+
Deux commandes complètent l'ensemble : `mini publish`, `mini whoami` et `mini logout`, pour une
|
|
30
|
+
distribution par backend.
|
|
31
|
+
|
|
32
|
+
## La bibliothèque
|
|
33
|
+
|
|
34
|
+
Le paquet s'importe aussi, pour outiller un éditeur ou un site :
|
|
35
|
+
|
|
36
|
+
| Export | Rôle |
|
|
37
|
+
|---|---|
|
|
38
|
+
| `parseTemplate`, `generateRenderFunction` | template vers instructions de rendu |
|
|
39
|
+
| `rewriteExpression` | réécriture d'une expression de template |
|
|
40
|
+
| `compileStyle`, `buildThemeSheet` | SCSS scopé, et feuille des tokens |
|
|
41
|
+
| `parseManifest`, `allManifestPages` | lecture et validation d'un manifeste |
|
|
42
|
+
| `buildMiniApp`, `startDevServer`, `publishMiniApp` | les trois commandes, en API |
|
|
43
|
+
|
|
44
|
+
Le sous-chemin `@cadence-app/compiler/template` expose le parseur seul, sans tirer esbuild ni sass.
|
|
45
|
+
|
|
46
|
+
## Les imports d'un mini-programme
|
|
47
|
+
|
|
48
|
+
Dans le code d'un mini-programme, `@cadence/core`, `@cadence/runtime`, `@cadence/bridge` et
|
|
49
|
+
`@cadence/router` sont un espace virtuel : le compilateur les remplace par des lectures du moteur
|
|
50
|
+
déjà présent dans la WebView. Rien à installer pour eux (ADR-031).
|
|
51
|
+
|
|
52
|
+
## Licence
|
|
53
|
+
|
|
54
|
+
MIT
|
package/dist/build.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { MiniAppManifest } from './manifest.js';
|
|
2
|
+
export declare class BuildError extends Error {
|
|
3
|
+
constructor(message: string);
|
|
4
|
+
}
|
|
5
|
+
export interface BuildOptions {
|
|
6
|
+
readonly miniappDir: string;
|
|
7
|
+
readonly outDir?: string;
|
|
8
|
+
readonly minify?: boolean;
|
|
9
|
+
readonly zip?: boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface SizeReport {
|
|
12
|
+
readonly raw: number;
|
|
13
|
+
readonly gzip: number;
|
|
14
|
+
}
|
|
15
|
+
export interface BuildSummary {
|
|
16
|
+
readonly outDir: string;
|
|
17
|
+
readonly manifest: MiniAppManifest;
|
|
18
|
+
readonly pageRoutes: readonly string[];
|
|
19
|
+
readonly componentTags: readonly string[];
|
|
20
|
+
readonly subPackageFiles: readonly string[];
|
|
21
|
+
readonly minified: boolean;
|
|
22
|
+
readonly engine: SizeReport;
|
|
23
|
+
readonly app: SizeReport;
|
|
24
|
+
readonly zipFile: string | null;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Pipeline complet : manifest → compilation template+SCSS de chaque unité →
|
|
28
|
+
* bundle esbuild (app + sous-packages, imports `@cadence/*` shimés vers le
|
|
29
|
+
* global Cadence) → bundle du moteur → HTML → zip versionné.
|
|
30
|
+
*/
|
|
31
|
+
export declare function buildMiniApp(options: BuildOptions): Promise<BuildSummary>;
|
package/dist/build.js
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
import { BUILTIN_ICONS } from '@cadence-app/runtime';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { gzipSync } from 'node:zlib';
|
|
7
|
+
import * as esbuild from 'esbuild';
|
|
8
|
+
import JSZip from 'jszip';
|
|
9
|
+
import { generateRenderFunction } from "./template/codegen.js";
|
|
10
|
+
import { parseTemplate } from "./template/parser.js";
|
|
11
|
+
import { compileStyle } from "./style/compile-style.js";
|
|
12
|
+
import { buildThemeSheet } from "./style/theme-sheet.js";
|
|
13
|
+
import { parseManifest } from "./manifest.js";
|
|
14
|
+
import { stableHash } from "./hash.js";
|
|
15
|
+
export class BuildError extends Error {
|
|
16
|
+
constructor(message) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'BuildError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const HOST_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), 'host');
|
|
22
|
+
/* Le dépôt exécute les sources des hôtes, le paquet publié leur compilation. L'entrée
|
|
23
|
+
change donc d'extension selon l'endroit d'où le compilateur tourne. */
|
|
24
|
+
const HOST_EXTENSION = existsSync(path.join(HOST_DIR, 'engine-entry.ts')) ? '.ts' : '.js';
|
|
25
|
+
const ENGINE_TARGET = 'es2020';
|
|
26
|
+
const DEV_SHELL_FILE = 'dev.html';
|
|
27
|
+
const DEV_HOST_ENTRY = 'dev-host';
|
|
28
|
+
const DEV_CLIENT_ENTRY = 'dev-client';
|
|
29
|
+
/**
|
|
30
|
+
* L'échafaudage que `mini dev` sert dans le navigateur. Il reste dans `outDir`,
|
|
31
|
+
* mais l'archive part sur le serveur de distribution et jusque sur les
|
|
32
|
+
* appareils : elle n'embarque que ce que le conteneur exécute.
|
|
33
|
+
*/
|
|
34
|
+
const DEV_SCAFFOLD_FILES = new Set([
|
|
35
|
+
DEV_SHELL_FILE,
|
|
36
|
+
`${DEV_HOST_ENTRY}.js`,
|
|
37
|
+
`${DEV_CLIENT_ENTRY}.js`,
|
|
38
|
+
]);
|
|
39
|
+
/**
|
|
40
|
+
* Pipeline complet : manifest → compilation template+SCSS de chaque unité →
|
|
41
|
+
* bundle esbuild (app + sous-packages, imports `@cadence/*` shimés vers le
|
|
42
|
+
* global Cadence) → bundle du moteur → HTML → zip versionné.
|
|
43
|
+
*/
|
|
44
|
+
export async function buildMiniApp(options) {
|
|
45
|
+
const miniappDir = path.resolve(options.miniappDir);
|
|
46
|
+
const outDir = path.resolve(options.outDir ?? path.join(miniappDir, 'dist'));
|
|
47
|
+
const minified = options.minify ?? false;
|
|
48
|
+
const manifest = await readManifest(miniappDir);
|
|
49
|
+
const virtualModules = new Map();
|
|
50
|
+
const componentTags = await compileComponents(miniappDir, virtualModules);
|
|
51
|
+
const pageRoutes = await compilePages(miniappDir, manifest.pages, virtualModules);
|
|
52
|
+
const subEntryNames = [];
|
|
53
|
+
for (const subPackage of manifest.subPackages ?? []) {
|
|
54
|
+
await compilePages(miniappDir, subPackage.pages, virtualModules);
|
|
55
|
+
virtualModules.set(`cadence-entry:${subPackage.root}`, {
|
|
56
|
+
contents: generateSubPackageEntry(subPackage.pages),
|
|
57
|
+
resolveDir: miniappDir,
|
|
58
|
+
});
|
|
59
|
+
subEntryNames.push(subPackage.root);
|
|
60
|
+
}
|
|
61
|
+
const appIcons = await readAppIcons(miniappDir);
|
|
62
|
+
assertTabBarIconsExist(manifest, appIcons);
|
|
63
|
+
virtualModules.set('cadence-entry:main', {
|
|
64
|
+
contents: generateMainEntry(manifest, componentTags, appIcons, hasAppLogic(miniappDir)),
|
|
65
|
+
resolveDir: miniappDir,
|
|
66
|
+
});
|
|
67
|
+
await rm(outDir, { recursive: true, force: true });
|
|
68
|
+
await mkdir(outDir, { recursive: true });
|
|
69
|
+
await bundleApp(outDir, virtualModules, subEntryNames, minified);
|
|
70
|
+
await bundleHostScripts(outDir, minified);
|
|
71
|
+
await writeHtmlShells(outDir, manifest.language ?? DEFAULT_DOCUMENT_LANGUAGE);
|
|
72
|
+
await writeFile(path.join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
|
|
73
|
+
const engine = await measure(path.join(outDir, 'engine.js'));
|
|
74
|
+
const app = await measure(path.join(outDir, 'app.js'));
|
|
75
|
+
const zipFile = (options.zip ?? true) ? await writeBundleArchive(outDir, manifest) : null;
|
|
76
|
+
return {
|
|
77
|
+
outDir,
|
|
78
|
+
manifest,
|
|
79
|
+
pageRoutes,
|
|
80
|
+
componentTags,
|
|
81
|
+
subPackageFiles: subEntryNames.map((name) => `subpackages/${name}.js`),
|
|
82
|
+
minified,
|
|
83
|
+
engine,
|
|
84
|
+
app,
|
|
85
|
+
zipFile,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
async function readManifest(miniappDir) {
|
|
89
|
+
const manifestPath = path.join(miniappDir, 'manifest.json');
|
|
90
|
+
if (!existsSync(manifestPath)) {
|
|
91
|
+
throw new BuildError(`manifest.json not found in ${miniappDir}`);
|
|
92
|
+
}
|
|
93
|
+
return parseManifest(await readFile(manifestPath, 'utf8'));
|
|
94
|
+
}
|
|
95
|
+
async function compilePages(miniappDir, pages, virtualModules) {
|
|
96
|
+
const routes = [];
|
|
97
|
+
for (const page of pages) {
|
|
98
|
+
const pageDir = path.join(miniappDir, page.path);
|
|
99
|
+
virtualModules.set(`cadence-unit:${page.path}`, {
|
|
100
|
+
contents: await compileUnitModule(pageDir, page.path, null),
|
|
101
|
+
resolveDir: pageDir,
|
|
102
|
+
});
|
|
103
|
+
routes.push(page.path);
|
|
104
|
+
}
|
|
105
|
+
return routes;
|
|
106
|
+
}
|
|
107
|
+
async function compileComponents(miniappDir, virtualModules) {
|
|
108
|
+
const componentsDir = path.join(miniappDir, 'components');
|
|
109
|
+
if (!existsSync(componentsDir)) {
|
|
110
|
+
return [];
|
|
111
|
+
}
|
|
112
|
+
const tags = [];
|
|
113
|
+
const entries = await readdir(componentsDir, { withFileTypes: true });
|
|
114
|
+
for (const entry of entries.filter((candidate) => candidate.isDirectory())) {
|
|
115
|
+
const tag = entry.name;
|
|
116
|
+
const componentDir = path.join(componentsDir, tag);
|
|
117
|
+
virtualModules.set(`cadence-unit:components/${tag}`, {
|
|
118
|
+
contents: await compileUnitModule(componentDir, `components/${tag}`, tag),
|
|
119
|
+
resolveDir: componentDir,
|
|
120
|
+
});
|
|
121
|
+
tags.push(tag);
|
|
122
|
+
}
|
|
123
|
+
return tags;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Jeu d'icônes propre au mini-programme : un fichier `.svg` par icône dans
|
|
127
|
+
* `icons/`, nommé comme l'attribut `name` qui le désignera.
|
|
128
|
+
*/
|
|
129
|
+
async function readAppIcons(miniappDir) {
|
|
130
|
+
const iconsDir = path.join(miniappDir, 'icons');
|
|
131
|
+
if (!existsSync(iconsDir)) {
|
|
132
|
+
return {};
|
|
133
|
+
}
|
|
134
|
+
const icons = {};
|
|
135
|
+
const entries = await readdir(iconsDir, { withFileTypes: true });
|
|
136
|
+
for (const entry of entries.filter((candidate) => candidate.name.endsWith('.svg'))) {
|
|
137
|
+
const source = (await readFile(path.join(iconsDir, entry.name), 'utf8')).trim();
|
|
138
|
+
if (!source.startsWith('<svg')) {
|
|
139
|
+
throw new BuildError(`icons/${entry.name} does not start with an <svg> element`);
|
|
140
|
+
}
|
|
141
|
+
icons[entry.name.slice(0, -'.svg'.length)] = source;
|
|
142
|
+
}
|
|
143
|
+
return icons;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Un nom d'icône introuvable rendrait une pastille vide, sans erreur : le build
|
|
147
|
+
* est le seul endroit qui connaisse à la fois le jeu embarqué et celui du
|
|
148
|
+
* mini-programme, donc le seul qui puisse le dire.
|
|
149
|
+
*/
|
|
150
|
+
function assertTabBarIconsExist(manifest, appIcons) {
|
|
151
|
+
const available = new Set([...Object.keys(BUILTIN_ICONS), ...Object.keys(appIcons)]);
|
|
152
|
+
for (const item of manifest.tabBar?.items ?? []) {
|
|
153
|
+
for (const name of [item.icon, item.activeIcon]) {
|
|
154
|
+
if (name !== undefined && !available.has(name)) {
|
|
155
|
+
throw new BuildError(`tab bar icon '${name}' is neither part of the built-in set nor a file in icons/`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Module virtuel d'une unité (page ou composant) : template compilé en
|
|
162
|
+
* fonction de rendu, SCSS compilé embarqué, logique importée depuis le disque.
|
|
163
|
+
*/
|
|
164
|
+
async function compileUnitModule(unitDir, unitKey, componentTag) {
|
|
165
|
+
const templatePath = path.join(unitDir, 'template.html');
|
|
166
|
+
if (!existsSync(templatePath)) {
|
|
167
|
+
throw new BuildError(`template.html not found for '${unitKey}' (${unitDir})`);
|
|
168
|
+
}
|
|
169
|
+
let renderSource;
|
|
170
|
+
try {
|
|
171
|
+
renderSource = generateRenderFunction(parseTemplate(await readFile(templatePath, 'utf8')));
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
throw new BuildError(`failed to compile template of '${unitKey}': ${error instanceof Error ? error.message : String(error)}`);
|
|
175
|
+
}
|
|
176
|
+
const styleId = stableHash(unitKey);
|
|
177
|
+
const stylePath = path.join(unitDir, 'style.scss');
|
|
178
|
+
const css = existsSync(stylePath)
|
|
179
|
+
? await compileStyle(await readFile(stylePath, 'utf8'), styleId, {
|
|
180
|
+
unitName: unitKey,
|
|
181
|
+
loadPaths: [unitDir],
|
|
182
|
+
})
|
|
183
|
+
: null;
|
|
184
|
+
const hasLogic = existsSync(path.join(unitDir, 'logic.ts'));
|
|
185
|
+
const lines = [];
|
|
186
|
+
if (hasLogic) {
|
|
187
|
+
lines.push(`import * as logicModule from './logic.ts';`);
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
lines.push('const logicModule = {};');
|
|
191
|
+
}
|
|
192
|
+
lines.push('export const definition = {');
|
|
193
|
+
if (componentTag !== null) {
|
|
194
|
+
lines.push(` tag: ${JSON.stringify(componentTag)},`);
|
|
195
|
+
lines.push(' props: logicModule.props ?? [],');
|
|
196
|
+
}
|
|
197
|
+
lines.push(' setup: logicModule.default ?? (() => ({})),');
|
|
198
|
+
lines.push(` render: ${indentBlock(renderSource, ' ')},`);
|
|
199
|
+
lines.push(` styleId: ${JSON.stringify(styleId)},`);
|
|
200
|
+
if (css !== null) {
|
|
201
|
+
lines.push(` css: ${JSON.stringify(css)},`);
|
|
202
|
+
}
|
|
203
|
+
lines.push('};');
|
|
204
|
+
return lines.join('\n');
|
|
205
|
+
}
|
|
206
|
+
/** Facultatif à la racine : le setup de l'application, passé au démarrage. */
|
|
207
|
+
const APP_LOGIC_FILE = 'app.ts';
|
|
208
|
+
function hasAppLogic(miniappDir) {
|
|
209
|
+
return existsSync(path.join(miniappDir, APP_LOGIC_FILE));
|
|
210
|
+
}
|
|
211
|
+
function generateMainEntry(manifest, componentTags, icons, hasApp) {
|
|
212
|
+
const lines = [];
|
|
213
|
+
if (hasApp) {
|
|
214
|
+
lines.push(`import App from ${JSON.stringify(`./${APP_LOGIC_FILE}`)};`);
|
|
215
|
+
}
|
|
216
|
+
componentTags.forEach((tag, index) => {
|
|
217
|
+
lines.push(`import { definition as component${index} } from ${JSON.stringify(`cadence-unit:components/${tag}`)};`);
|
|
218
|
+
});
|
|
219
|
+
manifest.pages.forEach((page, index) => {
|
|
220
|
+
lines.push(`import { definition as page${index} } from ${JSON.stringify(`cadence-unit:${page.path}`)};`);
|
|
221
|
+
});
|
|
222
|
+
lines.push('const Cadence = globalThis.Cadence;');
|
|
223
|
+
lines.push(`Cadence.registerTheme(${JSON.stringify(buildThemeSheet(manifest.theme))});`);
|
|
224
|
+
if (Object.keys(icons).length > 0) {
|
|
225
|
+
lines.push(`Cadence.registerIcons(${JSON.stringify(icons)});`);
|
|
226
|
+
}
|
|
227
|
+
componentTags.forEach((_tag, index) => {
|
|
228
|
+
lines.push(`Cadence.registerComponent(component${index});`);
|
|
229
|
+
});
|
|
230
|
+
manifest.pages.forEach((page, index) => {
|
|
231
|
+
lines.push(`Cadence.registerPage(${JSON.stringify(page.path)}, page${index});`);
|
|
232
|
+
});
|
|
233
|
+
const app = hasApp ? ', { setup: App }' : '';
|
|
234
|
+
lines.push(`Cadence.bootstrap(${JSON.stringify(manifest)}${app})`);
|
|
235
|
+
lines.push(" .catch((error) => console.error('[cadence] bootstrap failed', error));");
|
|
236
|
+
return lines.join('\n');
|
|
237
|
+
}
|
|
238
|
+
function generateSubPackageEntry(pages) {
|
|
239
|
+
const lines = [];
|
|
240
|
+
pages.forEach((page, index) => {
|
|
241
|
+
lines.push(`import { definition as page${index} } from ${JSON.stringify(`cadence-unit:${page.path}`)};`);
|
|
242
|
+
});
|
|
243
|
+
lines.push('const Cadence = globalThis.Cadence;');
|
|
244
|
+
pages.forEach((page, index) => {
|
|
245
|
+
lines.push(`Cadence.registerPage(${JSON.stringify(page.path)}, page${index});`);
|
|
246
|
+
});
|
|
247
|
+
return lines.join('\n');
|
|
248
|
+
}
|
|
249
|
+
async function bundleApp(outDir, virtualModules, subEntryNames, minify) {
|
|
250
|
+
const entryPoints = { app: 'cadence-entry:main' };
|
|
251
|
+
for (const name of subEntryNames) {
|
|
252
|
+
entryPoints[`subpackages/${name}`] = `cadence-entry:${name}`;
|
|
253
|
+
}
|
|
254
|
+
await runEsbuild({
|
|
255
|
+
entryPoints,
|
|
256
|
+
outdir: outDir,
|
|
257
|
+
entryNames: '[dir]/[name]',
|
|
258
|
+
minify,
|
|
259
|
+
plugins: [virtualModulesPlugin(virtualModules), cadenceShimPlugin()],
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
async function bundleHostScripts(outDir, minify) {
|
|
263
|
+
await runEsbuild({
|
|
264
|
+
entryPoints: {
|
|
265
|
+
engine: path.join(HOST_DIR, `engine-entry${HOST_EXTENSION}`),
|
|
266
|
+
[DEV_HOST_ENTRY]: path.join(HOST_DIR, `browser-mock-host${HOST_EXTENSION}`),
|
|
267
|
+
[DEV_CLIENT_ENTRY]: path.join(HOST_DIR, `dev-client${HOST_EXTENSION}`),
|
|
268
|
+
},
|
|
269
|
+
outdir: outDir,
|
|
270
|
+
entryNames: '[name]',
|
|
271
|
+
minify,
|
|
272
|
+
plugins: [],
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
async function runEsbuild(run) {
|
|
276
|
+
try {
|
|
277
|
+
await esbuild.build({
|
|
278
|
+
entryPoints: run.entryPoints,
|
|
279
|
+
outdir: run.outdir,
|
|
280
|
+
entryNames: run.entryNames,
|
|
281
|
+
bundle: true,
|
|
282
|
+
format: 'iife',
|
|
283
|
+
platform: 'browser',
|
|
284
|
+
target: ENGINE_TARGET,
|
|
285
|
+
minify: run.minify,
|
|
286
|
+
plugins: run.plugins,
|
|
287
|
+
logLevel: 'silent',
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
catch (error) {
|
|
291
|
+
throw new BuildError(formatEsbuildError(error));
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
function formatEsbuildError(error) {
|
|
295
|
+
if (error !== null && typeof error === 'object' && 'errors' in error) {
|
|
296
|
+
const messages = error.errors
|
|
297
|
+
.map((entry) => entry.text)
|
|
298
|
+
.join('; ');
|
|
299
|
+
if (messages.length > 0) {
|
|
300
|
+
return `bundling failed: ${messages}`;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return `bundling failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
304
|
+
}
|
|
305
|
+
function virtualModulesPlugin(modules) {
|
|
306
|
+
return {
|
|
307
|
+
name: 'cadence-virtual-modules',
|
|
308
|
+
setup(build) {
|
|
309
|
+
build.onResolve({ filter: /^cadence-(unit|entry):/ }, (args) => ({
|
|
310
|
+
path: args.path,
|
|
311
|
+
namespace: 'cadence-virtual',
|
|
312
|
+
}));
|
|
313
|
+
build.onLoad({ filter: /.*/, namespace: 'cadence-virtual' }, (args) => {
|
|
314
|
+
const module = modules.get(args.path);
|
|
315
|
+
if (module === undefined) {
|
|
316
|
+
return { errors: [{ text: `unknown virtual module '${args.path}'` }] };
|
|
317
|
+
}
|
|
318
|
+
return { contents: module.contents, loader: 'ts', resolveDir: module.resolveDir };
|
|
319
|
+
});
|
|
320
|
+
},
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Le bundle applicatif n'embarque jamais le moteur : les imports `@cadence/*`
|
|
325
|
+
* du code applicatif sont réécrits vers les modules exposés par `engine.js`
|
|
326
|
+
* sur le global Cadence (une seule instance du graphe réactif par WebView).
|
|
327
|
+
*/
|
|
328
|
+
const SHIM_EXPORTS = {
|
|
329
|
+
core: [
|
|
330
|
+
'signal',
|
|
331
|
+
'computed',
|
|
332
|
+
'effect',
|
|
333
|
+
'EffectScope',
|
|
334
|
+
'getCurrentScope',
|
|
335
|
+
'untracked',
|
|
336
|
+
'flushEffects',
|
|
337
|
+
'FlushOverflowError',
|
|
338
|
+
'ScopeDisposedError',
|
|
339
|
+
],
|
|
340
|
+
runtime: ['onAttached', 'onDetached'],
|
|
341
|
+
bridge: ['native', 'BridgeMethods', 'BridgeEvents', 'BridgeTimeoutError', 'BridgeInvokeError'],
|
|
342
|
+
router: [
|
|
343
|
+
'onLoad',
|
|
344
|
+
'onShow',
|
|
345
|
+
'onReady',
|
|
346
|
+
'onHide',
|
|
347
|
+
'onUnload',
|
|
348
|
+
'onLaunch',
|
|
349
|
+
'onError',
|
|
350
|
+
'navigateTo',
|
|
351
|
+
'redirectTo',
|
|
352
|
+
'navigateBack',
|
|
353
|
+
'reLaunch',
|
|
354
|
+
'switchTab',
|
|
355
|
+
],
|
|
356
|
+
};
|
|
357
|
+
function cadenceShimPlugin() {
|
|
358
|
+
return {
|
|
359
|
+
name: 'cadence-engine-shims',
|
|
360
|
+
setup(build) {
|
|
361
|
+
build.onResolve({ filter: /^@cadence\/(core|runtime|bridge|router)$/ }, (args) => ({
|
|
362
|
+
path: args.path.replace('@cadence/', ''),
|
|
363
|
+
namespace: 'cadence-shim',
|
|
364
|
+
}));
|
|
365
|
+
build.onLoad({ filter: /.*/, namespace: 'cadence-shim' }, (args) => {
|
|
366
|
+
const exports = SHIM_EXPORTS[args.path];
|
|
367
|
+
if (exports === undefined) {
|
|
368
|
+
return { errors: [{ text: `no shim for '@cadence/${args.path}'` }] };
|
|
369
|
+
}
|
|
370
|
+
const lines = [
|
|
371
|
+
`const m = globalThis.Cadence.modules[${JSON.stringify(args.path)}];`,
|
|
372
|
+
...exports.map((name) => `export const ${name} = m.${name};`),
|
|
373
|
+
];
|
|
374
|
+
return { contents: lines.join('\n'), loader: 'js' };
|
|
375
|
+
});
|
|
376
|
+
},
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
async function writeHtmlShells(outDir, language) {
|
|
380
|
+
await writeFile(path.join(outDir, 'index.html'), htmlShell(['engine.js', 'app.js'], language));
|
|
381
|
+
await writeFile(path.join(outDir, DEV_SHELL_FILE), htmlShell(['engine.js', `${DEV_HOST_ENTRY}.js`, 'app.js', `${DEV_CLIENT_ENTRY}.js`], language));
|
|
382
|
+
}
|
|
383
|
+
/* Le `lang` du document décrit ce qu'on lit, pas qui lit : il vient donc du
|
|
384
|
+
manifeste et non de la locale de l'appareil. Sans lui, tout bundle était
|
|
385
|
+
prononcé en français par VoiceOver et TalkBack, y compris un mini-programme
|
|
386
|
+
entièrement anglophone. */
|
|
387
|
+
const DEFAULT_DOCUMENT_LANGUAGE = 'en';
|
|
388
|
+
function htmlShell(scripts, language) {
|
|
389
|
+
const scriptTags = scripts.map((src) => ` <script src="./${src}"></script>`).join('\n');
|
|
390
|
+
return `<!doctype html>
|
|
391
|
+
<html lang="${language}">
|
|
392
|
+
<head>
|
|
393
|
+
<meta charset="utf-8" />
|
|
394
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
|
395
|
+
<title>Cadence</title>
|
|
396
|
+
</head>
|
|
397
|
+
<body>
|
|
398
|
+
<div id="app"></div>
|
|
399
|
+
${scriptTags}
|
|
400
|
+
</body>
|
|
401
|
+
</html>
|
|
402
|
+
`;
|
|
403
|
+
}
|
|
404
|
+
async function measure(filePath) {
|
|
405
|
+
const contents = await readFile(filePath);
|
|
406
|
+
return { raw: contents.byteLength, gzip: gzipSync(contents).byteLength };
|
|
407
|
+
}
|
|
408
|
+
async function writeBundleArchive(outDir, manifest) {
|
|
409
|
+
const zip = new JSZip();
|
|
410
|
+
await addDirectoryToZip(zip, outDir, '', DEV_SCAFFOLD_FILES);
|
|
411
|
+
const archiveName = `${manifest.name}-${manifest.version}.zip`;
|
|
412
|
+
const buffer = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
|
|
413
|
+
await writeFile(path.join(outDir, archiveName), buffer);
|
|
414
|
+
return archiveName;
|
|
415
|
+
}
|
|
416
|
+
async function addDirectoryToZip(zip, directory, prefix, excludedPaths) {
|
|
417
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
418
|
+
for (const entry of entries) {
|
|
419
|
+
const entryPath = path.join(directory, entry.name);
|
|
420
|
+
const zipPath = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
|
|
421
|
+
if (excludedPaths.has(zipPath)) {
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
if (entry.isDirectory()) {
|
|
425
|
+
await addDirectoryToZip(zip, entryPath, zipPath, excludedPaths);
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
zip.file(zipPath, await readFile(entryPath));
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
function indentBlock(code, indent) {
|
|
433
|
+
return code
|
|
434
|
+
.split('\n')
|
|
435
|
+
.map((line, index) => (index === 0 ? line : `${indent}${line}`))
|
|
436
|
+
.join('\n');
|
|
437
|
+
}
|
package/dist/cli.d.ts
ADDED