Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issues with optional chaining #411

Closed
CharlieEriksen opened this issue Oct 3, 2023 · 8 comments · Fixed by #413
Closed

Issues with optional chaining #411

CharlieEriksen opened this issue Oct 3, 2023 · 8 comments · Fixed by #413
Labels

Comments

@CharlieEriksen
Copy link
Contributor

CharlieEriksen commented Oct 3, 2023

const user = {
  profile: {
    name: 'Alice',
    address: {
      city: 'Wonderland'
    }
  }
};

const city = user?.profile?.address?.city;

It doesn't seem to like this code, with the dot following the question mark. It is valid JS from what I can tell, with optional chaining being introduced in ES2020.

@lahma
Copy link
Collaborator

lahma commented Oct 3, 2023

Which version of Esprima are you using?

@CharlieEriksen
Copy link
Contributor Author

@lahma 3.0.1 :)

@lahma
Copy link
Collaborator

lahma commented Oct 3, 2023

This test case passes in main:

[Fact]
public void Testing()
{
    var parser = new JavaScriptParser();

    var input = """
                const user = {
                  profile: {
                    name: 'Alice',
                    address: {
                      city: 'Wonderland'
                    }
                  }
                };

                const city = user?.profile?.address?.city;
                """;
    parser.ParseScript(input);
}

@CharlieEriksen
Copy link
Contributor Author

Odd. Try this, though it seems to be a slightly different error from what I originally saw:

  [Fact]
