@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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -0
  3. package/dist/build.d.ts +31 -0
  4. package/dist/build.js +437 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +180 -0
  7. package/dist/dev-server.d.ts +16 -0
  8. package/dist/dev-server.js +81 -0
  9. package/dist/engine-budget.d.ts +9 -0
  10. package/dist/engine-budget.js +8 -0
  11. package/dist/hash.d.ts +2 -0
  12. package/dist/hash.js +12 -0
  13. package/dist/host/browser-mock-host.d.ts +1 -0
  14. package/dist/host/browser-mock-host.js +175 -0
  15. package/dist/host/dev-client.d.ts +1 -0
  16. package/dist/host/dev-client.js +6 -0
  17. package/dist/host/engine-entry.d.ts +1 -0
  18. package/dist/host/engine-entry.js +199 -0
  19. package/dist/index.d.ts +23 -0
  20. package/dist/index.js +14 -0
  21. package/dist/manifest.d.ts +47 -0
  22. package/dist/manifest.js +202 -0
  23. package/dist/publish/credentials.d.ts +17 -0
  24. package/dist/publish/credentials.js +87 -0
  25. package/dist/publish/distribution-client.d.ts +45 -0
  26. package/dist/publish/distribution-client.js +113 -0
  27. package/dist/publish/publish-bundle.d.ts +27 -0
  28. package/dist/publish/publish-bundle.js +44 -0
  29. package/dist/publish/publish-errors.d.ts +41 -0
  30. package/dist/publish/publish-errors.js +60 -0
  31. package/dist/publish/read-secret.d.ts +7 -0
  32. package/dist/publish/read-secret.js +30 -0
  33. package/dist/style/compile-style.d.ts +13 -0
  34. package/dist/style/compile-style.js +135 -0
  35. package/dist/style/theme-sheet.d.ts +6 -0
  36. package/dist/style/theme-sheet.js +8 -0
  37. package/dist/template/ast.d.ts +47 -0
  38. package/dist/template/ast.js +1 -0
  39. package/dist/template/codegen.d.ts +8 -0
  40. package/dist/template/codegen.js +220 -0
  41. package/dist/template/entities.d.ts +12 -0
  42. package/dist/template/entities.js +103 -0
  43. package/dist/template/expression.d.ts +16 -0
  44. package/dist/template/expression.js +196 -0
  45. package/dist/template/parser.d.ts +10 -0
  46. package/dist/template/parser.js +437 -0
  47. package/package.json +62 -0
