@nodii/dev 0.6.108 → 0.6.110

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -47,6 +47,7 @@ import {
47
47
  figmaLockText,
48
48
  figmaLogWrite,
49
49
  figmaPublishPlan,
50
+ figmaPublishPlanFromLane,
50
51
  figmaPublishPlanText,
51
52
  figmaResubmit,
52
53
  figmaScopeAdd,
@@ -192,8 +193,13 @@ Usage: nodii-dev <command> [options] [--json]
192
193
  # no --scope locks the whole file (DEC-0032)
193
194
  figma scope add CHANGE_SET --scope KIND:ID [--scope ...] # widen a held set's scopes
194
195
  figma scope set CHANGE_SET --scope KIND:ID [--scope ...] # narrow to exactly these; the rest frees
195
- figma publish-plan FILE_KEY # what to publish, and what to leave unchecked in Figma's dialog
196
- figma published FILE_KEY|CHANGE_SET --figma-version V # a file key marks every awaiting set published
196
+ figma publish-plan FILE_KEY [--lane-reads FILE]
197
+ # what to publish, and what to leave unchecked in Figma's dialog. With
198
+ # --lane-reads Dev runs no job: it takes your MCP reads, and the version
199
+ # compares run here through REST on FIGMA_PAT, paced, stopping at a 429
200
+ figma published FILE_KEY|CHANGE_SET --figma-version V [--lane-reads FILE]
201
+ # a file key marks every awaiting set published. Dev reads no Figma here:
202
+ # FIGMA_READS_NEEDED names a node to place, or a version it hasn't seen
197
203
  figma apply CHANGE_SET --lane-reads FILE
198
204
  # MW1-57.11: what you read through the Figma MCP, sent as data. Dev runs its
199
205
  # gates on it with no job and no Figma call; FIGMA_READS_NEEDED names what's missing
@@ -716,6 +722,16 @@ const REGISTER_REFUSALS = {
716
722
  FIGMA_FILE_NOT_READABLE: (key) => `Dev's Figma account can't read ${key}; share the file with that account.`,
717
723
  };
718
724
 
725
+ // `figma published`: the version is the library's publish, whatever version the
726
+ // reads were made at, so it's always named.
727
+ export async function publishedBody(f) {
728
+ if (f.file) return JSON.parse(await readFile(f.file, "utf8"));
729
+ return {
730
+ figmaVersion: requireFlag(f, "figma-version"),
731
+ ...(f["lane-reads"] ? { laneReads: await readLaneReads(f["lane-reads"]) } : {}),
732
+ };
733
+ }
734
+
719
735
  const FILE_RETIRE_USAGE = "figma file retire FILE_KEY --reason TEXT";
720
736
  export async function figmaFileRetire(value, reason, { request = devRequest } = {}) {
721
737
  if (!value || typeof reason !== "string" || !reason.trim()) throw new CliError("USAGE", FILE_RETIRE_USAGE, 2);
@@ -1310,13 +1326,14 @@ export async function main(argv = process.argv.slice(2)) {
1310
1326
  `${rest[1]} holds ${p.data?.scopes?.length ?? "its"} scope(s)${p.data?.scopes?.length ? `: ${p.data.scopes.map(scopeText).join(", ")}` : ""}`);
1311
1327
  }
1312
1328
  if (action === "publish-plan") {
1313
- if (!rest[0] || rest.length > 1) throw new CliError("USAGE", "figma publish-plan FILE_KEY", 2);
1314
- return emit(await figmaPublishPlan(rest[0]), json, (p) => figmaPublishPlanText(p.data));
1329
+ if (!rest[0] || rest.length > 1) throw new CliError("USAGE", "figma publish-plan FILE_KEY [--lane-reads FILE]", 2);
1330
+ const plan = f["lane-reads"] ? await figmaPublishPlanFromLane(rest[0], await readLaneReads(f["lane-reads"])) : await figmaPublishPlan(rest[0]);
1331
+ return emit(plan, json, (p) => figmaPublishPlanText(p.data));
1315
1332
  }
1316
1333
  // One publish covers every set awaiting publish on the file (MW1-57.8); a
1317
1334
  // change set id keeps the per-set route.
1318
1335
  if (action === "published" && rest[0] && !isChangeSetId(rest[0]))
1319
- return emit(await figmaFilePublished(rest[0], f.file ? JSON.parse(await readFile(f.file, "utf8")) : { figmaVersion: requireFlag(f, "figma-version") }), json, (p) => figmaFilePublishedText(p.data));
1336
+ return emit(await figmaFilePublished(rest[0], await publishedBody(f)).catch((error) => { throw laneReadsRefusal(error); }), json, (p) => figmaFilePublishedText(p.data));
1320
1337
  // --dry-run runs Dev's dry run of the submit gate (design check --change-set)
1321
1338
  // on the same body, and never writes (CLI-18).
1322
1339
  const dryRun = async (id, text, file) => {
@@ -1379,6 +1396,12 @@ export async function main(argv = process.argv.slice(2)) {
1379
1396
  if (action === "log-write")
1380
1397
  return emit(await figmaLogWrite(rest[0], requireFlag(f, "tool"), requireFlag(f, "nodes").split(",").filter(Boolean)), json);
1381
1398
  if (action === "lane-reads-script") return console.log(laneReadsScript(f.nodes));
1399
+ if (action === "published" && f["lane-reads"]) {
1400
+ return emit(
1401
+ await devRequest("POST", `/api/v1/design/change-sets/${encode(rest[0])}/published`, await publishedBody(f)).catch((error) => { throw laneReadsRefusal(error); }),
1402
+ json,
1403
+ );
1404
+ }
1382
1405
  if (action === "apply" && f["lane-reads"]) {
1383
1406
  const laneReads = await readLaneReads(f["lane-reads"]);
1384
1407
  return emit(
package/dist/core.js CHANGED
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { homedir, platform } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.108";
7
+ export const VERSION = "0.6.110";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
package/dist/figma.js CHANGED
@@ -3,6 +3,8 @@ import { readFile } from "node:fs/promises";
3
3
  import { setTimeout as delay } from "node:timers/promises";
4
4
  import { CliError, devAsyncRequest, devRequest, encode } from "./core.js";
5
5
  import { assertWithinLaneScope, currentLaneFigmaScope } from "./figma-scope.js";
6
+ import { answerPlanReads, countedReads, figmaToken } from "./publish-compare.js";
7
+ import { pacedFigma } from "./surface.js";
6
8
 
7
9
  /** A Figma file key, or the key inside a figma.com file link (a branch link's branch key). */
8
10
  export function figmaFileKey(value) {
@@ -831,6 +833,33 @@ export async function figmaPublishPlan(value, { request = devRequest, sleep = de
831
833
  return planJobOutcome(job);
832
834
  }
833
835
 
836
+ /**
837
+ * The plan with no job on Dev (MW1-57.11, hub-295). The lane's MCP reads go with
838
+ * the request. Dev asks for what needs Figma's version history, which the MCP
839
+ * can't read; those compares run here, on the lane's own token, and go back with
840
+ * the same request. Each is evidence for this answer, and never a pass.
841
+ */
842
+ export async function figmaPublishPlanFromLane(value, laneReads, { request = devRequest, env = process.env, figmaGet, progress = stderrLine, now = Date.now } = {}) {
843
+ const key = figmaFileKey(value);
844
+ const call = fileCall(key, request);
845
+ const start = now();
846
+ let counted = null;
847
+ let reads = laneReads;
848
+ // A round for what sets wrote late, one for the last publish, and one to answer.
849
+ for (let round = 0; round < 4; round++) {
850
+ try {
851
+ const answer = await call("POST", `/api/v1/design/files/${encode(key)}/publish-plan`, { laneReads: reads });
852
+ if (counted) progress(`${key}: ${counted.calls()} Figma REST reads on this session's token in ${Math.round((now() - start) / 1000)} s`);
853
+ return answer;
854
+ } catch (error) {
855
+ if (error?.code !== "FIGMA_READS_NEEDED" || error.details?.read !== "publish") throw laneReadsRefusal(error);
856
+ counted ??= countedReads(figmaGet ?? pacedFigma(figmaToken(env), { log: progress }));
857
+ reads = await answerPlanReads(key, error.details, reads, counted.get, progress);
858
+ }
859
+ }
860
+ throw new CliError("PUBLISH_PLAN_READS_UNSETTLED", `Dev kept asking for more reads of ${key}: the file or its sets are moving. Run the same command again.`);
861
+ }
862
+
834
863
  // The whole-file Surfaces check (DESIGN-SYSTEM-253): Dev reads every Surface of
835
864
  // the file as a job, a few at a time at Figma's pace, so the POST answers 202 and
836
865
  // the job is polled until it ends, as the publish plan is.
@@ -0,0 +1,129 @@
1
+ // The publish plan's compares, run in the lane's own session (MW1-57.11, hub-295).
2
+ // The Figma MCP has no version history, so these reads go through REST, on the
3
+ // token the lane was launched with. They're named in restReads. One failed read
4
+ // never clears anything: a read that fails lists its nodes as changed, and a 429
5
+ // stops the run, since it means stop reading.
6
+ import { CliError, encode } from "./core.js";
7
+ import { componentsToCompare, sameAuthored } from "./vendor/authored.mjs";
8
+
9
+ // Full-depth documents run to megabytes, so reads stay this small, as on Dev.
10
+ const IDS_PER_READ = 3;
11
+ const batches = (ids) => {
12
+ const unique = [...new Set(ids)];
13
+ const out = [];
14
+ for (let i = 0; i < unique.length; i += IDS_PER_READ) out.push(unique.slice(i, i + IDS_PER_READ));
15
+ return out;
16
+ };
17
+
18
+ /** The lane's own Figma token. A lane launched with none stops here; it never borrows one. Never printed. */
19
+ export function figmaToken(env = process.env) {
20
+ const token = env.FIGMA_PAT || env.FIGMA_TOKEN;
21
+ if (!token) throw new CliError("FIGMA_TOKEN_REQUIRED", "This compare reads Figma's version history through REST, which the MCP can't do: launch the lane with FIGMA_PAT. Don't take a token from another lane or from Secrets Manager.", 2);
22
+ return token;
23
+ }
24
+
25
+ /** Counts the REST calls a run makes, for the report on whether one token is enough. */
26
+ export function countedReads(get) {
27
+ let calls = 0;
28
+ return { get: (path) => { calls++; return get(path); }, calls: () => calls };
29
+ }
30
+
31
+ const nodesPath = (key, ids, version) =>
32
+ `/files/${encode(key)}/nodes?ids=${encodeURIComponent(ids.join(","))}${version ? `&version=${encodeURIComponent(version)}` : ""}`;
33
+
34
+ const keysOf = (entry) => new Map(Object.entries(entry?.components ?? {}).flatMap(([id, component]) => (component?.key ? [[id, component.key]] : [])));
35
+
36
+ /**
37
+ * Whether a node holds the same own edits in two /nodes entries; both absent is
38
+ * the same. A component that only took a new local id from a library update is
39
+ * the same component, by the published key each entry names (hub-273). A local
40
+ * id with no key there stays as it is, so it still differs.
41
+ */
42
+ export function sameOwnEdits(then, now) {
43
+ if (!then?.document || !now?.document) return !then?.document && !now?.document;
44
+ const [before, after] = [JSON.stringify(then.document), JSON.stringify(now.document)];
45
+ if (sameAuthored(before, after)) return true;
46
+ const asked = componentsToCompare(before, after);
47
+ if (asked.before.instances.length === 0 && asked.after.instances.length === 0) return false;
48
+ const named = (entry, components) => new Map([...keysOf(entry)].filter(([id]) => components.has(id)));
49
+ return sameAuthored(before, after, { before: named(then, asked.before.components), after: named(now, asked.after.components) });
50
+ }
51
+
52
+ const rateLimited = (error) => error?.code === "FIGMA_RATE_LIMITED";
53
+
54
+ /** What a set wrote after its reviewed version and that differs from it. A node it can't compare is listed. */
55
+ export async function compareLateWrites(key, { changeSetId, version, nodeIds }, { get, progress = () => {} }) {
56
+ const changed = [];
57
+ for (const batch of batches(nodeIds)) {
58
+ let then;
59
+ let now;
60
+ try {
61
+ then = (await get(nodesPath(key, batch, version))).nodes ?? {};
62
+ now = (await get(nodesPath(key, batch))).nodes ?? {};
63
+ } catch (error) {
64
+ if (rateLimited(error)) throw error;
65
+ progress(`${changeSetId}: ${batch.join(", ")} listed as changed: ${error.code ?? error.message}`);
66
+ changed.push(...batch.map((nodeId) => ({ nodeId, name: nodeId })));
67
+ continue;
68
+ }
69
+ for (const nodeId of batch)
70
+ if (!sameOwnEdits(then[nodeId], now[nodeId])) changed.push({ nodeId, name: then[nodeId]?.document?.name ?? nodeId });
71
+ }
72
+ return { changeSetId, version, compared: [...new Set(nodeIds)], changed };
73
+ }
74
+
75
+ // A variant publishes with its set, so each set is compared once, as a whole.
76
+ async function publishedComponents(key, get) {
77
+ const [components, sets] = [await get(`/files/${encode(key)}/components`), await get(`/files/${encode(key)}/component_sets`)];
78
+ const out = new Map();
79
+ for (const c of [...(components.meta?.components ?? []), ...(sets.meta?.component_sets ?? [])]) {
80
+ const set = c.containing_frame?.containingComponentSet?.nodeId;
81
+ if (set && !out.has(set)) out.set(set, c.name);
82
+ if (!set) out.set(c.node_id, c.name);
83
+ }
84
+ return out;
85
+ }
86
+
87
+ /** The published components that differ from the last published version. Any failed read fails the whole compare. */
88
+ export async function compareSincePublish(key, { publishedVersion, publishedAt }, { get, progress = () => {} }) {
89
+ const head = await get(`/files/${encode(key)}?depth=1`);
90
+ // Untouched since the publish: nothing to compare, and no node read.
91
+ if (publishedAt && head.lastModified && new Date(head.lastModified) <= new Date(publishedAt)) return { publishedVersion, changed: [] };
92
+ const components = await publishedComponents(key, get);
93
+ const changed = [];
94
+ let compared = 0;
95
+ for (const batch of batches([...components.keys()])) {
96
+ let then;
97
+ try { then = (await get(nodesPath(key, batch, publishedVersion))).nodes ?? {}; }
98
+ catch (error) {
99
+ if (error?.code === "FIGMA_NOT_FOUND") throw new CliError("FIGMA_VERSION_NOT_FOUND", `Figma has no version ${publishedVersion} of ${key} to compare the file with`, 1, { figmaVersion: publishedVersion });
100
+ throw error;
101
+ }
102
+ const now = (await get(nodesPath(key, batch))).nodes ?? {};
103
+ for (const nodeId of batch)
104
+ if (!sameOwnEdits(then[nodeId], now[nodeId])) changed.push({ nodeId, name: components.get(nodeId) ?? nodeId });
105
+ compared += batch.length;
106
+ progress(`${key}: ${compared} of ${components.size} published components compared with ${publishedVersion}`);
107
+ }
108
+ return { publishedVersion, changed };
109
+ }
110
+
111
+ /** Dev's FIGMA_READS_NEEDED answered: the reads with these compares added, and the REST reads they took named. */
112
+ export async function answerPlanReads(key, asked, reads, get, progress = () => {}) {
113
+ const publish = { ...(reads.publish ?? {}) };
114
+ const restReads = new Set(reads.restReads ?? []);
115
+ if (asked.lateWrites?.length) {
116
+ const answers = [];
117
+ for (const one of asked.lateWrites) {
118
+ answers.push(await compareLateWrites(key, one, { get, progress }));
119
+ restReads.add(`GET /files/${key}/nodes at ${one.version} and now: ${one.changeSetId}'s late writes`);
120
+ }
121
+ const replaced = new Set(answers.map((x) => x.changeSetId));
122
+ publish.lateWrites = [...(publish.lateWrites ?? []).filter((x) => !replaced.has(x.changeSetId)), ...answers];
123
+ }
124
+ if (asked.sincePublish) {
125
+ publish.sincePublish = await compareSincePublish(key, asked.sincePublish, { get, progress });
126
+ restReads.add(`GET /files/${key} and its components, component_sets and nodes at ${asked.sincePublish.publishedVersion} and now: changes since the last publish`);
127
+ }
128
+ return { ...reads, publish, restReads: [...restReads] };
129
+ }
@@ -0,0 +1,251 @@
1
+ // What a file's own edits decide about a node, without what Figma resolves
2
+ // from elsewhere. A document read from Figma carries each instance's content
3
+ // from its main component, and the sizes and positions that follow from it, so
4
+ // another set's change to a shared component shows up in every node that uses
5
+ // it. Dev compares this view to ask whether a set's own edits are gone.
6
+ //
7
+ // Canonical source: the hub's `src/lib/design/authored.mjs`. nodii-clis vendors
8
+ // these exact bytes and pins their sha256 in a test, for the compare a lane runs
9
+ // in its own session (MW1-57.11). Pure and dependency-free: no imports, no I/O.
10
+
11
+ const FREE = new Set(["FIXED", undefined]);
12
+ const isAutoLayout = (node) =>
13
+ node?.layoutMode !== undefined && node.layoutMode !== "NONE";
14
+ const box = (node) => node.absoluteBoundingBox;
15
+
16
+ // Figma reports an absolute layer stretched by its constraints as FIXED, but its
17
+ // size follows its parent, as a hugged size follows its content.
18
+ function stretched(node, axis) {
19
+ const along = axis === "horizontal" ? "LEFT_RIGHT" : "TOP_BOTTOM";
20
+ const constraint = node.constraints?.[axis];
21
+ return (
22
+ node.layoutPositioning === "ABSOLUTE" &&
23
+ (constraint === along || constraint === "SCALE")
24
+ );
25
+ }
26
+ function fixedSize(node) {
27
+ const size = box(node);
28
+ if (!size) return {};
29
+ return {
30
+ ...(FREE.has(node.layoutSizingHorizontal) &&
31
+ !stretched(node, "horizontal") && { width: size.width }),
32
+ ...(FREE.has(node.layoutSizingVertical) &&
33
+ !stretched(node, "vertical") && { height: size.height }),
34
+ };
35
+ }
36
+ // A token's value is the token's, not the node's: the binding is what was set.
37
+ const paint = (value) =>
38
+ value.map(({ color, ...rest }) =>
39
+ rest.boundVariables?.color ? rest : { ...rest, color },
40
+ );
41
+ const unresolvedPaints = (node) =>
42
+ Object.fromEntries(
43
+ ["fills", "strokes", "background"].flatMap((key) =>
44
+ Array.isArray(node[key]) ? [[key, paint(node[key])]] : [],
45
+ ),
46
+ );
47
+ function overrideValue(node, field) {
48
+ if (field === "width" || field === "height") return fixedSize(node)[field];
49
+ if (field === "fills" || field === "strokes")
50
+ return unresolvedPaints(node)[field];
51
+ return field in node ? node[field] : node.style?.[field];
52
+ }
53
+ // A layer inside an instance is named from the instance's id, so the same
54
+ // override has another id on an instance that was deleted and made again. What
55
+ // follows that prefix is the layer in the main component; the instance's own
56
+ // override has nothing after it.
57
+ function layerOf(id, instanceId) {
58
+ if (id === instanceId) return "";
59
+ const prefix = `I${instanceId.replace(/^I/, "")};`;
60
+ return id.startsWith(prefix) ? id.slice(prefix.length) : id;
61
+ }
62
+ // A swap property's value is a component's local id, as an instance's main is.
63
+ function swapsByKey(properties, keys) {
64
+ if (!properties || !keys) return properties;
65
+ return Object.fromEntries(
66
+ Object.entries(properties).map(([name, property]) => [
67
+ name,
68
+ property?.type === "INSTANCE_SWAP"
69
+ ? {
70
+ ...property,
71
+ value: keys.get(property.value) ?? property.value,
72
+ }
73
+ : property,
74
+ ]),
75
+ );
76
+ }
77
+ // An instance is its main component, the properties set on it, the way its
78
+ // parent lays it out, and the overrides it lists, with its layers to read their
79
+ // values from. Its id and fixed size count only between two instances that
80
+ // differ (sameInstance).
81
+ function authoredInstance(node, parent, keys) {
82
+ const inside = new Map();
83
+ const listed = [];
84
+ const walk = (n) => {
85
+ inside.set(n.id, n);
86
+ listed.push(...(n.overrides ?? []));
87
+ for (const child of n.children ?? []) walk(child);
88
+ };
89
+ walk(node);
90
+ return {
91
+ id: node.id,
92
+ type: node.type,
93
+ size: fixedSize(node),
94
+ componentId: keys?.get(node.componentId) ?? node.componentId,
95
+ componentProperties: swapsByKey(node.componentProperties, keys),
96
+ ...placed(node, parent),
97
+ layoutAlign: node.layoutAlign,
98
+ layoutGrow: node.layoutGrow,
99
+ layoutSizingHorizontal: node.layoutSizingHorizontal,
100
+ layoutSizingVertical: node.layoutSizingVertical,
101
+ overrides: listed.map(({ id, overriddenFields }) => ({
102
+ layer: layerOf(id, node.id),
103
+ fields: overriddenFields,
104
+ })),
105
+ layers: new Map(
106
+ [...inside].map(([id, layer]) => [layerOf(id, node.id), layer]),
107
+ ),
108
+ };
109
+ }
110
+ // Every field either side overrides must hold the same value on both. A layer
111
+ // shows its effective value, so on a side that doesn't list the field that value
112
+ // is the main component's: an override equal to main is no override. Figma can't
113
+ // record one again, so a node put back on a base that carried some is still at
114
+ // base (CS-2817). A layer one side lacks went with a change to the main
115
+ // component; that is the other set's change, not this one's.
116
+ function sameOverrides(a, b) {
117
+ const fields = new Map();
118
+ for (const { layer, fields: named } of [...a.overrides, ...b.overrides])
119
+ fields.set(layer, new Set([...(fields.get(layer) ?? []), ...named]));
120
+ for (const [layer, named] of fields) {
121
+ const [mine, theirs] = [a.layers.get(layer), b.layers.get(layer)];
122
+ if (!mine || !theirs) continue;
123
+ for (const field of named)
124
+ if (!same(overrideValue(mine, field), overrideValue(theirs, field)))
125
+ return false;
126
+ }
127
+ return true;
128
+ }
129
+ function placed(node, parent) {
130
+ const at = box(node);
131
+ const from = parent ? box(parent) : null;
132
+ if (!at || (isAutoLayout(parent) && node.layoutPositioning !== "ABSOLUTE"))
133
+ return {};
134
+ return { x: at.x - (from?.x ?? 0), y: at.y - (from?.y ?? 0) };
135
+ }
136
+ function authoredNode(node, parent, keys) {
137
+ if (node.type === "INSTANCE") return authoredInstance(node, parent, keys);
138
+ const {
139
+ absoluteBoundingBox: _box,
140
+ absoluteRenderBounds: _render,
141
+ backgroundColor: _background,
142
+ children,
143
+ ...own
144
+ } = node;
145
+ return {
146
+ ...own,
147
+ ...unresolvedPaints(node),
148
+ ...placed(node, parent),
149
+ ...fixedSize(node),
150
+ ...(children && {
151
+ children: children.map((c) => authoredNode(c, node, keys)),
152
+ }),
153
+ };
154
+ }
155
+ const isObject = (value) => typeof value === "object" && value !== null;
156
+ // The same instance's size follows from its main component unless an override
157
+ // sets it. An instance made again lists no such override for a size given when
158
+ // it was drawn, so a fixed size must match the size it replaced. A hugged or
159
+ // filled size follows from elsewhere, whichever instance it is.
160
+ function sameInstance(
161
+ { id: idA, type: _a, size: sizeA, overrides: oa, layers: la, ...a },
162
+ { id: idB, type: _b, size: sizeB, overrides: ob, layers: lb, ...b },
163
+ ) {
164
+ return (
165
+ (idA === idB || same(sizeA, sizeB)) &&
166
+ same(a, b) &&
167
+ sameOverrides({ overrides: oa, layers: la }, { overrides: ob, layers: lb })
168
+ );
169
+ }
170
+ // Two views match when every value set on both sides matches. A property only
171
+ // one side has came from a change to the main component.
172
+ function same(a, b, key) {
173
+ if (a === b) return true;
174
+ if (Array.isArray(a) || Array.isArray(b))
175
+ return (
176
+ Array.isArray(a) &&
177
+ Array.isArray(b) &&
178
+ a.length === b.length &&
179
+ a.every((value, i) => same(value, b[i]))
180
+ );
181
+ if (!isObject(a) || !isObject(b)) return false;
182
+ if (a.type === "INSTANCE" && b.type === "INSTANCE") return sameInstance(a, b);
183
+ const keys =
184
+ key === "componentProperties"
185
+ ? Object.keys(a).filter((k) => k in b)
186
+ : [...new Set([...Object.keys(a), ...Object.keys(b)])];
187
+ return keys.every((k) => same(a[k], b[k], k));
188
+ }
189
+ /**
190
+ * Whether two versions of a node hold the same own edits. Takes each document
191
+ * as JSON, as nodeDocuments returns it.
192
+ *
193
+ * @param {string} then
194
+ * @param {string} now
195
+ * @param {{ before: ReadonlyMap<string, string>, after: ReadonlyMap<string, string> }} [keys]
196
+ * @returns {boolean}
197
+ */
198
+ export function sameAuthored(then, now, keys) {
199
+ return same(
200
+ authoredNode(JSON.parse(then), undefined, keys?.before),
201
+ authoredNode(JSON.parse(now), undefined, keys?.after),
202
+ );
203
+ }
204
+
205
+ // The component each of a document's own instances names, by instance. An
206
+ // instance's insides come from its main component, so they aren't looked in.
207
+ function instanceComponents(document) {
208
+ const found = new Map();
209
+ const walk = (node) => {
210
+ if (node.type !== "INSTANCE") {
211
+ for (const child of node.children ?? []) walk(child);
212
+ return;
213
+ }
214
+ const swaps = Object.values(node.componentProperties ?? {})
215
+ .filter((p) => p?.type === "INSTANCE_SWAP")
216
+ .map((p) => p.value);
217
+ found.set(node.id, new Set([node.componentId, ...swaps]));
218
+ };
219
+ walk(document);
220
+ return found;
221
+ }
222
+ /**
223
+ * What differs between two documents only by a component's local id. Accepting
224
+ * a library update gives a remote component a new local id, while its published
225
+ * key stays (hub-273). Names, per side, the instances to read those
226
+ * keys from and the local ids the keys may stand for: an id both sides name is
227
+ * the same component and is left as it is.
228
+ *
229
+ * @param {string} then
230
+ * @param {string} now
231
+ * @returns {Record<"before" | "after", { instances: string[], components: Set<string> }>}
232
+ */
233
+ export function componentsToCompare(then, now) {
234
+ const [a, b] = [then, now].map((document) =>
235
+ instanceComponents(JSON.parse(document)),
236
+ );
237
+ const ids = (side) => new Set([...side.values()].flatMap((set) => [...set]));
238
+ const [idsA, idsB] = [ids(a), ids(b)];
239
+ const side = (mine, theirs) => {
240
+ const only = [...mine].filter(([, set]) =>
241
+ [...set].some((id) => !theirs.has(id)),
242
+ );
243
+ return {
244
+ instances: only.map(([id]) => id),
245
+ components: new Set(
246
+ only.flatMap(([, set]) => [...set].filter((id) => !theirs.has(id))),
247
+ ),
248
+ };
249
+ };
250
+ return { before: side(a, idsB), after: side(b, idsA) };
251
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.108",
3
+ "version": "0.6.110",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {