dsh-multi-device-config-sync 0.0.0-stage → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/plugins.js ADDED
@@ -0,0 +1,469 @@
1
+ /**
2
+ * Which of the profile's declared plugins this machine actually has, and the one
3
+ * action that closes the gap.
4
+ *
5
+ * A restore writes a manifest, not an installation. `package.json` and
6
+ * `dsh.profile.bundles` arrive as text; the packages they name do not, because
7
+ * installed plugins are never part of a backup. DSH survives that — it logs
8
+ * `skipping profile bundle "..."` and boots — but the plugins are not there, so
9
+ * the page has to be able to answer the question a restore raises and cannot
10
+ * settle by itself: what is declared here that this machine does not have?
11
+ *
12
+ * The answer comes from the host's `pluginManager` service when the deployment
13
+ * publishes one. That service is optional, so "cannot check" is a first-class
14
+ * answer here: it is `available: false` with a reason and no verdict at all,
15
+ * because "nothing is missing" and "nobody looked" are different statements and
16
+ * only one of them deserves a green line. Nothing in this module throws for a
17
+ * service that is absent, that throws, or that answers a shape it does not
18
+ * recognize — the page has to be told, not taken down.
19
+ *
20
+ * Installing is deliberately additive. The only mutation performed here is
21
+ * `installBundle`, one spec at a time; nothing is ever removed or disabled, no
22
+ * bundle selection is rewritten, and the spec handed over is the one the
23
+ * manifest already declares (or the manager's own `source` for that dependency),
24
+ * so a successful install saves the same value back instead of resolving a new
25
+ * range behind the reader's back.
26
+ */
27
+ import { existsSync, readFileSync } from 'node:fs'
28
+ import { join } from 'node:path'
29
+ import { isMachineLocalSpec, profileRoot, syncPackageOmission } from './backup.js'
30
+
31
+ /** Outcome vocabulary the install route answers with, in report order. */
32
+ export const INSTALL_OUTCOMES = ['installed', 'already-present', 'failed', 'skipped']
33
+
34
+ /** Outcome notes the client localizes, keyed as `note.<value>`. */
35
+ export const LOCAL_SPEC_NOTES = {
36
+ 'local-path': 'local-path',
37
+ 'workspace-protocol': 'workspace-protocol',
38
+ }
39
+
40
+ /**
41
+ * A `name@link:…`-shaped machine-local spec. The plugin manager's own `source`
42
+ * field is a whole `pnpm add` argument, so it prefixes the package name to the
43
+ * recorded value; `isMachineLocalSpec` alone would not see the `link:` through
44
+ * that prefix.
45
+ */
46
+ const PREFIXED_LOCAL_RE = /^(?:@[^/\\]+[/\\])?[^@/\\]+@(?:link|file|portal|workspace):/i
47
+
48
+ /** A spec pnpm resolves by itself: a URL, a git address, or a tarball. */
49
+ const SELF_RESOLVING_RE = /^(?:https?:\/\/|git\+|git:\/\/|ssh:\/\/|git@[^:/\s]+:|github:|gitlab:|bitbucket:)/i
50
+
51
+ /** A value this module accepts as a package name. */
52
+ const PACKAGE_NAME_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/
53
+ export const validPackageName = name => typeof name === 'string' && name.length <= 214 && PACKAGE_NAME_RE.test(name) && !['node_modules', 'constructor', 'prototype'].includes(name)
54
+
55
+ /** A dependency map, or an empty one for anything else. */
56
+ function dependencyMap(value) {
57
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {}
58
+ }
59
+
60
+ /** A thrown value's message, whatever was thrown. */
61
+ function messageOf(error) {
62
+ if (error instanceof Error && typeof error.message === 'string') return error.message
63
+ return String(error)
64
+ }
65
+
66
+ /**
67
+ * The package name a manager row names, or null when the row names no package.
68
+ *
69
+ * `listPlugins()` reports a module specifier, which for a profile dependency is
70
+ * the dependency name but can also carry a subpath (`@scope/pkg/lib/x.js`) or be
71
+ * a relative path or file URL for something composed from the profile itself.
72
+ * Only the first one or two segments of a plausible package specifier are kept;
73
+ * everything else is refused rather than guessed at, because a wrong name here
74
+ * would mask a genuinely missing plugin.
75
+ * @param {unknown} value - a row field.
76
+ */
77
+ function packageNameOf(value) {
78
+ if (typeof value !== 'string') return null
79
+ const trimmed = value.trim()
80
+ if (trimmed === '' || trimmed.startsWith('.') || trimmed.includes('://') || /^[A-Za-z]:/.test(trimmed)) return null
81
+ const parts = trimmed.replaceAll('\\', '/').split('/').filter(part => part !== '')
82
+ if (parts.length === 0) return null
83
+ const name = parts[0].startsWith('@') && parts.length > 1 ? `${parts[0]}/${parts[1]}` : parts[0]
84
+ return PACKAGE_NAME_RE.test(name) ? name : null
85
+ }
86
+
87
+ /**
88
+ * The note for a machine-local spec, or null when the spec is installable.
89
+ * @param {string} value - the spec, with or without a `name@` prefix.
90
+ */
91
+ function localNote(value) {
92
+ const prefixed = PREFIXED_LOCAL_RE.test(value)
93
+ if (!prefixed && !isMachineLocalSpec(value)) return null
94
+ return /(?:^|@)workspace:/i.test(value) ? LOCAL_SPEC_NOTES['workspace-protocol'] : LOCAL_SPEC_NOTES['local-path']
95
+ }
96
+
97
+ /**
98
+ * The profile's declared plugins, in manifest order.
99
+ *
100
+ * Dependencies come first because they carry the spec an install needs. A name
101
+ * only `dsh.profile.bundles` names follows with no spec at all — that is exactly
102
+ * what a dropped machine-local dependency leaves behind, and it is a statement
103
+ * of intent DSH tolerates, so it is listed rather than hidden.
104
+ * @param {string} root - the profile directory.
105
+ * @returns {Array<{ name: string, spec: string | null, kind: 'dependency' | 'bundle' | 'both' }>}
106
+ */
107
+ export function declaredPlugins(root) {
108
+ let manifest = null
109
+ try {
110
+ manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
111
+ } catch {
112
+ // An unreadable profile manifest has no declared plugins; the route that
113
+ // needed it reports the missing profile separately.
114
+ return []
115
+ }
116
+ return declarationsFromManifest(manifest)
117
+ }
118
+
119
+ /** Also accepts the downloaded manifest, without writing it to disk for a preview. */
120
+ export function declarationsFromManifest(manifest) {
121
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) return []
122
+ const dependencies = dependencyMap(manifest.dependencies)
123
+ const profile = dependencyMap(dependencyMap(manifest.dsh).profile)
124
+ const bundles = new Set(Array.isArray(profile.bundles)
125
+ ? profile.bundles.filter(name => typeof name === 'string' && name.trim() !== '') : [])
126
+ const declared = []
127
+ for (const [name, spec] of Object.entries(dependencies)) {
128
+ declared.push({
129
+ name,
130
+ spec: typeof spec === 'string' ? spec : null,
131
+ kind: bundles.has(name) ? 'both' : 'dependency',
132
+ })
133
+ }
134
+ for (const name of bundles) {
135
+ if (Object.hasOwn(dependencies, name)) continue
136
+ declared.push({ name, spec: null, kind: 'bundle' })
137
+ }
138
+ return declared
139
+ }
140
+
141
+ /**
142
+ * The install spec to hand `pluginManager.installBundle`, or why this machine
143
+ * cannot install it.
144
+ *
145
+ * Every value that names a path — `link:`, `file:`, `portal:`, `workspace:`, a
146
+ * bare `/x` or `E:/x`, and the `name@link:…` form the manager reports as
147
+ * `source` — is refused with a note instead of a spec. Such a value is a
148
+ * statement about the filesystem of the machine that wrote the manifest; pnpm
149
+ * would fail on it here, and naming the reason up front is worth more than a
150
+ * guaranteed failure. A registry range, tag, or alias is composed back into
151
+ * `name@spec` so pnpm saves the spec the manifest already declares.
152
+ * @param {string} name - the declared package name.
153
+ * @param {string | null} spec - the manifest's value, when it has one.
154
+ * @param {unknown} source - the `source` a bundle row reported, when it did.
155
+ * @returns {{ installSpec: string | null, resolvable: boolean, note: string | null }}
156
+ */
157
+ export function installSpecFor(name, spec, source) {
158
+ const reported = typeof source === 'string' && source.trim() !== '' ? source.trim() : null
159
+ const recorded = reported ?? (typeof spec === 'string' && spec.trim() !== '' ? spec.trim() : null)
160
+ if (!validPackageName(name)) return { installSpec: null, resolvable: false, note: 'invalid-name' }
161
+ // A stale declaration left in this local profile is still missing, not an
162
+ // alias for an installed package and not consent to reinstall the sync tool.
163
+ const omission = syncPackageOmission(name)
164
+ if (omission !== null) return { installSpec: null, resolvable: false, note: omission }
165
+ if (recorded === null) return { installSpec: null, resolvable: false, note: 'missing-source' }
166
+ const note = localNote(recorded)
167
+ if (note !== null) return { installSpec: null, resolvable: false, note }
168
+ // A reported `source` is already a whole `pnpm add` argument; a manifest value
169
+ // is only the version part and needs its package name back.
170
+ if (reported !== null) return { installSpec: recorded, resolvable: true, note: null }
171
+ if (SELF_RESOLVING_RE.test(recorded)) return { installSpec: recorded, resolvable: true, note: null }
172
+ return { installSpec: `${name}@${recorded}`, resolvable: true, note: null }
173
+ }
174
+
175
+ /** A cloud copy describes sources, not shell arguments or paths on this machine. */
176
+ function portableSpec(name, spec) {
177
+ const ordinary = installSpecFor(name, spec, null)
178
+ if (!ordinary.resolvable) return ordinary
179
+ const value = spec.trim()
180
+ const denied = { installSpec: null, resolvable: false, note: 'unsupported-source' }
181
+ if (value.length > 2048 || /[\x00-\x1f\x7f]/.test(value)) return denied
182
+ // npm versions/ranges/dist-tags, and explicit registry aliases.
183
+ const range = /^[A-Za-z0-9*^~<>=][A-Za-z0-9*^~<>=.|+ -]*$/
184
+ if (range.test(value)) return ordinary
185
+ if (/^npm:(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+(?:@[A-Za-z0-9*^~<>=.|+ -]+)?$/i.test(value)) return ordinary
186
+ if (/^(?:github|gitlab|bitbucket):[\w.-]+\/[\w.-]+(?:#[\w./-]+)?$/i.test(value)) return ordinary
187
+ if (/^git@[a-z0-9.-]+:[\w./-]+(?:#[\w./-]+)?$/i.test(value)) return ordinary
188
+ if (/^(?:https:|git\+https:|git\+ssh:|ssh:)\/\//i.test(value)) {
189
+ try {
190
+ const u = new URL(value)
191
+ // In particular, do not echo a password-bearing Git URL in the preview.
192
+ if (u.hostname && !u.password && !u.search && (!u.username || (u.protocol.endsWith('ssh:') && u.username === 'git'))) return ordinary
193
+ } catch { /* unsupported spec */ }
194
+ }
195
+ return denied
196
+ }
197
+
198
+ /**
199
+ * Whether the profile's own dependency tree holds the package, as a third piece
200
+ * of evidence beside the two inventory services.
201
+ *
202
+ * `listBundles()` describes bundles and dependencies it can resolve, and omits a
203
+ * dependency that is present but neither selected nor a bundle at all;
204
+ * `listPlugins()` describes the loader's entries and says nothing about a
205
+ * package that is installed but not composed. The disk is where such a package
206
+ * still is, and checking it is what keeps a plain library dependency from being
207
+ * reported as a missing plugin.
208
+ * @param {string} root - the profile directory.
209
+ * @param {string} name - the package name.
210
+ */
211
+ function installedOnDisk(root, name) {
212
+ if (!validPackageName(name)) return false
213
+ return existsSync(join(root, 'node_modules', name, 'package.json'))
214
+ }
215
+
216
+ /**
217
+ * The host's plugin manager, by either access style a Cordis context offers.
218
+ *
219
+ * The service is reached as `ctx.pluginManager`, which is the documented access;
220
+ * `ctx.get('pluginManager')` is the style the rest of this plugin uses for
221
+ * optional services, and a host that publishes one but not the other still has
222
+ * to work. A context whose service lookup throws reports no manager rather than
223
+ * failing the request.
224
+ * @param {unknown} ctx - the host context.
225
+ */
226
+ function managerOf(ctx) {
227
+ try {
228
+ const direct = /** @type {{ pluginManager?: unknown }} */ (ctx)?.pluginManager
229
+ if (direct !== null && typeof direct === 'object') return direct
230
+ } catch {
231
+ // A context without the service can throw on property access.
232
+ }
233
+ try {
234
+ const fetched = /** @type {{ get?: (name: string) => unknown }} */ (ctx)?.get?.('pluginManager')
235
+ return fetched !== null && typeof fetched === 'object' ? fetched : null
236
+ } catch {
237
+ return null
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Package names this machine can already see, plus the bundle rows seen on the
243
+ * way (their `source` is the spec an install of that dependency needs).
244
+ * @param {string} root - the profile directory.
245
+ * @param {object} manager - the plugin manager service.
246
+ */
247
+ async function presentInventory(root, manager, declared) {
248
+ const names = new Set()
249
+ const bundles = new Map()
250
+ const sources = { plugins: false, bundles: false }
251
+ try {
252
+ const plugins = await manager.listPlugins()
253
+ if (Array.isArray(plugins)) {
254
+ sources.plugins = true
255
+ for (const entry of plugins) {
256
+ const name = packageNameOf(entry?.moduleName)
257
+ if (name !== null) names.add(name)
258
+ }
259
+ }
260
+ } catch {
261
+ // An inventory this host cannot read is not an answer; the caller reports
262
+ // which sources answered instead of pretending the reading succeeded.
263
+ }
264
+ try {
265
+ const rows = await manager.listBundles()
266
+ if (Array.isArray(rows)) {
267
+ sources.bundles = true
268
+ for (const row of rows) {
269
+ const name = typeof row?.name === 'string' ? row.name : null
270
+ if (name === null) continue
271
+ bundles.set(name, row)
272
+ // An installation-provided bundle is on disk; a catalogue offer alone isn't.
273
+ // A missing row also takes precedence over a stale loader entry.
274
+ if (row.availability === 'missing') names.delete(name)
275
+ else if (row.availability === 'installation' || row.installed !== false) names.add(name)
276
+ }
277
+ }
278
+ } catch {
279
+ // Same as above.
280
+ }
281
+ for (const entry of declared) {
282
+ if (installedOnDisk(root, entry.name)) names.add(entry.name)
283
+ }
284
+ return { names, bundles, sources }
285
+ }
286
+
287
+ /**
288
+ * What the profile declares and this machine does not have.
289
+ *
290
+ * Two shapes are possible, and they are deliberately different rather than one
291
+ * shape with zeros in it. When the manager answered, the payload carries
292
+ * `installed`, `missing`, and `counts` — a real verdict. When it did not, the
293
+ * payload carries `available: false` and a `reason`, and deliberately carries no
294
+ * `missing` array at all, so a reader that forgets to look at `available` fails
295
+ * loudly instead of showing an empty list as a clean bill of health.
296
+ * @param {unknown} ctx - the host context.
297
+ * @returns {Promise<object>} the `/api/plugins` answer.
298
+ */
299
+ export async function pluginInventory(ctx, cloudDeclarations = null) {
300
+ const checkedAt = new Date().toISOString()
301
+ const root = profileRoot()
302
+ const declared = cloudDeclarations ?? declaredPlugins(root)
303
+ const manager = managerOf(ctx)
304
+ if (manager === null || (cloudDeclarations !== null && typeof manager.installBundle !== 'function')) {
305
+ return { available: false, reason: 'no-plugin-manager', checkedAt, declared: declared.length }
306
+ }
307
+ const present = await presentInventory(root, manager, declared)
308
+ if (!present.sources.plugins && !present.sources.bundles) {
309
+ return { available: false, reason: 'plugin-manager-error', checkedAt, declared: declared.length }
310
+ }
311
+ const installed = []
312
+ const missing = []
313
+ for (const entry of declared) {
314
+ if (present.names.has(entry.name)) {
315
+ installed.push(entry.name)
316
+ continue
317
+ }
318
+ const row = present.bundles.get(entry.name)
319
+ const spec = cloudDeclarations === null
320
+ ? installSpecFor(entry.name, entry.spec, row?.source)
321
+ : portableSpec(entry.name, entry.spec)
322
+ missing.push({
323
+ name: entry.name,
324
+ spec: spec.note === 'unsupported-source' || syncPackageOmission(entry.name) !== null ? null : entry.spec,
325
+ kind: entry.kind,
326
+ installSpec: spec.installSpec,
327
+ resolvable: spec.resolvable,
328
+ note: spec.note,
329
+ version: typeof row?.version === 'string' ? row.version : null,
330
+ })
331
+ }
332
+ return {
333
+ available: true,
334
+ reason: null,
335
+ checkedAt,
336
+ sources: present.sources,
337
+ installed,
338
+ missing,
339
+ counts: {
340
+ declared: declared.length,
341
+ installed: installed.length,
342
+ missing: missing.length,
343
+ installable: missing.filter(entry => entry.resolvable).length,
344
+ unresolved: missing.filter(entry => !entry.resolvable).length,
345
+ },
346
+ }
347
+ }
348
+
349
+ /**
350
+ * One `installBundle` answer as an outcome the page can print.
351
+ *
352
+ * The manager reports what it *did* (`application`) together with a coded error.
353
+ * A refusal of an already-installed package is the second run of this same
354
+ * route, which is not a failure; a build script left unapproved is not a failure
355
+ * either, but the package will not work until it is approved on the plugins
356
+ * page, so the names are carried out rather than swallowed.
357
+ * @param {object} entry - one row of the missing list.
358
+ * @param {unknown} result - the manager's change result.
359
+ */
360
+ function outcomeOf(entry, result) {
361
+ const value = /** @type {Record<string, any>} */ (result ?? {})
362
+ const application = typeof value.application === 'string' ? value.application : null
363
+ const code = typeof value.error?.code === 'string' ? value.error.code : null
364
+ const diagnostic = typeof value.error?.diagnostic === 'string' ? value.error.diagnostic : null
365
+ const version = typeof value.version === 'string' ? value.version : null
366
+ const pendingBuilds = Array.isArray(value.pendingBuilds)
367
+ ? value.pendingBuilds.filter(name => typeof name === 'string')
368
+ : []
369
+ const base = { name: entry.name, spec: entry.spec, installSpec: entry.installSpec, version, pendingBuilds }
370
+ if (code === 'already-installed') return { ...base, outcome: 'already-present', application, message: null }
371
+ if (code !== null || !['applied', 'restart-required'].includes(application)) {
372
+ return { ...base, outcome: 'failed', application, message: diagnostic ?? code ?? application ?? 'failed' }
373
+ }
374
+ return { ...base, outcome: 'installed', application, message: null }
375
+ }
376
+
377
+ /** A zeroed outcome tally. */
378
+ function emptyOutcomes() {
379
+ const counts = {}
380
+ for (const outcome of INSTALL_OUTCOMES) counts[outcome] = 0
381
+ return counts
382
+ }
383
+
384
+ /**
385
+ * Install every declared plugin this machine is missing, one spec at a time.
386
+ *
387
+ * Safe to run twice by construction rather than by hope: a name that is already
388
+ * present is skipped before the manager is called at all, and a manager that
389
+ * refuses an installed package answers `already-installed`, which is reported as
390
+ * `already-present` rather than as a failure. Nothing here removes or disables
391
+ * anything — the install calls are the only mutation this module makes.
392
+ *
393
+ * Installs run strictly one after another. Every call takes the profile's
394
+ * `package.json` lock and runs a package manager; issuing them together would
395
+ * only queue behind that lock while making each outcome impossible to attribute
396
+ * to the spec that produced it.
397
+ * @param {unknown} ctx - the host context.
398
+ * @returns {Promise<object>} the `/api/plugins/install` answer.
399
+ */
400
+ export async function installMissingPlugins(ctx, { declarations = null, approved = null, selected = null } = {}) {
401
+ const before = await pluginInventory(ctx, declarations)
402
+ if (before.available !== true) {
403
+ return { ...before, results: [], outcomeCounts: emptyOutcomes(), restart: false }
404
+ }
405
+ const manager = /** @type {object} */ (managerOf(ctx))
406
+ const results = []
407
+ for (const entry of before.missing) {
408
+ if (entry.installSpec === null || (approved && approved.get(entry.name) !== entry.installSpec)) {
409
+ results.push({
410
+ name: entry.name,
411
+ spec: entry.spec,
412
+ installSpec: null,
413
+ outcome: 'skipped',
414
+ application: null,
415
+ version: null,
416
+ message: entry.note ?? 'stale-plan',
417
+ pendingBuilds: [],
418
+ })
419
+ continue
420
+ }
421
+ try {
422
+ const options = selected ? { enabled: selected.has(entry.name) } : undefined
423
+ if (options && /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/.test(entry.spec)) {
424
+ options.expected = { name: entry.name, version: entry.spec }
425
+ options.saveExact = true
426
+ }
427
+ results.push(outcomeOf(entry, await manager.installBundle(entry.installSpec, options)))
428
+ } catch (error) {
429
+ results.push({
430
+ name: entry.name,
431
+ spec: entry.spec,
432
+ installSpec: entry.installSpec,
433
+ outcome: 'failed',
434
+ application: null,
435
+ version: null,
436
+ message: messageOf(error),
437
+ pendingBuilds: [],
438
+ })
439
+ }
440
+ }
441
+ // Re-read rather than assume: an installation that saved its dependency and
442
+ // one that failed to are told apart by what the manager reports now, not by
443
+ // what this run asked for.
444
+ const after = await pluginInventory(ctx, declarations)
445
+ if (declarations && after.available) {
446
+ const stillMissing = new Set(after.missing.map(row => row.name))
447
+ for (const result of results) {
448
+ if (stillMissing.has(result.name) && (result.outcome === 'already-present' || result.outcome === 'installed')) {
449
+ result.outcome = 'failed'
450
+ result.message = 'The package is still missing after the installer returned. Check its entry in Plugins.'
451
+ }
452
+ }
453
+ }
454
+ const outcomeCounts = emptyOutcomes()
455
+ for (const result of results) outcomeCounts[result.outcome] += 1
456
+ return {
457
+ available: after.available,
458
+ reason: after.reason,
459
+ checkedAt: after.checkedAt,
460
+ declared: after.declared,
461
+ ...(after.sources === undefined ? {} : { sources: after.sources }),
462
+ installed: after.installed ?? [],
463
+ missing: after.missing ?? [],
464
+ counts: after.counts ?? null,
465
+ results,
466
+ outcomeCounts,
467
+ restart: results.some(result => result.outcome === 'installed'),
468
+ }
469
+ }