@milofly/theme-sdk 0.0.0-stage → 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/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-27)
4
+
5
+ - First version: manifest v1 types, `readThemeProject`, `writeThemeProject`, `checkManifestShape`, `canonicalJson`,
6
+ `component-schema` validators (same source as the Milofly platform).
7
+ - `assets` (the package's own icons and fonts): `PROJECT_LAYOUT.assets|assetFiles`, `readThemeAssets`, `assetFilePath`; `readThemeProject`
8
+ adds `assets` with each file's SHA-256, `writeThemeProject` leaves the local asset list untouched.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alper Baydeniz
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 CHANGED
@@ -1,3 +1,39 @@
1
- # Temporary Holding Version
1
+ # @milofly/theme-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Types and helpers for Milofly **composition theme packages** (manifest v1). A Milofly theme is data, not code: pages,
4
+ layouts and theme settings built from Milofly's component library, plus the *offerings* (which components, product cards,
5
+ modals and badges the theme provides). You build it visually in your development store; this SDK keeps it as a reviewable
6
+ folder. The `milofly` CLI (`@milofly/cli`) uses it.
7
+
8
+ ```
9
+ npm install @milofly/theme-sdk
10
+ ```
11
+
12
+ The rules (component keys, settings, offerings, store neutrality, languages, custom CSS) are enforced by the Milofly API with
13
+ the same validator that writes releases. Run `milofly theme check` to ask it.
14
+
15
+ ## Project layout
16
+
17
+ ```
18
+ theme/package.json packageKey, version, languages, catalog name/description per language
19
+ theme/theme.json category, thumbnailUrl, …
20
+ theme/pages/<page>.json one file per system page (components in order)
21
+ theme/layouts.json header, footer, popup
22
+ theme/settings/<key>.json theme settings (theme_config, badge_config, modal_config, …)
23
+ theme/offerings.json what the theme offers (surfaces)
24
+ ```
25
+
26
+ ```js
27
+ import { readThemeProject, writeThemeProject, checkManifestShape } from "@milofly/theme-sdk";
28
+
29
+ const manifest = await readThemeProject("."); // one manifest object
30
+ console.log(checkManifestShape(manifest)); // local type check only
31
+ await writeThemeProject(".", manifest); // stable JSON, one file per page/setting
32
+ ```
33
+
34
+ ## Component schema contract
35
+
36
+ `@milofly/theme-sdk/component-schema` exposes the validators Milofly runs on its own components' `schema.json`
37
+ (language coverage, schema fragments, dynamic field declarations). Uploading your own code components is not open yet.
38
+
39
+ Requires Node.js 20 or newer. No runtime dependencies.
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@milofly/theme-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Milofly theme package SDK: manifest types, project layout (read/write), shape check and component schema contract helpers.",
5
+ "license": "MIT",
6
+ "homepage": "https://developer.milofly.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Milofly/milofly-sdk.git",
10
+ "directory": "js/theme-sdk"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/Milofly/milofly-sdk/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "engines": {
18
+ "node": ">=20"
19
+ },
20
+ "exports": {
21
+ ".": {
22
+ "types": "./src/index.d.ts",
23
+ "default": "./src/index.js"
24
+ },
25
+ "./component-schema": {
26
+ "types": "./src/component-schema.d.ts",
27
+ "default": "./src/component-schema.js"
28
+ }
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ }
33
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Component schema (`schema.json`) contract validators — the same functions the Milofly platform runs on its own components
3
+ * (single source: the platform's component contract, `scripts/component-contracts.mjs`). Each returns a list of human-readable issues; empty = valid.
4
+ * Uploading your own code components is not open yet (developer platform G6).
5
+ */
6
+
7
+ export interface ComponentSchemaField {
8
+ key: string;
9
+ type: string;
10
+ label_key?: string;
11
+ setting_role?: string;
12
+ content_role?: string;
13
+ [extra: string]: unknown;
14
+ }
15
+
16
+ export interface ComponentSchema {
17
+ componentKey: string;
18
+ settingsSchema?: ComponentSchemaField[];
19
+ itemsSchema?: ComponentSchemaField[];
20
+ defaultSettings?: Record<string, unknown>;
21
+ defaultsByLang?: Record<string, { settings?: Record<string, unknown>; items?: unknown[] }>;
22
+ schemaLabels?: Record<string, Record<string, string>>;
23
+ translations?: { languageCode: string; [extra: string]: unknown }[];
24
+ [extra: string]: unknown;
25
+ }
26
+
27
+ export function defineComponentSchema<T extends ComponentSchema>(schema: T): T;
28
+
29
+ export function validateActiveLanguageCoverage(schema: ComponentSchema, activeLanguageCodes: string[], sourceName?: string): string[];
30
+ export function collectSchemaLabelReferences(schema: ComponentSchema): string[];
31
+ export function indexSchemaFragments(fragmentDocuments: [string, unknown][]): { byName: Map<string, unknown>; issues: string[] };
32
+ export function expandSchemaFragments(schema: ComponentSchema, fragmentsByName: Map<string, unknown>, sourceName?: string): { schema: ComponentSchema; issues: string[] };
33
+ export function validateSchemaFragments(schema: ComponentSchema, fragmentsByName: Map<string, unknown>, sourceName?: string): string[];
34
+ export function validateDynamicFieldDeclarations(
35
+ schema: ComponentSchema,
36
+ contract: unknown,
37
+ sourceName?: string,
38
+ options?: { yerelBeyanAcik?: boolean; canliBeyanAcik?: boolean; zenginMetinAcik?: boolean },
39
+ ): string[];
40
+
41
+ /** The dynamic field contract (token pattern, local namespace, text field types). */
42
+ export declare const dynamicFieldContract: Readonly<Record<string, unknown>>;
@@ -0,0 +1,29 @@
1
+ // @milofly/theme-sdk/component-schema — bileşen şema sözleşmesinin (schema.json) doğrulayıcıları.
2
+ //
3
+ // TEK KAYNAK: kuralların sahibi platformun bileşen sözleşmesidir (scripts/component-contracts.mjs; platformun kendi bileşenleri
4
+ // aynı fonksiyonlardan geçer). Burada kopya YOK: kaynakta o dosya doğrudan içe aktarılır; yayın paketinde paketle.mjs
5
+ // aynı dosyayı dist/vendor/ altına kopyalar ve bu içe aktarmayı oraya çevirir. Dinamik alan sözleşmesi de aynı yoldan gelir.
6
+ //
7
+ // Not: dış geliştiricinin KOD bileşeni yüklemesi henüz açık değil (geliştirici platformu G6). Bu doğrulayıcılar şemayı yerelde
8
+ // denetlemek ve platformun bileşen sözleşmesini öğrenmek içindir.
9
+ import { readFileSync } from "node:fs";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ export {
13
+ collectSchemaLabelReferences,
14
+ expandSchemaFragments,
15
+ indexSchemaFragments,
16
+ validateActiveLanguageCoverage,
17
+ validateDynamicFieldDeclarations,
18
+ validateSchemaFragments,
19
+ } from "../vendor/component-contracts.mjs";
20
+
21
+ const SOZLESME_YOLU = new URL("../vendor/dinamik-alan-sozlesmesi.json", import.meta.url);
22
+
23
+ /** Dinamik alan sözleşmesi (jeton deseni, yerel ad alanı, metin alan türleri) — `validateDynamicFieldDeclarations`'ın girdisi. */
24
+ export const dynamicFieldContract = Object.freeze(JSON.parse(readFileSync(fileURLToPath(SOZLESME_YOLU), "utf8")));
25
+
26
+ /** Yazım yardımcısı: şemayı olduğu gibi döner; editörde tip denetimi ve tamamlama içindir. */
27
+ export function defineComponentSchema(schema) {
28
+ return schema;
29
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,166 @@
1
+ /**
2
+ * @milofly/theme-sdk — types of the Milofly composition theme package (manifest v1) and helpers to keep a package as a
3
+ * reviewable directory. The authoritative rules (component keys, settings, offerings, neutrality, languages, custom CSS)
4
+ * live on the Milofly API; `milofly theme check` asks the API with the same validator the release writer uses.
5
+ *
6
+ * Field names mirror the API contract (`CompositionThemePackageManifestDto`, `ThemeExportDto`, `TemaSunumYazimIstegiDto`).
7
+ */
8
+
9
+ export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
10
+
11
+ export interface CatalogTranslation {
12
+ name: string;
13
+ description: string;
14
+ }
15
+
16
+ /** One component instance on a page. Text and language-bound links live in `defaultsByLang[lang]`. */
17
+ export interface ThemeComponent {
18
+ componentKey: string;
19
+ sortOrder: number;
20
+ defaultSettings?: { [key: string]: Json };
21
+ defaultItems?: Json[];
22
+ defaultsByLang?: { [language: string]: { settings?: { [key: string]: Json }; items?: Json[] } };
23
+ [extra: string]: unknown;
24
+ }
25
+
26
+ export interface ThemePage {
27
+ systemPageKey: string;
28
+ sortOrder: number;
29
+ components: ThemeComponent[];
30
+ [extra: string]: unknown;
31
+ }
32
+
33
+ export interface ThemeLayout {
34
+ layoutType: "header" | "footer" | "popup" | (string & {});
35
+ componentKey: string;
36
+ sortOrder: number;
37
+ defaultSettings?: { [key: string]: Json };
38
+ defaultItems?: Json[];
39
+ defaultsByLang?: { [language: string]: { settings?: { [key: string]: Json }; items?: Json[] } };
40
+ [extra: string]: unknown;
41
+ }
42
+
43
+ export interface ThemeSetting {
44
+ key: string;
45
+ value: Json;
46
+ [extra: string]: unknown;
47
+ }
48
+
49
+ export interface ThemeSnapshot {
50
+ code?: string;
51
+ catalogTranslations?: { [language: string]: CatalogTranslation };
52
+ category?: string | null;
53
+ thumbnailUrl?: string | null;
54
+ sortOrder?: number;
55
+ pages: ThemePage[];
56
+ layouts: ThemeLayout[];
57
+ settings: ThemeSetting[];
58
+ [extra: string]: unknown;
59
+ }
60
+
61
+ /** One offered part of a surface (`component`, `product_card_variant`, `modal_group`, `modal_variant`, `badge_*`, …). */
62
+ export interface OfferingItem {
63
+ key: string;
64
+ order?: number;
65
+ default?: boolean;
66
+ absent?: boolean;
67
+ group?: string;
68
+ [extra: string]: unknown;
69
+ }
70
+
71
+ export interface Offerings {
72
+ surfaces: { [surfaceKey: string]: OfferingItem[] };
73
+ [extra: string]: unknown;
74
+ }
75
+
76
+ /** Licence declaration of an asset (required). `url` (https) is required for every kind except `own`. */
77
+ export interface ThemeAssetLicense {
78
+ kind: "own" | "ofl-1.1" | "apache-2.0" | "mit" | "isc" | "cc0-1.0" | "cc-by-4.0" | "commercial";
79
+ holder: string;
80
+ url?: string;
81
+ }
82
+
83
+ /**
84
+ * One file the package carries. Icons: `icons/<name>.svg|png`, referenced from content as `paket:<path>` (an icon field or
85
+ * `theme_config.icons.glyphs.*`). Fonts: `fonts/<name>.woff2`, one file per face; the theme uses the `family` name.
86
+ * `sha256` is computed by `readThemeProject` from the file under `theme/assets/`.
87
+ */
88
+ export interface ThemeAsset {
89
+ path: string;
90
+ kind: "icon" | "font";
91
+ sha256: string;
92
+ family?: string;
93
+ weight?: number;
94
+ style?: "normal" | "italic";
95
+ /** Icon only: follows the icon color of where it sits (single-color SVG up to 16 KB). */
96
+ tint?: boolean;
97
+ license: ThemeAssetLicense;
98
+ }
99
+
100
+ export interface ThemePackageManifest {
101
+ schemaVersion: 1;
102
+ /** `{publisher}/{name}` — the publisher segment is your developer publisher key. */
103
+ packageKey: string;
104
+ /** SemVer; the same version can never be written twice with different content. */
105
+ version: string;
106
+ mode: "composition";
107
+ localizationMode: "milofly-db";
108
+ defaultLanguageCode: string;
109
+ supportedLanguageCodes: string[];
110
+ catalogTranslations: { [language: string]: CatalogTranslation };
111
+ theme: ThemeSnapshot;
112
+ offerings: Offerings;
113
+ /** The package's own icons and fonts (optional). */
114
+ assets?: { files: ThemeAsset[] };
115
+ [extra: string]: unknown;
116
+ }
117
+
118
+ /** One finding. `code` is a Milofly code (`theme_package.*`, `THEME_*`) or, for the local shape check, `local.*`. */
119
+ export interface ThemeIssue {
120
+ code: string;
121
+ path: string;
122
+ detail: string;
123
+ }
124
+
125
+ /** Answer of `POST /api/dev/theme-packages/validate`. */
126
+ export interface ThemeCheckReport {
127
+ valid: boolean;
128
+ /** Blocks writing a release. */
129
+ release: ThemeIssue[];
130
+ /** The release can be written but no store can install it. */
131
+ install: ThemeIssue[];
132
+ /** Blocks opening the package to all stores (offer, review approval): neutrality + languages. */
133
+ publish: ThemeIssue[];
134
+ }
135
+
136
+ /** Local shape check (types only). Rules are checked by the API. */
137
+ export function checkManifestShape(manifest: unknown): ThemeIssue[];
138
+
139
+ /** Directory layout of a theme project. */
140
+ export declare const PROJECT_LAYOUT: Readonly<{
141
+ root: "theme";
142
+ package: "theme/package.json";
143
+ theme: "theme/theme.json";
144
+ pages: "theme/pages";
145
+ layouts: "theme/layouts.json";
146
+ settings: "theme/settings";
147
+ offerings: "theme/offerings.json";
148
+ assets: "theme/assets.json";
149
+ assetFiles: "theme/assets";
150
+ }>;
151
+
152
+ /** Reads `theme/assets.json` and hashes every file under `theme/assets/`. `null` when the package has no assets. */
153
+ export function readThemeAssets(projectDir: string): Promise<{ files: ThemeAsset[] } | null>;
154
+
155
+ /** Absolute path of an asset file inside `theme/assets/`. */
156
+ export function assetFilePath(projectDir: string, assetPath: string): string;
157
+
158
+ /** Writes a manifest as a directory (one file per page and per setting; stable JSON). Existing page/setting files that are no
159
+ * longer in the manifest are removed. Returns the written paths (relative to `projectDir`). */
160
+ export function writeThemeProject(projectDir: string, manifest: ThemePackageManifest): Promise<string[]>;
161
+
162
+ /** Reads a theme directory back into one manifest. Throws with the file name when a file is missing or not JSON. */
163
+ export function readThemeProject(projectDir: string): Promise<ThemePackageManifest>;
164
+
165
+ /** Canonical JSON (sorted keys, no whitespace): the same input always gives the same bytes. Useful for diffs and caching. */
166
+ export function canonicalJson(value: unknown): string;
package/src/index.js ADDED
@@ -0,0 +1,223 @@
1
+ // @milofly/theme-sdk — çalışma zamanı. Tipler: index.d.ts. Sıfır bağımlılık (node:fs, node:path).
2
+ //
3
+ // Bu paket kural KOYMAZ: bileşen anahtarı, ayar, sunum, tarafsızlık, dil ve özel CSS kurallarının tek sahibi Milofly API'sidir
4
+ // (sürüm yazıcısı ve kurulumla aynı doğrulayıcı; CLI `theme check` onu çağırır). Burada yalnız iki iş var:
5
+ // 1. manifesti incelenebilir bir klasör olarak yazıp geri okumak (sayfa ve ayar başına bir dosya, kararlı JSON);
6
+ // 2. tip düzeyinde biçim denetimi (sunucuya göndermeden önce bozuk JSON'u yakalar; kural denetimi değildir).
7
+ import { createHash } from "node:crypto";
8
+ import { existsSync } from "node:fs";
9
+ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+
12
+ export const PROJECT_LAYOUT = Object.freeze({
13
+ root: "theme",
14
+ package: "theme/package.json",
15
+ theme: "theme/theme.json",
16
+ pages: "theme/pages",
17
+ layouts: "theme/layouts.json",
18
+ settings: "theme/settings",
19
+ offerings: "theme/offerings.json",
20
+ /** The package's own icons and fonts: the list (path, kind, font face or icon tint, licence) — optional. */
21
+ assets: "theme/assets.json",
22
+ /** The files themselves: theme/assets/icons/<name>.svg|png, theme/assets/fonts/<name>.woff2. */
23
+ assetFiles: "theme/assets",
24
+ });
25
+
26
+ const DOSYA_ADI = /^[A-Za-z0-9._-]+$/;
27
+
28
+ function nesneMi(v) {
29
+ return v !== null && typeof v === "object" && !Array.isArray(v);
30
+ }
31
+
32
+ function yaz(dosya, deger) {
33
+ return writeFile(dosya, JSON.stringify(deger, null, 2) + "\n", "utf8");
34
+ }
35
+
36
+ async function oku(dosya) {
37
+ let metin;
38
+ try {
39
+ metin = await readFile(dosya, "utf8");
40
+ } catch (hata) {
41
+ throw new Error(`${dosya}: ${hata.code === "ENOENT" ? "missing" : hata.message}`);
42
+ }
43
+ try {
44
+ return JSON.parse(metin);
45
+ } catch (hata) {
46
+ throw new Error(`${dosya}: invalid JSON (${hata.message})`);
47
+ }
48
+ }
49
+
50
+ function dosyaAdi(anahtar, ne) {
51
+ if (typeof anahtar !== "string" || !DOSYA_ADI.test(anahtar))
52
+ throw new Error(`${ne} key "${anahtar}" cannot be used as a file name (allowed: letters, digits, . _ -).`);
53
+ return `${anahtar}.json`;
54
+ }
55
+
56
+ /** @param {string} kok @param {any} manifest */
57
+ export async function writeThemeProject(kok, manifest) {
58
+ const sorunlar = checkManifestShape(manifest);
59
+ if (sorunlar.length > 0)
60
+ throw new Error(`Manifest shape is invalid:\n${sorunlar.map((s) => ` ${s.path}: ${s.detail}`).join("\n")}`);
61
+
62
+ // Varlık listesi (assets) yerelde yaşar: dosyalar klasördedir, sunucu onları geri vermez. Çekilen manifest yerel listeyi ezmez.
63
+ const { theme, offerings, assets: _assets, ...paket } = manifest;
64
+ const { pages, layouts, settings, ...tema } = theme;
65
+ const yazilan = [];
66
+ const yol = (goreli) => {
67
+ yazilan.push(goreli);
68
+ return join(kok, goreli);
69
+ };
70
+
71
+ await mkdir(join(kok, PROJECT_LAYOUT.pages), { recursive: true });
72
+ await mkdir(join(kok, PROJECT_LAYOUT.settings), { recursive: true });
73
+ await yaz(yol(PROJECT_LAYOUT.package), paket);
74
+ await yaz(yol(PROJECT_LAYOUT.theme), tema);
75
+ await yaz(yol(PROJECT_LAYOUT.layouts), layouts);
76
+ await yaz(yol(PROJECT_LAYOUT.offerings), offerings);
77
+
78
+ const sayfaDosyalari = new Set();
79
+ for (const sayfa of pages) {
80
+ const ad = dosyaAdi(sayfa.systemPageKey, "Page");
81
+ if (sayfaDosyalari.has(ad)) throw new Error(`Page "${sayfa.systemPageKey}" appears twice in the manifest.`);
82
+ sayfaDosyalari.add(ad);
83
+ await yaz(yol(`${PROJECT_LAYOUT.pages}/${ad}`), sayfa);
84
+ }
85
+ const ayarDosyalari = new Set();
86
+ for (const ayar of settings) {
87
+ const ad = dosyaAdi(ayar.key, "Setting");
88
+ if (ayarDosyalari.has(ad)) throw new Error(`Setting "${ayar.key}" appears twice in the manifest.`);
89
+ ayarDosyalari.add(ad);
90
+ await yaz(yol(`${PROJECT_LAYOUT.settings}/${ad}`), ayar);
91
+ }
92
+ // Manifestte artık olmayan sayfa/ayar dosyası kalırsa geri okumada pakete geri girerdi: silinir.
93
+ for (const [klasor, tutulan] of [[PROJECT_LAYOUT.pages, sayfaDosyalari], [PROJECT_LAYOUT.settings, ayarDosyalari]])
94
+ for (const ad of await readdir(join(kok, klasor)))
95
+ if (ad.endsWith(".json") && !tutulan.has(ad)) await rm(join(kok, klasor, ad));
96
+ return yazilan;
97
+ }
98
+
99
+ /** @param {string} kok */
100
+ export async function readThemeProject(kok) {
101
+ const paket = await oku(join(kok, PROJECT_LAYOUT.package));
102
+ const tema = await oku(join(kok, PROJECT_LAYOUT.theme));
103
+ const layouts = await oku(join(kok, PROJECT_LAYOUT.layouts));
104
+ const offerings = await oku(join(kok, PROJECT_LAYOUT.offerings));
105
+
106
+ const pages = [];
107
+ for (const ad of (await readdir(join(kok, PROJECT_LAYOUT.pages))).filter((a) => a.endsWith(".json")).sort())
108
+ pages.push(await oku(join(kok, PROJECT_LAYOUT.pages, ad)));
109
+ // Sayfa sırası sayfanın kendi sortOrder'ıdır; eşitlikte anahtar (kararlı).
110
+ pages.sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0) || String(a.systemPageKey).localeCompare(String(b.systemPageKey)));
111
+
112
+ const settings = [];
113
+ for (const ad of (await readdir(join(kok, PROJECT_LAYOUT.settings))).filter((a) => a.endsWith(".json")).sort())
114
+ settings.push(await oku(join(kok, PROJECT_LAYOUT.settings, ad)));
115
+
116
+ const manifest = { ...paket, theme: { ...tema, pages, layouts, settings }, offerings };
117
+ const varliklar = await readThemeAssets(kok);
118
+ if (varliklar) manifest.assets = varliklar;
119
+ const sorunlar = checkManifestShape(manifest);
120
+ if (sorunlar.length > 0)
121
+ throw new Error(`Theme project shape is invalid:\n${sorunlar.map((s) => ` ${s.path}: ${s.detail}`).join("\n")}`);
122
+ return manifest;
123
+ }
124
+
125
+ /**
126
+ * The package's own icons and fonts: `theme/assets.json` (optional) + the files under `theme/assets/`. Every entry gets the SHA-256
127
+ * of its file (the API matches the uploaded file by this digest). Returns `null` when the package has no assets.
128
+ * @param {string} kok
129
+ */
130
+ export async function readThemeAssets(kok) {
131
+ const liste = join(kok, PROJECT_LAYOUT.assets);
132
+ if (!existsSync(liste)) return null;
133
+ const ham = await oku(liste);
134
+ if (!nesneMi(ham) || !Array.isArray(ham.files)) throw new Error(`${liste}: must be { "files": [ ... ] }`);
135
+ const files = [];
136
+ for (const [i, f] of ham.files.entries()) {
137
+ if (!nesneMi(f) || typeof f.path !== "string") throw new Error(`${liste}: files[${i}].path must be a string`);
138
+ const dosya = assetFilePath(kok, f.path);
139
+ let icerik;
140
+ try {
141
+ icerik = await readFile(dosya);
142
+ } catch (hata) {
143
+ throw new Error(`${dosya}: ${hata.code === "ENOENT" ? "missing" : hata.message}`);
144
+ }
145
+ const { sha256: _yazilan, ...kalan } = f;
146
+ files.push({ ...kalan, sha256: createHash("sha256").update(icerik).digest("hex") });
147
+ }
148
+ return { files };
149
+ }
150
+
151
+ /** Absolute path of an asset file (`icons/cart.svg` -> `<project>/theme/assets/icons/cart.svg`). Rejects paths leaving the folder.
152
+ * @param {string} kok @param {string} yol */
153
+ export function assetFilePath(kok, yol) {
154
+ if (typeof yol !== "string" || yol.includes("..") || yol.startsWith("/") || yol.includes("\\"))
155
+ throw new Error(`Asset path "${yol}" must be relative (icons/<name> or fonts/<name>).`);
156
+ return join(kok, PROJECT_LAYOUT.assetFiles, ...yol.split("/"));
157
+ }
158
+
159
+ /** @param {unknown} m */
160
+ export function checkManifestShape(m) {
161
+ const s = [];
162
+ const ekle = (path, detail) => s.push({ code: "local.shape", path, detail });
163
+ if (!nesneMi(m)) {
164
+ ekle("", "manifest must be a JSON object");
165
+ return s;
166
+ }
167
+ for (const alan of ["packageKey", "version", "mode", "localizationMode", "defaultLanguageCode"])
168
+ if (typeof m[alan] !== "string") ekle(alan, "must be a string");
169
+ if (typeof m.schemaVersion !== "number") ekle("schemaVersion", "must be a number");
170
+ if (!Array.isArray(m.supportedLanguageCodes) || m.supportedLanguageCodes.some((d) => typeof d !== "string"))
171
+ ekle("supportedLanguageCodes", "must be an array of language codes");
172
+ if (!nesneMi(m.catalogTranslations)) ekle("catalogTranslations", "must be an object keyed by language");
173
+ if (!nesneMi(m.offerings) || !nesneMi(m.offerings.surfaces)) ekle("offerings.surfaces", "must be an object keyed by surface");
174
+ else
175
+ for (const [yuzey, ogeler] of Object.entries(m.offerings.surfaces))
176
+ if (!Array.isArray(ogeler)) ekle(`offerings.surfaces.${yuzey}`, "must be an array");
177
+ const t = m.theme;
178
+ if (!nesneMi(t)) {
179
+ ekle("theme", "must be an object");
180
+ return s;
181
+ }
182
+ for (const [alan, ne] of [["pages", "page"], ["layouts", "layout"], ["settings", "setting"]])
183
+ if (!Array.isArray(t[alan])) ekle(`theme.${alan}`, `must be an array of ${ne}s`);
184
+ (Array.isArray(t.pages) ? t.pages : []).forEach((p, i) => {
185
+ if (!nesneMi(p)) return ekle(`theme.pages[${i}]`, "must be an object");
186
+ if (typeof p.systemPageKey !== "string") ekle(`theme.pages[${i}].systemPageKey`, "must be a string");
187
+ if (!Array.isArray(p.components)) ekle(`theme.pages[${i}].components`, "must be an array");
188
+ else
189
+ p.components.forEach((c, j) => {
190
+ if (!nesneMi(c) || typeof c.componentKey !== "string")
191
+ ekle(`theme.pages[${i}].components[${j}].componentKey`, "must be a string");
192
+ });
193
+ });
194
+ (Array.isArray(t.layouts) ? t.layouts : []).forEach((l, i) => {
195
+ if (!nesneMi(l) || typeof l.componentKey !== "string" || typeof l.layoutType !== "string")
196
+ ekle(`theme.layouts[${i}]`, "needs layoutType and componentKey strings");
197
+ });
198
+ (Array.isArray(t.settings) ? t.settings : []).forEach((a, i) => {
199
+ if (!nesneMi(a) || typeof a.key !== "string") ekle(`theme.settings[${i}].key`, "must be a string");
200
+ });
201
+ if (m.assets !== undefined) {
202
+ if (!nesneMi(m.assets) || !Array.isArray(m.assets.files)) ekle("assets.files", "must be an array");
203
+ else
204
+ m.assets.files.forEach((f, i) => {
205
+ if (!nesneMi(f)) return ekle(`assets.files[${i}]`, "must be an object");
206
+ for (const alan of ["path", "kind", "sha256"]) if (typeof f[alan] !== "string") ekle(`assets.files[${i}].${alan}`, "must be a string");
207
+ if (!nesneMi(f.license)) ekle(`assets.files[${i}].license`, "every file declares its licence { kind, holder, url }");
208
+ });
209
+ }
210
+ return s;
211
+ }
212
+
213
+ /** @param {unknown} deger */
214
+ export function canonicalJson(deger) {
215
+ if (Array.isArray(deger)) return `[${deger.map(canonicalJson).join(",")}]`;
216
+ if (nesneMi(deger))
217
+ return `{${Object.keys(deger)
218
+ .filter((k) => deger[k] !== undefined)
219
+ .sort()
220
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(deger[k])}`)
221
+ .join(",")}}`;
222
+ return JSON.stringify(deger);
223
+ }