bearminion 1.13.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # bearminion
2
2
 
3
+ ## 1.14.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5ae0f26: `githubStore` gets `mode: 'pr'`: each edited page gets a branch and a pull request of its own, later saves join it, and nothing is ever merged. Stores can now expose `scoped(scope)` for this, and the editor API uses it per page, site, upload and batch save.
8
+
3
9
  ## 1.13.0
4
10
 
5
11
  ### Minor Changes
package/dist/astro.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { A as ContentModel, X as SiteOf, Xt as ContentMigrator, Y as SiteDefinition, d as SectionOf, j as SectionRegistry, t as Page } from "./page-CwbIDegI.js";
2
- import { a as StoreOperation, i as FileStoreOptions, n as EditorContext, o as UploadStore, r as ContentStore, s as createFileStore, t as BearminionOptions } from "./options-DP6mTauQ.js";
2
+ import { a as StoreOperation, i as FileStoreOptions, n as EditorContext, o as UploadStore, r as ContentStore, s as createFileStore, t as BearminionOptions } from "./options-CosfIOMs.js";
3
3
  import { AstroIntegration } from "astro";
4
4
  //#region src/store-error.d.ts
5
5
  /** A key that is empty, absolute or leaves the content directory. */
@@ -50,6 +50,23 @@ interface GithubStoreOptions {
50
50
  written: readonly string[];
51
51
  removed: readonly string[];
52
52
  }) => string;
53
+ /**
54
+ * `direct` (default): a save is a commit on `branch`. `pr`: a save is a commit on a branch of its own for the entry
55
+ * being edited, with a pull request opened on the first save. Nothing here ever merges. Needs "Pull requests: Read
56
+ * and write" besides "Contents: Read and write".
57
+ */
58
+ mode?: 'direct' | 'pr';
59
+ /** `pr` mode: the title and body of the pull request opened for an entry. */
60
+ pullRequest?: (change: {
61
+ scope: string;
62
+ written: readonly string[];
63
+ removed: readonly string[];
64
+ }) => {
65
+ title: string;
66
+ body: string;
67
+ };
68
+ /** `pr` mode: the label put on the pull requests. Default `bearminion`; `false` for none. */
69
+ label?: string | false;
53
70
  /** The GitHub API. Default `https://api.github.com`. Set it for GitHub Enterprise. */
54
71
  apiUrl?: string;
55
72
  /** Default: the global `fetch`. */
package/dist/astro.js CHANGED
@@ -768,12 +768,12 @@ async function route(request, context, meta) {
768
768
  return methodNotAllowed(["GET"]);
769
769
  }
770
770
  if (parts.length === 1 && parts[0] === "site") {
771
- if (method === "GET") return getSite(context);
772
- if (method === "PUT") return putSite(request, context);
771
+ if (method === "GET") return getSite(scoped(context, "site"));
772
+ if (method === "PUT") return putSite(request, scoped(context, "site"));
773
773
  return methodNotAllowed(["GET", "PUT"]);
774
774
  }
775
775
  if (parts.length === 1 && parts[0] === "save") {
776
- if (method === "POST") return postSave(request, context);
776
+ if (method === "POST") return postSave(request, scoped(context, "edits"));
777
777
  return methodNotAllowed(["POST"]);
778
778
  }
