beplus-mcp 0.44.0 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -2
- package/dist/index.js +3520 -57
- package/dist/index.js.map +1 -1
- package/dist/remote-server.js +3520 -57
- package/dist/remote-server.js.map +1 -1
- package/package.json +1 -1
package/dist/remote-server.js
CHANGED
|
@@ -6884,6 +6884,2721 @@ var require_dist = __commonJS({
|
|
|
6884
6884
|
}
|
|
6885
6885
|
});
|
|
6886
6886
|
|
|
6887
|
+
// src/vendor/canvas-core/index.cjs
|
|
6888
|
+
var require_canvas_core = __commonJS({
|
|
6889
|
+
"src/vendor/canvas-core/index.cjs"(exports, module) {
|
|
6890
|
+
"use strict";
|
|
6891
|
+
var __defProp2 = Object.defineProperty;
|
|
6892
|
+
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
6893
|
+
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
6894
|
+
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
6895
|
+
var __export2 = (target, all) => {
|
|
6896
|
+
for (var name in all)
|
|
6897
|
+
__defProp2(target, name, { get: all[name], enumerable: true });
|
|
6898
|
+
};
|
|
6899
|
+
var __copyProps2 = (to, from, except, desc) => {
|
|
6900
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
6901
|
+
for (let key of __getOwnPropNames2(from))
|
|
6902
|
+
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
6903
|
+
__defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
6904
|
+
}
|
|
6905
|
+
return to;
|
|
6906
|
+
};
|
|
6907
|
+
var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
|
|
6908
|
+
var index_exports = {};
|
|
6909
|
+
__export2(index_exports, {
|
|
6910
|
+
BOARD_FIELDS: () => BOARD_FIELDS,
|
|
6911
|
+
BoardStore: () => BoardStore,
|
|
6912
|
+
DEFAULT_MAX_PER_COLUMN: () => DEFAULT_MAX_PER_COLUMN,
|
|
6913
|
+
DEFAULT_PLACEMENT_GAP: () => DEFAULT_PLACEMENT_GAP,
|
|
6914
|
+
DEFAULT_SHAPE_SIZE: () => DEFAULT_SHAPE_SIZE,
|
|
6915
|
+
DEFAULT_TIDY_GAP_X: () => DEFAULT_TIDY_GAP_X,
|
|
6916
|
+
DEFAULT_TIDY_GAP_Y: () => DEFAULT_TIDY_GAP_Y,
|
|
6917
|
+
DEFAULT_TIDY_SWEEPS: () => DEFAULT_TIDY_SWEEPS,
|
|
6918
|
+
Draft: () => Draft,
|
|
6919
|
+
EMPTY_INTERACTION: () => EMPTY_INTERACTION,
|
|
6920
|
+
FORBIDDEN_PATH_SEGMENTS: () => FORBIDDEN_PATH_SEGMENTS,
|
|
6921
|
+
HISTORY_LIMIT: () => HISTORY_LIMIT,
|
|
6922
|
+
HISTORY_MAX_BYTES: () => HISTORY_MAX_BYTES,
|
|
6923
|
+
HistoryStack: () => HistoryStack,
|
|
6924
|
+
InvalidBoardSetError: () => InvalidBoardSetError,
|
|
6925
|
+
InvalidPathError: () => InvalidPathError,
|
|
6926
|
+
MAX_OP_BYTES: () => MAX_OP_BYTES2,
|
|
6927
|
+
MAX_REPLAY: () => MAX_REPLAY,
|
|
6928
|
+
MIGRATIONS: () => MIGRATIONS,
|
|
6929
|
+
OPS: () => OPS2,
|
|
6930
|
+
OpSyncClient: () => OpSyncClient,
|
|
6931
|
+
OpTooLargeError: () => OpTooLargeError2,
|
|
6932
|
+
SCHEMA_VERSION: () => SCHEMA_VERSION2,
|
|
6933
|
+
SHAPE_NODE_TYPE: () => SHAPE_NODE_TYPE,
|
|
6934
|
+
anyPathCrosses: () => anyPathCrosses,
|
|
6935
|
+
applyBoardSet: () => applyBoardSet,
|
|
6936
|
+
applyConfirmed: () => applyConfirmed2,
|
|
6937
|
+
applyEnvelopes: () => applyEnvelopes,
|
|
6938
|
+
applyOp: () => applyOp,
|
|
6939
|
+
applyOps: () => applyOps,
|
|
6940
|
+
assertBoardSet: () => assertBoardSet,
|
|
6941
|
+
assertOpEnvelopeFits: () => assertOpEnvelopeFits,
|
|
6942
|
+
batchOf: () => batchOf2,
|
|
6943
|
+
boundsOf: () => boundsOf,
|
|
6944
|
+
captureOf: () => captureOf,
|
|
6945
|
+
createCloneCounts: () => createCloneCounts,
|
|
6946
|
+
createEmptyBoard: () => createEmptyBoard,
|
|
6947
|
+
createOpIdGenerator: () => createOpIdGenerator,
|
|
6948
|
+
createShapeNode: () => createShapeNode,
|
|
6949
|
+
defaultScheduler: () => defaultScheduler,
|
|
6950
|
+
estimateOpBytes: () => estimateOpBytes,
|
|
6951
|
+
fanOutPositions: () => fanOutPositions,
|
|
6952
|
+
findFreeSpot: () => findFreeSpot,
|
|
6953
|
+
getPath: () => getPath,
|
|
6954
|
+
hasPath: () => hasPath,
|
|
6955
|
+
invert: () => invert,
|
|
6956
|
+
invertBoardSet: () => invertBoardSet,
|
|
6957
|
+
invertEdgeAdd: () => invertEdgeAdd,
|
|
6958
|
+
invertEdgeRemove: () => invertEdgeRemove,
|
|
6959
|
+
invertHistoryAppend: () => invertHistoryAppend,
|
|
6960
|
+
invertHistoryRemove: () => invertHistoryRemove,
|
|
6961
|
+
invertNodeAdd: () => invertNodeAdd,
|
|
6962
|
+
invertNodeRemove: () => invertNodeRemove,
|
|
6963
|
+
invertNodeSet: () => invertNodeSet,
|
|
6964
|
+
invertResultSet: () => invertResultSet,
|
|
6965
|
+
isLocalEnvelope: () => isLocalEnvelope,
|
|
6966
|
+
isPropValue: () => isPropValue,
|
|
6967
|
+
migrate: () => migrate,
|
|
6968
|
+
moveOps: () => moveOps,
|
|
6969
|
+
newOpId: () => newOpId,
|
|
6970
|
+
opEnvelopeBytes: () => opEnvelopeBytes,
|
|
6971
|
+
parsePath: () => parsePath,
|
|
6972
|
+
pathsCross: () => pathsCross,
|
|
6973
|
+
placeWithoutOverlap: () => placeWithoutOverlap,
|
|
6974
|
+
propValue: () => propValue,
|
|
6975
|
+
rectOf: () => rectOf2,
|
|
6976
|
+
rectsCollide: () => rectsCollide,
|
|
6977
|
+
reduce: () => reduce,
|
|
6978
|
+
removeNode: () => removeNode,
|
|
6979
|
+
sameBox: () => sameBox,
|
|
6980
|
+
sameNodeIds: () => sameNodeIds,
|
|
6981
|
+
setPath: () => setPath,
|
|
6982
|
+
shallowestMissingPath: () => shallowestMissingPath,
|
|
6983
|
+
tidyUp: () => tidyUp,
|
|
6984
|
+
tidyUpOps: () => tidyUpOps,
|
|
6985
|
+
touchedPaths: () => touchedPaths,
|
|
6986
|
+
trackCapture: () => trackCapture,
|
|
6987
|
+
tryApplyEnvelope: () => tryApplyEnvelope,
|
|
6988
|
+
tryApplyOp: () => tryApplyOp,
|
|
6989
|
+
unsetPath: () => unsetPath,
|
|
6990
|
+
unsetPropValue: () => unsetPropValue,
|
|
6991
|
+
utf8ByteLength: () => utf8ByteLength,
|
|
6992
|
+
walkBatch: () => walkBatch,
|
|
6993
|
+
writeKey: () => writeKey
|
|
6994
|
+
});
|
|
6995
|
+
module.exports = __toCommonJS(index_exports);
|
|
6996
|
+
var SCHEMA_VERSION2 = 1;
|
|
6997
|
+
var SHAPE_NODE_TYPE = "shape";
|
|
6998
|
+
var DEFAULT_SHAPE_SIZE = { w: 180, h: 120 };
|
|
6999
|
+
function randomUuidV4() {
|
|
7000
|
+
let out = "";
|
|
7001
|
+
for (let i = 0; i < 36; i += 1) {
|
|
7002
|
+
if (i === 8 || i === 13 || i === 18 || i === 23) {
|
|
7003
|
+
out += "-";
|
|
7004
|
+
continue;
|
|
7005
|
+
}
|
|
7006
|
+
if (i === 14) {
|
|
7007
|
+
out += "4";
|
|
7008
|
+
continue;
|
|
7009
|
+
}
|
|
7010
|
+
const value = Math.floor(Math.random() * 16);
|
|
7011
|
+
out += (i === 19 ? value & 3 | 8 : value).toString(16);
|
|
7012
|
+
}
|
|
7013
|
+
return out;
|
|
7014
|
+
}
|
|
7015
|
+
function createEmptyBoard(init = {}) {
|
|
7016
|
+
const newId = init.newId ?? randomUuidV4;
|
|
7017
|
+
const timestamp = (init.now ?? Date.now)();
|
|
7018
|
+
return {
|
|
7019
|
+
id: init.id ?? newId(),
|
|
7020
|
+
schemaVersion: SCHEMA_VERSION2,
|
|
7021
|
+
title: init.title ?? "Board sem t\xEDtulo",
|
|
7022
|
+
ownerId: init.ownerId ?? "",
|
|
7023
|
+
folderId: init.folderId ?? null,
|
|
7024
|
+
version: 0,
|
|
7025
|
+
nodes: {},
|
|
7026
|
+
edges: {},
|
|
7027
|
+
results: {},
|
|
7028
|
+
nodeHistory: {},
|
|
7029
|
+
createdAt: timestamp,
|
|
7030
|
+
updatedAt: timestamp
|
|
7031
|
+
};
|
|
7032
|
+
}
|
|
7033
|
+
function createShapeNode(shape, init = {}) {
|
|
7034
|
+
const newId = init.newId ?? randomUuidV4;
|
|
7035
|
+
const timestamp = (init.now ?? Date.now)();
|
|
7036
|
+
return {
|
|
7037
|
+
id: init.id ?? newId(),
|
|
7038
|
+
type: SHAPE_NODE_TYPE,
|
|
7039
|
+
position: init.position ?? { x: 0, y: 0 },
|
|
7040
|
+
size: init.size ?? { w: DEFAULT_SHAPE_SIZE.w, h: DEFAULT_SHAPE_SIZE.h },
|
|
7041
|
+
zIndex: init.zIndex ?? 0,
|
|
7042
|
+
parentId: init.parentId ?? null,
|
|
7043
|
+
data: { shape },
|
|
7044
|
+
createdBy: init.createdBy ?? null,
|
|
7045
|
+
createdAt: timestamp,
|
|
7046
|
+
updatedAt: timestamp
|
|
7047
|
+
};
|
|
7048
|
+
}
|
|
7049
|
+
var MIGRATIONS = {};
|
|
7050
|
+
var MAX_MIGRATION_STEPS = 16;
|
|
7051
|
+
function isRecord2(value) {
|
|
7052
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7053
|
+
}
|
|
7054
|
+
function isFiniteNumber3(value) {
|
|
7055
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
7056
|
+
}
|
|
7057
|
+
function isStringOrNull2(value) {
|
|
7058
|
+
return value === null || typeof value === "string";
|
|
7059
|
+
}
|
|
7060
|
+
function isSeq(value) {
|
|
7061
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
7062
|
+
}
|
|
7063
|
+
function hasOnlyKeys2(record2, keys) {
|
|
7064
|
+
return Object.keys(record2).every((key) => keys.includes(key));
|
|
7065
|
+
}
|
|
7066
|
+
function isJson2(value) {
|
|
7067
|
+
if (value === null) return true;
|
|
7068
|
+
const kind = typeof value;
|
|
7069
|
+
if (kind === "boolean" || kind === "string") return true;
|
|
7070
|
+
if (kind === "number") return Number.isFinite(value);
|
|
7071
|
+
if (Array.isArray(value)) return value.every(isJson2);
|
|
7072
|
+
if (isRecord2(value)) return Object.values(value).every(isJson2);
|
|
7073
|
+
return false;
|
|
7074
|
+
}
|
|
7075
|
+
function isJsonBag2(value) {
|
|
7076
|
+
return isRecord2(value) && Object.values(value).every(isJson2);
|
|
7077
|
+
}
|
|
7078
|
+
function isStringMap(value) {
|
|
7079
|
+
return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
|
|
7080
|
+
}
|
|
7081
|
+
function isPoint2(value) {
|
|
7082
|
+
return isRecord2(value) && hasOnlyKeys2(value, ["x", "y"]) && isFiniteNumber3(value["x"]) && isFiniteNumber3(value["y"]);
|
|
7083
|
+
}
|
|
7084
|
+
function isSize2(value) {
|
|
7085
|
+
return isRecord2(value) && hasOnlyKeys2(value, ["w", "h"]) && isFiniteNumber3(value["w"]) && isFiniteNumber3(value["h"]);
|
|
7086
|
+
}
|
|
7087
|
+
var NODE_KEYS2 = [
|
|
7088
|
+
"id",
|
|
7089
|
+
"type",
|
|
7090
|
+
"position",
|
|
7091
|
+
"size",
|
|
7092
|
+
"zIndex",
|
|
7093
|
+
"parentId",
|
|
7094
|
+
"data",
|
|
7095
|
+
"createdBy",
|
|
7096
|
+
"createdAt",
|
|
7097
|
+
"updatedAt"
|
|
7098
|
+
];
|
|
7099
|
+
var EDGE_KEYS2 = [
|
|
7100
|
+
"id",
|
|
7101
|
+
"source",
|
|
7102
|
+
"sourcePort",
|
|
7103
|
+
"target",
|
|
7104
|
+
"targetPort",
|
|
7105
|
+
"data",
|
|
7106
|
+
"createdBy",
|
|
7107
|
+
"createdAt"
|
|
7108
|
+
];
|
|
7109
|
+
var RESULT_KEYS = [
|
|
7110
|
+
"id",
|
|
7111
|
+
"nodeId",
|
|
7112
|
+
"runId",
|
|
7113
|
+
"generationId",
|
|
7114
|
+
"kind",
|
|
7115
|
+
"url",
|
|
7116
|
+
"lodUrls",
|
|
7117
|
+
"status",
|
|
7118
|
+
"spec",
|
|
7119
|
+
"costDiamonds",
|
|
7120
|
+
"error",
|
|
7121
|
+
"createdAt"
|
|
7122
|
+
];
|
|
7123
|
+
var DOC_KEYS = [
|
|
7124
|
+
"id",
|
|
7125
|
+
"schemaVersion",
|
|
7126
|
+
"title",
|
|
7127
|
+
"ownerId",
|
|
7128
|
+
"folderId",
|
|
7129
|
+
"version",
|
|
7130
|
+
"nodes",
|
|
7131
|
+
"edges",
|
|
7132
|
+
"results",
|
|
7133
|
+
"nodeHistory",
|
|
7134
|
+
"createdAt",
|
|
7135
|
+
"updatedAt",
|
|
7136
|
+
"meta"
|
|
7137
|
+
];
|
|
7138
|
+
var META_KEYS = ["guide", "ialab", "assetUrls"];
|
|
7139
|
+
function isValidMeta(value) {
|
|
7140
|
+
if (value === void 0) return true;
|
|
7141
|
+
return isRecord2(value) && hasOnlyKeys2(value, META_KEYS) && (value["guide"] === void 0 || isStringOrNull2(value["guide"])) && (value["ialab"] === void 0 || value["ialab"] === null || isJsonBag2(value["ialab"])) && (value["assetUrls"] === void 0 || isStringMap(value["assetUrls"]));
|
|
7142
|
+
}
|
|
7143
|
+
var RESULT_KINDS = ["image", "video", "audio", "text"];
|
|
7144
|
+
var RESULT_STATUSES = ["pending", "running", "done", "failed", "cancelled"];
|
|
7145
|
+
function isValidNode2(key, value) {
|
|
7146
|
+
return isRecord2(value) && hasOnlyKeys2(value, NODE_KEYS2) && value["id"] === key && typeof value["type"] === "string" && isPoint2(value["position"]) && isSize2(value["size"]) && isFiniteNumber3(value["zIndex"]) && isStringOrNull2(value["parentId"]) && isJsonBag2(value["data"]) && isStringOrNull2(value["createdBy"]) && isFiniteNumber3(value["createdAt"]) && isFiniteNumber3(value["updatedAt"]);
|
|
7147
|
+
}
|
|
7148
|
+
function isValidEdge2(key, value) {
|
|
7149
|
+
return isRecord2(value) && hasOnlyKeys2(value, EDGE_KEYS2) && value["id"] === key && typeof value["source"] === "string" && typeof value["sourcePort"] === "string" && typeof value["target"] === "string" && typeof value["targetPort"] === "string" && isJsonBag2(value["data"]) && isStringOrNull2(value["createdBy"]) && isFiniteNumber3(value["createdAt"]);
|
|
7150
|
+
}
|
|
7151
|
+
function isValidResult(key, value) {
|
|
7152
|
+
return isRecord2(value) && hasOnlyKeys2(value, RESULT_KEYS) && value["id"] === key && typeof value["nodeId"] === "string" && isStringOrNull2(value["runId"]) && isStringOrNull2(value["generationId"]) && typeof value["kind"] === "string" && RESULT_KINDS.includes(value["kind"]) && isStringOrNull2(value["url"]) && isStringMap(value["lodUrls"]) && typeof value["status"] === "string" && RESULT_STATUSES.includes(value["status"]) && isJsonBag2(value["spec"]) && (value["costDiamonds"] === null || isFiniteNumber3(value["costDiamonds"])) && isStringOrNull2(value["error"]) && isFiniteNumber3(value["createdAt"]);
|
|
7153
|
+
}
|
|
7154
|
+
function isValidHistory(value) {
|
|
7155
|
+
return Array.isArray(value) && value.every((resultId) => typeof resultId === "string");
|
|
7156
|
+
}
|
|
7157
|
+
function normalizeHistory(history) {
|
|
7158
|
+
for (const [nodeId3, list] of Object.entries(history)) {
|
|
7159
|
+
if (Array.isArray(list) && list.length === 0) delete history[nodeId3];
|
|
7160
|
+
}
|
|
7161
|
+
}
|
|
7162
|
+
function everyEntry(value, check2) {
|
|
7163
|
+
return isRecord2(value) && Object.entries(value).every(([key, entry]) => check2(key, entry));
|
|
7164
|
+
}
|
|
7165
|
+
function upgrade(raw) {
|
|
7166
|
+
let current = raw;
|
|
7167
|
+
for (let step2 = 0; step2 <= MAX_MIGRATION_STEPS; step2 += 1) {
|
|
7168
|
+
if (!isRecord2(current)) return null;
|
|
7169
|
+
const version2 = current["schemaVersion"];
|
|
7170
|
+
if (typeof version2 !== "number" || !Number.isInteger(version2)) return null;
|
|
7171
|
+
if (version2 === SCHEMA_VERSION2) return current;
|
|
7172
|
+
const migration = MIGRATIONS[version2];
|
|
7173
|
+
if (migration === void 0) return null;
|
|
7174
|
+
current = migration(current);
|
|
7175
|
+
}
|
|
7176
|
+
return null;
|
|
7177
|
+
}
|
|
7178
|
+
function migrate(raw) {
|
|
7179
|
+
try {
|
|
7180
|
+
return read(raw);
|
|
7181
|
+
} catch {
|
|
7182
|
+
return null;
|
|
7183
|
+
}
|
|
7184
|
+
}
|
|
7185
|
+
function read(raw) {
|
|
7186
|
+
const upgraded = upgrade(raw);
|
|
7187
|
+
if (!isRecord2(upgraded)) return null;
|
|
7188
|
+
const ok = hasOnlyKeys2(upgraded, DOC_KEYS) && typeof upgraded["id"] === "string" && upgraded["schemaVersion"] === SCHEMA_VERSION2 && typeof upgraded["title"] === "string" && typeof upgraded["ownerId"] === "string" && isStringOrNull2(upgraded["folderId"]) && isSeq(upgraded["version"]) && everyEntry(upgraded["nodes"], isValidNode2) && everyEntry(upgraded["edges"], isValidEdge2) && everyEntry(upgraded["results"], isValidResult) && everyEntry(upgraded["nodeHistory"], (_key, entry) => isValidHistory(entry)) && isFiniteNumber3(upgraded["createdAt"]) && isFiniteNumber3(upgraded["updatedAt"]) && isValidMeta(upgraded["meta"]);
|
|
7189
|
+
if (!ok) return null;
|
|
7190
|
+
if (isRecord2(upgraded["meta"]) && Object.keys(upgraded["meta"]).length === 0) {
|
|
7191
|
+
delete upgraded["meta"];
|
|
7192
|
+
}
|
|
7193
|
+
normalizeHistory(upgraded["nodeHistory"]);
|
|
7194
|
+
return upgraded;
|
|
7195
|
+
}
|
|
7196
|
+
function propValue(value) {
|
|
7197
|
+
return { kind: "value", value };
|
|
7198
|
+
}
|
|
7199
|
+
function unsetPropValue() {
|
|
7200
|
+
return { kind: "unset" };
|
|
7201
|
+
}
|
|
7202
|
+
function isJson22(root) {
|
|
7203
|
+
const pending = [{ visit: root }];
|
|
7204
|
+
const open3 = /* @__PURE__ */ new Set();
|
|
7205
|
+
for (let step2 = pending.pop(); step2 !== void 0; step2 = pending.pop()) {
|
|
7206
|
+
if ("close" in step2) {
|
|
7207
|
+
open3.delete(step2.close);
|
|
7208
|
+
continue;
|
|
7209
|
+
}
|
|
7210
|
+
const value = step2.visit;
|
|
7211
|
+
if (value === null) continue;
|
|
7212
|
+
const kind = typeof value;
|
|
7213
|
+
if (kind === "boolean" || kind === "string") continue;
|
|
7214
|
+
if (kind === "number") {
|
|
7215
|
+
if (!Number.isFinite(value)) return false;
|
|
7216
|
+
continue;
|
|
7217
|
+
}
|
|
7218
|
+
if (kind !== "object") return false;
|
|
7219
|
+
const node = value;
|
|
7220
|
+
if (open3.has(node)) return false;
|
|
7221
|
+
open3.add(node);
|
|
7222
|
+
pending.push({ close: node });
|
|
7223
|
+
const children = Array.isArray(node) ? node : Object.values(node);
|
|
7224
|
+
for (const item of children) pending.push({ visit: item });
|
|
7225
|
+
}
|
|
7226
|
+
return true;
|
|
7227
|
+
}
|
|
7228
|
+
function isPropValue(candidate) {
|
|
7229
|
+
if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) return false;
|
|
7230
|
+
const record2 = candidate;
|
|
7231
|
+
const keys = Object.keys(record2);
|
|
7232
|
+
if (record2["kind"] === "unset") return keys.length === 1;
|
|
7233
|
+
if (record2["kind"] !== "value") return false;
|
|
7234
|
+
if (keys.length !== 2 || !Object.hasOwn(record2, "value")) return false;
|
|
7235
|
+
return isJson22(record2["value"]);
|
|
7236
|
+
}
|
|
7237
|
+
var FORBIDDEN_PATH_SEGMENTS = ["__proto__", "constructor", "prototype"];
|
|
7238
|
+
var InvalidPathError = class extends Error {
|
|
7239
|
+
/** O caminho recusado, já como veio da operação. */
|
|
7240
|
+
path;
|
|
7241
|
+
constructor(path, reason) {
|
|
7242
|
+
super(`Caminho inv\xE1lido em node.set: ${JSON.stringify(path)} \u2014 ${reason}`);
|
|
7243
|
+
this.name = "InvalidPathError";
|
|
7244
|
+
this.path = path;
|
|
7245
|
+
}
|
|
7246
|
+
};
|
|
7247
|
+
function asRecord(value) {
|
|
7248
|
+
return value;
|
|
7249
|
+
}
|
|
7250
|
+
function isPlainRecord(value) {
|
|
7251
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7252
|
+
}
|
|
7253
|
+
function parsePath(path) {
|
|
7254
|
+
if (path.length === 0) throw new InvalidPathError(path, "caminho vazio");
|
|
7255
|
+
const segments = path.split(".");
|
|
7256
|
+
for (const segment of segments) {
|
|
7257
|
+
if (segment.length === 0) throw new InvalidPathError(path, "segmento vazio entre pontos");
|
|
7258
|
+
if (FORBIDDEN_PATH_SEGMENTS.includes(segment)) {
|
|
7259
|
+
throw new InvalidPathError(path, `segmento proibido: ${segment}`);
|
|
7260
|
+
}
|
|
7261
|
+
}
|
|
7262
|
+
return segments;
|
|
7263
|
+
}
|
|
7264
|
+
function splitLeaf(path) {
|
|
7265
|
+
const segments = parsePath(path);
|
|
7266
|
+
const leaf = segments[segments.length - 1];
|
|
7267
|
+
if (leaf === void 0) throw new InvalidPathError(path, "caminho sem folha");
|
|
7268
|
+
return { parents: segments.slice(0, -1), leaf };
|
|
7269
|
+
}
|
|
7270
|
+
function getPath(target, path) {
|
|
7271
|
+
const segments = parsePath(path);
|
|
7272
|
+
let cursor = target;
|
|
7273
|
+
for (const segment of segments) {
|
|
7274
|
+
if (!isPlainRecord(cursor) || !Object.hasOwn(cursor, segment)) return void 0;
|
|
7275
|
+
cursor = cursor[segment];
|
|
7276
|
+
}
|
|
7277
|
+
return cursor;
|
|
7278
|
+
}
|
|
7279
|
+
function hasPath(target, path) {
|
|
7280
|
+
const segments = parsePath(path);
|
|
7281
|
+
let cursor = target;
|
|
7282
|
+
for (const segment of segments) {
|
|
7283
|
+
if (!isPlainRecord(cursor) || !Object.hasOwn(cursor, segment)) return false;
|
|
7284
|
+
cursor = cursor[segment];
|
|
7285
|
+
}
|
|
7286
|
+
return true;
|
|
7287
|
+
}
|
|
7288
|
+
function setPath(target, path, value) {
|
|
7289
|
+
const { parents, leaf } = splitLeaf(path);
|
|
7290
|
+
const root = { ...asRecord(target) };
|
|
7291
|
+
let cursor = root;
|
|
7292
|
+
for (const segment of parents) {
|
|
7293
|
+
const current = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
|
|
7294
|
+
if (current === void 0) {
|
|
7295
|
+
const created = {};
|
|
7296
|
+
writeKey(cursor, segment, created);
|
|
7297
|
+
cursor = created;
|
|
7298
|
+
continue;
|
|
7299
|
+
}
|
|
7300
|
+
if (!isPlainRecord(current)) {
|
|
7301
|
+
throw new InvalidPathError(path, `o n\xEDvel ${segment} existe e n\xE3o \xE9 objeto`);
|
|
7302
|
+
}
|
|
7303
|
+
const cloned = { ...current };
|
|
7304
|
+
writeKey(cursor, segment, cloned);
|
|
7305
|
+
cursor = cloned;
|
|
7306
|
+
}
|
|
7307
|
+
writeKey(cursor, leaf, value);
|
|
7308
|
+
return root;
|
|
7309
|
+
}
|
|
7310
|
+
function unsetPath(target, path) {
|
|
7311
|
+
if (!hasPath(target, path)) return target;
|
|
7312
|
+
const { parents, leaf } = splitLeaf(path);
|
|
7313
|
+
const root = { ...asRecord(target) };
|
|
7314
|
+
let cursor = root;
|
|
7315
|
+
for (const segment of parents) {
|
|
7316
|
+
const current = cursor[segment];
|
|
7317
|
+
if (!isPlainRecord(current))
|
|
7318
|
+
throw new InvalidPathError(path, `o n\xEDvel ${segment} n\xE3o \xE9 objeto`);
|
|
7319
|
+
const cloned = { ...current };
|
|
7320
|
+
writeKey(cursor, segment, cloned);
|
|
7321
|
+
cursor = cloned;
|
|
7322
|
+
}
|
|
7323
|
+
delete cursor[leaf];
|
|
7324
|
+
return root;
|
|
7325
|
+
}
|
|
7326
|
+
function writeKey(record2, key, value) {
|
|
7327
|
+
if (key === "__proto__") {
|
|
7328
|
+
Object.defineProperty(record2, key, {
|
|
7329
|
+
value,
|
|
7330
|
+
writable: true,
|
|
7331
|
+
enumerable: true,
|
|
7332
|
+
configurable: true
|
|
7333
|
+
});
|
|
7334
|
+
return;
|
|
7335
|
+
}
|
|
7336
|
+
record2[key] = value;
|
|
7337
|
+
}
|
|
7338
|
+
function createCloneCounts() {
|
|
7339
|
+
return { doc: 0, nodes: 0, edges: 0, results: 0, nodeHistory: 0, nodeEntry: 0, historyEntry: 0 };
|
|
7340
|
+
}
|
|
7341
|
+
var Draft = class {
|
|
7342
|
+
base;
|
|
7343
|
+
counts;
|
|
7344
|
+
nodes;
|
|
7345
|
+
edges;
|
|
7346
|
+
results;
|
|
7347
|
+
nodeHistory;
|
|
7348
|
+
nodesOwned = false;
|
|
7349
|
+
edgesOwned = false;
|
|
7350
|
+
resultsOwned = false;
|
|
7351
|
+
nodeHistoryOwned = false;
|
|
7352
|
+
changed = /* @__PURE__ */ new Set();
|
|
7353
|
+
/** Título e metadado do board (`board.set`). Só entram no documento novo se foram escritos. */
|
|
7354
|
+
title;
|
|
7355
|
+
titleChanged = false;
|
|
7356
|
+
boardMeta;
|
|
7357
|
+
metaOwned = false;
|
|
7358
|
+
constructor(base, counts) {
|
|
7359
|
+
this.base = base;
|
|
7360
|
+
this.counts = counts;
|
|
7361
|
+
this.nodes = base.nodes;
|
|
7362
|
+
this.edges = base.edges;
|
|
7363
|
+
this.results = base.results;
|
|
7364
|
+
this.nodeHistory = base.nodeHistory;
|
|
7365
|
+
this.title = base.title;
|
|
7366
|
+
this.boardMeta = base.meta;
|
|
7367
|
+
}
|
|
7368
|
+
// ------------------------------------------------------------------- leitura
|
|
7369
|
+
node(id) {
|
|
7370
|
+
return Object.hasOwn(this.nodes, id) ? this.nodes[id] : void 0;
|
|
7371
|
+
}
|
|
7372
|
+
edge(id) {
|
|
7373
|
+
return Object.hasOwn(this.edges, id) ? this.edges[id] : void 0;
|
|
7374
|
+
}
|
|
7375
|
+
// Não existe leitor de `results` aqui: `result.set` grava sem consultar, e a
|
|
7376
|
+
// inversa dele é nula (story 004). Ler resultado é da fase 2, e o método nasce
|
|
7377
|
+
// no dia em que tiver chamador.
|
|
7378
|
+
history(nodeId3) {
|
|
7379
|
+
return Object.hasOwn(this.nodeHistory, nodeId3) ? this.nodeHistory[nodeId3] : void 0;
|
|
7380
|
+
}
|
|
7381
|
+
/** O título do board como está no rascunho. */
|
|
7382
|
+
boardTitle() {
|
|
7383
|
+
return this.title;
|
|
7384
|
+
}
|
|
7385
|
+
/** O metadado do board como está no rascunho. Ausente: sem metadado. */
|
|
7386
|
+
meta() {
|
|
7387
|
+
return this.boardMeta;
|
|
7388
|
+
}
|
|
7389
|
+
/** Marca o nó como tocado, para o `changedNodeIds` que a projeção lê. */
|
|
7390
|
+
touch(nodeId3) {
|
|
7391
|
+
this.changed.add(nodeId3);
|
|
7392
|
+
}
|
|
7393
|
+
// ------------------------------------------------------------------- escrita
|
|
7394
|
+
putNode(id, node) {
|
|
7395
|
+
this.ownNodes();
|
|
7396
|
+
writeKey(this.nodes, id, node);
|
|
7397
|
+
this.changed.add(id);
|
|
7398
|
+
}
|
|
7399
|
+
/**
|
|
7400
|
+
* Apaga o nó e, junto, a chave de histórico dele que já era lista vazia.
|
|
7401
|
+
*
|
|
7402
|
+
* Apagar a chave não é limpeza de referência, é normalização: lista vazia não
|
|
7403
|
+
* existe na forma canônica, chave ausente é que significa "sem variação"
|
|
7404
|
+
* (`dev/PLANO-FASE-0.md` §4). Descartar `[]` não perde informação nenhuma, e
|
|
7405
|
+
* por isso a inversa `node.add` devolve um documento equivalente sem precisar
|
|
7406
|
+
* recriar a chave. Chave com item continua intocada: aí sim existe informação,
|
|
7407
|
+
* e `node.remove` nunca limpa sozinho nada que carregue informação. Quem tira
|
|
7408
|
+
* as variações de um nó que vai embora é o `batch` de `removeNode`.
|
|
7409
|
+
*
|
|
7410
|
+
* Nó ausente sai antes de qualquer cópia, senão um `node.remove` que o CA8
|
|
7411
|
+
* declara no-op sujaria o rascunho e produziria documento novo por nada.
|
|
7412
|
+
*/
|
|
7413
|
+
dropNode(id) {
|
|
7414
|
+
if (!Object.hasOwn(this.nodes, id)) return;
|
|
7415
|
+
this.ownNodes();
|
|
7416
|
+
delete this.nodes[id];
|
|
7417
|
+
this.changed.add(id);
|
|
7418
|
+
this.discardEmptyHistory(id);
|
|
7419
|
+
}
|
|
7420
|
+
discardEmptyHistory(nodeId3) {
|
|
7421
|
+
const current = this.history(nodeId3);
|
|
7422
|
+
if (current === void 0 || current.length > 0) return;
|
|
7423
|
+
this.ownNodeHistory();
|
|
7424
|
+
delete this.nodeHistory[nodeId3];
|
|
7425
|
+
}
|
|
7426
|
+
/**
|
|
7427
|
+
* Troca um nó pelo resultado de uma escrita por caminho.
|
|
7428
|
+
*
|
|
7429
|
+
* A função recebe o nó e devolve o nó novo, ou o mesmo quando não há o que
|
|
7430
|
+
* mudar. Devolvendo o mesmo, nada é escrito e nenhuma coleção é clonada: é
|
|
7431
|
+
* assim que `node.set` sem efeito sai de graça.
|
|
7432
|
+
*/
|
|
7433
|
+
mutateNode(id, change) {
|
|
7434
|
+
const current = this.node(id);
|
|
7435
|
+
if (current === void 0) return;
|
|
7436
|
+
const next = change(current);
|
|
7437
|
+
if (next === current) return;
|
|
7438
|
+
if (this.counts !== void 0) this.counts.nodeEntry += 1;
|
|
7439
|
+
this.putNode(id, next);
|
|
7440
|
+
}
|
|
7441
|
+
putEdge(id, edge) {
|
|
7442
|
+
this.ownEdges();
|
|
7443
|
+
writeKey(this.edges, id, edge);
|
|
7444
|
+
}
|
|
7445
|
+
dropEdge(id) {
|
|
7446
|
+
if (!Object.hasOwn(this.edges, id)) return;
|
|
7447
|
+
this.ownEdges();
|
|
7448
|
+
delete this.edges[id];
|
|
7449
|
+
}
|
|
7450
|
+
putResult(id, entry) {
|
|
7451
|
+
this.ownResults();
|
|
7452
|
+
writeKey(this.results, id, entry);
|
|
7453
|
+
}
|
|
7454
|
+
/**
|
|
7455
|
+
* Acrescenta uma variação ao histórico do nó, no fim da lista.
|
|
7456
|
+
*
|
|
7457
|
+
* A lista nasce na primeira chamada. Id repetido entra de novo, de propósito:
|
|
7458
|
+
* `history.remove` tira a última ocorrência, então append seguido de remove
|
|
7459
|
+
* devolve a lista exatamente como estava, que é o que a inversa da story 004
|
|
7460
|
+
* precisa.
|
|
7461
|
+
*/
|
|
7462
|
+
appendHistory(nodeId3, resultId) {
|
|
7463
|
+
const current = this.history(nodeId3);
|
|
7464
|
+
const next = current === void 0 ? [] : [...current];
|
|
7465
|
+
if (current !== void 0 && this.counts !== void 0) this.counts.historyEntry += 1;
|
|
7466
|
+
next.push(resultId);
|
|
7467
|
+
this.ownNodeHistory();
|
|
7468
|
+
writeKey(this.nodeHistory, nodeId3, next);
|
|
7469
|
+
this.changed.add(nodeId3);
|
|
7470
|
+
}
|
|
7471
|
+
/**
|
|
7472
|
+
* Tira a última ocorrência da variação no histórico do nó.
|
|
7473
|
+
*
|
|
7474
|
+
* Id ausente é no-op. Lista que fica vazia some junto com a chave: histórico
|
|
7475
|
+
* vazio pendurado em nó que vai ser apagado é exatamente a referência órfã que
|
|
7476
|
+
* o §4 do plano proíbe, e é o que o CA9 cobra depois de `removeNode`.
|
|
7477
|
+
*/
|
|
7478
|
+
removeHistory(nodeId3, resultId) {
|
|
7479
|
+
const current = this.history(nodeId3);
|
|
7480
|
+
if (current === void 0) return;
|
|
7481
|
+
const at = current.lastIndexOf(resultId);
|
|
7482
|
+
if (at === -1) return;
|
|
7483
|
+
if (this.counts !== void 0) this.counts.historyEntry += 1;
|
|
7484
|
+
const next = [...current.slice(0, at), ...current.slice(at + 1)];
|
|
7485
|
+
this.ownNodeHistory();
|
|
7486
|
+
if (next.length === 0) {
|
|
7487
|
+
delete this.nodeHistory[nodeId3];
|
|
7488
|
+
} else {
|
|
7489
|
+
writeKey(this.nodeHistory, nodeId3, next);
|
|
7490
|
+
}
|
|
7491
|
+
this.changed.add(nodeId3);
|
|
7492
|
+
}
|
|
7493
|
+
/** Troca o título. Título igual sai de graça, sem documento novo. */
|
|
7494
|
+
setTitle(title) {
|
|
7495
|
+
if (title === this.title) return;
|
|
7496
|
+
this.title = title;
|
|
7497
|
+
this.titleChanged = true;
|
|
7498
|
+
}
|
|
7499
|
+
/**
|
|
7500
|
+
* Troca o metadado inteiro do board pela versão que `change` devolve.
|
|
7501
|
+
*
|
|
7502
|
+
* Metadado vazio vira ausente: `{}` não existe na forma canônica, pela mesma
|
|
7503
|
+
* razão da lista vazia de `nodeHistory`. Sem isso, gravar e desfazer a dica
|
|
7504
|
+
* num board sem metadado devolveria um documento com `meta: {}` a mais.
|
|
7505
|
+
*/
|
|
7506
|
+
mutateMeta(change) {
|
|
7507
|
+
const current = this.boardMeta ?? {};
|
|
7508
|
+
const next = change(current);
|
|
7509
|
+
if (next === current) return;
|
|
7510
|
+
this.boardMeta = Object.keys(next).length === 0 ? void 0 : next;
|
|
7511
|
+
this.metaOwned = true;
|
|
7512
|
+
}
|
|
7513
|
+
// --------------------------------------------------------- cópia por escrita
|
|
7514
|
+
ownNodes() {
|
|
7515
|
+
if (this.nodesOwned) return;
|
|
7516
|
+
this.nodes = { ...this.base.nodes };
|
|
7517
|
+
this.nodesOwned = true;
|
|
7518
|
+
if (this.counts !== void 0) this.counts.nodes += 1;
|
|
7519
|
+
}
|
|
7520
|
+
ownEdges() {
|
|
7521
|
+
if (this.edgesOwned) return;
|
|
7522
|
+
this.edges = { ...this.base.edges };
|
|
7523
|
+
this.edgesOwned = true;
|
|
7524
|
+
if (this.counts !== void 0) this.counts.edges += 1;
|
|
7525
|
+
}
|
|
7526
|
+
ownResults() {
|
|
7527
|
+
if (this.resultsOwned) return;
|
|
7528
|
+
this.results = { ...this.base.results };
|
|
7529
|
+
this.resultsOwned = true;
|
|
7530
|
+
if (this.counts !== void 0) this.counts.results += 1;
|
|
7531
|
+
}
|
|
7532
|
+
ownNodeHistory() {
|
|
7533
|
+
if (this.nodeHistoryOwned) return;
|
|
7534
|
+
this.nodeHistory = { ...this.base.nodeHistory };
|
|
7535
|
+
this.nodeHistoryOwned = true;
|
|
7536
|
+
if (this.counts !== void 0) this.counts.nodeHistory += 1;
|
|
7537
|
+
}
|
|
7538
|
+
// ---------------------------------------------------------------- fechamento
|
|
7539
|
+
/** Alguma coleção foi escrita? Lote de no-ops não produz documento novo. */
|
|
7540
|
+
get dirty() {
|
|
7541
|
+
return this.nodesOwned || this.edgesOwned || this.resultsOwned || this.nodeHistoryOwned || this.titleChanged || this.metaOwned;
|
|
7542
|
+
}
|
|
7543
|
+
/**
|
|
7544
|
+
* Fecha o rascunho.
|
|
7545
|
+
*
|
|
7546
|
+
* Sem escrita, devolve a própria referência de entrada: o lote inteiro de
|
|
7547
|
+
* no-ops não gera documento novo e a tela não re-renderiza por nada.
|
|
7548
|
+
*
|
|
7549
|
+
* O documento sai sem `Object.freeze`, desvio do plano §4 ("congela e
|
|
7550
|
+
* devolve"), e a razão é custo e alcance. Congelamento fundo percorre o
|
|
7551
|
+
* documento inteiro a cada lote e joga fora justamente o ganho da cópia por
|
|
7552
|
+
* escrita. Congelamento raso protegeria só o objeto de topo, enquanto
|
|
7553
|
+
* `nodes`, `edges`, `results` e `nodeHistory` continuariam mutáveis, e compra
|
|
7554
|
+
* quase nada. Escrever `version` depois não é argumento contra congelar:
|
|
7555
|
+
* spread funciona sobre objeto congelado, e é o que `reduce` já faz. A
|
|
7556
|
+
* garantia de imutabilidade da entrada é estrutural e tem teste.
|
|
7557
|
+
*/
|
|
7558
|
+
finish() {
|
|
7559
|
+
const changedNodeIds = [...this.changed];
|
|
7560
|
+
if (!this.dirty) return { doc: this.base, changedNodeIds };
|
|
7561
|
+
if (this.counts !== void 0) this.counts.doc += 1;
|
|
7562
|
+
const doc = {
|
|
7563
|
+
...this.base,
|
|
7564
|
+
nodes: this.nodes,
|
|
7565
|
+
edges: this.edges,
|
|
7566
|
+
results: this.results,
|
|
7567
|
+
nodeHistory: this.nodeHistory
|
|
7568
|
+
};
|
|
7569
|
+
if (this.titleChanged) doc.title = this.title;
|
|
7570
|
+
if (this.metaOwned) {
|
|
7571
|
+
if (this.boardMeta === void 0) delete doc.meta;
|
|
7572
|
+
else doc.meta = this.boardMeta;
|
|
7573
|
+
}
|
|
7574
|
+
return { doc, changedNodeIds };
|
|
7575
|
+
}
|
|
7576
|
+
};
|
|
7577
|
+
function nodeOf(doc, id) {
|
|
7578
|
+
return Object.hasOwn(doc.nodes, id) ? doc.nodes[id] : void 0;
|
|
7579
|
+
}
|
|
7580
|
+
function edgeOf(doc, id) {
|
|
7581
|
+
return Object.hasOwn(doc.edges, id) ? doc.edges[id] : void 0;
|
|
7582
|
+
}
|
|
7583
|
+
function historyOf(doc, nodeId3) {
|
|
7584
|
+
return Object.hasOwn(doc.nodeHistory, nodeId3) ? doc.nodeHistory[nodeId3] : void 0;
|
|
7585
|
+
}
|
|
7586
|
+
function previousValue(node, path) {
|
|
7587
|
+
return getPath(node, path);
|
|
7588
|
+
}
|
|
7589
|
+
function shallowestMissingPath(target, path) {
|
|
7590
|
+
const walked = [];
|
|
7591
|
+
for (const segment of parsePath(path)) {
|
|
7592
|
+
walked.push(segment);
|
|
7593
|
+
const prefix = walked.join(".");
|
|
7594
|
+
if (!hasPath(target, prefix)) return prefix;
|
|
7595
|
+
}
|
|
7596
|
+
return path;
|
|
7597
|
+
}
|
|
7598
|
+
function invertNodeAdd(doc, op) {
|
|
7599
|
+
const previous = nodeOf(doc, op.nodeId);
|
|
7600
|
+
if (previous === void 0) return { type: "node.remove", nodeId: op.nodeId };
|
|
7601
|
+
return { type: "node.add", nodeId: op.nodeId, node: previous };
|
|
7602
|
+
}
|
|
7603
|
+
function invertNodeRemove(doc, op) {
|
|
7604
|
+
const current = nodeOf(doc, op.nodeId);
|
|
7605
|
+
if (current === void 0) return { type: "node.remove", nodeId: op.nodeId };
|
|
7606
|
+
return { type: "node.add", nodeId: op.nodeId, node: current };
|
|
7607
|
+
}
|
|
7608
|
+
function invertNodeSet(doc, op) {
|
|
7609
|
+
const node = nodeOf(doc, op.nodeId);
|
|
7610
|
+
if (node === void 0) {
|
|
7611
|
+
return { type: "node.set", nodeId: op.nodeId, path: op.path, value: unsetPropValue() };
|
|
7612
|
+
}
|
|
7613
|
+
if (hasPath(node, op.path)) {
|
|
7614
|
+
return {
|
|
7615
|
+
type: "node.set",
|
|
7616
|
+
nodeId: op.nodeId,
|
|
7617
|
+
path: op.path,
|
|
7618
|
+
value: propValue(previousValue(node, op.path))
|
|
7619
|
+
};
|
|
7620
|
+
}
|
|
7621
|
+
return {
|
|
7622
|
+
type: "node.set",
|
|
7623
|
+
nodeId: op.nodeId,
|
|
7624
|
+
path: shallowestMissingPath(node, op.path),
|
|
7625
|
+
value: unsetPropValue()
|
|
7626
|
+
};
|
|
7627
|
+
}
|
|
7628
|
+
function invertEdgeAdd(doc, op) {
|
|
7629
|
+
const previous = edgeOf(doc, op.edgeId);
|
|
7630
|
+
if (previous === void 0) return { type: "edge.remove", edgeId: op.edgeId };
|
|
7631
|
+
return { type: "edge.add", edgeId: op.edgeId, edge: previous };
|
|
7632
|
+
}
|
|
7633
|
+
function invertEdgeRemove(doc, op) {
|
|
7634
|
+
const current = edgeOf(doc, op.edgeId);
|
|
7635
|
+
if (current === void 0) return { type: "edge.remove", edgeId: op.edgeId };
|
|
7636
|
+
return { type: "edge.add", edgeId: op.edgeId, edge: current };
|
|
7637
|
+
}
|
|
7638
|
+
function invertResultSet() {
|
|
7639
|
+
return null;
|
|
7640
|
+
}
|
|
7641
|
+
function invertHistoryAppend(op) {
|
|
7642
|
+
return { type: "history.remove", nodeId: op.nodeId, resultId: op.resultId };
|
|
7643
|
+
}
|
|
7644
|
+
function invertHistoryRemove(doc, op) {
|
|
7645
|
+
const list = historyOf(doc, op.nodeId);
|
|
7646
|
+
const at = list === void 0 ? -1 : list.lastIndexOf(op.resultId);
|
|
7647
|
+
if (list === void 0 || at === -1) {
|
|
7648
|
+
return { type: "history.remove", nodeId: op.nodeId, resultId: op.resultId };
|
|
7649
|
+
}
|
|
7650
|
+
if (at === list.length - 1) {
|
|
7651
|
+
return { type: "history.append", nodeId: op.nodeId, resultId: op.resultId };
|
|
7652
|
+
}
|
|
7653
|
+
const tail = list.slice(at + 1);
|
|
7654
|
+
const ops = [];
|
|
7655
|
+
for (const resultId of [...tail].reverse()) {
|
|
7656
|
+
ops.push({ type: "history.remove", nodeId: op.nodeId, resultId });
|
|
7657
|
+
}
|
|
7658
|
+
ops.push({ type: "history.append", nodeId: op.nodeId, resultId: op.resultId });
|
|
7659
|
+
for (const resultId of tail) {
|
|
7660
|
+
ops.push({ type: "history.append", nodeId: op.nodeId, resultId });
|
|
7661
|
+
}
|
|
7662
|
+
return { type: "batch", ops };
|
|
7663
|
+
}
|
|
7664
|
+
var BOARD_FIELDS = ["title", "guide", "ialab", "assetUrls"];
|
|
7665
|
+
var InvalidBoardSetError = class extends Error {
|
|
7666
|
+
field;
|
|
7667
|
+
constructor(field, reason) {
|
|
7668
|
+
super(`board.set inv\xE1lido em ${JSON.stringify(field)}: ${reason}`);
|
|
7669
|
+
this.name = "InvalidBoardSetError";
|
|
7670
|
+
this.field = field;
|
|
7671
|
+
}
|
|
7672
|
+
};
|
|
7673
|
+
function isPlainRecord2(value) {
|
|
7674
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7675
|
+
}
|
|
7676
|
+
function isStringMap2(value) {
|
|
7677
|
+
return isPlainRecord2(value) && Object.values(value).every((item) => typeof item === "string");
|
|
7678
|
+
}
|
|
7679
|
+
function assertBoardSet(op) {
|
|
7680
|
+
const { field, key, value } = op;
|
|
7681
|
+
if (!BOARD_FIELDS.includes(field)) throw new InvalidBoardSetError(field, "campo desconhecido");
|
|
7682
|
+
if (key !== void 0) {
|
|
7683
|
+
if (field !== "assetUrls") throw new InvalidBoardSetError(field, "s\xF3 assetUrls aceita key");
|
|
7684
|
+
if (key === "" || FORBIDDEN_PATH_SEGMENTS.includes(key)) {
|
|
7685
|
+
throw new InvalidBoardSetError(field, `key recusada: ${JSON.stringify(key)}`);
|
|
7686
|
+
}
|
|
7687
|
+
}
|
|
7688
|
+
if (value.kind === "unset") {
|
|
7689
|
+
if (field === "title") throw new InvalidBoardSetError(field, "t\xEDtulo n\xE3o pode ser apagado");
|
|
7690
|
+
return;
|
|
7691
|
+
}
|
|
7692
|
+
const raw = value.value;
|
|
7693
|
+
const ok = field === "title" ? typeof raw === "string" : field === "guide" ? raw === null || typeof raw === "string" : field === "ialab" ? raw === null || isPlainRecord2(raw) : key === void 0 ? isStringMap2(raw) : typeof raw === "string";
|
|
7694
|
+
if (!ok) throw new InvalidBoardSetError(field, "valor com tipo errado");
|
|
7695
|
+
}
|
|
7696
|
+
function applyBoardSet(draft, op) {
|
|
7697
|
+
assertBoardSet(op);
|
|
7698
|
+
const { field, key, value } = op;
|
|
7699
|
+
if (field === "title") {
|
|
7700
|
+
if (value.kind === "value" && typeof value.value === "string") draft.setTitle(value.value);
|
|
7701
|
+
return;
|
|
7702
|
+
}
|
|
7703
|
+
draft.mutateMeta((meta) => {
|
|
7704
|
+
if (field === "assetUrls" && key !== void 0) return withAssetUrl(meta, key, value);
|
|
7705
|
+
return withField(meta, field, value);
|
|
7706
|
+
});
|
|
7707
|
+
}
|
|
7708
|
+
function withField(meta, field, value) {
|
|
7709
|
+
if (value.kind === "unset") {
|
|
7710
|
+
if (!Object.hasOwn(meta, field)) return meta;
|
|
7711
|
+
const next2 = { ...meta };
|
|
7712
|
+
delete next2[field];
|
|
7713
|
+
return next2;
|
|
7714
|
+
}
|
|
7715
|
+
const current = Object.hasOwn(meta, field) ? meta[field] : void 0;
|
|
7716
|
+
if (current === value.value && (value.value === null || typeof value.value === "string")) {
|
|
7717
|
+
return meta;
|
|
7718
|
+
}
|
|
7719
|
+
const next = { ...meta };
|
|
7720
|
+
writeKey(next, field, value.value);
|
|
7721
|
+
return next;
|
|
7722
|
+
}
|
|
7723
|
+
function withAssetUrl(meta, key, value) {
|
|
7724
|
+
const urls = meta.assetUrls;
|
|
7725
|
+
if (value.kind === "unset") {
|
|
7726
|
+
if (urls === void 0 || !Object.hasOwn(urls, key)) return meta;
|
|
7727
|
+
const nextUrls2 = { ...urls };
|
|
7728
|
+
delete nextUrls2[key];
|
|
7729
|
+
return { ...meta, assetUrls: nextUrls2 };
|
|
7730
|
+
}
|
|
7731
|
+
const url = value.value;
|
|
7732
|
+
if (urls !== void 0 && Object.hasOwn(urls, key) && urls[key] === url) return meta;
|
|
7733
|
+
const nextUrls = { ...urls };
|
|
7734
|
+
writeKey(nextUrls, key, url);
|
|
7735
|
+
return { ...meta, assetUrls: nextUrls };
|
|
7736
|
+
}
|
|
7737
|
+
function invertBoardSet(doc, op) {
|
|
7738
|
+
const { field, key } = op;
|
|
7739
|
+
if (field === "title") return { type: "board.set", field, value: propValue(doc.title) };
|
|
7740
|
+
const meta = doc.meta ?? {};
|
|
7741
|
+
if (field === "assetUrls" && key !== void 0) {
|
|
7742
|
+
const urls = meta.assetUrls;
|
|
7743
|
+
if (urls === void 0) return { type: "board.set", field, value: unsetPropValue() };
|
|
7744
|
+
return Object.hasOwn(urls, key) ? { type: "board.set", field, key, value: propValue(urls[key]) } : { type: "board.set", field, key, value: unsetPropValue() };
|
|
7745
|
+
}
|
|
7746
|
+
if (!Object.hasOwn(meta, field)) return { type: "board.set", field, value: unsetPropValue() };
|
|
7747
|
+
return { type: "board.set", field, value: propValue(meta[field]) };
|
|
7748
|
+
}
|
|
7749
|
+
function touchEdgeEnds(draft, source, target) {
|
|
7750
|
+
draft.touch(source);
|
|
7751
|
+
draft.touch(target);
|
|
7752
|
+
}
|
|
7753
|
+
var OPS2 = {
|
|
7754
|
+
"node.add": {
|
|
7755
|
+
apply(draft, op) {
|
|
7756
|
+
draft.putNode(op.nodeId, op.node);
|
|
7757
|
+
},
|
|
7758
|
+
invert: invertNodeAdd
|
|
7759
|
+
},
|
|
7760
|
+
"node.remove": {
|
|
7761
|
+
apply(draft, op) {
|
|
7762
|
+
draft.dropNode(op.nodeId);
|
|
7763
|
+
},
|
|
7764
|
+
invert: invertNodeRemove
|
|
7765
|
+
},
|
|
7766
|
+
"node.set": {
|
|
7767
|
+
apply(draft, op) {
|
|
7768
|
+
draft.mutateNode(
|
|
7769
|
+
op.nodeId,
|
|
7770
|
+
(node) => op.value.kind === "value" ? setPath(node, op.path, op.value.value) : unsetPath(node, op.path)
|
|
7771
|
+
);
|
|
7772
|
+
},
|
|
7773
|
+
invert: invertNodeSet
|
|
7774
|
+
},
|
|
7775
|
+
"edge.add": {
|
|
7776
|
+
apply(draft, op) {
|
|
7777
|
+
draft.putEdge(op.edgeId, op.edge);
|
|
7778
|
+
touchEdgeEnds(draft, op.edge.source, op.edge.target);
|
|
7779
|
+
},
|
|
7780
|
+
invert: invertEdgeAdd
|
|
7781
|
+
},
|
|
7782
|
+
"edge.remove": {
|
|
7783
|
+
apply(draft, op) {
|
|
7784
|
+
const current = draft.edge(op.edgeId);
|
|
7785
|
+
if (current === void 0) return;
|
|
7786
|
+
draft.dropEdge(op.edgeId);
|
|
7787
|
+
touchEdgeEnds(draft, current.source, current.target);
|
|
7788
|
+
},
|
|
7789
|
+
invert: invertEdgeRemove
|
|
7790
|
+
},
|
|
7791
|
+
"result.set": {
|
|
7792
|
+
apply(draft, op) {
|
|
7793
|
+
draft.putResult(op.resultId, op.entry);
|
|
7794
|
+
draft.touch(op.entry.nodeId);
|
|
7795
|
+
},
|
|
7796
|
+
invert: invertResultSet
|
|
7797
|
+
},
|
|
7798
|
+
"history.append": {
|
|
7799
|
+
apply(draft, op) {
|
|
7800
|
+
draft.appendHistory(op.nodeId, op.resultId);
|
|
7801
|
+
},
|
|
7802
|
+
invert: (_doc, op) => invertHistoryAppend(op)
|
|
7803
|
+
},
|
|
7804
|
+
"history.remove": {
|
|
7805
|
+
apply(draft, op) {
|
|
7806
|
+
draft.removeHistory(op.nodeId, op.resultId);
|
|
7807
|
+
},
|
|
7808
|
+
invert: invertHistoryRemove
|
|
7809
|
+
},
|
|
7810
|
+
"board.set": {
|
|
7811
|
+
apply: applyBoardSet,
|
|
7812
|
+
invert: invertBoardSet
|
|
7813
|
+
},
|
|
7814
|
+
batch: {
|
|
7815
|
+
apply(draft, op) {
|
|
7816
|
+
for (const inner of op.ops) applyOp(draft, inner);
|
|
7817
|
+
},
|
|
7818
|
+
/**
|
|
7819
|
+
* As inversas dos membros, em ordem reversa.
|
|
7820
|
+
*
|
|
7821
|
+
* O estado avança membro a membro, e não dá para fugir disso: inverter dois
|
|
7822
|
+
* `history.remove` seguidos contra o MESMO documento de entrada devolveria
|
|
7823
|
+
* dois `history.append` iguais, e a lista voltaria com um item a mais do que
|
|
7824
|
+
* tinha. Quem avança é `walkBatch`, com um rascunho de rascunho que nunca
|
|
7825
|
+
* toca o documento de quem chamou.
|
|
7826
|
+
*/
|
|
7827
|
+
invert(doc, op) {
|
|
7828
|
+
const parts = walkBatch(doc, op.ops, invert);
|
|
7829
|
+
return { type: "batch", ops: parts.reverse() };
|
|
7830
|
+
}
|
|
7831
|
+
}
|
|
7832
|
+
};
|
|
7833
|
+
function applyOp(draft, op) {
|
|
7834
|
+
const handler = OPS2[op.type];
|
|
7835
|
+
handler.apply(draft, op);
|
|
7836
|
+
}
|
|
7837
|
+
function invert(doc, op) {
|
|
7838
|
+
const handler = OPS2[op.type];
|
|
7839
|
+
return handler.invert(doc, op);
|
|
7840
|
+
}
|
|
7841
|
+
function walkBatch(doc, ops, visit) {
|
|
7842
|
+
const scratch = new Draft(doc);
|
|
7843
|
+
const collected = [];
|
|
7844
|
+
for (const op of ops) {
|
|
7845
|
+
const item = visit(scratch.finish().doc, op);
|
|
7846
|
+
if (item !== null) collected.push(item);
|
|
7847
|
+
applyOp(scratch, op);
|
|
7848
|
+
}
|
|
7849
|
+
return collected;
|
|
7850
|
+
}
|
|
7851
|
+
var MAX_OP_BYTES2 = 64 * 1024;
|
|
7852
|
+
var OpTooLargeError2 = class extends Error {
|
|
7853
|
+
/** O envelope recusado, para o `onError` da story 005 citar na mensagem. */
|
|
7854
|
+
opId;
|
|
7855
|
+
/** Quanto ele pesa, serializado em UTF-8. */
|
|
7856
|
+
bytes;
|
|
7857
|
+
/** Quanto cabia. */
|
|
7858
|
+
limit;
|
|
7859
|
+
constructor(opId, bytes, limit = MAX_OP_BYTES2) {
|
|
7860
|
+
super(`Opera\xE7\xE3o ${opId} tem ${bytes} bytes e o teto \xE9 ${limit}`);
|
|
7861
|
+
this.name = "OpTooLargeError";
|
|
7862
|
+
this.opId = opId;
|
|
7863
|
+
this.bytes = bytes;
|
|
7864
|
+
this.limit = limit;
|
|
7865
|
+
}
|
|
7866
|
+
};
|
|
7867
|
+
function utf8ByteLength(text) {
|
|
7868
|
+
let bytes = 0;
|
|
7869
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
7870
|
+
const code = text.charCodeAt(i);
|
|
7871
|
+
if (code < 128) {
|
|
7872
|
+
bytes += 1;
|
|
7873
|
+
} else if (code < 2048) {
|
|
7874
|
+
bytes += 2;
|
|
7875
|
+
} else if (code >= 55296 && code <= 56319 && i + 1 < text.length) {
|
|
7876
|
+
const next = text.charCodeAt(i + 1);
|
|
7877
|
+
if (next >= 56320 && next <= 57343) {
|
|
7878
|
+
bytes += 4;
|
|
7879
|
+
i += 1;
|
|
7880
|
+
} else {
|
|
7881
|
+
bytes += 3;
|
|
7882
|
+
}
|
|
7883
|
+
} else {
|
|
7884
|
+
bytes += 3;
|
|
7885
|
+
}
|
|
7886
|
+
}
|
|
7887
|
+
return bytes;
|
|
7888
|
+
}
|
|
7889
|
+
function opEnvelopeBytes(envelope2) {
|
|
7890
|
+
return utf8ByteLength(JSON.stringify(envelope2));
|
|
7891
|
+
}
|
|
7892
|
+
function assertOpEnvelopeFits(envelope2, limit = MAX_OP_BYTES2) {
|
|
7893
|
+
const bytes = opEnvelopeBytes(envelope2);
|
|
7894
|
+
if (bytes > limit) throw new OpTooLargeError2(envelope2.id, bytes, limit);
|
|
7895
|
+
}
|
|
7896
|
+
function applyOps(doc, ops, options = {}) {
|
|
7897
|
+
const draft = new Draft(doc, options.counts);
|
|
7898
|
+
for (const op of ops) applyOp(draft, op);
|
|
7899
|
+
return draft.finish();
|
|
7900
|
+
}
|
|
7901
|
+
function applyEnvelopes(doc, envelopes, options = {}) {
|
|
7902
|
+
for (const envelope2 of envelopes) assertOpEnvelopeFits(envelope2);
|
|
7903
|
+
return applyOps(
|
|
7904
|
+
doc,
|
|
7905
|
+
envelopes.map((envelope2) => envelope2.op),
|
|
7906
|
+
options
|
|
7907
|
+
);
|
|
7908
|
+
}
|
|
7909
|
+
function reduce(log, base) {
|
|
7910
|
+
const doc = base ?? emptyBoardFor(log);
|
|
7911
|
+
if (log.length === 0) return doc;
|
|
7912
|
+
let lastSeq = base === void 0 ? -1 : base.version;
|
|
7913
|
+
for (const envelope2 of log) {
|
|
7914
|
+
if (envelope2.seq === null) {
|
|
7915
|
+
throw new Error(
|
|
7916
|
+
`reduce recebeu o envelope ${envelope2.id} sem seq: s\xF3 entra no log o que j\xE1 foi confirmado`
|
|
7917
|
+
);
|
|
7918
|
+
}
|
|
7919
|
+
if (envelope2.seq <= lastSeq) {
|
|
7920
|
+
throw new Error(
|
|
7921
|
+
`reduce recebeu o log fora de ordem: seq ${envelope2.seq} depois de ${lastSeq}`
|
|
7922
|
+
);
|
|
7923
|
+
}
|
|
7924
|
+
lastSeq = envelope2.seq;
|
|
7925
|
+
}
|
|
7926
|
+
const applied = applyOps(
|
|
7927
|
+
doc,
|
|
7928
|
+
log.map((envelope2) => envelope2.op)
|
|
7929
|
+
);
|
|
7930
|
+
return { ...applied.doc, version: lastSeq };
|
|
7931
|
+
}
|
|
7932
|
+
function emptyBoardFor(log) {
|
|
7933
|
+
const first = log[0];
|
|
7934
|
+
if (first === void 0) {
|
|
7935
|
+
throw new Error("reduce sem base precisa de um log com ao menos um envelope");
|
|
7936
|
+
}
|
|
7937
|
+
return createEmptyBoard({ id: first.boardId, now: () => first.ts });
|
|
7938
|
+
}
|
|
7939
|
+
function removeNode(doc, nodeId3) {
|
|
7940
|
+
const ops = [];
|
|
7941
|
+
const edgeIds = Object.keys(doc.edges).filter((edgeId) => {
|
|
7942
|
+
const edge = doc.edges[edgeId];
|
|
7943
|
+
return edge !== void 0 && (edge.source === nodeId3 || edge.target === nodeId3);
|
|
7944
|
+
}).sort();
|
|
7945
|
+
for (const edgeId of edgeIds) ops.push({ type: "edge.remove", edgeId });
|
|
7946
|
+
const history = Object.hasOwn(doc.nodeHistory, nodeId3) ? doc.nodeHistory[nodeId3] : void 0;
|
|
7947
|
+
if (history !== void 0) {
|
|
7948
|
+
for (const resultId of [...history].reverse()) {
|
|
7949
|
+
ops.push({ type: "history.remove", nodeId: nodeId3, resultId });
|
|
7950
|
+
}
|
|
7951
|
+
}
|
|
7952
|
+
ops.push({ type: "node.remove", nodeId: nodeId3 });
|
|
7953
|
+
return { type: "batch", ops };
|
|
7954
|
+
}
|
|
7955
|
+
function batchOf2(ops) {
|
|
7956
|
+
const [first, ...rest] = ops;
|
|
7957
|
+
if (first !== void 0 && rest.length === 0) return first;
|
|
7958
|
+
return { type: "batch", ops: [...ops] };
|
|
7959
|
+
}
|
|
7960
|
+
function createOpIdGenerator(random = Math.random) {
|
|
7961
|
+
return () => {
|
|
7962
|
+
let out = "";
|
|
7963
|
+
for (let i = 0; i < 36; i += 1) {
|
|
7964
|
+
if (i === 8 || i === 13 || i === 18 || i === 23) {
|
|
7965
|
+
out += "-";
|
|
7966
|
+
continue;
|
|
7967
|
+
}
|
|
7968
|
+
if (i === 14) {
|
|
7969
|
+
out += "4";
|
|
7970
|
+
continue;
|
|
7971
|
+
}
|
|
7972
|
+
const value = Math.floor(random() * 16) & 15;
|
|
7973
|
+
out += (i === 19 ? value & 3 | 8 : value).toString(16);
|
|
7974
|
+
}
|
|
7975
|
+
return out;
|
|
7976
|
+
};
|
|
7977
|
+
}
|
|
7978
|
+
var newOpId = createOpIdGenerator();
|
|
7979
|
+
function touchedPaths(op, out = []) {
|
|
7980
|
+
switch (op.type) {
|
|
7981
|
+
case "node.add":
|
|
7982
|
+
case "node.remove":
|
|
7983
|
+
out.push(["node", op.nodeId]);
|
|
7984
|
+
break;
|
|
7985
|
+
case "node.set":
|
|
7986
|
+
out.push(["node", op.nodeId, ...segmentsOf(op.path)]);
|
|
7987
|
+
break;
|
|
7988
|
+
case "edge.add":
|
|
7989
|
+
case "edge.remove":
|
|
7990
|
+
out.push(["edge", op.edgeId]);
|
|
7991
|
+
break;
|
|
7992
|
+
case "result.set":
|
|
7993
|
+
out.push(["result", op.resultId]);
|
|
7994
|
+
break;
|
|
7995
|
+
case "history.append":
|
|
7996
|
+
case "history.remove":
|
|
7997
|
+
out.push(["history", op.nodeId]);
|
|
7998
|
+
break;
|
|
7999
|
+
case "board.set":
|
|
8000
|
+
out.push(op.key === void 0 ? ["board", op.field] : ["board", op.field, op.key]);
|
|
8001
|
+
break;
|
|
8002
|
+
case "batch":
|
|
8003
|
+
for (const inner of op.ops) touchedPaths(inner, out);
|
|
8004
|
+
break;
|
|
8005
|
+
}
|
|
8006
|
+
return out;
|
|
8007
|
+
}
|
|
8008
|
+
function segmentsOf(path) {
|
|
8009
|
+
try {
|
|
8010
|
+
return parsePath(path);
|
|
8011
|
+
} catch {
|
|
8012
|
+
return [];
|
|
8013
|
+
}
|
|
8014
|
+
}
|
|
8015
|
+
function pathsCross(a, b) {
|
|
8016
|
+
const length = Math.min(a.length, b.length);
|
|
8017
|
+
for (let i = 0; i < length; i += 1) if (a[i] !== b[i]) return false;
|
|
8018
|
+
return true;
|
|
8019
|
+
}
|
|
8020
|
+
function anyPathCrosses(a, b) {
|
|
8021
|
+
for (const left of a) for (const right of b) if (pathsCross(left, right)) return true;
|
|
8022
|
+
return false;
|
|
8023
|
+
}
|
|
8024
|
+
var HISTORY_LIMIT = 100;
|
|
8025
|
+
var HISTORY_MAX_BYTES = 8 * 1024 * 1024;
|
|
8026
|
+
var OBJECT_OVERHEAD = 16;
|
|
8027
|
+
var KEY_OVERHEAD = 8;
|
|
8028
|
+
var NUMBER_BYTES = 8;
|
|
8029
|
+
var SMALL_BYTES = 4;
|
|
8030
|
+
function estimateOpBytes(op) {
|
|
8031
|
+
let total = 0;
|
|
8032
|
+
const pending = [op];
|
|
8033
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8034
|
+
while (pending.length > 0) {
|
|
8035
|
+
const value = pending.pop();
|
|
8036
|
+
if (typeof value === "string") {
|
|
8037
|
+
total += KEY_OVERHEAD + value.length * 2;
|
|
8038
|
+
} else if (typeof value === "number") {
|
|
8039
|
+
total += NUMBER_BYTES;
|
|
8040
|
+
} else if (Array.isArray(value)) {
|
|
8041
|
+
if (seen.has(value)) continue;
|
|
8042
|
+
seen.add(value);
|
|
8043
|
+
total += OBJECT_OVERHEAD;
|
|
8044
|
+
for (const item of value) pending.push(item);
|
|
8045
|
+
} else if (typeof value === "object" && value !== null) {
|
|
8046
|
+
if (seen.has(value)) continue;
|
|
8047
|
+
seen.add(value);
|
|
8048
|
+
total += OBJECT_OVERHEAD;
|
|
8049
|
+
for (const [key, item] of Object.entries(value)) {
|
|
8050
|
+
total += KEY_OVERHEAD + key.length * 2;
|
|
8051
|
+
pending.push(item);
|
|
8052
|
+
}
|
|
8053
|
+
} else {
|
|
8054
|
+
total += SMALL_BYTES;
|
|
8055
|
+
}
|
|
8056
|
+
}
|
|
8057
|
+
return total;
|
|
8058
|
+
}
|
|
8059
|
+
var HistoryStack = class {
|
|
8060
|
+
entries = [];
|
|
8061
|
+
redoEntries = [];
|
|
8062
|
+
limit;
|
|
8063
|
+
maxBytes;
|
|
8064
|
+
clock;
|
|
8065
|
+
onHistoryTrimmed;
|
|
8066
|
+
/** Soma de `bytes` das entradas de desfazer, mantida incrementalmente. */
|
|
8067
|
+
totalBytes = 0;
|
|
8068
|
+
/** Grupo aberto por `startCapture`, ou nulo quando nenhum gesto está aberto. */
|
|
8069
|
+
openGroupId = null;
|
|
8070
|
+
/** Contador de grupos. O id é local à pilha, então não precisa de fonte injetada. */
|
|
8071
|
+
groupSeq = 0;
|
|
8072
|
+
constructor(options = {}) {
|
|
8073
|
+
this.limit = options.limit ?? HISTORY_LIMIT;
|
|
8074
|
+
this.maxBytes = options.maxBytes ?? HISTORY_MAX_BYTES;
|
|
8075
|
+
this.clock = options.clock ?? Date.now;
|
|
8076
|
+
this.onHistoryTrimmed = options.onHistoryTrimmed;
|
|
8077
|
+
}
|
|
8078
|
+
// ------------------------------------------------------------------ leitura
|
|
8079
|
+
get canUndo() {
|
|
8080
|
+
return this.entries.length > 0;
|
|
8081
|
+
}
|
|
8082
|
+
get canRedo() {
|
|
8083
|
+
return this.redoEntries.length > 0;
|
|
8084
|
+
}
|
|
8085
|
+
/** Quantas entradas dá para desfazer. É o que o painel da story 007 mostra. */
|
|
8086
|
+
get size() {
|
|
8087
|
+
return this.entries.length;
|
|
8088
|
+
}
|
|
8089
|
+
/** Quantas entradas dá para refazer. */
|
|
8090
|
+
get redoSize() {
|
|
8091
|
+
return this.redoEntries.length;
|
|
8092
|
+
}
|
|
8093
|
+
/** Memória somada das entradas de desfazer, estimada. */
|
|
8094
|
+
get bytes() {
|
|
8095
|
+
return this.totalBytes;
|
|
8096
|
+
}
|
|
8097
|
+
/** Tem gesto aberto? */
|
|
8098
|
+
get capturing() {
|
|
8099
|
+
return this.openGroupId !== null;
|
|
8100
|
+
}
|
|
8101
|
+
/** A entrada mais recente, sem tirá-la da pilha. Leitura, não consumo. */
|
|
8102
|
+
peek() {
|
|
8103
|
+
return this.entries[this.entries.length - 1];
|
|
8104
|
+
}
|
|
8105
|
+
// ------------------------------------------------------------------ captura
|
|
8106
|
+
/**
|
|
8107
|
+
* Abre um gesto: tudo que for capturado até `endCapture` vira uma entrada só.
|
|
8108
|
+
*
|
|
8109
|
+
* Chamada com um gesto já aberto, devolve o grupo aberto em vez de abrir
|
|
8110
|
+
* outro. Gesto dentro de gesto não existe na tela, e contar profundidade
|
|
8111
|
+
* pediria um `endCapture` por chamada, que é um jeito novo de esquecer de
|
|
8112
|
+
* fechar.
|
|
8113
|
+
*/
|
|
8114
|
+
startCapture() {
|
|
8115
|
+
if (this.openGroupId === null) {
|
|
8116
|
+
this.groupSeq += 1;
|
|
8117
|
+
this.openGroupId = `gesture-${this.groupSeq}`;
|
|
8118
|
+
}
|
|
8119
|
+
return this.openGroupId;
|
|
8120
|
+
}
|
|
8121
|
+
/** Fecha o gesto. A próxima captura abre entrada nova. */
|
|
8122
|
+
endCapture() {
|
|
8123
|
+
this.openGroupId = null;
|
|
8124
|
+
}
|
|
8125
|
+
/**
|
|
8126
|
+
* Guarda uma operação e a inversa dela.
|
|
8127
|
+
*
|
|
8128
|
+
* A inversa entra na FRENTE da lista da entrada: desfazer aplica `inverse` na
|
|
8129
|
+
* ordem do array, e a última coisa que aconteceu é a primeira a ser desfeita.
|
|
8130
|
+
*/
|
|
8131
|
+
capture(op, inverse, options = {}) {
|
|
8132
|
+
this.redoEntries.length = 0;
|
|
8133
|
+
const groupId = options.groupId ?? this.openGroupId;
|
|
8134
|
+
const bytes = estimateOpBytes(op) + estimateOpBytes(inverse);
|
|
8135
|
+
const last = this.peek();
|
|
8136
|
+
if (last !== void 0 && (options.amendLast === true || groupId !== null && last.groupId === groupId)) {
|
|
8137
|
+
last.ops.push(op);
|
|
8138
|
+
last.inverse.unshift(inverse);
|
|
8139
|
+
touchedPaths(op, last.paths);
|
|
8140
|
+
last.bytes += bytes;
|
|
8141
|
+
last.ts = this.clock();
|
|
8142
|
+
this.totalBytes += bytes;
|
|
8143
|
+
this.trim();
|
|
8144
|
+
return last;
|
|
8145
|
+
}
|
|
8146
|
+
const entry = {
|
|
8147
|
+
ops: [op],
|
|
8148
|
+
inverse: [inverse],
|
|
8149
|
+
groupId,
|
|
8150
|
+
ts: this.clock(),
|
|
8151
|
+
bytes,
|
|
8152
|
+
paths: touchedPaths(op),
|
|
8153
|
+
stale: false
|
|
8154
|
+
};
|
|
8155
|
+
this.entries.push(entry);
|
|
8156
|
+
this.totalBytes += bytes;
|
|
8157
|
+
this.trim();
|
|
8158
|
+
return entry;
|
|
8159
|
+
}
|
|
8160
|
+
// ------------------------------------------------------- desfazer e refazer
|
|
8161
|
+
/**
|
|
8162
|
+
* Tira a entrada mais recente e a passa para o refazer.
|
|
8163
|
+
*
|
|
8164
|
+
* A pilha não aplica nada: quem aplica é o store, com a inversa recarimbada.
|
|
8165
|
+
* Devolver a entrada em vez de aplicá-la é o que mantém o núcleo do histórico
|
|
8166
|
+
* sem opinião sobre transporte, relógio e id.
|
|
8167
|
+
*/
|
|
8168
|
+
undo() {
|
|
8169
|
+
const entry = this.entries.pop();
|
|
8170
|
+
if (entry === void 0) return void 0;
|
|
8171
|
+
this.totalBytes -= entry.bytes;
|
|
8172
|
+
if (!entry.stale) this.redoEntries.push(entry);
|
|
8173
|
+
return entry;
|
|
8174
|
+
}
|
|
8175
|
+
/**
|
|
8176
|
+
* Devolve à pilha de desfazer a entrada que `undo` acabou de tirar, quando a
|
|
8177
|
+
* inversa dela não pôde ser aplicada (recusada pelo teto de tamanho). Sem
|
|
8178
|
+
* isto, um desfazer recusado perderia o passo.
|
|
8179
|
+
*/
|
|
8180
|
+
revertUndo(entry) {
|
|
8181
|
+
if (this.redoEntries[this.redoEntries.length - 1] === entry) this.redoEntries.pop();
|
|
8182
|
+
this.entries.push(entry);
|
|
8183
|
+
this.totalBytes += entry.bytes;
|
|
8184
|
+
}
|
|
8185
|
+
/** O par de `revertUndo` para o refazer. */
|
|
8186
|
+
revertRedo(entry) {
|
|
8187
|
+
if (this.entries[this.entries.length - 1] === entry) {
|
|
8188
|
+
this.entries.pop();
|
|
8189
|
+
this.totalBytes -= entry.bytes;
|
|
8190
|
+
}
|
|
8191
|
+
this.redoEntries.push(entry);
|
|
8192
|
+
}
|
|
8193
|
+
/**
|
|
8194
|
+
* Outra pessoa tocou estes caminhos: as entradas que cruzam com eles, nas duas
|
|
8195
|
+
* pilhas, ficam marcadas como velhas. Não apaga nada aqui: quem descarta, e
|
|
8196
|
+
* avisa, é o desfazer, no momento em que a pessoa pede.
|
|
8197
|
+
*/
|
|
8198
|
+
invalidate(paths) {
|
|
8199
|
+
if (paths.length === 0) return 0;
|
|
8200
|
+
let marked = 0;
|
|
8201
|
+
for (const entry of [...this.entries, ...this.redoEntries]) {
|
|
8202
|
+
if (entry.stale || !anyPathCrosses(entry.paths, paths)) continue;
|
|
8203
|
+
entry.stale = true;
|
|
8204
|
+
marked += 1;
|
|
8205
|
+
}
|
|
8206
|
+
return marked;
|
|
8207
|
+
}
|
|
8208
|
+
/**
|
|
8209
|
+
* Tira a entrada mais recente do refazer e a devolve para o desfazer.
|
|
8210
|
+
*
|
|
8211
|
+
* Não precisa de poda: o que volta já esteve na pilha dentro do teto, e
|
|
8212
|
+
* qualquer captura no meio do caminho teria zerado o refazer.
|
|
8213
|
+
*/
|
|
8214
|
+
redo() {
|
|
8215
|
+
const entry = this.redoEntries.pop();
|
|
8216
|
+
if (entry === void 0) return void 0;
|
|
8217
|
+
if (entry.stale) return entry;
|
|
8218
|
+
this.entries.push(entry);
|
|
8219
|
+
this.totalBytes += entry.bytes;
|
|
8220
|
+
return entry;
|
|
8221
|
+
}
|
|
8222
|
+
/** Esvazia as duas pilhas. O documento não muda; a memória, sim. */
|
|
8223
|
+
clear() {
|
|
8224
|
+
this.entries.length = 0;
|
|
8225
|
+
this.redoEntries.length = 0;
|
|
8226
|
+
this.totalBytes = 0;
|
|
8227
|
+
this.openGroupId = null;
|
|
8228
|
+
}
|
|
8229
|
+
// --------------------------------------------------------------------- teto
|
|
8230
|
+
/**
|
|
8231
|
+
* Aplica os dois tetos, o de contagem e o de memória.
|
|
8232
|
+
*
|
|
8233
|
+
* A entrada mais recente nunca é descartada pelo teto de memória, mesmo
|
|
8234
|
+
* sozinha acima dele: o documento já mudou, e descartá-la deixaria o Marco sem
|
|
8235
|
+
* como desfazer o que ele acabou de fazer. Quando é esse o caso, o total fica
|
|
8236
|
+
* acima do teto e nenhum aviso é forjado, porque nada foi descartado.
|
|
8237
|
+
*/
|
|
8238
|
+
trim() {
|
|
8239
|
+
const excess = this.entries.length - this.limit;
|
|
8240
|
+
if (excess > 0) {
|
|
8241
|
+
const dropped = this.entries.splice(0, excess);
|
|
8242
|
+
for (const entry of dropped) this.totalBytes -= entry.bytes;
|
|
8243
|
+
this.report("count", dropped);
|
|
8244
|
+
}
|
|
8245
|
+
let cut = 0;
|
|
8246
|
+
let running = this.totalBytes;
|
|
8247
|
+
for (const entry of this.entries) {
|
|
8248
|
+
if (running <= this.maxBytes || cut >= this.entries.length - 1) break;
|
|
8249
|
+
running -= entry.bytes;
|
|
8250
|
+
cut += 1;
|
|
8251
|
+
}
|
|
8252
|
+
if (cut > 0) {
|
|
8253
|
+
const dropped = this.entries.splice(0, cut);
|
|
8254
|
+
this.totalBytes = running;
|
|
8255
|
+
this.report("bytes", dropped);
|
|
8256
|
+
}
|
|
8257
|
+
}
|
|
8258
|
+
report(reason, dropped) {
|
|
8259
|
+
if (this.onHistoryTrimmed === void 0) return;
|
|
8260
|
+
this.onHistoryTrimmed({ reason, dropped, bytes: this.totalBytes });
|
|
8261
|
+
}
|
|
8262
|
+
};
|
|
8263
|
+
function isLocalEnvelope(envelope2, localActorId) {
|
|
8264
|
+
return envelope2.actorId === localActorId;
|
|
8265
|
+
}
|
|
8266
|
+
function captureOf(doc, op) {
|
|
8267
|
+
if (op.type === "batch") {
|
|
8268
|
+
const parts = walkBatch(doc, op.ops, captureOf);
|
|
8269
|
+
if (parts.length === 0) return null;
|
|
8270
|
+
return {
|
|
8271
|
+
op: { type: "batch", ops: parts.map((part) => part.op) },
|
|
8272
|
+
inverse: { type: "batch", ops: parts.map((part) => part.inverse).reverse() }
|
|
8273
|
+
};
|
|
8274
|
+
}
|
|
8275
|
+
const inverse = invert(doc, op);
|
|
8276
|
+
if (inverse === null) return null;
|
|
8277
|
+
return { op, inverse };
|
|
8278
|
+
}
|
|
8279
|
+
function trackCapture(doc, envelope2, localActorId) {
|
|
8280
|
+
if (!isLocalEnvelope(envelope2, localActorId)) return null;
|
|
8281
|
+
return captureOf(doc, envelope2.op);
|
|
8282
|
+
}
|
|
8283
|
+
var EMPTY_INTERACTION = Object.freeze({
|
|
8284
|
+
drag: null,
|
|
8285
|
+
resize: null,
|
|
8286
|
+
selection: Object.freeze([])
|
|
8287
|
+
});
|
|
8288
|
+
function sameNodeIds(a, b) {
|
|
8289
|
+
if (a.length !== b.length) return false;
|
|
8290
|
+
for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
|
|
8291
|
+
return true;
|
|
8292
|
+
}
|
|
8293
|
+
function sameBox(a, b) {
|
|
8294
|
+
if (a == null || b == null) return (a ?? null) === (b ?? null);
|
|
8295
|
+
return a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;
|
|
8296
|
+
}
|
|
8297
|
+
function isOpList(value) {
|
|
8298
|
+
return Array.isArray(value);
|
|
8299
|
+
}
|
|
8300
|
+
var BoardStore = class {
|
|
8301
|
+
current;
|
|
8302
|
+
interaction = EMPTY_INTERACTION;
|
|
8303
|
+
options;
|
|
8304
|
+
stack;
|
|
8305
|
+
clock;
|
|
8306
|
+
newId;
|
|
8307
|
+
listeners = /* @__PURE__ */ new Set();
|
|
8308
|
+
envelopeListeners = /* @__PURE__ */ new Set();
|
|
8309
|
+
last = null;
|
|
8310
|
+
lastFromSync = false;
|
|
8311
|
+
constructor(doc, options) {
|
|
8312
|
+
this.current = doc;
|
|
8313
|
+
this.options = options;
|
|
8314
|
+
this.clock = options.clock ?? Date.now;
|
|
8315
|
+
this.newId = options.newId ?? newOpId;
|
|
8316
|
+
this.stack = new HistoryStack({
|
|
8317
|
+
limit: options.history?.limit,
|
|
8318
|
+
maxBytes: options.history?.maxBytes,
|
|
8319
|
+
clock: this.clock,
|
|
8320
|
+
onHistoryTrimmed: options.onHistoryTrimmed
|
|
8321
|
+
});
|
|
8322
|
+
}
|
|
8323
|
+
// ------------------------------------------------------------------ leitura
|
|
8324
|
+
/**
|
|
8325
|
+
* O documento de agora. Estável por referência entre mudanças.
|
|
8326
|
+
*
|
|
8327
|
+
* Propriedade de seta, e não método, porque ela é passada direto para
|
|
8328
|
+
* `useSyncExternalStore`: assim não precisa de `bind`, e o React não reassina
|
|
8329
|
+
* a cada render por receber uma função nova. `subscribe` e `getInteraction`
|
|
8330
|
+
* seguem a mesma forma, e as três mudam juntas ou nenhuma: metade convertida
|
|
8331
|
+
* faz o React reassinar sem erro visível.
|
|
8332
|
+
*/
|
|
8333
|
+
getDoc = () => this.current;
|
|
8334
|
+
/** O estado efêmero de agora. Mesma regra de estabilidade do documento. */
|
|
8335
|
+
getInteraction = () => this.interaction;
|
|
8336
|
+
/** Assina mudanças. Devolve a função que cancela a assinatura. */
|
|
8337
|
+
subscribe = (listener) => {
|
|
8338
|
+
this.listeners.add(listener);
|
|
8339
|
+
return () => {
|
|
8340
|
+
this.listeners.delete(listener);
|
|
8341
|
+
};
|
|
8342
|
+
};
|
|
8343
|
+
/** A pilha, para quem mostra o estado dela na tela (story 007). */
|
|
8344
|
+
get history() {
|
|
8345
|
+
return this.stack;
|
|
8346
|
+
}
|
|
8347
|
+
get canUndo() {
|
|
8348
|
+
return this.stack.canUndo;
|
|
8349
|
+
}
|
|
8350
|
+
get canRedo() {
|
|
8351
|
+
return this.stack.canRedo;
|
|
8352
|
+
}
|
|
8353
|
+
/**
|
|
8354
|
+
* O último envelope aplicado, nosso ou de fora. É por ele que quem assina
|
|
8355
|
+
* sabe se a mudança que acabou de acordá-lo nasceu nesta aba (`clientId`
|
|
8356
|
+
* igual ao da sessão) e, portanto, se deve derivar operação a partir dela
|
|
8357
|
+
* (SV2b). Nulo antes do primeiro despacho.
|
|
8358
|
+
*/
|
|
8359
|
+
get lastEnvelope() {
|
|
8360
|
+
return this.last;
|
|
8361
|
+
}
|
|
8362
|
+
/**
|
|
8363
|
+
* A última troca do documento veio de `replaceDoc` (a sincronização trocou a
|
|
8364
|
+
* foto: remotas mais as pendentes reaplicadas), e não de um despacho. Para
|
|
8365
|
+
* quem deriva operação, isso conta como mudança de fora: as pendentes desta
|
|
8366
|
+
* aba já derivaram quando foram despachadas pela primeira vez.
|
|
8367
|
+
*/
|
|
8368
|
+
get lastChangeFromSync() {
|
|
8369
|
+
return this.lastFromSync;
|
|
8370
|
+
}
|
|
8371
|
+
// ------------------------------------------------------------------ gestos
|
|
8372
|
+
/** Abre um gesto: o que for despachado até `endCapture` vira uma entrada só. */
|
|
8373
|
+
startCapture() {
|
|
8374
|
+
return this.stack.startCapture();
|
|
8375
|
+
}
|
|
8376
|
+
/** Fecha o gesto. */
|
|
8377
|
+
endCapture() {
|
|
8378
|
+
this.stack.endCapture();
|
|
8379
|
+
}
|
|
8380
|
+
// ---------------------------------------------------------------- interação
|
|
8381
|
+
/**
|
|
8382
|
+
* Troca a seleção. Não é documento, não é op, não entra na pilha.
|
|
8383
|
+
*
|
|
8384
|
+
* Seleção igual sai de graça: sem troca de referência ninguém é acordado.
|
|
8385
|
+
*/
|
|
8386
|
+
select(nodeIds) {
|
|
8387
|
+
if (sameNodeIds(this.interaction.selection, nodeIds)) return;
|
|
8388
|
+
this.interaction = { ...this.interaction, selection: [...nodeIds] };
|
|
8389
|
+
this.notify();
|
|
8390
|
+
}
|
|
8391
|
+
/**
|
|
8392
|
+
* Abre um gesto de arraste, capturando a posição de partida de cada nó.
|
|
8393
|
+
*
|
|
8394
|
+
* Id que não existe no documento é ignorado, e um gesto sem nenhum nó válido
|
|
8395
|
+
* não abre nem notifica. Gesto já aberto também não reabre: o primeiro frame
|
|
8396
|
+
* é quem define a base da op do soltar, e recapturar a base no meio do
|
|
8397
|
+
* caminho mediria o gesto pela metade.
|
|
8398
|
+
*/
|
|
8399
|
+
beginDrag(nodeIds) {
|
|
8400
|
+
if (this.interaction.drag !== null) return;
|
|
8401
|
+
const origin = {};
|
|
8402
|
+
const ids = [];
|
|
8403
|
+
for (const id of nodeIds) {
|
|
8404
|
+
const node = this.current.nodes[id];
|
|
8405
|
+
if (node === void 0) continue;
|
|
8406
|
+
origin[id] = { x: node.position.x, y: node.position.y };
|
|
8407
|
+
ids.push(id);
|
|
8408
|
+
}
|
|
8409
|
+
if (ids.length === 0) return;
|
|
8410
|
+
this.interaction = { ...this.interaction, drag: { nodeIds: ids, origin, live: origin } };
|
|
8411
|
+
this.notify();
|
|
8412
|
+
}
|
|
8413
|
+
/**
|
|
8414
|
+
* Move o gesto vivo. Sem op, sem histórico, sem tocar no documento.
|
|
8415
|
+
*
|
|
8416
|
+
* Posição repetida sai de graça, e é isso que impede um `pointermove` que não
|
|
8417
|
+
* andou de custar um render. Id fora do gesto é ignorado.
|
|
8418
|
+
*/
|
|
8419
|
+
moveDrag(positions) {
|
|
8420
|
+
const drag = this.interaction.drag;
|
|
8421
|
+
if (drag === null) return;
|
|
8422
|
+
let changed = false;
|
|
8423
|
+
const live = { ...drag.live };
|
|
8424
|
+
for (const id of drag.nodeIds) {
|
|
8425
|
+
const next = positions[id];
|
|
8426
|
+
if (next === void 0) continue;
|
|
8427
|
+
const current = live[id];
|
|
8428
|
+
if (current !== void 0 && current.x === next.x && current.y === next.y) continue;
|
|
8429
|
+
live[id] = { x: next.x, y: next.y };
|
|
8430
|
+
changed = true;
|
|
8431
|
+
}
|
|
8432
|
+
if (!changed) return;
|
|
8433
|
+
this.interaction = { ...this.interaction, drag: { ...drag, live } };
|
|
8434
|
+
this.notify();
|
|
8435
|
+
}
|
|
8436
|
+
/**
|
|
8437
|
+
* Fecha o gesto: uma op de topo, uma entrada de histórico, uma notificação.
|
|
8438
|
+
*
|
|
8439
|
+
* **A troca é atômica.** A camada efêmera é limpa ANTES de o despacho
|
|
8440
|
+
* notificar, então a única notificação que sai já carrega o documento com a
|
|
8441
|
+
* posição nova e o gesto encerrado. Nenhum assinante consegue observar o par
|
|
8442
|
+
* (posição velha, arraste já encerrado), que é o piscar de um frame que o
|
|
8443
|
+
* desenho de dois donos de estado produz.
|
|
8444
|
+
*
|
|
8445
|
+
* `positions` é a posição final vinda de quem viu o gesto acontecer (o
|
|
8446
|
+
* `change.position` da lib), e a camada efêmera entra só como reserva: uma
|
|
8447
|
+
* fonte de verdade por valor, com a segunda cobrindo o dia em que a primeira
|
|
8448
|
+
* faltar. Nó que voltou para onde começou não emite nada, e gesto em que
|
|
8449
|
+
* ninguém andou não emite op nenhuma.
|
|
8450
|
+
*/
|
|
8451
|
+
endDrag(positions = {}) {
|
|
8452
|
+
const drag = this.interaction.drag;
|
|
8453
|
+
if (drag === null) return null;
|
|
8454
|
+
const ops = [];
|
|
8455
|
+
for (const id of drag.nodeIds) {
|
|
8456
|
+
const from = drag.origin[id];
|
|
8457
|
+
const to = positions[id] ?? drag.live[id];
|
|
8458
|
+
if (from === void 0 || to === void 0) continue;
|
|
8459
|
+
if (from.x === to.x && from.y === to.y) continue;
|
|
8460
|
+
ops.push({
|
|
8461
|
+
type: "node.set",
|
|
8462
|
+
nodeId: id,
|
|
8463
|
+
path: "position",
|
|
8464
|
+
value: propValue({ x: to.x, y: to.y })
|
|
8465
|
+
});
|
|
8466
|
+
}
|
|
8467
|
+
if (ops.length === 0) {
|
|
8468
|
+
this.cancelDrag();
|
|
8469
|
+
return null;
|
|
8470
|
+
}
|
|
8471
|
+
this.interaction = { ...this.interaction, drag: null };
|
|
8472
|
+
const result = this.dispatch(ops, { silent: true });
|
|
8473
|
+
this.notify();
|
|
8474
|
+
return result;
|
|
8475
|
+
}
|
|
8476
|
+
/**
|
|
8477
|
+
* Saída do gesto interrompido: `Escape`, `pointercancel` e a aba perdendo o
|
|
8478
|
+
* foco. Zero op, zero entrada de histórico, e o nó volta para a posição do
|
|
8479
|
+
* documento porque é ela que sempre esteve lá.
|
|
8480
|
+
*/
|
|
8481
|
+
cancelDrag() {
|
|
8482
|
+
if (this.interaction.drag === null) return;
|
|
8483
|
+
this.interaction = { ...this.interaction, drag: null };
|
|
8484
|
+
this.notify();
|
|
8485
|
+
}
|
|
8486
|
+
/**
|
|
8487
|
+
* Abre um gesto de redimensionar (SV2b). Mesmo desenho do arraste: nada vira
|
|
8488
|
+
* operação até o soltar. Nó ausente não abre.
|
|
8489
|
+
*/
|
|
8490
|
+
beginResize(nodeId3) {
|
|
8491
|
+
const node = this.current.nodes[nodeId3];
|
|
8492
|
+
if (node === void 0) return;
|
|
8493
|
+
const origin = { ...node.position, ...node.size };
|
|
8494
|
+
this.interaction = { ...this.interaction, resize: { nodeId: nodeId3, origin, live: origin } };
|
|
8495
|
+
this.notify();
|
|
8496
|
+
}
|
|
8497
|
+
/** A caixa do frame atual. Sem op, sem histórico. Caixa igual sai de graça. */
|
|
8498
|
+
moveResize(box) {
|
|
8499
|
+
const resize = this.interaction.resize;
|
|
8500
|
+
if (resize == null || sameBox(resize.live, box)) return;
|
|
8501
|
+
const live = { x: box.x, y: box.y, w: box.w, h: box.h };
|
|
8502
|
+
this.interaction = { ...this.interaction, resize: { ...resize, live } };
|
|
8503
|
+
this.notify();
|
|
8504
|
+
}
|
|
8505
|
+
/**
|
|
8506
|
+
* Fecha o gesto: uma op, uma entrada de histórico, uma notificação. A troca
|
|
8507
|
+
* é atômica pela mesma razão de `endDrag`. Caixa final igual à de partida
|
|
8508
|
+
* não emite nada.
|
|
8509
|
+
*/
|
|
8510
|
+
endResize(box) {
|
|
8511
|
+
const resize = this.interaction.resize;
|
|
8512
|
+
if (resize == null) return null;
|
|
8513
|
+
const to = box ?? resize.live;
|
|
8514
|
+
const from = resize.origin;
|
|
8515
|
+
const ops = [];
|
|
8516
|
+
if (from.w !== to.w || from.h !== to.h) {
|
|
8517
|
+
ops.push({
|
|
8518
|
+
type: "node.set",
|
|
8519
|
+
nodeId: resize.nodeId,
|
|
8520
|
+
path: "size",
|
|
8521
|
+
value: propValue({ w: to.w, h: to.h })
|
|
8522
|
+
});
|
|
8523
|
+
}
|
|
8524
|
+
if (from.x !== to.x || from.y !== to.y) {
|
|
8525
|
+
ops.push({
|
|
8526
|
+
type: "node.set",
|
|
8527
|
+
nodeId: resize.nodeId,
|
|
8528
|
+
path: "position",
|
|
8529
|
+
value: propValue({ x: to.x, y: to.y })
|
|
8530
|
+
});
|
|
8531
|
+
}
|
|
8532
|
+
this.interaction = { ...this.interaction, resize: null };
|
|
8533
|
+
if (ops.length === 0 || this.current.nodes[resize.nodeId] === void 0) {
|
|
8534
|
+
this.notify();
|
|
8535
|
+
return null;
|
|
8536
|
+
}
|
|
8537
|
+
const result = this.dispatch(ops, { silent: true });
|
|
8538
|
+
this.notify();
|
|
8539
|
+
return result;
|
|
8540
|
+
}
|
|
8541
|
+
/** Gesto interrompido: zero op, e o nó volta ao tamanho do documento. */
|
|
8542
|
+
cancelResize() {
|
|
8543
|
+
if (this.interaction.resize == null) return;
|
|
8544
|
+
this.interaction = { ...this.interaction, resize: null };
|
|
8545
|
+
this.notify();
|
|
8546
|
+
}
|
|
8547
|
+
// ----------------------------------------------------------------- despacho
|
|
8548
|
+
/**
|
|
8549
|
+
* Despacha operação nossa: carimba o envelope com a sessão local e aplica.
|
|
8550
|
+
*
|
|
8551
|
+
* Lista com mais de uma operação vira um `batch`, porque um envelope carrega
|
|
8552
|
+
* UMA operação de topo, e um `batch` é uma operação, logo um `seq`
|
|
8553
|
+
* (`dev/PLANO-FASE-0.md` §3).
|
|
8554
|
+
*/
|
|
8555
|
+
dispatch(ops, options = {}) {
|
|
8556
|
+
const op = isOpList(ops) ? batchOf2(ops) : ops;
|
|
8557
|
+
return this.dispatchEnvelope(this.stamp(op), options);
|
|
8558
|
+
}
|
|
8559
|
+
/**
|
|
8560
|
+
* Despacha um envelope já carimbado.
|
|
8561
|
+
*
|
|
8562
|
+
* É a porta por onde entra o que NÃO nasceu nesta aba: o motor de execução da
|
|
8563
|
+
* fase 4 e, um dia, o `pull` da colaboração. O filtro de captura compara o
|
|
8564
|
+
* `actorId` do envelope com o da sessão, e é por isso que a regra do autor
|
|
8565
|
+
* mora no envelope em vez de virar um parâmetro do despacho.
|
|
8566
|
+
*/
|
|
8567
|
+
dispatchEnvelope(envelope2, options = {}) {
|
|
8568
|
+
const before = this.current;
|
|
8569
|
+
const ours = envelope2.clientId === this.options.session.clientId;
|
|
8570
|
+
const split = ours && options.unbounded !== true ? this.wireEnvelopes(envelope2) : [envelope2];
|
|
8571
|
+
const envelopes = split === null && this.envelopeListeners.size > 0 ? [envelope2] : split;
|
|
8572
|
+
if (envelopes === null) {
|
|
8573
|
+
const rejected = {
|
|
8574
|
+
code: "op-too-large",
|
|
8575
|
+
message: "Essa altera\xE7\xE3o \xE9 grande demais para ir de uma vez s\xF3 (mais de 64 KB numa opera\xE7\xE3o) e n\xE3o foi aplicada.",
|
|
8576
|
+
boardId: this.current.id,
|
|
8577
|
+
opId: envelope2.id
|
|
8578
|
+
};
|
|
8579
|
+
this.options.onError(rejected);
|
|
8580
|
+
return { envelope: envelope2, doc: before, changedNodeIds: [], entry: null, envelopes: [], rejected };
|
|
8581
|
+
}
|
|
8582
|
+
const capture = options.tracked === false ? null : trackCapture(before, envelope2, this.options.session.actorId);
|
|
8583
|
+
const applied = applyOps(before, [envelope2.op]);
|
|
8584
|
+
const entry = capture === null ? null : this.stack.capture(capture.op, capture.inverse, {
|
|
8585
|
+
groupId: options.groupId,
|
|
8586
|
+
amendLast: options.amendLast
|
|
8587
|
+
});
|
|
8588
|
+
if (envelope2.actorId !== null && envelope2.actorId !== this.options.session.actorId) {
|
|
8589
|
+
this.stack.invalidate(touchedPaths(envelope2.op));
|
|
8590
|
+
}
|
|
8591
|
+
this.current = applied.doc;
|
|
8592
|
+
this.last = envelope2;
|
|
8593
|
+
this.lastFromSync = false;
|
|
8594
|
+
for (const listener of this.envelopeListeners) for (const wire of envelopes) listener(wire);
|
|
8595
|
+
if (options.silent !== true && applied.doc !== before) this.notify();
|
|
8596
|
+
return {
|
|
8597
|
+
envelope: envelope2,
|
|
8598
|
+
doc: applied.doc,
|
|
8599
|
+
changedNodeIds: applied.changedNodeIds,
|
|
8600
|
+
entry,
|
|
8601
|
+
envelopes,
|
|
8602
|
+
rejected: null
|
|
8603
|
+
};
|
|
8604
|
+
}
|
|
8605
|
+
// ----------------------------------------------------------- sincronização
|
|
8606
|
+
/**
|
|
8607
|
+
* Assina os envelopes que ESTA aba aplicou pelo despacho (edição, desfazer,
|
|
8608
|
+
* refazer, soltar de arraste). É por aqui que o cliente de sincronização
|
|
8609
|
+
* (`transport/`) monta a fila de pendentes. Avisado só depois de o apply
|
|
8610
|
+
* passar: envelope que lançou nunca vira pendente.
|
|
8611
|
+
*
|
|
8612
|
+
* Sem assinante, o despacho se comporta exatamente como antes.
|
|
8613
|
+
*/
|
|
8614
|
+
subscribeEnvelopes = (listener) => {
|
|
8615
|
+
this.envelopeListeners.add(listener);
|
|
8616
|
+
return () => {
|
|
8617
|
+
this.envelopeListeners.delete(listener);
|
|
8618
|
+
};
|
|
8619
|
+
};
|
|
8620
|
+
/**
|
|
8621
|
+
* Troca o documento inteiro pelo que a sincronização calculou (foto confirmada
|
|
8622
|
+
* + remotas + pendentes reaplicadas). Não entra no histórico, não avisa
|
|
8623
|
+
* `subscribeEnvelopes` (senão o remoto voltaria como pendente) e só notifica
|
|
8624
|
+
* quando a referência muda.
|
|
8625
|
+
*/
|
|
8626
|
+
replaceDoc(doc) {
|
|
8627
|
+
if (doc === this.current) return;
|
|
8628
|
+
this.current = doc;
|
|
8629
|
+
this.lastFromSync = true;
|
|
8630
|
+
this.notify();
|
|
8631
|
+
}
|
|
8632
|
+
/**
|
|
8633
|
+
* O envelope como vai ao fio, em pedaços que cabem no teto.
|
|
8634
|
+
*
|
|
8635
|
+
* Cabe inteiro: sai como está, e é o caso de quase todo despacho. Não cabe e
|
|
8636
|
+
* é `batch`: os membros (com `batch` aninhado aberto, a ordem preservada) são
|
|
8637
|
+
* empacotados em envelopes consecutivos. Uma folha sozinha acima do teto não
|
|
8638
|
+
* tem como ir: devolve nulo, e o despacho é recusado inteiro.
|
|
8639
|
+
*/
|
|
8640
|
+
wireEnvelopes(envelope2) {
|
|
8641
|
+
if (opEnvelopeBytes(envelope2) <= MAX_OP_BYTES2) return [envelope2];
|
|
8642
|
+
if (envelope2.op.type !== "batch") return null;
|
|
8643
|
+
const leaves = [];
|
|
8644
|
+
const open3 = (op) => {
|
|
8645
|
+
if (op.type === "batch") for (const inner of op.ops) open3(inner);
|
|
8646
|
+
else leaves.push(op);
|
|
8647
|
+
};
|
|
8648
|
+
open3(envelope2.op);
|
|
8649
|
+
const slack = 64;
|
|
8650
|
+
const overhead = opEnvelopeBytes({ ...envelope2, op: { type: "batch", ops: [] } }) + slack;
|
|
8651
|
+
const chunks = [];
|
|
8652
|
+
let chunk = [];
|
|
8653
|
+
let bytes = overhead;
|
|
8654
|
+
for (const leaf of leaves) {
|
|
8655
|
+
const size = utf8ByteLength(JSON.stringify(leaf));
|
|
8656
|
+
if (overhead + size > MAX_OP_BYTES2) return null;
|
|
8657
|
+
const added = chunk.length === 0 ? size : size + 1;
|
|
8658
|
+
if (chunk.length > 0 && bytes + added > MAX_OP_BYTES2) {
|
|
8659
|
+
chunks.push(chunk);
|
|
8660
|
+
chunk = [leaf];
|
|
8661
|
+
bytes = overhead + size;
|
|
8662
|
+
} else {
|
|
8663
|
+
chunk.push(leaf);
|
|
8664
|
+
bytes += added;
|
|
8665
|
+
}
|
|
8666
|
+
}
|
|
8667
|
+
if (chunk.length > 0) chunks.push(chunk);
|
|
8668
|
+
return chunks.map((ops, index) => ({
|
|
8669
|
+
...envelope2,
|
|
8670
|
+
// O primeiro pedaço herda o id: é por ele que quem despachou reconhece o eco.
|
|
8671
|
+
id: index === 0 ? envelope2.id : this.newId(),
|
|
8672
|
+
op: ops.length === 1 ? ops[0] : { type: "batch", ops }
|
|
8673
|
+
}));
|
|
8674
|
+
}
|
|
8675
|
+
// -------------------------------------------------------- desfazer e refazer
|
|
8676
|
+
/**
|
|
8677
|
+
* Desfaz o último gesto.
|
|
8678
|
+
*
|
|
8679
|
+
* Cada inversa sai recarimbada com id novo e o `clientId` local, embrulhada em
|
|
8680
|
+
* `batch` quando a entrada juntou mais de um despacho, e despachada com
|
|
8681
|
+
* `{tracked:false}`. A entrada vai para a pilha de refazer inteira, do jeito
|
|
8682
|
+
* que estava.
|
|
8683
|
+
*/
|
|
8684
|
+
undo() {
|
|
8685
|
+
const entry = this.stack.undo();
|
|
8686
|
+
if (entry === void 0) return { applied: false, changedNodeIds: [], envelope: null };
|
|
8687
|
+
if (entry.stale) return this.discard("desfazer");
|
|
8688
|
+
const result = this.replay(entry.inverse);
|
|
8689
|
+
if (!result.applied) this.stack.revertUndo(entry);
|
|
8690
|
+
return result;
|
|
8691
|
+
}
|
|
8692
|
+
/** Refaz o gesto desfeito mais recente, pelas operações originais e na ordem delas. */
|
|
8693
|
+
redo() {
|
|
8694
|
+
const entry = this.stack.redo();
|
|
8695
|
+
if (entry === void 0) return { applied: false, changedNodeIds: [], envelope: null };
|
|
8696
|
+
if (entry.stale) return this.discard("refazer");
|
|
8697
|
+
const result = this.replay(entry.ops);
|
|
8698
|
+
if (!result.applied) this.stack.revertRedo(entry);
|
|
8699
|
+
return result;
|
|
8700
|
+
}
|
|
8701
|
+
// ------------------------------------------------------------------ privados
|
|
8702
|
+
/** O passo velho sai da pilha sem tocar no documento, com aviso. */
|
|
8703
|
+
discard(verb) {
|
|
8704
|
+
this.options.onError({
|
|
8705
|
+
code: "undo-conflict",
|
|
8706
|
+
message: `Outra pessoa mexeu no mesmo lugar depois. Esse passo de ${verb} foi descartado para n\xE3o apagar o trabalho dela.`,
|
|
8707
|
+
boardId: this.current.id
|
|
8708
|
+
});
|
|
8709
|
+
this.notify();
|
|
8710
|
+
return { applied: false, changedNodeIds: [], envelope: null, discarded: true };
|
|
8711
|
+
}
|
|
8712
|
+
/** Despacha uma lista guardada na pilha, sem deixá-la voltar para a pilha. */
|
|
8713
|
+
replay(ops) {
|
|
8714
|
+
const result = this.dispatch(batchOf2(ops), { tracked: false });
|
|
8715
|
+
if (result.rejected !== null) return { applied: false, changedNodeIds: [], envelope: null };
|
|
8716
|
+
return { applied: true, changedNodeIds: result.changedNodeIds, envelope: result.envelope };
|
|
8717
|
+
}
|
|
8718
|
+
/** O envelope de uma operação nossa. `seq` nasce nulo: quem confirma é o commit. */
|
|
8719
|
+
stamp(op) {
|
|
8720
|
+
return {
|
|
8721
|
+
id: this.newId(),
|
|
8722
|
+
boardId: this.current.id,
|
|
8723
|
+
clientId: this.options.session.clientId,
|
|
8724
|
+
actorId: this.options.session.actorId,
|
|
8725
|
+
seq: null,
|
|
8726
|
+
ts: this.clock(),
|
|
8727
|
+
op
|
|
8728
|
+
};
|
|
8729
|
+
}
|
|
8730
|
+
notify() {
|
|
8731
|
+
for (const listener of this.listeners) listener();
|
|
8732
|
+
}
|
|
8733
|
+
};
|
|
8734
|
+
function resolveGap(gap) {
|
|
8735
|
+
return typeof gap === "number" ? { x: gap, y: gap } : { x: gap.x, y: gap.y };
|
|
8736
|
+
}
|
|
8737
|
+
function rectOf2(node) {
|
|
8738
|
+
return { x: node.position.x, y: node.position.y, w: node.size.w, h: node.size.h };
|
|
8739
|
+
}
|
|
8740
|
+
function rectsCollide(a, b, gap) {
|
|
8741
|
+
return a.x < b.x + b.w + gap.x && b.x < a.x + a.w + gap.x && a.y < b.y + b.h + gap.y && b.y < a.y + a.h + gap.y;
|
|
8742
|
+
}
|
|
8743
|
+
function boundsOf(rects) {
|
|
8744
|
+
let minX = Number.POSITIVE_INFINITY;
|
|
8745
|
+
let minY = Number.POSITIVE_INFINITY;
|
|
8746
|
+
let maxX = Number.NEGATIVE_INFINITY;
|
|
8747
|
+
let maxY = Number.NEGATIVE_INFINITY;
|
|
8748
|
+
for (const rect of rects) {
|
|
8749
|
+
minX = Math.min(minX, rect.x);
|
|
8750
|
+
minY = Math.min(minY, rect.y);
|
|
8751
|
+
maxX = Math.max(maxX, rect.x + rect.w);
|
|
8752
|
+
maxY = Math.max(maxY, rect.y + rect.h);
|
|
8753
|
+
}
|
|
8754
|
+
if (rects.length === 0) return { x: 0, y: 0, w: 0, h: 0 };
|
|
8755
|
+
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
|
|
8756
|
+
}
|
|
8757
|
+
function compareText(a, b) {
|
|
8758
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
8759
|
+
}
|
|
8760
|
+
function byScreenOrder(a, b) {
|
|
8761
|
+
return a.position.y - b.position.y || a.position.x - b.position.x || compareText(a.id, b.id);
|
|
8762
|
+
}
|
|
8763
|
+
function obstaclesOf(doc, ignore = []) {
|
|
8764
|
+
const skipped = new Set(ignore);
|
|
8765
|
+
return Object.values(doc.nodes).filter((node) => node.parentId === null && !skipped.has(node.id)).sort(byScreenOrder).map(rectOf2);
|
|
8766
|
+
}
|
|
8767
|
+
var DEFAULT_MAX_PER_COLUMN = 8;
|
|
8768
|
+
function positiveInt(value, fallback) {
|
|
8769
|
+
if (value === void 0 || !Number.isFinite(value)) return fallback;
|
|
8770
|
+
return Math.max(1, Math.floor(value));
|
|
8771
|
+
}
|
|
8772
|
+
function fanOutPositions(input) {
|
|
8773
|
+
const count = Number.isFinite(input.count) ? Math.floor(input.count) : 0;
|
|
8774
|
+
if (count < 1) return [];
|
|
8775
|
+
const gap = resolveGap(input.gap);
|
|
8776
|
+
const maxPerColumn = positiveInt(input.maxPerColumn, DEFAULT_MAX_PER_COLUMN);
|
|
8777
|
+
const columns = Math.min(count, positiveInt(input.columns, Math.ceil(count / maxPerColumn)));
|
|
8778
|
+
const rows = Math.ceil(count / columns);
|
|
8779
|
+
const { position, size } = input.source;
|
|
8780
|
+
const blockHeight = rows * input.nodeSize.h + (rows - 1) * gap.y;
|
|
8781
|
+
const left = Math.round(position.x + size.w + gap.x);
|
|
8782
|
+
const top = Math.round(position.y + size.h / 2 - blockHeight / 2);
|
|
8783
|
+
const positions = [];
|
|
8784
|
+
for (let index = 0; index < count; index += 1) {
|
|
8785
|
+
const column = index % columns;
|
|
8786
|
+
const row = Math.floor(index / columns);
|
|
8787
|
+
positions.push({
|
|
8788
|
+
x: left + column * (input.nodeSize.w + gap.x),
|
|
8789
|
+
y: top + row * (input.nodeSize.h + gap.y)
|
|
8790
|
+
});
|
|
8791
|
+
}
|
|
8792
|
+
return positions;
|
|
8793
|
+
}
|
|
8794
|
+
var DEFAULT_PLACEMENT_GAP = 40;
|
|
8795
|
+
function uniqueAscending(values) {
|
|
8796
|
+
return [...new Set(values)].sort((a, b) => a - b);
|
|
8797
|
+
}
|
|
8798
|
+
function blockIsFree(rects, bounds, dx, dy, obstacles, gap) {
|
|
8799
|
+
const movedBounds = { ...bounds, x: bounds.x + dx, y: bounds.y + dy };
|
|
8800
|
+
for (const obstacle of obstacles) {
|
|
8801
|
+
if (!rectsCollide(movedBounds, obstacle, gap)) continue;
|
|
8802
|
+
for (const rect of rects) {
|
|
8803
|
+
if (rectsCollide({ ...rect, x: rect.x + dx, y: rect.y + dy }, obstacle, gap)) return false;
|
|
8804
|
+
}
|
|
8805
|
+
}
|
|
8806
|
+
return true;
|
|
8807
|
+
}
|
|
8808
|
+
function placeWithoutOverlap(doc, rects, options) {
|
|
8809
|
+
if (rects.length === 0) return [];
|
|
8810
|
+
const gap = resolveGap(options.gap);
|
|
8811
|
+
const original = boundsOf(rects);
|
|
8812
|
+
const baseDx = options.near === void 0 ? 0 : options.near.x - original.x;
|
|
8813
|
+
const baseDy = options.near === void 0 ? 0 : options.near.y - original.y;
|
|
8814
|
+
const block = rects.map((rect) => ({ ...rect, x: rect.x + baseDx, y: rect.y + baseDy }));
|
|
8815
|
+
const bounds = boundsOf(block);
|
|
8816
|
+
const obstacles = obstaclesOf(doc, options.ignore);
|
|
8817
|
+
const maxDown = options.maxDown ?? 3 * (bounds.h + gap.y);
|
|
8818
|
+
const rightSteps = uniqueAscending([
|
|
8819
|
+
0,
|
|
8820
|
+
...obstacles.map((o) => o.x + o.w + gap.x - bounds.x).filter((dx) => dx > 0)
|
|
8821
|
+
]);
|
|
8822
|
+
const downSteps = uniqueAscending([
|
|
8823
|
+
0,
|
|
8824
|
+
...obstacles.map((o) => o.y + o.h + gap.y - bounds.y).filter((dy) => dy > 0 && dy <= maxDown)
|
|
8825
|
+
]);
|
|
8826
|
+
for (const dx of rightSteps) {
|
|
8827
|
+
for (const dy of downSteps) {
|
|
8828
|
+
if (blockIsFree(block, bounds, dx, dy, obstacles, gap)) {
|
|
8829
|
+
return block.map((rect) => ({ ...rect, x: rect.x + dx, y: rect.y + dy }));
|
|
8830
|
+
}
|
|
8831
|
+
}
|
|
8832
|
+
}
|
|
8833
|
+
return block;
|
|
8834
|
+
}
|
|
8835
|
+
function byDistance(a, b) {
|
|
8836
|
+
return a.distance - b.distance || b.y - a.y || b.x - a.x;
|
|
8837
|
+
}
|
|
8838
|
+
function findFreeSpot(doc, size, near, options = {}) {
|
|
8839
|
+
const gap = resolveGap(options.gap ?? DEFAULT_PLACEMENT_GAP);
|
|
8840
|
+
const obstacles = obstaclesOf(doc, options.ignore);
|
|
8841
|
+
const xs = uniqueAscending([
|
|
8842
|
+
near.x,
|
|
8843
|
+
...obstacles.flatMap((o) => [o.x + o.w + gap.x, o.x - gap.x - size.w])
|
|
8844
|
+
]);
|
|
8845
|
+
const candidates = xs.map((x) => {
|
|
8846
|
+
const blocked = obstacles.filter((o) => x < o.x + o.w + gap.x && o.x < x + size.w + gap.x).map((o) => ({ from: o.y - gap.y - size.h, to: o.y + o.h + gap.y })).sort((a, b) => a.from - b.from);
|
|
8847
|
+
let y = near.y;
|
|
8848
|
+
let wall;
|
|
8849
|
+
for (const interval of blocked) {
|
|
8850
|
+
if (wall !== void 0 && interval.from < wall.to) {
|
|
8851
|
+
wall.to = Math.max(wall.to, interval.to);
|
|
8852
|
+
} else if (wall !== void 0 && wall.from < near.y && near.y < wall.to) {
|
|
8853
|
+
break;
|
|
8854
|
+
} else {
|
|
8855
|
+
wall = { ...interval };
|
|
8856
|
+
}
|
|
8857
|
+
}
|
|
8858
|
+
if (wall !== void 0 && wall.from < near.y && near.y < wall.to) {
|
|
8859
|
+
y = wall.to - near.y <= near.y - wall.from ? wall.to : wall.from;
|
|
8860
|
+
}
|
|
8861
|
+
return { x, y, distance: Math.hypot(x - near.x, y - near.y) };
|
|
8862
|
+
});
|
|
8863
|
+
const [best] = candidates.sort(byDistance);
|
|
8864
|
+
if (best === void 0) return { x: near.x, y: near.y };
|
|
8865
|
+
return { x: best.x, y: best.y };
|
|
8866
|
+
}
|
|
8867
|
+
function topLevelOf(doc, nodeId3) {
|
|
8868
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8869
|
+
let current = nodeId3;
|
|
8870
|
+
for (; ; ) {
|
|
8871
|
+
if (seen.has(current) || !Object.hasOwn(doc.nodes, current)) return void 0;
|
|
8872
|
+
seen.add(current);
|
|
8873
|
+
const node = doc.nodes[current];
|
|
8874
|
+
if (node === void 0) return void 0;
|
|
8875
|
+
if (node.parentId === null) return current;
|
|
8876
|
+
current = node.parentId;
|
|
8877
|
+
}
|
|
8878
|
+
}
|
|
8879
|
+
function pushTo(map, key, value) {
|
|
8880
|
+
const list = map.get(key);
|
|
8881
|
+
if (list === void 0) map.set(key, [value]);
|
|
8882
|
+
else if (!list.includes(value)) list.push(value);
|
|
8883
|
+
}
|
|
8884
|
+
function buildLayoutGraph(doc, nodeIds) {
|
|
8885
|
+
const wanted = nodeIds === void 0 ? void 0 : new Set(nodeIds);
|
|
8886
|
+
const nodes = Object.values(doc.nodes).filter((node) => node.parentId === null && (wanted === void 0 || wanted.has(node.id))).sort(byScreenOrder);
|
|
8887
|
+
const rank = new Map(nodes.map((node, index) => [node.id, index]));
|
|
8888
|
+
const byRank = (a, b) => (rank.get(a) ?? 0) - (rank.get(b) ?? 0);
|
|
8889
|
+
const forward = /* @__PURE__ */ new Map();
|
|
8890
|
+
const neighbors = /* @__PURE__ */ new Map();
|
|
8891
|
+
for (const node of nodes) {
|
|
8892
|
+
forward.set(node.id, []);
|
|
8893
|
+
neighbors.set(node.id, []);
|
|
8894
|
+
}
|
|
8895
|
+
const branchSiblings = /* @__PURE__ */ new Map();
|
|
8896
|
+
const inputSiblings = /* @__PURE__ */ new Map();
|
|
8897
|
+
const edgeIds = Object.keys(doc.edges).sort(compareText);
|
|
8898
|
+
for (const edgeId of edgeIds) {
|
|
8899
|
+
const edge = doc.edges[edgeId];
|
|
8900
|
+
if (edge === void 0) continue;
|
|
8901
|
+
const source = topLevelOf(doc, edge.source);
|
|
8902
|
+
const target = topLevelOf(doc, edge.target);
|
|
8903
|
+
if (source === void 0 || target === void 0 || source === target) continue;
|
|
8904
|
+
if (!rank.has(source) || !rank.has(target)) continue;
|
|
8905
|
+
pushTo(forward, source, target);
|
|
8906
|
+
pushTo(neighbors, source, target);
|
|
8907
|
+
pushTo(neighbors, target, source);
|
|
8908
|
+
if (typeof edge.data["branch"] !== "number") {
|
|
8909
|
+
pushTo(branchSiblings, `${edge.source}\0${edge.sourcePort}`, target);
|
|
8910
|
+
}
|
|
8911
|
+
if (typeof edge.data["order"] !== "number") {
|
|
8912
|
+
pushTo(inputSiblings, `${edge.target}\0${edge.targetPort}`, source);
|
|
8913
|
+
}
|
|
8914
|
+
}
|
|
8915
|
+
for (const list of forward.values()) list.sort(byRank);
|
|
8916
|
+
for (const list of neighbors.values()) list.sort(byRank);
|
|
8917
|
+
const successors = withoutBackEdges(nodes, forward);
|
|
8918
|
+
const predecessors = new Map(nodes.map((node) => [node.id, []]));
|
|
8919
|
+
for (const node of nodes) {
|
|
8920
|
+
for (const target of successors.get(node.id) ?? []) predecessors.get(target)?.push(node.id);
|
|
8921
|
+
}
|
|
8922
|
+
const orderedSiblings = [...branchSiblings.values(), ...inputSiblings.values()].filter((group) => group.length > 1).map((group) => [...group].sort(byRank));
|
|
8923
|
+
return { nodes, rank, successors, predecessors, neighbors, orderedSiblings };
|
|
8924
|
+
}
|
|
8925
|
+
function withoutBackEdges(nodes, forward) {
|
|
8926
|
+
const hasIncoming = /* @__PURE__ */ new Set();
|
|
8927
|
+
for (const targets of forward.values()) for (const target of targets) hasIncoming.add(target);
|
|
8928
|
+
const starts = [
|
|
8929
|
+
...nodes.filter((node) => !hasIncoming.has(node.id)),
|
|
8930
|
+
...nodes.filter((node) => hasIncoming.has(node.id)).sort(
|
|
8931
|
+
(a, b) => a.position.x - b.position.x || a.position.y - b.position.y || compareText(a.id, b.id)
|
|
8932
|
+
)
|
|
8933
|
+
];
|
|
8934
|
+
const kept = new Map(nodes.map((node) => [node.id, []]));
|
|
8935
|
+
const state = /* @__PURE__ */ new Map();
|
|
8936
|
+
for (const start of starts) {
|
|
8937
|
+
if (state.has(start.id)) continue;
|
|
8938
|
+
const stack = [{ id: start.id, next: 0 }];
|
|
8939
|
+
state.set(start.id, "open");
|
|
8940
|
+
for (let frame = stack[stack.length - 1]; frame !== void 0; frame = stack[stack.length - 1]) {
|
|
8941
|
+
const targets = forward.get(frame.id) ?? [];
|
|
8942
|
+
const target = targets[frame.next];
|
|
8943
|
+
if (target === void 0) {
|
|
8944
|
+
state.set(frame.id, "done");
|
|
8945
|
+
stack.pop();
|
|
8946
|
+
continue;
|
|
8947
|
+
}
|
|
8948
|
+
frame.next += 1;
|
|
8949
|
+
const seen = state.get(target);
|
|
8950
|
+
if (seen === "open") continue;
|
|
8951
|
+
kept.get(frame.id)?.push(target);
|
|
8952
|
+
if (seen === void 0) {
|
|
8953
|
+
state.set(target, "open");
|
|
8954
|
+
stack.push({ id: target, next: 0 });
|
|
8955
|
+
}
|
|
8956
|
+
}
|
|
8957
|
+
}
|
|
8958
|
+
return kept;
|
|
8959
|
+
}
|
|
8960
|
+
function assignLayers(graph, ids) {
|
|
8961
|
+
const pending = /* @__PURE__ */ new Map();
|
|
8962
|
+
for (const id of ids) pending.set(id, graph.predecessors.get(id)?.length ?? 0);
|
|
8963
|
+
const layer = /* @__PURE__ */ new Map();
|
|
8964
|
+
const queue = ids.filter((id) => pending.get(id) === 0);
|
|
8965
|
+
for (const id of queue) layer.set(id, 0);
|
|
8966
|
+
for (let head = 0; head < queue.length; head += 1) {
|
|
8967
|
+
const id = queue[head];
|
|
8968
|
+
if (id === void 0) continue;
|
|
8969
|
+
const current = layer.get(id) ?? 0;
|
|
8970
|
+
for (const target of graph.successors.get(id) ?? []) {
|
|
8971
|
+
layer.set(target, Math.max(layer.get(target) ?? 0, current + 1));
|
|
8972
|
+
const left = (pending.get(target) ?? 0) - 1;
|
|
8973
|
+
pending.set(target, left);
|
|
8974
|
+
if (left === 0) queue.push(target);
|
|
8975
|
+
}
|
|
8976
|
+
}
|
|
8977
|
+
for (const id of ids) {
|
|
8978
|
+
const targets = graph.successors.get(id) ?? [];
|
|
8979
|
+
if ((graph.predecessors.get(id)?.length ?? 0) > 0 || targets.length === 0) continue;
|
|
8980
|
+
layer.set(id, Math.min(...targets.map((target) => layer.get(target) ?? 1)) - 1);
|
|
8981
|
+
}
|
|
8982
|
+
return layer;
|
|
8983
|
+
}
|
|
8984
|
+
function splitComponents(graph) {
|
|
8985
|
+
const components = [];
|
|
8986
|
+
const isolated = [];
|
|
8987
|
+
const visited = /* @__PURE__ */ new Set();
|
|
8988
|
+
for (const node of graph.nodes) {
|
|
8989
|
+
if (visited.has(node.id)) continue;
|
|
8990
|
+
visited.add(node.id);
|
|
8991
|
+
if ((graph.neighbors.get(node.id)?.length ?? 0) === 0) {
|
|
8992
|
+
isolated.push(node.id);
|
|
8993
|
+
continue;
|
|
8994
|
+
}
|
|
8995
|
+
const members = [node.id];
|
|
8996
|
+
for (let head = 0; head < members.length; head += 1) {
|
|
8997
|
+
const id = members[head];
|
|
8998
|
+
if (id === void 0) continue;
|
|
8999
|
+
for (const next of graph.neighbors.get(id) ?? []) {
|
|
9000
|
+
if (visited.has(next)) continue;
|
|
9001
|
+
visited.add(next);
|
|
9002
|
+
members.push(next);
|
|
9003
|
+
}
|
|
9004
|
+
}
|
|
9005
|
+
members.sort((a, b) => (graph.rank.get(a) ?? 0) - (graph.rank.get(b) ?? 0));
|
|
9006
|
+
components.push(members);
|
|
9007
|
+
}
|
|
9008
|
+
return { components, isolated };
|
|
9009
|
+
}
|
|
9010
|
+
function countCrossings(graph, layers) {
|
|
9011
|
+
let crossings = 0;
|
|
9012
|
+
for (let index = 0; index + 1 < layers.length; index += 1) {
|
|
9013
|
+
const left = layers[index] ?? [];
|
|
9014
|
+
const right = new Map((layers[index + 1] ?? []).map((id, slot) => [id, slot]));
|
|
9015
|
+
const spans = [];
|
|
9016
|
+
left.forEach((id, slot) => {
|
|
9017
|
+
for (const target of graph.successors.get(id) ?? []) {
|
|
9018
|
+
const targetSlot = right.get(target);
|
|
9019
|
+
if (targetSlot !== void 0) spans.push([slot, targetSlot]);
|
|
9020
|
+
}
|
|
9021
|
+
});
|
|
9022
|
+
for (let a = 0; a < spans.length; a += 1) {
|
|
9023
|
+
for (let b = a + 1; b < spans.length; b += 1) {
|
|
9024
|
+
const first = spans[a];
|
|
9025
|
+
const second = spans[b];
|
|
9026
|
+
if (first === void 0 || second === void 0) continue;
|
|
9027
|
+
if ((first[0] - second[0]) * (first[1] - second[1]) < 0) crossings += 1;
|
|
9028
|
+
}
|
|
9029
|
+
}
|
|
9030
|
+
}
|
|
9031
|
+
return crossings;
|
|
9032
|
+
}
|
|
9033
|
+
function reorderLayer(layer, reference, neighborsOf) {
|
|
9034
|
+
const slotOf = new Map(reference.map((id, slot) => [id, slot]));
|
|
9035
|
+
const weight = /* @__PURE__ */ new Map();
|
|
9036
|
+
for (const id of layer) {
|
|
9037
|
+
const slots = neighborsOf(id).flatMap((neighbor) => {
|
|
9038
|
+
const slot = slotOf.get(neighbor);
|
|
9039
|
+
return slot === void 0 ? [] : [slot];
|
|
9040
|
+
});
|
|
9041
|
+
if (slots.length > 0) weight.set(id, slots.reduce((sum, slot) => sum + slot, 0) / slots.length);
|
|
9042
|
+
}
|
|
9043
|
+
const current = new Map(layer.map((id, slot) => [id, slot]));
|
|
9044
|
+
const movable = layer.filter((id) => weight.has(id)).sort(
|
|
9045
|
+
(a, b) => (weight.get(a) ?? 0) - (weight.get(b) ?? 0) || (current.get(a) ?? 0) - (current.get(b) ?? 0)
|
|
9046
|
+
);
|
|
9047
|
+
let next = 0;
|
|
9048
|
+
return layer.map((id) => weight.has(id) ? movable[next++] ?? id : id);
|
|
9049
|
+
}
|
|
9050
|
+
function restoreSiblingOrder(graph, layer) {
|
|
9051
|
+
const result = [...layer];
|
|
9052
|
+
for (const group of graph.orderedSiblings) {
|
|
9053
|
+
const members = new Set(group);
|
|
9054
|
+
const slots = [];
|
|
9055
|
+
result.forEach((id, slot) => {
|
|
9056
|
+
if (members.has(id)) slots.push(slot);
|
|
9057
|
+
});
|
|
9058
|
+
if (slots.length < 2) continue;
|
|
9059
|
+
const present = group.filter((id) => result.includes(id));
|
|
9060
|
+
slots.forEach((slot, index) => {
|
|
9061
|
+
const id = present[index];
|
|
9062
|
+
if (id !== void 0) result[slot] = id;
|
|
9063
|
+
});
|
|
9064
|
+
}
|
|
9065
|
+
return result;
|
|
9066
|
+
}
|
|
9067
|
+
function orderLayers(graph, initial, sweeps) {
|
|
9068
|
+
let layers = initial.map((layer) => [...layer]);
|
|
9069
|
+
let best = layers;
|
|
9070
|
+
let bestCrossings = countCrossings(graph, layers);
|
|
9071
|
+
for (let pass = 0; pass < sweeps && bestCrossings > 0; pass += 1) {
|
|
9072
|
+
const forward = pass % 2 === 0;
|
|
9073
|
+
const next = layers.map((layer) => [...layer]);
|
|
9074
|
+
const order = next.map((_, index) => index);
|
|
9075
|
+
if (!forward) order.reverse();
|
|
9076
|
+
for (const index of order) {
|
|
9077
|
+
const reference = next[forward ? index - 1 : index + 1];
|
|
9078
|
+
const layer = next[index];
|
|
9079
|
+
if (reference === void 0 || layer === void 0) continue;
|
|
9080
|
+
const neighborsOf = (id) => (forward ? graph.predecessors.get(id) : graph.successors.get(id)) ?? [];
|
|
9081
|
+
next[index] = restoreSiblingOrder(graph, reorderLayer(layer, reference, neighborsOf));
|
|
9082
|
+
}
|
|
9083
|
+
layers = next;
|
|
9084
|
+
const crossings = countCrossings(graph, layers);
|
|
9085
|
+
if (crossings < bestCrossings) {
|
|
9086
|
+
best = layers;
|
|
9087
|
+
bestCrossings = crossings;
|
|
9088
|
+
}
|
|
9089
|
+
}
|
|
9090
|
+
return best;
|
|
9091
|
+
}
|
|
9092
|
+
var DEFAULT_TIDY_GAP_X = 120;
|
|
9093
|
+
var DEFAULT_TIDY_GAP_Y = 48;
|
|
9094
|
+
var DEFAULT_TIDY_SWEEPS = 4;
|
|
9095
|
+
function layoutComponent(doc, graph, members, gapX, gapY, sweeps) {
|
|
9096
|
+
const layerOf = assignLayers(graph, members);
|
|
9097
|
+
const initial = [];
|
|
9098
|
+
for (const id of members) {
|
|
9099
|
+
const index = layerOf.get(id) ?? 0;
|
|
9100
|
+
(initial[index] ??= []).push(id);
|
|
9101
|
+
}
|
|
9102
|
+
const layers = orderLayers(
|
|
9103
|
+
graph,
|
|
9104
|
+
Array.from(initial, (layer) => layer ?? []).filter((layer) => layer.length > 0),
|
|
9105
|
+
sweeps
|
|
9106
|
+
);
|
|
9107
|
+
const columns = layers.map((layer) => {
|
|
9108
|
+
const nodes = layer.flatMap((id) => {
|
|
9109
|
+
const node = doc.nodes[id];
|
|
9110
|
+
return node === void 0 ? [] : [node];
|
|
9111
|
+
});
|
|
9112
|
+
const width2 = Math.max(...nodes.map((node) => node.size.w));
|
|
9113
|
+
const height = nodes.reduce((sum, node) => sum + node.size.h, 0) + (nodes.length - 1) * gapY;
|
|
9114
|
+
return { nodes, width: width2, height };
|
|
9115
|
+
});
|
|
9116
|
+
const tallest = Math.max(...columns.map((column) => column.height));
|
|
9117
|
+
const placed = [];
|
|
9118
|
+
let x = 0;
|
|
9119
|
+
for (const column of columns) {
|
|
9120
|
+
let y = Math.round((tallest - column.height) / 2);
|
|
9121
|
+
for (const node of column.nodes) {
|
|
9122
|
+
placed.push({ id: node.id, rect: { x, y, w: node.size.w, h: node.size.h } });
|
|
9123
|
+
y += node.size.h + gapY;
|
|
9124
|
+
}
|
|
9125
|
+
x += column.width + gapX;
|
|
9126
|
+
}
|
|
9127
|
+
return placed;
|
|
9128
|
+
}
|
|
9129
|
+
function layoutStrip(nodes, width2, gapX, gapY) {
|
|
9130
|
+
const placed = [];
|
|
9131
|
+
let x = 0;
|
|
9132
|
+
let y = 0;
|
|
9133
|
+
let shelfHeight = 0;
|
|
9134
|
+
for (const node of nodes) {
|
|
9135
|
+
if (x > 0 && x + node.size.w > width2) {
|
|
9136
|
+
x = 0;
|
|
9137
|
+
y += shelfHeight + gapY;
|
|
9138
|
+
shelfHeight = 0;
|
|
9139
|
+
}
|
|
9140
|
+
placed.push({ id: node.id, rect: { x, y, w: node.size.w, h: node.size.h } });
|
|
9141
|
+
x += node.size.w + gapX;
|
|
9142
|
+
shelfHeight = Math.max(shelfHeight, node.size.h);
|
|
9143
|
+
}
|
|
9144
|
+
return placed;
|
|
9145
|
+
}
|
|
9146
|
+
function shifted(placed, dx, dy) {
|
|
9147
|
+
return placed.map(({ id, rect }) => ({ id, rect: { ...rect, x: rect.x + dx, y: rect.y + dy } }));
|
|
9148
|
+
}
|
|
9149
|
+
function tidyUp(doc, options = {}) {
|
|
9150
|
+
const gapX = options.gapX ?? DEFAULT_TIDY_GAP_X;
|
|
9151
|
+
const gapY = options.gapY ?? DEFAULT_TIDY_GAP_Y;
|
|
9152
|
+
const componentGap = options.componentGap ?? gapY * 2;
|
|
9153
|
+
const sweeps = options.sweeps ?? DEFAULT_TIDY_SWEEPS;
|
|
9154
|
+
const graph = buildLayoutGraph(doc, options.nodeIds);
|
|
9155
|
+
if (graph.nodes.length === 0) return /* @__PURE__ */ new Map();
|
|
9156
|
+
const { components, isolated } = splitComponents(graph);
|
|
9157
|
+
let placed = [];
|
|
9158
|
+
let cursorY = 0;
|
|
9159
|
+
let widest = 0;
|
|
9160
|
+
for (const members of components) {
|
|
9161
|
+
const block = layoutComponent(doc, graph, members, gapX, gapY, sweeps);
|
|
9162
|
+
const bounds = boundsOf(block.map((item) => item.rect));
|
|
9163
|
+
placed = placed.concat(shifted(block, 0, cursorY));
|
|
9164
|
+
cursorY += bounds.h + componentGap;
|
|
9165
|
+
widest = Math.max(widest, bounds.w);
|
|
9166
|
+
}
|
|
9167
|
+
if (isolated.length > 0) {
|
|
9168
|
+
const loose = graph.nodes.filter((node) => isolated.includes(node.id));
|
|
9169
|
+
const area = loose.reduce((sum, node) => sum + (node.size.w + gapX) * (node.size.h + gapY), 0);
|
|
9170
|
+
const stripWidth = Math.max(widest, Math.sqrt(area * 1.6));
|
|
9171
|
+
placed = placed.concat(shifted(layoutStrip(loose, stripWidth, gapX, gapY), 0, cursorY));
|
|
9172
|
+
}
|
|
9173
|
+
const anchor = boundsOf(graph.nodes.map(rectOf2));
|
|
9174
|
+
const anchored = shifted(placed, Math.round(anchor.x), Math.round(anchor.y));
|
|
9175
|
+
const scope = graph.nodes.map((node) => node.id);
|
|
9176
|
+
const others = obstaclesOf(doc, scope);
|
|
9177
|
+
const touching = { x: 0, y: 0 };
|
|
9178
|
+
const covers = anchored.some(
|
|
9179
|
+
({ rect }) => others.some((other) => rectsCollide(rect, other, touching))
|
|
9180
|
+
);
|
|
9181
|
+
const rects = covers ? placeWithoutOverlap(
|
|
9182
|
+
doc,
|
|
9183
|
+
anchored.map((item) => item.rect),
|
|
9184
|
+
{ gap: { x: gapX, y: gapY }, ignore: scope }
|
|
9185
|
+
) : anchored.map((item) => item.rect);
|
|
9186
|
+
const positions = /* @__PURE__ */ new Map();
|
|
9187
|
+
anchored.forEach(({ id }, index) => {
|
|
9188
|
+
const rect = rects[index];
|
|
9189
|
+
if (rect !== void 0) positions.set(id, { x: rect.x, y: rect.y });
|
|
9190
|
+
});
|
|
9191
|
+
return positions;
|
|
9192
|
+
}
|
|
9193
|
+
function moveOps(positions) {
|
|
9194
|
+
const latest = /* @__PURE__ */ new Map();
|
|
9195
|
+
for (const [nodeId3, point2] of positions) latest.set(nodeId3, point2);
|
|
9196
|
+
const ops = [...latest.keys()].sort(compareText).flatMap((nodeId3) => {
|
|
9197
|
+
const point2 = latest.get(nodeId3);
|
|
9198
|
+
if (point2 === void 0) return [];
|
|
9199
|
+
return [
|
|
9200
|
+
{ type: "node.set", nodeId: nodeId3, path: "position", value: propValue({ x: point2.x, y: point2.y }) }
|
|
9201
|
+
];
|
|
9202
|
+
});
|
|
9203
|
+
return { type: "batch", ops };
|
|
9204
|
+
}
|
|
9205
|
+
function tidyUpOps(doc, options = {}) {
|
|
9206
|
+
const moved = [...tidyUp(doc, options)].filter(([nodeId3, point2]) => {
|
|
9207
|
+
const node = doc.nodes[nodeId3];
|
|
9208
|
+
return node !== void 0 && (node.position.x !== point2.x || node.position.y !== point2.y);
|
|
9209
|
+
});
|
|
9210
|
+
return moveOps(moved);
|
|
9211
|
+
}
|
|
9212
|
+
var MAX_REPLAY = 200;
|
|
9213
|
+
function tryApplyOp(doc, op) {
|
|
9214
|
+
const result = step(doc, op);
|
|
9215
|
+
return typeof result === "string" ? { ok: false, reason: result } : { ok: true, doc: result };
|
|
9216
|
+
}
|
|
9217
|
+
function tryApplyEnvelope(doc, envelope2) {
|
|
9218
|
+
if (opEnvelopeBytes(envelope2) > MAX_OP_BYTES2) return { ok: false, reason: "too-large" };
|
|
9219
|
+
return tryApplyOp(doc, envelope2.op);
|
|
9220
|
+
}
|
|
9221
|
+
function applyConfirmed2(doc, envelope2) {
|
|
9222
|
+
if (envelope2.seq === null) {
|
|
9223
|
+
throw new Error(`applyConfirmed recebeu o envelope ${envelope2.id} sem seq`);
|
|
9224
|
+
}
|
|
9225
|
+
const next = applyOps(doc, [envelope2.op]).doc;
|
|
9226
|
+
return { ...next, version: envelope2.seq };
|
|
9227
|
+
}
|
|
9228
|
+
function step(doc, op) {
|
|
9229
|
+
switch (op.type) {
|
|
9230
|
+
case "batch": {
|
|
9231
|
+
let current = doc;
|
|
9232
|
+
for (const inner of op.ops) {
|
|
9233
|
+
const result = step(current, inner);
|
|
9234
|
+
if (typeof result === "string") return result;
|
|
9235
|
+
current = result;
|
|
9236
|
+
}
|
|
9237
|
+
return current;
|
|
9238
|
+
}
|
|
9239
|
+
case "node.set":
|
|
9240
|
+
case "history.append":
|
|
9241
|
+
if (doc.nodes[op.nodeId] === void 0) return "node-missing";
|
|
9242
|
+
break;
|
|
9243
|
+
case "edge.add":
|
|
9244
|
+
if (doc.nodes[op.edge.source] === void 0 || doc.nodes[op.edge.target] === void 0) {
|
|
9245
|
+
return "edge-endpoint-missing";
|
|
9246
|
+
}
|
|
9247
|
+
break;
|
|
9248
|
+
default:
|
|
9249
|
+
break;
|
|
9250
|
+
}
|
|
9251
|
+
try {
|
|
9252
|
+
return applyOps(doc, [op]).doc;
|
|
9253
|
+
} catch {
|
|
9254
|
+
return "invalid-op";
|
|
9255
|
+
}
|
|
9256
|
+
}
|
|
9257
|
+
function defaultScheduler() {
|
|
9258
|
+
const host = globalThis;
|
|
9259
|
+
return {
|
|
9260
|
+
setTimeout: (callback, ms) => host.setTimeout(callback, ms),
|
|
9261
|
+
clearTimeout: (handle) => host.clearTimeout(handle)
|
|
9262
|
+
};
|
|
9263
|
+
}
|
|
9264
|
+
var OpSyncClient = class {
|
|
9265
|
+
store;
|
|
9266
|
+
transport;
|
|
9267
|
+
scheduler;
|
|
9268
|
+
batchMs;
|
|
9269
|
+
gapGraceMs;
|
|
9270
|
+
retryMs;
|
|
9271
|
+
maxRetryMs;
|
|
9272
|
+
maxBatch;
|
|
9273
|
+
onDiscard;
|
|
9274
|
+
onTransportError;
|
|
9275
|
+
confirmed;
|
|
9276
|
+
lastSeq;
|
|
9277
|
+
buffer = /* @__PURE__ */ new Map();
|
|
9278
|
+
pending = [];
|
|
9279
|
+
online = false;
|
|
9280
|
+
started = false;
|
|
9281
|
+
stopped = false;
|
|
9282
|
+
commitInFlight = false;
|
|
9283
|
+
syncInFlight = false;
|
|
9284
|
+
snapshotInFlight = false;
|
|
9285
|
+
flushTimer = null;
|
|
9286
|
+
gapTimer = null;
|
|
9287
|
+
retryTimer = null;
|
|
9288
|
+
retryDelay;
|
|
9289
|
+
unsubscribe = [];
|
|
9290
|
+
stats = {
|
|
9291
|
+
commits: 0,
|
|
9292
|
+
commitFailures: 0,
|
|
9293
|
+
syncs: 0,
|
|
9294
|
+
gapSyncs: 0,
|
|
9295
|
+
snapshots: 0,
|
|
9296
|
+
discarded: 0,
|
|
9297
|
+
echoes: 0
|
|
9298
|
+
};
|
|
9299
|
+
constructor(options) {
|
|
9300
|
+
this.store = options.store;
|
|
9301
|
+
this.transport = options.transport;
|
|
9302
|
+
this.scheduler = options.scheduler ?? defaultScheduler();
|
|
9303
|
+
this.batchMs = options.batchMs ?? 200;
|
|
9304
|
+
this.gapGraceMs = options.gapGraceMs ?? 300;
|
|
9305
|
+
this.retryMs = options.retryMs ?? 1e3;
|
|
9306
|
+
this.maxRetryMs = options.maxRetryMs ?? 3e4;
|
|
9307
|
+
this.maxBatch = options.maxBatch ?? 100;
|
|
9308
|
+
this.onDiscard = options.onDiscard;
|
|
9309
|
+
this.onTransportError = options.onTransportError;
|
|
9310
|
+
this.retryDelay = this.retryMs;
|
|
9311
|
+
this.lastSeq = options.seq;
|
|
9312
|
+
this.confirmed = { ...this.store.getDoc(), version: options.seq };
|
|
9313
|
+
}
|
|
9314
|
+
/** Entra na sala, passa a ouvir o store e pede o que perdeu desde `seq`. */
|
|
9315
|
+
start() {
|
|
9316
|
+
if (this.started) return;
|
|
9317
|
+
this.started = true;
|
|
9318
|
+
this.unsubscribe.push(
|
|
9319
|
+
this.store.subscribeEnvelopes((envelope2) => this.enqueue(envelope2)),
|
|
9320
|
+
this.transport.subscribe({
|
|
9321
|
+
onOps: (envelopes) => this.receive(envelopes),
|
|
9322
|
+
onResync: () => this.requestSnapshot(),
|
|
9323
|
+
onConnectionChange: (online) => this.setOnline(online)
|
|
9324
|
+
})
|
|
9325
|
+
);
|
|
9326
|
+
this.online = this.transport.isOnline();
|
|
9327
|
+
if (this.online) this.requestSync();
|
|
9328
|
+
}
|
|
9329
|
+
/** Sai da sala e para os relógios. Pendentes ficam onde estão (`pendingEnvelopes`). */
|
|
9330
|
+
stop() {
|
|
9331
|
+
this.stopped = true;
|
|
9332
|
+
for (const off of this.unsubscribe) off();
|
|
9333
|
+
this.unsubscribe = [];
|
|
9334
|
+
this.clearTimer("flushTimer");
|
|
9335
|
+
this.clearTimer("gapTimer");
|
|
9336
|
+
this.clearTimer("retryTimer");
|
|
9337
|
+
}
|
|
9338
|
+
/** Commita já, sem esperar a janela do lote. */
|
|
9339
|
+
flushNow() {
|
|
9340
|
+
this.clearTimer("flushTimer");
|
|
9341
|
+
this.flush();
|
|
9342
|
+
}
|
|
9343
|
+
getStatus() {
|
|
9344
|
+
const inFlight = this.pending.filter((item) => item.inFlight).length;
|
|
9345
|
+
return {
|
|
9346
|
+
online: this.online,
|
|
9347
|
+
lastSeq: this.lastSeq,
|
|
9348
|
+
pending: this.pending.length,
|
|
9349
|
+
inFlight,
|
|
9350
|
+
buffered: this.buffer.size,
|
|
9351
|
+
settled: this.pending.length === 0 && this.buffer.size === 0 && !this.commitInFlight && !this.syncInFlight && !this.snapshotInFlight
|
|
9352
|
+
};
|
|
9353
|
+
}
|
|
9354
|
+
/** A foto confirmada, sem pendentes. */
|
|
9355
|
+
getConfirmedDoc() {
|
|
9356
|
+
return this.confirmed;
|
|
9357
|
+
}
|
|
9358
|
+
/** As pendentes, em ordem. Para o cache local guardar até voltarem. */
|
|
9359
|
+
pendingEnvelopes() {
|
|
9360
|
+
return this.pending.map((item) => item.envelope);
|
|
9361
|
+
}
|
|
9362
|
+
// ------------------------------------------------------------------ entrada
|
|
9363
|
+
enqueue(envelope2) {
|
|
9364
|
+
if (this.stopped) return;
|
|
9365
|
+
if (opEnvelopeBytes(envelope2) > MAX_OP_BYTES2) {
|
|
9366
|
+
this.discard(envelope2, "too-large", "too-large");
|
|
9367
|
+
this.rebuild();
|
|
9368
|
+
return;
|
|
9369
|
+
}
|
|
9370
|
+
this.pending.push({ envelope: envelope2, sent: false, inFlight: false });
|
|
9371
|
+
this.scheduleFlush();
|
|
9372
|
+
}
|
|
9373
|
+
receive(envelopes) {
|
|
9374
|
+
if (this.stopped) return;
|
|
9375
|
+
let changed = false;
|
|
9376
|
+
for (const envelope2 of envelopes) {
|
|
9377
|
+
if (envelope2.seq === null) continue;
|
|
9378
|
+
if (this.findPending(envelope2.id) >= 0) this.stats.echoes += 1;
|
|
9379
|
+
if (this.confirm(envelope2.id, envelope2.seq, envelope2)) changed = true;
|
|
9380
|
+
}
|
|
9381
|
+
if (changed) this.settle();
|
|
9382
|
+
else this.checkGap();
|
|
9383
|
+
}
|
|
9384
|
+
/**
|
|
9385
|
+
* Registra que `opId` foi confirmado com `seq`. Se é pendente nossa, sai da
|
|
9386
|
+
* fila (eco, resposta do commit ou replay: tanto faz qual chega primeiro).
|
|
9387
|
+
* Devolve se algo mudou.
|
|
9388
|
+
*/
|
|
9389
|
+
confirm(opId, seq, wire) {
|
|
9390
|
+
const index = this.findPending(opId);
|
|
9391
|
+
let envelope2 = wire;
|
|
9392
|
+
if (index >= 0) {
|
|
9393
|
+
const [item] = this.pending.splice(index, 1);
|
|
9394
|
+
envelope2 = item?.envelope;
|
|
9395
|
+
}
|
|
9396
|
+
if (seq <= this.lastSeq) return index >= 0;
|
|
9397
|
+
if (envelope2 === void 0) return index >= 0;
|
|
9398
|
+
if (!this.buffer.has(seq)) this.buffer.set(seq, { ...envelope2, seq });
|
|
9399
|
+
return true;
|
|
9400
|
+
}
|
|
9401
|
+
// ---------------------------------------------------------------- commit
|
|
9402
|
+
scheduleFlush() {
|
|
9403
|
+
if (this.flushTimer !== null || this.stopped) return;
|
|
9404
|
+
this.flushTimer = this.scheduler.setTimeout(() => {
|
|
9405
|
+
this.flushTimer = null;
|
|
9406
|
+
this.flush();
|
|
9407
|
+
}, this.batchMs);
|
|
9408
|
+
}
|
|
9409
|
+
flush() {
|
|
9410
|
+
if (this.stopped || !this.online || this.commitInFlight) return;
|
|
9411
|
+
const batch = this.pending.slice(0, this.maxBatch);
|
|
9412
|
+
if (batch.length === 0) return;
|
|
9413
|
+
for (const item of batch) {
|
|
9414
|
+
item.sent = true;
|
|
9415
|
+
item.inFlight = true;
|
|
9416
|
+
}
|
|
9417
|
+
this.commitInFlight = true;
|
|
9418
|
+
this.stats.commits += 1;
|
|
9419
|
+
this.transport.commit(batch.map((item) => item.envelope)).then(
|
|
9420
|
+
(response) => this.onCommitted(batch, response),
|
|
9421
|
+
(error2) => this.onCommitFailed(batch, error2)
|
|
9422
|
+
);
|
|
9423
|
+
}
|
|
9424
|
+
onCommitted(batch, response) {
|
|
9425
|
+
this.commitInFlight = false;
|
|
9426
|
+
for (const item of batch) item.inFlight = false;
|
|
9427
|
+
if (this.stopped) return;
|
|
9428
|
+
this.retryDelay = this.retryMs;
|
|
9429
|
+
let changed = false;
|
|
9430
|
+
for (const outcome of response.outcomes) {
|
|
9431
|
+
if ("seq" in outcome) {
|
|
9432
|
+
if (this.confirm(outcome.opId, outcome.seq)) changed = true;
|
|
9433
|
+
} else {
|
|
9434
|
+
const index = this.findPending(outcome.opId);
|
|
9435
|
+
if (index < 0) continue;
|
|
9436
|
+
const [item] = this.pending.splice(index, 1);
|
|
9437
|
+
if (item !== void 0) this.discard(item.envelope, "rejected", outcome.rejected);
|
|
9438
|
+
changed = true;
|
|
9439
|
+
}
|
|
9440
|
+
}
|
|
9441
|
+
if (changed) this.settle();
|
|
9442
|
+
if (this.pending.length > 0) this.flush();
|
|
9443
|
+
}
|
|
9444
|
+
onCommitFailed(batch, error2) {
|
|
9445
|
+
this.commitInFlight = false;
|
|
9446
|
+
for (const item of batch) item.inFlight = false;
|
|
9447
|
+
if (this.stopped) return;
|
|
9448
|
+
this.stats.commitFailures += 1;
|
|
9449
|
+
this.onTransportError?.(error2);
|
|
9450
|
+
this.scheduleRetry();
|
|
9451
|
+
}
|
|
9452
|
+
// ------------------------------------------------------- sync e foto
|
|
9453
|
+
requestSync() {
|
|
9454
|
+
if (this.stopped || !this.online || this.syncInFlight) return;
|
|
9455
|
+
this.syncInFlight = true;
|
|
9456
|
+
this.stats.syncs += 1;
|
|
9457
|
+
this.transport.sync(this.lastSeq).then(
|
|
9458
|
+
(response) => this.onSynced(response),
|
|
9459
|
+
(error2) => {
|
|
9460
|
+
this.syncInFlight = false;
|
|
9461
|
+
if (this.stopped) return;
|
|
9462
|
+
this.onTransportError?.(error2);
|
|
9463
|
+
this.scheduleRetry();
|
|
9464
|
+
}
|
|
9465
|
+
);
|
|
9466
|
+
}
|
|
9467
|
+
onSynced(response) {
|
|
9468
|
+
this.syncInFlight = false;
|
|
9469
|
+
if (this.stopped) return;
|
|
9470
|
+
if (response.status === "resync") {
|
|
9471
|
+
this.requestSnapshot();
|
|
9472
|
+
return;
|
|
9473
|
+
}
|
|
9474
|
+
this.receive(response.envelopes);
|
|
9475
|
+
}
|
|
9476
|
+
requestSnapshot() {
|
|
9477
|
+
if (this.stopped || !this.online || this.snapshotInFlight) return;
|
|
9478
|
+
this.snapshotInFlight = true;
|
|
9479
|
+
this.stats.snapshots += 1;
|
|
9480
|
+
this.transport.snapshot().then(
|
|
9481
|
+
(snapshot) => {
|
|
9482
|
+
this.snapshotInFlight = false;
|
|
9483
|
+
if (this.stopped) return;
|
|
9484
|
+
if (snapshot.seq < this.lastSeq) return;
|
|
9485
|
+
this.confirmed = { ...snapshot.doc, version: snapshot.seq };
|
|
9486
|
+
this.lastSeq = snapshot.seq;
|
|
9487
|
+
this.settle();
|
|
9488
|
+
this.flush();
|
|
9489
|
+
},
|
|
9490
|
+
(error2) => {
|
|
9491
|
+
this.snapshotInFlight = false;
|
|
9492
|
+
if (this.stopped) return;
|
|
9493
|
+
this.onTransportError?.(error2);
|
|
9494
|
+
this.scheduleRetry();
|
|
9495
|
+
}
|
|
9496
|
+
);
|
|
9497
|
+
}
|
|
9498
|
+
// --------------------------------------------------------------- conexão
|
|
9499
|
+
setOnline(online) {
|
|
9500
|
+
if (this.stopped) return;
|
|
9501
|
+
this.online = online;
|
|
9502
|
+
if (!online) return;
|
|
9503
|
+
this.retryDelay = this.retryMs;
|
|
9504
|
+
this.clearTimer("retryTimer");
|
|
9505
|
+
this.resume();
|
|
9506
|
+
}
|
|
9507
|
+
resume() {
|
|
9508
|
+
this.requestSync();
|
|
9509
|
+
this.flush();
|
|
9510
|
+
}
|
|
9511
|
+
scheduleRetry() {
|
|
9512
|
+
if (this.retryTimer !== null || !this.online) return;
|
|
9513
|
+
const delay = this.retryDelay;
|
|
9514
|
+
this.retryDelay = Math.min(this.retryDelay * 2, this.maxRetryMs);
|
|
9515
|
+
this.retryTimer = this.scheduler.setTimeout(() => {
|
|
9516
|
+
this.retryTimer = null;
|
|
9517
|
+
this.resume();
|
|
9518
|
+
}, delay);
|
|
9519
|
+
}
|
|
9520
|
+
// ---------------------------------------------------------- foto e tela
|
|
9521
|
+
/** Avança a foto pelo que é contíguo, reconstrói a tela e confere buraco. */
|
|
9522
|
+
settle() {
|
|
9523
|
+
for (const seq of [...this.buffer.keys()]) {
|
|
9524
|
+
if (seq <= this.lastSeq) this.buffer.delete(seq);
|
|
9525
|
+
}
|
|
9526
|
+
for (; ; ) {
|
|
9527
|
+
const next = this.buffer.get(this.lastSeq + 1);
|
|
9528
|
+
if (next === void 0) break;
|
|
9529
|
+
this.buffer.delete(this.lastSeq + 1);
|
|
9530
|
+
try {
|
|
9531
|
+
this.confirmed = applyConfirmed2(this.confirmed, next);
|
|
9532
|
+
} catch {
|
|
9533
|
+
this.buffer.clear();
|
|
9534
|
+
this.requestSnapshot();
|
|
9535
|
+
break;
|
|
9536
|
+
}
|
|
9537
|
+
this.lastSeq += 1;
|
|
9538
|
+
}
|
|
9539
|
+
this.rebuild();
|
|
9540
|
+
this.checkGap();
|
|
9541
|
+
}
|
|
9542
|
+
/**
|
|
9543
|
+
* A tela = foto confirmada + confirmados à frente do buraco + pendentes.
|
|
9544
|
+
*
|
|
9545
|
+
* Pendente que nunca saiu e não vale mais é descartada aqui. A que já saiu
|
|
9546
|
+
* fica fora da tela, mas na fila, até o servidor dizer o que houve com ela.
|
|
9547
|
+
*/
|
|
9548
|
+
rebuild() {
|
|
9549
|
+
let doc = this.confirmed;
|
|
9550
|
+
for (const seq of [...this.buffer.keys()].sort((a, b) => a - b)) {
|
|
9551
|
+
const envelope2 = this.buffer.get(seq);
|
|
9552
|
+
if (envelope2 === void 0) continue;
|
|
9553
|
+
const verdict = tryApplyEnvelope(doc, envelope2);
|
|
9554
|
+
if (verdict.ok) doc = verdict.doc;
|
|
9555
|
+
}
|
|
9556
|
+
const kept = [];
|
|
9557
|
+
for (const item of this.pending) {
|
|
9558
|
+
const verdict = tryApplyEnvelope(doc, item.envelope);
|
|
9559
|
+
if (verdict.ok) {
|
|
9560
|
+
doc = verdict.doc;
|
|
9561
|
+
kept.push(item);
|
|
9562
|
+
} else if (item.sent) {
|
|
9563
|
+
kept.push(item);
|
|
9564
|
+
} else {
|
|
9565
|
+
this.discard(item.envelope, "not-applicable", verdict.reason);
|
|
9566
|
+
}
|
|
9567
|
+
}
|
|
9568
|
+
this.pending = kept;
|
|
9569
|
+
this.store.replaceDoc(doc.version === this.lastSeq ? doc : { ...doc, version: this.lastSeq });
|
|
9570
|
+
}
|
|
9571
|
+
checkGap() {
|
|
9572
|
+
if (this.buffer.size === 0) {
|
|
9573
|
+
this.clearTimer("gapTimer");
|
|
9574
|
+
return;
|
|
9575
|
+
}
|
|
9576
|
+
if (this.gapTimer !== null) return;
|
|
9577
|
+
this.gapTimer = this.scheduler.setTimeout(() => {
|
|
9578
|
+
this.gapTimer = null;
|
|
9579
|
+
if (this.buffer.size === 0) return;
|
|
9580
|
+
this.stats.gapSyncs += 1;
|
|
9581
|
+
this.requestSync();
|
|
9582
|
+
}, this.gapGraceMs);
|
|
9583
|
+
}
|
|
9584
|
+
// -------------------------------------------------------------- miúdos
|
|
9585
|
+
discard(envelope2, reason, detail) {
|
|
9586
|
+
this.stats.discarded += 1;
|
|
9587
|
+
this.onDiscard?.({ envelope: envelope2, reason, detail });
|
|
9588
|
+
}
|
|
9589
|
+
findPending(opId) {
|
|
9590
|
+
return this.pending.findIndex((item) => item.envelope.id === opId);
|
|
9591
|
+
}
|
|
9592
|
+
clearTimer(name) {
|
|
9593
|
+
const handle = this[name];
|
|
9594
|
+
if (handle === null) return;
|
|
9595
|
+
this.scheduler.clearTimeout(handle);
|
|
9596
|
+
this[name] = null;
|
|
9597
|
+
}
|
|
9598
|
+
};
|
|
9599
|
+
}
|
|
9600
|
+
});
|
|
9601
|
+
|
|
6887
9602
|
// node_modules/@hono/node-server/dist/index.mjs
|
|
6888
9603
|
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
|
|
6889
9604
|
import { Http2ServerRequest } from "http2";
|
|
@@ -22351,8 +25066,19 @@ var LoginExpiredError = class extends ApiError {
|
|
|
22351
25066
|
this.name = "LoginExpiredError";
|
|
22352
25067
|
}
|
|
22353
25068
|
};
|
|
25069
|
+
var ServerBusyError = class extends ApiError {
|
|
25070
|
+
constructor(status, waitS, what) {
|
|
25071
|
+
super(
|
|
25072
|
+
status,
|
|
25073
|
+
`O servidor da BePlus est\xE1 ocupado agora (${status === 0 ? "falha de rede" : `HTTP ${status}`} em ${what}). Nada foi alterado por esta chamada. Tente de novo em ${waitS} s, sem repetir em sequ\xEAncia.`
|
|
25074
|
+
);
|
|
25075
|
+
this.waitS = waitS;
|
|
25076
|
+
this.name = "ServerBusyError";
|
|
25077
|
+
}
|
|
25078
|
+
waitS;
|
|
25079
|
+
};
|
|
22354
25080
|
function apiErrorToUserMessage(err) {
|
|
22355
|
-
if (err instanceof LoginExpiredError) return err.message;
|
|
25081
|
+
if (err instanceof LoginExpiredError || err instanceof ServerBusyError) return err.message;
|
|
22356
25082
|
if (err instanceof ApiError) {
|
|
22357
25083
|
const detail = err.message || "";
|
|
22358
25084
|
switch (err.httpStatus) {
|
|
@@ -22431,6 +25157,26 @@ async function fetchWithAuth(cfg, url, init, what) {
|
|
|
22431
25157
|
}
|
|
22432
25158
|
|
|
22433
25159
|
// src/api/client.ts
|
|
25160
|
+
var retryPolicy = {
|
|
25161
|
+
retries: 4,
|
|
25162
|
+
baseMs: 1e3,
|
|
25163
|
+
capMs: 3e4,
|
|
25164
|
+
/** Passou disso esperando, desiste e devolve "tente em N s" ao agente em vez de segurar a tool. */
|
|
25165
|
+
budgetMs: 45e3,
|
|
25166
|
+
random: Math.random,
|
|
25167
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
|
|
25168
|
+
};
|
|
25169
|
+
var RETRYABLE = /* @__PURE__ */ new Set([0, 429, 503]);
|
|
25170
|
+
function retryAfterMs(res) {
|
|
25171
|
+
const raw = res.headers.get("retry-after");
|
|
25172
|
+
if (!raw) return null;
|
|
25173
|
+
const secs = Number(raw);
|
|
25174
|
+
if (Number.isFinite(secs)) return Math.max(0, secs * 1e3);
|
|
25175
|
+
const at = Date.parse(raw);
|
|
25176
|
+
return Number.isFinite(at) ? Math.max(0, at - Date.now()) : null;
|
|
25177
|
+
}
|
|
25178
|
+
var costCachePolicy = { ttlMs: 10 * 6e4, capacity: 256, now: () => Date.now() };
|
|
25179
|
+
var costCache = /* @__PURE__ */ new Map();
|
|
22434
25180
|
var BeplusClient = class {
|
|
22435
25181
|
constructor(cfg) {
|
|
22436
25182
|
this.cfg = cfg;
|
|
@@ -22438,23 +25184,63 @@ var BeplusClient = class {
|
|
|
22438
25184
|
cfg;
|
|
22439
25185
|
/** Público para os módulos de rota própria (ex.: Canvas) reaproveitarem auth, timeout e erros. */
|
|
22440
25186
|
async request(method, path, opts = {}) {
|
|
25187
|
+
return (await this.requestMeta(method, path, opts)).data;
|
|
25188
|
+
}
|
|
25189
|
+
/** Igual a `request`, mas devolve status e ETag, e trata 304 como resposta (sem corpo). */
|
|
25190
|
+
async requestMeta(method, path, opts = {}) {
|
|
22441
25191
|
const url = new URL(`${opts.base ?? this.cfg.apiBase}${path}`);
|
|
22442
25192
|
if (opts.query) {
|
|
22443
25193
|
for (const [k, v] of Object.entries(opts.query)) {
|
|
22444
25194
|
if (v !== void 0 && v !== null && v !== "") url.searchParams.set(k, String(v));
|
|
22445
25195
|
}
|
|
22446
25196
|
}
|
|
22447
|
-
const
|
|
22448
|
-
|
|
22449
|
-
|
|
22450
|
-
|
|
22451
|
-
|
|
22452
|
-
|
|
22453
|
-
|
|
22454
|
-
|
|
22455
|
-
|
|
22456
|
-
|
|
22457
|
-
|
|
25197
|
+
const retry = opts.retry ?? method === "GET";
|
|
25198
|
+
const p = retryPolicy;
|
|
25199
|
+
const started = Date.now();
|
|
25200
|
+
for (let attempt = 0; ; attempt++) {
|
|
25201
|
+
let res = null;
|
|
25202
|
+
let failure2 = null;
|
|
25203
|
+
try {
|
|
25204
|
+
res = await fetchWithAuth(
|
|
25205
|
+
this.cfg,
|
|
25206
|
+
url,
|
|
25207
|
+
{
|
|
25208
|
+
method,
|
|
25209
|
+
headers: { ...opts.body ? { "Content-Type": "application/json" } : {}, ...opts.headers },
|
|
25210
|
+
body: opts.body ? JSON.stringify(opts.body) : void 0,
|
|
25211
|
+
timeoutMs: opts.timeoutMs ?? 3e4
|
|
25212
|
+
},
|
|
25213
|
+
path
|
|
25214
|
+
);
|
|
25215
|
+
} catch (e) {
|
|
25216
|
+
if (!(e instanceof ApiError) || e.httpStatus !== 0) throw e;
|
|
25217
|
+
failure2 = e;
|
|
25218
|
+
}
|
|
25219
|
+
const status = res ? res.status : 0;
|
|
25220
|
+
if (!retry || !RETRYABLE.has(status)) {
|
|
25221
|
+
if (failure2) throw failure2;
|
|
25222
|
+
return this.read(res, path);
|
|
25223
|
+
}
|
|
25224
|
+
const step = Math.min(p.capMs, p.baseMs * 2 ** attempt);
|
|
25225
|
+
const asked = res ? retryAfterMs(res) : null;
|
|
25226
|
+
const wait = asked ?? step / 2 + p.random() * (step / 2);
|
|
25227
|
+
if (attempt >= p.retries || asked !== null && asked > p.capMs || Date.now() - started + wait > p.budgetMs) {
|
|
25228
|
+
await res?.body?.cancel().catch(() => {
|
|
25229
|
+
});
|
|
25230
|
+
throw new ServerBusyError(status, Math.max(1, Math.ceil(Math.max(wait, p.baseMs) / 1e3)), path);
|
|
25231
|
+
}
|
|
25232
|
+
await res?.body?.cancel().catch(() => {
|
|
25233
|
+
});
|
|
25234
|
+
await p.sleep(wait);
|
|
25235
|
+
}
|
|
25236
|
+
}
|
|
25237
|
+
async read(res, path) {
|
|
25238
|
+
const etag = res.headers.get("etag");
|
|
25239
|
+
if (res.status === 304) {
|
|
25240
|
+
await res.body?.cancel().catch(() => {
|
|
25241
|
+
});
|
|
25242
|
+
return { status: 304, etag, data: null, bytes: 0 };
|
|
25243
|
+
}
|
|
22458
25244
|
let text;
|
|
22459
25245
|
try {
|
|
22460
25246
|
text = await res.text();
|
|
@@ -22472,7 +25258,8 @@ var BeplusClient = class {
|
|
|
22472
25258
|
const message = json?.message || (Array.isArray(json?.error?.formatted) ? json.error.formatted.join(", ") : void 0) || res.statusText || `HTTP ${res.status}`;
|
|
22473
25259
|
throw new ApiError(res.status, message, json);
|
|
22474
25260
|
}
|
|
22475
|
-
|
|
25261
|
+
const data = json && typeof json === "object" && "result" in json ? json.result : json;
|
|
25262
|
+
return { status: res.status, etag, data, bytes: text.length };
|
|
22476
25263
|
}
|
|
22477
25264
|
startGeneration(body2) {
|
|
22478
25265
|
return this.request("POST", "/generations", { body: body2 });
|
|
@@ -22549,11 +25336,47 @@ var BeplusClient = class {
|
|
|
22549
25336
|
);
|
|
22550
25337
|
return r?.state ?? null;
|
|
22551
25338
|
}
|
|
25339
|
+
// `retry: false` nas leituras de apoio: 503 aqui é "não configurado" e não pode segurar list_models nem check_generation.
|
|
25340
|
+
elevenLabsCatalog(opts = {}) {
|
|
25341
|
+
return this.request("GET", "/elevenlabs/catalog", { timeoutMs: 15e3, ...opts });
|
|
25342
|
+
}
|
|
25343
|
+
elevenLabsVoices(query) {
|
|
25344
|
+
return this.request("GET", "/elevenlabs/voices", { query, timeoutMs: 2e4 });
|
|
25345
|
+
}
|
|
25346
|
+
deleteElevenLabsVoice(id) {
|
|
25347
|
+
return this.request("DELETE", `/elevenlabs/voices/${encodeURIComponent(id)}`, { timeoutMs: 3e4 });
|
|
25348
|
+
}
|
|
25349
|
+
saveElevenLabsVoice(body2) {
|
|
25350
|
+
return this.request("POST", "/elevenlabs/voices/design/save", { body: body2, timeoutMs: 6e4 });
|
|
25351
|
+
}
|
|
25352
|
+
elevenLabsEstimate(body2) {
|
|
25353
|
+
return this.request("POST", "/elevenlabs/estimate", { body: body2, timeoutMs: 6e4 });
|
|
25354
|
+
}
|
|
25355
|
+
// Sem repetição: este POST cobra. Ferramenta longa volta `processing` logo, a rápida segura até a resposta.
|
|
25356
|
+
elevenLabsGenerate(body2) {
|
|
25357
|
+
return this.request("POST", "/elevenlabs/generate", { body: body2, timeoutMs: 18e4 });
|
|
25358
|
+
}
|
|
25359
|
+
elevenLabsJob(id, opts = {}) {
|
|
25360
|
+
return this.request("GET", `/elevenlabs/generations/${encodeURIComponent(id)}`, { timeoutMs: 15e3, ...opts });
|
|
25361
|
+
}
|
|
22552
25362
|
models() {
|
|
22553
25363
|
return this.request("GET", "/models");
|
|
22554
25364
|
}
|
|
25365
|
+
/** Cache por parâmetros: o preço não muda entre chamadas, e o agente estima o mesmo modelo várias vezes. */
|
|
22555
25366
|
calculateCost(query) {
|
|
22556
|
-
|
|
25367
|
+
const normalized = Object.entries(query).filter(([, v]) => v !== void 0 && v !== null && v !== "").map(([k, v]) => [k, String(v)]).sort(([a], [b]) => a.localeCompare(b));
|
|
25368
|
+
const key = `${this.cfg.apiBase}|${JSON.stringify(normalized)}`;
|
|
25369
|
+
const now = costCachePolicy.now();
|
|
25370
|
+
const hit = costCache.get(key);
|
|
25371
|
+
if (hit && (hit.expiresAt === null || hit.expiresAt > now)) return hit.value;
|
|
25372
|
+
const value = this.request("GET", "/calculate-cost", { query });
|
|
25373
|
+
costCache.set(key, { value, expiresAt: null });
|
|
25374
|
+
value.then(
|
|
25375
|
+
() => costCache.set(key, { value, expiresAt: costCachePolicy.now() + costCachePolicy.ttlMs }),
|
|
25376
|
+
() => costCache.delete(key)
|
|
25377
|
+
);
|
|
25378
|
+
while (costCache.size > costCachePolicy.capacity) costCache.delete(costCache.keys().next().value);
|
|
25379
|
+
return value;
|
|
22557
25380
|
}
|
|
22558
25381
|
/** `billing: 'personal'` pula o budget do projeto ativo no preview do saldo. */
|
|
22559
25382
|
balance(billing) {
|
|
@@ -22655,6 +25478,9 @@ var remote = false;
|
|
|
22655
25478
|
function enableRemoteMode() {
|
|
22656
25479
|
remote = true;
|
|
22657
25480
|
}
|
|
25481
|
+
function isRemoteMode() {
|
|
25482
|
+
return remote;
|
|
25483
|
+
}
|
|
22658
25484
|
function refuseLocalPath(ref) {
|
|
22659
25485
|
if (!remote) return;
|
|
22660
25486
|
throw new ApiError(
|
|
@@ -22933,6 +25759,11 @@ async function uploadBytes(cfg, file) {
|
|
|
22933
25759
|
}
|
|
22934
25760
|
return fileUrl;
|
|
22935
25761
|
}
|
|
25762
|
+
async function toStorageUrl(cfg, ref) {
|
|
25763
|
+
if (!isRemoteRef(ref)) return uploadBytes(cfg, await loadLocal(ref));
|
|
25764
|
+
if (new URL(ref).host === BEPLUS_STORAGE_HOST) return ref;
|
|
25765
|
+
return uploadBytes(cfg, await loadRemote(ref));
|
|
25766
|
+
}
|
|
22936
25767
|
async function uploadFile(cfg, ref) {
|
|
22937
25768
|
return uploadBytes(cfg, await loadLocal(ref));
|
|
22938
25769
|
}
|
|
@@ -23224,6 +26055,19 @@ var ASPECT_RATIOS = ["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3", "4:5", "
|
|
|
23224
26055
|
var VIDEO_ASPECT_RATIOS = [...ASPECT_RATIOS, "adaptive"];
|
|
23225
26056
|
var IMAGE_RESOLUTIONS = ["1K", "2K", "4K"];
|
|
23226
26057
|
var VIDEO_RESOLUTIONS = ["480p", "720p", "1080p", "4K"];
|
|
26058
|
+
var ELEVENLABS_TOOLS = [
|
|
26059
|
+
"tts",
|
|
26060
|
+
"dialogue",
|
|
26061
|
+
"sfx",
|
|
26062
|
+
"isolate",
|
|
26063
|
+
"voice_change",
|
|
26064
|
+
"transcribe",
|
|
26065
|
+
"align",
|
|
26066
|
+
"music",
|
|
26067
|
+
"stems",
|
|
26068
|
+
"video_music",
|
|
26069
|
+
"voice_design"
|
|
26070
|
+
];
|
|
23227
26071
|
var DEFAULTS = {
|
|
23228
26072
|
imageModel: "google/nano-banana-2.1",
|
|
23229
26073
|
imageAspect: "1:1",
|
|
@@ -23482,6 +26326,433 @@ function formatToolResult(state, fullWords) {
|
|
|
23482
26326
|
return lines.join("\n") || "(sem resultado)";
|
|
23483
26327
|
}
|
|
23484
26328
|
|
|
26329
|
+
// src/tools/elevenlabs.ts
|
|
26330
|
+
import { randomUUID } from "crypto";
|
|
26331
|
+
var elevenLabsPolling = {
|
|
26332
|
+
intervalMs: 3e3,
|
|
26333
|
+
budgetMs: 9e4,
|
|
26334
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, ms))
|
|
26335
|
+
};
|
|
26336
|
+
var MAX_TEXT_CHARS = 2e4;
|
|
26337
|
+
var SITE_ONLY_TOOLS = /* @__PURE__ */ new Set(["dub", "voice_clone"]);
|
|
26338
|
+
var SITE_ONLY_LABEL = "s\xF3 no site da BePlus, na aba \xC1udio do IA Lab";
|
|
26339
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
26340
|
+
var DESTINATION_NOTE = " Vai para o cliente e projeto ativos: confirme o destino com o usu\xE1rio antes (list_clients, list_projects).";
|
|
26341
|
+
var COST_NOTE = " Gasta diamantes; dry_run: true mostra o custo sem gastar.";
|
|
26342
|
+
var SOURCE_HELP = "Arquivo local (s\xF3 no stdio), URL ou id de uma gera\xE7\xE3o sua. Arquivo e URL de fora sobem para a BePlus antes (at\xE9 95 MB; acima disso, s\xF3 pelo site).";
|
|
26343
|
+
var TOO_LARGE_MESSAGE = "Este arquivo passa de 95 MB, o limite de envio por aqui. Use a mesma ferramenta no site da BePlus, na aba \xC1udio do IA Lab, que aceita arquivos maiores.";
|
|
26344
|
+
var COMMON_FIELDS = {
|
|
26345
|
+
project: external_exports.string().max(64).optional().describe("Projeto (uuid ou code curto). Omita para usar o projeto ativo."),
|
|
26346
|
+
billing: external_exports.enum(["personal"]).optional().describe('"personal" cobra do seu saldo pessoal e ignora o projeto, mesmo o ativo. Incompat\xEDvel com project.'),
|
|
26347
|
+
dry_run: external_exports.boolean().optional().describe("true devolve o custo em diamantes sem gerar nem gastar.")
|
|
26348
|
+
};
|
|
26349
|
+
function contractMessage(e) {
|
|
26350
|
+
if (!(e instanceof ApiError)) return void 0;
|
|
26351
|
+
const body2 = e.body;
|
|
26352
|
+
const message = body2?.error?.message ?? body2?.result?.error?.message;
|
|
26353
|
+
return typeof message === "string" && message ? message : void 0;
|
|
26354
|
+
}
|
|
26355
|
+
async function failure(client, e) {
|
|
26356
|
+
const ready = contractMessage(e);
|
|
26357
|
+
const raw = ready ?? (e instanceof Error ? e.message : "");
|
|
26358
|
+
if (isTeamGatingError(raw)) return errorResult(await buildPickProjectMessage(client));
|
|
26359
|
+
const text = ready ?? apiErrorToUserMessage(e);
|
|
26360
|
+
return errorResult(isBudgetBlockedError(raw) ? `${text}
|
|
26361
|
+
${BUDGET_BLOCKED_GUIDANCE}` : text);
|
|
26362
|
+
}
|
|
26363
|
+
var VOICE_ORIGIN = { premade: "padr\xE3o", library: "biblioteca", mine: "sua" };
|
|
26364
|
+
function voiceLine(v) {
|
|
26365
|
+
const traits = [v.language, v.gender, v.accent].filter(Boolean).join(", ");
|
|
26366
|
+
const description = v.description ? ` | ${v.description.length > 110 ? `${v.description.slice(0, 107)}...` : v.description}` : "";
|
|
26367
|
+
return `${v.id} | ${v.name} | ${VOICE_ORIGIN[v.source]}${traits ? ` | ${traits}` : ""}${description}`;
|
|
26368
|
+
}
|
|
26369
|
+
function jobFooter(job) {
|
|
26370
|
+
const balance = job.balance === void 0 ? "" : ` \xB7 Saldo: ${job.balance} \u{1F48E}`;
|
|
26371
|
+
return `Gera\xE7\xE3o: ${job.generationId}
|
|
26372
|
+
Custo: ${job.diamonds} \u{1F48E}${balance}`;
|
|
26373
|
+
}
|
|
26374
|
+
function formatJob(job) {
|
|
26375
|
+
if (job.status === "failed") return errorResult(`${job.error?.message ?? "A gera\xE7\xE3o falhou."}
|
|
26376
|
+
${jobFooter(job)}`);
|
|
26377
|
+
if (job.status === "processing") {
|
|
26378
|
+
return textResult(
|
|
26379
|
+
`\u23F3 Ainda em processamento. N\xE3o gere de novo: use check_generation com o id abaixo.
|
|
26380
|
+
${jobFooter(job)}`
|
|
26381
|
+
);
|
|
26382
|
+
}
|
|
26383
|
+
const out = job.output ?? {};
|
|
26384
|
+
const lines = [`\u2705 Pronto (${job.tool}).`];
|
|
26385
|
+
for (const f of out.files ?? []) {
|
|
26386
|
+
const duration3 = f.durationSec === void 0 ? "" : ` (${f.durationSec.toFixed(1)}s)`;
|
|
26387
|
+
lines.push(`${f.label ? `${f.label}: ` : ""}${f.url}${duration3}`);
|
|
26388
|
+
}
|
|
26389
|
+
if (out.text) {
|
|
26390
|
+
const cut = out.text.length > MAX_TEXT_CHARS;
|
|
26391
|
+
lines.push(cut ? `${out.text.slice(0, MAX_TEXT_CHARS)}
|
|
26392
|
+
[texto cortado em ${MAX_TEXT_CHARS} caracteres]` : out.text);
|
|
26393
|
+
}
|
|
26394
|
+
if (out.words?.length) {
|
|
26395
|
+
const speakers = new Set(out.words.map((w) => w.speaker).filter(Boolean)).size;
|
|
26396
|
+
lines.push(`${out.words.length} palavras com tempo${speakers ? `, ${speakers} locutores` : ""}.`);
|
|
26397
|
+
}
|
|
26398
|
+
if (out.srtUrl) lines.push(`Legenda: ${out.srtUrl}`);
|
|
26399
|
+
if (out.previews?.length) {
|
|
26400
|
+
lines.push("Pr\xE9vias (id | \xE1udio):", ...out.previews.map((p) => `${p.id} | ${p.url}`));
|
|
26401
|
+
lines.push("Mostre as pr\xE9vias ao usu\xE1rio. A escolhida vira voz com elevenlabs_voice_design_save.");
|
|
26402
|
+
}
|
|
26403
|
+
if (out.voice) lines.push(`Voz: ${voiceLine(out.voice)}`);
|
|
26404
|
+
lines.push(jobFooter(job));
|
|
26405
|
+
return textResult(lines.join("\n"));
|
|
26406
|
+
}
|
|
26407
|
+
async function waitForJob(client, first) {
|
|
26408
|
+
const { intervalMs, budgetMs, sleep: sleep4 } = elevenLabsPolling;
|
|
26409
|
+
let job = first;
|
|
26410
|
+
for (let waited = 0; job.status === "processing" && waited < budgetMs; waited += intervalMs) {
|
|
26411
|
+
await sleep4(intervalMs);
|
|
26412
|
+
try {
|
|
26413
|
+
job = await client.elevenLabsJob(first.generationId);
|
|
26414
|
+
} catch {
|
|
26415
|
+
return job;
|
|
26416
|
+
}
|
|
26417
|
+
}
|
|
26418
|
+
return job;
|
|
26419
|
+
}
|
|
26420
|
+
async function toSource(cfg, ref) {
|
|
26421
|
+
if (UUID.test(ref)) return { generationId: ref };
|
|
26422
|
+
try {
|
|
26423
|
+
return { fileUrl: await toStorageUrl(cfg, ref) };
|
|
26424
|
+
} catch (e) {
|
|
26425
|
+
if (e instanceof ApiError && e.httpStatus === 413) throw new ApiError(413, TOO_LARGE_MESSAGE);
|
|
26426
|
+
throw e;
|
|
26427
|
+
}
|
|
26428
|
+
}
|
|
26429
|
+
function uploadedHint(body2) {
|
|
26430
|
+
const url = body2.source?.fileUrl;
|
|
26431
|
+
return url ? `
|
|
26432
|
+
Arquivo na BePlus: ${url}. Use esta URL em source para n\xE3o subir de novo.` : "";
|
|
26433
|
+
}
|
|
26434
|
+
async function estimate(client, body2) {
|
|
26435
|
+
const res = await client.elevenLabsEstimate(body2);
|
|
26436
|
+
const duration3 = res.durationSec === void 0 ? "" : ` para ${res.durationSec.toFixed(1)}s`;
|
|
26437
|
+
return textResult(`Custo estimado: ${res.diamonds} \u{1F48E}${duration3}. Nada foi gerado nem cobrado.${uploadedHint(body2)}`);
|
|
26438
|
+
}
|
|
26439
|
+
async function generate(client, body2) {
|
|
26440
|
+
let job;
|
|
26441
|
+
try {
|
|
26442
|
+
job = await client.elevenLabsGenerate({ ...body2, idempotencyKey: randomUUID() });
|
|
26443
|
+
} catch (e) {
|
|
26444
|
+
if (e instanceof ApiError && (e.httpStatus === 0 || e.httpStatus === 408)) {
|
|
26445
|
+
return errorResult(
|
|
26446
|
+
"A resposta n\xE3o chegou, ent\xE3o a gera\xE7\xE3o pode ter come\xE7ado e sido cobrada. N\xE3o repita: confira em list_generations antes."
|
|
26447
|
+
);
|
|
26448
|
+
}
|
|
26449
|
+
throw e;
|
|
26450
|
+
}
|
|
26451
|
+
return formatJob(await waitForJob(client, job));
|
|
26452
|
+
}
|
|
26453
|
+
async function estimateElevenLabsModel(client, cfg, model, params, file) {
|
|
26454
|
+
const [, tool, variant] = model.split("/");
|
|
26455
|
+
if (!ELEVENLABS_TOOLS.includes(tool ?? "")) {
|
|
26456
|
+
return errorResult(`Ferramenta desconhecida em "${model}". Use elevenlabs/<ferramenta>: ${ELEVENLABS_TOOLS.join(", ")}.`);
|
|
26457
|
+
}
|
|
26458
|
+
try {
|
|
26459
|
+
const body2 = { ...params, tool };
|
|
26460
|
+
if (variant) body2.model = variant;
|
|
26461
|
+
if (file) body2.source = await toSource(cfg, file);
|
|
26462
|
+
return await estimate(client, body2);
|
|
26463
|
+
} catch (e) {
|
|
26464
|
+
return failure(client, e);
|
|
26465
|
+
}
|
|
26466
|
+
}
|
|
26467
|
+
function elevenLabsCatalogBlock(catalog) {
|
|
26468
|
+
if (!catalog?.enabled) return "";
|
|
26469
|
+
const lines = catalog.tools.filter((t) => t.available).map((t) => {
|
|
26470
|
+
if (SITE_ONLY_TOOLS.has(t.tool)) return `\u2022 ${t.label}: ${SITE_ONLY_LABEL}.`;
|
|
26471
|
+
const models = t.models?.length ? ` Modelos: ${t.models.map((m) => m.id).join(", ")}.` : "";
|
|
26472
|
+
return `\u2022 elevenlabs_${t.tool}: ${t.label}, ${t.diamondsPerUnitHint}.${models}`;
|
|
26473
|
+
});
|
|
26474
|
+
return lines.length ? `
|
|
26475
|
+
|
|
26476
|
+
ElevenLabs (detalhes e limites em elevenlabs_catalog):
|
|
26477
|
+
${lines.join("\n")}` : "";
|
|
26478
|
+
}
|
|
26479
|
+
function registerElevenLabsTools(server, client, cfg) {
|
|
26480
|
+
function spendTool(name, title, description, shape, build2) {
|
|
26481
|
+
server.registerTool(
|
|
26482
|
+
name,
|
|
26483
|
+
{
|
|
26484
|
+
title,
|
|
26485
|
+
description: description + COST_NOTE + DESTINATION_NOTE,
|
|
26486
|
+
inputSchema: { ...shape, ...COMMON_FIELDS },
|
|
26487
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
|
|
26488
|
+
},
|
|
26489
|
+
(async (args) => {
|
|
26490
|
+
try {
|
|
26491
|
+
const body2 = compact({
|
|
26492
|
+
...await build2(args),
|
|
26493
|
+
project: resolveProjectArg(args.project, args.billing, cfg.activeProject),
|
|
26494
|
+
billing: args.billing
|
|
26495
|
+
});
|
|
26496
|
+
return await (args.dry_run ? estimate(client, body2) : generate(client, body2));
|
|
26497
|
+
} catch (e) {
|
|
26498
|
+
return failure(client, e);
|
|
26499
|
+
}
|
|
26500
|
+
})
|
|
26501
|
+
);
|
|
26502
|
+
}
|
|
26503
|
+
const modelField = (example) => external_exports.string().min(1).describe(`Id do modelo, ex.: ${example}. A lista sai de elevenlabs_catalog.`);
|
|
26504
|
+
const voiceField = external_exports.string().min(1).describe("Id de uma voz de elevenlabs_list_voices. Outra voz \xE9 recusada.");
|
|
26505
|
+
const sourceField = external_exports.string().min(1).describe(SOURCE_HELP);
|
|
26506
|
+
server.registerTool(
|
|
26507
|
+
"elevenlabs_catalog",
|
|
26508
|
+
{
|
|
26509
|
+
title: "ElevenLabs: ferramentas e modelos",
|
|
26510
|
+
description: "Mostra o que a ElevenLabs oferece agora na BePlus: ferramentas ligadas, modelos, pre\xE7o aproximado e limites. Chame antes da primeira gera\xE7\xE3o para escolher o model. Somente leitura, sem custo.",
|
|
26511
|
+
inputSchema: {},
|
|
26512
|
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
|
26513
|
+
},
|
|
26514
|
+
async () => {
|
|
26515
|
+
try {
|
|
26516
|
+
const catalog = await client.elevenLabsCatalog();
|
|
26517
|
+
if (!catalog.enabled) return textResult("A ElevenLabs est\xE1 desligada na plataforma agora.");
|
|
26518
|
+
const lines = catalog.tools.map((t) => {
|
|
26519
|
+
if (SITE_ONLY_TOOLS.has(t.tool)) return `${t.label}: ${SITE_ONLY_LABEL}. N\xE3o h\xE1 tool para isso aqui.`;
|
|
26520
|
+
const head = `elevenlabs_${t.tool} | ${t.label} | ${t.available ? t.diamondsPerUnitHint : "indispon\xEDvel agora"}`;
|
|
26521
|
+
const models = (t.models ?? []).map((m) => ` ${m.id}: ${m.label}. ${m.description}`);
|
|
26522
|
+
return [head, ` ${t.description}`, ` Limites: ${JSON.stringify(t.limits)}`, ...models].join("\n");
|
|
26523
|
+
});
|
|
26524
|
+
return textResult(lines.join("\n"));
|
|
26525
|
+
} catch (e) {
|
|
26526
|
+
return failure(client, e);
|
|
26527
|
+
}
|
|
26528
|
+
}
|
|
26529
|
+
);
|
|
26530
|
+
server.registerTool(
|
|
26531
|
+
"elevenlabs_list_voices",
|
|
26532
|
+
{
|
|
26533
|
+
title: "ElevenLabs: listar vozes",
|
|
26534
|
+
description: "Lista as vozes que voc\xEA pode usar nas ferramentas elevenlabs_*: as da biblioteca, as padr\xE3o e as que voc\xEA criou. N\xE3o serve para generate_audio, que tem vozes pr\xF3prias. Somente leitura, sem custo.",
|
|
26535
|
+
inputSchema: {
|
|
26536
|
+
search: external_exports.string().max(100).optional().describe("Texto livre: nome, descri\xE7\xE3o, sotaque."),
|
|
26537
|
+
language: external_exports.string().max(12).optional().describe("Idioma, ex.: pt, en."),
|
|
26538
|
+
gender: external_exports.string().max(20).optional(),
|
|
26539
|
+
page: external_exports.number().int().min(1).optional().describe("Padr\xE3o 1.")
|
|
26540
|
+
},
|
|
26541
|
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
|
26542
|
+
},
|
|
26543
|
+
async (args) => {
|
|
26544
|
+
try {
|
|
26545
|
+
const res = await client.elevenLabsVoices(compact(args));
|
|
26546
|
+
if (!res.voices.length) return textResult("Nenhuma voz encontrada com esses filtros.");
|
|
26547
|
+
const more = res.hasMore ? `
|
|
26548
|
+
Use page=${res.page + 1} para ver mais.` : "";
|
|
26549
|
+
return textResult(`Vozes, p\xE1gina ${res.page} (id | nome | origem | detalhes):
|
|
26550
|
+
${res.voices.map(voiceLine).join("\n")}${more}`);
|
|
26551
|
+
} catch (e) {
|
|
26552
|
+
return failure(client, e);
|
|
26553
|
+
}
|
|
26554
|
+
}
|
|
26555
|
+
);
|
|
26556
|
+
server.registerTool(
|
|
26557
|
+
"elevenlabs_delete_voice",
|
|
26558
|
+
{
|
|
26559
|
+
title: "ElevenLabs: apagar voz sua",
|
|
26560
|
+
description: "DESTRUTIVO e sem volta: apaga uma voz que voc\xEA criou e libera a vaga. \xC1udios j\xE1 gerados continuam tocando. N\xE3o devolve diamantes. Confirme com o usu\xE1rio antes.",
|
|
26561
|
+
inputSchema: { id: external_exports.string().min(1).describe('Id da voz em elevenlabs_list_voices, com origem "sua".') },
|
|
26562
|
+
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }
|
|
26563
|
+
},
|
|
26564
|
+
async ({ id }) => {
|
|
26565
|
+
try {
|
|
26566
|
+
await client.deleteElevenLabsVoice(id);
|
|
26567
|
+
return textResult(`\u2705 Voz ${id} apagada.`);
|
|
26568
|
+
} catch (e) {
|
|
26569
|
+
return failure(client, e);
|
|
26570
|
+
}
|
|
26571
|
+
}
|
|
26572
|
+
);
|
|
26573
|
+
server.registerTool(
|
|
26574
|
+
"elevenlabs_voice_design_save",
|
|
26575
|
+
{
|
|
26576
|
+
title: "ElevenLabs: salvar voz criada",
|
|
26577
|
+
description: "Transforma uma pr\xE9via de elevenlabs_voice_design em voz sua, para usar nas ferramentas elevenlabs_*. Ocupa uma vaga de voz: salve s\xF3 a pr\xE9via que o usu\xE1rio escolheu.",
|
|
26578
|
+
inputSchema: {
|
|
26579
|
+
preview_id: external_exports.string().min(1).describe("Id da pr\xE9via escolhida."),
|
|
26580
|
+
name: external_exports.string().min(1).max(40).describe("Nome da voz.")
|
|
26581
|
+
},
|
|
26582
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
|
|
26583
|
+
},
|
|
26584
|
+
async ({ preview_id, name }) => {
|
|
26585
|
+
try {
|
|
26586
|
+
const voice = await client.saveElevenLabsVoice({ previewId: preview_id, name });
|
|
26587
|
+
return textResult(`\u2705 Voz salva.
|
|
26588
|
+
${voiceLine(voice)}`);
|
|
26589
|
+
} catch (e) {
|
|
26590
|
+
return failure(client, e);
|
|
26591
|
+
}
|
|
26592
|
+
}
|
|
26593
|
+
);
|
|
26594
|
+
spendTool(
|
|
26595
|
+
"elevenlabs_tts",
|
|
26596
|
+
"ElevenLabs: texto em fala",
|
|
26597
|
+
"Narra\xE7\xE3o com uma voz s\xF3, com a qualidade da ElevenLabs. Para duas ou mais vozes conversando use elevenlabs_dialogue. Para o TTS do Gemini e o SeedAudio use generate_audio.",
|
|
26598
|
+
{
|
|
26599
|
+
text: external_exports.string().min(1).describe("Texto a falar. O teto depende do modelo."),
|
|
26600
|
+
voice: voiceField,
|
|
26601
|
+
model: modelField("eleven_v4"),
|
|
26602
|
+
language: external_exports.string().max(12).optional().describe("Idioma do texto, ex.: pt."),
|
|
26603
|
+
stability: external_exports.number().min(0).max(1).optional(),
|
|
26604
|
+
similarity: external_exports.number().min(0).max(1).optional(),
|
|
26605
|
+
style: external_exports.number().min(0).max(1).optional().describe("N\xE3o vale nos modelos eleven_v4."),
|
|
26606
|
+
speed: external_exports.number().positive().optional().describe("N\xE3o vale nos modelos eleven_v4.")
|
|
26607
|
+
},
|
|
26608
|
+
({ text, voice, model, language, stability, similarity, style, speed }) => {
|
|
26609
|
+
if (model.startsWith("eleven_v4") && (style !== void 0 || speed !== void 0)) {
|
|
26610
|
+
throw new Error("Os modelos eleven_v4 n\xE3o aceitam style nem speed. Tire esses campos ou troque o modelo.");
|
|
26611
|
+
}
|
|
26612
|
+
const settings = compact({ stability, similarity, style, speed });
|
|
26613
|
+
return { tool: "tts", text, voice, model, language, settings: Object.keys(settings).length ? settings : void 0 };
|
|
26614
|
+
}
|
|
26615
|
+
);
|
|
26616
|
+
spendTool(
|
|
26617
|
+
"elevenlabs_dialogue",
|
|
26618
|
+
"ElevenLabs: di\xE1logo",
|
|
26619
|
+
"Conversa entre duas ou mais vozes num \xE1udio s\xF3, na ordem das falas. Para uma voz s\xF3 use elevenlabs_tts.",
|
|
26620
|
+
{
|
|
26621
|
+
lines: external_exports.array(external_exports.object({ voice: voiceField, text: external_exports.string().min(1) })).min(2).describe("Falas em ordem, cada uma com a sua voz. At\xE9 2.000 caracteres somando todas."),
|
|
26622
|
+
model: modelField("eleven_v3")
|
|
26623
|
+
},
|
|
26624
|
+
({ lines, model }) => ({ tool: "dialogue", lines, model })
|
|
26625
|
+
);
|
|
26626
|
+
spendTool(
|
|
26627
|
+
"elevenlabs_sfx",
|
|
26628
|
+
"ElevenLabs: efeito sonoro",
|
|
26629
|
+
"Cria um efeito sonoro a partir de uma descri\xE7\xE3o (porta batendo, chuva, whoosh). Para trilha musical use elevenlabs_music.",
|
|
26630
|
+
{
|
|
26631
|
+
text: external_exports.string().min(1).describe("Descri\xE7\xE3o do som."),
|
|
26632
|
+
model: modelField("eleven_text_to_sound_v2"),
|
|
26633
|
+
duration_sec: external_exports.number().positive().optional().describe("De 0,5 a 30 s. Omita para o modelo decidir."),
|
|
26634
|
+
loop: external_exports.boolean().optional().describe("true faz o som emendar sem corte."),
|
|
26635
|
+
prompt_influence: external_exports.number().min(0).max(1).optional().describe("Quanto seguir a descri\xE7\xE3o ao p\xE9 da letra.")
|
|
26636
|
+
},
|
|
26637
|
+
({ text, model, duration_sec, loop, prompt_influence }) => ({
|
|
26638
|
+
tool: "sfx",
|
|
26639
|
+
text,
|
|
26640
|
+
model,
|
|
26641
|
+
durationSec: duration_sec,
|
|
26642
|
+
loop,
|
|
26643
|
+
promptInfluence: prompt_influence
|
|
26644
|
+
})
|
|
26645
|
+
);
|
|
26646
|
+
spendTool(
|
|
26647
|
+
"elevenlabs_isolate",
|
|
26648
|
+
"ElevenLabs: isolar voz",
|
|
26649
|
+
"Tira ru\xEDdo e fundo de uma grava\xE7\xE3o e deixa s\xF3 a voz. Para separar instrumentos de uma m\xFAsica use elevenlabs_stems.",
|
|
26650
|
+
{ source: sourceField },
|
|
26651
|
+
async ({ source }) => ({ tool: "isolate", source: await toSource(cfg, source) })
|
|
26652
|
+
);
|
|
26653
|
+
spendTool(
|
|
26654
|
+
"elevenlabs_voice_change",
|
|
26655
|
+
"ElevenLabs: trocar a voz",
|
|
26656
|
+
"Refala uma grava\xE7\xE3o com outra voz, mantendo ritmo e emo\xE7\xE3o. Use s\xF3 em grava\xE7\xE3o que o usu\xE1rio pode alterar.",
|
|
26657
|
+
{
|
|
26658
|
+
source: sourceField,
|
|
26659
|
+
voice: voiceField,
|
|
26660
|
+
model: external_exports.string().min(1).optional().describe("Id do modelo, ex.: eleven_multilingual_sts_v2."),
|
|
26661
|
+
remove_noise: external_exports.boolean().optional().describe("true limpa o ru\xEDdo da grava\xE7\xE3o antes.")
|
|
26662
|
+
},
|
|
26663
|
+
async ({ source, voice, model, remove_noise }) => ({
|
|
26664
|
+
tool: "voice_change",
|
|
26665
|
+
source: await toSource(cfg, source),
|
|
26666
|
+
voice,
|
|
26667
|
+
model,
|
|
26668
|
+
removeNoise: remove_noise
|
|
26669
|
+
})
|
|
26670
|
+
);
|
|
26671
|
+
spendTool(
|
|
26672
|
+
"elevenlabs_transcribe",
|
|
26673
|
+
"ElevenLabs: transcrever",
|
|
26674
|
+
"Transforma \xE1udio ou v\xEDdeo em texto, com tempo por palavra e legenda. Se j\xE1 tem o texto e s\xF3 quer o tempo, use elevenlabs_align. Reuni\xE3o gravada da equipe j\xE1 est\xE1 em search_calls.",
|
|
26675
|
+
{
|
|
26676
|
+
source: sourceField,
|
|
26677
|
+
language: external_exports.string().max(12).optional().describe("Idioma falado. Omita para detectar."),
|
|
26678
|
+
diarize: external_exports.boolean().optional().describe("true separa quem falou o qu\xEA."),
|
|
26679
|
+
num_speakers: external_exports.number().int().min(1).optional().describe("Quantas pessoas falam, se souber."),
|
|
26680
|
+
audio_events: external_exports.boolean().optional().describe("true marca risos, palmas e outros sons."),
|
|
26681
|
+
keyterms: external_exports.array(external_exports.string().min(1)).optional().describe("Nomes e termos dif\xEDceis para acertar a grafia.")
|
|
26682
|
+
},
|
|
26683
|
+
async ({ source, language, diarize, num_speakers, audio_events, keyterms }) => ({
|
|
26684
|
+
tool: "transcribe",
|
|
26685
|
+
source: await toSource(cfg, source),
|
|
26686
|
+
language,
|
|
26687
|
+
diarize,
|
|
26688
|
+
numSpeakers: num_speakers,
|
|
26689
|
+
audioEvents: audio_events,
|
|
26690
|
+
keyterms
|
|
26691
|
+
})
|
|
26692
|
+
);
|
|
26693
|
+
spendTool(
|
|
26694
|
+
"elevenlabs_align",
|
|
26695
|
+
"ElevenLabs: alinhar texto ao \xE1udio",
|
|
26696
|
+
"Recebe o \xE1udio e o texto j\xE1 pronto e devolve o tempo de cada palavra, para legenda exata. Sem o texto, use elevenlabs_transcribe.",
|
|
26697
|
+
{ source: sourceField, text: external_exports.string().min(1).describe("Texto exato do que \xE9 falado.") },
|
|
26698
|
+
async ({ source, text }) => ({ tool: "align", source: await toSource(cfg, source), text })
|
|
26699
|
+
);
|
|
26700
|
+
spendTool(
|
|
26701
|
+
"elevenlabs_music",
|
|
26702
|
+
"ElevenLabs: m\xFAsica",
|
|
26703
|
+
"Cria m\xFAsica a partir de uma descri\xE7\xE3o, com letra ou instrumental. Para Suno use generate_music. Para trilha casada com um v\xEDdeo use elevenlabs_video_music.",
|
|
26704
|
+
{
|
|
26705
|
+
prompt: external_exports.string().min(1).describe("Estilo, clima e instrumentos."),
|
|
26706
|
+
model: external_exports.string().min(1).optional().describe("Id do modelo. Omita para o padr\xE3o."),
|
|
26707
|
+
duration_sec: external_exports.number().min(3).optional().describe("Dura\xE7\xE3o em segundos, m\xEDnimo 3."),
|
|
26708
|
+
instrumental: external_exports.boolean().optional(),
|
|
26709
|
+
lyrics: external_exports.string().min(1).optional().describe("Letra pr\xF3pria.")
|
|
26710
|
+
},
|
|
26711
|
+
({ prompt, model, duration_sec, instrumental, lyrics }) => ({
|
|
26712
|
+
tool: "music",
|
|
26713
|
+
prompt,
|
|
26714
|
+
model,
|
|
26715
|
+
durationSec: duration_sec,
|
|
26716
|
+
instrumental,
|
|
26717
|
+
lyrics
|
|
26718
|
+
})
|
|
26719
|
+
);
|
|
26720
|
+
spendTool(
|
|
26721
|
+
"elevenlabs_stems",
|
|
26722
|
+
"ElevenLabs: separar faixas",
|
|
26723
|
+
"Separa uma m\xFAsica em faixas (voz, bateria, baixo e outras). Para limpar uma fala gravada use elevenlabs_isolate.",
|
|
26724
|
+
{ source: sourceField },
|
|
26725
|
+
async ({ source }) => ({ tool: "stems", source: await toSource(cfg, source) })
|
|
26726
|
+
);
|
|
26727
|
+
spendTool(
|
|
26728
|
+
"elevenlabs_video_music",
|
|
26729
|
+
"ElevenLabs: trilha para v\xEDdeo",
|
|
26730
|
+
"Cria trilha que acompanha um v\xEDdeo existente. Para m\xFAsica sem v\xEDdeo use elevenlabs_music.",
|
|
26731
|
+
{
|
|
26732
|
+
source: sourceField,
|
|
26733
|
+
description: external_exports.string().min(1).optional().describe("Clima desejado."),
|
|
26734
|
+
add_sfx: external_exports.boolean().optional().describe("true acrescenta efeitos sonoros.")
|
|
26735
|
+
},
|
|
26736
|
+
async ({ source, description, add_sfx }) => ({
|
|
26737
|
+
tool: "video_music",
|
|
26738
|
+
source: await toSource(cfg, source),
|
|
26739
|
+
description,
|
|
26740
|
+
addSfx: add_sfx
|
|
26741
|
+
})
|
|
26742
|
+
);
|
|
26743
|
+
spendTool(
|
|
26744
|
+
"elevenlabs_voice_design",
|
|
26745
|
+
"ElevenLabs: criar voz por descri\xE7\xE3o",
|
|
26746
|
+
"Gera pr\xE9vias de uma voz nova a partir de uma descri\xE7\xE3o. N\xE3o cria a voz ainda: mostre as pr\xE9vias e salve a escolhida com elevenlabs_voice_design_save. Para vozes do Gemini use design_voice.",
|
|
26747
|
+
{
|
|
26748
|
+
description: external_exports.string().min(20).describe("Idade, timbre, sotaque e jeito de falar. M\xEDnimo 20 caracteres."),
|
|
26749
|
+
text: external_exports.string().min(1).optional().describe("Frase que as pr\xE9vias v\xE3o falar."),
|
|
26750
|
+
model: external_exports.string().min(1).optional().describe("Id do modelo. Omita para o padr\xE3o.")
|
|
26751
|
+
},
|
|
26752
|
+
({ description, text, model }) => ({ tool: "voice_design", description, text, model })
|
|
26753
|
+
);
|
|
26754
|
+
}
|
|
26755
|
+
|
|
23485
26756
|
// src/tools/generation.ts
|
|
23486
26757
|
var IMAGE_BUDGET_MS = 9e4;
|
|
23487
26758
|
var VIDEO_BUDGET_MS = 12e4;
|
|
@@ -24014,13 +27285,15 @@ ${BUDGET_BLOCKED_GUIDANCE}`);
|
|
|
24014
27285
|
"check_generation",
|
|
24015
27286
|
{
|
|
24016
27287
|
title: "Checar gera\xE7\xE3o",
|
|
24017
|
-
description: "Consulta o status de uma gera\xE7\xE3o ass\xEDncrona (imagem
|
|
27288
|
+
description: "Consulta o status de uma gera\xE7\xE3o ass\xEDncrona (imagem, v\xEDdeo ou ElevenLabs) pelo id. Use depois de generate_video, de um generate_image que estourou o tempo ou de uma elevenlabs_* em processamento. Retorna status, progresso e (quando pronto) as URLs.",
|
|
24018
27289
|
inputSchema: {
|
|
24019
|
-
generation_id: external_exports.string().min(1).describe("O id retornado por generate_image
|
|
27290
|
+
generation_id: external_exports.string().min(1).describe("O id retornado por generate_image, generate_video ou elevenlabs_*.")
|
|
24020
27291
|
}
|
|
24021
27292
|
},
|
|
24022
27293
|
async ({ generation_id }) => {
|
|
24023
27294
|
try {
|
|
27295
|
+
const job = await client.elevenLabsJob(generation_id, { retry: false }).catch(() => null);
|
|
27296
|
+
if (job?.generationId) return formatJob(job);
|
|
24024
27297
|
const status = await client.getStatus(generation_id);
|
|
24025
27298
|
if (status.status === "completed") {
|
|
24026
27299
|
const urls = outputUrls(status);
|
|
@@ -24096,6 +27369,7 @@ ${list}${flagsLine(status)}${draftHint}` }, ...blocks] };
|
|
|
24096
27369
|
await client.cancel(generation_id);
|
|
24097
27370
|
return textResult(`\u2705 Gera\xE7\xE3o ${generation_id} cancelada (diamantes estornados quando aplic\xE1vel).`);
|
|
24098
27371
|
} catch (e) {
|
|
27372
|
+
if (e instanceof ApiError && e.httpStatus === 409) return textResult(e.message);
|
|
24099
27373
|
return errorResult(apiErrorToUserMessage(e));
|
|
24100
27374
|
}
|
|
24101
27375
|
}
|
|
@@ -24991,7 +28265,7 @@ Use o valor de "voice" no generate_audio com um modelo 3.8 (sem multi_speaker).`
|
|
|
24991
28265
|
}
|
|
24992
28266
|
|
|
24993
28267
|
// src/tools/account.ts
|
|
24994
|
-
function registerAccountTools(server, client,
|
|
28268
|
+
function registerAccountTools(server, client, cfg) {
|
|
24995
28269
|
server.registerTool(
|
|
24996
28270
|
"whoami",
|
|
24997
28271
|
{
|
|
@@ -25048,14 +28322,17 @@ ${budget}` : "")
|
|
|
25048
28322
|
},
|
|
25049
28323
|
async () => {
|
|
25050
28324
|
try {
|
|
25051
|
-
const m = await
|
|
28325
|
+
const [m, elevenLabs] = await Promise.all([
|
|
28326
|
+
client.models(),
|
|
28327
|
+
client.elevenLabsCatalog({ retry: false }).catch(() => null)
|
|
28328
|
+
]);
|
|
25052
28329
|
const lines = m.models.map((x) => {
|
|
25053
28330
|
const price = typeof x.pricing === "number" ? `$${x.pricing}` : JSON.stringify(x.pricing);
|
|
25054
28331
|
return `\u2022 ${x.model} \u2014 ${price} (base USD)`;
|
|
25055
28332
|
});
|
|
25056
28333
|
const analyzeBlock = analyzeCatalogBlock(m.analyze);
|
|
25057
28334
|
const txt = `Modelos de gera\xE7\xE3o:
|
|
25058
|
-
${lines.join("\n") || "(nenhum)"}` + analyzeBlock + `
|
|
28335
|
+
${lines.join("\n") || "(nenhum)"}` + analyzeBlock + elevenLabsCatalogBlock(elevenLabs) + `
|
|
25059
28336
|
|
|
25060
28337
|
Limites simult\xE2neos por usu\xE1rio: imagem=${m.limits.perUserMaxImage}, v\xEDdeo=${m.limits.perUserMaxVideo}, \xE1udio=${m.limits.perUserMaxAudio}.
|
|
25061
28338
|
1 \u{1F48E} \u2248 $${m.pricing.diamondValueUsd} (margem ${m.pricing.diamondMargin}x, m\xEDn ${m.pricing.minDiamonds} \u{1F48E}). Use estimate_cost para o custo exato em diamantes (gera\xE7\xE3o).`;
|
|
@@ -25069,9 +28346,10 @@ Limites simult\xE2neos por usu\xE1rio: imagem=${m.limits.perUserMaxImage}, v\xED
|
|
|
25069
28346
|
"estimate_cost",
|
|
25070
28347
|
{
|
|
25071
28348
|
title: "Estimar custo",
|
|
25072
|
-
description: "Retorna o custo autoritativo em diamantes ANTES de gerar. Para \xE1udio (TTS) o custo \xE9 por segundo e s\xF3 \xE9 conhecido ap\xF3s a s\xEDntese.",
|
|
28349
|
+
description: "Retorna o custo autoritativo em diamantes ANTES de gerar. Para \xE1udio (TTS) o custo \xE9 por segundo e s\xF3 \xE9 conhecido ap\xF3s a s\xEDntese. ElevenLabs: model = elevenlabs/<ferramenta>[/<modelo>], os campos da gera\xE7\xE3o em elevenlabs_params e o arquivo em file (ou dry_run: true na pr\xF3pria ferramenta elevenlabs_*).",
|
|
25073
28350
|
inputSchema: {
|
|
25074
28351
|
model: external_exports.string().min(1).describe("Id do modelo (ex.: google/nano-banana-pro, bytedance/seedance-2.0)."),
|
|
28352
|
+
elevenlabs_params: external_exports.record(external_exports.unknown()).optional().describe('[ElevenLabs] Campos do pedido no formato da API, ex.: { "voice": "...", "text": "..." }.'),
|
|
25075
28353
|
resolution: external_exports.string().optional(),
|
|
25076
28354
|
duration: external_exports.number().int().optional(),
|
|
25077
28355
|
mode: external_exports.string().optional(),
|
|
@@ -25097,6 +28375,9 @@ Limites simult\xE2neos por usu\xE1rio: imagem=${m.limits.perUserMaxImage}, v\xED
|
|
|
25097
28375
|
}
|
|
25098
28376
|
},
|
|
25099
28377
|
async (args) => {
|
|
28378
|
+
if (args.model.startsWith("elevenlabs/")) {
|
|
28379
|
+
return estimateElevenLabsModel(client, cfg, args.model, args.elevenlabs_params, args.file);
|
|
28380
|
+
}
|
|
25100
28381
|
try {
|
|
25101
28382
|
let width2 = args.source_width;
|
|
25102
28383
|
let height = args.source_height;
|
|
@@ -25463,9 +28744,11 @@ ${calls.map(callLine).join("\n\n")}`);
|
|
|
25463
28744
|
}
|
|
25464
28745
|
|
|
25465
28746
|
// src/tools/canvas.ts
|
|
25466
|
-
import { createHash } from "crypto";
|
|
28747
|
+
import { createHash as createHash2 } from "crypto";
|
|
25467
28748
|
|
|
25468
28749
|
// src/canvas/api.ts
|
|
28750
|
+
import { createHash } from "crypto";
|
|
28751
|
+
var import_canvas_core = __toESM(require_canvas_core(), 1);
|
|
25469
28752
|
var PINNED_CORE_VERSION = "ca7b3b406184c7f679f555c3a008013197182b23";
|
|
25470
28753
|
var RUN_REQUEST_TIMEOUT_MS = 4e4;
|
|
25471
28754
|
var FOCUS_REQUEST_TIMEOUT_MS = 12e3;
|
|
@@ -25480,6 +28763,54 @@ var commentPacing = {
|
|
|
25480
28763
|
now: () => Date.now(),
|
|
25481
28764
|
sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
|
|
25482
28765
|
};
|
|
28766
|
+
var boardCachePolicy = {
|
|
28767
|
+
/** Contrato 5: duas leituras do mesmo board com menos que isso reaproveitam a anterior sem rede. */
|
|
28768
|
+
minIntervalMs: 2e3,
|
|
28769
|
+
stdio: { entries: 4, bytes: 256 * 1024 * 1024 },
|
|
28770
|
+
/** Dentro do academy-api: o doc em cache ocupa a memória da própria API. */
|
|
28771
|
+
remote: { entries: 2, bytes: 64 * 1024 * 1024 },
|
|
28772
|
+
/** Envelopes guardados para o conflito do edit() sem ir à rede (o servidor manda reler acima de 200). */
|
|
28773
|
+
recentMax: 200,
|
|
28774
|
+
now: () => Date.now()
|
|
28775
|
+
};
|
|
28776
|
+
var boardStore = /* @__PURE__ */ new Map();
|
|
28777
|
+
var boardLoads = /* @__PURE__ */ new Map();
|
|
28778
|
+
function storeEntry(key, entry) {
|
|
28779
|
+
const limit = isRemoteMode() ? boardCachePolicy.remote : boardCachePolicy.stdio;
|
|
28780
|
+
boardStore.delete(key);
|
|
28781
|
+
if (entry.bytes > limit.bytes) return;
|
|
28782
|
+
boardStore.set(key, entry);
|
|
28783
|
+
let total = 0;
|
|
28784
|
+
for (const e of boardStore.values()) total += e.bytes;
|
|
28785
|
+
for (const [k, e] of boardStore) {
|
|
28786
|
+
if (boardStore.size <= limit.entries && total <= limit.bytes) break;
|
|
28787
|
+
boardStore.delete(k);
|
|
28788
|
+
total -= e.bytes;
|
|
28789
|
+
}
|
|
28790
|
+
}
|
|
28791
|
+
function touchEntry(key, entry) {
|
|
28792
|
+
boardStore.delete(key);
|
|
28793
|
+
boardStore.set(key, entry);
|
|
28794
|
+
}
|
|
28795
|
+
function applyDelta(snap, envelopes) {
|
|
28796
|
+
let doc = snap.doc;
|
|
28797
|
+
let seq = snap.seq;
|
|
28798
|
+
try {
|
|
28799
|
+
for (const env of envelopes) {
|
|
28800
|
+
if (env.seq <= seq) continue;
|
|
28801
|
+
if (!knownOp(env.op)) return null;
|
|
28802
|
+
doc = (0, import_canvas_core.applyConfirmed)(doc, env);
|
|
28803
|
+
seq = env.seq;
|
|
28804
|
+
}
|
|
28805
|
+
} catch {
|
|
28806
|
+
return null;
|
|
28807
|
+
}
|
|
28808
|
+
return seq === snap.seq ? snap : { ...snap, doc, seq, title: doc.title };
|
|
28809
|
+
}
|
|
28810
|
+
function knownOp(op) {
|
|
28811
|
+
if (!Object.hasOwn(import_canvas_core.OPS, op.type)) return false;
|
|
28812
|
+
return op.type !== "batch" || Array.isArray(op.ops) && op.ops.every((o) => knownOp(o));
|
|
28813
|
+
}
|
|
25483
28814
|
var CanvasApi = class {
|
|
25484
28815
|
constructor(client, cfg) {
|
|
25485
28816
|
this.client = client;
|
|
@@ -25509,11 +28840,87 @@ var CanvasApi = class {
|
|
|
25509
28840
|
createBoard(body2) {
|
|
25510
28841
|
return this.req("POST", "/boards", { body: body2 });
|
|
25511
28842
|
}
|
|
25512
|
-
|
|
25513
|
-
|
|
28843
|
+
cacheKey(boardId4) {
|
|
28844
|
+
const who2 = createHash("sha256").update(this.cfg.token).digest("hex").slice(0, 16);
|
|
28845
|
+
return `${this.cfg.canvasBase}|${who2}|${boardId4}`;
|
|
28846
|
+
}
|
|
28847
|
+
/** Board pelo cache: delta quando dá, inteiro com If-None-Match quando não. Um GET em voo por board. */
|
|
28848
|
+
async snapshot(boardId4, opts = {}) {
|
|
28849
|
+
const key = this.cacheKey(boardId4);
|
|
28850
|
+
const entry = boardStore.get(key);
|
|
28851
|
+
if (entry && !opts.fresh && !opts.runs && boardCachePolicy.now() - entry.checkedAt < boardCachePolicy.minIntervalMs) {
|
|
28852
|
+
touchEntry(key, entry);
|
|
28853
|
+
return entry.snap;
|
|
28854
|
+
}
|
|
28855
|
+
const loadKey = opts.runs ? `${key}|runs` : key;
|
|
28856
|
+
const inFlight = boardLoads.get(loadKey);
|
|
28857
|
+
if (inFlight) return inFlight;
|
|
28858
|
+
const load = this.load(boardId4, key, !!opts.runs).finally(() => boardLoads.delete(loadKey));
|
|
28859
|
+
boardLoads.set(loadKey, load);
|
|
28860
|
+
return load;
|
|
28861
|
+
}
|
|
28862
|
+
async load(boardId4, key, needRuns) {
|
|
28863
|
+
const entry = boardStore.get(key);
|
|
28864
|
+
if (entry && !needRuns && this.coreVersion === PINNED_CORE_VERSION) {
|
|
28865
|
+
const envelopes = await this.fetchOpsAfter(boardId4, entry.snap.seq);
|
|
28866
|
+
const next = envelopes && applyDelta(entry.snap, envelopes);
|
|
28867
|
+
if (next) {
|
|
28868
|
+
let recent = entry.recent;
|
|
28869
|
+
let logFrom = entry.logFrom;
|
|
28870
|
+
if (next !== entry.snap) {
|
|
28871
|
+
recent = [...recent, ...envelopes.filter((e) => e.seq > entry.snap.seq)];
|
|
28872
|
+
if (recent.length > boardCachePolicy.recentMax) {
|
|
28873
|
+
recent = recent.slice(-boardCachePolicy.recentMax);
|
|
28874
|
+
logFrom = recent[0].seq - 1;
|
|
28875
|
+
}
|
|
28876
|
+
}
|
|
28877
|
+
const delta = envelopes.reduce((sum, e) => sum + JSON.stringify(e.op).length, 0);
|
|
28878
|
+
storeEntry(key, {
|
|
28879
|
+
snap: next,
|
|
28880
|
+
// O ETag cobre o snapshot inteiro: se o seq andou, o guardado não vale mais.
|
|
28881
|
+
etag: next === entry.snap ? entry.etag : null,
|
|
28882
|
+
bytes: entry.bytes + delta,
|
|
28883
|
+
checkedAt: boardCachePolicy.now(),
|
|
28884
|
+
recent,
|
|
28885
|
+
logFrom
|
|
28886
|
+
});
|
|
28887
|
+
return next;
|
|
28888
|
+
}
|
|
28889
|
+
}
|
|
28890
|
+
const res = await this.client.requestMeta("GET", `/boards/${boardId4}`, {
|
|
28891
|
+
base: this.cfg.canvasBase,
|
|
28892
|
+
headers: entry?.etag ? { "If-None-Match": entry.etag } : void 0
|
|
28893
|
+
});
|
|
28894
|
+
if (res.status === 304 && entry) {
|
|
28895
|
+
storeEntry(key, { ...entry, checkedAt: boardCachePolicy.now() });
|
|
28896
|
+
return entry.snap;
|
|
28897
|
+
}
|
|
28898
|
+
if (!res.data) throw new ApiError(502, "O servidor do Canvas respondeu sem o board.");
|
|
28899
|
+
storeEntry(key, {
|
|
28900
|
+
snap: res.data,
|
|
28901
|
+
etag: res.etag,
|
|
28902
|
+
bytes: res.bytes,
|
|
28903
|
+
checkedAt: boardCachePolicy.now(),
|
|
28904
|
+
recent: [],
|
|
28905
|
+
logFrom: res.data.seq
|
|
28906
|
+
});
|
|
28907
|
+
return res.data;
|
|
28908
|
+
}
|
|
28909
|
+
/** Esquece o board deste token (ex.: o servidor recusou por papel e o cache pode estar velho). */
|
|
28910
|
+
forget(boardId4) {
|
|
28911
|
+
boardStore.delete(this.cacheKey(boardId4));
|
|
25514
28912
|
}
|
|
25515
|
-
/**
|
|
28913
|
+
/**
|
|
28914
|
+
* O que mudou depois de `after`. Vem do cache quando a última leitura cobre esse trecho (o
|
|
28915
|
+
* edit() acabou de reler), senão da rede. `null` quando o servidor manda reler a foto (410).
|
|
28916
|
+
*/
|
|
25516
28917
|
async opsAfter(boardId4, after) {
|
|
28918
|
+
const entry = boardStore.get(this.cacheKey(boardId4));
|
|
28919
|
+
if (entry && after >= entry.logFrom && after <= entry.snap.seq) return entry.recent.filter((e) => e.seq > after);
|
|
28920
|
+
return this.fetchOpsAfter(boardId4, after);
|
|
28921
|
+
}
|
|
28922
|
+
/** Replay depois de `after`. `null` quando o servidor manda reler a foto (410). */
|
|
28923
|
+
async fetchOpsAfter(boardId4, after) {
|
|
25517
28924
|
try {
|
|
25518
28925
|
const { envelopes } = await this.req("GET", `/boards/${boardId4}/ops`, {
|
|
25519
28926
|
query: { after }
|
|
@@ -25525,9 +28932,14 @@ var CanvasApi = class {
|
|
|
25525
28932
|
}
|
|
25526
28933
|
}
|
|
25527
28934
|
async commit(boardId4, ops) {
|
|
25528
|
-
const send = () =>
|
|
25529
|
-
|
|
25530
|
-
|
|
28935
|
+
const send = () => (
|
|
28936
|
+
// Reenvio seguro: o servidor ignora operação com id que já entrou.
|
|
28937
|
+
this.client.request("POST", `/boards/${boardId4}/ops`, {
|
|
28938
|
+
base: this.cfg.canvasBase,
|
|
28939
|
+
body: { coreVersion: this.coreVersion, ops },
|
|
28940
|
+
retry: true
|
|
28941
|
+
})
|
|
28942
|
+
);
|
|
25531
28943
|
try {
|
|
25532
28944
|
return await send();
|
|
25533
28945
|
} catch (e) {
|
|
@@ -25707,6 +29119,33 @@ var KINDS = {
|
|
|
25707
29119
|
outputs: ["audio", "approved"],
|
|
25708
29120
|
dynamic: "style conforme o modelo; SeedAudio 1.0 tem reference (audio, at\xE9 3 vozes na ordem @Audio1..3), volume seedLoudnessRate (-50..100), usa voice: seed-auto e seedConsent: true com refer\xEAncia; alternativa seedReferenceGenerationId de gera\xE7\xE3o pr\xF3pria"
|
|
25709
29121
|
},
|
|
29122
|
+
"audio-tools": {
|
|
29123
|
+
title: "Ferramentas de \xE1udio",
|
|
29124
|
+
size: { w: 320, h: 212 },
|
|
29125
|
+
data: {
|
|
29126
|
+
tool: "sfx",
|
|
29127
|
+
model: null,
|
|
29128
|
+
voice: null,
|
|
29129
|
+
durationSec: null,
|
|
29130
|
+
loop: false,
|
|
29131
|
+
instrumental: true,
|
|
29132
|
+
removeNoise: false,
|
|
29133
|
+
language: null,
|
|
29134
|
+
diarize: true,
|
|
29135
|
+
audioEvents: false,
|
|
29136
|
+
targetLang: "en",
|
|
29137
|
+
sourceLang: null,
|
|
29138
|
+
dubMode: "v1",
|
|
29139
|
+
history: [],
|
|
29140
|
+
pinned: null,
|
|
29141
|
+
results: [],
|
|
29142
|
+
pinnedResult: null
|
|
29143
|
+
},
|
|
29144
|
+
inputs: ["prompt", "lyrics", "source"],
|
|
29145
|
+
outputs: ["audio", "approved", "text", "subtitle", "video"],
|
|
29146
|
+
dynamic: "as portas mudam com data.tool (sfx, isolate, voice_change, music, stems, transcribe, dub)",
|
|
29147
|
+
main: "tool"
|
|
29148
|
+
},
|
|
25710
29149
|
music: {
|
|
25711
29150
|
title: "Trilha",
|
|
25712
29151
|
size: { w: 320, h: 212 },
|
|
@@ -25797,6 +29236,7 @@ function ratioOfAspect(aspect) {
|
|
|
25797
29236
|
const height = Number(match[2]);
|
|
25798
29237
|
return width2 > 0 && height > 0 ? width2 / height : null;
|
|
25799
29238
|
}
|
|
29239
|
+
var DUB_NOTE = "Dublagem no Canvas exige clique de pessoa: agente n\xE3o roda. ";
|
|
25800
29240
|
function isGeneratorKind(kind) {
|
|
25801
29241
|
return kind === "image" || kind === "video";
|
|
25802
29242
|
}
|
|
@@ -25819,7 +29259,7 @@ function knownPort(kind, side, port) {
|
|
|
25819
29259
|
}
|
|
25820
29260
|
|
|
25821
29261
|
// src/canvas/core.ts
|
|
25822
|
-
import { randomBytes, randomUUID } from "crypto";
|
|
29262
|
+
import { randomBytes, randomUUID as randomUUID2 } from "crypto";
|
|
25823
29263
|
var SCHEMA_VERSION = 1;
|
|
25824
29264
|
var MAX_ENVELOPES_PER_COMMIT = 200;
|
|
25825
29265
|
var MAX_OP_BYTES = 64 * 1024;
|
|
@@ -25905,7 +29345,7 @@ function checkOp(op) {
|
|
|
25905
29345
|
}
|
|
25906
29346
|
}
|
|
25907
29347
|
function envelope(boardId4, op, actorId) {
|
|
25908
|
-
return { id:
|
|
29348
|
+
return { id: randomUUID2(), boardId: boardId4, clientId: CLIENT_ID, actorId, seq: null, ts: Date.now(), op };
|
|
25909
29349
|
}
|
|
25910
29350
|
function checkEnvelope(env) {
|
|
25911
29351
|
const bad = checkOp(env.op);
|
|
@@ -25917,7 +29357,7 @@ function checkEnvelope(env) {
|
|
|
25917
29357
|
}
|
|
25918
29358
|
function emptyBoard(title, now = Date.now()) {
|
|
25919
29359
|
return {
|
|
25920
|
-
id:
|
|
29360
|
+
id: randomUUID2(),
|
|
25921
29361
|
schemaVersion: SCHEMA_VERSION,
|
|
25922
29362
|
title,
|
|
25923
29363
|
ownerId: "",
|
|
@@ -25934,7 +29374,7 @@ function emptyBoard(title, now = Date.now()) {
|
|
|
25934
29374
|
function makeNode(init) {
|
|
25935
29375
|
const now = init.now ?? Date.now();
|
|
25936
29376
|
return {
|
|
25937
|
-
id: init.id ??
|
|
29377
|
+
id: init.id ?? randomUUID2(),
|
|
25938
29378
|
type: init.type,
|
|
25939
29379
|
position: { x: init.position.x, y: init.position.y },
|
|
25940
29380
|
size: { w: init.size.w, h: init.size.h },
|
|
@@ -25948,7 +29388,7 @@ function makeNode(init) {
|
|
|
25948
29388
|
}
|
|
25949
29389
|
function makeEdge(init) {
|
|
25950
29390
|
return {
|
|
25951
|
-
id:
|
|
29391
|
+
id: randomUUID2(),
|
|
25952
29392
|
source: init.source,
|
|
25953
29393
|
sourcePort: init.sourcePort,
|
|
25954
29394
|
target: init.target,
|
|
@@ -27186,7 +30626,7 @@ ${text}`;
|
|
|
27186
30626
|
}
|
|
27187
30627
|
|
|
27188
30628
|
// src/canvas/upload.ts
|
|
27189
|
-
import { randomUUID as
|
|
30629
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
27190
30630
|
import { basename as basename2, extname as extname3 } from "path";
|
|
27191
30631
|
function kindOfMime(mime) {
|
|
27192
30632
|
if (mime.startsWith("image/")) return "image";
|
|
@@ -27226,7 +30666,7 @@ async function uploadMedia(cfg, source, name) {
|
|
|
27226
30666
|
meta: meta ?? {},
|
|
27227
30667
|
measuredBy,
|
|
27228
30668
|
reused,
|
|
27229
|
-
assetId: `asset_${
|
|
30669
|
+
assetId: `asset_${randomUUID3()}`
|
|
27230
30670
|
};
|
|
27231
30671
|
}
|
|
27232
30672
|
function mediaItem(u) {
|
|
@@ -27408,9 +30848,14 @@ ${payload(u)}`
|
|
|
27408
30848
|
}
|
|
27409
30849
|
|
|
27410
30850
|
// src/tools/canvas-run.ts
|
|
27411
|
-
import { randomUUID as
|
|
30851
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
27412
30852
|
var MAX_REMEMBERED = 50;
|
|
27413
|
-
var acceptedPacing = { repeats:
|
|
30853
|
+
var acceptedPacing = { repeats: 8, pauseMs: 2e3 };
|
|
30854
|
+
var statusPacing = {
|
|
30855
|
+
minIntervalMs: 3e3,
|
|
30856
|
+
now: () => Date.now(),
|
|
30857
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
|
|
30858
|
+
};
|
|
27414
30859
|
var sleep3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
27415
30860
|
var seconds = (ms) => `${new Intl.NumberFormat("pt-BR", { maximumFractionDigits: 1 }).format(ms / 1e3)} s`;
|
|
27416
30861
|
function timingsLine(t) {
|
|
@@ -27432,23 +30877,23 @@ function prettyClient(name) {
|
|
|
27432
30877
|
function modeText(mode) {
|
|
27433
30878
|
return mode === "simulated" ? "Simulado (n\xE3o gasta)" : mode === "live" ? "Real" : mode ?? "?";
|
|
27434
30879
|
}
|
|
27435
|
-
function estimateLines(
|
|
27436
|
-
if (!
|
|
30880
|
+
function estimateLines(estimate2, titleOf) {
|
|
30881
|
+
if (!estimate2) return [];
|
|
27437
30882
|
const lines = [];
|
|
27438
|
-
const nodes =
|
|
30883
|
+
const nodes = estimate2.nodes ?? [];
|
|
27439
30884
|
const now = nodes.filter((n) => n.willRun);
|
|
27440
30885
|
for (const n of now) {
|
|
27441
30886
|
const cost = n.error ? `estimativa falhou (${n.error})` : dia(n.diamonds);
|
|
27442
30887
|
lines.push(`- ${n.title ?? titleOf(n.nodeId)} (${n.nodeId}): ${cost}`);
|
|
27443
30888
|
}
|
|
27444
|
-
if (
|
|
27445
|
-
lines.push(`\u2026 e mais ${
|
|
30889
|
+
if (estimate2.omitted) {
|
|
30890
|
+
lines.push(`\u2026 e mais ${estimate2.omitted} n\xF3(s) fora da lista (a resposta da aba foi cortada pelo tamanho; o total vale para todos).`);
|
|
27446
30891
|
}
|
|
27447
|
-
const cached2 =
|
|
30892
|
+
const cached2 = estimate2.cached ?? nodes.filter((n) => !n.willRun && !n.afterApproval).length;
|
|
27448
30893
|
if (cached2) lines.push(`Em cache (n\xE3o rodam): ${cached2}.`);
|
|
27449
|
-
const later =
|
|
27450
|
-
if (later) lines.push(`Esperando aprova\xE7\xE3o no board depois disso: ${later} n\xF3(s), \u2248 ${dia(
|
|
27451
|
-
const unknown2 =
|
|
30894
|
+
const later = estimate2.counts?.later ?? estimate2.later?.nodes?.length ?? 0;
|
|
30895
|
+
if (later) lines.push(`Esperando aprova\xE7\xE3o no board depois disso: ${later} n\xF3(s), \u2248 ${dia(estimate2.later?.total ?? 0)} (fora desta conta).`);
|
|
30896
|
+
const unknown2 = estimate2.counts?.unknown ?? estimate2.unknown?.length ?? 0;
|
|
27452
30897
|
if (unknown2) {
|
|
27453
30898
|
lines.push(`Sem estimativa: ${unknown2} n\xF3(s) (texto cobra por token; o total \xE9 piso).`);
|
|
27454
30899
|
}
|
|
@@ -27465,6 +30910,7 @@ function targetOf(args) {
|
|
|
27465
30910
|
}
|
|
27466
30911
|
function registerCanvasRunTools(server, api, run) {
|
|
27467
30912
|
const remembered = /* @__PURE__ */ new Map();
|
|
30913
|
+
const lastStatusAt = /* @__PURE__ */ new Map();
|
|
27468
30914
|
const remember = (requestId, entry) => {
|
|
27469
30915
|
remembered.delete(requestId);
|
|
27470
30916
|
remembered.set(requestId, entry);
|
|
@@ -27553,7 +30999,7 @@ function registerCanvasRunTools(server, api, run) {
|
|
|
27553
30999
|
},
|
|
27554
31000
|
async (args) => run(async () => {
|
|
27555
31001
|
const target = targetOf(args);
|
|
27556
|
-
const requestId = (args.request_id ??
|
|
31002
|
+
const requestId = (args.request_id ?? randomUUID4()).toLowerCase();
|
|
27557
31003
|
const label = args.label ?? prettyClient(server.server.getClientVersion()?.name);
|
|
27558
31004
|
const ask = async () => {
|
|
27559
31005
|
try {
|
|
@@ -27612,6 +31058,11 @@ function registerCanvasRunTools(server, api, run) {
|
|
|
27612
31058
|
},
|
|
27613
31059
|
async ({ board_id, request_id, node_ids }) => run(async () => {
|
|
27614
31060
|
const requestId = request_id.toLowerCase();
|
|
31061
|
+
const since = statusPacing.now() - (lastStatusAt.get(requestId) ?? -Infinity);
|
|
31062
|
+
if (since < statusPacing.minIntervalMs) await statusPacing.sleep(statusPacing.minIntervalMs - since);
|
|
31063
|
+
lastStatusAt.delete(requestId);
|
|
31064
|
+
lastStatusAt.set(requestId, statusPacing.now());
|
|
31065
|
+
while (lastStatusAt.size > MAX_REMEMBERED) lastStatusAt.delete(lastStatusAt.keys().next().value);
|
|
27615
31066
|
let why = "";
|
|
27616
31067
|
try {
|
|
27617
31068
|
const status = await api.runStatus(board_id, requestId);
|
|
@@ -27628,7 +31079,7 @@ function registerCanvasRunTools(server, api, run) {
|
|
|
27628
31079
|
}
|
|
27629
31080
|
const partial2 = known?.omitted ? ` (parcial: s\xF3 os ${ids.length} n\xF3s que a aba listou; outros ${known.omitted} ficaram fora da resposta. Para eles, chame com node_ids)` : "";
|
|
27630
31081
|
return `${why} Pelo estado de execu\xE7\xE3o do board${partial2}:
|
|
27631
|
-
${fromRuns(await api.snapshot(board_id), ids)}`;
|
|
31082
|
+
${fromRuns(await api.snapshot(board_id, { runs: true }), ids)}`;
|
|
27632
31083
|
})
|
|
27633
31084
|
);
|
|
27634
31085
|
}
|
|
@@ -28050,6 +31501,17 @@ function registerCanvasTools(server, client, cfg) {
|
|
|
28050
31501
|
}
|
|
28051
31502
|
return errorResult(apiErrorToUserMessage(e));
|
|
28052
31503
|
}
|
|
31504
|
+
async function commitOps(id, envs) {
|
|
31505
|
+
try {
|
|
31506
|
+
return await api.commit(id, envs);
|
|
31507
|
+
} catch (e) {
|
|
31508
|
+
if (!(e instanceof ApiError) || e.httpStatus !== 403) throw e;
|
|
31509
|
+
api.forget(id);
|
|
31510
|
+
const again = await api.snapshot(id, { runs: true }).catch(() => null);
|
|
31511
|
+
if (again?.role === "viewer") throw new CanvasToolError("Voc\xEA \xE9 s\xF3 leitor neste board: pe\xE7a ao dono para te dar papel de editor.");
|
|
31512
|
+
throw e;
|
|
31513
|
+
}
|
|
31514
|
+
}
|
|
28053
31515
|
async function run(fn) {
|
|
28054
31516
|
try {
|
|
28055
31517
|
return textResult(await fn());
|
|
@@ -28062,7 +31524,7 @@ function registerCanvasTools(server, client, cfg) {
|
|
|
28062
31524
|
if (last === void 0 && !opts.layoutOnly) {
|
|
28063
31525
|
throw new CanvasToolError("Leia o board com canvas_read_board antes de editar (a leitura vale para a sess\xE3o).");
|
|
28064
31526
|
}
|
|
28065
|
-
const snap = await api.snapshot(id);
|
|
31527
|
+
const snap = await api.snapshot(id, { fresh: true });
|
|
28066
31528
|
if (snap.role === "viewer") throw new CanvasToolError("Voc\xEA \xE9 s\xF3 leitor neste board: pe\xE7a ao dono para te dar papel de editor.");
|
|
28067
31529
|
const doc = snap.doc;
|
|
28068
31530
|
const { ops, done, targets } = await build2(doc, snap);
|
|
@@ -28097,7 +31559,7 @@ Aviso: ${changesSince(theirs, doc)}.`;
|
|
|
28097
31559
|
const env = envelope(id, batchOf(ops), await api.me());
|
|
28098
31560
|
const bad = checkEnvelope(env);
|
|
28099
31561
|
if (bad) throw new CanvasToolError(`Edi\xE7\xE3o recusada antes de enviar: ${bad}.`);
|
|
28100
|
-
const res = await
|
|
31562
|
+
const res = await commitOps(id, [env]);
|
|
28101
31563
|
const outcome = res.outcomes.find((o) => o.opId === env.id);
|
|
28102
31564
|
if (!outcome || "rejected" in outcome) {
|
|
28103
31565
|
if (!opts.layoutOnly) seen.delete(id);
|
|
@@ -28125,7 +31587,7 @@ Aviso: ${changesSince(theirs, doc)}.`;
|
|
|
28125
31587
|
const outcomes = /* @__PURE__ */ new Map();
|
|
28126
31588
|
let last = null;
|
|
28127
31589
|
for (let i = 0; i < envs.length; i += MAX_ENVELOPES_PER_COMMIT) {
|
|
28128
|
-
const res = await
|
|
31590
|
+
const res = await commitOps(id, envs.slice(i, i + MAX_ENVELOPES_PER_COMMIT));
|
|
28129
31591
|
for (const o of res.outcomes) outcomes.set(o.opId, o);
|
|
28130
31592
|
last = res.seq;
|
|
28131
31593
|
}
|
|
@@ -28338,7 +31800,7 @@ ${lines.join("\n")}${note}`;
|
|
|
28338
31800
|
const from = Math.min(offset ?? 0, total);
|
|
28339
31801
|
const size = max_chars ?? 4e4;
|
|
28340
31802
|
const to = Math.min(from + size, total);
|
|
28341
|
-
const hash =
|
|
31803
|
+
const hash = createHash2("sha256").update(json).digest("hex").slice(0, 12);
|
|
28342
31804
|
const where = `data${segments.length ? `.${segments.join(".")}` : ""}`;
|
|
28343
31805
|
const at = readMeasured(node)?.at;
|
|
28344
31806
|
const head = `${node.id} \xB7 ${nodeKind(node) ?? node.type} \xB7 "${oneLine2(nodeName(node), 60)}" \xB7 board seq ${snap.seq} \xB7 tamanho ${sizeLabel(node)}${at ? ` \xB7 medido em ${at}` : ""} \xB7 ${where}${which}: ${total} caracteres (JSON compacto) \xB7 sha256 ${hash}`;
|
|
@@ -28402,7 +31864,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
|
|
|
28402
31864
|
"canvas_add_node",
|
|
28403
31865
|
{
|
|
28404
31866
|
title: "Canvas: adicionar n\xF3",
|
|
28405
|
-
description: `Adiciona um n\xF3 (n\xE3o executa). ${READ}kind: ${kindList()}. data completa o padr\xE3o do tipo; label d\xE1 o nome. Sem position, nasce ao lado do n\xF3 ligado ou \xE0 direita do board (com aba, no fim do conte\xFAdo da aba); aba grava data.abaId. Texto livre (label) sem size {w} nasce na largura do tamanho do texto: titulo 2000, subtitulo 1200, corpo 320. Prompt sem size nasce com 1024 \xD7 516; gerador de imagem ou v\xEDdeo, com altura 516 e a largura do aspect_ratio (16:9 917, 9:16 290, 1:1 516). inputs/outputs j\xE1 ligam o n\xF3 no mesmo passo. ` + MENTION_NOTE + MONTAGE_NOTE,
|
|
31867
|
+
description: `Adiciona um n\xF3 (n\xE3o executa). ${READ}kind: ${kindList()}. data completa o padr\xE3o do tipo; label d\xE1 o nome. Sem position, nasce ao lado do n\xF3 ligado ou \xE0 direita do board (com aba, no fim do conte\xFAdo da aba); aba grava data.abaId. Texto livre (label) sem size {w} nasce na largura do tamanho do texto: titulo 2000, subtitulo 1200, corpo 320. Prompt sem size nasce com 1024 \xD7 516; gerador de imagem ou v\xEDdeo, com altura 516 e a largura do aspect_ratio (16:9 917, 9:16 290, 1:1 516). inputs/outputs j\xE1 ligam o n\xF3 no mesmo passo. ` + DUB_NOTE + MENTION_NOTE + MONTAGE_NOTE,
|
|
28406
31868
|
inputSchema: {
|
|
28407
31869
|
board_id: boardId3,
|
|
28408
31870
|
kind: external_exports.string().min(1).max(40),
|
|
@@ -28467,7 +31929,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
|
|
|
28467
31929
|
"canvas_update_node",
|
|
28468
31930
|
{
|
|
28469
31931
|
title: "Canvas: editar n\xF3",
|
|
28470
|
-
description: `Muda campos do data de um n\xF3, chave a chave (null apaga a chave), sem executar. ${READ}label renomeia; position move; size {w, h} muda a caixa (piso: o cart\xE3o cresce com o conte\xFAdo). N\xE3o troca o tipo. Cada chave \xE9 gravada inteira: leia antes com canvas_read_node e mande o valor completo j\xE1 revisado, para n\xE3o apagar o que outra pessoa escreveu. Para mudar partes de uma estrutura grande (clipes da timeline), use canvas_patch_node, por caminho; v\xE1rios n\xF3s de uma vez, canvas_update_nodes. ` + MENTION_NOTE + MONTAGE_NOTE,
|
|
31932
|
+
description: `Muda campos do data de um n\xF3, chave a chave (null apaga a chave), sem executar. ${READ}label renomeia; position move; size {w, h} muda a caixa (piso: o cart\xE3o cresce com o conte\xFAdo). N\xE3o troca o tipo. Cada chave \xE9 gravada inteira: leia antes com canvas_read_node e mande o valor completo j\xE1 revisado, para n\xE3o apagar o que outra pessoa escreveu. Para mudar partes de uma estrutura grande (clipes da timeline), use canvas_patch_node, por caminho; v\xE1rios n\xF3s de uma vez, canvas_update_nodes. ` + DUB_NOTE + MENTION_NOTE + MONTAGE_NOTE,
|
|
28471
31933
|
inputSchema: {
|
|
28472
31934
|
board_id: boardId3,
|
|
28473
31935
|
node_id: nodeIdArg2,
|
|
@@ -28495,7 +31957,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
|
|
|
28495
31957
|
"canvas_update_nodes",
|
|
28496
31958
|
{
|
|
28497
31959
|
title: "Canvas: editar v\xE1rios n\xF3s",
|
|
28498
|
-
description: 'Muda v\xE1rios n\xF3s num passo s\xF3, cada um como no canvas_update_node (position, size, label, data com null apagando). layout_only: true aceita s\xF3 position e size {w, h}, n\xE3o exige leitura e n\xE3o recusa por "outra pessoa mexeu" (nesses dois campos vale quem grava por \xFAltimo). Sem layout_only, exige canvas_read_board nesta sess\xE3o e recusa se outra pessoa mexeu em algum desses n\xF3s. Quebra em envelopes de at\xE9 64 KB e relata cada um. Para arrumar linhas inteiras (t\xEDtulo, prompt, refer\xEAncia, gerador), use canvas_arrange_rows.',
|
|
31960
|
+
description: 'Muda v\xE1rios n\xF3s num passo s\xF3, cada um como no canvas_update_node (position, size, label, data com null apagando). layout_only: true aceita s\xF3 position e size {w, h}, n\xE3o exige leitura e n\xE3o recusa por "outra pessoa mexeu" (nesses dois campos vale quem grava por \xFAltimo). Sem layout_only, exige canvas_read_board nesta sess\xE3o e recusa se outra pessoa mexeu em algum desses n\xF3s. Quebra em envelopes de at\xE9 64 KB e relata cada um. Para arrumar linhas inteiras (t\xEDtulo, prompt, refer\xEAncia, gerador), use canvas_arrange_rows. ' + DUB_NOTE,
|
|
28499
31961
|
inputSchema: {
|
|
28500
31962
|
board_id: boardId3,
|
|
28501
31963
|
nodes: external_exports.array(
|
|
@@ -28547,7 +32009,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
|
|
|
28547
32009
|
"canvas_patch_node",
|
|
28548
32010
|
{
|
|
28549
32011
|
title: "Canvas: gravar por caminho",
|
|
28550
|
-
description: `Grava v\xE1rios caminhos dentro do data de um n\xF3, sem executar: {path, value} grava, {path, unset: true} apaga. ${READ}O caminho atravessa objetos (o n\xEDvel que falta \xE9 criado) e n\xE3o entra em lista: para mudar um item de lista, grave a lista inteira. Quebra sozinho em envelopes de at\xE9 64 KB, em ordem, e devolve o resultado de cada um; entre envelopes n\xE3o h\xE1 atomicidade (o que entrou fica). Serve para mexer em partes de uma estrutura grande, como clipes da timeline da Montagem, sem reenviar tudo. Leia antes com canvas_read_node. ` + MENTION_NOTE + MONTAGE_NOTE,
|
|
32012
|
+
description: `Grava v\xE1rios caminhos dentro do data de um n\xF3, sem executar: {path, value} grava, {path, unset: true} apaga. ${READ}O caminho atravessa objetos (o n\xEDvel que falta \xE9 criado) e n\xE3o entra em lista: para mudar um item de lista, grave a lista inteira. Quebra sozinho em envelopes de at\xE9 64 KB, em ordem, e devolve o resultado de cada um; entre envelopes n\xE3o h\xE1 atomicidade (o que entrou fica). Serve para mexer em partes de uma estrutura grande, como clipes da timeline da Montagem, sem reenviar tudo. Leia antes com canvas_read_node. ` + DUB_NOTE + MENTION_NOTE + MONTAGE_NOTE,
|
|
28551
32013
|
inputSchema: {
|
|
28552
32014
|
board_id: boardId3,
|
|
28553
32015
|
node_id: nodeIdArg2,
|
|
@@ -28787,7 +32249,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
|
|
|
28787
32249
|
import { createRequire } from "module";
|
|
28788
32250
|
var require2 = createRequire(import.meta.url);
|
|
28789
32251
|
function readVersion() {
|
|
28790
|
-
if ("0.
|
|
32252
|
+
if ("0.46.0") return "0.46.0";
|
|
28791
32253
|
try {
|
|
28792
32254
|
const pkg = require2("../package.json");
|
|
28793
32255
|
return pkg.version ?? "0.0.0-unknown";
|
|
@@ -28800,7 +32262,7 @@ var VERSION = readVersion();
|
|
|
28800
32262
|
// src/server.ts
|
|
28801
32263
|
var SERVER_INSTRUCTIONS = [
|
|
28802
32264
|
"BePlus: tudo roda pela conta do usu\xE1rio (diamantes, limites e hist\xF3rico na plataforma).",
|
|
28803
|
-
'M\xEDdia: generate_*
|
|
32265
|
+
'M\xEDdia: generate_* e elevenlabs_* gastam diamantes; confira com estimate_cost antes de lotes grandes. Sem project, a gera\xE7\xE3o cai no projeto ativo; billing:"personal" cobra do usu\xE1rio.',
|
|
28804
32266
|
"Calls: search_calls acha, get_call traz a transcri\xE7\xE3o.",
|
|
28805
32267
|
"Canvas online (canvas_*): leia com canvas_read_board antes de editar e siga o estado lido. Cada edi\xE7\xE3o vai num passo s\xF3; se outra pessoa mexeu nos mesmos n\xF3s, a ferramenta recusa e pede releitura. As canvas_* n\xE3o geram m\xEDdia, exceto canvas_run: roda n\xF3s pela aba do Canvas aberta do usu\xE1rio e gasta diamantes; max_diamonds \xE9 o teto que o usu\xE1rio autorizou (dry_run s\xF3 estima). D\xEA nome (label) aos n\xF3s, n\xE3o invente tipos nem portas, e confirme antes de canvas_delete.",
|
|
28806
32268
|
"Cada aba \xE9 um plano: ao criar, passe aba (id da se\xE7\xE3o) em canvas_add_node e canvas_upload_media, sen\xE3o o cart\xE3o pode cair em Avulsos. canvas_read_board com aba l\xEA uma aba s\xF3.",
|
|
@@ -28815,6 +32277,7 @@ function buildServer(cfg) {
|
|
|
28815
32277
|
registerUpscaleTools(server, client, cfg);
|
|
28816
32278
|
registerAudioTools(server, client, cfg);
|
|
28817
32279
|
registerMusicTools(server, client, cfg);
|
|
32280
|
+
registerElevenLabsTools(server, client, cfg);
|
|
28818
32281
|
registerAccountTools(server, client, cfg);
|
|
28819
32282
|
registerAnalyzeTools(server, client, cfg);
|
|
28820
32283
|
registerProjectTools(server, client, cfg);
|