@milesroxas/design-hub 0.8.1 → 0.9.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/README.md +7 -2
- package/core/prototype.test.ts +83 -0
- package/core/prototype.ts +84 -0
- package/core/review/model.ts +7 -0
- package/core/review/policy.test.ts +4 -2
- package/core/review/policy.ts +4 -2
- package/core/review/service.test.ts +144 -4
- package/core/review/service.ts +70 -2
- package/core/review/store.ts +6 -0
- package/dist/core/prototype.d.ts +35 -0
- package/dist/core/prototype.js +84 -0
- package/dist/core/review/model.d.ts +2 -0
- package/dist/core/review/model.js +6 -0
- package/dist/core/review/policy.d.ts +1 -1
- package/dist/core/review/policy.js +1 -0
- package/dist/core/review/service.d.ts +23 -1
- package/dist/core/review/service.js +62 -3
- package/dist/core/review/store.d.ts +6 -0
- package/dist/core/review/store.js +6 -0
- package/dist/scripts/lib/cdp.js +6 -1
- package/dist/scripts/lib/export-smoke.d.ts +18 -0
- package/dist/scripts/lib/export-smoke.js +73 -0
- package/dist/scripts/new.js +5 -2
- package/dist/scripts/release-check.d.ts +5 -3
- package/dist/scripts/release-check.js +17 -4
- package/dist/scripts/share.d.ts +2 -2
- package/dist/server/api.js +8 -0
- package/dist/server/session.d.ts +5 -1
- package/dist/server/session.js +39 -21
- package/dist/vercel/proxy.js +44 -8
- package/dist/vite/boundary.d.ts +93 -0
- package/dist/vite/boundary.js +218 -0
- package/dist/vite/css-boundary.d.ts +39 -0
- package/dist/vite/css-boundary.js +167 -0
- package/dist/vite/kit.js +15 -6
- package/dist/vite/leaks.d.ts +37 -0
- package/dist/vite/leaks.js +331 -0
- package/dist/vite/plugin.js +2 -1
- package/dist/vite/registry.d.ts +15 -4
- package/dist/vite/registry.js +531 -27
- package/dist/vite/settle.d.ts +27 -0
- package/dist/vite/settle.js +185 -0
- package/package.json +4 -3
- package/shell/ClientViewNote.tsx +18 -0
- package/shell/Guide.tsx +17 -2
- package/shell/Index.tsx +257 -25
- package/shell/audience.test.ts +63 -0
- package/shell/audience.ts +47 -0
- package/shell/hub.ts +36 -0
- package/shell/main.tsx +39 -5
- package/shell/registry.ts +28 -7
- package/shell/registry.virtual.d.ts +12 -4
- package/shell/review/client.ts +16 -4
- package/shell/review/review.css +2 -2
- package/shell/shell.css +50 -3
- package/shell/system.css +5 -0
- package/skills/miles-deploy/SKILL.md +17 -0
- package/skills/miles-new-feature/SKILL.md +1 -1
- package/skills/miles-prototype/SKILL.md +14 -1
package/dist/server/session.js
CHANGED
|
@@ -6,12 +6,13 @@
|
|
|
6
6
|
// lasts until their access ends, at most 400 days (the longest a browser
|
|
7
7
|
// keeps a cookie). HMAC-SHA256 with GATE_SECRET.
|
|
8
8
|
//
|
|
9
|
-
// It also carries when the store last said yes (checkedAt). For CHECK_SECONDS
|
|
9
|
+
// It also carries the person's kind, and when the store last said yes (checkedAt). For CHECK_SECONDS
|
|
10
10
|
// after that the gate trusts the signature; then it asks the store again and
|
|
11
11
|
// issues a fresh cookie, so a revoke, a sign out everywhere or a changed
|
|
12
12
|
// access end reaches every request within CHECK_SECONDS, whatever it claims to be.
|
|
13
13
|
// Every function that reads the clock takes `at`, so tests need not wait.
|
|
14
14
|
import { base64url } from '../core/bytes.js';
|
|
15
|
+
import { PERSON_KINDS } from '../core/review/model.js';
|
|
15
16
|
export const PERSON_COOKIE = '__Host-hub_person';
|
|
16
17
|
const MAX_SESSION_SECONDS = 60 * 60 * 24 * 400;
|
|
17
18
|
/** How long the store's last yes is trusted before the gate asks again. */
|
|
@@ -47,41 +48,58 @@ export function sessionSeconds(endsAt, at = new Date()) {
|
|
|
47
48
|
const left = Math.floor(Date.parse(endsAt) / 1000) - seconds(at);
|
|
48
49
|
return Number.isFinite(left) ? Math.max(0, Math.min(MAX_SESSION_SECONDS, left)) : 0;
|
|
49
50
|
}
|
|
50
|
-
const VERSION = '
|
|
51
|
+
const VERSION = 'p4';
|
|
52
|
+
const OLD_VERSION = 'p3';
|
|
51
53
|
// The site is signed, never written into the token; a newline cannot occur in a URL, so the parts cannot run together.
|
|
52
|
-
const personMessage = (site, id, epoch, expires, checkedAt) => `${VERSION}\n${site}\n${id}.${epoch}.${expires}.${checkedAt}`;
|
|
53
|
-
const
|
|
54
|
+
const personMessage = (site, id, epoch, kind, expires, checkedAt) => `${VERSION}\n${site}\n${id}.${epoch}.${kind}.${expires}.${checkedAt}`;
|
|
55
|
+
const oldMessage = (site, id, epoch, expires, checkedAt) => `${OLD_VERSION}\n${site}\n${id}.${epoch}.${expires}.${checkedAt}`;
|
|
56
|
+
const tokenText = (id, epoch, kind, expires, checkedAt) => `${VERSION}.${id}.${epoch}.${kind}.${expires}.${checkedAt}`;
|
|
54
57
|
/** A token for someone the store said yes to at `at`, lasting to their access end. */
|
|
55
58
|
export async function issuePersonToken(gate, claim, endsAt, at = new Date()) {
|
|
56
59
|
const checkedAt = seconds(at);
|
|
57
60
|
const expires = checkedAt + sessionSeconds(endsAt, at);
|
|
58
|
-
const message = personMessage(gate.site, claim.id, claim.epoch, expires, checkedAt);
|
|
59
|
-
return `${tokenText(claim.id, claim.epoch, expires, checkedAt)}.${await hmac(gate.secret, message)}`;
|
|
61
|
+
const message = personMessage(gate.site, claim.id, claim.epoch, claim.kind, expires, checkedAt);
|
|
62
|
+
return `${tokenText(claim.id, claim.epoch, claim.kind, expires, checkedAt)}.${await hmac(gate.secret, message)}`;
|
|
60
63
|
}
|
|
61
64
|
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
65
|
+
const isKind = (k) => PERSON_KINDS.includes(k);
|
|
66
|
+
function parseCurrent(parts) {
|
|
67
|
+
const [, id, epoch, kind, expires, checkedAt, sig, extra] = parts;
|
|
68
|
+
if (!/^[a-z0-9]+$/.test(id ?? '') || !isKind(kind) || !sig || extra !== undefined)
|
|
69
|
+
return null;
|
|
70
|
+
if (![epoch, expires, checkedAt].every((n) => isCount(Number(n))))
|
|
71
|
+
return null;
|
|
72
|
+
const claim = { id, epoch: Number(epoch), kind, checkedAt: Number(checkedAt) };
|
|
73
|
+
const message = (site) => personMessage(site, id, claim.epoch, kind, Number(expires), claim.checkedAt);
|
|
74
|
+
return { claim, expires: Number(expires), sig, message };
|
|
75
|
+
}
|
|
76
|
+
function parseOld(parts) {
|
|
77
|
+
const [, id, epoch, expires, checkedAt, sig, extra] = parts;
|
|
78
|
+
if (!/^[a-z0-9]+$/.test(id ?? '') || !sig || extra !== undefined)
|
|
79
|
+
return null;
|
|
80
|
+
if (![epoch, expires, checkedAt].every((n) => isCount(Number(n))))
|
|
81
|
+
return null;
|
|
82
|
+
const claim = { id, epoch: Number(epoch), kind: null, checkedAt: Number(checkedAt) };
|
|
83
|
+
const message = (site) => oldMessage(site, id, claim.epoch, Number(expires), claim.checkedAt);
|
|
84
|
+
return { claim, expires: Number(expires), sig, message };
|
|
85
|
+
}
|
|
86
|
+
const PARSERS = {
|
|
87
|
+
[VERSION]: parseCurrent,
|
|
88
|
+
[OLD_VERSION]: parseOld,
|
|
69
89
|
};
|
|
70
90
|
/** The person a token names when its signature and expiry hold; the caller decides whether to ask the store. */
|
|
71
91
|
export async function readPersonToken(gate, token, at = new Date()) {
|
|
72
92
|
const parts = (token ?? '').split('.');
|
|
73
|
-
|
|
93
|
+
const parse = Object.hasOwn(PARSERS, parts[0]) ? PARSERS[parts[0]] : null;
|
|
94
|
+
const parsed = parse?.(parts);
|
|
95
|
+
if (!parsed || parsed.expires <= seconds(at))
|
|
74
96
|
return null;
|
|
75
|
-
|
|
76
|
-
if (Number(expires) <= seconds(at))
|
|
77
|
-
return null;
|
|
78
|
-
const message = personMessage(gate.site, id, Number(epoch), Number(expires), Number(checkedAt));
|
|
79
|
-
return sameText(sig, await hmac(gate.secret, message))
|
|
80
|
-
? { id, epoch: Number(epoch), checkedAt: Number(checkedAt) }
|
|
81
|
-
: null;
|
|
97
|
+
return sameText(parsed.sig, await hmac(gate.secret, parsed.message(gate.site))) ? parsed.claim : null;
|
|
82
98
|
}
|
|
83
99
|
/** Whether the store's yes in this claim is recent enough to trust without asking again. */
|
|
84
100
|
export function isFresh(claim, at = new Date()) {
|
|
101
|
+
if (claim.kind === null)
|
|
102
|
+
return false;
|
|
85
103
|
const age = seconds(at) - claim.checkedAt;
|
|
86
104
|
return age >= 0 && age < CHECK_SECONDS;
|
|
87
105
|
}
|
package/dist/vercel/proxy.js
CHANGED
|
@@ -12,13 +12,16 @@
|
|
|
12
12
|
// It carries when the store last said yes; after CHECK_SECONDS (5 minutes)
|
|
13
13
|
// the gate asks the store again on the next request of any kind, so a revoke,
|
|
14
14
|
// a sign out everywhere or a changed access end reaches every request within
|
|
15
|
-
// minutes. A store that does not answer is 503, never a sign out.
|
|
15
|
+
// minutes. A store that does not answer is 503, never a sign out. A Client
|
|
16
|
+
// asking for a prototype that is not client-facing, its page or any file
|
|
17
|
+
// built from it under /_p/<slug>/, gets 404. Without a session a
|
|
16
18
|
// page gets the sign-in page (401), which says what to do and has no form,
|
|
17
19
|
// and anything else a plain-text 401. Without GATE_SECRET the gate fails
|
|
18
20
|
// closed (503).
|
|
19
21
|
import { next } from '@vercel/functions';
|
|
20
22
|
import { base64, sha256 } from '../core/bytes.js';
|
|
21
23
|
import { escapeHtml } from '../core/html.js';
|
|
24
|
+
import { isPrototypeSlug, prototypeOfPath } from '../core/prototype.js';
|
|
22
25
|
import { deployedReview } from '../server/api.js';
|
|
23
26
|
import { clearedCookie, isFresh, issuePersonToken, PERSON_COOKIE, readCookie, readGate, readPersonToken, sameOrigin, sessionCookie, sessionSeconds, } from '../server/session.js';
|
|
24
27
|
const DEFAULT_SITE_NAME = 'Prototypes';
|
|
@@ -149,6 +152,9 @@ async function page(request, status, html, text, extra = {}) {
|
|
|
149
152
|
return new Response(request.method === 'HEAD' ? null : html, { status, headers });
|
|
150
153
|
}
|
|
151
154
|
const unavailable = (request, error) => plain(request, 503, error);
|
|
155
|
+
/** One answer for a prototype a Client may not have, whether it is internal or not there at all. */
|
|
156
|
+
const notFound = (request) => plain(request, 404, NOT_FOUND);
|
|
157
|
+
const NOT_FOUND = 'Not found.';
|
|
152
158
|
/** The store did not answer: a 503 that passes, so it says when to try again. */
|
|
153
159
|
const storeDown = (request) => plain(request, 503, STORE_DOWN, { retryAfter: 30 });
|
|
154
160
|
const STORE_DOWN = 'The review store did not answer. Try again in a minute.';
|
|
@@ -180,7 +186,8 @@ async function showLink(ctx, token) {
|
|
|
180
186
|
}
|
|
181
187
|
/** The cookie for someone the store just said yes to, lasting to their access end. */
|
|
182
188
|
async function sessionFor(gate, person, at) {
|
|
183
|
-
const
|
|
189
|
+
const claim = { id: person.id, epoch: person.epoch, kind: person.kind };
|
|
190
|
+
const token = await issuePersonToken(gate, claim, person.accessEndsAt, at);
|
|
184
191
|
return sessionCookie(PERSON_COOKIE, token, sessionSeconds(person.accessEndsAt, at));
|
|
185
192
|
}
|
|
186
193
|
async function signInWithLink(ctx, token) {
|
|
@@ -220,23 +227,52 @@ function signedOut({ siteName, request }, staleCookie) {
|
|
|
220
227
|
return page(request, 401, signInPage(siteName), SIGNED_OUT, extra);
|
|
221
228
|
}
|
|
222
229
|
const pass = (cookie) => next({ headers: { 'cache-control': 'private, no-store', ...(cookie ? { 'set-cookie': cookie } : {}) } });
|
|
230
|
+
/**
|
|
231
|
+
* The prototype boundary, for a Client only: a path that belongs to a
|
|
232
|
+
* prototype (its page, or a file under /_p/<slug>/) passes when that
|
|
233
|
+
* prototype is client-facing, asked of the store on every request. Anything
|
|
234
|
+
* else is the same 404, for an internal prototype, one that does not exist and
|
|
235
|
+
* /_p/all.js alike, so the answer says nothing about what is there. A store
|
|
236
|
+
* that does not answer is 503. Hub paths pass with no store read.
|
|
237
|
+
*/
|
|
238
|
+
async function clientMay(ctx, review, slug) {
|
|
239
|
+
if (!isPrototypeSlug(slug))
|
|
240
|
+
return notFound(ctx.request);
|
|
241
|
+
const audience = await ask(() => review.audienceOf(slug));
|
|
242
|
+
if (audience === undefined)
|
|
243
|
+
return storeDown(ctx.request);
|
|
244
|
+
return audience === 'client' ? null : notFound(ctx.request);
|
|
245
|
+
}
|
|
246
|
+
/** Asks the store whether a stale session still holds: the person, or the answer that ends the request. */
|
|
247
|
+
async function recheck(ctx, review, claim) {
|
|
248
|
+
const current = await ask(() => review.sessionPerson(claim.id, claim.epoch));
|
|
249
|
+
if (current === undefined)
|
|
250
|
+
return storeDown(ctx.request);
|
|
251
|
+
return current ?? (await signedOut(ctx, true));
|
|
252
|
+
}
|
|
223
253
|
/**
|
|
224
254
|
* A signed session. While the store's last yes is fresh the signature is
|
|
225
255
|
* enough. Once it is stale the store is asked, whatever the request says it
|
|
226
256
|
* is (its headers are the client's to choose): yes passes with a fresh cookie
|
|
227
257
|
* whose expiry follows the person's current access end; no signs out and
|
|
228
|
-
* clears the cookie; no answer is 503 and the cookie stays.
|
|
258
|
+
* clears the cookie; no answer is 503 and the cookie stays. A p3 cookie,
|
|
259
|
+
* which carries no kind, is always stale, so its first request re-issues it.
|
|
260
|
+
* Then, for anyone but Studio, the prototype boundary on a prototype's path.
|
|
229
261
|
*/
|
|
230
262
|
async function personSession(ctx, gate, claim) {
|
|
231
|
-
|
|
263
|
+
const slug = prototypeOfPath(new URL(ctx.request.url).pathname);
|
|
264
|
+
const fresh = isFresh(claim, ctx.at);
|
|
265
|
+
if (fresh && (claim.kind === 'studio' || slug === null))
|
|
232
266
|
return pass();
|
|
233
267
|
const setup = deployedReview(process.env, null, () => ctx.at);
|
|
234
268
|
if ('error' in setup)
|
|
235
269
|
return unavailable(ctx.request, setup.error);
|
|
236
|
-
const current = await
|
|
237
|
-
if (current
|
|
238
|
-
return
|
|
239
|
-
|
|
270
|
+
const current = fresh ? null : await recheck(ctx, setup.review, claim);
|
|
271
|
+
if (current instanceof Response)
|
|
272
|
+
return current;
|
|
273
|
+
const kind = current ? current.kind : claim.kind;
|
|
274
|
+
const refused = kind !== 'studio' && slug !== null ? await clientMay(ctx, setup.review, slug) : null;
|
|
275
|
+
return refused ?? pass(current ? await sessionFor(gate, current, ctx.at) : undefined);
|
|
240
276
|
}
|
|
241
277
|
/** The middleware a project's proxy.ts default-exports. */
|
|
242
278
|
export function createProxy({ siteName = DEFAULT_SITE_NAME, now = () => new Date() } = {}) {
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import nodePath from 'node:path';
|
|
2
|
+
/** The virtual module Studio and a Client load a prototype through: its README and its loader. */
|
|
3
|
+
export declare const ENTRY_ID = "virtual:design-hub/entry/";
|
|
4
|
+
/**
|
|
5
|
+
* A path with every symlink followed and in the letter case it has on disk,
|
|
6
|
+
* or the path itself when it is not a file on disk (a virtual module). The
|
|
7
|
+
* native call, because Node's own keeps the case as written: on a disk that
|
|
8
|
+
* folds case (macOS, Windows) `Prototypes/beta/x.css` is `prototypes/beta/x.css`,
|
|
9
|
+
* and an owner must be the same either way.
|
|
10
|
+
*/
|
|
11
|
+
export declare const real: (path: string) => string;
|
|
12
|
+
/**
|
|
13
|
+
* Which prototype folder a module or file belongs to, on its real path (a
|
|
14
|
+
* symlink into another prototype's folder is that prototype's): the first
|
|
15
|
+
* segment under `prototypes/`, whatever its name (a file directly there is
|
|
16
|
+
* owned by its own name, so nothing under `prototypes/` is ever the hub's),
|
|
17
|
+
* or null for anything outside it. A prototype's virtual entry belongs to its
|
|
18
|
+
* slug. Whether that owner is a prototype at all is for the caller: a folder
|
|
19
|
+
* with no README, or a file directly in `prototypes/`, is refused (looseFile).
|
|
20
|
+
*/
|
|
21
|
+
export declare function ownerOf(prototypes: string, paths?: typeof nodePath): (id: string) => string | null;
|
|
22
|
+
/** The owners of a set of modules or files, each once, sorted; none for shared code. */
|
|
23
|
+
export declare function ownersOf(owner: (id: string) => string | null, ids: readonly string[]): string[];
|
|
24
|
+
/** Where a built file goes: under `_p/<slug>/` when one prototype owns it, else the shared `assets/`. */
|
|
25
|
+
export declare function placed(owners: string[], pattern: string, shared?: boolean): string;
|
|
26
|
+
/** A file resolved against the Vite root: Rolldown reports an asset's original files relative to it. */
|
|
27
|
+
export declare const fromRoot: (viteRoot: string) => (file: string) => string;
|
|
28
|
+
/** A path for an error message: from the project root, with no `\0` or query. */
|
|
29
|
+
export declare const relativeTo: (root: string, path: string) => string;
|
|
30
|
+
/** The error for a file reaching a prototype's file, naming both: another prototype's, or (from the kit or the hub) any prototype's. */
|
|
31
|
+
export declare function crossImport(root: string, importer: string, imported: string, fromPrototype?: boolean): string;
|
|
32
|
+
/** Who owns a built file's content: a prototype's slug, or null for the hub, the kit or a package. */
|
|
33
|
+
export type Owner = string | null;
|
|
34
|
+
/**
|
|
35
|
+
* One source of a built asset's content: a file, or for a stylesheet a CSS
|
|
36
|
+
* module it holds. `writer` is the owner of the chunk that wrote a
|
|
37
|
+
* stylesheet, whose name Vite took from that chunk.
|
|
38
|
+
*/
|
|
39
|
+
export type Source = {
|
|
40
|
+
owner: Owner;
|
|
41
|
+
file: string;
|
|
42
|
+
writer?: Owner;
|
|
43
|
+
};
|
|
44
|
+
/** Where one owner's copy of an asset lives. */
|
|
45
|
+
export type Placement = {
|
|
46
|
+
owner: Owner;
|
|
47
|
+
fileName: string;
|
|
48
|
+
};
|
|
49
|
+
/** Files the build names on purpose: never moved, copied, renamed or read for references. */
|
|
50
|
+
export declare const isFixed: (fileName: string) => boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Where an asset must be, one file per owner of its content: `_p/<slug>/`
|
|
53
|
+
* for a prototype, `assets/` for the hub or the kit. Null when it is already
|
|
54
|
+
* there or nothing shows where its content comes from.
|
|
55
|
+
*/
|
|
56
|
+
export declare function placementsOf(fileName: string, sources: Source[] | null, slugs: readonly string[], hash: string): Placement[] | null;
|
|
57
|
+
/**
|
|
58
|
+
* What a reader gets for a file it reads: its own owner's copy, else the
|
|
59
|
+
* hub's (anyone may read the kit), else nothing, which the build refuses.
|
|
60
|
+
*/
|
|
61
|
+
export declare function copyFor(places: Placement[], reader: Owner): Placement | null;
|
|
62
|
+
/** The error for a file that reads what another prototype owns, naming reader and source. */
|
|
63
|
+
export declare const readsAcross: (reader: string, source: Source) => string;
|
|
64
|
+
/** The error for a reach into `prototypes/` outside any prototype's folder. */
|
|
65
|
+
export declare const looseFile: (root: string, importer: string, file: string) => string;
|
|
66
|
+
/** A stylesheet language whose own `@import` and `@use` resolve inside its preprocessor. */
|
|
67
|
+
export declare const PREPROCESSED: RegExp;
|
|
68
|
+
/** The error for a prototype or the project's kit/ importing Sass, Less or Stylus. */
|
|
69
|
+
export declare const preprocessed: (root: string, importer: string, file: string) => string;
|
|
70
|
+
/** The error for a stylesheet the build cannot read. */
|
|
71
|
+
export declare const unreadable: (root: string, file: string, line: number, column: number, reason: string) => string;
|
|
72
|
+
/**
|
|
73
|
+
* The paths a module names with `new URL('…', import.meta.url)`, found with
|
|
74
|
+
* the parser Vite itself uses (oxc, through `parseSync`), on the code Vite's
|
|
75
|
+
* own `new URL` plugin sees: TypeScript and JSX already compiled. So a quote
|
|
76
|
+
* in a regex literal, in JSX text, in a string or in a comment never hides
|
|
77
|
+
* one or fakes one. A template with `${…}` becomes an import.meta.glob, which
|
|
78
|
+
* the resolver sees; a data URL and one marked `@vite-ignore` are skipped, as
|
|
79
|
+
* Vite skips them. The query stays: `?inline` is a reach too. Null when the
|
|
80
|
+
* code does not parse (Vite then reports the error itself).
|
|
81
|
+
*/
|
|
82
|
+
export declare function newUrlTargets(code: string, file: string): string[] | null;
|
|
83
|
+
/** The error for a built file with no record of where its content comes from. */
|
|
84
|
+
export declare const unrecorded: (fileName: string) => string;
|
|
85
|
+
/** The error for a worker that reaches a prototype's folder. */
|
|
86
|
+
export declare const workerRefused: (root: string, file: string) => string;
|
|
87
|
+
/**
|
|
88
|
+
* A file's text with every reference to `from` pointed at `to`: the whole
|
|
89
|
+
* path, and the path relative to the referring file when that differs.
|
|
90
|
+
*/
|
|
91
|
+
export declare function repointText(text: string, referrer: string, from: string, to: string): string;
|
|
92
|
+
/** A chunk where its modules say: `_p/<slug>/` for one prototype's, never two. */
|
|
93
|
+
export declare function chunkProblems(fileName: string, owners: string[]): string[];
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// The prototype boundary as the build sees it. A built file is owned by where
|
|
3
|
+
// its content comes from, never by who reads it:
|
|
4
|
+
//
|
|
5
|
+
// - owned only by prototype `a` (its modules, or for a stylesheet the
|
|
6
|
+
// modules whose CSS it holds): it lives in `_p/a/`, and only `a`'s files read it;
|
|
7
|
+
// - owned by nothing under `prototypes/` (the hub, the kit, node_modules): it
|
|
8
|
+
// lives in `assets/` and is never copied into a prototype's folder;
|
|
9
|
+
// - the same bytes from several owners (Rolldown writes them once): one copy
|
|
10
|
+
// per owner, each owner's files pointed at its own.
|
|
11
|
+
//
|
|
12
|
+
// A file that reads what another prototype owns, or a hub file that reads
|
|
13
|
+
// what a prototype owns, fails the build. These are the pure rules;
|
|
14
|
+
// vite/registry.ts and vite/settle.ts apply them to the modules and bundle
|
|
15
|
+
// Rolldown hands them.
|
|
16
|
+
import { realpathSync } from 'node:fs';
|
|
17
|
+
import nodePath, { extname, posix, resolve } from 'node:path';
|
|
18
|
+
import { parseSync, Visitor } from 'vite';
|
|
19
|
+
import { ALL_FILE, PROTOTYPE_DIR } from '../core/prototype.js';
|
|
20
|
+
/** The virtual module Studio and a Client load a prototype through: its README and its loader. */
|
|
21
|
+
export const ENTRY_ID = 'virtual:design-hub/entry/';
|
|
22
|
+
const realCache = new Map();
|
|
23
|
+
/**
|
|
24
|
+
* A path with every symlink followed and in the letter case it has on disk,
|
|
25
|
+
* or the path itself when it is not a file on disk (a virtual module). The
|
|
26
|
+
* native call, because Node's own keeps the case as written: on a disk that
|
|
27
|
+
* folds case (macOS, Windows) `Prototypes/beta/x.css` is `prototypes/beta/x.css`,
|
|
28
|
+
* and an owner must be the same either way.
|
|
29
|
+
*/
|
|
30
|
+
export const real = (path) => {
|
|
31
|
+
let found = realCache.get(path);
|
|
32
|
+
if (found === undefined) {
|
|
33
|
+
try {
|
|
34
|
+
found = realpathSync.native(path);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
found = path;
|
|
38
|
+
}
|
|
39
|
+
realCache.set(path, found);
|
|
40
|
+
}
|
|
41
|
+
return found;
|
|
42
|
+
};
|
|
43
|
+
/** A module id as a file path: no leading `\0`, no `?query`. */
|
|
44
|
+
const fileOf = (id) => id.replace(/^\0/, '').replace(/\?.*$/, '');
|
|
45
|
+
/**
|
|
46
|
+
* Which prototype folder a module or file belongs to, on its real path (a
|
|
47
|
+
* symlink into another prototype's folder is that prototype's): the first
|
|
48
|
+
* segment under `prototypes/`, whatever its name (a file directly there is
|
|
49
|
+
* owned by its own name, so nothing under `prototypes/` is ever the hub's),
|
|
50
|
+
* or null for anything outside it. A prototype's virtual entry belongs to its
|
|
51
|
+
* slug. Whether that owner is a prototype at all is for the caller: a folder
|
|
52
|
+
* with no README, or a file directly in `prototypes/`, is refused (looseFile).
|
|
53
|
+
*/
|
|
54
|
+
export function ownerOf(prototypes, paths = nodePath) {
|
|
55
|
+
const roots = [...new Set([prototypes, real(prototypes)])];
|
|
56
|
+
return (id) => {
|
|
57
|
+
const path = real(fileOf(id));
|
|
58
|
+
if (path.startsWith(ENTRY_ID))
|
|
59
|
+
return path.slice(ENTRY_ID.length) || null;
|
|
60
|
+
if (!paths.isAbsolute(path))
|
|
61
|
+
return null;
|
|
62
|
+
// By the platform's path rules, so a Windows path (backslashes from realpath, `/` from Vite) is judged as a POSIX one.
|
|
63
|
+
for (const root of roots) {
|
|
64
|
+
const rest = paths.relative(root, path);
|
|
65
|
+
if (rest === '..' || rest.startsWith(`..${paths.sep}`) || paths.isAbsolute(rest))
|
|
66
|
+
continue;
|
|
67
|
+
// A file directly in prototypes/ is owned by its own name: nothing there is the hub's.
|
|
68
|
+
return rest.split(paths.sep)[0] || null;
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** The owners of a set of modules or files, each once, sorted; none for shared code. */
|
|
74
|
+
export function ownersOf(owner, ids) {
|
|
75
|
+
return [...new Set(ids.map(owner).filter((o) => o !== null))].sort();
|
|
76
|
+
}
|
|
77
|
+
/** Where a built file goes: under `_p/<slug>/` when one prototype owns it, else the shared `assets/`. */
|
|
78
|
+
export function placed(owners, pattern, shared = false) {
|
|
79
|
+
return owners.length === 1 && !shared ? `${PROTOTYPE_DIR}/${owners[0]}/${pattern}` : `assets/${pattern}`;
|
|
80
|
+
}
|
|
81
|
+
/** A file resolved against the Vite root: Rolldown reports an asset's original files relative to it. */
|
|
82
|
+
export const fromRoot = (viteRoot) => (file) => resolve(viteRoot, file);
|
|
83
|
+
/** A path for an error message: from the project root, with no `\0` or query. */
|
|
84
|
+
export const relativeTo = (root, path) => fileOf(path)
|
|
85
|
+
.replace(`${real(root)}/`, '')
|
|
86
|
+
.replace(`${root}/`, '');
|
|
87
|
+
/** The error for a file reaching a prototype's file, naming both: another prototype's, or (from the kit or the hub) any prototype's. */
|
|
88
|
+
export function crossImport(root, importer, imported, fromPrototype = true) {
|
|
89
|
+
const whose = fromPrototype
|
|
90
|
+
? "another prototype's file"
|
|
91
|
+
: "a prototype's file, which the kit and the hub never read";
|
|
92
|
+
return `${relativeTo(root, importer)} imports ${relativeTo(root, imported)}, ${whose}. A prototype imports only @kit/* and its own folder: copy the file into this prototype, or move it into kit/.`;
|
|
93
|
+
}
|
|
94
|
+
/** Files the build names on purpose: never moved, copied, renamed or read for references. */
|
|
95
|
+
export const isFixed = (fileName) => fileName === ALL_FILE ||
|
|
96
|
+
!fileName.includes('/') ||
|
|
97
|
+
fileName.startsWith('_gate/') ||
|
|
98
|
+
(fileName.startsWith(`${PROTOTYPE_DIR}/`) && fileName.endsWith('/entry.js'));
|
|
99
|
+
const folderOf = (owner) => (owner === null ? 'assets' : `${PROTOTYPE_DIR}/${owner}`);
|
|
100
|
+
const HASH_TAIL = /-[\w-]{8}$/;
|
|
101
|
+
/** A built name without its hash: `logo-Fji5aE1.png` is `logo`. */
|
|
102
|
+
const stemOf = (base) => posix.basename(base, extname(base)).replace(HASH_TAIL, '');
|
|
103
|
+
/** What Rolldown makes of a name: the characters a URL or a file system would trip on become `_`. */
|
|
104
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: the control characters are what it replaces
|
|
105
|
+
const sanitize = (name) => name.replace(/[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g, '_');
|
|
106
|
+
/**
|
|
107
|
+
* The name one owner's copy takes. The built name, which Rolldown has
|
|
108
|
+
* already made safe, while every source of the file, and the chunk that
|
|
109
|
+
* wrote it, is that owner's; else from that owner's own source (file or CSS
|
|
110
|
+
* module), made safe the same way. So a copy never carries a name from
|
|
111
|
+
* another owner's file: not another prototype's, and in `assets/` never a
|
|
112
|
+
* prototype's at all.
|
|
113
|
+
*/
|
|
114
|
+
function nameFor(base, owner, sources, slugs, hash) {
|
|
115
|
+
const ext = extname(base);
|
|
116
|
+
const elsewhere = sources.some((s) => s.owner !== owner || (s.writer !== undefined && s.writer !== owner));
|
|
117
|
+
const foreign = slugs.some((s) => s !== owner && stemOf(base).includes(s));
|
|
118
|
+
if (!elsewhere && !foreign)
|
|
119
|
+
return base;
|
|
120
|
+
const own = sources.find((s) => s.owner === owner);
|
|
121
|
+
const stem = own ? sanitize(posix.basename(own.file, extname(own.file))) : (owner ?? 'asset');
|
|
122
|
+
return stemOf(base) === stem ? base : `${stem}-${hash}${ext}`;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Where an asset must be, one file per owner of its content: `_p/<slug>/`
|
|
126
|
+
* for a prototype, `assets/` for the hub or the kit. Null when it is already
|
|
127
|
+
* there or nothing shows where its content comes from.
|
|
128
|
+
*/
|
|
129
|
+
export function placementsOf(fileName, sources, slugs, hash) {
|
|
130
|
+
if (!sources?.length || isFixed(fileName))
|
|
131
|
+
return null;
|
|
132
|
+
const owners = [...new Set(sources.map((s) => s.owner))].sort((a, b) => String(a).localeCompare(String(b)));
|
|
133
|
+
const base = posix.basename(fileName);
|
|
134
|
+
const places = owners.map((owner) => ({
|
|
135
|
+
owner,
|
|
136
|
+
fileName: `${folderOf(owner)}/${nameFor(base, owner, sources, slugs, hash)}`,
|
|
137
|
+
}));
|
|
138
|
+
return places.length === 1 && places[0].fileName === fileName ? null : places;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* What a reader gets for a file it reads: its own owner's copy, else the
|
|
142
|
+
* hub's (anyone may read the kit), else nothing, which the build refuses.
|
|
143
|
+
*/
|
|
144
|
+
export function copyFor(places, reader) {
|
|
145
|
+
return places.find((p) => p.owner === reader) ?? places.find((p) => p.owner === null) ?? null;
|
|
146
|
+
}
|
|
147
|
+
/** The error for a file that reads what another prototype owns, naming reader and source. */
|
|
148
|
+
export const readsAcross = (reader, source) => `${reader} reads ${source.file}, which belongs to prototypes/${source.owner}/. A prototype's files are read only by that prototype: copy the file into the one that reads it, or move it into kit/.`;
|
|
149
|
+
/** The error for a reach into `prototypes/` outside any prototype's folder. */
|
|
150
|
+
export const looseFile = (root, importer, file) => `${relativeTo(root, importer)} imports ${relativeTo(root, file)}, which is in prototypes/ but in no prototype's folder. Nothing in prototypes/ is shared: shared code belongs in kit/.`;
|
|
151
|
+
/** A stylesheet language whose own `@import` and `@use` resolve inside its preprocessor. */
|
|
152
|
+
export const PREPROCESSED = /\.(scss|sass|less|styl|stylus)$/;
|
|
153
|
+
/** The error for a prototype or the project's kit/ importing Sass, Less or Stylus. */
|
|
154
|
+
export const preprocessed = (root, importer, file) => `${relativeTo(root, importer)} imports ${relativeTo(root, file)}. Sass, Less and Stylus are refused in prototypes and kit/: they resolve their own @import and @use inside the preprocessor, where the build cannot check them for reaches into a prototype's folder. Use plain CSS or .pcss.`;
|
|
155
|
+
/** The error for a stylesheet the build cannot read. */
|
|
156
|
+
export const unreadable = (root, file, line, column, reason) => `${relativeTo(root, file)}:${line}:${column}: this stylesheet does not parse (${reason}). Fix the stylesheet: the build reads every stylesheet for reaches into a prototype's folder and refuses one it cannot read.`;
|
|
157
|
+
/** The path a `new URL(…)` argument names, when it is a literal: a string, or a template with no `${…}`. */
|
|
158
|
+
function literalPath(arg) {
|
|
159
|
+
if (arg.type === 'Literal' && typeof arg.value === 'string')
|
|
160
|
+
return arg.value;
|
|
161
|
+
if (arg.type === 'TemplateLiteral' && !arg.expressions?.length)
|
|
162
|
+
return arg.quasis?.[0]?.value.cooked ?? null;
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
const isImportMetaUrl = (arg) => arg?.type === 'MemberExpression' && arg.object?.type === 'MetaProperty' && arg.property?.name === 'url';
|
|
166
|
+
/**
|
|
167
|
+
* The paths a module names with `new URL('…', import.meta.url)`, found with
|
|
168
|
+
* the parser Vite itself uses (oxc, through `parseSync`), on the code Vite's
|
|
169
|
+
* own `new URL` plugin sees: TypeScript and JSX already compiled. So a quote
|
|
170
|
+
* in a regex literal, in JSX text, in a string or in a comment never hides
|
|
171
|
+
* one or fakes one. A template with `${…}` becomes an import.meta.glob, which
|
|
172
|
+
* the resolver sees; a data URL and one marked `@vite-ignore` are skipped, as
|
|
173
|
+
* Vite skips them. The query stays: `?inline` is a reach too. Null when the
|
|
174
|
+
* code does not parse (Vite then reports the error itself).
|
|
175
|
+
*/
|
|
176
|
+
export function newUrlTargets(code, file) {
|
|
177
|
+
const parsed = parseSync(`${file.replace(/\?.*$/, '')}.js`, code, { lang: 'js', sourceType: 'module' });
|
|
178
|
+
if (parsed.errors.length)
|
|
179
|
+
return null;
|
|
180
|
+
const found = [];
|
|
181
|
+
new Visitor({
|
|
182
|
+
NewExpression(node) {
|
|
183
|
+
const callee = node.callee;
|
|
184
|
+
const [url, base] = node.arguments;
|
|
185
|
+
if (callee.type !== 'Identifier' || callee.name !== 'URL' || !url || !isImportMetaUrl(base))
|
|
186
|
+
return;
|
|
187
|
+
const ignored = parsed.comments.some((c) => c.start >= node.start && c.end <= url.start && c.value.includes('@vite-ignore'));
|
|
188
|
+
const path = literalPath(url);
|
|
189
|
+
if (path !== null && !ignored && !path.startsWith('data:'))
|
|
190
|
+
found.push(path);
|
|
191
|
+
},
|
|
192
|
+
}).visit(parsed.program);
|
|
193
|
+
return found;
|
|
194
|
+
}
|
|
195
|
+
/** The error for a built file with no record of where its content comes from. */
|
|
196
|
+
export const unrecorded = (fileName) => `${fileName} was written with no record of where its content comes from, so the build cannot tell who may read it. Only the hub's fixed files and a worker built from the kit may be written that way.`;
|
|
197
|
+
/** The error for a worker that reaches a prototype's folder. */
|
|
198
|
+
export const workerRefused = (root, file) => `${relativeTo(root, file)} is in a web worker. A worker cannot use a prototype's files: Vite builds it as a file of its own that the build cannot place in the prototype's folder. Run the work on the main thread, or build the worker from kit/ files only.`;
|
|
199
|
+
/**
|
|
200
|
+
* A file's text with every reference to `from` pointed at `to`: the whole
|
|
201
|
+
* path, and the path relative to the referring file when that differs.
|
|
202
|
+
*/
|
|
203
|
+
export function repointText(text, referrer, from, to) {
|
|
204
|
+
let out = text.split(from).join(to);
|
|
205
|
+
const rel = posix.relative(posix.dirname(referrer), from);
|
|
206
|
+
if (rel.includes('/') && rel !== from)
|
|
207
|
+
out = out.split(rel).join(posix.relative(posix.dirname(referrer), to));
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
/** A chunk where its modules say: `_p/<slug>/` for one prototype's, never two. */
|
|
211
|
+
export function chunkProblems(fileName, owners) {
|
|
212
|
+
if (owners.length > 1)
|
|
213
|
+
return [`${fileName} holds files of ${owners.map((o) => `prototypes/${o}/`).join(' and ')}`];
|
|
214
|
+
const [slug] = owners;
|
|
215
|
+
return slug && !fileName.startsWith(`${PROTOTYPE_DIR}/${slug}/`)
|
|
216
|
+
? [`${fileName} holds files of prototypes/${slug}/ but is not under ${PROTOTYPE_DIR}/${slug}/`]
|
|
217
|
+
: [];
|
|
218
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type ChildNode, type PluginCreator } from 'postcss';
|
|
2
|
+
type Owner = (id: string) => string | null;
|
|
3
|
+
/** The references in a declaration's value, unescaped: `url()` and the strings in `image-set()`. */
|
|
4
|
+
export declare function valueRefs(value: string): string[];
|
|
5
|
+
/**
|
|
6
|
+
* Vite's own resolvers, as its CSS plugin builds them from the resolved
|
|
7
|
+
* config (`config.createResolver`: `resolve.alias` and Vite's node
|
|
8
|
+
* resolution): `url` for `url()` and `image-set()`, `css` for `@import`,
|
|
9
|
+
* `composes`, `@value` and `:import`. Each gives a file, or undefined.
|
|
10
|
+
*/
|
|
11
|
+
export type CssResolvers = {
|
|
12
|
+
url: (id: string, importer: string) => Promise<string | undefined>;
|
|
13
|
+
css: (id: string, importer: string) => Promise<string | undefined>;
|
|
14
|
+
};
|
|
15
|
+
/** The file `@import` names, quoted or as `url()`. */
|
|
16
|
+
export declare const importRef: (params: string) => string;
|
|
17
|
+
/**
|
|
18
|
+
* A reference as a file on disk, or null: relative to the file that makes
|
|
19
|
+
* it, or an absolute path that exists (a `/` path that does not is the
|
|
20
|
+
* public folder's).
|
|
21
|
+
*/
|
|
22
|
+
export declare function fileOfRef(ref: string, from: string): string | null;
|
|
23
|
+
/** The file a CSS modules node names: `composes … from`, `@value … from`, or `:import("…")`. */
|
|
24
|
+
export declare function moduleRef(node: ChildNode): string | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Every file a CSS module's chain reaches, read from disk, each once:
|
|
27
|
+
* `composes … from`, `@value … from` and `:import("…")`, through every module
|
|
28
|
+
* they name. postcss-modules resolves these before any other plugin sees the
|
|
29
|
+
* sheet, so they are followed here.
|
|
30
|
+
*/
|
|
31
|
+
export declare function modulesChain(file: string, resolve?: CssResolvers['css'], seen?: Set<string>): Promise<string[]>;
|
|
32
|
+
/**
|
|
33
|
+
* The postcss plugin: for the stylesheet being compiled (the root), a node
|
|
34
|
+
* inlined from another owner's file, or a reference into a prototype the
|
|
35
|
+
* root's owner is not, throws the error that names both files. The kit and
|
|
36
|
+
* the hub own no prototype, so they may reach none.
|
|
37
|
+
*/
|
|
38
|
+
export declare function cssBoundary(project: string, owner: Owner, isPrototype: (owner: string) => boolean, resolvers: () => CssResolvers | null): PluginCreator<never>;
|
|
39
|
+
export {};
|