public void Testing()
{
    var parser = new JavaScriptParser();

    var input = """
      INSERT BELOW CODE HERE
                """;
   var node =  parser.ParseScript(input);
   var prettyPrinted =    node.ToJavaScriptString(true);
   node =  parser.ParseScript(prettyPrinted);

}
import{c as t,a8 as e,$ as s,dQ as i,f as r,_ as o,n,t as a,s as l,x as d,g as c,e as h,i as u,ah as p}from"./shell-0889b821.js";import{I as g,F as f}from"./icon-warning-fill-42a164a9.js";import{I as b}from"./icon-checkmark-outline-652b3791.js";import"./faceplate-modal-2efaeb8b.js";import"./faceplate-bottom-sheet-a7f81009.js";import"./faceplate-radio-input-def2ab55.js";import"./faceplate-text-input-c8fb5c9d.js";import"./shreddit-slotter-067b3b4a.js";import"./faceplate-textarea-input-6f68827f.js";import"./faceplate-switch-input-4965e2b6.js";var m;!function(t){t.isSubmitError="isSubmitError",t.isRateLimitError="isRateLimitError",t.isBlockingError="isBlockingError",t.isReportBlockingSuccess="isReportBlockingSuccess",t.isReportUnblockingSuccess="isReportUnblockingSuccess"}(m||(m={}));class y{constructor(t){this.bottomScrollIntoViewIfNeeded=t=>{const e=t?.parentElement;if(e&&t){e.clientHeight-(t.offsetTop+t.clientHeight)<0&&t.scrollIntoView()}},this.getHiddenInputValue=t=>this.reportFormEl.querySelector(`faceplate-form input[type=hidden][name="${t}"]`)?.getAttribute("value")??"",this.setHiddenInputValue=(t,e)=>this.reportFormEl.querySelector(`faceplate-form input[type=hidden][name="${t}"]`)?.setAttribute("value",e)??"",this.getComputedValueByRef=t=>{if("siteRule.value"===t){const e=this.getHiddenInputValue("categoryOrRule.value");return this.getHiddenInputValue(t).includes(e)?this.getHiddenInputValue(t):""}return this.getHiddenInputValue(t)},this.checkCondition=t=>{if("object"==typeof t){const{args:e,$type:s}=t;if("computed"===s&&Array.isArray(e)){const s=e.map((t=>"object"==typeof t&&"ref"===t.$type?this.getComputedValueByRef(t.ref):t));switch(t.function){case"neq":return String(s[0])!==String(s[1]);case"eq":default:return String(s[0])===String(s[1])}}else if("ref"===s&&t.ref)return this.getHiddenInputValue(t.ref)}return!1},this.getComputedProp=t=>{if("computed"===t.$type&&"conditionalSelect"===t.function&&t.conditions&&t.values){const e=t.conditions;for(const[s,i]of e.entries())if(!0===i||"boolean"!=typeof i&&this.checkCondition(i))return t.values[s]}return t},this.getText=t=>{if(this.isString(t))return t;const e=this.getComputedProp(t);return this.isString(e)?e:""},this.getAction=t=>this.getComputedProp(t),this.getDisabledCondition=t=>!!this.checkCondition(this.getComputedProp(t)),this.getTextDataRef=t=>{const e=t.conditions?.[0];if(e&&"boolean"!=typeof e){const t=e.args;if(Array.isArray(t)&&!this.isString(t[0]))return t[0].ref}return""},this.getDisabledRef=t=>{const e=t.args;if(e&&Array.isArray(e)&&!this.isString(e[0]))return[e[0].ref];const s=t.values;return s?s.map((t=>t.args[0].ref)):void 0},this.isString=t=>"string"==typeof t,this.sanitizeTextContent=t=>{const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return t.replace(/[&<>"'/]/gi,(t=>e[t]))},this.performAction=t=>{switch(t.actionType){case"formSubmit":return{formSubmit:!0,data:t.args};case"formClose":return{formClose:!0};case"flow":return"SELF_HARM"===this.getHiddenInputValue(t.args[0].ref)?{openCtlFlow:!0}:void 0;case"openTemplatedUrl":const e=t.args,{urlTemplate:s,placeholders:i}=e;if(e&&s&&i){let t="";return i.forEach((i=>{const r=e[i],o=this.getHiddenInputValue(r.ref);o&&(t=s.replaceAll(`%(${i})s`,o))})),{href:t,formClose:!0}}return{formClose:!0};case"setState":default:const{value:r,key:o}=t.args;return"ref"===r.$type?(this.setHiddenInputValue(o,this.getHiddenInputValue(r.ref)),{key:o,value:this.getHiddenInputValue(r.ref)}):void 0}},this.reportFormEl=t}}var v;!function(t){t.Post="post",t.Comment="comment"}(v||(v={}));class S{constructor(){this.showSubmissionError=()=>window.dispatchEvent(t("report-error",{bannerType:m.isSubmitError})),this.getItemType=t=>t&&t.includes("t3_")?v.Post:v.Comment,this.onReportSubmit=async e=>{const{el:s,actionData:i}=e;if(!s||!i)return;const r=new y(s),o=t("shreddit-slotter-set-slot-name",{slotName:"formSubmitted"}),n=r?.getHiddenInputValue("thingId"),a=this.getItemType(n),{freeText:l,ruleId:d,ruleType:c}=i,h=this.reportInputGenerator(r,c,d,l?.ref??""),u=await this.getReportOperationResponse(a,n,h);return u.data?.reportPost?.ok||u.data?.reportComment?.ok?(r.setHiddenInputValue("formSubmitted","true"),s.querySelector("shreddit-slotter").dispatchEvent(o),!0):(u.errors&&this.showSubmissionError(),null)},this.onCTLReportSubmit=async t=>{const e=this.getItemType(t),s=await this.getReportOperationResponse(e,t,{fromHelpDesk:!1,siteRule:"SELF_HARM"});return!(!s.data?.reportPost?.ok&&!s.data?.reportComment?.ok)||!s.errors&&null},this.reportInputGenerator=(t,e,s,i)=>{const r={fromHelpDesk:!1},o=t.getHiddenInputValue(s.ref);switch(e){case"site":r.siteRule=o;break;case"subreddit":default:"other"===o?r.customRule=t.getHiddenInputValue("customRule.value"):r.subredditRule=t.getHiddenInputValue("subredditRule.value")}return i&&(r.freeText=t.getHiddenInputValue("freeText.value")),r},this.getReportOperationResponse=async(t,e,s)=>{let i;switch(t){case v.Post:{const t={postId:e,...s};i=await this.reportRequest(v.Post,t);break}case v.Comment:{const t={commentId:e,...s};i=await this.reportRequest(v.Comment,t);break}default:throw new Error("Unsupported item type provided")}return i},this.reportRequest=async(t,i)=>{try{let r;switch(t){case v.Post:r=await e({operation:s.ReportPost,variables:{input:i}});break;case v.Comment:r=await e({operation:s.ReportComment,variables:{input:i}});break;default:throw new Error("Unsupported item type provided")}return r}catch(t){this.showSubmissionError()}},this.blockUserRequest=async(r,o)=>{let n;try{return n=await e({operation:s.UpdateRedditorBlockState,variables:{input:{redditorId:o,blockState:r}}}),n={response:n,...r===i.None?{unblocked:!0}:{blocked:!0}},n}catch(e){return window.dispatchEvent(t("report-error",{bannerType:m.isBlockingError}))}},this.handleBlockUserState=async(e,s)=>{try{if(e){let r;r=s?await this.blockUserRequest(i.None,e):await this.blockUserRequest(i.Blocked,e);const{data:o,errors:n}=r.response,{blocked:a,unblocked:l}=r,{updateRedditorBlockState:d}=o;if(d?.ok&&l)return window.dispatchEvent(t("blocking-success",{bannerType:m.isReportUnblockingSuccess})),{unblocked:l};if(d?.ok&&a)return window.dispatchEvent(t("blocking-success",{bannerType:m.isReportBlockingSuccess})),{blocked:a};(n?.length||null===d)&&window.dispatchEvent(t("report-error",{bannerType:m.isRateLimitError}))}else window.dispatchEvent(t("report-error",{bannerType:m.isBlockingError}));return}catch(e){return void window.dispatchEvent(t("report-error",{bannerType:m.isBlockingError}))}}}}let w=class extends l{constructor(){super(...arguments),this.buttonText="Next",this.isDisabled=!0,this.href="",this.onButtonClick=()=>{const e=this.config.action,s=e?this.helpers?.getAction(e):null;if(e&&s){const e=this.helpers?.performAction(s);if("screenId"===e?.key){const s=t("shreddit-slotter-set-slot-name",{slotName:e.value}),i=this.helpers?.getHiddenInputValue("screenSequence"),r=i.split(" ");r.push(e.value),this.helpers?.setHiddenInputValue("screenSequence",r.toString()),this.getRootNode().host.dispatchEvent(s)}else if(e?.formSubmit){const t=e.data;this.gqlHelpers?.onReportSubmit({el:this.formEl,actionData:t})}else e?.formClose?this.dispatchEvent(t("close-report-modal")):e?.openCtlFlow&&this.dispatchEvent(t("open-ctl-modal"))}},this.initTemplatedUrlListener=()=>{const{action:t}=this.config;if(t&&"openTemplatedUrl"===t.actionType){const e=t.args;if(e){const s=e?.placeholders;s?.forEach((s=>{const i=e[s]?.ref;i&&this.formEl?.querySelector(`input[type=hidden][name="${i}"]`)?.addEventListener("change",(()=>{const e=this.helpers?.performAction(t);e?.href&&(this.href=e.href)}))}))}}},this.initEventListeners=()=>{const{text:t,disabled:e}=this.config;if(!this.helpers?.isString(t)){const e=this.helpers?.getTextDataRef(t);e&&this.formEl?.querySelector(`input[type=hidden][name="${e}"]`)?.addEventListener("change",(()=>{this.buttonText=this.helpers?.getText(this.config.text)??this.buttonText}))}if(e){const t=this.helpers?.getDisabledRef(e);t&&t.length&&t.forEach((t=>this.formEl?.querySelector(`input[type=hidden][name="${t}"]`)?.addEventListener("change",(async()=>{this.isDisabled=(this.config.disabled&&this.helpers?.getDisabledCondition(this.config.disabled))??this.isDisabled,await this.updateComplete,this.getRootNode()?.host?.getRootNode()?.host?.getModal().focusManager.refresh()}))))}else this.isDisabled=!1;this.initTemplatedUrlListener()}}firstUpdated(){this.initEventListeners()}connectedCallback(){super.connectedCallback();const t=this.getRootNode().host.closest("report-form");this.formEl=t,this.helpers=new y(t),this.gqlHelpers=new S,this.buttonText=this.helpers?.getText(this.config.text)??this.buttonText,this.config.disabled?this.isDisabled=this.helpers?.getDisabledCondition(this.config.disabled)??this.isDisabled:this.isDisabled=!1}render(){const t=this.href?{href:this.href,target:"_blank",rel:"noopener noreferrer"}:{};return d`\n ${c({attributes:{disabled:this.isDisabled,onclick:this.onButtonClick,className:"w-full s:w-auto",...t},children:this.buttonText})}\n `}};w.styles=[r],o([n({type:Object})],w.prototype,"config",void 0),o([a()],w.prototype,"buttonText",void 0),o([a()],w.prototype,"isDisabled",void 0),o([a()],w.prototype,"href",void 0),w=o([h("report-action")],w);const k=[{hiddenInputRef:"value",inputAttribute:"value"},{hiddenInputRef:"nextAction",inputAttribute:"data-nextaction"},{hiddenInputRef:"label",inputAttribute:"data-label"},{hiddenInputRef:"description",inputAttribute:"data-description"}];let E=class extends l{constructor(){super(),this.reasonSelectionCache={},this.getSlotter=()=>this.querySelector("shreddit-slotter")?.shadowRoot,this.getSelectedReason=()=>this.getSlotter()?.querySelector("[data-buttonbar] button.button-activated"),this.getHiddenInput=t=>this.querySelector("faceplate-form")?.querySelector(`input[type=hidden][name="${t}"]`),this.getFormElementById=t=>this.getSlotter()?.querySelector(`#${t}`),this.setHiddenInputValue=(t,e)=>{const s=this.getHiddenInput(t);s?.setAttribute("value",e??""),s?.dispatchEvent(new Event("change"))},this.getPreviousValue=t=>{if("siteRule.value"===t){const e=this.getHiddenInput("categoryOrRule.value")?.getAttribute("value")??"",s=this.reasonSelectionCache[e];this.setHiddenInputValue(t,s)}return this.getHiddenInput(t)?.getAttribute("value")},this.populateValue=async({fieldName:t,el:e,elType:s})=>{if(t){const i=this.getPreviousValue(t);if(i||""===i)switch(s){case"button":e.getAttribute("value")===i&&this.toggleReportReason(e);break;case"textDisplay":e.textContent=i,await this.updateComplete,this.helpers?.bottomScrollIntoViewIfNeeded(this.getSelectedReason());break;case"radioInput":e.getAttribute("value")===i&&e.setAttribute("checked","true");break;case"textInput":default:e.setAttribute("value",i)}}},this.toggleReportReason=t=>{const e=this.getSelectedReason();e&&(e.classList.remove("button-activated"),e.ariaChecked=null,e.removeAttribute("aria-describedby")),t.classList.add("button-activated"),t.ariaChecked="true",t.setAttribute("aria-describedby","report-footer-content-body")},this.updateHiddenInputsFromReportReason=t=>{const e=t.getAttribute("data-ref");k.forEach((({hiddenInputRef:s,inputAttribute:i})=>{this.setHiddenInputValue(`${e}.${s}`,t.getAttribute(i))}))},this.updateReasonSelectionCache=t=>{const e=this.getHiddenInput("categoryOrRule.value")?.getAttribute("value")??"";this.reasonSelectionCache={...this.reasonSelectionCache,[e]:t}},this.addReportReasonListeners=()=>{const t=this.getSlotter()?.querySelectorAll("[data-buttonbar] button");t?.length&&t.forEach((t=>{const e=t.getAttribute("data-ref");this.populateValue({fieldName:`${e}.value`,el:t,elType:"button"}),t.addEventListener("click",(t=>{t.preventDefault(),t.currentTarget instanceof Element&&(this.toggleReportReason(t.currentTarget),this.updateHiddenInputsFromReportReason(t.currentTarget))}))}))},this.addFooterListener=(t,e)=>{const s=this.getFormElementById(t),i=s?.getAttribute(e);s&&i&&(this.populateValue({fieldName:s.getAttribute(e),el:s,elType:"textDisplay"}),this.getHiddenInput(i)?.addEventListener("change",(async t=>{t.currentTarget instanceof Element&&(s.textContent=t.currentTarget.getAttribute("value")??"",await this.updateComplete,this.helpers?.bottomScrollIntoViewIfNeeded(this.getSelectedReason()))})))},this.addReasonFooterContentListeners=()=>{this.addFooterListener("report-footer-content-title","data-title-ref"),this.addFooterListener("report-footer-content-body","data-text-ref")},this.addRadioListeners=()=>{const t=this.getSlotter()?.querySelectorAll("faceplate-radio-input");t?.length&&t?.forEach((t=>{this.populateValue({fieldName:`${t.getAttribute("name")}.value`,el:t,elType:"radioInput"}),t.addEventListener("input",(t=>{if(t.currentTarget instanceof Element){const e=t.currentTarget.getAttribute("name"),s=t.currentTarget.getAttribute("value");this.setHiddenInputValue(`${e}.value`,s),this.updateReasonSelectionCache(s??"")}}))}))},this.showTextInput=t=>{t.classList.remove("hidden"),this.querySelector("shreddit-slotter")?.shadowRoot?.querySelector('faceplate-radio-input[name="subredditRule"][value="other"]')?.scrollIntoView()},this.addTextInputListeners=()=>{const t=this.getSlotter()?.querySelectorAll("faceplate-textarea-input");t?.length&&t.forEach((t=>{const e=t.getAttribute("data-visibility-ref"),s=t.getAttribute("data-visibility-check");this.populateValue({fieldName:t.name,el:t,elType:"textInput"});if(e&&s){const i=this.getHiddenInput(e);i?.getAttribute("value")===s&&this.showTextInput(t),i?.addEventListener("change",(e=>{e.currentTarget.getAttribute("value")===s?this.showTextInput(t):t.classList.contains("hidden")||t.classList.add("hidden")}))}t.shadowRoot?.querySelector("textarea")?.addEventListener("keyup",(t=>{const e=t.currentTarget.getAttribute("name"),s=t.currentTarget.value;e&&s&&this.setHiddenInputValue(e,this.helpers?.sanitizeTextContent(s))}))}))},this.addUserBlockSwitchListener=()=>{const t=this.getSlotter()?.querySelector("faceplate-switch-input");t&&(this.isAuthorBlocked=void 0!==this.isAuthorBlocked&&this.isAuthorBlocked,this.isAuthorBlocked?t.checked=!0:t.checked=!1,t?.addEventListener("input",(async()=>{const t=await(this.gqlHelpers?.handleBlockUserState(this.authorId,this.isAuthorBlocked));t?.blocked?this.isAuthorBlocked=!0:t?.unblocked&&(this.isAuthorBlocked=!1)})))},this.addInteractionListeners=()=>{this.addReportReasonListeners(),this.addReasonFooterContentListeners(),this.addRadioListeners(),this.addTextInputListeners(),this.addUserBlockSwitchListener()},this.addStepChangeListener=()=>{const t=this.querySelector("shreddit-slotter");t?.addEventListener("shreddit-slotter-set-slot-name",(async()=>{await t.updateComplete,this.addInteractionListeners()}))},this.initEventListeners=t=>{"report/view/reportform"===t.SAN&&(this.addInteractionListeners(),this.addStepChangeListener())},this.helpers=new y(this),this.gqlHelpers=new S,this.addEventListener("faceplate-track",this.initEventListeners)}connectedCallback(){super.connectedCallback(),this.showError&&this.dispatchEvent(t("report-error")),this.updateComplete.then((()=>{this.dispatchEvent(t("report-form-rendered"))}))}render(){return d` <slot></slot>`}};E.styles=[u`:host{display:block;width:100%}`,r],o([n({type:Boolean,attribute:"show-error"})],E.prototype,"showError",void 0),o([n({type:String,attribute:"author-id"})],E.prototype,"authorId",void 0),o([n({type:Boolean,attribute:"is-author-blocked"})],E.prototype,"isAuthorBlocked",void 0),E=o([h("report-form")],E);let L=class extends l{constructor(){super(),this.thingId="",this.authorName="",this.authorId="",this.isAuthorBlocked=!1,this.isOpen=!1,this.showError=!1,this.showSuccess=!1,this.partialSrc="/svc/shreddit/report-flow/",this.errorMessage="",this.successMessage="",this.getModal=()=>this.isDesktop?this.shadowRoot?.querySelector("faceplate-modal"):this.shadowRoot?.querySelector("faceplate-bottom-sheet"),this.initModalCloseListener=()=>{this.getModal()?.querySelector("#report-modal-close")?.addEventListener("click",this.onCloseModal)},this.initReportFlow=()=>{this.initFlowSlotterListener()},this.dispatchCloseReportFlowEvent=()=>{this.dispatchEvent(t("report-flow-close"))},this.onCloseModal=()=>{this.getModal()?.close(),this.dispatchCloseReportFlowEvent()},this.addBaseSlotterListener=()=>{const t=this.getModal()?.querySelector("shreddit-slotter");t?.addEventListener("shreddit-slotter-set-slot-name",(async()=>{await t.updateComplete,this.getModal()?.focusManager.refresh(),this.getModal()?.focusManager.focusFirst()}))},this.initFlowSlotterListener=()=>{this.addEventListener("shreddit-slotter-set-slot-name",(()=>{this.renderBackButton(),this.updateModalTitle()}))},this.initModal=()=>{this.getModal()?.showModal(),this.initModalCloseListener(),this.initEscapeListener(),this.initModalBackButtonListener(),this.addBaseSlotterListener()},this.getInputValue=t=>this.getModal()?.querySelector("report-form")?.querySelector(`faceplate-form input[type=hidden][name="${t}"]`)?.getAttribute("value"),this.setInputValue=(t,e)=>this.getModal()?.querySelector("report-form")?.querySelector(`faceplate-form input[type=hidden][name="${t}"]`)?.setAttribute("value",e),this.onBackButtonClick=()=>{const e=this.getInputValue("screenSequence").split(","),s=e.slice(0,e.length);s.pop(),this.setInputValue("screenSequence",s.toString());const i=t("shreddit-slotter-set-slot-name",{slotName:s[s.length-1]});this.shadowRoot.querySelector("shreddit-slotter").dispatchEvent(i)},this.renderBackButton=()=>{const t=this.getModal()?.querySelector("#report-modal-back");if(t){const e=this.getInputValue("formSubmitted");this.getInputValue("screenSequence").split(",").length>1&&"false"===e?(t?.classList.remove("hidden"),t.disabled=!1):(t?.classList.add("hidden"),t.disabled=!0)}},this.updateModalTitle=async()=>{await this.updateComplete;"true"===this.getInputValue("formSubmitted")&&(this.getModal()?.querySelector(".header-title")?.classList.add("hidden"),this.getModal()?.querySelector(".report-success-title")?.classList.remove("hidden"))},this.initModalBackButtonListener=()=>{this.getModal()?.querySelector("#report-modal-back")?.addEventListener("click",this.onBackButtonClick)},this.initEscapeListener=()=>{document.addEventListener("keydown",(t=>{if("Escape"===t.key){const t=this.getModal(),e=this.getCTLModal();""===t?.getAttribute("open")&&this.onCloseModal(),""===e?.getAttribute("open")&&this.onCloseCTLModal(),this.dispatchCloseReportFlowEvent()}}))},this.onCloseCTLModal=()=>{this.getCTLModal()?.close(),this.dispatchCloseReportFlowEvent()},this.addCTLSlotterListener=()=>{const t=this.getCTLModal()?.querySelector("shreddit-slotter");t?.addEventListener("shreddit-slotter-set-slot-name",(async()=>{await t.updateComplete,this.getCTLModal()?.focusManager.refresh(),this.getCTLModal()?.focusManager.focusFirst();const e=this.getCTLModal()?.querySelector("shreddit-slotter")?.shadowRoot?.querySelector("#ctl-ok-button");e?.addEventListener("click",this.onCloseCTLModal)}))},this.getCTLModal=()=>this.shadowRoot?.querySelector("#ctl-modal"),this.initCTLModalCloseListener=()=>{this.getCTLModal()?.querySelector("#ctl-modal-close")?.addEventListener("click",this.onCloseCTLModal)},this.initCTLModal=async()=>{this.getModal()?.close(),this.getCTLModal()?.showModal(),this.initCTLModalCloseListener()},this.showThankYou=()=>{const e=t("shreddit-slotter-set-slot-name",{slotName:"thankyou"});this.getCTLModal()?.querySelector("shreddit-slotter")?.dispatchEvent(e)},this.submitCTLReport=async()=>{await(this.gqlHelpers?.onCTLReportSubmit(this.thingId))?this.showThankYou():this.showErrorBanner(t("report-error",{isSubmitError:!0}))},this.initCTLListeners=t=>{if("report/view/ctl"===t.SAN){const t=this.getCTLModal()?.querySelector("shreddit-slotter")?.shadowRoot?.querySelector("#ctl-yes-button");t?.addEventListener("click",this.submitCTLReport),this.getCTLModal()?.focusManager.refresh(),this.getCTLModal()?.focusManager.focusFirst(),this.addCTLSlotterListener()}},this.getMessageByType=t=>{switch(t){case m.isSubmitError:return"An error occurred while submitting your report. Wait a bit, and try again.";case m.isRateLimitError:return`You can't block ${this.authorName} for 24 hours after unblocking them`;case m.isBlockingError:return"An error has occurred. Please try again later.";case m.isReportBlockingSuccess:return`${this.authorName} is now blocked.`;case m.isReportUnblockingSuccess:return`${this.authorName} is now unblocked.`;default:return"Reporting is currently unavailable. Try reloading the page or waiting a few minutes, before trying again."}},this.showErrorBanner=t=>{const e=t.detail?.bannerType;this.errorMessage=this.getMessageByType(e),e||this.dispatchCloseReportFlowEvent(),this.showError=!0},this.showBlockingSuccessBanner=t=>{const e=t.detail?.bannerType;this.successMessage=this.getMessageByType(e),this.showSuccess=!0},this.closeBanner=()=>{this.showError=!1,this.showSuccess=!1},this.gqlHelpers=new S,window.addEventListener("report-error",this.showErrorBanner),window.addEventListener("blocking-success",this.showBlockingSuccessBanner),this.addEventListener("report-form-rendered",this.initModal),this.addEventListener("faceplate-track",this.initCTLListeners),this.addEventListener("close-report-modal",this.onCloseModal),this.addEventListener("open-ctl-modal",this.initCTLModal)}static get styles(){return[u`:host>faceplate-banner{display:flex;flex-direction:column;gap:var(--spacer-md);align-items:center;position:fixed;left:50%;transform:translateX(-50%);padding:0 1rem;bottom:var(--rem16);width:calc(100% - 2rem)}`,r]}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener("report-error",this.showErrorBanner),window.removeEventListener("blocking-success",this.showBlockingSuccessBanner)}updated(t){super.updated(t),t.has("isOpen")&&this.isOpen&&this.initReportFlow()}render(){const t=this.isOpen?d`<faceplate-partial \n src="${this.partialSrc}${this.thingId}/${this.isDesktop?"is-desktop":"is-not-desktop"}/${this.authorName}/${this.authorId}/${this.isAuthorBlocked?"author-is-blocked":"author-is-not-blocked"}" \n></faceplate-partial>`:p;return d`\n <div>${t}</div>\n ${this.showError?d`<faceplate-banner \n class="z-[5] pointer-events-auto" \n appearance="error" \n shape="rounded" \n msg="${this.errorMessage}" \n aria-live="polite" \n dismissible\n><div slot="leadingIcon">${g()}</div>\n <span slot="closeButton">\n ${f.getCloseButton("error",{"aria-label":"close error button",onclick:this.closeBanner})}\n </span>\n </faceplate-banner>`:p}\n ${this.showSuccess?d`<faceplate-banner \n class="z-[5] pointer-events-auto" \n appearance="success" \n shape="rounded" \n msg="${this.successMessage}" \n aria-live="polite" \n dismissible\n><div slot="leadingIcon">${b()}</div>\n <span slot="closeButton">\n ${f.getCloseButton("success",{"aria-label":"button to close success banner",onclick:this.closeBanner})}\n </span>\n </faceplate-banner>`:p}\n `}};o([n({type:Boolean,attribute:"is-desktop"})],L.prototype,"isDesktop",void 0),o([n({type:String,attribute:"thing-id"})],L.prototype,"thingId",void 0),o([n({type:String,attribute:"author-name"})],L.prototype,"authorName",void 0),o([n({type:String,attribute:"author-id"})],L.prototype,"authorId",void 0),o([n({type:Boolean,attribute:"is-author-blocked"})],L.prototype,"isAuthorBlocked",void 0),o([n({type:Boolean,attribute:"is-open"})],L.prototype,"isOpen",void 0),o([a()],L.prototype,"showError",void 0),o([a()],L.prototype,"showSuccess",void 0),L=o([h("report-flow")],L);export{m as R,L as a};
//# sourceMappingURL=report-flow-d910001d.js.map

@lahma
Copy link
Collaborator

lahma commented Oct 3, 2023

Because that's module code (it has import), you need to call ParseModule instead of ParseScript.

@CharlieEriksen
Copy link
Contributor Author

Oh yeah, that's just me being lazy.

  [Fact]
    public void Testing()
    {
        var parser = new JavaScriptParser();

        var input = """
                    import{c as t,a8 as e,$ as s,dQ as i,f as r,_ as o,n,t as a,s as l,x as d,g as c,e as h,i as u,ah as p}from"./shell-0889b821.js";import{I as g,F as f}from"./icon-warning-fill-42a164a9.js";import{I as b}from"./icon-checkmark-outline-652b3791.js";import"./faceplate-modal-2efaeb8b.js";import"./faceplate-bottom-sheet-a7f81009.js";import"./faceplate-radio-input-def2ab55.js";import"./faceplate-text-input-c8fb5c9d.js";import"./shreddit-slotter-067b3b4a.js";import"./faceplate-textarea-input-6f68827f.js";import"./faceplate-switch-input-4965e2b6.js";var m;!function(t){t.isSubmitError="isSubmitError",t.isRateLimitError="isRateLimitError",t.isBlockingError="isBlockingError",t.isReportBlockingSuccess="isReportBlockingSuccess",t.isReportUnblockingSuccess="isReportUnblockingSuccess"}(m||(m={}));class y{constructor(t){this.bottomScrollIntoViewIfNeeded=t=>{const e=t?.parentElement;if(e&&t){e.clientHeight-(t.offsetTop+t.clientHeight)<0&&t.scrollIntoView()}},this.getHiddenInputValue=t=>this.reportFormEl.querySelector(`faceplate-form input[type=hidden][name="${t}"]`)?.getAttribute("value")??"",this.setHiddenInputValue=(t,e)=>this.reportFormEl.querySelector(`faceplate-form input[type=hidden][name="${t}"]`)?.setAttribute("value",e)??"",this.getComputedValueByRef=t=>{if("siteRule.value"===t){const e=this.getHiddenInputValue("categoryOrRule.value");return this.getHiddenInputValue(t).includes(e)?this.getHiddenInputValue(t):""}return this.getHiddenInputValue(t)},this.checkCondition=t=>{if("object"==typeof t){const{args:e,$type:s}=t;if("computed"===s&&Array.isArray(e)){const s=e.map((t=>"object"==typeof t&&"ref"===t.$type?this.getComputedValueByRef(t.ref):t));switch(t.function){case"neq":return String(s[0])!==String(s[1]);case"eq":default:return String(s[0])===String(s[1])}}else if("ref"===s&&t.ref)return this.getHiddenInputValue(t.ref)}return!1},this.getComputedProp=t=>{if("computed"===t.$type&&"conditionalSelect"===t.function&&t.conditions&&t.values){const e=t.conditions;for(const[s,i]of e.entries())if(!0===i||"boolean"!=typeof i&&this.checkCondition(i))return t.values[s]}return t},this.getText=t=>{if(this.isString(t))return t;const e=this.getComputedProp(t);return this.isString(e)?e:""},this.getAction=t=>this.getComputedProp(t),this.getDisabledCondition=t=>!!this.checkCondition(this.getComputedProp(t)),this.getTextDataRef=t=>{const e=t.conditions?.[0];if(e&&"boolean"!=typeof e){const t=e.args;if(Array.isArray(t)&&!this.isString(t[0]))return t[0].ref}return""},this.getDisabledRef=t=>{const e=t.args;if(e&&Array.isArray(e)&&!this.isString(e[0]))return[e[0].ref];const s=t.values;return s?s.map((t=>t.args[0].ref)):void 0},this.isString=t=>"string"==typeof t,this.sanitizeTextContent=t=>{const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return t.replace(/[&<>"'/]/gi,(t=>e[t]))},this.performAction=t=>{switch(t.actionType){case"formSubmit":return{formSubmit:!0,data:t.args};case"formClose":return{formClose:!0};case"flow":return"SELF_HARM"===this.getHiddenInputValue(t.args[0].ref)?{openCtlFlow:!0}:void 0;case"openTemplatedUrl":const e=t.args,{urlTemplate:s,placeholders:i}=e;if(e&&s&&i){let t="";return i.forEach((i=>{const r=e[i],o=this.getHiddenInputValue(r.ref);o&&(t=s.replaceAll(`%(${i})s`,o))})),{href:t,formClose:!0}}return{formClose:!0};case"setState":default:const{value:r,key:o}=t.args;return"ref"===r.$type?(this.setHiddenInputValue(o,this.getHiddenInputValue(r.ref)),{key:o,value:this.getHiddenInputValue(r.ref)}):void 0}},this.reportFormEl=t}}var v;!function(t){t.Post="post",t.Comment="comment"}(v||(v={}));class S{constructor(){this.showSubmissionError=()=>window.dispatchEvent(t("report-error",{bannerType:m.isSubmitError})),this.getItemType=t=>t&&t.includes("t3_")?v.Post:v.Comment,this.onReportSubmit=async e=>{const{el:s,actionData:i}=e;if(!s||!i)return;const r=new y(s),o=t("shreddit-slotter-set-slot-name",{slotName:"formSubmitted"}),n=r?.getHiddenInputValue("thingId"),a=this.getItemType(n),{freeText:l,ruleId:d,ruleType:c}=i,h=this.reportInputGenerator(r,c,d,l?.ref??""),u=await this.getReportOperationResponse(a,n,h);return u.data?.reportPost?.ok||u.data?.reportComment?.ok?(r.setHiddenInputValue("formSubmitted","true"),s.querySelector("shreddit-slotter").dispatchEvent(o),!0):(u.errors&&this.showSubmissionError(),null)},this.onCTLReportSubmit=async t=>{const e=this.getItemType(t),s=await this.getReportOperationResponse(e,t,{fromHelpDesk:!1,siteRule:"SELF_HARM"});return!(!s.data?.reportPost?.ok&&!s.data?.reportComment?.ok)||!s.errors&&null},this.reportInputGenerator=(t,e,s,i)=>{const r={fromHelpDesk:!1},o=t.getHiddenInputValue(s.ref);switch(e){case"site":r.siteRule=o;break;case"subreddit":default:"other"===o?r.customRule=t.getHiddenInputValue("customRule.value"):r.subredditRule=t.getHiddenInputValue("subredditRule.value")}return i&&(r.freeText=t.getHiddenInputValue("freeText.value")),r},this.getReportOperationResponse=async(t,e,s)=>{let i;switch(t){case v.Post:{const t={postId:e,...s};i=await this.reportRequest(v.Post,t);break}case v.Comment:{const t={commentId:e,...s};i=await this.reportRequest(v.Comment,t);break}default:throw new Error("Unsupported item type provided")}return i},this.reportRequest=async(t,i)=>{try{let r;switch(t){case v.Post:r=await e({operation:s.ReportPost,variables:{input:i}});break;case v.Comment:r=await e({operation:s.ReportComment,variables:{input:i}});break;default:throw new Error("Unsupported item type provided")}return r}catch(t){this.showSubmissionError()}},this.blockUserRequest=async(r,o)=>{let n;try{return n=await e({operation:s.UpdateRedditorBlockState,variables:{input:{redditorId:o,blockState:r}}}),n={response:n,...r===i.None?{unblocked:!0}:{blocked:!0}},n}catch(e){return window.dispatchEvent(t("report-error",{bannerType:m.isBlockingError}))}},this.handleBlockUserState=async(e,s)=>{try{if(e){let r;r=s?await this.blockUserRequest(i.None,e):await this.blockUserRequest(i.Blocked,e);const{data:o,errors:n}=r.response,{blocked:a,unblocked:l}=r,{updateRedditorBlockState:d}=o;if(d?.ok&&l)return window.dispatchEvent(t("blocking-success",{bannerType:m.isReportUnblockingSuccess})),{unblocked:l};if(d?.ok&&a)return window.dispatchEvent(t("blocking-success",{bannerType:m.isReportBlockingSuccess})),{blocked:a};(n?.length||null===d)&&window.dispatchEvent(t("report-error",{bannerType:m.isRateLimitError}))}else window.dispatchEvent(t("report-error",{bannerType:m.isBlockingError}));return}catch(e){return void window.dispatchEvent(t("report-error",{bannerType:m.isBlockingError}))}}}}let w=class extends l{constructor(){super(...arguments),this.buttonText="Next",this.isDisabled=!0,this.href="",this.onButtonClick=()=>{const e=this.config.action,s=e?this.helpers?.getAction(e):null;if(e&&s){const e=this.helpers?.performAction(s);if("screenId"===e?.key){const s=t("shreddit-slotter-set-slot-name",{slotName:e.value}),i=this.helpers?.getHiddenInputValue("screenSequence"),r=i.split(" ");r.push(e.value),this.helpers?.setHiddenInputValue("screenSequence",r.toString()),this.getRootNode().host.dispatchEvent(s)}else if(e?.formSubmit){const t=e.data;this.gqlHelpers?.onReportSubmit({el:this.formEl,actionData:t})}else e?.formClose?this.dispatchEvent(t("close-report-modal")):e?.openCtlFlow&&this.dispatchEvent(t("open-ctl-modal"))}},this.initTemplatedUrlListener=()=>{const{action:t}=this.config;if(t&&"openTemplatedUrl"===t.actionType){const e=t.args;if(e){const s=e?.placeholders;s?.forEach((s=>{const i=e[s]?.ref;i&&this.formEl?.querySelector(`input[type=hidden][name="${i}"]`)?.addEventListener("change",(()=>{const e=this.helpers?.performAction(t);e?.href&&(this.href=e.href)}))}))}}},this.initEventListeners=()=>{const{text:t,disabled:e}=this.config;if(!this.helpers?.isString(t)){const e=this.helpers?.getTextDataRef(t);e&&this.formEl?.querySelector(`input[type=hidden][name="${e}"]`)?.addEventListener("change",(()=>{this.buttonText=this.helpers?.getText(this.config.text)??this.buttonText}))}if(e){const t=this.helpers?.getDisabledRef(e);t&&t.length&&t.forEach((t=>this.formEl?.querySelector(`input[type=hidden][name="${t}"]`)?.addEventListener("change",(async()=>{this.isDisabled=(this.config.disabled&&this.helpers?.getDisabledCondition(this.config.disabled))??this.isDisabled,await this.updateComplete,this.getRootNode()?.host?.getRootNode()?.host?.getModal().focusManager.refresh()}))))}else this.isDisabled=!1;this.initTemplatedUrlListener()}}firstUpdated(){this.initEventListeners()}connectedCallback(){super.connectedCallback();const t=this.getRootNode().host.closest("report-form");this.formEl=t,this.helpers=new y(t),this.gqlHelpers=new S,this.buttonText=this.helpers?.getText(this.config.text)??this.buttonText,this.config.disabled?this.isDisabled=this.helpers?.getDisabledCondition(this.config.disabled)??this.isDisabled:this.isDisabled=!1}render(){const t=this.href?{href:this.href,target:"_blank",rel:"noopener noreferrer"}:{};return d`\n ${c({attributes:{disabled:this.isDisabled,onclick:this.onButtonClick,className:"w-full s:w-auto",...t},children:this.buttonText})}\n `}};w.styles=[r],o([n({type:Object})],w.prototype,"config",void 0),o([a()],w.prototype,"buttonText",void 0),o([a()],w.prototype,"isDisabled",void 0),o([a()],w.prototype,"href",void 0),w=o([h("report-action")],w);const k=[{hiddenInputRef:"value",inputAttribute:"value"},{hiddenInputRef:"nextAction",inputAttribute:"data-nextaction"},{hiddenInputRef:"label",inputAttribute:"data-label"},{hiddenInputRef:"description",inputAttribute:"data-description"}];let E=class extends l{constructor(){super(),this.reasonSelectionCache={},this.getSlotter=()=>this.querySelector("shreddit-slotter")?.shadowRoot,this.getSelectedReason=()=>this.getSlotter()?.querySelector("[data-buttonbar] button.button-activated"),this.getHiddenInput=t=>this.querySelector("faceplate-form")?.querySelector(`input[type=hidden][name="${t}"]`),this.getFormElementById=t=>this.getSlotter()?.querySelector(`#${t}`),this.setHiddenInputValue=(t,e)=>{const s=this.getHiddenInput(t);s?.setAttribute("value",e??""),s?.dispatchEvent(new Event("change"))},this.getPreviousValue=t=>{if("siteRule.value"===t){const e=this.getHiddenInput("categoryOrRule.value")?.getAttribute("value")??"",s=this.reasonSelectionCache[e];this.setHiddenInputValue(t,s)}return this.getHiddenInput(t)?.getAttribute("value")},this.populateValue=async({fieldName:t,el:e,elType:s})=>{if(t){const i=this.getPreviousValue(t);if(i||""===i)switch(s){case"button":e.getAttribute("value")===i&&this.toggleReportReason(e);break;case"textDisplay":e.textContent=i,await this.updateComplete,this.helpers?.bottomScrollIntoViewIfNeeded(this.getSelectedReason());break;case"radioInput":e.getAttribute("value")===i&&e.setAttribute("checked","true");break;case"textInput":default:e.setAttribute("value",i)}}},this.toggleReportReason=t=>{const e=this.getSelectedReason();e&&(e.classList.remove("button-activated"),e.ariaChecked=null,e.removeAttribute("aria-describedby")),t.classList.add("button-activated"),t.ariaChecked="true",t.setAttribute("aria-describedby","report-footer-content-body")},this.updateHiddenInputsFromReportReason=t=>{const e=t.getAttribute("data-ref");k.forEach((({hiddenInputRef:s,inputAttribute:i})=>{this.setHiddenInputValue(`${e}.${s}`,t.getAttribute(i))}))},this.updateReasonSelectionCache=t=>{const e=this.getHiddenInput("categoryOrRule.value")?.getAttribute("value")??"";this.reasonSelectionCache={...this.reasonSelectionCache,[e]:t}},this.addReportReasonListeners=()=>{const t=this.getSlotter()?.querySelectorAll("[data-buttonbar] button");t?.length&&t.forEach((t=>{const e=t.getAttribute("data-ref");this.populateValue({fieldName:`${e}.value`,el:t,elType:"button"}),t.addEventListener("click",(t=>{t.preventDefault(),t.currentTarget instanceof Element&&(this.toggleReportReason(t.currentTarget),this.updateHiddenInputsFromReportReason(t.currentTarget))}))}))},this.addFooterListener=(t,e)=>{const s=this.getFormElementById(t),i=s?.getAttribute(e);s&&i&&(this.populateValue({fieldName:s.getAttribute(e),el:s,elType:"textDisplay"}),this.getHiddenInput(i)?.addEventListener("change",(async t=>{t.currentTarget instanceof Element&&(s.textContent=t.currentTarget.getAttribute("value")??"",await this.updateComplete,this.helpers?.bottomScrollIntoViewIfNeeded(this.getSelectedReason()))})))},this.addReasonFooterContentListeners=()=>{this.addFooterListener("report-footer-content-title","data-title-ref"),this.addFooterListener("report-footer-content-body","data-text-ref")},this.addRadioListeners=()=>{const t=this.getSlotter()?.querySelectorAll("faceplate-radio-input");t?.length&&t?.forEach((t=>{this.populateValue({fieldName:`${t.getAttribute("name")}.value`,el:t,elType:"radioInput"}),t.addEventListener("input",(t=>{if(t.currentTarget instanceof Element){const e=t.currentTarget.getAttribute("name"),s=t.currentTarget.getAttribute("value");this.setHiddenInputValue(`${e}.value`,s),this.updateReasonSelectionCache(s??"")}}))}))},this.showTextInput=t=>{t.classList.remove("hidden"),this.querySelector("shreddit-slotter")?.shadowRoot?.querySelector('faceplate-radio-input[name="subredditRule"][value="other"]')?.scrollIntoView()},this.addTextInputListeners=()=>{const t=this.getSlotter()?.querySelectorAll("faceplate-textarea-input");t?.length&&t.forEach((t=>{const e=t.getAttribute("data-visibility-ref"),s=t.getAttribute("data-visibility-check");this.populateValue({fieldName:t.name,el:t,elType:"textInput"});if(e&&s){const i=this.getHiddenInput(e);i?.getAttribute("value")===s&&this.showTextInput(t),i?.addEventListener("change",(e=>{e.currentTarget.getAttribute("value")===s?this.showTextInput(t):t.classList.contains("hidden")||t.classList.add("hidden")}))}t.shadowRoot?.querySelector("textarea")?.addEventListener("keyup",(t=>{const e=t.currentTarget.getAttribute("name"),s=t.currentTarget.value;e&&s&&this.setHiddenInputValue(e,this.helpers?.sanitizeTextContent(s))}))}))},this.addUserBlockSwitchListener=()=>{const t=this.getSlotter()?.querySelector("faceplate-switch-input");t&&(this.isAuthorBlocked=void 0!==this.isAuthorBlocked&&this.isAuthorBlocked,this.isAuthorBlocked?t.checked=!0:t.checked=!1,t?.addEventListener("input",(async()=>{const t=await(this.gqlHelpers?.handleBlockUserState(this.authorId,this.isAuthorBlocked));t?.blocked?this.isAuthorBlocked=!0:t?.unblocked&&(this.isAuthorBlocked=!1)})))},this.addInteractionListeners=()=>{this.addReportReasonListeners(),this.addReasonFooterContentListeners(),this.addRadioListeners(),this.addTextInputListeners(),this.addUserBlockSwitchListener()},this.addStepChangeListener=()=>{const t=this.querySelector("shreddit-slotter");t?.addEventListener("shreddit-slotter-set-slot-name",(async()=>{await t.updateComplete,this.addInteractionListeners()}))},this.initEventListeners=t=>{"report/view/reportform"===t.SAN&&(this.addInteractionListeners(),this.addStepChangeListener())},this.helpers=new y(this),this.gqlHelpers=new S,this.addEventListener("faceplate-track",this.initEventListeners)}connectedCallback(){super.connectedCallback(),this.showError&&this.dispatchEvent(t("report-error")),this.updateComplete.then((()=>{this.dispatchEvent(t("report-form-rendered"))}))}render(){return d` <slot></slot>`}};E.styles=[u`:host{display:block;width:100%}`,r],o([n({type:Boolean,attribute:"show-error"})],E.prototype,"showError",void 0),o([n({type:String,attribute:"author-id"})],E.prototype,"authorId",void 0),o([n({type:Boolean,attribute:"is-author-blocked"})],E.prototype,"isAuthorBlocked",void 0),E=o([h("report-form")],E);let L=class extends l{constructor(){super(),this.thingId="",this.authorName="",this.authorId="",this.isAuthorBlocked=!1,this.isOpen=!1,this.showError=!1,this.showSuccess=!1,this.partialSrc="/svc/shreddit/report-flow/",this.errorMessage="",this.successMessage="",this.getModal=()=>this.isDesktop?this.shadowRoot?.querySelector("faceplate-modal"):this.shadowRoot?.querySelector("faceplate-bottom-sheet"),this.initModalCloseListener=()=>{this.getModal()?.querySelector("#report-modal-close")?.addEventListener("click",this.onCloseModal)},this.initReportFlow=()=>{this.initFlowSlotterListener()},this.dispatchCloseReportFlowEvent=()=>{this.dispatchEvent(t("report-flow-close"))},this.onCloseModal=()=>{this.getModal()?.close(),this.dispatchCloseReportFlowEvent()},this.addBaseSlotterListener=()=>{const t=this.getModal()?.querySelector("shreddit-slotter");t?.addEventListener("shreddit-slotter-set-slot-name",(async()=>{await t.updateComplete,this.getModal()?.focusManager.refresh(),this.getModal()?.focusManager.focusFirst()}))},this.initFlowSlotterListener=()=>{this.addEventListener("shreddit-slotter-set-slot-name",(()=>{this.renderBackButton(),this.updateModalTitle()}))},this.initModal=()=>{this.getModal()?.showModal(),this.initModalCloseListener(),this.initEscapeListener(),this.initModalBackButtonListener(),this.addBaseSlotterListener()},this.getInputValue=t=>this.getModal()?.querySelector("report-form")?.querySelector(`faceplate-form input[type=hidden][name="${t}"]`)?.getAttribute("value"),this.setInputValue=(t,e)=>this.getModal()?.querySelector("report-form")?.querySelector(`faceplate-form input[type=hidden][name="${t}"]`)?.setAttribute("value",e),this.onBackButtonClick=()=>{const e=this.getInputValue("screenSequence").split(","),s=e.slice(0,e.length);s.pop(),this.setInputValue("screenSequence",s.toString());const i=t("shreddit-slotter-set-slot-name",{slotName:s[s.length-1]});this.shadowRoot.querySelector("shreddit-slotter").dispatchEvent(i)},this.renderBackButton=()=>{const t=this.getModal()?.querySelector("#report-modal-back");if(t){const e=this.getInputValue("formSubmitted");this.getInputValue("screenSequence").split(",").length>1&&"false"===e?(t?.classList.remove("hidden"),t.disabled=!1):(t?.classList.add("hidden"),t.disabled=!0)}},this.updateModalTitle=async()=>{await this.updateComplete;"true"===this.getInputValue("formSubmitted")&&(this.getModal()?.querySelector(".header-title")?.classList.add("hidden"),this.getModal()?.querySelector(".report-success-title")?.classList.remove("hidden"))},this.initModalBackButtonListener=()=>{this.getModal()?.querySelector("#report-modal-back")?.addEventListener("click",this.onBackButtonClick)},this.initEscapeListener=()=>{document.addEventListener("keydown",(t=>{if("Escape"===t.key){const t=this.getModal(),e=this.getCTLModal();""===t?.getAttribute("open")&&this.onCloseModal(),""===e?.getAttribute("open")&&this.onCloseCTLModal(),this.dispatchCloseReportFlowEvent()}}))},this.onCloseCTLModal=()=>{this.getCTLModal()?.close(),this.dispatchCloseReportFlowEvent()},this.addCTLSlotterListener=()=>{const t=this.getCTLModal()?.querySelector("shreddit-slotter");t?.addEventListener("shreddit-slotter-set-slot-name",(async()=>{await t.updateComplete,this.getCTLModal()?.focusManager.refresh(),this.getCTLModal()?.focusManager.focusFirst();const e=this.getCTLModal()?.querySelector("shreddit-slotter")?.shadowRoot?.querySelector("#ctl-ok-button");e?.addEventListener("click",this.onCloseCTLModal)}))},this.getCTLModal=()=>this.shadowRoot?.querySelector("#ctl-modal"),this.initCTLModalCloseListener=()=>{this.getCTLModal()?.querySelector("#ctl-modal-close")?.addEventListener("click",this.onCloseCTLModal)},this.initCTLModal=async()=>{this.getModal()?.close(),this.getCTLModal()?.showModal(),this.initCTLModalCloseListener()},this.showThankYou=()=>{const e=t("shreddit-slotter-set-slot-name",{slotName:"thankyou"});this.getCTLModal()?.querySelector("shreddit-slotter")?.dispatchEvent(e)},this.submitCTLReport=async()=>{await(this.gqlHelpers?.onCTLReportSubmit(this.thingId))?this.showThankYou():this.showErrorBanner(t("report-error",{isSubmitError:!0}))},this.initCTLListeners=t=>{if("report/view/ctl"===t.SAN){const t=this.getCTLModal()?.querySelector("shreddit-slotter")?.shadowRoot?.querySelector("#ctl-yes-button");t?.addEventListener("click",this.submitCTLReport),this.getCTLModal()?.focusManager.refresh(),this.getCTLModal()?.focusManager.focusFirst(),this.addCTLSlotterListener()}},this.getMessageByType=t=>{switch(t){case m.isSubmitError:return"An error occurred while submitting your report. Wait a bit, and try again.";case m.isRateLimitError:return`You can't block ${this.authorName} for 24 hours after unblocking them`;case m.isBlockingError:return"An error has occurred. Please try again later.";case m.isReportBlockingSuccess:return`${this.authorName} is now blocked.`;case m.isReportUnblockingSuccess:return`${this.authorName} is now unblocked.`;default:return"Reporting is currently unavailable. Try reloading the page or waiting a few minutes, before trying again."}},this.showErrorBanner=t=>{const e=t.detail?.bannerType;this.errorMessage=this.getMessageByType(e),e||this.dispatchCloseReportFlowEvent(),this.showError=!0},this.showBlockingSuccessBanner=t=>{const e=t.detail?.bannerType;this.successMessage=this.getMessageByType(e),this.showSuccess=!0},this.closeBanner=()=>{this.showError=!1,this.showSuccess=!1},this.gqlHelpers=new S,window.addEventListener("report-error",this.showErrorBanner),window.addEventListener("blocking-success",this.showBlockingSuccessBanner),this.addEventListener("report-form-rendered",this.initModal),this.addEventListener("faceplate-track",this.initCTLListeners),this.addEventListener("close-report-modal",this.onCloseModal),this.addEventListener("open-ctl-modal",this.initCTLModal)}static get styles(){return[u`:host>faceplate-banner{display:flex;flex-direction:column;gap:var(--spacer-md);align-items:center;position:fixed;left:50%;transform:translateX(-50%);padding:0 1rem;bottom:var(--rem16);width:calc(100% - 2rem)}`,r]}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener("report-error",this.showErrorBanner),window.removeEventListener("blocking-success",this.showBlockingSuccessBanner)}updated(t){super.updated(t),t.has("isOpen")&&this.isOpen&&this.initReportFlow()}render(){const t=this.isOpen?d`<faceplate-partial \n src="${this.partialSrc}${this.thingId}/${this.isDesktop?"is-desktop":"is-not-desktop"}/${this.authorName}/${this.authorId}/${this.isAuthorBlocked?"author-is-blocked":"author-is-not-blocked"}" \n></faceplate-partial>`:p;return d`\n <div>${t}</div>\n ${this.showError?d`<faceplate-banner \n class="z-[5] pointer-events-auto" \n appearance="error" \n shape="rounded" \n msg="${this.errorMessage}" \n aria-live="polite" \n dismissible\n><div slot="leadingIcon">${g()}</div>\n <span slot="closeButton">\n ${f.getCloseButton("error",{"aria-label":"close error button",onclick:this.closeBanner})}\n </span>\n </faceplate-banner>`:p}\n ${this.showSuccess?d`<faceplate-banner \n class="z-[5] pointer-events-auto" \n appearance="success" \n shape="rounded" \n msg="${this.successMessage}" \n aria-live="polite" \n dismissible\n><div slot="leadingIcon">${b()}</div>\n <span slot="closeButton">\n ${f.getCloseButton("success",{"aria-label":"button to close success banner",onclick:this.closeBanner})}\n </span>\n </faceplate-banner>`:p}\n `}};o([n({type:Boolean,attribute:"is-desktop"})],L.prototype,"isDesktop",void 0),o([n({type:String,attribute:"thing-id"})],L.prototype,"thingId",void 0),o([n({type:String,attribute:"author-name"})],L.prototype,"authorName",void 0),o([n({type:String,attribute:"author-id"})],L.prototype,"authorId",void 0),o([n({type:Boolean,attribute:"is-author-blocked"})],L.prototype,"isAuthorBlocked",void 0),o([n({type:Boolean,attribute:"is-open"})],L.prototype,"isOpen",void 0),o([a()],L.prototype,"showError",void 0),o([a()],L.prototype,"showSuccess",void 0),L=o([h("report-flow")],L);export{m as R,L as a};
                    //# sourceMappingURL=report-flow-d910001d.js.map
                    """;
        var node = parser.ParseModule(input);
        var prettyPrinted = node.ToJavaScriptString(true);
        node = parser.ParseModule(prettyPrinted);
    }
Esprima.ParserException
Line 235: Unexpected token ??
   at Esprima.JavaScriptParser.ThrowUnexpectedToken(Token& token, String message)
   at Esprima.JavaScriptParser.ParseBinaryExpression()
   at Esprima.JavaScriptParser.ParseAssignmentExpression()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseAssignmentExpression()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseExpression()
   at Esprima.JavaScriptParser.ParseExpressionStatement()
   at Esprima.JavaScriptParser.ParseStatement()
   at Esprima.JavaScriptParser.ParseStatementListItem()
   at Esprima.JavaScriptParser.ParseFunctionSourceElements()
   at Esprima.JavaScriptParser.ParseAssignmentExpression()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseArguments()
   at Esprima.JavaScriptParser.ParseCallExpression(Boolean maybeAsync, Marker& startToken, Expression callee, Boolean optional)
   at Esprima.JavaScriptParser.ParseLeftHandSideExpressionAllowCall()
   at Esprima.JavaScriptParser.ParseUpdateExpression()
   at Esprima.JavaScriptParser.ParseUnaryExpression()
   at Esprima.JavaScriptParser.ParseBinaryExpressionOperand()
   at Esprima.JavaScriptParser.ParseBinaryExpression()
   at Esprima.JavaScriptParser.ParseAssignmentExpression()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseAssignmentExpression()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseArguments()
   at Esprima.JavaScriptParser.ParseCallExpression(Boolean maybeAsync, Marker& startToken, Expression callee, Boolean optional)
   at Esprima.JavaScriptParser.ParseLeftHandSideExpressionAllowCall()
   at Esprima.JavaScriptParser.ParseUpdateExpression()
   at Esprima.JavaScriptParser.ParseUnaryExpression()
   at Esprima.JavaScriptParser.ParseBinaryExpressionOperand()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseBinaryExpression()
   at Esprima.JavaScriptParser.ParseAssignmentExpression()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseExpression()
   at Esprima.JavaScriptParser.ParseLabelledStatement()
   at Esprima.JavaScriptParser.ParseStatement()
   at Esprima.JavaScriptParser.ParseStatementListItem()
   at Esprima.JavaScriptParser.ParseBlock()
   at Esprima.JavaScriptParser.ParseStatement()
   at Esprima.JavaScriptParser.ParseIfClause()
   at Esprima.JavaScriptParser.ParseIfStatement()
   at Esprima.JavaScriptParser.ParseStatement()
   at Esprima.JavaScriptParser.ParseStatementListItem()
   at Esprima.JavaScriptParser.ParseFunctionSourceElements()
   at Esprima.JavaScriptParser.ParseAssignmentExpression()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseAssignmentExpression()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseExpression()
   at Esprima.JavaScriptParser.ParseExpressionStatement()
   at Esprima.JavaScriptParser.ParseStatement()
   at Esprima.JavaScriptParser.ParseStatementListItem()
   at Esprima.JavaScriptParser.ParseFunctionSourceElements()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParsePropertyMethod(ParsedParameters& parameters, Boolean& hasStrictDirective)
   at Esprima.JavaScriptParser.ParsePropertyMethodFunction(Boolean isAsync, Boolean isGenerator, Boolean allowSuperCall)
   at Esprima.JavaScriptParser.ParseClassElement(Boolean hasSuperClass, Boolean& hasConstructor)
   at Esprima.JavaScriptParser.ParseClassElementList(Boolean hasSuperClass)
   at Esprima.JavaScriptParser.ParseClassBody(Boolean hasSuperClass)
   at Esprima.JavaScriptParser.ParseClassExpression()
   at Esprima.JavaScriptParser.ParsePrimaryExpression()
   at Esprima.JavaScriptParser.ParseLeftHandSideExpressionAllowCall()
   at Esprima.JavaScriptParser.ParseUpdateExpression()
   at Esprima.JavaScriptParser.ParseUnaryExpression()
   at Esprima.JavaScriptParser.ParseBinaryExpressionOperand()
   at Esprima.JavaScriptParser.ParseBinaryExpression()
   at Esprima.JavaScriptParser.ParseAssignmentExpression()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseLexicalBinding(VariableDeclarationKind kind, Boolean inFor)
   at Esprima.JavaScriptParser.ParseBindingList(VariableDeclarationKind kind, Boolean inFor)
   at Esprima.JavaScriptParser.ParseLexicalDeclaration()
   at Esprima.JavaScriptParser.ParseStatementListItem()
   at Esprima.JavaScriptParser.ParseModule(String code, String source)

@lahma
Copy link
Collaborator

lahma commented Oct 11, 2023

OK so the minimal repro is:

[Fact]
public void LooseOptionalChaining()
{
    var parser = new JavaScriptParser();
    parser.ParseScript("this.config.disabled && this.helpers?.getDisabledCondition(this.config.disabled) ?? this.isDisabled");
}

This would also fail with acorn when using non-loose parsing, error: Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses (1:81)

This would work in format where parenthesis are added:

this.config.disabled && (this.helpers?.getDisabledCondition(this.config.disabled) ?? this.isDisabled)

@adams85
Copy link
Collaborator

adams85 commented Oct 12, 2023

AFAICS, the AST to JS conversion is what doesn't handle mixing ?? and && correctly. This is addressed by #413

Just to make this clear, we have no other (incl. parser) issues here, right?

@adams85 adams85 added the bug label Oct 12, 2023
@adams85 adams85 linked a pull request Oct 12, 2023 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants