@meith/marketplace 0.16.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/LICENSE.md ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@meith/marketplace",
3
+ "version": "0.16.0",
4
+ "license": "LGPL-3.0-or-later",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/meith-dev/meith.git",
8
+ "directory": "packages/marketplace"
9
+ },
10
+ "type": "module",
11
+ "main": "./src/index.ts",
12
+ "types": "./src/index.ts",
13
+ "files": [
14
+ "src",
15
+ "!src/**/*.test.*",
16
+ "!src/**/*.type-test.*"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "dependencies": {
22
+ "@meith/theme-kit": "0.16.0"
23
+ }
24
+ }
@@ -0,0 +1,27 @@
1
+ import { parseApiVersion, THEME_API_VERSION } from '@meith/theme-kit'
2
+
3
+ /**
4
+ * This board's own release version, checked against a listing's `meith`
5
+ * range. Duplicated the same way `CODE_VERSION` already is across
6
+ * apps/cli/src/upgrade.ts, apps/community/src/server/upgrade-notice.ts and
7
+ * packages/create-meith/src/bin.ts — see docs/release.md — and kept honest
8
+ * by the same `scripts/release-check.mjs`.
9
+ */
10
+ export const MEITH_VERSION = '0.16.0'
11
+
12
+ /**
13
+ * The theme-kit major this build implements, read from the single place
14
+ * that already declares it rather than duplicated as a literal.
15
+ */
16
+ export const THEME_API_MAJOR = parseApiVersion(THEME_API_VERSION).major
17
+
18
+ /**
19
+ * The plugin-kit major this build implements. Unlike theme-kit, plugin-kit
20
+ * exports no equivalent constant — a plugin's own `apiVersion` is a free
21
+ * string nothing currently checks (see docs/plugin-api.md's Versioning
22
+ * section, which describes the policy without a constant enforcing it).
23
+ * Both kits are pre-1.0, so this is 0 until plugin-kit ships a major of its
24
+ * own; bump it by hand alongside that, the same way this file's other
25
+ * constant is bumped by hand at every release.
26
+ */
27
+ export const PLUGIN_API_MAJOR = 0
package/src/cache.ts ADDED
@@ -0,0 +1,40 @@
1
+ import type { MarketplaceFeed } from './schema'
2
+
3
+ export interface CachedMarketplace {
4
+ readonly feed: MarketplaceFeed | null
5
+ /** The feed URL `feed` was actually fetched from — a listing's screenshot
6
+ * path is resolved against this, not against today's setting. */
7
+ readonly sourceUrl: string | null
8
+ readonly fetchedAt: Date | null
9
+ readonly error: string | null
10
+ readonly errorAt: Date | null
11
+ }
12
+
13
+ export const EMPTY_CACHE: CachedMarketplace = {
14
+ feed: null,
15
+ sourceUrl: null,
16
+ fetchedAt: null,
17
+ error: null,
18
+ errorAt: null,
19
+ }
20
+
21
+ /**
22
+ * The cached feed and the daily task's own bookkeeping — one row, whichever
23
+ * infrastructure package backs it (see packages/db's `marketplace-repo.ts`).
24
+ * `hasNotified`/`markNotified` are what make an update notify administrators
25
+ * exactly once per (plugin, version), ever: independent of whether the
26
+ * notification itself has since been read, which a bare `dedupeKey` on the
27
+ * notification service is not (its coalescing only holds while a
28
+ * notification is unread — see packages/notifications).
29
+ */
30
+ export interface MarketplaceCacheRepository {
31
+ read(): Promise<CachedMarketplace>
32
+ saveFeed(input: {
33
+ readonly feed: MarketplaceFeed
34
+ readonly sourceUrl: string
35
+ readonly fetchedAt: Date
36
+ }): Promise<void>
37
+ saveError(input: { readonly message: string; readonly at: Date }): Promise<void>
38
+ hasNotified(key: string, version: string): Promise<boolean>
39
+ markNotified(key: string, version: string): Promise<void>
40
+ }
package/src/fetch.ts ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The one place this package touches the network — and only ever server-side:
3
+ * the daily task and the admin "Refresh" action both call `refreshCatalog`
4
+ * (see refresh.ts), never the browser. Node's built-in `fetch` is enough; no
5
+ * HTTP client dependency is added for this.
6
+ */
7
+ export interface FetchFeedResult {
8
+ readonly ok: boolean
9
+ /** Parsed JSON body, present only when `ok` is true. */
10
+ readonly body: unknown
11
+ /** A short, loggable reason, present only when `ok` is false. */
12
+ readonly error: string | null
13
+ }
14
+
15
+ const DEFAULT_TIMEOUT_MS = 10_000
16
+ const MAX_BODY_BYTES = 2_000_000
17
+
18
+ export interface FetchFeedOptions {
19
+ readonly url: string
20
+ readonly timeoutMs?: number
21
+ /** Swappable for tests; defaults to the platform's global `fetch`. */
22
+ readonly fetchImpl?: typeof fetch
23
+ }
24
+
25
+ /**
26
+ * Fetches and JSON-parses a marketplace feed. Never throws: an unreachable
27
+ * host, a non-200 response, an oversized body or invalid JSON are all
28
+ * reported as `{ ok: false, error }` — the board with no outbound network is
29
+ * meant to fail quietly here, not crash the task that called this.
30
+ */
31
+ export async function fetchMarketplaceFeed(options: FetchFeedOptions): Promise<FetchFeedResult> {
32
+ const fetchImpl = options.fetchImpl ?? fetch
33
+ const controller = new AbortController()
34
+ const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
35
+
36
+ try {
37
+ let response: Response
38
+ try {
39
+ response = await fetchImpl(options.url, {
40
+ signal: controller.signal,
41
+ headers: { accept: 'application/json' },
42
+ })
43
+ } catch (error) {
44
+ return { ok: false, body: null, error: `could not reach ${options.url}: ${String(error)}` }
45
+ }
46
+
47
+ if (!response.ok) {
48
+ return { ok: false, body: null, error: `${options.url} answered ${response.status}` }
49
+ }
50
+
51
+ const text = await response.text()
52
+ if (text.length > MAX_BODY_BYTES) {
53
+ return {
54
+ ok: false,
55
+ body: null,
56
+ error: `${options.url} answered a body over ${MAX_BODY_BYTES} bytes`,
57
+ }
58
+ }
59
+
60
+ try {
61
+ return { ok: true, body: JSON.parse(text), error: null }
62
+ } catch {
63
+ return { ok: false, body: null, error: `${options.url} did not answer valid JSON` }
64
+ }
65
+ } finally {
66
+ clearTimeout(timeout)
67
+ }
68
+ }
package/src/index.ts ADDED
@@ -0,0 +1,30 @@
1
+ export { MEITH_VERSION, PLUGIN_API_MAJOR, THEME_API_MAJOR } from './build-info'
2
+ export { type CachedMarketplace, EMPTY_CACHE, type MarketplaceCacheRepository } from './cache'
3
+ export { type FetchFeedOptions, type FetchFeedResult, fetchMarketplaceFeed } from './fetch'
4
+ export {
5
+ compareSemver,
6
+ parseMeithRange,
7
+ parseSemver,
8
+ type Semver,
9
+ satisfiesMeithRange,
10
+ } from './range'
11
+ export { type RefreshCatalogInput, type RefreshCatalogResult, refreshCatalog } from './refresh'
12
+ export {
13
+ type FeedValidation,
14
+ type ListingKind,
15
+ type MarketplaceFeed,
16
+ type MarketplaceListing,
17
+ REQUIRED_LISTING_FIELDS,
18
+ validateFeed,
19
+ } from './schema'
20
+ export {
21
+ type BuildInfo,
22
+ type CompatibilityCheck,
23
+ type CompatibilityResult,
24
+ checkCompatibility,
25
+ computeListingStatus,
26
+ type InstalledEntry,
27
+ type ListingStatus,
28
+ type ListingStatusInput,
29
+ type ListingStatusResult,
30
+ } from './status'
package/src/range.ts ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Version comparison and the "meith" range check.
3
+ *
4
+ * `marketplace/schema.json` documents the range syntax but the generator
5
+ * only checks that it *parses* — it is never evaluated against a real
6
+ * version there (see docs/marketplace.md). This is that evaluation, written
7
+ * for the first time here: comparators `>=`, `<=`, `>`, `<` or `=` (default
8
+ * `=`) against a version of one to three numeric parts, space-separated to
9
+ * mean AND.
10
+ *
11
+ * Precision is handled differently for the two families, which is a
12
+ * deliberate reading rather than something the docs pin down:
13
+ *
14
+ * - `=` **truncates** the board version to the comparator's own precision,
15
+ * so `=1` means "meith major 1, whatever the minor and patch" and `=1.2`
16
+ * means "1.2.x". That is what "pin to a major or minor" has to mean.
17
+ * - `>=`, `<=`, `>`, `<` **zero-pad** the comparator to three parts before
18
+ * comparing the full version against it, so `<1` means "strictly before
19
+ * 1.0.0" and `>1.2` means "newer than 1.2.0" (1.2.5 included) rather than
20
+ * "1.3.0 or later". That is the ordinary meaning of a version bound.
21
+ */
22
+
23
+ export type Semver = readonly [number, number, number]
24
+
25
+ const SEMVER_PATTERN = /^(\d+)\.(\d+)\.(\d+)$/
26
+
27
+ export function parseSemver(value: string): Semver | null {
28
+ const match = SEMVER_PATTERN.exec(value.trim())
29
+ if (match === null) return null
30
+ return [Number(match[1]), Number(match[2]), Number(match[3])]
31
+ }
32
+
33
+ function compareParts(a: readonly number[], b: readonly number[]): number {
34
+ const length = Math.max(a.length, b.length)
35
+ for (let i = 0; i < length; i += 1) {
36
+ const diff = (a[i] ?? 0) - (b[i] ?? 0)
37
+ if (diff !== 0) return Math.sign(diff)
38
+ }
39
+ return 0
40
+ }
41
+
42
+ /** -1 if `a` is older than `b`, 0 if equal, 1 if newer. Both must be full semver. */
43
+ export function compareSemver(a: string, b: string): number {
44
+ const left = parseSemver(a)
45
+ const right = parseSemver(b)
46
+ if (left === null || right === null) {
47
+ throw new Error(`marketplace: "${left === null ? a : b}" is not a major.minor.patch version`)
48
+ }
49
+ return compareParts(left, right)
50
+ }
51
+
52
+ type ComparatorOp = '>=' | '<=' | '>' | '<' | '='
53
+
54
+ interface Comparator {
55
+ readonly op: ComparatorOp
56
+ readonly parts: readonly number[]
57
+ }
58
+
59
+ const COMPARATOR_TOKEN = /^(>=|<=|>|<|=)?(\d+)(?:\.(\d+))?(?:\.(\d+))?$/
60
+
61
+ function parseComparator(token: string): Comparator | null {
62
+ const match = COMPARATOR_TOKEN.exec(token)
63
+ if (match === null) return null
64
+
65
+ const op = (match[1] ?? '=') as ComparatorOp
66
+ const parts = [match[2], match[3], match[4]]
67
+ .filter((part): part is string => part !== undefined)
68
+ .map(Number)
69
+ return { op, parts }
70
+ }
71
+
72
+ /** Parses a `meith` range string, or null when it does not parse. */
73
+ export function parseMeithRange(range: string): readonly Comparator[] | null {
74
+ const trimmed = range.trim()
75
+ if (trimmed === '') return null
76
+
77
+ const comparators = trimmed.split(/\s+/).map(parseComparator)
78
+ return comparators.every((c): c is Comparator => c !== null) ? comparators : null
79
+ }
80
+
81
+ function satisfiesComparator(comparator: Comparator, version: Semver): boolean {
82
+ if (comparator.op === '=') {
83
+ return compareParts(version.slice(0, comparator.parts.length), comparator.parts) === 0
84
+ }
85
+
86
+ const padded: Semver = [
87
+ comparator.parts[0] ?? 0,
88
+ comparator.parts[1] ?? 0,
89
+ comparator.parts[2] ?? 0,
90
+ ]
91
+ const cmp = compareParts(version, padded)
92
+ switch (comparator.op) {
93
+ case '>=':
94
+ return cmp >= 0
95
+ case '<=':
96
+ return cmp <= 0
97
+ case '>':
98
+ return cmp > 0
99
+ case '<':
100
+ return cmp < 0
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Whether `version` (major.minor.patch) satisfies every comparator in
106
+ * `range`. An unparseable range or version is never satisfied — an honest
107
+ * "no", not a thrown error, since this runs against untrusted feed data.
108
+ */
109
+ export function satisfiesMeithRange(range: string, version: string): boolean {
110
+ const comparators = parseMeithRange(range)
111
+ if (comparators === null) return false
112
+
113
+ const parsedVersion = parseSemver(version)
114
+ if (parsedVersion === null) return false
115
+
116
+ return comparators.every((comparator) => satisfiesComparator(comparator, parsedVersion))
117
+ }
package/src/refresh.ts ADDED
@@ -0,0 +1,73 @@
1
+ import type { MarketplaceCacheRepository } from './cache'
2
+ import { fetchMarketplaceFeed } from './fetch'
3
+ import type { MarketplaceListing } from './schema'
4
+ import { validateFeed } from './schema'
5
+ import { type BuildInfo, computeListingStatus, type InstalledEntry } from './status'
6
+
7
+ export interface RefreshCatalogInput {
8
+ readonly url: string
9
+ readonly repository: MarketplaceCacheRepository
10
+ readonly build: BuildInfo
11
+ /** How this build resolves a listing's key against what it compiled in. */
12
+ readonly resolveInstalled: (listing: MarketplaceListing) => InstalledEntry | null
13
+ /** Called once per newly-detected (plugin, version) update, before it is recorded as notified. */
14
+ readonly notifyUpdate: (listing: MarketplaceListing) => Promise<void>
15
+ readonly now?: () => Date
16
+ readonly fetchImpl?: typeof fetch
17
+ readonly timeoutMs?: number
18
+ }
19
+
20
+ export interface RefreshCatalogResult {
21
+ readonly ok: boolean
22
+ readonly listingCount: number
23
+ readonly notified: number
24
+ readonly error: string | null
25
+ }
26
+
27
+ /**
28
+ * Fetches, validates and caches the feed, then raises the update
29
+ * notification for any plugin whose new version this board has not already
30
+ * notified about. This is the one function both the daily task and the
31
+ * admin "Refresh" button call — see docs/marketplace.md — so there is
32
+ * exactly one place that decides what counts as a successful refresh.
33
+ */
34
+ export async function refreshCatalog(input: RefreshCatalogInput): Promise<RefreshCatalogResult> {
35
+ const now = input.now ?? (() => new Date())
36
+
37
+ const fetched = await fetchMarketplaceFeed({
38
+ url: input.url,
39
+ ...(input.fetchImpl === undefined ? {} : { fetchImpl: input.fetchImpl }),
40
+ ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
41
+ })
42
+
43
+ if (!fetched.ok) {
44
+ const message = fetched.error ?? 'unknown fetch error'
45
+ await input.repository.saveError({ message, at: now() })
46
+ return { ok: false, listingCount: 0, notified: 0, error: message }
47
+ }
48
+
49
+ const validated = validateFeed(fetched.body)
50
+ if (!validated.ok) {
51
+ const message = `feed failed validation: ${validated.errors.slice(0, 5).join('; ')}`
52
+ await input.repository.saveError({ message, at: now() })
53
+ return { ok: false, listingCount: 0, notified: 0, error: message }
54
+ }
55
+
56
+ await input.repository.saveFeed({ feed: validated.feed, sourceUrl: input.url, fetchedAt: now() })
57
+
58
+ let notified = 0
59
+ for (const listing of validated.feed.listings) {
60
+ if (listing.kind !== 'plugin') continue
61
+
62
+ const installed = input.resolveInstalled(listing)
63
+ const result = computeListingStatus({ ...listing, installed }, input.build)
64
+ if (result.status !== 'update-available') continue
65
+ if (await input.repository.hasNotified(listing.key, listing.version)) continue
66
+
67
+ await input.notifyUpdate(listing)
68
+ await input.repository.markNotified(listing.key, listing.version)
69
+ notified += 1
70
+ }
71
+
72
+ return { ok: true, listingCount: validated.feed.listings.length, notified, error: null }
73
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,172 @@
1
+ /**
2
+ * The shape of a listing on the wire — mirroring `marketplace/schema.json`
3
+ * and `scripts/marketplace-gen.mjs`, which this package never imports (a
4
+ * board-side consumer and the generator that produces the feed it consumes
5
+ * are deliberately separate concerns; see docs/marketplace.md). One
6
+ * difference is load-bearing: `marketplace/schema.json` validates a
7
+ * *listing file* before it is merged, where `screenshots` is a bare
8
+ * filename. What a board actually fetches is the *emitted* feed at
9
+ * `/marketplace/v1.json`, where `buildFeed()` has already rewritten every
10
+ * screenshot into an absolute site path (`/marketplace/screenshots/x.png`)
11
+ * and wrapped the listings in `{ schema, listings }`. `validateFeed` below
12
+ * validates that served shape — same fields, same rules, screenshots
13
+ * checked as paths rather than bare names — which is "the same schema
14
+ * shape" the issue asks for once the wrapper and the path rewrite are
15
+ * accounted for. `packages/marketplace/src/schema.test.ts` cross-checks the
16
+ * required field list against `marketplace/schema.json` itself so the two
17
+ * cannot silently drift apart.
18
+ */
19
+
20
+ export type ListingKind = 'plugin' | 'theme'
21
+
22
+ export interface MarketplaceListing {
23
+ readonly key: string
24
+ readonly kind: ListingKind
25
+ readonly package: string
26
+ readonly name: string
27
+ readonly description: string
28
+ readonly screenshots: readonly string[]
29
+ readonly version: string
30
+ readonly apiVersion: number
31
+ readonly meith: string
32
+ readonly repository: string
33
+ readonly licence: string
34
+ }
35
+
36
+ export interface MarketplaceFeed {
37
+ readonly schema: string
38
+ readonly listings: readonly MarketplaceListing[]
39
+ }
40
+
41
+ export const REQUIRED_LISTING_FIELDS = [
42
+ 'key',
43
+ 'kind',
44
+ 'package',
45
+ 'name',
46
+ 'description',
47
+ 'screenshots',
48
+ 'version',
49
+ 'apiVersion',
50
+ 'meith',
51
+ 'repository',
52
+ 'licence',
53
+ ] as const
54
+
55
+ const KEY_PATTERN = /^[a-z][a-z0-9-]{1,39}$/
56
+ const VERSION_PATTERN = /^\d+\.\d+\.\d+$/
57
+ const PACKAGE_PATTERN = /^(@[a-z0-9-][a-z0-9-._]*\/)?[a-z0-9-][a-z0-9-._]*$/
58
+ // The served feed's screenshots are absolute site paths, not bare filenames —
59
+ // see the module comment above.
60
+ const SCREENSHOT_PATH_PATTERN = /^\/marketplace\/screenshots\/[a-z0-9][a-z0-9-]*\.png$/
61
+ const KINDS = new Set<string>(['plugin', 'theme'])
62
+
63
+ export type FeedValidation =
64
+ | { readonly ok: true; readonly feed: MarketplaceFeed; readonly errors: readonly [] }
65
+ | { readonly ok: false; readonly feed: null; readonly errors: readonly string[] }
66
+
67
+ function isRecord(value: unknown): value is Record<string, unknown> {
68
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
69
+ }
70
+
71
+ function validateListing(entry: unknown, index: number): readonly string[] {
72
+ const where = `listings[${index}]`
73
+ if (!isRecord(entry)) return [`${where}: a listing must be an object`]
74
+
75
+ const errors: string[] = []
76
+ for (const field of REQUIRED_LISTING_FIELDS) {
77
+ if (!(field in entry)) errors.push(`${where}: missing field "${field}"`)
78
+ }
79
+ for (const field of Object.keys(entry)) {
80
+ if (!(REQUIRED_LISTING_FIELDS as readonly string[]).includes(field)) {
81
+ errors.push(`${where}: unexpected field "${field}"`)
82
+ }
83
+ }
84
+
85
+ if ('key' in entry && (typeof entry.key !== 'string' || !KEY_PATTERN.test(entry.key))) {
86
+ errors.push(`${where}: "key" is not lower-case letters, digits and hyphens`)
87
+ }
88
+ if ('kind' in entry && (typeof entry.kind !== 'string' || !KINDS.has(entry.kind))) {
89
+ errors.push(`${where}: "kind" must be "plugin" or "theme"`)
90
+ }
91
+ if (
92
+ 'package' in entry &&
93
+ (typeof entry.package !== 'string' || !PACKAGE_PATTERN.test(entry.package))
94
+ ) {
95
+ errors.push(`${where}: "package" is not a valid npm package name`)
96
+ }
97
+ if ('name' in entry && (typeof entry.name !== 'string' || entry.name.trim() === '')) {
98
+ errors.push(`${where}: "name" must not be empty`)
99
+ }
100
+ if (
101
+ 'description' in entry &&
102
+ (typeof entry.description !== 'string' || entry.description.trim() === '')
103
+ ) {
104
+ errors.push(`${where}: "description" must not be empty`)
105
+ }
106
+ if ('screenshots' in entry) {
107
+ if (!Array.isArray(entry.screenshots) || entry.screenshots.length === 0) {
108
+ errors.push(`${where}: "screenshots" must be a non-empty array`)
109
+ } else if (
110
+ !entry.screenshots.every(
111
+ (shot) => typeof shot === 'string' && SCREENSHOT_PATH_PATTERN.test(shot),
112
+ )
113
+ ) {
114
+ errors.push(
115
+ `${where}: "screenshots" has an entry that is not a /marketplace/screenshots/*.png path`,
116
+ )
117
+ }
118
+ }
119
+ if (
120
+ 'version' in entry &&
121
+ (typeof entry.version !== 'string' || !VERSION_PATTERN.test(entry.version))
122
+ ) {
123
+ errors.push(`${where}: "version" must be major.minor.patch`)
124
+ }
125
+ if (
126
+ 'apiVersion' in entry &&
127
+ (!Number.isInteger(entry.apiVersion) || (entry.apiVersion as number) < 0)
128
+ ) {
129
+ errors.push(`${where}: "apiVersion" must be a non-negative integer`)
130
+ }
131
+ if ('meith' in entry && typeof entry.meith !== 'string') {
132
+ errors.push(`${where}: "meith" must be a string range`)
133
+ }
134
+ if (
135
+ 'repository' in entry &&
136
+ (typeof entry.repository !== 'string' || !/^https:\/\//.test(entry.repository))
137
+ ) {
138
+ errors.push(`${where}: "repository" must be an https URL`)
139
+ }
140
+ if ('licence' in entry && (typeof entry.licence !== 'string' || entry.licence.trim() === '')) {
141
+ errors.push(`${where}: "licence" must not be empty`)
142
+ }
143
+
144
+ return errors
145
+ }
146
+
147
+ /**
148
+ * Validates the document a board fetches from `/marketplace/v1.json` (or a
149
+ * self-hosted mirror of it) against the same shape MEI-79's schema defines.
150
+ * Never throws — a malformed feed is exactly the case this function exists
151
+ * to report, not to crash the fetch task over.
152
+ */
153
+ export function validateFeed(raw: unknown): FeedValidation {
154
+ if (!isRecord(raw)) {
155
+ return { ok: false, feed: null, errors: ['the feed must be a JSON object'] }
156
+ }
157
+ if (typeof raw.schema !== 'string' || raw.schema === '') {
158
+ return { ok: false, feed: null, errors: ['the feed has no "schema" field'] }
159
+ }
160
+ if (!Array.isArray(raw.listings)) {
161
+ return { ok: false, feed: null, errors: ['the feed has no "listings" array'] }
162
+ }
163
+
164
+ const errors = raw.listings.flatMap((entry, index) => validateListing(entry, index))
165
+ if (errors.length > 0) return { ok: false, feed: null, errors }
166
+
167
+ return {
168
+ ok: true,
169
+ feed: { schema: raw.schema, listings: raw.listings as MarketplaceListing[] },
170
+ errors: [],
171
+ }
172
+ }
package/src/status.ts ADDED
@@ -0,0 +1,114 @@
1
+ import { compareSemver, satisfiesMeithRange } from './range'
2
+ import type { ListingKind } from './schema'
3
+
4
+ export type ListingStatus =
5
+ | 'active'
6
+ | 'installed-disabled'
7
+ | 'not-installed'
8
+ | 'update-available'
9
+ | 'incompatible'
10
+
11
+ export interface CompatibilityCheck {
12
+ readonly kind: ListingKind
13
+ readonly version: string
14
+ readonly apiVersion: number
15
+ readonly meith: string
16
+ }
17
+
18
+ export interface BuildInfo {
19
+ /** This board's own release version — `CODE_VERSION`, checked against `meith`. */
20
+ readonly meithVersion: string
21
+ /** The plugin-kit major this build implements, checked against a plugin listing's `apiVersion`. */
22
+ readonly pluginApiMajor: number
23
+ /** The theme-kit major this build implements, checked against a theme listing's `apiVersion`. */
24
+ readonly themeApiMajor: number
25
+ }
26
+
27
+ export interface CompatibilityResult {
28
+ readonly compatible: boolean
29
+ /** Set exactly when `compatible` is false — why, in words a board operator can act on. */
30
+ readonly reason: string | null
31
+ }
32
+
33
+ /** Checks a listing's declared `apiVersion` and `meith` range against this build. */
34
+ export function checkCompatibility(
35
+ listing: CompatibilityCheck,
36
+ build: BuildInfo,
37
+ ): CompatibilityResult {
38
+ const wantedMajor = listing.kind === 'plugin' ? build.pluginApiMajor : build.themeApiMajor
39
+ const apiOk = listing.apiVersion === wantedMajor
40
+ const meithOk = satisfiesMeithRange(listing.meith, build.meithVersion)
41
+
42
+ if (apiOk && meithOk) return { compatible: true, reason: null }
43
+
44
+ const reasons: string[] = []
45
+ if (!apiOk) {
46
+ reasons.push(
47
+ `built against ${listing.kind === 'plugin' ? 'plugin' : 'theme'}-kit major ${listing.apiVersion}, ` +
48
+ `this board runs major ${wantedMajor}`,
49
+ )
50
+ }
51
+ if (!meithOk) {
52
+ reasons.push(`needs meith ${listing.meith}, this board runs ${build.meithVersion}`)
53
+ }
54
+ return { compatible: false, reason: reasons.join('; ') }
55
+ }
56
+
57
+ /** What this build already knows about a listing's key, if anything. */
58
+ export interface InstalledEntry {
59
+ readonly enabled: boolean
60
+ /** The compiled version to compare the feed against, or null when there is none to compare. */
61
+ readonly version: string | null
62
+ }
63
+
64
+ export interface ListingStatusInput extends CompatibilityCheck {
65
+ readonly installed: InstalledEntry | null
66
+ }
67
+
68
+ export interface ListingStatusResult {
69
+ readonly status: ListingStatus
70
+ /** Set exactly when `status` is 'incompatible'. */
71
+ readonly incompatibleReason: string | null
72
+ }
73
+
74
+ /**
75
+ * The five statuses the Browse tab renders, computed against what this build
76
+ * actually contains — never against what installing would do, because this
77
+ * screen does not install anything.
78
+ *
79
+ * An installed plugin or theme that is merely *running* is never recomputed
80
+ * to 'incompatible' on the strength of the catalog's opinion of its current
81
+ * listing — what is already active keeps being reported as active. Incompat-
82
+ * ibility only gates two things: a listing nothing has installed, and an
83
+ * update this board would otherwise offer. That is also why a theme (whose
84
+ * compiled version this build cannot see — `defineTheme` carries none) never
85
+ * reports 'update-available': there is nothing reliable to compare against,
86
+ * so it settles on active/disabled once compatibility has been read for the
87
+ * not-installed case.
88
+ */
89
+ export function computeListingStatus(
90
+ input: ListingStatusInput,
91
+ build: BuildInfo,
92
+ ): ListingStatusResult {
93
+ const compatibility = checkCompatibility(input, build)
94
+
95
+ if (input.installed === null) {
96
+ return compatibility.compatible
97
+ ? { status: 'not-installed', incompatibleReason: null }
98
+ : { status: 'incompatible', incompatibleReason: compatibility.reason }
99
+ }
100
+
101
+ const hasNewerListedVersion =
102
+ input.installed.version !== null && compareSemver(input.version, input.installed.version) > 0
103
+
104
+ if (hasNewerListedVersion) {
105
+ return compatibility.compatible
106
+ ? { status: 'update-available', incompatibleReason: null }
107
+ : { status: 'incompatible', incompatibleReason: compatibility.reason }
108
+ }
109
+
110
+ return {
111
+ status: input.installed.enabled ? 'active' : 'installed-disabled',
112
+ incompatibleReason: null,
113
+ }
114
+ }