@theholocron/holocron-plugin-bruno 5.0.0-alpha.454 → 5.0.0-alpha.456

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # `@theholocron/holocron-plugin-bruno`
2
2
 
3
3
  Bruno plugin for [Holocron](../../cli/cli). Implements the `tooling` capability over files: `holocron export requests`
4
- writes the repo's request collections as OpenCollection YAML, which Bruno imports. Bruno has no HTTP API and no account
4
+ writes the repo's request collections as Bruno JSON files, which Bruno imports. Bruno has no HTTP API and no account
5
5
  to sync to, so there is no token and no network call.
6
6
 
7
7
  ## Install
@@ -19,8 +19,8 @@ pnpm add -D @theholocron/holocron-plugin-bruno
19
19
  providers: {
20
20
  tooling: [
21
21
  ["bruno", {
22
- collectionFiles: ["requests/collection.json"],
23
- envFiles: ["requests/environment.json"],
22
+ collectionFiles: ["api/webhook.collection.json"],
23
+ envFiles: ["api/webhook.environment.json"],
24
24
  }],
25
25
  ],
26
26
  },
@@ -30,18 +30,28 @@ providers: {
30
30
 
31
31
  | Option | Required | Description |
32
32
  | ----------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------ |
33
- | `collectionFiles` | Yes | The collection JSON files (v2.1), relative to the repo root. Each becomes one YAML file. |
33
+ | `workspaceName` | No | The name Bruno shows for the `.bruno/` workspace `sync requests` keeps (default `Workspace`). |
34
+ | `collectionFiles` | Yes | The collection JSON files (v2.1), relative to the repo root. Each becomes one JSON file. |
34
35
  | `envFiles` | No | The environment JSON files, relative to the repo root. A collection holds the ones in its own folder (all when none is there). |
35
36
 
36
37
  ## What it does
37
38
 
38
39
  - `export` converts each collection with Bruno's collection reader (`@usebruno/converters`, which rewrites `pm.*` scripts to
39
- `bru.*` / `req.*`) and the OpenCollection writer (`@opencollection/converters`), dumped with `js-yaml`, and writes
40
- `<name>.yml` under the folder it is given. Environments are inside the document; a secret-type variable is marked `transient`.
41
- The same collection is also written as `<name>.bruno.json`, Bruno's own collection export with the environments inside,
42
- which is the file to import in Bruno (one file for the requests and the environments).
40
+ `bru.*` / `req.*`) and writes `<name>.bruno.json` under the folder it is given (`api/webhook.collection.json` is
41
+ `webhook.bruno.json`): Bruno's own collection export with the environments inside, a secret-type variable marked
42
+ `secret`. It is the file to import in Bruno (one file for the requests and the environments). Bruno rejected the
43
+ OpenCollection YAML this plugin once wrote, so it no longer does.
43
44
  Converter issues are returned, not thrown. A dry run converts and writes nothing.
44
- - `sync` does nothing and succeeds: Bruno keeps no state, and the files are written by `export`.
45
+ - `workspace` keeps the committed `.bruno/` workspace and the request files in step, both ways (`holocron sync requests`), with Bruno's own
46
+ file writer (`@usebruno/filestore`) and reader (`parseRequest`, `parseFolder`, `parseCollection`, `parseEnvironment`):
47
+ `workspace.yml`, and one folder per collection under `collections/` holding `opencollection.yml`, a `folder.yml` per folder,
48
+ a YAML file per request and an `environments/` folder. A secret variable is written without its value. `.bruno/.sync.json`
49
+ records a hash of both sides of each pair at the last sync, so a run knows which side changed: the request file only
50
+ regenerates the workspace, the workspace only regenerates the request file (through `brunoToPostman`, with the request
51
+ file's untouched entries kept as they were), both is a `conflict` that writes nothing unless `prefer` (`source` or
52
+ `workspace`) settles it. A setting only Bruno has stays in the workspace and is reported as an issue. Each file is `new`,
53
+ `changed`, `unchanged`, `removed` or `conflict`; a dry run writes and deletes nothing.
54
+ - `sync` does nothing and succeeds: Bruno keeps no state, and the files are written by `export` and `workspace`.
45
55
  - `doctor` checks `collectionFiles` is set and every file exists and parses as JSON.
46
56
 
47
57
  ## Documentation
package/dist/index.d.mts CHANGED
@@ -2,16 +2,18 @@
2
2
  * `@theholocron/holocron-plugin-bruno` — entrypoint.
3
3
  *
4
4
  * Implements the `tooling` capability for Bruno over files: `holocron export requests` writes the repo's request
5
- * collections as OpenCollection YAML, which Bruno opens as a collection. Bruno has no HTTP API and no account to sync
5
+ * collections as Bruno JSON files, which Bruno imports. Bruno has no HTTP API and no account to sync
6
6
  * to, so the plugin has no token and makes no network call, and so no `auth.ts`.
7
7
  */
8
- import { Tooling, ToolingDoctorReport, ToolingExportInput, ToolingExportResult } from "@theholocron/cli";
8
+ import { Tooling, ToolingDoctorReport, ToolingExportInput, ToolingExportResult, ToolingWorkspaceInput, ToolingWorkspaceResult } from "@theholocron/cli";
9
9
  /** Options for the Bruno `tooling` provider: the same two file lists the other tooling providers take. */
10
10
  interface BrunoToolingOptions {
11
11
  /** Collection JSON files (v2.1), relative to `repoRoot`. */
12
12
  collectionFiles?: string[];
13
13
  /** Environment JSON files, relative to `repoRoot`; each goes into every collection it is exported with (`export requests` hands a folder's collections the files beside them). */
14
14
  envFiles?: string[];
15
+ /** The name Bruno shows for the `.bruno/` workspace that `workspace()` keeps (default `Workspace`). */
16
+ workspaceName?: string;
15
17
  /** Working repo root. Defaults to `process.cwd()`. */
16
18
  repoRoot?: string;
17
19
  }
@@ -28,27 +30,26 @@ export declare class BrunoTooling implements Tooling {
28
30
  sync(): Promise<void>;
29
31
  doctor(): Promise<ToolingDoctorReport>;
30
32
  export(input: ToolingExportInput): Promise<ToolingExportResult>;
33
+ workspace(input: ToolingWorkspaceInput): Promise<ToolingWorkspaceResult>;
31
34
  }
32
35
  /** What {@link convertCollection} produced. */
33
36
  interface ConvertedCollection {
34
- /** The OpenCollection document, as YAML. */
35
- text: string;
36
- /** The same collection as one Bruno JSON file, environments inside, which Bruno's collection import reads. */
37
+ /** The collection as one Bruno JSON file, environments inside, which Bruno's collection import reads. */
37
38
  json: string;
38
39
  /** What the converters reported they could not carry across, one line each. */
39
40
  issues: string[];
40
41
  }
41
42
  /**
42
- * Converts one v2.1 collection (and the environments that go with it) to an OpenCollection YAML document: Bruno's
43
- * reader turns it into a Bruno collection and rewrites its `pm.*` scripts to `bru.*` / `req.*`, then the OpenCollection
44
- * converter lays that out, environments included (a secret-type variable becomes `transient`). Each environment is
45
- * given its `.bru` file name first, because that is where the OpenCollection converter takes its name from.
43
+ * Converts one v2.1 collection (and the environments that go with it) to Bruno's own JSON export: Bruno's reader turns
44
+ * it into a Bruno collection and rewrites its `pm.*` scripts to `bru.*` / `req.*`, and the environments go inside the
45
+ * file (a secret-type variable is marked `secret`).
46
46
  */
