beplus-mcp 0.43.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.
@@ -6884,6 +6884,2721 @@ var require_dist = __commonJS({
6884
6884
  }
6885
6885
  });
6886
6886
 
6887
+ // src/vendor/canvas-core/index.cjs
6888
+ var require_canvas_core = __commonJS({
6889
+ "src/vendor/canvas-core/index.cjs"(exports, module) {
6890
+ "use strict";
6891
+ var __defProp2 = Object.defineProperty;
6892
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
6893
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
6894
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
6895
+ var __export2 = (target, all) => {
6896
+ for (var name in all)
6897
+ __defProp2(target, name, { get: all[name], enumerable: true });
6898
+ };
6899
+ var __copyProps2 = (to, from, except, desc) => {
6900
+ if (from && typeof from === "object" || typeof from === "function") {
6901
+ for (let key of __getOwnPropNames2(from))
6902
+ if (!__hasOwnProp2.call(to, key) && key !== except)
6903
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
6904
+ }
6905
+ return to;
6906
+ };
6907
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
6908
+ var index_exports = {};
6909
+ __export2(index_exports, {
6910
+ BOARD_FIELDS: () => BOARD_FIELDS,
6911
+ BoardStore: () => BoardStore,
6912
+ DEFAULT_MAX_PER_COLUMN: () => DEFAULT_MAX_PER_COLUMN,
6913
+ DEFAULT_PLACEMENT_GAP: () => DEFAULT_PLACEMENT_GAP,
6914
+ DEFAULT_SHAPE_SIZE: () => DEFAULT_SHAPE_SIZE,
6915
+ DEFAULT_TIDY_GAP_X: () => DEFAULT_TIDY_GAP_X,
6916
+ DEFAULT_TIDY_GAP_Y: () => DEFAULT_TIDY_GAP_Y,
6917
+ DEFAULT_TIDY_SWEEPS: () => DEFAULT_TIDY_SWEEPS,
6918
+ Draft: () => Draft,
6919
+ EMPTY_INTERACTION: () => EMPTY_INTERACTION,
6920
+ FORBIDDEN_PATH_SEGMENTS: () => FORBIDDEN_PATH_SEGMENTS,
6921
+ HISTORY_LIMIT: () => HISTORY_LIMIT,
6922
+ HISTORY_MAX_BYTES: () => HISTORY_MAX_BYTES,
6923
+ HistoryStack: () => HistoryStack,
6924
+ InvalidBoardSetError: () => InvalidBoardSetError,
6925
+ InvalidPathError: () => InvalidPathError,
6926
+ MAX_OP_BYTES: () => MAX_OP_BYTES2,
6927
+ MAX_REPLAY: () => MAX_REPLAY,
6928
+ MIGRATIONS: () => MIGRATIONS,
6929
+ OPS: () => OPS2,
6930
+ OpSyncClient: () => OpSyncClient,
6931
+ OpTooLargeError: () => OpTooLargeError2,
6932
+ SCHEMA_VERSION: () => SCHEMA_VERSION2,
6933
+ SHAPE_NODE_TYPE: () => SHAPE_NODE_TYPE,
6934
+ anyPathCrosses: () => anyPathCrosses,
6935
+ applyBoardSet: () => applyBoardSet,
6936
+ applyConfirmed: () => applyConfirmed2,
6937
+ applyEnvelopes: () => applyEnvelopes,
6938
+ applyOp: () => applyOp,
6939
+ applyOps: () => applyOps,
6940
+ assertBoardSet: () => assertBoardSet,
6941
+ assertOpEnvelopeFits: () => assertOpEnvelopeFits,
6942
+ batchOf: () => batchOf2,
6943
+ boundsOf: () => boundsOf,
6944
+ captureOf: () => captureOf,
6945
+ createCloneCounts: () => createCloneCounts,
6946
+ createEmptyBoard: () => createEmptyBoard,
6947
+ createOpIdGenerator: () => createOpIdGenerator,
6948
+ createShapeNode: () => createShapeNode,
6949
+ defaultScheduler: () => defaultScheduler,
6950
+ estimateOpBytes: () => estimateOpBytes,
6951
+ fanOutPositions: () => fanOutPositions,
6952
+ findFreeSpot: () => findFreeSpot,
6953
+ getPath: () => getPath,
6954
+ hasPath: () => hasPath,
6955
+ invert: () => invert,
6956
+ invertBoardSet: () => invertBoardSet,
6957
+ invertEdgeAdd: () => invertEdgeAdd,
6958
+ invertEdgeRemove: () => invertEdgeRemove,
6959
+ invertHistoryAppend: () => invertHistoryAppend,
6960
+ invertHistoryRemove: () => invertHistoryRemove,
6961
+ invertNodeAdd: () => invertNodeAdd,
6962
+ invertNodeRemove: () => invertNodeRemove,
6963
+ invertNodeSet: () => invertNodeSet,
6964
+ invertResultSet: () => invertResultSet,
6965
+ isLocalEnvelope: () => isLocalEnvelope,
6966
+ isPropValue: () => isPropValue,
6967
+ migrate: () => migrate,
6968
+ moveOps: () => moveOps,
6969
+ newOpId: () => newOpId,
6970
+ opEnvelopeBytes: () => opEnvelopeBytes,
6971
+ parsePath: () => parsePath,
6972
+ pathsCross: () => pathsCross,
6973
+ placeWithoutOverlap: () => placeWithoutOverlap,
6974
+ propValue: () => propValue,
6975
+ rectOf: () => rectOf2,
6976
+ rectsCollide: () => rectsCollide,
6977
+ reduce: () => reduce,
6978
+ removeNode: () => removeNode,
6979
+ sameBox: () => sameBox,
6980
+ sameNodeIds: () => sameNodeIds,
6981
+ setPath: () => setPath,
6982
+ shallowestMissingPath: () => shallowestMissingPath,
6983
+ tidyUp: () => tidyUp,
6984
+ tidyUpOps: () => tidyUpOps,
6985
+ touchedPaths: () => touchedPaths,
6986
+ trackCapture: () => trackCapture,
6987
+ tryApplyEnvelope: () => tryApplyEnvelope,
6988
+ tryApplyOp: () => tryApplyOp,
6989
+ unsetPath: () => unsetPath,
6990
+ unsetPropValue: () => unsetPropValue,
6991
+ utf8ByteLength: () => utf8ByteLength,
6992
+ walkBatch: () => walkBatch,
6993
+ writeKey: () => writeKey
6994
+ });
6995
+ module.exports = __toCommonJS(index_exports);
6996
+ var SCHEMA_VERSION2 = 1;
6997
+ var SHAPE_NODE_TYPE = "shape";
6998
+ var DEFAULT_SHAPE_SIZE = { w: 180, h: 120 };
6999
+ function randomUuidV4() {
7000
+ let out = "";
7001
+ for (let i = 0; i < 36; i += 1) {
7002
+ if (i === 8 || i === 13 || i === 18 || i === 23) {
7003
+ out += "-";
7004
+ continue;
7005
+ }
7006
+ if (i === 14) {
7007
+ out += "4";
7008
+ continue;
7009
+ }
7010
+ const value = Math.floor(Math.random() * 16);
7011
+ out += (i === 19 ? value & 3 | 8 : value).toString(16);
7012
+ }
7013
+ return out;
7014
+ }
7015
+ function createEmptyBoard(init = {}) {
7016
+ const newId = init.newId ?? randomUuidV4;
7017
+ const timestamp = (init.now ?? Date.now)();
7018
+ return {
7019
+ id: init.id ?? newId(),
7020
+ schemaVersion: SCHEMA_VERSION2,
7021
+ title: init.title ?? "Board sem t\xEDtulo",
7022
+ ownerId: init.ownerId ?? "",
7023
+ folderId: init.folderId ?? null,
7024
+ version: 0,
7025
+ nodes: {},
7026
+ edges: {},
7027
+ results: {},
7028
+ nodeHistory: {},
7029
+ createdAt: timestamp,
7030
+ updatedAt: timestamp
7031
+ };
7032
+ }
7033
+ function createShapeNode(shape, init = {}) {
7034
+ const newId = init.newId ?? randomUuidV4;
7035
+ const timestamp = (init.now ?? Date.now)();
7036
+ return {
7037
+ id: init.id ?? newId(),
7038
+ type: SHAPE_NODE_TYPE,
7039
+ position: init.position ?? { x: 0, y: 0 },
7040
+ size: init.size ?? { w: DEFAULT_SHAPE_SIZE.w, h: DEFAULT_SHAPE_SIZE.h },
7041
+ zIndex: init.zIndex ?? 0,
7042
+ parentId: init.parentId ?? null,
7043
+ data: { shape },
7044
+ createdBy: init.createdBy ?? null,
7045
+ createdAt: timestamp,
7046
+ updatedAt: timestamp
7047
+ };
7048
+ }
7049
+ var MIGRATIONS = {};
7050
+ var MAX_MIGRATION_STEPS = 16;
7051
+ function isRecord2(value) {
7052
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7053
+ }
7054
+ function isFiniteNumber3(value) {
7055
+ return typeof value === "number" && Number.isFinite(value);
7056
+ }
7057
+ function isStringOrNull2(value) {
7058
+ return value === null || typeof value === "string";
7059
+ }
7060
+ function isSeq(value) {
7061
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
7062
+ }
7063
+ function hasOnlyKeys2(record2, keys) {
7064
+ return Object.keys(record2).every((key) => keys.includes(key));
7065
+ }
7066
+ function isJson2(value) {
7067
+ if (value === null) return true;
7068
+ const kind = typeof value;
7069
+ if (kind === "boolean" || kind === "string") return true;
7070
+ if (kind === "number") return Number.isFinite(value);
7071
+ if (Array.isArray(value)) return value.every(isJson2);
7072
+ if (isRecord2(value)) return Object.values(value).every(isJson2);
7073
+ return false;
7074
+ }
7075
+ function isJsonBag2(value) {
7076
+ return isRecord2(value) && Object.values(value).every(isJson2);
7077
+ }
7078
+ function isStringMap(value) {
7079
+ return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
7080
+ }
7081
+ function isPoint2(value) {
7082
+ return isRecord2(value) && hasOnlyKeys2(value, ["x", "y"]) && isFiniteNumber3(value["x"]) && isFiniteNumber3(value["y"]);
7083
+ }
7084
+ function isSize2(value) {
7085
+ return isRecord2(value) && hasOnlyKeys2(value, ["w", "h"]) && isFiniteNumber3(value["w"]) && isFiniteNumber3(value["h"]);
7086
+ }
7087
+ var NODE_KEYS2 = [
7088
+ "id",
7089
+ "type",
7090
+ "position",
7091
+ "size",
7092
+ "zIndex",
7093
+ "parentId",
7094
+ "data",
7095
+ "createdBy",
7096
+ "createdAt",
7097
+ "updatedAt"
7098
+ ];
7099
+ var EDGE_KEYS2 = [
7100
+ "id",
7101
+ "source",
7102
+ "sourcePort",
7103
+ "target",
7104
+ "targetPort",
7105
+ "data",
7106
+ "createdBy",
7107
+ "createdAt"
7108
+ ];
7109
+ var RESULT_KEYS = [
7110
+ "id",
7111
+ "nodeId",
7112
+ "runId",
7113
+ "generationId",
7114
+ "kind",
7115
+ "url",
7116
+ "lodUrls",
7117
+ "status",
7118
+ "spec",
7119
+ "costDiamonds",
7120
+ "error",
7121
+ "createdAt"
7122
+ ];
7123
+ var DOC_KEYS = [
7124
+ "id",
7125
+ "schemaVersion",
7126
+ "title",
7127
+ "ownerId",
7128
+ "folderId",
7129
+ "version",
7130
+ "nodes",
7131
+ "edges",
7132
+ "results",
7133
+ "nodeHistory",
7134
+ "createdAt",
7135
+ "updatedAt",
7136
+ "meta"
7137
+ ];
7138
+ var META_KEYS = ["guide", "ialab", "assetUrls"];
7139
+ function isValidMeta(value) {
7140
+ if (value === void 0) return true;
7141
+ return isRecord2(value) && hasOnlyKeys2(value, META_KEYS) && (value["guide"] === void 0 || isStringOrNull2(value["guide"])) && (value["ialab"] === void 0 || value["ialab"] === null || isJsonBag2(value["ialab"])) && (value["assetUrls"] === void 0 || isStringMap(value["assetUrls"]));
7142
+ }
7143
+ var RESULT_KINDS = ["image", "video", "audio", "text"];
7144
+ var RESULT_STATUSES = ["pending", "running", "done", "failed", "cancelled"];
7145
+ function isValidNode2(key, value) {
7146
+ return isRecord2(value) && hasOnlyKeys2(value, NODE_KEYS2) && value["id"] === key && typeof value["type"] === "string" && isPoint2(value["position"]) && isSize2(value["size"]) && isFiniteNumber3(value["zIndex"]) && isStringOrNull2(value["parentId"]) && isJsonBag2(value["data"]) && isStringOrNull2(value["createdBy"]) && isFiniteNumber3(value["createdAt"]) && isFiniteNumber3(value["updatedAt"]);
7147
+ }
7148
+ function isValidEdge2(key, value) {
7149
+ return isRecord2(value) && hasOnlyKeys2(value, EDGE_KEYS2) && value["id"] === key && typeof value["source"] === "string" && typeof value["sourcePort"] === "string" && typeof value["target"] === "string" && typeof value["targetPort"] === "string" && isJsonBag2(value["data"]) && isStringOrNull2(value["createdBy"]) && isFiniteNumber3(value["createdAt"]);
7150
+ }
7151
+ function isValidResult(key, value) {
7152
+ return isRecord2(value) && hasOnlyKeys2(value, RESULT_KEYS) && value["id"] === key && typeof value["nodeId"] === "string" && isStringOrNull2(value["runId"]) && isStringOrNull2(value["generationId"]) && typeof value["kind"] === "string" && RESULT_KINDS.includes(value["kind"]) && isStringOrNull2(value["url"]) && isStringMap(value["lodUrls"]) && typeof value["status"] === "string" && RESULT_STATUSES.includes(value["status"]) && isJsonBag2(value["spec"]) && (value["costDiamonds"] === null || isFiniteNumber3(value["costDiamonds"])) && isStringOrNull2(value["error"]) && isFiniteNumber3(value["createdAt"]);
7153
+ }
7154
+ function isValidHistory(value) {
7155
+ return Array.isArray(value) && value.every((resultId) => typeof resultId === "string");
7156
+ }
7157
+ function normalizeHistory(history) {
7158
+ for (const [nodeId3, list] of Object.entries(history)) {
7159
+ if (Array.isArray(list) && list.length === 0) delete history[nodeId3];
7160
+ }
7161
+ }
7162
+ function everyEntry(value, check2) {
7163
+ return isRecord2(value) && Object.entries(value).every(([key, entry]) => check2(key, entry));
7164
+ }
7165
+ function upgrade(raw) {
7166
+ let current = raw;
7167
+ for (let step2 = 0; step2 <= MAX_MIGRATION_STEPS; step2 += 1) {
7168
+ if (!isRecord2(current)) return null;
7169
+ const version2 = current["schemaVersion"];
7170
+ if (typeof version2 !== "number" || !Number.isInteger(version2)) return null;
7171
+ if (version2 === SCHEMA_VERSION2) return current;
7172
+ const migration = MIGRATIONS[version2];
7173
+ if (migration === void 0) return null;
7174
+ current = migration(current);
7175
+ }
7176
+ return null;
7177
+ }
7178
+ function migrate(raw) {
7179
+ try {
7180
+ return read(raw);
7181
+ } catch {
7182
+ return null;
7183
+ }
7184
+ }
7185
+ function read(raw) {
7186
+ const upgraded = upgrade(raw);
7187
+ if (!isRecord2(upgraded)) return null;
7188
+ const ok = hasOnlyKeys2(upgraded, DOC_KEYS) && typeof upgraded["id"] === "string" && upgraded["schemaVersion"] === SCHEMA_VERSION2 && typeof upgraded["title"] === "string" && typeof upgraded["ownerId"] === "string" && isStringOrNull2(upgraded["folderId"]) && isSeq(upgraded["version"]) && everyEntry(upgraded["nodes"], isValidNode2) && everyEntry(upgraded["edges"], isValidEdge2) && everyEntry(upgraded["results"], isValidResult) && everyEntry(upgraded["nodeHistory"], (_key, entry) => isValidHistory(entry)) && isFiniteNumber3(upgraded["createdAt"]) && isFiniteNumber3(upgraded["updatedAt"]) && isValidMeta(upgraded["meta"]);
7189
+ if (!ok) return null;
7190
+ if (isRecord2(upgraded["meta"]) && Object.keys(upgraded["meta"]).length === 0) {
7191
+ delete upgraded["meta"];
7192
+ }
7193
+ normalizeHistory(upgraded["nodeHistory"]);
7194
+ return upgraded;
7195
+ }
7196
+ function propValue(value) {
7197
+ return { kind: "value", value };
7198
+ }
7199
+ function unsetPropValue() {
7200
+ return { kind: "unset" };
7201
+ }
7202
+ function isJson22(root) {
7203
+ const pending = [{ visit: root }];
7204
+ const open3 = /* @__PURE__ */ new Set();
7205
+ for (let step2 = pending.pop(); step2 !== void 0; step2 = pending.pop()) {
7206
+ if ("close" in step2) {
7207
+ open3.delete(step2.close);
7208
+ continue;
7209
+ }
7210
+ const value = step2.visit;
7211
+ if (value === null) continue;
7212
+ const kind = typeof value;
7213
+ if (kind === "boolean" || kind === "string") continue;
7214
+ if (kind === "number") {
7215
+ if (!Number.isFinite(value)) return false;
7216
+ continue;
7217
+ }
7218
+ if (kind !== "object") return false;
7219
+ const node = value;
7220
+ if (open3.has(node)) return false;
7221
+ open3.add(node);
7222
+ pending.push({ close: node });
7223
+ const children = Array.isArray(node) ? node : Object.values(node);
7224
+ for (const item of children) pending.push({ visit: item });
7225
+ }
7226
+ return true;
7227
+ }
7228
+ function isPropValue(candidate) {
7229
+ if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) return false;
7230
+ const record2 = candidate;
7231
+ const keys = Object.keys(record2);
7232
+ if (record2["kind"] === "unset") return keys.length === 1;
7233
+ if (record2["kind"] !== "value") return false;
7234
+ if (keys.length !== 2 || !Object.hasOwn(record2, "value")) return false;
7235
+ return isJson22(record2["value"]);
7236
+ }
7237
+ var FORBIDDEN_PATH_SEGMENTS = ["__proto__", "constructor", "prototype"];
7238
+ var InvalidPathError = class extends Error {
7239
+ /** O caminho recusado, já como veio da operação. */
7240
+ path;
7241
+ constructor(path, reason) {
7242
+ super(`Caminho inv\xE1lido em node.set: ${JSON.stringify(path)} \u2014 ${reason}`);
7243
+ this.name = "InvalidPathError";
7244
+ this.path = path;
7245
+ }
7246
+ };
7247
+ function asRecord(value) {
7248
+ return value;
7249
+ }
7250
+ function isPlainRecord(value) {
7251
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7252
+ }
7253
+ function parsePath(path) {
7254
+ if (path.length === 0) throw new InvalidPathError(path, "caminho vazio");
7255
+ const segments = path.split(".");
7256
+ for (const segment of segments) {
7257
+ if (segment.length === 0) throw new InvalidPathError(path, "segmento vazio entre pontos");
7258
+ if (FORBIDDEN_PATH_SEGMENTS.includes(segment)) {
7259
+ throw new InvalidPathError(path, `segmento proibido: ${segment}`);
7260
+ }
7261
+ }
7262
+ return segments;
7263
+ }
7264
+ function splitLeaf(path) {
7265
+ const segments = parsePath(path);
7266
+ const leaf = segments[segments.length - 1];
7267
+ if (leaf === void 0) throw new InvalidPathError(path, "caminho sem folha");
7268
+ return { parents: segments.slice(0, -1), leaf };
7269
+ }
7270
+ function getPath(target, path) {
7271
+ const segments = parsePath(path);
7272
+ let cursor = target;
7273
+ for (const segment of segments) {
7274
+ if (!isPlainRecord(cursor) || !Object.hasOwn(cursor, segment)) return void 0;
7275
+ cursor = cursor[segment];
7276
+ }
7277
+ return cursor;
7278
+ }
7279
+ function hasPath(target, path) {
7280
+ const segments = parsePath(path);
7281
+ let cursor = target;
7282
+ for (const segment of segments) {
7283
+ if (!isPlainRecord(cursor) || !Object.hasOwn(cursor, segment)) return false;
7284
+ cursor = cursor[segment];
7285
+ }
7286
+ return true;
7287
+ }
7288
+ function setPath(target, path, value) {
7289
+ const { parents, leaf } = splitLeaf(path);
7290
+ const root = { ...asRecord(target) };
7291
+ let cursor = root;
7292
+ for (const segment of parents) {
7293
+ const current = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
7294
+ if (current === void 0) {
7295
+ const created = {};
7296
+ writeKey(cursor, segment, created);
7297
+ cursor = created;
7298
+ continue;
7299
+ }
7300
+ if (!isPlainRecord(current)) {
7301
+ throw new InvalidPathError(path, `o n\xEDvel ${segment} existe e n\xE3o \xE9 objeto`);
7302
+ }
7303
+ const cloned = { ...current };
7304
+ writeKey(cursor, segment, cloned);
7305
+ cursor = cloned;
7306
+ }
7307
+ writeKey(cursor, leaf, value);
7308
+ return root;
7309
+ }
7310
+ function unsetPath(target, path) {
7311
+ if (!hasPath(target, path)) return target;
7312
+ const { parents, leaf } = splitLeaf(path);
7313
+ const root = { ...asRecord(target) };
7314
+ let cursor = root;
7315
+ for (const segment of parents) {
7316
+ const current = cursor[segment];
7317
+ if (!isPlainRecord(current))
7318
+ throw new InvalidPathError(path, `o n\xEDvel ${segment} n\xE3o \xE9 objeto`);
7319
+ const cloned = { ...current };
7320
+ writeKey(cursor, segment, cloned);
7321
+ cursor = cloned;
7322
+ }
7323
+ delete cursor[leaf];
7324
+ return root;
7325
+ }
7326
+ function writeKey(record2, key, value) {
7327
+ if (key === "__proto__") {
7328
+ Object.defineProperty(record2, key, {
7329
+ value,
7330
+ writable: true,
7331
+ enumerable: true,
7332
+ configurable: true
7333
+ });
7334
+ return;
7335
+ }
7336
+ record2[key] = value;
7337
+ }
7338
+ function createCloneCounts() {
7339
+ return { doc: 0, nodes: 0, edges: 0, results: 0, nodeHistory: 0, nodeEntry: 0, historyEntry: 0 };
7340
+ }
7341
+ var Draft = class {
7342
+ base;
7343
+ counts;
7344
+ nodes;
7345
+ edges;
7346
+ results;
7347
+ nodeHistory;
7348
+ nodesOwned = false;
7349
+ edgesOwned = false;
7350
+ resultsOwned = false;
7351
+ nodeHistoryOwned = false;
7352
+ changed = /* @__PURE__ */ new Set();
7353
+ /** Título e metadado do board (`board.set`). Só entram no documento novo se foram escritos. */
7354
+ title;
7355
+ titleChanged = false;
7356
+ boardMeta;
7357
+ metaOwned = false;
7358
+ constructor(base, counts) {
7359
+ this.base = base;
7360
+ this.counts = counts;
7361
+ this.nodes = base.nodes;
7362
+ this.edges = base.edges;
7363
+ this.results = base.results;
7364
+ this.nodeHistory = base.nodeHistory;
7365
+ this.title = base.title;
7366
+ this.boardMeta = base.meta;
7367
+ }
7368
+ // ------------------------------------------------------------------- leitura
7369
+ node(id) {
7370
+ return Object.hasOwn(this.nodes, id) ? this.nodes[id] : void 0;
7371
+ }
7372
+ edge(id) {
7373
+ return Object.hasOwn(this.edges, id) ? this.edges[id] : void 0;
7374
+ }
7375
+ // Não existe leitor de `results` aqui: `result.set` grava sem consultar, e a
7376
+ // inversa dele é nula (story 004). Ler resultado é da fase 2, e o método nasce
7377
+ // no dia em que tiver chamador.
7378
+ history(nodeId3) {
7379
+ return Object.hasOwn(this.nodeHistory, nodeId3) ? this.nodeHistory[nodeId3] : void 0;
7380
+ }
7381
+ /** O título do board como está no rascunho. */
7382
+ boardTitle() {
7383
+ return this.title;
7384
+ }
7385
+ /** O metadado do board como está no rascunho. Ausente: sem metadado. */
7386
+ meta() {
7387
+ return this.boardMeta;
7388
+ }
7389
+ /** Marca o nó como tocado, para o `changedNodeIds` que a projeção lê. */
7390
+ touch(nodeId3) {
7391
+ this.changed.add(nodeId3);
7392
+ }
7393
+ // ------------------------------------------------------------------- escrita
7394
+ putNode(id, node) {
7395
+ this.ownNodes();
7396
+ writeKey(this.nodes, id, node);
7397
+ this.changed.add(id);
7398
+ }
7399
+ /**
7400
+ * Apaga o nó e, junto, a chave de histórico dele que já era lista vazia.
7401
+ *
7402
+ * Apagar a chave não é limpeza de referência, é normalização: lista vazia não
7403
+ * existe na forma canônica, chave ausente é que significa "sem variação"
7404
+ * (`dev/PLANO-FASE-0.md` §4). Descartar `[]` não perde informação nenhuma, e
7405
+ * por isso a inversa `node.add` devolve um documento equivalente sem precisar
7406
+ * recriar a chave. Chave com item continua intocada: aí sim existe informação,
7407
+ * e `node.remove` nunca limpa sozinho nada que carregue informação. Quem tira
7408
+ * as variações de um nó que vai embora é o `batch` de `removeNode`.
7409
+ *
7410
+ * Nó ausente sai antes de qualquer cópia, senão um `node.remove` que o CA8
7411
+ * declara no-op sujaria o rascunho e produziria documento novo por nada.
7412
+ */
7413
+ dropNode(id) {
7414
+ if (!Object.hasOwn(this.nodes, id)) return;
7415
+ this.ownNodes();
7416
+ delete this.nodes[id];
7417
+ this.changed.add(id);
7418
+ this.discardEmptyHistory(id);
7419
+ }
7420
+ discardEmptyHistory(nodeId3) {
7421
+ const current = this.history(nodeId3);
7422
+ if (current === void 0 || current.length > 0) return;
7423
+ this.ownNodeHistory();
7424
+ delete this.nodeHistory[nodeId3];
7425
+ }
7426
+ /**
7427
+ * Troca um nó pelo resultado de uma escrita por caminho.
7428
+ *
7429
+ * A função recebe o nó e devolve o nó novo, ou o mesmo quando não há o que
7430
+ * mudar. Devolvendo o mesmo, nada é escrito e nenhuma coleção é clonada: é
7431
+ * assim que `node.set` sem efeito sai de graça.
7432
+ */
7433
+ mutateNode(id, change) {
7434
+ const current = this.node(id);
7435
+ if (current === void 0) return;
7436
+ const next = change(current);
7437
+ if (next === current) return;
7438
+ if (this.counts !== void 0) this.counts.nodeEntry += 1;
7439
+ this.putNode(id, next);
7440
+ }
7441
+ putEdge(id, edge) {
7442
+ this.ownEdges();
7443
+ writeKey(this.edges, id, edge);
7444
+ }
7445
+ dropEdge(id) {
7446
+ if (!Object.hasOwn(this.edges, id)) return;
7447
+ this.ownEdges();
7448
+ delete this.edges[id];
7449
+ }
7450
+ putResult(id, entry) {
7451
+ this.ownResults();
7452
+ writeKey(this.results, id, entry);
7453
+ }
7454
+ /**
7455
+ * Acrescenta uma variação ao histórico do nó, no fim da lista.
7456
+ *
7457
+ * A lista nasce na primeira chamada. Id repetido entra de novo, de propósito:
7458
+ * `history.remove` tira a última ocorrência, então append seguido de remove
7459
+ * devolve a lista exatamente como estava, que é o que a inversa da story 004
7460
+ * precisa.
7461
+ */
7462
+ appendHistory(nodeId3, resultId) {
7463
+ const current = this.history(nodeId3);
7464
+ const next = current === void 0 ? [] : [...current];
7465
+ if (current !== void 0 && this.counts !== void 0) this.counts.historyEntry += 1;
7466
+ next.push(resultId);
7467
+ this.ownNodeHistory();
7468
+ writeKey(this.nodeHistory, nodeId3, next);
7469
+ this.changed.add(nodeId3);
7470
+ }
7471
+ /**
7472
+ * Tira a última ocorrência da variação no histórico do nó.
7473
+ *
7474
+ * Id ausente é no-op. Lista que fica vazia some junto com a chave: histórico
7475
+ * vazio pendurado em nó que vai ser apagado é exatamente a referência órfã que
7476
+ * o §4 do plano proíbe, e é o que o CA9 cobra depois de `removeNode`.
7477
+ */
7478
+ removeHistory(nodeId3, resultId) {
7479
+ const current = this.history(nodeId3);
7480
+ if (current === void 0) return;
7481
+ const at = current.lastIndexOf(resultId);
7482
+ if (at === -1) return;
7483
+ if (this.counts !== void 0) this.counts.historyEntry += 1;
7484
+ const next = [...current.slice(0, at), ...current.slice(at + 1)];
7485
+ this.ownNodeHistory();
7486
+ if (next.length === 0) {
7487
+ delete this.nodeHistory[nodeId3];
7488
+ } else {
7489
+ writeKey(this.nodeHistory, nodeId3, next);
7490
+ }
7491
+ this.changed.add(nodeId3);
7492
+ }
7493
+ /** Troca o título. Título igual sai de graça, sem documento novo. */
7494
+ setTitle(title) {
7495
+ if (title === this.title) return;
7496
+ this.title = title;
7497
+ this.titleChanged = true;
7498
+ }
7499
+ /**
7500
+ * Troca o metadado inteiro do board pela versão que `change` devolve.
7501
+ *
7502
+ * Metadado vazio vira ausente: `{}` não existe na forma canônica, pela mesma
7503
+ * razão da lista vazia de `nodeHistory`. Sem isso, gravar e desfazer a dica
7504
+ * num board sem metadado devolveria um documento com `meta: {}` a mais.
7505
+ */
7506
+ mutateMeta(change) {
7507
+ const current = this.boardMeta ?? {};
7508
+ const next = change(current);
7509
+ if (next === current) return;
7510
+ this.boardMeta = Object.keys(next).length === 0 ? void 0 : next;
7511
+ this.metaOwned = true;
7512
+ }
7513
+ // --------------------------------------------------------- cópia por escrita
7514
+ ownNodes() {
7515
+ if (this.nodesOwned) return;
7516
+ this.nodes = { ...this.base.nodes };
7517
+ this.nodesOwned = true;
7518
+ if (this.counts !== void 0) this.counts.nodes += 1;
7519
+ }
7520
+ ownEdges() {
7521
+ if (this.edgesOwned) return;
7522
+ this.edges = { ...this.base.edges };
7523
+ this.edgesOwned = true;
7524
+ if (this.counts !== void 0) this.counts.edges += 1;
7525
+ }
7526
+ ownResults() {
7527
+ if (this.resultsOwned) return;
7528
+ this.results = { ...this.base.results };
7529
+ this.resultsOwned = true;
7530
+ if (this.counts !== void 0) this.counts.results += 1;
7531
+ }
7532
+ ownNodeHistory() {
7533
+ if (this.nodeHistoryOwned) return;
7534
+ this.nodeHistory = { ...this.base.nodeHistory };
7535
+ this.nodeHistoryOwned = true;
7536
+ if (this.counts !== void 0) this.counts.nodeHistory += 1;
7537
+ }
7538
+ // ---------------------------------------------------------------- fechamento
7539
+ /** Alguma coleção foi escrita? Lote de no-ops não produz documento novo. */
7540
+ get dirty() {
7541
+ return this.nodesOwned || this.edgesOwned || this.resultsOwned || this.nodeHistoryOwned || this.titleChanged || this.metaOwned;
7542
+ }
7543
+ /**
7544
+ * Fecha o rascunho.
7545
+ *
7546
+ * Sem escrita, devolve a própria referência de entrada: o lote inteiro de
7547
+ * no-ops não gera documento novo e a tela não re-renderiza por nada.
7548
+ *
7549
+ * O documento sai sem `Object.freeze`, desvio do plano §4 ("congela e
7550
+ * devolve"), e a razão é custo e alcance. Congelamento fundo percorre o
7551
+ * documento inteiro a cada lote e joga fora justamente o ganho da cópia por
7552
+ * escrita. Congelamento raso protegeria só o objeto de topo, enquanto
7553
+ * `nodes`, `edges`, `results` e `nodeHistory` continuariam mutáveis, e compra
7554
+ * quase nada. Escrever `version` depois não é argumento contra congelar:
7555
+ * spread funciona sobre objeto congelado, e é o que `reduce` já faz. A
7556
+ * garantia de imutabilidade da entrada é estrutural e tem teste.
7557
+ */
7558
+ finish() {
7559
+ const changedNodeIds = [...this.changed];
7560
+ if (!this.dirty) return { doc: this.base, changedNodeIds };
7561
+ if (this.counts !== void 0) this.counts.doc += 1;
7562
+ const doc = {
7563
+ ...this.base,
7564
+ nodes: this.nodes,
7565
+ edges: this.edges,
7566
+ results: this.results,
7567
+ nodeHistory: this.nodeHistory
7568
+ };
7569
+ if (this.titleChanged) doc.title = this.title;
7570
+ if (this.metaOwned) {
7571
+ if (this.boardMeta === void 0) delete doc.meta;
7572
+ else doc.meta = this.boardMeta;
7573
+ }
7574
+ return { doc, changedNodeIds };
7575
+ }
7576
+ };
7577
+ function nodeOf(doc, id) {
7578
+ return Object.hasOwn(doc.nodes, id) ? doc.nodes[id] : void 0;
7579
+ }
7580
+ function edgeOf(doc, id) {
7581
+ return Object.hasOwn(doc.edges, id) ? doc.edges[id] : void 0;
7582
+ }
7583
+ function historyOf(doc, nodeId3) {
7584
+ return Object.hasOwn(doc.nodeHistory, nodeId3) ? doc.nodeHistory[nodeId3] : void 0;
7585
+ }
7586
+ function previousValue(node, path) {
7587
+ return getPath(node, path);
7588
+ }
7589
+ function shallowestMissingPath(target, path) {
7590
+ const walked = [];
7591
+ for (const segment of parsePath(path)) {
7592
+ walked.push(segment);
7593
+ const prefix = walked.join(".");
7594
+ if (!hasPath(target, prefix)) return prefix;
7595
+ }
7596
+ return path;
7597
+ }
7598
+ function invertNodeAdd(doc, op) {
7599
+ const previous = nodeOf(doc, op.nodeId);
7600
+ if (previous === void 0) return { type: "node.remove", nodeId: op.nodeId };
7601
+ return { type: "node.add", nodeId: op.nodeId, node: previous };
7602
+ }
7603
+ function invertNodeRemove(doc, op) {
7604
+ const current = nodeOf(doc, op.nodeId);
7605
+ if (current === void 0) return { type: "node.remove", nodeId: op.nodeId };
7606
+ return { type: "node.add", nodeId: op.nodeId, node: current };
7607
+ }
7608
+ function invertNodeSet(doc, op) {
7609
+ const node = nodeOf(doc, op.nodeId);
7610
+ if (node === void 0) {
7611
+ return { type: "node.set", nodeId: op.nodeId, path: op.path, value: unsetPropValue() };
7612
+ }
7613
+ if (hasPath(node, op.path)) {
7614
+ return {
7615
+ type: "node.set",
7616
+ nodeId: op.nodeId,
7617
+ path: op.path,
7618
+ value: propValue(previousValue(node, op.path))
7619
+ };
7620
+ }
7621
+ return {
7622
+ type: "node.set",
7623
+ nodeId: op.nodeId,
7624
+ path: shallowestMissingPath(node, op.path),
7625
+ value: unsetPropValue()
7626
+ };
7627
+ }
7628
+ function invertEdgeAdd(doc, op) {
7629
+ const previous = edgeOf(doc, op.edgeId);
7630
+ if (previous === void 0) return { type: "edge.remove", edgeId: op.edgeId };
7631
+ return { type: "edge.add", edgeId: op.edgeId, edge: previous };
7632
+ }
7633
+ function invertEdgeRemove(doc, op) {
7634
+ const current = edgeOf(doc, op.edgeId);
7635
+ if (current === void 0) return { type: "edge.remove", edgeId: op.edgeId };
7636
+ return { type: "edge.add", edgeId: op.edgeId, edge: current };
7637
+ }
7638
+ function invertResultSet() {
7639
+ return null;
7640
+ }
7641
+ function invertHistoryAppend(op) {
7642
+ return { type: "history.remove", nodeId: op.nodeId, resultId: op.resultId };
7643
+ }
7644
+ function invertHistoryRemove(doc, op) {
7645
+ const list = historyOf(doc, op.nodeId);
7646
+ const at = list === void 0 ? -1 : list.lastIndexOf(op.resultId);
7647
+ if (list === void 0 || at === -1) {
7648
+ return { type: "history.remove", nodeId: op.nodeId, resultId: op.resultId };
7649
+ }
7650
+ if (at === list.length - 1) {
7651
+ return { type: "history.append", nodeId: op.nodeId, resultId: op.resultId };
7652
+ }
7653
+ const tail = list.slice(at + 1);
7654
+ const ops = [];
7655
+ for (const resultId of [...tail].reverse()) {
7656
+ ops.push({ type: "history.remove", nodeId: op.nodeId, resultId });
7657
+ }
7658
+ ops.push({ type: "history.append", nodeId: op.nodeId, resultId: op.resultId });
7659
+ for (const resultId of tail) {
7660
+ ops.push({ type: "history.append", nodeId: op.nodeId, resultId });
7661
+ }
7662
+ return { type: "batch", ops };
7663
+ }
7664
+ var BOARD_FIELDS = ["title", "guide", "ialab", "assetUrls"];
7665
+ var InvalidBoardSetError = class extends Error {
7666
+ field;
7667
+ constructor(field, reason) {
7668
+ super(`board.set inv\xE1lido em ${JSON.stringify(field)}: ${reason}`);
7669
+ this.name = "InvalidBoardSetError";
7670
+ this.field = field;
7671
+ }
7672
+ };
7673
+ function isPlainRecord2(value) {
7674
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7675
+ }
7676
+ function isStringMap2(value) {
7677
+ return isPlainRecord2(value) && Object.values(value).every((item) => typeof item === "string");
7678
+ }
7679
+ function assertBoardSet(op) {
7680
+ const { field, key, value } = op;
7681
+ if (!BOARD_FIELDS.includes(field)) throw new InvalidBoardSetError(field, "campo desconhecido");
7682
+ if (key !== void 0) {
7683
+ if (field !== "assetUrls") throw new InvalidBoardSetError(field, "s\xF3 assetUrls aceita key");
7684
+ if (key === "" || FORBIDDEN_PATH_SEGMENTS.includes(key)) {
7685
+ throw new InvalidBoardSetError(field, `key recusada: ${JSON.stringify(key)}`);
7686
+ }
7687
+ }
7688
+ if (value.kind === "unset") {
7689
+ if (field === "title") throw new InvalidBoardSetError(field, "t\xEDtulo n\xE3o pode ser apagado");
7690
+ return;
7691
+ }
7692
+ const raw = value.value;
7693
+ const ok = field === "title" ? typeof raw === "string" : field === "guide" ? raw === null || typeof raw === "string" : field === "ialab" ? raw === null || isPlainRecord2(raw) : key === void 0 ? isStringMap2(raw) : typeof raw === "string";
7694
+ if (!ok) throw new InvalidBoardSetError(field, "valor com tipo errado");
7695
+ }
7696
+ function applyBoardSet(draft, op) {
7697
+ assertBoardSet(op);
7698
+ const { field, key, value } = op;
7699
+ if (field === "title") {
7700
+ if (value.kind === "value" && typeof value.value === "string") draft.setTitle(value.value);
7701
+ return;
7702
+ }
7703
+ draft.mutateMeta((meta) => {
7704
+ if (field === "assetUrls" && key !== void 0) return withAssetUrl(meta, key, value);
7705
+ return withField(meta, field, value);
7706
+ });
7707
+ }
7708
+ function withField(meta, field, value) {
7709
+ if (value.kind === "unset") {
7710
+ if (!Object.hasOwn(meta, field)) return meta;
7711
+ const next2 = { ...meta };
7712
+ delete next2[field];
7713
+ return next2;
7714
+ }
7715
+ const current = Object.hasOwn(meta, field) ? meta[field] : void 0;
7716
+ if (current === value.value && (value.value === null || typeof value.value === "string")) {
7717
+ return meta;
7718
+ }
7719
+ const next = { ...meta };
7720
+ writeKey(next, field, value.value);
7721
+ return next;
7722
+ }
7723
+ function withAssetUrl(meta, key, value) {
7724
+ const urls = meta.assetUrls;
7725
+ if (value.kind === "unset") {
7726
+ if (urls === void 0 || !Object.hasOwn(urls, key)) return meta;
7727
+ const nextUrls2 = { ...urls };
7728
+ delete nextUrls2[key];
7729
+ return { ...meta, assetUrls: nextUrls2 };
7730
+ }
7731
+ const url = value.value;
7732
+ if (urls !== void 0 && Object.hasOwn(urls, key) && urls[key] === url) return meta;
7733
+ const nextUrls = { ...urls };
7734
+ writeKey(nextUrls, key, url);
7735
+ return { ...meta, assetUrls: nextUrls };
7736
+ }
7737
+ function invertBoardSet(doc, op) {
7738
+ const { field, key } = op;
7739
+ if (field === "title") return { type: "board.set", field, value: propValue(doc.title) };
7740
+ const meta = doc.meta ?? {};
7741
+ if (field === "assetUrls" && key !== void 0) {
7742
+ const urls = meta.assetUrls;
7743
+ if (urls === void 0) return { type: "board.set", field, value: unsetPropValue() };
7744
+ return Object.hasOwn(urls, key) ? { type: "board.set", field, key, value: propValue(urls[key]) } : { type: "board.set", field, key, value: unsetPropValue() };
7745
+ }
7746
+ if (!Object.hasOwn(meta, field)) return { type: "board.set", field, value: unsetPropValue() };
7747
+ return { type: "board.set", field, value: propValue(meta[field]) };
7748
+ }
7749
+ function touchEdgeEnds(draft, source, target) {
7750
+ draft.touch(source);
7751
+ draft.touch(target);
7752
+ }
7753
+ var OPS2 = {
7754
+ "node.add": {
7755
+ apply(draft, op) {
7756
+ draft.putNode(op.nodeId, op.node);
7757
+ },
7758
+ invert: invertNodeAdd
7759
+ },
7760
+ "node.remove": {
7761
+ apply(draft, op) {
7762
+ draft.dropNode(op.nodeId);
7763
+ },
7764
+ invert: invertNodeRemove
7765
+ },
7766
+ "node.set": {
7767
+ apply(draft, op) {
7768
+ draft.mutateNode(
7769
+ op.nodeId,
7770
+ (node) => op.value.kind === "value" ? setPath(node, op.path, op.value.value) : unsetPath(node, op.path)
7771
+ );
7772
+ },
7773
+ invert: invertNodeSet
7774
+ },
7775
+ "edge.add": {
7776
+ apply(draft, op) {
7777
+ draft.putEdge(op.edgeId, op.edge);
7778
+ touchEdgeEnds(draft, op.edge.source, op.edge.target);
7779
+ },
7780
+ invert: invertEdgeAdd
7781
+ },
7782
+ "edge.remove": {
7783
+ apply(draft, op) {
7784
+ const current = draft.edge(op.edgeId);
7785
+ if (current === void 0) return;
7786
+ draft.dropEdge(op.edgeId);
7787
+ touchEdgeEnds(draft, current.source, current.target);
7788
+ },
7789
+ invert: invertEdgeRemove
7790
+ },
7791
+ "result.set": {
7792
+ apply(draft, op) {
7793
+ draft.putResult(op.resultId, op.entry);
7794
+ draft.touch(op.entry.nodeId);
7795
+ },
7796
+ invert: invertResultSet
7797
+ },
7798
+ "history.append": {
7799
+ apply(draft, op) {
7800
+ draft.appendHistory(op.nodeId, op.resultId);
7801
+ },
7802
+ invert: (_doc, op) => invertHistoryAppend(op)
7803
+ },
7804
+ "history.remove": {
7805
+ apply(draft, op) {
7806
+ draft.removeHistory(op.nodeId, op.resultId);
7807
+ },
7808
+ invert: invertHistoryRemove
7809
+ },
7810
+ "board.set": {
7811
+ apply: applyBoardSet,
7812
+ invert: invertBoardSet
7813
+ },
7814
+ batch: {
7815
+ apply(draft, op) {
7816
+ for (const inner of op.ops) applyOp(draft, inner);
7817
+ },
7818
+ /**
7819
+ * As inversas dos membros, em ordem reversa.
7820
+ *
7821
+ * O estado avança membro a membro, e não dá para fugir disso: inverter dois
7822
+ * `history.remove` seguidos contra o MESMO documento de entrada devolveria
7823
+ * dois `history.append` iguais, e a lista voltaria com um item a mais do que
7824
+ * tinha. Quem avança é `walkBatch`, com um rascunho de rascunho que nunca
7825
+ * toca o documento de quem chamou.
7826
+ */
7827
+ invert(doc, op) {
7828
+ const parts = walkBatch(doc, op.ops, invert);
7829
+ return { type: "batch", ops: parts.reverse() };
7830
+ }
7831
+ }
7832
+ };
7833
+ function applyOp(draft, op) {
7834
+ const handler = OPS2[op.type];
7835
+ handler.apply(draft, op);
7836
+ }
7837
+ function invert(doc, op) {
7838
+ const handler = OPS2[op.type];
7839
+ return handler.invert(doc, op);
7840
+ }
7841
+ function walkBatch(doc, ops, visit) {
7842
+ const scratch = new Draft(doc);
7843
+ const collected = [];
7844
+ for (const op of ops) {
7845
+ const item = visit(scratch.finish().doc, op);
7846
+ if (item !== null) collected.push(item);
7847
+ applyOp(scratch, op);
7848
+ }
7849
+ return collected;
7850
+ }
7851
+ var MAX_OP_BYTES2 = 64 * 1024;
7852
+ var OpTooLargeError2 = class extends Error {
7853
+ /** O envelope recusado, para o `onError` da story 005 citar na mensagem. */
7854
+ opId;
7855
+ /** Quanto ele pesa, serializado em UTF-8. */
7856
+ bytes;
7857
+ /** Quanto cabia. */
7858
+ limit;
7859
+ constructor(opId, bytes, limit = MAX_OP_BYTES2) {
7860
+ super(`Opera\xE7\xE3o ${opId} tem ${bytes} bytes e o teto \xE9 ${limit}`);
7861
+ this.name = "OpTooLargeError";
7862
+ this.opId = opId;
7863
+ this.bytes = bytes;
7864
+ this.limit = limit;
7865
+ }
7866
+ };
7867
+ function utf8ByteLength(text) {
7868
+ let bytes = 0;
7869
+ for (let i = 0; i < text.length; i += 1) {
7870
+ const code = text.charCodeAt(i);
7871
+ if (code < 128) {
7872
+ bytes += 1;
7873
+ } else if (code < 2048) {
7874
+ bytes += 2;
7875
+ } else if (code >= 55296 && code <= 56319 && i + 1 < text.length) {
7876
+ const next = text.charCodeAt(i + 1);
7877
+ if (next >= 56320 && next <= 57343) {
7878
+ bytes += 4;
7879
+ i += 1;
7880
+ } else {
7881
+ bytes += 3;
7882
+ }
7883
+ } else {
7884
+ bytes += 3;
7885
+ }
7886
+ }
7887
+ return bytes;
7888
+ }
7889
+ function opEnvelopeBytes(envelope2) {
7890
+ return utf8ByteLength(JSON.stringify(envelope2));
7891
+ }
7892
+ function assertOpEnvelopeFits(envelope2, limit = MAX_OP_BYTES2) {
7893
+ const bytes = opEnvelopeBytes(envelope2);
7894
+ if (bytes > limit) throw new OpTooLargeError2(envelope2.id, bytes, limit);
7895
+ }
7896
+ function applyOps(doc, ops, options = {}) {
7897
+ const draft = new Draft(doc, options.counts);
7898
+ for (const op of ops) applyOp(draft, op);
7899
+ return draft.finish();
7900
+ }
7901
+ function applyEnvelopes(doc, envelopes, options = {}) {
7902
+ for (const envelope2 of envelopes) assertOpEnvelopeFits(envelope2);
7903
+ return applyOps(
7904
+ doc,
7905
+ envelopes.map((envelope2) => envelope2.op),
7906
+ options
7907
+ );
7908
+ }
7909
+ function reduce(log, base) {
7910
+ const doc = base ?? emptyBoardFor(log);
7911
+ if (log.length === 0) return doc;
7912
+ let lastSeq = base === void 0 ? -1 : base.version;
7913
+ for (const envelope2 of log) {
7914
+ if (envelope2.seq === null) {
7915
+ throw new Error(
7916
+ `reduce recebeu o envelope ${envelope2.id} sem seq: s\xF3 entra no log o que j\xE1 foi confirmado`
7917
+ );
7918
+ }
7919
+ if (envelope2.seq <= lastSeq) {
7920
+ throw new Error(
7921
+ `reduce recebeu o log fora de ordem: seq ${envelope2.seq} depois de ${lastSeq}`
7922
+ );
7923
+ }
7924
+ lastSeq = envelope2.seq;
7925
+ }
7926
+ const applied = applyOps(
7927
+ doc,
7928
+ log.map((envelope2) => envelope2.op)
7929
+ );
7930
+ return { ...applied.doc, version: lastSeq };
7931
+ }
7932
+ function emptyBoardFor(log) {
7933
+ const first = log[0];
7934
+ if (first === void 0) {
7935
+ throw new Error("reduce sem base precisa de um log com ao menos um envelope");
7936
+ }
7937
+ return createEmptyBoard({ id: first.boardId, now: () => first.ts });
7938
+ }
7939
+ function removeNode(doc, nodeId3) {
7940
+ const ops = [];
7941
+ const edgeIds = Object.keys(doc.edges).filter((edgeId) => {
7942
+ const edge = doc.edges[edgeId];
7943
+ return edge !== void 0 && (edge.source === nodeId3 || edge.target === nodeId3);
7944
+ }).sort();
7945
+ for (const edgeId of edgeIds) ops.push({ type: "edge.remove", edgeId });
7946
+ const history = Object.hasOwn(doc.nodeHistory, nodeId3) ? doc.nodeHistory[nodeId3] : void 0;
7947
+ if (history !== void 0) {
7948
+ for (const resultId of [...history].reverse()) {
7949
+ ops.push({ type: "history.remove", nodeId: nodeId3, resultId });
7950
+ }
7951
+ }
7952
+ ops.push({ type: "node.remove", nodeId: nodeId3 });
7953
+ return { type: "batch", ops };
7954
+ }
7955
+ function batchOf2(ops) {
7956
+ const [first, ...rest] = ops;
7957
+ if (first !== void 0 && rest.length === 0) return first;
7958
+ return { type: "batch", ops: [...ops] };
7959
+ }
7960
+ function createOpIdGenerator(random = Math.random) {
7961
+ return () => {
7962
+ let out = "";
7963
+ for (let i = 0; i < 36; i += 1) {
7964
+ if (i === 8 || i === 13 || i === 18 || i === 23) {
7965
+ out += "-";
7966
+ continue;
7967
+ }
7968
+ if (i === 14) {
7969
+ out += "4";
7970
+ continue;
7971
+ }
7972
+ const value = Math.floor(random() * 16) & 15;
7973
+ out += (i === 19 ? value & 3 | 8 : value).toString(16);
7974
+ }
7975
+ return out;
7976
+ };
7977
+ }
7978
+ var newOpId = createOpIdGenerator();
7979
+ function touchedPaths(op, out = []) {
7980
+ switch (op.type) {
7981
+ case "node.add":
7982
+ case "node.remove":
7983
+ out.push(["node", op.nodeId]);
7984
+ break;
7985
+ case "node.set":
7986
+ out.push(["node", op.nodeId, ...segmentsOf(op.path)]);
7987
+ break;
7988
+ case "edge.add":
7989
+ case "edge.remove":
7990
+ out.push(["edge", op.edgeId]);
7991
+ break;
7992
+ case "result.set":
7993
+ out.push(["result", op.resultId]);
7994
+ break;
7995
+ case "history.append":
7996
+ case "history.remove":
7997
+ out.push(["history", op.nodeId]);
7998
+ break;
7999
+ case "board.set":
8000
+ out.push(op.key === void 0 ? ["board", op.field] : ["board", op.field, op.key]);
8001
+ break;
8002
+ case "batch":
8003
+ for (const inner of op.ops) touchedPaths(inner, out);
8004
+ break;
8005
+ }
8006
+ return out;
8007
+ }
8008
+ function segmentsOf(path) {
8009
+ try {
8010
+ return parsePath(path);
8011
+ } catch {
8012
+ return [];
8013
+ }
8014
+ }
8015
+ function pathsCross(a, b) {
8016
+ const length = Math.min(a.length, b.length);
8017
+ for (let i = 0; i < length; i += 1) if (a[i] !== b[i]) return false;
8018
+ return true;
8019
+ }
8020
+ function anyPathCrosses(a, b) {
8021
+ for (const left of a) for (const right of b) if (pathsCross(left, right)) return true;
8022
+ return false;
8023
+ }
8024
+ var HISTORY_LIMIT = 100;
8025
+ var HISTORY_MAX_BYTES = 8 * 1024 * 1024;
8026
+ var OBJECT_OVERHEAD = 16;
8027
+ var KEY_OVERHEAD = 8;
8028
+ var NUMBER_BYTES = 8;
8029
+ var SMALL_BYTES = 4;
8030
+ function estimateOpBytes(op) {
8031
+ let total = 0;
8032
+ const pending = [op];
8033
+ const seen = /* @__PURE__ */ new Set();
8034
+ while (pending.length > 0) {
8035
+ const value = pending.pop();
8036
+ if (typeof value === "string") {
8037
+ total += KEY_OVERHEAD + value.length * 2;
8038
+ } else if (typeof value === "number") {
8039
+ total += NUMBER_BYTES;
8040
+ } else if (Array.isArray(value)) {
8041
+ if (seen.has(value)) continue;
8042
+ seen.add(value);
8043
+ total += OBJECT_OVERHEAD;
8044
+ for (const item of value) pending.push(item);
8045
+ } else if (typeof value === "object" && value !== null) {
8046
+ if (seen.has(value)) continue;
8047
+ seen.add(value);
8048
+ total += OBJECT_OVERHEAD;
8049
+ for (const [key, item] of Object.entries(value)) {
8050
+ total += KEY_OVERHEAD + key.length * 2;
8051
+ pending.push(item);
8052
+ }
8053
+ } else {
8054
+ total += SMALL_BYTES;
8055
+ }
8056
+ }
8057
+ return total;
8058
+ }
8059
+ var HistoryStack = class {
8060
+ entries = [];
8061
+ redoEntries = [];
8062
+ limit;
8063
+ maxBytes;
8064
+ clock;
8065
+ onHistoryTrimmed;
8066
+ /** Soma de `bytes` das entradas de desfazer, mantida incrementalmente. */
8067
+ totalBytes = 0;
8068
+ /** Grupo aberto por `startCapture`, ou nulo quando nenhum gesto está aberto. */
8069
+ openGroupId = null;
8070
+ /** Contador de grupos. O id é local à pilha, então não precisa de fonte injetada. */
8071
+ groupSeq = 0;
8072
+ constructor(options = {}) {
8073
+ this.limit = options.limit ?? HISTORY_LIMIT;
8074
+ this.maxBytes = options.maxBytes ?? HISTORY_MAX_BYTES;
8075
+ this.clock = options.clock ?? Date.now;
8076
+ this.onHistoryTrimmed = options.onHistoryTrimmed;
8077
+ }
8078
+ // ------------------------------------------------------------------ leitura
8079
+ get canUndo() {
8080
+ return this.entries.length > 0;
8081
+ }
8082
+ get canRedo() {
8083
+ return this.redoEntries.length > 0;
8084
+ }
8085
+ /** Quantas entradas dá para desfazer. É o que o painel da story 007 mostra. */
8086
+ get size() {
8087
+ return this.entries.length;
8088
+ }
8089
+ /** Quantas entradas dá para refazer. */
8090
+ get redoSize() {
8091
+ return this.redoEntries.length;
8092
+ }
8093
+ /** Memória somada das entradas de desfazer, estimada. */
8094
+ get bytes() {
8095
+ return this.totalBytes;
8096
+ }
8097
+ /** Tem gesto aberto? */
8098
+ get capturing() {
8099
+ return this.openGroupId !== null;
8100
+ }
8101
+ /** A entrada mais recente, sem tirá-la da pilha. Leitura, não consumo. */
8102
+ peek() {
8103
+ return this.entries[this.entries.length - 1];
8104
+ }
8105
+ // ------------------------------------------------------------------ captura
8106
+ /**
8107
+ * Abre um gesto: tudo que for capturado até `endCapture` vira uma entrada só.
8108
+ *
8109
+ * Chamada com um gesto já aberto, devolve o grupo aberto em vez de abrir
8110
+ * outro. Gesto dentro de gesto não existe na tela, e contar profundidade
8111
+ * pediria um `endCapture` por chamada, que é um jeito novo de esquecer de
8112
+ * fechar.
8113
+ */
8114
+ startCapture() {
8115
+ if (this.openGroupId === null) {
8116
+ this.groupSeq += 1;
8117
+ this.openGroupId = `gesture-${this.groupSeq}`;
8118
+ }
8119
+ return this.openGroupId;
8120
+ }
8121
+ /** Fecha o gesto. A próxima captura abre entrada nova. */
8122
+ endCapture() {
8123
+ this.openGroupId = null;
8124
+ }
8125
+ /**
8126
+ * Guarda uma operação e a inversa dela.
8127
+ *
8128
+ * A inversa entra na FRENTE da lista da entrada: desfazer aplica `inverse` na
8129
+ * ordem do array, e a última coisa que aconteceu é a primeira a ser desfeita.
8130
+ */
8131
+ capture(op, inverse, options = {}) {
8132
+ this.redoEntries.length = 0;
8133
+ const groupId = options.groupId ?? this.openGroupId;
8134
+ const bytes = estimateOpBytes(op) + estimateOpBytes(inverse);
8135
+ const last = this.peek();
8136
+ if (last !== void 0 && (options.amendLast === true || groupId !== null && last.groupId === groupId)) {
8137
+ last.ops.push(op);
8138
+ last.inverse.unshift(inverse);
8139
+ touchedPaths(op, last.paths);
8140
+ last.bytes += bytes;
8141
+ last.ts = this.clock();
8142
+ this.totalBytes += bytes;
8143
+ this.trim();
8144
+ return last;
8145
+ }
8146
+ const entry = {
8147
+ ops: [op],
8148
+ inverse: [inverse],
8149
+ groupId,
8150
+ ts: this.clock(),
8151
+ bytes,
8152
+ paths: touchedPaths(op),
8153
+ stale: false
8154
+ };
8155
+ this.entries.push(entry);
8156
+ this.totalBytes += bytes;
8157
+ this.trim();
8158
+ return entry;
8159
+ }
8160
+ // ------------------------------------------------------- desfazer e refazer
8161
+ /**
8162
+ * Tira a entrada mais recente e a passa para o refazer.
8163
+ *
8164
+ * A pilha não aplica nada: quem aplica é o store, com a inversa recarimbada.
8165
+ * Devolver a entrada em vez de aplicá-la é o que mantém o núcleo do histórico
8166
+ * sem opinião sobre transporte, relógio e id.
8167
+ */
8168
+ undo() {
8169
+ const entry = this.entries.pop();
8170
+ if (entry === void 0) return void 0;
8171
+ this.totalBytes -= entry.bytes;
8172
+ if (!entry.stale) this.redoEntries.push(entry);
8173
+ return entry;
8174
+ }
8175
+ /**
8176
+ * Devolve à pilha de desfazer a entrada que `undo` acabou de tirar, quando a
8177
+ * inversa dela não pôde ser aplicada (recusada pelo teto de tamanho). Sem
8178
+ * isto, um desfazer recusado perderia o passo.
8179
+ */
8180
+ revertUndo(entry) {
8181
+ if (this.redoEntries[this.redoEntries.length - 1] === entry) this.redoEntries.pop();
8182
+ this.entries.push(entry);
8183
+ this.totalBytes += entry.bytes;
8184
+ }
8185
+ /** O par de `revertUndo` para o refazer. */
8186
+ revertRedo(entry) {
8187
+ if (this.entries[this.entries.length - 1] === entry) {
8188
+ this.entries.pop();
8189
+ this.totalBytes -= entry.bytes;
8190
+ }
8191
+ this.redoEntries.push(entry);
8192
+ }
8193
+ /**
8194
+ * Outra pessoa tocou estes caminhos: as entradas que cruzam com eles, nas duas
8195
+ * pilhas, ficam marcadas como velhas. Não apaga nada aqui: quem descarta, e
8196
+ * avisa, é o desfazer, no momento em que a pessoa pede.
8197
+ */
8198
+ invalidate(paths) {
8199
+ if (paths.length === 0) return 0;
8200
+ let marked = 0;
8201
+ for (const entry of [...this.entries, ...this.redoEntries]) {
8202
+ if (entry.stale || !anyPathCrosses(entry.paths, paths)) continue;
8203
+ entry.stale = true;
8204
+ marked += 1;
8205
+ }
8206
+ return marked;
8207
+ }
8208
+ /**
8209
+ * Tira a entrada mais recente do refazer e a devolve para o desfazer.
8210
+ *
8211
+ * Não precisa de poda: o que volta já esteve na pilha dentro do teto, e
8212
+ * qualquer captura no meio do caminho teria zerado o refazer.
8213
+ */
8214
+ redo() {
8215
+ const entry = this.redoEntries.pop();
8216
+ if (entry === void 0) return void 0;
8217
+ if (entry.stale) return entry;
8218
+ this.entries.push(entry);
8219
+ this.totalBytes += entry.bytes;
8220
+ return entry;
8221
+ }
8222
+ /** Esvazia as duas pilhas. O documento não muda; a memória, sim. */
8223
+ clear() {
8224
+ this.entries.length = 0;
8225
+ this.redoEntries.length = 0;
8226
+ this.totalBytes = 0;
8227
+ this.openGroupId = null;
8228
+ }
8229
+ // --------------------------------------------------------------------- teto
8230
+ /**
8231
+ * Aplica os dois tetos, o de contagem e o de memória.
8232
+ *
8233
+ * A entrada mais recente nunca é descartada pelo teto de memória, mesmo
8234
+ * sozinha acima dele: o documento já mudou, e descartá-la deixaria o Marco sem
8235
+ * como desfazer o que ele acabou de fazer. Quando é esse o caso, o total fica
8236
+ * acima do teto e nenhum aviso é forjado, porque nada foi descartado.
8237
+ */
8238
+ trim() {
8239
+ const excess = this.entries.length - this.limit;
8240
+ if (excess > 0) {
8241
+ const dropped = this.entries.splice(0, excess);
8242
+ for (const entry of dropped) this.totalBytes -= entry.bytes;
8243
+ this.report("count", dropped);
8244
+ }
8245
+ let cut = 0;
8246
+ let running = this.totalBytes;
8247
+ for (const entry of this.entries) {
8248
+ if (running <= this.maxBytes || cut >= this.entries.length - 1) break;
8249
+ running -= entry.bytes;
8250
+ cut += 1;
8251
+ }
8252
+ if (cut > 0) {
8253
+ const dropped = this.entries.splice(0, cut);
8254
+ this.totalBytes = running;
8255
+ this.report("bytes", dropped);
8256
+ }
8257
+ }
8258
+ report(reason, dropped) {
8259
+ if (this.onHistoryTrimmed === void 0) return;
8260
+ this.onHistoryTrimmed({ reason, dropped, bytes: this.totalBytes });
8261
+ }
8262
+ };
8263
+ function isLocalEnvelope(envelope2, localActorId) {
8264
+ return envelope2.actorId === localActorId;
8265
+ }
8266
+ function captureOf(doc, op) {
8267
+ if (op.type === "batch") {
8268
+ const parts = walkBatch(doc, op.ops, captureOf);
8269
+ if (parts.length === 0) return null;
8270
+ return {
8271
+ op: { type: "batch", ops: parts.map((part) => part.op) },
8272
+ inverse: { type: "batch", ops: parts.map((part) => part.inverse).reverse() }
8273
+ };
8274
+ }
8275
+ const inverse = invert(doc, op);
8276
+ if (inverse === null) return null;
8277
+ return { op, inverse };
8278
+ }
8279
+ function trackCapture(doc, envelope2, localActorId) {
8280
+ if (!isLocalEnvelope(envelope2, localActorId)) return null;
8281
+ return captureOf(doc, envelope2.op);
8282
+ }
8283
+ var EMPTY_INTERACTION = Object.freeze({
8284
+ drag: null,
8285
+ resize: null,
8286
+ selection: Object.freeze([])
8287
+ });
8288
+ function sameNodeIds(a, b) {
8289
+ if (a.length !== b.length) return false;
8290
+ for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
8291
+ return true;
8292
+ }
8293
+ function sameBox(a, b) {
8294
+ if (a == null || b == null) return (a ?? null) === (b ?? null);
8295
+ return a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;
8296
+ }
8297
+ function isOpList(value) {
8298
+ return Array.isArray(value);
8299
+ }
8300
+ var BoardStore = class {
8301
+ current;
8302
+ interaction = EMPTY_INTERACTION;
8303
+ options;
8304
+ stack;
8305
+ clock;
8306
+ newId;
8307
+ listeners = /* @__PURE__ */ new Set();
8308
+ envelopeListeners = /* @__PURE__ */ new Set();
8309
+ last = null;
8310
+ lastFromSync = false;
8311
+ constructor(doc, options) {
8312
+ this.current = doc;
8313
+ this.options = options;
8314
+ this.clock = options.clock ?? Date.now;
8315
+ this.newId = options.newId ?? newOpId;
8316
+ this.stack = new HistoryStack({
8317
+ limit: options.history?.limit,
8318
+ maxBytes: options.history?.maxBytes,
8319
+ clock: this.clock,
8320
+ onHistoryTrimmed: options.onHistoryTrimmed
8321
+ });
8322
+ }
8323
+ // ------------------------------------------------------------------ leitura
8324
+ /**
8325
+ * O documento de agora. Estável por referência entre mudanças.
8326
+ *
8327
+ * Propriedade de seta, e não método, porque ela é passada direto para
8328
+ * `useSyncExternalStore`: assim não precisa de `bind`, e o React não reassina
8329
+ * a cada render por receber uma função nova. `subscribe` e `getInteraction`
8330
+ * seguem a mesma forma, e as três mudam juntas ou nenhuma: metade convertida
8331
+ * faz o React reassinar sem erro visível.
8332
+ */
8333
+ getDoc = () => this.current;
8334
+ /** O estado efêmero de agora. Mesma regra de estabilidade do documento. */
8335
+ getInteraction = () => this.interaction;
8336
+ /** Assina mudanças. Devolve a função que cancela a assinatura. */
8337
+ subscribe = (listener) => {
8338
+ this.listeners.add(listener);
8339
+ return () => {
8340
+ this.listeners.delete(listener);
8341
+ };
8342
+ };
8343
+ /** A pilha, para quem mostra o estado dela na tela (story 007). */
8344
+ get history() {
8345
+ return this.stack;
8346
+ }
8347
+ get canUndo() {
8348
+ return this.stack.canUndo;
8349
+ }
8350
+ get canRedo() {
8351
+ return this.stack.canRedo;
8352
+ }
8353
+ /**
8354
+ * O último envelope aplicado, nosso ou de fora. É por ele que quem assina
8355
+ * sabe se a mudança que acabou de acordá-lo nasceu nesta aba (`clientId`
8356
+ * igual ao da sessão) e, portanto, se deve derivar operação a partir dela
8357
+ * (SV2b). Nulo antes do primeiro despacho.
8358
+ */
8359
+ get lastEnvelope() {
8360
+ return this.last;
8361
+ }
8362
+ /**
8363
+ * A última troca do documento veio de `replaceDoc` (a sincronização trocou a
8364
+ * foto: remotas mais as pendentes reaplicadas), e não de um despacho. Para
8365
+ * quem deriva operação, isso conta como mudança de fora: as pendentes desta
8366
+ * aba já derivaram quando foram despachadas pela primeira vez.
8367
+ */
8368
+ get lastChangeFromSync() {
8369
+ return this.lastFromSync;
8370
+ }
8371
+ // ------------------------------------------------------------------ gestos
8372
+ /** Abre um gesto: o que for despachado até `endCapture` vira uma entrada só. */
8373
+ startCapture() {
8374
+ return this.stack.startCapture();
8375
+ }
8376
+ /** Fecha o gesto. */
8377
+ endCapture() {
8378
+ this.stack.endCapture();
8379
+ }
8380
+ // ---------------------------------------------------------------- interação
8381
+ /**
8382
+ * Troca a seleção. Não é documento, não é op, não entra na pilha.
8383
+ *
8384
+ * Seleção igual sai de graça: sem troca de referência ninguém é acordado.
8385
+ */
8386
+ select(nodeIds) {
8387
+ if (sameNodeIds(this.interaction.selection, nodeIds)) return;
8388
+ this.interaction = { ...this.interaction, selection: [...nodeIds] };
8389
+ this.notify();
8390
+ }
8391
+ /**
8392
+ * Abre um gesto de arraste, capturando a posição de partida de cada nó.
8393
+ *
8394
+ * Id que não existe no documento é ignorado, e um gesto sem nenhum nó válido
8395
+ * não abre nem notifica. Gesto já aberto também não reabre: o primeiro frame
8396
+ * é quem define a base da op do soltar, e recapturar a base no meio do
8397
+ * caminho mediria o gesto pela metade.
8398
+ */
8399
+ beginDrag(nodeIds) {
8400
+ if (this.interaction.drag !== null) return;
8401
+ const origin = {};
8402
+ const ids = [];
8403
+ for (const id of nodeIds) {
8404
+ const node = this.current.nodes[id];
8405
+ if (node === void 0) continue;
8406
+ origin[id] = { x: node.position.x, y: node.position.y };
8407
+ ids.push(id);
8408
+ }
8409
+ if (ids.length === 0) return;
8410
+ this.interaction = { ...this.interaction, drag: { nodeIds: ids, origin, live: origin } };
8411
+ this.notify();
8412
+ }
8413
+ /**
8414
+ * Move o gesto vivo. Sem op, sem histórico, sem tocar no documento.
8415
+ *
8416
+ * Posição repetida sai de graça, e é isso que impede um `pointermove` que não
8417
+ * andou de custar um render. Id fora do gesto é ignorado.
8418
+ */
8419
+ moveDrag(positions) {
8420
+ const drag = this.interaction.drag;
8421
+ if (drag === null) return;
8422
+ let changed = false;
8423
+ const live = { ...drag.live };
8424
+ for (const id of drag.nodeIds) {
8425
+ const next = positions[id];
8426
+ if (next === void 0) continue;
8427
+ const current = live[id];
8428
+ if (current !== void 0 && current.x === next.x && current.y === next.y) continue;
8429
+ live[id] = { x: next.x, y: next.y };
8430
+ changed = true;
8431
+ }
8432
+ if (!changed) return;
8433
+ this.interaction = { ...this.interaction, drag: { ...drag, live } };
8434
+ this.notify();
8435
+ }
8436
+ /**
8437
+ * Fecha o gesto: uma op de topo, uma entrada de histórico, uma notificação.
8438
+ *
8439
+ * **A troca é atômica.** A camada efêmera é limpa ANTES de o despacho
8440
+ * notificar, então a única notificação que sai já carrega o documento com a
8441
+ * posição nova e o gesto encerrado. Nenhum assinante consegue observar o par
8442
+ * (posição velha, arraste já encerrado), que é o piscar de um frame que o
8443
+ * desenho de dois donos de estado produz.
8444
+ *
8445
+ * `positions` é a posição final vinda de quem viu o gesto acontecer (o
8446
+ * `change.position` da lib), e a camada efêmera entra só como reserva: uma
8447
+ * fonte de verdade por valor, com a segunda cobrindo o dia em que a primeira
8448
+ * faltar. Nó que voltou para onde começou não emite nada, e gesto em que
8449
+ * ninguém andou não emite op nenhuma.
8450
+ */
8451
+ endDrag(positions = {}) {
8452
+ const drag = this.interaction.drag;
8453
+ if (drag === null) return null;
8454
+ const ops = [];
8455
+ for (const id of drag.nodeIds) {
8456
+ const from = drag.origin[id];
8457
+ const to = positions[id] ?? drag.live[id];
8458
+ if (from === void 0 || to === void 0) continue;
8459
+ if (from.x === to.x && from.y === to.y) continue;
8460
+ ops.push({
8461
+ type: "node.set",
8462
+ nodeId: id,
8463
+ path: "position",
8464
+ value: propValue({ x: to.x, y: to.y })
8465
+ });
8466
+ }
8467
+ if (ops.length === 0) {
8468
+ this.cancelDrag();
8469
+ return null;
8470
+ }
8471
+ this.interaction = { ...this.interaction, drag: null };
8472
+ const result = this.dispatch(ops, { silent: true });
8473
+ this.notify();
8474
+ return result;
8475
+ }
8476
+ /**
8477
+ * Saída do gesto interrompido: `Escape`, `pointercancel` e a aba perdendo o
8478
+ * foco. Zero op, zero entrada de histórico, e o nó volta para a posição do
8479
+ * documento porque é ela que sempre esteve lá.
8480
+ */
8481
+ cancelDrag() {
8482
+ if (this.interaction.drag === null) return;
8483
+ this.interaction = { ...this.interaction, drag: null };
8484
+ this.notify();
8485
+ }
8486
+ /**
8487
+ * Abre um gesto de redimensionar (SV2b). Mesmo desenho do arraste: nada vira
8488
+ * operação até o soltar. Nó ausente não abre.
8489
+ */
8490
+ beginResize(nodeId3) {
8491
+ const node = this.current.nodes[nodeId3];
8492
+ if (node === void 0) return;
8493
+ const origin = { ...node.position, ...node.size };
8494
+ this.interaction = { ...this.interaction, resize: { nodeId: nodeId3, origin, live: origin } };
8495
+ this.notify();
8496
+ }
8497
+ /** A caixa do frame atual. Sem op, sem histórico. Caixa igual sai de graça. */
8498
+ moveResize(box) {
8499
+ const resize = this.interaction.resize;
8500
+ if (resize == null || sameBox(resize.live, box)) return;
8501
+ const live = { x: box.x, y: box.y, w: box.w, h: box.h };
8502
+ this.interaction = { ...this.interaction, resize: { ...resize, live } };
8503
+ this.notify();
8504
+ }
8505
+ /**
8506
+ * Fecha o gesto: uma op, uma entrada de histórico, uma notificação. A troca
8507
+ * é atômica pela mesma razão de `endDrag`. Caixa final igual à de partida
8508
+ * não emite nada.
8509
+ */
8510
+ endResize(box) {
8511
+ const resize = this.interaction.resize;
8512
+ if (resize == null) return null;
8513
+ const to = box ?? resize.live;
8514
+ const from = resize.origin;
8515
+ const ops = [];
8516
+ if (from.w !== to.w || from.h !== to.h) {
8517
+ ops.push({
8518
+ type: "node.set",
8519
+ nodeId: resize.nodeId,
8520
+ path: "size",
8521
+ value: propValue({ w: to.w, h: to.h })
8522
+ });
8523
+ }
8524
+ if (from.x !== to.x || from.y !== to.y) {
8525
+ ops.push({
8526
+ type: "node.set",
8527
+ nodeId: resize.nodeId,
8528
+ path: "position",
8529
+ value: propValue({ x: to.x, y: to.y })
8530
+ });
8531
+ }
8532
+ this.interaction = { ...this.interaction, resize: null };
8533
+ if (ops.length === 0 || this.current.nodes[resize.nodeId] === void 0) {
8534
+ this.notify();
8535
+ return null;
8536
+ }
8537
+ const result = this.dispatch(ops, { silent: true });
8538
+ this.notify();
8539
+ return result;
8540
+ }
8541
+ /** Gesto interrompido: zero op, e o nó volta ao tamanho do documento. */
8542
+ cancelResize() {
8543
+ if (this.interaction.resize == null) return;
8544
+ this.interaction = { ...this.interaction, resize: null };
8545
+ this.notify();
8546
+ }
8547
+ // ----------------------------------------------------------------- despacho
8548
+ /**
8549
+ * Despacha operação nossa: carimba o envelope com a sessão local e aplica.
8550
+ *
8551
+ * Lista com mais de uma operação vira um `batch`, porque um envelope carrega
8552
+ * UMA operação de topo, e um `batch` é uma operação, logo um `seq`
8553
+ * (`dev/PLANO-FASE-0.md` §3).
8554
+ */
8555
+ dispatch(ops, options = {}) {
8556
+ const op = isOpList(ops) ? batchOf2(ops) : ops;
8557
+ return this.dispatchEnvelope(this.stamp(op), options);
8558
+ }
8559
+ /**
8560
+ * Despacha um envelope já carimbado.
8561
+ *
8562
+ * É a porta por onde entra o que NÃO nasceu nesta aba: o motor de execução da
8563
+ * fase 4 e, um dia, o `pull` da colaboração. O filtro de captura compara o
8564
+ * `actorId` do envelope com o da sessão, e é por isso que a regra do autor
8565
+ * mora no envelope em vez de virar um parâmetro do despacho.
8566
+ */
8567
+ dispatchEnvelope(envelope2, options = {}) {
8568
+ const before = this.current;
8569
+ const ours = envelope2.clientId === this.options.session.clientId;
8570
+ const split = ours && options.unbounded !== true ? this.wireEnvelopes(envelope2) : [envelope2];
8571
+ const envelopes = split === null && this.envelopeListeners.size > 0 ? [envelope2] : split;
8572
+ if (envelopes === null) {
8573
+ const rejected = {
8574
+ code: "op-too-large",
8575
+ message: "Essa altera\xE7\xE3o \xE9 grande demais para ir de uma vez s\xF3 (mais de 64 KB numa opera\xE7\xE3o) e n\xE3o foi aplicada.",
8576
+ boardId: this.current.id,
8577
+ opId: envelope2.id
8578
+ };
8579
+ this.options.onError(rejected);
8580
+ return { envelope: envelope2, doc: before, changedNodeIds: [], entry: null, envelopes: [], rejected };
8581
+ }
8582
+ const capture = options.tracked === false ? null : trackCapture(before, envelope2, this.options.session.actorId);
8583
+ const applied = applyOps(before, [envelope2.op]);
8584
+ const entry = capture === null ? null : this.stack.capture(capture.op, capture.inverse, {
8585
+ groupId: options.groupId,
8586
+ amendLast: options.amendLast
8587
+ });
8588
+ if (envelope2.actorId !== null && envelope2.actorId !== this.options.session.actorId) {
8589
+ this.stack.invalidate(touchedPaths(envelope2.op));
8590
+ }
8591
+ this.current = applied.doc;
8592
+ this.last = envelope2;
8593
+ this.lastFromSync = false;
8594
+ for (const listener of this.envelopeListeners) for (const wire of envelopes) listener(wire);
8595
+ if (options.silent !== true && applied.doc !== before) this.notify();
8596
+ return {
8597
+ envelope: envelope2,
8598
+ doc: applied.doc,
8599
+ changedNodeIds: applied.changedNodeIds,
8600
+ entry,
8601
+ envelopes,
8602
+ rejected: null
8603
+ };
8604
+ }
8605
+ // ----------------------------------------------------------- sincronização
8606
+ /**
8607
+ * Assina os envelopes que ESTA aba aplicou pelo despacho (edição, desfazer,
8608
+ * refazer, soltar de arraste). É por aqui que o cliente de sincronização
8609
+ * (`transport/`) monta a fila de pendentes. Avisado só depois de o apply
8610
+ * passar: envelope que lançou nunca vira pendente.
8611
+ *
8612
+ * Sem assinante, o despacho se comporta exatamente como antes.
8613
+ */
8614
+ subscribeEnvelopes = (listener) => {
8615
+ this.envelopeListeners.add(listener);
8616
+ return () => {
8617
+ this.envelopeListeners.delete(listener);
8618
+ };
8619
+ };
8620
+ /**
8621
+ * Troca o documento inteiro pelo que a sincronização calculou (foto confirmada
8622
+ * + remotas + pendentes reaplicadas). Não entra no histórico, não avisa
8623
+ * `subscribeEnvelopes` (senão o remoto voltaria como pendente) e só notifica
8624
+ * quando a referência muda.
8625
+ */
8626
+ replaceDoc(doc) {
8627
+ if (doc === this.current) return;
8628
+ this.current = doc;
8629
+ this.lastFromSync = true;
8630
+ this.notify();
8631
+ }
8632
+ /**
8633
+ * O envelope como vai ao fio, em pedaços que cabem no teto.
8634
+ *
8635
+ * Cabe inteiro: sai como está, e é o caso de quase todo despacho. Não cabe e
8636
+ * é `batch`: os membros (com `batch` aninhado aberto, a ordem preservada) são
8637
+ * empacotados em envelopes consecutivos. Uma folha sozinha acima do teto não
8638
+ * tem como ir: devolve nulo, e o despacho é recusado inteiro.
8639
+ */
8640
+ wireEnvelopes(envelope2) {
8641
+ if (opEnvelopeBytes(envelope2) <= MAX_OP_BYTES2) return [envelope2];
8642
+ if (envelope2.op.type !== "batch") return null;
8643
+ const leaves = [];
8644
+ const open3 = (op) => {
8645
+ if (op.type === "batch") for (const inner of op.ops) open3(inner);
8646
+ else leaves.push(op);
8647
+ };
8648
+ open3(envelope2.op);
8649
+ const slack = 64;
8650
+ const overhead = opEnvelopeBytes({ ...envelope2, op: { type: "batch", ops: [] } }) + slack;
8651
+ const chunks = [];
8652
+ let chunk = [];
8653
+ let bytes = overhead;
8654
+ for (const leaf of leaves) {
8655
+ const size = utf8ByteLength(JSON.stringify(leaf));
8656
+ if (overhead + size > MAX_OP_BYTES2) return null;
8657
+ const added = chunk.length === 0 ? size : size + 1;
8658
+ if (chunk.length > 0 && bytes + added > MAX_OP_BYTES2) {
8659
+ chunks.push(chunk);
8660
+ chunk = [leaf];
8661
+ bytes = overhead + size;
8662
+ } else {
8663
+ chunk.push(leaf);
8664
+ bytes += added;
8665
+ }
8666
+ }
8667
+ if (chunk.length > 0) chunks.push(chunk);
8668
+ return chunks.map((ops, index) => ({
8669
+ ...envelope2,
8670
+ // O primeiro pedaço herda o id: é por ele que quem despachou reconhece o eco.
8671
+ id: index === 0 ? envelope2.id : this.newId(),
8672
+ op: ops.length === 1 ? ops[0] : { type: "batch", ops }
8673
+ }));
8674
+ }
8675
+ // -------------------------------------------------------- desfazer e refazer
8676
+ /**
8677
+ * Desfaz o último gesto.
8678
+ *
8679
+ * Cada inversa sai recarimbada com id novo e o `clientId` local, embrulhada em
8680
+ * `batch` quando a entrada juntou mais de um despacho, e despachada com
8681
+ * `{tracked:false}`. A entrada vai para a pilha de refazer inteira, do jeito
8682
+ * que estava.
8683
+ */
8684
+ undo() {
8685
+ const entry = this.stack.undo();
8686
+ if (entry === void 0) return { applied: false, changedNodeIds: [], envelope: null };
8687
+ if (entry.stale) return this.discard("desfazer");
8688
+ const result = this.replay(entry.inverse);
8689
+ if (!result.applied) this.stack.revertUndo(entry);
8690
+ return result;
8691
+ }
8692
+ /** Refaz o gesto desfeito mais recente, pelas operações originais e na ordem delas. */
8693
+ redo() {
8694
+ const entry = this.stack.redo();
8695
+ if (entry === void 0) return { applied: false, changedNodeIds: [], envelope: null };
8696
+ if (entry.stale) return this.discard("refazer");
8697
+ const result = this.replay(entry.ops);
8698
+ if (!result.applied) this.stack.revertRedo(entry);
8699
+ return result;
8700
+ }
8701
+ // ------------------------------------------------------------------ privados
8702
+ /** O passo velho sai da pilha sem tocar no documento, com aviso. */
8703
+ discard(verb) {
8704
+ this.options.onError({
8705
+ code: "undo-conflict",
8706
+ message: `Outra pessoa mexeu no mesmo lugar depois. Esse passo de ${verb} foi descartado para n\xE3o apagar o trabalho dela.`,
8707
+ boardId: this.current.id
8708
+ });
8709
+ this.notify();
8710
+ return { applied: false, changedNodeIds: [], envelope: null, discarded: true };
8711
+ }
8712
+ /** Despacha uma lista guardada na pilha, sem deixá-la voltar para a pilha. */
8713
+ replay(ops) {
8714
+ const result = this.dispatch(batchOf2(ops), { tracked: false });
8715
+ if (result.rejected !== null) return { applied: false, changedNodeIds: [], envelope: null };
8716
+ return { applied: true, changedNodeIds: result.changedNodeIds, envelope: result.envelope };
8717
+ }
8718
+ /** O envelope de uma operação nossa. `seq` nasce nulo: quem confirma é o commit. */
8719
+ stamp(op) {
8720
+ return {
8721
+ id: this.newId(),
8722
+ boardId: this.current.id,
8723
+ clientId: this.options.session.clientId,
8724
+ actorId: this.options.session.actorId,
8725
+ seq: null,
8726
+ ts: this.clock(),
8727
+ op
8728
+ };
8729
+ }
8730
+ notify() {
8731
+ for (const listener of this.listeners) listener();
8732
+ }
8733
+ };
8734
+ function resolveGap(gap) {
8735
+ return typeof gap === "number" ? { x: gap, y: gap } : { x: gap.x, y: gap.y };
8736
+ }
8737
+ function rectOf2(node) {
8738
+ return { x: node.position.x, y: node.position.y, w: node.size.w, h: node.size.h };
8739
+ }
8740
+ function rectsCollide(a, b, gap) {
8741
+ return a.x < b.x + b.w + gap.x && b.x < a.x + a.w + gap.x && a.y < b.y + b.h + gap.y && b.y < a.y + a.h + gap.y;
8742
+ }
8743
+ function boundsOf(rects) {
8744
+ let minX = Number.POSITIVE_INFINITY;
8745
+ let minY = Number.POSITIVE_INFINITY;
8746
+ let maxX = Number.NEGATIVE_INFINITY;
8747
+ let maxY = Number.NEGATIVE_INFINITY;
8748
+ for (const rect of rects) {
8749
+ minX = Math.min(minX, rect.x);
8750
+ minY = Math.min(minY, rect.y);
8751
+ maxX = Math.max(maxX, rect.x + rect.w);
8752
+ maxY = Math.max(maxY, rect.y + rect.h);
8753
+ }
8754
+ if (rects.length === 0) return { x: 0, y: 0, w: 0, h: 0 };
8755
+ return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
8756
+ }
8757
+ function compareText(a, b) {
8758
+ return a < b ? -1 : a > b ? 1 : 0;
8759
+ }
8760
+ function byScreenOrder(a, b) {
8761
+ return a.position.y - b.position.y || a.position.x - b.position.x || compareText(a.id, b.id);
8762
+ }
8763
+ function obstaclesOf(doc, ignore = []) {
8764
+ const skipped = new Set(ignore);
8765
+ return Object.values(doc.nodes).filter((node) => node.parentId === null && !skipped.has(node.id)).sort(byScreenOrder).map(rectOf2);
8766
+ }
8767
+ var DEFAULT_MAX_PER_COLUMN = 8;
8768
+ function positiveInt(value, fallback) {
8769
+ if (value === void 0 || !Number.isFinite(value)) return fallback;
8770
+ return Math.max(1, Math.floor(value));
8771
+ }
8772
+ function fanOutPositions(input) {
8773
+ const count = Number.isFinite(input.count) ? Math.floor(input.count) : 0;
8774
+ if (count < 1) return [];
8775
+ const gap = resolveGap(input.gap);
8776
+ const maxPerColumn = positiveInt(input.maxPerColumn, DEFAULT_MAX_PER_COLUMN);
8777
+ const columns = Math.min(count, positiveInt(input.columns, Math.ceil(count / maxPerColumn)));
8778
+ const rows = Math.ceil(count / columns);
8779
+ const { position, size } = input.source;
8780
+ const blockHeight = rows * input.nodeSize.h + (rows - 1) * gap.y;
8781
+ const left = Math.round(position.x + size.w + gap.x);
8782
+ const top = Math.round(position.y + size.h / 2 - blockHeight / 2);
8783
+ const positions = [];
8784
+ for (let index = 0; index < count; index += 1) {
8785
+ const column = index % columns;
8786
+ const row = Math.floor(index / columns);
8787
+ positions.push({
8788
+ x: left + column * (input.nodeSize.w + gap.x),
8789
+ y: top + row * (input.nodeSize.h + gap.y)
8790
+ });
8791
+ }
8792
+ return positions;
8793
+ }
8794
+ var DEFAULT_PLACEMENT_GAP = 40;
8795
+ function uniqueAscending(values) {
8796
+ return [...new Set(values)].sort((a, b) => a - b);
8797
+ }
8798
+ function blockIsFree(rects, bounds, dx, dy, obstacles, gap) {
8799
+ const movedBounds = { ...bounds, x: bounds.x + dx, y: bounds.y + dy };
8800
+ for (const obstacle of obstacles) {
8801
+ if (!rectsCollide(movedBounds, obstacle, gap)) continue;
8802
+ for (const rect of rects) {
8803
+ if (rectsCollide({ ...rect, x: rect.x + dx, y: rect.y + dy }, obstacle, gap)) return false;
8804
+ }
8805
+ }
8806
+ return true;
8807
+ }
8808
+ function placeWithoutOverlap(doc, rects, options) {
8809
+ if (rects.length === 0) return [];
8810
+ const gap = resolveGap(options.gap);
8811
+ const original = boundsOf(rects);
8812
+ const baseDx = options.near === void 0 ? 0 : options.near.x - original.x;
8813
+ const baseDy = options.near === void 0 ? 0 : options.near.y - original.y;
8814
+ const block = rects.map((rect) => ({ ...rect, x: rect.x + baseDx, y: rect.y + baseDy }));
8815
+ const bounds = boundsOf(block);
8816
+ const obstacles = obstaclesOf(doc, options.ignore);
8817
+ const maxDown = options.maxDown ?? 3 * (bounds.h + gap.y);
8818
+ const rightSteps = uniqueAscending([
8819
+ 0,
8820
+ ...obstacles.map((o) => o.x + o.w + gap.x - bounds.x).filter((dx) => dx > 0)
8821
+ ]);
8822
+ const downSteps = uniqueAscending([
8823
+ 0,
8824
+ ...obstacles.map((o) => o.y + o.h + gap.y - bounds.y).filter((dy) => dy > 0 && dy <= maxDown)
8825
+ ]);
8826
+ for (const dx of rightSteps) {
8827
+ for (const dy of downSteps) {
8828
+ if (blockIsFree(block, bounds, dx, dy, obstacles, gap)) {
8829
+ return block.map((rect) => ({ ...rect, x: rect.x + dx, y: rect.y + dy }));
8830
+ }
8831
+ }
8832
+ }
8833
+ return block;
8834
+ }
8835
+ function byDistance(a, b) {
8836
+ return a.distance - b.distance || b.y - a.y || b.x - a.x;
8837
+ }
8838
+ function findFreeSpot(doc, size, near, options = {}) {
8839
+ const gap = resolveGap(options.gap ?? DEFAULT_PLACEMENT_GAP);
8840
+ const obstacles = obstaclesOf(doc, options.ignore);
8841
+ const xs = uniqueAscending([
8842
+ near.x,
8843
+ ...obstacles.flatMap((o) => [o.x + o.w + gap.x, o.x - gap.x - size.w])
8844
+ ]);
8845
+ const candidates = xs.map((x) => {
8846
+ const blocked = obstacles.filter((o) => x < o.x + o.w + gap.x && o.x < x + size.w + gap.x).map((o) => ({ from: o.y - gap.y - size.h, to: o.y + o.h + gap.y })).sort((a, b) => a.from - b.from);
8847
+ let y = near.y;
8848
+ let wall;
8849
+ for (const interval of blocked) {
8850
+ if (wall !== void 0 && interval.from < wall.to) {
8851
+ wall.to = Math.max(wall.to, interval.to);
8852
+ } else if (wall !== void 0 && wall.from < near.y && near.y < wall.to) {
8853
+ break;
8854
+ } else {
8855
+ wall = { ...interval };
8856
+ }
8857
+ }
8858
+ if (wall !== void 0 && wall.from < near.y && near.y < wall.to) {
8859
+ y = wall.to - near.y <= near.y - wall.from ? wall.to : wall.from;
8860
+ }
8861
+ return { x, y, distance: Math.hypot(x - near.x, y - near.y) };
8862
+ });
8863
+ const [best] = candidates.sort(byDistance);
8864
+ if (best === void 0) return { x: near.x, y: near.y };
8865
+ return { x: best.x, y: best.y };
8866
+ }
8867
+ function topLevelOf(doc, nodeId3) {
8868
+ const seen = /* @__PURE__ */ new Set();
8869
+ let current = nodeId3;
8870
+ for (; ; ) {
8871
+ if (seen.has(current) || !Object.hasOwn(doc.nodes, current)) return void 0;
8872
+ seen.add(current);
8873
+ const node = doc.nodes[current];
8874
+ if (node === void 0) return void 0;
8875
+ if (node.parentId === null) return current;
8876
+ current = node.parentId;
8877
+ }
8878
+ }
8879
+ function pushTo(map, key, value) {
8880
+ const list = map.get(key);
8881
+ if (list === void 0) map.set(key, [value]);
8882
+ else if (!list.includes(value)) list.push(value);
8883
+ }
8884
+ function buildLayoutGraph(doc, nodeIds) {
8885
+ const wanted = nodeIds === void 0 ? void 0 : new Set(nodeIds);
8886
+ const nodes = Object.values(doc.nodes).filter((node) => node.parentId === null && (wanted === void 0 || wanted.has(node.id))).sort(byScreenOrder);
8887
+ const rank = new Map(nodes.map((node, index) => [node.id, index]));
8888
+ const byRank = (a, b) => (rank.get(a) ?? 0) - (rank.get(b) ?? 0);
8889
+ const forward = /* @__PURE__ */ new Map();
8890
+ const neighbors = /* @__PURE__ */ new Map();
8891
+ for (const node of nodes) {
8892
+ forward.set(node.id, []);
8893
+ neighbors.set(node.id, []);
8894
+ }
8895
+ const branchSiblings = /* @__PURE__ */ new Map();
8896
+ const inputSiblings = /* @__PURE__ */ new Map();
8897
+ const edgeIds = Object.keys(doc.edges).sort(compareText);
8898
+ for (const edgeId of edgeIds) {
8899
+ const edge = doc.edges[edgeId];
8900
+ if (edge === void 0) continue;
8901
+ const source = topLevelOf(doc, edge.source);
8902
+ const target = topLevelOf(doc, edge.target);
8903
+ if (source === void 0 || target === void 0 || source === target) continue;
8904
+ if (!rank.has(source) || !rank.has(target)) continue;
8905
+ pushTo(forward, source, target);
8906
+ pushTo(neighbors, source, target);
8907
+ pushTo(neighbors, target, source);
8908
+ if (typeof edge.data["branch"] !== "number") {
8909
+ pushTo(branchSiblings, `${edge.source}\0${edge.sourcePort}`, target);
8910
+ }
8911
+ if (typeof edge.data["order"] !== "number") {
8912
+ pushTo(inputSiblings, `${edge.target}\0${edge.targetPort}`, source);
8913
+ }
8914
+ }
8915
+ for (const list of forward.values()) list.sort(byRank);
8916
+ for (const list of neighbors.values()) list.sort(byRank);
8917
+ const successors = withoutBackEdges(nodes, forward);
8918
+ const predecessors = new Map(nodes.map((node) => [node.id, []]));
8919
+ for (const node of nodes) {
8920
+ for (const target of successors.get(node.id) ?? []) predecessors.get(target)?.push(node.id);
8921
+ }
8922
+ const orderedSiblings = [...branchSiblings.values(), ...inputSiblings.values()].filter((group) => group.length > 1).map((group) => [...group].sort(byRank));
8923
+ return { nodes, rank, successors, predecessors, neighbors, orderedSiblings };
8924
+ }
8925
+ function withoutBackEdges(nodes, forward) {
8926
+ const hasIncoming = /* @__PURE__ */ new Set();
8927
+ for (const targets of forward.values()) for (const target of targets) hasIncoming.add(target);
8928
+ const starts = [
8929
+ ...nodes.filter((node) => !hasIncoming.has(node.id)),
8930
+ ...nodes.filter((node) => hasIncoming.has(node.id)).sort(
8931
+ (a, b) => a.position.x - b.position.x || a.position.y - b.position.y || compareText(a.id, b.id)
8932
+ )
8933
+ ];
8934
+ const kept = new Map(nodes.map((node) => [node.id, []]));
8935
+ const state = /* @__PURE__ */ new Map();
8936
+ for (const start of starts) {
8937
+ if (state.has(start.id)) continue;
8938
+ const stack = [{ id: start.id, next: 0 }];
8939
+ state.set(start.id, "open");
8940
+ for (let frame = stack[stack.length - 1]; frame !== void 0; frame = stack[stack.length - 1]) {
8941
+ const targets = forward.get(frame.id) ?? [];
8942
+ const target = targets[frame.next];
8943
+ if (target === void 0) {
8944
+ state.set(frame.id, "done");
8945
+ stack.pop();
8946
+ continue;
8947
+ }
8948
+ frame.next += 1;
8949
+ const seen = state.get(target);
8950
+ if (seen === "open") continue;
8951
+ kept.get(frame.id)?.push(target);
8952
+ if (seen === void 0) {
8953
+ state.set(target, "open");
8954
+ stack.push({ id: target, next: 0 });
8955
+ }
8956
+ }
8957
+ }
8958
+ return kept;
8959
+ }
8960
+ function assignLayers(graph, ids) {
8961
+ const pending = /* @__PURE__ */ new Map();
8962
+ for (const id of ids) pending.set(id, graph.predecessors.get(id)?.length ?? 0);
8963
+ const layer = /* @__PURE__ */ new Map();
8964
+ const queue = ids.filter((id) => pending.get(id) === 0);
8965
+ for (const id of queue) layer.set(id, 0);
8966
+ for (let head = 0; head < queue.length; head += 1) {
8967
+ const id = queue[head];
8968
+ if (id === void 0) continue;
8969
+ const current = layer.get(id) ?? 0;
8970
+ for (const target of graph.successors.get(id) ?? []) {
8971
+ layer.set(target, Math.max(layer.get(target) ?? 0, current + 1));
8972
+ const left = (pending.get(target) ?? 0) - 1;
8973
+ pending.set(target, left);
8974
+ if (left === 0) queue.push(target);
8975
+ }
8976
+ }
8977
+ for (const id of ids) {
8978
+ const targets = graph.successors.get(id) ?? [];
8979
+ if ((graph.predecessors.get(id)?.length ?? 0) > 0 || targets.length === 0) continue;
8980
+ layer.set(id, Math.min(...targets.map((target) => layer.get(target) ?? 1)) - 1);
8981
+ }
8982
+ return layer;
8983
+ }
8984
+ function splitComponents(graph) {
8985
+ const components = [];
8986
+ const isolated = [];
8987
+ const visited = /* @__PURE__ */ new Set();
8988
+ for (const node of graph.nodes) {
8989
+ if (visited.has(node.id)) continue;
8990
+ visited.add(node.id);
8991
+ if ((graph.neighbors.get(node.id)?.length ?? 0) === 0) {
8992
+ isolated.push(node.id);
8993
+ continue;
8994
+ }
8995
+ const members = [node.id];
8996
+ for (let head = 0; head < members.length; head += 1) {
8997
+ const id = members[head];
8998
+ if (id === void 0) continue;
8999
+ for (const next of graph.neighbors.get(id) ?? []) {
9000
+ if (visited.has(next)) continue;
9001
+ visited.add(next);
9002
+ members.push(next);
9003
+ }
9004
+ }
9005
+ members.sort((a, b) => (graph.rank.get(a) ?? 0) - (graph.rank.get(b) ?? 0));
9006
+ components.push(members);
9007
+ }
9008
+ return { components, isolated };
9009
+ }
9010
+ function countCrossings(graph, layers) {
9011
+ let crossings = 0;
9012
+ for (let index = 0; index + 1 < layers.length; index += 1) {
9013
+ const left = layers[index] ?? [];
9014
+ const right = new Map((layers[index + 1] ?? []).map((id, slot) => [id, slot]));
9015
+ const spans = [];
9016
+ left.forEach((id, slot) => {
9017
+ for (const target of graph.successors.get(id) ?? []) {
9018
+ const targetSlot = right.get(target);
9019
+ if (targetSlot !== void 0) spans.push([slot, targetSlot]);
9020
+ }
9021
+ });
9022
+ for (let a = 0; a < spans.length; a += 1) {
9023
+ for (let b = a + 1; b < spans.length; b += 1) {
9024
+ const first = spans[a];
9025
+ const second = spans[b];
9026
+ if (first === void 0 || second === void 0) continue;
9027
+ if ((first[0] - second[0]) * (first[1] - second[1]) < 0) crossings += 1;
9028
+ }
9029
+ }
9030
+ }
9031
+ return crossings;
9032
+ }
9033
+ function reorderLayer(layer, reference, neighborsOf) {
9034
+ const slotOf = new Map(reference.map((id, slot) => [id, slot]));
9035
+ const weight = /* @__PURE__ */ new Map();
9036
+ for (const id of layer) {
9037
+ const slots = neighborsOf(id).flatMap((neighbor) => {
9038
+ const slot = slotOf.get(neighbor);
9039
+ return slot === void 0 ? [] : [slot];
9040
+ });
9041
+ if (slots.length > 0) weight.set(id, slots.reduce((sum, slot) => sum + slot, 0) / slots.length);
9042
+ }
9043
+ const current = new Map(layer.map((id, slot) => [id, slot]));
9044
+ const movable = layer.filter((id) => weight.has(id)).sort(
9045
+ (a, b) => (weight.get(a) ?? 0) - (weight.get(b) ?? 0) || (current.get(a) ?? 0) - (current.get(b) ?? 0)
9046
+ );
9047
+ let next = 0;
9048
+ return layer.map((id) => weight.has(id) ? movable[next++] ?? id : id);
9049
+ }
9050
+ function restoreSiblingOrder(graph, layer) {
9051
+ const result = [...layer];
9052
+ for (const group of graph.orderedSiblings) {
9053
+ const members = new Set(group);
9054
+ const slots = [];
9055
+ result.forEach((id, slot) => {
9056
+ if (members.has(id)) slots.push(slot);
9057
+ });
9058
+ if (slots.length < 2) continue;
9059
+ const present = group.filter((id) => result.includes(id));
9060
+ slots.forEach((slot, index) => {
9061
+ const id = present[index];
9062
+ if (id !== void 0) result[slot] = id;
9063
+ });
9064
+ }
9065
+ return result;
9066
+ }
9067
+ function orderLayers(graph, initial, sweeps) {
9068
+ let layers = initial.map((layer) => [...layer]);
9069
+ let best = layers;
9070
+ let bestCrossings = countCrossings(graph, layers);
9071
+ for (let pass = 0; pass < sweeps && bestCrossings > 0; pass += 1) {
9072
+ const forward = pass % 2 === 0;
9073
+ const next = layers.map((layer) => [...layer]);
9074
+ const order = next.map((_, index) => index);
9075
+ if (!forward) order.reverse();
9076
+ for (const index of order) {
9077
+ const reference = next[forward ? index - 1 : index + 1];
9078
+ const layer = next[index];
9079
+ if (reference === void 0 || layer === void 0) continue;
9080
+ const neighborsOf = (id) => (forward ? graph.predecessors.get(id) : graph.successors.get(id)) ?? [];
9081
+ next[index] = restoreSiblingOrder(graph, reorderLayer(layer, reference, neighborsOf));
9082
+ }
9083
+ layers = next;
9084
+ const crossings = countCrossings(graph, layers);
9085
+ if (crossings < bestCrossings) {
9086
+ best = layers;
9087
+ bestCrossings = crossings;
9088
+ }
9089
+ }
9090
+ return best;
9091
+ }
9092
+ var DEFAULT_TIDY_GAP_X = 120;
9093
+ var DEFAULT_TIDY_GAP_Y = 48;
9094
+ var DEFAULT_TIDY_SWEEPS = 4;
9095
+ function layoutComponent(doc, graph, members, gapX, gapY, sweeps) {
9096
+ const layerOf = assignLayers(graph, members);
9097
+ const initial = [];
9098
+ for (const id of members) {
9099
+ const index = layerOf.get(id) ?? 0;
9100
+ (initial[index] ??= []).push(id);
9101
+ }
9102
+ const layers = orderLayers(
9103
+ graph,
9104
+ Array.from(initial, (layer) => layer ?? []).filter((layer) => layer.length > 0),
9105
+ sweeps
9106
+ );
9107
+ const columns = layers.map((layer) => {
9108
+ const nodes = layer.flatMap((id) => {
9109
+ const node = doc.nodes[id];
9110
+ return node === void 0 ? [] : [node];
9111
+ });
9112
+ const width2 = Math.max(...nodes.map((node) => node.size.w));
9113
+ const height = nodes.reduce((sum, node) => sum + node.size.h, 0) + (nodes.length - 1) * gapY;
9114
+ return { nodes, width: width2, height };
9115
+ });
9116
+ const tallest = Math.max(...columns.map((column) => column.height));
9117
+ const placed = [];
9118
+ let x = 0;
9119
+ for (const column of columns) {
9120
+ let y = Math.round((tallest - column.height) / 2);
9121
+ for (const node of column.nodes) {
9122
+ placed.push({ id: node.id, rect: { x, y, w: node.size.w, h: node.size.h } });
9123
+ y += node.size.h + gapY;
9124
+ }
9125
+ x += column.width + gapX;
9126
+ }
9127
+ return placed;
9128
+ }
9129
+ function layoutStrip(nodes, width2, gapX, gapY) {
9130
+ const placed = [];
9131
+ let x = 0;
9132
+ let y = 0;
9133
+ let shelfHeight = 0;
9134
+ for (const node of nodes) {
9135
+ if (x > 0 && x + node.size.w > width2) {
9136
+ x = 0;
9137
+ y += shelfHeight + gapY;
9138
+ shelfHeight = 0;
9139
+ }
9140
+ placed.push({ id: node.id, rect: { x, y, w: node.size.w, h: node.size.h } });
9141
+ x += node.size.w + gapX;
9142
+ shelfHeight = Math.max(shelfHeight, node.size.h);
9143
+ }
9144
+ return placed;
9145
+ }
9146
+ function shifted(placed, dx, dy) {
9147
+ return placed.map(({ id, rect }) => ({ id, rect: { ...rect, x: rect.x + dx, y: rect.y + dy } }));
9148
+ }
9149
+ function tidyUp(doc, options = {}) {
9150
+ const gapX = options.gapX ?? DEFAULT_TIDY_GAP_X;
9151
+ const gapY = options.gapY ?? DEFAULT_TIDY_GAP_Y;
9152
+ const componentGap = options.componentGap ?? gapY * 2;
9153
+ const sweeps = options.sweeps ?? DEFAULT_TIDY_SWEEPS;
9154
+ const graph = buildLayoutGraph(doc, options.nodeIds);
9155
+ if (graph.nodes.length === 0) return /* @__PURE__ */ new Map();
9156
+ const { components, isolated } = splitComponents(graph);
9157
+ let placed = [];
9158
+ let cursorY = 0;
9159
+ let widest = 0;
9160
+ for (const members of components) {
9161
+ const block = layoutComponent(doc, graph, members, gapX, gapY, sweeps);
9162
+ const bounds = boundsOf(block.map((item) => item.rect));
9163
+ placed = placed.concat(shifted(block, 0, cursorY));
9164
+ cursorY += bounds.h + componentGap;
9165
+ widest = Math.max(widest, bounds.w);
9166
+ }
9167
+ if (isolated.length > 0) {
9168
+ const loose = graph.nodes.filter((node) => isolated.includes(node.id));
9169
+ const area = loose.reduce((sum, node) => sum + (node.size.w + gapX) * (node.size.h + gapY), 0);
9170
+ const stripWidth = Math.max(widest, Math.sqrt(area * 1.6));
9171
+ placed = placed.concat(shifted(layoutStrip(loose, stripWidth, gapX, gapY), 0, cursorY));
9172
+ }
9173
+ const anchor = boundsOf(graph.nodes.map(rectOf2));
9174
+ const anchored = shifted(placed, Math.round(anchor.x), Math.round(anchor.y));
9175
+ const scope = graph.nodes.map((node) => node.id);
9176
+ const others = obstaclesOf(doc, scope);
9177
+ const touching = { x: 0, y: 0 };
9178
+ const covers = anchored.some(
9179
+ ({ rect }) => others.some((other) => rectsCollide(rect, other, touching))
9180
+ );
9181
+ const rects = covers ? placeWithoutOverlap(
9182
+ doc,
9183
+ anchored.map((item) => item.rect),
9184
+ { gap: { x: gapX, y: gapY }, ignore: scope }
9185
+ ) : anchored.map((item) => item.rect);
9186
+ const positions = /* @__PURE__ */ new Map();
9187
+ anchored.forEach(({ id }, index) => {
9188
+ const rect = rects[index];
9189
+ if (rect !== void 0) positions.set(id, { x: rect.x, y: rect.y });
9190
+ });
9191
+ return positions;
9192
+ }
9193
+ function moveOps(positions) {
9194
+ const latest = /* @__PURE__ */ new Map();
9195
+ for (const [nodeId3, point2] of positions) latest.set(nodeId3, point2);
9196
+ const ops = [...latest.keys()].sort(compareText).flatMap((nodeId3) => {
9197
+ const point2 = latest.get(nodeId3);
9198
+ if (point2 === void 0) return [];
9199
+ return [
9200
+ { type: "node.set", nodeId: nodeId3, path: "position", value: propValue({ x: point2.x, y: point2.y }) }
9201
+ ];
9202
+ });
9203
+ return { type: "batch", ops };
9204
+ }
9205
+ function tidyUpOps(doc, options = {}) {
9206
+ const moved = [...tidyUp(doc, options)].filter(([nodeId3, point2]) => {
9207
+ const node = doc.nodes[nodeId3];
9208
+ return node !== void 0 && (node.position.x !== point2.x || node.position.y !== point2.y);
9209
+ });
9210
+ return moveOps(moved);
9211
+ }
9212
+ var MAX_REPLAY = 200;
9213
+ function tryApplyOp(doc, op) {
9214
+ const result = step(doc, op);
9215
+ return typeof result === "string" ? { ok: false, reason: result } : { ok: true, doc: result };
9216
+ }
9217
+ function tryApplyEnvelope(doc, envelope2) {
9218
+ if (opEnvelopeBytes(envelope2) > MAX_OP_BYTES2) return { ok: false, reason: "too-large" };
9219
+ return tryApplyOp(doc, envelope2.op);
9220
+ }
9221
+ function applyConfirmed2(doc, envelope2) {
9222
+ if (envelope2.seq === null) {
9223
+ throw new Error(`applyConfirmed recebeu o envelope ${envelope2.id} sem seq`);
9224
+ }
9225
+ const next = applyOps(doc, [envelope2.op]).doc;
9226
+ return { ...next, version: envelope2.seq };
9227
+ }
9228
+ function step(doc, op) {
9229
+ switch (op.type) {
9230
+ case "batch": {
9231
+ let current = doc;
9232
+ for (const inner of op.ops) {
9233
+ const result = step(current, inner);
9234
+ if (typeof result === "string") return result;
9235
+ current = result;
9236
+ }
9237
+ return current;
9238
+ }
9239
+ case "node.set":
9240
+ case "history.append":
9241
+ if (doc.nodes[op.nodeId] === void 0) return "node-missing";
9242
+ break;
9243
+ case "edge.add":
9244
+ if (doc.nodes[op.edge.source] === void 0 || doc.nodes[op.edge.target] === void 0) {
9245
+ return "edge-endpoint-missing";
9246
+ }
9247
+ break;
9248
+ default:
9249
+ break;
9250
+ }
9251
+ try {
9252
+ return applyOps(doc, [op]).doc;
9253
+ } catch {
9254
+ return "invalid-op";
9255
+ }
9256
+ }
9257
+ function defaultScheduler() {
9258
+ const host = globalThis;
9259
+ return {
9260
+ setTimeout: (callback, ms) => host.setTimeout(callback, ms),
9261
+ clearTimeout: (handle) => host.clearTimeout(handle)
9262
+ };
9263
+ }
9264
+ var OpSyncClient = class {
9265
+ store;
9266
+ transport;
9267
+ scheduler;
9268
+ batchMs;
9269
+ gapGraceMs;
9270
+ retryMs;
9271
+ maxRetryMs;
9272
+ maxBatch;
9273
+ onDiscard;
9274
+ onTransportError;
9275
+ confirmed;
9276
+ lastSeq;
9277
+ buffer = /* @__PURE__ */ new Map();
9278
+ pending = [];
9279
+ online = false;
9280
+ started = false;
9281
+ stopped = false;
9282
+ commitInFlight = false;
9283
+ syncInFlight = false;
9284
+ snapshotInFlight = false;
9285
+ flushTimer = null;
9286
+ gapTimer = null;
9287
+ retryTimer = null;
9288
+ retryDelay;
9289
+ unsubscribe = [];
9290
+ stats = {
9291
+ commits: 0,
9292
+ commitFailures: 0,
9293
+ syncs: 0,
9294
+ gapSyncs: 0,
9295
+ snapshots: 0,
9296
+ discarded: 0,
9297
+ echoes: 0
9298
+ };
9299
+ constructor(options) {
9300
+ this.store = options.store;
9301
+ this.transport = options.transport;
9302
+ this.scheduler = options.scheduler ?? defaultScheduler();
9303
+ this.batchMs = options.batchMs ?? 200;
9304
+ this.gapGraceMs = options.gapGraceMs ?? 300;
9305
+ this.retryMs = options.retryMs ?? 1e3;
9306
+ this.maxRetryMs = options.maxRetryMs ?? 3e4;
9307
+ this.maxBatch = options.maxBatch ?? 100;
9308
+ this.onDiscard = options.onDiscard;
9309
+ this.onTransportError = options.onTransportError;
9310
+ this.retryDelay = this.retryMs;
9311
+ this.lastSeq = options.seq;
9312
+ this.confirmed = { ...this.store.getDoc(), version: options.seq };
9313
+ }
9314
+ /** Entra na sala, passa a ouvir o store e pede o que perdeu desde `seq`. */
9315
+ start() {
9316
+ if (this.started) return;
9317
+ this.started = true;
9318
+ this.unsubscribe.push(
9319
+ this.store.subscribeEnvelopes((envelope2) => this.enqueue(envelope2)),
9320
+ this.transport.subscribe({
9321
+ onOps: (envelopes) => this.receive(envelopes),
9322
+ onResync: () => this.requestSnapshot(),
9323
+ onConnectionChange: (online) => this.setOnline(online)
9324
+ })
9325
+ );
9326
+ this.online = this.transport.isOnline();
9327
+ if (this.online) this.requestSync();
9328
+ }
9329
+ /** Sai da sala e para os relógios. Pendentes ficam onde estão (`pendingEnvelopes`). */
9330
+ stop() {
9331
+ this.stopped = true;
9332
+ for (const off of this.unsubscribe) off();
9333
+ this.unsubscribe = [];
9334
+ this.clearTimer("flushTimer");
9335
+ this.clearTimer("gapTimer");
9336
+ this.clearTimer("retryTimer");
9337
+ }
9338
+ /** Commita já, sem esperar a janela do lote. */
9339
+ flushNow() {
9340
+ this.clearTimer("flushTimer");
9341
+ this.flush();
9342
+ }
9343
+ getStatus() {
9344
+ const inFlight = this.pending.filter((item) => item.inFlight).length;
9345
+ return {
9346
+ online: this.online,
9347
+ lastSeq: this.lastSeq,
9348
+ pending: this.pending.length,
9349
+ inFlight,
9350
+ buffered: this.buffer.size,
9351
+ settled: this.pending.length === 0 && this.buffer.size === 0 && !this.commitInFlight && !this.syncInFlight && !this.snapshotInFlight
9352
+ };
9353
+ }
9354
+ /** A foto confirmada, sem pendentes. */
9355
+ getConfirmedDoc() {
9356
+ return this.confirmed;
9357
+ }
9358
+ /** As pendentes, em ordem. Para o cache local guardar até voltarem. */
9359
+ pendingEnvelopes() {
9360
+ return this.pending.map((item) => item.envelope);
9361
+ }
9362
+ // ------------------------------------------------------------------ entrada
9363
+ enqueue(envelope2) {
9364
+ if (this.stopped) return;
9365
+ if (opEnvelopeBytes(envelope2) > MAX_OP_BYTES2) {
9366
+ this.discard(envelope2, "too-large", "too-large");
9367
+ this.rebuild();
9368
+ return;
9369
+ }
9370
+ this.pending.push({ envelope: envelope2, sent: false, inFlight: false });
9371
+ this.scheduleFlush();
9372
+ }
9373
+ receive(envelopes) {
9374
+ if (this.stopped) return;
9375
+ let changed = false;
9376
+ for (const envelope2 of envelopes) {
9377
+ if (envelope2.seq === null) continue;
9378
+ if (this.findPending(envelope2.id) >= 0) this.stats.echoes += 1;
9379
+ if (this.confirm(envelope2.id, envelope2.seq, envelope2)) changed = true;
9380
+ }
9381
+ if (changed) this.settle();
9382
+ else this.checkGap();
9383
+ }
9384
+ /**
9385
+ * Registra que `opId` foi confirmado com `seq`. Se é pendente nossa, sai da
9386
+ * fila (eco, resposta do commit ou replay: tanto faz qual chega primeiro).
9387
+ * Devolve se algo mudou.
9388
+ */
9389
+ confirm(opId, seq, wire) {
9390
+ const index = this.findPending(opId);
9391
+ let envelope2 = wire;
9392
+ if (index >= 0) {
9393
+ const [item] = this.pending.splice(index, 1);
9394
+ envelope2 = item?.envelope;
9395
+ }
9396
+ if (seq <= this.lastSeq) return index >= 0;
9397
+ if (envelope2 === void 0) return index >= 0;
9398
+ if (!this.buffer.has(seq)) this.buffer.set(seq, { ...envelope2, seq });
9399
+ return true;
9400
+ }
9401
+ // ---------------------------------------------------------------- commit
9402
+ scheduleFlush() {
9403
+ if (this.flushTimer !== null || this.stopped) return;
9404
+ this.flushTimer = this.scheduler.setTimeout(() => {
9405
+ this.flushTimer = null;
9406
+ this.flush();
9407
+ }, this.batchMs);
9408
+ }
9409
+ flush() {
9410
+ if (this.stopped || !this.online || this.commitInFlight) return;
9411
+ const batch = this.pending.slice(0, this.maxBatch);
9412
+ if (batch.length === 0) return;
9413
+ for (const item of batch) {
9414
+ item.sent = true;
9415
+ item.inFlight = true;
9416
+ }
9417
+ this.commitInFlight = true;
9418
+ this.stats.commits += 1;
9419
+ this.transport.commit(batch.map((item) => item.envelope)).then(
9420
+ (response) => this.onCommitted(batch, response),
9421
+ (error2) => this.onCommitFailed(batch, error2)
9422
+ );
9423
+ }
9424
+ onCommitted(batch, response) {
9425
+ this.commitInFlight = false;
9426
+ for (const item of batch) item.inFlight = false;
9427
+ if (this.stopped) return;
9428
+ this.retryDelay = this.retryMs;
9429
+ let changed = false;
9430
+ for (const outcome of response.outcomes) {
9431
+ if ("seq" in outcome) {
9432
+ if (this.confirm(outcome.opId, outcome.seq)) changed = true;
9433
+ } else {
9434
+ const index = this.findPending(outcome.opId);
9435
+ if (index < 0) continue;
9436
+ const [item] = this.pending.splice(index, 1);
9437
+ if (item !== void 0) this.discard(item.envelope, "rejected", outcome.rejected);
9438
+ changed = true;
9439
+ }
9440
+ }
9441
+ if (changed) this.settle();
9442
+ if (this.pending.length > 0) this.flush();
9443
+ }
9444
+ onCommitFailed(batch, error2) {
9445
+ this.commitInFlight = false;
9446
+ for (const item of batch) item.inFlight = false;
9447
+ if (this.stopped) return;
9448
+ this.stats.commitFailures += 1;
9449
+ this.onTransportError?.(error2);
9450
+ this.scheduleRetry();
9451
+ }
9452
+ // ------------------------------------------------------- sync e foto
9453
+ requestSync() {
9454
+ if (this.stopped || !this.online || this.syncInFlight) return;
9455
+ this.syncInFlight = true;
9456
+ this.stats.syncs += 1;
9457
+ this.transport.sync(this.lastSeq).then(
9458
+ (response) => this.onSynced(response),
9459
+ (error2) => {
9460
+ this.syncInFlight = false;
9461
+ if (this.stopped) return;
9462
+ this.onTransportError?.(error2);
9463
+ this.scheduleRetry();
9464
+ }
9465
+ );
9466
+ }
9467
+ onSynced(response) {
9468
+ this.syncInFlight = false;
9469
+ if (this.stopped) return;
9470
+ if (response.status === "resync") {
9471
+ this.requestSnapshot();
9472
+ return;
9473
+ }
9474
+ this.receive(response.envelopes);
9475
+ }
9476
+ requestSnapshot() {
9477
+ if (this.stopped || !this.online || this.snapshotInFlight) return;
9478
+ this.snapshotInFlight = true;
9479
+ this.stats.snapshots += 1;
9480
+ this.transport.snapshot().then(
9481
+ (snapshot) => {
9482
+ this.snapshotInFlight = false;
9483
+ if (this.stopped) return;
9484
+ if (snapshot.seq < this.lastSeq) return;
9485
+ this.confirmed = { ...snapshot.doc, version: snapshot.seq };
9486
+ this.lastSeq = snapshot.seq;
9487
+ this.settle();
9488
+ this.flush();
9489
+ },
9490
+ (error2) => {
9491
+ this.snapshotInFlight = false;
9492
+ if (this.stopped) return;
9493
+ this.onTransportError?.(error2);
9494
+ this.scheduleRetry();
9495
+ }
9496
+ );
9497
+ }
9498
+ // --------------------------------------------------------------- conexão
9499
+ setOnline(online) {
9500
+ if (this.stopped) return;
9501
+ this.online = online;
9502
+ if (!online) return;
9503
+ this.retryDelay = this.retryMs;
9504
+ this.clearTimer("retryTimer");
9505
+ this.resume();
9506
+ }
9507
+ resume() {
9508
+ this.requestSync();
9509
+ this.flush();
9510
+ }
9511
+ scheduleRetry() {
9512
+ if (this.retryTimer !== null || !this.online) return;
9513
+ const delay = this.retryDelay;
9514
+ this.retryDelay = Math.min(this.retryDelay * 2, this.maxRetryMs);
9515
+ this.retryTimer = this.scheduler.setTimeout(() => {
9516
+ this.retryTimer = null;
9517
+ this.resume();
9518
+ }, delay);
9519
+ }
9520
+ // ---------------------------------------------------------- foto e tela
9521
+ /** Avança a foto pelo que é contíguo, reconstrói a tela e confere buraco. */
9522
+ settle() {
9523
+ for (const seq of [...this.buffer.keys()]) {
9524
+ if (seq <= this.lastSeq) this.buffer.delete(seq);
9525
+ }
9526
+ for (; ; ) {
9527
+ const next = this.buffer.get(this.lastSeq + 1);
9528
+ if (next === void 0) break;
9529
+ this.buffer.delete(this.lastSeq + 1);
9530
+ try {
9531
+ this.confirmed = applyConfirmed2(this.confirmed, next);
9532
+ } catch {
9533
+ this.buffer.clear();
9534
+ this.requestSnapshot();
9535
+ break;
9536
+ }
9537
+ this.lastSeq += 1;
9538
+ }
9539
+ this.rebuild();
9540
+ this.checkGap();
9541
+ }
9542
+ /**
9543
+ * A tela = foto confirmada + confirmados à frente do buraco + pendentes.
9544
+ *
9545
+ * Pendente que nunca saiu e não vale mais é descartada aqui. A que já saiu
9546
+ * fica fora da tela, mas na fila, até o servidor dizer o que houve com ela.
9547
+ */
9548
+ rebuild() {
9549
+ let doc = this.confirmed;
9550
+ for (const seq of [...this.buffer.keys()].sort((a, b) => a - b)) {
9551
+ const envelope2 = this.buffer.get(seq);
9552
+ if (envelope2 === void 0) continue;
9553
+ const verdict = tryApplyEnvelope(doc, envelope2);
9554
+ if (verdict.ok) doc = verdict.doc;
9555
+ }
9556
+ const kept = [];
9557
+ for (const item of this.pending) {
9558
+ const verdict = tryApplyEnvelope(doc, item.envelope);
9559
+ if (verdict.ok) {
9560
+ doc = verdict.doc;
9561
+ kept.push(item);
9562
+ } else if (item.sent) {
9563
+ kept.push(item);
9564
+ } else {
9565
+ this.discard(item.envelope, "not-applicable", verdict.reason);
9566
+ }
9567
+ }
9568
+ this.pending = kept;
9569
+ this.store.replaceDoc(doc.version === this.lastSeq ? doc : { ...doc, version: this.lastSeq });
9570
+ }
9571
+ checkGap() {
9572
+ if (this.buffer.size === 0) {
9573
+ this.clearTimer("gapTimer");
9574
+ return;
9575
+ }
9576
+ if (this.gapTimer !== null) return;
9577
+ this.gapTimer = this.scheduler.setTimeout(() => {
9578
+ this.gapTimer = null;
9579
+ if (this.buffer.size === 0) return;
9580
+ this.stats.gapSyncs += 1;
9581
+ this.requestSync();
9582
+ }, this.gapGraceMs);
9583
+ }
9584
+ // -------------------------------------------------------------- miúdos
9585
+ discard(envelope2, reason, detail) {
9586
+ this.stats.discarded += 1;
9587
+ this.onDiscard?.({ envelope: envelope2, reason, detail });
9588
+ }
9589
+ findPending(opId) {
9590
+ return this.pending.findIndex((item) => item.envelope.id === opId);
9591
+ }
9592
+ clearTimer(name) {
9593
+ const handle = this[name];
9594
+ if (handle === null) return;
9595
+ this.scheduler.clearTimeout(handle);
9596
+ this[name] = null;
9597
+ }
9598
+ };
9599
+ }
9600
+ });
9601
+
6887
9602
  // node_modules/@hono/node-server/dist/index.mjs