@@ -0,0 +1,199 @@
1
+ import * as core from '@cadence-app/core';
2
+ import * as runtime from '@cadence-app/runtime';
3
+ import * as bridge from '@cadence-app/bridge';
4
+ import * as router from '@cadence-app/router';
5
+ import { JavaScriptChannelTransport, containerBridgeObject, NativeBridge, TransportUnavailableError, createNativeApi, setActiveNativeApi, } from '@cadence-app/bridge';
6
+ import { APP_ICON_STYLE_ID, BASE_STYLESHEET, BASE_STYLE_ID, BUILTIN_COMPONENTS, BUILTIN_COMPONENT_STYLESHEET, BUILTIN_COMPONENT_STYLE_ID, BUILTIN_ICONS, ComponentRegistry, ICON_BASE_STYLESHEET, ICON_STYLE_ID, appendStyle, iconRulesFor, applyTextScale, applyViewportGeometry, injectStyleOnce, installErrorBoundary, instructions, textScaleOf, toEngineError, } from '@cadence-app/runtime';
7
+ import { BridgeEvents } from '@cadence-app/bridge';
8
+ import { PageRegistry, ROUTER_STYLESHEET, ROUTER_STYLE_ID, Router, resolvePageChrome, setActiveRouter, } from '@cadence-app/router';
9
+ import { COLOR_SCHEME_ATTRIBUTE, PLATFORM_ATTRIBUTE, THEME_STYLE_ID } from '@cadence-app/theme';
10
+ import { allManifestPages } from "../manifest.js";
11
+ const ENGINE_VERSION = '0.1.0';
12
+ const metrics = { timeToInteractiveMs: null };
13
+ /**
14
+ * Installée avant toute autre chose : une exception pendant la sélection du
15
+ * transport ou l'amorçage doit rester visible, même si le bridge n'existe
16
+ * jamais. `reportToContainer` et `reportToApp` sont branchés plus tard, dès que
17
+ * le bridge et le routeur sont là.
18
+ */
19
+ let reportToContainer = null;
20
+ let reportToApp = null;
21
+ const errorBoundary = installErrorBoundary({
22
+ document,
23
+ report: (error) => {
24
+ reportToContainer?.(error);
25
+ reportToApp?.(error);
26
+ },
27
+ });
28
+ const componentRegistry = new ComponentRegistry();
29
+ const pageRegistry = new PageRegistry();
30
+ for (const definition of BUILTIN_COMPONENTS) {
31
+ componentRegistry.register(definition);
32
+ }
33
+ function registerPage(route, definition) {
34
+ pageRegistry.register(route, {
35
+ setup: definition.setup ?? (() => ({})),
36
+ render: definition.render,
37
+ ...(definition.styleId === undefined ? {} : { styleId: definition.styleId }),
38
+ ...(definition.css === undefined ? {} : { css: definition.css }),
39
+ });
40
+ }
41
+ function registerComponent(definition) {
42
+ componentRegistry.register(definition);
43
+ }
44
+ /**
45
+ * La feuille de tokens est calculée au build : le moteur ne fait que
46
+ * l'installer, et assez tôt pour que rien ne soit peint sans elle.
47
+ */
48
+ function registerTheme(css) {
49
+ injectStyleOnce(document, THEME_STYLE_ID, css);
50
+ }
51
+ /**
52
+ * Jeu d'icônes propre au mini-programme : on enregistre, on ne modifie pas le
53
+ * noyau (§3, ouvert/fermé). Un nom déjà pris par le jeu embarqué le remplace,
54
+ * puisque les règles s'ajoutent après dans la cascade.
55
+ */
56
+ function registerIcons(icons) {
57
+ appendStyle(document, APP_ICON_STYLE_ID, iconRulesFor(icons));
58
+ }
59
+ function selectTransport() {
60
+ if (containerBridgeObject() !== undefined) {
61
+ return new JavaScriptChannelTransport();
62
+ }
63
+ const devTransport = globalThis.__cadenceDevTransport;
64
+ if (devTransport !== undefined) {
65
+ return devTransport;
66
+ }
67
+ throw new TransportUnavailableError('neither the Flutter WebView handler nor a dev transport is present');
68
+ }
69
+ function loadSubPackageChunk(chunkRoot) {
70
+ return new Promise((resolve, reject) => {
71
+ const script = document.createElement('script');
72
+ script.src = `subpackages/${chunkRoot}.js`;
73
+ script.onload = () => resolve();
74
+ script.onerror = () => reject(new Error(`could not load subpackages/${chunkRoot}.js`));
75
+ document.head.appendChild(script);
76
+ });
77
+ }
78
+ /**
79
+ * La WebView occupe tout l'écran, barre de statut comprise : sans ces valeurs
80
+ * le mini-programme dessinerait son en-tête sous l'heure et la batterie.
81
+ */
82
+ async function applyInitialEnvironment(nativeApi) {
83
+ const info = await nativeApi.system.getSystemInfo();
84
+ applyViewportGeometry(document, { safeAreaInsets: info.safeAreaInsets, capsule: info.capsule });
85
+ applyColorScheme(nativeApi, info.colorScheme);
86
+ applyTextScale(document, textScaleOf(info));
87
+ /* La plateforme ne change pas en cours de route : elle se pose une fois, et
88
+ un nom que le preset ignore ne matche simplement aucun bloc. */
89
+ document.documentElement.setAttribute(PLATFORM_ATTRIBUTE, info.platform);
90
+ }
91
+ /**
92
+ * Le schéma va sur la racine, comme le style de navigation (ADR-006) : les
93
+ * feuilles réagissent, rien n'est reconstruit. Les icônes de la barre de statut
94
+ * suivent par défaut — un en-tête sombre demande des icônes claires — et un
95
+ * mini-programme qui en décide autrement appelle `ui.setStatusBarIcons` après.
96
+ */
97
+ function applyColorScheme(nativeApi, colorScheme) {
98
+ document.documentElement.setAttribute(COLOR_SCHEME_ATTRIBUTE, colorScheme);
99
+ void nativeApi.ui
100
+ .setStatusBarIcons(colorScheme === 'dark' ? 'light' : 'dark')
101
+ .catch(() => undefined);
102
+ }
103
+ /**
104
+ * Le conteneur répond sous le dernier chrome qu'on lui a annoncé : sans cette
105
+ * annonce, une entrée `custom` écrirait ses zones sûres sous la barre que le
106
+ * conteneur affiche par défaut.
107
+ */
108
+ function announceEntryChrome(nativeApi, manifest) {
109
+ nativeApi.nav.setChrome(resolvePageChrome(manifest, manifest.entry)).catch((error) => {
110
+ console.error('[cadence] the container did not take the entry chrome', error);
111
+ });
112
+ }
113
+ function resolveAppRoot() {
114
+ const existing = document.getElementById('app');
115
+ if (existing !== null) {
116
+ return existing;
117
+ }
118
+ const created = document.createElement('div');
119
+ created.id = 'app';
120
+ document.body.appendChild(created);
121
+ return created;
122
+ }
123
+ async function bootstrap(manifest, app) {
124
+ try {
125
+ await startEngine(manifest, app);
126
+ }
127
+ catch (error) {
128
+ errorBoundary.handle(toEngineError(error, 'bootstrap'));
129
+ throw error;
130
+ }
131
+ }
132
+ async function startEngine(manifest, app) {
133
+ const transport = selectTransport();
134
+ const nativeBridge = new NativeBridge(transport);
135
+ const nativeApi = createNativeApi(nativeBridge);
136
+ setActiveNativeApi(nativeApi);
137
+ reportToContainer = (error) => {
138
+ // Un rejet ici relancerait le gestionnaire de rejets non interceptés.
139
+ void nativeApi.app.reportError(error).catch(() => undefined);
140
+ };
141
+ injectStyleOnce(document, BASE_STYLE_ID, BASE_STYLESHEET);
142
+ injectStyleOnce(document, ICON_STYLE_ID, ICON_BASE_STYLESHEET + iconRulesFor(BUILTIN_ICONS));
143
+ injectStyleOnce(document, BUILTIN_COMPONENT_STYLE_ID, BUILTIN_COMPONENT_STYLESHEET);
144
+ injectStyleOnce(document, ROUTER_STYLE_ID, ROUTER_STYLESHEET);
145
+ const routerManifest = {
146
+ entry: manifest.entry,
147
+ pages: allManifestPages(manifest),
148
+ ...(manifest.tabBar === undefined ? {} : { tabBar: manifest.tabBar }),
149
+ ...(manifest.subPackages === undefined ? {} : { subPackages: manifest.subPackages }),
150
+ ...(manifest.navigationStyle === undefined
151
+ ? {}
152
+ : { navigationStyle: manifest.navigationStyle }),
153
+ };
154
+ announceEntryChrome(nativeApi, routerManifest);
155
+ await applyInitialEnvironment(nativeApi);
156
+ nativeBridge.on(BridgeEvents.colorSchemeChanged, (payload) => {
157
+ applyColorScheme(nativeApi, payload.colorScheme);
158
+ });
159
+ nativeBridge.on(BridgeEvents.textScaleChanged, (payload) => {
160
+ applyTextScale(document, textScaleOf(payload));
161
+ });
162
+ nativeBridge.on(BridgeEvents.viewportChanged, (payload) => {
163
+ const viewport = payload;
164
+ applyViewportGeometry(document, {
165
+ safeAreaInsets: viewport.safeAreaInsets,
166
+ capsule: viewport.capsule,
167
+ });
168
+ });
169
+ const root = resolveAppRoot();
170
+ root.className = 'cadence-app';
171
+ const appRouter = new Router({
172
+ document,
173
+ rootElement: root,
174
+ registry: componentRegistry,
175
+ instructionTable: instructions,
176
+ pages: pageRegistry,
177
+ nav: nativeApi.nav,
178
+ bridge: nativeBridge,
179
+ manifest: routerManifest,
180
+ loadChunk: loadSubPackageChunk,
181
+ reportError: (error) => errorBoundary.handle(toEngineError(error, 'uncaught')),
182
+ ...(app === undefined ? {} : { app }),
183
+ });
184
+ reportToApp = (error) => appRouter.reportErrorToApp(error);
185
+ setActiveRouter(appRouter);
186
+ await appRouter.launch();
187
+ metrics.timeToInteractiveMs = performance.now();
188
+ }
189
+ const cadenceGlobal = {
190
+ version: ENGINE_VERSION,
191
+ modules: { core, runtime, bridge, router },
192
+ metrics,
193
+ registerPage,
194
+ registerComponent,
195
+ registerTheme,
196
+ registerIcons,
197
+ bootstrap,
198
+ };
199
+ globalThis.Cadence = cadenceGlobal;
@@ -0,0 +1,23 @@
1
+ export { parseTemplate, TemplateParseError } from './template/parser.js';
2
+ export type { TemplateNode, ElementNode, TextNode, InterpolationNode, IfNode, IfBranchNode, ForNode, SwitchNode, SwitchCaseNode, SlotNode, } from './template/ast.js';
3
+ export { decodeHtmlEntities, UnknownHtmlEntityError, InvalidCharacterReferenceError, } from './template/entities.js';
4
+ export { rewriteExpression, ExpressionError, EMPTY_SCOPE } from './template/expression.js';
5
+ export type { ExpressionScope } from './template/expression.js';
6
+ export { generateRenderFunction } from './template/codegen.js';
7
+ export { compileStyle, StyleCompileError } from './style/compile-style.js';
8
+ export { buildThemeSheet } from './style/theme-sheet.js';
9
+ export type { CompileStyleOptions } from './style/compile-style.js';
10
+ export { parseManifest, allManifestPages, ManifestError } from './manifest.js';
11
+ export type { MiniAppManifest, ManifestPage, ManifestTabBar, ManifestTabBarItem, ManifestSubPackage, } from './manifest.js';
12
+ export { stableHash } from './hash.js';
13
+ export { buildMiniApp, BuildError } from './build.js';
14
+ export type { BuildOptions, BuildSummary, SizeReport } from './build.js';
15
+ export { startDevServer } from './dev-server.js';
16
+ export type { DevServer, DevServerOptions } from './dev-server.js';
17
+ export { credentialsPath, readCredentials, writeCredentials, clearCredentials, normalizeRemoteUrl, } from './publish/credentials.js';
18
+ export type { Credentials } from './publish/credentials.js';
19
+ export { DistributionClient } from './publish/distribution-client.js';
20
+ export type { FetchLike, RemoteApp, PublishedVersion, DistributionClientOptions, } from './publish/distribution-client.js';
21
+ export { publishMiniApp } from './publish/publish-bundle.js';
22
+ export type { PublishOptions, PublishReport } from './publish/publish-bundle.js';
23
+ export { NotAuthenticatedError, InvalidTokenError, AppNotFoundError, VersionConflictError, PublishRejectedError, RemoteUnreachableError, } from './publish/publish-errors.js';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ export { parseTemplate, TemplateParseError } from "./template/parser.js";
2
+ export { decodeHtmlEntities, UnknownHtmlEntityError, InvalidCharacterReferenceError, } from "./template/entities.js";
3
+ export { rewriteExpression, ExpressionError, EMPTY_SCOPE } from "./template/expression.js";
4
+ export { generateRenderFunction } from "./template/codegen.js";
5
+ export { compileStyle, StyleCompileError } from "./style/compile-style.js";
6
+ export { buildThemeSheet } from "./style/theme-sheet.js";
7
+ export { parseManifest, allManifestPages, ManifestError } from "./manifest.js";
8
+ export { stableHash } from "./hash.js";
9
+ export { buildMiniApp, BuildError } from "./build.js";
10
+ export { startDevServer } from "./dev-server.js";
11
+ export { credentialsPath, readCredentials, writeCredentials, clearCredentials, normalizeRemoteUrl, } from "./publish/credentials.js";
12
+ export { DistributionClient } from "./publish/distribution-client.js";
13
+ export { publishMiniApp } from "./publish/publish-bundle.js";
14
+ export { NotAuthenticatedError, InvalidTokenError, AppNotFoundError, VersionConflictError, PublishRejectedError, RemoteUnreachableError, } from "./publish/publish-errors.js";
@@ -0,0 +1,47 @@
1
+ import type { NavigationStyle } from '@cadence-app/bridge';
2
+ import type { TokenTree } from '@cadence-app/theme';
3
+ import type { TabBarStyle } from '@cadence-app/router';
4
+ export declare class ManifestError extends Error {
5
+ constructor(reason: string);
6
+ }
7
+ export interface ManifestPage {
8
+ readonly path: string;
9
+ readonly title?: string;
10
+ /** Surcharge le réglage global pour cette page. */
11
+ readonly navigationStyle?: NavigationStyle;
12
+ }
13
+ export interface ManifestTabBarItem {
14
+ readonly path: string;
15
+ readonly title: string;
16
+ /** Nom d'icône : jeu embarqué du moteur, ou fichier de `icons/`. */
17
+ readonly icon?: string;
18
+ readonly activeIcon?: string;
19
+ }
20
+ export interface ManifestTabBar {
21
+ readonly items: readonly ManifestTabBarItem[];
22
+ readonly style?: TabBarStyle;
23
+ }
24
+ export interface ManifestSubPackage {
25
+ readonly root: string;
26
+ readonly pages: readonly ManifestPage[];
27
+ }
28
+ export interface MiniAppManifest {
29
+ readonly name: string;
30
+ readonly version: string;
31
+ readonly entry: string;
32
+ readonly pages: readonly ManifestPage[];
33
+ readonly tabBar?: ManifestTabBar;
34
+ readonly subPackages?: readonly ManifestSubPackage[];
35
+ readonly navigationStyle?: NavigationStyle;
36
+ /** Surcharge partielle du preset embarqué, fusionnée au build. */
37
+ readonly theme?: TokenTree;
38
+ /**
39
+ * La langue du **contenu**, pas celle du lecteur : un mini-programme
40
+ * anglophone se lit en anglais même sur un téléphone configuré en français.
41
+ * Elle devient le `lang` du document, que VoiceOver et TalkBack suivent.
42
+ */
43
+ readonly language?: string;
44
+ }
45
+ export declare function parseManifest(json: string): MiniAppManifest;
46
+ /** Toutes les pages du mini-programme, sous-packages inclus. */
47
+ export declare function allManifestPages(manifest: MiniAppManifest): ManifestPage[];
@@ -0,0 +1,202 @@
1
+ import { NAVIGATION_STYLES } from '@cadence-app/bridge';
2
+ export class ManifestError extends Error {
3
+ constructor(reason) {
4
+ super(`Invalid manifest.json: ${reason}`);
5
+ this.name = 'ManifestError';
6
+ }
7
+ }
8
+ const LANGUAGE_TAG_PATTERN = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
9
+ const MIN_TAB_ITEMS = 2;
10
+ const MAX_TAB_ITEMS = 5;
11
+ export function parseManifest(json) {
12
+ let raw;
13
+ try {
14
+ raw = JSON.parse(json);
15
+ }
16
+ catch {
17
+ throw new ManifestError('not valid JSON');
18
+ }
19
+ if (!isRecord(raw)) {
20
+ throw new ManifestError('expected a JSON object');
21
+ }
22
+ const name = requireNonEmptyString(raw, 'name');
23
+ const version = requireNonEmptyString(raw, 'version');
24
+ const entry = requireNonEmptyString(raw, 'entry');
25
+ const pages = parsePages(raw['pages'], 'pages');
26
+ if (pages.length === 0) {
27
+ throw new ManifestError('pages must list at least one page');
28
+ }
29
+ const subPackages = raw['subPackages'] === undefined ? [] : parseSubPackages(raw['subPackages']);
30
+ const mainPaths = new Set(pages.map((page) => page.path));
31
+ if (!mainPaths.has(entry)) {
32
+ throw new ManifestError(`entry '${entry}' is not declared in pages`);
33
+ }
34
+ const manifest = {
35
+ name,
36
+ version,
37
+ entry,
38
+ pages,
39
+ ...(raw['navigationStyle'] === undefined
40
+ ? {}
41
+ : { navigationStyle: parseNavigationStyle(raw['navigationStyle'], 'navigationStyle') }),
42
+ ...(raw['language'] === undefined ? {} : { language: parseLanguage(raw['language']) }),
43
+ ...(subPackages.length === 0 ? {} : { subPackages }),
44
+ ...(raw['tabBar'] === undefined ? {} : { tabBar: parseTabBar(raw['tabBar'], mainPaths) }),
45
+ ...(raw['theme'] === undefined ? {} : { theme: parseTheme(raw['theme'], 'theme') }),
46
+ };
47
+ return manifest;
48
+ }
49
+ /**
50
+ * Une étiquette de langue BCP 47, telle que `lang` l'attend : `fr`, `en-US`.
51
+ * On vérifie la forme, pas l'existence — la liste des langues n'est pas au
52
+ * compilateur, et une étiquette bien formée mais inconnue est simplement
53
+ * ignorée par le lecteur d'écran.
54
+ */
55
+ function parseLanguage(value) {
56
+ if (typeof value !== 'string' || !LANGUAGE_TAG_PATTERN.test(value)) {
57
+ throw new ManifestError(`language must be a BCP 47 tag such as 'fr' or 'en-US', got ${JSON.stringify(value)}`);
58
+ }
59
+ return value;
60
+ }
61
+ /** Toutes les pages du mini-programme, sous-packages inclus. */
62
+ export function allManifestPages(manifest) {
63
+ return [...manifest.pages, ...(manifest.subPackages ?? []).flatMap((sub) => [...sub.pages])];
64
+ }
65
+ function parsePages(value, field) {
66
+ if (!Array.isArray(value)) {
67
+ throw new ManifestError(`${field} must be an array`);
68
+ }
69
+ return value.map((candidate, index) => {
70
+ if (!isRecord(candidate)) {
71
+ throw new ManifestError(`${field}[${index}] must be an object`);
72
+ }
73
+ const path = candidate['path'];
74
+ if (typeof path !== 'string' || path.length === 0) {
75
+ throw new ManifestError(`${field}[${index}].path must be a non-empty string`);
76
+ }
77
+ const title = candidate['title'];
78
+ if (title !== undefined && typeof title !== 'string') {
79
+ throw new ManifestError(`${field}[${index}].title must be a string`);
80
+ }
81
+ const style = candidate['navigationStyle'];
82
+ return {
83
+ path,
84
+ ...(title === undefined ? {} : { title }),
85
+ ...(style === undefined
86
+ ? {}
87
+ : { navigationStyle: parseNavigationStyle(style, `${field}[${index}].navigationStyle`) }),
88
+ };
89
+ });
90
+ }
91
+ function parseTabBar(value, knownPaths) {
92
+ if (!isRecord(value) || !Array.isArray(value['items'])) {
93
+ throw new ManifestError('tabBar.items must be an array');
94
+ }
95
+ const items = value['items'].map((candidate, index) => parseTabBarItem(candidate, index, knownPaths));
96
+ if (items.length < MIN_TAB_ITEMS || items.length > MAX_TAB_ITEMS) {
97
+ throw new ManifestError(`tabBar requires between ${MIN_TAB_ITEMS} and ${MAX_TAB_ITEMS} items`);
98
+ }
99
+ const style = value['style'];
100
+ return {
101
+ items,
102
+ ...(style === undefined ? {} : { style: parseTabBarStyle(style) }),
103
+ };
104
+ }
105
+ function parseTabBarItem(candidate, index, knownPaths) {
106
+ if (!isRecord(candidate)) {
107
+ throw new ManifestError(`tabBar.items[${index}] must be an object`);
108
+ }
109
+ const path = candidate['path'];
110
+ const title = candidate['title'];
111
+ if (typeof path !== 'string' || typeof title !== 'string') {
112
+ throw new ManifestError(`tabBar.items[${index}] requires string path and title`);
113
+ }
114
+ if (!knownPaths.has(path)) {
115
+ throw new ManifestError(`tabBar.items[${index}].path '${path}' is not a main-package page`);
116
+ }
117
+ const icon = requireOptionalIconName(candidate['icon'], `tabBar.items[${index}].icon`);
118
+ const activeIcon = requireOptionalIconName(candidate['activeIcon'], `tabBar.items[${index}].activeIcon`);
119
+ return {
120
+ path,
121
+ title,
122
+ ...(icon === undefined ? {} : { icon }),
123
+ ...(activeIcon === undefined ? {} : { activeIcon }),
124
+ };
125
+ }
126
+ function requireOptionalIconName(value, field) {
127
+ if (value === undefined) {
128
+ return undefined;
129
+ }
130
+ if (typeof value !== 'string' || value.length === 0) {
131
+ throw new ManifestError(`${field} must be a non-empty string`);
132
+ }
133
+ return value;
134
+ }
135
+ function parseTabBarStyle(value) {
136
+ if (value !== 'anchored' && value !== 'floating') {
137
+ throw new ManifestError("tabBar.style must be 'anchored' or 'floating'");
138
+ }
139
+ return value;
140
+ }
141
+ /**
142
+ * La forme seule est vérifiée ici — un arbre dont les feuilles sont des chaînes.
143
+ * Que les chemins existent dans le preset de base relève de la fusion, qui sait
144
+ * lequel manque.
145
+ */
146
+ function parseTheme(value, field) {
147
+ if (!isRecord(value)) {
148
+ throw new ManifestError(`${field} must be an object`);
149
+ }
150
+ const tree = {};
151
+ for (const [key, leaf] of Object.entries(value)) {
152
+ if (typeof leaf === 'string') {
153
+ tree[key] = leaf;
154
+ }
155
+ else if (isRecord(leaf)) {
156
+ tree[key] = parseTheme(leaf, `${field}.${key}`);
157
+ }
158
+ else {
159
+ throw new ManifestError(`${field}.${key} must be a string or an object`);
160
+ }
161
+ }
162
+ return tree;
163
+ }
164
+ function parseSubPackages(value) {
165
+ if (!Array.isArray(value)) {
166
+ throw new ManifestError('subPackages must be an array');
167
+ }
168
+ return value.map((candidate, index) => {
169
+ if (!isRecord(candidate)) {
170
+ throw new ManifestError(`subPackages[${index}] must be an object`);
171
+ }
172
+ const root = candidate['root'];
173
+ if (typeof root !== 'string' || root.length === 0) {
174
+ throw new ManifestError(`subPackages[${index}].root must be a non-empty string`);
175
+ }
176
+ const pages = parsePages(candidate['pages'], `subPackages[${index}].pages`);
177
+ for (const page of pages) {
178
+ if (!page.path.startsWith(`${root}/`)) {
179
+ throw new ManifestError(`subPackages[${index}] page '${page.path}' must live under '${root}/'`);
180
+ }
181
+ }
182
+ return { root, pages };
183
+ });
184
+ }
185
+ function parseNavigationStyle(value, field) {
186
+ const style = NAVIGATION_STYLES.find((supported) => supported === value);
187
+ if (style === undefined) {
188
+ const choices = NAVIGATION_STYLES.map((supported) => `'${supported}'`).join(' or ');
189
+ throw new ManifestError(`${field} must be ${choices}`);
190
+ }
191
+ return style;
192
+ }
193
+ function requireNonEmptyString(record, field) {
194
+ const value = record[field];
195
+ if (typeof value !== 'string' || value.length === 0) {
196
+ throw new ManifestError(`${field} must be a non-empty string`);
197
+ }
198
+ return value;
199
+ }
200
+ function isRecord(value) {
201
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
202
+ }
@@ -0,0 +1,17 @@
1
+ /** Ce qu'il faut pour parler à un serveur de distribution en son nom. */
2
+ export interface Credentials {
3
+ /** Racine de l'API, sans barre finale (`https://api.exemple.fr`). */
4
+ readonly remoteUrl: string;
5
+ /** Jeton d'accès personnel, présenté en `Authorization: Bearer`. */
6
+ readonly token: string;
7
+ }
8
+ /** Emplacement du fichier d'identifiants, dérivé du dossier personnel. */
9
+ export declare function credentialsPath(home?: string): string;
10
+ /** Les identifiants enregistrés, ou `null` s'il n'y en a aucun d'exploitable. */
11
+ export declare function readCredentials(home?: string): Promise<Credentials | null>;
12
+ /** Écrit les identifiants, en n'accordant l'accès qu'au propriétaire. */
13
+ export declare function writeCredentials(credentials: Credentials, home?: string): Promise<string>;
14
+ /** Efface les identifiants. Vrai si un fichier a bien été supprimé. */
15
+ export declare function clearCredentials(home?: string): Promise<boolean>;
16
+ /** Normalise une racine d'API : une barre finale changerait toutes les URL. */
17
+ export declare function normalizeRemoteUrl(remoteUrl: string): string;
@@ -0,0 +1,87 @@
1
+ import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import path from 'node:path';
4
+ const CONFIG_DIRECTORY = '.cadence';
5
+ const CONFIG_FILE = 'config.json';
6
+ /**
7
+ * Le fichier d'identifiants et son dossier ne sont lisibles que par leur
8
+ * propriétaire : il porte un jeton en clair, comme le fait `~/.npmrc`.
9
+ */
10
+ const OWNER_ONLY_FILE = 0o600;
11
+ const OWNER_ONLY_DIRECTORY = 0o700;
12
+ /** Emplacement du fichier d'identifiants, dérivé du dossier personnel. */
13
+ export function credentialsPath(home = homedir()) {
14
+ return path.join(home, CONFIG_DIRECTORY, CONFIG_FILE);
15
+ }
16
+ /** Les identifiants enregistrés, ou `null` s'il n'y en a aucun d'exploitable. */
17
+ export async function readCredentials(home) {
18
+ const file = credentialsPath(home);
19
+ let raw;
20
+ try {
21
+ raw = await readFile(file, 'utf8');
22
+ }
23
+ catch (error) {
24
+ if (isFileNotFound(error)) {
25
+ return null;
26
+ }
27
+ throw error;
28
+ }
29
+ return parseCredentials(raw);
30
+ }
31
+ /** Écrit les identifiants, en n'accordant l'accès qu'au propriétaire. */
32
+ export async function writeCredentials(credentials, home) {
33
+ const file = credentialsPath(home);
34
+ await mkdir(path.dirname(file), { recursive: true, mode: OWNER_ONLY_DIRECTORY });
35
+ await writeFile(file, `${JSON.stringify(credentials, null, 2)}\n`, { mode: OWNER_ONLY_FILE });
36
+ // `writeFile` n'applique `mode` qu'à la création : un fichier déjà présent
37
+ // garderait des permissions plus larges sans ce second appel.
38
+ await chmod(file, OWNER_ONLY_FILE);
39
+ return file;
40
+ }
41
+ /** Efface les identifiants. Vrai si un fichier a bien été supprimé. */
42
+ export async function clearCredentials(home) {
43
+ const file = credentialsPath(home);
44
+ try {
45
+ await rm(file);
46
+ return true;
47
+ }
48
+ catch (error) {
49
+ if (isFileNotFound(error)) {
50
+ return false;
51
+ }
52
+ throw error;
53
+ }
54
+ }
55
+ /** Normalise une racine d'API : une barre finale changerait toutes les URL. */
56
+ export function normalizeRemoteUrl(remoteUrl) {
57
+ return remoteUrl.replace(/\/+$/, '');
58
+ }
59
+ /**
60
+ * Un fichier corrompu ou incomplet vaut « pas d'identifiants » plutôt qu'un
61
+ * plantage : le CLI renverra vers `mini login`, qui est l'action utile.
62
+ */
63
+ function parseCredentials(raw) {
64
+ let parsed;
65
+ try {
66
+ parsed = JSON.parse(raw);
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ if (typeof parsed !== 'object' || parsed === null) {
72
+ return null;
73
+ }
74
+ const { remoteUrl, token } = parsed;
75
+ if (typeof remoteUrl !== 'string' || typeof token !== 'string') {
76
+ return null;
77
+ }
78
+ if (remoteUrl === '' || token === '') {
79
+ return null;
80
+ }
81
+ return { remoteUrl: normalizeRemoteUrl(remoteUrl), token };
82
+ }
83
+ function isFileNotFound(error) {
84
+ return (typeof error === 'object' &&
85
+ error !== null &&
86
+ error.code === 'ENOENT');
87
+ }
@@ -0,0 +1,45 @@
1
+ /** La frontière réseau, injectée pour que les tests n'aient rien d'autre à simuler. */
2
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
3
+ /** Une application telle que le serveur de distribution la décrit. */
4
+ export interface RemoteApp {
5
+ readonly id: string;
6
+ readonly name: string;
7
+ readonly slug: string;
8
+ }
9
+ /** Ce que le serveur répond quand une version est acceptée. */
10
+ export interface PublishedVersion {
11
+ readonly versionString: string;
12
+ readonly status: string | null;
13
+ readonly createdAt: string | null;
14
+ }
15
+ export interface DistributionClientOptions {
16
+ readonly remoteUrl: string;
17
+ readonly token: string;
18
+ readonly fetch?: FetchLike;
19
+ }
20
+ /**
21
+ * Le serveur de distribution, vu du CLI. Une méthode par intention, et des
22
+ * erreurs typées : aucun appelant n'a à lire un code HTTP.
23
+ */
24
+ export declare class DistributionClient {
25
+ constructor(options: DistributionClientOptions);
26
+ private readonly remoteUrl;
27
+ private readonly token;
28
+ private readonly fetch;
29
+ /** Lève si le serveur refuse le jeton ; se tait s'il l'accepte. */
30
+ verifyToken(): Promise<void>;
31
+ /**
32
+ * L'application dont le slug est celui du manifeste. Le serveur ne l'expose
33
+ * pas par slug : on parcourt les pages du tenant et on compare.
34
+ */
35
+ findAppBySlug(slug: string): Promise<RemoteApp>;
36
+ /** Envoie l'archive comme nouvelle version de l'application. */
37
+ publishVersion(input: {
38
+ readonly appId: string;
39
+ readonly version: string;
40
+ readonly archive: Uint8Array;
41
+ readonly filename: string;
42
+ }): Promise<PublishedVersion>;
43
+ private send;
44
+ private rejectionFor;
45
+ }