iagenify 0.4.1 → 0.4.2

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/dist/index.js CHANGED
@@ -522,11 +522,15 @@ function createHttpClient({ baseUrl, sessionManager, appName = "", timeout = DEF
522
522
  async function request(method, path, body, opts = {}) {
523
523
  const url = `${baseUrl}${path}`;
524
524
  const isFormData = typeof FormData !== "undefined" && body instanceof FormData;
525
+ const isBinary = body instanceof Uint8Array;
525
526
  const headers = {
526
527
  "X-IaGenify-Version": SDK_VERSION,
527
- ...appName ? { "X-IaGenify-App-Name": appName } : {}
528
+ ...appName ? { "X-IaGenify-App-Name": appName } : {},
529
+ ...opts.headers || {}
528
530
  };
529
- if (!isFormData) {
531
+ if (isBinary) {
532
+ headers["Content-Type"] = "application/octet-stream";
533
+ } else if (!isFormData) {
530
534
  headers["Content-Type"] = "application/json";
531
535
  }
532
536
  if (opts.skipAuth !== true) {
@@ -546,7 +550,7 @@ function createHttpClient({ baseUrl, sessionManager, appName = "", timeout = DEF
546
550
  const res = await doFetch(url, {
547
551
  method,
548
552
  headers,
549
- body: body !== void 0 ? isFormData ? body : JSON.stringify(body) : void 0
553
+ body: body !== void 0 ? isFormData || isBinary ? body : JSON.stringify(body) : void 0
550
554
  }, { timeout: opts.timeout ?? timeout, signal: opts.signal });
551
555
  const text2 = await res.text();
552
556
  let data;
@@ -1661,10 +1665,10 @@ function cloudUsageLine(storage, usage) {
1661
1665
  const u = usage?.[storage?.service];
1662
1666
  if (!u) return "";
1663
1667
  const mine = storage.limits?.usedBytes || 0;
1664
- const base = (u.storages || []).find((b) => String(b.id) === String(storage.id));
1665
- const plafond = base ? base.quotaBytes : u.perBaseBytes;
1668
+ const base2 = (u.storages || []).find((b) => String(b.id) === String(storage.id));
1669
+ const plafond = base2 ? base2.quotaBytes : u.perBaseBytes;
1666
1670
  const plan = `(${PLAN_NAMES[usage.pack] || usage.pack} plan)`;
1667
- const plein = base?.overQuota || !base && u.overQuota;
1671
+ const plein = base2?.overQuota || !base2 && u.overQuota;
1668
1672
  if (plafond == null) {
1669
1673
  return `${formatBytes(mine)} used, ${SERVICE_NAMES[storage.service]} space ${formatBytes(u.usedBytes)} of ${formatBytes(u.quotaBytes)} ${plan}${u.overQuota ? " \u2014 FULL: writes are refused" : ""}`;
1670
1674
  }
@@ -4838,8 +4842,8 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
4838
4842
  if (!result?.ok) fail5(result?.message || `Conversion ${from} \u2192 ${target} failed.`);
4839
4843
  const data = result.content !== void 0 ? String(result.content) : Buffer.from(result.base64 || "", "base64");
4840
4844
  const ext = EXT_FOR[target] || target;
4841
- const base = sourceName.replace(/\.[^.]+$/, "");
4842
- const destination = filled2(save) ? String(save) : filled2(path) ? `${base}.${ext}` : `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${base}.${ext}`;
4845
+ const base2 = sourceName.replace(/\.[^.]+$/, "");
4846
+ const destination = filled2(save) ? String(save) : filled2(path) ? `${base2}.${ext}` : `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${base2}.${ext}`;
4843
4847
  const written = await files.write(destination, data);
4844
4848
  return {
4845
4849
  output: `Converted ${sourceName} (${from} \u2192 ${target}) to ${written.path} \u2014 ${Math.round(written.size / 1024)} KB, ${result.creditsUsed ?? 1} credit.`,
@@ -5259,8 +5263,8 @@ function storageIndex(storages = []) {
5259
5263
  const byProvider = /* @__PURE__ */ new Map();
5260
5264
  for (const s of storages) {
5261
5265
  if (!s) continue;
5262
- const slug = storageSlug(s.label || s.name);
5263
- if (slug) index.set(slug, s);
5266
+ const slug2 = storageSlug(s.label || s.name);
5267
+ if (slug2) index.set(slug2, s);
5264
5268
  if (s.provider) byProvider.set(s.provider, [...byProvider.get(s.provider) || [], s]);
5265
5269
  }
5266
5270
  for (const [provider, list] of byProvider) if (list.length === 1 && !index.has(provider)) index.set(provider, list[0]);
@@ -5428,10 +5432,10 @@ var LocalLibrary = class {
5428
5432
  throw fail7(409, "storage_not_on_this_machine", `\xAB ${this.storage.label} \xBB belongs to another computer: its ${this.kind} stay there.`);
5429
5433
  }
5430
5434
  const { fs, path, os } = await node3();
5431
- const base = this.root || path.join(os.homedir(), ".iagenify");
5432
- const dir = path.join(base, this.spec.folder);
5435
+ const base2 = this.root || path.join(os.homedir(), ".iagenify");
5436
+ const dir = path.join(base2, this.spec.folder);
5433
5437
  await fs.mkdir(dir, { recursive: true, mode: 448 });
5434
- return { fs, path, base, dir };
5438
+ return { fs, path, base: base2, dir };
5435
5439
  }
5436
5440
  _file(path, dir, name) {
5437
5441
  return this.kind === "skills" ? path.join(dir, name, "SKILL.md") : path.join(dir, `${name}.md`);
@@ -5444,9 +5448,9 @@ var LocalLibrary = class {
5444
5448
  /** Un élément lu sur disque : { name, description, …, content, builtIn: false }. */
5445
5449
  _fromFile(name, text2, extra = {}) {
5446
5450
  const { data, body } = parseFrontmatter(text2);
5447
- const base = { name, description: String(data.description || "").trim(), builtIn: false };
5448
- if (this.kind === "subagents") Object.assign(base, { tools: normalizeTools(data.tools), model: normalizeModel(data.model) });
5449
- return { ...base, ...extra, content: body };
5451
+ const base2 = { name, description: String(data.description || "").trim(), builtIn: false };
5452
+ if (this.kind === "subagents") Object.assign(base2, { tools: normalizeTools(data.tools), model: normalizeModel(data.model) });
5453
+ return { ...base2, ...extra, content: body };
5450
5454
  }
5451
5455
  _builtIn(name) {
5452
5456
  const item = this.spec.builtIns[name];
@@ -5526,14 +5530,14 @@ var LocalLibrary = class {
5526
5530
  async remove(name) {
5527
5531
  this._checkName(name);
5528
5532
  if (this.spec.builtIns[name]) throw fail7(400, "builtin_item", `"${name}" is built in and cannot be removed.`);
5529
- const { fs, path, base, dir } = await this._ready();
5533
+ const { fs, path, base: base2, dir } = await this._ready();
5530
5534
  const source = this.kind === "skills" ? path.join(dir, name) : this._file(path, dir, name);
5531
5535
  try {
5532
5536
  await fs.access(source);
5533
5537
  } catch {
5534
5538
  throw fail7(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
5535
5539
  }
5536
- const target = path.join(base, ".trash", (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-"), this.spec.folder, path.basename(source));
5540
+ const target = path.join(base2, ".trash", (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-"), this.spec.folder, path.basename(source));
5537
5541
  await fs.mkdir(path.dirname(target), { recursive: true });
5538
5542
  await fs.rename(source, target);
5539
5543
  return { ok: true };
@@ -8839,10 +8843,16 @@ var Host = class {
8839
8843
  if (files !== void 0) throw new IaGenifyError(400, "invalid_deploy", "An edge host deploys code, not a folder.");
8840
8844
  if (typeof code !== "string" || !code.trim()) throw new IaGenifyError(400, "nothing_to_deploy", "An edge host needs a code module.");
8841
8845
  }
8842
- const body = {};
8843
- if (code !== void 0) body.code = code;
8844
- if (files !== void 0) body.files = await readFiles(files);
8845
- if (this.runtime === "node" && server !== void 0) body.server = server;
8846
+ const withServer = this.runtime === "node" && server !== void 0;
8847
+ if (files !== void 0 && code !== void 0) throw new IaGenifyError(400, "invalid_deploy", "Pass files or code, not both.");
8848
+ if (files === void 0) {
8849
+ return (await this.client.post(`/api/hosting/${this.id}/deploy`, { code, ...withServer ? { server } : {} })).deploy;
8850
+ }
8851
+ const entries = await collectFiles(files);
8852
+ const total = entries.reduce((sum, file) => sum + file.size, 0);
8853
+ if (total > DIRECT_UPLOAD_ABOVE) return deployDirect(this.client, this.id, entries, withServer ? server : void 0);
8854
+ const body = { files: await Promise.all(entries.map(async (file) => ({ path: file.path, content: toBase64(await file.load()) }))) };
8855
+ if (withServer) body.server = server;
8846
8856
  return (await this.client.post(`/api/hosting/${this.id}/deploy`, body)).deploy;
8847
8857
  }
8848
8858
  async update({ label } = {}) {
@@ -8863,14 +8873,18 @@ var Host = class {
8863
8873
  return this.client.delete(`/api/hosting/${this.id}`);
8864
8874
  }
8865
8875
  };
8866
- async function readFiles(input) {
8876
+ var DIRECT_UPLOAD_ABOVE = 8 * 1024 * 1024;
8877
+ var PACKS_IN_FLIGHT = 3;
8878
+ var PACK_TIMEOUT_MS = 5 * 60 * 1e3;
8879
+ var FINISH_TIMEOUT_MS = 10 * 60 * 1e3;
8880
+ async function collectFiles(input) {
8867
8881
  if (Array.isArray(input)) {
8868
8882
  const files = input.map((file) => {
8869
8883
  const path2 = String(file?.path ?? "").replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "");
8870
8884
  if (!path2) throw new IaGenifyError(400, "nothing_to_deploy", "Every file needs a path.");
8871
8885
  if (NEVER_DEPLOY2.some((rule) => rule.test(path2))) return null;
8872
8886
  const bytes = typeof file?.content === "string" ? new TextEncoder().encode(file.content) : new Uint8Array(file?.content ?? []);
8873
- return { path: path2, content: toBase64(bytes) };
8887
+ return { path: path2, size: bytes.length, load: async () => bytes };
8874
8888
  }).filter(Boolean);
8875
8889
  if (!files.length) throw new IaGenifyError(400, "nothing_to_deploy", "No deployable files were provided.");
8876
8890
  return files;
@@ -8892,7 +8906,10 @@ async function readFiles(input) {
8892
8906
  const relative = path.relative(root, full).split(path.sep).join("/");
8893
8907
  if (NEVER_DEPLOY2.some((rule) => rule.test(relative))) continue;
8894
8908
  if (entry.isDirectory()) await visit(full);
8895
- else if (entry.isFile()) result.push({ path: relative, content: (await fs.readFile(full)).toString("base64") });
8909
+ else if (entry.isFile()) {
8910
+ const { size } = await fs.stat(full);
8911
+ result.push({ path: relative, size, load: async () => new Uint8Array(await fs.readFile(full)) });
8912
+ }
8896
8913
  }
8897
8914
  };
8898
8915
  try {
@@ -8904,6 +8921,80 @@ async function readFiles(input) {
8904
8921
  if (!result.length) throw new IaGenifyError(400, "nothing_to_deploy", `The folder "${input}" contains no deployable files.`);
8905
8922
  return result;
8906
8923
  }
8924
+ async function hashBytes(bytes) {
8925
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", bytes));
8926
+ let hex = "";
8927
+ for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
8928
+ return hex.slice(0, 32);
8929
+ }
8930
+ function planPacks(hashes, sizeOf, { maxBytes, maxFiles }) {
8931
+ const packs = [];
8932
+ let current = [];
8933
+ let bytes = 0;
8934
+ for (const hash of hashes) {
8935
+ const size = sizeOf(hash);
8936
+ if (current.length && (bytes + size > maxBytes || current.length >= maxFiles)) {
8937
+ packs.push(current);
8938
+ current = [];
8939
+ bytes = 0;
8940
+ }
8941
+ current.push(hash);
8942
+ bytes += size;
8943
+ }
8944
+ if (current.length) packs.push(current);
8945
+ return packs;
8946
+ }
8947
+ async function deployDirect(client, hostId, entries, server) {
8948
+ const base2 = `/api/hosting/${hostId}/uploads`;
8949
+ const byHash = /* @__PURE__ */ new Map();
8950
+ const manifest = [];
8951
+ for (const entry of entries) {
8952
+ const hash = await hashBytes(await entry.load());
8953
+ manifest.push({ path: entry.path, size: entry.size, hash });
8954
+ if (!byHash.has(hash)) byHash.set(hash, entry);
8955
+ }
8956
+ const { upload } = await client.post(base2, { files: manifest, ...server !== void 0 ? { server } : {} });
8957
+ const send = async (missing2) => {
8958
+ const packs = planPacks(
8959
+ missing2.filter((hash) => byHash.has(hash)),
8960
+ (hash) => byHash.get(hash).size,
8961
+ { maxBytes: upload.packBytes, maxFiles: upload.packFiles }
8962
+ );
8963
+ let next = 0;
8964
+ const worker = async () => {
8965
+ while (next < packs.length) {
8966
+ const pack = packs[next++];
8967
+ const parts = await Promise.all(pack.map((hash) => byHash.get(hash).load()));
8968
+ const body = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
8969
+ let offset = 0;
8970
+ for (const part of parts) {
8971
+ body.set(part, offset);
8972
+ offset += part.length;
8973
+ }
8974
+ const header = pack.map((hash) => `${hash}:${byHash.get(hash).size}`).join(",");
8975
+ for (let attempt = 1; ; attempt++) {
8976
+ try {
8977
+ await client.put(`${base2}/${upload.id}/parts`, body, { headers: { "X-IaGenify-Parts": header }, timeout: PACK_TIMEOUT_MS });
8978
+ break;
8979
+ } catch (error) {
8980
+ const transient = !error?.status || error.status >= 500 || error.status === 429;
8981
+ if (!transient || attempt >= 3) throw error;
8982
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * attempt));
8983
+ }
8984
+ }
8985
+ }
8986
+ };
8987
+ await Promise.all(Array.from({ length: Math.min(PACKS_IN_FLIGHT, packs.length) }, worker));
8988
+ };
8989
+ await send(upload.missing || []);
8990
+ try {
8991
+ return (await client.post(`${base2}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
8992
+ } catch (error) {
8993
+ if (error?.code !== "upload_incomplete" || !Array.isArray(error.details?.missing)) throw error;
8994
+ await send(error.details.missing);
8995
+ return (await client.post(`${base2}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
8996
+ }
8997
+ }
8907
8998
  function toBase64(bytes) {
8908
8999
  if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
8909
9000
  let binary = "";
@@ -8915,10 +9006,10 @@ var HostsResource = class {
8915
9006
  this.client = client;
8916
9007
  }
8917
9008
  /** `runtime` is the public contract. `kind` remains accepted for one upgrade cycle. */
8918
- async create({ runtime, framework, label, slug, kind } = {}) {
9009
+ async create({ runtime, framework, label, slug: slug2, kind } = {}) {
8919
9010
  const rule = assertRuntime(runtime || LEGACY_RUNTIME[kind], framework);
8920
9011
  const resolvedRuntime = runtime || LEGACY_RUNTIME[kind];
8921
- const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug });
9012
+ const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug: slug2 });
8922
9013
  return new Host(this.client, res.host, { framework });
8923
9014
  }
8924
9015
  async list() {
@@ -9312,8 +9403,8 @@ var Contacts = class {
9312
9403
  /** `avatar` est rendu absolu ici : l'API rend un chemin, elle ignore sous quel nom on l'atteint. */
9313
9404
  _absolu(contact) {
9314
9405
  if (!contact) return contact;
9315
- const base = typeof this.client?.baseUrl === "string" ? this.client.baseUrl : "";
9316
- return contact.avatar?.startsWith("/") && base ? { ...contact, avatar: `${base}${contact.avatar}` } : contact;
9406
+ const base2 = typeof this.client?.baseUrl === "string" ? this.client.baseUrl : "";
9407
+ return contact.avatar?.startsWith("/") && base2 ? { ...contact, avatar: `${base2}${contact.avatar}` } : contact;
9317
9408
  }
9318
9409
  async list() {
9319
9410
  const res = await this.client.get("/api/mail/contacts");
@@ -9404,6 +9495,952 @@ var MailResource = class {
9404
9495
  }
9405
9496
  };
9406
9497
 
9498
+ // src/studio/errors.js
9499
+ var StudioError = class extends Error {
9500
+ constructor(code, message, details = void 0, status = 400) {
9501
+ super(message);
9502
+ this.name = "StudioError";
9503
+ this.status = status;
9504
+ this.code = code;
9505
+ if (details !== void 0) this.details = details;
9506
+ }
9507
+ };
9508
+
9509
+ // src/studio/format.js
9510
+ var FORMAT = "iagenify.design";
9511
+ var FORMAT_VERSION = 1;
9512
+ var NODE_TYPES = ["frame", "text", "image", "shape"];
9513
+ var CONTENEURS = /* @__PURE__ */ new Set(["frame"]);
9514
+ var TAGS = {
9515
+ frame: ["div", "section", "header", "footer", "nav", "main", "article", "aside", "figure", "ul", "li", "a", "button"],
9516
+ text: ["p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "a", "button", "li", "small", "strong", "em", "label"],
9517
+ image: ["img"],
9518
+ shape: ["div"]
9519
+ };
9520
+ var DEFAULT_TAG = { frame: "div", text: "p", image: "img", shape: "div" };
9521
+ var CHAMPS_NOEUD = /* @__PURE__ */ new Set(["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"]);
9522
+ var CHAMPS = {
9523
+ layout: { mode: ["flex", "grid", "free"], direction: ["row", "column"], gap: "longueur", padding: "padding", align: ["start", "center", "end", "stretch"], justify: ["start", "center", "end", "between"], wrap: "booleen", columns: "entier" },
9524
+ size: { w: "dimension", h: "dimension", minW: "longueur", minH: "longueur", maxW: "longueur", maxH: "longueur" },
9525
+ position: { x: "nombre", y: "nombre", absolute: "booleen" },
9526
+ style: { fill: "remplissage", stroke: "trait", radius: "rayon", shadow: "ombres", opacity: "opacite", clip: "booleen" },
9527
+ text: { content: "texte", font: "police", size: "longueur", weight: "graisse", lineHeight: "interligne", align: ["left", "center", "right", "justify"], color: "couleur", letterSpacing: "nombre", transform: ["none", "uppercase", "lowercase", "capitalize"] },
9528
+ image: { src: "source", fit: ["cover", "contain", "fill"] },
9529
+ shape: { kind: ["rect", "ellipse", "line"] }
9530
+ };
9531
+ var COULEUR = /^(#[0-9a-f]{3}|#[0-9a-f]{4}|#[0-9a-f]{6}|#[0-9a-f]{8}|transparent|rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,\s*(0|1|0?\.\d+)\s*)?\))$/i;
9532
+ var POLICE = /^[A-Za-z0-9 \-]{1,64}$/;
9533
+ var SOURCE = /^asset:[A-Za-z0-9_\-]{1,64}$/;
9534
+ var fini = (v) => typeof v === "number" && Number.isFinite(v);
9535
+ function isColor(v) {
9536
+ return typeof v === "string" && COULEUR.test(v.trim());
9537
+ }
9538
+ function verifierValeur(regle, v) {
9539
+ if (Array.isArray(regle)) return regle.includes(v) ? null : `valeur_non_permise (${regle.join(", ")})`;
9540
+ switch (regle) {
9541
+ case "booleen":
9542
+ return typeof v === "boolean" ? null : "booleen_attendu";
9543
+ case "nombre":
9544
+ return fini(v) ? null : "nombre_attendu";
9545
+ case "entier":
9546
+ return Number.isInteger(v) && v >= 1 && v <= 24 ? null : "entier_1_24_attendu";
9547
+ case "longueur":
9548
+ return fini(v) && v >= 0 && v <= 1e5 ? null : "longueur_positive_attendue";
9549
+ case "dimension":
9550
+ return v === "hug" || v === "fill" || fini(v) && v >= 0 && v <= 1e5 ? null : "hug_fill_ou_longueur_attendu";
9551
+ case "padding":
9552
+ if (fini(v) && v >= 0) return null;
9553
+ if (Array.isArray(v) && (v.length === 2 || v.length === 4) && v.every((x) => fini(x) && x >= 0)) return null;
9554
+ return "padding_nombre_ou_liste_2_4";
9555
+ case "rayon":
9556
+ if (fini(v) && v >= 0) return null;
9557
+ if (Array.isArray(v) && v.length === 4 && v.every((x) => fini(x) && x >= 0)) return null;
9558
+ return "rayon_nombre_ou_liste_4";
9559
+ case "opacite":
9560
+ return fini(v) && v >= 0 && v <= 1 ? null : "opacite_0_1";
9561
+ case "couleur":
9562
+ return isColor(v) ? null : "couleur_invalide";
9563
+ case "remplissage":
9564
+ if (isColor(v)) return null;
9565
+ if (v && typeof v === "object" && v.type === "linear") {
9566
+ const cles = Object.keys(v).filter((k) => !["type", "angle", "stops"].includes(k));
9567
+ if (cles.length) return `champ_inconnu (${cles[0]})`;
9568
+ if (!fini(v.angle)) return "angle_attendu";
9569
+ if (!Array.isArray(v.stops) || v.stops.length < 2 || v.stops.length > 8) return "2_a_8_arrets";
9570
+ for (const s of v.stops) if (!s || !isColor(s.color) || !fini(s.at) || s.at < 0 || s.at > 1 || Object.keys(s).length !== 2) return "arret_invalide";
9571
+ return null;
9572
+ }
9573
+ return "couleur_ou_degrade_attendu";
9574
+ case "trait":
9575
+ if (v && typeof v === "object" && isColor(v.color) && fini(v.width) && v.width >= 0 && v.width <= 100 && Object.keys(v).length === 2) return null;
9576
+ return "trait_{color,width}_attendu";
9577
+ case "ombres":
9578
+ if (!Array.isArray(v) || v.length > 4) return "liste_de_4_ombres_max";
9579
+ for (const o of v) {
9580
+ if (!o || typeof o !== "object") return "ombre_invalide";
9581
+ const cles = Object.keys(o).filter((k) => !["x", "y", "blur", "spread", "color", "inset"].includes(k));
9582
+ if (cles.length) return `champ_inconnu (${cles[0]})`;
9583
+ if (![o.x, o.y, o.blur].every(fini) || !isColor(o.color) || o.spread !== void 0 && !fini(o.spread) || o.inset !== void 0 && typeof o.inset !== "boolean") return "ombre_invalide";
9584
+ }
9585
+ return null;
9586
+ case "texte":
9587
+ return typeof v === "string" && v.length <= 2e4 ? null : "texte_attendu";
9588
+ case "police":
9589
+ return typeof v === "string" && POLICE.test(v) ? null : "nom_de_police_invalide";
9590
+ case "graisse":
9591
+ return Number.isInteger(v) && v >= 100 && v <= 900 && v % 100 === 0 ? null : "graisse_100_a_900";
9592
+ case "interligne":
9593
+ return fini(v) && v > 0 && v <= 10 ? null : "interligne_0_10";
9594
+ case "source":
9595
+ return typeof v === "string" && SOURCE.test(v) ? null : "source_asset:<id>_attendue";
9596
+ default:
9597
+ return "regle_inconnue";
9598
+ }
9599
+ }
9600
+ function verifierGroupe(groupe, objet, chemin, erreurs) {
9601
+ if (objet === void 0) return;
9602
+ if (!objet || typeof objet !== "object" || Array.isArray(objet)) {
9603
+ erreurs.push({ path: chemin, reason: "objet_attendu" });
9604
+ return;
9605
+ }
9606
+ const regles = CHAMPS[groupe];
9607
+ for (const [cle, valeur] of Object.entries(objet)) {
9608
+ if (!(cle in regles)) {
9609
+ erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
9610
+ continue;
9611
+ }
9612
+ if (valeur === null && ["stroke", "shadow"].includes(cle)) continue;
9613
+ const motif = verifierValeur(regles[cle], valeur);
9614
+ if (motif) erreurs.push({ path: `${chemin}.${cle}`, reason: motif });
9615
+ }
9616
+ }
9617
+ function validateNode(node4, chemin = "node") {
9618
+ const erreurs = [];
9619
+ if (!node4 || typeof node4 !== "object" || Array.isArray(node4)) return [{ path: chemin, reason: "objet_attendu" }];
9620
+ for (const cle of Object.keys(node4)) if (!CHAMPS_NOEUD.has(cle)) erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
9621
+ if (!NODE_TYPES.includes(node4.type)) erreurs.push({ path: `${chemin}.type`, reason: `type_inconnu (${NODE_TYPES.join(", ")})` });
9622
+ if (typeof node4.name !== "string" || !node4.name.trim() || node4.name.length > 120) erreurs.push({ path: `${chemin}.name`, reason: "nom_1_a_120_caracteres" });
9623
+ if (node4.as !== void 0 && !(TAGS[node4.type] || []).includes(node4.as)) erreurs.push({ path: `${chemin}.as`, reason: "balise_non_permise" });
9624
+ if (node4.alt !== void 0 && (typeof node4.alt !== "string" || node4.alt.length > 500)) erreurs.push({ path: `${chemin}.alt`, reason: "texte_500_max" });
9625
+ for (const groupe of ["layout", "size", "position", "style", "text", "image", "shape"]) verifierGroupe(groupe, node4[groupe], `${chemin}.${groupe}`, erreurs);
9626
+ if (node4.type !== "frame" && node4.layout !== void 0) erreurs.push({ path: `${chemin}.layout`, reason: "seul_un_cadre_a_une_mise_en_page" });
9627
+ if (node4.type !== "text" && node4.text !== void 0) erreurs.push({ path: `${chemin}.text`, reason: "seul_un_texte_a_du_texte" });
9628
+ if (node4.type === "text" && typeof node4.text?.content !== "string") erreurs.push({ path: `${chemin}.text.content`, reason: "texte_attendu" });
9629
+ if (node4.type !== "image" && node4.image !== void 0) erreurs.push({ path: `${chemin}.image`, reason: "seule_une_image_a_une_source" });
9630
+ if (node4.type === "image" && typeof node4.image?.src !== "string") erreurs.push({ path: `${chemin}.image.src`, reason: "source_asset:<id>_attendue" });
9631
+ if (node4.type !== "shape" && node4.shape !== void 0) erreurs.push({ path: `${chemin}.shape`, reason: "seule_une_forme_a_un_genre" });
9632
+ if (CONTENEURS.has(node4.type)) {
9633
+ if (!Array.isArray(node4.children)) erreurs.push({ path: `${chemin}.children`, reason: "liste_attendue" });
9634
+ } else if (node4.children !== void 0) erreurs.push({ path: `${chemin}.children`, reason: "ce_type_n_a_pas_d_enfants" });
9635
+ return erreurs;
9636
+ }
9637
+ function isContainer(node4) {
9638
+ return CONTENEURS.has(node4?.type);
9639
+ }
9640
+ function createDocument() {
9641
+ return { format: FORMAT, version: FORMAT_VERSION, meta: { nextId: 1 }, pages: [{ id: "p_1", name: "Page 1", frames: [] }], nodes: {} };
9642
+ }
9643
+ function validate(doc) {
9644
+ const erreurs = [];
9645
+ const err = (path, reason) => erreurs.push({ path, reason });
9646
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) return { ok: false, errors: [{ path: "", reason: "objet_attendu" }] };
9647
+ for (const cle of Object.keys(doc)) if (!["format", "version", "meta", "pages", "nodes"].includes(cle)) err(cle, "champ_inconnu");
9648
+ if (doc.format !== FORMAT) err("format", `attendu_${FORMAT}`);
9649
+ if (doc.version !== FORMAT_VERSION) err("version", `version_${FORMAT_VERSION}_attendue`);
9650
+ if (!doc.meta || !Number.isInteger(doc.meta.nextId) || doc.meta.nextId < 1 || Object.keys(doc.meta).length !== 1) err("meta", "meta_{nextId}_attendu");
9651
+ if (!doc.nodes || typeof doc.nodes !== "object" || Array.isArray(doc.nodes)) {
9652
+ err("nodes", "objet_attendu");
9653
+ return { ok: false, errors: erreurs };
9654
+ }
9655
+ if (!Array.isArray(doc.pages) || doc.pages.length === 0) {
9656
+ err("pages", "au_moins_une_page");
9657
+ return { ok: false, errors: erreurs };
9658
+ }
9659
+ const parents = /* @__PURE__ */ new Map();
9660
+ const cite = (id, path) => {
9661
+ if (typeof id !== "string" || !Object.hasOwn(doc.nodes, id)) {
9662
+ err(path, "enfant_inexistant");
9663
+ return;
9664
+ }
9665
+ parents.set(id, (parents.get(id) || 0) + 1);
9666
+ };
9667
+ const idsPages = /* @__PURE__ */ new Set();
9668
+ doc.pages.forEach((p, i) => {
9669
+ const c = `pages[${i}]`;
9670
+ if (!p || typeof p !== "object") return err(c, "objet_attendu");
9671
+ for (const cle of Object.keys(p)) if (!["id", "name", "route", "frames"].includes(cle)) err(`${c}.${cle}`, "champ_inconnu");
9672
+ if (typeof p.id !== "string" || !/^p_[a-z0-9]+$/.test(p.id) || idsPages.has(p.id)) err(`${c}.id`, "id_de_page_invalide_ou_double");
9673
+ idsPages.add(p.id);
9674
+ if (typeof p.name !== "string" || !p.name.trim() || p.name.length > 120) err(`${c}.name`, "nom_1_a_120_caracteres");
9675
+ if (p.route !== void 0 && (typeof p.route !== "string" || !/^\/[a-z0-9\-/[\]]*$/.test(p.route))) err(`${c}.route`, "route_invalide");
9676
+ if (!Array.isArray(p.frames)) return err(`${c}.frames`, "liste_attendue");
9677
+ p.frames.forEach((id, k) => {
9678
+ cite(id, `${c}.frames[${k}]`);
9679
+ if (typeof id === "string" && Object.hasOwn(doc.nodes, id) && doc.nodes[id]?.type !== "frame") {
9680
+ err(`${c}.frames[${k}]`, "une_page_ne_contient_que_des_cadres");
9681
+ }
9682
+ });
9683
+ });
9684
+ const limite = doc.meta?.nextId ?? 1;
9685
+ for (const [id, node4] of Object.entries(doc.nodes)) {
9686
+ const c = `nodes.${id}`;
9687
+ if (!/^n_[0-9a-z]+$/.test(id)) err(c, "id_invalide");
9688
+ else if (parseInt(id.slice(2), 36) >= limite) err(c, "id_au_dela_du_compteur");
9689
+ if (node4?.id !== id) err(`${c}.id`, "id_different_de_la_cle");
9690
+ erreurs.push(...validateNode(node4, c));
9691
+ if (Array.isArray(node4?.children)) node4.children.forEach((enfant, k) => cite(enfant, `${c}.children[${k}]`));
9692
+ }
9693
+ for (const id of Object.keys(doc.nodes)) {
9694
+ const n = parents.get(id) || 0;
9695
+ if (n === 0) err(`nodes.${id}`, "noeud_orphelin");
9696
+ if (n > 1) err(`nodes.${id}`, "noeud_a_plusieurs_parents");
9697
+ }
9698
+ if (erreurs.length) return { ok: false, errors: erreurs };
9699
+ const vus = /* @__PURE__ */ new Set();
9700
+ const pile = doc.pages.flatMap((p) => p.frames);
9701
+ while (pile.length) {
9702
+ const id = pile.pop();
9703
+ vus.add(id);
9704
+ for (const enfant of doc.nodes[id].children || []) pile.push(enfant);
9705
+ }
9706
+ for (const id of Object.keys(doc.nodes)) if (!vus.has(id)) err(`nodes.${id}`, "cycle");
9707
+ return { ok: erreurs.length === 0, errors: erreurs };
9708
+ }
9709
+ function assertValid(doc) {
9710
+ const r = validate(doc);
9711
+ if (!r.ok) throw new StudioError("studio_document_invalid", `Document invalide : ${r.errors[0].path} \u2014 ${r.errors[0].reason}`, { errors: r.errors.slice(0, 20) });
9712
+ return doc;
9713
+ }
9714
+ var ORDRE_NOEUD = ["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"];
9715
+ var ordonner = (objet, ordre) => {
9716
+ const out = {};
9717
+ for (const k of ordre) if (objet[k] !== void 0) out[k] = objet[k];
9718
+ return out;
9719
+ };
9720
+ function canonical(doc) {
9721
+ const nodes = {};
9722
+ const ids = Object.keys(doc.nodes).sort((a, b) => parseInt(a.slice(2), 36) - parseInt(b.slice(2), 36));
9723
+ for (const id of ids) {
9724
+ const n = ordonner(doc.nodes[id], ORDRE_NOEUD);
9725
+ for (const g of Object.keys(CHAMPS)) if (n[g] && typeof n[g] === "object") n[g] = ordonner(n[g], Object.keys(CHAMPS[g]));
9726
+ nodes[id] = n;
9727
+ }
9728
+ return {
9729
+ format: doc.format,
9730
+ version: doc.version,
9731
+ meta: { nextId: doc.meta.nextId },
9732
+ pages: doc.pages.map((p) => ordonner({ ...p, frames: [...p.frames] }, ["id", "name", "route", "frames"])),
9733
+ nodes
9734
+ };
9735
+ }
9736
+ function migrate(doc) {
9737
+ if (doc && doc.version === FORMAT_VERSION) return doc;
9738
+ throw new StudioError("studio_document_invalid", `Version de document non prise en charge : ${doc?.version}`, { errors: [{ path: "version", reason: `version_${FORMAT_VERSION}_attendue` }] });
9739
+ }
9740
+
9741
+ // src/studio/ops.js
9742
+ var GROUPES = /* @__PURE__ */ new Set(["layout", "size", "position", "style", "text", "image", "shape"]);
9743
+ var SIMPLES = /* @__PURE__ */ new Set(["name", "as", "alt"]);
9744
+ var refus = (index, reason, message) => {
9745
+ throw new StudioError("studio_op_invalid", message || `Op\xE9ration ${index} refus\xE9e : ${reason}`, { index, reason });
9746
+ };
9747
+ function nouvelId(doc) {
9748
+ const id = `n_${doc.meta.nextId.toString(36)}`;
9749
+ doc.meta.nextId += 1;
9750
+ return id;
9751
+ }
9752
+ function emplacement(doc, id) {
9753
+ for (const p of doc.pages) {
9754
+ const i = p.frames.indexOf(id);
9755
+ if (i >= 0) return { parent: p.id, liste: p.frames, index: i };
9756
+ }
9757
+ for (const n of Object.values(doc.nodes)) if (n.children) {
9758
+ const i = n.children.indexOf(id);
9759
+ if (i >= 0) return { parent: n.id, liste: n.children, index: i };
9760
+ }
9761
+ return null;
9762
+ }
9763
+ function listeDuParent(doc, parent, type, index) {
9764
+ const page = doc.pages.find((p) => p.id === parent);
9765
+ if (page) {
9766
+ if (type !== "frame") refus(index, "une_page_ne_contient_que_des_cadres");
9767
+ return page.frames;
9768
+ }
9769
+ const n = doc.nodes[parent];
9770
+ if (!n) refus(index, "parent_introuvable");
9771
+ if (!isContainer(n)) refus(index, "le_parent_n_est_pas_un_cadre");
9772
+ return n.children;
9773
+ }
9774
+ function sousArbre(doc, id, acc = {}) {
9775
+ const n = doc.nodes[id];
9776
+ acc[id] = n;
9777
+ for (const e of n.children || []) sousArbre(doc, e, acc);
9778
+ return acc;
9779
+ }
9780
+ function placer(liste, id, index, iop) {
9781
+ const i = index === void 0 ? liste.length : index;
9782
+ if (!Number.isInteger(i) || i < 0 || i > liste.length) refus(iop, "index_hors_limites");
9783
+ liste.splice(i, 0, id);
9784
+ return i;
9785
+ }
9786
+ function aplatir(doc, brut, iop, acc) {
9787
+ if (!brut || typeof brut !== "object" || Array.isArray(brut)) refus(iop, "noeud_objet_attendu");
9788
+ if ("id" in brut) refus(iop, "un_id_ne_se_choisit_pas");
9789
+ const { children, ...reste } = brut;
9790
+ const id = nouvelId(doc);
9791
+ const node4 = { id, ...reste };
9792
+ if (isContainer(node4)) {
9793
+ if (children !== void 0 && !Array.isArray(children)) refus(iop, "children_liste_attendue");
9794
+ node4.children = (children || []).map((c) => aplatir(doc, c, iop, acc));
9795
+ } else if (children !== void 0) refus(iop, "ce_type_n_a_pas_d_enfants");
9796
+ const erreurs = validateNode(node4, "node");
9797
+ if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
9798
+ acc[id] = node4;
9799
+ return id;
9800
+ }
9801
+ function estDescendant(doc, ancetre, id) {
9802
+ const n = doc.nodes[ancetre];
9803
+ return (n?.children || []).some((e) => e === id || estDescendant(doc, e, id));
9804
+ }
9805
+ function lire(node4, path) {
9806
+ const [a, b] = path.split(".");
9807
+ if (b === void 0) return node4[a];
9808
+ return node4[a]?.[b];
9809
+ }
9810
+ function appliquerUne(doc, op, iop, inverses, created, removed) {
9811
+ if (!op || typeof op !== "object") refus(iop, "operation_objet_attendue");
9812
+ switch (op.op) {
9813
+ case "set": {
9814
+ const node4 = doc.nodes[op.id];
9815
+ if (!node4) refus(iop, "noeud_introuvable");
9816
+ if (typeof op.path !== "string") refus(iop, "chemin_attendu");
9817
+ const [a, b, ...trop] = op.path.split(".");
9818
+ if (trop.length || !(SIMPLES.has(a) && b === void 0) && !GROUPES.has(a)) refus(iop, "chemin_non_modifiable");
9819
+ const avant = lire(node4, op.path);
9820
+ const copie2 = structuredClone(node4);
9821
+ if (b === void 0) {
9822
+ if (op.value === void 0) delete copie2[a];
9823
+ else copie2[a] = structuredClone(op.value);
9824
+ } else {
9825
+ const groupe = { ...copie2[a] || {} };
9826
+ if (op.value === void 0) delete groupe[b];
9827
+ else groupe[b] = structuredClone(op.value);
9828
+ if (Object.keys(groupe).length) copie2[a] = groupe;
9829
+ else delete copie2[a];
9830
+ }
9831
+ const erreurs = validateNode(copie2, op.id);
9832
+ if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
9833
+ doc.nodes[op.id] = copie2;
9834
+ inverses.push({ op: "set", id: op.id, path: op.path, value: avant === void 0 ? void 0 : structuredClone(avant) });
9835
+ return;
9836
+ }
9837
+ case "insert": {
9838
+ const acc = {};
9839
+ const racine = aplatir(doc, op.node, iop, acc);
9840
+ const liste = listeDuParent(doc, op.parent, acc[racine].type, iop);
9841
+ Object.assign(doc.nodes, acc);
9842
+ placer(liste, racine, op.index, iop);
9843
+ created.push(...Object.keys(acc));
9844
+ inverses.push({ op: "remove", id: racine });
9845
+ return;
9846
+ }
9847
+ case "move": {
9848
+ const node4 = doc.nodes[op.id];
9849
+ if (!node4) refus(iop, "noeud_introuvable");
9850
+ if (op.parent === op.id || estDescendant(doc, op.id, op.parent)) refus(iop, "deplacement_dans_son_propre_descendant");
9851
+ const ici = emplacement(doc, op.id);
9852
+ const liste = listeDuParent(doc, op.parent, node4.type, iop);
9853
+ ici.liste.splice(ici.index, 1);
9854
+ placer(liste, op.id, op.index, iop);
9855
+ inverses.push({ op: "move", id: op.id, parent: ici.parent, index: ici.index });
9856
+ return;
9857
+ }
9858
+ case "remove": {
9859
+ if (!doc.nodes[op.id]) refus(iop, "noeud_introuvable");
9860
+ const ici = emplacement(doc, op.id);
9861
+ const arbre = sousArbre(doc, op.id);
9862
+ ici.liste.splice(ici.index, 1);
9863
+ for (const id of Object.keys(arbre)) delete doc.nodes[id];
9864
+ removed.push(...Object.keys(arbre));
9865
+ inverses.push({ op: "restore", parent: ici.parent, index: ici.index, root: op.id, nodes: arbre });
9866
+ return;
9867
+ }
9868
+ case "restore": {
9869
+ if (!op.__interne) refus(iop, "operation_inconnue");
9870
+ const liste = listeDuParent(doc, op.parent, op.nodes[op.root].type, iop);
9871
+ Object.assign(doc.nodes, structuredClone(op.nodes));
9872
+ placer(liste, op.root, op.index, iop);
9873
+ inverses.push({ op: "remove", id: op.root });
9874
+ return;
9875
+ }
9876
+ default:
9877
+ refus(iop, "operation_inconnue");
9878
+ }
9879
+ }
9880
+ function applyOps(doc, ops, { internal = false } = {}) {
9881
+ if (!Array.isArray(ops)) throw new StudioError("studio_op_invalid", "Un lot d'op\xE9rations est une liste.", { index: -1, reason: "liste_attendue" });
9882
+ const copie2 = structuredClone(doc);
9883
+ const inverses = [];
9884
+ const created = [];
9885
+ const removed = [];
9886
+ ops.forEach((op, i) => appliquerUne(copie2, internal && op?.op === "restore" ? { ...op, __interne: true } : op, i, inverses, created, removed));
9887
+ return { doc: copie2, inverse: inverses.reverse(), created, removed };
9888
+ }
9889
+
9890
+ // src/studio/style.js
9891
+ var px = (v) => `${+v.toFixed(3)}px`;
9892
+ var ALIGN = { start: "flex-start", center: "center", end: "flex-end", stretch: "stretch" };
9893
+ var JUSTIFY = { start: "flex-start", center: "center", end: "flex-end", between: "space-between" };
9894
+ function remplissage(f) {
9895
+ if (typeof f === "string") return f;
9896
+ return `linear-gradient(${+f.angle.toFixed(3)}deg, ${f.stops.map((s) => `${s.color} ${+(s.at * 100).toFixed(3)}%`).join(", ")})`;
9897
+ }
9898
+ function padding(p) {
9899
+ if (typeof p === "number") return px(p);
9900
+ return p.map(px).join(" ");
9901
+ }
9902
+ function taille(decl, axe, v, parent) {
9903
+ if (v === void 0) return;
9904
+ const prop = axe === "w" ? "width" : "height";
9905
+ const mode = parent?.layout?.mode;
9906
+ const dir = parent?.layout?.direction || "row";
9907
+ const principal = mode === "flex" && (axe === "w" && dir === "row" || axe === "h" && dir === "column");
9908
+ if (typeof v === "number") {
9909
+ decl.push([prop, px(v)]);
9910
+ if (principal) decl.push(["flex-shrink", "0"]);
9911
+ } else if (v === "fill") {
9912
+ if (principal) decl.push(["flex", "1 1 0"], [axe === "w" ? "min-width" : "min-height", "0"]);
9913
+ else if (mode === "flex") decl.push(["align-self", "stretch"]);
9914
+ else decl.push([prop, "100%"]);
9915
+ } else if (v === "hug") {
9916
+ decl.push([prop, "fit-content"]);
9917
+ }
9918
+ }
9919
+ function nodeCss(node4, parent = null) {
9920
+ const d = [];
9921
+ const pos = node4.position;
9922
+ if (parent?.layout?.mode === "free" || pos?.absolute) {
9923
+ d.push(["position", "absolute"], ["left", px(pos?.x ?? 0)], ["top", px(pos?.y ?? 0)]);
9924
+ }
9925
+ const l = node4.layout;
9926
+ if (node4.type === "frame") {
9927
+ if (l?.mode === "grid") {
9928
+ d.push(["display", "grid"], ["grid-template-columns", `repeat(${l.columns || 2}, minmax(0, 1fr))`]);
9929
+ } else if (l?.mode === "free") {
9930
+ if (!d.some(([p]) => p === "position")) d.push(["position", "relative"]);
9931
+ } else {
9932
+ d.push(["display", "flex"], ["flex-direction", l?.direction || "column"]);
9933
+ if (l?.wrap) d.push(["flex-wrap", "wrap"]);
9934
+ if (l?.align) d.push(["align-items", ALIGN[l.align]]);
9935
+ if (l?.justify) d.push(["justify-content", JUSTIFY[l.justify]]);
9936
+ }
9937
+ if (l?.gap !== void 0 && l.mode !== "free") d.push(["gap", px(l.gap)]);
9938
+ if (l?.padding !== void 0) d.push(["padding", padding(l.padding)]);
9939
+ }
9940
+ taille(d, "w", node4.size?.w, parent);
9941
+ taille(d, "h", node4.size?.h, parent);
9942
+ for (const [k, prop] of [["minW", "min-width"], ["minH", "min-height"], ["maxW", "max-width"], ["maxH", "max-height"]]) {
9943
+ if (node4.size?.[k] !== void 0) d.push([prop, px(node4.size[k])]);
9944
+ }
9945
+ const s = node4.style || {};
9946
+ if (s.fill !== void 0 && node4.type !== "text") d.push(["background", remplissage(s.fill)]);
9947
+ if (s.stroke) d.push(["border", `${px(s.stroke.width)} solid ${s.stroke.color}`]);
9948
+ if (node4.type === "shape" && node4.shape?.kind === "ellipse") d.push(["border-radius", "50%"]);
9949
+ else if (s.radius !== void 0) d.push(["border-radius", typeof s.radius === "number" ? px(s.radius) : s.radius.map(px).join(" ")]);
9950
+ if (s.shadow?.length) d.push(["box-shadow", s.shadow.map((o) => `${o.inset ? "inset " : ""}${px(o.x)} ${px(o.y)} ${px(o.blur)} ${px(o.spread || 0)} ${o.color}`).join(", ")]);
9951
+ if (s.opacity !== void 0 && s.opacity !== 1) d.push(["opacity", String(s.opacity)]);
9952
+ if (s.clip) d.push(["overflow", "hidden"]);
9953
+ if (node4.type === "shape" && node4.shape?.kind === "line") d.push(["height", "0"], ["border-top", `${px(s.stroke?.width ?? 1)} solid ${s.stroke?.color ?? "#000000"}`]);
9954
+ const t = node4.text;
9955
+ if (node4.type === "text") {
9956
+ if (t.font) d.push(["font-family", `"${t.font}", sans-serif`]);
9957
+ if (t.size !== void 0) d.push(["font-size", px(t.size)]);
9958
+ if (t.weight !== void 0) d.push(["font-weight", String(t.weight)]);
9959
+ if (t.lineHeight !== void 0) d.push(["line-height", String(t.lineHeight)]);
9960
+ if (t.letterSpacing !== void 0) d.push(["letter-spacing", px(t.letterSpacing)]);
9961
+ if (t.align) d.push(["text-align", t.align]);
9962
+ if (t.transform && t.transform !== "none") d.push(["text-transform", t.transform]);
9963
+ d.push(["color", t.color || "#000000"]);
9964
+ if (s.fill !== void 0) d.push(["background", remplissage(s.fill)]);
9965
+ d.push(["white-space", "pre-wrap"]);
9966
+ }
9967
+ if (node4.type === "image") d.push(["display", "block"], ["object-fit", node4.image.fit || "cover"]);
9968
+ return d;
9969
+ }
9970
+ function tagOf(node4) {
9971
+ return node4.as || DEFAULT_TAG[node4.type];
9972
+ }
9973
+ var BASE_CSS = "*,*::before,*::after{box-sizing:border-box;margin:0}";
9974
+ function parentsOf(doc) {
9975
+ const m = /* @__PURE__ */ new Map();
9976
+ for (const p of doc.pages) for (const id of p.frames) m.set(id, null);
9977
+ for (const n of Object.values(doc.nodes)) for (const e of n.children || []) m.set(e, n);
9978
+ return m;
9979
+ }
9980
+
9981
+ // src/studio/check.js
9982
+ function parseColor(c) {
9983
+ if (!isColor(c)) return null;
9984
+ const s = c.trim().toLowerCase();
9985
+ if (s === "transparent") return [0, 0, 0, 0];
9986
+ if (s.startsWith("#")) {
9987
+ let h = s.slice(1);
9988
+ if (h.length <= 4) h = [...h].map((x) => x + x).join("");
9989
+ const n = (i) => parseInt(h.slice(i, i + 2), 16);
9990
+ return [n(0), n(2), n(4), h.length === 8 ? n(6) / 255 : 1];
9991
+ }
9992
+ const v = s.match(/[\d.]+/g).map(Number);
9993
+ return [v[0], v[1], v[2], v[3] ?? 1];
9994
+ }
9995
+ function luminance([r, g, b]) {
9996
+ const lin = (x) => {
9997
+ x /= 255;
9998
+ return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
9999
+ };
10000
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
10001
+ }
10002
+ var melange = (dessus, fond) => [0, 1, 2].map((i) => dessus[i] * dessus[3] + fond[i] * (1 - dessus[3])).concat(1);
10003
+ function contrastRatio(a, b) {
10004
+ const [l1, l2] = [luminance(a), luminance(b)].sort((x, y) => y - x);
10005
+ return (l1 + 0.05) / (l2 + 0.05);
10006
+ }
10007
+ function fondsSous(doc, id, parents) {
10008
+ const couches = [];
10009
+ let n = doc.nodes[id];
10010
+ if (n.type === "text" && n.style?.fill !== void 0) couches.push(n.style.fill);
10011
+ for (let p = parents.get(id); p; p = parents.get(p.id)) if (p.style?.fill !== void 0) couches.push(p.style.fill);
10012
+ let fonds = [[255, 255, 255, 1]];
10013
+ for (const f of couches.reverse()) {
10014
+ const couleurs = typeof f === "string" ? [parseColor(f)] : f.stops.map((s) => parseColor(s.color));
10015
+ fonds = couleurs.flatMap((c) => fonds.map((base2) => melange(c, base2)));
10016
+ }
10017
+ return fonds;
10018
+ }
10019
+ function check(doc) {
10020
+ const issues = [];
10021
+ const parents = parentsOf(doc);
10022
+ for (const n of Object.values(doc.nodes)) {
10023
+ if (n.type === "text") {
10024
+ const couleur = parseColor(n.text.color || "#000000");
10025
+ const grand = (n.text.size ?? 16) >= 24 || (n.text.size ?? 16) >= 18.66 && (n.text.weight ?? 400) >= 700;
10026
+ const requis = grand ? 3 : 4.5;
10027
+ let pire = null;
10028
+ for (const fond of fondsSous(doc, n.id, parents)) {
10029
+ const ratio = contrastRatio(melange(couleur, fond), fond);
10030
+ if (!pire || ratio < pire.ratio) pire = { ratio, fond };
10031
+ }
10032
+ if (pire && pire.ratio < requis) {
10033
+ const hex = (c) => `#${c.slice(0, 3).map((x) => Math.round(x).toString(16).padStart(2, "0")).join("")}`;
10034
+ issues.push({ rule: "contrast", severity: "error", node: n.id, name: n.name, detail: { ratio: Math.floor(pire.ratio * 100) / 100, required: requis, fg: n.text.color || "#000000", bg: hex(pire.fond) } });
10035
+ }
10036
+ }
10037
+ if (n.type === "frame" && n.children.length === 0 && n.style?.fill === void 0 && !n.style?.stroke) {
10038
+ issues.push({ rule: "empty-frame", severity: "warning", node: n.id, name: n.name });
10039
+ }
10040
+ if (n.type === "image" && !n.alt) issues.push({ rule: "image-alt", severity: "warning", node: n.id, name: n.name });
10041
+ }
10042
+ return { issues };
10043
+ }
10044
+
10045
+ // src/studio/emit/html.js
10046
+ var ECHAPPE = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
10047
+ var escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ECHAPPE[c]);
10048
+ function slug(nom) {
10049
+ const s = String(nom).normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
10050
+ return /^[a-z]/.test(s) ? s : `n-${s || "noeud"}`;
10051
+ }
10052
+ function classNames(doc, page) {
10053
+ const prises = /* @__PURE__ */ new Set();
10054
+ const classes = /* @__PURE__ */ new Map();
10055
+ const unique = (base2) => {
10056
+ let c = base2;
10057
+ let k = 2;
10058
+ while (prises.has(c)) c = `${base2}-${k++}`;
10059
+ prises.add(c);
10060
+ return c;
10061
+ };
10062
+ const visiter = (id, racine) => {
10063
+ const n = doc.nodes[id];
10064
+ const c = racine ? unique(`${racine}__${slug(n.name)}`) : unique(slug(n.name));
10065
+ classes.set(id, c);
10066
+ for (const e of n.children || []) visiter(e, racine || c);
10067
+ };
10068
+ for (const id of page.frames) visiter(id, null);
10069
+ return classes;
10070
+ }
10071
+ function emitHtml(doc, { page: pageId, assets = {}, title, lang = "fr" } = {}) {
10072
+ const page = pageId ? doc.pages.find((p) => p.id === pageId) : doc.pages[0];
10073
+ if (!page) throw new StudioError("studio_page_not_found", `Page introuvable : ${pageId}`, void 0, 404);
10074
+ const parents = parentsOf(doc);
10075
+ const classes = classNames(doc, page);
10076
+ const warnings = [];
10077
+ const regles = [BASE_CSS];
10078
+ const html = (id, profondeur) => {
10079
+ const n = doc.nodes[id];
10080
+ const c = classes.get(id);
10081
+ const decl = nodeCss(n, parents.get(id));
10082
+ if (decl.length) regles.push(`.${c}{${decl.map(([p, v]) => `${p}:${v}`).join(";")}}`);
10083
+ const tag = tagOf(n);
10084
+ const pad2 = " ".repeat(profondeur);
10085
+ if (n.type === "image") {
10086
+ const asset = n.image.src.slice("asset:".length);
10087
+ if (n.alt === void 0) warnings.push(`image-alt : \xAB ${n.name} \xBB n'a pas de texte alternatif`);
10088
+ return `${pad2}<img class="${c}" src="${escapeHtml(assets[asset] || `assets/${asset}`)}" alt="${escapeHtml(n.alt ?? "")}">`;
10089
+ }
10090
+ if (n.type === "text") return `${pad2}<${tag} class="${c}">${escapeHtml(n.text.content)}</${tag}>`;
10091
+ const enfants = (n.children || []).map((e) => html(e, profondeur + 1));
10092
+ return enfants.length ? `${pad2}<${tag} class="${c}">
10093
+ ${enfants.join("\n")}
10094
+ ${pad2}</${tag}>` : `${pad2}<${tag} class="${c}"></${tag}>`;
10095
+ };
10096
+ const corps = page.frames.map((id) => html(id, 2)).join("\n");
10097
+ const index = `<!doctype html>
10098
+ <html lang="${escapeHtml(lang)}">
10099
+ <head>
10100
+ <meta charset="utf-8">
10101
+ <meta name="viewport" content="width=device-width, initial-scale=1">
10102
+ <title>${escapeHtml(title || page.name)}</title>
10103
+ <link rel="stylesheet" href="styles.css">
10104
+ </head>
10105
+ <body>
10106
+ ${corps}
10107
+ </body>
10108
+ </html>
10109
+ `;
10110
+ const css = `${regles.join("\n")}
10111
+ `;
10112
+ const octets = (s) => new TextEncoder().encode(s).length;
10113
+ return {
10114
+ target: "html",
10115
+ files: [
10116
+ { path: "index.html", content: index, bytes: octets(index) },
10117
+ { path: "styles.css", content: css, bytes: octets(css) }
10118
+ ],
10119
+ warnings
10120
+ };
10121
+ }
10122
+
10123
+ // src/studio/render.js
10124
+ function renderNode(doc, nodeId, { document: d = globalThis.document, assets = {}, parents = parentsOf(doc) } = {}) {
10125
+ if (!d || typeof d.createElement !== "function") {
10126
+ throw new StudioError("studio_render_unavailable", "Le rendu demande un navigateur (aucun DOM ici).");
10127
+ }
10128
+ const creer = (id) => {
10129
+ const n = doc.nodes[id];
10130
+ const el = d.createElement(tagOf(n));
10131
+ el.setAttribute("data-node-id", id);
10132
+ for (const [prop, valeur] of nodeCss(n, parents.get(id))) el.style.setProperty(prop, valeur);
10133
+ if (n.type === "image") {
10134
+ const asset = n.image.src.slice("asset:".length);
10135
+ el.setAttribute("src", assets[asset] || `assets/${asset}`);
10136
+ el.setAttribute("alt", n.alt ?? "");
10137
+ } else if (n.type === "text") {
10138
+ el.textContent = n.text.content;
10139
+ } else {
10140
+ for (const e of n.children || []) el.appendChild(creer(e));
10141
+ }
10142
+ return el;
10143
+ };
10144
+ if (!doc.nodes[nodeId]) throw new StudioError("studio_node_not_found", `N\u0153ud introuvable : ${nodeId}`, void 0, 404);
10145
+ return creer(nodeId);
10146
+ }
10147
+
10148
+ // src/studio/raster.js
10149
+ var XHTML = "http://www.w3.org/1999/xhtml";
10150
+ async function enData(url) {
10151
+ const reponse = await fetch(url);
10152
+ if (!reponse.ok) throw new StudioError("studio_asset_unavailable", `Ressource illisible pour l'export : ${url} (${reponse.status})`);
10153
+ const blob = await reponse.blob();
10154
+ return await new Promise((ok, ko) => {
10155
+ const f = new FileReader();
10156
+ f.onload = () => ok(f.result);
10157
+ f.onerror = ko;
10158
+ f.readAsDataURL(blob);
10159
+ });
10160
+ }
10161
+ async function policesIncorporees(d) {
10162
+ const regles = [];
10163
+ for (const feuille of d.styleSheets) {
10164
+ let liste;
10165
+ try {
10166
+ liste = feuille.cssRules;
10167
+ } catch {
10168
+ continue;
10169
+ }
10170
+ for (const r of liste) {
10171
+ if (r.type !== 5) continue;
10172
+ let css = r.cssText;
10173
+ const base2 = feuille.href || d.baseURI;
10174
+ for (const [, brut] of css.matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/g)) {
10175
+ if (brut.startsWith("data:")) continue;
10176
+ css = css.replace(brut, await enData(new URL(brut, base2).href));
10177
+ }
10178
+ regles.push(css);
10179
+ }
10180
+ }
10181
+ return regles.join("\n");
10182
+ }
10183
+ function figerLignes(racine, d) {
10184
+ for (const el of racine.querySelectorAll("[data-node-id]")) {
10185
+ const texte = el.firstChild;
10186
+ if (!texte || texte.nodeType !== 3 || el.childNodes.length !== 1) continue;
10187
+ const t = texte.textContent;
10188
+ const r = d.createRange();
10189
+ let haut = null;
10190
+ let sortie = "";
10191
+ for (let i = 0; i < t.length; i++) {
10192
+ r.setStart(texte, i);
10193
+ r.setEnd(texte, i + 1);
10194
+ const rect = r.getClientRects()[0];
10195
+ if (rect && haut !== null && rect.top > haut + 1 && t[i] !== " " && t[i] !== "\n") sortie = `${sortie.replace(/ +$/, "")}
10196
+ `;
10197
+ if (rect) haut = rect.top;
10198
+ sortie += t[i];
10199
+ }
10200
+ texte.textContent = sortie;
10201
+ el.style.setProperty("white-space", "pre");
10202
+ }
10203
+ }
10204
+ async function renderPng(doc, { frame, scale = 1, assets = {}, document: d = globalThis.document } = {}) {
10205
+ const W = globalThis;
10206
+ if (!d?.body || typeof W.XMLSerializer !== "function" || typeof W.Image !== "function" || typeof W.fetch !== "function") {
10207
+ throw new StudioError("studio_render_unavailable", "L'export d'image se fait dans un navigateur (aucun DOM ici).");
10208
+ }
10209
+ if (![1, 2, 3, 4].includes(scale)) throw new StudioError("studio_render_invalid", "scale vaut 1, 2, 3 ou 4.", { reason: "scale_1_a_4" });
10210
+ const id = doc.nodes[frame]?.type === "frame" ? frame : Object.values(doc.nodes).find((n) => n.type === "frame" && n.name === frame)?.id;
10211
+ if (!id) throw new StudioError("studio_node_not_found", `Cadre introuvable : ${frame}`, void 0, 404);
10212
+ const hote = d.createElement("div");
10213
+ hote.setAttribute("aria-hidden", "true");
10214
+ hote.setAttribute("data-studio-raster", "");
10215
+ hote.style.cssText = "position:fixed;left:-100000px;top:0;contain:layout style;pointer-events:none";
10216
+ const base2 = d.createElement("style");
10217
+ base2.textContent = "[data-studio-raster] *,[data-studio-raster] *::before,[data-studio-raster] *::after{box-sizing:border-box;margin:0}";
10218
+ hote.append(base2, renderNode(doc, id, { document: d, assets }));
10219
+ d.body.appendChild(hote);
10220
+ try {
10221
+ const el = hote.lastChild;
10222
+ await d.fonts?.ready;
10223
+ await Promise.all([...el.querySelectorAll("img")].map((img) => img.decode().catch(() => {
10224
+ })));
10225
+ figerLignes(el, d);
10226
+ const rect = el.getBoundingClientRect();
10227
+ const width = Math.ceil(rect.width);
10228
+ const height = Math.ceil(rect.height);
10229
+ const copie2 = el.cloneNode(true);
10230
+ for (const img of copie2.querySelectorAll("img")) img.setAttribute("src", await enData(new URL(img.getAttribute("src"), d.baseURI).href));
10231
+ const polices = await policesIncorporees(d);
10232
+ const xhtml = new W.XMLSerializer().serializeToString(copie2);
10233
+ const style = `${BASE_CSS}
10234
+ ${polices}`.replace(/]]>/g, "]]&gt;");
10235
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width * scale}" height="${height * scale}" viewBox="0 0 ${width} ${height}"><foreignObject x="0" y="0" width="${width}" height="${height}"><div xmlns="${XHTML}"><style><![CDATA[${style}]]></style>${xhtml}</div></foreignObject></svg>`;
10236
+ const image = new W.Image();
10237
+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
10238
+ await image.decode();
10239
+ const canvas = d.createElement("canvas");
10240
+ canvas.width = Math.round(width * scale);
10241
+ canvas.height = Math.round(height * scale);
10242
+ canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
10243
+ const blob = await new Promise((ok) => canvas.toBlob(ok, "image/png"));
10244
+ return { bytes: new Uint8Array(await blob.arrayBuffer()), mime: "image/png", width: canvas.width, height: canvas.height };
10245
+ } finally {
10246
+ hote.remove();
10247
+ }
10248
+ }
10249
+
10250
+ // src/studio/targets.js
10251
+ var TARGETS = Object.freeze([
10252
+ Object.freeze({ target: "html", status: "available" }),
10253
+ Object.freeze({ target: "email", status: "planned", phase: 3 }),
10254
+ Object.freeze({ target: "react", status: "planned", phase: 6 })
10255
+ ]);
10256
+
10257
+ // src/studio/document.js
10258
+ var copie = (v) => v === void 0 ? void 0 : structuredClone(v);
10259
+ var StudioDocument = class {
10260
+ #doc;
10261
+ #passe = [];
10262
+ // lots qui défont, du plus ancien au plus récent
10263
+ #futur = [];
10264
+ // lots qui refont
10265
+ #ecoutes = /* @__PURE__ */ new Set();
10266
+ /** @param {object} [json] un document enregistré ; absent : un document vide */
10267
+ constructor(json) {
10268
+ this.#doc = json === void 0 ? createDocument() : assertValid(migrate(structuredClone(json)));
10269
+ }
10270
+ /* ── Lire ────────────────────────────────────────────────────────────────────────────────── */
10271
+ get pages() {
10272
+ return this.#doc.pages.map((p) => ({ ...p, frames: [...p.frames] }));
10273
+ }
10274
+ /** Une copie du nœud : la modifier ne change pas le document (seules les opérations le font). */
10275
+ node(id) {
10276
+ return copie(this.#doc.nodes[id]) ?? null;
10277
+ }
10278
+ /** Premier nœud qui correspond, dans l'ordre des pages puis de l'arbre. `{ name, type }` */
10279
+ find(critere = {}) {
10280
+ return this.findAll(critere)[0] ?? null;
10281
+ }
10282
+ findAll({ name, type } = {}) {
10283
+ const out = [];
10284
+ const visiter = (id) => {
10285
+ const n = this.#doc.nodes[id];
10286
+ if ((name === void 0 || n.name === name) && (type === void 0 || n.type === type)) out.push(copie(n));
10287
+ for (const e of n.children || []) visiter(e);
10288
+ };
10289
+ for (const p of this.#doc.pages) for (const id of p.frames) visiter(id);
10290
+ return out;
10291
+ }
10292
+ /** Le document en forme canonique : deux documents égaux donnent les mêmes octets. */
10293
+ toJSON() {
10294
+ return structuredClone(canonical(this.#doc));
10295
+ }
10296
+ /* ── Vérifier, émettre, rendre (P85) ─────────────────────────────────────────────────────── */
10297
+ /** → `{ issues: [{ rule, severity, node, name, detail? }] }` */
10298
+ check() {
10299
+ return check(this.#doc);
10300
+ }
10301
+ /** → `{ target, files: [{ path, content, bytes }], warnings }`. Phase 1 : `target: "html"` seulement. */
10302
+ emit({ target = "html", ...options } = {}) {
10303
+ if (target !== "html") {
10304
+ const prevue = TARGETS.find((t) => t.target === target);
10305
+ throw new StudioError("studio_target_unavailable", prevue ? `La cible \xAB ${target} \xBB arrive en phase ${prevue.phase}.` : `Cible inconnue : ${target}`, { target, available: TARGETS.filter((t) => t.status === "available").map((t) => t.target) }, 501);
10306
+ }
10307
+ return emitHtml(this.#doc, options);
10308
+ }
10309
+ /** Un cadre en PNG, dans le navigateur. → `{ bytes, mime, width, height }` ; hors navigateur : `studio_render_unavailable`. */
10310
+ async render({ frame, format = "png", scale = 1, assets, document } = {}) {
10311
+ if (format !== "png") throw new StudioError("studio_target_unavailable", `Le format \xAB ${format} \xBB n'est pas encore livr\xE9 (phase 2) ; png l'est.`, { format, available: ["png"] }, 501);
10312
+ return renderPng(this.#doc, { frame, scale, assets, document });
10313
+ }
10314
+ /* ── Modifier ────────────────────────────────────────────────────────────────────────────── */
10315
+ /** Applique un lot, en entier ou pas du tout. → `{ applied, created, removed }` */
10316
+ apply(ops, { source = "user" } = {}) {
10317
+ const r = applyOps(this.#doc, ops);
10318
+ this.#doc = r.doc;
10319
+ this.#passe.push(r.inverse);
10320
+ this.#futur = [];
10321
+ this.#emettre(ops, source);
10322
+ return { applied: ops.length, created: r.created, removed: r.removed };
10323
+ }
10324
+ set(id, path, value) {
10325
+ return this.apply([{ op: "set", id, path, value }]);
10326
+ }
10327
+ /** Insère un nœud et rend son id. `parent` : id d'un cadre, ou d'une page. */
10328
+ insert(parent, node4, { index } = {}) {
10329
+ return this.apply([{ op: "insert", parent, node: node4, index }]).created[0];
10330
+ }
10331
+ move(id, { parent, index } = {}) {
10332
+ return this.apply([{ op: "move", id, parent, index }]);
10333
+ }
10334
+ remove(id) {
10335
+ return this.apply([{ op: "remove", id }]);
10336
+ }
10337
+ undo() {
10338
+ return this.#deplacer(this.#passe, this.#futur, "undo");
10339
+ }
10340
+ redo() {
10341
+ return this.#deplacer(this.#futur, this.#passe, "redo");
10342
+ }
10343
+ history() {
10344
+ return { undo: this.#passe.length, redo: this.#futur.length };
10345
+ }
10346
+ /** Écoute les changements ; rend la fonction qui arrête l'écoute. `e = { ops, source }` */
10347
+ on(evenement, fn) {
10348
+ if (evenement !== "change") throw new StudioError("studio_event_unknown", `\xC9v\xE9nement inconnu : ${evenement}`);
10349
+ this.#ecoutes.add(fn);
10350
+ return () => this.#ecoutes.delete(fn);
10351
+ }
10352
+ #deplacer(depuis, vers, source) {
10353
+ const lot = depuis.pop();
10354
+ if (!lot) return false;
10355
+ const r = applyOps(this.#doc, lot, { internal: true });
10356
+ this.#doc = r.doc;
10357
+ vers.push(r.inverse);
10358
+ this.#emettre(lot, source);
10359
+ return true;
10360
+ }
10361
+ #emettre(ops, source) {
10362
+ for (const fn of this.#ecoutes) {
10363
+ try {
10364
+ fn({ ops: copie(ops), source });
10365
+ } catch {
10366
+ }
10367
+ }
10368
+ }
10369
+ };
10370
+
10371
+ // src/resources/studio.js
10372
+ var base = "/api/studio";
10373
+ var projectPath = (id) => `${base}/projects/${encodeURIComponent(id)}`;
10374
+ var byType = (path, type) => type === void 0 ? path : `${path}?type=${encodeURIComponent(type)}`;
10375
+ var StudioProject = class _StudioProject {
10376
+ #client;
10377
+ constructor(client, data) {
10378
+ this.#client = client;
10379
+ Object.assign(this, data);
10380
+ }
10381
+ async open() {
10382
+ const path = projectPath(this.id);
10383
+ const { document, version } = await this.#client.get(`${path}/document`);
10384
+ const doc = new StudioDocument(document);
10385
+ let current = version;
10386
+ let pending = Promise.resolve();
10387
+ doc.save = ({ version: name } = {}) => {
10388
+ const document2 = doc.toJSON();
10389
+ const request = pending.then(async () => {
10390
+ const result = await this.#client.post(`${path}/document`, { document: document2, baseVersion: current, name });
10391
+ current = result.version;
10392
+ this.version = { id: current, name: name ?? null };
10393
+ this.bytes = result.bytes;
10394
+ return { version: current, bytes: result.bytes };
10395
+ });
10396
+ pending = request.catch(() => {
10397
+ });
10398
+ return request;
10399
+ };
10400
+ return doc;
10401
+ }
10402
+ async update(data) {
10403
+ const { project } = await this.#client.post(projectPath(this.id), data);
10404
+ Object.assign(this, project);
10405
+ return this;
10406
+ }
10407
+ async duplicate(data) {
10408
+ const { project } = await this.#client.post(`${projectPath(this.id)}/duplicate`, data);
10409
+ return new _StudioProject(this.#client, project);
10410
+ }
10411
+ async versions() {
10412
+ return (await this.#client.get(`${projectPath(this.id)}/versions`)).versions;
10413
+ }
10414
+ async restore(version) {
10415
+ const { project } = await this.#client.post(`${projectPath(this.id)}/restore`, { version });
10416
+ Object.assign(this, project);
10417
+ return this;
10418
+ }
10419
+ };
10420
+ var StudioResource = class {
10421
+ constructor(client) {
10422
+ const wrap = (data) => new StudioProject(client, data);
10423
+ this.templates = {
10424
+ list: async ({ type } = {}) => (await client.get(byType(`${base}/templates`, type))).templates,
10425
+ get: async (id) => (await client.get(`${base}/templates/${encodeURIComponent(id)}`)).template
10426
+ };
10427
+ this.projects = {
10428
+ create: async (data) => wrap((await client.post(`${base}/projects`, data)).project),
10429
+ list: async ({ type } = {}) => (await client.get(byType(`${base}/projects`, type))).projects.map(wrap),
10430
+ get: async (id) => wrap((await client.get(projectPath(id))).project),
10431
+ remove: async (id) => client.delete(projectPath(id))
10432
+ };
10433
+ }
10434
+ /** Un document vide, ou rouvert depuis son JSON (validé ; invalide → `studio_document_invalid`). */
10435
+ document(json) {
10436
+ return new StudioDocument(json);
10437
+ }
10438
+ /** Les cibles d'émission et leur état : `[{ target, status: "available" | "planned", phase? }]` */
10439
+ targets() {
10440
+ return TARGETS.map((t) => ({ ...t }));
10441
+ }
10442
+ };
10443
+
9407
10444
  // src/index.js
9408
10445
  var DEFAULT_BASE_URL = typeof process !== "undefined" && process?.env?.IAGENIFY_API_URL || "https://api.iagenify.com";
9409
10446
  var IaGenify = class {
@@ -9492,6 +10529,7 @@ var IaGenify = class {
9492
10529
  this.mail = new MailResource(this._client);
9493
10530
  this.hosts = new HostsResource(this._client);
9494
10531
  this.compute = new ComputeResource(this._client);
10532
+ this.studio = new StudioResource(this._client);
9495
10533
  }
9496
10534
  async getUser() {
9497
10535
  const res = await this._client.get("/api/auth/me");