47
47
  export declare function convertCollection(collection: unknown, environments: unknown[]): Promise<ConvertedCollection>;
48
48
  /**
49
- * The output file name for each collection file, in order: its own name with `extension` in place of `.json`
50
- * (`collection.json` is `collection.yml` for `.yml`). Two files with the same name would overwrite each other, so those
51
- * use the whole path instead, its folders joined with `-` (`apps-a-collection.yml`).
49
+ * The output file name for each collection file, in order: its own name with `extension` in place of `.json`, and
50
+ * without a `.collection` part (`api/webhook.collection.json` is `webhook.bruno.json`; `collection.json` is
51
+ * `collection.bruno.json`). Two files with the same name would overwrite each other, so those use the whole path instead, its
52
+ * folders joined with `-` (`apps-a-collection.bruno.json`).
52
53
  */
53
54
  export declare function outputNames(files: string[], extension?: string): string[];
54
55
  /** Options for the Bruno plugin; the same as the `tooling` capability's. */
package/dist/index.mjs CHANGED
@@ -1,15 +1,16 @@
1
- import { mkdir, readFile, writeFile } from "node:fs/promises";
2
- import { basename, extname, join, resolve } from "node:path";
3
- import { brunoToOpenCollection } from "@opencollection/converters";
4
- import { postmanToBruno, postmanToBrunoEnvironment } from "@usebruno/converters";
5
- import { dump } from "js-yaml";
6
- // src/convert-collection.ts
1
+ import { access, mkdir, readFile, readdir, rmdir, unlink, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
3
+ import { brunoToPostman, postmanToBruno, postmanToBrunoEnvironment } from "@usebruno/converters";
4
+ import { parseCollection, parseEnvironment, parseFolder, parseRequest, stringifyCollection, stringifyEnvironment, stringifyFolder, stringifyRequest } from "@usebruno/filestore";
5
+ import { createHash } from "node:crypto";
6
+ // src/describe-issue.ts
7
7
  /** One line for a converter's issue, whatever shape it came in. */
8
8
  const describeIssue = (issue) => {
9
9
  if (typeof issue === "string") return issue;
10
10
  if (issue !== null && typeof issue === "object" && "message" in issue && typeof issue.message === "string") return issue.message;
11
11
  return JSON.stringify(issue);
12
12
  };
13
+ // src/convert-collection.ts
13
14
  /** The collection as Bruno's own JSON export lays it out: one file, with the environments inside it. */
14
15
  function brunoJson(bruno) {
15
16
  const environments = (bruno.environments ?? []).map(({ filename: _filename, ...env }) => env);
@@ -29,51 +30,848 @@ function brunoJson(bruno) {
29
30
  return `${JSON.stringify(exported, null, 2)}\n`;
30
31
  }
31
32
  /**
32
- * Converts one v2.1 collection (and the environments that go with it) to an OpenCollection YAML document: Bruno's
33
- * reader turns it into a Bruno collection and rewrites its `pm.*` scripts to `bru.*` / `req.*`, then the OpenCollection
34
- * converter lays that out, environments included (a secret-type variable becomes `transient`). Each environment is
35
- * given its `.bru` file name first, because that is where the OpenCollection converter takes its name from.
33
+ * Converts one v2.1 collection (and the environments that go with it) to Bruno's own JSON export: Bruno's reader turns
34
+ * it into a Bruno collection and rewrites its `pm.*` scripts to `bru.*` / `req.*`, and the environments go inside the
35
+ * file (a secret-type variable is marked `secret`).
36
36
  */
37
37
  async function convertCollection(collection, environments) {
38
38
  const read = await postmanToBruno(collection, { preserveScripts: false });
39
39
  const bruno = read.collection;
40
40
  const converted = await Promise.all(environments.map((env) => postmanToBrunoEnvironment(env)));
41
- if (converted.length > 0) bruno.environments = converted.map((env) => ({
42
- ...env,
43
- filename: `${env.name}.bru`
44
- }));
41
+ if (converted.length > 0) bruno.environments = converted;
45
42
  return {
46
- text: dump(brunoToOpenCollection(bruno), { lineWidth: 120 }),
47
43
  json: brunoJson(bruno),
48
44
  issues: (read.issues ?? []).map(describeIssue)
49
45
  };
50
46
  }
51
47
  // src/output-names.ts
48
+ /** A file's path with its extension and a trailing `.collection` taken off (`api/webhook.collection.json` is `api/webhook`). */
49
+ const withoutSuffix = (file) => file.slice(0, file.length - extname(file).length).replace(/\.collection$/, "");
52
50
  /**
53
- * The output file name for each collection file, in order: its own name with `extension` in place of `.json`
54
- * (`collection.json` is `collection.yml` for `.yml`). Two files with the same name would overwrite each other, so those
55
- * use the whole path instead, its folders joined with `-` (`apps-a-collection.yml`).
51
+ * The output file name for each collection file, in order: its own name with `extension` in place of `.json`, and
52
+ * without a `.collection` part (`api/webhook.collection.json` is `webhook.bruno.json`; `collection.json` is
53
+ * `collection.bruno.json`). Two files with the same name would overwrite each other, so those use the whole path instead, its
54
+ * folders joined with `-` (`apps-a-collection.bruno.json`).
56
55
  */
57
- function outputNames(files, extension = ".yml") {
58
- const stem = (file) => basename(file, extname(file));
56
+ function outputNames(files, extension = ".bruno.json") {
57
+ const stem = (file) => basename(withoutSuffix(file));
59
58
  const counts = /* @__PURE__ */ new Map();
60
59
  for (const file of files) counts.set(stem(file), (counts.get(stem(file)) ?? 0) + 1);
61
60
  return files.map((file) => {
62
61
  if (counts.get(stem(file)) === 1) return `${stem(file)}${extension}`;
63
- return `${file.slice(0, file.length - extname(file).length).split("/").filter(Boolean).join("-")}${extension}`;
62
+ return `${withoutSuffix(file).split("/").filter(Boolean).join("-")}${extension}`;
63
+ });
64
+ }
65
+ // src/format-json.ts
66
+ /** Prettier's default for a JSON file under this repo's config (`printWidth: 120`, 2-space indent). */
67
+ const PRINT_WIDTH = 120;
68
+ const INDENT = " ";
69
+ const pad = (depth) => INDENT.repeat(depth);
70
+ const isPlain = (value) => value === null || typeof value !== "object";
71
+ /** `column` is how many characters are already on the line before `value`; `comma` is 1 when a `,` follows it. */
72
+ function render(value, depth, column, comma) {
73
+ if (isPlain(value)) return JSON.stringify(value);
74
+ if (Array.isArray(value)) {
75
+ if (value.length === 0) return "[]";
76
+ if (value.every(isPlain)) {
77
+ const oneLine = `[${value.map((item) => JSON.stringify(item)).join(", ")}]`;
78
+ if (column + oneLine.length + comma <= PRINT_WIDTH) return oneLine;
79
+ }
80
+ return `[\n${value.map((item, i) => {
81
+ const last = i === value.length - 1;
82
+ return `${pad(depth + 1)}${render(item, depth + 1, (depth + 1) * 2, last ? 0 : 1)}`;
83
+ }).join(",\n")}\n${pad(depth)}]`;
84
+ }
85
+ const entries = Object.entries(value);
86
+ if (entries.length === 0) return "{}";
87
+ return `{\n${entries.map(([key, member], i) => {
88
+ const prefix = `${pad(depth + 1)}${JSON.stringify(key)}: `;
89
+ return `${prefix}${render(member, depth + 1, prefix.length, i === entries.length - 1 ? 0 : 1)}`;
90
+ }).join(",\n")}\n${pad(depth)}}`;
91
+ }
92
+ /**
93
+ * `value` as JSON laid out the way this repo's Prettier lays out a `.json` file, so a request file this plugin writes
94
+ * already passes the formatting check: objects expanded one key per line, an array of plain values on one line when it
95
+ * fits in 120 columns, a single newline at the end. (The same layout as astromech's `formatJson`; a plugin imports no
96
+ * astromech.)
97
+ */
98
+ function formatJson(value) {
99
+ return `${render(JSON.parse(JSON.stringify(value)), 0, 0, 0)}\n`;
100
+ }
101
+ // src/baseline.ts
102
+ /** Where the baseline sits, relative to the repo root. */
103
+ const BASELINE_FILE = ".bruno/.sync.json";
104
+ const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
105
+ /** Checks the shape of a parsed baseline; anything else is an error that names the file. */
106
+ function parseBaseline(value) {
107
+ if (!isObject$1(value) || value.version !== 1 || !Array.isArray(value.pairs)) throw new Error(`${BASELINE_FILE}: not a version 1 baseline; delete it to start again (the next sync rebuilds it)`);
108
+ return {
109
+ version: 1,
110
+ pairs: value.pairs.map((pair, index) => {
111
+ if (!(isObject$1(pair) && (pair.kind === "collection" || pair.kind === "environment") && [
112
+ pair.source,
113
+ pair.workspace,
114
+ pair.sourceHash,
115
+ pair.workspaceHash
116
+ ].every((v) => typeof v === "string"))) throw new Error(`${BASELINE_FILE}: pair ${index + 1} is malformed; delete the file to start again`);
117
+ return pair;
118
+ })
119
+ };
120
+ }
121
+ /** The text of the baseline, pairs in a fixed order so a re-run changes nothing. */
122
+ function serializeBaseline(pairs) {
123
+ return formatJson({
124
+ version: 1,
125
+ pairs: [...pairs].sort((a, b) => `${a.source}\0${a.workspace}` < `${b.source}\0${b.workspace}` ? -1 : 1)
126
+ });
127
+ }
128
+ /** The baseline and its text, or `undefined` when there is none yet. A damaged one is an error. */
129
+ async function readBaseline(repoRoot) {
130
+ let text;
131
+ try {
132
+ text = await readFile(join(repoRoot, BASELINE_FILE), "utf8");
133
+ } catch (err) {
134
+ if (err.code === "ENOENT") return void 0;
135
+ throw err;
136
+ }
137
+ try {
138
+ return {
139
+ baseline: parseBaseline(JSON.parse(text)),
140
+ text
141
+ };
142
+ } catch (err) {
143
+ if (err.message.startsWith(".bruno/.sync.json")) throw err;
144
+ throw new Error(`${BASELINE_FILE}: ${err.message}; delete it to start again`, { cause: err });
145
+ }
146
+ }
147
+ // src/collection-files.ts
148
+ /** A name safe to use as a file or folder name on any platform, as Bruno itself makes one from a request's name. */
149
+ function safeName(name) {
150
+ const cleaned = name.replace(/[\\/:*?"<>|]/g, "-").trim().replace(/[. ]+$/, "");
151
+ return cleaned === "" ? "untitled" : cleaned;
152
+ }
153
+ /** The first of `name`, `name (2)`, `name (3)`… that `taken` does not hold, compared without regard to case. */
154
+ function uniqueName(name, taken) {
155
+ let candidate = name;
156
+ for (let n = 2; taken.has(candidate.toLowerCase()); n += 1) candidate = `${name} (${n})`;
157
+ taken.add(candidate.toLowerCase());
158
+ return candidate;
159
+ }
160
+ /** Lays one folder's items out under `dir`: a folder as `<name>/folder.yml` plus its items, a request as `<name>.yml`. */
161
+ function writeItems(items, dir, files) {
162
+ const taken = /* @__PURE__ */ new Set();
163
+ for (const item of items) {
164
+ const name = uniqueName(safeName(item.name ?? "untitled"), taken);
165
+ if (item.type === "folder") {
166
+ const folder = `${dir}${name}/`;
167
+ const meta = {
168
+ name: item.name,
169
+ ...item.seq === void 0 ? {} : { seq: item.seq }
170
+ };
171
+ files.set(`${folder}folder.yml`, stringifyFolder({
172
+ ...item.root,
173
+ meta
174
+ }, { format: "yml" }));
175
+ writeItems(item.items ?? [], folder, files);
176
+ } else files.set(`${dir}${name}.yml`, stringifyRequest(item, { format: "yml" }));
177
+ }
178
+ }
179
+ /**
180
+ * Converts one v2.1 collection (and the environments that go with it) to the files Bruno itself writes for a
181
+ * collection folder: `opencollection.yml`, a `folder.yml` for each folder, one YAML file for each request and one
182
+ * for each environment under `environments/`. Bruno's reader turns the collection into Bruno's own model and
183
+ * rewrites its `pm.*` scripts to `bru.*` / `req.*`; Bruno's file writer then lays that model out, so the files are
184
+ * what the app would have saved. A secret-type variable is written without its value.
185
+ */
186
+ async function collectionFiles(collection, environments) {
187
+ const read = await postmanToBruno(collection, { preserveScripts: false });
188
+ const bruno = read.collection;
189
+ const name = bruno.name ?? "Untitled Collection";
190
+ const files = /* @__PURE__ */ new Map();
191
+ files.set("opencollection.yml", stringifyCollection(bruno.root ?? {}, {
192
+ name,
193
+ type: "collection",
194
+ ignore: ["node_modules", ".git"]
195
+ }, { format: "yml" }));
196
+ writeItems(bruno.items ?? [], "", files);
197
+ const taken = /* @__PURE__ */ new Set();
198
+ const environmentFiles = [];
199
+ for (const source of environments) {
200
+ const environment = await postmanToBrunoEnvironment(source);
201
+ const file = `environments/${uniqueName(safeName(environment.name), taken)}.yml`;
202
+ environmentFiles.push(file);
203
+ files.set(file, stringifyEnvironment(environment, { format: "yml" }));
204
+ }
205
+ return {
206
+ name,
207
+ files,
208
+ environmentFiles,
209
+ issues: (read.issues ?? []).map(describeIssue)
210
+ };
211
+ }
212
+ // src/workspace-to-source.ts
213
+ /** A value in a stable text: object keys sorted, so two equal documents give the same text whatever their key order. */
214
+ function canonicalJson(value) {
215
+ const sort = (v) => {
216
+ if (Array.isArray(v)) return v.map(sort);
217
+ if (v !== null && typeof v === "object") return Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, member]) => [key, sort(member)]));
218
+ return v;
219
+ };
220
+ return JSON.stringify(sort(value));
221
+ }
222
+ /** The SHA-256 of a text, in hex. */
223
+ const hashOf = (text) => createHash("sha256").update(text).digest("hex");
224
+ /** Names a text as the file it came from, for an error. */
225
+ function reading(path, read) {
226
+ try {
227
+ return read();
228
+ } catch (err) {
229
+ throw new Error(`${path}: ${err.message}`, { cause: err });
230
+ }
231
+ }
232
+ /** Lays the files of one folder out as Bruno's items: the folders (each with its `folder.yml`) and the requests. */
233
+ function itemsIn(files, prefix) {
234
+ const folders = /* @__PURE__ */ new Set();
235
+ const requests = [];
236
+ for (const path of files.keys()) {
237
+ if (!path.startsWith(prefix)) continue;
238
+ const rest = path.slice(prefix.length);
239
+ const slash = rest.indexOf("/");
240
+ if (slash >= 0) folders.add(rest.slice(0, slash));
241
+ else if (rest !== "folder.yml" && (prefix !== "" || rest !== "opencollection.yml")) requests.push(path);
242
+ }
243
+ const items = [];
244
+ for (const name of [...folders].sort()) {
245
+ const folderPath = `${prefix}${name}/`;
246
+ const text = files.get(`${folderPath}folder.yml`);
247
+ const root = text === void 0 ? {} : reading(`${folderPath}folder.yml`, () => parseFolder(text, { format: "yml" }));
248
+ const meta = root.meta ?? {};
249
+ items.push({
250
+ type: "folder",
251
+ name: meta.name ?? name,
252
+ seq: meta.seq,
253
+ root,
254
+ items: itemsIn(files, folderPath)
255
+ });
256
+ }
257
+ for (const path of requests.sort()) {
258
+ const parsed = reading(path, () => parseRequest(files.get(path), { format: "yml" }));
259
+ for (const key of [
260
+ "items",
261
+ "root",
262
+ "fileContent",
263
+ "filename",
264
+ "pathname",
265
+ "app"
266
+ ]) delete parsed[key];
267
+ items.push({
268
+ ...parsed,
269
+ type: parsed.type,
270
+ seq: parsed.seq
271
+ });
272
+ }
273
+ items.sort((a, b) => (a.seq ?? Number.MAX_SAFE_INTEGER) - (b.seq ?? Number.MAX_SAFE_INTEGER));
274
+ items.forEach((item, index) => {
275
+ if (!Number.isInteger(item.seq)) item.seq = index + 1;
276
+ });
277
+ return items;
278
+ }
279
+ /** The documentation text of each folder, by name, in the order of Bruno's items (a name used twice is taken in turn). */
280
+ function folderDocs(items) {
281
+ const docs = /* @__PURE__ */ new Map();
282
+ for (const item of items.filter((i) => i.type === "folder")) {
283
+ const text = typeof item.root?.docs === "string" ? item.root.docs : "";
284
+ docs.set(item.name ?? "", [...docs.get(item.name ?? "") ?? [], text]);
285
+ }
286
+ return docs;
287
+ }
288
+ /** Puts a folder's documentation back as its `description`, which Bruno's own writer leaves out, all the way down. */
289
+ function describeFolders(exported, items) {
290
+ const docs = folderDocs(items);
291
+ const children = /* @__PURE__ */ new Map();
292
+ for (const item of items.filter((i) => i.type === "folder")) children.set(item.name ?? "", [...children.get(item.name ?? "") ?? [], item.items ?? []]);
293
+ return exported.map((entry) => {
294
+ if (!Array.isArray(entry.item)) return entry;
295
+ const name = String(entry.name);
296
+ const description = docs.get(name)?.shift() ?? "";
297
+ const inner = children.get(name)?.shift() ?? [];
298
+ const { name: _name, description: _description, item: nested, ...rest } = entry;
299
+ return {
300
+ name,
301
+ ...description === "" ? {} : { description },
302
+ ...rest,
303
+ item: describeFolders(nested, inner)
304
+ };
305
+ });
306
+ }
307
+ const isJson = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
308
+ const asList = (value) => Array.isArray(value) ? value.filter(isJson) : [];
309
+ /** Drops the entries of `names` from `entry` whose value is `empty` (an empty string, `false`, `{}`, `[]` or `"default"`). */
310
+ function dropEmpty(entry, names, empty) {
311
+ return Object.fromEntries(Object.entries(entry).filter(([key, value]) => !(names.includes(key) && empty(value))));
312
+ }
313
+ const isEmptyValue = (value) => value === "" || value === false || value === "default" || Array.isArray(value) && value.length === 0 || isJson(value) && Object.keys(value).length === 0;
314
+ /** Puts the keys of `entry` in the order `first` names, then the rest in the order they were. */
315
+ function ordered(entry, first) {
316
+ const rest = Object.keys(entry).filter((key) => !first.includes(key));
317
+ return Object.fromEntries([...first.filter((key) => key in entry), ...rest].map((key) => [key, entry[key]]));
318
+ }
319
+ /**
320
+ * Takes out what Bruno's exporter adds to every entry and a request file never carries (an empty `description`, a
321
+ * header's `disabled: false` and `type: "default"`, an empty `packages` / `requests` on a script, an empty `protocol`,
322
+ * `query` and `variable` on a URL) and puts keys in the order a request file lists them, so a collection Bruno rewrote
323
+ * differs from the one before it only where its content changed.
324
+ */
325
+ function tidy(item) {
326
+ if (Array.isArray(item.item)) return ordered({
327
+ ...item,
328
+ item: asList(item.item).map(tidy),
329
+ event: tidyEvents(item.event)
330
+ }, [
331
+ "name",
332
+ "description",
333
+ "event",
334
+ "item"
335
+ ]);
336
+ const request = isJson(item.request) ? item.request : void 0;
337
+ const url = request && isJson(request.url) ? dropEmpty(request.url, [
338
+ "protocol",
339
+ "query",
340
+ "variable"
341
+ ], isEmptyValue) : void 0;
342
+ const tidied = request ? ordered({
343
+ ...request,
344
+ header: asList(request.header).map((h) => dropEmpty(h, [
345
+ "description",
346
+ "disabled",
347
+ "type"
348
+ ], isEmptyValue)),
349
+ ...url ? { url: ordered(url, [
350
+ "raw",
351
+ "host",
352
+ "path"
353
+ ]) } : {}
354
+ }, [
355
+ "method",
356
+ "description",
357
+ "header",
358
+ "body",
359
+ "auth",
360
+ "url"
361
+ ]) : void 0;
362
+ return ordered({
363
+ ...item,
364
+ event: tidyEvents(item.event),
365
+ ...tidied ? { request: tidied } : {}
366
+ }, [
367
+ "name",
368
+ "event",
369
+ "request"
370
+ ]);
371
+ }
372
+ /** A script's events without the empty `packages` and `requests` Bruno's exporter adds. */
373
+ function tidyEvents(events) {
374
+ if (!Array.isArray(events)) return void 0;
375
+ return asList(events).map((event) => isJson(event.script) ? {
376
+ ...event,
377
+ script: dropEmpty(event.script, ["packages", "requests"], isEmptyValue)
378
+ } : event);
379
+ }
380
+ /**
381
+ * Turns the files of one Bruno collection folder (paths inside the folder, `/` separators, the `environments/` files
382
+ * left out) back into a v2.1 collection: Bruno's own reader for each file, Bruno's own `brunoToPostman` for the whole,
383
+ * and two repairs for what that exporter drops, a folder's documentation and the variables it makes up for a dynamic
384
+ * `{{$guid}}`. The result is a function of what the files hold, so it is also the text two equal collections have in
385
+ * common: the sync generates it from the request file as well and compares the two.
386
+ */
387
+ function workspaceToSource(files) {
388
+ const opencollection = files.get("opencollection.yml");
389
+ if (opencollection === void 0) throw new Error("opencollection.yml: not found");
390
+ const { collectionRoot, brunoConfig } = reading("opencollection.yml", () => parseCollection(opencollection, { format: "yml" }));
391
+ const items = itemsIn(files, "");
392
+ const exported = brunoToPostman({
393
+ name: brunoConfig.name ?? "Untitled Collection",
394
+ root: collectionRoot,
395
+ items: structuredClone(items),
396
+ environments: []
397
+ });
398
+ const variable = Array.isArray(exported.variable) ? asList(exported.variable).filter((entry) => !String(entry.key ?? "").startsWith("$")).map((entry) => dropEmpty(entry, ["type"], isEmptyValue)) : void 0;
399
+ const { event, ...rest } = exported;
400
+ return {
401
+ ...rest,
402
+ ...variable === void 0 ? {} : { variable },
403
+ ...event === void 0 ? {} : { event: tidyEvents(event) },
404
+ item: describeFolders(asList(exported.item), items).map(tidy)
405
+ };
406
+ }
407
+ /**
408
+ * `derived` with each key whose value is the same as in `carried` (as the workspace carries it) taken from `original`;
409
+ * for a key named in `nested`, the same is done one level down, so a request whose URL changed keeps its own scripts.
410
+ */
411
+ function keepKeys(derived, carried, original, nested = []) {
412
+ const merged = {};
413
+ for (const key of [...Object.keys(original), ...Object.keys(derived)]) {
414
+ if (key in merged || !(key in derived)) continue;
415
+ if (key in original && canonicalJson(carried[key]) === canonicalJson(derived[key])) merged[key] = original[key];
416
+ else if (nested.includes(key) && isJson(derived[key]) && isJson(carried[key]) && isJson(original[key])) merged[key] = keepKeys(derived[key], carried[key], original[key]);
417
+ else merged[key] = derived[key];
418
+ }
419
+ return merged;
420
+ }
421
+ /** The items of `derived` with each one that is the same as in `carried` (the original as the workspace carries it) swapped for the original's own text. */
422
+ function keepItems(derived, carried, original) {
423
+ return derived.map((item) => {
424
+ const same = (candidate) => candidate.name === item.name && Array.isArray(candidate.item) === Array.isArray(item.item);
425
+ const carriedItem = carried.find(same);
426
+ const originalItem = original.find(same);
427
+ if (!carriedItem || !originalItem) return item;
428
+ if (canonicalJson(carriedItem) === canonicalJson(item)) return originalItem;
429
+ if (!Array.isArray(item.item)) return keepKeys(item, carriedItem, originalItem, ["request"]);
430
+ const own = (entry) => canonicalJson({
431
+ ...entry,
432
+ item: void 0
433
+ });
434
+ const children = keepItems(asList(item.item), asList(carriedItem.item), asList(originalItem.item));
435
+ return own(carriedItem) === own(item) ? {
436
+ ...originalItem,
437
+ item: children
438
+ } : {
439
+ ...item,
440
+ item: children
441
+ };
442
+ });
443
+ }
444
+ /**
445
+ * `derived` (a collection read back from the workspace) laid over `original` (the request file as it was): every
446
+ * entry the workspace carries the same as before keeps the original's own text, in its own key order, so a change made
447
+ * in the workspace rewrites only what it changed and not every script Bruno writes a little differently. `carried`
448
+ * is the original as the workspace carries it (`workspaceToSource` of the files the original generates).
449
+ */
450
+ function keepOriginal(derived, carried, original) {
451
+ const merged = {};
452
+ for (const key of [...Object.keys(original), ...Object.keys(derived)]) {
453
+ if (key in merged || !(key in derived)) continue;
454
+ if (key === "item") merged.item = keepItems(asList(derived.item), asList(carried.item), asList(original.item));
455
+ else if (key in original && canonicalJson(carried[key]) === canonicalJson(derived[key])) merged[key] = original[key];
456
+ else if (key === "info" && isJson(original.info) && isJson(derived.info)) merged.info = {
457
+ ...original.info,
458
+ ...derived.info
459
+ };
460
+ else merged[key] = derived[key];
461
+ }
462
+ return merged;
463
+ }
464
+ /** What an environment file holds as the request files write it: `{ name, values: [{ key, value, type, enabled }] }`. */
465
+ function environmentToSource(text, path) {
466
+ const environment = reading(path, () => parseEnvironment(text, { format: "yml" }));
467
+ return {
468
+ name: environment.name,
469
+ values: (environment.variables ?? []).map((variable) => ({
470
+ key: variable.name,
471
+ value: variable.secret ? "" : variable.value ?? "",
472
+ type: variable.secret ? "secret" : "default",
473
+ enabled: variable.enabled ?? true
474
+ }))
475
+ };
476
+ }
477
+ // src/sync-workspace.ts
478
+ /** The folder at the repo root that holds the workspace Bruno opens. */
479
+ const WORKSPACE_DIR = ".bruno";
480
+ /** `Sentinel webhook` as `sentinel-webhook`: the folder a collection gets under `collections/`. */
481
+ function collectionFolder(name) {
482
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
483
+ return slug === "" ? "collection" : slug;
484
+ }
485
+ /** The workspace file Bruno reads: its name and the collections it lists, each by a path from the workspace folder. */
486
+ function workspaceYml(name, collections) {
487
+ const listed = collections.map((c) => ` - name: ${JSON.stringify(c.name)}\n path: ${JSON.stringify(c.path)}`);
488
+ return [
489
+ "opencollection: 1.0.0",
490
+ "info:",
491
+ ` name: ${JSON.stringify(name)}`,
492
+ " type: workspace",
493
+ "",
494
+ "collections:",
495
+ ...listed,
496
+ ""
497
+ ].join("\n");
498
+ }
499
+ /** The text of a file, or `undefined` when it is not there. */
500
+ async function readIfThere(path) {
501
+ try {
502
+ return await readFile(path, "utf8");
503
+ } catch (err) {
504
+ if (err.code === "ENOENT") return void 0;
505
+ throw err;
506
+ }
507
+ }
508
+ /** Every `.yml` file below `dir` (empty when it is not there) with its text, by path from `dir` with `/` separators. */
509
+ async function ymlFilesBelow(dir) {
510
+ const files = /* @__PURE__ */ new Map();
511
+ let entries;
512
+ try {
513
+ entries = await readdir(dir, {
514
+ recursive: true,
515
+ withFileTypes: true
516
+ });
517
+ } catch (err) {
518
+ if (err.code === "ENOENT") return files;
519
+ throw err;
520
+ }
521
+ const paths = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".yml")).map((entry) => relative(dir, join(entry.parentPath, entry.name)).split(sep).join("/")).filter((path) => !path.split("/").includes("node_modules")).sort();
522
+ for (const path of paths) files.set(path, await readFile(join(dir, path), "utf8"));
523
+ return files;
524
+ }
525
+ /** Removes `dir` and each parent up to `stop` while it is empty; a folder that still holds something stays. */
526
+ async function pruneEmpty(dir, stop) {
527
+ for (let current = dir; current !== stop && current.startsWith(stop); current = dirname(current)) try {
528
+ await rmdir(current);
529
+ } catch {
530
+ return;
531
+ }
532
+ }
533
+ /**
534
+ * Which way one pair goes. A side that is not there is made from the other. With a baseline, only the side that
535
+ * differs from it has changed: the other is regenerated from it. A pair with no baseline, or with both sides
536
+ * changed, is in step when the two already hold the same thing and otherwise a conflict, which `prefer` settles.
537
+ */
538
+ function decide(input) {
539
+ if (!input.workspacePresent) return "toWorkspace";
540
+ if (!input.sourcePresent) return "toSource";
541
+ const { prior } = input;
542
+ if (prior) {
543
+ const sourceChanged = prior.sourceHash !== input.sourceHash;
544
+ const workspaceChanged = prior.workspaceHash !== input.workspaceHash;
545
+ if (!sourceChanged && !workspaceChanged) return "agree";
546
+ if (!workspaceChanged) return "toWorkspace";
547
+ if (!sourceChanged) return "toSource";
548
+ }
549
+ if (input.agree()) return "agree";
550
+ if (input.prefer === "source") return "toWorkspace";
551
+ if (input.prefer === "workspace") return "toSource";
552
+ return "conflict";
553
+ }
554
+ /** The hash of a folder's request files: every path and text, in path order. */
555
+ const folderHash = (files) => hashOf([...files.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([path, text]) => `${path}\0${text}`).join("\0\0"));
556
+ /** A collection with nothing in it, to name and convert environments when the collection file is not there. */
557
+ const EMPTY_COLLECTION = {
558
+ info: {
559
+ name: "Collection",
560
+ schema: "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
561
+ },
562
+ item: []
563
+ };
564
+ /** Whether two sets of files have the same paths and the same texts. */
565
+ const sameFiles = (a, b) => a.size === b.size && [...a].every(([path, text]) => b.get(path) === text);
566
+ /** A request file as the workspace can carry it: what its own conversion gives back, as a stable text. */
567
+ async function carriedCollection(json) {
568
+ return { canon: canonicalJson(workspaceToSource(requestFiles((await collectionFiles(json, [])).files))) };
569
+ }
570
+ /** The files of a collection folder that are requests and folders, not environments. */
571
+ function requestFiles(files) {
572
+ return new Map([...files].filter(([path]) => !path.startsWith("environments/")));
573
+ }
574
+ /** An environment's file text and the `{ name, values }` it carries, from the request file's side. */
575
+ async function carriedEnvironment(json) {
576
+ const text = stringifyEnvironment(await postmanToBrunoEnvironment(json), { format: "yml" });
577
+ return {
578
+ text,
579
+ canon: canonicalJson(environmentToSource(text, "the environment"))
580
+ };
581
+ }
582
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
583
+ /** Everything a run decided, applied only when it is not a dry run and nothing is in conflict. */
584
+ var Plan = class {
585
+ files = [];
586
+ issues = [];
587
+ writes = /* @__PURE__ */ new Map();
588
+ deletes = [];
589
+ pairs = [];
590
+ conflicts = 0;
591
+ /** Plans a write; a second, different text for the same path is a conflict of its own. */
592
+ write(path, text) {
593
+ const earlier = this.writes.get(path);
594
+ if (earlier !== void 0 && earlier !== text) {
595
+ this.conflicts += 1;
596
+ this.files.push({
597
+ path,
598
+ state: "conflict",
599
+ note: "two pairs would write different content to this file; edit one environment file and sync again"
600
+ });
601
+ return;
602
+ }
603
+ this.writes.set(path, text);
604
+ }
605
+ };
606
+ /** Reports what a pair in conflict holds and keeps its baseline as it was. */
607
+ function conflictNote(what) {
608
+ return `${what} changed on both sides since the last sync; pass --prefer source (the request file wins) or --prefer workspace (the workspace wins)`;
609
+ }
610
+ /**
611
+ * Keeps the `.bruno/` workspace and the request files in step, both ways. Each collection and each environment is a
612
+ * pair; `.bruno/.sync.json` holds what both sides looked like at the last sync, so a run can tell which side changed
613
+ * (see {@link decide}). The request file's hash is the hash of what the workspace can carry of it, so a setting that
614
+ * only the workspace holds (a request's timeout) never looks like a change to the request file; the workspace's hash is
615
+ * that of its own files, so such an edit is still seen as a change to the workspace and is never overwritten by a
616
+ * request-file change without a conflict. `workspace.yml` is written when it is missing or does not list a collection,
617
+ * and left alone otherwise, because Bruno adds settings of its own to it, such as the active environment.
618
+ *
619
+ * A file is `new`, `changed` or `unchanged` by its text; a workspace file that is no longer generated is `removed`;
620
+ * a pair that both sides changed is a `conflict`, and with a conflict (and no `prefer`) nothing at all is written.
621
+ */
622
+ async function syncWorkspace(input) {
623
+ const { repoRoot, prefer } = input;
624
+ const prior = await readBaseline(repoRoot);
625
+ const plan = new Plan();
626
+ const workspaceDir = join(repoRoot, WORKSPACE_DIR);
627
+ const taken = /* @__PURE__ */ new Set();
628
+ const folders = /* @__PURE__ */ new Map();
629
+ for (const c of input.collections) {
630
+ const known = priorPair(prior?.baseline, "collection", c.source);
631
+ if (known) {
632
+ folders.set(c.source, known.workspace);
633
+ taken.add(known.workspace);
634
+ }
635
+ }
636
+ const listed = [];
637
+ for (const c of input.collections) {
638
+ const environmentsPresent = c.environments.filter((env) => env.json !== void 0);
639
+ const generated = c.json === void 0 ? void 0 : await collectionFiles(c.json, environmentsPresent.map((env) => env.json)).catch((err) => {
640
+ throw new Error(`${c.source}: ${err.message}`, { cause: err });
641
+ });
642
+ const known = priorPair(prior?.baseline, "collection", c.source);
643
+ if (c.json === void 0 && !known) throw new Error(`${c.source}: not found`);
644
+ let folderPath = folders.get(c.source);
645
+ if (folderPath === void 0) {
646
+ const base = collectionFolder(generated?.name ?? "collection");
647
+ let slug = `collections/${base}`;
648
+ for (let n = 2; taken.has(slug); n += 1) slug = `collections/${base}-${n}`;
649
+ taken.add(slug);
650
+ folderPath = slug;
651
+ }
652
+ const folder = folderPath;
653
+ const current = await ymlFilesBelow(join(workspaceDir, folder));
654
+ const currentRequests = requestFiles(current);
655
+ const generatedRequests = generated ? requestFiles(generated.files) : /* @__PURE__ */ new Map();
656
+ const sourceCanon = generated ? canonicalJson(workspaceToSource(generatedRequests)) : "";
657
+ const sourceHash = generated ? hashOf(sourceCanon) : "";
658
+ const workspaceHash = folderHash(currentRequests);
659
+ let derived;
660
+ const derive = () => derived ??= workspaceToSource(currentRequests);
661
+ const direction = decide({
662
+ sourcePresent: c.json !== void 0,
663
+ workspacePresent: currentRequests.size > 0,
664
+ prior: known,
665
+ sourceHash,
666
+ workspaceHash,
667
+ agree: () => sameFiles(generatedRequests, currentRequests) || canonicalJson(derive()) === sourceCanon,
668
+ prefer
669
+ });
670
+ let name = generated?.name ?? "";
671
+ let finalWorkspace = currentRequests;
672
+ let finalSourceHash = sourceHash;
673
+ if (direction === "toWorkspace") {
674
+ for (const [path, text] of generatedRequests) {
675
+ const now = currentRequests.get(path);
676
+ plan.files.push({
677
+ path: `${WORKSPACE_DIR}/${folder}/${path}`,
678
+ state: now === void 0 ? "new" : now === text ? "unchanged" : "changed"
679
+ });
680
+ if (now !== text) plan.write(`${WORKSPACE_DIR}/${folder}/${path}`, text);
681
+ }
682
+ for (const path of currentRequests.keys()) {
683
+ if (generatedRequests.has(path)) continue;
684
+ plan.files.push({
685
+ path: `${WORKSPACE_DIR}/${folder}/${path}`,
686
+ state: "removed"
687
+ });
688
+ plan.deletes.push(`${WORKSPACE_DIR}/${folder}/${path}`);
689
+ }
690
+ finalWorkspace = generatedRequests;
691
+ for (const issue of generated?.issues ?? []) plan.issues.push({
692
+ file: c.source,
693
+ message: issue
694
+ });
695
+ } else {
696
+ for (const path of currentRequests.keys()) plan.files.push({
697
+ path: `${WORKSPACE_DIR}/${folder}/${path}`,
698
+ state: "unchanged"
699
+ });
700
+ if (direction === "conflict") {
701
+ plan.conflicts += 1;
702
+ plan.files.push({
703
+ path: c.source,
704
+ state: "conflict",
705
+ note: conflictNote("The collection")
706
+ });
707
+ } else if (direction === "toSource") {
708
+ const fromWorkspace = derive();
709
+ name = String(fromWorkspace.info?.name ?? name);
710
+ if (c.json === void 0 || canonicalJson(fromWorkspace) !== sourceCanon) {
711
+ const text = formatJson(isObject(c.json) ? keepOriginal(fromWorkspace, workspaceToSource(generatedRequests), c.json) : fromWorkspace);
712
+ plan.files.push({
713
+ path: c.source,
714
+ state: c.json === void 0 ? "new" : "changed"
715
+ });
716
+ plan.write(c.source, text);
717
+ const written = JSON.parse(text);
718
+ finalSourceHash = hashOf((await carriedCollection(written)).canon);
719
+ const regenerated = requestFiles((await collectionFiles(written, [])).files);
720
+ for (const [path, text] of currentRequests) if (regenerated.get(path) !== text) plan.issues.push({
721
+ file: c.source,
722
+ message: `${WORKSPACE_DIR}/${folder}/${path} holds settings the request file cannot carry; they stay in the workspace`
723
+ });
724
+ }
725
+ }
726
+ }
727
+ listed.push({
728
+ name,
729
+ path: folder
730
+ });
731
+ if (direction === "conflict") {
732
+ if (known) plan.pairs.push(known);
733
+ } else plan.pairs.push({
734
+ kind: "collection",
735
+ source: c.source,
736
+ workspace: folder,
737
+ sourceHash: finalSourceHash,
738
+ workspaceHash: folderHash(finalWorkspace)
739
+ });
740
+ const envFiles = generated ?? await collectionFiles(EMPTY_COLLECTION, environmentsPresent.map((env) => env.json));
741
+ const mapped = /* @__PURE__ */ new Set();
742
+ let index = 0;
743
+ for (const env of c.environments) {
744
+ const knownEnv = prior?.baseline.pairs.find((p) => p.kind === "environment" && p.source === env.source && p.workspace.startsWith(`${folder}/environments/`));
745
+ const file = (env.json === void 0 ? void 0 : envFiles.environmentFiles[index++]) ?? knownEnv?.workspace.slice(folder.length + 1);
746
+ if (file === void 0) throw new Error(`${env.source}: not found`);
747
+ mapped.add(file);
748
+ const workspacePath = `${folder}/${file}`;
749
+ const now = current.get(file);
750
+ const carried = env.json === void 0 ? void 0 : await carriedEnvironment(env.json);
751
+ const envSourceHash = carried ? hashOf(carried.canon) : "";
752
+ const envDirection = decide({
753
+ sourcePresent: carried !== void 0,
754
+ workspacePresent: now !== void 0,
755
+ prior: knownEnv,
756
+ sourceHash: envSourceHash,
757
+ workspaceHash: now === void 0 ? "" : hashOf(now),
758
+ agree: () => carried !== void 0 && now !== void 0 && (carried.text === now || canonicalJson(environmentToSource(now, workspacePath)) === carried.canon),
759
+ prefer
760
+ });
761
+ const path = `${WORKSPACE_DIR}/${workspacePath}`;
762
+ let finalText = now;
763
+ let finalEnvHash = envSourceHash;
764
+ if (envDirection === "toWorkspace") {
765
+ const text = carried.text;
766
+ plan.files.push({
767
+ path,
768
+ state: now === void 0 ? "new" : now === text ? "unchanged" : "changed"
769
+ });
770
+ if (now !== text) plan.write(path, text);
771
+ finalText = text;
772
+ } else if (envDirection === "conflict") {
773
+ plan.conflicts += 1;
774
+ plan.files.push({
775
+ path: env.source,
776
+ state: "conflict",
777
+ note: conflictNote("The environment")
778
+ });
779
+ } else {
780
+ plan.files.push({
781
+ path,
782
+ state: "unchanged"
783
+ });
784
+ if (envDirection === "toSource") {
785
+ const fromWorkspace = environmentToSource(now, workspacePath);
786
+ if (carried === void 0 || canonicalJson(fromWorkspace) !== carried.canon) {
787
+ const text = formatJson({
788
+ ...isObject(env.json) ? env.json : {},
789
+ ...fromWorkspace
790
+ });
791
+ plan.files.push({
792
+ path: env.source,
793
+ state: env.json === void 0 ? "new" : "changed"
794
+ });
795
+ plan.write(env.source, text);
796
+ const rewritten = await carriedEnvironment(JSON.parse(text));
797
+ finalEnvHash = hashOf(rewritten.canon);
798
+ if (rewritten.text !== now) plan.issues.push({
799
+ file: env.source,
800
+ message: `${path} holds settings the environment file cannot carry; they stay in the workspace`
801
+ });
802
+ }
803
+ }
804
+ }
805
+ if (envDirection === "conflict") {
806
+ if (knownEnv) plan.pairs.push(knownEnv);
807
+ } else plan.pairs.push({
808
+ kind: "environment",
809
+ source: env.source,
810
+ workspace: workspacePath,
811
+ sourceHash: finalEnvHash,
812
+ workspaceHash: hashOf(finalText)
813
+ });
814
+ }
815
+ for (const file of current.keys()) if (file.startsWith("environments/") && !mapped.has(file)) plan.issues.push({
816
+ file: c.source,
817
+ message: `${WORKSPACE_DIR}/${folder}/${file} is only in the workspace: no environment file of the request files names it, so it is not synced`
818
+ });
819
+ }
820
+ const workspacePath = `${WORKSPACE_DIR}/workspace.yml`;
821
+ const workspaceNow = await readIfThere(join(repoRoot, workspacePath));
822
+ if (workspaceNow !== void 0 && listed.every((c) => workspaceNow.includes(JSON.stringify(c.path)))) plan.files.push({
823
+ path: workspacePath,
824
+ state: "unchanged"
825
+ });
826
+ else {
827
+ plan.files.push({
828
+ path: workspacePath,
829
+ state: workspaceNow === void 0 ? "new" : "changed"
830
+ });
831
+ plan.write(workspacePath, workspaceYml(input.workspaceName, listed));
832
+ }
833
+ const baselineText = serializeBaseline(plan.pairs);
834
+ const baselineNow = prior?.text;
835
+ plan.files.push({
836
+ path: BASELINE_FILE,
837
+ state: baselineNow === void 0 ? "new" : baselineNow === baselineText ? "unchanged" : "changed"
64
838
  });
839
+ if (baselineNow !== baselineText) plan.write(BASELINE_FILE, baselineText);
840
+ plan.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.state < b.state ? -1 : 1);
841
+ if (!input.dryRun && plan.conflicts === 0) {
842
+ for (const [path, text] of plan.writes) {
843
+ const absolute = join(repoRoot, path);
844
+ await mkdir(dirname(absolute), { recursive: true });
845
+ await writeFile(absolute, text);
846
+ }
847
+ for (const path of plan.deletes) {
848
+ const absolute = join(repoRoot, path);
849
+ await unlink(absolute);
850
+ await pruneEmpty(dirname(absolute), workspaceDir);
851
+ }
852
+ }
853
+ return {
854
+ files: plan.files,
855
+ issues: plan.issues
856
+ };
857
+ }
858
+ /** The baseline's pair of a kind for a request file, if the baseline has one. */
859
+ function priorPair(baseline, kind, source) {
860
+ return baseline?.pairs.find((pair) => pair.kind === kind && pair.source === source);
65
861
  }
