iagenify 0.4.3 → 0.4.5

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
@@ -1665,10 +1665,10 @@ function cloudUsageLine(storage, usage) {
1665
1665
  const u = usage?.[storage?.service];
1666
1666
  if (!u) return "";
1667
1667
  const mine = storage.limits?.usedBytes || 0;
1668
- const base2 = (u.storages || []).find((b) => String(b.id) === String(storage.id));
1669
- const plafond = base2 ? base2.quotaBytes : u.perBaseBytes;
1668
+ const base = (u.storages || []).find((b) => String(b.id) === String(storage.id));
1669
+ const plafond = base ? base.quotaBytes : u.perBaseBytes;
1670
1670
  const plan = `(${PLAN_NAMES[usage.pack] || usage.pack} plan)`;
1671
- const plein = base2?.overQuota || !base2 && u.overQuota;
1671
+ const plein = base?.overQuota || !base && u.overQuota;
1672
1672
  if (plafond == null) {
1673
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" : ""}`;
1674
1674
  }
@@ -4119,135 +4119,6 @@ function createServiceTools() {
4119
4119
  };
4120
4120
  }
4121
4121
 
4122
- // src/resources/designTools.js
4123
- var DESIGN_TOOL_NAMES = ["design_read", "design_apply", "design_render", "design_check", "design_template"];
4124
- var fail5 = (message) => {
4125
- throw Object.assign(new Error(message), { code: "tool_error" });
4126
- };
4127
- var clip3 = (value, max = 48e3) => String(value || "").length > max ? `${String(value).slice(0, max)}
4128
- \u2026[truncated]` : String(value || "");
4129
- var projectId = (value) => {
4130
- const id = String(value || "").trim();
4131
- if (!id) fail5('"projectId" is required. Use the design project currently open in the editor.');
4132
- return id;
4133
- };
4134
- var parseOperations = (value) => {
4135
- let operations = value;
4136
- if (typeof value === "string") {
4137
- try {
4138
- operations = JSON.parse(value);
4139
- } catch (error) {
4140
- fail5(`"operations" is not valid JSON (${error.message}).`);
4141
- }
4142
- }
4143
- if (!Array.isArray(operations) || operations.length < 1 || operations.length > 100) {
4144
- fail5('"operations" must be a JSON array with 1 to 100 document operations.');
4145
- }
4146
- return operations;
4147
- };
4148
- function createDesignTools() {
4149
- return {
4150
- design_read: {
4151
- category: "read",
4152
- description: "Read the Design document of projectId. Optional node selects one subtree; otherwise return the page/frame tree, tokens, and node ids, names, types, sizes, layout and text. Call before making changes.",
4153
- parameters: {
4154
- projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
4155
- node: { type: "string", description: "An existing node id from this document" }
4156
- },
4157
- async run({ projectId: id, node: node4 }, { api }) {
4158
- const project = await api.design.projects.get(projectId(id));
4159
- const doc = await project.open();
4160
- const json = doc.toJSON();
4161
- const describe = (nodeId) => {
4162
- const item = json.nodes[nodeId];
4163
- if (!item) return null;
4164
- return {
4165
- id: nodeId,
4166
- type: item.type,
4167
- name: item.name,
4168
- size: item.size,
4169
- position: item.position,
4170
- text: item.text,
4171
- style: item.style,
4172
- layout: item.layout,
4173
- children: (item.children || []).map(describe)
4174
- };
4175
- };
4176
- if (node4) {
4177
- const item = json.nodes[node4];
4178
- if (!item) fail5(`Unknown design node id "${node4}".`);
4179
- return { output: clip3(JSON.stringify(describe(node4))), summary: `Read ${item.name || node4}`, meta: { projectId: project.id, node: node4 } };
4180
- }
4181
- const pages = json.pages.map((page) => ({ id: page.id, name: page.name, frames: page.frames.map(describe) }));
4182
- return { output: clip3(JSON.stringify({ pages, tokens: json.tokens || {}, version: project.version?.id || null })), summary: `Read ${project.label}`, meta: { projectId: project.id, pages: pages.length } };
4183
- }
4184
- },
4185
- design_apply: {
4186
- category: "write",
4187
- description: "Apply an atomic, undoable batch to the saved Design document. operations is JSON text containing 1\u2013100 set/insert/move/remove operations. Use ids from design_read. The project is version-checked; the editor receives the exact operations and new version.",
4188
- parameters: {
4189
- projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
4190
- operations: { type: "string", required: true, description: "JSON array of 1\u2013100 valid document operations" }
4191
- },
4192
- async run({ projectId: id, operations: raw }, { api }) {
4193
- const operations = parseOperations(raw);
4194
- const project = await api.design.projects.get(projectId(id));
4195
- const doc = await project.open();
4196
- const applied = doc.apply(operations, { source: "agent" });
4197
- const saved = await doc.save();
4198
- return {
4199
- output: `Applied and saved ${applied.applied} design operation${applied.applied === 1 ? "" : "s"} to ${project.label}. The open editor will receive this exact batch.`,
4200
- summary: `Updated ${project.label}`,
4201
- meta: { projectId: project.id, version: saved.version, operations, created: applied.created }
4202
- };
4203
- }
4204
- },
4205
- design_render: {
4206
- category: "read",
4207
- description: "Render one frame of a saved Design project as PNG. The PNG is attached to your context so you can inspect it visually and correct the design.",
4208
- parameters: {
4209
- projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
4210
- frame: { type: "string", description: "Frame id from design_read; omit to render the first frame" }
4211
- },
4212
- async run({ projectId: id, frame }, { api }) {
4213
- const project = await api.design.projects.get(projectId(id));
4214
- const result = await project.render({ frame });
4215
- if (!result?.image?.data) fail5("The design preview returned no image.");
4216
- return {
4217
- output: `Rendered frame ${result.image.frame || frame || "first frame"} at ${result.image.width}\xD7${result.image.height}. Inspect the attached image before changing the design again.`,
4218
- summary: "Rendered the design for visual review",
4219
- meta: { projectId: project.id, frame: result.image.frame, width: result.image.width, height: result.image.height },
4220
- attachments: [{ mime: result.image.mime || "image/png", data: result.image.data }]
4221
- };
4222
- }
4223
- },
4224
- design_check: {
4225
- category: "read",
4226
- description: "Run deterministic design checks on a saved project and report every issue with rule, severity, node and measured details.",
4227
- parameters: { projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" } },
4228
- async run({ projectId: id }, { api }) {
4229
- const project = await api.design.projects.get(projectId(id));
4230
- const doc = await project.open();
4231
- const result = doc.check();
4232
- return { output: clip3(JSON.stringify(result)), summary: `${result.issues.length} design checks reported`, meta: { projectId: project.id, issues: result.issues.length } };
4233
- }
4234
- },
4235
- design_template: {
4236
- category: "read",
4237
- description: "List available Design templates, or read one template by id including its starting document.",
4238
- parameters: { id: { type: "string", description: "Template id; omit to list templates" } },
4239
- async run({ id }, { api }) {
4240
- if (!id) {
4241
- const templates2 = await api.design.templates.list({ type: "design" });
4242
- return { output: clip3(JSON.stringify(templates2)), summary: `${templates2.length} design templates`, meta: { count: templates2.length } };
4243
- }
4244
- const template = await api.design.templates.get(id);
4245
- return { output: clip3(JSON.stringify(template)), summary: `Read template ${id}`, meta: { template: id } };
4246
- }
4247
- }
4248
- };
4249
- }
4250
-
4251
4122
  // src/resources/workspaceTools.js
4252
4123
  var MAX_OUTPUT = 6e4;
4253
4124
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", "__pycache__", ".venv"]);
@@ -4270,12 +4141,12 @@ var MEDIA_MIME = {
4270
4141
  };
4271
4142
  var EXT_FOR = { markdown: "md", text: "txt", jpeg: "jpg", base64: "txt" };
4272
4143
  var ATTACHMENT_MAX = 15 * 1024 * 1024;
4273
- var fail6 = (message) => {
4144
+ var fail5 = (message) => {
4274
4145
  throw new IaGenifyError(400, "tool_error", message);
4275
4146
  };
4276
4147
  var short = (text2 = "", max = 80) => String(text2).length > max ? `${String(text2).slice(0, max)}\u2026` : String(text2);
4277
4148
  var filled2 = (value) => typeof value === "string" && value.trim() !== "";
4278
- var clip4 = (text2, max = MAX_OUTPUT) => text2.length > max ? `${text2.slice(0, max)}
4149
+ var clip3 = (text2, max = MAX_OUTPUT) => text2.length > max ? `${text2.slice(0, max)}
4279
4150
  \u2026[truncated ${text2.length - max} characters]` : text2;
4280
4151
  var stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
4281
4152
  var isTextMime = (mime) => mime.startsWith("text/") || /json|xml|yaml|javascript|typescript/.test(mime);
@@ -4349,7 +4220,7 @@ async function backup(files, path) {
4349
4220
  }
4350
4221
  async function readText(files, path) {
4351
4222
  const file = await files.read(path);
4352
- if (typeof file.content !== "string") fail6(`"${path}" is not a text file.`);
4223
+ if (typeof file.content !== "string") fail5(`"${path}" is not a text file.`);
4353
4224
  return file.content;
4354
4225
  }
4355
4226
  var countOf = (text2, needle) => needle ? text2.split(needle).length - 1 : 0;
@@ -4407,11 +4278,11 @@ function storageArgs(args = {}) {
4407
4278
  try {
4408
4279
  parsed = JSON.parse(value);
4409
4280
  } catch (err) {
4410
- fail6(`"${name}" is not valid JSON (${err.message}). Send it as JSON text, e.g. ${shape === "array" ? "[{\u2026}]" : "{\u2026}"}.`);
4281
+ fail5(`"${name}" is not valid JSON (${err.message}). Send it as JSON text, e.g. ${shape === "array" ? "[{\u2026}]" : "{\u2026}"}.`);
4411
4282
  }
4412
4283
  }
4413
4284
  const isArray = Array.isArray(parsed);
4414
- if (shape === "array" ? !isArray : isArray || parsed === null || typeof parsed !== "object") fail6(`"${name}" must be a JSON ${shape}.`);
4285
+ if (shape === "array" ? !isArray : isArray || parsed === null || typeof parsed !== "object") fail5(`"${name}" must be a JSON ${shape}.`);
4415
4286
  return parsed;
4416
4287
  };
4417
4288
  return {
@@ -4424,25 +4295,25 @@ function storageArgs(args = {}) {
4424
4295
  documents: parse("documents", "array")
4425
4296
  };
4426
4297
  }
4427
- var requireText2 = (value, name) => typeof value === "string" && value.trim() ? value.trim() : fail6(`"${name}" is required for this action.`);
4298
+ var requireText2 = (value, name) => typeof value === "string" && value.trim() ? value.trim() : fail5(`"${name}" is required for this action.`);
4428
4299
  async function pickStorage(api, name, providers) {
4429
- if (!providers) fail6("Unknown action for this tool.");
4300
+ if (!providers) fail5("Unknown action for this tool.");
4430
4301
  const connected = (await api.storage.list()).filter((s) => s.type === "database" || s.type === "object");
4431
- if (!connected.length) fail6("No database or bucket is connected. Tell the user to connect one in Cloud.");
4302
+ if (!connected.length) fail5("No database or bucket is connected. Tell the user to connect one in Cloud.");
4432
4303
  const describe = (list) => list.map((s) => `"${s.label}" (${storageKindName(s, PROVIDER_NAMES)})`).join(", ");
4433
4304
  const byName = name ? connected.find((s) => s.id === name || s.label === name) || connected.find((s) => s.label.toLowerCase() === String(name).trim().toLowerCase()) : null;
4434
- if (name && !byName) fail6(`No connected storage named "${name}". Connected: ${describe(connected)}.`);
4305
+ if (name && !byName) fail5(`No connected storage named "${name}". Connected: ${describe(connected)}.`);
4435
4306
  const able = connected.filter((s) => providers.includes(engineOf(s)));
4436
4307
  const storage = byName || (able.length === 1 ? able[0] : null);
4437
- if (!storage) fail6(able.length ? `Several storages can do this: set "storage" to one of ${describe(able)}.` : `No connected storage supports this action (it needs ${providers.map((p) => PROVIDER_NAMES[p]).join(" or ")}). Connected: ${describe(connected)}.`);
4438
- if (!providers.includes(engineOf(storage))) fail6(`"${storage.label}" is ${storageKindName(storage, PROVIDER_NAMES)}; this action needs ${providers.map((p) => PROVIDER_NAMES[p]).join(" or ")}.`);
4308
+ if (!storage) fail5(able.length ? `Several storages can do this: set "storage" to one of ${describe(able)}.` : `No connected storage supports this action (it needs ${providers.map((p) => PROVIDER_NAMES[p]).join(" or ")}). Connected: ${describe(connected)}.`);
4309
+ if (!providers.includes(engineOf(storage))) fail5(`"${storage.label}" is ${storageKindName(storage, PROVIDER_NAMES)}; this action needs ${providers.map((p) => PROVIDER_NAMES[p]).join(" or ")}.`);
4439
4310
  return storage;
4440
4311
  }
4441
4312
  function sqlStatement(input) {
4442
4313
  const sql = String(input || "").trim().replace(/;\s*$/, "");
4443
- if (!sql) fail6('"sql" is required for this action.');
4314
+ if (!sql) fail5('"sql" is required for this action.');
4444
4315
  const bare = sql.replace(/--[^\n]*/g, " ").replace(/\/\*[\s\S]*?\*\//g, " ").replace(/'(?:[^']|'')*'/g, "''").replace(/"(?:[^"]|"")*"/g, '""');
4445
- if (bare.includes(";")) fail6("Send one SQL statement per call.");
4316
+ if (bare.includes(";")) fail5("Send one SQL statement per call.");
4446
4317
  const verb = (bare.match(/^\s*([a-z]+)/i) || [])[1]?.toUpperCase() || "";
4447
4318
  const writesInside = /\b(INSERT|UPDATE|DELETE|REPLACE|CREATE|ALTER|DROP)\b/i.test(bare);
4448
4319
  const read = ["SELECT", "EXPLAIN"].includes(verb) && !writesInside || verb === "WITH" && !writesInside || verb === "PRAGMA" && !bare.includes("=");
@@ -4457,28 +4328,28 @@ async function checkStorageWrite(rawArgs = {}, { api, mode } = {}) {
4457
4328
  const emptyFilter = !args.filter || !Object.keys(args.filter).length;
4458
4329
  let statement = null;
4459
4330
  if (["insert", "update", "delete"].includes(action)) requireText2(args.collection, "collection");
4460
- if (action === "insert" && (!Array.isArray(args.documents) || !args.documents.length || args.documents.length > 500)) fail6("insert needs documents: a list of 1 to 500 objects.");
4331
+ if (action === "insert" && (!Array.isArray(args.documents) || !args.documents.length || args.documents.length > 500)) fail5("insert needs documents: a list of 1 to 500 objects.");
4461
4332
  if (action === "update") {
4462
- if (emptyFilter && args.all !== true) fail6("update with an empty filter would change every document. Add a filter, or all: true if that is really what the user wants.");
4463
- if (!args.update || !Object.keys(args.update).length || !Object.keys(args.update).every((k) => k.startsWith("$"))) fail6('update needs operators such as {"$set":{"field":"value"}}, not a whole document.');
4333
+ if (emptyFilter && args.all !== true) fail5("update with an empty filter would change every document. Add a filter, or all: true if that is really what the user wants.");
4334
+ if (!args.update || !Object.keys(args.update).length || !Object.keys(args.update).every((k) => k.startsWith("$"))) fail5('update needs operators such as {"$set":{"field":"value"}}, not a whole document.');
4464
4335
  }
4465
- if (action === "delete" && emptyFilter && args.all !== true) fail6("delete with an empty filter would remove every document. Add a filter, or all: true if that is really what the user wants.");
4336
+ if (action === "delete" && emptyFilter && args.all !== true) fail5("delete with an empty filter would remove every document. Add a filter, or all: true if that is really what the user wants.");
4466
4337
  if (action === "sql") {
4467
4338
  statement = sqlStatement(args.sql);
4468
- if (statement.read) fail6('This statement only reads: use query_storage with action "sql".');
4469
- if (!statement.write) fail6(`write_storage runs INSERT, UPDATE, DELETE, REPLACE, CREATE, ALTER or DROP \u2014 not ${statement.verb || "this statement"}.`);
4470
- if (statement.drop && mode?.() !== "full") fail6("DROP is only allowed in Full access mode. Ask the user to switch mode if they really want to drop it.");
4471
- if (statement.unbounded && args.all !== true) fail6(`${statement.verb} without WHERE would touch every row. Add a WHERE clause, or all: true if that is really what the user wants.`);
4339
+ if (statement.read) fail5('This statement only reads: use query_storage with action "sql".');
4340
+ if (!statement.write) fail5(`write_storage runs INSERT, UPDATE, DELETE, REPLACE, CREATE, ALTER or DROP \u2014 not ${statement.verb || "this statement"}.`);
4341
+ if (statement.drop && mode?.() !== "full") fail5("DROP is only allowed in Full access mode. Ask the user to switch mode if they really want to drop it.");
4342
+ if (statement.unbounded && args.all !== true) fail5(`${statement.verb} without WHERE would touch every row. Add a WHERE clause, or all: true if that is really what the user wants.`);
4472
4343
  }
4473
4344
  if (action === "put") {
4474
4345
  requireText2(args.key, "key");
4475
- if (args.content == null && !args.path) fail6("put needs content (text) or path (a workspace file).");
4346
+ if (args.content == null && !args.path) fail5("put needs content (text) or path (a workspace file).");
4476
4347
  }
4477
4348
  if (action === "remove") requireText2(args.key, "key");
4478
4349
  if (action === "create_collection") requireText2(args.collection, "collection");
4479
4350
  if (action === "drop_collection") {
4480
4351
  requireText2(args.collection, "collection");
4481
- if (mode?.() !== "full") fail6("drop_collection removes a collection and every document in it: it is only allowed in Full access mode. Ask the user to switch mode if they really want to drop it.");
4352
+ if (mode?.() !== "full") fail5("drop_collection removes a collection and every document in it: it is only allowed in Full access mode. Ask the user to switch mode if they really want to drop it.");
4482
4353
  }
4483
4354
  return { db, statement, args };
4484
4355
  }
@@ -4492,7 +4363,7 @@ function createWorkspaceTools({ client }) {
4492
4363
  if (typeof text2 !== "string" && attachMime) {
4493
4364
  if (file.size > ATTACHMENT_MAX) {
4494
4365
  const advice = /^(audio|video)\//.test(attachMime) ? ` Convert it to a lighter form first \u2014 convert { path: "${file.path}", to: "mp3" } keeps the sound and drops the weight.` : " Ask the user for a smaller version.";
4495
- fail6(`"${file.path}" is ${(file.size / 1048576).toFixed(1)} MB; files over ${ATTACHMENT_MAX / 1048576} MB cannot be attached.${advice}`);
4366
+ fail5(`"${file.path}" is ${(file.size / 1048576).toFixed(1)} MB; files over ${ATTACHMENT_MAX / 1048576} MB cannot be attached.${advice}`);
4496
4367
  }
4497
4368
  const kind = attachMime.startsWith("audio/") ? "Listen to it" : attachMime.startsWith("video/") ? "Watch it" : "Read it";
4498
4369
  return {
@@ -4506,7 +4377,7 @@ function createWorkspaceTools({ client }) {
4506
4377
  if (CONVERTIBLE[ext]) {
4507
4378
  const converted = await convert.convert({ from: ext, to: CONVERTIBLE[ext], file: file.content });
4508
4379
  text2 = String(converted.content ?? converted.markdown ?? converted.text ?? "");
4509
- if (!text2) fail6(`Could not extract text from "${path}".`);
4380
+ if (!text2) fail5(`Could not extract text from "${path}".`);
4510
4381
  } else {
4511
4382
  return { output: `"${file.path}" is a binary file (${file.mimeType}, ${file.size} bytes) and has no text to read.`, summary: `${file.path} (binary)`, meta: { path: file.path } };
4512
4383
  }
@@ -4517,7 +4388,7 @@ function createWorkspaceTools({ client }) {
4517
4388
  const numbered = slice.map((l, i) => `${start + i} ${l.length > 2e3 ? `${l.slice(0, 2e3)}\u2026` : l}`).join("\n");
4518
4389
  const more = start - 1 + slice.length < lines.length ? `
4519
4390
  \u2026[${lines.length - (start - 1 + slice.length)} more lines \u2014 use offset]` : "";
4520
- return { output: clip4(numbered + more) || "(empty file)", summary: `${file.path} \xB7 ${lines.length} lines`, meta: { path: file.path, lines: lines.length } };
4391
+ return { output: clip3(numbered + more) || "(empty file)", summary: `${file.path} \xB7 ${lines.length} lines`, meta: { path: file.path, lines: lines.length } };
4521
4392
  }
4522
4393
  const search = new SearchResource(client);
4523
4394
  const fetchPage = new FetchResource(client);
@@ -4526,7 +4397,6 @@ function createWorkspaceTools({ client }) {
4526
4397
  ...createPlatformTools(),
4527
4398
  // P54 : les services de la plateforme — hébergement, courrier, domaines, compte, documents, second modèle.
4528
4399
  ...createServiceTools(),
4529
- ...createDesignTools(),
4530
4400
  read: {
4531
4401
  category: "read",
4532
4402
  description: "Read any file in the workspace and SEE it: text and code as numbered lines (use offset/limit for long files); PDFs (including scanned ones), images, audio and video are attached so you read, hear and watch them directly, like a person would; DOCX, PPTX and XLSX are converted to text. This is the only tool you need to understand a document, a recording or a clip \u2014 never write scripts to parse file formats, and never look for a transcription tool: read the file.",
@@ -4538,8 +4408,8 @@ function createWorkspaceTools({ client }) {
4538
4408
  },
4539
4409
  async run({ path, paths, offset = 1, limit = 2e3 }, context) {
4540
4410
  const liste = Array.isArray(paths) && paths.length ? paths.map((p) => String(p)) : [String(path ?? "")];
4541
- if (!filled2(liste[0])) fail6('Give "path" (one file) or "paths" (several).');
4542
- if (liste.length > 20) fail6(`A single call reads at most 20 files (got ${liste.length}).`);
4411
+ if (!filled2(liste[0])) fail5('Give "path" (one file) or "paths" (several).');
4412
+ if (liste.length > 20) fail5(`A single call reads at most 20 files (got ${liste.length}).`);
4543
4413
  if (liste.length === 1) return lireFichier(liste[0], { offset, limit }, context);
4544
4414
  const lus = [];
4545
4415
  const pieces2 = [];
@@ -4555,7 +4425,7 @@ Error: ${err.message}`);
4555
4425
  }
