velloo 0.4.0 → 0.5.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 +29 -7
- package/canvas/assets/index-BDBBHdHH.css +2 -0
- package/canvas/assets/index-QdsLJNY9.js +29 -0
- package/canvas/assets/lucide-all-R8DUyY-B.js +1 -0
- package/canvas/index.html +2 -2
- package/chunk-0rdf6trc.js +2 -0
- package/{chunk-tkvb3wb8.js → chunk-0wafc9aw.js} +1 -1
- package/chunk-0wqxb8r9.js +3 -0
- package/{chunk-hzjzmkp6.js → chunk-10hap8kc.js} +1 -1
- package/chunk-18eqh3s1.js +2 -0
- package/chunk-19xyzep8.js +2 -0
- package/{chunk-sn9vg42q.js → chunk-1h3gqy7w.js} +1 -1
- package/{chunk-3kqtny5t.js → chunk-33t0csxs.js} +2 -2
- package/{chunk-0r80246c.js → chunk-3ffs39e8.js} +1 -1
- package/chunk-42bj6r30.js +3 -0
- package/chunk-49w26e94.js +5 -0
- package/{chunk-nte0t7v3.js → chunk-4pkw6d9n.js} +2 -2
- package/{chunk-vh4144az.js → chunk-4sjvdakg.js} +1 -1
- package/chunk-5f0xv80x.js +5 -0
- package/{chunk-2fgfex9b.js → chunk-5ma8zbty.js} +1 -1
- package/{chunk-8yz604tw.js → chunk-5y9hem1j.js} +1 -1
- package/chunk-66qgm91k.js +708 -0
- package/{chunk-46xykc71.js → chunk-675tr675.js} +1 -1
- package/{chunk-7cktk5qr.js → chunk-6cgvzwec.js} +1 -1
- package/chunk-6k05kqnc.js +3 -0
- package/{chunk-09385g5r.js → chunk-6ytv1v2r.js} +1 -1
- package/{chunk-33r6266k.js → chunk-75sc3adm.js} +1 -1
- package/chunk-7cexzg71.js +2 -0
- package/chunk-98rann8t.js +2 -0
- package/{chunk-e56eb38j.js → chunk-a16mz9zf.js} +1 -1
- package/chunk-afe25dpr.js +2 -0
- package/{chunk-zkn1m8tw.js → chunk-ahm4zd56.js} +1 -1
- package/chunk-asvdqkdp.js +6 -0
- package/{chunk-8sfx5x8k.js → chunk-b3x80jc1.js} +1 -1
- package/{chunk-4rvmpsda.js → chunk-cdqah1hy.js} +1 -1
- package/{chunk-z1r0sc3k.js → chunk-cqt1dpxd.js} +1 -1
- package/{chunk-k10n8na7.js → chunk-d4r0myxr.js} +1 -1
- package/{chunk-cdxy4xzs.js → chunk-d9kx7v12.js} +1 -1
- package/{chunk-t4zss1tk.js → chunk-df557bn4.js} +1 -1
- package/{chunk-25j8vgpa.js → chunk-edgwx026.js} +1 -1
- package/chunk-emv1j50t.js +2 -0
- package/{chunk-3gbmq4jz.js → chunk-ewgdcgrk.js} +1 -1
- package/chunk-f45p6kcb.js +2 -0
- package/{chunk-8krqgzny.js → chunk-gn9wcc1b.js} +1 -1
- package/{chunk-vbe2r4kv.js → chunk-hr3gbak5.js} +2 -2
- package/{chunk-y0rwf1ze.js → chunk-j7tzbt3d.js} +1 -1
- package/chunk-mm8wv3bg.js +3 -0
- package/chunk-nbbnb5e9.js +3 -0
- package/{chunk-c4fym47a.js → chunk-ngbqd7kb.js} +32 -12
- package/chunk-nkqtnwzz.js +2 -0
- package/{chunk-jtsn41cs.js → chunk-q3kf8243.js} +1 -1
- package/{chunk-c6hywdvq.js → chunk-qpv28z8d.js} +1 -1
- package/{chunk-n5acf0s3.js → chunk-rd65xm6r.js} +1 -1
- package/{chunk-ys3s5gaa.js → chunk-ryga3ny1.js} +1 -1
- package/{chunk-cvn689d5.js → chunk-sb5h27w9.js} +2 -2
- package/chunk-tw4kw4ps.js +22 -0
- package/chunk-v6c3h9ft.js +3 -0
- package/chunk-vgx47anc.js +3 -0
- package/chunk-vrvkvb0v.js +244 -0
- package/{chunk-v0syg2hx.js → chunk-vryadew3.js} +9 -7
- package/chunk-w6f40y2x.js +11 -0
- package/{chunk-c5zjen06.js → chunk-we8hvy6e.js} +1 -1
- package/chunk-wkqrb2tz.js +4 -0
- package/{chunk-js6mz7h1.js → chunk-xzkczmgg.js} +1 -1
- package/{chunk-8yadb6xz.js → chunk-ycrddh47.js} +1 -1
- package/{chunk-bhx8k09w.js → chunk-z78c1kf8.js} +1 -1
- package/cli.js +1 -1
- package/package.json +3 -1
- package/pkgs/provider-html/src/index.ts +68 -0
- package/pkgs/provider-html/src/registry.ts +121 -0
- package/pkgs/provider-html/src/version.ts +1 -0
- package/pkgs/provider-none/src/components-inline.tsx +12 -3
- package/pkgs/provider-none/src/components.tsx +11 -3
- package/pkgs/provider-none/src/manifest.ts +1 -0
- package/pkgs/schema/src/comment.ts +12 -0
- package/pkgs/schema/src/config.ts +33 -1
- package/pkgs/schema/src/css-declarations.ts +41 -0
- package/pkgs/schema/src/index.ts +4 -0
- package/pkgs/schema/src/theme.ts +40 -0
- package/plugins/claude/velloo/agents/velloo-design-reviewer.md +56 -13
- package/plugins/claude/velloo/agents/velloo-designer.md +4 -1
- package/skills/velloo-setup/SKILL.md +19 -55
- package/canvas/assets/index-CSSyvzzo.css +0 -2
- package/canvas/assets/index-MXiDRs_Q.js +0 -29
- package/canvas/assets/lucide-all-BSrW0hTo.js +0 -1
- package/chunk-0zen7bzb.js +0 -3
- package/chunk-1tdh4h14.js +0 -6
- package/chunk-38ev3cp3.js +0 -3
- package/chunk-5qd2ykvw.js +0 -26
- package/chunk-6qfyem23.js +0 -2
- package/chunk-6z0kpe65.js +0 -2
- package/chunk-8g5ghy46.js +0 -5
- package/chunk-cgzhcvsj.js +0 -2
- package/chunk-egccxmed.js +0 -688
- package/chunk-fjbzk4sw.js +0 -3
- package/chunk-gsne0ap4.js +0 -2
- package/chunk-nc5k1ez4.js +0 -2
- package/chunk-njhdn9j0.js +0 -4
- package/chunk-q4d60wr3.js +0 -3
- package/chunk-rsy246re.js +0 -2
- package/chunk-syg6k8m0.js +0 -10
- package/chunk-t8xk4thc.js +0 -244
- package/chunk-tqwe5tc3.js +0 -2
- package/chunk-va9v9y5m.js +0 -2
- package/chunk-yjmawrv5.js +0 -5
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ScreenSchema}from"./chunk-4pkw6d9n.js";import{detectTailwindMajor,emitCode,moduleTarget,emitHtml,v3ClassIssues,classNamesInJsx,styleChannelOf,loadDesignFolder,registryForScreen,hostAppRootFrom,resolveProviders}from"./chunk-66qgm91k.js";import"./chunk-ngbqd7kb.js";import"./chunk-afe25dpr.js";import"./chunk-80fjfyha.js";import{fail}from"./chunk-s23gtejf.js";import{findDesignConfig}from"./chunk-z78c1kf8.js";import{createProgress}from"./chunk-pjtg3wnm.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign,pickScreen}from"./chunk-675tr675.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{readFile,writeFile}from"fs/promises";import{extname,isAbsolute,resolve}from"path";import{stdout}from"process";async function folderEmitContext(screenPath,screen){let found=await findDesignConfig(screenPath);if(!found)return{};let design=await loadDesignFolder(found.folder),{providers,defaultProvider}=await resolveProviders(design.config,found.folder),provider=screen.library&&providers[screen.library]||defaultProvider,adapter=provider;if(adapter.codegenFormat==="html"){let registry=registryForScreen(screen,providers,defaultProvider,design.config.extensions??{},design.config.styling?.framework);return{html:await emitHtml(screen,{registry,snippets:design.snippets})}}let target;if(adapter.codegenModule){let manifest=await provider.loadManifest();target=moduleTarget(manifest.filter((c)=>c.source!=="velloo").map((c)=>c.id),adapter.codegenModule)}let inlineStyle=styleChannelOf(provider,design.config.styling?.framework).kind==="style";return{snippets:design.snippets,...design.config.extensions?{extensions:design.config.extensions}:{},...target?{target}:{},...inlineStyle?{inlineStyle:!0}:{}}}var emit_default=defineCommand({meta:{name:"emit",description:"Print or write agent-consumed IR for a screen."},args:{screen:{type:"positional",required:!1,description:"Screen id, or a path to a screen JSON. Omit to pick interactively."},design:{type:"string",description:DESIGN_ARG_DESCRIPTION},to:{type:"string",description:"Write IR as JSON to this path; for HTML screens, a .html path writes native markup. Omit to print the native body to stdout."},"components-alias":{type:"string",description:'Override the import prefix the IR mentions in snippet identifiers. Defaults to .design/config.json#codegen.componentsAlias, else "@/components/ui".'}},async run({args}){let interactive=Boolean(process.stdin.isTTY),screenArg=args.screen,screenPath=!!screenArg&&(screenArg.includes("/")||screenArg.endsWith(".json"))?resolve(screenArg):(await pickScreen(await resolveDesign(args.design,"emit",{designFlag:"--design"}),screenArg,interactive,"emit")).path,screenJson=JSON.parse(await readFile(screenPath,"utf8")),screen=ScreenSchema.parse(screenJson),progress=createProgress();progress.start("preparing code");try{let componentsAlias=args["components-alias"]??await readConfigAlias(screenPath),context=await folderEmitContext(screenPath,screen);if(progress.step("generating code"),context.html){let ir=context.html;if(progress.succeed("generated HTML"),args.to){let outPath=isAbsolute(args.to)?args.to:resolve(args.to),asMarkup=extname(outPath).toLowerCase()===".html";await writeFile(outPath,asMarkup?ir.html:JSON.stringify(ir,null,2),"utf8"),console.log(`velloo emit: wrote ${outPath}`);for(let warning of ir.warnings)console.log(` note: ${warning}`)}else stdout.write(`${ir.html}
|
|
3
|
+
`);return}let result=await emitCode(screen,{...componentsAlias?{componentsAlias}:{},...context});if(!result.ok){progress.fail("code generation failed");let e=result.error;if(e.kind==="UnknownComponent")fail("emit",`unknown component: ${JSON.stringify(e.ref)}`);else if(e.kind==="SnippetNotFound")fail("emit",`snippet not found: ${JSON.stringify(e.snippetId)}`);else fail("emit",`screen not found: ${JSON.stringify(e.screenId)}`)}let found=await findDesignConfig(screenPath),tailwindV3Compat=found&&!context?.target&&!context?.inlineStyle?detectTailwindMajor(hostAppRootFrom(found.folder,found.config.hostApp))===3?v3ClassIssues([...result.value.classesUsed,...result.value.snippetsUsed.flatMap((s)=>classNamesInJsx(s.jsx))]):[]:[];if(args.to){progress.step("writing code");let outPath=isAbsolute(args.to)?args.to:resolve(args.to),ir=tailwindV3Compat.length>0?{...result.value,tailwindV3Compat}:result.value;await writeFile(outPath,JSON.stringify(ir,null,2),"utf8"),progress.succeed("generated code"),console.log(`velloo emit: wrote ${outPath}`);return}if(progress.succeed("generated code"),stdout.write(`// screen: ${result.value.screen.id} (${result.value.screen.name})
|
|
4
|
+
`),stdout.write(`// components: ${result.value.componentsUsed.join(", ")||"(none)"}
|
|
5
|
+
`),result.value.iconsUsed.length>0)stdout.write(`// icons (lucide): ${result.value.iconsUsed.join(", ")}
|
|
6
|
+
`);if(result.value.snippetsUsed.length>0)stdout.write(`// snippets: ${result.value.snippetsUsed.map((s)=>`${s.componentName}(${s.id})`).join(", ")}
|
|
7
|
+
`);for(let issue of tailwindV3Compat)stdout.write(issue.v3?`// tailwind v3 host: \`${issue.class}\` \u2192 \`${issue.v3}\` (${issue.note})
|
|
8
|
+
`:`// tailwind v3 host: \`${issue.class}\` \u2014 ${issue.note}
|
|
9
|
+
`);stdout.write(`
|
|
10
|
+
`),stdout.write(`${result.value.jsx}
|
|
11
|
+
`)}catch(error){throw progress.fail("code generation failed"),error}}});async function readConfigAlias(screenPath){return(await findDesignConfig(screenPath))?.config.codegen?.componentsAlias}export{emit_default as default};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{TAILWIND_CLASSNAME,helperSourcePath}from"./chunk-egccxmed.js";import{snapshotVersion2,entryCssPath2,componentsDir2}from"./chunk-cvn689d5.js";import{registry2}from"./chunk-vbe2r4kv.js";import"./chunk-c6hywdvq.js";import{readFile}from"fs/promises";import{join}from"path";async function readManifest(cacheDir){let raw=await readFile(join(cacheDir,"manifest.json"),"utf8");return JSON.parse(raw)}import{existsSync as existsSync4}from"fs";import{join as join5}from"path";import{existsSync as existsSync3,readFileSync as readFileSync3}from"fs";import{join as join4}from"path";import{existsSync,readFileSync}from"fs";import{join as join2}from"path";function exportsName(source,id){let name=id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:async\\s+)?(?:function|const|let|var|class)\\s+${name}\\b`).test(source))return!0;for(let match of source.matchAll(/\bexport\s*\{([^}]*)\}/g)){let clause=match[1]??"";for(let part of clause.split(",")){let local=part.trim().split(/\s+as\s+/);if((local.length>1?local[1]:local[0])?.trim()===id)return!0}}return/\bexport\s+\*\s+from\b/.test(source)}function hostComponentFile(uiDir,addName,id){for(let extension of["tsx","ts","jsx","js"]){let path=join2(uiDir,`${addName}.${extension}`);if(!existsSync(path))continue;try{return exportsName(readFileSync(path,"utf8"),id)?path:null}catch{return null}}return null}import{existsSync as existsSync2,readdirSync,readFileSync as readFileSync2}from"fs";import{join as join3,resolve}from"path";function kebab(id){return id.replace(/(?<!^)(?=[A-Z])/g,"-").toLowerCase()}function addNameIndex(manifest){let byId=new Map(manifest.flatMap((c)=>c.registryName?[[c.id,c.registryName]]:[]));return(id)=>byId.get(id)??kebab(id)}function findUiDir(hostAppRoot){let candidates=[];try{let cj=JSON.parse(readFileSync2(join3(hostAppRoot,"components.json"),"utf8")),fromAlias=(alias,suffix="")=>{if(!alias)return;let srcBase=existsSync2(join3(hostAppRoot,"src"))?"src":"",rel=alias.replace(/^@\//,srcBase?`${srcBase}/`:"")+suffix;candidates.push(resolve(hostAppRoot,rel))};fromAlias(cj.aliases?.ui),fromAlias(cj.aliases?.components,"/ui")}catch{}candidates.push(resolve(hostAppRoot,"src/components/ui"),resolve(hostAppRoot,"components/ui"),resolve(hostAppRoot,"app/components/ui"));for(let dir of candidates)if(existsSync2(dir))return dir;return null}function installedAddNames(hostAppRoot){let dir=findUiDir(hostAppRoot);if(!dir)return new Set;try{return new Set(readdirSync(dir).filter((f)=>f.endsWith(".tsx")||f.endsWith(".ts")).map((f)=>f.replace(/\.(tsx|ts)$/,"")))}catch{return new Set}}function enrichManifestFromHost(manifest,uiDir){if(!uiDir)return manifest;let addNameOf=addNameIndex(manifest),byFile=new Map,read=(addName)=>{if(byFile.has(addName))return byFile.get(addName)??null;for(let ext of["tsx","ts","jsx","js"]){let path=join4(uiDir,`${addName}.${ext}`);if(!existsSync3(path))continue;let source=readFileSync3(path,"utf8");return byFile.set(addName,source),source}return byFile.set(addName,""),null};return manifest.map((descriptor)=>{if(descriptor.source==="velloo")return descriptor;let source=read(addNameOf(descriptor.id));if(!source||!exportsName(source,descriptor.id))return descriptor;let additions=[...variantPropsFor(source,descriptor.id===descriptor.family),...declaredPropsFor(source,descriptor.id)];if(additions.length===0)return descriptor;let props=[...descriptor.props];for(let addition of additions){let index=props.findIndex((prop)=>prop.name===addition.name);if(index>=0)props[index]={...props[index],...addition};else props.push(addition)}return{...descriptor,props,designModeNotes:appendNote(descriptor.designModeNotes,"Props include variants detected from the app's component source.")}})}function appendNote(current,next){return current?`${current} ${next}`:next}function variantPropsFor(source,primary){let out=[];if(!primary)return out;let variantsAt=source.indexOf("variants:");if(variantsAt<0)return out;let open=source.indexOf("{",variantsAt),block=balancedBlock(source,open);if(!block)return out;for(let[name,value]of objectEntries(block.slice(1,-1))){let values=objectEntries(value.slice(1,-1)).map(([key])=>key);if(values.length===0)continue;out.push({name,type:`${values.map((value)=>JSON.stringify(value)).join(" | ")} | undefined`,optional:!0,control:"enum",enumValues:values,...defaultVariant(source,name)?{defaultValue:defaultVariant(source,name)}:{}})}return out}function defaultVariant(source,name){let at=source.indexOf("defaultVariants:");if(at<0)return;let open=source.indexOf("{",at),block=balancedBlock(source,open);if(!block)return;return objectEntries(block.slice(1,-1)).find(([key])=>key===name)?.[1].replace(/["'`\s]/g,"")}function declaredPropsFor(source,componentId){let match=[new RegExp(`interface\\s+${componentId}Props(?:\\s+extends[^\\{]+)?\\s*\\{`,"m"),new RegExp(`type\\s+${componentId}Props\\s*=.*?&\\s*\\{`,"m")].map((pattern)=>pattern.exec(source)).find(Boolean);if(!match||match.index===void 0)return[];let open=source.indexOf("{",match.index),block=balancedBlock(source,open);if(!block)return[];let out=[],property=/(?:^|[;{\n])\s*([A-Za-z_$][\w$]*)(\?)?\s*:\s*([^;\n}]+)/gm;for(let found of block.slice(1,-1).matchAll(property)){let name=found[1],raw=found[3]?.trim();if(!name||!raw||name==="children")continue;let enumValues=[...raw.matchAll(/["']([^"']+)["']/g)].map((value)=>value[1]),optional=found[2]==="?"||raw.includes("undefined");out.push({name,type:optional&&!raw.includes("undefined")?`${raw} | undefined`:raw,optional,control:enumValues.length>0?"enum":/boolean/.test(raw)?"boolean":/number/.test(raw)?"number":"string",...enumValues.length>0?{enumValues}:{}})}return out}function balancedBlock(source,open){if(open<0||source[open]!=="{")return null;let depth=0,quote="";for(let index=open;index<source.length;index++){let char=source[index],prev=source[index-1];if(quote){if(char===quote&&prev!=="\\")quote="";continue}if(char==='"'||char==="'"||char==="`"){quote=char;continue}if(char==="{")depth++;if(char==="}"&&--depth===0)return source.slice(open,index+1)}return null}function objectEntries(body){let out=[],index=0;while(index<body.length){while(index<body.length&&/[\s,]/.test(body[index]))index++;let keyMatch=/^(?:["']([^"']+)["']|([A-Za-z_$][\w$-]*))\s*:/.exec(body.slice(index));if(!keyMatch)break;let key=keyMatch[1]??keyMatch[2];if(!key)break;index+=keyMatch[0].length;while(/\s/.test(body[index]??""))index++;if(body[index]==="{"){let block=balancedBlock(body,index);if(!block)break;out.push([key,block]),index+=block.length;continue}let end=body.indexOf(",",index),value=body.slice(index,end<0?body.length:end).trim();out.push([key,value]),index=end<0?body.length:end+1}return out}function createProvider(opts={}){let cacheDir=opts.cacheDir,plannedUiDir=cacheDir?join5(cacheDir,"ui"):void 0,hostUiDir=()=>plannedUiDir&&existsSync4(plannedUiDir)?plannedUiDir:opts.hostAppRoot?findUiDir(opts.hostAppRoot):null,componentsDir=componentsDir2,version=opts.version??snapshotVersion2,hostAppRoot=opts.hostAppRoot,loadManifest=async()=>{if(cacheDir&&existsSync4(join5(cacheDir,"manifest.json")))return enrichManifestFromHost(await readManifest(cacheDir),hostUiDir());let{loadManifest:snapshotManifest}=await import("./chunk-tqwe5tc3.js");return enrichManifestFromHost(await snapshotManifest(),hostUiDir())};return{id:"shadcn-upstream",version,componentsDir,styleEntryPath:entryCssPath2,registry:registry2,loadManifest,label:`shadcn (upstream @ ${version})`,styleChannel:TAILWIND_CLASSNAME,styleChannels:["tailwind-classname"],mcpIntro:()=>['**This folder targets shadcn/ui with Tailwind.** The canvas imports client-safe components directly from the app, uses named canvas-safe adaptations for portal/state-heavy families, and falls back per component when a host file is missing or cannot compile. Velloo helpers (`Box`, `Heading`, `Text`, `Icon`, `Image`, `Gradient`, `Layer`, `SVG`, `Divider`, `Placeholder`, `Prose`) remain canvas primitives. Style through `update_props { style: "flex gap-4 p-6" }` \u2014 a Tailwind className string. Call `list_components` for the catalog and `component_status` before making a fidelity claim.',""],catalog:async()=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),shadcn=manifest.filter((c)=>c.source!=="velloo"),present=hostAppRoot?installedAddNames(hostAppRoot):new Set;return shadcn.map((c)=>{let addName=addNameOf(c.id);return{id:c.id,installed:present.has(addName),importPath:`@/components/ui/${addName}`}})},ownedModules:{dirs:()=>{let uiDir=hostUiDir();return uiDir?[uiDir]:[]}},canvasBundleSpec:{styleRuntime:{kind:"none"},components:async(ids)=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),sourceById=new Map(manifest.map((entry)=>[entry.id,entry.source])),uiDir=hostUiDir();return ids.flatMap((id)=>{if(sourceById.get(id)==="velloo"){let path=helperSourcePath(id);return path?[{id,sources:[{importPath:path,exportName:id,fidelity:"fallback",note:"Velloo helper used alongside repo-backed shadcn components."}]}]:[]}if(!sourceById.has(id))return[];let addName=addNameOf(id),snapshotPath=join5(componentsDir2,"ui",`${addName}.tsx`);if(CANVAS_ADAPTED_FAMILIES.has(addName))return[{id,sources:[{importPath:snapshotPath,exportName:id,fidelity:"adapted",note:"The app component uses portals or runtime state; Velloo renders its canvas-safe counterpart inline."}]}];let hostPath=uiDir?hostComponentFile(uiDir,addName,id):null;return[{id,sources:[...hostPath?[{importPath:hostPath,exportName:id,fidelity:"exact",preflight:!0,note:"Rendered directly from the app's shadcn source file."}]:[],{importPath:snapshotPath,exportName:id,fidelity:"fallback",note:hostPath?"The app source did not compile for the browser canvas; using the bundled canvas fallback.":"The app does not install this component under this name (it may be renamed in its own file); using the bundled canvas fallback."}]}]})},sourceDirs:()=>{let uiDir=hostUiDir()??plannedUiDir;return uiDir?[uiDir]:[]}}}}var CANVAS_ADAPTED_FAMILIES=new Set(["alert-dialog","calendar","carousel","chart","dialog","dropdown-menu","popover","select","sheet","sonner","tooltip"]);export{createProvider};
|
|
2
|
+
import{TAILWIND_CLASSNAME,helperSourcePath}from"./chunk-66qgm91k.js";import{snapshotVersion2,entryCssPath3,componentsDir3}from"./chunk-sb5h27w9.js";import{registry2}from"./chunk-hr3gbak5.js";import"./chunk-qpv28z8d.js";import{readFile}from"fs/promises";import{join}from"path";async function readManifest(cacheDir){let raw=await readFile(join(cacheDir,"manifest.json"),"utf8");return JSON.parse(raw)}import{existsSync as existsSync4}from"fs";import{join as join5}from"path";import{existsSync as existsSync3,readFileSync as readFileSync3}from"fs";import{join as join4}from"path";import{existsSync,readFileSync}from"fs";import{join as join2}from"path";function exportsName(source,id){let name=id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:async\\s+)?(?:function|const|let|var|class)\\s+${name}\\b`).test(source))return!0;for(let match of source.matchAll(/\bexport\s*\{([^}]*)\}/g)){let clause=match[1]??"";for(let part of clause.split(",")){let local=part.trim().split(/\s+as\s+/);if((local.length>1?local[1]:local[0])?.trim()===id)return!0}}return/\bexport\s+\*\s+from\b/.test(source)}function hostComponentFile(uiDir,addName,id){for(let extension of["tsx","ts","jsx","js"]){let path=join2(uiDir,`${addName}.${extension}`);if(!existsSync(path))continue;try{return exportsName(readFileSync(path,"utf8"),id)?path:null}catch{return null}}return null}import{existsSync as existsSync2,readdirSync,readFileSync as readFileSync2}from"fs";import{join as join3,resolve}from"path";function kebab(id){return id.replace(/(?<!^)(?=[A-Z])/g,"-").toLowerCase()}function addNameIndex(manifest){let byId=new Map(manifest.flatMap((c)=>c.registryName?[[c.id,c.registryName]]:[]));return(id)=>byId.get(id)??kebab(id)}function findUiDir(hostAppRoot){let candidates=[];try{let cj=JSON.parse(readFileSync2(join3(hostAppRoot,"components.json"),"utf8")),fromAlias=(alias,suffix="")=>{if(!alias)return;let srcBase=existsSync2(join3(hostAppRoot,"src"))?"src":"",rel=alias.replace(/^@\//,srcBase?`${srcBase}/`:"")+suffix;candidates.push(resolve(hostAppRoot,rel))};fromAlias(cj.aliases?.ui),fromAlias(cj.aliases?.components,"/ui")}catch{}candidates.push(resolve(hostAppRoot,"src/components/ui"),resolve(hostAppRoot,"components/ui"),resolve(hostAppRoot,"app/components/ui"));for(let dir of candidates)if(existsSync2(dir))return dir;return null}function installedAddNames(hostAppRoot){let dir=findUiDir(hostAppRoot);if(!dir)return new Set;try{return new Set(readdirSync(dir).filter((f)=>f.endsWith(".tsx")||f.endsWith(".ts")).map((f)=>f.replace(/\.(tsx|ts)$/,"")))}catch{return new Set}}function enrichManifestFromHost(manifest,uiDir){if(!uiDir)return manifest;let addNameOf=addNameIndex(manifest),byFile=new Map,read=(addName)=>{if(byFile.has(addName))return byFile.get(addName)??null;for(let ext of["tsx","ts","jsx","js"]){let path=join4(uiDir,`${addName}.${ext}`);if(!existsSync3(path))continue;let source=readFileSync3(path,"utf8");return byFile.set(addName,source),source}return byFile.set(addName,""),null};return manifest.map((descriptor)=>{if(descriptor.source==="velloo")return descriptor;let source=read(addNameOf(descriptor.id));if(!source||!exportsName(source,descriptor.id))return descriptor;let additions=[...variantPropsFor(source,descriptor.id===descriptor.family),...declaredPropsFor(source,descriptor.id)];if(additions.length===0)return descriptor;let props=[...descriptor.props];for(let addition of additions){let index=props.findIndex((prop)=>prop.name===addition.name);if(index>=0)props[index]={...props[index],...addition};else props.push(addition)}return{...descriptor,props,designModeNotes:appendNote(descriptor.designModeNotes,"Props include variants detected from the app's component source.")}})}function appendNote(current,next){return current?`${current} ${next}`:next}function variantPropsFor(source,primary){let out=[];if(!primary)return out;let variantsAt=source.indexOf("variants:");if(variantsAt<0)return out;let open=source.indexOf("{",variantsAt),block=balancedBlock(source,open);if(!block)return out;for(let[name,value]of objectEntries(block.slice(1,-1))){let values=objectEntries(value.slice(1,-1)).map(([key])=>key);if(values.length===0)continue;out.push({name,type:`${values.map((value)=>JSON.stringify(value)).join(" | ")} | undefined`,optional:!0,control:"enum",enumValues:values,...defaultVariant(source,name)?{defaultValue:defaultVariant(source,name)}:{}})}return out}function defaultVariant(source,name){let at=source.indexOf("defaultVariants:");if(at<0)return;let open=source.indexOf("{",at),block=balancedBlock(source,open);if(!block)return;return objectEntries(block.slice(1,-1)).find(([key])=>key===name)?.[1].replace(/["'`\s]/g,"")}function declaredPropsFor(source,componentId){let match=[new RegExp(`interface\\s+${componentId}Props(?:\\s+extends[^\\{]+)?\\s*\\{`,"m"),new RegExp(`type\\s+${componentId}Props\\s*=.*?&\\s*\\{`,"m")].map((pattern)=>pattern.exec(source)).find(Boolean);if(!match||match.index===void 0)return[];let open=source.indexOf("{",match.index),block=balancedBlock(source,open);if(!block)return[];let out=[],property=/(?:^|[;{\n])\s*([A-Za-z_$][\w$]*)(\?)?\s*:\s*([^;\n}]+)/gm;for(let found of block.slice(1,-1).matchAll(property)){let name=found[1],raw=found[3]?.trim();if(!name||!raw||name==="children")continue;let enumValues=[...raw.matchAll(/["']([^"']+)["']/g)].map((value)=>value[1]),optional=found[2]==="?"||raw.includes("undefined");out.push({name,type:optional&&!raw.includes("undefined")?`${raw} | undefined`:raw,optional,control:enumValues.length>0?"enum":/boolean/.test(raw)?"boolean":/number/.test(raw)?"number":"string",...enumValues.length>0?{enumValues}:{}})}return out}function balancedBlock(source,open){if(open<0||source[open]!=="{")return null;let depth=0,quote="";for(let index=open;index<source.length;index++){let char=source[index],prev=source[index-1];if(quote){if(char===quote&&prev!=="\\")quote="";continue}if(char==='"'||char==="'"||char==="`"){quote=char;continue}if(char==="{")depth++;if(char==="}"&&--depth===0)return source.slice(open,index+1)}return null}function objectEntries(body){let out=[],index=0;while(index<body.length){while(index<body.length&&/[\s,]/.test(body[index]))index++;let keyMatch=/^(?:["']([^"']+)["']|([A-Za-z_$][\w$-]*))\s*:/.exec(body.slice(index));if(!keyMatch)break;let key=keyMatch[1]??keyMatch[2];if(!key)break;index+=keyMatch[0].length;while(/\s/.test(body[index]??""))index++;if(body[index]==="{"){let block=balancedBlock(body,index);if(!block)break;out.push([key,block]),index+=block.length;continue}let end=valueEnd(body,index);out.push([key,body.slice(index,end).trim()]),index=end+1}return out}function valueEnd(body,start){let quote="",depth=0;for(let index=start;index<body.length;index++){let char=body[index];if(quote){if(char===quote&&body[index-1]!=="\\")quote=""}else if(char==='"'||char==="'"||char==="`")quote=char;else if("([{".includes(char))depth++;else if(")]}".includes(char))depth--;else if(char===","&&depth===0)return index}return body.length}function createProvider(opts={}){let cacheDir=opts.cacheDir,plannedUiDir=cacheDir?join5(cacheDir,"ui"):void 0,hostUiDir=()=>plannedUiDir&&existsSync4(plannedUiDir)?plannedUiDir:opts.hostAppRoot?findUiDir(opts.hostAppRoot):null,componentsDir=componentsDir3,version=opts.version??snapshotVersion2,hostAppRoot=opts.hostAppRoot,loadManifest=async()=>{if(cacheDir&&existsSync4(join5(cacheDir,"manifest.json")))return enrichManifestFromHost(await readManifest(cacheDir),hostUiDir());let{loadManifest:snapshotManifest}=await import("./chunk-emv1j50t.js");return enrichManifestFromHost(await snapshotManifest(),hostUiDir())};return{id:"shadcn-upstream",version,componentsDir,styleEntryPath:entryCssPath3,registry:registry2,loadManifest,label:`shadcn (upstream @ ${version})`,styleChannel:TAILWIND_CLASSNAME,styleChannels:["tailwind-classname"],mcpIntro:()=>['**This folder targets shadcn/ui with Tailwind.** The canvas imports client-safe components directly from the app\'s `components/ui`, adapts overlay families to stay inline, and falls back per component when a file is missing \u2014 `component_status` says which, before you claim fidelity. Style with a className string: `update_props { style: "flex gap-4 p-6" }`.',""],catalog:async()=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),shadcn=manifest.filter((c)=>c.source!=="velloo"),present=hostAppRoot?installedAddNames(hostAppRoot):new Set;return shadcn.map((c)=>{let addName=addNameOf(c.id);return{id:c.id,installed:present.has(addName),importPath:`@/components/ui/${addName}`}})},ownedModules:{dirs:()=>{let uiDir=hostUiDir();return uiDir?[uiDir]:[]}},canvasBundleSpec:{styleRuntime:{kind:"none"},components:async(ids)=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),sourceById=new Map(manifest.map((entry)=>[entry.id,entry.source])),uiDir=hostUiDir();return ids.flatMap((id)=>{if(sourceById.get(id)==="velloo"){let path=helperSourcePath(id);return path?[{id,sources:[{importPath:path,exportName:id,fidelity:"fallback",note:"Velloo helper used alongside repo-backed shadcn components."}]}]:[]}if(!sourceById.has(id))return[];let addName=addNameOf(id),snapshotPath=join5(componentsDir3,"ui",`${addName}.tsx`);if(CANVAS_ADAPTED_FAMILIES.has(addName))return[{id,sources:[{importPath:snapshotPath,exportName:id,fidelity:"adapted",note:"The app component uses portals or runtime state; Velloo renders its canvas-safe counterpart inline."}]}];let hostPath=uiDir?hostComponentFile(uiDir,addName,id):null;return[{id,sources:[...hostPath?[{importPath:hostPath,exportName:id,fidelity:"exact",preflight:!0,note:"Rendered directly from the app's shadcn source file."}]:[],{importPath:snapshotPath,exportName:id,fidelity:"fallback",note:hostPath?"The app source did not compile for the browser canvas; using the bundled canvas fallback.":"The app does not install this component under this name (it may be renamed in its own file); using the bundled canvas fallback."}]}]})},sourceDirs:()=>{let uiDir=hostUiDir()??plannedUiDir;return uiDir?[uiDir]:[]}}}}var CANVAS_ADAPTED_FAMILIES=new Set(["alert-dialog","calendar","carousel","chart","dialog","dropdown-menu","popover","select","sheet","sonner","tooltip"]);export{createProvider};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{AuthConfigResponseSchema,AccountResponseSchema,DeviceCodeResponseSchema,DeviceTokenResponseSchema,CliTokenResponseSchema,readFailure}from"./chunk-afe25dpr.js";import{string,object,record,literal}from"./chunk-4pkw6d9n.js";import{openUrl}from"./chunk-hggap8fq.js";import{isSecureCloudUrl,assertSecureCloudUrl}from"./chunk-edgwx026.js";import{chmod,mkdir,readFile,writeFile}from"fs/promises";import{homedir}from"os";import{dirname,join}from"path";var CloudCredentialSchema=object({token:string().min(1),email:string().min(1)}),CredentialsFileSchema=object({version:literal(1),clouds:record(string(),CloudCredentialSchema)}),credentialsPath=()=>process.env.VELLOO_CREDENTIALS_PATH??join(homedir(),".velloo","credentials.json"),normalizeCloudUrl=(url)=>url.replace(/\/+$/,"");async function readAll(){try{let parsed=CredentialsFileSchema.safeParse(JSON.parse(await readFile(credentialsPath(),"utf8")));if(parsed.success)return parsed.data}catch{}return{version:1,clouds:{}}}async function loadCredential(cloudUrl){return(await readAll()).clouds[normalizeCloudUrl(cloudUrl)]??null}async function listCredentials(){return(await readAll()).clouds}async function saveCredential(cloudUrl,cred){let all=await readAll();return all.clouds[normalizeCloudUrl(cloudUrl)]=cred,writeAll(all)}async function deleteCredential(cloudUrl){let all=await readAll(),key=normalizeCloudUrl(cloudUrl);if(!(key in all.clouds))return!1;return delete all.clouds[key],await writeAll(all),!0}async function clearCredentials(){let all=await readAll(),count=Object.keys(all.clouds).length;if(count===0)return 0;return await writeAll({version:1,clouds:{}}),count}async function writeAll(all){let path=credentialsPath();return await mkdir(dirname(path),{recursive:!0,mode:448}),await writeFile(path,`${JSON.stringify(all,null,2)}
|
|
3
|
+
`,{mode:384}),await chmod(path,384),path}import{hostname}from"os";async function fetchAccount(cloudUrl,token,timeoutMs=8000){if(!isSecureCloudUrl(cloudUrl))return{status:"unreachable"};let res=await fetch(`${cloudUrl}/v1/me`,{headers:{authorization:`Bearer ${token}`},signal:AbortSignal.timeout(timeoutMs)}).catch(()=>null);if(!res)return{status:"unreachable"};if(res.status===401||res.status===403)return{status:"rejected"};if(!res.ok)return{status:"unreachable"};let parsed=AccountResponseSchema.safeParse(await res.json().catch(()=>null));if(!parsed.success)return{status:"unreachable"};let body=parsed.data;return{status:"ok",account:{email:body.email,...body.name?{name:body.name}:{},...body.tier?{tier:body.tier}:{},...body.accountId?{accountId:body.accountId}:{},...body.creditMicros!==void 0?{creditMicros:body.creditMicros}:{}}}}async function verifyCredential(cloudUrl,token,timeoutMs=8000){let found=await fetchAccount(cloudUrl,token,timeoutMs);return found.status==="ok"?found.account.email:null}async function revokeCredential(cloudUrl,token,timeoutMs=5000){if(!isSecureCloudUrl(cloudUrl))return!1;return(await fetch(`${cloudUrl}/v1/auth/cli-token`,{method:"DELETE",headers:{authorization:`Bearer ${token}`},signal:AbortSignal.timeout(timeoutMs)}).catch(()=>null))?.ok??!1}var sleepCancelable=(ms,signal)=>new Promise((resolve,reject)=>{if(signal.aborted){reject(Error("cancelled"));return}let timer=setTimeout(resolve,ms);signal.addEventListener("abort",()=>{clearTimeout(timer),reject(Error("cancelled"))},{once:!0})});async function performDeviceLogin(cloudUrl,onPrompt,signal){assertSecureCloudUrl(cloudUrl);let configRes=await fetch(`${cloudUrl}/v1/auth/config`).catch(()=>null);if(!configRes?.ok)throw Error(`cannot reach ${cloudUrl} \u2014 is velloo-cloud up?`);let config=AuthConfigResponseSchema.safeParse(await configRes.json().catch(()=>null)),issuer=config.success?config.data.issuer:void 0,clientId=config.success?config.data.clientId:void 0;if(issuer===void 0||clientId===void 0)throw Error(`${cloudUrl} does not advertise a sign-in service \u2014 is velloo-cloud current?`);let codeRes=await fetch(`${issuer}/api/auth/device/code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:clientId})}).catch(()=>null);if(!codeRes?.ok)throw Error(`the auth service at ${issuer} is not answering \u2014 is it up?`);let deviceBody=DeviceCodeResponseSchema.safeParse(await codeRes.json().catch(()=>null));if(!deviceBody.success)throw Error(`the auth service at ${issuer} answered something this velloo can't read`);let device=deviceBody.data;await onPrompt({verificationUrl:device.verification_uri_complete,userCode:device.user_code,expiresIn:device.expires_in}),openUrl(device.verification_uri_complete);let deadline=Date.now()+device.expires_in*1000,intervalMs=Math.max(1,device.interval)*1000,accessToken=null,abortSignal=signal??new AbortController().signal;while(Date.now()<deadline){await sleepCancelable(intervalMs,abortSignal);let res=await fetch(`${issuer}/api/auth/device/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:device.device_code,client_id:clientId}),signal:abortSignal}),polled=DeviceTokenResponseSchema.safeParse(await res.json().catch(()=>({}))),body=polled.success?polled.data:{};if(body.access_token){accessToken=body.access_token;break}if(body.error==="authorization_pending")continue;if(body.error==="slow_down"){intervalMs+=5000;continue}throw Error(body.error_description??body.error??"device authorization failed")}if(!accessToken)throw Error("the sign-in code expired \u2014 run velloo login again");let label=hostname().trim().slice(0,80),exchangeRes=await fetch(`${cloudUrl}/v1/auth/cli-token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({accessToken,...label?{label}:{}})});if(exchangeRes.status!==201){let{detail}=await readFailure(exchangeRes);throw Error(`token exchange failed (${exchangeRes.status}): ${detail}`)}let exchanged=CliTokenResponseSchema.safeParse(await exchangeRes.json().catch(()=>null));if(!exchanged.success)throw Error(`${cloudUrl} returned a sign-in token this velloo can't read`);return exchanged.data}
|
|
4
|
+
export{normalizeCloudUrl,loadCredential,listCredentials,saveCredential,deleteCredential,clearCredentials,fetchAccount,verifyCredential,revokeCredential,performDeviceLogin};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{require_react_development}from"./chunk-
|
|
2
|
+
import{require_react_development}from"./chunk-ngbqd7kb.js";import{__toESM,__commonJS,__require}from"./chunk-2smsg2ct.js";var require_emotion_sheet_development_cjs=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:!0});var isDevelopment=!0;function sheetForTag(tag){if(tag.sheet)return tag.sheet;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].ownerNode===tag)return document.styleSheets[i];return}function createStyleElement(options){var tag=document.createElement("style");if(tag.setAttribute("data-emotion",options.key),options.nonce!==void 0)tag.setAttribute("nonce",options.nonce);return tag.appendChild(document.createTextNode("")),tag.setAttribute("data-s",""),tag}var StyleSheet=function(){function StyleSheet(options){var _this=this;this._insertTag=function(tag){var before;if(_this.tags.length===0)if(_this.insertionPoint)before=_this.insertionPoint.nextSibling;else if(_this.prepend)before=_this.container.firstChild;else before=_this.before;else before=_this.tags[_this.tags.length-1].nextSibling;_this.container.insertBefore(tag,before),_this.tags.push(tag)},this.isSpeedy=options.speedy===void 0?!isDevelopment:options.speedy,this.tags=[],this.ctr=0,this.nonce=options.nonce,this.key=options.key,this.container=options.container,this.prepend=options.prepend,this.insertionPoint=options.insertionPoint,this.before=null}var _proto=StyleSheet.prototype;return _proto.hydrate=function(nodes){nodes.forEach(this._insertTag)},_proto.insert=function(rule){if(this.ctr%(this.isSpeedy?65000:1)===0)this._insertTag(createStyleElement(this));var tag=this.tags[this.tags.length-1];{var isImportRule=rule.charCodeAt(0)===64&&rule.charCodeAt(1)===105;if(isImportRule&&this._alreadyInsertedOrderInsensitiveRule)console.error(`You're attempting to insert the following rule:
|
|
3
3
|
`+rule+"\n\n`@import` rules must be before all other types of rules in a stylesheet but other rules have already been inserted. Please ensure that `@import` rules are before all other rules.");this._alreadyInsertedOrderInsensitiveRule=this._alreadyInsertedOrderInsensitiveRule||!isImportRule}if(this.isSpeedy){var sheet=sheetForTag(tag);try{sheet.insertRule(rule,sheet.cssRules.length)}catch(e){if(!/:(-moz-placeholder|-moz-focus-inner|-moz-focusring|-ms-input-placeholder|-moz-read-write|-moz-read-only|-ms-clear|-ms-expand|-ms-reveal){/.test(rule))console.error('There was a problem inserting the following rule: "'+rule+'"',e)}}else tag.appendChild(document.createTextNode(rule));this.ctr++},_proto.flush=function(){this.tags.forEach(function(tag){var _tag$parentNode;return(_tag$parentNode=tag.parentNode)==null?void 0:_tag$parentNode.removeChild(tag)}),this.tags=[],this.ctr=0,this._alreadyInsertedOrderInsensitiveRule=!1},StyleSheet}();exports.StyleSheet=StyleSheet});var require_stylis=__commonJS(function(exports,module){(function(e,r){typeof exports==="object"&&typeof module<"u"?r(exports):typeof define==="function"&&define.amd?define(["exports"],r):(e=e||self,r(e.stylis={}))})(exports,function(e){var r="-ms-",a="-moz-",c="-webkit-",n="comm",t="rule",s="decl",i="@page",u="@media",o="@import",f="@charset",l="@viewport",p="@supports",h="@document",v="@namespace",d="@keyframes",b="@font-face",w="@counter-style",m="@font-feature-values",g="@layer",k=Math.abs,$=String.fromCharCode,x=Object.assign;function E(e,r){return M(e,0)^45?(((r<<2^M(e,0))<<2^M(e,1))<<2^M(e,2))<<2^M(e,3):0}function y(e){return e.trim()}function T(e,r){return(e=r.exec(e))?e[0]:e}function A(e,r,a){return e.replace(r,a)}function O(e,r){return e.indexOf(r)}function M(e,r){return e.charCodeAt(r)|0}function C(e,r,a){return e.slice(r,a)}function R(e){return e.length}function S(e){return e.length}function z(e,r){return r.push(e),e}function N(e,r){return e.map(r).join("")}e.line=1,e.column=1,e.length=0,e.position=0,e.character=0,e.characters="";function P(r,a,c,n,t,s,i){return{value:r,root:a,parent:c,type:n,props:t,children:s,line:e.line,column:e.column,length:i,return:""}}function j(e,r){return x(P("",null,null,"",null,null,0),e,{length:-e.length},r)}function U(){return e.character}function _(){if(e.character=e.position>0?M(e.characters,--e.position):0,e.column--,e.character===10)e.column=1,e.line--;return e.character}function F(){if(e.character=e.position<e.length?M(e.characters,e.position++):0,e.column++,e.character===10)e.column=1,e.line++;return e.character}function I(){return M(e.characters,e.position)}function L(){return e.position}function D(r,a){return C(e.characters,r,a)}function Y(e){switch(e){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function K(r){return e.line=e.column=1,e.length=R(e.characters=r),e.position=0,[]}function V(r){return e.characters="",r}function W(r){return y(D(e.position-1,q(r===91?r+2:r===40?r+1:r)))}function B(e){return V(H(K(e)))}function G(r){while(e.character=I())if(e.character<33)F();else break;return Y(r)>2||Y(e.character)>3?"":" "}function H(r){while(F())switch(Y(e.character)){case 0:z(Q(e.position-1),r);break;case 2:z(W(e.character),r);break;default:z($(e.character),r)}return r}function Z(r,a){while(--a&&F())if(e.character<48||e.character>102||e.character>57&&e.character<65||e.character>70&&e.character<97)break;return D(r,L()+(a<6&&I()==32&&F()==32))}function q(r){while(F())switch(e.character){case r:return e.position;case 34:case 39:if(r!==34&&r!==39)q(e.character);break;case 40:if(r===41)q(r);break;case 92:F();break}return e.position}function J(r,a){while(F())if(r+e.character===57)break;else if(r+e.character===84&&I()===47)break;return"/*"+D(a,e.position-1)+"*"+$(r===47?r:F())}function Q(r){while(!Y(I()))F();return D(r,e.position)}function X(e){return V(ee("",null,null,null,[""],e=K(e),0,[0],e))}function ee(e,r,a,c,n,t,s,i,u){var o=0,f=0,l=s,p=0,h=0,v=0,d=1,b=1,w=1,m=0,g="",k=n,x=t,E=c,y=g;while(b)switch(v=m,m=F()){case 40:if(v!=108&&M(y,l-1)==58){if(O(y+=A(W(m),"&","&\f"),"&\f")!=-1)w=-1;break}case 34:case 39:case 91:y+=W(m);break;case 9:case 10:case 13:case 32:y+=G(v);break;case 92:y+=Z(L()-1,7);continue;case 47:switch(I()){case 42:case 47:z(ae(J(F(),L()),r,a),u);break;default:y+="/"}break;case 123*d:i[o++]=R(y)*w;case 125*d:case 59:case 0:switch(m){case 0:case 125:b=0;case 59+f:if(w==-1)y=A(y,/\f/g,"");if(h>0&&R(y)-l)z(h>32?ce(y+";",c,a,l-1):ce(A(y," ","")+";",c,a,l-2),u);break;case 59:y+=";";default:if(z(E=re(y,r,a,o,f,n,i,g,k=[],x=[],l),t),m===123)if(f===0)ee(y,r,E,E,k,t,l,i,x);else switch(p===99&&M(y,3)===110?100:p){case 100:case 108:case 109:case 115:ee(e,E,E,c&&z(re(e,E,E,0,0,n,i,g,n,k=[],l),x),n,x,l,i,c?k:x);break;default:ee(y,E,E,E,[""],x,0,i,x)}}o=f=h=0,d=w=1,g=y="",l=s;break;case 58:l=1+R(y),h=v;default:if(d<1){if(m==123)--d;else if(m==125&&d++==0&&_()==125)continue}switch(y+=$(m),m*d){case 38:w=f>0?1:(y+="\f",-1);break;case 44:i[o++]=(R(y)-1)*w,w=1;break;case 64:if(I()===45)y+=W(F());p=I(),f=l=R(g=y+=Q(L())),m++;break;case 45:if(v===45&&R(y)==2)d=0}}return t}function re(e,r,a,c,n,s,i,u,o,f,l){var p=n-1,h=n===0?s:[""],v=S(h);for(var d=0,b=0,w=0;d<c;++d)for(var m=0,g=C(e,p+1,p=k(b=i[d])),$=e;m<v;++m)if($=y(b>0?h[m]+" "+g:A(g,/&\f/g,h[m])))o[w++]=$;return P(e,r,a,n===0?t:u,o,f,l)}function ae(e,r,a){return P(e,r,a,n,$(U()),C(e,2,-2),0)}function ce(e,r,a,c){return P(e,r,a,s,C(e,0,c),C(e,c+1,-1),c)}function ne(e,n,t){switch(E(e,n)){case 5103:return c+"print-"+e+e;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return c+e+e;case 4789:return a+e+e;case 5349:case 4246:case 4810:case 6968:case 2756:return c+e+a+e+r+e+e;case 5936:switch(M(e,n+11)){case 114:return c+e+r+A(e,/[svh]\w+-[tblr]{2}/,"tb")+e;case 108:return c+e+r+A(e,/[svh]\w+-[tblr]{2}/,"tb-rl")+e;case 45:return c+e+r+A(e,/[svh]\w+-[tblr]{2}/,"lr")+e}case 6828:case 4268:case 2903:return c+e+r+e+e;case 6165:return c+e+r+"flex-"+e+e;case 5187:return c+e+A(e,/(\w+).+(:[^]+)/,c+"box-$1$2"+r+"flex-$1$2")+e;case 5443:return c+e+r+"flex-item-"+A(e,/flex-|-self/g,"")+(!T(e,/flex-|baseline/)?r+"grid-row-"+A(e,/flex-|-self/g,""):"")+e;case 4675:return c+e+r+"flex-line-pack"+A(e,/align-content|flex-|-self/g,"")+e;case 5548:return c+e+r+A(e,"shrink","negative")+e;case 5292:return c+e+r+A(e,"basis","preferred-size")+e;case 6060:return c+"box-"+A(e,"-grow","")+c+e+r+A(e,"grow","positive")+e;case 4554:return c+A(e,/([^-])(transform)/g,"$1"+c+"$2")+e;case 6187:return A(A(A(e,/(zoom-|grab)/,c+"$1"),/(image-set)/,c+"$1"),e,"")+e;case 5495:case 3959:return A(e,/(image-set\([^]*)/,c+"$1$`$1");case 4968:return A(A(e,/(.+:)(flex-)?(.*)/,c+"box-pack:$3"+r+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+c+e+e;case 4200:if(!T(e,/flex-|baseline/))return r+"grid-column-align"+C(e,n)+e;break;case 2592:case 3360:return r+A(e,"template-","")+e;case 4384:case 3616:if(t&&t.some(function(e,r){return n=r,T(e.props,/grid-\w+-end/)}))return~O(e+(t=t[n].value),"span")?e:r+A(e,"-start","")+e+r+"grid-row-span:"+(~O(t,"span")?T(t,/\d+/):+T(t,/\d+/)-+T(e,/\d+/))+";";return r+A(e,"-start","")+e;case 4896:case 4128:return t&&t.some(function(e){return T(e.props,/grid-\w+-start/)})?e:r+A(A(e,"-end","-span"),"span ","")+e;case 4095:case 3583:case 4068:case 2532:return A(e,/(.+)-inline(.+)/,c+"$1$2")+e;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(R(e)-1-n>6)switch(M(e,n+1)){case 109:if(M(e,n+4)!==45)break;case 102:return A(e,/(.+:)(.+)-([^]+)/,"$1"+c+"$2-$3$1"+a+(M(e,n+3)==108?"$3":"$2-$3"))+e;case 115:return~O(e,"stretch")?ne(A(e,"stretch","fill-available"),n,t)+e:e}break;case 5152:case 5920:return A(e,/(.+?):(\d+)(\s*\/\s*(span)?\s*(\d+))?(.*)/,function(a,c,n,t,s,i,u){return r+c+":"+n+u+(t?r+c+"-span:"+(s?i:+i-+n)+u:"")+e});case 4949:if(M(e,n+6)===121)return A(e,":",":"+c)+e;break;case 6444:switch(M(e,M(e,14)===45?18:11)){case 120:return A(e,/(.+:)([^;\s!]+)(;|(\s+)?!.+)?/,"$1"+c+(M(e,14)===45?"inline-":"")+"box$3$1"+c+"$2$3$1"+r+"$2box$3")+e;case 100:return A(e,":",":"+r)+e}break;case 5719:case 2647:case 2135:case 3927:case 2391:return A(e,"scroll-","scroll-snap-")+e}return e}function te(e,r){var a="",c=S(e);for(var n=0;n<c;n++)a+=r(e[n],n,e,r)||"";return a}function se(e,r,a,c){switch(e.type){case g:if(e.children.length)break;case o:case s:return e.return=e.return||e.value;case n:return"";case d:return e.return=e.value+"{"+te(e.children,c)+"}";case t:e.value=e.props.join(",")}return R(a=te(e.children,c))?e.return=e.value+"{"+a+"}":""}function ie(e){var r=S(e);return function(a,c,n,t){var s="";for(var i=0;i<r;i++)s+=e[i](a,c,n,t)||"";return s}}function ue(e){return function(r){if(!r.root){if(r=r.return)e(r)}}}function oe(e,n,i,u){if(e.length>-1){if(!e.return)switch(e.type){case s:e.return=ne(e.value,e.length,i);return;case d:return te([j(e,{value:A(e.value,"@","@"+c)})],u);case t:if(e.length)return N(e.props,function(n){switch(T(n,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return te([j(e,{props:[A(n,/:(read-\w+)/,":"+a+"$1")]})],u);case"::placeholder":return te([j(e,{props:[A(n,/:(plac\w+)/,":"+c+"input-$1")]}),j(e,{props:[A(n,/:(plac\w+)/,":"+a+"$1")]}),j(e,{props:[A(n,/:(plac\w+)/,r+"input-$1")]})],u)}return""})}}}function fe(e){switch(e.type){case t:e.props=e.props.map(function(r){return N(B(r),function(r,a,c){switch(M(r,0)){case 12:return C(r,1,R(r));case 0:case 40:case 43:case 62:case 126:return r;case 58:if(c[++a]==="global")c[a]="",c[++a]="\f"+C(c[a],a=1,-1);case 32:return a===1?"":r;default:switch(a){case 0:return e=r,S(c)>1?"":r;case(a=S(c)-1):case 2:return a===2?r+e+e:r+e;default:return r}}})})}}e.CHARSET=f,e.COMMENT=n,e.COUNTER_STYLE=w,e.DECLARATION=s,e.DOCUMENT=h,e.FONT_FACE=b,e.FONT_FEATURE_VALUES=m,e.IMPORT=o,e.KEYFRAMES=d,e.LAYER=g,e.MEDIA=u,e.MOZ=a,e.MS=r,e.NAMESPACE=v,e.PAGE=i,e.RULESET=t,e.SUPPORTS=p,e.VIEWPORT=l,e.WEBKIT=c,e.abs=k,e.alloc=K,e.append=z,e.assign=x,e.caret=L,e.char=U,e.charat=M,e.combine=N,e.comment=ae,e.commenter=J,e.compile=X,e.copy=j,e.dealloc=V,e.declaration=ce,e.delimit=W,e.delimiter=q,e.escaping=Z,e.from=$,e.hash=E,e.identifier=Q,e.indexof=O,e.match=T,e.middleware=ie,e.namespace=fe,e.next=F,e.node=P,e.parse=ee,e.peek=I,e.prefix=ne,e.prefixer=oe,e.prev=_,e.replace=A,e.ruleset=re,e.rulesheet=ue,e.serialize=te,e.sizeof=S,e.slice=D,e.stringify=se,e.strlen=R,e.substr=C,e.token=Y,e.tokenize=B,e.tokenizer=H,e.trim=y,e.whitespace=G,Object.defineProperty(e,"__esModule",{value:!0})})});var require_emotion_weak_memoize_cjs_dev=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:!0});var weakMemoize=function(func){var cache=new WeakMap;return function(arg){if(cache.has(arg))return cache.get(arg);var ret=func(arg);return cache.set(arg,ret),ret}};exports.default=weakMemoize});var require_emotion_memoize_cjs_dev=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:!0});function memoize(fn){var cache=Object.create(null);return function(arg){if(cache[arg]===void 0)cache[arg]=fn(arg);return cache[arg]}}exports.default=memoize});var require_emotion_cache_development_cjs=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:!0});var sheet=require_emotion_sheet_development_cjs(),stylis=require_stylis(),weakMemoize=require_emotion_weak_memoize_cjs_dev(),memoize=require_emotion_memoize_cjs_dev();function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var weakMemoize__default=_interopDefault(weakMemoize),memoize__default=_interopDefault(memoize),isBrowser=typeof document<"u",identifierWithPointTracking=function(begin,points,index){var previous=0,character=0;while(!0){if(previous=character,character=stylis.peek(),previous===38&&character===12)points[index]=1;if(stylis.token(character))break;stylis.next()}return stylis.slice(begin,stylis.position)},toRules=function(parsed,points){var index=-1,character=44;do switch(stylis.token(character)){case 0:if(character===38&&stylis.peek()===12)points[index]=1;parsed[index]+=identifierWithPointTracking(stylis.position-1,points,index);break;case 2:parsed[index]+=stylis.delimit(character);break;case 4:if(character===44){parsed[++index]=stylis.peek()===58?"&\f":"",points[index]=parsed[index].length;break}default:parsed[index]+=stylis.from(character)}while(character=stylis.next());return parsed},getRules=function(value,points){return stylis.dealloc(toRules(stylis.alloc(value),points))},fixedElements=new WeakMap,compat=function(element){if(element.type!=="rule"||!element.parent||element.length<1)return;var{value,parent}=element,isImplicitRule=element.column===parent.column&&element.line===parent.line;while(parent.type!=="rule")if(parent=parent.parent,!parent)return;if(element.props.length===1&&value.charCodeAt(0)!==58&&!fixedElements.get(parent))return;if(isImplicitRule)return;fixedElements.set(element,!0);var points=[],rules=getRules(value,points),parentRules=parent.props;for(var i=0,k=0;i<rules.length;i++)for(var j=0;j<parentRules.length;j++,k++)element.props[k]=points[i]?rules[i].replace(/&\f/g,parentRules[j]):parentRules[j]+" "+rules[i]},removeLabel=function(element){if(element.type==="decl"){var value=element.value;if(value.charCodeAt(0)===108&&value.charCodeAt(2)===98)element.return="",element.value=""}},ignoreFlag="emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason",isIgnoringComment=function(element){return element.type==="comm"&&element.children.indexOf(ignoreFlag)>-1},createUnsafeSelectorsAlarm=function(cache){return function(element,index,children){if(element.type!=="rule"||cache.compat)return;var unsafePseudoClasses=element.value.match(/(:first|:nth|:nth-last)-child/g);if(unsafePseudoClasses){var isNested=!!element.parent,commentContainer=isNested?element.parent.children:children;for(var i=commentContainer.length-1;i>=0;i--){var node=commentContainer[i];if(node.line<element.line)break;if(node.column<element.column){if(isIgnoringComment(node))return;break}}unsafePseudoClasses.forEach(function(unsafePseudoClass){console.error('The pseudo class "'+unsafePseudoClass+'" is potentially unsafe when doing server-side rendering. Try changing it to "'+unsafePseudoClass.split("-child")[0]+'-of-type".')})}}},isImportRule=function(element){return element.type.charCodeAt(1)===105&&element.type.charCodeAt(0)===64},isPrependedWithRegularRules=function(index,children){for(var i=index-1;i>=0;i--)if(!isImportRule(children[i]))return!0;return!1},nullifyElement=function(element){element.type="",element.value="",element.return="",element.children="",element.props=""},incorrectImportAlarm=function(element,index,children){if(!isImportRule(element))return;if(element.parent)console.error("`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles."),nullifyElement(element);else if(isPrependedWithRegularRules(index,children))console.error("`@import` rules can't be after other rules. Please put your `@import` rules before your other rules."),nullifyElement(element)};function prefix(value,length){switch(stylis.hash(value,length)){case 5103:return stylis.WEBKIT+"print-"+value+value;case 5737:case 4201:case 3177:case 3433:case 1641:case 4457:case 2921:case 5572:case 6356:case 5844:case 3191:case 6645:case 3005:case 6391:case 5879:case 5623:case 6135:case 4599:case 4855:case 4215:case 6389:case 5109:case 5365:case 5621:case 3829:return stylis.WEBKIT+value+value;case 5349:case 4246:case 4810:case 6968:case 2756:return stylis.WEBKIT+value+stylis.MOZ+value+stylis.MS+value+value;case 6828:case 4268:return stylis.WEBKIT+value+stylis.MS+value+value;case 6165:return stylis.WEBKIT+value+stylis.MS+"flex-"+value+value;case 5187:return stylis.WEBKIT+value+stylis.replace(value,/(\w+).+(:[^]+)/,stylis.WEBKIT+"box-$1$2"+stylis.MS+"flex-$1$2")+value;case 5443:return stylis.WEBKIT+value+stylis.MS+"flex-item-"+stylis.replace(value,/flex-|-self/,"")+value;case 4675:return stylis.WEBKIT+value+stylis.MS+"flex-line-pack"+stylis.replace(value,/align-content|flex-|-self/,"")+value;case 5548:return stylis.WEBKIT+value+stylis.MS+stylis.replace(value,"shrink","negative")+value;case 5292:return stylis.WEBKIT+value+stylis.MS+stylis.replace(value,"basis","preferred-size")+value;case 6060:return stylis.WEBKIT+"box-"+stylis.replace(value,"-grow","")+stylis.WEBKIT+value+stylis.MS+stylis.replace(value,"grow","positive")+value;case 4554:return stylis.WEBKIT+stylis.replace(value,/([^-])(transform)/g,"$1"+stylis.WEBKIT+"$2")+value;case 6187:return stylis.replace(stylis.replace(stylis.replace(value,/(zoom-|grab)/,stylis.WEBKIT+"$1"),/(image-set)/,stylis.WEBKIT+"$1"),value,"")+value;case 5495:case 3959:return stylis.replace(value,/(image-set\([^]*)/,stylis.WEBKIT+"$1$`$1");case 4968:return stylis.replace(stylis.replace(value,/(.+:)(flex-)?(.*)/,stylis.WEBKIT+"box-pack:$3"+stylis.MS+"flex-pack:$3"),/s.+-b[^;]+/,"justify")+stylis.WEBKIT+value+value;case 4095:case 3583:case 4068:case 2532:return stylis.replace(value,/(.+)-inline(.+)/,stylis.WEBKIT+"$1$2")+value;case 8116:case 7059:case 5753:case 5535:case 5445:case 5701:case 4933:case 4677:case 5533:case 5789:case 5021:case 4765:if(stylis.strlen(value)-1-length>6)switch(stylis.charat(value,length+1)){case 109:if(stylis.charat(value,length+4)!==45)break;case 102:return stylis.replace(value,/(.+:)(.+)-([^]+)/,"$1"+stylis.WEBKIT+"$2-$3$1"+stylis.MOZ+(stylis.charat(value,length+3)==108?"$3":"$2-$3"))+value;case 115:return~stylis.indexof(value,"stretch")?prefix(stylis.replace(value,"stretch","fill-available"),length)+value:value}break;case 4949:if(stylis.charat(value,length+1)!==115)break;case 6444:switch(stylis.charat(value,stylis.strlen(value)-3-(~stylis.indexof(value,"!important")&&10))){case 107:return stylis.replace(value,":",":"+stylis.WEBKIT)+value;case 101:return stylis.replace(value,/(.+:)([^;!]+)(;|!.+)?/,"$1"+stylis.WEBKIT+(stylis.charat(value,14)===45?"inline-":"")+"box$3$1"+stylis.WEBKIT+"$2$3$1"+stylis.MS+"$2box$3")+value}break;case 5936:switch(stylis.charat(value,length+11)){case 114:return stylis.WEBKIT+value+stylis.MS+stylis.replace(value,/[svh]\w+-[tblr]{2}/,"tb")+value;case 108:return stylis.WEBKIT+value+stylis.MS+stylis.replace(value,/[svh]\w+-[tblr]{2}/,"tb-rl")+value;case 45:return stylis.WEBKIT+value+stylis.MS+stylis.replace(value,/[svh]\w+-[tblr]{2}/,"lr")+value}return stylis.WEBKIT+value+stylis.MS+value+value}return value}var prefixer=function(element,index,children,callback){if(element.length>-1){if(!element.return)switch(element.type){case stylis.DECLARATION:element.return=prefix(element.value,element.length);break;case stylis.KEYFRAMES:return stylis.serialize([stylis.copy(element,{value:stylis.replace(element.value,"@","@"+stylis.WEBKIT)})],callback);case stylis.RULESET:if(element.length)return stylis.combine(element.props,function(value){switch(stylis.match(value,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return stylis.serialize([stylis.copy(element,{props:[stylis.replace(value,/:(read-\w+)/,":"+stylis.MOZ+"$1")]})],callback);case"::placeholder":return stylis.serialize([stylis.copy(element,{props:[stylis.replace(value,/:(plac\w+)/,":"+stylis.WEBKIT+"input-$1")]}),stylis.copy(element,{props:[stylis.replace(value,/:(plac\w+)/,":"+stylis.MOZ+"$1")]}),stylis.copy(element,{props:[stylis.replace(value,/:(plac\w+)/,stylis.MS+"input-$1")]})],callback)}return""})}}},getServerStylisCache=isBrowser?void 0:weakMemoize__default.default(function(){return memoize__default.default(function(){return{}})}),defaultStylisPlugins=[prefixer],getSourceMap;sourceMapPattern=/\/\*#\ssourceMappingURL=data:application\/json;\S+\s+\*\//g,getSourceMap=function(styles){var matches=styles.match(sourceMapPattern);if(!matches)return;return matches[matches.length-1]};var sourceMapPattern,createCache=function(options){var key=options.key;if(!key)throw Error(`You have to configure \`key\` for your cache. Please make sure it's unique (and not equal to 'css') as it's used for linking styles to your cache.
|
|
4
4
|
If multiple caches share the same key they might "fight" for each other's style elements.`);if(isBrowser&&key==="css"){var ssrStyles=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(ssrStyles,function(node){var dataEmotionAttribute=node.getAttribute("data-emotion");if(dataEmotionAttribute.indexOf(" ")===-1)return;document.head.appendChild(node),node.setAttribute("data-s","")})}var stylisPlugins=options.stylisPlugins||defaultStylisPlugins;if(/[^a-z-]/.test(key))throw Error('Emotion key must only contain lower case alphabetical characters and - but "'+key+'" was passed');var inserted={},container,nodesToHydrate=[];if(isBrowser)container=options.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+key+' "]'),function(node){var attrib=node.getAttribute("data-emotion").split(" ");for(var i=1;i<attrib.length;i++)inserted[attrib[i]]=!0;nodesToHydrate.push(node)});var _insert,omnipresentPlugins=[compat,removeLabel];if(omnipresentPlugins.push(createUnsafeSelectorsAlarm({get compat(){return cache.compat}}),incorrectImportAlarm),!getServerStylisCache){var currentSheet,finalizingPlugins=[stylis.stringify,function(element){if(!element.root){if(element.return)currentSheet.insert(element.return);else if(element.value&&element.type!==stylis.COMMENT)currentSheet.insert(element.value+"{}")}}],serializer=stylis.middleware(omnipresentPlugins.concat(stylisPlugins,finalizingPlugins)),stylis$1=function(styles){return stylis.serialize(stylis.compile(styles),serializer)};_insert=function(selector,serialized,sheet,shouldCache){if(currentSheet=sheet,getSourceMap){var sourceMap=getSourceMap(serialized.styles);if(sourceMap)currentSheet={insert:function(rule){sheet.insert(rule+sourceMap)}}}if(stylis$1(selector?selector+"{"+serialized.styles+"}":serialized.styles),shouldCache)cache.inserted[serialized.name]=!0}}else{var _finalizingPlugins=[stylis.stringify],_serializer=stylis.middleware(omnipresentPlugins.concat(stylisPlugins,_finalizingPlugins)),_stylis=function(styles){return stylis.serialize(stylis.compile(styles),_serializer)},serverStylisCache=getServerStylisCache(stylisPlugins)(key),getRules=function(selector,serialized){var name=serialized.name;if(serverStylisCache[name]===void 0)serverStylisCache[name]=_stylis(selector?selector+"{"+serialized.styles+"}":serialized.styles);return serverStylisCache[name]};_insert=function(selector,serialized,sheet,shouldCache){var name=serialized.name,rules=getRules(selector,serialized);if(cache.compat===void 0){if(shouldCache)cache.inserted[name]=!0;if(getSourceMap){var sourceMap=getSourceMap(serialized.styles);if(sourceMap)return rules+sourceMap}return rules}else if(shouldCache)cache.inserted[name]=rules;else return rules}}var cache={key,sheet:new sheet.StyleSheet({key,container,nonce:options.nonce,speedy:options.speedy,prepend:options.prepend,insertionPoint:options.insertionPoint}),nonce:options.nonce,inserted,registered:{},insert:_insert};return cache.sheet.hydrate(nodesToHydrate),cache};exports.default=createCache});var require_extends=__commonJS(function(exports,module){function _extends(){return module.exports=_extends=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(n[r]=t[r])}return n},module.exports.__esModule=!0,module.exports.default=module.exports,_extends.apply(null,arguments)}module.exports=_extends,module.exports.__esModule=!0,module.exports.default=module.exports});var require_react_is_development=__commonJS(function(exports){(function(){var hasSymbol=typeof Symbol==="function"&&Symbol.for,REACT_ELEMENT_TYPE=hasSymbol?Symbol.for("react.element"):60103,REACT_PORTAL_TYPE=hasSymbol?Symbol.for("react.portal"):60106,REACT_FRAGMENT_TYPE=hasSymbol?Symbol.for("react.fragment"):60107,REACT_STRICT_MODE_TYPE=hasSymbol?Symbol.for("react.strict_mode"):60108,REACT_PROFILER_TYPE=hasSymbol?Symbol.for("react.profiler"):60114,REACT_PROVIDER_TYPE=hasSymbol?Symbol.for("react.provider"):60109,REACT_CONTEXT_TYPE=hasSymbol?Symbol.for("react.context"):60110,REACT_ASYNC_MODE_TYPE=hasSymbol?Symbol.for("react.async_mode"):60111,REACT_CONCURRENT_MODE_TYPE=hasSymbol?Symbol.for("react.concurrent_mode"):60111,REACT_FORWARD_REF_TYPE=hasSymbol?Symbol.for("react.forward_ref"):60112,REACT_SUSPENSE_TYPE=hasSymbol?Symbol.for("react.suspense"):60113,REACT_SUSPENSE_LIST_TYPE=hasSymbol?Symbol.for("react.suspense_list"):60120,REACT_MEMO_TYPE=hasSymbol?Symbol.for("react.memo"):60115,REACT_LAZY_TYPE=hasSymbol?Symbol.for("react.lazy"):60116,REACT_BLOCK_TYPE=hasSymbol?Symbol.for("react.block"):60121,REACT_FUNDAMENTAL_TYPE=hasSymbol?Symbol.for("react.fundamental"):60117,REACT_RESPONDER_TYPE=hasSymbol?Symbol.for("react.responder"):60118,REACT_SCOPE_TYPE=hasSymbol?Symbol.for("react.scope"):60119;function isValidElementType(type){return typeof type==="string"||typeof type==="function"||type===REACT_FRAGMENT_TYPE||type===REACT_CONCURRENT_MODE_TYPE||type===REACT_PROFILER_TYPE||type===REACT_STRICT_MODE_TYPE||type===REACT_SUSPENSE_TYPE||type===REACT_SUSPENSE_LIST_TYPE||typeof type==="object"&&type!==null&&(type.$$typeof===REACT_LAZY_TYPE||type.$$typeof===REACT_MEMO_TYPE||type.$$typeof===REACT_PROVIDER_TYPE||type.$$typeof===REACT_CONTEXT_TYPE||type.$$typeof===REACT_FORWARD_REF_TYPE||type.$$typeof===REACT_FUNDAMENTAL_TYPE||type.$$typeof===REACT_RESPONDER_TYPE||type.$$typeof===REACT_SCOPE_TYPE||type.$$typeof===REACT_BLOCK_TYPE)}function typeOf(object){if(typeof object==="object"&&object!==null){var $$typeof=object.$$typeof;switch($$typeof){case REACT_ELEMENT_TYPE:var type=object.type;switch(type){case REACT_ASYNC_MODE_TYPE:case REACT_CONCURRENT_MODE_TYPE:case REACT_FRAGMENT_TYPE:case REACT_PROFILER_TYPE:case REACT_STRICT_MODE_TYPE:case REACT_SUSPENSE_TYPE:return type;default:var $$typeofType=type&&type.$$typeof;switch($$typeofType){case REACT_CONTEXT_TYPE:case REACT_FORWARD_REF_TYPE:case REACT_LAZY_TYPE:case REACT_MEMO_TYPE:case REACT_PROVIDER_TYPE:return $$typeofType;default:return $$typeof}}case REACT_PORTAL_TYPE:return $$typeof}}return}var AsyncMode=REACT_ASYNC_MODE_TYPE,ConcurrentMode=REACT_CONCURRENT_MODE_TYPE,ContextConsumer=REACT_CONTEXT_TYPE,ContextProvider=REACT_PROVIDER_TYPE,Element=REACT_ELEMENT_TYPE,ForwardRef=REACT_FORWARD_REF_TYPE,Fragment=REACT_FRAGMENT_TYPE,Lazy=REACT_LAZY_TYPE,Memo=REACT_MEMO_TYPE,Portal=REACT_PORTAL_TYPE,Profiler=REACT_PROFILER_TYPE,StrictMode=REACT_STRICT_MODE_TYPE,Suspense=REACT_SUSPENSE_TYPE,hasWarnedAboutDeprecatedIsAsyncMode=!1;function isAsyncMode(object){if(!hasWarnedAboutDeprecatedIsAsyncMode)hasWarnedAboutDeprecatedIsAsyncMode=!0,console.warn("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.");return isConcurrentMode(object)||typeOf(object)===REACT_ASYNC_MODE_TYPE}function isConcurrentMode(object){return typeOf(object)===REACT_CONCURRENT_MODE_TYPE}function isContextConsumer(object){return typeOf(object)===REACT_CONTEXT_TYPE}function isContextProvider(object){return typeOf(object)===REACT_PROVIDER_TYPE}function isElement(object){return typeof object==="object"&&object!==null&&object.$$typeof===REACT_ELEMENT_TYPE}function isForwardRef(object){return typeOf(object)===REACT_FORWARD_REF_TYPE}function isFragment(object){return typeOf(object)===REACT_FRAGMENT_TYPE}function isLazy(object){return typeOf(object)===REACT_LAZY_TYPE}function isMemo(object){return typeOf(object)===REACT_MEMO_TYPE}function isPortal(object){return typeOf(object)===REACT_PORTAL_TYPE}function isProfiler(object){return typeOf(object)===REACT_PROFILER_TYPE}function isStrictMode(object){return typeOf(object)===REACT_STRICT_MODE_TYPE}function isSuspense(object){return typeOf(object)===REACT_SUSPENSE_TYPE}exports.AsyncMode=AsyncMode,exports.ConcurrentMode=ConcurrentMode,exports.ContextConsumer=ContextConsumer,exports.ContextProvider=ContextProvider,exports.Element=Element,exports.ForwardRef=ForwardRef,exports.Fragment=Fragment,exports.Lazy=Lazy,exports.Memo=Memo,exports.Portal=Portal,exports.Profiler=Profiler,exports.StrictMode=StrictMode,exports.Suspense=Suspense,exports.isAsyncMode=isAsyncMode,exports.isConcurrentMode=isConcurrentMode,exports.isContextConsumer=isContextConsumer,exports.isContextProvider=isContextProvider,exports.isElement=isElement,exports.isForwardRef=isForwardRef,exports.isFragment=isFragment,exports.isLazy=isLazy,exports.isMemo=isMemo,exports.isPortal=isPortal,exports.isProfiler=isProfiler,exports.isStrictMode=isStrictMode,exports.isSuspense=isSuspense,exports.isValidElementType=isValidElementType,exports.typeOf=typeOf})()});var require_hoist_non_react_statics_cjs=__commonJS(function(exports,module){var reactIs=__toESM(require_react_is_development()),REACT_STATICS={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},KNOWN_STATICS={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},FORWARD_REF_STATICS={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},MEMO_STATICS={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},TYPE_STATICS={};TYPE_STATICS[reactIs.ForwardRef]=FORWARD_REF_STATICS;TYPE_STATICS[reactIs.Memo]=MEMO_STATICS;function getStatics(component){if(reactIs.isMemo(component))return MEMO_STATICS;return TYPE_STATICS[component.$$typeof]||REACT_STATICS}var{defineProperty,getOwnPropertyNames,getOwnPropertySymbols,getOwnPropertyDescriptor,getPrototypeOf,prototype:objectPrototype}=Object;function hoistNonReactStatics(targetComponent,sourceComponent,blacklist){if(typeof sourceComponent!=="string"){if(objectPrototype){var inheritedComponent=getPrototypeOf(sourceComponent);if(inheritedComponent&&inheritedComponent!==objectPrototype)hoistNonReactStatics(targetComponent,inheritedComponent,blacklist)}var keys=getOwnPropertyNames(sourceComponent);if(getOwnPropertySymbols)keys=keys.concat(getOwnPropertySymbols(sourceComponent));var targetStatics=getStatics(targetComponent),sourceStatics=getStatics(sourceComponent);for(var i=0;i<keys.length;++i){var key=keys[i];if(!KNOWN_STATICS[key]&&!(blacklist&&blacklist[key])&&!(sourceStatics&&sourceStatics[key])&&!(targetStatics&&targetStatics[key])){var descriptor=getOwnPropertyDescriptor(sourceComponent,key);try{defineProperty(targetComponent,key,descriptor)}catch(e){}}}}return targetComponent}module.exports=hoistNonReactStatics});var require_emotion_react__isolated_hnrs_development_cjs=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:!0});var hoistNonReactStatics$1=require_hoist_non_react_statics_cjs();function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var hoistNonReactStatics__default=_interopDefault(hoistNonReactStatics$1),hoistNonReactStatics=function(targetComponent,sourceComponent){return hoistNonReactStatics__default.default(targetComponent,sourceComponent)};exports.default=hoistNonReactStatics});var require_emotion_utils_cjs=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:!0});var isBrowser=typeof document<"u";function getRegisteredStyles(registered,registeredStyles,classNames){var rawClassName="";return classNames.split(" ").forEach(function(className){if(registered[className]!==void 0)registeredStyles.push(registered[className]+";");else if(className)rawClassName+=className+" "}),rawClassName}var registerStyles=function(cache,serialized,isStringTag){var className=cache.key+"-"+serialized.name;if((isStringTag===!1||isBrowser===!1&&cache.compat!==void 0)&&cache.registered[className]===void 0)cache.registered[className]=serialized.styles},insertStyles=function(cache,serialized,isStringTag){registerStyles(cache,serialized,isStringTag);var className=cache.key+"-"+serialized.name;if(cache.inserted[serialized.name]===void 0){var stylesForSSR="",current=serialized;do{var maybeStyles=cache.insert(serialized===current?"."+className:"",current,cache.sheet,!0);if(!isBrowser&&maybeStyles!==void 0)stylesForSSR+=maybeStyles;current=current.next}while(current!==void 0);if(!isBrowser&&stylesForSSR.length!==0)return stylesForSSR}};exports.getRegisteredStyles=getRegisteredStyles;exports.insertStyles=insertStyles;exports.registerStyles=registerStyles});var require_emotion_hash_cjs_dev=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:!0});function murmur2(str){var h=0,k,i=0,len=str.length;for(;len>=4;++i,len-=4)k=str.charCodeAt(i)&255|(str.charCodeAt(++i)&255)<<8|(str.charCodeAt(++i)&255)<<16|(str.charCodeAt(++i)&255)<<24,k=(k&65535)*1540483477+((k>>>16)*59797<<16),k^=k>>>24,h=(k&65535)*1540483477+((k>>>16)*59797<<16)^(h&65535)*1540483477+((h>>>16)*59797<<16);switch(len){case 3:h^=(str.charCodeAt(i+2)&255)<<16;case 2:h^=(str.charCodeAt(i+1)&255)<<8;case 1:h^=str.charCodeAt(i)&255,h=(h&65535)*1540483477+((h>>>16)*59797<<16)}return h^=h>>>13,h=(h&65535)*1540483477+((h>>>16)*59797<<16),((h^h>>>15)>>>0).toString(36)}exports.default=murmur2});var require_emotion_unitless_cjs=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:!0});var unitlessKeys={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,scale:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1};exports.default=unitlessKeys});var require_emotion_serialize_development_cjs=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:!0});var hashString=require_emotion_hash_cjs_dev(),unitless=require_emotion_unitless_cjs(),memoize=require_emotion_memoize_cjs_dev();function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var hashString__default=_interopDefault(hashString),unitless__default=_interopDefault(unitless),memoize__default=_interopDefault(memoize),isDevelopment=!0,ILLEGAL_ESCAPE_SEQUENCE_ERROR=`You have illegal escape sequence in your template literal, most likely inside content's property value.
|
|
5
5
|
Because you write your CSS inside a JavaScript string you actually have to do double escaping, so for example "content: '\\00d7';" should become "content: '\\\\00d7';".
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isCancel,confirm,password,select}from"./chunk-80fjfyha.js";import{protectedSharesAllowed,PROTECTED_SHARES_UNAVAILABLE,teamOnlyAllowed,describeCloudError}from"./chunk-
|
|
2
|
+
import{isCancel,confirm,password,select}from"./chunk-80fjfyha.js";import{protectedSharesAllowed,PROTECTED_SHARES_UNAVAILABLE,teamOnlyAllowed,describeCloudError}from"./chunk-afe25dpr.js";import"./chunk-4pkw6d9n.js";import{closePooledBrowser}from"./chunk-ngbqd7kb.js";import{loadDesignFolder,screensForBoards,resolveProviders,findHostTailwindConfig,TailwindJit,extraThemeBlock}from"./chunk-66qgm91k.js";import{loadCredential,fetchAccount}from"./chunk-wkqrb2tz.js";import{fail}from"./chunk-s23gtejf.js";import{confirmRenderFailures}from"./chunk-j7tzbt3d.js";import{publishedDesignSubtitle,listPublishedDesigns,unpublishDesign,listPublishDestinations,designGitEnv,teamChoiceRequired,describePublishError,recommendedPublishSlot,exactPublishSlots,gitContext,resolvePublishTeam,listTeams,publishDesign,createPublishBundler}from"./chunk-49w26e94.js";import"./chunk-vgx47anc.js";import{createProgress}from"./chunk-pjtg3wnm.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign,pickBoards}from"./chunk-675tr675.js";import{defaultCloudUrl,publishedBoardsUrl,billingPageUrl,checkCloudHealth}from"./chunk-edgwx026.js";import{withSubcommands}from"./chunk-94vx1yb0.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{join as join2}from"path";import{execFileSync}from"child_process";import{realpathSync}from"fs";import{join,relative,resolve,sep}from"path";function plainJsonStem(path,dir){let prefix=`${dir}/`;if(!path.startsWith(prefix)||!path.endsWith(".json"))return null;let stem=path.slice(prefix.length,-5);if(stem.includes("/")||stem.includes("."))return null;return stem}function classifyChanges(changes){let set={screens:new Map,global:!1,snippets:new Set,assets:new Set};for(let{status,path}of changes){let screen=plainJsonStem(path,"screens");if(screen){set.screens.set(screen,status);continue}if(path.startsWith("theme/")||path===".design/config.json"){set.global=!0;continue}let snippet=plainJsonStem(path,"snippets");if(snippet){set.snippets.add(snippet);continue}if(path.startsWith("assets/"))set.assets.add(`/${path}`)}return set}function snippetIdsIn(value,acc){if(Array.isArray(value)){for(let v of value)snippetIdsIn(v,acc);return}if(value!==null&&typeof value==="object"){let id=value.$snippet;if(typeof id==="string")acc.add(id);for(let v of Object.values(value))snippetIdsIn(v,acc)}}function snippetsUsedByScreen(screen,snippets){let used=new Set;snippetIdsIn(screen.tree,used);let grew=!0;while(grew){grew=!1;for(let id of[...used]){let body=snippets.get(id);if(!body)continue;let inner=new Set;snippetIdsIn(body,inner);for(let innerId of inner)if(!used.has(innerId))used.add(innerId),grew=!0}}return used}function detectChangedScreens(changes,afterScreens,afterSnippets){let out=new Map;for(let[id,status]of changes.screens)out.set(id,{id,status:status==="A"?"added":status==="D"?"deleted":"modified",reasons:["screen"]});let markModified=(id,reason)=>{let existing=out.get(id);if(existing){if(!existing.reasons.includes(reason))existing.reasons.push(reason);return}out.set(id,{id,status:"modified",reasons:[reason]})};if(changes.global||changes.snippets.size>0||changes.assets.size>0)for(let[id,screen]of afterScreens){if(changes.global)markModified(id,"theme");if(changes.snippets.size===0&&changes.assets.size===0)continue;let used=snippetsUsedByScreen(screen,afterSnippets);for(let snippetId of changes.snippets)if(used.has(snippetId))markModified(id,`snippet:${snippetId}`);if(changes.assets.size>0){let haystack=JSON.stringify(screen);for(let snippetId of used){let body=afterSnippets.get(snippetId);if(body)haystack+=JSON.stringify(body)}for(let asset of changes.assets)if(haystack.includes(asset))markModified(id,`asset:${asset}`)}}return[...out.values()].sort((a,b)=>a.id.localeCompare(b.id))}function git(repo,args){return execFileSync("git",["-C",repo,...args],{encoding:"utf8",maxBuffer:67108864,stdio:["ignore","pipe","pipe"]})}function resolveGitContext(designFolder,base,head){let repoRoot;try{repoRoot=execFileSync("git",["-C",designFolder,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],env:designGitEnv(designFolder)}).trim()}catch{throw Error(`design folder ${designFolder} is not in a git repository, so there are no refs to compare`)}let designRel=relative(realpathSync.native(repoRoot),realpathSync.native(resolve(designFolder))).split(sep).join("/");if(designRel.startsWith(".."))throw Error(`design folder ${designFolder} is outside the git repo at ${repoRoot}`);let rev=(ref)=>{try{return git(repoRoot,["rev-parse","--verify",`${ref}^{commit}`]).trim()}catch{throw Error(`cannot resolve git ref '${ref}'`)}},baseSha=rev(base),headSha=rev(head),currentSha=rev("HEAD");return{repoRoot,designRel,baseSha,headSha,headIsWorktree:headSha===currentSha}}function diffDesignFolder(ctx){let args=["diff","--name-status","--no-renames",ctx.baseSha];if(!ctx.headIsWorktree)args.push(ctx.headSha);if(ctx.designRel!=="")args.push("--",ctx.designRel);let output=git(ctx.repoRoot,args),prefix=ctx.designRel===""?"":`${ctx.designRel}/`,out=[];for(let line of output.split(`
|
|
3
3
|
`)){if(line.trim()==="")continue;let tab=line.indexOf("\t");if(tab===-1)continue;let code=line.slice(0,tab).trim(),repoPath=line.slice(tab+1);if(!repoPath.startsWith(prefix))continue;let status=code==="A"?"A":code==="D"?"D":code==="M"||code==="T"?"M":null;if(!status)continue;out.push({status,path:repoPath.slice(prefix.length)})}return out}function changedBoardId(path){if(!path.startsWith("boards/")||!path.endsWith(".json"))return null;let id=path.slice(7,-5);return id.includes("/")||id.includes(".")?null:id}function selectChangedPreviews(changes,screens,snippets,boards){let availableScreens=new Map(screens.map((screen)=>[screen.id,screen])),screenIds=new Set(detectChangedScreens(classifyChanges(changes),availableScreens,snippets).filter((change)=>change.status!=="deleted"&&availableScreens.has(change.id)).map((change)=>change.id)),directlyChangedBoards=new Set(changes.map((change)=>changedBoardId(change.path)).filter((id)=>id!==null)),boardIds=new Set(boards.filter((board)=>directlyChangedBoards.has(board.id)||board.frames.some((frame)=>screenIds.has(frame.screen))).map((board)=>board.id));return{screenIds,boardIds}}function changedPreviewsSince(designFolder,baseRef,screens,snippets,boards){let git=resolveGitContext(designFolder,baseRef,"HEAD");return selectChangedPreviews(diffDesignFolder(git),screens,snippets,boards)}async function resolveCloud(command,args){let baseUrl=args.url?args.url.replace(/\/+$/,""):defaultCloudUrl(),token=args.token??process.env.VELLOO_CLOUD_TOKEN??(await loadCredential(baseUrl))?.token;if(!token)fail(command,"not logged in. Run `velloo login` first.");return{baseUrl,token}}function cloudFailure(command,error){fail(command,describeCloudError(error))}async function listPublished(args){let{baseUrl,token}=await resolveCloud("publish list",args),listed=await listPublishedDesigns({baseUrl,token});if(!listed.ok)cloudFailure("publish list",listed.error);let designs=listed.value;if(designs.length===0){console.log("velloo publish: no published designs."),console.log(` ${await publishedBoardsUrl(baseUrl)}`);return}console.log(`velloo publish: ${designs.length} design${designs.length===1?"":"s"}`);for(let design of designs)console.log(`
|
|
4
4
|
${design.title?.trim()||"Untitled design"}`),console.log(` ${publishedDesignAccess(design)}`),console.log(` ${publishedDesignSubtitle(design)}`),console.log(` ${design.url}`);console.log(`
|
|
5
5
|
Manage in velloo-cloud: ${await publishedBoardsUrl(baseUrl)}`)}async function removePublished(args){let{baseUrl,token}=await resolveCloud("publish remove",args),interactive=Boolean(process.stdin.isTTY);if(!interactive&&!args.shareUrl)fail("publish remove","pass the full share URL and --yes when there is no interactive terminal");if(!interactive&&args.yes!==!0)fail("publish remove","refusing to remove a published design without --yes");let listed=await listPublishedDesigns({baseUrl,token});if(!listed.ok)cloudFailure("publish remove",listed.error);let designs=listed.value,manageable=designs.filter((design)=>design.canManage);if(manageable.length===0)fail("publish remove",`there are no published designs you can remove. Manage boards at ${await publishedBoardsUrl(baseUrl)}`);let target;if(args.shareUrl){if(target=designFromReference(args.shareUrl,designs),!target)fail("publish remove",`that share URL is not in your published designs. Manage boards at ${await publishedBoardsUrl(baseUrl)}`);if(!target.canManage)fail("publish remove","you do not have permission to remove that design")}else{let value=await select({message:"Design to unpublish",options:manageable.map((design)=>({value:design.slug,label:design.title?.trim()||"Untitled design",hint:publishedDesignSubtitle(design)}))});if(target=resolveUnpublishSelection(isCancel(value)?null:String(value),manageable),!target)fail("publish remove","cancelled")}if(args.yes!==!0){let approved=await confirm({message:`Unpublish \u201C${target.title?.trim()||"Untitled design"}\u201D? Its share URL will stop working.`,initialValue:!1});if(isCancel(approved)||!approved)fail("publish remove","cancelled")}let removed=await unpublishDesign({baseUrl,token,slug:target.slug});if(!removed.ok)cloudFailure("publish remove",removed.error);console.log(`velloo publish: removed ${target.title?.trim()||"Untitled design"}`),console.log(` ${target.url}`)}function publishedDesignAccess(design){let teamOnly=design.audience?.find((entry)=>entry.type==="team"),access=design.visibility==="private"?teamOnly?`only ${teamOnly.name||design.teamName||"its team"}`:"private":"public",parts=[design.passwordProtected?`${access}, password protected`:access],team=design.teamName?.trim();if(team)parts.push(`team ${team}`);if(design.publicComments&&(design.visibility==="public"||design.passwordProtected))parts.push("public comments on");return parts.join(" \xB7 ")}function resolveUnpublishSelection(value,designs){return value===null?null:designs.find((design)=>design.slug===value)??null}function designFromReference(reference,designs){if(!/^https?:\/\//i.test(reference.trim()))return null;let normalize=(raw)=>{try{let url=new URL(raw.trim());return url.search="",url.hash="",url.toString().replace(/\/+$/,"")}catch{return null}},normalized=normalize(reference);if(normalized===null)return null;return designs.find((design)=>normalize(design.url)===normalized)??null}function upgradeHint(upgradeUrl){return upgradeUrl?`upgrade at ${upgradeUrl}`:"upgrade from your cloud's billing page"}function privacyFlagsError(args,protectedShares=!0,upgradeUrl){if(args.visibility!==void 0&&args.visibility!=="public"&&args.visibility!=="private")return`--visibility must be 'public' or 'private', got '${args.visibility}'`;if(args.private&&args.public)return"--private and --public cannot be used together";if(args.private&&args.visibility==="public")return"--private conflicts with --visibility public";if(args.public&&args.visibility==="private")return"--public conflicts with --visibility private";let teamOnly=args["team-only"]===!0;if(teamOnly&&(args.public||args.visibility==="public"))return"--team-only is a private link; it cannot be combined with --public";if((args.private===!0||args.visibility==="private"||args.password===!0||teamOnly)&&!protectedShares)return`${PROTECTED_SHARES_UNAVAILABLE}. Publish with --public, or ${upgradeHint(upgradeUrl)}`;return null}async function resolvePublishPrivacy(args,interactive,{protectedShares=!0,upgradeUrl,team,offerTeamOnly=!1,choose=promptForPrivacyMode,askPublicComments=promptForPublicComments,warn=()=>{}}={}){let invalid=privacyFlagsError(args,protectedShares,upgradeUrl);if(invalid)throw Error(invalid);let explicit=args.visibility!==void 0||args.private===!0||args.public===!0||args.password===!0||args["team-only"]===!0,choice;if(explicit){let teamOnly=args["team-only"]===!0;if(teamOnly&&!team)throw Error("--team-only needs an organization team to publish into");choice={visibility:teamOnly||args.private||args.visibility==="private"?"private":"public",password:args.password===!0,teamOnly}}else{if(!interactive)throw Error("privacy mode is required without a terminal; pass --public, --private, --team-only, --password, or --visibility");let mode=await choose({protectedShares,upgradeUrl,...offerTeamOnly&&team?{teamName:team.name}:{}});if(typeof mode==="symbol")throw Error("cancelled");if(mode!=="public"&&!protectedShares)throw Error(PROTECTED_SHARES_UNAVAILABLE);choice=mode==="private"||mode==="team"?{visibility:"private",password:!1,teamOnly:mode==="team"}:{visibility:"public",password:mode==="password",teamOnly:!1}}let reachableOutside=choice.visibility==="public"||choice.password,flag=args["public-comments"];if(flag!==void 0){if(reachableOutside)return{...choice,publicComments:flag};if(flag)warn("--public-comments ignored: only people in your organization can open a private link");return choice}if(!explicit&&reachableOutside){let answer=await askPublicComments();if(typeof answer==="symbol")throw Error("cancelled");return{...choice,publicComments:answer}}return choice}async function promptForPrivacyMode({protectedShares,upgradeUrl,teamName}){let locked=protectedShares?{}:{disabled:!0,hint:"requires a paid plan"};return select({message:protectedShares?"Who should be able to view this publish?":`Who should be able to view this publish? (free plan: public links \u2014 ${upgradeHint(upgradeUrl)})`,initialValue:"public",options:[{value:"public",label:"Public",hint:"anyone with the link"},{value:"private",label:"Private",hint:"everyone in your organization",...locked},...teamName?[{value:"team",label:`Only ${teamName}`,hint:"that team, plus your organization's owner and admins",...locked}]:[],{value:"password",label:"Password protected",hint:"anyone with the password",...locked}]})}function promptForPublicComments(){return confirm({message:"Let people outside your organization comment? (they'll give their name)",initialValue:!1})}var CLOUD_ARGS={url:{type:"string",description:"velloo-cloud base URL (default: $VELLOO_CLOUD_URL or the built-in default)"},token:{type:"string",description:"velloo-cloud access token (default: $VELLOO_CLOUD_TOKEN)"}},list=defineCommand({meta:{name:"list",description:"List the designs you've published"},args:CLOUD_ARGS,run:({args})=>listPublished(args)}),remove=defineCommand({meta:{name:"remove",description:"Take a published design down"},args:{"share-url":{type:"positional",required:!1,description:"The share URL to take down (default: pick one interactively)"},yes:{type:"boolean",description:"Skip the confirmation (required without an interactive terminal)"},...CLOUD_ARGS},run:({args})=>removePublished({...args,shareUrl:args["share-url"]})}),publish=defineCommand({meta:{name:"publish",description:"Publish a design as a velloo-cloud share link"},args:{design:{type:"positional",required:!1,description:DESIGN_ARG_DESCRIPTION},yes:{type:"boolean",description:"Publish even when a screen's component fails to render (required without an interactive terminal)"},...CLOUD_ARGS,slug:{type:"string",description:"Custom slug for --new (default: server-generated)"},new:{type:"boolean",description:"Create a separate publish link instead of updating an existing slot"},update:{type:"boolean",description:"Update the exact matching published design"},title:{type:"string",description:"Link title (default: the design's name)"},boards:{type:"string",description:"Comma-separated board ids to publish (default: pick interactively; all when non-interactive)"},visibility:{type:"string",description:"public | private \u2014 explicit alternative to the interactive privacy prompt"},public:{type:"boolean",description:"Publish for anyone with the link; skips the privacy prompt"},private:{type:"boolean",description:"Publish for everyone in your organization; skips the privacy prompt"},"team-only":{type:"boolean",description:"Publish for the board's team only (plus the organization's owner and admins); skips the privacy prompt"},"public-comments":{type:"boolean",description:"Let people outside your organization comment on a public or password link (--no-public-comments turns it off)"},password:{type:"boolean",description:"Password-protect the link; anyone with the password can view. Prompts for it, or reads $VELLOO_SHARE_PASSWORD"},"password-expires":{type:"string",description:"Stop accepting the password after this date (YYYY-MM-DD or ISO timestamp)"},team:{type:"string",description:"Organization team to publish into, by name or UUID (default: your only team; asked when you can publish to more than one)"},w:{type:"string",description:"Viewport width in px (default: 1440)"},h:{type:"string",description:"Viewport height in px (default: 900)"},"changed-since":{type:"string",description:"Capture only screen/board previews affected since this git ref (the full design still publishes)"}},async run({args}){let folder=await resolveDesign(args.design,"publish"),baseUrl=args.url?args.url.replace(/\/+$/,""):defaultCloudUrl(),token=args.token??process.env.VELLOO_CLOUD_TOKEN??(await loadCredential(baseUrl))?.token;if(!token)fail("publish","not logged in. Run `velloo login` (or pass --token / VELLOO_CLOUD_TOKEN).");let interactive=Boolean(process.stdin.isTTY),viewport={w:args.w?Number(args.w):1440,h:args.h?Number(args.h):900},design=await loadDesignFolder(folder),config=design.config,health=await checkCloudHealth(baseUrl);if(health.status==="unreachable")fail("publish",`cannot reach ${baseUrl} (${health.reason}). Is velloo-cloud up? (bun cloud:up)`);if(health.status==="unhealthy")fail("publish",health.detail);let account=await fetchAccount(baseUrl,token,5000),protectedShares=protectedSharesAllowed(account.status==="ok"?account.account.tier:void 0),upgradeUrl=protectedShares?void 0:await billingPageUrl(baseUrl),flagsError=privacyFlagsError(args,protectedShares,upgradeUrl);if(flagsError)fail("publish",flagsError);let listedTeams=await listTeams(baseUrl,token),teamsUnsupported=!listedTeams.ok&&listedTeams.error.kind==="HttpFailure"&&listedTeams.error.status===404&&!args.team;if(!listedTeams.ok&&!teamsUnsupported)fail("publish",describePublishError(listedTeams.error));let teams=listedTeams.ok?listedTeams.value:[],teamResolution=resolvePublishTeam(teams,args.team);if(!teamResolution.ok)fail("publish",describePublishError(teamResolution.error));let resolvedTeam=teamResolution.value,knownTeam=resolvedTeam.kind==="team"?resolvedTeam.team:void 0,selected=await pickBoards(folder,args.boards,interactive,"publish");if(selected===null){console.log("velloo publish: no boards selected \u2014 nothing was published.");return}let provenance=gitContext(folder),selectedBoardIds=new Set(selected.map((board)=>board.id)),selectedBoards=[...design.boards.values()].filter((board)=>selectedBoardIds.has(board.id)),screenshotSelection=args["changed-since"]?(()=>{try{return changedPreviewsSince(folder,args["changed-since"],[...design.screens.values()],design.snippets,selectedBoards)}catch(error){fail("publish",`cannot determine previews changed since '${args["changed-since"]}': ${error instanceof Error?error.message:String(error)}`)}})():void 0,listed=await(async()=>{if(!config.folderId||args.new===!0)return{effectiveTeamId:knownTeam?.id??null,slots:[]};let destinations=await listPublishDestinations({baseUrl,token,folderId:config.folderId,...knownTeam?{teamId:knownTeam.id}:{}});if(!destinations.ok)fail("publish",describePublishError(destinations.error));return destinations.value})(),source={boardIds:selected.map((board)=>board.id),teamId:listed.effectiveTeamId,...resolvedTeam.kind==="choose"?{candidateTeamIds:resolvedTeam.teams.map((team)=>team.id)}:{},...provenance},destination=await choosePublishDestination({slots:listed.slots,source,interactive,createNew:args.new===!0,updateExisting:args.update===!0,customSlug:args.slug,manageUrl:await publishedBoardsUrl(baseUrl)}),team=await publishTeamFor({resolution:resolvedTeam,destination,slots:listed.slots,teams,interactive}).catch((error)=>fail("publish",error instanceof Error?error.message:String(error))),tier=account.status==="ok"?account.account.tier:void 0,privacy=await resolvePublishPrivacy(args,interactive,{protectedShares,...upgradeUrl?{upgradeUrl}:{},team,offerTeamOnly:teams.length>1&&teamOnlyAllowed(tier),warn:(message)=>console.log(`velloo publish: ${message}`)}).catch((error)=>fail("publish",error instanceof Error?error.message:String(error))),visibility=privacy.visibility,password=privacy.password?await readSharePassword():void 0,passwordExpiresAt=resolvePasswordExpiry(args["password-expires"],password!=null),{providers,defaultProvider}=await resolveProviders(config,folder);await confirmRenderFailures("publish",{folder:design,providers,defaultProvider},source.boardIds.length>0?screensForBoards(design,source.boardIds):[...design.screens.values()],args.yes===!0);let bundler=createPublishBundler(folder,config),jit=new TailwindJit(Object.values(providers),join2(folder,"screens"),void 0,()=>extraThemeBlock(design),()=>bundler.hostSourceDirs(),()=>findHostTailwindConfig(folder,config.hostApp),config.styling?.framework),progress=createProgress(),report=createPublishReporter(progress),outcome;try{let published=await publishDesign({baseUrl,token},{folder:design,providers,defaultProvider,snapshotCss:()=>jit.build(),liveBundler:bundler},{boardIds:selected.map((b)=>b.id),...args.title?{title:args.title}:{},visibility,...password?{password}:{},...passwordExpiresAt?{passwordExpiresAt}:{},destination,...team?{teamId:team.id}:{},...privacy.teamOnly&&team?{audience:[{type:"team",id:team.id}]}:{},...privacy.publicComments!==void 0?{publicComments:privacy.publicComments}:{},provenance,viewport,...screenshotSelection?{screenshotSelection}:{}},report);if(!published.ok)progress.fail("publish failed"),fail("publish",describePublishError(published.error));outcome=published.value,progress.succeed("published design")}catch(error){progress.fail("publish failed"),fail("publish",error instanceof Error?error.message:String(error))}finally{await closePooledBrowser()}console.log(`velloo publish: ${outcome.files} files, ${Math.round(outcome.bytes/1024)} KB${outcome.screenshots>0?`, ${outcome.screenshots} screenshots`:""}${outcome.commitSha?`, commit ${outcome.commitSha.slice(0,7)}`:""}`),console.log(` ${outcome.shareUrl}`);for(let line of describePublishedAccess(outcome,{teamName:team?.name,publicComments:privacy.publicComments}))console.log(` ${line}`);let history=outcome.history;if(history&&!history.retained&&history.pruned>0)console.log(" replaced the previous version \u2014 the free plan keeps only the latest."),console.log(` Upgrade your plan to keep version history and revisit past publishes: ${await billingPageUrl(baseUrl)}`);else if(history?.retained&&history.versions>1)console.log(` history: ${history.versions} versions kept \u2014 pin any of them from ${outcome.shareUrl}v/<version>/`)}}),publish_default=withSubcommands(publish,{list,remove});function resolvePublishDestinationChoice(value,slots){if(value===null)return null;if(value==="new")return{mode:"new"};let slug=value.replace(/^update:/,""),slot=slots.find((candidate)=>candidate.slug===slug);if(!slot)return null;return{mode:"update",slug:slot.slug,expectedVersionId:slot.latestVersionId}}async function choosePublishDestination(opts){if(opts.createNew&&opts.updateExisting)fail("publish","choose either --new or --update, not both");if(opts.customSlug&&!opts.createNew)fail("publish","--slug names a new link; use it together with --new");let matching=exactPublishSlots(opts.slots,opts.source);if(opts.updateExisting){let slot=matching[0];if(!slot)fail("publish",`there is no exact published-design match to update. Manage existing boards at ${opts.manageUrl}`);return{mode:"update",slug:slot.slug,expectedVersionId:slot.latestVersionId}}if(opts.createNew)return{mode:"new",...opts.customSlug?{slug:opts.customSlug}:{}};if(matching.length===0)return(opts.log??console.log)("velloo publish: no matching published design \u2014 a new link will be created."),{mode:"new"};if(!opts.interactive)fail("publish","this folder already has published designs; pass --update or --new explicitly");let recommended=recommendedPublishSlot(opts.slots,opts.source),latestMatch=matching[0],value=await select({message:"Publish destination",initialValue:recommended?`update:${recommended.slug}`:"new",options:[...latestMatch?[{value:`update:${latestMatch.slug}`,label:`Update ${latestMatch.title||"Untitled design"}`,hint:"latest exact match for this team, board selection, and source"}]:[],{value:"new",label:"Create a new link",hint:recommended?"keep the matching design separate":"recommended for this source"}]}),destination=resolvePublishDestinationChoice(isCancel(value)?null:String(value),matching);if(!destination)fail("publish",isCancel(value)?"cancelled":"selected publish slot is no longer available");return destination}function createPublishReporter(progress){let latestCapture;return(event)=>{if(event.kind==="capture"){latestCapture=`capturing previews ${event.done}/${event.total}`,progress.step(latestCapture,{transient:!0});return}if(event.kind==="step"){if(latestCapture)progress.step(latestCapture);latestCapture=void 0,progress.step(event.message);return}progress.log(event.message)}}async function readSharePassword(){let fromEnv=process.env.VELLOO_SHARE_PASSWORD?.trim();if(fromEnv){if(fromEnv.length<3)fail("publish","VELLOO_SHARE_PASSWORD must be at least 3 characters");return fromEnv}if(!process.stdin.isTTY)fail("publish","--password needs a terminal to prompt \u2014 set $VELLOO_SHARE_PASSWORD instead");let entered=await password({message:"Password for this share link",validate:(value)=>(value??"").length<3?"At least 3 characters.":void 0});if(isCancel(entered))fail("publish","cancelled");return entered}function resolvePasswordExpiry(raw,hasPassword){if(!raw)return;if(!hasPassword)fail("publish","--password-expires needs --password");let value=/^\d{4}-\d{2}-\d{2}$/.test(raw)?`${raw}T23:59:59`:raw,when=new Date(value);if(Number.isNaN(when.getTime()))fail("publish",`--password-expires must be a date (YYYY-MM-DD) or ISO timestamp, got '${raw}'`);return when.toISOString()}async function publishTeamFor(opts){let{resolution,destination}=opts;if(destination.mode==="update"){let slotTeamId=opts.slots.find((slot)=>slot.slug===destination.slug)?.teamId;if(slotTeamId)return opts.teams.find((team)=>team.id===slotTeamId)??{id:slotTeamId,name:"its team"}}if(resolution.kind==="personal")return;if(resolution.kind==="team")return resolution.team;if(!opts.interactive)throw Error(describePublishError(teamChoiceRequired(resolution.teams.map((team)=>team.name))));let picked=await(opts.pick??promptForTeam)(resolution.teams),team=isCancel(picked)?void 0:resolution.teams.find((candidate)=>candidate.id===picked);if(!team)throw Error("cancelled");return team}function promptForTeam(teams){return select({message:"Publish to which team?",initialValue:(teams.find((team)=>team.isDefault)??teams[0])?.id,options:teams.map((team)=>({value:team.id,label:team.name}))})}function describePublishedAccess(outcome,context={}){let teamAudience=outcome.audience?.find((entry)=>entry.type==="team"),lines=[];if(outcome.visibility==="private"){let who=teamAudience?`only ${teamAudience.name||context.teamName||"its team"}`:"anyone signed in at your organization";lines.push(outcome.passwordProtected?`private \u2014 ${teamAudience?who:"your organization"}, or anyone with the password`:`private \u2014 ${who}`)}else lines.push(outcome.passwordProtected?"public \u2014 anyone with the link and the password":"public \u2014 anyone with the link");if(context.teamName)lines.push(`team: ${context.teamName}`);let reachableOutside=outcome.visibility==="public"||outcome.passwordProtected,publicComments=outcome.publicComments??context.publicComments;if(reachableOutside&&publicComments!==void 0)lines.push(publicComments?"comments: open to people outside your organization (they give their name)":"comments: your organization only");return lines}export{publish_default as default};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ConfigSchema}from"./chunk-
|
|
2
|
+
import{ConfigSchema}from"./chunk-4pkw6d9n.js";import{readFile}from"fs/promises";import{dirname,join,resolve}from"path";async function findDesignConfig(startPath){let dir=resolve(startPath);if(!dir.endsWith("/"))dir=dirname(dir);while(!0){let candidate=join(dir,".design","config.json");try{let raw=await readFile(candidate,"utf8"),config=ConfigSchema.parse(JSON.parse(raw));return{folder:dir,config}}catch(err){if(err.code!=="ENOENT")throw err}let parent=dirname(dir);if(parent===dir)return null;dir=parent}}
|
|
3
3
|
export{findDesignConfig};
|
package/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import"./chunk-s23gtejf.js";import{COMMANDS}from"./chunk-
|
|
3
|
+
import"./chunk-s23gtejf.js";import{COMMANDS}from"./chunk-cqt1dpxd.js";import{TOOL_VERSION}from"./chunk-42bj6r30.js";import{maybeNotifyAboutUpdate}from"./chunk-0wafc9aw.js";import{defineCommand,runMain}from"./chunk-2smsg2ct.js";var main=defineCommand({meta:{name:"velloo",version:TOOL_VERSION,description:"Open-source, local-first canvas for agent-driven design."},subCommands:COMMANDS});await runMain(main);var command=process.argv[2];if(!["mcp","__daemon","__update_check","run","upgrade"].includes(command??""))await maybeNotifyAboutUpdate();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "velloo",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local-first, code-shaped design canvas — your AI agent designs with your real components, in your repo",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -47,7 +47,9 @@
|
|
|
47
47
|
"dependencies": {
|
|
48
48
|
"@tailwindcss/node": "4.3.3",
|
|
49
49
|
"@tailwindcss/oxide": "4.3.3",
|
|
50
|
+
"clsx": "2.1.1",
|
|
50
51
|
"playwright-core": "1.62.1",
|
|
52
|
+
"tailwind-merge": "3.6.0",
|
|
51
53
|
"tailwindcss": "4.3.3",
|
|
52
54
|
"tw-animate-css": "1.4.0"
|
|
53
55
|
},
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type ComponentDescriptor,
|
|
3
|
+
type FrameworkAdapter,
|
|
4
|
+
type Manifest,
|
|
5
|
+
STYLE_PROP,
|
|
6
|
+
} from "@velloo/provider";
|
|
7
|
+
import { componentsDir, entryCssPath, NONE_MANIFEST } from "@velloo/provider-none";
|
|
8
|
+
import { registry } from "./registry.ts";
|
|
9
|
+
import { HTML_VERSION } from "./version.ts";
|
|
10
|
+
|
|
11
|
+
export { Html, isSafeTag, safeAttributeValue } from "./registry.ts";
|
|
12
|
+
|
|
13
|
+
const htmlDescriptors: ComponentDescriptor[] = [
|
|
14
|
+
{
|
|
15
|
+
id: "Html",
|
|
16
|
+
category: "ui",
|
|
17
|
+
source: "velloo",
|
|
18
|
+
group: "layout",
|
|
19
|
+
family: "Html",
|
|
20
|
+
allowUnknownProps: true,
|
|
21
|
+
designModeNotes:
|
|
22
|
+
"Use for a native HTML element. Set as to a semantic tag and pass ordinary HTML or hx-* attributes as props.",
|
|
23
|
+
props: [
|
|
24
|
+
{ name: "as", type: "string", optional: true, control: "string", defaultValue: "div" },
|
|
25
|
+
{ name: "className", type: "string", optional: true, control: "string" },
|
|
26
|
+
{ name: "style", type: "CSSProperties", optional: true, control: "string" },
|
|
27
|
+
{ name: "children", type: "ReactNode", optional: true, control: "string" },
|
|
28
|
+
],
|
|
29
|
+
},
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
const HTML_MANIFEST: Manifest = [...NONE_MANIFEST, ...htmlDescriptors];
|
|
33
|
+
|
|
34
|
+
const HTML_INTRO = [
|
|
35
|
+
"**This is a server-rendered HTML/htmx app.** Compose semantic HTML with `Html` nodes (`as=\"form\"`, …), styled by the app's own CSS classes or inline `style` — there is no Tailwind; new classes need CSS authored in the app. Give forms and controls the real `hx-*` attributes: the canvas never fires them, and `emit_code` keeps them in the native HTML it returns for the app's templates.",
|
|
36
|
+
"",
|
|
37
|
+
"A design never contacts the running app: it is styled by copies of the app's stylesheets, which `store_host_files` refreshes from source or from a capture (including built CSS a `screenshot` reports missing). Reference the app's files by their real paths (`src=\"/static/logo.png\"`), not as Velloo assets. Theme tokens are CSS variables (`var(--color-primary)`); `emit_theme` writes the stylesheet that defines them.",
|
|
38
|
+
"",
|
|
39
|
+
"To reproduce a page, capture it from the running app with `start_capture_session` (the user signs in if needed), rebuild it from `get_capture` with the content written into the nodes, and verify with `compare_to_url { captureId }`.",
|
|
40
|
+
"",
|
|
41
|
+
"On a form, a custom `hx-trigger` replaces htmx's default submit trigger — include `submit` when a submit button must swap a response instead of navigating.",
|
|
42
|
+
"",
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The HTML/htmx adapter: the no-library primitives and helpers on the inline
|
|
47
|
+
* `style` channel, plus `Html`, styled by the app's own stylesheets. No browser
|
|
48
|
+
* component bundle — the server render is the page — and emission is native
|
|
49
|
+
* HTML, not JSX.
|
|
50
|
+
*/
|
|
51
|
+
export function createProvider(): FrameworkAdapter {
|
|
52
|
+
return {
|
|
53
|
+
id: "html",
|
|
54
|
+
version: HTML_VERSION,
|
|
55
|
+
label: "HTML + htmx",
|
|
56
|
+
componentsDir,
|
|
57
|
+
styleEntryPath: entryCssPath,
|
|
58
|
+
registry,
|
|
59
|
+
loadManifest: async () => HTML_MANIFEST,
|
|
60
|
+
styleChannel: STYLE_PROP,
|
|
61
|
+
styleChannels: ["style"],
|
|
62
|
+
registryForChannel: () => registry,
|
|
63
|
+
mcpIntro: () => HTML_INTRO,
|
|
64
|
+
hostStylesheets: true,
|
|
65
|
+
codegenFormat: "html",
|
|
66
|
+
elementComponent: "Html",
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTML/htmx components and their sanitizer, free of Node APIs: the canvas
|
|
3
|
+
* renders them server-side, and the cloud share viewer imports this module in
|
|
4
|
+
* the browser to render a published HTML design. A published tree is
|
|
5
|
+
* untrusted input there, so every guarantee below holds at render time, not
|
|
6
|
+
* only when a design is written.
|
|
7
|
+
*/
|
|
8
|
+
import type { ComponentRegistry } from "@velloo/provider";
|
|
9
|
+
import { inlineRegistry } from "@velloo/provider-none/registry-inline";
|
|
10
|
+
import { styleObjectFromCss } from "@velloo/schema";
|
|
11
|
+
import { createElement, type HTMLAttributes, type ReactNode } from "react";
|
|
12
|
+
|
|
13
|
+
// Keep executable/embedded tags out of editable designs while accepting the
|
|
14
|
+
// ordinary semantic elements and static SVG shapes found in native templates.
|
|
15
|
+
const SAFE_TAG =
|
|
16
|
+
/^(?:a|abbr|address|article|aside|b|bdi|bdo|blockquote|br|button|caption|circle|cite|clipPath|code|col|colgroup|data|dd|defs|del|details|dfn|div|dl|dt|ellipse|em|fieldset|figcaption|figure|footer|form|g|h[1-6]|header|hr|i|img|input|ins|kbd|label|legend|li|line|linearGradient|main|mark|mask|meter|nav|ol|optgroup|option|output|p|path|picture|polygon|polyline|pre|progress|q|radialGradient|rect|s|samp|section|select|small|source|span|stop|strong|sub|summary|sup|svg|table|tbody|td|text|textarea|tfoot|th|thead|time|tr|tspan|u|ul|var|wbr)$/;
|
|
17
|
+
|
|
18
|
+
/** Attributes whose value the browser loads or navigates to. */
|
|
19
|
+
const URL_ATTRIBUTES = new Set([
|
|
20
|
+
"href",
|
|
21
|
+
"src",
|
|
22
|
+
"action",
|
|
23
|
+
"formaction",
|
|
24
|
+
"poster",
|
|
25
|
+
"cite",
|
|
26
|
+
"xlinkhref",
|
|
27
|
+
"xlink:href",
|
|
28
|
+
]);
|
|
29
|
+
// Browsers ignore ASCII whitespace and control characters inside a scheme, so
|
|
30
|
+
// `java\tscript:` must be caught too.
|
|
31
|
+
const SCRIPT_URL = /^(?:javascript|vbscript):|^data:text\/html/i;
|
|
32
|
+
|
|
33
|
+
const withoutControls = (value: string): string =>
|
|
34
|
+
[...value].filter((char) => char.charCodeAt(0) > 0x20).join("");
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* HTML attribute names an agent writing markup reaches for, as the React props
|
|
38
|
+
* that render them — React renders `autocomplete` too, but warns on every
|
|
39
|
+
* render and drops `class`'s meaning for its own `className` handling.
|
|
40
|
+
*/
|
|
41
|
+
const REACT_PROP: Record<string, string> = {
|
|
42
|
+
class: "className",
|
|
43
|
+
for: "htmlFor",
|
|
44
|
+
autocomplete: "autoComplete",
|
|
45
|
+
autofocus: "autoFocus",
|
|
46
|
+
tabindex: "tabIndex",
|
|
47
|
+
readonly: "readOnly",
|
|
48
|
+
maxlength: "maxLength",
|
|
49
|
+
minlength: "minLength",
|
|
50
|
+
colspan: "colSpan",
|
|
51
|
+
rowspan: "rowSpan",
|
|
52
|
+
enctype: "encType",
|
|
53
|
+
novalidate: "noValidate",
|
|
54
|
+
datetime: "dateTime",
|
|
55
|
+
srcset: "srcSet",
|
|
56
|
+
crossorigin: "crossOrigin",
|
|
57
|
+
accesskey: "accessKey",
|
|
58
|
+
contenteditable: "contentEditable",
|
|
59
|
+
spellcheck: "spellCheck",
|
|
60
|
+
formaction: "formAction",
|
|
61
|
+
formmethod: "formMethod",
|
|
62
|
+
inputmode: "inputMode",
|
|
63
|
+
referrerpolicy: "referrerPolicy",
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
type HtmlProps = HTMLAttributes<HTMLElement> & {
|
|
67
|
+
as?: string;
|
|
68
|
+
children?: ReactNode;
|
|
69
|
+
[key: string]: unknown;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/** Whether `Html` renders this tag: semantic HTML and static SVG, nothing that runs or embeds. */
|
|
73
|
+
export function isSafeTag(tag: string): boolean {
|
|
74
|
+
return SAFE_TAG.test(tag);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Whether an attribute may carry this value: never an event handler or raw
|
|
79
|
+
* inner HTML, and never a URL that runs script.
|
|
80
|
+
*/
|
|
81
|
+
export function safeAttributeValue(name: string, value: unknown): boolean {
|
|
82
|
+
const key = name.toLowerCase();
|
|
83
|
+
if (key.startsWith("on") || key === "dangerouslysetinnerhtml") return false;
|
|
84
|
+
if (URL_ATTRIBUTES.has(key) && typeof value === "string") {
|
|
85
|
+
return !SCRIPT_URL.test(withoutControls(value));
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function safeTag(component: string, as: string): string {
|
|
91
|
+
if (!SAFE_TAG.test(as))
|
|
92
|
+
throw new Error(`${component}: unsupported HTML tag ${JSON.stringify(as)}`);
|
|
93
|
+
return as;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Props a design may put on a native element: never event handlers, raw inner
|
|
98
|
+
* HTML, or a URL that runs script — the canvas executes the document, so an
|
|
99
|
+
* attribute is as dangerous as a `<script>` tag.
|
|
100
|
+
*/
|
|
101
|
+
function nativeAttributes(props: Record<string, unknown>): Record<string, unknown> {
|
|
102
|
+
return Object.fromEntries(
|
|
103
|
+
Object.entries(props)
|
|
104
|
+
.map(([name, value]) => [REACT_PROP[name] ?? name, value] as const)
|
|
105
|
+
.filter(([name, value]) => safeAttributeValue(name, value))
|
|
106
|
+
.flatMap(([name, value]) => {
|
|
107
|
+
// HTML's own `style="…"` (a snapshot of server output, or a design
|
|
108
|
+
// written as markup) is text; React only takes an object.
|
|
109
|
+
if (name !== "style" || typeof value !== "string") return [[name, value] as const];
|
|
110
|
+
const style = styleObjectFromCss(value);
|
|
111
|
+
return style ? [[name, style] as const] : [];
|
|
112
|
+
}),
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function Html({ as = "div", children, ...props }: HtmlProps) {
|
|
117
|
+
return createElement(safeTag("Html", as), nativeAttributes(props), children);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The inline-style primitives and helpers, plus the native HTML components. */
|
|
121
|
+
export const registry: ComponentRegistry = { ...inlineRegistry, Html };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const HTML_VERSION = "1";
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { headingInlineStyle, textInlineStyle } from "@velloo/schema/typeset";
|
|
2
2
|
import * as React from "react";
|
|
3
|
-
import
|
|
3
|
+
import {
|
|
4
|
+
BOX_TAG,
|
|
5
|
+
type ButtonProps,
|
|
6
|
+
type ContainerProps,
|
|
7
|
+
type InputProps,
|
|
8
|
+
type StackProps,
|
|
9
|
+
} from "./components.tsx";
|
|
4
10
|
|
|
5
11
|
/**
|
|
6
12
|
* Inline-styled variants of the no-library primitives, for a `none`-CSS folder
|
|
@@ -28,8 +34,11 @@ function merge(
|
|
|
28
34
|
/** Tailwind's spacing scale is 0.25rem per step (gap-4 ⇒ 1rem). */
|
|
29
35
|
const space = (n: number) => `${n * 0.25}rem`;
|
|
30
36
|
|
|
31
|
-
export const Box = React.forwardRef<
|
|
32
|
-
|
|
37
|
+
export const Box = React.forwardRef<
|
|
38
|
+
HTMLDivElement,
|
|
39
|
+
React.HTMLAttributes<HTMLDivElement> & { as?: string }
|
|
40
|
+
>(({ as, ...rest }, ref) =>
|
|
41
|
+
React.createElement(typeof as === "string" && BOX_TAG.test(as) ? as : "div", { ref, ...rest }),
|
|
33
42
|
);
|
|
34
43
|
Box.displayName = "Box";
|
|
35
44
|
|
|
@@ -14,9 +14,17 @@ import * as React from "react";
|
|
|
14
14
|
|
|
15
15
|
interface DivProps extends React.HTMLAttributes<HTMLDivElement> {}
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
/** `as` takes a lowercase HTML tag only — anything else renders the div. */
|
|
18
|
+
export const BOX_TAG = /^[a-z][a-z0-9]*$/;
|
|
19
|
+
|
|
20
|
+
export const Box = React.forwardRef<HTMLDivElement, DivProps & { as?: string }>(
|
|
21
|
+
({ as, className, ...rest }, ref) =>
|
|
22
|
+
React.createElement(typeof as === "string" && BOX_TAG.test(as) ? as : "div", {
|
|
23
|
+
ref,
|
|
24
|
+
className: clsx(className),
|
|
25
|
+
...rest,
|
|
26
|
+
}),
|
|
27
|
+
);
|
|
20
28
|
Box.displayName = "Box";
|
|
21
29
|
|
|
22
30
|
export interface StackProps extends DivProps {
|
|
@@ -47,10 +47,22 @@ export const CommentAnchorSchema = z.discriminatedUnion("kind", [
|
|
|
47
47
|
]);
|
|
48
48
|
export type CommentAnchor = z.infer<typeof CommentAnchorSchema>;
|
|
49
49
|
|
|
50
|
+
/**
|
|
51
|
+
* The author's role in the board's organization when the cloud served the
|
|
52
|
+
* thread — "guest" for someone invited to (or reading) a link without a seat.
|
|
53
|
+
* Distinct from `kind`: a `reviewer` is anyone who wrote through the share
|
|
54
|
+
* page, the link's owner included.
|
|
55
|
+
*/
|
|
56
|
+
const CommentAuthorRoleSchema = z.enum(["owner", "admin", "member", "reviewer", "guest"]);
|
|
57
|
+
export type CommentAuthorRole = z.infer<typeof CommentAuthorRoleSchema>;
|
|
58
|
+
|
|
50
59
|
export const CommentAuthorSchema = z.object({
|
|
51
60
|
kind: z.enum(["user", "agent", "reviewer"]),
|
|
52
61
|
displayName: z.string().min(1).max(200).optional(),
|
|
53
62
|
accountId: z.string().min(1).max(200).optional(),
|
|
63
|
+
role: CommentAuthorRoleSchema.optional(),
|
|
64
|
+
/** The cloud's word that this author published the board. Never set on an agent's message. */
|
|
65
|
+
publisher: z.boolean().optional(),
|
|
54
66
|
});
|
|
55
67
|
export type CommentAuthor = z.infer<typeof CommentAuthorSchema>;
|
|
56
68
|
|