@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.
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Publishing a plugin: what a person is asked to say yes to, and the comparison that makes the yes mean exactly that. Pure; the service does the I/O.
3
+ */
4
+ import type { PublishGitPort, RepositoryHostPort } from '@acryldev/plugin-hub-core';
5
+ /** Everything that leaves the machine, named before anything does. */
6
+ export interface PublishPlan {
7
+ readonly owner: string;
8
+ readonly repo: string;
9
+ readonly version: string;
10
+ readonly visibility: 'public';
11
+ readonly license: string;
12
+ /** The repository does not exist yet: publishing creates it. */
13
+ readonly createsRepository: boolean;
14
+ /** The version already released there; the plan then releases the next patch. */
15
+ readonly released?: string;
16
+ readonly files: readonly string[];
17
+ /** The sha512 of the release file. */
18
+ readonly integrity: string;
19
+ /** The sha256 of the plugin's content. */
20
+ readonly digest: string;
21
+ /** What a friend runs to get exactly these bytes. */
22
+ readonly pullLine: string;
23
+ }
24
+ export interface PublishRefused {
25
+ readonly ok: false;
26
+ readonly reason: string;
27
+ readonly next: string;
28
+ }
29
+ export type PublishResult = {
30
+ readonly ok: true;
31
+ readonly url: string;
32
+ readonly releaseUrl: string;
33
+ readonly version: string;
34
+ readonly integrity: string;
35
+ readonly digest: string;
36
+ readonly pullLine: string;
37
+ } | PublishRefused;
38
+ export interface PublishOptions {
39
+ /** The account or organization; the signed-in one when absent. */
40
+ readonly owner?: string;
41
+ /** The license the plugin is offered under, as an SPDX id; MIT when absent. The plan shows it before the person says yes. */
42
+ readonly license?: string;
43
+ }
44
+ /** Where a publish goes through: the person's own `gh` and `git`. A test passes stand-ins, so no test publishes. */
45
+ export interface PublishPorts {
46
+ readonly host: RepositoryHostPort;
47
+ readonly git: PublishGitPort;
48
+ }
49
+ /** The line a friend copies: it names the bytes, so the check comes for free. */
50
+ export declare const pullLineOf: (owner: string, repo: string, version: string, digest: string) => string;
51
+ /**
52
+ * 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.
53
+ * 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.
54
+ */
55
+ export declare function samePlan(a: PublishPlan, b: PublishPlan): boolean;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * What decides whether a pulled plugin may enter this app. Pure, over the files of the package: nothing here touches a disk or runs the plugin,
3
+ * so a refusal has nothing to undo (Clean Architecture: policy free of I/O).
4
+ */
5
+ import { type PluginFile } from '@acryldev/blends-core';
6
+ export type Refusal = 'source' | 'fetch' | 'name' | 'digest' | 'portability' | 'dependencies'
7
+ /** Its `acrylblends.native` list (native.ts) cannot be used. */
8
+ | 'native' | 'entry' | 'inject' | 'missing-service' | 'folder-exists' | 'install'
9
+ /** A list of sources that cannot be read, or holds a line that is not one source. */
10
+ | 'list';
11
+ export interface PullRefused {
12
+ readonly ok: false;
13
+ readonly refusal: Refusal;
14
+ readonly reason: string;
15
+ /** What the person can do about it. */
16
+ readonly next: string;
17
+ }
18
+ export declare const refuse: (refusal: Refusal, reason: string, next: string) => PullRefused;
19
+ /** The source a person wrote, split into where it comes from and the content digest it names. @throws when the digest is malformed. */
20
+ export declare function splitDigest(input: string): {
21
+ readonly source: string;
22
+ readonly digest?: string;
23
+ };
24
+ export interface PullContext {
25
+ /** The content digest the source names. */
26
+ readonly digest?: string | undefined;
27
+ /** Whether the extensions folder can hold a plugin of this name. */
28
+ readonly nameFits: (name: string) => boolean;
29
+ /** Whether this app has the service right now. */
30
+ readonly hasService: (name: string) => boolean;
31
+ }
32
+ /** The first reason this package may not enter the app, or undefined. */
33
+ export declare function pullRefusal(manifest: Readonly<Record<string, unknown>>, files: readonly PluginFile[], context: PullContext): PullRefused | undefined;
34
+ export declare const missingServices: (missing: readonly string[]) => PullRefused;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * A group's list of plugins: one source per line, as each person sends it (`github:<owner>/<repo>@<version>@sha256:<digest>`, or the whole line
3
+ * `plugin publish` prints). The list is text a person or a group keeps (a file in the app, a gist, a file in a repository), so reading it is
4
+ * forgiving about comments, blank lines and the pasted command, and strict about anything else: a line that is not one source is named, not guessed.
5
+ */
6
+ /** A list is a few lines of text: anything larger is not a list of plugins. */
7
+ export declare const LIST_MAX_BYTES: number;
8
+ /** More sources than a group has people is a mistake, not a workshop. */
9
+ export declare const LIST_MAX_SOURCES = 100;
10
+ export interface PullListLine {
11
+ /** Its line in the list, from 1, so a problem is easy to find. */
12
+ readonly line: number;
13
+ readonly source: string;
14
+ }
15
+ export interface ParsedPullList {
16
+ /** The sources in their order, each once. */
17
+ readonly sources: readonly PullListLine[];
18
+ /** Lines that are not one source, each with what is wrong. */
19
+ readonly problems: readonly string[];
20
+ }
21
+ /** The sources of a list, in order and without repeats, and the lines that are not a source. */
22
+ export declare function parsePullList(text: string): ParsedPullList;
23
+ /** Where a list is read from: an https address, or a file (relative to the app folder). */
24
+ export type PullListLocation = {
25
+ readonly kind: 'address';
26
+ readonly url: string;
27
+ } | {
28
+ readonly kind: 'file';
29
+ readonly path: string;
30
+ };
31
+ /** @returns undefined for something that is neither (an http: address, a github: source): the caller names what a list may be. */
32
+ export declare function pullListLocation(from: string): PullListLocation | undefined;
@@ -0,0 +1,16 @@
1
+ export declare const ROW = "plugin-share";
2
+ export interface PulledRecord {
3
+ /** `github:<owner>/<repo>@<version>` or an https address: something another machine can fetch. */
4
+ readonly source: string;
5
+ /** The sha512 of the release file. */
6
+ readonly integrity: string;
7
+ /** The sha256 of the plugin's content. */
8
+ readonly digest: string;
9
+ }
10
+ /** The plugins this definition remembers pulling. */
11
+ export declare function pulledRecords(text: string): Readonly<Record<string, PulledRecord>>;
12
+ /**
13
+ * The definition with one plugin's record written, or taken out when `record` is undefined. Unchanged when it has no `plugin-share` row: an app
14
+ * composed without the row has nowhere to remember.
15
+ */
16
+ export declare function withPulledRecord(text: string, name: string, record: PulledRecord | undefined): string;
@@ -0,0 +1,2 @@
1
+ declare const _default: import("tsdown").UserConfig;
2
+ export default _default;
package/native.ts ADDED
@@ -0,0 +1,290 @@
1
+ /**
2
+ * 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
3
+ * Office preview plugin is the first: DSH's LibreOffice engine, 150 to 190 MB per OS, which the frame does not install (frame/packages.json `omit`).
4
+ *
5
+ * A plugin's package.json names them, one entry per OS and CPU, each pinned by npm's sha512:
6
+ *
7
+ * "@acryldev/blends": { "native": [
8
+ * { "package": "@deepseek-ai/libreoffice-kit-darwin-arm64", "version": "0.1.5", "os": "darwin", "cpu": "arm64",
9
+ * "integrity": "sha512-...", "size": 153171456 } ] }
10
+ *
11
+ * The pull reads the list (the policy below is pure), downloads only this computer's entry from the npm registry, checks its sha512, unpacks it into
12
+ * the app's home (`<home>/native/<package>@<version>`, so an `npm install` cannot prune it) and links `node_modules/<package>` to it, where the package
13
+ * that needs it resolves it. Only a missing package or the empty placeholder (`@acryldev/absent`) is replaced; a real copy npm installed stays.
14
+ * Removing the plugin takes the link and the download away; an app's start links again what an `npm install` unlinked.
15
+ */
16
+ import { spawn } from 'node:child_process'
17
+ import { createHash } from 'node:crypto'
18
+ import {
19
+ createReadStream,
20
+ createWriteStream,
21
+ existsSync,
22
+ lstatSync,
23
+ mkdirSync,
24
+ mkdtempSync,
25
+ readFileSync,
26
+ realpathSync,
27
+ renameSync,
28
+ rmSync,
29
+ symlinkSync,
30
+ unlinkSync,
31
+ writeFileSync,
32
+ } from 'node:fs'
33
+ import { dirname, join } from 'node:path'
34
+ import { Readable } from 'node:stream'
35
+ import { pipeline } from 'node:stream/promises'
36
+
37
+ /** Where a native package is downloaded from: the npm registry, and nothing else. */
38
+ export const NATIVE_REGISTRY = 'https://registry.npmjs.org'
39
+
40
+ /** The most a plugin's native packages may unpack to, all of its entries for one computer together. */
41
+ export const NATIVE_MAX_BYTES = 1_000_000_000
42
+
43
+ /** The empty package the frame installs in place of an omitted one (frame/packages.json `omit.placeholder`). */
44
+ export const PLACEHOLDER = '@acryldev/absent'
45
+
46
+ /** The file written last into an unpacked native package: without it the folder is an interrupted download. */
47
+ const COMPLETE = '.acrylblends-native-complete'
48
+
49
+ export type NativeOs = 'darwin' | 'linux' | 'win32'
50
+ export type NativeCpu = 'arm64' | 'x64'
51
+
52
+ export interface NativePackage {
53
+ /** The npm package, as the package that needs it resolves it. */
54
+ readonly package: string
55
+ /** Its exact version. */
56
+ readonly version: string
57
+ readonly os: NativeOs
58
+ /** Absent: any CPU of that OS (a WebAssembly build). */
59
+ readonly cpu?: NativeCpu
60
+ /** npm's `dist.integrity` of the tarball. */
61
+ readonly integrity: string
62
+ /** npm's `dist.unpackedSize`, in bytes: what a person is told before it is downloaded. */
63
+ readonly size: number
64
+ }
65
+
66
+ const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u
67
+ const EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u
68
+ const SHA512 = /^sha512-[A-Za-z0-9+/]{86}==$/u
69
+ const OSES: readonly string[] = ['darwin', 'linux', 'win32']
70
+ const CPUS: readonly string[] = ['arm64', 'x64']
71
+
72
+ const isObject = (value: unknown): value is Record<string, unknown> =>
73
+ typeof value === 'object' && value !== null && !Array.isArray(value)
74
+
75
+ /** The native packages a plugin's package.json declares (none without the field), or why the declaration cannot be used. */
76
+ export function nativesOf(
77
+ manifest: Readonly<Record<string, unknown>>,
78
+ ): { readonly natives: readonly NativePackage[] } | { readonly error: string } {
79
+ const section = manifest.acrylblends
80
+ if (section === undefined || (isObject(section) && section.native === undefined))
81
+ return { natives: [] }
82
+ if (!isObject(section) || !Array.isArray(section.native))
83
+ return { error: '"acrylblends.native" is not a list' }
84
+ const natives: NativePackage[] = []
85
+ for (const [index, entry] of section.native.entries()) {
86
+ const at = `acrylblends.native[${index}]`
87
+ if (!isObject(entry)) return { error: `${at} is not an object` }
88
+ const { package: name, version, os, cpu, integrity, size } = entry
89
+ if (typeof name !== 'string' || !NPM_NAME.test(name))
90
+ return { error: `${at}.package is not an npm package name` }
91
+ if (typeof version !== 'string' || !EXACT_VERSION.test(version))
92
+ return { error: `${at}.version is not an exact version` }
93
+ if (typeof os !== 'string' || !OSES.includes(os))
94
+ return { error: `${at}.os is not one of ${OSES.join(', ')}` }
95
+ if (cpu !== undefined && (typeof cpu !== 'string' || !CPUS.includes(cpu)))
96
+ return { error: `${at}.cpu is not one of ${CPUS.join(', ')}` }
97
+ if (typeof integrity !== 'string' || !SHA512.test(integrity))
98
+ return { error: `${at}.integrity is not npm's sha512 of the tarball` }
99
+ if (typeof size !== 'number' || !Number.isSafeInteger(size) || size <= 0)
100
+ return { error: `${at}.size is not a number of bytes` }
101
+ if (size > NATIVE_MAX_BYTES)
102
+ return {
103
+ error: `${at} unpacks to ${size} bytes, more than a plugin may bring (${NATIVE_MAX_BYTES})`,
104
+ }
105
+ natives.push({
106
+ package: name,
107
+ version,
108
+ os: os as NativeOs,
109
+ ...(cpu === undefined ? {} : { cpu: cpu as NativeCpu }),
110
+ integrity,
111
+ size,
112
+ })
113
+ }
114
+ return { natives }
115
+ }
116
+
117
+ /** The entry for this computer: its OS, and its CPU or any. Undefined when the plugin brings nothing for it. */
118
+ export function nativeFor(
119
+ natives: readonly NativePackage[],
120
+ platform: string = process.platform,
121
+ arch: string = process.arch,
122
+ ): NativePackage | undefined {
123
+ return (
124
+ natives.find((entry) => entry.os === platform && entry.cpu === arch) ??
125
+ natives.find((entry) => entry.os === platform && entry.cpu === undefined)
126
+ )
127
+ }
128
+
129
+ /** The tarball's address in the npm registry, the way npm names it. */
130
+ export function tarballUrl(native: Pick<NativePackage, 'package' | 'version'>): string {
131
+ const base = native.package.slice(native.package.lastIndexOf('/') + 1)
132
+ return `${NATIVE_REGISTRY}/${native.package}/-/${base}-${native.version}.tgz`
133
+ }
134
+
135
+ /** What a download and an unpack are, so a test can hand in local ones. */
136
+ export interface NativePorts {
137
+ /** Write the file at `url` to `file`. */
138
+ readonly download: (url: string, file: string) => Promise<void>
139
+ /** Unpack the `.tgz` at `file` into `dir`, without the archive's top folder (npm's `package/`) and with the files' modes. */
140
+ readonly unpack: (file: string, dir: string) => Promise<void>
141
+ }
142
+
143
+ /** The real ones: https from the npm registry, and the system's tar (macOS, Linux, and Windows 10 and later carry one), which keeps execute bits. */
144
+ export function nativePorts(): NativePorts {
145
+ return {
146
+ async download(url, file) {
147
+ if (!url.startsWith(`${NATIVE_REGISTRY}/`))
148
+ throw new Error(`${url} is not in the npm registry`)
149
+ const response = await fetch(url)
150
+ if (!response.ok || response.body === null)
151
+ throw new Error(`the npm registry answered ${response.status} for ${url}`)
152
+ await pipeline(Readable.fromWeb(response.body as never), createWriteStream(file))
153
+ },
154
+ unpack: (file, dir) =>
155
+ new Promise((done, fail) => {
156
+ const tar = spawn('tar', ['-xzf', file, '-C', dir, '--strip-components=1'], {
157
+ stdio: ['ignore', 'ignore', 'pipe'],
158
+ windowsHide: true,
159
+ })
160
+ let error = ''
161
+ tar.stderr.on('data', (chunk: Buffer) => {
162
+ error += chunk.toString()
163
+ })
164
+ tar.once('error', fail)
165
+ tar.once('exit', (code) =>
166
+ code === 0 ? done() : fail(new Error(`tar could not unpack ${file}: ${error.trim()}`)),
167
+ )
168
+ }),
169
+ }
170
+ }
171
+
172
+ /** Where the app keeps what it downloaded, and where it links it. */
173
+ export interface NativePlaces {
174
+ /** The app's folder, whose `node_modules` the link goes into. */
175
+ readonly root: string
176
+ /** The app's home, which keeps the downloads. */
177
+ readonly home: string
178
+ }
179
+
180
+ /** The folder a native package is unpacked into. */
181
+ export function nativeStore(
182
+ home: string,
183
+ native: Pick<NativePackage, 'package' | 'version'>,
184
+ ): string {
185
+ return join(home, 'native', `${native.package.replace('/', '+')}@${native.version}`)
186
+ }
187
+
188
+ const linkOf = (root: string, native: Pick<NativePackage, 'package'>) =>
189
+ join(root, 'node_modules', ...native.package.split('/'))
190
+
191
+ /** What is at the package's place in node_modules: our link, nothing, something we may replace, or a real package someone installed. */
192
+ function placeState(link: string, store: string): 'ours' | 'missing' | 'replaceable' | 'foreign' {
193
+ let stat: ReturnType<typeof lstatSync>
194
+ try {
195
+ stat = lstatSync(link)
196
+ } catch {
197
+ return 'missing'
198
+ }
199
+ if (stat.isSymbolicLink()) {
200
+ let target: string
201
+ try {
202
+ target = realpathSync(link)
203
+ } catch {
204
+ return 'replaceable'
205
+ }
206
+ if (existsSync(store) && target === realpathSync(store)) return 'ours'
207
+ // Another version this app downloaded (the plugin was updated): replaced, never mistaken for a copy npm installed.
208
+ if (existsSync(dirname(store)) && dirname(target) === realpathSync(dirname(store)))
209
+ return 'replaceable'
210
+ }
211
+ let name: unknown
212
+ try {
213
+ name = (JSON.parse(readFileSync(join(link, 'package.json'), 'utf8')) as { name?: unknown }).name
214
+ } catch {
215
+ return stat.isSymbolicLink() ? 'replaceable' : 'foreign'
216
+ }
217
+ return name === PLACEHOLDER ? 'replaceable' : 'foreign'
218
+ }
219
+
220
+ const sha512Of = async (file: string): Promise<string> => {
221
+ const hash = createHash('sha512')
222
+ await pipeline(createReadStream(file), hash)
223
+ return `sha512-${hash.digest('base64')}`
224
+ }
225
+
226
+ /** Download, check and unpack into the store; the store appears whole or not at all. */
227
+ async function fetchInto(native: NativePackage, store: string, ports: NativePorts): Promise<void> {
228
+ mkdirSync(dirname(store), { recursive: true })
229
+ const incoming = mkdtempSync(join(dirname(store), '.incoming-'))
230
+ try {
231
+ const file = join(incoming, 'package.tgz')
232
+ await ports.download(tarballUrl(native), file)
233
+ const integrity = await sha512Of(file)
234
+ if (integrity !== native.integrity)
235
+ throw new Error(
236
+ `${native.package}@${native.version} from npm is not the file the plugin names (its sha512 differs)`,
237
+ )
238
+ const unpacked = join(incoming, 'package')
239
+ mkdirSync(unpacked)
240
+ await ports.unpack(file, unpacked)
241
+ const manifest = JSON.parse(readFileSync(join(unpacked, 'package.json'), 'utf8')) as {
242
+ name?: unknown
243
+ version?: unknown
244
+ }
245
+ if (manifest.name !== native.package || manifest.version !== native.version)
246
+ throw new Error(
247
+ `the tarball holds ${String(manifest.name)}@${String(manifest.version)}, not ${native.package}@${native.version}`,
248
+ )
249
+ writeFileSync(join(unpacked, COMPLETE), '')
250
+ rmSync(store, { recursive: true, force: true })
251
+ renameSync(unpacked, store)
252
+ } finally {
253
+ rmSync(incoming, { recursive: true, force: true })
254
+ }
255
+ }
256
+
257
+ /** What `ensureNative` did: downloaded it, only linked a download it had, found it linked, or left a real copy npm installed. */
258
+ export type NativeAction = 'downloaded' | 'linked' | 'unchanged' | 'present'
259
+
260
+ /** Make the native package resolvable from the app: download it unless the store has it, and link it. @throws when the download fails or differs. */
261
+ export async function ensureNative(
262
+ native: NativePackage,
263
+ places: NativePlaces,
264
+ ports: NativePorts = nativePorts(),
265
+ ): Promise<NativeAction> {
266
+ const store = nativeStore(places.home, native)
267
+ const link = linkOf(places.root, native)
268
+ const state = placeState(link, store)
269
+ if (state === 'foreign') return 'present'
270
+ const complete = existsSync(join(store, COMPLETE))
271
+ if (state === 'ours' && complete) return 'unchanged'
272
+ if (!complete) await fetchInto(native, store, ports)
273
+ rmSync(link, { recursive: true, force: true })
274
+ mkdirSync(dirname(link), { recursive: true })
275
+ // A junction on Windows: a directory symlink there needs a privilege a person may not have.
276
+ symlinkSync(store, link, process.platform === 'win32' ? 'junction' : 'dir')
277
+ return complete ? 'linked' : 'downloaded'
278
+ }
279
+
280
+ /** Take the link away and, unless `keepDownload`, the download. A real copy npm installed is never touched. */
281
+ export function releaseNative(
282
+ native: Pick<NativePackage, 'package' | 'version'>,
283
+ places: NativePlaces,
284
+ keepDownload = false,
285
+ ): void {
286
+ const store = nativeStore(places.home, native)
287
+ const link = linkOf(places.root, native)
288
+ if (placeState(link, store) === 'ours') unlinkSync(link)
289
+ if (!keepDownload) rmSync(store, { recursive: true, force: true })
290
+ }
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@acryldev/plugin-share",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Share plugins between people. Pull one someone released into the running app: fetched without running anything, checked by digest and for every OS, then installed live. Publish one, only as a plan a person confirmed.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/acryldev/acryl.git",
9
+ "directory": "plugins/plugin-share"
10
+ },
11
+ "homepage": "https://github.com/acryldev/acryl/tree/main/plugins/plugin-share#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/acryldev/acryl/issues"
14
+ },
15
+ "type": "module",
16
+ "engines": {
17
+ "node": "^22.19.0 || >=24.0.0"
18
+ },
19
+ "main": "./lib/index.js",
20
+ "types": "./lib/types/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./lib/types/index.d.ts",
24
+ "default": "./lib/index.js"
25
+ },
26
+ "./package": {
27
+ "types": "./lib/types/package.d.ts",
28
+ "default": "./lib/package.js"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "dependencies": {
33
+ "@acryldev/extensions": "0.1.1",
34
+ "@acryldev/instance": "0.1.2",
35
+ "@acryldev/manifest": "0.1.1",
36
+ "@acryldev/app-persistence": "^0.1.5",
37
+ "@acryldev/blends-core": "^0.6.0",
38
+ "@acryldev/plugin-hub-core": "^0.2.3",
39
+ "yaml": "2.9.0"
40
+ },
41
+ "peerDependencies": {
42
+ "@deepseek-ai/cordis": "^4.0.2"
43
+ },
44
+ "devDependencies": {
45
+ "@deepseek-ai/cordis": "4.0.4",
46
+ "@types/node": "^22.20.0",
47
+ "@acryldev/router": "0.1.0",
48
+ "tsdown": "0.22.2",
49
+ "typescript": "6.0.3"
50
+ },
51
+ "scripts": {
52
+ "build": "tsdown && tsc -p tsconfig.json --emitDeclarationOnly"
53
+ }
6
54
  }
