@bepack/cli 0.1.0-beta.3 → 0.1.0-beta.5

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/dist/cli.js CHANGED
@@ -1,10 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import{lstatSync as e,promises as t,readFileSync as n,statSync as r}from"node:fs";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import o,{dirname as s,join as c}from"node:path";import{randomUUID as l}from"node:crypto";import u,{platform as d}from"node:os";import{replacePlugin as f}from"rolldown/plugins";import{exec as p,spawn as m}from"node:child_process";import h,{mkdir as g}from"node:fs/promises";import{rolldown as _}from"rolldown";import{loadConfig as v}from"rolldown/config";import{createRequire as y}from"module";import b from"chokidar";var x=Object.create,S=Object.defineProperty,C=Object.getOwnPropertyDescriptor,w=Object.getOwnPropertyNames,T=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty,D=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},O=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ee=(e,t)=>{let n={};for(var r in e)S(n,r,{get:e[r],enumerable:!0});return t||S(n,Symbol.toStringTag,{value:`Module`}),n},k=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=w(t),a=0,o=i.length,s;a<o;a++)s=i[a],!E.call(e,s)&&s!==n&&S(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=C(t,s))||r.enumerable});return e},A=(e,t,n)=>(n=e==null?{}:x(T(e)),k(t||!e||!e.__esModule||!E.call(e,`default`)?S(n,`default`,{value:e,enumerable:!0}):n,e));function j(e){return e==null?[]:Array.isArray(e)?e:[e]}function M(e,t,n,r){var i,a=e[t],o=~r.string.indexOf(t)?n==null||n===!0?``:String(n):typeof n==`boolean`?n:~r.boolean.indexOf(t)?n===`false`?!1:n===`true`||(e._.push((i=+n,i*0==0?i:n)),!!n):(i=+n,i*0==0?i:n);e[t]=a==null?o:Array.isArray(a)?a.concat(o):[a,o]}function N(e,t){e||=[],t||={};var n,r,i,a,o,s={_:[]},c=0,l=0,u=0,d=e.length;let f=t.alias!==void 0,p=t.unknown!==void 0,m=t.default!==void 0;if(t.alias=t.alias||{},t.string=j(t.string),t.boolean=j(t.boolean),f)for(n in t.alias)for(r=t.alias[n]=j(t.alias[n]),c=0;c<r.length;c++)(t.alias[r[c]]=r.concat(n)).splice(c,1);for(c=t.boolean.length;c-->0;)for(r=t.alias[t.boolean[c]]||[],l=r.length;l-->0;)t.boolean.push(r[l]);for(c=t.string.length;c-->0;)for(r=t.alias[t.string[c]]||[],l=r.length;l-->0;)t.string.push(r[l]);if(m){for(n in t.default)if(a=typeof t.default[n],r=t.alias[n]=t.alias[n]||[],t[a]!==void 0)for(t[a].push(n),c=0;c<r.length;c++)t[a].push(r[c])}let h=p?Object.keys(t.alias):[];for(c=0;c<d;c++){if(i=e[c],i===`--`){s._=s._.concat(e.slice(++c));break}for(l=0;l<i.length&&i.charCodeAt(l)===45;l++);if(l===0)s._.push(i);else if(i.substring(l,l+3)===`no-`){if(a=i.substring(l+3),p&&!~h.indexOf(a))return t.unknown(i);s[a]=!1}else{for(u=l+1;u<i.length&&i.charCodeAt(u)!==61;u++);for(a=i.substring(l,u),o=i.substring(++u)||c+1===d||(``+e[c+1]).charCodeAt(0)===45||e[++c],r=l===2?[a]:a,u=0;u<r.length;u++){if(a=r[u],p&&!~h.indexOf(a))return t.unknown(`-`.repeat(l)+a);M(s,a,u+1<r.length||o,t)}}}if(m)for(n in t.default)s[n]===void 0&&(s[n]=t.default[n]);if(f)for(n in s)for(r=t.alias[n]||[];r.length>0;)s[r.shift()]=s[n];return s}function te(e){return e.replace(/[<[].+/,``).trim()}function ne(e){let t=/<([^>]+)>/g,n=/\[([^\]]+)\]/g,r=[],i=e=>{let t=!1,n=e[1];return n.startsWith(`...`)&&(n=n.slice(3),t=!0),{required:e[0].startsWith(`<`),value:n,variadic:t}},a;for(;a=t.exec(e);)r.push(i(a));let o;for(;o=n.exec(e);)r.push(i(o));return r}function P(e){let t={alias:{},boolean:[]};for(let[n,r]of e.entries())r.names.length>1&&(t.alias[r.names[0]]=r.names.slice(1)),r.isBoolean&&(r.negated&&e.some((e,t)=>t!==n&&e.names.some(e=>r.names.includes(e))&&typeof e.required==`boolean`)||t.boolean.push(r.names[0]));return t}function re(e){return e.sort((e,t)=>e.length>t.length?-1:1)[0]}function ie(e,t){return e.length>=t?e:`${e}${` `.repeat(t-e.length)}`}function ae(e){return e.replaceAll(/([a-z])-([a-z])/g,(e,t,n)=>t+n.toUpperCase())}function F(e,t,n){let r=e;for(let e=0;e<t.length;e++){let i=t[e];if(e===t.length-1){r[i]=n;return}if(r[i]==null){let n=+t[e+1]>-1;r[i]=n?[]:{}}r=r[i]}}function oe(e,t){for(let n of Object.keys(t)){let r=t[n];r.shouldTransform&&(e[n]=[e[n]].flat(),typeof r.transformFunction==`function`&&(e[n]=e[n].map(r.transformFunction)))}}function se(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:``}function ce(e){return e.split(`.`).map((e,t)=>t===0?ae(e):e).join(`.`)}var le=class extends Error{constructor(e){super(e),this.name=`CACError`,typeof Error.captureStackTrace!=`function`&&(this.stack=Error(e).stack)}},ue=class{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,n){this.rawName=e,this.description=t,this.config=Object.assign({},n),e=e.replaceAll(`.*`,``),this.negated=!1,this.names=te(e).split(`,`).map(e=>{let t=e.trim().replace(/^-{1,2}/,``);return t.startsWith(`no-`)&&(this.negated=!0,t=t.replace(/^no-/,``)),ce(t)}).sort((e,t)=>e.length>t.length?1:-1),this.name=this.names.at(-1),this.negated&&this.config.default==null&&(this.config.default=!0),e.includes(`<`)?this.required=!0:e.includes(`[`)?this.required=!1:this.isBoolean=!0}};let de,fe;if(typeof process<`u`){let e;e=typeof Deno<`u`&&typeof Deno.version?.deno==`string`?`deno`:typeof Bun<`u`&&typeof Bun.version==`string`?`bun`:`node`,fe=`${process.platform}-${process.arch} ${e}-${process.version}`,de=process.argv}else fe=typeof navigator>`u`?`unknown`:`${navigator.platform} ${navigator.userAgent}`;var pe=class{rawName;description;config;cli;options;aliasNames;name;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;constructor(e,t,n={},r){this.rawName=e,this.description=t,this.config=n,this.cli=r,this.options=[],this.aliasNames=[],this.name=te(e),this.args=ne(e),this.examples=[]}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t=`-v, --version`){return this.versionNumber=e,this.option(t,`Display version number`),this}example(e){return this.examples.push(e),this}option(e,t,n){let r=new ue(e,t,n);return this.options.push(r),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}isMatched(e){return this.name===e||this.aliasNames.includes(e)}get isDefaultCommand(){return this.name===``||this.aliasNames.includes(`!`)}get isGlobalCommand(){return this instanceof me}hasOption(e){return e=e.split(`.`)[0],this.options.find(t=>t.names.includes(e))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:n,options:r,helpCallback:i}=this.cli.globalCommand,a=[{body:`${e}${n?`/${n}`:``}`}];if(a.push({title:`Usage`,body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let n=re(t.map(e=>e.rawName));a.push({title:`Commands`,body:t.map(e=>` ${ie(e.rawName,n.length)} ${e.description}`).join(`
2
+ import{constants as e,lstatSync as t,promises as n,readFileSync as r,statSync as i}from"node:fs";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import s,{dirname as c,join as l}from"node:path";import{randomUUID as u}from"node:crypto";import d,{platform as f}from"node:os";import{replacePlugin as p}from"rolldown/plugins";import{spawn as m}from"node:child_process";import h,{access as g,mkdir as _,readFile as v}from"node:fs/promises";import{rolldown as y}from"rolldown";import{loadConfig as b}from"rolldown/config";import{createRequire as x}from"module";import S from"chokidar";var C=Object.create,w=Object.defineProperty,T=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,ee=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty,te=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},O=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),k=(e,t)=>{let n={};for(var r in e)w(n,r,{get:e[r],enumerable:!0});return t||w(n,Symbol.toStringTag,{value:`Module`}),n},ne=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=E(t),a=0,o=i.length,s;a<o;a++)s=i[a],!D.call(e,s)&&s!==n&&w(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=T(t,s))||r.enumerable});return e},A=(e,t,n)=>(n=e==null?{}:C(ee(e)),ne(t||!e||!e.__esModule||!D.call(e,`default`)?w(n,`default`,{value:e,enumerable:!0}):n,e));function j(e){return e==null?[]:Array.isArray(e)?e:[e]}function re(e,t,n,r){var i,a=e[t],o=~r.string.indexOf(t)?n==null||n===!0?``:String(n):typeof n==`boolean`?n:~r.boolean.indexOf(t)?n===`false`?!1:n===`true`||(e._.push((i=+n,i*0==0?i:n)),!!n):(i=+n,i*0==0?i:n);e[t]=a==null?o:Array.isArray(a)?a.concat(o):[a,o]}function ie(e,t){e||=[],t||={};var n,r,i,a,o,s={_:[]},c=0,l=0,u=0,d=e.length;let f=t.alias!==void 0,p=t.unknown!==void 0,m=t.default!==void 0;if(t.alias=t.alias||{},t.string=j(t.string),t.boolean=j(t.boolean),f)for(n in t.alias)for(r=t.alias[n]=j(t.alias[n]),c=0;c<r.length;c++)(t.alias[r[c]]=r.concat(n)).splice(c,1);for(c=t.boolean.length;c-->0;)for(r=t.alias[t.boolean[c]]||[],l=r.length;l-->0;)t.boolean.push(r[l]);for(c=t.string.length;c-->0;)for(r=t.alias[t.string[c]]||[],l=r.length;l-->0;)t.string.push(r[l]);if(m){for(n in t.default)if(a=typeof t.default[n],r=t.alias[n]=t.alias[n]||[],t[a]!==void 0)for(t[a].push(n),c=0;c<r.length;c++)t[a].push(r[c])}let h=p?Object.keys(t.alias):[];for(c=0;c<d;c++){if(i=e[c],i===`--`){s._=s._.concat(e.slice(++c));break}for(l=0;l<i.length&&i.charCodeAt(l)===45;l++);if(l===0)s._.push(i);else if(i.substring(l,l+3)===`no-`){if(a=i.substring(l+3),p&&!~h.indexOf(a))return t.unknown(i);s[a]=!1}else{for(u=l+1;u<i.length&&i.charCodeAt(u)!==61;u++);for(a=i.substring(l,u),o=i.substring(++u)||c+1===d||(``+e[c+1]).charCodeAt(0)===45||e[++c],r=l===2?[a]:a,u=0;u<r.length;u++){if(a=r[u],p&&!~h.indexOf(a))return t.unknown(`-`.repeat(l)+a);re(s,a,u+1<r.length||o,t)}}}if(m)for(n in t.default)s[n]===void 0&&(s[n]=t.default[n]);if(f)for(n in s)for(r=t.alias[n]||[];r.length>0;)s[r.shift()]=s[n];return s}function M(e){return e.replace(/[<[].+/,``).trim()}function ae(e){let t=/<([^>]+)>/g,n=/\[([^\]]+)\]/g,r=[],i=e=>{let t=!1,n=e[1];return n.startsWith(`...`)&&(n=n.slice(3),t=!0),{required:e[0].startsWith(`<`),value:n,variadic:t}},a;for(;a=t.exec(e);)r.push(i(a));let o;for(;o=n.exec(e);)r.push(i(o));return r}function oe(e){let t={alias:{},boolean:[]};for(let[n,r]of e.entries())r.names.length>1&&(t.alias[r.names[0]]=r.names.slice(1)),r.isBoolean&&(r.negated&&e.some((e,t)=>t!==n&&e.names.some(e=>r.names.includes(e))&&typeof e.required==`boolean`)||t.boolean.push(r.names[0]));return t}function se(e){return e.sort((e,t)=>e.length>t.length?-1:1)[0]}function N(e,t){return e.length>=t?e:`${e}${` `.repeat(t-e.length)}`}function ce(e){return e.replaceAll(/([a-z])-([a-z])/g,(e,t,n)=>t+n.toUpperCase())}function le(e,t,n){let r=e;for(let e=0;e<t.length;e++){let i=t[e];if(e===t.length-1){r[i]=n;return}if(r[i]==null){let n=+t[e+1]>-1;r[i]=n?[]:{}}r=r[i]}}function ue(e,t){for(let n of Object.keys(t)){let r=t[n];r.shouldTransform&&(e[n]=[e[n]].flat(),typeof r.transformFunction==`function`&&(e[n]=e[n].map(r.transformFunction)))}}function de(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:``}function fe(e){return e.split(`.`).map((e,t)=>t===0?ce(e):e).join(`.`)}var pe=class extends Error{constructor(e){super(e),this.name=`CACError`,typeof Error.captureStackTrace!=`function`&&(this.stack=Error(e).stack)}},me=class{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,n){this.rawName=e,this.description=t,this.config=Object.assign({},n),e=e.replaceAll(`.*`,``),this.negated=!1,this.names=M(e).split(`,`).map(e=>{let t=e.trim().replace(/^-{1,2}/,``);return t.startsWith(`no-`)&&(this.negated=!0,t=t.replace(/^no-/,``)),fe(t)}).sort((e,t)=>e.length>t.length?1:-1),this.name=this.names.at(-1),this.negated&&this.config.default==null&&(this.config.default=!0),e.includes(`<`)?this.required=!0:e.includes(`[`)?this.required=!1:this.isBoolean=!0}};let he,ge;if(typeof process<`u`){let e;e=typeof Deno<`u`&&typeof Deno.version?.deno==`string`?`deno`:typeof Bun<`u`&&typeof Bun.version==`string`?`bun`:`node`,ge=`${process.platform}-${process.arch} ${e}-${process.version}`,he=process.argv}else ge=typeof navigator>`u`?`unknown`:`${navigator.platform} ${navigator.userAgent}`;var _e=class{rawName;description;config;cli;options;aliasNames;name;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;constructor(e,t,n={},r){this.rawName=e,this.description=t,this.config=n,this.cli=r,this.options=[],this.aliasNames=[],this.name=M(e),this.args=ae(e),this.examples=[]}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t=`-v, --version`){return this.versionNumber=e,this.option(t,`Display version number`),this}example(e){return this.examples.push(e),this}option(e,t,n){let r=new me(e,t,n);return this.options.push(r),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}isMatched(e){return this.name===e||this.aliasNames.includes(e)}get isDefaultCommand(){return this.name===``||this.aliasNames.includes(`!`)}get isGlobalCommand(){return this instanceof ve}hasOption(e){return e=e.split(`.`)[0],this.options.find(t=>t.names.includes(e))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:n,options:r,helpCallback:i}=this.cli.globalCommand,a=[{body:`${e}${n?`/${n}`:``}`}];if(a.push({title:`Usage`,body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let n=se(t.map(e=>e.rawName));a.push({title:`Commands`,body:t.map(e=>` ${N(e.rawName,n.length)} ${e.description}`).join(`
3
3
  `)},{title:"For more info, run any command with the `--help` flag",body:t.map(t=>` $ ${e}${t.name===``?``:` ${t.name}`} --help`).join(`
4
- `)})}let o=this.isGlobalCommand?r:[...this.options,...r||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand&&(o=o.filter(e=>e.name!==`version`)),o.length>0){let e=re(o.map(e=>e.rawName));a.push({title:`Options`,body:o.map(t=>` ${ie(t.rawName,e.length)} ${t.description} ${t.config.default===void 0?``:`(default: ${t.config.default})`}`).join(`
4
+ `)})}let o=this.isGlobalCommand?r:[...this.options,...r||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand&&(o=o.filter(e=>e.name!==`version`)),o.length>0){let e=se(o.map(e=>e.rawName));a.push({title:`Options`,body:o.map(t=>` ${N(t.rawName,e.length)} ${t.description} ${t.config.default===void 0?``:`(default: ${t.config.default})`}`).join(`
5
5
  `)})}this.examples.length>0&&a.push({title:`Examples`,body:this.examples.map(t=>typeof t==`function`?t(e):t).join(`
6
6
  `)}),i&&(a=i(a)||a),console.info(a.map(e=>e.title?`${e.title}:\n${e.body}`:e.body).join(`
7
7
 
8
- `))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;t&&console.info(`${e}/${t} ${fe}`)}checkRequiredArgs(){let e=this.args.filter(e=>e.required).length;if(this.cli.args.length<e)throw new le(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let n of Object.keys(e))if(n!==`--`&&!this.hasOption(n)&&!t.hasOption(n))throw new le(`Unknown option \`${n.length>1?`--${n}`:`-${n}`}\``)}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,n=[...t.options,...this.options];for(let t of n){let r=e[t.name.split(`.`)[0]];if(t.required){let e=n.some(e=>e.negated&&e.names.includes(t.name));if(r===!0||r===!1&&!e)throw new le(`option \`${t.rawName}\` value is missing`)}}}checkUnusedArgs(){let e=this.args.some(e=>e.variadic)?1/0:this.args.length;if(e<this.cli.args.length)throw new le(`Unused args: ${this.cli.args.slice(e).map(e=>`\`${e}\``).join(`, `)}`)}},me=class extends pe{constructor(e){super(`@@global@@`,``,{},e)}},he=class extends EventTarget{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;constructor(e=``){super(),this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new me(this),this.globalCommand.usage(`<command> [options]`)}usage(e){return this.globalCommand.usage(e),this}command(e,t,n){let r=new pe(e,t||``,n,this);return r.globalCommand=this.globalCommand,this.commands.push(r),r}option(e,t,n){return this.globalCommand.option(e,t,n),this}help(e){return this.globalCommand.option(`-h, --help`,`Display this message`),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t=`-v, --version`){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){this.matchedCommand?this.matchedCommand.outputHelp():this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},n,r){return this.args=e,this.options=t,n&&(this.matchedCommand=n),r&&(this.matchedCommandName=r),this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(e,{run:t=!0}={}){if(!e){if(!de)throw Error(`No argv provided and runtime process argv is not available.`);e=de}this.rawArgs=e,this.name||=e[1]?se(e[1]):`cli`;let n=!0;for(let t of this.commands){let r=this.mri(e.slice(2),t),i=r.args[0];if(t.isMatched(i)){n=!1;let e={...r,args:r.args.slice(1)};this.setParsedInfo(e,t,i),this.dispatchEvent(new CustomEvent(`command:${i}`,{detail:t}))}}if(n){for(let t of this.commands)if(t.isDefaultCommand){n=!1;let r=this.mri(e.slice(2),t);this.setParsedInfo(r,t),this.dispatchEvent(new CustomEvent(`command:!`,{detail:t}))}}if(n){let t=this.mri(e.slice(2));this.setParsedInfo(t)}this.options.help&&this.showHelpOnExit&&(this.outputHelp(),t=!1,this.unsetMatchedCommand()),this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null&&(this.outputVersion(),t=!1,this.unsetMatchedCommand());let r={args:this.args,options:this.options};return t&&this.runMatchedCommand(),!this.matchedCommand&&this.args[0]&&this.dispatchEvent(new CustomEvent(`command:*`,{detail:this.args[0]})),r}mri(e,t){let n=[...this.globalCommand.options,...t?t.options:[]],r=P(n),i=[],a=e.indexOf(`--`);a!==-1&&(i=e.slice(a+1),e=e.slice(0,a));let o=N(e,r);o=Object.keys(o).reduce((e,t)=>({...e,[ce(t)]:o[t]}),{_:[]});let s=o._,c={"--":i},l=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,u=Object.create(null);for(let e of n){if(!l&&e.config.default!==void 0)for(let t of e.names)c[t]=e.config.default;Array.isArray(e.config.type)&&u[e.name]===void 0&&(u[e.name]=Object.create(null),u[e.name].shouldTransform=!0,u[e.name].transformFunction=e.config.type[0])}for(let e of Object.keys(o))e!==`_`&&(F(c,e.split(`.`),o[e]),oe(c,u));return{args:s,options:c}}runMatchedCommand(){let{args:e,options:t,matchedCommand:n}=this;if(!n||!n.commandAction)return;n.checkUnknownOptions(),n.checkOptionValue(),n.checkRequiredArgs(),n.checkUnusedArgs();let r=[];return n.args.forEach((t,n)=>{t.variadic?r.push(e.slice(n)):r.push(e[n])}),r.push(t),n.commandAction.apply(this,r)}};const ge=(e=``)=>new he(e);function _e(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Invalid JSON in ${t}: ${e instanceof Error?e.message:String(e)}`)}}function ve(e){return`${JSON.stringify(e,null,4)}\n`}async function I(e){try{return await t.access(e),!0}catch{return!1}}async function ye(e){await t.mkdir(e,{recursive:!0})}async function be(e){await t.rm(e,{recursive:!0,force:!0}),await t.mkdir(e,{recursive:!0})}async function xe(e){return _e(await t.readFile(e,`utf8`),e)}async function Se(e,n){await ye(o.dirname(e)),await t.writeFile(e,ve(n),`utf8`)}async function Ce(e,n){await t.rm(n,{recursive:!0,force:!0}),await t.mkdir(o.dirname(n),{recursive:!0}),await t.cp(e,n,{recursive:!0})}var L=class extends Error{code;details;suggestions;constructor(e,t,n={}){super(t),this.name=`BePackError`,this.code=e,this.details=n.details,this.suggestions=n.suggestions}},we=/* @__PURE__ */ A((/* @__PURE__ */ O(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})))(),1);const R=we.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);var Te=class{options;constructor(e={}){this.options=e}formatDuration(e){return R.green(`${(e/1e3).toFixed(2)}s`)}info(e){this.options.silent||console.log(e)}warn(e){this.options.silent||console.warn(R.yellow(e))}error(e){this.options.silent||console.error(R.red(e))}verbose(e){!this.options.silent&&this.options.verbose&&console.log(R.gray(e))}clear(){this.options.silent||console.clear()}step(e,t,n=`cyan`){this.info(`${R[n](e.padEnd(10))} ${t}`)}progress(e,t){this.step(e,t,`blue`)}success(e,t){this.step(e,t,`green`)}bepack(e,t){this.info(`${R.green(`bepack`)} ${R.bold(e)} ${R.gray(t)}`)}manifest(e){this.step(`manifest`,e,`yellow`)}typescript(e){this.step(`TS`,e,`blue`)}rolldown(e){this.step(`rolldown`,e,`magenta`)}install(e){this.step(`install`,e,`blue`)}copy(e){this.step(`copy`,e,`cyan`)}pack(e){this.step(`pack`,e,`magenta`)}hook(e,t){this.step(`hook`,`${e}: ${t}`,`gray`)}timing(e,t){this.step(`timing`,`${e.padEnd(14)} ${t} ms`,`gray`)}done(e,t){this.info(`${R.green(`√`)} ${R.green(e)} ${t}`)}};function Ee(e){return Array.isArray(e)&&e.length===3&&typeof e[0]==`number`&&typeof e[1]==`number`&&typeof e[2]==`number`}function De(e){return typeof e==`string`&&/^\d+\.\d+\.\d+$/.test(e)}function Oe(e){return e===3?De:Ee}function ke(e,t){return e===3?`${t} must be SemVer string like "x.y.z" (format 3)`:`${t} must be [number, number, number] (format 2)`}const Ae=[e=>e.format_version===void 0?`format_version is required`:null,e=>e.header?null:`header is required`,e=>e.header&&!e.header.name?`header.name is required`:null,e=>e.header&&!e.header.uuid?`header.uuid is required`:null,e=>e.header?Oe(e.format_version)(e.header.version)?null:ke(e.format_version,`header.version`):null,e=>e.header?Oe(e.format_version)(e.header.min_engine_version)?null:ke(e.format_version,`header.min_engine_version`):null,e=>e.modules!==void 0&&!Array.isArray(e.modules)?`modules must be an array`:null,(e,t)=>{if(!Array.isArray(e.modules))return null;let n=e.modules.some(e=>e?.type===`resources`),r=[];return t===`rp`&&!n&&r.push(`RP manifest must have a resources module`),r.length>0?r:null},e=>{if(!Array.isArray(e.modules))return null;let t=Oe(e.format_version),n=[];for(let r=0;r<e.modules.length;r++){let i=e.modules[r];i&&i.version!==void 0&&i.version!==null&&!t(i.version)&&n.push(`modules[${r}] (uuid: ${i.uuid??`unknown`}): ${ke(e.format_version,`version`)}`)}return n.length>0?n:null},e=>e.dependencies!==void 0&&!Array.isArray(e.dependencies)?`dependencies must be an array`:null,e=>{if(!Array.isArray(e.dependencies))return null;let t=Oe(e.format_version),n=[];for(let r=0;r<e.dependencies.length;r++){let i=e.dependencies[r];if(!i){n.push(`dependencies[${r}] is invalid`);continue}`uuid`in i&&i.uuid&&!t(i.version)&&n.push(`dependencies[${r}] (uuid: ${i.uuid}): ${ke(e.format_version,`version`)}`),`module_name`in i&&i.module_name&&typeof i.version!=`string`&&n.push(`dependencies[${r}] (module_name: ${i.module_name}): version must be a string`)}return n.length>0?n:null},e=>e.capabilities===void 0?null:Array.isArray(e.capabilities)?e.capabilities.every(e=>typeof e==`string`)?null:`capabilities must be an array of strings`:`capabilities must be an array`,e=>e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)?`metadata must be an object`:null];function je(e,t){let n=[];for(let r of Ae){let i=r(e,t);i!==null&&(Array.isArray(i)?n.push(...i):n.push(i))}if(n.length>0)throw new L(`MANIFEST_INVALID`,`Manifest validation failed: ${n.join(`; `)}`)}function Me(e){return!e||typeof e!=`object`||Array.isArray(e)?{}:{...e}}function Ne(e){return Array.isArray(e)?e:[]}var Pe=class{static async read(e){if(!await I(e))return;let n=await t.readFile(e,`utf8`);try{return Me(JSON.parse(n))}catch{throw new L(`MANIFEST_INVALID`,`Invalid JSON in manifest: ${e}`)}}static async write(e,t,n){je(t,n),await Se(e,t)}};function Fe(e){let t=/^(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)throw new L(`VERSION_INVALID`,`Manifest version requires x.y.z.`,{details:{version:e}});return[Number(t[1]),Number(t[2]),Number(t[3])]}function Ie(e){return/^\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/.test(e)}function z(e,t){let n=e.split(/[^0-9A-Za-z]+/),r=t.split(/[^0-9A-Za-z]+/),i=Math.max(n.length,r.length);for(let e=0;e<i;e+=1){let t=n[e]??``,i=r[e]??``,a=/^\d+$/.test(t)?Number(t):NaN,o=/^\d+$/.test(i)?Number(i):NaN,s=Number.isNaN(a)||Number.isNaN(o)?t.localeCompare(i):a-o;if(s!==0)return s}return 0}function Le(e){return e===`latest`||z(e,`1.21.120`)>=0}function Re(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(e.trim());if(!t)return;let n=/(?:^|[.-])(\d+)\.(\d+)\.(\d+)(?:[.-]|$)/.exec(t[4]??``);return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),...n?{minecraftTarget:[Number(n[1]),Number(n[2]),Number(n[3])]}:{}}}function ze(e,t){for(let n of[`major`,`minor`,`patch`])if(e[n]!==t[n])return e[n]-t[n];return 0}function Be(e,t){let n=Re(e);return n?t.split(`||`).some(e=>{let t=/(?:\^|~|>=|<=|>|<|=)?\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(e.trim()),r=t?Re(t[1]):void 0;return!r||n.major!==r.major||ze(n,r)<0?!1:r.minecraftTarget?n.minecraftTarget?z(n.minecraftTarget.join(`.`),r.minecraftTarget.join(`.`))>=0:!1:!0}):!1}function Ve(e){if(e===`stable`||e===`beta`||e===`preview`)throw new L(`DEPENDENCY_VERSION_INVALID`,`${e} must be resolved from npm registry before writing package.json.`,{details:{specifier:e}});if(Ie(e))return e;throw new L(`DEPENDENCY_VERSION_INVALID`,`Unsupported dependency version: ${e}`,{details:{specifier:e}})}function He(e){return e.filter(e=>/^\d+\.\d+\.\d+$/.test(e)).sort(z)}function Ue(e){return e.filter(e=>/(?:^|[-.])beta(?:[-.]|$)/i.test(e)).sort(z)}var We=class{npm;logger;constructor(e,t){this.npm=e,this.logger=t}latestStable(e,t){let n=this.npm.distTag(t,`latest`);if(n&&/^\d+\.\d+\.\d+$/.test(n))return this.logger?.verbose(`Resolved ${e}@stable -> ${n}`),n;let r=He(this.npm.versions(t)).at(-1);if(!r)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest stable version for ${e}.`,{details:{package:e}});return this.logger?.verbose(`Resolved ${e}@stable -> ${r}`),r}latestBeta(e,t){let n=this.npm.distTag(t,`beta`);if(n)return this.logger?.verbose(`Resolved ${e}@beta -> ${n}`),n;let r=Ue(this.npm.versions(t)).at(-1);if(!r)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest beta version for ${e}.`,{details:{package:e}});return this.logger?.verbose(`Resolved ${e}@beta -> ${r}`),r}betaForTarget(e,t,n){let r=t.replace(/\./g,`\\.`),i=RegExp(`beta[-.]${r}-stable`),a=this.npm.versions(n).filter(e=>i.test(e)).sort(z).at(-1);if(!a)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e}@beta for target ${t}.`,{details:{package:e,specifier:`beta`,target:t},suggestions:[`Use target: "latest"`,`Specify an exact version`,`Update BePack`,`Manually edit package.json and manifest.json`]});return this.logger?.verbose(`Resolved ${e}@beta for target ${t} -> ${a}`),a}inferStableFromBeta(e,t,n,r){let i=/^(\d+)\.(\d+)\.(\d+)-beta[.-]/.exec(n);if(!i)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot infer stable version from ${e}@${n}.`,{details:{package:e,beta:n,target:t}});let a=Number(i[1]),o=Number(i[2])-1,s=`${a}.${o}.${Number(i[3])}`;if(o<0||!r.versions?.[s])throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot confirm inferred stable version ${s} for ${e}.`,{details:{package:e,target:t,beta:n,inferredStable:s}});return s}};function Ge(e,t){return t===`latest`||Le(t)?`beta`:/^(\d+\.\d+\.\d+-beta)/i.exec(e)?.[1]??e}function Ke(e,t,n){let r=Ue(t).filter(e=>/^\d+\.\d+\.\d+-beta\.\d+\.\d+\.\d+/.test(e)).filter(e=>!/(?:rc|beta)\.\d+\.\d+\.\d+-preview\.\d+$/i.test(e)).at(-1);if(!r)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest beta version for ${e}.`,{details:{package:e}});return n?.verbose(`Resolved ${e}@beta -> ${r}`),r}function qe(e){return e.filter(e=>/(?:rc|beta)\.\d+\.\d+\.\d+-preview\.\d+$/i.test(e)).sort(z)}function Je(e,t,n){let r=qe(t).at(-1);if(!r)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest preview version for ${e}.`,{details:{package:e}});return n?.verbose(`Resolved ${e}@preview -> ${r}`),r}function Ye(e,t,n,r){let i=n.replace(/\./g,`\\.`),a=RegExp(`(?:rc|beta)\\.${i}-preview\\.\\d+$`),o=t.filter(e=>a.test(e)).sort(z).at(-1);if(!o)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e}@preview for target ${n}.`,{details:{package:e,specifier:`preview`,target:n},suggestions:[`Use target: "latest"`,`Specify an exact version`]});return r?.verbose(`Resolved ${e}@preview for target ${n} -> ${o}`),o}const Xe={name:`minecraft-script-api`,resolver:`minecraft-script-api`,match:e=>e.specifier===`stable`||e.specifier===`beta`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName),n=new We(e.npm,e.logger);if(e.specifier===`stable`){e.logger?.verbose(`Resolving ${e.packageName}@stable for target ${e.target}`);let r=e.target===`latest`?n.latestStable(e.packageName,t):n.inferStableFromBeta(e.packageName,e.target,n.betaForTarget(e.packageName,e.target,t),t);return{packageVersion:r,manifestVersion:r}}if(e.specifier===`beta`){e.logger?.verbose(`Resolving ${e.packageName}@beta for target ${e.target}`);let r=e.target===`latest`?Ke(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:Ge(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?Je(e.packageName,e.npm.versions(t),e.logger):Ye(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}},Ze={name:`minecraft-script-api-bp`,resolver:`minecraft-script-api-bp`,match:e=>e.specifier===`beta`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName),n=new We(e.npm,e.logger);if(e.specifier===`beta`){e.logger?.verbose(`Resolving ${e.packageName}@beta for target ${e.target}`);let r=e.target===`latest`?Ke(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:Ge(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?Je(e.packageName,e.npm.versions(t),e.logger):Ye(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}},Qe=/^\d+\.\d+\.\d+$/,$e=/^\d+\.\d+\.\d+-preview\.\d+$/,et={name:`minecraft-vanilla-data`,resolver:`minecraft-vanilla-data`,match:e=>e.specifier===`stable`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName);return e.specifier===`stable`?tt(e,t):nt(e,t)}};function tt(e,t){if(e.logger?.verbose(`Resolving ${e.packageName}@stable for target ${e.target}`),e.target===`latest`){let n=e.npm.distTag(t,`latest`);if(n&&Qe.test(n))return e.logger?.verbose(`Resolved ${e.packageName}@stable -> ${n}`),{packageVersion:n};let r=e.npm.versions(t).filter(e=>Qe.test(e)).sort(z).at(-1);if(!r)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest stable version for ${e.packageName}.`,{details:{package:e.packageName}});return e.logger?.verbose(`Resolved ${e.packageName}@stable -> ${r}`),{packageVersion:r}}if(t.versions?.[e.target])return e.logger?.verbose(`Resolved ${e.packageName}@stable for target ${e.target} -> ${e.target}`),{packageVersion:e.target};throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e.packageName}@stable for target ${e.target}. The target version does not exist in the registry.`,{details:{package:e.packageName,specifier:`stable`,target:e.target},suggestions:[`Use target: "latest"`,`Specify an exact version`]})}function nt(e,t){if(e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`),e.target===`latest`){let n=e.npm.versions(t).filter(e=>$e.test(e)).sort(z).at(-1);if(!n)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest preview version for ${e.packageName}.`,{details:{package:e.packageName}});return e.logger?.verbose(`Resolved ${e.packageName}@preview -> ${n}`),{packageVersion:n}}let n=e.target.replace(/\./g,`\\.`),r=RegExp(`^${n}-preview\\.\\d+$`),i=e.npm.versions(t).filter(e=>r.test(e)).sort(z).at(-1);if(!i)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e.packageName}@preview for target ${e.target}. No matching preview version found.`,{details:{package:e.packageName,specifier:`preview`,target:e.target},suggestions:[`Use target: "latest"`,`Specify an exact preview version`]});return e.logger?.verbose(`Resolved ${e.packageName}@preview for target ${e.target} -> ${i}`),{packageVersion:i}}const rt={"@minecraft/common":{resolver:Xe,manifest:!0},"@minecraft/server":{resolver:Xe,manifest:!0},"@minecraft/server-ui":{resolver:Xe,manifest:!0},"@minecraft/server-net":{resolver:Ze,manifest:!0},"@minecraft/server-admin":{resolver:Ze,manifest:!0},"@minecraft/server-gametest":{resolver:Ze,manifest:!0},"@minecraft/debug-utilities":{resolver:Ze,manifest:!0},"@minecraft/diagnostics":{resolver:Ze,manifest:!0},"@minecraft/server-graphics":{resolver:Ze,manifest:!0},"@minecraft/server-editor":{resolver:Ze,manifest:!0},"@minecraft/vanilla-data":{resolver:et,manifest:!1}};var it=class e{static validateHeader(e,t){if(!e.header?.name||!e.header?.uuid)throw new L(`MANIFEST_INVALID`,`${t} manifest is missing header.name or header.uuid`);return{name:e.header.name,uuid:e.header.uuid,...e.header.description?{description:e.header.description}:{}}}static findScriptModuleUuid(t){for(let n of t.modules??[])if(n&&e.isScriptModule(n))return n.uuid}static findScriptModuleEntry(t){for(let n of t.modules??[])if(n&&e.isScriptModule(n))return n.entry}static findResourcesModuleUuid(t){for(let n of t.modules??[])if(n&&e.isResourcesModule(n))return n.uuid}static matchDependencies(e){let t={};for(let n of e.dependencies??[])if(`module_name`in n&&typeof n.module_name==`string`){let e=n.module_name;rt[e]&&(t[e]=typeof n.version==`string`?n.version:String(n.version))}return t}static isScriptModule(e){return e?.type===`script`&&e?.language===`javascript`}static isResourcesModule(e){return e?.type===`resources`}};function at(e,t){if(typeof e!=`string`||!e)throw new L(`MANIFEST_INVALID`,`${t} script module entry must be a non-empty string.`);let n=e.replace(/\\/g,`/`);if(o.posix.isAbsolute(n)||o.win32.isAbsolute(n))throw new L(`MANIFEST_INVALID`,`${t} script module entry must be a relative path, got absolute: "${e}".`);if(!n.endsWith(`.js`))throw new L(`MANIFEST_INVALID`,`${t} script module entry must end with .js, got: "${e}".`);let r=n.split(`/`);if(r.includes(`..`))throw new L(`MANIFEST_INVALID`,`${t} script module entry must not contain "..": "${e}".`);if(r.includes(``))throw new L(`MANIFEST_INVALID`,`${t} script module entry must not contain empty segments: "${e}".`);return n}function ot(e,t){let n=o.resolve(e,t),r=o.dirname(n),i=o.relative(e,r);if(i.startsWith(`..`)||o.isAbsolute(i))throw new L(`CONFIG_INVALID`,`Manifest path is outside the project directory: ${t}`);return i||`.`}async function st(e,t){if(!t&&await I(e))throw new L(`CONFIG_INVALID`,`Config file already exists: ${e}. Use --force to overwrite.`,{suggestions:[`Pass --force to overwrite the existing file.`]})}async function ct(e,n,r,i=!1){return await st(e,r),!i&&(await ye(o.dirname(e)),await t.writeFile(e,n,`utf8`),!0)}const lt=[`.ts`,`.mts`,`.js`,`.mjs`];async function ut(e,t){let n=(t===`main`?[`main`]:[t,`main`]).flatMap(e=>lt.map(t=>`src/${e}${t}`));for(let t of n)if(await I(o.join(e,t))){let e=o.extname(t);return{entry:t,typecheckable:e===`.ts`||e===`.mts`,searched:n}}}function dt(e){return(e===`main`?[`main`]:[e,`main`]).map(e=>`src/${e}.{${lt.join(`,`).replace(/\./g,``)}}`).join(` or `)}function ft(e){return`export default ${JSON.stringify(e,null,4).replace(/\n( +)"([a-zA-Z_$][a-zA-Z0-9_$]*)": /g,`
9
- $1$2: `)}\n`}function pt(e){if(e){if(Array.isArray(e))return e.join(`.`);if(typeof e==`string`)return e}}function mt(e,t){return e[0]===t[0]?e[1]===t[1]?e[2]-t[2]:e[1]-t[1]:e[0]-t[0]}function ht(e){if(Array.isArray(e)&&e.length===3)return e;if(typeof e==`string`){let t=e.split(`.`).map(Number);if(t.length===3&&t.every(e=>!Number.isNaN(e)))return t}}async function gt(e,t){let n=t.format??`ts`;if(![`ts`,`js`,`mjs`].includes(n))throw new L(`CONFIG_INVALID`,`init --format must be ts, js, or mjs.`);let r=o.join(e,`bepack.config.${n}`),i=!!t.force,a=!!t.dryRun,s=new Te({silent:t.silent,verbose:t.verbose}),c=!!t.fromBp,l=!!t.fromRp,u,d,f,p=!1,m,h,g,_,v,y,b=[];if(c){let n=o.resolve(e,t.fromBp),r=await Pe.read(n);if(!r)throw new L(`CONFIG_NOT_FOUND`,`BP manifest not found: ${t.fromBp}`);f??=r.format_version,r.format_version!==void 0&&r.header?.version!==void 0&&(r.format_version===3&&Array.isArray(r.header.version)||r.format_version===2&&typeof r.header.version==`string`)&&(p=!0);let i=it.validateHeader(r,`BP`),a=it.findScriptModuleUuid(r),s=it.findScriptModuleEntry(r),c=pt(r.header?.version);c&&b.push(c),u={root:ot(e,n),uuid:i.uuid,...a?{moduleUuid:a}:{},...c?{version:c}:{},deps:it.matchDependencies(r),...s?{scriptEntry:s}:{}},m=i.name,h=i.description,g=i.name,_=i.description}if(l){let n=o.resolve(e,t.fromRp),r=await Pe.read(n);if(!r)throw new L(`CONFIG_NOT_FOUND`,`RP manifest not found: ${t.fromRp}`);f??=r.format_version,r.format_version!==void 0&&r.header?.version!==void 0&&(r.format_version===3&&Array.isArray(r.header.version)||r.format_version===2&&typeof r.header.version==`string`)&&(p=!0);let i=it.validateHeader(r,`RP`),a=it.findResourcesModuleUuid(r);if(!a)throw new L(`MANIFEST_INVALID`,`RP manifest is missing a resources module with uuid`);let s=pt(r.header?.version);s&&b.push(s),d={root:ot(e,n),uuid:i.uuid,moduleUuid:a,...s?{version:s}:{}},c||(m=i.name,h=i.description),v=i.name,y=i.description}let x;if(b.length===1)x=b[0];else if(b.length===2){let e=b[0],t=b[1];if(e===t)x=e;else{let n=ht(e),r=ht(t);x=n&&r?mt(n,r)>=0?e:t:e,s.warn(`BP version (${e}) and RP version (${t}) differ. Using ${x}.`)}}p&&(s.warn(`Detected format_version ${f} doesn't match the actual version format used in manifest. Falling back to format_version 2.`),f=2);let S={root:`.`,target:`latest`,pack:{outDir:`dist`}};f!==void 0&&(S.manifestFormat=f),x&&(S.version=x),m&&(S.name=m),h&&(S.description=h);let C={};if(u){let t={root:u.root,uuid:u.uuid};if(u.moduleUuid){if(t.moduleUuid=u.moduleUuid,u.scriptEntry){let n=at(u.scriptEntry,`BP`),r=o.posix.dirname(n),i=o.posix.basename(n,`.js`);if(r===`.`)throw new L(`MANIFEST_INVALID`,`BP manifest script entry "${u.scriptEntry}" is at the BP root. BePack cannot safely manage root-level script output because the output directory would need to be emptied on each build, which would delete the entire BP root. Please add a subdirectory prefix to the script module entry in your manifest.json (e.g. "scripts/main.js"), then rerun init.`);let a=await ut(e,i);if(a){let n=await I(o.join(e,`tsconfig.json`)),i=a.typecheckable&&n;t.compile={entry:a.entry,scriptOutputDir:r,...i?{}:{typecheck:!1}},i||s.warn(`Detected script entry "${u.scriptEntry}" with source "${a.entry}", but ${a.typecheckable?`tsconfig.json is missing`:`the source is JavaScript`}. Generated config sets compile.typecheck: false.`+(a.typecheckable?` Add tsconfig.json and remove that flag to enable typechecking.`:``))}else s.warn(`BP manifest declares script entry "${u.scriptEntry}" but no matching source file exists (looked for ${dt(i)}). Leaving packs.bp.compile unset: the existing "${r}" folder is copied/packed as-is. Set packs.bp.compile manually once you add sources.`)}else s.warn("BP manifest has a script module but no `entry` field, so the script output directory cannot be derived. Leaving packs.bp.compile unset; add it manually to compile TypeScript into the pack.")}g&&(t.name=g),_&&(t.description=_),Object.keys(u.deps).length>0&&(t.dependencies={...u.deps}),C.bp=t}if(d){let e={root:d.root,uuid:d.uuid,moduleUuid:d.moduleUuid};v&&(e.name=v),y&&(e.description=y),C.rp=e}S.packs=C,process.platform===`win32`&&(S.copy={defaultTarget:`win`});let w=await ct(r,ft(S),i,a);return a&&s.info(`init dry-run: would create ${r}`),{ok:!0,command:`init`,dryRun:a,filesCreated:+!!w,files:[r]}}function _t(){return ft({root:`.`,name:`example-addon`,version:`1.0.0`,target:`latest`,packs:{bp:{root:`bp`,uuid:l(),moduleUuid:l(),compile:{entry:`src/main.ts`},dependencies:{"@minecraft/server":`stable`}}},pack:{outDir:`dist`}})}async function vt(e){let t=o.resolve(e.cwd??process.cwd());if(e.fromBp||e.fromRp)return await gt(t,e);let n=e.format??`ts`;if(![`ts`,`js`,`mjs`].includes(n))throw new L(`CONFIG_INVALID`,`init --format must be ts, js, or mjs.`);let r=o.join(t,`bepack.config.${n}`),i=!!e.dryRun,a=await ct(r,_t(),!!e.force,i);return i&&new Te({silent:e.silent,verbose:e.verbose}).info(`init dry-run: would create ${r}`),{ok:!0,command:`init`,dryRun:i,filesCreated:+!!a,files:[r]}}const yt=[`bepack.config.ts`,`bepack.config.mjs`,`bepack.config.js`],B={root:`.`,configured:{root:!1,packOutDir:!1},name:`minecraft-addon`,version:`1.0.0`,description:``,replace:{values:{},builtins:{VERSION:!1,NAME:!1,UUID:!1,DESCRIPTION:!1}},target:`latest`,plugins:[],install:{registry:`https://registry.npmjs.org/`,saveTo:`dependencies`,packageManager:`auto`,runPackageManager:!0,updatePackageJson:!0,updateManifest:!0,dependencyCatalog:{},dependencyResolvers:[]},build:{copy:!1,timing:!1},dev:{copy:!1},copy:{defaultTarget:``,targets:{}},pack:{name:`{name}-{version}`,outDir:`dist`},hooks:{}},bt={dev:!0,build:!1,file:`node_modules/.cache/bepack/tsconfig.tsbuildinfo`},xt={keepLooseFiles:!1,keepLoose:[],exclude:[],minifyJson:!0,packOptimizationVersion:`0.1.0`,allowUnsupportedTarget:!1},St={entry:`src/main.ts`,define:{},tsconfig:`tsconfig.json`,typecheck:!0,preserveModules:!0,external:[/^@minecraft\/server.*/],useNpx:!1,minify:!1,cache:bt,scriptOutputDir:`scripts`},Ct=[`world`,`global`,`any`];function wt(e){let t=[];return e.packs.bp&&t.push({type:`bp`,root:e.packs.bp.root,uuid:e.packs.bp.uuid,...e.packs.bp.moduleUuid===void 0?{}:{moduleUuid:e.packs.bp.moduleUuid},name:e.packs.bp.name,include:e.packs.bp.include}),e.packs.rp&&t.push({type:`rp`,root:e.packs.rp.root,uuid:e.packs.rp.uuid,moduleUuid:e.packs.rp.moduleUuid,name:e.packs.rp.name,include:e.packs.rp.include}),t}const Tt=[`scripts`,`manifest.json`,`animation_controllers`,`animations`,`biomes`,`blocks`,`cameras`,`dialogue`,`entities`,`functions`,`items`,`loot_tables`,`pack_icon.png`,`recipes`,`shapes`,`spawn_rules`,`structures`,`texts`,`trading`,`feature_rules`,`features`,`worldgen`],Et=[];function Dt(e,t){return o.isAbsolute(t)?t:o.join(e,t)}function V(e){return e.replace(/\\/g,`/`)}function H(e,t){return Dt(e,t.root)}function U(e,t,n){return n===`bp`?t.packs.bp?Dt(e,t.packs.bp.root):void 0:t.packs.rp?Dt(e,t.packs.rp.root):void 0}function Ot(e,t){let n=U(H(e,t),t,`bp`);if(!n)throw Error(`packs.bp is not configured`);return n}function kt(e,t){let n=U(H(e,t),t,`rp`);if(!n)throw Error(`packs.rp is not configured`);return n}function At(e){return!!e.packs.bp?.compile}function W(e,t){if(t.packs.bp?.compile)return Dt(H(e,t),t.packs.bp.compile.entry)}function jt(e,t){if(!t.packs.bp)return;let n=t.packs.bp.compile?.scriptOutputDir??`scripts`;return o.join(Ot(e,t),n)}function Mt(e,t){let n=jt(e,t);if(!n)return;if(!t.packs.bp?.compile)return o.join(n,`main.js`);let r=o.basename(t.packs.bp.compile.entry,o.extname(t.packs.bp.compile.entry));return o.join(n,`${r}.js`)}function Nt(e,t){let n=o.relative(e,t);return n===``||!n.startsWith(`..${o.sep}`)&&n!==`..`&&!o.isAbsolute(n)}function Pt(e,t,n){if(!t||t===`.`)throw new L(`CONFIG_INVALID`,`compile.scriptOutputDir must be a non-empty relative path strictly inside the BP root. Got: "${t}". This directory will be emptied during build.`);let r=t.replace(/\\/g,`/`);if(o.posix.isAbsolute(r)||o.win32.isAbsolute(r))throw new L(`CONFIG_INVALID`,`compile.scriptOutputDir must be a relative path, not absolute. Got: "${t}". This directory will be emptied during build.`);let i=o.posix.normalize(r);if(i.split(`/`).includes(`..`))throw new L(`CONFIG_INVALID`,`compile.scriptOutputDir must not contain ".." (path escape). Got: "${t}" resolves outside the BP root. This directory will be emptied during build.`);let a=o.resolve(e,i),s=o.relative(e,a);if(!s||s.startsWith(`..`)||o.isAbsolute(s))throw new L(`CONFIG_INVALID`,`compile.scriptOutputDir must be a directory strictly inside the BP root. Value: "${t}", resolved: "${a}". This directory will be emptied during build and must not be the BP root or a path outside it.`);if(n&&Nt(a,n))throw new L(`CONFIG_INVALID`,`compile.scriptOutputDir "${t}" dangerously overlaps with the source entry directory. The output directory will be emptied during build and would delete source files.`);return V(s)}function Ft(e,t,n,i=[]){let a=o.resolve(e),s=o.resolve(t),c=[s,...i.map(e=>o.resolve(e))];for(let t of c)if(Nt(a,t))throw new L(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" would overwrite a protected path ("${t}"). Refusing to empty this directory.`);try{if(!r(a).isDirectory())throw new L(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" is not a directory. Refusing to empty a non-directory path.`)}catch(e){if(e?.code!==`ENOENT`)throw e}let l=o.relative(s,a);if(!l||l.startsWith(`..`)||o.isAbsolute(l))throw new L(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" is not inside the BP root "${t}". Refusing to empty this directory.`)}function It(e){let t=[e.packs.bp?.compile?.scriptOutputDir??`scripts`,...Tt.filter(e=>e!==`scripts`)],n=e.packs.bp?.include??[],r=[...t,...n],i=/* @__PURE__ */ new Set;return r.filter(e=>!i.has(e)&&(i.add(e),!0))}function Lt(e,t){if(t.packs.bp)return o.join(Ot(e,t),`manifest.json`)}function Rt(e,t){if(t.packs.rp)return o.join(kt(e,t),`manifest.json`)}function zt(e,t){return Dt(H(e,t),t.pack.outDir)}const Bt=d()!==`win32`;function Vt(e){let t=/* @__PURE__ */ new Set;return e.filter(e=>{let n=V(o.resolve(e)),r=Bt?n:n.toLowerCase();return!t.has(r)&&(t.add(r),!0)})}const Ht={VERSION:e=>e.version,NAME:e=>e.name,UUID:e=>e.packs.bp?.uuid??``,DESCRIPTION:e=>e.packs.bp?.description??e.description??``};function Ut(e){return Object.fromEntries(Object.entries(e.replace.values).map(([t,n])=>[t,typeof n==`function`?n(e):n]))}function Wt(e){let t=Ut(e),n=Object.fromEntries(Object.entries(e.replace.builtins).filter(([,e])=>e).map(([t])=>[`**${t}**`,Ht[t](e)])),r={...t,...n};return Object.keys(r).length===0?[]:[f(r,{delimiters:[``,``]})]}function Gt(e){return{values:e?.values??{},builtins:{VERSION:e?.builtins?.VERSION??!1,NAME:e?.builtins?.NAME??!1,UUID:e?.builtins?.UUID??!1,DESCRIPTION:e?.builtins?.DESCRIPTION??!1}}}function Kt(e){let t={...e??{}};for(let[e,n]of Object.entries(t))try{Function(`return (${n});`)}catch{throw new L(`CONFIG_INVALID`,`packs.bp.compile.define["${e}"] is not a valid JavaScript expression: ${n}. Define values must be expression strings, e.g. JSON.stringify("server") or "true".`,{details:{defineKey:e,defineValue:n}})}return t}function qt(e){return Object.keys(e).length>0?{transform:{define:e}}:void 0}const Jt=[Xe,Ze,et,{name:`exact-version`,match:e=>Ie(e.specifier),resolve(e){return e.logger?.verbose(`Using exact ${e.packageName}@${e.specifier}`),{packageVersion:Ve(e.specifier),manifestVersion:e.specifier}}}];var Yt=class e{resolvers;pluginNames=/* @__PURE__ */ new Map;constructor(e,t=[]){this.resolvers=e;for(let e of t)for(let t of e.install?.dependencyResolvers??[])this.pluginNames.set(t,e.name)}static fromConfig(t,n=[]){return new e([...t,...Jt],n)}resolverMatchesCatalog(e,t){let n=e.entry.resolver;if(!n)return!0;let r=typeof n==`string`?n:n.name;return t.resolver===void 0||t.resolver===r}find(e){let t;for(let n of this.resolvers)if(this.resolverMatchesCatalog(e,n))try{if(n.match(e)){t=n;break}}catch(e){let t=this.pluginNames.get(n);throw t?new L(`PLUGIN_FAILED`,`Plugin ${t} resolver ${n.name} match failed: ${e instanceof Error?e.message:String(e)}`):e}if(!t)throw new L(`DEPENDENCY_VERSION_INVALID`,`${e.packageName} dependency version is invalid: ${e.specifier}`,{details:{package:e.packageName,specifier:e.specifier,resolver:e.entry.resolver}});return e.logger?.verbose(`Resolving ${e.packageName}@${e.specifier} with ${t.name}`),t}async resolve(e){let t=this.find(e);try{return await t.resolve(e)}catch(e){let n=this.pluginNames.get(t);throw n?new L(`PLUGIN_FAILED`,`Plugin ${n} resolver ${t.name} failed: ${e instanceof Error?e.message:String(e)}`):e}}};const Xt=`sapi-pro`,Zt=[`@minecraft/server`,`@minecraft/server-ui`];function Qt(e){return/(?:beta|preview|alpha|rc)/i.test(e)}function $t(e){return Qt(e)?`beta`:`stable`}function en(e){let t=/^(\d+)\.(\d+)\./.exec(e);return!!t&&(Number(t[1])>0||Number(t[2])>=4)}function tn(e){return{...e.dependencies??{},...e.peerDependencies??{}}}async function nn(e,t,n,r){let i=e.config.packs.bp?.dependencies??{},a={...rt,...e.config.install.dependencyCatalog},o=Yt.fromConfig(e.config.install.dependencyResolvers.filter(e=>e!==an),e.config.plugins);for(let[s,c]of Object.entries(t)){if(!s.startsWith(`@minecraft/`))continue;let t=i[s],l=a[s];if(!t||!l)return r.add(s),!1;let u;if(n.has(s)?u=n.get(s):(u=await o.resolve({packageName:s,specifier:t,target:e.target,entry:l,config:e.config,npm:e.npm,...e.logger?{logger:e.logger}:{}}),n.set(s,u)),!u||Zt.includes(s)&&Qt(c)!==Qt(u.packageVersion)||!Be(u.packageVersion,c))return!1}return!0}function rn(e,t){if(t!==`stable`&&t!==`beta`){let n=e[t];return n?[[t,n]]:[]}return Object.entries(e).filter(([e,n])=>{if(!en(e))return!1;let r=tn(n);return Object.keys(r).length===0?!1:t===`stable`?/-stable(?:\.\d+)?$/i.test(e):/^\d+\.\d+\.\d+$/.test(e)}).sort(([e],[t])=>z(e,t)).reverse()}const an={name:`sapi-pro`,resolver:`sapi-pro`,match:e=>e.specifier===`stable`||e.specifier===`beta`||/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(e.specifier),async resolve(e){let t=await e.npm.metadata(Xt),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set;for(let[i,a]of rn(t.versions??{},e.specifier))if(await nn(e,tn(a),n,r))return/^0\.3\./.test(i)&&e.logger?.warn(`sapi-pro@${i} uses legacy metadata; compatibility is best-effort only.`),{packageVersion:i,manifestVersion:null};throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot find a compatible ${Xt}@${e.specifier} for target ${e.target}.${r.size>0?` Missing explicit dependencies: ${[...r].join(`, `)}.`:``}`,{details:{package:Xt,specifier:e.specifier,target:e.target},suggestions:[`Explicitly declare the @minecraft packages required by sapi-pro.`,`Use a compatible target or specify an exact sapi-pro version.`]})}};function on(){return{name:`sapi-pro`,apiVersion:1,description:`Resolve sapi-pro versions compatible with BePack Script API dependencies.`,configResolved:({config:e})=>{let t=e.packs.bp?.dependencies??{},n=t[Xt];if(!n)return;let r=Zt.filter(e=>!t[e]);if(r.length>0)throw Error(`sapi-pro requires explicit dependencies: ${r.join(`, `)}.`);if(n===`stable`||n===`beta`)for(let e of Zt){let r=t[e];if($t(r)!==n)throw Error(`sapi-pro ${n} requires ${e} to use ${n}, received ${r}.`)}},install:{dependencyCatalog:{[Xt]:{resolver:`sapi-pro`,manifest:!1}},dependencyResolvers:[an]}}}const sn={"sapi-pro":on};function G(e){return e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):{}}function cn(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e==`function`?`function`:typeof e==`object`?`object`:typeof e==`string`?JSON.stringify(e):String(e)}function ln(e,t){let n={};(e.packs?.bp||t.packs?.bp)&&(n.bp={...e.packs?.bp??{},...G(t.packs?.bp)}),(e.packs?.rp||t.packs?.rp)&&(n.rp={...e.packs?.rp??{},...G(t.packs?.rp)});let r={...e.copy?.targets??{},...G(t.copy?.targets)},i=G(t);return{...e,...i,...t.plugins!==void 0||e.plugins!==void 0?{plugins:t.plugins??e.plugins}:{},packs:n,install:{...e.install,...G(t.install)},build:{...e.build,...G(t.build)},dev:{...e.dev,...G(t.dev)},copy:{...e.copy,...G(t.copy),targets:r},pack:{...e.pack,...G(t.pack)},hooks:{...e.hooks,...G(t.hooks)}}}function un(e){let t=(e??[]).map(e=>{if(typeof e!=`string`)return e;let t=sn[e];if(!t)throw new L(`CONFIG_INVALID`,`Unknown built-in plugin: ${e}.`);return t()}),n=/* @__PURE__ */ new Set;for(let e of t){if(!e?.name||e.name.trim()===``)throw new L(`CONFIG_INVALID`,`Every plugin must have a non-empty name.`);if(n.has(e.name))throw new L(`CONFIG_INVALID`,`Plugin name is duplicated: ${e.name}.`);if(e.apiVersion!==void 0&&e.apiVersion!==1)throw new L(`CONFIG_INVALID`,`Plugin ${e.name} requires unsupported BePack plugin API version ${e.apiVersion}.`);if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new L(`CONFIG_INVALID`,`Plugin ${e.name} priority must be a finite number.`);n.add(e.name)}return t.sort((e,t)=>(t.priority??0)-(e.priority??0))}function dn(e,t){let n=/* @__PURE__ */ new Set;for(let r of[...e.map(e=>e.hooks),t])for(let e of Object.keys(r??{}))n.add(e);return Object.fromEntries([...n].map(n=>{let r=[...e.map(e=>({plugin:e,hook:e.hooks?.[n]})).filter(e=>e.hook!==void 0),...t?.[n]?[{hook:t[n]}]:[]];return[n,async(...e)=>{let t;for(let i of r)try{t=await i.hook(...e)}catch(e){let t=`plugin`in i?i.plugin:void 0;throw t?new L(`PLUGIN_FAILED`,`Plugin ${t.name} ${String(n)} hook failed: ${e instanceof Error?e.message:String(e)}`):e}return t}]}))}function fn(e,t){let n={},r=/* @__PURE__ */ new Map,i=[];for(let t of e)for(let[e,a]of Object.entries(t.install?.dependencyCatalog??{})){let o=r.get(e);if(o){i.push(`dependency catalog ${e}: plugin ${o} takes precedence over plugin ${t.name}`);continue}n[e]=a,r.set(e,t.name)}for(let[e,a]of Object.entries(t)){let t=r.get(e);t&&i.push(`dependency catalog ${e}: project config overrides plugin ${t}`),n[e]=a}return{catalog:n,diagnostics:i}}function pn(e,t,n){let r=St,i=e?.scriptOutputDir??r.scriptOutputDir,a=o.resolve(n,e?.entry??r.entry),s=Pt(t,i,o.dirname(a));return{entry:e?.entry??r.entry,define:Kt(e?.define),tsconfig:e?.tsconfig??r.tsconfig,typecheck:e?.typecheck??r.typecheck,preserveModules:e?.preserveModules??r.preserveModules,external:e?.external??r.external,useNpx:e?.useNpx??r.useNpx,minify:e?.minify??r.minify,cache:u(e?.cache),scriptOutputDir:s,...e?.rolldown===void 0?{}:{rolldown:c(e.rolldown)},...e?.rolldownConfig===void 0?{}:{rolldownConfig:l(e.rolldownConfig)}};function c(e){if(typeof e==`function`||e&&typeof e==`object`&&!Array.isArray(e))return e;throw new L(`CONFIG_INVALID`,`packs.bp.compile.rolldown must be a rolldown options object or a function (options, context) => options, got: ${cn(e)}.`)}function l(e){if(typeof e!=`string`||e.trim()===``)throw new L(`CONFIG_INVALID`,`packs.bp.compile.rolldownConfig must be a non-empty path string, got: ${cn(e)}.`);return e}function u(e){let t=bt;return{dev:e?.dev??t.dev,build:e?.build??t.build,file:e?.file??t.file}}}function mn(e){if(e===void 0||e===!1)return;let t=e===!0?{}:e;if(typeof t!=`object`||!t||Array.isArray(t))throw new L(`CONFIG_INVALID`,`pack.optimize must be a boolean or an options object, got: ${cn(e)}.`);let n=t.packOptimizationVersion;if(n!==void 0&&(typeof n!=`string`||n.trim()===``))throw new L(`CONFIG_INVALID`,`pack.optimize.packOptimizationVersion must be a non-empty string, got: ${cn(n)}.`);return{keepLooseFiles:t.keepLooseFiles??xt.keepLooseFiles,keepLoose:t.keepLoose!==!1&&(t.keepLoose??[]).map(hn),exclude:(t.exclude??[]).map(hn),minifyJson:t.minifyJson??xt.minifyJson,packOptimizationVersion:n??xt.packOptimizationVersion,allowUnsupportedTarget:t.allowUnsupportedTarget??xt.allowUnsupportedTarget}}function hn(e){let t=String(e).replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``);if(!t||t.includes(`/`)||t.includes(`..`)||o.posix.isAbsolute(t))throw new L(`CONFIG_INVALID`,`pack.optimize.exclude entries must be top-level folder names (no path separators, no ".."), got: ${cn(e)}.`);return t}function gn(e){let t=e?.merge??`preserve`;if(t!==`preserve`&&t!==`clean`)throw new L(`CONFIG_INVALID`,`manifest.merge must be "preserve" or "clean", got: ${String(e?.merge)}.`);let n=e?.minEngineVersion;if(n!==void 0&&!/^\d+\.\d+\.\d+$/.test(n))throw new L(`CONFIG_INVALID`,`manifest.minEngineVersion must be a SemVer string like "1.21.0", got: ${n}.`);return{merge:t,...n===void 0?{}:{minEngineVersion:n},extraDependencies:e?.extraDependencies??[],extraModules:e?.extraModules??[],extraHeader:e?.extraHeader??{}}}function _n(e,t={},n=process.cwd()){let r=ln(e,t),i=un(r.plugins),a=r.target??B.target;if(a===`stable`||a===`beta`)throw new L(`TARGET_INVALID`,`target must be a Minecraft game version or latest, not a Script API channel.`,{details:{target:a}});let s=!!r.packs?.bp,c=!!r.packs?.rp;if(!s&&!c)throw new L(`CONFIG_INVALID`,`At least one pack (packs.bp or packs.rp) is required.`);if(!r.name||r.name.trim()===``)throw new L(`CONFIG_INVALID`,`name is required.`);let l=r.name,u=r.version??B.version,d=r.description,f=r.packs,p=f.bp?.compile,m=f.bp,h=f.rp;if(m){if(!m.uuid)throw new L(`CONFIG_INVALID`,`packs.bp.uuid is required.`);if(m.compile&&!m.moduleUuid)throw new L(`CONFIG_INVALID`,`packs.bp.moduleUuid is required when packs.bp.compile is configured.`);if(m.root===void 0)throw new L(`CONFIG_INVALID`,`packs.bp.root is required. Set the behavior pack directory in bepack.config.ts.`);if(p?.define){let e=Object.keys(r.replace?.values??{}),t=Object.keys(p.define),n=e.filter(e=>t.includes(e));if(n.length>0)throw new L(`CONFIG_INVALID`,`Config conflict: ${n.map(e=>`"${e}"`).join(`, `)} is configured in both replace.values and packs.bp.compile.define. Use only one mechanism per key.`,{details:{overlap:n}})}}let g=o.resolve(n,r.root??`.`),_=m?o.resolve(g,m.root):void 0;if(h){if(!h.uuid||!h.moduleUuid)throw new L(`CONFIG_INVALID`,`packs.rp.uuid and packs.rp.moduleUuid are required.`);if(h.root===void 0)throw new L(`CONFIG_INVALID`,`packs.rp.root is required when packs.rp is configured.`);if(h.packScope!==void 0&&!Ct.includes(h.packScope))throw new L(`CONFIG_INVALID`,`packs.rp.packScope must be one of ${Ct.map(e=>`"${e}"`).join(`, `)}.`,{details:{packScope:h.packScope}})}let v=m?.description??d,y=h?.description??d,{catalog:b,diagnostics:x}=fn(i,r.install?.dependencyCatalog??{}),S=i.flatMap(e=>e.install?.dependencyResolvers??[]),C=mn(r.pack?.optimize),w=mn(r.copy?.optimize);return{root:r.root??B.root,configured:{root:r.root!==void 0,packOutDir:r.pack?.outDir!==void 0},name:l,version:u,...d===void 0?{}:{description:d},replace:Gt(r.replace),target:a,plugins:i,...x.length>0?{pluginDiagnostics:x}:{},...r.manifestFormat===void 0?{}:{manifestFormat:r.manifestFormat},packs:{...m?{bp:{root:m.root,uuid:m.uuid,...m.moduleUuid===void 0?{}:{moduleUuid:m.moduleUuid},name:m.name??l,...v===void 0?{}:{description:v},...p&&_?{compile:pn(p,_,g)}:{},manifest:gn(m.manifest),dependencies:m.dependencies??{},include:m.include??[]}}:{},...h?{rp:{root:h.root,uuid:h.uuid,moduleUuid:h.moduleUuid,name:h.name??l,...y===void 0?{}:{description:y},manifest:gn(h.manifest),...h.pbr===void 0?{}:{pbr:h.pbr},...h.packScope===void 0?{}:{packScope:h.packScope},include:h.include??[]}}:{}},install:{registry:r.install?.registry??B.install.registry,saveTo:r.install?.saveTo??B.install.saveTo,packageManager:r.install?.packageManager??B.install.packageManager,runPackageManager:r.install?.runPackageManager??B.install.runPackageManager,updatePackageJson:r.install?.updatePackageJson??B.install.updatePackageJson,updateManifest:r.install?.updateManifest??B.install.updateManifest,dependencyCatalog:b,dependencyResolvers:[...S,...r.install?.dependencyResolvers??[]]},build:{copy:r.build?.copy??B.build.copy,timing:r.build?.timing??B.build.timing},dev:{copy:r.dev?.copy??B.dev.copy,...r.dev?.watch?{watch:r.dev.watch}:{}},copy:{defaultTarget:r.copy?.defaultTarget??B.copy.defaultTarget,...r.copy?.name?{name:r.copy.name}:{},...r.copy?.include?{include:r.copy.include}:{},targets:r.copy?.targets??{},...w?{optimize:w}:{}},pack:{name:r.pack?.name??B.pack.name,outDir:r.pack?.outDir??B.pack.outDir,...C?{optimize:C}:{}},hooks:dn(i,r.hooks)}}async function vn(e,n){if(n){let r=Dt(e,n);return await t.access(r).catch(()=>{throw new L(`CONFIG_NOT_FOUND`,`Config not found: ${n}`,{details:{configPath:n}})}),r}for(let n of yt){let r=o.join(e,n);try{return await t.access(r),r}catch{}}throw new L(`CONFIG_NOT_FOUND`,`No bepack.config.ts, bepack.config.mjs, or bepack.config.js found.`,{details:{cwd:e}})}async function yn(e){try{if(e.endsWith(`.ts`))try{return await import(`${a(e).href}?t=${Date.now()}`)}catch{let n=bn(await t.readFile(e,`utf8`));return await import(`data:text/javascript;base64,${Buffer.from(n,`utf8`).toString(`base64`)}`)}return await import(`${a(e).href}?t=${Date.now()}`)}catch(t){throw new L(`CONFIG_INVALID`,`Failed to load config: ${t instanceof Error?t.message:String(t)}`,{details:{file:e},suggestions:[`Use bepack.config.mjs/js for complex config logic.`,`Keep bepack.config.ts free of TypeScript-only runtime syntax.`]})}}function bn(e){return e.replace(/^\s*import\s+type\s+[^;]+;\s*$/gm,``).replace(/\s+satisfies\s+[A-Za-z_$][\w$<>,\s.[\]|&{}]*/g,``).replace(/\((\s*[A-Za-z_$][\w$]*)\s*:\s*[^)=]+?\)\s*=>/g,`($1) =>`)}async function xn(e,t){for(let n of e.plugins??[])if(n.configResolved)try{await n.configResolved({cwd:t,config:e})}catch(e){throw new L(`PLUGIN_FAILED`,`Plugin ${n.name} configResolved hook failed: ${e instanceof Error?e.message:String(e)}`)}}async function Sn(e){let t=o.resolve(e.cwd),n=await vn(t,e.configPath),r=await yn(n);if(r.default===void 0)throw new L(`CONFIG_INVALID`,`Config must use default export.`,{details:{file:n}});let i=_n(r.default,e.overrides,t);return await xn(i,t),{config:i,path:n,cwd:t}}function Cn(e){return{...rt,...e.install.dependencyCatalog}}function wn(e,t){let n=e[t];if(!n)throw new L(`UNSUPPORTED_DEPENDENCY`,`${t} is not a managed dependency. Add it to install.dependencyCatalog or remove it from packs.bp.dependencies.`,{details:{package:t}});return n}function Tn(e,t){e?.install?e.install(t):e?.info(`[Install] ${t}`)}var En=class{registry;logger;cache=/* @__PURE__ */ new Map;constructor(e,t){this.registry=e,this.logger=t}async metadata(e){let t=this.packageUrl(e),n=this.cache.get(t);if(n)return this.logger?.verbose(`Using cached metadata for ${e}`),n;Tn(this.logger,`fetching ${e} metadata from ${this.registry}`);let r=await fetch(t);if(!r.ok)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot fetch ${e} versions from registry.`,{details:{package:e,registry:this.registry,status:r.status}});let i=await r.json();return this.cache.set(t,i),this.logger?.verbose(`Fetched ${e} metadata (${Object.keys(i.versions??{}).length} versions)`),i}versions(e){return Object.keys(e.versions??{})}async versionsOf(e){return this.versions(await this.metadata(e))}distTag(e,t){let n=e[`dist-tags`]?.[t];return n&&e.versions?.[n]?n:void 0}packageUrl(e){return`${this.registry.replace(/\/$/,``)}/${encodeURIComponent(e).replace(/^%40/,`@`)}`}};function Dn(e){return t=>{e?.install?e.install(t):e?.info(`[Install] ${t}`)}}var On=class{config;logger;npm;catalog;pkgResolver;log;constructor(e,t){this.config=e,this.logger=t,this.npm=new En(e.install.registry,t),this.catalog=Cn(e),this.pkgResolver=new We(this.npm,t),this.log=Dn(t)}async resolveAll(){let e={},t=this.config.packs.bp?.dependencies;if(!t||Object.keys(t).length===0)return this.log(`no BP dependencies to resolve`),e;this.log(`resolving dependencies for target ${this.config.target}`);for(let[n,r]of Object.entries(t)){let t=wn(this.catalog,n),i=await this.resolveOne(n,r,t),a=t.manifest??!1;e[n]={specifier:r,packageVersion:i.packageVersion,manifestVersion:a?i.manifestVersion??i.packageVersion:null,manifest:a,external:a,resolver:typeof t.resolver==`string`?t.resolver:t.resolver.name},this.log(`${n}: ${r} -> package ${e[n].packageVersion}, manifest ${e[n].manifestVersion}`)}return this.logger?.verbose(`Dependency resolution complete`),e}async resolveOne(e,t,n){let r={packageName:e,specifier:t,target:this.config.target,entry:n,config:this.config};await this.runDependencyHooks(`beforeResolveDependency`,r);let i=await Yt.fromConfig(this.config.install.dependencyResolvers,this.config.plugins??[]).resolve({packageName:e,specifier:t,target:this.config.target,entry:n,config:this.config,npm:this.npm,...this.logger?{logger:this.logger}:{}});return await this.runDependencyHooks(`afterResolveDependency`,{...r,result:i}),i}async runDependencyHooks(e,t){for(let n of this.config.plugins??[]){let r=n.install?.hooks?.[e];if(r)try{await r(t)}catch(t){throw new L(`PLUGIN_FAILED`,`Plugin ${n.name} ${e} hook failed: ${t instanceof Error?t.message:String(t)}`)}}}};async function kn(e,t,n,r=!1){let i=o.join(e,`package.json`);if(!await I(i))throw new L(`PACKAGE_JSON_NOT_FOUND`,`package.json not found.`,{details:{cwd:e}});let a=await xe(i),s=t.install.saveTo;a.dependencies=a.dependencies??{},a.devDependencies=a.devDependencies??{};for(let e of Object.keys(n))delete a.dependencies[e],delete a.devDependencies[e];a[s]=a[s]??{};for(let[e,t]of Object.entries(n))a[s][e]=t.packageVersion;return Object.keys(a.dependencies).length||delete a.dependencies,Object.keys(a.devDependencies).length||delete a.devDependencies,r||await Se(i,a),{updated:!0,path:`package.json`}}const An=[1,21,0],jn=[1,0,0];var Mn=class{config;version;versionStr;depManager;constructor(e,t){this.config=e,this.version=Fe(e.version),this.versionStr=e.version,this.depManager=t}buildBp(e){let t=this.requireBp(),n=Me(e);this.depManager.validateBpDependencies();let r=this.getWriteFormatVersion(n);return t.manifest.merge===`clean`?this.buildCleanBp(t,r):this.buildPreserveBp(n,t,r)}buildRp(e){let t=this.requireRp(),n=Me(e),r=this.getWriteFormatVersion(n),i=t.manifest.merge===`clean`?this.buildCleanRp(t,r):this.buildPreserveRp(n,t,r);return this.applyPbrCapability(i,t),i}buildPreserveBp(e,t,n){return{...e,format_version:n,header:this.buildBpHeader(e,t,n),...t.moduleUuid?{modules:this.replaceManagedBpModules(e.modules,t,n)}:e.modules?{modules:e.modules}:{},dependencies:this.depManager.replaceBpDependencies(e.dependencies,this.config.packs.rp?.uuid,n)}}buildPreserveRp(e,t,n){return{...e,format_version:n,header:this.buildRpHeader(e,t,n),modules:this.replaceManagedRpModules(e.modules,t,n),dependencies:this.depManager.replaceRpDependencies(e.dependencies,this.config.packs.bp?.uuid,n)}}buildCleanBp(e,t){return{format_version:t,header:this.buildBpHeaderClean(e,t),...e.moduleUuid?{modules:this.buildCleanBpModules(e,t)}:{},dependencies:this.depManager.buildBpDependenciesClean(t,this.config.packs.rp?.uuid,e.manifest.extraDependencies)}}buildCleanRp(e,t){return{format_version:t,header:this.buildRpHeaderClean(e,t),modules:this.buildCleanRpModules(e,t),dependencies:this.depManager.buildRpDependenciesClean(t,this.config.packs.bp?.uuid,e.manifest.extraDependencies)}}buildBpHeaderClean(e,t){return{...e.manifest.extraHeader,name:e.name,...e.description===void 0?{}:{description:e.description},uuid:e.uuid,version:this.getVersionFor(t),min_engine_version:e.manifest.minEngineVersion===void 0?this.defaultMinEngineVersion(t):this.configMinEngineVersion(e.manifest.minEngineVersion,t)}}buildRpHeaderClean(e,t){return{...e.manifest.extraHeader,name:e.name,...e.description===void 0?{}:{description:e.description},uuid:e.uuid,...e.packScope===void 0?{}:{pack_scope:e.packScope},version:this.getVersionFor(t),min_engine_version:e.manifest.minEngineVersion===void 0?this.defaultMinEngineVersion(t):this.configMinEngineVersion(e.manifest.minEngineVersion,t)}}buildCleanBpModules(e,t){return[...e.moduleUuid?[this.createScriptModule(e,t)]:[],...e.manifest.extraModules]}buildCleanRpModules(e,t){return[this.createResourcesModule(e,t),...e.manifest.extraModules]}buildBpHeader(e,t,n){return{...e.header??{},name:t.name,...t.description===void 0?{}:{description:t.description},uuid:t.uuid,version:this.getVersionFor(n),min_engine_version:this.normalizeMinEngineVersion(e.header?.min_engine_version,n,t.manifest.minEngineVersion)}}buildRpHeader(e,t,n){return{...e.header??{},name:t.name,...t.description===void 0?{}:{description:t.description},uuid:t.uuid,...t.packScope===void 0?{}:{pack_scope:t.packScope},version:this.getVersionFor(n),min_engine_version:this.normalizeMinEngineVersion(e.header?.min_engine_version,n,t.manifest.minEngineVersion)}}getScriptEntry(){let e=this.config.packs.bp?.compile;return e?`${e.scriptOutputDir}/${o.basename(e.entry,o.extname(e.entry))}.js`:`scripts/main.js`}isManagedBpModule(e,t){if(e.type!==`script`||e.language!==`javascript`)return!1;let n=this.getScriptEntry();return e.uuid===t.moduleUuid||e.entry===n}isManagedRpModule(e,t){return e.type===`resources`&&e.uuid===t.moduleUuid}createScriptModule(e,t){return{type:`script`,language:`javascript`,uuid:e.moduleUuid,version:this.getModuleVersion(t),entry:this.getScriptEntry()}}createResourcesModule(e,t){return{type:`resources`,uuid:e.moduleUuid,version:this.getModuleVersion(t)}}replaceManagedBpModules(e,t,n){return[...Ne(e).filter(e=>!this.isManagedBpModule(e,t)),this.createScriptModule(t,n)]}replaceManagedRpModules(e,t,n){return[...Ne(e).filter(e=>!this.isManagedRpModule(e,t)),this.createResourcesModule(t,n)]}applyPbrCapability(e,t){if(t.pbr===!0){let t=Ne(e.capabilities);e.capabilities=t.includes(`pbr`)?t:[...t,`pbr`]}else if(t.pbr===!1){let t=Ne(e.capabilities).filter(e=>e!==`pbr`);t.length>0?e.capabilities=t:delete e.capabilities}}getVersionFor(e){return e===3?this.versionStr:this.version}getModuleVersion(e){return e===3?`1.0.0`:jn}getWriteFormatVersion(e){return this.config.manifestFormat===void 0?e.format_version??2:this.config.manifestFormat}normalizeMinEngineVersion(e,t,n){if(n!==void 0)return this.configMinEngineVersion(n,t);if(e==null)return this.defaultMinEngineVersion(t);if(Array.isArray(e))return t===3?e.join(`.`):e;if(typeof e==`string`){if(t===2){let t=this.stringToVersionTuple(e);if(t)return t}return e}return this.defaultMinEngineVersion(t)}configMinEngineVersion(e,t){return t===3?e:this.stringToVersionTuple(e)??this.defaultMinEngineVersion(t)}defaultMinEngineVersion(e){return e===3?`1.21.0`:An}stringToVersionTuple(e){let t=e.split(`.`).map(Number);if(t.length===3&&t.every(e=>!Number.isNaN(e)))return t}requireBp(){if(!this.config.packs.bp)throw new L(`CONFIG_INVALID`,`packs.bp is required to build the BP manifest.`);return this.config.packs.bp}requireRp(){if(!this.config.packs.rp)throw new L(`CONFIG_INVALID`,`packs.rp is required to build the RP manifest.`);return this.config.packs.rp}},Nn=class e{config;catalog;installVersions;manifestVersions;version;versionStr;dependencyDiagnostics=[];constructor(e,t,n={}){this.config=e,this.catalog=t,this.installVersions=n.install??{},this.manifestVersions=n.manifest??{},this.version=Fe(e.version),this.versionStr=e.version}static isAllowedSpecifier(e){return e===`stable`||e===`beta`||e===`preview`||/^\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/.test(e)}static resolveVersion(t){return e.resolveVersionDetail(t).version}static resolveVersionDetail(e){let{specifier:t,target:n,resolvedVersion:r,manifestVersion:i}=e;if(t===`stable`){if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new L(`DEPENDENCY_REQUIRES_INSTALL`,"Run `bepack install` to resolve stable manifest dependencies.",{details:{specifier:t,target:n}})}if(t===`beta`){if(Le(n))return{version:`beta`,source:`config`};if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new L(`DEPENDENCY_REQUIRES_INSTALL`,`Run \`bepack install\` to resolve manifest dependencies for target ${n}.`,{details:{target:n}})}if(t===`preview`){if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new L(`DEPENDENCY_REQUIRES_INSTALL`,`Run \`bepack install\` to resolve preview manifest dependencies for target ${n}.`,{details:{specifier:t,target:n}})}return{version:t,source:`config`}}validateBpDependencies(){if(this.config.packs.bp)for(let[t,n]of Object.entries(this.config.packs.bp.dependencies)){if(!this.catalog[t]){let e=Object.keys(this.catalog),n=e.length>0?[`Managed packages: ${e.join(`, `)}.`,`Add a missing package to install.dependencyCatalog, or remove it from packs.bp.dependencies.`]:[`No managed packages are available. Extend install.dependencyCatalog to add one.`];throw new L(`UNSUPPORTED_DEPENDENCY`,`${t} is not a managed dependency.`,{details:{package:t},suggestions:n})}if(!e.isAllowedSpecifier(n))throw new L(`DEPENDENCY_VERSION_INVALID`,`${t} dependency version is invalid: ${n}`,{details:{package:t,specifier:n}})}}isManagedBpDependency(e){return!!(`module_name`in e&&typeof e.module_name==`string`&&this.catalog[e.module_name]?.manifest||`uuid`in e&&typeof e.uuid==`string`&&this.config.packs.rp?.uuid===e.uuid)}isManagedRpDependency(e,t){return t!==void 0&&`uuid`in e&&typeof e.uuid==`string`&&e.uuid===t}buildManagedDependencies(){if(this.dependencyDiagnostics.length=0,!this.config.packs.bp)return[];let t=[];for(let[n,r]of Object.entries(this.config.packs.bp.dependencies)){if(!this.catalog[n]?.manifest)continue;let i=e.resolveVersionDetail({specifier:r,target:this.config.target,resolvedVersion:this.installVersions[n],manifestVersion:this.manifestVersions[n]});t.push({module_name:n,version:i.version}),this.dependencyDiagnostics.push({name:n,specifier:r,version:i.version,source:i.source})}return t}getDependencyDiagnostics(){return this.dependencyDiagnostics}getFormatAwareVersion(e){return(e??this.config.manifestFormat??2)===3?this.versionStr:this.version}replaceBpDependencies(e,t,n){let r=Ne(e).filter(e=>!this.isManagedBpDependency(e)),i=this.buildManagedDependencies();return t&&i.push({uuid:t,version:this.getFormatAwareVersion(n)}),[...r,...i]}replaceRpDependencies(e,t,n){let r=Ne(e).filter(e=>!this.isManagedRpDependency(e,t));return t?[...r,{uuid:t,version:this.getFormatAwareVersion(n)}]:r}buildBpDependenciesClean(e,t,n){let r=this.buildManagedDependencies();return t&&r.push({uuid:t,version:this.getFormatAwareVersion(e)}),[...r,...n]}buildRpDependenciesClean(e,t,n){let r=[];return t&&r.push({uuid:t,version:this.getFormatAwareVersion(e)}),[...r,...n]}};const Pn=we.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);async function Fn(e){let t=Cn(e.config),n=e.config.packs.bp?Lt(e.cwd,e.config):void 0,r=n?await Pe.read(n):void 0,i=Ln(r,t),a=new Nn(e.config,t,{...e.resolvedDeps?{install:e.resolvedDeps}:{},manifest:i}),s=new Mn(e.config,a),c={};if(e.config.packs.bp){let t=r!==void 0;e.config.manifestFormat===2&&r?.format_version===3&&(e.logger?.warn??console.warn)(`Warning: config manifestFormat is 2, but existing manifest uses format_version 3. format_version 2 does not support string versions; any string versions in the existing manifest will be preserved as-is.`);let l=s.buildBp(r),u=a.getDependencyDiagnostics().map(e=>({module_name:e.name,specifier:e.specifier,version:e.version,source:e.source,...i[e.name]===void 0?{}:{previous:i[e.name]}}));e.dryRun||await Pe.write(n,l,`bp`),In(u,e.logger),c.bpManifest={path:V(o.relative(e.cwd,n)),updated:!0,existed:t,dependencies:u}}if(e.config.packs.rp){let t=Rt(e.cwd,e.config),n=await Pe.read(t),r=n!==void 0,i=s.buildRp(n);e.dryRun||await Pe.write(t,i,`rp`),c.rpManifest={path:V(o.relative(e.cwd,t)),updated:!0,existed:r}}return c}function In(e,t){if(t)for(let n of e){let e=Pn.cyan(n.module_name);n.previous!==void 0&&n.previous!==n.version?t.info(`manifest ${e}: ${n.previous} ${Pn.dim(`->`)} ${n.version} (specifier ${JSON.stringify(n.specifier)}, ${n.source})`):n.source===`manifest`?t.info(`manifest ${e} ${n.version} ${Pn.dim(`kept from manifest`)} (specifier ${JSON.stringify(n.specifier)}) — run \`bepack install\` to refresh`):t.verbose(`manifest ${e} ${n.version} (specifier ${JSON.stringify(n.specifier)}, ${n.source})`)}}function Ln(e,t){let n={};for(let r of e?.dependencies??[])`module_name`in r&&typeof r.module_name==`string`&&typeof r.version==`string`&&t[r.module_name]?.manifest&&r.version!==`stable`&&(n[r.module_name]=r.version);return n}function Rn(e){if(e==null||e===``)return`hook ran`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function zn(e,t){let n={dist:zt(e,t)};if(t.packs.bp&&(n.bpRoot=Ot(e,t),n.bpManifest=Lt(e,t),At(t))){let r=W(e,t);r&&(n.srcEntry=r);let i=Mt(e,t);i&&(n.scriptOutFile=i);let a=jt(e,t);a&&(n.scriptOutDir=a)}return t.packs.rp&&(n.rpRoot=kt(e,t),n.rpManifest=Rt(e,t)),n}async function K(e,t,n,r,i,a={}){let o=r.hooks[e];if(o)try{let s=await o({command:t,cwd:n,...a.mode===void 0?{}:{mode:a.mode},target:r.target,dryRun:!!a.dryRun,config:r,paths:zn(n,r),logger:i});i.hook(String(e),Rn(s))}catch(t){throw new L(`HOOK_FAILED`,`${String(e)} hook failed: ${t instanceof Error?t.message:String(t)}`)}}async function Bn(e){let{command:t,logger:n,mode:r,...i}=e,a={...r===void 0?{}:{mode:r},dryRun:!!i.dryRun};await K(`beforeManifest`,t,i.cwd,i.config,n,a);let o=await Fn({...i,logger:n});return await K(`afterManifest`,t,i.cwd,i.config,n,a),o}function Vn(e){let t=[],n={};for(let[r,i]of Object.entries(e)){if(r.toLowerCase()===`npm_config_allow_scripts`){t.push(r);continue}n[r]=i}return{env:n,removed:t}}var Hn=class{cwd;registry;logger;constructor(e,t,n){this.cwd=e,this.registry=t,this.logger=n}async detect(e){if(e!==`auto`)return e;let t=o.join(this.cwd,`package.json`);if(await I(t)){let e=(await xe(t)).packageManager?.split(`@`)[0];if(e===`npm`||e===`pnpm`||e===`yarn`||e===`bun`)return e}return await I(o.join(this.cwd,`pnpm-lock.yaml`))?`pnpm`:await I(o.join(this.cwd,`yarn.lock`))?`yarn`:await I(o.join(this.cwd,`bun.lock`))||await I(o.join(this.cwd,`bun.lockb`))?`bun`:`npm`}async install(e){let{command:t,args:n}=this.commandForPlatform(e,this.installArgs(e)),{env:r,removed:i}=Vn(process.env);return i.length>0&&this.logger?.warn(`Ignoring inherited ${i.join(`, `)}: npm rejects --allow-scripts for project-scoped installs. Declare allowed packages in package.json "allowScripts" or in .npmrc instead.`),await new Promise((i,a)=>{let o;try{o=m(t,n,{cwd:this.cwd,stdio:`inherit`,env:r})}catch(t){a(new L(`PACKAGE_MANAGER_NOT_FOUND`,`${e} is not available.`,{details:{manager:e,cause:t instanceof Error?t.message:String(t)}}));return}o.on(`error`,t=>a(new L(`PACKAGE_MANAGER_NOT_FOUND`,`${e} is not available.`,{details:{manager:e,cause:t.message}}))),o.on(`exit`,t=>{t&&t!==0?a(new L(`PACKAGE_MANAGER_FAILED`,`${e} install failed.`,{details:{manager:e,registry:this.registry,exitCode:t}})):i(t??0)})})}commandForPlatform(e,t){return process.platform===`win32`?{command:process.env.ComSpec??`cmd.exe`,args:[`/d`,`/s`,`/c`,e,...t]}:{command:e,args:t}}installArgs(e){let t=[`install`];return this.registry&&(e===`npm`||e===`pnpm`||e===`bun`||e===`yarn`)&&t.push(`--registry`,this.registry),t}};async function Un(e){let t=new Te({...e,silent:e.silent||e.json}),n={target:e.target};(e.registry||e.pm||e.saveTo||e.skipPm||e.skipManifest||e.skipPackageJson)&&(n.install={...e.registry?{registry:e.registry}:{},...e.pm?{packageManager:e.pm}:{},...e.saveTo?{saveTo:e.saveTo}:{},...e.skipPm?{runPackageManager:!1}:{},...e.skipManifest?{updateManifest:!1}:{},...e.skipPackageJson?{updatePackageJson:!1}:{}});let{cwd:r,config:i}=await Sn({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:n});await K(`beforeInstall`,`install`,r,i,t,{dryRun:!!e.dryRun});let a=await new On(i,t).resolveAll(),o=Object.fromEntries(Object.entries(a).filter(([,e])=>e.manifestVersion!==null).map(([e,t])=>[e,t.manifestVersion])),s={};i.install.updatePackageJson&&(s.packageJson=await kn(r,i,a,e.dryRun)),i.install.updateManifest&&Object.assign(s,await Bn({cwd:r,config:i,command:`install`,dryRun:e.dryRun,logger:t,resolvedDeps:o}));let c=new Hn(r,i.install.registry,t),l=await c.detect(i.install.packageManager),u={ran:!1,manager:l,exitCode:null};return!e.dryRun&&i.install.runPackageManager&&(t.progress(`Install`,`running ${l} install with registry ${i.install.registry}`),u={ran:!0,manager:l,exitCode:await c.install(l)}),await K(`afterInstall`,`install`,r,i,t,{dryRun:!!e.dryRun}),t.success(`Install`,`done`),{ok:!0,command:`install`,target:i.target,packageManager:l,resolved:a,files:s,packageInstall:u}}async function Wn(e){let t=new Te({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await Sn({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{target:e.target}}),i=await Bn({cwd:n,config:r,command:`manifest`,dryRun:e.dryRun,logger:t});return t.success(`Manifest`,e.dryRun?`dry-run complete`:`updated manifest.json`),{ok:!0,command:`manifest`,target:r.target,files:i}}function Gn(e,t,n,r){let i=e?`npx tsc --noEmit`:`tsc --noEmit`;return i+=` --project "${t}"`,n&&r&&(i+=` --incremental --tsBuildInfoFile "${r}"`),i}async function Kn(e,t={}){let n=t.tsconfigPath??`tsconfig.json`,r=o.resolve(e,n);if(!await I(r))throw new L(`TYPECHECK_FAILED`,`TypeScript config not found: ${n}. Create it or run build with --skip-typecheck.`,{details:{path:n}});t.incremental&&t.tsBuildInfoFile&&await g(o.dirname(t.tsBuildInfoFile),{recursive:!0});let i=Gn(!!t.useNpx,r,!!t.incremental,t.tsBuildInfoFile);await new Promise((n,r)=>{let a=``,o=``,s;try{s=p(i,{cwd:e,windowsHide:!0,maxBuffer:10485760},e=>{if(!e){n();return}let s=[a.trim(),o.trim()].filter(Boolean).join(`
10
- `),c=s.includes(`not recognized`)||s.includes(`not found`)||s.includes(`ENOENT`)||s.includes(`不是内部或外部命令`),l=c?t.useNpx?[`Install npm/npx or set packs.bp.compile.entry to skip typecheck.`]:["Install TypeScript globally so `tsc` is available.",`Set packs.bp.compile.useNpx: true to use the project local TypeScript.`]:void 0;r(new L(`TYPECHECK_FAILED`,c?`Cannot find ${t.useNpx?`npx`:`tsc`}.`:`${i} failed.`,{details:{command:i,exitCode:typeof e.code==`number`?e.code:null,...s?{diagnostics:s}:{}},...l?{suggestions:l}:{}}))})}catch(e){r(new L(`TYPECHECK_FAILED`,`Cannot start ${i}.`,{details:{command:i,cause:e instanceof Error?e.message:String(e)},suggestions:t.useNpx?[`Install npm/npx or set build.useNpx to false.`]:["Install TypeScript globally so `tsc` is available.",`Set build.useNpx: true to use the project local TypeScript.`]}));return}s.on(`error`,e=>{r(new L(`TYPECHECK_FAILED`,`Cannot start ${i}.`,{details:{command:i,cause:e.message},suggestions:t.useNpx?[`Install npm/npx or set build.useNpx to false.`]:["Install TypeScript globally so `tsc` is available.",`Set build.useNpx: true to use the project local TypeScript.`]}))}),s.stdout?.on(`data`,e=>{a+=String(e),t.quiet||process.stdout.write(e)}),s.stderr?.on(`data`,e=>{o+=String(e),t.quiet||process.stderr.write(e)})})}const qn=/* @__PURE__ */ new Set([`plugins`]),Jn=/* @__PURE__ */ new Set([`external`]),Yn=/* @__PURE__ */ new Set([`output`,`resolve`,`transform`,`experimental`,`checks`,`optimization`,`watch`,`moduleTypes`]),Xn=[{key:`file`,suggestion:`The output file is derived from packs.bp.compile.entry and scriptOutputDir.`},{key:`dir`,suggestion:`The output directory is derived from packs.bp.compile.scriptOutputDir.`},{key:`format`,suggestion:`Minecraft Script API modules must be ESM, so BePack always writes format: "esm".`},{key:`preserveModules`,suggestion:`Use packs.bp.compile.preserveModules instead.`},{key:`preserveModulesRoot`,suggestion:`The modules root is always the entry file directory.`},{key:`entryFileNames`,suggestion:"Manifest script entries assume one `.js` file per source module."}];function q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zn(e){return e==null||e===!1?[]:Array.isArray(e)?e:[e]}function Qn(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function $n(e,t,n){return typeof e!=`string`||typeof t!=`string`?!1:Qn(o.resolve(n,e),o.resolve(n,t))}function er(e){if(e instanceof Error){let t=e.cause;return t instanceof Error&&t.message?t.message:e.message}return String(e)}function tr(e,t){if(typeof e==`function`||typeof t==`function`)return t;let n=[],r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set;for(let a of[...Zn(e),...Zn(t)])if(typeof a==`string`){if(r.has(a))continue;r.add(a),n.push(a)}else if(a instanceof RegExp){let e=`${a.source}/${a.flags}`;if(i.has(e))continue;i.add(e),n.push(a)}return n}function nr(e,t){if(!q(t))return t;let n=q(e)?e:{},r={...n,...t},i=q(n.define)?n.define:{};return q(t.define)&&(r.define={...i,...t.define}),r}function rr(e,t){if(!t)return{...e};let n={...e};for(let[e,r]of Object.entries(t)){if(r===void 0)continue;let t=n[e];n[e]=qn.has(e)?[...Zn(t),...Zn(r)]:Jn.has(e)?tr(t,r):e===`transform`?nr(t,r):Yn.has(e)&&q(t)&&q(r)?{...t,...r}:r}return n}function ir(e){if(!e.packs.bp?.compile)return[];let t=[...e.packs.bp.compile.external],n=new Set(t.filter(e=>typeof e==`string`));for(let[r,i]of Object.entries(Cn(e)))i.manifest&&!n.has(r)&&(t.push(r),n.add(r));return t}function ar(e){let t=e.packs.bp?.compile;if(!t)throw new L(`BUILD_FAILED`,`rolldown requires packs.bp.compile to be configured.`);return t}function or(e,t){let n=ar(t),r=W(e,t);if(!r)throw new L(`BUILD_FAILED`,`packs.bp.compile.entry could not be resolved.`);return{input:r,external:ir(t),plugins:Wt(t),...qt(n.define)??{},onwarn(e,t){e.code!==`CIRCULAR_DEPENDENCY`&&t(e)},experimental:{attachDebugInfo:n.preserveModules?`none`:`simple`}}}function sr(e,t){let n=ar(t),r=W(e,t),i=jt(e,t),a=Mt(e,t);if(!r||!i||!a)throw new L(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);return n.preserveModules?{dir:i,format:`esm`,preserveModules:!0,preserveModulesRoot:o.dirname(r),entryFileNames:`[name].js`,minify:n.minify}:{file:a,format:`esm`,minify:n.minify}}function cr(e,t){if(typeof e==`string`)return[o.resolve(t,e)];if(Array.isArray(e))return e.every(e=>typeof e==`string`)?e.map(e=>o.resolve(t,e)).sort():void 0;if(q(e)){let n=Object.values(e);return n.every(e=>typeof e==`string`)?n.map(e=>o.resolve(t,e)).sort():void 0}}function lr(e,t,n){if(e.input===void 0)return;let r=cr(e.input,n),i=cr(t.input,n);if(!(r!==void 0&&i!==void 0&&r.length===i.length&&r.every((e,t)=>Qn(e,i[t]))))throw new L(`CONFIG_INVALID`,`packs.bp.compile.rolldown cannot override "input" — the bundle entry is managed by BePack.`,{details:{input:e.input,expected:t.input},suggestions:[`Set the entry file via packs.bp.compile.entry instead.`]})}function ur(e,t,n){for(let{key:r,suggestion:i}of Xn){let a=e[r];if(a===void 0)continue;let o=t[r];if(!(r===`file`||r===`dir`||r===`preserveModulesRoot`?$n(a,o,n):Object.is(a,o)||r===`preserveModules`&&o===void 0&&a===!1))throw new L(`CONFIG_INVALID`,`packs.bp.compile.rolldown cannot override "output.${r}" — it is managed by BePack.`,{details:{key:r,value:a,expected:o},suggestions:[i]})}}function dr(e,t){if(q(e)&&e.__esModule===!0&&`default`in e)return dr(e.default,t);if(typeof e==`function`)return e;if(Array.isArray(e)){if(e.length===0)throw new L(`CONFIG_INVALID`,`rolldown config file exports an empty array: ${t}`,{details:{file:t},suggestions:[`Export a single rolldown options object.`]});if(e.length>1)throw new L(`CONFIG_INVALID`,`rolldown config file exports ${e.length} configs, but BePack builds a single behavior pack per run: ${t}`,{details:{file:t,count:e.length},suggestions:[`Export a single rolldown options object.`]});if(!q(e[0]))throw new L(`CONFIG_INVALID`,`rolldown config file must export an options object or function: ${t}`);return e[0]}if(q(e))return e;throw new L(`CONFIG_INVALID`,`rolldown config file must default-export a rolldown options object, a function, or a single-element array: ${t}`)}async function fr(e){if(!await I(e))throw new L(`CONFIG_INVALID`,`rolldown config file not found: ${e}`,{details:{path:e},suggestions:[`Check the path in packs.bp.compile.rolldownConfig or --rolldown-config.`]});let t;try{t=await v(e)}catch(t){throw new L(`CONFIG_INVALID`,`Failed to load rolldown config file "${e}": ${er(t)}`)}return dr(t,e)}async function pr(e,t,n){let r;try{r=await e(t,n)}catch(e){throw new L(`BUILD_FAILED`,`compile.rolldown customization function failed: ${er(e)}`)}if(r==null)return t;if(!q(r))throw new L(`CONFIG_INVALID`,`compile.rolldown customization function must return a rolldown options object (or nothing).`);return rr(t,r)}async function mr(e){let{cwd:t,config:n}=e,r=ar(n),i=H(t,n),a=W(t,n),s=jt(t,n),c=Mt(t,n);if(!a||!s||!c)throw new L(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);let l=or(t,n),u=sr(t,n),d={command:e.command??`build`,...e.mode===void 0?{}:{mode:e.mode},target:n.target,entry:a,outDir:s,outFile:c,preserveModules:r.preserveModules},f=r.rolldown,p=e.configPath??r.rolldownConfig,m=p?await fr(o.resolve(i,p)):void 0,h=rr(l,typeof f==`function`?void 0:f);h=rr(h,typeof m==`function`?void 0:m),typeof f==`function`&&(h=await pr(f,h,d)),typeof m==`function`&&(h=await pr(m,h,d));let{output:g,input:_,...v}=h;if(Array.isArray(g))throw new L(`CONFIG_INVALID`,"packs.bp.compile.rolldown cannot declare multiple outputs (an `output` array) — BePack writes exactly one output.",{suggestions:["Declare a single `output` object."]});if(g!==void 0&&!q(g))throw new L(`CONFIG_INVALID`,"packs.bp.compile.rolldown `output` must be an object.",{details:{output:g}});lr({input:_},l,i);let y=rr(u,g);return ur(y,u,i),{inputOptions:{...v,input:l.input},outputOptions:y}}function hr(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(2)} MB`}function gr(t,n){let r=o.resolve(t),i=o.resolve(n),a=o.relative(r,i);if(!a||a.startsWith(`..`)||o.isAbsolute(a))return;try{if(e(r).isSymbolicLink())throw new L(`BUILD_FAILED`,`Safety check failed: BP root is a symbolic link or junction: "${r}". Refusing to recursively delete through a symbolic link.`)}catch(e){if(e instanceof L)throw e;if(e?.code===`ENOENT`)return;throw e}let s=r;for(let t of a.split(o.sep)){s=o.join(s,t);try{if(e(s).isSymbolicLink())throw new L(`BUILD_FAILED`,`Safety check failed: script output path contains a symbolic link: "${s}". Refusing to recursively delete through a symbolic link.`)}catch(e){if(e.code===`ENOENT`)break;throw e}}}function _r(e,t,n){let r=o.resolve(e),i=o.resolve(t);if(Nt(r,i)||Nt(i,r))throw new L(`BUILD_FAILED`,`Safety check failed: script output directory "${e}" overlaps ${n} "${t}". Refusing to empty this directory.`)}function vr(e,t,n,r){let i=H(e,t),a=Ot(e,t),s=o.join(a,`manifest.json`),c=[o.join(i,`.git`),o.join(a,`.git`)];for(let e of c)_r(r,e,`.git metadata`);if(t.packs.rp){let e=U(i,t,`rp`);o.resolve(e)!==o.resolve(a)&&_r(r,e,`RP root`)}_r(r,s,`BP manifest`);let l=o.dirname(n),u=o.relative(a,l);Ft(r,a,`script output directory`,u&&!u.startsWith(`..`)&&!o.isAbsolute(u)?[l]:[]),gr(a,r)}async function yr(e,t,n,r={}){if(!At(t))throw new L(`BUILD_FAILED`,`rolldown requires packs.bp.compile to be configured.`);let i=W(e,t),a=jt(e,t),o=Mt(e,t);if(!i||!a||!o)throw new L(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);try{let{inputOptions:o,outputOptions:s}=await mr({cwd:e,config:t,...r.command===void 0?{}:{command:r.command},...r.mode===void 0?{}:{mode:r.mode},...r.rolldownConfig===void 0?{}:{configPath:r.rolldownConfig}});vr(e,t,i,a),await be(a);let c=await _(o);try{await c.write(s)}finally{await c.close()}await br(a,n)}catch(e){throw e instanceof L?e:new L(`BUILD_FAILED`,`rolldown failed: ${e instanceof Error?e.message:String(e)}`)}}async function br(e,t){let n=[];async function r(t){let i=await h.readdir(t,{withFileTypes:!0});for(let a of i){let i=o.join(t,a.name);if(a.isDirectory())await r(i);else if(a.isFile()&&a.name.endsWith(`.js`)){let t=await h.stat(i);n.push({path:o.relative(e,i),size:t.size})}}}if(await r(e),n.length===0)return;n.sort((e,t)=>t.size-e.size);let i=n.reduce((e,t)=>e+t.size,0);t?.rolldown(n.length===1?`${n[0].path} (${hr(n[0].size)})`:`${n.length} files, total ${hr(i)}`)}async function xr(e,t,n,r){let i=r?Date.now():0,a=await t();return r&&n.timing(e,Date.now()-i),a}async function Sr(e){let t=Date.now(),n=e.config.build.timing,r=H(e.cwd,e.config),i=At(e.config),a=e.command??`build`,s={...e.mode===void 0?{}:{mode:e.mode},dryRun:!!e.dryRun};await xr(`manifest`,()=>Bn({cwd:e.cwd,config:e.config,command:a,logger:e.logger,dryRun:!!e.dryRun,...e.mode===void 0?{}:{mode:e.mode},...e.resolvedDeps?{resolvedDeps:e.resolvedDeps}:{}}),e.logger,n);let c=[];e.config.packs.bp&&c.push(`bp`),e.config.packs.rp&&c.push(`rp`),e.logger.manifest(`manifest.json updated (${c.join(`, `)})`),await K(`beforeBuild`,a,e.cwd,e.config,e.logger,s);let l=!1;if(i&&!e.dryRun&&e.typecheck!==!1){let t=e.config.packs.bp.compile,i=e.cache?o.resolve(r,t.cache.file):void 0;await xr(`typecheck`,()=>Kn(r,{quiet:!!e.quiet,useNpx:t.useNpx,tsconfigPath:t.tsconfig,incremental:!!e.cache,...i?{tsBuildInfoFile:i}:{}}),e.logger,n),l=!0,e.logger.typescript(`typecheck complete`)}i&&!e.dryRun&&(await xr(`rolldown`,()=>yr(e.cwd,e.config,e.logger,{...e.command===void 0?{}:{command:e.command},...e.mode===void 0?{}:{mode:e.mode},...e.rolldownConfig===void 0?{}:{rolldownConfig:e.rolldownConfig}}),e.logger,n),e.logger.rolldown(e.config.packs.bp.compile.preserveModules?`preserve modules build complete`:`bundle complete`)),await K(`afterBuild`,a,e.cwd,e.config,e.logger,s);let u=Date.now()-t;return{script:i?V(Mt(e.cwd,e.config)):void 0,compiled:i,typecheck:l,durationMs:u}}async function Cr(e,n=``){let r={},i=await t.readdir(e,{withFileTypes:!0});for(let a of i){let i=o.join(e,a.name),s=n?`${n}/${a.name}`:a.name;a.isDirectory()?Object.assign(r,await Cr(i,s)):r[s]=new Uint8Array(await t.readFile(i))}return r}async function wr(e,n){let r={};for(let i of n){let n=o.join(e,i);try{(await t.stat(n)).isDirectory()?Object.assign(r,await Cr(n,i)):r[i]=new Uint8Array(await t.readFile(n))}catch{}}return r}async function Tr(e,t){return t?await t(e):e}function Er(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}/${r}`]=i;return n}function Dr(e){let t={};for(let n of Object.keys(e).sort())t[n]=e[n];return t}async function Or(e,n){await t.rm(e,{recursive:!0,force:!0}),await t.mkdir(e,{recursive:!0});for(let[r,i]of Object.entries(n)){let n=o.join(e,r);await t.mkdir(o.dirname(n),{recursive:!0}),await t.writeFile(n,i)}}var kr=D((()=>{}));kr();const Ar=new TextEncoder;new TextDecoder;function jr(e){let t=16+e.length*256,n=0,r=[];for(let t of e){let e=Ar.encode(t.name);if(e.length===0)throw new L(`PACK_FAILED`,`brarchive entry names must not be empty.`);if(e.length>247)throw new L(`PACK_FAILED`,`brarchive entry name is too long (max 247 bytes): ${t.name}`,{details:{name:t.name,bytes:e.length}});r.push(e),n+=t.data.length}let i=new Uint8Array(t+n),a=new DataView(i.buffer);a.setBigUint64(0,9018218223661903910n,!1),a.setUint32(8,e.length,!0),a.setUint32(12,1,!0);let o=0;return e.forEach((e,n)=>{let s=16+n*256,c=r[n];a.setUint8(s,c.length),i.set(c,s+1),a.setUint32(s+248,o,!0),a.setUint32(s+252,e.data.length,!0),i.set(e.data,t+o),o+=e.data.length}),i}const Mr=[`functions`,`loot_tables`,`structures`,`texts`],Nr=[`font`,`materials`,`sounds`,`texts`,`textures`],Pr=[1,26,40],Fr=Pr.join(`.`),Ir=new TextEncoder,Lr=new TextDecoder,Rr=new TextDecoder(`utf-16le`),zr=new TextDecoder(`utf-16be`);function Br(e){if(e.length>=2){if(e[0]===255&&e[1]===254)return Rr.decode(e.subarray(2));if(e[0]===254&&e[1]===255)return zr.decode(e.subarray(2))}return Lr.decode(e)}function Vr(e){return e.length>=2&&(e[0]===255&&e[1]===254||e[0]===254&&e[1]===255)}function Hr(e){return e.startsWith(``)?e.slice(1):e}function Ur(e){if(e&&typeof e==`object`&&!Array.isArray(e))return e}function Wr(e){if(typeof e==`string`){let t=e.split(`.`).map(e=>Number.parseInt(e,10));return t.length>=3&&t.slice(0,3).every(e=>Number.isInteger(e))?[t[0],t[1],t[2]]:void 0}if(Array.isArray(e)&&e.length>=3){let t=e.slice(0,3);if(t.every(e=>typeof e==`number`&&Number.isInteger(e)))return t}}function Gr(e,t){for(let n=0;n<3;n++){let r=(e[n]??0)-(t[n]??0);if(r!==0)return r}return 0}function Kr(e){if(e)try{return Ur(JSON.parse(Hr(Br(e))))}catch{return}}function qr(e){return Wr(Ur(e?.header)?.min_engine_version)}function Jr(e){let t=e?.modules;return Array.isArray(t)?t.some(e=>Ur(e)?.type===`resources`):!1}function Yr(e,t,n){if(t.allowUnsupportedTarget)return;let r=qr(e);if(r&&Gr(r,Pr)>=0)return;let i=r?r.join(`.`):`(not declared)`;n?.warn(`pack optimization: header.min_engine_version is ${i}, below ${Fr}. The archives still load on 1.26.40+, but older clients cannot read __brarchive/ and will show missing content. Set allowUnsupportedTarget: true to silence this warning.`)}function Xr(e,t,n){if(!e.toLowerCase().endsWith(`.json`))return t;try{let e=JSON.parse(Hr(Br(t)));return Ir.encode(JSON.stringify(e))}catch(r){let i=r instanceof Error?r.message:String(r),a=Vr(t)?` (UTF-16)`:``;return n?.warn(`pack optimization: could not minify ${e}${a}, storing it unchanged. ${i}. Fix the JSON to have it minified.`),t}}function Zr(e,t){if(!e)throw new L(`PACK_FAILED`,`Pack optimization needs a manifest.json to write header.pack_optimization_version into.`);let n;try{let t=Ur(JSON.parse(Hr(Br(e))));if(!t)throw Error(`manifest is not an object`);n=t}catch{throw new L(`PACK_FAILED`,`Cannot write header.pack_optimization_version: the pack's manifest.json is not valid JSON.`)}let r={...Ur(n.header)??{}};return r.pack_optimization_version=t,n.header=r,Ir.encode(JSON.stringify(n))}function Qr(e,t,n,r){let i=e[`manifest.json`]??r,a=Kr(i);Yr(a,t,n);let o=new Set(t.exclude),s=t.keepLoose===!1?/* @__PURE__ */ new Set:/* @__PURE__ */ new Set([...Jr(a)?Nr:Mr,...t.keepLoose]),c=/* @__PURE__ */ new Map,l={},u={},d=0,f=0;for(let r of Object.keys(e).sort()){let i=e[r],a=r.split(`/`),p=a[0];if(a.length<2||p===`__brarchive`||o.has(p)){l[r]=i;continue}let m=a.slice(0,-1).join(`/`),h=a[a.length-1],g=c.get(m)??[],_=t.keepLooseFiles||s.has(p);s.has(p)&&!t.keepLooseFiles?(g.push({name:h,data:/* @__PURE__ */ new Uint8Array}),u[r]=i,f++):(g.push({name:h,data:t.minifyJson?Xr(h,i,n):i}),d++,_&&(u[r]=i)),c.set(m,g)}let p={...l,...u};for(let e of[...c.keys()].sort())p[`__brarchive/${e}.brarchive`]=jr(c.get(e));p[`manifest.json`]=Zr(i,t.packOptimizationVersion);let m=Object.keys(u).length,h=f>0?`, ${f} name-stub${f===1?``:`s`}`:``;return n?.pack(`optimized into ${c.size} archive${c.size===1?``:`s`} (${d} file${d===1?``:`s`} archived${h}, ${m} kept loose)`),Dr(p)}function $r(e,t,n){return r=>Qr(r,e,t,n)}const ei={win:()=>({type:`gameRoot`,path:o.join(`C:/Users`,u.userInfo().username,`AppData/Roaming/Minecraft Bedrock/Users/Shared/games/com.mojang`)}),winold:()=>{let e=process.env.LOCALAPPDATA;if(!e)throw new L(`COPY_TARGET_NOT_FOUND`,`%LOCALAPPDATA% is required for winold copy target.`);return{type:`gameRoot`,path:o.join(e,`Packages`,`Microsoft.MinecraftUWP_8wekyb3d8bbwe`,`LocalState`,`games`,`com.mojang`)}}};function ti(e,t){return{type:`custom`,bp:o.join(t.path,`development_behavior_packs`),...e.packs.rp?{rp:o.join(t.path,`development_resource_packs`)}:{}}}function ni(e,t){let n=t??e.copy.defaultTarget;if(!n)throw new L(`COPY_TARGET_NOT_FOUND`,`No copy target configured. Set copy.defaultTarget or copy.targets in bepack.config.ts, or pass --target.`,{suggestions:[`Add copy.defaultTarget to your config file.`,`Or set build.copy / dev.copy to a target name instead of true.`,`Built-in targets: win, winold.`]});let r=e.copy.targets[n]??ei[n]?.();if(!r)throw new L(`COPY_TARGET_NOT_FOUND`,`Copy target not found: ${n}`,{details:{target:n}});let i=e.copy.targets[n]?.name,a=e.copy.name,o=e=>typeof e==`string`?{bp:e,rp:e}:e??{},s=o(i),c=o(a),l={},u=s.bp??c.bp,d=s.rp??c.rp;return u&&(l.bp=u),d&&(l.rp=d),r.type===`gameRoot`?{name:n,target:ti(e,r),names:l}:{name:n,target:r,names:l}}const ri=/* @__PURE__ */ new Set([`node_modules`,`package.json`,`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lock`,`bun.lockb`,`tsconfig.json`,...yt]);function ii(e,t,n){let r=U(H(e,t),t,n);if(!r)return[];let i=W(e,t),a=[zt(e,t),i?o.dirname(i):void 0],s=[];for(let e of a){if(!e)continue;let t=o.relative(r,e);if(!t||t.startsWith(`..`)||o.isAbsolute(t))continue;let n=t.split(o.sep)[0];n&&s.push(n)}return s}async function ai(e,n,r=[]){let i;try{i=await t.readdir(e,{withFileTypes:!0})}catch{return[]}let a=new Set(n);return i.map(e=>e.name).filter(e=>!a.has(e)).filter(e=>!e.startsWith(`.`)&&!ri.has(e)).filter(e=>!r.includes(e)).sort((e,t)=>e.localeCompare(t))}function oi(e){return e===`bp`?`packs.bp.include`:`packs.rp.include`}async function si(e){let{logger:t,packType:n,root:r,items:i,action:a}=e;if(!t)return;let o=await ai(r,i,e.ignore??[]);if(o.length===0)return;let s=e.limit??8,c=o.slice(0,s).join(`, `),l=o.length>s?`, +${o.length-s} more`:``,u=n===`bp`?`behavior pack`:`resource pack`;t.warn(`${u} ${a} only includes ${i.length} configured item(s); ${o.length} entr${o.length===1?`y`:`ies`} in "${ci(r,e.cwd)}" ${o.length===1?`is`:`are`} skipped: ${c}${l}. Add them to ${oi(n)} to include them.`)}function ci(e,t){if(!t)return e;let n=o.relative(t,e).replace(/\\/g,`/`);return n&&!n.startsWith(`..`)&&!o.isAbsolute(n)?n:e}kr();const li=we.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);async function ui(e,n,r){await t.rm(n,{recursive:!0,force:!0}),await t.mkdir(n,{recursive:!0});for(let i of r){let r=o.join(e,i),a=o.join(n,i);try{await t.cp(r,a,{recursive:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}function di(e,t){let n=o.resolve(e),r=o.resolve(t);if(Nt(n,r)||Nt(r,n))throw new L(`COPY_FAILED`,`Copy target "${t}" overlaps source pack "${e}". Refusing to copy.`,{details:{source:n,target:r}})}function fi(e,t){let n=o.resolve(e),r=o.resolve(n,t);if(r===n||!Nt(n,r))throw new L(`COPY_FAILED`,`Copy folder name "${t}" must resolve to a directory inside "${e}".`,{details:{targetDir:n,folderName:t,destination:r}});return r}async function pi(e,t){if(!await I(e))throw new L(`COPY_FAILED`,`Copy target directory does not exist: ${e}`,{details:{dir:e,label:t},suggestions:[`Create the target directory: mkdir -p "${e}"`,`Or check the copy target path in bepack.config.ts.`]})}function mi(e,t){if(t===`bp`)return It(e);let n=e.packs.rp?.include??[],r=e.copy.include?.rp??[],i=n.length>0?n:r;return i.length>0?[...Et,...i]:[]}async function hi(e){try{return new Uint8Array(await t.readFile(o.join(e,`manifest.json`)))}catch{return}}async function gi(e,t,n,r,i,a,o,s,c){let l=mi(i,e),u=fi(n,r);di(t,u);let d=e===`bp`||l.length>0;d&&await si({...s?{logger:s}:{},packType:e,root:t,items:l,action:`copy`,cwd:o,ignore:ii(o,i,e)});let f=c===void 0?i.copy.optimize:c?i.copy.optimize??xt:void 0;if(!a){if(f){let e=d?await wr(t,l):await Cr(t),n=$r(f,s,await hi(t));try{await Or(u,await Tr(e,n))}catch(e){throw e instanceof L?new L(e.code===`PACK_FAILED`?`COPY_FAILED`:e.code,e.message,{...e.details===void 0?{}:{details:e.details},...e.suggestions===void 0?{}:{suggestions:e.suggestions}}):e}}else d?await ui(t,u,l):await Ce(t,u)}let p=l.length>0?l.length:void 0;return s?.copy(`${a?`would copy`:`copied`} ${e}${p?` (${p} items)`:``} -> ${li.gray(u)}`),u}async function _i(e,t,n,r=!1,i,a={}){let{name:o,target:s,names:c}=ni(t,n),l=[],u=H(e,t),d=wt(t);for(let n of d){let o;if(o=n.type===`bp`?s.bp:s.rp,!o)continue;await pi(o,n.type);let d=c[n.type]??n.name,f=U(u,t,n.type),p=await gi(n.type,f,o,d,t,r,e,i,a.optimize);l.push(p)}return{target:o,copied:l}}async function vi(e){let{command:t,cwd:n,config:r,logger:i,targetName:a,mode:o,optimize:s}=e,c=!!e.dryRun,l={...o===void 0?{}:{mode:o},dryRun:c};await K(`beforeCopy`,t,n,r,i,l);let u=await _i(n,r,a,c,i,s===void 0?{}:{optimize:s});return await K(`afterCopy`,t,n,r,i,l),u}function yi(e,t){return na(e,t||{},0,0)}function bi(e,t){if(t){for(var n=new J(e.length),r=0;r<e.length;++r)n[r]=e.charCodeAt(r);return n}if(aa)return aa.encode(e);for(var i=e.length,a=new J(e.length+(e.length>>1)),o=0,s=function(e){a[o++]=e},r=0;r<i;++r){if(o+5>a.length){var c=new J(o+8+(i-r<<1));c.set(a),a=c}var l=e.charCodeAt(r);l<128||t?s(l):l<2048?(s(192|l>>6),s(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|e.charCodeAt(++r)&1023,s(240|l>>18),s(128|l>>12&63),s(128|l>>6&63),s(128|l&63)):(s(224|l>>12),s(128|l>>6&63),s(128|l&63))}return Vi(a,0,o)}function xi(e,t){t||={};var n={},r=[];ia(e,``,n,t);var i=0,a=0;for(var o in n){var s=n[o],c=s[0],l=s[1],u=l.level==0?0:8,d=bi(o),f=d.length,p=l.comment,m=p&&bi(p),h=m&&m.length,g=sa(l.extra);f>65535&&Ui(11);var _=u?yi(c,l):c,v=_.length,y=ta();y.p(c),r.push(ra(l,{size:c.length,crc:y.d(),c:_,f:d,m,u:f!=o.length||m&&p.length!=h,o:i,compression:u})),i+=30+f+g+v,a+=76+2*(f+g)+(h||0)+v}for(var b=new J(a+22),x=i,S=a-i,C=0;C<r.length;++C){var d=r[C];ca(b,d.o,d,d.f,d.u,d.c.length);var w=30+d.f.length+sa(d.extra);b.set(d.c,d.o+w),ca(b,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+w+(d.m?d.m.length:0)}return la(b,i,r.length,S,x),b}var Si,Ci,J,Y,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,X,Pi,Fi,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Z,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra,Q,ia,aa,oa,sa,ca,la,ua=D((()=>{Si=y(`/`);try{Ci=Si("worker_threads"),Ci.Worker,Ci.isMarkedAsUntransferable}catch{}for(J=Uint8Array,Y=Uint16Array,wi=Int32Array,Ti=new J([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ei=new J([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Di=new J([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Oi=function(e,t){for(var n=new Y(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new wi(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Ci=Oi(Ti,2),ki=Ci.b,Ai=Ci.r,ki[28]=258,Ai[258]=28,ji=Oi(Ei,0),ji.b,Mi=ji.r,Ni=new Y(32768),X=0;X<32768;++X)Pi=(X&43690)>>1|(X&21845)<<1,Pi=(Pi&52428)>>2|(Pi&13107)<<2,Pi=(Pi&61680)>>4|(Pi&3855)<<4,Ni[X]=((Pi&65280)>>8|(Pi&255)<<8)>>1;for(Fi=(function(e,t,n){for(var r=e.length,i=0,a=new Y(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Y(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Y(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[Ni[d]>>c]=l}else for(s=new Y(r),i=0;i<r;++i)e[i]&&(s[i]=Ni[o[e[i]-1]++]>>15-e[i]);return s}),Ii=new J(288),X=0;X<144;++X)Ii[X]=8;for(X=144;X<256;++X)Ii[X]=9;for(X=256;X<280;++X)Ii[X]=7;for(X=280;X<288;++X)Ii[X]=8;for(Li=new J(32),X=0;X<32;++X)Li[X]=5;Ri=/*#__PURE__*/ Fi(Ii,9,0),zi=/*#__PURE__*/ Fi(Li,5,0),Bi=function(e){return(e+7)/8|0},Vi=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new J(e.subarray(t,n))},Hi=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],Ui=function(e,t,n){var r=Error(t||Hi[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Ui),!n)throw r;return r},Z=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},Wi=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},Gi=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var i=n.length,a=n.slice();if(!i)return{t:Qi,l:0};if(i==1){var o=new J(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var s=n[0],c=n[1],l=0,u=1,d=2;for(n[0]={s:-1,f:s.f+c.f,l:s,r:c};u!=i-1;)s=n[n[l].f<n[d].f?l++:d++],c=n[l!=u&&n[l].f<n[d].f?l++:d++],n[u++]={s:-1,f:s.f+c.f,l:s,r:c};for(var f=a[0].s,r=1;r<i;++r)a[r].s>f&&(f=a[r].s);var p=new Y(f+1),m=Ki(n[u-1],p,0);if(m>t){var r=0,h=0,g=m-t,_=1<<g;for(a.sort(function(e,t){return p[t.s]-p[e.s]||e.f-t.f});r<i;++r){var v=a[r].s;if(p[v]>t)h+=_-(1<<m-p[v]),p[v]=t;else break}for(h>>=g;h>0;){var y=a[r].s;p[y]<t?h-=1<<t-p[y]++-1:++r}for(;r>=0&&h;--r){var b=a[r].s;p[b]==t&&(--p[b],++h)}m=t}return{t:new J(p),l:m}},Ki=function(e,t,n){return e.s==-1?Math.max(Ki(e.l,t,n+1),Ki(e.r,t,n+1)):t[e.s]=n},qi=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Y(++t),r=0,i=e[0],a=1,o=function(e){n[r++]=e},s=1;s<=t;++s)if(e[s]==i&&s!=t)++a;else{if(!i&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(i),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(i);a=1,i=e[s]}return{c:n.subarray(0,r),n:t}},Ji=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},Yi=function(e,t,n){var r=n.length,i=Bi(t+2);e[i]=r&255,e[i+1]=r>>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var a=0;a<r;++a)e[i+a+4]=n[a];return(i+4+r)*8},Xi=function(e,t,n,r,i,a,o,s,c,l,u){Z(t,u++,n),++i[256];for(var d=Gi(i,15),f=d.t,p=d.l,m=Gi(a,15),h=m.t,g=m.l,_=qi(f),v=_.c,y=_.n,b=qi(h),x=b.c,S=b.n,C=new Y(19),w=0;w<v.length;++w)++C[v[w]&31];for(var w=0;w<x.length;++w)++C[x[w]&31];for(var T=Gi(C,7),E=T.t,D=T.l,O=19;O>4&&!E[Di[O-1]];--O);var ee=l+5<<3,k=Ji(i,Ii)+Ji(a,Li)+o,A=Ji(i,f)+Ji(a,h)+o+14+3*O+Ji(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&ee<=k&&ee<=A)return Yi(t,u,e.subarray(c,c+l));var j,M,N,te;if(Z(t,u,1+(A<k)),u+=2,A<k){j=Fi(f,p,0),M=f,N=Fi(h,g,0),te=h;var ne=Fi(E,D,0);Z(t,u,y-257),Z(t,u+5,S-1),Z(t,u+10,O-4),u+=14;for(var w=0;w<O;++w)Z(t,u+3*w,E[Di[w]]);u+=3*O;for(var P=[v,x],re=0;re<2;++re)for(var ie=P[re],w=0;w<ie.length;++w){var ae=ie[w]&31;Z(t,u,ne[ae]),u+=E[ae],ae>15&&(Z(t,u,ie[w]>>5&127),u+=ie[w]>>12)}}else j=Ri,M=Ii,N=zi,te=Li;for(var w=0;w<s;++w){var F=r[w];if(F>255){var ae=F>>18&31;Wi(t,u,j[ae+257]),u+=M[ae+257],ae>7&&(Z(t,u,F>>23&31),u+=Ti[ae]);var oe=F&31;Wi(t,u,N[oe]),u+=te[oe],oe>3&&(Wi(t,u,F>>5&8191),u+=Ei[oe])}else Wi(t,u,j[F]),u+=M[F]}return Wi(t,u,j[256]),u+M[256]},Zi=/*#__PURE__*/ new wi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Qi=/*#__PURE__*/ new J(0),$i=function(e,t,n,r,i,a){var o=a.z||e.length,s=new J(r+o+5*(1+Math.ceil(o/7e3))+i),c=s.subarray(r,s.length-i),l=a.l,u=(a.r||0)&7;if(t){u&&(c[0]=a.r>>3);for(var d=Zi[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new Y(32768),g=a.h||new Y(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new wi(25e3),x=new Y(288),S=new Y(32),C=0,w=0,T=a.i||0,E=0,D=a.w||0,O=0;T+2<o;++T){var ee=y(T),k=T&32767,A=g[ee];if(h[k]=A,g[ee]=k,D<=T){var j=o-T;if((C>7e3||E>24576)&&(j>423||!l)){u=Xi(e,c,0,b,x,S,w,E,O,T-O,u),E=C=w=0,O=T;for(var M=0;M<286;++M)x[M]=0;for(var M=0;M<30;++M)S[M]=0}var N=2,te=0,ne=p,P=k-A&32767;if(j>2&&ee==y(T-P))for(var re=Math.min(f,j)-1,ie=Math.min(32767,T),ae=Math.min(258,j);P<=ie&&--ne&&k!=A;){if(e[T+N]==e[T+N-P]){for(var F=0;F<ae&&e[T+F]==e[T+F-P];++F);if(F>N){if(N=F,te=P,F>re)break;for(var oe=Math.min(P,F-2),se=0,M=0;M<oe;++M){var ce=T-P+M&32767,le=ce-h[ce]&32767;le>se&&(se=le,A=ce)}}}k=A,A=h[k],P+=k-A&32767}if(te){b[E++]=268435456|Ai[N]<<18|Mi[te];var ue=Ai[N]&31,de=Mi[te]&31;w+=Ti[ue]+Ei[de],++x[257+ue],++S[de],D=T+N,++C}else b[E++]=e[T],++x[e[T]]}}for(T=Math.max(T,D);T<o;++T)b[E++]=e[T],++x[e[T]];u=Xi(e,c,l,b,x,S,w,E,O,T-O,u),l||(a.r=u&7|c[u/8|0]<<3,u-=7,a.h=g,a.p=h,a.i=T,a.w=D)}else{for(var T=a.w||0;T<o+l;T+=65535){var fe=T+65535;fe>=o&&(c[u/8|0]=l,fe=o),u=Yi(c,u+1,e.subarray(T,fe))}a.i=o}return Vi(s,0,r+Bi(u)+i)},ea=/*#__PURE__*/ (function(){for(var e=/* @__PURE__ */ new Int32Array(256),t=0;t<256;++t){for(var n=t,r=9;--r;)n=(n&1&&-306674912)^n>>>1;e[t]=n}return e})(),ta=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=ea[n&255^t[r]]^n>>>8;e=n},d:function(){return~e}}},na=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new J(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return $i(e,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,r,i)},ra=function(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n},Q=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8},ia=function(e,t,n,r){for(var i in e){var a=e[i],o=t+i,s=r;Array.isArray(a)&&(s=ra(r,a[1]),a=a[0]),ArrayBuffer.isView(a)?n[o]=[a,s]:(n[o+=`/`]=[new J(0),s],ia(a,o,n,r))}},aa=typeof TextEncoder<`u`&&/*#__PURE__*/ new TextEncoder,oa=typeof TextDecoder<`u`&&/*#__PURE__*/ new TextDecoder;try{oa.decode(Qi,{stream:!0})}catch{}sa=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&Ui(9),t+=r+4}return t},ca=function(e,t,n,r,i,a,o,s){var c=r.length,l=n.extra,u=s&&s.length,d=sa(l);Q(e,t,o==null?67324752:33639248),t+=4,o!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(a<0&&8),e[t++]=i&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var f=new Date(n.mtime==null?Date.now():n.mtime),p=f.getFullYear()-1980;if((p<0||p>119)&&Ui(10),Q(e,t,p<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,a!=-1&&(Q(e,t,n.crc),Q(e,t+4,a<0?-a-2:a),Q(e,t+8,n.size)),Q(e,t+12,c),Q(e,t+14,d),t+=16,o!=null&&(Q(e,t,u),Q(e,t+6,n.attrs),Q(e,t+10,o),t+=14),e.set(r,t),t+=c,d)for(var m in l){var h=l[m],g=h.length;Q(e,t,+m),Q(e,t+2,g),e.set(h,t+4),t+=4+g}return u&&(e.set(s,t),t+=u),t},la=function(e,t,n,r,i){Q(e,t,101010256),Q(e,t+8,n),Q(e,t+10,n),Q(e,t+12,r),Q(e,t+16,i)}}));async function da(e,n){await t.mkdir(o.dirname(n),{recursive:!0}),await t.writeFile(n,xi(Dr(e)))}async function fa(e,t,n){await da(await Tr(await Cr(e),n),t)}async function pa(e,t,n,r){await da(await Tr(await wr(e,t),r),n)}async function ma(e,t){let n={};for(let t of e){let e=await Tr(await wr(t.source,t.items),t.transform);Object.assign(n,Er(e,o.basename(o.resolve(t.source))))}await da(n,t)}async function ha(e,t,n){let r={};for(let t of e){let e=await Tr(await wr(t.source,t.items),t.transform);Object.assign(r,Er(e,o.basename(o.resolve(t.source))))}for(let e of t){let t=await Tr(await Cr(e.dir),e.transform);Object.assign(r,Er(t,o.basename(o.resolve(e.dir))))}await da(r,n)}var ga=D((()=>{ua(),kr()})),_a=/* @__PURE__ */ ee({packMcpack:()=>va});async function va(e,t,n,r=!1,i){let a=o.join(t,`${n}.mcpack`);return r||await fa(e,a,i),a}var ya=D((()=>{ga()}));ga();function ba(e,t,n){let r=o.resolve(e),i=o.resolve(t),a=o.relative(i,r);if(a&&!a.startsWith(`..`)&&!o.isAbsolute(a))throw new L(`PACK_FAILED`,`pack output must not be inside ${n} directory.`,{details:{output:r,dir:i},suggestions:[`Set pack.outDir to a path outside ${n}: ${i}`]})}function xa(e,t,n){let r=o.resolve(e),i=o.resolve(t);for(let e of n){let t=o.resolve(i,e),n=o.relative(t,r);if(n===``||!n.startsWith(`..${o.sep}`)&&n!==`..`&&!o.isAbsolute(n))throw new L(`PACK_FAILED`,`pack output must not be included in the BP archive.`,{details:{output:r,includedPath:t},suggestions:[`Set pack.outDir outside the selected BP include path: ${t}`]})}}function Sa(e,t){let n=o.relative(o.resolve(t),o.resolve(e));if(n.startsWith(`..`)||o.isAbsolute(n))throw new L(`PACK_FAILED`,`pack output name must stay inside pack.outDir.`,{details:{output:o.resolve(e),dist:o.resolve(t)}})}function Ca(e,t){if(t===`bp`)return{items:It(e),selective:!0};let n=e.packs.rp?.include??[],r=e.copy.include?.rp??[],i=n.length>0?n:r;return i.length>0?{items:[...Et,...i],selective:!0}:{items:[],selective:!1}}async function wa(e,t,n={}){let r=H(e,t),i=(n.name??t.pack.name).replaceAll(`{name}`,t.name).replaceAll(`{version}`,t.version),a=zt(e,t);if(wt(t).length===0)throw new L(`PACK_FAILED`,`No packs configured. At least one pack is required.`);let s=n.optimize===void 0?t.pack.optimize:n.optimize?t.pack.optimize??xt:void 0,c=s?$r(s,n.logger):void 0,l=t.packs.bp?{root:U(r,t,`bp`),config:t}:void 0,u=t.packs.rp?{root:U(r,t,`rp`),config:t}:void 0,d=l?Ca(t,`bp`):void 0;if(l&&d?.selective&&await si({...n.logger?{logger:n.logger}:{},packType:`bp`,root:l.root,items:d.items,action:`pack`,cwd:e,ignore:ii(e,t,`bp`)}),u){let r=Ca(t,`rp`);r.selective&&await si({...n.logger?{logger:n.logger}:{},packType:`rp`,root:u.root,items:r.items,action:`pack`,cwd:e,ignore:ii(e,t,`rp`)})}if(l&&u){if(!d)throw new L(`PACK_FAILED`,`BP pack configuration is missing.`);let e=o.join(a,`${i}.mcaddon`);if(Sa(e,a),d?.selective&&xa(e,l.root,d.items),ba(e,u.root,`RP`),!n.dryRun){let n=Ca(t,`rp`);n.selective?await ma([{source:l.root,items:d.items,...c?{transform:c}:{}},{source:u.root,items:n.items,...c?{transform:c}:{}}],e):await ha([{source:l.root,items:d.items,...c?{transform:c}:{}}],[{dir:u.root,...c?{transform:c}:{}}],e)}return e}if(l){if(!d)throw new L(`PACK_FAILED`,`BP pack configuration is missing.`);let e=o.join(a,`${i}.mcpack`);return Sa(e,a),d?.selective&&xa(e,l.root,d.items),n.dryRun||await pa(l.root,d.items,e,c),e}if(u){let e=o.join(a,`${i}.mcpack`);if(Sa(e,a),ba(e,u.root,`RP`),!n.dryRun){let r=Ca(t,`rp`);if(r.selective)await pa(u.root,r.items,e,c);else{let{packMcpack:e}=await Promise.resolve().then(()=>(ya(),_a));return await e(u.root,a,i,n.dryRun,c)}}return e}throw new L(`PACK_FAILED`,`No packs configured.`)}async function Ta(e,t,n,r={}){let i=Date.now();await K(`beforePack`,`pack`,e,t,n,{dryRun:!!r.dryRun});let a=await wa(e,t,{...r,logger:n});await K(`afterPack`,`pack`,e,t,n,{dryRun:!!r.dryRun});let o=Date.now()-i;return n.done(`pack`,r.dryRun?`dry-run: would pack ${a} (no file written)`:`packed ${a} in ${n.formatDuration(o)}`),{output:a,durationMs:o,dryRun:!!r.dryRun}}async function Ea(e){let t=new Te({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await Sn({cwd:e.cwd??process.cwd(),configPath:e.config}),i=e.build===!1||!!e.skipBuild,a=null;if(!i){let i=e.skipTypecheck?!1:e.typecheck?!0:r.packs.bp?.compile?.typecheck,o=e.cache===void 0?r.packs.bp?.compile?.cache.build??!1:!!e.cache;a=await Sr({cwd:n,config:r,logger:t,command:`build`,...i===void 0?{}:{typecheck:i},...e.cache===void 0?{}:{cache:o},dryRun:!!e.dryRun,quiet:!!(e.json||e.silent),...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{}})}let{output:o,durationMs:s}=await Ta(n,r,t,{name:e.name,dryRun:e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}});return{ok:!0,command:`pack`,durationMs:s,output:o,built:!i,build:a}}function Da(e){for(let t of[[`copy`,`skipCopy`],[`pack`,`skipPack`],[`typecheck`,`skipTypecheck`],[`install`,`skipInstall`]]){let[n,r]=t;if(e[n]&&e[r])throw new L(`CLI_ARGUMENT_CONFLICT`,`--${n} and --${r} cannot be used together.`)}}async function Oa(e){Da(e);let t=new Te({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await Sn({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{target:e.target,...e.timing===void 0?{}:{build:{timing:e.timing}}}});t.bepack(`build`,`target ${r.target}`);let i;if(e.install){let t=await Un({...e,cwd:n,config:void 0,silent:e.silent||e.json});i=Object.fromEntries(Object.entries(t.resolved).filter(([,e])=>e.manifestVersion!==null).map(([e,t])=>[e,t.manifestVersion]))}let a=r.packs.bp?.compile,o=e.skipTypecheck?!1:e.typecheck?!0:a?.typecheck??!1,s=e.cache===void 0?a?.cache.build??!1:e.cache,c=await Sr({cwd:n,config:r,logger:t,mode:e.mode,command:`build`,...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},typecheck:!!o,cache:!!s,dryRun:!!e.dryRun,quiet:!!(e.json||e.silent),...i?{resolvedDeps:i}:{}}),l=null,u=e.skipCopy?!1:e.copy||e.copyTarget?!0:r.build.copy;u&&(l=await vi({command:`build`,cwd:n,config:r,logger:t,...e.mode===void 0?{}:{mode:e.mode},targetName:e.copyTarget??(typeof u==`string`?u:void 0),dryRun:!!e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}}));let d=null;return!e.skipPack&&e.pack&&(d=await Ta(n,r,t,{name:e.name,dryRun:e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}})),t.done(`build`,`complete in ${t.formatDuration(c.durationMs)}`),{ok:!0,command:`build`,durationMs:c.durationMs,build:c,copy:l,pack:d}}async function ka(e){let t=Date.now(),n=new Te({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await Sn({cwd:e.cwd??process.cwd(),configPath:e.config});await K(`beforeCopy`,`copy`,r,i,n,{dryRun:!!e.dryRun});let a=e.all?[`win`,`winold`,...Object.keys(i.copy.targets)]:[e.target??i.copy.defaultTarget],o={...e.optimize===void 0?{}:{optimize:!!e.optimize}},s=[];for(let t of a)s.push(await _i(r,i,t,e.dryRun,n,o));await K(`afterCopy`,`copy`,r,i,n,{dryRun:!!e.dryRun});let c=Date.now()-t;return n.done(`copy`,`${e.dryRun?`dry-run complete`:`complete`} in ${n.formatDuration(c)}`),{ok:!0,command:`copy`,durationMs:c,results:s}}const Aa=/[/\\]rolldown\.config\.[A-Za-z0-9_-]+\.js$/;function ja(e,t){return V(o.relative(e,t))}function Ma(e,t,n,r){let i=H(e,t),a=At(t),s=[];if(a){let n=W(e,t);n&&s.push(ja(e,o.dirname(n)))}if(r.copy){for(let n of wt(t))if(U(i,t,n.type)){let r=Na(e,t,n.type,i);s.push(...r)}}let c=t.dev.watch?.include??[];s.push(...c);let l=Vt(s.map(t=>o.resolve(e,t))).map(t=>ja(e,t));if(l.length===0)throw new L(`DEV_NO_WATCH_TARGETS`,`Nothing to watch: no compile entry, no copy-enabled pack directories and no dev.watch.include paths.`,{suggestions:[`Configure packs.bp.compile.entry to watch TypeScript sources.`,"Enable copying (packs.rp/bp, dev.copy or `bepack dev --copy`) to watch pack folders.",`Add paths explicitly with dev.watch.include.`]});let u=[`node_modules`,`.git`,ja(e,zt(e,t))];for(let n of wt(t)){let r=U(i,t,n.type);if(r&&(u.push(ja(e,o.join(r,`manifest.json`))),n.type===`bp`&&a)){let n=U(i,t,`bp`),r=t.packs.bp.compile.scriptOutputDir;u.push(ja(e,o.join(n,r)))}}let d=b.watch(l,{cwd:e,ignored:[...u,Aa],ignoreInitial:!0}),f=!1,p=!1,m=!1,h=async()=>{r.copy&&await vi({command:`dev`,cwd:e,config:t,logger:n,targetName:r.copyTarget,dryRun:r.dryRun,...r.mode===void 0?{}:{mode:r.mode},...r.optimize===void 0?{}:{optimize:r.optimize}})},g=async()=>{await Bn({cwd:e,config:t,command:`dev`,dryRun:r.dryRun,logger:n,...r.mode===void 0?{}:{mode:r.mode}}),await h()},_=async()=>{a?await Sr({cwd:e,config:t,logger:n,command:`dev`,typecheck:r.typecheck,cache:r.cache,dryRun:r.dryRun,quiet:!!r.quiet,...r.mode===void 0?{}:{mode:r.mode},...r.rolldownConfig===void 0?{}:{rolldownConfig:r.rolldownConfig}}):await Bn({cwd:e,config:t,command:`dev`,dryRun:r.dryRun,logger:n,...r.mode===void 0?{}:{mode:r.mode}}),await h()},v=async()=>{for(;p||m;){let e=p;p=!1,m=!1;let t=Date.now();try{n.clear(),e?(n.bepack(`dev`,`rebuilding (pending changes)`),await _(),n.done(`dev`,`rebuild done in ${n.formatDuration(Date.now()-t)}`)):await g()}catch(e){n.error(e instanceof Error?e.message:String(e))}}};d.on(`all`,async(r,i)=>{let s=V(i),c=a?W(e,t):void 0,l=c?o.dirname(c):void 0,u=o.resolve(e,s),d=l?u===l||u.startsWith(l+o.sep):!1;if(f){d?p=!0:m=!0;return}f=!0;let h=Date.now();try{n.clear(),n.bepack(`dev`,`changed ${o.normalize(i)}`),d&&a?await _():await g(),n.done(`dev`,`updated after ${o.normalize(i)} in ${n.formatDuration(Date.now()-h)}`)}catch(e){n.error(e instanceof Error?e.message:String(e))}finally{try{await v()}finally{f=!1}}});let y=t.packs.bp?V(o.relative(e,U(i,t,`bp`))):null,x=t.packs.rp?V(o.relative(e,U(i,t,`rp`))):null,S=a&&W(e,t)?ja(e,o.dirname(W(e,t))):null,C=!1,w=[],T=0,E=0;for(let e of l)y&&(e===y||e.startsWith(y+`/`))?(T++,S&&(e===S||e.startsWith(S+`/`))&&(C=!0)):x&&(e===x||e.startsWith(x+`/`))?(E++,S&&(e===S||e.startsWith(S+`/`))&&(C=!0)):S&&(e===S||e.startsWith(S+`/`))||w.push(e);return S&&!C&&w.unshift(S),T>0&&w.push(`bp(${T})`),E>0&&w.push(`rp(${E})`),n.progress(`dev`,`watching ${w.join(`, `)}`),d}function Na(e,t,n,r){let i=U(r,t,n);if(!i)return[];if(n===`bp`)return It(t).filter(e=>e!==`manifest.json`).map(t=>V(o.relative(e,o.join(i,t))));let a=t.packs.rp;return a?a.include&&a.include.length>0?a.include.filter(e=>e!==`manifest.json`).map(t=>V(o.relative(e,o.join(i,t)))):[V(o.relative(e,i))]:[]}async function Pa(e){let t=Date.now(),n=new Te({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await Sn({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{...e.timing===void 0?{}:{build:{timing:e.timing}}}});n.clear(),n.bepack(`dev`,`target ${i.target}`),n.progress(`dev`,`initial build started`);let a=i.packs.bp?.compile,o=e.skipTypecheck?!1:e.typecheck?!0:a?.typecheck??!1,s=!e.skipCopy&&!!(e.copy||e.copyTarget||i.dev.copy),c=e.copyTarget??(typeof i.dev.copy==`string`?i.dev.copy:void 0),l=a?.cache.dev??!0,u=!!e.dryRun,d=!!(e.json||e.silent),f=e.optimize===void 0?{}:{optimize:!!e.optimize};return await Sr({cwd:r,config:i,logger:n,mode:e.mode,command:`dev`,...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},typecheck:!!o,cache:l,dryRun:u,quiet:d}),s&&await vi({command:`dev`,cwd:r,config:i,logger:n,targetName:c,dryRun:u,...e.mode===void 0?{}:{mode:e.mode},...f}),n.done(`dev`,`initial build complete in ${n.formatDuration(Date.now()-t)}`),Ma(r,i,n,{copy:s,mode:e.mode,...c?{copyTarget:c}:{},...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},...f,typecheck:!!o,cache:l,dryRun:u,quiet:d}),{ok:!0,command:`dev`,initialBuildDurationMs:Date.now()-t}}function Fa(e){let t=/* @__PURE__ */ new WeakSet;function n(e){if(typeof e==`function`)return`[function]`;if(e instanceof RegExp)return e.toString();if(typeof e!=`object`||!e)return e;if(t.has(e))return`[circular]`;t.add(e);let r=Array.isArray(e)?e.map(n):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)]));return t.delete(e),r}return n(e)}async function Ia(e){let t=new Te({...e,silent:e.silent||e.json}),{cwd:n,config:r,path:i}=await Sn({cwd:e.cwd??process.cwd(),configPath:e.config});if(e.json)return{cwd:n,configFile:i,config:Fa(r)};if(e.summary){t.bepack(`config`,i),t.info(`root: ${r.root}`),t.info(`name: ${r.name}`),t.info(`version: ${r.version}`),r.description&&t.info(`description: ${r.description}`),t.info(`target: ${r.target}`);let e=[];if(r.packs.bp&&e.push(`bp`),r.packs.rp&&e.push(`rp`),t.info(`packs: ${e.join(`, `)}`),r.packs.bp?.compile){let e=r.packs.bp.compile;t.info(`compile.entry: ${e.entry}`),t.info(`compile.scriptOutputDir: ${e.scriptOutputDir}`),t.info(`compile.preserveModules: ${e.preserveModules}`),t.info(`compile.typecheck: ${e.typecheck}`),e.external.length>0&&t.info(`compile.external: [${e.external.map(e=>typeof e==`string`?e:e.toString()).join(`, `)}]`)}let n=Object.keys(r.hooks);n.length>0?t.info(`hooks: ${n.join(`, `)}`):t.info(`hooks: (none)`);let a=r.plugins??[];if(a.length>0){t.info(`plugins: ${a.map(e=>`${e.name} (priority ${e.priority??0})`).join(`, `)}`);for(let e of r.pluginDiagnostics??[])t.warn(`plugin conflict: ${e}`)}else t.info(`plugins: (none)`);t.info(`install.registry: ${r.install.registry}`);let o=Object.keys(Cn(r));return o.length>0?t.info(`install.dependencyCatalog: ${o.join(`, `)}`):t.info(`install.dependencyCatalog: (none)`),t.info(`pack.outDir: ${r.pack.outDir}`),r.copy.defaultTarget&&t.info(`copy.defaultTarget: ${r.copy.defaultTarget}`),r.build.copy&&t.info(`build.copy: ${r.build.copy}`),r.dev.copy&&t.info(`dev.copy: ${r.dev.copy}`),{ok:!0,command:`config`}}let a=Fa(r),o=JSON.stringify(a,null,2);return t.bepack(`config`,i),t.info(`cwd: ${n}`),t.info(`configFile: ${i}`),t.info(``),t.info(o),{ok:!0,command:`config`}}function La(e){return e instanceof L?{code:e.code,message:e.message,...e.details===void 0?{}:{details:e.details},...e.suggestions===void 0?{}:{suggestions:e.suggestions},...e.stack?{stack:e.stack}:{}}:e instanceof Error?{code:`UNKNOWN`,message:e.message,...e.stack?{stack:e.stack}:{}}:{code:`UNKNOWN`,message:String(e)}}function Ra(e){console.log(JSON.stringify(e,null,4))}const za=we.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`),Ba=i(import.meta.url),Va=s(Ba),Ha=c(Va,`../package.json`);let Ua;try{let e=JSON.parse(n(Ha,`utf-8`));(typeof e.version!=`string`||!e.version)&&(console.error(`ERROR: package.json missing valid 'version' field`),process.exit(1)),Ua=e.version}catch(e){console.error(`ERROR: Failed to read package version: ${e.message}`),process.exit(1)}const $=ge(`bepack`);function Wa(e){return e.option(`--cwd <path>`,`Working directory`).option(`--config <path>`,`Config path`).option(`--json`,`JSON output`).option(`--dry-run`,`Do not write files`).option(`--silent`,`Silent output`).option(`--verbose`,`Verbose output`)}let Ga=!1;function Ka(e,t,n){let r=La(t);if(n)Ra({ok:!1,command:e,error:r});else if(t instanceof L){if(console.error(`${za.red(r.code)}: ${r.message}`),r.suggestions?.length)for(let e of r.suggestions)console.error(` ${za.dim(`→`)} ${e}`);Ga&&r.stack&&console.error(`${za.dim(r.stack)}`)}else t instanceof Error?(console.error(`${za.red(`ERROR`)}: ${t.message}`),Ga&&r.stack&&console.error(`${za.dim(r.stack)}`)):console.error(`${za.red(`ERROR`)}: ${String(t)}`);process.exitCode=1}async function qa(e,t,n){Ga=!!n.verbose;try{let e=await t(n);n.json&&Ra(e)}catch(t){Ka(e,t,!!n.json)}}Wa($.command(`init`,`Create BePack project`)).option(`--format <format>`,`ts/js/mjs`).option(`--yes`,`Use defaults`).option(`--force`,`Overwrite generated files`).option(`--from-bp <path>`,`Reverse-engineer config from existing BP manifest.json`).option(`--from-rp <path>`,`Reverse-engineer config from existing RP manifest.json`).action(e=>qa(`init`,vt,e)),Wa($.command(`install`,`Sync dependencies`)).option(`--target <target>`,`Target MC version`).option(`--registry <url>`,`npm registry`).option(`--pm <pm>`,`Package manager`).option(`--skip-pm`,`Do not run package manager`).option(`--skip-manifest`,`Do not patch manifest`).option(`--skip-package-json`,`Do not patch package.json`).option(`--save-to <field>`,`dependencies/devDependencies`).action(e=>qa(`install`,Un,e)),Wa($.command(`manifest`,`Patch manifest files`)).option(`--target <target>`,`Target MC version`).action(e=>qa(`manifest`,Wn,e)),Wa($.command(`build`,`Build project`)).alias(`b`).option(`--mode <value>`,`Execution mode (passed to hooks)`).option(`--target <target>`,`Target MC version`).option(`--install`,`Run install`).option(`--skip-install`,`Skip install`).option(`--copy`,`Copy after build`).option(`--copy-target <target>`,`Copy target`).option(`--skip-copy`,`Skip copy`).option(`--pack`,`Pack after build`).option(`--skip-pack`,`Skip pack`).option(`--optimize`,`Optimize packed/copied output into __brarchive archives (--no-optimize to disable)`).option(`--typecheck`,`Run typecheck`).option(`--skip-typecheck`,`Skip typecheck`).option(`--preserve-modules`,`Preserve module output`).option(`--use-npx`,`Use npx tsc for typecheck`).option(`--minify`,`Minify output`).option(`--cache`,`Enable incremental compilation cache (--no-cache to disable)`).option(`--rolldown-config <path>`,`Custom rolldown config file (overrides bepack.config)`).option(`--timing`,`Show per-step timing`).action(e=>qa(`build`,Oa,e)),Wa($.command(`copy`,`Copy packs`)).option(`--target <target>`,`Copy target`).option(`--all`,`Copy to all targets`).option(`--optimize`,`Optimize the copied packs into __brarchive archives (--no-optimize to disable)`).action(e=>qa(`copy`,ka,e)),Wa($.command(`pack`,`Build and pack mcpack/mcaddon`)).option(`--name <name>`,`Output name`).option(`--optimize`,`Bundle loose files into __brarchive archives (--no-optimize to disable)`).option(`--build`,`Build before packing (default; --no-build to skip)`).option(`--skip-build`,`Pack the current pack folders without building first`).option(`--typecheck`,`Run typecheck before packing`).option(`--skip-typecheck`,`Skip typecheck before packing`).option(`--rolldown-config <path>`,`Custom rolldown config file (overrides bepack.config)`).action(e=>qa(`pack`,Ea,e)),Wa($.command(`dev`,`Watch project`)).option(`--mode <value>`,`Execution mode (passed to hooks)`).option(`--copy`,`Copy on change`).option(`--copy-target <target>`,`Copy target`).option(`--skip-copy`,`Skip copy`).option(`--typecheck`,`Run typecheck`).option(`--skip-typecheck`,`Skip typecheck`).option(`--rolldown-config <path>`,`Custom rolldown config file (overrides bepack.config)`).option(`--optimize`,`Optimize packed/copied output into __brarchive archives (--no-optimize to disable)`).option(`--timing`,`Show per-step timing`).action(e=>qa(`dev`,Pa,e)),Wa($.command(`config`,`Show resolved config`)).option(`--summary`,`Show brief summary instead of full config`).action(e=>qa(`config`,Ia,e)),$.help(),$.version(Ua);async function Ja(e){if($.unsetMatchedCommand(),$.parse(e,{run:!1}),!$.options.help&&!$.options.version){if(!$.matchedCommand){let e=$.args[0]??$.rawArgs.slice(2).find(e=>e!==`--`&&!e.startsWith(`-`));if(e){Ka(`cli`,new L(`UNKNOWN_COMMAND`,`Unknown command: ${e}`,{suggestions:["Run `bepack --help` to see available commands."]}),!!$.options.json);return}$.outputHelp();return}try{await $.runMatchedCommand()}catch(e){Ka(`cli`,e,!!$.options.json)}}}await Ja(process.argv);export{};
8
+ `))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;t&&console.info(`${e}/${t} ${ge}`)}checkRequiredArgs(){let e=this.args.filter(e=>e.required).length;if(this.cli.args.length<e)throw new pe(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let n of Object.keys(e))if(n!==`--`&&!this.hasOption(n)&&!t.hasOption(n))throw new pe(`Unknown option \`${n.length>1?`--${n}`:`-${n}`}\``)}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,n=[...t.options,...this.options];for(let t of n){let r=e[t.name.split(`.`)[0]];if(t.required){let e=n.some(e=>e.negated&&e.names.includes(t.name));if(r===!0||r===!1&&!e)throw new pe(`option \`${t.rawName}\` value is missing`)}}}checkUnusedArgs(){let e=this.args.some(e=>e.variadic)?1/0:this.args.length;if(e<this.cli.args.length)throw new pe(`Unused args: ${this.cli.args.slice(e).map(e=>`\`${e}\``).join(`, `)}`)}},ve=class extends _e{constructor(e){super(`@@global@@`,``,{},e)}},ye=class extends EventTarget{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;constructor(e=``){super(),this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new ve(this),this.globalCommand.usage(`<command> [options]`)}usage(e){return this.globalCommand.usage(e),this}command(e,t,n){let r=new _e(e,t||``,n,this);return r.globalCommand=this.globalCommand,this.commands.push(r),r}option(e,t,n){return this.globalCommand.option(e,t,n),this}help(e){return this.globalCommand.option(`-h, --help`,`Display this message`),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t=`-v, --version`){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){this.matchedCommand?this.matchedCommand.outputHelp():this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},n,r){return this.args=e,this.options=t,n&&(this.matchedCommand=n),r&&(this.matchedCommandName=r),this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(e,{run:t=!0}={}){if(!e){if(!he)throw Error(`No argv provided and runtime process argv is not available.`);e=he}this.rawArgs=e,this.name||=e[1]?de(e[1]):`cli`;let n=!0;for(let t of this.commands){let r=this.mri(e.slice(2),t),i=r.args[0];if(t.isMatched(i)){n=!1;let e={...r,args:r.args.slice(1)};this.setParsedInfo(e,t,i),this.dispatchEvent(new CustomEvent(`command:${i}`,{detail:t}))}}if(n){for(let t of this.commands)if(t.isDefaultCommand){n=!1;let r=this.mri(e.slice(2),t);this.setParsedInfo(r,t),this.dispatchEvent(new CustomEvent(`command:!`,{detail:t}))}}if(n){let t=this.mri(e.slice(2));this.setParsedInfo(t)}this.options.help&&this.showHelpOnExit&&(this.outputHelp(),t=!1,this.unsetMatchedCommand()),this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null&&(this.outputVersion(),t=!1,this.unsetMatchedCommand());let r={args:this.args,options:this.options};return t&&this.runMatchedCommand(),!this.matchedCommand&&this.args[0]&&this.dispatchEvent(new CustomEvent(`command:*`,{detail:this.args[0]})),r}mri(e,t){let n=[...this.globalCommand.options,...t?t.options:[]],r=oe(n),i=[],a=e.indexOf(`--`);a!==-1&&(i=e.slice(a+1),e=e.slice(0,a));let o=ie(e,r);o=Object.keys(o).reduce((e,t)=>({...e,[fe(t)]:o[t]}),{_:[]});let s=o._,c={"--":i},l=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,u=Object.create(null);for(let e of n){if(!l&&e.config.default!==void 0)for(let t of e.names)c[t]=e.config.default;Array.isArray(e.config.type)&&u[e.name]===void 0&&(u[e.name]=Object.create(null),u[e.name].shouldTransform=!0,u[e.name].transformFunction=e.config.type[0])}for(let e of Object.keys(o))e!==`_`&&(le(c,e.split(`.`),o[e]),ue(c,u));return{args:s,options:c}}runMatchedCommand(){let{args:e,options:t,matchedCommand:n}=this;if(!n||!n.commandAction)return;n.checkUnknownOptions(),n.checkOptionValue(),n.checkRequiredArgs(),n.checkUnusedArgs();let r=[];return n.args.forEach((t,n)=>{t.variadic?r.push(e.slice(n)):r.push(e[n])}),r.push(t),n.commandAction.apply(this,r)}};const be=(e=``)=>new ye(e);function xe(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Invalid JSON in ${t}: ${e instanceof Error?e.message:String(e)}`)}}function Se(e){return`${JSON.stringify(e,null,4)}\n`}async function P(e){try{return await n.access(e),!0}catch{return!1}}async function Ce(e){await n.mkdir(e,{recursive:!0})}async function we(e){await n.rm(e,{recursive:!0,force:!0}),await n.mkdir(e,{recursive:!0})}async function Te(e){return xe(await n.readFile(e,`utf8`),e)}async function Ee(e,t){await Ce(s.dirname(e)),await n.writeFile(e,Se(t),`utf8`)}async function De(e,t){await n.rm(t,{recursive:!0,force:!0}),await n.mkdir(s.dirname(t),{recursive:!0}),await n.cp(e,t,{recursive:!0})}var F=class extends Error{code;details;suggestions;constructor(e,t,n={}){super(t),this.name=`BePackError`,this.code=e,this.details=n.details,this.suggestions=n.suggestions}},Oe=/* @__PURE__ */ A((/* @__PURE__ */ O(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})))(),1);const I=Oe.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);var L=class{options;constructor(e={}){this.options=e}formatDuration(e){return I.green(`${(e/1e3).toFixed(2)}s`)}info(e){this.options.silent||console.log(e)}warn(e){this.options.silent||console.warn(I.yellow(e))}error(e){this.options.silent||console.error(I.red(e))}verbose(e){!this.options.silent&&this.options.verbose&&console.log(I.gray(e))}clear(){this.options.silent||console.clear()}step(e,t,n=`cyan`){this.info(`${I[n](e.padEnd(10))} ${t}`)}progress(e,t){this.step(e,t,`blue`)}success(e,t){this.step(e,t,`green`)}bepack(e,t){this.info(`${I.green(`bepack`)} ${I.bold(e)} ${I.gray(t)}`)}manifest(e){this.step(`manifest`,e,`yellow`)}typescript(e){this.step(`TS`,e,`blue`)}rolldown(e){this.step(`rolldown`,e,`magenta`)}install(e){this.step(`install`,e,`blue`)}copy(e){this.step(`copy`,e,`cyan`)}pack(e){this.step(`pack`,e,`magenta`)}hook(e,t){this.step(`hook`,`${e}: ${t}`,`gray`)}timing(e,t){this.step(`timing`,`${e.padEnd(14)} ${t} ms`,`gray`)}done(e,t){this.info(`${I.green(`√`)} ${I.green(e)} ${t}`)}};function ke(e){return Array.isArray(e)&&e.length===3&&typeof e[0]==`number`&&typeof e[1]==`number`&&typeof e[2]==`number`}function Ae(e){return typeof e==`string`&&/^\d+\.\d+\.\d+$/.test(e)}function je(e){return e===3?Ae:ke}function Me(e,t){return e===3?`${t} must be SemVer string like "x.y.z" (format 3)`:`${t} must be [number, number, number] (format 2)`}const Ne=[e=>e.format_version===void 0?`format_version is required`:null,e=>e.header?null:`header is required`,e=>e.header&&!e.header.name?`header.name is required`:null,e=>e.header&&!e.header.uuid?`header.uuid is required`:null,e=>e.header?je(e.format_version)(e.header.version)?null:Me(e.format_version,`header.version`):null,e=>e.header?je(e.format_version)(e.header.min_engine_version)?null:Me(e.format_version,`header.min_engine_version`):null,e=>e.modules!==void 0&&!Array.isArray(e.modules)?`modules must be an array`:null,(e,t)=>{if(!Array.isArray(e.modules))return null;let n=e.modules.some(e=>e?.type===`resources`),r=[];return t===`rp`&&!n&&r.push(`RP manifest must have a resources module`),r.length>0?r:null},e=>{if(!Array.isArray(e.modules))return null;let t=je(e.format_version),n=[];for(let r=0;r<e.modules.length;r++){let i=e.modules[r];i&&i.version!==void 0&&i.version!==null&&!t(i.version)&&n.push(`modules[${r}] (uuid: ${i.uuid??`unknown`}): ${Me(e.format_version,`version`)}`)}return n.length>0?n:null},e=>e.dependencies!==void 0&&!Array.isArray(e.dependencies)?`dependencies must be an array`:null,e=>{if(!Array.isArray(e.dependencies))return null;let t=je(e.format_version),n=[];for(let r=0;r<e.dependencies.length;r++){let i=e.dependencies[r];if(!i){n.push(`dependencies[${r}] is invalid`);continue}`uuid`in i&&i.uuid&&!t(i.version)&&n.push(`dependencies[${r}] (uuid: ${i.uuid}): ${Me(e.format_version,`version`)}`),`module_name`in i&&i.module_name&&typeof i.version!=`string`&&n.push(`dependencies[${r}] (module_name: ${i.module_name}): version must be a string`)}return n.length>0?n:null},e=>e.capabilities===void 0?null:Array.isArray(e.capabilities)?e.capabilities.every(e=>typeof e==`string`)?null:`capabilities must be an array of strings`:`capabilities must be an array`,e=>e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)?`metadata must be an object`:null];function Pe(e,t){let n=[];for(let r of Ne){let i=r(e,t);i!==null&&(Array.isArray(i)?n.push(...i):n.push(i))}if(n.length>0)throw new F(`MANIFEST_INVALID`,`Manifest validation failed: ${n.join(`; `)}`)}function Fe(e){return!e||typeof e!=`object`||Array.isArray(e)?{}:{...e}}function Ie(e){return Array.isArray(e)?e:[]}function Le(e){if(!(e&&Object.keys(e).length===0))return e}var Re=class{static async read(e){if(!await P(e))return;let t=await n.readFile(e,`utf8`);try{return Fe(JSON.parse(t))}catch{throw new F(`MANIFEST_INVALID`,`Invalid JSON in manifest: ${e}`)}}static async write(e,t,n){Pe(t,n),await Ee(e,t)}};function ze(e){let t=/^(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)throw new F(`VERSION_INVALID`,`Manifest version requires x.y.z.`,{details:{version:e}});return[Number(t[1]),Number(t[2]),Number(t[3])]}function Be(e){return/^\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/.test(e)}function R(e,t){let n=e.split(/[^0-9A-Za-z]+/),r=t.split(/[^0-9A-Za-z]+/),i=Math.max(n.length,r.length);for(let e=0;e<i;e+=1){let t=n[e]??``,i=r[e]??``,a=/^\d+$/.test(t)?Number(t):NaN,o=/^\d+$/.test(i)?Number(i):NaN,s=Number.isNaN(a)||Number.isNaN(o)?t.localeCompare(i):a-o;if(s!==0)return s}return 0}function Ve(e){return e===`latest`||R(e,`1.21.120`)>=0}function He(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(e.trim());if(!t)return;let n=/(?:^|[.-])(\d+)\.(\d+)\.(\d+)(?:[.-]|$)/.exec(t[4]??``);return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),...n?{minecraftTarget:[Number(n[1]),Number(n[2]),Number(n[3])]}:{}}}function Ue(e,t){for(let n of[`major`,`minor`,`patch`])if(e[n]!==t[n])return e[n]-t[n];return 0}function We(e,t){let n=He(e);return n?t.split(`||`).some(e=>{let t=/(?:\^|~|>=|<=|>|<|=)?\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(e.trim()),r=t?He(t[1]):void 0;return!r||n.major!==r.major||Ue(n,r)<0?!1:r.minecraftTarget?n.minecraftTarget?R(n.minecraftTarget.join(`.`),r.minecraftTarget.join(`.`))>=0:!1:!0}):!1}function Ge(e){if(e===`stable`||e===`beta`||e===`preview`)throw new F(`DEPENDENCY_VERSION_INVALID`,`${e} must be resolved from npm registry before writing package.json.`,{details:{specifier:e}});if(Be(e))return e;throw new F(`DEPENDENCY_VERSION_INVALID`,`Unsupported dependency version: ${e}`,{details:{specifier:e}})}function Ke(e){return e.filter(e=>/^\d+\.\d+\.\d+$/.test(e)).sort(R)}function qe(e){return e.filter(e=>/(?:^|[-.])beta(?:[-.]|$)/i.test(e)).sort(R)}var Je=class{npm;logger;constructor(e,t){this.npm=e,this.logger=t}latestStable(e,t){let n=this.npm.distTag(t,`latest`);if(n&&/^\d+\.\d+\.\d+$/.test(n))return this.logger?.verbose(`Resolved ${e}@stable -> ${n}`),n;let r=Ke(this.npm.versions(t)).at(-1);if(!r)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest stable version for ${e}.`,{details:{package:e}});return this.logger?.verbose(`Resolved ${e}@stable -> ${r}`),r}latestBeta(e,t){let n=this.npm.distTag(t,`beta`);if(n)return this.logger?.verbose(`Resolved ${e}@beta -> ${n}`),n;let r=qe(this.npm.versions(t)).at(-1);if(!r)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest beta version for ${e}.`,{details:{package:e}});return this.logger?.verbose(`Resolved ${e}@beta -> ${r}`),r}betaForTarget(e,t,n){let r=t.replace(/\./g,`\\.`),i=RegExp(`beta[-.]${r}-stable`),a=this.npm.versions(n).filter(e=>i.test(e)).sort(R).at(-1);if(!a)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e}@beta for target ${t}.`,{details:{package:e,specifier:`beta`,target:t},suggestions:[`Use target: "latest"`,`Specify an exact version`,`Update BePack`,`Manually edit package.json and manifest.json`]});return this.logger?.verbose(`Resolved ${e}@beta for target ${t} -> ${a}`),a}inferStableFromBeta(e,t,n,r){let i=/^(\d+)\.(\d+)\.(\d+)-beta[.-]/.exec(n);if(!i)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot infer stable version from ${e}@${n}.`,{details:{package:e,beta:n,target:t}});let a=Number(i[1]),o=Number(i[2])-1,s=`${a}.${o}.${Number(i[3])}`;if(o<0||!r.versions?.[s])throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot confirm inferred stable version ${s} for ${e}.`,{details:{package:e,target:t,beta:n,inferredStable:s}});return s}};function Ye(e,t){return t===`latest`||Ve(t)?`beta`:/^(\d+\.\d+\.\d+-beta)/i.exec(e)?.[1]??e}function Xe(e,t,n){let r=qe(t).filter(e=>/^\d+\.\d+\.\d+-beta\.\d+\.\d+\.\d+/.test(e)).filter(e=>!/(?:rc|beta)\.\d+\.\d+\.\d+-preview\.\d+$/i.test(e)).at(-1);if(!r)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest beta version for ${e}.`,{details:{package:e}});return n?.verbose(`Resolved ${e}@beta -> ${r}`),r}function Ze(e){return e.filter(e=>/(?:rc|beta)\.\d+\.\d+\.\d+-preview\.\d+$/i.test(e)).sort(R)}function Qe(e,t,n){let r=Ze(t).at(-1);if(!r)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest preview version for ${e}.`,{details:{package:e}});return n?.verbose(`Resolved ${e}@preview -> ${r}`),r}function $e(e,t,n,r){let i=n.replace(/\./g,`\\.`),a=RegExp(`(?:rc|beta)\\.${i}-preview\\.\\d+$`),o=t.filter(e=>a.test(e)).sort(R).at(-1);if(!o)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e}@preview for target ${n}.`,{details:{package:e,specifier:`preview`,target:n},suggestions:[`Use target: "latest"`,`Specify an exact version`]});return r?.verbose(`Resolved ${e}@preview for target ${n} -> ${o}`),o}const et={name:`minecraft-script-api`,resolver:`minecraft-script-api`,match:e=>e.specifier===`stable`||e.specifier===`beta`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName),n=new Je(e.npm,e.logger);if(e.specifier===`stable`){e.logger?.verbose(`Resolving ${e.packageName}@stable for target ${e.target}`);let r=e.target===`latest`?n.latestStable(e.packageName,t):n.inferStableFromBeta(e.packageName,e.target,n.betaForTarget(e.packageName,e.target,t),t);return{packageVersion:r,manifestVersion:r}}if(e.specifier===`beta`){e.logger?.verbose(`Resolving ${e.packageName}@beta for target ${e.target}`);let r=e.target===`latest`?Xe(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:Ye(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?Qe(e.packageName,e.npm.versions(t),e.logger):$e(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}},tt={name:`minecraft-script-api-bp`,resolver:`minecraft-script-api-bp`,match:e=>e.specifier===`beta`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName),n=new Je(e.npm,e.logger);if(e.specifier===`beta`){e.logger?.verbose(`Resolving ${e.packageName}@beta for target ${e.target}`);let r=e.target===`latest`?Xe(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:Ye(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?Qe(e.packageName,e.npm.versions(t),e.logger):$e(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}},nt=/^\d+\.\d+\.\d+$/,rt=/^\d+\.\d+\.\d+-preview\.\d+$/,it={name:`minecraft-vanilla-data`,resolver:`minecraft-vanilla-data`,match:e=>e.specifier===`stable`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName);return e.specifier===`stable`?at(e,t):ot(e,t)}};function at(e,t){if(e.logger?.verbose(`Resolving ${e.packageName}@stable for target ${e.target}`),e.target===`latest`){let n=e.npm.distTag(t,`latest`);if(n&&nt.test(n))return e.logger?.verbose(`Resolved ${e.packageName}@stable -> ${n}`),{packageVersion:n};let r=e.npm.versions(t).filter(e=>nt.test(e)).sort(R).at(-1);if(!r)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest stable version for ${e.packageName}.`,{details:{package:e.packageName}});return e.logger?.verbose(`Resolved ${e.packageName}@stable -> ${r}`),{packageVersion:r}}if(t.versions?.[e.target])return e.logger?.verbose(`Resolved ${e.packageName}@stable for target ${e.target} -> ${e.target}`),{packageVersion:e.target};throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e.packageName}@stable for target ${e.target}. The target version does not exist in the registry.`,{details:{package:e.packageName,specifier:`stable`,target:e.target},suggestions:[`Use target: "latest"`,`Specify an exact version`]})}function ot(e,t){if(e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`),e.target===`latest`){let n=e.npm.versions(t).filter(e=>rt.test(e)).sort(R).at(-1);if(!n)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest preview version for ${e.packageName}.`,{details:{package:e.packageName}});return e.logger?.verbose(`Resolved ${e.packageName}@preview -> ${n}`),{packageVersion:n}}let n=e.target.replace(/\./g,`\\.`),r=RegExp(`^${n}-preview\\.\\d+$`),i=e.npm.versions(t).filter(e=>r.test(e)).sort(R).at(-1);if(!i)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e.packageName}@preview for target ${e.target}. No matching preview version found.`,{details:{package:e.packageName,specifier:`preview`,target:e.target},suggestions:[`Use target: "latest"`,`Specify an exact preview version`]});return e.logger?.verbose(`Resolved ${e.packageName}@preview for target ${e.target} -> ${i}`),{packageVersion:i}}const st={"@minecraft/common":{resolver:et,manifest:!0},"@minecraft/server":{resolver:et,manifest:!0},"@minecraft/server-ui":{resolver:et,manifest:!0},"@minecraft/server-net":{resolver:tt,manifest:!0},"@minecraft/server-admin":{resolver:tt,manifest:!0},"@minecraft/server-gametest":{resolver:tt,manifest:!0},"@minecraft/debug-utilities":{resolver:tt,manifest:!0},"@minecraft/diagnostics":{resolver:tt,manifest:!0},"@minecraft/server-graphics":{resolver:tt,manifest:!0},"@minecraft/server-editor":{resolver:tt,manifest:!0},"@minecraft/vanilla-data":{resolver:it,manifest:!1}};var ct=class e{static validateHeader(e,t){if(!e.header?.name||!e.header?.uuid)throw new F(`MANIFEST_INVALID`,`${t} manifest is missing header.name or header.uuid`);return{name:e.header.name,uuid:e.header.uuid,...e.header.description?{description:e.header.description}:{}}}static findScriptModuleUuid(t){for(let n of t.modules??[])if(n&&e.isScriptModule(n))return n.uuid}static findScriptModuleEntry(t){for(let n of t.modules??[])if(n&&e.isScriptModule(n))return n.entry}static findResourcesModuleUuid(t){for(let n of t.modules??[])if(n&&e.isResourcesModule(n))return n.uuid}static matchDependencies(e){let t={};for(let n of e.dependencies??[])if(`module_name`in n&&typeof n.module_name==`string`){let e=n.module_name;st[e]&&(t[e]=typeof n.version==`string`?n.version:String(n.version))}return t}static isScriptModule(e){return e?.type===`script`&&e?.language===`javascript`}static isResourcesModule(e){return e?.type===`resources`}};function lt(e,t){if(typeof e!=`string`||!e)throw new F(`MANIFEST_INVALID`,`${t} script module entry must be a non-empty string.`);let n=e.replace(/\\/g,`/`);if(s.posix.isAbsolute(n)||s.win32.isAbsolute(n))throw new F(`MANIFEST_INVALID`,`${t} script module entry must be a relative path, got absolute: "${e}".`);if(!n.endsWith(`.js`))throw new F(`MANIFEST_INVALID`,`${t} script module entry must end with .js, got: "${e}".`);let r=n.split(`/`);if(r.includes(`..`))throw new F(`MANIFEST_INVALID`,`${t} script module entry must not contain "..": "${e}".`);if(r.includes(``))throw new F(`MANIFEST_INVALID`,`${t} script module entry must not contain empty segments: "${e}".`);return n}function ut(e,t){let n=s.resolve(e,t),r=s.dirname(n),i=s.relative(e,r);if(i.startsWith(`..`)||s.isAbsolute(i))throw new F(`CONFIG_INVALID`,`Manifest path is outside the project directory: ${t}`);return i||`.`}async function dt(e,t){if(!t&&await P(e))throw new F(`CONFIG_INVALID`,`Config file already exists: ${e}. Use --force to overwrite.`,{suggestions:[`Pass --force to overwrite the existing file.`]})}async function ft(e,t,r,i=!1){return await dt(e,r),!i&&(await Ce(s.dirname(e)),await n.writeFile(e,t,`utf8`),!0)}const pt=[`.ts`,`.mts`,`.js`,`.mjs`];async function mt(e,t){let n=(t===`main`?[`main`]:[t,`main`]).flatMap(e=>pt.map(t=>`src/${e}${t}`));for(let t of n)if(await P(s.join(e,t))){let e=s.extname(t);return{entry:t,typecheckable:e===`.ts`||e===`.mts`,searched:n}}}function ht(e){return(e===`main`?[`main`]:[e,`main`]).map(e=>`src/${e}.{${pt.join(`,`).replace(/\./g,``)}}`).join(` or `)}function gt(e){return`export default ${JSON.stringify(e,null,4).replace(/\n( +)"([a-zA-Z_$][a-zA-Z0-9_$]*)": /g,`
9
+ $1$2: `)}\n`}function _t(e){if(e){if(Array.isArray(e))return e.join(`.`);if(typeof e==`string`)return e}}function vt(e,t){return e[0]===t[0]?e[1]===t[1]?e[2]-t[2]:e[1]-t[1]:e[0]-t[0]}function yt(e){if(Array.isArray(e)&&e.length===3)return e;if(typeof e==`string`){let t=e.split(`.`).map(Number);if(t.length===3&&t.every(e=>!Number.isNaN(e)))return t}}async function bt(e,t){let n=t.format??`ts`;if(![`ts`,`js`,`mjs`].includes(n))throw new F(`CONFIG_INVALID`,`init --format must be ts, js, or mjs.`);let r=s.join(e,`bepack.config.${n}`),i=!!t.force,a=!!t.dryRun,o=new L({silent:t.silent,verbose:t.verbose}),c=!!t.fromBp,l=!!t.fromRp,u,d,f,p=!1,m,h,g,_,v,y,b=[];if(c){let n=s.resolve(e,t.fromBp),r=await Re.read(n);if(!r)throw new F(`CONFIG_NOT_FOUND`,`BP manifest not found: ${t.fromBp}`);f??=r.format_version,r.format_version!==void 0&&r.header?.version!==void 0&&(r.format_version===3&&Array.isArray(r.header.version)||r.format_version===2&&typeof r.header.version==`string`)&&(p=!0);let i=ct.validateHeader(r,`BP`),a=ct.findScriptModuleUuid(r),o=ct.findScriptModuleEntry(r),c=_t(r.header?.version);c&&b.push(c),u={root:ut(e,n),uuid:i.uuid,...a?{moduleUuid:a}:{},...c?{version:c}:{},deps:ct.matchDependencies(r),...o?{scriptEntry:o}:{}},m=i.name,h=i.description,g=i.name,_=i.description}if(l){let n=s.resolve(e,t.fromRp),r=await Re.read(n);if(!r)throw new F(`CONFIG_NOT_FOUND`,`RP manifest not found: ${t.fromRp}`);f??=r.format_version,r.format_version!==void 0&&r.header?.version!==void 0&&(r.format_version===3&&Array.isArray(r.header.version)||r.format_version===2&&typeof r.header.version==`string`)&&(p=!0);let i=ct.validateHeader(r,`RP`),a=ct.findResourcesModuleUuid(r);if(!a)throw new F(`MANIFEST_INVALID`,`RP manifest is missing a resources module with uuid`);let o=_t(r.header?.version);o&&b.push(o),d={root:ut(e,n),uuid:i.uuid,moduleUuid:a,...o?{version:o}:{}},c||(m=i.name,h=i.description),v=i.name,y=i.description}let x;if(b.length===1)x=b[0];else if(b.length===2){let e=b[0],t=b[1];if(e===t)x=e;else{let n=yt(e),r=yt(t);x=n&&r?vt(n,r)>=0?e:t:e,o.warn(`BP version (${e}) and RP version (${t}) differ. Using ${x}.`)}}p&&(o.warn(`Detected format_version ${f} doesn't match the actual version format used in manifest. Falling back to format_version 2.`),f=2);let S={root:`.`,target:`latest`,pack:{outDir:`dist`}};f!==void 0&&(S.manifestFormat=f),x&&(S.version=x),m&&(S.name=m),h&&(S.description=h);let C={};if(u){let t={root:u.root,uuid:u.uuid};if(u.moduleUuid){if(t.moduleUuid=u.moduleUuid,u.scriptEntry){let n=lt(u.scriptEntry,`BP`),r=s.posix.dirname(n),i=s.posix.basename(n,`.js`);if(r===`.`)throw new F(`MANIFEST_INVALID`,`BP manifest script entry "${u.scriptEntry}" is at the BP root. BePack cannot safely manage root-level script output because the output directory would need to be emptied on each build, which would delete the entire BP root. Please add a subdirectory prefix to the script module entry in your manifest.json (e.g. "scripts/main.js"), then rerun init.`);let a=await mt(e,i);if(a){let n=await P(s.join(e,`tsconfig.json`)),i=a.typecheckable&&n;t.compile={entry:a.entry,scriptOutputDir:r,...i?{}:{typecheck:!1}},i||o.warn(`Detected script entry "${u.scriptEntry}" with source "${a.entry}", but ${a.typecheckable?`tsconfig.json is missing`:`the source is JavaScript`}. Generated config sets compile.typecheck: false.`+(a.typecheckable?` Add tsconfig.json and remove that flag to enable typechecking.`:``))}else o.warn(`BP manifest declares script entry "${u.scriptEntry}" but no matching source file exists (looked for ${ht(i)}). Leaving packs.bp.compile unset: the existing "${r}" folder is copied/packed as-is. Set packs.bp.compile manually once you add sources.`)}else o.warn("BP manifest has a script module but no `entry` field, so the script output directory cannot be derived. Leaving packs.bp.compile unset; add it manually to compile TypeScript into the pack.")}g&&(t.name=g),_&&(t.description=_),Object.keys(u.deps).length>0&&(t.dependencies={...u.deps}),C.bp=t}if(d){let e={root:d.root,uuid:d.uuid,moduleUuid:d.moduleUuid};v&&(e.name=v),y&&(e.description=y),C.rp=e}S.packs=C,process.platform===`win32`&&(S.copy={defaultTarget:`win`});let w=await ft(r,gt(S),i,a);return a&&o.info(`init dry-run: would create ${r}`),{ok:!0,command:`init`,dryRun:a,filesCreated:+!!w,files:[r]}}function xt(){return gt({root:`.`,name:`example-addon`,version:`1.0.0`,target:`latest`,packs:{bp:{root:`bp`,uuid:u(),moduleUuid:u(),compile:{entry:`src/main.ts`},dependencies:{"@minecraft/server":`stable`}}},pack:{outDir:`dist`}})}async function St(e){let t=s.resolve(e.cwd??process.cwd());if(e.fromBp||e.fromRp)return await bt(t,e);let n=e.format??`ts`;if(![`ts`,`js`,`mjs`].includes(n))throw new F(`CONFIG_INVALID`,`init --format must be ts, js, or mjs.`);let r=s.join(t,`bepack.config.${n}`),i=!!e.dryRun,a=await ft(r,xt(),!!e.force,i);return i&&new L({silent:e.silent,verbose:e.verbose}).info(`init dry-run: would create ${r}`),{ok:!0,command:`init`,dryRun:i,filesCreated:+!!a,files:[r]}}const Ct=[`bepack.config.ts`,`bepack.config.mjs`,`bepack.config.js`],z={root:`.`,configured:{root:!1,packOutDir:!1},name:`minecraft-addon`,version:`1.0.0`,description:``,replace:{values:{},builtins:{VERSION:!1,NAME:!1,UUID:!1,DESCRIPTION:!1}},target:`latest`,plugins:[],install:{registry:`https://registry.npmjs.org/`,saveTo:`dependencies`,packageManager:`auto`,runPackageManager:!0,updatePackageJson:!0,updateManifest:!0,dependencyCatalog:{},dependencyResolvers:[]},build:{copy:!1,timing:!1},dev:{copy:!1},copy:{defaultTarget:``,targets:{}},pack:{name:`{name}-{version}`,outDir:`dist`},hooks:{}},wt={dev:!0,build:!1,file:`node_modules/.cache/bepack/tsconfig.tsbuildinfo`},Tt={keepLooseFiles:!1,keepLoose:[],exclude:[],minifyJson:!0,packOptimizationVersion:`0.1.0`,allowUnsupportedTarget:!1},Et={entry:`src/main.ts`,define:{},tsconfig:`tsconfig.json`,typecheck:!0,typecheckArgs:[],preserveModules:!0,external:[/^@minecraft\/server.*/],useNpx:!1,minify:!1,cache:wt,scriptOutputDir:`scripts`},Dt=[`world`,`global`,`any`];function Ot(e){let t=[];return e.packs.bp&&t.push({type:`bp`,root:e.packs.bp.root,uuid:e.packs.bp.uuid,...e.packs.bp.moduleUuid===void 0?{}:{moduleUuid:e.packs.bp.moduleUuid},name:e.packs.bp.name,include:e.packs.bp.include}),e.packs.rp&&t.push({type:`rp`,root:e.packs.rp.root,uuid:e.packs.rp.uuid,moduleUuid:e.packs.rp.moduleUuid,name:e.packs.rp.name,include:e.packs.rp.include}),t}const kt=[`scripts`,`manifest.json`,`animation_controllers`,`animations`,`biomes`,`blocks`,`cameras`,`dialogue`,`entities`,`functions`,`items`,`loot_tables`,`pack_icon.png`,`recipes`,`shapes`,`spawn_rules`,`structures`,`texts`,`trading`,`feature_rules`,`features`,`worldgen`],At=[];function jt(e,t){return s.isAbsolute(t)?t:s.join(e,t)}function B(e){return e.replace(/\\/g,`/`)}function V(e,t){return jt(e,t.root)}function H(e,t,n){return n===`bp`?t.packs.bp?jt(e,t.packs.bp.root):void 0:t.packs.rp?jt(e,t.packs.rp.root):void 0}function Mt(e,t){let n=H(V(e,t),t,`bp`);if(!n)throw Error(`packs.bp is not configured`);return n}function Nt(e,t){let n=H(V(e,t),t,`rp`);if(!n)throw Error(`packs.rp is not configured`);return n}function Pt(e){return!!e.packs.bp?.compile}function U(e,t){if(t.packs.bp?.compile)return jt(V(e,t),t.packs.bp.compile.entry)}function Ft(e,t){if(!t.packs.bp)return;let n=t.packs.bp.compile?.scriptOutputDir??`scripts`;return s.join(Mt(e,t),n)}function It(e,t){let n=Ft(e,t);if(!n)return;if(!t.packs.bp?.compile)return s.join(n,`main.js`);let r=s.basename(t.packs.bp.compile.entry,s.extname(t.packs.bp.compile.entry));return s.join(n,`${r}.js`)}function Lt(e,t){let n=s.relative(e,t);return n===``||!n.startsWith(`..${s.sep}`)&&n!==`..`&&!s.isAbsolute(n)}function Rt(e,t,n){if(!t||t===`.`)throw new F(`CONFIG_INVALID`,`compile.scriptOutputDir must be a non-empty relative path strictly inside the BP root. Got: "${t}". This directory will be emptied during build.`);let r=t.replace(/\\/g,`/`);if(s.posix.isAbsolute(r)||s.win32.isAbsolute(r))throw new F(`CONFIG_INVALID`,`compile.scriptOutputDir must be a relative path, not absolute. Got: "${t}". This directory will be emptied during build.`);let i=s.posix.normalize(r);if(i.split(`/`).includes(`..`))throw new F(`CONFIG_INVALID`,`compile.scriptOutputDir must not contain ".." (path escape). Got: "${t}" resolves outside the BP root. This directory will be emptied during build.`);let a=s.resolve(e,i),o=s.relative(e,a);if(!o||o.startsWith(`..`)||s.isAbsolute(o))throw new F(`CONFIG_INVALID`,`compile.scriptOutputDir must be a directory strictly inside the BP root. Value: "${t}", resolved: "${a}". This directory will be emptied during build and must not be the BP root or a path outside it.`);if(n&&Lt(a,n))throw new F(`CONFIG_INVALID`,`compile.scriptOutputDir "${t}" dangerously overlaps with the source entry directory. The output directory will be emptied during build and would delete source files.`);return B(o)}function zt(e,t,n,r=[]){let a=s.resolve(e),o=s.resolve(t),c=[o,...r.map(e=>s.resolve(e))];for(let t of c)if(Lt(a,t))throw new F(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" would overwrite a protected path ("${t}"). Refusing to empty this directory.`);try{if(!i(a).isDirectory())throw new F(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" is not a directory. Refusing to empty a non-directory path.`)}catch(e){if(e?.code!==`ENOENT`)throw e}let l=s.relative(o,a);if(!l||l.startsWith(`..`)||s.isAbsolute(l))throw new F(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" is not inside the BP root "${t}". Refusing to empty this directory.`)}function Bt(e){let t=[e.packs.bp?.compile?.scriptOutputDir??`scripts`,...kt.filter(e=>e!==`scripts`)],n=e.packs.bp?.include??[],r=[...t,...n],i=/* @__PURE__ */ new Set;return r.filter(e=>!i.has(e)&&(i.add(e),!0))}function Vt(e,t){if(t.packs.bp)return s.join(Mt(e,t),`manifest.json`)}function Ht(e,t){if(t.packs.rp)return s.join(Nt(e,t),`manifest.json`)}function Ut(e,t){return jt(V(e,t),t.pack.outDir)}const Wt=f()!==`win32`;function Gt(e){let t=/* @__PURE__ */ new Set;return e.filter(e=>{let n=B(s.resolve(e)),r=Wt?n:n.toLowerCase();return!t.has(r)&&(t.add(r),!0)})}const Kt={VERSION:e=>e.version,NAME:e=>e.name,UUID:e=>e.packs.bp?.uuid??``,DESCRIPTION:e=>e.packs.bp?.description??e.description??``};function qt(e){return Object.fromEntries(Object.entries(e.replace.values).map(([t,n])=>[t,typeof n==`function`?n(e):n]))}function Jt(e){let t=qt(e),n=Object.fromEntries(Object.entries(e.replace.builtins).filter(([,e])=>e).map(([t])=>[`**${t}**`,Kt[t](e)])),r={...t,...n};return Object.keys(r).length===0?[]:[p(r,{delimiters:[``,``]})]}function Yt(e){return{values:e?.values??{},builtins:{VERSION:e?.builtins?.VERSION??!1,NAME:e?.builtins?.NAME??!1,UUID:e?.builtins?.UUID??!1,DESCRIPTION:e?.builtins?.DESCRIPTION??!1}}}function Xt(e){let t={...e??{}};for(let[e,n]of Object.entries(t))try{Function(`return (${n});`)}catch{throw new F(`CONFIG_INVALID`,`packs.bp.compile.define["${e}"] is not a valid JavaScript expression: ${n}. Define values must be expression strings, e.g. JSON.stringify("server") or "true".`,{details:{defineKey:e,defineValue:n}})}return t}function Zt(e){return Object.keys(e).length>0?{transform:{define:e}}:void 0}const Qt=`tsc --noEmit`;function $t(e){let t=[],n=``,r,i=!1;for(let a=0;a<e.length;a+=1){let o=e[a];if(r){o===r?r=void 0:o===`\\`&&e[a+1]===r?(a+=1,n+=r):n+=o;continue}if(o===`"`||o===`'`){r=o,i=!0;continue}if(o===`\\`&&(e[a+1]===`"`||e[a+1]===`'`)){a+=1,n+=e[a],i=!0;continue}if(/\s/.test(o)){i&&=(t.push(n),n=``,!1);continue}n+=o,i=!0}if(r)throw new F(`CONFIG_INVALID`,`Unterminated ${r===`"`?`double`:`single`} quote in typecheck command: ${e}`);return i&&t.push(n),t}function en(e,t=[],n={}){let r=typeof e==`string`?e.trim():``;if(r===``){let e=[...$t(Qt)],r=e.shift(),i=[...tn(e,n),...t];return n.useNpx?{command:`npx`,args:[r,...i],label:`npx tsc --noEmit`,isDefault:!0}:{command:r,args:i,label:Qt,isDefault:!0}}let i=$t(r),a=i[0];if(!a)throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck.command must be a non-empty command line, got: ${JSON.stringify(e)}`);return{command:a,args:[...i.slice(1),...t],label:r,isDefault:!1}}function tn(e,t){let n=[...e];return t.tsconfigPath&&n.push(`--project`,t.tsconfigPath),t.incremental&&t.tsBuildInfoFile&&n.push(`--incremental`,`--tsBuildInfoFile`,t.tsBuildInfoFile),n}function nn(e){return[e.command,...e.args].map(e=>/\s/.test(e)?JSON.stringify(e):e).join(` `)}function rn(e,t){if(e===void 0||typeof e==`boolean`)return{typecheck:e??t.typecheck,...t.typecheckCommand===void 0?{}:{typecheckCommand:t.typecheckCommand},typecheckArgs:t.typecheckArgs??[]};if(typeof e!=`object`||!e||Array.isArray(e))throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck must be a boolean or an object { enabled?, command?, args? }, got: ${cn(e)}.`);sn(e);let{enabled:n,command:r,args:i}=e;if(n!==void 0&&typeof n!=`boolean`)throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck.enabled must be a boolean, got: ${cn(n)}.`);if(r!==void 0&&typeof r!=`string`)throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck.command must be a string, got: ${cn(r)}.`);if(typeof r==`string`&&r.trim()===``)throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck.command must be a non-empty command line, got: ${cn(r)}.`);let a=an(i,`packs.bp.compile.typecheck.args`);return{typecheck:n??t.typecheck,...r===void 0?t.typecheckCommand===void 0?{}:{typecheckCommand:t.typecheckCommand}:{typecheckCommand:r},typecheckArgs:a??t.typecheckArgs??[]}}function an(e,t){if(e!==void 0){if(!Array.isArray(e))throw new F(`CONFIG_INVALID`,`${t} must be an array of strings, got: ${cn(e)}.`);return e.map(e=>{if(typeof e!=`string`)throw new F(`CONFIG_INVALID`,`${t} entries must be strings, got: ${cn(e)}.`);return e})}}function on(e,t){if(e!==void 0){if(typeof e!=`string`||e.trim()===``)throw new F(`CONFIG_INVALID`,`${t} must be a non-empty command line string, got: ${cn(e)}.`);return e.trim()}}function sn(e){let t=e;if(t.typechecker!==void 0)throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck.typechecker was replaced by packs.bp.compile.typecheck.command: write the full command line instead, e.g. { command: "bun check" }, got: ${cn(t.typechecker)}.`)}function cn(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e==`object`?`object`:typeof e==`string`?JSON.stringify(e):String(e)}const ln=[et,tt,it,{name:`exact-version`,match:e=>Be(e.specifier),resolve(e){return e.logger?.verbose(`Using exact ${e.packageName}@${e.specifier}`),{packageVersion:Ge(e.specifier),manifestVersion:e.specifier}}}];var un=class e{resolvers;pluginNames=/* @__PURE__ */ new Map;constructor(e,t=[]){this.resolvers=e;for(let e of t)for(let t of e.install?.dependencyResolvers??[])this.pluginNames.set(t,e.name)}static fromConfig(t,n=[]){return new e([...t,...ln],n)}resolverMatchesCatalog(e,t){let n=e.entry.resolver;if(!n)return!0;let r=typeof n==`string`?n:n.name;return t.resolver===void 0||t.resolver===r}find(e){let t;for(let n of this.resolvers)if(this.resolverMatchesCatalog(e,n))try{if(n.match(e)){t=n;break}}catch(e){let t=this.pluginNames.get(n);throw t?new F(`PLUGIN_FAILED`,`Plugin ${t} resolver ${n.name} match failed: ${e instanceof Error?e.message:String(e)}`):e}if(!t)throw new F(`DEPENDENCY_VERSION_INVALID`,`${e.packageName} dependency version is invalid: ${e.specifier}`,{details:{package:e.packageName,specifier:e.specifier,resolver:e.entry.resolver}});return e.logger?.verbose(`Resolving ${e.packageName}@${e.specifier} with ${t.name}`),t}async resolve(e){let t=this.find(e);try{return await t.resolve(e)}catch(e){let n=this.pluginNames.get(t);throw n?new F(`PLUGIN_FAILED`,`Plugin ${n} resolver ${t.name} failed: ${e instanceof Error?e.message:String(e)}`):e}}};const dn=`sapi-pro`,fn=[`@minecraft/server`,`@minecraft/server-ui`];function pn(e){return/(?:beta|preview|alpha|rc)/i.test(e)}function mn(e){return pn(e)?`beta`:`stable`}function hn(e){let t=/^(\d+)\.(\d+)\./.exec(e);return!!t&&(Number(t[1])>0||Number(t[2])>=4)}function gn(e){return{...e.dependencies??{},...e.peerDependencies??{}}}async function _n(e,t,n,r){let i=e.config.packs.bp?.dependencies??{},a={...st,...e.config.install.dependencyCatalog},o=un.fromConfig(e.config.install.dependencyResolvers.filter(e=>e!==yn),e.config.plugins);for(let[s,c]of Object.entries(t)){if(!s.startsWith(`@minecraft/`))continue;let t=i[s],l=a[s];if(!t||!l)return r.add(s),!1;let u;if(n.has(s)?u=n.get(s):(u=await o.resolve({packageName:s,specifier:t,target:e.target,entry:l,config:e.config,npm:e.npm,...e.logger?{logger:e.logger}:{}}),n.set(s,u)),!u||fn.includes(s)&&pn(c)!==pn(u.packageVersion)||!We(u.packageVersion,c))return!1}return!0}function vn(e,t){if(t!==`stable`&&t!==`beta`){let n=e[t];return n?[[t,n]]:[]}return Object.entries(e).filter(([e,n])=>{if(!hn(e))return!1;let r=gn(n);return Object.keys(r).length===0?!1:t===`stable`?/-stable(?:\.\d+)?$/i.test(e):/^\d+\.\d+\.\d+$/.test(e)}).sort(([e],[t])=>R(e,t)).reverse()}const yn={name:`sapi-pro`,resolver:`sapi-pro`,match:e=>e.specifier===`stable`||e.specifier===`beta`||/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(e.specifier),async resolve(e){let t=await e.npm.metadata(dn),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set;for(let[i,a]of vn(t.versions??{},e.specifier))if(await _n(e,gn(a),n,r))return/^0\.3\./.test(i)&&e.logger?.warn(`sapi-pro@${i} uses legacy metadata; compatibility is best-effort only.`),{packageVersion:i,manifestVersion:null};throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot find a compatible ${dn}@${e.specifier} for target ${e.target}.${r.size>0?` Missing explicit dependencies: ${[...r].join(`, `)}.`:``}`,{details:{package:dn,specifier:e.specifier,target:e.target},suggestions:[`Explicitly declare the @minecraft packages required by sapi-pro.`,`Use a compatible target or specify an exact sapi-pro version.`]})}};function bn(){return{name:`sapi-pro`,apiVersion:1,description:`Resolve sapi-pro versions compatible with BePack Script API dependencies.`,configResolved:({config:e})=>{let t=e.packs.bp?.dependencies??{},n=t[dn];if(!n)return;let r=fn.filter(e=>!t[e]);if(r.length>0)throw Error(`sapi-pro requires explicit dependencies: ${r.join(`, `)}.`);if(n===`stable`||n===`beta`)for(let e of fn){let r=t[e];if(mn(r)!==n)throw Error(`sapi-pro ${n} requires ${e} to use ${n}, received ${r}.`)}},install:{dependencyCatalog:{[dn]:{resolver:`sapi-pro`,manifest:!1}},dependencyResolvers:[yn]}}}const xn={"sapi-pro":bn};function W(e){return e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):{}}function Sn(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e==`function`?`function`:typeof e==`object`?`object`:typeof e==`string`?JSON.stringify(e):String(e)}function Cn(e,t){let n={};(e.packs?.bp||t.packs?.bp)&&(n.bp={...e.packs?.bp??{},...W(t.packs?.bp)}),(e.packs?.rp||t.packs?.rp)&&(n.rp={...e.packs?.rp??{},...W(t.packs?.rp)});let r={...e.copy?.targets??{},...W(t.copy?.targets)},i=W(t);return{...e,...i,...t.plugins!==void 0||e.plugins!==void 0?{plugins:t.plugins??e.plugins}:{},packs:n,install:{...e.install,...W(t.install)},build:{...e.build,...W(t.build)},dev:{...e.dev,...W(t.dev)},copy:{...e.copy,...W(t.copy),targets:r},pack:{...e.pack,...W(t.pack)},hooks:{...e.hooks,...W(t.hooks)}}}function wn(e){let t=(e??[]).map(e=>{if(typeof e!=`string`)return e;let t=xn[e];if(!t)throw new F(`CONFIG_INVALID`,`Unknown built-in plugin: ${e}.`);return t()}),n=/* @__PURE__ */ new Set;for(let e of t){if(!e?.name||e.name.trim()===``)throw new F(`CONFIG_INVALID`,`Every plugin must have a non-empty name.`);if(n.has(e.name))throw new F(`CONFIG_INVALID`,`Plugin name is duplicated: ${e.name}.`);if(e.apiVersion!==void 0&&e.apiVersion!==1)throw new F(`CONFIG_INVALID`,`Plugin ${e.name} requires unsupported BePack plugin API version ${e.apiVersion}.`);if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new F(`CONFIG_INVALID`,`Plugin ${e.name} priority must be a finite number.`);n.add(e.name)}return t.sort((e,t)=>(t.priority??0)-(e.priority??0))}function Tn(e,t){let n=/* @__PURE__ */ new Set;for(let r of[...e.map(e=>e.hooks),t])for(let e of Object.keys(r??{}))n.add(e);return Object.fromEntries([...n].map(n=>{let r=[...e.map(e=>({plugin:e,hook:e.hooks?.[n]})).filter(e=>e.hook!==void 0),...t?.[n]?[{hook:t[n]}]:[]];return[n,async(...e)=>{let t;for(let i of r)try{t=await i.hook(...e)}catch(e){let t=`plugin`in i?i.plugin:void 0;throw t?new F(`PLUGIN_FAILED`,`Plugin ${t.name} ${String(n)} hook failed: ${e instanceof Error?e.message:String(e)}`):e}return t}]}))}function En(e,t){let n={},r=/* @__PURE__ */ new Map,i=[];for(let t of e)for(let[e,a]of Object.entries(t.install?.dependencyCatalog??{})){let o=r.get(e);if(o){i.push(`dependency catalog ${e}: plugin ${o} takes precedence over plugin ${t.name}`);continue}n[e]=a,r.set(e,t.name)}for(let[e,a]of Object.entries(t)){let t=r.get(e);t&&i.push(`dependency catalog ${e}: project config overrides plugin ${t}`),n[e]=a}return{catalog:n,diagnostics:i}}function Dn(e,t,n){let r=Et,i=e?.scriptOutputDir??r.scriptOutputDir,a=s.resolve(n,e?.entry??r.entry),o=Rt(t,i,s.dirname(a)),c=on(e?.typecheckCommand,`packs.bp.compile.typecheckCommand`)??r.typecheckCommand,l=an(e?.typecheckArgs,`packs.bp.compile.typecheckArgs`),u=rn(e?.typecheck,{typecheck:r.typecheck,...c===void 0?{}:{typecheckCommand:c},...l===void 0?{}:{typecheckArgs:l}});return{entry:e?.entry??r.entry,define:Xt(e?.define),tsconfig:e?.tsconfig??r.tsconfig,typecheck:u.typecheck,typecheckArgs:u.typecheckArgs,...u.typecheckCommand===void 0?{}:{typecheckCommand:u.typecheckCommand},preserveModules:e?.preserveModules??r.preserveModules,external:e?.external??r.external,useNpx:e?.useNpx??r.useNpx,minify:e?.minify??r.minify,cache:p(e?.cache),scriptOutputDir:o,...e?.rolldown===void 0?{}:{rolldown:d(e.rolldown)},...e?.rolldownConfig===void 0?{}:{rolldownConfig:f(e.rolldownConfig)}};function d(e){if(typeof e==`function`||e&&typeof e==`object`&&!Array.isArray(e))return e;throw new F(`CONFIG_INVALID`,`packs.bp.compile.rolldown must be a rolldown options object or a function (options, context) => options, got: ${Sn(e)}.`)}function f(e){if(typeof e!=`string`||e.trim()===``)throw new F(`CONFIG_INVALID`,`packs.bp.compile.rolldownConfig must be a non-empty path string, got: ${Sn(e)}.`);return e}function p(e){let t=wt;return{dev:e?.dev??t.dev,build:e?.build??t.build,file:e?.file??t.file}}}function On(e){if(e===void 0||e===!1)return;let t=e===!0?{}:e;if(typeof t!=`object`||!t||Array.isArray(t))throw new F(`CONFIG_INVALID`,`pack.optimize must be a boolean or an options object, got: ${Sn(e)}.`);let n=t.packOptimizationVersion;if(n!==void 0&&(typeof n!=`string`||n.trim()===``))throw new F(`CONFIG_INVALID`,`pack.optimize.packOptimizationVersion must be a non-empty string, got: ${Sn(n)}.`);return{keepLooseFiles:t.keepLooseFiles??Tt.keepLooseFiles,keepLoose:t.keepLoose!==!1&&(t.keepLoose??[]).map(kn),exclude:(t.exclude??[]).map(kn),minifyJson:t.minifyJson??Tt.minifyJson,packOptimizationVersion:n??Tt.packOptimizationVersion,allowUnsupportedTarget:t.allowUnsupportedTarget??Tt.allowUnsupportedTarget}}function kn(e){let t=String(e).replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``);if(!t||t.includes(`/`)||t.includes(`..`)||s.posix.isAbsolute(t))throw new F(`CONFIG_INVALID`,`pack.optimize.exclude entries must be top-level folder names (no path separators, no ".."), got: ${Sn(e)}.`);return t}function An(e){let t=e?.merge??`preserve`;if(t!==`preserve`&&t!==`clean`)throw new F(`CONFIG_INVALID`,`manifest.merge must be "preserve" or "clean", got: ${String(e?.merge)}.`);let n=e?.minEngineVersion;if(n!==void 0&&!/^\d+\.\d+\.\d+$/.test(n))throw new F(`CONFIG_INVALID`,`manifest.minEngineVersion must be a SemVer string like "1.21.0", got: ${n}.`);return{merge:t,...n===void 0?{}:{minEngineVersion:n},extraDependencies:e?.extraDependencies??[],extraModules:e?.extraModules??[],extraHeader:e?.extraHeader??{}}}function jn(e,t={},n=process.cwd()){let r=Cn(e,t),i=wn(r.plugins),a=r.target??z.target;if(a===`stable`||a===`beta`)throw new F(`TARGET_INVALID`,`target must be a Minecraft game version or latest, not a Script API channel.`,{details:{target:a}});let o=!!r.packs?.bp,c=!!r.packs?.rp;if(!o&&!c)throw new F(`CONFIG_INVALID`,`At least one pack (packs.bp or packs.rp) is required.`);if(!r.name||r.name.trim()===``)throw new F(`CONFIG_INVALID`,`name is required.`);let l=r.name,u=r.version??z.version,d=r.description,f=r.packs,p=f.bp?.compile,m=f.bp,h=f.rp;if(m){if(!m.uuid)throw new F(`CONFIG_INVALID`,`packs.bp.uuid is required.`);if(m.compile&&!m.moduleUuid)throw new F(`CONFIG_INVALID`,`packs.bp.moduleUuid is required when packs.bp.compile is configured.`);if(m.root===void 0)throw new F(`CONFIG_INVALID`,`packs.bp.root is required. Set the behavior pack directory in bepack.config.ts.`);if(p?.define){let e=Object.keys(r.replace?.values??{}),t=Object.keys(p.define),n=e.filter(e=>t.includes(e));if(n.length>0)throw new F(`CONFIG_INVALID`,`Config conflict: ${n.map(e=>`"${e}"`).join(`, `)} is configured in both replace.values and packs.bp.compile.define. Use only one mechanism per key.`,{details:{overlap:n}})}}let g=s.resolve(n,r.root??`.`),_=m?s.resolve(g,m.root):void 0;if(h){if(!h.uuid||!h.moduleUuid)throw new F(`CONFIG_INVALID`,`packs.rp.uuid and packs.rp.moduleUuid are required.`);if(h.root===void 0)throw new F(`CONFIG_INVALID`,`packs.rp.root is required when packs.rp is configured.`);if(h.packScope!==void 0&&!Dt.includes(h.packScope))throw new F(`CONFIG_INVALID`,`packs.rp.packScope must be one of ${Dt.map(e=>`"${e}"`).join(`, `)}.`,{details:{packScope:h.packScope}})}let v=m?.description??d,y=h?.description??d,{catalog:b,diagnostics:x}=En(i,r.install?.dependencyCatalog??{}),S=i.flatMap(e=>e.install?.dependencyResolvers??[]),C=On(r.pack?.optimize),w=On(r.copy?.optimize);return{root:r.root??z.root,configured:{root:r.root!==void 0,packOutDir:r.pack?.outDir!==void 0},name:l,version:u,...d===void 0?{}:{description:d},replace:Yt(r.replace),target:a,plugins:i,...x.length>0?{pluginDiagnostics:x}:{},...r.manifestFormat===void 0?{}:{manifestFormat:r.manifestFormat},packs:{...m?{bp:{root:m.root,uuid:m.uuid,...m.moduleUuid===void 0?{}:{moduleUuid:m.moduleUuid},name:m.name??l,...v===void 0?{}:{description:v},...p&&_?{compile:Dn(p,_,g)}:{},manifest:An(m.manifest),dependencies:m.dependencies??{},...m.achievement===void 0?{}:{achievement:m.achievement},include:m.include??[]}}:{},...h?{rp:{root:h.root,uuid:h.uuid,moduleUuid:h.moduleUuid,name:h.name??l,...y===void 0?{}:{description:y},manifest:An(h.manifest),...h.pbr===void 0?{}:{pbr:h.pbr},...h.packScope===void 0?{}:{packScope:h.packScope},include:h.include??[]}}:{}},install:{registry:r.install?.registry??z.install.registry,saveTo:r.install?.saveTo??z.install.saveTo,packageManager:r.install?.packageManager??z.install.packageManager,runPackageManager:r.install?.runPackageManager??z.install.runPackageManager,updatePackageJson:r.install?.updatePackageJson??z.install.updatePackageJson,updateManifest:r.install?.updateManifest??z.install.updateManifest,dependencyCatalog:b,dependencyResolvers:[...S,...r.install?.dependencyResolvers??[]]},build:{copy:r.build?.copy??z.build.copy,timing:r.build?.timing??z.build.timing},dev:{copy:r.dev?.copy??z.dev.copy,...r.dev?.watch?{watch:r.dev.watch}:{}},copy:{defaultTarget:r.copy?.defaultTarget??z.copy.defaultTarget,...r.copy?.name?{name:r.copy.name}:{},...r.copy?.include?{include:r.copy.include}:{},targets:r.copy?.targets??{},...w?{optimize:w}:{}},pack:{name:r.pack?.name??z.pack.name,outDir:r.pack?.outDir??z.pack.outDir,...C?{optimize:C}:{}},hooks:Tn(i,r.hooks)}}async function Mn(e,t){if(t){let r=jt(e,t);return await n.access(r).catch(()=>{throw new F(`CONFIG_NOT_FOUND`,`Config not found: ${t}`,{details:{configPath:t}})}),r}for(let t of Ct){let r=s.join(e,t);try{return await n.access(r),r}catch{}}throw new F(`CONFIG_NOT_FOUND`,`No bepack.config.ts, bepack.config.mjs, or bepack.config.js found.`,{details:{cwd:e}})}async function Nn(e){try{if(e.endsWith(`.ts`))try{return await import(`${o(e).href}?t=${Date.now()}`)}catch{let t=Pn(await n.readFile(e,`utf8`));return await import(`data:text/javascript;base64,${Buffer.from(t,`utf8`).toString(`base64`)}`)}return await import(`${o(e).href}?t=${Date.now()}`)}catch(t){throw new F(`CONFIG_INVALID`,`Failed to load config: ${t instanceof Error?t.message:String(t)}`,{details:{file:e},suggestions:[`Use bepack.config.mjs/js for complex config logic.`,`Keep bepack.config.ts free of TypeScript-only runtime syntax.`]})}}function Pn(e){return e.replace(/^\s*import\s+type\s+[^;]+;\s*$/gm,``).replace(/\s+satisfies\s+[A-Za-z_$][\w$<>,\s.[\]|&{}]*/g,``).replace(/\((\s*[A-Za-z_$][\w$]*)\s*:\s*[^)=]+?\)\s*=>/g,`($1) =>`)}async function Fn(e,t){for(let n of e.plugins??[])if(n.configResolved)try{await n.configResolved({cwd:t,config:e})}catch(e){throw new F(`PLUGIN_FAILED`,`Plugin ${n.name} configResolved hook failed: ${e instanceof Error?e.message:String(e)}`)}}async function In(e){let t=s.resolve(e.cwd),n=await Mn(t,e.configPath),r=await Nn(n);if(r.default===void 0)throw new F(`CONFIG_INVALID`,`Config must use default export.`,{details:{file:n}});let i=jn(r.default,e.overrides,t);return await Fn(i,t),{config:i,path:n,cwd:t}}function Ln(e){return{...st,...e.install.dependencyCatalog}}function Rn(e,t){let n=e[t];if(!n)throw new F(`UNSUPPORTED_DEPENDENCY`,`${t} is not a managed dependency. Add it to install.dependencyCatalog or remove it from packs.bp.dependencies.`,{details:{package:t}});return n}function zn(e,t){e?.install?e.install(t):e?.info(`[Install] ${t}`)}var Bn=class{registry;logger;cache=/* @__PURE__ */ new Map;constructor(e,t){this.registry=e,this.logger=t}async metadata(e){let t=this.packageUrl(e),n=this.cache.get(t);if(n)return this.logger?.verbose(`Using cached metadata for ${e}`),n;zn(this.logger,`fetching ${e} metadata from ${this.registry}`);let r=await fetch(t);if(!r.ok)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot fetch ${e} versions from registry.`,{details:{package:e,registry:this.registry,status:r.status}});let i=await r.json();return this.cache.set(t,i),this.logger?.verbose(`Fetched ${e} metadata (${Object.keys(i.versions??{}).length} versions)`),i}versions(e){return Object.keys(e.versions??{})}async versionsOf(e){return this.versions(await this.metadata(e))}distTag(e,t){let n=e[`dist-tags`]?.[t];return n&&e.versions?.[n]?n:void 0}packageUrl(e){return`${this.registry.replace(/\/$/,``)}/${encodeURIComponent(e).replace(/^%40/,`@`)}`}};function Vn(e){return t=>{e?.install?e.install(t):e?.info(`[Install] ${t}`)}}var Hn=class{config;logger;npm;catalog;pkgResolver;log;constructor(e,t){this.config=e,this.logger=t,this.npm=new Bn(e.install.registry,t),this.catalog=Ln(e),this.pkgResolver=new Je(this.npm,t),this.log=Vn(t)}async resolveAll(){let e={},t=this.config.packs.bp?.dependencies;if(!t||Object.keys(t).length===0)return this.log(`no BP dependencies to resolve`),e;this.log(`resolving dependencies for target ${this.config.target}`);for(let[n,r]of Object.entries(t)){let t=Rn(this.catalog,n),i=await this.resolveOne(n,r,t),a=t.manifest??!1;e[n]={specifier:r,packageVersion:i.packageVersion,manifestVersion:a?i.manifestVersion??i.packageVersion:null,manifest:a,external:a,resolver:typeof t.resolver==`string`?t.resolver:t.resolver.name},this.log(`${n}: ${r} -> package ${e[n].packageVersion}, manifest ${e[n].manifestVersion}`)}return this.logger?.verbose(`Dependency resolution complete`),e}async resolveOne(e,t,n){let r={packageName:e,specifier:t,target:this.config.target,entry:n,config:this.config};await this.runDependencyHooks(`beforeResolveDependency`,r);let i=await un.fromConfig(this.config.install.dependencyResolvers,this.config.plugins??[]).resolve({packageName:e,specifier:t,target:this.config.target,entry:n,config:this.config,npm:this.npm,...this.logger?{logger:this.logger}:{}});return await this.runDependencyHooks(`afterResolveDependency`,{...r,result:i}),i}async runDependencyHooks(e,t){for(let n of this.config.plugins??[]){let r=n.install?.hooks?.[e];if(r)try{await r(t)}catch(t){throw new F(`PLUGIN_FAILED`,`Plugin ${n.name} ${e} hook failed: ${t instanceof Error?t.message:String(t)}`)}}}};async function Un(e,t,n,r=!1){let i=s.join(e,`package.json`);if(!await P(i))throw new F(`PACKAGE_JSON_NOT_FOUND`,`package.json not found.`,{details:{cwd:e}});let a=await Te(i),o=t.install.saveTo;a.dependencies=a.dependencies??{},a.devDependencies=a.devDependencies??{};for(let e of Object.keys(n))delete a.dependencies[e],delete a.devDependencies[e];a[o]=a[o]??{};for(let[e,t]of Object.entries(n))a[o][e]=t.packageVersion;return Object.keys(a.dependencies).length||delete a.dependencies,Object.keys(a.devDependencies).length||delete a.devDependencies,r||await Ee(i,a),{updated:!0,path:`package.json`}}const Wn=[1,21,0],Gn=[1,0,0];var Kn=class{config;version;versionStr;depManager;constructor(e,t){this.config=e,this.version=ze(e.version),this.versionStr=e.version,this.depManager=t}buildBp(e){let t=this.requireBp(),n=Fe(e);this.depManager.validateBpDependencies();let r=this.getWriteFormatVersion(n),i=t.manifest.merge===`clean`?this.buildCleanBp(t,r):this.buildPreserveBp(n,t,r);return this.applyAchievementMetadata(i,t),i}buildRp(e){let t=this.requireRp(),n=Fe(e),r=this.getWriteFormatVersion(n),i=t.manifest.merge===`clean`?this.buildCleanRp(t,r):this.buildPreserveRp(n,t,r);return this.applyPbrCapability(i,t),i}buildPreserveBp(e,t,n){return{...e,format_version:n,header:this.buildBpHeader(e,t,n),...t.moduleUuid?{modules:this.replaceManagedBpModules(e.modules,t,n)}:e.modules?{modules:e.modules}:{},dependencies:this.depManager.replaceBpDependencies(e.dependencies,this.config.packs.rp?.uuid,n)}}buildPreserveRp(e,t,n){return{...e,format_version:n,header:this.buildRpHeader(e,t,n),modules:this.replaceManagedRpModules(e.modules,t,n),dependencies:this.depManager.replaceRpDependencies(e.dependencies,this.config.packs.bp?.uuid,n)}}buildCleanBp(e,t){return{format_version:t,header:this.buildBpHeaderClean(e,t),...e.moduleUuid?{modules:this.buildCleanBpModules(e,t)}:{},dependencies:this.depManager.buildBpDependenciesClean(t,this.config.packs.rp?.uuid,e.manifest.extraDependencies)}}buildCleanRp(e,t){return{format_version:t,header:this.buildRpHeaderClean(e,t),modules:this.buildCleanRpModules(e,t),dependencies:this.depManager.buildRpDependenciesClean(t,this.config.packs.bp?.uuid,e.manifest.extraDependencies)}}buildBpHeaderClean(e,t){return{...e.manifest.extraHeader,name:e.name,...e.description===void 0?{}:{description:e.description},uuid:e.uuid,version:this.getVersionFor(t),min_engine_version:e.manifest.minEngineVersion===void 0?this.defaultMinEngineVersion(t):this.configMinEngineVersion(e.manifest.minEngineVersion,t)}}buildRpHeaderClean(e,t){return{...e.manifest.extraHeader,name:e.name,...e.description===void 0?{}:{description:e.description},uuid:e.uuid,...e.packScope===void 0?{}:{pack_scope:e.packScope},version:this.getVersionFor(t),min_engine_version:e.manifest.minEngineVersion===void 0?this.defaultMinEngineVersion(t):this.configMinEngineVersion(e.manifest.minEngineVersion,t)}}buildCleanBpModules(e,t){return[...e.moduleUuid?[this.createScriptModule(e,t)]:[],...e.manifest.extraModules]}buildCleanRpModules(e,t){return[this.createResourcesModule(e,t),...e.manifest.extraModules]}buildBpHeader(e,t,n){return{...e.header??{},name:t.name,...t.description===void 0?{}:{description:t.description},uuid:t.uuid,version:this.getVersionFor(n),min_engine_version:this.normalizeMinEngineVersion(e.header?.min_engine_version,n,t.manifest.minEngineVersion)}}buildRpHeader(e,t,n){return{...e.header??{},name:t.name,...t.description===void 0?{}:{description:t.description},uuid:t.uuid,...t.packScope===void 0?{}:{pack_scope:t.packScope},version:this.getVersionFor(n),min_engine_version:this.normalizeMinEngineVersion(e.header?.min_engine_version,n,t.manifest.minEngineVersion)}}getScriptEntry(){let e=this.config.packs.bp?.compile;return e?`${e.scriptOutputDir}/${s.basename(e.entry,s.extname(e.entry))}.js`:`scripts/main.js`}isManagedBpModule(e,t){if(e.type!==`script`||e.language!==`javascript`)return!1;let n=this.getScriptEntry();return e.uuid===t.moduleUuid||e.entry===n}isManagedRpModule(e,t){return e.type===`resources`&&e.uuid===t.moduleUuid}createScriptModule(e,t){return{type:`script`,language:`javascript`,uuid:e.moduleUuid,version:this.getModuleVersion(t),entry:this.getScriptEntry()}}createResourcesModule(e,t){return{type:`resources`,uuid:e.moduleUuid,version:this.getModuleVersion(t)}}replaceManagedBpModules(e,t,n){return[...Ie(e).filter(e=>!this.isManagedBpModule(e,t)),this.createScriptModule(t,n)]}replaceManagedRpModules(e,t,n){return[...Ie(e).filter(e=>!this.isManagedRpModule(e,t)),this.createResourcesModule(t,n)]}applyAchievementMetadata(e,t){if(t.achievement===!0)e.metadata={...e.metadata??{},product_type:`addon`};else if(t.achievement===!1&&e.metadata){let t={...e.metadata};delete t.product_type;let n=Le(t);n?e.metadata=n:delete e.metadata}}applyPbrCapability(e,t){if(t.pbr===!0){let t=Ie(e.capabilities);e.capabilities=t.includes(`pbr`)?t:[...t,`pbr`]}else if(t.pbr===!1){let t=Ie(e.capabilities).filter(e=>e!==`pbr`);t.length>0?e.capabilities=t:delete e.capabilities}}getVersionFor(e){return e===3?this.versionStr:this.version}getModuleVersion(e){return e===3?`1.0.0`:Gn}getWriteFormatVersion(e){return this.config.manifestFormat===void 0?e.format_version??2:this.config.manifestFormat}normalizeMinEngineVersion(e,t,n){if(n!==void 0)return this.configMinEngineVersion(n,t);if(e==null)return this.defaultMinEngineVersion(t);if(Array.isArray(e))return t===3?e.join(`.`):e;if(typeof e==`string`){if(t===2){let t=this.stringToVersionTuple(e);if(t)return t}return e}return this.defaultMinEngineVersion(t)}configMinEngineVersion(e,t){return t===3?e:this.stringToVersionTuple(e)??this.defaultMinEngineVersion(t)}defaultMinEngineVersion(e){return e===3?`1.21.0`:Wn}stringToVersionTuple(e){let t=e.split(`.`).map(Number);if(t.length===3&&t.every(e=>!Number.isNaN(e)))return t}requireBp(){if(!this.config.packs.bp)throw new F(`CONFIG_INVALID`,`packs.bp is required to build the BP manifest.`);return this.config.packs.bp}requireRp(){if(!this.config.packs.rp)throw new F(`CONFIG_INVALID`,`packs.rp is required to build the RP manifest.`);return this.config.packs.rp}},qn=class e{config;catalog;installVersions;manifestVersions;version;versionStr;dependencyDiagnostics=[];constructor(e,t,n={}){this.config=e,this.catalog=t,this.installVersions=n.install??{},this.manifestVersions=n.manifest??{},this.version=ze(e.version),this.versionStr=e.version}static isAllowedSpecifier(e){return e===`stable`||e===`beta`||e===`preview`||/^\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/.test(e)}static resolveVersion(t){return e.resolveVersionDetail(t).version}static resolveVersionDetail(e){let{specifier:t,target:n,resolvedVersion:r,manifestVersion:i}=e;if(t===`stable`){if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new F(`DEPENDENCY_REQUIRES_INSTALL`,"Run `bepack install` to resolve stable manifest dependencies.",{details:{specifier:t,target:n}})}if(t===`beta`){if(Ve(n))return{version:`beta`,source:`config`};if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new F(`DEPENDENCY_REQUIRES_INSTALL`,`Run \`bepack install\` to resolve manifest dependencies for target ${n}.`,{details:{target:n}})}if(t===`preview`){if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new F(`DEPENDENCY_REQUIRES_INSTALL`,`Run \`bepack install\` to resolve preview manifest dependencies for target ${n}.`,{details:{specifier:t,target:n}})}return{version:t,source:`config`}}static isAchievementCompatible(e){return e!==`beta`&&e!==`preview`}validateBpDependencies(){if(this.config.packs.bp){for(let[t,n]of Object.entries(this.config.packs.bp.dependencies)){if(!this.catalog[t]){let e=Object.keys(this.catalog),n=e.length>0?[`Managed packages: ${e.join(`, `)}.`,`Add a missing package to install.dependencyCatalog, or remove it from packs.bp.dependencies.`]:[`No managed packages are available. Extend install.dependencyCatalog to add one.`];throw new F(`UNSUPPORTED_DEPENDENCY`,`${t} is not a managed dependency.`,{details:{package:t},suggestions:n})}if(!e.isAllowedSpecifier(n))throw new F(`DEPENDENCY_VERSION_INVALID`,`${t} dependency version is invalid: ${n}`,{details:{package:t,specifier:n}})}if(this.config.packs.bp.achievement){for(let[t,n]of Object.entries(this.config.packs.bp.dependencies))if(!e.isAchievementCompatible(n))throw new F(`ACHIEVEMENT_REQUIRES_STABLE_API`,`${t}: achievement requires stable Script API dependencies (${n} is not allowed).`)}}}isManagedBpDependency(e){return!!(`module_name`in e&&typeof e.module_name==`string`&&this.catalog[e.module_name]?.manifest||`uuid`in e&&typeof e.uuid==`string`&&this.config.packs.rp?.uuid===e.uuid)}isManagedRpDependency(e,t){return t!==void 0&&`uuid`in e&&typeof e.uuid==`string`&&e.uuid===t}buildManagedDependencies(){if(this.dependencyDiagnostics.length=0,!this.config.packs.bp)return[];let t=[];for(let[n,r]of Object.entries(this.config.packs.bp.dependencies)){if(!this.catalog[n]?.manifest)continue;let i=e.resolveVersionDetail({specifier:r,target:this.config.target,resolvedVersion:this.installVersions[n],manifestVersion:this.manifestVersions[n]});t.push({module_name:n,version:i.version}),this.dependencyDiagnostics.push({name:n,specifier:r,version:i.version,source:i.source})}return t}getDependencyDiagnostics(){return this.dependencyDiagnostics}getFormatAwareVersion(e){return(e??this.config.manifestFormat??2)===3?this.versionStr:this.version}replaceBpDependencies(e,t,n){let r=Ie(e).filter(e=>!this.isManagedBpDependency(e)),i=this.buildManagedDependencies();return t&&i.push({uuid:t,version:this.getFormatAwareVersion(n)}),[...r,...i]}replaceRpDependencies(e,t,n){let r=Ie(e).filter(e=>!this.isManagedRpDependency(e,t));return t?[...r,{uuid:t,version:this.getFormatAwareVersion(n)}]:r}buildBpDependenciesClean(e,t,n){let r=this.buildManagedDependencies();return t&&r.push({uuid:t,version:this.getFormatAwareVersion(e)}),[...r,...n]}buildRpDependenciesClean(e,t,n){let r=[];return t&&r.push({uuid:t,version:this.getFormatAwareVersion(e)}),[...r,...n]}};const Jn=Oe.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);async function Yn(e){let t=Ln(e.config),n=e.config.packs.bp?Vt(e.cwd,e.config):void 0,r=n?await Re.read(n):void 0,i=Zn(r,t),a=new qn(e.config,t,{...e.resolvedDeps?{install:e.resolvedDeps}:{},manifest:i}),o=new Kn(e.config,a),c={};if(e.config.packs.bp){let t=r!==void 0;e.config.manifestFormat===2&&r?.format_version===3&&(e.logger?.warn??console.warn)(`Warning: config manifestFormat is 2, but existing manifest uses format_version 3. format_version 2 does not support string versions; any string versions in the existing manifest will be preserved as-is.`);let l=o.buildBp(r),u=a.getDependencyDiagnostics().map(e=>({module_name:e.name,specifier:e.specifier,version:e.version,source:e.source,...i[e.name]===void 0?{}:{previous:i[e.name]}}));e.dryRun||await Re.write(n,l,`bp`),Xn(u,e.logger),c.bpManifest={path:B(s.relative(e.cwd,n)),updated:!0,existed:t,dependencies:u}}if(e.config.packs.rp){let t=Ht(e.cwd,e.config),n=await Re.read(t),r=n!==void 0,i=o.buildRp(n);e.dryRun||await Re.write(t,i,`rp`),c.rpManifest={path:B(s.relative(e.cwd,t)),updated:!0,existed:r}}return c}function Xn(e,t){if(t)for(let n of e){let e=Jn.cyan(n.module_name);n.previous!==void 0&&n.previous!==n.version?t.info(`manifest ${e}: ${n.previous} ${Jn.dim(`->`)} ${n.version} (specifier ${JSON.stringify(n.specifier)}, ${n.source})`):n.source===`manifest`?t.info(`manifest ${e} ${n.version} ${Jn.dim(`kept from manifest`)} (specifier ${JSON.stringify(n.specifier)}) — run \`bepack install\` to refresh`):t.verbose(`manifest ${e} ${n.version} (specifier ${JSON.stringify(n.specifier)}, ${n.source})`)}}function Zn(e,t){let n={};for(let r of e?.dependencies??[])`module_name`in r&&typeof r.module_name==`string`&&typeof r.version==`string`&&t[r.module_name]?.manifest&&r.version!==`stable`&&(n[r.module_name]=r.version);return n}function Qn(e){if(e==null||e===``)return`hook ran`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function $n(e,t){let n={dist:Ut(e,t)};if(t.packs.bp&&(n.bpRoot=Mt(e,t),n.bpManifest=Vt(e,t),Pt(t))){let r=U(e,t);r&&(n.srcEntry=r);let i=It(e,t);i&&(n.scriptOutFile=i);let a=Ft(e,t);a&&(n.scriptOutDir=a)}return t.packs.rp&&(n.rpRoot=Nt(e,t),n.rpManifest=Ht(e,t)),n}async function G(e,t,n,r,i,a={}){let o=r.hooks[e];if(o)try{let s=await o({command:t,cwd:n,...a.mode===void 0?{}:{mode:a.mode},target:r.target,dryRun:!!a.dryRun,config:r,paths:$n(n,r),logger:i});i.hook(String(e),Qn(s))}catch(t){throw new F(`HOOK_FAILED`,`${String(e)} hook failed: ${t instanceof Error?t.message:String(t)}`)}}async function er(e){let{command:t,logger:n,mode:r,...i}=e,a={...r===void 0?{}:{mode:r},dryRun:!!i.dryRun};await G(`beforeManifest`,t,i.cwd,i.config,n,a);let o=await Yn({...i,logger:n});return await G(`afterManifest`,t,i.cwd,i.config,n,a),o}function tr(e){let t=[],n={};for(let[r,i]of Object.entries(e)){if(r.toLowerCase()===`npm_config_allow_scripts`){t.push(r);continue}n[r]=i}return{env:n,removed:t}}var nr=class{cwd;registry;logger;constructor(e,t,n){this.cwd=e,this.registry=t,this.logger=n}async detect(e){if(e!==`auto`)return e;let t=s.join(this.cwd,`package.json`);if(await P(t)){let e=(await Te(t)).packageManager?.split(`@`)[0];if(e===`npm`||e===`pnpm`||e===`yarn`||e===`bun`)return e}return await P(s.join(this.cwd,`pnpm-lock.yaml`))?`pnpm`:await P(s.join(this.cwd,`yarn.lock`))?`yarn`:await P(s.join(this.cwd,`bun.lock`))||await P(s.join(this.cwd,`bun.lockb`))?`bun`:`npm`}async install(e){let{command:t,args:n}=this.commandForPlatform(e,this.installArgs(e)),{env:r,removed:i}=tr(process.env);return i.length>0&&this.logger?.warn(`Ignoring inherited ${i.join(`, `)}: npm rejects --allow-scripts for project-scoped installs. Declare allowed packages in package.json "allowScripts" or in .npmrc instead.`),await new Promise((i,a)=>{let o;try{o=m(t,n,{cwd:this.cwd,stdio:`inherit`,env:r})}catch(t){a(new F(`PACKAGE_MANAGER_NOT_FOUND`,`${e} is not available.`,{details:{manager:e,cause:t instanceof Error?t.message:String(t)}}));return}o.on(`error`,t=>a(new F(`PACKAGE_MANAGER_NOT_FOUND`,`${e} is not available.`,{details:{manager:e,cause:t.message}}))),o.on(`exit`,t=>{t&&t!==0?a(new F(`PACKAGE_MANAGER_FAILED`,`${e} install failed.`,{details:{manager:e,registry:this.registry,exitCode:t}})):i(t??0)})})}commandForPlatform(e,t){return process.platform===`win32`?{command:process.env.ComSpec??`cmd.exe`,args:[`/d`,`/s`,`/c`,e,...t]}:{command:e,args:t}}installArgs(e){let t=[`install`];return this.registry&&(e===`npm`||e===`pnpm`||e===`bun`||e===`yarn`)&&t.push(`--registry`,this.registry),t}};async function rr(e){let t=new L({...e,silent:e.silent||e.json}),n={target:e.target};(e.registry||e.pm||e.saveTo||e.skipPm||e.skipManifest||e.skipPackageJson)&&(n.install={...e.registry?{registry:e.registry}:{},...e.pm?{packageManager:e.pm}:{},...e.saveTo?{saveTo:e.saveTo}:{},...e.skipPm?{runPackageManager:!1}:{},...e.skipManifest?{updateManifest:!1}:{},...e.skipPackageJson?{updatePackageJson:!1}:{}});let{cwd:r,config:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:n});await G(`beforeInstall`,`install`,r,i,t,{dryRun:!!e.dryRun});let a=await new Hn(i,t).resolveAll(),o=Object.fromEntries(Object.entries(a).filter(([,e])=>e.manifestVersion!==null).map(([e,t])=>[e,t.manifestVersion])),s={};i.install.updatePackageJson&&(s.packageJson=await Un(r,i,a,e.dryRun)),i.install.updateManifest&&Object.assign(s,await er({cwd:r,config:i,command:`install`,dryRun:e.dryRun,logger:t,resolvedDeps:o}));let c=new nr(r,i.install.registry,t),l=await c.detect(i.install.packageManager),u={ran:!1,manager:l,exitCode:null};return!e.dryRun&&i.install.runPackageManager&&(t.progress(`Install`,`running ${l} install with registry ${i.install.registry}`),u={ran:!0,manager:l,exitCode:await c.install(l)}),await G(`afterInstall`,`install`,r,i,t,{dryRun:!!e.dryRun}),t.success(`Install`,`done`),{ok:!0,command:`install`,target:i.target,packageManager:l,resolved:a,files:s,packageInstall:u}}async function ir(e){let t=new L({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{target:e.target}}),i=await er({cwd:n,config:r,command:`manifest`,dryRun:e.dryRun,logger:t});return t.success(`Manifest`,e.dryRun?`dry-run complete`:`updated manifest.json`),{ok:!0,command:`manifest`,target:r.target,files:i}}const ar=10485760;async function or(e,t={}){let n=mr(t.command),r=t.tsconfigPath??`tsconfig.json`,i=s.resolve(e,r),a=await P(i),o=en(t.command,t.args??[],n?{tsconfigPath:i,incremental:!!t.incremental,useNpx:!!t.useNpx,...t.tsBuildInfoFile?{tsBuildInfoFile:t.tsBuildInfoFile}:{}}:{});if(!a){if(n)throw new F(`TYPECHECK_FAILED`,`TypeScript config not found: ${r}. Create it or run build with --skip-typecheck.`,{details:{path:r,command:o.label}});t.warn?.(`TypeScript config not found: ${r} — running \`${o.label}\` anyway.`)}t.incremental&&t.tsBuildInfoFile&&n&&await _(s.dirname(t.tsBuildInfoFile),{recursive:!0});let c=nn(o),l=await dr(o.command,e);if(!l)throw new F(`TYPECHECK_FAILED`,`Cannot find ${o.command}.`,{details:{command:c,label:o.label},suggestions:pr(o)});let u=process.platform===`win32`&&/\.(cmd|bat)$/i.test(l),d=u?sr(l,o.args):l,f=u?[]:o.args,p;try{p=m(d,f,{cwd:e,windowsHide:!0,shell:u,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){throw new F(`TYPECHECK_FAILED`,`Cannot start ${c}.`,{details:{command:c,label:o.label,cause:e instanceof Error?e.message:String(e)},suggestions:pr(o)})}return await new Promise((e,n)=>{let r=``,i=``,a=0,s=e=>{let t=Buffer.isBuffer(e)?e:Buffer.from(String(e)),n=ar-a;return n<=0?``:t.length<=n?(a+=t.length,t.toString(`utf8`)):(a=ar,t.subarray(0,n).toString(`utf8`))};p.stdout?.on(`data`,e=>{r+=s(e),t.quiet||process.stdout.write(e)}),p.stderr?.on(`data`,e=>{i+=s(e),t.quiet||process.stderr.write(e)}),p.on(`error`,e=>{n(new F(`TYPECHECK_FAILED`,`Cannot start ${c}.`,{details:{command:c,label:o.label,cause:e.message},suggestions:pr(o)}))}),p.on(`close`,t=>{if(t===0){e();return}let a=[r.trim(),i.trim()].filter(Boolean).join(`
10
+ `),s=ur(a);n(new F(`TYPECHECK_FAILED`,s?`Cannot find ${o.command}.`:`${c} failed.`,{details:{command:c,label:o.label,exitCode:typeof t==`number`?t:null,...a?{diagnostics:a}:{}},...s?{suggestions:pr(o)}:{}}))})}),{...o,commandLine:c}}function sr(e,t){let n=process.platform===`win32`?cr:lr;return[e,...t].map(n).join(` `)}function cr(e){if(e===``)return`""`;if(!/[\s"&|<>^()!,;=]/.test(e))return e.replace(/%/g,`^%`);let t=`"`,n=0;for(let r of e){if(r===`\\`){n+=1;continue}if(r===`%`){t+=`\\`.repeat(n*2)+`"^%"`,n=0;continue}if(r===`"`){t+=`\\`.repeat(n*2+1)+`"`,n=0;continue}t+=`\\`.repeat(n)+r,n=0}return t+=`\\`.repeat(n*2)+`"`,t}function lr(e){return e===``?`''`:/[\s"'\\$`!*?[\]{}();&|<>~#]/.test(e)?`'${e.replace(/'/g,`'\\''`)}'`:e}function ur(e){return e.includes(`ENOENT`)||e.includes(`is not recognized`)||e.includes(`不是内部或外部命令`)||e.includes(`command not found`)}async function dr(e,t){let n=e.includes(`/`)||e.includes(`\\`);if(s.isAbsolute(e)||n){let n=s.resolve(t,e);return await fr(n)?n:void 0}let r=process.env.PATH??``,i=process.platform===`win32`?(process.env.PATHEXT??`.COM;.EXE;.BAT;.CMD`).split(`;`).filter(Boolean):[``];for(let n of r.split(s.delimiter)){let r=n?s.resolve(t,n):t,a=s.join(r,e);if(await fr(a))return a;for(let t of i){if(t&&s.extname(e))continue;let n=s.join(r,e+t);if(await fr(n))return n}}}async function fr(t){try{return await g(t,e.X_OK),!0}catch{return!1}}function pr(e){return[`Install the checker so \`${e.command}\` is available, or point packs.bp.compile.typecheck.command at a command you do have (for example "bun check", "tsc-rs --noEmit", "npx tsc --noEmit").`,`Run with --skip-typecheck to build without checking (the bundle is still produced).`]}function mr(e){return typeof e!=`string`||e.trim()===``}const hr=/* @__PURE__ */ new Set([`plugins`]),gr=/* @__PURE__ */ new Set([`external`]),_r=/* @__PURE__ */ new Set([`output`,`resolve`,`transform`,`experimental`,`checks`,`optimization`,`watch`,`moduleTypes`]),vr=[{key:`file`,suggestion:`The output file is derived from packs.bp.compile.entry and scriptOutputDir.`},{key:`dir`,suggestion:`The output directory is derived from packs.bp.compile.scriptOutputDir.`},{key:`format`,suggestion:`Minecraft Script API modules must be ESM, so BePack always writes format: "esm".`},{key:`preserveModules`,suggestion:`Use packs.bp.compile.preserveModules instead.`},{key:`preserveModulesRoot`,suggestion:`The modules root is always the entry file directory.`},{key:`entryFileNames`,suggestion:"Manifest script entries assume one `.js` file per source module."}];function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yr(e){return e==null||e===!1?[]:Array.isArray(e)?e:[e]}function br(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function xr(e,t,n){return typeof e!=`string`||typeof t!=`string`?!1:br(s.resolve(n,e),s.resolve(n,t))}function Sr(e){if(e instanceof Error){let t=e.cause;return t instanceof Error&&t.message?t.message:e.message}return String(e)}function Cr(e,t){if(typeof e==`function`||typeof t==`function`)return t;let n=[],r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set;for(let a of[...yr(e),...yr(t)])if(typeof a==`string`){if(r.has(a))continue;r.add(a),n.push(a)}else if(a instanceof RegExp){let e=`${a.source}/${a.flags}`;if(i.has(e))continue;i.add(e),n.push(a)}return n}function wr(e,t){if(!K(t))return t;let n=K(e)?e:{},r={...n,...t},i=K(n.define)?n.define:{};return K(t.define)&&(r.define={...i,...t.define}),r}function Tr(e,t){if(!t)return{...e};let n={...e};for(let[e,r]of Object.entries(t)){if(r===void 0)continue;let t=n[e];n[e]=hr.has(e)?[...yr(t),...yr(r)]:gr.has(e)?Cr(t,r):e===`transform`?wr(t,r):_r.has(e)&&K(t)&&K(r)?{...t,...r}:r}return n}function Er(e){if(!e.packs.bp?.compile)return[];let t=[...e.packs.bp.compile.external],n=new Set(t.filter(e=>typeof e==`string`));for(let[r,i]of Object.entries(Ln(e)))i.manifest&&!n.has(r)&&(t.push(r),n.add(r));return t}function Dr(e){let t=e.packs.bp?.compile;if(!t)throw new F(`BUILD_FAILED`,`rolldown requires packs.bp.compile to be configured.`);return t}function Or(e,t){let n=Dr(t),r=U(e,t);if(!r)throw new F(`BUILD_FAILED`,`packs.bp.compile.entry could not be resolved.`);return{input:r,external:Er(t),plugins:Jt(t),...Zt(n.define)??{},onwarn(e,t){e.code!==`CIRCULAR_DEPENDENCY`&&t(e)},experimental:{attachDebugInfo:n.preserveModules?`none`:`simple`}}}function kr(e,t){let n=Dr(t),r=U(e,t),i=Ft(e,t),a=It(e,t);if(!r||!i||!a)throw new F(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);return n.preserveModules?{dir:i,format:`esm`,preserveModules:!0,preserveModulesRoot:s.dirname(r),entryFileNames:`[name].js`,minify:n.minify}:{file:a,format:`esm`,minify:n.minify}}function Ar(e,t){if(typeof e==`string`)return[s.resolve(t,e)];if(Array.isArray(e))return e.every(e=>typeof e==`string`)?e.map(e=>s.resolve(t,e)).sort():void 0;if(K(e)){let n=Object.values(e);return n.every(e=>typeof e==`string`)?n.map(e=>s.resolve(t,e)).sort():void 0}}function jr(e,t,n){if(e.input===void 0)return;let r=Ar(e.input,n),i=Ar(t.input,n);if(!(r!==void 0&&i!==void 0&&r.length===i.length&&r.every((e,t)=>br(e,i[t]))))throw new F(`CONFIG_INVALID`,`packs.bp.compile.rolldown cannot override "input" — the bundle entry is managed by BePack.`,{details:{input:e.input,expected:t.input},suggestions:[`Set the entry file via packs.bp.compile.entry instead.`]})}function Mr(e,t,n){for(let{key:r,suggestion:i}of vr){let a=e[r];if(a===void 0)continue;let o=t[r];if(!(r===`file`||r===`dir`||r===`preserveModulesRoot`?xr(a,o,n):Object.is(a,o)||r===`preserveModules`&&o===void 0&&a===!1))throw new F(`CONFIG_INVALID`,`packs.bp.compile.rolldown cannot override "output.${r}" — it is managed by BePack.`,{details:{key:r,value:a,expected:o},suggestions:[i]})}}function Nr(e,t){if(K(e)&&e.__esModule===!0&&`default`in e)return Nr(e.default,t);if(typeof e==`function`)return e;if(Array.isArray(e)){if(e.length===0)throw new F(`CONFIG_INVALID`,`rolldown config file exports an empty array: ${t}`,{details:{file:t},suggestions:[`Export a single rolldown options object.`]});if(e.length>1)throw new F(`CONFIG_INVALID`,`rolldown config file exports ${e.length} configs, but BePack builds a single behavior pack per run: ${t}`,{details:{file:t,count:e.length},suggestions:[`Export a single rolldown options object.`]});if(!K(e[0]))throw new F(`CONFIG_INVALID`,`rolldown config file must export an options object or function: ${t}`);return e[0]}if(K(e))return e;throw new F(`CONFIG_INVALID`,`rolldown config file must default-export a rolldown options object, a function, or a single-element array: ${t}`)}async function Pr(e){if(!await P(e))throw new F(`CONFIG_INVALID`,`rolldown config file not found: ${e}`,{details:{path:e},suggestions:[`Check the path in packs.bp.compile.rolldownConfig or --rolldown-config.`]});let t;try{t=await b(e)}catch(t){throw new F(`CONFIG_INVALID`,`Failed to load rolldown config file "${e}": ${Sr(t)}`)}return Nr(t,e)}async function Fr(e,t,n){let r;try{r=await e(t,n)}catch(e){throw new F(`BUILD_FAILED`,`compile.rolldown customization function failed: ${Sr(e)}`)}if(r==null)return t;if(!K(r))throw new F(`CONFIG_INVALID`,`compile.rolldown customization function must return a rolldown options object (or nothing).`);return Tr(t,r)}async function Ir(e){let{cwd:t,config:n}=e,r=Dr(n),i=V(t,n),a=U(t,n),o=Ft(t,n),c=It(t,n);if(!a||!o||!c)throw new F(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);let l=Or(t,n),u=kr(t,n),d={command:e.command??`build`,...e.mode===void 0?{}:{mode:e.mode},target:n.target,entry:a,outDir:o,outFile:c,preserveModules:r.preserveModules},f=r.rolldown,p=e.configPath??r.rolldownConfig,m=p?await Pr(s.resolve(i,p)):void 0,h=Tr(l,typeof f==`function`?void 0:f);h=Tr(h,typeof m==`function`?void 0:m),typeof f==`function`&&(h=await Fr(f,h,d)),typeof m==`function`&&(h=await Fr(m,h,d));let{output:g,input:_,...v}=h;if(Array.isArray(g))throw new F(`CONFIG_INVALID`,"packs.bp.compile.rolldown cannot declare multiple outputs (an `output` array) — BePack writes exactly one output.",{suggestions:["Declare a single `output` object."]});if(g!==void 0&&!K(g))throw new F(`CONFIG_INVALID`,"packs.bp.compile.rolldown `output` must be an object.",{details:{output:g}});jr({input:_},l,i);let y=Tr(u,g);return Mr(y,u,i),{inputOptions:{...v,input:l.input},outputOptions:y}}function Lr(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(2)} MB`}function Rr(e,n){let r=s.resolve(e),i=s.resolve(n),a=s.relative(r,i);if(!a||a.startsWith(`..`)||s.isAbsolute(a))return;try{if(t(r).isSymbolicLink())throw new F(`BUILD_FAILED`,`Safety check failed: BP root is a symbolic link or junction: "${r}". Refusing to recursively delete through a symbolic link.`)}catch(e){if(e instanceof F)throw e;if(e?.code===`ENOENT`)return;throw e}let o=r;for(let e of a.split(s.sep)){o=s.join(o,e);try{if(t(o).isSymbolicLink())throw new F(`BUILD_FAILED`,`Safety check failed: script output path contains a symbolic link: "${o}". Refusing to recursively delete through a symbolic link.`)}catch(e){if(e.code===`ENOENT`)break;throw e}}}function zr(e,t,n){let r=s.resolve(e),i=s.resolve(t);if(Lt(r,i)||Lt(i,r))throw new F(`BUILD_FAILED`,`Safety check failed: script output directory "${e}" overlaps ${n} "${t}". Refusing to empty this directory.`)}function Br(e,t,n,r){let i=V(e,t),a=Mt(e,t),o=s.join(a,`manifest.json`),c=[s.join(i,`.git`),s.join(a,`.git`)];for(let e of c)zr(r,e,`.git metadata`);if(t.packs.rp){let e=H(i,t,`rp`);s.resolve(e)!==s.resolve(a)&&zr(r,e,`RP root`)}zr(r,o,`BP manifest`);let l=s.dirname(n),u=s.relative(a,l);zt(r,a,`script output directory`,u&&!u.startsWith(`..`)&&!s.isAbsolute(u)?[l]:[]),Rr(a,r)}async function Vr(e,t,n,r={}){if(!Pt(t))throw new F(`BUILD_FAILED`,`rolldown requires packs.bp.compile to be configured.`);let i=U(e,t),a=Ft(e,t),o=It(e,t);if(!i||!a||!o)throw new F(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);try{let{inputOptions:o,outputOptions:s}=await Ir({cwd:e,config:t,...r.command===void 0?{}:{command:r.command},...r.mode===void 0?{}:{mode:r.mode},...r.rolldownConfig===void 0?{}:{configPath:r.rolldownConfig}});Br(e,t,i,a),await we(a);let c=await y(o);try{await c.write(s)}finally{await c.close()}await Hr(a,n)}catch(e){throw e instanceof F?e:new F(`BUILD_FAILED`,`rolldown failed: ${e instanceof Error?e.message:String(e)}`)}}async function Hr(e,t){let n=[];async function r(t){let i=await h.readdir(t,{withFileTypes:!0});for(let a of i){let i=s.join(t,a.name);if(a.isDirectory())await r(i);else if(a.isFile()&&a.name.endsWith(`.js`)){let t=await h.stat(i);n.push({path:s.relative(e,i),size:t.size})}}}if(await r(e),n.length===0)return;n.sort((e,t)=>t.size-e.size);let i=n.reduce((e,t)=>e+t.size,0);t?.rolldown(n.length===1?`${n[0].path} (${Lr(n[0].size)})`:`${n.length} files, total ${Lr(i)}`)}async function Ur(e,t,n,r){let i=r?Date.now():0,a=await t();return r&&n.timing(e,Date.now()-i),a}async function Wr(e){let t=Date.now(),n=e.config.build.timing,r=V(e.cwd,e.config),i=Pt(e.config),a=e.command??`build`,o={...e.mode===void 0?{}:{mode:e.mode},dryRun:!!e.dryRun};await Ur(`manifest`,()=>er({cwd:e.cwd,config:e.config,command:a,logger:e.logger,dryRun:!!e.dryRun,...e.mode===void 0?{}:{mode:e.mode},...e.resolvedDeps?{resolvedDeps:e.resolvedDeps}:{}}),e.logger,n);let c=[];e.config.packs.bp&&c.push(`bp`),e.config.packs.rp&&c.push(`rp`),e.logger.manifest(`manifest.json updated (${c.join(`, `)})`),await G(`beforeBuild`,a,e.cwd,e.config,e.logger,o);let l=!1,u;if(i&&!e.dryRun&&e.typecheck!==!1){let t=e.config.packs.bp.compile,i=e.cache?s.resolve(r,t.cache.file):void 0,a=e.typecheckCommand??(e.useNpx?void 0:t.typecheckCommand),o=e.typecheckCommand===void 0&&(!!e.useNpx||a===void 0&&t.useNpx),c=await Ur(`typecheck`,()=>or(r,{quiet:!!e.quiet,...a===void 0?{}:{command:a},useNpx:o,args:e.typecheckCommand!==void 0||e.useNpx?[]:t.typecheckArgs,tsconfigPath:t.tsconfig,incremental:!!e.cache,...i?{tsBuildInfoFile:i}:{},warn:t=>e.logger.warn(t)}),e.logger,n);l=!0,u=c.commandLine,e.logger.typescript(`typecheck complete (${c.commandLine})`)}i&&!e.dryRun&&(await Ur(`rolldown`,()=>Vr(e.cwd,e.config,e.logger,{...e.command===void 0?{}:{command:e.command},...e.mode===void 0?{}:{mode:e.mode},...e.rolldownConfig===void 0?{}:{rolldownConfig:e.rolldownConfig}}),e.logger,n),e.logger.rolldown(e.config.packs.bp.compile.preserveModules?`preserve modules build complete`:`bundle complete`)),await G(`afterBuild`,a,e.cwd,e.config,e.logger,o);let d=Date.now()-t;return{script:i?B(It(e.cwd,e.config)):void 0,compiled:i,typecheck:l,...u?{typecheckCommand:u}:{},durationMs:d}}async function Gr(e,t=``){let r={},i=await n.readdir(e,{withFileTypes:!0});for(let a of i){let i=s.join(e,a.name),o=t?`${t}/${a.name}`:a.name;a.isDirectory()?Object.assign(r,await Gr(i,o)):r[o]=new Uint8Array(await n.readFile(i))}return r}async function Kr(e,t){let r={};for(let i of t){let t=s.join(e,i);try{(await n.stat(t)).isDirectory()?Object.assign(r,await Gr(t,i)):r[i]=new Uint8Array(await n.readFile(t))}catch{}}return r}async function qr(e,t){return t?await t(e):e}function Jr(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}/${r}`]=i;return n}function Yr(e){let t={};for(let n of Object.keys(e).sort())t[n]=e[n];return t}async function Xr(e,t){await n.rm(e,{recursive:!0,force:!0}),await n.mkdir(e,{recursive:!0});for(let[r,i]of Object.entries(t)){let t=s.join(e,r);await n.mkdir(s.dirname(t),{recursive:!0}),await n.writeFile(t,i)}}var Zr=te((()=>{}));Zr();const Qr=new TextEncoder;new TextDecoder;function $r(e){let t=16+e.length*256,n=0,r=[];for(let t of e){let e=Qr.encode(t.name);if(e.length===0)throw new F(`PACK_FAILED`,`brarchive entry names must not be empty.`);if(e.length>247)throw new F(`PACK_FAILED`,`brarchive entry name is too long (max 247 bytes): ${t.name}`,{details:{name:t.name,bytes:e.length}});r.push(e),n+=t.data.length}let i=new Uint8Array(t+n),a=new DataView(i.buffer);a.setBigUint64(0,9018218223661903910n,!1),a.setUint32(8,e.length,!0),a.setUint32(12,1,!0);let o=0;return e.forEach((e,n)=>{let s=16+n*256,c=r[n];a.setUint8(s,c.length),i.set(c,s+1),a.setUint32(s+248,o,!0),a.setUint32(s+252,e.data.length,!0),i.set(e.data,t+o),o+=e.data.length}),i}const ei=[`functions`,`loot_tables`,`structures`,`texts`],ti=[`font`,`materials`,`sounds`,`texts`,`textures`],ni=[1,26,40],ri=ni.join(`.`),ii=new TextEncoder,ai=new TextDecoder,oi=new TextDecoder(`utf-16le`),si=new TextDecoder(`utf-16be`);function ci(e){if(e.length>=2){if(e[0]===255&&e[1]===254)return oi.decode(e.subarray(2));if(e[0]===254&&e[1]===255)return si.decode(e.subarray(2))}return ai.decode(e)}function li(e){return e.length>=2&&(e[0]===255&&e[1]===254||e[0]===254&&e[1]===255)}function ui(e){return e.startsWith(``)?e.slice(1):e}function di(e){if(e&&typeof e==`object`&&!Array.isArray(e))return e}function fi(e){if(typeof e==`string`){let t=e.split(`.`).map(e=>Number.parseInt(e,10));return t.length>=3&&t.slice(0,3).every(e=>Number.isInteger(e))?[t[0],t[1],t[2]]:void 0}if(Array.isArray(e)&&e.length>=3){let t=e.slice(0,3);if(t.every(e=>typeof e==`number`&&Number.isInteger(e)))return t}}function pi(e,t){for(let n=0;n<3;n++){let r=(e[n]??0)-(t[n]??0);if(r!==0)return r}return 0}function mi(e){if(e)try{return di(JSON.parse(ui(ci(e))))}catch{return}}function hi(e){return fi(di(e?.header)?.min_engine_version)}function gi(e){let t=e?.modules;return Array.isArray(t)?t.some(e=>di(e)?.type===`resources`):!1}function _i(e,t,n){if(t.allowUnsupportedTarget)return;let r=hi(e);if(r&&pi(r,ni)>=0)return;let i=r?r.join(`.`):`(not declared)`;n?.warn(`pack optimization: header.min_engine_version is ${i}, below ${ri}. The archives still load on 1.26.40+, but older clients cannot read __brarchive/ and will show missing content. Set allowUnsupportedTarget: true to silence this warning.`)}function vi(e,t,n){if(!e.toLowerCase().endsWith(`.json`))return t;try{let e=JSON.parse(ui(ci(t)));return ii.encode(JSON.stringify(e))}catch(r){let i=r instanceof Error?r.message:String(r),a=li(t)?` (UTF-16)`:``;return n?.warn(`pack optimization: could not minify ${e}${a}, storing it unchanged. ${i}. Fix the JSON to have it minified.`),t}}function yi(e,t){if(!e)throw new F(`PACK_FAILED`,`Pack optimization needs a manifest.json to write header.pack_optimization_version into.`);let n;try{let t=di(JSON.parse(ui(ci(e))));if(!t)throw Error(`manifest is not an object`);n=t}catch{throw new F(`PACK_FAILED`,`Cannot write header.pack_optimization_version: the pack's manifest.json is not valid JSON.`)}let r={...di(n.header)??{}};return r.pack_optimization_version=t,n.header=r,ii.encode(JSON.stringify(n))}function bi(e,t,n,r){let i=e[`manifest.json`]??r,a=mi(i);_i(a,t,n);let o=new Set(t.exclude),s=t.keepLoose===!1?/* @__PURE__ */ new Set:/* @__PURE__ */ new Set([...gi(a)?ti:ei,...t.keepLoose]),c=/* @__PURE__ */ new Map,l={},u={},d=0,f=0;for(let r of Object.keys(e).sort()){let i=e[r],a=r.split(`/`),p=a[0];if(a.length<2||p===`__brarchive`||o.has(p)){l[r]=i;continue}let m=a.slice(0,-1).join(`/`),h=a[a.length-1],g=c.get(m)??[],_=t.keepLooseFiles||s.has(p);s.has(p)&&!t.keepLooseFiles?(g.push({name:h,data:/* @__PURE__ */ new Uint8Array}),u[r]=i,f++):(g.push({name:h,data:t.minifyJson?vi(h,i,n):i}),d++,_&&(u[r]=i)),c.set(m,g)}let p={...l,...u};for(let e of[...c.keys()].sort())p[`__brarchive/${e}.brarchive`]=$r(c.get(e));p[`manifest.json`]=yi(i,t.packOptimizationVersion);let m=Object.keys(u).length,h=f>0?`, ${f} name-stub${f===1?``:`s`}`:``;return n?.pack(`optimized into ${c.size} archive${c.size===1?``:`s`} (${d} file${d===1?``:`s`} archived${h}, ${m} kept loose)`),Yr(p)}function xi(e,t,n){return r=>bi(r,e,t,n)}const Si={win:()=>({type:`gameRoot`,path:s.join(`C:/Users`,d.userInfo().username,`AppData/Roaming/Minecraft Bedrock/Users/Shared/games/com.mojang`)}),winold:()=>{let e=process.env.LOCALAPPDATA;if(!e)throw new F(`COPY_TARGET_NOT_FOUND`,`%LOCALAPPDATA% is required for winold copy target.`);return{type:`gameRoot`,path:s.join(e,`Packages`,`Microsoft.MinecraftUWP_8wekyb3d8bbwe`,`LocalState`,`games`,`com.mojang`)}}};function Ci(e,t){return{type:`custom`,bp:s.join(t.path,`development_behavior_packs`),...e.packs.rp?{rp:s.join(t.path,`development_resource_packs`)}:{}}}function wi(e,t){let n=t??e.copy.defaultTarget;if(!n)throw new F(`COPY_TARGET_NOT_FOUND`,`No copy target configured. Set copy.defaultTarget or copy.targets in bepack.config.ts, or pass --target.`,{suggestions:[`Add copy.defaultTarget to your config file.`,`Or set build.copy / dev.copy to a target name instead of true.`,`Built-in targets: win, winold.`]});let r=e.copy.targets[n]??Si[n]?.();if(!r)throw new F(`COPY_TARGET_NOT_FOUND`,`Copy target not found: ${n}`,{details:{target:n}});let i=e.copy.targets[n]?.name,a=e.copy.name,o=e=>typeof e==`string`?{bp:e,rp:e}:e??{},s=o(i),c=o(a),l={},u=s.bp??c.bp,d=s.rp??c.rp;return u&&(l.bp=u),d&&(l.rp=d),r.type===`gameRoot`?{name:n,target:Ci(e,r),names:l}:{name:n,target:r,names:l}}const Ti=/* @__PURE__ */ new Set([`node_modules`,`package.json`,`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lock`,`bun.lockb`,`tsconfig.json`,...Ct]);function Ei(e,t,n){let r=H(V(e,t),t,n);if(!r)return[];let i=U(e,t),a=[Ut(e,t),i?s.dirname(i):void 0],o=[];for(let e of a){if(!e)continue;let t=s.relative(r,e);if(!t||t.startsWith(`..`)||s.isAbsolute(t))continue;let n=t.split(s.sep)[0];n&&o.push(n)}return o}async function Di(e,t,r=[]){let i;try{i=await n.readdir(e,{withFileTypes:!0})}catch{return[]}let a=new Set(t);return i.map(e=>e.name).filter(e=>!a.has(e)).filter(e=>!e.startsWith(`.`)&&!Ti.has(e)).filter(e=>!r.includes(e)).sort((e,t)=>e.localeCompare(t))}function Oi(e){return e===`bp`?`packs.bp.include`:`packs.rp.include`}async function ki(e){let{logger:t,packType:n,root:r,items:i,action:a}=e;if(!t)return;let o=await Di(r,i,e.ignore??[]);if(o.length===0)return;let s=e.limit??8,c=o.slice(0,s).join(`, `),l=o.length>s?`, +${o.length-s} more`:``,u=n===`bp`?`behavior pack`:`resource pack`;t.warn(`${u} ${a} only includes ${i.length} configured item(s); ${o.length} entr${o.length===1?`y`:`ies`} in "${Ai(r,e.cwd)}" ${o.length===1?`is`:`are`} skipped: ${c}${l}. Add them to ${Oi(n)} to include them.`)}function Ai(e,t){if(!t)return e;let n=s.relative(t,e).replace(/\\/g,`/`);return n&&!n.startsWith(`..`)&&!s.isAbsolute(n)?n:e}Zr();const ji=Oe.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);async function Mi(e,t,r){await n.rm(t,{recursive:!0,force:!0}),await n.mkdir(t,{recursive:!0});for(let i of r){let r=s.join(e,i),a=s.join(t,i);try{await n.cp(r,a,{recursive:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}function Ni(e,t){let n=s.resolve(e),r=s.resolve(t);if(Lt(n,r)||Lt(r,n))throw new F(`COPY_FAILED`,`Copy target "${t}" overlaps source pack "${e}". Refusing to copy.`,{details:{source:n,target:r}})}function Pi(e,t){let n=s.resolve(e),r=s.resolve(n,t);if(r===n||!Lt(n,r))throw new F(`COPY_FAILED`,`Copy folder name "${t}" must resolve to a directory inside "${e}".`,{details:{targetDir:n,folderName:t,destination:r}});return r}async function Fi(e,t){if(!await P(e))throw new F(`COPY_FAILED`,`Copy target directory does not exist: ${e}`,{details:{dir:e,label:t},suggestions:[`Create the target directory: mkdir -p "${e}"`,`Or check the copy target path in bepack.config.ts.`]})}function Ii(e,t){if(t===`bp`)return Bt(e);let n=e.packs.rp?.include??[],r=e.copy.include?.rp??[],i=n.length>0?n:r;return i.length>0?[...At,...i]:[]}async function Li(e){try{return new Uint8Array(await n.readFile(s.join(e,`manifest.json`)))}catch{return}}async function Ri(e,t,n,r,i,a,o,s,c){let l=Ii(i,e),u=Pi(n,r);Ni(t,u);let d=e===`bp`||l.length>0;d&&await ki({...s?{logger:s}:{},packType:e,root:t,items:l,action:`copy`,cwd:o,ignore:Ei(o,i,e)});let f=c===void 0?i.copy.optimize:c?i.copy.optimize??Tt:void 0;if(!a){if(f){let e=d?await Kr(t,l):await Gr(t),n=xi(f,s,await Li(t));try{await Xr(u,await qr(e,n))}catch(e){throw e instanceof F?new F(e.code===`PACK_FAILED`?`COPY_FAILED`:e.code,e.message,{...e.details===void 0?{}:{details:e.details},...e.suggestions===void 0?{}:{suggestions:e.suggestions}}):e}}else d?await Mi(t,u,l):await De(t,u)}let p=l.length>0?l.length:void 0;return s?.copy(`${a?`would copy`:`copied`} ${e}${p?` (${p} items)`:``} -> ${ji.gray(u)}`),u}async function zi(e,t,n,r=!1,i,a={}){let{name:o,target:s,names:c}=wi(t,n),l=[],u=V(e,t),d=Ot(t);for(let n of d){let o;if(o=n.type===`bp`?s.bp:s.rp,!o)continue;await Fi(o,n.type);let d=c[n.type]??n.name,f=H(u,t,n.type),p=await Ri(n.type,f,o,d,t,r,e,i,a.optimize);l.push(p)}return{target:o,copied:l}}async function Bi(e){let{command:t,cwd:n,config:r,logger:i,targetName:a,mode:o,optimize:s}=e,c=!!e.dryRun,l={...o===void 0?{}:{mode:o},dryRun:c};await G(`beforeCopy`,t,n,r,i,l);let u=await zi(n,r,a,c,i,s===void 0?{}:{optimize:s});return await G(`afterCopy`,t,n,r,i,l),u}function Vi(e,t){return Ta(e,t||{},0,0)}function Hi(e,t){if(t){for(var n=new q(e.length),r=0;r<e.length;++r)n[r]=e.charCodeAt(r);return n}if(Oa)return Oa.encode(e);for(var i=e.length,a=new q(e.length+(e.length>>1)),o=0,s=function(e){a[o++]=e},r=0;r<i;++r){if(o+5>a.length){var c=new q(o+8+(i-r<<1));c.set(a),a=c}var l=e.charCodeAt(r);l<128||t?s(l):l<2048?(s(192|l>>6),s(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|e.charCodeAt(++r)&1023,s(240|l>>18),s(128|l>>12&63),s(128|l>>6&63),s(128|l&63)):(s(224|l>>12),s(128|l>>6&63),s(128|l&63))}return la(a,0,o)}function Ui(e,t){t||={};var n={},r=[];Da(e,``,n,t);var i=0,a=0;for(var o in n){var s=n[o],c=s[0],l=s[1],u=l.level==0?0:8,d=Hi(o),f=d.length,p=l.comment,m=p&&Hi(p),h=m&&m.length,g=Aa(l.extra);f>65535&&da(11);var _=u?Vi(c,l):c,v=_.length,y=wa();y.p(c),r.push(Ea(l,{size:c.length,crc:y.d(),c:_,f:d,m,u:f!=o.length||m&&p.length!=h,o:i,compression:u})),i+=30+f+g+v,a+=76+2*(f+g)+(h||0)+v}for(var b=new q(a+22),x=i,S=a-i,C=0;C<r.length;++C){var d=r[C];ja(b,d.o,d,d.f,d.u,d.c.length);var w=30+d.f.length+Aa(d.extra);b.set(d.c,d.o+w),ja(b,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+w+(d.m?d.m.length:0)}return Ma(b,i,r.length,S,x),b}var Wi,Gi,q,J,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,Y,na,ra,ia,aa,oa,sa,ca,la,ua,da,fa,pa,ma,ha,ga,_a,va,ya,ba,xa,Sa,Ca,wa,Ta,Ea,X,Da,Oa,ka,Aa,ja,Ma,Na=te((()=>{Wi=x(`/`);try{Gi=Wi("worker_threads"),Gi.Worker,Gi.isMarkedAsUntransferable}catch{}for(q=Uint8Array,J=Uint16Array,Ki=Int32Array,qi=new q([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ji=new q([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Yi=new q([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Xi=function(e,t){for(var n=new J(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Ki(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Gi=Xi(qi,2),Zi=Gi.b,Qi=Gi.r,Zi[28]=258,Qi[258]=28,$i=Xi(Ji,0),$i.b,ea=$i.r,ta=new J(32768),Y=0;Y<32768;++Y)na=(Y&43690)>>1|(Y&21845)<<1,na=(na&52428)>>2|(na&13107)<<2,na=(na&61680)>>4|(na&3855)<<4,ta[Y]=((na&65280)>>8|(na&255)<<8)>>1;for(ra=(function(e,t,n){for(var r=e.length,i=0,a=new J(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new J(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new J(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[ta[d]>>c]=l}else for(s=new J(r),i=0;i<r;++i)e[i]&&(s[i]=ta[o[e[i]-1]++]>>15-e[i]);return s}),ia=new q(288),Y=0;Y<144;++Y)ia[Y]=8;for(Y=144;Y<256;++Y)ia[Y]=9;for(Y=256;Y<280;++Y)ia[Y]=7;for(Y=280;Y<288;++Y)ia[Y]=8;for(aa=new q(32),Y=0;Y<32;++Y)aa[Y]=5;oa=/*#__PURE__*/ ra(ia,9,0),sa=/*#__PURE__*/ ra(aa,5,0),ca=function(e){return(e+7)/8|0},la=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new q(e.subarray(t,n))},ua=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],da=function(e,t,n){var r=Error(t||ua[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,da),!n)throw r;return r},fa=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},pa=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},ma=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var i=n.length,a=n.slice();if(!i)return{t:xa,l:0};if(i==1){var o=new q(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var s=n[0],c=n[1],l=0,u=1,d=2;for(n[0]={s:-1,f:s.f+c.f,l:s,r:c};u!=i-1;)s=n[n[l].f<n[d].f?l++:d++],c=n[l!=u&&n[l].f<n[d].f?l++:d++],n[u++]={s:-1,f:s.f+c.f,l:s,r:c};for(var f=a[0].s,r=1;r<i;++r)a[r].s>f&&(f=a[r].s);var p=new J(f+1),m=ha(n[u-1],p,0);if(m>t){var r=0,h=0,g=m-t,_=1<<g;for(a.sort(function(e,t){return p[t.s]-p[e.s]||e.f-t.f});r<i;++r){var v=a[r].s;if(p[v]>t)h+=_-(1<<m-p[v]),p[v]=t;else break}for(h>>=g;h>0;){var y=a[r].s;p[y]<t?h-=1<<t-p[y]++-1:++r}for(;r>=0&&h;--r){var b=a[r].s;p[b]==t&&(--p[b],++h)}m=t}return{t:new q(p),l:m}},ha=function(e,t,n){return e.s==-1?Math.max(ha(e.l,t,n+1),ha(e.r,t,n+1)):t[e.s]=n},ga=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new J(++t),r=0,i=e[0],a=1,o=function(e){n[r++]=e},s=1;s<=t;++s)if(e[s]==i&&s!=t)++a;else{if(!i&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(i),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(i);a=1,i=e[s]}return{c:n.subarray(0,r),n:t}},_a=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},va=function(e,t,n){var r=n.length,i=ca(t+2);e[i]=r&255,e[i+1]=r>>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var a=0;a<r;++a)e[i+a+4]=n[a];return(i+4+r)*8},ya=function(e,t,n,r,i,a,o,s,c,l,u){fa(t,u++,n),++i[256];for(var d=ma(i,15),f=d.t,p=d.l,m=ma(a,15),h=m.t,g=m.l,_=ga(f),v=_.c,y=_.n,b=ga(h),x=b.c,S=b.n,C=new J(19),w=0;w<v.length;++w)++C[v[w]&31];for(var w=0;w<x.length;++w)++C[x[w]&31];for(var T=ma(C,7),E=T.t,ee=T.l,D=19;D>4&&!E[Yi[D-1]];--D);var te=l+5<<3,O=_a(i,ia)+_a(a,aa)+o,k=_a(i,f)+_a(a,h)+o+14+3*D+_a(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&te<=O&&te<=k)return va(t,u,e.subarray(c,c+l));var ne,A,j,re;if(fa(t,u,1+(k<O)),u+=2,k<O){ne=ra(f,p,0),A=f,j=ra(h,g,0),re=h;var ie=ra(E,ee,0);fa(t,u,y-257),fa(t,u+5,S-1),fa(t,u+10,D-4),u+=14;for(var w=0;w<D;++w)fa(t,u+3*w,E[Yi[w]]);u+=3*D;for(var M=[v,x],ae=0;ae<2;++ae)for(var oe=M[ae],w=0;w<oe.length;++w){var se=oe[w]&31;fa(t,u,ie[se]),u+=E[se],se>15&&(fa(t,u,oe[w]>>5&127),u+=oe[w]>>12)}}else ne=oa,A=ia,j=sa,re=aa;for(var w=0;w<s;++w){var N=r[w];if(N>255){var se=N>>18&31;pa(t,u,ne[se+257]),u+=A[se+257],se>7&&(fa(t,u,N>>23&31),u+=qi[se]);var ce=N&31;pa(t,u,j[ce]),u+=re[ce],ce>3&&(pa(t,u,N>>5&8191),u+=Ji[ce])}else pa(t,u,ne[N]),u+=A[N]}return pa(t,u,ne[256]),u+A[256]},ba=/*#__PURE__*/ new Ki([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),xa=/*#__PURE__*/ new q(0),Sa=function(e,t,n,r,i,a){var o=a.z||e.length,s=new q(r+o+5*(1+Math.ceil(o/7e3))+i),c=s.subarray(r,s.length-i),l=a.l,u=(a.r||0)&7;if(t){u&&(c[0]=a.r>>3);for(var d=ba[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new J(32768),g=a.h||new J(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new Ki(25e3),x=new J(288),S=new J(32),C=0,w=0,T=a.i||0,E=0,ee=a.w||0,D=0;T+2<o;++T){var te=y(T),O=T&32767,k=g[te];if(h[O]=k,g[te]=O,ee<=T){var ne=o-T;if((C>7e3||E>24576)&&(ne>423||!l)){u=ya(e,c,0,b,x,S,w,E,D,T-D,u),E=C=w=0,D=T;for(var A=0;A<286;++A)x[A]=0;for(var A=0;A<30;++A)S[A]=0}var j=2,re=0,ie=p,M=O-k&32767;if(ne>2&&te==y(T-M))for(var ae=Math.min(f,ne)-1,oe=Math.min(32767,T),se=Math.min(258,ne);M<=oe&&--ie&&O!=k;){if(e[T+j]==e[T+j-M]){for(var N=0;N<se&&e[T+N]==e[T+N-M];++N);if(N>j){if(j=N,re=M,N>ae)break;for(var ce=Math.min(M,N-2),le=0,A=0;A<ce;++A){var ue=T-M+A&32767,de=ue-h[ue]&32767;de>le&&(le=de,k=ue)}}}O=k,k=h[O],M+=O-k&32767}if(re){b[E++]=268435456|Qi[j]<<18|ea[re];var fe=Qi[j]&31,pe=ea[re]&31;w+=qi[fe]+Ji[pe],++x[257+fe],++S[pe],ee=T+j,++C}else b[E++]=e[T],++x[e[T]]}}for(T=Math.max(T,ee);T<o;++T)b[E++]=e[T],++x[e[T]];u=ya(e,c,l,b,x,S,w,E,D,T-D,u),l||(a.r=u&7|c[u/8|0]<<3,u-=7,a.h=g,a.p=h,a.i=T,a.w=ee)}else{for(var T=a.w||0;T<o+l;T+=65535){var me=T+65535;me>=o&&(c[u/8|0]=l,me=o),u=va(c,u+1,e.subarray(T,me))}a.i=o}return la(s,0,r+ca(u)+i)},Ca=/*#__PURE__*/ (function(){for(var e=/* @__PURE__ */ new Int32Array(256),t=0;t<256;++t){for(var n=t,r=9;--r;)n=(n&1&&-306674912)^n>>>1;e[t]=n}return e})(),wa=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=Ca[n&255^t[r]]^n>>>8;e=n},d:function(){return~e}}},Ta=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new q(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return Sa(e,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,r,i)},Ea=function(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n},X=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8},Da=function(e,t,n,r){for(var i in e){var a=e[i],o=t+i,s=r;Array.isArray(a)&&(s=Ea(r,a[1]),a=a[0]),ArrayBuffer.isView(a)?n[o]=[a,s]:(n[o+=`/`]=[new q(0),s],Da(a,o,n,r))}},Oa=typeof TextEncoder<`u`&&/*#__PURE__*/ new TextEncoder,ka=typeof TextDecoder<`u`&&/*#__PURE__*/ new TextDecoder;try{ka.decode(xa,{stream:!0})}catch{}Aa=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&da(9),t+=r+4}return t},ja=function(e,t,n,r,i,a,o,s){var c=r.length,l=n.extra,u=s&&s.length,d=Aa(l);X(e,t,o==null?67324752:33639248),t+=4,o!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(a<0&&8),e[t++]=i&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var f=new Date(n.mtime==null?Date.now():n.mtime),p=f.getFullYear()-1980;if((p<0||p>119)&&da(10),X(e,t,p<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,a!=-1&&(X(e,t,n.crc),X(e,t+4,a<0?-a-2:a),X(e,t+8,n.size)),X(e,t+12,c),X(e,t+14,d),t+=16,o!=null&&(X(e,t,u),X(e,t+6,n.attrs),X(e,t+10,o),t+=14),e.set(r,t),t+=c,d)for(var m in l){var h=l[m],g=h.length;X(e,t,+m),X(e,t+2,g),e.set(h,t+4),t+=4+g}return u&&(e.set(s,t),t+=u),t},Ma=function(e,t,n,r,i){X(e,t,101010256),X(e,t+8,n),X(e,t+10,n),X(e,t+12,r),X(e,t+16,i)}}));async function Pa(e,t){await n.mkdir(s.dirname(t),{recursive:!0}),await n.writeFile(t,Ui(Yr(e)))}async function Fa(e,t,n){await Pa(await qr(await Gr(e),n),t)}async function Ia(e,t,n,r){await Pa(await qr(await Kr(e,t),r),n)}async function La(e,t){let n={};for(let t of e){let e=await qr(await Kr(t.source,t.items),t.transform);Object.assign(n,Jr(e,s.basename(s.resolve(t.source))))}await Pa(n,t)}async function Ra(e,t,n){let r={};for(let t of e){let e=await qr(await Kr(t.source,t.items),t.transform);Object.assign(r,Jr(e,s.basename(s.resolve(t.source))))}for(let e of t){let t=await qr(await Gr(e.dir),e.transform);Object.assign(r,Jr(t,s.basename(s.resolve(e.dir))))}await Pa(r,n)}var za=te((()=>{Na(),Zr()})),Ba=/* @__PURE__ */ k({packMcpack:()=>Va});async function Va(e,t,n,r=!1,i){let a=s.join(t,`${n}.mcpack`);return r||await Fa(e,a,i),a}var Ha=te((()=>{za()}));za();function Ua(e,t,n){let r=s.resolve(e),i=s.resolve(t),a=s.relative(i,r);if(a&&!a.startsWith(`..`)&&!s.isAbsolute(a))throw new F(`PACK_FAILED`,`pack output must not be inside ${n} directory.`,{details:{output:r,dir:i},suggestions:[`Set pack.outDir to a path outside ${n}: ${i}`]})}function Wa(e,t,n){let r=s.resolve(e),i=s.resolve(t);for(let e of n){let t=s.resolve(i,e),n=s.relative(t,r);if(n===``||!n.startsWith(`..${s.sep}`)&&n!==`..`&&!s.isAbsolute(n))throw new F(`PACK_FAILED`,`pack output must not be included in the BP archive.`,{details:{output:r,includedPath:t},suggestions:[`Set pack.outDir outside the selected BP include path: ${t}`]})}}function Ga(e,t){let n=s.relative(s.resolve(t),s.resolve(e));if(n.startsWith(`..`)||s.isAbsolute(n))throw new F(`PACK_FAILED`,`pack output name must stay inside pack.outDir.`,{details:{output:s.resolve(e),dist:s.resolve(t)}})}function Ka(e,t){if(t===`bp`)return{items:Bt(e),selective:!0};let n=e.packs.rp?.include??[],r=e.copy.include?.rp??[],i=n.length>0?n:r;return i.length>0?{items:[...At,...i],selective:!0}:{items:[],selective:!1}}async function qa(e,t,n={}){let r=V(e,t),i=(n.name??t.pack.name).replaceAll(`{name}`,t.name).replaceAll(`{version}`,t.version),a=Ut(e,t);if(Ot(t).length===0)throw new F(`PACK_FAILED`,`No packs configured. At least one pack is required.`);let o=n.optimize===void 0?t.pack.optimize:n.optimize?t.pack.optimize??Tt:void 0,c=o?xi(o,n.logger):void 0,l=t.packs.bp?{root:H(r,t,`bp`),config:t}:void 0,u=t.packs.rp?{root:H(r,t,`rp`),config:t}:void 0,d=l?Ka(t,`bp`):void 0;if(l&&d?.selective&&await ki({...n.logger?{logger:n.logger}:{},packType:`bp`,root:l.root,items:d.items,action:`pack`,cwd:e,ignore:Ei(e,t,`bp`)}),u){let r=Ka(t,`rp`);r.selective&&await ki({...n.logger?{logger:n.logger}:{},packType:`rp`,root:u.root,items:r.items,action:`pack`,cwd:e,ignore:Ei(e,t,`rp`)})}if(l&&u){if(!d)throw new F(`PACK_FAILED`,`BP pack configuration is missing.`);let e=s.join(a,`${i}.mcaddon`);if(Ga(e,a),d?.selective&&Wa(e,l.root,d.items),Ua(e,u.root,`RP`),!n.dryRun){let n=Ka(t,`rp`);n.selective?await La([{source:l.root,items:d.items,...c?{transform:c}:{}},{source:u.root,items:n.items,...c?{transform:c}:{}}],e):await Ra([{source:l.root,items:d.items,...c?{transform:c}:{}}],[{dir:u.root,...c?{transform:c}:{}}],e)}return e}if(l){if(!d)throw new F(`PACK_FAILED`,`BP pack configuration is missing.`);let e=s.join(a,`${i}.mcpack`);return Ga(e,a),d?.selective&&Wa(e,l.root,d.items),n.dryRun||await Ia(l.root,d.items,e,c),e}if(u){let e=s.join(a,`${i}.mcpack`);if(Ga(e,a),Ua(e,u.root,`RP`),!n.dryRun){let r=Ka(t,`rp`);if(r.selective)await Ia(u.root,r.items,e,c);else{let{packMcpack:e}=await Promise.resolve().then(()=>(Ha(),Ba));return await e(u.root,a,i,n.dryRun,c)}}return e}throw new F(`PACK_FAILED`,`No packs configured.`)}async function Ja(e,t,n,r={}){let i=Date.now();await G(`beforePack`,`pack`,e,t,n,{dryRun:!!r.dryRun});let a=await qa(e,t,{...r,logger:n});await G(`afterPack`,`pack`,e,t,n,{dryRun:!!r.dryRun});let o=Date.now()-i;return n.done(`pack`,r.dryRun?`dry-run: would pack ${a} (no file written)`:`packed ${a} in ${n.formatDuration(o)}`),{output:a,durationMs:o,dryRun:!!r.dryRun}}async function Ya(e){let t=new L({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await In({cwd:e.cwd??process.cwd(),configPath:e.config}),i=e.build===!1||!!e.skipBuild,a=null;if(!i){let i=e.skipTypecheck?!1:e.typecheck?!0:r.packs.bp?.compile?.typecheck,o=e.cache===void 0?r.packs.bp?.compile?.cache.build??!1:!!e.cache,s=e.typecheckCommand;a=await Wr({cwd:n,config:r,logger:t,command:`build`,...i===void 0?{}:{typecheck:i},...s===void 0?{}:{typecheckCommand:s},...e.cache===void 0?{}:{cache:o},dryRun:!!e.dryRun,quiet:!!(e.json||e.silent),...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{}})}let{output:o,durationMs:s}=await Ja(n,r,t,{name:e.name,dryRun:e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}});return{ok:!0,command:`pack`,durationMs:s,output:o,built:!i,build:a}}function Xa(e){for(let t of[[`copy`,`skipCopy`],[`pack`,`skipPack`],[`typecheck`,`skipTypecheck`],[`install`,`skipInstall`]]){let[n,r]=t;if(e[n]&&e[r])throw new F(`CLI_ARGUMENT_CONFLICT`,`--${n} and --${r} cannot be used together.`)}}async function Za(e){Xa(e);let t=new L({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{target:e.target,...e.timing===void 0?{}:{build:{timing:e.timing}}}});t.bepack(`build`,`target ${r.target}`);let i;if(e.install){let t=await rr({...e,cwd:n,config:void 0,silent:e.silent||e.json});i=Object.fromEntries(Object.entries(t.resolved).filter(([,e])=>e.manifestVersion!==null).map(([e,t])=>[e,t.manifestVersion]))}let a=r.packs.bp?.compile,o=e.skipTypecheck?!1:e.typecheck?!0:a?.typecheck??!1,s=e.typecheckCommand,c=e.cache===void 0?a?.cache.build??!1:e.cache,l=await Wr({cwd:n,config:r,logger:t,mode:e.mode,command:`build`,...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},typecheck:!!o,...s===void 0?{}:{typecheckCommand:s},...e.useNpx?{useNpx:!0}:{},cache:!!c,dryRun:!!e.dryRun,quiet:!!(e.json||e.silent),...i?{resolvedDeps:i}:{}}),u=null,d=e.skipCopy?!1:e.copy||e.copyTarget?!0:r.build.copy;d&&(u=await Bi({command:`build`,cwd:n,config:r,logger:t,...e.mode===void 0?{}:{mode:e.mode},targetName:e.copyTarget??(typeof d==`string`?d:void 0),dryRun:!!e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}}));let f=null;return!e.skipPack&&e.pack&&(f=await Ja(n,r,t,{name:e.name,dryRun:e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}})),t.done(`build`,`complete in ${t.formatDuration(l.durationMs)}`),{ok:!0,command:`build`,durationMs:l.durationMs,build:l,copy:u,pack:f}}async function Qa(e){let t=Date.now(),n=new L({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config});await G(`beforeCopy`,`copy`,r,i,n,{dryRun:!!e.dryRun});let a=e.all?[`win`,`winold`,...Object.keys(i.copy.targets)]:[e.target??i.copy.defaultTarget],o={...e.optimize===void 0?{}:{optimize:!!e.optimize}},s=[];for(let t of a)s.push(await zi(r,i,t,e.dryRun,n,o));await G(`afterCopy`,`copy`,r,i,n,{dryRun:!!e.dryRun});let c=Date.now()-t;return n.done(`copy`,`${e.dryRun?`dry-run complete`:`complete`} in ${n.formatDuration(c)}`),{ok:!0,command:`copy`,durationMs:c,results:s}}const $a=/[/\\]rolldown\.config\.[A-Za-z0-9_-]+\.js$/;function eo(e,t){return B(s.relative(e,t))}function to(e,t,n,r){let i=V(e,t),a=Pt(t),o=[];if(a){let n=U(e,t);n&&o.push(eo(e,s.dirname(n)))}if(r.copy){for(let n of Ot(t))if(H(i,t,n.type)){let r=no(e,t,n.type,i);o.push(...r)}}let c=t.dev.watch?.include??[];o.push(...c);let l=Gt(o.map(t=>s.resolve(e,t))).map(t=>eo(e,t));if(l.length===0)throw new F(`DEV_NO_WATCH_TARGETS`,`Nothing to watch: no compile entry, no copy-enabled pack directories and no dev.watch.include paths.`,{suggestions:[`Configure packs.bp.compile.entry to watch TypeScript sources.`,"Enable copying (packs.rp/bp, dev.copy or `bepack dev --copy`) to watch pack folders.",`Add paths explicitly with dev.watch.include.`]});let u=[`node_modules`,`.git`,eo(e,Ut(e,t))];for(let n of Ot(t)){let r=H(i,t,n.type);if(r&&(u.push(eo(e,s.join(r,`manifest.json`))),n.type===`bp`&&a)){let n=H(i,t,`bp`),r=t.packs.bp.compile.scriptOutputDir;u.push(eo(e,s.join(n,r)))}}let d=S.watch(l,{cwd:e,ignored:[...u,$a],ignoreInitial:!0}),f=!1,p=!1,m=!1,h=async()=>{r.copy&&await Bi({command:`dev`,cwd:e,config:t,logger:n,targetName:r.copyTarget,dryRun:r.dryRun,...r.mode===void 0?{}:{mode:r.mode},...r.optimize===void 0?{}:{optimize:r.optimize}})},g=async()=>{await er({cwd:e,config:t,command:`dev`,dryRun:r.dryRun,logger:n,...r.mode===void 0?{}:{mode:r.mode}}),await h()},_=async()=>{a?await Wr({cwd:e,config:t,logger:n,command:`dev`,typecheck:r.typecheck,cache:r.cache,dryRun:r.dryRun,quiet:!!r.quiet,...r.mode===void 0?{}:{mode:r.mode},...r.typecheckCommand===void 0?{}:{typecheckCommand:r.typecheckCommand},...r.rolldownConfig===void 0?{}:{rolldownConfig:r.rolldownConfig}}):await er({cwd:e,config:t,command:`dev`,dryRun:r.dryRun,logger:n,...r.mode===void 0?{}:{mode:r.mode}}),await h()},v=async()=>{for(;p||m;){let e=p;p=!1,m=!1;let t=Date.now();try{n.clear(),e?(n.bepack(`dev`,`rebuilding (pending changes)`),await _(),n.done(`dev`,`rebuild done in ${n.formatDuration(Date.now()-t)}`)):await g()}catch(e){n.error(e instanceof Error?e.message:String(e))}}};d.on(`all`,async(r,i)=>{let o=B(i),c=a?U(e,t):void 0,l=c?s.dirname(c):void 0,u=s.resolve(e,o),d=l?u===l||u.startsWith(l+s.sep):!1;if(f){d?p=!0:m=!0;return}f=!0;let h=Date.now();try{n.clear(),n.bepack(`dev`,`changed ${s.normalize(i)}`),d&&a?await _():await g(),n.done(`dev`,`updated after ${s.normalize(i)} in ${n.formatDuration(Date.now()-h)}`)}catch(e){n.error(e instanceof Error?e.message:String(e))}finally{try{await v()}finally{f=!1}}});let y=t.packs.bp?B(s.relative(e,H(i,t,`bp`))):null,b=t.packs.rp?B(s.relative(e,H(i,t,`rp`))):null,x=a&&U(e,t)?eo(e,s.dirname(U(e,t))):null,C=!1,w=[],T=0,E=0;for(let e of l)y&&(e===y||e.startsWith(y+`/`))?(T++,x&&(e===x||e.startsWith(x+`/`))&&(C=!0)):b&&(e===b||e.startsWith(b+`/`))?(E++,x&&(e===x||e.startsWith(x+`/`))&&(C=!0)):x&&(e===x||e.startsWith(x+`/`))||w.push(e);return x&&!C&&w.unshift(x),T>0&&w.push(`bp(${T})`),E>0&&w.push(`rp(${E})`),n.progress(`dev`,`watching ${w.join(`, `)}`),d}function no(e,t,n,r){let i=H(r,t,n);if(!i)return[];if(n===`bp`)return Bt(t).filter(e=>e!==`manifest.json`).map(t=>B(s.relative(e,s.join(i,t))));let a=t.packs.rp;return a?a.include&&a.include.length>0?a.include.filter(e=>e!==`manifest.json`).map(t=>B(s.relative(e,s.join(i,t)))):[B(s.relative(e,i))]:[]}async function ro(e){let t=Date.now(),n=new L({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{...e.timing===void 0?{}:{build:{timing:e.timing}}}});n.clear(),n.bepack(`dev`,`target ${i.target}`),n.progress(`dev`,`initial build started`);let a=i.packs.bp?.compile,o=e.skipTypecheck?!1:e.typecheck?!0:a?.typecheck??!1,s=e.typecheckCommand,c=!e.skipCopy&&!!(e.copy||e.copyTarget||i.dev.copy),l=e.copyTarget??(typeof i.dev.copy==`string`?i.dev.copy:void 0),u=a?.cache.dev??!0,d=!!e.dryRun,f=!!(e.json||e.silent),p=e.optimize===void 0?{}:{optimize:!!e.optimize};return await Wr({cwd:r,config:i,logger:n,mode:e.mode,command:`dev`,...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},typecheck:!!o,...s===void 0?{}:{typecheckCommand:s},cache:u,dryRun:d,quiet:f}),c&&await Bi({command:`dev`,cwd:r,config:i,logger:n,targetName:l,dryRun:d,...e.mode===void 0?{}:{mode:e.mode},...p}),n.done(`dev`,`initial build complete in ${n.formatDuration(Date.now()-t)}`),to(r,i,n,{copy:c,mode:e.mode,...l?{copyTarget:l}:{},...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},...p,typecheck:!!o,...s===void 0?{}:{typecheckCommand:s},cache:u,dryRun:d,quiet:f}),{ok:!0,command:`dev`,initialBuildDurationMs:Date.now()-t}}function io(e){let t=/* @__PURE__ */ new WeakSet;function n(e){if(typeof e==`function`)return`[function]`;if(e instanceof RegExp)return e.toString();if(typeof e!=`object`||!e)return e;if(t.has(e))return`[circular]`;t.add(e);let r=Array.isArray(e)?e.map(n):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)]));return t.delete(e),r}return n(e)}async function ao(e){let t=new L({...e,silent:e.silent||e.json}),{cwd:n,config:r,path:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config});if(e.json)return{cwd:n,configFile:i,config:io(r)};if(e.summary){t.bepack(`config`,i),t.info(`root: ${r.root}`),t.info(`name: ${r.name}`),t.info(`version: ${r.version}`),r.description&&t.info(`description: ${r.description}`),t.info(`target: ${r.target}`);let e=[];if(r.packs.bp&&e.push(`bp`),r.packs.rp&&e.push(`rp`),t.info(`packs: ${e.join(`, `)}`),r.packs.bp?.compile){let e=r.packs.bp.compile;t.info(`compile.entry: ${e.entry}`),t.info(`compile.scriptOutputDir: ${e.scriptOutputDir}`),t.info(`compile.preserveModules: ${e.preserveModules}`),t.info(`compile.typecheck: ${e.typecheck}`),e.typecheckCommand&&t.info(`compile.typecheckCommand: ${e.typecheckCommand}`),e.typecheckArgs.length>0&&t.info(`compile.typecheckArgs: [${e.typecheckArgs.join(`, `)}]`),e.external.length>0&&t.info(`compile.external: [${e.external.map(e=>typeof e==`string`?e:e.toString()).join(`, `)}]`)}let n=Object.keys(r.hooks);n.length>0?t.info(`hooks: ${n.join(`, `)}`):t.info(`hooks: (none)`);let a=r.plugins??[];if(a.length>0){t.info(`plugins: ${a.map(e=>`${e.name} (priority ${e.priority??0})`).join(`, `)}`);for(let e of r.pluginDiagnostics??[])t.warn(`plugin conflict: ${e}`)}else t.info(`plugins: (none)`);t.info(`install.registry: ${r.install.registry}`);let o=Object.keys(Ln(r));return o.length>0?t.info(`install.dependencyCatalog: ${o.join(`, `)}`):t.info(`install.dependencyCatalog: (none)`),t.info(`pack.outDir: ${r.pack.outDir}`),r.copy.defaultTarget&&t.info(`copy.defaultTarget: ${r.copy.defaultTarget}`),r.build.copy&&t.info(`build.copy: ${r.build.copy}`),r.dev.copy&&t.info(`dev.copy: ${r.dev.copy}`),{ok:!0,command:`config`}}let a=io(r),o=JSON.stringify(a,null,2);return t.bepack(`config`,i),t.info(`cwd: ${n}`),t.info(`configFile: ${i}`),t.info(``),t.info(o),{ok:!0,command:`config`}}function Z(e,t,n){throw new F(`PROFILE_INVALID`,`${e}: ${t}`,{...n===void 0?{}:{details:n},suggestions:[`Check that the file was produced by a V8 profiler and is valid JSON.`]})}function oo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function so(e,t,n){return(typeof e!=`number`||!Number.isFinite(e))&&Z(n,`${t} must be a finite number`),e}function co(e,t,n){let r=so(e,t,n);return Number.isInteger(r)||Z(n,`${t} must be an integer`),r}function lo(e,t,n,r){let i=e[t];if(i!==void 0)return so(i,`${n}.${t}`,r)}function uo(e,t,n,r){let i=e[t];if(i!==void 0)return co(i,`${n}.${t}`,r)}function fo(e,t,n){oo(e)||Z(n,`${t} must be an object`);let r=e.functionName??``;typeof r!=`string`&&Z(n,`${t}.functionName must be a string`);let i=e.url??``;typeof i!=`string`&&Z(n,`${t}.url must be a string`);let a=e.scriptId,o;a===void 0?o=`0`:typeof a==`number`&&Number.isFinite(a)?o=String(a):typeof a==`string`?o=a:Z(n,`${t}.scriptId must be a string`);let s=e.lineNumber??-1;(typeof s!=`number`||!Number.isFinite(s))&&Z(n,`${t}.lineNumber must be a finite number`);let c=e.columnNumber??-1;return(typeof c!=`number`||!Number.isFinite(c))&&Z(n,`${t}.columnNumber must be a finite number`),{functionName:r,scriptId:o,url:i,lineNumber:s,columnNumber:c}}function po(e,t,n){let r=`nodes[${t}]`;oo(e)||Z(n,`${r} must be an object`);let i=co(e.id,`${r}.id`,n),a=fo(e.callFrame,`${r}.callFrame`,n),o=uo(e,`hitCount`,r,n),s=uo(e,`locationId`,r,n),c;return e.children!==void 0&&(Array.isArray(e.children)||Z(n,`${r}.children must be an array`),c=e.children.map((e,t)=>co(e,`${r}.children[${t}]`,n))),{id:i,callFrame:a,...o===void 0?{}:{hitCount:o},...c===void 0?{}:{children:c},...s===void 0?{}:{locationId:s}}}function mo(e,t=`<profile>`){oo(e)||Z(t,`profile root must be a JSON object`),Array.isArray(e.nodes)||Z(t,`missing nodes array`),Array.isArray(e.samples)||Z(t,`missing samples array`),Array.isArray(e.timeDeltas)||Z(t,`missing timeDeltas array`);let n=e.nodes.map((e,n)=>po(e,n,t)),r=/* @__PURE__ */ new Set;for(let e of n)r.has(e.id)&&Z(t,`duplicate node id ${e.id}`),r.add(e.id);for(let e of n)for(let n of e.children??[])r.has(n)||Z(t,`node ${e.id} references unknown child node ${n}`);e.timeDeltas.length!==e.samples.length&&Z(t,`samples and timeDeltas must have the same length (${e.samples.length} != ${e.timeDeltas.length})`);let i=e.samples.map((e,n)=>{let i=co(e,`samples[${n}]`,t);return r.has(i)||Z(t,`samples[${n}] references unknown node ${i}`),i}),a=e.timeDeltas.map((e,n)=>{let r=so(e,`timeDeltas[${n}]`,t);return r<0&&Z(t,`timeDeltas[${n}] must not be negative`),r}),o=lo(e,`startTime`,`profile`,t),s=lo(e,`endTime`,`profile`,t);return{nodes:n,samples:i,timeDeltas:a,...o===void 0?{}:{startTime:o},...s===void 0?{}:{endTime:s}}}function ho(e,t,n){let r=[],i=/* @__PURE__ */ new Set,a=e.id;for(;a!==void 0&&!i.has(a);){i.add(a);let e=n.get(a);if(!e)break;r.push(e),a=t.get(a)}return r}function go(e){let t=e[0],n=e[e.length-1];if(!t||!n)throw Error(`cannot create a burst from an empty sample run`);let r=e.reduce((e,t)=>e+t.deltaMs,0);return{startMs:t.timeMs,endMs:n.timeMs,spanMs:n.timeMs-t.timeMs,busyMs:r,samples:e.length,run:e}}function _o(e,t){let n=[],r=[];for(let i of e){if(i.active){r.push(i);continue}r.length>0&&r.length>=t&&n.push(go(r)),r=[]}return r.length>0&&r.length>=t&&n.push(go(r)),n}function vo(e,t,n){let r=mo(e,t),i=n.gapMs??5,a=n.minSamples??20,o=new Map(r.nodes.map(e=>[e.id,e])),s=/* @__PURE__ */ new Map;for(let e of r.nodes)for(let t of e.children??[])s.set(t,e.id);let c=i*1e3,l=0,u=[];for(let e=0;e<r.samples.length;e++){let t=r.timeDeltas[e]??0;l+=t;let n=o.get(r.samples[e]??-1);n&&u.push({index:e,timeMs:l/1e3,deltaMs:t/1e3,active:t<=c,node:n,stack:ho(n,s,o)})}let d=u.filter(e=>e.active),f=u.filter(e=>!e.active);return{file:t,raw:r,samples:u,activeSamples:d,gapSamples:f,busyMs:d.reduce((e,t)=>e+t.deltaMs,0),idleMs:f.reduce((e,t)=>e+t.deltaMs,0),durationMs:l/1e3,gapMs:i,minSamples:a,bursts:_o(u,a)}}async function yo(e,t={}){let n;try{n=await v(e,`utf8`)}catch(t){throw new F(`PROFILE_READ_FAILED`,`Cannot read profile ${e}: ${t instanceof Error?t.message:String(t)}`,{details:{file:e},suggestions:[`Check the path and that the file is readable.`]})}let r;try{r=JSON.parse(n)}catch(t){Z(e,`not valid JSON: ${t instanceof Error?t.message:String(t)}`)}return vo(r,e,t)}function bo(e){let t=e.callFrame;return`${t.functionName||`(anonymous)`}\u0000${t.url||`(unknown)`}\u0000${t.lineNumber}`}function xo(e,{by:t,gapMs:n}){let r=/* @__PURE__ */ new Map,i=0,a=0;for(let o of e){if(o.deltaMs>n)continue;if(i++,a+=o.deltaMs,t===`self`){let e=o.stack[0];if(!e)continue;let t=bo(e),n=r.get(t)??{node:e,count:0};n.count++,r.set(t,n);continue}let e=/* @__PURE__ */ new Set;for(let t of o.stack){let n=bo(t);if(e.has(n))continue;e.add(n);let i=r.get(n)??{node:t,count:0};i.count++,r.set(n,i)}}return{rows:[...r.values()].map(e=>({node:e.node,count:e.count,share:i===0?0:e.count/i,ms:i===0?0:a*e.count/i})).sort((e,t)=>t.count-e.count||e.node.callFrame.functionName.localeCompare(t.node.callFrame.functionName)),active:i,busyMs:a}}function So(e,t,n){let r=/* @__PURE__ */ new Map,i=0,a=0;for(let n of e){if(n.deltaMs>t)continue;i++,a+=n.deltaMs;let e=n.stack.map(e=>bo(e)).join(`
11
+ `),o=r.get(e)??{sample:n,count:0};o.count++,r.set(e,o)}return[...r.values()].sort((e,t)=>t.count-e.count).slice(0,n).map(e=>({sample:e.sample,count:e.count,share:i===0?0:e.count/i,ms:i===0?0:a*e.count/i}))}function Co(e){return e.bursts.reduce((e,t)=>e?t.samples===e.samples?t.busyMs>e.busyMs?t:e:t.samples>e.samples?t:e:t,void 0)}function Q(e){return e>=1e3?`${(e/1e3).toFixed(2)} s`:`${e.toFixed(1)} ms`}function wo(e){return`${(e*100).toFixed(1)}%`}function To(e,t){let n=e.callFrame,r=n.url||`(unknown)`,i=r.replace(/\\/g,`/`),a=t.replace(/\\/g,`/`).replace(/\/+$/,``),o=process.platform===`win32`?i.toLowerCase():i,s=[a];process.platform===`win32`&&/^[a-z]:/i.test(a)&&s.push(a.slice(2));let c=s.find(e=>{let t=process.platform===`win32`?e.toLowerCase():e;return o===t||t!==`/`&&o.startsWith(`${t}/`)||t===`/`&&o.startsWith(`/`)});return r=c===`/`?i.slice(1):c?o===(process.platform===`win32`?c.toLowerCase():c)?`.`:i.slice(c.length+1):!a&&i.startsWith(`/`)?i.slice(1):i,{functionName:n.functionName||`(anonymous)`,url:r,line:n.lineNumber>=0?n.lineNumber+1:null}}function Eo(e){return`${e.functionName} ${e.url}${e.line===null?``:`:${e.line}`}`}function Do(e){return Eo(e)}function Oo(e,t){return{...To(e.node,t),count:e.count,share:e.share,ms:e.ms}}function ko(e,t){return e.sample.stack.map(e=>{let n=To(e,t);return`${n.functionName} (${n.url}${n.line===null?``:`:${n.line}`})`}).join(` <- `)}function Ao(e,t){return{count:e.count,share:e.share,ms:e.ms,stack:ko(e,t),frames:e.sample.stack.map(e=>{let n=To(e,t);return`${n.functionName} (${n.url}${n.line===null?``:`:${n.line}`})`})}}function jo(e,t){return`${t}${String(e.count).padStart(4)} ${wo(e.share).padStart(6)} ${Q(e.ms).padStart(9)} ${Do(e)}`}function Mo(e,t){return`${t}${String(e.count).padStart(4)} ${wo(e.share).padStart(6)} ${Q(e.ms).padStart(9)} ${e.stack}`}function No(e,t=``){return`${t}${e.startMs.toFixed(1)}-${e.endMs.toFixed(1)} ms | ${e.samples} samples | span ${Q(e.spanMs)} | busy ${Q(e.busyMs)}`}function Po(e,t,n){return{startMs:t.startMs,endMs:t.endMs,spanMs:t.spanMs,busyMs:t.busyMs,samples:t.samples,topSelf:xo(t.run,{by:`self`,gapMs:e.gapMs}).rows.slice(0,n.limit).map(e=>Oo(e,n.root)),topStacks:So(t.run,e.gapMs,n.stacks).map(e=>Ao(e,n.root))}}function Fo(e,t){let n=e.map(e=>{let n=[...e.bursts].sort((e,t)=>t.busyMs-e.busyMs).map(n=>Po(e,n,{limit:t.limit,stacks:0,root:t.root}));return{file:e.file,durationMs:e.durationMs,samples:e.samples.length,activeSamples:e.activeSamples.length,busyMs:e.busyMs,idleMs:e.idleMs,gapMs:e.gapMs,minSamples:e.minSamples,bursts:n}});return{text:n.map(e=>{let t=[`profile: ${e.file}`,`duration: ${Q(e.durationMs)} | samples: ${e.samples} | active: ${e.activeSamples} (${Q(e.busyMs)}) | gaps: ${e.samples-e.activeSamples} (${Q(e.idleMs)})`,`gap threshold: ${e.gapMs} ms | bursts: ${e.bursts.length} (>= ${e.minSamples} samples)`];for(let n of e.bursts){t.push(` @ ${No(n)}`);for(let e of n.topSelf)t.push(jo(e,` `))}return t.join(`
12
+ `)}).join(`
13
+ `),data:{profiles:n}}}function Io(e,t){let n=e.map(e=>{let n=e.bursts.map(n=>Po(e,n,t)),r=e.bursts.map(e=>e.startMs);return{file:e.file,minSamples:e.minSamples,bursts:n,intervals:r.slice(1).map((e,t)=>e-(r[t]??e))}});return{text:n.map(e=>{if(e.bursts.length===0)return[`profile: ${e.file}`,`no bursts with >= ${e.minSamples} active samples`].join(`
14
+ `);let t=[];for(let[n,r]of e.bursts.entries()){t.push(`burst #${n+1}: ${No(r)}`),t.push(` top self:`);for(let e of r.topSelf)t.push(jo(e,` `));t.push(` top stacks:`);for(let e of r.topStacks)t.push(Mo(e,` `));t.push(``)}return e.bursts.length>1&&t.push(`burst intervals: ${e.intervals.map(e=>e.toFixed(1)).join(`, `)} ms`),t.join(`
15
+ `)}).join(`
16
+ `),data:{profiles:n}}}function Lo(e,t){let{rows:n,active:r,busyMs:i}=xo(e.samples.filter(e=>!(t.fromMs!==void 0&&e.timeMs<t.fromMs||t.toMs!==void 0&&e.timeMs>t.toMs)),{by:t.by,gapMs:e.gapMs}),a=n.slice(0,t.limit).map(e=>Oo(e,t.root)),o=t.fromMs===void 0&&t.toMs===void 0?`whole profile`:`${t.fromMs??0}-${t.toMs??`end`} ms`;return{text:[`profile: ${e.file}`,`window: ${o} | active: ${r} samples | busy: ${Q(i)} | by: ${t.by}`,...a.map(e=>jo(e,` `))].join(`
17
+ `),data:{profile:{file:e.file,window:{fromMs:t.fromMs??null,toMs:t.toMs??null},by:t.by,activeSamples:r,busyMs:i,rows:a}}}}function Ro(e){return{startMs:e.startMs,endMs:e.endMs,spanMs:e.spanMs,busyMs:e.busyMs,samples:e.samples,topSelf:[],topStacks:[]}}function zo(e){let t=Co(e);return{file:e.file,durationMs:e.durationMs,activeSamples:e.activeSamples.length,busyMs:e.busyMs,bursts:e.bursts.length,largestBurst:t?Ro(t):null}}function Bo(e,t,n){let r=Co(e),i=Co(t),a=r?.run??e.samples,o=i?.run??t.samples,s=new Map(xo(a,{by:`self`,gapMs:e.gapMs}).rows.map(e=>[bo(e.node),e])),c=new Map(xo(o,{by:`self`,gapMs:t.gapMs}).rows.map(e=>[bo(e.node),e])),l=[.../* @__PURE__ */ new Set([...s.keys(),...c.keys()])].map(e=>{let t=s.get(e),n=c.get(e),r=t?.node??n?.node;if(r)return{node:r,before:t?.count??0,after:n?.count??0,delta:(n?.count??0)-(t?.count??0)}}).filter(e=>e!==void 0&&e.delta!==0).sort((e,t)=>Math.abs(t.delta)-Math.abs(e.delta)||t.before-e.before).slice(0,n.limit).map(e=>({...To(e.node,n.root),before:e.before,after:e.after,delta:e.delta})),u=!!(r&&i),d=zo(e),f=zo(t),p=[`before: ${e.file}`,`after: ${t.file}`,`duration: ${Q(e.durationMs)} -> ${Q(t.durationMs)} | active: ${e.activeSamples.length} -> ${t.activeSamples.length} | busy: ${Q(e.busyMs)} -> ${Q(t.busyMs)} | bursts: ${e.bursts.length} -> ${t.bursts.length}`];if(r||i){p.push(`largest burst:`);for(let[e,t]of[[`before`,r],[`after `,i]])p.push(t?` ${e}: ${No(Ro(t))}`:` ${e}: none`)}if(p.push(u?`largest-burst self samples (after - before):`:`active self samples (after - before):`),l.length===0)p.push(` no difference`);else for(let e of l){let t=e.delta>0?`+`:``;p.push(` ${t}${String(e.delta).padStart(4)} ${String(e.before).padStart(4)} -> ${String(e.after).padStart(4)} ${Eo(e)}`)}return{text:p.join(`
18
+ `),data:{before:d,after:f,compared:u?`burst`:`active`,changes:l}}}const Vo=[`summary`,`bursts`,`top`,`diff`];function Ho(e,t=[]){throw new F(`CLI_ARGUMENT_INVALID`,e,{...t.length===0?{}:{suggestions:t}})}function Uo(e,t,n,r){if(e===void 0)return n;let i=typeof e==`number`?e:Number(e);return(!Number.isFinite(i)||i<r.min)&&Ho(`--${t} must be a number >= ${r.min}, got ${JSON.stringify(e)}.`),r.integer&&!Number.isInteger(i)&&Ho(`--${t} must be an integer, got ${JSON.stringify(e)}.`),i}function Wo(e,t){if(e===void 0)return;let n=typeof e==`number`?e:Number(e);return Number.isFinite(n)||Ho(`--${t} must be a number, got ${JSON.stringify(e)}.`),n}function Go(e){if(e&&Vo.includes(e))return e;Ho(`Unknown profile command: ${e??`(none)`}. Expected one of ${Vo.join(`, `)}.`,["Run `bepack profile --help` to see available commands."])}async function Ko(e,t,n){let r=Go(e),i=r===`diff`?2:1;t.length!==i&&Ho(`${r} expects ${i} profile file${i===1?``:`s`}, got ${t.length}.`,[r===`diff`?`Usage: bepack profile diff <before> <after>`:`Usage: bepack profile ${r} <profile>`]);let a=Uo(n.gap,`gap`,5,{min:0}),o=Uo(n.minSamples,`min-samples`,20,{min:1,integer:!0}),c=Uo(n.limit??n.n,`limit`,15,{min:0,integer:!0}),l=Uo(n.stacks,`stacks`,5,{min:0,integer:!0}),u=Wo(n.from,`from`),d=Wo(n.to,`to`),f=n.by??`self`;f!==`self`&&f!==`total`&&Ho(`--by must be self or total, got ${JSON.stringify(n.by)}.`);let p=s.resolve(typeof n.cwd==`string`?n.cwd:process.cwd()),m=s.resolve(p,typeof n.root==`string`?n.root:`.`),h=new L({silent:n.silent||n.json,verbose:n.verbose}),g=t.map(e=>s.resolve(p,e)),_=await Promise.all(g.map(e=>yo(e,{gapMs:a,minSamples:o}))),v={limit:c,root:m};if(r===`summary`){let e=Fo(_,v);return n.json||h.info(e.text),{ok:!0,command:`profile`,mode:r,...e.data}}if(r===`bursts`){let e=Io(_,{...v,stacks:l});return n.json||h.info(e.text),{ok:!0,command:`profile`,mode:r,...e.data}}let y=_[0];if(y||Ho(`top expects one profile file.`),r===`top`){let e=Lo(y,{...v,by:f,...u===void 0?{}:{fromMs:u},...d===void 0?{}:{toMs:d}});return n.json||h.info(e.text),{ok:!0,command:`profile`,mode:r,...e.data}}let b=_[1];b||Ho(`diff expects two profile files.`);let x=Bo(y,b,v);return n.json||h.info(x.text),{ok:!0,command:`profile`,mode:r,...x.data}}function qo(e){return e instanceof F?{code:e.code,message:e.message,...e.details===void 0?{}:{details:e.details},...e.suggestions===void 0?{}:{suggestions:e.suggestions},...e.stack?{stack:e.stack}:{}}:e instanceof Error?{code:`UNKNOWN`,message:e.message,...e.stack?{stack:e.stack}:{}}:{code:`UNKNOWN`,message:String(e)}}function Jo(e){console.log(JSON.stringify(e,null,4))}const Yo=Oe.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`),Xo=a(import.meta.url),Zo=c(Xo),Qo=l(Zo,`../package.json`);let $o;try{let e=JSON.parse(r(Qo,`utf-8`));(typeof e.version!=`string`||!e.version)&&(console.error(`ERROR: package.json missing valid 'version' field`),process.exit(1)),$o=e.version}catch(e){console.error(`ERROR: Failed to read package version: ${e.message}`),process.exit(1)}const $=be(`bepack`);function es(e){return e.option(`--cwd <path>`,`Working directory`).option(`--config <path>`,`Config path`).option(`--json`,`JSON output`).option(`--dry-run`,`Do not write files`).option(`--silent`,`Silent output`).option(`--verbose`,`Verbose output`)}let ts=!1;function ns(e,t,n){let r=qo(t);if(n)Jo({ok:!1,command:e,error:r});else if(t instanceof F){if(console.error(`${Yo.red(r.code)}: ${r.message}`),r.suggestions?.length)for(let e of r.suggestions)console.error(` ${Yo.dim(`→`)} ${e}`);ts&&r.stack&&console.error(`${Yo.dim(r.stack)}`)}else t instanceof Error?(console.error(`${Yo.red(`ERROR`)}: ${t.message}`),ts&&r.stack&&console.error(`${Yo.dim(r.stack)}`)):console.error(`${Yo.red(`ERROR`)}: ${String(t)}`);process.exitCode=1}async function rs(e,t,n){ts=!!n.verbose;try{let e=await t(n);n.json&&Jo(e)}catch(t){ns(e,t,!!n.json)}}es($.command(`init`,`Create BePack project`)).option(`--format <format>`,`ts/js/mjs`).option(`--yes`,`Use defaults`).option(`--force`,`Overwrite generated files`).option(`--from-bp <path>`,`Reverse-engineer config from existing BP manifest.json`).option(`--from-rp <path>`,`Reverse-engineer config from existing RP manifest.json`).action(e=>rs(`init`,St,e)),es($.command(`install`,`Sync dependencies`)).option(`--target <target>`,`Target MC version`).option(`--registry <url>`,`npm registry`).option(`--pm <pm>`,`Package manager`).option(`--skip-pm`,`Do not run package manager`).option(`--skip-manifest`,`Do not patch manifest`).option(`--skip-package-json`,`Do not patch package.json`).option(`--save-to <field>`,`dependencies/devDependencies`).action(e=>rs(`install`,rr,e)),es($.command(`manifest`,`Patch manifest files`)).option(`--target <target>`,`Target MC version`).action(e=>rs(`manifest`,ir,e)),es($.command(`build`,`Build project`)).alias(`b`).option(`--mode <value>`,`Execution mode (passed to hooks)`).option(`--target <target>`,`Target MC version`).option(`--install`,`Run install`).option(`--skip-install`,`Skip install`).option(`--copy`,`Copy after build`).option(`--copy-target <target>`,`Copy target`).option(`--skip-copy`,`Skip copy`).option(`--pack`,`Pack after build`).option(`--skip-pack`,`Skip pack`).option(`--optimize`,`Optimize packed/copied output into __brarchive archives (--no-optimize to disable)`).option(`--typecheck`,`Run typecheck`).option(`--skip-typecheck`,`Skip typecheck`).option(`--typecheck-command <command>`,`Typecheck command line, e.g. "bun check"`).option(`--preserve-modules`,`Preserve module output`).option(`--use-npx`,`Use npx tsc for typecheck (deprecated: use --typecheck-command)`).option(`--minify`,`Minify output`).option(`--cache`,`Enable incremental compilation cache (--no-cache to disable)`).option(`--rolldown-config <path>`,`Custom rolldown config file (overrides bepack.config)`).option(`--timing`,`Show per-step timing`).action(e=>rs(`build`,Za,e)),es($.command(`copy`,`Copy packs`)).option(`--target <target>`,`Copy target`).option(`--all`,`Copy to all targets`).option(`--optimize`,`Optimize the copied packs into __brarchive archives (--no-optimize to disable)`).action(e=>rs(`copy`,Qa,e)),es($.command(`pack`,`Build and pack mcpack/mcaddon`)).option(`--name <name>`,`Output name`).option(`--optimize`,`Bundle loose files into __brarchive archives (--no-optimize to disable)`).option(`--build`,`Build before packing (default; --no-build to skip)`).option(`--skip-build`,`Pack the current pack folders without building first`).option(`--typecheck`,`Run typecheck before packing`).option(`--skip-typecheck`,`Skip typecheck before packing`).option(`--typecheck-command <command>`,`Typecheck command line, e.g. "bun check"`).option(`--rolldown-config <path>`,`Custom rolldown config file (overrides bepack.config)`).action(e=>rs(`pack`,Ya,e)),es($.command(`dev`,`Watch project`)).option(`--mode <value>`,`Execution mode (passed to hooks)`).option(`--copy`,`Copy on change`).option(`--copy-target <target>`,`Copy target`).option(`--skip-copy`,`Skip copy`).option(`--typecheck`,`Run typecheck`).option(`--skip-typecheck`,`Skip typecheck`).option(`--typecheck-command <command>`,`Typecheck command line, e.g. "bun check"`).option(`--rolldown-config <path>`,`Custom rolldown config file (overrides bepack.config)`).option(`--optimize`,`Optimize packed/copied output into __brarchive archives (--no-optimize to disable)`).option(`--timing`,`Show per-step timing`).action(e=>rs(`dev`,ro,e)),es($.command(`config`,`Show resolved config`)).option(`--summary`,`Show brief summary instead of full config`).action(e=>rs(`config`,ao,e)),$.command(`profile <command> [...profiles]`,`Analyze Bedrock .cpuprofile captures (summary|bursts|top|diff)`).option(`--cwd <path>`,`Working directory for profile paths`).option(`--gap <ms>`,`Deltas above this are idle gaps (default: 5)`).option(`--min-samples <count>`,`Minimum active samples in a burst (default: 20)`).option(`--from <ms>`,`Restrict top to samples at or after this time`).option(`--to <ms>`,`Restrict top to samples at or before this time`).option(`--by <mode>`,`Count self or total samples (default: self)`).option(`-n, --limit <count>`,`Rows to print or return (default: 15)`).option(`--stacks <count>`,`Stacks per burst (default: 5)`).option(`--root <dir>`,`Make source paths relative to this directory`).option(`--json`,`JSON output`).option(`--silent`,`Silent output`).option(`--verbose`,`Verbose output`).example(`bepack profile summary bedrock.cpuprofile`).example(`bepack profile bursts bedrock.cpuprofile --stacks 10`).example(`bepack profile top bedrock.cpuprofile --from 2900 --to 2950 --by total`).example(`bepack profile diff before.cpuprofile after.cpuprofile`).action((e,t,n)=>rs(`profile`,n=>Ko(e,t??[],n),n)),$.help(),$.version($o);async function is(e){if($.unsetMatchedCommand(),$.parse(e,{run:!1}),!$.options.help&&!$.options.version){if(!$.matchedCommand){let e=$.args[0]??$.rawArgs.slice(2).find(e=>e!==`--`&&!e.startsWith(`-`));if(e){ns(`cli`,new F(`UNKNOWN_COMMAND`,`Unknown command: ${e}`,{suggestions:["Run `bepack --help` to see available commands."]}),!!$.options.json);return}$.outputHelp();return}try{await $.runMatchedCommand()}catch(e){ns(`cli`,e,!!$.options.json)}}}await is(process.argv);export{};