beplus-mcp 0.44.0 → 0.45.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/dist/index.js +2984 -28
- package/dist/index.js.map +1 -1
- package/dist/remote-server.js +2984 -28
- package/dist/remote-server.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -6885,6 +6885,2721 @@ var require_dist = __commonJS({
|
|
|
6885
6885
|
}
|
|
6886
6886
|
});
|
|
6887
6887
|
|
|
6888
|
+
// src/vendor/canvas-core/index.cjs
|
|
6889
|
+
var require_canvas_core = __commonJS({
|
|
6890
|
+
"src/vendor/canvas-core/index.cjs"(exports, module) {
|
|
6891
|
+
"use strict";
|
|
6892
|
+
var __defProp2 = Object.defineProperty;
|
|
6893
|
+
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
6894
|
+
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
6895
|
+
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
6896
|
+
var __export2 = (target, all) => {
|
|
6897
|
+
for (var name in all)
|
|
6898
|
+
__defProp2(target, name, { get: all[name], enumerable: true });
|
|
6899
|
+
};
|
|
6900
|
+
var __copyProps2 = (to, from, except, desc) => {
|
|
6901
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
6902
|
+
for (let key of __getOwnPropNames2(from))
|
|
6903
|
+
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
6904
|
+
__defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
6905
|
+
}
|
|
6906
|
+
return to;
|
|
6907
|
+
};
|
|
6908
|
+
var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
|
|
6909
|
+
var index_exports = {};
|
|
6910
|
+
__export2(index_exports, {
|
|
6911
|
+
BOARD_FIELDS: () => BOARD_FIELDS,
|
|
6912
|
+
BoardStore: () => BoardStore,
|
|
6913
|
+
DEFAULT_MAX_PER_COLUMN: () => DEFAULT_MAX_PER_COLUMN,
|
|
6914
|
+
DEFAULT_PLACEMENT_GAP: () => DEFAULT_PLACEMENT_GAP,
|
|
6915
|
+
DEFAULT_SHAPE_SIZE: () => DEFAULT_SHAPE_SIZE,
|
|
6916
|
+
DEFAULT_TIDY_GAP_X: () => DEFAULT_TIDY_GAP_X,
|
|
6917
|
+
DEFAULT_TIDY_GAP_Y: () => DEFAULT_TIDY_GAP_Y,
|
|
6918
|
+
DEFAULT_TIDY_SWEEPS: () => DEFAULT_TIDY_SWEEPS,
|
|
6919
|
+
Draft: () => Draft,
|
|
6920
|
+
EMPTY_INTERACTION: () => EMPTY_INTERACTION,
|
|
6921
|
+
FORBIDDEN_PATH_SEGMENTS: () => FORBIDDEN_PATH_SEGMENTS,
|
|
6922
|
+
HISTORY_LIMIT: () => HISTORY_LIMIT,
|
|
6923
|
+
HISTORY_MAX_BYTES: () => HISTORY_MAX_BYTES,
|
|
6924
|
+
HistoryStack: () => HistoryStack,
|
|
6925
|
+
InvalidBoardSetError: () => InvalidBoardSetError,
|
|
6926
|
+
InvalidPathError: () => InvalidPathError,
|
|
6927
|
+
MAX_OP_BYTES: () => MAX_OP_BYTES2,
|
|
6928
|
+
MAX_REPLAY: () => MAX_REPLAY,
|
|
6929
|
+
MIGRATIONS: () => MIGRATIONS,
|
|
6930
|
+
OPS: () => OPS2,
|
|
6931
|
+
OpSyncClient: () => OpSyncClient,
|
|
6932
|
+
OpTooLargeError: () => OpTooLargeError2,
|
|
6933
|
+
SCHEMA_VERSION: () => SCHEMA_VERSION2,
|
|
6934
|
+
SHAPE_NODE_TYPE: () => SHAPE_NODE_TYPE,
|
|
6935
|
+
anyPathCrosses: () => anyPathCrosses,
|
|
6936
|
+
applyBoardSet: () => applyBoardSet,
|
|
6937
|
+
applyConfirmed: () => applyConfirmed2,
|
|
6938
|
+
applyEnvelopes: () => applyEnvelopes,
|
|
6939
|
+
applyOp: () => applyOp,
|
|
6940
|
+
applyOps: () => applyOps,
|
|
6941
|
+
assertBoardSet: () => assertBoardSet,
|
|
6942
|
+
assertOpEnvelopeFits: () => assertOpEnvelopeFits,
|
|
6943
|
+
batchOf: () => batchOf2,
|
|
6944
|
+
boundsOf: () => boundsOf,
|
|
6945
|
+
captureOf: () => captureOf,
|
|
6946
|
+
createCloneCounts: () => createCloneCounts,
|
|
6947
|
+
createEmptyBoard: () => createEmptyBoard,
|
|
6948
|
+
createOpIdGenerator: () => createOpIdGenerator,
|
|
6949
|
+
createShapeNode: () => createShapeNode,
|
|
6950
|
+
defaultScheduler: () => defaultScheduler,
|
|
6951
|
+
estimateOpBytes: () => estimateOpBytes,
|
|
6952
|
+
fanOutPositions: () => fanOutPositions,
|
|
6953
|
+
findFreeSpot: () => findFreeSpot,
|
|
6954
|
+
getPath: () => getPath,
|
|
6955
|
+
hasPath: () => hasPath,
|
|
6956
|
+
invert: () => invert,
|
|
6957
|
+
invertBoardSet: () => invertBoardSet,
|
|
6958
|
+
invertEdgeAdd: () => invertEdgeAdd,
|
|
6959
|
+
invertEdgeRemove: () => invertEdgeRemove,
|
|
6960
|
+
invertHistoryAppend: () => invertHistoryAppend,
|
|
6961
|
+
invertHistoryRemove: () => invertHistoryRemove,
|
|
6962
|
+
invertNodeAdd: () => invertNodeAdd,
|
|
6963
|
+
invertNodeRemove: () => invertNodeRemove,
|
|
6964
|
+
invertNodeSet: () => invertNodeSet,
|
|
6965
|
+
invertResultSet: () => invertResultSet,
|
|
6966
|
+
isLocalEnvelope: () => isLocalEnvelope,
|
|
6967
|
+
isPropValue: () => isPropValue,
|
|
6968
|
+
migrate: () => migrate,
|
|
6969
|
+
moveOps: () => moveOps,
|
|
6970
|
+
newOpId: () => newOpId,
|
|
6971
|
+
opEnvelopeBytes: () => opEnvelopeBytes,
|
|
6972
|
+
parsePath: () => parsePath,
|
|
6973
|
+
pathsCross: () => pathsCross,
|
|
6974
|
+
placeWithoutOverlap: () => placeWithoutOverlap,
|
|
6975
|
+
propValue: () => propValue,
|
|
6976
|
+
rectOf: () => rectOf2,
|
|
6977
|
+
rectsCollide: () => rectsCollide,
|
|
6978
|
+
reduce: () => reduce,
|
|
6979
|
+
removeNode: () => removeNode,
|
|
6980
|
+
sameBox: () => sameBox,
|
|
6981
|
+
sameNodeIds: () => sameNodeIds,
|
|
6982
|
+
setPath: () => setPath,
|
|
6983
|
+
shallowestMissingPath: () => shallowestMissingPath,
|
|
6984
|
+
tidyUp: () => tidyUp,
|
|
6985
|
+
tidyUpOps: () => tidyUpOps,
|
|
6986
|
+
touchedPaths: () => touchedPaths,
|
|
6987
|
+
trackCapture: () => trackCapture,
|
|
6988
|
+
tryApplyEnvelope: () => tryApplyEnvelope,
|
|
6989
|
+
tryApplyOp: () => tryApplyOp,
|
|
6990
|
+
unsetPath: () => unsetPath,
|
|
6991
|
+
unsetPropValue: () => unsetPropValue,
|
|
6992
|
+
utf8ByteLength: () => utf8ByteLength,
|
|
6993
|
+
walkBatch: () => walkBatch,
|
|
6994
|
+
writeKey: () => writeKey
|
|
6995
|
+
});
|
|
6996
|
+
module.exports = __toCommonJS(index_exports);
|
|
6997
|
+
var SCHEMA_VERSION2 = 1;
|
|
6998
|
+
var SHAPE_NODE_TYPE = "shape";
|
|
6999
|
+
var DEFAULT_SHAPE_SIZE = { w: 180, h: 120 };
|
|
7000
|
+
function randomUuidV4() {
|
|
7001
|
+
let out = "";
|
|
7002
|
+
for (let i = 0; i < 36; i += 1) {
|
|
7003
|
+
if (i === 8 || i === 13 || i === 18 || i === 23) {
|
|
7004
|
+
out += "-";
|
|
7005
|
+
continue;
|
|
7006
|
+
}
|
|
7007
|
+
if (i === 14) {
|
|
7008
|
+
out += "4";
|
|
7009
|
+
continue;
|
|
7010
|
+
}
|
|
7011
|
+
const value = Math.floor(Math.random() * 16);
|
|
7012
|
+
out += (i === 19 ? value & 3 | 8 : value).toString(16);
|
|
7013
|
+
}
|
|
7014
|
+
return out;
|
|
7015
|
+
}
|
|
7016
|
+
function createEmptyBoard(init = {}) {
|
|
7017
|
+
const newId = init.newId ?? randomUuidV4;
|
|
7018
|
+
const timestamp = (init.now ?? Date.now)();
|
|
7019
|
+
return {
|
|
7020
|
+
id: init.id ?? newId(),
|
|
7021
|
+
schemaVersion: SCHEMA_VERSION2,
|
|
7022
|
+
title: init.title ?? "Board sem t\xEDtulo",
|
|
7023
|
+
ownerId: init.ownerId ?? "",
|
|
7024
|
+
folderId: init.folderId ?? null,
|
|
7025
|
+
version: 0,
|
|
7026
|
+
nodes: {},
|
|
7027
|
+
edges: {},
|
|
7028
|
+
results: {},
|
|
7029
|
+
nodeHistory: {},
|
|
7030
|
+
createdAt: timestamp,
|
|
7031
|
+
updatedAt: timestamp
|
|
7032
|
+
};
|
|
7033
|
+
}
|
|
7034
|
+
function createShapeNode(shape, init = {}) {
|
|
7035
|
+
const newId = init.newId ?? randomUuidV4;
|
|
7036
|
+
const timestamp = (init.now ?? Date.now)();
|
|
7037
|
+
return {
|
|
7038
|
+
id: init.id ?? newId(),
|
|
7039
|
+
type: SHAPE_NODE_TYPE,
|
|
7040
|
+
position: init.position ?? { x: 0, y: 0 },
|
|
7041
|
+
size: init.size ?? { w: DEFAULT_SHAPE_SIZE.w, h: DEFAULT_SHAPE_SIZE.h },
|
|
7042
|
+
zIndex: init.zIndex ?? 0,
|
|
7043
|
+
parentId: init.parentId ?? null,
|
|
7044
|
+
data: { shape },
|
|
7045
|
+
createdBy: init.createdBy ?? null,
|
|
7046
|
+
createdAt: timestamp,
|
|
7047
|
+
updatedAt: timestamp
|
|
7048
|
+
};
|
|
7049
|
+
}
|
|
7050
|
+
var MIGRATIONS = {};
|
|
7051
|
+
var MAX_MIGRATION_STEPS = 16;
|
|
7052
|
+
function isRecord2(value) {
|
|
7053
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7054
|
+
}
|
|
7055
|
+
function isFiniteNumber3(value) {
|
|
7056
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
7057
|
+
}
|
|
7058
|
+
function isStringOrNull2(value) {
|
|
7059
|
+
return value === null || typeof value === "string";
|
|
7060
|
+
}
|
|
7061
|
+
function isSeq(value) {
|
|
7062
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
7063
|
+
}
|
|
7064
|
+
function hasOnlyKeys2(record2, keys) {
|
|
7065
|
+
return Object.keys(record2).every((key) => keys.includes(key));
|
|
7066
|
+
}
|
|
7067
|
+
function isJson2(value) {
|
|
7068
|
+
if (value === null) return true;
|
|
7069
|
+
const kind = typeof value;
|
|
7070
|
+
if (kind === "boolean" || kind === "string") return true;
|
|
7071
|
+
if (kind === "number") return Number.isFinite(value);
|
|
7072
|
+
if (Array.isArray(value)) return value.every(isJson2);
|
|
7073
|
+
if (isRecord2(value)) return Object.values(value).every(isJson2);
|
|
7074
|
+
return false;
|
|
7075
|
+
}
|
|
7076
|
+
function isJsonBag2(value) {
|
|
7077
|
+
return isRecord2(value) && Object.values(value).every(isJson2);
|
|
7078
|
+
}
|
|
7079
|
+
function isStringMap(value) {
|
|
7080
|
+
return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
|
|
7081
|
+
}
|
|
7082
|
+
function isPoint2(value) {
|
|
7083
|
+
return isRecord2(value) && hasOnlyKeys2(value, ["x", "y"]) && isFiniteNumber3(value["x"]) && isFiniteNumber3(value["y"]);
|
|
7084
|
+
}
|
|
7085
|
+
function isSize2(value) {
|
|
7086
|
+
return isRecord2(value) && hasOnlyKeys2(value, ["w", "h"]) && isFiniteNumber3(value["w"]) && isFiniteNumber3(value["h"]);
|
|
7087
|
+
}
|
|
7088
|
+
var NODE_KEYS2 = [
|
|
7089
|
+
"id",
|
|
7090
|
+
"type",
|
|
7091
|
+
"position",
|
|
7092
|
+
"size",
|
|
7093
|
+
"zIndex",
|
|
7094
|
+
"parentId",
|
|
7095
|
+
"data",
|
|
7096
|
+
"createdBy",
|
|
7097
|
+
"createdAt",
|
|
7098
|
+
"updatedAt"
|
|
7099
|
+
];
|
|
7100
|
+
var EDGE_KEYS2 = [
|
|
7101
|
+
"id",
|
|
7102
|
+
"source",
|
|
7103
|
+
"sourcePort",
|
|
7104
|
+
"target",
|
|
7105
|
+
"targetPort",
|
|
7106
|
+
"data",
|
|
7107
|
+
"createdBy",
|
|
7108
|
+
"createdAt"
|
|
7109
|
+
];
|
|
7110
|
+
var RESULT_KEYS = [
|
|
7111
|
+
"id",
|
|
7112
|
+
"nodeId",
|
|
7113
|
+
"runId",
|
|
7114
|
+
"generationId",
|
|
7115
|
+
"kind",
|
|
7116
|
+
"url",
|
|
7117
|
+
"lodUrls",
|
|
7118
|
+
"status",
|
|
7119
|
+
"spec",
|
|
7120
|
+
"costDiamonds",
|
|
7121
|
+
"error",
|
|
7122
|
+
"createdAt"
|
|
7123
|
+
];
|
|
7124
|
+
var DOC_KEYS = [
|
|
7125
|
+
"id",
|
|
7126
|
+
"schemaVersion",
|
|
7127
|
+
"title",
|
|
7128
|
+
"ownerId",
|
|
7129
|
+
"folderId",
|
|
7130
|
+
"version",
|
|
7131
|
+
"nodes",
|
|
7132
|
+
"edges",
|
|
7133
|
+
"results",
|
|
7134
|
+
"nodeHistory",
|
|
7135
|
+
"createdAt",
|
|
7136
|
+
"updatedAt",
|
|
7137
|
+
"meta"
|
|
7138
|
+
];
|
|
7139
|
+
var META_KEYS = ["guide", "ialab", "assetUrls"];
|
|
7140
|
+
function isValidMeta(value) {
|
|
7141
|
+
if (value === void 0) return true;
|
|
7142
|
+
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"]));
|
|
7143
|
+
}
|
|
7144
|
+
var RESULT_KINDS = ["image", "video", "audio", "text"];
|
|
7145
|
+
var RESULT_STATUSES = ["pending", "running", "done", "failed", "cancelled"];
|
|
7146
|
+
function isValidNode2(key, value) {
|
|
7147
|
+
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"]);
|
|
7148
|
+
}
|
|
7149
|
+
function isValidEdge2(key, value) {
|
|
7150
|
+
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"]);
|
|
7151
|
+
}
|
|
7152
|
+
function isValidResult(key, value) {
|
|
7153
|
+
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"]);
|
|
7154
|
+
}
|
|
7155
|
+
function isValidHistory(value) {
|
|
7156
|
+
return Array.isArray(value) && value.every((resultId) => typeof resultId === "string");
|
|
7157
|
+
}
|
|
7158
|
+
function normalizeHistory(history) {
|
|
7159
|
+
for (const [nodeId3, list] of Object.entries(history)) {
|
|
7160
|
+
if (Array.isArray(list) && list.length === 0) delete history[nodeId3];
|
|
7161
|
+
}
|
|
7162
|
+
}
|
|
7163
|
+
function everyEntry(value, check2) {
|
|
7164
|
+
return isRecord2(value) && Object.entries(value).every(([key, entry]) => check2(key, entry));
|
|
7165
|
+
}
|
|
7166
|
+
function upgrade(raw) {
|
|
7167
|
+
let current = raw;
|
|
7168
|
+
for (let step2 = 0; step2 <= MAX_MIGRATION_STEPS; step2 += 1) {
|
|
7169
|
+
if (!isRecord2(current)) return null;
|
|
7170
|
+
const version2 = current["schemaVersion"];
|
|
7171
|
+
if (typeof version2 !== "number" || !Number.isInteger(version2)) return null;
|
|
7172
|
+
if (version2 === SCHEMA_VERSION2) return current;
|
|
7173
|
+
const migration = MIGRATIONS[version2];
|
|
7174
|
+
if (migration === void 0) return null;
|
|
7175
|
+
current = migration(current);
|
|
7176
|
+
}
|
|
7177
|
+
return null;
|
|
7178
|
+
}
|
|
7179
|
+
function migrate(raw) {
|
|
7180
|
+
try {
|
|
7181
|
+
return read(raw);
|
|
7182
|
+
} catch {
|
|
7183
|
+
return null;
|
|
7184
|
+
}
|
|
7185
|
+
}
|
|
7186
|
+
function read(raw) {
|
|
7187
|
+
const upgraded = upgrade(raw);
|
|
7188
|
+
if (!isRecord2(upgraded)) return null;
|
|
7189
|
+
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"]);
|
|
7190
|
+
if (!ok) return null;
|
|
7191
|
+
if (isRecord2(upgraded["meta"]) && Object.keys(upgraded["meta"]).length === 0) {
|
|
7192
|
+
delete upgraded["meta"];
|
|
7193
|
+
}
|
|
7194
|
+
normalizeHistory(upgraded["nodeHistory"]);
|
|
7195
|
+
return upgraded;
|
|
7196
|
+
}
|
|
7197
|
+
function propValue(value) {
|
|
7198
|
+
return { kind: "value", value };
|
|
7199
|
+
}
|
|
7200
|
+
function unsetPropValue() {
|
|
7201
|
+
return { kind: "unset" };
|
|
7202
|
+
}
|
|
7203
|
+
function isJson22(root) {
|
|
7204
|
+
const pending = [{ visit: root }];
|
|
7205
|
+
const open3 = /* @__PURE__ */ new Set();
|
|
7206
|
+
for (let step2 = pending.pop(); step2 !== void 0; step2 = pending.pop()) {
|
|
7207
|
+
if ("close" in step2) {
|
|
7208
|
+
open3.delete(step2.close);
|
|
7209
|
+
continue;
|
|
7210
|
+
}
|
|
7211
|
+
const value = step2.visit;
|
|
7212
|
+
if (value === null) continue;
|
|
7213
|
+
const kind = typeof value;
|
|
7214
|
+
if (kind === "boolean" || kind === "string") continue;
|
|
7215
|
+
if (kind === "number") {
|
|
7216
|
+
if (!Number.isFinite(value)) return false;
|
|
7217
|
+
continue;
|
|
7218
|
+
}
|
|
7219
|
+
if (kind !== "object") return false;
|
|
7220
|
+
const node = value;
|
|
7221
|
+
if (open3.has(node)) return false;
|
|
7222
|
+
open3.add(node);
|
|
7223
|
+
pending.push({ close: node });
|
|
7224
|
+
const children = Array.isArray(node) ? node : Object.values(node);
|
|
7225
|
+
for (const item of children) pending.push({ visit: item });
|
|
7226
|
+
}
|
|
7227
|
+
return true;
|
|
7228
|
+
}
|
|
7229
|
+
function isPropValue(candidate) {
|
|
7230
|
+
if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) return false;
|
|
7231
|
+
const record2 = candidate;
|
|
7232
|
+
const keys = Object.keys(record2);
|
|
7233
|
+
if (record2["kind"] === "unset") return keys.length === 1;
|
|
7234
|
+
if (record2["kind"] !== "value") return false;
|
|
7235
|
+
if (keys.length !== 2 || !Object.hasOwn(record2, "value")) return false;
|
|
7236
|
+
return isJson22(record2["value"]);
|
|
7237
|
+
}
|
|
7238
|
+
var FORBIDDEN_PATH_SEGMENTS = ["__proto__", "constructor", "prototype"];
|
|
7239
|
+
var InvalidPathError = class extends Error {
|
|
7240
|
+
/** O caminho recusado, já como veio da operação. */
|
|
7241
|
+
path;
|
|
7242
|
+
constructor(path, reason) {
|
|
7243
|
+
super(`Caminho inv\xE1lido em node.set: ${JSON.stringify(path)} \u2014 ${reason}`);
|
|
7244
|
+
this.name = "InvalidPathError";
|
|
7245
|
+
this.path = path;
|
|
7246
|
+
}
|
|
7247
|
+
};
|
|
7248
|
+
function asRecord(value) {
|
|
7249
|
+
return value;
|
|
7250
|
+
}
|
|
7251
|
+
function isPlainRecord(value) {
|
|
7252
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7253
|
+
}
|
|
7254
|
+
function parsePath(path) {
|
|
7255
|
+
if (path.length === 0) throw new InvalidPathError(path, "caminho vazio");
|
|
7256
|
+
const segments = path.split(".");
|
|
7257
|
+
for (const segment of segments) {
|
|
7258
|
+
if (segment.length === 0) throw new InvalidPathError(path, "segmento vazio entre pontos");
|
|
7259
|
+
if (FORBIDDEN_PATH_SEGMENTS.includes(segment)) {
|
|
7260
|
+
throw new InvalidPathError(path, `segmento proibido: ${segment}`);
|
|
7261
|
+
}
|
|
7262
|
+
}
|
|
7263
|
+
return segments;
|
|
7264
|
+
}
|
|
7265
|
+
function splitLeaf(path) {
|
|
7266
|
+
const segments = parsePath(path);
|
|
7267
|
+
const leaf = segments[segments.length - 1];
|
|
7268
|
+
if (leaf === void 0) throw new InvalidPathError(path, "caminho sem folha");
|
|
7269
|
+
return { parents: segments.slice(0, -1), leaf };
|
|
7270
|
+
}
|
|
7271
|
+
function getPath(target, path) {
|
|
7272
|
+
const segments = parsePath(path);
|
|
7273
|
+
let cursor = target;
|
|
7274
|
+
for (const segment of segments) {
|
|
7275
|
+
if (!isPlainRecord(cursor) || !Object.hasOwn(cursor, segment)) return void 0;
|
|
7276
|
+
cursor = cursor[segment];
|
|
7277
|
+
}
|
|
7278
|
+
return cursor;
|
|
7279
|
+
}
|
|
7280
|
+
function hasPath(target, path) {
|
|
7281
|
+
const segments = parsePath(path);
|
|
7282
|
+
let cursor = target;
|
|
7283
|
+
for (const segment of segments) {
|
|
7284
|
+
if (!isPlainRecord(cursor) || !Object.hasOwn(cursor, segment)) return false;
|
|
7285
|
+
cursor = cursor[segment];
|
|
7286
|
+
}
|
|
7287
|
+
return true;
|
|
7288
|
+
}
|
|
7289
|
+
function setPath(target, path, value) {
|
|
7290
|
+
const { parents, leaf } = splitLeaf(path);
|
|
7291
|
+
const root = { ...asRecord(target) };
|
|
7292
|
+
let cursor = root;
|
|
7293
|
+
for (const segment of parents) {
|
|
7294
|
+
const current = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
|
|
7295
|
+
if (current === void 0) {
|
|
7296
|
+
const created = {};
|
|
7297
|
+
writeKey(cursor, segment, created);
|
|
7298
|
+
cursor = created;
|
|
7299
|
+
continue;
|
|
7300
|
+
}
|
|
7301
|
+
if (!isPlainRecord(current)) {
|
|
7302
|
+
throw new InvalidPathError(path, `o n\xEDvel ${segment} existe e n\xE3o \xE9 objeto`);
|
|
7303
|
+
}
|
|
7304
|
+
const cloned = { ...current };
|
|
7305
|
+
writeKey(cursor, segment, cloned);
|
|
7306
|
+
cursor = cloned;
|
|
7307
|
+
}
|
|
7308
|
+
writeKey(cursor, leaf, value);
|
|
7309
|
+
return root;
|
|
7310
|
+
}
|
|
7311
|
+
function unsetPath(target, path) {
|
|
7312
|
+
if (!hasPath(target, path)) return target;
|
|
7313
|
+
const { parents, leaf } = splitLeaf(path);
|
|
7314
|
+
const root = { ...asRecord(target) };
|
|
7315
|
+
let cursor = root;
|
|
7316
|
+
for (const segment of parents) {
|
|
7317
|
+
const current = cursor[segment];
|
|
7318
|
+
if (!isPlainRecord(current))
|
|
7319
|
+
throw new InvalidPathError(path, `o n\xEDvel ${segment} n\xE3o \xE9 objeto`);
|
|
7320
|
+
const cloned = { ...current };
|
|
7321
|
+
writeKey(cursor, segment, cloned);
|
|
7322
|
+
cursor = cloned;
|
|
7323
|
+
}
|
|
7324
|
+
delete cursor[leaf];
|
|
7325
|
+
return root;
|
|
7326
|
+
}
|
|
7327
|
+
function writeKey(record2, key, value) {
|
|
7328
|
+
if (key === "__proto__") {
|
|
7329
|
+
Object.defineProperty(record2, key, {
|
|
7330
|
+
value,
|
|
7331
|
+
writable: true,
|
|
7332
|
+
enumerable: true,
|
|
7333
|
+
configurable: true
|
|
7334
|
+
});
|
|
7335
|
+
return;
|
|
7336
|
+
}
|
|
7337
|
+
record2[key] = value;
|
|
7338
|
+
}
|
|
7339
|
+
function createCloneCounts() {
|
|
7340
|
+
return { doc: 0, nodes: 0, edges: 0, results: 0, nodeHistory: 0, nodeEntry: 0, historyEntry: 0 };
|
|
7341
|
+
}
|
|
7342
|
+
var Draft = class {
|
|
7343
|
+
base;
|
|
7344
|
+
counts;
|
|
7345
|
+
nodes;
|
|
7346
|
+
edges;
|
|
7347
|
+
results;
|
|
7348
|
+
nodeHistory;
|
|
7349
|
+
nodesOwned = false;
|
|
7350
|
+
edgesOwned = false;
|
|
7351
|
+
resultsOwned = false;
|
|
7352
|
+
nodeHistoryOwned = false;
|
|
7353
|
+
changed = /* @__PURE__ */ new Set();
|
|
7354
|
+
/** Título e metadado do board (`board.set`). Só entram no documento novo se foram escritos. */
|
|
7355
|
+
title;
|
|
7356
|
+
titleChanged = false;
|
|
7357
|
+
boardMeta;
|
|
7358
|
+
metaOwned = false;
|
|
7359
|
+
constructor(base, counts) {
|
|
7360
|
+
this.base = base;
|
|
7361
|
+
this.counts = counts;
|
|
7362
|
+
this.nodes = base.nodes;
|
|
7363
|
+
this.edges = base.edges;
|
|
7364
|
+
this.results = base.results;
|
|
7365
|
+
this.nodeHistory = base.nodeHistory;
|
|
7366
|
+
this.title = base.title;
|
|
7367
|
+
this.boardMeta = base.meta;
|
|
7368
|
+
}
|
|
7369
|
+
// ------------------------------------------------------------------- leitura
|
|
7370
|
+
node(id) {
|
|
7371
|
+
return Object.hasOwn(this.nodes, id) ? this.nodes[id] : void 0;
|
|
7372
|
+
}
|
|
7373
|
+
edge(id) {
|
|
7374
|
+
return Object.hasOwn(this.edges, id) ? this.edges[id] : void 0;
|
|
7375
|
+
}
|
|
7376
|
+
// Não existe leitor de `results` aqui: `result.set` grava sem consultar, e a
|
|
7377
|
+
// inversa dele é nula (story 004). Ler resultado é da fase 2, e o método nasce
|
|
7378
|
+
// no dia em que tiver chamador.
|
|
7379
|
+
history(nodeId3) {
|
|
7380
|
+
return Object.hasOwn(this.nodeHistory, nodeId3) ? this.nodeHistory[nodeId3] : void 0;
|
|
7381
|
+
}
|
|
7382
|
+
/** O título do board como está no rascunho. */
|
|
7383
|
+
boardTitle() {
|
|
7384
|
+
return this.title;
|
|
7385
|
+
}
|
|
7386
|
+
/** O metadado do board como está no rascunho. Ausente: sem metadado. */
|
|
7387
|
+
meta() {
|
|
7388
|
+
return this.boardMeta;
|
|
7389
|
+
}
|
|
7390
|
+
/** Marca o nó como tocado, para o `changedNodeIds` que a projeção lê. */
|
|
7391
|
+
touch(nodeId3) {
|
|
7392
|
+
this.changed.add(nodeId3);
|
|
7393
|
+
}
|
|
7394
|
+
// ------------------------------------------------------------------- escrita
|
|
7395
|
+
putNode(id, node) {
|
|
7396
|
+
this.ownNodes();
|
|
7397
|
+
writeKey(this.nodes, id, node);
|
|
7398
|
+
this.changed.add(id);
|
|
7399
|
+
}
|
|
7400
|
+
/**
|
|
7401
|
+
* Apaga o nó e, junto, a chave de histórico dele que já era lista vazia.
|
|
7402
|
+
*
|
|
7403
|
+
* Apagar a chave não é limpeza de referência, é normalização: lista vazia não
|
|
7404
|
+
* existe na forma canônica, chave ausente é que significa "sem variação"
|
|
7405
|
+
* (`dev/PLANO-FASE-0.md` §4). Descartar `[]` não perde informação nenhuma, e
|
|
7406
|
+
* por isso a inversa `node.add` devolve um documento equivalente sem precisar
|
|
7407
|
+
* recriar a chave. Chave com item continua intocada: aí sim existe informação,
|
|
7408
|
+
* e `node.remove` nunca limpa sozinho nada que carregue informação. Quem tira
|
|
7409
|
+
* as variações de um nó que vai embora é o `batch` de `removeNode`.
|
|
7410
|
+
*
|
|
7411
|
+
* Nó ausente sai antes de qualquer cópia, senão um `node.remove` que o CA8
|
|
7412
|
+
* declara no-op sujaria o rascunho e produziria documento novo por nada.
|
|
7413
|
+
*/
|
|
7414
|
+
dropNode(id) {
|
|
7415
|
+
if (!Object.hasOwn(this.nodes, id)) return;
|
|
7416
|
+
this.ownNodes();
|
|
7417
|
+
delete this.nodes[id];
|
|
7418
|
+
this.changed.add(id);
|
|
7419
|
+
this.discardEmptyHistory(id);
|
|
7420
|
+
}
|
|
7421
|
+
discardEmptyHistory(nodeId3) {
|
|
7422
|
+
const current = this.history(nodeId3);
|
|
7423
|
+
if (current === void 0 || current.length > 0) return;
|
|
7424
|
+
this.ownNodeHistory();
|
|
7425
|
+
delete this.nodeHistory[nodeId3];
|
|
7426
|
+
}
|
|
7427
|
+
/**
|
|
7428
|
+
* Troca um nó pelo resultado de uma escrita por caminho.
|
|
7429
|
+
*
|
|
7430
|
+
* A função recebe o nó e devolve o nó novo, ou o mesmo quando não há o que
|
|
7431
|
+
* mudar. Devolvendo o mesmo, nada é escrito e nenhuma coleção é clonada: é
|
|
7432
|
+
* assim que `node.set` sem efeito sai de graça.
|
|
7433
|
+
*/
|
|
7434
|
+
mutateNode(id, change) {
|
|
7435
|
+
const current = this.node(id);
|
|
7436
|
+
if (current === void 0) return;
|
|
7437
|
+
const next = change(current);
|
|
7438
|
+
if (next === current) return;
|
|
7439
|
+
if (this.counts !== void 0) this.counts.nodeEntry += 1;
|
|
7440
|
+
this.putNode(id, next);
|
|
7441
|
+
}
|
|
7442
|
+
putEdge(id, edge) {
|
|
7443
|
+
this.ownEdges();
|
|
7444
|
+
writeKey(this.edges, id, edge);
|
|
7445
|
+
}
|
|
7446
|
+
dropEdge(id) {
|
|
7447
|
+
if (!Object.hasOwn(this.edges, id)) return;
|
|
7448
|
+
this.ownEdges();
|
|
7449
|
+
delete this.edges[id];
|
|
7450
|
+
}
|
|
7451
|
+
putResult(id, entry) {
|
|
7452
|
+
this.ownResults();
|
|
7453
|
+
writeKey(this.results, id, entry);
|
|
7454
|
+
}
|
|
7455
|
+
/**
|
|
7456
|
+
* Acrescenta uma variação ao histórico do nó, no fim da lista.
|
|
7457
|
+
*
|
|
7458
|
+
* A lista nasce na primeira chamada. Id repetido entra de novo, de propósito:
|
|
7459
|
+
* `history.remove` tira a última ocorrência, então append seguido de remove
|
|
7460
|
+
* devolve a lista exatamente como estava, que é o que a inversa da story 004
|
|
7461
|
+
* precisa.
|
|
7462
|
+
*/
|
|
7463
|
+
appendHistory(nodeId3, resultId) {
|
|
7464
|
+
const current = this.history(nodeId3);
|
|
7465
|
+
const next = current === void 0 ? [] : [...current];
|
|
7466
|
+
if (current !== void 0 && this.counts !== void 0) this.counts.historyEntry += 1;
|
|
7467
|
+
next.push(resultId);
|
|
7468
|
+
this.ownNodeHistory();
|
|
7469
|
+
writeKey(this.nodeHistory, nodeId3, next);
|
|
7470
|
+
this.changed.add(nodeId3);
|
|
7471
|
+
}
|
|
7472
|
+
/**
|
|
7473
|
+
* Tira a última ocorrência da variação no histórico do nó.
|
|
7474
|
+
*
|
|
7475
|
+
* Id ausente é no-op. Lista que fica vazia some junto com a chave: histórico
|
|
7476
|
+
* vazio pendurado em nó que vai ser apagado é exatamente a referência órfã que
|
|
7477
|
+
* o §4 do plano proíbe, e é o que o CA9 cobra depois de `removeNode`.
|
|
7478
|
+
*/
|
|
7479
|
+
removeHistory(nodeId3, resultId) {
|
|
7480
|
+
const current = this.history(nodeId3);
|
|
7481
|
+
if (current === void 0) return;
|
|
7482
|
+
const at = current.lastIndexOf(resultId);
|
|
7483
|
+
if (at === -1) return;
|
|
7484
|
+
if (this.counts !== void 0) this.counts.historyEntry += 1;
|
|
7485
|
+
const next = [...current.slice(0, at), ...current.slice(at + 1)];
|
|
7486
|
+
this.ownNodeHistory();
|
|
7487
|
+
if (next.length === 0) {
|
|
7488
|
+
delete this.nodeHistory[nodeId3];
|
|
7489
|
+
} else {
|
|
7490
|
+
writeKey(this.nodeHistory, nodeId3, next);
|
|
7491
|
+
}
|
|
7492
|
+
this.changed.add(nodeId3);
|
|
7493
|
+
}
|
|
7494
|
+
/** Troca o título. Título igual sai de graça, sem documento novo. */
|
|
7495
|
+
setTitle(title) {
|
|
7496
|
+
if (title === this.title) return;
|
|
7497
|
+
this.title = title;
|
|
7498
|
+
this.titleChanged = true;
|
|
7499
|
+
}
|
|
7500
|
+
/**
|
|
7501
|
+
* Troca o metadado inteiro do board pela versão que `change` devolve.
|
|
7502
|
+
*
|
|
7503
|
+
* Metadado vazio vira ausente: `{}` não existe na forma canônica, pela mesma
|
|
7504
|
+
* razão da lista vazia de `nodeHistory`. Sem isso, gravar e desfazer a dica
|
|
7505
|
+
* num board sem metadado devolveria um documento com `meta: {}` a mais.
|
|
7506
|
+
*/
|
|
7507
|
+
mutateMeta(change) {
|
|
7508
|
+
const current = this.boardMeta ?? {};
|
|
7509
|
+
const next = change(current);
|
|
7510
|
+
if (next === current) return;
|
|
7511
|
+
this.boardMeta = Object.keys(next).length === 0 ? void 0 : next;
|
|
7512
|
+
this.metaOwned = true;
|
|
7513
|
+
}
|
|
7514
|
+
// --------------------------------------------------------- cópia por escrita
|
|
7515
|
+
ownNodes() {
|
|
7516
|
+
if (this.nodesOwned) return;
|
|
7517
|
+
this.nodes = { ...this.base.nodes };
|
|
7518
|
+
this.nodesOwned = true;
|
|
7519
|
+
if (this.counts !== void 0) this.counts.nodes += 1;
|
|
7520
|
+
}
|
|
7521
|
+
ownEdges() {
|
|
7522
|
+
if (this.edgesOwned) return;
|
|
7523
|
+
this.edges = { ...this.base.edges };
|
|
7524
|
+
this.edgesOwned = true;
|
|
7525
|
+
if (this.counts !== void 0) this.counts.edges += 1;
|
|
7526
|
+
}
|
|
7527
|
+
ownResults() {
|
|
7528
|
+
if (this.resultsOwned) return;
|
|
7529
|
+
this.results = { ...this.base.results };
|
|
7530
|
+
this.resultsOwned = true;
|
|
7531
|
+
if (this.counts !== void 0) this.counts.results += 1;
|
|
7532
|
+
}
|
|
7533
|
+
ownNodeHistory() {
|
|
7534
|
+
if (this.nodeHistoryOwned) return;
|
|
7535
|
+
this.nodeHistory = { ...this.base.nodeHistory };
|
|
7536
|
+
this.nodeHistoryOwned = true;
|
|
7537
|
+
if (this.counts !== void 0) this.counts.nodeHistory += 1;
|
|
7538
|
+
}
|
|
7539
|
+
// ---------------------------------------------------------------- fechamento
|
|
7540
|
+
/** Alguma coleção foi escrita? Lote de no-ops não produz documento novo. */
|
|
7541
|
+
get dirty() {
|
|
7542
|
+
return this.nodesOwned || this.edgesOwned || this.resultsOwned || this.nodeHistoryOwned || this.titleChanged || this.metaOwned;
|
|
7543
|
+
}
|
|
7544
|
+
/**
|
|
7545
|
+
* Fecha o rascunho.
|
|
7546
|
+
*
|
|
7547
|
+
* Sem escrita, devolve a própria referência de entrada: o lote inteiro de
|
|
7548
|
+
* no-ops não gera documento novo e a tela não re-renderiza por nada.
|
|
7549
|
+
*
|
|
7550
|
+
* O documento sai sem `Object.freeze`, desvio do plano §4 ("congela e
|
|
7551
|
+
* devolve"), e a razão é custo e alcance. Congelamento fundo percorre o
|
|
7552
|
+
* documento inteiro a cada lote e joga fora justamente o ganho da cópia por
|
|
7553
|
+
* escrita. Congelamento raso protegeria só o objeto de topo, enquanto
|
|
7554
|
+
* `nodes`, `edges`, `results` e `nodeHistory` continuariam mutáveis, e compra
|
|
7555
|
+
* quase nada. Escrever `version` depois não é argumento contra congelar:
|
|
7556
|
+
* spread funciona sobre objeto congelado, e é o que `reduce` já faz. A
|
|
7557
|
+
* garantia de imutabilidade da entrada é estrutural e tem teste.
|
|
7558
|
+
*/
|
|
7559
|
+
finish() {
|
|
7560
|
+
const changedNodeIds = [...this.changed];
|
|
7561
|
+
if (!this.dirty) return { doc: this.base, changedNodeIds };
|
|
7562
|
+
if (this.counts !== void 0) this.counts.doc += 1;
|
|
7563
|
+
const doc = {
|
|
7564
|
+
...this.base,
|
|
7565
|
+
nodes: this.nodes,
|
|
7566
|
+
edges: this.edges,
|
|
7567
|
+
results: this.results,
|
|
7568
|
+
nodeHistory: this.nodeHistory
|
|
7569
|
+
};
|
|
7570
|
+
if (this.titleChanged) doc.title = this.title;
|
|
7571
|
+
if (this.metaOwned) {
|
|
7572
|
+
if (this.boardMeta === void 0) delete doc.meta;
|
|
7573
|
+
else doc.meta = this.boardMeta;
|
|
7574
|
+
}
|
|
7575
|
+
return { doc, changedNodeIds };
|
|
7576
|
+
}
|
|
7577
|
+
};
|
|
7578
|
+
function nodeOf(doc, id) {
|
|
7579
|
+
return Object.hasOwn(doc.nodes, id) ? doc.nodes[id] : void 0;
|
|
7580
|
+
}
|
|
7581
|
+
function edgeOf(doc, id) {
|
|
7582
|
+
return Object.hasOwn(doc.edges, id) ? doc.edges[id] : void 0;
|
|
7583
|
+
}
|
|
7584
|
+
function historyOf(doc, nodeId3) {
|
|
7585
|
+
return Object.hasOwn(doc.nodeHistory, nodeId3) ? doc.nodeHistory[nodeId3] : void 0;
|
|
7586
|
+
}
|
|
7587
|
+
function previousValue(node, path) {
|
|
7588
|
+
return getPath(node, path);
|
|
7589
|
+
}
|
|
7590
|
+
function shallowestMissingPath(target, path) {
|
|
7591
|
+
const walked = [];
|
|
7592
|
+
for (const segment of parsePath(path)) {
|
|
7593
|
+
walked.push(segment);
|
|
7594
|
+
const prefix = walked.join(".");
|
|
7595
|
+
if (!hasPath(target, prefix)) return prefix;
|
|
7596
|
+
}
|
|
7597
|
+
return path;
|
|
7598
|
+
}
|
|
7599
|
+
function invertNodeAdd(doc, op) {
|
|
7600
|
+
const previous = nodeOf(doc, op.nodeId);
|
|
7601
|
+
if (previous === void 0) return { type: "node.remove", nodeId: op.nodeId };
|
|
7602
|
+
return { type: "node.add", nodeId: op.nodeId, node: previous };
|
|
7603
|
+
}
|
|
7604
|
+
function invertNodeRemove(doc, op) {
|
|
7605
|
+
const current = nodeOf(doc, op.nodeId);
|
|
7606
|
+
if (current === void 0) return { type: "node.remove", nodeId: op.nodeId };
|
|
7607
|
+
return { type: "node.add", nodeId: op.nodeId, node: current };
|
|
7608
|
+
}
|
|
7609
|
+
function invertNodeSet(doc, op) {
|
|
7610
|
+
const node = nodeOf(doc, op.nodeId);
|
|
7611
|
+
if (node === void 0) {
|
|
7612
|
+
return { type: "node.set", nodeId: op.nodeId, path: op.path, value: unsetPropValue() };
|
|
7613
|
+
}
|
|
7614
|
+
if (hasPath(node, op.path)) {
|
|
7615
|
+
return {
|
|
7616
|
+
type: "node.set",
|
|
7617
|
+
nodeId: op.nodeId,
|
|
7618
|
+
path: op.path,
|
|
7619
|
+
value: propValue(previousValue(node, op.path))
|
|
7620
|
+
};
|
|
7621
|
+
}
|
|
7622
|
+
return {
|
|
7623
|
+
type: "node.set",
|
|
7624
|
+
nodeId: op.nodeId,
|
|
7625
|
+
path: shallowestMissingPath(node, op.path),
|
|
7626
|
+
value: unsetPropValue()
|
|
7627
|
+
};
|
|
7628
|
+
}
|
|
7629
|
+
function invertEdgeAdd(doc, op) {
|
|
7630
|
+
const previous = edgeOf(doc, op.edgeId);
|
|
7631
|
+
if (previous === void 0) return { type: "edge.remove", edgeId: op.edgeId };
|
|
7632
|
+
return { type: "edge.add", edgeId: op.edgeId, edge: previous };
|
|
7633
|
+
}
|
|
7634
|
+
function invertEdgeRemove(doc, op) {
|
|
7635
|
+
const current = edgeOf(doc, op.edgeId);
|
|
7636
|
+
if (current === void 0) return { type: "edge.remove", edgeId: op.edgeId };
|
|
7637
|
+
return { type: "edge.add", edgeId: op.edgeId, edge: current };
|
|
7638
|
+
}
|
|
7639
|
+
function invertResultSet() {
|
|
7640
|
+
return null;
|
|
7641
|
+
}
|
|
7642
|
+
function invertHistoryAppend(op) {
|
|
7643
|
+
return { type: "history.remove", nodeId: op.nodeId, resultId: op.resultId };
|
|
7644
|
+
}
|
|
7645
|
+
function invertHistoryRemove(doc, op) {
|
|
7646
|
+
const list = historyOf(doc, op.nodeId);
|
|
7647
|
+
const at = list === void 0 ? -1 : list.lastIndexOf(op.resultId);
|
|
7648
|
+
if (list === void 0 || at === -1) {
|
|
7649
|
+
return { type: "history.remove", nodeId: op.nodeId, resultId: op.resultId };
|
|
7650
|
+
}
|
|
7651
|
+
if (at === list.length - 1) {
|
|
7652
|
+
return { type: "history.append", nodeId: op.nodeId, resultId: op.resultId };
|
|
7653
|
+
}
|
|
7654
|
+
const tail = list.slice(at + 1);
|
|
7655
|
+
const ops = [];
|
|
7656
|
+
for (const resultId of [...tail].reverse()) {
|
|
7657
|
+
ops.push({ type: "history.remove", nodeId: op.nodeId, resultId });
|
|
7658
|
+
}
|
|
7659
|
+
ops.push({ type: "history.append", nodeId: op.nodeId, resultId: op.resultId });
|
|
7660
|
+
for (const resultId of tail) {
|
|
7661
|
+
ops.push({ type: "history.append", nodeId: op.nodeId, resultId });
|
|
7662
|
+
}
|
|
7663
|
+
return { type: "batch", ops };
|
|
7664
|
+
}
|
|
7665
|
+
var BOARD_FIELDS = ["title", "guide", "ialab", "assetUrls"];
|
|
7666
|
+
var InvalidBoardSetError = class extends Error {
|
|
7667
|
+
field;
|
|
7668
|
+
constructor(field, reason) {
|
|
7669
|
+
super(`board.set inv\xE1lido em ${JSON.stringify(field)}: ${reason}`);
|
|
7670
|
+
this.name = "InvalidBoardSetError";
|
|
7671
|
+
this.field = field;
|
|
7672
|
+
}
|
|
7673
|
+
};
|
|
7674
|
+
function isPlainRecord2(value) {
|
|
7675
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7676
|
+
}
|
|
7677
|
+
function isStringMap2(value) {
|
|
7678
|
+
return isPlainRecord2(value) && Object.values(value).every((item) => typeof item === "string");
|
|
7679
|
+
}
|
|
7680
|
+
function assertBoardSet(op) {
|
|
7681
|
+
const { field, key, value } = op;
|
|
7682
|
+
if (!BOARD_FIELDS.includes(field)) throw new InvalidBoardSetError(field, "campo desconhecido");
|
|
7683
|
+
if (key !== void 0) {
|
|
7684
|
+
if (field !== "assetUrls") throw new InvalidBoardSetError(field, "s\xF3 assetUrls aceita key");
|
|
7685
|
+
if (key === "" || FORBIDDEN_PATH_SEGMENTS.includes(key)) {
|
|
7686
|
+
throw new InvalidBoardSetError(field, `key recusada: ${JSON.stringify(key)}`);
|
|
7687
|
+
}
|
|
7688
|
+
}
|
|
7689
|
+
if (value.kind === "unset") {
|
|
7690
|
+
if (field === "title") throw new InvalidBoardSetError(field, "t\xEDtulo n\xE3o pode ser apagado");
|
|
7691
|
+
return;
|
|
7692
|
+
}
|
|
7693
|
+
const raw = value.value;
|
|
7694
|
+
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";
|
|
7695
|
+
if (!ok) throw new InvalidBoardSetError(field, "valor com tipo errado");
|
|
7696
|
+
}
|
|
7697
|
+
function applyBoardSet(draft, op) {
|
|
7698
|
+
assertBoardSet(op);
|
|
7699
|
+
const { field, key, value } = op;
|
|
7700
|
+
if (field === "title") {
|
|
7701
|
+
if (value.kind === "value" && typeof value.value === "string") draft.setTitle(value.value);
|
|
7702
|
+
return;
|
|
7703
|
+
}
|
|
7704
|
+
draft.mutateMeta((meta) => {
|
|
7705
|
+
if (field === "assetUrls" && key !== void 0) return withAssetUrl(meta, key, value);
|
|
7706
|
+
return withField(meta, field, value);
|
|
7707
|
+
});
|
|
7708
|
+
}
|
|
7709
|
+
function withField(meta, field, value) {
|
|
7710
|
+
if (value.kind === "unset") {
|
|
7711
|
+
if (!Object.hasOwn(meta, field)) return meta;
|
|
7712
|
+
const next2 = { ...meta };
|
|
7713
|
+
delete next2[field];
|
|
7714
|
+
return next2;
|
|
7715
|
+
}
|
|
7716
|
+
const current = Object.hasOwn(meta, field) ? meta[field] : void 0;
|
|
7717
|
+
if (current === value.value && (value.value === null || typeof value.value === "string")) {
|
|
7718
|
+
return meta;
|
|
7719
|
+
}
|
|
7720
|
+
const next = { ...meta };
|
|
7721
|
+
writeKey(next, field, value.value);
|
|
7722
|
+
return next;
|
|
7723
|
+
}
|
|
7724
|
+
function withAssetUrl(meta, key, value) {
|
|
7725
|
+
const urls = meta.assetUrls;
|
|
7726
|
+
if (value.kind === "unset") {
|
|
7727
|
+
if (urls === void 0 || !Object.hasOwn(urls, key)) return meta;
|
|
7728
|
+
const nextUrls2 = { ...urls };
|
|
7729
|
+
delete nextUrls2[key];
|
|
7730
|
+
return { ...meta, assetUrls: nextUrls2 };
|
|
7731
|
+
}
|
|
7732
|
+
const url = value.value;
|
|
7733
|
+
if (urls !== void 0 && Object.hasOwn(urls, key) && urls[key] === url) return meta;
|
|
7734
|
+
const nextUrls = { ...urls };
|
|
7735
|
+
writeKey(nextUrls, key, url);
|
|
7736
|
+
return { ...meta, assetUrls: nextUrls };
|
|
7737
|
+
}
|
|
7738
|
+
function invertBoardSet(doc, op) {
|
|
7739
|
+
const { field, key } = op;
|
|
7740
|
+
if (field === "title") return { type: "board.set", field, value: propValue(doc.title) };
|
|
7741
|
+
const meta = doc.meta ?? {};
|
|
7742
|
+
if (field === "assetUrls" && key !== void 0) {
|
|
7743
|
+
const urls = meta.assetUrls;
|
|
7744
|
+
if (urls === void 0) return { type: "board.set", field, value: unsetPropValue() };
|
|
7745
|
+
return Object.hasOwn(urls, key) ? { type: "board.set", field, key, value: propValue(urls[key]) } : { type: "board.set", field, key, value: unsetPropValue() };
|
|
7746
|
+
}
|
|
7747
|
+
if (!Object.hasOwn(meta, field)) return { type: "board.set", field, value: unsetPropValue() };
|
|
7748
|
+
return { type: "board.set", field, value: propValue(meta[field]) };
|
|
7749
|
+
}
|
|
7750
|
+
function touchEdgeEnds(draft, source, target) {
|
|
7751
|
+
draft.touch(source);
|
|
7752
|
+
draft.touch(target);
|
|
7753
|
+
}
|
|
7754
|
+
var OPS2 = {
|
|
7755
|
+
"node.add": {
|
|
7756
|
+
apply(draft, op) {
|
|
7757
|
+
draft.putNode(op.nodeId, op.node);
|
|
7758
|
+
},
|
|
7759
|
+
invert: invertNodeAdd
|
|
7760
|
+
},
|
|
7761
|
+
"node.remove": {
|
|
7762
|
+
apply(draft, op) {
|
|
7763
|
+
draft.dropNode(op.nodeId);
|
|
7764
|
+
},
|
|
7765
|
+
invert: invertNodeRemove
|
|
7766
|
+
},
|
|
7767
|
+
"node.set": {
|
|
7768
|
+
apply(draft, op) {
|
|
7769
|
+
draft.mutateNode(
|
|
7770
|
+
op.nodeId,
|
|
7771
|
+
(node) => op.value.kind === "value" ? setPath(node, op.path, op.value.value) : unsetPath(node, op.path)
|
|
7772
|
+
);
|
|
7773
|
+
},
|
|
7774
|
+
invert: invertNodeSet
|
|
7775
|
+
},
|
|
7776
|
+
"edge.add": {
|
|
7777
|
+
apply(draft, op) {
|
|
7778
|
+
draft.putEdge(op.edgeId, op.edge);
|
|
7779
|
+
touchEdgeEnds(draft, op.edge.source, op.edge.target);
|
|
7780
|
+
},
|
|
7781
|
+
invert: invertEdgeAdd
|
|
7782
|
+
},
|
|
7783
|
+
"edge.remove": {
|
|
7784
|
+
apply(draft, op) {
|
|
7785
|
+
const current = draft.edge(op.edgeId);
|
|
7786
|
+
if (current === void 0) return;
|
|
7787
|
+
draft.dropEdge(op.edgeId);
|
|
7788
|
+
touchEdgeEnds(draft, current.source, current.target);
|
|
7789
|
+
},
|
|
7790
|
+
invert: invertEdgeRemove
|
|
7791
|
+
},
|
|
7792
|
+
"result.set": {
|
|
7793
|
+
apply(draft, op) {
|
|
7794
|
+
draft.putResult(op.resultId, op.entry);
|
|
7795
|
+
draft.touch(op.entry.nodeId);
|
|
7796
|
+
},
|
|
7797
|
+
invert: invertResultSet
|
|
7798
|
+
},
|
|
7799
|
+
"history.append": {
|
|
7800
|
+
apply(draft, op) {
|
|
7801
|
+
draft.appendHistory(op.nodeId, op.resultId);
|
|
7802
|
+
},
|
|
7803
|
+
invert: (_doc, op) => invertHistoryAppend(op)
|
|
7804
|
+
},
|
|
7805
|
+
"history.remove": {
|
|
7806
|
+
apply(draft, op) {
|
|
7807
|
+
draft.removeHistory(op.nodeId, op.resultId);
|
|
7808
|
+
},
|
|
7809
|
+
invert: invertHistoryRemove
|
|
7810
|
+
},
|
|
7811
|
+
"board.set": {
|
|
7812
|
+
apply: applyBoardSet,
|
|
7813
|
+
invert: invertBoardSet
|
|
7814
|
+
},
|
|
7815
|
+
batch: {
|
|
7816
|
+
apply(draft, op) {
|
|
7817
|
+
for (const inner of op.ops) applyOp(draft, inner);
|
|
7818
|
+
},
|
|
7819
|
+
/**
|
|
7820
|
+
* As inversas dos membros, em ordem reversa.
|
|
7821
|
+
*
|
|
7822
|
+
* O estado avança membro a membro, e não dá para fugir disso: inverter dois
|
|
7823
|
+
* `history.remove` seguidos contra o MESMO documento de entrada devolveria
|
|
7824
|
+
* dois `history.append` iguais, e a lista voltaria com um item a mais do que
|
|
7825
|
+
* tinha. Quem avança é `walkBatch`, com um rascunho de rascunho que nunca
|
|
7826
|
+
* toca o documento de quem chamou.
|
|
7827
|
+
*/
|
|
7828
|
+
invert(doc, op) {
|
|
7829
|
+
const parts = walkBatch(doc, op.ops, invert);
|
|
7830
|
+
return { type: "batch", ops: parts.reverse() };
|
|
7831
|
+
}
|
|
7832
|
+
}
|
|
7833
|
+
};
|
|
7834
|
+
function applyOp(draft, op) {
|
|
7835
|
+
const handler = OPS2[op.type];
|
|
7836
|
+
handler.apply(draft, op);
|
|
7837
|
+
}
|
|
7838
|
+
function invert(doc, op) {
|
|
7839
|
+
const handler = OPS2[op.type];
|
|
7840
|
+
return handler.invert(doc, op);
|
|
7841
|
+
}
|
|
7842
|
+
function walkBatch(doc, ops, visit) {
|
|
7843
|
+
const scratch = new Draft(doc);
|
|
7844
|
+
const collected = [];
|
|
7845
|
+
for (const op of ops) {
|
|
7846
|
+
const item = visit(scratch.finish().doc, op);
|
|
7847
|
+
if (item !== null) collected.push(item);
|
|
7848
|
+
applyOp(scratch, op);
|
|
7849
|
+
}
|
|
7850
|
+
return collected;
|
|
7851
|
+
}
|
|
7852
|
+
var MAX_OP_BYTES2 = 64 * 1024;
|
|
7853
|
+
var OpTooLargeError2 = class extends Error {
|
|
7854
|
+
/** O envelope recusado, para o `onError` da story 005 citar na mensagem. */
|
|
7855
|
+
opId;
|
|
7856
|
+
/** Quanto ele pesa, serializado em UTF-8. */
|
|
7857
|
+
bytes;
|
|
7858
|
+
/** Quanto cabia. */
|
|
7859
|
+
limit;
|
|
7860
|
+
constructor(opId, bytes, limit = MAX_OP_BYTES2) {
|
|
7861
|
+
super(`Opera\xE7\xE3o ${opId} tem ${bytes} bytes e o teto \xE9 ${limit}`);
|
|
7862
|
+
this.name = "OpTooLargeError";
|
|
7863
|
+
this.opId = opId;
|
|
7864
|
+
this.bytes = bytes;
|
|
7865
|
+
this.limit = limit;
|
|
7866
|
+
}
|
|
7867
|
+
};
|
|
7868
|
+
function utf8ByteLength(text) {
|
|
7869
|
+
let bytes = 0;
|
|
7870
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
7871
|
+
const code = text.charCodeAt(i);
|
|
7872
|
+
if (code < 128) {
|
|
7873
|
+
bytes += 1;
|
|
7874
|
+
} else if (code < 2048) {
|
|
7875
|
+
bytes += 2;
|
|
7876
|
+
} else if (code >= 55296 && code <= 56319 && i + 1 < text.length) {
|
|
7877
|
+
const next = text.charCodeAt(i + 1);
|
|
7878
|
+
if (next >= 56320 && next <= 57343) {
|
|
7879
|
+
bytes += 4;
|
|
7880
|
+
i += 1;
|
|
7881
|
+
} else {
|
|
7882
|
+
bytes += 3;
|
|
7883
|
+
}
|
|
7884
|
+
} else {
|
|
7885
|
+
bytes += 3;
|
|
7886
|
+
}
|
|
7887
|
+
}
|
|
7888
|
+
return bytes;
|
|
7889
|
+
}
|
|
7890
|
+
function opEnvelopeBytes(envelope2) {
|
|
7891
|
+
return utf8ByteLength(JSON.stringify(envelope2));
|
|
7892
|
+
}
|
|
7893
|
+
function assertOpEnvelopeFits(envelope2, limit = MAX_OP_BYTES2) {
|
|
7894
|
+
const bytes = opEnvelopeBytes(envelope2);
|
|
7895
|
+
if (bytes > limit) throw new OpTooLargeError2(envelope2.id, bytes, limit);
|
|
7896
|
+
}
|
|
7897
|
+
function applyOps(doc, ops, options = {}) {
|
|
7898
|
+
const draft = new Draft(doc, options.counts);
|
|
7899
|
+
for (const op of ops) applyOp(draft, op);
|
|
7900
|
+
return draft.finish();
|
|
7901
|
+
}
|
|
7902
|
+
function applyEnvelopes(doc, envelopes, options = {}) {
|
|
7903
|
+
for (const envelope2 of envelopes) assertOpEnvelopeFits(envelope2);
|
|
7904
|
+
return applyOps(
|
|
7905
|
+
doc,
|
|
7906
|
+
envelopes.map((envelope2) => envelope2.op),
|
|
7907
|
+
options
|
|
7908
|
+
);
|
|
7909
|
+
}
|
|
7910
|
+
function reduce(log, base) {
|
|
7911
|
+
const doc = base ?? emptyBoardFor(log);
|
|
7912
|
+
if (log.length === 0) return doc;
|
|
7913
|
+
let lastSeq = base === void 0 ? -1 : base.version;
|
|
7914
|
+
for (const envelope2 of log) {
|
|
7915
|
+
if (envelope2.seq === null) {
|
|
7916
|
+
throw new Error(
|
|
7917
|
+
`reduce recebeu o envelope ${envelope2.id} sem seq: s\xF3 entra no log o que j\xE1 foi confirmado`
|
|
7918
|
+
);
|
|
7919
|
+
}
|
|
7920
|
+
if (envelope2.seq <= lastSeq) {
|
|
7921
|
+
throw new Error(
|
|
7922
|
+
`reduce recebeu o log fora de ordem: seq ${envelope2.seq} depois de ${lastSeq}`
|
|
7923
|
+
);
|
|
7924
|
+
}
|
|
7925
|
+
lastSeq = envelope2.seq;
|
|
7926
|
+
}
|
|
7927
|
+
const applied = applyOps(
|
|
7928
|
+
doc,
|
|
7929
|
+
log.map((envelope2) => envelope2.op)
|
|
7930
|
+
);
|
|
7931
|
+
return { ...applied.doc, version: lastSeq };
|
|
7932
|
+
}
|
|
7933
|
+
function emptyBoardFor(log) {
|
|
7934
|
+
const first = log[0];
|
|
7935
|
+
if (first === void 0) {
|
|
7936
|
+
throw new Error("reduce sem base precisa de um log com ao menos um envelope");
|
|
7937
|
+
}
|
|
7938
|
+
return createEmptyBoard({ id: first.boardId, now: () => first.ts });
|
|
7939
|
+
}
|
|
7940
|
+
function removeNode(doc, nodeId3) {
|
|
7941
|
+
const ops = [];
|
|
7942
|
+
const edgeIds = Object.keys(doc.edges).filter((edgeId) => {
|
|
7943
|
+
const edge = doc.edges[edgeId];
|
|
7944
|
+
return edge !== void 0 && (edge.source === nodeId3 || edge.target === nodeId3);
|
|
7945
|
+
}).sort();
|
|
7946
|
+
for (const edgeId of edgeIds) ops.push({ type: "edge.remove", edgeId });
|
|
7947
|
+
const history = Object.hasOwn(doc.nodeHistory, nodeId3) ? doc.nodeHistory[nodeId3] : void 0;
|
|
7948
|
+
if (history !== void 0) {
|
|
7949
|
+
for (const resultId of [...history].reverse()) {
|
|
7950
|
+
ops.push({ type: "history.remove", nodeId: nodeId3, resultId });
|
|
7951
|
+
}
|
|
7952
|
+
}
|
|
7953
|
+
ops.push({ type: "node.remove", nodeId: nodeId3 });
|
|
7954
|
+
return { type: "batch", ops };
|
|
7955
|
+
}
|
|
7956
|
+
function batchOf2(ops) {
|
|
7957
|
+
const [first, ...rest] = ops;
|
|
7958
|
+
if (first !== void 0 && rest.length === 0) return first;
|
|
7959
|
+
return { type: "batch", ops: [...ops] };
|
|
7960
|
+
}
|
|
7961
|
+
function createOpIdGenerator(random = Math.random) {
|
|
7962
|
+
return () => {
|
|
7963
|
+
let out = "";
|
|
7964
|
+
for (let i = 0; i < 36; i += 1) {
|
|
7965
|
+
if (i === 8 || i === 13 || i === 18 || i === 23) {
|
|
7966
|
+
out += "-";
|
|
7967
|
+
continue;
|
|
7968
|
+
}
|
|
7969
|
+
if (i === 14) {
|
|
7970
|
+
out += "4";
|
|
7971
|
+
continue;
|
|
7972
|
+
}
|
|
7973
|
+
const value = Math.floor(random() * 16) & 15;
|
|
7974
|
+
out += (i === 19 ? value & 3 | 8 : value).toString(16);
|
|
7975
|
+
}
|
|
7976
|
+
return out;
|
|
7977
|
+
};
|
|
7978
|
+
}
|
|
7979
|
+
var newOpId = createOpIdGenerator();
|
|
7980
|
+
function touchedPaths(op, out = []) {
|
|
7981
|
+
switch (op.type) {
|
|
7982
|
+
case "node.add":
|
|
7983
|
+
case "node.remove":
|
|
7984
|
+
out.push(["node", op.nodeId]);
|
|
7985
|
+
break;
|
|
7986
|
+
case "node.set":
|
|
7987
|
+
out.push(["node", op.nodeId, ...segmentsOf(op.path)]);
|
|
7988
|
+
break;
|
|
7989
|
+
case "edge.add":
|
|
7990
|
+
case "edge.remove":
|
|
7991
|
+
out.push(["edge", op.edgeId]);
|
|
7992
|
+
break;
|
|
7993
|
+
case "result.set":
|
|
7994
|
+
out.push(["result", op.resultId]);
|
|
7995
|
+
break;
|
|
7996
|
+
case "history.append":
|
|
7997
|
+
case "history.remove":
|
|
7998
|
+
out.push(["history", op.nodeId]);
|
|
7999
|
+
break;
|
|
8000
|
+
case "board.set":
|
|
8001
|
+
out.push(op.key === void 0 ? ["board", op.field] : ["board", op.field, op.key]);
|
|
8002
|
+
break;
|
|
8003
|
+
case "batch":
|
|
8004
|
+
for (const inner of op.ops) touchedPaths(inner, out);
|
|
8005
|
+
break;
|
|
8006
|
+
}
|
|
8007
|
+
return out;
|
|
8008
|
+
}
|
|
8009
|
+
function segmentsOf(path) {
|
|
8010
|
+
try {
|
|
8011
|
+
return parsePath(path);
|
|
8012
|
+
} catch {
|
|
8013
|
+
return [];
|
|
8014
|
+
}
|
|
8015
|
+
}
|
|
8016
|
+
function pathsCross(a, b) {
|
|
8017
|
+
const length = Math.min(a.length, b.length);
|
|
8018
|
+
for (let i = 0; i < length; i += 1) if (a[i] !== b[i]) return false;
|
|
8019
|
+
return true;
|
|
8020
|
+
}
|
|
8021
|
+
function anyPathCrosses(a, b) {
|
|
8022
|
+
for (const left of a) for (const right of b) if (pathsCross(left, right)) return true;
|
|
8023
|
+
return false;
|
|
8024
|
+
}
|
|
8025
|
+
var HISTORY_LIMIT = 100;
|
|
8026
|
+
var HISTORY_MAX_BYTES = 8 * 1024 * 1024;
|
|
8027
|
+
var OBJECT_OVERHEAD = 16;
|
|
8028
|
+
var KEY_OVERHEAD = 8;
|
|
8029
|
+
var NUMBER_BYTES = 8;
|
|
8030
|
+
var SMALL_BYTES = 4;
|
|
8031
|
+
function estimateOpBytes(op) {
|
|
8032
|
+
let total = 0;
|
|
8033
|
+
const pending = [op];
|
|
8034
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8035
|
+
while (pending.length > 0) {
|
|
8036
|
+
const value = pending.pop();
|
|
8037
|
+
if (typeof value === "string") {
|
|
8038
|
+
total += KEY_OVERHEAD + value.length * 2;
|
|
8039
|
+
} else if (typeof value === "number") {
|
|
8040
|
+
total += NUMBER_BYTES;
|
|
8041
|
+
} else if (Array.isArray(value)) {
|
|
8042
|
+
if (seen.has(value)) continue;
|
|
8043
|
+
seen.add(value);
|
|
8044
|
+
total += OBJECT_OVERHEAD;
|
|
8045
|
+
for (const item of value) pending.push(item);
|
|
8046
|
+
} else if (typeof value === "object" && value !== null) {
|
|
8047
|
+
if (seen.has(value)) continue;
|
|
8048
|
+
seen.add(value);
|
|
8049
|
+
total += OBJECT_OVERHEAD;
|
|
8050
|
+
for (const [key, item] of Object.entries(value)) {
|
|
8051
|
+
total += KEY_OVERHEAD + key.length * 2;
|
|
8052
|
+
pending.push(item);
|
|
8053
|
+
}
|
|
8054
|
+
} else {
|
|
8055
|
+
total += SMALL_BYTES;
|
|
8056
|
+
}
|
|
8057
|
+
}
|
|
8058
|
+
return total;
|
|
8059
|
+
}
|
|
8060
|
+
var HistoryStack = class {
|
|
8061
|
+
entries = [];
|
|
8062
|
+
redoEntries = [];
|
|
8063
|
+
limit;
|
|
8064
|
+
maxBytes;
|
|
8065
|
+
clock;
|
|
8066
|
+
onHistoryTrimmed;
|
|
8067
|
+
/** Soma de `bytes` das entradas de desfazer, mantida incrementalmente. */
|
|
8068
|
+
totalBytes = 0;
|
|
8069
|
+
/** Grupo aberto por `startCapture`, ou nulo quando nenhum gesto está aberto. */
|
|
8070
|
+
openGroupId = null;
|
|
8071
|
+
/** Contador de grupos. O id é local à pilha, então não precisa de fonte injetada. */
|
|
8072
|
+
groupSeq = 0;
|
|
8073
|
+
constructor(options = {}) {
|
|
8074
|
+
this.limit = options.limit ?? HISTORY_LIMIT;
|
|
8075
|
+
this.maxBytes = options.maxBytes ?? HISTORY_MAX_BYTES;
|
|
8076
|
+
this.clock = options.clock ?? Date.now;
|
|
8077
|
+
this.onHistoryTrimmed = options.onHistoryTrimmed;
|
|
8078
|
+
}
|
|
8079
|
+
// ------------------------------------------------------------------ leitura
|
|
8080
|
+
get canUndo() {
|
|
8081
|
+
return this.entries.length > 0;
|
|
8082
|
+
}
|
|
8083
|
+
get canRedo() {
|
|
8084
|
+
return this.redoEntries.length > 0;
|
|
8085
|
+
}
|
|
8086
|
+
/** Quantas entradas dá para desfazer. É o que o painel da story 007 mostra. */
|
|
8087
|
+
get size() {
|
|
8088
|
+
return this.entries.length;
|
|
8089
|
+
}
|
|
8090
|
+
/** Quantas entradas dá para refazer. */
|
|
8091
|
+
get redoSize() {
|
|
8092
|
+
return this.redoEntries.length;
|
|
8093
|
+
}
|
|
8094
|
+
/** Memória somada das entradas de desfazer, estimada. */
|
|
8095
|
+
get bytes() {
|
|
8096
|
+
return this.totalBytes;
|
|
8097
|
+
}
|
|
8098
|
+
/** Tem gesto aberto? */
|
|
8099
|
+
get capturing() {
|
|
8100
|
+
return this.openGroupId !== null;
|
|
8101
|
+
}
|
|
8102
|
+
/** A entrada mais recente, sem tirá-la da pilha. Leitura, não consumo. */
|
|
8103
|
+
peek() {
|
|
8104
|
+
return this.entries[this.entries.length - 1];
|
|
8105
|
+
}
|
|
8106
|
+
// ------------------------------------------------------------------ captura
|
|
8107
|
+
/**
|
|
8108
|
+
* Abre um gesto: tudo que for capturado até `endCapture` vira uma entrada só.
|
|
8109
|
+
*
|
|
8110
|
+
* Chamada com um gesto já aberto, devolve o grupo aberto em vez de abrir
|
|
8111
|
+
* outro. Gesto dentro de gesto não existe na tela, e contar profundidade
|
|
8112
|
+
* pediria um `endCapture` por chamada, que é um jeito novo de esquecer de
|
|
8113
|
+
* fechar.
|
|
8114
|
+
*/
|
|
8115
|
+
startCapture() {
|
|
8116
|
+
if (this.openGroupId === null) {
|
|
8117
|
+
this.groupSeq += 1;
|
|
8118
|
+
this.openGroupId = `gesture-${this.groupSeq}`;
|
|
8119
|
+
}
|
|
8120
|
+
return this.openGroupId;
|
|
8121
|
+
}
|
|
8122
|
+
/** Fecha o gesto. A próxima captura abre entrada nova. */
|
|
8123
|
+
endCapture() {
|
|
8124
|
+
this.openGroupId = null;
|
|
8125
|
+
}
|
|
8126
|
+
/**
|
|
8127
|
+
* Guarda uma operação e a inversa dela.
|
|
8128
|
+
*
|
|
8129
|
+
* A inversa entra na FRENTE da lista da entrada: desfazer aplica `inverse` na
|
|
8130
|
+
* ordem do array, e a última coisa que aconteceu é a primeira a ser desfeita.
|
|
8131
|
+
*/
|
|
8132
|
+
capture(op, inverse, options = {}) {
|
|
8133
|
+
this.redoEntries.length = 0;
|
|
8134
|
+
const groupId = options.groupId ?? this.openGroupId;
|
|
8135
|
+
const bytes = estimateOpBytes(op) + estimateOpBytes(inverse);
|
|
8136
|
+
const last = this.peek();
|
|
8137
|
+
if (last !== void 0 && (options.amendLast === true || groupId !== null && last.groupId === groupId)) {
|
|
8138
|
+
last.ops.push(op);
|
|
8139
|
+
last.inverse.unshift(inverse);
|
|
8140
|
+
touchedPaths(op, last.paths);
|
|
8141
|
+
last.bytes += bytes;
|
|
8142
|
+
last.ts = this.clock();
|
|
8143
|
+
this.totalBytes += bytes;
|
|
8144
|
+
this.trim();
|
|
8145
|
+
return last;
|
|
8146
|
+
}
|
|
8147
|
+
const entry = {
|
|
8148
|
+
ops: [op],
|
|
8149
|
+
inverse: [inverse],
|
|
8150
|
+
groupId,
|
|
8151
|
+
ts: this.clock(),
|
|
8152
|
+
bytes,
|
|
8153
|
+
paths: touchedPaths(op),
|
|
8154
|
+
stale: false
|
|
8155
|
+
};
|
|
8156
|
+
this.entries.push(entry);
|
|
8157
|
+
this.totalBytes += bytes;
|
|
8158
|
+
this.trim();
|
|
8159
|
+
return entry;
|
|
8160
|
+
}
|
|
8161
|
+
// ------------------------------------------------------- desfazer e refazer
|
|
8162
|
+
/**
|
|
8163
|
+
* Tira a entrada mais recente e a passa para o refazer.
|
|
8164
|
+
*
|
|
8165
|
+
* A pilha não aplica nada: quem aplica é o store, com a inversa recarimbada.
|
|
8166
|
+
* Devolver a entrada em vez de aplicá-la é o que mantém o núcleo do histórico
|
|
8167
|
+
* sem opinião sobre transporte, relógio e id.
|
|
8168
|
+
*/
|
|
8169
|
+
undo() {
|
|
8170
|
+
const entry = this.entries.pop();
|
|
8171
|
+
if (entry === void 0) return void 0;
|
|
8172
|
+
this.totalBytes -= entry.bytes;
|
|
8173
|
+
if (!entry.stale) this.redoEntries.push(entry);
|
|
8174
|
+
return entry;
|
|
8175
|
+
}
|
|
8176
|
+
/**
|
|
8177
|
+
* Devolve à pilha de desfazer a entrada que `undo` acabou de tirar, quando a
|
|
8178
|
+
* inversa dela não pôde ser aplicada (recusada pelo teto de tamanho). Sem
|
|
8179
|
+
* isto, um desfazer recusado perderia o passo.
|
|
8180
|
+
*/
|
|
8181
|
+
revertUndo(entry) {
|
|
8182
|
+
if (this.redoEntries[this.redoEntries.length - 1] === entry) this.redoEntries.pop();
|
|
8183
|
+
this.entries.push(entry);
|
|
8184
|
+
this.totalBytes += entry.bytes;
|
|
8185
|
+
}
|
|
8186
|
+
/** O par de `revertUndo` para o refazer. */
|
|
8187
|
+
revertRedo(entry) {
|
|
8188
|
+
if (this.entries[this.entries.length - 1] === entry) {
|
|
8189
|
+
this.entries.pop();
|
|
8190
|
+
this.totalBytes -= entry.bytes;
|
|
8191
|
+
}
|
|
8192
|
+
this.redoEntries.push(entry);
|
|
8193
|
+
}
|
|
8194
|
+
/**
|
|
8195
|
+
* Outra pessoa tocou estes caminhos: as entradas que cruzam com eles, nas duas
|
|
8196
|
+
* pilhas, ficam marcadas como velhas. Não apaga nada aqui: quem descarta, e
|
|
8197
|
+
* avisa, é o desfazer, no momento em que a pessoa pede.
|
|
8198
|
+
*/
|
|
8199
|
+
invalidate(paths) {
|
|
8200
|
+
if (paths.length === 0) return 0;
|
|
8201
|
+
let marked = 0;
|
|
8202
|
+
for (const entry of [...this.entries, ...this.redoEntries]) {
|
|
8203
|
+
if (entry.stale || !anyPathCrosses(entry.paths, paths)) continue;
|
|
8204
|
+
entry.stale = true;
|
|
8205
|
+
marked += 1;
|
|
8206
|
+
}
|
|
8207
|
+
return marked;
|
|
8208
|
+
}
|
|
8209
|
+
/**
|
|
8210
|
+
* Tira a entrada mais recente do refazer e a devolve para o desfazer.
|
|
8211
|
+
*
|
|
8212
|
+
* Não precisa de poda: o que volta já esteve na pilha dentro do teto, e
|
|
8213
|
+
* qualquer captura no meio do caminho teria zerado o refazer.
|
|
8214
|
+
*/
|
|
8215
|
+
redo() {
|
|
8216
|
+
const entry = this.redoEntries.pop();
|
|
8217
|
+
if (entry === void 0) return void 0;
|
|
8218
|
+
if (entry.stale) return entry;
|
|
8219
|
+
this.entries.push(entry);
|
|
8220
|
+
this.totalBytes += entry.bytes;
|
|
8221
|
+
return entry;
|
|
8222
|
+
}
|
|
8223
|
+
/** Esvazia as duas pilhas. O documento não muda; a memória, sim. */
|
|
8224
|
+
clear() {
|
|
8225
|
+
this.entries.length = 0;
|
|
8226
|
+
this.redoEntries.length = 0;
|
|
8227
|
+
this.totalBytes = 0;
|
|
8228
|
+
this.openGroupId = null;
|
|
8229
|
+
}
|
|
8230
|
+
// --------------------------------------------------------------------- teto
|
|
8231
|
+
/**
|
|
8232
|
+
* Aplica os dois tetos, o de contagem e o de memória.
|
|
8233
|
+
*
|
|
8234
|
+
* A entrada mais recente nunca é descartada pelo teto de memória, mesmo
|
|
8235
|
+
* sozinha acima dele: o documento já mudou, e descartá-la deixaria o Marco sem
|
|
8236
|
+
* como desfazer o que ele acabou de fazer. Quando é esse o caso, o total fica
|
|
8237
|
+
* acima do teto e nenhum aviso é forjado, porque nada foi descartado.
|
|
8238
|
+
*/
|
|
8239
|
+
trim() {
|
|
8240
|
+
const excess = this.entries.length - this.limit;
|
|
8241
|
+
if (excess > 0) {
|
|
8242
|
+
const dropped = this.entries.splice(0, excess);
|
|
8243
|
+
for (const entry of dropped) this.totalBytes -= entry.bytes;
|
|
8244
|
+
this.report("count", dropped);
|
|
8245
|
+
}
|
|
8246
|
+
let cut = 0;
|
|
8247
|
+
let running = this.totalBytes;
|
|
8248
|
+
for (const entry of this.entries) {
|
|
8249
|
+
if (running <= this.maxBytes || cut >= this.entries.length - 1) break;
|
|
8250
|
+
running -= entry.bytes;
|
|
8251
|
+
cut += 1;
|
|
8252
|
+
}
|
|
8253
|
+
if (cut > 0) {
|
|
8254
|
+
const dropped = this.entries.splice(0, cut);
|
|
8255
|
+
this.totalBytes = running;
|
|
8256
|
+
this.report("bytes", dropped);
|
|
8257
|
+
}
|
|
8258
|
+
}
|
|
8259
|
+
report(reason, dropped) {
|
|
8260
|
+
if (this.onHistoryTrimmed === void 0) return;
|
|
8261
|
+
this.onHistoryTrimmed({ reason, dropped, bytes: this.totalBytes });
|
|
8262
|
+
}
|
|
8263
|
+
};
|
|
8264
|
+
function isLocalEnvelope(envelope2, localActorId) {
|
|
8265
|
+
return envelope2.actorId === localActorId;
|
|
8266
|
+
}
|
|
8267
|
+
function captureOf(doc, op) {
|
|
8268
|
+
if (op.type === "batch") {
|
|
8269
|
+
const parts = walkBatch(doc, op.ops, captureOf);
|
|
8270
|
+
if (parts.length === 0) return null;
|
|
8271
|
+
return {
|
|
8272
|
+
op: { type: "batch", ops: parts.map((part) => part.op) },
|
|
8273
|
+
inverse: { type: "batch", ops: parts.map((part) => part.inverse).reverse() }
|
|
8274
|
+
};
|
|
8275
|
+
}
|
|
8276
|
+
const inverse = invert(doc, op);
|
|
8277
|
+
if (inverse === null) return null;
|
|
8278
|
+
return { op, inverse };
|
|
8279
|
+
}
|
|
8280
|
+
function trackCapture(doc, envelope2, localActorId) {
|
|
8281
|
+
if (!isLocalEnvelope(envelope2, localActorId)) return null;
|
|
8282
|
+
return captureOf(doc, envelope2.op);
|
|
8283
|
+
}
|
|
8284
|
+
var EMPTY_INTERACTION = Object.freeze({
|
|
8285
|
+
drag: null,
|
|
8286
|
+
resize: null,
|
|
8287
|
+
selection: Object.freeze([])
|
|
8288
|
+
});
|
|
8289
|
+
function sameNodeIds(a, b) {
|
|
8290
|
+
if (a.length !== b.length) return false;
|
|
8291
|
+
for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
|
|
8292
|
+
return true;
|
|
8293
|
+
}
|
|
8294
|
+
function sameBox(a, b) {
|
|
8295
|
+
if (a == null || b == null) return (a ?? null) === (b ?? null);
|
|
8296
|
+
return a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;
|
|
8297
|
+
}
|
|
8298
|
+
function isOpList(value) {
|
|
8299
|
+
return Array.isArray(value);
|
|
8300
|
+
}
|
|
8301
|
+
var BoardStore = class {
|
|
8302
|
+
current;
|
|
8303
|
+
interaction = EMPTY_INTERACTION;
|
|
8304
|
+
options;
|
|
8305
|
+
stack;
|
|
8306
|
+
clock;
|
|
8307
|
+
newId;
|
|
8308
|
+
listeners = /* @__PURE__ */ new Set();
|
|
8309
|
+
envelopeListeners = /* @__PURE__ */ new Set();
|
|
8310
|
+
last = null;
|
|
8311
|
+
lastFromSync = false;
|
|
8312
|
+
constructor(doc, options) {
|
|
8313
|
+
this.current = doc;
|
|
8314
|
+
this.options = options;
|
|
8315
|
+
this.clock = options.clock ?? Date.now;
|
|
8316
|
+
this.newId = options.newId ?? newOpId;
|
|
8317
|
+
this.stack = new HistoryStack({
|
|
8318
|
+
limit: options.history?.limit,
|
|
8319
|
+
maxBytes: options.history?.maxBytes,
|
|
8320
|
+
clock: this.clock,
|
|
8321
|
+
onHistoryTrimmed: options.onHistoryTrimmed
|
|
8322
|
+
});
|
|
8323
|
+
}
|
|
8324
|
+
// ------------------------------------------------------------------ leitura
|
|
8325
|
+
/**
|
|
8326
|
+
* O documento de agora. Estável por referência entre mudanças.
|
|
8327
|
+
*
|
|
8328
|
+
* Propriedade de seta, e não método, porque ela é passada direto para
|
|
8329
|
+
* `useSyncExternalStore`: assim não precisa de `bind`, e o React não reassina
|
|
8330
|
+
* a cada render por receber uma função nova. `subscribe` e `getInteraction`
|
|
8331
|
+
* seguem a mesma forma, e as três mudam juntas ou nenhuma: metade convertida
|
|
8332
|
+
* faz o React reassinar sem erro visível.
|
|
8333
|
+
*/
|
|
8334
|
+
getDoc = () => this.current;
|
|
8335
|
+
/** O estado efêmero de agora. Mesma regra de estabilidade do documento. */
|
|
8336
|
+
getInteraction = () => this.interaction;
|
|
8337
|
+
/** Assina mudanças. Devolve a função que cancela a assinatura. */
|
|
8338
|
+
subscribe = (listener) => {
|
|
8339
|
+
this.listeners.add(listener);
|
|
8340
|
+
return () => {
|
|
8341
|
+
this.listeners.delete(listener);
|
|
8342
|
+
};
|
|
8343
|
+
};
|
|
8344
|
+
/** A pilha, para quem mostra o estado dela na tela (story 007). */
|
|
8345
|
+
get history() {
|
|
8346
|
+
return this.stack;
|
|
8347
|
+
}
|
|
8348
|
+
get canUndo() {
|
|
8349
|
+
return this.stack.canUndo;
|
|
8350
|
+
}
|
|
8351
|
+
get canRedo() {
|
|
8352
|
+
return this.stack.canRedo;
|
|
8353
|
+
}
|
|
8354
|
+
/**
|
|
8355
|
+
* O último envelope aplicado, nosso ou de fora. É por ele que quem assina
|
|
8356
|
+
* sabe se a mudança que acabou de acordá-lo nasceu nesta aba (`clientId`
|
|
8357
|
+
* igual ao da sessão) e, portanto, se deve derivar operação a partir dela
|
|
8358
|
+
* (SV2b). Nulo antes do primeiro despacho.
|
|
8359
|
+
*/
|
|
8360
|
+
get lastEnvelope() {
|
|
8361
|
+
return this.last;
|
|
8362
|
+
}
|
|
8363
|
+
/**
|
|
8364
|
+
* A última troca do documento veio de `replaceDoc` (a sincronização trocou a
|
|
8365
|
+
* foto: remotas mais as pendentes reaplicadas), e não de um despacho. Para
|
|
8366
|
+
* quem deriva operação, isso conta como mudança de fora: as pendentes desta
|
|
8367
|
+
* aba já derivaram quando foram despachadas pela primeira vez.
|
|
8368
|
+
*/
|
|
8369
|
+
get lastChangeFromSync() {
|
|
8370
|
+
return this.lastFromSync;
|
|
8371
|
+
}
|
|
8372
|
+
// ------------------------------------------------------------------ gestos
|
|
8373
|
+
/** Abre um gesto: o que for despachado até `endCapture` vira uma entrada só. */
|
|
8374
|
+
startCapture() {
|
|
8375
|
+
return this.stack.startCapture();
|
|
8376
|
+
}
|
|
8377
|
+
/** Fecha o gesto. */
|
|
8378
|
+
endCapture() {
|
|
8379
|
+
this.stack.endCapture();
|
|
8380
|
+
}
|
|
8381
|
+
// ---------------------------------------------------------------- interação
|
|
8382
|
+
/**
|
|
8383
|
+
* Troca a seleção. Não é documento, não é op, não entra na pilha.
|
|
8384
|
+
*
|
|
8385
|
+
* Seleção igual sai de graça: sem troca de referência ninguém é acordado.
|
|
8386
|
+
*/
|
|
8387
|
+
select(nodeIds) {
|
|
8388
|
+
if (sameNodeIds(this.interaction.selection, nodeIds)) return;
|
|
8389
|
+
this.interaction = { ...this.interaction, selection: [...nodeIds] };
|
|
8390
|
+
this.notify();
|
|
8391
|
+
}
|
|
8392
|
+
/**
|
|
8393
|
+
* Abre um gesto de arraste, capturando a posição de partida de cada nó.
|
|
8394
|
+
*
|
|
8395
|
+
* Id que não existe no documento é ignorado, e um gesto sem nenhum nó válido
|
|
8396
|
+
* não abre nem notifica. Gesto já aberto também não reabre: o primeiro frame
|
|
8397
|
+
* é quem define a base da op do soltar, e recapturar a base no meio do
|
|
8398
|
+
* caminho mediria o gesto pela metade.
|
|
8399
|
+
*/
|
|
8400
|
+
beginDrag(nodeIds) {
|
|
8401
|
+
if (this.interaction.drag !== null) return;
|
|
8402
|
+
const origin = {};
|
|
8403
|
+
const ids = [];
|
|
8404
|
+
for (const id of nodeIds) {
|
|
8405
|
+
const node = this.current.nodes[id];
|
|
8406
|
+
if (node === void 0) continue;
|
|
8407
|
+
origin[id] = { x: node.position.x, y: node.position.y };
|
|
8408
|
+
ids.push(id);
|
|
8409
|
+
}
|
|
8410
|
+
if (ids.length === 0) return;
|
|
8411
|
+
this.interaction = { ...this.interaction, drag: { nodeIds: ids, origin, live: origin } };
|
|
8412
|
+
this.notify();
|
|
8413
|
+
}
|
|
8414
|
+
/**
|
|
8415
|
+
* Move o gesto vivo. Sem op, sem histórico, sem tocar no documento.
|
|
8416
|
+
*
|
|
8417
|
+
* Posição repetida sai de graça, e é isso que impede um `pointermove` que não
|
|
8418
|
+
* andou de custar um render. Id fora do gesto é ignorado.
|
|
8419
|
+
*/
|
|
8420
|
+
moveDrag(positions) {
|
|
8421
|
+
const drag = this.interaction.drag;
|
|
8422
|
+
if (drag === null) return;
|
|
8423
|
+
let changed = false;
|
|
8424
|
+
const live = { ...drag.live };
|
|
8425
|
+
for (const id of drag.nodeIds) {
|
|
8426
|
+
const next = positions[id];
|
|
8427
|
+
if (next === void 0) continue;
|
|
8428
|
+
const current = live[id];
|
|
8429
|
+
if (current !== void 0 && current.x === next.x && current.y === next.y) continue;
|
|
8430
|
+
live[id] = { x: next.x, y: next.y };
|
|
8431
|
+
changed = true;
|
|
8432
|
+
}
|
|
8433
|
+
if (!changed) return;
|
|
8434
|
+
this.interaction = { ...this.interaction, drag: { ...drag, live } };
|
|
8435
|
+
this.notify();
|
|
8436
|
+
}
|
|
8437
|
+
/**
|
|
8438
|
+
* Fecha o gesto: uma op de topo, uma entrada de histórico, uma notificação.
|
|
8439
|
+
*
|
|
8440
|
+
* **A troca é atômica.** A camada efêmera é limpa ANTES de o despacho
|
|
8441
|
+
* notificar, então a única notificação que sai já carrega o documento com a
|
|
8442
|
+
* posição nova e o gesto encerrado. Nenhum assinante consegue observar o par
|
|
8443
|
+
* (posição velha, arraste já encerrado), que é o piscar de um frame que o
|
|
8444
|
+
* desenho de dois donos de estado produz.
|
|
8445
|
+
*
|
|
8446
|
+
* `positions` é a posição final vinda de quem viu o gesto acontecer (o
|
|
8447
|
+
* `change.position` da lib), e a camada efêmera entra só como reserva: uma
|
|
8448
|
+
* fonte de verdade por valor, com a segunda cobrindo o dia em que a primeira
|
|
8449
|
+
* faltar. Nó que voltou para onde começou não emite nada, e gesto em que
|
|
8450
|
+
* ninguém andou não emite op nenhuma.
|
|
8451
|
+
*/
|
|
8452
|
+
endDrag(positions = {}) {
|
|
8453
|
+
const drag = this.interaction.drag;
|
|
8454
|
+
if (drag === null) return null;
|
|
8455
|
+
const ops = [];
|
|
8456
|
+
for (const id of drag.nodeIds) {
|
|
8457
|
+
const from = drag.origin[id];
|
|
8458
|
+
const to = positions[id] ?? drag.live[id];
|
|
8459
|
+
if (from === void 0 || to === void 0) continue;
|
|
8460
|
+
if (from.x === to.x && from.y === to.y) continue;
|
|
8461
|
+
ops.push({
|
|
8462
|
+
type: "node.set",
|
|
8463
|
+
nodeId: id,
|
|
8464
|
+
path: "position",
|
|
8465
|
+
value: propValue({ x: to.x, y: to.y })
|
|
8466
|
+
});
|
|
8467
|
+
}
|
|
8468
|
+
if (ops.length === 0) {
|
|
8469
|
+
this.cancelDrag();
|
|
8470
|
+
return null;
|
|
8471
|
+
}
|
|
8472
|
+
this.interaction = { ...this.interaction, drag: null };
|
|
8473
|
+
const result = this.dispatch(ops, { silent: true });
|
|
8474
|
+
this.notify();
|
|
8475
|
+
return result;
|
|
8476
|
+
}
|
|
8477
|
+
/**
|
|
8478
|
+
* Saída do gesto interrompido: `Escape`, `pointercancel` e a aba perdendo o
|
|
8479
|
+
* foco. Zero op, zero entrada de histórico, e o nó volta para a posição do
|
|
8480
|
+
* documento porque é ela que sempre esteve lá.
|
|
8481
|
+
*/
|
|
8482
|
+
cancelDrag() {
|
|
8483
|
+
if (this.interaction.drag === null) return;
|
|
8484
|
+
this.interaction = { ...this.interaction, drag: null };
|
|
8485
|
+
this.notify();
|
|
8486
|
+
}
|
|
8487
|
+
/**
|
|
8488
|
+
* Abre um gesto de redimensionar (SV2b). Mesmo desenho do arraste: nada vira
|
|
8489
|
+
* operação até o soltar. Nó ausente não abre.
|
|
8490
|
+
*/
|
|
8491
|
+
beginResize(nodeId3) {
|
|
8492
|
+
const node = this.current.nodes[nodeId3];
|
|
8493
|
+
if (node === void 0) return;
|
|
8494
|
+
const origin = { ...node.position, ...node.size };
|
|
8495
|
+
this.interaction = { ...this.interaction, resize: { nodeId: nodeId3, origin, live: origin } };
|
|
8496
|
+
this.notify();
|
|
8497
|
+
}
|
|
8498
|
+
/** A caixa do frame atual. Sem op, sem histórico. Caixa igual sai de graça. */
|
|
8499
|
+
moveResize(box) {
|
|
8500
|
+
const resize = this.interaction.resize;
|
|
8501
|
+
if (resize == null || sameBox(resize.live, box)) return;
|
|
8502
|
+
const live = { x: box.x, y: box.y, w: box.w, h: box.h };
|
|
8503
|
+
this.interaction = { ...this.interaction, resize: { ...resize, live } };
|
|
8504
|
+
this.notify();
|
|
8505
|
+
}
|
|
8506
|
+
/**
|
|
8507
|
+
* Fecha o gesto: uma op, uma entrada de histórico, uma notificação. A troca
|
|
8508
|
+
* é atômica pela mesma razão de `endDrag`. Caixa final igual à de partida
|
|
8509
|
+
* não emite nada.
|
|
8510
|
+
*/
|
|
8511
|
+
endResize(box) {
|
|
8512
|
+
const resize = this.interaction.resize;
|
|
8513
|
+
if (resize == null) return null;
|
|
8514
|
+
const to = box ?? resize.live;
|
|
8515
|
+
const from = resize.origin;
|
|
8516
|
+
const ops = [];
|
|
8517
|
+
if (from.w !== to.w || from.h !== to.h) {
|
|
8518
|
+
ops.push({
|
|
8519
|
+
type: "node.set",
|
|
8520
|
+
nodeId: resize.nodeId,
|
|
8521
|
+
path: "size",
|
|
8522
|
+
value: propValue({ w: to.w, h: to.h })
|
|
8523
|
+
});
|
|
8524
|
+
}
|
|
8525
|
+
if (from.x !== to.x || from.y !== to.y) {
|
|
8526
|
+
ops.push({
|
|
8527
|
+
type: "node.set",
|
|
8528
|
+
nodeId: resize.nodeId,
|
|
8529
|
+
path: "position",
|
|
8530
|
+
value: propValue({ x: to.x, y: to.y })
|
|
8531
|
+
});
|
|
8532
|
+
}
|
|
8533
|
+
this.interaction = { ...this.interaction, resize: null };
|
|
8534
|
+
if (ops.length === 0 || this.current.nodes[resize.nodeId] === void 0) {
|
|
8535
|
+
this.notify();
|
|
8536
|
+
return null;
|
|
8537
|
+
}
|
|
8538
|
+
const result = this.dispatch(ops, { silent: true });
|
|
8539
|
+
this.notify();
|
|
8540
|
+
return result;
|
|
8541
|
+
}
|
|
8542
|
+
/** Gesto interrompido: zero op, e o nó volta ao tamanho do documento. */
|
|
8543
|
+
cancelResize() {
|
|
8544
|
+
if (this.interaction.resize == null) return;
|
|
8545
|
+
this.interaction = { ...this.interaction, resize: null };
|
|
8546
|
+
this.notify();
|
|
8547
|
+
}
|
|
8548
|
+
// ----------------------------------------------------------------- despacho
|
|
8549
|
+
/**
|
|
8550
|
+
* Despacha operação nossa: carimba o envelope com a sessão local e aplica.
|
|
8551
|
+
*
|
|
8552
|
+
* Lista com mais de uma operação vira um `batch`, porque um envelope carrega
|
|
8553
|
+
* UMA operação de topo, e um `batch` é uma operação, logo um `seq`
|
|
8554
|
+
* (`dev/PLANO-FASE-0.md` §3).
|
|
8555
|
+
*/
|
|
8556
|
+
dispatch(ops, options = {}) {
|
|
8557
|
+
const op = isOpList(ops) ? batchOf2(ops) : ops;
|
|
8558
|
+
return this.dispatchEnvelope(this.stamp(op), options);
|
|
8559
|
+
}
|
|
8560
|
+
/**
|
|
8561
|
+
* Despacha um envelope já carimbado.
|
|
8562
|
+
*
|
|
8563
|
+
* É a porta por onde entra o que NÃO nasceu nesta aba: o motor de execução da
|
|
8564
|
+
* fase 4 e, um dia, o `pull` da colaboração. O filtro de captura compara o
|
|
8565
|
+
* `actorId` do envelope com o da sessão, e é por isso que a regra do autor
|
|
8566
|
+
* mora no envelope em vez de virar um parâmetro do despacho.
|
|
8567
|
+
*/
|
|
8568
|
+
dispatchEnvelope(envelope2, options = {}) {
|
|
8569
|
+
const before = this.current;
|
|
8570
|
+
const ours = envelope2.clientId === this.options.session.clientId;
|
|
8571
|
+
const split = ours && options.unbounded !== true ? this.wireEnvelopes(envelope2) : [envelope2];
|
|
8572
|
+
const envelopes = split === null && this.envelopeListeners.size > 0 ? [envelope2] : split;
|
|
8573
|
+
if (envelopes === null) {
|
|
8574
|
+
const rejected = {
|
|
8575
|
+
code: "op-too-large",
|
|
8576
|
+
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.",
|
|
8577
|
+
boardId: this.current.id,
|
|
8578
|
+
opId: envelope2.id
|
|
8579
|
+
};
|
|
8580
|
+
this.options.onError(rejected);
|
|
8581
|
+
return { envelope: envelope2, doc: before, changedNodeIds: [], entry: null, envelopes: [], rejected };
|
|
8582
|
+
}
|
|
8583
|
+
const capture = options.tracked === false ? null : trackCapture(before, envelope2, this.options.session.actorId);
|
|
8584
|
+
const applied = applyOps(before, [envelope2.op]);
|
|
8585
|
+
const entry = capture === null ? null : this.stack.capture(capture.op, capture.inverse, {
|
|
8586
|
+
groupId: options.groupId,
|
|
8587
|
+
amendLast: options.amendLast
|
|
8588
|
+
});
|
|
8589
|
+
if (envelope2.actorId !== null && envelope2.actorId !== this.options.session.actorId) {
|
|
8590
|
+
this.stack.invalidate(touchedPaths(envelope2.op));
|
|
8591
|
+
}
|
|
8592
|
+
this.current = applied.doc;
|
|
8593
|
+
this.last = envelope2;
|
|
8594
|
+
this.lastFromSync = false;
|
|
8595
|
+
for (const listener of this.envelopeListeners) for (const wire of envelopes) listener(wire);
|
|
8596
|
+
if (options.silent !== true && applied.doc !== before) this.notify();
|
|
8597
|
+
return {
|
|
8598
|
+
envelope: envelope2,
|
|
8599
|
+
doc: applied.doc,
|
|
8600
|
+
changedNodeIds: applied.changedNodeIds,
|
|
8601
|
+
entry,
|
|
8602
|
+
envelopes,
|
|
8603
|
+
rejected: null
|
|
8604
|
+
};
|
|
8605
|
+
}
|
|
8606
|
+
// ----------------------------------------------------------- sincronização
|
|
8607
|
+
/**
|
|
8608
|
+
* Assina os envelopes que ESTA aba aplicou pelo despacho (edição, desfazer,
|
|
8609
|
+
* refazer, soltar de arraste). É por aqui que o cliente de sincronização
|
|
8610
|
+
* (`transport/`) monta a fila de pendentes. Avisado só depois de o apply
|
|
8611
|
+
* passar: envelope que lançou nunca vira pendente.
|
|
8612
|
+
*
|
|
8613
|
+
* Sem assinante, o despacho se comporta exatamente como antes.
|
|
8614
|
+
*/
|
|
8615
|
+
subscribeEnvelopes = (listener) => {
|
|
8616
|
+
this.envelopeListeners.add(listener);
|
|
8617
|
+
return () => {
|
|
8618
|
+
this.envelopeListeners.delete(listener);
|
|
8619
|
+
};
|
|
8620
|
+
};
|
|
8621
|
+
/**
|
|
8622
|
+
* Troca o documento inteiro pelo que a sincronização calculou (foto confirmada
|
|
8623
|
+
* + remotas + pendentes reaplicadas). Não entra no histórico, não avisa
|
|
8624
|
+
* `subscribeEnvelopes` (senão o remoto voltaria como pendente) e só notifica
|
|
8625
|
+
* quando a referência muda.
|
|
8626
|
+
*/
|
|
8627
|
+
replaceDoc(doc) {
|
|
8628
|
+
if (doc === this.current) return;
|
|
8629
|
+
this.current = doc;
|
|
8630
|
+
this.lastFromSync = true;
|
|
8631
|
+
this.notify();
|
|
8632
|
+
}
|
|
8633
|
+
/**
|
|
8634
|
+
* O envelope como vai ao fio, em pedaços que cabem no teto.
|
|
8635
|
+
*
|
|
8636
|
+
* Cabe inteiro: sai como está, e é o caso de quase todo despacho. Não cabe e
|
|
8637
|
+
* é `batch`: os membros (com `batch` aninhado aberto, a ordem preservada) são
|
|
8638
|
+
* empacotados em envelopes consecutivos. Uma folha sozinha acima do teto não
|
|
8639
|
+
* tem como ir: devolve nulo, e o despacho é recusado inteiro.
|
|
8640
|
+
*/
|
|
8641
|
+
wireEnvelopes(envelope2) {
|
|
8642
|
+
if (opEnvelopeBytes(envelope2) <= MAX_OP_BYTES2) return [envelope2];
|
|
8643
|
+
if (envelope2.op.type !== "batch") return null;
|
|
8644
|
+
const leaves = [];
|
|
8645
|
+
const open3 = (op) => {
|
|
8646
|
+
if (op.type === "batch") for (const inner of op.ops) open3(inner);
|
|
8647
|
+
else leaves.push(op);
|
|
8648
|
+
};
|
|
8649
|
+
open3(envelope2.op);
|
|
8650
|
+
const slack = 64;
|
|
8651
|
+
const overhead = opEnvelopeBytes({ ...envelope2, op: { type: "batch", ops: [] } }) + slack;
|
|
8652
|
+
const chunks = [];
|
|
8653
|
+
let chunk = [];
|
|
8654
|
+
let bytes = overhead;
|
|
8655
|
+
for (const leaf of leaves) {
|
|
8656
|
+
const size = utf8ByteLength(JSON.stringify(leaf));
|
|
8657
|
+
if (overhead + size > MAX_OP_BYTES2) return null;
|
|
8658
|
+
const added = chunk.length === 0 ? size : size + 1;
|
|
8659
|
+
if (chunk.length > 0 && bytes + added > MAX_OP_BYTES2) {
|
|
8660
|
+
chunks.push(chunk);
|
|
8661
|
+
chunk = [leaf];
|
|
8662
|
+
bytes = overhead + size;
|
|
8663
|
+
} else {
|
|
8664
|
+
chunk.push(leaf);
|
|
8665
|
+
bytes += added;
|
|
8666
|
+
}
|
|
8667
|
+
}
|
|
8668
|
+
if (chunk.length > 0) chunks.push(chunk);
|
|
8669
|
+
return chunks.map((ops, index) => ({
|
|
8670
|
+
...envelope2,
|
|
8671
|
+
// O primeiro pedaço herda o id: é por ele que quem despachou reconhece o eco.
|
|
8672
|
+
id: index === 0 ? envelope2.id : this.newId(),
|
|
8673
|
+
op: ops.length === 1 ? ops[0] : { type: "batch", ops }
|
|
8674
|
+
}));
|
|
8675
|
+
}
|
|
8676
|
+
// -------------------------------------------------------- desfazer e refazer
|
|
8677
|
+
/**
|
|
8678
|
+
* Desfaz o último gesto.
|
|
8679
|
+
*
|
|
8680
|
+
* Cada inversa sai recarimbada com id novo e o `clientId` local, embrulhada em
|
|
8681
|
+
* `batch` quando a entrada juntou mais de um despacho, e despachada com
|
|
8682
|
+
* `{tracked:false}`. A entrada vai para a pilha de refazer inteira, do jeito
|
|
8683
|
+
* que estava.
|
|
8684
|
+
*/
|
|
8685
|
+
undo() {
|
|
8686
|
+
const entry = this.stack.undo();
|
|
8687
|
+
if (entry === void 0) return { applied: false, changedNodeIds: [], envelope: null };
|
|
8688
|
+
if (entry.stale) return this.discard("desfazer");
|
|
8689
|
+
const result = this.replay(entry.inverse);
|
|
8690
|
+
if (!result.applied) this.stack.revertUndo(entry);
|
|
8691
|
+
return result;
|
|
8692
|
+
}
|
|
8693
|
+
/** Refaz o gesto desfeito mais recente, pelas operações originais e na ordem delas. */
|
|
8694
|
+
redo() {
|
|
8695
|
+
const entry = this.stack.redo();
|
|
8696
|
+
if (entry === void 0) return { applied: false, changedNodeIds: [], envelope: null };
|
|
8697
|
+
if (entry.stale) return this.discard("refazer");
|
|
8698
|
+
const result = this.replay(entry.ops);
|
|
8699
|
+
if (!result.applied) this.stack.revertRedo(entry);
|
|
8700
|
+
return result;
|
|
8701
|
+
}
|
|
8702
|
+
// ------------------------------------------------------------------ privados
|
|
8703
|
+
/** O passo velho sai da pilha sem tocar no documento, com aviso. */
|
|
8704
|
+
discard(verb) {
|
|
8705
|
+
this.options.onError({
|
|
8706
|
+
code: "undo-conflict",
|
|
8707
|
+
message: `Outra pessoa mexeu no mesmo lugar depois. Esse passo de ${verb} foi descartado para n\xE3o apagar o trabalho dela.`,
|
|
8708
|
+
boardId: this.current.id
|
|
8709
|
+
});
|
|
8710
|
+
this.notify();
|
|
8711
|
+
return { applied: false, changedNodeIds: [], envelope: null, discarded: true };
|
|
8712
|
+
}
|
|
8713
|
+
/** Despacha uma lista guardada na pilha, sem deixá-la voltar para a pilha. */
|
|
8714
|
+
replay(ops) {
|
|
8715
|
+
const result = this.dispatch(batchOf2(ops), { tracked: false });
|
|
8716
|
+
if (result.rejected !== null) return { applied: false, changedNodeIds: [], envelope: null };
|
|
8717
|
+
return { applied: true, changedNodeIds: result.changedNodeIds, envelope: result.envelope };
|
|
8718
|
+
}
|
|
8719
|
+
/** O envelope de uma operação nossa. `seq` nasce nulo: quem confirma é o commit. */
|
|
8720
|
+
stamp(op) {
|
|
8721
|
+
return {
|
|
8722
|
+
id: this.newId(),
|
|
8723
|
+
boardId: this.current.id,
|
|
8724
|
+
clientId: this.options.session.clientId,
|
|
8725
|
+
actorId: this.options.session.actorId,
|
|
8726
|
+
seq: null,
|
|
8727
|
+
ts: this.clock(),
|
|
8728
|
+
op
|
|
8729
|
+
};
|
|
8730
|
+
}
|
|
8731
|
+
notify() {
|
|
8732
|
+
for (const listener of this.listeners) listener();
|
|
8733
|
+
}
|
|
8734
|
+
};
|
|
8735
|
+
function resolveGap(gap) {
|
|
8736
|
+
return typeof gap === "number" ? { x: gap, y: gap } : { x: gap.x, y: gap.y };
|
|
8737
|
+
}
|
|
8738
|
+
function rectOf2(node) {
|
|
8739
|
+
return { x: node.position.x, y: node.position.y, w: node.size.w, h: node.size.h };
|
|
8740
|
+
}
|
|
8741
|
+
function rectsCollide(a, b, gap) {
|
|
8742
|
+
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;
|
|
8743
|
+
}
|
|
8744
|
+
function boundsOf(rects) {
|
|
8745
|
+
let minX = Number.POSITIVE_INFINITY;
|
|
8746
|
+
let minY = Number.POSITIVE_INFINITY;
|
|
8747
|
+
let maxX = Number.NEGATIVE_INFINITY;
|
|
8748
|
+
let maxY = Number.NEGATIVE_INFINITY;
|
|
8749
|
+
for (const rect of rects) {
|
|
8750
|
+
minX = Math.min(minX, rect.x);
|
|
8751
|
+
minY = Math.min(minY, rect.y);
|
|
8752
|
+
maxX = Math.max(maxX, rect.x + rect.w);
|
|
8753
|
+
maxY = Math.max(maxY, rect.y + rect.h);
|
|
8754
|
+
}
|
|
8755
|
+
if (rects.length === 0) return { x: 0, y: 0, w: 0, h: 0 };
|
|
8756
|
+
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
|
|
8757
|
+
}
|
|
8758
|
+
function compareText(a, b) {
|
|
8759
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
8760
|
+
}
|
|
8761
|
+
function byScreenOrder(a, b) {
|
|
8762
|
+
return a.position.y - b.position.y || a.position.x - b.position.x || compareText(a.id, b.id);
|
|
8763
|
+
}
|
|
8764
|
+
function obstaclesOf(doc, ignore = []) {
|
|
8765
|
+
const skipped = new Set(ignore);
|
|
8766
|
+
return Object.values(doc.nodes).filter((node) => node.parentId === null && !skipped.has(node.id)).sort(byScreenOrder).map(rectOf2);
|
|
8767
|
+
}
|
|
8768
|
+
var DEFAULT_MAX_PER_COLUMN = 8;
|
|
8769
|
+
function positiveInt(value, fallback) {
|
|
8770
|
+
if (value === void 0 || !Number.isFinite(value)) return fallback;
|
|
8771
|
+
return Math.max(1, Math.floor(value));
|
|
8772
|
+
}
|
|
8773
|
+
function fanOutPositions(input) {
|
|
8774
|
+
const count = Number.isFinite(input.count) ? Math.floor(input.count) : 0;
|
|
8775
|
+
if (count < 1) return [];
|
|
8776
|
+
const gap = resolveGap(input.gap);
|
|
8777
|
+
const maxPerColumn = positiveInt(input.maxPerColumn, DEFAULT_MAX_PER_COLUMN);
|
|
8778
|
+
const columns = Math.min(count, positiveInt(input.columns, Math.ceil(count / maxPerColumn)));
|
|
8779
|
+
const rows = Math.ceil(count / columns);
|
|
8780
|
+
const { position, size } = input.source;
|
|
8781
|
+
const blockHeight = rows * input.nodeSize.h + (rows - 1) * gap.y;
|
|
8782
|
+
const left = Math.round(position.x + size.w + gap.x);
|
|
8783
|
+
const top = Math.round(position.y + size.h / 2 - blockHeight / 2);
|
|
8784
|
+
const positions = [];
|
|
8785
|
+
for (let index = 0; index < count; index += 1) {
|
|
8786
|
+
const column = index % columns;
|
|
8787
|
+
const row = Math.floor(index / columns);
|
|
8788
|
+
positions.push({
|
|
8789
|
+
x: left + column * (input.nodeSize.w + gap.x),
|
|
8790
|
+
y: top + row * (input.nodeSize.h + gap.y)
|
|
8791
|
+
});
|
|
8792
|
+
}
|
|
8793
|
+
return positions;
|
|
8794
|
+
}
|
|
8795
|
+
var DEFAULT_PLACEMENT_GAP = 40;
|
|
8796
|
+
function uniqueAscending(values) {
|
|
8797
|
+
return [...new Set(values)].sort((a, b) => a - b);
|
|
8798
|
+
}
|
|
8799
|
+
function blockIsFree(rects, bounds, dx, dy, obstacles, gap) {
|
|
8800
|
+
const movedBounds = { ...bounds, x: bounds.x + dx, y: bounds.y + dy };
|
|
8801
|
+
for (const obstacle of obstacles) {
|
|
8802
|
+
if (!rectsCollide(movedBounds, obstacle, gap)) continue;
|
|
8803
|
+
for (const rect of rects) {
|
|
8804
|
+
if (rectsCollide({ ...rect, x: rect.x + dx, y: rect.y + dy }, obstacle, gap)) return false;
|
|
8805
|
+
}
|
|
8806
|
+
}
|
|
8807
|
+
return true;
|
|
8808
|
+
}
|
|
8809
|
+
function placeWithoutOverlap(doc, rects, options) {
|
|
8810
|
+
if (rects.length === 0) return [];
|
|
8811
|
+
const gap = resolveGap(options.gap);
|
|
8812
|
+
const original = boundsOf(rects);
|
|
8813
|
+
const baseDx = options.near === void 0 ? 0 : options.near.x - original.x;
|
|
8814
|
+
const baseDy = options.near === void 0 ? 0 : options.near.y - original.y;
|
|
8815
|
+
const block = rects.map((rect) => ({ ...rect, x: rect.x + baseDx, y: rect.y + baseDy }));
|
|
8816
|
+
const bounds = boundsOf(block);
|
|
8817
|
+
const obstacles = obstaclesOf(doc, options.ignore);
|
|
8818
|
+
const maxDown = options.maxDown ?? 3 * (bounds.h + gap.y);
|
|
8819
|
+
const rightSteps = uniqueAscending([
|
|
8820
|
+
0,
|
|
8821
|
+
...obstacles.map((o) => o.x + o.w + gap.x - bounds.x).filter((dx) => dx > 0)
|
|
8822
|
+
]);
|
|
8823
|
+
const downSteps = uniqueAscending([
|
|
8824
|
+
0,
|
|
8825
|
+
...obstacles.map((o) => o.y + o.h + gap.y - bounds.y).filter((dy) => dy > 0 && dy <= maxDown)
|
|
8826
|
+
]);
|
|
8827
|
+
for (const dx of rightSteps) {
|
|
8828
|
+
for (const dy of downSteps) {
|
|
8829
|
+
if (blockIsFree(block, bounds, dx, dy, obstacles, gap)) {
|
|
8830
|
+
return block.map((rect) => ({ ...rect, x: rect.x + dx, y: rect.y + dy }));
|
|
8831
|
+
}
|
|
8832
|
+
}
|
|
8833
|
+
}
|
|
8834
|
+
return block;
|
|
8835
|
+
}
|
|
8836
|
+
function byDistance(a, b) {
|
|
8837
|
+
return a.distance - b.distance || b.y - a.y || b.x - a.x;
|
|
8838
|
+
}
|
|
8839
|
+
function findFreeSpot(doc, size, near, options = {}) {
|
|
8840
|
+
const gap = resolveGap(options.gap ?? DEFAULT_PLACEMENT_GAP);
|
|
8841
|
+
const obstacles = obstaclesOf(doc, options.ignore);
|
|
8842
|
+
const xs = uniqueAscending([
|
|
8843
|
+
near.x,
|
|
8844
|
+
...obstacles.flatMap((o) => [o.x + o.w + gap.x, o.x - gap.x - size.w])
|
|
8845
|
+
]);
|
|
8846
|
+
const candidates = xs.map((x) => {
|
|
8847
|
+
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);
|
|
8848
|
+
let y = near.y;
|
|
8849
|
+
let wall;
|
|
8850
|
+
for (const interval of blocked) {
|
|
8851
|
+
if (wall !== void 0 && interval.from < wall.to) {
|
|
8852
|
+
wall.to = Math.max(wall.to, interval.to);
|
|
8853
|
+
} else if (wall !== void 0 && wall.from < near.y && near.y < wall.to) {
|
|
8854
|
+
break;
|
|
8855
|
+
} else {
|
|
8856
|
+
wall = { ...interval };
|
|
8857
|
+
}
|
|
8858
|
+
}
|
|
8859
|
+
if (wall !== void 0 && wall.from < near.y && near.y < wall.to) {
|
|
8860
|
+
y = wall.to - near.y <= near.y - wall.from ? wall.to : wall.from;
|
|
8861
|
+
}
|
|
8862
|
+
return { x, y, distance: Math.hypot(x - near.x, y - near.y) };
|
|
8863
|
+
});
|
|
8864
|
+
const [best] = candidates.sort(byDistance);
|
|
8865
|
+
if (best === void 0) return { x: near.x, y: near.y };
|
|
8866
|
+
return { x: best.x, y: best.y };
|
|
8867
|
+
}
|
|
8868
|
+
function topLevelOf(doc, nodeId3) {
|
|
8869
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8870
|
+
let current = nodeId3;
|
|
8871
|
+
for (; ; ) {
|
|
8872
|
+
if (seen.has(current) || !Object.hasOwn(doc.nodes, current)) return void 0;
|
|
8873
|
+
seen.add(current);
|
|
8874
|
+
const node = doc.nodes[current];
|
|
8875
|
+
if (node === void 0) return void 0;
|
|
8876
|
+
if (node.parentId === null) return current;
|
|
8877
|
+
current = node.parentId;
|
|
8878
|
+
}
|
|
8879
|
+
}
|
|
8880
|
+
function pushTo(map, key, value) {
|
|
8881
|
+
const list = map.get(key);
|
|
8882
|
+
if (list === void 0) map.set(key, [value]);
|
|
8883
|
+
else if (!list.includes(value)) list.push(value);
|
|
8884
|
+
}
|
|
8885
|
+
function buildLayoutGraph(doc, nodeIds) {
|
|
8886
|
+
const wanted = nodeIds === void 0 ? void 0 : new Set(nodeIds);
|
|
8887
|
+
const nodes = Object.values(doc.nodes).filter((node) => node.parentId === null && (wanted === void 0 || wanted.has(node.id))).sort(byScreenOrder);
|
|
8888
|
+
const rank = new Map(nodes.map((node, index) => [node.id, index]));
|
|
8889
|
+
const byRank = (a, b) => (rank.get(a) ?? 0) - (rank.get(b) ?? 0);
|
|
8890
|
+
const forward = /* @__PURE__ */ new Map();
|
|
8891
|
+
const neighbors = /* @__PURE__ */ new Map();
|
|
8892
|
+
for (const node of nodes) {
|
|
8893
|
+
forward.set(node.id, []);
|
|
8894
|
+
neighbors.set(node.id, []);
|
|
8895
|
+
}
|
|
8896
|
+
const branchSiblings = /* @__PURE__ */ new Map();
|
|
8897
|
+
const inputSiblings = /* @__PURE__ */ new Map();
|
|
8898
|
+
const edgeIds = Object.keys(doc.edges).sort(compareText);
|
|
8899
|
+
for (const edgeId of edgeIds) {
|
|
8900
|
+
const edge = doc.edges[edgeId];
|
|
8901
|
+
if (edge === void 0) continue;
|
|
8902
|
+
const source = topLevelOf(doc, edge.source);
|
|
8903
|
+
const target = topLevelOf(doc, edge.target);
|
|
8904
|
+
if (source === void 0 || target === void 0 || source === target) continue;
|
|
8905
|
+
if (!rank.has(source) || !rank.has(target)) continue;
|
|
8906
|
+
pushTo(forward, source, target);
|
|
8907
|
+
pushTo(neighbors, source, target);
|
|
8908
|
+
pushTo(neighbors, target, source);
|
|
8909
|
+
if (typeof edge.data["branch"] !== "number") {
|
|
8910
|
+
pushTo(branchSiblings, `${edge.source}\0${edge.sourcePort}`, target);
|
|
8911
|
+
}
|
|
8912
|
+
if (typeof edge.data["order"] !== "number") {
|
|
8913
|
+
pushTo(inputSiblings, `${edge.target}\0${edge.targetPort}`, source);
|
|
8914
|
+
}
|
|
8915
|
+
}
|
|
8916
|
+
for (const list of forward.values()) list.sort(byRank);
|
|
8917
|
+
for (const list of neighbors.values()) list.sort(byRank);
|
|
8918
|
+
const successors = withoutBackEdges(nodes, forward);
|
|
8919
|
+
const predecessors = new Map(nodes.map((node) => [node.id, []]));
|
|
8920
|
+
for (const node of nodes) {
|
|
8921
|
+
for (const target of successors.get(node.id) ?? []) predecessors.get(target)?.push(node.id);
|
|
8922
|
+
}
|
|
8923
|
+
const orderedSiblings = [...branchSiblings.values(), ...inputSiblings.values()].filter((group) => group.length > 1).map((group) => [...group].sort(byRank));
|
|
8924
|
+
return { nodes, rank, successors, predecessors, neighbors, orderedSiblings };
|
|
8925
|
+
}
|
|
8926
|
+
function withoutBackEdges(nodes, forward) {
|
|
8927
|
+
const hasIncoming = /* @__PURE__ */ new Set();
|
|
8928
|
+
for (const targets of forward.values()) for (const target of targets) hasIncoming.add(target);
|
|
8929
|
+
const starts = [
|
|
8930
|
+
...nodes.filter((node) => !hasIncoming.has(node.id)),
|
|
8931
|
+
...nodes.filter((node) => hasIncoming.has(node.id)).sort(
|
|
8932
|
+
(a, b) => a.position.x - b.position.x || a.position.y - b.position.y || compareText(a.id, b.id)
|
|
8933
|
+
)
|
|
8934
|
+
];
|
|
8935
|
+
const kept = new Map(nodes.map((node) => [node.id, []]));
|
|
8936
|
+
const state = /* @__PURE__ */ new Map();
|
|
8937
|
+
for (const start of starts) {
|
|
8938
|
+
if (state.has(start.id)) continue;
|
|
8939
|
+
const stack = [{ id: start.id, next: 0 }];
|
|
8940
|
+
state.set(start.id, "open");
|
|
8941
|
+
for (let frame = stack[stack.length - 1]; frame !== void 0; frame = stack[stack.length - 1]) {
|
|
8942
|
+
const targets = forward.get(frame.id) ?? [];
|
|
8943
|
+
const target = targets[frame.next];
|
|
8944
|
+
if (target === void 0) {
|
|
8945
|
+
state.set(frame.id, "done");
|
|
8946
|
+
stack.pop();
|
|
8947
|
+
continue;
|
|
8948
|
+
}
|
|
8949
|
+
frame.next += 1;
|
|
8950
|
+
const seen = state.get(target);
|
|
8951
|
+
if (seen === "open") continue;
|
|
8952
|
+
kept.get(frame.id)?.push(target);
|
|
8953
|
+
if (seen === void 0) {
|
|
8954
|
+
state.set(target, "open");
|
|
8955
|
+
stack.push({ id: target, next: 0 });
|
|
8956
|
+
}
|
|
8957
|
+
}
|
|
8958
|
+
}
|
|
8959
|
+
return kept;
|
|
8960
|
+
}
|
|
8961
|
+
function assignLayers(graph, ids) {
|
|
8962
|
+
const pending = /* @__PURE__ */ new Map();
|
|
8963
|
+
for (const id of ids) pending.set(id, graph.predecessors.get(id)?.length ?? 0);
|
|
8964
|
+
const layer = /* @__PURE__ */ new Map();
|
|
8965
|
+
const queue = ids.filter((id) => pending.get(id) === 0);
|
|
8966
|
+
for (const id of queue) layer.set(id, 0);
|
|
8967
|
+
for (let head = 0; head < queue.length; head += 1) {
|
|
8968
|
+
const id = queue[head];
|
|
8969
|
+
if (id === void 0) continue;
|
|
8970
|
+
const current = layer.get(id) ?? 0;
|
|
8971
|
+
for (const target of graph.successors.get(id) ?? []) {
|
|
8972
|
+
layer.set(target, Math.max(layer.get(target) ?? 0, current + 1));
|
|
8973
|
+
const left = (pending.get(target) ?? 0) - 1;
|
|
8974
|
+
pending.set(target, left);
|
|
8975
|
+
if (left === 0) queue.push(target);
|
|
8976
|
+
}
|
|
8977
|
+
}
|
|
8978
|
+
for (const id of ids) {
|
|
8979
|
+
const targets = graph.successors.get(id) ?? [];
|
|
8980
|
+
if ((graph.predecessors.get(id)?.length ?? 0) > 0 || targets.length === 0) continue;
|
|
8981
|
+
layer.set(id, Math.min(...targets.map((target) => layer.get(target) ?? 1)) - 1);
|
|
8982
|
+
}
|
|
8983
|
+
return layer;
|
|
8984
|
+
}
|
|
8985
|
+
function splitComponents(graph) {
|
|
8986
|
+
const components = [];
|
|
8987
|
+
const isolated = [];
|
|
8988
|
+
const visited = /* @__PURE__ */ new Set();
|
|
8989
|
+
for (const node of graph.nodes) {
|
|
8990
|
+
if (visited.has(node.id)) continue;
|
|
8991
|
+
visited.add(node.id);
|
|
8992
|
+
if ((graph.neighbors.get(node.id)?.length ?? 0) === 0) {
|
|
8993
|
+
isolated.push(node.id);
|
|
8994
|
+
continue;
|
|
8995
|
+
}
|
|
8996
|
+
const members = [node.id];
|
|
8997
|
+
for (let head = 0; head < members.length; head += 1) {
|
|
8998
|
+
const id = members[head];
|
|
8999
|
+
if (id === void 0) continue;
|
|
9000
|
+
for (const next of graph.neighbors.get(id) ?? []) {
|
|
9001
|
+
if (visited.has(next)) continue;
|
|
9002
|
+
visited.add(next);
|
|
9003
|
+
members.push(next);
|
|
9004
|
+
}
|
|
9005
|
+
}
|
|
9006
|
+
members.sort((a, b) => (graph.rank.get(a) ?? 0) - (graph.rank.get(b) ?? 0));
|
|
9007
|
+
components.push(members);
|
|
9008
|
+
}
|
|
9009
|
+
return { components, isolated };
|
|
9010
|
+
}
|
|
9011
|
+
function countCrossings(graph, layers) {
|
|
9012
|
+
let crossings = 0;
|
|
9013
|
+
for (let index = 0; index + 1 < layers.length; index += 1) {
|
|
9014
|
+
const left = layers[index] ?? [];
|
|
9015
|
+
const right = new Map((layers[index + 1] ?? []).map((id, slot) => [id, slot]));
|
|
9016
|
+
const spans = [];
|
|
9017
|
+
left.forEach((id, slot) => {
|
|
9018
|
+
for (const target of graph.successors.get(id) ?? []) {
|
|
9019
|
+
const targetSlot = right.get(target);
|
|
9020
|
+
if (targetSlot !== void 0) spans.push([slot, targetSlot]);
|
|
9021
|
+
}
|
|
9022
|
+
});
|
|
9023
|
+
for (let a = 0; a < spans.length; a += 1) {
|
|
9024
|
+
for (let b = a + 1; b < spans.length; b += 1) {
|
|
9025
|
+
const first = spans[a];
|
|
9026
|
+
const second = spans[b];
|
|
9027
|
+
if (first === void 0 || second === void 0) continue;
|
|
9028
|
+
if ((first[0] - second[0]) * (first[1] - second[1]) < 0) crossings += 1;
|
|
9029
|
+
}
|
|
9030
|
+
}
|
|
9031
|
+
}
|
|
9032
|
+
return crossings;
|
|
9033
|
+
}
|
|
9034
|
+
function reorderLayer(layer, reference, neighborsOf) {
|
|
9035
|
+
const slotOf = new Map(reference.map((id, slot) => [id, slot]));
|
|
9036
|
+
const weight = /* @__PURE__ */ new Map();
|
|
9037
|
+
for (const id of layer) {
|
|
9038
|
+
const slots = neighborsOf(id).flatMap((neighbor) => {
|
|
9039
|
+
const slot = slotOf.get(neighbor);
|
|
9040
|
+
return slot === void 0 ? [] : [slot];
|
|
9041
|
+
});
|
|
9042
|
+
if (slots.length > 0) weight.set(id, slots.reduce((sum, slot) => sum + slot, 0) / slots.length);
|
|
9043
|
+
}
|
|
9044
|
+
const current = new Map(layer.map((id, slot) => [id, slot]));
|
|
9045
|
+
const movable = layer.filter((id) => weight.has(id)).sort(
|
|
9046
|
+
(a, b) => (weight.get(a) ?? 0) - (weight.get(b) ?? 0) || (current.get(a) ?? 0) - (current.get(b) ?? 0)
|
|
9047
|
+
);
|
|
9048
|
+
let next = 0;
|
|
9049
|
+
return layer.map((id) => weight.has(id) ? movable[next++] ?? id : id);
|
|
9050
|
+
}
|
|
9051
|
+
function restoreSiblingOrder(graph, layer) {
|
|
9052
|
+
const result = [...layer];
|
|
9053
|
+
for (const group of graph.orderedSiblings) {
|
|
9054
|
+
const members = new Set(group);
|
|
9055
|
+
const slots = [];
|
|
9056
|
+
result.forEach((id, slot) => {
|
|
9057
|
+
if (members.has(id)) slots.push(slot);
|
|
9058
|
+
});
|
|
9059
|
+
if (slots.length < 2) continue;
|
|
9060
|
+
const present = group.filter((id) => result.includes(id));
|
|
9061
|
+
slots.forEach((slot, index) => {
|
|
9062
|
+
const id = present[index];
|
|
9063
|
+
if (id !== void 0) result[slot] = id;
|
|
9064
|
+
});
|
|
9065
|
+
}
|
|
9066
|
+
return result;
|
|
9067
|
+
}
|
|
9068
|
+
function orderLayers(graph, initial, sweeps) {
|
|
9069
|
+
let layers = initial.map((layer) => [...layer]);
|
|
9070
|
+
let best = layers;
|
|
9071
|
+
let bestCrossings = countCrossings(graph, layers);
|
|
9072
|
+
for (let pass = 0; pass < sweeps && bestCrossings > 0; pass += 1) {
|
|
9073
|
+
const forward = pass % 2 === 0;
|
|
9074
|
+
const next = layers.map((layer) => [...layer]);
|
|
9075
|
+
const order = next.map((_, index) => index);
|
|
9076
|
+
if (!forward) order.reverse();
|
|
9077
|
+
for (const index of order) {
|
|
9078
|
+
const reference = next[forward ? index - 1 : index + 1];
|
|
9079
|
+
const layer = next[index];
|
|
9080
|
+
if (reference === void 0 || layer === void 0) continue;
|
|
9081
|
+
const neighborsOf = (id) => (forward ? graph.predecessors.get(id) : graph.successors.get(id)) ?? [];
|
|
9082
|
+
next[index] = restoreSiblingOrder(graph, reorderLayer(layer, reference, neighborsOf));
|
|
9083
|
+
}
|
|
9084
|
+
layers = next;
|
|
9085
|
+
const crossings = countCrossings(graph, layers);
|
|
9086
|
+
if (crossings < bestCrossings) {
|
|
9087
|
+
best = layers;
|
|
9088
|
+
bestCrossings = crossings;
|
|
9089
|
+
}
|
|
9090
|
+
}
|
|
9091
|
+
return best;
|
|
9092
|
+
}
|
|
9093
|
+
var DEFAULT_TIDY_GAP_X = 120;
|
|
9094
|
+
var DEFAULT_TIDY_GAP_Y = 48;
|
|
9095
|
+
var DEFAULT_TIDY_SWEEPS = 4;
|
|
9096
|
+
function layoutComponent(doc, graph, members, gapX, gapY, sweeps) {
|
|
9097
|
+
const layerOf = assignLayers(graph, members);
|
|
9098
|
+
const initial = [];
|
|
9099
|
+
for (const id of members) {
|
|
9100
|
+
const index = layerOf.get(id) ?? 0;
|
|
9101
|
+
(initial[index] ??= []).push(id);
|
|
9102
|
+
}
|
|
9103
|
+
const layers = orderLayers(
|
|
9104
|
+
graph,
|
|
9105
|
+
Array.from(initial, (layer) => layer ?? []).filter((layer) => layer.length > 0),
|
|
9106
|
+
sweeps
|
|
9107
|
+
);
|
|
9108
|
+
const columns = layers.map((layer) => {
|
|
9109
|
+
const nodes = layer.flatMap((id) => {
|
|
9110
|
+
const node = doc.nodes[id];
|
|
9111
|
+
return node === void 0 ? [] : [node];
|
|
9112
|
+
});
|
|
9113
|
+
const width2 = Math.max(...nodes.map((node) => node.size.w));
|
|
9114
|
+
const height = nodes.reduce((sum, node) => sum + node.size.h, 0) + (nodes.length - 1) * gapY;
|
|
9115
|
+
return { nodes, width: width2, height };
|
|
9116
|
+
});
|
|
9117
|
+
const tallest = Math.max(...columns.map((column) => column.height));
|
|
9118
|
+
const placed = [];
|
|
9119
|
+
let x = 0;
|
|
9120
|
+
for (const column of columns) {
|
|
9121
|
+
let y = Math.round((tallest - column.height) / 2);
|
|
9122
|
+
for (const node of column.nodes) {
|
|
9123
|
+
placed.push({ id: node.id, rect: { x, y, w: node.size.w, h: node.size.h } });
|
|
9124
|
+
y += node.size.h + gapY;
|
|
9125
|
+
}
|
|
9126
|
+
x += column.width + gapX;
|
|
9127
|
+
}
|
|
9128
|
+
return placed;
|
|
9129
|
+
}
|
|
9130
|
+
function layoutStrip(nodes, width2, gapX, gapY) {
|
|
9131
|
+
const placed = [];
|
|
9132
|
+
let x = 0;
|
|
9133
|
+
let y = 0;
|
|
9134
|
+
let shelfHeight = 0;
|
|
9135
|
+
for (const node of nodes) {
|
|
9136
|
+
if (x > 0 && x + node.size.w > width2) {
|
|
9137
|
+
x = 0;
|
|
9138
|
+
y += shelfHeight + gapY;
|
|
9139
|
+
shelfHeight = 0;
|
|
9140
|
+
}
|
|
9141
|
+
placed.push({ id: node.id, rect: { x, y, w: node.size.w, h: node.size.h } });
|
|
9142
|
+
x += node.size.w + gapX;
|
|
9143
|
+
shelfHeight = Math.max(shelfHeight, node.size.h);
|
|
9144
|
+
}
|
|
9145
|
+
return placed;
|
|
9146
|
+
}
|
|
9147
|
+
function shifted(placed, dx, dy) {
|
|
9148
|
+
return placed.map(({ id, rect }) => ({ id, rect: { ...rect, x: rect.x + dx, y: rect.y + dy } }));
|
|
9149
|
+
}
|
|
9150
|
+
function tidyUp(doc, options = {}) {
|
|
9151
|
+
const gapX = options.gapX ?? DEFAULT_TIDY_GAP_X;
|
|
9152
|
+
const gapY = options.gapY ?? DEFAULT_TIDY_GAP_Y;
|
|
9153
|
+
const componentGap = options.componentGap ?? gapY * 2;
|
|
9154
|
+
const sweeps = options.sweeps ?? DEFAULT_TIDY_SWEEPS;
|
|
9155
|
+
const graph = buildLayoutGraph(doc, options.nodeIds);
|
|
9156
|
+
if (graph.nodes.length === 0) return /* @__PURE__ */ new Map();
|
|
9157
|
+
const { components, isolated } = splitComponents(graph);
|
|
9158
|
+
let placed = [];
|
|
9159
|
+
let cursorY = 0;
|
|
9160
|
+
let widest = 0;
|
|
9161
|
+
for (const members of components) {
|
|
9162
|
+
const block = layoutComponent(doc, graph, members, gapX, gapY, sweeps);
|
|
9163
|
+
const bounds = boundsOf(block.map((item) => item.rect));
|
|
9164
|
+
placed = placed.concat(shifted(block, 0, cursorY));
|
|
9165
|
+
cursorY += bounds.h + componentGap;
|
|
9166
|
+
widest = Math.max(widest, bounds.w);
|
|
9167
|
+
}
|
|
9168
|
+
if (isolated.length > 0) {
|
|
9169
|
+
const loose = graph.nodes.filter((node) => isolated.includes(node.id));
|
|
9170
|
+
const area = loose.reduce((sum, node) => sum + (node.size.w + gapX) * (node.size.h + gapY), 0);
|
|
9171
|
+
const stripWidth = Math.max(widest, Math.sqrt(area * 1.6));
|
|
9172
|
+
placed = placed.concat(shifted(layoutStrip(loose, stripWidth, gapX, gapY), 0, cursorY));
|
|
9173
|
+
}
|
|
9174
|
+
const anchor = boundsOf(graph.nodes.map(rectOf2));
|
|
9175
|
+
const anchored = shifted(placed, Math.round(anchor.x), Math.round(anchor.y));
|
|
9176
|
+
const scope = graph.nodes.map((node) => node.id);
|
|
9177
|
+
const others = obstaclesOf(doc, scope);
|
|
9178
|
+
const touching = { x: 0, y: 0 };
|
|
9179
|
+
const covers = anchored.some(
|
|
9180
|
+
({ rect }) => others.some((other) => rectsCollide(rect, other, touching))
|
|
9181
|
+
);
|
|
9182
|
+
const rects = covers ? placeWithoutOverlap(
|
|
9183
|
+
doc,
|
|
9184
|
+
anchored.map((item) => item.rect),
|
|
9185
|
+
{ gap: { x: gapX, y: gapY }, ignore: scope }
|
|
9186
|
+
) : anchored.map((item) => item.rect);
|
|
9187
|
+
const positions = /* @__PURE__ */ new Map();
|
|
9188
|
+
anchored.forEach(({ id }, index) => {
|
|
9189
|
+
const rect = rects[index];
|
|
9190
|
+
if (rect !== void 0) positions.set(id, { x: rect.x, y: rect.y });
|
|
9191
|
+
});
|
|
9192
|
+
return positions;
|
|
9193
|
+
}
|
|
9194
|
+
function moveOps(positions) {
|
|
9195
|
+
const latest = /* @__PURE__ */ new Map();
|
|
9196
|
+
for (const [nodeId3, point2] of positions) latest.set(nodeId3, point2);
|
|
9197
|
+
const ops = [...latest.keys()].sort(compareText).flatMap((nodeId3) => {
|
|
9198
|
+
const point2 = latest.get(nodeId3);
|
|
9199
|
+
if (point2 === void 0) return [];
|
|
9200
|
+
return [
|
|
9201
|
+
{ type: "node.set", nodeId: nodeId3, path: "position", value: propValue({ x: point2.x, y: point2.y }) }
|
|
9202
|
+
];
|
|
9203
|
+
});
|
|
9204
|
+
return { type: "batch", ops };
|
|
9205
|
+
}
|
|
9206
|
+
function tidyUpOps(doc, options = {}) {
|
|
9207
|
+
const moved = [...tidyUp(doc, options)].filter(([nodeId3, point2]) => {
|
|
9208
|
+
const node = doc.nodes[nodeId3];
|
|
9209
|
+
return node !== void 0 && (node.position.x !== point2.x || node.position.y !== point2.y);
|
|
9210
|
+
});
|
|
9211
|
+
return moveOps(moved);
|
|
9212
|
+
}
|
|
9213
|
+
var MAX_REPLAY = 200;
|
|
9214
|
+
function tryApplyOp(doc, op) {
|
|
9215
|
+
const result = step(doc, op);
|
|
9216
|
+
return typeof result === "string" ? { ok: false, reason: result } : { ok: true, doc: result };
|
|
9217
|
+
}
|
|
9218
|
+
function tryApplyEnvelope(doc, envelope2) {
|
|
9219
|
+
if (opEnvelopeBytes(envelope2) > MAX_OP_BYTES2) return { ok: false, reason: "too-large" };
|
|
9220
|
+
return tryApplyOp(doc, envelope2.op);
|
|
9221
|
+
}
|
|
9222
|
+
function applyConfirmed2(doc, envelope2) {
|
|
9223
|
+
if (envelope2.seq === null) {
|
|
9224
|
+
throw new Error(`applyConfirmed recebeu o envelope ${envelope2.id} sem seq`);
|
|
9225
|
+
}
|
|
9226
|
+
const next = applyOps(doc, [envelope2.op]).doc;
|
|
9227
|
+
return { ...next, version: envelope2.seq };
|
|
9228
|
+
}
|
|
9229
|
+
function step(doc, op) {
|
|
9230
|
+
switch (op.type) {
|
|
9231
|
+
case "batch": {
|
|
9232
|
+
let current = doc;
|
|
9233
|
+
for (const inner of op.ops) {
|
|
9234
|
+
const result = step(current, inner);
|
|
9235
|
+
if (typeof result === "string") return result;
|
|
9236
|
+
current = result;
|
|
9237
|
+
}
|
|
9238
|
+
return current;
|
|
9239
|
+
}
|
|
9240
|
+
case "node.set":
|
|
9241
|
+
case "history.append":
|
|
9242
|
+
if (doc.nodes[op.nodeId] === void 0) return "node-missing";
|
|
9243
|
+
break;
|
|
9244
|
+
case "edge.add":
|
|
9245
|
+
if (doc.nodes[op.edge.source] === void 0 || doc.nodes[op.edge.target] === void 0) {
|
|
9246
|
+
return "edge-endpoint-missing";
|
|
9247
|
+
}
|
|
9248
|
+
break;
|
|
9249
|
+
default:
|
|
9250
|
+
break;
|
|
9251
|
+
}
|
|
9252
|
+
try {
|
|
9253
|
+
return applyOps(doc, [op]).doc;
|
|
9254
|
+
} catch {
|
|
9255
|
+
return "invalid-op";
|
|
9256
|
+
}
|
|
9257
|
+
}
|
|
9258
|
+
function defaultScheduler() {
|
|
9259
|
+
const host = globalThis;
|
|
9260
|
+
return {
|
|
9261
|
+
setTimeout: (callback, ms) => host.setTimeout(callback, ms),
|
|
9262
|
+
clearTimeout: (handle) => host.clearTimeout(handle)
|
|
9263
|
+
};
|
|
9264
|
+
}
|
|
9265
|
+
var OpSyncClient = class {
|
|
9266
|
+
store;
|
|
9267
|
+
transport;
|
|
9268
|
+
scheduler;
|
|
9269
|
+
batchMs;
|
|
9270
|
+
gapGraceMs;
|
|
9271
|
+
retryMs;
|
|
9272
|
+
maxRetryMs;
|
|
9273
|
+
maxBatch;
|
|
9274
|
+
onDiscard;
|
|
9275
|
+
onTransportError;
|
|
9276
|
+
confirmed;
|
|
9277
|
+
lastSeq;
|
|
9278
|
+
buffer = /* @__PURE__ */ new Map();
|
|
9279
|
+
pending = [];
|
|
9280
|
+
online = false;
|
|
9281
|
+
started = false;
|
|
9282
|
+
stopped = false;
|
|
9283
|
+
commitInFlight = false;
|
|
9284
|
+
syncInFlight = false;
|
|
9285
|
+
snapshotInFlight = false;
|
|
9286
|
+
flushTimer = null;
|
|
9287
|
+
gapTimer = null;
|
|
9288
|
+
retryTimer = null;
|
|
9289
|
+
retryDelay;
|
|
9290
|
+
unsubscribe = [];
|
|
9291
|
+
stats = {
|
|
9292
|
+
commits: 0,
|
|
9293
|
+
commitFailures: 0,
|
|
9294
|
+
syncs: 0,
|
|
9295
|
+
gapSyncs: 0,
|
|
9296
|
+
snapshots: 0,
|
|
9297
|
+
discarded: 0,
|
|
9298
|
+
echoes: 0
|
|
9299
|
+
};
|
|
9300
|
+
constructor(options) {
|
|
9301
|
+
this.store = options.store;
|
|
9302
|
+
this.transport = options.transport;
|
|
9303
|
+
this.scheduler = options.scheduler ?? defaultScheduler();
|
|
9304
|
+
this.batchMs = options.batchMs ?? 200;
|
|
9305
|
+
this.gapGraceMs = options.gapGraceMs ?? 300;
|
|
9306
|
+
this.retryMs = options.retryMs ?? 1e3;
|
|
9307
|
+
this.maxRetryMs = options.maxRetryMs ?? 3e4;
|
|
9308
|
+
this.maxBatch = options.maxBatch ?? 100;
|
|
9309
|
+
this.onDiscard = options.onDiscard;
|
|
9310
|
+
this.onTransportError = options.onTransportError;
|
|
9311
|
+
this.retryDelay = this.retryMs;
|
|
9312
|
+
this.lastSeq = options.seq;
|
|
9313
|
+
this.confirmed = { ...this.store.getDoc(), version: options.seq };
|
|
9314
|
+
}
|
|
9315
|
+
/** Entra na sala, passa a ouvir o store e pede o que perdeu desde `seq`. */
|
|
9316
|
+
start() {
|
|
9317
|
+
if (this.started) return;
|
|
9318
|
+
this.started = true;
|
|
9319
|
+
this.unsubscribe.push(
|
|
9320
|
+
this.store.subscribeEnvelopes((envelope2) => this.enqueue(envelope2)),
|
|
9321
|
+
this.transport.subscribe({
|
|
9322
|
+
onOps: (envelopes) => this.receive(envelopes),
|
|
9323
|
+
onResync: () => this.requestSnapshot(),
|
|
9324
|
+
onConnectionChange: (online) => this.setOnline(online)
|
|
9325
|
+
})
|
|
9326
|
+
);
|
|
9327
|
+
this.online = this.transport.isOnline();
|
|
9328
|
+
if (this.online) this.requestSync();
|
|
9329
|
+
}
|
|
9330
|
+
/** Sai da sala e para os relógios. Pendentes ficam onde estão (`pendingEnvelopes`). */
|
|
9331
|
+
stop() {
|
|
9332
|
+
this.stopped = true;
|
|
9333
|
+
for (const off of this.unsubscribe) off();
|
|
9334
|
+
this.unsubscribe = [];
|
|
9335
|
+
this.clearTimer("flushTimer");
|
|
9336
|
+
this.clearTimer("gapTimer");
|
|
9337
|
+
this.clearTimer("retryTimer");
|
|
9338
|
+
}
|
|
9339
|
+
/** Commita já, sem esperar a janela do lote. */
|
|
9340
|
+
flushNow() {
|
|
9341
|
+
this.clearTimer("flushTimer");
|
|
9342
|
+
this.flush();
|
|
9343
|
+
}
|
|
9344
|
+
getStatus() {
|
|
9345
|
+
const inFlight = this.pending.filter((item) => item.inFlight).length;
|
|
9346
|
+
return {
|
|
9347
|
+
online: this.online,
|
|
9348
|
+
lastSeq: this.lastSeq,
|
|
9349
|
+
pending: this.pending.length,
|
|
9350
|
+
inFlight,
|
|
9351
|
+
buffered: this.buffer.size,
|
|
9352
|
+
settled: this.pending.length === 0 && this.buffer.size === 0 && !this.commitInFlight && !this.syncInFlight && !this.snapshotInFlight
|
|
9353
|
+
};
|
|
9354
|
+
}
|
|
9355
|
+
/** A foto confirmada, sem pendentes. */
|
|
9356
|
+
getConfirmedDoc() {
|
|
9357
|
+
return this.confirmed;
|
|
9358
|
+
}
|
|
9359
|
+
/** As pendentes, em ordem. Para o cache local guardar até voltarem. */
|
|
9360
|
+
pendingEnvelopes() {
|
|
9361
|
+
return this.pending.map((item) => item.envelope);
|
|
9362
|
+
}
|
|
9363
|
+
// ------------------------------------------------------------------ entrada
|
|
9364
|
+
enqueue(envelope2) {
|
|
9365
|
+
if (this.stopped) return;
|
|
9366
|
+
if (opEnvelopeBytes(envelope2) > MAX_OP_BYTES2) {
|
|
9367
|
+
this.discard(envelope2, "too-large", "too-large");
|
|
9368
|
+
this.rebuild();
|
|
9369
|
+
return;
|
|
9370
|
+
}
|
|
9371
|
+
this.pending.push({ envelope: envelope2, sent: false, inFlight: false });
|
|
9372
|
+
this.scheduleFlush();
|
|
9373
|
+
}
|
|
9374
|
+
receive(envelopes) {
|
|
9375
|
+
if (this.stopped) return;
|
|
9376
|
+
let changed = false;
|
|
9377
|
+
for (const envelope2 of envelopes) {
|
|
9378
|
+
if (envelope2.seq === null) continue;
|
|
9379
|
+
if (this.findPending(envelope2.id) >= 0) this.stats.echoes += 1;
|
|
9380
|
+
if (this.confirm(envelope2.id, envelope2.seq, envelope2)) changed = true;
|
|
9381
|
+
}
|
|
9382
|
+
if (changed) this.settle();
|
|
9383
|
+
else this.checkGap();
|
|
9384
|
+
}
|
|
9385
|
+
/**
|
|
9386
|
+
* Registra que `opId` foi confirmado com `seq`. Se é pendente nossa, sai da
|
|
9387
|
+
* fila (eco, resposta do commit ou replay: tanto faz qual chega primeiro).
|
|
9388
|
+
* Devolve se algo mudou.
|
|
9389
|
+
*/
|
|
9390
|
+
confirm(opId, seq, wire) {
|
|
9391
|
+
const index = this.findPending(opId);
|
|
9392
|
+
let envelope2 = wire;
|
|
9393
|
+
if (index >= 0) {
|
|
9394
|
+
const [item] = this.pending.splice(index, 1);
|
|
9395
|
+
envelope2 = item?.envelope;
|
|
9396
|
+
}
|
|
9397
|
+
if (seq <= this.lastSeq) return index >= 0;
|
|
9398
|
+
if (envelope2 === void 0) return index >= 0;
|
|
9399
|
+
if (!this.buffer.has(seq)) this.buffer.set(seq, { ...envelope2, seq });
|
|
9400
|
+
return true;
|
|
9401
|
+
}
|
|
9402
|
+
// ---------------------------------------------------------------- commit
|
|
9403
|
+
scheduleFlush() {
|
|
9404
|
+
if (this.flushTimer !== null || this.stopped) return;
|
|
9405
|
+
this.flushTimer = this.scheduler.setTimeout(() => {
|
|
9406
|
+
this.flushTimer = null;
|
|
9407
|
+
this.flush();
|
|
9408
|
+
}, this.batchMs);
|
|
9409
|
+
}
|
|
9410
|
+
flush() {
|
|
9411
|
+
if (this.stopped || !this.online || this.commitInFlight) return;
|
|
9412
|
+
const batch = this.pending.slice(0, this.maxBatch);
|
|
9413
|
+
if (batch.length === 0) return;
|
|
9414
|
+
for (const item of batch) {
|
|
9415
|
+
item.sent = true;
|
|
9416
|
+
item.inFlight = true;
|
|
9417
|
+
}
|
|
9418
|
+
this.commitInFlight = true;
|
|
9419
|
+
this.stats.commits += 1;
|
|
9420
|
+
this.transport.commit(batch.map((item) => item.envelope)).then(
|
|
9421
|
+
(response) => this.onCommitted(batch, response),
|
|
9422
|
+
(error2) => this.onCommitFailed(batch, error2)
|
|
9423
|
+
);
|
|
9424
|
+
}
|
|
9425
|
+
onCommitted(batch, response) {
|
|
9426
|
+
this.commitInFlight = false;
|
|
9427
|
+
for (const item of batch) item.inFlight = false;
|
|
9428
|
+
if (this.stopped) return;
|
|
9429
|
+
this.retryDelay = this.retryMs;
|
|
9430
|
+
let changed = false;
|
|
9431
|
+
for (const outcome of response.outcomes) {
|
|
9432
|
+
if ("seq" in outcome) {
|
|
9433
|
+
if (this.confirm(outcome.opId, outcome.seq)) changed = true;
|
|
9434
|
+
} else {
|
|
9435
|
+
const index = this.findPending(outcome.opId);
|
|
9436
|
+
if (index < 0) continue;
|
|
9437
|
+
const [item] = this.pending.splice(index, 1);
|
|
9438
|
+
if (item !== void 0) this.discard(item.envelope, "rejected", outcome.rejected);
|
|
9439
|
+
changed = true;
|
|
9440
|
+
}
|
|
9441
|
+
}
|
|
9442
|
+
if (changed) this.settle();
|
|
9443
|
+
if (this.pending.length > 0) this.flush();
|
|
9444
|
+
}
|
|
9445
|
+
onCommitFailed(batch, error2) {
|
|
9446
|
+
this.commitInFlight = false;
|
|
9447
|
+
for (const item of batch) item.inFlight = false;
|
|
9448
|
+
if (this.stopped) return;
|
|
9449
|
+
this.stats.commitFailures += 1;
|
|
9450
|
+
this.onTransportError?.(error2);
|
|
9451
|
+
this.scheduleRetry();
|
|
9452
|
+
}
|
|
9453
|
+
// ------------------------------------------------------- sync e foto
|
|
9454
|
+
requestSync() {
|
|
9455
|
+
if (this.stopped || !this.online || this.syncInFlight) return;
|
|
9456
|
+
this.syncInFlight = true;
|
|
9457
|
+
this.stats.syncs += 1;
|
|
9458
|
+
this.transport.sync(this.lastSeq).then(
|
|
9459
|
+
(response) => this.onSynced(response),
|
|
9460
|
+
(error2) => {
|
|
9461
|
+
this.syncInFlight = false;
|
|
9462
|
+
if (this.stopped) return;
|
|
9463
|
+
this.onTransportError?.(error2);
|
|
9464
|
+
this.scheduleRetry();
|
|
9465
|
+
}
|
|
9466
|
+
);
|
|
9467
|
+
}
|
|
9468
|
+
onSynced(response) {
|
|
9469
|
+
this.syncInFlight = false;
|
|
9470
|
+
if (this.stopped) return;
|
|
9471
|
+
if (response.status === "resync") {
|
|
9472
|
+
this.requestSnapshot();
|
|
9473
|
+
return;
|
|
9474
|
+
}
|
|
9475
|
+
this.receive(response.envelopes);
|
|
9476
|
+
}
|
|
9477
|
+
requestSnapshot() {
|
|
9478
|
+
if (this.stopped || !this.online || this.snapshotInFlight) return;
|
|
9479
|
+
this.snapshotInFlight = true;
|
|
9480
|
+
this.stats.snapshots += 1;
|
|
9481
|
+
this.transport.snapshot().then(
|
|
9482
|
+
(snapshot) => {
|
|
9483
|
+
this.snapshotInFlight = false;
|
|
9484
|
+
if (this.stopped) return;
|
|
9485
|
+
if (snapshot.seq < this.lastSeq) return;
|
|
9486
|
+
this.confirmed = { ...snapshot.doc, version: snapshot.seq };
|
|
9487
|
+
this.lastSeq = snapshot.seq;
|
|
9488
|
+
this.settle();
|
|
9489
|
+
this.flush();
|
|
9490
|
+
},
|
|
9491
|
+
(error2) => {
|
|
9492
|
+
this.snapshotInFlight = false;
|
|
9493
|
+
if (this.stopped) return;
|
|
9494
|
+
this.onTransportError?.(error2);
|
|
9495
|
+
this.scheduleRetry();
|
|
9496
|
+
}
|
|
9497
|
+
);
|
|
9498
|
+
}
|
|
9499
|
+
// --------------------------------------------------------------- conexão
|
|
9500
|
+
setOnline(online) {
|
|
9501
|
+
if (this.stopped) return;
|
|
9502
|
+
this.online = online;
|
|
9503
|
+
if (!online) return;
|
|
9504
|
+
this.retryDelay = this.retryMs;
|
|
9505
|
+
this.clearTimer("retryTimer");
|
|
9506
|
+
this.resume();
|
|
9507
|
+
}
|
|
9508
|
+
resume() {
|
|
9509
|
+
this.requestSync();
|
|
9510
|
+
this.flush();
|
|
9511
|
+
}
|
|
9512
|
+
scheduleRetry() {
|
|
9513
|
+
if (this.retryTimer !== null || !this.online) return;
|
|
9514
|
+
const delay = this.retryDelay;
|
|
9515
|
+
this.retryDelay = Math.min(this.retryDelay * 2, this.maxRetryMs);
|
|
9516
|
+
this.retryTimer = this.scheduler.setTimeout(() => {
|
|
9517
|
+
this.retryTimer = null;
|
|
9518
|
+
this.resume();
|
|
9519
|
+
}, delay);
|
|
9520
|
+
}
|
|
9521
|
+
// ---------------------------------------------------------- foto e tela
|
|
9522
|
+
/** Avança a foto pelo que é contíguo, reconstrói a tela e confere buraco. */
|
|
9523
|
+
settle() {
|
|
9524
|
+
for (const seq of [...this.buffer.keys()]) {
|
|
9525
|
+
if (seq <= this.lastSeq) this.buffer.delete(seq);
|
|
9526
|
+
}
|
|
9527
|
+
for (; ; ) {
|
|
9528
|
+
const next = this.buffer.get(this.lastSeq + 1);
|
|
9529
|
+
if (next === void 0) break;
|
|
9530
|
+
this.buffer.delete(this.lastSeq + 1);
|
|
9531
|
+
try {
|
|
9532
|
+
this.confirmed = applyConfirmed2(this.confirmed, next);
|
|
9533
|
+
} catch {
|
|
9534
|
+
this.buffer.clear();
|
|
9535
|
+
this.requestSnapshot();
|
|
9536
|
+
break;
|
|
9537
|
+
}
|
|
9538
|
+
this.lastSeq += 1;
|
|
9539
|
+
}
|
|
9540
|
+
this.rebuild();
|
|
9541
|
+
this.checkGap();
|
|
9542
|
+
}
|
|
9543
|
+
/**
|
|
9544
|
+
* A tela = foto confirmada + confirmados à frente do buraco + pendentes.
|
|
9545
|
+
*
|
|
9546
|
+
* Pendente que nunca saiu e não vale mais é descartada aqui. A que já saiu
|
|
9547
|
+
* fica fora da tela, mas na fila, até o servidor dizer o que houve com ela.
|
|
9548
|
+
*/
|
|
9549
|
+
rebuild() {
|
|
9550
|
+
let doc = this.confirmed;
|
|
9551
|
+
for (const seq of [...this.buffer.keys()].sort((a, b) => a - b)) {
|
|
9552
|
+
const envelope2 = this.buffer.get(seq);
|
|
9553
|
+
if (envelope2 === void 0) continue;
|
|
9554
|
+
const verdict = tryApplyEnvelope(doc, envelope2);
|
|
9555
|
+
if (verdict.ok) doc = verdict.doc;
|
|
9556
|
+
}
|
|
9557
|
+
const kept = [];
|
|
9558
|
+
for (const item of this.pending) {
|
|
9559
|
+
const verdict = tryApplyEnvelope(doc, item.envelope);
|
|
9560
|
+
if (verdict.ok) {
|
|
9561
|
+
doc = verdict.doc;
|
|
9562
|
+
kept.push(item);
|
|
9563
|
+
} else if (item.sent) {
|
|
9564
|
+
kept.push(item);
|
|
9565
|
+
} else {
|
|
9566
|
+
this.discard(item.envelope, "not-applicable", verdict.reason);
|
|
9567
|
+
}
|
|
9568
|
+
}
|
|
9569
|
+
this.pending = kept;
|
|
9570
|
+
this.store.replaceDoc(doc.version === this.lastSeq ? doc : { ...doc, version: this.lastSeq });
|
|
9571
|
+
}
|
|
9572
|
+
checkGap() {
|
|
9573
|
+
if (this.buffer.size === 0) {
|
|
9574
|
+
this.clearTimer("gapTimer");
|
|
9575
|
+
return;
|
|
9576
|
+
}
|
|
9577
|
+
if (this.gapTimer !== null) return;
|
|
9578
|
+
this.gapTimer = this.scheduler.setTimeout(() => {
|
|
9579
|
+
this.gapTimer = null;
|
|
9580
|
+
if (this.buffer.size === 0) return;
|
|
9581
|
+
this.stats.gapSyncs += 1;
|
|
9582
|
+
this.requestSync();
|
|
9583
|
+
}, this.gapGraceMs);
|
|
9584
|
+
}
|
|
9585
|
+
// -------------------------------------------------------------- miúdos
|
|
9586
|
+
discard(envelope2, reason, detail) {
|
|
9587
|
+
this.stats.discarded += 1;
|
|
9588
|
+
this.onDiscard?.({ envelope: envelope2, reason, detail });
|
|
9589
|
+
}
|
|
9590
|
+
findPending(opId) {
|
|
9591
|
+
return this.pending.findIndex((item) => item.envelope.id === opId);
|
|
9592
|
+
}
|
|
9593
|
+
clearTimer(name) {
|
|
9594
|
+
const handle = this[name];
|
|
9595
|
+
if (handle === null) return;
|
|
9596
|
+
this.scheduler.clearTimeout(handle);
|
|
9597
|
+
this[name] = null;
|
|
9598
|
+
}
|
|
9599
|
+
};
|
|
9600
|
+
}
|
|
9601
|
+
});
|
|
9602
|
+
|
|
6888
9603
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
|
|
6889
9604
|
import process2 from "process";
|
|
6890
9605
|
|
|
@@ -21172,8 +23887,19 @@ var LoginExpiredError = class extends ApiError {
|
|
|
21172
23887
|
this.name = "LoginExpiredError";
|
|
21173
23888
|
}
|
|
21174
23889
|
};
|
|
23890
|
+
var ServerBusyError = class extends ApiError {
|
|
23891
|
+
constructor(status, waitS, what) {
|
|
23892
|
+
super(
|
|
23893
|
+
status,
|
|
23894
|
+
`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.`
|
|
23895
|
+
);
|
|
23896
|
+
this.waitS = waitS;
|
|
23897
|
+
this.name = "ServerBusyError";
|
|
23898
|
+
}
|
|
23899
|
+
waitS;
|
|
23900
|
+
};
|
|
21175
23901
|
function apiErrorToUserMessage(err) {
|
|
21176
|
-
if (err instanceof LoginExpiredError) return err.message;
|
|
23902
|
+
if (err instanceof LoginExpiredError || err instanceof ServerBusyError) return err.message;
|
|
21177
23903
|
if (err instanceof ApiError) {
|
|
21178
23904
|
const detail = err.message || "";
|
|
21179
23905
|
switch (err.httpStatus) {
|
|
@@ -21533,6 +24259,26 @@ async function fetchWithAuth(cfg, url, init, what) {
|
|
|
21533
24259
|
}
|
|
21534
24260
|
|
|
21535
24261
|
// src/api/client.ts
|
|
24262
|
+
var retryPolicy = {
|
|
24263
|
+
retries: 4,
|
|
24264
|
+
baseMs: 1e3,
|
|
24265
|
+
capMs: 3e4,
|
|
24266
|
+
/** Passou disso esperando, desiste e devolve "tente em N s" ao agente em vez de segurar a tool. */
|
|
24267
|
+
budgetMs: 45e3,
|
|
24268
|
+
random: Math.random,
|
|
24269
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
|
|
24270
|
+
};
|
|
24271
|
+
var RETRYABLE = /* @__PURE__ */ new Set([0, 429, 503]);
|
|
24272
|
+
function retryAfterMs(res) {
|
|
24273
|
+
const raw = res.headers.get("retry-after");
|
|
24274
|
+
if (!raw) return null;
|
|
24275
|
+
const secs = Number(raw);
|
|
24276
|
+
if (Number.isFinite(secs)) return Math.max(0, secs * 1e3);
|
|
24277
|
+
const at = Date.parse(raw);
|
|
24278
|
+
return Number.isFinite(at) ? Math.max(0, at - Date.now()) : null;
|
|
24279
|
+
}
|
|
24280
|
+
var costCachePolicy = { ttlMs: 10 * 6e4, capacity: 256, now: () => Date.now() };
|
|
24281
|
+
var costCache = /* @__PURE__ */ new Map();
|
|
21536
24282
|
var BeplusClient = class {
|
|
21537
24283
|
constructor(cfg) {
|
|
21538
24284
|
this.cfg = cfg;
|
|
@@ -21540,23 +24286,63 @@ var BeplusClient = class {
|
|
|
21540
24286
|
cfg;
|
|
21541
24287
|
/** Público para os módulos de rota própria (ex.: Canvas) reaproveitarem auth, timeout e erros. */
|
|
21542
24288
|
async request(method, path, opts = {}) {
|
|
24289
|
+
return (await this.requestMeta(method, path, opts)).data;
|
|
24290
|
+
}
|
|
24291
|
+
/** Igual a `request`, mas devolve status e ETag, e trata 304 como resposta (sem corpo). */
|
|
24292
|
+
async requestMeta(method, path, opts = {}) {
|
|
21543
24293
|
const url = new URL(`${opts.base ?? this.cfg.apiBase}${path}`);
|
|
21544
24294
|
if (opts.query) {
|
|
21545
24295
|
for (const [k, v] of Object.entries(opts.query)) {
|
|
21546
24296
|
if (v !== void 0 && v !== null && v !== "") url.searchParams.set(k, String(v));
|
|
21547
24297
|
}
|
|
21548
24298
|
}
|
|
21549
|
-
const
|
|
21550
|
-
|
|
21551
|
-
|
|
21552
|
-
|
|
21553
|
-
|
|
21554
|
-
|
|
21555
|
-
|
|
21556
|
-
|
|
21557
|
-
|
|
21558
|
-
|
|
21559
|
-
|
|
24299
|
+
const retry = opts.retry ?? method === "GET";
|
|
24300
|
+
const p = retryPolicy;
|
|
24301
|
+
const started = Date.now();
|
|
24302
|
+
for (let attempt = 0; ; attempt++) {
|
|
24303
|
+
let res = null;
|
|
24304
|
+
let failure = null;
|
|
24305
|
+
try {
|
|
24306
|
+
res = await fetchWithAuth(
|
|
24307
|
+
this.cfg,
|
|
24308
|
+
url,
|
|
24309
|
+
{
|
|
24310
|
+
method,
|
|
24311
|
+
headers: { ...opts.body ? { "Content-Type": "application/json" } : {}, ...opts.headers },
|
|
24312
|
+
body: opts.body ? JSON.stringify(opts.body) : void 0,
|
|
24313
|
+
timeoutMs: opts.timeoutMs ?? 3e4
|
|
24314
|
+
},
|
|
24315
|
+
path
|
|
24316
|
+
);
|
|
24317
|
+
} catch (e) {
|
|
24318
|
+
if (!(e instanceof ApiError) || e.httpStatus !== 0) throw e;
|
|
24319
|
+
failure = e;
|
|
24320
|
+
}
|
|
24321
|
+
const status = res ? res.status : 0;
|
|
24322
|
+
if (!retry || !RETRYABLE.has(status)) {
|
|
24323
|
+
if (failure) throw failure;
|
|
24324
|
+
return this.read(res, path);
|
|
24325
|
+
}
|
|
24326
|
+
const step = Math.min(p.capMs, p.baseMs * 2 ** attempt);
|
|
24327
|
+
const asked = res ? retryAfterMs(res) : null;
|
|
24328
|
+
const wait = asked ?? step / 2 + p.random() * (step / 2);
|
|
24329
|
+
if (attempt >= p.retries || asked !== null && asked > p.capMs || Date.now() - started + wait > p.budgetMs) {
|
|
24330
|
+
await res?.body?.cancel().catch(() => {
|
|
24331
|
+
});
|
|
24332
|
+
throw new ServerBusyError(status, Math.max(1, Math.ceil(Math.max(wait, p.baseMs) / 1e3)), path);
|
|
24333
|
+
}
|
|
24334
|
+
await res?.body?.cancel().catch(() => {
|
|
24335
|
+
});
|
|
24336
|
+
await p.sleep(wait);
|
|
24337
|
+
}
|
|
24338
|
+
}
|
|
24339
|
+
async read(res, path) {
|
|
24340
|
+
const etag = res.headers.get("etag");
|
|
24341
|
+
if (res.status === 304) {
|
|
24342
|
+
await res.body?.cancel().catch(() => {
|
|
24343
|
+
});
|
|
24344
|
+
return { status: 304, etag, data: null, bytes: 0 };
|
|
24345
|
+
}
|
|
21560
24346
|
let text;
|
|
21561
24347
|
try {
|
|
21562
24348
|
text = await res.text();
|
|
@@ -21574,7 +24360,8 @@ var BeplusClient = class {
|
|
|
21574
24360
|
const message = json2?.message || (Array.isArray(json2?.error?.formatted) ? json2.error.formatted.join(", ") : void 0) || res.statusText || `HTTP ${res.status}`;
|
|
21575
24361
|
throw new ApiError(res.status, message, json2);
|
|
21576
24362
|
}
|
|
21577
|
-
|
|
24363
|
+
const data = json2 && typeof json2 === "object" && "result" in json2 ? json2.result : json2;
|
|
24364
|
+
return { status: res.status, etag, data, bytes: text.length };
|
|
21578
24365
|
}
|
|
21579
24366
|
startGeneration(body2) {
|
|
21580
24367
|
return this.request("POST", "/generations", { body: body2 });
|
|
@@ -21654,8 +24441,21 @@ var BeplusClient = class {
|
|
|
21654
24441
|
models() {
|
|
21655
24442
|
return this.request("GET", "/models");
|
|
21656
24443
|
}
|
|
24444
|
+
/** Cache por parâmetros: o preço não muda entre chamadas, e o agente estima o mesmo modelo várias vezes. */
|
|
21657
24445
|
calculateCost(query) {
|
|
21658
|
-
|
|
24446
|
+
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));
|
|
24447
|
+
const key = `${this.cfg.apiBase}|${JSON.stringify(normalized)}`;
|
|
24448
|
+
const now = costCachePolicy.now();
|
|
24449
|
+
const hit = costCache.get(key);
|
|
24450
|
+
if (hit && (hit.expiresAt === null || hit.expiresAt > now)) return hit.value;
|
|
24451
|
+
const value = this.request("GET", "/calculate-cost", { query });
|
|
24452
|
+
costCache.set(key, { value, expiresAt: null });
|
|
24453
|
+
value.then(
|
|
24454
|
+
() => costCache.set(key, { value, expiresAt: costCachePolicy.now() + costCachePolicy.ttlMs }),
|
|
24455
|
+
() => costCache.delete(key)
|
|
24456
|
+
);
|
|
24457
|
+
while (costCache.size > costCachePolicy.capacity) costCache.delete(costCache.keys().next().value);
|
|
24458
|
+
return value;
|
|
21659
24459
|
}
|
|
21660
24460
|
/** `billing: 'personal'` pula o budget do projeto ativo no preview do saldo. */
|
|
21661
24461
|
balance(billing) {
|
|
@@ -21754,6 +24554,9 @@ import { readFile as readFile2, stat as stat2 } from "fs/promises";
|
|
|
21754
24554
|
import { lookup } from "dns/promises";
|
|
21755
24555
|
import { isIP } from "net";
|
|
21756
24556
|
var remote = false;
|
|
24557
|
+
function isRemoteMode() {
|
|
24558
|
+
return remote;
|
|
24559
|
+
}
|
|
21757
24560
|
function refuseLocalPath(ref) {
|
|
21758
24561
|
if (!remote) return;
|
|
21759
24562
|
throw new ApiError(
|
|
@@ -24566,9 +27369,11 @@ ${calls.map(callLine).join("\n\n")}`);
|
|
|
24566
27369
|
}
|
|
24567
27370
|
|
|
24568
27371
|
// src/tools/canvas.ts
|
|
24569
|
-
import { createHash } from "crypto";
|
|
27372
|
+
import { createHash as createHash2 } from "crypto";
|
|
24570
27373
|
|
|
24571
27374
|
// src/canvas/api.ts
|
|
27375
|
+
import { createHash } from "crypto";
|
|
27376
|
+
var import_canvas_core = __toESM(require_canvas_core(), 1);
|
|
24572
27377
|
var PINNED_CORE_VERSION = "ca7b3b406184c7f679f555c3a008013197182b23";
|
|
24573
27378
|
var RUN_REQUEST_TIMEOUT_MS = 4e4;
|
|
24574
27379
|
var FOCUS_REQUEST_TIMEOUT_MS = 12e3;
|
|
@@ -24583,6 +27388,54 @@ var commentPacing = {
|
|
|
24583
27388
|
now: () => Date.now(),
|
|
24584
27389
|
sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
|
|
24585
27390
|
};
|
|
27391
|
+
var boardCachePolicy = {
|
|
27392
|
+
/** Contrato 5: duas leituras do mesmo board com menos que isso reaproveitam a anterior sem rede. */
|
|
27393
|
+
minIntervalMs: 2e3,
|
|
27394
|
+
stdio: { entries: 4, bytes: 256 * 1024 * 1024 },
|
|
27395
|
+
/** Dentro do academy-api: o doc em cache ocupa a memória da própria API. */
|
|
27396
|
+
remote: { entries: 2, bytes: 64 * 1024 * 1024 },
|
|
27397
|
+
/** Envelopes guardados para o conflito do edit() sem ir à rede (o servidor manda reler acima de 200). */
|
|
27398
|
+
recentMax: 200,
|
|
27399
|
+
now: () => Date.now()
|
|
27400
|
+
};
|
|
27401
|
+
var boardStore = /* @__PURE__ */ new Map();
|
|
27402
|
+
var boardLoads = /* @__PURE__ */ new Map();
|
|
27403
|
+
function storeEntry(key, entry) {
|
|
27404
|
+
const limit = isRemoteMode() ? boardCachePolicy.remote : boardCachePolicy.stdio;
|
|
27405
|
+
boardStore.delete(key);
|
|
27406
|
+
if (entry.bytes > limit.bytes) return;
|
|
27407
|
+
boardStore.set(key, entry);
|
|
27408
|
+
let total = 0;
|
|
27409
|
+
for (const e of boardStore.values()) total += e.bytes;
|
|
27410
|
+
for (const [k, e] of boardStore) {
|
|
27411
|
+
if (boardStore.size <= limit.entries && total <= limit.bytes) break;
|
|
27412
|
+
boardStore.delete(k);
|
|
27413
|
+
total -= e.bytes;
|
|
27414
|
+
}
|
|
27415
|
+
}
|
|
27416
|
+
function touchEntry(key, entry) {
|
|
27417
|
+
boardStore.delete(key);
|
|
27418
|
+
boardStore.set(key, entry);
|
|
27419
|
+
}
|
|
27420
|
+
function applyDelta(snap, envelopes) {
|
|
27421
|
+
let doc = snap.doc;
|
|
27422
|
+
let seq = snap.seq;
|
|
27423
|
+
try {
|
|
27424
|
+
for (const env of envelopes) {
|
|
27425
|
+
if (env.seq <= seq) continue;
|
|
27426
|
+
if (!knownOp(env.op)) return null;
|
|
27427
|
+
doc = (0, import_canvas_core.applyConfirmed)(doc, env);
|
|
27428
|
+
seq = env.seq;
|
|
27429
|
+
}
|
|
27430
|
+
} catch {
|
|
27431
|
+
return null;
|
|
27432
|
+
}
|
|
27433
|
+
return seq === snap.seq ? snap : { ...snap, doc, seq, title: doc.title };
|
|
27434
|
+
}
|
|
27435
|
+
function knownOp(op) {
|
|
27436
|
+
if (!Object.hasOwn(import_canvas_core.OPS, op.type)) return false;
|
|
27437
|
+
return op.type !== "batch" || Array.isArray(op.ops) && op.ops.every((o) => knownOp(o));
|
|
27438
|
+
}
|
|
24586
27439
|
var CanvasApi = class {
|
|
24587
27440
|
constructor(client, cfg) {
|
|
24588
27441
|
this.client = client;
|
|
@@ -24612,11 +27465,87 @@ var CanvasApi = class {
|
|
|
24612
27465
|
createBoard(body2) {
|
|
24613
27466
|
return this.req("POST", "/boards", { body: body2 });
|
|
24614
27467
|
}
|
|
24615
|
-
|
|
24616
|
-
|
|
27468
|
+
cacheKey(boardId4) {
|
|
27469
|
+
const who2 = createHash("sha256").update(this.cfg.token).digest("hex").slice(0, 16);
|
|
27470
|
+
return `${this.cfg.canvasBase}|${who2}|${boardId4}`;
|
|
27471
|
+
}
|
|
27472
|
+
/** Board pelo cache: delta quando dá, inteiro com If-None-Match quando não. Um GET em voo por board. */
|
|
27473
|
+
async snapshot(boardId4, opts = {}) {
|
|
27474
|
+
const key = this.cacheKey(boardId4);
|
|
27475
|
+
const entry = boardStore.get(key);
|
|
27476
|
+
if (entry && !opts.fresh && !opts.runs && boardCachePolicy.now() - entry.checkedAt < boardCachePolicy.minIntervalMs) {
|
|
27477
|
+
touchEntry(key, entry);
|
|
27478
|
+
return entry.snap;
|
|
27479
|
+
}
|
|
27480
|
+
const loadKey = opts.runs ? `${key}|runs` : key;
|
|
27481
|
+
const inFlight = boardLoads.get(loadKey);
|
|
27482
|
+
if (inFlight) return inFlight;
|
|
27483
|
+
const load = this.load(boardId4, key, !!opts.runs).finally(() => boardLoads.delete(loadKey));
|
|
27484
|
+
boardLoads.set(loadKey, load);
|
|
27485
|
+
return load;
|
|
27486
|
+
}
|
|
27487
|
+
async load(boardId4, key, needRuns) {
|
|
27488
|
+
const entry = boardStore.get(key);
|
|
27489
|
+
if (entry && !needRuns && this.coreVersion === PINNED_CORE_VERSION) {
|
|
27490
|
+
const envelopes = await this.fetchOpsAfter(boardId4, entry.snap.seq);
|
|
27491
|
+
const next = envelopes && applyDelta(entry.snap, envelopes);
|
|
27492
|
+
if (next) {
|
|
27493
|
+
let recent = entry.recent;
|
|
27494
|
+
let logFrom = entry.logFrom;
|
|
27495
|
+
if (next !== entry.snap) {
|
|
27496
|
+
recent = [...recent, ...envelopes.filter((e) => e.seq > entry.snap.seq)];
|
|
27497
|
+
if (recent.length > boardCachePolicy.recentMax) {
|
|
27498
|
+
recent = recent.slice(-boardCachePolicy.recentMax);
|
|
27499
|
+
logFrom = recent[0].seq - 1;
|
|
27500
|
+
}
|
|
27501
|
+
}
|
|
27502
|
+
const delta = envelopes.reduce((sum, e) => sum + JSON.stringify(e.op).length, 0);
|
|
27503
|
+
storeEntry(key, {
|
|
27504
|
+
snap: next,
|
|
27505
|
+
// O ETag cobre o snapshot inteiro: se o seq andou, o guardado não vale mais.
|
|
27506
|
+
etag: next === entry.snap ? entry.etag : null,
|
|
27507
|
+
bytes: entry.bytes + delta,
|
|
27508
|
+
checkedAt: boardCachePolicy.now(),
|
|
27509
|
+
recent,
|
|
27510
|
+
logFrom
|
|
27511
|
+
});
|
|
27512
|
+
return next;
|
|
27513
|
+
}
|
|
27514
|
+
}
|
|
27515
|
+
const res = await this.client.requestMeta("GET", `/boards/${boardId4}`, {
|
|
27516
|
+
base: this.cfg.canvasBase,
|
|
27517
|
+
headers: entry?.etag ? { "If-None-Match": entry.etag } : void 0
|
|
27518
|
+
});
|
|
27519
|
+
if (res.status === 304 && entry) {
|
|
27520
|
+
storeEntry(key, { ...entry, checkedAt: boardCachePolicy.now() });
|
|
27521
|
+
return entry.snap;
|
|
27522
|
+
}
|
|
27523
|
+
if (!res.data) throw new ApiError(502, "O servidor do Canvas respondeu sem o board.");
|
|
27524
|
+
storeEntry(key, {
|
|
27525
|
+
snap: res.data,
|
|
27526
|
+
etag: res.etag,
|
|
27527
|
+
bytes: res.bytes,
|
|
27528
|
+
checkedAt: boardCachePolicy.now(),
|
|
27529
|
+
recent: [],
|
|
27530
|
+
logFrom: res.data.seq
|
|
27531
|
+
});
|
|
27532
|
+
return res.data;
|
|
24617
27533
|
}
|
|
24618
|
-
/**
|
|
27534
|
+
/** Esquece o board deste token (ex.: o servidor recusou por papel e o cache pode estar velho). */
|
|
27535
|
+
forget(boardId4) {
|
|
27536
|
+
boardStore.delete(this.cacheKey(boardId4));
|
|
27537
|
+
}
|
|
27538
|
+
/**
|
|
27539
|
+
* O que mudou depois de `after`. Vem do cache quando a última leitura cobre esse trecho (o
|
|
27540
|
+
* edit() acabou de reler), senão da rede. `null` quando o servidor manda reler a foto (410).
|
|
27541
|
+
*/
|
|
24619
27542
|
async opsAfter(boardId4, after) {
|
|
27543
|
+
const entry = boardStore.get(this.cacheKey(boardId4));
|
|
27544
|
+
if (entry && after >= entry.logFrom && after <= entry.snap.seq) return entry.recent.filter((e) => e.seq > after);
|
|
27545
|
+
return this.fetchOpsAfter(boardId4, after);
|
|
27546
|
+
}
|
|
27547
|
+
/** Replay depois de `after`. `null` quando o servidor manda reler a foto (410). */
|
|
27548
|
+
async fetchOpsAfter(boardId4, after) {
|
|
24620
27549
|
try {
|
|
24621
27550
|
const { envelopes } = await this.req("GET", `/boards/${boardId4}/ops`, {
|
|
24622
27551
|
query: { after }
|
|
@@ -24628,9 +27557,14 @@ var CanvasApi = class {
|
|
|
24628
27557
|
}
|
|
24629
27558
|
}
|
|
24630
27559
|
async commit(boardId4, ops) {
|
|
24631
|
-
const send = () =>
|
|
24632
|
-
|
|
24633
|
-
|
|
27560
|
+
const send = () => (
|
|
27561
|
+
// Reenvio seguro: o servidor ignora operação com id que já entrou.
|
|
27562
|
+
this.client.request("POST", `/boards/${boardId4}/ops`, {
|
|
27563
|
+
base: this.cfg.canvasBase,
|
|
27564
|
+
body: { coreVersion: this.coreVersion, ops },
|
|
27565
|
+
retry: true
|
|
27566
|
+
})
|
|
27567
|
+
);
|
|
24634
27568
|
try {
|
|
24635
27569
|
return await send();
|
|
24636
27570
|
} catch (e) {
|
|
@@ -26513,7 +29447,12 @@ ${payload(u)}`
|
|
|
26513
29447
|
// src/tools/canvas-run.ts
|
|
26514
29448
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
26515
29449
|
var MAX_REMEMBERED = 50;
|
|
26516
|
-
var acceptedPacing = { repeats:
|
|
29450
|
+
var acceptedPacing = { repeats: 8, pauseMs: 2e3 };
|
|
29451
|
+
var statusPacing = {
|
|
29452
|
+
minIntervalMs: 3e3,
|
|
29453
|
+
now: () => Date.now(),
|
|
29454
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
|
|
29455
|
+
};
|
|
26517
29456
|
var sleep3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
26518
29457
|
var seconds = (ms) => `${new Intl.NumberFormat("pt-BR", { maximumFractionDigits: 1 }).format(ms / 1e3)} s`;
|
|
26519
29458
|
function timingsLine(t) {
|
|
@@ -26568,6 +29507,7 @@ function targetOf(args) {
|
|
|
26568
29507
|
}
|
|
26569
29508
|
function registerCanvasRunTools(server, api, run) {
|
|
26570
29509
|
const remembered = /* @__PURE__ */ new Map();
|
|
29510
|
+
const lastStatusAt = /* @__PURE__ */ new Map();
|
|
26571
29511
|
const remember = (requestId, entry) => {
|
|
26572
29512
|
remembered.delete(requestId);
|
|
26573
29513
|
remembered.set(requestId, entry);
|
|
@@ -26715,6 +29655,11 @@ function registerCanvasRunTools(server, api, run) {
|
|
|
26715
29655
|
},
|
|
26716
29656
|
async ({ board_id, request_id, node_ids }) => run(async () => {
|
|
26717
29657
|
const requestId = request_id.toLowerCase();
|
|
29658
|
+
const since = statusPacing.now() - (lastStatusAt.get(requestId) ?? -Infinity);
|
|
29659
|
+
if (since < statusPacing.minIntervalMs) await statusPacing.sleep(statusPacing.minIntervalMs - since);
|
|
29660
|
+
lastStatusAt.delete(requestId);
|
|
29661
|
+
lastStatusAt.set(requestId, statusPacing.now());
|
|
29662
|
+
while (lastStatusAt.size > MAX_REMEMBERED) lastStatusAt.delete(lastStatusAt.keys().next().value);
|
|
26718
29663
|
let why = "";
|
|
26719
29664
|
try {
|
|
26720
29665
|
const status = await api.runStatus(board_id, requestId);
|
|
@@ -26731,7 +29676,7 @@ function registerCanvasRunTools(server, api, run) {
|
|
|
26731
29676
|
}
|
|
26732
29677
|
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)` : "";
|
|
26733
29678
|
return `${why} Pelo estado de execu\xE7\xE3o do board${partial2}:
|
|
26734
|
-
${fromRuns(await api.snapshot(board_id), ids)}`;
|
|
29679
|
+
${fromRuns(await api.snapshot(board_id, { runs: true }), ids)}`;
|
|
26735
29680
|
})
|
|
26736
29681
|
);
|
|
26737
29682
|
}
|
|
@@ -27153,6 +30098,17 @@ function registerCanvasTools(server, client, cfg) {
|
|
|
27153
30098
|
}
|
|
27154
30099
|
return errorResult(apiErrorToUserMessage(e));
|
|
27155
30100
|
}
|
|
30101
|
+
async function commitOps(id, envs) {
|
|
30102
|
+
try {
|
|
30103
|
+
return await api.commit(id, envs);
|
|
30104
|
+
} catch (e) {
|
|
30105
|
+
if (!(e instanceof ApiError) || e.httpStatus !== 403) throw e;
|
|
30106
|
+
api.forget(id);
|
|
30107
|
+
const again = await api.snapshot(id, { runs: true }).catch(() => null);
|
|
30108
|
+
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.");
|
|
30109
|
+
throw e;
|
|
30110
|
+
}
|
|
30111
|
+
}
|
|
27156
30112
|
async function run(fn) {
|
|
27157
30113
|
try {
|
|
27158
30114
|
return textResult(await fn());
|
|
@@ -27165,7 +30121,7 @@ function registerCanvasTools(server, client, cfg) {
|
|
|
27165
30121
|
if (last === void 0 && !opts.layoutOnly) {
|
|
27166
30122
|
throw new CanvasToolError("Leia o board com canvas_read_board antes de editar (a leitura vale para a sess\xE3o).");
|
|
27167
30123
|
}
|
|
27168
|
-
const snap = await api.snapshot(id);
|
|
30124
|
+
const snap = await api.snapshot(id, { fresh: true });
|
|
27169
30125
|
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.");
|
|
27170
30126
|
const doc = snap.doc;
|
|
27171
30127
|
const { ops, done, targets } = await build2(doc, snap);
|
|
@@ -27200,7 +30156,7 @@ Aviso: ${changesSince(theirs, doc)}.`;
|
|
|
27200
30156
|
const env = envelope(id, batchOf(ops), await api.me());
|
|
27201
30157
|
const bad = checkEnvelope(env);
|
|
27202
30158
|
if (bad) throw new CanvasToolError(`Edi\xE7\xE3o recusada antes de enviar: ${bad}.`);
|
|
27203
|
-
const res = await
|
|
30159
|
+
const res = await commitOps(id, [env]);
|
|
27204
30160
|
const outcome = res.outcomes.find((o) => o.opId === env.id);
|
|
27205
30161
|
if (!outcome || "rejected" in outcome) {
|
|
27206
30162
|
if (!opts.layoutOnly) seen.delete(id);
|
|
@@ -27228,7 +30184,7 @@ Aviso: ${changesSince(theirs, doc)}.`;
|
|
|
27228
30184
|
const outcomes = /* @__PURE__ */ new Map();
|
|
27229
30185
|
let last = null;
|
|
27230
30186
|
for (let i = 0; i < envs.length; i += MAX_ENVELOPES_PER_COMMIT) {
|
|
27231
|
-
const res = await
|
|
30187
|
+
const res = await commitOps(id, envs.slice(i, i + MAX_ENVELOPES_PER_COMMIT));
|
|
27232
30188
|
for (const o of res.outcomes) outcomes.set(o.opId, o);
|
|
27233
30189
|
last = res.seq;
|
|
27234
30190
|
}
|
|
@@ -27441,7 +30397,7 @@ ${lines.join("\n")}${note}`;
|
|
|
27441
30397
|
const from = Math.min(offset ?? 0, total);
|
|
27442
30398
|
const size = max_chars ?? 4e4;
|
|
27443
30399
|
const to = Math.min(from + size, total);
|
|
27444
|
-
const hash =
|
|
30400
|
+
const hash = createHash2("sha256").update(json2).digest("hex").slice(0, 12);
|
|
27445
30401
|
const where = `data${segments.length ? `.${segments.join(".")}` : ""}`;
|
|
27446
30402
|
const at = readMeasured(node)?.at;
|
|
27447
30403
|
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}`;
|
|
@@ -27890,7 +30846,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
|
|
|
27890
30846
|
import { createRequire } from "module";
|
|
27891
30847
|
var require2 = createRequire(import.meta.url);
|
|
27892
30848
|
function readVersion() {
|
|
27893
|
-
if ("0.
|
|
30849
|
+
if ("0.45.0") return "0.45.0";
|
|
27894
30850
|
try {
|
|
27895
30851
|
const pkg = require2("../package.json");
|
|
27896
30852
|
return pkg.version ?? "0.0.0-unknown";
|