velloo 0.3.0 → 0.3.1
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/canvas/assets/{index-CqXW6xA_.js → index-DZFrkC4P.js} +11 -11
- package/canvas/assets/{lucide-all-C_CNpsMs.js → lucide-all-Bu8-9UDF.js} +1 -1
- package/canvas/index.html +1 -1
- package/chunk-0s6drs3n.js +2 -0
- package/{chunk-1jzhw3p4.js → chunk-1xb88e07.js} +1 -1
- package/{chunk-tc4mzzfw.js → chunk-2e3nd4tz.js} +1 -1
- package/{chunk-m3czg1tt.js → chunk-2p37rp3j.js} +1 -1
- package/{chunk-n9kcxaj7.js → chunk-2zbn6641.js} +1 -1
- package/{chunk-wcqqx6tz.js → chunk-3px2d1j1.js} +1 -1
- package/{chunk-dsks52m7.js → chunk-4e9jh482.js} +1 -1
- package/{chunk-bpeezw7w.js → chunk-4g250157.js} +1 -1
- package/{chunk-k9219kmj.js → chunk-4ma2wnqw.js} +1 -1
- package/{chunk-7bvvbsqy.js → chunk-59zas5y2.js} +1 -1
- package/{chunk-nr3ej3qf.js → chunk-7cvhnp9h.js} +1 -1
- package/{chunk-9f22qnge.js → chunk-7s8frnag.js} +1 -1
- package/chunk-7t13w87m.js +2 -0
- package/{chunk-cxzkkn12.js → chunk-7yaafw73.js} +1 -1
- package/{chunk-5ezzc1h2.js → chunk-88eqqdk1.js} +2 -2
- package/{chunk-wzngjjeb.js → chunk-8z3ykvcs.js} +1 -1
- package/{chunk-wa6qamwh.js → chunk-98vvrj0c.js} +1 -1
- package/{chunk-3tmsrvaj.js → chunk-9cdwhrkh.js} +1 -1
- package/{chunk-7k7dpj5y.js → chunk-9p1dk5cb.js} +1 -1
- package/{chunk-kz4423th.js → chunk-9psr8atb.js} +1 -1
- package/{chunk-qdnb2t6a.js → chunk-9ydc34wc.js} +1 -1
- package/{chunk-6nzqhfqq.js → chunk-asbajsmd.js} +1 -1
- package/{chunk-9nhw49vv.js → chunk-avkfsc3p.js} +1 -1
- package/{chunk-t5bb30zy.js → chunk-f0vsjfpc.js} +1 -1
- package/{chunk-4nqr089t.js → chunk-g71v35gd.js} +1 -1
- package/{chunk-k7sehkm8.js → chunk-mfbxfb9b.js} +1 -1
- package/{chunk-9g4tr0r6.js → chunk-mt8ds8zj.js} +1 -1
- package/{chunk-d9p6s05n.js → chunk-nev5mv85.js} +1 -1
- package/{chunk-3g3dqej3.js → chunk-p62fygqz.js} +1 -1
- package/{chunk-nycs0z7h.js → chunk-p6e1eg76.js} +1 -1
- package/{chunk-jx11jvq8.js → chunk-ph2jfg1x.js} +1 -1
- package/{chunk-y5r2w2z3.js → chunk-pve2mmnr.js} +1 -1
- package/{chunk-7njj1qmq.js → chunk-t2w8a591.js} +1 -1
- package/{chunk-qgwhd4n6.js → chunk-t5m5mznb.js} +1 -1
- package/{chunk-yeh9gb5w.js → chunk-t947mxr1.js} +1 -1
- package/{chunk-49cgk5s2.js → chunk-tt7fys2w.js} +1 -1
- package/{chunk-td5z2sm4.js → chunk-wafb2xm9.js} +1 -1
- package/{chunk-52hxv18g.js → chunk-whw3epmr.js} +1 -1
- package/{chunk-1n5kmsxb.js → chunk-wndntr7s.js} +1 -1
- package/{chunk-tbmkq7wy.js → chunk-wnwgqvtd.js} +1 -1
- package/{chunk-k6n249vb.js → chunk-wp123630.js} +1 -1
- package/{chunk-maz6z7tz.js → chunk-wvs939t5.js} +1 -1
- package/{chunk-bvmtq0vn.js → chunk-z21hg6j3.js} +1 -1
- package/cli.js +1 -1
- package/package.json +1 -1
- package/chunk-788t8y5x.js +0 -2
- package/chunk-xyfed1j0.js +0 -2
package/canvas/index.html
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
<link rel="manifest" href="/site.webmanifest" />
|
|
10
10
|
<meta name="theme-color" content="#0d0c0a" />
|
|
11
11
|
<title>velloo</title>
|
|
12
|
-
<script type="module" crossorigin src="/assets/index-
|
|
12
|
+
<script type="module" crossorigin src="/assets/index-DZFrkC4P.js"></script>
|
|
13
13
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
|
|
14
14
|
<link rel="modulepreload" crossorigin href="/assets/react-D0Ec-185.js">
|
|
15
15
|
<link rel="modulepreload" crossorigin href="/assets/vendor-CKmQ-Zst.js">
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{init_default,runInit2}from"./chunk-59zas5y2.js";import"./chunk-nev5mv85.js";import"./chunk-avkfsc3p.js";import"./chunk-ph2jfg1x.js";import"./chunk-wafb2xm9.js";import"./chunk-6zz9kfbd.js";import"./chunk-hfzg98c8.js";import"./chunk-t2w8a591.js";import"./chunk-t5m5mznb.js";import"./chunk-2fgfex9b.js";import"./chunk-4ma2wnqw.js";import"./chunk-80fjfyha.js";import"./chunk-88eqqdk1.js";import"./chunk-c4fym47a.js";import"./chunk-as08hzp3.js";import"./chunk-n9t36h0q.js";import"./chunk-9p1dk5cb.js";import"./chunk-9ydc34wc.js";import"./chunk-9psr8atb.js";import"./chunk-s23gtejf.js";import"./chunk-nte0t7v3.js";import"./chunk-cvn689d5.js";export{init_default as default,runInit2 as runInit};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{fail}from"./chunk-s23gtejf.js";import"./chunk-
|
|
2
|
+
import{fail}from"./chunk-s23gtejf.js";import"./chunk-9ydc34wc.js";import{SHELLS,completionScript,commandSpecs,detectShell,installCompletions}from"./chunk-t5m5mznb.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";var import_picocolors=__toESM(require_picocolors(),1);var completions_default=defineCommand({meta:{name:"completions",description:"Shell TAB completions \u2014 print the script, or install it with --install"},args:{shell:{type:"positional",required:!1,description:`Shell: ${SHELLS.join(" | ")} (default: detected from $SHELL)`},install:{type:"boolean",default:!1,description:"Write the script + wire it into your shell (idempotent)"}},async run({args}){let shell=args.shell??detectShell();if(!shell||!SHELLS.includes(shell))fail("completions",`unsupported or undetected shell${args.shell?` "${args.shell}"`:""} \u2014 pass one of: ${SHELLS.join(", ")}.`);if(!args.install){console.log(completionScript(shell,await commandSpecs()));return}let r=await installCompletions(shell);if(console.log(""),console.log(import_picocolors.default.green(`\u2713 ${shell} completions installed.`)),console.log(` script ${import_picocolors.default.cyan(r.scriptPath)}`),r.rcPath)console.log(r.rcUpdated?` rc ${import_picocolors.default.cyan(r.rcPath)} ${import_picocolors.default.dim("(source line appended)")}`:` rc ${import_picocolors.default.cyan(r.rcPath)} ${import_picocolors.default.dim("(already wired)")}`);console.log(""),console.log(import_picocolors.default.dim(shell==="fish"?" New fish sessions pick it up automatically.":` Restart your shell (or \`source ${r.rcPath}\`) to activate TAB completion.`))}});export{completions_default as default};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-n9t36h0q.js";import"./chunk-nte0t7v3.js";import{loadCredential}from"./chunk-hfzg98c8.js";import"./chunk-
|
|
2
|
+
import"./chunk-n9t36h0q.js";import"./chunk-nte0t7v3.js";import{loadCredential}from"./chunk-hfzg98c8.js";import"./chunk-88eqqdk1.js";import"./chunk-c4fym47a.js";import"./chunk-9psr8atb.js";import{listDaemons}from"./chunk-4ma2wnqw.js";import"./chunk-80fjfyha.js";import"./chunk-s23gtejf.js";import"./chunk-2fgfex9b.js";import"./chunk-9ydc34wc.js";import"./chunk-cvn689d5.js";import"./chunk-t2w8a591.js";import{designWithFolder}from"./chunk-4g250157.js";import{verifyCredential}from"./chunk-6zz9kfbd.js";import"./chunk-t5m5mznb.js";import{defaultCloudUrl}from"./chunk-as08hzp3.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";var import_picocolors=__toESM(require_picocolors(),1);var status_default=defineCommand({meta:{name:"status",description:"List the velloo canvas daemons running on this machine + cloud sign-in"},args:{},async run(){let daemons=await listDaemons();if(daemons.length===0)console.log("velloo: no canvas daemons running.");else for(let d of daemons)console.log(`${d.canvasUrl} ${designWithFolder(d.root,void 0,{absolute:!0})} (pid ${d.pid}, since ${d.startedAt})`);let cloudUrl=defaultCloudUrl(),cred=await loadCredential(cloudUrl);if(!cred){console.log(import_picocolors.default.dim(`cloud: not signed in (${cloudUrl}) \u2014 run \`velloo login\` to share.`));return}let email=await verifyCredential(cloudUrl,cred.token,3000);console.log(email?`cloud: signed in as ${email} (${cloudUrl})`:import_picocolors.default.dim(`cloud: stored credential for ${cred.email} (${cloudUrl}) \u2014 expired or cloud unreachable; \`velloo login\` to refresh.`))}});export{status_default as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isCancel,select}from"./chunk-80fjfyha.js";import{preflightScreens}from"./chunk-
|
|
2
|
+
import{isCancel,select}from"./chunk-80fjfyha.js";import{preflightScreens}from"./chunk-88eqqdk1.js";import{fail}from"./chunk-s23gtejf.js";import{copyToClipboard}from"./chunk-vbk1qhdz.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM}from"./chunk-2smsg2ct.js";import{stripVTControlCharacters}from"util";var import_picocolors=__toESM(require_picocolors(),1);function plural(count,noun){return`${count} ${noun}${count===1?"":"s"}`}function formatFailures(command,failures){let byScreen=new Map;for(let failure of failures)byScreen.set(failure.screenId,[...byScreen.get(failure.screenId)??[],failure]);let notDrawn=[...byScreen.values()].filter((group)=>group.some((failure)=>failure.componentId===null)),placeholders=[...byScreen.values()].filter((group)=>!notDrawn.includes(group)).reduce((sum,group)=>sum+group.length,0),consequences=[placeholders>0&&`${plural(placeholders,"component")} will appear as placeholders`,notDrawn.length>0&&`${plural(notDrawn.length,"screen")} will not render at all`].filter(Boolean),lines=[`${import_picocolors.default.yellow(`velloo ${command}:`)} render failures on ${plural(byScreen.size,"screen")} \u2014 ${consequences.join(", and ")}:`];for(let group of byScreen.values()){let[first]=group;if(!first)continue;let boards=first.boards.length>0?first.boards.map((board)=>board.name).join(", "):"no board";lines.push("",` ${import_picocolors.default.dim(`${boards} \u203A`)} ${import_picocolors.default.bold(first.screenName)} ${import_picocolors.default.dim(`(${first.screenId})`)}`);let pinned=group.some((failure)=>failure.componentId!==null);for(let failure of group)if(failure.componentId!==null)lines.push(` ${import_picocolors.default.cyan(failure.componentId)}: ${failure.reason}`);else{let label=pinned?"screen not drawn":"screen not drawn \u2014 the error could not be pinned on one component";lines.push(` ${import_picocolors.default.red(label)}: ${failure.reason}`)}}return lines}async function confirmRenderFailures(command,source,screens,yes){let failures=preflightScreens(source,screens);if(failures.length===0)return;let report=formatFailures(command,failures);for(let line of report)console.error(line);if(console.error(""),yes)return;if(!process.stdin.isTTY)fail(command,"refusing to continue \u2014 re-run with --yes to accept the placeholders.");for(;;){let choice=await select({message:"Continue anyway?",options:[{value:"cancel",label:"No, cancel"},{value:"continue",label:"Yes, continue with the failures"},{value:"copy",label:"Copy errors to clipboard"}],initialValue:"cancel"});if(isCancel(choice)||choice==="cancel")fail(command,"cancelled.");if(choice==="continue")return;let copied=await copyToClipboard(stripVTControlCharacters(report.join(`
|
|
3
3
|
`)));console.error(copied?` ${import_picocolors.default.green("\u2713")} Errors copied to the clipboard.`:import_picocolors.default.dim(" Couldn't reach a clipboard tool \u2014 copy the errors printed above."))}}
|
|
4
4
|
export{confirmRenderFailures};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{clsx_default,helpersRegistry,parse_default,formatRgb,SX_PROP,catalogFromManifest,helperSourcePath}from"./chunk-5ezzc1h2.js";import{require_react_is_development,require_object_assign,require_emotion_serialize_development_cjs,$_default,import_emotion_react_development_cjs,$_default2,$_default3}from"./chunk-js6mz7h1.js";import{resolveColors,DEFAULT_TYPESET_NAME,typesetScale}from"./chunk-nte0t7v3.js";import{_objectWithoutPropertiesLoose,_extends,_assertThisInitialized,_setPrototypeOf}from"./chunk-h6gchare.js";import{resolveProviderSrcDir}from"./chunk-fjbzk4sw.js";import{require_react_jsx_runtime_development}from"./chunk-c6hywdvq.js";import{require_react_development,require_react_dom}from"./chunk-c4fym47a.js";import{__toESM,__commonJS}from"./chunk-2smsg2ct.js";import{MUI_VERSION}from"./chunk-mzhdrawd.js";var require_ReactPropTypesSecret=__commonJS(function(exports,module){var ReactPropTypesSecret="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";module.exports=ReactPropTypesSecret});var require_has=__commonJS(function(exports,module){module.exports=Function.call.bind(Object.prototype.hasOwnProperty)});var require_checkPropTypes=__commonJS(function(exports,module){var printWarning=function(){};ReactPropTypesSecret=require_ReactPropTypesSecret(),loggedTypeFailures={},has=require_has(),printWarning=function(text){var message="Warning: "+text;if(typeof console<"u")console.error(message);try{throw Error(message)}catch(x){}};var ReactPropTypesSecret,loggedTypeFailures,has;function checkPropTypes(typeSpecs,values,location,componentName,getStack){for(var typeSpecName in typeSpecs)if(has(typeSpecs,typeSpecName)){var error;try{if(typeof typeSpecs[typeSpecName]!=="function"){var err=Error((componentName||"React class")+": "+location+" type `"+typeSpecName+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof typeSpecs[typeSpecName]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw err.name="Invariant Violation",err}error=typeSpecs[typeSpecName](values,typeSpecName,componentName,location,null,ReactPropTypesSecret)}catch(ex){error=ex}if(error&&!(error instanceof Error))printWarning((componentName||"React class")+": type specification of "+location+" `"+typeSpecName+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof error+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).");if(error instanceof Error&&!(error.message in loggedTypeFailures)){loggedTypeFailures[error.message]=!0;var stack=getStack?getStack():"";printWarning("Failed "+location+" type: "+error.message+(stack!=null?stack:""))}}}checkPropTypes.resetWarningCache=function(){loggedTypeFailures={}};module.exports=checkPropTypes});var require_factoryWithTypeCheckers=__commonJS(function(exports,module){var ReactIs=__toESM(require_react_is_development()),assign=require_object_assign(),ReactPropTypesSecret=require_ReactPropTypesSecret(),has=require_has(),checkPropTypes=require_checkPropTypes(),printWarning=function(){};printWarning=function(text){var message="Warning: "+text;if(typeof console<"u")console.error(message);try{throw Error(message)}catch(x){}};function emptyFunctionThatReturnsNull(){return null}module.exports=function(isValidElement,throwOnDirectAccess){var ITERATOR_SYMBOL=typeof Symbol==="function"&&Symbol.iterator,FAUX_ITERATOR_SYMBOL="@@iterator";function getIteratorFn(maybeIterable){var iteratorFn=maybeIterable&&(ITERATOR_SYMBOL&&maybeIterable[ITERATOR_SYMBOL]||maybeIterable[FAUX_ITERATOR_SYMBOL]);if(typeof iteratorFn==="function")return iteratorFn}var ANONYMOUS="<<anonymous>>",ReactPropTypes={array:createPrimitiveTypeChecker("array"),bigint:createPrimitiveTypeChecker("bigint"),bool:createPrimitiveTypeChecker("boolean"),func:createPrimitiveTypeChecker("function"),number:createPrimitiveTypeChecker("number"),object:createPrimitiveTypeChecker("object"),string:createPrimitiveTypeChecker("string"),symbol:createPrimitiveTypeChecker("symbol"),any:createAnyTypeChecker(),arrayOf:createArrayOfTypeChecker,element:createElementTypeChecker(),elementType:createElementTypeTypeChecker(),instanceOf:createInstanceTypeChecker,node:createNodeChecker(),objectOf:createObjectOfTypeChecker,oneOf:createEnumTypeChecker,oneOfType:createUnionTypeChecker,shape:createShapeTypeChecker,exact:createStrictShapeTypeChecker};function is(x,y){if(x===y)return x!==0||1/x===1/y;else return x!==x&&y!==y}function PropTypeError(message,data){this.message=message,this.data=data&&typeof data==="object"?data:{},this.stack=""}PropTypeError.prototype=Error.prototype;function createChainableTypeChecker(validate){var manualPropTypeCallCache={},manualPropTypeWarningCount=0;function checkType(isRequired,props,propName,componentName,location,propFullName,secret){if(componentName=componentName||ANONYMOUS,propFullName=propFullName||propName,secret!==ReactPropTypesSecret){if(throwOnDirectAccess){var err=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw err.name="Invariant Violation",err}else if(typeof console<"u"){var cacheKey=componentName+":"+propName;if(!manualPropTypeCallCache[cacheKey]&&manualPropTypeWarningCount<3)printWarning("You are manually calling a React.PropTypes validation function for the `"+propFullName+"` prop on `"+componentName+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),manualPropTypeCallCache[cacheKey]=!0,manualPropTypeWarningCount++}}if(props[propName]==null){if(isRequired){if(props[propName]===null)return new PropTypeError("The "+location+" `"+propFullName+"` is marked as required "+("in `"+componentName+"`, but its value is `null`."));return new PropTypeError("The "+location+" `"+propFullName+"` is marked as required in "+("`"+componentName+"`, but its value is `undefined`."))}return null}else return validate(props,propName,componentName,location,propFullName)}var chainedCheckType=checkType.bind(null,!1);return chainedCheckType.isRequired=checkType.bind(null,!0),chainedCheckType}function createPrimitiveTypeChecker(expectedType){function validate(props,propName,componentName,location,propFullName,secret){var propValue=props[propName],propType=getPropType(propValue);if(propType!==expectedType){var preciseType=getPreciseType(propValue);return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+preciseType+"` supplied to `"+componentName+"`, expected ")+("`"+expectedType+"`."),{expectedType})}return null}return createChainableTypeChecker(validate)}function createAnyTypeChecker(){return createChainableTypeChecker(emptyFunctionThatReturnsNull)}function createArrayOfTypeChecker(typeChecker){function validate(props,propName,componentName,location,propFullName){if(typeof typeChecker!=="function")return new PropTypeError("Property `"+propFullName+"` of component `"+componentName+"` has invalid PropType notation inside arrayOf.");var propValue=props[propName];if(!Array.isArray(propValue)){var propType=getPropType(propValue);return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+propType+"` supplied to `"+componentName+"`, expected an array."))}for(var i=0;i<propValue.length;i++){var error=typeChecker(propValue,i,componentName,location,propFullName+"["+i+"]",ReactPropTypesSecret);if(error instanceof Error)return error}return null}return createChainableTypeChecker(validate)}function createElementTypeChecker(){function validate(props,propName,componentName,location,propFullName){var propValue=props[propName];if(!isValidElement(propValue)){var propType=getPropType(propValue);return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+propType+"` supplied to `"+componentName+"`, expected a single ReactElement."))}return null}return createChainableTypeChecker(validate)}function createElementTypeTypeChecker(){function validate(props,propName,componentName,location,propFullName){var propValue=props[propName];if(!ReactIs.isValidElementType(propValue)){var propType=getPropType(propValue);return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+propType+"` supplied to `"+componentName+"`, expected a single ReactElement type."))}return null}return createChainableTypeChecker(validate)}function createInstanceTypeChecker(expectedClass){function validate(props,propName,componentName,location,propFullName){if(!(props[propName]instanceof expectedClass)){var expectedClassName=expectedClass.name||ANONYMOUS,actualClassName=getClassName(props[propName]);return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+actualClassName+"` supplied to `"+componentName+"`, expected ")+("instance of `"+expectedClassName+"`."))}return null}return createChainableTypeChecker(validate)}function createEnumTypeChecker(expectedValues){if(!Array.isArray(expectedValues)){if(arguments.length>1)printWarning("Invalid arguments supplied to oneOf, expected an array, got "+arguments.length+" arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).");else printWarning("Invalid argument supplied to oneOf, expected an array.");return emptyFunctionThatReturnsNull}function validate(props,propName,componentName,location,propFullName){var propValue=props[propName];for(var i=0;i<expectedValues.length;i++)if(is(propValue,expectedValues[i]))return null;var valuesString=JSON.stringify(expectedValues,function(key,value){var type=getPreciseType(value);if(type==="symbol")return String(value);return value});return new PropTypeError("Invalid "+location+" `"+propFullName+"` of value `"+String(propValue)+"` "+("supplied to `"+componentName+"`, expected one of "+valuesString+"."))}return createChainableTypeChecker(validate)}function createObjectOfTypeChecker(typeChecker){function validate(props,propName,componentName,location,propFullName){if(typeof typeChecker!=="function")return new PropTypeError("Property `"+propFullName+"` of component `"+componentName+"` has invalid PropType notation inside objectOf.");var propValue=props[propName],propType=getPropType(propValue);if(propType!=="object")return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+propType+"` supplied to `"+componentName+"`, expected an object."));for(var key in propValue)if(has(propValue,key)){var error=typeChecker(propValue,key,componentName,location,propFullName+"."+key,ReactPropTypesSecret);if(error instanceof Error)return error}return null}return createChainableTypeChecker(validate)}function createUnionTypeChecker(arrayOfTypeCheckers){if(!Array.isArray(arrayOfTypeCheckers))return printWarning("Invalid argument supplied to oneOfType, expected an instance of array."),emptyFunctionThatReturnsNull;for(var i=0;i<arrayOfTypeCheckers.length;i++){var checker=arrayOfTypeCheckers[i];if(typeof checker!=="function")return printWarning("Invalid argument supplied to oneOfType. Expected an array of check functions, but received "+getPostfixForTypeWarning(checker)+" at index "+i+"."),emptyFunctionThatReturnsNull}function validate(props,propName,componentName,location,propFullName){var expectedTypes=[];for(var i=0;i<arrayOfTypeCheckers.length;i++){var checker=arrayOfTypeCheckers[i],checkerResult=checker(props,propName,componentName,location,propFullName,ReactPropTypesSecret);if(checkerResult==null)return null;if(checkerResult.data&&has(checkerResult.data,"expectedType"))expectedTypes.push(checkerResult.data.expectedType)}var expectedTypesMessage=expectedTypes.length>0?", expected one of type ["+expectedTypes.join(", ")+"]":"";return new PropTypeError("Invalid "+location+" `"+propFullName+"` supplied to "+("`"+componentName+"`"+expectedTypesMessage+"."))}return createChainableTypeChecker(validate)}function createNodeChecker(){function validate(props,propName,componentName,location,propFullName){if(!isNode(props[propName]))return new PropTypeError("Invalid "+location+" `"+propFullName+"` supplied to "+("`"+componentName+"`, expected a ReactNode."));return null}return createChainableTypeChecker(validate)}function invalidValidatorError(componentName,location,propFullName,key,type){return new PropTypeError((componentName||"React class")+": "+location+" type `"+propFullName+"."+key+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+type+"`.")}function createShapeTypeChecker(shapeTypes){function validate(props,propName,componentName,location,propFullName){var propValue=props[propName],propType=getPropType(propValue);if(propType!=="object")return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+propType+"` "+("supplied to `"+componentName+"`, expected `object`."));for(var key in shapeTypes){var checker=shapeTypes[key];if(typeof checker!=="function")return invalidValidatorError(componentName,location,propFullName,key,getPreciseType(checker));var error=checker(propValue,key,componentName,location,propFullName+"."+key,ReactPropTypesSecret);if(error)return error}return null}return createChainableTypeChecker(validate)}function createStrictShapeTypeChecker(shapeTypes){function validate(props,propName,componentName,location,propFullName){var propValue=props[propName],propType=getPropType(propValue);if(propType!=="object")return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+propType+"` "+("supplied to `"+componentName+"`, expected `object`."));var allKeys=assign({},props[propName],shapeTypes);for(var key in allKeys){var checker=shapeTypes[key];if(has(shapeTypes,key)&&typeof checker!=="function")return invalidValidatorError(componentName,location,propFullName,key,getPreciseType(checker));if(!checker)return new PropTypeError("Invalid "+location+" `"+propFullName+"` key `"+key+"` supplied to `"+componentName+"`.\nBad object: "+JSON.stringify(props[propName],null," ")+`
|
|
2
|
+
import{clsx_default,helpersRegistry,parse_default,formatRgb,SX_PROP,catalogFromManifest,helperSourcePath}from"./chunk-88eqqdk1.js";import{require_react_is_development,require_object_assign,require_emotion_serialize_development_cjs,$_default,import_emotion_react_development_cjs,$_default2,$_default3}from"./chunk-js6mz7h1.js";import{resolveColors,DEFAULT_TYPESET_NAME,typesetScale}from"./chunk-nte0t7v3.js";import{_objectWithoutPropertiesLoose,_extends,_assertThisInitialized,_setPrototypeOf}from"./chunk-h6gchare.js";import{resolveProviderSrcDir}from"./chunk-fjbzk4sw.js";import{require_react_jsx_runtime_development}from"./chunk-c6hywdvq.js";import{require_react_development,require_react_dom}from"./chunk-c4fym47a.js";import{__toESM,__commonJS}from"./chunk-2smsg2ct.js";import{MUI_VERSION}from"./chunk-mzhdrawd.js";var require_ReactPropTypesSecret=__commonJS(function(exports,module){var ReactPropTypesSecret="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";module.exports=ReactPropTypesSecret});var require_has=__commonJS(function(exports,module){module.exports=Function.call.bind(Object.prototype.hasOwnProperty)});var require_checkPropTypes=__commonJS(function(exports,module){var printWarning=function(){};ReactPropTypesSecret=require_ReactPropTypesSecret(),loggedTypeFailures={},has=require_has(),printWarning=function(text){var message="Warning: "+text;if(typeof console<"u")console.error(message);try{throw Error(message)}catch(x){}};var ReactPropTypesSecret,loggedTypeFailures,has;function checkPropTypes(typeSpecs,values,location,componentName,getStack){for(var typeSpecName in typeSpecs)if(has(typeSpecs,typeSpecName)){var error;try{if(typeof typeSpecs[typeSpecName]!=="function"){var err=Error((componentName||"React class")+": "+location+" type `"+typeSpecName+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof typeSpecs[typeSpecName]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw err.name="Invariant Violation",err}error=typeSpecs[typeSpecName](values,typeSpecName,componentName,location,null,ReactPropTypesSecret)}catch(ex){error=ex}if(error&&!(error instanceof Error))printWarning((componentName||"React class")+": type specification of "+location+" `"+typeSpecName+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof error+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).");if(error instanceof Error&&!(error.message in loggedTypeFailures)){loggedTypeFailures[error.message]=!0;var stack=getStack?getStack():"";printWarning("Failed "+location+" type: "+error.message+(stack!=null?stack:""))}}}checkPropTypes.resetWarningCache=function(){loggedTypeFailures={}};module.exports=checkPropTypes});var require_factoryWithTypeCheckers=__commonJS(function(exports,module){var ReactIs=__toESM(require_react_is_development()),assign=require_object_assign(),ReactPropTypesSecret=require_ReactPropTypesSecret(),has=require_has(),checkPropTypes=require_checkPropTypes(),printWarning=function(){};printWarning=function(text){var message="Warning: "+text;if(typeof console<"u")console.error(message);try{throw Error(message)}catch(x){}};function emptyFunctionThatReturnsNull(){return null}module.exports=function(isValidElement,throwOnDirectAccess){var ITERATOR_SYMBOL=typeof Symbol==="function"&&Symbol.iterator,FAUX_ITERATOR_SYMBOL="@@iterator";function getIteratorFn(maybeIterable){var iteratorFn=maybeIterable&&(ITERATOR_SYMBOL&&maybeIterable[ITERATOR_SYMBOL]||maybeIterable[FAUX_ITERATOR_SYMBOL]);if(typeof iteratorFn==="function")return iteratorFn}var ANONYMOUS="<<anonymous>>",ReactPropTypes={array:createPrimitiveTypeChecker("array"),bigint:createPrimitiveTypeChecker("bigint"),bool:createPrimitiveTypeChecker("boolean"),func:createPrimitiveTypeChecker("function"),number:createPrimitiveTypeChecker("number"),object:createPrimitiveTypeChecker("object"),string:createPrimitiveTypeChecker("string"),symbol:createPrimitiveTypeChecker("symbol"),any:createAnyTypeChecker(),arrayOf:createArrayOfTypeChecker,element:createElementTypeChecker(),elementType:createElementTypeTypeChecker(),instanceOf:createInstanceTypeChecker,node:createNodeChecker(),objectOf:createObjectOfTypeChecker,oneOf:createEnumTypeChecker,oneOfType:createUnionTypeChecker,shape:createShapeTypeChecker,exact:createStrictShapeTypeChecker};function is(x,y){if(x===y)return x!==0||1/x===1/y;else return x!==x&&y!==y}function PropTypeError(message,data){this.message=message,this.data=data&&typeof data==="object"?data:{},this.stack=""}PropTypeError.prototype=Error.prototype;function createChainableTypeChecker(validate){var manualPropTypeCallCache={},manualPropTypeWarningCount=0;function checkType(isRequired,props,propName,componentName,location,propFullName,secret){if(componentName=componentName||ANONYMOUS,propFullName=propFullName||propName,secret!==ReactPropTypesSecret){if(throwOnDirectAccess){var err=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw err.name="Invariant Violation",err}else if(typeof console<"u"){var cacheKey=componentName+":"+propName;if(!manualPropTypeCallCache[cacheKey]&&manualPropTypeWarningCount<3)printWarning("You are manually calling a React.PropTypes validation function for the `"+propFullName+"` prop on `"+componentName+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),manualPropTypeCallCache[cacheKey]=!0,manualPropTypeWarningCount++}}if(props[propName]==null){if(isRequired){if(props[propName]===null)return new PropTypeError("The "+location+" `"+propFullName+"` is marked as required "+("in `"+componentName+"`, but its value is `null`."));return new PropTypeError("The "+location+" `"+propFullName+"` is marked as required in "+("`"+componentName+"`, but its value is `undefined`."))}return null}else return validate(props,propName,componentName,location,propFullName)}var chainedCheckType=checkType.bind(null,!1);return chainedCheckType.isRequired=checkType.bind(null,!0),chainedCheckType}function createPrimitiveTypeChecker(expectedType){function validate(props,propName,componentName,location,propFullName,secret){var propValue=props[propName],propType=getPropType(propValue);if(propType!==expectedType){var preciseType=getPreciseType(propValue);return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+preciseType+"` supplied to `"+componentName+"`, expected ")+("`"+expectedType+"`."),{expectedType})}return null}return createChainableTypeChecker(validate)}function createAnyTypeChecker(){return createChainableTypeChecker(emptyFunctionThatReturnsNull)}function createArrayOfTypeChecker(typeChecker){function validate(props,propName,componentName,location,propFullName){if(typeof typeChecker!=="function")return new PropTypeError("Property `"+propFullName+"` of component `"+componentName+"` has invalid PropType notation inside arrayOf.");var propValue=props[propName];if(!Array.isArray(propValue)){var propType=getPropType(propValue);return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+propType+"` supplied to `"+componentName+"`, expected an array."))}for(var i=0;i<propValue.length;i++){var error=typeChecker(propValue,i,componentName,location,propFullName+"["+i+"]",ReactPropTypesSecret);if(error instanceof Error)return error}return null}return createChainableTypeChecker(validate)}function createElementTypeChecker(){function validate(props,propName,componentName,location,propFullName){var propValue=props[propName];if(!isValidElement(propValue)){var propType=getPropType(propValue);return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+propType+"` supplied to `"+componentName+"`, expected a single ReactElement."))}return null}return createChainableTypeChecker(validate)}function createElementTypeTypeChecker(){function validate(props,propName,componentName,location,propFullName){var propValue=props[propName];if(!ReactIs.isValidElementType(propValue)){var propType=getPropType(propValue);return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+propType+"` supplied to `"+componentName+"`, expected a single ReactElement type."))}return null}return createChainableTypeChecker(validate)}function createInstanceTypeChecker(expectedClass){function validate(props,propName,componentName,location,propFullName){if(!(props[propName]instanceof expectedClass)){var expectedClassName=expectedClass.name||ANONYMOUS,actualClassName=getClassName(props[propName]);return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+actualClassName+"` supplied to `"+componentName+"`, expected ")+("instance of `"+expectedClassName+"`."))}return null}return createChainableTypeChecker(validate)}function createEnumTypeChecker(expectedValues){if(!Array.isArray(expectedValues)){if(arguments.length>1)printWarning("Invalid arguments supplied to oneOf, expected an array, got "+arguments.length+" arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).");else printWarning("Invalid argument supplied to oneOf, expected an array.");return emptyFunctionThatReturnsNull}function validate(props,propName,componentName,location,propFullName){var propValue=props[propName];for(var i=0;i<expectedValues.length;i++)if(is(propValue,expectedValues[i]))return null;var valuesString=JSON.stringify(expectedValues,function(key,value){var type=getPreciseType(value);if(type==="symbol")return String(value);return value});return new PropTypeError("Invalid "+location+" `"+propFullName+"` of value `"+String(propValue)+"` "+("supplied to `"+componentName+"`, expected one of "+valuesString+"."))}return createChainableTypeChecker(validate)}function createObjectOfTypeChecker(typeChecker){function validate(props,propName,componentName,location,propFullName){if(typeof typeChecker!=="function")return new PropTypeError("Property `"+propFullName+"` of component `"+componentName+"` has invalid PropType notation inside objectOf.");var propValue=props[propName],propType=getPropType(propValue);if(propType!=="object")return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type "+("`"+propType+"` supplied to `"+componentName+"`, expected an object."));for(var key in propValue)if(has(propValue,key)){var error=typeChecker(propValue,key,componentName,location,propFullName+"."+key,ReactPropTypesSecret);if(error instanceof Error)return error}return null}return createChainableTypeChecker(validate)}function createUnionTypeChecker(arrayOfTypeCheckers){if(!Array.isArray(arrayOfTypeCheckers))return printWarning("Invalid argument supplied to oneOfType, expected an instance of array."),emptyFunctionThatReturnsNull;for(var i=0;i<arrayOfTypeCheckers.length;i++){var checker=arrayOfTypeCheckers[i];if(typeof checker!=="function")return printWarning("Invalid argument supplied to oneOfType. Expected an array of check functions, but received "+getPostfixForTypeWarning(checker)+" at index "+i+"."),emptyFunctionThatReturnsNull}function validate(props,propName,componentName,location,propFullName){var expectedTypes=[];for(var i=0;i<arrayOfTypeCheckers.length;i++){var checker=arrayOfTypeCheckers[i],checkerResult=checker(props,propName,componentName,location,propFullName,ReactPropTypesSecret);if(checkerResult==null)return null;if(checkerResult.data&&has(checkerResult.data,"expectedType"))expectedTypes.push(checkerResult.data.expectedType)}var expectedTypesMessage=expectedTypes.length>0?", expected one of type ["+expectedTypes.join(", ")+"]":"";return new PropTypeError("Invalid "+location+" `"+propFullName+"` supplied to "+("`"+componentName+"`"+expectedTypesMessage+"."))}return createChainableTypeChecker(validate)}function createNodeChecker(){function validate(props,propName,componentName,location,propFullName){if(!isNode(props[propName]))return new PropTypeError("Invalid "+location+" `"+propFullName+"` supplied to "+("`"+componentName+"`, expected a ReactNode."));return null}return createChainableTypeChecker(validate)}function invalidValidatorError(componentName,location,propFullName,key,type){return new PropTypeError((componentName||"React class")+": "+location+" type `"+propFullName+"."+key+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+type+"`.")}function createShapeTypeChecker(shapeTypes){function validate(props,propName,componentName,location,propFullName){var propValue=props[propName],propType=getPropType(propValue);if(propType!=="object")return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+propType+"` "+("supplied to `"+componentName+"`, expected `object`."));for(var key in shapeTypes){var checker=shapeTypes[key];if(typeof checker!=="function")return invalidValidatorError(componentName,location,propFullName,key,getPreciseType(checker));var error=checker(propValue,key,componentName,location,propFullName+"."+key,ReactPropTypesSecret);if(error)return error}return null}return createChainableTypeChecker(validate)}function createStrictShapeTypeChecker(shapeTypes){function validate(props,propName,componentName,location,propFullName){var propValue=props[propName],propType=getPropType(propValue);if(propType!=="object")return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+propType+"` "+("supplied to `"+componentName+"`, expected `object`."));var allKeys=assign({},props[propName],shapeTypes);for(var key in allKeys){var checker=shapeTypes[key];if(has(shapeTypes,key)&&typeof checker!=="function")return invalidValidatorError(componentName,location,propFullName,key,getPreciseType(checker));if(!checker)return new PropTypeError("Invalid "+location+" `"+propFullName+"` key `"+key+"` supplied to `"+componentName+"`.\nBad object: "+JSON.stringify(props[propName],null," ")+`
|
|
3
3
|
Valid keys: `+JSON.stringify(Object.keys(shapeTypes),null," "));var error=checker(propValue,key,componentName,location,propFullName+"."+key,ReactPropTypesSecret);if(error)return error}return null}return createChainableTypeChecker(validate)}function isNode(propValue){switch(typeof propValue){case"number":case"string":case"undefined":return!0;case"boolean":return!propValue;case"object":if(Array.isArray(propValue))return propValue.every(isNode);if(propValue===null||isValidElement(propValue))return!0;var iteratorFn=getIteratorFn(propValue);if(iteratorFn){var iterator=iteratorFn.call(propValue),step;if(iteratorFn!==propValue.entries){while(!(step=iterator.next()).done)if(!isNode(step.value))return!1}else while(!(step=iterator.next()).done){var entry=step.value;if(entry){if(!isNode(entry[1]))return!1}}}else return!1;return!0;default:return!1}}function isSymbol(propType,propValue){if(propType==="symbol")return!0;if(!propValue)return!1;if(propValue["@@toStringTag"]==="Symbol")return!0;if(typeof Symbol==="function"&&propValue instanceof Symbol)return!0;return!1}function getPropType(propValue){var propType=typeof propValue;if(Array.isArray(propValue))return"array";if(propValue instanceof RegExp)return"object";if(isSymbol(propType,propValue))return"symbol";return propType}function getPreciseType(propValue){if(typeof propValue>"u"||propValue===null)return""+propValue;var propType=getPropType(propValue);if(propType==="object"){if(propValue instanceof Date)return"date";else if(propValue instanceof RegExp)return"regexp"}return propType}function getPostfixForTypeWarning(value){var type=getPreciseType(value);switch(type){case"array":case"object":return"an "+type;case"boolean":case"date":case"regexp":return"a "+type;default:return type}}function getClassName(propValue){if(!propValue.constructor||!propValue.constructor.name)return ANONYMOUS;return propValue.constructor.name}return ReactPropTypes.checkPropTypes=checkPropTypes,ReactPropTypes.resetWarningCache=checkPropTypes.resetWarningCache,ReactPropTypes.PropTypes=ReactPropTypes,ReactPropTypes}});var require_prop_types=__commonJS(function(exports,module){var ReactIs=__toESM(require_react_is_development());throwOnDirectAccess=!0,module.exports=require_factoryWithTypeCheckers()(ReactIs.isElement,throwOnDirectAccess);var throwOnDirectAccess});var require_react_is_development2=__commonJS(function(exports){(function(){function typeOf(object){if(typeof object==="object"&&object!==null){var $$typeof=object.$$typeof;switch($$typeof){case REACT_ELEMENT_TYPE:switch(object=object.type,object){case REACT_FRAGMENT_TYPE:case REACT_PROFILER_TYPE:case REACT_STRICT_MODE_TYPE:case REACT_SUSPENSE_TYPE:case REACT_SUSPENSE_LIST_TYPE:case REACT_VIEW_TRANSITION_TYPE:return object;default:switch(object=object&&object.$$typeof,object){case REACT_CONTEXT_TYPE:case REACT_FORWARD_REF_TYPE:case REACT_LAZY_TYPE:case REACT_MEMO_TYPE:return object;case REACT_CONSUMER_TYPE:return object;default:return $$typeof}}case REACT_PORTAL_TYPE:return $$typeof}}}var REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element"),REACT_PORTAL_TYPE=Symbol.for("react.portal"),REACT_FRAGMENT_TYPE=Symbol.for("react.fragment"),REACT_STRICT_MODE_TYPE=Symbol.for("react.strict_mode"),REACT_PROFILER_TYPE=Symbol.for("react.profiler"),REACT_CONSUMER_TYPE=Symbol.for("react.consumer"),REACT_CONTEXT_TYPE=Symbol.for("react.context"),REACT_FORWARD_REF_TYPE=Symbol.for("react.forward_ref"),REACT_SUSPENSE_TYPE=Symbol.for("react.suspense"),REACT_SUSPENSE_LIST_TYPE=Symbol.for("react.suspense_list"),REACT_MEMO_TYPE=Symbol.for("react.memo"),REACT_LAZY_TYPE=Symbol.for("react.lazy"),REACT_VIEW_TRANSITION_TYPE=Symbol.for("react.view_transition"),REACT_CLIENT_REFERENCE=Symbol.for("react.client.reference");exports.ContextConsumer=REACT_CONSUMER_TYPE,exports.ContextProvider=REACT_CONTEXT_TYPE,exports.Element=REACT_ELEMENT_TYPE,exports.ForwardRef=REACT_FORWARD_REF_TYPE,exports.Fragment=REACT_FRAGMENT_TYPE,exports.Lazy=REACT_LAZY_TYPE,exports.Memo=REACT_MEMO_TYPE,exports.Portal=REACT_PORTAL_TYPE,exports.Profiler=REACT_PROFILER_TYPE,exports.StrictMode=REACT_STRICT_MODE_TYPE,exports.Suspense=REACT_SUSPENSE_TYPE,exports.SuspenseList=REACT_SUSPENSE_LIST_TYPE,exports.isContextConsumer=function(object){return typeOf(object)===REACT_CONSUMER_TYPE},exports.isContextProvider=function(object){return typeOf(object)===REACT_CONTEXT_TYPE},exports.isElement=function(object){return typeof object==="object"&&object!==null&&object.$$typeof===REACT_ELEMENT_TYPE},exports.isForwardRef=function(object){return typeOf(object)===REACT_FORWARD_REF_TYPE},exports.isFragment=function(object){return typeOf(object)===REACT_FRAGMENT_TYPE},exports.isLazy=function(object){return typeOf(object)===REACT_LAZY_TYPE},exports.isMemo=function(object){return typeOf(object)===REACT_MEMO_TYPE},exports.isPortal=function(object){return typeOf(object)===REACT_PORTAL_TYPE},exports.isProfiler=function(object){return typeOf(object)===REACT_PROFILER_TYPE},exports.isStrictMode=function(object){return typeOf(object)===REACT_STRICT_MODE_TYPE},exports.isSuspense=function(object){return typeOf(object)===REACT_SUSPENSE_TYPE},exports.isSuspenseList=function(object){return typeOf(object)===REACT_SUSPENSE_LIST_TYPE},exports.isValidElementType=function(type){return typeof type==="string"||typeof type==="function"||type===REACT_FRAGMENT_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_CONTEXT_TYPE||type.$$typeof===REACT_CONSUMER_TYPE||type.$$typeof===REACT_FORWARD_REF_TYPE||type.$$typeof===REACT_CLIENT_REFERENCE||type.getModuleId!==void 0)?!0:!1},exports.typeOf=typeOf})()});import{dirname,join}from"path";import{fileURLToPath}from"url";var MUI_INTRO=["**This folder targets Material UI.** Components are real MUI: `Box`/`Stack`/`Container`/`Paper` for layout, `Card`/`CardContent`/`CardHeader`/`CardActions`, `Typography` (ALL text \u2014 pick `variant` for the type scale), `Button`/`IconButton`, `TextField`, `Chip`, `Divider`, `Avatar`, `List`/`ListItem`, `Table*`, `Tabs`/`Tab`, `Alert`, `Tooltip`, and the overlay surface `Dialog`/`Menu`/`Popover`/`Drawer`/`Snackbar` (rendered open + inline in design mode). Call `list_components` for the full set and per-component `example` props.","",'**Style through `sx`.** `update_props { style: { display: "flex", alignItems: "center", gap: 2, p: 3, color: "primary.main" } }` \u2014 an object of MUI system props, where spacing is theme units (`p: 2` = 16px). It merges shallowly; an inner `null` drops a key, `style: null` clears. `emit_code` emits `<Component sx={{\u2026}} />` importing from `@mui/material`; `emit_theme` emits a `createTheme(...)` module. Tailwind utility diagnostics do not apply here \u2014 style via `sx` plus the shared theme tokens from `get_theme`, which project onto MUI.',""];var sx={name:"sx",type:"SxProps | undefined",optional:!0,control:"string"},children={name:"children",type:"ReactNode",optional:!0,control:"string"},enumProp=(name,values,defaultValue)=>({name,type:values.map((v)=>`"${v}"`).join(" | "),optional:!0,control:"enum",enumValues:values,defaultValue});function ui(id,props,notes,example){return{id,category:"ui",source:"mui",props:[...props,sx],designModeNotes:notes,example}}var className={name:"className",type:"string | undefined",optional:!0,control:"string"};function helper(id,props,notes,example){return{id,category:"ui",source:"velloo",props:[...props,className],designModeNotes:notes,example}}var MUI_MANIFEST=[ui("Box",[children],"Generic layout primitive; style via sx."),ui("Stack",[children,enumProp("direction",["row","column"],"column")],"Flex layout; set spacing via sx or the spacing prop."),ui("Container",[children,enumProp("maxWidth",["xs","sm","md","lg","xl"],"lg")],"Centers + max-widths content."),ui("Paper",[children,enumProp("variant",["elevation","outlined"],"elevation")]),ui("Card",[children,enumProp("variant",["elevation","outlined"],"elevation")]),ui("CardContent",[children]),ui("CardHeader",[{name:"title",type:"ReactNode",optional:!0,control:"string"},{name:"subheader",type:"ReactNode",optional:!0,control:"string"}]),ui("CardActions",[children]),ui("Button",[children,enumProp("variant",["text","outlined","contained"],"text"),enumProp("color",["primary","secondary","success","error","inherit"],"primary"),enumProp("size",["small","medium","large"],"medium")],"Action button.",{variant:"contained",color:"primary",children:"Submit"}),ui("Typography",[children,enumProp("variant",["h1","h2","h3","h4","h5","h6","subtitle1","subtitle2","body1","body2","caption","overline"],"body1"),enumProp("color",["text.primary","text.secondary","primary","error"])],"All text. Pick variant for the type scale; this is MUI's Heading + Text.",{variant:"h4",children:"Team analytics"}),ui("TextField",[enumProp("variant",["outlined","filled","standard"],"outlined"),{name:"label",type:"string",optional:!0,control:"string"},{name:"placeholder",type:"string",optional:!0,control:"string"}]),ui("Chip",[{name:"label",type:"ReactNode",optional:!0,control:"string"},enumProp("variant",["filled","outlined"],"filled"),enumProp("color",["default","primary","success","warning","error"],"default"),enumProp("size",["small","medium"],"medium")]),ui("Divider",[]),ui("Avatar",[children,{name:"src",type:"string",optional:!0,control:"string"}]),ui("LinearProgress",[{name:"value",type:"number",optional:!0,control:"number"},enumProp("variant",["determinate","indeterminate"],"indeterminate")]),ui("AppBar",[children,enumProp("position",["fixed","static","sticky"],"fixed"),enumProp("color",["primary","default","transparent","inherit"],"primary")]),ui("Toolbar",[children]),ui("IconButton",[children,enumProp("size",["small","medium","large"],"medium")]),ui("Link",[children,{name:"href",type:"string",optional:!0,control:"string"}]),ui("List",[children]),ui("ListItem",[children]),ui("ListItemText",[{name:"primary",type:"ReactNode",optional:!0,control:"string"},{name:"secondary",type:"ReactNode",optional:!0,control:"string"}]),ui("Table",[children]),ui("TableHead",[children]),ui("TableBody",[children]),ui("TableRow",[children]),ui("TableCell",[children,enumProp("align",["left","center","right"],"left")]),ui("Tabs",[children,{name:"value",type:"number | string",optional:!0,control:"string"}]),ui("Tab",[{name:"label",type:"ReactNode",optional:!0,control:"string"}]),ui("Badge",[children,{name:"badgeContent",type:"ReactNode",optional:!0,control:"string"}]),ui("Checkbox",[{name:"checked",type:"boolean",optional:!0,control:"boolean"}]),ui("Switch",[{name:"checked",type:"boolean",optional:!0,control:"boolean"}]),ui("Select",[children,enumProp("variant",["outlined","filled","standard"],"outlined")]),ui("MenuItem",[children,{name:"value",type:"string | number",optional:!0,control:"string"}]),ui("Tooltip",[children,{name:"title",type:"ReactNode",optional:!0,control:"string"}]),ui("Alert",[children,enumProp("severity",["success","info","warning","error"],"success")]),ui("Dialog",[children,enumProp("maxWidth",["xs","sm","md","lg","xl"],"sm")],"Modal dialog surface \u2014 renders open + inline in design mode. Fill it with DialogTitle / DialogContent / DialogActions.",{maxWidth:"sm"}),ui("DialogTitle",[children],"The dialog's heading row."),ui("DialogContent",[children],"The dialog's body."),ui("DialogContentText",[children],"Secondary text inside DialogContent."),ui("DialogActions",[children],"The dialog's button row (right-aligned)."),ui("Menu",[children],"A menu surface holding MenuItems \u2014 renders open + inline in design mode."),ui("Popover",[children],"A popover surface \u2014 renders open + inline in design mode."),ui("Drawer",[children],"A side panel \u2014 renders inline as a fixed-width column in design mode."),ui("Snackbar",[children,{name:"message",type:"ReactNode",optional:!0,control:"string"}],"A toast \u2014 renders inline as a dark pill in design mode. Use `message` or children.",{message:"Saved"}),helper("Icon",[{name:"name",type:"string",optional:!1,control:"icon"},{name:"size",type:"number",optional:!0,control:"number"}],"A lucide icon \u2014 MUI has no bundled icon set. Set the pixel `size` prop (not Tailwind). `name` is a lucide id (PascalCase or kebab). Emits a `lucide-react` import.",{name:"ArrowRight",size:20}),helper("Image",[{name:"src",type:"string",optional:!1,control:"string"},{name:"alt",type:"string",optional:!1,control:"string"}],"An image. Use velloo assets (`/assets/\u2026`) or a URL."),helper("Placeholder",[{name:"label",type:"string",optional:!0,control:"string"}],"A labeled placeholder box for imagery you haven't authored yet (avatars, hero shots)."),helper("SVG",[{name:"content",type:"string",optional:!1,control:"string"},{name:"viewBox",type:"string",optional:!1,control:"string"}],"Raw inline SVG markup."),helper("Layer",[children],"An absolutely-positioned overlay layer for stacked composition."),helper("Gradient",[{name:"from",type:"string",optional:!0,control:"color"}],"A gradient fill block."),helper("Prose",[children,{name:"preset",type:"string",optional:!0,control:"string"},{name:"as",type:"string",optional:!0,control:"string"}],"A long-form content region. Everything inside \u2014 Typography, headings, lists, quotes, code, tables \u2014 picks up the theme typeset's proportions and vertical rhythm automatically. `preset` selects a named typeset (see set_typeset). Reach for this for articles, docs, and marketing copy instead of setting sizes block by block.",{as:"article"})];var React49=__toESM(require_react_development()),import_prop_types26=__toESM(require_prop_types());function composeClasses(slots,getUtilityClass,classes=void 0){let output={};for(let slotName in slots){let slot=slots[slotName],buffer="",start=!0;for(let i=0;i<slot.length;i+=1){let value=slot[i];if(value){if(buffer+=(start===!0?"":" ")+getUtilityClass(value),start=!1,classes&&classes[value])buffer+=" "+classes[value]}}output[slotName]=buffer}return output}function clamp(val,min=Number.MIN_SAFE_INTEGER,max=Number.MAX_SAFE_INTEGER){return Math.max(min,Math.min(val,max))}var clamp_default=clamp;function clampWrapper(value,min=0,max=1){if(value<min||value>max)console.error(`MUI: The value provided ${value} is out of range [${min}, ${max}].`);return clamp_default(value,min,max)}function hexToRgb(color){color=color.slice(1);let re=new RegExp(`.{1,${color.length>=6?2:1}}`,"g"),colors=color.match(re);if(colors&&colors[0].length===1)colors=colors.map((n)=>n+n);if(color.length!==color.trim().length)console.error(`MUI: The color: "${color}" is invalid. Make sure the color input doesn't contain leading/trailing space.`);return colors?`rgb${colors.length===4?"a":""}(${colors.map((n,index)=>index<3?parseInt(n,16):Math.round(parseInt(n,16)/255*1000)/1000).join(", ")})`:""}function decomposeColor(color){if(color.type)return color;if(color.charAt(0)==="#")return decomposeColor(hexToRgb(color));let marker=color.indexOf("("),type=color.substring(0,marker);if(!["rgb","rgba","hsl","hsla","color"].includes(type))throw Error(`MUI: Unsupported \`${color}\` color.
|
|
4
4
|
The following formats are supported: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color().`);let values=color.substring(marker+1,color.length-1),colorSpace;if(type==="color"){if(values=values.split(" "),colorSpace=values.shift(),values.length===4&&values[3].charAt(0)==="/")values[3]=values[3].slice(1);if(!["srgb","display-p3","a98-rgb","prophoto-rgb","rec-2020"].includes(colorSpace))throw Error(`MUI: unsupported \`${colorSpace}\` color space.
|
|
5
5
|
The following color spaces are supported: srgb, display-p3, a98-rgb, prophoto-rgb, rec-2020.`)}else values=values.split(",");return values=values.map((value)=>parseFloat(value)),{type,values,colorSpace}}var colorChannel=(color)=>{let decomposedColor=decomposeColor(color);return decomposedColor.values.slice(0,3).map((val,idx)=>decomposedColor.type.includes("hsl")&&idx!==0?`${val}%`:val).join(" ")},private_safeColorChannel=(color,warning)=>{try{return colorChannel(color)}catch(error){if(warning)console.warn(warning);return color}};function recomposeColor(color){let{type,colorSpace}=color,{values}=color;if(type.includes("rgb"))values=values.map((n,i)=>i<3?parseInt(n,10):n);else if(type.includes("hsl"))values[1]=`${values[1]}%`,values[2]=`${values[2]}%`;if(type.includes("color"))values=`${colorSpace} ${values.join(" ")}`;else values=`${values.join(", ")}`;return`${type}(${values})`}function hslToRgb(color){color=decomposeColor(color);let{values}=color,h=values[0],s=values[1]/100,l=values[2]/100,a=s*Math.min(l,1-l),f=(n,k=(n+h/30)%12)=>l-a*Math.max(Math.min(k-3,9-k,1),-1),type="rgb",rgb=[Math.round(f(0)*255),Math.round(f(8)*255),Math.round(f(4)*255)];if(color.type==="hsla")type+="a",rgb.push(values[3]);return recomposeColor({type,values:rgb})}function getLuminance(color){color=decomposeColor(color);let rgb=color.type==="hsl"||color.type==="hsla"?decomposeColor(hslToRgb(color)).values:color.values;return rgb=rgb.map((val)=>{if(color.type!=="color")val/=255;return val<=0.03928?val/12.92:((val+0.055)/1.055)**2.4}),Number((0.2126*rgb[0]+0.7152*rgb[1]+0.0722*rgb[2]).toFixed(3))}function getContrastRatio(foreground,background){let lumA=getLuminance(foreground),lumB=getLuminance(background);return(Math.max(lumA,lumB)+0.05)/(Math.min(lumA,lumB)+0.05)}function alpha(color,value){if(color=decomposeColor(color),value=clampWrapper(value),color.type==="rgb"||color.type==="hsl")color.type+="a";if(color.type==="color")color.values[3]=`/${value}`;else color.values[3]=value;return recomposeColor(color)}function private_safeAlpha(color,value,warning){try{return alpha(color,value)}catch(error){if(warning)console.warn(warning);return color}}function darken(color,coefficient){if(color=decomposeColor(color),coefficient=clampWrapper(coefficient),color.type.includes("hsl"))color.values[2]*=1-coefficient;else if(color.type.includes("rgb")||color.type.includes("color"))for(let i=0;i<3;i+=1)color.values[i]*=1-coefficient;return recomposeColor(color)}function private_safeDarken(color,coefficient,warning){try{return darken(color,coefficient)}catch(error){if(warning)console.warn(warning);return color}}function lighten(color,coefficient){if(color=decomposeColor(color),coefficient=clampWrapper(coefficient),color.type.includes("hsl"))color.values[2]+=(100-color.values[2])*coefficient;else if(color.type.includes("rgb"))for(let i=0;i<3;i+=1)color.values[i]+=(255-color.values[i])*coefficient;else if(color.type.includes("color"))for(let i=0;i<3;i+=1)color.values[i]+=(1-color.values[i])*coefficient;return recomposeColor(color)}function private_safeLighten(color,coefficient,warning){try{return lighten(color,coefficient)}catch(error){if(warning)console.warn(warning);return color}}function emphasize(color,coefficient=0.15){return getLuminance(color)>0.5?darken(color,coefficient):lighten(color,coefficient)}function private_safeEmphasize(color,coefficient,warning){try{return emphasize(color,coefficient)}catch(error){if(warning)console.warn(warning);return color}}var React27=__toESM(require_react_development());function capitalize(string){if(typeof string!=="string")throw Error("MUI: `capitalize(string)` expects a string argument.");return string.charAt(0).toUpperCase()+string.slice(1)}var React=__toESM(require_react_development()),import_react_is=__toESM(require_react_is_development2());function isPlainObject(item){if(typeof item!=="object"||item===null)return!1;let prototype=Object.getPrototypeOf(item);return(prototype===null||prototype===Object.prototype||Object.getPrototypeOf(prototype)===null)&&!(Symbol.toStringTag in item)&&!(Symbol.iterator in item)}function deepClone(source){if(React.isValidElement(source)||import_react_is.isValidElementType(source)||!isPlainObject(source))return source;let output={};return Object.keys(source).forEach((key)=>{output[key]=deepClone(source[key])}),output}function deepmerge(target,source,options={clone:!0}){let output=options.clone?{...target}:target;if(isPlainObject(target)&&isPlainObject(source))Object.keys(source).forEach((key)=>{if(React.isValidElement(source[key])||import_react_is.isValidElementType(source[key]))output[key]=source[key];else if(isPlainObject(source[key])&&Object.prototype.hasOwnProperty.call(target,key)&&isPlainObject(target[key]))output[key]=deepmerge(target[key],source[key],options);else if(options.clone)output[key]=isPlainObject(source[key])?deepClone(source[key]):source[key];else output[key]=source[key]});return output}function merge(acc,item){if(!item)return acc;return deepmerge(acc,item,{clone:!1})}var merge_default=merge;var import_prop_types=__toESM(require_prop_types()),responsivePropType=import_prop_types.default.oneOfType([import_prop_types.default.number,import_prop_types.default.string,import_prop_types.default.object,import_prop_types.default.array]),responsivePropType_default=responsivePropType;function sortContainerQueries(theme,css){if(!theme.containerQueries)return css;let sorted=Object.keys(css).filter((key)=>key.startsWith("@container")).sort((a,b)=>{let regex=/min-width:\s*([0-9.]+)/;return+(a.match(regex)?.[1]||0)-+(b.match(regex)?.[1]||0)});if(!sorted.length)return css;return sorted.reduce((acc,key)=>{let value=css[key];return delete acc[key],acc[key]=value,acc},{...css})}function isCqShorthand(breakpointKeys,value){return value==="@"||value.startsWith("@")&&(breakpointKeys.some((key)=>value.startsWith(`@${key}`))||!!value.match(/^@\d/))}function getContainerQuery(theme,shorthand){let matches=shorthand.match(/^@([^/]+)?\/?(.+)?$/);if(!matches)throw Error(`MUI: The provided shorthand ${`(${shorthand})`} is invalid. The format should be \`@<breakpoint | number>\` or \`@<breakpoint | number>/<container>\`.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-
|
|
2
|
+
import"./chunk-9psr8atb.js";import{refreshUpdateCache}from"./chunk-9p1dk5cb.js";import{defineCommand}from"./chunk-2smsg2ct.js";var update_check_default=defineCommand({meta:{name:"__update_check",description:"Internal release check",hidden:!0},async run(){await refreshUpdateCache()}});export{update_check_default as default};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{TAILWIND_CLASSNAME,helperSourcePath}from"./chunk-5ezzc1h2.js";import{snapshotVersion2,entryCssPath2,componentsDir2}from"./chunk-cvn689d5.js";import{registry2}from"./chunk-3g3dqej3.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-cxzkkn12.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-88eqqdk1.js";import{snapshotVersion2,entryCssPath2,componentsDir2}from"./chunk-cvn689d5.js";import{registry2}from"./chunk-p62fygqz.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-7yaafw73.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};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{recordedDesignName}from"./chunk-
|
|
2
|
+
import{recordedDesignName}from"./chunk-88eqqdk1.js";import{displayPath}from"./chunk-t2w8a591.js";import{basename,relative,resolve}from"path";function designWithFolder(folder,name,opts={}){let shown=name??recordedDesignName(folder)??basename(folder),rel=relative(resolve("."),folder),where=rel!==""&&!rel.startsWith("..")&&!opts.absolute?`./${rel}`:displayPath(folder);return`"${shown}" (${where})`}
|
|
3
3
|
export{designWithFolder};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{string,number,object,CURRENT_SCHEMA_VERSION,schemaVersionOf}from"./chunk-nte0t7v3.js";import{writeJsonAtomic}from"./chunk-
|
|
2
|
+
import{string,number,object,CURRENT_SCHEMA_VERSION,schemaVersionOf}from"./chunk-nte0t7v3.js";import{writeJsonAtomic}from"./chunk-88eqqdk1.js";import{TOOL_VERSION}from"./chunk-9psr8atb.js";import{defaultCloudUrl}from"./chunk-as08hzp3.js";function isLoopbackHost(host){let normalized=host.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(normalized==="localhost"||normalized==="::1")return!0;let octets=normalized.split(".");return octets.length===4&&octets[0]==="127"&&octets.every((part)=>/^\d+$/.test(part))}function assertLoopbackHost(host){if(isLoopbackHost(host))return;throw Error(`refusing to bind ${JSON.stringify(host)}: the canvas and MCP endpoints have no authentication and only serve loopback (use 127.0.0.1, localhost or ::1)`)}import{closeSync,existsSync,mkdirSync,openSync,readFileSync,realpathSync,statSync,unlinkSync,writeSync}from"fs";import{mkdir,readFile}from"fs/promises";import{homedir}from"os";import{dirname,join,resolve}from"path";var DaemonRecordSchema=object({root:string().min(1),pid:number().int().positive(),canvasUrl:string().min(1),canvasPort:number().int().positive(),mcpUrl:string().min(1),mcpPort:number().int().positive(),cloudUrl:string().min(1),version:string().min(1),startedAt:string().min(1)});function daemonMatchesRuntime(rec,cloudUrl=defaultCloudUrl()){return rec.version===TOOL_VERSION&&rec.cloudUrl===cloudUrl}var MUTEX_STALE_MS=15000,HEALTHY_TIMEOUT_MS=15000,cacheDir=(root)=>join(root,".design","cache"),lockPath=(root)=>join(cacheDir(root),"runtime.json"),mutexPath=(root)=>join(cacheDir(root),"runtime.lock"),logPath=(root)=>join(cacheDir(root),"daemon.log"),portMemoPath=(root)=>join(cacheDir(root),"port.json"),registryPath=()=>process.env.VELLOO_DAEMONS_PATH??join(homedir(),".velloo","daemons.json");function daemonRoot(folder){let abs=resolve(folder);return existsSync(abs)?realpathSync(abs):abs}class DesignFolderFormatError extends Error{root;found;current;constructor(message,root,found,current){super(message);this.root=root;this.found=found;this.current=current;this.name="DesignFolderFormatError"}}function assertFolderFormatCurrent(root){let raw;try{raw=JSON.parse(readFileSync(join(root,".design","config.json"),"utf8"))}catch{return}let found=schemaVersionOf(raw);if(found===CURRENT_SCHEMA_VERSION)return;let message=found>CURRENT_SCHEMA_VERSION?`velloo: ${root} uses design-folder schema version ${found}, but this velloo only knows version ${CURRENT_SCHEMA_VERSION}. Upgrade velloo to open it.`:`velloo: ${root} uses design-folder schema version ${found} (current: ${CURRENT_SCHEMA_VERSION}). Run \`velloo upgrade ${root}\` to migrate it.`;throw new DesignFolderFormatError(message,root,found,CURRENT_SCHEMA_VERSION)}async function readLock(root){try{let parsed=DaemonRecordSchema.safeParse(JSON.parse(await readFile(lockPath(root),"utf8")));return parsed.success?parsed.data:null}catch{return null}}async function writeLock(rec){await writeJsonAtomic(lockPath(rec.root),rec)}function removeLock(root){try{unlinkSync(lockPath(root))}catch{}}var DEFAULT_CANVAS_PORT=7300,DERIVED_BAND={start:7310,size:90},PortMemoSchema=object({canvasPort:number().int().min(1).max(65535)});async function readRememberedPort(root){try{let parsed=PortMemoSchema.safeParse(JSON.parse(await readFile(portMemoPath(root),"utf8")));return parsed.success?parsed.data.canvasPort:null}catch{return null}}async function rememberPort(root,canvasPort){await writeJsonAtomic(portMemoPath(root),{canvasPort})}function derivedPort(root){let digest=Bun.CryptoHasher.hash("sha256",root,"hex");return DERIVED_BAND.start+Number.parseInt(digest.slice(0,8),16)%DERIVED_BAND.size}function portCandidates(opts){if(opts.explicit!==void 0)return[opts.explicit];let wanted=[opts.remembered,DEFAULT_CANVAS_PORT,derivedPort(opts.root)];return[...new Set(wanted.filter((p)=>typeof p==="number"))]}var HealthSchema=object({app:string().optional(),root:string().optional()});async function isLive(rec){try{let res=await fetch(`http://127.0.0.1:${rec.canvasPort}/api/health`,{signal:AbortSignal.timeout(1000)});if(!res.ok)return!1;let body=await res.json(),health=HealthSchema.safeParse(body);return health.success&&health.data.app==="velloo"&&health.data.root===rec.root}catch{return!1}}async function registryRead(){try{let raw=JSON.parse(await readFile(registryPath(),"utf8"));if(!Array.isArray(raw))return[];return raw.flatMap((entry)=>{let parsed=DaemonRecordSchema.safeParse(entry);return parsed.success?[parsed.data]:[]})}catch{return[]}}async function registryWrite(records){let p=registryPath();await mkdir(dirname(p),{recursive:!0}),await writeJsonAtomic(p,records)}async function registryUpsert(rec){let others=(await registryRead()).filter((r)=>r.root!==rec.root);await registryWrite([...others,rec])}async function registryRemove(root){await registryWrite((await registryRead()).filter((r)=>r.root!==root))}async function listDaemons(){let all=await registryRead(),live=[];for(let rec of all)if(await isLive(rec))live.push(rec);if(live.length!==all.length)await registryWrite(live);return live}function daemonSpawnCmd(root,preferredPort,host){let args=["__daemon",root,"--host",host];if(preferredPort!==void 0)args.push("--port",String(preferredPort));let entry=Bun.main;return existsSync(entry)?[process.execPath,entry,...args]:[process.execPath,...args]}function spawnDetached(root,preferredPort,host){mkdirSync(cacheDir(root),{recursive:!0});let logStart=0;try{logStart=statSync(logPath(root)).size}catch{}let log=openSync(logPath(root),"a"),proc=Bun.spawn(daemonSpawnCmd(root,preferredPort,host),{stdin:"ignore",stdout:log,stderr:log,detached:process.platform==="win32"});return proc.unref(),{exited:proc.exited,logStart}}function claimMutex(root){let path=mutexPath(root);try{let fd=openSync(path,"wx");return writeSync(fd,String(process.pid)),closeSync(fd),!0}catch{try{if(Date.now()-statSync(path).mtimeMs>MUTEX_STALE_MS)return unlinkSync(path),claimMutex(root)}catch{}return!1}}function releaseMutex(root){try{unlinkSync(mutexPath(root))}catch{}}function startupFailure(root,logStart){let appended="";try{appended=readFileSync(logPath(root),"utf8").slice(logStart)}catch{}let lines=appended.split(`
|
|
3
3
|
`).map((l)=>l.replace(/^velloo __daemon: /,"").trimEnd()).filter((l)=>l.trim().length>0).slice(-8);if(lines.length===0)return`velloo: the canvas daemon for ${root} exited during startup with no output \u2014 see ${logPath(root)}`;return`velloo: the canvas daemon for ${root} exited during startup:
|
|
4
4
|
${lines.join(`
|
|
5
5
|
`)}`}async function waitForHealthy(root,spawned){let deadline=Date.now()+HEALTHY_TIMEOUT_MS,died=!1;if(spawned)spawned.exited.then(()=>died=!0);while(Date.now()<deadline){let rec=await readLock(root);if(rec&&await isLive(rec))return rec;if(died)throw Error(startupFailure(root,spawned?.logStart??0));await new Promise((r)=>setTimeout(r,150))}throw Error(`velloo: canvas daemon for ${root} didn't come up \u2014 see ${logPath(root)}`)}async function ensureDaemon(folder,opts={}){let root=daemonRoot(folder);assertFolderFormatCurrent(root);let host=opts.host??"127.0.0.1";assertLoopbackHost(host),mkdirSync(cacheDir(root),{recursive:!0});let deadline=Date.now()+HEALTHY_TIMEOUT_MS+5000;while(Date.now()<deadline){let existing=await readLock(root);if(existing&&await isLive(existing)){if(daemonMatchesRuntime(existing))return existing;await stopDaemon(root)}if(claimMutex(root))try{let again=await readLock(root);if(again&&await isLive(again)){if(daemonMatchesRuntime(again))return again;await stopDaemon(root)}let spawned=spawnDetached(root,opts.preferredPort,host);return opts.onSpawn?.(),await waitForHealthy(root,spawned)}finally{releaseMutex(root)}await new Promise((r)=>setTimeout(r,200))}throw Error(`velloo: timed out ensuring a canvas daemon for ${root}`)}async function stopDaemon(root){let rec=await readLock(root);if(!rec)return!1;try{process.kill(rec.pid,"SIGTERM")}catch{}for(let i=0;i<30;i++){if(!await isLive(rec))break;await new Promise((r)=>setTimeout(r,100))}return removeLock(root),await registryRemove(root),!0}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isCancel,confirm,log,cancel,note,spinner,select,text}from"./chunk-80fjfyha.js";import{designNameIssue,CURRENT_SCHEMA_VERSION,schemaVersionOf,APP_PATH_PREFIX,planMigration,ConfigSchema}from"./chunk-nte0t7v3.js";import{writeJsonAtomic,managedDesignPath,managedDesignId,localDesignOf,writeLocalDesign,removeLocalDesign,resolveAppPath,recordedDesignName,pickDesign,readRepoFeedback,writeRepoFeedback,writeFeedbackContactOk,loadDesignFolder,hostAppRootFrom,topUpTokens}from"./chunk-5ezzc1h2.js";import{CHROMIUM_INSTALL_CMD,chromiumExecutable}from"./chunk-c4fym47a.js";import{PROJECT_AGENT_IDS,resolveProjectRoot,manualSetupText,askAgentWiring,globallyWiredAgents,connect}from"./chunk-9nhw49vv.js";import{TOOL_VERSION}from"./chunk-kz4423th.js";import{fail}from"./chunk-s23gtejf.js";import{daemonRoot,ensureDaemon,stopDaemon}from"./chunk-k9219kmj.js";import{installedVellooBin,updateStatus,upgradeInstalledVelloo}from"./chunk-7k7dpj5y.js";import{dirExists,discoverScanRoots,scanApps,primaryApp,buildScreensFromScan,buildBoardsFromScan,DEFAULT_THEME_PRESET,isValidPreset,WIZARD_PROVIDERS,LIBRARY_IDS,DEFAULT_LIBRARY_ID,interactiveLibraryChoices,planInstall,scanAdoption,DEFAULT_STACK_ID,stackForFramework,isValidStack,importThemeFromMui,findMuiTheme,importThemeFromGlobals,isEmptyOrMissing,resolveTheme,buildScaffold,writeScaffold,displayPath,printSummary,printExitInstructions,printScreenshotReadiness,promptShellCompletions}from"./chunk-7njj1qmq.js";import{loadCredential,saveCredential}from"./chunk-hfzg98c8.js";import{installChromiumInteractive}from"./chunk-2fgfex9b.js";import{detectHost,findComponentsDir}from"./chunk-d9p6s05n.js";import{copyToClipboard}from"./chunk-vbk1qhdz.js";import{upgradeFolder}from"./chunk-jx11jvq8.js";import{findManifest,manifestListing,findDesigns,withoutDesign,isWithin,findGitRoot,chooseDesignName,registerDesign,registerLocalDesign,existingDesignFolder,isDesignFolderSync,isEmptyOrMissingSync,hasDesignConfig,resolveDesign}from"./chunk-td5z2sm4.js";import{verifyCredential,performDeviceLogin}from"./chunk-6zz9kfbd.js";import{openUrl}from"./chunk-hggap8fq.js";import{defaultCloudUrl}from"./chunk-as08hzp3.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";import{randomUUID as randomUUID2}from"crypto";import{dirname as dirname2,relative as relative5,resolve as resolve7}from"path";var import_picocolors11=__toESM(require_picocolors(),1);import{existsSync}from"fs";import{readFile}from"fs/promises";import{join,relative,resolve,sep}from"path";function isSentinel(path){return path==="binary"||path.startsWith("~/")}function toPosix(path){return path.split(sep).join("/")||"."}function isUnder(parent,child){let rel=relative(parent,child);return rel===""||!rel.startsWith("..")&&!/^(?:[\\/]|[A-Za-z]:)/.test(rel)}async function readConfig(folder){return ConfigSchema.parse(JSON.parse(await readFile(join(folder,".design","config.json"),"utf8")))}async function recordedAppRoot(designFolder){let folder=resolve(designFolder),local=localDesignOf(folder);if(local){let path=resolve(local.appRoot);return{path,kind:"local",localId:local.id,checkout:local.root,...appShape(path)}}let recorded=(await readConfig(folder)).hostApp?.root,path=recorded&&!isSentinel(recorded)?resolveAppPath(folder,recorded):resolve(folder,".."),found=await manifestListing(folder).catch(()=>null),designName=recordedDesignName(folder);return{path,kind:"in-repo",...designName?{designName}:{},...found?{manifestPath:found.path}:{},...appShape(path)}}function appShape(path){let exists=existsSync(path);return{exists,looksLikeApp:exists&&existsSync(join(path,"package.json"))}}async function planAppRootChange(designFolder,newRoot){let folder=resolve(designFolder),current=await recordedAppRoot(folder),to=resolve(newRoot),change={from:current.path,to,rewritten:[]};if(current.kind==="local"&¤t.localId&¤t.checkout){if(!isUnder(current.checkout,to))throw Error(`An application root must live inside the design's checkout (${current.checkout}). ${to} is outside it.`);return change.local={id:current.localId,root:current.checkout},change}let config=await readConfig(folder),reanchor=(field,stored)=>{if(isSentinel(stored))return;let abs=resolveAppPath(folder,stored);if(!isUnder(current.path,abs))return;let next=toPosix(relative(folder,join(to,relative(current.path,abs))));if(next===stored)return;return change.rewritten.push({field,from:stored,to:next}),next};if(config.hostApp)reanchor("hostApp.root",config.hostApp.root);else change.rewritten.push({field:"hostApp.root",from:"(unset)",to:toPosix(relative(folder,to))});for(let[name,app]of Object.entries(config.hostApps??{}))reanchor(`hostApps.${name}.root`,app.root);for(let[name,library]of Object.entries(config.libraries))if(library.source==="in-repo")reanchor(`libraries.${name}.componentsPath`,library.componentsPath);return change}async function applyAppRootChange(designFolder,change){let folder=resolve(designFolder);if(change.local){await writeLocalDesign(change.local.id,{root:change.local.root,appRoot:change.to,...managedDesignId(folder)?{}:{designPath:folder}});return}let config=await readConfig(folder),patch=new Map(change.rewritten.map((r)=>[r.field,r.to])),hostRoot=patch.get("hostApp.root");if(hostRoot!==void 0)config.hostApp=config.hostApp?{...config.hostApp,root:hostRoot}:{root:hostRoot};for(let[name,app]of Object.entries(config.hostApps??{})){let next=patch.get(`hostApps.${name}.root`);if(next!==void 0)app.root=next}for(let[name,library]of Object.entries(config.libraries)){let next=patch.get(`libraries.${name}.componentsPath`);if(next!==void 0)library.componentsPath=next}await writeJsonAtomic(join(folder,".design","config.json"),ConfigSchema.parse(config))}async function appRootCandidates(near){let start=resolve(near),from=(await findManifest(start).catch(()=>null))?.dir??await findGitRoot(start)??start;return(await discoverScanRoots(from)).map((app)=>({dir:app.dir,rel:relative(from,app.dir)||"."}))}async function appRootIsNotAnApp(appRoot){let abs=resolve(appRoot);if(existsSync(join(abs,"package.json"))&&(await discoverScanRoots(abs))[0]?.dir===abs)return null;let candidates=(await appRootCandidates(abs)).filter((c)=>c.dir!==abs);return candidates.length>0?candidates:null}async function promptAppRootChoice(current,opts={}){let message=opts.message??"Which application is this design for?",currentHint=opts.currentHint??"recorded now",abs=resolve(current),candidates=await appRootCandidates(abs),options=candidates.map((c)=>({value:c.dir,label:c.rel,...c.dir===abs?{hint:currentHint}:{}}));if(!candidates.some((c)=>c.dir===abs))options.push({value:abs,label:current,hint:currentHint});if(options.length<=1)return null;let chosen=await select({message,options});if(isCancel(chosen))return null;return chosen}import{createHash,randomUUID}from"crypto";import{existsSync as existsSync2,lstatSync,realpathSync}from"fs";import{cp,lstat,mkdir,readdir,readFile as readFile2,rm}from"fs/promises";import{basename,dirname,join as join2,relative as relative2,resolve as resolve2,sep as sep2}from"path";function physicalDestination(path){if(lstatSync(path,{throwIfNoEntry:!1}))return realpathSync(path);let parent=dirname(path);return join2(physicalDestination(parent),relative2(parent,path))}var RUNTIME=[".design/cache",".velloo","node_modules"];async function rebaseDesignConfig(source,destination,appRoot,external){let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(destination,".design/config.json"),"utf8"))),rebase=(path)=>{if(path==="binary"||path.startsWith("~/"))return path;let abs=resolveAppPath(source,path),withinDesign=relative2(source,abs);if(withinDesign===""||withinDesign!==".."&&!withinDesign.startsWith(`..${sep2}`)&&!/^(?:[\\/]|[A-Za-z]:)/.test(withinDesign))return withinDesign.split(sep2).join("/")||".";return external?`${APP_PATH_PREFIX}${relative2(appRoot,abs).split(sep2).join("/")||"."}`:relative2(destination,abs).split(sep2).join("/")||"."};config.hostApp=config.hostApp?{...config.hostApp,root:rebase(config.hostApp.root)}:{root:rebase("..")};for(let app of Object.values(config.hostApps??{}))app.root=rebase(app.root);for(let library of Object.values(config.libraries))if(library.componentsPath)library.componentsPath=rebase(library.componentsPath);await writeJsonAtomic(join2(destination,".design/config.json"),config)}async function fingerprint(folder){let hash=createHash("sha256");async function walk(rel){if(rel===".git"||RUNTIME.some((p)=>rel===p||rel.startsWith(`${p}/`)))return;let path=join2(folder,rel),stat=await lstat(path);if(stat.isSymbolicLink())throw Error(`Cannot relocate symbolic link ${path}. Replace it with its actual design content first.`);if(stat.isDirectory())for(let name of(await readdir(path)).sort())await walk(rel?`${rel}/${name}`:name);else if(stat.isFile())hash.update(rel).update("\x00").update(await readFile2(path));else throw Error(`Unsupported filesystem entry: ${path}`)}return await walk(""),hash.digest("hex")}async function planRelocation(source,cwd,to,external){if(Boolean(to)===external)throw Error("Choose exactly one destination: --external or --to <path>.");let designs=await findDesigns(cwd),physicalSource=realpathSync(source),local=designs?.local.find((design)=>realOr(design.designRoot)===physicalSource),repo=designs?.repo??null,index=repo?.folders.findIndex((path)=>existsSync2(path)&&realpathSync(path)===physicalSource)??-1;if(!local&&index===-1)throw Error("Run relocation from the checkout the design belongs to; the source must be one of its designs.");let root=local?.root??repo?.dir,name=recordedDesignName(source);if(!name)throw Error(`${source} has no design name \u2014 run \`velloo upgrade\` first.`);let physicalRoot=realpathSync(root);if(physicalSource===physicalRoot)throw Error("Cannot relocate the application repository itself. Use a separate design directory.");if(external&&managedDesignId(source))throw Error("This design already lives in managed storage.");let destination=external?managedDesignPath(local?.id??randomUUID()):resolve2(cwd,to??""),physicalTarget=physicalDestination(destination),inRepo=!external&&isWithin(physicalRoot,physicalTarget);if(physicalTarget===physicalSource||physicalTarget.startsWith(physicalSource+sep2)||physicalSource.startsWith(physicalTarget+sep2))throw Error("Source and destination cannot contain each other.");if(existsSync2(destination))throw Error(`Destination is occupied: ${destination}. Choose a new path; nothing was changed.`);let manifestPath=repo?.path??join2(root,"velloo.json"),before=repo?await readFile2(repo.path,"utf8"):null,manifest,destinationManifestPath;if(repo?.legacy)throw Error(`${repo.path} is in the pre-designs format \u2014 run \`velloo upgrade\` first.`);if(inRepo){destinationManifestPath=relative2(physicalRoot,physicalTarget).split(sep2).join("/")||".";let designs=[...repo?.manifest.designs??[]];if(index===-1)designs.push(destinationManifestPath);else designs[index]=destinationManifestPath;manifest={...repo?.manifest??{},designs}}else if(repo&&index!==-1)manifest=withoutDesign(repo.manifest,index,name);let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(source,".design/config.json"),"utf8")));return{source,destination,root,appRoot:local?.appRoot??hostAppRootFrom(source,config.hostApp),designName:name,sourceLocalId:local?.id,sourceManifestPath:index===-1?void 0:repo?.manifest.designs[index],destinationManifestPath,destinationLocal:inRepo?void 0:{id:local?.id??(external?basename(destination):randomUUID()),...external?{}:{designPath:destination}},manifestPath,before,manifest}}function realOr(path){return existsSync2(path)?realpathSync(path):resolve2(path)}async function relocateDesign(plan){await stopDaemon(daemonRoot(plan.source));let original=await fingerprint(plan.source);await mkdir(dirname(plan.destination),{recursive:!0}),await mkdir(plan.destination);let committed=!1;try{for(let entry of await readdir(plan.source))await cp(join2(plan.source,entry),join2(plan.destination,entry),{recursive:!0,errorOnExist:!0,force:!1,filter:(path)=>!RUNTIME.some((p)=>{let rel=relative2(plan.source,path).split(sep2).join("/");return rel===p||rel.startsWith(`${p}/`)})});if(await fingerprint(plan.destination)!==original)throw Error("Copied content did not match the source.");if(await rebaseDesignConfig(plan.source,plan.destination,plan.appRoot,plan.destinationLocal!==void 0),await loadDesignFolder(plan.destination,{preferences:!1}),await fingerprint(plan.source)!==original)throw Error("The source changed during relocation. Close editors and retry.");if(await readFile2(plan.manifestPath,"utf8").catch(()=>null)!==plan.before)throw Error("The manifest changed during relocation. Review it and retry.");if(plan.destinationLocal){if(plan.sourceLocalId&&plan.sourceLocalId!==plan.destinationLocal.id)await removeLocalDesign(plan.sourceLocalId);await writeLocalDesign(plan.destinationLocal.id,{root:plan.root,appRoot:plan.appRoot,...plan.destinationLocal.designPath?{designPath:plan.destinationLocal.designPath}:{}})}else if(plan.sourceLocalId)await removeLocalDesign(plan.sourceLocalId);if(plan.manifest===null)await rm(plan.manifestPath,{force:!0});else if(plan.manifest)await writeJsonAtomic(plan.manifestPath,plan.manifest);committed=!0}finally{if(!committed)await rm(plan.destination,{recursive:!0,force:!0})}try{await rm(plan.source,{recursive:!0})}catch(error){throw Error(`Relocation completed to ${plan.destination}, but the old copy remains at ${plan.source}. Remove it after checking the destination. ${error}`)}}var import_picocolors=__toESM(require_picocolors(),1);async function offerUpgradeBeforeInit(argv){if(process.env.VELLOO_DISABLE_UPDATE_CHECK==="1"||!process.stdin.isTTY)return!1;let status;try{status=await updateStatus({refresh:!0})}catch{return!1}if(!status.available||!status.upgradable||!status.latest)return!1;console.log(""),console.log(`${import_picocolors.default.yellow("A newer velloo is available:")} ${status.current} \u2192 ${import_picocolors.default.bold(status.latest)}`);let yes=await confirm({message:"Upgrade before setting up this design folder?",initialValue:!0});if(isCancel(yes)||!yes)return console.log(import_picocolors.default.dim(" Continuing on the current version.")),!1;try{if(!(await upgradeInstalledVelloo()).upgraded)return!1;let bin=installedVellooBin();if(!bin)return console.log(import_picocolors.default.dim(" Upgraded. Run `velloo init` again to continue on the new version.")),!0;let code=await Bun.spawn([bin,...argv],{stdin:"inherit",stdout:"inherit",stderr:"inherit",env:{...process.env,VELLOO_DISABLE_UPDATE_CHECK:"1"}}).exited;process.exit(code)}catch(error){return console.log(import_picocolors.default.yellow(` Could not upgrade (${error instanceof Error?error.message:String(error)}) \u2014 continuing on the current version.`)),!1}}import{resolve as resolve3}from"path";var START_TO_CONTENT={"redesign-screen":"redesign-screen","redesign-component":"component",custom:"custom",sample:"sample",blank:"blank",scratch:"sample",scan:"scan"};function isValidLibraryId(v){return LIBRARY_IDS.includes(v)}function isValidContent(v){return v==="sample"||v==="blank"||v==="scan"||v==="redesign-screen"||v==="component"||v==="custom"}function isValidStart(v){return v in START_TO_CONTENT}function shouldRunWizard(args,stdinIsTTY){if(args.nonInteractive)return!1;return stdinIsTTY}function answersFromArgs(args){if(args.library&&!isValidLibraryId(args.library))throw Error(`unknown --library ${JSON.stringify(args.library)}. Valid: ${LIBRARY_IDS.join(" | ")}.`);if(args.start&&!isValidStart(args.start))throw Error(`unknown --start ${JSON.stringify(args.start)}. Valid: redesign-screen | redesign-component | custom | sample | blank | scan.`);if(args.initialContent&&!isValidContent(args.initialContent))throw Error(`unknown --initial-content ${JSON.stringify(args.initialContent)}. Valid: sample | blank | scan | redesign-screen | component | custom.`);let themePreset=args.themePreset?.trim()||void 0;if(themePreset&&!isValidPreset(themePreset))throw Error(`unknown --theme-preset ${JSON.stringify(args.themePreset)}.`);let stack=args.stack?.trim()||void 0;if(stack&&!isValidStack(stack))throw Error(`unknown --stack ${JSON.stringify(args.stack)}. Valid: nextjs | vite | astro | remix.`);let appRoot=resolve3(args.folder??"."),folder=resolve3(appRoot,args.designFolder??"velloo"),library=args.library??DEFAULT_LIBRARY_ID,initialContent=args.initialContent??"sample";if(args.start)initialContent=START_TO_CONTENT[args.start]??initialContent;let screenName=args.screenName?.trim()||void 0,componentDescription=args.component?.trim()||void 0,customRequest=args.request?.trim()||void 0;if(initialContent==="component"&&!componentDescription)throw Error("--component is required for --start=redesign-component.");if(initialContent==="custom"&&!customRequest)throw Error("--request is required for --start=custom.");if(initialContent==="redesign-screen"&&!screenName&&args.start==="redesign-screen");let source=WIZARD_PROVIDERS[library].defaultSource;return{appRoot,scanRoot:appRoot,folder,library,source,componentsRelative:args.componentsDir??"src/components/ui",initialContent,themePreset,...stack?{stack}:{},...screenName?{screenName}:{},...componentDescription?{componentDescription}:{},...customRequest?{customRequest}:{}}}import{readFile as readFile3,rm as rm2,writeFile}from"fs/promises";import{tmpdir}from"os";import{join as join3}from"path";var import_picocolors2=__toESM(require_picocolors(),1);import{relative as relative3,sep as sep3}from"path";var SCREENS_PLACEHOLDER="{{screens}}";function libraryLabel(answers){let unsupported=answers.detected?.unsupportedUi;if(answers.library==="none"&&unsupported)return`own ${unsupported}`;return WIZARD_PROVIDERS[answers.library].handoffComponentsLabel}function appContextLines(answers){let lines=[],appRels=[...new Set((answers.selectedRoutes??[]).map((r)=>r.appRel).filter(Boolean))];if(appRels.length>1)lines.push(`This is a monorepo with ${appRels.length} apps (${appRels.map((r)=>`\`${r}\``).join(", ")}); each app's screens sit on their own board. Run the matching app's dev server when comparing screens.`);else{let uiRel=relative3(answers.appRoot,answers.scanRoot).split(sep3).join("/");if(uiRel&&!uiRel.startsWith(".."))lines.push(`This app's UI lives in \`${uiRel}/\` \u2014 run its dev server from there.`)}return lines}function setupFirstGuidance(){return"**Calibrate before you design** \u2014 run the **velloo-setup** skill first. My app's own components render on the canvas once their preview entry is set up (`preview_status`, then `set_preview_entry`); everything else is drawn with Velloo's components themed by this folder's tokens, so an uncalibrated board won't look like my app. Set up the preview entry, import my stylesheet, set the real fonts, and get the app running so there's something real to check against. Use my components from list_components' Repo shelves rather than rebuilding them from primitives. Tell me in a line what you matched and what stayed unverified."}function compareGuidance(){return"Compare against the real app, not memory: iterate with `screenshot` + `compare_to_url` at the same viewport and fix the `topMismatches` in the order they're ranked. If a capture comes back `unverified`, the similarity number means nothing \u2014 and if the reason is a login wall, call `start_capture_session` so I can sign in and capture the page for you, then verify against it with `compare_to_url { captureId }`."}function captureSiteGuidance(url){return[`**Start by capturing the site.** Call \`start_capture_session { url: "${url}" }\` \u2014 it opens a browser window I drive. I'll log in if needed and hit "Capture page" on each page worth designing from; the call returns straight away, so poll \`list_captures\` until my captures appear.`,"Then read each one with `get_capture`: it gives you a structural outline (repeated blocks are marked \u2014 those are your component candidates), the site's CSS custom properties as `import_theme`-ready CSS, and its images. Run `import_theme` with that CSS before composing so the real tokens resolve.","Re-express the pages with real components against the theme \u2014 do not transcribe the DOM node-for-node. Verify each screen with `compare_to_url { captureId }`."].join(`
|
|
2
|
+
import{isCancel,confirm,log,cancel,note,spinner,select,text}from"./chunk-80fjfyha.js";import{designNameIssue,CURRENT_SCHEMA_VERSION,schemaVersionOf,APP_PATH_PREFIX,planMigration,ConfigSchema}from"./chunk-nte0t7v3.js";import{writeJsonAtomic,managedDesignPath,managedDesignId,localDesignOf,writeLocalDesign,removeLocalDesign,resolveAppPath,recordedDesignName,pickDesign,readRepoFeedback,writeRepoFeedback,writeFeedbackContactOk,loadDesignFolder,hostAppRootFrom,topUpTokens}from"./chunk-88eqqdk1.js";import{CHROMIUM_INSTALL_CMD,chromiumExecutable}from"./chunk-c4fym47a.js";import{PROJECT_AGENT_IDS,resolveProjectRoot,manualSetupText,askAgentWiring,globallyWiredAgents,connect}from"./chunk-avkfsc3p.js";import{TOOL_VERSION}from"./chunk-9psr8atb.js";import{fail}from"./chunk-s23gtejf.js";import{daemonRoot,ensureDaemon,stopDaemon}from"./chunk-4ma2wnqw.js";import{installedVellooBin,updateStatus,upgradeInstalledVelloo}from"./chunk-9p1dk5cb.js";import{dirExists,discoverScanRoots,scanApps,primaryApp,buildScreensFromScan,buildBoardsFromScan,DEFAULT_THEME_PRESET,isValidPreset,WIZARD_PROVIDERS,LIBRARY_IDS,DEFAULT_LIBRARY_ID,interactiveLibraryChoices,planInstall,scanAdoption,DEFAULT_STACK_ID,stackForFramework,isValidStack,importThemeFromMui,findMuiTheme,importThemeFromGlobals,isEmptyOrMissing,resolveTheme,buildScaffold,writeScaffold,displayPath,printSummary,printExitInstructions,printScreenshotReadiness,promptShellCompletions}from"./chunk-t2w8a591.js";import{loadCredential,saveCredential}from"./chunk-hfzg98c8.js";import{installChromiumInteractive}from"./chunk-2fgfex9b.js";import{detectHost,findComponentsDir}from"./chunk-nev5mv85.js";import{copyToClipboard}from"./chunk-vbk1qhdz.js";import{upgradeFolder}from"./chunk-ph2jfg1x.js";import{findManifest,manifestListing,findDesigns,withoutDesign,isWithin,findGitRoot,chooseDesignName,registerDesign,registerLocalDesign,existingDesignFolder,isDesignFolderSync,isEmptyOrMissingSync,hasDesignConfig,resolveDesign}from"./chunk-wafb2xm9.js";import{verifyCredential,performDeviceLogin}from"./chunk-6zz9kfbd.js";import{openUrl}from"./chunk-hggap8fq.js";import{defaultCloudUrl}from"./chunk-as08hzp3.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";import{randomUUID as randomUUID2}from"crypto";import{dirname as dirname2,relative as relative5,resolve as resolve7}from"path";var import_picocolors11=__toESM(require_picocolors(),1);import{existsSync}from"fs";import{readFile}from"fs/promises";import{join,relative,resolve,sep}from"path";function isSentinel(path){return path==="binary"||path.startsWith("~/")}function toPosix(path){return path.split(sep).join("/")||"."}function isUnder(parent,child){let rel=relative(parent,child);return rel===""||!rel.startsWith("..")&&!/^(?:[\\/]|[A-Za-z]:)/.test(rel)}async function readConfig(folder){return ConfigSchema.parse(JSON.parse(await readFile(join(folder,".design","config.json"),"utf8")))}async function recordedAppRoot(designFolder){let folder=resolve(designFolder),local=localDesignOf(folder);if(local){let path=resolve(local.appRoot);return{path,kind:"local",localId:local.id,checkout:local.root,...appShape(path)}}let recorded=(await readConfig(folder)).hostApp?.root,path=recorded&&!isSentinel(recorded)?resolveAppPath(folder,recorded):resolve(folder,".."),found=await manifestListing(folder).catch(()=>null),designName=recordedDesignName(folder);return{path,kind:"in-repo",...designName?{designName}:{},...found?{manifestPath:found.path}:{},...appShape(path)}}function appShape(path){let exists=existsSync(path);return{exists,looksLikeApp:exists&&existsSync(join(path,"package.json"))}}async function planAppRootChange(designFolder,newRoot){let folder=resolve(designFolder),current=await recordedAppRoot(folder),to=resolve(newRoot),change={from:current.path,to,rewritten:[]};if(current.kind==="local"&¤t.localId&¤t.checkout){if(!isUnder(current.checkout,to))throw Error(`An application root must live inside the design's checkout (${current.checkout}). ${to} is outside it.`);return change.local={id:current.localId,root:current.checkout},change}let config=await readConfig(folder),reanchor=(field,stored)=>{if(isSentinel(stored))return;let abs=resolveAppPath(folder,stored);if(!isUnder(current.path,abs))return;let next=toPosix(relative(folder,join(to,relative(current.path,abs))));if(next===stored)return;return change.rewritten.push({field,from:stored,to:next}),next};if(config.hostApp)reanchor("hostApp.root",config.hostApp.root);else change.rewritten.push({field:"hostApp.root",from:"(unset)",to:toPosix(relative(folder,to))});for(let[name,app]of Object.entries(config.hostApps??{}))reanchor(`hostApps.${name}.root`,app.root);for(let[name,library]of Object.entries(config.libraries))if(library.source==="in-repo")reanchor(`libraries.${name}.componentsPath`,library.componentsPath);return change}async function applyAppRootChange(designFolder,change){let folder=resolve(designFolder);if(change.local){await writeLocalDesign(change.local.id,{root:change.local.root,appRoot:change.to,...managedDesignId(folder)?{}:{designPath:folder}});return}let config=await readConfig(folder),patch=new Map(change.rewritten.map((r)=>[r.field,r.to])),hostRoot=patch.get("hostApp.root");if(hostRoot!==void 0)config.hostApp=config.hostApp?{...config.hostApp,root:hostRoot}:{root:hostRoot};for(let[name,app]of Object.entries(config.hostApps??{})){let next=patch.get(`hostApps.${name}.root`);if(next!==void 0)app.root=next}for(let[name,library]of Object.entries(config.libraries)){let next=patch.get(`libraries.${name}.componentsPath`);if(next!==void 0)library.componentsPath=next}await writeJsonAtomic(join(folder,".design","config.json"),ConfigSchema.parse(config))}async function appRootCandidates(near){let start=resolve(near),from=(await findManifest(start).catch(()=>null))?.dir??await findGitRoot(start)??start;return(await discoverScanRoots(from)).map((app)=>({dir:app.dir,rel:relative(from,app.dir)||"."}))}async function appRootIsNotAnApp(appRoot){let abs=resolve(appRoot);if(existsSync(join(abs,"package.json"))&&(await discoverScanRoots(abs))[0]?.dir===abs)return null;let candidates=(await appRootCandidates(abs)).filter((c)=>c.dir!==abs);return candidates.length>0?candidates:null}async function promptAppRootChoice(current,opts={}){let message=opts.message??"Which application is this design for?",currentHint=opts.currentHint??"recorded now",abs=resolve(current),candidates=await appRootCandidates(abs),options=candidates.map((c)=>({value:c.dir,label:c.rel,...c.dir===abs?{hint:currentHint}:{}}));if(!candidates.some((c)=>c.dir===abs))options.push({value:abs,label:current,hint:currentHint});if(options.length<=1)return null;let chosen=await select({message,options});if(isCancel(chosen))return null;return chosen}import{createHash,randomUUID}from"crypto";import{existsSync as existsSync2,lstatSync,realpathSync}from"fs";import{cp,lstat,mkdir,readdir,readFile as readFile2,rm}from"fs/promises";import{basename,dirname,join as join2,relative as relative2,resolve as resolve2,sep as sep2}from"path";function physicalDestination(path){if(lstatSync(path,{throwIfNoEntry:!1}))return realpathSync(path);let parent=dirname(path);return join2(physicalDestination(parent),relative2(parent,path))}var RUNTIME=[".design/cache",".velloo","node_modules"];async function rebaseDesignConfig(source,destination,appRoot,external){let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(destination,".design/config.json"),"utf8"))),rebase=(path)=>{if(path==="binary"||path.startsWith("~/"))return path;let abs=resolveAppPath(source,path),withinDesign=relative2(source,abs);if(withinDesign===""||withinDesign!==".."&&!withinDesign.startsWith(`..${sep2}`)&&!/^(?:[\\/]|[A-Za-z]:)/.test(withinDesign))return withinDesign.split(sep2).join("/")||".";return external?`${APP_PATH_PREFIX}${relative2(appRoot,abs).split(sep2).join("/")||"."}`:relative2(destination,abs).split(sep2).join("/")||"."};config.hostApp=config.hostApp?{...config.hostApp,root:rebase(config.hostApp.root)}:{root:rebase("..")};for(let app of Object.values(config.hostApps??{}))app.root=rebase(app.root);for(let library of Object.values(config.libraries))if(library.componentsPath)library.componentsPath=rebase(library.componentsPath);await writeJsonAtomic(join2(destination,".design/config.json"),config)}async function fingerprint(folder){let hash=createHash("sha256");async function walk(rel){if(rel===".git"||RUNTIME.some((p)=>rel===p||rel.startsWith(`${p}/`)))return;let path=join2(folder,rel),stat=await lstat(path);if(stat.isSymbolicLink())throw Error(`Cannot relocate symbolic link ${path}. Replace it with its actual design content first.`);if(stat.isDirectory())for(let name of(await readdir(path)).sort())await walk(rel?`${rel}/${name}`:name);else if(stat.isFile())hash.update(rel).update("\x00").update(await readFile2(path));else throw Error(`Unsupported filesystem entry: ${path}`)}return await walk(""),hash.digest("hex")}async function planRelocation(source,cwd,to,external){if(Boolean(to)===external)throw Error("Choose exactly one destination: --external or --to <path>.");let designs=await findDesigns(cwd),physicalSource=realpathSync(source),local=designs?.local.find((design)=>realOr(design.designRoot)===physicalSource),repo=designs?.repo??null,index=repo?.folders.findIndex((path)=>existsSync2(path)&&realpathSync(path)===physicalSource)??-1;if(!local&&index===-1)throw Error("Run relocation from the checkout the design belongs to; the source must be one of its designs.");let root=local?.root??repo?.dir,name=recordedDesignName(source);if(!name)throw Error(`${source} has no design name \u2014 run \`velloo upgrade\` first.`);let physicalRoot=realpathSync(root);if(physicalSource===physicalRoot)throw Error("Cannot relocate the application repository itself. Use a separate design directory.");if(external&&managedDesignId(source))throw Error("This design already lives in managed storage.");let destination=external?managedDesignPath(local?.id??randomUUID()):resolve2(cwd,to??""),physicalTarget=physicalDestination(destination),inRepo=!external&&isWithin(physicalRoot,physicalTarget);if(physicalTarget===physicalSource||physicalTarget.startsWith(physicalSource+sep2)||physicalSource.startsWith(physicalTarget+sep2))throw Error("Source and destination cannot contain each other.");if(existsSync2(destination))throw Error(`Destination is occupied: ${destination}. Choose a new path; nothing was changed.`);let manifestPath=repo?.path??join2(root,"velloo.json"),before=repo?await readFile2(repo.path,"utf8"):null,manifest,destinationManifestPath;if(repo?.legacy)throw Error(`${repo.path} is in the pre-designs format \u2014 run \`velloo upgrade\` first.`);if(inRepo){destinationManifestPath=relative2(physicalRoot,physicalTarget).split(sep2).join("/")||".";let designs=[...repo?.manifest.designs??[]];if(index===-1)designs.push(destinationManifestPath);else designs[index]=destinationManifestPath;manifest={...repo?.manifest??{},designs}}else if(repo&&index!==-1)manifest=withoutDesign(repo.manifest,index,name);let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(source,".design/config.json"),"utf8")));return{source,destination,root,appRoot:local?.appRoot??hostAppRootFrom(source,config.hostApp),designName:name,sourceLocalId:local?.id,sourceManifestPath:index===-1?void 0:repo?.manifest.designs[index],destinationManifestPath,destinationLocal:inRepo?void 0:{id:local?.id??(external?basename(destination):randomUUID()),...external?{}:{designPath:destination}},manifestPath,before,manifest}}function realOr(path){return existsSync2(path)?realpathSync(path):resolve2(path)}async function relocateDesign(plan){await stopDaemon(daemonRoot(plan.source));let original=await fingerprint(plan.source);await mkdir(dirname(plan.destination),{recursive:!0}),await mkdir(plan.destination);let committed=!1;try{for(let entry of await readdir(plan.source))await cp(join2(plan.source,entry),join2(plan.destination,entry),{recursive:!0,errorOnExist:!0,force:!1,filter:(path)=>!RUNTIME.some((p)=>{let rel=relative2(plan.source,path).split(sep2).join("/");return rel===p||rel.startsWith(`${p}/`)})});if(await fingerprint(plan.destination)!==original)throw Error("Copied content did not match the source.");if(await rebaseDesignConfig(plan.source,plan.destination,plan.appRoot,plan.destinationLocal!==void 0),await loadDesignFolder(plan.destination,{preferences:!1}),await fingerprint(plan.source)!==original)throw Error("The source changed during relocation. Close editors and retry.");if(await readFile2(plan.manifestPath,"utf8").catch(()=>null)!==plan.before)throw Error("The manifest changed during relocation. Review it and retry.");if(plan.destinationLocal){if(plan.sourceLocalId&&plan.sourceLocalId!==plan.destinationLocal.id)await removeLocalDesign(plan.sourceLocalId);await writeLocalDesign(plan.destinationLocal.id,{root:plan.root,appRoot:plan.appRoot,...plan.destinationLocal.designPath?{designPath:plan.destinationLocal.designPath}:{}})}else if(plan.sourceLocalId)await removeLocalDesign(plan.sourceLocalId);if(plan.manifest===null)await rm(plan.manifestPath,{force:!0});else if(plan.manifest)await writeJsonAtomic(plan.manifestPath,plan.manifest);committed=!0}finally{if(!committed)await rm(plan.destination,{recursive:!0,force:!0})}try{await rm(plan.source,{recursive:!0})}catch(error){throw Error(`Relocation completed to ${plan.destination}, but the old copy remains at ${plan.source}. Remove it after checking the destination. ${error}`)}}var import_picocolors=__toESM(require_picocolors(),1);async function offerUpgradeBeforeInit(argv){if(process.env.VELLOO_DISABLE_UPDATE_CHECK==="1"||!process.stdin.isTTY)return!1;let status;try{status=await updateStatus({refresh:!0})}catch{return!1}if(!status.available||!status.upgradable||!status.latest)return!1;console.log(""),console.log(`${import_picocolors.default.yellow("A newer velloo is available:")} ${status.current} \u2192 ${import_picocolors.default.bold(status.latest)}`);let yes=await confirm({message:"Upgrade before setting up this design folder?",initialValue:!0});if(isCancel(yes)||!yes)return console.log(import_picocolors.default.dim(" Continuing on the current version.")),!1;try{if(!(await upgradeInstalledVelloo()).upgraded)return!1;let bin=installedVellooBin();if(!bin)return console.log(import_picocolors.default.dim(" Upgraded. Run `velloo init` again to continue on the new version.")),!0;let code=await Bun.spawn([bin,...argv],{stdin:"inherit",stdout:"inherit",stderr:"inherit",env:{...process.env,VELLOO_DISABLE_UPDATE_CHECK:"1"}}).exited;process.exit(code)}catch(error){return console.log(import_picocolors.default.yellow(` Could not upgrade (${error instanceof Error?error.message:String(error)}) \u2014 continuing on the current version.`)),!1}}import{resolve as resolve3}from"path";var START_TO_CONTENT={"redesign-screen":"redesign-screen","redesign-component":"component",custom:"custom",sample:"sample",blank:"blank",scratch:"sample",scan:"scan"};function isValidLibraryId(v){return LIBRARY_IDS.includes(v)}function isValidContent(v){return v==="sample"||v==="blank"||v==="scan"||v==="redesign-screen"||v==="component"||v==="custom"}function isValidStart(v){return v in START_TO_CONTENT}function shouldRunWizard(args,stdinIsTTY){if(args.nonInteractive)return!1;return stdinIsTTY}function answersFromArgs(args){if(args.library&&!isValidLibraryId(args.library))throw Error(`unknown --library ${JSON.stringify(args.library)}. Valid: ${LIBRARY_IDS.join(" | ")}.`);if(args.start&&!isValidStart(args.start))throw Error(`unknown --start ${JSON.stringify(args.start)}. Valid: redesign-screen | redesign-component | custom | sample | blank | scan.`);if(args.initialContent&&!isValidContent(args.initialContent))throw Error(`unknown --initial-content ${JSON.stringify(args.initialContent)}. Valid: sample | blank | scan | redesign-screen | component | custom.`);let themePreset=args.themePreset?.trim()||void 0;if(themePreset&&!isValidPreset(themePreset))throw Error(`unknown --theme-preset ${JSON.stringify(args.themePreset)}.`);let stack=args.stack?.trim()||void 0;if(stack&&!isValidStack(stack))throw Error(`unknown --stack ${JSON.stringify(args.stack)}. Valid: nextjs | vite | astro | remix.`);let appRoot=resolve3(args.folder??"."),folder=resolve3(appRoot,args.designFolder??"velloo"),library=args.library??DEFAULT_LIBRARY_ID,initialContent=args.initialContent??"sample";if(args.start)initialContent=START_TO_CONTENT[args.start]??initialContent;let screenName=args.screenName?.trim()||void 0,componentDescription=args.component?.trim()||void 0,customRequest=args.request?.trim()||void 0;if(initialContent==="component"&&!componentDescription)throw Error("--component is required for --start=redesign-component.");if(initialContent==="custom"&&!customRequest)throw Error("--request is required for --start=custom.");if(initialContent==="redesign-screen"&&!screenName&&args.start==="redesign-screen");let source=WIZARD_PROVIDERS[library].defaultSource;return{appRoot,scanRoot:appRoot,folder,library,source,componentsRelative:args.componentsDir??"src/components/ui",initialContent,themePreset,...stack?{stack}:{},...screenName?{screenName}:{},...componentDescription?{componentDescription}:{},...customRequest?{customRequest}:{}}}import{readFile as readFile3,rm as rm2,writeFile}from"fs/promises";import{tmpdir}from"os";import{join as join3}from"path";var import_picocolors2=__toESM(require_picocolors(),1);import{relative as relative3,sep as sep3}from"path";var SCREENS_PLACEHOLDER="{{screens}}";function libraryLabel(answers){let unsupported=answers.detected?.unsupportedUi;if(answers.library==="none"&&unsupported)return`own ${unsupported}`;return WIZARD_PROVIDERS[answers.library].handoffComponentsLabel}function appContextLines(answers){let lines=[],appRels=[...new Set((answers.selectedRoutes??[]).map((r)=>r.appRel).filter(Boolean))];if(appRels.length>1)lines.push(`This is a monorepo with ${appRels.length} apps (${appRels.map((r)=>`\`${r}\``).join(", ")}); each app's screens sit on their own board. Run the matching app's dev server when comparing screens.`);else{let uiRel=relative3(answers.appRoot,answers.scanRoot).split(sep3).join("/");if(uiRel&&!uiRel.startsWith(".."))lines.push(`This app's UI lives in \`${uiRel}/\` \u2014 run its dev server from there.`)}return lines}function setupFirstGuidance(){return"**Calibrate before you design** \u2014 run the **velloo-setup** skill first. My app's own components render on the canvas once their preview entry is set up (`preview_status`, then `set_preview_entry`); everything else is drawn with Velloo's components themed by this folder's tokens, so an uncalibrated board won't look like my app. Set up the preview entry, import my stylesheet, set the real fonts, and get the app running so there's something real to check against. Use my components from list_components' Repo shelves rather than rebuilding them from primitives. Tell me in a line what you matched and what stayed unverified."}function compareGuidance(){return"Compare against the real app, not memory: iterate with `screenshot` + `compare_to_url` at the same viewport and fix the `topMismatches` in the order they're ranked. If a capture comes back `unverified`, the similarity number means nothing \u2014 and if the reason is a login wall, call `start_capture_session` so I can sign in and capture the page for you, then verify against it with `compare_to_url { captureId }`."}function captureSiteGuidance(url){return[`**Start by capturing the site.** Call \`start_capture_session { url: "${url}" }\` \u2014 it opens a browser window I drive. I'll log in if needed and hit "Capture page" on each page worth designing from; the call returns straight away, so poll \`list_captures\` until my captures appear.`,"Then read each one with `get_capture`: it gives you a structural outline (repeated blocks are marked \u2014 those are your component candidates), the site's CSS custom properties as `import_theme`-ready CSS, and its images. Run `import_theme` with that CSS before composing so the real tokens resolve.","Re-express the pages with real components against the theme \u2014 do not transcribe the DOM node-for-node. Verify each screen with `compare_to_url { captureId }`."].join(`
|
|
3
3
|
`)}function exploreAlternativesGuidance(){return"After the faithful recreation, explore alternatives on the same board \u2014 side-by-side A/B/C (or more) frames or grouped explorations of different directions. Velloo's strength is comparing options visually; do not stop at a single redesign."}function wantsHandoff(answers){switch(answers.initialContent){case"scan":case"redesign-screen":case"component":case"custom":return!0;default:return!1}}function buildHandoffPrompt(answers,screens,boards){switch(answers.initialContent){case"redesign-screen":return buildRedesignScreenHandoff(answers,screens);case"component":return buildComponentHandoff(answers);case"custom":return buildCustomHandoff(answers);case"scan":return buildLegacyScanHandoff(answers,screens,boards);default:return buildLegacyScanHandoff(answers,screens,boards)}}function buildRedesignScreenHandoff(answers,screens){let name=answers.screenName?.trim()||screens[0]?.name||screens[0]?.id||"the chosen screen",lines=[`Recreate and then explore alternatives for **${name}** as a Velloo design. Work entirely through the velloo MCP tools.`,...appContextLines(answers)];if(screens.length>0)lines.push(`A placeholder screen is already scaffolded (desktop + mobile frames \u2014 edits sync). Design it with the project's ${libraryLabel(answers)} components:`,SCREENS_PLACEHOLDER);else lines.push(`- Create a Velloo screen for **${name}** using the project's ${libraryLabel(answers)} components.`);return lines.push(`1. ${setupFirstGuidance()}`,`2. **Recreate** the real page faithfully. ${compareGuidance()}`,`3. **Then explore alternatives** \u2014 ${exploreAlternativesGuidance()}`),lines.join(`
|
|
4
4
|
`)}function buildComponentHandoff(answers){let target=answers.componentDescription?.trim()||"the component";return[`Redesign **${target}** in Velloo \u2014 recreate it, then explore alternatives. Work entirely through the velloo MCP tools.`,...appContextLines(answers),`A component-focused board is scaffolded. Target: **${target}**. Prefer a snippet if the piece should be reused.`,`1. ${setupFirstGuidance()}`,`2. **Recreate** the current component faithfully with the project's ${libraryLabel(answers)} components. ${compareGuidance()}`,`3. **Then explore alternatives** \u2014 ${exploreAlternativesGuidance()}`].join(`
|
|
5
5
|
`)}function buildCustomHandoff(answers){return["Design this in Velloo. Work entirely through the velloo MCP tools.","","**Request:**",answers.customRequest?.trim()||"the design I described","",...answers.captureUrl?[captureSiteGuidance(answers.captureUrl),""]:[],setupFirstGuidance(),`Then design it with the project's ${libraryLabel(answers)} components. When comparing options, put alternatives side-by-side on the board (explorations) instead of overwriting a single direction.`].join(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isCancel,confirm,password,select}from"./chunk-80fjfyha.js";import{PRICING_URL,protectedSharesAllowed,PROTECTED_SHARES_UNAVAILABLE,describeCloudError}from"./chunk-n9t36h0q.js";import"./chunk-nte0t7v3.js";import{closePooledBrowser}from"./chunk-c4fym47a.js";import{loadDesignFolder,screensForBoards,resolveProviders,findHostTailwindConfig,TailwindJit,extraThemeBlock}from"./chunk-
|
|
2
|
+
import{isCancel,confirm,password,select}from"./chunk-80fjfyha.js";import{PRICING_URL,protectedSharesAllowed,PROTECTED_SHARES_UNAVAILABLE,describeCloudError}from"./chunk-n9t36h0q.js";import"./chunk-nte0t7v3.js";import{closePooledBrowser}from"./chunk-c4fym47a.js";import{loadDesignFolder,screensForBoards,resolveProviders,findHostTailwindConfig,TailwindJit,extraThemeBlock}from"./chunk-88eqqdk1.js";import{loadCredential}from"./chunk-hfzg98c8.js";import{fail}from"./chunk-s23gtejf.js";import{confirmRenderFailures}from"./chunk-2p37rp3j.js";import{publishedDesignSubtitle,listPublishedDesigns,unpublishDesign,listPublishDestinations,designGitEnv,describePublishError,recommendedPublishSlot,exactPublishSlots,gitContext,resolveTeam,publishDesign,createPublishBundler}from"./chunk-asbajsmd.js";import{createProgress}from"./chunk-pjtg3wnm.js";import{DESIGN_ARG_DESCRIPTION,resolveDesign,pickBoards}from"./chunk-wafb2xm9.js";import{fetchAccount}from"./chunk-6zz9kfbd.js";import{defaultCloudUrl,publishedBoardsUrl,billingPageUrl,checkCloudHealth}from"./chunk-as08hzp3.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){let access=design.passwordProtected?"password protected":design.visibility==="private"?"private":"public";console.log(`
|
|
4
4
|
${design.title?.trim()||"Untitled design"}`),console.log(` ${access}`),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 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 privacyFlagsError(args,protectedShares=!0,upgradeUrl=PRICING_URL){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";if((args.private===!0||args.visibility==="private"||args.password===!0)&&!protectedShares)return`${PROTECTED_SHARES_UNAVAILABLE}. Publish with --public, or upgrade at ${upgradeUrl}`;return null}async function resolvePublishPrivacy(args,interactive,{protectedShares=!0,upgradeUrl=PRICING_URL,choose=promptForPrivacyMode}={}){let invalid=privacyFlagsError(args,protectedShares,upgradeUrl);if(invalid)throw Error(invalid);if(args.visibility!==void 0||args.private===!0||args.public===!0||args.password===!0)return{visibility:args.private||args.visibility==="private"?"private":"public",password:args.password===!0};if(!interactive)throw Error("privacy mode is required without a terminal; pass --public, --private, --password, or --visibility");let mode=await choose(protectedShares,upgradeUrl);if(typeof mode==="symbol")throw Error("cancelled");if(mode!=="public"&&!protectedShares)throw Error(PROTECTED_SHARES_UNAVAILABLE);return mode==="private"?{visibility:"private",password:!1}:{visibility:"public",password:mode==="password"}}async function promptForPrivacyMode(protectedShares,upgradeUrl){let locked=protectedShares?{}:{disabled:!0,hint:"Team & Business plans"};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 upgrade at ${upgradeUrl})`,initialValue:"public",options:[{value:"public",label:"Public",hint:"anyone with the link"},{value:"private",label:"Private",hint:"only your organization",...locked},{value:"password",label:"Password protected",hint:"anyone with the password",...locked}]})}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 your organization only; skips the privacy prompt"},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:"Publish into a team by name or UUID (default: personal workspace)"},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),team=await resolveTeam(baseUrl,token,args.team);if(!team.ok)fail("publish",describePublishError(team.error));let teamId=team.value,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 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:teamId??null,slots:[]};let destinations=await listPublishDestinations({baseUrl,token,folderId:config.folderId,...teamId?{teamId}:{}});if(!destinations.ok)fail("publish",describePublishError(destinations.error));return destinations.value})(),source={boardIds:selected.map((board)=>board.id),teamId:listed.effectiveTeamId,...provenance},destination=await choosePublishDestination({slots:listed.slots,source,interactive,createNew:args.new===!0,updateExisting:args.update===!0,customSlug:args.slug,manageUrl:await publishedBoardsUrl(baseUrl)}),privacy=await resolvePublishPrivacy(args,interactive,{protectedShares,...upgradeUrl?{upgradeUrl}:{}}).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,...teamId?{teamId}:{},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}`),console.log(` ${describeAccess(outcome)}`);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 to Team to keep version history and revisit past publishes: ${PRICING_URL}`);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()}function describeAccess(outcome){if(outcome.visibility==="private")return outcome.passwordProtected?"private \u2014 your organization, or anyone with the password":"private \u2014 anyone signed in at your organization";return outcome.passwordProtected?"public \u2014 anyone with the link and the password":"public \u2014 anyone with the link"}export{publish_default as default};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-nte0t7v3.js";import{signInRequired,boardLimitReached,topUpTokens,createServer}from"./chunk-5ezzc1h2.js";import{boardLimitFrom,describeCloudError}from"./chunk-n9t36h0q.js";import"./chunk-c4fym47a.js";import{loadCredential,saveCredential,deleteCredential}from"./chunk-hfzg98c8.js";import{listPublishedDesigns,unpublishDesign,listPublishDestinations,describePublishError,PUBLISH_VIEWPORT,gitContext,listTeams,publishDesign}from"./chunk-6nzqhfqq.js";import{TOOL_VERSION}from"./chunk-kz4423th.js";import{updateStatus,upgradeInstalledVelloo}from"./chunk-7k7dpj5y.js";import{assertLoopbackHost,daemonRoot,writeLock,removeLock,readRememberedPort,rememberPort,portCandidates,registryUpsert,registryRemove}from"./chunk-k9219kmj.js";import{fetchAccount,performDeviceLogin}from"./chunk-6zz9kfbd.js";import{defaultCloudUrl,fetchCloudAppUrl}from"./chunk-as08hzp3.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{existsSync as existsSync2}from"fs";import{existsSync}from"fs";import{dirname,join}from"path";import{fileURLToPath}from"url";var here=dirname(fileURLToPath(import.meta.url));function resolveCanvasDist(){let devLayout=join(here,"..","dist");return[process.env.VELLOO_CANVAS_DIST,join(here,"canvas"),devLayout].filter((p)=>Boolean(p)).find((p)=>existsSync(join(p,"index.html")))??devLayout}var canvasDistPath=resolveCanvasDist();var ACCOUNT_TTL_MS=60000,ACCOUNT_TIMEOUT_MS=5000;function createCanvasAuth(cloudUrl,dependencies={}){let runDeviceLogin=dependencies.performDeviceLogin??performDeviceLogin,login={state:"idle"},pending=null,cached=null,cachedApp=null,describe=async(token,email)=>{if(cached&&cached.token===token&&Date.now()-cached.at<ACCOUNT_TTL_MS)return{account:cached.account,verified:cached.verified};let found=await fetchAccount(cloudUrl,token,ACCOUNT_TIMEOUT_MS),resolved=found.status==="ok"?{account:found.account,verified:!0}:{account:{email},verified:found.status==="rejected"?!1:null};return cached={token,at:Date.now(),...resolved},resolved},resolveAppUrl=async()=>{if(cachedApp&&Date.now()-cachedApp.at<ACCOUNT_TTL_MS)return cachedApp.url;let url=await fetchCloudAppUrl(cloudUrl,ACCOUNT_TIMEOUT_MS);return cachedApp={at:Date.now(),url},url},status=async()=>{let cred=await loadCredential(cloudUrl),appUrlP=resolveAppUrl();if(!cred?.token)return{loggedIn:!1,cloudUrl,appUrl:await appUrlP,verified:null,login};let[{account,verified},appUrl]=await Promise.all([describe(cred.token,cred.email),appUrlP]);return{loggedIn:!0,cloudUrl,appUrl,verified,login,...account?{account}:{}}};return{status,async beginLogin(){if(login.state==="pending")return status();let attempt=new AbortController;pending=attempt,login={state:"idle"};let settle=()=>{},ready=new Promise((resolve)=>{settle=resolve});return runDeviceLogin(cloudUrl,({verificationUrl,userCode,expiresIn})=>{login={state:"pending",userCode,verificationUrl,expiresAt:new Date(Date.now()+expiresIn*1000).toISOString()},settle()},attempt.signal).then(async(result)=>{await saveCredential(cloudUrl,result),cached=null,login={state:"idle"},await topUpTokens({url:cloudUrl,token:result.token},10).catch(()=>{return})}).catch((err)=>{login=attempt.signal.aborted?{state:"idle"}:{state:"error",message:err instanceof Error?err.message:String(err)}}).finally(()=>{if(pending===attempt)pending=null;settle()}),await ready,status()},async cancelLogin(){pending?.abort(),pending=null,login={state:"idle"}},async logout(){pending?.abort(),pending=null,login={state:"idle"},cached=null,await deleteCredential(cloudUrl)}}}function createCanvasPublish(cloudUrl,auth){let tokenFor=async()=>(await loadCredential(cloudUrl))?.token,access=async()=>{if(!await tokenFor())return{state:"signed-out"};return(await auth.status().catch(()=>null))?.verified===!1?{state:"expired"}:{state:"ready"}},rejection=(error)=>error.kind==="LoggedOut"?signInRequired("expired",describeCloudError(error)):Error(describeCloudError(error)),publishedAt=(value)=>{let parsed=value?Date.parse(value):Number.NaN;return Number.isFinite(parsed)?parsed:Number.NEGATIVE_INFINITY};return{access,async teams(){let token=await tokenFor();if(!token)return[];let listed=await listTeams(cloudUrl,token);return listed.ok?listed.value:[]},async published(){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let listed=await listPublishedDesigns({baseUrl:cloudUrl,token});if(!listed.ok)throw rejection(listed.error);return listed.value.map((design)=>({slug:design.slug,title:design.title??"",url:design.url,visibility:design.visibility,passwordProtected:design.passwordProtected,canManage:design.canManage,lastPublishedAt:design.lastPublishedAt})).sort((left,right)=>publishedAt(right.lastPublishedAt)-publishedAt(left.lastPublishedAt))},async unpublish(slug){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let removed=await unpublishDesign({baseUrl:cloudUrl,token,slug});if(!removed.ok)throw rejection(removed.error)},async destinations(host){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let provenance=gitContext(host.folder.root),folderId=host.folder.config.folderId;if(!folderId){let teams=await listTeams(cloudUrl,token);if(!teams.ok)throw rejection(teams.error);return{effectiveTeamId:teams.value.find((team)=>team.isDefault)?.id??null,provenance,slots:[]}}let listed=await listPublishDestinations({baseUrl:cloudUrl,token,folderId});if(!listed.ok)throw rejection(listed.error);return{...listed.value,provenance}},async run(host,request,onProgress,onWarning){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud \u2014 sign in from the account menu first.");let step="start",message="starting",published=await publishDesign({baseUrl:cloudUrl,token},{folder:host.folder,providers:host.providers,defaultProvider:host.defaultProvider,snapshotCss:host.snapshotCss},{boardIds:request.boardIds,...request.title?{title:request.title}:{},visibility:request.visibility,...request.password?{password:request.password}:{},destination:request.destination,...request.teamId?{teamId:request.teamId}:{},provenance:gitContext(host.folder.root),viewport:PUBLISH_VIEWPORT},(event)=>{if(event.kind==="warn"){onWarning(event.message);return}if(event.kind==="note"){onWarning(event.message);return}if(event.kind==="info")return;if(event.kind==="capture"){onProgress({step,message,capture:{done:event.done,total:event.total}});return}step=event.step,message=event.message,onProgress({step,message})});if(!published.ok){let reason=describePublishError(published.error);if(published.error.kind==="LoggedOut")throw signInRequired("expired",reason);let limit=published.error.kind==="HttpFailure"?boardLimitFrom(published.error):null;if(limit)throw boardLimitReached(limit,reason);throw Error(reason)}let outcome=published.value;return{shareUrl:outcome.shareUrl,visibility:outcome.visibility,passwordProtected:outcome.passwordProtected,files:outcome.files,bytes:outcome.bytes,screenshots:outcome.screenshots,boards:outcome.boards,screens:outcome.screens,created:outcome.created,...outcome.tier!==void 0?{tier:outcome.tier}:{},...outcome.history!==void 0?{history:outcome.history}:{}}}}}function createCanvasUpdates(){return{async status(opts={}){let status=await updateStatus(opts);return{current:status.current,latest:status.latest,available:status.available,method:status.method,channel:status.channel,upgradable:status.upgradable,...status.reason===void 0?{}:{reason:status.reason}}},async upgrade(){let outcome=await upgradeInstalledVelloo();return{upgraded:outcome.upgraded,from:outcome.from,to:outcome.to,restartRequired:outcome.upgraded}}}}var IDLE_MS=300000;function portFree(port,host){try{return Bun.serve({port,hostname:host,fetch:()=>new Response("")}).stop(!0),!0}catch{return!1}}var daemon_default=defineCommand({meta:{name:"__daemon",hidden:!0,description:"(internal) Run the persistent canvas daemon. Spawned by `velloo run` / `velloo mcp`."},args:{folder:{type:"positional",required:!0,description:"Design folder (absolute)"},port:{type:"string",description:"Preferred canvas port"},host:{type:"string",description:"Bind hostname (default 127.0.0.1)"}},async run({args}){let root=daemonRoot(args.folder),host=args.host??"127.0.0.1";assertLoopbackHost(host);let cloudUrl=defaultCloudUrl(),cred=await loadCredential(cloudUrl),cloud={url:cloudUrl,token:cred?.token,resolveToken:async()=>(await loadCredential(cloudUrl))?.token},auth=createCanvasAuth(cloudUrl),publish=createCanvasPublish(cloudUrl,auth),updates=createCanvasUpdates(),canvasPort=portCandidates({explicit:args.port?Number(args.port):void 0,remembered:await readRememberedPort(root),root}).find((port)=>portFree(port,host))??0,handle;try{handle=await createServer({folder:root,port:canvasPort,host,mcp:{transport:"http",port:0},canvasDist:canvasDistPath,cloud,auth,publish,updates})}catch(err){if(canvasPort===0)throw err;handle=await createServer({folder:root,port:0,host,mcp:{transport:"http",port:0},canvasDist:canvasDistPath,cloud,auth,publish,updates})}let rec={root,pid:process.pid,canvasUrl:handle.url,canvasPort:handle.port,mcpUrl:handle.mcpUrl??"",mcpPort:handle.mcpPort??0,cloudUrl,version:TOOL_VERSION,startedAt:new Date().toISOString()};await writeLock(rec),await registryUpsert(rec),await rememberPort(root,handle.port).catch(()=>{return}),console.error(`velloo: canvas daemon up at ${handle.url} (mcp ${handle.mcpUrl}), pid ${process.pid}`);let stopped=!1,shutdown=async()=>{if(stopped)return;stopped=!0,removeLock(root),await registryRemove(root).catch(()=>{return}),await handle.close(),process.exit(0)};process.on("SIGTERM",shutdown),process.on("SIGINT",shutdown);let rootMissing=0;setInterval(()=>{if(existsSync2(root)){rootMissing=0;return}if(rootMissing+=1,rootMissing>=2)console.error(`velloo: design folder ${root} is gone \u2014 shutting down.`),shutdown()},1e4);let idleSince=Date.now();setInterval(()=>{let{canvas,mcp}=handle.connections();if(canvas+mcp>0){idleSince=null;return}if(idleSince===null){idleSince=Date.now();return}if(Date.now()-idleSince>=IDLE_MS)console.error("velloo: canvas idle for 5 min \u2014 shutting down."),shutdown()},30000),await new Promise(()=>{})}});export{daemon_default as default};
|
|
2
|
+
import"./chunk-nte0t7v3.js";import{signInRequired,boardLimitReached,topUpTokens,createServer}from"./chunk-88eqqdk1.js";import{boardLimitFrom,describeCloudError}from"./chunk-n9t36h0q.js";import"./chunk-c4fym47a.js";import{loadCredential,saveCredential,deleteCredential}from"./chunk-hfzg98c8.js";import{listPublishedDesigns,unpublishDesign,listPublishDestinations,describePublishError,PUBLISH_VIEWPORT,gitContext,listTeams,publishDesign}from"./chunk-asbajsmd.js";import{TOOL_VERSION}from"./chunk-9psr8atb.js";import{updateStatus,upgradeInstalledVelloo}from"./chunk-9p1dk5cb.js";import{assertLoopbackHost,daemonRoot,writeLock,removeLock,readRememberedPort,rememberPort,portCandidates,registryUpsert,registryRemove}from"./chunk-4ma2wnqw.js";import{fetchAccount,performDeviceLogin}from"./chunk-6zz9kfbd.js";import{defaultCloudUrl,fetchCloudAppUrl}from"./chunk-as08hzp3.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{existsSync as existsSync2}from"fs";import{existsSync}from"fs";import{dirname,join}from"path";import{fileURLToPath}from"url";var here=dirname(fileURLToPath(import.meta.url));function resolveCanvasDist(){let devLayout=join(here,"..","dist");return[process.env.VELLOO_CANVAS_DIST,join(here,"canvas"),devLayout].filter((p)=>Boolean(p)).find((p)=>existsSync(join(p,"index.html")))??devLayout}var canvasDistPath=resolveCanvasDist();var ACCOUNT_TTL_MS=60000,ACCOUNT_TIMEOUT_MS=5000;function createCanvasAuth(cloudUrl,dependencies={}){let runDeviceLogin=dependencies.performDeviceLogin??performDeviceLogin,login={state:"idle"},pending=null,cached=null,cachedApp=null,describe=async(token,email)=>{if(cached&&cached.token===token&&Date.now()-cached.at<ACCOUNT_TTL_MS)return{account:cached.account,verified:cached.verified};let found=await fetchAccount(cloudUrl,token,ACCOUNT_TIMEOUT_MS),resolved=found.status==="ok"?{account:found.account,verified:!0}:{account:{email},verified:found.status==="rejected"?!1:null};return cached={token,at:Date.now(),...resolved},resolved},resolveAppUrl=async()=>{if(cachedApp&&Date.now()-cachedApp.at<ACCOUNT_TTL_MS)return cachedApp.url;let url=await fetchCloudAppUrl(cloudUrl,ACCOUNT_TIMEOUT_MS);return cachedApp={at:Date.now(),url},url},status=async()=>{let cred=await loadCredential(cloudUrl),appUrlP=resolveAppUrl();if(!cred?.token)return{loggedIn:!1,cloudUrl,appUrl:await appUrlP,verified:null,login};let[{account,verified},appUrl]=await Promise.all([describe(cred.token,cred.email),appUrlP]);return{loggedIn:!0,cloudUrl,appUrl,verified,login,...account?{account}:{}}};return{status,async beginLogin(){if(login.state==="pending")return status();let attempt=new AbortController;pending=attempt,login={state:"idle"};let settle=()=>{},ready=new Promise((resolve)=>{settle=resolve});return runDeviceLogin(cloudUrl,({verificationUrl,userCode,expiresIn})=>{login={state:"pending",userCode,verificationUrl,expiresAt:new Date(Date.now()+expiresIn*1000).toISOString()},settle()},attempt.signal).then(async(result)=>{await saveCredential(cloudUrl,result),cached=null,login={state:"idle"},await topUpTokens({url:cloudUrl,token:result.token},10).catch(()=>{return})}).catch((err)=>{login=attempt.signal.aborted?{state:"idle"}:{state:"error",message:err instanceof Error?err.message:String(err)}}).finally(()=>{if(pending===attempt)pending=null;settle()}),await ready,status()},async cancelLogin(){pending?.abort(),pending=null,login={state:"idle"}},async logout(){pending?.abort(),pending=null,login={state:"idle"},cached=null,await deleteCredential(cloudUrl)}}}function createCanvasPublish(cloudUrl,auth){let tokenFor=async()=>(await loadCredential(cloudUrl))?.token,access=async()=>{if(!await tokenFor())return{state:"signed-out"};return(await auth.status().catch(()=>null))?.verified===!1?{state:"expired"}:{state:"ready"}},rejection=(error)=>error.kind==="LoggedOut"?signInRequired("expired",describeCloudError(error)):Error(describeCloudError(error)),publishedAt=(value)=>{let parsed=value?Date.parse(value):Number.NaN;return Number.isFinite(parsed)?parsed:Number.NEGATIVE_INFINITY};return{access,async teams(){let token=await tokenFor();if(!token)return[];let listed=await listTeams(cloudUrl,token);return listed.ok?listed.value:[]},async published(){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let listed=await listPublishedDesigns({baseUrl:cloudUrl,token});if(!listed.ok)throw rejection(listed.error);return listed.value.map((design)=>({slug:design.slug,title:design.title??"",url:design.url,visibility:design.visibility,passwordProtected:design.passwordProtected,canManage:design.canManage,lastPublishedAt:design.lastPublishedAt})).sort((left,right)=>publishedAt(right.lastPublishedAt)-publishedAt(left.lastPublishedAt))},async unpublish(slug){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let removed=await unpublishDesign({baseUrl:cloudUrl,token,slug});if(!removed.ok)throw rejection(removed.error)},async destinations(host){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let provenance=gitContext(host.folder.root),folderId=host.folder.config.folderId;if(!folderId){let teams=await listTeams(cloudUrl,token);if(!teams.ok)throw rejection(teams.error);return{effectiveTeamId:teams.value.find((team)=>team.isDefault)?.id??null,provenance,slots:[]}}let listed=await listPublishDestinations({baseUrl:cloudUrl,token,folderId});if(!listed.ok)throw rejection(listed.error);return{...listed.value,provenance}},async run(host,request,onProgress,onWarning){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud \u2014 sign in from the account menu first.");let step="start",message="starting",published=await publishDesign({baseUrl:cloudUrl,token},{folder:host.folder,providers:host.providers,defaultProvider:host.defaultProvider,snapshotCss:host.snapshotCss},{boardIds:request.boardIds,...request.title?{title:request.title}:{},visibility:request.visibility,...request.password?{password:request.password}:{},destination:request.destination,...request.teamId?{teamId:request.teamId}:{},provenance:gitContext(host.folder.root),viewport:PUBLISH_VIEWPORT},(event)=>{if(event.kind==="warn"){onWarning(event.message);return}if(event.kind==="note"){onWarning(event.message);return}if(event.kind==="info")return;if(event.kind==="capture"){onProgress({step,message,capture:{done:event.done,total:event.total}});return}step=event.step,message=event.message,onProgress({step,message})});if(!published.ok){let reason=describePublishError(published.error);if(published.error.kind==="LoggedOut")throw signInRequired("expired",reason);let limit=published.error.kind==="HttpFailure"?boardLimitFrom(published.error):null;if(limit)throw boardLimitReached(limit,reason);throw Error(reason)}let outcome=published.value;return{shareUrl:outcome.shareUrl,visibility:outcome.visibility,passwordProtected:outcome.passwordProtected,files:outcome.files,bytes:outcome.bytes,screenshots:outcome.screenshots,boards:outcome.boards,screens:outcome.screens,created:outcome.created,...outcome.tier!==void 0?{tier:outcome.tier}:{},...outcome.history!==void 0?{history:outcome.history}:{}}}}}function createCanvasUpdates(){return{async status(opts={}){let status=await updateStatus(opts);return{current:status.current,latest:status.latest,available:status.available,method:status.method,channel:status.channel,upgradable:status.upgradable,...status.reason===void 0?{}:{reason:status.reason}}},async upgrade(){let outcome=await upgradeInstalledVelloo();return{upgraded:outcome.upgraded,from:outcome.from,to:outcome.to,restartRequired:outcome.upgraded}}}}var IDLE_MS=300000;function portFree(port,host){try{return Bun.serve({port,hostname:host,fetch:()=>new Response("")}).stop(!0),!0}catch{return!1}}var daemon_default=defineCommand({meta:{name:"__daemon",hidden:!0,description:"(internal) Run the persistent canvas daemon. Spawned by `velloo run` / `velloo mcp`."},args:{folder:{type:"positional",required:!0,description:"Design folder (absolute)"},port:{type:"string",description:"Preferred canvas port"},host:{type:"string",description:"Bind hostname (default 127.0.0.1)"}},async run({args}){let root=daemonRoot(args.folder),host=args.host??"127.0.0.1";assertLoopbackHost(host);let cloudUrl=defaultCloudUrl(),cred=await loadCredential(cloudUrl),cloud={url:cloudUrl,token:cred?.token,resolveToken:async()=>(await loadCredential(cloudUrl))?.token},auth=createCanvasAuth(cloudUrl),publish=createCanvasPublish(cloudUrl,auth),updates=createCanvasUpdates(),canvasPort=portCandidates({explicit:args.port?Number(args.port):void 0,remembered:await readRememberedPort(root),root}).find((port)=>portFree(port,host))??0,handle;try{handle=await createServer({folder:root,port:canvasPort,host,mcp:{transport:"http",port:0},canvasDist:canvasDistPath,cloud,auth,publish,updates})}catch(err){if(canvasPort===0)throw err;handle=await createServer({folder:root,port:0,host,mcp:{transport:"http",port:0},canvasDist:canvasDistPath,cloud,auth,publish,updates})}let rec={root,pid:process.pid,canvasUrl:handle.url,canvasPort:handle.port,mcpUrl:handle.mcpUrl??"",mcpPort:handle.mcpPort??0,cloudUrl,version:TOOL_VERSION,startedAt:new Date().toISOString()};await writeLock(rec),await registryUpsert(rec),await rememberPort(root,handle.port).catch(()=>{return}),console.error(`velloo: canvas daemon up at ${handle.url} (mcp ${handle.mcpUrl}), pid ${process.pid}`);let stopped=!1,shutdown=async()=>{if(stopped)return;stopped=!0,removeLock(root),await registryRemove(root).catch(()=>{return}),await handle.close(),process.exit(0)};process.on("SIGTERM",shutdown),process.on("SIGINT",shutdown);let rootMissing=0;setInterval(()=>{if(existsSync2(root)){rootMissing=0;return}if(rootMissing+=1,rootMissing>=2)console.error(`velloo: design folder ${root} is gone \u2014 shutting down.`),shutdown()},1e4);let idleSince=Date.now();setInterval(()=>{let{canvas,mcp}=handle.connections();if(canvas+mcp>0){idleSince=null;return}if(idleSince===null){idleSince=Date.now();return}if(Date.now()-idleSince>=IDLE_MS)console.error("velloo: canvas idle for 5 min \u2014 shutting down."),shutdown()},30000),await new Promise(()=>{})}});export{daemon_default as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{upgrade_default,migrateFolder2}from"./chunk-mfbxfb9b.js";import"./chunk-pjtg3wnm.js";import"./chunk-avkfsc3p.js";import"./chunk-ph2jfg1x.js";import"./chunk-wafb2xm9.js";import"./chunk-4ma2wnqw.js";import"./chunk-80fjfyha.js";import"./chunk-88eqqdk1.js";import"./chunk-c4fym47a.js";import"./chunk-as08hzp3.js";import"./chunk-n9t36h0q.js";import"./chunk-9p1dk5cb.js";import"./chunk-9psr8atb.js";import"./chunk-s23gtejf.js";import"./chunk-nte0t7v3.js";export{upgrade_default as default,migrateFolder2 as migrateFolder};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{registry2,loadManifest2}from"./chunk-
|
|
2
|
+
import{registry2,loadManifest2}from"./chunk-p62fygqz.js";import"./chunk-c6hywdvq.js";import{snapshotVersion2,entryCssPath2,componentsDir2}from"./chunk-cvn689d5.js";export{componentsDir2 as componentsDir,entryCssPath2 as entryCssPath,loadManifest2 as loadManifest,registry2 as registry,snapshotVersion2 as snapshotVersion};
|