66
862
  // src/capabilities/tooling.ts
67
863
  /**
68
864
  * `tooling` capability for Bruno.
69
865
  *
70
866
  * Bruno has no HTTP API and no account to push to: it reads a folder of files. So this provider works on files only,
71
- * with no token and no network, and its one real job is `export()`: it writes each of the repo's collection files as
72
- * an OpenCollection YAML document and a Bruno JSON file, each with the environments inside it, for
73
- * `holocron export requests`.
867
+ * with no token and no network. `export()` writes each of the repo's collection files as a Bruno JSON file with the
868
+ * environments inside it, for `holocron export requests`.
869
+ * `workspace()` keeps the committed `.bruno/` workspace (Bruno's own files, one folder per collection) equal to the
870
+ * repo's request files, for `holocron sync requests`.
74
871
  *
75
872
  * `sync()` has nothing to reconcile, so it does nothing and succeeds: `holocron setup` calls it on every `tooling`
76
- * provider, and the files are written by `export()`, which is the person's call, never a side effect of `setup`.
873
+ * provider, and the files are written by `export()` and `workspace()`, which are the person's call, never a side
874
+ * effect of `setup`.
77
875
  * `doctor()` checks the input files exist and parse as JSON.
78
876
  */
79
877
  /** The text of what a read, a parse or a converter threw: always an `Error`. */