4556
4426
  }
4557
4427
  return {
4558
- output: clip4(lus.join("\n\n"), 6e4),
4428
+ output: clip3(lus.join("\n\n"), 6e4),
4559
4429
  summary: `${liste.length} files`,
4560
4430
  meta: { paths: liste, attached: pieces2.length || void 0 },
4561
4431
  ...pieces2.length ? { attachments: pieces2 } : {}
@@ -4592,7 +4462,7 @@ Error: ${err.message}`);
4592
4462
  try {
4593
4463
  re = new RegExp(pattern, ignore_case ? "i" : "");
4594
4464
  } catch (err) {
4595
- fail6(`Invalid regular expression: ${err.message}`);
4465
+ fail5(`Invalid regular expression: ${err.message}`);
4596
4466
  }
4597
4467
  const only = glob ? globToRegExp(glob) : null;
4598
4468
  const hits = [];
@@ -4626,8 +4496,8 @@ Error: ${err.message}`);
4626
4496
  async run({ path, old_string, new_string, replace_all = false }, { files }) {
4627
4497
  const before = await readText(files, path);
4628
4498
  const count = countOf(before, old_string);
4629
- if (!count) fail6(`old_string was not found in "${path}". Read the file and copy the text exactly.`);
4630
- if (count > 1 && !replace_all) fail6(`old_string appears ${count} times in "${path}". Add surrounding lines to make it unique, or set replace_all.`);
4499
+ if (!count) fail5(`old_string was not found in "${path}". Read the file and copy the text exactly.`);
4500
+ if (count > 1 && !replace_all) fail5(`old_string appears ${count} times in "${path}". Add surrounding lines to make it unique, or set replace_all.`);
4631
4501
  const after = replace_all ? before.split(old_string).join(new_string) : before.replace(old_string, () => new_string);
4632
4502
  await backup(files, path);
4633
4503
  await files.write(path, after);
@@ -4651,8 +4521,8 @@ Error: ${err.message}`);
4651
4521
  const diffs = [];
4652
4522
  edits.forEach((e, i) => {
4653
4523
  const count = countOf(text2, e.old_string);
4654
- if (!count) fail6(`Edit ${i + 1}: old_string not found in "${path}". Nothing was changed.`);
4655
- if (count > 1 && !e.replace_all) fail6(`Edit ${i + 1}: old_string appears ${count} times. Nothing was changed.`);
4524
+ if (!count) fail5(`Edit ${i + 1}: old_string not found in "${path}". Nothing was changed.`);
4525
+ if (count > 1 && !e.replace_all) fail5(`Edit ${i + 1}: old_string appears ${count} times. Nothing was changed.`);
4656
4526
  diffs.push(diffOf(text2, e.old_string, e.new_string));
4657
4527
  text2 = e.replace_all ? text2.split(e.old_string).join(e.new_string) : text2.replace(e.old_string, () => e.new_string);
4658
4528
  });
@@ -4696,17 +4566,17 @@ Error: ${err.message}`);
4696
4566
  // Refusé avant toute permission, en disant comment faire.
4697
4567
  check({ command = "", commands, background } = {}, { shell, terminals } = {}) {
4698
4568
  if (commands !== void 0) {
4699
- if (!Array.isArray(commands) || !commands.length) fail6('"commands" must be a list of shell commands, e.g. ["npm ci", "npm run build"].');
4700
- if (commands.some((c) => typeof c !== "string" || !c.trim())) fail6('Every entry of "commands" must be a non-empty command.');
4701
- if (commands.length > 20) fail6(`A single call runs at most 20 commands (got ${commands.length}).`);
4702
- if (background === true) fail6("background: true runs ONE command in a terminal. Use command, not commands \u2014 or run the sequence without background.");
4569
+ if (!Array.isArray(commands) || !commands.length) fail5('"commands" must be a list of shell commands, e.g. ["npm ci", "npm run build"].');
4570
+ if (commands.some((c) => typeof c !== "string" || !c.trim())) fail5('Every entry of "commands" must be a non-empty command.');
4571
+ if (commands.length > 20) fail5(`A single call runs at most 20 commands (got ${commands.length}).`);
4572
+ if (background === true) fail5("background: true runs ONE command in a terminal. Use command, not commands \u2014 or run the sequence without background.");
4703
4573
  } else if (!filled2(command)) {
4704
- fail6('Give "command" (one command) or "commands" (several, run in order).');
4574
+ fail5('Give "command" (one command) or "commands" (several, run in order).');
4705
4575
  }
4706
4576
  if (background === true || !terminals) return;
4707
4577
  const text2 = [command, ...Array.isArray(commands) ? commands : []].filter(Boolean).join("\n");
4708
4578
  if (DETACHED.test(text2) && RUNTIME.test(text2)) {
4709
- fail6(`Do not detach servers or dev tools (Start-Process, Start-Job, nohup, setsid, a trailing &): they would run hidden, outside the user's terminals, where nobody can see or stop them. Run the command itself with background: true \u2014 e.g. bash { command: "cd my-app; npm run dev -- --port 5173", background: true } \u2014 then read it with terminal { action: "output" } and stop it with terminal { action: "kill" }.`);
4579
+ fail5(`Do not detach servers or dev tools (Start-Process, Start-Job, nohup, setsid, a trailing &): they would run hidden, outside the user's terminals, where nobody can see or stop them. Run the command itself with background: true \u2014 e.g. bash { command: "cd my-app; npm run dev -- --port 5173", background: true } \u2014 then read it with terminal { action: "output" } and stop it with terminal { action: "kill" }.`);
4710
4580
  }
4711
4581
  },
4712
4582
  async run({ command, commands, timeout_ms = 12e4, background = false, stop_on_error = true, port = null }, { root, signal, shell, terminals }) {
@@ -4715,7 +4585,7 @@ Error: ${err.message}`);
4715
4585
  const seule = liste[0];
4716
4586
  const auto = background !== true && Boolean(terminals) && liste.length === 1 && LONG_RUNNING.test(seule);
4717
4587
  if (background === true || auto) {
4718
- if (!terminals) fail6("Background commands need a terminal environment, and there are none here. Run the command without background.");
4588
+ if (!terminals) fail5("Background commands need a terminal environment, and there are none here. Run the command without background.");
4719
4589
  const note = auto ? "This command starts a server that never exits, so it runs in a terminal instead of blocking.\n" : "";
4720
4590
  const terminal = await terminals.create({ name: short(seule, 60), command: seule, by: "agent", ...port ? { port } : {} });
4721
4591
  const first = await settle(terminal, signal);
@@ -4724,9 +4594,9 @@ Error: ${err.message}`);
4724
4594
  const exited = first.status === "exited";
4725
4595
  const output = exited ? `Terminal ${terminal.id} (${seule}) exited with code ${first.exitCode} right away.
4726
4596
  --- output ---
4727
- ${clip4(text2, 2e4)}` : `Started terminal ${terminal.id} (${seule}). It keeps running after your answer; use terminal { action: "output", id: "${terminal.id}" } to check it and terminal { action: "kill" } to stop it.
4597
+ ${clip3(text2, 2e4)}` : `Started terminal ${terminal.id} (${seule}). It keeps running after your answer; use terminal { action: "output", id: "${terminal.id}" } to check it and terminal { action: "kill" } to stop it.
4728
4598
  --- first output ---
4729
- ${clip4(text2, 2e4) || "(nothing yet)"}`;
4599
+ ${clip3(text2, 2e4) || "(nothing yet)"}`;
4730
4600
  const adresse = terminal.url ? `
4731
4601
 
4732
4602
  Open it at: ${terminal.url}
@@ -4734,7 +4604,7 @@ If it does not answer, the server is listening on localhost instead of 0.0.0.0 \
4734
4604
  return {
4735
4605
  output: note + output + adresse,
4736
4606
  summary: `${seule.slice(0, 80)} \xB7 ${exited ? `exit ${first.exitCode}` : terminal.url || `terminal ${terminal.id}`}`,
4737
- meta: { command: seule, background: true, terminalId: terminal.id, status: first.status, exitCode: first.exitCode, stdout: clip4(text2, 4e3), url: terminal.url ?? null, port: terminal.port ?? null }
4607
+ meta: { command: seule, background: true, terminalId: terminal.id, status: first.status, exitCode: first.exitCode, stdout: clip3(text2, 4e3), url: terminal.url ?? null, port: terminal.port ?? null }
4738
4608
  };
4739
4609
  }
4740
4610
  const executer = async (cmd) => {
@@ -4786,9 +4656,9 @@ If it does not answer, the server is listening on localhost instead of 0.0.0.0 \
4786
4656
  if (liste.length === 1) {
4787
4657
  const r = await executer(seule);
4788
4658
  const output = [`exit code ${etat(r)}`, r.stdout && `--- stdout ---
4789
- ${clip4(r.stdout, 3e4)}`, r.stderr && `--- stderr ---
4790
- ${clip4(r.stderr, 3e4)}`].filter(Boolean).join("\n");
4791
- return { output, summary: `${seule.slice(0, 80)} \xB7 exit ${etat(r)}`, meta: { command: seule, exitCode: r.code, timedOut: r.timedOut, stdout: clip4(r.stdout, 4e3), stderr: clip4(r.stderr, 4e3) } };
4659
+ ${clip3(r.stdout, 3e4)}`, r.stderr && `--- stderr ---
4660
+ ${clip3(r.stderr, 3e4)}`].filter(Boolean).join("\n");
4661
+ return { output, summary: `${seule.slice(0, 80)} \xB7 exit ${etat(r)}`, meta: { command: seule, exitCode: r.code, timedOut: r.timedOut, stdout: clip3(r.stdout, 4e3), stderr: clip3(r.stderr, 4e3) } };
4792
4662
  }
4793
4663
  const faits = [];
4794
4664
  for (const cmd of liste) {
@@ -4801,9 +4671,9 @@ ${clip4(r.stderr, 3e4)}`].filter(Boolean).join("\n");
4801
4671
  const bloc = faits.map((r, i) => [
4802
4672
  `[${i + 1}/${liste.length}] ${r.cmd} \u2014 exit ${etat(r)}`,
4803
4673
  r.stdout && `--- stdout ---
4804
- ${clip4(r.stdout, part)}`,
4674
+ ${clip3(r.stdout, part)}`,
4805
4675
  r.stderr && `--- stderr ---
4806
- ${clip4(r.stderr, part)}`
4676
+ ${clip3(r.stderr, part)}`
4807
4677
  ].filter(Boolean).join("\n")).join("\n\n");
4808
4678
  const dernier = faits.at(-1);
4809
4679
  const rates = faits.filter((r) => r.timedOut || r.code !== 0).length;
@@ -4819,8 +4689,8 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
4819
4689
  exitCode: dernier ? dernier.code : null,
4820
4690
  timedOut: Boolean(dernier?.timedOut),
4821
4691
  results: faits.map((r) => ({ command: r.cmd, exitCode: r.code, timedOut: r.timedOut })),
4822
- stdout: clip4(faits.map((r) => r.stdout).filter(Boolean).join("\n"), 4e3),
4823
- stderr: clip4(faits.map((r) => r.stderr).filter(Boolean).join("\n"), 4e3)
4692
+ stdout: clip3(faits.map((r) => r.stdout).filter(Boolean).join("\n"), 4e3),
4693
+ stderr: clip3(faits.map((r) => r.stderr).filter(Boolean).join("\n"), 4e3)
4824
4694
  }
4825
4695
  };
4826
4696
  }
@@ -4837,14 +4707,14 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
4837
4707
  since: { type: "integer", description: "output: read from this position; 0 = everything kept" }
4838
4708
  },
