@acryldev/plugin-share 0.1.3 → 0.1.4

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/lib/index.js CHANGED
@@ -2,16 +2,96 @@ import { packagePlugin } from "./package.js";
2
2
  import { createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { findSecrets } from "@acryldev/app-persistence";
5
- import { digestFiles, digestFolder, portabilityIssues } from "@acryldev/blends-core";
5
+ import { digestFiles, digestFolder, pluginFiles, portabilityIssues } from "@acryldev/blends-core";
6
6
  import { NAME } from "@acryldev/extensions";
7
7
  import { LOCK_FILE, writeLock } from "@acryldev/manifest/lock";
8
- import { InvalidPluginSourceError, PluginStore, PullError, bumpVersion, gitCli, githubCli, githubReleasesOverHttps, hostInjectFromSource, httpsDownload, packFolder, parsePluginSource, pullPlugin, readTarball, sharePlugin, storeRootOf } from "@acryldev/plugin-hub-core";
8
+ import { InvalidPluginSourceError, NPM_REGISTRY, PluginStore, PullError, bumpVersion, firstRegistryPort, gitCli, githubCli, githubReleasesOverHttps, hostInjectFromSource, httpsDownload, npmCli, npmRegistryOverHttps, npmRegistryViaCli, packFolder, parsePluginSource, pullPlugin, readTarball, sharePlugin, storeRootOf } from "@acryldev/plugin-hub-core";
9
9
  import { Service } from "@deepseek-ai/cordis";
10
- import { spawn } from "node:child_process";
10
+ import { spawn, spawnSync } from "node:child_process";
11
+ import { tmpdir } from "node:os";
11
12
  import { createHash } from "node:crypto";
12
13
  import { Readable } from "node:stream";
13
14
  import { pipeline } from "node:stream/promises";
14
15
  import { isMap, isSeq, parseDocument } from "yaml";
16
+ //#region merge-edits.ts
17
+ /**
18
+ * A pulled plugin pulled again at a newer release, with the person's own edits in its folder. Three trees meet: `base` (the release they pulled), `mine` (the
19
+ * folder now) and `theirs` (the new release). A file only one side changed takes that side's change; a file both changed is merged line by line, and the
20
+ * merge is refused when the changes overlap. Pure over bytes, except the line merge, which is git's (`git merge-file`) and is passed in so a test needs no git.
21
+ */
22
+ const same = (a, b) => a === void 0 || b === void 0 ? a === b : Buffer.from(a).equals(b);
23
+ /** git's own three-way line merge. A binary file, a conflict, or no git on this computer is "cannot merge". */
24
+ const gitMergeFile = (base, mine, theirs) => {
25
+ if ([
26
+ base,
27
+ mine,
28
+ theirs
29
+ ].some((bytes) => bytes.includes(0))) return void 0;
30
+ const dir = mkdtempSync(join(tmpdir(), "plugin-merge-"));
31
+ try {
32
+ const [b, m, t] = [
33
+ "base",
34
+ "mine",
35
+ "theirs"
36
+ ].map((name) => join(dir, name));
37
+ writeFileSync(b, base);
38
+ writeFileSync(m, mine);
39
+ writeFileSync(t, theirs);
40
+ const result = spawnSync("git", [
41
+ "merge-file",
42
+ "-p",
43
+ m,
44
+ b,
45
+ t
46
+ ], { maxBuffer: 64 * 1024 * 1024 });
47
+ return result.error === void 0 && result.status === 0 ? result.stdout : void 0;
48
+ } finally {
49
+ rmSync(dir, {
50
+ recursive: true,
51
+ force: true
52
+ });
53
+ }
54
+ };
55
+ /** shortcut: a symlink is read as the file it points at and written back as a file; a plugin that is pulled holds none (portability refuses them). */
56
+ function mergeTrees(base, mine, theirs, mergeFile = gitMergeFile) {
57
+ const files = /* @__PURE__ */ new Map();
58
+ const kept = [];
59
+ const conflicts = [];
60
+ const paths = [.../* @__PURE__ */ new Set([
61
+ ...base.keys(),
62
+ ...mine.keys(),
63
+ ...theirs.keys()
64
+ ])].sort();
65
+ for (const path of paths) {
66
+ const [b, m, t] = [
67
+ base.get(path),
68
+ mine.get(path),
69
+ theirs.get(path)
70
+ ];
71
+ const put = (bytes) => {
72
+ if (bytes !== void 0) files.set(path, bytes);
73
+ };
74
+ if (same(m, t)) put(m);
75
+ else if (same(m, b)) put(t);
76
+ else if (same(t, b)) {
77
+ put(m);
78
+ kept.push(path);
79
+ } else if (b !== void 0 && m !== void 0 && t !== void 0) {
80
+ const merged = mergeFile(b, m, t);
81
+ if (merged === void 0) conflicts.push(path);
82
+ else {
83
+ files.set(path, merged);
84
+ kept.push(path);
85
+ }
86
+ } else conflicts.push(path);
87
+ }
88
+ return {
89
+ files,
90
+ kept,
91
+ conflicts
92
+ };
93
+ }
94
+ //#endregion
15
95
  //#region native.ts
16
96
  /**
17
97
  * A plugin's native packages: large, per-OS npm packages a plugin needs and declares instead of depending on (a pull installs no dependencies). The
@@ -204,15 +284,49 @@ function releaseNative(native, places, keepDownload = false) {
204
284
  });
205
285
  }
206
286
  //#endregion
287
+ //#region npm-login.ts
288
+ /**
289
+ * The person's own npm, for a publish: who is signed in (`npm whoami`) and the publish itself, both through the `npm` on this computer and its configuration
290
+ * (`.npmrc`). Nothing here reads or stores a token; a missing npm or login is reported with what to do.
291
+ */
292
+ function npmWithLogin() {
293
+ return {
294
+ ...npmCli(),
295
+ login(registry) {
296
+ const result = spawnSync("npm", [
297
+ "whoami",
298
+ "--registry",
299
+ registry
300
+ ], {
301
+ encoding: "utf8",
302
+ shell: process.platform === "win32",
303
+ env: {
304
+ ...process.env,
305
+ npm_config_update_notifier: "false"
306
+ }
307
+ });
308
+ if (result.error !== void 0) throw new Error("npm is not available here: install Node.js (https://nodejs.org), which includes npm, and sign in with: npm login");
309
+ const account = (result.stdout ?? "").trim();
310
+ if (result.status !== 0 || account === "") {
311
+ const last = (result.stderr ?? "").trim().split("\n").filter((line) => !/^npm (notice|warn)/iu.test(line)).at(-1) ?? "not signed in";
312
+ throw new Error(`npm whoami failed: ${last} (sign in with: npm login --registry ${registry})`);
313
+ }
314
+ return account;
315
+ }
316
+ };
317
+ }
318
+ //#endregion
207
319
  //#region publish.ts
208
320
  /** The line a friend copies: it names the bytes, so the check comes for free. */
209
321
  const pullLineOf = (owner, repo, version, digest) => `npm run acryl -- plugin pull github:${owner}/${repo}@${version}@sha256:${digest}`;
322
+ /** The line a friend copies for an npm package. */
323
+ const npmPullLineOf = (name, version, digest) => `npm run acryl -- plugin pull npm:${name}@${version}@sha256:${digest}`;
210
324
  /**
211
325
  * The same plan: what the person confirmed is what would be published now. `released` only explains the version, and is gone once the next one is packaged.
212
326
  * Field by field, so a plan that came back through JSON from another surface (the frame's confirm) is the same plan whatever order its fields arrived in.
213
327
  */
214
328
  function samePlan(a, b) {
215
- return a.owner === b.owner && a.repo === b.repo && a.version === b.version && a.visibility === b.visibility && a.license === b.license && a.createsRepository === b.createsRepository && a.integrity === b.integrity && a.digest === b.digest && a.pullLine === b.pullLine && a.files.length === b.files.length && a.files.every((file, index) => file === b.files[index]);
329
+ return a.target === b.target && a.package === b.package && a.registry === b.registry && a.owner === b.owner && a.repo === b.repo && a.version === b.version && a.visibility === b.visibility && a.license === b.license && a.createsRepository === b.createsRepository && a.integrity === b.integrity && a.digest === b.digest && a.pullLine === b.pullLine && a.files.length === b.files.length && a.files.every((file, index) => file === b.files[index]);
216
330
  }
217
331
  //#endregion
218
332
  //#region pull-check.ts
@@ -375,6 +489,41 @@ function withPulledRecord(text, name, record) {
375
489
  }
376
490
  return String(document);
377
491
  }
