@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 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../native.ts","../publish.ts","../pull-check.ts","../pull-list.ts","../pulled-records.ts","../index.ts"],"sourcesContent":["/**\n * 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\n * 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`).\n *\n * A plugin's package.json names them, one entry per OS and CPU, each pinned by npm's sha512:\n *\n * \"@acryldev/blends\": { \"native\": [\n * { \"package\": \"@deepseek-ai/libreoffice-kit-darwin-arm64\", \"version\": \"0.1.5\", \"os\": \"darwin\", \"cpu\": \"arm64\",\n * \"integrity\": \"sha512-...\", \"size\": 153171456 } ] }\n *\n * 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\n * 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\n * that needs it resolves it. Only a missing package or the empty placeholder (`@acryldev/absent`) is replaced; a real copy npm installed stays.\n * Removing the plugin takes the link and the download away; an app's start links again what an `npm install` unlinked.\n */\nimport { spawn } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport {\n createReadStream,\n createWriteStream,\n existsSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n symlinkSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\n\n/** Where a native package is downloaded from: the npm registry, and nothing else. */\nexport const NATIVE_REGISTRY = 'https://registry.npmjs.org'\n\n/** The most a plugin's native packages may unpack to, all of its entries for one computer together. */\nexport const NATIVE_MAX_BYTES = 1_000_000_000\n\n/** The empty package the frame installs in place of an omitted one (frame/packages.json `omit.placeholder`). */\nexport const PLACEHOLDER = '@acryldev/absent'\n\n/** The file written last into an unpacked native package: without it the folder is an interrupted download. */\nconst COMPLETE = '.acrylblends-native-complete'\n\nexport type NativeOs = 'darwin' | 'linux' | 'win32'\nexport type NativeCpu = 'arm64' | 'x64'\n\nexport interface NativePackage {\n /** The npm package, as the package that needs it resolves it. */\n readonly package: string\n /** Its exact version. */\n readonly version: string\n readonly os: NativeOs\n /** Absent: any CPU of that OS (a WebAssembly build). */\n readonly cpu?: NativeCpu\n /** npm's `dist.integrity` of the tarball. */\n readonly integrity: string\n /** npm's `dist.unpackedSize`, in bytes: what a person is told before it is downloaded. */\n readonly size: number\n}\n\nconst NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u\nconst EXACT_VERSION = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u\nconst SHA512 = /^sha512-[A-Za-z0-9+/]{86}==$/u\nconst OSES: readonly string[] = ['darwin', 'linux', 'win32']\nconst CPUS: readonly string[] = ['arm64', 'x64']\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** The native packages a plugin's package.json declares (none without the field), or why the declaration cannot be used. */\nexport function nativesOf(\n manifest: Readonly<Record<string, unknown>>,\n): { readonly natives: readonly NativePackage[] } | { readonly error: string } {\n const section = manifest.acrylblends\n if (section === undefined || (isObject(section) && section.native === undefined))\n return { natives: [] }\n if (!isObject(section) || !Array.isArray(section.native))\n return { error: '\"acrylblends.native\" is not a list' }\n const natives: NativePackage[] = []\n for (const [index, entry] of section.native.entries()) {\n const at = `acrylblends.native[${index}]`\n if (!isObject(entry)) return { error: `${at} is not an object` }\n const { package: name, version, os, cpu, integrity, size } = entry\n if (typeof name !== 'string' || !NPM_NAME.test(name))\n return { error: `${at}.package is not an npm package name` }\n if (typeof version !== 'string' || !EXACT_VERSION.test(version))\n return { error: `${at}.version is not an exact version` }\n if (typeof os !== 'string' || !OSES.includes(os))\n return { error: `${at}.os is not one of ${OSES.join(', ')}` }\n if (cpu !== undefined && (typeof cpu !== 'string' || !CPUS.includes(cpu)))\n return { error: `${at}.cpu is not one of ${CPUS.join(', ')}` }\n if (typeof integrity !== 'string' || !SHA512.test(integrity))\n return { error: `${at}.integrity is not npm's sha512 of the tarball` }\n if (typeof size !== 'number' || !Number.isSafeInteger(size) || size <= 0)\n return { error: `${at}.size is not a number of bytes` }\n if (size > NATIVE_MAX_BYTES)\n return {\n error: `${at} unpacks to ${size} bytes, more than a plugin may bring (${NATIVE_MAX_BYTES})`,\n }\n natives.push({\n package: name,\n version,\n os: os as NativeOs,\n ...(cpu === undefined ? {} : { cpu: cpu as NativeCpu }),\n integrity,\n size,\n })\n }\n return { natives }\n}\n\n/** The entry for this computer: its OS, and its CPU or any. Undefined when the plugin brings nothing for it. */\nexport function nativeFor(\n natives: readonly NativePackage[],\n platform: string = process.platform,\n arch: string = process.arch,\n): NativePackage | undefined {\n return (\n natives.find((entry) => entry.os === platform && entry.cpu === arch) ??\n natives.find((entry) => entry.os === platform && entry.cpu === undefined)\n )\n}\n\n/** The tarball's address in the npm registry, the way npm names it. */\nexport function tarballUrl(native: Pick<NativePackage, 'package' | 'version'>): string {\n const base = native.package.slice(native.package.lastIndexOf('/') + 1)\n return `${NATIVE_REGISTRY}/${native.package}/-/${base}-${native.version}.tgz`\n}\n\n/** What a download and an unpack are, so a test can hand in local ones. */\nexport interface NativePorts {\n /** Write the file at `url` to `file`. */\n readonly download: (url: string, file: string) => Promise<void>\n /** Unpack the `.tgz` at `file` into `dir`, without the archive's top folder (npm's `package/`) and with the files' modes. */\n readonly unpack: (file: string, dir: string) => Promise<void>\n}\n\n/** 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. */\nexport function nativePorts(): NativePorts {\n return {\n async download(url, file) {\n if (!url.startsWith(`${NATIVE_REGISTRY}/`))\n throw new Error(`${url} is not in the npm registry`)\n const response = await fetch(url)\n if (!response.ok || response.body === null)\n throw new Error(`the npm registry answered ${response.status} for ${url}`)\n await pipeline(Readable.fromWeb(response.body as never), createWriteStream(file))\n },\n unpack: (file, dir) =>\n new Promise((done, fail) => {\n const tar = spawn('tar', ['-xzf', file, '-C', dir, '--strip-components=1'], {\n stdio: ['ignore', 'ignore', 'pipe'],\n windowsHide: true,\n })\n let error = ''\n tar.stderr.on('data', (chunk: Buffer) => {\n error += chunk.toString()\n })\n tar.once('error', fail)\n tar.once('exit', (code) =>\n code === 0 ? done() : fail(new Error(`tar could not unpack ${file}: ${error.trim()}`)),\n )\n }),\n }\n}\n\n/** Where the app keeps what it downloaded, and where it links it. */\nexport interface NativePlaces {\n /** The app's folder, whose `node_modules` the link goes into. */\n readonly root: string\n /** The app's home, which keeps the downloads. */\n readonly home: string\n}\n\n/** The folder a native package is unpacked into. */\nexport function nativeStore(\n home: string,\n native: Pick<NativePackage, 'package' | 'version'>,\n): string {\n return join(home, 'native', `${native.package.replace('/', '+')}@${native.version}`)\n}\n\nconst linkOf = (root: string, native: Pick<NativePackage, 'package'>) =>\n join(root, 'node_modules', ...native.package.split('/'))\n\n/** What is at the package's place in node_modules: our link, nothing, something we may replace, or a real package someone installed. */\nfunction placeState(link: string, store: string): 'ours' | 'missing' | 'replaceable' | 'foreign' {\n let stat: ReturnType<typeof lstatSync>\n try {\n stat = lstatSync(link)\n } catch {\n return 'missing'\n }\n if (stat.isSymbolicLink()) {\n let target: string\n try {\n target = realpathSync(link)\n } catch {\n return 'replaceable'\n }\n if (existsSync(store) && target === realpathSync(store)) return 'ours'\n // Another version this app downloaded (the plugin was updated): replaced, never mistaken for a copy npm installed.\n if (existsSync(dirname(store)) && dirname(target) === realpathSync(dirname(store)))\n return 'replaceable'\n }\n let name: unknown\n try {\n name = (JSON.parse(readFileSync(join(link, 'package.json'), 'utf8')) as { name?: unknown }).name\n } catch {\n return stat.isSymbolicLink() ? 'replaceable' : 'foreign'\n }\n return name === PLACEHOLDER ? 'replaceable' : 'foreign'\n}\n\nconst sha512Of = async (file: string): Promise<string> => {\n const hash = createHash('sha512')\n await pipeline(createReadStream(file), hash)\n return `sha512-${hash.digest('base64')}`\n}\n\n/** Download, check and unpack into the store; the store appears whole or not at all. */\nasync function fetchInto(native: NativePackage, store: string, ports: NativePorts): Promise<void> {\n mkdirSync(dirname(store), { recursive: true })\n const incoming = mkdtempSync(join(dirname(store), '.incoming-'))\n try {\n const file = join(incoming, 'package.tgz')\n await ports.download(tarballUrl(native), file)\n const integrity = await sha512Of(file)\n if (integrity !== native.integrity)\n throw new Error(\n `${native.package}@${native.version} from npm is not the file the plugin names (its sha512 differs)`,\n )\n const unpacked = join(incoming, 'package')\n mkdirSync(unpacked)\n await ports.unpack(file, unpacked)\n const manifest = JSON.parse(readFileSync(join(unpacked, 'package.json'), 'utf8')) as {\n name?: unknown\n version?: unknown\n }\n if (manifest.name !== native.package || manifest.version !== native.version)\n throw new Error(\n `the tarball holds ${String(manifest.name)}@${String(manifest.version)}, not ${native.package}@${native.version}`,\n )\n writeFileSync(join(unpacked, COMPLETE), '')\n rmSync(store, { recursive: true, force: true })\n renameSync(unpacked, store)\n } finally {\n rmSync(incoming, { recursive: true, force: true })\n }\n}\n\n/** What `ensureNative` did: downloaded it, only linked a download it had, found it linked, or left a real copy npm installed. */\nexport type NativeAction = 'downloaded' | 'linked' | 'unchanged' | 'present'\n\n/** 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. */\nexport async function ensureNative(\n native: NativePackage,\n places: NativePlaces,\n ports: NativePorts = nativePorts(),\n): Promise<NativeAction> {\n const store = nativeStore(places.home, native)\n const link = linkOf(places.root, native)\n const state = placeState(link, store)\n if (state === 'foreign') return 'present'\n const complete = existsSync(join(store, COMPLETE))\n if (state === 'ours' && complete) return 'unchanged'\n if (!complete) await fetchInto(native, store, ports)\n rmSync(link, { recursive: true, force: true })\n mkdirSync(dirname(link), { recursive: true })\n // A junction on Windows: a directory symlink there needs a privilege a person may not have.\n symlinkSync(store, link, process.platform === 'win32' ? 'junction' : 'dir')\n return complete ? 'linked' : 'downloaded'\n}\n\n/** Take the link away and, unless `keepDownload`, the download. A real copy npm installed is never touched. */\nexport function releaseNative(\n native: Pick<NativePackage, 'package' | 'version'>,\n places: NativePlaces,\n keepDownload = false,\n): void {\n const store = nativeStore(places.home, native)\n const link = linkOf(places.root, native)\n if (placeState(link, store) === 'ours') unlinkSync(link)\n if (!keepDownload) rmSync(store, { recursive: true, force: true })\n}\n","/**\n * 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.\n */\nimport type { PublishGitPort, RepositoryHostPort } from '@acryldev/plugin-hub-core'\n\n/** Everything that leaves the machine, named before anything does. */\nexport interface PublishPlan {\n readonly owner: string\n readonly repo: string\n readonly version: string\n readonly visibility: 'public'\n readonly license: string\n /** The repository does not exist yet: publishing creates it. */\n readonly createsRepository: boolean\n /** The version already released there; the plan then releases the next patch. */\n readonly released?: string\n readonly files: readonly string[]\n /** The sha512 of the release file. */\n readonly integrity: string\n /** The sha256 of the plugin's content. */\n readonly digest: string\n /** What a friend runs to get exactly these bytes. */\n readonly pullLine: string\n}\n\nexport interface PublishRefused {\n readonly ok: false\n readonly reason: string\n readonly next: string\n}\n\nexport type PublishResult =\n | {\n readonly ok: true\n readonly url: string\n readonly releaseUrl: string\n readonly version: string\n readonly integrity: string\n readonly digest: string\n readonly pullLine: string\n }\n | PublishRefused\n\nexport interface PublishOptions {\n /** The account or organization; the signed-in one when absent. */\n readonly owner?: string\n /** The license the plugin is offered under, as an SPDX id; MIT when absent. The plan shows it before the person says yes. */\n readonly license?: string\n}\n\n/** Where a publish goes through: the person's own `gh` and `git`. A test passes stand-ins, so no test publishes. */\nexport interface PublishPorts {\n readonly host: RepositoryHostPort\n readonly git: PublishGitPort\n}\n\n/** The line a friend copies: it names the bytes, so the check comes for free. */\nexport const pullLineOf = (owner: string, repo: string, version: string, digest: string): string =>\n `npm run acryl -- plugin pull github:${owner}/${repo}@${version}@sha256:${digest}`\n\n/**\n * 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.\n * 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.\n */\nexport function samePlan(a: PublishPlan, b: PublishPlan): boolean {\n return (\n a.owner === b.owner &&\n a.repo === b.repo &&\n a.version === b.version &&\n a.visibility === b.visibility &&\n a.license === b.license &&\n a.createsRepository === b.createsRepository &&\n a.integrity === b.integrity &&\n a.digest === b.digest &&\n a.pullLine === b.pullLine &&\n a.files.length === b.files.length &&\n a.files.every((file, index) => file === b.files[index])\n )\n}\n","/**\n * 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,\n * so a refusal has nothing to undo (Clean Architecture: policy free of I/O).\n */\nimport { digestFiles, type PluginFile, portabilityIssues } from '@acryldev/blends-core'\nimport { hostInjectFromSource } from '@acryldev/plugin-hub-core'\nimport { nativesOf } from './native.ts'\n\nexport type Refusal =\n | 'source'\n | 'fetch'\n | 'name'\n | 'digest'\n | 'portability'\n | 'dependencies'\n /** Its `acrylblends.native` list (native.ts) cannot be used. */\n | 'native'\n | 'entry'\n | 'inject'\n | 'missing-service'\n | 'folder-exists'\n | 'install'\n /** A list of sources that cannot be read, or holds a line that is not one source. */\n | 'list'\n\nexport interface PullRefused {\n readonly ok: false\n readonly refusal: Refusal\n readonly reason: string\n /** What the person can do about it. */\n readonly next: string\n}\n\nexport const refuse = (refusal: Refusal, reason: string, next: string): PullRefused => ({\n ok: false,\n refusal,\n reason,\n next,\n})\n\nconst SHA256 = /^[0-9a-f]{64}$/\nconst DIGEST_MARK = '@sha256:'\n\n/** The source a person wrote, split into where it comes from and the content digest it names. @throws when the digest is malformed. */\nexport function splitDigest(input: string): { readonly source: string; readonly digest?: string } {\n const at = input.lastIndexOf(DIGEST_MARK)\n if (at === -1) return { source: input }\n const digest = input.slice(at + DIGEST_MARK.length)\n if (!SHA256.test(digest))\n throw new Error(`\"${digest}\" is not a content digest: it has 64 lowercase hex characters`)\n return { source: input.slice(0, at), digest }\n}\n\n/** The entry files the extensions folder loads, in its order. */\nconst ENTRIES = ['index.ts', 'index.js', 'index.mjs']\n\nconst text = (file: PluginFile): string => Buffer.from(file.bytes).toString('utf8')\n\nexport interface PullContext {\n /** The content digest the source names. */\n readonly digest?: string | undefined\n /** Whether the extensions folder can hold a plugin of this name. */\n readonly nameFits: (name: string) => boolean\n /** Whether this app has the service right now. */\n readonly hasService: (name: string) => boolean\n}\n\n/** The first reason this package may not enter the app, or undefined. */\nexport function pullRefusal(\n manifest: Readonly<Record<string, unknown>>,\n files: readonly PluginFile[],\n context: PullContext,\n): PullRefused | undefined {\n const name = String(manifest.name)\n if (!context.nameFits(name)) {\n return refuse(\n 'name',\n `the package is called \"${name}\", which a folder in plugins/ cannot hold`,\n 'ask its author to release it under lowercase letters, digits and dashes',\n )\n }\n const digest = digestFiles(files)\n if (context.digest !== undefined && context.digest !== digest) {\n return refuse(\n 'digest',\n `${digest} is not the digest the source names (${context.digest}); these are different bytes`,\n 'ask the person who gave you the digest which release they meant',\n )\n }\n const issues = portabilityIssues(files)\n if (issues.length > 0) {\n return refuse(\n 'portability',\n issues.map((issue) => `${issue.path}: ${issue.reason}`).join('; '),\n 'ask its author to fix this and release again, so it works on every OS',\n )\n }\n const dependencies = Object.keys(\n (manifest.dependencies as Record<string, unknown> | undefined) ?? {},\n )\n if (dependencies.length > 0) {\n return refuse(\n 'dependencies',\n `it needs ${dependencies.join(', ')} installed, and a pull installs nothing`,\n 'ask its author to bundle them or name them as peers',\n )\n }\n const native = nativesOf(manifest)\n if ('error' in native) {\n return refuse(\n 'native',\n native.error,\n 'ask its author to fix \"acrylblends.native\" in its package.json and release again',\n )\n }\n const entry = ENTRIES.flatMap((path) => files.filter((file) => file.path === path))[0]\n if (entry === undefined) {\n return refuse(\n 'entry',\n `it has none of ${ENTRIES.join(', ')} at its top level`,\n 'this package is not a plugin an app can load; ask its author',\n )\n }\n const inject = hostInjectFromSource(text(entry))\n if (inject !== undefined && 'error' in inject) {\n return refuse(\n 'inject',\n `${inject.error}. A pull reads what a plugin needs without running it`,\n 'ask its author to list the services as plain names',\n )\n }\n const missing = (inject?.names ?? []).filter((service) => !context.hasService(service))\n if (missing.length > 0) return missingServices(missing)\n return undefined\n}\n\nexport const missingServices = (missing: readonly string[]): PullRefused =>\n refuse(\n 'missing-service',\n `it needs ${missing.join(', ')}, which this app does not have`,\n 'add the plugin that provides it, then pull again',\n )\n","/**\n * 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\n * `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\n * 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.\n */\n\n/** A list is a few lines of text: anything larger is not a list of plugins. */\nexport const LIST_MAX_BYTES = 64 * 1024\n\n/** More sources than a group has people is a mistake, not a workshop. */\nexport const LIST_MAX_SOURCES = 100\n\n/** The command a person pastes from `plugin publish`: only its source is kept. */\nconst PULL_COMMAND = /^(?:npm run acryl --\\s+)?plugin pull\\s+/u\n\n/** A `#` at the start of a line or after a space begins a comment; a source never holds one there. */\nconst COMMENT = /(?:^|\\s)#.*$/u\n\nexport interface PullListLine {\n /** Its line in the list, from 1, so a problem is easy to find. */\n readonly line: number\n readonly source: string\n}\n\nexport interface ParsedPullList {\n /** The sources in their order, each once. */\n readonly sources: readonly PullListLine[]\n /** Lines that are not one source, each with what is wrong. */\n readonly problems: readonly string[]\n}\n\n/** The sources of a list, in order and without repeats, and the lines that are not a source. */\nexport function parsePullList(text: string): ParsedPullList {\n const sources: PullListLine[] = []\n const problems: string[] = []\n const seen = new Set<string>()\n text.split(/\\r?\\n/u).forEach((raw, index) => {\n const line = index + 1\n const value = raw.replace(COMMENT, '').trim().replace(PULL_COMMAND, '').trim()\n if (value === '') return\n if (/\\s/u.test(value)) {\n problems.push(\n `line ${String(line)} holds more than one word (\"${value}\"); write one source per line`,\n )\n return\n }\n if (seen.has(value)) return\n seen.add(value)\n sources.push({ line, source: value })\n })\n if (sources.length > LIST_MAX_SOURCES)\n problems.push(\n `the list has ${String(sources.length)} sources; a list holds at most ${String(LIST_MAX_SOURCES)}`,\n )\n return { sources, problems }\n}\n\n/** Where a list is read from: an https address, or a file (relative to the app folder). */\nexport type PullListLocation =\n | { readonly kind: 'address'; readonly url: string }\n | { readonly kind: 'file'; readonly path: string }\n\n/** @returns undefined for something that is neither (an http: address, a github: source): the caller names what a list may be. */\nexport function pullListLocation(from: string): PullListLocation | undefined {\n const value = from.trim()\n if (value === '') return undefined\n if (/^https:\\/\\//iu.test(value)) return { kind: 'address', url: value }\n // A drive letter (C:\\...) is a path; any other scheme is not a place a list is read from.\n if (/^[a-z][a-z0-9+.-]+:/iu.test(value) && !/^[a-z]:[\\\\/]/iu.test(value)) return undefined\n return { kind: 'file', path: value }\n}\n","/**\n * What an app remembers about the plugins it pulled: their source and digests, in the `plugin-share` row's config of `blend.yaml`. A row's config is\n * resolved into `blend.lock.json` too, so the lock records them with no new format, and a copy of the app can fetch exactly the same bytes. Pure text\n * to text; comments and the person's formatting stay.\n */\nimport { isMap, isSeq, parseDocument } from 'yaml'\n\nexport const ROW = 'plugin-share'\n\nexport interface PulledRecord {\n /** `github:<owner>/<repo>@<version>` or an https address: something another machine can fetch. */\n readonly source: string\n /** The sha512 of the release file. */\n readonly integrity: string\n /** The sha256 of the plugin's content. */\n readonly digest: string\n}\n\nconst isRecord = (value: unknown): value is PulledRecord => {\n const record = value as Partial<Record<keyof PulledRecord, unknown>> | null\n return (\n typeof record?.source === 'string' &&\n typeof record.integrity === 'string' &&\n typeof record.digest === 'string'\n )\n}\n\n/** The plugins this definition remembers pulling. */\nexport function pulledRecords(text: string): Readonly<Record<string, PulledRecord>> {\n const rows = (parseDocument(text).toJS() as { spec?: { rows?: unknown } } | null)?.spec?.rows\n if (!Array.isArray(rows)) return {}\n const pulled = (\n rows.find((row: { name?: unknown }) => row?.name === ROW) as\n | { config?: { pulled?: unknown } }\n | undefined\n )?.config?.pulled\n if (typeof pulled !== 'object' || pulled === null) return {}\n return Object.fromEntries(\n Object.entries(pulled).filter(([, record]) => isRecord(record)),\n ) as Record<string, PulledRecord>\n}\n\n/**\n * 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\n * composed without the row has nowhere to remember.\n */\nexport function withPulledRecord(\n text: string,\n name: string,\n record: PulledRecord | undefined,\n): string {\n const document = parseDocument(text)\n const rows = document.getIn(['spec', 'rows'])\n if (!isSeq(rows)) return text\n const row = rows.items.find((item) => isMap(item) && item.get('name') === ROW)\n if (!isMap(row)) return text\n if (record === undefined) {\n if (!row.hasIn(['config', 'pulled', name])) return text\n row.deleteIn(['config', 'pulled', name])\n const left = row.getIn(['config', 'pulled'])\n if (isMap(left) && left.items.length === 0) row.deleteIn(['config', 'pulled'])\n const config = row.get('config')\n if (isMap(config) && config.items.length === 0) row.delete('config')\n } else {\n row.setIn(['config'], row.get('config') ?? document.createNode({}))\n if (!row.hasIn(['config', 'pulled'])) row.setIn(['config', 'pulled'], document.createNode({}))\n row.setIn(['config', 'pulled', name], document.createNode(record))\n }\n return String(document)\n}\n","/**\n * Sharing a plugin between people: `pull(source)` turns a release someone published into a running plugin in this app. It fetches without running\n * anything, decides from the package's files (`pull-check.ts`), and hands a folder to `extensions`, which owns the install and its rollback.\n * Design: docs/plans/plugin-share.md.\n */\nimport {\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { findSecrets } from '@acryldev/app-persistence'\nimport { digestFolder, type PluginFile } from '@acryldev/blends-core'\nimport { type ExtensionInfo, NAME } from '@acryldev/extensions'\nimport type {} from '@acryldev/instance'\nimport { LOCK_FILE, writeLock } from '@acryldev/manifest/lock'\nimport {\n bumpVersion,\n gitCli,\n githubCli,\n githubReleasesOverHttps,\n httpsDownload,\n InvalidPluginSourceError,\n type PluginSource,\n PluginStore,\n PullError,\n packFolder,\n parsePluginSource,\n pullPlugin,\n type ReleasePort,\n readTarball,\n sharePlugin,\n storeRootOf,\n} from '@acryldev/plugin-hub-core'\nimport { type Context, Service } from '@deepseek-ai/cordis'\nimport {\n ensureNative,\n type NativeAction,\n type NativePackage,\n type NativePlaces,\n type NativePorts,\n nativeFor,\n nativePorts,\n nativesOf,\n releaseNative,\n} from './native.ts'\nimport { packagePlugin } from './package.ts'\nimport {\n type PublishOptions,\n type PublishPlan,\n type PublishPorts,\n type PublishRefused,\n type PublishResult,\n pullLineOf,\n samePlan,\n} from './publish.ts'\nimport {\n missingServices,\n type PullRefused,\n pullRefusal,\n refuse,\n splitDigest,\n} from './pull-check.ts'\nimport { LIST_MAX_BYTES, parsePullList, pullListLocation } from './pull-list.ts'\nimport { type PulledRecord, pulledRecords, withPulledRecord } from './pulled-records.ts'\n\nexport type {\n PublishOptions,\n PublishPlan,\n PublishPorts,\n PublishRefused,\n PublishResult,\n} from './publish.ts'\n\n/** One remembered plugin the app fetched again at its start because its folder was gone. */\nexport type RestoreOutcome =\n | { readonly name: string; readonly ok: true }\n | { readonly name: string; readonly ok: false; readonly reason: string; readonly next: string }\n\nexport interface PluginShareConfig {\n /** Where pulled plugins go; must be an extensions source. Defaults to `<project>/plugins`. */\n dir?: string\n /** Where a `github:` source reads releases. Defaults to GitHub over HTTPS. */\n releases?: ReleasePort\n /** Where a publish goes. Defaults to the person's own `gh` and `git`. */\n publish?: PublishPorts\n /** 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. */\n download?: (url: string) => Promise<Uint8Array>\n /** How a plugin's native package is downloaded and unpacked (native.ts). Defaults to the npm registry and the system's tar. */\n native?: NativePorts\n}\n\nexport type PullResult =\n | {\n readonly ok: true\n readonly name: string\n readonly version: string\n /** The sha512 of the release's tarball, as the registry lists it. */\n readonly integrity: string\n /** The sha256 of the plugin's content: the same on every OS. A source can name it (`@sha256:<digest>`). */\n readonly digest: string\n readonly action: 'installed' | 'updated' | 'unchanged'\n readonly state: string\n /** 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. */\n readonly remembered: boolean\n /** The native package the plugin brought for this computer (native.ts), and what installing it did. */\n readonly native?: {\n readonly package: string\n readonly version: string\n readonly size: number\n readonly action: NativeAction\n }\n }\n | PullRefused\n\n/** One source of a list and what pulling it did. */\nexport interface PullListEntry {\n /** Its line in the list. */\n readonly line: number\n readonly source: string\n readonly result: PullResult\n}\n\n/** A list pulled: every source with its own result (some may be refused while the others install), or the list itself refused. */\nexport type PullListResult =\n | { readonly ok: true; readonly from: string; readonly entries: readonly PullListEntry[] }\n | PullRefused\n\n/** 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. */\n/** What extensions says about an installed plugin (its state, the services a pending one waits for, ...), and where a pulled one came from. */\nexport interface SharedPluginInfo extends ExtensionInfo {\n /** 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. */\n readonly pulledFrom?: string\n /** Who released it: the account of a `github:` source or of a release address on github.com. */\n readonly author?: string\n /** The version its `package.json` names (`version` is the installed content's short digest); absent without one. */\n readonly release?: string\n}\n\n/** What removing a plugin did with its folder in `plugins/`. */\nexport type RemovedFolder =\n /** It held the release as pulled, so nothing of anyone's is lost: the pull line brings it back. */\n | 'deleted'\n /** 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. */\n | 'kept'\n | 'none'\n\nexport type SharedRemoveResult =\n | {\n readonly ok: true\n readonly name: string\n readonly folder: RemovedFolder\n readonly note?: string\n }\n | { readonly ok: false; readonly name: string; readonly errors: readonly string[] }\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n pluginShare: PluginShare\n }\n}\n\n/** The account that released a source: the owner of a `github:<owner>/<repo>@<version>` source or of a release address on github.com. */\nconst authorOf = (source: string): string | undefined =>\n (/^github:([^/]+)\\//u.exec(source) ?? /^https:\\/\\/github\\.com\\/([^/]+)\\//u.exec(source))?.[1]\n\n/** The version a plugin folder's `package.json` names, when it names a plain one. */\nfunction releaseOf(folder: string): string | undefined {\n try {\n const version = (\n JSON.parse(readFileSync(join(folder, 'package.json'), 'utf8')) as { version?: unknown }\n ).version\n return typeof version === 'string' && /^\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.+-]+)?$/u.test(version)\n ? version\n : undefined\n } catch {\n return undefined\n }\n}\n\n/** The license a new public plugin is offered under; the plan shows it before the person says yes. */\nconst DEFAULT_LICENSE = 'MIT'\nconst LICENSE_ID = /^[A-Za-z0-9][A-Za-z0-9.+-]*$/u\n\nconst publishRefused = (reason: string, next: string): PublishRefused => ({\n ok: false,\n reason,\n next,\n})\n\nconst SOURCE_FORMS = 'github:<owner>/<repo>[@<version>] or a .tgz path or address'\n\n/** Read what a person wrote. A `.tgz` path may be relative to the app folder; the hub only takes absolute ones. */\nfunction readSource(\n input: string,\n root: string,\n): { readonly source: PluginSource; readonly digest?: string } {\n const { source, digest } = splitDigest(input.trim())\n const isLocalTarball = /\\.(?:tgz|tar\\.gz)$/iu.test(source) && !/^[a-z][a-z0-9+]+:/iu.test(source)\n const parsed = parsePluginSource(isLocalTarball ? resolve(root, source) : source)\n if (parsed.kind !== 'github' && parsed.kind !== 'tarball-file' && parsed.kind !== 'tarball-url') {\n const named = parsed.kind === 'name' ? 'a bare name' : parsed.kind\n throw new InvalidPluginSourceError(\n input,\n `${named} sources are not offered here; pull ${SOURCE_FORMS}`,\n )\n }\n return { source: parsed, ...(digest === undefined ? {} : { digest }) }\n}\n\n/** The source as another machine can fetch it: the version pinned; a file on this machine names nothing. */\nfunction recordedSource(source: PluginSource, version: string): string | undefined {\n if (source.kind === 'github') return `github:${source.owner}/${source.repo}@${version}`\n return source.kind === 'tarball-url' ? source.url : undefined\n}\n\nconst reasonOf = (cause: unknown): string => {\n if (cause instanceof PullError || cause instanceof InvalidPluginSourceError) return cause.reason\n return cause instanceof Error ? cause.message : String(cause)\n}\n\nexport class PluginShare extends Service {\n /** What was fetched again at this start. */\n readonly restored: Promise<readonly RestoreOutcome[]>\n private readonly dir: string\n private readonly releases: ReleasePort\n private readonly download: (url: string) => Promise<Uint8Array>\n private readonly ports: PublishPorts\n /** One at a time: two pulls of one name must not race for its folder, nor two publishes for its package. */\n private queue: Promise<unknown> = Promise.resolve()\n /** The content digest of each plugin pulled while the app runs, a local file's too, which `blend.yaml` does not remember. */\n private readonly live = new Map<string, string>()\n private readonly nativeWork: NativePorts\n /** The native package each installed plugin brought for this computer: what its removal takes away. */\n private readonly natives = new Map<string, NativePackage>()\n\n /**\n * 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\n * 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.\n */\n private readonly own: Context\n\n constructor(ctx: Context, config: PluginShareConfig) {\n super(ctx, 'pluginShare')\n this.own = ctx\n this.dir = resolve(config.dir ?? join(ctx.appInstance.root, 'plugins'))\n this.releases = config.releases ?? githubReleasesOverHttps()\n this.download = config.download ?? httpsDownload()\n this.nativeWork = config.native ?? nativePorts()\n this.ports = config.publish ?? { host: githubCli(), git: gitCli() }\n // Removing a plugin removes its record. Listened to here, not asked of each caller: every way of removing it goes through extensions.\n ctx.on('extensions/changed', (name, change) => {\n if (change !== 'removed') return\n this.live.delete(name)\n this.remember(name, undefined)\n this.dropNative(name)\n })\n // Not awaited by the app's start: a person offline still gets their app, and the warning says what is missing.\n this.restored = this.inTurn(() => this.restore())\n }\n\n /** 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. */\n pull(source: string): Promise<PullResult> {\n return this.inTurn(() => this.pullNow(source))\n }\n\n /**\n * 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\n * 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.\n * A list that cannot be read, or has a line that is not one source, pulls nothing.\n */\n async pullList(from: string): Promise<PullListResult> {\n const text = await this.readList(from)\n if (typeof text !== 'string') return text\n const { sources, problems } = parsePullList(text)\n if (problems.length > 0)\n return refuse('list', `${from}: ${problems.join('; ')}`, 'fix the list; nothing was pulled')\n if (sources.length === 0)\n return refuse(\n 'list',\n `${from} names no plugin`,\n 'write one source per line, e.g. github:someone/pomodoro@0.1.0',\n )\n const entries: PullListEntry[] = []\n for (const { line, source } of sources)\n entries.push({ line, source, result: await this.pull(source) })\n return { ok: true, from, entries }\n }\n\n /** The text of a list, or why it cannot be read. */\n private async readList(from: string): Promise<string | PullRefused> {\n const where = pullListLocation(from)\n if (where === undefined)\n return refuse(\n 'list',\n `\"${from}\" is not a list`,\n 'name a file in the app (e.g. group.txt) or an https address of one',\n )\n try {\n let bytes: Uint8Array\n if (where.kind === 'address') bytes = await this.download(where.url)\n else {\n const path = resolve(this.own.appInstance.root, where.path)\n if (!existsSync(path) || !statSync(path).isFile())\n return refuse(\n 'list',\n `there is no file ${where.path}`,\n 'name a file in the app, or an https address',\n )\n bytes = readFileSync(path)\n }\n if (bytes.length > LIST_MAX_BYTES)\n return refuse(\n 'list',\n `${from} is larger than ${String(LIST_MAX_BYTES)} bytes, so it is not a list of plugins`,\n 'name the list itself',\n )\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n } catch (cause) {\n return refuse(\n 'list',\n `${from} could not be read: ${reasonOf(cause)}`,\n 'check the address; nothing was pulled',\n )\n }\n }\n\n /**\n * 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\n * 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.\n */\n pulledDigest(name: string): string | undefined {\n return this.live.get(name) ?? this.recorded(name)?.digest\n }\n\n /** The plugins installed while the app runs, each pulled one with its source and author. */\n list(): SharedPluginInfo[] {\n const file = join(this.own.appInstance.root, 'blend.yaml')\n const records = existsSync(file) ? pulledRecords(readFileSync(file, 'utf8')) : {}\n return this.own.extensions.list().map((info) => {\n const record = records[info.name]\n const author = record === undefined ? undefined : authorOf(record.source)\n const release = releaseOf(join(this.dir, info.name))\n return {\n ...info,\n ...(record === undefined ? {} : { pulledFrom: record.source }),\n ...(author === undefined ? {} : { author }),\n ...(release === undefined ? {} : { release }),\n }\n })\n }\n\n /**\n * 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\n * folder with someone's work in it (this app's own plugin, or a pulled one changed since) stays, and the answer says so.\n */\n remove(name: string): Promise<SharedRemoveResult> {\n return this.inTurn(() => this.removeNow(name))\n }\n\n private inTurn<T>(step: () => Promise<T>): Promise<T> {\n const run = this.queue.then(step)\n this.queue = run.catch(() => undefined)\n return run\n }\n\n /**\n * 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.\n */\n planPublish(name: string, options: PublishOptions = {}): Promise<PublishPlan | PublishRefused> {\n return this.inTurn(() => this.planNow(name, options))\n }\n\n /**\n * 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\n * is sent. Only the person's own surfaces call this: the frame's confirm and the terminal's prompt. No verb reaches it.\n */\n publish(\n name: string,\n confirmed: PublishPlan,\n options: PublishOptions = {},\n ): Promise<PublishResult> {\n return this.inTurn(async () => {\n const plan = await this.planNow(name, options)\n if ('ok' in plan) return plan\n if (!samePlan(plan, confirmed)) {\n return publishRefused(\n `this plugin's publish changed since you confirmed it (now ${plan.owner}/${plan.repo} v${plan.version}, digest ${plan.digest}); nothing was sent`,\n 'look at the new plan and say yes again',\n )\n }\n const { home } = this.own.appInstance\n try {\n const shared = await sharePlugin(\n join(this.packages, name),\n {\n owner: plan.owner,\n repo: plan.repo,\n visibility: plan.visibility,\n kind: 'source-plugin',\n },\n { ...this.ports, store: new PluginStore(storeRootOf(home)) },\n )\n if (shared.status === 'refused')\n return publishRefused(shared.reason, 'fix what it names; nothing was sent')\n return {\n ok: true,\n url: shared.url,\n releaseUrl: shared.releaseUrl,\n version: shared.version,\n integrity: shared.integrity,\n digest: plan.digest,\n pullLine: plan.pullLine,\n }\n } catch (cause) {\n return publishRefused(\n reasonOf(cause),\n 'look at the repository; part of this publish may have been sent',\n )\n }\n })\n }\n\n /** 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. */\n private remember(name: string, record: PulledRecord | undefined): boolean {\n const { root } = this.own.appInstance\n const file = join(root, 'blend.yaml')\n if (!existsSync(file)) return false\n const text = readFileSync(file, 'utf8')\n const next = withPulledRecord(text, name, record)\n if (next !== text) {\n writeFileSync(`${file}.tmp`, next)\n renameSync(`${file}.tmp`, file)\n if (existsSync(join(root, LOCK_FILE))) writeLock(root)\n }\n return record === undefined || pulledRecords(next)[name] !== undefined\n }\n\n private async removeNow(name: string): Promise<SharedRemoveResult> {\n // Read before the removal, which forgets both the record and the live digest.\n const pulled = this.pulledDigest(name)\n const removed = await this.own.extensions.remove(name)\n if (!removed.ok) return removed\n const folder = join(this.dir, name)\n if (!existsSync(folder)) return { ok: true, name, folder: 'none' }\n if (pulled !== undefined && digestFolder(folder) === pulled) {\n rmSync(folder, { recursive: true, force: true })\n return { ok: true, name, folder: 'deleted' }\n }\n const why = pulled === undefined ? \"is this app's own plugin\" : 'was changed after the pull'\n return {\n ok: true,\n name,\n folder: 'kept',\n 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`,\n }\n }\n\n /** What `blend.yaml` remembers about one pulled plugin now. */\n private recorded(name: string): PulledRecord | undefined {\n const file = join(this.own.appInstance.root, 'blend.yaml')\n return existsSync(file) ? pulledRecords(readFileSync(file, 'utf8'))[name] : undefined\n }\n\n /** Fetch the remembered plugins whose folder is gone, exactly as recorded: other bytes are refused, and the record stays for the person to decide. */\n private get places(): NativePlaces {\n return { root: this.own.appInstance.root, home: this.own.appInstance.home }\n }\n\n /** Remember the native package an installed plugin brought; one it no longer brings (an update) goes. The result's `native` field. */\n private keepNative(\n name: string,\n native: NativePackage | undefined,\n before: NativePackage | undefined,\n action: NativeAction | undefined,\n ): Pick<Extract<PullResult, { ok: true }>, 'native'> {\n if (\n before !== undefined &&\n (native === undefined ||\n before.version !== native.version ||\n before.package !== native.package)\n )\n this.dropNative(name)\n if (native === undefined || action === undefined) return {}\n this.natives.set(name, native)\n return {\n native: { package: native.package, version: native.version, size: native.size, action },\n }\n }\n\n /** Take away the native package a removed plugin brought, unless another installed plugin brought the same one. */\n private dropNative(name: string): void {\n const native = this.natives.get(name)\n if (native === undefined) return\n this.natives.delete(name)\n const shared = [...this.natives.values()].some(\n (other) => other.package === native.package && other.version === native.version,\n )\n if (!shared) releaseNative(native, this.places)\n }\n\n /** A pulled plugin that is here again links its native package again: an `npm install` puts the placeholder back in its place. */\n private async relinkNative(name: string): Promise<void> {\n let manifest: Record<string, unknown>\n try {\n manifest = JSON.parse(readFileSync(join(this.dir, name, 'package.json'), 'utf8')) as Record<\n string,\n unknown\n >\n } catch {\n return\n }\n const declared = nativesOf(manifest)\n const native = 'natives' in declared ? nativeFor(declared.natives) : undefined\n if (native === undefined) return\n try {\n await ensureNative(native, this.places, this.nativeWork)\n this.natives.set(name, native)\n } catch (cause) {\n console.warn(\n `plugin-share: ${name}'s ${native.package} was not installed again: ${reasonOf(cause)}`,\n )\n }\n }\n\n private async restore(): Promise<readonly RestoreOutcome[]> {\n const file = join(this.own.appInstance.root, 'blend.yaml')\n if (!existsSync(file)) return []\n const outcomes: RestoreOutcome[] = []\n for (const [name, record] of Object.entries(pulledRecords(readFileSync(file, 'utf8')))) {\n if (existsSync(join(this.dir, name))) {\n await this.relinkNative(name)\n continue\n }\n const result = await this.pullNow(\n `${record.source}@sha256:${record.digest}`,\n record.integrity,\n )\n outcomes.push(\n result.ok\n ? { name, ok: true }\n : { name, ok: false, reason: result.reason, next: result.next },\n )\n if (!result.ok)\n console.warn(\n `plugin-share: ${name} was not fetched again: ${result.reason}. ${result.next}.`,\n )\n }\n return outcomes\n }\n\n private get packages(): string {\n return join(this.own.appInstance.home, 'plugin-packages')\n }\n\n private async planNow(\n name: string,\n options: PublishOptions,\n ): Promise<PublishPlan | PublishRefused> {\n const source = join(this.dir, name)\n if (!NAME.test(name) || !existsSync(source))\n return publishRefused(\n `this app has no plugin \"${name}\" in plugins/`,\n 'name a folder of plugins/',\n )\n try {\n const { host } = this.ports\n const owner = options.owner ?? host.login()\n const repo = name\n const description = `The ${name} Cordis plugin.`\n const license = options.license ?? DEFAULT_LICENSE\n if (!LICENSE_ID.test(license))\n return publishRefused(\n `\"${license}\" is not a license id`,\n 'write one such as MIT or Apache-2.0',\n )\n const release = { owner, repo, license }\n const existing = host.repository(owner, repo)\n let packaged = await packagePlugin(source, this.packages, name, description, { release })\n const released =\n existing !== undefined && host.releaseExists(owner, repo, `v${packaged.version}`)\n ? packaged.version\n : undefined\n if (released !== undefined)\n packaged = await packagePlugin(source, this.packages, name, description, {\n release,\n version: bumpVersion(released, 'patch'),\n })\n const secrets = findSecrets(\n readTarball(packFolder(packaged.dir).tarball).map((file) => ({\n path: file.path,\n text: Buffer.from(file.content).toString('utf8'),\n })),\n )\n if (secrets.length > 0) {\n return publishRefused(\n `the secret check found ${String(secrets.length)} possible secret(s) in ${secrets.map((secret) => secret.path).join(', ')}; nothing was sent`,\n \"take them out of the plugin and read them from the app's settings\",\n )\n }\n return {\n owner,\n repo,\n version: packaged.version,\n visibility: 'public',\n license,\n createsRepository: existing === undefined,\n ...(released === undefined ? {} : { released }),\n files: packaged.files,\n integrity: packaged.integrity,\n digest: packaged.digest,\n pullLine: pullLineOf(owner, repo, packaged.version, packaged.digest),\n }\n } catch (cause) {\n return publishRefused(reasonOf(cause), 'fix it, or sign in with gh; nothing was sent')\n }\n }\n\n private async pullNow(input: string, expectIntegrity?: string): Promise<PullResult> {\n const { home, root } = this.own.appInstance\n let read: ReturnType<typeof readSource>\n try {\n read = readSource(input, root)\n } catch (cause) {\n return refuse(\n 'source',\n reasonOf(cause),\n `write ${SOURCE_FORMS}, with @sha256:<digest> at the end to name the content`,\n )\n }\n mkdirSync(home, { recursive: true })\n const scratch = mkdtempSync(join(home, 'plugin-pull-'))\n try {\n let pulled: Awaited<ReturnType<typeof pullPlugin>>\n try {\n pulled = await pullPlugin(\n read.source,\n {\n store: new PluginStore(scratch),\n releases: this.releases,\n download: this.download,\n },\n expectIntegrity === undefined ? {} : { expectIntegrity },\n )\n } catch (cause) {\n return refuse(\n 'fetch',\n reasonOf(cause),\n 'check the source with the person who released it; nothing was installed',\n )\n }\n const files: PluginFile[] = readTarball(readFileSync(pulled.stored.path)).map(\n ({ path, content }) => ({ path, bytes: content, kind: 'file' }),\n )\n const refused = pullRefusal(pulled.manifest, files, {\n digest: read.digest,\n nameFits: (name) => NAME.test(name),\n hasService: (service) => this.own.get(service as never) !== undefined,\n })\n if (refused !== undefined) return refused\n const declared = nativesOf(pulled.manifest)\n return await this.install(\n pulled.stored.name,\n pulled.stored.version,\n pulled.stored.integrity,\n files,\n recordedSource(read.source, pulled.stored.version),\n 'natives' in declared ? nativeFor(declared.natives) : undefined,\n )\n } finally {\n rmSync(scratch, { recursive: true, force: true })\n }\n }\n\n /** Put the files in `plugins/<name>/` and install them; whatever does not end running takes its folder with it. */\n private async install(\n name: string,\n version: string,\n integrity: string,\n files: readonly PluginFile[],\n source: string | undefined,\n native: NativePackage | undefined,\n ): Promise<PullResult> {\n const target = join(this.dir, name)\n const incoming = join(this.dir, `.pulling-${name}`)\n rmSync(incoming, { recursive: true, force: true })\n try {\n for (const file of files) {\n const path = join(incoming, ...file.path.split('/'))\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, file.bytes)\n }\n const digest = digestFolder(incoming)\n // The folder may be there already: the same bytes are already pulled, anything else is someone's work.\n const wrote = !existsSync(target)\n const before = this.recorded(name)\n const held = wrote ? undefined : digestFolder(target)\n if (held !== undefined && held !== digest) {\n const holder = before === undefined ? 'made in this app' : `pulled from ${before.source}`\n // Only an untouched pulled copy goes with `plugin remove`; anything else is someone's work, which the person moves themselves.\n const next =\n before !== undefined && held === before.digest\n ? `keep it, or remove it (npm run acryl -- plugin remove ${name}) and pull again`\n : `keep it, or move plugins/${name} out of plugins/ and pull again`\n return refuse(\n 'folder-exists',\n `plugins/${name} holds a different copy of this plugin, ${holder}`,\n next,\n )\n }\n const liveBefore = this.live.get(name)\n this.live.set(name, digest)\n if (wrote) renameSync(incoming, target)\n // 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\n // 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.\n const remembered = source !== undefined && this.remember(name, { source, integrity, digest })\n // Installed before the plugin starts, so the plugin finds it; an install that does not end running takes back only what it added.\n let nativeAction: NativeAction | undefined\n const nativeBefore = this.natives.get(name)\n const undo = () => {\n if (native !== undefined && (nativeAction === 'downloaded' || nativeAction === 'linked'))\n releaseNative(native, this.places, nativeAction === 'linked')\n if (wrote) rmSync(target, { recursive: true, force: true })\n if (remembered) this.remember(name, before)\n if (liveBefore === undefined) this.live.delete(name)\n else this.live.set(name, liveBefore)\n }\n if (native !== undefined) {\n try {\n nativeAction = await ensureNative(native, this.places, this.nativeWork)\n } catch (cause) {\n undo()\n return refuse(\n 'native',\n `${native.package}@${native.version} (${Math.round(native.size / 1e6)} MB) could not be installed: ${reasonOf(cause)}`,\n 'check the internet connection and pull again; the plugin was not installed',\n )\n }\n }\n let result: Awaited<ReturnType<Context['extensions']['install']>>\n try {\n result = await this.own.extensions.install(target)\n } catch (cause) {\n undo()\n return refuse(\n 'install',\n reasonOf(cause),\n 'this app does not install plugins while it runs like this',\n )\n }\n if (!result.ok) {\n undo()\n return refuse('install', result.errors.join('; '), result.next)\n }\n if (result.state === 'pending') {\n await this.own.extensions.remove(name)\n undo()\n return missingServices(result.missing)\n }\n return {\n ok: true,\n name,\n version,\n integrity,\n digest,\n action: result.action,\n state: result.state,\n remembered,\n ...this.keepNative(name, native, nativeBefore, nativeAction),\n }\n } finally {\n rmSync(incoming, { recursive: true, force: true })\n }\n }\n}\n\nexport const pluginShare = {\n name: 'plugin-share',\n inject: ['extensions', 'appInstance'],\n apply(ctx: Context, config: PluginShareConfig) {\n // 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\n // app whose src/app.ts is older than that line is covered here.\n if (process.env.NODE_ENV === 'production') return\n new PluginShare(ctx, config ?? {})\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,kBAAkB;;AAG/B,MAAa,mBAAmB;;AAMhC,MAAM,WAAW;AAmBjB,MAAM,WAAW;AACjB,MAAM,gBAAgB;AACtB,MAAM,SAAS;AACf,MAAM,OAA0B;CAAC;CAAU;CAAS;AAAO;AAC3D,MAAM,OAA0B,CAAC,SAAS,KAAK;AAE/C,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;AAGrE,SAAgB,UACd,UAC6E;CAC7E,MAAM,UAAU,SAAS;CACzB,IAAI,YAAY,KAAA,KAAc,SAAS,OAAO,KAAK,QAAQ,WAAW,KAAA,GACpE,OAAO,EAAE,SAAS,CAAC,EAAE;CACvB,IAAI,CAAC,SAAS,OAAO,KAAK,CAAC,MAAM,QAAQ,QAAQ,MAAM,GACrD,OAAO,EAAE,OAAO,uCAAqC;CACvD,MAAM,UAA2B,CAAC;CAClC,KAAK,MAAM,CAAC,OAAO,UAAU,QAAQ,OAAO,QAAQ,GAAG;EACrD,MAAM,KAAK,sBAAsB,MAAM;EACvC,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO,EAAE,OAAO,GAAG,GAAG,mBAAmB;EAC/D,MAAM,EAAE,SAAS,MAAM,SAAS,IAAI,KAAK,WAAW,SAAS;EAC7D,IAAI,OAAO,SAAS,YAAY,CAAC,SAAS,KAAK,IAAI,GACjD,OAAO,EAAE,OAAO,GAA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I;GACJ,IAAI;IACF,SAAS,MAAM,KAAK,IAAI,WAAW,QAAQ,MAAM;GACnD,SAAS,OAAO;IACd,KAAK;IACL,OAAO,OACL,WACA,SAAS,KAAK,GACd,2DACF;GACF;GACA,IAAI,CAAC,OAAO,IAAI;IACd,KAAK;IACL,OAAO,OAAO,WAAW,OAAO,OAAO,KAAK,IAAI,GAAG,OAAO,IAAI;GAChE;GACA,IAAI,OAAO,UAAU,WAAW;IAC9B,MAAM,KAAK,IAAI,WAAW,OAAO,IAAI;IACrC,KAAK;IACL,OAAO,gBAAgB,OAAO,OAAO;GACvC;GACA,OAAO;IACL,IAAI;IACJ;IACA;IACA;IACA;IACA,QAAQ,OAAO;IACf,OAAO,OAAO;IACd;IACA,GAAG,KAAK,WAAW,MAAM,QAAQ,cAAc,YAAY;GAC7D;EACF,UAAU;GACR,OAAO,UAAU;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;EACnD;CACF;AACF;AAEA,MAAa,cAAc;CACzB,MAAM;CACN,QAAQ,CAAC,cAAc,aAAa;CACpC,MAAM,KAAc,QAA2B;EAG7C,IAAI,QAAQ,IAAI,aAAa,cAAc;EAC3C,IAAI,YAAY,KAAK,UAAU,CAAC,CAAC;CACnC;AACF"}
package/lib/package.js ADDED
@@ -0,0 +1,138 @@
1
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { extname, join } from "node:path";
3
+ import { digestFiles, pluginFiles, portabilityIssues } from "@acryldev/blends-core";
4
+ import { packFolder, readTarball, syncServiceContract } from "@acryldev/plugin-hub-core";
5
+ //#region package.ts
6
+ /**
7
+ * 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
8
+ * hub owns the tarball and the contract, blends-core what "portable" and "digest" mean; this module only decides what goes in.
9
+ */
10
+ /** The package.json of a standalone plugin package: the host framework is a peer, never a second installed copy. */
11
+ function packageManifest(name, description, version = "0.1.0", release) {
12
+ return {
13
+ name,
14
+ version,
15
+ description,
16
+ ...release === void 0 ? {} : {
17
+ license: release.license,
18
+ repository: {
19
+ type: "git",
20
+ url: `git+https://github.com/${release.owner}/${release.repo}.git`
21
+ }
22
+ },
23
+ type: "module",
24
+ exports: {
25
+ ".": "./index.ts",
26
+ "./package.json": "./package.json"
27
+ },
28
+ peerDependencies: { "@deepseek-ai/cordis": "4.0.4" },
29
+ keywords: [
30
+ "cordis",
31
+ "cordis-plugin",
32
+ "acrylblends"
33
+ ]
34
+ };
35
+ }
36
+ /** 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. */
37
+ const TEXT = /* @__PURE__ */ new Set([
38
+ ".ts",
39
+ ".mts",
40
+ ".cts",
41
+ ".tsx",
42
+ ".js",
43
+ ".mjs",
44
+ ".cjs",
45
+ ".jsx",
46
+ ".json",
47
+ ".md",
48
+ ".txt",
49
+ ".css",
50
+ ".html",
51
+ ".yml",
52
+ ".yaml",
53
+ ".svg"
54
+ ]);
55
+ function withLineFeeds(dir) {
56
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
57
+ const path = join(dir, entry.name);
58
+ if (entry.isDirectory()) withLineFeeds(path);
59
+ else if (entry.isFile() && TEXT.has(extname(entry.name).toLowerCase())) {
60
+ const text = readFileSync(path, "utf8");
61
+ if (text.includes("\r\n")) writeFileSync(path, text.replaceAll("\r\n", "\n"));
62
+ }
63
+ }
64
+ }
65
+ /** What the hub's share would otherwise add on the way out, changing the bytes after they were planned. */
66
+ function markPublic(target) {
67
+ const file = join(target, "package.json");
68
+ const manifest = JSON.parse(readFileSync(file, "utf8"));
69
+ writeFileSync(file, `${JSON.stringify({
70
+ ...manifest,
71
+ acryl: {
72
+ ...manifest.acryl,
73
+ visibility: "public"
74
+ }
75
+ }, null, 2)}\n`);
76
+ }
77
+ function versionIn(target) {
78
+ try {
79
+ const { version } = JSON.parse(readFileSync(join(target, "package.json"), "utf8"));
80
+ return typeof version === "string" ? version : void 0;
81
+ } catch {
82
+ return;
83
+ }
84
+ }
85
+ /**
86
+ * Package the plugin in `source` as `<packages>/<name>/` and `<packages>/<name>-<version>.tgz`. The person's folder is not touched. A version already
87
+ * packaged stays: a release is made once, and a person bumps it deliberately.
88
+ * @throws when the plugin would not work on every OS or its contract cannot be read; no package is left.
89
+ */
90
+ async function packagePlugin(source, packages, name, description, options = {}) {
91
+ const target = join(packages, name);
92
+ const version = options.version ?? versionIn(target);
93
+ rmSync(target, {
94
+ recursive: true,
95
+ force: true
96
+ });
97
+ mkdirSync(packages, { recursive: true });
98
+ cpSync(source, target, {
99
+ recursive: true,
100
+ filter: (path) => !path.includes("node_modules")
101
+ });
102
+ try {
103
+ writeFileSync(join(target, "package.json"), `${JSON.stringify(packageManifest(name, description, version, options.release), null, 2)}\n`);
104
+ if (!existsSync(join(target, "README.md"))) writeFileSync(join(target, "README.md"), `# ${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`);
105
+ withLineFeeds(target);
106
+ const issues = portabilityIssues(pluginFiles(target));
107
+ if (issues.length > 0) throw new Error(`it would not work on every OS: ${issues.map((issue) => `${issue.path}: ${issue.reason}`).join("; ")}`);
108
+ const contract = await syncServiceContract(target);
109
+ if (!contract.ok) throw new Error(`its service contract cannot be read: ${contract.errors.join("; ")}`);
110
+ if (options.release !== void 0) markPublic(target);
111
+ const packed = packFolder(target);
112
+ const tarball = join(packages, packed.fileName);
113
+ writeFileSync(tarball, packed.tarball);
114
+ const digest = digestFiles(readTarball(packed.tarball).map(({ path, content }) => ({
115
+ path,
116
+ bytes: content,
117
+ kind: "file"
118
+ })));
119
+ return {
120
+ dir: target,
121
+ version: packed.version,
122
+ files: packed.files,
123
+ tarball,
124
+ integrity: packed.integrity,
125
+ digest
126
+ };
127
+ } catch (cause) {
128
+ rmSync(target, {
129
+ recursive: true,
130
+ force: true
131
+ });
132
+ throw cause;
133
+ }
134
+ }
135
+ //#endregion
136
+ export { packageManifest, packagePlugin };
137
+
138
+ //# sourceMappingURL=package.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package.js","names":[],"sources":["../package.ts"],"sourcesContent":["/**\n * 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\n * hub owns the tarball and the contract, blends-core what \"portable\" and \"digest\" mean; this module only decides what goes in.\n */\nimport {\n cpSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { extname, join } from 'node:path'\nimport { digestFiles, pluginFiles, portabilityIssues } from '@acryldev/blends-core'\nimport { packFolder, readTarball, syncServiceContract } from '@acryldev/plugin-hub-core'\n\n/** The package.json of a standalone plugin package: the host framework is a peer, never a second installed copy. */\nexport function packageManifest(\n name: string,\n description: string,\n version = '0.1.0',\n release?: PackageRelease,\n): Record<string, unknown> {\n return {\n name,\n version,\n description,\n ...(release === undefined\n ? {}\n : {\n license: release.license,\n repository: {\n type: 'git',\n url: `git+https://github.com/${release.owner}/${release.repo}.git`,\n },\n }),\n type: 'module',\n exports: { '.': './index.ts', './package.json': './package.json' },\n // 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.\n // ACRYL measured it: a host package listed under dependencies brings a second copy of the framework, and its services stop\n // matching after a restart. A peer names the version and installs nothing.\n peerDependencies: { '@deepseek-ai/cordis': '4.0.4' },\n keywords: ['cordis', 'cordis-plugin', 'acrylblends'],\n }\n}\n\n/** Where a package is going to be released: written in now, so what is planned is byte for byte what is released. */\nexport interface PackageRelease {\n readonly owner: string\n readonly repo: string\n readonly license: string\n}\n\nexport interface PackageOptions {\n /** This version, instead of the one already packaged. */\n readonly version?: string\n readonly release?: PackageRelease\n}\n\nexport interface PackagedPlugin {\n readonly dir: string\n readonly version: string\n readonly files: readonly string[]\n /** The release file, next to the package folder. */\n readonly tarball: string\n /** The tarball's sha512, as the registry lists it. */\n readonly integrity: string\n /** The sha256 of the plugin's content, which a source can name (`@sha256:<digest>`). */\n readonly digest: string\n}\n\n/** 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. */\nconst TEXT = new Set([\n '.ts',\n '.mts',\n '.cts',\n '.tsx',\n '.js',\n '.mjs',\n '.cjs',\n '.jsx',\n '.json',\n '.md',\n '.txt',\n '.css',\n '.html',\n '.yml',\n '.yaml',\n '.svg',\n])\n\nfunction withLineFeeds(dir: string): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const path = join(dir, entry.name)\n if (entry.isDirectory()) withLineFeeds(path)\n else if (entry.isFile() && TEXT.has(extname(entry.name).toLowerCase())) {\n const text = readFileSync(path, 'utf8')\n if (text.includes('\\r\\n')) writeFileSync(path, text.replaceAll('\\r\\n', '\\n'))\n }\n }\n}\n\n/** What the hub's share would otherwise add on the way out, changing the bytes after they were planned. */\nfunction markPublic(target: string): void {\n const file = join(target, 'package.json')\n const manifest = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>\n writeFileSync(\n file,\n `${JSON.stringify({ ...manifest, acryl: { ...(manifest.acryl as object), visibility: 'public' } }, null, 2)}\\n`,\n )\n}\n\nfunction versionIn(target: string): string | undefined {\n try {\n const { version } = JSON.parse(readFileSync(join(target, 'package.json'), 'utf8')) as {\n version?: unknown\n }\n return typeof version === 'string' ? version : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Package the plugin in `source` as `<packages>/<name>/` and `<packages>/<name>-<version>.tgz`. The person's folder is not touched. A version already\n * packaged stays: a release is made once, and a person bumps it deliberately.\n * @throws when the plugin would not work on every OS or its contract cannot be read; no package is left.\n */\nexport async function packagePlugin(\n source: string,\n packages: string,\n name: string,\n description: string,\n options: PackageOptions = {},\n): Promise<PackagedPlugin> {\n const target = join(packages, name)\n const version = options.version ?? versionIn(target)\n rmSync(target, { recursive: true, force: true })\n mkdirSync(packages, { recursive: true })\n cpSync(source, target, { recursive: true, filter: (path) => !path.includes('node_modules') })\n try {\n writeFileSync(\n join(target, 'package.json'),\n `${JSON.stringify(packageManifest(name, description, version, options.release), null, 2)}\\n`,\n )\n if (!existsSync(join(target, 'README.md'))) {\n writeFileSync(\n join(target, 'README.md'),\n `# ${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`,\n )\n }\n withLineFeeds(target)\n const issues = portabilityIssues(pluginFiles(target))\n if (issues.length > 0)\n throw new Error(\n `it would not work on every OS: ${issues.map((issue) => `${issue.path}: ${issue.reason}`).join('; ')}`,\n )\n // The contract other people's apps and the registry read: what the plugin needs and provides, from its code.\n const contract = await syncServiceContract(target)\n if (!contract.ok)\n throw new Error(`its service contract cannot be read: ${contract.errors.join('; ')}`)\n if (options.release !== undefined) markPublic(target)\n const packed = packFolder(target)\n const tarball = join(packages, packed.fileName)\n writeFileSync(tarball, packed.tarball)\n const digest = digestFiles(\n readTarball(packed.tarball).map(({ path, content }) => ({\n path,\n bytes: content,\n kind: 'file' as const,\n })),\n )\n return {\n dir: target,\n version: packed.version,\n files: packed.files,\n tarball,\n integrity: packed.integrity,\n digest,\n }\n } catch (cause) {\n rmSync(target, { recursive: true, force: true })\n throw cause\n }\n}\n"],"mappings":";;;;;;;;;;AAkBA,SAAgB,gBACd,MACA,aACA,UAAU,SACV,SACyB;CACzB,OAAO;EACL;EACA;EACA;EACA,GAAI,YAAY,KAAA,IACZ,CAAC,IACD;GACE,SAAS,QAAQ;GACjB,YAAY;IACV,MAAM;IACN,KAAK,0BAA0B,QAAQ,MAAM,GAAG,QAAQ,KAAK;GAC/D;EACF;EACJ,MAAM;EACN,SAAS;GAAE,KAAK;GAAc,kBAAkB;EAAiB;EAIjE,kBAAkB,EAAE,uBAAuB,QAAQ;EACnD,UAAU;GAAC;GAAU;GAAiB;EAAa;CACrD;AACF;;AA4BA,MAAM,uBAAO,IAAI,IAAI;CACnB;CACA;C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,cAAc;CAAE,CAAC;CAC5F,IAAI;EACF,cACE,KAAK,QAAQ,cAAc,GAC3B,GAAG,KAAK,UAAU,gBAAgB,MAAM,aAAa,SAAS,QAAQ,OAAO,GAAG,MAAM,CAAC,EAAE,GAC3F;EACA,IAAI,CAAC,WAAW,KAAK,QAAQ,WAAW,CAAC,GACvC,cACE,KAAK,QAAQ,WAAW,GACxB,KAAK,KAAK,MAAM,YAAY,2KAC9B;EAEF,cAAc,MAAM;EACpB,MAAM,SAAS,kBAAkB,YAAY,MAAM,CAAC;EACpD,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,MACR,kCAAkC,OAAO,KAAK,UAAU,GAAG,MAAM,KAAK,IAAI,MAAM,QAAQ,CAAC,CAAC,KAAK,IAAI,GACrG;EAEF,MAAM,WAAW,MAAM,oBAAoB,MAAM;EACjD,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,wCAAwC,SAAS,OAAO,KAAK,IAAI,GAAG;EACtF,IAAI,QAAQ,YAAY,KAAA,GAAW,WAAW,MAAM;EACpD,MAAM,SAAS,WAAW,MAAM;EAChC,MAAM,UAAU,KAAK,UAAU,OAAO,QAAQ;EAC9C,cAAc,SAAS,OAAO,OAAO;EACrC,MAAM,SAAS,YACb,YAAY,OAAO,OAAO,CAAC,CAAC,KAAK,EAAE,MAAM,eAAe;GACtD;GACA,OAAO;GACP,MAAM;EACR,EAAE,CACJ;EACA,OAAO;GACL,KAAK;GACL,SAAS,OAAO;GAChB,OAAO,OAAO;GACd;GACA,WAAW,OAAO;GAClB;EACF;CACF,SAAS,OAAO;EACd,OAAO,QAAQ;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;EAC/C,MAAM;CACR;AACF"}
@@ -0,0 +1,170 @@
1
+ import { type ExtensionInfo } from '@acryldev/extensions';
2
+ import { type ReleasePort } from '@acryldev/plugin-hub-core';
3
+ import { type Context, Service } from '@deepseek-ai/cordis';
4
+ import { type NativeAction, type NativePorts } from './native.ts';
5
+ import { type PublishOptions, type PublishPlan, type PublishPorts, type PublishRefused, type PublishResult } from './publish.ts';
6
+ import { type PullRefused } from './pull-check.ts';
7
+ export type { PublishOptions, PublishPlan, PublishPorts, PublishRefused, PublishResult, } from './publish.ts';
8
+ /** One remembered plugin the app fetched again at its start because its folder was gone. */
9
+ export type RestoreOutcome = {
10
+ readonly name: string;
11
+ readonly ok: true;
12
+ } | {
13
+ readonly name: string;
14
+ readonly ok: false;
15
+ readonly reason: string;
16
+ readonly next: string;
17
+ };
18
+ export interface PluginShareConfig {
19
+ /** Where pulled plugins go; must be an extensions source. Defaults to `<project>/plugins`. */
20
+ dir?: string;
21
+ /** Where a `github:` source reads releases. Defaults to GitHub over HTTPS. */
22
+ releases?: ReleasePort;
23
+ /** Where a publish goes. Defaults to the person's own `gh` and `git`. */
24
+ publish?: PublishPorts;
25
+ /** 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. */
26
+ download?: (url: string) => Promise<Uint8Array>;
27
+ /** How a plugin's native package is downloaded and unpacked (native.ts). Defaults to the npm registry and the system's tar. */
28
+ native?: NativePorts;
29
+ }
30
+ export type PullResult = {
31
+ readonly ok: true;
32
+ readonly name: string;
33
+ readonly version: string;
34
+ /** The sha512 of the release's tarball, as the registry lists it. */
35
+ readonly integrity: string;
36
+ /** The sha256 of the plugin's content: the same on every OS. A source can name it (`@sha256:<digest>`). */
37
+ readonly digest: string;
38
+ readonly action: 'installed' | 'updated' | 'unchanged';
39
+ readonly state: string;
40
+ /** 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. */
41
+ readonly remembered: boolean;
42
+ /** The native package the plugin brought for this computer (native.ts), and what installing it did. */
43
+ readonly native?: {
44
+ readonly package: string;
45
+ readonly version: string;
46
+ readonly size: number;
47
+ readonly action: NativeAction;
48
+ };
49
+ } | PullRefused;
50
+ /** One source of a list and what pulling it did. */
51
+ export interface PullListEntry {
52
+ /** Its line in the list. */
53
+ readonly line: number;
54
+ readonly source: string;
55
+ readonly result: PullResult;
56
+ }
57
+ /** A list pulled: every source with its own result (some may be refused while the others install), or the list itself refused. */
58
+ export type PullListResult = {
59
+ readonly ok: true;
60
+ readonly from: string;
61
+ readonly entries: readonly PullListEntry[];
62
+ } | PullRefused;
63
+ /** 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. */
64
+ /** What extensions says about an installed plugin (its state, the services a pending one waits for, ...), and where a pulled one came from. */
65
+ export interface SharedPluginInfo extends ExtensionInfo {
66
+ /** 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. */
67
+ readonly pulledFrom?: string;
68
+ /** Who released it: the account of a `github:` source or of a release address on github.com. */
69
+ readonly author?: string;
70
+ /** The version its `package.json` names (`version` is the installed content's short digest); absent without one. */
71
+ readonly release?: string;
72
+ }
73
+ /** What removing a plugin did with its folder in `plugins/`. */
74
+ export type RemovedFolder =
75
+ /** It held the release as pulled, so nothing of anyone's is lost: the pull line brings it back. */
76
+ 'deleted'
77
+ /** 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. */
78
+ | 'kept' | 'none';
79
+ export type SharedRemoveResult = {
80
+ readonly ok: true;
81
+ readonly name: string;
82
+ readonly folder: RemovedFolder;
83
+ readonly note?: string;
84
+ } | {
85
+ readonly ok: false;
86
+ readonly name: string;
87
+ readonly errors: readonly string[];
88
+ };
89
+ declare module '@deepseek-ai/cordis' {
90
+ interface Context {
91
+ pluginShare: PluginShare;
92
+ }
93
+ }
94
+ export declare class PluginShare extends Service {
95
+ /** What was fetched again at this start. */
96
+ readonly restored: Promise<readonly RestoreOutcome[]>;
97
+ private readonly dir;
98
+ private readonly releases;
99
+ private readonly download;
100
+ private readonly ports;
101
+ /** One at a time: two pulls of one name must not race for its folder, nor two publishes for its package. */
102
+ private queue;
103
+ /** The content digest of each plugin pulled while the app runs, a local file's too, which `blend.yaml` does not remember. */
104
+ private readonly live;
105
+ private readonly nativeWork;
106
+ /** The native package each installed plugin brought for this computer: what its removal takes away. */
107
+ private readonly natives;
108
+ /**
109
+ * 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
110
+ * 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.
111
+ */
112
+ private readonly own;
113
+ constructor(ctx: Context, config: PluginShareConfig);
114
+ /** 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. */
115
+ pull(source: string): Promise<PullResult>;
116
+ /**
117
+ * 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
118
+ * 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.
119
+ * A list that cannot be read, or has a line that is not one source, pulls nothing.
120
+ */
121
+ pullList(from: string): Promise<PullListResult>;
122
+ /** The text of a list, or why it cannot be read. */
123
+ private readList;
124
+ /**
125
+ * 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
126
+ * 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.
127
+ */
128
+ pulledDigest(name: string): string | undefined;
129
+ /** The plugins installed while the app runs, each pulled one with its source and author. */
130
+ list(): SharedPluginInfo[];
131
+ /**
132
+ * 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
133
+ * folder with someone's work in it (this app's own plugin, or a pulled one changed since) stays, and the answer says so.
134
+ */
135
+ remove(name: string): Promise<SharedRemoveResult>;
136
+ private inTurn;
137
+ /**
138
+ * 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.
139
+ */
140
+ planPublish(name: string, options?: PublishOptions): Promise<PublishPlan | PublishRefused>;
141
+ /**
142
+ * 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
143
+ * is sent. Only the person's own surfaces call this: the frame's confirm and the terminal's prompt. No verb reaches it.
144
+ */
145
+ publish(name: string, confirmed: PublishPlan, options?: PublishOptions): Promise<PublishResult>;
146
+ /** 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. */
147
+ private remember;
148
+ private removeNow;
149
+ /** What `blend.yaml` remembers about one pulled plugin now. */
150
+ private recorded;
151
+ /** Fetch the remembered plugins whose folder is gone, exactly as recorded: other bytes are refused, and the record stays for the person to decide. */
152
+ private get places();
153
+ /** Remember the native package an installed plugin brought; one it no longer brings (an update) goes. The result's `native` field. */
154
+ private keepNative;
155
+ /** Take away the native package a removed plugin brought, unless another installed plugin brought the same one. */
156
+ private dropNative;
157
+ /** A pulled plugin that is here again links its native package again: an `npm install` puts the placeholder back in its place. */
158
+ private relinkNative;
159
+ private restore;
160
+ private get packages();
161
+ private planNow;
162
+ private pullNow;
163
+ /** Put the files in `plugins/<name>/` and install them; whatever does not end running takes its folder with it. */
164
+ private install;
165
+ }
166
+ export declare const pluginShare: {
167
+ name: string;
168
+ inject: string[];
169
+ apply(ctx: Context, config: PluginShareConfig): void;
170
+ };
@@ -0,0 +1,55 @@
1
+ /** Where a native package is downloaded from: the npm registry, and nothing else. */
2
+ export declare const NATIVE_REGISTRY = "https://registry.npmjs.org";
3
+ /** The most a plugin's native packages may unpack to, all of its entries for one computer together. */
4
+ export declare const NATIVE_MAX_BYTES = 1000000000;
5
+ /** The empty package the frame installs in place of an omitted one (frame/packages.json `omit.placeholder`). */
6
+ export declare const PLACEHOLDER = "@acryldev/absent";
7
+ export type NativeOs = 'darwin' | 'linux' | 'win32';
8
+ export type NativeCpu = 'arm64' | 'x64';
9
+ export interface NativePackage {
10
+ /** The npm package, as the package that needs it resolves it. */
11
+ readonly package: string;
12
+ /** Its exact version. */
13
+ readonly version: string;
14
+ readonly os: NativeOs;
15
+ /** Absent: any CPU of that OS (a WebAssembly build). */
16
+ readonly cpu?: NativeCpu;
17
+ /** npm's `dist.integrity` of the tarball. */
18
+ readonly integrity: string;
19
+ /** npm's `dist.unpackedSize`, in bytes: what a person is told before it is downloaded. */
20
+ readonly size: number;
21
+ }
22
+ /** The native packages a plugin's package.json declares (none without the field), or why the declaration cannot be used. */
23
+ export declare function nativesOf(manifest: Readonly<Record<string, unknown>>): {
24
+ readonly natives: readonly NativePackage[];
25
+ } | {
26
+ readonly error: string;
27
+ };
28
+ /** The entry for this computer: its OS, and its CPU or any. Undefined when the plugin brings nothing for it. */
29
+ export declare function nativeFor(natives: readonly NativePackage[], platform?: string, arch?: string): NativePackage | undefined;
30
+ /** The tarball's address in the npm registry, the way npm names it. */
31
+ export declare function tarballUrl(native: Pick<NativePackage, 'package' | 'version'>): string;
32
+ /** What a download and an unpack are, so a test can hand in local ones. */
33
+ export interface NativePorts {
34
+ /** Write the file at `url` to `file`. */
35
+ readonly download: (url: string, file: string) => Promise<void>;
36
+ /** Unpack the `.tgz` at `file` into `dir`, without the archive's top folder (npm's `package/`) and with the files' modes. */
37
+ readonly unpack: (file: string, dir: string) => Promise<void>;
38
+ }
39
+ /** 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. */
40
+ export declare function nativePorts(): NativePorts;
41
+ /** Where the app keeps what it downloaded, and where it links it. */
42
+ export interface NativePlaces {
43
+ /** The app's folder, whose `node_modules` the link goes into. */
44
+ readonly root: string;
45
+ /** The app's home, which keeps the downloads. */
46
+ readonly home: string;
47
+ }
48
+ /** The folder a native package is unpacked into. */
49
+ export declare function nativeStore(home: string, native: Pick<NativePackage, 'package' | 'version'>): string;
50
+ /** What `ensureNative` did: downloaded it, only linked a download it had, found it linked, or left a real copy npm installed. */
51
+ export type NativeAction = 'downloaded' | 'linked' | 'unchanged' | 'present';
52
+ /** 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. */
53
+ export declare function ensureNative(native: NativePackage, places: NativePlaces, ports?: NativePorts): Promise<NativeAction>;
54
+ /** Take the link away and, unless `keepDownload`, the download. A real copy npm installed is never touched. */
55
+ export declare function releaseNative(native: Pick<NativePackage, 'package' | 'version'>, places: NativePlaces, keepDownload?: boolean): void;
@@ -0,0 +1,30 @@
1
+ /** The package.json of a standalone plugin package: the host framework is a peer, never a second installed copy. */
2
+ export declare function packageManifest(name: string, description: string, version?: string, release?: PackageRelease): Record<string, unknown>;
3
+ /** Where a package is going to be released: written in now, so what is planned is byte for byte what is released. */
4
+ export interface PackageRelease {
5
+ readonly owner: string;
6
+ readonly repo: string;
7
+ readonly license: string;
8
+ }
9
+ export interface PackageOptions {
10
+ /** This version, instead of the one already packaged. */
11
+ readonly version?: string;
12
+ readonly release?: PackageRelease;
13
+ }
14
+ export interface PackagedPlugin {
15
+ readonly dir: string;
16
+ readonly version: string;
17
+ readonly files: readonly string[];
18
+ /** The release file, next to the package folder. */
19
+ readonly tarball: string;
20
+ /** The tarball's sha512, as the registry lists it. */
21
+ readonly integrity: string;
22
+ /** The sha256 of the plugin's content, which a source can name (`@sha256:<digest>`). */
23
+ readonly digest: string;
24
+ }
25
+ /**
26
+ * Package the plugin in `source` as `<packages>/<name>/` and `<packages>/<name>-<version>.tgz`. The person's folder is not touched. A version already
27
+ * packaged stays: a release is made once, and a person bumps it deliberately.
28
+ * @throws when the plugin would not work on every OS or its contract cannot be read; no package is left.
29
+ */
30
+ export declare function packagePlugin(source: string, packages: string, name: string, description: string, options?: PackageOptions): Promise<PackagedPlugin>;