@1agh/maude 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,317 @@
1
+ // ds-assets.ts — a design system's own asset library, one folder at a time (2.0.2; the Assets tab's "Design system"
2
+ // source, routes/ds-assets.ts).
3
+ //
4
+ // v1 let a person browse a design system's picked photo gallery from the left panel; v2's Assets tab listed only the
5
+ // project's flat uploads under `<designRoot>/assets/`. A real system keeps thousands of pictures in folders under
6
+ // `system/<ds>/assets/` (photos-cut/, logos/, …): this lists them so none of them is out of reach.
7
+ //
8
+ // listDsAssets({ designRoot, systemPath, dir, q, cursor, limit, candidates? })
9
+ // → { ok, ds root, dir, dirs:[{path,name,count}], files:[{path,name,ext,kind,size,mtimeMs,placeable}], total, next }
10
+ //
11
+ // - Media only: the same image / video / sound extensions the project listing shows (api.ts `listAssets`).
12
+ // - Contained: `systemPath` must be `system/<one segment>`; every segment of `dir` is a real folder (lstat — a symlink
13
+ // anywhere on the way is refused, and a symlinked file is never listed); `_` runtime names and `.` hidden names are
14
+ // neither walked nor listed.
15
+ // - Fast on one 3000-file folder: ONE readdir (a Dirent says file / folder / symlink without a stat), sort by name,
16
+ // then lstat only the page. A folder's `count` is one shallow readdir of it. A search walks from `dir` down, readdir
17
+ // only, with a depth and an entry cap.
18
+ // - Paged by name: `cursor` is the last path of the previous page (keyset, so a file added meanwhile neither repeats
19
+ // nor shifts a page); `limit` defaults to 200 and is capped at 500.
20
+ // - `candidates` (a canvas-only session): the listing is built from THOSE paths only (the session's closure), never
21
+ // from the disk — such a session learns nothing about a file its canvases do not show.
22
+
23
+ import type { Dirent } from 'node:fs';
24
+ import { lstat, readdir } from 'node:fs/promises';
25
+ import path from 'node:path';
26
+ import { dsAssetRel } from './editing/ds-asset-ref.ts';
27
+
28
+ const IMG = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.svg']);
29
+ const VID = new Set(['.mp4', '.webm', '.mov', '.m4v', '.ogg']);
30
+ const AUD = new Set(['.mp3', '.wav', '.m4a', '.aac', '.flac', '.oga', '.opus']);
31
+
32
+ export type DsAssetKind = 'image' | 'video' | 'audio';
33
+
34
+ export function dsAssetKindOf(name: string): DsAssetKind | null {
35
+ const ext = path.extname(name).toLowerCase();
36
+ return IMG.has(ext) ? 'image' : VID.has(ext) ? 'video' : AUD.has(ext) ? 'audio' : null;
37
+ }
38
+
39
+ export const DS_ASSETS_LIMIT = 200;
40
+ export const DS_ASSETS_LIMIT_MAX = 500;
41
+ const DIRS_MAX = 200;
42
+ const SEARCH_DEPTH = 10;
43
+ const SEARCH_VISIT_MAX = 50_000;
44
+ const DIR_MAX_LEN = 400;
45
+ const Q_MAX_LEN = 120;
46
+
47
+ export interface DsAssetFile {
48
+ path: string;
49
+ name: string;
50
+ ext: string;
51
+ kind: DsAssetKind;
52
+ size: number;
53
+ mtimeMs: number;
54
+ /** a canvas can show it: `image.place` takes it as a literal reference (editing/ds-asset-ref.ts) */
55
+ placeable: boolean;
56
+ }
57
+ export interface DsAssetDir {
58
+ path: string;
59
+ name: string;
60
+ /** pictures, clips and sounds directly inside */
61
+ count: number;
62
+ }
63
+ export interface DsAssetPage {
64
+ ok: true;
65
+ /** `system/<ds>/assets` */
66
+ root: string;
67
+ /** the folder listed, relative to `root` ('' = the library's top) */
68
+ dir: string;
69
+ dirs: DsAssetDir[];
70
+ files: DsAssetFile[];
71
+ /** how many files match in this folder (or this search), all pages together */
72
+ total: number;
73
+ /** the cursor of the next page, or null */
74
+ next: string | null;
75
+ }
76
+ export type DsAssetRefusal = { ok: false; status: number; reason: string };
77
+
78
+ const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' });
79
+ const byPath = (a: string, b: string) => collator.compare(a, b) || (a < b ? -1 : a > b ? 1 : 0);
80
+
81
+ const hiddenName = (n: string) => n.startsWith('_') || n.startsWith('.');
82
+
83
+ /** The assets root of a configured system path, or null when it is not `system/<one segment>`. */
84
+ export function dsAssetsRootOf(systemPath: unknown): string | null {
85
+ if (typeof systemPath !== 'string') return null;
86
+ const p = systemPath.replace(/^\/+|\/+$/g, '');
87
+ const m = /^system\/([^/]+)$/.exec(p);
88
+ if (!m || hiddenName(m[1] as string) || m[1] === '..') return null;
89
+ return `${p}/assets`;
90
+ }
91
+
92
+ /** A folder below the root: '' or `a/b`; null when any segment is empty, `.`/`..`, `_…`/`.…`, or has a `\`. */
93
+ export function normDsDir(raw: unknown): string | null {
94
+ if (raw === undefined || raw === null || raw === '') return '';
95
+ if (typeof raw !== 'string' || raw.length > DIR_MAX_LEN) return null;
96
+ const d = raw.replace(/^\/+|\/+$/g, '');
97
+ if (!d) return '';
98
+ const parts = d.split('/');
99
+ for (const s of parts) {
100
+ if (!s || s === '..' || s === '.' || hiddenName(s) || s.includes('\\') || s.includes('\0'))
101
+ return null;
102
+ }
103
+ return parts.join('/');
104
+ }
105
+
106
+ function searchWords(q: unknown): string[] {
107
+ if (typeof q !== 'string') return [];
108
+ return q.slice(0, Q_MAX_LEN).toLowerCase().split(/\s+/).filter(Boolean);
109
+ }
110
+
111
+ const matches = (name: string, words: string[]) => {
112
+ const n = name.toLowerCase();
113
+ return words.every((w) => n.includes(w));
114
+ };
115
+
116
+ function clampLimit(raw: unknown): number {
117
+ const n =
118
+ typeof raw === 'string' ? Number.parseInt(raw, 10) : typeof raw === 'number' ? raw : NaN;
119
+ if (!Number.isFinite(n) || n <= 0) return DS_ASSETS_LIMIT;
120
+ return Math.min(Math.trunc(n), DS_ASSETS_LIMIT_MAX);
121
+ }
122
+
123
+ /** Every segment from the designRoot down to `rel` is a real folder (no symlink on the way). */
124
+ async function realDirChain(designRoot: string, rel: string): Promise<boolean> {
125
+ let cur = designRoot;
126
+ for (const seg of rel.split('/')) {
127
+ cur = path.join(cur, seg);
128
+ try {
129
+ const st = await lstat(cur);
130
+ if (!st.isDirectory()) return false;
131
+ } catch {
132
+ return false;
133
+ }
134
+ }
135
+ return true;
136
+ }
137
+
138
+ async function dirents(abs: string): Promise<Dirent[]> {
139
+ try {
140
+ return await readdir(abs, { withFileTypes: true });
141
+ } catch {
142
+ return [];
143
+ }
144
+ }
145
+
146
+ /** Media files directly inside, and whether a folder is inside (a folder with neither is not one to open). */
147
+ async function shallowCount(abs: string): Promise<{ count: number; dirs: boolean }> {
148
+ let count = 0;
149
+ let dirs = false;
150
+ for (const e of await dirents(abs)) {
151
+ if (hiddenName(e.name)) continue;
152
+ if (e.isDirectory()) dirs = true;
153
+ else if (e.isFile() && dsAssetKindOf(e.name)) count++;
154
+ }
155
+ return { count, dirs };
156
+ }
157
+
158
+ /** Media files under `startRel` (designRoot-relative), readdir only. */
159
+ async function walkMedia(designRoot: string, startRel: string): Promise<string[]> {
160
+ const out: string[] = [];
161
+ let visited = 0;
162
+ const stack: Array<{ rel: string; depth: number }> = [{ rel: startRel, depth: 0 }];
163
+ while (stack.length && visited < SEARCH_VISIT_MAX) {
164
+ const { rel, depth } = stack.pop() as { rel: string; depth: number };
165
+ for (const e of await dirents(path.join(designRoot, rel))) {
166
+ if (++visited > SEARCH_VISIT_MAX) break;
167
+ if (hiddenName(e.name)) continue;
168
+ const child = `${rel}/${e.name}`;
169
+ if (e.isDirectory()) {
170
+ if (depth + 1 < SEARCH_DEPTH) stack.push({ rel: child, depth: depth + 1 });
171
+ } else if (e.isFile() && dsAssetKindOf(e.name)) out.push(child);
172
+ }
173
+ }
174
+ return out;
175
+ }
176
+
177
+ async function rowOf(designRoot: string, rel: string): Promise<DsAssetFile | null> {
178
+ const name = rel.slice(rel.lastIndexOf('/') + 1);
179
+ const kind = dsAssetKindOf(name);
180
+ if (!kind) return null;
181
+ try {
182
+ const st = await lstat(path.join(designRoot, rel));
183
+ if (!st.isFile()) return null;
184
+ return {
185
+ path: rel,
186
+ name,
187
+ ext: path.extname(name).slice(1).toLowerCase(),
188
+ kind,
189
+ size: st.size,
190
+ mtimeMs: st.mtimeMs,
191
+ placeable: kind !== 'audio' && dsAssetRel(rel) !== null,
192
+ };
193
+ } catch {
194
+ return null;
195
+ }
196
+ }
197
+
198
+ export interface ListDsAssetsInput {
199
+ designRoot: string;
200
+ /** the system's configured path (designRoot-relative): `system/<ds>` */
201
+ systemPath: string;
202
+ dir?: unknown;
203
+ q?: unknown;
204
+ cursor?: unknown;
205
+ limit?: unknown;
206
+ /** a canvas-only session: the designRoot-relative paths it may see (its closure); the disk is not walked */
207
+ candidates?: Iterable<string>;
208
+ }
209
+
210
+ export async function listDsAssets(
211
+ input: ListDsAssetsInput
212
+ ): Promise<DsAssetPage | DsAssetRefusal> {
213
+ const root = dsAssetsRootOf(input.systemPath);
214
+ if (!root) return { ok: false, status: 404, reason: 'not-found' };
215
+ const dir = normDsDir(input.dir);
216
+ if (dir === null) return { ok: false, status: 400, reason: 'bad-dir' };
217
+ const designRoot = path.resolve(input.designRoot);
218
+ const base = dir ? `${root}/${dir}` : root;
219
+ const words = searchWords(input.q);
220
+ const limit = clampLimit(input.limit);
221
+ const cursor = typeof input.cursor === 'string' && input.cursor ? input.cursor : null;
222
+
223
+ // The candidate files (designRoot-relative) and the folders directly below `base`.
224
+ let files: string[];
225
+ const dirCounts = new Map<string, number>();
226
+ if (input.candidates) {
227
+ files = [];
228
+ const under = `${base}/`;
229
+ for (const rel of input.candidates) {
230
+ if (typeof rel !== 'string' || !rel.startsWith(under)) continue;
231
+ const rest = rel.slice(under.length);
232
+ const segs = rest.split('/');
233
+ if (segs.some((s) => !s || s === '..' || hiddenName(s))) continue;
234
+ if (!dsAssetKindOf(rest)) continue;
235
+ if (words.length) {
236
+ if (matches(segs[segs.length - 1] as string, words)) files.push(rel);
237
+ } else if (segs.length === 1) files.push(rel);
238
+ else if (segs.length === 2) {
239
+ const d = `${base}/${segs[0]}`;
240
+ dirCounts.set(d, (dirCounts.get(d) ?? 0) + 1);
241
+ } else {
242
+ const d = `${base}/${segs[0]}`;
243
+ dirCounts.set(d, dirCounts.get(d) ?? 0);
244
+ }
245
+ }
246
+ // a folder exists for this session only when a file it may see is under it; and every folder on the way to a
247
+ // listed file is a real one (a symlinked folder is not walked in a project listing either)
248
+ if (dir && !files.length && !dirCounts.size)
249
+ return { ok: false, status: 404, reason: 'not-found' };
250
+ const real = new Map<string, Promise<boolean>>();
251
+ const chainOk = (rel: string) => {
252
+ const d = rel.slice(0, rel.lastIndexOf('/'));
253
+ const known = real.get(d);
254
+ if (known) return known;
255
+ const p = realDirChain(designRoot, d);
256
+ real.set(d, p);
257
+ return p;
258
+ };
259
+ const ok = await Promise.all(files.map(chainOk));
260
+ files = files.filter((_, i) => ok[i]);
261
+ for (const d of [...dirCounts.keys()])
262
+ if (!(await realDirChain(designRoot, d))) dirCounts.delete(d);
263
+ } else {
264
+ if (!(await realDirChain(designRoot, base))) {
265
+ // no library yet is an empty one; a folder that is not there (or a symlink) is not found
266
+ if (!dir && !(await realDirChain(designRoot, root)))
267
+ return { ok: true, root, dir, dirs: [], files: [], total: 0, next: null };
268
+ return { ok: false, status: 404, reason: 'not-found' };
269
+ }
270
+ if (words.length) {
271
+ files = (await walkMedia(designRoot, base)).filter((rel) =>
272
+ matches(rel.slice(rel.lastIndexOf('/') + 1), words)
273
+ );
274
+ } else {
275
+ files = [];
276
+ const subdirs: string[] = [];
277
+ for (const e of await dirents(path.join(designRoot, base))) {
278
+ if (hiddenName(e.name)) continue;
279
+ if (e.isDirectory()) subdirs.push(`${base}/${e.name}`);
280
+ else if (e.isFile() && dsAssetKindOf(e.name)) files.push(`${base}/${e.name}`);
281
+ }
282
+ if (!cursor) {
283
+ subdirs.sort(byPath);
284
+ const shown = subdirs.slice(0, DIRS_MAX);
285
+ const counts = await Promise.all(shown.map((d) => shallowCount(path.join(designRoot, d))));
286
+ shown.forEach((d, i) => {
287
+ const c = counts[i] as { count: number; dirs: boolean };
288
+ if (c.count || c.dirs) dirCounts.set(d, c.count);
289
+ });
290
+ }
291
+ }
292
+ }
293
+
294
+ files.sort(byPath);
295
+ const total = files.length;
296
+ const from = cursor ? files.findIndex((f) => byPath(f, cursor) > 0) : 0;
297
+ const slice = from < 0 ? [] : files.slice(from, from + limit);
298
+ const rows = (await Promise.all(slice.map((rel) => rowOf(designRoot, rel)))).filter(
299
+ (r): r is DsAssetFile => r !== null
300
+ );
301
+ const more = from >= 0 && from + limit < files.length;
302
+ const dirs: DsAssetDir[] =
303
+ cursor || words.length
304
+ ? []
305
+ : [...dirCounts.entries()]
306
+ .sort((a, b) => byPath(a[0], b[0]))
307
+ .map(([p, count]) => ({ path: p, name: p.slice(p.lastIndexOf('/') + 1), count }));
308
+ return {
309
+ ok: true,
310
+ root,
311
+ dir,
312
+ dirs,
313
+ files: rows,
314
+ total,
315
+ next: more ? (slice[slice.length - 1] as string) : null,
316
+ };
317
+ }
@@ -28,6 +28,7 @@ import MagicString from 'magic-string';
28
28
  import { parseSync } from 'oxc-parser';
