@aiwayds/dsh-opentui 0.17.3 → 0.18.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,406 @@
1
+ // Pure planning logic for the `upgrade` subcommand and for the downgrade
2
+ // guard that provisioning shares with it.
3
+ //
4
+ // Same split as provision-plan.mjs (see its header): no filesystem, no
5
+ // child_process, no network. The caller reads `.npmrc` files, spawns
6
+ // `npm view`, and writes the override file; this module only decides what
7
+ // those actions should be, so every decision is unit-testable from plain
8
+ // fixtures.
9
+ //
10
+ // Version ordering is NOT re-implemented here. provision-plan.mjs already
11
+ // exports parseVersion/compareVersions (a deliberately small semver subset)
12
+ // and owns the shipped pins, so both the upgrade command and provisioning
13
+ // must judge "newer" with the same rule; a second copy would be free to drift.
14
+
15
+ import { compareVersions, parseVersion, resolveEffectivePin } from './provision-plan.mjs'
16
+
17
+ export const OFFICIAL_REGISTRY = 'https://registry.npmjs.org'
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Registry resolution
21
+ // ---------------------------------------------------------------------------
22
+
23
+ /** A .npmrc value ends at a `#` comment; surrounding quotes are optional.
24
+ * npm allows `key = "value"` and `registry=https://host/` alike. */
25
+ function cleanRegistryValue(raw) {
26
+ let text = String(raw)
27
+ const comment = text.indexOf('#')
28
+ if (comment !== -1) text = text.slice(0, comment)
29
+ text = text.trim()
30
+ const quoted = /^(['"])(.*)\1$/.exec(text)
31
+ if (quoted) text = quoted[2].trim()
32
+ return text
33
+ }
34
+
35
+ function stripTrailingSlashes(value) {
36
+ return String(value).replace(/\/+$/, '')
37
+ }
38
+
39
+ /** Last `registry=` line across all texts wins: later files override earlier
40
+ * ones, and inside one file the last assignment wins, which is how npm's
41
+ * own config layering behaves. */
42
+ function registryFromNpmrcTexts(npmrcTexts) {
43
+ let found = ''
44
+ for (const text of npmrcTexts) {
45
+ if (typeof text !== 'string') continue
46
+ for (const line of text.split(/\r?\n/)) {
47
+ const match = /^\s*registry\s*=\s*(.+)$/i.exec(line)
48
+ if (!match) continue
49
+ const value = cleanRegistryValue(match[1])
50
+ if (value) found = value
51
+ }
52
+ }
53
+ return found
54
+ }
55
+
56
+ /**
57
+ * Where the `npm view` query should go.
58
+ *
59
+ * Priority: DSH_UPGRADE_REGISTRY (explicit operator override) -> the npmrc
60
+ * texts the caller read, last one winning -> the public registry.
61
+ *
62
+ * `npmrcTexts` is a list of file *contents*, not paths: this module does no
63
+ * IO, and the caller decides which files apply (user, global, profile).
64
+ * The returned registry never ends with `/` so argv and string comparisons
65
+ * stay canonical.
66
+ *
67
+ * @param {{ env?: Record<string, string|undefined>, npmrcTexts?: string[] }} [input]
68
+ * @returns {{ registry: string, source: 'env'|'npmrc'|'default' }}
69
+ */
70
+ export function resolveRegistry({ env = {}, npmrcTexts = [] } = {}) {
71
+ const rawEnv = env && typeof env === 'object' ? env.DSH_UPGRADE_REGISTRY : undefined
72
+ const fromEnv = typeof rawEnv === 'string' ? stripTrailingSlashes(cleanRegistryValue(rawEnv)) : ''
73
+ if (fromEnv) return { registry: fromEnv, source: 'env' }
74
+
75
+ const fromNpmrc = stripTrailingSlashes(registryFromNpmrcTexts(Array.isArray(npmrcTexts) ? npmrcTexts : []))
76
+ if (fromNpmrc) return { registry: fromNpmrc, source: 'npmrc' }
77
+
78
+ return { registry: OFFICIAL_REGISTRY, source: 'default' }
79
+ }
80
+
81
+ /**
82
+ * Is this the public npm registry (as opposed to a mirror)? A mirror can lag
83
+ * behind upstream, which is worth a warning line in the plan output.
84
+ * Accepts the bare host and both URL spellings, with or without a trailing
85
+ * slash; the path and protocol are otherwise ignored.
86
+ */
87
+ export function isOfficialRegistry(registry) {
88
+ if (typeof registry !== 'string') return false
89
+ return /^(?:https?:\/\/)?registry\.npmjs\.org\/*$/i.test(registry.trim())
90
+ }
91
+
92
+ /**
93
+ * argv for `npm view <pkg> dist-tags --json`.
94
+ *
95
+ * `dist-tags` returns every tag (latest, next, ...) in one call, so a single
96
+ * invocation answers "what would --tag next resolve to" as well.
97
+ *
98
+ * `--prefer-online` is mandatory: without it npm answers from its local cache
99
+ * (including negative cache entries), so a freshly published version can be
100
+ * invisible for hours. `--registry` is mandatory too, because the machine's
101
+ * configured registry may be a lagging mirror.
102
+ *
103
+ * `--fetch-retries 0` and `--fetch-timeout 20000` are part of the query, not a
104
+ * tuning afterthought: an unreachable registry otherwise costs npm's default
105
+ * retry ladder (2 retries with backoff) per package, which made a `--dry-run`
106
+ * against a dead host take minutes before reporting `query-failed`. An
107
+ * unreachable host is answered either way — only the wait differs, and no
108
+ * retry can turn it into an answer.
109
+ *
110
+ * @param {{ pkg: string, registry: string }} input
111
+ * @returns {string[]}
112
+ */
113
+ export function buildViewArgs({ pkg, registry } = {}) {
114
+ if (typeof pkg !== 'string' || pkg === '') {
115
+ throw new TypeError('buildViewArgs: pkg must be a non-empty string')
116
+ }
117
+ if (typeof registry !== 'string' || registry === '') {
118
+ throw new TypeError('buildViewArgs: registry must be a non-empty string')
119
+ }
120
+ return [
121
+ 'view',
122
+ pkg,
123
+ 'dist-tags',
124
+ '--json',
125
+ '--registry',
126
+ registry,
127
+ '--prefer-online',
128
+ '--fetch-retries',
129
+ '0',
130
+ '--fetch-timeout',
131
+ '20000',
132
+ ]
133
+ }
134
+
135
+ // ---------------------------------------------------------------------------
136
+ // Which dependencies the upgrade command may touch
137
+ // ---------------------------------------------------------------------------
138
+
139
+ const NON_REGISTRY_SPEC = /^(?:link|file|workspace|portal):|^(?:git\+|https?:)/i
140
+
141
+ /**
142
+ * May the upgrade command replace this dependency's spec with a registry
143
+ * version?
144
+ *
145
+ * Never: host-closure packages (`@deepseek-ai/*`) — the host pins those and a
146
+ * profile-local upgrade would fight it — and specs that do not point at a
147
+ * registry (`link:`, `file:`, `workspace:`, `portal:`, `git+`, `http(s):`),
148
+ * e.g. the profile's local `link:` dev dependency.
149
+ * Everything else (caret, tilde, exact, `*`) is upgradable; a non-string spec
150
+ * is not, because there is nothing to resolve.
151
+ */
152
+ export function isUpgradableDependency(name, spec) {
153
+ if (typeof name !== 'string' || name.startsWith('@deepseek-ai/')) return false
154
+ if (typeof spec !== 'string') return false
155
+ return !NON_REGISTRY_SPEC.test(spec.trim())
156
+ }
157
+
158
+ /** The exact version a spec names, if it names one (`1.2.3`, `=1.2.3`);
159
+ * ranges (`^1.2.3`, `~1.2.3`, `*`) answer null. */
160
+ function exactVersionFromSpec(spec) {
161
+ if (typeof spec !== 'string') return null
162
+ const text = spec.trim().replace(/^=\s*/, '')
163
+ return parseVersion(text) ? text : null
164
+ }
165
+
166
+ function byName(a, b) {
167
+ if (a.name === b.name) return 0
168
+ return a.name < b.name ? -1 : 1
169
+ }
170
+
171
+ const ACTION_ORDER = ['upgrade', 'latest', 'excluded', 'query-failed']
172
+ const COUNT_KEY = {
173
+ upgrade: 'upgrade',
174
+ latest: 'latest',
175
+ excluded: 'excluded',
176
+ 'query-failed': 'queryFailed',
177
+ }
178
+
179
+ /**
180
+ * Turn "manifest deps + installed versions + registry answers" into the plan
181
+ * table the command prints and executes.
182
+ *
183
+ * Per dependency:
184
+ * - `excluded` — isUpgradableDependency says no (checked first)
185
+ * - `query-failed` — the caller has no dist-tag answer for the package
186
+ * - `latest` — installed version equals the registry target
187
+ * - `upgrade` — everything else, including "installed unknown"
188
+ *
189
+ * `current` prefers the version on disk (`installedVersions`); when the caller
190
+ * could not read it, the exact version in the spec is the best available
191
+ * truth. `null` means unknown and is never treated as up to date.
192
+ * `target` is null only for rows that have no registry answer (`query-failed`).
193
+ *
194
+ * Row order is stable: upgrades first (by name), then latest, excluded, and
195
+ * query-failed, each sorted by name, so two runs over the same inputs print
196
+ * the same table.
197
+ *
198
+ * `tag` names the dist-tag the caller queried; its value already lives in
199
+ * `latestByPkg`, so this function does not need it. It stays in the signature
200
+ * because the plan header reports it.
201
+ *
202
+ * @param {{
203
+ * deps: Record<string, string>,
204
+ * installedVersions?: Record<string, string>,
205
+ * latestByPkg?: Record<string, string>,
206
+ * tag?: string,
207
+ * }} input
208
+ * @returns {{
209
+ * rows: Array<{ name: string, currentSpec: string, current: string|null, target: string|null, action: 'upgrade'|'latest'|'excluded'|'query-failed' }>,
210
+ * counts: { upgrade: number, latest: number, excluded: number, queryFailed: number },
211
+ * }}
212
+ */
213
+ export function buildUpgradePlan({ deps, installedVersions = {}, latestByPkg = {}, tag = 'latest' } = {}) {
214
+ const dependencies = deps && typeof deps === 'object' ? deps : {}
215
+ const installed = installedVersions && typeof installedVersions === 'object' ? installedVersions : {}
216
+ const latest = latestByPkg && typeof latestByPkg === 'object' ? latestByPkg : {}
217
+ void tag // documented above: the caller has already resolved it into latestByPkg
218
+
219
+ const rows = []
220
+ for (const [name, spec] of Object.entries(dependencies)) {
221
+ const currentSpec = typeof spec === 'string' ? spec : null
222
+ const rawInstalled = installed[name]
223
+ const current =
224
+ typeof rawInstalled === 'string' && rawInstalled !== ''
225
+ ? rawInstalled
226
+ : exactVersionFromSpec(currentSpec)
227
+ const rawTarget = latest[name]
228
+ const target = typeof rawTarget === 'string' && rawTarget !== '' ? rawTarget : null
229
+
230
+ let action
231
+ if (!isUpgradableDependency(name, currentSpec)) action = 'excluded'
232
+ else if (target === null) action = 'query-failed'
233
+ else if (current !== null && current === target) action = 'latest'
234
+ else action = 'upgrade'
235
+
236
+ rows.push({ name, currentSpec, current, target, action })
237
+ }
238
+
239
+ const counts = { upgrade: 0, latest: 0, excluded: 0, queryFailed: 0 }
240
+ for (const row of rows) counts[COUNT_KEY[row.action]] += 1
241
+
242
+ const ordered = []
243
+ for (const action of ACTION_ORDER) {
244
+ ordered.push(...rows.filter((row) => row.action === action).sort(byName))
245
+ }
246
+
247
+ return { rows: ordered, counts }
248
+ }
249
+
250
+ // ---------------------------------------------------------------------------
251
+ // upgrade-overrides.json — the file that stops the next start from
252
+ // downgrading a package the upgrade command raised above the shipped pin.
253
+ // ---------------------------------------------------------------------------
254
+
255
+ function isPlainObject(value) {
256
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
257
+ }
258
+
259
+ /** An entry is either the bare version string or an object carrying a
260
+ * `version` (e.g. `{ version, shippedPin, updatedAt }`). The bare form is
261
+ * accepted for hand-written files; the object form is what the command
262
+ * writes and what provisioning reads. */
263
+ function entryVersion(entry) {
264
+ if (typeof entry === 'string') return entry.trim()
265
+ if (isPlainObject(entry) && typeof entry.version === 'string') return entry.version.trim()
266
+ return null
267
+ }
268
+
269
+ /** The name -> entry map of an override document. Both shapes are accepted
270
+ * because the reader that feeds provisioning returns the inner map while the
271
+ * command works with the whole document; `packages` wins when both exist. */
272
+ function overridePackageMap(overrides) {
273
+ if (!isPlainObject(overrides)) return {}
274
+ if (isPlainObject(overrides.packages)) return overrides.packages
275
+ return overrides
276
+ }
277
+
278
+ /**
279
+ * Parse the override document text. Returns null when the document as a whole
280
+ * is unusable (bad JSON, not an object, no usable `packages` object) — the
281
+ * caller maps null to "no overrides", never to an error.
282
+ *
283
+ * A single malformed entry (no version string) is dropped instead of failing
284
+ * the file: one hand-edit typo must not silently disable the other pins.
285
+ * Surviving entries keep their shape — a string stays a string, an object keeps
286
+ * its metadata (`shippedPin`, `updatedAt`) — so a read/serialize round trip
287
+ * does not destroy fields this module does not interpret. Neither `version`
288
+ * nor the entry's semver validity is enforced here (pickEffectivePin judges
289
+ * validity, so a bad version can still be reported and cleaned up).
290
+ *
291
+ * @param {string} text
292
+ * @returns {{ version: number, packages: Record<string, string|{version: string}> } | null}
293
+ */
294
+ export function parseOverrides(text) {
295
+ let doc
296
+ try {
297
+ doc = JSON.parse(String(text ?? ''))
298
+ } catch {
299
+ return null
300
+ }
301
+ if (!isPlainObject(doc)) return null
302
+ if (!isPlainObject(doc.packages)) return null
303
+
304
+ const packages = {}
305
+ for (const [name, entry] of Object.entries(doc.packages)) {
306
+ if (name === '') continue
307
+ const version = entryVersion(entry)
308
+ if (version === null || version === '') continue
309
+ packages[name] = typeof entry === 'string' ? version : { ...entry, version }
310
+ }
311
+
312
+ return { version: Number.isInteger(doc.version) ? doc.version : 1, packages }
313
+ }
314
+
315
+ /**
316
+ * Stable serialization: two-space JSON, trailing newline, `packages` keys in
317
+ * lexicographic order. Stability matters because the file is written after
318
+ * every upgrade and lives in a directory users inspect and diff; insertion
319
+ * order must not leak into the bytes.
320
+ *
321
+ * @param {{ packages?: Record<string, string>, [key: string]: unknown }} obj
322
+ * @returns {string}
323
+ */
324
+ export function serializeOverrides(obj) {
325
+ if (!isPlainObject(obj)) throw new TypeError('serializeOverrides: expected a plain object')
326
+ const packages = isPlainObject(obj.packages) ? obj.packages : {}
327
+ const sorted = {}
328
+ for (const name of Object.keys(packages).sort()) sorted[name] = packages[name]
329
+ return `${JSON.stringify({ ...obj, packages: sorted }, null, 2)}\n`
330
+ }
331
+
332
+ /**
333
+ * Should an override be written for this package?
334
+ *
335
+ * Only when the override is strictly newer than the shipped pin. Equal means
336
+ * the product has caught up (the pin now does the job), older means the
337
+ * override would downgrade, and an unparsable version cannot be judged at
338
+ * all. In all three cases writing would either be useless or harmful.
339
+ *
340
+ * This is the single verdict both writers and readers share: provisioning
341
+ * must ignore an override under exactly the same conditions, or the upgrade
342
+ * command writes pins that the next start silently rejects (or honours when
343
+ * it should not).
344
+ *
345
+ * @param {{ overrideVersion?: string, shippedPin?: string }} input
346
+ * @returns {boolean}
347
+ */
348
+ export function shouldWriteOverride({ overrideVersion, shippedPin } = {}) {
349
+ if (!parseVersion(overrideVersion) || !parseVersion(shippedPin)) return false
350
+ return compareVersions(overrideVersion, shippedPin) > 0
351
+ }
352
+
353
+ /**
354
+ * Which version provisioning should require for one plugin.
355
+ *
356
+ * DELEGATES the decision to provision-plan's `resolveEffectivePin`: that
357
+ * function is the single authority, and a second copy here would be free to
358
+ * drift and let the upgrade command write pins the next start ignores. This
359
+ * wrapper only keeps the richer `{ pin, overridden, ignoredReason }` shape the
360
+ * command logs, by classifying *why* a present entry did not win.
361
+ *
362
+ * `overrides` is the parsed document ({ version, packages }) or the inner
363
+ * name -> entry map that a reader returns; both are accepted. Behaviour (all
364
+ * inherited from resolveEffectivePin):
365
+ * - name absent -> shipped pin, overridden: false
366
+ * - override equal to / older than pin -> shipped pin, ignoredReason 'stale'
367
+ * - override or entry shape invalid -> shipped pin, ignoredReason 'invalid'
368
+ * - name outside PLUGIN_SET (allowlist) -> shipped pin, ignoredReason 'unmanaged'
369
+ * - otherwise -> override version, overridden: true
370
+ *
371
+ * `ignoredReason` is only present when an override existed and was ignored;
372
+ * `pin` is always safe to use. 'unmanaged' exists because the allowlist lives
373
+ * in provision-plan: an otherwise valid, newer entry for a package the
374
+ * launcher does not manage can never take effect, and that is worth saying
375
+ * instead of mislabelling it 'stale'.
376
+ *
377
+ * @param {{
378
+ * name: string,
379
+ * shippedPin: string,
380
+ * overrides?: { version?: number, packages?: Record<string, string|{version?: string}> } | Record<string, string|{version?: string}> | null,
381
+ * }} input
382
+ * @returns {{ pin: string, overridden: boolean, ignoredReason?: 'stale'|'invalid'|'unmanaged' }}
383
+ */
384
+ export function pickEffectivePin({ name, shippedPin, overrides } = {}) {
385
+ const packages = overridePackageMap(overrides)
386
+ const pin = resolveEffectivePin({ name, shippedPin, overrides: packages })
387
+ if (pin !== shippedPin) return { pin, overridden: true }
388
+
389
+ // The entry exists but provisioning did not honour it — say why.
390
+ if (!Object.prototype.hasOwnProperty.call(packages, name)) {
391
+ return { pin, overridden: false }
392
+ }
393
+ const entry = packages[name]
394
+ // resolveEffectivePin requires the object form; a bare string (and any
395
+ // entry without a version string) is unusable to it, whatever this
396
+ // module's own reader tolerates.
397
+ const overrideVersion =
398
+ isPlainObject(entry) && typeof entry.version === 'string' ? entry.version.trim() : ''
399
+ if (overrideVersion === '' || !parseVersion(overrideVersion) || !parseVersion(shippedPin)) {
400
+ return { pin, overridden: false, ignoredReason: 'invalid' }
401
+ }
402
+ if (compareVersions(overrideVersion, shippedPin) <= 0) {
403
+ return { pin, overridden: false, ignoredReason: 'stale' }
404
+ }
405
+ return { pin, overridden: false, ignoredReason: 'unmanaged' }
406
+ }