@@ -86,6 +884,15 @@ async function readJson(root, file) {
86
884
  throw new Error(`${file}: ${message(err)}`, { cause: err });
87
885
  }
88
886
  }
887
+ /** Like {@link readJson}, but a file that is not there is `undefined`: the workspace may make it. */
888
+ async function readJsonIfThere(root, file) {
889
+ try {
890
+ await access(resolve(root, file));
891
+ } catch {
892
+ return;
893
+ }
894
+ return readJson(root, file);
895
+ }
89
896
  /** The Bruno implementation of the `tooling` capability: files only. */
90
897
  var BrunoTooling = class {
91
898
  options;
@@ -124,8 +931,7 @@ var BrunoTooling = class {
124
931
  async export(input) {
125
932
  const { collectionFiles, envFiles, outDir, repoRoot } = input;
126
933
  const environments = await Promise.all(envFiles.map((file) => readJson(repoRoot, file)));
127
- const names = outputNames(collectionFiles);
128
- const jsonNames = outputNames(collectionFiles, ".bruno.json");
934
+ const names = outputNames(collectionFiles, ".bruno.json");
129
935
  const files = [];
130
936
  const issues = [];
131
937
  for (const [index, file] of collectionFiles.entries()) {
@@ -137,19 +943,39 @@ var BrunoTooling = class {
137
943
  message: issue
138
944
  });
139
945
  const name = names[index];
140
- const jsonName = jsonNames[index];
141
946
  if (!input.dryRun) {
142
947
  await mkdir(outDir, { recursive: true });
143
- await writeFile(join(outDir, name), converted.text);
144
- await writeFile(join(outDir, jsonName), converted.json);
948
+ await writeFile(join(outDir, name), converted.json);
145
949
  }
146
- files.push(name, jsonName);
950
+ files.push(name);
147
951
  }
148
952
  return {
149
953
  files,
150
954
  issues
151
955
  };
152
956
  }
957
+ async workspace(input) {
958
+ const { collectionFiles, envFiles, repoRoot } = input;
959
+ const collections = [];
960
+ for (const file of collectionFiles) {
961
+ const beside = envFiles.filter((env) => dirname(env) === dirname(file));
962
+ collections.push({
963
+ source: file,
964
+ json: await readJsonIfThere(repoRoot, file),
965
+ environments: await Promise.all((beside.length > 0 ? beside : envFiles).map(async (env) => ({
966
+ source: env,
967
+ json: await readJsonIfThere(repoRoot, env)
968
+ })))
969
+ });
970
+ }
971
+ return syncWorkspace({
972
+ workspaceName: this.options.workspaceName ?? "Workspace",
973
+ collections,
974
+ repoRoot,
975
+ ...input.dryRun ? { dryRun: true } : {},
976
+ ...input.prefer ? { prefer: input.prefer } : {}
977
+ });
978
+ }
153
979
  };