4839
4709
  async run({ action, id, since }, { terminals }) {
4840
- if (!terminals) fail6("There are no terminals here: they only exist on a computer.");
4710
+ if (!terminals) fail5("There are no terminals here: they only exist on a computer.");
4841
4711
  if (action === "list") {
4842
4712
  const all = await terminals.list();
4843
4713
  if (!all.length) return { output: "No terminals are open.", summary: "No terminals", meta: { terminals: [] } };
4844
4714
  const lines = all.map((t) => `${t.id} \xB7 ${t.status}${t.status === "exited" ? ` (code ${t.exitCode ?? "stopped"})` : ""} \xB7 ${t.command || t.name} \xB7 cwd ${t.cwd || "."} \xB7 by ${t.by} \xB7 started ${t.startedAt}`);
4845
4715
  return { output: lines.join("\n"), summary: `${all.filter((t) => t.status === "running").length} running \xB7 ${all.length} terminals`, meta: { terminals: all } };
4846
4716
  }
4847
- if (!id) fail6(`"id" is required for ${action}. Use terminal { action: "list" } to find it.`);
4717
+ if (!id) fail5(`"id" is required for ${action}. Use terminal { action: "list" } to find it.`);
4848
4718
  const terminal = await terminals.get(id);
4849
4719
  if (action === "output") {
4850
4720
  const from = since != null ? Number(since) : terminal.agentCursor || 0;
@@ -4854,16 +4724,16 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
4854
4724
  return {
4855
4725
  output: `${terminal.id} \xB7 ${out.status}${out.status === "exited" ? ` (code ${out.exitCode ?? "stopped"})` : ""}${out.truncated ? " \xB7 older output was dropped" : ""}
4856
4726
  --- output ---
4857
- ${clip4(text2, 3e4) || "(no new output)"}`,
4727
+ ${clip3(text2, 3e4) || "(no new output)"}`,
4858
4728
  summary: `${terminal.name} \xB7 ${out.status}`,
4859
- meta: { terminalId: terminal.id, status: out.status, exitCode: out.exitCode, stdout: clip4(text2, 4e3) }
4729
+ meta: { terminalId: terminal.id, status: out.status, exitCode: out.exitCode, stdout: clip3(text2, 4e3) }
4860
4730
  };
4861
4731
  }
4862
4732
  if (action === "kill") {
4863
4733
  const stopped = await terminal.kill();
4864
4734
  return { output: `Stopped terminal ${stopped.id} (${stopped.command || stopped.name}).`, summary: `Stopped ${stopped.name}`, meta: { terminalId: stopped.id, status: stopped.status } };
4865
4735
  }
4866
- fail6(`Unknown action "${action}": use list, output or kill.`);
4736
+ fail5(`Unknown action "${action}": use list, output or kill.`);
4867
4737
  }
4868
4738
  },
4869
4739
  ask_user: {
@@ -4936,7 +4806,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
4936
4806
  const shot = r.screenshot?.base64 ? { mime: r.screenshot.mimeType || "image/jpeg", data: r.screenshot.base64 } : null;
4937
4807
  if (screenshot === true && !shot) sections.push("--- screenshot ---\n(the page could not be captured as an image)");
4938
4808
  return {
4939
- output: clip4(sections.filter(Boolean).join("\n\n"), 3e4),
4809
+ output: clip3(sections.filter(Boolean).join("\n\n"), 3e4),
4940
4810
  summary: `${r.title || url}${shot ? " \xB7 seen" : ""}`,
4941
4811
  meta: { url: r.url || url, title: r.title || "", credits: r.creditsUsed ?? 1, ...shot ? { screenshot: true } : {}, ...wants.has("console") ? { consoleErrors: (r.console || []).filter((l) => l.level === "error").length } : {} },
4942
4812
  ...shot ? { attachments: [shot] } : {}
@@ -4955,12 +4825,12 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
4955
4825
  },
4956
4826
  async run({ path, url, to, save }, { files }) {
4957
4827
  const target = String(to || "").trim().toLowerCase();
4958
- if (!target) fail6('"to" is required: the format to convert into, e.g. "pdf".');
4959
- if (!filled2(path) && !filled2(url)) fail6('Give "path" (a workspace file) or "url".');
4960
- if (filled2(path) && filled2(url)) fail6('Give "path" or "url", not both.');
4828
+ if (!target) fail5('"to" is required: the format to convert into, e.g. "pdf".');
4829
+ if (!filled2(path) && !filled2(url)) fail5('Give "path" (a workspace file) or "url".');
4830
+ if (filled2(path) && filled2(url)) fail5('Give "path" or "url", not both.');
4961
4831
  const sourceName = filled2(path) ? String(path) : new URL(String(url)).pathname.split("/").filter(Boolean).pop() || "page";
4962
4832
  const from = sourceName.includes(".") ? sourceName.split(".").pop().toLowerCase() : "";
4963
- if (!from) fail6(`Cannot tell the format of "${sourceName}": the name has no extension.`);
4833
+ if (!from) fail5(`Cannot tell the format of "${sourceName}": the name has no extension.`);
4964
4834
  let result;
4965
4835
  if (filled2(path)) {
4966
4836
  const file = await files.read(path);
@@ -4969,11 +4839,11 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
4969
4839
  } else {
4970
4840
  result = await convert.convert({ from, to: target, url: String(url) });
4971
4841
  }
4972
- if (!result?.ok) fail6(result?.message || `Conversion ${from} \u2192 ${target} failed.`);
4842
+ if (!result?.ok) fail5(result?.message || `Conversion ${from} \u2192 ${target} failed.`);
4973
4843
  const data = result.content !== void 0 ? String(result.content) : Buffer.from(result.base64 || "", "base64");
4974
4844
  const ext = EXT_FOR[target] || target;
4975
- const base2 = sourceName.replace(/\.[^.]+$/, "");
4976
- const destination = filled2(save) ? String(save) : filled2(path) ? `${base2}.${ext}` : `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${base2}.${ext}`;
4845
+ const base = sourceName.replace(/\.[^.]+$/, "");
4846
+ const destination = filled2(save) ? String(save) : filled2(path) ? `${base}.${ext}` : `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${base}.${ext}`;
4977
4847
  const written = await files.write(destination, data);
4978
4848
  return {
4979
4849
  output: `Converted ${sourceName} (${from} \u2192 ${target}) to ${written.path} \u2014 ${Math.round(written.size / 1024)} KB, ${result.creditsUsed ?? 1} credit.`,
@@ -5050,7 +4920,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
5050
4920
  const usage = await api.cloud.usage();
5051
4921
  if (!args.storage) return { output: cloudUsageReport(usage), summary: "IaGenify Cloud \xB7 usage", meta: { action, storage: null } };
5052
4922
  const target2 = await pickStorage(api, args.storage, STORAGE_READS.usage);
5053
- if (!target2.service) fail6(`"${target2.label}" is a connected storage: its space is managed by its own provider. usage only reports IaGenify Cloud storages.`);
4923
+ if (!target2.service) fail5(`"${target2.label}" is a connected storage: its space is managed by its own provider. usage only reports IaGenify Cloud storages.`);
5054
4924
  return { output: cloudUsageReport(usage, target2), summary: `${target2.label} \xB7 usage`, meta: { storage: target2.label, provider: target2.provider, action } };
5055
4925
  }
5056
4926
  const db = await pickStorage(api, args.storage, STORAGE_READS[action]);
@@ -5058,7 +4928,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
5058
4928
  if (action === "overview") {
5059
4929
  const seen = await db.run({ action: "overview" });
5060
4930
  return {
5061
- output: clip4(overviewReport(db, seen), 3e4),
4931
+ output: clip3(overviewReport(db, seen), 3e4),
5062
4932
  summary: `${db.label} \xB7 overview`,
5063
4933
  meta: { storage: db.label, provider: db.provider, action, returned: (seen.collections || seen.tables || seen.folders || []).length }
5064
4934
  };
@@ -5074,13 +4944,13 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
5074
4944
  });
5075
4945
  } else if (action === "count") result = await db.run({ action: "count", collection: requireText2(args.collection, "collection"), filter: args.filter || {} });
5076
4946
  else if (action === "aggregate") {
5077
- if (!Array.isArray(args.pipeline) || !args.pipeline.length) fail6('aggregate needs a pipeline: a list of stages such as [{"$group":{"_id":"$model","total":{"$sum":"$credits"}}}].');
5078
- if (/"\$(out|merge)"/.test(JSON.stringify(args.pipeline))) fail6("aggregate is read-only: $out and $merge are not allowed.");
4947
+ if (!Array.isArray(args.pipeline) || !args.pipeline.length) fail5('aggregate needs a pipeline: a list of stages such as [{"$group":{"_id":"$model","total":{"$sum":"$credits"}}}].');
4948
+ if (/"\$(out|merge)"/.test(JSON.stringify(args.pipeline))) fail5("aggregate is read-only: $out and $merge are not allowed.");
5079
4949
  result = await db.run({ action: "aggregate", collection: requireText2(args.collection, "collection"), pipeline: args.pipeline });
5080
4950
  } else if (action === "tables") result = await db.run({ action: "tables" });
5081
4951
  else if (action === "sql") {
5082
4952
  const statement = sqlStatement(args.sql);
5083
- if (!statement.read) fail6(`query_storage only runs SELECT, WITH, PRAGMA or EXPLAIN. To change data (${statement.verb || "this statement"}), use write_storage with action "sql".`);
4953
+ if (!statement.read) fail5(`query_storage only runs SELECT, WITH, PRAGMA or EXPLAIN. To change data (${statement.verb || "this statement"}), use write_storage with action "sql".`);
5084
4954
  result = await db.run({ sql: statement.sql, params: Array.isArray(args.params) ? args.params : [] });
5085
4955
  } else if (action === "objects") result = await db.run({ action: "list", prefix: String(args.prefix || "") });
5086
4956
  else if (action === "object") result = await db.run({ action: "object", key: requireText2(args.key, "key") });
@@ -5095,7 +4965,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
5095
4965
  };
5096
4966
  }
5097
4967
  return {
5098
- output: clip4(results.map((r, i) => `[${i + 1}] ${r.source?.name || "document"} \xB7 ${r.score}
4968
+ output: clip3(results.map((r, i) => `[${i + 1}] ${r.source?.name || "document"} \xB7 ${r.score}
5099
4969
  ${r.text}`).join("\n\n"), 3e4),
5100
4970
  summary: `${db.label} \xB7 ${results.length} extract${results.length === 1 ? "" : "s"}`,
5101
4971
  meta: { storage: db.label, provider: db.provider, action, credits: found.creditsUsed ?? 1, returned: results.length, scanned: found.scanned ?? null, sources: [...new Set(results.map((r) => r.source?.name).filter(Boolean))] }
@@ -5149,7 +5019,7 @@ ${r.text}`).join("\n\n"), 3e4),
5149
5019
  else if (action === "drop_collection") result = await db.run({ action: "dropCollection", collection: args.collection.trim() });
5150
5020
  const target = args.collection || args.key || (args.sql ? String(args.sql).trim().split(/\s+/).slice(0, 3).join(" ") : "");
5151
5021
  return {
5152
- output: clip4(JSON.stringify(result, null, 1), 3e4),
5022
+ output: clip3(JSON.stringify(result, null, 1), 3e4),
5153
5023
  summary: `${db.label} \xB7 ${action}${target ? ` ${target}` : ""}`,
5154
5024
  meta: { storage: db.label, provider: db.provider, action, collection: args.collection || null, result }
5155
5025
  };
@@ -5220,28 +5090,28 @@ var MEDIA = {
5220
5090
  // produire doit se dire tout de suite, pas revenir en erreur du fournisseur une fois payé.
5221
5091
  verify: (a, model) => {
5222
5092
  if (OMNI_MODELS.includes(model)) {
5223
- if (a.audio === true) fail6(`"${model}" has no sound option. Use veo-3.1 for sound.`);
5093
+ if (a.audio === true) fail5(`"${model}" has no sound option. Use veo-3.1 for sound.`);
5224
5094
  if (a.duration !== void 0 && a.duration !== null && a.duration !== "") {
5225
5095
  const d = Number(a.duration);
5226
5096
  if (!Number.isFinite(d) || d < OMNI_SECONDS.min || d > OMNI_SECONDS.max) {
5227
- fail6(`"${model}" makes videos of ${OMNI_SECONDS.min} to ${OMNI_SECONDS.max} seconds (the provider's limit); you asked for ${a.duration}.`);
5097
+ fail5(`"${model}" makes videos of ${OMNI_SECONDS.min} to ${OMNI_SECONDS.max} seconds (the provider's limit); you asked for ${a.duration}.`);
5228
5098
  }
5229
5099
  }
5230
5100
  const permises = VIDEO_RESOLUTIONS[model] || [];
5231
5101
  if (filled2(a.resolution) && !permises.includes(a.resolution)) {
5232
- fail6(`"${model}" has no ${a.resolution}. It does ${permises.join(", ")}.`);
5102
+ fail5(`"${model}" has no ${a.resolution}. It does ${permises.join(", ")}.`);
5233
5103
  }
5234
5104
  return;
5235
5105
  }
5236
5106
  if (a.audio === true && !VIDEO_WITH_AUDIO.includes(model)) {
5237
- fail6(`"${model}" makes no sound. Only ${VIDEO_WITH_AUDIO.join(", ")} does \u2014 pass model: "veo-3.1", or leave audio out.`);
5107
+ fail5(`"${model}" makes no sound. Only ${VIDEO_WITH_AUDIO.join(", ")} does \u2014 pass model: "veo-3.1", or leave audio out.`);
5238
5108
  }
5239
5109
  if (a.duration !== void 0 && a.duration !== null && !VIDEO_DURATIONS.includes(Number(a.duration))) {
5240
- fail6(`duration must be ${VIDEO_DURATIONS.join(", ")} seconds; you asked for ${a.duration}.`);
5110
+ fail5(`duration must be ${VIDEO_DURATIONS.join(", ")} seconds; you asked for ${a.duration}.`);
5241
5111
  }
5242
5112
  const allowed = VIDEO_RESOLUTIONS[model] || [];
5243
5113
  if (filled2(a.resolution) && !allowed.includes(a.resolution)) {
5244
- fail6(`"${model}" has no ${a.resolution}. It does ${allowed.join(", ")} \u2014 change the resolution, or pick another model.`);
5114
+ fail5(`"${model}" has no ${a.resolution}. It does ${allowed.join(", ")} \u2014 change the resolution, or pick another model.`);
5245
5115
  }
5246
5116
  },
5247
5117
  // Omni : seulement ce qui a été demandé — sans durée, le modèle fait ses 10 s par défaut, et un
@@ -5330,7 +5200,7 @@ function createMediaTools({ client, media = {} }) {
5330
5200
  const args = fusionner(spec, media[MEDIA_KINDS[name]] || {}, brut);
5331
5201
  const model = filled2(args.model) ? args.model : spec.model;
5332
5202
  if (!spec.models.includes(model)) {
5333
- fail6(`${name} has no model "${args.model}". Available: ${spec.models.join(", ")}.`);
5203
+ fail5(`${name} has no model "${args.model}". Available: ${spec.models.join(", ")}.`);
5334
5204
  }
5335
5205
  if (spec.verify) spec.verify(args, model);
5336
5206
  },
@@ -5342,15 +5212,15 @@ function createMediaTools({ client, media = {} }) {
5342
5212
  if (spec.from && filled2(image)) {
5343
5213
  const source = await files.read(String(image));
5344
5214
  const mime = /^image\//.test(source.mimeType || "") ? source.mimeType : mimeOf(String(image));
5345
- if (!mime || !mime.startsWith("image/")) fail6(`"${source.path}" is not an image (${source.mimeType || "unknown type"}).`);
5346
- if (source.size > ATTACHMENT_MAX) fail6(`"${source.path}" is ${(source.size / 1048576).toFixed(1)} MB; the starting image must be under ${ATTACHMENT_MAX / 1048576} MB.`);
5215
+ if (!mime || !mime.startsWith("image/")) fail5(`"${source.path}" is not an image (${source.mimeType || "unknown type"}).`);
5216
+ if (source.size > ATTACHMENT_MAX) fail5(`"${source.path}" is ${(source.size / 1048576).toFixed(1)} MB; the starting image must be under ${ATTACHMENT_MAX / 1048576} MB.`);
5347
5217
  inputs.push({ type: "image", content: Buffer.from(source.content).toString("base64"), mime });
5348
5218
  }
5349
5219
  const session = await models.create({ model, settings: spec.settings(args, model), memory: false });
5350
5220
  try {
5351
5221
  const result = await session.generate({ inputs, outputs: [{ type: spec.output }] });
5352
5222
  const output = result.outputs?.find((o) => o.content);
5353
- if (!output) fail6(`The ${spec.type} model returned nothing.`);
5223
+ if (!output) fail5(`The ${spec.type} model returned nothing.`);
5354
5224
  const ext = output.mime?.split("/")[1]?.split(";")[0]?.replace("mpeg", "mp3") || spec.ext;
5355
5225
  const target = path || `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${Date.now()}.${ext}`;
5356
5226
  const item = await files.write(target, Buffer.from(output.content, "base64"));
@@ -5367,10 +5237,10 @@ function createMediaTools({ client, media = {} }) {
5367
5237
  }
5368
5238
  }]));
5369
5239
  }
5370
- var WORKSPACE_TOOL_NAMES = ["read", "list", "glob", "grep", "write", "edit", "multi_edit", "move", "delete", "bash", "terminal", "todo_write", "ask_user", "search", "fetch", "convert", "account", "query_storage", "write_storage", "memory", "recall", ...PLATFORM_TOOL_NAMES, ...SERVICE_TOOL_NAMES, ...DESIGN_TOOL_NAMES, ...Object.keys(MEDIA)];
5240
+ var WORKSPACE_TOOL_NAMES = ["read", "list", "glob", "grep", "write", "edit", "multi_edit", "move", "delete", "bash", "terminal", "todo_write", "ask_user", "search", "fetch", "convert", "account", "query_storage", "write_storage", "memory", "recall", ...PLATFORM_TOOL_NAMES, ...SERVICE_TOOL_NAMES, ...Object.keys(MEDIA)];
5371
5241
 
5372
5242
  // src/resources/prompt.js
