@buffercreations/levelsui 0.0.0-stage → 0.1.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/01. Elements/.gitkeep +0 -0
- package/01. Elements/actions/controls/button/api.json +106 -0
- package/01. Elements/actions/controls/button/button.definition.json +38 -0
- package/01. Elements/actions/controls/button/button.scss +80 -0
- package/01. Elements/actions/controls/button/docs.md +41 -0
- package/01. Elements/actions/controls/button/examples/contexts/code.html +3 -0
- package/01. Elements/actions/controls/button/examples/contexts/preview.html +3 -0
- package/01. Elements/actions/controls/button/examples/icons/code.html +6 -0
- package/01. Elements/actions/controls/button/examples/icons/preview.html +5 -0
- package/01. Elements/actions/controls/button/examples/index.json +51 -0
- package/01. Elements/actions/controls/button/examples/links/code.html +1 -0
- package/01. Elements/actions/controls/button/examples/links/preview.html +3 -0
- package/01. Elements/actions/controls/button/examples/native-default/code.html +9 -0
- package/01. Elements/actions/controls/button/examples/native-default/preview.html +9 -0
- package/01. Elements/actions/controls/button/examples/sizes/code.html +1 -0
- package/01. Elements/actions/controls/button/examples/sizes/preview.html +7 -0
- package/01. Elements/actions/controls/button/examples/states/code.html +1 -0
- package/01. Elements/actions/controls/button/examples/states/preview.html +5 -0
- package/01. Elements/actions/controls/button/examples/treatments/code.html +1 -0
- package/01. Elements/actions/controls/button/examples/treatments/preview.html +5 -0
- package/01. Elements/media/identity/avatar/api.json +126 -0
- package/01. Elements/media/identity/avatar/avatar.definition.json +38 -0
- package/01. Elements/media/identity/avatar/avatar.scss +80 -0
- package/01. Elements/media/identity/avatar/docs.md +64 -0
- package/01. Elements/media/identity/avatar/examples/badges/code.html +10 -0
- package/01. Elements/media/identity/avatar/examples/badges/preview.html +29 -0
- package/01. Elements/media/identity/avatar/examples/fallbacks/code.html +5 -0
- package/01. Elements/media/identity/avatar/examples/fallbacks/preview.html +23 -0
- package/01. Elements/media/identity/avatar/examples/index.json +37 -0
- package/01. Elements/media/identity/avatar/examples/presence/code.html +6 -0
- package/01. Elements/media/identity/avatar/examples/presence/preview.html +26 -0
- package/01. Elements/media/identity/avatar/examples/shapes/code.html +5 -0
- package/01. Elements/media/identity/avatar/examples/shapes/preview.html +17 -0
- package/01. Elements/media/identity/avatar/examples/sizes/code.html +5 -0
- package/01. Elements/media/identity/avatar/examples/sizes/preview.html +32 -0
- package/02. Layouts/.gitkeep +0 -0
- package/02. Layouts/UTILITY-RECIPES.md +55 -0
- package/02. Layouts/application/app-shell/api.json +46 -0
- package/02. Layouts/application/app-shell/app-shell.definition.json +25 -0
- package/02. Layouts/application/app-shell/app-shell.scss +68 -0
- package/02. Layouts/application/app-shell/docs.md +31 -0
- package/02. Layouts/application/app-shell/examples/basic/code.html +17 -0
- package/02. Layouts/application/app-shell/examples/basic/preview.html +17 -0
- package/02. Layouts/application/app-shell/examples/collapsed/code.html +17 -0
- package/02. Layouts/application/app-shell/examples/collapsed/preview.html +17 -0
- package/02. Layouts/application/app-shell/examples/hidden/code.html +17 -0
- package/02. Layouts/application/app-shell/examples/hidden/preview.html +17 -0
- package/02. Layouts/application/app-shell/examples/index.json +23 -0
- package/02. Layouts/composition/stack/api.json +1 -0
- package/02. Layouts/composition/stack/docs.md +5 -0
- package/02. Layouts/composition/stack/examples/basic/code.html +4 -0
- package/02. Layouts/composition/stack/examples/basic/preview.html +4 -0
- package/02. Layouts/composition/stack/examples/index.json +1 -0
- package/02. Layouts/composition/stack/stack.definition.json +7 -0
- package/02. Layouts/composition/stack/stack.html +4 -0
- package/02. Layouts/content/grid/api.json +23 -0
- package/02. Layouts/content/grid/docs.md +19 -0
- package/02. Layouts/content/grid/examples/basic/code.html +5 -0
- package/02. Layouts/content/grid/examples/basic/preview.html +5 -0
- package/02. Layouts/content/grid/examples/index.json +9 -0
- package/02. Layouts/content/grid/grid.definition.json +25 -0
- package/02. Layouts/content/grid/grid.scss +5 -0
- package/02. Layouts/content/split/api.json +23 -0
- package/02. Layouts/content/split/docs.md +18 -0
- package/02. Layouts/content/split/examples/basic/code.html +4 -0
- package/02. Layouts/content/split/examples/basic/preview.html +4 -0
- package/02. Layouts/content/split/examples/index.json +9 -0
- package/02. Layouts/content/split/split.definition.json +25 -0
- package/02. Layouts/content/split/split.scss +7 -0
- package/02. Layouts/primitives/overlay/api.json +23 -0
- package/02. Layouts/primitives/overlay/docs.md +19 -0
- package/02. Layouts/primitives/overlay/examples/basic/code.html +5 -0
- package/02. Layouts/primitives/overlay/examples/basic/preview.html +5 -0
- package/02. Layouts/primitives/overlay/examples/index.json +9 -0
- package/02. Layouts/primitives/overlay/overlay.definition.json +25 -0
- package/02. Layouts/primitives/overlay/overlay.scss +4 -0
- package/02. Layouts/sections/section/api.json +23 -0
- package/02. Layouts/sections/section/docs.md +19 -0
- package/02. Layouts/sections/section/examples/basic/code.html +5 -0
- package/02. Layouts/sections/section/examples/basic/preview.html +5 -0
- package/02. Layouts/sections/section/examples/index.json +9 -0
- package/02. Layouts/sections/section/section.definition.json +25 -0
- package/02. Layouts/sections/section/section.scss +4 -0
- package/02. Layouts/sections/sidebar/api.json +23 -0
- package/02. Layouts/sections/sidebar/docs.md +18 -0
- package/02. Layouts/sections/sidebar/examples/basic/code.html +4 -0
- package/02. Layouts/sections/sidebar/examples/basic/preview.html +4 -0
- package/02. Layouts/sections/sidebar/examples/index.json +9 -0
- package/02. Layouts/sections/sidebar/sidebar.definition.json +25 -0
- package/02. Layouts/sections/sidebar/sidebar.scss +7 -0
- package/03. Components/.gitkeep +0 -0
- package/04. Templates/.gitkeep +0 -0
- package/05. Pages/.gitkeep +0 -0
- package/LICENSE +17 -0
- package/README.md +29 -2
- package/dist/components/app-shell.css +95 -0
- package/dist/components/avatar.css +232 -0
- package/dist/components/button.css +150 -0
- package/dist/components/grid.css +22 -0
- package/dist/components/overlay.css +17 -0
- package/dist/components/section.css +14 -0
- package/dist/components/sidebar.css +22 -0
- package/dist/components/split.css +22 -0
- package/package.json +48 -4
- package/schemas/reusable-ui.schema.json +351 -0
- package/tooling/cli/build.mjs +82 -0
- package/tooling/cli/cli.mjs +56 -0
- package/tooling/cli/migrate.mjs +57 -0
- package/tooling/cli/project.mjs +261 -0
- package/tooling/cli/registry-location.mjs +32 -0
- package/tooling/cli/registry.mjs +3 -0
- package/tooling/registry/definitions.mjs +69 -0
- package/tooling/registry/index.mjs +3 -0
- package/tooling/registry/paths.mjs +15 -0
- package/tools/build-css.mjs +75 -0
- package/tools/validate.mjs +6 -0
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import { loadRegistry, resolveAssets } from './registry.mjs';
|
|
5
|
+
import {assertWithin,safeRelative} from '../registry/paths.mjs';
|
|
6
|
+
import {validateReusableUiDefinition} from '../registry/definitions.mjs';
|
|
7
|
+
import {migrateInstalled} from './migrate.mjs';
|
|
8
|
+
|
|
9
|
+
export const STATE_FILE = 'buffercore.assets.json';
|
|
10
|
+
const allowed = /\.(?:scss|css|js|json|html|md)$/i;
|
|
11
|
+
const hash = data => crypto.createHash('sha256').update(data).digest('hex');
|
|
12
|
+
const slash = value => value.split(path.sep).join('/');
|
|
13
|
+
const fileHash = file => hash(fs.readFileSync(file));
|
|
14
|
+
const fail = message => { throw new Error(message); };
|
|
15
|
+
function assetFiles(dir) {
|
|
16
|
+
const files=[];
|
|
17
|
+
function visit(current) {
|
|
18
|
+
for (const entry of fs.readdirSync(current,{withFileTypes:true})) {
|
|
19
|
+
const full=path.join(current,entry.name);
|
|
20
|
+
if(entry.isSymbolicLink()) fail(`Symlinks are not permitted in library assets: ${full}`);
|
|
21
|
+
if(entry.isDirectory()) { if(entry.name==='node_modules') fail('Asset contains node_modules'); visit(full); }
|
|
22
|
+
else if(entry.isFile() && allowed.test(entry.name)) files.push(slash(path.relative(dir,full)));
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
visit(dir);return files.sort();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function normalise(state) {
|
|
29
|
+
if(!state || typeof state!=='object' || Array.isArray(state))fail('Invalid BufferCore manifest');
|
|
30
|
+
if(![1,2,3].includes(state.schemaVersion))fail('Unsupported BufferCore manifest schema');
|
|
31
|
+
if(!state.installed || typeof state.installed!=='object' || Array.isArray(state.installed))fail('Invalid installed assets');
|
|
32
|
+
if(!Array.isArray(state.active)) fail('Invalid active asset list');
|
|
33
|
+
for(const [id,entry] of Object.entries(state.installed)){
|
|
34
|
+
if(!/^[a-z][a-z0-9-]*$/.test(id)||!entry||typeof entry!=='object'||!safeRelative(entry.path))fail('Invalid installed asset entry');
|
|
35
|
+
if(entry.files && (Array.isArray(entry.files)||typeof entry.files!=='object'||Object.entries(entry.files).some(([name,digest])=>!safeRelative(name)||! /^[a-f0-9]{64}$/.test(digest))))fail('Invalid tracked file inventory');
|
|
36
|
+
}
|
|
37
|
+
if(state.active.some(id=>typeof id!=='string'||!Object.hasOwn(state.installed,id))||new Set(state.active).size!==state.active.length)fail('Invalid active roots');
|
|
38
|
+
return state;
|
|
39
|
+
}
|
|
40
|
+
export function openProject(project, registryRoot) {
|
|
41
|
+
const base=path.resolve(project), location=path.join(base,STATE_FILE);
|
|
42
|
+
const state=fs.existsSync(location)?normalise(JSON.parse(fs.readFileSync(location,'utf8'))):{schemaVersion:3,installed:{},active:[]};
|
|
43
|
+
assertWithin(base,location);
|
|
44
|
+
const registry=registryRoot?loadRegistry(registryRoot):new Map();
|
|
45
|
+
let catalogue=null;const packageFile=registryRoot&&path.join(registryRoot,'package.json');
|
|
46
|
+
if(packageFile&&fs.existsSync(packageFile)){const meta=JSON.parse(fs.readFileSync(assertWithin(registryRoot,packageFile)));catalogue={name:typeof meta.name==='string'?meta.name:null,version:typeof meta.version==='string'?meta.version:null};}
|
|
47
|
+
const projectAssets=path.join(base,'src','buffercore');
|
|
48
|
+
function destFor(asset) {
|
|
49
|
+
const rel=slash(path.relative(registryRoot,path.dirname(asset.definitionFile)));
|
|
50
|
+
if(rel.startsWith('../')||rel==='..'||path.isAbsolute(rel))fail('Unsafe registry entry');
|
|
51
|
+
const target=path.join(projectAssets,rel);assertWithin(projectAssets,target);
|
|
52
|
+
return {rel,target};
|
|
53
|
+
}
|
|
54
|
+
function readInstalled(id) {
|
|
55
|
+
const entry=state.installed[id];if(!entry)fail(`Asset not installed: ${id}`);
|
|
56
|
+
if(typeof entry.path!=='string')fail(`Invalid recorded path for ${id}`);
|
|
57
|
+
if(!safeRelative(entry.path))fail('Invalid installed path');
|
|
58
|
+
const target=path.resolve(projectAssets,entry.path);assertWithin(projectAssets,target);
|
|
59
|
+
return {entry,target};
|
|
60
|
+
}
|
|
61
|
+
function sourceFiles(asset) {
|
|
62
|
+
const {rel,target}=destFor(asset),source=path.dirname(asset.definitionFile);
|
|
63
|
+
return assetFiles(source).map(file=>({file,source:path.join(source,file),target:path.join(target,file),digest:fileHash(assertWithin(source,path.join(source,file))),rel}));
|
|
64
|
+
}
|
|
65
|
+
function storedDigest(entry,file) {return entry.files?.[file] ?? null;}
|
|
66
|
+
function checkExisting(entry, file) {
|
|
67
|
+
assertWithin(base,file.target);
|
|
68
|
+
if(!fs.existsSync(file.target)) {
|
|
69
|
+
if(entry && storedDigest(entry,file.file))fail(`Missing previously installed file: ${file.target}`);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const existing=fileHash(file.target);
|
|
73
|
+
const previous=entry && storedDigest(entry,file.file);
|
|
74
|
+
if(previous && existing!==previous)fail(`Local modifications detected: ${file.target}`);
|
|
75
|
+
if(!previous && existing!==file.digest)fail(`Untracked file would be overwritten: ${file.target}`);
|
|
76
|
+
}
|
|
77
|
+
function commitState() {
|
|
78
|
+
fs.mkdirSync(base,{recursive:true});
|
|
79
|
+
assertWithin(base,location);
|
|
80
|
+
const temp=location+'.tmp';assertWithin(base,temp);
|
|
81
|
+
fs.writeFileSync(temp,JSON.stringify({...state,schemaVersion:3},null,2)+'\n');
|
|
82
|
+
fs.renameSync(temp,location);
|
|
83
|
+
}
|
|
84
|
+
function add(ids,{update=false,dryRun=false}={}) {
|
|
85
|
+
const resolved=resolveAssets(registry,ids);
|
|
86
|
+
const plan=[];
|
|
87
|
+
// Check the entire operation before changing any file.
|
|
88
|
+
for(const asset of resolved) {
|
|
89
|
+
const {rel}=destFor(asset);
|
|
90
|
+
const prior=state.installed[asset.id];
|
|
91
|
+
if(prior && prior.path!==rel)fail(`Installed ${asset.id} has a different source path; manual migration required`);
|
|
92
|
+
const files=sourceFiles(asset);
|
|
93
|
+
const obsolete=Object.keys(prior?.files||{}).filter(name=>!files.some(file=>file.file===name));
|
|
94
|
+
if(obsolete.length && update)fail(`Source files were removed from ${asset.id}; manual review required: ${obsolete.join(', ')}`);
|
|
95
|
+
if(prior && !update) {
|
|
96
|
+
plan.push({id:asset.id,action:'already-installed',files:0});
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
for(const file of files)checkExisting(prior,file);
|
|
100
|
+
plan.push({id:asset.id,action:prior?'update':'install',files:files.filter(file=>!fs.existsSync(file.target)||fileHash(file.target)!==file.digest).length,asset,rel,items:files});
|
|
101
|
+
}
|
|
102
|
+
if(!dryRun) {
|
|
103
|
+
for(const item of plan) {
|
|
104
|
+
if(!item.items)continue;
|
|
105
|
+
for(const file of item.items) {
|
|
106
|
+
if(fs.existsSync(file.target)&&fileHash(file.target)===file.digest)continue;
|
|
107
|
+
fs.mkdirSync(path.dirname(file.target),{recursive:true});
|
|
108
|
+
fs.copyFileSync(file.source,file.target);
|
|
109
|
+
}
|
|
110
|
+
state.installed[item.id]={catalogue,definition:structuredClone(item.asset),level:item.asset.level,path:item.rel,version:item.asset.version||null,dependencies:item.asset.dependencies||{},files:Object.fromEntries(item.items.map(file=>[file.file,file.digest]))};
|
|
111
|
+
}
|
|
112
|
+
commitState();
|
|
113
|
+
}
|
|
114
|
+
return plan.map(({id,action,files})=>({id,action,files}));
|
|
115
|
+
}
|
|
116
|
+
function activeClosure(){
|
|
117
|
+
const installed=new Map();
|
|
118
|
+
for(const [id,e] of Object.entries(state.installed)){
|
|
119
|
+
if(!e.definition)fail('Legacy installed metadata requires levelsui migrate before building');
|
|
120
|
+
const errors=validateReusableUiDefinition(e.definition);if(errors.length)fail(id+': invalid installed definition: '+errors.join('; '));
|
|
121
|
+
if(e.definition.id!==id)fail('Installed identity mismatch');installed.set(id,e.definition);
|
|
122
|
+
}
|
|
123
|
+
return resolveAssets(installed,state.active||[]);
|
|
124
|
+
}
|
|
125
|
+
function usage(id) {
|
|
126
|
+
const users=[];
|
|
127
|
+
for(const [other,entry] of Object.entries(state.installed)){
|
|
128
|
+
if(other===id)continue;
|
|
129
|
+
const deps=entry.dependencies||{};
|
|
130
|
+
if(['elements','layout','components','templates','pages'].some(key=>Array.isArray(deps[key])&&deps[key].includes(id)))users.push(other);
|
|
131
|
+
}
|
|
132
|
+
return users;
|
|
133
|
+
}
|
|
134
|
+
function remove(ids,{apply=false}={}) {
|
|
135
|
+
const requested=new Set(ids);
|
|
136
|
+
const active=new Set(activeClosure().map(asset=>asset.id));
|
|
137
|
+
const actions=[];
|
|
138
|
+
for(const id of requested) {
|
|
139
|
+
const {entry,target}=readInstalled(id);
|
|
140
|
+
if(state.active.includes(id))fail(`Cannot remove active asset ${id}; unuse it first`);
|
|
141
|
+
if(active.has(id))fail(`Cannot remove ${id}; an active asset requires it`);
|
|
142
|
+
const users=usage(id).filter(other=>!requested.has(other));
|
|
143
|
+
if(users.length)fail(`Cannot remove ${id}; installed assets depend on it: ${users.join(', ')}`);
|
|
144
|
+
if(!entry.files || !Object.keys(entry.files).length)fail(`Cannot safely remove legacy ${id}; file hashes not recorded. Run update ${id} to adopt unchanged files first`);
|
|
145
|
+
for(const [name,digest] of Object.entries(entry.files)) {
|
|
146
|
+
const file=path.resolve(target,name);assertWithin(target,file);
|
|
147
|
+
if(!fs.existsSync(file))fail(`Cannot remove ${id}; tracked file missing: ${file}`);
|
|
148
|
+
if(fileHash(file)!==digest)fail(`Cannot remove ${id}; local modifications detected: ${file}`);
|
|
149
|
+
}
|
|
150
|
+
// Untracked files are left untouched. Only tracked files are removed.
|
|
151
|
+
actions.push({id,entry,target,count:Object.keys(entry.files).length});
|
|
152
|
+
}
|
|
153
|
+
if(apply) {
|
|
154
|
+
for(const action of actions) {
|
|
155
|
+
for(const name of Object.keys(action.entry.files)){
|
|
156
|
+
const file=path.resolve(action.target,name);
|
|
157
|
+
fs.unlinkSync(file);
|
|
158
|
+
}
|
|
159
|
+
// Only remove empty directories; preserve user-created files.
|
|
160
|
+
function removeEmpty(dir){if(!fs.existsSync(dir))return;for(const e of fs.readdirSync(dir,{withFileTypes:true}))if(e.isDirectory())removeEmpty(path.join(dir,e.name));if(fs.readdirSync(dir).length===0)fs.rmdirSync(dir);}
|
|
161
|
+
removeEmpty(action.target);
|
|
162
|
+
delete state.installed[action.id];
|
|
163
|
+
}
|
|
164
|
+
commitState();
|
|
165
|
+
}
|
|
166
|
+
return actions.map(({id,count})=>({id,files:count}));
|
|
167
|
+
}
|
|
168
|
+
function prune({apply=false}={}) {
|
|
169
|
+
const required=new Set(activeClosure().map(a=>a.id));
|
|
170
|
+
// Inactive top-level assets may be removed together with their now-unused dependencies.
|
|
171
|
+
const candidates=new Set(Object.keys(state.installed).filter(id=>!required.has(id)));
|
|
172
|
+
return remove([...candidates],{apply});
|
|
173
|
+
}
|
|
174
|
+
function activate(id,enabled) {
|
|
175
|
+
if(enabled){readInstalled(id);state.active=[...new Set([...state.active,id])];}
|
|
176
|
+
else state.active=state.active.filter(item=>item!==id);
|
|
177
|
+
if(enabled)activeClosure();
|
|
178
|
+
commitState();
|
|
179
|
+
}
|
|
180
|
+
function doctor() {
|
|
181
|
+
const active=activeClosure();
|
|
182
|
+
for(const asset of active)if(!state.installed[asset.id])fail(`Missing installed dependency: ${asset.id}`);
|
|
183
|
+
const warnings=[];
|
|
184
|
+
for(const [id,entry] of Object.entries(state.installed)) {
|
|
185
|
+
const {target}=readInstalled(id);
|
|
186
|
+
if(!entry.files) {warnings.push(`${id}: legacy manifest without tracked file hashes`);continue;}
|
|
187
|
+
for(const [name,digest] of Object.entries(entry.files)) {
|
|
188
|
+
const file=path.resolve(target,name);assertWithin(target,file);
|
|
189
|
+
if(!fs.existsSync(file))fail(`Missing tracked file: ${file}`);
|
|
190
|
+
if(fileHash(file)!==digest)warnings.push(`${id}: locally modified ${name}`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return {installed:Object.keys(state.installed).length,required:active.length,warnings};
|
|
194
|
+
}
|
|
195
|
+
function generate({write=true}={}) {
|
|
196
|
+
const assets=activeClosure();
|
|
197
|
+
// Behaviour identifiers are deliberately allowlisted to public Core exports.
|
|
198
|
+
// Never transform registry metadata into arbitrary JavaScript imports.
|
|
199
|
+
const knownBehaviours = new Map([
|
|
200
|
+
['disclosure', {
|
|
201
|
+
module: '@buffercreations/buffercore/behaviours/declarative-disclosure',
|
|
202
|
+
exportName: 'registerDeclarativeDisclosure'
|
|
203
|
+
}]
|
|
204
|
+
]);
|
|
205
|
+
const neededBehaviours = new Set();
|
|
206
|
+
for (const asset of assets) {
|
|
207
|
+
const requested = asset.dependencies?.behaviours ?? [];
|
|
208
|
+
if (!Array.isArray(requested) || requested.some(value => typeof value !== 'string')) {
|
|
209
|
+
fail(`Invalid Behaviour dependencies for ${asset.id}: expected an array of names`);
|
|
210
|
+
}
|
|
211
|
+
for (const name of requested) {
|
|
212
|
+
if (!knownBehaviours.has(name)) fail(`Unsupported Core Behaviour '${name}' requested by ${asset.id}`);
|
|
213
|
+
neededBehaviours.add(name);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const lines=['// BufferCore CLI generated. Do not edit; regenerate with `buffercore entries`.','@use "@buffercreations/buffercore/scss/buffercore";'];
|
|
217
|
+
const js=['// BufferCore CLI generated. Import and call mountBufferCoreAssets(root) explicitly.'];
|
|
218
|
+
const mounts=[];
|
|
219
|
+
for(const asset of assets){
|
|
220
|
+
const {entry}=readInstalled(asset.id);
|
|
221
|
+
if(asset.source?.scss){const source=path.posix.basename(asset.source.scss);lines.push('@use '+JSON.stringify('./'+slash(entry.path)+'/'+source)+';');}
|
|
222
|
+
if(asset.source?.js && asset.mount?.export && asset.mount?.selector){
|
|
223
|
+
const alias=`mount${mounts.length}`;
|
|
224
|
+
js.push('import { '+asset.mount.export+' as '+alias+' } from '+JSON.stringify('./'+slash(entry.path)+'/'+path.posix.basename(asset.source.js))+';');
|
|
225
|
+
mounts.push({alias,selector:asset.mount.selector,id:asset.id});
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
// Reuse Core Runtime for both Asset-specific controllers and shared Behaviours.
|
|
229
|
+
// No Asset-specific JavaScript file is required for declarative Behaviours.
|
|
230
|
+
if(mounts.length || neededBehaviours.size){
|
|
231
|
+
js.splice(1,0,"import { createRuntime } from '@buffercreations/buffercore/runtime';");
|
|
232
|
+
js.push('export function mountBufferCoreAssets(root = document) {');
|
|
233
|
+
js.push(' const runtime = createRuntime();');
|
|
234
|
+
for (const name of [...neededBehaviours].sort()) {
|
|
235
|
+
const spec = knownBehaviours.get(name);
|
|
236
|
+
const alias = `registerBehaviour${js.length}`;
|
|
237
|
+
js.splice(1, 0, `import { ${spec.exportName} as ${alias} } from '${spec.module}';`);
|
|
238
|
+
js.push(` ${alias}(runtime);`);
|
|
239
|
+
}
|
|
240
|
+
mounts.forEach(({alias,selector,id})=>{
|
|
241
|
+
js.push(` runtime.register(${JSON.stringify('asset:'+id)}, { selector: ${JSON.stringify(selector)}, create: element => ${alias}(element) });`);
|
|
242
|
+
});
|
|
243
|
+
js.push(' try { runtime.mount(root); }');
|
|
244
|
+
js.push(' catch (error) { try { runtime.destroy(); } catch { /* Preserve mounting error. */ } throw error; }');
|
|
245
|
+
js.push(' return { destroy: () => runtime.destroy() };');
|
|
246
|
+
js.push('}');
|
|
247
|
+
}else{
|
|
248
|
+
js.push('export function mountBufferCoreAssets() { return { destroy() {} }; }');
|
|
249
|
+
}
|
|
250
|
+
const outputs={scss:lines.join('\n')+'\n',js:js.join('\n')+'\n',assets:assets.map(x=>x.id)};
|
|
251
|
+
if(write){
|
|
252
|
+
assertWithin(base,projectAssets);
|
|
253
|
+
assertWithin(base,path.join(projectAssets,'_active.scss'));assertWithin(base,path.join(projectAssets,'active.mjs'));
|
|
254
|
+
fs.mkdirSync(projectAssets,{recursive:true});
|
|
255
|
+
fs.writeFileSync(path.join(projectAssets,'_active.scss'),outputs.scss);
|
|
256
|
+
fs.writeFileSync(path.join(projectAssets,'active.mjs'),outputs.js);
|
|
257
|
+
}
|
|
258
|
+
return outputs;
|
|
259
|
+
}
|
|
260
|
+
return {state,registry,add,remove,prune,activate,generate,doctor,activeClosure,migrate:options=>migrateInstalled(base,options),manifestFile:location};
|
|
261
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {createRequire} from 'node:module';
|
|
4
|
+
|
|
5
|
+
const LEVELS_PACKAGE = '@buffercreations/levelsui';
|
|
6
|
+
|
|
7
|
+
/** Resolve a source catalogue without coupling Foundations to Levels.
|
|
8
|
+
* Precedence: explicit location > project's installed optional package > local checkout.
|
|
9
|
+
*/
|
|
10
|
+
export function resolveRegistryLocation({project, explicit, checkoutRoot,packageRoot} = {}) {
|
|
11
|
+
if (explicit !== undefined) {
|
|
12
|
+
if (typeof explicit !== 'string' || !explicit.trim()) throw Error('--registry requires a directory');
|
|
13
|
+
const chosen = path.resolve(explicit);
|
|
14
|
+
if (!fs.existsSync(chosen) || !fs.statSync(chosen).isDirectory()) throw Error(`Registry directory not found: ${chosen}`);
|
|
15
|
+
return chosen;
|
|
16
|
+
}
|
|
17
|
+
const base = path.resolve(project || process.cwd());
|
|
18
|
+
const requireFromProject = createRequire(path.join(base, 'package.json'));
|
|
19
|
+
try {
|
|
20
|
+
// The package explicitly exposes its package.json; no dependency on workspace layout.
|
|
21
|
+
const manifest = requireFromProject.resolve(`${LEVELS_PACKAGE}/package.json`);
|
|
22
|
+
return path.dirname(manifest);
|
|
23
|
+
} catch (error) {
|
|
24
|
+
if (error.code !== 'MODULE_NOT_FOUND' && error.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') throw error;
|
|
25
|
+
}
|
|
26
|
+
if (checkoutRoot) {
|
|
27
|
+
const sibling = path.resolve(checkoutRoot, '02. LevelsUI');
|
|
28
|
+
if (fs.existsSync(sibling) && fs.statSync(sibling).isDirectory()) return sibling;
|
|
29
|
+
}
|
|
30
|
+
if(packageRoot && fs.existsSync(path.join(packageRoot,'01. Elements'))) return packageRoot;
|
|
31
|
+
throw Error(`No Levels registry found. Install ${LEVELS_PACKAGE} in the project or pass --registry <directory>. Foundations does not require Levels.`);
|
|
32
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import Ajv2020 from 'ajv/dist/2020.js';
|
|
4
|
+
import {safeRelative,assertWithin} from './paths.mjs';
|
|
5
|
+
export const folders=Object.freeze({elements:'01. Elements',layout:'02. Layouts',components:'03. Components',templates:'04. Templates',pages:'05. Pages'});
|
|
6
|
+
const prefixes={elements:'bce-',layout:'bcl-',components:'bcc-',templates:'bct-',pages:'bcp-'};
|
|
7
|
+
const schema=JSON.parse(fs.readFileSync(new URL('../../schemas/reusable-ui.schema.json',import.meta.url)));
|
|
8
|
+
const validate=new Ajv2020({allErrors:true,strict:false}).compile(schema);
|
|
9
|
+
export function validateReusableUiDefinition(def,{coreRoot,filename}={}){
|
|
10
|
+
const errors=[];
|
|
11
|
+
if(!validate(def))for(const e of validate.errors)errors.push(e.keyword==='additionalProperties'?(e.instancePath?e.instancePath+' ':'')+'Unknown field '+e.params.additionalProperty:`${e.instancePath||'definition'} ${e.message}${e.keyword==='uniqueItems'?' (unique identifier array required)':''}`);
|
|
12
|
+
if(!def||typeof def!=='object')return errors;
|
|
13
|
+
if(def.kind!=='recipe'&&typeof def.className==='string'&&!def.className.startsWith(prefixes[def.level]))errors.push('className has wrong level prefix');
|
|
14
|
+
if(filename&&filename!==def.id+'.definition.json')errors.push('Definition filename must match id');
|
|
15
|
+
if(def.mount&&(!def.source?.js||!/^[A-Za-z_$][\w$]*$/.test(def.mount.export||'')))errors.push('mount requires source.js and a valid export identifier');
|
|
16
|
+
for(const [key,value] of Object.entries(def.source||{})){
|
|
17
|
+
if(!safeRelative(value)||!value.endsWith('.'+key))errors.push('Invalid source.'+key+' path');
|
|
18
|
+
else if(coreRoot)try{const p=assertWithin(coreRoot,path.resolve(coreRoot,value));if(!fs.statSync(p).isFile())throw Error('not a file');}catch(e){errors.push('Missing or unsafe source.'+key+': '+e.message);}
|
|
19
|
+
}
|
|
20
|
+
return errors;
|
|
21
|
+
}
|
|
22
|
+
export function resolveAssets(map,ids){
|
|
23
|
+
const ordered=[],seen=new Set(),visiting=new Set();
|
|
24
|
+
function visit(id){
|
|
25
|
+
if(seen.has(id))return;if(visiting.has(id))throw Error('Circular asset dependency: '+id);
|
|
26
|
+
const asset=map.get(id);if(!asset)throw Error('Unknown required asset: '+id);visiting.add(id);
|
|
27
|
+
for(const key of ['elements','layout','components','templates','pages'])for(const dep of asset.dependencies?.[key]||[]){
|
|
28
|
+
if(!map.has(dep))throw Error(`${id}: unknown ${key} dependency ${dep}`);
|
|
29
|
+
if(map.get(dep).level&&map.get(dep).level!==key)throw Error(`${id}: ${key} dependency ${dep} resolves to ${map.get(dep).level}, not ${key}`);visit(dep);
|
|
30
|
+
}
|
|
31
|
+
visiting.delete(id);seen.add(id);ordered.push(asset);
|
|
32
|
+
}
|
|
33
|
+
ids.forEach(visit);return ordered;
|
|
34
|
+
}
|
|
35
|
+
export function discoverReusableUiDefinitions(root,{hydrate=true}={}){
|
|
36
|
+
root=path.resolve(root);const definitions=[];
|
|
37
|
+
function walk(dir,level){
|
|
38
|
+
assertWithin(root,dir);
|
|
39
|
+
for(const e of fs.readdirSync(dir,{withFileTypes:true})){
|
|
40
|
+
if(e.name.startsWith('.'))continue;const file=assertWithin(root,path.join(dir,e.name));
|
|
41
|
+
if(e.isDirectory()){walk(file,level);continue;}if(!e.name.endsWith('.definition.json'))continue;
|
|
42
|
+
const def=JSON.parse(fs.readFileSync(file,'utf8')),errors=validateReusableUiDefinition(def,{coreRoot:root,filename:e.name});
|
|
43
|
+
if(def.level!==level||path.basename(dir)!==def.id)errors.push('Definition identity does not match level or asset folder');
|
|
44
|
+
for(const key of ['scss','js','html'])if(def.source?.[key]&&path.dirname(path.resolve(root,def.source[key]))!==dir)errors.push('Source must be co-located with its definition');
|
|
45
|
+
if(errors.length)throw Error(file+': '+errors.join('; '));
|
|
46
|
+
const read=rel=>{if(!safeRelative(rel))throw Error('Invalid documentation/example path');return fs.readFileSync(assertWithin(dir,path.resolve(dir,rel)),'utf8');};
|
|
47
|
+
if(def.documentation){
|
|
48
|
+
const doc=def.documentation,api=JSON.parse(read(doc.api)),specs=JSON.parse(read(doc.examples));
|
|
49
|
+
const allowed=new Set(['variants','sizes','anatomy','properties','accessibility','tags','notes','reference','status']);
|
|
50
|
+
if(!api||Array.isArray(api)||Object.keys(api).some(k=>!allowed.has(k)))throw Error(file+': api.json contains unsupported fields');
|
|
51
|
+
if(!Array.isArray(specs))throw Error('examples index must be an array');
|
|
52
|
+
const seen=new Set(),examples=specs.map(s=>{
|
|
53
|
+
if(!s||!/^[a-z][a-z0-9-]*$/.test(s.id)||seen.has(s.id))throw Error('Invalid or duplicate example id');seen.add(s.id);
|
|
54
|
+
for(const field of ['preview','code'])if(!s[field]?.startsWith('examples/'))throw Error('Invalid '+field+' path');
|
|
55
|
+
const previewHtml=read(s.preview),codeHtml=read(s.code);
|
|
56
|
+
if(/\sstyle\s*=|<style\b/i.test(previewHtml+codeHtml))throw Error(file+': inline presentation is not permitted in examples');
|
|
57
|
+
return {...s,...(hydrate?{previewHtml,codeHtml}:{})};
|
|
58
|
+
});
|
|
59
|
+
const guide=read(doc.guide);if(hydrate)Object.assign(def,api,{examples,usage:guide.replace(/^#.*\n+/,'').trim()});
|
|
60
|
+
}
|
|
61
|
+
Object.defineProperty(def,'definitionFile',{value:file,enumerable:false});definitions.push(def);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
for(const [level,dir] of Object.entries(folders)){const p=path.join(root,dir);if(fs.existsSync(p))walk(p,level);}
|
|
65
|
+
for(const a of definitions)for(const b of definitions){if(a===b)continue;const dir=path.dirname(a.definitionFile),rel=path.relative(dir,path.dirname(b.definitionFile));if(rel&&!rel.startsWith('..'+path.sep)&&rel!=='..'&&!path.isAbsolute(rel))throw Error('Asset directories must be leaves; nested Asset: '+b.id);}
|
|
66
|
+
const map=new Map();for(const def of definitions){if(map.has(def.id))throw Error('Duplicate asset: '+def.id);map.set(def.id,def);}
|
|
67
|
+
for(const def of definitions){const css=new Set();for(const a of resolveAssets(map,[def.id])){for(const name of a.dependencies?.css||[])css.add(({foundations:'dist/buffercore.min.css',tokens:'dist/buffercore-tokens.min.css',utilities:'dist/buffercore-utilities.min.css'})[name]);if(a.source?.css)css.add(a.source.css);}if(hydrate){def.resolvedCss=[...css];def.resolvedAssets=resolveAssets(map,[def.id]).map(a=>a.id);}}
|
|
68
|
+
return definitions.sort((a,b)=>a.level.localeCompare(b.level)||a.displayName.localeCompare(b.displayName));
|
|
69
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
export const safeRelative=value=>typeof value==='string'&&/^[a-zA-Z0-9_ .\/-]+$/.test(value)&&!path.isAbsolute(value)&&value.split('/').every(p=>p&&p!=='.'&&p!=='..'&&!p.startsWith('.'));
|
|
4
|
+
export function assertWithin(root,file){
|
|
5
|
+
root=path.resolve(root);file=path.resolve(file);const rel=path.relative(root,file);
|
|
6
|
+
if(rel==='..'||rel.startsWith('..'+path.sep)||path.isAbsolute(rel))throw Error('Unsafe asset path: '+file);
|
|
7
|
+
let current=path.parse(file).root;
|
|
8
|
+
for(const part of file.slice(current.length).split(path.sep).filter(Boolean)){
|
|
9
|
+
current=path.join(current,part);
|
|
10
|
+
try {if(fs.lstatSync(current).isSymbolicLink())throw Error('Symlink/junction not permitted: '+current);}
|
|
11
|
+
catch(error){if(error.code==='ENOENT')break;throw error;}
|
|
12
|
+
}
|
|
13
|
+
if(fs.existsSync(root)&&fs.existsSync(file)){const real=path.relative(fs.realpathSync(root),fs.realpathSync(file));if(real==='..'||real.startsWith('..'+path.sep)||path.isAbsolute(real))throw Error('Realpath escapes root: '+file);}
|
|
14
|
+
return file;
|
|
15
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
import {assertWithin} from '../tooling/registry/paths.mjs';
|
|
6
|
+
import {discoverReusableUiDefinitions} from '../tooling/registry/definitions.mjs';
|
|
7
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
8
|
+
const levels = ['01. Elements', '02. Layouts', '03. Components', '04. Templates', '05. Pages'];
|
|
9
|
+
|
|
10
|
+
let sass;
|
|
11
|
+
try {
|
|
12
|
+
sass = await import('sass');
|
|
13
|
+
} catch (error) {
|
|
14
|
+
if (error.code !== 'ERR_MODULE_NOT_FOUND') throw error;
|
|
15
|
+
console.error('LevelsUI: Sass is not installed. Run `npm install` in LevelsUI, then `npm run build`.');
|
|
16
|
+
process.exit(1);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const assets = [];
|
|
20
|
+
function walk(folder) {
|
|
21
|
+
if (!fs.existsSync(folder)) return;
|
|
22
|
+
for (const item of fs.readdirSync(folder, { withFileTypes: true })) {
|
|
23
|
+
const location = path.join(folder, item.name);
|
|
24
|
+
if (item.isDirectory()) walk(location);
|
|
25
|
+
else if (item.isFile() && item.name.endsWith('.definition.json')) {
|
|
26
|
+
let definition;
|
|
27
|
+
try {
|
|
28
|
+
definition = JSON.parse(fs.readFileSync(location, 'utf8'));
|
|
29
|
+
} catch (error) {
|
|
30
|
+
throw new Error(`Invalid definition ${path.relative(root, location)}: ${error.message}`);
|
|
31
|
+
}
|
|
32
|
+
assets.push({ definition, location });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
for (const definition of discoverReusableUiDefinitions(root,{hydrate:false})) assets.push({definition,location:definition.definitionFile});
|
|
38
|
+
assets.sort((a, b) => a.location.localeCompare(b.location));
|
|
39
|
+
|
|
40
|
+
const outputRoot = path.join(root, 'dist', 'components');
|
|
41
|
+
assertWithin(root,outputRoot);
|
|
42
|
+
fs.mkdirSync(outputRoot, { recursive: true });
|
|
43
|
+
const known = new Set();
|
|
44
|
+
const outputs=new Set();
|
|
45
|
+
let count = 0;
|
|
46
|
+
|
|
47
|
+
for (const { definition, location } of assets) {
|
|
48
|
+
if (!definition.source?.scss) continue;
|
|
49
|
+
const id = definition.id;
|
|
50
|
+
if (typeof id !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
|
|
51
|
+
throw new Error(`Invalid asset id in ${path.relative(root, location)}: ${JSON.stringify(id)}`);
|
|
52
|
+
}
|
|
53
|
+
if (known.has(id)) throw new Error(`Duplicate asset id: ${id}`);
|
|
54
|
+
known.add(id);
|
|
55
|
+
|
|
56
|
+
const input = path.resolve(root, definition.source.scss);
|
|
57
|
+
if (!input.startsWith(root + path.sep) || !fs.existsSync(input)) {
|
|
58
|
+
throw new Error(`SCSS file missing or outside registry for ${id}: ${definition.source.scss}`);
|
|
59
|
+
}
|
|
60
|
+
const output = assertWithin(root,path.resolve(root,definition.source.css));
|
|
61
|
+
if(outputs.has(output))throw Error("Duplicate CSS output: "+definition.source.css);outputs.add(output);fs.mkdirSync(path.dirname(output),{recursive:true});
|
|
62
|
+
try {
|
|
63
|
+
const result = sass.compile(input, { style: 'expanded', sourceMap: false, loadPaths: [path.join(root, 'node_modules')] });
|
|
64
|
+
fs.writeFileSync(output, result.css);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
console.error(`Unable to compile ${id} (${path.relative(root, input)}):`);
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
if (!fs.statSync(output).size) throw new Error(`Empty CSS output for ${id}`);
|
|
70
|
+
count++;
|
|
71
|
+
console.log(`${id}: ${path.relative(root, output)} (${fs.statSync(output).size} bytes)`);
|
|
72
|
+
}
|
|
73
|
+
console.log(`Built ${count} library stylesheet${count === 1 ? '' : 's'}.`);
|
|
74
|
+
|
|
75
|
+
for(const entry of fs.readdirSync(outputRoot)){if(entry.endsWith('.css')&&!outputs.has(path.join(outputRoot,entry)))fs.unlinkSync(assertWithin(outputRoot,path.join(outputRoot,entry)));}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { discoverReusableUiDefinitions } from '../tooling/registry/definitions.mjs';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
|
|
5
|
+
const definitions=discoverReusableUiDefinitions(root);
|
|
6
|
+
console.log(`Valid LevelsUI definitions: ${definitions.length}`);
|