492
+ const GITHUB_REPO = /^https:\/\/github\.com\/([A-Za-z0-9][A-Za-z0-9-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*?)(?:\.git)?\/?$/u;
493
+ /** Find `id` (or the package name, `@scope/name`) in the index text; its release as a source, or why there is none. */
494
+ function lookUpRegistry(indexText, id) {
495
+ let entries;
496
+ try {
497
+ entries = JSON.parse(indexText).entries;
498
+ } catch {
499
+ entries = void 0;
500
+ }
501
+ if (!Array.isArray(entries)) return {
502
+ ok: false,
503
+ reason: "the registry answered in a way this app does not understand",
504
+ next: "try again later, or pull github:<owner>/<repo> from the plugin page"
505
+ };
506
+ const wanted = id.trim().toLowerCase();
507
+ const entry = entries.find((item) => typeof item?.id === "string" && (item.id.toLowerCase() === wanted || typeof item.name === "string" && item.name.toLowerCase() === wanted));
508
+ if (entry === void 0) return {
509
+ ok: false,
510
+ reason: `the registry lists no plugin ${id}`,
511
+ next: "copy the id from https://cordisplugins.github.io, or pull github:<owner>/<repo>"
512
+ };
513
+ const repo = typeof entry.repo === "string" ? GITHUB_REPO.exec(entry.repo) : null;
514
+ if (repo === null || typeof entry.version !== "string" || typeof entry.integrity !== "string") return {
515
+ ok: false,
516
+ reason: `the registry's entry for ${id} does not name a GitHub release this app can pull`,
517
+ next: "open its page on https://cordisplugins.github.io for how to install it"
518
+ };
519
+ return {
520
+ ok: true,
521
+ hit: {
522
+ source: `github:${repo[1]}/${repo[2]}@${entry.version}`,
523
+ integrity: entry.integrity
524
+ }
525
+ };
526
+ }
378
527
  //#endregion
379
528
  //#region index.ts
380
529
  /**
@@ -396,17 +545,19 @@ function releaseOf(folder) {
396
545
  /** The license a new public plugin is offered under; the plan shows it before the person says yes. */
397
546
  const DEFAULT_LICENSE = "MIT";
398
547
  const LICENSE_ID = /^[A-Za-z0-9][A-Za-z0-9.+-]*$/u;
548
+ /** An npm scope: what follows `@`. */
549
+ const NPM_SCOPE = /^[a-z0-9][a-z0-9._~-]*$/u;
399
550
  const publishRefused = (reason, next) => ({
400
551
  ok: false,
401
552
  reason,
402
553
  next
403
554
  });
404
- const SOURCE_FORMS = "github:<owner>/<repo>[@<version>] or a .tgz path or address";
555
+ const SOURCE_FORMS = "github:<owner>/<repo>[@<version>], npm:<package>[@<version>], registry:<id> or a .tgz path or address";
405
556
  /** Read what a person wrote. A `.tgz` path may be relative to the app folder; the hub only takes absolute ones. */
406
557
  function readSource(input, root) {
407
558
  const { source, digest } = splitDigest(input.trim());
408
559
  const parsed = parsePluginSource(/\.(?:tgz|tar\.gz)$/iu.test(source) && !/^[a-z][a-z0-9+]+:/iu.test(source) ? resolve(root, source) : source);
409
- if (parsed.kind !== "github" && parsed.kind !== "tarball-file" && parsed.kind !== "tarball-url") throw new InvalidPluginSourceError(input, `${parsed.kind === "name" ? "a bare name" : parsed.kind} sources are not offered here; pull ${SOURCE_FORMS}`);
560
+ if (parsed.kind !== "github" && parsed.kind !== "npm" && parsed.kind !== "tarball-file" && parsed.kind !== "tarball-url") throw new InvalidPluginSourceError(input, `${parsed.kind === "name" ? "a bare name" : parsed.kind} sources are not offered here; pull ${SOURCE_FORMS}`);
410
561
  return {
411
562
  source: parsed,
412
563
  ...digest === void 0 ? {} : { digest }
@@ -415,8 +566,27 @@ function readSource(input, root) {
415
566
  /** The source as another machine can fetch it: the version pinned; a file on this machine names nothing. */
416
567
  function recordedSource(source, version) {
417
568
  if (source.kind === "github") return `github:${source.owner}/${source.repo}@${version}`;
569
+ if (source.kind === "npm") return `npm:${source.name.full}@${version}`;
418
570
  return source.kind === "tarball-url" ? source.url : void 0;
419
571
  }
572
+ /** What two releases of one plugin share in a recorded source: `github:<owner>/<repo>` or `npm:<package>`, lower case. */
573
+ const repoOf = (source) => {
574
+ const github = /^(github:[^/@]+\/[^/@]+)@/u.exec(source)?.[1];
575
+ const npm = /^(npm:(?:@[^/@]+\/)?[^/@]+)@/u.exec(source)?.[1];
576
+ return (github ?? npm)?.toLowerCase();
577
+ };
578
+ /** A package's folder in `plugins/`: the name after its scope (`@ana/clock` is `clock`). */
579
+ const folderOf = (packageName) => packageName.includes("/") ? packageName.slice(packageName.lastIndexOf("/") + 1) : packageName;
580
+ const treeOf = (files) => new Map(files.map((file) => [file.path, file.bytes]));
581
+ /** Make a plugin folder hold exactly `to`, having held `from`: files only `from` had go, every file of `to` is written. */
582
+ function applyTree(folder, from, to) {
583
+ for (const path of from.keys()) if (!to.has(path)) rmSync(join(folder, ...path.split("/")), { force: true });
584
+ for (const [path, bytes] of to) {
585
+ const file = join(folder, ...path.split("/"));
586
+ mkdirSync(dirname(file), { recursive: true });
587
+ writeFileSync(file, bytes);
588
+ }
589
+ }
420
590
  const reasonOf = (cause) => {
421
591
  if (cause instanceof PullError || cause instanceof InvalidPluginSourceError) return cause.reason;
422
592
  return cause instanceof Error ? cause.message : String(cause);
@@ -427,6 +597,8 @@ var PluginShare = class extends Service {
427
597
  dir;
428
598
  releases;
429
599
  download;
600
+ registryIndex;
601
+ npmRegistry;
430
602
  ports;
431
603
  /** One at a time: two pulls of one name must not race for its folder, nor two publishes for its package. */
432
604
  queue = Promise.resolve();
@@ -446,6 +618,8 @@ var PluginShare = class extends Service {
446
618
  this.dir = resolve(config.dir ?? join(ctx.appInstance.root, "plugins"));
447
619
  this.releases = config.releases ?? githubReleasesOverHttps();
448
620
  this.download = config.download ?? httpsDownload();
621
+ this.registryIndex = config.registryIndex ?? "https://cordisplugins.github.io/registry/index.json";
622
+ this.npmRegistry = config.npm ?? firstRegistryPort(npmRegistryOverHttps(), npmRegistryViaCli());
449
623
  this.nativeWork = config.native ?? nativePorts();
450
624
  this.ports = config.publish ?? {
451
625
  host: githubCli(),
@@ -554,6 +728,7 @@ var PluginShare = class extends Service {
554
728
  const plan = await this.planNow(name, options);
555
729
  if ("ok" in plan) return plan;
556
730
  if (!samePlan(plan, confirmed)) return publishRefused(`this plugin's publish changed since you confirmed it (now ${plan.owner}/${plan.repo} v${plan.version}, digest ${plan.digest}); nothing was sent`, "look at the new plan and say yes again");
731
+ if (plan.target === "npm") return this.publishNpm(name, plan);
557
732
  const { home } = this.own.appInstance;
558
733
  try {
559
734
  const shared = await sharePlugin(join(this.packages, name), {
@@ -700,6 +875,7 @@ var PluginShare = class extends Service {
700
875
  async planNow(name, options) {
701
876
  const source = join(this.dir, name);
702
877
  if (!NAME.test(name) || !existsSync(source)) return publishRefused(`this app has no plugin "${name}" in plugins/`, "name a folder of plugins/");
878
+ if (options.to === "npm") return this.planNpm(name, source, options);
703
879
  try {
704
880
  const { host } = this.ports;
705
881
  const owner = options.owner ?? host.login();
@@ -741,8 +917,111 @@ var PluginShare = class extends Service {
741
917
  return publishRefused(reasonOf(cause), "fix it, or sign in with gh; nothing was sent");
742
918
  }
743
919
  }
920
+ /**
921
+ * What publishing to npm would do, read without sending anything: the account is the person's own npm login (`npm whoami`), the package is
922
+ * `@<scope>/<name>` (the scope defaults to that account), and a version npm already has makes the plan name the next patch, as a GitHub release does.
923
+ */
924
+ async planNpm(name, source, options) {
925
+ const npm = this.ports.npm ?? npmWithLogin();
926
+ const registry = options.registry ?? NPM_REGISTRY;
927
+ try {
928
+ const account = npm.login(registry);
929
+ const scope = (options.scope ?? account).replace(/^@/u, "").toLowerCase();
930
+ if (!NPM_SCOPE.test(scope)) return publishRefused(`"${scope}" is not an npm scope`, "write letters, digits and dashes, for example --scope acme");
931
+ const license = options.license ?? DEFAULT_LICENSE;
932
+ if (!LICENSE_ID.test(license)) return publishRefused(`"${license}" is not a license id`, "write one such as MIT or Apache-2.0");
933
+ const packageName = `@${scope}/${name}`;
934
+ const pack = (version) => this.packNpm(source, name, packageName, license, version);
935
+ let packaged = await pack();
936
+ const released = npm.hasVersion(packageName, packaged.version, registry) ? packaged.version : void 0;
937
+ if (released !== void 0) packaged = await pack(bumpVersion(released, "patch"));
938
+ const secrets = findSecrets(readTarball(packFolder(packaged.dir).tarball).map((file) => ({
939
+ path: file.path,
940
+ text: Buffer.from(file.content).toString("utf8")
941
+ })));
942
+ if (secrets.length > 0) return publishRefused(`the secret check found ${String(secrets.length)} possible secret(s) in ${secrets.map((secret) => secret.path).join(", ")}; nothing was sent`, "take them out of the plugin and read them from the app's settings");
943
+ return {
944
+ target: "npm",
945
+ package: packageName,
946
+ registry,
947
+ owner: scope,
948
+ repo: name,
949
+ version: packaged.version,
950
+ visibility: "public",
951
+ license,
952
+ createsRepository: false,
953
+ ...released === void 0 ? {} : { released },
954
+ files: packaged.files,
955
+ integrity: packaged.integrity,
956
+ digest: packaged.digest,
957
+ pullLine: npmPullLineOf(packageName, packaged.version, packaged.digest)
958
+ };
959
+ } catch (cause) {
960
+ return publishRefused(reasonOf(cause), "fix it, or sign in with: npm login (--registry <address> for another registry); nothing was sent");
961
+ }
962
+ }
963
+ /** The plugin as the npm package `packageName`: a package of its own folder, the same bytes whenever it is made again for the same version. */
964
+ packNpm(source, name, packageName, license, version) {
965
+ return packagePlugin(source, this.packages, name, `The ${name} Cordis plugin.`, {
966
+ release: { license },
967
+ packageName,
968
+ ...version === void 0 ? {} : { version }
969
+ });
970
+ }
971
+ /** The confirmed npm plan, published with the person's own npm: the package is made again, and only the bytes that were planned are sent. */
972
+ async publishNpm(name, plan) {
973
+ const registry = plan.registry ?? NPM_REGISTRY;
974
+ const packageName = plan.package ?? `@${plan.owner}/${plan.repo}`;
975
+ try {
976
+ const packed = await this.packNpm(join(this.dir, name), name, packageName, plan.license, plan.version);
977
+ if (packed.integrity !== plan.integrity) return publishRefused(`the package made now is not the one that was planned (${packageName} v${plan.version}); nothing was sent`, "look at the new plan and say yes again");
978
+ (this.ports.npm ?? npmWithLogin()).publish(packed.tarball, registry, "public");
979
+ const url = registry === NPM_REGISTRY ? `https://www.npmjs.com/package/${packageName}` : `${registry.replace(/\/$/u, "")}/${packageName}`;
980
+ return {
981
+ ok: true,
982
+ url,
983
+ releaseUrl: url,
984
+ version: packed.version,
985
+ integrity: packed.integrity,
986
+ digest: plan.digest,
987
+ pullLine: plan.pullLine
988
+ };
989
+ } catch (cause) {
990
+ return publishRefused(reasonOf(cause), "look at the registry; part of this publish may have been sent");
991
+ }
992
+ }
993
+ /** A `registry:<id>` source turned into the release it lists, with the integrity the registry lists for it; any other source as it is. */
994
+ async resolveRegistry(input, expectIntegrity) {
995
+ const text = input.trim();
996
+ if (!/^registry:/iu.test(text)) return {
997
+ input,
998
+ ...expectIntegrity === void 0 ? {} : { expectIntegrity }
999
+ };
1000
+ let named;
1001
+ try {
1002
+ named = splitDigest(text);
1003
+ } catch (cause) {
1004
+ return refuse("source", reasonOf(cause), "write the 64 hex digits the plugin page shows after @sha256:");
1005
+ }
1006
+ let index;
1007
+ try {
1008
+ index = Buffer.from(await this.download(this.registryIndex)).toString("utf8");
1009
+ } catch (cause) {
1010
+ return refuse("fetch", `the registry could not be read: ${reasonOf(cause)}`, "check the internet connection and pull again, or pull github:<owner>/<repo>");
1011
+ }
1012
+ const found = lookUpRegistry(index, named.source.slice(9));
1013
+ if (!found.ok) return refuse("source", found.reason, found.next);
1014
+ return {
1015
+ input: named.digest === void 0 ? found.hit.source : `${found.hit.source}@sha256:${named.digest}`,
1016
+ expectIntegrity: expectIntegrity ?? found.hit.integrity
1017
+ };
1018
+ }
744
1019
  async pullNow(input, expectIntegrity) {
745
1020
  const { home, root } = this.own.appInstance;
1021
+ const resolved = await this.resolveRegistry(input, expectIntegrity);
1022
+ if ("refusal" in resolved) return resolved;
1023
+ input = resolved.input;
1024
+ expectIntegrity = resolved.expectIntegrity;
746
1025
  let read;
747
1026
  try {
748
1027
  read = readSource(input, root);
@@ -757,11 +1036,13 @@ var PluginShare = class extends Service {
757
1036
  pulled = await pullPlugin(read.source, {
758
1037
  store: new PluginStore(scratch),
759
1038
  releases: this.releases,
1039
+ registry: this.npmRegistry,
760
1040
  download: this.download
761
1041
  }, expectIntegrity === void 0 ? {} : { expectIntegrity });
762
1042
  } catch (cause) {
763
1043
  return refuse("fetch", reasonOf(cause), "check the source with the person who released it; nothing was installed");
764
1044
  }
1045
+ const folderIn = (packageName) => read.source.kind === "npm" ? folderOf(packageName) : packageName;
765
1046
  const files = readTarball(readFileSync(pulled.stored.path)).map(({ path, content }) => ({
766
1047
  path,
767
1048
  bytes: content,
@@ -769,12 +1050,12 @@ var PluginShare = class extends Service {
769
1050
  }));
770
1051
  const refused = pullRefusal(pulled.manifest, files, {
771
1052
  digest: read.digest,
772
- nameFits: (name) => NAME.test(name),
1053
+ nameFits: (name) => NAME.test(folderIn(name)),
773
1054
  hasService: (service) => this.own.get(service) !== void 0
774
1055
  });
775
1056
  if (refused !== void 0) return refused;
776
1057
  const declared = nativesOf(pulled.manifest);
777
- return await this.install(pulled.stored.name, pulled.stored.version, pulled.stored.integrity, files, recordedSource(read.source, pulled.stored.version), "natives" in declared ? nativeFor(declared.natives) : void 0);
1058
+ return await this.install(folderIn(pulled.stored.name), pulled.stored.version, pulled.stored.integrity, files, recordedSource(read.source, pulled.stored.version), "natives" in declared ? nativeFor(declared.natives) : void 0);
778
1059
  } finally {
779
1060
  rmSync(scratch, {
780
1061
  recursive: true,
@@ -782,6 +1063,44 @@ var PluginShare = class extends Service {
782
1063
  });
783
1064
  }
784
1065
  }
1066
+ /**
1067
+ * What the folder holds once a newer release of its pulled plugin comes in, the person's own changes kept: the release they pulled is the base of a
1068
+ * three-way merge (fetched again from where it came from, checked against its recorded integrity, unless the folder is untouched and is the base).
1069
+ * Refused, and nothing written, when the release and the person changed the same lines.
1070
+ */
1071
+ async planUpdate(name, before, held, release, target) {
1072
+ const mine = treeOf(pluginFiles(target));
1073
+ let base = mine;
1074
+ if (held !== before.digest) {
1075
+ const scratch = mkdtempSync(join(this.own.appInstance.home, "plugin-base-"));
1076
+ try {
1077
+ const pulled = await pullPlugin(readSource(before.source, this.own.appInstance.root).source, {
1078
+ store: new PluginStore(scratch),
1079
+ releases: this.releases,
1080
+ registry: this.npmRegistry,
1081
+ download: this.download
1082
+ }, { expectIntegrity: before.integrity });
1083
+ base = treeOf(readTarball(readFileSync(pulled.stored.path)).map(({ path, content }) => ({
1084
+ path,
1085
+ bytes: content,
1086
+ kind: "file"
1087
+ })));
1088
+ } catch (cause) {
1089
+ return refuse("folder-exists", `plugins/${name} has changes of your own, and the release it was pulled from could not be fetched to keep them: ${reasonOf(cause)}`, `check the internet connection and pull again, or move plugins/${name} out of plugins/ and pull again`);
1090
+ } finally {
1091
+ rmSync(scratch, {
1092
+ recursive: true,
1093
+ force: true
1094
+ });
1095
+ }
1096
+ }
1097
+ const merged = mergeTrees(base, mine, treeOf(release));
1098
+ if (merged.conflicts.length > 0) return refuse("folder-exists", `plugins/${name} has changes of your own to ${merged.conflicts.join(", ")}, and the new release changes ${merged.conflicts.length === 1 ? "it" : "them"} too`, `plugins/${name} is untouched: move it out of plugins/ and pull again, then bring your changes back by hand`);
1099
+ return {
1100
+ mine,
1101
+ merged
1102
+ };
1103
+ }
785
1104
  /** Put the files in `plugins/<name>/` and install them; whatever does not end running takes its folder with it. */
786
1105
  async install(name, version, integrity, files, source, native) {
787
1106
  const target = join(this.dir, name);
@@ -800,14 +1119,23 @@ var PluginShare = class extends Service {
800
1119
  const wrote = !existsSync(target);
801
1120
  const before = this.recorded(name);
802
1121
  const held = wrote ? void 0 : digestFolder(target);
1122
+ let update;
803
1123
  if (held !== void 0 && held !== digest) {
804
- const holder = before === void 0 ? "made in this app" : `pulled from ${before.source}`;
805
- const next = before !== void 0 && held === before.digest ? `keep it, or remove it (npm run acryl -- plugin remove ${name}) and pull again` : `keep it, or move plugins/${name} out of plugins/ and pull again`;
806
- return refuse("folder-exists", `plugins/${name} holds a different copy of this plugin, ${holder}`, next);
1124
+ const sameRepo = before !== void 0 && source !== void 0 && repoOf(before.source) !== void 0 && repoOf(before.source) === repoOf(source);
1125
+ if (before !== void 0 && sameRepo && before.digest !== digest) {
1126
+ const planned = await this.planUpdate(name, before, held, files, target);
1127
+ if ("refusal" in planned) return planned;
1128
+ update = planned;
1129
+ } else {
1130
+ const holder = before === void 0 ? "made in this app" : `pulled from ${before.source}`;
1131
+ const next = before !== void 0 && held === before.digest ? `keep it, or remove it (npm run acryl -- plugin remove ${name}) and pull again` : `keep it, or move plugins/${name} out of plugins/ and pull again`;
1132
+ return refuse("folder-exists", `plugins/${name} holds a different copy of this plugin, ${holder}`, next);
1133
+ }
807
1134
  }
808
1135
  const liveBefore = this.live.get(name);
809
1136
  this.live.set(name, digest);
810
1137
  if (wrote) renameSync(incoming, target);
1138
+ else if (update !== void 0) applyTree(target, update.mine, update.merged.files);
811
1139
  const remembered = source !== void 0 && this.remember(name, {
812
1140
  source,
813
1141
  integrity,
@@ -821,6 +1149,7 @@ var PluginShare = class extends Service {
821
1149
  recursive: true,
822
1150
  force: true
823
1151
  });
1152
+ else if (update !== void 0) applyTree(target, update.merged.files, update.mine);
824
1153
  if (remembered) this.remember(name, before);
825
1154
  if (liveBefore === void 0) this.live.delete(name);
826
1155
  else this.live.set(name, liveBefore);
@@ -856,6 +1185,7 @@ var PluginShare = class extends Service {
856
1185
  action: result.action,
857
1186
  state: result.state,
858
1187
  remembered,
1188
+ ...update === void 0 || update.merged.kept.length === 0 ? {} : { kept: update.merged.kept },
859
1189
  ...this.keepNative(name, native, nativeBefore, nativeAction)
860
1190
  };
861
1191
  } finally {