@acryldev/plugin-share 0.0.0-stage → 0.1.1

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/index.ts ADDED
@@ -0,0 +1,791 @@
1
+ /**
2
+ * Sharing a plugin between people: `pull(source)` turns a release someone published into a running plugin in this app. It fetches without running
3
+ * anything, decides from the package's files (`pull-check.ts`), and hands a folder to `extensions`, which owns the install and its rollback.
4
+ * Design: docs/plans/plugin-share.md.
5
+ */
6
+ import {
7
+ existsSync,
8
+ mkdirSync,
9
+ mkdtempSync,
10
+ readFileSync,
11
+ renameSync,
12
+ rmSync,
13
+ statSync,
14
+ writeFileSync,
15
+ } from 'node:fs'
16
+ import { dirname, join, resolve } from 'node:path'
17
+ import { findSecrets } from '@acryldev/app-persistence'
18
+ import { digestFolder, type PluginFile } from '@acryldev/blends-core'
19
+ import { type ExtensionInfo, NAME } from '@acryldev/extensions'
20
+ import type {} from '@acryldev/instance'
21
+ import { LOCK_FILE, writeLock } from '@acryldev/manifest/lock'
22
+ import {
23
+ bumpVersion,
24
+ gitCli,
25
+ githubCli,
26
+ githubReleasesOverHttps,
27
+ httpsDownload,
28
+ InvalidPluginSourceError,
29
+ type PluginSource,
30
+ PluginStore,
31
+ PullError,
32
+ packFolder,
33
+ parsePluginSource,
34
+ pullPlugin,
35
+ type ReleasePort,
36
+ readTarball,
37
+ sharePlugin,
38
+ storeRootOf,
39
+ } from '@acryldev/plugin-hub-core'
40
+ import { type Context, Service } from '@deepseek-ai/cordis'
41
+ import {
42
+ ensureNative,
43
+ type NativeAction,
44
+ type NativePackage,
45
+ type NativePlaces,
46
+ type NativePorts,
47
+ nativeFor,
48
+ nativePorts,
49
+ nativesOf,
50
+ releaseNative,
51
+ } from './native.ts'
52
+ import { packagePlugin } from './package.ts'
53
+ import {
54
+ type PublishOptions,
55
+ type PublishPlan,
56
+ type PublishPorts,
57
+ type PublishRefused,
58
+ type PublishResult,
59
+ pullLineOf,
60
+ samePlan,
61
+ } from './publish.ts'
62
+ import {
63
+ missingServices,
64
+ type PullRefused,
65
+ pullRefusal,
66
+ refuse,
67
+ splitDigest,
68
+ } from './pull-check.ts'
69
+ import { LIST_MAX_BYTES, parsePullList, pullListLocation } from './pull-list.ts'
70
+ import { type PulledRecord, pulledRecords, withPulledRecord } from './pulled-records.ts'
71
+
72
+ export type {
73
+ PublishOptions,
74
+ PublishPlan,
75
+ PublishPorts,
76
+ PublishRefused,
77
+ PublishResult,
78
+ } from './publish.ts'
79
+
80
+ /** One remembered plugin the app fetched again at its start because its folder was gone. */
81
+ export type RestoreOutcome =
82
+ | { readonly name: string; readonly ok: true }
83
+ | { readonly name: string; readonly ok: false; readonly reason: string; readonly next: string }
84
+
85
+ export interface PluginShareConfig {
86
+ /** Where pulled plugins go; must be an extensions source. Defaults to `<project>/plugins`. */
87
+ dir?: string
88
+ /** Where a `github:` source reads releases. Defaults to GitHub over HTTPS. */
89
+ releases?: ReleasePort
90
+ /** Where a publish goes. Defaults to the person's own `gh` and `git`. */
91
+ publish?: PublishPorts
92
+ /** How an https address is read: a release `.tgz` and a list of sources. Defaults to HTTPS with the hub's size and time limits. */
93
+ download?: (url: string) => Promise<Uint8Array>
94
+ /** How a plugin's native package is downloaded and unpacked (native.ts). Defaults to the npm registry and the system's tar. */
95
+ native?: NativePorts
96
+ }
97
+
98
+ export type PullResult =
99
+ | {
100
+ readonly ok: true
101
+ readonly name: string
102
+ readonly version: string
103
+ /** The sha512 of the release's tarball, as the registry lists it. */
104
+ readonly integrity: string
105
+ /** The sha256 of the plugin's content: the same on every OS. A source can name it (`@sha256:<digest>`). */
106
+ readonly digest: string
107
+ readonly action: 'installed' | 'updated' | 'unchanged'
108
+ readonly state: string
109
+ /** Whether the app's `blend.yaml` and lock now name this source, so a copy of the app can fetch it. A local file names nothing to fetch. */
110
+ readonly remembered: boolean
111
+ /** The native package the plugin brought for this computer (native.ts), and what installing it did. */
112
+ readonly native?: {
113
+ readonly package: string
114
+ readonly version: string
115
+ readonly size: number
116
+ readonly action: NativeAction
117
+ }
118
+ }
119
+ | PullRefused
120
+
121
+ /** One source of a list and what pulling it did. */
122
+ export interface PullListEntry {
123
+ /** Its line in the list. */
124
+ readonly line: number
125
+ readonly source: string
126
+ readonly result: PullResult
127
+ }
128
+
129
+ /** A list pulled: every source with its own result (some may be refused while the others install), or the list itself refused. */
130
+ export type PullListResult =
131
+ | { readonly ok: true; readonly from: string; readonly entries: readonly PullListEntry[] }
132
+ | PullRefused
133
+
134
+ /** One plugin installed while the app runs, as a person reads the list: what it is and, for one pulled, where it came from and who released it. */
135
+ /** What extensions says about an installed plugin (its state, the services a pending one waits for, ...), and where a pulled one came from. */
136
+ export interface SharedPluginInfo extends ExtensionInfo {
137
+ /** The source it was pulled from (`github:<owner>/<repo>@<version>` or an address); absent for one made in this app or pulled from a local file. */
138
+ readonly pulledFrom?: string
139
+ /** Who released it: the account of a `github:` source or of a release address on github.com. */
140
+ readonly author?: string
141
+ /** The version its `package.json` names (`version` is the installed content's short digest); absent without one. */
142
+ readonly release?: string
143
+ }
144
+
145
+ /** What removing a plugin did with its folder in `plugins/`. */
146
+ export type RemovedFolder =
147
+ /** It held the release as pulled, so nothing of anyone's is lost: the pull line brings it back. */
148
+ | 'deleted'
149
+ /** It is this app's own work, or a pulled plugin changed after the pull: it stays, and the app starts it again at its next start. */
150
+ | 'kept'
151
+ | 'none'
152
+
153
+ export type SharedRemoveResult =
154
+ | {
155
+ readonly ok: true
156
+ readonly name: string
157
+ readonly folder: RemovedFolder
158
+ readonly note?: string
159
+ }
160
+ | { readonly ok: false; readonly name: string; readonly errors: readonly string[] }
161
+
162
+ declare module '@deepseek-ai/cordis' {
163
+ interface Context {
164
+ pluginShare: PluginShare
165
+ }
166
+ }
167
+
168
+ /** The account that released a source: the owner of a `github:<owner>/<repo>@<version>` source or of a release address on github.com. */
169
+ const authorOf = (source: string): string | undefined =>
170
+ (/^github:([^/]+)\//u.exec(source) ?? /^https:\/\/github\.com\/([^/]+)\//u.exec(source))?.[1]
171
+
172
+ /** The version a plugin folder's `package.json` names, when it names a plain one. */
173
+ function releaseOf(folder: string): string | undefined {
174
+ try {
175
+ const version = (
176
+ JSON.parse(readFileSync(join(folder, 'package.json'), 'utf8')) as { version?: unknown }
177
+ ).version
178
+ return typeof version === 'string' && /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/u.test(version)
179
+ ? version
180
+ : undefined
181
+ } catch {
182
+ return undefined
183
+ }
184
+ }
185
+
186
+ /** The license a new public plugin is offered under; the plan shows it before the person says yes. */
187
+ const DEFAULT_LICENSE = 'MIT'
188
+ const LICENSE_ID = /^[A-Za-z0-9][A-Za-z0-9.+-]*$/u
189
+
190
+ const publishRefused = (reason: string, next: string): PublishRefused => ({
191
+ ok: false,
192
+ reason,
193
+ next,
194
+ })
195
+
196
+ const SOURCE_FORMS = 'github:<owner>/<repo>[@<version>] or a .tgz path or address'
197
+
198
+ /** Read what a person wrote. A `.tgz` path may be relative to the app folder; the hub only takes absolute ones. */
199
+ function readSource(
200
+ input: string,
201
+ root: string,
202
+ ): { readonly source: PluginSource; readonly digest?: string } {
203
+ const { source, digest } = splitDigest(input.trim())
204
+ const isLocalTarball = /\.(?:tgz|tar\.gz)$/iu.test(source) && !/^[a-z][a-z0-9+]+:/iu.test(source)
205
+ const parsed = parsePluginSource(isLocalTarball ? resolve(root, source) : source)
206
+ if (parsed.kind !== 'github' && parsed.kind !== 'tarball-file' && parsed.kind !== 'tarball-url') {
207
+ const named = parsed.kind === 'name' ? 'a bare name' : parsed.kind
208
+ throw new InvalidPluginSourceError(
209
+ input,
210
+ `${named} sources are not offered here; pull ${SOURCE_FORMS}`,
211
+ )
212
+ }
213
+ return { source: parsed, ...(digest === undefined ? {} : { digest }) }
214
+ }
215
+
216
+ /** The source as another machine can fetch it: the version pinned; a file on this machine names nothing. */
217
+ function recordedSource(source: PluginSource, version: string): string | undefined {
218
+ if (source.kind === 'github') return `github:${source.owner}/${source.repo}@${version}`
219
+ return source.kind === 'tarball-url' ? source.url : undefined
220
+ }
221
+
222
+ const reasonOf = (cause: unknown): string => {
223
+ if (cause instanceof PullError || cause instanceof InvalidPluginSourceError) return cause.reason
224
+ return cause instanceof Error ? cause.message : String(cause)
225
+ }
226
+
227
+ export class PluginShare extends Service {
228
+ /** What was fetched again at this start. */
229
+ readonly restored: Promise<readonly RestoreOutcome[]>
230
+ private readonly dir: string
231
+ private readonly releases: ReleasePort
232
+ private readonly download: (url: string) => Promise<Uint8Array>
233
+ private readonly ports: PublishPorts
234
+ /** One at a time: two pulls of one name must not race for its folder, nor two publishes for its package. */
235
+ private queue: Promise<unknown> = Promise.resolve()
236
+ /** The content digest of each plugin pulled while the app runs, a local file's too, which `blend.yaml` does not remember. */
237
+ private readonly live = new Map<string, string>()
238
+ private readonly nativeWork: NativePorts
239
+ /** The native package each installed plugin brought for this computer: what its removal takes away. */
240
+ private readonly natives = new Map<string, NativePackage>()
241
+
242
+ /**
243
+ * The context the service was constructed with, in the app's realm. Inside a service method `this.ctx` is Cordis's shadow context of the caller: in the
244
+ * frame that is the host's door, which does not see the app's own services (`home`), so a plugin needing them was refused. As `extensions` does.
245
+ */
246
+ private readonly own: Context
247
+
248
+ constructor(ctx: Context, config: PluginShareConfig) {
249
+ super(ctx, 'pluginShare')
250
+ this.own = ctx
251
+ this.dir = resolve(config.dir ?? join(ctx.appInstance.root, 'plugins'))
252
+ this.releases = config.releases ?? githubReleasesOverHttps()
253
+ this.download = config.download ?? httpsDownload()
254
+ this.nativeWork = config.native ?? nativePorts()
255
+ this.ports = config.publish ?? { host: githubCli(), git: gitCli() }
256
+ // Removing a plugin removes its record. Listened to here, not asked of each caller: every way of removing it goes through extensions.
257
+ ctx.on('extensions/changed', (name, change) => {
258
+ if (change !== 'removed') return
259
+ this.live.delete(name)
260
+ this.remember(name, undefined)
261
+ this.dropNative(name)
262
+ })
263
+ // Not awaited by the app's start: a person offline still gets their app, and the warning says what is missing.
264
+ this.restored = this.inTurn(() => this.restore())
265
+ }
266
+
267
+ /** Pull a plugin into the running app. Never throws for what a person can act on: a refusal says what is wrong and what to do, and changes nothing. */
268
+ pull(source: string): Promise<PullResult> {
269
+ return this.inTurn(() => this.pullNow(source))
270
+ }
271
+
272
+ /**
273
+ * Pull every source of a list, a file in the app or an https address (a gist, a file in the group's repository): one after the other and each on
274
+ * its own, so a source that is refused, or clashes with a plugin already here, is reported with its reason while the others install and keep running.
275
+ * A list that cannot be read, or has a line that is not one source, pulls nothing.
276
+ */
277
+ async pullList(from: string): Promise<PullListResult> {
278
+ const text = await this.readList(from)
279
+ if (typeof text !== 'string') return text
280
+ const { sources, problems } = parsePullList(text)
281
+ if (problems.length > 0)
282
+ return refuse('list', `${from}: ${problems.join('; ')}`, 'fix the list; nothing was pulled')
283
+ if (sources.length === 0)
284
+ return refuse(
285
+ 'list',
286
+ `${from} names no plugin`,
287
+ 'write one source per line, e.g. github:someone/pomodoro@0.1.0',
288
+ )
289
+ const entries: PullListEntry[] = []
290
+ for (const { line, source } of sources)
291
+ entries.push({ line, source, result: await this.pull(source) })
292
+ return { ok: true, from, entries }
293
+ }
294
+
295
+ /** The text of a list, or why it cannot be read. */
296
+ private async readList(from: string): Promise<string | PullRefused> {
297
+ const where = pullListLocation(from)
298
+ if (where === undefined)
299
+ return refuse(
300
+ 'list',
301
+ `"${from}" is not a list`,
302
+ 'name a file in the app (e.g. group.txt) or an https address of one',
303
+ )
304
+ try {
305
+ let bytes: Uint8Array
306
+ if (where.kind === 'address') bytes = await this.download(where.url)
307
+ else {
308
+ const path = resolve(this.own.appInstance.root, where.path)
309
+ if (!existsSync(path) || !statSync(path).isFile())
310
+ return refuse(
311
+ 'list',
312
+ `there is no file ${where.path}`,
313
+ 'name a file in the app, or an https address',
314
+ )
315
+ bytes = readFileSync(path)
316
+ }
317
+ if (bytes.length > LIST_MAX_BYTES)
318
+ return refuse(
319
+ 'list',
320
+ `${from} is larger than ${String(LIST_MAX_BYTES)} bytes, so it is not a list of plugins`,
321
+ 'name the list itself',
322
+ )
323
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes)
324
+ } catch (cause) {
325
+ return refuse(
326
+ 'list',
327
+ `${from} could not be read: ${reasonOf(cause)}`,
328
+ 'check the address; nothing was pulled',
329
+ )
330
+ }
331
+ }
332
+
333
+ /**
334
+ * The content digest of a pulled plugin as it was installed: set before its folder appears, so whoever sees the folder change can tell the release as
335
+ * pulled from an edit (the frame then does not load the app again for it). A pull from a local file has no record in `blend.yaml`; this knows it too.
336
+ */
337
+ pulledDigest(name: string): string | undefined {
338
+ return this.live.get(name) ?? this.recorded(name)?.digest
339
+ }
340
+
341
+ /** The plugins installed while the app runs, each pulled one with its source and author. */
342
+ list(): SharedPluginInfo[] {
343
+ const file = join(this.own.appInstance.root, 'blend.yaml')
344
+ const records = existsSync(file) ? pulledRecords(readFileSync(file, 'utf8')) : {}
345
+ return this.own.extensions.list().map((info) => {
346
+ const record = records[info.name]
347
+ const author = record === undefined ? undefined : authorOf(record.source)
348
+ const release = releaseOf(join(this.dir, info.name))
349
+ return {
350
+ ...info,
351
+ ...(record === undefined ? {} : { pulledFrom: record.source }),
352
+ ...(author === undefined ? {} : { author }),
353
+ ...(release === undefined ? {} : { release }),
354
+ }
355
+ })
356
+ }
357
+
358
+ /**
359
+ * Take a plugin out of the running app and forget its record. A pulled plugin's folder is deleted when it still holds the release as pulled; a
360
+ * folder with someone's work in it (this app's own plugin, or a pulled one changed since) stays, and the answer says so.
361
+ */
362
+ remove(name: string): Promise<SharedRemoveResult> {
363
+ return this.inTurn(() => this.removeNow(name))
364
+ }
365
+
366
+ private inTurn<T>(step: () => Promise<T>): Promise<T> {
367
+ const run = this.queue.then(step)
368
+ this.queue = run.catch(() => undefined)
369
+ return run
370
+ }
371
+
372
+ /**
373
+ * What publishing this plugin would do, read without sending anything. A plan is the only thing an agent can get: it never confirms for a person.
374
+ */
375
+ planPublish(name: string, options: PublishOptions = {}): Promise<PublishPlan | PublishRefused> {
376
+ return this.inTurn(() => this.planNow(name, options))
377
+ }
378
+
379
+ /**
380
+ * Publish exactly the plan a person said yes to: it is made again, and if anything differs (the plugin, the account, a release made meanwhile) nothing
381
+ * is sent. Only the person's own surfaces call this: the frame's confirm and the terminal's prompt. No verb reaches it.
382
+ */
383
+ publish(
384
+ name: string,
385
+ confirmed: PublishPlan,
386
+ options: PublishOptions = {},
387
+ ): Promise<PublishResult> {
388
+ return this.inTurn(async () => {
389
+ const plan = await this.planNow(name, options)
390
+ if ('ok' in plan) return plan
391
+ if (!samePlan(plan, confirmed)) {
392
+ return publishRefused(
393
+ `this plugin's publish changed since you confirmed it (now ${plan.owner}/${plan.repo} v${plan.version}, digest ${plan.digest}); nothing was sent`,
394
+ 'look at the new plan and say yes again',
395
+ )
396
+ }
397
+ const { home } = this.own.appInstance
398
+ try {
399
+ const shared = await sharePlugin(
400
+ join(this.packages, name),
401
+ {
402
+ owner: plan.owner,
403
+ repo: plan.repo,
404
+ visibility: plan.visibility,
405
+ kind: 'source-plugin',
406
+ },
407
+ { ...this.ports, store: new PluginStore(storeRootOf(home)) },
408
+ )
409
+ if (shared.status === 'refused')
410
+ return publishRefused(shared.reason, 'fix what it names; nothing was sent')
411
+ return {
412
+ ok: true,
413
+ url: shared.url,
414
+ releaseUrl: shared.releaseUrl,
415
+ version: shared.version,
416
+ integrity: shared.integrity,
417
+ digest: plan.digest,
418
+ pullLine: plan.pullLine,
419
+ }
420
+ } catch (cause) {
421
+ return publishRefused(
422
+ reasonOf(cause),
423
+ 'look at the repository; part of this publish may have been sent',
424
+ )
425
+ }
426
+ })
427
+ }
428
+
429
+ /** Write one plugin's record into `blend.yaml`, and the lock when the app has one, so the two still match. @returns whether the app holds the record. */
430
+ private remember(name: string, record: PulledRecord | undefined): boolean {
431
+ const { root } = this.own.appInstance
432
+ const file = join(root, 'blend.yaml')
433
+ if (!existsSync(file)) return false
434
+ const text = readFileSync(file, 'utf8')
435
+ const next = withPulledRecord(text, name, record)
436
+ if (next !== text) {
437
+ writeFileSync(`${file}.tmp`, next)
438
+ renameSync(`${file}.tmp`, file)
439
+ if (existsSync(join(root, LOCK_FILE))) writeLock(root)
440
+ }
441
+ return record === undefined || pulledRecords(next)[name] !== undefined
442
+ }
443
+
444
+ private async removeNow(name: string): Promise<SharedRemoveResult> {
445
+ // Read before the removal, which forgets both the record and the live digest.
446
+ const pulled = this.pulledDigest(name)
447
+ const removed = await this.own.extensions.remove(name)
448
+ if (!removed.ok) return removed
449
+ const folder = join(this.dir, name)
450
+ if (!existsSync(folder)) return { ok: true, name, folder: 'none' }
451
+ if (pulled !== undefined && digestFolder(folder) === pulled) {
452
+ rmSync(folder, { recursive: true, force: true })
453
+ return { ok: true, name, folder: 'deleted' }
454
+ }
455
+ const why = pulled === undefined ? "is this app's own plugin" : 'was changed after the pull'
456
+ return {
457
+ ok: true,
458
+ name,
459
+ folder: 'kept',
460
+ note: `plugins/${name} ${why}, so it stays and the app starts it again at its next start; delete the folder to drop it for good`,
461
+ }
462
+ }
463
+
464
+ /** What `blend.yaml` remembers about one pulled plugin now. */
465
+ private recorded(name: string): PulledRecord | undefined {
466
+ const file = join(this.own.appInstance.root, 'blend.yaml')
467
+ return existsSync(file) ? pulledRecords(readFileSync(file, 'utf8'))[name] : undefined
468
+ }
469
+
470
+ /** Fetch the remembered plugins whose folder is gone, exactly as recorded: other bytes are refused, and the record stays for the person to decide. */
471
+ private get places(): NativePlaces {
472
+ return { root: this.own.appInstance.root, home: this.own.appInstance.home }
473
+ }
474
+
475
+ /** Remember the native package an installed plugin brought; one it no longer brings (an update) goes. The result's `native` field. */
476
+ private keepNative(
477
+ name: string,
478
+ native: NativePackage | undefined,
479
+ before: NativePackage | undefined,
480
+ action: NativeAction | undefined,
481
+ ): Pick<Extract<PullResult, { ok: true }>, 'native'> {
482
+ if (
483
+ before !== undefined &&
484
+ (native === undefined ||
485
+ before.version !== native.version ||
486
+ before.package !== native.package)
487
+ )
488
+ this.dropNative(name)
489
+ if (native === undefined || action === undefined) return {}
490
+ this.natives.set(name, native)
491
+ return {
492
+ native: { package: native.package, version: native.version, size: native.size, action },
493
+ }
494
+ }
495
+
496
+ /** Take away the native package a removed plugin brought, unless another installed plugin brought the same one. */
497
+ private dropNative(name: string): void {
498
+ const native = this.natives.get(name)
499
+ if (native === undefined) return
500
+ this.natives.delete(name)
501
+ const shared = [...this.natives.values()].some(
502
+ (other) => other.package === native.package && other.version === native.version,
503
+ )
504
+ if (!shared) releaseNative(native, this.places)
505
+ }
506
+
507
+ /** A pulled plugin that is here again links its native package again: an `npm install` puts the placeholder back in its place. */
508
+ private async relinkNative(name: string): Promise<void> {
509
+ let manifest: Record<string, unknown>
510
+ try {
511
+ manifest = JSON.parse(readFileSync(join(this.dir, name, 'package.json'), 'utf8')) as Record<
512
+ string,
513
+ unknown
514
+ >
515
+ } catch {
516
+ return
517
+ }
518
+ const declared = nativesOf(manifest)
519
+ const native = 'natives' in declared ? nativeFor(declared.natives) : undefined
520
+ if (native === undefined) return
521
+ try {
522
+ await ensureNative(native, this.places, this.nativeWork)
523
+ this.natives.set(name, native)
524
+ } catch (cause) {
525
+ console.warn(
526
+ `plugin-share: ${name}'s ${native.package} was not installed again: ${reasonOf(cause)}`,
527
+ )
528
+ }
529
+ }
530
+
531
+ private async restore(): Promise<readonly RestoreOutcome[]> {
532
+ const file = join(this.own.appInstance.root, 'blend.yaml')
533
+ if (!existsSync(file)) return []
534
+ const outcomes: RestoreOutcome[] = []
535
+ for (const [name, record] of Object.entries(pulledRecords(readFileSync(file, 'utf8')))) {
536
+ if (existsSync(join(this.dir, name))) {
537
+ await this.relinkNative(name)
538
+ continue
539
+ }
540
+ const result = await this.pullNow(
541
+ `${record.source}@sha256:${record.digest}`,
542
+ record.integrity,
543
+ )
544
+ outcomes.push(
545
+ result.ok
546
+ ? { name, ok: true }
547
+ : { name, ok: false, reason: result.reason, next: result.next },
548
+ )
549
+ if (!result.ok)
550
+ console.warn(
551
+ `plugin-share: ${name} was not fetched again: ${result.reason}. ${result.next}.`,
552
+ )
553
+ }
554
+ return outcomes
555
+ }
556
+
557
+ private get packages(): string {
558
+ return join(this.own.appInstance.home, 'plugin-packages')
559
+ }
560
+
561
+ private async planNow(
562
+ name: string,
563
+ options: PublishOptions,
564
+ ): Promise<PublishPlan | PublishRefused> {
565
+ const source = join(this.dir, name)
566
+ if (!NAME.test(name) || !existsSync(source))
567
+ return publishRefused(
568
+ `this app has no plugin "${name}" in plugins/`,
569
+ 'name a folder of plugins/',
570
+ )
571
+ try {
572
+ const { host } = this.ports
573
+ const owner = options.owner ?? host.login()
574
+ const repo = name
575
+ const description = `The ${name} Cordis plugin.`
576
+ const license = options.license ?? DEFAULT_LICENSE
577
+ if (!LICENSE_ID.test(license))
578
+ return publishRefused(
579
+ `"${license}" is not a license id`,
580
+ 'write one such as MIT or Apache-2.0',
581
+ )
582
+ const release = { owner, repo, license }
583
+ const existing = host.repository(owner, repo)
584
+ let packaged = await packagePlugin(source, this.packages, name, description, { release })
585
+ const released =
586
+ existing !== undefined && host.releaseExists(owner, repo, `v${packaged.version}`)
587
+ ? packaged.version
588
+ : undefined
589
+ if (released !== undefined)
590
+ packaged = await packagePlugin(source, this.packages, name, description, {
591
+ release,
592
+ version: bumpVersion(released, 'patch'),
593
+ })
594
+ const secrets = findSecrets(
595
+ readTarball(packFolder(packaged.dir).tarball).map((file) => ({
596
+ path: file.path,
597
+ text: Buffer.from(file.content).toString('utf8'),
598
+ })),
599
+ )
600
+ if (secrets.length > 0) {
601
+ return publishRefused(
602
+ `the secret check found ${String(secrets.length)} possible secret(s) in ${secrets.map((secret) => secret.path).join(', ')}; nothing was sent`,
603
+ "take them out of the plugin and read them from the app's settings",
604
+ )
605
+ }
606
+ return {
607
+ owner,
608
+ repo,
609
+ version: packaged.version,
610
+ visibility: 'public',
611
+ license,
612
+ createsRepository: existing === undefined,
613
+ ...(released === undefined ? {} : { released }),
614
+ files: packaged.files,
615
+ integrity: packaged.integrity,
616
+ digest: packaged.digest,
617
+ pullLine: pullLineOf(owner, repo, packaged.version, packaged.digest),
618
+ }
619
+ } catch (cause) {
620
+ return publishRefused(reasonOf(cause), 'fix it, or sign in with gh; nothing was sent')
621
+ }
622
+ }
623
+
624
+ private async pullNow(input: string, expectIntegrity?: string): Promise<PullResult> {
625
+ const { home, root } = this.own.appInstance
626
+ let read: ReturnType<typeof readSource>
627
+ try {
628
+ read = readSource(input, root)
629
+ } catch (cause) {
630
+ return refuse(
631
+ 'source',
632
+ reasonOf(cause),
633
+ `write ${SOURCE_FORMS}, with @sha256:<digest> at the end to name the content`,
634
+ )
635
+ }
636
+ mkdirSync(home, { recursive: true })
637
+ const scratch = mkdtempSync(join(home, 'plugin-pull-'))
638
+ try {
639
+ let pulled: Awaited<ReturnType<typeof pullPlugin>>
640
+ try {
641
+ pulled = await pullPlugin(
642
+ read.source,
643
+ {
644
+ store: new PluginStore(scratch),
645
+ releases: this.releases,
646
+ download: this.download,
647
+ },
648
+ expectIntegrity === undefined ? {} : { expectIntegrity },
649
+ )
650
+ } catch (cause) {
651
+ return refuse(
652
+ 'fetch',
653
+ reasonOf(cause),
654
+ 'check the source with the person who released it; nothing was installed',
655
+ )
656
+ }
657
+ const files: PluginFile[] = readTarball(readFileSync(pulled.stored.path)).map(
658
+ ({ path, content }) => ({ path, bytes: content, kind: 'file' }),
659
+ )
660
+ const refused = pullRefusal(pulled.manifest, files, {
661
+ digest: read.digest,
662
+ nameFits: (name) => NAME.test(name),
663
+ hasService: (service) => this.own.get(service as never) !== undefined,
664
+ })
665
+ if (refused !== undefined) return refused
666
+ const declared = nativesOf(pulled.manifest)
667
+ return await this.install(
668
+ pulled.stored.name,
669
+ pulled.stored.version,
670
+ pulled.stored.integrity,
671
+ files,
672
+ recordedSource(read.source, pulled.stored.version),
673
+ 'natives' in declared ? nativeFor(declared.natives) : undefined,
674
+ )
675
+ } finally {
676
+ rmSync(scratch, { recursive: true, force: true })
677
+ }
678
+ }
679
+
680
+ /** Put the files in `plugins/<name>/` and install them; whatever does not end running takes its folder with it. */
681
+ private async install(
682
+ name: string,
683
+ version: string,
684
+ integrity: string,
685
+ files: readonly PluginFile[],
686
+ source: string | undefined,
687
+ native: NativePackage | undefined,
688
+ ): Promise<PullResult> {
689
+ const target = join(this.dir, name)
690
+ const incoming = join(this.dir, `.pulling-${name}`)
691
+ rmSync(incoming, { recursive: true, force: true })
692
+ try {
693
+ for (const file of files) {
694
+ const path = join(incoming, ...file.path.split('/'))
695
+ mkdirSync(dirname(path), { recursive: true })
696
+ writeFileSync(path, file.bytes)
697
+ }
698
+ const digest = digestFolder(incoming)
699
+ // The folder may be there already: the same bytes are already pulled, anything else is someone's work.
700
+ const wrote = !existsSync(target)
701
+ const before = this.recorded(name)
702
+ const held = wrote ? undefined : digestFolder(target)
703
+ if (held !== undefined && held !== digest) {
704
+ const holder = before === undefined ? 'made in this app' : `pulled from ${before.source}`
705
+ // Only an untouched pulled copy goes with `plugin remove`; anything else is someone's work, which the person moves themselves.
706
+ const next =
707
+ before !== undefined && held === before.digest
708
+ ? `keep it, or remove it (npm run acryl -- plugin remove ${name}) and pull again`
709
+ : `keep it, or move plugins/${name} out of plugins/ and pull again`
710
+ return refuse(
711
+ 'folder-exists',
712
+ `plugins/${name} holds a different copy of this plugin, ${holder}`,
713
+ next,
714
+ )
715
+ }
716
+ const liveBefore = this.live.get(name)
717
+ this.live.set(name, digest)
718
+ if (wrote) renameSync(incoming, target)
719
+ // Remembered as the folder appears, before it is installed, so whoever sees the folder can tell it is these released bytes (the frame then does
720
+ // not load the app again for a plugin the app installs live); a pull that does not end running puts back what was remembered before.
721
+ const remembered = source !== undefined && this.remember(name, { source, integrity, digest })
722
+ // Installed before the plugin starts, so the plugin finds it; an install that does not end running takes back only what it added.
723
+ let nativeAction: NativeAction | undefined
724
+ const nativeBefore = this.natives.get(name)
725
+ const undo = () => {
726
+ if (native !== undefined && (nativeAction === 'downloaded' || nativeAction === 'linked'))
727
+ releaseNative(native, this.places, nativeAction === 'linked')
728
+ if (wrote) rmSync(target, { recursive: true, force: true })
729
+ if (remembered) this.remember(name, before)
730
+ if (liveBefore === undefined) this.live.delete(name)
731
+ else this.live.set(name, liveBefore)
732
+ }
733
+ if (native !== undefined) {
734
+ try {
735
+ nativeAction = await ensureNative(native, this.places, this.nativeWork)
736
+ } catch (cause) {
737
+ undo()
738
+ return refuse(
739
+ 'native',
740
+ `${native.package}@${native.version} (${Math.round(native.size / 1e6)} MB) could not be installed: ${reasonOf(cause)}`,
741
+ 'check the internet connection and pull again; the plugin was not installed',
742
+ )
743
+ }
744
+ }
745
+ let result: Awaited<ReturnType<Context['extensions']['install']>>
746
+ try {
747
+ result = await this.own.extensions.install(target)
748
+ } catch (cause) {
749
+ undo()
750
+ return refuse(
751
+ 'install',
752
+ reasonOf(cause),
753
+ 'this app does not install plugins while it runs like this',
754
+ )
755
+ }
756
+ if (!result.ok) {
757
+ undo()
758
+ return refuse('install', result.errors.join('; '), result.next)
759
+ }
760
+ if (result.state === 'pending') {
761
+ await this.own.extensions.remove(name)
762
+ undo()
763
+ return missingServices(result.missing)
764
+ }
765
+ return {
766
+ ok: true,
767
+ name,
768
+ version,
769
+ integrity,
770
+ digest,
771
+ action: result.action,
772
+ state: result.state,
773
+ remembered,
774
+ ...this.keepNative(name, native, nativeBefore, nativeAction),
775
+ }
776
+ } finally {
777
+ rmSync(incoming, { recursive: true, force: true })
778
+ }
779
+ }
780
+ }
781
+
782
+ export const pluginShare = {
783
+ name: 'plugin-share',
784
+ inject: ['extensions', 'appInstance'],
785
+ apply(ctx: Context, config: PluginShareConfig) {
786
+ // A pull runs a stranger's code and a publish leaves the machine: development only. The templates' src/app.ts leaves the row out in production; an
787
+ // app whose src/app.ts is older than that line is covered here.
788
+ if (process.env.NODE_ENV === 'production') return
789
+ new PluginShare(ctx, config ?? {})
790
+ },
791
+ }