package/package.ts ADDED
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Turning a plugin folder into what other people's apps can pull: a package folder and its release tarball, with the same bytes on every OS. The
3
+ * hub owns the tarball and the contract, blends-core what "portable" and "digest" mean; this module only decides what goes in.
4
+ */
5
+ import {
6
+ cpSync,
7
+ existsSync,
8
+ mkdirSync,
9
+ readdirSync,
10
+ readFileSync,
11
+ rmSync,
12
+ writeFileSync,
13
+ } from 'node:fs'
14
+ import { extname, join } from 'node:path'
15
+ import { digestFiles, pluginFiles, portabilityIssues } from '@acryldev/blends-core'
16
+ import { packFolder, readTarball, syncServiceContract } from '@acryldev/plugin-hub-core'
17
+
18
+ /** The package.json of a standalone plugin package: the host framework is a peer, never a second installed copy. */
19
+ export function packageManifest(
20
+ name: string,
21
+ description: string,
22
+ version = '0.1.0',
23
+ release?: PackageRelease,
24
+ ): Record<string, unknown> {
25
+ return {
26
+ name,
27
+ version,
28
+ description,
29
+ ...(release === undefined
30
+ ? {}
31
+ : {
32
+ license: release.license,
33
+ repository: {
34
+ type: 'git',
35
+ url: `git+https://github.com/${release.owner}/${release.repo}.git`,
36
+ },
37
+ }),
38
+ type: 'module',
39
+ exports: { '.': './index.ts', './package.json': './package.json' },
40
+ // No `files` list: a plugin's plugin.json, data and .js files go with it, and the packer's own skips (node_modules, .git) apply.
41
+ // ACRYL measured it: a host package listed under dependencies brings a second copy of the framework, and its services stop
42
+ // matching after a restart. A peer names the version and installs nothing.
43
+ peerDependencies: { '@deepseek-ai/cordis': '4.0.4' },
44
+ keywords: ['cordis', 'cordis-plugin', 'acrylblends'],
45
+ }
46
+ }
47
+
48
+ /** Where a package is going to be released: written in now, so what is planned is byte for byte what is released. */
49
+ export interface PackageRelease {
50
+ readonly owner: string
51
+ readonly repo: string
52
+ readonly license: string
53
+ }
54
+
55
+ export interface PackageOptions {
56
+ /** This version, instead of the one already packaged. */
57
+ readonly version?: string
58
+ readonly release?: PackageRelease
59
+ }
60
+
61
+ export interface PackagedPlugin {
62
+ readonly dir: string
63
+ readonly version: string
64
+ readonly files: readonly string[]
65
+ /** The release file, next to the package folder. */
66
+ readonly tarball: string
67
+ /** The tarball's sha512, as the registry lists it. */
68
+ readonly integrity: string
69
+ /** The sha256 of the plugin's content, which a source can name (`@sha256:<digest>`). */
70
+ readonly digest: string
71
+ }
72
+
73
+ /** Text whose line endings an editor or git on Windows may change: LF in the package, so those endings are not part of the plugin's identity. */
74
+ const TEXT = new Set([
75
+ '.ts',
76
+ '.mts',
77
+ '.cts',
78
+ '.tsx',
79
+ '.js',
80
+ '.mjs',
81
+ '.cjs',
82
+ '.jsx',
83
+ '.json',
84
+ '.md',
85
+ '.txt',
86
+ '.css',
87
+ '.html',
88
+ '.yml',
89
+ '.yaml',
90
+ '.svg',
91
+ ])
92
+
93
+ function withLineFeeds(dir: string): void {
94
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
95
+ const path = join(dir, entry.name)
96
+ if (entry.isDirectory()) withLineFeeds(path)
97
+ else if (entry.isFile() && TEXT.has(extname(entry.name).toLowerCase())) {
98
+ const text = readFileSync(path, 'utf8')
99
+ if (text.includes('\r\n')) writeFileSync(path, text.replaceAll('\r\n', '\n'))
100
+ }
101
+ }
102
+ }
103
+
104
+ /** What the hub's share would otherwise add on the way out, changing the bytes after they were planned. */
105
+ function markPublic(target: string): void {
106
+ const file = join(target, 'package.json')
107
+ const manifest = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>
108
+ writeFileSync(
109
+ file,
110
+ `${JSON.stringify({ ...manifest, acryl: { ...(manifest.acryl as object), visibility: 'public' } }, null, 2)}\n`,
111
+ )
112
+ }
113
+
114
+ function versionIn(target: string): string | undefined {
115
+ try {
116
+ const { version } = JSON.parse(readFileSync(join(target, 'package.json'), 'utf8')) as {
117
+ version?: unknown
118
+ }
119
+ return typeof version === 'string' ? version : undefined
120
+ } catch {
121
+ return undefined
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Package the plugin in `source` as `<packages>/<name>/` and `<packages>/<name>-<version>.tgz`. The person's folder is not touched. A version already
127
+ * packaged stays: a release is made once, and a person bumps it deliberately.
128
+ * @throws when the plugin would not work on every OS or its contract cannot be read; no package is left.
129
+ */
130
+ export async function packagePlugin(
131
+ source: string,
132
+ packages: string,
133
+ name: string,
134
+ description: string,
135
+ options: PackageOptions = {},
136
+ ): Promise<PackagedPlugin> {
137
+ const target = join(packages, name)
138
+ const version = options.version ?? versionIn(target)
139
+ rmSync(target, { recursive: true, force: true })
140
+ mkdirSync(packages, { recursive: true })
141
+ cpSync(source, target, { recursive: true, filter: (path) => !path.includes('node_modules') })
142
+ try {
143
+ writeFileSync(
144
+ join(target, 'package.json'),
145
+ `${JSON.stringify(packageManifest(name, description, version, options.release), null, 2)}\n`,
146
+ )
147
+ if (!existsSync(join(target, 'README.md'))) {
148
+ writeFileSync(
149
+ join(target, 'README.md'),
150
+ `# ${name}\n\n${description}\n\nA Cordis plugin. Once it is released, pull it into an ACRYLBLENDS app while that app runs (\`npm run dev\`): \`npm run acryl -- plugin pull github:<owner>/<repo>\`.\n`,
151
+ )
152
+ }
153
+ withLineFeeds(target)
154
+ const issues = portabilityIssues(pluginFiles(target))
155
+ if (issues.length > 0)
156
+ throw new Error(
157
+ `it would not work on every OS: ${issues.map((issue) => `${issue.path}: ${issue.reason}`).join('; ')}`,
158
+ )
159
+ // The contract other people's apps and the registry read: what the plugin needs and provides, from its code.
160
+ const contract = await syncServiceContract(target)
161
+ if (!contract.ok)
162
+ throw new Error(`its service contract cannot be read: ${contract.errors.join('; ')}`)
163
+ if (options.release !== undefined) markPublic(target)
164
+ const packed = packFolder(target)
165
+ const tarball = join(packages, packed.fileName)
166
+ writeFileSync(tarball, packed.tarball)
167
+ const digest = digestFiles(
168
+ readTarball(packed.tarball).map(({ path, content }) => ({
169
+ path,
170
+ bytes: content,
171
+ kind: 'file' as const,
172
+ })),
173
+ )
174
+ return {
175
+ dir: target,
176
+ version: packed.version,
177
+ files: packed.files,
178
+ tarball,
179
+ integrity: packed.integrity,
180
+ digest,
181
+ }
182
+ } catch (cause) {
183
+ rmSync(target, { recursive: true, force: true })
184
+ throw cause
185
+ }
186
+ }