29
29
 
30
30
  import { applyEdit, applyRemove, readAttributeState } from '../canvas-edit.ts';
31
+ import { dsAssetRelOfSrc } from '../editing/ds-asset-ref.ts';
31
32
  import {
32
33
  generateElementId,
33
34
  type IdElement,
@@ -55,6 +56,22 @@ export const isAssetSrc = (v: unknown): v is string =>
55
56
 
56
57
  const NOT_AN_ASSET = 'That picture is not in this project’s assets.';
57
58
 
59
+ /**
60
+ * 2.0.2 — what `image.place` / `image.replace` may write as a source: a project upload (`assets/<flat name>`), or a
61
+ * design system's own picture as its literal `/<designRel>/system/<ds>/assets/…` reference — under THIS server's
62
+ * designRel (`ctx`), naming a regular file that is there (`exists`: a symlink is not one).
63
+ */
64
+ export function isPlaceableSrc(
65
+ v: unknown,
66
+ req: Pick<ResolvedEditOp, 'ctx' | 'exists'>
67
+ ): v is string {
68
+ if (isAssetSrc(v)) return true;
69
+ const designRel = req.ctx?.designRel;
70
+ if (typeof designRel !== 'string' || !req.exists) return false;
71
+ const rel = dsAssetRelOfSrc(v, designRel);
72
+ return rel !== null && req.exists(rel);
73
+ }
74
+
58
75
  /** A video in Assets: the extensions the asset route stores for video (`sniffAssetType`: mp4 · mov · m4v · webm). */
59
76
  export const VIDEO_ASSET_RE = /\.(mp4|mov|m4v|webm)$/i;
60
77
  export const isVideoAsset = (v: string): boolean => VIDEO_ASSET_RE.test(v);
@@ -173,7 +190,7 @@ function placeParams(req: ResolvedEditOp): PlaceParams {
173
190
  const list = Array.isArray(p.assets) ? p.assets : p.asset !== undefined ? [p.asset] : [];
174
191
  if (!list.length) return refuse(req, 'Pick a picture to place.');
175
192
  if (list.length > MAX_ASSETS) return refuse(req, `Place up to ${MAX_ASSETS} pictures at a time.`);
176
- for (const a of list) if (!isAssetSrc(a)) return refuse(req, NOT_AN_ASSET);
193
+ for (const a of list) if (!isPlaceableSrc(a, req)) return refuse(req, NOT_AN_ASSET);
177
194
  const mode = p.mode === undefined ? 'fill' : p.mode;
178
195
  if (typeof mode !== 'string' || !(PLACE_MODES as readonly string[]).includes(mode))
179
196
  return refuse(req, 'Place it to fill, loose, in order or in a grid.');
@@ -562,7 +579,7 @@ export const imageReplace: EditOp = {
562
579
  const t = req.targets[0];
563
580
  if (!t) return refuse(req, 'Select a picture first.');
564
581
  const asset = req.params.asset;
565
- if (!isAssetSrc(asset)) return refuse(req, NOT_AN_ASSET, t.element);
582
+ if (!isPlaceableSrc(asset, req)) return refuse(req, NOT_AN_ASSET, t.element);
566
583
  const walk = walkOrRefuse(source, req);
567
584
  const el = elementOf(walk, t);
568
585
  if (!el || !isPicture(el)) return refuse(req, 'That is not a picture.', t.element);
@@ -94,6 +94,11 @@ export interface EditCtx {
94
94
  * against what the request claims.
95
95
  */
96
96
  variantsOf?(component: string): readonly string[] | null;
97
+ /**
98
+ * 2.0.2 — the server's designRoot relative to the repo (`.design`): a design system's own picture is placed as the
99
+ * literal `/<designRel>/system/<ds>/assets/…` (editing/ds-asset-ref.ts), checked against THIS, never the request.
100
+ */
101
+ designRel?: string;
97
102
  }
98
103
 
99
104
  /** One writer. Pure: bytes in, bytes out; throw `CanvasEditError` to refuse with `invalid`. */
@@ -7,9 +7,15 @@
7
7
  // listener can tell a tile from a file, and for same-origin targets.
8
8
  // Pure: no DOM, no React, no server import (the canvas bundle imports this).
9
9
 
10
+ import { isDsAssetSrc } from './ds-asset-ref.ts';
11
+
10
12
  export const ASSET_DRAG_MIME = 'application/x-maude-asset';
11
13
 
12
- /** The same allowlist the server applies: `assets/<flat name>`, no `..`, no scheme. */
14
+ /**
15
+ * The same allowlist the server applies: `assets/<flat name>`, no `..`, no scheme — or (2.0.2) a design system's own
16
+ * picture by its literal `/<designRel>/system/<ds>/assets/…` reference (ds-asset-ref.ts; the server re-checks the
17
+ * designRel and that the file is there).
18
+ */
13
19
  const ASSET_RE = /^assets\/[A-Za-z0-9._-]+$/;
14
20
  const MAX_PX = 100_000;
15
21
 
@@ -21,7 +27,7 @@ export interface AssetDrag {
21
27
  }
22
28
 
23
29
  export const isAssetPath = (v: unknown): v is string =>
24
- typeof v === 'string' && ASSET_RE.test(v) && !v.includes('..');
30
+ (typeof v === 'string' && ASSET_RE.test(v) && !v.includes('..')) || isDsAssetSrc(v);
25
31
 
26
32
  /** The string a tile puts under {@link ASSET_DRAG_MIME}. */
27
33
  export function assetDragData(a: AssetDrag): string {
@@ -0,0 +1,66 @@
1
+ // editing/ds-asset-ref.ts — a design system's own picture as a canvas reference (2.0.2, the Assets tab's
2
+ // "Design system" source).
3
+ //
4
+ // A project upload is `assets/<flat name>` (content-addressed, edit-ops/image-fit.ts `ASSET_SRC_RE`). A design
5
+ // system keeps its library in folders under `system/<ds>/assets/` (photos-cut/, logos/, …), so its pictures are
6
+ // placed by a LITERAL, root-absolute designRoot path:
7
+ //
8
+ // src="/.design/system/alligators/assets/photos-cut/IMG_2231.jpg"
9
+ //
10
+ // — the form a DS's own specimens already write (`system/maude-v2/preview/textures.tsx`) and the one the canvas
11
+ // build rewrites a DS stylesheet's `url(../system/<ds>/assets/…)` into (canvas-build.ts). It is a static string the
12
+ // canvas closure can read (access/closure.ts) and the canvas origin serves through its designRel lane.
13
+ //
14
+ // Pure: no DOM, no server import (the shell and the canvas bundle import this; the edit op re-checks on the server
15
+ // against ITS designRel and the disk).
16
+
17
+ /** The pictures and clips a DS reference may name — what the canvas origin serves and `image.place` writes. */
18
+ export const DS_PLACEABLE_EXT_RE = /\.(png|jpe?g|gif|webp|svg|mp4|mov|m4v|webm)$/i;
19
+
20
+ /**
21
+ * One path segment a reference may carry. Never empty, `.`/`..`, a runtime (`_…`) or hidden (`.…`) name, and none of
22
+ * the characters that would change what a JSX attribute, a CSS `url("…")` or a URL means: quotes, `<>{}`, `\`, `&`
23
+ * (a JSX entity), `%` (an escape), `?`/`#` (a query, a fragment), or a control character.
24
+ */
25
+ const SEGMENT_RE = /^(?![._])[^/"'`<>{}\\&%?#]{1,200}$/;
26
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: refusing control characters is the point
27
+ const CONTROL_RE = /[\u0000-\u001f\u007f]/;
28
+ const safeSegment = (s: string) => SEGMENT_RE.test(s) && !CONTROL_RE.test(s);
29
+
30
+ const MAX_REF = 600;
31
+
32
+ /** `system/<ds>/assets/<…>/<name.ext>` (designRoot-relative) when every segment is safe, else null. */
33
+ export function dsAssetRel(rel: unknown): string | null {
34
+ if (typeof rel !== 'string' || rel.length > MAX_REF) return null;
35
+ const parts = rel.split('/');
36
+ if (parts.length < 4 || parts[0] !== 'system' || parts[2] !== 'assets') return null;
37
+ if (!safeSegment(parts[1] as string)) return null;
38
+ if (!parts.slice(3).every(safeSegment)) return null;
39
+ return DS_PLACEABLE_EXT_RE.test(rel) ? rel : null;
40
+ }
41
+
42
+ /** The literal `src` a placed DS picture gets: `/<designRel>/system/<ds>/assets/…`, or null when it may not be one. */
43
+ export function dsAssetSrc(rel: unknown, designRel: string): string | null {
44
+ const r = dsAssetRel(rel);
45
+ const d = String(designRel ?? '').replace(/^\/+|\/+$/g, '');
46
+ if (!r || !d || d.split('/').some((s) => !s || s === '..' || s === '.')) return null;
47
+ return `/${d}/${r}`;
48
+ }
49
+
50
+ /**
51
+ * The designRoot-relative path a literal DS reference names, or null. `designRel` given: the prefix must be exactly it
52
+ * (the server's check). Without it (the shell's drag, which only gates shape): any one-or-more-segment prefix.
53
+ */
54
+ export function dsAssetRelOfSrc(src: unknown, designRel?: string): string | null {
55
+ if (typeof src !== 'string' || !src.startsWith('/') || src.length > MAX_REF) return null;
56
+ const at = src.indexOf('/system/');
57
+ if (at <= 0) return null;
58
+ const prefix = src.slice(1, at);
59
+ if (prefix.split('/').some((s) => !s || s === '..' || s === '.')) return null;
60
+ if (designRel !== undefined && prefix !== String(designRel).replace(/^\/+|\/+$/g, ''))
61
+ return null;
62
+ return dsAssetRel(src.slice(at + 1));
63
+ }
64
+
65
+ /** A literal DS reference by shape (no designRel known): what the shell lets a tile drag carry. */
66
+ export const isDsAssetSrc = (v: unknown): v is string => dsAssetRelOfSrc(v) !== null;
@@ -50,6 +50,7 @@ import {
50
50
  FRAME_PARAM,
51
51
  type FrameScope,
52
52
  frameKeyFor,
53
+ frameReadsProjectMedia,
53
54
  frameSubjectOf,
54
55
  frameTokenOf,
55
56
  inputsRefusal,
@@ -2514,6 +2515,13 @@ export function createHttp(
2514
2515
  },
2515
2516
  inCell: isWorkspaceMode(),
2516
2517
  },
2518
+ // 2.0.2 — GET /_api/ds/assets (routes/ds-assets.ts): a design system's own library in the Assets tab, paged by
2519
+ // folder; a canvas-only session is answered from its closure (visOf), like /_api/assets.
2520
+ dsAssets: {
2521
+ designRoot: ctx.paths.designRoot,
2522
+ systems: () => ctx.cfg.designSystems ?? [],
2523
+ visibility: (req) => visOf(req),
2524
+ },
2517
2525
  // S8.16 — /_api/generate-takes* (routes/generate.ts): N takes on the generation queue, the consent quote, ← →.
2518
2526
  generate: generateDepsFor({
2519
2527
  designRoot: ctx.paths.designRoot,
@@ -7949,6 +7957,9 @@ export function createHttp(
7949
7957
 
7950
7958
  async function accessRefusal(req: Request): Promise<Response | null> {
7951
7959
  const access = accessOf(req);
7960
+ // 2.0.2 — on a materializing cell, the closure lists the journal's media (DDR-243: none of it
7961
+ // is on the checkout); wait for the first listing so a frame's own DS asset is not refused.
7962
+ if (access.grants.length > 0) await visibility.ready?.();
7952
7963
  const g = gateInput(access);
7953
7964
  // S9.11 (V2-1.16 L15) — a file of the design root (the static lane, its `/assets/`
7954
7965
  // alias, `?sha=` builds) is judged on its PATH, before any query names a target: a
@@ -7962,8 +7973,12 @@ export function createHttp(
7962
7973
  }
7963
7974
  const file = canvasOriginTarget(pathname, designRel);
7964
7975
  const see = seerOf(access, () => closureOf(access));
7965
- if (file !== undefined && (file === null || see?.(file) !== true))
7966
- return notInScopeResponse();
7976
+ if (file !== undefined && (file === null || see?.(file) !== true)) {
7977
+ // 2.0.2 (decision maude/v2-202-project-role-frames-read-project-media) — a frame opened with a
7978
+ // project read role GETs any project media; a canvas-only opener keeps the strict closure.
7979
+ if (file === null || !frameReadsProjectMedia(access, file, req.method))
7980
+ return notInScopeResponse();
7981
+ }
7967
7982
  }
7968
7983
  const scope = await canvasScopeRefusal(req, g);
7969
7984
  if (scope) return scope;
@@ -170,6 +170,17 @@ export async function listMaterializable({
170
170
  return listInflight;
171
171
  }
172
172
 
173
+ /**
174
+ * The last listing `listMaterializable` got, whatever its age — `null` before the first answer
175
+ * (and always off a cell). The SAME array until a new answer replaces it, so a caller may key a
176
+ * cache on its identity. The access closure reads it synchronously (access/filters.ts): on a cell
177
+ * a design system's media is in the journal, never at its checkout path, and a canvas frame's
178
+ * closure must still hold it (2.0.2 — the alligators logos answered 403 on the canvas origin).
179
+ */
180
+ export function lastMaterializable(): readonly string[] | null {
181
+ return listCache?.rels ?? null;
182
+ }
183
+
173
184
  /** Test seam — forget the cached listing. */
174
185
  export function resetMaterializableListCache(): void {
175
186
  listCache = null;
@@ -0,0 +1,70 @@
1
+ // routes/ds-assets.ts — `GET /_api/ds/assets` (2.0.2): a design system's own asset library, for the Assets tab's
2
+ // "Design system" source.
3
+ //
4
+ // GET /_api/ds/assets?ds=<name>&dir=<folder>&q=<search>&cursor=<c>&limit=<n>
5
+ // 200 { ok: true, ds, root, dir, dirs:[{path,name,count}], files:[{path,name,ext,kind,size,mtimeMs,placeable}],
6
+ // total, next } ds-assets.ts `listDsAssets`: one folder (or a search below it), one page, by name
7
+ // 400 { ok: false, reason: 'bad-dir' } a folder with `..`, a `_`/`.` name or a `\`
8
+ // 404 { ok: false, reason: 'not-found' } no such system, a folder that is not there (or is a symlink), or —
9
+ // for a canvas-only session — one with nothing its canvases show
10
+ //
11
+ // `ds` is a name from the project's config `designSystems` (path per system, which must be `system/<one segment>`);
12
+ // `path` in every row is designRoot-relative (`system/<ds>/assets/photos-cut/x.jpg`) — the shell shows it at
13
+ // `/<designRel>/<path>` and places it as that literal reference (editing/ds-asset-ref.ts).
14
+ //
15
+ // MAIN ORIGIN ONLY, never canvas-safe (a shell panel's read; absent from both canvas allowlists). Reads only, for
16
+ // every role that can read the project. A canvas-only session is answered from its closure alone (`filterAssetListing`'s
17
+ // rule for `/_api/assets`): the files its canvases' closure reads, and no folder without one.
18
+
19
+ import type { Visibility } from '../access/filters.ts';
20
+ import { listDsAssets } from '../ds-assets.ts';
21
+ import type { RouteSpec } from './table.ts';
22
+
23
+ const json = (status: number, body: unknown) =>
24
+ Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
25
+
26
+ export interface DsAssetsRouteDeps {
27
+ designRoot: string;
28
+ /** The project's design systems (config `designSystems`), read per request. */
29
+ systems: () => ReadonlyArray<{ name: string; path: string }>;
30
+ /** The session's visibility (http.ts `visOf`). */
31
+ visibility: (req: Request) => Visibility;
32
+ }
33
+
34
+ export function createDsAssetsRoutes(deps: DsAssetsRouteDeps): RouteSpec[] {
35
+ return [
36
+ {
37
+ method: 'GET',
38
+ path: '/_api/ds/assets',
39
+ origin: 'main',
40
+ readOnly: 'allowed',
41
+ handle: async (req) => {
42
+ const q = new URL(req.url).searchParams;
43
+ const name = q.get('ds') ?? '';
44
+ const sys =
45
+ name && name.length <= 64 ? deps.systems().find((s) => s.name === name) : undefined;
46
+ if (!sys) return json(404, { ok: false, reason: 'not-found' });
47
+ const vis = deps.visibility(req);
48
+ let candidates: string[] | undefined;
49
+ if (!vis.full) {
50
+ const closure = vis.closure();
51
+ candidates = closure ? [...closure.read].filter((rel) => vis.sees(rel)) : [];
52
+ }
53
+ const page = await listDsAssets({
54
+ designRoot: deps.designRoot,
55
+ systemPath: sys.path,
56
+ dir: q.get('dir'),
57
+ q: q.get('q'),
58
+ cursor: q.get('cursor'),
59
+ limit: q.get('limit'),
60
+ ...(candidates ? { candidates } : {}),
61
+ });
62
+ if (!page.ok) return json(page.status, { ok: false, reason: page.reason });
63
+ // a canvas-only session that sees nothing of this library is told it is not there
64
+ if (candidates && !candidates.some((rel) => rel.startsWith(`${page.root}/`)))
65
+ return json(404, { ok: false, reason: 'not-found' });
66
+ return json(200, { ...page, ds: sys.name });
67
+ },
68
+ },
69
+ ];
70
+ }
@@ -503,6 +503,7 @@ export function createEditRoutes(deps: EditRouteDeps): RouteSpec[] {
503
503
  dsRev: dsRevOf(rel),
504
504
  layout: layoutOf(rel),
505
505
  variantsOf: variantsOf(rel),
506
+ designRel: deps.designRel,
506
507
  }),
507
508
  ...(deps.references ? { references: deps.references } : {}),
508
509
  ...(deps.ops ? { ops: deps.ops } : {}),
@@ -35,6 +35,7 @@ import { type ConnectionsRouteDeps, createConnectionsRoutes } from './connection
35
35
  import { createDescribeRoutes, type DescribeRouteDeps } from './describe.ts';
36
36
  import { createDiagnosticsRoutes, type DiagnosticsRouteDeps } from './diagnostics.ts';
37
37
  import { createDsRoutes, type DsRouteDeps } from './ds.ts';
38
+ import { createDsAssetsRoutes, type DsAssetsRouteDeps } from './ds-assets.ts';
38
39
  import { createDsCheckRoutes } from './ds-check.ts';
39
40
  import { createEditRoutes, type EditRouteDeps } from './edit.ts';
40
41
  import { createElementLinksRoutes, type ElementLinksRouteDeps } from './element-links.ts';
@@ -150,6 +151,8 @@ export interface RouteDeps {
150
151
  describe?: DescribeRouteDeps;
151
152
  /** S8.21 — `GET /_api/asset-details` and `GET /_api/asset-generated` (main origin, reads): details per kind, the Generated runs */
152
153
  assetDetails?: AssetDetailsRouteDeps;
154
+ /** 2.0.2 — `GET /_api/ds/assets`: a design system's own asset library for the Assets tab (main origin, reads) */
155
+ dsAssets?: DsAssetsRouteDeps;
153
156
  /** S8.22 — `POST /_api/import-asset` v2 (main origin, Can edit on the project): PSD/HEIC converters, the dedupe answer */
154
157
  assetImport?: AssetImportRouteDeps;
155
158
  /**
@@ -270,6 +273,7 @@ export function allSpecs(deps: RouteDeps): RouteSpec[] {
270
273
  ...(deps.figma ? createFigmaRoutes(deps.figma) : []),
271
274
  ...(deps.describe ? createDescribeRoutes(deps.describe) : []),
272
275
  ...(deps.assetDetails ? createAssetDetailsRoutes(deps.assetDetails) : []),
276
+ ...(deps.dsAssets ? createDsAssetsRoutes(deps.dsAssets) : []),
273
277
  ...(deps.assetImport ? createAssetImportRoutes(deps.assetImport) : []),
274
278
  ...importLinkSpecs(deps),
275
279
  ...(deps.generate ? createGenerateRoutes(deps.generate) : []),