154
980
  // src/index.ts
155
981
  /** Builds the `tooling` capability from the plugin options. */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-bruno",
3
- "version": "5.0.0-alpha.454",
4
- "description": "Holocron plugin for Bruno. Implements the tooling capability over files: it exports the repo's request collections as OpenCollection YAML.",
3
+ "version": "5.0.0-alpha.456",
4
+ "description": "Holocron plugin for Bruno. Implements the tooling capability over files: it exports the repo's request collections as Bruno JSON files.",
5
5
  "keywords": [
6
6
  "bruno",
7
7
  "holocron",
@@ -30,9 +30,8 @@
30
30
  "dist"
31
31
  ],
32
32
  "dependencies": {
33
- "@opencollection/converters": "^0.0.2",
34
33
  "@usebruno/converters": "^0.25.0",
35
- "js-yaml": "^5.5.0"
34
+ "@usebruno/filestore": "^0.14.0"
36
35
  },
37
36
  "devDependencies": {
38
37
  "@types/node": "^26",
@@ -45,14 +44,14 @@
45
44
  "tsx": "4.23.15",
46
45
  "typescript": "^5.9.3",
47
46
  "vitest": "^5.1.0",
48
- "@theholocron/cli": "5.0.0-alpha.454",
49
47
  "@theholocron/eslint-config": "^8.9.0-alpha.18",
50
- "@theholocron/vitest-config": "^8.9.0-alpha.18",
51
48
  "@theholocron/tsdown-config": "^8.9.0-alpha.18",
49
+ "@theholocron/vitest-config": "^8.9.0-alpha.18",
50
+ "@theholocron/cli": "5.0.0-alpha.456",
52
51
  "@theholocron/tsconfig": "^8.9.0-alpha.18"
53
52
  },
54
53
  "peerDependencies": {
55
- "@theholocron/cli": "5.0.0-alpha.454"
54
+ "@theholocron/cli": "5.0.0-alpha.456"
56
55
  },
57
56
  "engines": {
58
57
  "node": ">=22"