5373
- var fail7 = (code, message) => new IaGenifyError(400, code, message);
5243
+ var fail6 = (code, message) => new IaGenifyError(400, code, message);
5374
5244
  var PROMPT_OPTIONS = {
5375
5245
  model: "text",
5376
5246
  mode: ["ask", "auto", "plan", "full"],
@@ -5393,8 +5263,8 @@ function storageIndex(storages = []) {
5393
5263
  const byProvider = /* @__PURE__ */ new Map();
5394
5264
  for (const s of storages) {
5395
5265
  if (!s) continue;
5396
- const slug2 = storageSlug(s.label || s.name);
5397
- if (slug2) index.set(slug2, s);
5266
+ const slug = storageSlug(s.label || s.name);
5267
+ if (slug) index.set(slug, s);
5398
5268
  if (s.provider) byProvider.set(s.provider, [...byProvider.get(s.provider) || [], s]);
5399
5269
  }
5400
5270
  for (const [provider, list] of byProvider) if (list.length === 1 && !index.has(provider)) index.set(provider, list[0]);
@@ -5411,26 +5281,26 @@ function parsePrompt(input, library = {}) {
5411
5281
  if (!flag) break;
5412
5282
  const key = flag[1].toLowerCase();
5413
5283
  const kind = PROMPT_OPTIONS[key];
5414
- if (!kind) throw fail7("unknown_option", `Unknown option --${key}. Options: ${Object.keys(PROMPT_OPTIONS).map((k) => `--${k}`).join(" ")}. Write \\-- to start a message with "--".`);
5284
+ if (!kind) throw fail6("unknown_option", `Unknown option --${key}. Options: ${Object.keys(PROMPT_OPTIONS).map((k) => `--${k}`).join(" ")}. Write \\-- to start a message with "--".`);
5415
5285
  rest = rest.slice(flag[0].length);
5416
5286
  if (kind === "flag") {
5417
5287
  if (key === "no-memory") options.memory = false;
5418
5288
  continue;
5419
5289
  }
5420
5290
  const found = rest.match(/^(?:=|[ \t]+)("([^"]*)"|'([^']*)'|\S+)/);
5421
- if (!found) throw fail7("option_value_required", `--${key} needs a value.`);
5291
+ if (!found) throw fail6("option_value_required", `--${key} needs a value.`);
5422
5292
  const value = found[2] ?? found[3] ?? found[1];
5423
5293
  rest = rest.slice(found[0].length);
5424
5294
  if (key === "mode") {
5425
- if (!kind.includes(value)) throw fail7("invalid_option", `--mode must be one of ${kind.join(", ")}.`);
5295
+ if (!kind.includes(value)) throw fail6("invalid_option", `--mode must be one of ${kind.join(", ")}.`);
5426
5296
  options.mode = value;
5427
5297
  } else if (key === "budget") {
5428
5298
  if (value === "none") options.budget = null;
5429
5299
  else if (Number(value) > 0) options.budget = Math.round(Number(value));
5430
- else throw fail7("invalid_option", "--budget takes a number of credits, or none.");
5300
+ else throw fail6("invalid_option", "--budget takes a number of credits, or none.");
5431
5301
  } else if (key === "context") {
5432
5302
  const tokens = parseTokenCount(value);
5433
- if (!tokens) throw fail7("invalid_option", "--context takes a number of tokens: 200k, 400k, 1M.");
5303
+ if (!tokens) throw fail6("invalid_option", "--context takes a number of tokens: 200k, 400k, 1M.");
5434
5304
  options.contextTokens = tokens;
5435
5305
  } else {
5436
5306
  options[key] = value;
@@ -5471,7 +5341,7 @@ function parsePrompt(input, library = {}) {
5471
5341
  }
5472
5342
 
5473
5343
  // src/resources/library.js
5474
- var fail8 = (status, code, message) => new IaGenifyError(status, code, message);
5344
+ var fail7 = (status, code, message) => new IaGenifyError(status, code, message);
5475
5345
  var NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
5476
5346
  var MAX_CONTENT = 1e5;
5477
5347
  var CLAUDE_TOOLS = { ls: "list", websearch: "search", webfetch: "fetch", multiedit: "multi_edit", todowrite: "todo_write" };
@@ -5553,34 +5423,34 @@ var LocalLibrary = class {
5553
5423
  }
5554
5424
  async _ready() {
5555
5425
  if (typeof process === "undefined" || !process.versions?.node) {
5556
- throw fail8(400, "local_files_require_node", "A computer's skills and subagents live on its disk: that source is only available from Node.js. The account's own are available everywhere.");
5426
+ throw fail7(400, "local_files_require_node", "A computer's skills and subagents live on its disk: that source is only available from Node.js. The account's own are available everywhere.");
5557
5427
  }
5558
5428
  if (this.storage && this.storage.type !== "filesystem") {
5559
- throw fail8(400, "storage_not_local", `\xAB ${this.storage.label} \xBB n'est pas un stockage ordinateur : ses ${this.kind} ne sont pas sur un disque.`);
5429
+ throw fail7(400, "storage_not_local", `\xAB ${this.storage.label} \xBB n'est pas un stockage ordinateur : ses ${this.kind} ne sont pas sur un disque.`);
5560
5430
  }
5561
5431
  if (this.storage?.machineId && this.storage.machineId !== await getMachineId()) {
5562
- throw fail8(409, "storage_not_on_this_machine", `\xAB ${this.storage.label} \xBB belongs to another computer: its ${this.kind} stay there.`);
5432
+ throw fail7(409, "storage_not_on_this_machine", `\xAB ${this.storage.label} \xBB belongs to another computer: its ${this.kind} stay there.`);
5563
5433
  }
5564
5434
  const { fs, path, os } = await node3();
5565
- const base2 = this.root || path.join(os.homedir(), ".iagenify");
5566
- const dir = path.join(base2, this.spec.folder);
5435
+ const base = this.root || path.join(os.homedir(), ".iagenify");
5436
+ const dir = path.join(base, this.spec.folder);
5567
5437
  await fs.mkdir(dir, { recursive: true, mode: 448 });
5568
- return { fs, path, base: base2, dir };
5438
+ return { fs, path, base, dir };
5569
5439
  }
5570
5440
  _file(path, dir, name) {
5571
5441
  return this.kind === "skills" ? path.join(dir, name, "SKILL.md") : path.join(dir, `${name}.md`);
5572
5442
  }
5573
5443
  _checkName(name) {
5574
5444
  if (typeof name !== "string" || !NAME.test(name)) {
5575
- throw fail8(400, "invalid_name", `A ${this.spec.label} name uses lowercase letters, digits and dashes (e.g. "legal-review"), 64 characters at most.`);
5445
+ throw fail7(400, "invalid_name", `A ${this.spec.label} name uses lowercase letters, digits and dashes (e.g. "legal-review"), 64 characters at most.`);
5576
5446
  }
5577
5447
  }
5578
5448
  /** Un élément lu sur disque : { name, description, …, content, builtIn: false }. */
5579
5449
  _fromFile(name, text2, extra = {}) {
5580
5450
  const { data, body } = parseFrontmatter(text2);
5581
- const base2 = { name, description: String(data.description || "").trim(), builtIn: false };
5582
- if (this.kind === "subagents") Object.assign(base2, { tools: normalizeTools(data.tools), model: normalizeModel(data.model) });
5583
- return { ...base2, ...extra, content: body };
5451
+ const base = { name, description: String(data.description || "").trim(), builtIn: false };
5452
+ if (this.kind === "subagents") Object.assign(base, { tools: normalizeTools(data.tools), model: normalizeModel(data.model) });
5453
+ return { ...base, ...extra, content: body };
5584
5454
  }
5585
5455
  _builtIn(name) {
5586
5456
  const item = this.spec.builtIns[name];
@@ -5616,7 +5486,7 @@ var LocalLibrary = class {
5616
5486
  try {
5617
5487
  text2 = await fs.readFile(file, "utf8");
5618
5488
  } catch (err) {
5619
- if (err.code === "ENOENT") throw fail8(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
5489
+ if (err.code === "ENOENT") throw fail7(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
5620
5490
  throw err;
5621
5491
  }
5622
5492
  if (this.kind !== "skills") return this._fromFile(name, text2);
@@ -5640,10 +5510,10 @@ var LocalLibrary = class {
5640
5510
  async save(item = {}) {
5641
5511
  const { name, description, content } = item;
5642
5512
  this._checkName(name);
5643
- if (this.spec.builtIns[name]) throw fail8(409, "name_reserved", `"${name}" is a built-in ${this.spec.label}; choose another name.`);
5644
- if (typeof description !== "string" || !description.trim()) throw fail8(400, "description_required", `A ${this.spec.label} needs a description: it is how the agent knows when to use it.`);
5645
- if (typeof content !== "string" || !content.trim()) throw fail8(400, "content_required", `A ${this.spec.label} needs instructions (content).`);
5646
- if (content.length > MAX_CONTENT) throw fail8(400, "content_too_long", `Instructions are limited to ${MAX_CONTENT.toLocaleString("en")} characters.`);
5513
+ if (this.spec.builtIns[name]) throw fail7(409, "name_reserved", `"${name}" is a built-in ${this.spec.label}; choose another name.`);
5514
+ if (typeof description !== "string" || !description.trim()) throw fail7(400, "description_required", `A ${this.spec.label} needs a description: it is how the agent knows when to use it.`);
5515
+ if (typeof content !== "string" || !content.trim()) throw fail7(400, "content_required", `A ${this.spec.label} needs instructions (content).`);
5516
+ if (content.length > MAX_CONTENT) throw fail7(400, "content_too_long", `Instructions are limited to ${MAX_CONTENT.toLocaleString("en")} characters.`);
5647
5517
  const data = { name, description: description.trim().replace(/\s+/g, " ") };
5648
5518
  if (this.kind === "subagents") {
5649
5519
  const tools = normalizeTools(item.tools);
@@ -5659,30 +5529,30 @@ var LocalLibrary = class {
5659
5529
  /** Met l'élément à la corbeille (~/.iagenify/.trash/<horodatage>/…), d'où on peut le récupérer. */
5660
5530
  async remove(name) {
5661
5531
  this._checkName(name);
5662
- if (this.spec.builtIns[name]) throw fail8(400, "builtin_item", `"${name}" is built in and cannot be removed.`);
5663
- const { fs, path, base: base2, dir } = await this._ready();
5532
+ if (this.spec.builtIns[name]) throw fail7(400, "builtin_item", `"${name}" is built in and cannot be removed.`);
5533
+ const { fs, path, base, dir } = await this._ready();
5664
5534
  const source = this.kind === "skills" ? path.join(dir, name) : this._file(path, dir, name);
5665
5535
  try {
5666
5536
  await fs.access(source);
5667
5537
  } catch {
5668
- throw fail8(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
5538
+ throw fail7(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
5669
5539
  }
5670
- const target = path.join(base2, ".trash", (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-"), this.spec.folder, path.basename(source));
5540
+ const target = path.join(base, ".trash", (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-"), this.spec.folder, path.basename(source));
5671
5541
  await fs.mkdir(path.dirname(target), { recursive: true });
5672
5542
  await fs.rename(source, target);
5673
5543
  return { ok: true };
5674
5544
  }
5675
5545
  /** Skills seulement : un fichier du skill (modèle, référence…), en texte. */
5676
5546
  async readFile(name, file) {
5677
- if (this.kind !== "skills") throw fail8(400, "not_a_skill", "Only skills have files.");
5547
+ if (this.kind !== "skills") throw fail7(400, "not_a_skill", "Only skills have files.");
5678
5548
  const skill = await this.get(name);
5679
5549
  const { fs, path } = await node3();
5680
5550
  const full = path.resolve(skill.folder, String(file || "").replace(/\\/g, "/"));
5681
- if (!full.startsWith(skill.folder + path.sep)) throw fail8(400, "invalid_path", `"${file}" is outside the skill folder.`);
5551
+ if (!full.startsWith(skill.folder + path.sep)) throw fail7(400, "invalid_path", `"${file}" is outside the skill folder.`);
5682
5552
  try {
5683
5553
  return { name: path.basename(full), path: path.relative(skill.folder, full).split(path.sep).join("/"), content: await fs.readFile(full, "utf8") };
5684
5554
  } catch (err) {
5685
- if (err.code === "ENOENT" || err.code === "EISDIR") throw fail8(404, "path_not_found", `The skill "${name}" has no file "${file}". Files: ${skill.files.join(", ") || "none"}.`);
5555
+ if (err.code === "ENOENT" || err.code === "EISDIR") throw fail7(404, "path_not_found", `The skill "${name}" has no file "${file}". Files: ${skill.files.join(", ") || "none"}.`);
5686
5556
  throw err;
5687
5557
  }
5688
5558
  }
@@ -5757,13 +5627,13 @@ var AgentLibrary = class {
5757
5627
  if (err.status !== 404 || !this.computer) throw err;
5758
5628
  const onDisk = await this.computer.get(name).catch(() => null);
5759
5629
  if (!onDisk) throw err;
5760
- throw fail8(409, "item_on_computer", `\xAB ${name} \xBB est un fichier de cet ordinateur (~/.iagenify/${this.spec.folder}) : supprimez-le sur le disque.`);
5630
+ throw fail7(409, "item_on_computer", `\xAB ${name} \xBB est un fichier de cet ordinateur (~/.iagenify/${this.spec.folder}) : supprimez-le sur le disque.`);
5761
5631
  }
5762
5632
  }
5763
5633
  /** Skills seulement : un fichier annexe. Ceux du compte n'en ont pas — le contenu est le document. */
5764
5634
  async readFile(name, file) {
5765
- if (this.kind !== "skills") throw fail8(400, "not_a_skill", "Only skills have files.");
5766
- if (!this.computer) throw fail8(404, "path_not_found", `\xAB ${name} \xBB n'a pas de fichiers : les skills du compte sont un seul document.`);
5635
+ if (this.kind !== "skills") throw fail7(400, "not_a_skill", "Only skills have files.");
5636
+ if (!this.computer) throw fail7(404, "path_not_found", `\xAB ${name} \xBB n'a pas de fichiers : les skills du compte sont un seul document.`);
5767
5637
  return this.computer.readFile(name, file);
5768
5638
  }
5769
5639
  };
@@ -5779,11 +5649,11 @@ var MAX_OUTPUT2 = 6e4;
5779
5649
  var CALL_TIMEOUT_MS = 6e4;
5780
5650
  var LIST_TIMEOUT_MS = 3e4;
5781
5651
  var MAX_PAGES = 20;
5782
- var fail9 = (status, code, message) => new IaGenifyError(status, code, message);
5652
+ var fail8 = (status, code, message) => new IaGenifyError(status, code, message);
5783
5653
  var CODE_VERSION_NON_SUPPORTEE = -32022;
5784
5654
  var estErreurModerne = (code) => typeof code === "number" && code <= -32020 && code >= -32099;
5785
5655
  var REPLI_ANCIENNE_POIGNEE = /* @__PURE__ */ new Set(["mcp_error", "mcp_http_error", "mcp_bad_response"]);
5786
- var clip5 = (text2, max = MAX_OUTPUT2) => text2.length > max ? `${text2.slice(0, max)}
5656
+ var clip4 = (text2, max = MAX_OUTPUT2) => text2.length > max ? `${text2.slice(0, max)}
5787
5657
  \u2026[truncated ${text2.length - max} characters]` : text2;
5788
5658
  var SCHEMA_TYPES = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "array", "object"]);
5789
5659
  var SCHEMA_KEYS = /* @__PURE__ */ new Set(["type", "description", "properties", "required", "items", "enum", "nullable"]);
@@ -5840,7 +5710,7 @@ function cleanToken(value) {
5840
5710
  token = token.replace(/^authorization\s*:\s*/i, "").replace(/^bearer\b\s*/i, "").replace(/^token\s*=\s*/i, "").trim().replace(quotes, "").trim();
5841
5711
  if (!token) return null;
5842
5712
  if (/\s/.test(token)) {
5843
- throw fail9(400, "mcp_token_malformed", "Ce jeton contient une espace : collez le jeton seul, sans \xAB Bearer \xBB, sans guillemets et sans retour \xE0 la ligne.");
5713
+ throw fail8(400, "mcp_token_malformed", "Ce jeton contient une espace : collez le jeton seul, sans \xAB Bearer \xBB, sans guillemets et sans retour \xE0 la ligne.");
5844
5714
  }
5845
5715
  return token;
5846
5716
  }
@@ -5916,7 +5786,7 @@ function mirroredParams(schema, args) {
5916
5786
  }
5917
5787
  var McpClient = class {
5918
5788
  constructor({ url, token = null, name = "mcp", fetchImpl = null } = {}) {
5919
- if (!url) throw fail9(400, "url_required", "An MCP server needs its address.");
5789
+ if (!url) throw fail8(400, "url_required", "An MCP server needs its address.");
5920
5790
  this.url = String(url);
5921
5791
  this.token = cleanToken(token);
5922
5792
  this.name = name;
@@ -5978,8 +5848,8 @@ var McpClient = class {
5978
5848
  redirect: "manual"
5979
5849
  });
5980
5850
  } catch (err) {
5981
- if (controller.signal.aborted) throw fail9(504, "mcp_timeout", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en ${Math.round(timeout / 1e3)} s.`);
5982
- throw fail9(502, "mcp_unreachable", `\xAB ${this.name} \xBB est injoignable : ${err.message}`);
5851
+ if (controller.signal.aborted) throw fail8(504, "mcp_timeout", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en ${Math.round(timeout / 1e3)} s.`);
5852
+ throw fail8(502, "mcp_unreachable", `\xAB ${this.name} \xBB est injoignable : ${err.message}`);
5983
5853
  } finally {
5984
5854
  clearTimeout(timer);
5985
5855
  signal?.removeEventListener?.("abort", abort);
@@ -5988,17 +5858,17 @@ var McpClient = class {
5988
5858
  const detail = this._detail(brut);
5989
5859
  if (response.status === 401 || response.status === 403) {
5990
5860
  if (!this.token) {
5991
- throw fail9(401, "mcp_token_required", `\xAB ${this.name} \xBB demande un jeton : ce serveur ne r\xE9pond pas sans authentification.${detail}`);
5861
+ throw fail8(401, "mcp_token_required", `\xAB ${this.name} \xBB demande un jeton : ce serveur ne r\xE9pond pas sans authentification.${detail}`);
5992
5862
  }
5993
- throw fail9(401, "mcp_unauthorized", `\xAB ${this.name} \xBB refuse le jeton (${response.status}). V\xE9rifiez-le, ou recr\xE9ez-en un.${detail}`);
5863
+ throw fail8(401, "mcp_unauthorized", `\xAB ${this.name} \xBB refuse le jeton (${response.status}). V\xE9rifiez-le, ou recr\xE9ez-en un.${detail}`);
5994
5864
  }
5995
5865
  if (response.status >= 300 && response.status < 400) {
5996
- throw fail9(502, "mcp_redirect", `\xAB ${this.name} \xBB redirige vers une autre adresse : reconnectez-le avec l'adresse d\xE9finitive.`);
5866
+ throw fail8(502, "mcp_redirect", `\xAB ${this.name} \xBB redirige vers une autre adresse : reconnectez-le avec l'adresse d\xE9finitive.`);
5997
5867
  }
5998
- if (!response.ok) throw this._rpcError(fail9(502, "mcp_http_error", `\xAB ${this.name} \xBB a r\xE9pondu ${response.status}.${detail}`), brut);
5868
+ if (!response.ok) throw this._rpcError(fail8(502, "mcp_http_error", `\xAB ${this.name} \xBB a r\xE9pondu ${response.status}.${detail}`), brut);
5999
5869
  const message = await this._readMessage(response, id);
6000
5870
  if (message?.error) {
6001
- const err = fail9(502, "mcp_error", `\xAB ${this.name} \xBB refuse : ${String(message.error.message || message.error.code || "erreur").slice(0, 500)}`);
5871
+ const err = fail8(502, "mcp_error", `\xAB ${this.name} \xBB refuse : ${String(message.error.message || message.error.code || "erreur").slice(0, 500)}`);
6002
5872
  err.rpc = { code: message.error.code, data: message.error.data };
6003
5873
  throw err;
6004
5874
  }
@@ -6028,12 +5898,12 @@ var McpClient = class {
6028
5898
  /** La réponse, qu'elle arrive en JSON ou en flux d'événements (`text/event-stream`). */
6029
5899
  async _readMessage(response, id) {
6030
5900
  const type = String(response.headers.get("content-type") || "");
6031
- const body = clip5(await response.text(), 2e6);
5901
+ const body = clip4(await response.text(), 2e6);
6032
5902
  if (!type.includes("text/event-stream")) {
6033
5903
  try {
6034
5904
  return JSON.parse(body);
6035
5905
  } catch {
6036
- throw fail9(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en JSON.`);
5906
+ throw fail8(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en JSON.`);
6037
5907
  }
6038
5908
  }
6039
5909
  let last = null;
@@ -6048,7 +5918,7 @@ var McpClient = class {
6048
5918
  }
6049
5919
  }
6050
5920
  if (last) return last;
6051
- throw fail9(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a renvoy\xE9 aucune r\xE9ponse exploitable.`);
5921
+ throw fail8(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a renvoy\xE9 aucune r\xE9ponse exploitable.`);
6052
5922
  }
6053
5923
  /**
6054
5924
  * La poignée de main, dans les deux révisions. Elle dit quelle version le serveur a acceptée.
@@ -6070,7 +5940,7 @@ var McpClient = class {
6070
5940
  const propose = err.rpc?.data?.supportedVersions || err.rpc?.data?.supported;
6071
5941
  const version = negotiateVersion(propose);
6072
5942
  if (!version) {
6073
- throw fail9(
5943
+ throw fail8(
6074
5944
  502,
6075
5945
  "mcp_protocol_unsupported",
6076
5946
  `\xAB ${this.name} \xBB ne parle aucune r\xE9vision que ce client conna\xEEt (il propose ${[].concat(propose || []).join(", ") || "rien"}).`
@@ -6101,7 +5971,7 @@ var McpClient = class {
6101
5971
  const found = await this._rpc("server/discover", {}, { signal });
6102
5972
  const version = negotiateVersion(found.supportedVersions);
6103
5973
  if (found.supportedVersions && !version) {
6104
- throw fail9(
5974
+ throw fail8(
6105
5975
  502,
6106
5976
  "mcp_protocol_unsupported",
6107
5977
  `\xAB ${this.name} \xBB ne parle aucune r\xE9vision que ce client conna\xEEt (il propose ${[].concat(found.supportedVersions).join(", ")}).`
@@ -6153,7 +6023,7 @@ var McpClient = class {
6153
6023
  return part?.text ? String(part.text) : "";
6154
6024
  }).filter(Boolean).join("\n");
6155
6025
  const output = text2 || (result.structuredContent ? JSON.stringify(result.structuredContent) : "(aucun contenu)");
6156
- return { output: clip5(output), isError: Boolean(result.isError) };
6026
+ return { output: clip4(output), isError: Boolean(result.isError) };
6157
6027
  }
6158
6028
  };
6159
6029
  var McpResource = class {
@@ -6563,7 +6433,6 @@ var TOOL_FAMILIES = [
6563
6433
  ["Storages", ["query_storage", "write_storage"]],
6564
6434
  ["The account", ["account", "cloud"]],
6565
6435
  ["Put online and communicate", ["deploy", "domain", "mail", "send_mail"]],
6566
- ["Design", ["design_read", "design_apply", "design_render", "design_check", "design_template"]],
6567
6436
  ["The platform itself", ["iagenify_docs", "workflow", "mcp"]],
6568
6437
  ["Ask another model", ["generate"]],
6569
6438
  ["This conversation", ["todo_write", "ask_user", "memory", "recall", "skill", "task"]]
@@ -6743,9 +6612,9 @@ var SUBAGENT_MAX_STEPS = 40;
6743
6612
  var MAX_SKILL_OUTPUT = 6e4;
6744
6613
  var withoutAttachments = (messages) => messages.map(({ attachments, images, ...m }) => attachments?.length || images?.length ? { ...m, content: `${m.content || ""} [${(attachments || images).length} file(s) attached]` } : m);
6745
6614
  var estimateTokens = (messages) => Math.ceil(JSON.stringify(withoutAttachments(messages)).length / 4);
6746
- var clip6 = (text2, max) => text2.length > max ? `${text2.slice(0, max)}
6615
+ var clip5 = (text2, max) => text2.length > max ? `${text2.slice(0, max)}
6747
6616
  \u2026[truncated ${text2.length - max} characters]` : text2;
6748
- var fail10 = (message) => {
6617
+ var fail9 = (message) => {
6749
6618
  throw new IaGenifyError(400, "tool_error", message);
6750
6619
  };
6751
6620
  var KEEP_ATTACHMENTS_FOR = 6;
@@ -7096,11 +6965,11 @@ var LocalAgent = class _LocalAgent {
7096
6965
  const notes = await this.api.memory.list();
7097
6966
  return { output: notes.length ? notes.map((n) => `- ${n.name}: ${n.description || n.content.slice(0, 80)}`).join("\n") : "(no memory yet)", summary: `${notes.length} notes` };
7098
6967
  }
7099
- if (!name) fail10("memory needs a name.");
6968
+ if (!name) fail9("memory needs a name.");
7100
6969
  if (action === "read") {
7101
6970
  const notes = await this.api.memory.list();
7102
6971
  const note = notes.find((n) => n.name === name);
7103
- if (!note) fail10(`No memory called "${name}". Listed names: ${notes.map((n) => n.name).join(", ") || "none"}.`);
6972
+ if (!note) fail9(`No memory called "${name}". Listed names: ${notes.map((n) => n.name).join(", ") || "none"}.`);
7104
6973
  return { output: `# ${note.name}
7105
6974
  ${note.description}
7106
6975
 
@@ -7111,7 +6980,7 @@ ${note.content}`, summary: note.name, meta: { memory: note.name } };
7111
6980
  this.memories = this.memories.filter((n) => n.name !== name);
7112
6981
  return { output: `Memory "${name}" deleted.`, summary: name, meta: { memory: name, deleted: true } };
7113
6982
  }
7114
- if (!content.trim()) fail10("memory save needs content.");
6983
+ if (!content.trim()) fail9("memory save needs content.");
7115
6984
  const saved = await this.api.memory.save({ name, description, content, type, source: "agent", ...this.memory ? { sessionId: this.id } : {} });
7116
6985
  this.memories = [saved, ...this.memories.filter((n) => n.name !== saved.name)];
7117
6986
  return { output: `Remembered as "${saved.name}". It will be in your memory index from now on.`, summary: saved.name, meta: { memory: saved.name, saved: true } };
@@ -7145,19 +7014,19 @@ ${note.content}`, summary: note.name, meta: { memory: note.name } };
7145
7014
  file: { type: "string", description: "Optional: one of the skill's files, as listed when it is loaded" }
7146
7015
  }),
7147
7016
  run: async ({ name, file }) => {
7148
- if (!this.library.skills.some((s) => s.name === name)) fail10(`Unknown skill "${name}". Available: ${this.library.skills.map((s) => s.name).join(", ")}.`);
7017
+ if (!this.library.skills.some((s) => s.name === name)) fail9(`Unknown skill "${name}". Available: ${this.library.skills.map((s) => s.name).join(", ")}.`);
7149
7018
  const library = this._library("skills");
7150
- if (!library) fail10("No skills are available here.");
7019
+ if (!library) fail9("No skills are available here.");
7151
7020
  if (file) {
7152
7021
  const read = await library.readFile(name, file);
7153
- return { output: clip6(read.content, MAX_SKILL_OUTPUT) || "(empty file)", summary: `${name} \xB7 ${read.path}`, meta: { skill: name, file: read.path } };
7022
+ return { output: clip5(read.content, MAX_SKILL_OUTPUT) || "(empty file)", summary: `${name} \xB7 ${read.path}`, meta: { skill: name, file: read.path } };
7154
7023
  }
7155
7024
  const skill = await library.get(name);
7156
7025
  const files = skill.files?.length ? `
7157
7026
 
7158
7027
  Files in this skill (read one with skill + file): ${skill.files.join(", ")}${skill.folder ? `
7159
7028
  Folder on this computer, for commands: ${skill.folder}` : ""}` : "";
7160
- return { output: clip6(`# Skill: ${name}
7029
+ return { output: clip5(`# Skill: ${name}
7161
7030
 
7162
7031
  ${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: { skill: name, files: skill.files?.length || 0 } };
7163
7032
  }
@@ -7176,8 +7045,8 @@ ${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: {
7176
7045
  }
7177
7046
  /** Lance un sous-agent : même machine, même mode, mêmes permissions, budget et crédits partagés avec ce run. */
7178
7047
  async _runSubagent({ agent: name, description = "", prompt }, call) {
7179
- if (!this.library.subagents.some((a) => a.name === name)) fail10(`Unknown subagent "${name}". Available: ${this.library.subagents.map((a) => a.name).join(", ")}.`);
7180
- if (!String(prompt || "").trim()) fail10("task needs a prompt: the subagent sees nothing of this conversation.");
7048
+ if (!this.library.subagents.some((a) => a.name === name)) fail9(`Unknown subagent "${name}". Available: ${this.library.subagents.map((a) => a.name).join(", ")}.`);
7049
+ if (!String(prompt || "").trim()) fail9("task needs a prompt: the subagent sees nothing of this conversation.");
7181
7050
  const definition = await this._definition("subagents", name);
7182
7051
  const wanted = !definition.tools || definition.tools === "all" ? WORKSPACE_TOOL_NAMES : definition.tools;
7183
7052
  const tools = wanted.filter((t) => this.toolNames.includes(t) && !PARENT_ONLY_TOOLS.has(t));
@@ -7227,7 +7096,7 @@ ${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: {
7227
7096
 
7228
7097
  [${name} subagent \xB7 ${turns} turns \xB7 ${toolCalls} tool calls \xB7 ${credits} credits${ended}]`,
7229
7098
  summary: description || name,
7230
- meta: { agent: name, description, model: child.model, turns, toolCalls, credits, stopReason: result.stopReason, report: clip6(result.text || "", 4e3) }
7099
+ meta: { agent: name, description, model: child.model, turns, toolCalls, credits, stopReason: result.stopReason, report: clip5(result.text || "", 4e3) }
7231
7100
  };
7232
7101
  } finally {
7233
7102
  this.children.delete(child);
@@ -7258,7 +7127,7 @@ Files in this skill (read one with skill + file): ${skill.files.join(", ")}` : "
7258
7127
 
7259
7128
  # Skill: ${name}
7260
7129
 
7261
- ${clip6(skill.content, MAX_SKILL_OUTPUT)}${files}
7130
+ ${clip5(skill.content, MAX_SKILL_OUTPUT)}${files}
7262
7131
 
7263
7132
  # Request
7264
7133
  ${args || "Apply this skill."}`;
@@ -7321,13 +7190,13 @@ ${args || "Apply this skill."}`;
7321
7190
  const read = await this.catalog.read.run({ path }, { files });
7322
7191
  if (read.attachments?.length) images.push(...read.attachments.map((a) => ({ mime: a.mime, data: a.data })));
7323
7192
  sections.push(`## @${read.meta?.path || path}
7324
- ${read.attachments?.length ? read.output : clip6(read.output, 3e4)}`);
7193
+ ${read.attachments?.length ? read.output : clip5(read.output, 3e4)}`);
7325
7194
  emit({ type: "mention", kind: "file", path: read.meta?.path || path });
7326
7195
  } catch {
7327
7196
  try {
7328
7197
  const list = await this.catalog.list.run({ path }, { files });
7329
7198
  sections.push(`## @${path} (folder)
7330
- ${clip6(list.output, 8e3)}`);
7199
+ ${clip5(list.output, 8e3)}`);
7331
7200
  emit({ type: "mention", kind: "folder", path });
7332
7201
  } catch {
7333
7202
  }
@@ -7338,7 +7207,7 @@ ${clip6(list.output, 8e3)}`);
7338
7207
  try {
7339
7208
  const read = await this.catalog.query_storage.run({ storage: s.name, action, ...action === "schema" ? { collection: s.collection } : {}, ...action === "objects" && s.collection ? { prefix: s.collection } : {} }, { api: this.api });
7340
7209
  sections.push(`## #${s.name}${s.collection ? ` \xB7 ${s.collection}` : ""}
7341
- ${clip6(read.output, 8e3)}`);
7210
+ ${clip5(read.output, 8e3)}`);
7342
7211
  emit({ type: "mention", kind: "storage", storage: s.name, collection: s.collection });
7343
7212
  } catch (err) {
7344
7213
  sections.push(`## #${s.name}${s.collection ? ` \xB7 ${s.collection}` : ""}
@@ -9076,7 +8945,7 @@ function planPacks(hashes, sizeOf, { maxBytes, maxFiles }) {
9076
8945
  return packs;
9077
8946
  }
9078
8947
  async function deployDirect(client, hostId, entries, server) {
9079
- const base2 = `/api/hosting/${hostId}/uploads`;
8948
+ const base = `/api/hosting/${hostId}/uploads`;
9080
8949
  const byHash = /* @__PURE__ */ new Map();
9081
8950
  const manifest = [];
9082
8951
  for (const entry of entries) {
@@ -9084,7 +8953,7 @@ async function deployDirect(client, hostId, entries, server) {
9084
8953
  manifest.push({ path: entry.path, size: entry.size, hash });
9085
8954
  if (!byHash.has(hash)) byHash.set(hash, entry);
9086
8955
  }
9087
- const { upload } = await client.post(base2, { files: manifest, ...server !== void 0 ? { server } : {} });
8956
+ const { upload } = await client.post(base, { files: manifest, ...server !== void 0 ? { server } : {} });
9088
8957
  const send = async (missing2) => {
9089
8958
  const packs = planPacks(
9090
8959
  missing2.filter((hash) => byHash.has(hash)),
@@ -9105,7 +8974,7 @@ async function deployDirect(client, hostId, entries, server) {
9105
8974
  const header = pack.map((hash) => `${hash}:${byHash.get(hash).size}`).join(",");
9106
8975
  for (let attempt = 1; ; attempt++) {
9107
8976
  try {
9108
- await client.put(`${base2}/${upload.id}/parts`, body, { headers: { "X-IaGenify-Parts": header }, timeout: PACK_TIMEOUT_MS });
8977
+ await client.put(`${base}/${upload.id}/parts`, body, { headers: { "X-IaGenify-Parts": header }, timeout: PACK_TIMEOUT_MS });
9109
8978
  break;
9110
8979
  } catch (error) {
9111
8980
  const transient = !error?.status || error.status >= 500 || error.status === 429;
@@ -9119,11 +8988,11 @@ async function deployDirect(client, hostId, entries, server) {
9119
8988
  };
9120
8989
  await send(upload.missing || []);
9121
8990
  try {
9122
- return (await client.post(`${base2}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
8991
+ return (await client.post(`${base}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
9123
8992
  } catch (error) {
9124
8993
  if (error?.code !== "upload_incomplete" || !Array.isArray(error.details?.missing)) throw error;
9125
8994
  await send(error.details.missing);
9126
- return (await client.post(`${base2}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
8995
+ return (await client.post(`${base}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
9127
8996
  }
9128
8997
  }
9129
8998
  function toBase64(bytes) {
@@ -9137,10 +9006,10 @@ var HostsResource = class {
9137
9006
  this.client = client;
9138
9007
  }
9139
9008
  /** `runtime` is the public contract. `kind` remains accepted for one upgrade cycle. */
9140
- async create({ runtime, framework, label, slug: slug2, kind } = {}) {
9009
+ async create({ runtime, framework, label, slug, kind } = {}) {
9141
9010
  const rule = assertRuntime(runtime || LEGACY_RUNTIME[kind], framework);
9142
9011
  const resolvedRuntime = runtime || LEGACY_RUNTIME[kind];
9143
- const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug: slug2 });
9012
+ const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug });
9144
9013
  return new Host(this.client, res.host, { framework });
9145
9014
  }
9146
9015
  async list() {
@@ -9534,8 +9403,8 @@ var Contacts = class {
9534
9403
  /** `avatar` est rendu absolu ici : l'API rend un chemin, elle ignore sous quel nom on l'atteint. */
9535
9404
  _absolu(contact) {
9536
9405
  if (!contact) return contact;
9537
- const base2 = typeof this.client?.baseUrl === "string" ? this.client.baseUrl : "";
9538
- return contact.avatar?.startsWith("/") && base2 ? { ...contact, avatar: `${base2}${contact.avatar}` } : contact;
9406
+ const base = typeof this.client?.baseUrl === "string" ? this.client.baseUrl : "";
9407
+ return contact.avatar?.startsWith("/") && base ? { ...contact, avatar: `${base}${contact.avatar}` } : contact;
9539
9408
  }
9540
9409
  async list() {
9541
9410
  const res = await this.client.get("/api/mail/contacts");
@@ -9626,955 +9495,6 @@ var MailResource = class {
9626
9495
  }
9627
9496
  };
9628
9497
 
9629
- // src/studio/errors.js
9630
- var StudioError = class extends Error {
9631
- constructor(code, message, details = void 0, status = 400) {
9632
- super(message);
9633
- this.name = "StudioError";
9634
- this.status = status;
9635
- this.code = code;
9636
- if (details !== void 0) this.details = details;
9637
- }
9638
- };
9639
-
9640
- // src/studio/format.js
9641
- var FORMAT = "iagenify.design";
9642
- var FORMAT_VERSION = 1;
9643
- var NODE_TYPES = ["frame", "text", "image", "shape"];
9644
- var CONTENEURS = /* @__PURE__ */ new Set(["frame"]);
9645
- var TAGS = {
9646
- frame: ["div", "section", "header", "footer", "nav", "main", "article", "aside", "figure", "ul", "li", "a", "button"],
9647
- text: ["p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "a", "button", "li", "small", "strong", "em", "label"],
9648
- image: ["img"],
9649
- shape: ["div"]
9650
- };
9651
- var DEFAULT_TAG = { frame: "div", text: "p", image: "img", shape: "div" };
9652
- var CHAMPS_NOEUD = /* @__PURE__ */ new Set(["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"]);
9653
- var CHAMPS = {
9654
- 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" },
9655
- size: { w: "dimension", h: "dimension", minW: "longueur", minH: "longueur", maxW: "longueur", maxH: "longueur" },
9656
- position: { x: "nombre", y: "nombre", absolute: "booleen" },
9657
- style: { fill: "remplissage", stroke: "trait", radius: "rayon", shadow: "ombres", opacity: "opacite", clip: "booleen" },
9658
- 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"] },
9659
- image: { src: "source", fit: ["cover", "contain", "fill"] },
9660
- shape: { kind: ["rect", "ellipse", "line"] }
9661
- };
9662
- 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;
9663
- var POLICE = /^[A-Za-z0-9 \-]{1,64}$/;
9664
- var SOURCE = /^asset:[A-Za-z0-9_\-]{1,64}$/;
9665
- var fini = (v) => typeof v === "number" && Number.isFinite(v);
9666
- function isColor(v) {
9667
- return typeof v === "string" && COULEUR.test(v.trim());
9668
- }
9669
- function verifierValeur(regle, v) {
9670
- if (Array.isArray(regle)) return regle.includes(v) ? null : `valeur_non_permise (${regle.join(", ")})`;
9671
- switch (regle) {
9672
- case "booleen":
9673
- return typeof v === "boolean" ? null : "booleen_attendu";
9674
- case "nombre":
9675
- return fini(v) ? null : "nombre_attendu";
9676
- case "entier":
9677
- return Number.isInteger(v) && v >= 1 && v <= 24 ? null : "entier_1_24_attendu";
9678
- case "longueur":
9679
- return fini(v) && v >= 0 && v <= 1e5 ? null : "longueur_positive_attendue";
9680
- case "dimension":
9681
- return v === "hug" || v === "fill" || fini(v) && v >= 0 && v <= 1e5 ? null : "hug_fill_ou_longueur_attendu";
9682
- case "padding":
9683
- if (fini(v) && v >= 0) return null;
9684
- if (Array.isArray(v) && (v.length === 2 || v.length === 4) && v.every((x) => fini(x) && x >= 0)) return null;
9685
- return "padding_nombre_ou_liste_2_4";
9686
- case "rayon":
9687
- if (fini(v) && v >= 0) return null;
9688
- if (Array.isArray(v) && v.length === 4 && v.every((x) => fini(x) && x >= 0)) return null;
9689
- return "rayon_nombre_ou_liste_4";
9690
- case "opacite":
9691
- return fini(v) && v >= 0 && v <= 1 ? null : "opacite_0_1";
9692
- case "couleur":
9693
- return isColor(v) ? null : "couleur_invalide";
9694
- case "remplissage":
9695
- if (isColor(v)) return null;
9696
- if (v && typeof v === "object" && v.type === "linear") {
9697
- const cles = Object.keys(v).filter((k) => !["type", "angle", "stops"].includes(k));
9698
- if (cles.length) return `champ_inconnu (${cles[0]})`;
9699
- if (!fini(v.angle)) return "angle_attendu";
9700
- if (!Array.isArray(v.stops) || v.stops.length < 2 || v.stops.length > 8) return "2_a_8_arrets";
9701
- 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";
9702
- return null;
9703
- }
9704
- return "couleur_ou_degrade_attendu";
9705
- case "trait":
9706
- if (v && typeof v === "object" && isColor(v.color) && fini(v.width) && v.width >= 0 && v.width <= 100 && Object.keys(v).length === 2) return null;
9707
- return "trait_{color,width}_attendu";
9708
- case "ombres":
9709
- if (!Array.isArray(v) || v.length > 4) return "liste_de_4_ombres_max";
9710
- for (const o of v) {
9711
- if (!o || typeof o !== "object") return "ombre_invalide";
9712
- const cles = Object.keys(o).filter((k) => !["x", "y", "blur", "spread", "color", "inset"].includes(k));
9713
- if (cles.length) return `champ_inconnu (${cles[0]})`;
9714
- 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";
9715
- }
9716
- return null;
9717
- case "texte":
9718
- return typeof v === "string" && v.length <= 2e4 ? null : "texte_attendu";
9719
- case "police":
9720
- return typeof v === "string" && POLICE.test(v) ? null : "nom_de_police_invalide";
9721
- case "graisse":
9722
- return Number.isInteger(v) && v >= 100 && v <= 900 && v % 100 === 0 ? null : "graisse_100_a_900";
9723
- case "interligne":
9724
- return fini(v) && v > 0 && v <= 10 ? null : "interligne_0_10";
9725
- case "source":
9726
- return typeof v === "string" && SOURCE.test(v) ? null : "source_asset:<id>_attendue";
9727
- default:
9728
- return "regle_inconnue";
9729
- }
9730
- }
9731
- function verifierGroupe(groupe, objet, chemin, erreurs) {
9732
- if (objet === void 0) return;
9733
- if (!objet || typeof objet !== "object" || Array.isArray(objet)) {
9734
- erreurs.push({ path: chemin, reason: "objet_attendu" });
9735
- return;
9736
- }
9737
- const regles = CHAMPS[groupe];
9738
- for (const [cle, valeur] of Object.entries(objet)) {
9739
- if (!(cle in regles)) {
9740
- erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
9741
- continue;
9742
- }
9743
- if (valeur === null && ["stroke", "shadow"].includes(cle)) continue;
9744
- const motif = verifierValeur(regles[cle], valeur);
9745
- if (motif) erreurs.push({ path: `${chemin}.${cle}`, reason: motif });
9746
- }
9747
- }
9748
- function validateNode(node4, chemin = "node") {
9749
- const erreurs = [];
9750
- if (!node4 || typeof node4 !== "object" || Array.isArray(node4)) return [{ path: chemin, reason: "objet_attendu" }];
9751
- for (const cle of Object.keys(node4)) if (!CHAMPS_NOEUD.has(cle)) erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
9752
- if (!NODE_TYPES.includes(node4.type)) erreurs.push({ path: `${chemin}.type`, reason: `type_inconnu (${NODE_TYPES.join(", ")})` });
9753
- if (typeof node4.name !== "string" || !node4.name.trim() || node4.name.length > 120) erreurs.push({ path: `${chemin}.name`, reason: "nom_1_a_120_caracteres" });
9754
- if (node4.as !== void 0 && !(TAGS[node4.type] || []).includes(node4.as)) erreurs.push({ path: `${chemin}.as`, reason: "balise_non_permise" });
9755
- if (node4.alt !== void 0 && (typeof node4.alt !== "string" || node4.alt.length > 500)) erreurs.push({ path: `${chemin}.alt`, reason: "texte_500_max" });
9756
- for (const groupe of ["layout", "size", "position", "style", "text", "image", "shape"]) verifierGroupe(groupe, node4[groupe], `${chemin}.${groupe}`, erreurs);
9757
- if (node4.type !== "frame" && node4.layout !== void 0) erreurs.push({ path: `${chemin}.layout`, reason: "seul_un_cadre_a_une_mise_en_page" });
9758
- if (node4.type !== "text" && node4.text !== void 0) erreurs.push({ path: `${chemin}.text`, reason: "seul_un_texte_a_du_texte" });
9759
- if (node4.type === "text" && typeof node4.text?.content !== "string") erreurs.push({ path: `${chemin}.text.content`, reason: "texte_attendu" });
9760
- if (node4.type !== "image" && node4.image !== void 0) erreurs.push({ path: `${chemin}.image`, reason: "seule_une_image_a_une_source" });
9761
- if (node4.type === "image" && typeof node4.image?.src !== "string") erreurs.push({ path: `${chemin}.image.src`, reason: "source_asset:<id>_attendue" });
9762
- if (node4.type !== "shape" && node4.shape !== void 0) erreurs.push({ path: `${chemin}.shape`, reason: "seule_une_forme_a_un_genre" });
9763
- if (CONTENEURS.has(node4.type)) {
9764
- if (!Array.isArray(node4.children)) erreurs.push({ path: `${chemin}.children`, reason: "liste_attendue" });
9765
- } else if (node4.children !== void 0) erreurs.push({ path: `${chemin}.children`, reason: "ce_type_n_a_pas_d_enfants" });
9766
- return erreurs;
9767
- }
9768
- function isContainer(node4) {
9769
- return CONTENEURS.has(node4?.type);
9770
- }
9771
- function createDocument() {
9772
- return { format: FORMAT, version: FORMAT_VERSION, meta: { nextId: 1 }, pages: [{ id: "p_1", name: "Page 1", frames: [] }], nodes: {} };
9773
- }
9774
- function validate(doc) {
9775
- const erreurs = [];
9776
- const err = (path, reason) => erreurs.push({ path, reason });
9777
- if (!doc || typeof doc !== "object" || Array.isArray(doc)) return { ok: false, errors: [{ path: "", reason: "objet_attendu" }] };
9778
- for (const cle of Object.keys(doc)) if (!["format", "version", "meta", "pages", "nodes"].includes(cle)) err(cle, "champ_inconnu");
9779
- if (doc.format !== FORMAT) err("format", `attendu_${FORMAT}`);
9780
- if (doc.version !== FORMAT_VERSION) err("version", `version_${FORMAT_VERSION}_attendue`);
9781
- if (!doc.meta || !Number.isInteger(doc.meta.nextId) || doc.meta.nextId < 1 || Object.keys(doc.meta).length !== 1) err("meta", "meta_{nextId}_attendu");
9782
- if (!doc.nodes || typeof doc.nodes !== "object" || Array.isArray(doc.nodes)) {
9783
- err("nodes", "objet_attendu");
9784
- return { ok: false, errors: erreurs };
9785
- }
9786
- if (!Array.isArray(doc.pages) || doc.pages.length === 0) {
9787
- err("pages", "au_moins_une_page");
9788
- return { ok: false, errors: erreurs };
9789
- }
9790
- const parents = /* @__PURE__ */ new Map();
9791
- const cite = (id, path) => {
9792
- if (typeof id !== "string" || !Object.hasOwn(doc.nodes, id)) {
9793
- err(path, "enfant_inexistant");
9794
- return;
9795
- }
9796
- parents.set(id, (parents.get(id) || 0) + 1);
9797
- };
9798
- const idsPages = /* @__PURE__ */ new Set();
9799
- doc.pages.forEach((p, i) => {
9800
- const c = `pages[${i}]`;
9801
- if (!p || typeof p !== "object") return err(c, "objet_attendu");
9802
- for (const cle of Object.keys(p)) if (!["id", "name", "route", "frames"].includes(cle)) err(`${c}.${cle}`, "champ_inconnu");
9803
- 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");
9804
- idsPages.add(p.id);
9805
- if (typeof p.name !== "string" || !p.name.trim() || p.name.length > 120) err(`${c}.name`, "nom_1_a_120_caracteres");
9806
- if (p.route !== void 0 && (typeof p.route !== "string" || !/^\/[a-z0-9\-/[\]]*$/.test(p.route))) err(`${c}.route`, "route_invalide");
9807
- if (!Array.isArray(p.frames)) return err(`${c}.frames`, "liste_attendue");
9808
- p.frames.forEach((id, k) => {
9809
- cite(id, `${c}.frames[${k}]`);
9810
- if (typeof id === "string" && Object.hasOwn(doc.nodes, id) && doc.nodes[id]?.type !== "frame") {
9811
- err(`${c}.frames[${k}]`, "une_page_ne_contient_que_des_cadres");
9812
- }
9813
- });
9814
- });
9815
- const limite = doc.meta?.nextId ?? 1;
9816
- for (const [id, node4] of Object.entries(doc.nodes)) {
9817
- const c = `nodes.${id}`;
9818
- if (!/^n_[0-9a-z]+$/.test(id)) err(c, "id_invalide");
9819
- else if (parseInt(id.slice(2), 36) >= limite) err(c, "id_au_dela_du_compteur");
9820
- if (node4?.id !== id) err(`${c}.id`, "id_different_de_la_cle");
9821
- erreurs.push(...validateNode(node4, c));
9822
- if (Array.isArray(node4?.children)) node4.children.forEach((enfant, k) => cite(enfant, `${c}.children[${k}]`));
9823
- }
9824
- for (const id of Object.keys(doc.nodes)) {
9825
- const n = parents.get(id) || 0;
9826
- if (n === 0) err(`nodes.${id}`, "noeud_orphelin");
9827
- if (n > 1) err(`nodes.${id}`, "noeud_a_plusieurs_parents");
9828
- }
9829
- if (erreurs.length) return { ok: false, errors: erreurs };
9830
- const vus = /* @__PURE__ */ new Set();
9831
- const pile = doc.pages.flatMap((p) => p.frames);
9832
- while (pile.length) {
9833
- const id = pile.pop();
9834
- vus.add(id);
9835
- for (const enfant of doc.nodes[id].children || []) pile.push(enfant);
9836
- }
9837
- for (const id of Object.keys(doc.nodes)) if (!vus.has(id)) err(`nodes.${id}`, "cycle");
9838
- return { ok: erreurs.length === 0, errors: erreurs };
9839
- }
9840
- function assertValid(doc) {
9841
- const r = validate(doc);
9842
- 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) });
9843
- return doc;
9844
- }
9845
- var ORDRE_NOEUD = ["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"];
9846
- var ordonner = (objet, ordre) => {
9847
- const out = {};
9848
- for (const k of ordre) if (objet[k] !== void 0) out[k] = objet[k];
9849
- return out;
9850
- };
9851
- function canonical(doc) {
9852
- const nodes = {};
9853
- const ids = Object.keys(doc.nodes).sort((a, b) => parseInt(a.slice(2), 36) - parseInt(b.slice(2), 36));
9854
- for (const id of ids) {
9855
- const n = ordonner(doc.nodes[id], ORDRE_NOEUD);
9856
- for (const g of Object.keys(CHAMPS)) if (n[g] && typeof n[g] === "object") n[g] = ordonner(n[g], Object.keys(CHAMPS[g]));
9857
- nodes[id] = n;
9858
- }
9859
- return {
9860
- format: doc.format,
9861
- version: doc.version,
9862
- meta: { nextId: doc.meta.nextId },
9863
- pages: doc.pages.map((p) => ordonner({ ...p, frames: [...p.frames] }, ["id", "name", "route", "frames"])),
9864
- nodes
9865
- };
9866
- }
9867
- function migrate(doc) {
9868
- if (doc && doc.version === FORMAT_VERSION) return doc;
9869
- throw new StudioError("studio_document_invalid", `Version de document non prise en charge : ${doc?.version}`, { errors: [{ path: "version", reason: `version_${FORMAT_VERSION}_attendue` }] });
9870
- }
9871
-
9872
- // src/studio/ops.js
9873
- var GROUPES = /* @__PURE__ */ new Set(["layout", "size", "position", "style", "text", "image", "shape"]);
9874
- var SIMPLES = /* @__PURE__ */ new Set(["name", "as", "alt"]);
9875
- var refus = (index, reason, message) => {
9876
- throw new StudioError("studio_op_invalid", message || `Op\xE9ration ${index} refus\xE9e : ${reason}`, { index, reason });
9877
- };
9878
- function nouvelId(doc) {
9879
- const id = `n_${doc.meta.nextId.toString(36)}`;
9880
- doc.meta.nextId += 1;
9881
- return id;
9882
- }
9883
- function emplacement(doc, id) {
9884
- for (const p of doc.pages) {
9885
- const i = p.frames.indexOf(id);
9886
- if (i >= 0) return { parent: p.id, liste: p.frames, index: i };
9887
- }
9888
- for (const n of Object.values(doc.nodes)) if (n.children) {
9889
- const i = n.children.indexOf(id);
9890
- if (i >= 0) return { parent: n.id, liste: n.children, index: i };
9891
- }
9892
- return null;
9893
- }
9894
- function listeDuParent(doc, parent, type, index) {
9895
- const page = doc.pages.find((p) => p.id === parent);
9896
- if (page) {
9897
- if (type !== "frame") refus(index, "une_page_ne_contient_que_des_cadres");
9898
- return page.frames;
9899
- }
9900
- const n = doc.nodes[parent];
9901
- if (!n) refus(index, "parent_introuvable");
9902
- if (!isContainer(n)) refus(index, "le_parent_n_est_pas_un_cadre");
9903
- return n.children;
9904
- }
9905
- function sousArbre(doc, id, acc = {}) {
9906
- const n = doc.nodes[id];
9907
- acc[id] = n;
9908
- for (const e of n.children || []) sousArbre(doc, e, acc);
9909
- return acc;
9910
- }
9911
- function placer(liste, id, index, iop) {
9912
- const i = index === void 0 ? liste.length : index;
9913
- if (!Number.isInteger(i) || i < 0 || i > liste.length) refus(iop, "index_hors_limites");
9914
- liste.splice(i, 0, id);
9915
- return i;
9916
- }
9917
- function aplatir(doc, brut, iop, acc) {
9918
- if (!brut || typeof brut !== "object" || Array.isArray(brut)) refus(iop, "noeud_objet_attendu");
9919
- if ("id" in brut) refus(iop, "un_id_ne_se_choisit_pas");
9920
- const { children, ...reste } = brut;
9921
- const id = nouvelId(doc);
9922
- const node4 = { id, ...reste };
9923
- if (isContainer(node4)) {
9924
- if (children !== void 0 && !Array.isArray(children)) refus(iop, "children_liste_attendue");
9925
- node4.children = (children || []).map((c) => aplatir(doc, c, iop, acc));
9926
- } else if (children !== void 0) refus(iop, "ce_type_n_a_pas_d_enfants");
9927
- const erreurs = validateNode(node4, "node");
9928
- if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
9929
- acc[id] = node4;
9930
- return id;
9931
- }
9932
- function estDescendant(doc, ancetre, id) {
9933
- const n = doc.nodes[ancetre];
9934
- return (n?.children || []).some((e) => e === id || estDescendant(doc, e, id));
9935
- }
9936
- function lire(node4, path) {
9937
- const [a, b] = path.split(".");
9938
- if (b === void 0) return node4[a];
9939
- return node4[a]?.[b];
9940
- }
9941
- function appliquerUne(doc, op, iop, inverses, created, removed) {
9942
- if (!op || typeof op !== "object") refus(iop, "operation_objet_attendue");
9943
- switch (op.op) {
9944
- case "set": {
9945
- const node4 = doc.nodes[op.id];
9946
- if (!node4) refus(iop, "noeud_introuvable");
9947
- if (typeof op.path !== "string") refus(iop, "chemin_attendu");
9948
- const [a, b, ...trop] = op.path.split(".");
9949
- if (trop.length || !(SIMPLES.has(a) && b === void 0) && !GROUPES.has(a)) refus(iop, "chemin_non_modifiable");
9950
- const avant = lire(node4, op.path);
9951
- const copie2 = structuredClone(node4);
9952
- if (b === void 0) {
9953
- if (op.value === void 0) delete copie2[a];
9954
- else copie2[a] = structuredClone(op.value);
9955
- } else {
9956
- const groupe = { ...copie2[a] || {} };
9957
- if (op.value === void 0) delete groupe[b];
9958
- else groupe[b] = structuredClone(op.value);
9959
- if (Object.keys(groupe).length) copie2[a] = groupe;
9960
- else delete copie2[a];
9961
- }
9962
- const erreurs = validateNode(copie2, op.id);
9963
- if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
9964
- doc.nodes[op.id] = copie2;
9965
- inverses.push({ op: "set", id: op.id, path: op.path, value: avant === void 0 ? void 0 : structuredClone(avant) });
9966
- return;
9967
- }
9968
- case "insert": {
9969
- const acc = {};
9970
- const racine = aplatir(doc, op.node, iop, acc);
9971
- const liste = listeDuParent(doc, op.parent, acc[racine].type, iop);
9972
- Object.assign(doc.nodes, acc);
9973
- placer(liste, racine, op.index, iop);
9974
- created.push(...Object.keys(acc));
9975
- inverses.push({ op: "remove", id: racine });
9976
- return;
9977
- }
9978
- case "move": {
9979
- const node4 = doc.nodes[op.id];
9980
- if (!node4) refus(iop, "noeud_introuvable");
9981
- if (op.parent === op.id || estDescendant(doc, op.id, op.parent)) refus(iop, "deplacement_dans_son_propre_descendant");
9982
- const ici = emplacement(doc, op.id);
9983
- const liste = listeDuParent(doc, op.parent, node4.type, iop);
9984
- ici.liste.splice(ici.index, 1);
9985
- placer(liste, op.id, op.index, iop);
9986
- inverses.push({ op: "move", id: op.id, parent: ici.parent, index: ici.index });
9987
- return;
9988
- }
9989
- case "remove": {
9990
- if (!doc.nodes[op.id]) refus(iop, "noeud_introuvable");
9991
- const ici = emplacement(doc, op.id);
9992
- const arbre = sousArbre(doc, op.id);
9993
- ici.liste.splice(ici.index, 1);
9994
- for (const id of Object.keys(arbre)) delete doc.nodes[id];
9995
- removed.push(...Object.keys(arbre));
9996
- inverses.push({ op: "restore", parent: ici.parent, index: ici.index, root: op.id, nodes: arbre });
9997
- return;
9998
- }
9999
- case "restore": {
10000
- if (!op.__interne) refus(iop, "operation_inconnue");
10001
- const liste = listeDuParent(doc, op.parent, op.nodes[op.root].type, iop);
10002
- Object.assign(doc.nodes, structuredClone(op.nodes));
10003
- placer(liste, op.root, op.index, iop);
10004
- inverses.push({ op: "remove", id: op.root });
10005
- return;
10006
- }
10007
- default:
10008
- refus(iop, "operation_inconnue");
10009
- }
10010
- }
10011
- function applyOps(doc, ops, { internal = false } = {}) {
10012
- if (!Array.isArray(ops)) throw new StudioError("studio_op_invalid", "Un lot d'op\xE9rations est une liste.", { index: -1, reason: "liste_attendue" });
10013
- const copie2 = structuredClone(doc);
10014
- const inverses = [];
10015
- const created = [];
10016
- const removed = [];
10017
- ops.forEach((op, i) => appliquerUne(copie2, internal && op?.op === "restore" ? { ...op, __interne: true } : op, i, inverses, created, removed));
10018
- return { doc: copie2, inverse: inverses.reverse(), created, removed };
10019
- }
10020
-
10021
- // src/studio/style.js
10022
- var px = (v) => `${+v.toFixed(3)}px`;
10023
- var ALIGN = { start: "flex-start", center: "center", end: "flex-end", stretch: "stretch" };
10024
- var JUSTIFY = { start: "flex-start", center: "center", end: "flex-end", between: "space-between" };
10025
- function remplissage(f) {
10026
- if (typeof f === "string") return f;
10027
- return `linear-gradient(${+f.angle.toFixed(3)}deg, ${f.stops.map((s) => `${s.color} ${+(s.at * 100).toFixed(3)}%`).join(", ")})`;
10028
- }
10029
- function padding(p) {
10030
- if (typeof p === "number") return px(p);
10031
- return p.map(px).join(" ");
10032
- }
10033
- function taille(decl, axe, v, parent) {
10034
- if (v === void 0) return;
10035
- const prop = axe === "w" ? "width" : "height";
10036
- const mode = parent?.layout?.mode;
10037
- const dir = parent?.layout?.direction || "row";
10038
- const principal = mode === "flex" && (axe === "w" && dir === "row" || axe === "h" && dir === "column");
10039
- if (typeof v === "number") {
10040
- decl.push([prop, px(v)]);
10041
- if (principal) decl.push(["flex-shrink", "0"]);
10042
- } else if (v === "fill") {
10043
- if (principal) decl.push(["flex", "1 1 0"], [axe === "w" ? "min-width" : "min-height", "0"]);
10044
- else if (mode === "flex") decl.push(["align-self", "stretch"]);
10045
- else decl.push([prop, "100%"]);
10046
- } else if (v === "hug") {
10047
- decl.push([prop, "fit-content"]);
10048
- }
10049
- }
10050
- function nodeCss(node4, parent = null) {
10051
- const d = [];
10052
- const pos = node4.position;
10053
- if (parent?.layout?.mode === "free" || pos?.absolute) {
10054
- d.push(["position", "absolute"], ["left", px(pos?.x ?? 0)], ["top", px(pos?.y ?? 0)]);
10055
- }
10056
- const l = node4.layout;
10057
- if (node4.type === "frame") {
10058
- if (l?.mode === "grid") {
10059
- d.push(["display", "grid"], ["grid-template-columns", `repeat(${l.columns || 2}, minmax(0, 1fr))`]);
10060
- } else if (l?.mode === "free") {
10061
- if (!d.some(([p]) => p === "position")) d.push(["position", "relative"]);
10062
- } else {
10063
- d.push(["display", "flex"], ["flex-direction", l?.direction || "column"]);
10064
- if (l?.wrap) d.push(["flex-wrap", "wrap"]);
10065
- if (l?.align) d.push(["align-items", ALIGN[l.align]]);
10066
- if (l?.justify) d.push(["justify-content", JUSTIFY[l.justify]]);
10067
- }
10068
- if (l?.gap !== void 0 && l.mode !== "free") d.push(["gap", px(l.gap)]);
10069
- if (l?.padding !== void 0) d.push(["padding", padding(l.padding)]);
10070
- }
10071
- taille(d, "w", node4.size?.w, parent);
10072
- taille(d, "h", node4.size?.h, parent);
10073
- for (const [k, prop] of [["minW", "min-width"], ["minH", "min-height"], ["maxW", "max-width"], ["maxH", "max-height"]]) {
10074
- if (node4.size?.[k] !== void 0) d.push([prop, px(node4.size[k])]);
10075
- }
10076
- const s = node4.style || {};
10077
- if (s.fill !== void 0 && node4.type !== "text") d.push(["background", remplissage(s.fill)]);
10078
- if (s.stroke) d.push(["border", `${px(s.stroke.width)} solid ${s.stroke.color}`]);
10079
- if (node4.type === "shape" && node4.shape?.kind === "ellipse") d.push(["border-radius", "50%"]);
10080
- else if (s.radius !== void 0) d.push(["border-radius", typeof s.radius === "number" ? px(s.radius) : s.radius.map(px).join(" ")]);
10081
- 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(", ")]);
10082
- if (s.opacity !== void 0 && s.opacity !== 1) d.push(["opacity", String(s.opacity)]);
10083
- if (s.clip) d.push(["overflow", "hidden"]);
10084
- if (node4.type === "shape" && node4.shape?.kind === "line") d.push(["height", "0"], ["border-top", `${px(s.stroke?.width ?? 1)} solid ${s.stroke?.color ?? "#000000"}`]);
10085
- const t = node4.text;
10086
- if (node4.type === "text") {
10087
- if (t.font) d.push(["font-family", `"${t.font}", sans-serif`]);
10088
- if (t.size !== void 0) d.push(["font-size", px(t.size)]);
10089
- if (t.weight !== void 0) d.push(["font-weight", String(t.weight)]);
10090
- if (t.lineHeight !== void 0) d.push(["line-height", String(t.lineHeight)]);
10091
- if (t.letterSpacing !== void 0) d.push(["letter-spacing", px(t.letterSpacing)]);
10092
- if (t.align) d.push(["text-align", t.align]);
10093
- if (t.transform && t.transform !== "none") d.push(["text-transform", t.transform]);
10094
- d.push(["color", t.color || "#000000"]);
10095
- if (s.fill !== void 0) d.push(["background", remplissage(s.fill)]);
10096
- d.push(["white-space", "pre-wrap"]);
10097
- }
10098
- if (node4.type === "image") d.push(["display", "block"], ["object-fit", node4.image.fit || "cover"]);
10099
- return d;
10100
- }
10101
- function tagOf(node4) {
10102
- return node4.as || DEFAULT_TAG[node4.type];
10103
- }
10104
- var BASE_CSS = "*,*::before,*::after{box-sizing:border-box;margin:0}";
10105
- function parentsOf(doc) {
10106
- const m = /* @__PURE__ */ new Map();
10107
- for (const p of doc.pages) for (const id of p.frames) m.set(id, null);
10108
- for (const n of Object.values(doc.nodes)) for (const e of n.children || []) m.set(e, n);
10109
- return m;
10110
- }
10111
-
10112
- // src/studio/check.js
10113
- function parseColor(c) {
10114
- if (!isColor(c)) return null;
10115
- const s = c.trim().toLowerCase();
10116
- if (s === "transparent") return [0, 0, 0, 0];
10117
- if (s.startsWith("#")) {
10118
- let h = s.slice(1);
10119
- if (h.length <= 4) h = [...h].map((x) => x + x).join("");
10120
- const n = (i) => parseInt(h.slice(i, i + 2), 16);
10121
- return [n(0), n(2), n(4), h.length === 8 ? n(6) / 255 : 1];
10122
- }
10123
- const v = s.match(/[\d.]+/g).map(Number);
10124
- return [v[0], v[1], v[2], v[3] ?? 1];
10125
- }
10126
- function luminance([r, g, b]) {
10127
- const lin = (x) => {
10128
- x /= 255;
10129
- return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
10130
- };
10131
- return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
10132
- }
10133
- var melange = (dessus, fond) => [0, 1, 2].map((i) => dessus[i] * dessus[3] + fond[i] * (1 - dessus[3])).concat(1);
10134
- function contrastRatio(a, b) {
10135
- const [l1, l2] = [luminance(a), luminance(b)].sort((x, y) => y - x);
10136
- return (l1 + 0.05) / (l2 + 0.05);
10137
- }
10138
- function fondsSous(doc, id, parents) {
10139
- const couches = [];
10140
- let n = doc.nodes[id];
10141
- if (n.type === "text" && n.style?.fill !== void 0) couches.push(n.style.fill);
10142
- for (let p = parents.get(id); p; p = parents.get(p.id)) if (p.style?.fill !== void 0) couches.push(p.style.fill);
10143
- let fonds = [[255, 255, 255, 1]];
10144
- for (const f of couches.reverse()) {
10145
- const couleurs = typeof f === "string" ? [parseColor(f)] : f.stops.map((s) => parseColor(s.color));
10146
- fonds = couleurs.flatMap((c) => fonds.map((base2) => melange(c, base2)));
10147
- }
10148
- return fonds;
10149
- }
10150
- function check(doc) {
10151
- const issues = [];
10152
- const parents = parentsOf(doc);
10153
- for (const n of Object.values(doc.nodes)) {
10154
- if (n.type === "text") {
10155
- const couleur = parseColor(n.text.color || "#000000");
10156
- const grand = (n.text.size ?? 16) >= 24 || (n.text.size ?? 16) >= 18.66 && (n.text.weight ?? 400) >= 700;
10157
- const requis = grand ? 3 : 4.5;
10158
- let pire = null;
10159
- for (const fond of fondsSous(doc, n.id, parents)) {
10160
- const ratio = contrastRatio(melange(couleur, fond), fond);
10161
- if (!pire || ratio < pire.ratio) pire = { ratio, fond };
10162
- }
10163
- if (pire && pire.ratio < requis) {
10164
- const hex = (c) => `#${c.slice(0, 3).map((x) => Math.round(x).toString(16).padStart(2, "0")).join("")}`;
10165
- 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) } });
10166
- }
10167
- }
10168
- if (n.type === "frame" && n.children.length === 0 && n.style?.fill === void 0 && !n.style?.stroke) {
10169
- issues.push({ rule: "empty-frame", severity: "warning", node: n.id, name: n.name });
10170
- }
10171
- if (n.type === "image" && !n.alt) issues.push({ rule: "image-alt", severity: "warning", node: n.id, name: n.name });
10172
- }
10173
- return { issues };
10174
- }
10175
-
10176
- // src/studio/emit/html.js
10177
- var ECHAPPE = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
10178
- var escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ECHAPPE[c]);
10179
- function slug(nom) {
10180
- const s = String(nom).normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
10181
- return /^[a-z]/.test(s) ? s : `n-${s || "noeud"}`;
10182
- }
10183
- function classNames(doc, page) {
10184
- const prises = /* @__PURE__ */ new Set();
10185
- const classes = /* @__PURE__ */ new Map();
10186
- const unique = (base2) => {
10187
- let c = base2;
10188
- let k = 2;
10189
- while (prises.has(c)) c = `${base2}-${k++}`;
10190
- prises.add(c);
10191
- return c;
10192
- };
10193
- const visiter = (id, racine) => {
10194
- const n = doc.nodes[id];
10195
- const c = racine ? unique(`${racine}__${slug(n.name)}`) : unique(slug(n.name));
10196
- classes.set(id, c);
10197
- for (const e of n.children || []) visiter(e, racine || c);
10198
- };
10199
- for (const id of page.frames) visiter(id, null);
10200
- return classes;
10201
- }
10202
- function emitHtml(doc, { page: pageId, assets = {}, title, lang = "fr" } = {}) {
10203
- const page = pageId ? doc.pages.find((p) => p.id === pageId) : doc.pages[0];
10204
- if (!page) throw new StudioError("studio_page_not_found", `Page introuvable : ${pageId}`, void 0, 404);
10205
- const parents = parentsOf(doc);
10206
- const classes = classNames(doc, page);
10207
- const warnings = [];
10208
- const regles = [BASE_CSS];
10209
- const html = (id, profondeur) => {
10210
- const n = doc.nodes[id];
10211
- const c = classes.get(id);
10212
- const decl = nodeCss(n, parents.get(id));
10213
- if (decl.length) regles.push(`.${c}{${decl.map(([p, v]) => `${p}:${v}`).join(";")}}`);
10214
- const tag = tagOf(n);
10215
- const pad2 = " ".repeat(profondeur);
10216
- if (n.type === "image") {
10217
- const asset = n.image.src.slice("asset:".length);
10218
- if (n.alt === void 0) warnings.push(`image-alt : \xAB ${n.name} \xBB n'a pas de texte alternatif`);
10219
- return `${pad2}<img class="${c}" src="${escapeHtml(assets[asset] || `assets/${asset}`)}" alt="${escapeHtml(n.alt ?? "")}">`;
10220
- }
10221
- if (n.type === "text") return `${pad2}<${tag} class="${c}">${escapeHtml(n.text.content)}</${tag}>`;
10222
- const enfants = (n.children || []).map((e) => html(e, profondeur + 1));
10223
- return enfants.length ? `${pad2}<${tag} class="${c}">
10224
- ${enfants.join("\n")}
10225
- ${pad2}</${tag}>` : `${pad2}<${tag} class="${c}"></${tag}>`;
10226
- };
10227
- const corps = page.frames.map((id) => html(id, 2)).join("\n");
10228
- const index = `<!doctype html>
10229
- <html lang="${escapeHtml(lang)}">
10230
- <head>
10231
- <meta charset="utf-8">
10232
- <meta name="viewport" content="width=device-width, initial-scale=1">
10233
- <title>${escapeHtml(title || page.name)}</title>
10234
- <link rel="stylesheet" href="styles.css">
10235
- </head>
10236
- <body>
10237
- ${corps}
10238
- </body>
10239
- </html>
10240
- `;
10241
- const css = `${regles.join("\n")}
10242
- `;
10243
- const octets = (s) => new TextEncoder().encode(s).length;
10244
- return {
10245
- target: "html",
10246
- files: [
10247
- { path: "index.html", content: index, bytes: octets(index) },
10248
- { path: "styles.css", content: css, bytes: octets(css) }
10249
- ],
10250
- warnings
10251
- };
10252
- }
10253
-
10254
- // src/studio/render.js
10255
- function renderNode(doc, nodeId, { document: d = globalThis.document, assets = {}, parents = parentsOf(doc) } = {}) {
10256
- if (!d || typeof d.createElement !== "function") {
10257
- throw new StudioError("studio_render_unavailable", "Le rendu demande un navigateur (aucun DOM ici).");
10258
- }
10259
- const creer = (id) => {
10260
- const n = doc.nodes[id];
10261
- const el = d.createElement(tagOf(n));
10262
- el.setAttribute("data-node-id", id);
10263
- for (const [prop, valeur] of nodeCss(n, parents.get(id))) el.style.setProperty(prop, valeur);
10264
- if (n.type === "image") {
10265
- const asset = n.image.src.slice("asset:".length);
10266
- el.setAttribute("src", assets[asset] || `assets/${asset}`);
10267
- el.setAttribute("alt", n.alt ?? "");
10268
- } else if (n.type === "text") {
10269
- el.textContent = n.text.content;
10270
- } else {
10271
- for (const e of n.children || []) el.appendChild(creer(e));
10272
- }
10273
- return el;
10274
- };
10275
- if (!doc.nodes[nodeId]) throw new StudioError("studio_node_not_found", `N\u0153ud introuvable : ${nodeId}`, void 0, 404);
10276
- return creer(nodeId);
10277
- }
10278
-
10279
- // src/studio/raster.js
10280
- var XHTML = "http://www.w3.org/1999/xhtml";
10281
- async function enData(url) {
10282
- const reponse = await fetch(url);
10283
- if (!reponse.ok) throw new StudioError("studio_asset_unavailable", `Ressource illisible pour l'export : ${url} (${reponse.status})`);
10284
- const blob = await reponse.blob();
10285
- return await new Promise((ok, ko) => {
10286
- const f = new FileReader();
10287
- f.onload = () => ok(f.result);
10288
- f.onerror = ko;
10289
- f.readAsDataURL(blob);
10290
- });
10291
- }
10292
- async function policesIncorporees(d) {
10293
- const regles = [];
10294
- for (const feuille of d.styleSheets) {
10295
- let liste;
10296
- try {
10297
- liste = feuille.cssRules;
10298
- } catch {
10299
- continue;
10300
- }
10301
- for (const r of liste) {
10302
- if (r.type !== 5) continue;
10303
- let css = r.cssText;
10304
- const base2 = feuille.href || d.baseURI;
10305
- for (const [, brut] of css.matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/g)) {
10306
- if (brut.startsWith("data:")) continue;
10307
- css = css.replace(brut, await enData(new URL(brut, base2).href));
10308
- }
10309
- regles.push(css);
10310
- }
10311
- }
10312
- return regles.join("\n");
10313
- }
10314
- function figerLignes(racine, d) {
10315
- for (const el of racine.querySelectorAll("[data-node-id]")) {
10316
- const texte = el.firstChild;
10317
- if (!texte || texte.nodeType !== 3 || el.childNodes.length !== 1) continue;
10318
- const t = texte.textContent;
10319
- const r = d.createRange();
10320
- let haut = null;
10321
- let sortie = "";
10322
- for (let i = 0; i < t.length; i++) {
10323
- r.setStart(texte, i);
10324
- r.setEnd(texte, i + 1);
10325
- const rect = r.getClientRects()[0];
10326
- if (rect && haut !== null && rect.top > haut + 1 && t[i] !== " " && t[i] !== "\n") sortie = `${sortie.replace(/ +$/, "")}
10327
- `;
10328
- if (rect) haut = rect.top;
10329
- sortie += t[i];
10330
- }
10331
- texte.textContent = sortie;
10332
- el.style.setProperty("white-space", "pre");
10333
- }
10334
- }
10335
- async function renderPng(doc, { frame, scale = 1, assets = {}, document: d = globalThis.document } = {}) {
10336
- const W = globalThis;
10337
- if (!d?.body || typeof W.XMLSerializer !== "function" || typeof W.Image !== "function" || typeof W.fetch !== "function") {
10338
- throw new StudioError("studio_render_unavailable", "L'export d'image se fait dans un navigateur (aucun DOM ici).");
10339
- }
10340
- 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" });
10341
- const id = doc.nodes[frame]?.type === "frame" ? frame : Object.values(doc.nodes).find((n) => n.type === "frame" && n.name === frame)?.id;
10342
- if (!id) throw new StudioError("studio_node_not_found", `Cadre introuvable : ${frame}`, void 0, 404);
10343
- const hote = d.createElement("div");
10344
- hote.setAttribute("aria-hidden", "true");
10345
- hote.setAttribute("data-studio-raster", "");
10346
- hote.style.cssText = "position:fixed;left:-100000px;top:0;contain:layout style;pointer-events:none";
10347
- const base2 = d.createElement("style");
10348
- base2.textContent = "[data-studio-raster] *,[data-studio-raster] *::before,[data-studio-raster] *::after{box-sizing:border-box;margin:0}";
10349
- hote.append(base2, renderNode(doc, id, { document: d, assets }));
10350
- d.body.appendChild(hote);
10351
- try {
10352
- const el = hote.lastChild;
10353
- await d.fonts?.ready;
10354
- await Promise.all([...el.querySelectorAll("img")].map((img) => img.decode().catch(() => {
10355
- })));
10356
- figerLignes(el, d);
10357
- const rect = el.getBoundingClientRect();
10358
- const width = Math.ceil(rect.width);
10359
- const height = Math.ceil(rect.height);
10360
- const copie2 = el.cloneNode(true);
10361
- for (const img of copie2.querySelectorAll("img")) img.setAttribute("src", await enData(new URL(img.getAttribute("src"), d.baseURI).href));
10362
- const polices = await policesIncorporees(d);
10363
- const xhtml = new W.XMLSerializer().serializeToString(copie2);
10364
- const style = `${BASE_CSS}
10365
- ${polices}`.replace(/]]>/g, "]]&gt;");
10366
- 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>`;
10367
- const image = new W.Image();
10368
- image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
10369
- await image.decode();
10370
- const canvas = d.createElement("canvas");
10371
- canvas.width = Math.round(width * scale);
10372
- canvas.height = Math.round(height * scale);
10373
- canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
10374
- const blob = await new Promise((ok) => canvas.toBlob(ok, "image/png"));
10375
- return { bytes: new Uint8Array(await blob.arrayBuffer()), mime: "image/png", width: canvas.width, height: canvas.height };
10376
- } finally {
10377
- hote.remove();
10378
- }
10379
- }
10380
-
10381
- // src/studio/targets.js
10382
- var TARGETS = Object.freeze([
10383
- Object.freeze({ target: "html", status: "available" }),
10384
- Object.freeze({ target: "email", status: "planned", phase: 3 }),
10385
- Object.freeze({ target: "react", status: "planned", phase: 6 })
10386
- ]);
10387
-
10388
- // src/studio/document.js
10389
- var copie = (v) => v === void 0 ? void 0 : structuredClone(v);
10390
- var StudioDocument = class {
10391
- #doc;
10392
- #passe = [];
10393
- // lots qui défont, du plus ancien au plus récent
10394
- #futur = [];
10395
- // lots qui refont
10396
- #ecoutes = /* @__PURE__ */ new Set();
10397
- /** @param {object} [json] un document enregistré ; absent : un document vide */
10398
- constructor(json) {
10399
- this.#doc = json === void 0 ? createDocument() : assertValid(migrate(structuredClone(json)));
10400
- }
10401
- /* ── Lire ────────────────────────────────────────────────────────────────────────────────── */
10402
- get pages() {
10403
- return this.#doc.pages.map((p) => ({ ...p, frames: [...p.frames] }));
10404
- }
10405
- /** Une copie du nœud : la modifier ne change pas le document (seules les opérations le font). */
10406
- node(id) {
10407
- return copie(this.#doc.nodes[id]) ?? null;
10408
- }
10409
- /** Premier nœud qui correspond, dans l'ordre des pages puis de l'arbre. `{ name, type }` */
10410
- find(critere = {}) {
10411
- return this.findAll(critere)[0] ?? null;
10412
- }
10413
- findAll({ name, type } = {}) {
10414
- const out = [];
10415
- const visiter = (id) => {
10416
- const n = this.#doc.nodes[id];
10417
- if ((name === void 0 || n.name === name) && (type === void 0 || n.type === type)) out.push(copie(n));
10418
- for (const e of n.children || []) visiter(e);
10419
- };
10420
- for (const p of this.#doc.pages) for (const id of p.frames) visiter(id);
10421
- return out;
10422
- }
10423
- /** Le document en forme canonique : deux documents égaux donnent les mêmes octets. */
10424
- toJSON() {
10425
- return structuredClone(canonical(this.#doc));
10426
- }
10427
- /* ── Vérifier, émettre, rendre (P85) ─────────────────────────────────────────────────────── */
10428
- /** → `{ issues: [{ rule, severity, node, name, detail? }] }` */
10429
- check() {
10430
- return check(this.#doc);
10431
- }
10432
- /** → `{ target, files: [{ path, content, bytes }], warnings }`. Phase 1 : `target: "html"` seulement. */
10433
- emit({ target = "html", ...options } = {}) {
10434
- if (target !== "html") {
10435
- const prevue = TARGETS.find((t) => t.target === target);
10436
- 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);
10437
- }
10438
- return emitHtml(this.#doc, options);
10439
- }
10440
- /** Un cadre en PNG, dans le navigateur. → `{ bytes, mime, width, height }` ; hors navigateur : `studio_render_unavailable`. */
10441
- async render({ frame, format = "png", scale = 1, assets, document } = {}) {
10442
- 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);
10443
- return renderPng(this.#doc, { frame, scale, assets, document });
10444
- }
10445
- /* ── Modifier ────────────────────────────────────────────────────────────────────────────── */
10446
- /** Applique un lot, en entier ou pas du tout. → `{ applied, created, removed }` */
10447
- apply(ops, { source = "user" } = {}) {
10448
- const r = applyOps(this.#doc, ops);
10449
- this.#doc = r.doc;
10450
- this.#passe.push(r.inverse);
10451
- this.#futur = [];
10452
- this.#emettre(ops, source);
10453
- return { applied: ops.length, created: r.created, removed: r.removed };
10454
- }
10455
- set(id, path, value) {
10456
- return this.apply([{ op: "set", id, path, value }]);
10457
- }
10458
- /** Insère un nœud et rend son id. `parent` : id d'un cadre, ou d'une page. */
10459
- insert(parent, node4, { index } = {}) {
10460
- return this.apply([{ op: "insert", parent, node: node4, index }]).created[0];
10461
- }
10462
- move(id, { parent, index } = {}) {
10463
- return this.apply([{ op: "move", id, parent, index }]);
10464
- }
10465
- remove(id) {
10466
- return this.apply([{ op: "remove", id }]);
10467
- }
10468
- undo() {
10469
- return this.#deplacer(this.#passe, this.#futur, "undo");
10470
- }
10471
- redo() {
10472
- return this.#deplacer(this.#futur, this.#passe, "redo");
10473
- }
10474
- history() {
10475
- return { undo: this.#passe.length, redo: this.#futur.length };
10476
- }
10477
- /** Écoute les changements ; rend la fonction qui arrête l'écoute. `e = { ops, source }` */
10478
- on(evenement, fn) {
10479
- if (evenement !== "change") throw new StudioError("studio_event_unknown", `\xC9v\xE9nement inconnu : ${evenement}`);
10480
- this.#ecoutes.add(fn);
10481
- return () => this.#ecoutes.delete(fn);
10482
- }
10483
- #deplacer(depuis, vers, source) {
10484
- const lot = depuis.pop();
10485
- if (!lot) return false;
10486
- const r = applyOps(this.#doc, lot, { internal: true });
10487
- this.#doc = r.doc;
10488
- vers.push(r.inverse);
10489
- this.#emettre(lot, source);
10490
- return true;
10491
- }
10492
- #emettre(ops, source) {
10493
- for (const fn of this.#ecoutes) {
10494
- try {
10495
- fn({ ops: copie(ops), source });
10496
- } catch {
10497
- }
10498
- }
10499
- }
10500
- };
10501
-
10502
- // src/resources/design.js
10503
- var base = "/api/design";
10504
- var projectPath = (id) => `${base}/projects/${encodeURIComponent(id)}`;
10505
- var byType = (path, type) => type === void 0 ? path : `${path}?type=${encodeURIComponent(type)}`;
10506
- var StudioProject = class _StudioProject {
10507
- #client;
10508
- constructor(client, data) {
10509
- this.#client = client;
10510
- Object.assign(this, data);
10511
- }
10512
- async open() {
10513
- const path = projectPath(this.id);
10514
- const { document, version } = await this.#client.get(`${path}/document`);
10515
- const doc = new StudioDocument(document);
10516
- let current = version;
10517
- let pending = Promise.resolve();
10518
- doc.save = ({ version: name } = {}) => {
10519
- const document2 = doc.toJSON();
10520
- const request = pending.then(async () => {
10521
- const result = await this.#client.post(`${path}/document`, { document: document2, baseVersion: current, name });
10522
- current = result.version;
10523
- this.version = { id: current, name: name ?? null };
10524
- this.bytes = result.bytes;
10525
- return { version: current, bytes: result.bytes };
10526
- });
10527
- pending = request.catch(() => {
10528
- });
10529
- return request;
10530
- };
10531
- return doc;
10532
- }
10533
- async update(data) {
10534
- const { project } = await this.#client.post(projectPath(this.id), data);
10535
- Object.assign(this, project);
10536
- return this;
10537
- }
10538
- async duplicate(data) {
10539
- const { project } = await this.#client.post(`${projectPath(this.id)}/duplicate`, data);
10540
- return new _StudioProject(this.#client, project);
10541
- }
10542
- async versions() {
10543
- return (await this.#client.get(`${projectPath(this.id)}/versions`)).versions;
10544
- }
10545
- async restore(version) {
10546
- const { project } = await this.#client.post(`${projectPath(this.id)}/restore`, { version });
10547
- Object.assign(this, project);
10548
- return this;
10549
- }
10550
- async render({ frame, width, height } = {}) {
10551
- return this.#client.post(`${projectPath(this.id)}/render`, { frame, width, height }, { timeout: 0 });
10552
- }
10553
- };
10554
- var DesignResource = class {
10555
- constructor(client) {
10556
- const wrap = (data) => new StudioProject(client, data);
10557
- this.templates = {
10558
- list: async ({ type } = {}) => (await client.get(byType(`${base}/templates`, type))).templates,
10559
- get: async (id) => (await client.get(`${base}/templates/${encodeURIComponent(id)}`)).template
10560
- };
10561
- this.projects = {
10562
- create: async (data) => wrap((await client.post(`${base}/projects`, data)).project),
10563
- list: async ({ type } = {}) => (await client.get(byType(`${base}/projects`, type))).projects.map(wrap),
10564
- get: async (id) => wrap((await client.get(projectPath(id))).project),
10565
- remove: async (id) => client.delete(projectPath(id))
10566
- };
10567
- }
10568
- /** Un document vide, ou rouvert depuis son JSON (validé ; invalide → `studio_document_invalid`). */
10569
- document(json) {
10570
- return new StudioDocument(json);
10571
- }
10572
- /** Les cibles d'émission et leur état : `[{ target, status: "available" | "planned", phase? }]` */
10573
- targets() {
10574
- return TARGETS.map((t) => ({ ...t }));
10575
- }
10576
- };
10577
-
10578
9498
  // src/index.js
10579
9499
  var DEFAULT_BASE_URL = typeof process !== "undefined" && process?.env?.IAGENIFY_API_URL || "https://api.iagenify.com";
10580
9500
  var IaGenify = class {
@@ -10663,7 +9583,6 @@ var IaGenify = class {
10663
9583
  this.mail = new MailResource(this._client);
10664
9584
  this.hosts = new HostsResource(this._client);
10665
9585
  this.compute = new ComputeResource(this._client);
10666
- this.design = new DesignResource(this._client);
10667
9586
  }
10668
9587
  async getUser() {
10669
9588
  const res = await this._client.get("/api/auth/me");