779
779
  if (parts.length === 1 && parts[0] === "pages") {
@@ -794,12 +794,12 @@ async function route(request, context, meta) {
794
794
  return methodNotAllowed(["POST"]);
795
795
  }
796
796
  if (parts.length === 1 && parts[0] === "images") {
797
- if (method === "GET") return getImages(context);
798
- if (method === "POST") return postImage(request, context);
797
+ if (method === "GET") return getImages(scoped(context, "uploads"));
798
+ if (method === "POST") return postImage(request, scoped(context, "uploads"));
799
799
  return methodNotAllowed(["GET", "POST"]);
800
800
  }
801
801
  if (parts.length === 2 && parts[0] === "images") {
802
- if (method === "DELETE") return removeImage(context, decodeSegment(parts[1] ?? ""));
802
+ if (method === "DELETE") return removeImage(scoped(context, "uploads"), decodeSegment(parts[1] ?? ""));
803
803
  return methodNotAllowed(["DELETE"]);
804
804
  }
805
805
  if (parts.length === 1 && parts[0] === "videos") {
@@ -831,9 +831,10 @@ async function route(request, context, meta) {
831
831
  if (parts.length === 2 && parts[0] === "pages") {
832
832
  const slug = readSlug(parts[1] ?? "");
833
833
  if (slug === null) return badSlug();
834
- if (method === "GET") return getPage(context, slug);
835
- if (method === "PUT") return putPage(request, context, slug);
836
- if (method === "DELETE") return deletePage(context, slug);
834
+ const entry = scoped(context, `page:${slug}`);
835
+ if (method === "GET") return getPage(entry, slug);
836
+ if (method === "PUT") return putPage(request, entry, slug);
837
+ if (method === "DELETE") return deletePage(entry, slug);
837
838
  return methodNotAllowed([
838
839
  "GET",
839
840
  "PUT",
@@ -843,13 +844,13 @@ async function route(request, context, meta) {
843
844
  if (parts.length === 3 && parts[0] === "pages" && parts[2] === "rename") {
844
845
  const slug = readSlug(parts[1] ?? "");
845
846
  if (slug === null) return badSlug();
846
- if (method === "POST") return renamePage(request, context, slug);
847
+ if (method === "POST") return renamePage(request, scoped(context, `page:${slug}`), slug);
847
848
  return methodNotAllowed(["POST"]);
848
849
  }
849
850
  if (parts.length === 3 && parts[0] === "pages" && parts[2] === "set-home") {
850
851
  const slug = readSlug(parts[1] ?? "");
851
852
  if (slug === null) return badSlug();
852
- if (method === "POST") return setHome(request, context, slug);
853
+ if (method === "POST") return setHome(request, scoped(context, `page:${slug}`), slug);
853
854
  return methodNotAllowed(["POST"]);
854
855
  }
855
856
  return problem(404, "not_found", "Unknown editor API route.");
@@ -875,6 +876,17 @@ function relativeTo(root, file) {
875
876
  const prefix = root.endsWith("/") || root.endsWith("\\") ? root : `${root}/`;
876
877
  return file.startsWith(prefix) ? file.slice(prefix.length).replaceAll("\\", "/") : file;
877
878
  }
879
+ /**
880
+ * The context for editing one entry. A store that keeps each entry's pending edits apart (`githubStore` in `pr` mode)
881
+ * hands out a view of its own; every other store is used as it is.
882
+ */
883
+ function scoped(context, scope) {
884
+ const store = context.store.scoped?.(scope);
885
+ return store ? {
886
+ ...context,
887
+ store
888
+ } : context;
889
+ }
878
890
  async function getSchema(context) {
879
891
  const sectionDefaults = {};
880
892
  const sectionLabels = {};
@@ -1184,11 +1196,12 @@ async function putPage(request, context, slug) {
1184
1196
  return json(200, page);
1185
1197
  }
1186
1198
  const orphanKey = (section) => `${section.id}:${section.type}`;
1187
- async function createPage(request, context) {
1199
+ async function createPage(request, baseContext) {
1188
1200
  const body = await readJsonBody(request);
1189
1201
  if (body.response) return body.response;
1190
1202
  const parsed = createPageSchema.safeParse(body.value);
1191
1203
  if (!parsed.success) return validation(fieldIssues(parsed.error));
1204
+ const context = scoped(baseContext, `page:${parsed.data.slug}`);
1192
1205
  if (isSystemPage(parsed.data.slug)) return problem(409, "reserved_slug", `"${parsed.data.slug}" is a system page and cannot be created.`);
1193
1206
  const loaded = await loadStoredPages(context, { allowMissing: true });
1194
1207
  if (loaded.response) return loaded.response;
@@ -2090,6 +2103,11 @@ function defaultMessage({ written, removed }) {
2090
2103
  if (written.length + removed.length === 1) return written.length === 1 ? `Update ${written[0]}` : `Remove ${removed[0]}`;
2091
2104
  return `Update ${written.length + removed.length} files`;
2092
2105
  }
2106
+ function branchStem(scope) {
2107
+ const part = scope.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
2108
+ return `bearminion/${part === "" ? "edit" : part}`;
2109
+ }
2110
+ const MAX_BRANCHES_PER_SCOPE = 20;
2093
2111
  function githubStore(options) {
2094
2112
  const match = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(options.repo);
2095
2113
  if (!match) throw new Error(`githubStore(): repo must be "owner/name", got "${options.repo}".`);
@@ -2101,6 +2119,8 @@ function githubStore(options) {
2101
2119
  const contentDir = folder(options.contentDir ?? "content", "contentDir");
2102
2120
  const uploadsDir = folder(options.uploadsDir ?? "src/assets/uploads", "uploadsDir");
2103
2121
  const message = options.message ?? defaultMessage;
2122
+ const prMode = options.mode === "pr";
2123
+ if (options.mode !== void 0 && options.mode !== "direct" && options.mode !== "pr") throw new Error(`githubStore(): mode must be "direct" or "pr", got "${String(options.mode)}".`);
2104
2124
  const inRepo = (...parts) => [rootDir, ...parts].filter((part) => part !== "").join("/");
2105
2125
  /** The repository path of a store key, checked the way the file store checks it. */
2106
2126
  function contentPath(key) {
@@ -2149,7 +2169,8 @@ function githubStore(options) {
2149
2169
  return JSON.parse(settled.text);
2150
2170
  }
2151
2171
  let branchName;
2152
- function branch() {
2172
+ /** The branch edits are based on: the configured one, or the repository's default. */
2173
+ function baseBranch() {
2153
2174
  if (options.branch) return Promise.resolve(options.branch);
2154
2175
  branchName ??= json(send("GET", `/repos/${repo}`), "read the repository").then((info) => info.default_branch, (error) => {
2155
2176
  branchName = void 0;
@@ -2179,143 +2200,279 @@ function githubStore(options) {
2179
2200
  return reply;
2180
2201
  }
2181
2202
  const contentsRoute = (path, ref) => `/repos/${repo}/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`;
2182
- async function readFile(path, ref) {
2183
- const reply = await cached(contentsRoute(path, ref ?? await branch()), RAW);
2203
+ async function readFileAt(path, ref) {
2204
+ const reply = await cached(contentsRoute(path, ref), RAW);
2184
2205
  if (reply.status === 404) return void 0;
2185
2206
  if (reply.status !== 200) throw failure(reply, `read ${path}`);
2186
2207
  return reply.text;
2187
2208
  }
2188
2209
  /** The names of the files directly inside `path`, or `undefined` when there is no such folder. */
2189
- async function listFiles(path) {
2190
- const reply = await cached(contentsRoute(path, await branch()), JSON_TYPE);
2210
+ async function listFilesAt(path, ref) {
2211
+ const reply = await cached(contentsRoute(path, ref), JSON_TYPE);
2191
2212
  if (reply.status === 404) return void 0;
2192
2213
  if (reply.status !== 200) throw failure(reply, `list ${path}`);
2193
2214
  const entries = JSON.parse(reply.text);
2194
2215
  if (!Array.isArray(entries)) return void 0;
2195
2216
  return entries.filter((entry) => typeof entry === "object" && entry !== null && "name" in entry).filter((entry) => entry.type === "file").map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
2196
2217
  }
2197
- /** One commit on the branch holding all of `changes`. Goes through the Git Data API so the files land together. */
2198
- async function commit(changes, describe) {
2199
- const name = await branch();
2200
- const refRoute = `/repos/${repo}/git/refs/heads/${encodePath(name)}`;
2201
- for (let attempt = 0; attempt < 2; attempt += 1) {
2202
- const head = await json(send("GET", `/repos/${repo}/git/ref/heads/${encodePath(name)}`), "read the branch");
2203
- const parent = await json(send("GET", `/repos/${repo}/git/commits/${head.object.sha}`), "read the latest commit");
2204
- const entries = [];
2205
- const applied = [];
2206
- for (const change of changes) if ("remove" in change) {
2207
- if (await readFile(change.path, head.object.sha) === void 0) continue;
2208
- entries.push({
2209
- path: change.path,
2210
- mode: "100644",
2211
- type: "blob",
2212
- sha: null
2213
- });
2214
- applied.push(change);
2215
- } else if ("text" in change) {
2216
- entries.push({
2217
- path: change.path,
2218
- mode: "100644",
2219
- type: "blob",
2220
- content: change.text
2221
- });
2222
- applied.push(change);
2223
- } else {
2224
- const blob = await json(send("POST", `/repos/${repo}/git/blobs`, { body: {
2225
- content: toBase64(change.bytes),
2226
- encoding: "base64"
2227
- } }), `upload ${change.path}`);
2228
- entries.push({
2229
- path: change.path,
2230
- mode: "100644",
2231
- type: "blob",
2232
- sha: blob.sha
2233
- });
2234
- applied.push(change);
2235
- }
2236
- if (entries.length === 0) return;
2237
- const tree = await json(send("POST", `/repos/${repo}/git/trees`, { body: {
2238
- base_tree: parent.tree.sha,
2239
- tree: entries
2240
- } }), "write the files");
2241
- const update = await send("PATCH", refRoute, { body: {
2242
- sha: (await json(send("POST", `/repos/${repo}/git/commits`, { body: {
2218
+ async function branchHead(name) {
2219
+ const reply = await send("GET", `/repos/${repo}/git/ref/heads/${encodePath(name)}`);
2220
+ if (reply.status === 404) return void 0;
2221
+ if (reply.status !== 200) throw failure(reply, `read the branch "${name}"`);
2222
+ return JSON.parse(reply.text).object.sha;
2223
+ }
2224
+ /** The state of the pull requests whose head is `name`: any open one wins, then closed or merged ones. */
2225
+ async function pullState(name) {
2226
+ const head = encodeURIComponent(`${match?.[1] ?? ""}:${name}`);
2227
+ const pulls = await json(send("GET", `/repos/${repo}/pulls?head=${head}&state=all&per_page=100`), "look up pull requests");
2228
+ if (pulls.some((pull) => pull.state === "open")) return "open";
2229
+ return pulls.length > 0 ? "closed" : "none";
2230
+ }
2231
+ /** One commit on the target's branch holding all of `changes`. Goes through the Git Data API so the files land together. */
2232
+ function view(target) {
2233
+ async function readFile(path) {
2234
+ return readFileAt(path, await target.readRef());
2235
+ }
2236
+ async function listFile(path) {
2237
+ return listFilesAt(path, await target.readRef());
2238
+ }
2239
+ async function listAcross(path) {
2240
+ const names = /* @__PURE__ */ new Set();
2241
+ for (const ref of await target.refs()) for (const name of await listFilesAt(path, ref) ?? []) names.add(name);
2242
+ return [...names].sort((a, b) => a.localeCompare(b));
2243
+ }
2244
+ async function commit(changes, describe) {
2245
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2246
+ const name = await target.writeBranch();
2247
+ const headSha = await branchHead(name);
2248
+ if (headSha === void 0) throw failure({
2249
+ status: 404,
2250
+ headers: new Headers(),
2251
+ text: ""
2252
+ }, `read the branch "${name}"`);
2253
+ const parent = await json(send("GET", `/repos/${repo}/git/commits/${headSha}`), "read the latest commit");
2254
+ const entries = [];
2255
+ const applied = [];
2256
+ for (const change of changes) if ("remove" in change) {
2257
+ if (await readFileAt(change.path, headSha) === void 0) continue;
2258
+ entries.push({
2259
+ path: change.path,
2260
+ mode: "100644",
2261
+ type: "blob",
2262
+ sha: null
2263
+ });
2264
+ applied.push(change);
2265
+ } else if ("text" in change) {
2266
+ entries.push({
2267
+ path: change.path,
2268
+ mode: "100644",
2269
+ type: "blob",
2270
+ content: change.text
2271
+ });
2272
+ applied.push(change);
2273
+ } else {
2274
+ const blob = await json(send("POST", `/repos/${repo}/git/blobs`, { body: {
2275
+ content: toBase64(change.bytes),
2276
+ encoding: "base64"
2277
+ } }), `upload ${change.path}`);
2278
+ entries.push({
2279
+ path: change.path,
2280
+ mode: "100644",
2281
+ type: "blob",
2282
+ sha: blob.sha
2283
+ });
2284
+ applied.push(change);
2285
+ }
2286
+ if (entries.length === 0) return;
2287
+ const tree = await json(send("POST", `/repos/${repo}/git/trees`, { body: {
2288
+ base_tree: parent.tree.sha,
2289
+ tree: entries
2290
+ } }), "write the files");
2291
+ const created = await json(send("POST", `/repos/${repo}/git/commits`, { body: {
2243
2292
  message: describe(applied),
2244
2293
  tree: tree.sha,
2245
- parents: [head.object.sha]
2246
- } }), "create the commit")).sha,
2247
- force: false
2248
- } });
2249
- if (update.status === 200) return;
2250
- if ((update.status === 403 || update.status === 422) && PROTECTED.test(messageOf(update.text))) throw new StoreError(409, "branch_protected", `The branch "${name}" is protected, so edits cannot be committed to it directly. Allow this token to push to it, or use another branch.`);
2251
- if (update.status === 422 && attempt === 0) continue;
2252
- if (update.status === 422) throw new StoreError(409, "branch_moved", "The branch changed while saving. Reload the editor and try again.");
2253
- throw failure(update, `update the branch "${name}"`);
2294
+ parents: [headSha]
2295
+ } }), "create the commit");
2296
+ const update = await send("PATCH", `/repos/${repo}/git/refs/heads/${encodePath(name)}`, { body: {
2297
+ sha: created.sha,
2298
+ force: false
2299
+ } });
2300
+ if (update.status === 200) {
2301
+ await target.committed?.(name, {
2302
+ written: applied.filter((change) => !("remove" in change)).map((change) => change.path),
2303
+ removed: applied.filter((change) => "remove" in change).map((change) => change.path)
2304
+ });
2305
+ return;
2306
+ }
2307
+ if ((update.status === 403 || update.status === 422) && PROTECTED.test(messageOf(update.text))) throw new StoreError(409, "branch_protected", `The branch "${name}" is protected, so edits cannot be committed to it directly. Allow this token to push to it, use another branch, or set mode: 'pr'.`);
2308
+ if (update.status === 422 && attempt === 0) continue;
2309
+ if (update.status === 422) throw new StoreError(409, "branch_moved", "The branch changed while saving. Reload the editor and try again.");
2310
+ throw failure(update, `update the branch "${name}"`);
2311
+ }
2254
2312
  }
2255
- }
2256
- return {
2257
- async read(key) {
2258
- return readFile(contentPath(key));
2259
- },
2260
- async exists(key) {
2261
- return await readFile(contentPath(key)) !== void 0;
2262
- },
2263
- async list(dir) {
2264
- return listFiles(contentPath(dir));
2265
- },
2266
- async apply(operations) {
2267
- const changes = operations.map((operation) => operation.type === "write" ? {
2268
- path: contentPath(operation.key),
2269
- text: operation.text
2270
- } : {
2271
- path: contentPath(operation.key),
2272
- remove: true
2273
- });
2274
- if (changes.length === 0) return;
2275
- await commit(changes, (applied) => message({
2276
- written: applied.filter((change) => !("remove" in change)).map((change) => change.path),
2277
- removed: applied.filter((change) => "remove" in change).map((change) => change.path)
2278
- }));
2279
- },
2280
- uploads: {
2281
- async list() {
2282
- return (await listFiles(inRepo(uploadsDir)) ?? []).filter((name) => !name.startsWith(".") && hasImageExtension(name)).map((filename) => ({
2283
- filename,
2284
- path: `${uploadsDir}/${filename}`
2313
+ return {
2314
+ async read(key) {
2315
+ return readFile(contentPath(key));
2316
+ },
2317
+ async exists(key) {
2318
+ return await readFile(contentPath(key)) !== void 0;
2319
+ },
2320
+ async list(dir) {
2321
+ return listFile(contentPath(dir));
2322
+ },
2323
+ async apply(operations) {
2324
+ const changes = operations.map((operation) => operation.type === "write" ? {
2325
+ path: contentPath(operation.key),
2326
+ text: operation.text
2327
+ } : {
2328
+ path: contentPath(operation.key),
2329
+ remove: true
2330
+ });
2331
+ if (changes.length === 0) return;
2332
+ await commit(changes, (applied) => message({
2333
+ written: applied.filter((change) => !("remove" in change)).map((change) => change.path),
2334
+ removed: applied.filter((change) => "remove" in change).map((change) => change.path)
2285
2335
  }));
2286
2336
  },
2287
- async save({ originalName, bytes, kind }) {
2288
- const taken = new Set(await listFiles(inRepo(uploadsDir)) ?? []);
2289
- for (let attempt = 0; attempt < 8; attempt += 1) {
2290
- const filename = uploadFilename(originalName, kind);
2291
- if (taken.has(filename)) continue;
2337
+ uploads: {
2338
+ async list() {
2339
+ return (await listAcross(inRepo(uploadsDir))).filter((name) => !name.startsWith(".") && hasImageExtension(name)).map((filename) => ({
2340
+ filename,
2341
+ path: `${uploadsDir}/${filename}`
2342
+ }));
2343
+ },
2344
+ async save({ originalName, bytes, kind }) {
2345
+ const taken = new Set(await listAcross(inRepo(uploadsDir)));
2346
+ for (let attempt = 0; attempt < 8; attempt += 1) {
2347
+ const filename = uploadFilename(originalName, kind);
2348
+ if (taken.has(filename)) continue;
2349
+ await commit([{
2350
+ path: inRepo(uploadsDir, filename),
2351
+ bytes
2352
+ }], () => `Upload ${filename}`);
2353
+ return {
2354
+ filename,
2355
+ path: `${uploadsDir}/${filename}`,
2356
+ bytes: bytes.byteLength
2357
+ };
2358
+ }
2359
+ throw new Error("Unable to allocate a unique upload filename.");
2360
+ },
2361
+ async remove(filename) {
2362
+ if (!isUploadFilename(filename)) return false;
2363
+ if (!(await listAcross(inRepo(uploadsDir))).includes(filename)) return false;
2292
2364
  await commit([{
2293
2365
  path: inRepo(uploadsDir, filename),
2294
- bytes
2295
- }], () => `Upload ${filename}`);
2296
- return {
2297
- filename,
2298
- path: `${uploadsDir}/${filename}`,
2299
- bytes: bytes.byteLength
2300
- };
2366
+ remove: true
2367
+ }], () => `Remove ${filename}`);
2368
+ return true;
2301
2369
  }
2302
- throw new Error("Unable to allocate a unique upload filename.");
2303
2370
  },
2304
- async remove(filename) {
2305
- if (!isUploadFilename(filename)) return false;
2306
- if (!(await listFiles(inRepo(uploadsDir)) ?? []).includes(filename)) return false;
2307
- await commit([{
2308
- path: inRepo(uploadsDir, filename),
2309
- remove: true
2310
- }], () => `Remove ${filename}`);
2311
- return true;
2371
+ async assetExists(src) {
2372
+ if (!isAssetPath(src)) return false;
2373
+ const slash = src.lastIndexOf("/");
2374
+ const folder = inRepo(src.slice(0, slash));
2375
+ const name = src.slice(slash + 1);
2376
+ for (const ref of await target.refs()) if ((await listFilesAt(folder, ref))?.includes(name)) return true;
2377
+ return false;
2312
2378
  }
2313
- },
2314
- async assetExists(src) {
2315
- if (!isAssetPath(src)) return false;
2316
- const slash = src.lastIndexOf("/");
2317
- return (await listFiles(inRepo(src.slice(0, slash))))?.includes(src.slice(slash + 1)) ?? false;
2379
+ };
2380
+ }
2381
+ const direct = {
2382
+ readRef: baseBranch,
2383
+ refs: async () => [await baseBranch()],
2384
+ writeBranch: baseBranch
2385
+ };
2386
+ if (!prMode) return view(direct);
2387
+ /** The branch of one entry's pull request: `bearminion/<scope>`, then `-2`, `-3` once earlier pull requests are closed. */
2388
+ async function activeBranch(scope) {
2389
+ const stem = branchStem(scope);
2390
+ for (let index = 1; index <= MAX_BRANCHES_PER_SCOPE; index += 1) {
2391
+ const name = index === 1 ? stem : `${stem}-${index}`;
2392
+ if (await branchHead(name) === void 0) return {
2393
+ name,
2394
+ exists: false
2395
+ };
2396
+ if (await pullState(name) !== "closed") return {
2397
+ name,
2398
+ exists: true
2399
+ };
2318
2400
  }
2401
+ throw new StoreError(409, "branch_exhausted", `There are already ${MAX_BRANCHES_PER_SCOPE} closed pull requests for "${scope}". Delete some of the bearminion/ branches.`);
2402
+ }
2403
+ const labelName = options.label === void 0 ? "bearminion" : options.label;
2404
+ async function openPullRequest(scope, name, change) {
2405
+ if (await pullState(name) === "open") return;
2406
+ const kind = scope.replace(":", ": ");
2407
+ const files = [...change.written.map((path) => `- ${path}`), ...change.removed.map((path) => `- ${path} (removed)`)].join("\n");
2408
+ const text = options.pullRequest?.({
2409
+ scope,
2410
+ ...change
2411
+ }) ?? {
2412
+ title: `Edit ${kind}`,
2413
+ body: `Opened by the BearMinion editor. Merge it to publish the change.\n\nFirst save changed:\n${files}\n\nLater saves of the same entry are added to this pull request.`
2414
+ };
2415
+ const reply = await send("POST", `/repos/${repo}/pulls`, { body: {
2416
+ title: text.title,
2417
+ head: name,
2418
+ base: await baseBranch(),
2419
+ body: text.body
2420
+ } });
2421
+ if (reply.status === 422 && /already exists/i.test(messageOf(reply.text))) return;
2422
+ if (reply.status !== 201) throw failure(reply, "open the pull request");
2423
+ if (labelName === false) return;
2424
+ const { number } = JSON.parse(reply.text);
2425
+ await send("POST", `/repos/${repo}/issues/${number}/labels`, { body: { labels: [labelName] } });
2426
+ }
2427
+ function scopeTarget(scope) {
2428
+ const readRef = async () => {
2429
+ const active = await activeBranch(scope);
2430
+ return active.exists ? active.name : baseBranch();
2431
+ };
2432
+ return {
2433
+ readRef,
2434
+ refs: async () => {
2435
+ const refs = [await readRef()];
2436
+ if (scope !== "uploads") {
2437
+ const uploads = await activeBranch("uploads");
2438
+ if (uploads.exists) refs.push(uploads.name);
2439
+ }
2440
+ const base = await baseBranch();
2441
+ if (!refs.includes(base)) refs.push(base);
2442
+ return refs;
2443
+ },
2444
+ async writeBranch() {
2445
+ const active = await activeBranch(scope);
2446
+ if (active.exists) return active.name;
2447
+ const base = await baseBranch();
2448
+ const sha = await branchHead(base);
2449
+ if (sha === void 0) throw failure({
2450
+ status: 404,
2451
+ headers: new Headers(),
2452
+ text: ""
2453
+ }, `read the branch "${base}"`);
2454
+ const created = await send("POST", `/repos/${repo}/git/refs`, { body: {
2455
+ ref: `refs/heads/${active.name}`,
2456
+ sha
2457
+ } });
2458
+ if (created.status !== 201 && created.status !== 422) throw failure(created, `create the branch "${active.name}"`);
2459
+ return active.name;
2460
+ },
2461
+ committed: (name, change) => openPullRequest(scope, name, change)
2462
+ };
2463
+ }
2464
+ const scoped = (scope) => view(scopeTarget(scope));
2465
+ const base = view(direct);
2466
+ const edits = scoped("edits");
2467
+ const uploadScope = scoped("uploads");
2468
+ return {
2469
+ read: base.read,
2470
+ exists: base.exists,
2471
+ list: base.list,
2472
+ apply: edits.apply,
2473
+ uploads: uploadScope.uploads,
2474
+ assetExists: base.assetExists,
2475
+ scoped
2319
2476
  };
2320
2477
  }
2321
2478
  //#endregion
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { $ as Theme, $t as SCHEMA_VERSION_KEY, A as ContentModel, At as wireKinds, B as Footer, Bt as motionOption, C as jsonLdSchema, Ct as SectionConfig, D as siteJsonLdIds, Dt as WireRect, E as parseJsonLdInput, Et as WireKind, F as defaultTheme, Ft as EnumOption, G as Site, Gt as FieldChoices, H as FooterConfig, Ht as toneOption, I as defineTheme, It as NumberOption, J as SiteConsent, Jt as ShowWhen, K as SiteAnalytics, Kt as FieldIcons, L as BRAND_LOGO_HEIGHT, Lt as Option, M as ThemeConfig, Mt as OptionalContent, N as ThemeDefinition, Nt as BooleanOption, O as upsertJsonLd, Ot as Wireframe, P as ThemeFont, Pt as CountRule, Q as SiteWith, Qt as DocumentKind, R as DEFAULT_MAX_FOOTER_COLUMNS, Rt as StringOption, S as isPlaceholderSiteUrl, St as withEmphasis, T as mergeJsonLd, Tt as defineSection, U as Header, Ut as tones, V as FooterColumn, Vt as themeModes, W as HeaderConfig, Wt as variantOption, X as SiteOf, Xt as ContentMigrator, Y as SiteDefinition, Yt as ContentMigration, Z as SiteSeo, Zt as ContentVersioning, _ as SiteJsonLdIds, _t as richTextSchema, a as createPageSchema, at as themeColorsSchema, b as generateSiteJsonLd, bt as toneSchema, c as withoutOrphanSections, ct as Image, d as SectionOf, dt as RichText, en as createMigrator, et as brandLogoSchema, f as anchorSchema, ft as Text, g as JsonLdResult, gt as linkSchema, h as JsonLdBlock, ht as imageSchema, i as Seo, it as siteSeoSchema, j as SectionRegistry, jt as wireframeIssues, k as API_PREFIX, kt as defineWireframe, l as BaseSection, lt as Link, m as sectionIdSchema, mt as htmlIdSchema, nt as siteAnalyticsSchema, o as isSystemPage, ot as themeSchema, p as createSectionSchema, pt as Tone, q as SiteConfig, qt as ShowCondition, r as SYSTEM_PAGES, rt as siteConsentSchema, s as seoSchema, st as ButtonStyle, t as Page, tt as defineSite, u as PropsOf, ut as MAX_NAV_DEPTH, v as SiteJsonLdSource, vt as textMarkSchema, w as jsonLdWarnings, wt as SectionDefinition, x as hasJsonLdId, xt as trackingIdSchema, y as formatJsonLd, yt as textSchema, z as DEFAULT_MAX_HEADER_ACTIONS, zt as buttonStyles } from "./page-CwbIDegI.js";
2
2
  import { _ as renderMarkedHtml, a as WeightMark, f as markClass, g as reconcileMarks, i as TextRun, l as fontMarks, m as marksFromEmphasis, o as applyTextMark, r as TextMark, t as FontMark, v as splitMarkedText, y as weightMarks } from "./marks-BzLa48Y9.js";
3
- import "./options-DP6mTauQ.js";
3
+ import "./options-CosfIOMs.js";
4
4
  import { a as TURNSTILE_FIELD, i as HONEYPOT_FIELD, n as FormResult, r as FormSubmission, t as FormFieldErrors } from "./form-contract-BURSJP3Y.js";
5
5
  //#region src/errors.d.ts
6
6
  /** One schema problem, addressed by a dot path such as `sections.0.props.heading`. */
@@ -60,6 +60,12 @@ interface ContentStore {
60
60
  * fail validation. A store without it skips that check.
61
61
  */
62
62
  assetExists?(src: string): Promise<boolean>;
63
+ /**
64
+ * A view of the store for editing one entry (`page:about`, `site`), for stores that keep each entry's pending edits
65
+ * apart, such as `githubStore` in `pr` mode, where every scope is a branch and a pull request. Reads see the entry's
66
+ * pending edits, writes go to them. Absent when every write goes to the same place.
67
+ */
68
+ scoped?(scope: string): ContentStore;
63
69
  }
64
70
  type StoreOperation = {
65
71
  type: 'write';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bearminion",
3
- "version": "1.13.0",
3
+ "version": "1.14.0",
4
4
  "description": "A git-based CMS for Astro with no database and no server: JSON content in your repo, edited by clicking on the page during astro dev.",
5
5
  "license": "MIT",
6
6
  "author": "Jakub Lange",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "template": "default",
4
- "version": "1.13.0",
4
+ "version": "1.14.0",
5
5
  "files": {
6
6
  "src/components/atoms/Button.astro": {
7
7
  "hash": "7be42b3dc3a3b59bec169de32a9d801904689e2705473d1945724658dc799043",