@cagov/ca-ds 0.0.0-stage → 1.0.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 +21 -0
- package/README.md +600 -2
- package/bin/ca-ds.js +5 -0
- package/package.json +62 -4
- package/src/cli/add.js +134 -0
- package/src/cli/build.js +15 -0
- package/src/cli/diff.js +39 -0
- package/src/cli/eject.js +112 -0
- package/src/cli/exit.js +22 -0
- package/src/cli/format.js +52 -0
- package/src/cli/init.js +148 -0
- package/src/cli/install.js +178 -0
- package/src/cli/items.js +10 -0
- package/src/cli/login.js +331 -0
- package/src/cli/main.js +108 -0
- package/src/cli/new.js +230 -0
- package/src/cli/outdated.js +74 -0
- package/src/cli/pack.js +75 -0
- package/src/cli/preview.js +31 -0
- package/src/cli/publish.js +295 -0
- package/src/cli/pull.js +208 -0
- package/src/cli/remote.js +52 -0
- package/src/cli/remove.js +69 -0
- package/src/cli/update.js +223 -0
- package/src/cli/validate.js +131 -0
- package/src/lib/browser.js +12 -0
- package/src/lib/build.js +249 -0
- package/src/lib/bundle.js +148 -0
- package/src/lib/catalog.js +44 -0
- package/src/lib/checks.js +31 -0
- package/src/lib/collection.js +65 -0
- package/src/lib/emblem.js +29 -0
- package/src/lib/fixtures.js +59 -0
- package/src/lib/floor.js +79 -0
- package/src/lib/glyph.js +148 -0
- package/src/lib/image.js +138 -0
- package/src/lib/json-text.js +213 -0
- package/src/lib/keys.js +322 -0
- package/src/lib/links.js +321 -0
- package/src/lib/markdown.js +408 -0
- package/src/lib/merge.js +93 -0
- package/src/lib/pack.js +30 -0
- package/src/lib/page-schema.js +368 -0
- package/src/lib/page.js +372 -0
- package/src/lib/patch.js +9 -0
- package/src/lib/regions.js +173 -0
- package/src/lib/registry.js +371 -0
- package/src/lib/release.js +119 -0
- package/src/lib/repoints.js +120 -0
- package/src/lib/resolve.js +32 -0
- package/src/lib/schema.js +28 -0
- package/src/lib/serial.js +4 -0
- package/src/lib/serialize.js +444 -0
- package/src/lib/structured.js +72 -0
- package/src/lib/system.js +13 -0
- package/src/lib/targets.js +85 -0
- package/src/lib/terms.js +11 -0
- package/src/lib/token-view.js +289 -0
- package/src/lib/tokens.js +247 -0
- package/src/lib/version.js +34 -0
- package/src/preview/frame.js +75 -0
- package/src/preview/pages.js +128 -0
- package/src/preview/preview.css +58 -0
- package/src/preview/screenshots.js +72 -0
- package/src/preview/server.js +378 -0
- package/src/preview/shell.js +153 -0
- package/src/schema/a11y.schema.json +56 -0
- package/src/schema/collection.lock.schema.json +58 -0
- package/src/schema/collection.schema.json +65 -0
- package/src/schema/composition.schema.json +98 -0
- package/src/schema/contract.schema.json +116 -0
- package/src/schema/interface.schema.json +257 -0
- package/src/schema/item.schema.json +362 -0
- package/src/schema/release.schema.json +39 -0
- package/src/schema/system.schema.json +75 -0
- package/src/schema/variants.schema.json +60 -0
- package/src/validate/collection.js +19 -0
- package/src/validate/collisions.js +124 -0
- package/src/validate/context.js +357 -0
- package/src/validate/facts.js +253 -0
- package/src/validate/files.js +103 -0
- package/src/validate/findings.js +19 -0
- package/src/validate/glyphs.js +126 -0
- package/src/validate/html.js +215 -0
- package/src/validate/imports.js +29 -0
- package/src/validate/index.js +75 -0
- package/src/validate/item.js +47 -0
- package/src/validate/links.js +113 -0
- package/src/validate/manifest.js +147 -0
- package/src/validate/media.js +65 -0
- package/src/validate/page.js +74 -0
- package/src/validate/prefixes.js +58 -0
- package/src/validate/relations.js +310 -0
- package/src/validate/release.js +109 -0
- package/src/validate/skill.js +122 -0
- package/src/validate/structured.js +335 -0
- package/src/validate/tasc.js +80 -0
- package/src/validate/template.js +129 -0
- package/src/validate/tokens.js +154 -0
- package/src/validate/zip.js +40 -0
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
// The credentials file's shape and precedence are in the package README.
|
|
2
|
+
// Every write, and every refresh from read to write, holds credentials.json.lock, so two runs never lose
|
|
3
|
+
// entries or both spend one refresh token.
|
|
4
|
+
|
|
5
|
+
import { chmodSync, closeSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { dirname, join } from 'node:path';
|
|
8
|
+
import { sha256 } from './pack.js';
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_REGISTRY = 'https://v0.ds.innovation.ca.gov';
|
|
11
|
+
|
|
12
|
+
// The service's MAX_LIMIT.
|
|
13
|
+
export const LIST_LIMIT = 500;
|
|
14
|
+
|
|
15
|
+
// auth: the registry refused or found no credential. status is null when no answer came.
|
|
16
|
+
export class RegistryFailure extends Error {
|
|
17
|
+
constructor(message, { auth = false, status = null, code = null } = {}) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.auth = auth;
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.code = code;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const trimmed = (url) => url.replace(/\/+$/, '');
|
|
26
|
+
|
|
27
|
+
export function registryUrl(config, env = process.env) {
|
|
28
|
+
return trimmed(env.CA_DS_URL || config?.registry || DEFAULT_REGISTRY);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function credentialsFile(env = process.env, platform = process.platform) {
|
|
32
|
+
const base = env.XDG_CONFIG_HOME || (platform === 'win32' && env.APPDATA) || join(env.HOME || homedir(), '.config');
|
|
33
|
+
return join(base, 'ca-ds', 'credentials.json');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function readCredentials(file) {
|
|
37
|
+
try {
|
|
38
|
+
const data = JSON.parse(readFileSync(file, 'utf8'));
|
|
39
|
+
if (data && typeof data === 'object' && data.registries && typeof data.registries === 'object') return data;
|
|
40
|
+
} catch {
|
|
41
|
+
/* none stored */
|
|
42
|
+
}
|
|
43
|
+
return { registries: {} };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function writeCredentials(file, data) {
|
|
47
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
48
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
49
|
+
writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
|
|
50
|
+
chmodSync(tmp, 0o600);
|
|
51
|
+
renameSync(tmp, file);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// A lock older than LOCK_STALE belongs to a run that died, and is taken over.
|
|
55
|
+
export const LOCK_STALE = 30 * 1000;
|
|
56
|
+
const LOCK_WAIT = 10 * 1000;
|
|
57
|
+
const LOCK_POLL = 25;
|
|
58
|
+
|
|
59
|
+
function tryLock(lock) {
|
|
60
|
+
try {
|
|
61
|
+
closeSync(openSync(lock, 'wx', 0o600));
|
|
62
|
+
return true;
|
|
63
|
+
} catch (err) {
|
|
64
|
+
if (err.code === 'ENOENT') {
|
|
65
|
+
mkdirSync(dirname(lock), { recursive: true, mode: 0o700 });
|
|
66
|
+
return tryLock(lock);
|
|
67
|
+
}
|
|
68
|
+
if (err.code !== 'EEXIST') throw err;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE) unlinkSync(lock);
|
|
72
|
+
} catch {
|
|
73
|
+
/* released meanwhile */
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const release = (lock) => {
|
|
79
|
+
try {
|
|
80
|
+
unlinkSync(lock);
|
|
81
|
+
} catch {
|
|
82
|
+
/* removed as stale */
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const lockTimeout = (file) => new Error(`Another ca-ds run has held ${file}.lock for ${LOCK_WAIT / 1000} seconds. If none is running, delete that file.`);
|
|
87
|
+
|
|
88
|
+
function locked(file, fn) {
|
|
89
|
+
const lock = `${file}.lock`;
|
|
90
|
+
const until = Date.now() + LOCK_WAIT;
|
|
91
|
+
const pause = new Int32Array(new SharedArrayBuffer(4));
|
|
92
|
+
while (!tryLock(lock)) {
|
|
93
|
+
if (Date.now() > until) throw lockTimeout(file);
|
|
94
|
+
Atomics.wait(pause, 0, 0, LOCK_POLL);
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
return fn();
|
|
98
|
+
} finally {
|
|
99
|
+
release(lock);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function lockedAsync(file, fn) {
|
|
104
|
+
const lock = `${file}.lock`;
|
|
105
|
+
const until = Date.now() + LOCK_WAIT;
|
|
106
|
+
while (!tryLock(lock)) {
|
|
107
|
+
if (Date.now() > until) throw lockTimeout(file);
|
|
108
|
+
await new Promise((resolve) => setTimeout(resolve, LOCK_POLL));
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
return await fn();
|
|
112
|
+
} finally {
|
|
113
|
+
release(lock);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function storedCredential(url, file = credentialsFile()) {
|
|
118
|
+
const entry = readCredentials(file).registries[trimmed(url)];
|
|
119
|
+
return entry && typeof entry === 'object' && typeof entry.token === 'string' && entry.token ? entry : null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function storedToken(url, file = credentialsFile()) {
|
|
123
|
+
return storedCredential(url, file)?.token ?? null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function saveCredential(url, entry, file = credentialsFile()) {
|
|
127
|
+
locked(file, () => {
|
|
128
|
+
const data = readCredentials(file);
|
|
129
|
+
data.registries[trimmed(url)] = entry;
|
|
130
|
+
writeCredentials(file, data);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export const saveToken = (url, token, file = credentialsFile()) => saveCredential(url, { token }, file);
|
|
135
|
+
|
|
136
|
+
export const OAUTH_CLIENT = 'ca-ds';
|
|
137
|
+
|
|
138
|
+
export const REFRESH_MARGIN = 60 * 1000;
|
|
139
|
+
|
|
140
|
+
export const isOAuth = (entry) => entry?.kind === 'oauth' && typeof entry.refresh === 'string' && typeof entry.tokenEndpoint === 'string';
|
|
141
|
+
|
|
142
|
+
// An expiry that doesn't parse counts as near.
|
|
143
|
+
const expiring = (entry, now) => !(Date.parse(entry.expiresAt) - now > REFRESH_MARGIN);
|
|
144
|
+
|
|
145
|
+
export async function postForm(endpoint, form, fetch = globalThis.fetch) {
|
|
146
|
+
let res;
|
|
147
|
+
try {
|
|
148
|
+
res = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' }, body: new URLSearchParams(form).toString() });
|
|
149
|
+
} catch (err) {
|
|
150
|
+
throw new RegistryFailure(`The registry's endpoint ${endpoint} is unreachable: ${err.cause?.message ?? err.message}.`);
|
|
151
|
+
}
|
|
152
|
+
const text = await res.text();
|
|
153
|
+
let body = null;
|
|
154
|
+
try {
|
|
155
|
+
body = text ? JSON.parse(text) : null;
|
|
156
|
+
} catch {
|
|
157
|
+
/* no JSON answer */
|
|
158
|
+
}
|
|
159
|
+
return { status: res.status, body };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// A refresh that issues no new refresh token keeps the old one.
|
|
163
|
+
export function oauthEntry(body, base, now = Date.now()) {
|
|
164
|
+
if (!body || typeof body.access_token !== 'string' || !body.access_token) return null;
|
|
165
|
+
const life = Number.isFinite(body.expires_in) ? body.expires_in * 1000 : 0;
|
|
166
|
+
return {
|
|
167
|
+
token: body.access_token,
|
|
168
|
+
refresh: typeof body.refresh_token === 'string' && body.refresh_token ? body.refresh_token : base.refresh,
|
|
169
|
+
expiresAt: new Date(now + life).toISOString(),
|
|
170
|
+
clientId: base.clientId ?? OAUTH_CLIENT,
|
|
171
|
+
tokenEndpoint: base.tokenEndpoint,
|
|
172
|
+
revocationEndpoint: base.revocationEndpoint ?? null,
|
|
173
|
+
kind: 'oauth',
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export async function refreshCredential(url, entry, { fetch = globalThis.fetch, now = Date.now() } = {}) {
|
|
178
|
+
const { status, body } = await postForm(entry.tokenEndpoint, { grant_type: 'refresh_token', refresh_token: entry.refresh, client_id: entry.clientId ?? OAUTH_CLIENT }, fetch);
|
|
179
|
+
if (status === 200) {
|
|
180
|
+
const next = oauthEntry(body, entry, now);
|
|
181
|
+
if (next) return next;
|
|
182
|
+
throw new RegistryFailure(`The registry at ${url} answered the refresh of its sign-in with no access token.`, { status });
|
|
183
|
+
}
|
|
184
|
+
const said = body?.error_description ? ` ${body.error_description}` : '';
|
|
185
|
+
const code = typeof body?.error === 'string' ? body.error : null;
|
|
186
|
+
if (status === 400 || status === 401) {
|
|
187
|
+
throw new RegistryFailure(`The registry at ${url} refused to refresh the stored sign-in, ${code ?? status}.${said} Run ca-ds login again.`, { auth: true, status, code });
|
|
188
|
+
}
|
|
189
|
+
throw new RegistryFailure(`The registry at ${url} failed to refresh the stored sign-in, ${status}.${said}`, { status, code });
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function forgetToken(url, file = credentialsFile()) {
|
|
193
|
+
return locked(file, () => {
|
|
194
|
+
const data = readCredentials(file);
|
|
195
|
+
if (!Object.hasOwn(data.registries, trimmed(url))) return false;
|
|
196
|
+
delete data.registries[trimmed(url)];
|
|
197
|
+
writeCredentials(file, data);
|
|
198
|
+
return true;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function tokenFor(url, { token = null, env = process.env, file = credentialsFile(env) } = {}) {
|
|
203
|
+
return token || env.CA_DS_TOKEN || storedToken(url, file);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// A token from --token or CA_DS_TOKEN never refreshes; only the credentials file's entry does.
|
|
207
|
+
export function authFor(url, { token = null, env = process.env, file = credentialsFile(env) } = {}) {
|
|
208
|
+
const given = token || env.CA_DS_TOKEN;
|
|
209
|
+
return given ? { token: given, credentials: null } : { token: null, credentials: file };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function body(res) {
|
|
213
|
+
try {
|
|
214
|
+
return await res.json();
|
|
215
|
+
} catch {
|
|
216
|
+
return { error: 'not-json', message: `The registry answered ${res.status} with a body that isn't JSON.` };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function registryClient({ url, token = null, credentials = null, fetch = globalThis.fetch, now = Date.now }) {
|
|
221
|
+
url = trimmed(url);
|
|
222
|
+
let entry = !token && credentials ? storedCredential(url, credentials) : null;
|
|
223
|
+
const bearer = () => token ?? entry?.token ?? null;
|
|
224
|
+
|
|
225
|
+
// The file's entry wins: another run may have rotated the refresh token, which spends this one's.
|
|
226
|
+
const refresh = ({ force }) =>
|
|
227
|
+
lockedAsync(credentials, async () => {
|
|
228
|
+
const held = storedCredential(url, credentials);
|
|
229
|
+
if (!isOAuth(held)) {
|
|
230
|
+
entry = held;
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
if (held.refresh !== entry.refresh) {
|
|
234
|
+
entry = held;
|
|
235
|
+
if (!expiring(entry, now())) return;
|
|
236
|
+
} else if (!force && !expiring(entry, now())) return;
|
|
237
|
+
entry = await refreshCredential(url, entry, { fetch, now: now() });
|
|
238
|
+
const data = readCredentials(credentials);
|
|
239
|
+
data.registries[url] = entry;
|
|
240
|
+
writeCredentials(credentials, data);
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
const once = async (path, init) => {
|
|
244
|
+
const auth = bearer() ? { authorization: `Bearer ${bearer()}` } : {};
|
|
245
|
+
try {
|
|
246
|
+
return await fetch(`${url}${path}`, { ...init, headers: { ...auth, ...init.headers } });
|
|
247
|
+
} catch (err) {
|
|
248
|
+
throw new RegistryFailure(`The registry at ${url} is unreachable: ${err.cause?.message ?? err.message}.`);
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
const send = async (path, init = {}) => {
|
|
253
|
+
if (!isOAuth(entry)) return once(path, init);
|
|
254
|
+
if (expiring(entry, now())) await refresh({ force: false });
|
|
255
|
+
const res = await once(path, init);
|
|
256
|
+
if (res.status !== 401) return res;
|
|
257
|
+
await refresh({ force: true });
|
|
258
|
+
return once(path, init);
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
const refusal = (status, answer, what) => {
|
|
262
|
+
const said = answer.message ? ` ${answer.message}` : '';
|
|
263
|
+
if (status === 401 || status === 403) {
|
|
264
|
+
const hint = isOAuth(entry)
|
|
265
|
+
? status === 401
|
|
266
|
+
? ' Run ca-ds login again.'
|
|
267
|
+
: ''
|
|
268
|
+
: bearer()
|
|
269
|
+
? ''
|
|
270
|
+
: ` Run ca-ds login, pass --token, or set CA_DS_TOKEN, with a token from ${url}/settings/api-keys.`;
|
|
271
|
+
return new RegistryFailure(`The registry at ${url} refused ${what}, ${status}.${said}${hint}`, { auth: true, status, code: answer.error ?? null });
|
|
272
|
+
}
|
|
273
|
+
return new RegistryFailure(`The registry at ${url} refused ${what}, ${status}.${said}`, { status, code: answer.error ?? null });
|
|
274
|
+
};
|
|
275
|
+
const refused = async (res, what) => refusal(res.status, await body(res), what);
|
|
276
|
+
|
|
277
|
+
const call = async (path, init, what) => {
|
|
278
|
+
const res = await send(path, init);
|
|
279
|
+
const answer = await body(res);
|
|
280
|
+
if (res.status === 401 || res.status === 403) throw refusal(res.status, answer, what);
|
|
281
|
+
return { status: res.status, body: answer, headers: res.headers };
|
|
282
|
+
};
|
|
283
|
+
const zipBody = (bytes) => ({ method: 'POST', headers: { 'content-type': 'application/zip' }, body: bytes });
|
|
284
|
+
|
|
285
|
+
const json = async (path, what, { missing = false } = {}) => {
|
|
286
|
+
const res = await send(path);
|
|
287
|
+
if (missing && (res.status === 404 || res.status === 410)) return null;
|
|
288
|
+
if (!res.ok) throw await refused(res, what);
|
|
289
|
+
return body(res);
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
const query = (params) => {
|
|
293
|
+
const set = Object.entries(params).filter(([, v]) => v !== null && v !== undefined);
|
|
294
|
+
return set.length ? `?${new URLSearchParams(set)}` : '';
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
const at = (name, version) => `/api/items/${name}${version ? `/${encodeURIComponent(version)}` : ''}`;
|
|
298
|
+
|
|
299
|
+
return {
|
|
300
|
+
url,
|
|
301
|
+
|
|
302
|
+
item: (name, version = null) => json(at(name, version), `${name}${version ? ` ${version}` : ''}`, { missing: true }),
|
|
303
|
+
|
|
304
|
+
// Null for an item the registry lacks, or a registry from before changelogs.
|
|
305
|
+
changelog: (name, since = null) => json(`${at(name)}/changelog${query({ since })}`, `${name}'s changelog`, { missing: true }),
|
|
306
|
+
|
|
307
|
+
// A full page may hide more items, so it throws rather than answer a partial list.
|
|
308
|
+
async list() {
|
|
309
|
+
const { items } = await json(`/api/items?limit=${LIST_LIMIT}&unlisted=1`, 'the item list');
|
|
310
|
+
if (items.length >= LIST_LIMIT) throw new RegistryFailure(`The registry at ${url} answered ${items.length} items, the most one listing answers, so it may hold more than the list says.`);
|
|
311
|
+
return [...items].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
312
|
+
},
|
|
313
|
+
|
|
314
|
+
async file(name, version, path, expected = null) {
|
|
315
|
+
const what = `${name} ${version}'s ${path}`;
|
|
316
|
+
const res = await send(`${at(name, version)}/files/${path.split('/').map(encodeURIComponent).join('/')}`);
|
|
317
|
+
if (!res.ok) throw await refused(res, what);
|
|
318
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
319
|
+
if (expected && sha256(bytes) !== expected) throw new RegistryFailure(`The registry at ${url} answered ${what} with bytes whose hash isn't its listed one.`);
|
|
320
|
+
return bytes;
|
|
321
|
+
},
|
|
322
|
+
|
|
323
|
+
async files(name, version) {
|
|
324
|
+
const record = await this.item(name, version);
|
|
325
|
+
if (!record) throw new RegistryFailure(`The registry at ${url} holds no ${name} ${version}.`, { status: 404, code: 'not-found' });
|
|
326
|
+
const files = new Map();
|
|
327
|
+
for (const f of record.files) files.set(f.path, await this.file(name, version, f.path, f.sha256));
|
|
328
|
+
return { record, files };
|
|
329
|
+
},
|
|
330
|
+
|
|
331
|
+
async resolve({ items, release = null, versions = {} }) {
|
|
332
|
+
const res = await send('/api/resolve', {
|
|
333
|
+
method: 'POST',
|
|
334
|
+
headers: { 'content-type': 'application/json' },
|
|
335
|
+
body: JSON.stringify({ items, ...(release ? { release } : {}), ...(Object.keys(versions).length ? { versions } : {}) }),
|
|
336
|
+
});
|
|
337
|
+
if (!res.ok) throw await refused(res, `to resolve ${items.join(', ')}`);
|
|
338
|
+
return body(res);
|
|
339
|
+
},
|
|
340
|
+
|
|
341
|
+
// A registry that predates purges answers none.
|
|
342
|
+
async purges() {
|
|
343
|
+
const answer = await json('/api/purges', 'the purges', { missing: true });
|
|
344
|
+
return answer?.purges ?? [];
|
|
345
|
+
},
|
|
346
|
+
|
|
347
|
+
releases: () => json('/api/releases', 'the release list'),
|
|
348
|
+
|
|
349
|
+
// The gate admits this read only with a live token.
|
|
350
|
+
checkToken: () => json('/api/releases', 'the token'),
|
|
351
|
+
|
|
352
|
+
health: () => json('/api/health', 'the health check'),
|
|
353
|
+
|
|
354
|
+
dryRun: (bytes, what = 'the dry run', { bump = null } = {}) => call(`/api/validate${query({ bump })}`, zipBody(bytes), what),
|
|
355
|
+
|
|
356
|
+
// The registry merges, mints, and answers the version; item.json's version names the base.
|
|
357
|
+
upload: (bytes, what = 'the upload', { bump = null, summary = null } = {}) => call(`/api/items${query({ bump, summary })}`, zipBody(bytes), what),
|
|
358
|
+
|
|
359
|
+
recordRelease: (manifest) =>
|
|
360
|
+
call('/api/releases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(manifest) }, `the release ${manifest.tag}`),
|
|
361
|
+
|
|
362
|
+
async warm(preset, tag) {
|
|
363
|
+
const what = `the preset ${preset}`;
|
|
364
|
+
const res = await send(`/api/bundles/presets/${encodeURIComponent(preset)}?release=${encodeURIComponent(tag)}`, { redirect: 'manual' });
|
|
365
|
+
if (res.status !== 302) throw await refused(res, what);
|
|
366
|
+
return res.headers.get('location');
|
|
367
|
+
},
|
|
368
|
+
|
|
369
|
+
release: (tag) => json(`/api/releases/${encodeURIComponent(tag)}`, `the release ${tag}`, { missing: true }),
|
|
370
|
+
};
|
|
371
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Between releases system.json's release tag is null: --tag names it, and the collection's versions are the pins.
|
|
2
|
+
|
|
3
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import semver from 'semver';
|
|
6
|
+
import { validate, loadContext } from '../validate/index.js';
|
|
7
|
+
import { formatDeclarers } from '../validate/collisions.js';
|
|
8
|
+
import { itemFiles, zipName, zip, sha256 } from './pack.js';
|
|
9
|
+
import { validateReleaseManifest } from './schema.js';
|
|
10
|
+
import { resolve } from './resolve.js';
|
|
11
|
+
import { SYSTEM_NAMESPACE, isSystemItem } from './system.js';
|
|
12
|
+
|
|
13
|
+
export async function packItem(item, ctx) {
|
|
14
|
+
const result = await validate(item, ctx);
|
|
15
|
+
if (result.rejections.length > 0) return { result, file: null, bytes: null, count: 0 };
|
|
16
|
+
const files = itemFiles(item);
|
|
17
|
+
return { result, file: zipName(item.manifest), bytes: zip(files), count: files.size };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class ReleaseError extends Error {}
|
|
21
|
+
|
|
22
|
+
export function releaseTag(system, catalog, tag = null) {
|
|
23
|
+
const versions = new Map([...catalog].map(([name, item]) => [name, item.manifest.version]));
|
|
24
|
+
const problems = [...versions.keys()].filter((n) => !isSystemItem(n)).map((n) => `${n} is outside ${SYSTEM_NAMESPACE}, and only ${SYSTEM_NAMESPACE}'s items enter a release.`);
|
|
25
|
+
const { tag: pinned, items: pins } = system.release;
|
|
26
|
+
if (pinned) {
|
|
27
|
+
if (tag && tag !== pinned) problems.push(`system.json's release is ${pinned}, and --tag names ${tag}.`);
|
|
28
|
+
for (const [name, version] of versions) {
|
|
29
|
+
if (!(name in pins)) problems.push(`system.json's release doesn't pin ${name}.`);
|
|
30
|
+
else if (pins[name] !== version) problems.push(`system.json pins ${name} at ${pins[name]}, and the checkout holds ${version}.`);
|
|
31
|
+
}
|
|
32
|
+
for (const name of Object.keys(pins)) {
|
|
33
|
+
if (!versions.has(name)) problems.push(`system.json pins ${name}, which the checkout doesn't hold.`);
|
|
34
|
+
}
|
|
35
|
+
} else if (!tag) {
|
|
36
|
+
problems.push("system.json's release has no tag. Name one with --tag v<semver>.");
|
|
37
|
+
} else if (!tag.startsWith('v') || !semver.valid(tag.slice(1)) || tag.includes('+')) {
|
|
38
|
+
problems.push(`${tag} is not a release tag. A tag is v<semver>, as in v0.1.0.`);
|
|
39
|
+
}
|
|
40
|
+
if (problems.length > 0) throw new ReleaseError(problems.join('\n'));
|
|
41
|
+
return pinned ?? tag;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Ingest order: members and frames' format declarers join the dependencies for ordering alone, since resolve reads neither.
|
|
45
|
+
// A declarer that depends on the framed item stays after it, and that upload warns instead.
|
|
46
|
+
export function publishOrder(catalog, foundation) {
|
|
47
|
+
const withMembers = (m) => ({ ...m, dependencies: { ...m.dependencies, ...Object.fromEntries((m.members ?? []).map((x) => [x, '*'])) } });
|
|
48
|
+
const base = new Map([...catalog].map(([n, item]) => [n, withMembers(item.manifest)]));
|
|
49
|
+
const reaches = (from, to, seen = new Set()) => {
|
|
50
|
+
if (from === to) return true;
|
|
51
|
+
if (seen.has(from)) return false;
|
|
52
|
+
seen.add(from);
|
|
53
|
+
return Object.keys(base.get(from)?.dependencies ?? {}).some((d) => reaches(d, to, seen));
|
|
54
|
+
};
|
|
55
|
+
const declarers = formatDeclarers(catalog.values());
|
|
56
|
+
const framed = (m) =>
|
|
57
|
+
(m.files ?? [])
|
|
58
|
+
.flatMap((f) => (typeof f.frame?.format === 'string' ? [...(declarers.get(f.frame.format) ?? [])] : []))
|
|
59
|
+
.filter((d) => !reaches(d, m.name));
|
|
60
|
+
const manifests = new Map(
|
|
61
|
+
[...base].map(([n, m]) => [n, { ...m, dependencies: { ...m.dependencies, ...Object.fromEntries(framed(m).map((x) => [x, '*'])) } }]),
|
|
62
|
+
);
|
|
63
|
+
return resolve([...manifests.keys()].sort(), manifests, { foundation });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Writes nothing when any item is rejected.
|
|
67
|
+
export async function packRelease({ root, tag = null, out = null, system = null }) {
|
|
68
|
+
if (!system && !existsSync(join(root, 'system.json'))) throw new ReleaseError("A release takes its tag and pins from system.json's release block, and the collection holds no system.json.");
|
|
69
|
+
system ??= JSON.parse(readFileSync(join(root, 'system.json'), 'utf8'));
|
|
70
|
+
const ctx = await loadContext(root);
|
|
71
|
+
const members = new Map([...ctx.catalog].filter(([n]) => isSystemItem(n)));
|
|
72
|
+
if (members.size === 0) throw new ReleaseError(`The collection holds no ${SYSTEM_NAMESPACE} item, and only ${SYSTEM_NAMESPACE}'s items enter a release.`);
|
|
73
|
+
const name = releaseTag(system, members, tag);
|
|
74
|
+
const results = [];
|
|
75
|
+
for (const item of members.values()) results.push(await validate(item, ctx));
|
|
76
|
+
const rejected = results.filter((r) => r.rejections.length > 0);
|
|
77
|
+
if (rejected.length > 0) return { tag: name, dir: null, manifest: null, results, rejected };
|
|
78
|
+
|
|
79
|
+
const order = publishOrder(members, system.foundation);
|
|
80
|
+
const dir = out ?? join(root, 'build/release', name);
|
|
81
|
+
mkdirSync(dir, { recursive: true });
|
|
82
|
+
for (const file of readdirSync(dir)) {
|
|
83
|
+
if (file.endsWith('.zip') || file === 'release.json') rmSync(join(dir, file));
|
|
84
|
+
}
|
|
85
|
+
const items = order.map((n) => {
|
|
86
|
+
const item = ctx.catalog.get(n);
|
|
87
|
+
const bytes = zip(itemFiles(item));
|
|
88
|
+
const file = zipName(item.manifest);
|
|
89
|
+
writeFileSync(join(dir, file), bytes);
|
|
90
|
+
return { name: n, version: item.manifest.version, file, sha256: sha256(bytes) };
|
|
91
|
+
});
|
|
92
|
+
const manifest = { tag: name, foundation: system.foundation, ...(system.fixtures ? { fixtures: system.fixtures } : {}), presets: system.presets, items };
|
|
93
|
+
writeFileSync(join(dir, 'release.json'), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
94
|
+
return { tag: name, dir, manifest, results, rejected };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function readRelease(dir) {
|
|
98
|
+
let release;
|
|
99
|
+
try {
|
|
100
|
+
release = JSON.parse(readFileSync(join(dir, 'release.json'), 'utf8'));
|
|
101
|
+
} catch (err) {
|
|
102
|
+
throw new ReleaseError(`${dir} holds no readable release.json: ${err.message}`);
|
|
103
|
+
}
|
|
104
|
+
if (!validateReleaseManifest(release)) {
|
|
105
|
+
const errors = validateReleaseManifest.errors.map((e) => `${e.instancePath || '(root)'} ${e.message}`);
|
|
106
|
+
throw new ReleaseError(`release.json fails its schema: ${errors.join('; ')}.`);
|
|
107
|
+
}
|
|
108
|
+
const zips = release.items.map((entry) => {
|
|
109
|
+
let bytes;
|
|
110
|
+
try {
|
|
111
|
+
bytes = readFileSync(join(dir, entry.file));
|
|
112
|
+
} catch {
|
|
113
|
+
throw new ReleaseError(`${entry.file} is listed in release.json and missing from ${dir}.`);
|
|
114
|
+
}
|
|
115
|
+
if (sha256(bytes) !== entry.sha256) throw new ReleaseError(`${entry.file} doesn't match the hash release.json lists for it.`);
|
|
116
|
+
return { entry, bytes };
|
|
117
|
+
});
|
|
118
|
+
return { release, zips };
|
|
119
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { transform } from 'lightningcss';
|
|
2
|
+
|
|
3
|
+
// Blanked in place so LightningCSS's locations still land on the same character.
|
|
4
|
+
const blankComments = (text) => text.replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, ' '));
|
|
5
|
+
|
|
6
|
+
// LightningCSS reports a 0-based line and a 1-based column.
|
|
7
|
+
function preludeAt(text, loc) {
|
|
8
|
+
const lines = text.split('\n');
|
|
9
|
+
let i = 0;
|
|
10
|
+
for (let k = 0; k < loc.line; k++) i += lines[k].length + 1;
|
|
11
|
+
i += loc.column - 1;
|
|
12
|
+
const end = text.indexOf('{', i);
|
|
13
|
+
return text.slice(i, end < 0 ? undefined : end).replace(/\s+/g, ' ').trim();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function pastQuote(text, i) {
|
|
17
|
+
const quote = text[i];
|
|
18
|
+
let j = i + 1;
|
|
19
|
+
while (j < text.length && text[j] !== quote) j += text[j] === '\\' ? 2 : 1;
|
|
20
|
+
return j + 1;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function splitList(text) {
|
|
24
|
+
const out = [];
|
|
25
|
+
let depth = 0;
|
|
26
|
+
let from = 0;
|
|
27
|
+
for (let i = 0; i < text.length; i++) {
|
|
28
|
+
const c = text[i];
|
|
29
|
+
if (c === '"' || c === "'") i = pastQuote(text, i) - 1;
|
|
30
|
+
else if (c === '(' || c === '[') depth++;
|
|
31
|
+
else if (c === ')' || c === ']') depth--;
|
|
32
|
+
else if (c === ',' && depth === 0) {
|
|
33
|
+
out.push(text.slice(from, i).trim());
|
|
34
|
+
from = i + 1;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
out.push(text.slice(from).trim());
|
|
38
|
+
return out.filter(Boolean);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function closing(text, open) {
|
|
42
|
+
let depth = 0;
|
|
43
|
+
for (let i = open; i < text.length; i++) {
|
|
44
|
+
const c = text[i];
|
|
45
|
+
if (c === '"' || c === "'") i = pastQuote(text, i) - 1;
|
|
46
|
+
else if (c === '(') depth++;
|
|
47
|
+
else if (c === ')' && --depth === 0) return i;
|
|
48
|
+
}
|
|
49
|
+
return -1;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const WRAPPER = /^:(?:where|is)\(/i;
|
|
53
|
+
|
|
54
|
+
// A top-level :where() or :is() gives way to its contents; inside another function, only when it holds one selector.
|
|
55
|
+
function unwrap(selector) {
|
|
56
|
+
let depth = 0;
|
|
57
|
+
for (let i = 0; i < selector.length; i++) {
|
|
58
|
+
const c = selector[i];
|
|
59
|
+
if (c === '"' || c === "'") {
|
|
60
|
+
i = pastQuote(selector, i) - 1;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (c === '(') depth++;
|
|
64
|
+
else if (c === ')') depth--;
|
|
65
|
+
const wrapper = c === ':' ? WRAPPER.exec(selector.slice(i, i + 7)) : null;
|
|
66
|
+
if (!wrapper) continue;
|
|
67
|
+
const open = i + wrapper[0].length - 1;
|
|
68
|
+
const close = closing(selector, open);
|
|
69
|
+
if (close < 0) return [selector];
|
|
70
|
+
const inner = splitList(selector.slice(open + 1, close));
|
|
71
|
+
if (inner.length === 1 || depth === 0) return inner.flatMap((s) => unwrap(`${selector.slice(0, i)}${s}${selector.slice(close + 1)}`));
|
|
72
|
+
}
|
|
73
|
+
return [selector.replace(/\s+/g, ' ').trim()];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const nest = (selector, parent) => (selector.includes('&') ? selector.replaceAll('&', parent) : `${parent} ${selector}`);
|
|
77
|
+
|
|
78
|
+
const declaredIn = (declarations) =>
|
|
79
|
+
[...(declarations?.declarations ?? []), ...(declarations?.importantDeclarations ?? [])].filter((d) => d.property === 'custom').map((d) => d.value.name);
|
|
80
|
+
|
|
81
|
+
// Only the item's own stylesheets count. A condition (@media, @supports) leads its selector; a cascade layer doesn't.
|
|
82
|
+
export function repointedBy(texts, names) {
|
|
83
|
+
const out = new Map([...names].map((name) => [name, []]));
|
|
84
|
+
for (const text of texts) {
|
|
85
|
+
const code = blankComments(String(text));
|
|
86
|
+
const record = (declarations, selectors, conditions) => {
|
|
87
|
+
for (const name of declaredIn(declarations)) {
|
|
88
|
+
const list = out.get(name);
|
|
89
|
+
if (!list) continue;
|
|
90
|
+
for (const selector of selectors) {
|
|
91
|
+
for (const entry of unwrap(selector)) {
|
|
92
|
+
const shown = [...conditions, entry].join(' ');
|
|
93
|
+
if (!list.includes(shown)) list.push(shown);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
const walk = (rules, parents, conditions) => {
|
|
99
|
+
for (const rule of rules ?? []) {
|
|
100
|
+
if (rule.type === 'style') {
|
|
101
|
+
const own = splitList(preludeAt(code, rule.value.loc));
|
|
102
|
+
const selectors = parents ? parents.flatMap((p) => own.map((s) => nest(s, p))) : own;
|
|
103
|
+
record(rule.value.declarations, selectors, conditions);
|
|
104
|
+
walk(rule.value.rules, selectors, conditions);
|
|
105
|
+
} else if (rule.type === 'nested-declarations') {
|
|
106
|
+
if (parents) record(rule.value.declarations, parents, conditions);
|
|
107
|
+
} else if (Array.isArray(rule.value?.rules)) {
|
|
108
|
+
const condition = rule.type === 'layer-block' || !rule.value.loc ? [] : [preludeAt(code, rule.value.loc)];
|
|
109
|
+
walk(rule.value.rules, parents, [...conditions, ...condition]);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
try {
|
|
114
|
+
transform({ filename: 'style.css', code: Buffer.from(code), errorRecovery: true, visitor: { StyleSheet: (sheet) => walk(sheet.rules, null, []) } });
|
|
115
|
+
} catch {
|
|
116
|
+
// The validator reports the parse failure.
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// A collection's members are never read: resolving it loads none of them.
|
|
2
|
+
|
|
3
|
+
export class ResolveError extends Error {}
|
|
4
|
+
|
|
5
|
+
export function resolve(names, manifests, { foundation = [] } = {}) {
|
|
6
|
+
const byName = manifests instanceof Map ? manifests : new Map(manifests.map((m) => [m.name, m]));
|
|
7
|
+
const base = new Set(foundation);
|
|
8
|
+
for (const name of foundation) {
|
|
9
|
+
if (!byName.has(name)) throw new ResolveError(`Unknown foundation item ${name}`);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const order = [];
|
|
13
|
+
const state = new Map();
|
|
14
|
+
|
|
15
|
+
const visit = (name, path) => {
|
|
16
|
+
if (base.has(name) || state.get(name) === 'done') return;
|
|
17
|
+
if (state.get(name) === 'visiting') {
|
|
18
|
+
throw new ResolveError(`Dependency cycle: ${[...path, name].join(' -> ')}`);
|
|
19
|
+
}
|
|
20
|
+
const manifest = byName.get(name);
|
|
21
|
+
if (!manifest) {
|
|
22
|
+
throw new ResolveError(path.length ? `${path.at(-1)} depends on unknown item ${name}` : `Unknown item ${name}`);
|
|
23
|
+
}
|
|
24
|
+
state.set(name, 'visiting');
|
|
25
|
+
for (const dep of Object.keys(manifest.dependencies ?? {})) visit(dep, [...path, name]);
|
|
26
|
+
state.set(name, 'done');
|
|
27
|
+
order.push(name);
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
for (const name of names) visit(name, []);
|
|
31
|
+
return [...foundation, ...order];
|
|
32
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import Ajv2020 from 'ajv/dist/2020.js';
|
|
3
|
+
|
|
4
|
+
const load = (name) => JSON.parse(readFileSync(new URL(`../schema/${name}`, import.meta.url), 'utf8'));
|
|
5
|
+
|
|
6
|
+
const ajv = new Ajv2020({ allErrors: true });
|
|
7
|
+
// The structured files' schemas reference the manifest's shapes by $id.
|
|
8
|
+
ajv.addSchema(load('item.schema.json'));
|
|
9
|
+
ajv.addSchema(load('system.schema.json'));
|
|
10
|
+
|
|
11
|
+
export const validateItem = ajv.getSchema('item.schema.json');
|
|
12
|
+
export const validateSystem = ajv.getSchema('system.schema.json');
|
|
13
|
+
export const validateCollection = ajv.compile(load('collection.schema.json'));
|
|
14
|
+
export const validateLock = ajv.compile(load('collection.lock.schema.json'));
|
|
15
|
+
export const validateReleaseManifest = ajv.compile(load('release.schema.json'));
|
|
16
|
+
export const validateContract = ajv.compile(load('contract.schema.json'));
|
|
17
|
+
export const validateInterface = ajv.compile(load('interface.schema.json'));
|
|
18
|
+
export const validateVariants = ajv.compile(load('variants.schema.json'));
|
|
19
|
+
export const validateA11y = ajv.compile(load('a11y.schema.json'));
|
|
20
|
+
export const validateComposition = ajv.compile(load('composition.schema.json'));
|
|
21
|
+
|
|
22
|
+
export const STRUCTURED = {
|
|
23
|
+
contract: validateContract,
|
|
24
|
+
interface: validateInterface,
|
|
25
|
+
variants: validateVariants,
|
|
26
|
+
accessibility: validateA11y,
|
|
27
|
+
composition: validateComposition,
|
|
28
|
+
};
|