@tobelabs/chainwright 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +9 -34
- package/dist/core/index.js +1 -1
- package/dist/wallets/index.js +16 -16
- package/package.json +3 -3
package/dist/cli/index.js
CHANGED
|
@@ -1,36 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
${
|
|
6
|
-
|
|
7
|
-
- a short flag is a single dash and a single character
|
|
8
|
-
- either use a single dash and a single character (for a short flag)
|
|
9
|
-
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(a)?new Error(`${c}
|
|
10
|
-
- too many short flags`):r.test(a)?new Error(`${c}
|
|
11
|
-
- too many long flags`):new Error(`${c}
|
|
12
|
-
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${o}'.`);return{shortFlag:e,longFlag:t}}Te.Option=De;Te.DualOptions=Ne});var nt=T(tt=>{"use strict";function pn(o,e){if(Math.abs(o.length-e.length)>3)return Math.max(o.length,e.length);let t=[];for(let n=0;n<=o.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let r=1;r<=o.length;r++){let i=1;o[r-1]===e[n-1]?i=0:i=1,t[r][n]=Math.min(t[r-1][n]+1,t[r][n-1]+1,t[r-1][n-1]+i),r>1&&n>1&&o[r-1]===e[n-2]&&o[r-2]===e[n-1]&&(t[r][n]=Math.min(t[r][n],t[r-2][n-2]+1))}return t[o.length][e.length]}function gn(o,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=o.startsWith("--");t&&(o=o.slice(2),e=e.map(a=>a.slice(2)));let n=[],r=3,i=.4;return e.forEach(a=>{if(a.length<=1)return;let c=pn(o,a),d=Math.max(o.length,a.length);(d-c)/d>i&&(c<r?(r=c,n=[a]):c===r&&n.push(a))}),n.sort((a,c)=>a.localeCompare(c)),t&&(n=n.map(a=>`--${a}`)),n.length>1?`
|
|
13
|
-
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
14
|
-
(Did you mean ${n[0]}?)`:""}tt.suggestSimilar=gn});var st=T(Ue=>{"use strict";var En=M("events").EventEmitter,Fe=M("child_process"),G=M("path"),ue=M("fs"),A=M("process"),{Argument:_n,humanReadableArgName:Cn}=ce(),{CommanderError:be}=Q(),{Help:yn,stripColor:On}=Le(),{Option:rt,DualOptions:Sn}=ve(),{suggestSimilar:it}=nt(),Re=class o extends En{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>A.stdout.write(t),writeErr:t=>A.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>A.stdout.isTTY?A.stdout.columns:void 0,getErrHelpWidth:()=>A.stderr.isTTY?A.stderr.columns:void 0,getOutHasColors:()=>He()??(A.stdout.isTTY&&A.stdout.hasColors?.()),getErrHasColors:()=>He()??(A.stderr.isTTY&&A.stderr.hasColors?.()),stripColor:t=>On(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,i=n;typeof r=="object"&&r!==null&&(i=r,r=null),i=i||{};let[,a,c]=e.match(/([^ ]+) *(.*)/),d=this.createCommand(a);return r&&(d.description(r),d._executableHandler=!0),i.isDefault&&(this._defaultCommandName=d._name),d._hidden=!!(i.noHelp||i.hidden),d._executableFile=i.executableFile||null,c&&d.arguments(c),this._registerCommand(d),d.parent=this,d.copyInheritedSettings(this),r?this:d}createCommand(e){return new o(e)}createHelp(){return Object.assign(new yn,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
15
|
-
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new _n(e,t)}argument(e,t,n,r){let i=this.createArgument(e,t);return typeof n=="function"?i.default(r).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let n=e??"help [command]",[,r,i]=n.match(/([^ ]+) *(.*)/),a=t??"display help for command",c=this.createCommand(r);return c.helpOption(!1),i&&c.arguments(i),a&&c.description(a),this._addImplicitHelpCommand=!0,this._helpCommand=c,(e||t)&&this._initCommandGroup(c),this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
16
|
-
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new be(e,t,n)),A.exit(e)}action(e){let t=n=>{let r=this.registeredArguments.length,i=n.slice(0,r);return this._storeOptionsAsProperties?i[r]=this:i[r]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new rt(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let a=`${r} ${i.message}`;this.error(a,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
17
|
-
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=r=>[r.name()].concat(r.aliases()),n=t(e).find(r=>this._findCommand(r));if(n){let r=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${r}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(i,a,c)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let d=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,d,a):i!==null&&e.variadic&&(i=e._collectValue(i,d)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,c)};return this.on("option:"+t,i=>{let a=`error: option '${e.flags}' argument '${i}' is invalid.`;r(i,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let a=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;r(i,a,"env")}),this}_optionEx(e,t,n,r,i){if(typeof t=="object"&&t instanceof rt)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r=="function")a.default(i).argParser(r);else if(r instanceof RegExp){let c=r;r=(d,g)=>{let C=c.exec(d);return C?C[0]:g},a.default(i).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){A.versions?.electron&&(t.from="electron");let r=A.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=A.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":A.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
18
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,n){if(ue.existsSync(e))return;let r=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",i=`'${e}' does not exist
|
|
19
|
-
- if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
|
-
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
21
|
-
- ${r}`;throw new Error(i)}_executeSubCommand(e,t){t=t.slice();let n=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function i(C,E){let S=G.resolve(C,E);if(ue.existsSync(S))return S;if(r.includes(G.extname(E)))return;let l=r.find(u=>ue.existsSync(`${S}${u}`));if(l)return`${S}${l}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let C;try{C=ue.realpathSync(this._scriptPath)}catch{C=this._scriptPath}c=G.resolve(G.dirname(C),c)}if(c){let C=i(c,a);if(!C&&!e._executableFile&&this._scriptPath){let E=G.basename(this._scriptPath,G.extname(this._scriptPath));E!==this._name&&(C=i(c,`${E}-${e._name}`))}a=C||a}n=r.includes(G.extname(a));let d;A.platform!=="win32"?n?(t.unshift(a),t=ot(A.execArgv).concat(t),d=Fe.spawn(A.argv[0],t,{stdio:"inherit"})):d=Fe.spawn(a,t,{stdio:"inherit"}):(this._checkForMissingExecutable(a,c,e._name),t.unshift(a),t=ot(A.execArgv).concat(t),d=Fe.spawn(A.execPath,t,{stdio:"inherit"})),d.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(E=>{A.on(E,()=>{d.killed===!1&&d.exitCode===null&&d.kill(E)})});let g=this._exitCallback;d.on("close",C=>{C=C??1,g?g(new be(C,"commander.executeSubCommandAsync","(close)")):A.exit(C)}),d.on("error",C=>{if(C.code==="ENOENT")this._checkForMissingExecutable(a,c,e._name);else if(C.code==="EACCES")throw new Error(`'${a}' not executable`);if(!g)A.exit(1);else{let E=new be(1,"commander.executeSubCommandAsync","(error)");E.nestedError=C,g(E)}}),this.runningCommand=d}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,"preSubcommand"),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,r,i)=>{let a=r;if(r!==null&&n.parseArg){let c=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;a=this._callParseArg(n,r,i,c)}return a};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((a,c)=>e(n,c,a),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(a=>{r.push({hookedCommand:i,callback:a})})}),t==="postAction"&&r.reverse(),r.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{r=this._chainOrCall(r,()=>i(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let a;return a=this._chainOrCallHooks(a,"preAction"),a=this._chainOrCall(a,()=>this._actionHandler(this.processedArgs)),this.parent&&(a=this._chainOrCall(a,()=>{this.parent.emit(i,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let r=n.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let r=e.find(i=>n.conflictsWith.includes(i.attributeName()));r&&this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(C){return C.length>1&&C[0]==="-"}let a=C=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(C)?!this._getCommandAndAncestors().some(E=>E.options.map(S=>S.short).some(S=>/^-\d$/.test(S))):!1,c=null,d=null,g=0;for(;g<e.length||d;){let C=d??e[g++];if(d=null,C==="--"){r===n&&r.push(C),r.push(...e.slice(g));break}if(c&&(!i(C)||a(C))){this.emit(`option:${c.name()}`,C);continue}if(c=null,i(C)){let E=this._findOption(C);if(E){if(E.required){let S=e[g++];S===void 0&&this.optionMissingArgument(E),this.emit(`option:${E.name()}`,S)}else if(E.optional){let S=null;g<e.length&&(!i(e[g])||a(e[g]))&&(S=e[g++]),this.emit(`option:${E.name()}`,S)}else this.emit(`option:${E.name()}`);c=E.variadic?E:null;continue}}if(C.length>2&&C[0]==="-"&&C[1]!=="-"){let E=this._findOption(`-${C[1]}`);if(E){E.required||E.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${E.name()}`,C.slice(2)):(this.emit(`option:${E.name()}`),d=`-${C.slice(2)}`);continue}}if(/^--[^=]+=/.test(C)){let E=C.indexOf("="),S=this._findOption(C.slice(0,E));if(S&&(S.required||S.optional)){this.emit(`option:${S.name()}`,C.slice(E+1));continue}}if(r===t&&i(C)&&!(this.commands.length===0&&a(C))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(C)){t.push(C),n.push(...e.slice(g));break}else if(this._getHelpCommand()&&C===this._getHelpCommand().name()){t.push(C,...e.slice(g));break}else if(this._defaultCommandName){n.push(C,...e.slice(g));break}}if(this._passThroughOptions){r.push(C,...e.slice(g));break}r.push(C)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let r=this.options[n].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
22
|
-
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
23
|
-
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
24
|
-
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||"commander.error";this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in A.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,A.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Sn(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(r=>!t(r)).forEach(r=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=a=>{let c=a.attributeName(),d=this.getOptionValue(c),g=this.options.find(E=>E.negate&&c===E.attributeName()),C=this.options.find(E=>!E.negate&&c===E.attributeName());return g&&(g.presetArg===void 0&&d===!1||g.presetArg!==void 0&&d===g.presetArg)?g:C||a},r=a=>{let c=n(a),d=c.attributeName();return this.getOptionValueSource(d)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],i=this;do{let a=i.createHelp().visibleOptions(i).filter(c=>c.long).map(c=>c.long);r=r.concat(a),i=i.parent}while(i&&!i._enablePositionalOptions);t=it(e,r)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(i=>{r.push(i.name()),i.alias()&&r.push(i.alias())}),t=it(e,r)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
25
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let r=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>Cn(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=G.basename(e,G.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,n,r,i;return t?(n=c=>this._outputConfiguration.writeErr(c),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=c=>this._outputConfiguration.writeOut(c),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:c=>(r||(c=this._outputConfiguration.stripColor(c)),n(c)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(a=>a.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(a=>a.emit("afterAllHelp",r))}helpOption(e,t){return typeof e=="boolean"?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(A.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
26
|
-
Expecting one of '${n.join("', '")}'`);let r=`${e}Help`;return this.on(r,i=>{let a;typeof t=="function"?a=t({error:i.error,command:i.command}):a=t,a&&i.write(`${a}
|
|
27
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ot(o){return o.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",r="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]),t&&r!=="0"?`${t}=${n}:${parseInt(r)+1}`:e})}function He(){if(A.env.NO_COLOR||A.env.FORCE_COLOR==="0"||A.env.FORCE_COLOR==="false")return!1;if(A.env.FORCE_COLOR||A.env.CLICOLOR_FORCE!==void 0)return!0}Ue.Command=Re;Ue.useColor=He});var ut=T(W=>{"use strict";var{Argument:at}=ce(),{Command:Pe}=st(),{CommanderError:wn,InvalidArgumentError:lt}=Q(),{Help:xn}=Le(),{Option:ct}=ve();W.program=new Pe;W.createCommand=o=>new Pe(o);W.createOption=(o,e)=>new ct(o,e);W.createArgument=(o,e)=>new at(o,e);W.Command=Pe;W.Option=ct;W.Argument=at;W.Help=xn;W.CommanderError=wn;W.InvalidArgumentError=lt;W.InvalidOptionArgumentError=lt});var We=T((ui,_t)=>{"use strict";_t.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var de=T(yt=>{"use strict";var Ct={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function qn(o){return function(...e){return e.length&&(o=o.replace(/\{(\d)\}/g,(t,n)=>e[n]||"")),new Error("ADM-ZIP: "+o)}}for(let o of Object.keys(Ct))yt[o]=qn(Ct[o])});var At=T((hi,xt)=>{"use strict";var Xn=M("fs"),U=M("path"),Ot=We(),Kn=de(),Yn=typeof process=="object"&&process.platform==="win32",St=o=>typeof o=="object"&&o!==null,wt=new Uint32Array(256).map((o,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function R(o){this.sep=U.sep,this.fs=Xn,St(o)&&St(o.fs)&&typeof o.fs.statSync=="function"&&(this.fs=o.fs)}xt.exports=R;R.prototype.makeDir=function(o){let e=this;function t(n){let r=n.split(e.sep)[0];n.split(e.sep).forEach(function(i){if(!(!i||i.substr(-1,1)===":")){r+=e.sep+i;var a;try{a=e.fs.statSync(r)}catch(c){if(c.message&&c.message.startsWith("ENOENT"))e.fs.mkdirSync(r);else throw c}if(a&&a.isFile())throw Kn.FILE_IN_THE_WAY(`"${r}"`)}})}t(o)};R.prototype.writeFileTo=function(o,e,t,n){let r=this;if(r.fs.existsSync(o)){if(!t)return!1;var i=r.fs.statSync(o);if(i.isDirectory())return!1}var a=U.dirname(o);r.fs.existsSync(a)||r.makeDir(a);var c;try{c=r.fs.openSync(o,"w",438)}catch{r.fs.chmodSync(o,438),c=r.fs.openSync(o,"w",438)}if(c)try{r.fs.writeSync(c,e,0,e.length,0)}finally{r.fs.closeSync(c)}return r.fs.chmodSync(o,n||438),!0};R.prototype.writeFileToAsync=function(o,e,t,n,r){typeof n=="function"&&(r=n,n=void 0);let i=this;i.fs.exists(o,function(a){if(a&&!t)return r(!1);i.fs.stat(o,function(c,d){if(a&&d.isDirectory())return r(!1);var g=U.dirname(o);i.fs.exists(g,function(C){C||i.makeDir(g),i.fs.open(o,"w",438,function(E,S){E?i.fs.chmod(o,438,function(){i.fs.open(o,"w",438,function(l,u){i.fs.write(u,e,0,e.length,0,function(){i.fs.close(u,function(){i.fs.chmod(o,n||438,function(){r(!0)})})})})}):S?i.fs.write(S,e,0,e.length,0,function(){i.fs.close(S,function(){i.fs.chmod(o,n||438,function(){r(!0)})})}):i.fs.chmod(o,n||438,function(){r(!0)})})})})})};R.prototype.findFiles=function(o){let e=this;function t(n,r,i){typeof r=="boolean"&&(i=r,r=void 0);let a=[];return e.fs.readdirSync(n).forEach(function(c){let d=U.join(n,c),g=e.fs.statSync(d);(!r||r.test(d))&&a.push(U.normalize(d)+(g.isDirectory()?e.sep:"")),g.isDirectory()&&i&&(a=a.concat(t(d,r,i)))}),a}return t(o,void 0,!0)};R.prototype.findFilesAsync=function(o,e){let t=this,n=[];t.fs.readdir(o,function(r,i){if(r)return e(r);let a=i.length;if(!a)return e(null,n);i.forEach(function(c){c=U.join(o,c),t.fs.stat(c,function(d,g){if(d)return e(d);g&&(n.push(U.normalize(c)+(g.isDirectory()?t.sep:"")),g.isDirectory()?t.findFilesAsync(c,function(C,E){if(C)return e(C);n=n.concat(E),--a||e(null,n)}):--a||e(null,n))})})})};R.prototype.getAttributes=function(){};R.prototype.setAttributes=function(){};R.crc32update=function(o,e){return wt[(o^e)&255]^o>>>8};R.crc32=function(o){typeof o=="string"&&(o=Buffer.from(o,"utf8"));let e=o.length,t=-1;for(let n=0;n<e;)t=R.crc32update(t,o[n++]);return~t>>>0};R.methodToString=function(o){switch(o){case Ot.STORED:return"STORED ("+o+")";case Ot.DEFLATED:return"DEFLATED ("+o+")";default:return"UNSUPPORTED ("+o+")"}};R.canonical=function(o){if(!o)return"";let e=U.posix.normalize("/"+o.split("\\").join("/"));return U.join(".",e)};R.zipnamefix=function(o){if(!o)return"";let e=U.posix.normalize("/"+o.split("\\").join("/"));return U.posix.join(".",e)};R.findLast=function(o,e){if(!Array.isArray(o))throw new TypeError("arr is not array");let t=o.length>>>0;for(let n=t-1;n>=0;n--)if(e(o[n],n,o))return o[n]};R.sanitize=function(o,e){o=U.resolve(U.normalize(o));for(var t=e.split("/"),n=0,r=t.length;n<r;n++){var i=U.normalize(U.join(o,t.slice(n,r).join(U.sep)));if(i.indexOf(o)===0)return i}return U.normalize(U.join(o,U.basename(e)))};R.toBuffer=function(e,t){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?t(e):Buffer.alloc(0)};R.readBigUInt64LE=function(o,e){let t=o.readUInt32LE(e);return o.readUInt32LE(e+4)*4294967296+t};R.fromDOS2Date=function(o){return new Date((o>>25&127)+1980,Math.max((o>>21&15)-1,0),Math.max(o>>16&31,1),o>>11&31,o>>5&63,(o&31)<<1)};R.fromDate2DOS=function(o){let e=0,t=0;return o.getFullYear()>1979&&(e=(o.getFullYear()-1980&127)<<9|o.getMonth()+1<<5|o.getDate(),t=o.getHours()<<11|o.getMinutes()<<5|o.getSeconds()>>1),e<<16|t};R.isWin=Yn;R.crcTable=wt});var Lt=T((di,It)=>{"use strict";var Jn=M("path");It.exports=function(o,{fs:e}){var t=o||"",n=i(),r=null;function i(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return t&&e.existsSync(t)?(r=e.statSync(t),n.directory=r.isDirectory(),n.mtime=r.mtime,n.atime=r.atime,n.executable=(73&r.mode)!==0,n.readonly=(128&r.mode)===0,n.hidden=Jn.basename(t)[0]==="."):console.warn("Invalid path: "+t),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:t,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Nt=T((mi,Dt)=>{"use strict";Dt.exports={efs:!0,encode:o=>Buffer.from(o,"utf8"),decode:o=>o.toString("utf8")}});var Y=T((pi,K)=>{"use strict";K.exports=At();K.exports.Constants=We();K.exports.Errors=de();K.exports.FileAttr=Lt();K.exports.decoder=Nt()});var vt=T((gi,Tt)=>{"use strict";var j=Y(),O=j.Constants;Tt.exports=function(){var o=20,e=10,t=0,n=0,r=0,i=0,a=0,c=0,d=0,g=0,C=0,E=0,S=0,l=0,u=0;o|=j.isWin?2560:768,t|=O.FLG_EFS;let p={extraLen:0},f=s=>Math.max(0,s)>>>0,m=s=>Math.max(0,s)&65535,y=s=>Math.max(0,s)&255;return r=j.fromDate2DOS(new Date),{get made(){return o},set made(s){o=s},get version(){return e},set version(s){e=s},get flags(){return t},set flags(s){t=s},get flags_efs(){return(t&O.FLG_EFS)>0},set flags_efs(s){s?t|=O.FLG_EFS:t&=~O.FLG_EFS},get flags_desc(){return(t&O.FLG_DESC)>0},set flags_desc(s){s?t|=O.FLG_DESC:t&=~O.FLG_DESC},get method(){return n},set method(s){switch(s){case O.STORED:this.version=10;case O.DEFLATED:default:this.version=20}n=s},get time(){return j.fromDOS2Date(this.timeval)},set time(s){s=new Date(s),this.timeval=j.fromDate2DOS(s)},get timeval(){return r},set timeval(s){r=f(s)},get timeHighByte(){return y(r>>>8)},get crc(){return i},set crc(s){i=f(s)},get compressedSize(){return a},set compressedSize(s){a=f(s)},get size(){return c},set size(s){c=f(s)},get fileNameLength(){return d},set fileNameLength(s){d=s},get extraLength(){return g},set extraLength(s){g=s},get extraLocalLength(){return p.extraLen},set extraLocalLength(s){p.extraLen=s},get commentLength(){return C},set commentLength(s){C=s},get diskNumStart(){return E},set diskNumStart(s){E=f(s)},get inAttr(){return S},set inAttr(s){S=f(s)},get attr(){return l},set attr(s){l=f(s)},get fileAttr(){return(l||0)>>16&4095},get offset(){return u},set offset(s){u=f(s)},get encrypted(){return(t&O.FLG_ENC)===O.FLG_ENC},get centralHeaderSize(){return O.CENHDR+d+g+C},get realDataOffset(){return u+O.LOCHDR+p.fnameLen+p.extraLen},get localHeader(){return p},loadLocalHeaderFromBinary:function(s){var h=s.slice(u,u+O.LOCHDR);if(h.readUInt32LE(0)!==O.LOCSIG)throw j.Errors.INVALID_LOC();p.version=h.readUInt16LE(O.LOCVER),p.flags=h.readUInt16LE(O.LOCFLG),p.flags_desc=(p.flags&O.FLG_DESC)>0,p.method=h.readUInt16LE(O.LOCHOW),p.time=h.readUInt32LE(O.LOCTIM),p.crc=h.readUInt32LE(O.LOCCRC),p.compressedSize=h.readUInt32LE(O.LOCSIZ),p.size=h.readUInt32LE(O.LOCLEN),p.fnameLen=h.readUInt16LE(O.LOCNAM),p.extraLen=h.readUInt16LE(O.LOCEXT);let _=u+O.LOCHDR+p.fnameLen,x=_+p.extraLen;return s.slice(_,x)},loadFromBinary:function(s){if(s.length!==O.CENHDR||s.readUInt32LE(0)!==O.CENSIG)throw j.Errors.INVALID_CEN();o=s.readUInt16LE(O.CENVEM),e=s.readUInt16LE(O.CENVER),t=s.readUInt16LE(O.CENFLG),n=s.readUInt16LE(O.CENHOW),r=s.readUInt32LE(O.CENTIM),i=s.readUInt32LE(O.CENCRC),a=s.readUInt32LE(O.CENSIZ),c=s.readUInt32LE(O.CENLEN),d=s.readUInt16LE(O.CENNAM),g=s.readUInt16LE(O.CENEXT),C=s.readUInt16LE(O.CENCOM),E=s.readUInt16LE(O.CENDSK),S=s.readUInt16LE(O.CENATT),l=s.readUInt32LE(O.CENATX),u=s.readUInt32LE(O.CENOFF)},localHeaderToBinary:function(){var s=Buffer.alloc(O.LOCHDR);return s.writeUInt32LE(O.LOCSIG,0),s.writeUInt16LE(e,O.LOCVER),s.writeUInt16LE(t,O.LOCFLG),s.writeUInt16LE(n,O.LOCHOW),s.writeUInt32LE(r,O.LOCTIM),s.writeUInt32LE(i,O.LOCCRC),s.writeUInt32LE(a,O.LOCSIZ),s.writeUInt32LE(c,O.LOCLEN),s.writeUInt16LE(d,O.LOCNAM),s.writeUInt16LE(p.extraLen,O.LOCEXT),s},centralHeaderToBinary:function(){var s=Buffer.alloc(O.CENHDR+d+g+C);return s.writeUInt32LE(O.CENSIG,0),s.writeUInt16LE(o,O.CENVEM),s.writeUInt16LE(e,O.CENVER),s.writeUInt16LE(t,O.CENFLG),s.writeUInt16LE(n,O.CENHOW),s.writeUInt32LE(r,O.CENTIM),s.writeUInt32LE(i,O.CENCRC),s.writeUInt32LE(a,O.CENSIZ),s.writeUInt32LE(c,O.CENLEN),s.writeUInt16LE(d,O.CENNAM),s.writeUInt16LE(g,O.CENEXT),s.writeUInt16LE(C,O.CENCOM),s.writeUInt16LE(E,O.CENDSK),s.writeUInt16LE(S,O.CENATT),s.writeUInt32LE(l,O.CENATX),s.writeUInt32LE(u,O.CENOFF),s},toJSON:function(){let s=function(h){return h+" bytes"};return{made:o,version:e,flags:t,method:j.methodToString(n),time:this.time,crc:"0x"+i.toString(16).toUpperCase(),compressedSize:s(a),size:s(c),fileNameLength:s(d),extraLength:s(g),commentLength:s(C),diskNumStart:E,inAttr:S,attr:l,offset:u,centralHeaderSize:s(O.CENHDR+d+g+C)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var bt=T((Ei,Ft)=>{"use strict";var J=Y(),v=J.Constants;Ft.exports=function(){var o=0,e=0,t=0,n=0,r=0;return{get diskEntries(){return o},set diskEntries(i){o=e=i},get totalEntries(){return e},set totalEntries(i){e=o=i},get size(){return t},set size(i){t=i},get offset(){return n},set offset(i){n=i},get commentLength(){return r},set commentLength(i){r=i},get mainHeaderSize(){return v.ENDHDR+r},loadFromBinary:function(i){if((i.length!==v.ENDHDR||i.readUInt32LE(0)!==v.ENDSIG)&&(i.length<v.ZIP64HDR||i.readUInt32LE(0)!==v.ZIP64SIG))throw J.Errors.INVALID_END();i.readUInt32LE(0)===v.ENDSIG?(o=i.readUInt16LE(v.ENDSUB),e=i.readUInt16LE(v.ENDTOT),t=i.readUInt32LE(v.ENDSIZ),n=i.readUInt32LE(v.ENDOFF),r=i.readUInt16LE(v.ENDCOM)):(o=J.readBigUInt64LE(i,v.ZIP64SUB),e=J.readBigUInt64LE(i,v.ZIP64TOT),t=J.readBigUInt64LE(i,v.ZIP64SIZE),n=J.readBigUInt64LE(i,v.ZIP64OFF),r=0)},toBinary:function(){var i=Buffer.alloc(v.ENDHDR+r);return i.writeUInt32LE(v.ENDSIG,0),i.writeUInt32LE(0,4),i.writeUInt16LE(o,v.ENDSUB),i.writeUInt16LE(e,v.ENDTOT),i.writeUInt32LE(t,v.ENDSIZ),i.writeUInt32LE(n,v.ENDOFF),i.writeUInt16LE(r,v.ENDCOM),i.fill(" ",v.ENDHDR),i},toJSON:function(){let i=function(a,c){let d=a.toString(16).toUpperCase();for(;d.length<c;)d="0"+d;return"0x"+d};return{diskEntries:o,totalEntries:e,size:t+" bytes",offset:i(n,4),commentLength:r}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ke=T(Ve=>{"use strict";Ve.EntryHeader=vt();Ve.MainHeader=bt()});var Ht=T((Ci,Rt)=>{"use strict";Rt.exports=function(o){var e=M("zlib"),t={chunkSize:(parseInt(o.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(o,t)},deflateAsync:function(n){var r=e.createDeflateRaw(t),i=[],a=0;r.on("data",function(c){i.push(c),a+=c.length}),r.on("end",function(){var c=Buffer.alloc(a),d=0;c.fill(0);for(var g=0;g<i.length;g++){var C=i[g];C.copy(c,d),d+=C.length}n&&n(c)}),r.end(o)}}}});var Pt=T((yi,Ut)=>{"use strict";var Qn=+(process.versions?process.versions.node:"").split(".")[0]||0;Ut.exports=function(o,e){var t=M("zlib");let n=Qn>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return t.inflateRawSync(o,n)},inflateAsync:function(r){var i=t.createInflateRaw(n),a=[],c=0;i.on("data",function(d){a.push(d),c+=d.length}),i.on("end",function(){var d=Buffer.alloc(c),g=0;d.fill(0);for(var C=0;C<a.length;C++){var E=a[C];E.copy(d,g),g+=E.length}r&&r(d)}),i.end(o)}}}});var Vt=T((Oi,Wt)=>{"use strict";var{randomFillSync:$t}=M("crypto"),er=de(),tr=new Uint32Array(256).map((o,e)=>{for(let t=0;t<8;t++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Mt=(o,e)=>Math.imul(o,e)>>>0,Bt=(o,e)=>tr[(o^e)&255]^o>>>8,ie=()=>typeof $t=="function"?$t(Buffer.alloc(12)):ie.node();ie.node=()=>{let o=Buffer.alloc(12),e=o.length;for(let t=0;t<e;t++)o[t]=Math.random()*256&255;return o};var me={genSalt:ie};function pe(o){let e=Buffer.isBuffer(o)?o:Buffer.from(o);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let t=0;t<e.length;t++)this.updateKeys(e[t])}pe.prototype.updateKeys=function(o){let e=this.keys;return e[0]=Bt(e[0],o),e[1]+=e[0]&255,e[1]=Mt(e[1],134775813)+1,e[2]=Bt(e[2],e[1]>>>24),o};pe.prototype.next=function(){let o=(this.keys[2]|2)>>>0;return Mt(o,o^1)>>8&255};function nr(o){let e=new pe(o);return function(t){let n=Buffer.alloc(t.length),r=0;for(let i of t)n[r++]=e.updateKeys(i^e.next());return n}}function rr(o){let e=new pe(o);return function(t,n,r=0){n||(n=Buffer.alloc(t.length));for(let i of t){let a=e.next();n[r++]=i^a,e.updateKeys(i)}return n}}function ir(o,e,t){if(!o||!Buffer.isBuffer(o)||o.length<12)return Buffer.alloc(0);let n=nr(t),r=n(o.slice(0,12)),i=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(r[11]!==i)throw er.WRONG_PASSWORD();return n(o.slice(12))}function or(o){Buffer.isBuffer(o)&&o.length>=12?me.genSalt=function(){return o.slice(0,12)}:o==="node"?me.genSalt=ie.node:me.genSalt=ie}function sr(o,e,t,n=!1){o==null&&(o=Buffer.alloc(0)),Buffer.isBuffer(o)||(o=Buffer.from(o.toString()));let r=rr(t),i=me.genSalt();i[11]=e.crc>>>24&255,n&&(i[10]=e.crc>>>16&255);let a=Buffer.alloc(o.length+12);return r(i,a),r(o,a,12)}Wt.exports={decrypt:ir,encrypt:sr,_salter:or}});var kt=T(ge=>{"use strict";ge.Deflater=Ht();ge.Inflater=Pt();ge.ZipCrypto=Vt()});var je=T((wi,Gt)=>{"use strict";var L=Y(),ar=ke(),H=L.Constants,Ge=kt();Gt.exports=function(o,e){var t=new ar.EntryHeader,n=Buffer.alloc(0),r=Buffer.alloc(0),i=!1,a=null,c=Buffer.alloc(0),d=Buffer.alloc(0),g=!0;let C=o,E=typeof C.decoder=="object"?C.decoder:L.decoder;g=E.hasOwnProperty("efs")?E.efs:!1;function S(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(d=t.loadLocalHeaderFromBinary(e),e.slice(t.realDataOffset,t.realDataOffset+t.compressedSize))}function l(s){if(!t.flags_desc&&!t.localHeader.flags_desc){if(L.crc32(s)!==t.localHeader.crc)return!1}else{let h={},_=t.realDataOffset+t.compressedSize;if(e.readUInt32LE(_)==H.LOCSIG||e.readUInt32LE(_)==H.CENSIG)throw L.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(_)==H.EXTSIG)h.crc=e.readUInt32LE(_+H.EXTCRC),h.compressedSize=e.readUInt32LE(_+H.EXTSIZ),h.size=e.readUInt32LE(_+H.EXTLEN);else if(e.readUInt16LE(_+12)===19280)h.crc=e.readUInt32LE(_+H.EXTCRC-4),h.compressedSize=e.readUInt32LE(_+H.EXTSIZ-4),h.size=e.readUInt32LE(_+H.EXTLEN-4);else throw L.Errors.DESCRIPTOR_UNKNOWN();if(h.compressedSize!==t.compressedSize||h.size!==t.size||h.crc!==t.crc)throw L.Errors.DESCRIPTOR_FAULTY();if(L.crc32(s)!==h.crc)return!1}return!0}function u(s,h,_){if(typeof h>"u"&&typeof s=="string"&&(_=s,s=void 0),i)return s&&h&&h(Buffer.alloc(0),L.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var x=S();if(x.length===0)return s&&h&&h(x),x;if(t.encrypted){if(typeof _!="string"&&!Buffer.isBuffer(_))throw L.Errors.INVALID_PASS_PARAM();x=Ge.ZipCrypto.decrypt(x,t,_)}var w=Buffer.alloc(t.size);switch(t.method){case L.Constants.STORED:if(x.copy(w),l(w))return s&&h&&h(w),w;throw s&&h&&h(w,L.Errors.BAD_CRC()),L.Errors.BAD_CRC();case L.Constants.DEFLATED:var D=new Ge.Inflater(x,t.size);if(s)D.inflateAsync(function(I){I.copy(I,0),h&&(l(I)?h(I):h(I,L.Errors.BAD_CRC()))});else{if(D.inflate(w).copy(w,0),!l(w))throw L.Errors.BAD_CRC(`"${E.decode(n)}"`);return w}break;default:throw s&&h&&h(Buffer.alloc(0),L.Errors.UNKNOWN_METHOD()),L.Errors.UNKNOWN_METHOD()}}function p(s,h){if((!a||!a.length)&&Buffer.isBuffer(e))return s&&h&&h(S()),S();if(a.length&&!i){var _;switch(t.method){case L.Constants.STORED:return t.compressedSize=t.size,_=Buffer.alloc(a.length),a.copy(_),s&&h&&h(_),_;default:case L.Constants.DEFLATED:var x=new Ge.Deflater(a);if(s)x.deflateAsync(function(D){_=Buffer.alloc(D.length),t.compressedSize=D.length,D.copy(_),h&&h(_)});else{var w=x.deflate();return t.compressedSize=w.length,w}x=null;break}}else if(s&&h)h(Buffer.alloc(0));else return Buffer.alloc(0)}function f(s,h){return L.readBigUInt64LE(s,h)}function m(s){try{for(var h=0,_,x,w;h+4<s.length;)_=s.readUInt16LE(h),h+=2,x=s.readUInt16LE(h),h+=2,w=s.slice(h,h+x),h+=x,H.ID_ZIP64===_&&y(w)}catch{throw L.Errors.EXTRA_FIELD_PARSE_ERROR()}}function y(s){var h,_,x,w;s.length>=H.EF_ZIP64_SCOMP&&(h=f(s,H.EF_ZIP64_SUNCOMP),t.size===H.EF_ZIP64_OR_32&&(t.size=h)),s.length>=H.EF_ZIP64_RHO&&(_=f(s,H.EF_ZIP64_SCOMP),t.compressedSize===H.EF_ZIP64_OR_32&&(t.compressedSize=_)),s.length>=H.EF_ZIP64_DSN&&(x=f(s,H.EF_ZIP64_RHO),t.offset===H.EF_ZIP64_OR_32&&(t.offset=x)),s.length>=H.EF_ZIP64_DSN+4&&(w=s.readUInt32LE(H.EF_ZIP64_DSN),t.diskNumStart===H.EF_ZIP64_OR_16&&(t.diskNumStart=w))}return{get entryName(){return E.decode(n)},get rawEntryName(){return n},set entryName(s){n=L.toBuffer(s,E.encode);var h=n[n.length-1];i=h===47||h===92,t.fileNameLength=n.length},get efs(){return typeof g=="function"?g(this.entryName):g},get extra(){return c},set extra(s){c=s,t.extraLength=s.length,m(s)},get comment(){return E.decode(r)},set comment(s){if(r=L.toBuffer(s,E.encode),t.commentLength=r.length,r.length>65535)throw L.Errors.COMMENT_TOO_LONG()},get name(){var s=E.decode(n);return i?s.substr(s.length-1).split("/").pop():s.split("/").pop()},get isDirectory(){return i},getCompressedData:function(){return p(!1,null)},getCompressedDataAsync:function(s){p(!0,s)},setData:function(s){a=L.toBuffer(s,L.decoder.encode),!i&&a.length?(t.size=a.length,t.method=L.Constants.DEFLATED,t.crc=L.crc32(s),t.changed=!0):t.method=L.Constants.STORED},getData:function(s){return t.changed?a:u(!1,null,s)},getDataAsync:function(s,h){t.changed?s(a):u(!0,s,h)},set attr(s){t.attr=s},get attr(){return t.attr},set header(s){t.loadFromBinary(s)},get header(){return t},packCentralHeader:function(){t.flags_efs=this.efs,t.extraLength=c.length;var s=t.centralHeaderToBinary(),h=L.Constants.CENHDR;return n.copy(s,h),h+=n.length,c.copy(s,h),h+=t.extraLength,r.copy(s,h),s},packLocalHeader:function(){let s=0;t.flags_efs=this.efs,t.extraLocalLength=d.length;let h=t.localHeaderToBinary(),_=Buffer.alloc(h.length+n.length+t.extraLocalLength);return h.copy(_,s),s+=h.length,n.copy(_,s),s+=n.length,d.copy(_,s),s+=d.length,_},toJSON:function(){let s=function(h){return"<"+(h&&h.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:t.toJSON(),compressedData:s(e),data:s(a)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Zt=T((xi,zt)=>{"use strict";var jt=je(),lr=ke(),$=Y();zt.exports=function(o,e){var t=[],n={},r=Buffer.alloc(0),i=new lr.MainHeader,a=!1,c=null;let d=new Set,g=e,{noSort:C,decoder:E}=g;o?u(g.readEntries):a=!0;function S(){let f=new Set;for(let m of Object.keys(n)){let y=m.split("/");if(y.pop(),!!y.length)for(let s=0;s<y.length;s++){let h=y.slice(0,s+1).join("/")+"/";f.add(h)}}for(let m of f)if(!(m in n)){let y=new jt(g);y.entryName=m,y.attr=16,y.temporary=!0,t.push(y),n[y.entryName]=y,d.add(y)}}function l(){if(a=!0,n={},i.diskEntries>(o.length-i.offset)/$.Constants.CENHDR)throw $.Errors.DISK_ENTRY_TOO_LARGE();t=new Array(i.diskEntries);for(var f=i.offset,m=0;m<t.length;m++){var y=f,s=new jt(g,o);s.header=o.slice(y,y+=$.Constants.CENHDR),s.entryName=o.slice(y,y+=s.header.fileNameLength),s.header.extraLength&&(s.extra=o.slice(y,y+=s.header.extraLength)),s.header.commentLength&&(s.comment=o.slice(y,y+s.header.commentLength)),f+=s.header.centralHeaderSize,t[m]=s,n[s.entryName]=s}d.clear(),S()}function u(f){var m=o.length-$.Constants.ENDHDR,y=Math.max(0,m-65535),s=y,h=o.length,_=-1,x=0;for(typeof g.trailingSpace=="boolean"&&g.trailingSpace&&(y=0),m;m>=s;m--)if(o[m]===80){if(o.readUInt32LE(m)===$.Constants.ENDSIG){_=m,x=m,h=m+$.Constants.ENDHDR,s=m-$.Constants.END64HDR;continue}if(o.readUInt32LE(m)===$.Constants.END64SIG){s=y;continue}if(o.readUInt32LE(m)===$.Constants.ZIP64SIG){_=m,h=m+$.readBigUInt64LE(o,m+$.Constants.ZIP64SIZE)+$.Constants.ZIP64LEAD;break}}if(_==-1)throw $.Errors.INVALID_FORMAT();i.loadFromBinary(o.slice(_,h)),i.commentLength&&(r=o.slice(x+$.Constants.ENDHDR)),f&&l()}function p(){t.length>1&&!C&&t.sort((f,m)=>f.entryName.toLowerCase().localeCompare(m.entryName.toLowerCase()))}return{get entries(){return a||l(),t.filter(f=>!d.has(f))},get comment(){return E.decode(r)},set comment(f){r=$.toBuffer(f,E.encode),i.commentLength=r.length},getEntryCount:function(){return a?t.length:i.diskEntries},forEach:function(f){this.entries.forEach(f)},getEntry:function(f){return a||l(),n[f]||null},setEntry:function(f){a||l(),t.push(f),n[f.entryName]=f,i.totalEntries=t.length},deleteFile:function(f,m=!0){a||l();let y=n[f];this.getEntryChildren(y,m).map(h=>h.entryName).forEach(this.deleteEntry)},deleteEntry:function(f){a||l();let m=n[f],y=t.indexOf(m);y>=0&&(t.splice(y,1),delete n[f],i.totalEntries=t.length)},getEntryChildren:function(f,m=!0){if(a||l(),typeof f=="object")if(f.isDirectory&&m){let y=[],s=f.entryName;for(let h of t)h.entryName.startsWith(s)&&y.push(h);return y}else return[f];return[]},getChildCount:function(f){if(f&&f.isDirectory){let m=this.getEntryChildren(f);return m.includes(f)?m.length-1:m.length}return 0},compressToBuffer:function(){a||l(),p();let f=[],m=[],y=0,s=0;i.size=0,i.offset=0;let h=0;for(let w of this.entries){let D=w.getCompressedData();w.header.offset=s;let I=w.packLocalHeader(),P=I.length+D.length;s+=P,f.push(I),f.push(D);let N=w.packCentralHeader();m.push(N),i.size+=N.length,y+=P+N.length,h++}y+=i.mainHeaderSize,i.offset=s,i.totalEntries=h,s=0;let _=Buffer.alloc(y);for(let w of f)w.copy(_,s),s+=w.length;for(let w of m)w.copy(_,s),s+=w.length;let x=i.toBinary();return r&&r.copy(x,$.Constants.ENDHDR),x.copy(_,s),o=_,a=!1,_},toAsyncBuffer:function(f,m,y,s){try{a||l(),p();let h=[],_=[],x=0,w=0,D=0;i.size=0,i.offset=0;let I=function(P){if(P.length>0){let N=P.shift(),k=N.entryName+N.extra.toString();y&&y(k),N.getCompressedDataAsync(function(B){s&&s(k),N.header.offset=w;let ae=N.packLocalHeader(),Ke=ae.length+B.length;w+=Ke,h.push(ae),h.push(B);let ye=N.packCentralHeader();_.push(ye),i.size+=ye.length,x+=Ke+ye.length,D++,I(P)})}else{x+=i.mainHeaderSize,i.offset=w,i.totalEntries=D,w=0;let N=Buffer.alloc(x);h.forEach(function(B){B.copy(N,w),w+=B.length}),_.forEach(function(B){B.copy(N,w),w+=B.length});let k=i.toBinary();r&&r.copy(k,$.Constants.ENDHDR),k.copy(N,w),o=N,a=!1,f(N)}};I(Array.from(this.entries))}catch(h){m(h)}}}}});var Kt=T((Ai,Xt)=>{"use strict";var b=Y(),F=M("path"),cr=je(),ur=Zt(),q=(...o)=>b.findLast(o,e=>typeof e=="boolean"),qt=(...o)=>b.findLast(o,e=>typeof e=="string"),fr=(...o)=>b.findLast(o,e=>typeof e=="function"),hr={noSort:!1,readEntries:!1,method:b.Constants.NONE,fs:null};Xt.exports=function(o,e){let t=null,n=Object.assign(Object.create(null),hr);o&&typeof o=="object"&&(o instanceof Uint8Array||(Object.assign(n,o),o=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(o)&&(t=o,n.method=b.Constants.BUFFER,o=void 0)),Object.assign(n,e);let r=new b(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=b.decoder),o&&typeof o=="string")if(r.fs.existsSync(o))n.method=b.Constants.FILE,n.filename=o,t=r.fs.readFileSync(o);else throw b.Errors.INVALID_FILENAME();let i=new ur(t,n),{canonical:a,sanitize:c,zipnamefix:d}=b;function g(l){if(l&&i){var u;if(typeof l=="string"&&(u=i.getEntry(F.posix.normalize(l))),typeof l=="object"&&typeof l.entryName<"u"&&typeof l.header<"u"&&(u=i.getEntry(l.entryName)),u)return u}return null}function C(l){let{join:u,normalize:p,sep:f}=F.posix;return u(F.isAbsolute(l)?"/":".",p(f+l.split("\\").join(f)+f))}function E(l){return l instanceof RegExp?(function(u){return function(p){return u.test(p)}})(l):typeof l!="function"?()=>!0:l}let S=(l,u)=>{let p=u.slice(-1);return p=p===r.sep?r.sep:"",F.relative(l,u)+p};return{readFile:function(l,u){var p=g(l);return p&&p.getData(u)||null},childCount:function(l){let u=g(l);if(u)return i.getChildCount(u)},readFileAsync:function(l,u){var p=g(l);p?p.getDataAsync(u):u(null,"getEntry failed for:"+l)},readAsText:function(l,u){var p=g(l);if(p){var f=p.getData();if(f&&f.length)return f.toString(u||"utf8")}return""},readAsTextAsync:function(l,u,p){var f=g(l);f?f.getDataAsync(function(m,y){if(y){u(m,y);return}m&&m.length?u(m.toString(p||"utf8")):u("")}):u("")},deleteFile:function(l,u=!0){var p=g(l);p&&i.deleteFile(p.entryName,u)},deleteEntry:function(l){var u=g(l);u&&i.deleteEntry(u.entryName)},addZipComment:function(l){i.comment=l},getZipComment:function(){return i.comment||""},addZipEntryComment:function(l,u){var p=g(l);p&&(p.comment=u)},getZipEntryComment:function(l){var u=g(l);return u&&u.comment||""},updateFile:function(l,u){var p=g(l);p&&p.setData(u)},addLocalFile:function(l,u,p,f){if(r.fs.existsSync(l)){u=u?C(u):"";let m=F.win32.basename(F.win32.normalize(l));u+=p||m;let y=r.fs.statSync(l),s=y.isFile()?r.fs.readFileSync(l):Buffer.alloc(0);y.isDirectory()&&(u+=r.sep),this.addFile(u,s,f,y)}else throw b.Errors.FILE_NOT_FOUND(l)},addLocalFileAsync:function(l,u){l=typeof l=="object"?l:{localPath:l};let p=F.resolve(l.localPath),{comment:f}=l,{zipPath:m,zipName:y}=l,s=this;r.fs.stat(p,function(h,_){if(h)return u(h,!1);m=m?C(m):"";let x=F.win32.basename(F.win32.normalize(p));if(m+=y||x,_.isFile())r.fs.readFile(p,function(w,D){return w?u(w,!1):(s.addFile(m,D,f,_),setImmediate(u,void 0,!0))});else if(_.isDirectory())return m+=r.sep,s.addFile(m,Buffer.alloc(0),f,_),setImmediate(u,void 0,!0)})},addLocalFolder:function(l,u,p){if(p=E(p),u=u?C(u):"",l=F.normalize(l),r.fs.existsSync(l)){let f=r.findFiles(l),m=this;if(f.length)for(let y of f){let s=F.join(u,S(l,y));p(s)&&m.addLocalFile(y,F.dirname(s))}}else throw b.Errors.FILE_NOT_FOUND(l)},addLocalFolderAsync:function(l,u,p,f){f=E(f),p=p?C(p):"",l=F.normalize(l);var m=this;r.fs.open(l,"r",function(y){if(y&&y.code==="ENOENT")u(void 0,b.Errors.FILE_NOT_FOUND(l));else if(y)u(void 0,y);else{var s=r.findFiles(l),h=-1,_=function(){if(h+=1,h<s.length){var x=s[h],w=S(l,x).split("\\").join("/");w=w.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),f(w)?r.fs.stat(x,function(D,I){D&&u(void 0,D),I.isFile()?r.fs.readFile(x,function(P,N){P?u(void 0,P):(m.addFile(p+w,N,"",I),_())}):(m.addFile(p+w+"/",Buffer.alloc(0),"",I),_())}):process.nextTick(()=>{_()})}else u(!0,void 0)};_()}})},addLocalFolderAsync2:function(l,u){let p=this;l=typeof l=="object"?l:{localPath:l},localPath=F.resolve(C(l.localPath));let{zipPath:f,filter:m,namefix:y}=l;m instanceof RegExp?m=(function(_){return function(x){return _.test(x)}})(m):typeof m!="function"&&(m=function(){return!0}),f=f?C(f):"",y=="latin1"&&(y=_=>_.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof y!="function"&&(y=_=>_);let s=_=>F.join(f,y(S(localPath,_))),h=_=>F.win32.basename(F.win32.normalize(y(_)));r.fs.open(localPath,"r",function(_){_&&_.code==="ENOENT"?u(void 0,b.Errors.FILE_NOT_FOUND(localPath)):_?u(void 0,_):r.findFilesAsync(localPath,function(x,w){if(x)return u(x);w=w.filter(D=>m(s(D))),w.length||u(void 0,!1),setImmediate(w.reverse().reduce(function(D,I){return function(P,N){if(P||N===!1)return setImmediate(D,P,!1);p.addLocalFileAsync({localPath:I,zipPath:F.dirname(s(I)),zipName:h(I)},D)}},u))})})},addLocalFolderPromise:function(l,u){return new Promise((p,f)=>{this.addLocalFolderAsync2(Object.assign({localPath:l},u),(m,y)=>{m&&f(m),y&&p(this)})})},addFile:function(l,u,p,f){l=d(l);let m=g(l),y=m!=null;y||(m=new cr(n),m.entryName=l),m.comment=p||"";let s=typeof f=="object"&&f instanceof r.fs.Stats;s&&(m.header.time=f.mtime);var h=m.isDirectory?16:0;let _=m.isDirectory?16384:32768;return s?_|=4095&f.mode:typeof f=="number"?_|=4095&f:_|=m.isDirectory?493:420,h=(h|_<<16)>>>0,m.attr=h,m.setData(u),y||i.setEntry(m),m},getEntries:function(l){return i.password=l,i?i.entries:[]},getEntry:function(l){return g(l)},getEntryCount:function(){return i.getEntryCount()},forEach:function(l){return i.forEach(l)},extractEntryTo:function(l,u,p,f,m,y){f=q(!1,f),m=q(!1,m),p=q(!0,p),y=qt(m,y);var s=g(l);if(!s)throw b.Errors.NO_ENTRY();var h=a(s.entryName),_=c(u,y&&!s.isDirectory?y:p?h:F.basename(h));if(s.isDirectory){var x=i.getEntryChildren(s);return x.forEach(function(I){if(I.isDirectory)return;var P=I.getData();if(!P)throw b.Errors.CANT_EXTRACT_FILE();var N=a(I.entryName),k=c(u,p?N:F.basename(N));let B=m?I.header.fileAttr:void 0;r.writeFileTo(k,P,f,B)}),!0}var w=s.getData(i.password);if(!w)throw b.Errors.CANT_EXTRACT_FILE();if(r.fs.existsSync(_)&&!f)throw b.Errors.CANT_OVERRIDE();let D=m?l.header.fileAttr:void 0;return r.writeFileTo(_,w,f,D),!0},test:function(l){if(!i)return!1;for(var u in i.entries)try{if(u.isDirectory)continue;var p=i.entries[u].getData(l);if(!p)return!1}catch{return!1}return!0},extractAllTo:function(l,u,p,f){if(p=q(!1,p),f=qt(p,f),u=q(!1,u),!i)throw b.Errors.NO_ZIP();i.entries.forEach(function(m){var y=c(l,a(m.entryName));if(m.isDirectory){r.makeDir(y);return}var s=m.getData(f);if(!s)throw b.Errors.CANT_EXTRACT_FILE();let h=p?m.header.fileAttr:void 0;r.writeFileTo(y,s,u,h);try{r.fs.utimesSync(y,m.header.time,m.header.time)}catch{throw b.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(l,u,p,f){if(f=fr(u,p,f),p=q(!1,p),u=q(!1,u),!f)return new Promise((_,x)=>{this.extractAllToAsync(l,u,p,function(w){w?x(w):_(this)})});if(!i){f(b.Errors.NO_ZIP());return}l=F.resolve(l);let m=_=>c(l,F.normalize(a(_.entryName))),y=(_,x)=>new Error(_+': "'+x+'"'),s=[],h=[];i.entries.forEach(_=>{_.isDirectory?s.push(_):h.push(_)});for(let _ of s){let x=m(_),w=p?_.header.fileAttr:void 0;try{r.makeDir(x),w&&r.fs.chmodSync(x,w),r.fs.utimesSync(x,_.header.time,_.header.time)}catch{f(y("Unable to create folder",x))}}h.reverse().reduce(function(_,x){return function(w){if(w)_(w);else{let D=F.normalize(a(x.entryName)),I=c(l,D);x.getDataAsync(function(P,N){if(N)_(N);else if(!P)_(b.Errors.CANT_EXTRACT_FILE());else{let k=p?x.header.fileAttr:void 0;r.writeFileToAsync(I,P,u,k,function(B){B||_(y("Unable to write file",I)),r.fs.utimes(I,x.header.time,x.header.time,function(ae){ae?_(y("Unable to set times",I)):_()})})}})}}},f)()},writeZip:function(l,u){if(arguments.length===1&&typeof l=="function"&&(u=l,l=""),!l&&n.filename&&(l=n.filename),!!l){var p=i.compressToBuffer();if(p){var f=r.writeFileTo(l,p,!0);typeof u=="function"&&u(f?null:new Error("failed"),"")}}},writeZipPromise:function(l,u){let{overwrite:p,perm:f}=Object.assign({overwrite:!0},u);return new Promise((m,y)=>{!l&&n.filename&&(l=n.filename),l||y("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(s=>{let h=_=>_?m(_):y("ADM-ZIP: Wasn't able to write zip file");r.writeFileToAsync(l,s,p,f,h)},y)})},toBufferPromise:function(){return new Promise((l,u)=>{i.toAsyncBuffer(l,u)})},toBuffer:function(l,u,p,f){return typeof l=="function"?(i.toAsyncBuffer(l,u,p,f),null):i.compressToBuffer()}}}});import Ce from"path";import{fileURLToPath as Or}from"url";import{styleText as V}from"util";import Sr from"@inquirer/checkbox";var ft=Je(ut(),1),{program:Hr,createCommand:Ur,createArgument:Pr,createOption:$r,CommanderError:Br,InvalidArgumentError:Mr,InvalidOptionArgumentError:Wr,Command:ht,Argument:Vr,Option:kr,Help:Gr}=ft.default;import ee from"fs";import dt from"path";import{fileURLToPath as An}from"url";var In=An(import.meta.url),Ln=dt.dirname(In),te=dt.resolve(Ln,"..","..","generated-profile-name.types.ts"),Dn=o=>o.replace(/(^\w)/g,e=>e.toUpperCase());async function mt({walletName:o,profileName:e}){let t=Dn(o),n=`export type ${t}Profiles = "${e}";`;if(ee.existsSync(te)){let r=ee.readFileSync(te,"utf-8"),i=r.match(new RegExp(`export type ${t}Profiles = ("[^"]+"(?:\\s*\\|\\s*"[^"]+")*)`));if(i){let a=i[0];if(!a.includes(`"${e}"`)){let c=a.concat(` | "${e}"`),d=r.replace(a,c);try{ee.writeFileSync(te,d)}catch(g){console.error("Error updating existing profile name type: ",g)}}}else try{ee.appendFileSync(te,`
|
|
28
|
-
${n}`,{encoding:"utf-8"})}catch(a){console.error("Error appending new profile name type: ",a)}}else try{ee.writeFileSync(te,n)}catch(r){console.error("Error writing new profile name type: ",r)}}import Tn from"path";import{pathToFileURL as vn}from"url";import{styleText as Fn}from"util";import{glob as bn}from"glob";import Nn from"path";function $e(o){let e=Nn.basename(o),t=e.match(/^([a-z0-9_]+)(?:-[a-z0-9_]+)*\.setup\.(?:ts|js|mjs)$/i);if(!t)throw new Error(`Invalid wallet setup filename: ${e} (expected "<name>[ -variant].setup.{ts,js,mjs}")`);return t[1]}var Rn=o=>o.replace(/\\/g,"/"),Hn=o=>`${Rn(Tn.resolve(o))}/**/*.setup.{ts,js,}`;async function Be({walletSetupDir:o,selectedWallets:e}){let t=Hn(o),n=(await bn(t,{dot:!0,absolute:!0,nodir:!0,windowsPathsNoEscape:!0})).sort(),r=e.length===1?e[0]:e,i=["metamask","solflare","petra","meteor","keplr","phantom"];Array.isArray(r)&&r.forEach(g=>{i.includes(g)||console.warn(Fn("magenta",`Unsupported wallet: "${g}". Supported wallets are: ${i.join(", ")}`,{validateStream:!1}))});let c=(r==="all"?n:Array.isArray(r)?n.filter(g=>r.some(C=>g.includes(C))):n.filter(g=>g.includes(r))).map(g=>({filePath:g,walletName:$e(g)}));if(!c.length||c.length===0)throw new Error([`No wallet setup file found at ${o} for wallet: "${e}".`,'Setup files must use a ".setup.{ts,js,mjs}" extension and include a valid wallet name.','Examples: "metamask.setup.ts", "solflare.setup.ts", "phantom.setup.ts", "metamask-connected.setup.ts"'].join(`
|
|
29
|
-
`));return await Promise.all(c.map(async({filePath:g,walletName:C})=>{let S=await import(new URL(vn(g)).href).then(f=>f.default),{fn:l,config:u,password:p}=S;return{walletName:C,fileList:c,config:u,walletPassword:p,setupFunction:l}}))}import z from"fs";import _e from"path";import{styleText as Z}from"util";import{chromium as yr}from"@playwright/test";import Me from"path";import{fileURLToPath as Un}from"url";var Pn=Un(import.meta.url),$n=Me.dirname(Pn),Bn=Me.resolve($n,"..","../.wallet-cache");function ne(o){return Me.resolve(`${Bn}/${o}`)}import{z as fe}from"zod";var Mn=fe.object({id:fe.string(),name:fe.string()}),Wn=fe.array(Mn);async function pt(o,e){let t=await o.newPage();await t.goto("chrome://extensions");let n=await t.evaluate("chrome.management.getAll()"),r=Wn.parse(n),i=r.find(a=>a.name.toLowerCase()===e.toLowerCase());if(!i)throw new Error([`[GetExtensionId] Extension with name ${e} not found.`,`Available extensions: ${r.map(a=>a.name).join(", ")}`].join(`
|
|
30
|
-
`));return await t.close(),i.id}var Et="wallet-setup",gt="13.22.0",re="https://github.com/amaify/chainwright/releases/download/v0.1.0/",Vn=`https://github.com/MetaMask/metamask-extension/releases/download/v${gt}/metamask-chrome-${gt}.zip`,kn=`${re}solflare-wallet-extension-v2.19.1.zip`,Gn=`${re}petra-wallet-extension-v2.4.8.zip`,jn=`${re}phantom-wallet-extension-v26.10.0.zip`,zn=`${re}meteor-wallet-extension-v0.7.0.zip`,Zn=`${re}keplr-wallet-extension-v0.13.3.zip`,he={metamask:{downloadUrl:Vn,extensionName:"MetaMask"},solflare:{downloadUrl:kn,extensionName:"Solflare Wallet"},petra:{downloadUrl:Gn,extensionName:"Petra Aptos Wallet"},phantom:{downloadUrl:jn,extensionName:"Phantom"},meteor:{downloadUrl:zn,extensionName:"Meteor Wallet"},keplr:{downloadUrl:Zn,extensionName:"Keplr"}};var Qt=Je(Kt(),1);import X from"fs";import Ze from"path";import{styleText as oe}from"util";import{createWriteStream as dr}from"fs";import{Readable as mr}from"stream";import{styleText as ze}from"util";import pr from"cli-progress";var gr=12e4;async function Yt({url:o,destination:e}){let t=new AbortController,n=setTimeout(()=>t.abort(),gr),r=await fetch(o,{redirect:"follow",signal:t.signal});r.ok||(console.error(ze("redBright",`\u274C Download failed: HTTP ${r.status}`,{validateStream:!1})),t.abort(),process.exit(1));let i=parseInt(r.headers.get("content-length")||"0",10),a=0,c=mr.fromWeb(r.body);try{let d=new pr.SingleBar({format:`Downloading ${ze("cyan","{bar}",{validateStream:!1})} {percentage}%`,clearOnComplete:!0,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0});d.start(i,0,{speed:"N/A"}),await new Promise((g,C)=>{let E=dr(e);c.pipe(E),c.on("data",S=>{a+=S.length,d.update(a)}),E.on("error",C),E.on("finish",()=>{d.stop(),g(void 0)})})}catch(d){console.error(ze("redBright",`\u274C Download failed: ${d}`,{validateStream:!1})),process.exit(1)}finally{clearTimeout(n)}}var Jt=!1;async function en({downloadUrl:o,name:e,force:t}){let n=ne(e),i=he[e].extensionName,a=Ze.join(n,`${e}-extension.zip`),c=Ze.join(n,`${e}-extension`);if(t&&X.existsSync(n)&&(X.rmSync(n,{recursive:!0}),console.info(oe("magenta",`\u{1F9F9} Removed ${i} because of the force flag`,{validateStream:!1}))),X.existsSync(n)||X.mkdir(n,{recursive:!0},g=>{if(g)throw Error("Failed to create cache directory");console.info(`\u2705 ${i} Cache directory created successfully.`)}),X.existsSync(c)?console.info(`\u2705 ${i} Version is downloaded already.`):(console.info(oe("cyanBright",`\u{1F4E5} Downloading ${i} extension...`,{validateStream:!1})),await Yt({url:o,destination:a}),console.info(oe("green",`\u2705 ${e.toUpperCase()} Extension downloaded successfully.`,{validateStream:!1}))),!X.existsSync(c))console.info("\u{1F4E6} Extracting extension..."),new Qt.default(a).extractAllTo(c,!0),console.info(`\u2705 ${i} Extension extracted successfully.`);else{if(Jt)return console.info(oe("magentaBright",`Using the cached ${i} extension for profile creation.`,{validateStream:!1})),c;console.info(oe("yellow",`\u26A0\uFE0F Skipping ${i} cache creation: Cache already exists at ${c}. Use --force to overwrite.`,{validateStream:!1}))}let d=Ze.join(c,"manifest.json");if(!X.existsSync(d))throw new Error(`\u274C (${i}) Invalid extension: manifest.json not found`);return Jt=!0,c}import{styleText as Er}from"util";function qe(o){return new Promise(e=>setTimeout(e,o))}var Ee=20,_r=6e3,tn=4e3;async function Cr(o){return o.pages().find(n=>{try{return n.url().startsWith("chrome-extension://")}catch(r){return console.error("[WaitForExtensionOnLoadPage] Error checking page URL:",r),!1}})}async function nn(o,e){let t=0,n=null;if(e==="meteor")return await o.newPage();for(console.info(`Waiting ${tn}ms for browser to initialize...`),await qe(tn);t<=Ee;)try{if(console.info(`Looking for extension page (attempt ${t+1}/${Ee})...`),t===Ee)throw new Error("Extension page not found after maximum retries");let r=await Cr(o);if(r){console.info(`Found extension page after ${t+1} polling attempts`),n=r;break}r||(t++,console.info(`Extension page not found, retrying (${t}/${Ee})...`),await qe(_r))}catch(r){throw console.error("Error waiting for extension page:",r instanceof Error?r.message:"Unknown error"),new Error(`Extension failed to load properly after ${t} attempts!`)}return console.info(Er("greenBright","\u2705 Extension page is properly loaded and ready",{validateStream:!1})),n}async function Xe({walletName:o,force:e,config:t,fileList:n,walletPassword:r,setupFunction:i}){let{downloadUrl:a,extensionName:c}=he[o],d=ne(o),g=t?.profileName,C=g?`${g}`:"wallet-data",E=_e.resolve(d,"extension-id.txt"),S=_e.resolve(d,"extension-path.txt"),l=_e.resolve(d,"password.txt"),u=_e.resolve(d,C),p=await en({downloadUrl:a,name:o,force:e}),f=[`--disable-extensions-except=${p}`,`--load-extension=${p}`];if(z.existsSync(u)&&n.length>1)throw Error([Z("yellowBright",[`\u274C ${C} directory already exists for ${c}.`,`
|
|
31
|
-
To setup another wallet profile, add a profile name to the wallet setup function.`,Z(["blueBright","italic"],'Example: defineWalletSetup(async ({ context, walletPage }) => { ... }, { profileName: "profile-name" });'),Z("italic","You can also use the --force flag to overwrite the existing cache.")].join(`
|
|
2
|
+
import O from"path";import{fileURLToPath as Te}from"url";import{styleText as d}from"util";import De from"@inquirer/checkbox";import{Command as Re}from"commander";import L from"fs";import H from"path";import{fileURLToPath as ee}from"url";var te=ee(import.meta.url),oe=H.dirname(te),$=H.resolve(oe,"..","..","generated-profile-name.types.ts"),re=e=>e.replace(/(^\w)/g,o=>o.toUpperCase());async function G({walletName:e,profileName:o}){let t=re(e),a=`export type ${t}Profiles = "${o}";`;if(L.existsSync($)){let r=L.readFileSync($,"utf-8"),s=r.match(new RegExp(`export type ${t}Profiles = ("[^"]+"(?:\\s*\\|\\s*"[^"]+")*)`));if(s){let l=s[0];if(!l.includes(`"${o}"`)){let i=l.concat(` | "${o}"`),c=r.replace(l,i);try{L.writeFileSync($,c)}catch(n){console.error("Error updating existing profile name type: ",n)}}}else try{L.appendFileSync($,`
|
|
3
|
+
${a}`,{encoding:"utf-8"})}catch(l){console.error("Error appending new profile name type: ",l)}}else try{L.writeFileSync($,a)}catch(r){console.error("Error writing new profile name type: ",r)}}import ne from"path";import{pathToFileURL as se}from"url";import{styleText as ie}from"util";import{glob as le}from"glob";import ae from"path";function N(e){let o=ae.basename(e),t=o.match(/^([a-z0-9_]+)(?:-[a-z0-9_]+)*\.setup\.(?:ts|js|mjs)$/i);if(!t)throw new Error(`Invalid wallet setup filename: ${o} (expected "<name>[ -variant].setup.{ts,js,mjs}")`);return t[1]}var pe=e=>e.replace(/\\/g,"/"),ce=e=>`${pe(ne.resolve(e))}/**/*.setup.{ts,js,}`;async function U({walletSetupDir:e,selectedWallets:o}){let t=ce(e),a=(await le(t,{dot:!0,absolute:!0,nodir:!0,windowsPathsNoEscape:!0})).sort(),r=o.length===1?o[0]:o,s=["metamask","solflare","petra","meteor","keplr","phantom"];Array.isArray(r)&&r.forEach(n=>{s.includes(n)||console.warn(ie("magenta",`Unsupported wallet: "${n}". Supported wallets are: ${s.join(", ")}`,{validateStream:!1}))});let i=(r==="all"?a:Array.isArray(r)?a.filter(n=>r.some(u=>n.includes(u))):a.filter(n=>n.includes(r))).map(n=>({filePath:n,walletName:N(n)}));if(!i.length||i.length===0)throw new Error([`No wallet setup file found at ${e} for wallet: "${o}".`,'Setup files must use a ".setup.{ts,js,mjs}" extension and include a valid wallet name.','Examples: "metamask.setup.ts", "solflare.setup.ts", "phantom.setup.ts", "metamask-connected.setup.ts"'].join(`
|
|
4
|
+
`));return await Promise.all(i.map(async({filePath:n,walletName:u})=>{let m=await import(new URL(se(n)).href).then(S=>S.default),{fn:w,config:y,password:x}=m;return{walletName:u,fileList:i,config:y,walletPassword:x,setupFunction:w}}))}import E from"fs";import R from"path";import{styleText as v}from"util";import{chromium as Fe}from"@playwright/test";import k from"path";import{fileURLToPath as me}from"url";var fe=me(import.meta.url),ue=k.dirname(fe),de=k.resolve(ue,"..","../.wallet-cache");function P(e){return k.resolve(`${de}/${e}`)}import{z as F}from"zod";var we=F.object({id:F.string(),name:F.string()}),ge=F.array(we);async function K(e,o){let t=await e.newPage();await t.goto("chrome://extensions");let a=await t.evaluate("chrome.management.getAll()"),r=ge.parse(a),s=r.find(l=>l.name.toLowerCase()===o.toLowerCase());if(!s)throw new Error([`[GetExtensionId] Extension with name ${o} not found.`,`Available extensions: ${r.map(l=>l.name).join(", ")}`].join(`
|
|
5
|
+
`));return await t.close(),s.id}var Y="wallet-setup",V="13.22.0",C="https://github.com/amaify/chainwright/releases/download/v0.1.0/",he=`https://github.com/MetaMask/metamask-extension/releases/download/v${V}/metamask-chrome-${V}.zip`,ye=`${C}solflare-wallet-extension-v2.19.1.zip`,xe=`${C}petra-wallet-extension-v2.4.8.zip`,Se=`${C}phantom-wallet-extension-v26.10.0.zip`,Ee=`${C}meteor-wallet-extension-v0.7.0.zip`,ve=`${C}keplr-wallet-extension-v0.13.3.zip`,T={metamask:{downloadUrl:he,extensionName:"MetaMask"},solflare:{downloadUrl:ye,extensionName:"Solflare Wallet"},petra:{downloadUrl:xe,extensionName:"Petra Aptos Wallet"},phantom:{downloadUrl:Se,extensionName:"Phantom"},meteor:{downloadUrl:Ee,extensionName:"Meteor Wallet"},keplr:{downloadUrl:ve,extensionName:"Keplr"}};import A from"fs";import M from"path";import{styleText as _}from"util";import Ce from"adm-zip";import{createWriteStream as Ae}from"fs";import{Readable as Le}from"stream";import{styleText as B}from"util";import $e from"cli-progress";var Pe=12e4;async function X({url:e,destination:o}){let t=new AbortController,a=setTimeout(()=>t.abort(),Pe),r=await fetch(e,{redirect:"follow",signal:t.signal});r.ok||(console.error(B("redBright",`\u274C Download failed: HTTP ${r.status}`,{validateStream:!1})),t.abort(),process.exit(1));let s=parseInt(r.headers.get("content-length")||"0",10),l=0,i=Le.fromWeb(r.body);try{let c=new $e.SingleBar({format:`Downloading ${B("cyan","{bar}",{validateStream:!1})} {percentage}%`,clearOnComplete:!0,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0});c.start(s,0,{speed:"N/A"}),await new Promise((n,u)=>{let p=Ae(o);i.pipe(p),i.on("data",m=>{l+=m.length,c.update(l)}),p.on("error",u),p.on("finish",()=>{c.stop(),n(void 0)})})}catch(c){console.error(B("redBright",`\u274C Download failed: ${c}`,{validateStream:!1})),process.exit(1)}finally{clearTimeout(a)}}var q=!1;async function Z({downloadUrl:e,name:o,force:t}){let a=P(o),s=T[o].extensionName,l=M.join(a,`${o}-extension.zip`),i=M.join(a,`${o}-extension`);if(t&&A.existsSync(a)&&(A.rmSync(a,{recursive:!0}),console.info(_("magenta",`\u{1F9F9} Removed ${s} because of the force flag`,{validateStream:!1}))),A.existsSync(a)||A.mkdir(a,{recursive:!0},n=>{if(n)throw Error("Failed to create cache directory");console.info(`\u2705 ${s} Cache directory created successfully.`)}),A.existsSync(i)?console.info(`\u2705 ${s} Version is downloaded already.`):(console.info(_("cyanBright",`\u{1F4E5} Downloading ${s} extension...`,{validateStream:!1})),await X({url:e,destination:l}),console.info(_("green",`\u2705 ${o.toUpperCase()} Extension downloaded successfully.`,{validateStream:!1}))),!A.existsSync(i))console.info("\u{1F4E6} Extracting extension..."),new Ce(l).extractAllTo(i,!0),console.info(`\u2705 ${s} Extension extracted successfully.`);else{if(q)return console.info(_("magentaBright",`Using the cached ${s} extension for profile creation.`,{validateStream:!1})),i;console.info(_("yellow",`\u26A0\uFE0F Skipping ${s} cache creation: Cache already exists at ${i}. Use --force to overwrite.`,{validateStream:!1}))}let c=M.join(i,"manifest.json");if(!A.existsSync(c))throw new Error(`\u274C (${s}) Invalid extension: manifest.json not found`);return q=!0,i}import{styleText as _e}from"util";function j(e){return new Promise(o=>setTimeout(o,e))}var D=20,We=6e3,J=4e3;async function be(e){return e.pages().find(a=>{try{return a.url().startsWith("chrome-extension://")}catch(r){return console.error("[WaitForExtensionOnLoadPage] Error checking page URL:",r),!1}})}async function Q(e,o){let t=0,a=null;if(o==="meteor")return await e.newPage();for(console.info(`Waiting ${J}ms for browser to initialize...`),await j(J);t<=D;)try{if(console.info(`Looking for extension page (attempt ${t+1}/${D})...`),t===D)throw new Error("Extension page not found after maximum retries");let r=await be(e);if(r){console.info(`Found extension page after ${t+1} polling attempts`),a=r;break}r||(t++,console.info(`Extension page not found, retrying (${t}/${D})...`),await j(We))}catch(r){throw console.error("Error waiting for extension page:",r instanceof Error?r.message:"Unknown error"),new Error(`Extension failed to load properly after ${t} attempts!`)}return console.info(_e("greenBright","\u2705 Extension page is properly loaded and ready",{validateStream:!1})),a}async function z({walletName:e,force:o,config:t,fileList:a,walletPassword:r,setupFunction:s}){let{downloadUrl:l,extensionName:i}=T[e],c=P(e),n=t?.profileName,u=n?`${n}`:"wallet-data",p=R.resolve(c,"extension-id.txt"),m=R.resolve(c,"extension-path.txt"),w=R.resolve(c,"password.txt"),y=R.resolve(c,u),x=await Z({downloadUrl:l,name:e,force:o}),S=[`--disable-extensions-except=${x}`,`--load-extension=${x}`];if(E.existsSync(y)&&a.length>1)throw Error([v("yellowBright",[`\u274C ${u} directory already exists for ${i}.`,`
|
|
6
|
+
To setup another wallet profile, add a profile name to the wallet setup function.`,v(["blueBright","italic"],'Example: defineWalletSetup(async ({ context, walletPage }) => { ... }, { profileName: "profile-name" });'),v("italic","You can also use the --force flag to overwrite the existing cache.")].join(`
|
|
32
7
|
`),{validateStream:!1})].join(`
|
|
33
|
-
`));if(
|
|
34
|
-
Setting up cache for ${
|
|
35
|
-
\u274C Failed to setup cache for ${
|
|
36
|
-
\u274C Attempt ${
|
|
8
|
+
`));if(E.existsSync(y))return;let f=await Fe.launchPersistentContext(y,{headless:!1,args:S,slowMo:t?.slowMo??0});console.info(v("magentaBright",`\u{1F9E9}\u{1F680} Starting Chrome extension for ${e.toUpperCase()}`,{validateStream:!1}));let I=await Q(f,e);if(!E.existsSync(p)&&!E.existsSync(m)){let b=await K(f,i);console.info(v("magentaBright",`\u{1F194} ${i} extension ID: ${b}`,{validateStream:!1})),E.writeFileSync(p,b,"utf-8"),console.info(v("cyanBright",`\u{1F4BE} Saved extension ID to: ${p}`,{validateStream:!1})),E.writeFileSync(m,x,"utf-8"),console.info(v("blueBright",`\u{1F4C1} Saved extension Path to: ${m}`,{validateStream:!1})),E.writeFileSync(w,r,"utf-8"),console.info(v("yellowBright",`\u{1F511} Saved ${e} password to: ${w}`,{validateStream:!1}))}try{await s({context:f,walletPage:I})}catch(b){await f.close(),E.rmSync(c,{force:!0,recursive:!0}),console.error("Error setting up wallet: ",b.message)}await f.close()}var Oe=Te(import.meta.url),Ie=O.dirname(Oe),Ne=O.join(Ie,"..","tests",Y),W=2;async function Ue(){let e=new Re;e.name(d("yellow","Chainwright")).description(d("green","A CLI tool for setting up wallet cache for E2E testing of web3 applications")).version(d("blue","0.0.0")),e.command("chainwright").argument("[dir]","Directory containing the wallet setup functions",O.resolve(Ne)).option("--headless","Build cache in the headless browser mode. Alternatively, set the `HEADLESS` env variable to `true`",!1).option("-f, --force","Force the creation of cache even if it already exists",!1).option("-a, --all","Setup all wallets","all").option("--kp, --keplr","Setup Keplr","keplr").option("-m, --metamask","Setup MetaMask","metamask").option("--mt, --meteor","Setup Meteor","meteor").option("--pt, --petra","Setup Petra","petra").option("--ph, --phantom","Setup Phantom","phantom").option("-s, --solflare","Setup Solflare","solflare").option("--wls, --wallets <wallets...>","Specify wallets to setup (e.g., --wallets keplr metamask)").action(async(o,t)=>{let a=["all","metamask","solflare","petra","meteor","keplr","phantom"],r=Object.keys(t).filter(p=>a.includes(p)?t[p]===!0:!1),s=r.length>0,l=t.wallets,i=l||(s?r:await De({message:"Select the wallet you want to setup",choices:[{name:"All",value:"all"},{name:"Keplr",value:"keplr"},{name:"MetaMask",value:"metamask"},{name:"Meteor",value:"meteor"},{name:"Petra",value:"petra"},{name:"Phantom",value:"phantom"},{name:"Solflare",value:"solflare"}],validate:p=>{let m=p.map(w=>w.value);return m.includes("all")&&m.length>1?'Select either "All" or specific wallets, not both.':!0},pageSize:10})),c=o,n=e.commands[0]?.args??[];n[0]&&(c=O.resolve(process.cwd(),n[0])),t.headless&&(process.env.HEADLESS=!0);let u=await U({walletSetupDir:c,selectedWallets:i});for(let{walletName:p,config:m,walletPassword:w,setupFunction:y,fileList:x}of u)try{console.info(d("cyanBright",`
|
|
9
|
+
Setting up cache for ${p}...`,{validateStream:!1})),await z({walletName:p,config:m,setupFunction:y,fileList:x,force:t.force,walletPassword:w}),m.profileName&&await G({walletName:p,profileName:m.profileName})}catch(S){if(S.message.includes("directory already exists")&&console.warn(S.message),!S.message.includes("directory already exists")){console.error(d("redBright",`
|
|
10
|
+
\u274C Failed to setup cache for ${p}: ${S.message}`,{validateStream:!1}));let f=0;for(;W>f;){console.info(`${d("yellow",`Retry Attempt ${f+1} of ${W} for ${p}...`,{validateStream:!1})}`),console.info(d("yellow","Retrying wallet setup...",{validateStream:!1}));try{await z({walletName:p,config:m,setupFunction:y,fileList:x,force:t.force,walletPassword:w});break}catch(I){f+1<W&&console.error(d("redBright",`
|
|
11
|
+
\u274C Attempt ${f+1} failed! Retrying...`,{validateStream:!1})),f++,f===W&&console.error(d("redBright",`\u274C Failed to setup cache after ${W} attempts for ${p}: ${I.message}`,{validateStream:!1}))}}}}}),await e.parseAsync(process.argv)}Ue().catch(e=>console.error(d("redBright",`Failed to run the CLI: ${e.message})`,{validateStream:!1})));export{Ue as clientEntry};
|
package/dist/core/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
async function
|
|
1
|
+
async function u(t,r,p={}){return{fn:r,password:t,config:p}}import{test as s,mergeTests as i}from"@playwright/test";function a(t){return i(s,t)}export{u as defineWalletSetup,a as testWithChainwright};
|
package/dist/wallets/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import{expect as
|
|
2
|
-
Already on ${e} account. No need to switch.`);return}await a.click();let n=t.locator("div[class='simplebar-content'] > div").locator("> div",{hasText:e});if(!await n.isVisible().catch(()=>!1))throw new Error(`Account "${e}" not found. Make sure the account is onboarded or verify the account name.`);let i=t.locator("div:has-text('Select Wallet')").last();await n.click(),await i.waitFor({state:"detached",timeout:3e4})}async function
|
|
3
|
-
Keplr onboarding started...`,{validateStream:!1})),e.length===1)for(let{privateKey:a,walletName:o,chains:n}of e)await
|
|
4
|
-
\u26A0\uFE0F Skipping test: ${e}`),Na.skip())}var P={buyButton:"eth-overview-buy",swapButton:"eth-overview-swap",sendButton:"eth-overview-send",receiveButton:"eth-overview-receive",openSettingsButton:"account-options-menu-button",accountMenuButton:"account-menu-icon",accountCell:"multichain-account-cell-entropy",openNetworkSelectorButton:"sort-by-networks",accountAddressesButton:"networks-subtitle-test-id",accountAddressesElements:"multichain-address-row",accountAddressQRCode:"multichain-address-row-qr-button"},Bt={lockButton:"global-menu-lock",networksButton:"global-menu-networks"},$t={passwordInput:"unlock-password",unlockButton:"unlock-submit"},ot={accountOptionsMenuButton:"multichain-account-cell-end-accessory",accountDetailsLabel:"Account details",renameAccountLabel:"Rename",addressesLabel:"Addresses",pinToTopLabel:"Pin to top",hideAccountLabel:"Hide account",backButton:"back",addMultichainAccountButton:"add-multichain-account-button",addWalletButton:"account-list-add-wallet-button",importWalletButton:"add-wallet-modal-import-wallet",importAccountButton:"add-wallet-modal-import-account"};var F={createWalletButton:"onboarding-create-wallet",importWalletButton:"onboarding-import-wallet",useSecretRecoveryPhraseButton:"onboarding-create-with-srp-button",createNewPasswordInput:"create-password-new-input",confirmNewPasswordInput:"create-password-confirm-input",confirmPasswordCheckbox:"create-password-terms",createPasswordButton:"create-password-submit",revealSecretRecoveryPhraseButton:"recovery-phrase-reveal",recoveryPhraseRemindMeLaterButton:"recovery-phrase-remind-later",metamaskMetricsIAgreeButton:"metametrics-i-agree",onboardingDoneButton:"onboarding-complete-done",importUsingSecretRecoveryPhraseButton:"onboarding-import-with-srp-button",secretRecoveryPhraseTextAreaInput:"srp-input-import__srp-note",importWalletConfirmButton:"import-srp-confirm",importAccountConfirmButton:"import-account-confirm-button",importSRPError:"bannerAlert"};async function eo({page:t,privateKey:e,accountName:a}){let o=to.string().min(1,"Account name cannot be an empty string").trim().parse(a),n=to.string().min(1,"Private key cannot be an empty string").trim().parse(e),r=t.getByTestId(P.accountMenuButton);await L(r).toBeVisible({timeout:3e4}),await r.click(),await L(t.getByRole("heading",{name:/accounts/i})).toBeVisible();let i=t.getByTestId(ot.addWalletButton),c=await i.textContent();c?.includes("Syncing")&&await L.poll(async()=>(await i.textContent())?.trim()??"",{timeout:12e4}).not.toBe(c),await L(i).toBeEnabled({timeout:6e4}),await i.click();let s=t.getByRole("dialog");await L(s).toContainText(/add wallet/i),await t.getByTestId(ot.importAccountButton).click(),await t.locator("input[id='private-key-box']").fill(n);let m=t.getByTestId(F.importAccountConfirmButton);await L(m).toBeEnabled(),await m.click();let p=t.getByTestId(F.importSRPError),w=await p.isVisible().catch(()=>!1);w&&Je(w,`${(await p.textContent())?.split(".")[0]}`);let d=t.locator("div:has(> div[data-testid^='multichain-account-cell-keyring'][class*='mm-box--background-color-background-muted'])"),g=(await d.textContent())?.split("$")[0];g&&await Ma({page:t,accountName:o,activeAccountLocator:d,activeAccountName:g}),await t.locator("button[aria-label='Back']").first().click()}async function Ma({page:t,accountName:e,activeAccountLocator:a,activeAccountName:o}){let n=a.locator(`div[aria-label='${o} options']`);await L(n).toBeVisible(),await n.click(),await L(t.getByRole("tooltip")).toBeVisible();let r=t.locator(`div[aria-label='${ot.renameAccountLabel}']`);await L(r).toBeVisible(),await r.click();let i=t.getByRole("dialog"),c=i.getByRole("heading",{name:/rename/i});await L(c).toBeVisible();let s=i.getByRole("textbox");await L(s).toBeVisible(),await s.fill(e);let l=i.getByRole("button",{name:/confirm/i});await L(l).toBeEnabled(),await l.click(),await i.waitFor({state:"detached",timeout:2e4});let u=t.locator("div:has(> div[data-testid^='multichain-account-cell-keyring'][class*='mm-box--background-color-background-muted'])");await L(u).toContainText(e)}import{expect as Lt}from"@playwright/test";import kt from"zod";var oo=kt.object({networkName:kt.string().min(1,"Network name cannot be an empty string"),rpcUrl:kt.url(),chainId:kt.number().or(kt.string().includes("0x")),currencySymbol:kt.string().toUpperCase().min(1,"Currency symbol cannot be an empty string")});import{expect as Ea}from"@playwright/test";async function Zt(t){let e=t.locator("div:has(> p[data-testid='notifications-tag-counter__unread-dot'])"),a=t.getByTestId(P.openSettingsButton);await e.isVisible().catch(()=>!1)?await e.click():(await Ea(a).toBeVisible(),await a.click())}async function ao({page:t,...e}){let{chainId:a,currencySymbol:o,networkName:n,rpcUrl:r}=oo.parse({...e},{reportInput:!0});await Zt(t),await t.getByTestId(Bt.networksButton).click();let c=t.locator("section[role='dialog']");await Lt(c).toContainText(/manage networks/i),await t.getByRole("button",{name:/add a custom network/i}).click(),await Lt(c).toContainText(/Add a custom network/i);let l=t.getByTestId("network-form-network-name"),u=t.getByTestId("test-add-rpc-drop-down"),m=t.getByTestId("network-form-chain-id"),p=t.getByTestId("network-form-ticker-input");await l.fill(n),await u.click(),await t.getByRole("tooltip").locator("div:has(> button:has-text('Add RPC URL'))").click(),await Lt(c).toContainText(/Add RPC URL/i);let g=t.getByTestId("rpc-url-input-test"),f=t.getByRole("button",{name:/Add URL/i});await g.fill(r),await f.click(),await Lt(c).toContainText(/Add a custom network/i);let h=t.getByTestId("network-form-chain-id-error");if(await h.isVisible().catch(()=>!1)){let C=await h.textContent();throw Error(`RPC error: ${C}`)}await m.fill(`${a}`),await p.fill(o);let A=t.getByRole("button",{name:/save/i});await Lt(A).toBeEnabled(),await A.click()}import{expect as no}from"@playwright/test";var Jt={confirmButton:"confirm-footer-button",cancelButton:"confirm-footer-cancel-button"};async function ro(t,e){let a=t.getByTestId(Jt.confirmButton);await y(2e3);let n=(await a.textContent())?.includes("Review alert"),r=await a.isDisabled().catch(()=>!1);if(n&&r){await t.getByTestId("edit-gas-fees-row").locator("> div").first().click();let u=t.getByRole("dialog");await no(u).toBeVisible();let m=u.locator("h4",{hasText:"Insufficient funds"}),p=await u.getByTestId("alert-modal__selected-alert").textContent();if(await m.isVisible().catch(()=>!1))throw Error(`${p}`)}if(e){let s=t.getByTestId("edit-gas-fee-icon");if(await s.scrollIntoViewIfNeeded(),await s.click(),e.feeType!=="advanced"&&await t.getByTestId(`gas-option-${e.feeType}`).click(),e.feeType==="advanced"){await t.getByTestId("gas-option-advanced").click();let u=t.getByRole("textbox",{name:"Max base fee"}),m=t.getByRole("textbox",{name:"Priority fee"}),p=t.getByRole("button",{name:"Save",exact:!0});await u.fill(e.maxBaseFee),await m.fill(e.priorityFee),await p.click()}}await no(a).toBeEnabled(),await a.click();let i=t.getByRole("dialog");await i.isVisible().catch(()=>!1)&&await i.locator("h4",{hasText:"Your assets may be at risk"}).isVisible().catch(()=>!1)&&(await i.getByTestId("alert-modal-acknowledge-checkbox").click(),await i.getByTestId("confirm-alert-modal-submit-button").click()),await t.waitForEvent("close",{timeout:15e3})}import{expect as Ra}from"@playwright/test";import{expect as Pe}from"@playwright/test";async function bt({page:t,accountName:e}){let a=t.getByTestId(P.accountMenuButton);if(await a.textContent()===e){console.info(`Can't switch account to "${e}", it is already selected.`);return}await Pe(a).toBeVisible({timeout:15e3}),await a.click(),await Pe(t.getByRole("heading",{name:/accounts/i})).toBeVisible();let n=t.getByTestId(ot.addMultichainAccountButton),r=await n.textContent();r?.includes("Syncing")&&await Pe.poll(async()=>(await n.textContent())?.trim()??"",{timeout:6e4}).not.toBe(r);let i=await t.getByTestId(/^multichain-account-cell-(?:entropy|keyring):/).all(),c=null;for(let s of i)if(await s.scrollIntoViewIfNeeded(),(await s.textContent())?.includes(e)){c=s;break}if(!c)throw Error(`Account with name "${e}" not found.`);await c?.click()}async function io(t,e){e&&await bt({page:t,accountName:e});let a=t.getByRole("button",{name:"Connect",exact:!0});await a.waitFor({state:"visible",timeout:25e3}),await a.click(),await t.getByRole("heading",{name:"Connecting",exact:!0}).waitFor({state:"detached",timeout:3e4});let n;await Ra.poll(async()=>(n=await t.locator("div[class='permissions-connect']").isVisible().catch(()=>!1),n),{timeout:25e3}).toBe(!0).catch(()=>console.error("Notice dialog did not appear within the timeout period."));let r=t.getByTestId("page-container-footer-next");await r.waitFor({state:"visible",timeout:25e3}),await r.click(),await t.waitForEvent("close",{predicate:()=>!0,timeout:25e3}).catch(()=>console.error("Extension popup did not close within the timeout period when connecting to the DApp."))}async function co(t,e){return await t.getByTestId(P.accountAddressesButton).hover(),await t.getByTestId("multichain-address-rows-list").getByRole("button",{name:/view all/i}).click(),await t.getByRole("searchbox",{name:/search networks/i}).fill(e),await t.locator(`div[data-testid='${P.accountAddressesElements}']:has-text('${e}')`).getByTestId(P.accountAddressQRCode).click(),await t.getByRole("dialog").locator("div > p[data-testid='account-address']").textContent()}import{expect as La}from"@playwright/test";import{errors as _a}from"@playwright/test";var so={loadingOverlay:"loading-overlay",loadingSpinner:"spinner loading-overlay__spinner"};var Va=6e4,$a=async(t,e,a)=>{await M(e);try{await e.locator(`div[class="${t}"]`).waitFor({state:"detached",timeout:a})}catch(o){if(o instanceof _a.TimeoutError)console.info(`Loading indicator '${t}' not found - continuing.`);else throw console.error(`Error while waiting for loading indicator '${t}' to disappear`),o}},te=async t=>{try{await $a(so.loadingSpinner,t,Va)}catch(e){console.warn("Warning during MetaMask load:",e)}return await y(300),t};async function lo(t){if(await t.getByTestId($t.unlockButton).isVisible().catch(()=>!1)){console.info("\u{1F4A1} Wallet is already locked");return}await Zt(t);let o=t.getByTestId(Bt.lockButton);await La(o).toBeVisible(),await o.click(),await te(t)}import{styleText as uo}from"util";import{expect as At}from"@playwright/test";var Q=class{name="metamask";onboardingPath="/home.html#onboarding";async indexUrl(){return`chrome-extension://${await this.extensionId()}/home.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/notification.html`}async extensionId(){return await U(this.name)}async promptPage(e){let a=await this.promptUrl();return await D({context:e,path:a,locator:"div[data-testid='multichain-page']"})}};import{expect as Ae}from"@playwright/test";async function Pt({page:t}){await t.locator(`div:has(> button[data-testid='${P.openSettingsButton}'])`).click(),await t.getByTestId(Bt.networksButton).click();let o=t.locator("section[role='dialog']");await Ae(o).toBeVisible(),await Ae(o).toContainText(/manage networks/i);let n="div:has(> p:has-text('Show test networks'))";await o.locator(n).scrollIntoViewIfNeeded();let r=o.locator(n);if(!await r.locator("label[class='toggle-button toggle-button--off']").isVisible().catch(()=>!1)){await o.getByRole("button",{name:/close/i}).click(),console.info("Testnet networks are already visible.");return}await r.locator("label[class='toggle-button toggle-button--off']").click(),await t.getByTestId("Sepolia").scrollIntoViewIfNeeded(),await Ae(t.getByTestId("Sepolia")).toBeVisible(),await o.getByRole("button",{name:/close/i}).click()}async function Ce({page:t,mainAccountName:e,...a}){console.info(uo("yellowBright",`
|
|
5
|
-
\u{1F98A} MetaMask onboarding started...`,{validateStream:!1}));let o=await k("metamask"),n=new Q,r=t.locator("img[class='loading-spinner']"),i=t.getByTestId(F.createWalletButton),c=t.getByTestId(F.importWalletButton),s=t.getByTestId(F.createNewPasswordInput),l=t.getByTestId(F.confirmNewPasswordInput),u=t.getByTestId(F.confirmPasswordCheckbox),m=t.getByTestId(F.createPasswordButton),p=t.getByTestId(F.metamaskMetricsIAgreeButton),w=t.getByTestId(F.onboardingDoneButton);if(await r.waitFor({state:"detached",timeout:3e4}),a.mode==="create"){let A=t.getByTestId(F.useSecretRecoveryPhraseButton);await i.click(),await A.click(),await s.fill(o),await l.fill(o),await u.click(),await m.click(),await t.getByTestId(F.revealSecretRecoveryPhraseButton).click(),await t.getByTestId(F.recoveryPhraseRemindMeLaterButton).click(),await p.click()}if(a.mode==="import"){let{secretRecoveryPhrase:A}=a,C=A.split(" "),R=t.getByTestId(F.importUsingSecretRecoveryPhraseButton);await c.click(),await R.click();let V=t.getByTestId(F.secretRecoveryPhraseTextAreaInput);await V.fill(C[0]),await V.press("Space");for(let Y=1;Y<C.length;Y++){let zt=t.getByTestId(`import-srp__srp-word-${Y}`);await zt.fill(C[Y]),await zt.press("Space")}await t.getByTestId(F.importWalletConfirmButton).click(),await s.fill(o),await l.fill(o),await u.click(),await m.click(),await p.click();let et=t.getByTestId("wallet-ready");await At(et).toContainText(/your wallet is ready/i)}await w.click();let g=`chrome-extension://${await n.extensionId()}/sidepanel.html`,h=await t.context().browser()?.newBrowserCDPSession(),S;await At.poll(async()=>{if(h){let{targetInfos:A}=await h.send("Target.getTargets"),C=A.find(R=>R.url===g);return S=C,!!C}},{timeout:15e3}).toBe(!0),S&&await h?.send("Target.closeTarget",{targetId:S.targetId}),await t.goto(await n.indexUrl()),await r.waitFor({state:"detached",timeout:3e4}),await At(t.getByTestId(P.buyButton)).toBeVisible(),await At(t.getByTestId(P.swapButton)).toBeVisible(),await At(t.getByTestId(P.sendButton)).toBeVisible(),await At(t.getByTestId(P.receiveButton)).toBeVisible(),await Pt({page:t}),e&&await bt({page:t,accountName:e}),await y(5e3),console.info(uo("greenBright","\u2728 MetaMask onboarding completed successfully",{validateStream:!1}))}import{expect as Oa}from"@playwright/test";async function mo(t){let e=t.getByTestId(Jt.cancelButton);await y(1e3),await Oa(e).toBeEnabled(),await e.click()}import{expect as z}from"@playwright/test";async function po({page:t,currentAccountName:e,newAccountName:a}){let o=t.getByTestId(P.accountMenuButton);if(await o.textContent()===a)throw Error(`The account to be renamed "${a}" already exists.`);await z(o).toBeVisible({timeout:15e3}),await o.click(),await z(t.getByRole("heading",{name:/accounts/i})).toBeVisible();let r=t.getByTestId(ot.addMultichainAccountButton),i=await r.textContent();i?.includes("Syncing")&&await z.poll(async()=>(await r.textContent())?.trim()??"",{timeout:6e4}).not.toBe(i);let c=await t.getByTestId(/^multichain-account-cell/).all(),s=null;for(let h of c)if((await h.textContent())?.includes(e)){s=h;break}if(!s)throw Error(`Account with name "${e}" not found.`);if((await s.textContent())?.split("$")[0]===a)throw Error(`The new account name "${a}" is the same as the old account name "${e}".`);let u=t.locator(`div[aria-label='${e} options']`);await z(u).toBeVisible(),await u.click(),await z(t.getByRole("tooltip")).toBeVisible();let m=t.locator(`div[aria-label='${ot.renameAccountLabel}']`);await z(m).toBeVisible(),await m.click();let p=t.getByRole("dialog"),w=p.getByRole("heading",{name:/rename/i});await z(w).toBeVisible();let d=p.getByRole("textbox");await z(d).toBeVisible(),await d.fill(a);let g=p.getByRole("button",{name:/confirm/i});await z(g).toBeEnabled(),await g.click();for(let h of c)if((await h.textContent())?.includes(a)){await z(h).toBeVisible(),await z(h).toContainText(a);break}await t.locator("button[aria-label='Back']").first().click()}import{expect as Se}from"@playwright/test";async function wo({page:t,networkType:e,chainName:a}){let o=t.getByTestId(P.openNetworkSelectorButton);await o.click();let n=t.getByTestId("modal-header-close-button");if(e==="testnet"||e==="custom"){let s=t.getByRole("tab",{name:"Custom"});await s.click(),await t.locator("p:has-text('Testnets')").isVisible().catch(()=>!1)||(await n.click(),await Pt({page:t}),await o.click(),await s.click());let m=t.locator(`div div[data-testid='${a}']`),p=await m.textContent();Se(p).toBe(a),await m.click();return}await t.getByRole("tab",{name:"Popular"}).click();let i=t.locator(`div div[data-testid='${a}']`),c=await i.textContent();Se(c).toBe(a),await i.click(),await Se(o).toContainText(a,{timeout:3e4})}import{expect as fo}from"@playwright/test";async function Ot(t){let e=await k("metamask"),a=t.getByTestId($t.passwordInput);if(await t.getByTestId(P.openNetworkSelectorButton).isVisible().catch(()=>!1)){console.info("\u{1F4A1} Wallet is already unlocked");return}await a.fill(e);let r=t.getByTestId($t.unlockButton);await fo(r).toBeVisible(),await r.click(),await te(t),await fo(t.getByTestId(P.buyButton)).toBeVisible({timeout:3e4})}var lt=class extends Q{page;constructor(e){super(),this.page=e}async onboard(e){await Ce({page:this.page,...e})}async unlock(){await Ot(this.page)}async lock(){await lo(this.page)}async renameAccount({newAccountName:e,currentAccountName:a}){await po({page:this.page,newAccountName:e,currentAccountName:a})}async addAccount({privateKey:e,accountName:a}){await eo({page:this.page,privateKey:e,accountName:a})}async switchAccount({accountName:e}){await bt({page:this.page,accountName:e})}async switchNetwork({...e}){await wo({page:this.page,...e})}async getAccountAddress(e){return await co(this.page,e)}async toggleShowTestnetNetwork(){await Pt({page:this.page})}async addCustomNetwork({chainId:e,currencySymbol:a,networkName:o,rpcUrl:n}){await ao({page:this.page,chainId:e,currencySymbol:a,networkName:o,rpcUrl:n})}async connectToApp(e){await io(await this.promptPage(this.page.context()),e)}async confirmTransaction(e){await ro(await this.promptPage(this.page.context()),e)}async rejectTransaction(){await mo(await this.promptPage(this.page.context()))}};import go from"fs";import Da from"path";import{test as Ua,chromium as Ka}from"@playwright/test";import{Instance as Ha,Pool as ja}from"prool";var Dt,Rs=({slowMo:t=0,profileName:e}={})=>Ua.extend({contextPath:async({browserName:a},o,n)=>{let r=await v(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new Q,i=x(r.name),c=await I(r.name),s=Da.resolve(i,e??"wallet-data");if(!go.existsSync(s))throw new Error("\u274C Cache for MetaMask wallet data not found. Create it first");go.cpSync(s,o,{recursive:!0,force:!0});let l=[`--disable-extensions-except=${c}`,`--load-extension=${c}`];process.env.HEADLESS&&(l.push("--headless=new"),t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!"));let u=await Ka.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:t}),{cookies:m,origins:p}=await a.storageState();m&&await u.addCookies(m),p&&p.length>0&&$(p,u);let w=await r.indexUrl();await u.waitForEvent("page",{predicate:f=>f.url().startsWith(w),timeout:3e4}),Dt=u.pages().find(f=>f.url().startsWith(w))??await E(u,w);for(let f of u.pages())f.url().includes("about:blank")&&await f.close();await Dt.locator("img[class='loading-spinner']").waitFor({state:"detached"}),await Ot(Dt),await n(u),await b(u,o)},metamaskPage:async({context:a},o)=>{await o(Dt)},metamask:async({context:a},o)=>{let n=new lt(Dt);await o(n)},createAnvilNode:async({context:a},o,n)=>{let r=n.workerIndex,i;await o(async c=>{i=ja.define({instance:Ha.anvil(c)});let s=await i.start(r),l=`http://${s.host}:${s.port}`,m=c?.chainId??31337;return{rpcUrl:l,anvil:s,chainId:m}}),i&&await i.stop(r)},connectToAnvil:async({context:a,metamask:o,createAnvilNode:n},r)=>{await r(async()=>{let{chainId:i,rpcUrl:c}=await n({chainId:2251});await o.addCustomNetwork({chainId:i,currencySymbol:"ETH",networkName:"Anvil Localnet",rpcUrl:c})})}});import{test as qa}from"@playwright/test";import{Instance as Ya,Pool as Qa}from"prool";import ho from"fs";import Ga from"path";import{chromium as za}from"@playwright/test";async function yo({workerInfo:t,profileName:e,slowMo:a}){let o=new Q,n=await v(t.workerIndex.toString()),r=x(o.name),i=Ga.resolve(r,e??"wallet-data");if(!ho.existsSync(i))throw new Error(`Cache for ${o.name} does not exist. Create it first!`);ho.cpSync(i,n,{recursive:!0,force:!0});let c=await I(o.name),s=await za.launchPersistentContext(n,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:a}),l=await o.indexUrl();await s.waitForEvent("page",{predicate:m=>m.url().startsWith(l),timeout:4e4});let u=s.pages().find(m=>m.url().startsWith(l));u||(u=await s.newPage(),await u.goto(l),await M(u));for(let m of s.pages())m.url().includes("about:blank")&&await m.close();return{context:s,walletPage:u,contextPath:n}}var Xs=({profileName:t,dappUrl:e,slowMo:a}={})=>qa.extend({workerScopeContents:[async({browser:o},n,r)=>{let{context:i,contextPath:c,walletPage:s}=await yo({workerInfo:r,profileName:t,slowMo:a});await i.grantPermissions(["clipboard-read"]);let l=new lt(s);await l.unlock(),await n({wallet:l,walletPage:s,context:i}),await b(i,c)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();e&&await i.goto(e),await n(i)},{scope:"worker"}],metamaskPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},metamask:async({workerScopeContents:o},n)=>{let r=new lt(o.walletPage);await n(r)},createAnvilNode:async({context:o},n,r)=>{let i=r.workerIndex,c;await n(async s=>{c=Qa.define({instance:Ya.anvil(s)});let l=await c.start(i),u=`http://${l.host}:${l.port}`,p=s?.chainId??31337;return{rpcUrl:u,anvil:l,chainId:p}}),c&&await c.stop(i)},connectToAnvil:async({context:o,metamask:n,createAnvilNode:r},i)=>{await i(async()=>{let{chainId:c,rpcUrl:s}=await r({chainId:2251});await n.addCustomNetwork({chainId:c,currencySymbol:"ETH",networkName:"Anvil Localnet",rpcUrl:s})})}});var _={openSidebarMenuButton:"button[aria-label='open sidebar']",addWalletButton:"button:has-text('Add Wallet')",settingsButton:"button:has-text('Settings')",settingsMenuBackButton:"button[aria-label='Back']"};var K={importExistingWalletButton:'button:has-text("Import an existing wallet")',switchNetworkButton:"button[id^='menu-button']",privateKeyButton:"button:has-text('Private Key')",findMyAccountButton:"button:has-text('Find my account')"};async function ee(t,e,a){let o=t.locator(K.switchNetworkButton).last();await o.scrollIntoViewIfNeeded();let n=await o.textContent(),r=e.split("net")[0]?.toLowerCase()??"";if(n?.toLowerCase()===r)return console.info(`
|
|
6
|
-
Already on ${e}, no need to switch network.`),"Exit";await o.click();let c=t.locator(a).last().locator(`> button:has-text('${e}')`);await c.click(),await t.locator("div > h2:has-text('Meteor Community')").isVisible().catch(()=>!1)&&await c.click()}async function
|
|
7
|
-
Switching to the ${e} account aborted. Account is already selected.`);return}await t.locator(
|
|
8
|
-
`))}async function
|
|
9
|
-
Meteor onboarding started...`,{validateStream:!1}));let r=await
|
|
10
|
-
Retrying search for account. ${
|
|
11
|
-
`),{validateStream:!1}))}await t.locator("button:not([aria-label='Back'],[id^='menu-button']):has-text('Account')").click();let
|
|
12
|
-
Switching to ${e} account aborted because the account is already selected.`);return}await a.click();let r=await t.getByRole("dialog").locator("> div > div > button[type='button']").all(),i=null;for(let c of r)if((await c.textContent())?.toLowerCase()?.trim().includes(e.toLowerCase().trim())){i=c;break}if(!i)throw new Error(`Account with name "${e}" not found.`);await i.click()}async function
|
|
13
|
-
Petra onboarding started...`,{validateStream:!1}));let a=new J,o=await k("petra"),n=t.locator(W.createWalletButton),r=t.locator(W.importWalletButton),i=t.locator(W.createNewPasswordInput),c=t.locator(W.confirmNewPasswordInput),s=t.locator(W.confirmPasswordCheckbox),l=t.locator(W.continueButton),u=t.locator(W.getStartedButton),m=t.locator(W.onboardingCompleteText);if(e.mode==="create"){let p=t.locator(W.createSeedPhraseButton);await n.click(),await p.click(),await i.fill(o),await c.fill(o),await s.click(),await l.click(),await t.locator(W.skipCopyRecoveryPhraseButton).click(),await u.click(),await at(m).toBeVisible({timeout:25e3}),await t.goto(await a.indexUrl()),await at(t.locator(T.depositButton)).toBeVisible({timeout:Ft}),await at(t.locator(T.sendButton)).toBeVisible({timeout:Ft})}if(e.mode==="importPrivateKey"){let{privateKey:p}=e,w=t.locator(W.importUsingPrivateKeyButton),d=t.locator(W.privateKeyInput),g=t.locator(W.importButton);await r.click(),await w.click(),await d.fill(p),await g.click(),await i.fill(o),await c.fill(o),await s.click(),await l.click(),await u.click(),await at(m).toBeVisible({timeout:25e3}),await t.goto(await a.indexUrl()),await M(t),await at(t.locator(T.depositButton)).toBeVisible({timeout:Ft}),await at(t.locator(T.sendButton)).toBeVisible({timeout:Ft})}if(e.mode==="importMnemonic"){let{secretRecoveryPhrase:p}=e,w=t.locator(W.importUsingMnemonicButton);await r.click(),await w.click();for(let[d,g]of p.split(" ").entries())await t.locator(`input[name="mnemonic-${String.fromCharCode(97+d)}"]`).fill(g);await l.click(),await i.fill(o),await c.fill(o),await s.click(),await l.click(),await u.click(),await at(m).toBeVisible({timeout:25e3}),await t.goto(await a.indexUrl()),await at(t.locator(T.depositButton)).toBeVisible({timeout:Ft}),await at(t.locator(T.sendButton)).toBeVisible({timeout:Ft})}if(await mt({page:t,newAccountName:e.accountName}),e.addWallet&&e.addWallet.length>0){for(let{...p}of e.addWallet)await ne({page:t,...p});await Wt(t,e.accountName)}await y(1500),console.info(No("greenBright","\u2728 Petra onboarding completed successfully",{validateStream:!1}))}import{expect as cn}from"@playwright/test";async function Mo(t){let e=t.locator(Tt.cancelButton);await cn(e).toBeEnabled(),await e.click()}async function Eo(t,e){await t.locator(T.settingsMenu).click(),await t.locator(Te.networkSection).click(),await t.locator(`div:has(> span:has-text("${e}"))`).first().click();let r=t.locator(Te.backButton);await r.click(),await r.click()}import{expect as Ro}from"@playwright/test";async function Ht(t){let e=await k("petra"),a=t.locator(We.passwordInput);if(!await a.isVisible().then(()=>!0).catch(()=>!1)){console.info("\u{1F4A1} Wallet is already unlocked");return}await Ro(a).toBeVisible({timeout:15e3}),await a.fill(e);let n=t.locator(We.unlockButton);await Ro(n).toBeEnabled(),await n.click(),await Promise.allSettled([t.locator(T.sendButton).waitFor({state:"visible",timeout:2e4}),t.locator(T.receiveButton).waitFor({state:"visible",timeout:2e4})])}var pt=class extends J{page;constructor(e){super(),this.page=e}async onboard(e){await Fe({page:this.page,...e})}async unlock(){await Ht(this.page)}async lock(){await Fo(this.page)}async renameAccount({newAccountName:e}){await mt({page:this.page,newAccountName:e})}async switchNetwork(e){await Eo(this.page,e)}async switchAccount(e){await Wt(this.page,e)}async getAccountAddress(){return await Io(this.page)}async addAccount({accountName:e,...a}){await ne({page:this.page,accountName:e,...a})}async connectToApp(e){await vo(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await So(await this.promptPage(this.page.context()))}async rejectTransaction(){await Mo(await this.promptPage(this.page.context()))}};import _o from"fs";import sn from"path";import{test as ln,chromium as un}from"@playwright/test";var jt,sp=({slowMo:t=0,profileName:e}={})=>ln.extend({contextPath:async({browserName:a},o,n)=>{let r=await v(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new J,i=x(r.name),c=await I(r.name),s=sn.resolve(i,e??"wallet-data");if(!_o.existsSync(s))throw new Error("\u274C Cache for Petra wallet data not found. Create it first");_o.cpSync(s,o,{recursive:!0,force:!0});let l=[`--disable-extensions-except=${c}`,`--load-extension=${c}`];process.env.HEADLESS&&(l.push("--headless=new"),t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!"));let u=await un.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:t});await u.grantPermissions(["clipboard-read"]);let{cookies:m,origins:p}=await a.storageState();m&&await u.addCookies(m),p&&p.length>0&&$(p,u);let w=await r.indexUrl();jt=u.pages().find(g=>g.url().startsWith(w))||await E(u,w);for(let g of u.pages()){let f=g.url();(f.includes("about:blank")||f.includes(r.onboardingPath))&&await g.close()}await jt.bringToFront(),await Ht(jt),await n(u),await b(u,o)},petraPage:async({context:a},o)=>{await o(jt)},petra:async({context:a},o)=>{let n=new pt(jt);await o(n)}});import{test as mn}from"@playwright/test";var fp=({slowMo:t,profileName:e,dappUrl:a}={})=>mn.extend({workerScopeContents:[async({browser:o},n,r)=>{let i=new J,{context:c,contextPath:s,walletPage:l}=await xt({wallet:i,workerInfo:r,profileName:e,slowMo:t});await c.grantPermissions(["clipboard-read"]);for(let m of c.pages())m.url().includes(i.onboardingPath)&&await m.close();let u=new pt(l);await u.unlock(),await n({wallet:u,walletPage:l,context:c}),await b(c,s)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],petraPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},petra:async({workerScopeContents:o},n)=>{let r=new pt(o.walletPage);await n(r)}});var N={openMenuButton:"settings-menu-open-button",settingsButton:"sidebar_menu-button-settings",addAccountButton:"sidebar_menu-button-add_account",unlockWalletButton:"unlock-form-submit-button",manageAccountsButton:"sidebar_menu-button-manage_accounts",homeHeaderAccountName:"home-header-account-name"},O={lockWalletButton:"lock-menu-item",closeMenuButton:"settings-menu-close-button",developerSettingsButton:"settings-item-developer-settings",activeNetworksButton:"settings-item-active-networks"},Vo={accountProfileContainer:"sortable-account-container"};var B={createNewWalletButton:"button:has-text('Create a new wallet')",IAlreadyHaveAWalletButton:"button:has-text('I already have a wallet')",importRecoveryPhraseButton:"button:has-text('Import Recovery Phrase')",importPrivateKeyButton:"button:has-text('Import Private Key')",createSeedPhraseWalletButton:"create-manual-seed-phrase",passwordInput:"onboarding-form-password-input",passwordConfirmInput:"onboarding-form-confirm-password-input",termsCheckBox:"onboarding-form-terms-of-service-checkbox",continueButton:"button:has-text('Continue')",importWalletButton:"button:has-text('Import Wallet')",getStartedButton:"button:has-text('Get Started')",recoveryPhraseSavedCheckbox:"onboarding-form-saved-secret-recovery-phrase-checkbox",recoveryPhraseInput:"secret-recovery-phrase-word-input"};async function re({page:t,privateKey:e,accountName:a,chain:o}){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.addAccountButton).click(),await t.locator(B.importPrivateKeyButton).click();let c=t.locator("span[id^='button--listbox-input--']"),s=await c.textContent(),l=t.locator("input[name='name']"),u=t.locator("textarea[name='privateKey']");s!==o&&(await c.click(),await t.locator("ul[id^='listbox--listbox-input--']").locator(`li[data-label='${o}']`).click()),await l.fill(a),await u.fill(e),await t.locator("button:has-text('Import')").click()}var Nt={confirmButton:"primary-button",cancelButton:"secondary-button"};async function $o(t){let e=t.getByTestId(Nt.confirmButton);await t.getByTestId("approve-transaction").waitFor({state:"attached"});let o=t.getByRole("button",{name:"Confirm anyway",exact:!0});if(await o.isVisible().catch(()=>!1)){await o.click();return}await e.click()}import{expect as dn}from"@playwright/test";import pn from"zod";async function Mt(t,e){let a=pn.string().min(1,"Account name cannot be an empty string").parse(e);await t.getByTestId(N.openMenuButton).click();let n=null,r=await t.locator("div[data-testid='account-menu'] div[data-testid='tooltip_interactive-wrapper']").all();for(let i of r)if((await i.textContent())?.includes(a)){n=i;break}if(!n)throw new Error(`Account with name "${a}" not found in the account list.`);await n.click()}async function Lo(t,e){e&&await Mt(t,e);let a=t.getByTestId(Nt.confirmButton);await dn(a).toBeEnabled({timeout:15e3}),await a.click()}import wn from"zod";var fn=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");async function Oo({page:t,accountName:e,chain:a}){let o=wn.string().min(1,"Account name cannot be an empty string").parse(e);await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.manageAccountsButton).click(),await t.getByTestId(`manage-accounts-sortable-${o}`).click();let c=t.getByRole("button",{name:/Account Address(?:es)?/i});await c.waitFor({state:"visible",timeout:2e4});let l=await c.locator("div[data-name='row.pair'] > div").last().textContent();if(l&&Number(l)===1){await c.locator("> div > div").last().click(),await t.getByTestId("header--back").click();let p=t.getByTestId(O.closeMenuButton);await p.waitFor({state:"visible",timeout:15e3}),await p.click()}else{await c.click();let m=new RegExp(`${fn(a.network)}`,"i");await t.getByRole("button",{name:m}).locator("> div").last().locator("> div").last().locator("div > button").last().click(),await t.getByRole("button",{name:"Close",exact:!0}).last().click();let h=t.getByTestId("header--back");await h.waitFor({state:"visible",timeout:15e3}),await h.click();let S=t.getByTestId(O.closeMenuButton);await S.waitFor({state:"visible",timeout:15e3}),await S.click()}return await t.evaluate(async()=>await navigator.clipboard.readText())}async function Do(t){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.settingsButton).click(),await t.getByTestId(O.lockWalletButton).click()}import{styleText as Uo}from"util";import{expect as gn}from"@playwright/test";var tt=class{name="phantom";onboardingPath="/onboarding.html";async indexUrl(){return`chrome-extension://${await this.extensionId()}/popup.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/notification.html`}async extensionId(){return await U(this.name)}async promptPage(e){let a=await this.promptUrl();return await D({context:e,path:a,locator:"div[id='root']"})}};async function Et(t,e){let o=!1;for(;!e();){let n=e();if(n||o||t.isClosed())break;try{let r=t.locator("div[id='modal']").locator("div > svg").first();await r.isVisible().catch(()=>!1)&&(await r.click(),o=!0)}catch(r){if(t.isClosed())break;console.error("[autoClosePhantomNotification]: ",r)}if(n||o||t.isClosed())break;await y(300)}}async function ie({page:t,currentAccountName:e,newAccountName:a}){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.manageAccountsButton).click();let i=await t.getByTestId(Vo.accountProfileContainer).locator("div[data-testid^='manage-accounts-sortable'] div > p").all(),c=null;for(let w of i)if((await w.textContent())?.toLowerCase()===e.toLowerCase()){c=w;break}if(!c)throw new Error(`Account with name "${e}" not found`);await c.click(),await t.locator("button:has-text('Account Name')").click();let l=t.locator("input[name='name']");await l.clear(),await l.fill(a),await t.getByTestId("primary-button").click(),await t.getByTestId("header--back").click(),await t.getByTestId(O.closeMenuButton).click()}async function ce(t){await t.getByTestId(N.openMenuButton).click(),await t.getByTestId(N.settingsButton).click()}async function se({page:t,...e}){await ce(t);let a=t.locator(`button[id='${O.developerSettingsButton}']`);await a.scrollIntoViewIfNeeded(),await a.click();let o=t.getByTestId("toggleTestNetwork"),r=await o.locator("label[data-testid='toggleTestNetwork-switch'] > input[aria-label='Toggle']").isChecked().catch(()=>!1);if(!r&&e.mode==="on"&&await o.click(),r&&e.mode==="off"){await o.click(),await t.getByTestId("header--back").click(),await t.getByTestId(O.closeMenuButton).click();return}if(e.mode==="on"&&e.chain==="Solana"){let{network:s}=e;await t.locator(`button:has-text("${s}")`).click()}if(e.mode==="on"&&e.chain==="Ethereum"){let{network:s}=e;if(!await t.getByText("EVM",{exact:!0}).isVisible().catch(()=>!1))throw new Error(["EVM testnet options are not available. Please ensure Ethereum is enabled in optional chains.","To enable Ethereum, call the 'toggleOptionalChain' action before switching the network.","toggleOptionalChain({ page: page, toggleMode: 'on', supportedChains: ['Ethereum'] })","Tip: For persistence, enable Ethereum in your setup file after the onboarding step completes."].join(`
|
|
14
|
-
`));await t.locator(`button:has-text("${
|
|
15
|
-
Phantom onboarding started...`,{validateStream:!1}));let o=await k("phantom");if(a.mode==="create"){await t.locator(B.createNewWalletButton).click(),await t.getByTestId(B.createSeedPhraseWalletButton).click();let w=t.getByTestId(B.passwordInput),d=t.getByTestId(B.passwordConfirmInput),g=t.getByTestId(B.termsCheckBox),f=t.locator(B.continueButton);await w.fill(o),await d.fill(o),await g.click(),await f.click(),await f.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.getByTestId(B.recoveryPhraseSavedCheckbox).click(),await f.click(),await y(1e3),await f.click(),await t.locator(B.getStartedButton).last().click()}if(a.mode==="recovery phrase"){let p=a.secretRecoveryPhrase.split(" ");await t.locator(B.IAlreadyHaveAWalletButton).click(),await t.locator(B.importRecoveryPhraseButton).click();for(let[nt,et]of Object.entries(p))await t.getByTestId(`${B.recoveryPhraseInput}-${nt}`).fill(et);await t.locator(B.importWalletButton).click(),await t.locator("p:has-text('Finding accounts with activity')").waitFor({state:"detached",timeout:6e4});let h=t.locator(B.continueButton);await h.click();let S=t.getByTestId(B.passwordInput),A=t.getByTestId(B.passwordConfirmInput),C=t.getByTestId(B.termsCheckBox);await S.fill(o),await A.fill(o),await C.click(),await h.click(),await h.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.locator(B.getStartedButton).last().click()}if(a.mode==="private key"){await t.locator(B.IAlreadyHaveAWalletButton).click();let{privateKey:p,chain:w,accountName:d}=a;await t.locator(B.importPrivateKeyButton).click();let f=t.locator("span[id='button--listbox-input--1']"),h=await f.textContent(),S=t.locator("input[name='name']"),A=t.locator("textarea[name='privateKey']");h!==w&&(await f.click(),await t.locator("ul[id='listbox--listbox-input--1']").locator(`li[data-label='${w}']`).click()),await S.fill(d),await A.fill(p),await t.locator("button:has-text('Import')").click();let R=t.getByTestId(B.passwordInput),V=t.getByTestId(B.passwordConfirmInput),nt=t.getByTestId(B.termsCheckBox);await R.fill(o),await V.fill(o),await nt.click();let et=t.locator(B.continueButton);await et.click(),await et.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.locator(B.getStartedButton).last().click()}let n=await t.context().newPage(),r=await new tt().indexUrl();await n.goto(r);let c=await t.context().browser()?.newBrowserCDPSession(),s;await gn.poll(async()=>{if(c){let{targetInfos:m}=await c.send("Target.getTargets"),w=m.filter(d=>d.title==="Phantom Wallet").find(d=>!d.attached&&d.url===r);return s=w,!!w}},{timeout:2e4}).toBe(!0),s&&await c?.send("Target.closeTarget",{targetId:s.targetId});let l=await n.getByTestId("home-header-account-name").textContent();if(a.mode==="create"){let{accountName:m}=a;await ie({page:n,newAccountName:m,currentAccountName:"Account 1"})}if(e&&e.length>0){let m=!1;Et(n,()=>m).catch(d=>console.error({error:d}));for(let{accountName:d,chain:g,privateKey:f}of e)await re({page:n,privateKey:f,accountName:d,chain:g}),m=!0;let w=a.mode==="create"?a.accountName:l;w&&await Mt(n,w)}a.toggleNetworkMode&&await se({page:n,...a.toggleNetworkMode}),await y(3e3),console.info(Uo("greenBright","\u2728 Phantom onboarding completed successfully",{validateStream:!1}))}async function Ko(t){let e=t.getByTestId(Nt.cancelButton);await t.getByTestId("approve-transaction").waitFor({state:"attached"}),await e.click()}async function Ho({page:t,supportedChains:e,toggleMode:a="off"}){if(await ce(t),await t.locator("button[id='settings-item-active-networks']").click(),e.length===0)throw Error("Supported chains array cannot be empty for toggle mode other than 'onboard'");for(let i of e){let c=t.locator(`button[id='toggle-${i.toLowerCase()}']`),l=await c.locator(`label[data-testid='toggle-${i.toLowerCase()}-switch'] > input[aria-label='Toggle']`).isChecked().catch(()=>!1);a==="off"&&l&&await c.click(),a==="on"&&!l&&await c.click()}await t.getByTestId("header--back").click(),await t.getByTestId(O.closeMenuButton).click()}async function le(t){let e=await k("phantom"),a=t.locator("input[name='password']"),o=t.getByTestId("unlock-form-submit-button");await a.fill(e),await o.click(),await o.waitFor({state:"detached"})}var dt=class extends tt{page;constructor(e){super(),this.page=e}async onboard({...e}){await Ne({page:this.page,...e})}async unlock(){await le(this.page)}async lock(){await Do(this.page)}async renameAccount({...e}){await ie({page:this.page,...e})}async switchAccount(e){await Mt(this.page,e)}async getAccountAddress({accountName:e,chain:a}){return await Oo({page:this.page,accountName:e,chain:a})}async addAccount({...e}){await re({page:this.page,...e})}async toggleOptionalChains({toggleMode:e,supportedChains:a}){await Ho({page:this.page,supportedChains:a,toggleMode:e})}async switchNetwork({...e}){await se({page:this.page,...e})}async connectToApp(e){await Lo(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await $o(await this.promptPage(this.page.context()))}async rejectTransaction(){await Ko(await this.promptPage(this.page.context()))}};import jo from"fs";import hn from"path";import{test as yn,chromium as xn}from"@playwright/test";var Rt,jd=({slowMo:t=0,profileName:e}={})=>yn.extend({contextPath:async({browserName:a},o,n)=>{let r=await v(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new tt,i=x(r.name),c=await I(r.name),s=hn.resolve(i,e??"wallet-data");if(!jo.existsSync(s))throw new Error("\u274C Cache for Phantom wallet data not found. Create it first");jo.cpSync(s,o,{recursive:!0,force:!0}),process.env.HEADLESS&&t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!");let l=await xn.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`,`--load-extension=${c}`],slowMo:process.env.HEADLESS?0:t});await l.grantPermissions(["clipboard-read"]);let{cookies:u,origins:m}=await a.storageState();u&&await l.addCookies(u),m&&m.length>0&&await $(m,l);let p=await r.indexUrl();Rt=l.pages().find(d=>d.url().startsWith(p))||await E(l,p);for(let d of l.pages())d.url().includes("about:blank")&&await d.close();await Rt.bringToFront(),await le(Rt),await n(l),await b(l,o)},phantomPage:async({context:a},o)=>{await o(Rt)},phantom:async({context:a},o)=>{let n=new dt(Rt);await o(n)},autoCloseNotification:[async({context:a},o)=>{let n=!1,i=Et(Rt,()=>n);await o(void 0),n=!0,await i.catch(c=>{console.error(`Auto close notification error: ${c.message}`)})},{auto:!0}]});import{test as bn}from"@playwright/test";import Go from"fs";import Bn from"path";import{chromium as kn}from"@playwright/test";async function zo({workerInfo:t,profileName:e,slowMo:a}){let o=new tt,n=await v(t.workerIndex.toString()),r=x(o.name),i=Bn.resolve(r,e??"wallet-data");if(!Go.existsSync(i))throw new Error(`Cache for ${o.name} does not exist. Create it first!`);Go.cpSync(i,n,{recursive:!0,force:!0});let c=await I(o.name),s=await kn.launchPersistentContext(n,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:a}),l=await o.indexUrl(),u=await E(s,l);return{context:s,walletPage:u,contextPath:n}}var cw=({slowMo:t,profileName:e,dappUrl:a}={})=>bn.extend({workerScopeContents:[async({browser:o},n,r)=>{let{context:i,contextPath:c,walletPage:s}=await zo({workerInfo:r,profileName:e,slowMo:t});await i.grantPermissions(["clipboard-read"]);for(let u of i.pages())u.url().includes("about:blank")&&await u.close();let l=new dt(s);await l.unlock(),await n({wallet:l,walletPage:s,context:i}),await b(i,c)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],phantomPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},phantom:async({workerScopeContents:o},n)=>{let r=new dt(o.walletPage);await n(r)},autoCloseNotification:[async({workerScopeContents:o},n)=>{let r=!1,i=()=>r,c=Et(o.walletPage,i);await n(void 0),r=!0,await c.catch(s=>{console.error(`Auto close notification error: ${s.message}`)})},{auto:!0}]});var wt={networkSettings:"li-settings-network",selectNetwork:"select-network",confirmModal:"modal-confirm",confifmButton:"btn-confirm",securityAndPrivacyButton:"nav-item-security-and-privacy",lockButton:"btn-lock"},_t={portfolioButton:"nav-item-portfolio",walletSelectorButton:"icon-section-wallet-picker-arrow-right"};import ue from"zod";var qo=ue.object({walletName:ue.string().min(1,"Wallet name cannot be an empty string"),privateKey:ue.array(ue.number()).length(64)});async function me({page:t,privateKey:e,walletName:a}){let o=qo.parse({privateKey:e,walletName:a});await t.getByTestId(_t.walletSelectorButton).click(),await t.getByTestId("icon-btn-add").click(),await t.getByTestId("li-add-wallet-privateKey-add").click();let c=t.getByTestId("input-name"),s=t.getByTestId("input-private-key");await c.fill(o.walletName),await s.fill(`${o.privateKey}`),await t.getByTestId("btn-import").click(),await t.locator("span:has-text('My wallets')").waitFor({state:"attached"}),await t.getByRole("dialog").getByTestId("icon-btn-close").click()}import{expect as Pn}from"@playwright/test";var pe={approveButton:"btn-approve",rejectButton:"btn-reject"};async function Yo(t){let e=t.getByTestId(pe.approveButton);await t.getByTestId("section-network-fee").waitFor({state:"attached",timeout:3e4}).catch(async()=>{console.error("Network fee section did not appear within the timeout period, which may indicate that the transaction confirmation popup did not load correctly."),await t.getByText("Network mismatch",{exact:!0}).isVisible().catch(()=>!1)&&(await t.getByRole("button",{name:"Close",exact:!0}).click(),console.error("A 'Network mismatch' error was detected in the popup. Closing the popup and aborting the transaction confirmation process."))});let o=t.locator("div[data-id='control-label']");await o.isVisible().catch(()=>!1)&&await o.click(),await Pn(e).toBeEnabled(),await e.click()}async function de(t,e){await t.getByTestId("icon-section-wallet-picker-arrow-right").click();let o=t.getByTestId("list-item-m-title").filter({hasText:e}).locator("xpath=../..");if(!await o.isVisible().catch(()=>!1))throw new Error(`Account "${e}" not found. Make sure the account is onboarded or verify the account name.`);await o.click()}async function Qo(t,e){e&&await de(t,e),await t.getByRole("button",{name:"Connect",exact:!0}).click()}async function Xo(t){return await t.getByTestId("icon-section-wallet-picker-copy").click(),await t.evaluate(async()=>await navigator.clipboard.readText())}async function we(t){let e=t.getByRole("button",{name:"settings",exact:!0});await e.waitFor({state:"attached",timeout:3e4}),await e.click()}async function Zo(t){await we(t),await t.getByTestId(wt.securityAndPrivacyButton).click(),await t.getByTestId("li-settings-lock").getByTestId(wt.lockButton).click()}import{styleText as Jo}from"util";var it={alreadyHaveAWalletButton:"btn-already-have-wallet",recoveryPhraseInput:"input-recovery-phrase",continueButton:"btn-continue",passwordInput:"input-new-password",repeatPasswordInput:"input-repeat-password",quickSetupButton:"btn-quick-setup",IAgreeButton:"btn-explore"};async function fe({page:t,currentAccountName:e,newAccountName:a}){await t.getByTestId(_t.walletSelectorButton).click();let n=t.locator(`button[data-testid^='li-wallets']:has-text('${e}')`);if(!await n.isVisible().catch(()=>!1))throw new Error(`Account "${e}" not found. Make sure the account is available.`);await n.hover({timeout:2e4}),await n.getByTestId("icon-btn-three-dots").click({timeout:2e4});let c=t.getByTestId("li-manage-wallet-rename-wallet");await c.click();let s=t.getByTestId("input-name");await s.clear(),await s.fill(a),await t.getByTestId("btn-save").click(),await c.waitFor({state:"attached",timeout:15e3}),await t.getByTestId("icon-btn-close").click()}async function ge(t,e){await we(t);let o=t.getByTestId("li-settings-network").getByRole("combobox");await o.locator(" > p").textContent()!==e?(await o.click(),await t.getByTestId(wt.selectNetwork).getByRole("option",{name:e,exact:!0}).click(),(e==="Devnet"||e==="Testnet")&&await t.getByTestId(wt.confirmModal).getByTestId(wt.confifmButton).click()):console.info(`Network is already set to ${e}`),await t.getByTestId(_t.portfolioButton).click()}async function ta({page:t,recoveryPhrase:e,network:a,walletName:o,addWallet:n}){console.info(Jo("yellowBright",`
|
|
16
|
-
Solflare onboarding started...`,{validateStream:!1}));let r=await
|
|
1
|
+
import{expect as Oe}from"@playwright/test";function B(t){return new Promise(e=>setTimeout(e,t))}async function R(t){await t.waitForLoadState("load",{timeout:15e3}),await t.waitForLoadState("domcontentloaded",{timeout:15e3})}import $e from"fs";import pa from"path";import ke from"path";import{fileURLToPath as sa}from"url";var la=sa(import.meta.url),ua=ke.dirname(la),ma=ke.resolve(ua,"..","../.wallet-cache");function k(t){return ke.resolve(`${ma}/${t}`)}async function P(t){let e=k(t),a=pa.resolve(e,"password.txt");try{if(!$e.existsSync(a))throw new Error("\u274C password.txt not found. Run setup script first.");return $e.readFileSync(a,"utf-8")}catch(o){throw new Error(`\u274C Failed to get ${t} password from cache: ${o.message}`)}}import{expect as da}from"@playwright/test";async function K({context:t,path:e,locator:a}){let o;try{await da.poll(async()=>(o=t.pages().filter(n=>n.url().startsWith("chrome-extension://")).find(n=>n.url().match(e)),!!o),{timeout:3e4}).toBe(!0)}catch{let n=t.pages().filter(r=>r.url().startsWith("chrome-extension://")).map(r=>r.url());throw new Error(`Popup page with path "${e}" not found in context after 30s. Pages in context: ${JSON.stringify(n)}`)}if(!o)throw new Error(`Popup page with path ${e} not found in context.`);return await wa(o,a),await o.setViewportSize({width:360,height:592}),o}async function wa(t,e){await t.waitForLoadState("load",{timeout:4e4}),await t.waitForLoadState("domcontentloaded",{timeout:4e4}),await t.locator(e).first().waitFor({state:"attached",timeout:4e4})}import Le from"fs";import fa from"path";async function H(t){let e=k(t),a=fa.resolve(e,"extension-id.txt");try{if(!Le.existsSync(a))throw new Error("\u274C extension-id.txt not found. Run setup script first.");return Le.readFileSync(a,"utf-8")}catch(o){throw new Error(`\u274C Failed to get ${t} extension ID from cache: ${o.message}`)}}var G=class{name="keplr";onboardingPath="register.html";async indexUrl(){return`chrome-extension://${await this.extensionId()}/sidePanel.html`}async onboardingUrl(){return`chrome-extension://${await this.extensionId()}/${this.onboardingPath}`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/popup.html`}async extensionId(){return await H(this.name)}async promptPage(e){let a=await this.promptUrl();return await K({context:e,path:a,locator:"div[data-simplebar='init']"})}};var z={importExistingWalletButton:"button:has-text('Import an existing wallet')",usePrivateKeyButton:"button:has-text('Use recovery phrase or private key')",privateKeyTabButton:"button:has-text('Private key')",privateKeyInput:"input[type='password']",importButton:"button:has-text('Import')",walletNameInput:"input[name='name']",walletPasswordInput:"input[name='password']",confirmWalletPasswordInput:"input[name='confirmPassword']",nextButton:"button:has-text('Next')",searchNetworkInput:"input[placeholder='Search networks']",saveButton:"button:has-text('Save')",finishButton:"button:has-text('Finish')"};function ga(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function xt({page:t,privateKey:e,walletName:a,chains:o,mode:n="onboard"}){let r=await P("keplr"),i=new G;if(await t.locator(z.importExistingWalletButton).click(),await t.locator(z.usePrivateKeyButton).click(),await t.getByRole("button",{name:"Private key",exact:!0}).click(),await t.locator(z.privateKeyInput).fill(e),await t.getByRole("button",{name:"Import",exact:!0}).click(),await t.locator(z.walletNameInput).fill(a),n==="onboard"){let v=t.locator(z.walletPasswordInput),V=t.locator(z.confirmWalletPasswordInput);await v.fill(r),await V.fill(r)}await t.locator(z.nextButton).click();let f=t.locator("div:has-text('All Native Chains')").nth(-4),y=t.locator("div[cursor='pointer']:has-text('Cosmos Hub')"),h=await f.locator("input[type='checkbox']").getAttribute("checked"),x=await y.locator("input[type='checkbox']").getAttribute("checked");h!==null&&await f.click(),x!==null&&await y.click();let I=t.locator(z.searchNetworkInput);for(let v of o){await I.fill(v);let L=t.locator("div[class='simplebar-content']").locator("div[cursor] > div").first().locator("div").filter({hasText:new RegExp(`^${ga(v)}$`,"i")}).nth(2).locator("../../../../..");await L.waitFor({state:"visible",timeout:2e4}),await L.locator("input[type='checkbox']").getAttribute("checked")===null&&await L.click()}let S=t.locator(z.saveButton);if(await S.scrollIntoViewIfNeeded(),await S.click(),await B(2e3),n==="onboard"){await t.goto(await i.indexUrl());return}if(n==="add-account-single"){let v=t.locator(z.finishButton);await v.waitFor({state:"visible",timeout:2e4}),await Oe(v).toBeEnabled({timeout:2e4}),await v.click()}}async function Qt(t){let a=await new G().onboardingUrl();await t.getByRole("link",{name:"Settings",exact:!0}).click(),await t.locator("div[cursor='pointer']").first().click(),await t.getByRole("button",{name:"Add Wallet",exact:!0}).click();let i;if(await Oe.poll(async()=>(i=t.context().pages().find(c=>c.url().match(a)),!!i),{timeout:3e4}).toBe(!0).catch(c=>{console.error(`Failed to find onboarding page with URL matching ${a}. Original error: ${c}`)}),!i)throw new Error(`Onboarding page not found. Expected URL: ${a}`);return await R(i),await i.bringToFront(),i}async function De({page:t,privateKey:e,chains:a,walletName:o,mode:n}){let r=await Qt(t);await xt({page:r,privateKey:e,walletName:o,chains:a,mode:n}),await t.locator("div:has(div:has-text('Select Wallet'))").nth(-4).locator("div:has(> div > svg)").first().click(),await t.getByRole("link",{name:"Home",exact:!0}).click()}import{expect as ha}from"@playwright/test";var Xt={approveButton:"button:has-text('Approve')",rejectButton:"button[color='secondary']"};async function Ue(t){let e=t.locator(Xt.approveButton);await ha(e).toBeEnabled({timeout:2e4}),await e.click()}async function Ke(t){t.getByRole("button",{name:"Approve",exact:!0}).click(),await B(1e3)}import{expect as ya}from"@playwright/test";import q from"zod";var He=q.discriminatedUnion("chain",[q.object({chain:q.literal(["Injective","Injective (Testnet)","Polygon"]),walletName:q.string().min(1,"Wallet name cannot be an empty string")}),q.object({chain:q.literal(["Bitcoin","Bitcoin Signet","Bitcoin Testnet"]),chainTag:q.literal(["Taproot","Native Segwit"]),walletName:q.string().min(1,"Wallet name cannot be an empty string")})]),je=q.object({currentAccountName:q.string().min(1,"Current account name cannot be an empty string"),newAccountName:q.string().min(1,"New account name cannot be an empty string")});async function Ge({page:t,...e}){let a=He.parse({...e});await t.getByRole("textbox",{name:"Search for asset or chain (i.e. ATOM, Cosmos)",exact:!0}).fill(a.chain);let n=t.locator(`div:has-text("${a.chain}")`).nth(-2).filter({hasNot:t.locator("span")});if(await n.waitFor({state:"attached",timeout:2e4}),!await n.isVisible().catch(()=>!1))throw Error(`Make sure "${a.chain}" is activated.`);let i=await n.locator("div").all();ya(i.length).toBeGreaterThan(0),await t.locator(`div:has(div:has-text('${a.walletName}'))`).nth(-3).locator("div:has(> div > svg)").click();let m=t.locator("div:has(> div[data-simplebar='init'])").last(),d=m.locator("div:has(> div > input)").locator("input");await d.fill(a.chain);let g=await m.locator("div[cursor='pointer']",{hasText:a.chain}).all(),f;for(let h of g){let x;"chainTag"in e&&(x=e.chainTag);let I=h.locator("div",{hasText:a.chain}).last(),S=x?h.locator("div",{hasText:x}).last():null,V=(S?await S?.isVisible().catch(()=>!1):!1)?await S?.textContent():null,L=await I.textContent(),it=V?`${L} ${V}`:L,at=x?`${a.chain} ${x}`:a.chain;if(it===at){f=I.locator("xpath=../../../.."),await d.clear();break}}if(!f)throw Error(`Address for ${a.walletName} account on "${a.chain}" chain not found.`);return await f.hover(),await f.scrollIntoViewIfNeeded(),await f.click(),await t.evaluate(async()=>await navigator.clipboard.readText())}var Lt={openSidebarMenuButton:"div[cursor='pointer']:has(> div[cursor='pointer'])",menuPopupContent:"div[id='modal-root-3']",lockWalletButton:"div:has(> div:has-text('Lock Wallet'))",settingsButton:"div:has(a[href='#/settings'])"},be={unlockButton:"button[type='submit']:has-text('Unlock')",passwordInput:"input[placeholder='Type Your Password']"};async function ze(t){await t.locator(Lt.openSidebarMenuButton).click(),await t.locator(Lt.lockWalletButton).nth(-1).click(),await t.getByText("Welcome Back").waitFor({state:"visible",timeout:3e4})}import{styleText as qe}from"util";import{expect as xa}from"@playwright/test";async function Zt(t,e){let a=t.locator("div[color]").nth(1);if(await a.textContent()===e){console.info(`
|
|
2
|
+
Already on ${e} account. No need to switch.`);return}await a.click();let n=t.locator("div[class='simplebar-content'] > div").locator("> div",{hasText:e});if(!await n.isVisible().catch(()=>!1))throw new Error(`Account "${e}" not found. Make sure the account is onboarded or verify the account name.`);let i=t.locator("div:has-text('Select Wallet')").last();await n.click(),await i.waitFor({state:"detached",timeout:3e4})}async function Pe({page:t,onboard:e}){if(console.info(qe("yellowBright",`
|
|
3
|
+
Keplr onboarding started...`,{validateStream:!1})),e.length===1)for(let{privateKey:a,walletName:o,chains:n}of e)await xt({page:t,privateKey:a,walletName:o,chains:n,mode:"onboard"});if(e.length>1){let a=e[0];if(a){let{privateKey:p,walletName:d,chains:w}=a;await xt({page:t,privateKey:p,walletName:d,chains:w,mode:"onboard"})}let o=e.slice(1);for(let{privateKey:p,walletName:d,chains:w}of o){let g=await Qt(t);await xt({page:g,privateKey:p,walletName:d,chains:w,mode:"add-account-single"})}await t.locator("div",{hasText:"Select Wallet"}).last().locator("../../..").locator("div > svg").click(),await t.getByRole("link",{name:"Home",exact:!0}).click();let c=t.locator(Lt.openSidebarMenuButton);await xa(c).toBeVisible({timeout:3e4});let u=e.at(-1)?.walletName,m=e[0]?.walletName;u&&m&&await Zt(t,m)}await B(3e3),console.info(qe("greenBright","\u2728 Keplr onboarding completed successfully",{validateStream:!1}))}async function Ye(t){let e=t.locator(Xt.rejectButton);await e.waitFor({state:"visible",timeout:2e4}),await e.click()}async function Qe({page:t,currentAccountName:e,newAccountName:a}){let o=je.parse({currentAccountName:e,newAccountName:a});await t.getByRole("link",{name:"Settings",exact:!0}).click(),await t.locator("div[cursor='pointer']").first().click();let i=t.locator("div",{hasText:o.currentAccountName}).nth(-4);if(!await i.isVisible().catch(()=>!1))throw Error(`Account with name "${o.currentAccountName}" not found`);await i.locator("div[cursor='pointer'] svg").click(),await t.locator("div > div[cursor='pointer'] > div:has-text('Change Wallet Name')").last().click(),await t.locator("input[name='name']").fill(o.newAccountName),await t.locator("button:has-text('Save')").click()}async function Jt(t){let e=await P("keplr");await t.locator(be.passwordInput).fill(e),await t.locator(be.unlockButton).click(),await t.locator("div:has-text('Deposit')").last().waitFor({state:"visible",timeout:3e4})}var ut=class extends G{page;constructor(e){super(),this.page=e}async onboard(e){await Pe({page:this.page,onboard:e})}async unlock(){await Jt(this.page)}async lock(){await ze(this.page)}async renameAccount({currentAccountName:e,newAccountName:a}){await Qe({page:this.page,currentAccountName:e,newAccountName:a})}async switchAccount(e){await Zt(this.page,e)}async getAccountAddress({...e}){return await Ge({page:this.page,...e})}async addAccount({chains:e,privateKey:a,walletName:o,mode:n="add-account-multiple"}){await De({page:this.page,privateKey:a,walletName:o,chains:e,mode:n})}async connectToApp(){await Ke(await this.promptPage(this.page.context()))}async confirmTransaction(){await Ue(await this.promptPage(this.page.context()))}async rejectTransaction(){await Ye(await this.promptPage(this.page.context()))}};import Je from"fs";import Ia from"path";import{test as Ta,chromium as Wa}from"@playwright/test";import Ae from"path";import{fileURLToPath as Ba}from"url";var ka=Ba(import.meta.url),ba=Ae.dirname(ka),Pa=Ae.resolve(ba,"..","../.wallet-context");async function T(t){return Ae.resolve(Pa,`${t}`)}import{expect as Aa}from"@playwright/test";async function _(t,e){let a=await t.newPage();return await Aa(async()=>{await a.goto(e),await R(a)}).toPass(),a}async function O(t,e){let a=await e.newPage();for(let{origin:o,localStorage:n}of t){let r=a.mainFrame();await r.goto(o),await r.evaluate(i=>{i.forEach(({name:c,value:u})=>{window.localStorage.setItem(c,u)})},n)}await a.close()}import Ca from"fs/promises";async function Xe(t){await Ca.rm(t,{maxRetries:50,retryDelay:500,recursive:!0,force:!0})}var Sa=35e3;async function A(t,e){try{await Promise.race([t.close(),new Promise((a,o)=>setTimeout(()=>o(new Error("Context close timed out")),Sa))])}catch(a){console.warn(`Browser context close did not complete cleanly: ${a.message}`)}try{await Xe(e)}catch(a){console.error(`Failed to remove temporary context directory at ${e}. Error:`,a)}}import Ze from"fs";import va from"path";async function W(t){try{let e=k(t),a=va.resolve(e,"extension-path.txt");if(!Ze.existsSync(a))throw new Error("\u274C extension-path.txt not found. Run setup script first.");let o=Ze.readFileSync(a,"utf-8").trim();if(!o)throw new Error("\u274C extension-path.txt is empty. Run setup script first.");return o}catch(e){throw new Error(`\u274C Failed to get ${t} extension path: ${e.message}`)}}var Bt,Qi=({slowMo:t=0,profileName:e}={})=>Ta.extend({contextPath:async({browserName:a},o,n)=>{let r=await T(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new G,i=k(r.name),c=await W(r.name),u=Ia.resolve(i,e??"wallet-data");if(!Je.existsSync(u))throw new Error("\u274C Cache for Keplr wallet data not found. Create it first");Je.cpSync(u,o,{recursive:!0,force:!0});let m=[`--disable-extensions-except=${c}`,`--load-extension=${c}`];process.env.HEADLESS&&(m.push("--headless=new"),t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!"));let p=await Wa.launchPersistentContext(o,{headless:!1,args:m,slowMo:process.env.HEADLESS?0:t});await p.grantPermissions(["clipboard-read"]);let{cookies:d,origins:w}=await a.storageState();d&&await p.addCookies(d),w&&w.length>0&&O(w,p);let g=await r.indexUrl();Bt=p.pages().find(y=>y.url().startsWith(g))||await _(p,g),await R(Bt);for(let y of p.pages()){let h=y.url();(h.includes("about:blank")||h.includes(r.onboardingPath))&&await y.close()}await Bt.bringToFront(),await Jt(Bt),await n(p),await A(p,o)},keplrPage:async({context:a},o)=>{await o(Bt)},keplr:async({context:a},o)=>{let n=new ut(Bt);await o(n)}});import{test as Ma}from"@playwright/test";import to from"fs";import Fa from"path";import{chromium as Na}from"@playwright/test";async function kt({wallet:t,workerInfo:e,profileName:a,slowMo:o}){let n=await T(e.workerIndex.toString()),r=k(t.name),i=Fa.resolve(r,a??"wallet-data");if(!to.existsSync(i))throw new Error(`Cache for ${t.name} does not exist. Create it first!`);to.cpSync(i,n,{recursive:!0,force:!0});let c=await W(t.name),u=await Na.launchPersistentContext(n,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:o}),m=await t.indexUrl(),p=u.pages()[0];return p||(p=await u.newPage()),await p.goto(m),{context:u,walletPage:p,contextPath:n}}var pc=({slowMo:t,profileName:e,dappUrl:a}={})=>Ma.extend({workerScopeContents:[async({browser:o},n,r)=>{let i=new G,{context:c,contextPath:u,walletPage:m}=await kt({wallet:i,workerInfo:r,profileName:e,slowMo:t});await c.grantPermissions(["clipboard-read"]);for(let d of c.pages())d.url().includes("about:blank")&&await d.close();let p=new ut(m);await p.unlock(),await n({wallet:p,walletPage:m,context:c}),await A(c,u)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],keplrPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},keplr:async({workerScopeContents:o},n)=>{let r=new ut(o.walletPage);await n(r)}});import{expect as D}from"@playwright/test";import oo from"zod";import{test as Ea}from"@playwright/test";function eo(t,e){t&&(console.warn(`
|
|
4
|
+
\u26A0\uFE0F Skipping test: ${e}`),Ea.skip())}var C={buyButton:"eth-overview-buy",swapButton:"eth-overview-swap",sendButton:"eth-overview-send",receiveButton:"eth-overview-receive",openSettingsButton:"account-options-menu-button",accountMenuButton:"account-menu-icon",accountCell:"multichain-account-cell-entropy",openNetworkSelectorButton:"sort-by-networks",accountAddressesButton:"networks-subtitle-test-id",accountAddressesElements:"multichain-address-row",accountAddressQRCode:"multichain-address-row-qr-button"},bt={lockButton:"global-menu-lock",networksButton:"global-menu-networks"},Ot={passwordInput:"unlock-password",unlockButton:"unlock-submit"},nt={accountOptionsMenuButton:"multichain-account-cell-end-accessory",accountDetailsLabel:"Account details",renameAccountLabel:"Rename",addressesLabel:"Addresses",pinToTopLabel:"Pin to top",hideAccountLabel:"Hide account",backButton:"back",addMultichainAccountButton:"add-multichain-account-button",addWalletButton:"account-list-add-wallet-button",importWalletButton:"add-wallet-modal-import-wallet",importAccountButton:"add-wallet-modal-import-account"};var M={createWalletButton:"onboarding-create-wallet",importWalletButton:"onboarding-import-wallet",useSecretRecoveryPhraseButton:"onboarding-create-with-srp-button",createNewPasswordInput:"create-password-new-input",confirmNewPasswordInput:"create-password-confirm-input",confirmPasswordCheckbox:"create-password-terms",createPasswordButton:"create-password-submit",revealSecretRecoveryPhraseButton:"recovery-phrase-reveal",recoveryPhraseRemindMeLaterButton:"recovery-phrase-remind-later",metamaskMetricsIAgreeButton:"metametrics-i-agree",onboardingDoneButton:"onboarding-complete-done",importUsingSecretRecoveryPhraseButton:"onboarding-import-with-srp-button",secretRecoveryPhraseTextAreaInput:"srp-input-import__srp-note",importWalletConfirmButton:"import-srp-confirm",importAccountConfirmButton:"import-account-confirm-button",importSRPError:"bannerAlert"};async function ao({page:t,privateKey:e,accountName:a}){let o=oo.string().min(1,"Account name cannot be an empty string").trim().parse(a),n=oo.string().min(1,"Private key cannot be an empty string").trim().parse(e),r=t.getByTestId(C.accountMenuButton);await D(r).toBeVisible({timeout:3e4}),await r.click(),await D(t.getByRole("heading",{name:/accounts/i})).toBeVisible();let i=t.getByTestId(nt.addWalletButton),c=await i.textContent();c?.includes("Syncing")&&await D.poll(async()=>(await i.textContent())?.trim()??"",{timeout:12e4}).not.toBe(c),await D(i).toBeEnabled({timeout:6e4}),await i.click();let u=t.getByRole("dialog");await D(u).toContainText(/add wallet/i),await t.getByTestId(nt.importAccountButton).click(),await t.locator("input[id='private-key-box']").fill(n);let d=t.getByTestId(M.importAccountConfirmButton);await D(d).toBeEnabled(),await d.click();let w=t.getByTestId(M.importSRPError),g=await w.isVisible().catch(()=>!1);g&&eo(g,`${(await w.textContent())?.split(".")[0]}`);let f=t.locator("div:has(> div[data-testid^='multichain-account-cell-keyring'][class*='mm-box--background-color-background-muted'])"),y=(await f.textContent())?.split("$")[0];y&&await Ra({page:t,accountName:o,activeAccountLocator:f,activeAccountName:y}),await t.locator("button[aria-label='Back']").first().click()}async function Ra({page:t,accountName:e,activeAccountLocator:a,activeAccountName:o}){let n=a.locator(`div[aria-label='${o} options']`);await D(n).toBeVisible(),await n.click(),await D(t.getByRole("tooltip")).toBeVisible();let r=t.locator(`div[aria-label='${nt.renameAccountLabel}']`);await D(r).toBeVisible(),await r.click();let i=t.getByRole("dialog"),c=i.getByRole("heading",{name:/rename/i});await D(c).toBeVisible();let u=i.getByRole("textbox");await D(u).toBeVisible(),await u.fill(e);let m=i.getByRole("button",{name:/confirm/i});await D(m).toBeEnabled(),await m.click(),await i.waitFor({state:"detached",timeout:2e4});let p=t.locator("div:has(> div[data-testid^='multichain-account-cell-keyring'][class*='mm-box--background-color-background-muted'])");await D(p).toContainText(e)}import{expect as Dt}from"@playwright/test";import Pt from"zod";var no=Pt.object({networkName:Pt.string().min(1,"Network name cannot be an empty string"),rpcUrl:Pt.url(),chainId:Pt.number().or(Pt.string().includes("0x")),currencySymbol:Pt.string().toUpperCase().min(1,"Currency symbol cannot be an empty string")});import{expect as _a}from"@playwright/test";async function te(t){let e=t.locator("div:has(> p[data-testid='notifications-tag-counter__unread-dot'])"),a=t.getByTestId(C.openSettingsButton);await e.isVisible().catch(()=>!1)?await e.click():(await _a(a).toBeVisible(),await a.click())}async function ro({page:t,...e}){let{chainId:a,currencySymbol:o,networkName:n,rpcUrl:r}=no.parse({...e},{reportInput:!0});await te(t),await t.getByTestId(bt.networksButton).click();let c=t.locator("section[role='dialog']");await Dt(c).toContainText(/manage networks/i),await t.getByRole("button",{name:/add a custom network/i}).click(),await Dt(c).toContainText(/Add a custom network/i);let m=t.getByTestId("network-form-network-name"),p=t.getByTestId("test-add-rpc-drop-down"),d=t.getByTestId("network-form-chain-id"),w=t.getByTestId("network-form-ticker-input");await m.fill(n),await p.click(),await t.getByRole("tooltip").locator("div:has(> button:has-text('Add RPC URL'))").click(),await Dt(c).toContainText(/Add RPC URL/i);let y=t.getByTestId("rpc-url-input-test"),h=t.getByRole("button",{name:/Add URL/i});await y.fill(r),await h.click(),await Dt(c).toContainText(/Add a custom network/i);let x=t.getByTestId("network-form-chain-id-error");if(await x.isVisible().catch(()=>!1)){let v=await x.textContent();throw Error(`RPC error: ${v}`)}await d.fill(`${a}`),await w.fill(o);let S=t.getByRole("button",{name:/save/i});await Dt(S).toBeEnabled(),await S.click()}import{expect as io}from"@playwright/test";var ee={confirmButton:"confirm-footer-button",cancelButton:"confirm-footer-cancel-button"};async function co(t,e){let a=t.getByTestId(ee.confirmButton);await B(2e3);let n=(await a.textContent())?.includes("Review alert"),r=await a.isDisabled().catch(()=>!1);if(n&&r){await t.getByTestId("edit-gas-fees-row").locator("> div").first().click();let p=t.getByRole("dialog");await io(p).toBeVisible();let d=p.locator("h4",{hasText:"Insufficient funds"}),w=await p.getByTestId("alert-modal__selected-alert").textContent();if(await d.isVisible().catch(()=>!1))throw Error(`${w}`)}if(e){let u=t.getByTestId("edit-gas-fee-icon");if(await u.scrollIntoViewIfNeeded(),await u.click(),e.feeType!=="advanced"&&await t.getByTestId(`gas-option-${e.feeType}`).click(),e.feeType==="advanced"){await t.getByTestId("gas-option-advanced").click();let p=t.getByRole("textbox",{name:"Max base fee"}),d=t.getByRole("textbox",{name:"Priority fee"}),w=t.getByRole("button",{name:"Save",exact:!0});await p.fill(e.maxBaseFee),await d.fill(e.priorityFee),await w.click()}}await io(a).toBeEnabled(),await a.click();let i=t.getByRole("dialog");await i.isVisible().catch(()=>!1)&&await i.locator("h4",{hasText:"Your assets may be at risk"}).isVisible().catch(()=>!1)&&(await i.getByTestId("alert-modal-acknowledge-checkbox").click(),await i.getByTestId("confirm-alert-modal-submit-button").click()),await t.waitForEvent("close",{timeout:15e3})}import{expect as Va}from"@playwright/test";import{expect as Ce}from"@playwright/test";async function At({page:t,accountName:e}){let a=t.getByTestId(C.accountMenuButton);if(await a.textContent()===e){console.info(`Can't switch account to "${e}", it is already selected.`);return}await Ce(a).toBeVisible({timeout:15e3}),await a.click(),await Ce(t.getByRole("heading",{name:/accounts/i})).toBeVisible();let n=t.getByTestId(nt.addMultichainAccountButton),r=await n.textContent();r?.includes("Syncing")&&await Ce.poll(async()=>(await n.textContent())?.trim()??"",{timeout:6e4}).not.toBe(r);let i=await t.getByTestId(/^multichain-account-cell-(?:entropy|keyring):/).all(),c=null;for(let u of i)if(await u.scrollIntoViewIfNeeded(),(await u.textContent())?.includes(e)){c=u;break}if(!c)throw Error(`Account with name "${e}" not found.`);await c?.click()}async function so(t,e){e&&await At({page:t,accountName:e});let a=t.getByRole("button",{name:"Connect",exact:!0});await a.waitFor({state:"visible",timeout:25e3}),await a.click(),await t.getByRole("heading",{name:"Connecting",exact:!0}).waitFor({state:"detached",timeout:3e4});let n;await Va.poll(async()=>(n=await t.locator("div[class='permissions-connect']").isVisible().catch(()=>!1),n),{timeout:25e3}).toBe(!0).catch(()=>console.error("Notice dialog did not appear within the timeout period."));let r=t.getByTestId("page-container-footer-next");await r.waitFor({state:"visible",timeout:25e3}),await r.click(),await t.waitForEvent("close",{predicate:()=>!0,timeout:25e3}).catch(()=>console.error("Extension popup did not close within the timeout period when connecting to the DApp."))}async function lo(t,e){return await t.getByTestId(C.accountAddressesButton).hover(),await t.getByTestId("multichain-address-rows-list").getByRole("button",{name:/view all/i}).click(),await t.getByRole("searchbox",{name:/search networks/i}).fill(e),await t.locator(`div[data-testid='${C.accountAddressesElements}']:has-text('${e}')`).getByTestId(C.accountAddressQRCode).click(),await t.getByRole("dialog").locator("div > p[data-testid='account-address']").textContent()}import{expect as Da}from"@playwright/test";import{errors as $a}from"@playwright/test";var uo={loadingOverlay:"loading-overlay",loadingSpinner:"spinner loading-overlay__spinner"};var La=6e4,Oa=async(t,e,a)=>{await R(e);try{await e.locator(`div[class="${t}"]`).waitFor({state:"detached",timeout:a})}catch(o){if(o instanceof $a.TimeoutError)console.info(`Loading indicator '${t}' not found - continuing.`);else throw console.error(`Error while waiting for loading indicator '${t}' to disappear`),o}},oe=async t=>{try{await Oa(uo.loadingSpinner,t,La)}catch(e){console.warn("Warning during MetaMask load:",e)}return await B(300),t};async function mo(t){if(await t.getByTestId(Ot.unlockButton).isVisible().catch(()=>!1)){console.info("\u{1F4A1} Wallet is already locked");return}await te(t);let o=t.getByTestId(bt.lockButton);await Da(o).toBeVisible(),await o.click(),await oe(t)}import{styleText as po}from"util";import{expect as St}from"@playwright/test";var Z=class{name="metamask";onboardingPath="/home.html#onboarding";async indexUrl(){return`chrome-extension://${await this.extensionId()}/home.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/notification.html`}async extensionId(){return await H(this.name)}async promptPage(e){let a=await this.promptUrl();return await K({context:e,path:a,locator:"div[data-testid='multichain-page']"})}};import{expect as Se}from"@playwright/test";async function Ct({page:t}){await t.locator(`div:has(> button[data-testid='${C.openSettingsButton}'])`).click(),await t.getByTestId(bt.networksButton).click();let o=t.locator("section[role='dialog']");await Se(o).toBeVisible(),await Se(o).toContainText(/manage networks/i);let n="div:has(> p:has-text('Show test networks'))";await o.locator(n).scrollIntoViewIfNeeded();let r=o.locator(n);if(!await r.locator("label[class='toggle-button toggle-button--off']").isVisible().catch(()=>!1)){await o.getByRole("button",{name:/close/i}).click(),console.info("Testnet networks are already visible.");return}await r.locator("label[class='toggle-button toggle-button--off']").click(),await t.getByTestId("Sepolia").scrollIntoViewIfNeeded(),await Se(t.getByTestId("Sepolia")).toBeVisible(),await o.getByRole("button",{name:/close/i}).click()}async function ve({page:t,mainAccountName:e,...a}){console.info(po("yellowBright",`
|
|
5
|
+
\u{1F98A} MetaMask onboarding started...`,{validateStream:!1}));let o=await P("metamask"),n=new Z,r=t.locator("img[class='loading-spinner']"),i=t.getByTestId(M.createWalletButton),c=t.getByTestId(M.importWalletButton),u=t.getByTestId(M.createNewPasswordInput),m=t.getByTestId(M.confirmNewPasswordInput),p=t.getByTestId(M.confirmPasswordCheckbox),d=t.getByTestId(M.createPasswordButton),w=t.getByTestId(M.metamaskMetricsIAgreeButton),g=t.getByTestId(M.onboardingDoneButton);if(await r.waitFor({state:"detached",timeout:3e4}),a.mode==="create"){let S=t.getByTestId(M.useSecretRecoveryPhraseButton);await i.click(),await S.click(),await u.fill(o),await m.fill(o),await p.click(),await d.click(),await t.getByTestId(M.revealSecretRecoveryPhraseButton).click(),await t.getByTestId(M.recoveryPhraseRemindMeLaterButton).click(),await w.click()}if(a.mode==="import"){let{secretRecoveryPhrase:S}=a,v=S.split(" "),V=t.getByTestId(M.importUsingSecretRecoveryPhraseButton);await c.click(),await V.click();let L=t.getByTestId(M.secretRecoveryPhraseTextAreaInput);await L.fill(v[0]),await L.press("Space");for(let X=1;X<v.length;X++){let Yt=t.getByTestId(`import-srp__srp-word-${X}`);await Yt.fill(v[X]),await Yt.press("Space")}await t.getByTestId(M.importWalletConfirmButton).click(),await u.fill(o),await m.fill(o),await p.click(),await d.click(),await w.click();let at=t.getByTestId("wallet-ready");await St(at).toContainText(/your wallet is ready/i)}await g.click();let y=`chrome-extension://${await n.extensionId()}/sidepanel.html`,x=await t.context().browser()?.newBrowserCDPSession(),I;await St.poll(async()=>{if(x){let{targetInfos:S}=await x.send("Target.getTargets"),v=S.find(V=>V.url===y);return I=v,!!v}},{timeout:15e3}).toBe(!0),I&&await x?.send("Target.closeTarget",{targetId:I.targetId}),await t.goto(await n.indexUrl()),await r.waitFor({state:"detached",timeout:3e4}),await St(t.getByTestId(C.buyButton)).toBeVisible(),await St(t.getByTestId(C.swapButton)).toBeVisible(),await St(t.getByTestId(C.sendButton)).toBeVisible(),await St(t.getByTestId(C.receiveButton)).toBeVisible(),await Ct({page:t}),e&&await At({page:t,accountName:e}),await B(5e3),console.info(po("greenBright","\u2728 MetaMask onboarding completed successfully",{validateStream:!1}))}import{expect as Ua}from"@playwright/test";async function wo(t){let e=t.getByTestId(ee.cancelButton);await B(1e3),await Ua(e).toBeEnabled(),await e.click()}import{expect as Y}from"@playwright/test";async function fo({page:t,currentAccountName:e,newAccountName:a}){let o=t.getByTestId(C.accountMenuButton);if(await o.textContent()===a)throw Error(`The account to be renamed "${a}" already exists.`);await Y(o).toBeVisible({timeout:15e3}),await o.click(),await Y(t.getByRole("heading",{name:/accounts/i})).toBeVisible();let r=t.getByTestId(nt.addMultichainAccountButton),i=await r.textContent();i?.includes("Syncing")&&await Y.poll(async()=>(await r.textContent())?.trim()??"",{timeout:6e4}).not.toBe(i);let c=await t.getByTestId(/^multichain-account-cell/).all(),u=null;for(let x of c)if((await x.textContent())?.includes(e)){u=x;break}if(!u)throw Error(`Account with name "${e}" not found.`);if((await u.textContent())?.split("$")[0]===a)throw Error(`The new account name "${a}" is the same as the old account name "${e}".`);let p=t.locator(`div[aria-label='${e} options']`);await Y(p).toBeVisible(),await p.click(),await Y(t.getByRole("tooltip")).toBeVisible();let d=t.locator(`div[aria-label='${nt.renameAccountLabel}']`);await Y(d).toBeVisible(),await d.click();let w=t.getByRole("dialog"),g=w.getByRole("heading",{name:/rename/i});await Y(g).toBeVisible();let f=w.getByRole("textbox");await Y(f).toBeVisible(),await f.fill(a);let y=w.getByRole("button",{name:/confirm/i});await Y(y).toBeEnabled(),await y.click();for(let x of c)if((await x.textContent())?.includes(a)){await Y(x).toBeVisible(),await Y(x).toContainText(a);break}await t.locator("button[aria-label='Back']").first().click()}import{expect as Ie}from"@playwright/test";async function go({page:t,networkType:e,chainName:a}){let o=t.getByTestId(C.openNetworkSelectorButton);await o.click();let n=t.getByTestId("modal-header-close-button");if(e==="testnet"||e==="custom"){let u=t.getByRole("tab",{name:"Custom"});await u.click(),await t.locator("p:has-text('Testnets')").isVisible().catch(()=>!1)||(await n.click(),await Ct({page:t}),await o.click(),await u.click());let d=t.locator(`div div[data-testid='${a}']`),w=await d.textContent();Ie(w).toBe(a),await d.click();return}await t.getByRole("tab",{name:"Popular"}).click();let i=t.locator(`div div[data-testid='${a}']`),c=await i.textContent();Ie(c).toBe(a),await i.click(),await Ie(o).toContainText(a,{timeout:3e4})}import{expect as ho}from"@playwright/test";async function Ut(t){let e=await P("metamask"),a=t.getByTestId(Ot.passwordInput);if(await t.getByTestId(C.openNetworkSelectorButton).isVisible().catch(()=>!1)){console.info("\u{1F4A1} Wallet is already unlocked");return}await a.fill(e);let r=t.getByTestId(Ot.unlockButton);await ho(r).toBeVisible(),await r.click(),await oe(t),await ho(t.getByTestId(C.buyButton)).toBeVisible({timeout:3e4})}var mt=class extends Z{page;constructor(e){super(),this.page=e}async onboard(e){await ve({page:this.page,...e})}async unlock(){await Ut(this.page)}async lock(){await mo(this.page)}async renameAccount({newAccountName:e,currentAccountName:a}){await fo({page:this.page,newAccountName:e,currentAccountName:a})}async addAccount({privateKey:e,accountName:a}){await ao({page:this.page,privateKey:e,accountName:a})}async switchAccount({accountName:e}){await At({page:this.page,accountName:e})}async switchNetwork({...e}){await go({page:this.page,...e})}async getAccountAddress(e){return await lo(this.page,e)}async toggleShowTestnetNetwork(){await Ct({page:this.page})}async addCustomNetwork({chainId:e,currencySymbol:a,networkName:o,rpcUrl:n}){await ro({page:this.page,chainId:e,currencySymbol:a,networkName:o,rpcUrl:n})}async connectToApp(e){await so(await this.promptPage(this.page.context()),e)}async confirmTransaction(e){await co(await this.promptPage(this.page.context()),e)}async rejectTransaction(){await wo(await this.promptPage(this.page.context()))}};import yo from"fs";import Ka from"path";import{test as Ha,chromium as ja}from"@playwright/test";import{Instance as Ga,Pool as za}from"prool";var Kt,Ll=({slowMo:t=0,profileName:e}={})=>Ha.extend({contextPath:async({browserName:a},o,n)=>{let r=await T(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new Z,i=k(r.name),c=await W(r.name),u=Ka.resolve(i,e??"wallet-data");if(!yo.existsSync(u))throw new Error("\u274C Cache for MetaMask wallet data not found. Create it first");yo.cpSync(u,o,{recursive:!0,force:!0});let m=[`--disable-extensions-except=${c}`,`--load-extension=${c}`];process.env.HEADLESS&&(m.push("--headless=new"),t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!"));let p=await ja.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:t}),{cookies:d,origins:w}=await a.storageState();d&&await p.addCookies(d),w&&w.length>0&&O(w,p);let g=await r.indexUrl();await p.waitForEvent("page",{predicate:h=>h.url().startsWith(g),timeout:3e4}),Kt=p.pages().find(h=>h.url().startsWith(g))??await _(p,g);for(let h of p.pages())h.url().includes("about:blank")&&await h.close();await Kt.locator("img[class='loading-spinner']").waitFor({state:"detached"}),await Ut(Kt),await n(p),await A(p,o)},metamaskPage:async({context:a},o)=>{await o(Kt)},metamask:async({context:a},o)=>{let n=new mt(Kt);await o(n)},createAnvilNode:async({context:a},o,n)=>{let r=n.workerIndex,i;await o(async c=>{i=za.define({instance:Ga.anvil(c)});let u=await i.start(r),m=`http://${u.host}:${u.port}`,d=c?.chainId??31337;return{rpcUrl:m,anvil:u,chainId:d}}),i&&await i.stop(r)},connectToAnvil:async({context:a,metamask:o,createAnvilNode:n},r)=>{await r(async()=>{let{chainId:i,rpcUrl:c}=await n({chainId:2251});await o.addCustomNetwork({chainId:i,currencySymbol:"ETH",networkName:"Anvil Localnet",rpcUrl:c})})}});import{test as Qa}from"@playwright/test";import{Instance as Xa,Pool as Za}from"prool";import xo from"fs";import qa from"path";import{chromium as Ya}from"@playwright/test";async function Bo({workerInfo:t,profileName:e,slowMo:a}){let o=new Z,n=await T(t.workerIndex.toString()),r=k(o.name),i=qa.resolve(r,e??"wallet-data");if(!xo.existsSync(i))throw new Error(`Cache for ${o.name} does not exist. Create it first!`);xo.cpSync(i,n,{recursive:!0,force:!0});let c=await W(o.name),u=await Ya.launchPersistentContext(n,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:a}),m=await o.indexUrl();await u.waitForEvent("page",{predicate:d=>d.url().startsWith(m),timeout:4e4});let p=u.pages().find(d=>d.url().startsWith(m));p||(p=await u.newPage(),await p.goto(m),await R(p));for(let d of u.pages())d.url().includes("about:blank")&&await d.close();return{context:u,walletPage:p,contextPath:n}}var au=({profileName:t,dappUrl:e,slowMo:a}={})=>Qa.extend({workerScopeContents:[async({browser:o},n,r)=>{let{context:i,contextPath:c,walletPage:u}=await Bo({workerInfo:r,profileName:t,slowMo:a});await i.grantPermissions(["clipboard-read"]);let m=new mt(u);await m.unlock(),await n({wallet:m,walletPage:u,context:i}),await A(i,c)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();e&&await i.goto(e),await n(i)},{scope:"worker"}],metamaskPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},metamask:async({workerScopeContents:o},n)=>{let r=new mt(o.walletPage);await n(r)},createAnvilNode:async({context:o},n,r)=>{let i=r.workerIndex,c;await n(async u=>{c=Za.define({instance:Xa.anvil(u)});let m=await c.start(i),p=`http://${m.host}:${m.port}`,w=u?.chainId??31337;return{rpcUrl:p,anvil:m,chainId:w}}),c&&await c.stop(i)},connectToAnvil:async({context:o,metamask:n,createAnvilNode:r},i)=>{await i(async()=>{let{chainId:c,rpcUrl:u}=await r({chainId:2251});await n.addCustomNetwork({chainId:c,currencySymbol:"ETH",networkName:"Anvil Localnet",rpcUrl:u})})}});var $={openSidebarMenuButton:"button[aria-label='open sidebar']",addWalletButton:"button:has-text('Add Wallet')",settingsButton:"button:has-text('Settings')",settingsMenuBackButton:"button[aria-label='Back']"};var j={importExistingWalletButton:'button:has-text("Import an existing wallet")',switchNetworkButton:"button[id^='menu-button']",privateKeyButton:"button:has-text('Private Key')",findMyAccountButton:"button:has-text('Find my account')"};async function ae(t,e,a){let o=t.locator(j.switchNetworkButton).last();await o.scrollIntoViewIfNeeded();let n=await o.textContent(),r=e.split("net")[0]?.toLowerCase()??"";if(n?.toLowerCase()===r)return console.info(`
|
|
6
|
+
Already on ${e}, no need to switch network.`),"Exit";await o.click();let c=t.locator(a).last().locator(`> button:has-text('${e}')`);await c.click(),await t.locator("div > h2:has-text('Meteor Community')").isVisible().catch(()=>!1)&&await c.click()}async function vt({page:t,newAccountName:e}){await t.locator($.openSidebarMenuButton).click(),await t.locator("div:has(> h2):has(> svg)").click();let n=t.locator("input[placeholder='Ex. My Meteor Wallet']"),r=t.locator("button[type='submit']:has-text('Update')");await n.fill(e),await r.click(),await t.locator("div[id='root'] button[aria-label='Close']").click()}async function ne({page:t,privateKey:e,accountName:a,network:o}){await t.locator($.openSidebarMenuButton).click(),await t.locator($.addWalletButton).click(),await ae(t,o,"section[role='dialog'] div[role='menu']"),await t.locator(j.importExistingWalletButton).click(),await t.locator(j.privateKeyButton).click();let u=t.locator('button:has-text("Continue")');await u.scrollIntoViewIfNeeded(),await u.click(),await t.locator("textarea:not([disabled])").fill(e),await t.locator(j.findMyAccountButton).click(),await t.locator("button[type='submit'][data-loading]").waitFor({state:"detached",timeout:25e3}),await t.locator("button:not([aria-label='Back'],[id^='menu-button']):has-text('Account')").click(),await vt({page:t,newAccountName:a})}var It={approveButton:"button:has-text('Approve')",connectButton:"button:has-text('Connect')",cancelButton:"button:has-text('Cancel')"};async function J(t){let e=await P("meteor"),a=t.locator("input[placeholder='Enter Password']"),o=t.locator('button:has-text("Unlock")');await a.fill(e),await o.click()}async function ko(t){await J(t),await t.locator(It.approveButton).click(),await t.locator("h2:has-text('Executing Transaction')").waitFor({state:"attached"}),await t.waitForEvent("close",{timeout:15e3})}async function Tt(t,e){if((await t.locator("div:has(button[type='button'][aria-label='open sidebar'])").nth(-2).locator("div:has(div > h2)").locator("div > h2").textContent())?.toLowerCase()===e.toLowerCase()){console.info(`
|
|
7
|
+
Switching to the ${e} account aborted. Account is already selected.`);return}await t.locator($.openSidebarMenuButton).click();let u=await t.locator("div:has(div > button[type='button'][aria-label='Close'])").nth(-2).locator("div").nth(2).locator("> div").nth(1).locator("div").nth(1).locator("div > h2").all(),m=null;for(let p of u)if((await p.textContent())?.toLowerCase()===e.toLowerCase()){m=p;break}if(!m)throw new Error(`Account with name "${e}" not found.`);await m.click()}async function bo(t,e){await J(t),e&&await Tt(t,e);let a=t.getByRole("heading",{name:"Connect Request",exact:!0});await Promise.all([t.locator(It.connectButton).click(),a.waitFor({state:"detached",timeout:3e4})])}async function Po(t){return await t.locator("div:has(button[type='button'][aria-label='open sidebar'])").nth(-2).locator("div:has(div > h2)").locator("div > svg").click(),await t.evaluate(async()=>await navigator.clipboard.readText())}async function Ao(t){await t.locator($.openSidebarMenuButton).click(),await t.locator("button:has-text('Lock Wallet')").click()}import{styleText as Te}from"util";var tt=class{name="meteor";onboardingPath="ext_index_popup.html";async indexUrl(){return`chrome-extension://${await this.extensionId()}/ext_index_popup.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/ext_index.html`}async extensionId(){return await H(this.name)}async promptPage(e){let a=await this.promptUrl();return await K({context:e,path:a,locator:"div[id='root']"})}};async function Wt(t){await t.locator($.openSidebarMenuButton).click(),await t.locator($.settingsButton).click()}async function re(t,e){if(await Wt(t),await ae(t,e,"div[role='menu']")==="Exit"){let r=t.locator($.settingsMenuBackButton);await r.scrollIntoViewIfNeeded(),await r.click();return}let o=t.locator("p:has-text('Available Balance')");if(await B(1e3),!await o.isVisible().catch(()=>!1))throw new Error([`There is no associated account for the ${e} network in your wallet.`,`Please add an account to the ${e} network in your wallet using the "addAccount" method.`,"NOTE: For the account to be persisted across tests, do this when onboarding the wallet."].join(`
|
|
8
|
+
`))}async function We({page:t,privateKey:e,network:a,accountName:o,addWallet:n}){console.info(Te("yellowBright",`
|
|
9
|
+
Meteor onboarding started...`,{validateStream:!1}));let r=await P("meteor"),c=await new tt().indexUrl();await t.goto(c);let u=t.locator(j.switchNetworkButton),m=await u.textContent(),p=a.split("net")[0]?.toLowerCase()??"";m?.toLowerCase().includes(p)||(await u.click(),await t.locator("div[role='menu']").locator(`> button:has-text('${a}')`).click());let d=t.locator("input[placeholder='Enter Password']"),w=t.locator("input[placeholder='Confirm Password']"),g=t.locator("label.chakra-checkbox .chakra-checkbox__control"),f=t.locator('button:has-text("Continue")');await d.fill(r),await w.fill(r),await g.click(),await f.click(),await t.locator(j.importExistingWalletButton).click(),await t.locator(j.privateKeyButton).click(),await f.scrollIntoViewIfNeeded(),await f.click(),await t.locator("textarea:not([disabled])").fill(e);let I=t.locator(j.findMyAccountButton);await I.click();let S=t.locator("button[type='submit'][data-loading]");if(await S.waitFor({state:"detached",timeout:25e3}),await t.getByRole("status").locator("div[id='toast-1-title']:has-text('No Account Found')").isVisible().catch(()=>!1)){let ct=5,yt=!1;for(;ct>0;){if(console.info(`
|
|
10
|
+
Retrying search for account. ${ct} attempts left`),await B(15e3),await I.click(),await S.waitFor({state:"detached",timeout:2e4}),await t.locator("div:has-text('Import Your Account')").nth(-2).locator("button").isVisible().catch(()=>!1)){yt=!0;break}ct-=1}if(!yt)throw Error(Te("redBright",["No Account Found","Account associated with the private key not found. Please make sure you are trying to import an account on the correct network(Mainnet/Testnet)."].join(`
|
|
11
|
+
`),{validateStream:!1}))}await t.locator("button:not([aria-label='Back'],[id^='menu-button']):has-text('Account')").click();let X=t.locator("section[role='dialog']").locator("button:has-text('Close')").first();if(await X.isVisible().then(()=>!0).catch(()=>!1)&&await X.click(),await vt({page:t,newAccountName:o}),n&&n.length>0){for(let{privateKey:_e,accountName:Ve,network:ca}of n)await ne({page:t,privateKey:_e,accountName:Ve,network:ca});await Wt(t);let ct=t.locator(j.switchNetworkButton).last();await ct.scrollIntoViewIfNeeded();let yt=await ct.textContent(),Re=a.split("net")[0]?.toLowerCase()??"";yt?.toLowerCase()!==Re&&await re(t,a),await Tt(t,o)}await B(3e3),console.info(Te("greenBright","\u2728 Meteor onboarding completed successfully"))}async function Co(t){await J(t),await t.locator(It.cancelButton).click()}var pt=class extends tt{page;constructor(e){super(),this.page=e}async onboard({network:e,privateKey:a,accountName:o,addWallet:n}){await We({page:this.page,network:e,privateKey:a,accountName:o,addWallet:n})}async unlock(){await J(this.page)}async lock(){await Ao(this.page)}async renameAccount({newAccountName:e}){await vt({page:this.page,newAccountName:e})}async switchNetwork(e){await re(this.page,e)}async switchAccount(e){await Tt(this.page,e)}async getAccountAddress(){return await Po(this.page)}async addAccount({accountName:e,network:a,privateKey:o}){await ne({page:this.page,accountName:e,network:a,privateKey:o})}async openSettings(){await Wt(this.page)}async connectToApp(e){await bo(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await ko(await this.promptPage(this.page.context()))}async rejectTransaction(){await Co(await this.promptPage(this.page.context()))}};import So from"fs";import Ja from"path";import{test as tn,chromium as en}from"@playwright/test";var Ht,Xm=({slowMo:t=0,profileName:e}={})=>tn.extend({contextPath:async({browserName:a},o,n)=>{let r=await T(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new tt,i=k(r.name),c=await W(r.name),u=Ja.resolve(i,e??"wallet-data");if(!So.existsSync(u))throw new Error("\u274C Cache for Meteor wallet data not found. Create it first");So.cpSync(u,o,{recursive:!0,force:!0}),process.env.HEADLESS&&t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!");let m=await en.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`,`--load-extension=${c}`],slowMo:process.env.HEADLESS?0:t});await m.grantPermissions(["clipboard-read"]);let{cookies:p,origins:d}=await a.storageState();p&&await m.addCookies(p),d&&d.length>0&&O(d,m);let w=await r.indexUrl();Ht=m.pages().find(f=>f.url().startsWith(w))||await _(m,w);for(let f of m.pages())f.url().includes("about:blank")&&await f.close();await Ht.bringToFront(),await J(Ht),await n(m),await A(m,o)},meteorPage:async({context:a},o)=>{await o(Ht)},meteor:async({context:a},o)=>{let n=new pt(Ht);await o(n)}});import{test as on}from"@playwright/test";var rp=({slowMo:t,profileName:e,dappUrl:a}={})=>on.extend({workerScopeContents:[async({browser:o},n,r)=>{let{context:i,contextPath:c,walletPage:u}=await kt({workerInfo:r,profileName:e,slowMo:t,wallet:new tt});await i.grantPermissions(["clipboard-read"]);for(let p of i.pages())p.url().includes("about:blank")&&await p.close();let m=new pt(u);await m.unlock(),await n({wallet:m,walletPage:u,context:i}),await A(i,c)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],meteorPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},meteor:async({workerScopeContents:o},n)=>{let r=new pt(o.walletPage);await n(r)}});import nn from"zod";var F={depositButton:"button:has-text('Deposit')",sendButton:"button:has-text('Send')",receiveButton:"button:has-text('Receive')",settingsMenu:"button[aria-label='Settings']",lockButton:"global-menu-lock",accountMenuButton:"button[data-part='trigger']",accountDialog:"div[role='dialog']",backButton:"button[id='back-button']"},Fe={networkSection:"a[href='/settings/network']",backButton:"button[id='back-button']"},Ne={passwordInput:"input[name='password']",unlockButton:"button:has-text('Unlock')"},Q={accountOptionsMenuButton:"button[data-scope='popover']",editAccountButton:"button[aria-label='Edit account name']",renameAccountInput:"input[name='name']",saveButton:"button:has-text('Save')",cancelButton:"button:has-text('Cancel')",addAccountButton:"button:has-text('Add accounts')",addAccountWithPrivateKeyButton:"button:has-text('Import private key')",addAccountWithMnemonicButton:"button:has-text('Import mnemonic')"};var N={createWalletButton:"button:has-text('Create an account')",createSeedPhraseButton:"button:has-text('Create a seed phrase wallet')",createNewPasswordInput:"input[name='password']",confirmNewPasswordInput:"input[name='confirmPassword']",confirmPasswordCheckbox:"label>div[data-scope='checkbox']",continueButton:"button:has-text('Continue')",skipCopyRecoveryPhraseButton:"button:has-text('Skip')",getStartedButton:"button:has-text('Get started')",onboardingCompleteText:"h1:has-text('Your wallet is ready, you may close this window')",importWalletButton:"button:has-text('Import an account')",importUsingPrivateKeyButton:"button:has-text('Import private key')",importUsingMnemonicButton:"button:has-text('Import mnemonic')",importButton:"button:has-text('Import')",privateKeyInput:"input[name='privateKey']"};import{expect as jt}from"@playwright/test";import an from"zod";async function dt({page:t,newAccountName:e}){let a=an.string().min(1,"Account name cannot be an empty string").parse(e);await t.locator(F.settingsMenu).click(),await jt(t.getByText("Settings").first()).toBeVisible();let n=t.locator(Q.editAccountButton);await jt(n).toBeVisible(),await n.click(),await jt(t.getByText("Account name").first()).toBeVisible();let r=t.locator(Q.renameAccountInput);if(await r.getAttribute("value")===a)throw Error(`The account to be renamed "${a}" already exists.`);await r.fill(a);let c=t.locator(Q.saveButton);await jt(c).toBeEnabled(),await c.click(),await jt(t.getByText(a).first()).toBeVisible(),await t.locator(F.backButton).click(),await Promise.allSettled([t.locator(F.depositButton).waitFor({state:"visible",timeout:2e4}),t.locator(F.sendButton).waitFor({state:"visible",timeout:2e4})])}async function ie({page:t,accountName:e,mode:a,...o}){let n=nn.string().max(14,"For switching accounts reason, account name should not be longer than 14 characters. The reason for this is because the name will be truncated. Hence, it will be difficult to select the account.").parse(e);if(await t.locator(Q.accountOptionsMenuButton).first().click(),await t.getByRole("dialog").locator(Q.addAccountButton).click(),a==="privateKey"){let u="privateKey"in o?o.privateKey:"";if(await t.locator(Q.addAccountWithPrivateKeyButton).click(),await t.locator(N.privateKeyInput).fill(u),await t.locator(N.importButton).click(),(await t.getByRole("status").locator("div[data-part='description']",{hasText:"Account already exists in wallet"}).textContent({timeout:3e3}).catch(()=>null))?.includes("Account already exists in wallet"))throw Error(`Account ${n} already exists in wallet`);await dt({page:t,newAccountName:n})}if(a==="mnemonic"){let m=("mnemonicPhrase"in o?o.mnemonicPhrase:"").split(" ");await t.locator(Q.addAccountWithMnemonicButton).click();for(let[y,h]of m.entries())await t.locator(`input[name="mnemonic-${String.fromCharCode(97+y)}"]`).fill(h);if(await t.locator(N.continueButton).click(),(await t.getByRole("status").locator("div[data-part='description']",{hasText:"Account already exists in wallet"}).textContent({timeout:3e3}).catch(()=>null))?.includes("Account already exists in wallet"))throw Error(`Account ${n} already exists in wallet`);await dt({page:t,newAccountName:n})}}var Ft={approveButton:'button:has-text("Approve")',cancelButton:'button:has-text("Cancel")'};var rn=/^[A-Z0-9]+(?:_[A-Z0-9]+)+$/;function vo(t){return rn.test(t)?t.toLowerCase().replace(/_/g," ").replace(/\b[a-z]/g,e=>e.toUpperCase()):t}async function cn(t,e){for(;;){let o=e();if(o||t.isClosed())break;try{let n=t.locator("div:has(> h2:has-text('Simulation error'))");if(await n.isVisible().catch(()=>!1)){let i=await n.locator("p").textContent();throw new Error(`[Confirm Transaction Error]: ${vo(i||"Unexpected error!")}`)}}catch(n){if(t.isClosed())break;throw n instanceof Error?n:new Error(`[Confirm Transaction Error]: ${n}`)}if(o||t.isClosed())break;await B(300)}}async function Io(t){let e=!1;cn(t,()=>e).catch(async n=>{t.isClosed()||console.error(n.message)}),await t.locator(Ft.approveButton).click(),e=!0}import{expect as sn}from"@playwright/test";async function Nt(t,e){let a=t.locator(Q.accountOptionsMenuButton).first();if((await a.textContent())?.split("Switch wallet")[1]?.split("0x")[0]?.toLowerCase().trim().includes(e.toLowerCase().trim())){console.info(`
|
|
12
|
+
Switching to ${e} account aborted because the account is already selected.`);return}await a.click();let r=await t.getByRole("dialog").locator("> div > div > button[type='button']").all(),i=null;for(let c of r)if((await c.textContent())?.toLowerCase()?.trim().includes(e.toLowerCase().trim())){i=c;break}if(!i)throw new Error(`Account with name "${e}" not found.`);await i.click()}async function To(t,e){e&&await Nt(t,e);let a=t.locator(Ft.approveButton);await sn(a).toBeEnabled({timeout:2e4}),await a.click()}async function Wo(t){return await t.getByRole("button",{name:"Copy Address",exact:!0}).click(),await t.evaluate(async()=>await navigator.clipboard.readText())}import{expect as Fo}from"@playwright/test";async function No(t){let e=t.locator(F.settingsMenu);await Fo(e).toBeVisible(),await e.click(),await Fo(t.getByText("Settings").first()).toBeVisible()}async function Mo(t){await No(t),await t.getByRole("button",{name:/lock wallet/i}).click(),await t.getByRole("heading",{name:/welcome/i}).waitFor({state:"visible",timeout:2e4})}import{styleText as Eo}from"util";import{expect as rt}from"@playwright/test";var et=class{name="petra";onboardingPath="/onboarding.html";async indexUrl(){return`chrome-extension://${await this.extensionId()}/index.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/prompt.html`}async extensionId(){return await H(this.name)}async promptPage(e){let a=await this.promptUrl();return await K({context:e,path:a,locator:"div[id='prompt']"})}};var Mt=3e4;async function Me({page:t,...e}){console.info(Eo("yellowBright",`
|
|
13
|
+
Petra onboarding started...`,{validateStream:!1}));let a=new et,o=await P("petra"),n=t.locator(N.createWalletButton),r=t.locator(N.importWalletButton),i=t.locator(N.createNewPasswordInput),c=t.locator(N.confirmNewPasswordInput),u=t.locator(N.confirmPasswordCheckbox),m=t.locator(N.continueButton),p=t.locator(N.getStartedButton),d=t.locator(N.onboardingCompleteText);if(e.mode==="create"){let w=t.locator(N.createSeedPhraseButton);await n.click(),await w.click(),await i.fill(o),await c.fill(o),await u.click(),await m.click(),await t.locator(N.skipCopyRecoveryPhraseButton).click(),await p.click(),await rt(d).toBeVisible({timeout:25e3}),await t.goto(await a.indexUrl()),await rt(t.locator(F.depositButton)).toBeVisible({timeout:Mt}),await rt(t.locator(F.sendButton)).toBeVisible({timeout:Mt})}if(e.mode==="importPrivateKey"){let{privateKey:w}=e,g=t.locator(N.importUsingPrivateKeyButton),f=t.locator(N.privateKeyInput),y=t.locator(N.importButton);await r.click(),await g.click(),await f.fill(w),await y.click(),await i.fill(o),await c.fill(o),await u.click(),await m.click(),await p.click(),await rt(d).toBeVisible({timeout:25e3}),await t.goto(await a.indexUrl()),await R(t),await rt(t.locator(F.depositButton)).toBeVisible({timeout:Mt}),await rt(t.locator(F.sendButton)).toBeVisible({timeout:Mt})}if(e.mode==="importMnemonic"){let{secretRecoveryPhrase:w}=e,g=t.locator(N.importUsingMnemonicButton);await r.click(),await g.click();for(let[f,y]of w.split(" ").entries())await t.locator(`input[name="mnemonic-${String.fromCharCode(97+f)}"]`).fill(y);await m.click(),await i.fill(o),await c.fill(o),await u.click(),await m.click(),await p.click(),await rt(d).toBeVisible({timeout:25e3}),await t.goto(await a.indexUrl()),await rt(t.locator(F.depositButton)).toBeVisible({timeout:Mt}),await rt(t.locator(F.sendButton)).toBeVisible({timeout:Mt})}if(await dt({page:t,newAccountName:e.accountName}),e.addWallet&&e.addWallet.length>0){for(let{...w}of e.addWallet)await ie({page:t,...w});await Nt(t,e.accountName)}await B(1500),console.info(Eo("greenBright","\u2728 Petra onboarding completed successfully",{validateStream:!1}))}import{expect as ln}from"@playwright/test";async function Ro(t){let e=t.locator(Ft.cancelButton);await ln(e).toBeEnabled(),await e.click()}async function _o(t,e){await t.locator(F.settingsMenu).click(),await t.locator(Fe.networkSection).click(),await t.locator(`div:has(> span:has-text("${e}"))`).first().click();let r=t.locator(Fe.backButton);await r.click(),await r.click()}import{expect as Vo}from"@playwright/test";async function Gt(t){let e=await P("petra"),a=t.locator(Ne.passwordInput);if(!await a.isVisible().then(()=>!0).catch(()=>!1)){console.info("\u{1F4A1} Wallet is already unlocked");return}await Vo(a).toBeVisible({timeout:15e3}),await a.fill(e);let n=t.locator(Ne.unlockButton);await Vo(n).toBeEnabled(),await n.click(),await Promise.allSettled([t.locator(F.sendButton).waitFor({state:"visible",timeout:2e4}),t.locator(F.receiveButton).waitFor({state:"visible",timeout:2e4})])}var wt=class extends et{page;constructor(e){super(),this.page=e}async onboard(e){await Me({page:this.page,...e})}async unlock(){await Gt(this.page)}async lock(){await Mo(this.page)}async renameAccount({newAccountName:e}){await dt({page:this.page,newAccountName:e})}async switchNetwork(e){await _o(this.page,e)}async switchAccount(e){await Nt(this.page,e)}async getAccountAddress(){return await Wo(this.page)}async addAccount({accountName:e,...a}){await ie({page:this.page,accountName:e,...a})}async connectToApp(e){await To(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await Io(await this.promptPage(this.page.context()))}async rejectTransaction(){await Ro(await this.promptPage(this.page.context()))}};import $o from"fs";import un from"path";import{test as mn,chromium as pn}from"@playwright/test";var zt,ew=({slowMo:t=0,profileName:e}={})=>mn.extend({contextPath:async({browserName:a},o,n)=>{let r=await T(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new et,i=k(r.name),c=await W(r.name),u=un.resolve(i,e??"wallet-data");if(!$o.existsSync(u))throw new Error("\u274C Cache for Petra wallet data not found. Create it first");$o.cpSync(u,o,{recursive:!0,force:!0});let m=[`--disable-extensions-except=${c}`,`--load-extension=${c}`];process.env.HEADLESS&&(m.push("--headless=new"),t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!"));let p=await pn.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:t});await p.grantPermissions(["clipboard-read"]);let{cookies:d,origins:w}=await a.storageState();d&&await p.addCookies(d),w&&w.length>0&&O(w,p);let g=await r.indexUrl();zt=p.pages().find(y=>y.url().startsWith(g))||await _(p,g);for(let y of p.pages()){let h=y.url();(h.includes("about:blank")||h.includes(r.onboardingPath))&&await y.close()}await zt.bringToFront(),await Gt(zt),await n(p),await A(p,o)},petraPage:async({context:a},o)=>{await o(zt)},petra:async({context:a},o)=>{let n=new wt(zt);await o(n)}});import{test as dn}from"@playwright/test";var lw=({slowMo:t,profileName:e,dappUrl:a}={})=>dn.extend({workerScopeContents:[async({browser:o},n,r)=>{let i=new et,{context:c,contextPath:u,walletPage:m}=await kt({wallet:i,workerInfo:r,profileName:e,slowMo:t});await c.grantPermissions(["clipboard-read"]);for(let d of c.pages())d.url().includes(i.onboardingPath)&&await d.close();let p=new wt(m);await p.unlock(),await n({wallet:p,walletPage:m,context:c}),await A(c,u)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],petraPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},petra:async({workerScopeContents:o},n)=>{let r=new wt(o.walletPage);await n(r)}});var E={openMenuButton:"settings-menu-open-button",settingsButton:"sidebar_menu-button-settings",addAccountButton:"sidebar_menu-button-add_account",unlockWalletButton:"unlock-form-submit-button",manageAccountsButton:"sidebar_menu-button-manage_accounts",homeHeaderAccountName:"home-header-account-name"},U={lockWalletButton:"lock-menu-item",closeMenuButton:"settings-menu-close-button",developerSettingsButton:"settings-item-developer-settings",activeNetworksButton:"settings-item-active-networks"},Lo={accountProfileContainer:"sortable-account-container"};var b={createNewWalletButton:"button:has-text('Create a new wallet')",IAlreadyHaveAWalletButton:"button:has-text('I already have a wallet')",importRecoveryPhraseButton:"button:has-text('Import Recovery Phrase')",importPrivateKeyButton:"button:has-text('Import Private Key')",createSeedPhraseWalletButton:"create-manual-seed-phrase",passwordInput:"onboarding-form-password-input",passwordConfirmInput:"onboarding-form-confirm-password-input",termsCheckBox:"onboarding-form-terms-of-service-checkbox",continueButton:"button:has-text('Continue')",importWalletButton:"button:has-text('Import Wallet')",getStartedButton:"button:has-text('Get Started')",recoveryPhraseSavedCheckbox:"onboarding-form-saved-secret-recovery-phrase-checkbox",recoveryPhraseInput:"secret-recovery-phrase-word-input"};async function ce({page:t,privateKey:e,accountName:a,chain:o}){await t.getByTestId(E.openMenuButton).click(),await t.getByTestId(E.addAccountButton).click(),await t.locator(b.importPrivateKeyButton).click();let c=t.locator("span[id^='button--listbox-input--']"),u=await c.textContent(),m=t.locator("input[name='name']"),p=t.locator("textarea[name='privateKey']");u!==o&&(await c.click(),await t.locator("ul[id^='listbox--listbox-input--']").locator(`li[data-label='${o}']`).click()),await m.fill(a),await p.fill(e),await t.locator("button:has-text('Import')").click()}var Et={confirmButton:"primary-button",cancelButton:"secondary-button"};async function Oo(t){let e=t.getByTestId(Et.confirmButton);await t.getByTestId("approve-transaction").waitFor({state:"attached"});let o=t.getByRole("button",{name:"Confirm anyway",exact:!0});if(await o.isVisible().catch(()=>!1)){await o.click();return}await e.click()}import{expect as fn}from"@playwright/test";import wn from"zod";async function Rt(t,e){let a=wn.string().min(1,"Account name cannot be an empty string").parse(e);await t.getByTestId(E.openMenuButton).click();let n=null,r=await t.locator("div[data-testid='account-menu'] div[data-testid='tooltip_interactive-wrapper']").all();for(let i of r)if((await i.textContent())?.includes(a)){n=i;break}if(!n)throw new Error(`Account with name "${a}" not found in the account list.`);await n.click()}async function Do(t,e){e&&await Rt(t,e);let a=t.getByTestId(Et.confirmButton);await fn(a).toBeEnabled({timeout:15e3}),await a.click()}import gn from"zod";var hn=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");async function Uo({page:t,accountName:e,chain:a}){let o=gn.string().min(1,"Account name cannot be an empty string").parse(e);await t.getByTestId(E.openMenuButton).click(),await t.getByTestId(E.manageAccountsButton).click(),await t.getByTestId(`manage-accounts-sortable-${o}`).click();let c=t.getByRole("button",{name:/Account Address(?:es)?/i});await c.waitFor({state:"visible",timeout:2e4});let m=await c.locator("div[data-name='row.pair'] > div").last().textContent();if(m&&Number(m)===1){await c.locator("> div > div").last().click(),await t.getByTestId("header--back").click();let w=t.getByTestId(U.closeMenuButton);await w.waitFor({state:"visible",timeout:15e3}),await w.click()}else{await c.click();let d=new RegExp(`${hn(a.network)}`,"i");await t.getByRole("button",{name:d}).locator("> div").last().locator("> div").last().locator("div > button").last().click(),await t.getByRole("button",{name:"Close",exact:!0}).last().click();let x=t.getByTestId("header--back");await x.waitFor({state:"visible",timeout:15e3}),await x.click();let I=t.getByTestId(U.closeMenuButton);await I.waitFor({state:"visible",timeout:15e3}),await I.click()}return await t.evaluate(async()=>await navigator.clipboard.readText())}async function Ko(t){await t.getByTestId(E.openMenuButton).click(),await t.getByTestId(E.settingsButton).click(),await t.getByTestId(U.lockWalletButton).click()}import{styleText as Ho}from"util";import{expect as yn}from"@playwright/test";var ot=class{name="phantom";onboardingPath="/onboarding.html";async indexUrl(){return`chrome-extension://${await this.extensionId()}/popup.html`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/notification.html`}async extensionId(){return await H(this.name)}async promptPage(e){let a=await this.promptUrl();return await K({context:e,path:a,locator:"div[id='root']"})}};async function _t(t,e){let o=!1;for(;!e();){let n=e();if(n||o||t.isClosed())break;try{let r=t.locator("div[id='modal']").locator("div > svg").first();await r.isVisible().catch(()=>!1)&&(await r.click(),o=!0)}catch(r){if(t.isClosed())break;console.error("[autoClosePhantomNotification]: ",r)}if(n||o||t.isClosed())break;await B(300)}}async function se({page:t,currentAccountName:e,newAccountName:a}){await t.getByTestId(E.openMenuButton).click(),await t.getByTestId(E.manageAccountsButton).click();let i=await t.getByTestId(Lo.accountProfileContainer).locator("div[data-testid^='manage-accounts-sortable'] div > p").all(),c=null;for(let g of i)if((await g.textContent())?.toLowerCase()===e.toLowerCase()){c=g;break}if(!c)throw new Error(`Account with name "${e}" not found`);await c.click(),await t.locator("button:has-text('Account Name')").click();let m=t.locator("input[name='name']");await m.clear(),await m.fill(a),await t.getByTestId("primary-button").click(),await t.getByTestId("header--back").click(),await t.getByTestId(U.closeMenuButton).click()}async function le(t){await t.getByTestId(E.openMenuButton).click(),await t.getByTestId(E.settingsButton).click()}async function ue({page:t,...e}){await le(t);let a=t.locator(`button[id='${U.developerSettingsButton}']`);await a.scrollIntoViewIfNeeded(),await a.click();let o=t.getByTestId("toggleTestNetwork"),r=await o.locator("label[data-testid='toggleTestNetwork-switch'] > input[aria-label='Toggle']").isChecked().catch(()=>!1);if(!r&&e.mode==="on"&&await o.click(),r&&e.mode==="off"){await o.click(),await t.getByTestId("header--back").click(),await t.getByTestId(U.closeMenuButton).click();return}if(e.mode==="on"&&e.chain==="Solana"){let{network:u}=e;await t.locator(`button:has-text("${u}")`).click()}if(e.mode==="on"&&e.chain==="Ethereum"){let{network:u}=e;if(!await t.getByText("EVM",{exact:!0}).isVisible().catch(()=>!1))throw new Error(["EVM testnet options are not available. Please ensure Ethereum is enabled in optional chains.","To enable Ethereum, call the 'toggleOptionalChain' action before switching the network.","toggleOptionalChain({ page: page, toggleMode: 'on', supportedChains: ['Ethereum'] })","Tip: For persistence, enable Ethereum in your setup file after the onboarding step completes."].join(`
|
|
14
|
+
`));await t.locator(`button:has-text("${u}")`).click()}await t.getByTestId("header--back").click(),await t.getByTestId(U.closeMenuButton).click()}async function Ee({page:t,addWallet:e,...a}){console.info(Ho("yellowBright",`
|
|
15
|
+
Phantom onboarding started...`,{validateStream:!1}));let o=await P("phantom");if(a.mode==="create"){await t.locator(b.createNewWalletButton).click(),await t.getByTestId(b.createSeedPhraseWalletButton).click();let g=t.getByTestId(b.passwordInput),f=t.getByTestId(b.passwordConfirmInput),y=t.getByTestId(b.termsCheckBox),h=t.locator(b.continueButton);await g.fill(o),await f.fill(o),await y.click(),await h.click(),await h.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.getByTestId(b.recoveryPhraseSavedCheckbox).click(),await h.click(),await B(1e3),await h.click(),await t.locator(b.getStartedButton).last().click()}if(a.mode==="recovery phrase"){let w=a.secretRecoveryPhrase.split(" ");await t.locator(b.IAlreadyHaveAWalletButton).click(),await t.locator(b.importRecoveryPhraseButton).click();for(let[it,at]of Object.entries(w))await t.getByTestId(`${b.recoveryPhraseInput}-${it}`).fill(at);await t.locator(b.importWalletButton).click(),await t.locator("p:has-text('Finding accounts with activity')").waitFor({state:"detached",timeout:6e4});let x=t.locator(b.continueButton);await x.click();let I=t.getByTestId(b.passwordInput),S=t.getByTestId(b.passwordConfirmInput),v=t.getByTestId(b.termsCheckBox);await I.fill(o),await S.fill(o),await v.click(),await x.click(),await x.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.locator(b.getStartedButton).last().click()}if(a.mode==="private key"){await t.locator(b.IAlreadyHaveAWalletButton).click();let{privateKey:w,chain:g,accountName:f}=a;await t.locator(b.importPrivateKeyButton).click();let h=t.locator("span[id='button--listbox-input--1']"),x=await h.textContent(),I=t.locator("input[name='name']"),S=t.locator("textarea[name='privateKey']");x!==g&&(await h.click(),await t.locator("ul[id='listbox--listbox-input--1']").locator(`li[data-label='${g}']`).click()),await I.fill(f),await S.fill(w),await t.locator("button:has-text('Import')").click();let V=t.getByTestId(b.passwordInput),L=t.getByTestId(b.passwordConfirmInput),it=t.getByTestId(b.termsCheckBox);await V.fill(o),await L.fill(o),await it.click();let at=t.locator(b.continueButton);await at.click(),await at.locator("> div > svg").waitFor({state:"detached",timeout:3e4}),await t.locator(b.getStartedButton).last().click()}let n=await t.context().newPage(),r=await new ot().indexUrl();await n.goto(r);let c=await t.context().browser()?.newBrowserCDPSession(),u;await yn.poll(async()=>{if(c){let{targetInfos:d}=await c.send("Target.getTargets"),g=d.filter(f=>f.title==="Phantom Wallet").find(f=>!f.attached&&f.url===r);return u=g,!!g}},{timeout:2e4}).toBe(!0),u&&await c?.send("Target.closeTarget",{targetId:u.targetId});let m=await n.getByTestId("home-header-account-name").textContent();if(a.mode==="create"){let{accountName:d}=a;await se({page:n,newAccountName:d,currentAccountName:"Account 1"})}if(e&&e.length>0){let d=!1;_t(n,()=>d).catch(f=>console.error({error:f}));for(let{accountName:f,chain:y,privateKey:h}of e)await ce({page:n,privateKey:h,accountName:f,chain:y}),d=!0;let g=a.mode==="create"?a.accountName:m;g&&await Rt(n,g)}a.toggleNetworkMode&&await ue({page:n,...a.toggleNetworkMode}),await B(3e3),console.info(Ho("greenBright","\u2728 Phantom onboarding completed successfully",{validateStream:!1}))}async function jo(t){let e=t.getByTestId(Et.cancelButton);await t.getByTestId("approve-transaction").waitFor({state:"attached"}),await e.click()}async function Go({page:t,supportedChains:e,toggleMode:a="off"}){if(await le(t),await t.locator("button[id='settings-item-active-networks']").click(),e.length===0)throw Error("Supported chains array cannot be empty for toggle mode other than 'onboard'");for(let i of e){let c=t.locator(`button[id='toggle-${i.toLowerCase()}']`),m=await c.locator(`label[data-testid='toggle-${i.toLowerCase()}-switch'] > input[aria-label='Toggle']`).isChecked().catch(()=>!1);a==="off"&&m&&await c.click(),a==="on"&&!m&&await c.click()}await t.getByTestId("header--back").click(),await t.getByTestId(U.closeMenuButton).click()}async function me(t){let e=await P("phantom"),a=t.locator("input[name='password']"),o=t.getByTestId("unlock-form-submit-button");await a.fill(e),await o.click(),await o.waitFor({state:"detached"})}var ft=class extends ot{page;constructor(e){super(),this.page=e}async onboard({...e}){await Ee({page:this.page,...e})}async unlock(){await me(this.page)}async lock(){await Ko(this.page)}async renameAccount({...e}){await se({page:this.page,...e})}async switchAccount(e){await Rt(this.page,e)}async getAccountAddress({accountName:e,chain:a}){return await Uo({page:this.page,accountName:e,chain:a})}async addAccount({...e}){await ce({page:this.page,...e})}async toggleOptionalChains({toggleMode:e,supportedChains:a}){await Go({page:this.page,supportedChains:a,toggleMode:e})}async switchNetwork({...e}){await ue({page:this.page,...e})}async connectToApp(e){await Do(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await Oo(await this.promptPage(this.page.context()))}async rejectTransaction(){await jo(await this.promptPage(this.page.context()))}};import zo from"fs";import xn from"path";import{test as Bn,chromium as kn}from"@playwright/test";var Vt,cg=({slowMo:t=0,profileName:e}={})=>Bn.extend({contextPath:async({browserName:a},o,n)=>{let r=await T(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new ot,i=k(r.name),c=await W(r.name),u=xn.resolve(i,e??"wallet-data");if(!zo.existsSync(u))throw new Error("\u274C Cache for Phantom wallet data not found. Create it first");zo.cpSync(u,o,{recursive:!0,force:!0}),process.env.HEADLESS&&t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!");let m=await kn.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`,`--load-extension=${c}`],slowMo:process.env.HEADLESS?0:t});await m.grantPermissions(["clipboard-read"]);let{cookies:p,origins:d}=await a.storageState();p&&await m.addCookies(p),d&&d.length>0&&await O(d,m);let w=await r.indexUrl();Vt=m.pages().find(f=>f.url().startsWith(w))||await _(m,w);for(let f of m.pages())f.url().includes("about:blank")&&await f.close();await Vt.bringToFront(),await me(Vt),await n(m),await A(m,o)},phantomPage:async({context:a},o)=>{await o(Vt)},phantom:async({context:a},o)=>{let n=new ft(Vt);await o(n)},autoCloseNotification:[async({context:a},o)=>{let n=!1,i=_t(Vt,()=>n);await o(void 0),n=!0,await i.catch(c=>{console.error(`Auto close notification error: ${c.message}`)})},{auto:!0}]});import{test as An}from"@playwright/test";import qo from"fs";import bn from"path";import{chromium as Pn}from"@playwright/test";async function Yo({workerInfo:t,profileName:e,slowMo:a}){let o=new ot,n=await T(t.workerIndex.toString()),r=k(o.name),i=bn.resolve(r,e??"wallet-data");if(!qo.existsSync(i))throw new Error(`Cache for ${o.name} does not exist. Create it first!`);qo.cpSync(i,n,{recursive:!0,force:!0});let c=await W(o.name),u=await Pn.launchPersistentContext(n,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:a}),m=await o.indexUrl(),p=await _(u,m);return{context:u,walletPage:p,contextPath:n}}var Cg=({slowMo:t,profileName:e,dappUrl:a}={})=>An.extend({workerScopeContents:[async({browser:o},n,r)=>{let{context:i,contextPath:c,walletPage:u}=await Yo({workerInfo:r,profileName:e,slowMo:t});await i.grantPermissions(["clipboard-read"]);for(let p of i.pages())p.url().includes("about:blank")&&await p.close();let m=new ft(u);await m.unlock(),await n({wallet:m,walletPage:u,context:i}),await A(i,c)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],phantomPage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},phantom:async({workerScopeContents:o},n)=>{let r=new ft(o.walletPage);await n(r)},autoCloseNotification:[async({workerScopeContents:o},n)=>{let r=!1,i=()=>r,c=_t(o.walletPage,i);await n(void 0),r=!0,await c.catch(u=>{console.error(`Auto close notification error: ${u.message}`)})},{auto:!0}]});var gt={networkSettings:"li-settings-network",selectNetwork:"select-network",confirmModal:"modal-confirm",confifmButton:"btn-confirm",securityAndPrivacyButton:"nav-item-security-and-privacy",lockButton:"btn-lock"},$t={portfolioButton:"nav-item-portfolio",walletSelectorButton:"icon-section-wallet-picker-arrow-right"};import pe from"zod";var Qo=pe.object({walletName:pe.string().min(1,"Wallet name cannot be an empty string"),privateKey:pe.array(pe.number()).length(64)});async function de({page:t,privateKey:e,walletName:a}){let o=Qo.parse({privateKey:e,walletName:a});await t.getByTestId($t.walletSelectorButton).click(),await t.getByTestId("icon-btn-add").click(),await t.getByTestId("li-add-wallet-privateKey-add").click();let c=t.getByTestId("input-name"),u=t.getByTestId("input-private-key");await c.fill(o.walletName),await u.fill(`${o.privateKey}`),await t.getByTestId("btn-import").click(),await t.locator("span:has-text('My wallets')").waitFor({state:"attached"}),await t.getByRole("dialog").getByTestId("icon-btn-close").click()}import{expect as Cn}from"@playwright/test";var we={approveButton:"btn-approve",rejectButton:"btn-reject"};async function Xo(t){let e=t.getByTestId(we.approveButton);await t.getByTestId("section-network-fee").waitFor({state:"attached",timeout:3e4}).catch(async()=>{console.error("Network fee section did not appear within the timeout period, which may indicate that the transaction confirmation popup did not load correctly."),await t.getByText("Network mismatch",{exact:!0}).isVisible().catch(()=>!1)&&(await t.getByRole("button",{name:"Close",exact:!0}).click(),console.error("A 'Network mismatch' error was detected in the popup. Closing the popup and aborting the transaction confirmation process."))});let o=t.locator("div[data-id='control-label']");await o.isVisible().catch(()=>!1)&&await o.click(),await Cn(e).toBeEnabled(),await e.click()}async function fe(t,e){await t.getByTestId("icon-section-wallet-picker-arrow-right").click();let o=t.getByTestId("list-item-m-title").filter({hasText:e}).locator("xpath=../..");if(!await o.isVisible().catch(()=>!1))throw new Error(`Account "${e}" not found. Make sure the account is onboarded or verify the account name.`);await o.click()}async function Zo(t,e){e&&await fe(t,e),await t.getByRole("button",{name:"Connect",exact:!0}).click()}async function Jo(t){return await t.getByTestId("icon-section-wallet-picker-copy").click(),await t.evaluate(async()=>await navigator.clipboard.readText())}async function ge(t){let e=t.getByRole("button",{name:"settings",exact:!0});await e.waitFor({state:"attached",timeout:3e4}),await e.click()}async function ta(t){await ge(t),await t.getByTestId(gt.securityAndPrivacyButton).click(),await t.getByTestId("li-settings-lock").getByTestId(gt.lockButton).click()}import{styleText as ea}from"util";var st={alreadyHaveAWalletButton:"btn-already-have-wallet",recoveryPhraseInput:"input-recovery-phrase",continueButton:"btn-continue",passwordInput:"input-new-password",repeatPasswordInput:"input-repeat-password",quickSetupButton:"btn-quick-setup",IAgreeButton:"btn-explore"};async function he({page:t,currentAccountName:e,newAccountName:a}){await t.getByTestId($t.walletSelectorButton).click();let n=t.locator(`button[data-testid^='li-wallets']:has-text('${e}')`);if(!await n.isVisible().catch(()=>!1))throw new Error(`Account "${e}" not found. Make sure the account is available.`);await n.hover({timeout:2e4}),await n.getByTestId("icon-btn-three-dots").click({timeout:2e4});let c=t.getByTestId("li-manage-wallet-rename-wallet");await c.click();let u=t.getByTestId("input-name");await u.clear(),await u.fill(a),await t.getByTestId("btn-save").click(),await c.waitFor({state:"attached",timeout:15e3}),await t.getByTestId("icon-btn-close").click()}async function ye(t,e){await ge(t);let o=t.getByTestId("li-settings-network").getByRole("combobox");await o.locator(" > p").textContent()!==e?(await o.click(),await t.getByTestId(gt.selectNetwork).getByRole("option",{name:e,exact:!0}).click(),(e==="Devnet"||e==="Testnet")&&await t.getByTestId(gt.confirmModal).getByTestId(gt.confifmButton).click()):console.info(`Network is already set to ${e}`),await t.getByTestId($t.portfolioButton).click()}async function oa({page:t,recoveryPhrase:e,network:a,walletName:o,addWallet:n}){console.info(ea("yellowBright",`
|
|
16
|
+
Solflare onboarding started...`,{validateStream:!1}));let r=await P("solflare");await t.getByTestId(st.alreadyHaveAWalletButton).click();let c=e.split(" ");for(let[y,h]of Object.entries(c))await t.getByTestId(`${st.recoveryPhraseInput}-${Number(y)+1}`).fill(h);let u=t.getByTestId(st.continueButton);await u.click();let m=t.getByTestId(st.passwordInput),p=t.getByTestId(st.repeatPasswordInput);if(await m.fill(r),await p.fill(r),await u.click(),await t.locator("div",{hasText:"Detecting your existing accounts. This process can take up to a minute."}).waitFor({state:"detached"}),await t.getByTestId(st.quickSetupButton).click(),await t.getByTestId(st.IAgreeButton).click(),await he({page:t,currentAccountName:"Main Wallet",newAccountName:o}),a&&await ye(t,a),n&&n?.length>0)for(let{privateKey:y,walletName:h}of n)await de({page:t,privateKey:y,walletName:h});console.info(ea("greenBright","\u2728 Solflare onboarding completed successfully",{validateStream:!1}))}async function aa(t){await t.getByTestId(we.rejectButton).click()}async function xe(t){let e=await P("solflare");await t.getByTestId("input-password").fill(e),await t.getByTestId("btn-unlock").click(),await t.getByTestId("nav-main").waitFor({state:"attached",timeout:3e4})}var lt=class{name="solflare";onboardingPath="wallet.html#/onboard";async indexUrl(){return`chrome-extension://${await this.extensionId()}/wallet.html#/portfolio`}async promptUrl(){return`chrome-extension://${await this.extensionId()}/confirm_popup.html`}async extensionId(){return await H(this.name)}async promptPage(e){let a=await this.promptUrl();return await K({context:e,path:a,locator:"div[data-testid='page-dapp-connect'], div[data-testid='page-tx-sign']"})}};var ht=class extends lt{page;constructor(e){super(),this.page=e}async onboard({recoveryPhrase:e,network:a,addWallet:o,walletName:n}){await oa({page:this.page,recoveryPhrase:e,network:a,addWallet:o,walletName:n})}async unlock(){await xe(this.page)}async lock(){await ta(this.page)}async renameAccount({currentAccountName:e,newAccountName:a}){await he({page:this.page,currentAccountName:e,newAccountName:a})}async switchNetwork(e){await ye(this.page,e)}async switchAccount(e){await fe(this.page,e)}async getAccountAddress(){return await Jo(this.page)}async addAccount({privateKey:e,walletName:a}){await de({page:this.page,privateKey:e,walletName:a})}async connectToApp(e){await Zo(await this.promptPage(this.page.context()),e)}async confirmTransaction(){await Xo(await this.promptPage(this.page.context()))}async rejectTransaction(){await aa(await this.promptPage(this.page.context()))}};import na from"fs";import Sn from"path";import{test as vn,chromium as In}from"@playwright/test";async function Be(t,e){let o=!1;for(;!e();){let n=e();if(n||o||t.isClosed())break;try{let r=t.locator("div[role='dialog']").locator("button[data-testid='icon-btn-whats-new-modal-close']");await r.isVisible().catch(()=>!1)&&(await r.click(),o=!0)}catch(r){console.error("[autoCloseSolflareNotification]: ",r)}if(n||o||t.isClosed())break;await B(150)}}var qt,uy=({slowMo:t=0,profileName:e}={})=>vn.extend({contextPath:async({browserName:a},o,n)=>{let r=await T(`${a}-${n.testId}`);await o(r)},context:async({context:a,contextPath:o},n)=>{let r=new lt,i=k(r.name),c=await W(r.name),u=Sn.resolve(i,e??"wallet-data");if(!na.existsSync(u))throw new Error("\u274C Cache for Solflare wallet data not found. Create it first");await na.promises.cp(u,o,{recursive:!0,force:!0});let m=[`--disable-extensions-except=${c}`,`--load-extension=${c}`];process.env.HEADLESS&&(m.push("--headless=new"),t>0&&console.warn("\u26A0\uFE0F Slow motion makes no sense in headless mode. It will be ignored!"));let p=await In.launchPersistentContext(o,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:t});await p.grantPermissions(["clipboard-read"]);let{cookies:d,origins:w}=await a.storageState();d&&await p.addCookies(d),w&&w.length>0&&O(w,p);let g=await r.indexUrl(),f=g.split("#")[0]??"";await p.waitForEvent("page",{predicate:h=>h.url().includes(f),timeout:15e3}),qt=p.pages().find(h=>h.url().startsWith(f))||await _(p,g);for(let h of p.pages())h.url().includes("about:blank")&&await h.close();await xe(qt),await n(p),await A(p,o)},solflarePage:async({context:a},o)=>{await o(qt)},solflare:async({context:a},o)=>{let n=new ht(qt);await o(n)},autoCloseNotification:[async({context:a},o)=>{let n=!1,i=Be(qt,()=>n);await o(void 0),n=!0,await i.catch(c=>{console.error(`Auto close notification error: ${c.message}`)})},{auto:!0}]});import{test as Fn}from"@playwright/test";import ra from"fs";import Tn from"path";import{chromium as Wn}from"@playwright/test";async function ia({workerInfo:t,profileName:e,slowMo:a}){let o=new lt,n=await T(t.workerIndex.toString()),r=k(o.name),i=Tn.resolve(r,e??"wallet-data");if(!ra.existsSync(i))throw new Error(`Cache for ${o.name} does not exist. Create it first!`);ra.cpSync(i,n,{recursive:!0,force:!0});let c=await W(o.name),u=await Wn.launchPersistentContext(n,{headless:!1,args:[`--disable-extensions-except=${c}`],slowMo:process.env.HEADLESS?0:a}),m=await o.indexUrl(),p=m.split("#")[0]??"";await u.waitForEvent("page",{predicate:w=>w.url().includes(p),timeout:15e3});let d=u.pages().find(w=>w.url().startsWith(p));d||(d=await u.newPage(),await d.goto(m),await R(d));for(let w of u.pages())w.url().includes("about:blank")&&await w.close();return{context:u,walletPage:d,contextPath:n}}var Iy=({slowMo:t,profileName:e,dappUrl:a}={})=>Fn.extend({workerScopeContents:[async({browser:o},n,r)=>{let{context:i,contextPath:c,walletPage:u}=await ia({workerInfo:r,profileName:e,slowMo:t});await i.grantPermissions(["clipboard-read"]);let m=new ht(u);await m.unlock(),await n({wallet:m,walletPage:u,context:i}),await A(i,c)},{scope:"worker"}],dappPage:[async({workerScopeContents:o},n)=>{let{context:r}=o,i=await r.newPage();a&&await i.goto(a),await n(i)},{scope:"worker"}],solflarePage:async({workerScopeContents:o},n)=>{await n(o.walletPage)},solflare:async({workerScopeContents:o},n)=>{let r=new ht(o.walletPage);await n(r)},autoCloseNotification:[async({workerScopeContents:o},n)=>{let r=!1,i=()=>r,c=Be(o.walletPage,i);await n(void 0),r=!0,await c.catch(u=>{console.error(`Auto close notification error: ${u.message}`)})},{auto:!0}]});export{ut as Keplr,mt as Metamask,pt as Meteor,wt as Petra,ft as Phantom,ht as Solflare,Qi as keplrFixture,pc as keplrWorkerScopeFixture,Ll as metamaskFixture,au as metamaskWorkerScopeFixture,Xm as meteorFixture,rp as meteorWorkerScopeFixture,ew as petraFixture,lw as petraWorkerScopeFixture,cg as phantomFixture,Cg as phantomWorkerScopeFixture,uy as solflareFixture,Iy as solflareWorkerScopeFixture};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tobelabs/chainwright",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "An end-to-end testing framework built on top of Playwright for Web3 wallet interactions",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -56,8 +56,6 @@
|
|
|
56
56
|
"@types/adm-zip": "^0.5.8",
|
|
57
57
|
"@types/cli-progress": "^3.11.6",
|
|
58
58
|
"@types/node": "^25.8.0",
|
|
59
|
-
"adm-zip": "^0.5.17",
|
|
60
|
-
"commander": "^14.0.3",
|
|
61
59
|
"tsup": "^8.5.1",
|
|
62
60
|
"tsx": "^4.22.0",
|
|
63
61
|
"typescript": "^6.0.3",
|
|
@@ -65,7 +63,9 @@
|
|
|
65
63
|
},
|
|
66
64
|
"dependencies": {
|
|
67
65
|
"@inquirer/checkbox": "^5.1.5",
|
|
66
|
+
"adm-zip": "^0.5.17",
|
|
68
67
|
"cli-progress": "^3.12.0",
|
|
68
|
+
"commander": "^14.0.3",
|
|
69
69
|
"glob": "^13.0.6",
|
|
70
70
|
"prool": "^0.2.4",
|
|
71
71
|
"zod": "^4.4.3"
|