6888
9603
  import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
6889
9604
  import { Http2ServerRequest } from "http2";
@@ -22351,8 +25066,19 @@ var LoginExpiredError = class extends ApiError {
22351
25066
  this.name = "LoginExpiredError";
22352
25067
  }
22353
25068
  };
25069
+ var ServerBusyError = class extends ApiError {
25070
+ constructor(status, waitS, what) {
25071
+ super(
25072
+ status,
25073
+ `O servidor da BePlus est\xE1 ocupado agora (${status === 0 ? "falha de rede" : `HTTP ${status}`} em ${what}). Nada foi alterado por esta chamada. Tente de novo em ${waitS} s, sem repetir em sequ\xEAncia.`
25074
+ );
25075
+ this.waitS = waitS;
25076
+ this.name = "ServerBusyError";
25077
+ }
25078
+ waitS;
25079
+ };
22354
25080
  function apiErrorToUserMessage(err) {
22355
- if (err instanceof LoginExpiredError) return err.message;
25081
+ if (err instanceof LoginExpiredError || err instanceof ServerBusyError) return err.message;
22356
25082
  if (err instanceof ApiError) {
22357
25083
  const detail = err.message || "";
22358
25084
  switch (err.httpStatus) {
@@ -22431,6 +25157,26 @@ async function fetchWithAuth(cfg, url, init, what) {
22431
25157
  }
22432
25158
 
22433
25159
  // src/api/client.ts
25160
+ var retryPolicy = {
25161
+ retries: 4,
25162
+ baseMs: 1e3,
25163
+ capMs: 3e4,
25164
+ /** Passou disso esperando, desiste e devolve "tente em N s" ao agente em vez de segurar a tool. */
25165
+ budgetMs: 45e3,
25166
+ random: Math.random,
25167
+ sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
25168
+ };
25169
+ var RETRYABLE = /* @__PURE__ */ new Set([0, 429, 503]);
25170
+ function retryAfterMs(res) {
25171
+ const raw = res.headers.get("retry-after");
25172
+ if (!raw) return null;
25173
+ const secs = Number(raw);
25174
+ if (Number.isFinite(secs)) return Math.max(0, secs * 1e3);
25175
+ const at = Date.parse(raw);
25176
+ return Number.isFinite(at) ? Math.max(0, at - Date.now()) : null;
25177
+ }
25178
+ var costCachePolicy = { ttlMs: 10 * 6e4, capacity: 256, now: () => Date.now() };
25179
+ var costCache = /* @__PURE__ */ new Map();
22434
25180
  var BeplusClient = class {
22435
25181
  constructor(cfg) {
22436
25182
  this.cfg = cfg;
@@ -22438,23 +25184,63 @@ var BeplusClient = class {
22438
25184
  cfg;
22439
25185
  /** Público para os módulos de rota própria (ex.: Canvas) reaproveitarem auth, timeout e erros. */
22440
25186
  async request(method, path, opts = {}) {
25187
+ return (await this.requestMeta(method, path, opts)).data;
25188
+ }
25189
+ /** Igual a `request`, mas devolve status e ETag, e trata 304 como resposta (sem corpo). */
25190
+ async requestMeta(method, path, opts = {}) {
22441
25191
  const url = new URL(`${opts.base ?? this.cfg.apiBase}${path}`);
22442
25192
  if (opts.query) {
22443
25193
  for (const [k, v] of Object.entries(opts.query)) {
22444
25194
  if (v !== void 0 && v !== null && v !== "") url.searchParams.set(k, String(v));
22445
25195
  }
22446
25196
  }
22447
- const res = await fetchWithAuth(
22448
- this.cfg,
22449
- url,
22450
- {
22451
- method,
22452
- headers: opts.body ? { "Content-Type": "application/json" } : {},
22453
- body: opts.body ? JSON.stringify(opts.body) : void 0,
22454
- timeoutMs: opts.timeoutMs ?? 3e4
22455
- },
22456
- path
22457
- );
25197
+ const retry = opts.retry ?? method === "GET";
25198
+ const p = retryPolicy;
25199
+ const started = Date.now();
25200
+ for (let attempt = 0; ; attempt++) {
25201
+ let res = null;
25202
+ let failure = null;
25203
+ try {
25204
+ res = await fetchWithAuth(
25205
+ this.cfg,
25206
+ url,
25207
+ {
25208
+ method,
25209
+ headers: { ...opts.body ? { "Content-Type": "application/json" } : {}, ...opts.headers },
25210
+ body: opts.body ? JSON.stringify(opts.body) : void 0,
25211
+ timeoutMs: opts.timeoutMs ?? 3e4
25212
+ },
25213
+ path
25214
+ );
25215
+ } catch (e) {
25216
+ if (!(e instanceof ApiError) || e.httpStatus !== 0) throw e;
25217
+ failure = e;
25218
+ }
25219
+ const status = res ? res.status : 0;
25220
+ if (!retry || !RETRYABLE.has(status)) {
25221
+ if (failure) throw failure;
25222
+ return this.read(res, path);
25223
+ }
25224
+ const step = Math.min(p.capMs, p.baseMs * 2 ** attempt);
25225
+ const asked = res ? retryAfterMs(res) : null;
25226
+ const wait = asked ?? step / 2 + p.random() * (step / 2);
25227
+ if (attempt >= p.retries || asked !== null && asked > p.capMs || Date.now() - started + wait > p.budgetMs) {
25228
+ await res?.body?.cancel().catch(() => {
25229
+ });
25230
+ throw new ServerBusyError(status, Math.max(1, Math.ceil(Math.max(wait, p.baseMs) / 1e3)), path);
25231
+ }
25232
+ await res?.body?.cancel().catch(() => {
25233
+ });
25234
+ await p.sleep(wait);
25235
+ }
25236
+ }
25237
+ async read(res, path) {
25238
+ const etag = res.headers.get("etag");
25239
+ if (res.status === 304) {
25240
+ await res.body?.cancel().catch(() => {
25241
+ });
25242
+ return { status: 304, etag, data: null, bytes: 0 };
25243
+ }
22458
25244
  let text;
22459
25245
  try {
22460
25246
  text = await res.text();
@@ -22472,7 +25258,8 @@ var BeplusClient = class {
22472
25258
  const message = json?.message || (Array.isArray(json?.error?.formatted) ? json.error.formatted.join(", ") : void 0) || res.statusText || `HTTP ${res.status}`;
22473
25259
  throw new ApiError(res.status, message, json);
22474
25260
  }
22475
- return json && typeof json === "object" && "result" in json ? json.result : json;
25261
+ const data = json && typeof json === "object" && "result" in json ? json.result : json;
25262
+ return { status: res.status, etag, data, bytes: text.length };
22476
25263
  }
22477
25264
  startGeneration(body2) {
22478
25265
  return this.request("POST", "/generations", { body: body2 });
@@ -22552,8 +25339,21 @@ var BeplusClient = class {
22552
25339
  models() {
22553
25340
  return this.request("GET", "/models");
22554
25341
  }
25342
+ /** Cache por parâmetros: o preço não muda entre chamadas, e o agente estima o mesmo modelo várias vezes. */
22555
25343
  calculateCost(query) {
22556
- return this.request("GET", "/calculate-cost", { query });
25344
+ 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));
25345
+ const key = `${this.cfg.apiBase}|${JSON.stringify(normalized)}`;
25346
+ const now = costCachePolicy.now();
25347
+ const hit = costCache.get(key);
25348
+ if (hit && (hit.expiresAt === null || hit.expiresAt > now)) return hit.value;
25349
+ const value = this.request("GET", "/calculate-cost", { query });
25350
+ costCache.set(key, { value, expiresAt: null });
25351
+ value.then(
25352
+ () => costCache.set(key, { value, expiresAt: costCachePolicy.now() + costCachePolicy.ttlMs }),
25353
+ () => costCache.delete(key)
25354
+ );
25355
+ while (costCache.size > costCachePolicy.capacity) costCache.delete(costCache.keys().next().value);
25356
+ return value;
22557
25357
  }
22558
25358
  /** `billing: 'personal'` pula o budget do projeto ativo no preview do saldo. */
22559
25359
  balance(billing) {
@@ -22655,6 +25455,9 @@ var remote = false;
22655
25455
  function enableRemoteMode() {
22656
25456
  remote = true;
22657
25457
  }
25458
+ function isRemoteMode() {
25459
+ return remote;
25460
+ }
22658
25461
  function refuseLocalPath(ref) {
22659
25462
  if (!remote) return;
22660
25463
  throw new ApiError(
@@ -24516,8 +27319,8 @@ function probeBuffer(b, mime) {
24516
27319
  return meta;
24517
27320
  }
24518
27321
  if (mime.startsWith("audio/")) {
24519
- const seconds = probeWav(b) ?? probeFlac(b) ?? (mime === "audio/mpeg" ? probeMp3(b) : null);
24520
- return seconds ? { duration: round(seconds) } : null;
27322
+ const seconds2 = probeWav(b) ?? probeFlac(b) ?? (mime === "audio/mpeg" ? probeMp3(b) : null);
27323
+ return seconds2 ? { duration: round(seconds2) } : null;
24521
27324
  }
24522
27325
  return null;
24523
27326
  }
@@ -25463,9 +28266,11 @@ ${calls.map(callLine).join("\n\n")}`);
25463
28266
  }
25464
28267
 
25465
28268
  // src/tools/canvas.ts
25466
- import { createHash } from "crypto";
28269
+ import { createHash as createHash2 } from "crypto";
25467
28270
 
25468
28271
  // src/canvas/api.ts
28272
+ import { createHash } from "crypto";
28273
+ var import_canvas_core = __toESM(require_canvas_core(), 1);
25469
28274
  var PINNED_CORE_VERSION = "ca7b3b406184c7f679f555c3a008013197182b23";
25470
28275
  var RUN_REQUEST_TIMEOUT_MS = 4e4;
25471
28276
  var FOCUS_REQUEST_TIMEOUT_MS = 12e3;
@@ -25480,6 +28285,54 @@ var commentPacing = {
25480
28285
  now: () => Date.now(),
25481
28286
  sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
25482
28287
  };
28288
+ var boardCachePolicy = {
28289
+ /** Contrato 5: duas leituras do mesmo board com menos que isso reaproveitam a anterior sem rede. */
28290
+ minIntervalMs: 2e3,
28291
+ stdio: { entries: 4, bytes: 256 * 1024 * 1024 },
28292
+ /** Dentro do academy-api: o doc em cache ocupa a memória da própria API. */
28293
+ remote: { entries: 2, bytes: 64 * 1024 * 1024 },
28294
+ /** Envelopes guardados para o conflito do edit() sem ir à rede (o servidor manda reler acima de 200). */
28295
+ recentMax: 200,
28296
+ now: () => Date.now()
28297
+ };
28298
+ var boardStore = /* @__PURE__ */ new Map();
28299
+ var boardLoads = /* @__PURE__ */ new Map();
28300
+ function storeEntry(key, entry) {
28301
+ const limit = isRemoteMode() ? boardCachePolicy.remote : boardCachePolicy.stdio;
28302
+ boardStore.delete(key);
28303
+ if (entry.bytes > limit.bytes) return;
28304
+ boardStore.set(key, entry);
28305
+ let total = 0;
28306
+ for (const e of boardStore.values()) total += e.bytes;
28307
+ for (const [k, e] of boardStore) {
28308
+ if (boardStore.size <= limit.entries && total <= limit.bytes) break;
28309
+ boardStore.delete(k);
28310
+ total -= e.bytes;
28311
+ }
28312
+ }
28313
+ function touchEntry(key, entry) {
28314
+ boardStore.delete(key);
28315
+ boardStore.set(key, entry);
28316
+ }
28317
+ function applyDelta(snap, envelopes) {
28318
+ let doc = snap.doc;
28319
+ let seq = snap.seq;
28320
+ try {
28321
+ for (const env of envelopes) {
28322
+ if (env.seq <= seq) continue;
28323
+ if (!knownOp(env.op)) return null;
28324
+ doc = (0, import_canvas_core.applyConfirmed)(doc, env);
28325
+ seq = env.seq;
28326
+ }
28327
+ } catch {
28328
+ return null;
28329
+ }
28330
+ return seq === snap.seq ? snap : { ...snap, doc, seq, title: doc.title };
28331
+ }
28332
+ function knownOp(op) {
28333
+ if (!Object.hasOwn(import_canvas_core.OPS, op.type)) return false;
28334
+ return op.type !== "batch" || Array.isArray(op.ops) && op.ops.every((o) => knownOp(o));
28335
+ }
25483
28336
  var CanvasApi = class {
25484
28337
  constructor(client, cfg) {
25485
28338
  this.client = client;
@@ -25509,11 +28362,87 @@ var CanvasApi = class {
25509
28362
  createBoard(body2) {
25510
28363
  return this.req("POST", "/boards", { body: body2 });
25511
28364
  }
25512
- snapshot(boardId4) {
25513
- return this.req("GET", `/boards/${boardId4}`);
28365
+ cacheKey(boardId4) {
28366
+ const who2 = createHash("sha256").update(this.cfg.token).digest("hex").slice(0, 16);
28367
+ return `${this.cfg.canvasBase}|${who2}|${boardId4}`;
28368
+ }
28369
+ /** Board pelo cache: delta quando dá, inteiro com If-None-Match quando não. Um GET em voo por board. */
28370
+ async snapshot(boardId4, opts = {}) {
28371
+ const key = this.cacheKey(boardId4);
28372
+ const entry = boardStore.get(key);
28373
+ if (entry && !opts.fresh && !opts.runs && boardCachePolicy.now() - entry.checkedAt < boardCachePolicy.minIntervalMs) {
28374
+ touchEntry(key, entry);
28375
+ return entry.snap;
28376
+ }
28377
+ const loadKey = opts.runs ? `${key}|runs` : key;
28378
+ const inFlight = boardLoads.get(loadKey);
28379
+ if (inFlight) return inFlight;
28380
+ const load = this.load(boardId4, key, !!opts.runs).finally(() => boardLoads.delete(loadKey));
28381
+ boardLoads.set(loadKey, load);
28382
+ return load;
28383
+ }
28384
+ async load(boardId4, key, needRuns) {
28385
+ const entry = boardStore.get(key);
28386
+ if (entry && !needRuns && this.coreVersion === PINNED_CORE_VERSION) {
28387
+ const envelopes = await this.fetchOpsAfter(boardId4, entry.snap.seq);
28388
+ const next = envelopes && applyDelta(entry.snap, envelopes);
28389
+ if (next) {
28390
+ let recent = entry.recent;
28391
+ let logFrom = entry.logFrom;
28392
+ if (next !== entry.snap) {
28393
+ recent = [...recent, ...envelopes.filter((e) => e.seq > entry.snap.seq)];
28394
+ if (recent.length > boardCachePolicy.recentMax) {
28395
+ recent = recent.slice(-boardCachePolicy.recentMax);
28396
+ logFrom = recent[0].seq - 1;
28397
+ }
28398
+ }
28399
+ const delta = envelopes.reduce((sum, e) => sum + JSON.stringify(e.op).length, 0);
28400
+ storeEntry(key, {
28401
+ snap: next,
28402
+ // O ETag cobre o snapshot inteiro: se o seq andou, o guardado não vale mais.
28403
+ etag: next === entry.snap ? entry.etag : null,
28404
+ bytes: entry.bytes + delta,
28405
+ checkedAt: boardCachePolicy.now(),
28406
+ recent,
28407
+ logFrom
28408
+ });
28409
+ return next;
28410
+ }
28411
+ }
28412
+ const res = await this.client.requestMeta("GET", `/boards/${boardId4}`, {
28413
+ base: this.cfg.canvasBase,
28414
+ headers: entry?.etag ? { "If-None-Match": entry.etag } : void 0
28415
+ });
28416
+ if (res.status === 304 && entry) {
28417
+ storeEntry(key, { ...entry, checkedAt: boardCachePolicy.now() });
28418
+ return entry.snap;
28419
+ }
28420
+ if (!res.data) throw new ApiError(502, "O servidor do Canvas respondeu sem o board.");
28421
+ storeEntry(key, {
28422
+ snap: res.data,
28423
+ etag: res.etag,
28424
+ bytes: res.bytes,
28425
+ checkedAt: boardCachePolicy.now(),
28426
+ recent: [],
28427
+ logFrom: res.data.seq
28428
+ });
28429
+ return res.data;
25514
28430
  }
25515
- /** Replay depois de `after`. `null` quando o servidor manda reler a foto (410). */
28431
+ /** Esquece o board deste token (ex.: o servidor recusou por papel e o cache pode estar velho). */
28432
+ forget(boardId4) {
28433
+ boardStore.delete(this.cacheKey(boardId4));
28434
+ }
28435
+ /**
28436
+ * O que mudou depois de `after`. Vem do cache quando a última leitura cobre esse trecho (o
28437
+ * edit() acabou de reler), senão da rede. `null` quando o servidor manda reler a foto (410).
28438
+ */
25516
28439
  async opsAfter(boardId4, after) {
28440
+ const entry = boardStore.get(this.cacheKey(boardId4));
28441
+ if (entry && after >= entry.logFrom && after <= entry.snap.seq) return entry.recent.filter((e) => e.seq > after);
28442
+ return this.fetchOpsAfter(boardId4, after);
28443
+ }
28444
+ /** Replay depois de `after`. `null` quando o servidor manda reler a foto (410). */
28445
+ async fetchOpsAfter(boardId4, after) {
25517
28446
  try {
25518
28447
  const { envelopes } = await this.req("GET", `/boards/${boardId4}/ops`, {
25519
28448
  query: { after }
@@ -25525,9 +28454,14 @@ var CanvasApi = class {
25525
28454
  }
25526
28455
  }
25527
28456
  async commit(boardId4, ops) {
25528
- const send = () => this.req("POST", `/boards/${boardId4}/ops`, {
25529
- body: { coreVersion: this.coreVersion, ops }
25530
- });
28457
+ const send = () => (
28458
+ // Reenvio seguro: o servidor ignora operação com id que já entrou.
28459
+ this.client.request("POST", `/boards/${boardId4}/ops`, {
28460
+ base: this.cfg.canvasBase,
28461
+ body: { coreVersion: this.coreVersion, ops },
28462
+ retry: true
28463
+ })
28464
+ );
25531
28465
  try {
25532
28466
  return await send();
25533
28467
  } catch (e) {
@@ -27410,6 +30344,22 @@ ${payload(u)}`
27410
30344
  // src/tools/canvas-run.ts
27411
30345
  import { randomUUID as randomUUID3 } from "crypto";
27412
30346
  var MAX_REMEMBERED = 50;
30347
+ var acceptedPacing = { repeats: 8, pauseMs: 2e3 };
30348
+ var statusPacing = {
30349
+ minIntervalMs: 3e3,
30350
+ now: () => Date.now(),
30351
+ sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
30352
+ };
30353
+ var sleep3 = (ms) => new Promise((r) => setTimeout(r, ms));
30354
+ var seconds = (ms) => `${new Intl.NumberFormat("pt-BR", { maximumFractionDigits: 1 }).format(ms / 1e3)} s`;
30355
+ function timingsLine(t) {
30356
+ if (!t || t.estimateMs === null && t.startMs === null) return "";
30357
+ const parts = [];
30358
+ if (t.estimateMs !== null) parts.push(`estimar ${seconds(t.estimateMs)}`);
30359
+ if (t.startMs !== null) parts.push(`come\xE7ar ${seconds(t.startMs)}`);
30360
+ return `Tempo na aba: ${parts.join(", ")}.`;
30361
+ }
30362
+ var lacksTitles = (nodes) => (nodes ?? []).some((n) => !n.title);
27413
30363
  var boardId2 = external_exports.string().uuid().describe("Id (uuid) do board.");
27414
30364
  var nodeId = external_exports.string().min(1).max(128);
27415
30365
  var fmt2 = (n) => new Intl.NumberFormat("pt-BR").format(n);
@@ -27454,6 +30404,7 @@ function targetOf(args) {
27454
30404
  }
27455
30405
  function registerCanvasRunTools(server, api, run) {
27456
30406
  const remembered = /* @__PURE__ */ new Map();
30407
+ const lastStatusAt = /* @__PURE__ */ new Map();
27457
30408
  const remember = (requestId, entry) => {
27458
30409
  remembered.delete(requestId);
27459
30410
  remembered.set(requestId, entry);
@@ -27502,15 +30453,21 @@ function registerCanvasRunTools(server, api, run) {
27502
30453
  const total = a.estimate ? `${dia(a.estimate.total)} (teto ${fmt2(max)})` : "";
27503
30454
  const again = a.repeated ? " (a aba j\xE1 tinha recebido este request_id; esta \xE9 a mesma resposta)" : "";
27504
30455
  if (a.status === "estimate") {
27505
- return [`Estimativa, nada rodou${again}. Modo ${modeText(a.mode)}. Total agora: ${total}.`, ...est, cabeLine(a, max)].filter(Boolean).join("\n");
30456
+ return [
30457
+ `Estimativa, nada rodou${again}. Modo ${modeText(a.mode)}. Total agora: ${total}.`,
30458
+ ...est,
30459
+ cabeLine(a, max),
30460
+ timingsLine(a.timings)
30461
+ ].filter(Boolean).join("\n");
27506
30462
  }
27507
30463
  if (a.status === "nothing") return `Nada para rodar${again}: ${a.message ?? "o board j\xE1 est\xE1 em dia."}`;
27508
30464
  const willRun = (a.estimate?.nodes ?? []).filter((n) => n.willRun).map((n) => n.nodeId);
27509
30465
  return [
27510
30466
  `Rodando pela sua aba do Canvas${again}. Modo ${modeText(a.mode)}. Estimativa: ${total}.`,
27511
30467
  ...est,
27512
- `request_id: ${requestId}. Andamento: canvas_run_status (board_id, request_id). Resultado: canvas_read_board com node_ids [${willRun.slice(0, 20).join(", ")}] quando terminar.`
27513
- ].join("\n");
30468
+ `request_id: ${requestId}. Andamento: canvas_run_status (board_id, request_id). Resultado: canvas_read_board com node_ids [${willRun.slice(0, 20).join(", ")}] quando terminar.`,
30469
+ timingsLine(a.timings)
30470
+ ].filter(Boolean).join("\n");
27514
30471
  }
27515
30472
  function cabeLine(a, max) {
27516
30473
  if (!a.estimate) return "";
@@ -27538,20 +30495,32 @@ function registerCanvasRunTools(server, api, run) {
27538
30495
  const target = targetOf(args);
27539
30496
  const requestId = (args.request_id ?? randomUUID3()).toLowerCase();
27540
30497
  const label = args.label ?? prettyClient(server.server.getClientVersion()?.name);
27541
- let answer;
27542
- try {
27543
- answer = await api.runRequest(args.board_id, {
27544
- requestId,
27545
- target,
27546
- maxDiamonds: args.max_diamonds,
27547
- dryRun: args.dry_run === true,
27548
- simulated: args.simulated === true,
27549
- label
27550
- });
27551
- } catch (e) {
27552
- explain2(e, requestId);
30498
+ const ask = async () => {
30499
+ try {
30500
+ return await api.runRequest(args.board_id, {
30501
+ requestId,
30502
+ target,
30503
+ maxDiamonds: args.max_diamonds,
30504
+ dryRun: args.dry_run === true,
30505
+ simulated: args.simulated === true,
30506
+ label,
30507
+ earlyAck: true
30508
+ });
30509
+ } catch (e) {
30510
+ explain2(e, requestId);
30511
+ }
30512
+ };
30513
+ let answer = await ask();
30514
+ const wasAccepted = answer.ok === true && answer.status === "accepted";
30515
+ for (let i = 0; answer.ok === true && answer.status === "accepted" && i < acceptedPacing.repeats; i++) {
30516
+ await sleep3(acceptedPacing.pauseMs);
30517
+ answer = await ask();
27553
30518
  }
27554
- const titleOf = await titles(args.board_id);
30519
+ if (wasAccepted) answer = { ...answer, repeated: false };
30520
+ if (answer.ok === true && answer.status === "accepted") {
30521
+ return `A aba recebeu o pedido e ainda est\xE1 estimando e conferindo (board grande). request_id: ${requestId}. Acompanhe com canvas_run_status; para a resposta completa, chame canvas_run de novo com o MESMO request_id (\xE9 seguro: a aba n\xE3o roda duas vezes). N\xC3O pe\xE7a com outro id.`;
30522
+ }
30523
+ const titleOf = lacksTitles(answer.estimate?.nodes) ? await titles(args.board_id) : (id) => id;
27555
30524
  if (answer.ok !== true) {
27556
30525
  const est = estimateLines(answer.estimate, titleOf);
27557
30526
  throw new CanvasToolError(
@@ -27583,9 +30552,15 @@ function registerCanvasRunTools(server, api, run) {
27583
30552
  },
27584
30553
  async ({ board_id, request_id, node_ids }) => run(async () => {
27585
30554
  const requestId = request_id.toLowerCase();
30555
+ const since = statusPacing.now() - (lastStatusAt.get(requestId) ?? -Infinity);
30556
+ if (since < statusPacing.minIntervalMs) await statusPacing.sleep(statusPacing.minIntervalMs - since);
30557
+ lastStatusAt.delete(requestId);
30558
+ lastStatusAt.set(requestId, statusPacing.now());
30559
+ while (lastStatusAt.size > MAX_REMEMBERED) lastStatusAt.delete(lastStatusAt.keys().next().value);
27586
30560
  let why = "";
27587
30561
  try {
27588
- return statusText(await api.runStatus(board_id, requestId), await titles(board_id));
30562
+ const status = await api.runStatus(board_id, requestId);
30563
+ return statusText(status, lacksTitles(status.nodes) ? await titles(board_id) : (id) => id);
27589
30564
  } catch (e) {
27590
30565
  const reason = errorRaw(e)?.reason;
27591
30566
  if (!(e instanceof ApiError) || reason !== "unknown-request" && reason !== "no-tab") explain2(e);
@@ -27598,7 +30573,7 @@ function registerCanvasRunTools(server, api, run) {
27598
30573
  }
27599
30574
  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)` : "";
27600
30575
  return `${why} Pelo estado de execu\xE7\xE3o do board${partial2}:
27601
- ${fromRuns(await api.snapshot(board_id), ids)}`;
30576
+ ${fromRuns(await api.snapshot(board_id, { runs: true }), ids)}`;
27602
30577
  })
27603
30578
  );
27604
30579
  }
@@ -27639,6 +30614,8 @@ function statusText(a, titleOf) {
27639
30614
  }
27640
30615
  if (a.omitted) lines.push(`\u2026 e mais ${a.omitted} n\xF3(s) fora da lista (a resposta da aba foi cortada pelo tamanho).`);
27641
30616
  if (a.state === "done" || a.state === "failed") lines.push("Leia o resultado com canvas_read_board (node_ids).");
30617
+ const timing = timingsLine(a.timings);
30618
+ if (timing) lines.push(timing);
27642
30619
  return lines.join("\n");
27643
30620
  }
27644
30621
  function fromRuns(snap, ids) {
@@ -28018,6 +30995,17 @@ function registerCanvasTools(server, client, cfg) {
28018
30995
  }
28019
30996
  return errorResult(apiErrorToUserMessage(e));
28020
30997
  }
30998
+ async function commitOps(id, envs) {
30999
+ try {
31000
+ return await api.commit(id, envs);
31001
+ } catch (e) {
31002
+ if (!(e instanceof ApiError) || e.httpStatus !== 403) throw e;
31003
+ api.forget(id);
31004
+ const again = await api.snapshot(id, { runs: true }).catch(() => null);
31005
+ 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.");
31006
+ throw e;
31007
+ }
31008
+ }
28021
31009
  async function run(fn) {
28022
31010
  try {
28023
31011
  return textResult(await fn());
@@ -28030,7 +31018,7 @@ function registerCanvasTools(server, client, cfg) {
28030
31018
  if (last === void 0 && !opts.layoutOnly) {
28031
31019
  throw new CanvasToolError("Leia o board com canvas_read_board antes de editar (a leitura vale para a sess\xE3o).");
28032
31020
  }
28033
- const snap = await api.snapshot(id);
31021
+ const snap = await api.snapshot(id, { fresh: true });
28034
31022
  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.");
28035
31023
  const doc = snap.doc;
28036
31024
  const { ops, done, targets } = await build2(doc, snap);
@@ -28065,7 +31053,7 @@ Aviso: ${changesSince(theirs, doc)}.`;
28065
31053
  const env = envelope(id, batchOf(ops), await api.me());
28066
31054
  const bad = checkEnvelope(env);
28067
31055
  if (bad) throw new CanvasToolError(`Edi\xE7\xE3o recusada antes de enviar: ${bad}.`);
28068
- const res = await api.commit(id, [env]);
31056
+ const res = await commitOps(id, [env]);
28069
31057
  const outcome = res.outcomes.find((o) => o.opId === env.id);
28070
31058
  if (!outcome || "rejected" in outcome) {
28071
31059
  if (!opts.layoutOnly) seen.delete(id);
@@ -28093,7 +31081,7 @@ Aviso: ${changesSince(theirs, doc)}.`;
28093
31081
  const outcomes = /* @__PURE__ */ new Map();
28094
31082
  let last = null;
28095
31083
  for (let i = 0; i < envs.length; i += MAX_ENVELOPES_PER_COMMIT) {
28096
- const res = await api.commit(id, envs.slice(i, i + MAX_ENVELOPES_PER_COMMIT));
31084
+ const res = await commitOps(id, envs.slice(i, i + MAX_ENVELOPES_PER_COMMIT));
28097
31085
  for (const o of res.outcomes) outcomes.set(o.opId, o);
28098
31086
  last = res.seq;
28099
31087
  }
@@ -28306,7 +31294,7 @@ ${lines.join("\n")}${note}`;
28306
31294
  const from = Math.min(offset ?? 0, total);
28307
31295
  const size = max_chars ?? 4e4;
28308
31296
  const to = Math.min(from + size, total);
28309
- const hash = createHash("sha256").update(json).digest("hex").slice(0, 12);
31297
+ const hash = createHash2("sha256").update(json).digest("hex").slice(0, 12);
28310
31298
  const where = `data${segments.length ? `.${segments.join(".")}` : ""}`;
28311
31299
  const at = readMeasured(node)?.at;
28312
31300
  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}`;
@@ -28755,7 +31743,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
28755
31743
  import { createRequire } from "module";
28756
31744
  var require2 = createRequire(import.meta.url);
28757
31745
  function readVersion() {
28758
- if ("0.43.0") return "0.43.0";
31746
+ if ("0.45.0") return "0.45.0";
28759
31747
  try {
28760
31748
  const pkg = require2("../package.json");
28761
31749
  return pkg.version ?? "0.0.0-unknown";