iagenify 0.4.4 → 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/README.md +0 -38
- package/dist/index.cjs +161 -1242
- package/dist/index.js +161 -1242
- package/package.json +2 -7
- package/dist/studio.js +0 -907
package/dist/index.cjs
CHANGED
|
@@ -1723,10 +1723,10 @@ function cloudUsageLine(storage, usage) {
|
|
|
1723
1723
|
const u = usage?.[storage?.service];
|
|
1724
1724
|
if (!u) return "";
|
|
1725
1725
|
const mine = storage.limits?.usedBytes || 0;
|
|
1726
|
-
const
|
|
1727
|
-
const plafond =
|
|
1726
|
+
const base = (u.storages || []).find((b) => String(b.id) === String(storage.id));
|
|
1727
|
+
const plafond = base ? base.quotaBytes : u.perBaseBytes;
|
|
1728
1728
|
const plan = `(${PLAN_NAMES[usage.pack] || usage.pack} plan)`;
|
|
1729
|
-
const plein =
|
|
1729
|
+
const plein = base?.overQuota || !base && u.overQuota;
|
|
1730
1730
|
if (plafond == null) {
|
|
1731
1731
|
return `${formatBytes(mine)} used, ${SERVICE_NAMES[storage.service]} space ${formatBytes(u.usedBytes)} of ${formatBytes(u.quotaBytes)} ${plan}${u.overQuota ? " \u2014 FULL: writes are refused" : ""}`;
|
|
1732
1732
|
}
|
|
@@ -4177,135 +4177,6 @@ function createServiceTools() {
|
|
|
4177
4177
|
};
|
|
4178
4178
|
}
|
|
4179
4179
|
|
|
4180
|
-
// src/resources/designTools.js
|
|
4181
|
-
var DESIGN_TOOL_NAMES = ["design_read", "design_apply", "design_render", "design_check", "design_template"];
|
|
4182
|
-
var fail5 = (message) => {
|
|
4183
|
-
throw Object.assign(new Error(message), { code: "tool_error" });
|
|
4184
|
-
};
|
|
4185
|
-
var clip3 = (value, max = 48e3) => String(value || "").length > max ? `${String(value).slice(0, max)}
|
|
4186
|
-
\u2026[truncated]` : String(value || "");
|
|
4187
|
-
var projectId = (value) => {
|
|
4188
|
-
const id = String(value || "").trim();
|
|
4189
|
-
if (!id) fail5('"projectId" is required. Use the design project currently open in the editor.');
|
|
4190
|
-
return id;
|
|
4191
|
-
};
|
|
4192
|
-
var parseOperations = (value) => {
|
|
4193
|
-
let operations = value;
|
|
4194
|
-
if (typeof value === "string") {
|
|
4195
|
-
try {
|
|
4196
|
-
operations = JSON.parse(value);
|
|
4197
|
-
} catch (error) {
|
|
4198
|
-
fail5(`"operations" is not valid JSON (${error.message}).`);
|
|
4199
|
-
}
|
|
4200
|
-
}
|
|
4201
|
-
if (!Array.isArray(operations) || operations.length < 1 || operations.length > 100) {
|
|
4202
|
-
fail5('"operations" must be a JSON array with 1 to 100 document operations.');
|
|
4203
|
-
}
|
|
4204
|
-
return operations;
|
|
4205
|
-
};
|
|
4206
|
-
function createDesignTools() {
|
|
4207
|
-
return {
|
|
4208
|
-
design_read: {
|
|
4209
|
-
category: "read",
|
|
4210
|
-
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.",
|
|
4211
|
-
parameters: {
|
|
4212
|
-
projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
|
|
4213
|
-
node: { type: "string", description: "An existing node id from this document" }
|
|
4214
|
-
},
|
|
4215
|
-
async run({ projectId: id, node: node4 }, { api }) {
|
|
4216
|
-
const project = await api.design.projects.get(projectId(id));
|
|
4217
|
-
const doc = await project.open();
|
|
4218
|
-
const json = doc.toJSON();
|
|
4219
|
-
const describe = (nodeId) => {
|
|
4220
|
-
const item = json.nodes[nodeId];
|
|
4221
|
-
if (!item) return null;
|
|
4222
|
-
return {
|
|
4223
|
-
id: nodeId,
|
|
4224
|
-
type: item.type,
|
|
4225
|
-
name: item.name,
|
|
4226
|
-
size: item.size,
|
|
4227
|
-
position: item.position,
|
|
4228
|
-
text: item.text,
|
|
4229
|
-
style: item.style,
|
|
4230
|
-
layout: item.layout,
|
|
4231
|
-
children: (item.children || []).map(describe)
|
|
4232
|
-
};
|
|
4233
|
-
};
|
|
4234
|
-
if (node4) {
|
|
4235
|
-
const item = json.nodes[node4];
|
|
4236
|
-
if (!item) fail5(`Unknown design node id "${node4}".`);
|
|
4237
|
-
return { output: clip3(JSON.stringify(describe(node4))), summary: `Read ${item.name || node4}`, meta: { projectId: project.id, node: node4 } };
|
|
4238
|
-
}
|
|
4239
|
-
const pages = json.pages.map((page) => ({ id: page.id, name: page.name, frames: page.frames.map(describe) }));
|
|
4240
|
-
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 } };
|
|
4241
|
-
}
|
|
4242
|
-
},
|
|
4243
|
-
design_apply: {
|
|
4244
|
-
category: "write",
|
|
4245
|
-
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.",
|
|
4246
|
-
parameters: {
|
|
4247
|
-
projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
|
|
4248
|
-
operations: { type: "string", required: true, description: "JSON array of 1\u2013100 valid document operations" }
|
|
4249
|
-
},
|
|
4250
|
-
async run({ projectId: id, operations: raw }, { api }) {
|
|
4251
|
-
const operations = parseOperations(raw);
|
|
4252
|
-
const project = await api.design.projects.get(projectId(id));
|
|
4253
|
-
const doc = await project.open();
|
|
4254
|
-
const applied = doc.apply(operations, { source: "agent" });
|
|
4255
|
-
const saved = await doc.save();
|
|
4256
|
-
return {
|
|
4257
|
-
output: `Applied and saved ${applied.applied} design operation${applied.applied === 1 ? "" : "s"} to ${project.label}. The open editor will receive this exact batch.`,
|
|
4258
|
-
summary: `Updated ${project.label}`,
|
|
4259
|
-
meta: { projectId: project.id, version: saved.version, operations, created: applied.created }
|
|
4260
|
-
};
|
|
4261
|
-
}
|
|
4262
|
-
},
|
|
4263
|
-
design_render: {
|
|
4264
|
-
category: "read",
|
|
4265
|
-
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.",
|
|
4266
|
-
parameters: {
|
|
4267
|
-
projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
|
|
4268
|
-
frame: { type: "string", description: "Frame id from design_read; omit to render the first frame" }
|
|
4269
|
-
},
|
|
4270
|
-
async run({ projectId: id, frame }, { api }) {
|
|
4271
|
-
const project = await api.design.projects.get(projectId(id));
|
|
4272
|
-
const result = await project.render({ frame });
|
|
4273
|
-
if (!result?.image?.data) fail5("The design preview returned no image.");
|
|
4274
|
-
return {
|
|
4275
|
-
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.`,
|
|
4276
|
-
summary: "Rendered the design for visual review",
|
|
4277
|
-
meta: { projectId: project.id, frame: result.image.frame, width: result.image.width, height: result.image.height },
|
|
4278
|
-
attachments: [{ mime: result.image.mime || "image/png", data: result.image.data }]
|
|
4279
|
-
};
|
|
4280
|
-
}
|
|
4281
|
-
},
|
|
4282
|
-
design_check: {
|
|
4283
|
-
category: "read",
|
|
4284
|
-
description: "Run deterministic design checks on a saved project and report every issue with rule, severity, node and measured details.",
|
|
4285
|
-
parameters: { projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" } },
|
|
4286
|
-
async run({ projectId: id }, { api }) {
|
|
4287
|
-
const project = await api.design.projects.get(projectId(id));
|
|
4288
|
-
const doc = await project.open();
|
|
4289
|
-
const result = doc.check();
|
|
4290
|
-
return { output: clip3(JSON.stringify(result)), summary: `${result.issues.length} design checks reported`, meta: { projectId: project.id, issues: result.issues.length } };
|
|
4291
|
-
}
|
|
4292
|
-
},
|
|
4293
|
-
design_template: {
|
|
4294
|
-
category: "read",
|
|
4295
|
-
description: "List available Design templates, or read one template by id including its starting document.",
|
|
4296
|
-
parameters: { id: { type: "string", description: "Template id; omit to list templates" } },
|
|
4297
|
-
async run({ id }, { api }) {
|
|
4298
|
-
if (!id) {
|
|
4299
|
-
const templates2 = await api.design.templates.list({ type: "design" });
|
|
4300
|
-
return { output: clip3(JSON.stringify(templates2)), summary: `${templates2.length} design templates`, meta: { count: templates2.length } };
|
|
4301
|
-
}
|
|
4302
|
-
const template = await api.design.templates.get(id);
|
|
4303
|
-
return { output: clip3(JSON.stringify(template)), summary: `Read template ${id}`, meta: { template: id } };
|
|
4304
|
-
}
|
|
4305
|
-
}
|
|
4306
|
-
};
|
|
4307
|
-
}
|
|
4308
|
-
|
|
4309
4180
|
// src/resources/workspaceTools.js
|
|
4310
4181
|
var MAX_OUTPUT = 6e4;
|
|
4311
4182
|
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", "__pycache__", ".venv"]);
|
|
@@ -4328,12 +4199,12 @@ var MEDIA_MIME = {
|
|
|
4328
4199
|
};
|
|
4329
4200
|
var EXT_FOR = { markdown: "md", text: "txt", jpeg: "jpg", base64: "txt" };
|
|
4330
4201
|
var ATTACHMENT_MAX = 15 * 1024 * 1024;
|
|
4331
|
-
var
|
|
4202
|
+
var fail5 = (message) => {
|
|
4332
4203
|
throw new IaGenifyError(400, "tool_error", message);
|
|
4333
4204
|
};
|
|
4334
4205
|
var short = (text2 = "", max = 80) => String(text2).length > max ? `${String(text2).slice(0, max)}\u2026` : String(text2);
|
|
4335
4206
|
var filled2 = (value) => typeof value === "string" && value.trim() !== "";
|
|
4336
|
-
var
|
|
4207
|
+
var clip3 = (text2, max = MAX_OUTPUT) => text2.length > max ? `${text2.slice(0, max)}
|
|
4337
4208
|
\u2026[truncated ${text2.length - max} characters]` : text2;
|
|
4338
4209
|
var stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
4339
4210
|
var isTextMime = (mime) => mime.startsWith("text/") || /json|xml|yaml|javascript|typescript/.test(mime);
|
|
@@ -4407,7 +4278,7 @@ async function backup(files, path) {
|
|
|
4407
4278
|
}
|
|
4408
4279
|
async function readText(files, path) {
|
|
4409
4280
|
const file = await files.read(path);
|
|
4410
|
-
if (typeof file.content !== "string")
|
|
4281
|
+
if (typeof file.content !== "string") fail5(`"${path}" is not a text file.`);
|
|
4411
4282
|
return file.content;
|
|
4412
4283
|
}
|
|
4413
4284
|
var countOf = (text2, needle) => needle ? text2.split(needle).length - 1 : 0;
|
|
@@ -4465,11 +4336,11 @@ function storageArgs(args = {}) {
|
|
|
4465
4336
|
try {
|
|
4466
4337
|
parsed = JSON.parse(value);
|
|
4467
4338
|
} catch (err) {
|
|
4468
|
-
|
|
4339
|
+
fail5(`"${name}" is not valid JSON (${err.message}). Send it as JSON text, e.g. ${shape === "array" ? "[{\u2026}]" : "{\u2026}"}.`);
|
|
4469
4340
|
}
|
|
4470
4341
|
}
|
|
4471
4342
|
const isArray = Array.isArray(parsed);
|
|
4472
|
-
if (shape === "array" ? !isArray : isArray || parsed === null || typeof parsed !== "object")
|
|
4343
|
+
if (shape === "array" ? !isArray : isArray || parsed === null || typeof parsed !== "object") fail5(`"${name}" must be a JSON ${shape}.`);
|
|
4473
4344
|
return parsed;
|
|
4474
4345
|
};
|
|
4475
4346
|
return {
|
|
@@ -4482,25 +4353,25 @@ function storageArgs(args = {}) {
|
|
|
4482
4353
|
documents: parse("documents", "array")
|
|
4483
4354
|
};
|
|
4484
4355
|
}
|
|
4485
|
-
var requireText2 = (value, name) => typeof value === "string" && value.trim() ? value.trim() :
|
|
4356
|
+
var requireText2 = (value, name) => typeof value === "string" && value.trim() ? value.trim() : fail5(`"${name}" is required for this action.`);
|
|
4486
4357
|
async function pickStorage(api, name, providers) {
|
|
4487
|
-
if (!providers)
|
|
4358
|
+
if (!providers) fail5("Unknown action for this tool.");
|
|
4488
4359
|
const connected = (await api.storage.list()).filter((s) => s.type === "database" || s.type === "object");
|
|
4489
|
-
if (!connected.length)
|
|
4360
|
+
if (!connected.length) fail5("No database or bucket is connected. Tell the user to connect one in Cloud.");
|
|
4490
4361
|
const describe = (list) => list.map((s) => `"${s.label}" (${storageKindName(s, PROVIDER_NAMES)})`).join(", ");
|
|
4491
4362
|
const byName = name ? connected.find((s) => s.id === name || s.label === name) || connected.find((s) => s.label.toLowerCase() === String(name).trim().toLowerCase()) : null;
|
|
4492
|
-
if (name && !byName)
|
|
4363
|
+
if (name && !byName) fail5(`No connected storage named "${name}". Connected: ${describe(connected)}.`);
|
|
4493
4364
|
const able = connected.filter((s) => providers.includes(engineOf(s)));
|
|
4494
4365
|
const storage = byName || (able.length === 1 ? able[0] : null);
|
|
4495
|
-
if (!storage)
|
|
4496
|
-
if (!providers.includes(engineOf(storage)))
|
|
4366
|
+
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)}.`);
|
|
4367
|
+
if (!providers.includes(engineOf(storage))) fail5(`"${storage.label}" is ${storageKindName(storage, PROVIDER_NAMES)}; this action needs ${providers.map((p) => PROVIDER_NAMES[p]).join(" or ")}.`);
|
|
4497
4368
|
return storage;
|
|
4498
4369
|
}
|
|
4499
4370
|
function sqlStatement(input) {
|
|
4500
4371
|
const sql = String(input || "").trim().replace(/;\s*$/, "");
|
|
4501
|
-
if (!sql)
|
|
4372
|
+
if (!sql) fail5('"sql" is required for this action.');
|
|
4502
4373
|
const bare = sql.replace(/--[^\n]*/g, " ").replace(/\/\*[\s\S]*?\*\//g, " ").replace(/'(?:[^']|'')*'/g, "''").replace(/"(?:[^"]|"")*"/g, '""');
|
|
4503
|
-
if (bare.includes(";"))
|
|
4374
|
+
if (bare.includes(";")) fail5("Send one SQL statement per call.");
|
|
4504
4375
|
const verb = (bare.match(/^\s*([a-z]+)/i) || [])[1]?.toUpperCase() || "";
|
|
4505
4376
|
const writesInside = /\b(INSERT|UPDATE|DELETE|REPLACE|CREATE|ALTER|DROP)\b/i.test(bare);
|
|
4506
4377
|
const read = ["SELECT", "EXPLAIN"].includes(verb) && !writesInside || verb === "WITH" && !writesInside || verb === "PRAGMA" && !bare.includes("=");
|
|
@@ -4515,28 +4386,28 @@ async function checkStorageWrite(rawArgs = {}, { api, mode } = {}) {
|
|
|
4515
4386
|
const emptyFilter = !args.filter || !Object.keys(args.filter).length;
|
|
4516
4387
|
let statement = null;
|
|
4517
4388
|
if (["insert", "update", "delete"].includes(action)) requireText2(args.collection, "collection");
|
|
4518
|
-
if (action === "insert" && (!Array.isArray(args.documents) || !args.documents.length || args.documents.length > 500))
|
|
4389
|
+
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.");
|
|
4519
4390
|
if (action === "update") {
|
|
4520
|
-
if (emptyFilter && args.all !== true)
|
|
4521
|
-
if (!args.update || !Object.keys(args.update).length || !Object.keys(args.update).every((k) => k.startsWith("$")))
|
|
4391
|
+
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.");
|
|
4392
|
+
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.');
|
|
4522
4393
|
}
|
|
4523
|
-
if (action === "delete" && emptyFilter && args.all !== true)
|
|
4394
|
+
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.");
|
|
4524
4395
|
if (action === "sql") {
|
|
4525
4396
|
statement = sqlStatement(args.sql);
|
|
4526
|
-
if (statement.read)
|
|
4527
|
-
if (!statement.write)
|
|
4528
|
-
if (statement.drop && mode?.() !== "full")
|
|
4529
|
-
if (statement.unbounded && args.all !== true)
|
|
4397
|
+
if (statement.read) fail5('This statement only reads: use query_storage with action "sql".');
|
|
4398
|
+
if (!statement.write) fail5(`write_storage runs INSERT, UPDATE, DELETE, REPLACE, CREATE, ALTER or DROP \u2014 not ${statement.verb || "this statement"}.`);
|
|
4399
|
+
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.");
|
|
4400
|
+
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.`);
|
|
4530
4401
|
}
|
|
4531
4402
|
if (action === "put") {
|
|
4532
4403
|
requireText2(args.key, "key");
|
|
4533
|
-
if (args.content == null && !args.path)
|
|
4404
|
+
if (args.content == null && !args.path) fail5("put needs content (text) or path (a workspace file).");
|
|
4534
4405
|
}
|
|
4535
4406
|
if (action === "remove") requireText2(args.key, "key");
|
|
4536
4407
|
if (action === "create_collection") requireText2(args.collection, "collection");
|
|
4537
4408
|
if (action === "drop_collection") {
|
|
4538
4409
|
requireText2(args.collection, "collection");
|
|
4539
|
-
if (mode?.() !== "full")
|
|
4410
|
+
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.");
|
|
4540
4411
|
}
|
|
4541
4412
|
return { db, statement, args };
|
|
4542
4413
|
}
|
|
@@ -4550,7 +4421,7 @@ function createWorkspaceTools({ client }) {
|
|
|
4550
4421
|
if (typeof text2 !== "string" && attachMime) {
|
|
4551
4422
|
if (file.size > ATTACHMENT_MAX) {
|
|
4552
4423
|
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.";
|
|
4553
|
-
|
|
4424
|
+
fail5(`"${file.path}" is ${(file.size / 1048576).toFixed(1)} MB; files over ${ATTACHMENT_MAX / 1048576} MB cannot be attached.${advice}`);
|
|
4554
4425
|
}
|
|
4555
4426
|
const kind = attachMime.startsWith("audio/") ? "Listen to it" : attachMime.startsWith("video/") ? "Watch it" : "Read it";
|
|
4556
4427
|
return {
|
|
@@ -4564,7 +4435,7 @@ function createWorkspaceTools({ client }) {
|
|
|
4564
4435
|
if (CONVERTIBLE[ext]) {
|
|
4565
4436
|
const converted = await convert.convert({ from: ext, to: CONVERTIBLE[ext], file: file.content });
|
|
4566
4437
|
text2 = String(converted.content ?? converted.markdown ?? converted.text ?? "");
|
|
4567
|
-
if (!text2)
|
|
4438
|
+
if (!text2) fail5(`Could not extract text from "${path}".`);
|
|
4568
4439
|
} else {
|
|
4569
4440
|
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 } };
|
|
4570
4441
|
}
|
|
@@ -4575,7 +4446,7 @@ function createWorkspaceTools({ client }) {
|
|
|
4575
4446
|
const numbered = slice.map((l, i) => `${start + i} ${l.length > 2e3 ? `${l.slice(0, 2e3)}\u2026` : l}`).join("\n");
|
|
4576
4447
|
const more = start - 1 + slice.length < lines.length ? `
|
|
4577
4448
|
\u2026[${lines.length - (start - 1 + slice.length)} more lines \u2014 use offset]` : "";
|
|
4578
|
-
return { output:
|
|
4449
|
+
return { output: clip3(numbered + more) || "(empty file)", summary: `${file.path} \xB7 ${lines.length} lines`, meta: { path: file.path, lines: lines.length } };
|
|
4579
4450
|
}
|
|
4580
4451
|
const search = new SearchResource(client);
|
|
4581
4452
|
const fetchPage = new FetchResource(client);
|
|
@@ -4584,7 +4455,6 @@ function createWorkspaceTools({ client }) {
|
|
|
4584
4455
|
...createPlatformTools(),
|
|
4585
4456
|
// P54 : les services de la plateforme — hébergement, courrier, domaines, compte, documents, second modèle.
|
|
4586
4457
|
...createServiceTools(),
|
|
4587
|
-
...createDesignTools(),
|
|
4588
4458
|
read: {
|
|
4589
4459
|
category: "read",
|
|
4590
4460
|
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.",
|
|
@@ -4596,8 +4466,8 @@ function createWorkspaceTools({ client }) {
|
|
|
4596
4466
|
},
|
|
4597
4467
|
async run({ path, paths, offset = 1, limit = 2e3 }, context) {
|
|
4598
4468
|
const liste = Array.isArray(paths) && paths.length ? paths.map((p) => String(p)) : [String(path ?? "")];
|
|
4599
|
-
if (!filled2(liste[0]))
|
|
4600
|
-
if (liste.length > 20)
|
|
4469
|
+
if (!filled2(liste[0])) fail5('Give "path" (one file) or "paths" (several).');
|
|
4470
|
+
if (liste.length > 20) fail5(`A single call reads at most 20 files (got ${liste.length}).`);
|
|
4601
4471
|
if (liste.length === 1) return lireFichier(liste[0], { offset, limit }, context);
|
|
4602
4472
|
const lus = [];
|
|
4603
4473
|
const pieces2 = [];
|
|
@@ -4613,7 +4483,7 @@ Error: ${err.message}`);
|
|
|
4613
4483
|
}
|
|
4614
4484
|
}
|
|
4615
4485
|
return {
|
|
4616
|
-
output:
|
|
4486
|
+
output: clip3(lus.join("\n\n"), 6e4),
|
|
4617
4487
|
summary: `${liste.length} files`,
|
|
4618
4488
|
meta: { paths: liste, attached: pieces2.length || void 0 },
|
|
4619
4489
|
...pieces2.length ? { attachments: pieces2 } : {}
|
|
@@ -4650,7 +4520,7 @@ Error: ${err.message}`);
|
|
|
4650
4520
|
try {
|
|
4651
4521
|
re = new RegExp(pattern, ignore_case ? "i" : "");
|
|
4652
4522
|
} catch (err) {
|
|
4653
|
-
|
|
4523
|
+
fail5(`Invalid regular expression: ${err.message}`);
|
|
4654
4524
|
}
|
|
4655
4525
|
const only = glob ? globToRegExp(glob) : null;
|
|
4656
4526
|
const hits = [];
|
|
@@ -4684,8 +4554,8 @@ Error: ${err.message}`);
|
|
|
4684
4554
|
async run({ path, old_string, new_string, replace_all = false }, { files }) {
|
|
4685
4555
|
const before = await readText(files, path);
|
|
4686
4556
|
const count = countOf(before, old_string);
|
|
4687
|
-
if (!count)
|
|
4688
|
-
if (count > 1 && !replace_all)
|
|
4557
|
+
if (!count) fail5(`old_string was not found in "${path}". Read the file and copy the text exactly.`);
|
|
4558
|
+
if (count > 1 && !replace_all) fail5(`old_string appears ${count} times in "${path}". Add surrounding lines to make it unique, or set replace_all.`);
|
|
4689
4559
|
const after = replace_all ? before.split(old_string).join(new_string) : before.replace(old_string, () => new_string);
|
|
4690
4560
|
await backup(files, path);
|
|
4691
4561
|
await files.write(path, after);
|
|
@@ -4709,8 +4579,8 @@ Error: ${err.message}`);
|
|
|
4709
4579
|
const diffs = [];
|
|
4710
4580
|
edits.forEach((e, i) => {
|
|
4711
4581
|
const count = countOf(text2, e.old_string);
|
|
4712
|
-
if (!count)
|
|
4713
|
-
if (count > 1 && !e.replace_all)
|
|
4582
|
+
if (!count) fail5(`Edit ${i + 1}: old_string not found in "${path}". Nothing was changed.`);
|
|
4583
|
+
if (count > 1 && !e.replace_all) fail5(`Edit ${i + 1}: old_string appears ${count} times. Nothing was changed.`);
|
|
4714
4584
|
diffs.push(diffOf(text2, e.old_string, e.new_string));
|
|
4715
4585
|
text2 = e.replace_all ? text2.split(e.old_string).join(e.new_string) : text2.replace(e.old_string, () => e.new_string);
|
|
4716
4586
|
});
|
|
@@ -4754,17 +4624,17 @@ Error: ${err.message}`);
|
|
|
4754
4624
|
// Refusé avant toute permission, en disant comment faire.
|
|
4755
4625
|
check({ command = "", commands, background } = {}, { shell, terminals } = {}) {
|
|
4756
4626
|
if (commands !== void 0) {
|
|
4757
|
-
if (!Array.isArray(commands) || !commands.length)
|
|
4758
|
-
if (commands.some((c) => typeof c !== "string" || !c.trim()))
|
|
4759
|
-
if (commands.length > 20)
|
|
4760
|
-
if (background === true)
|
|
4627
|
+
if (!Array.isArray(commands) || !commands.length) fail5('"commands" must be a list of shell commands, e.g. ["npm ci", "npm run build"].');
|
|
4628
|
+
if (commands.some((c) => typeof c !== "string" || !c.trim())) fail5('Every entry of "commands" must be a non-empty command.');
|
|
4629
|
+
if (commands.length > 20) fail5(`A single call runs at most 20 commands (got ${commands.length}).`);
|
|
4630
|
+
if (background === true) fail5("background: true runs ONE command in a terminal. Use command, not commands \u2014 or run the sequence without background.");
|
|
4761
4631
|
} else if (!filled2(command)) {
|
|
4762
|
-
|
|
4632
|
+
fail5('Give "command" (one command) or "commands" (several, run in order).');
|
|
4763
4633
|
}
|
|
4764
4634
|
if (background === true || !terminals) return;
|
|
4765
4635
|
const text2 = [command, ...Array.isArray(commands) ? commands : []].filter(Boolean).join("\n");
|
|
4766
4636
|
if (DETACHED.test(text2) && RUNTIME.test(text2)) {
|
|
4767
|
-
|
|
4637
|
+
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" }.`);
|
|
4768
4638
|
}
|
|
4769
4639
|
},
|
|
4770
4640
|
async run({ command, commands, timeout_ms = 12e4, background = false, stop_on_error = true, port = null }, { root, signal, shell, terminals }) {
|
|
@@ -4773,7 +4643,7 @@ Error: ${err.message}`);
|
|
|
4773
4643
|
const seule = liste[0];
|
|
4774
4644
|
const auto = background !== true && Boolean(terminals) && liste.length === 1 && LONG_RUNNING.test(seule);
|
|
4775
4645
|
if (background === true || auto) {
|
|
4776
|
-
if (!terminals)
|
|
4646
|
+
if (!terminals) fail5("Background commands need a terminal environment, and there are none here. Run the command without background.");
|
|
4777
4647
|
const note = auto ? "This command starts a server that never exits, so it runs in a terminal instead of blocking.\n" : "";
|
|
4778
4648
|
const terminal = await terminals.create({ name: short(seule, 60), command: seule, by: "agent", ...port ? { port } : {} });
|
|
4779
4649
|
const first = await settle(terminal, signal);
|
|
@@ -4782,9 +4652,9 @@ Error: ${err.message}`);
|
|
|
4782
4652
|
const exited = first.status === "exited";
|
|
4783
4653
|
const output = exited ? `Terminal ${terminal.id} (${seule}) exited with code ${first.exitCode} right away.
|
|
4784
4654
|
--- output ---
|
|
4785
|
-
${
|
|
4655
|
+
${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.
|
|
4786
4656
|
--- first output ---
|
|
4787
|
-
${
|
|
4657
|
+
${clip3(text2, 2e4) || "(nothing yet)"}`;
|
|
4788
4658
|
const adresse = terminal.url ? `
|
|
4789
4659
|
|
|
4790
4660
|
Open it at: ${terminal.url}
|
|
@@ -4792,7 +4662,7 @@ If it does not answer, the server is listening on localhost instead of 0.0.0.0 \
|
|
|
4792
4662
|
return {
|
|
4793
4663
|
output: note + output + adresse,
|
|
4794
4664
|
summary: `${seule.slice(0, 80)} \xB7 ${exited ? `exit ${first.exitCode}` : terminal.url || `terminal ${terminal.id}`}`,
|
|
4795
|
-
meta: { command: seule, background: true, terminalId: terminal.id, status: first.status, exitCode: first.exitCode, stdout:
|
|
4665
|
+
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 }
|
|
4796
4666
|
};
|
|
4797
4667
|
}
|
|
4798
4668
|
const executer = async (cmd) => {
|
|
@@ -4844,9 +4714,9 @@ If it does not answer, the server is listening on localhost instead of 0.0.0.0 \
|
|
|
4844
4714
|
if (liste.length === 1) {
|
|
4845
4715
|
const r = await executer(seule);
|
|
4846
4716
|
const output = [`exit code ${etat(r)}`, r.stdout && `--- stdout ---
|
|
4847
|
-
${
|
|
4848
|
-
${
|
|
4849
|
-
return { output, summary: `${seule.slice(0, 80)} \xB7 exit ${etat(r)}`, meta: { command: seule, exitCode: r.code, timedOut: r.timedOut, stdout:
|
|
4717
|
+
${clip3(r.stdout, 3e4)}`, r.stderr && `--- stderr ---
|
|
4718
|
+
${clip3(r.stderr, 3e4)}`].filter(Boolean).join("\n");
|
|
4719
|
+
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) } };
|
|
4850
4720
|
}
|
|
4851
4721
|
const faits = [];
|
|
4852
4722
|
for (const cmd of liste) {
|
|
@@ -4859,9 +4729,9 @@ ${clip4(r.stderr, 3e4)}`].filter(Boolean).join("\n");
|
|
|
4859
4729
|
const bloc = faits.map((r, i) => [
|
|
4860
4730
|
`[${i + 1}/${liste.length}] ${r.cmd} \u2014 exit ${etat(r)}`,
|
|
4861
4731
|
r.stdout && `--- stdout ---
|
|
4862
|
-
${
|
|
4732
|
+
${clip3(r.stdout, part)}`,
|
|
4863
4733
|
r.stderr && `--- stderr ---
|
|
4864
|
-
${
|
|
4734
|
+
${clip3(r.stderr, part)}`
|
|
4865
4735
|
].filter(Boolean).join("\n")).join("\n\n");
|
|
4866
4736
|
const dernier = faits.at(-1);
|
|
4867
4737
|
const rates = faits.filter((r) => r.timedOut || r.code !== 0).length;
|
|
@@ -4877,8 +4747,8 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
|
|
|
4877
4747
|
exitCode: dernier ? dernier.code : null,
|
|
4878
4748
|
timedOut: Boolean(dernier?.timedOut),
|
|
4879
4749
|
results: faits.map((r) => ({ command: r.cmd, exitCode: r.code, timedOut: r.timedOut })),
|
|
4880
|
-
stdout:
|
|
4881
|
-
stderr:
|
|
4750
|
+
stdout: clip3(faits.map((r) => r.stdout).filter(Boolean).join("\n"), 4e3),
|
|
4751
|
+
stderr: clip3(faits.map((r) => r.stderr).filter(Boolean).join("\n"), 4e3)
|
|
4882
4752
|
}
|
|
4883
4753
|
};
|
|
4884
4754
|
}
|
|
@@ -4895,14 +4765,14 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
|
|
|
4895
4765
|
since: { type: "integer", description: "output: read from this position; 0 = everything kept" }
|
|
4896
4766
|
},
|
|
4897
4767
|
async run({ action, id, since }, { terminals }) {
|
|
4898
|
-
if (!terminals)
|
|
4768
|
+
if (!terminals) fail5("There are no terminals here: they only exist on a computer.");
|
|
4899
4769
|
if (action === "list") {
|
|
4900
4770
|
const all = await terminals.list();
|
|
4901
4771
|
if (!all.length) return { output: "No terminals are open.", summary: "No terminals", meta: { terminals: [] } };
|
|
4902
4772
|
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}`);
|
|
4903
4773
|
return { output: lines.join("\n"), summary: `${all.filter((t) => t.status === "running").length} running \xB7 ${all.length} terminals`, meta: { terminals: all } };
|
|
4904
4774
|
}
|
|
4905
|
-
if (!id)
|
|
4775
|
+
if (!id) fail5(`"id" is required for ${action}. Use terminal { action: "list" } to find it.`);
|
|
4906
4776
|
const terminal = await terminals.get(id);
|
|
4907
4777
|
if (action === "output") {
|
|
4908
4778
|
const from = since != null ? Number(since) : terminal.agentCursor || 0;
|
|
@@ -4912,16 +4782,16 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
|
|
|
4912
4782
|
return {
|
|
4913
4783
|
output: `${terminal.id} \xB7 ${out.status}${out.status === "exited" ? ` (code ${out.exitCode ?? "stopped"})` : ""}${out.truncated ? " \xB7 older output was dropped" : ""}
|
|
4914
4784
|
--- output ---
|
|
4915
|
-
${
|
|
4785
|
+
${clip3(text2, 3e4) || "(no new output)"}`,
|
|
4916
4786
|
summary: `${terminal.name} \xB7 ${out.status}`,
|
|
4917
|
-
meta: { terminalId: terminal.id, status: out.status, exitCode: out.exitCode, stdout:
|
|
4787
|
+
meta: { terminalId: terminal.id, status: out.status, exitCode: out.exitCode, stdout: clip3(text2, 4e3) }
|
|
4918
4788
|
};
|
|
4919
4789
|
}
|
|
4920
4790
|
if (action === "kill") {
|
|
4921
4791
|
const stopped = await terminal.kill();
|
|
4922
4792
|
return { output: `Stopped terminal ${stopped.id} (${stopped.command || stopped.name}).`, summary: `Stopped ${stopped.name}`, meta: { terminalId: stopped.id, status: stopped.status } };
|
|
4923
4793
|
}
|
|
4924
|
-
|
|
4794
|
+
fail5(`Unknown action "${action}": use list, output or kill.`);
|
|
4925
4795
|
}
|
|
4926
4796
|
},
|
|
4927
4797
|
ask_user: {
|
|
@@ -4994,7 +4864,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
4994
4864
|
const shot = r.screenshot?.base64 ? { mime: r.screenshot.mimeType || "image/jpeg", data: r.screenshot.base64 } : null;
|
|
4995
4865
|
if (screenshot === true && !shot) sections.push("--- screenshot ---\n(the page could not be captured as an image)");
|
|
4996
4866
|
return {
|
|
4997
|
-
output:
|
|
4867
|
+
output: clip3(sections.filter(Boolean).join("\n\n"), 3e4),
|
|
4998
4868
|
summary: `${r.title || url}${shot ? " \xB7 seen" : ""}`,
|
|
4999
4869
|
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 } : {} },
|
|
5000
4870
|
...shot ? { attachments: [shot] } : {}
|
|
@@ -5013,12 +4883,12 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
5013
4883
|
},
|
|
5014
4884
|
async run({ path, url, to, save }, { files }) {
|
|
5015
4885
|
const target = String(to || "").trim().toLowerCase();
|
|
5016
|
-
if (!target)
|
|
5017
|
-
if (!filled2(path) && !filled2(url))
|
|
5018
|
-
if (filled2(path) && filled2(url))
|
|
4886
|
+
if (!target) fail5('"to" is required: the format to convert into, e.g. "pdf".');
|
|
4887
|
+
if (!filled2(path) && !filled2(url)) fail5('Give "path" (a workspace file) or "url".');
|
|
4888
|
+
if (filled2(path) && filled2(url)) fail5('Give "path" or "url", not both.');
|
|
5019
4889
|
const sourceName = filled2(path) ? String(path) : new URL(String(url)).pathname.split("/").filter(Boolean).pop() || "page";
|
|
5020
4890
|
const from = sourceName.includes(".") ? sourceName.split(".").pop().toLowerCase() : "";
|
|
5021
|
-
if (!from)
|
|
4891
|
+
if (!from) fail5(`Cannot tell the format of "${sourceName}": the name has no extension.`);
|
|
5022
4892
|
let result;
|
|
5023
4893
|
if (filled2(path)) {
|
|
5024
4894
|
const file = await files.read(path);
|
|
@@ -5027,11 +4897,11 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
5027
4897
|
} else {
|
|
5028
4898
|
result = await convert.convert({ from, to: target, url: String(url) });
|
|
5029
4899
|
}
|
|
5030
|
-
if (!result?.ok)
|
|
4900
|
+
if (!result?.ok) fail5(result?.message || `Conversion ${from} \u2192 ${target} failed.`);
|
|
5031
4901
|
const data = result.content !== void 0 ? String(result.content) : Buffer.from(result.base64 || "", "base64");
|
|
5032
4902
|
const ext = EXT_FOR[target] || target;
|
|
5033
|
-
const
|
|
5034
|
-
const destination = filled2(save) ? String(save) : filled2(path) ? `${
|
|
4903
|
+
const base = sourceName.replace(/\.[^.]+$/, "");
|
|
4904
|
+
const destination = filled2(save) ? String(save) : filled2(path) ? `${base}.${ext}` : `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${base}.${ext}`;
|
|
5035
4905
|
const written = await files.write(destination, data);
|
|
5036
4906
|
return {
|
|
5037
4907
|
output: `Converted ${sourceName} (${from} \u2192 ${target}) to ${written.path} \u2014 ${Math.round(written.size / 1024)} KB, ${result.creditsUsed ?? 1} credit.`,
|
|
@@ -5108,7 +4978,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
5108
4978
|
const usage = await api.cloud.usage();
|
|
5109
4979
|
if (!args.storage) return { output: cloudUsageReport(usage), summary: "IaGenify Cloud \xB7 usage", meta: { action, storage: null } };
|
|
5110
4980
|
const target2 = await pickStorage(api, args.storage, STORAGE_READS.usage);
|
|
5111
|
-
if (!target2.service)
|
|
4981
|
+
if (!target2.service) fail5(`"${target2.label}" is a connected storage: its space is managed by its own provider. usage only reports IaGenify Cloud storages.`);
|
|
5112
4982
|
return { output: cloudUsageReport(usage, target2), summary: `${target2.label} \xB7 usage`, meta: { storage: target2.label, provider: target2.provider, action } };
|
|
5113
4983
|
}
|
|
5114
4984
|
const db = await pickStorage(api, args.storage, STORAGE_READS[action]);
|
|
@@ -5116,7 +4986,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
5116
4986
|
if (action === "overview") {
|
|
5117
4987
|
const seen = await db.run({ action: "overview" });
|
|
5118
4988
|
return {
|
|
5119
|
-
output:
|
|
4989
|
+
output: clip3(overviewReport(db, seen), 3e4),
|
|
5120
4990
|
summary: `${db.label} \xB7 overview`,
|
|
5121
4991
|
meta: { storage: db.label, provider: db.provider, action, returned: (seen.collections || seen.tables || seen.folders || []).length }
|
|
5122
4992
|
};
|
|
@@ -5132,13 +5002,13 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
5132
5002
|
});
|
|
5133
5003
|
} else if (action === "count") result = await db.run({ action: "count", collection: requireText2(args.collection, "collection"), filter: args.filter || {} });
|
|
5134
5004
|
else if (action === "aggregate") {
|
|
5135
|
-
if (!Array.isArray(args.pipeline) || !args.pipeline.length)
|
|
5136
|
-
if (/"\$(out|merge)"/.test(JSON.stringify(args.pipeline)))
|
|
5005
|
+
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"}}}].');
|
|
5006
|
+
if (/"\$(out|merge)"/.test(JSON.stringify(args.pipeline))) fail5("aggregate is read-only: $out and $merge are not allowed.");
|
|
5137
5007
|
result = await db.run({ action: "aggregate", collection: requireText2(args.collection, "collection"), pipeline: args.pipeline });
|
|
5138
5008
|
} else if (action === "tables") result = await db.run({ action: "tables" });
|
|
5139
5009
|
else if (action === "sql") {
|
|
5140
5010
|
const statement = sqlStatement(args.sql);
|
|
5141
|
-
if (!statement.read)
|
|
5011
|
+
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".`);
|
|
5142
5012
|
result = await db.run({ sql: statement.sql, params: Array.isArray(args.params) ? args.params : [] });
|
|
5143
5013
|
} else if (action === "objects") result = await db.run({ action: "list", prefix: String(args.prefix || "") });
|
|
5144
5014
|
else if (action === "object") result = await db.run({ action: "object", key: requireText2(args.key, "key") });
|
|
@@ -5153,7 +5023,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
5153
5023
|
};
|
|
5154
5024
|
}
|
|
5155
5025
|
return {
|
|
5156
|
-
output:
|
|
5026
|
+
output: clip3(results.map((r, i) => `[${i + 1}] ${r.source?.name || "document"} \xB7 ${r.score}
|
|
5157
5027
|
${r.text}`).join("\n\n"), 3e4),
|
|
5158
5028
|
summary: `${db.label} \xB7 ${results.length} extract${results.length === 1 ? "" : "s"}`,
|
|
5159
5029
|
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))] }
|
|
@@ -5207,7 +5077,7 @@ ${r.text}`).join("\n\n"), 3e4),
|
|
|
5207
5077
|
else if (action === "drop_collection") result = await db.run({ action: "dropCollection", collection: args.collection.trim() });
|
|
5208
5078
|
const target = args.collection || args.key || (args.sql ? String(args.sql).trim().split(/\s+/).slice(0, 3).join(" ") : "");
|
|
5209
5079
|
return {
|
|
5210
|
-
output:
|
|
5080
|
+
output: clip3(JSON.stringify(result, null, 1), 3e4),
|
|
5211
5081
|
summary: `${db.label} \xB7 ${action}${target ? ` ${target}` : ""}`,
|
|
5212
5082
|
meta: { storage: db.label, provider: db.provider, action, collection: args.collection || null, result }
|
|
5213
5083
|
};
|
|
@@ -5278,28 +5148,28 @@ var MEDIA = {
|
|
|
5278
5148
|
// produire doit se dire tout de suite, pas revenir en erreur du fournisseur une fois payé.
|
|
5279
5149
|
verify: (a, model) => {
|
|
5280
5150
|
if (OMNI_MODELS.includes(model)) {
|
|
5281
|
-
if (a.audio === true)
|
|
5151
|
+
if (a.audio === true) fail5(`"${model}" has no sound option. Use veo-3.1 for sound.`);
|
|
5282
5152
|
if (a.duration !== void 0 && a.duration !== null && a.duration !== "") {
|
|
5283
5153
|
const d = Number(a.duration);
|
|
5284
5154
|
if (!Number.isFinite(d) || d < OMNI_SECONDS.min || d > OMNI_SECONDS.max) {
|
|
5285
|
-
|
|
5155
|
+
fail5(`"${model}" makes videos of ${OMNI_SECONDS.min} to ${OMNI_SECONDS.max} seconds (the provider's limit); you asked for ${a.duration}.`);
|
|
5286
5156
|
}
|
|
5287
5157
|
}
|
|
5288
5158
|
const permises = VIDEO_RESOLUTIONS[model] || [];
|
|
5289
5159
|
if (filled2(a.resolution) && !permises.includes(a.resolution)) {
|
|
5290
|
-
|
|
5160
|
+
fail5(`"${model}" has no ${a.resolution}. It does ${permises.join(", ")}.`);
|
|
5291
5161
|
}
|
|
5292
5162
|
return;
|
|
5293
5163
|
}
|
|
5294
5164
|
if (a.audio === true && !VIDEO_WITH_AUDIO.includes(model)) {
|
|
5295
|
-
|
|
5165
|
+
fail5(`"${model}" makes no sound. Only ${VIDEO_WITH_AUDIO.join(", ")} does \u2014 pass model: "veo-3.1", or leave audio out.`);
|
|
5296
5166
|
}
|
|
5297
5167
|
if (a.duration !== void 0 && a.duration !== null && !VIDEO_DURATIONS.includes(Number(a.duration))) {
|
|
5298
|
-
|
|
5168
|
+
fail5(`duration must be ${VIDEO_DURATIONS.join(", ")} seconds; you asked for ${a.duration}.`);
|
|
5299
5169
|
}
|
|
5300
5170
|
const allowed = VIDEO_RESOLUTIONS[model] || [];
|
|
5301
5171
|
if (filled2(a.resolution) && !allowed.includes(a.resolution)) {
|
|
5302
|
-
|
|
5172
|
+
fail5(`"${model}" has no ${a.resolution}. It does ${allowed.join(", ")} \u2014 change the resolution, or pick another model.`);
|
|
5303
5173
|
}
|
|
5304
5174
|
},
|
|
5305
5175
|
// Omni : seulement ce qui a été demandé — sans durée, le modèle fait ses 10 s par défaut, et un
|
|
@@ -5388,7 +5258,7 @@ function createMediaTools({ client, media = {} }) {
|
|
|
5388
5258
|
const args = fusionner(spec, media[MEDIA_KINDS[name]] || {}, brut);
|
|
5389
5259
|
const model = filled2(args.model) ? args.model : spec.model;
|
|
5390
5260
|
if (!spec.models.includes(model)) {
|
|
5391
|
-
|
|
5261
|
+
fail5(`${name} has no model "${args.model}". Available: ${spec.models.join(", ")}.`);
|
|
5392
5262
|
}
|
|
5393
5263
|
if (spec.verify) spec.verify(args, model);
|
|
5394
5264
|
},
|
|
@@ -5400,15 +5270,15 @@ function createMediaTools({ client, media = {} }) {
|
|
|
5400
5270
|
if (spec.from && filled2(image)) {
|
|
5401
5271
|
const source = await files.read(String(image));
|
|
5402
5272
|
const mime = /^image\//.test(source.mimeType || "") ? source.mimeType : mimeOf(String(image));
|
|
5403
|
-
if (!mime || !mime.startsWith("image/"))
|
|
5404
|
-
if (source.size > ATTACHMENT_MAX)
|
|
5273
|
+
if (!mime || !mime.startsWith("image/")) fail5(`"${source.path}" is not an image (${source.mimeType || "unknown type"}).`);
|
|
5274
|
+
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.`);
|
|
5405
5275
|
inputs.push({ type: "image", content: Buffer.from(source.content).toString("base64"), mime });
|
|
5406
5276
|
}
|
|
5407
5277
|
const session = await models.create({ model, settings: spec.settings(args, model), memory: false });
|
|
5408
5278
|
try {
|
|
5409
5279
|
const result = await session.generate({ inputs, outputs: [{ type: spec.output }] });
|
|
5410
5280
|
const output = result.outputs?.find((o) => o.content);
|
|
5411
|
-
if (!output)
|
|
5281
|
+
if (!output) fail5(`The ${spec.type} model returned nothing.`);
|
|
5412
5282
|
const ext = output.mime?.split("/")[1]?.split(";")[0]?.replace("mpeg", "mp3") || spec.ext;
|
|
5413
5283
|
const target = path || `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${Date.now()}.${ext}`;
|
|
5414
5284
|
const item = await files.write(target, Buffer.from(output.content, "base64"));
|
|
@@ -5425,10 +5295,10 @@ function createMediaTools({ client, media = {} }) {
|
|
|
5425
5295
|
}
|
|
5426
5296
|
}]));
|
|
5427
5297
|
}
|
|
5428
|
-
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, ...
|
|
5298
|
+
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)];
|
|
5429
5299
|
|
|
5430
5300
|
// src/resources/prompt.js
|
|
5431
|
-
var
|
|
5301
|
+
var fail6 = (code, message) => new IaGenifyError(400, code, message);
|
|
5432
5302
|
var PROMPT_OPTIONS = {
|
|
5433
5303
|
model: "text",
|
|
5434
5304
|
mode: ["ask", "auto", "plan", "full"],
|
|
@@ -5451,8 +5321,8 @@ function storageIndex(storages = []) {
|
|
|
5451
5321
|
const byProvider = /* @__PURE__ */ new Map();
|
|
5452
5322
|
for (const s of storages) {
|
|
5453
5323
|
if (!s) continue;
|
|
5454
|
-
const
|
|
5455
|
-
if (
|
|
5324
|
+
const slug = storageSlug(s.label || s.name);
|
|
5325
|
+
if (slug) index.set(slug, s);
|
|
5456
5326
|
if (s.provider) byProvider.set(s.provider, [...byProvider.get(s.provider) || [], s]);
|
|
5457
5327
|
}
|
|
5458
5328
|
for (const [provider, list] of byProvider) if (list.length === 1 && !index.has(provider)) index.set(provider, list[0]);
|
|
@@ -5469,26 +5339,26 @@ function parsePrompt(input, library = {}) {
|
|
|
5469
5339
|
if (!flag) break;
|
|
5470
5340
|
const key = flag[1].toLowerCase();
|
|
5471
5341
|
const kind = PROMPT_OPTIONS[key];
|
|
5472
|
-
if (!kind) throw
|
|
5342
|
+
if (!kind) throw fail6("unknown_option", `Unknown option --${key}. Options: ${Object.keys(PROMPT_OPTIONS).map((k) => `--${k}`).join(" ")}. Write \\-- to start a message with "--".`);
|
|
5473
5343
|
rest = rest.slice(flag[0].length);
|
|
5474
5344
|
if (kind === "flag") {
|
|
5475
5345
|
if (key === "no-memory") options.memory = false;
|
|
5476
5346
|
continue;
|
|
5477
5347
|
}
|
|
5478
5348
|
const found = rest.match(/^(?:=|[ \t]+)("([^"]*)"|'([^']*)'|\S+)/);
|
|
5479
|
-
if (!found) throw
|
|
5349
|
+
if (!found) throw fail6("option_value_required", `--${key} needs a value.`);
|
|
5480
5350
|
const value = found[2] ?? found[3] ?? found[1];
|
|
5481
5351
|
rest = rest.slice(found[0].length);
|
|
5482
5352
|
if (key === "mode") {
|
|
5483
|
-
if (!kind.includes(value)) throw
|
|
5353
|
+
if (!kind.includes(value)) throw fail6("invalid_option", `--mode must be one of ${kind.join(", ")}.`);
|
|
5484
5354
|
options.mode = value;
|
|
5485
5355
|
} else if (key === "budget") {
|
|
5486
5356
|
if (value === "none") options.budget = null;
|
|
5487
5357
|
else if (Number(value) > 0) options.budget = Math.round(Number(value));
|
|
5488
|
-
else throw
|
|
5358
|
+
else throw fail6("invalid_option", "--budget takes a number of credits, or none.");
|
|
5489
5359
|
} else if (key === "context") {
|
|
5490
5360
|
const tokens = parseTokenCount(value);
|
|
5491
|
-
if (!tokens) throw
|
|
5361
|
+
if (!tokens) throw fail6("invalid_option", "--context takes a number of tokens: 200k, 400k, 1M.");
|
|
5492
5362
|
options.contextTokens = tokens;
|
|
5493
5363
|
} else {
|
|
5494
5364
|
options[key] = value;
|
|
@@ -5529,7 +5399,7 @@ function parsePrompt(input, library = {}) {
|
|
|
5529
5399
|
}
|
|
5530
5400
|
|
|
5531
5401
|
// src/resources/library.js
|
|
5532
|
-
var
|
|
5402
|
+
var fail7 = (status, code, message) => new IaGenifyError(status, code, message);
|
|
5533
5403
|
var NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
5534
5404
|
var MAX_CONTENT = 1e5;
|
|
5535
5405
|
var CLAUDE_TOOLS = { ls: "list", websearch: "search", webfetch: "fetch", multiedit: "multi_edit", todowrite: "todo_write" };
|
|
@@ -5611,34 +5481,34 @@ var LocalLibrary = class {
|
|
|
5611
5481
|
}
|
|
5612
5482
|
async _ready() {
|
|
5613
5483
|
if (typeof process === "undefined" || !process.versions?.node) {
|
|
5614
|
-
throw
|
|
5484
|
+
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.");
|
|
5615
5485
|
}
|
|
5616
5486
|
if (this.storage && this.storage.type !== "filesystem") {
|
|
5617
|
-
throw
|
|
5487
|
+
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.`);
|
|
5618
5488
|
}
|
|
5619
5489
|
if (this.storage?.machineId && this.storage.machineId !== await getMachineId()) {
|
|
5620
|
-
throw
|
|
5490
|
+
throw fail7(409, "storage_not_on_this_machine", `\xAB ${this.storage.label} \xBB belongs to another computer: its ${this.kind} stay there.`);
|
|
5621
5491
|
}
|
|
5622
5492
|
const { fs, path, os } = await node3();
|
|
5623
|
-
const
|
|
5624
|
-
const dir = path.join(
|
|
5493
|
+
const base = this.root || path.join(os.homedir(), ".iagenify");
|
|
5494
|
+
const dir = path.join(base, this.spec.folder);
|
|
5625
5495
|
await fs.mkdir(dir, { recursive: true, mode: 448 });
|
|
5626
|
-
return { fs, path, base
|
|
5496
|
+
return { fs, path, base, dir };
|
|
5627
5497
|
}
|
|
5628
5498
|
_file(path, dir, name) {
|
|
5629
5499
|
return this.kind === "skills" ? path.join(dir, name, "SKILL.md") : path.join(dir, `${name}.md`);
|
|
5630
5500
|
}
|
|
5631
5501
|
_checkName(name) {
|
|
5632
5502
|
if (typeof name !== "string" || !NAME.test(name)) {
|
|
5633
|
-
throw
|
|
5503
|
+
throw fail7(400, "invalid_name", `A ${this.spec.label} name uses lowercase letters, digits and dashes (e.g. "legal-review"), 64 characters at most.`);
|
|
5634
5504
|
}
|
|
5635
5505
|
}
|
|
5636
5506
|
/** Un élément lu sur disque : { name, description, …, content, builtIn: false }. */
|
|
5637
5507
|
_fromFile(name, text2, extra = {}) {
|
|
5638
5508
|
const { data, body } = parseFrontmatter(text2);
|
|
5639
|
-
const
|
|
5640
|
-
if (this.kind === "subagents") Object.assign(
|
|
5641
|
-
return { ...
|
|
5509
|
+
const base = { name, description: String(data.description || "").trim(), builtIn: false };
|
|
5510
|
+
if (this.kind === "subagents") Object.assign(base, { tools: normalizeTools(data.tools), model: normalizeModel(data.model) });
|
|
5511
|
+
return { ...base, ...extra, content: body };
|
|
5642
5512
|
}
|
|
5643
5513
|
_builtIn(name) {
|
|
5644
5514
|
const item = this.spec.builtIns[name];
|
|
@@ -5674,7 +5544,7 @@ var LocalLibrary = class {
|
|
|
5674
5544
|
try {
|
|
5675
5545
|
text2 = await fs.readFile(file, "utf8");
|
|
5676
5546
|
} catch (err) {
|
|
5677
|
-
if (err.code === "ENOENT") throw
|
|
5547
|
+
if (err.code === "ENOENT") throw fail7(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
|
|
5678
5548
|
throw err;
|
|
5679
5549
|
}
|
|
5680
5550
|
if (this.kind !== "skills") return this._fromFile(name, text2);
|
|
@@ -5698,10 +5568,10 @@ var LocalLibrary = class {
|
|
|
5698
5568
|
async save(item = {}) {
|
|
5699
5569
|
const { name, description, content } = item;
|
|
5700
5570
|
this._checkName(name);
|
|
5701
|
-
if (this.spec.builtIns[name]) throw
|
|
5702
|
-
if (typeof description !== "string" || !description.trim()) throw
|
|
5703
|
-
if (typeof content !== "string" || !content.trim()) throw
|
|
5704
|
-
if (content.length > MAX_CONTENT) throw
|
|
5571
|
+
if (this.spec.builtIns[name]) throw fail7(409, "name_reserved", `"${name}" is a built-in ${this.spec.label}; choose another name.`);
|
|
5572
|
+
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.`);
|
|
5573
|
+
if (typeof content !== "string" || !content.trim()) throw fail7(400, "content_required", `A ${this.spec.label} needs instructions (content).`);
|
|
5574
|
+
if (content.length > MAX_CONTENT) throw fail7(400, "content_too_long", `Instructions are limited to ${MAX_CONTENT.toLocaleString("en")} characters.`);
|
|
5705
5575
|
const data = { name, description: description.trim().replace(/\s+/g, " ") };
|
|
5706
5576
|
if (this.kind === "subagents") {
|
|
5707
5577
|
const tools = normalizeTools(item.tools);
|
|
@@ -5717,30 +5587,30 @@ var LocalLibrary = class {
|
|
|
5717
5587
|
/** Met l'élément à la corbeille (~/.iagenify/.trash/<horodatage>/…), d'où on peut le récupérer. */
|
|
5718
5588
|
async remove(name) {
|
|
5719
5589
|
this._checkName(name);
|
|
5720
|
-
if (this.spec.builtIns[name]) throw
|
|
5721
|
-
const { fs, path, base
|
|
5590
|
+
if (this.spec.builtIns[name]) throw fail7(400, "builtin_item", `"${name}" is built in and cannot be removed.`);
|
|
5591
|
+
const { fs, path, base, dir } = await this._ready();
|
|
5722
5592
|
const source = this.kind === "skills" ? path.join(dir, name) : this._file(path, dir, name);
|
|
5723
5593
|
try {
|
|
5724
5594
|
await fs.access(source);
|
|
5725
5595
|
} catch {
|
|
5726
|
-
throw
|
|
5596
|
+
throw fail7(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
|
|
5727
5597
|
}
|
|
5728
|
-
const target = path.join(
|
|
5598
|
+
const target = path.join(base, ".trash", (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-"), this.spec.folder, path.basename(source));
|
|
5729
5599
|
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
5730
5600
|
await fs.rename(source, target);
|
|
5731
5601
|
return { ok: true };
|
|
5732
5602
|
}
|
|
5733
5603
|
/** Skills seulement : un fichier du skill (modèle, référence…), en texte. */
|
|
5734
5604
|
async readFile(name, file) {
|
|
5735
|
-
if (this.kind !== "skills") throw
|
|
5605
|
+
if (this.kind !== "skills") throw fail7(400, "not_a_skill", "Only skills have files.");
|
|
5736
5606
|
const skill = await this.get(name);
|
|
5737
5607
|
const { fs, path } = await node3();
|
|
5738
5608
|
const full = path.resolve(skill.folder, String(file || "").replace(/\\/g, "/"));
|
|
5739
|
-
if (!full.startsWith(skill.folder + path.sep)) throw
|
|
5609
|
+
if (!full.startsWith(skill.folder + path.sep)) throw fail7(400, "invalid_path", `"${file}" is outside the skill folder.`);
|
|
5740
5610
|
try {
|
|
5741
5611
|
return { name: path.basename(full), path: path.relative(skill.folder, full).split(path.sep).join("/"), content: await fs.readFile(full, "utf8") };
|
|
5742
5612
|
} catch (err) {
|
|
5743
|
-
if (err.code === "ENOENT" || err.code === "EISDIR") throw
|
|
5613
|
+
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"}.`);
|
|
5744
5614
|
throw err;
|
|
5745
5615
|
}
|
|
5746
5616
|
}
|
|
@@ -5815,13 +5685,13 @@ var AgentLibrary = class {
|
|
|
5815
5685
|
if (err.status !== 404 || !this.computer) throw err;
|
|
5816
5686
|
const onDisk = await this.computer.get(name).catch(() => null);
|
|
5817
5687
|
if (!onDisk) throw err;
|
|
5818
|
-
throw
|
|
5688
|
+
throw fail7(409, "item_on_computer", `\xAB ${name} \xBB est un fichier de cet ordinateur (~/.iagenify/${this.spec.folder}) : supprimez-le sur le disque.`);
|
|
5819
5689
|
}
|
|
5820
5690
|
}
|
|
5821
5691
|
/** Skills seulement : un fichier annexe. Ceux du compte n'en ont pas — le contenu est le document. */
|
|
5822
5692
|
async readFile(name, file) {
|
|
5823
|
-
if (this.kind !== "skills") throw
|
|
5824
|
-
if (!this.computer) throw
|
|
5693
|
+
if (this.kind !== "skills") throw fail7(400, "not_a_skill", "Only skills have files.");
|
|
5694
|
+
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.`);
|
|
5825
5695
|
return this.computer.readFile(name, file);
|
|
5826
5696
|
}
|
|
5827
5697
|
};
|
|
@@ -5837,11 +5707,11 @@ var MAX_OUTPUT2 = 6e4;
|
|
|
5837
5707
|
var CALL_TIMEOUT_MS = 6e4;
|
|
5838
5708
|
var LIST_TIMEOUT_MS = 3e4;
|
|
5839
5709
|
var MAX_PAGES = 20;
|
|
5840
|
-
var
|
|
5710
|
+
var fail8 = (status, code, message) => new IaGenifyError(status, code, message);
|
|
5841
5711
|
var CODE_VERSION_NON_SUPPORTEE = -32022;
|
|
5842
5712
|
var estErreurModerne = (code) => typeof code === "number" && code <= -32020 && code >= -32099;
|
|
5843
5713
|
var REPLI_ANCIENNE_POIGNEE = /* @__PURE__ */ new Set(["mcp_error", "mcp_http_error", "mcp_bad_response"]);
|
|
5844
|
-
var
|
|
5714
|
+
var clip4 = (text2, max = MAX_OUTPUT2) => text2.length > max ? `${text2.slice(0, max)}
|
|
5845
5715
|
\u2026[truncated ${text2.length - max} characters]` : text2;
|
|
5846
5716
|
var SCHEMA_TYPES = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "array", "object"]);
|
|
5847
5717
|
var SCHEMA_KEYS = /* @__PURE__ */ new Set(["type", "description", "properties", "required", "items", "enum", "nullable"]);
|
|
@@ -5898,7 +5768,7 @@ function cleanToken(value) {
|
|
|
5898
5768
|
token = token.replace(/^authorization\s*:\s*/i, "").replace(/^bearer\b\s*/i, "").replace(/^token\s*=\s*/i, "").trim().replace(quotes, "").trim();
|
|
5899
5769
|
if (!token) return null;
|
|
5900
5770
|
if (/\s/.test(token)) {
|
|
5901
|
-
throw
|
|
5771
|
+
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.");
|
|
5902
5772
|
}
|
|
5903
5773
|
return token;
|
|
5904
5774
|
}
|
|
@@ -5974,7 +5844,7 @@ function mirroredParams(schema, args) {
|
|
|
5974
5844
|
}
|
|
5975
5845
|
var McpClient = class {
|
|
5976
5846
|
constructor({ url, token = null, name = "mcp", fetchImpl = null } = {}) {
|
|
5977
|
-
if (!url) throw
|
|
5847
|
+
if (!url) throw fail8(400, "url_required", "An MCP server needs its address.");
|
|
5978
5848
|
this.url = String(url);
|
|
5979
5849
|
this.token = cleanToken(token);
|
|
5980
5850
|
this.name = name;
|
|
@@ -6036,8 +5906,8 @@ var McpClient = class {
|
|
|
6036
5906
|
redirect: "manual"
|
|
6037
5907
|
});
|
|
6038
5908
|
} catch (err) {
|
|
6039
|
-
if (controller.signal.aborted) throw
|
|
6040
|
-
throw
|
|
5909
|
+
if (controller.signal.aborted) throw fail8(504, "mcp_timeout", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en ${Math.round(timeout / 1e3)} s.`);
|
|
5910
|
+
throw fail8(502, "mcp_unreachable", `\xAB ${this.name} \xBB est injoignable : ${err.message}`);
|
|
6041
5911
|
} finally {
|
|
6042
5912
|
clearTimeout(timer);
|
|
6043
5913
|
signal?.removeEventListener?.("abort", abort);
|
|
@@ -6046,17 +5916,17 @@ var McpClient = class {
|
|
|
6046
5916
|
const detail = this._detail(brut);
|
|
6047
5917
|
if (response.status === 401 || response.status === 403) {
|
|
6048
5918
|
if (!this.token) {
|
|
6049
|
-
throw
|
|
5919
|
+
throw fail8(401, "mcp_token_required", `\xAB ${this.name} \xBB demande un jeton : ce serveur ne r\xE9pond pas sans authentification.${detail}`);
|
|
6050
5920
|
}
|
|
6051
|
-
throw
|
|
5921
|
+
throw fail8(401, "mcp_unauthorized", `\xAB ${this.name} \xBB refuse le jeton (${response.status}). V\xE9rifiez-le, ou recr\xE9ez-en un.${detail}`);
|
|
6052
5922
|
}
|
|
6053
5923
|
if (response.status >= 300 && response.status < 400) {
|
|
6054
|
-
throw
|
|
5924
|
+
throw fail8(502, "mcp_redirect", `\xAB ${this.name} \xBB redirige vers une autre adresse : reconnectez-le avec l'adresse d\xE9finitive.`);
|
|
6055
5925
|
}
|
|
6056
|
-
if (!response.ok) throw this._rpcError(
|
|
5926
|
+
if (!response.ok) throw this._rpcError(fail8(502, "mcp_http_error", `\xAB ${this.name} \xBB a r\xE9pondu ${response.status}.${detail}`), brut);
|
|
6057
5927
|
const message = await this._readMessage(response, id);
|
|
6058
5928
|
if (message?.error) {
|
|
6059
|
-
const err =
|
|
5929
|
+
const err = fail8(502, "mcp_error", `\xAB ${this.name} \xBB refuse : ${String(message.error.message || message.error.code || "erreur").slice(0, 500)}`);
|
|
6060
5930
|
err.rpc = { code: message.error.code, data: message.error.data };
|
|
6061
5931
|
throw err;
|
|
6062
5932
|
}
|
|
@@ -6086,12 +5956,12 @@ var McpClient = class {
|
|
|
6086
5956
|
/** La réponse, qu'elle arrive en JSON ou en flux d'événements (`text/event-stream`). */
|
|
6087
5957
|
async _readMessage(response, id) {
|
|
6088
5958
|
const type = String(response.headers.get("content-type") || "");
|
|
6089
|
-
const body =
|
|
5959
|
+
const body = clip4(await response.text(), 2e6);
|
|
6090
5960
|
if (!type.includes("text/event-stream")) {
|
|
6091
5961
|
try {
|
|
6092
5962
|
return JSON.parse(body);
|
|
6093
5963
|
} catch {
|
|
6094
|
-
throw
|
|
5964
|
+
throw fail8(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en JSON.`);
|
|
6095
5965
|
}
|
|
6096
5966
|
}
|
|
6097
5967
|
let last = null;
|
|
@@ -6106,7 +5976,7 @@ var McpClient = class {
|
|
|
6106
5976
|
}
|
|
6107
5977
|
}
|
|
6108
5978
|
if (last) return last;
|
|
6109
|
-
throw
|
|
5979
|
+
throw fail8(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a renvoy\xE9 aucune r\xE9ponse exploitable.`);
|
|
6110
5980
|
}
|
|
6111
5981
|
/**
|
|
6112
5982
|
* La poignée de main, dans les deux révisions. Elle dit quelle version le serveur a acceptée.
|
|
@@ -6128,7 +5998,7 @@ var McpClient = class {
|
|
|
6128
5998
|
const propose = err.rpc?.data?.supportedVersions || err.rpc?.data?.supported;
|
|
6129
5999
|
const version = negotiateVersion(propose);
|
|
6130
6000
|
if (!version) {
|
|
6131
|
-
throw
|
|
6001
|
+
throw fail8(
|
|
6132
6002
|
502,
|
|
6133
6003
|
"mcp_protocol_unsupported",
|
|
6134
6004
|
`\xAB ${this.name} \xBB ne parle aucune r\xE9vision que ce client conna\xEEt (il propose ${[].concat(propose || []).join(", ") || "rien"}).`
|
|
@@ -6159,7 +6029,7 @@ var McpClient = class {
|
|
|
6159
6029
|
const found = await this._rpc("server/discover", {}, { signal });
|
|
6160
6030
|
const version = negotiateVersion(found.supportedVersions);
|
|
6161
6031
|
if (found.supportedVersions && !version) {
|
|
6162
|
-
throw
|
|
6032
|
+
throw fail8(
|
|
6163
6033
|
502,
|
|
6164
6034
|
"mcp_protocol_unsupported",
|
|
6165
6035
|
`\xAB ${this.name} \xBB ne parle aucune r\xE9vision que ce client conna\xEEt (il propose ${[].concat(found.supportedVersions).join(", ")}).`
|
|
@@ -6211,7 +6081,7 @@ var McpClient = class {
|
|
|
6211
6081
|
return part?.text ? String(part.text) : "";
|
|
6212
6082
|
}).filter(Boolean).join("\n");
|
|
6213
6083
|
const output = text2 || (result.structuredContent ? JSON.stringify(result.structuredContent) : "(aucun contenu)");
|
|
6214
|
-
return { output:
|
|
6084
|
+
return { output: clip4(output), isError: Boolean(result.isError) };
|
|
6215
6085
|
}
|
|
6216
6086
|
};
|
|
6217
6087
|
var McpResource = class {
|
|
@@ -6621,7 +6491,6 @@ var TOOL_FAMILIES = [
|
|
|
6621
6491
|
["Storages", ["query_storage", "write_storage"]],
|
|
6622
6492
|
["The account", ["account", "cloud"]],
|
|
6623
6493
|
["Put online and communicate", ["deploy", "domain", "mail", "send_mail"]],
|
|
6624
|
-
["Design", ["design_read", "design_apply", "design_render", "design_check", "design_template"]],
|
|
6625
6494
|
["The platform itself", ["iagenify_docs", "workflow", "mcp"]],
|
|
6626
6495
|
["Ask another model", ["generate"]],
|
|
6627
6496
|
["This conversation", ["todo_write", "ask_user", "memory", "recall", "skill", "task"]]
|
|
@@ -6801,9 +6670,9 @@ var SUBAGENT_MAX_STEPS = 40;
|
|
|
6801
6670
|
var MAX_SKILL_OUTPUT = 6e4;
|
|
6802
6671
|
var withoutAttachments = (messages) => messages.map(({ attachments, images, ...m }) => attachments?.length || images?.length ? { ...m, content: `${m.content || ""} [${(attachments || images).length} file(s) attached]` } : m);
|
|
6803
6672
|
var estimateTokens = (messages) => Math.ceil(JSON.stringify(withoutAttachments(messages)).length / 4);
|
|
6804
|
-
var
|
|
6673
|
+
var clip5 = (text2, max) => text2.length > max ? `${text2.slice(0, max)}
|
|
6805
6674
|
\u2026[truncated ${text2.length - max} characters]` : text2;
|
|
6806
|
-
var
|
|
6675
|
+
var fail9 = (message) => {
|
|
6807
6676
|
throw new IaGenifyError(400, "tool_error", message);
|
|
6808
6677
|
};
|
|
6809
6678
|
var KEEP_ATTACHMENTS_FOR = 6;
|
|
@@ -7154,11 +7023,11 @@ var LocalAgent = class _LocalAgent {
|
|
|
7154
7023
|
const notes = await this.api.memory.list();
|
|
7155
7024
|
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` };
|
|
7156
7025
|
}
|
|
7157
|
-
if (!name)
|
|
7026
|
+
if (!name) fail9("memory needs a name.");
|
|
7158
7027
|
if (action === "read") {
|
|
7159
7028
|
const notes = await this.api.memory.list();
|
|
7160
7029
|
const note = notes.find((n) => n.name === name);
|
|
7161
|
-
if (!note)
|
|
7030
|
+
if (!note) fail9(`No memory called "${name}". Listed names: ${notes.map((n) => n.name).join(", ") || "none"}.`);
|
|
7162
7031
|
return { output: `# ${note.name}
|
|
7163
7032
|
${note.description}
|
|
7164
7033
|
|
|
@@ -7169,7 +7038,7 @@ ${note.content}`, summary: note.name, meta: { memory: note.name } };
|
|
|
7169
7038
|
this.memories = this.memories.filter((n) => n.name !== name);
|
|
7170
7039
|
return { output: `Memory "${name}" deleted.`, summary: name, meta: { memory: name, deleted: true } };
|
|
7171
7040
|
}
|
|
7172
|
-
if (!content.trim())
|
|
7041
|
+
if (!content.trim()) fail9("memory save needs content.");
|
|
7173
7042
|
const saved = await this.api.memory.save({ name, description, content, type, source: "agent", ...this.memory ? { sessionId: this.id } : {} });
|
|
7174
7043
|
this.memories = [saved, ...this.memories.filter((n) => n.name !== saved.name)];
|
|
7175
7044
|
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 } };
|
|
@@ -7203,19 +7072,19 @@ ${note.content}`, summary: note.name, meta: { memory: note.name } };
|
|
|
7203
7072
|
file: { type: "string", description: "Optional: one of the skill's files, as listed when it is loaded" }
|
|
7204
7073
|
}),
|
|
7205
7074
|
run: async ({ name, file }) => {
|
|
7206
|
-
if (!this.library.skills.some((s) => s.name === name))
|
|
7075
|
+
if (!this.library.skills.some((s) => s.name === name)) fail9(`Unknown skill "${name}". Available: ${this.library.skills.map((s) => s.name).join(", ")}.`);
|
|
7207
7076
|
const library = this._library("skills");
|
|
7208
|
-
if (!library)
|
|
7077
|
+
if (!library) fail9("No skills are available here.");
|
|
7209
7078
|
if (file) {
|
|
7210
7079
|
const read = await library.readFile(name, file);
|
|
7211
|
-
return { output:
|
|
7080
|
+
return { output: clip5(read.content, MAX_SKILL_OUTPUT) || "(empty file)", summary: `${name} \xB7 ${read.path}`, meta: { skill: name, file: read.path } };
|
|
7212
7081
|
}
|
|
7213
7082
|
const skill = await library.get(name);
|
|
7214
7083
|
const files = skill.files?.length ? `
|
|
7215
7084
|
|
|
7216
7085
|
Files in this skill (read one with skill + file): ${skill.files.join(", ")}${skill.folder ? `
|
|
7217
7086
|
Folder on this computer, for commands: ${skill.folder}` : ""}` : "";
|
|
7218
|
-
return { output:
|
|
7087
|
+
return { output: clip5(`# Skill: ${name}
|
|
7219
7088
|
|
|
7220
7089
|
${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: { skill: name, files: skill.files?.length || 0 } };
|
|
7221
7090
|
}
|
|
@@ -7234,8 +7103,8 @@ ${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: {
|
|
|
7234
7103
|
}
|
|
7235
7104
|
/** Lance un sous-agent : même machine, même mode, mêmes permissions, budget et crédits partagés avec ce run. */
|
|
7236
7105
|
async _runSubagent({ agent: name, description = "", prompt }, call) {
|
|
7237
|
-
if (!this.library.subagents.some((a) => a.name === name))
|
|
7238
|
-
if (!String(prompt || "").trim())
|
|
7106
|
+
if (!this.library.subagents.some((a) => a.name === name)) fail9(`Unknown subagent "${name}". Available: ${this.library.subagents.map((a) => a.name).join(", ")}.`);
|
|
7107
|
+
if (!String(prompt || "").trim()) fail9("task needs a prompt: the subagent sees nothing of this conversation.");
|
|
7239
7108
|
const definition = await this._definition("subagents", name);
|
|
7240
7109
|
const wanted = !definition.tools || definition.tools === "all" ? WORKSPACE_TOOL_NAMES : definition.tools;
|
|
7241
7110
|
const tools = wanted.filter((t) => this.toolNames.includes(t) && !PARENT_ONLY_TOOLS.has(t));
|
|
@@ -7285,7 +7154,7 @@ ${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: {
|
|
|
7285
7154
|
|
|
7286
7155
|
[${name} subagent \xB7 ${turns} turns \xB7 ${toolCalls} tool calls \xB7 ${credits} credits${ended}]`,
|
|
7287
7156
|
summary: description || name,
|
|
7288
|
-
meta: { agent: name, description, model: child.model, turns, toolCalls, credits, stopReason: result.stopReason, report:
|
|
7157
|
+
meta: { agent: name, description, model: child.model, turns, toolCalls, credits, stopReason: result.stopReason, report: clip5(result.text || "", 4e3) }
|
|
7289
7158
|
};
|
|
7290
7159
|
} finally {
|
|
7291
7160
|
this.children.delete(child);
|
|
@@ -7316,7 +7185,7 @@ Files in this skill (read one with skill + file): ${skill.files.join(", ")}` : "
|
|
|
7316
7185
|
|
|
7317
7186
|
# Skill: ${name}
|
|
7318
7187
|
|
|
7319
|
-
${
|
|
7188
|
+
${clip5(skill.content, MAX_SKILL_OUTPUT)}${files}
|
|
7320
7189
|
|
|
7321
7190
|
# Request
|
|
7322
7191
|
${args || "Apply this skill."}`;
|
|
@@ -7379,13 +7248,13 @@ ${args || "Apply this skill."}`;
|
|
|
7379
7248
|
const read = await this.catalog.read.run({ path }, { files });
|
|
7380
7249
|
if (read.attachments?.length) images.push(...read.attachments.map((a) => ({ mime: a.mime, data: a.data })));
|
|
7381
7250
|
sections.push(`## @${read.meta?.path || path}
|
|
7382
|
-
${read.attachments?.length ? read.output :
|
|
7251
|
+
${read.attachments?.length ? read.output : clip5(read.output, 3e4)}`);
|
|
7383
7252
|
emit({ type: "mention", kind: "file", path: read.meta?.path || path });
|
|
7384
7253
|
} catch {
|
|
7385
7254
|
try {
|
|
7386
7255
|
const list = await this.catalog.list.run({ path }, { files });
|
|
7387
7256
|
sections.push(`## @${path} (folder)
|
|
7388
|
-
${
|
|
7257
|
+
${clip5(list.output, 8e3)}`);
|
|
7389
7258
|
emit({ type: "mention", kind: "folder", path });
|
|
7390
7259
|
} catch {
|
|
7391
7260
|
}
|
|
@@ -7396,7 +7265,7 @@ ${clip6(list.output, 8e3)}`);
|
|
|
7396
7265
|
try {
|
|
7397
7266
|
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 });
|
|
7398
7267
|
sections.push(`## #${s.name}${s.collection ? ` \xB7 ${s.collection}` : ""}
|
|
7399
|
-
${
|
|
7268
|
+
${clip5(read.output, 8e3)}`);
|
|
7400
7269
|
emit({ type: "mention", kind: "storage", storage: s.name, collection: s.collection });
|
|
7401
7270
|
} catch (err) {
|
|
7402
7271
|
sections.push(`## #${s.name}${s.collection ? ` \xB7 ${s.collection}` : ""}
|
|
@@ -9134,7 +9003,7 @@ function planPacks(hashes, sizeOf, { maxBytes, maxFiles }) {
|
|
|
9134
9003
|
return packs;
|
|
9135
9004
|
}
|
|
9136
9005
|
async function deployDirect(client, hostId, entries, server) {
|
|
9137
|
-
const
|
|
9006
|
+
const base = `/api/hosting/${hostId}/uploads`;
|
|
9138
9007
|
const byHash = /* @__PURE__ */ new Map();
|
|
9139
9008
|
const manifest = [];
|
|
9140
9009
|
for (const entry of entries) {
|
|
@@ -9142,7 +9011,7 @@ async function deployDirect(client, hostId, entries, server) {
|
|
|
9142
9011
|
manifest.push({ path: entry.path, size: entry.size, hash });
|
|
9143
9012
|
if (!byHash.has(hash)) byHash.set(hash, entry);
|
|
9144
9013
|
}
|
|
9145
|
-
const { upload } = await client.post(
|
|
9014
|
+
const { upload } = await client.post(base, { files: manifest, ...server !== void 0 ? { server } : {} });
|
|
9146
9015
|
const send = async (missing2) => {
|
|
9147
9016
|
const packs = planPacks(
|
|
9148
9017
|
missing2.filter((hash) => byHash.has(hash)),
|
|
@@ -9163,7 +9032,7 @@ async function deployDirect(client, hostId, entries, server) {
|
|
|
9163
9032
|
const header = pack.map((hash) => `${hash}:${byHash.get(hash).size}`).join(",");
|
|
9164
9033
|
for (let attempt = 1; ; attempt++) {
|
|
9165
9034
|
try {
|
|
9166
|
-
await client.put(`${
|
|
9035
|
+
await client.put(`${base}/${upload.id}/parts`, body, { headers: { "X-IaGenify-Parts": header }, timeout: PACK_TIMEOUT_MS });
|
|
9167
9036
|
break;
|
|
9168
9037
|
} catch (error) {
|
|
9169
9038
|
const transient = !error?.status || error.status >= 500 || error.status === 429;
|
|
@@ -9177,11 +9046,11 @@ async function deployDirect(client, hostId, entries, server) {
|
|
|
9177
9046
|
};
|
|
9178
9047
|
await send(upload.missing || []);
|
|
9179
9048
|
try {
|
|
9180
|
-
return (await client.post(`${
|
|
9049
|
+
return (await client.post(`${base}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
|
|
9181
9050
|
} catch (error) {
|
|
9182
9051
|
if (error?.code !== "upload_incomplete" || !Array.isArray(error.details?.missing)) throw error;
|
|
9183
9052
|
await send(error.details.missing);
|
|
9184
|
-
return (await client.post(`${
|
|
9053
|
+
return (await client.post(`${base}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
|
|
9185
9054
|
}
|
|
9186
9055
|
}
|
|
9187
9056
|
function toBase64(bytes) {
|
|
@@ -9195,10 +9064,10 @@ var HostsResource = class {
|
|
|
9195
9064
|
this.client = client;
|
|
9196
9065
|
}
|
|
9197
9066
|
/** `runtime` is the public contract. `kind` remains accepted for one upgrade cycle. */
|
|
9198
|
-
async create({ runtime, framework, label, slug
|
|
9067
|
+
async create({ runtime, framework, label, slug, kind } = {}) {
|
|
9199
9068
|
const rule = assertRuntime(runtime || LEGACY_RUNTIME[kind], framework);
|
|
9200
9069
|
const resolvedRuntime = runtime || LEGACY_RUNTIME[kind];
|
|
9201
|
-
const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug
|
|
9070
|
+
const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug });
|
|
9202
9071
|
return new Host(this.client, res.host, { framework });
|
|
9203
9072
|
}
|
|
9204
9073
|
async list() {
|
|
@@ -9592,8 +9461,8 @@ var Contacts = class {
|
|
|
9592
9461
|
/** `avatar` est rendu absolu ici : l'API rend un chemin, elle ignore sous quel nom on l'atteint. */
|
|
9593
9462
|
_absolu(contact) {
|
|
9594
9463
|
if (!contact) return contact;
|
|
9595
|
-
const
|
|
9596
|
-
return contact.avatar?.startsWith("/") &&
|
|
9464
|
+
const base = typeof this.client?.baseUrl === "string" ? this.client.baseUrl : "";
|
|
9465
|
+
return contact.avatar?.startsWith("/") && base ? { ...contact, avatar: `${base}${contact.avatar}` } : contact;
|
|
9597
9466
|
}
|
|
9598
9467
|
async list() {
|
|
9599
9468
|
const res = await this.client.get("/api/mail/contacts");
|
|
@@ -9684,955 +9553,6 @@ var MailResource = class {
|
|
|
9684
9553
|
}
|
|
9685
9554
|
};
|
|
9686
9555
|
|
|
9687
|
-
// src/studio/errors.js
|
|
9688
|
-
var StudioError = class extends Error {
|
|
9689
|
-
constructor(code, message, details = void 0, status = 400) {
|
|
9690
|
-
super(message);
|
|
9691
|
-
this.name = "StudioError";
|
|
9692
|
-
this.status = status;
|
|
9693
|
-
this.code = code;
|
|
9694
|
-
if (details !== void 0) this.details = details;
|
|
9695
|
-
}
|
|
9696
|
-
};
|
|
9697
|
-
|
|
9698
|
-
// src/studio/format.js
|
|
9699
|
-
var FORMAT = "iagenify.design";
|
|
9700
|
-
var FORMAT_VERSION = 1;
|
|
9701
|
-
var NODE_TYPES = ["frame", "text", "image", "shape"];
|
|
9702
|
-
var CONTENEURS = /* @__PURE__ */ new Set(["frame"]);
|
|
9703
|
-
var TAGS = {
|
|
9704
|
-
frame: ["div", "section", "header", "footer", "nav", "main", "article", "aside", "figure", "ul", "li", "a", "button"],
|
|
9705
|
-
text: ["p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "a", "button", "li", "small", "strong", "em", "label"],
|
|
9706
|
-
image: ["img"],
|
|
9707
|
-
shape: ["div"]
|
|
9708
|
-
};
|
|
9709
|
-
var DEFAULT_TAG = { frame: "div", text: "p", image: "img", shape: "div" };
|
|
9710
|
-
var CHAMPS_NOEUD = /* @__PURE__ */ new Set(["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"]);
|
|
9711
|
-
var CHAMPS = {
|
|
9712
|
-
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" },
|
|
9713
|
-
size: { w: "dimension", h: "dimension", minW: "longueur", minH: "longueur", maxW: "longueur", maxH: "longueur" },
|
|
9714
|
-
position: { x: "nombre", y: "nombre", absolute: "booleen" },
|
|
9715
|
-
style: { fill: "remplissage", stroke: "trait", radius: "rayon", shadow: "ombres", opacity: "opacite", clip: "booleen" },
|
|
9716
|
-
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"] },
|
|
9717
|
-
image: { src: "source", fit: ["cover", "contain", "fill"] },
|
|
9718
|
-
shape: { kind: ["rect", "ellipse", "line"] }
|
|
9719
|
-
};
|
|
9720
|
-
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;
|
|
9721
|
-
var POLICE = /^[A-Za-z0-9 \-]{1,64}$/;
|
|
9722
|
-
var SOURCE = /^asset:[A-Za-z0-9_\-]{1,64}$/;
|
|
9723
|
-
var fini = (v) => typeof v === "number" && Number.isFinite(v);
|
|
9724
|
-
function isColor(v) {
|
|
9725
|
-
return typeof v === "string" && COULEUR.test(v.trim());
|
|
9726
|
-
}
|
|
9727
|
-
function verifierValeur(regle, v) {
|
|
9728
|
-
if (Array.isArray(regle)) return regle.includes(v) ? null : `valeur_non_permise (${regle.join(", ")})`;
|
|
9729
|
-
switch (regle) {
|
|
9730
|
-
case "booleen":
|
|
9731
|
-
return typeof v === "boolean" ? null : "booleen_attendu";
|
|
9732
|
-
case "nombre":
|
|
9733
|
-
return fini(v) ? null : "nombre_attendu";
|
|
9734
|
-
case "entier":
|
|
9735
|
-
return Number.isInteger(v) && v >= 1 && v <= 24 ? null : "entier_1_24_attendu";
|
|
9736
|
-
case "longueur":
|
|
9737
|
-
return fini(v) && v >= 0 && v <= 1e5 ? null : "longueur_positive_attendue";
|
|
9738
|
-
case "dimension":
|
|
9739
|
-
return v === "hug" || v === "fill" || fini(v) && v >= 0 && v <= 1e5 ? null : "hug_fill_ou_longueur_attendu";
|
|
9740
|
-
case "padding":
|
|
9741
|
-
if (fini(v) && v >= 0) return null;
|
|
9742
|
-
if (Array.isArray(v) && (v.length === 2 || v.length === 4) && v.every((x) => fini(x) && x >= 0)) return null;
|
|
9743
|
-
return "padding_nombre_ou_liste_2_4";
|
|
9744
|
-
case "rayon":
|
|
9745
|
-
if (fini(v) && v >= 0) return null;
|
|
9746
|
-
if (Array.isArray(v) && v.length === 4 && v.every((x) => fini(x) && x >= 0)) return null;
|
|
9747
|
-
return "rayon_nombre_ou_liste_4";
|
|
9748
|
-
case "opacite":
|
|
9749
|
-
return fini(v) && v >= 0 && v <= 1 ? null : "opacite_0_1";
|
|
9750
|
-
case "couleur":
|
|
9751
|
-
return isColor(v) ? null : "couleur_invalide";
|
|
9752
|
-
case "remplissage":
|
|
9753
|
-
if (isColor(v)) return null;
|
|
9754
|
-
if (v && typeof v === "object" && v.type === "linear") {
|
|
9755
|
-
const cles = Object.keys(v).filter((k) => !["type", "angle", "stops"].includes(k));
|
|
9756
|
-
if (cles.length) return `champ_inconnu (${cles[0]})`;
|
|
9757
|
-
if (!fini(v.angle)) return "angle_attendu";
|
|
9758
|
-
if (!Array.isArray(v.stops) || v.stops.length < 2 || v.stops.length > 8) return "2_a_8_arrets";
|
|
9759
|
-
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";
|
|
9760
|
-
return null;
|
|
9761
|
-
}
|
|
9762
|
-
return "couleur_ou_degrade_attendu";
|
|
9763
|
-
case "trait":
|
|
9764
|
-
if (v && typeof v === "object" && isColor(v.color) && fini(v.width) && v.width >= 0 && v.width <= 100 && Object.keys(v).length === 2) return null;
|
|
9765
|
-
return "trait_{color,width}_attendu";
|
|
9766
|
-
case "ombres":
|
|
9767
|
-
if (!Array.isArray(v) || v.length > 4) return "liste_de_4_ombres_max";
|
|
9768
|
-
for (const o of v) {
|
|
9769
|
-
if (!o || typeof o !== "object") return "ombre_invalide";
|
|
9770
|
-
const cles = Object.keys(o).filter((k) => !["x", "y", "blur", "spread", "color", "inset"].includes(k));
|
|
9771
|
-
if (cles.length) return `champ_inconnu (${cles[0]})`;
|
|
9772
|
-
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";
|
|
9773
|
-
}
|
|
9774
|
-
return null;
|
|
9775
|
-
case "texte":
|
|
9776
|
-
return typeof v === "string" && v.length <= 2e4 ? null : "texte_attendu";
|
|
9777
|
-
case "police":
|
|
9778
|
-
return typeof v === "string" && POLICE.test(v) ? null : "nom_de_police_invalide";
|
|
9779
|
-
case "graisse":
|
|
9780
|
-
return Number.isInteger(v) && v >= 100 && v <= 900 && v % 100 === 0 ? null : "graisse_100_a_900";
|
|
9781
|
-
case "interligne":
|
|
9782
|
-
return fini(v) && v > 0 && v <= 10 ? null : "interligne_0_10";
|
|
9783
|
-
case "source":
|
|
9784
|
-
return typeof v === "string" && SOURCE.test(v) ? null : "source_asset:<id>_attendue";
|
|
9785
|
-
default:
|
|
9786
|
-
return "regle_inconnue";
|
|
9787
|
-
}
|
|
9788
|
-
}
|
|
9789
|
-
function verifierGroupe(groupe, objet, chemin, erreurs) {
|
|
9790
|
-
if (objet === void 0) return;
|
|
9791
|
-
if (!objet || typeof objet !== "object" || Array.isArray(objet)) {
|
|
9792
|
-
erreurs.push({ path: chemin, reason: "objet_attendu" });
|
|
9793
|
-
return;
|
|
9794
|
-
}
|
|
9795
|
-
const regles = CHAMPS[groupe];
|
|
9796
|
-
for (const [cle, valeur] of Object.entries(objet)) {
|
|
9797
|
-
if (!(cle in regles)) {
|
|
9798
|
-
erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
|
|
9799
|
-
continue;
|
|
9800
|
-
}
|
|
9801
|
-
if (valeur === null && ["stroke", "shadow"].includes(cle)) continue;
|
|
9802
|
-
const motif = verifierValeur(regles[cle], valeur);
|
|
9803
|
-
if (motif) erreurs.push({ path: `${chemin}.${cle}`, reason: motif });
|
|
9804
|
-
}
|
|
9805
|
-
}
|
|
9806
|
-
function validateNode(node4, chemin = "node") {
|
|
9807
|
-
const erreurs = [];
|
|
9808
|
-
if (!node4 || typeof node4 !== "object" || Array.isArray(node4)) return [{ path: chemin, reason: "objet_attendu" }];
|
|
9809
|
-
for (const cle of Object.keys(node4)) if (!CHAMPS_NOEUD.has(cle)) erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
|
|
9810
|
-
if (!NODE_TYPES.includes(node4.type)) erreurs.push({ path: `${chemin}.type`, reason: `type_inconnu (${NODE_TYPES.join(", ")})` });
|
|
9811
|
-
if (typeof node4.name !== "string" || !node4.name.trim() || node4.name.length > 120) erreurs.push({ path: `${chemin}.name`, reason: "nom_1_a_120_caracteres" });
|
|
9812
|
-
if (node4.as !== void 0 && !(TAGS[node4.type] || []).includes(node4.as)) erreurs.push({ path: `${chemin}.as`, reason: "balise_non_permise" });
|
|
9813
|
-
if (node4.alt !== void 0 && (typeof node4.alt !== "string" || node4.alt.length > 500)) erreurs.push({ path: `${chemin}.alt`, reason: "texte_500_max" });
|
|
9814
|
-
for (const groupe of ["layout", "size", "position", "style", "text", "image", "shape"]) verifierGroupe(groupe, node4[groupe], `${chemin}.${groupe}`, erreurs);
|
|
9815
|
-
if (node4.type !== "frame" && node4.layout !== void 0) erreurs.push({ path: `${chemin}.layout`, reason: "seul_un_cadre_a_une_mise_en_page" });
|
|
9816
|
-
if (node4.type !== "text" && node4.text !== void 0) erreurs.push({ path: `${chemin}.text`, reason: "seul_un_texte_a_du_texte" });
|
|
9817
|
-
if (node4.type === "text" && typeof node4.text?.content !== "string") erreurs.push({ path: `${chemin}.text.content`, reason: "texte_attendu" });
|
|
9818
|
-
if (node4.type !== "image" && node4.image !== void 0) erreurs.push({ path: `${chemin}.image`, reason: "seule_une_image_a_une_source" });
|
|
9819
|
-
if (node4.type === "image" && typeof node4.image?.src !== "string") erreurs.push({ path: `${chemin}.image.src`, reason: "source_asset:<id>_attendue" });
|
|
9820
|
-
if (node4.type !== "shape" && node4.shape !== void 0) erreurs.push({ path: `${chemin}.shape`, reason: "seule_une_forme_a_un_genre" });
|
|
9821
|
-
if (CONTENEURS.has(node4.type)) {
|
|
9822
|
-
if (!Array.isArray(node4.children)) erreurs.push({ path: `${chemin}.children`, reason: "liste_attendue" });
|
|
9823
|
-
} else if (node4.children !== void 0) erreurs.push({ path: `${chemin}.children`, reason: "ce_type_n_a_pas_d_enfants" });
|
|
9824
|
-
return erreurs;
|
|
9825
|
-
}
|
|
9826
|
-
function isContainer(node4) {
|
|
9827
|
-
return CONTENEURS.has(node4?.type);
|
|
9828
|
-
}
|
|
9829
|
-
function createDocument() {
|
|
9830
|
-
return { format: FORMAT, version: FORMAT_VERSION, meta: { nextId: 1 }, pages: [{ id: "p_1", name: "Page 1", frames: [] }], nodes: {} };
|
|
9831
|
-
}
|
|
9832
|
-
function validate(doc) {
|
|
9833
|
-
const erreurs = [];
|
|
9834
|
-
const err = (path, reason) => erreurs.push({ path, reason });
|
|
9835
|
-
if (!doc || typeof doc !== "object" || Array.isArray(doc)) return { ok: false, errors: [{ path: "", reason: "objet_attendu" }] };
|
|
9836
|
-
for (const cle of Object.keys(doc)) if (!["format", "version", "meta", "pages", "nodes"].includes(cle)) err(cle, "champ_inconnu");
|
|
9837
|
-
if (doc.format !== FORMAT) err("format", `attendu_${FORMAT}`);
|
|
9838
|
-
if (doc.version !== FORMAT_VERSION) err("version", `version_${FORMAT_VERSION}_attendue`);
|
|
9839
|
-
if (!doc.meta || !Number.isInteger(doc.meta.nextId) || doc.meta.nextId < 1 || Object.keys(doc.meta).length !== 1) err("meta", "meta_{nextId}_attendu");
|
|
9840
|
-
if (!doc.nodes || typeof doc.nodes !== "object" || Array.isArray(doc.nodes)) {
|
|
9841
|
-
err("nodes", "objet_attendu");
|
|
9842
|
-
return { ok: false, errors: erreurs };
|
|
9843
|
-
}
|
|
9844
|
-
if (!Array.isArray(doc.pages) || doc.pages.length === 0) {
|
|
9845
|
-
err("pages", "au_moins_une_page");
|
|
9846
|
-
return { ok: false, errors: erreurs };
|
|
9847
|
-
}
|
|
9848
|
-
const parents = /* @__PURE__ */ new Map();
|
|
9849
|
-
const cite = (id, path) => {
|
|
9850
|
-
if (typeof id !== "string" || !Object.hasOwn(doc.nodes, id)) {
|
|
9851
|
-
err(path, "enfant_inexistant");
|
|
9852
|
-
return;
|
|
9853
|
-
}
|
|
9854
|
-
parents.set(id, (parents.get(id) || 0) + 1);
|
|
9855
|
-
};
|
|
9856
|
-
const idsPages = /* @__PURE__ */ new Set();
|
|
9857
|
-
doc.pages.forEach((p, i) => {
|
|
9858
|
-
const c = `pages[${i}]`;
|
|
9859
|
-
if (!p || typeof p !== "object") return err(c, "objet_attendu");
|
|
9860
|
-
for (const cle of Object.keys(p)) if (!["id", "name", "route", "frames"].includes(cle)) err(`${c}.${cle}`, "champ_inconnu");
|
|
9861
|
-
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");
|
|
9862
|
-
idsPages.add(p.id);
|
|
9863
|
-
if (typeof p.name !== "string" || !p.name.trim() || p.name.length > 120) err(`${c}.name`, "nom_1_a_120_caracteres");
|
|
9864
|
-
if (p.route !== void 0 && (typeof p.route !== "string" || !/^\/[a-z0-9\-/[\]]*$/.test(p.route))) err(`${c}.route`, "route_invalide");
|
|
9865
|
-
if (!Array.isArray(p.frames)) return err(`${c}.frames`, "liste_attendue");
|
|
9866
|
-
p.frames.forEach((id, k) => {
|
|
9867
|
-
cite(id, `${c}.frames[${k}]`);
|
|
9868
|
-
if (typeof id === "string" && Object.hasOwn(doc.nodes, id) && doc.nodes[id]?.type !== "frame") {
|
|
9869
|
-
err(`${c}.frames[${k}]`, "une_page_ne_contient_que_des_cadres");
|
|
9870
|
-
}
|
|
9871
|
-
});
|
|
9872
|
-
});
|
|
9873
|
-
const limite = doc.meta?.nextId ?? 1;
|
|
9874
|
-
for (const [id, node4] of Object.entries(doc.nodes)) {
|
|
9875
|
-
const c = `nodes.${id}`;
|
|
9876
|
-
if (!/^n_[0-9a-z]+$/.test(id)) err(c, "id_invalide");
|
|
9877
|
-
else if (parseInt(id.slice(2), 36) >= limite) err(c, "id_au_dela_du_compteur");
|
|
9878
|
-
if (node4?.id !== id) err(`${c}.id`, "id_different_de_la_cle");
|
|
9879
|
-
erreurs.push(...validateNode(node4, c));
|
|
9880
|
-
if (Array.isArray(node4?.children)) node4.children.forEach((enfant, k) => cite(enfant, `${c}.children[${k}]`));
|
|
9881
|
-
}
|
|
9882
|
-
for (const id of Object.keys(doc.nodes)) {
|
|
9883
|
-
const n = parents.get(id) || 0;
|
|
9884
|
-
if (n === 0) err(`nodes.${id}`, "noeud_orphelin");
|
|
9885
|
-
if (n > 1) err(`nodes.${id}`, "noeud_a_plusieurs_parents");
|
|
9886
|
-
}
|
|
9887
|
-
if (erreurs.length) return { ok: false, errors: erreurs };
|
|
9888
|
-
const vus = /* @__PURE__ */ new Set();
|
|
9889
|
-
const pile = doc.pages.flatMap((p) => p.frames);
|
|
9890
|
-
while (pile.length) {
|
|
9891
|
-
const id = pile.pop();
|
|
9892
|
-
vus.add(id);
|
|
9893
|
-
for (const enfant of doc.nodes[id].children || []) pile.push(enfant);
|
|
9894
|
-
}
|
|
9895
|
-
for (const id of Object.keys(doc.nodes)) if (!vus.has(id)) err(`nodes.${id}`, "cycle");
|
|
9896
|
-
return { ok: erreurs.length === 0, errors: erreurs };
|
|
9897
|
-
}
|
|
9898
|
-
function assertValid(doc) {
|
|
9899
|
-
const r = validate(doc);
|
|
9900
|
-
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) });
|
|
9901
|
-
return doc;
|
|
9902
|
-
}
|
|
9903
|
-
var ORDRE_NOEUD = ["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"];
|
|
9904
|
-
var ordonner = (objet, ordre) => {
|
|
9905
|
-
const out = {};
|
|
9906
|
-
for (const k of ordre) if (objet[k] !== void 0) out[k] = objet[k];
|
|
9907
|
-
return out;
|
|
9908
|
-
};
|
|
9909
|
-
function canonical(doc) {
|
|
9910
|
-
const nodes = {};
|
|
9911
|
-
const ids = Object.keys(doc.nodes).sort((a, b) => parseInt(a.slice(2), 36) - parseInt(b.slice(2), 36));
|
|
9912
|
-
for (const id of ids) {
|
|
9913
|
-
const n = ordonner(doc.nodes[id], ORDRE_NOEUD);
|
|
9914
|
-
for (const g of Object.keys(CHAMPS)) if (n[g] && typeof n[g] === "object") n[g] = ordonner(n[g], Object.keys(CHAMPS[g]));
|
|
9915
|
-
nodes[id] = n;
|
|
9916
|
-
}
|
|
9917
|
-
return {
|
|
9918
|
-
format: doc.format,
|
|
9919
|
-
version: doc.version,
|
|
9920
|
-
meta: { nextId: doc.meta.nextId },
|
|
9921
|
-
pages: doc.pages.map((p) => ordonner({ ...p, frames: [...p.frames] }, ["id", "name", "route", "frames"])),
|
|
9922
|
-
nodes
|
|
9923
|
-
};
|
|
9924
|
-
}
|
|
9925
|
-
function migrate(doc) {
|
|
9926
|
-
if (doc && doc.version === FORMAT_VERSION) return doc;
|
|
9927
|
-
throw new StudioError("studio_document_invalid", `Version de document non prise en charge : ${doc?.version}`, { errors: [{ path: "version", reason: `version_${FORMAT_VERSION}_attendue` }] });
|
|
9928
|
-
}
|
|
9929
|
-
|
|
9930
|
-
// src/studio/ops.js
|
|
9931
|
-
var GROUPES = /* @__PURE__ */ new Set(["layout", "size", "position", "style", "text", "image", "shape"]);
|
|
9932
|
-
var SIMPLES = /* @__PURE__ */ new Set(["name", "as", "alt"]);
|
|
9933
|
-
var refus = (index, reason, message) => {
|
|
9934
|
-
throw new StudioError("studio_op_invalid", message || `Op\xE9ration ${index} refus\xE9e : ${reason}`, { index, reason });
|
|
9935
|
-
};
|
|
9936
|
-
function nouvelId(doc) {
|
|
9937
|
-
const id = `n_${doc.meta.nextId.toString(36)}`;
|
|
9938
|
-
doc.meta.nextId += 1;
|
|
9939
|
-
return id;
|
|
9940
|
-
}
|
|
9941
|
-
function emplacement(doc, id) {
|
|
9942
|
-
for (const p of doc.pages) {
|
|
9943
|
-
const i = p.frames.indexOf(id);
|
|
9944
|
-
if (i >= 0) return { parent: p.id, liste: p.frames, index: i };
|
|
9945
|
-
}
|
|
9946
|
-
for (const n of Object.values(doc.nodes)) if (n.children) {
|
|
9947
|
-
const i = n.children.indexOf(id);
|
|
9948
|
-
if (i >= 0) return { parent: n.id, liste: n.children, index: i };
|
|
9949
|
-
}
|
|
9950
|
-
return null;
|
|
9951
|
-
}
|
|
9952
|
-
function listeDuParent(doc, parent, type, index) {
|
|
9953
|
-
const page = doc.pages.find((p) => p.id === parent);
|
|
9954
|
-
if (page) {
|
|
9955
|
-
if (type !== "frame") refus(index, "une_page_ne_contient_que_des_cadres");
|
|
9956
|
-
return page.frames;
|
|
9957
|
-
}
|
|
9958
|
-
const n = doc.nodes[parent];
|
|
9959
|
-
if (!n) refus(index, "parent_introuvable");
|
|
9960
|
-
if (!isContainer(n)) refus(index, "le_parent_n_est_pas_un_cadre");
|
|
9961
|
-
return n.children;
|
|
9962
|
-
}
|
|
9963
|
-
function sousArbre(doc, id, acc = {}) {
|
|
9964
|
-
const n = doc.nodes[id];
|
|
9965
|
-
acc[id] = n;
|
|
9966
|
-
for (const e of n.children || []) sousArbre(doc, e, acc);
|
|
9967
|
-
return acc;
|
|
9968
|
-
}
|
|
9969
|
-
function placer(liste, id, index, iop) {
|
|
9970
|
-
const i = index === void 0 ? liste.length : index;
|
|
9971
|
-
if (!Number.isInteger(i) || i < 0 || i > liste.length) refus(iop, "index_hors_limites");
|
|
9972
|
-
liste.splice(i, 0, id);
|
|
9973
|
-
return i;
|
|
9974
|
-
}
|
|
9975
|
-
function aplatir(doc, brut, iop, acc) {
|
|
9976
|
-
if (!brut || typeof brut !== "object" || Array.isArray(brut)) refus(iop, "noeud_objet_attendu");
|
|
9977
|
-
if ("id" in brut) refus(iop, "un_id_ne_se_choisit_pas");
|
|
9978
|
-
const { children, ...reste } = brut;
|
|
9979
|
-
const id = nouvelId(doc);
|
|
9980
|
-
const node4 = { id, ...reste };
|
|
9981
|
-
if (isContainer(node4)) {
|
|
9982
|
-
if (children !== void 0 && !Array.isArray(children)) refus(iop, "children_liste_attendue");
|
|
9983
|
-
node4.children = (children || []).map((c) => aplatir(doc, c, iop, acc));
|
|
9984
|
-
} else if (children !== void 0) refus(iop, "ce_type_n_a_pas_d_enfants");
|
|
9985
|
-
const erreurs = validateNode(node4, "node");
|
|
9986
|
-
if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
|
|
9987
|
-
acc[id] = node4;
|
|
9988
|
-
return id;
|
|
9989
|
-
}
|
|
9990
|
-
function estDescendant(doc, ancetre, id) {
|
|
9991
|
-
const n = doc.nodes[ancetre];
|
|
9992
|
-
return (n?.children || []).some((e) => e === id || estDescendant(doc, e, id));
|
|
9993
|
-
}
|
|
9994
|
-
function lire(node4, path) {
|
|
9995
|
-
const [a, b] = path.split(".");
|
|
9996
|
-
if (b === void 0) return node4[a];
|
|
9997
|
-
return node4[a]?.[b];
|
|
9998
|
-
}
|
|
9999
|
-
function appliquerUne(doc, op, iop, inverses, created, removed) {
|
|
10000
|
-
if (!op || typeof op !== "object") refus(iop, "operation_objet_attendue");
|
|
10001
|
-
switch (op.op) {
|
|
10002
|
-
case "set": {
|
|
10003
|
-
const node4 = doc.nodes[op.id];
|
|
10004
|
-
if (!node4) refus(iop, "noeud_introuvable");
|
|
10005
|
-
if (typeof op.path !== "string") refus(iop, "chemin_attendu");
|
|
10006
|
-
const [a, b, ...trop] = op.path.split(".");
|
|
10007
|
-
if (trop.length || !(SIMPLES.has(a) && b === void 0) && !GROUPES.has(a)) refus(iop, "chemin_non_modifiable");
|
|
10008
|
-
const avant = lire(node4, op.path);
|
|
10009
|
-
const copie2 = structuredClone(node4);
|
|
10010
|
-
if (b === void 0) {
|
|
10011
|
-
if (op.value === void 0) delete copie2[a];
|
|
10012
|
-
else copie2[a] = structuredClone(op.value);
|
|
10013
|
-
} else {
|
|
10014
|
-
const groupe = { ...copie2[a] || {} };
|
|
10015
|
-
if (op.value === void 0) delete groupe[b];
|
|
10016
|
-
else groupe[b] = structuredClone(op.value);
|
|
10017
|
-
if (Object.keys(groupe).length) copie2[a] = groupe;
|
|
10018
|
-
else delete copie2[a];
|
|
10019
|
-
}
|
|
10020
|
-
const erreurs = validateNode(copie2, op.id);
|
|
10021
|
-
if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
|
|
10022
|
-
doc.nodes[op.id] = copie2;
|
|
10023
|
-
inverses.push({ op: "set", id: op.id, path: op.path, value: avant === void 0 ? void 0 : structuredClone(avant) });
|
|
10024
|
-
return;
|
|
10025
|
-
}
|
|
10026
|
-
case "insert": {
|
|
10027
|
-
const acc = {};
|
|
10028
|
-
const racine = aplatir(doc, op.node, iop, acc);
|
|
10029
|
-
const liste = listeDuParent(doc, op.parent, acc[racine].type, iop);
|
|
10030
|
-
Object.assign(doc.nodes, acc);
|
|
10031
|
-
placer(liste, racine, op.index, iop);
|
|
10032
|
-
created.push(...Object.keys(acc));
|
|
10033
|
-
inverses.push({ op: "remove", id: racine });
|
|
10034
|
-
return;
|
|
10035
|
-
}
|
|
10036
|
-
case "move": {
|
|
10037
|
-
const node4 = doc.nodes[op.id];
|
|
10038
|
-
if (!node4) refus(iop, "noeud_introuvable");
|
|
10039
|
-
if (op.parent === op.id || estDescendant(doc, op.id, op.parent)) refus(iop, "deplacement_dans_son_propre_descendant");
|
|
10040
|
-
const ici = emplacement(doc, op.id);
|
|
10041
|
-
const liste = listeDuParent(doc, op.parent, node4.type, iop);
|
|
10042
|
-
ici.liste.splice(ici.index, 1);
|
|
10043
|
-
placer(liste, op.id, op.index, iop);
|
|
10044
|
-
inverses.push({ op: "move", id: op.id, parent: ici.parent, index: ici.index });
|
|
10045
|
-
return;
|
|
10046
|
-
}
|
|
10047
|
-
case "remove": {
|
|
10048
|
-
if (!doc.nodes[op.id]) refus(iop, "noeud_introuvable");
|
|
10049
|
-
const ici = emplacement(doc, op.id);
|
|
10050
|
-
const arbre = sousArbre(doc, op.id);
|
|
10051
|
-
ici.liste.splice(ici.index, 1);
|
|
10052
|
-
for (const id of Object.keys(arbre)) delete doc.nodes[id];
|
|
10053
|
-
removed.push(...Object.keys(arbre));
|
|
10054
|
-
inverses.push({ op: "restore", parent: ici.parent, index: ici.index, root: op.id, nodes: arbre });
|
|
10055
|
-
return;
|
|
10056
|
-
}
|
|
10057
|
-
case "restore": {
|
|
10058
|
-
if (!op.__interne) refus(iop, "operation_inconnue");
|
|
10059
|
-
const liste = listeDuParent(doc, op.parent, op.nodes[op.root].type, iop);
|
|
10060
|
-
Object.assign(doc.nodes, structuredClone(op.nodes));
|
|
10061
|
-
placer(liste, op.root, op.index, iop);
|
|
10062
|
-
inverses.push({ op: "remove", id: op.root });
|
|
10063
|
-
return;
|
|
10064
|
-
}
|
|
10065
|
-
default:
|
|
10066
|
-
refus(iop, "operation_inconnue");
|
|
10067
|
-
}
|
|
10068
|
-
}
|
|
10069
|
-
function applyOps(doc, ops, { internal = false } = {}) {
|
|
10070
|
-
if (!Array.isArray(ops)) throw new StudioError("studio_op_invalid", "Un lot d'op\xE9rations est une liste.", { index: -1, reason: "liste_attendue" });
|
|
10071
|
-
const copie2 = structuredClone(doc);
|
|
10072
|
-
const inverses = [];
|
|
10073
|
-
const created = [];
|
|
10074
|
-
const removed = [];
|
|
10075
|
-
ops.forEach((op, i) => appliquerUne(copie2, internal && op?.op === "restore" ? { ...op, __interne: true } : op, i, inverses, created, removed));
|
|
10076
|
-
return { doc: copie2, inverse: inverses.reverse(), created, removed };
|
|
10077
|
-
}
|
|
10078
|
-
|
|
10079
|
-
// src/studio/style.js
|
|
10080
|
-
var px = (v) => `${+v.toFixed(3)}px`;
|
|
10081
|
-
var ALIGN = { start: "flex-start", center: "center", end: "flex-end", stretch: "stretch" };
|
|
10082
|
-
var JUSTIFY = { start: "flex-start", center: "center", end: "flex-end", between: "space-between" };
|
|
10083
|
-
function remplissage(f) {
|
|
10084
|
-
if (typeof f === "string") return f;
|
|
10085
|
-
return `linear-gradient(${+f.angle.toFixed(3)}deg, ${f.stops.map((s) => `${s.color} ${+(s.at * 100).toFixed(3)}%`).join(", ")})`;
|
|
10086
|
-
}
|
|
10087
|
-
function padding(p) {
|
|
10088
|
-
if (typeof p === "number") return px(p);
|
|
10089
|
-
return p.map(px).join(" ");
|
|
10090
|
-
}
|
|
10091
|
-
function taille(decl, axe, v, parent) {
|
|
10092
|
-
if (v === void 0) return;
|
|
10093
|
-
const prop = axe === "w" ? "width" : "height";
|
|
10094
|
-
const mode = parent?.layout?.mode;
|
|
10095
|
-
const dir = parent?.layout?.direction || "row";
|
|
10096
|
-
const principal = mode === "flex" && (axe === "w" && dir === "row" || axe === "h" && dir === "column");
|
|
10097
|
-
if (typeof v === "number") {
|
|
10098
|
-
decl.push([prop, px(v)]);
|
|
10099
|
-
if (principal) decl.push(["flex-shrink", "0"]);
|
|
10100
|
-
} else if (v === "fill") {
|
|
10101
|
-
if (principal) decl.push(["flex", "1 1 0"], [axe === "w" ? "min-width" : "min-height", "0"]);
|
|
10102
|
-
else if (mode === "flex") decl.push(["align-self", "stretch"]);
|
|
10103
|
-
else decl.push([prop, "100%"]);
|
|
10104
|
-
} else if (v === "hug") {
|
|
10105
|
-
decl.push([prop, "fit-content"]);
|
|
10106
|
-
}
|
|
10107
|
-
}
|
|
10108
|
-
function nodeCss(node4, parent = null) {
|
|
10109
|
-
const d = [];
|
|
10110
|
-
const pos = node4.position;
|
|
10111
|
-
if (parent?.layout?.mode === "free" || pos?.absolute) {
|
|
10112
|
-
d.push(["position", "absolute"], ["left", px(pos?.x ?? 0)], ["top", px(pos?.y ?? 0)]);
|
|
10113
|
-
}
|
|
10114
|
-
const l = node4.layout;
|
|
10115
|
-
if (node4.type === "frame") {
|
|
10116
|
-
if (l?.mode === "grid") {
|
|
10117
|
-
d.push(["display", "grid"], ["grid-template-columns", `repeat(${l.columns || 2}, minmax(0, 1fr))`]);
|
|
10118
|
-
} else if (l?.mode === "free") {
|
|
10119
|
-
if (!d.some(([p]) => p === "position")) d.push(["position", "relative"]);
|
|
10120
|
-
} else {
|
|
10121
|
-
d.push(["display", "flex"], ["flex-direction", l?.direction || "column"]);
|
|
10122
|
-
if (l?.wrap) d.push(["flex-wrap", "wrap"]);
|
|
10123
|
-
if (l?.align) d.push(["align-items", ALIGN[l.align]]);
|
|
10124
|
-
if (l?.justify) d.push(["justify-content", JUSTIFY[l.justify]]);
|
|
10125
|
-
}
|
|
10126
|
-
if (l?.gap !== void 0 && l.mode !== "free") d.push(["gap", px(l.gap)]);
|
|
10127
|
-
if (l?.padding !== void 0) d.push(["padding", padding(l.padding)]);
|
|
10128
|
-
}
|
|
10129
|
-
taille(d, "w", node4.size?.w, parent);
|
|
10130
|
-
taille(d, "h", node4.size?.h, parent);
|
|
10131
|
-
for (const [k, prop] of [["minW", "min-width"], ["minH", "min-height"], ["maxW", "max-width"], ["maxH", "max-height"]]) {
|
|
10132
|
-
if (node4.size?.[k] !== void 0) d.push([prop, px(node4.size[k])]);
|
|
10133
|
-
}
|
|
10134
|
-
const s = node4.style || {};
|
|
10135
|
-
if (s.fill !== void 0 && node4.type !== "text") d.push(["background", remplissage(s.fill)]);
|
|
10136
|
-
if (s.stroke) d.push(["border", `${px(s.stroke.width)} solid ${s.stroke.color}`]);
|
|
10137
|
-
if (node4.type === "shape" && node4.shape?.kind === "ellipse") d.push(["border-radius", "50%"]);
|
|
10138
|
-
else if (s.radius !== void 0) d.push(["border-radius", typeof s.radius === "number" ? px(s.radius) : s.radius.map(px).join(" ")]);
|
|
10139
|
-
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(", ")]);
|
|
10140
|
-
if (s.opacity !== void 0 && s.opacity !== 1) d.push(["opacity", String(s.opacity)]);
|
|
10141
|
-
if (s.clip) d.push(["overflow", "hidden"]);
|
|
10142
|
-
if (node4.type === "shape" && node4.shape?.kind === "line") d.push(["height", "0"], ["border-top", `${px(s.stroke?.width ?? 1)} solid ${s.stroke?.color ?? "#000000"}`]);
|
|
10143
|
-
const t = node4.text;
|
|
10144
|
-
if (node4.type === "text") {
|
|
10145
|
-
if (t.font) d.push(["font-family", `"${t.font}", sans-serif`]);
|
|
10146
|
-
if (t.size !== void 0) d.push(["font-size", px(t.size)]);
|
|
10147
|
-
if (t.weight !== void 0) d.push(["font-weight", String(t.weight)]);
|
|
10148
|
-
if (t.lineHeight !== void 0) d.push(["line-height", String(t.lineHeight)]);
|
|
10149
|
-
if (t.letterSpacing !== void 0) d.push(["letter-spacing", px(t.letterSpacing)]);
|
|
10150
|
-
if (t.align) d.push(["text-align", t.align]);
|
|
10151
|
-
if (t.transform && t.transform !== "none") d.push(["text-transform", t.transform]);
|
|
10152
|
-
d.push(["color", t.color || "#000000"]);
|
|
10153
|
-
if (s.fill !== void 0) d.push(["background", remplissage(s.fill)]);
|
|
10154
|
-
d.push(["white-space", "pre-wrap"]);
|
|
10155
|
-
}
|
|
10156
|
-
if (node4.type === "image") d.push(["display", "block"], ["object-fit", node4.image.fit || "cover"]);
|
|
10157
|
-
return d;
|
|
10158
|
-
}
|
|
10159
|
-
function tagOf(node4) {
|
|
10160
|
-
return node4.as || DEFAULT_TAG[node4.type];
|
|
10161
|
-
}
|
|
10162
|
-
var BASE_CSS = "*,*::before,*::after{box-sizing:border-box;margin:0}";
|
|
10163
|
-
function parentsOf(doc) {
|
|
10164
|
-
const m = /* @__PURE__ */ new Map();
|
|
10165
|
-
for (const p of doc.pages) for (const id of p.frames) m.set(id, null);
|
|
10166
|
-
for (const n of Object.values(doc.nodes)) for (const e of n.children || []) m.set(e, n);
|
|
10167
|
-
return m;
|
|
10168
|
-
}
|
|
10169
|
-
|
|
10170
|
-
// src/studio/check.js
|
|
10171
|
-
function parseColor(c) {
|
|
10172
|
-
if (!isColor(c)) return null;
|
|
10173
|
-
const s = c.trim().toLowerCase();
|
|
10174
|
-
if (s === "transparent") return [0, 0, 0, 0];
|
|
10175
|
-
if (s.startsWith("#")) {
|
|
10176
|
-
let h = s.slice(1);
|
|
10177
|
-
if (h.length <= 4) h = [...h].map((x) => x + x).join("");
|
|
10178
|
-
const n = (i) => parseInt(h.slice(i, i + 2), 16);
|
|
10179
|
-
return [n(0), n(2), n(4), h.length === 8 ? n(6) / 255 : 1];
|
|
10180
|
-
}
|
|
10181
|
-
const v = s.match(/[\d.]+/g).map(Number);
|
|
10182
|
-
return [v[0], v[1], v[2], v[3] ?? 1];
|
|
10183
|
-
}
|
|
10184
|
-
function luminance([r, g, b]) {
|
|
10185
|
-
const lin = (x) => {
|
|
10186
|
-
x /= 255;
|
|
10187
|
-
return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
|
|
10188
|
-
};
|
|
10189
|
-
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
|
|
10190
|
-
}
|
|
10191
|
-
var melange = (dessus, fond) => [0, 1, 2].map((i) => dessus[i] * dessus[3] + fond[i] * (1 - dessus[3])).concat(1);
|
|
10192
|
-
function contrastRatio(a, b) {
|
|
10193
|
-
const [l1, l2] = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
|
10194
|
-
return (l1 + 0.05) / (l2 + 0.05);
|
|
10195
|
-
}
|
|
10196
|
-
function fondsSous(doc, id, parents) {
|
|
10197
|
-
const couches = [];
|
|
10198
|
-
let n = doc.nodes[id];
|
|
10199
|
-
if (n.type === "text" && n.style?.fill !== void 0) couches.push(n.style.fill);
|
|
10200
|
-
for (let p = parents.get(id); p; p = parents.get(p.id)) if (p.style?.fill !== void 0) couches.push(p.style.fill);
|
|
10201
|
-
let fonds = [[255, 255, 255, 1]];
|
|
10202
|
-
for (const f of couches.reverse()) {
|
|
10203
|
-
const couleurs = typeof f === "string" ? [parseColor(f)] : f.stops.map((s) => parseColor(s.color));
|
|
10204
|
-
fonds = couleurs.flatMap((c) => fonds.map((base2) => melange(c, base2)));
|
|
10205
|
-
}
|
|
10206
|
-
return fonds;
|
|
10207
|
-
}
|
|
10208
|
-
function check(doc) {
|
|
10209
|
-
const issues = [];
|
|
10210
|
-
const parents = parentsOf(doc);
|
|
10211
|
-
for (const n of Object.values(doc.nodes)) {
|
|
10212
|
-
if (n.type === "text") {
|
|
10213
|
-
const couleur = parseColor(n.text.color || "#000000");
|
|
10214
|
-
const grand = (n.text.size ?? 16) >= 24 || (n.text.size ?? 16) >= 18.66 && (n.text.weight ?? 400) >= 700;
|
|
10215
|
-
const requis = grand ? 3 : 4.5;
|
|
10216
|
-
let pire = null;
|
|
10217
|
-
for (const fond of fondsSous(doc, n.id, parents)) {
|
|
10218
|
-
const ratio = contrastRatio(melange(couleur, fond), fond);
|
|
10219
|
-
if (!pire || ratio < pire.ratio) pire = { ratio, fond };
|
|
10220
|
-
}
|
|
10221
|
-
if (pire && pire.ratio < requis) {
|
|
10222
|
-
const hex = (c) => `#${c.slice(0, 3).map((x) => Math.round(x).toString(16).padStart(2, "0")).join("")}`;
|
|
10223
|
-
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) } });
|
|
10224
|
-
}
|
|
10225
|
-
}
|
|
10226
|
-
if (n.type === "frame" && n.children.length === 0 && n.style?.fill === void 0 && !n.style?.stroke) {
|
|
10227
|
-
issues.push({ rule: "empty-frame", severity: "warning", node: n.id, name: n.name });
|
|
10228
|
-
}
|
|
10229
|
-
if (n.type === "image" && !n.alt) issues.push({ rule: "image-alt", severity: "warning", node: n.id, name: n.name });
|
|
10230
|
-
}
|
|
10231
|
-
return { issues };
|
|
10232
|
-
}
|
|
10233
|
-
|
|
10234
|
-
// src/studio/emit/html.js
|
|
10235
|
-
var ECHAPPE = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
|
|
10236
|
-
var escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ECHAPPE[c]);
|
|
10237
|
-
function slug(nom) {
|
|
10238
|
-
const s = String(nom).normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
|
|
10239
|
-
return /^[a-z]/.test(s) ? s : `n-${s || "noeud"}`;
|
|
10240
|
-
}
|
|
10241
|
-
function classNames(doc, page) {
|
|
10242
|
-
const prises = /* @__PURE__ */ new Set();
|
|
10243
|
-
const classes = /* @__PURE__ */ new Map();
|
|
10244
|
-
const unique = (base2) => {
|
|
10245
|
-
let c = base2;
|
|
10246
|
-
let k = 2;
|
|
10247
|
-
while (prises.has(c)) c = `${base2}-${k++}`;
|
|
10248
|
-
prises.add(c);
|
|
10249
|
-
return c;
|
|
10250
|
-
};
|
|
10251
|
-
const visiter = (id, racine) => {
|
|
10252
|
-
const n = doc.nodes[id];
|
|
10253
|
-
const c = racine ? unique(`${racine}__${slug(n.name)}`) : unique(slug(n.name));
|
|
10254
|
-
classes.set(id, c);
|
|
10255
|
-
for (const e of n.children || []) visiter(e, racine || c);
|
|
10256
|
-
};
|
|
10257
|
-
for (const id of page.frames) visiter(id, null);
|
|
10258
|
-
return classes;
|
|
10259
|
-
}
|
|
10260
|
-
function emitHtml(doc, { page: pageId, assets = {}, title, lang = "fr" } = {}) {
|
|
10261
|
-
const page = pageId ? doc.pages.find((p) => p.id === pageId) : doc.pages[0];
|
|
10262
|
-
if (!page) throw new StudioError("studio_page_not_found", `Page introuvable : ${pageId}`, void 0, 404);
|
|
10263
|
-
const parents = parentsOf(doc);
|
|
10264
|
-
const classes = classNames(doc, page);
|
|
10265
|
-
const warnings = [];
|
|
10266
|
-
const regles = [BASE_CSS];
|
|
10267
|
-
const html = (id, profondeur) => {
|
|
10268
|
-
const n = doc.nodes[id];
|
|
10269
|
-
const c = classes.get(id);
|
|
10270
|
-
const decl = nodeCss(n, parents.get(id));
|
|
10271
|
-
if (decl.length) regles.push(`.${c}{${decl.map(([p, v]) => `${p}:${v}`).join(";")}}`);
|
|
10272
|
-
const tag = tagOf(n);
|
|
10273
|
-
const pad2 = " ".repeat(profondeur);
|
|
10274
|
-
if (n.type === "image") {
|
|
10275
|
-
const asset = n.image.src.slice("asset:".length);
|
|
10276
|
-
if (n.alt === void 0) warnings.push(`image-alt : \xAB ${n.name} \xBB n'a pas de texte alternatif`);
|
|
10277
|
-
return `${pad2}<img class="${c}" src="${escapeHtml(assets[asset] || `assets/${asset}`)}" alt="${escapeHtml(n.alt ?? "")}">`;
|
|
10278
|
-
}
|
|
10279
|
-
if (n.type === "text") return `${pad2}<${tag} class="${c}">${escapeHtml(n.text.content)}</${tag}>`;
|
|
10280
|
-
const enfants = (n.children || []).map((e) => html(e, profondeur + 1));
|
|
10281
|
-
return enfants.length ? `${pad2}<${tag} class="${c}">
|
|
10282
|
-
${enfants.join("\n")}
|
|
10283
|
-
${pad2}</${tag}>` : `${pad2}<${tag} class="${c}"></${tag}>`;
|
|
10284
|
-
};
|
|
10285
|
-
const corps = page.frames.map((id) => html(id, 2)).join("\n");
|
|
10286
|
-
const index = `<!doctype html>
|
|
10287
|
-
<html lang="${escapeHtml(lang)}">
|
|
10288
|
-
<head>
|
|
10289
|
-
<meta charset="utf-8">
|
|
10290
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
10291
|
-
<title>${escapeHtml(title || page.name)}</title>
|
|
10292
|
-
<link rel="stylesheet" href="styles.css">
|
|
10293
|
-
</head>
|
|
10294
|
-
<body>
|
|
10295
|
-
${corps}
|
|
10296
|
-
</body>
|
|
10297
|
-
</html>
|
|
10298
|
-
`;
|
|
10299
|
-
const css = `${regles.join("\n")}
|
|
10300
|
-
`;
|
|
10301
|
-
const octets = (s) => new TextEncoder().encode(s).length;
|
|
10302
|
-
return {
|
|
10303
|
-
target: "html",
|
|
10304
|
-
files: [
|
|
10305
|
-
{ path: "index.html", content: index, bytes: octets(index) },
|
|
10306
|
-
{ path: "styles.css", content: css, bytes: octets(css) }
|
|
10307
|
-
],
|
|
10308
|
-
warnings
|
|
10309
|
-
};
|
|
10310
|
-
}
|
|
10311
|
-
|
|
10312
|
-
// src/studio/render.js
|
|
10313
|
-
function renderNode(doc, nodeId, { document: d = globalThis.document, assets = {}, parents = parentsOf(doc) } = {}) {
|
|
10314
|
-
if (!d || typeof d.createElement !== "function") {
|
|
10315
|
-
throw new StudioError("studio_render_unavailable", "Le rendu demande un navigateur (aucun DOM ici).");
|
|
10316
|
-
}
|
|
10317
|
-
const creer = (id) => {
|
|
10318
|
-
const n = doc.nodes[id];
|
|
10319
|
-
const el = d.createElement(tagOf(n));
|
|
10320
|
-
el.setAttribute("data-node-id", id);
|
|
10321
|
-
for (const [prop, valeur] of nodeCss(n, parents.get(id))) el.style.setProperty(prop, valeur);
|
|
10322
|
-
if (n.type === "image") {
|
|
10323
|
-
const asset = n.image.src.slice("asset:".length);
|
|
10324
|
-
el.setAttribute("src", assets[asset] || `assets/${asset}`);
|
|
10325
|
-
el.setAttribute("alt", n.alt ?? "");
|
|
10326
|
-
} else if (n.type === "text") {
|
|
10327
|
-
el.textContent = n.text.content;
|
|
10328
|
-
} else {
|
|
10329
|
-
for (const e of n.children || []) el.appendChild(creer(e));
|
|
10330
|
-
}
|
|
10331
|
-
return el;
|
|
10332
|
-
};
|
|
10333
|
-
if (!doc.nodes[nodeId]) throw new StudioError("studio_node_not_found", `N\u0153ud introuvable : ${nodeId}`, void 0, 404);
|
|
10334
|
-
return creer(nodeId);
|
|
10335
|
-
}
|
|
10336
|
-
|
|
10337
|
-
// src/studio/raster.js
|
|
10338
|
-
var XHTML = "http://www.w3.org/1999/xhtml";
|
|
10339
|
-
async function enData(url) {
|
|
10340
|
-
const reponse = await fetch(url);
|
|
10341
|
-
if (!reponse.ok) throw new StudioError("studio_asset_unavailable", `Ressource illisible pour l'export : ${url} (${reponse.status})`);
|
|
10342
|
-
const blob = await reponse.blob();
|
|
10343
|
-
return await new Promise((ok, ko) => {
|
|
10344
|
-
const f = new FileReader();
|
|
10345
|
-
f.onload = () => ok(f.result);
|
|
10346
|
-
f.onerror = ko;
|
|
10347
|
-
f.readAsDataURL(blob);
|
|
10348
|
-
});
|
|
10349
|
-
}
|
|
10350
|
-
async function policesIncorporees(d) {
|
|
10351
|
-
const regles = [];
|
|
10352
|
-
for (const feuille of d.styleSheets) {
|
|
10353
|
-
let liste;
|
|
10354
|
-
try {
|
|
10355
|
-
liste = feuille.cssRules;
|
|
10356
|
-
} catch {
|
|
10357
|
-
continue;
|
|
10358
|
-
}
|
|
10359
|
-
for (const r of liste) {
|
|
10360
|
-
if (r.type !== 5) continue;
|
|
10361
|
-
let css = r.cssText;
|
|
10362
|
-
const base2 = feuille.href || d.baseURI;
|
|
10363
|
-
for (const [, brut] of css.matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/g)) {
|
|
10364
|
-
if (brut.startsWith("data:")) continue;
|
|
10365
|
-
css = css.replace(brut, await enData(new URL(brut, base2).href));
|
|
10366
|
-
}
|
|
10367
|
-
regles.push(css);
|
|
10368
|
-
}
|
|
10369
|
-
}
|
|
10370
|
-
return regles.join("\n");
|
|
10371
|
-
}
|
|
10372
|
-
function figerLignes(racine, d) {
|
|
10373
|
-
for (const el of racine.querySelectorAll("[data-node-id]")) {
|
|
10374
|
-
const texte = el.firstChild;
|
|
10375
|
-
if (!texte || texte.nodeType !== 3 || el.childNodes.length !== 1) continue;
|
|
10376
|
-
const t = texte.textContent;
|
|
10377
|
-
const r = d.createRange();
|
|
10378
|
-
let haut = null;
|
|
10379
|
-
let sortie = "";
|
|
10380
|
-
for (let i = 0; i < t.length; i++) {
|
|
10381
|
-
r.setStart(texte, i);
|
|
10382
|
-
r.setEnd(texte, i + 1);
|
|
10383
|
-
const rect = r.getClientRects()[0];
|
|
10384
|
-
if (rect && haut !== null && rect.top > haut + 1 && t[i] !== " " && t[i] !== "\n") sortie = `${sortie.replace(/ +$/, "")}
|
|
10385
|
-
`;
|
|
10386
|
-
if (rect) haut = rect.top;
|
|
10387
|
-
sortie += t[i];
|
|
10388
|
-
}
|
|
10389
|
-
texte.textContent = sortie;
|
|
10390
|
-
el.style.setProperty("white-space", "pre");
|
|
10391
|
-
}
|
|
10392
|
-
}
|
|
10393
|
-
async function renderPng(doc, { frame, scale = 1, assets = {}, document: d = globalThis.document } = {}) {
|
|
10394
|
-
const W = globalThis;
|
|
10395
|
-
if (!d?.body || typeof W.XMLSerializer !== "function" || typeof W.Image !== "function" || typeof W.fetch !== "function") {
|
|
10396
|
-
throw new StudioError("studio_render_unavailable", "L'export d'image se fait dans un navigateur (aucun DOM ici).");
|
|
10397
|
-
}
|
|
10398
|
-
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" });
|
|
10399
|
-
const id = doc.nodes[frame]?.type === "frame" ? frame : Object.values(doc.nodes).find((n) => n.type === "frame" && n.name === frame)?.id;
|
|
10400
|
-
if (!id) throw new StudioError("studio_node_not_found", `Cadre introuvable : ${frame}`, void 0, 404);
|
|
10401
|
-
const hote = d.createElement("div");
|
|
10402
|
-
hote.setAttribute("aria-hidden", "true");
|
|
10403
|
-
hote.setAttribute("data-studio-raster", "");
|
|
10404
|
-
hote.style.cssText = "position:fixed;left:-100000px;top:0;contain:layout style;pointer-events:none";
|
|
10405
|
-
const base2 = d.createElement("style");
|
|
10406
|
-
base2.textContent = "[data-studio-raster] *,[data-studio-raster] *::before,[data-studio-raster] *::after{box-sizing:border-box;margin:0}";
|
|
10407
|
-
hote.append(base2, renderNode(doc, id, { document: d, assets }));
|
|
10408
|
-
d.body.appendChild(hote);
|
|
10409
|
-
try {
|
|
10410
|
-
const el = hote.lastChild;
|
|
10411
|
-
await d.fonts?.ready;
|
|
10412
|
-
await Promise.all([...el.querySelectorAll("img")].map((img) => img.decode().catch(() => {
|
|
10413
|
-
})));
|
|
10414
|
-
figerLignes(el, d);
|
|
10415
|
-
const rect = el.getBoundingClientRect();
|
|
10416
|
-
const width = Math.ceil(rect.width);
|
|
10417
|
-
const height = Math.ceil(rect.height);
|
|
10418
|
-
const copie2 = el.cloneNode(true);
|
|
10419
|
-
for (const img of copie2.querySelectorAll("img")) img.setAttribute("src", await enData(new URL(img.getAttribute("src"), d.baseURI).href));
|
|
10420
|
-
const polices = await policesIncorporees(d);
|
|
10421
|
-
const xhtml = new W.XMLSerializer().serializeToString(copie2);
|
|
10422
|
-
const style = `${BASE_CSS}
|
|
10423
|
-
${polices}`.replace(/]]>/g, "]]>");
|
|
10424
|
-
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>`;
|
|
10425
|
-
const image = new W.Image();
|
|
10426
|
-
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
|
10427
|
-
await image.decode();
|
|
10428
|
-
const canvas = d.createElement("canvas");
|
|
10429
|
-
canvas.width = Math.round(width * scale);
|
|
10430
|
-
canvas.height = Math.round(height * scale);
|
|
10431
|
-
canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
|
|
10432
|
-
const blob = await new Promise((ok) => canvas.toBlob(ok, "image/png"));
|
|
10433
|
-
return { bytes: new Uint8Array(await blob.arrayBuffer()), mime: "image/png", width: canvas.width, height: canvas.height };
|
|
10434
|
-
} finally {
|
|
10435
|
-
hote.remove();
|
|
10436
|
-
}
|
|
10437
|
-
}
|
|
10438
|
-
|
|
10439
|
-
// src/studio/targets.js
|
|
10440
|
-
var TARGETS = Object.freeze([
|
|
10441
|
-
Object.freeze({ target: "html", status: "available" }),
|
|
10442
|
-
Object.freeze({ target: "email", status: "planned", phase: 3 }),
|
|
10443
|
-
Object.freeze({ target: "react", status: "planned", phase: 6 })
|
|
10444
|
-
]);
|
|
10445
|
-
|
|
10446
|
-
// src/studio/document.js
|
|
10447
|
-
var copie = (v) => v === void 0 ? void 0 : structuredClone(v);
|
|
10448
|
-
var StudioDocument = class {
|
|
10449
|
-
#doc;
|
|
10450
|
-
#passe = [];
|
|
10451
|
-
// lots qui défont, du plus ancien au plus récent
|
|
10452
|
-
#futur = [];
|
|
10453
|
-
// lots qui refont
|
|
10454
|
-
#ecoutes = /* @__PURE__ */ new Set();
|
|
10455
|
-
/** @param {object} [json] un document enregistré ; absent : un document vide */
|
|
10456
|
-
constructor(json) {
|
|
10457
|
-
this.#doc = json === void 0 ? createDocument() : assertValid(migrate(structuredClone(json)));
|
|
10458
|
-
}
|
|
10459
|
-
/* ── Lire ────────────────────────────────────────────────────────────────────────────────── */
|
|
10460
|
-
get pages() {
|
|
10461
|
-
return this.#doc.pages.map((p) => ({ ...p, frames: [...p.frames] }));
|
|
10462
|
-
}
|
|
10463
|
-
/** Une copie du nœud : la modifier ne change pas le document (seules les opérations le font). */
|
|
10464
|
-
node(id) {
|
|
10465
|
-
return copie(this.#doc.nodes[id]) ?? null;
|
|
10466
|
-
}
|
|
10467
|
-
/** Premier nœud qui correspond, dans l'ordre des pages puis de l'arbre. `{ name, type }` */
|
|
10468
|
-
find(critere = {}) {
|
|
10469
|
-
return this.findAll(critere)[0] ?? null;
|
|
10470
|
-
}
|
|
10471
|
-
findAll({ name, type } = {}) {
|
|
10472
|
-
const out = [];
|
|
10473
|
-
const visiter = (id) => {
|
|
10474
|
-
const n = this.#doc.nodes[id];
|
|
10475
|
-
if ((name === void 0 || n.name === name) && (type === void 0 || n.type === type)) out.push(copie(n));
|
|
10476
|
-
for (const e of n.children || []) visiter(e);
|
|
10477
|
-
};
|
|
10478
|
-
for (const p of this.#doc.pages) for (const id of p.frames) visiter(id);
|
|
10479
|
-
return out;
|
|
10480
|
-
}
|
|
10481
|
-
/** Le document en forme canonique : deux documents égaux donnent les mêmes octets. */
|
|
10482
|
-
toJSON() {
|
|
10483
|
-
return structuredClone(canonical(this.#doc));
|
|
10484
|
-
}
|
|
10485
|
-
/* ── Vérifier, émettre, rendre (P85) ─────────────────────────────────────────────────────── */
|
|
10486
|
-
/** → `{ issues: [{ rule, severity, node, name, detail? }] }` */
|
|
10487
|
-
check() {
|
|
10488
|
-
return check(this.#doc);
|
|
10489
|
-
}
|
|
10490
|
-
/** → `{ target, files: [{ path, content, bytes }], warnings }`. Phase 1 : `target: "html"` seulement. */
|
|
10491
|
-
emit({ target = "html", ...options } = {}) {
|
|
10492
|
-
if (target !== "html") {
|
|
10493
|
-
const prevue = TARGETS.find((t) => t.target === target);
|
|
10494
|
-
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);
|
|
10495
|
-
}
|
|
10496
|
-
return emitHtml(this.#doc, options);
|
|
10497
|
-
}
|
|
10498
|
-
/** Un cadre en PNG, dans le navigateur. → `{ bytes, mime, width, height }` ; hors navigateur : `studio_render_unavailable`. */
|
|
10499
|
-
async render({ frame, format = "png", scale = 1, assets, document } = {}) {
|
|
10500
|
-
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);
|
|
10501
|
-
return renderPng(this.#doc, { frame, scale, assets, document });
|
|
10502
|
-
}
|
|
10503
|
-
/* ── Modifier ────────────────────────────────────────────────────────────────────────────── */
|
|
10504
|
-
/** Applique un lot, en entier ou pas du tout. → `{ applied, created, removed }` */
|
|
10505
|
-
apply(ops, { source = "user" } = {}) {
|
|
10506
|
-
const r = applyOps(this.#doc, ops);
|
|
10507
|
-
this.#doc = r.doc;
|
|
10508
|
-
this.#passe.push(r.inverse);
|
|
10509
|
-
this.#futur = [];
|
|
10510
|
-
this.#emettre(ops, source);
|
|
10511
|
-
return { applied: ops.length, created: r.created, removed: r.removed };
|
|
10512
|
-
}
|
|
10513
|
-
set(id, path, value) {
|
|
10514
|
-
return this.apply([{ op: "set", id, path, value }]);
|
|
10515
|
-
}
|
|
10516
|
-
/** Insère un nœud et rend son id. `parent` : id d'un cadre, ou d'une page. */
|
|
10517
|
-
insert(parent, node4, { index } = {}) {
|
|
10518
|
-
return this.apply([{ op: "insert", parent, node: node4, index }]).created[0];
|
|
10519
|
-
}
|
|
10520
|
-
move(id, { parent, index } = {}) {
|
|
10521
|
-
return this.apply([{ op: "move", id, parent, index }]);
|
|
10522
|
-
}
|
|
10523
|
-
remove(id) {
|
|
10524
|
-
return this.apply([{ op: "remove", id }]);
|
|
10525
|
-
}
|
|
10526
|
-
undo() {
|
|
10527
|
-
return this.#deplacer(this.#passe, this.#futur, "undo");
|
|
10528
|
-
}
|
|
10529
|
-
redo() {
|
|
10530
|
-
return this.#deplacer(this.#futur, this.#passe, "redo");
|
|
10531
|
-
}
|
|
10532
|
-
history() {
|
|
10533
|
-
return { undo: this.#passe.length, redo: this.#futur.length };
|
|
10534
|
-
}
|
|
10535
|
-
/** Écoute les changements ; rend la fonction qui arrête l'écoute. `e = { ops, source }` */
|
|
10536
|
-
on(evenement, fn) {
|
|
10537
|
-
if (evenement !== "change") throw new StudioError("studio_event_unknown", `\xC9v\xE9nement inconnu : ${evenement}`);
|
|
10538
|
-
this.#ecoutes.add(fn);
|
|
10539
|
-
return () => this.#ecoutes.delete(fn);
|
|
10540
|
-
}
|
|
10541
|
-
#deplacer(depuis, vers, source) {
|
|
10542
|
-
const lot = depuis.pop();
|
|
10543
|
-
if (!lot) return false;
|
|
10544
|
-
const r = applyOps(this.#doc, lot, { internal: true });
|
|
10545
|
-
this.#doc = r.doc;
|
|
10546
|
-
vers.push(r.inverse);
|
|
10547
|
-
this.#emettre(lot, source);
|
|
10548
|
-
return true;
|
|
10549
|
-
}
|
|
10550
|
-
#emettre(ops, source) {
|
|
10551
|
-
for (const fn of this.#ecoutes) {
|
|
10552
|
-
try {
|
|
10553
|
-
fn({ ops: copie(ops), source });
|
|
10554
|
-
} catch {
|
|
10555
|
-
}
|
|
10556
|
-
}
|
|
10557
|
-
}
|
|
10558
|
-
};
|
|
10559
|
-
|
|
10560
|
-
// src/resources/design.js
|
|
10561
|
-
var base = "/api/design";
|
|
10562
|
-
var projectPath = (id) => `${base}/projects/${encodeURIComponent(id)}`;
|
|
10563
|
-
var byType = (path, type) => type === void 0 ? path : `${path}?type=${encodeURIComponent(type)}`;
|
|
10564
|
-
var StudioProject = class _StudioProject {
|
|
10565
|
-
#client;
|
|
10566
|
-
constructor(client, data) {
|
|
10567
|
-
this.#client = client;
|
|
10568
|
-
Object.assign(this, data);
|
|
10569
|
-
}
|
|
10570
|
-
async open() {
|
|
10571
|
-
const path = projectPath(this.id);
|
|
10572
|
-
const { document, version } = await this.#client.get(`${path}/document`);
|
|
10573
|
-
const doc = new StudioDocument(document);
|
|
10574
|
-
let current = version;
|
|
10575
|
-
let pending = Promise.resolve();
|
|
10576
|
-
doc.save = ({ version: name } = {}) => {
|
|
10577
|
-
const document2 = doc.toJSON();
|
|
10578
|
-
const request = pending.then(async () => {
|
|
10579
|
-
const result = await this.#client.post(`${path}/document`, { document: document2, baseVersion: current, name });
|
|
10580
|
-
current = result.version;
|
|
10581
|
-
this.version = { id: current, name: name ?? null };
|
|
10582
|
-
this.bytes = result.bytes;
|
|
10583
|
-
return { version: current, bytes: result.bytes };
|
|
10584
|
-
});
|
|
10585
|
-
pending = request.catch(() => {
|
|
10586
|
-
});
|
|
10587
|
-
return request;
|
|
10588
|
-
};
|
|
10589
|
-
return doc;
|
|
10590
|
-
}
|
|
10591
|
-
async update(data) {
|
|
10592
|
-
const { project } = await this.#client.post(projectPath(this.id), data);
|
|
10593
|
-
Object.assign(this, project);
|
|
10594
|
-
return this;
|
|
10595
|
-
}
|
|
10596
|
-
async duplicate(data) {
|
|
10597
|
-
const { project } = await this.#client.post(`${projectPath(this.id)}/duplicate`, data);
|
|
10598
|
-
return new _StudioProject(this.#client, project);
|
|
10599
|
-
}
|
|
10600
|
-
async versions() {
|
|
10601
|
-
return (await this.#client.get(`${projectPath(this.id)}/versions`)).versions;
|
|
10602
|
-
}
|
|
10603
|
-
async restore(version) {
|
|
10604
|
-
const { project } = await this.#client.post(`${projectPath(this.id)}/restore`, { version });
|
|
10605
|
-
Object.assign(this, project);
|
|
10606
|
-
return this;
|
|
10607
|
-
}
|
|
10608
|
-
async render({ frame, width, height } = {}) {
|
|
10609
|
-
return this.#client.post(`${projectPath(this.id)}/render`, { frame, width, height }, { timeout: 0 });
|
|
10610
|
-
}
|
|
10611
|
-
};
|
|
10612
|
-
var DesignResource = class {
|
|
10613
|
-
constructor(client) {
|
|
10614
|
-
const wrap = (data) => new StudioProject(client, data);
|
|
10615
|
-
this.templates = {
|
|
10616
|
-
list: async ({ type } = {}) => (await client.get(byType(`${base}/templates`, type))).templates,
|
|
10617
|
-
get: async (id) => (await client.get(`${base}/templates/${encodeURIComponent(id)}`)).template
|
|
10618
|
-
};
|
|
10619
|
-
this.projects = {
|
|
10620
|
-
create: async (data) => wrap((await client.post(`${base}/projects`, data)).project),
|
|
10621
|
-
list: async ({ type } = {}) => (await client.get(byType(`${base}/projects`, type))).projects.map(wrap),
|
|
10622
|
-
get: async (id) => wrap((await client.get(projectPath(id))).project),
|
|
10623
|
-
remove: async (id) => client.delete(projectPath(id))
|
|
10624
|
-
};
|
|
10625
|
-
}
|
|
10626
|
-
/** Un document vide, ou rouvert depuis son JSON (validé ; invalide → `studio_document_invalid`). */
|
|
10627
|
-
document(json) {
|
|
10628
|
-
return new StudioDocument(json);
|
|
10629
|
-
}
|
|
10630
|
-
/** Les cibles d'émission et leur état : `[{ target, status: "available" | "planned", phase? }]` */
|
|
10631
|
-
targets() {
|
|
10632
|
-
return TARGETS.map((t) => ({ ...t }));
|
|
10633
|
-
}
|
|
10634
|
-
};
|
|
10635
|
-
|
|
10636
9556
|
// src/index.js
|
|
10637
9557
|
var DEFAULT_BASE_URL = typeof process !== "undefined" && process?.env?.IAGENIFY_API_URL || "https://api.iagenify.com";
|
|
10638
9558
|
var IaGenify = class {
|
|
@@ -10721,7 +9641,6 @@ var IaGenify = class {
|
|
|
10721
9641
|
this.mail = new MailResource(this._client);
|
|
10722
9642
|
this.hosts = new HostsResource(this._client);
|
|
10723
9643
|
this.compute = new ComputeResource(this._client);
|
|
10724
|
-
this.design = new DesignResource(this._client);
|
|
10725
9644
|
}
|
|
10726
9645
|
async getUser() {
|
|
10727
9646
|
const res = await this._client.get("/api/auth/me");
|